@mistriwork/engine 1.0.0-rc.32 → 1.0.0-rc.34

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.
@@ -1,14 +1,134 @@
1
1
  /**
2
- * The wall clock, unless a test has pinned it: MISTRI_CLOCK holds an
3
- * instant the browser suite fixes so that "last 90 days" over a database
4
- * seeded for a known day reads the same on every run, and a stamp an action
5
- * writes ('now') is the same instant on every run. Never set in use.
2
+ * App logic's clock: what a command's `now()`, a loader, a dashboard's "last 30 days", a job's due check and a
3
+ * stamp an action writes read. The real time, unless
4
+ *
5
+ * - a test has pinned it: MISTRI_CLOCK holds an instant the browser suite fixes so that "last 90 days" over a
6
+ * database seeded for a known day reads the same on every run, and a stamp an action writes ('now') is the same
7
+ * instant on every run. Never set in use.
8
+ * - a development or test process was started as of another moment (`mistri dev --as-of 2026-01-05`, or
9
+ * MISTRI_AS_OF): the clock then reads that moment at start and moves on in real time from it, so seed data dated
10
+ * for one day reads as it was written on every later one. A field report: moving the machine's clock instead
11
+ * broke sign-in, and moving the browser's paused a tenant's access.
12
+ *
13
+ * Only App logic reads it. Sign-in, sessions, one-time codes, tokens and their expiry, rate limits, the read audit,
14
+ * receipts and history, caches and the job scheduler's own timers keep the real clock, so an as-of moment never
15
+ * expires a session or holds a lease past its time.
6
16
  */
17
+ import { appClockOffset, setAppClockOffset } from '../../shared/appClock.js';
7
18
  import { productEnv } from '../product.js';
