chuvsu-js 5.4.0 → 5.5.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.
Files changed (76) hide show
  1. package/README.md +32 -3
  2. package/dist/common/http.d.ts +3 -1
  3. package/dist/common/http.js +9 -2
  4. package/dist/{tt/utils → common}/lesson-type.d.ts +4 -2
  5. package/dist/{tt/utils → common}/lesson-type.js +17 -2
  6. package/dist/core.d.ts +13 -5
  7. package/dist/core.js +7 -2
  8. package/dist/index.d.ts +1 -0
  9. package/dist/index.js +1 -0
  10. package/dist/lk/client.d.ts +23 -1
  11. package/dist/lk/client.js +95 -0
  12. package/dist/lk/parse/grade-value.d.ts +4 -0
  13. package/dist/lk/parse/grade-value.js +16 -0
  14. package/dist/lk/parse/portfolio-content.d.ts +10 -0
  15. package/dist/lk/parse/portfolio-content.js +116 -0
  16. package/dist/lk/parse/portfolio-grades.d.ts +8 -0
  17. package/dist/lk/parse/portfolio-grades.js +41 -0
  18. package/dist/lk/parse/portfolio-performance.d.ts +2 -0
  19. package/dist/lk/parse/portfolio-performance.js +44 -0
  20. package/dist/lk/parse/portfolio.d.ts +6 -0
  21. package/dist/lk/parse/portfolio.js +64 -0
  22. package/dist/lk/parse/webinar-lesson.d.ts +7 -0
  23. package/dist/lk/parse/webinar-lesson.js +28 -0
  24. package/dist/lk/parse/webinars.d.ts +3 -0
  25. package/dist/lk/parse/webinars.js +67 -0
  26. package/dist/lk/portfolio-types.d.ts +113 -0
  27. package/dist/lk/portfolio-types.js +1 -0
  28. package/dist/lk/types.d.ts +29 -0
  29. package/dist/{tt → lk}/webinars.d.ts +3 -1
  30. package/dist/lk/webinars.js +52 -0
  31. package/dist/parsers.d.ts +3 -1
  32. package/dist/parsers.js +3 -1
  33. package/dist/tt/client.d.ts +1 -11
  34. package/dist/tt/client.js +1 -45
  35. package/dist/tt/domain/schedule.js +5 -1
  36. package/dist/tt/domain/substitution-occurrences.d.ts +3 -0
  37. package/dist/tt/domain/substitution-occurrences.js +75 -0
  38. package/dist/tt/domain/types.d.ts +1 -1
  39. package/dist/tt/observations.js +2 -1
  40. package/dist/tt/parse/index.d.ts +0 -1
  41. package/dist/tt/parse/index.js +0 -1
  42. package/dist/tt/types.d.ts +0 -21
  43. package/dist/tt/utils/index.d.ts +0 -1
  44. package/dist/tt/utils/index.js +0 -1
  45. package/dist/webinar/client.d.ts +52 -0
  46. package/dist/webinar/client.js +184 -0
  47. package/dist/webinar/ddp.d.ts +31 -0
  48. package/dist/webinar/ddp.js +208 -0
  49. package/dist/webinar/events.d.ts +6 -0
  50. package/dist/webinar/events.js +38 -0
  51. package/dist/webinar/gateway.d.ts +30 -0
  52. package/dist/webinar/gateway.js +114 -0
  53. package/dist/webinar/media-protocol.d.ts +9 -0
  54. package/dist/webinar/media-protocol.js +24 -0
  55. package/dist/webinar/media-types.d.ts +10 -0
  56. package/dist/webinar/media-types.js +1 -0
  57. package/dist/webinar/media.d.ts +21 -0
  58. package/dist/webinar/media.js +76 -0
  59. package/dist/webinar/parse.d.ts +14 -0
  60. package/dist/webinar/parse.js +113 -0
  61. package/dist/webinar/playback.d.ts +32 -0
  62. package/dist/webinar/playback.js +188 -0
  63. package/dist/webinar/socket.d.ts +3 -0
  64. package/dist/webinar/socket.js +18 -0
  65. package/dist/webinar/state.d.ts +4 -0
  66. package/dist/webinar/state.js +98 -0
  67. package/dist/webinar/types.d.ts +148 -0
  68. package/dist/webinar/types.js +12 -0
  69. package/docs/student-portal.md +151 -0
  70. package/docs/testing.md +13 -0
  71. package/docs/v5-migration.md +25 -2
  72. package/docs/webinar.md +145 -0
  73. package/package.json +2 -2
  74. package/dist/tt/parse/webinars.d.ts +0 -2
  75. package/dist/tt/parse/webinars.js +0 -97
  76. package/dist/tt/webinars.js +0 -39
package/README.md CHANGED
@@ -5,8 +5,8 @@
5
5
 
6
6
  Типизированная библиотека для сервисов ЧГУ им. И. Н. Ульянова:
7
7
 
