@buenos-nachos/time-sync 0.5.4 → 0.6.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,315 @@
1
+ //#region src/ReadonlyDate.d.ts
2
+ /**
3
+ * @file This comment is here to provide clarity on why proxy objects might
4
+ * always be a dead end for this library, and document failed experiments.
5
+ *
6
+ * Readonly dates need to have a lot of interoperability with native dates
7
+ * (pretty much every JavaScript library uses the built-in type). So, this code
8
+ * originally defined them as a Proxy wrapper over native dates. The handler
9
+ * intercepted all methods prefixed with `set` and turned them into no-ops.
10
+ *
11
+ * That got really close to working, but then development ran into a critical
12
+ * limitation of the Proxy API. Basically, if the readonly date is defined with
13
+ * a proxy, and you try to call Date.prototype.toISOString.call(readonlyDate),
14
+ * that immediately blows up because the proxy itself is treated as the receiver
15
+ * instead of the underlying native date.
16
+ *
17
+ * Vitest uses .call because it's the more airtight thing to do in most
18
+ * situations, but proxy objects only have traps for .apply calls, not .call. So
19
+ * there is no way in the language to intercept these calls and make sure
20
+ * they're going to the right place. It is a hard, HARD limitation.
21
+ *
22
+ * The good news, though, is that having an extended class seems like the better
23
+ * option, because it gives us the ability to define custom convenience methods
24
+ * without breaking instanceof checks or breaking TypeScript assignability for
25
+ * libraries that expect native dates. We just have to do a little bit of extra
26
+ * work to fudge things for test runners.
27
+ */
28
+ /**
29
+ * Any extra methods for readonly dates.
30
+ */
31
+ interface ReadonlyDateApi {
32
+ /**
33
+ * Converts a readonly date into a native (mutable) date.
34
+ */
35
+ toNativeDate(): Date;
36
+ }
37
+ /**
38
+ * A readonly version of a Date object. To maximize compatibility with existing
39
+ * libraries, all methods are the same as the native Date object at the type
40
+ * level. But crucially, all methods prefixed with `set` have all mutation logic
41
+ * removed.
42
+ *
43
+ * If you need a mutable version of the underlying date, ReadonlyDate exposes a
44
+ * .toNativeDate method to do a runtime conversion to a native/mutable date.
45
+ */
46
+ declare class ReadonlyDate extends Date implements ReadonlyDateApi {
47
+ constructor();
48
+ constructor(initValue: number | string | Date);
49
+ constructor(year: number, monthIndex: number);
50
+ constructor(year: number, monthIndex: number, day: number);
51
+ constructor(year: number, monthIndex: number, day: number, hours: number);
52
+ constructor(year: number, monthIndex: number, day: number, hours: number, seconds: number);
53
+ constructor(year: number, monthIndex: number, day: number, hours: number, seconds: number, milliseconds: number);
54
+ toNativeDate(): Date;
55
+ setDate(_date: number): number;
56
+ setFullYear(_year: number, _month?: number, _date?: number): number;
57
+ setHours(_hours: number, _min?: number, _sec?: number, _ms?: number): number;
58
+ setMilliseconds(_ms: number): number;
59
+ setMinutes(_min: number, _sec?: number, _ms?: number): number;
60
+ setMonth(_month: number, _date?: number): number;
61
+ setSeconds(_sec: number, _ms?: number): number;
62
+ setTime(_time: number): number;
63
+ setUTCDate(_date: number): number;
64
+ setUTCFullYear(_year: number, _month?: number, _date?: number): number;
65
+ setUTCHours(_hours: number, _min?: number, _sec?: number, _ms?: number): number;
66
+ setUTCMilliseconds(_ms: number): number;
67
+ setUTCMinutes(_min: number, _sec?: number, _ms?: number): number;
68
+ setUTCMonth(_month: number, _date?: number): number;
69
+ setUTCSeconds(_sec: number, _ms?: number): number;
70
+ }
71
+ //#endregion
72
+ //#region src/TimeSync.d.ts
73
+ /**
74
+ * A collection of commonly-needed intervals (all defined in milliseconds).
75
+ */
76
+ declare const refreshRates: Readonly<{
77
+ /**
78
+ * Indicates that a subscriber does not strictly need updates, but is still
79
+ * allowed to be updated if it would keep it in sync with other subscribers.
80
+ *
81
+ * If all subscribers use this update interval, TimeSync will never dispatch
82
+ * any updates.
83
+ */
84
+ idle: number;
85
+ halfSecond: number;
86
+ oneSecond: number;
87
+ thirtySeconds: number;
88
+ oneMinute: number;
89
+ fiveMinutes: number;
90
+ oneHour: number;
91
+ }>;
92
+ /**
93
+ * The set of readonly options that the TimeSync has been configured with.
94
+ */
95
+ interface Configuration {
96
+ /**
97
+ * Indicates whether the TimeSync instance should be frozen for Snapshot
98
+ * tests. Highly encouraged that you use this together with
99
+ * `initialDate`.
100
+ *
101
+ * Defaults to false.
102
+ */
103
+ readonly freezeUpdates: boolean;
104
+ /**
105
+ * The minimum refresh interval (in milliseconds) to use when dispatching
106
+ * interval-based state updates.
107
+ *
108
+ * If a value smaller than this is specified when trying to set up a new
109
+ * subscription, this minimum will be used instead.
110
+ *
111
+ * It is highly recommended that you only modify this value if you have a
112
+ * good reason. Updating this value to be too low can make the event loop
113
+ * get really hot and really tank performance elsewhere in an application.
114
+ *
115
+ * Defaults to 200ms.
116
+ */
117
+ readonly minimumRefreshIntervalMs: number;
118
+ /**
119
+ * Indicates whether the same `onUpdate` callback (by reference) should be
120
+ * called multiple time if registered by multiple systems.
121
+ *
122
+ * If this value is flipped to false, each onUpdate callback will receive
123
+ * the subscription context for the FIRST subscriber that registered the
124
+ * onUpdate callback.
125
+ *
126
+ * Defaults to true.
127
+ */
128
+ readonly allowDuplicateOnUpdateCalls: boolean;
129
+ }
130
+ /**
131
+ * The set of options that can be used to instantiate a TimeSync.
132
+ */
133
+ interface InitOptions extends Configuration {
134
+ /**
135
+ * The Date object to use when initializing TimeSync to make the
136
+ * constructor more pure and deterministic.
137
+ */
138
+ readonly initialDate: Date;
139
+ }
140
+ /**
141
+ * An object used to initialize a new subscription for TimeSync.
142
+ */
143
+ interface SubscriptionInitOptions {
144
+ /**
145
+ * The maximum update interval that a subscriber needs. A value of
146
+ * Number.POSITIVE_INFINITY indicates that the subscriber does not strictly
147
+ * need any updates (though they may still happen based on other
148
+ * subscribers).
149
+ *
150
+ * TimeSync always dispatches updates based on the lowest update interval
151
+ * among all subscribers.
152
+ *
153
+ * For example, let's say that we have these three subscribers:
154
+ * 1. A - Needs updates no slower than 500ms
155
+ * 2. B – Needs updates no slower than 1000ms
156
+ * 3. C – Uses interval of Infinity (does not strictly need an update)
157
+ *
158
+ * A, B, and C will all be updated at a rate of 500ms. If A unsubscribes,
159
+ * then B and C will shift to being updated every 1000ms. If B unsubscribes
160
+ * after A, updates will pause completely until a new subscriber gets
161
+ * added, and it has a non-infinite interval.
162
+ */
163
+ readonly targetRefreshIntervalMs: number;
164
+ /**
165
+ * The callback to call when a new state update needs to be flushed amongst
166
+ * all subscribers.
167
+ */
168
+ readonly onUpdate: OnTimeSyncUpdate;
169
+ }
170
+ /**
171
+ * A complete snapshot of the user-relevant internal state from TimeSync. This
172
+ * value is treated as immutable at both runtime and compile time.
173
+ */
174
+ interface Snapshot {
175
+ /**
176
+ * The date that TimeSync last processed. This will always match the date that
177
+ * was last dispatched to all subscribers, but if no updates have been issued,
178
+ * this value will match the date used to instantiate the TimeSync.
179
+ */
180
+ readonly date: ReadonlyDate;
181
+ /**
182
+ * The monotonic milliseconds that elapsed between the TimeSync being
183
+ * instantiated and the last update being dispatched.
184
+ *
185
+ * Will be null if no updates have ever been dispatched.
186
+ */
187
+ readonly lastUpdatedAtMs: number | null;
188
+ /**
189
+ * The number of subscribers registered with TimeSync.
190
+ */
191
+ readonly subscriberCount: number;
192
+ /**
193
+ * The configuration options used when instantiating the TimeSync instance.
194
+ * The value is guaranteed to be stable for the entire lifetime of TimeSync.
195
+ */
196
+ readonly config: Configuration;
197
+ }
198
+ /**
199
+ * An object with information about a specific subscription registered with
200
+ * TimeSync. The entire context is frozen at runtime.
201
+ */
202
+ interface SubscriptionContext {
203
+ /**
204
+ * A reference to the TimeSync instance that the subscription was registered
205
+ * with.
206
+ */
207
+ readonly timeSync: TimeSync;
208
+ /**
209
+ * The effective interval that the subscription is updating at. This may be a
210
+ * value larger than than the target refresh interval, depending on whether
211
+ * TimeSync was configured with a minimum refresh value.
212
+ */
213
+ readonly refreshIntervalMs: number;
214
+ /**
215
+ * The unsubscribe callback associated with a subscription. This is the same
216
+ * callback returned by `TimeSync.subscribe`.
217
+ */
218
+ readonly unsubscribe: () => void;
219
+ /**
220
+ * The monotonic milliseconds that elapsed between the TimeSync being
221
+ * instantiated and the subscription being registered.
222
+ */
223
+ readonly registeredAtMs: number;
224
+ }
225
+ /**
226
+ * The callback to call when a new state update is ready to be dispatched.
227
+ */
228
+ type OnTimeSyncUpdate = (newDate: ReadonlyDate, context: SubscriptionContext) => void;
229
+ interface TimeSyncApi {
230
+ /**
231
+ * Subscribes an external system to TimeSync.
232
+ *
233
+ * The same callback (by reference) is allowed to be registered multiple
234
+ * times, either for the same update interval, or different update
235
+ * intervals. Depending on how TimeSync is instantiated, it may choose to
236
+ * de-duplicate these function calls on each round of updates.
237
+ *
238
+ * If a value of Number.POSITIVE_INFINITY is used, the subscription will be
239
+ * considered "idle". Idle subscriptions cannot trigger updates on their
240
+ * own, but can stay in the loop as otherupdates get dispatched from via
241
+ * other subscriptions.
242
+ *
243
+ * Consider using the refreshRates object from this package for a set of
244
+ * commonly-used intervals.
245
+ *
246
+ * @throws {RangeError} If the provided interval is neither a positive
247
+ * integer nor positive infinity.
248
+ * @returns An unsubscribe callback. Calling the callback more than once
249
+ * results in a no-op.
250
+ */
251
+ subscribe: (options: SubscriptionInitOptions) => () => void;
252
+ /**
253
+ * Allows an external system to pull an immutable snapshot of some of the
254
+ * internal state inside TimeSync. The snapshot is frozen at runtime and
255
+ * cannot be mutated.
256
+ *
257
+ * @returns An object with multiple properties describing the TimeSync.
258
+ */
259
+ getStateSnapshot: () => Snapshot;
260
+ /**
261
+ * Resets all internal state in the TimeSync, and handles all cleanup for
262
+ * subscriptions and intervals previously set up. Configuration values are
263
+ * retained.
264
+ *
265
+ * This method can be used as a dispose method for a locally-scoped
266
+ * TimeSync (a TimeSync with no subscribers is safe to garbage-collect
267
+ * without any risks of memory leaks). It can also be used to reset a global
268
+ * TimeSync to its initial state for certain testing setups.
269
+ */
270
+ clearAll: () => void;
271
+ }
272
+ /**
273
+ * One thing that was considered was giving TimeSync the ability to flip which
274
+ * kinds of dates it uses, and let it use native dates instead of readonly
275
+ * dates. We type readonly dates as native dates for better interoperability
276
+ * with pretty much every JavaScript library under the sun, but there is still a
277
+ * big difference in runtime behavior. There is a risk that blocking mutations
278
+ * could break some other library in other ways.
279
+ *
280
+ * That might be worth revisiting if we get user feedback, but right now, it
281
+ * seems like an incredibly bad idea.
282
+ *
283
+ * 1. Any single mutation has a risk of breaking the entire integrity of the
284
+ * system. If a consumer would try to mutate them, things SHOULD blow up by
285
+ * default.
286
+ * 2. Dates are a type of object that are far more read-heavy than write-heavy,
287
+ * so the risks of breaking are generally lower
288
+ * 3. If a user really needs a mutable version of the date, they can make a
289
+ * mutable copy first via `const mutable = readonlyDate.toNativeDate()`
290
+ *
291
+ * The one case when turning off the readonly behavior would be good would be
292
+ * if you're on a server that really needs to watch its garbage collection
293
+ * output, and you the overhead from the readonly date is causing too much
294
+ * pressure on resources. In that case, you could switch to native dates, but
295
+ * you'd still need a LOT of trigger discipline to avoid mutations, especially
296
+ * if you rely on outside libraries.
297
+ */
298
+ /**
299
+ * TimeSync provides a centralized authority for working with time values in a
300
+ * more structured way. It ensures all dependents for the time values stay in
301
+ * sync with each other.
302
+ *
303
+ * (e.g., In a React codebase, you want multiple components that rely on time
304
+ * values to update together, to avoid screen tearing and stale data for only
305
+ * some parts of the screen.)
306
+ */
307
+ declare class TimeSync implements TimeSyncApi {
308
+ #private;
309
+ constructor(options?: Partial<InitOptions>);
310
+ subscribe(options: SubscriptionInitOptions): () => void;
311
+ getStateSnapshot(): Snapshot;
312
+ clearAll(): void;
313
+ }
314
+ //#endregion
315
+ export { type Configuration, type InitOptions, type OnTimeSyncUpdate, ReadonlyDate, type Snapshot, type SubscriptionContext, type SubscriptionInitOptions, TimeSync, refreshRates };