19
+ /**
20
+ * The pin wins over an as-of moment: a browser suite that pins the clock asks for the same instant on every run, and
21
+ * an offset from the real time would undo that.
22
+ */
8
23
  export function clockNow() {
9
24
  const pinned = productEnv('CLOCK');
10
25
  if (!pinned)
11
- return new Date();
26
+ return appTime();
12
27
  const at = new Date(pinned);
13
- return Number.isNaN(at.getTime()) ? new Date() : at;
28
+ return Number.isNaN(at.getTime()) ? appTime() : at;
29
+ }
30
+ /**
31
+ * A real instant as App logic reads it: moved by the as-of offset. For code handed a real clock (a tenant
32
+ * deployment's, a job host's) and for a default that read `new Date()`; it never applies the MISTRI_CLOCK pin, so
33
+ * what read the real time under the browser suite still does.
34
+ */
35
+ export function appTime(real = Date.now()) {
36
+ return new Date((typeof real === 'number' ? real : real.getTime()) + appClockOffset());
37
+ }
38
+ /** The as-of offset in milliseconds, 0 for the real clock: what an App's chrome carries to the browser. */
39
+ export { appClockOffset };
40
+ const DATE = /^(\d{4})-(\d{2})-(\d{2})$/;
41
+ const DATE_TIME = /^(\d{4})-(\d{2})-(\d{2})[T ](\d{2}):(\d{2})(?::(\d{2})(?:\.(\d{1,3}))?)?(Z|[+-]\d{2}:?\d{2})?$/;
42
+ /** How far `zone`'s wall clock stands ahead of UTC at `at`, in milliseconds. */
43
+ function zoneAhead(zone, at) {
44
+ const parts = new Intl.DateTimeFormat('en-US', {
45
+ timeZone: zone,
46
+ hourCycle: 'h23',
47
+ year: 'numeric',
48
+ month: '2-digit',
49
+ day: '2-digit',
50
+ hour: '2-digit',
51
+ minute: '2-digit',
52
+ second: '2-digit',
53
+ }).formatToParts(new Date(at));
54
+ const get = (type) => Number(parts.find((part) => part.type === type)?.value ?? 0);
55
+ return Date.UTC(get('year'), get('month') - 1, get('day'), get('hour'), get('minute'), get('second')) - Math.floor(at / 1000) * 1000;
56
+ }
57
+ /** The instant a wall clock (its fields read as UTC) names in `zone`; asked twice so a daylight-saving edge settles. */
58
+ function wallIn(zone, wall) {
59
+ if (!zone || zone === 'UTC')
60
+ return wall;
61
+ try {
62
+ const first = wall - zoneAhead(zone, wall);
63
+ return wall - zoneAhead(zone, first);
64
+ }
65
+ catch {
66
+ return wall;
67
+ }
68
+ }
69
+ /**
70
+ * The moment an as-of value names, or undefined when it names none. A date alone (2026-01-05) is midnight in
71
+ * `zone` (the caller passes the App's declared zone, else the server's own; UTC when none is given at all);
72
+ * a date and time without an offset (2026-01-05T09:30) is that wall clock in the same zone; one with an offset
73
+ * (…Z, …-05:00) is that instant.
74
+ */
75
+ export function parseAsOf(given, zone) {
76
+ const text = given.trim();
77
+ const day = DATE.exec(text);
78
+ const timed = day ? undefined : DATE_TIME.exec(text);
79
+ const m = day ?? timed;
80
+ if (!m)
81
+ return undefined;
82
+ const [y, mo, d] = [Number(m[1]), Number(m[2]), Number(m[3])];
83
+ const [h, mi, s, ms] = timed
84
+ ? [Number(timed[4]), Number(timed[5]), Number(timed[6] ?? 0), Number((timed[7] ?? '0').padEnd(3, '0'))]
85
+ : [0, 0, 0, 0];
86
+ const wall = Date.UTC(y, mo - 1, d, h, mi, s, ms);
87
+ const check = new Date(wall);
88
+ /* 2026-02-30 is not a day, and 24:00 not an hour: Date.UTC would roll either over without a word. */
89
+ if (check.getUTCFullYear() !== y ||
90
+ check.getUTCMonth() !== mo - 1 ||
91
+ check.getUTCDate() !== d ||
92
+ check.getUTCHours() !== h ||
93
+ check.getUTCMinutes() !== mi ||
94
+ s > 59)
95
+ return undefined;
96
+ const offset = timed?.[8];
97
+ if (offset === undefined)
98
+ return new Date(wallIn(zone, wall));
99
+ if (offset === 'Z')
100
+ return new Date(wall);
101
+ const sign = offset.startsWith('-') ? -1 : 1;
102
+ const digits = offset.slice(1).replace(':', '');
103
+ return new Date(wall - sign * (Number(digits.slice(0, 2)) * 60 + Number(digits.slice(2))) * 60_000);
104
+ }
105
+ /**
106
+ * Read the as-of moment the flag or MISTRI_AS_OF asks for (the flag wins), and set App logic's clock to start at
107
+ * it. Development and tests only: refused, with a message naming what asked, under NODE_ENV=production, when
108
+ * serving a build, and in any process that is neither `mistri dev` nor NODE_ENV=test — never ignored, since a
109
+ * server quietly running on another day's clock is worse than one that will not start. Returns the moment, or
110
+ * undefined when nothing asked for one.
111
+ */
112
+ export function configureAsOf(flag, asked) {
113
+ const env = asked.env ?? process.env;
114
+ const given = flag ?? env.MISTRI_AS_OF;
115
+ if (given === undefined || (flag === undefined && given.trim() === ''))
116
+ return undefined;
117
+ const source = flag !== undefined ? '--as-of' : 'MISTRI_AS_OF';
118
+ const refused = env.NODE_ENV === 'production'
119
+ ? 'NODE_ENV is production'
120
+ : asked.build
121
+ ? 'this serves a build, which is what is deployed'
122
+ : !asked.dev && env.NODE_ENV !== 'test'
123
+ ? 'this is neither mistri dev nor a test process (NODE_ENV=test)'
124
+ : undefined;
125
+ if (refused)
126
+ throw new Error(`${source} moves App logic's clock for development and tests (mistri dev, or NODE_ENV=test), and ${refused}. ` +
127
+ `Remove ${source} to serve.`);
128
+ const at = parseAsOf(given, asked.zone ?? new Intl.DateTimeFormat().resolvedOptions().timeZone);
129
+ if (!at)
130
+ throw new Error(`${source} takes a date (2026-01-05, midnight in the App's zone) or a date and time (2026-01-05T09:30, ` +
131
+ `or with an offset, 2026-01-05T09:30Z); it got "${given}".`);
132
+ setAppClockOffset(at.getTime() - (asked.now ?? Date.now()));
133
+ return at;
14
134
  }