8
- - `tt.chuvsu.ru` — расписания групп, преподавателей, аудиторий и вебинары;
9
- - `lk.chuvsu.ru` — личный кабинет студента.
8
+ - `tt.chuvsu.ru` — расписания групп, преподавателей, аудиторий;
9
+ - `lk.chuvsu.ru` — личный кабинет, вебинары и портфолио студента.
10
10
 
11
11
  В версии 5 расписание хранится в едином каноническом репозитории. Если одна
12
12
  пара встречается в расписаниях группы, преподавателя и аудитории, она сохраняет
@@ -257,7 +257,7 @@ const floorPlan = await client.getRoomFloorPlan(roomId);
257
257
  ## Личный кабинет
258
258
 
259
259
  ```ts
260
- import { StudentPortalClient } from "chuvsu-js";
260
+ import { StudentPortalClient, attachWebinars } from "chuvsu-js";
261
261
 
262
262
  const portal = new StudentPortalClient({ cache: 60_000 });
263
263
  await portal.login({ email: "student@example.com", password: "password" });
@@ -265,8 +265,37 @@ await portal.login({ email: "student@example.com", password: "password" });
265
265
  const profile = await portal.getProfile();
266
266
  const photo = await portal.getProfilePhoto();
267
267
  const groupId = await portal.getTimetableGroupId();
268
+ const webinars = await portal.getWebinars(); // LK current day
269
+ const page = await portal.getWebinarPage(); // date + availableDates + webinars
270
+ const portfolio = await portal.getPortfolio(); // own URL discovered from home
271
+ // Optional listing filter: { date: "2026-10-12" } (LocalDate)
272
+
273
+ const withWebinars = attachWebinars(schedule.today(), webinars);
274
+ const active = webinars.find((webinar) => webinar.joinAvailable);
275
+ if (active?.id) {
276
+ const url = await portal.getWebinarJoinUrl({ webinarId: active.id });
277
+ }
268
278
  ```
269
279
 
280
+ Webinar methods belong to `StudentPortalClient`; removed from `TimetableClient`.
281
+ `id` is `null` when LK exposes no join button. `title` is the topic;
282
+ `subject` is the discipline. Completed and not-yet-started rows remain in the list.
283
+ `findWebinar` attaches only a unique match by actual date, time, subject,
284
+ lesson type and known group/subgroup/teacher. `findWebinars` returns ambiguous
285
+ candidates for manual selection. Missing dates never match. Join URLs are resolved
286
+ on demand through LK; no webinar window opens automatically.
287
+
288
+ `getPortfolio()` returns identity fields, semester grades, control weeks,
289
+ attendance, planned activities and all portfolio tabs with document links.
290
+ Webinar/journal types and assessments use `LessonType`; grades are numeric,
291
+ credits are booleans, missing grades are `null`.
292
+ Referral controls are parsed as metadata only; no orders are submitted.
293
+ API details and examples: [docs/student-portal.md](docs/student-portal.md).
294
+
295
+ Live participant sessions, users, chat, presentation downloads and explicit room
296
+ actions: [docs/webinar.md](docs/webinar.md). Session setup is backend-only;
297
+ live state can connect directly from a custom browser UI.
298
+
270
299
  ## Разработка
271
300
 
