@ranzenjs/client 0.3.0 → 0.4.1

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/README.md CHANGED
@@ -7,8 +7,8 @@ does, keeps the session alive, and reads the portal's apps into plain, typed obj
7
7
  bun add @ranzenjs/client
8
8
  ```
9
9
 
10
- Runs on Bun and Node 22.1 or newer. It has three small dependencies (htmlparser2, domhandler,
11
- css-select) and no native code.
10
+ Runs on Bun and Node 22.1 or newer. It has four small dependencies (htmlparser2, domhandler,
11
+ css-select, and hash-wasm for Kurswahl Online) and no native code.
12
12
 
13
13
  ## Usage
14
14
 
@@ -37,6 +37,7 @@ Every portal feature is an app that you open on a connection. Opening makes no r
37
37
  | `@ranzenjs/client/lessons` | Mein Unterricht | `overview()`, `course(id, { semester })`, `setHomeworkDone()`, `download()`, `downloadAll()` |
38
38
  | `@ranzenjs/client/substitutions` | Vertretungsplan | `plan({ full })` |
39
39
  | `@ranzenjs/client/profile` | Benutzerdaten | `get()` |
40
+ | `@ranzenjs/client/calendar` | Kalender | `events({ from, to })`, `categories()`, `details(id)` |
40
41
  | `@ranzenjs/client/catalog` | Start page | `list()`, `offers(app)` |
41
42
 
42
43
  Schools turn apps on and off. To find out whether an account has an app, ask
@@ -52,6 +53,31 @@ const file = await connection
52
53
  await Bun.write('blatt.pdf', new Response(file.body));
53
54
  ```
54
55
 
56
+ ### Calendar
57
+
58
+ ```ts
59
+ import { calendar } from '@ranzenjs/client/calendar';
60
+
61
+ const dates = connection.open(calendar);
62
+ const events = await dates.events({ from: '2026-10-01', to: '2026-10-31' });
63
+ const categories = await dates.categories(); // { id, name, color }, as events refer to by categoryId
64
+ ```
65
+
66
+ `events()` returns every event that overlaps the inclusive range, once per id. The portal has no
67
+ recurrence, so each event is one occurrence. Dates and times are the portal's Europe/Berlin wall
68
+ clock as written. ranzen never converts them through UTC, so `"2026-10-25"` and `"02:30"` mean
69
+ exactly what the school entered. `endDate` is inclusive and never before `startDate`. All-day
70
+ events have `startTime` and `endTime` set to `null`. Descriptions are plain text with their line
71
+ breaks. The portal sometimes encodes them twice. ranzen then turns encoded `<br />` into line
72
+ breaks and keeps any other encoded markup as visible text.
73
+
74
+ The portal ends all-day events at `23:59` of their last day. Should one end at exactly midnight of
75
+ a later day instead, ranzen reads that end as exclusive, the way calendar widgets send it: an event
76
+ from `2026-10-19 00:00:00` to `2026-10-20 00:00:00` lasts only the 19th.
77
+
78
+ `details(id)` loads the responsible person's display name and the target groups of one event. It
79
+ reports `NOT_FOUND` for an unknown id.
80
+
55
81
  ### Sessions
56
82
 
57
83
  `exportState()` returns the portal cookies, the session's cipher secret, and the account. It never
@@ -81,6 +107,44 @@ that a session still works, so sign in again when one reports `SESSION_EXPIRED`.
81
107
  `maxConcurrency` (default 4) caps parallel requests per connection. Extra calls wait for a free
82
108
  slot, and a download frees its slot once the headers arrive.
83
109
 