@@ -0,0 +1,6 @@
1
+ /** The as-of offset in milliseconds; 0 is the real clock. */
2
+ export declare const appClockOffset: () => number;
3
+ /** Set the offset: startup's configureAsOf, and tests. */
4
+ export declare function setAppClockOffset(ms: number): void;
5
+ /** Now as App logic reads it on the server: the default of a shared rule (a dashboard's trend window) the server applies. */
6
+ export declare const appClockNow: () => Date;
@@ -0,0 +1,15 @@
1
+ /**
2
+ * How far App logic's clock stands from the real one, in milliseconds: 0 unless a development or test process was
3
+ * started "as of" another moment (`mistri dev --as-of`, server/http/clock.ts configureAsOf). Kept here, with no
4
+ * imports, so the chrome an App is served (appPayload.ts servedUi) can carry it to the browser without reaching for
5
+ * server code; only the server's startup sets it, and in a browser it stays 0.
6
+ */
7
+ let offset = 0;
8
+ /** The as-of offset in milliseconds; 0 is the real clock. */
9
+ export const appClockOffset = () => offset;
10
+ /** Set the offset: startup's configureAsOf, and tests. */
11
+ export function setAppClockOffset(ms) {
12
+ offset = Number.isFinite(ms) ? ms : 0;
13
+ }
14
+ /** Now as App logic reads it on the server: the default of a shared rule (a dashboard's trend window) the server applies. */
15
+ export const appClockNow = () => new Date(Date.now() + offset);
@@ -42,6 +42,16 @@ export declare function trendPoints<R extends {
42
42
  key: unknown;
43
43
  value: unknown;
44
44
  }>;
45
+ /**
46
+ * The buckets a window cuts through: a week, month or quarter that starts before the window does or runs on past
47
+ * its end, drawn from only part of its days. `last 30 days` by week has a short first week and a week still in
48
+ * hand at the end; drawn as full ones, the line fell at its end as if the measure had dropped. A day is never
49
+ * partial, and a label the unit does not spell is left alone.
50
+ */
51
+ export declare function partialPeriods(keys: readonly string[], unit: AutoUnit, window: {
52
+ start: Date;
53
+ end: Date;
54
+ }): Set<string>;
45
55
  /**
46
56
  * The unit a chart is drawn in: the span's, stepped up while the data is sparse in it.
47
57
  *
@@ -156,6 +156,33 @@ export function trendPoints(rows, read, unit, measure, window, now) {
156
156
  }
157
157
  return [...into].map(([key, value]) => ({ key, value }));
158
158
  }
159
+ /**
160
+ * The buckets a window cuts through: a week, month or quarter that starts before the window does or runs on past
161
+ * its end, drawn from only part of its days. `last 30 days` by week has a short first week and a week still in
162
+ * hand at the end; drawn as full ones, the line fell at its end as if the measure had dropped. A day is never
163
+ * partial, and a label the unit does not spell is left alone.
164
+ */
165
+ export function partialPeriods(keys, unit, window) {
166
+ const partial = new Set();
167
+ if (unit === 'day')
168
+ return partial;
169
+ const start = (key) => {
170
+ if (!SPELLED[unit].test(key))
171
+ return undefined;
172
+ if (unit === 'week')
173
+ return new Date(Number(key.slice(0, 4)), Number(key.slice(5, 7)) - 1, Number(key.slice(8, 10)));
174
+ if (unit === 'month')
175
+ return new Date(Number(key.slice(0, 4)), Number(key.slice(5, 7)) - 1, 1);
176
+ return new Date(Number(key.slice(0, 4)), (Number(key.slice(6)) - 1) * 3, 1);
177
+ };
178
+ for (const key of keys) {
179
+ const from = start(key);
180
+ const to = from && start(nextKey(key, unit));
181
+ if (from && to && (from < window.start || to > window.end))
182
+ partial.add(key);
183
+ }
184
+ return partial;
185
+ }
159
186
  /** How many periods of the unit run from the first label to the last, both ends counted. */
