tr-period-calc 0.0.0-stage → 1.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.
package/CHANGELOG.md ADDED
@@ -0,0 +1,55 @@
1
+ # Changelog
2
+
3
+ All notable changes to this package are recorded here. The format follows
4
+ [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) and the project uses
5
+ [Semantic Versioning](https://semver.org/spec/v2.0.0.html). The source lives
6
+ at [github.com/rinne/node-tr-period-calc](https://github.com/rinne/node-tr-period-calc).
7
+
8
+ ## [1.0.0] - 2026-11-17
9
+
10
+ ### Added
11
+
12
+ - `PeriodCalc` class: sequential period indexing from a spec that is either
13
+ fixed (unix-second epoch and length in seconds) or calendar (local date-time
14
+ epoch, `N × day|week|month|year`, IANA time zone). `byIndex`, `byTime`,
15
+ `byDateTime`, `byUri`, `range`, `localTime`, `parseDateTime`, `equals`.
16
+ - The `tr-period-calc://[index]?epoch=…&length=…[&tz=…]` URI form for a spec
17
+ or a single self-contained period, with `PeriodCalc.parseUri` and
18
+ `PeriodCalc.periodByUri`. Every calculator and period exposes its canonical
19
+ URI. The query is decoded as an RFC 3986 query: `%XX` only, `+` is a
20
+ literal plus.
21
+ - Calendar periods are computed with `Intl.DateTimeFormat` instead of
22
+ rewriting `process.env.TZ`; the local-clock rules match legacy `Date`
23
+ (and Temporal's `compatible` disambiguation): a time in a DST gap moves
24
+ forward by the gap, a repeated time resolves to its first occurrence.
25
+ - Calendar lengths take a multiplier (`3month` for quarters, `2week`).
26
+ - A demonstration under `examples/`: `nordpool.js` defines Nord Pool market
27
+ days (calendar days in CET), hours and quarters from the epoch
28
+ 1993-01-01 00:00 CET, with the countries of the system and their zones;
29
+ `nordpool-cli` looks up the periods of a time, the limits of a period, or
30
+ describes one with the periods it belongs to and contains, in local time,
31
+ UTC or a given zone, as text or JSON. `optist` becomes a devDependency for
32
+ it. The example lives in the repository only; the npm package contains
33
+ the library and its documentation.
34
+ - Requires Node.js 24 or later.
35
+ - The legacy spec objects of `periodCalculator.js` (`periodEpoch` /
36
+ `periodLength` and `calendarEpoch` / `calendarPeriodLength` / `timeZone`)
37
+ are accepted as they are. Indexes and period starts are identical to the
38
+ legacy implementation; the compatibility test runs the legacy code side by
39
+ side.
40
+
41
+ ### Changed
42
+
43
+ Relative to `periodCalculator.js`, on purpose:
44
+
45
+ - A period always ends one second before the next one starts. The legacy
46
+ `last` was computed from local wall-clock arithmetic and left a gap in
47
+ zones whose DST change falls exactly on the period boundary time.
48
+ - A time whose period assignment by local clock contradicts the period
49
+ boundaries (only possible when the epoch time-of-day lies inside a DST
50
+ transition) is assigned by the boundaries.
51
+ - Monthly periods from the 29th to 31st and yearly periods from Feb 29 are
52
+ constrained to the last day of shorter months instead of overflowing into
53
+ the following month.
54
+ - A time zone given with a fixed-length spec and a unix-second epoch is an
55
+ error, since it would have no effect.
package/COPYING ADDED
@@ -0,0 +1,24 @@
1
+ The MIT License
2
+
3
+ Copyright © 2026 Timo J. Rinne <tri@iki.fi>
4
+
5
+ Permission is hereby granted, free of charge, to any person
6
+ obtaining a copy of this software and associated documentation
7
+ files (the "Software"), to deal in the Software without
8
+ restriction, including without limitation the rights to use,
9
+ copy, modify, merge, publish, distribute, sublicense, and/or
10
+ sell copies of the Software, and to permit persons to whom
11
+ the Software is furnished to do so, subject to the following
12
+ conditions:
13
+
14
+ The above copyright notice and this permission notice shall be
15
+ included in all copies or substantial portions of the Software.
16
+
17
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
18
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
19
+ OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
20
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
21
+ HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
22
+ WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
23
+ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
24
+ OTHER DEALINGS IN THE SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,446 @@
1
- # Temporary Holding Version
1
+ # tr-period-calc
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Canonical sequential period indexing for Node.js with zero dependencies.
4
+
5
+ Given a spec, every instant in time belongs to exactly one period, and
6
+ every period has an integer index: period 0 starts at the epoch, period 1
7
+ follows it, period -1 precedes it. The mapping is fixed for the life of
8
+ the spec, so periodic statistics can be assigned to a period once and
9
+ found again forever, on any machine, in any process, at any later date.
10
+
11
+ Two kinds of spec are supported:
12
+
13
+ - **Fixed**: an epoch in unix seconds and a length in seconds. This is
14
+ plain unix-time arithmetic. Fifteen-minute periods anchored at
15
+ 12:00:00 UTC stay at `*:00`, `*:15`, `*:30`, `*:45` UTC forever,
16
+ regardless of DST or leap years, because that is what unix time does.
17
+ - **Calendar**: an epoch as a local date-time, a length of one or more
18
+ days, weeks, months or years, and an IANA time zone. Period boundaries
19
+ follow the local clock: a week starting Monday 08:00 in New York starts
20
+ at 08:00 local every Monday, and the week in which DST begins is one
21
+ hour shorter.
22
+
23
+ A spec, and a single period of it, can be written as a self-contained
24
+ URI:
25
+
26
+ ```
27
+ tr-period-calc://?epoch=1788964903&length=600
28
+ tr-period-calc://1231?epoch=1788964903&length=600
29
+ tr-period-calc://?epoch=2026-01-05T08:00:00&length=week&tz=America/New_York
30
+ tr-period-calc://8?epoch=2026-01-05T08:00:00&length=week&tz=America/New_York
31
+ ```
32
+
33
+ The first is a spec (ten-minute periods from 2026-09-09T14:41:43Z), the
34
+ second is its period 1231. The URI carries everything needed to recompute
35
+ the period's boundaries, so it makes a good key for stored data.
36
+
37
+ Time zone support is whatever `Intl` in the running Node.js provides; no
38
+ zone data is bundled.
39
+
40
+ # Reference
41
+
42
+ ## Installation
43
+
44
+ ```sh
45
+ npm install tr-period-calc
46
+ ```
47
+
48
+ Node.js `>=24.0.0` is required.
49
+
50
+ ## Exports
51
+
52
+ ```js
53
+ const PeriodCalc = require('tr-period-calc');
54
+ ```
55
+
56
+ The class is the only export.
57
+
58
+ ## Quick start
59
+
60
+ ```js
61
+ const PeriodCalc = require('tr-period-calc');
62
+
63
+ // weeks starting Monday 08:00 New York time
64
+ const weeks = new PeriodCalc({ epoch: '2026-01-05 08:00', length: 'week', timeZone: 'America/New_York' });
65
+
66
+ weeks.uri;
67
+ // 'tr-period-calc://?epoch=2026-01-05T08:00:00&length=week&tz=America/New_York'
68
+
69
+ const p = weeks.byTime(1772967600); // 2026-03-08T11:00:00Z, a Sunday
70
+ p.index; // 8
71
+ p.first; // 1772456400 = 2026-03-02T13:00:00Z (Mon 08:00 EST)
72
+ p.last; // 1773057599 = 2026-03-09T11:59:59Z (Mon 07:59:59 EDT)
73
+ p.uri;
74
+ // 'tr-period-calc://8?epoch=2026-01-05T08:00:00&length=week&tz=America/New_York'
75
+
76
+ weeks.byIndex(9).first; // 1773057600, one second after p.last
77
+ weeks.localTime(p.first).dateTimeStr; // '2026-03-02T08:00:00'
78
+
79
+ // later, anywhere, from a stored key
80
+ PeriodCalc.periodByUri(p.uri).first; // 1772456400
81
+ ```
82
+
83
+ ## Specs
84
+
85
+ A spec is given to the constructor as an object or as a URI. The object
86
+ form has three fields:
87
+
88
+ - `epoch`: the start of period 0. A unix-second integer (number or
89
+ numeric string), a `Date`, or a local date-time string
90
+ `YYYY-MM-DD`, `YYYY-MM-DD HH:MM` or `YYYY-MM-DD HH:MM:SS` (`T` is
91
+ accepted in place of the space). A date-time string is read in
92
+ `timeZone`.
93
+ - `length`: a positive integer number of seconds (number or numeric
94
+ string) for a fixed spec, or `day`, `week`, `month` or `year` with an
95
+ optional multiplier (`3month`, `2week`) for a calendar spec.
96
+ - `timeZone`: an IANA time zone name, optional, default `UTC`. Names are
97
+ matched case-insensitively (`europe/helsinki`), with underscores,
98
+ dashes and spaces interchangeable (`America/New York`). Any other
99
+ name `Intl` accepts (`US/Eastern`) is used with the spelling given.
100
+
101
+ The names folded this way are those `Intl.supportedValuesOf('timeZone')`
102
+ lists. Other names, mostly IANA links (`CET`, `US/Eastern`, and on some
103
+ ICU versions renamed zones such as `Asia/Kolkata` or `Europe/Kyiv`), are
104
+ kept exactly as written, case included. They are deliberately not
105
+ resolved to the zone they link to: which name ICU considers canonical
106
+ changes between versions, and a stored URI must not depend on the
107
+ Node.js version that wrote it. The consequence is that `CET` and `cet`,
108
+ or `US/Eastern` and `America/New_York`, compute identical boundaries
109
+ but are different specs with different URIs. Spell links as the IANA
110
+ database does.
111
+
112
+ The spec is normalized on construction:
113
+
114
+ - A **fixed** spec is stored as a unix-second `epoch`, a numeric `length`
115
+ and `timeZone: 'UTC'`. A date-time epoch is converted using the given
116
+ zone and the zone is then dropped, since it has no effect on unix-time
117
+ periods. Giving a non-UTC zone together with a unix-second epoch is an
118
+ error rather than silently ignored.
119
+ - A **calendar** spec is stored as a `YYYY-MM-DDTHH:MM:SS` epoch, the
120
+ length as `[N]unit` with `N` omitted when 1, and the zone. A unix-second
121
+ epoch is converted to the local date-time in the zone. Only that
122
+ date-time is kept, so the boundary rules below apply to it as to any
123
+ other: a unix-second epoch on the second pass through a repeated hour
124
+ becomes a local time that resolves to the first pass, and period 0
125
+ then starts one hour (the size of the overlap) before the instant
126
+ given. The given instant still falls in period 0.
127
+
128
+ The legacy spec objects of `periodCalculator.js` are accepted as they
129
+ are: `{ periodEpoch, periodLength }` and
130
+ `{ calendarEpoch, calendarPeriodLength, timeZone }`. Keys other than
131
+ these and the three above are an error.
132
+
133
+ ## URIs
134
+
135
+ ```
136
+ tr-period-calc://[index]?epoch=<epoch>&length=<length>[&tz=<zone>]
137
+ ```
138
+
139
+ - `index` is an optional integer, negative allowed, no leading zeros.
140
+ Without it the URI names a spec, with it a single period.
141
+ - `epoch`, `length` and `tz` carry the spec fields exactly as described
142
+ above. `tz` is omitted for `UTC`. Parameters may be given in any
143
+ order and percent-encoded, but each at most once, and no other
144
+ parameters are allowed; a URI a future version might produce must not
145
+ be silently misread by this one.
146
+ - The query is decoded as an RFC 3986 query, not as an HTML form: `%XX`
147
+ is decoded and nothing else, so `+` is a plus sign (`tz=Etc/GMT+3`
148
+ works as written) and a space must be written `%20` (or use `T` in a
149
+ date-time).
150
+ - The scheme is matched case-insensitively. A `/` before the `?` is
151
+ tolerated.
152
+
153
+ Every calculator and every period exposes its canonical URI, which is
154
+ the normalized spec in the fixed parameter order with a zone name
155
+ percent-encoded only where necessary (`Etc/GMT%2B3`). Two calculators
156
+ are equal exactly when their canonical URIs are equal.
157
+
158
+ ## Periods
159
+
160
+ A period is a frozen plain object:
161
+
162
+ ```js
163
+ {
164
+ index: 8, // integer
165
+ first: 1772456400, // unix seconds, inclusive
166
+ last: 1773057599, // unix seconds, inclusive
167
+ uri: 'tr-period-calc://8?epoch=2026-01-05T08:00:00&length=week&tz=America/New_York',
168
+ spec: { epoch: '2026-01-05T08:00:00', length: 'week', timeZone: 'America/New_York' }
169
+ }
170
+ ```
171
+
172
+ Periods are contiguous and disjoint: `last` is always one second before
173
+ the next period's `first`. For fixed specs `last - first + 1` is the
174
+ length; for calendar specs it varies with DST and month length.
175
+
176
+ A calendar period can be empty. When the local clock skips the whole
177
+ span of a period, its start and the next period's start are the same
178
+ instant and the period has `last === first - 1`. This happened in
179
+ `Pacific/Apia`, which moved across the date line so that 2011-12-30
180
+ never took place there: daily periods keep their one-index-per-local-day
181
+ numbering, and the index of that day is an empty period. `byIndex` and
182
+ `range` return such a period like any other; `byTime` never does, since
183
+ no instant belongs to it. Code that sums or divides by
184
+ `last - first + 1` should allow for zero.
185
+
186
+ Calendar period boundaries are local wall-clock times. Where the wall
187
+ clock is ambiguous they follow the same rules as the legacy `Date`
188
+ constructor and Temporal's `compatible` disambiguation:
189
+
190
+ - A time that does not exist because clocks moved forward is pushed
191
+ forward by the size of the gap: daily periods from 03:30 in Helsinki
192
+ start at 04:30 on the day the gap swallows 03:00–03:59.
193
+ - A time that occurs twice because clocks moved back resolves to its
194
+ first occurrence.
195
+ - A day of month beyond the end of a month is constrained to the last
196
+ day of that month: monthly periods from January 31 start on February
197
+ 28 (or 29), March 31, April 30. Yearly periods from February 29 start
198
+ on February 28 in common years.
199
+
200
+ The `index` of a time is always consistent with these boundaries. With
201
+ an epoch time-of-day inside a DST transition it can happen that, by the
202
+ wall clock alone, a time seems to fall on the other side of a boundary
203
+ than it does by the instant; the instant wins.
204
+
205
+ The supported range is 1000-01-01T00:00:00Z to 9999-12-31T23:59:59Z
206
+ (`PeriodCalc.MIN_TIME` and `PeriodCalc.MAX_TIME`). Times, epochs and
207
+ period boundaries outside it are errors. Only periods that lie entirely
208
+ inside the range exist, so near either end of it a time inside the
209
+ range can still be refused: with seven-second periods from epoch 0,
210
+ `byTime(PeriodCalc.MAX_TIME)` throws `Invalid time` because its period
211
+ would end after `MAX_TIME`. Every instant covered by an existing period
212
+ belongs to exactly one.
213
+
214
+ ## `new PeriodCalc(spec)`
215
+
216
+ `spec` is a spec object, a spec URI, a period URI (the index is
217
+ ignored), or another `PeriodCalc`. Throws `Invalid spec`, `Invalid URI`
218
+ or `Invalid time zone`.
219
+
220
+ ## Instance properties
221
+
222
+ - `spec`: the normalized spec, a frozen `{ epoch, length, timeZone }`
223
+ - `uri`: the canonical spec URI
224
+ - `type`: `'fixed'` or `'calendar'`
225
+
226
+ `toString()` and `toJSON()` return the URI, so a calculator can be
227
+ stored in JSON and restored with `new PeriodCalc(...)`.
228
+
229
+ ## `equals(other)`
230
+
231
+ `other` is a `PeriodCalc` or anything the constructor accepts. True when
232
+ the canonical URIs match.
233
+
234
+ ## `byIndex(index)`
235
+
236
+ The period with the given integer index. Throws `Invalid index` when
237
+ the period does not lie inside the supported range.
238
+
239
+ ## `byTime(time)`
240
+
241
+ The period containing `time`: unix seconds as a number (a fraction is
242
+ floored), a `Date`, or nothing for the current time. Milliseconds passed
243
+ by mistake fall outside the supported range and throw `Invalid time`.
244
+
245
+ ## `byDateTime(dateTime, timeZone)`
246
+
247
+ The period containing the local date-time string `dateTime` (formats as
248
+ for a spec epoch), read in `timeZone`, default the spec's zone. Note
249
+ that a fixed spec's zone is always `UTC`.
250
+
251
+ ## `byUri(uri)`
252
+
253
+ The period named by a period URI of this spec. Throws `Invalid URI` for
254
+ a spec URI without an index and `Spec mismatch` for a period of another
255
+ spec. Use it to validate stored keys against the spec they are supposed
256
+ to belong to; `PeriodCalc.periodByUri` accepts any spec.
257
+
258
+ ## `range(from, to)`
259
+
260
+ An array of the periods from the one containing `from` to the one
261
+ containing `to`, inclusive, in index order. Times as for `byTime`.
262
+ Throws `Invalid time` when `to` precedes `from`'s period.
263
+
264
+ The whole array is built at once and there is no limit on its size:
265
+ a year of one-second periods is over 31 million objects. For long spans
266
+ of short periods, take the end indexes with `byTime` and walk them with
267
+ `byIndex` instead.
268
+
269
+ ## `localTime(time, timeZone)` / `PeriodCalc.localTime(time, timeZone)`
270
+
271
+ The local wall-clock view of an instant:
272
+
273
+ ```js
274
+ {
275
+ time: 1774747800, // the instant, unix seconds
276
+ timeZone: 'Europe/Helsinki',
277
+ year: 2026, month: 3, day: 29, hour: 4, minute: 30, second: 0,
278
+ weekday: 0, // 0 = Sunday .. 6 = Saturday
279
+ offset: 10800, // seconds east of UTC at that instant
280
+ dateStr: '2026-03-29',
281
+ timeStr: '04:30:00',
282
+ dateTimeStr: '2026-03-29T04:30:00'
283
+ }
284
+ ```
285
+
286
+ `time` as for `byTime`. The instance method defaults `timeZone` to the
287
+ spec's zone, the static one to `UTC`.
288
+
289
+ ## `parseDateTime(dateTime, timeZone)` / `PeriodCalc.parseDateTime(dateTime, timeZone)`
290
+
291
+ A local date-time string (formats as for a spec epoch) in a zone to unix
292
+ seconds, with the gap and overlap rules above. Defaults for `timeZone`
293
+ as for `localTime`. Throws `Invalid datetime`.
294
+
295
+ ## `PeriodCalc.parseUri(uri)`
296
+
297
+ `{ spec, index }` for a URI: the normalized spec object and the integer
298
+ index, `undefined` when the URI has none.
299
+
300
+ ## `PeriodCalc.periodByUri(uri)`
301
+
302
+ The period named by a period URI, of whatever spec. Throws
303
+ `Invalid URI` when the URI has no index.
304
+
305
+ ## `PeriodCalc.normalizeTimeZone(timeZone)`
306
+
307
+ The canonical zone name for the spec, `UTC` for nothing. Throws
308
+ `Invalid time zone`.
309
+
310
+ ## `PeriodCalc.SCHEME`, `PeriodCalc.MIN_TIME`, `PeriodCalc.MAX_TIME`
311
+
312
+ The URI scheme `tr-period-calc` and the supported range in unix seconds.
313
+
314
+ ## Example: Nord Pool market periods
315
+
316
+ The example lives in the
317
+ [source repository](https://github.com/rinne/node-tr-period-calc/tree/main/examples);
318
+ it is not part of the npm package.
319
+
320
+ `examples/nordpool.js` defines the periods of the Nord Pool day-ahead
321
+ market as three specs sharing one epoch, the first traded hour,
322
+ 1993-01-01 00:00 CET:
323
+
324
+ - market days: calendar days in CET/CEST (`length=day&tz=CET`), which
325
+ every country in the system follows whatever its own zone
326
+ - market hours: `length=3600` from the epoch
327
+ - market quarters: `length=900` from the epoch
328
+
329
+ Hours and quarters do not divide days evenly. The day DST starts has 23
330
+ hours and the day it ends has 25, so the module answers "which hours
331
+ make up this day" and "which day is this hour in" by time, never by
332
+ division. It also carries the countries of the system with their zones,
333
+ so a market day can be shown on each country's clock: 01:00 to 01:00 in
334
+ Finland and the Baltics, 23:00 to 23:00 in Ireland and Portugal.
335
+
336
+ `examples/nordpool-cli` is a command line tool on top of it. In a
337
+ checkout of the repository, run `npm install` once for its option
338
+ parser (`optist`, a development dependency).
339
+
340
+ ```sh
341
+ node examples/nordpool-cli # now
342
+ node examples/nordpool-cli '2026-10-25 12:00' # a time in the local zone
343
+ node examples/nordpool-cli --utc 1993-01-02T00:00 # in UTC, or --tz=<zone>
344
+ node examples/nordpool-cli day 12350 # first and last second
345
+ node examples/nordpool-cli describe hour 25 # with what it belongs to
346
+ node examples/nordpool-cli --json describe hour 25 # every instant in UTC, market, local and --tz time
347
+ ```
348
+
349
+ A timestamp with a `Z` or `±HH:MM` suffix carries its own zone, and unix
350
+ seconds are accepted as they are. Hour 25 with times shown in market
351
+ time:
352
+
353
+ ```
354
+ $ node examples/nordpool-cli --tz=CET describe hour 25
355
+ Hour 25 (times in CET (tz))
356
+ uri tr-period-calc://25?epoch=725842800&length=3600
357
+ first 1993-01-02 01:00:00 725932800
358
+ last 1993-01-02 01:59:59 725936399
359
+ length 3600 s
360
+ day 1 1993-01-02 00:00:00 – 1993-01-02 23:59:59
361
+ quarters 100 – 103 (4)
362
+ on each country's clock
363
+ Germany Europe/Berlin 1993-01-02 01:00:00 – 1993-01-02 01:59:59
364
+ France Europe/Paris 1993-01-02 01:00:00 – 1993-01-02 01:59:59
365
+ Norway Europe/Oslo 1993-01-02 01:00:00 – 1993-01-02 01:59:59
366
+ Sweden Europe/Stockholm 1993-01-02 01:00:00 – 1993-01-02 01:59:59
367
+ Denmark Europe/Copenhagen 1993-01-02 01:00:00 – 1993-01-02 01:59:59
368
+ Netherlands Europe/Amsterdam 1993-01-02 01:00:00 – 1993-01-02 01:59:59
369
+ Belgium Europe/Brussels 1993-01-02 01:00:00 – 1993-01-02 01:59:59
370
+ Austria Europe/Vienna 1993-01-02 01:00:00 – 1993-01-02 01:59:59
371
+ Luxembourg Europe/Luxembourg 1993-01-02 01:00:00 – 1993-01-02 01:59:59
372
+ Poland Europe/Warsaw 1993-01-02 01:00:00 – 1993-01-02 01:59:59
373
+ Finland Europe/Helsinki 1993-01-02 02:00:00 – 1993-01-02 02:59:59
374
+ Estonia Europe/Tallinn 1993-01-02 02:00:00 – 1993-01-02 02:59:59
375
+ Latvia Europe/Riga 1993-01-02 02:00:00 – 1993-01-02 02:59:59
376
+ Lithuania Europe/Vilnius 1993-01-02 02:00:00 – 1993-01-02 02:59:59
377
+ Ireland Europe/Dublin 1993-01-02 00:00:00 – 1993-01-02 00:59:59
378
+ Portugal Europe/Lisbon 1993-01-02 01:00:00 – 1993-01-02 01:59:59
379
+ ```
380
+
381
+ The day DST ends in 2026 has 25 hours and 100 quarters:
382
+
383
+ ```
384
+ $ node examples/nordpool-cli --tz=CET describe day 12350
385
+ Day 12350 (times in CET (tz))
386
+ uri tr-period-calc://12350?epoch=1993-01-01T00:00:00&length=day&tz=CET
387
+ first 2026-10-25 00:00:00 1792879200
388
+ last 2026-10-25 23:59:59 1792969199
389
+ length 90000 s (25 h)
390
+ hours 296399 – 296423 (25)
391
+ quarters 1185596 – 1185695 (100)
392
+ on each country's clock
393
+ ...
394
+ ```
395
+
396
+ ## Performance
397
+
398
+ Fixed-spec lookups are integer arithmetic and cost a fraction of a
399
+ microsecond. Calendar-spec lookups go through `Intl.DateTimeFormat` a
400
+ dozen or so times and cost on the order of ten microseconds each; the
401
+ formatters are cached per zone. Constructing a calculator from a URI is
402
+ about a microsecond, so there is no need to cache calculators.
403
+
404
+ ## Errors
405
+
406
+ All errors are plain `Error` with one of the messages `Invalid spec`,
407
+ `Invalid URI`, `Invalid time zone`, `Invalid time`, `Invalid index`,
408
+ `Invalid datetime` or `Spec mismatch`. Inputs are validated strictly
409
+ and never coerced, except that time arguments accept a `Date` and
410
+ fractional seconds, and the constructor accepts numeric strings for the
411
+ fields a URI carries as strings.
412
+
413
+ ## Relation to `periodCalculator.js`
414
+
415
+ This package supersedes `periodCalculator.js`, an earlier set of
416
+ standalone functions kept in the source repository for reference.
417
+ Period indexes and starts are identical for every spec both accept, and
418
+ the test suite runs the legacy code side by side to keep it so. The
419
+ differences are deliberate:
420
+
421
+ - Periods are always contiguous. The legacy `last` came from separate
422
+ wall-clock arithmetic and left a one-hour gap in zones whose DST
423
+ change falls exactly on the period boundary time.
424
+ - A time whose wall-clock reading contradicts the period boundaries
425
+ (possible only with an epoch time-of-day inside a DST transition) is
426
+ assigned by the boundaries.
427
+ - Monthly periods from the 29th to 31st and yearly periods from February
428
+ 29 are constrained to the last day of shorter months instead of
429
+ overflowing into the following month.
430
+ - A time zone together with a fixed-length spec and a unix-second epoch
431
+ is an error instead of being ignored.
432
+ - The zone is looked up through `Intl.DateTimeFormat` instead of
433
+ rewriting `process.env.TZ`, which was process-global.
434
+
435
+ # Author
436
+
437
+ Timo J. Rinne <tri@iki.fi> — https://github.com/rinne/
438
+
439
+ # Copyright
440
+
441
+ Copyright © 2026 Timo J. Rinne <tri@iki.fi>.
442
+ See `COPYING` for the full MIT license text.
443
+
444
+ # License
445
+
446
+ MIT License
package/package.json CHANGED
@@ -1,6 +1,46 @@
1
1
  {
2
- "name": "tr-period-calc",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
2
+ "name": "tr-period-calc",
3
+ "version": "1.0.0",
4
+ "description": "Canonical sequential period indexing: fixed-length unix-time periods and calendar periods (day, week, month, year) in IANA time zones, with a self-contained URI form",
5
+ "main": "period-calc.js",
6
+ "files": [
7
+ "period-calc.js",
8
+ "COPYING",
9
+ "CHANGELOG.md"
10
+ ],
11
+ "scripts": {
12
+ "test": "node --test test/*.test.js"
13
+ },
14
+ "engines": {
15
+ "node": ">=24.0.0"
16
+ },
17
+ "repository": {
18
+ "type": "git",
19
+ "url": "git+https://github.com/rinne/node-tr-period-calc.git"
20
+ },
21
+ "keywords": [
22
+ "period",
23
+ "interval",
24
+ "bucket",
25
+ "epoch",
26
+ "unix-time",
27
+ "calendar",
28
+ "timezone",
29
+ "dst",
30
+ "statistics",
31
+ "uri"
32
+ ],
33
+ "author": {
34
+ "name": "Timo J. Rinne",
35
+ "email": "tri@iki.fi",
36
+ "url": "https://github.com/rinne/"
37
+ },
38
+ "license": "MIT",
39
+ "bugs": {
40
+ "url": "https://github.com/rinne/node-tr-period-calc/issues"
41
+ },
42
+ "homepage": "https://github.com/rinne/node-tr-period-calc#readme",
43
+ "devDependencies": {
44
+ "optist": "^2.0.1"
45
+ }
46
+ }
package/period-calc.js ADDED
@@ -0,0 +1,700 @@
1
+ 'use strict';
2
+
3
+ // tr-period-calc — canonical sequential period indexing.
4
+ //
5
+ // A period spec is one of two kinds:
6
+ //
7
+ // fixed: epoch (unix seconds) and length (seconds). Pure unix-time
8
+ // arithmetic; index = floor((t - epoch) / length). Boundaries
9
+ // never drift: 15-minute periods anchored at 12:00:00Z stay at
10
+ // *:00, *:15, *:30, *:45 UTC forever.
11
+ // calendar: epoch (local date-time), length (N × day|week|month|year)
12
+ // and an IANA time zone. Boundaries follow the local clock
13
+ // through DST changes and varying month lengths, so a
14
+ // "week starting Monday 08:00 in New York" is exactly that.
15
+ //
16
+ // Periods are contiguous and non-overlapping in whole unix seconds:
17
+ // period k is [first(k), first(k + 1) - 1]. Only periods lying entirely
18
+ // inside the supported range exist; every instant covered by them belongs
19
+ // to exactly one. A calendar period whose whole local span is skipped by
20
+ // the clock (Pacific/Apia lost 2011-12-30) is empty: last = first - 1.
21
+ // Period 0 starts at the epoch, negative indexes precede it.
22
+ //
23
+ // URI form, for a spec alone or for one self-contained period:
24
+ //
25
+ // tr-period-calc://?epoch=1788964903&length=600
26
+ // tr-period-calc://1231?epoch=1788964903&length=600
27
+ // tr-period-calc://?epoch=2026-01-05T08:00:00&length=week&tz=America/New_York
28
+ //
29
+ // Local wall-clock times map to instants the way legacy Date (and
30
+ // Temporal's 'compatible' disambiguation) do: a time inside a DST gap is
31
+ // pushed forward by the size of the gap, a repeated time resolves to its
32
+ // first occurrence. Month-day overflow is constrained: monthly periods
33
+ // from the 31st start on the last day of shorter months, yearly periods
34
+ // from Feb 29 start on Feb 28 in common years.
35
+
36
+ const SCHEME = 'tr-period-calc';
37
+
38
+ // Supported instants: 1000-01-01T00:00:00Z .. 9999-12-31T23:59:59Z.
39
+ const MIN_TIME = -30610224000;
40
+ const MAX_TIME = 253402300799;
41
+
42
+ const DAY = 86400;
43
+
44
+ // Calendar units are stepped either in days or in months.
45
+ const calendarUnits = {
46
+ day: { days: 1 },
47
+ week: { days: 7 },
48
+ month: { months: 1 },
49
+ year: { months: 12 }
50
+ };
51
+
52
+ // Accepted spec object forms: the current one and the two legacy forms
53
+ // of periodCalculator.js, mapped onto { epoch, length, timeZone }.
54
+ const specForms = [
55
+ { epoch: 'epoch', length: 'length', timeZone: 'timeZone' },
56
+ { epoch: 'periodEpoch', length: 'periodLength', timeZone: 'timeZone' },
57
+ { epoch: 'calendarEpoch', length: 'calendarPeriodLength', timeZone: 'timeZone' }
58
+ ];
59
+
60
+ const uriParams = new Map([ [ 'epoch', 'epoch' ], [ 'length', 'length' ], [ 'tz', 'timeZone' ] ]);
61
+
62
+ const uriRe = /^([A-Za-z][A-Za-z0-9+.-]*):\/\/([^/?#]*)\/?\?([^#]*)$/;
63
+ const integerRe = /^(?:0|-?[1-9]\d*)$/;
64
+ const dateTimeRe = /^(\d{4})-(\d{2})-(\d{2})(?:[T ](\d{2}):(\d{2})(?::(\d{2}))?)?$/;
65
+ const calendarLengthRe = /^([1-9]\d*)?(day|week|month|year)$/;
66
+
67
+ // ---- time zones ----
68
+
69
+ // Case-folded IANA names known to Intl, mapped to their listed spelling.
70
+ // Underscores, dashes and spaces are folded so that 'america/new york'
71
+ // finds America/New_York.
72
+ const tzListed = new Map();
73
+ for (const tz of Intl.supportedValuesOf('timeZone')) {
74
+ tzListed.set(tzFold(tz), tz);
75
+ }
76
+
77
+ const tzFormatters = new Map();
78
+
79
+ function tzFold(s) {
80
+ return s.toLowerCase().replace(/[_\s-]+/g, ' ');
81
+ }
82
+
83
+ // Returns the canonical name or undefined. Names on the Intl list get
84
+ // their listed spelling; other names Intl accepts (links such as
85
+ // US/Eastern, or spellings newer than the local ICU) are kept as given,
86
+ // so the spec never depends on which alias the local ICU prefers.
87
+ function timeZoneNormalize(timeZone) {
88
+ if ((timeZone === undefined) || (timeZone === null)) {
89
+ return 'UTC';
90
+ }
91
+ if (! (typeof(timeZone) === 'string')) {
92
+ return undefined;
93
+ }
94
+ if (timeZone.toUpperCase() === 'UTC') {
95
+ return 'UTC';
96
+ }
97
+ const listed = tzListed.get(tzFold(timeZone));
98
+ if (listed) {
99
+ return listed;
100
+ }
101
+ let resolved;
102
+ try {
103
+ resolved = new Intl.DateTimeFormat('en-US', { timeZone }).resolvedOptions().timeZone;
104
+ } catch (_) {
105
+ return undefined;
106
+ }
107
+ return ((resolved === 'UTC') ? 'UTC' : timeZone);
108
+ }
109
+
110
+ function tzFormatter(timeZone) {
111
+ let f = tzFormatters.get(timeZone);
112
+ if (! f) {
113
+ f = new Intl.DateTimeFormat('en-US', { timeZone,
114
+ hourCycle: 'h23',
115
+ year: 'numeric',
116
+ month: 'numeric',
117
+ day: 'numeric',
118
+ hour: 'numeric',
119
+ minute: 'numeric',
120
+ second: 'numeric' });
121
+ tzFormatters.set(timeZone, f);
122
+ }
123
+ return f;
124
+ }
125
+
126
+ // ---- dates ----
127
+
128
+ function isLeapYear(y) {
129
+ return ((((y % 4) === 0) && ((y % 100) !== 0)) || ((y % 400) === 0));
130
+ }
131
+
132
+ function daysInMonth(y, m) {
133
+ return [ 31, (isLeapYear(y) ? 29 : 28), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ][m - 1];
134
+ }
135
+
136
+ function legalDate(y, m, d) {
137
+ return (Number.isSafeInteger(y) && (y >= 1000) && (y <= 9999) &&
138
+ Number.isSafeInteger(m) && (m >= 1) && (m <= 12) &&
139
+ Number.isSafeInteger(d) && (d >= 1) && (d <= daysInMonth(y, m)));
140
+ }
141
+
142
+ function legalTime(h, m, s) {
143
+ return (Number.isSafeInteger(h) && (h >= 0) && (h <= 23) &&
144
+ Number.isSafeInteger(m) && (m >= 0) && (m <= 59) &&
145
+ Number.isSafeInteger(s) && (s >= 0) && (s <= 59));
146
+ }
147
+
148
+ function pad(n, w) {
149
+ return n.toString().padStart(w, '0');
150
+ }
151
+
152
+ function dateStr(f) {
153
+ return (pad(f.year, 4) + '-' + pad(f.month, 2) + '-' + pad(f.day, 2));
154
+ }
155
+
156
+ function timeStr(f) {
157
+ return (pad(f.hour, 2) + ':' + pad(f.minute, 2) + ':' + pad(f.second, 2));
158
+ }
159
+
160
+ function dateTimeStr(f) {
161
+ return (dateStr(f) + 'T' + timeStr(f));
162
+ }
163
+
164
+ // 'YYYY-MM-DD', 'YYYY-MM-DD HH:MM', 'YYYY-MM-DDTHH:MM:SS' (space or T)
165
+ // to wall-clock fields, or undefined.
166
+ function dateTimeFields(s) {
167
+ if (! (typeof(s) === 'string')) {
168
+ return undefined;
169
+ }
170
+ const m = s.match(dateTimeRe);
171
+ if (! m) {
172
+ return undefined;
173
+ }
174
+ const f = { year: Number(m[1]),
175
+ month: Number(m[2]),
176
+ day: Number(m[3]),
177
+ hour: Number(m[4] ?? '0'),
178
+ minute: Number(m[5] ?? '0'),
179
+ second: Number(m[6] ?? '0') };
180
+ return ((legalDate(f.year, f.month, f.day) && legalTime(f.hour, f.minute, f.second)) ? f : undefined);
181
+ }
182
+
183
+ // Wall-clock fields as if they were UTC, in ms. Years below 100 must
184
+ // never reach here (Date.UTC would remap them).
185
+ function wallMs(f) {
186
+ return Date.UTC(f.year, f.month - 1, f.day, f.hour, f.minute, f.second);
187
+ }
188
+
189
+ function inRange(t) {
190
+ return (Number.isSafeInteger(t) && (t >= MIN_TIME) && (t <= MAX_TIME));
191
+ }
192
+
193
+ // ---- instant <-> local wall clock ----
194
+
195
+ // Local wall-clock fields of an instant (unix seconds) in a zone, with
196
+ // weekday (0 = Sunday) and the zone offset in seconds east of UTC.
197
+ function localFields(time, timeZone) {
198
+ if (timeZone === 'UTC') {
199
+ const d = new Date(time * 1000);
200
+ return { year: d.getUTCFullYear(),
201
+ month: d.getUTCMonth() + 1,
202
+ day: d.getUTCDate(),
203
+ hour: d.getUTCHours(),
204
+ minute: d.getUTCMinutes(),
205
+ second: d.getUTCSeconds(),
206
+ weekday: d.getUTCDay(),
207
+ offset: 0 };
208
+ }
209
+ const v = {};
210
+ for (const p of tzFormatter(timeZone).formatToParts(new Date(time * 1000))) {
211
+ v[p.type] = p.value;
212
+ }
213
+ const f = { year: Number(v.year),
214
+ month: Number(v.month),
215
+ day: Number(v.day),
216
+ hour: Number(v.hour) % 24,
217
+ minute: Number(v.minute),
218
+ second: Number(v.second) };
219
+ const wall = wallMs(f);
220
+ f.weekday = new Date(wall).getUTCDay();
221
+ f.offset = Math.round(wall / 1000) - time;
222
+ return f;
223
+ }
224
+
225
+ // Wall-clock (ms, as if UTC) in a zone to the instant in unix seconds.
226
+ // Candidates are formed with the offsets in force a day before and a day
227
+ // after; the one that maps back to the wall time wins, the earlier one
228
+ // first (a repeated hour resolves to its first occurrence). A wall time
229
+ // that maps back with neither is inside a gap: the offset from before
230
+ // the transition is applied, pushing the time forward by the gap.
231
+ function wallToTime(wall, timeZone) {
232
+ const w = wall / 1000;
233
+ if (timeZone === 'UTC') {
234
+ return w;
235
+ }
236
+ const before = localFields(w - DAY, timeZone).offset;
237
+ const after = localFields(w + DAY, timeZone).offset;
238
+ if (localFields(w - before, timeZone).offset === before) {
239
+ return (w - before);
240
+ }
241
+ if (localFields(w - after, timeZone).offset === after) {
242
+ return (w - after);
243
+ }
244
+ return (w - before);
245
+ }
246
+
247
+ // ---- input parsing ----
248
+
249
+ // A time argument: unix seconds (number, fractions floored), a Date, or
250
+ // nullish for now. Returns unix seconds or undefined.
251
+ function timeParse(time) {
252
+ let t;
253
+ if ((time === undefined) || (time === null)) {
254
+ t = Math.floor(Date.now() / 1000);
255
+ } else if (time instanceof Date) {
256
+ t = Math.floor(time.getTime() / 1000);
257
+ } else if (typeof(time) === 'number') {
258
+ t = Math.floor(time);
259
+ }
260
+ return (inRange(t) ? t : undefined);
261
+ }
262
+
263
+ // Epoch input: unix seconds as a number, a numeric string or a Date, or
264
+ // a local date-time string. Returns { time } or { fields }, or undefined.
265
+ function epochParse(epoch) {
266
+ if (epoch instanceof Date) {
267
+ const t = Math.floor(epoch.getTime() / 1000);
268
+ return (Number.isSafeInteger(t) ? { time: t } : undefined);
269
+ }
270
+ if (typeof(epoch) === 'number') {
271
+ return (Number.isSafeInteger(epoch) ? { time: epoch } : undefined);
272
+ }
273
+ if (typeof(epoch) === 'string') {
274
+ if (integerRe.test(epoch)) {
275
+ const t = Number(epoch);
276
+ return (Number.isSafeInteger(t) ? { time: t } : undefined);
277
+ }
278
+ const fields = dateTimeFields(epoch);
279
+ return (fields ? { fields } : undefined);
280
+ }
281
+ return undefined;
282
+ }
283
+
284
+ // Length input: seconds as a number or numeric string (fixed), or
285
+ // '[N]day|week|month|year' (calendar). Returns { seconds } or
286
+ // { unit, count }, or undefined.
287
+ function lengthParse(length) {
288
+ if (typeof(length) === 'number') {
289
+ return ((Number.isSafeInteger(length) && (length > 0)) ? { seconds: length } : undefined);
290
+ }
291
+ if (typeof(length) === 'string') {
292
+ if (integerRe.test(length)) {
293
+ const n = Number(length);
294
+ return ((Number.isSafeInteger(n) && (n > 0)) ? { seconds: n } : undefined);
295
+ }
296
+ const m = length.match(calendarLengthRe);
297
+ if (m) {
298
+ const count = (m[1] === undefined) ? 1 : Number(m[1]);
299
+ return (Number.isSafeInteger(count) ? { unit: m[2], count } : undefined);
300
+ }
301
+ }
302
+ return undefined;
303
+ }
304
+
305
+ function isPlainObject(x) {
306
+ return ((typeof(x) === 'object') && (x !== null) && ! Array.isArray(x));
307
+ }
308
+
309
+ // A spec object in any accepted form to { epoch, length, timeZone }.
310
+ // Keys with undefined values count as absent; other unknown keys are
311
+ // rejected rather than silently ignored.
312
+ function specFromObject(o) {
313
+ const keys = Object.keys(o).filter((k) => (o[k] !== undefined));
314
+ for (const form of specForms) {
315
+ const known = Object.values(form);
316
+ if (keys.every((k) => known.includes(k)) && keys.includes(form.epoch) && keys.includes(form.length)) {
317
+ return { epoch: o[form.epoch], length: o[form.length], timeZone: o[form.timeZone] };
318
+ }
319
+ }
320
+ throw new Error('Invalid spec');
321
+ }
322
+
323
+ // { epoch, length, timeZone } in input form to the internal normalized
324
+ // spec.
325
+ function specNormalize(input) {
326
+ const timeZone = timeZoneNormalize(input.timeZone);
327
+ if (! timeZone) {
328
+ throw new Error('Invalid time zone');
329
+ }
330
+ const epoch = epochParse(input.epoch);
331
+ const length = lengthParse(input.length);
332
+ if (! (epoch && length)) {
333
+ throw new Error('Invalid spec');
334
+ }
335
+ if (length.seconds) {
336
+ let time;
337
+ if (epoch.fields) {
338
+ time = wallToTime(wallMs(epoch.fields), timeZone);
339
+ } else {
340
+ // A zone would have no effect on unix-time periods. Refuse it
341
+ // instead of letting the caller believe otherwise.
342
+ if (timeZone !== 'UTC') {
343
+ throw new Error('Invalid spec');
344
+ }
345
+ time = epoch.time;
346
+ }
347
+ if (! inRange(time)) {
348
+ throw new Error('Invalid spec');
349
+ }
350
+ return { type: 'fixed', epoch: time, length: length.seconds, timeZone: 'UTC' };
351
+ }
352
+ let fields;
353
+ if (epoch.fields) {
354
+ fields = epoch.fields;
355
+ } else {
356
+ if (! inRange(epoch.time)) {
357
+ throw new Error('Invalid spec');
358
+ }
359
+ fields = localFields(epoch.time, timeZone);
360
+ if (! legalDate(fields.year, fields.month, fields.day)) {
361
+ throw new Error('Invalid spec');
362
+ }
363
+ }
364
+ const step = calendarUnits[length.unit];
365
+ return { type: 'calendar',
366
+ epoch: dateTimeStr(fields),
367
+ length: ((length.count === 1) ? '' : length.count.toString()) + length.unit,
368
+ timeZone,
369
+ fields: { year: fields.year,
370
+ month: fields.month,
371
+ day: fields.day,
372
+ hour: fields.hour,
373
+ minute: fields.minute,
374
+ second: fields.second },
375
+ days: (step.days ?? 0) * length.count,
376
+ months: (step.months ?? 0) * length.count };
377
+ }
378
+
379
+ // ---- URI ----
380
+
381
+ // One query component, percent-decoded. A '+' is a literal plus, not a
382
+ // space: this is an RFC 3986 query, not a form submission.
383
+ function uriDecode(s) {
384
+ try {
385
+ return decodeURIComponent(s);
386
+ } catch (_) {
387
+ throw new Error('Invalid URI');
388
+ }
389
+ }
390
+
391
+ // Returns { index, spec } with index undefined when the URI carries none
392
+ // and spec in input form (strings).
393
+ function uriParse(uri) {
394
+ const m = ((typeof(uri) === 'string') ? uri.match(uriRe) : null);
395
+ if (! (m && (m[1].toLowerCase() === SCHEME))) {
396
+ throw new Error('Invalid URI');
397
+ }
398
+ let index;
399
+ if (m[2] !== '') {
400
+ index = (integerRe.test(m[2]) ? Number(m[2]) : undefined);
401
+ if (! Number.isSafeInteger(index)) {
402
+ throw new Error('Invalid URI');
403
+ }
404
+ }
405
+ const spec = {};
406
+ for (const param of m[3].split('&')) {
407
+ if (param === '') {
408
+ continue;
409
+ }
410
+ const eq = param.indexOf('=');
411
+ if (eq < 0) {
412
+ throw new Error('Invalid URI');
413
+ }
414
+ const name = uriParams.get(uriDecode(param.slice(0, eq)));
415
+ if (! (name && ! (name in spec))) {
416
+ throw new Error('Invalid URI');
417
+ }
418
+ spec[name] = uriDecode(param.slice(eq + 1));
419
+ }
420
+ if (! (('epoch' in spec) && ('length' in spec))) {
421
+ throw new Error('Invalid URI');
422
+ }
423
+ return { index, spec };
424
+ }
425
+
426
+ function uriBuild(spec, index) {
427
+ let s = SCHEME + '://' + ((index === undefined) ? '' : index.toString()) +
428
+ '?epoch=' + spec.epoch + '&length=' + spec.length;
429
+ if (spec.timeZone !== 'UTC') {
430
+ s += '&tz=' + encodeURIComponent(spec.timeZone).replace(/%2F/gi, '/');
431
+ }
432
+ return s;
433
+ }
434
+
435
+ // ---- the calculator ----
436
+
437
+ class PeriodCalc {
438
+
439
+ #spec;
440
+ #public;
441
+ #uri;
442
+
443
+ // spec: a spec URI (an index in it is ignored), a spec object in the
444
+ // current or a legacy form, or another PeriodCalc.
445
+ constructor(spec) {
446
+ let input;
447
+ if (spec instanceof PeriodCalc) {
448
+ input = spec.spec;
449
+ } else if (typeof(spec) === 'string') {
450
+ input = uriParse(spec).spec;
451
+ } else if (isPlainObject(spec)) {
452
+ input = specFromObject(spec);
453
+ } else {
454
+ throw new Error('Invalid spec');
455
+ }
456
+ this.#spec = specNormalize(input);
457
+ this.#public = Object.freeze({ epoch: this.#spec.epoch,
458
+ length: this.#spec.length,
459
+ timeZone: this.#spec.timeZone });
460
+ this.#uri = uriBuild(this.#public);
461
+ }
462
+
463
+ get spec() {
464
+ return this.#public;
465
+ }
466
+
467
+ get uri() {
468
+ return this.#uri;
469
+ }
470
+
471
+ get type() {
472
+ return this.#spec.type;
473
+ }
474
+
475
+ toString() {
476
+ return this.#uri;
477
+ }
478
+
479
+ toJSON() {
480
+ return this.#uri;
481
+ }
482
+
483
+ equals(other) {
484
+ const o = ((other instanceof PeriodCalc) ? other : new PeriodCalc(other));
485
+ return (o.uri === this.#uri);
486
+ }
487
+
488
+ byIndex(index) {
489
+ if (! Number.isSafeInteger(index)) {
490
+ throw new Error('Invalid index');
491
+ }
492
+ const first = this.#first(index);
493
+ const next = this.#first(index + 1);
494
+ if (! ((first !== undefined) && (first <= MAX_TIME) && (next !== undefined))) {
495
+ throw new Error('Invalid index');
496
+ }
497
+ return this.#period(index, first, next - 1);
498
+ }
499
+
500
+ byTime(time) {
501
+ const t = timeParse(time);
502
+ if (t === undefined) {
503
+ throw new Error('Invalid time');
504
+ }
505
+ let k = this.#estimate(t);
506
+ let first = this.#first(k);
507
+ let next = this.#first(k + 1);
508
+ // The estimate is exact for fixed periods and within one of the
509
+ // truth for calendar periods; make it agree with the boundaries.
510
+ if ((first !== undefined) && (t < first)) {
511
+ k -= 1;
512
+ next = first;
513
+ first = this.#first(k);
514
+ } else if ((next !== undefined) && (t >= next)) {
515
+ k += 1;
516
+ first = next;
517
+ next = this.#first(k + 1);
518
+ }
519
+ if (! ((first !== undefined) && (next !== undefined) && (t >= first) && (t < next))) {
520
+ throw new Error('Invalid time');
521
+ }
522
+ return this.#period(k, first, next - 1);
523
+ }
524
+
525
+ byDateTime(dateTime, timeZone) {
526
+ return this.byTime(PeriodCalc.parseDateTime(dateTime, timeZone ?? this.#spec.timeZone));
527
+ }
528
+
529
+ byUri(uri) {
530
+ const { index, spec } = uriParse(uri);
531
+ if (index === undefined) {
532
+ throw new Error('Invalid URI');
533
+ }
534
+ if (! this.equals(spec)) {
535
+ throw new Error('Spec mismatch');
536
+ }
537
+ return this.byIndex(index);
538
+ }
539
+
540
+ // All periods from the one containing `from` to the one containing
541
+ // `to`, inclusive, in order.
542
+ range(from, to) {
543
+ const a = this.byTime(from);
544
+ const b = this.byTime(to);
545
+ if (b.index < a.index) {
546
+ throw new Error('Invalid time');
547
+ }
548
+ const r = [];
549
+ let first = a.first;
550
+ for (let k = a.index; k <= b.index; k++) {
551
+ const next = ((k === b.index) ? (b.last + 1) : this.#first(k + 1));
552
+ r.push(this.#period(k, first, next - 1));
553
+ first = next;
554
+ }
555
+ return r;
556
+ }
557
+
558
+ localTime(time, timeZone) {
559
+ return PeriodCalc.localTime(time, timeZone ?? this.#spec.timeZone);
560
+ }
561
+
562
+ parseDateTime(dateTime, timeZone) {
563
+ return PeriodCalc.parseDateTime(dateTime, timeZone ?? this.#spec.timeZone);
564
+ }
565
+
566
+ static parseUri(uri) {
567
+ const { index, spec } = uriParse(uri);
568
+ return { index, spec: new PeriodCalc(spec).spec };
569
+ }
570
+
571
+ static periodByUri(uri) {
572
+ const { index, spec } = uriParse(uri);
573
+ if (index === undefined) {
574
+ throw new Error('Invalid URI');
575
+ }
576
+ return new PeriodCalc(spec).byIndex(index);
577
+ }
578
+
579
+ // Local wall-clock view of an instant. `time` as in byTime (nullish
580
+ // for now), `timeZone` defaults to UTC.
581
+ static localTime(time, timeZone) {
582
+ const tz = timeZoneNormalize(timeZone);
583
+ if (! tz) {
584
+ throw new Error('Invalid time zone');
585
+ }
586
+ const t = timeParse(time);
587
+ if (t === undefined) {
588
+ throw new Error('Invalid time');
589
+ }
590
+ const f = localFields(t, tz);
591
+ return { time: t,
592
+ timeZone: tz,
593
+ year: f.year,
594
+ month: f.month,
595
+ day: f.day,
596
+ hour: f.hour,
597
+ minute: f.minute,
598
+ second: f.second,
599
+ weekday: f.weekday,
600
+ offset: f.offset,
601
+ dateStr: dateStr(f),
602
+ timeStr: timeStr(f),
603
+ dateTimeStr: dateTimeStr(f) };
604
+ }
605
+
606
+ // 'YYYY-MM-DD[(T| )HH:MM[:SS]]' in a zone (default UTC) to unix seconds.
607
+ static parseDateTime(dateTime, timeZone) {
608
+ const tz = timeZoneNormalize(timeZone);
609
+ if (! tz) {
610
+ throw new Error('Invalid time zone');
611
+ }
612
+ const f = dateTimeFields(dateTime);
613
+ if (! f) {
614
+ throw new Error('Invalid datetime');
615
+ }
616
+ const t = wallToTime(wallMs(f), tz);
617
+ if (! inRange(t)) {
618
+ throw new Error('Invalid datetime');
619
+ }
620
+ return t;
621
+ }
622
+
623
+ static normalizeTimeZone(timeZone) {
624
+ const tz = timeZoneNormalize(timeZone);
625
+ if (! tz) {
626
+ throw new Error('Invalid time zone');
627
+ }
628
+ return tz;
629
+ }
630
+
631
+ // Start of period `index` in unix seconds, or undefined when it falls
632
+ // outside the supported range. One second past the range is allowed:
633
+ // it is where the last period ends.
634
+ #first(index) {
635
+ const s = this.#spec;
636
+ let t;
637
+ if (s.type === 'fixed') {
638
+ t = s.epoch + (index * s.length);
639
+ } else {
640
+ const e = s.fields;
641
+ let wall;
642
+ if (s.days) {
643
+ wall = Date.UTC(e.year, e.month - 1, e.day + (index * s.days), e.hour, e.minute, e.second);
644
+ } else {
645
+ const months = (e.month - 1) + (index * s.months);
646
+ const y = e.year + Math.floor(months / 12);
647
+ const m = (((months % 12) + 12) % 12) + 1;
648
+ if (! ((y >= 999) && (y <= 10000))) {
649
+ return undefined;
650
+ }
651
+ wall = Date.UTC(y, m - 1, Math.min(e.day, daysInMonth(y, m)), e.hour, e.minute, e.second);
652
+ }
653
+ if (! (Number.isFinite(wall) &&
654
+ (wall >= ((MIN_TIME - (2 * DAY)) * 1000)) &&
655
+ (wall <= ((MAX_TIME + (2 * DAY)) * 1000)))) {
656
+ return undefined;
657
+ }
658
+ t = wallToTime(wall, s.timeZone);
659
+ }
660
+ return ((Number.isSafeInteger(t) && (t >= MIN_TIME) && (t <= (MAX_TIME + 1))) ? t : undefined);
661
+ }
662
+
663
+ // Index estimate for an instant. Exact for fixed periods; for calendar
664
+ // periods it is local-clock arithmetic, off by at most one around a
665
+ // DST transition that overlaps the period boundary.
666
+ #estimate(t) {
667
+ const s = this.#spec;
668
+ if (s.type === 'fixed') {
669
+ return Math.floor((t - s.epoch) / s.length);
670
+ }
671
+ const T = localFields(t, s.timeZone);
672
+ const E = s.fields;
673
+ const tod = ((T.hour - E.hour) || (T.minute - E.minute) || (T.second - E.second));
674
+ if (s.days) {
675
+ let d = Math.round((Date.UTC(T.year, T.month - 1, T.day) - Date.UTC(E.year, E.month - 1, E.day)) / (DAY * 1000));
676
+ if (tod < 0) {
677
+ d -= 1;
678
+ }
679
+ return Math.floor(d / s.days);
680
+ }
681
+ let m = ((T.year - E.year) * 12) + (T.month - E.month);
682
+ // The epoch day constrained to the month at hand, as #first does.
683
+ const d = Math.min(E.day, daysInMonth(T.year, T.month));
684
+ if (((T.day - d) || tod) < 0) {
685
+ m -= 1;
686
+ }
687
+ return Math.floor(m / s.months);
688
+ }
689
+
690
+ #period(index, first, last) {
691
+ return Object.freeze({ index, first, last, uri: uriBuild(this.#public, index), spec: this.#public });
692
+ }
693
+
694
+ }
695
+
696
+ PeriodCalc.SCHEME = SCHEME;
697
+ PeriodCalc.MIN_TIME = MIN_TIME;
698
+ PeriodCalc.MAX_TIME = MAX_TIME;
699
+
700
+ module.exports = PeriodCalc;