Skip to content

Commit ed906d5

Browse files
feat(spec, objectql): working-calendar service, arithmetic and refusal codes (ADR-0157, part 1 of 2) (#35641)
repo:objectstack#5 · os-bill · session_01Utp6Ca1jJvsA1dHsPwMiQb Part of #35355 Clause-②: yes (widening) Metadata-protocol: none ## 维护者速读 用户能看到什么变化:系统管理员和普通用户在界面上都看不到变化(用户无感);之前平台不会按上班日算期限,之后平台内部能算,但要等配套的日历设置页一起上线才用得上。 为什么做:属于「工作日历」,替公式作者和审批流程计算“几个工作日后”“几个工作小时后”,让节假日和调休上班日都算对。 出错会怎样:若算错,按工作日计算的到期日会差一天或落在休息日,审批提醒会提前或推迟;没指明组织的计算会被直接拒绝,不会借用别的组织的日历;这一半只新增、不改旧功能,可以直接撤回。 要你做什么:无。 ## 席位核对 ### Pair and release (ADR-0157 D4) **Not released alone; pair #35641/#35642.** This is the first of two pull requests for #35355, split by layer; its pair is #35642 (the two calendar objects, Setup, import and translations), which lands right after this one. Both ship in the same release as #35356 (the working-day formula functions) and #35357 (the approval escalation's working-time clock), per ADR-0157 D4. On its own this half registers a service that refuses every resolution, because no calendar object exists until #35642 lands. ### Fix round 1 (contract review 7023325199, ruling record 7023403692) - **M1, an absent organization.** Outside the `single` tenancy posture (the engine's own reading, `resolveEnginePosture`), a computation whose `organizationId` is absent is refused `ERR_WORK_CALENDAR_UNRESOLVED` with reason `no_organization` before any read, the cache's included; `single` is unchanged. The rule is stated in the `WorkCalendarRef` jsdoc, the service header and the ADR anchor. The same rule binds the hooks' elevated reads (the one-default check and the time-zone fill), and the hooks take the organization from the session. When no posture is passed, the service and the hooks read the posture of the engine they run on, so SecurityPlugin's injected posture is the one in force. - **S1, where the arithmetic lives.** The period parser, `buildWorkCalendar`, the four counts, `isWorkingDay`, `workingPeriodsOn`, `exceptionDayOf`, `calendarDayOf` and the three error classes move to `@objectstack/formula` (`packages/formula/src/work-calendar.ts`). The edge already existed: `@objectstack/objectql` and `plugin-approvals` depend on formula, and formula depends on spec, so no dependency edge is new. Spec keeps `zonedWallClockToUtcMs`, the types, the constants and the ledger codes, and its module header now states Prime Directive #2 as schemas, types and constants only. The gantt's two ALLOW entries in `ui/scripts/check-spec-symbol-derivation.mjs` are dropped, since spec no longer exports those names; that file is back to its `main` bytes. - **S2, the contract.** `IWorkCalendarService`, `WorkCalendarRef` and `WORK_CALENDAR_SERVICE` are in `packages/spec/src/contracts/work-calendar-service.ts`, beside the other service contracts. The objectql class keeps its name and `implements IWorkCalendarService`. - **N1.** The 60-day lead's jsdoc says the next year's holidays are usually published around or after November, and makes no claim about the date. - **N2.** #35642 is named by number here and in the changeset, both with "Not released alone; pair #35641/#35642". - **N3.** `buildWorkCalendar` returns a frozen calendar (the calendar, the weekly lists, every period, the exceptions and each day), so a cached calendar answers every caller alike. - **The ledger entry.** It stays under `@objectstack/spec`. The three code constants stay in spec, and `check:error-code-provenance` attributes a code to the package whose constant spells it. Formula's error classes stamp it by reference. - **Semver.** Spec stays `patch` (`Metadata-protocol: none`); `@objectstack/formula` is added to the changeset as `patch`. ### Main merge and fix round 2 (contract delta 7026479156, PASS with S3; seat ruling: refuse) - `28fca759a9` merges `main` (`03865ae995`, K=25); the merge regenerates `api-surface/data.json` and `export-origins/data.json` and carries no hand edit (contract delta 7026479156). - `f502d9238c` (S3): the calendar insert hook refuses a create whose row names an organization other than the session's and sets `is_default: true`, before any read, with `400 VALIDATION_FAILED` (`is_default`, `invalid_value`) and a reason that says how to proceed. A mismatched create without a default passes as before. The module header says a future seed that sets a default loads pinned to its organization or sets it by an update. Pins: the member and system-writer cases now assert the refusal, with a CONTROL for a plain create and a new pin for the update route; ablation 3 red / 21 green, restored. `@objectstack/objectql` (`--project local`) at `f502d9238c`: 617 files, 13947 tests passed. 2204 lines against `main`. ### Comments read (through 7023325199) - **7021287976, the docs drift check.** No hand-written page under `content/docs`, `skills` or `docs` (ADRs aside) names the moved names: `git grep` for the arithmetic, the service, the contract constant and `zonedWallClockToUtcMs` finds none. The reference pages are generated, and `check:docs` passes. - **7022981176, L1-a.** - R1, the claim line for the ui script, is moot: that file is back to its `main` bytes. - Observations 1 to 3 were ruled in 7023403692 and are carried out above: semver stays `patch`, M1, and the pair sentence. - **7023325199, the contract review.** M1, S1, S2 and N1 to N3 are answered item by item in the fix-round section above. ### What changes - **Arithmetic**: `packages/formula/src/work-calendar.ts` (new). `isWorkingTime`, `addWorkingDays`, `workingDaysBetween` and `addWorkingHours` are pure functions over a resolved calendar, so #35356 can call them synchronously. `parseWorkPeriods` enforces D7 and D10: a period crossing midnight is refused, `24:00` is a legal end, and overlapping or malformed text is refused. `buildWorkCalendar` validates a stored row and its exceptions, and builds frozen. - **Types, constants and the time-zone rule**: `packages/spec/src/data/work-calendar.ts` and `wall-clock.ts`. `zonedWallClockToUtcMs`, `wallClockToUtcMs` and `WallClockParts` move from `@objectstack/core` byte-identical, and core re-exports all three (D11). - **Ledger codes**: `ERR_WORK_CALENDAR_UNRESOLVED`, `ERR_WORK_CALENDAR_NOT_MAINTAINED` and `ERR_WORK_CALENDAR_INVALID`, each a 400. - **Service**: `packages/objectql/src/work-calendar-service.ts`, registered as `work-calendar` from the ObjectQL plugin. Under D2 it takes the named code, else the organization default, else refuses, and never falls back to wall-clock time. It reads elevated in the named organization, refuses an absent one outside `single`, caches with a 60 s TTL, drops the cache on any calendar or exception write, and never caches a refusal. - **Write door**: hooks on both objects, bound by name and inert until #35642 registers the objects. Each of the following is refused `400 VALIDATION_FAILED` with an ADR-0114 field code: a period crossing midnight, a malformed or overlapping period, `off` with periods, `on` without, `maintained_through` before `maintained_from`, and a second default. A create placed in an organization other than the session's that sets Default is refused before any read; set the default by an update, which is judged in the stored row's organization. A create without `timezone` takes the organization's Localization zone. The hooks take the organization from the session. ### Service API for #35356 and #35357 - **Contract**, `@objectstack/spec/contracts`: - `IWorkCalendarService`: `resolve(ref)`, `isWorkingTime(ref, at)`, `addWorkingDays(ref, day, days)`, `workingDaysBetween(ref, start, end)` (start excluded, end included), `addWorkingHours(ref, start, hours)` (returns epoch ms) and `invalidate()`. - `ref` is `WorkCalendarRef`, `{ organizationId, calendar? }`. - The service registers under `WORK_CALENDAR_SERVICE` (`work-calendar`); the implementation is `WorkCalendarService` in `@objectstack/objectql`. - **Sync**, `@objectstack/formula`: the same four computations taking a resolved `WorkCalendar` first, plus `buildWorkCalendar`, `parseWorkPeriods`, `isWorkingDay` and `workingPeriodsOn`. The conversion is `zonedWallClockToUtcMs` from `@objectstack/spec/data`. - **Refusals**, `@objectstack/formula`: - `WorkCalendarUnresolvedError`, with reason `not_found`, `no_default`, `ambiguous` or `no_organization`. - `WorkCalendarNotMaintainedError` and `WorkCalendarInvalidError`. - `isWorkCalendarRefusal`. - The codes are `@objectstack/spec/data` constants. ### Tests Head `e8af402891`. Each run below went through `os-verify-lock` and read VERDICT `command-exit 0`. Commands are `--maxWorkers=2`. `--project local` is the package's own `test` script. - Builds: `@objectstack/objectql` plus its dependency closure; spec, formula and core among them. - Typecheck, exit 0: spec, formula, objectql and core. - `@objectstack/formula`: 69 test files and 1902 tests passed. - `@objectstack/objectql` (`--project local`): 617 test files and 13941 tests passed. - `@objectstack/spec` (`--project local`): 857 test files and 27394 tests passed, with 1 todo. This was after `check:generated --fix` rewrote and re-checked `api-surface/` and `export-origins/`. - `pnpm --dir ui run check:spec-symbols`: exit 0, with 0 untriaged collisions after the ALLOW entries were dropped. New pins this round (`packages/objectql/src/work-calendar-service.test.ts`, 23 tests; `packages/formula/src/work-calendar.test.ts`, 14 tests): - **The service, under `isolated` and under `group`.** A named code held only by another organization is refused `no_organization`, and so is a default held only by another organization. An empty-string organization is refused the same way, and so is `addWorkingDays`. Each refusal reaches HTTP as 400 `ERR_WORK_CALENDAR_UNRESOLVED`, with zero engine reads. CONTROL: naming the holding organization resolves it. - **The service, under `single`.** A computation without an organization still reads, unscoped. - **The posture source.** When none is passed, the service reads the engine's injected posture. - **The hooks take the organization from the session.** This runs under `single` and under `isolated`, with a CONTROL showing the session's own organization is read and judged. A system writer reads in its session's organization too. - **No organization, outside `single`.** Under `isolated`, an insert and an update that name no organization read nothing. CONTROL: under `single` the same writes are judged. - **The frozen calendar.** The built calendar is frozen down to its periods. The double scopes each read by its context's tenant, as the engine does. Ablations, one per new mechanism, through `scripts/ablation-replace.mjs`. Every anchor went from 1 hit to 0 and every blob moved. Each restore is proven by the blob equalling HEAD and by an empty `git diff HEAD`. Subjects are imported by relative source path, so there is no dist leg. - Resolve guard off: 3 red (isolated, group, engine posture). - Session rule off: 3 red (the three session pins). - Insert hook guard off: 1 red. - Update hook guard off: 1 red. - Outer freeze off: 1 red. - Period freeze off: 1 red. ### Gates - **Derived families.** `node scripts/pm/dispatch-gates.mjs --commands` at tree `e8af402891` derives 132 families. Each ran with its exit code captured before any pipe, and all 132 exited 0. - **Reconciliation** (`--ran`, each family recorded with its exit code): `Run reconciliation — 132 derived, 132 run, 0 NOT-MEASURED, 0 UNRUN`. The zero is derived, since every family carries an exit code. - **Among them:** - Error codes: `check:error-code-provenance`, `check:error-code-casing`, `check:dispatcher-error-vocabulary`. - Generated artifacts and docs: `check:api-surface`, `check:export-origins`, `check:docs`, `check:generated`. - `check:authorable-surface`: no authorable key moved, hence `Metadata-protocol: none`. - Test doubles: `check:where-matcher`, `check:objectql-double-limit`, `check:engine-double-contract`, `check:query-options-erasure`. - `check:system-context-census`, `check:dual-build-cjs-loads`, `check:adr-anchors`, `check:nul-bytes`. - **Outside the derived list.** `node scripts/check-platform-checklist.mjs --changed-from origin/main` (exported symbols moved) exits 0, and `overlap-check` gives `VERDICT clean exit 0`. - **Two reds on the first pass at `743be6587f`, both fixed in `e8af402891`:** - `check:system-context-census` flagged a new caller-keyed branch in the insert hook. The hooks now take every writer's organization from the session, so no branch is left. - `check:where-matcher` could not lift the test double's matcher once tenant scoping shared its callback. The scoping is now a step of its own. - **CI at `e8af402891`, read once:** 58 success, 10 skipped and 1 in progress (Test Core 10/10), with no failure. Every Lint and Type Check lane, Type Check UI, Build Core, Check Changeset and the PR-body guards passed. ### Acceptance notes - The service and hooks are inert until #35642 registers the two objects. Until then, `resolve` refuses `ERR_WORK_CALENDAR_UNRESOLVED` (`not_found` or `no_default`), and the hooks bind by object name. - `main` is merged at `28fca759a9` (K=25); #35581 and #35583 shared three files with this PR (`packages/spec/api-surface/data.json`, `packages/spec/export-origins/data.json`, `packages/spec/src/data/index.ts`), and the two generated files were regenerated in the merge. - #35657 (the ADR-0157 D1 note for `maintained_from`) stays outside both PRs. ### Verification - Read first: - `packages/objectql/src/work-calendar-service.ts`: `resolve` (the no-organization guard) and `insertReadOrganization` (the hooks' organization). - `packages/formula/src/work-calendar.ts`: `addWorkingHours` and `requireMaintained`, the D8 and D11 core. - `packages/spec/src/contracts/work-calendar-service.ts`: the contract. - Two-minute check: `pnpm --filter @objectstack/objectql exec vitest run src/work-calendar-service.test.ts`. Expect 24 passed, including the `isolated` and `group` no-organization pins and the session pins. --- _Generated by [Claude Code](https://claude.ai/code/session_01Utp6Ca1jJvsA1dHsPwMiQb)_ --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 7c122ff commit ed906d5

25 files changed

Lines changed: 2065 additions & 139 deletions
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
---
2+
'@objectstack/spec': patch
3+
'@objectstack/formula': patch
4+
'@objectstack/objectql': patch
5+
'@objectstack/core': patch
6+
---
7+
8+
feat: the working-calendar service, its arithmetic and its refusal codes (ADR-0157, part one of two)
9+
10+
Clause-②: yes (widening)
11+
Metadata-protocol: none
12+
13+
Not released alone; pair #35641/#35642. This ships in the same release as #35642 (the calendar objects and Setup pages, the second half of this change), the working-day formula functions (#35356) and the approval escalation's working-time clock (#35357), ADR-0157 D4.
14+
15+
- **The arithmetic** (`@objectstack/formula`). `isWorkingTime`, `addWorkingDays`, `workingDaysBetween` and `addWorkingHours` compute over a resolved calendar and its dated exceptions, as pure functions a formula can call synchronously, beside `parseWorkPeriods` (`HH:mm-HH:mm` periods; a period that crosses midnight is refused, `24:00` is a legal end), `buildWorkCalendar` (a frozen calendar) and the three error classes. A computation that needs a date outside the calendar's maintained span is refused rather than read from the weekly pattern.
16+
- **The types, constants and time-zone rule** (`@objectstack/spec`). `WorkCalendar` and the column and code constants are in `@objectstack/spec/data`; the service contract is `IWorkCalendarService` in `@objectstack/spec/contracts`. `zonedWallClockToUtcMs`, `wallClockToUtcMs` and `WallClockParts` move to `@objectstack/spec/data` from `@objectstack/core`, unchanged; `@objectstack/core` re-exports all three, so no import changes.
17+
- **Three error codes** in the ADR-0112 ledger: `ERR_WORK_CALENDAR_UNRESOLVED` (no calendar by that code, no organization default, two defaults, or no organization named outside the `single` posture), `ERR_WORK_CALENDAR_NOT_MAINTAINED` and `ERR_WORK_CALENDAR_INVALID`, each a 400.
18+
- **The calendar service** (`@objectstack/objectql`, registered as `work-calendar`). `resolve({ organizationId, calendar })` takes the named code, else the organization default, else refuses; it never falls back to wall-clock time. It reads in the organization the caller names, elevated, and caches until a calendar or exception row is written. Outside the `single` tenancy posture, a computation that names no organization is refused before any read. Until the calendar objects are registered it refuses every resolution.
19+
- **The write door** (`@objectstack/objectql`). Once the calendar objects exist, a calendar or exception write is refused `400 VALIDATION_FAILED` when a period crosses midnight, is malformed or overlaps another, an `off` row carries periods or an `on` row carries none, `maintained_through` is before `maintained_from`, a second calendar is marked the default, or a calendar created in an organization other than the one being worked in is marked the default (create it there, or set the default by an update); a calendar created without `timezone` takes the organization's Localization time zone. The hooks take the organization from the session.

‎content/docs/references/api/automation-api.mdx‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -424,7 +424,7 @@ const result = AutomationApiErrorCode.parse(data);
424424

425425
| Property | Type | Required | Description |
426426
| :--- | :--- | :--- | :--- |
427-
| **code** | `Enum<'VALIDATION_ERROR' \| 'INVALID_FIELD' \| 'MISSING_REQUIRED_FIELD' \| 'INVALID_FORMAT' \| 'VALUE_TOO_LONG' \| 'VALUE_TOO_SHORT' \| 'VALUE_OUT_OF_RANGE' \| … +369 more>` | ✅ | The inner refusal's code in its WIRE spelling - the ADR-0112 member a record save of the same write answers in `error.code` (e.g. `UNIQUE_VIOLATION`); the closed set `ApiErrorSchema.code` parses against |
427+
| **code** | `Enum<'VALIDATION_ERROR' \| 'INVALID_FIELD' \| 'MISSING_REQUIRED_FIELD' \| 'INVALID_FORMAT' \| 'VALUE_TOO_LONG' \| 'VALUE_TOO_SHORT' \| 'VALUE_OUT_OF_RANGE' \| … +372 more>` | ✅ | The inner refusal's code in its WIRE spelling - the ADR-0112 member a record save of the same write answers in `error.code` (e.g. `UNIQUE_VIOLATION`); the closed set `ApiErrorSchema.code` parses against |
428428
| **message** | `string` | ✅ | The inner refusal's own diagnostic text, verbatim, without the node and operation prefixes the run's failure text adds |
429429

430430
### Allowed Values: `FlowInnerRefusal.code`
@@ -575,6 +575,9 @@ const result = AutomationApiErrorCode.parse(data);
575575
* `ERR_SUMMARY_RECOMPUTE`
576576
* `ERR_SYSTEM_WRITE_ORGANIZATION_REQUIRED`
577577
* `ERR_TRANSACTION_UNSUPPORTED`
578+
* `ERR_WORK_CALENDAR_INVALID`
579+
* `ERR_WORK_CALENDAR_NOT_MAINTAINED`
580+
* `ERR_WORK_CALENDAR_UNRESOLVED`
578581
* `EXECUTION_ERROR`
579582
* `EXPIRED_OR_REVOKED`
580583
* `EXPIRY_IN_PAST`

‎content/docs/references/api/contract.mdx‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ const result = ApiErrorSchema.parse(data);
2828

2929
| Property | Type | Required | Description |
3030
| :--- | :--- | :--- | :--- |
31-
| **code** | `Enum<'VALIDATION_ERROR' \| 'INVALID_FIELD' \| 'MISSING_REQUIRED_FIELD' \| 'INVALID_FORMAT' \| 'VALUE_TOO_LONG' \| 'VALUE_TOO_SHORT' \| 'VALUE_OUT_OF_RANGE' \| … +369 more>` | ✅ | Error code (e.g. VALIDATION_ERROR; StandardErrorCode ∪ the ledger the serving side registers — ERROR_CODE_LEDGER for framework packages) |
31+
| **code** | `Enum<'VALIDATION_ERROR' \| 'INVALID_FIELD' \| 'MISSING_REQUIRED_FIELD' \| 'INVALID_FORMAT' \| 'VALUE_TOO_LONG' \| 'VALUE_TOO_SHORT' \| 'VALUE_OUT_OF_RANGE' \| … +372 more>` | ✅ | Error code (e.g. VALIDATION_ERROR; StandardErrorCode ∪ the ledger the serving side registers — ERROR_CODE_LEDGER for framework packages) |
3232
| **declaredCode** | `string` | optional | The producer-declared code, verbatim, when it is not a member of the closed `code` vocabulary — the open, author-authored channel (app-specific spellings; ADR-0112) |
3333
| **message** | `string` | ✅ | Readable error message |
3434
| **userMessage** | `string` | optional | Producer-marked user-facing refusal text, verbatim, in the request's locale: platform-composed text falls back to the workspace default locale, then `en`; an app-authored refusal falls back to its declared wording. Present exactly when the producer opted in at throw time; consumers render it to end users as received and keep their generic substitution for anything unmarked. Status-agnostic; never replaces `message`. |
@@ -186,6 +186,9 @@ const result = ApiErrorSchema.parse(data);
186186
* `ERR_SUMMARY_RECOMPUTE`
187187
* `ERR_SYSTEM_WRITE_ORGANIZATION_REQUIRED`
188188
* `ERR_TRANSACTION_UNSUPPORTED`
189+
* `ERR_WORK_CALENDAR_INVALID`
190+
* `ERR_WORK_CALENDAR_NOT_MAINTAINED`
191+
* `ERR_WORK_CALENDAR_UNRESOLVED`
189192
* `EXECUTION_ERROR`
190193
* `EXPIRED_OR_REVOKED`
191194
* `EXPIRY_IN_PAST`

‎content/docs/references/api/error-code-ledger.mdx‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -353,6 +353,9 @@ const result = ErrorCode.parse(data);
353353
* `ERR_SUMMARY_RECOMPUTE`
354354
* `ERR_SYSTEM_WRITE_ORGANIZATION_REQUIRED`
355355
* `ERR_TRANSACTION_UNSUPPORTED`
356+
* `ERR_WORK_CALENDAR_INVALID`
357+
* `ERR_WORK_CALENDAR_NOT_MAINTAINED`
358+
* `ERR_WORK_CALENDAR_UNRESOLVED`
356359
* `EXECUTION_ERROR`
357360
* `EXPIRED_OR_REVOKED`
358361
* `EXPIRY_IN_PAST`

‎packages/core/src/utils/datetime.ts‎

Lines changed: 13 additions & 133 deletions
Original file line numberDiff line numberDiff line change
@@ -16,54 +16,26 @@
1616
* to avoid a layering dependency on core.)
1717
*/
1818

