@niwa-labs/timer 0.0.0-stage → 0.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Niwa Labs contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,3 @@
1
- # Temporary Holding Version
1
+ # @niwa-labs/timer
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
+ Timers and schedules that wake handlers and workflows.
package/package.json CHANGED
@@ -1,6 +1,37 @@
1
1
  {
2
2
  "name": "@niwa-labs/timer",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.0.0",
4
+ "license": "MIT",
5
+ "type": "module",
6
+ "exports": {
7
+ ".": "./src/index.ts",
8
+ "./records": "./src/records.ts",
9
+ "./cockpit": "./src/cockpit/index.tsx"
10
+ },
11
+ "dependencies": {
12
+ "@niwa-labs/cockpit-sdk": "0.0.0",
13
+ "@niwa-labs/core": "0.0.0",
14
+ "@niwa-labs/plugin": "0.0.0",
15
+ "zod": "^4.6.7",
16
+ "@niwa-labs/ui-kit": "0.0.0"
17
+ },
18
+ "devDependencies": {
19
+ "@niwa-labs/testing": "0.0.0",
20
+ "@types/react": "^19.3.0",
21
+ "@types/react-dom": "^19.3.0",
22
+ "react": "^19.3.1",
23
+ "react-dom": "^19.3.1"
24
+ },
25
+ "peerDependencies": {
26
+ "react": "^19.3.1",
27
+ "react-dom": "^19.3.1"
28
+ },
29
+ "peerDependenciesMeta": {
30
+ "react": {
31
+ "optional": true
32
+ },
33
+ "react-dom": {
34
+ "optional": true
35
+ }
36
+ }
37
+ }
@@ -0,0 +1,182 @@
1
+ import { definePlugin, PageLink, recordList, useCall, useProjection } from "@niwa-labs/cockpit-sdk";
2
+ import { Badge, PageSection } from "@niwa-labs/ui-kit";
3
+ import { z } from "zod";
4
+
5
+ const schedule = z.discriminatedUnion("kind", [
6
+ z.object({ kind: z.literal("every"), ms: z.number() }),
7
+ z.object({ kind: z.literal("at"), at: z.number() }),
8
+ z.object({ kind: z.literal("daily"), time: z.string() }),
9
+ ]);
10
+ const timer = z.object({
11
+ name: z.string(),
12
+ description: z.string(),
13
+ schedule,
14
+ nextDue: z.number().nullable(),
15
+ });
16
+ type Timer = z.infer<typeof timer>;
17
+ const list = {
18
+ name: "timer.list",
19
+ input: z.object({}),
20
+ output: z.object({ sleeps: z.array(z.string()), timers: z.array(timer) }),
21
+ };
22
+ const refreshOn = { types: ["timer.*"] };
23
+ const recent = recordList({ types: ["timer.fired", "timer.slept"] }, 30);
24
+ const firing = z.object({ timer: z.string(), due: z.number() });
25
+ const dateTime = new Intl.DateTimeFormat("ru", { dateStyle: "medium", timeStyle: "medium" });
26
+ const durationFormats = {
27
+ hour: new Intl.NumberFormat("ru", { style: "unit", unit: "hour", unitDisplay: "long" }),
28
+ minute: new Intl.NumberFormat("ru", { style: "unit", unit: "minute", unitDisplay: "long" }),
29
+ second: new Intl.NumberFormat("ru", { style: "unit", unit: "second", unitDisplay: "long" }),
30
+ };
31
+
32
+ function Clock({ at }: { at: number }) {
33
+ return <time dateTime={new Date(at).toISOString()}>{dateTime.format(at)}</time>;
34
+ }
35
+
36
+ function Interval({ value }: { value: number }) {
37
+ const hours = Math.floor(value / 3_600_000);
38
+ const minutes = Math.floor(value / 60_000) % 60;
39
+ const seconds = (value / 1_000) % 60;
40
+ const parts = [
41
+ hours && durationFormats.hour.format(hours),
42
+ minutes && durationFormats.minute.format(minutes),
43
+ (seconds || !(hours || minutes)) && durationFormats.second.format(seconds),
44
+ ].filter(Boolean);
45
+ return <>Интервал · {parts.join(" ")}</>;
46
+ }
47
+
48
+ function Schedule({ value }: { value: Timer["schedule"] }) {
49
+ switch (value.kind) {
50
+ case "daily": return <>Ежедневно в {value.time} по времени хоста</>;
51
+ case "every": return <Interval value={value.ms} />;
52
+ case "at": return <>Однократно · <Clock at={value.at} /></>;
53
+ }
54
+ }
55
+
56
+ function nameOf(entry: Timer): string {
57
+ const automatic = /^(?:every \d+(?:\.\d+)?ms|daily \d\d:\d\d(?::\d\d)?|at \d{4}-\d\d-\d\dT[^\s]+)$/;
58
+ return automatic.test(entry.description) ? entry.name : entry.description;
59
+ }
60
+
61
+ function pending(timers: Timer[]): Timer[] {
62
+ return timers.filter((item) => item.nextDue !== null).sort((a, b) => (a.nextDue ?? Infinity) - (b.nextDue ?? Infinity));
63
+ }
64
+
65
+ function TimerRows({ rows }: { rows: Timer[] }) {
66
+ return (
67
+ <ul className="divide-y">
68
+ {rows.map((entry) => (
69
+ <li key={entry.name} className="min-w-0 flex flex-col gap-1 py-2">
70
+ <p className="font-semibold wrap-anywhere">{nameOf(entry)}</p>
71
+ <p className="flex flex-wrap items-center gap-2 text-sm text-muted-foreground">
72
+ <span><Schedule value={entry.schedule} /></span>
73
+ {entry.nextDue !== null && entry.schedule.kind !== "at" && <span>Следующее · <Clock at={entry.nextDue} /></span>}
74
+ </p>
75
+ </li>
76
+ ))}
77
+ </ul>
78
+ );
79
+ }
80
+
81
+ function WaitingSteps({ sleeps }: { sleeps: string[] }) {
82
+ if (sleeps.length === 0) return null;
83
+ return (
84
+ <PageSection title="Ожидают пробуждения">
85
+ <ul className="divide-y">
86
+ {sleeps.map((line, index) => {
87
+ // timer.list uses two spaces between the local clock, the owner of the wait and its label.
88
+ const columns = /^(.*?) {2}(\S+) {2}(.*)$/.exec(line);
89
+ const [, clock, owner, label] = columns ?? [];
90
+ const run = owner && /^run[-_][0-9a-z-]+$/i.test(owner) ? owner : undefined;
91
+ return (
92
+ <li key={line + index} className="flex min-w-0 flex-wrap items-center gap-2 py-2">
93
+ <span className="font-medium wrap-anywhere">{label || "Ожидание шага"}</span>
94
+ {clock && <span className="text-sm text-muted-foreground">Пробуждение · {clock}</span>}
95
+ {run && <PageLink to={"/runs/" + encodeURIComponent(run)} className="text-sm text-primary hover:underline">Открыть запуск</PageLink>}
96
+ </li>
97
+ );
98
+ })}
99
+ </ul>
100
+ </PageSection>
101
+ );
102
+ }
103
+
104
+ function TimerTile() {
105
+ const timers = useCall(list, {}, { refreshOn });
106
+ const upcoming = timers.data ? pending(timers.data.timers) : [];
107
+ return (
108
+ <PageSection title="Таймеры">
109
+ {timers.isPending ? <p role="status">Загружаю расписание…</p> : timers.isError ? (
110
+ <p role="alert">Не удалось загрузить расписание.</p>
111
+ ) : upcoming.length === 0 ? <p>Ближайших срабатываний нет.</p> : (
112
+ <TimerRows rows={upcoming.slice(0, 4)} />
113
+ )}
114
+ {Boolean(timers.data?.sleeps.length) && <p className="text-sm text-muted-foreground">Ожидают пробуждения · {timers.data?.sleeps.length}</p>}
115
+ <PageLink to="/timers" className="text-sm text-primary hover:underline">Все таймеры →</PageLink>
116
+ </PageSection>
117
+ );
118
+ }
119
+
120
+ function Timers() {
121
+ const timers = useCall(list, {}, { refreshOn });
122
+ const events = useProjection(recent);
123
+ const upcoming = timers.data ? pending(timers.data.timers) : [];
124
+ const next = upcoming[0];
125
+ const finished = timers.data?.timers.filter((entry) => entry.nextDue === null) ?? [];
126
+ const names = new Map(timers.data?.timers.map((entry) => [entry.name, nameOf(entry)]));
127
+ return (
128
+ <>
129
+ <PageSection title="Расписание">
130
+ {timers.isPending ? <p role="status">Загружаю расписание…</p> : timers.isError ? (
131
+ <p role="alert">Не удалось загрузить расписание.</p>
132
+ ) : next === undefined || next.nextDue === null ? <p>Предстоящих срабатываний нет.</p> : (
133
+ <>
134
+ <div className="rounded-md border bg-card px-4 py-2">
135
+ <p className="text-sm text-muted-foreground">Ближайшее срабатывание</p>
136
+ <p className="mt-1 text-base font-semibold wrap-anywhere">{nameOf(next)}</p>
137
+ <p className="mt-1 flex flex-wrap gap-2 text-sm">
138
+ <Clock at={next.nextDue} />
139
+ {next.schedule.kind !== "at" && <span className="text-muted-foreground"><Schedule value={next.schedule} /></span>}
140
+ </p>
141
+ </div>
142
+ {upcoming.length > 1 && <TimerRows rows={upcoming.slice(1)} />}
143
+ </>
144
+ )}
145
+ </PageSection>
146
+ <WaitingSteps sleeps={timers.data?.sleeps ?? []} />
147
+ {finished.length > 0 && <PageSection title="Без следующего срабатывания"><TimerRows rows={finished} /></PageSection>}
148
+ <PageSection title="Последние срабатывания и пробуждения">
149
+ {events.length === 0 ? <p>Срабатываний и пробуждений пока нет.</p> : (
150
+ <ul className="divide-y">
151
+ {events.toReversed().map((record) => {
152
+ const parsed = firing.safeParse(record.data);
153
+ const fired = record.type === "timer.fired";
154
+ const title = fired && parsed.success
155
+ ? names.get(parsed.data.timer) ?? parsed.data.timer
156
+ : fired ? "Срабатывание таймера" : "Шаг возобновлён";
157
+ return (
158
+ <li key={record.id} className="min-w-0 flex flex-col gap-1 py-2">
159
+ <p className="font-medium wrap-anywhere">{title}</p>
160
+ <div className="flex min-w-0 flex-wrap items-center gap-2 text-sm text-muted-foreground">
161
+ <Badge variant="secondary">{fired ? "Срабатывание" : "Пробуждение"}</Badge>
162
+ <Clock at={record.at} />
163
+ <PageLink to={"/journal?record=" + encodeURIComponent(record.id)} className="text-primary hover:underline">В журнале</PageLink>
164
+ </div>
165
+ </li>
166
+ );
167
+ })}
168
+ </ul>
169
+ )}
170
+ </PageSection>
171
+ </>
172
+ );
173
+ }
174
+
175
+ export default definePlugin({
176
+ id: "timers",
177
+ setup(ctx) {
178
+ if (!ctx.viewer.can(list)) return;
179
+ ctx.pages.add({ path: "/timers", title: "Таймеры", nav: { order: 37 }, commandHeading: true, component: Timers });
180
+ ctx.slots.register("home.tile", { key: "timers", order: 30, component: TimerTile });
181
+ },
182
+ });