160
187
  function periodsBetween(first, last, unit) {
161
188
  let count = 1;
@@ -17,4 +17,4 @@ export declare function sparkWindow(section: Pick<AskedSection, 'query' | 'over'
17
17
  * the section's own clock (`over`), composed with whatever the card is narrowed to by other than time. None without a
18
18
  * clock.
19
19
  */
20
- export declare function sparkText(section: Pick<AskedSection, 'table' | 'query' | 'windowBase' | 'windowPhrase' | 'measure' | 'over' | 'spark'>): string | null;
20
+ export declare function sparkText(section: Pick<AskedSection, 'table' | 'query' | 'windowBase' | 'windowPhrase' | 'measure' | 'over' | 'spark'>, now?: Date): string | null;
@@ -6,13 +6,14 @@
6
6
  * (server/http/firstPaintRooms.ts), in the same words.
7
7
  */
8
8
  import { andQuery } from './query.js';
9
+ import { appClockNow } from './appClock.js';
9
10
  import { unitForSpan, windowDays, windowPhraseOf } from './autoBucket.js';
10
11
  /**
11
12
  * The window a metric's trend is drawn over — the reader's, else the author's own on `over` — and the units it is
12
13
  * read and drawn in: the span's unit (autoBucket.ts), read as days under a week so a week is added up on the client
13
14
  * (`trendPoints`) and never handed whole to one month. Null where the metric has no window the date grammar bounds.
14
15
  */
15
- export function sparkWindow(section, now = new Date()) {
16
+ export function sparkWindow(section, now = appClockNow()) {
16
17
  if (!section.over)
17
18
  return null;
18
19
  const phrase = section.windowPhrase ?? windowPhraseOf(section.query, section.over);
@@ -34,11 +35,11 @@ const TREND_PERIODS = 400;
34
35
  * the section's own clock (`over`), composed with whatever the card is narrowed to by other than time. None without a
35
36
  * clock.
36
37
  */
37
- export function sparkText(section) {
38
+ export function sparkText(section, now = appClockNow()) {
38
39
  /* An authored false is heard over a window too: a card can be a figure alone, which it once could not say. */
39
40
  if (!section.over || section.spark === false)
40
41
  return null;
41
- const window = sparkWindow(section);
42
+ const window = sparkWindow(section, now);
42
43
  if (window)
43
44
  return [section.table, section.query, `${section.measure ?? 'count'} by ${window.read} ${section.over}`, `limit ${TREND_PERIODS}`]
44
45
  .filter(Boolean)
@@ -56,6 +56,8 @@ export declare const writesMask: (template: string) => boolean;
56
56
  export declare const writesDay: (template: string) => boolean;
57
57
  /** A template field for a date path said as its day, as the server writes it into a template it composes. */
58
58
  export declare const datedField: (path: string) => string;
59
+ /** The same inside a fallback chain, without its braces. */
60
+ export declare const datedPath: (path: string) => string;
59
61
  /**
60
62
  * The name a record with no name of its own is given: its noun and its key,
61
63
  * "Purchase order #3", rather than the bare key a title and a breadcrumb
@@ -145,7 +145,9 @@ export const writesMask = (template) => template.includes(MASK_MARK) || template
145
145
  /** Whether an authored template writes the day mark itself: the server's, in a name it composes. */
146
146
  export const writesDay = (template) => /\|date\s*[}?]/.test(template);
147
147
  /** A template field for a date path said as its day, as the server writes it into a template it composes. */
148
- export const datedField = (path) => `{${path}${DATE_MARK}}`;
148
+ export const datedField = (path) => `{${datedPath(path)}}`;
149
+ /** The same inside a fallback chain, without its braces. */
150
+ export const datedPath = (path) => `${path}${DATE_MARK}`;
149
151
  /**
150
152
  * The name a record with no name of its own is given: its noun and its key,
151
153
  * "Purchase order #3", rather than the bare key a title and a breadcrumb
@@ -274,6 +274,9 @@ export interface AppDisplayRule {
274
274
  };
275
275
  /** A copy button beside the value on a record: the stored value copied, a toast saying so. */
276
276
  copy?: true;
277
+ /** What a missing (null) value is said as where the dash would stand — "Open", "Never": a list's cell, a record's
278
+ field and a value drawn on its own. The row keeps its null for sorting, filtering and export. */
279
+ empty?: string;
277
280
  /** Value → one of the theme's chart colors, 1 to 8: a category's own color — a board card's chip and stripe, a
278
281
  chip in a cell — kept apart from `tone`, which says meaning. A value it does not name takes a color of its
279
282
  own, fixed by its words. */
@@ -3,7 +3,15 @@ import { type AppAccent } from './themePresets.js';
3
3
  import { HEAT_TOP, heatTop } from './themeColor.js';
4
4
  export { FONT_TOKENS, PALETTE_TOKENS, RADIUS_TOKENS, shapeTokens, THEME_BASES } from './themeTokens.js';
5
5
  export type { ThemeBase, ThemeDefinition, ThemePalette, ThemePaletteVariant } from '../../schema/theme.js';
6
- export declare function parseThemes(raw: unknown, where: string, key?: string): ThemeDefinition[] | undefined;
6
+ /**
7
+ * `platform` says the themes are the platform's own, derived from a built-in look (a tenant's branding is the App's
8
+ * chosen look with the tenant's accent over it): only those may carry `startedFrom`, which `useLook().preset` reads.
9
+ * An authored theme names its look with `extends`; one that sets `startedFrom` is refused, so no App can pass itself
10
+ * off as a built-in preset.
11
+ */
12
+ export declare function parseThemes(raw: unknown, where: string, key?: string, { platform }?: {
13
+ platform?: boolean;
14
+ }): ThemeDefinition[] | undefined;
7
15
  /**
8
16
  * What a theme's shape says that `check` warns of (theme-radius): a panel squarer than the controls it holds, its
9
17
  * corner cutting under theirs. A round control is a pill, not a corner, so it is never measured against a panel.
@@ -69,7 +69,13 @@ function paletteStrings(raw, where) {
69
69
  }
70
70
  return result;
71
71
  }
72
- export function parseThemes(raw, where, key = 'themes') {
72
+ /**
73
+ * `platform` says the themes are the platform's own, derived from a built-in look (a tenant's branding is the App's
74
+ * chosen look with the tenant's accent over it): only those may carry `startedFrom`, which `useLook().preset` reads.
75
+ * An authored theme names its look with `extends`; one that sets `startedFrom` is refused, so no App can pass itself
76
+ * off as a built-in preset.
77
+ */
78
+ export function parseThemes(raw, where, key = 'themes', { platform = false } = {}) {
73
79
  if (raw === undefined)
74
80
  return undefined;
75
81
  if (!Array.isArray(raw) || raw.length > 20)
@@ -79,11 +85,14 @@ export function parseThemes(raw, where, key = 'themes') {
79
85
  const path = `${where}.${key}[${index}]`;
80
86
  const theme = object(value, path);
81
87
  for (const key of Object.keys(theme)) {
88
+ if (key === 'startedFrom' && !platform)
89
+ throw new Error(`${path}.startedFrom is set by the platform when a theme starts from a built-in look; name the look with "extends" instead.`);
82
90
  if (key === 'scale' || key === 'headingWeight')
83
91
  throw new Error(`${path}.${key} is now ${path}.${TYPE_MOVED[`type.${key}`]}.`);
84
92
  if (![
85
93
  'id',
86
94
  'label',
95
+ 'startedFrom',
87
96
  'base',
88
97
  'light',
89
98
  'dark',
@@ -104,6 +113,8 @@ export function parseThemes(raw, where, key = 'themes') {
104
113
  used.add(theme.id);
105
114
  if (typeof theme.label !== 'string' || !theme.label.trim() || theme.label.trim().length > 60)
106
115
  throw new Error(`${path}.label must have 1 to 60 characters.`);
116
+ if (theme.startedFrom !== undefined && (typeof theme.startedFrom !== 'string' || !/^[a-z][a-z0-9-]{0,47}$/.test(theme.startedFrom)))
117
+ throw new Error(`${path}.startedFrom must be a slug.`);
107
118
  if (theme.base !== undefined && (typeof theme.base !== 'string' || !THEME_BASES.includes(theme.base)))
108
119
  throw new Error(`${path}.base must be one of ${THEME_BASES.join(', ')}.`);
109
120
  const palette = (mode) => {
@@ -129,6 +140,7 @@ export function parseThemes(raw, where, key = 'themes') {
129
140
  return {
130
141
  id: theme.id,
131
142
  label: theme.label.trim(),
143
+ ...(theme.startedFrom !== undefined && { startedFrom: theme.startedFrom }),
132
144
  base: (theme.base ?? 'mono'),
133
145
  light,
134
146
  dark,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mistriwork/engine",
3
- "version": "1.0.0-rc.32",
3
+ "version": "1.0.0-rc.34",
4
4
  "description": "The engine both products stand on: the adapters (SQLite, Postgres), the catalog, the query language, keyset pages, the HTTP kit and the shared rules. No React.",
5
5
  "homepage": "https://mistriwork.dev",
6
6
  "bugs": {
@@ -149,6 +149,7 @@
149
149
  "./server/startupWarnings.js": "./dist/server/startupWarnings.js",
150
150
  "./shared/addressParams.js": "./dist/shared/addressParams.js",
151
151
  "./shared/appCards.js": "./dist/shared/appCards.js",
152
+ "./shared/appClock.js": "./dist/shared/appClock.js",
152
153
  "./shared/appComponents.js": "./dist/shared/appComponents.js",
153
154
  "./shared/appDocuments.js": "./dist/shared/appDocuments.js",
154
155
  "./shared/appEmbeds.js": "./dist/shared/appEmbeds.js",
package/schema/theme.d.ts CHANGED
@@ -69,6 +69,9 @@ export interface ThemeDefinition {
69
69
  id: string;
70
70
  label: string;
71
71
  base?: ThemeBase;
72
+ /** The theme this one was derived from: a tenant's branding is the App's chosen theme with the tenant's accent over
73
+ it (`useLook().preset` says it). Set by the platform on that derived theme, never authored. */
74
+ startedFrom?: string;
72
75
  /** Opaque six-digit hex colors. Omitted roles inherit the base style. */
73
76
  light: ThemePalette;
74
77
  dark: ThemePalette;