19+
/**
20+
* [ADR-0157 D11, open point 3] The wall-clock → instant pair and its parts
21+
* type live in `@objectstack/spec/data` (`wall-clock.ts`) — the platform's one
22+
* daylight-saving rule, moved below `@objectstack/formula` so the working-day
23+
* formula functions read the same rule as everything here, as
24+
* `nextUtcCalendarDay` moved before it. Re-exported so this package's
25+
* published surface and every import site are unchanged; this file's own
26+
* helpers below build on them.
27+
*/
28+
import { wallClockToUtcMs, zonedWallClockToUtcMs } from '@objectstack/spec/data';
29+
export { wallClockToUtcMs, zonedWallClockToUtcMs } from '@objectstack/spec/data';
30+
export type { WallClockParts } from '@objectstack/spec/data';
31+
1932
/** Calendar-day parts in a reference timezone. `month` is 1-12. */
2033
export interface CalendarParts {
2134
year: number;
2235
month: number;
2336
day: number;
2437
}
2538

26-
/**
27-
* A wall clock as a human writes it — calendar day plus an optional
28-
* time-of-day, with **no zone attached**. `2026-08-01 06:00:00` is this shape:
29-
* it names a reading on a clock, and only a reference timezone turns it into an
30-
* instant. Omitted time components default to 0, so {@link CalendarParts} alone
31-
* is midnight.
32-
*/
33-
export interface WallClockParts extends CalendarParts {
34-
/** 0-23. */
35-
hour?: number;
36-
minute?: number;
37-
second?: number;
38-
millisecond?: number;
39-
}
40-
41-
/**
42-
* [#20599] The epoch milliseconds of a wall clock read as **UTC**: `Date.UTC`
43-
* without its two-digit-year remap. The zone-free sibling of
44-
* {@link zonedWallClockToUtcMs}, and the one construction this package and its
45-
* callers use to build a UTC instant from year / month / day / time parts.
46-
*
47-
* Not `Date.UTC(year, …)` and not `new Date(year, …)`: both read a year from 0
48-
* to 99 as 1900 + year (ECMA-262 `MakeFullYear`), so `0050-01-01` is built as
49-
* 1950-01-01 — while 0001..9999 is a `date`'s supported range ([#20280] a
50-
* `datetime`'s is 1000..9999; `isOutsideTemporalYearRange`).
51-
* `setUTCFullYear` takes the year as written.
52-
*
53-
* Every component rolls over past its end exactly as `Date.UTC` rolls it, and
54-
* callers rely on that: `month: 13` is January of the next year, `month: 0` is
55-
* December of the previous one, `day: 0` is the previous month's last day,
56-
* `day: 32` runs into the next month, and `hour: 24` is the next day's
57-
* midnight. Omitted time components default to 0. A `NaN` or non-finite
58-
* component, or an instant outside the `Date` range, gives `NaN`, as
59-
* `Date.UTC` does.
60-
*/
61-
export function wallClockToUtcMs(parts: WallClockParts): number {
62-
const dt = new Date(0);
63-
dt.setUTCFullYear(parts.year, parts.month - 1, parts.day);
64-
return dt.setUTCHours(parts.hour ?? 0, parts.minute ?? 0, parts.second ?? 0, parts.millisecond ?? 0);
65-
}
66-
6739
/**
6840
* The year/month/day an instant falls on in `tz`. Throws if `tz` is not a
6941
* valid IANA zone (callers treat that as a fall-through to UTC).
@@ -126,98 +98,6 @@ export function zonedDateStartToUtcMs(ymd: string, tz?: string): number {
12698
);
12799
}
128100

129-
/**
130-
* The UTC instant (epoch ms) at which a **wall clock** reading happens in
131-
* reference timezone `tz` — the general inverse of {@link calendarPartsInTz},
132-
* of which {@link zonedDateStartToUtcMs} is the midnight special case.
133-
*
134-
* `2026-08-01 06:00:00` in `Asia/Shanghai` is `2026-07-31T22:00:00Z`: a
135-
* different day, month and quarter. That gap is why this direction exists as a
136-
* shared primitive at all — bulk import (#8485) reads offset-free spreadsheet
137-
* cells, which are wall clocks and nothing more, and `new Date(cell)` resolves
138-
* them against the **process** `TZ`, i.e. a host setting rather than the
139-
* tenant's configured zone.
140-
*
141-
* DST-safe: the zone offset is read from the platform tz database via
142-
* `Intl.DateTimeFormat` (never hand-computed), and a two-pass resolution settles
143-
* the case where the offset differs side-to-side of the target instant. Two
144-
* wall clocks are not a bijection with instants, and this function resolves
145-
* both degenerate cases to the **earlier candidate instant** — in both, the
146-
* final pass reads the offset on the DST side of the transition (measured, not
147-
* merely intended — `datetime.test.ts` pins both):
148-
* - a clock reading the zone **skips** (spring forward: `02:30` on a US
149-
* spring-forward day) settles on the *post*-transition offset (EDT, −04),
150-
* which places the instant just **before** the gap: it reads `01:30` EST
151-
* locally, not `03:30` EDT. Note this is the opposite of Temporal's
152-
* `'compatible'` disambiguation, which pushes a gap reading forward;
153-
* - a clock reading that happens **twice** (fall back: `01:30` on a US
154-
* fall-back day) resolves to its first occurrence, the one still on the
155-
* pre-transition DST offset (EDT, −04).
156-
*
157-
* A spreadsheet cell naming a wall clock that its zone never had is ambiguous
158-
* by construction; what matters for an import is that the answer is
159-
* deterministic and host-independent, which both branches above are.
160-
*
161-
* FALLBACK — an unset, `'UTC'`, or invalid `tz` reads the wall clock **as UTC**,
162-
* never as the process-local clock. Every caller of this family already degrades
163-
* that way ({@link zonedDateStartToUtcMs}, and the export renderer's cell path),
164-
* and a host `TZ` fallback would reintroduce exactly the deployment-dependent
165-
* instant this primitive exists to remove. A parts object that produces an
166-
* invalid date (`NaN` components) returns `NaN`, as `Date.UTC` does.
167-
*
168-
* [#20599] A year from 0001 to 0099 is read as written, never as 1900 + year:
169-
* both the wall clock and the offset read below go through
170-
* {@link wallClockToUtcMs}, not `Date.UTC`. The offset read takes the zone's
171-
* year with its era, because `Intl`'s `year` part is an ERA year — 1 BC reads
172-
* `1` — and the first probe for a wall clock early on 0001-01-01 in a zone
173-
* west of UTC lands in year 0.
174-
*/
175-
export function zonedWallClockToUtcMs(parts: WallClockParts, tz?: string): number {
176-
const wallAsUtc = wallClockToUtcMs(parts);
177-
if (!tz || tz === 'UTC' || Number.isNaN(wallAsUtc)) return wallAsUtc;
178-
try {
179-
// The tz offset (local − UTC, in ms) at instant `t`: read t's wall clock in
180-
// `tz`, re-interpret those parts as UTC, and subtract t. `formatToParts`
181-
// resolves no finer than a second, so `t` is truncated to a whole second
182-
// first — otherwise a sub-second wall clock leaks its milliseconds into the
183-
// "offset" and shifts the answer by them (a real defect while generalising
184-
// this from the date-only form, where ms was always 0).
185-
const offsetAt = (t: number): number => {
186-
const whole = Math.floor(t / 1000) * 1000;
187-
const p = new Intl.DateTimeFormat('en-US', {
188-
timeZone: tz,
189-
hourCycle: 'h23',
190-
era: 'short',
191-
year: 'numeric',
192-
month: '2-digit',
193-
day: '2-digit',
194-
hour: '2-digit',
195-
minute: '2-digit',
196-
second: '2-digit',
197-
}).formatToParts(new Date(whole));
198-
const g = (k: string) => Number(p.find((x) => x.type === k)?.value);
199-
const eraYear = g('year');
200-
const year = p.find((x) => x.type === 'era')?.value === 'BC' ? 1 - eraYear : eraYear;
201-
return (
202-
wallClockToUtcMs({
203-
year,
204-
month: g('month'),
205-
day: g('day'),
206-
hour: g('hour'),
207-
minute: g('minute'),
208-
second: g('second'),
209-
}) - whole
210-
);
211-
};
212-
// Want U such that localParts(U) == the wall clock, i.e. U = wallAsUtc − offset(U).
213-
// Iterate from the zero-offset guess; converges in ≤2 steps off a DST edge.
214-
const off1 = offsetAt(wallAsUtc - offsetAt(wallAsUtc));
215-
return wallAsUtc - off1;
216-
} catch {
217-
return wallAsUtc; // unknown zone → the wall clock read as UTC
218-
}
219-
}
220-
221101
/**
222102
* Calendar-day bound semantics (ADR-0053 D-D) now live in `@objectstack/spec`,
223103
* beside the date-macro vocabulary they give meaning to — the fifth consumer

‎packages/formula/src/index.ts‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -195,6 +195,26 @@ export type { FormulaReturnDeclaration, FormulaSourceField } from './formula-ret
195195
// number the engine stores.
196196
export { toScaledDecimal, divideToPlaces, formatScaledDecimal, documentDateOf } from './home-amount-arithmetic';
197197
export type { ScaledDecimal } from './home-amount-arithmetic';
198+
// ADR-0157 — the working-calendar arithmetic: the calendar service
199+
// (`@objectstack/objectql`) and the working-day formula functions count with
200+
// this one copy, through the one daylight-saving rule. The codes, the column
201+
// names and the `WorkCalendar` shape are `@objectstack/spec/data`'s.
202+
export {
203+
WorkCalendarUnresolvedError,
204+
WorkCalendarNotMaintainedError,
205+
WorkCalendarInvalidError,
206+
isWorkCalendarRefusal,
207+
parseWorkPeriods,
208+
buildWorkCalendar,
209+
exceptionDayOf,
210+
calendarDayOf,
211+
workingPeriodsOn,
212+
isWorkingDay,
213+
isWorkingTime,
214+
addWorkingDays,
215+
workingDaysBetween,
216+
addWorkingHours,
217+
} from './work-calendar';
198218
// The closed set of refusal codes `validateExpression` and
199219
// `collectCelRootIdentifiers` carry beside their English message, with the
200220
// typed params each message interpolates — so a localized author surface keys

0 commit comments

Comments
 (0)