272
301
  ```bash
@@ -1,3 +1,4 @@
1
+ import { WebSocket } from "undici";
1
2
  export interface HttpResponse {
2
3
  status: number;
3
4
  body: string;
@@ -14,6 +15,7 @@ export declare class HttpClient {
14
15
  private saveCookies;
15
16
  get(url: string, followRedirects?: boolean): Promise<HttpResponse>;
16
17
  getBuffer(url: string): Promise<Buffer>;
17
- getBufferResponse(url: string): Promise<HttpBufferResponse>;
18
+ getBufferResponse(url: string, followRedirects?: boolean): Promise<HttpBufferResponse>;
19
+ createWebSocket(url: string): InstanceType<typeof WebSocket>;
18
20
  post(url: string, data: Record<string, string>, followRedirects?: boolean): Promise<HttpResponse>;
19
21
  }
@@ -1,4 +1,4 @@
1
- import { Agent, fetch } from "undici";
1
+ import { Agent, fetch, WebSocket } from "undici";
2
2
  import { CHUVSU_CA_CERTS } from "./certs.js";
3
3
  const agent = new Agent({
4
4
  connect: { ca: CHUVSU_CA_CERTS },
@@ -35,10 +35,11 @@ export class HttpClient {
35
35
  async getBuffer(url) {
36
36
  return (await this.getBufferResponse(url)).body;
37
37
  }
38
- async getBufferResponse(url) {
38
+ async getBufferResponse(url, followRedirects = true) {
39
39
  const res = await fetch(url, {
40
40
  method: "GET",
41
41
  headers: { Cookie: this.cookieHeader() },
42
+ redirect: followRedirects ? "follow" : "manual",
42
43
  dispatcher: agent,
43
44
  });
44
45
  this.saveCookies(res.headers);
@@ -48,6 +49,12 @@ export class HttpClient {
48
49
  contentType: res.headers.get("content-type") ?? undefined,
49
50
  };
50
51
  }
52
+ createWebSocket(url) {
53
+ return new WebSocket(url, {
54
+ dispatcher: agent,
55
+ headers: { Cookie: this.cookieHeader() },
56
+ });
57
+ }
51
58
  async post(url, data, followRedirects = true) {
52
59
  const body = new URLSearchParams(data).toString();
53
60
  const res = await fetch(url, {
@@ -11,7 +11,9 @@ export declare enum LessonType {
11
11
  Individual = 8,
12
12
  Group = 9,
13
13
  CourseProject = 10,
14
- Krp = 11
14
+ Krp = 11,
15
+ StateExam = 12,
16
+ ThesisDefense = 13
15
17
  }
16
- /** Convert portal short code into compact domain identifier. */
18
+ /** Convert portal short code or full assessment label into a domain identifier. */
17
19
  export declare function parseLessonType(code: string): LessonType;
@@ -13,6 +13,8 @@ export var LessonType;
13
13
  LessonType[LessonType["Group"] = 9] = "Group";
14
14
  LessonType[LessonType["CourseProject"] = 10] = "CourseProject";
15
15
  LessonType[LessonType["Krp"] = 11] = "Krp";
16
+ LessonType[LessonType["StateExam"] = 12] = "StateExam";
17
+ LessonType[LessonType["ThesisDefense"] = 13] = "ThesisDefense";
16
18
  })(LessonType || (LessonType = {}));
17
19
  const TYPE_BY_CODE = {
18
20
  лк: LessonType.Lecture,
@@ -26,8 +28,21 @@ const TYPE_BY_CODE = {
26
28
  гз: LessonType.Group,
27
29
  кп: LessonType.CourseProject,
28
30
  крп: LessonType.Krp,
31
+ лекция: LessonType.Lecture,
32
+ "практическое занятие": LessonType.Practical,
33
+ "лабораторная работа": LessonType.Laboratory,
34
+ консультация: LessonType.Consultation,
35
+ зачет: LessonType.Credit,
36
+ "зачет с оценкой": LessonType.GradedCredit,
37
+ "дифференцированный зачет": LessonType.GradedCredit,
38
+ экзамен: LessonType.Exam,
39
+ госэкзамен: LessonType.StateExam,
40
+ "государственный экзамен": LessonType.StateExam,
41
+ "защита выпускной квалификационной работы": LessonType.ThesisDefense,
42
+ "защита вкр": LessonType.ThesisDefense,
43
+ "курсовой проект": LessonType.CourseProject,
29
44
  };
30
- /** Convert portal short code into compact domain identifier. */
45
+ /** Convert portal short code or full assessment label into a domain identifier. */
31
46
  export function parseLessonType(code) {
32
- return TYPE_BY_CODE[code.trim().toLocaleLowerCase("ru-RU").replace(/\.$/u, "")] ?? LessonType.Unknown;
47
+ return TYPE_BY_CODE[code.trim().toLocaleLowerCase("ru-RU").replace(/ё/gu, "е").replace(/\s+/gu, " ").replace(/\.$/u, "")] ?? LessonType.Unknown;
33
48
  }
package/dist/core.d.ts CHANGED
@@ -1,10 +1,18 @@
1
+ export { LessonType, parseLessonType } from "./common/lesson-type.js";
1
2
  export * from "./tt/domain/index.js";
2
- export { attachWebinars, findWebinar } from "./tt/webinars.js";
3
- export type { LessonWithWebinar } from "./tt/webinars.js";
4
- export { getAdjacentSemester, getCompensatingWorkDays, getCurrentPeriod, getEffectiveHolidays, formatLocalDate, getHolidayTransfers, getSemesterStart, getSemesterWeeks, getStandardScheduleBlocks, getWeekNumber, getWeekdayName, isHoliday, isLocalDate, isSessionPeriod, LessonType, parseLessonType, parseLocalDate, RUSSIAN_HOLIDAYS, } from "./tt/utils/index.js";
3
+ export { attachWebinars, findWebinar, findWebinars } from "./lk/webinars.js";
4
+ export type { LessonWithWebinar } from "./lk/webinars.js";
5
+ export type * from "./lk/portfolio-types.js";
6
+ export { WebinarClient } from "./webinar/client.js";
7
+ export { WebinarMediaClient } from "./webinar/media.js";
8
+ export { WebinarPlayback } from "./webinar/playback.js";
9
+ export type * from "./webinar/media-types.js";
10
+ export { WebinarPermissionError, WebinarProtocolError } from "./webinar/types.js";
11
+ export type * from "./webinar/types.js";
12
+ export { getAdjacentSemester, getCompensatingWorkDays, getCurrentPeriod, getEffectiveHolidays, formatLocalDate, getHolidayTransfers, getSemesterStart, getSemesterWeeks, getStandardScheduleBlocks, getWeekNumber, getWeekdayName, isHoliday, isLocalDate, isSessionPeriod, parseLocalDate, RUSSIAN_HOLIDAYS, } from "./tt/utils/index.js";
5
13
  export type { Holiday, HolidayTransfer } from "./tt/utils/index.js";
6
14
  export { AuthError, EducationLevel, ParseError, AcademicPeriod, } from "./common/types.js";
7
15
  export type { LocalDate, Teacher, Time, TimeRange, WeekRange, } from "./common/types.js";
8
16
  export type { CacheAdapter, CacheEntry } from "./common/cache.js";
9
- export type { CacheConfig, DirectoryPreloadOptions, EntityResolutionStrategy, Faculty, GetScheduleOptions, Group, StandardScheduleBlock, Room, RoomInfo, SemesterWeek, TeacherInfo, TimetableClientOptions, Webinar, } from "./tt/types.js";
10
- export type { StudentPortalCacheConfig, StudentPortalClientOptions, StudentProfile, } from "./lk/types.js";
17
+ export type { CacheConfig, DirectoryPreloadOptions, EntityResolutionStrategy, Faculty, GetScheduleOptions, Group, StandardScheduleBlock, Room, RoomInfo, SemesterWeek, TeacherInfo, TimetableClientOptions, } from "./tt/types.js";
18
+ export type { StudentPortalCacheConfig, StudentPortalClientOptions, StudentProfile, Webinar, WebinarPage, } from "./lk/types.js";
package/dist/core.js CHANGED
@@ -1,5 +1,10 @@
1
1
  // Runtime-safe core for Node.js, browsers, Deno, and workers.
2
+ export { LessonType, parseLessonType } from "./common/lesson-type.js";
2
3
  export * from "./tt/domain/index.js";
3
- export { attachWebinars, findWebinar } from "./tt/webinars.js";
4
- export { getAdjacentSemester, getCompensatingWorkDays, getCurrentPeriod, getEffectiveHolidays, formatLocalDate, getHolidayTransfers, getSemesterStart, getSemesterWeeks, getStandardScheduleBlocks, getWeekNumber, getWeekdayName, isHoliday, isLocalDate, isSessionPeriod, LessonType, parseLessonType, parseLocalDate, RUSSIAN_HOLIDAYS, } from "./tt/utils/index.js";
4
+ export { attachWebinars, findWebinar, findWebinars } from "./lk/webinars.js";
5
+ export { WebinarClient } from "./webinar/client.js";
6
+ export { WebinarMediaClient } from "./webinar/media.js";
7
+ export { WebinarPlayback } from "./webinar/playback.js";
8
+ export { WebinarPermissionError, WebinarProtocolError } from "./webinar/types.js";
9
+ export { getAdjacentSemester, getCompensatingWorkDays, getCurrentPeriod, getEffectiveHolidays, formatLocalDate, getHolidayTransfers, getSemesterStart, getSemesterWeeks, getStandardScheduleBlocks, getWeekNumber, getWeekdayName, isHoliday, isLocalDate, isSessionPeriod, parseLocalDate, RUSSIAN_HOLIDAYS, } from "./tt/utils/index.js";
5
10
  export { AuthError, EducationLevel, ParseError, AcademicPeriod, } from "./common/types.js";
package/dist/index.d.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  export * from "./core.js";
2
2
  export { StudentPortalClient } from "./lk/client.js";
3
+ export { WebinarGateway } from "./webinar/gateway.js";
3
4
  export { TimetableClient } from "./tt/client.js";
4
5
  export * from "./parsers.js";
5
6
  export type { BlobAdapter, BlobPutOptions, } from "./common/cache.js";
package/dist/index.js CHANGED
@@ -1,4 +1,5 @@
1
1
  export * from "./core.js";
2
2
  export { StudentPortalClient } from "./lk/client.js";
3
+ export { WebinarGateway } from "./webinar/gateway.js";
3
4
  export { TimetableClient } from "./tt/client.js";
4
5
  export * from "./parsers.js";
@@ -1,4 +1,7 @@
1
- import type { StudentPortalClientOptions, StudentProfile } from "./types.js";
1
+ import { WebinarGateway } from "../webinar/gateway.js";
2
+ import type { StudentPortfolio } from "./portfolio-types.js";
3
+ import type { LocalDate } from "../common/types.js";
4
+ import type { StudentPortalClientOptions, StudentProfile, Webinar, WebinarPage } from "./types.js";
2
5
  export declare class StudentPortalClient {
3
6
  private http;
4
7
  private credentials;
@@ -16,4 +19,23 @@ export declare class StudentPortalClient {
16
19
  getProfile(): Promise<StudentProfile>;
17
20
  getProfilePhoto(): Promise<Buffer>;
18
21
  getTimetableGroupId(): Promise<number | null>;
22
+ /** No date means the portal's current day. Date POST only filters the listing. */
23
+ getWebinarPage(opts?: {
24
+ date?: LocalDate;
25
+ }): Promise<WebinarPage>;
26
+ getWebinars(opts?: {
27
+ date?: LocalDate;
28
+ }): Promise<Webinar[]>;
29
+ /** Creates a BBB participant session. May register the student's room presence. */
30
+ openWebinar(opts: {
31
+ webinarId: string | number;
32
+ }): Promise<WebinarGateway>;
33
+ /** Discovers the current student's portfolio through the home navigation. */
34
+ getPortfolio(): Promise<StudentPortfolio>;
35
+ getPortfolioUrl(): Promise<string>;
36
+ /** Resolves a URL only. Does not open or connect to the webinar. */
37
+ getWebinarJoinUrl(opts: {
38
+ webinarId: string | number;
39
+ }): Promise<string>;
40
+ private authPost;
19
41
  }
package/dist/lk/client.js CHANGED
@@ -2,6 +2,10 @@ import { HttpClient, } from "../common/http.js";
2
2
  import { HybridCache } from "../common/cache.js";
3
3
  import { AuthError, ParseError } from "../common/types.js";
4
4
  import { extractScriptValues } from "./parse.js";
5
+ import { parseWebinarPage } from "./parse/webinars.js";
6
+ import { parsePortfolio, parsePortfolioUrl } from "./parse/portfolio.js";
7
+ import { WebinarGateway } from "../webinar/gateway.js";
8
+ import { isLocalDate } from "../tt/utils/date.js";
5
9
  const BASE = "https://lk.chuvsu.ru";
6
10
  const LOGIN_URL = `${BASE}/info/login.php`;
7
11
  const STUDENT_BASE = `${BASE}/student`;
@@ -10,6 +14,8 @@ function makeUniformCacheConfig(ttl) {
10
14
  profile: ttl,
11
15
  profilePhoto: ttl,
12
16
  timetableGroupId: ttl,
17
+ webinars: ttl,
18
+ portfolio: ttl,
13
19
  };
14
20
  }
15
21
  export class StudentPortalClient {
@@ -140,4 +146,93 @@ export class StudentPortalClient {
140
146
  await this.cache?.set("timetableGroupId", "self", groupId);
141
147
  return groupId;
142
148
  }
149
+ /** No date means the portal's current day. Date POST only filters the listing. */
150
+ async getWebinarPage(opts) {
151
+ if (opts?.date !== undefined && !isLocalDate(opts.date)) {
152
+ throw new RangeError("Invalid webinar date");
153
+ }
154
+ const today = new Intl.DateTimeFormat("sv-SE", { timeZone: "Europe/Moscow" }).format(new Date());
155
+ const key = `v2:${opts?.date ?? `today:${today}`}`;
156
+ const cached = await this.cache?.get("webinars", key);
157
+ if (cached)
158
+ return cached;
159
+ const url = `${STUDENT_BASE}/mywebinars.php`;
160
+ const response = opts?.date
161
+ ? await this.authPost(url, { day: opts.date })
162
+ : await this.authGet(url);
163
+ const page = parseWebinarPage(response.body);
164
+ if (opts?.date && page.date !== opts.date) {
165
+ throw new ParseError("LK did not return the requested webinar date");
166
+ }
167
+ await this.cache?.set("webinars", key, page);
168
+ return page;
169
+ }
170
+ async getWebinars(opts) {
171
+ return (await this.getWebinarPage(opts)).webinars;
172
+ }
173
+ /** Creates a BBB participant session. May register the student's room presence. */
174
+ async openWebinar(opts) {
175
+ const gateway = new WebinarGateway();
176
+ await gateway.openSession({ joinUrl: await this.getWebinarJoinUrl(opts) });
177
+ return gateway;
178
+ }
179
+ /** Discovers the current student's portfolio through the home navigation. */
180
+ async getPortfolio() {
181
+ const cached = await this.cache?.get("portfolio", "v2:self");
182
+ if (cached)
183
+ return cached;
184
+ const home = await this.authGet(`${STUDENT_BASE}/index.php`);
185
+ const target = parsePortfolioUrl(home.body);
186
+ const { body } = await this.authGet(target);
187
+ const portfolio = parsePortfolio(body, { url: target });
188
+ await this.cache?.set("portfolio", "v2:self", portfolio);
189
+ return portfolio;
190
+ }
191
+ async getPortfolioUrl() {
192
+ return (await this.getPortfolio()).url;
193
+ }
194
+ /** Resolves a URL only. Does not open or connect to the webinar. */
195
+ async getWebinarJoinUrl(opts) {
196
+ if (!/^[1-9]\d*$/u.test(String(opts.webinarId))) {
197
+ throw new RangeError("Webinar ID must be a positive integer");
198
+ }
199
+ const { body } = await this.authPost(`${STUDENT_BASE}/joinweb.php`, {
200
+ idw: String(opts.webinarId),
201
+ });
202
+ let data;
203
+ try {
204
+ data = JSON.parse(body);
205
+ }
206
+ catch {
207
+ throw new ParseError("LK webinar join returned invalid JSON");
208
+ }
209
+ if (data?.mes !== "SUCCESS" || typeof data.url !== "string") {
210
+ throw new ParseError("LK webinar join returned no URL");
211
+ }
212
+ let url;
213
+ try {
214
+ url = new URL(data.url);
215
+ }
216
+ catch {
217
+ throw new ParseError("LK webinar join returned an invalid URL");
218
+ }
219
+ if (!["https:", "http:"].includes(url.protocol)) {
220
+ throw new ParseError("LK webinar join returned an unsafe URL");
221
+ }
222
+ return data.url;
223
+ }
224
+ async authPost(url, data) {
225
+ let response = await this.http.post(url, data);
226
+ if (this.credentials && this.isSessionExpired(response.body)) {
227
+ await this.login(this.credentials);
228
+ response = await this.http.post(url, data);
229
+ }
230
+ if (this.isSessionExpired(response.body)) {
231
+ throw new AuthError("LK request returned an authentication page");
232
+ }
233
+ if (response.status < 200 || response.status >= 300) {
234
+ throw new Error(`LK request failed with HTTP ${response.status}: ${url}`);
235
+ }
236
+ return response;
237
+ }
143
238
  }
@@ -0,0 +1,4 @@
1
+ import type { PortfolioGradeValue } from "../portfolio-types.js";
2
+ /** Missing/unrecognized grades stay null; numeric zero remains zero. */
3
+ export declare function parseNumericGrade(value: string): number | null;
4
+ export declare function parseGradeValue(value: string): PortfolioGradeValue;
@@ -0,0 +1,16 @@
1
+ /** Missing/unrecognized grades stay null; numeric zero remains zero. */
2
+ export function parseNumericGrade(value) {
3
+ const match = value.trim().match(/^(\d+(?:[.,]\d+)?)(?:\s*\([^()]*\))?$/u);
4
+ if (!match)
5
+ return null;
6
+ const grade = Number(match[1].replace(",", "."));
7
+ return Number.isFinite(grade) ? grade : null;
8
+ }
9
+ export function parseGradeValue(value) {
10
+ const normalized = value.trim().toLocaleLowerCase("ru-RU").replace(/ё/gu, "е").replace(/\s+/gu, " ");
11
+ if (normalized === "зачтено")
12
+ return true;
13
+ if (normalized === "не зачтено")
14
+ return false;
15
+ return parseNumericGrade(normalized);
16
+ }
@@ -0,0 +1,10 @@
1
+ import type { PortfolioCell, PortfolioContent, PortfolioLink, PortfolioTable } from "../portfolio-types.js";
2
+ export declare function resolvePortfolioUrl(raw: string | null, base: string): string | undefined;
3
+ /** Ignore executable code and ordering/edit controls; retain line boundaries. */
4
+ export declare function displayedText(element: Element): string;
5
+ export declare function portfolioLinks(element: Element, base: string): PortfolioLink[];
6
+ export declare function portfolioNotes(element: Element): string[];
7
+ export declare function parsePortfolioTable(table: Element, base: string): PortfolioTable;
8
+ /** Expand both spans so month/day/slot headers align with attendance cells. */
9
+ export declare function expandPortfolioRows(rows: PortfolioCell[][]): PortfolioCell[][];
10
+ export declare function parsePortfolioContent(parent: Element, base: string): PortfolioContent[];
@@ -0,0 +1,116 @@
1
+ import { text } from "../../common/parse.js";
2
+ export function resolvePortfolioUrl(raw, base) {
3
+ if (!raw)
4
+ return undefined;
5
+ try {
6
+ const url = new URL(raw, base);
7
+ return ["http:", "https:"].includes(url.protocol) ? url.href : undefined;
8
+ }
9
+ catch {
10
+ return undefined;
11
+ }
12
+ }
13
+ /** Ignore executable code and ordering/edit controls; retain line boundaries. */
14
+ export function displayedText(element) {
15
+ const clone = element.cloneNode(true);
16
+ for (const node of clone.querySelectorAll("script,style,button,input,select,textarea"))
17
+ node.remove();
18
+ for (const br of clone.querySelectorAll("br"))
19
+ br.replaceWith("\n");
20
+ return text(clone).replace(/[^\S\n]+/gu, " ").replace(/ *\n */gu, "\n").trim();
21
+ }
22
+ export function portfolioLinks(element, base) {
23
+ return [...element.querySelectorAll("a[href]")].flatMap((anchor) => {
24
+ const raw = anchor.getAttribute("href");
25
+ if (raw?.startsWith("#"))
26
+ return [];
27
+ const url = resolvePortfolioUrl(raw, base);
28
+ return url ? [{ text: displayedText(anchor), url, title: anchor.getAttribute("title") ?? undefined, content: parsePortfolioContent(anchor, base) }] : [];
29
+ });
30
+ }
31
+ export function portfolioNotes(element) {
32
+ return [...new Set([element, ...element.querySelectorAll("[title]")]
33
+ .filter((node) => !node.matches("button,input,select,textarea"))
34
+ .map((node) => node.getAttribute("title")?.trim()).filter((value) => !!value))];
35
+ }
36
+ function span(element, name) {
37
+ const value = Number(element.getAttribute(name) ?? 1);
38
+ return Number.isInteger(value) && value > 0 ? value : 1;
39
+ }
40
+ export function parsePortfolioTable(table, base) {
41
+ const rows = [...table.querySelectorAll("tr")].filter((row) => row.closest("table") === table);
42
+ return { rows: rows.map((row) => [...row.children].filter((cell) => cell.matches("td,th"))
43
+ .map((cell) => ({
44
+ text: displayedText(cell), header: cell.tagName === "TH",
45
+ colspan: span(cell, "colspan"), rowspan: span(cell, "rowspan"),
46
+ links: portfolioLinks(cell, base), notes: portfolioNotes(cell), content: parsePortfolioContent(cell, base),
47
+ }))) };
48
+ }
49
+ /** Expand both spans so month/day/slot headers align with attendance cells. */
50
+ export function expandPortfolioRows(rows) {
51
+ const grid = [];
52
+ rows.forEach((row, rowIndex) => {
53
+ const target = grid[rowIndex] ??= [];
54
+ let column = 0;
55
+ for (const cell of row) {
56
+ while (target[column])
57
+ column++;
58
+ for (let r = 0; r < cell.rowspan; r++) {
59
+ const output = grid[rowIndex + r] ??= [];
60
+ for (let c = 0; c < cell.colspan; c++)
61
+ output[column + c] = cell;
62
+ }
63
+ column += cell.colspan;
64
+ }
65
+ });
66
+ return grid;
67
+ }
68
+ export function parsePortfolioContent(parent, base) {
69
+ const result = [];
70
+ for (const node of parent.childNodes) {
71
+ if (node.nodeType === 3) {
72
+ const value = node.textContent?.replace(/\s+/gu, " ").trim();
73
+ if (value)
74
+ result.push({ kind: "text", text: value });
75
+ continue;
76
+ }
77
+ if (node.nodeType !== 1)
78
+ continue;
79
+ const element = node;
80
+ if (element.matches("script,style,input,select,textarea"))
81
+ continue;
82
+ const tag = element.tagName.toLowerCase();
83
+ if (/^h[1-6]$/u.test(tag)) {
84
+ result.push({ kind: "heading", level: Number(tag[1]), text: displayedText(element) });
85
+ }
86
+ else if (tag === "table") {
87
+ result.push({ kind: "table", table: parsePortfolioTable(element, base) });
88
+ }
89
+ else if (tag === "a" || tag === "button") {
90
+ const raw = tag === "a" ? element.getAttribute("href") :
91
+ element.getAttribute("onclick")?.match(/^\s*window\.open\(\s*['"]([^'"]+)['"]\s*\);?\s*$/u)?.[1];
92
+ if (!raw || raw.startsWith("#"))
93
+ continue;
94
+ const url = resolvePortfolioUrl(raw, base);
95
+ if (url)
96
+ result.push({ kind: "link", link: { text: displayedText(element), url, title: element.getAttribute("title") ?? undefined, content: parsePortfolioContent(element, base) } });
97
+ }
98
+ else if (tag === "img") {
99
+ const url = resolvePortfolioUrl(element.getAttribute("src"), base);
100
+ if (url)
101
+ result.push({ kind: "image", url, alt: element.getAttribute("alt") ?? "", title: element.getAttribute("title") ?? undefined });
102
+ }
103
+ else {
104
+ // Tab labels are retained as group labels rather than duplicate fragment links.
105
+ if (element.getAttribute("role") === "tablist")
106
+ continue;
107
+ const label = element.getAttribute("role") === "tabpanel" && element.id
108
+ ? text([...element.ownerDocument.querySelectorAll('a[href^="#"]')].find((anchor) => anchor.getAttribute("href") === `#${element.id}`) ?? null)
109
+ : undefined;
110
+ const content = parsePortfolioContent(element, base);
111
+ if (content.length)
112
+ result.push({ kind: "group", label, content });
113
+ }
114
+ }
115
+ return result;
116
+ }
@@ -0,0 +1,8 @@
1
+ import type { PortfolioControlWeek, PortfolioGrade } from "../portfolio-types.js";
2
+ /** Accordion sections are headed with Семестр N; IDs are randomly generated. */
3
+ export declare function semesterBlocks(panel: Element): {
4
+ semester: number;
5
+ body: Element;
6
+ }[];
7
+ export declare function parsePortfolioGrades(panel: Element): PortfolioGrade[];
8
+ export declare function parsePortfolioControlWeeks(panel: Element): PortfolioControlWeek[];
@@ -0,0 +1,41 @@
1
+ import { text } from "../../common/parse.js";
2
+ import { displayedText, portfolioNotes } from "./portfolio-content.js";
3
+ import { parseLessonType } from "../../common/lesson-type.js";
4
+ import { parseGradeValue, parseNumericGrade } from "./grade-value.js";
5
+ function referral(row) {
6
+ const onclick = row.querySelector('[onclick*="iexlist"]')?.getAttribute("onclick");
7
+ const match = onclick?.match(/iexlist\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*,\s*['"]([^'"]*)['"]\s*\)/u);
8
+ return match ? {
9
+ semester: Number(match[1]), disciplineId: Number(match[2]), lessonTypeId: Number(match[3]),
10
+ type: Number(match[4]), key: Number(match[5]), code: match[6],
11
+ } : undefined;
12
+ }
13
+ /** Accordion sections are headed with Семестр N; IDs are randomly generated. */
14
+ export function semesterBlocks(panel) {
15
+ return [...panel.querySelectorAll("h3")].flatMap((heading) => {
16
+ const match = text(heading).match(/^Семестр\s+(\d+)$/iu);
17
+ const body = heading.nextElementSibling;
18
+ return match && body ? [{ semester: Number(match[1]), body }] : [];
19
+ });
20
+ }
21
+ export function parsePortfolioGrades(panel) {
22
+ return semesterBlocks(panel).flatMap(({ semester, body }) => [...body.querySelectorAll("tbody > tr")].flatMap((row) => {
23
+ const cells = [...row.children];
24
+ if (cells.length < 3)
25
+ return [];
26
+ const code = text(cells[0].querySelector(".red"));
27
+ const raw = displayedText(cells[0]);
28
+ const assessment = parseLessonType(raw.match(/\(([^()]*)\)\s*$/u)?.[1] ?? "");
29
+ const subject = raw.slice(code && raw.startsWith(code) ? code.length : 0)
30
+ .replace(/\s*\([^()]*\)\s*$/u, "").trim();
31
+ return [{ semester, code, subject, assessment, grade: parseGradeValue(displayedText(cells[2])), notes: portfolioNotes(cells[2]), referral: referral(row) }];
32
+ }));
33
+ }
34
+ export function parsePortfolioControlWeeks(panel) {
35
+ return semesterBlocks(panel).flatMap(({ semester, body }) => [...body.querySelectorAll("tbody > tr")].flatMap((row) => {
36
+ const cells = [...row.children];
37
+ if (!cells.length || cells.some((cell) => cell.tagName === "TH"))
38
+ return [];
39
+ return [{ semester, subject: displayedText(cells[0]), grades: cells.slice(1).map((cell) => parseNumericGrade(displayedText(cell))) }];
40
+ }));
41
+ }
@@ -0,0 +1,2 @@
1
+ import type { PortfolioPerformance } from "../portfolio-types.js";
2
+ export declare function parsePortfolioPerformance(panel: Element, base: string): PortfolioPerformance[];
@@ -0,0 +1,44 @@
1
+ import { text } from "../../common/parse.js";
2
+ import { expandPortfolioRows, parsePortfolioTable } from "./portfolio-content.js";
3
+ import { parseLessonType } from "../../common/lesson-type.js";
4
+ export function parsePortfolioPerformance(panel, base) {
5
+ return [...panel.querySelectorAll("h3")].flatMap((heading) => {
6
+ const body = heading.nextElementSibling;
7
+ if (!body?.querySelector("table.journtable"))
8
+ return [];
9
+ const performance = { subject: text(heading), attendance: [], activities: [] };
10
+ for (const table of body.querySelectorAll("table.journtable")) {
11
+ const parsed = parsePortfolioTable(table, base);
12
+ const headerCount = [...table.querySelectorAll("thead > tr")].length;
13
+ const headers = expandPortfolioRows(parsed.rows.slice(0, headerCount));
14
+ const values = parsed.rows.slice(headerCount).filter((row) => row.some((cell) => !cell.header));
15
+ if (/Пропуски занятий/iu.test(headers[0]?.[0]?.text ?? "") && headers.length >= 5) {
16
+ for (const row of values) {
17
+ row.forEach((cell, index) => {
18
+ const day = Number(headers[2]?.[index]?.text);
19
+ const slotNumber = Number(headers[3]?.[index]?.text);
20
+ if (!Number.isInteger(day) || day < 1 || day > 31 || !Number.isInteger(slotNumber) || slotNumber < 1)
21
+ return;
22
+ const typeRaw = headers[4]?.[index]?.text ?? "";
23
+ const subgroup = typeRaw.match(/\((\d+)\)/u)?.[1];
24
+ performance.attendance.push({
25
+ month: headers[1]?.[index]?.text ?? "", day, slotNumber,
26
+ type: parseLessonType(typeRaw.replace(/\s*\(\d+\)/u, "")),
27
+ subgroup: subgroup ? Number(subgroup) : undefined,
28
+ mark: cell.text, notes: cell.notes,
29
+ });
30
+ });
31
+ }
32
+ }
33
+ else if (/Запланированная активность/iu.test(headers[0]?.[0]?.text ?? "")) {
34
+ performance.activities.push({
35
+ teacher: headers[1]?.[0]?.text ?? "",
36
+ items: values.flatMap((row) => row.map((cell, index) => ({
37
+ title: headers.at(-1)?.[index]?.text ?? "", value: cell.text, notes: cell.notes, links: cell.links, content: cell.content,
38
+ }))),
39
+ });
40
+ }
41
+ }
42
+ return [performance];
43
+ });
44
+ }
@@ -0,0 +1,6 @@
1
+ import type { StudentPortfolio } from "../portfolio-types.js";
2
+ /** Only the portfolio landing route or index.php?id=N can be discovered. */
3
+ export declare function parsePortfolioUrl(html: string): string;
4
+ export declare function parsePortfolio(html: string, opts?: {
5
+ url?: string;
6
+ }): StudentPortfolio;