@buenos-nachos/time-sync 0.1.1 → 0.1.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/CHANGELOG.md +6 -0
- package/README.md +3 -0
- package/package.json +6 -1
- package/dist/index.d.mts +0 -275
- package/dist/index.d.mts.map +0 -1
- package/dist/index.d.ts +0 -275
- package/dist/index.d.ts.map +0 -1
- package/dist/index.js +0 -409
- package/dist/index.js.map +0 -1
- package/dist/index.mjs +0 -406
- package/dist/index.mjs.map +0 -1
package/dist/index.js
DELETED
|
@@ -1,409 +0,0 @@
|
|
|
1
|
-
|
|
2
|
-
//#region src/ReadonlyDate.ts
|
|
3
|
-
/**
|
|
4
|
-
* A readonly version of a Date object. To maximize compatibility with existing
|
|
5
|
-
* libraries, all methods are the same as the native Date object at the type
|
|
6
|
-
* level. But crucially, all methods prefixed with `set` have all mutation logic
|
|
7
|
-
* removed.
|
|
8
|
-
*
|
|
9
|
-
* If you need a mutable version of the underlying date, ReadonlyDate exposes a
|
|
10
|
-
* .toNativeDate method to do a runtime conversion to a native/mutable date.
|
|
11
|
-
*/
|
|
12
|
-
var ReadonlyDate = class extends Date {
|
|
13
|
-
constructor(initValue, monthIndex, day, hours, minutes, seconds, milliseconds) {
|
|
14
|
-
if (initValue instanceof Date && initValue.toString() === "Invalid Date") throw new RangeError("Cannot instantiate ReadonlyDate via invalid date object");
|
|
15
|
-
if ([...arguments].some((el) => {
|
|
16
|
-
/**
|
|
17
|
-
* You almost never see them in practice, but native dates do
|
|
18
|
-
* support using negative AND fractional values for instantiation.
|
|
19
|
-
* Negative values produce values before 1970.
|
|
20
|
-
*/
|
|
21
|
-
return typeof el === "number" && !Number.isFinite(el);
|
|
22
|
-
})) throw new RangeError("Cannot instantiate ReadonlyDate via invalid number(s)");
|
|
23
|
-
/**
|
|
24
|
-
* This guard clause looks incredibly silly, but we need to do this to
|
|
25
|
-
* make sure that the readonly class works properly with Jest, Vitest,
|
|
26
|
-
* and anything else that supports fake timers. Critically, it makes
|
|
27
|
-
* this possible without introducing any extra runtime dependencies.
|
|
28
|
-
*
|
|
29
|
-
* Basically:
|
|
30
|
-
* 1. We need to make sure that ReadonlyDate extends the Date prototype,
|
|
31
|
-
* so that instanceof checks work correctly, and so that the class
|
|
32
|
-
* can interop with all libraries that rely on vanilla Dates
|
|
33
|
-
* 2. In ECMAScript, this linking happens right as the module is
|
|
34
|
-
* imported
|
|
35
|
-
* 3. Jest and Vitest will do some degree of hoisting before the
|
|
36
|
-
* imports get evaluated, but most of the mock functionality happens
|
|
37
|
-
* at runtime. useFakeTimers is NOT hoisted
|
|
38
|
-
* 4. A Vitest test file might import the readonly class at some point
|
|
39
|
-
* (directly or indirectly), which establishes the link
|
|
40
|
-
* 5. useFakeTimers can then be called after imports, and that updates
|
|
41
|
-
* the global scope so that when any FUTURE code references the
|
|
42
|
-
* global Date object, the fake version is used instead
|
|
43
|
-
* 6. But because the linking already happened before the call,
|
|
44
|
-
* ReadonlyDate will still be bound to the original Date object
|
|
45
|
-
* 7. When super is called (which is required when extending classes),
|
|
46
|
-
* the original date object will be instantiated and then linked to
|
|
47
|
-
* the readonly instance via the prototype chain
|
|
48
|
-
* 8. None of this is a problem when you're instantiating the class by
|
|
49
|
-
* passing it actual inputs, because then the date result will always
|
|
50
|
-
* be deterministic. The problem happens when you make the date with
|
|
51
|
-
* no arguments, because that causes a new date to be created with
|
|
52
|
-
* the true system time, instead of the fake system time.
|
|
53
|
-
* 9. So, to bridge the gap, we make a separate Date with `new Date()`
|
|
54
|
-
* (after it's been turned into the fake version), and then use it to
|
|
55
|
-
* overwrite the contents of the real date created with super
|
|
56
|
-
*/
|
|
57
|
-
if (initValue === void 0) {
|
|
58
|
-
super();
|
|
59
|
-
const constructorOverrideForTestCorrectness = /* @__PURE__ */ new Date();
|
|
60
|
-
super.setTime(constructorOverrideForTestCorrectness.getTime());
|
|
61
|
-
return;
|
|
62
|
-
}
|
|
63
|
-
if (typeof initValue === "string") {
|
|
64
|
-
super(initValue);
|
|
65
|
-
if (super.toString() === "Invalid Date") throw new RangeError("Cannot instantiate ReadonlyDate via invalid string");
|
|
66
|
-
return;
|
|
67
|
-
}
|
|
68
|
-
if (monthIndex === void 0) {
|
|
69
|
-
super(initValue);
|
|
70
|
-
return;
|
|
71
|
-
}
|
|
72
|
-
if (typeof initValue !== "number") throw new TypeError(`Impossible case encountered: init value has type of '${typeof initValue}, but additional arguments were provided after the first`);
|
|
73
|
-
/**
|
|
74
|
-
* biome-ignore lint:complexity/noArguments -- Native dates are super
|
|
75
|
-
* wonky, and they actually check arguments.length to define behavior
|
|
76
|
-
* at runtime. We can't pass all the arguments in via a single call,
|
|
77
|
-
* because then the constructor will create an invalid date the moment
|
|
78
|
-
* it finds any single undefined value.
|
|
79
|
-
*/
|
|
80
|
-
const argCount = arguments.length;
|
|
81
|
-
switch (argCount) {
|
|
82
|
-
case 2:
|
|
83
|
-
super(initValue, monthIndex);
|
|
84
|
-
return;
|
|
85
|
-
case 3:
|
|
86
|
-
super(initValue, monthIndex, day);
|
|
87
|
-
return;
|
|
88
|
-
case 4:
|
|
89
|
-
super(initValue, monthIndex, day, hours);
|
|
90
|
-
return;
|
|
91
|
-
case 5:
|
|
92
|
-
super(initValue, monthIndex, day, hours, minutes);
|
|
93
|
-
return;
|
|
94
|
-
case 6:
|
|
95
|
-
super(initValue, monthIndex, day, hours, minutes, seconds);
|
|
96
|
-
return;
|
|
97
|
-
case 7:
|
|
98
|
-
super(initValue, monthIndex, day, hours, minutes, seconds, milliseconds);
|
|
99
|
-
return;
|
|
100
|
-
default: throw new Error(`Cannot instantiate new Date with ${argCount} arguments`);
|
|
101
|
-
}
|
|
102
|
-
}
|
|
103
|
-
toNativeDate() {
|
|
104
|
-
const time = super.getTime();
|
|
105
|
-
return new Date(time);
|
|
106
|
-
}
|
|
107
|
-
setDate(_date) {
|
|
108
|
-
return super.getTime();
|
|
109
|
-
}
|
|
110
|
-
setFullYear(_year, _month, _date) {
|
|
111
|
-
return super.getTime();
|
|
112
|
-
}
|
|
113
|
-
setHours(_hours, _min, _sec, _ms) {
|
|
114
|
-
return super.getTime();
|
|
115
|
-
}
|
|
116
|
-
setMilliseconds(_ms) {
|
|
117
|
-
return super.getTime();
|
|
118
|
-
}
|
|
119
|
-
setMinutes(_min, _sec, _ms) {
|
|
120
|
-
return super.getTime();
|
|
121
|
-
}
|
|
122
|
-
setMonth(_month, _date) {
|
|
123
|
-
return super.getTime();
|
|
124
|
-
}
|
|
125
|
-
setSeconds(_sec, _ms) {
|
|
126
|
-
return super.getTime();
|
|
127
|
-
}
|
|
128
|
-
setTime(_time) {
|
|
129
|
-
return super.getTime();
|
|
130
|
-
}
|
|
131
|
-
setUTCDate(_date) {
|
|
132
|
-
return super.getTime();
|
|
133
|
-
}
|
|
134
|
-
setUTCFullYear(_year, _month, _date) {
|
|
135
|
-
return super.getTime();
|
|
136
|
-
}
|
|
137
|
-
setUTCHours(_hours, _min, _sec, _ms) {
|
|
138
|
-
return super.getTime();
|
|
139
|
-
}
|
|
140
|
-
setUTCMilliseconds(_ms) {
|
|
141
|
-
return super.getTime();
|
|
142
|
-
}
|
|
143
|
-
setUTCMinutes(_min, _sec, _ms) {
|
|
144
|
-
return super.getTime();
|
|
145
|
-
}
|
|
146
|
-
setUTCMonth(_month, _date) {
|
|
147
|
-
return super.getTime();
|
|
148
|
-
}
|
|
149
|
-
setUTCSeconds(_sec, _ms) {
|
|
150
|
-
return super.getTime();
|
|
151
|
-
}
|
|
152
|
-
};
|
|
153
|
-
|
|
154
|
-
//#endregion
|
|
155
|
-
//#region src/TimeSync.ts
|
|
156
|
-
/**
|
|
157
|
-
* A collection of commonly-needed intervals (all defined in milliseconds).
|
|
158
|
-
*/
|
|
159
|
-
const refreshRates = Object.freeze({
|
|
160
|
-
idle: Number.POSITIVE_INFINITY,
|
|
161
|
-
halfSecond: 500,
|
|
162
|
-
oneSecond: 1e3,
|
|
163
|
-
thirtySeconds: 3e4,
|
|
164
|
-
oneMinute: 60 * 1e3,
|
|
165
|
-
fiveMinutes: 300 * 1e3,
|
|
166
|
-
oneHour: 3600 * 1e3
|
|
167
|
-
});
|
|
168
|
-
function noOp(..._) {}
|
|
169
|
-
const defaultMinimumRefreshIntervalMs = 200;
|
|
170
|
-
/**
|
|
171
|
-
* One thing that was considered was giving TimeSync the ability to flip which
|
|
172
|
-
* kinds of dates it uses, and let it use native dates instead of readonly
|
|
173
|
-
* dates. We type readonly dates as native dates for better interoperability
|
|
174
|
-
* with pretty much every JavaScript library under the sun, but there is still a
|
|
175
|
-
* big difference in runtime behavior. There is a risk that blocking mutations
|
|
176
|
-
* could break some other library in other ways.
|
|
177
|
-
*
|
|
178
|
-
* That might be worth revisiting if we get user feedback, but right now, it
|
|
179
|
-
* seems like an incredibly bad idea.
|
|
180
|
-
*
|
|
181
|
-
* 1. Any single mutation has a risk of breaking the entire integrity of the
|
|
182
|
-
* system. If a consumer would try to mutate them, things SHOULD blow up by
|
|
183
|
-
* default.
|
|
184
|
-
* 2. Dates are a type of object that are far more read-heavy than write-heavy,
|
|
185
|
-
* so the risks of breaking are generally lower
|
|
186
|
-
* 3. If a user really needs a mutable version of the date, they can make a
|
|
187
|
-
* mutable copy first via `const mutable = readonlyDate.toNativeDate()`
|
|
188
|
-
*
|
|
189
|
-
* The one case when turning off the readonly behavior would be good would be
|
|
190
|
-
* if you're on a server that really needs to watch its garbage collection
|
|
191
|
-
* output, and you the overhead from the readonly date is causing too much
|
|
192
|
-
* pressure on resources. In that case, you could switch to native dates, but
|
|
193
|
-
* you'd still need a LOT of trigger discipline to avoid mutations, especially
|
|
194
|
-
* if you rely on outside libraries.
|
|
195
|
-
*/
|
|
196
|
-
/**
|
|
197
|
-
* TimeSync provides a centralized authority for working with time values in a
|
|
198
|
-
* more structured way. It ensures all dependents for the time values stay in
|
|
199
|
-
* sync with each other.
|
|
200
|
-
*
|
|
201
|
-
* (e.g., In a React codebase, you want multiple components that rely on time
|
|
202
|
-
* values to update together, to avoid screen tearing and stale data for only
|
|
203
|
-
* some parts of the screen.)
|
|
204
|
-
*/
|
|
205
|
-
var TimeSync = class {
|
|
206
|
-
/**
|
|
207
|
-
* Stores all refresh intervals actively associated with an onUpdate
|
|
208
|
-
* callback (along with their associated unsubscribe callbacks).
|
|
209
|
-
*
|
|
210
|
-
* Supports storing the exact same callback-interval pairs multiple times,
|
|
211
|
-
* in case multiple external systems need to subscribe with the exact same
|
|
212
|
-
* data concerns. Because the functions themselves are used as keys, that
|
|
213
|
-
* ensures that each callback will only be called once per update, no matter
|
|
214
|
-
* how subscribers use it.
|
|
215
|
-
*
|
|
216
|
-
* Each map value should stay sorted by refresh interval, in ascending
|
|
217
|
-
* order.
|
|
218
|
-
*/
|
|
219
|
-
#subscriptions;
|
|
220
|
-
/**
|
|
221
|
-
* The latest public snapshot of TimeSync's internal state. The snapshot
|
|
222
|
-
* should always be treated as an immutable value.
|
|
223
|
-
*/
|
|
224
|
-
#latestSnapshot;
|
|
225
|
-
/**
|
|
226
|
-
* A cached version of the fastest interval currently registered with
|
|
227
|
-
* TimeSync. Should always be derived from #subscriptions
|
|
228
|
-
*/
|
|
229
|
-
#fastestRefreshInterval;
|
|
230
|
-
/**
|
|
231
|
-
* Used for both its intended purpose (creating interval), but also as a
|
|
232
|
-
* janky version of setTimeout.
|
|
233
|
-
*
|
|
234
|
-
* There are a few times when we need timeout-like logic, but if we use
|
|
235
|
-
* setInterval for everything, we have fewer IDs to juggle, and less risk of
|
|
236
|
-
* things getting out of sync.
|
|
237
|
-
*
|
|
238
|
-
* Type defined like this to support client and server behavior. Node.js
|
|
239
|
-
* uses its own custom timeout type, but Deno, Bun, and the browser all use
|
|
240
|
-
* the number type.
|
|
241
|
-
*/
|
|
242
|
-
#intervalId;
|
|
243
|
-
constructor(options) {
|
|
244
|
-
const { initialDate, freezeUpdates = false, allowDuplicateOnUpdateCalls = false, minimumRefreshIntervalMs = defaultMinimumRefreshIntervalMs } = options ?? {};
|
|
245
|
-
if (!(Number.isInteger(minimumRefreshIntervalMs) && minimumRefreshIntervalMs > 0)) throw new RangeError(`Minimum refresh interval must be a positive integer (received ${minimumRefreshIntervalMs} ms)`);
|
|
246
|
-
this.#subscriptions = /* @__PURE__ */ new Map();
|
|
247
|
-
this.#fastestRefreshInterval = Number.POSITIVE_INFINITY;
|
|
248
|
-
this.#intervalId = void 0;
|
|
249
|
-
const initialSnapshot = {
|
|
250
|
-
subscriberCount: 0,
|
|
251
|
-
date: initialDate ? new ReadonlyDate(initialDate) : new ReadonlyDate(),
|
|
252
|
-
config: Object.freeze({
|
|
253
|
-
freezeUpdates,
|
|
254
|
-
minimumRefreshIntervalMs,
|
|
255
|
-
allowDuplicateOnUpdateCalls
|
|
256
|
-
})
|
|
257
|
-
};
|
|
258
|
-
this.#latestSnapshot = Object.freeze(initialSnapshot);
|
|
259
|
-
}
|
|
260
|
-
#setSnapshot(update) {
|
|
261
|
-
const { date, subscriberCount, config } = this.#latestSnapshot;
|
|
262
|
-
if (config.freezeUpdates) return false;
|
|
263
|
-
const updated = {
|
|
264
|
-
config,
|
|
265
|
-
date: update.date ?? date,
|
|
266
|
-
subscriberCount: update.subscriberCount ?? subscriberCount
|
|
267
|
-
};
|
|
268
|
-
this.#latestSnapshot = Object.freeze(updated);
|
|
269
|
-
return true;
|
|
270
|
-
}
|
|
271
|
-
#notifyAllSubscriptions() {
|
|
272
|
-
const { date, config } = this.#latestSnapshot;
|
|
273
|
-
if (config.freezeUpdates || this.#subscriptions.size === 0) return;
|
|
274
|
-
/**
|
|
275
|
-
* Two things for both paths:
|
|
276
|
-
* 1. We need to make sure that we do one-time serializations of the map
|
|
277
|
-
* entries into an array instead of constantly pulling from the map via
|
|
278
|
-
* the iterator protocol in the off chance that subscriptions add new
|
|
279
|
-
* subscriptions. We need to make infinite loops impossible. If new
|
|
280
|
-
* subscriptions get added, they'll just have to wait until the next
|
|
281
|
-
* update round.
|
|
282
|
-
*
|
|
283
|
-
* 2. The trade off of the serialization is that we do lose the ability
|
|
284
|
-
* to auto-break the loops if one of the subscribers ends up resetting
|
|
285
|
-
* all state, because we'll still have local copies of entries. We need
|
|
286
|
-
* to check on each iteration to see if we should continue.
|
|
287
|
-
*/
|
|
288
|
-
if (config.allowDuplicateOnUpdateCalls) {
|
|
289
|
-
const entries = Array.from(this.#subscriptions, ([onUpdate, subs]) => [onUpdate, subs.length]);
|
|
290
|
-
outer: for (const [onUpdate, subCount] of entries) for (let i = 0; i < subCount; i++) {
|
|
291
|
-
if (this.#subscriptions.size === 0) break outer;
|
|
292
|
-
onUpdate(date);
|
|
293
|
-
}
|
|
294
|
-
return;
|
|
295
|
-
}
|
|
296
|
-
const funcs = [...this.#subscriptions.keys()];
|
|
297
|
-
for (const onUpdate of funcs) {
|
|
298
|
-
if (this.#subscriptions.size === 0) break;
|
|
299
|
-
onUpdate(date);
|
|
300
|
-
}
|
|
301
|
-
}
|
|
302
|
-
/**
|
|
303
|
-
* The logic that should happen at each step in TimeSync's active interval.
|
|
304
|
-
*
|
|
305
|
-
* Defined as an arrow function so that we can just pass it directly to
|
|
306
|
-
* setInterval without needing to make a new wrapper function each time. We
|
|
307
|
-
* don't have many situations where we can lose the `this` context, but this
|
|
308
|
-
* is one of them.
|
|
309
|
-
*/
|
|
310
|
-
#onTick = () => {
|
|
311
|
-
const { config } = this.#latestSnapshot;
|
|
312
|
-
if (config.freezeUpdates) {
|
|
313
|
-
clearInterval(this.#intervalId);
|
|
314
|
-
this.#intervalId = void 0;
|
|
315
|
-
return;
|
|
316
|
-
}
|
|
317
|
-
if (this.#setSnapshot({ date: new ReadonlyDate() })) this.#notifyAllSubscriptions();
|
|
318
|
-
};
|
|
319
|
-
#onFastestIntervalChange() {
|
|
320
|
-
const fastest = this.#fastestRefreshInterval;
|
|
321
|
-
const { date, config } = this.#latestSnapshot;
|
|
322
|
-
if (config.freezeUpdates || fastest === Number.POSITIVE_INFINITY) {
|
|
323
|
-
clearInterval(this.#intervalId);
|
|
324
|
-
this.#intervalId = void 0;
|
|
325
|
-
return;
|
|
326
|
-
}
|
|
327
|
-
const timeBeforeNextUpdate = fastest - (new ReadonlyDate().getTime() - date.getTime());
|
|
328
|
-
clearInterval(this.#intervalId);
|
|
329
|
-
if (timeBeforeNextUpdate <= 0) {
|
|
330
|
-
if (this.#setSnapshot({ date: new ReadonlyDate() })) this.#notifyAllSubscriptions();
|
|
331
|
-
this.#intervalId = setInterval(this.#onTick, fastest);
|
|
332
|
-
return;
|
|
333
|
-
}
|
|
334
|
-
if (timeBeforeNextUpdate === fastest) {
|
|
335
|
-
this.#intervalId = setInterval(this.#onTick, timeBeforeNextUpdate);
|
|
336
|
-
return;
|
|
337
|
-
}
|
|
338
|
-
this.#intervalId = setInterval(() => {
|
|
339
|
-
clearInterval(this.#intervalId);
|
|
340
|
-
this.#intervalId = setInterval(this.#onTick, fastest);
|
|
341
|
-
this.#onTick();
|
|
342
|
-
}, timeBeforeNextUpdate);
|
|
343
|
-
}
|
|
344
|
-
#updateFastestInterval() {
|
|
345
|
-
const { config } = this.#latestSnapshot;
|
|
346
|
-
if (config.freezeUpdates) {
|
|
347
|
-
this.#fastestRefreshInterval = Number.POSITIVE_INFINITY;
|
|
348
|
-
return;
|
|
349
|
-
}
|
|
350
|
-
const prevFastest = this.#fastestRefreshInterval;
|
|
351
|
-
let newFastest = Number.POSITIVE_INFINITY;
|
|
352
|
-
for (const entries of this.#subscriptions.values()) {
|
|
353
|
-
const subFastest = entries[0]?.targetInterval ?? Number.POSITIVE_INFINITY;
|
|
354
|
-
if (subFastest < newFastest) newFastest = subFastest;
|
|
355
|
-
}
|
|
356
|
-
this.#fastestRefreshInterval = newFastest;
|
|
357
|
-
if (prevFastest !== newFastest) this.#onFastestIntervalChange();
|
|
358
|
-
}
|
|
359
|
-
subscribe(sh) {
|
|
360
|
-
const { config } = this.#latestSnapshot;
|
|
361
|
-
if (config.freezeUpdates) return noOp;
|
|
362
|
-
const { targetRefreshIntervalMs, onUpdate } = sh;
|
|
363
|
-
if (!(targetRefreshIntervalMs === Number.POSITIVE_INFINITY || Number.isInteger(targetRefreshIntervalMs) && targetRefreshIntervalMs > 0)) throw new Error(`Target refresh interval must be positive infinity or a positive integer (received ${targetRefreshIntervalMs} ms)`);
|
|
364
|
-
let unsubscribed = false;
|
|
365
|
-
const unsubscribe = () => {
|
|
366
|
-
if (unsubscribed) return;
|
|
367
|
-
const entries$1 = this.#subscriptions.get(onUpdate);
|
|
368
|
-
if (entries$1 === void 0) return;
|
|
369
|
-
const matchIndex = entries$1.findIndex((e) => e.unsubscribe === unsubscribe);
|
|
370
|
-
if (matchIndex === -1) return;
|
|
371
|
-
entries$1.splice(matchIndex, 1);
|
|
372
|
-
if (entries$1.length === 0) this.#subscriptions.delete(onUpdate);
|
|
373
|
-
this.#updateFastestInterval();
|
|
374
|
-
this.#setSnapshot({ subscriberCount: Math.max(0, this.#latestSnapshot.subscriberCount - 1) });
|
|
375
|
-
unsubscribed = true;
|
|
376
|
-
};
|
|
377
|
-
let entries = this.#subscriptions.get(onUpdate);
|
|
378
|
-
if (entries === void 0) {
|
|
379
|
-
entries = [];
|
|
380
|
-
this.#subscriptions.set(onUpdate, entries);
|
|
381
|
-
}
|
|
382
|
-
const targetInterval = Math.max(config.minimumRefreshIntervalMs, targetRefreshIntervalMs);
|
|
383
|
-
entries.push({
|
|
384
|
-
unsubscribe,
|
|
385
|
-
targetInterval
|
|
386
|
-
});
|
|
387
|
-
entries.sort((e1, e2) => e1.targetInterval - e2.targetInterval);
|
|
388
|
-
this.#setSnapshot({ subscriberCount: this.#latestSnapshot.subscriberCount + 1 });
|
|
389
|
-
this.#updateFastestInterval();
|
|
390
|
-
return unsubscribe;
|
|
391
|
-
}
|
|
392
|
-
getStateSnapshot() {
|
|
393
|
-
return this.#latestSnapshot;
|
|
394
|
-
}
|
|
395
|
-
clearAll() {
|
|
396
|
-
clearInterval(this.#intervalId);
|
|
397
|
-
this.#intervalId = void 0;
|
|
398
|
-
this.#fastestRefreshInterval = 0;
|
|
399
|
-
for (const entries of this.#subscriptions.values()) for (const e of entries) e.unsubscribe();
|
|
400
|
-
this.#subscriptions.clear();
|
|
401
|
-
this.#setSnapshot({ subscriberCount: 0 });
|
|
402
|
-
}
|
|
403
|
-
};
|
|
404
|
-
|
|
405
|
-
//#endregion
|
|
406
|
-
exports.ReadonlyDate = ReadonlyDate;
|
|
407
|
-
exports.TimeSync = TimeSync;
|
|
408
|
-
exports.refreshRates = refreshRates;
|
|
409
|
-
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["#subscriptions","#fastestRefreshInterval","#intervalId","initialSnapshot: Snapshot","#latestSnapshot","updated: Snapshot","#onTick","#setSnapshot","#notifyAllSubscriptions","#onFastestIntervalChange","entries","#updateFastestInterval"],"sources":["../src/ReadonlyDate.ts","../src/TimeSync.ts"],"sourcesContent":["/**\n * @file This comment is here to provide clarity on why proxy objects might\n * always be a dead end for this library, and document failed experiments.\n *\n * Readonly dates need to have a lot of interoperability with native dates\n * (pretty much every JavaScript library uses the built-in type). So, this code\n * originally defined them as a Proxy wrapper over native dates. The handler\n * intercepted all methods prefixed with `set` and turned them into no-ops.\n *\n * That got really close to working, but then development ran into a critical\n * limitation of the Proxy API. Basically, if the readonly date is defined with\n * a proxy, and you try to call Date.prototype.toISOString.call(readonlyDate),\n * that immediately blows up because the proxy itself is treated as the receiver\n * instead of the underlying native date.\n *\n * Vitest uses .call because it's the more airtight thing to do in most\n * situations, but proxy objects only have traps for .apply calls, not .call. So\n * there is no way in the language to intercept these calls and make sure\n * they're going to the right place. It is a hard, HARD limitation.\n *\n * The good news, though, is that having an extended class seems like the better\n * option, because it gives us the ability to define custom convenience methods\n * without breaking instanceof checks or breaking TypeScript assignability for\n * libraries that expect native dates. We just have to do a little bit of extra\n * work to fudge things for test runners.\n */\n\n/**\n * Any extra methods for readonly dates.\n */\ninterface ReadonlyDateApi {\n\t/**\n\t * Converts a readonly date into a native (mutable) date.\n\t */\n\ttoNativeDate(): Date;\n}\n\n/**\n * A readonly version of a Date object. To maximize compatibility with existing\n * libraries, all methods are the same as the native Date object at the type\n * level. But crucially, all methods prefixed with `set` have all mutation logic\n * removed.\n *\n * If you need a mutable version of the underlying date, ReadonlyDate exposes a\n * .toNativeDate method to do a runtime conversion to a native/mutable date.\n */\nexport class ReadonlyDate extends Date implements ReadonlyDateApi {\n\t// Native dates support such a wide range of arguments (from 0 to 7), so\n\t// conditional types would be incredibly awkward here. Just using\n\t// constructor overloads instead\n\tconstructor();\n\tconstructor(initValue: number | string | Date);\n\tconstructor(year: number, monthIndex: number);\n\tconstructor(year: number, monthIndex: number, day: number);\n\tconstructor(year: number, monthIndex: number, day: number, hours: number);\n\tconstructor(\n\t\tyear: number,\n\t\tmonthIndex: number,\n\t\tday: number,\n\t\thours: number,\n\t\tseconds: number,\n\t);\n\tconstructor(\n\t\tyear: number,\n\t\tmonthIndex: number,\n\t\tday: number,\n\t\thours: number,\n\t\tseconds: number,\n\t\tmilliseconds: number,\n\t);\n\tconstructor(\n\t\tinitValue?: number | string | Date,\n\t\tmonthIndex?: number,\n\t\tday?: number,\n\t\thours?: number,\n\t\tminutes?: number,\n\t\tseconds?: number,\n\t\tmilliseconds?: number,\n\t) {\n\t\t/**\n\t\t * One problem with the native Date type is that they allow you to\n\t\t * produce invalid dates silently, and you won't find out until it's too\n\t\t * late. It's a lot like NaN for numbers.\n\t\t *\n\t\t * Taking some extra steps to make sure that they can't ever creep into\n\t\t * the library and break all the state modeling.\n\t\t *\n\t\t * Strings are still a problem, but that gets taken care of later in the\n\t\t * constructor.\n\t\t */\n\t\tconst hasInvalidSourceDate =\n\t\t\tinitValue instanceof Date && initValue.toString() === \"Invalid Date\";\n\t\tif (hasInvalidSourceDate) {\n\t\t\tthrow new RangeError(\n\t\t\t\t\"Cannot instantiate ReadonlyDate via invalid date object\",\n\t\t\t);\n\t\t}\n\n\t\t/**\n\t\t * biome-ignore lint:complexity/noArguments -- We're going to be using\n\t\t * `arguments` a good bit because the native Date relies on the meta\n\t\t * parameter so much for runtime behavior\n\t\t */\n\t\tconst hasInvalidNums = [...arguments].some((el) => {\n\t\t\t/**\n\t\t\t * You almost never see them in practice, but native dates do\n\t\t\t * support using negative AND fractional values for instantiation.\n\t\t\t * Negative values produce values before 1970.\n\t\t\t */\n\t\t\treturn typeof el === \"number\" && !Number.isFinite(el);\n\t\t});\n\t\tif (hasInvalidNums) {\n\t\t\tthrow new RangeError(\n\t\t\t\t\"Cannot instantiate ReadonlyDate via invalid number(s)\",\n\t\t\t);\n\t\t}\n\n\t\t/**\n\t\t * This guard clause looks incredibly silly, but we need to do this to\n\t\t * make sure that the readonly class works properly with Jest, Vitest,\n\t\t * and anything else that supports fake timers. Critically, it makes\n\t\t * this possible without introducing any extra runtime dependencies.\n\t\t *\n\t\t * Basically:\n\t\t * 1. We need to make sure that ReadonlyDate extends the Date prototype,\n\t\t * so that instanceof checks work correctly, and so that the class\n\t\t * can interop with all libraries that rely on vanilla Dates\n\t\t * 2. In ECMAScript, this linking happens right as the module is\n\t\t * imported\n\t\t * 3. Jest and Vitest will do some degree of hoisting before the\n\t\t * imports get evaluated, but most of the mock functionality happens\n\t\t * at runtime. useFakeTimers is NOT hoisted\n\t\t * 4. A Vitest test file might import the readonly class at some point\n\t\t * (directly or indirectly), which establishes the link\n\t\t * 5. useFakeTimers can then be called after imports, and that updates\n\t\t * the global scope so that when any FUTURE code references the\n\t\t * global Date object, the fake version is used instead\n\t\t * 6. But because the linking already happened before the call,\n\t\t * ReadonlyDate will still be bound to the original Date object\n\t\t * 7. When super is called (which is required when extending classes),\n\t\t * the original date object will be instantiated and then linked to\n\t\t * the readonly instance via the prototype chain\n\t\t * 8. None of this is a problem when you're instantiating the class by\n\t\t * passing it actual inputs, because then the date result will always\n\t\t * be deterministic. The problem happens when you make the date with\n\t\t * no arguments, because that causes a new date to be created with\n\t\t * the true system time, instead of the fake system time.\n\t\t * 9. So, to bridge the gap, we make a separate Date with `new Date()`\n\t\t * (after it's been turned into the fake version), and then use it to\n\t\t * overwrite the contents of the real date created with super\n\t\t */\n\t\tif (initValue === undefined) {\n\t\t\tsuper();\n\t\t\tconst constructorOverrideForTestCorrectness = new Date();\n\t\t\tsuper.setTime(constructorOverrideForTestCorrectness.getTime());\n\t\t\treturn;\n\t\t}\n\n\t\tif (typeof initValue === \"string\") {\n\t\t\tsuper(initValue);\n\t\t\tif (super.toString() === \"Invalid Date\") {\n\t\t\t\tthrow new RangeError(\n\t\t\t\t\t\"Cannot instantiate ReadonlyDate via invalid string\",\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\n\t\tif (monthIndex === undefined) {\n\t\t\tsuper(initValue);\n\t\t\treturn;\n\t\t}\n\t\tif (typeof initValue !== \"number\") {\n\t\t\tthrow new TypeError(\n\t\t\t\t`Impossible case encountered: init value has type of '${typeof initValue}, but additional arguments were provided after the first`,\n\t\t\t);\n\t\t}\n\n\t\t/**\n\t\t * biome-ignore lint:complexity/noArguments -- Native dates are super\n\t\t * wonky, and they actually check arguments.length to define behavior\n\t\t * at runtime. We can't pass all the arguments in via a single call,\n\t\t * because then the constructor will create an invalid date the moment\n\t\t * it finds any single undefined value.\n\t\t */\n\t\tconst argCount = arguments.length;\n\t\tswitch (argCount) {\n\t\t\tcase 2: {\n\t\t\t\tsuper(initValue, monthIndex);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tcase 3: {\n\t\t\t\tsuper(initValue, monthIndex, day);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tcase 4: {\n\t\t\t\tsuper(initValue, monthIndex, day, hours);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tcase 5: {\n\t\t\t\tsuper(initValue, monthIndex, day, hours, minutes);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tcase 6: {\n\t\t\t\tsuper(initValue, monthIndex, day, hours, minutes, seconds);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tcase 7: {\n\t\t\t\tsuper(\n\t\t\t\t\tinitValue,\n\t\t\t\t\tmonthIndex,\n\t\t\t\t\tday,\n\t\t\t\t\thours,\n\t\t\t\t\tminutes,\n\t\t\t\t\tseconds,\n\t\t\t\t\tmilliseconds,\n\t\t\t\t);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tdefault: {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Cannot instantiate new Date with ${argCount} arguments`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t}\n\n\ttoNativeDate(): Date {\n\t\tconst time = super.getTime();\n\t\treturn new Date(time);\n\t}\n\n\t////////////////////////////////////////////////////////////////////////////\n\t// Start of custom set methods to shadow the ones from native dates. Note\n\t// that all set methods expect that the underlying timestamp be returned\n\t// afterwards, which always corresponds to Date.getTime.\n\t////////////////////////////////////////////////////////////////////////////\n\n\toverride setDate(_date: number): number {\n\t\treturn super.getTime();\n\t}\n\n\toverride setFullYear(_year: number, _month?: number, _date?: number): number {\n\t\treturn super.getTime();\n\t}\n\n\toverride setHours(\n\t\t_hours: number,\n\t\t_min?: number,\n\t\t_sec?: number,\n\t\t_ms?: number,\n\t): number {\n\t\treturn super.getTime();\n\t}\n\n\toverride setMilliseconds(_ms: number): number {\n\t\treturn super.getTime();\n\t}\n\n\toverride setMinutes(_min: number, _sec?: number, _ms?: number): number {\n\t\treturn super.getTime();\n\t}\n\n\toverride setMonth(_month: number, _date?: number): number {\n\t\treturn super.getTime();\n\t}\n\n\toverride setSeconds(_sec: number, _ms?: number): number {\n\t\treturn super.getTime();\n\t}\n\n\toverride setTime(_time: number): number {\n\t\treturn super.getTime();\n\t}\n\n\toverride setUTCDate(_date: number): number {\n\t\treturn super.getTime();\n\t}\n\n\toverride setUTCFullYear(\n\t\t_year: number,\n\t\t_month?: number,\n\t\t_date?: number,\n\t): number {\n\t\treturn super.getTime();\n\t}\n\n\toverride setUTCHours(\n\t\t_hours: number,\n\t\t_min?: number,\n\t\t_sec?: number,\n\t\t_ms?: number,\n\t): number {\n\t\treturn super.getTime();\n\t}\n\n\toverride setUTCMilliseconds(_ms: number): number {\n\t\treturn super.getTime();\n\t}\n\n\toverride setUTCMinutes(_min: number, _sec?: number, _ms?: number): number {\n\t\treturn super.getTime();\n\t}\n\n\toverride setUTCMonth(_month: number, _date?: number): number {\n\t\treturn super.getTime();\n\t}\n\n\toverride setUTCSeconds(_sec: number, _ms?: number): number {\n\t\treturn super.getTime();\n\t}\n}\n","import { ReadonlyDate } from \"./ReadonlyDate\";\n\n/**\n * A collection of commonly-needed intervals (all defined in milliseconds).\n */\n// Doing type assertion on the static numeric values to prevent compiler from\n// over-inferring the types, and exposing too much info to end users\nexport const refreshRates = Object.freeze({\n\t/**\n\t * Indicates that a subscriber does not strictly need updates, but is still\n\t * allowed to be updated if it would keep it in sync with other subscribers.\n\t *\n\t * If all subscribers use this update interval, TimeSync will never dispatch\n\t * any updates.\n\t */\n\tidle: Number.POSITIVE_INFINITY,\n\n\thalfSecond: 500 as number,\n\toneSecond: 1000 as number,\n\tthirtySeconds: 30_000 as number,\n\toneMinute: 60 * 1000,\n\tfiveMinutes: 5 * 60 * 1000,\n\toneHour: 60 * 60 * 1000,\n}) satisfies Record<string, number>;\n\n/**\n * The set of readonly options that the TimeSync has been configured with.\n */\nexport type Configuration = Readonly<{\n\t/**\n\t * Indicates whether the TimeSync instance should be frozen for Snapshot\n\t * tests.\n\t *\n\t * Defaults to false.\n\t */\n\tfreezeUpdates: boolean;\n\n\t/**\n\t * The minimum refresh interval (in milliseconds) to use when dispatching\n\t * interval-based state updates.\n\t *\n\t * If a value smaller than this is specified when trying to set up a new\n\t * subscription, this minimum will be used instead.\n\t *\n\t * It is highly recommended that you only modify this value if you have a\n\t * good reason. Updating this value to be too low and make the event loop\n\t * get really hot and really tank performance elsewhere in an application.\n\t *\n\t * Defaults to 200ms.\n\t */\n\tminimumRefreshIntervalMs: number;\n\n\t/**\n\t * Indicates whether the same `onUpdate` callback (by reference) should be\n\t * called multiple time if registered by multiple systems.\n\t *\n\t * Defaults to false.\n\t */\n\tallowDuplicateOnUpdateCalls: boolean;\n}>;\n\n/**\n * The set of options that can be used to instantiate a TimeSync.\n */\nexport type InitOptions = Readonly<\n\tConfiguration & {\n\t\t/**\n\t\t * Indicates whether the TimeSync instance should be frozen for snapshot\n\t\t * tests. Highly encouraged that you use this together with\n\t\t * `initialDate`.\n\t\t *\n\t\t * Defaults to false.\n\t\t */\n\t\t// Duplicated property to override the LSP comment\n\t\tfreezeUpdates: boolean;\n\n\t\t/**\n\t\t * The Date object to use when initializing TimeSync to make the\n\t\t * constructor more pure and deterministic.\n\t\t */\n\t\tinitialDate: Date;\n\t}\n>;\n\n/**\n * The callback to call when a new state update is ready to be dispatched.\n */\nexport type OnTimeSyncUpdate = (dateSnapshot: ReadonlyDate) => void;\n\n/**\n * An object used to initialize a new subscription for TimeSync.\n */\nexport type SubscriptionOptions = Readonly<{\n\t/**\n\t * The maximum update interval that a subscriber needs. A value of\n\t * Number.POSITIVE_INFINITY indicates that the subscriber does not strictly\n\t * need any updates (though they may still happen based on other\n\t * subscribers).\n\t *\n\t * TimeSync always dispatches updates based on the lowest update interval\n\t * among all subscribers.\n\t *\n\t * For example, let's say that we have these three subscribers:\n\t * 1. A - Needs updates no slower than 500ms\n\t * 2. B – Needs updates no slower than 1000ms\n\t * 3. C – Uses interval of Infinity (does not strictly need an update)\n\t *\n\t * A, B, and C will all be updated at a rate of 500ms. If A unsubscribes,\n\t * then B and C will shift to being updated every 1000ms. If B unsubscribes\n\t * after A, updates will pause completely until a new subscriber gets\n\t * added, and it has a non-infinite interval.\n\t */\n\ttargetRefreshIntervalMs: number;\n\n\t/**\n\t * The callback to call when a new state update needs to be flushed amongst\n\t * all subscribers.\n\t */\n\tonUpdate: OnTimeSyncUpdate;\n}>;\n\n/**\n * A complete snapshot of the user-relevant internal state from TimeSync. This\n * value is treated as immutable at both runtime and compile time.\n */\nexport type Snapshot = Readonly<{\n\t/**\n\t * The date that was last dispatched to all subscribers.\n\t */\n\tdate: ReadonlyDate;\n\n\t/**\n\t * The number of subscribers registered with TimeSync.\n\t */\n\tsubscriberCount: number;\n\n\t/**\n\t * The configuration options used when instantiating the TimeSync instance.\n\t * The value is guaranteed to be stable for the entire lifetime of TimeSync.\n\t */\n\tconfig: Configuration;\n}>;\n\ninterface TimeSyncApi {\n\t/**\n\t * Subscribes an external system to TimeSync.\n\t *\n\t * The same callback (by reference) is allowed to be registered multiple\n\t * times, either for the same update interval, or different update\n\t * intervals. Depending on how TimeSync is instantiated, it may choose to\n\t * de-duplicate these function calls on each round of updates.\n\t *\n\t * @throws {RangeError} If the provided interval is not either a positive\n\t * integer or positive infinity.\n\t * @returns An unsubscribe callback. Calling the callback more than once\n\t * results in a no-op.\n\t */\n\tsubscribe: (options: SubscriptionOptions) => () => void;\n\n\t/**\n\t * Allows an external system to pull an immutable snapshot of some of the\n\t * internal state inside TimeSync. The snapshot is frozen at runtime and\n\t * cannot be mutated.\n\t *\n\t * @returns An object with multiple properties describing the TimeSync.\n\t */\n\tgetStateSnapshot: () => Snapshot;\n\n\t/**\n\t * Resets all internal state in the TimeSync, and handles all cleanup for\n\t * subscriptions and intervals previously set up. Configuration values are\n\t * retained.\n\t *\n\t * This method can be used as a dispose method for a locally-scoped\n\t * TimeSync (a TimeSync with no subscribers is safe to garbage-collect\n\t * without any risks of memory leaks). It can also be used to reset a global\n\t * TimeSync to its initial state for certain testing setups.\n\t */\n\tclearAll: () => void;\n}\n\ntype SubscriptionEntry = Readonly<{\n\ttargetInterval: number;\n\tunsubscribe: () => void;\n}>;\n\n/* biome-ignore lint:suspicious/noEmptyBlockStatements -- Rare case where we do\n actually want a completely empty function body. */\nfunction noOp(..._: readonly unknown[]): void {}\n\nconst defaultMinimumRefreshIntervalMs = 200;\n\n/**\n * One thing that was considered was giving TimeSync the ability to flip which\n * kinds of dates it uses, and let it use native dates instead of readonly\n * dates. We type readonly dates as native dates for better interoperability\n * with pretty much every JavaScript library under the sun, but there is still a\n * big difference in runtime behavior. There is a risk that blocking mutations\n * could break some other library in other ways.\n *\n * That might be worth revisiting if we get user feedback, but right now, it\n * seems like an incredibly bad idea.\n *\n * 1. Any single mutation has a risk of breaking the entire integrity of the\n * system. If a consumer would try to mutate them, things SHOULD blow up by\n * default.\n * 2. Dates are a type of object that are far more read-heavy than write-heavy,\n * so the risks of breaking are generally lower\n * 3. If a user really needs a mutable version of the date, they can make a\n * mutable copy first via `const mutable = readonlyDate.toNativeDate()`\n *\n * The one case when turning off the readonly behavior would be good would be\n * if you're on a server that really needs to watch its garbage collection\n * output, and you the overhead from the readonly date is causing too much\n * pressure on resources. In that case, you could switch to native dates, but\n * you'd still need a LOT of trigger discipline to avoid mutations, especially\n * if you rely on outside libraries.\n */\n/**\n * TimeSync provides a centralized authority for working with time values in a\n * more structured way. It ensures all dependents for the time values stay in\n * sync with each other.\n *\n * (e.g., In a React codebase, you want multiple components that rely on time\n * values to update together, to avoid screen tearing and stale data for only\n * some parts of the screen.)\n */\nexport class TimeSync implements TimeSyncApi {\n\t/**\n\t * Stores all refresh intervals actively associated with an onUpdate\n\t * callback (along with their associated unsubscribe callbacks).\n\t *\n\t * Supports storing the exact same callback-interval pairs multiple times,\n\t * in case multiple external systems need to subscribe with the exact same\n\t * data concerns. Because the functions themselves are used as keys, that\n\t * ensures that each callback will only be called once per update, no matter\n\t * how subscribers use it.\n\t *\n\t * Each map value should stay sorted by refresh interval, in ascending\n\t * order.\n\t */\n\treadonly #subscriptions: Map<OnTimeSyncUpdate, SubscriptionEntry[]>;\n\n\t/**\n\t * The latest public snapshot of TimeSync's internal state. The snapshot\n\t * should always be treated as an immutable value.\n\t */\n\t#latestSnapshot: Snapshot;\n\n\t/**\n\t * A cached version of the fastest interval currently registered with\n\t * TimeSync. Should always be derived from #subscriptions\n\t */\n\t#fastestRefreshInterval: number;\n\n\t/**\n\t * Used for both its intended purpose (creating interval), but also as a\n\t * janky version of setTimeout.\n\t *\n\t * There are a few times when we need timeout-like logic, but if we use\n\t * setInterval for everything, we have fewer IDs to juggle, and less risk of\n\t * things getting out of sync.\n\t *\n\t * Type defined like this to support client and server behavior. Node.js\n\t * uses its own custom timeout type, but Deno, Bun, and the browser all use\n\t * the number type.\n\t */\n\t#intervalId: NodeJS.Timeout | number | undefined;\n\n\tconstructor(options?: Partial<InitOptions>) {\n\t\tconst {\n\t\t\tinitialDate,\n\t\t\tfreezeUpdates = false,\n\t\t\tallowDuplicateOnUpdateCalls = false,\n\t\t\tminimumRefreshIntervalMs = defaultMinimumRefreshIntervalMs,\n\t\t} = options ?? {};\n\n\t\tconst isMinValid =\n\t\t\tNumber.isInteger(minimumRefreshIntervalMs) &&\n\t\t\tminimumRefreshIntervalMs > 0;\n\t\tif (!isMinValid) {\n\t\t\tthrow new RangeError(\n\t\t\t\t`Minimum refresh interval must be a positive integer (received ${minimumRefreshIntervalMs} ms)`,\n\t\t\t);\n\t\t}\n\n\t\tthis.#subscriptions = new Map();\n\t\tthis.#fastestRefreshInterval = Number.POSITIVE_INFINITY;\n\t\tthis.#intervalId = undefined;\n\n\t\t// Not defined inline to avoid wonkiness that Object.freeze introduces\n\t\t// when you rename a property on a frozen object\n\t\tconst initialSnapshot: Snapshot = {\n\t\t\tsubscriberCount: 0,\n\t\t\tdate: initialDate ? new ReadonlyDate(initialDate) : new ReadonlyDate(),\n\t\t\tconfig: Object.freeze({\n\t\t\t\tfreezeUpdates,\n\t\t\t\tminimumRefreshIntervalMs,\n\t\t\t\tallowDuplicateOnUpdateCalls,\n\t\t\t}),\n\t\t};\n\t\tthis.#latestSnapshot = Object.freeze(initialSnapshot);\n\t}\n\n\t#setSnapshot(update: Partial<Snapshot>): boolean {\n\t\tconst { date, subscriberCount, config } = this.#latestSnapshot;\n\t\tif (config.freezeUpdates) {\n\t\t\treturn false;\n\t\t}\n\n\t\t// Avoiding both direct property assignment or spread syntax because\n\t\t// Object.freeze causes weird TypeScript LSP issues around assignability\n\t\t// where trying to rename a property. If you rename a property on a\n\t\t// type, it WON'T rename the runtime properties. Object.freeze\n\t\t// introduces an extra type boundary that break the linking\n\t\tconst updated: Snapshot = {\n\t\t\t// Always reject any new configs because trying to remove them at\n\t\t\t// the type level isn't worth it for an internal implementation\n\t\t\t// detail\n\t\t\tconfig,\n\t\t\tdate: update.date ?? date,\n\t\t\tsubscriberCount: update.subscriberCount ?? subscriberCount,\n\t\t};\n\n\t\tthis.#latestSnapshot = Object.freeze(updated);\n\t\treturn true;\n\t}\n\n\t#notifyAllSubscriptions(): void {\n\t\t// It's more important that we copy the date object into a separate\n\t\t// variable here than normal, because need make sure the `this` context\n\t\t// can't magically change between updates and cause subscribers to\n\t\t// receive different values (e.g., one of the subscribers calls the\n\t\t// invalidate method)\n\t\tconst { date, config } = this.#latestSnapshot;\n\n\t\t// We still need to let the logic go through if the current fastest\n\t\t// interval is Infinity, so that we can support letting any arbitrary\n\t\t// consumer invalidate the date immediately\n\t\tconst subscriptionsPaused =\n\t\t\tconfig.freezeUpdates || this.#subscriptions.size === 0;\n\t\tif (subscriptionsPaused) {\n\t\t\treturn;\n\t\t}\n\n\t\t/**\n\t\t * Two things for both paths:\n\t\t * 1. We need to make sure that we do one-time serializations of the map\n\t\t * entries into an array instead of constantly pulling from the map via\n\t\t * the iterator protocol in the off chance that subscriptions add new\n\t\t * subscriptions. We need to make infinite loops impossible. If new\n\t\t * subscriptions get added, they'll just have to wait until the next\n\t\t * update round.\n\t\t *\n\t\t * 2. The trade off of the serialization is that we do lose the ability\n\t\t * to auto-break the loops if one of the subscribers ends up resetting\n\t\t * all state, because we'll still have local copies of entries. We need\n\t\t * to check on each iteration to see if we should continue.\n\t\t */\n\t\tif (config.allowDuplicateOnUpdateCalls) {\n\t\t\t// Not super happy about this, but because each subscription array\n\t\t\t// is mutable, we have to make an immutable copy of the count of\n\t\t\t// each sub before starting any dispatches. If we wait until the\n\t\t\t// inner loop to store the length of the subs before iterating over\n\t\t\t// them, that's too late. It's possible that a subscription could\n\t\t\t// cause data to be pushed to an array for a different interval\n\t\t\tconst entries = Array.from(\n\t\t\t\tthis.#subscriptions,\n\t\t\t\t([onUpdate, subs]) => [onUpdate, subs.length] as const,\n\t\t\t);\n\t\t\touter: for (const [onUpdate, subCount] of entries) {\n\t\t\t\tfor (let i = 0; i < subCount; i++) {\n\t\t\t\t\tconst wasCleared = this.#subscriptions.size === 0;\n\t\t\t\t\tif (wasCleared) {\n\t\t\t\t\t\tbreak outer;\n\t\t\t\t\t}\n\t\t\t\t\tonUpdate(date);\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\n\t\tconst funcs = [...this.#subscriptions.keys()];\n\t\tfor (const onUpdate of funcs) {\n\t\t\tconst wasCleared = this.#subscriptions.size === 0;\n\t\t\tif (wasCleared) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tonUpdate(date);\n\t\t}\n\t}\n\n\t/**\n\t * The logic that should happen at each step in TimeSync's active interval.\n\t *\n\t * Defined as an arrow function so that we can just pass it directly to\n\t * setInterval without needing to make a new wrapper function each time. We\n\t * don't have many situations where we can lose the `this` context, but this\n\t * is one of them.\n\t */\n\treadonly #onTick = (): void => {\n\t\t// Defensive step to make sure that an invalid tick wasn't started\n\t\tconst { config } = this.#latestSnapshot;\n\t\tif (config.freezeUpdates) {\n\t\t\tclearInterval(this.#intervalId);\n\t\t\tthis.#intervalId = undefined;\n\t\t\treturn;\n\t\t}\n\n\t\tconst wasChanged = this.#setSnapshot({ date: new ReadonlyDate() });\n\t\tif (wasChanged) {\n\t\t\tthis.#notifyAllSubscriptions();\n\t\t}\n\t};\n\n\t#onFastestIntervalChange(): void {\n\t\tconst fastest = this.#fastestRefreshInterval;\n\t\tconst { date, config } = this.#latestSnapshot;\n\t\tconst updatesShouldStop =\n\t\t\tconfig.freezeUpdates || fastest === Number.POSITIVE_INFINITY;\n\t\tif (updatesShouldStop) {\n\t\t\tclearInterval(this.#intervalId);\n\t\t\tthis.#intervalId = undefined;\n\t\t\treturn;\n\t\t}\n\n\t\tconst elapsed = new ReadonlyDate().getTime() - date.getTime();\n\t\tconst timeBeforeNextUpdate = fastest - elapsed;\n\n\t\t// Clear previous interval sight unseen just to be on the safe side\n\t\tclearInterval(this.#intervalId);\n\n\t\tif (timeBeforeNextUpdate <= 0) {\n\t\t\tconst wasChanged = this.#setSnapshot({ date: new ReadonlyDate() });\n\t\t\tif (wasChanged) {\n\t\t\t\tthis.#notifyAllSubscriptions();\n\t\t\t}\n\t\t\tthis.#intervalId = setInterval(this.#onTick, fastest);\n\t\t\treturn;\n\t\t}\n\n\t\t// Most common case for this branch is the very first subscription\n\t\t// getting added, but there's still the small chance that the fastest\n\t\t// interval could change right after an update got flushed\n\t\tif (timeBeforeNextUpdate === fastest) {\n\t\t\tthis.#intervalId = setInterval(this.#onTick, timeBeforeNextUpdate);\n\t\t\treturn;\n\t\t}\n\n\t\t// Otherwise, use interval as pseudo-timeout, and then go back to using\n\t\t// it as a normal interval afterwards\n\t\tthis.#intervalId = setInterval(() => {\n\t\t\tclearInterval(this.#intervalId);\n\n\t\t\t// Need to set up interval before ticking in the tiny, tiny chance\n\t\t\t// that ticking would cause the TimeSync instance to be reset. We\n\t\t\t// don't want to start a new interval right after we've lost our\n\t\t\t// ability to do cleanup. The timer won't start getting processed\n\t\t\t// until the function leaves scope anyway\n\t\t\tthis.#intervalId = setInterval(this.#onTick, fastest);\n\t\t\tthis.#onTick();\n\t\t}, timeBeforeNextUpdate);\n\t}\n\n\t#updateFastestInterval(): void {\n\t\tconst { config } = this.#latestSnapshot;\n\t\tif (config.freezeUpdates) {\n\t\t\tthis.#fastestRefreshInterval = Number.POSITIVE_INFINITY;\n\t\t\treturn;\n\t\t}\n\n\t\tconst prevFastest = this.#fastestRefreshInterval;\n\t\tlet newFastest = Number.POSITIVE_INFINITY;\n\n\t\t// This setup requires that every interval array stay sorted. It\n\t\t// immediately falls apart if this isn't guaranteed.\n\t\tfor (const entries of this.#subscriptions.values()) {\n\t\t\tconst subFastest = entries[0]?.targetInterval ?? Number.POSITIVE_INFINITY;\n\t\t\tif (subFastest < newFastest) {\n\t\t\t\tnewFastest = subFastest;\n\t\t\t}\n\t\t}\n\n\t\tthis.#fastestRefreshInterval = newFastest;\n\t\tif (prevFastest !== newFastest) {\n\t\t\tthis.#onFastestIntervalChange();\n\t\t}\n\t}\n\n\tsubscribe(sh: SubscriptionOptions): () => void {\n\t\tconst { config } = this.#latestSnapshot;\n\t\tif (config.freezeUpdates) {\n\t\t\treturn noOp;\n\t\t}\n\n\t\t// Destructuring properties so that they can't be fiddled with after\n\t\t// this function call ends\n\t\tconst { targetRefreshIntervalMs, onUpdate } = sh;\n\n\t\tconst isTargetValid =\n\t\t\ttargetRefreshIntervalMs === Number.POSITIVE_INFINITY ||\n\t\t\t(Number.isInteger(targetRefreshIntervalMs) &&\n\t\t\t\ttargetRefreshIntervalMs > 0);\n\t\tif (!isTargetValid) {\n\t\t\tthrow new Error(\n\t\t\t\t`Target refresh interval must be positive infinity or a positive integer (received ${targetRefreshIntervalMs} ms)`,\n\t\t\t);\n\t\t}\n\n\t\tlet unsubscribed = false;\n\t\tconst unsubscribe = (): void => {\n\t\t\tif (unsubscribed) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst entries = this.#subscriptions.get(onUpdate);\n\t\t\tif (entries === undefined) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst matchIndex = entries.findIndex(\n\t\t\t\t(e) => e.unsubscribe === unsubscribe,\n\t\t\t);\n\t\t\tif (matchIndex === -1) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t// No need to sort on removal because everything gets sorted as it\n\t\t\t// enters the subscriptions map\n\t\t\tentries.splice(matchIndex, 1);\n\t\t\tif (entries.length === 0) {\n\t\t\t\tthis.#subscriptions.delete(onUpdate);\n\t\t\t}\n\t\t\tthis.#updateFastestInterval();\n\n\t\t\tvoid this.#setSnapshot({\n\t\t\t\tsubscriberCount: Math.max(0, this.#latestSnapshot.subscriberCount - 1),\n\t\t\t});\n\t\t\tunsubscribed = true;\n\t\t};\n\n\t\tlet entries = this.#subscriptions.get(onUpdate);\n\t\tif (entries === undefined) {\n\t\t\tentries = [];\n\t\t\tthis.#subscriptions.set(onUpdate, entries);\n\t\t}\n\n\t\tconst targetInterval = Math.max(\n\t\t\tconfig.minimumRefreshIntervalMs,\n\t\t\ttargetRefreshIntervalMs,\n\t\t);\n\t\tentries.push({ unsubscribe, targetInterval });\n\t\tentries.sort((e1, e2) => e1.targetInterval - e2.targetInterval);\n\n\t\tvoid this.#setSnapshot({\n\t\t\tsubscriberCount: this.#latestSnapshot.subscriberCount + 1,\n\t\t});\n\n\t\tthis.#updateFastestInterval();\n\t\treturn unsubscribe;\n\t}\n\n\tgetStateSnapshot(): Snapshot {\n\t\treturn this.#latestSnapshot;\n\t}\n\n\tclearAll(): void {\n\t\tclearInterval(this.#intervalId);\n\t\tthis.#intervalId = undefined;\n\t\tthis.#fastestRefreshInterval = 0;\n\n\t\tfor (const entries of this.#subscriptions.values()) {\n\t\t\tfor (const e of entries) {\n\t\t\t\te.unsubscribe();\n\t\t\t}\n\t\t}\n\t\tthis.#subscriptions.clear();\n\n\t\tvoid this.#setSnapshot({ subscriberCount: 0 });\n\t}\n}\n"],"mappings":";;;;;;;;;;;AA8CA,IAAa,eAAb,cAAkC,KAAgC;CAwBjE,YACC,WACA,YACA,KACA,OACA,SACA,SACA,cACC;AAcD,MADC,qBAAqB,QAAQ,UAAU,UAAU,KAAK,eAEtD,OAAM,IAAI,WACT,0DACA;AAgBF,MARuB,CAAC,GAAG,UAAU,CAAC,MAAM,OAAO;;;;;;AAMlD,UAAO,OAAO,OAAO,YAAY,CAAC,OAAO,SAAS,GAAG;IACpD,CAED,OAAM,IAAI,WACT,wDACA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqCF,MAAI,cAAc,QAAW;AAC5B,UAAO;GACP,MAAM,wDAAwC,IAAI,MAAM;AACxD,SAAM,QAAQ,sCAAsC,SAAS,CAAC;AAC9D;;AAGD,MAAI,OAAO,cAAc,UAAU;AACl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