110
+ ## Kurswahl Online
111
+
112
+ Many schools run their course timetable on [Kurswahl Online](https://www.kurswahl-online.de/).
113
+ Its client stands on its own: a school may use it, Schulportal, or both, and neither needs the
114
+ other.
115
+
116
+ ```ts
117
+ import { createKurswahl } from '@ranzenjs/client/kurswahl';
118
+
119
+ const kurswahl = createKurswahl({ onDrift: (drift) => console.warn('ranzen drift', drift) });
120
+ const schools = await kurswahl.schools(); // [{ id: 'musterschule', name: '…' }, …], no sign-in needed
121
+ const connection = await kurswahl.login({
122
+ school: 'musterschule',
123
+ username: 'max.muster',
124
+ password
125
+ });
126
+
127
+ const plan = await connection.timetable(); // the general plan, A and B weeks included
128
+ const week = await connection.timetable({ week: '2025-08-25' }); // one week, one rotation
129
+ const rotation = await connection.currentRotation(); // 'A', 'B', or null; this week
130
+ await connection.logout();
131
+ ```
132
+
133
+ Kurswahl lists only the courses the student takes, so treat it as the source of truth for them.
134
+ Each lesson names its course, ISO weekday, period, room and `rotation` (`'A'`, `'B'`, or `null`
135
+ for every week). Teachers come with their short code, which Schulportal uses too, and their
136
+ salutation. Sign-in hashes the password with Argon2 the way the login page does, which takes a few
137
+ seconds of CPU. The week list can still show last school year's dates, so ask
138
+ `currentRotation()` for this week's rotation rather than picking a week by date.
139
+
140
+ `exportState()`, `restore()`, `keepAlive()`, `keepWarm()` and `dispose()` work as they do for
141
+ Schulportal, with requests one at a time, since each page hands out the next CSRF token. Export
142
+ once the connection is idle, and let one connection at a time use a session.
143
+
144
+ To line both up, substitution days carry `rotation` next to their `week` label, and each
145
+ substitution has `periodNumbers` (`"3 - 4"` → `[3, 4]`). Break duties such as `"2/3"` or `"MP"`
146
+ have none.
147
+
84
148
  ## Errors
85
149
 
86
150
  ranzen throws a `RanzenError` with a `code` and a `fault`. The fault says who has to act:
@@ -0,0 +1,13 @@
1
+ import type { SignalOption } from '../../connection.js';
2
+ import type { CalendarCategory, CalendarEvent, CalendarEventDetails, DateRange } from './types.js';
3
+ export type * from './types.js';
4
+ export interface CalendarApi {
5
+ /** Events overlapping the inclusive range, once per id, in the portal's order. */
6
+ events(range: DateRange, options?: SignalOption): Promise<CalendarEvent[]>;
7
+ /** The categories events refer to by categoryId. */
8
+ categories(options?: SignalOption): Promise<CalendarCategory[]>;
9
+ /** Who is responsible for an event and whom it addresses; NOT_FOUND for an unknown id. */
10
+ details(id: string, options?: SignalOption): Promise<CalendarEventDetails>;
11
+ }
12
+ /** "Kalender": the school's events and dates. */
13
+ export declare const calendar: import("../../app.js").App<CalendarApi>;
@@ -0,0 +1,38 @@
1
+ import { defineApp } from '../../app.js';
2
+ import { fail } from '../../errors.js';
3
+ import { isIsoDate, parseCategories, parseEventDetails, parseEvents } from './parse.js';
4
+ const PAGE = 'kalender.php';
5
+ /** "Kalender": the school's events and dates. */
6
+ export const calendar = defineApp({ id: 'calendar', page: PAGE }, (context) => ({
7
+ async events({ from, to }, { signal } = {}) {
8
+ if (!isIsoDate(from) || !isIsoDate(to)) {
9
+ throw fail('INVALID_OPTION', 'from and to must be ISO dates such as "2026-10-19".');
10
+ }
11
+ if (from > to)
12
+ throw fail('INVALID_OPTION', 'from must not be after to.');
13
+ const { text } = await context.page({
14
+ path: PAGE,
15
+ // The portal returns the events overlapping both dates, inclusive.
16
+ form: { f: 'getEvents', start: from, end: to, s: '' },
17
+ ajax: true,
18
+ signal
19
+ });
20
+ // An all-day end read as exclusive can move an event out of the range.
21
+ return parseEvents(text, context.drift).filter((event) => event.startDate <= to && event.endDate >= from);
22
+ },
23
+ async categories({ signal } = {}) {
24
+ const { text } = await context.page({ path: PAGE, signal });
25
+ return parseCategories(text, context.drift);
26
+ },
27
+ async details(id, { signal } = {}) {
28
+ if (!id.trim())
29
+ throw fail('INVALID_OPTION', 'The event id must not be empty.');
30
+ const { text } = await context.page({
31
+ path: PAGE,
32
+ form: { f: 'getEvent', id },
33
+ ajax: true,
34
+ signal
35
+ });
36
+ return parseEventDetails(text, context.drift);
37
+ }
38
+ }));
@@ -0,0 +1,7 @@
1
+ import { type DriftSink } from '../../util.js';
2
+ import type { CalendarCategory, CalendarEvent, CalendarEventDetails } from './types.js';
3
+ export declare function isIsoDate(value: unknown): value is string;
4
+ export declare function parseEvents(body: string, drift?: DriftSink): CalendarEvent[];
5
+ /** Categories from the calendar page's inline script, one object literal per line. */
6
+ export declare function parseCategories(html: string, drift?: DriftSink): CalendarCategory[];
7
+ export declare function parseEventDetails(body: string, drift?: DriftSink): CalendarEventDetails;
@@ -0,0 +1,176 @@
1
+ import { fail, layoutChanged } from '../../errors.js';
2
+ import { parseHtml, text } from '../../html.js';
3
+ import { ignoreDrift, isRecord, parseJson } from '../../util.js';
4
+ // The portal's "YYYY-MM-DD HH:MM:SS", read as wall clock.
5
+ const STAMP = /^(\d{4}-\d{2}-\d{2})[ T]([01]\d|2[0-3]):([0-5]\d)(?::([0-5]\d))?$/;
6
+ // Real calendar dates only; Date arithmetic in UTC never shifts a plain date.
7
+ export function isIsoDate(value) {
8
+ if (typeof value !== 'string' || !/^\d{4}-\d{2}-\d{2}$/.test(value))
9
+ return false;
10
+ const date = new Date(`${value}T00:00:00Z`);
11
+ return !Number.isNaN(date.getTime()) && date.toISOString().startsWith(value);
12
+ }
13
+ function addDays(date, days) {
14
+ return new Date(Date.parse(`${date}T00:00:00Z`) + days * 86_400_000).toISOString().slice(0, 10);
15
+ }
16
+ export function parseEvents(body, drift = ignoreDrift) {
17
+ const data = parseJson(body, 'calendar events');
18
+ if (!Array.isArray(data))
19
+ throw layoutChanged('calendar events as a list');
20
+ const events = new Map();
21
+ for (const raw of data) {
22
+ const event = parseEvent(raw, drift);
23
+ // The same id twice is the same event; the first one wins.
24
+ if (event && !events.has(event.id))
25
+ events.set(event.id, event);
26
+ }
27
+ return [...events.values()];
28
+ }
29
+ function parseEvent(raw, drift) {
30
+ if (!isRecord(raw)) {
31
+ drift('A calendar event is not an object.');
32
+ return null;
33
+ }
34
+ const id = idOf(raw.Id);
35
+ const title = plain(raw.title);
36
+ const start = stamp(raw.Anfang);
37
+ const end = stamp(raw.Ende);
38
+ if (!id)
39
+ drift('A calendar event has no id.');
40
+ else if (!title)
41
+ drift('A calendar event has no title.');
42
+ else if (!start || !end)
43
+ drift('A calendar event has no readable start and end.');
44
+ if (!id || !title || !start || !end)
45
+ return null;
46
+ if (typeof raw.allDay !== 'boolean')
47
+ drift('A calendar event has no allDay flag.');
48
+ const allDay = raw.allDay === true;
49
+ let last = end;
50
+ // The portal ends all-day events at 23:59; an end at midnight of a later day is read as exclusive.
51
+ if (allDay && end.time === '00:00:00' && end.date > start.date) {
52
+ last = { date: addDays(end.date, -1), time: end.time };
53
+ }
54
+ if (`${last.date} ${last.time}` < `${start.date} ${start.time}`)
55
+ last = start;
56
+ const changed = raw.LetzteAenderung == null ? null : stamp(raw.LetzteAenderung);
57
+ if (raw.LetzteAenderung != null && !changed)
58
+ drift('A calendar event has an unreadable change date.');
59
+ return {
60
+ id,
61
+ title,
62
+ description: plain(raw.description, true),
63
+ location: plain(raw.Ort),
64
+ categoryId: idOf(raw.category),
65
+ group: isRecord(raw.Lerngruppe) ? plain(raw.Lerngruppe.Name) : null,
66
+ allDay,
67
+ startDate: start.date,
68
+ endDate: last.date,
69
+ startTime: allDay ? null : start.time.slice(0, 5),
70
+ endTime: allDay ? null : last.time.slice(0, 5),
71
+ updatedAt: changed && `${changed.date}T${changed.time}`,
72
+ isNew: flag(raw.Neu, drift),
73
+ isPublic: flag(raw.Oeffentlich, drift),
74
+ isPrivate: flag(raw.Privat, drift),
75
+ isSecret: flag(raw.Geheim, drift)
76
+ };
77
+ }
78
+ const CATEGORIES = /var\s+categories\s*=\s*new\s+Array\(\);([\s\S]*?)var\s+groups\s*=\s*new\s+Array\(\);/;
79
+ // A key with its single- or double-quoted value or bare number, e.g. id:'3' or "name": "Ferien".
80
+ const PROPERTY = /["']?(\w+)["']?\s*:\s*(?:'((?:[^'\\]|\\.)*)'|"((?:[^"\\]|\\.)*)"|(-?\d+))/g;
81
+ /** Categories from the calendar page's inline script, one object literal per line. */
82
+ export function parseCategories(html, drift = ignoreDrift) {
83
+ const block = CATEGORIES.exec(html)?.[1];
84
+ if (block === undefined)
85
+ throw layoutChanged('the category list on the calendar page');
86
+ const categories = new Map();
87
+ // Line by line, so a brace inside a name cannot split a literal.
88
+ for (const [literal] of block.matchAll(/\{.*\}/g)) {
89
+ const values = {};
90
+ for (const [, key = '', single, double, number] of literal.matchAll(PROPERTY)) {
91
+ values[key] = number ?? unescape(single ?? double ?? '');
92
+ }
93
+ const id = values.id?.trim();
94
+ const name = plain(values.name);
95
+ if (!id || !name) {
96
+ drift('A calendar category has no id or name.');
97
+ continue;
98
+ }
99
+ const color = values.color?.trim() || null;
100
+ const valid = color && /^#(?:[0-9a-f]{3}){1,2}$/i.test(color) ? color : null;
101
+ if (color && !valid)
102
+ drift('A calendar category has an unreadable color.');
103
+ if (!categories.has(id))
104
+ categories.set(id, { id, name, color: valid });
105
+ }
106
+ return [...categories.values()];
107
+ }
108
+ export function parseEventDetails(body, drift = ignoreDrift) {
109
+ const data = parseJson(body, 'a calendar event');
110
+ if (!isRecord(data) || Array.isArray(data))
111
+ throw layoutChanged('a calendar event as an object');
112
+ // The portal answers an unknown id with error -1, or with an empty id when it is not a number.
113
+ if (data.error === -1 || data.id === '' || data.id === null) {
114
+ throw fail('NOT_FOUND', 'The portal has no such calendar event.');
115
+ }
116
+ const id = idOf(data.id);
117
+ if (!id)
118
+ throw layoutChanged('a calendar event with an id');
119
+ const properties = isRecord(data.properties) ? data.properties : {};
120
+ if (!isRecord(data.properties))
121
+ drift('A calendar event has no properties.');
122
+ const groups = isRecord(properties.zielgruppen) ? Object.entries(properties.zielgruppen) : [];
123
+ return {
124
+ id,
125
+ responsible: plain(properties.verantwortlich),
126
+ targetGroups: groups.flatMap(([key, label]) => {
127
+ if (typeof label !== 'string')
128
+ return [];
129
+ // The -sus label carries leftover "amp;", which lanis-mobile drops the same way.
130
+ const name = plain(key === '-sus' ? label.replaceAll('amp;', '') : label);
131
+ return name ? [name] : [];
132
+ })
133
+ };
134
+ }
135
+ function stamp(value) {
136
+ const match = typeof value === 'string' ? STAMP.exec(value.trim()) : null;
137
+ if (!match || !isIsoDate(match[1]))
138
+ return null;
139
+ return { date: match[1], time: `${match[2]}:${match[3]}:${match[4] ?? '00'}` };
140
+ }
141
+ function idOf(value) {
142
+ if (typeof value !== 'string' && !(typeof value === 'number' && Number.isFinite(value))) {
143
+ return null;
144
+ }
145
+ return String(value).trim() || null;
146
+ }
147
+ // 'ja' or 'nein'; a missing flag is off (lanis-mobile reads anything but 'nein' as on).
148
+ function flag(value, drift) {
149
+ if (value !== undefined && value !== null && value !== 'ja' && value !== 'nein') {
150
+ drift('A calendar event has an unknown flag value.');
151
+ }
152
+ return value === 'ja';
153
+ }
154
+ // Values are HTML, sometimes encoded once more. Only encoded breaks such as "&lt;br /&gt;" become
155
+ // markup, so escaped text such as "a &lt;b" stays text; a second layer of entities is decoded.
156
+ function plain(value, multiline = false) {
157
+ if (typeof value !== 'string' && typeof value !== 'number')
158
+ return null;
159
+ const html = String(value).replace(/&(?:amp;)*lt;br\s*\/?&(?:amp;)*gt;/gi, '<br>');
160
+ const lines = text(parseHtml(html), multiline).split('\n');
161
+ return lines.map((line) => (ENTITY.test(line) ? decode(line) : line)).join('\n') || null;
162
+ }
163
+ const ENTITY = /&(?:[a-z][a-z\d]*|#\d+|#x[\da-f]+);/i;
164
+ // Entities only; a "<" in the text is escaped first so it cannot start a tag.
165
+ function decode(line) {
166
+ return text(parseHtml(line.replaceAll('<', '&lt;')));
167
+ }
168
+ // JavaScript string escapes such as \' and \u{...}.
169
+ function unescape(value) {
170
+ return value.replace(/\\(u\{[\da-f]{1,6}\}|u[\da-f]{4}|x[\da-f]{2}|.)/gi, (escape, code) => {
171
+ if (code.length === 1)
172
+ return { n: '\n', r: '\r', t: '\t' }[code] ?? code;
173
+ const point = parseInt(code.replace(/^[ux]\{?|\}$/g, ''), 16);
174
+ return point <= 0x10ffff ? String.fromCodePoint(point) : escape;
175
+ });
176
+ }
@@ -0,0 +1,49 @@
1
+ export interface DateRange {
2
+ /** ISO calendar date, e.g. "2026-10-01". */
3
+ from: string;
4
+ /** ISO calendar date, inclusive. */
5
+ to: string;
6
+ }
7
+ /**
8
+ * One occurrence; the portal has no recurrence. Dates and times are the portal's
9
+ * Europe/Berlin wall clock, as written, never converted through UTC.
10
+ */
11
+ export interface CalendarEvent {
12
+ id: string;
13
+ title: string;
14
+ /** Plain text, with line breaks kept. */
15
+ description: string | null;
16
+ location: string | null;
17
+ /** Refers to CalendarCategory.id. */
18
+ categoryId: string | null;
19
+ /** The course or group the event belongs to, e.g. "Q1 Mathematik". */
20
+ group: string | null;
21
+ allDay: boolean;
22
+ /** ISO calendar date, e.g. "2026-10-19". */
23
+ startDate: string;
24
+ /** ISO calendar date, inclusive; never before startDate. */
25
+ endDate: string;
26
+ /** "HH:MM"; null for all-day events. */
27
+ startTime: string | null;
28
+ endTime: string | null;
29
+ /** Last change as local portal time, e.g. "2026-10-16T11:58:40". */
30
+ updatedAt: string | null;
31
+ /** The portal's own flags: Neu, Oeffentlich, Privat and Geheim. */
32
+ isNew: boolean;
33
+ isPublic: boolean;
34
+ isPrivate: boolean;
35
+ isSecret: boolean;
36
+ }
37
+ export interface CalendarCategory {
38
+ id: string;
39
+ name: string;
40
+ /** CSS hex color, e.g. "#25599a". */
41
+ color: string | null;
42
+ }
43
+ export interface CalendarEventDetails {
44
+ id: string;
45
+ /** Display name of the person responsible; may name a person, so review it before logging. */
46
+ responsible: string | null;
47
+ /** Whom the event addresses, as the portal labels the groups. */
48
+ targetGroups: string[];
49
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -46,10 +46,12 @@ export function parsePlan(document, drift = ignoreDrift) {
46
46
  const entries = rows(table).filter((row) => !isPlaceholder(row));
47
47
  const stamp = /(\d{2}\.\d{2}\.\d{4}) um ([01]\d|2[0-3]):([0-5]\d):([0-5]\d)/.exec(text(panel));
48
48
  const stampDay = stamp && isoDate(stamp[1]);
49
+ const week = text(one('.badge.woche', panel)) || null;
49
50
  return [
50
51
  {
51
52
  date,
52
- week: text(one('.badge.woche', panel)) || null,
53
+ week,
54
+ rotation: rotation(week, drift),
53
55
  notices: parseNotices(panel),
54
56
  substitutions: entries.map((row) => {
55
57
  const columns = cells(row);
@@ -98,6 +100,7 @@ function substitution(values, date, marked, drift) {
98
100
  const entry = {
99
101
  date,
100
102
  periods: values.Stunde ?? '',
103
+ periodNumbers: periodNumbers(values.Stunde ?? '', drift),
101
104
  classes: null,
102
105
  previousClasses: null,
103
106
  substitute: null,
@@ -126,6 +129,27 @@ function substitution(values, date, marked, drift) {
126
129
  });
127
130
  return entry;
128
131
  }
132
+ // "A-Woche" or "WA-Woche" → "A".
133
+ function rotation(label, drift) {
134
+ if (!label)
135
+ return null;
136
+ const match = /^W?([AB])-?Woche$/i.exec(label);
137
+ if (!match)
138
+ drift('A plan day has an unknown week label.');
139
+ return match ? match[1].toUpperCase() : null;
140
+ }
141
+ // "3 - 4" → [3, 4]; break duties such as "2/3" (between periods 2 and 3) or "MP" (lunch) hold no lesson.
142
+ function periodNumbers(label, drift) {
143
+ const range = /^(\d{1,2})\.?(?:\s*[-–]\s*(\d{1,2})\.?)?$/.exec(label.trim());
144
+ const first = Number(range?.[1]);
145
+ const last = Number(range?.[2] ?? range?.[1]);
146
+ if (range && last >= first)
147
+ return Array.from({ length: last - first + 1 }, (_, i) => first + i);
148
+ if (!/^(?:\d{1,2}\s*\/\s*\d{1,2}|MP)$/i.test(label.trim())) {
149
+ drift('A substitution has periods in an unknown format.');
150
+ }
151
+ return [];
152
+ }
129
153
  // An empty day is one cell spanning the table, e.g. "Keine Einträge!".
130
154
  function isPlaceholder(row) {
131
155
  const [only, ...rest] = cells(row);
@@ -1,8 +1,15 @@
1
+ import type { Rotation } from '../../rotation.js';
2
+ export type { Rotation };
1
3
  export interface Substitution {
2
4
  /** ISO calendar date. */
3
5
  date: string;
4
- /** As shown by the portal, e.g. "3 - 4". */
6
+ /** As shown by the portal, e.g. "3 - 4", "2/3" or "MP". */
5
7
  periods: string;
8
+ /**
9
+ * The lesson periods, e.g. [3, 4] for "3 - 4". Empty for break duties such as "2/3"
10
+ * (between periods 2 and 3) or "MP" (lunch break), and for labels ranzen cannot read.
11
+ */
12
+ periodNumbers: number[];
6
13
  classes: string | null;
7
14
  previousClasses: string | null;
8
15
  substitute: string | null;
@@ -27,8 +34,10 @@ export interface Notice {
27
34
  }
28
35
  export interface Day {
29
36
  date: string;
30
- /** The school's week label, e.g. "A-Woche". */
37
+ /** The school's week label, e.g. "A-Woche" or "WA-Woche". */
31
38
  week: string | null;
39
+ /** The week label as A/B rotation; null without a label or for one ranzen cannot read. */
40
+ rotation: Rotation | null;
32
41
  notices: Notice[];
33
42
  substitutions: Substitution[];
34
43
  /** Local portal time, e.g. "2026-10-16T11:58:40". */
@@ -0,0 +1,34 @@
1
+ import type { Drift } from '../app.js';
2
+ import type { SignalOption } from '../connection.js';
3
+ import type { KurswahlAccount, KurswahlSession } from './session.js';
4
+ import type { Rotation, Timetable } from './types.js';
5
+ export interface TimetableOptions extends SignalOption {
6
+ /** First day of a week the portal offers, as ISO date, e.g. "2025-08-25"; omit for the general plan. */
7
+ week?: string;
8
+ }
9
+ /** One signed-in Kurswahl session. Save it with exportState(), end it with logout(). */
10
+ export declare class KurswahlConnection {
11
+ #private;
12
+ constructor(session: KurswahlSession, onDrift?: (drift: Drift) => void);
13
+ get account(): KurswahlAccount;
14
+ /**
15
+ * The personal timetable. The general plan lists every lesson, both rotations included;
16
+ * a dated week shows only the lessons of that week's rotation.
17
+ */
18
+ timetable({ week, signal }?: TimetableOptions): Promise<Timetable>;
19
+ /**
20
+ * This week's rotation, read from the plan Kurswahl shows by default, which is the current week.
21
+ * Null when that week has no A/B lessons, e.g. for a student without alternating courses.
22
+ */
23
+ currentRotation({ signal }?: SignalOption): Promise<Rotation | null>;
24
+ /** Extends the session; throws SESSION_EXPIRED once Kurswahl has ended it. */
25
+ keepAlive({ signal }?: SignalOption): Promise<void>;
26
+ /** Pings Kurswahl on an interval, as its pages do; stops on dispose() or a lasting failure. */
27
+ keepWarm(intervalMs?: number): void;
28
+ /** Cookies, CSRF token and identity; never the password. Store it encrypted. */
29
+ exportState(): string;
30
+ /** Stops keepWarm() and cancels pending requests; the session stays valid for restore(). */
31
+ dispose(): void;
32
+ /** Leaves through the logout link, then disposes. */
33
+ logout({ signal }?: SignalOption): Promise<void>;
34
+ }
@@ -0,0 +1,126 @@
1
+ import { fail, isRanzenError, layoutChanged } from '../errors.js';
2
+ import { positive } from '../util.js';
3
+ import { parseHtml } from '../html.js';
4
+ import { isGeneralPlan, parseTimetable, timetableDatabase } from './parse.js';
5
+ import { writeKurswahlState } from './state.js';
6
+ /** One signed-in Kurswahl session. Save it with exportState(), end it with logout(). */
7
+ export class KurswahlConnection {
8
+ #session;
9
+ #onDrift;
10
+ #drifted = new Set();
11
+ #heartbeat;
12
+ #beating = false;
13
+ constructor(session, onDrift) {
14
+ this.#session = session;
15
+ this.#onDrift = onDrift;
16
+ }
17
+ get account() {
18
+ return this.#session.account;
19
+ }
20
+ /**
21
+ * The personal timetable. The general plan lists every lesson, both rotations included;
22
+ * a dated week shows only the lessons of that week's rotation.
23
+ */
24
+ async timetable({ week, signal } = {}) {
25
+ const value = week === undefined ? '0' : weekValue(week);
26
+ const session = this.#session;
27
+ // The timetable form names its database; the first visit learns it.
28
+ if (!session.database) {
29
+ const first = await session.page('stundenplan.php', {}, signal);
30
+ session.database = timetableDatabase(parseHtml(first.text));
31
+ }
32
+ const { text } = await session.page('stundenplan.php', { woche: value, db_name: session.database, show_optimierung: 'false' }, signal);
33
+ const timetable = parseTimetable(text, (detail) => this.#drift(detail));
34
+ session.database = timetable.database;
35
+ if (week !== undefined && timetable.week?.start !== week) {
36
+ throw fail('NOT_FOUND', 'Kurswahl Online does not offer this week.');
37
+ }
38
+ // A single week holds only one rotation, so passing it off as the general plan would lose lessons.
39
+ if (week === undefined && !isGeneralPlan(text))
40
+ throw layoutChanged('the general plan');
41
+ return timetable;
42
+ }
43
+ /**
44
+ * This week's rotation, read from the plan Kurswahl shows by default, which is the current week.
45
+ * Null when that week has no A/B lessons, e.g. for a student without alternating courses.
46
+ */
47
+ async currentRotation({ signal } = {}) {
48
+ const { text } = await this.#session.page('stundenplan.php', {}, signal);
49
+ const timetable = parseTimetable(text, (detail) => this.#drift(detail));
50
+ this.#session.database = timetable.database;
51
+ if (timetable.week || isGeneralPlan(text))
52
+ throw layoutChanged('the current week');
53
+ const rotations = new Set(timetable.lessons.map((lesson) => lesson.rotation));
54
+ rotations.delete(null);
55
+ if (rotations.size > 1)
56
+ throw layoutChanged('a single rotation in the current week');
57
+ return [...rotations][0] ?? null;
58
+ }
59
+ /** Extends the session; throws SESSION_EXPIRED once Kurswahl has ended it. */
60
+ async keepAlive({ signal } = {}) {
61
+ await this.#session.ajax('index.php', { ajax: 'keepalive' }, signal);
62
+ }
63
+ /** Pings Kurswahl on an interval, as its pages do; stops on dispose() or a lasting failure. */
64
+ keepWarm(intervalMs = 60_000) {
65
+ this.#session.ensureOpen();
66
+ positive(intervalMs, 'intervalMs');
67
+ clearInterval(this.#heartbeat);
68
+ this.#heartbeat = setInterval(() => {
69
+ if (this.#beating)
70
+ return;
71
+ this.#beating = true;
72
+ this.keepAlive()
73
+ .catch((error) => {
74
+ if (!isRanzenError(error) || !error.retryable)
75
+ clearInterval(this.#heartbeat);
76
+ })
77
+ .finally(() => (this.#beating = false));
78
+ }, intervalMs);
79
+ this.#heartbeat.unref();
80
+ }
81
+ /** Cookies, CSRF token and identity; never the password. Store it encrypted. */
82
+ exportState() {
83
+ const session = this.#session;
84
+ session.ensureOpen();
85
+ return writeKurswahlState({
86
+ account: session.account,
87
+ token: session.token,
88
+ database: session.database,
89
+ cookies: session.transport.jar.snapshot()
90
+ });
91
+ }
92
+ /** Stops keepWarm() and cancels pending requests; the session stays valid for restore(). */
93
+ dispose() {
94
+ clearInterval(this.#heartbeat);
95
+ this.#heartbeat = undefined;
96
+ this.#session.dispose();
97
+ }
98
+ /** Leaves through the logout link, then disposes. */
99
+ async logout({ signal } = {}) {
100
+ try {
101
+ await this.#session.leave(signal);
102
+ }
103
+ finally {
104
+ this.dispose();
105
+ }
106
+ }
107
+ // Once per kind and connection, so a timetable read in a loop does not flood the hook.
108
+ #drift(detail) {
109
+ if (!this.#onDrift || this.#drifted.has(detail))
110
+ return;
111
+ this.#drifted.add(detail);
112
+ try {
113
+ this.#onDrift({ app: 'kurswahl', detail });
114
+ }
115
+ catch {
116
+ // A failing log hook must not fail a read that succeeded.
117
+ }
118
+ }
119
+ }
120
+ // "2025-08-25" → "25_08_2025", the portal's week value.
121
+ function weekValue(week) {
122
+ const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(week);
123
+ if (!match)
124
+ throw fail('INVALID_OPTION', 'week must be an ISO date such as "2025-08-25".');
125
+ return `${match[3]}_${match[2]}_${match[1]}`;
126
+ }
@@ -0,0 +1,30 @@
1
+ import type { Drift } from '../app.js';
2
+ import type { SignalOption } from '../connection.js';
3
+ import { type FetchFunction } from '../transport/http.js';
4
+ import { KurswahlConnection } from './connection.js';
5
+ import { type KurswahlCredentials } from './sign-in.js';
6
+ import type { School } from './types.js';
7
+ export { KurswahlConnection, type TimetableOptions } from './connection.js';
8
+ export type { KurswahlAccount } from './session.js';
9
+ export type { KurswahlCredentials } from './sign-in.js';
10
+ export type * from './types.js';
11
+ export interface KurswahlOptions {
12
+ /** Replaces the global fetch, e.g. for a proxy or tests. */
13
+ fetch?: FetchFunction;
14
+ /** Must look like a browser's, or Kurswahl Online refuses; defaults to a current Firefox. */
15
+ userAgent?: string;
16
+ /** Milliseconds per request, including the wait for each body chunk; defaults to 15000. */
17
+ timeoutMs?: number;
18
+ /** Called once per connection for each kind of drift; log it to learn that ranzen needs an update. */
19
+ onDrift?: (drift: Drift) => void;
20
+ }
21
+ export interface Kurswahl {
22
+ /** Every school on Kurswahl Online; no sign-in needed. */
23
+ schools(options?: SignalOption): Promise<School[]>;
24
+ /** Signs in like the login page does, Argon2 hashing included (about a second of CPU). */
25
+ login(credentials: KurswahlCredentials, options?: SignalOption): Promise<KurswahlConnection>;
26
+ /** Validates and rebuilds a connection from exportState() without any request. */
27
+ restore(state: string): KurswahlConnection;
28
+ }
29
+ /** A Kurswahl Online client, independent of any Schulportal connection; creating it makes no request. */
30
+ export declare function createKurswahl(options?: KurswahlOptions): Kurswahl;