@mo7yw4ng/openape 1.0.5 → 2.0.3

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 (152) hide show
  1. package/bin/openape +29 -0
  2. package/bin/openape.js +29 -0
  3. package/package.json +22 -28
  4. package/LICENSE +0 -21
  5. package/README.md +0 -135
  6. package/esm/_dnt.polyfills.d.ts +0 -101
  7. package/esm/_dnt.polyfills.d.ts.map +0 -1
  8. package/esm/_dnt.polyfills.js +0 -127
  9. package/esm/_dnt.shims.d.ts +0 -6
  10. package/esm/_dnt.shims.d.ts.map +0 -1
  11. package/esm/_dnt.shims.js +0 -61
  12. package/esm/deno.d.ts +0 -25
  13. package/esm/deno.d.ts.map +0 -1
  14. package/esm/deno.js +0 -23
  15. package/esm/package.json +0 -3
  16. package/esm/src/commands/announcements.d.ts +0 -3
  17. package/esm/src/commands/announcements.d.ts.map +0 -1
  18. package/esm/src/commands/announcements.js +0 -134
  19. package/esm/src/commands/assignments.d.ts +0 -3
  20. package/esm/src/commands/assignments.d.ts.map +0 -1
  21. package/esm/src/commands/assignments.js +0 -230
  22. package/esm/src/commands/auth.d.ts +0 -3
  23. package/esm/src/commands/auth.d.ts.map +0 -1
  24. package/esm/src/commands/auth.js +0 -290
  25. package/esm/src/commands/calendar.d.ts +0 -3
  26. package/esm/src/commands/calendar.d.ts.map +0 -1
  27. package/esm/src/commands/calendar.js +0 -179
  28. package/esm/src/commands/courses.d.ts +0 -3
  29. package/esm/src/commands/courses.d.ts.map +0 -1
  30. package/esm/src/commands/courses.js +0 -348
  31. package/esm/src/commands/forums.d.ts +0 -3
  32. package/esm/src/commands/forums.d.ts.map +0 -1
  33. package/esm/src/commands/forums.js +0 -318
  34. package/esm/src/commands/grades.d.ts +0 -3
  35. package/esm/src/commands/grades.d.ts.map +0 -1
  36. package/esm/src/commands/grades.js +0 -121
  37. package/esm/src/commands/materials.d.ts +0 -3
  38. package/esm/src/commands/materials.d.ts.map +0 -1
  39. package/esm/src/commands/materials.js +0 -413
  40. package/esm/src/commands/quizzes.d.ts +0 -3
  41. package/esm/src/commands/quizzes.d.ts.map +0 -1
  42. package/esm/src/commands/quizzes.js +0 -271
  43. package/esm/src/commands/skills.d.ts +0 -3
  44. package/esm/src/commands/skills.d.ts.map +0 -1
  45. package/esm/src/commands/skills.js +0 -106
  46. package/esm/src/commands/upload.d.ts +0 -3
  47. package/esm/src/commands/upload.d.ts.map +0 -1
  48. package/esm/src/commands/upload.js +0 -58
  49. package/esm/src/commands/videos.d.ts +0 -3
  50. package/esm/src/commands/videos.d.ts.map +0 -1
  51. package/esm/src/commands/videos.js +0 -336
  52. package/esm/src/index.d.ts +0 -27
  53. package/esm/src/index.d.ts.map +0 -1
  54. package/esm/src/index.js +0 -160
  55. package/esm/src/lib/auth.d.ts +0 -47
  56. package/esm/src/lib/auth.d.ts.map +0 -1
  57. package/esm/src/lib/auth.js +0 -227
  58. package/esm/src/lib/config.d.ts +0 -6
  59. package/esm/src/lib/config.d.ts.map +0 -1
  60. package/esm/src/lib/config.js +0 -36
  61. package/esm/src/lib/logger.d.ts +0 -3
  62. package/esm/src/lib/logger.d.ts.map +0 -1
  63. package/esm/src/lib/logger.js +0 -27
  64. package/esm/src/lib/moodle.d.ts +0 -433
  65. package/esm/src/lib/moodle.d.ts.map +0 -1
  66. package/esm/src/lib/moodle.js +0 -1318
  67. package/esm/src/lib/session.d.ts +0 -8
  68. package/esm/src/lib/session.d.ts.map +0 -1
  69. package/esm/src/lib/session.js +0 -42
  70. package/esm/src/lib/token.d.ts +0 -38
  71. package/esm/src/lib/token.d.ts.map +0 -1
  72. package/esm/src/lib/token.js +0 -178
  73. package/esm/src/lib/types.d.ts +0 -189
  74. package/esm/src/lib/types.d.ts.map +0 -1
  75. package/esm/src/lib/types.js +0 -2
  76. package/esm/src/lib/utils.d.ts +0 -57
  77. package/esm/src/lib/utils.d.ts.map +0 -1
  78. package/esm/src/lib/utils.js +0 -129
  79. package/script/_dnt.polyfills.d.ts +0 -101
  80. package/script/_dnt.polyfills.d.ts.map +0 -1
  81. package/script/_dnt.polyfills.js +0 -130
  82. package/script/_dnt.shims.d.ts +0 -6
  83. package/script/_dnt.shims.d.ts.map +0 -1
  84. package/script/_dnt.shims.js +0 -65
  85. package/script/deno.d.ts +0 -25
  86. package/script/deno.d.ts.map +0 -1
  87. package/script/deno.js +0 -25
  88. package/script/package.json +0 -3
  89. package/script/src/commands/announcements.d.ts +0 -3
  90. package/script/src/commands/announcements.d.ts.map +0 -1
  91. package/script/src/commands/announcements.js +0 -140
  92. package/script/src/commands/assignments.d.ts +0 -3
  93. package/script/src/commands/assignments.d.ts.map +0 -1
  94. package/script/src/commands/assignments.js +0 -269
  95. package/script/src/commands/auth.d.ts +0 -3
  96. package/script/src/commands/auth.d.ts.map +0 -1
  97. package/script/src/commands/auth.js +0 -296
  98. package/script/src/commands/calendar.d.ts +0 -3
  99. package/script/src/commands/calendar.d.ts.map +0 -1
  100. package/script/src/commands/calendar.js +0 -185
  101. package/script/src/commands/courses.d.ts +0 -3
  102. package/script/src/commands/courses.d.ts.map +0 -1
  103. package/script/src/commands/courses.js +0 -354
  104. package/script/src/commands/forums.d.ts +0 -3
  105. package/script/src/commands/forums.d.ts.map +0 -1
  106. package/script/src/commands/forums.js +0 -324
  107. package/script/src/commands/grades.d.ts +0 -3
  108. package/script/src/commands/grades.d.ts.map +0 -1
  109. package/script/src/commands/grades.js +0 -127
  110. package/script/src/commands/materials.d.ts +0 -3
  111. package/script/src/commands/materials.d.ts.map +0 -1
  112. package/script/src/commands/materials.js +0 -419
  113. package/script/src/commands/quizzes.d.ts +0 -3
  114. package/script/src/commands/quizzes.d.ts.map +0 -1
  115. package/script/src/commands/quizzes.js +0 -277
  116. package/script/src/commands/skills.d.ts +0 -3
  117. package/script/src/commands/skills.d.ts.map +0 -1
  118. package/script/src/commands/skills.js +0 -112
  119. package/script/src/commands/upload.d.ts +0 -3
  120. package/script/src/commands/upload.d.ts.map +0 -1
  121. package/script/src/commands/upload.js +0 -64
  122. package/script/src/commands/videos.d.ts +0 -3
  123. package/script/src/commands/videos.d.ts.map +0 -1
  124. package/script/src/commands/videos.js +0 -342
  125. package/script/src/index.d.ts +0 -27
  126. package/script/src/index.d.ts.map +0 -1
  127. package/script/src/index.js +0 -167
  128. package/script/src/lib/auth.d.ts +0 -47
  129. package/script/src/lib/auth.d.ts.map +0 -1
  130. package/script/src/lib/auth.js +0 -269
  131. package/script/src/lib/config.d.ts +0 -6
  132. package/script/src/lib/config.d.ts.map +0 -1
  133. package/script/src/lib/config.js +0 -42
  134. package/script/src/lib/logger.d.ts +0 -3
  135. package/script/src/lib/logger.d.ts.map +0 -1
  136. package/script/src/lib/logger.js +0 -30
  137. package/script/src/lib/moodle.d.ts +0 -433
  138. package/script/src/lib/moodle.d.ts.map +0 -1
  139. package/script/src/lib/moodle.js +0 -1389
  140. package/script/src/lib/session.d.ts +0 -8
  141. package/script/src/lib/session.d.ts.map +0 -1
  142. package/script/src/lib/session.js +0 -45
  143. package/script/src/lib/token.d.ts +0 -38
  144. package/script/src/lib/token.d.ts.map +0 -1
  145. package/script/src/lib/token.js +0 -189
  146. package/script/src/lib/types.d.ts +0 -189
  147. package/script/src/lib/types.d.ts.map +0 -1
  148. package/script/src/lib/types.js +0 -3
  149. package/script/src/lib/utils.d.ts +0 -57
  150. package/script/src/lib/utils.d.ts.map +0 -1
  151. package/script/src/lib/utils.js +0 -175
  152. package/skills/openape/SKILL.md +0 -115
@@ -1,227 +0,0 @@
1
- import fs from "node:fs";
2
- import path from "node:path";
3
- import { chromium } from "playwright-core";
4
- import { acquireWsToken, loadWsToken, saveWsToken } from "./token.js";
5
- /**
6
- * Find a Chromium-based browser executable on Windows.
7
- * Priority: Edge → Chrome → Brave
8
- */
9
- export function findEdgePath() {
10
- const roots = [
11
- process.env.PROGRAMFILES,
12
- process.env["PROGRAMFILES(X86)"],
13
- process.env.LOCALAPPDATA,
14
- ].filter(Boolean);
15
- const browsers = [
16
- { name: "Edge", suffix: "Microsoft\\Edge\\Application\\msedge.exe" },
17
- { name: "Chrome", suffix: "Google\\Chrome\\Application\\chrome.exe" },
18
- { name: "Brave", suffix: "BraveSoftware\\Brave-Browser\\Application\\brave.exe" },
19
- ];
20
- for (const { suffix } of browsers) {
21
- for (const root of roots) {
22
- const candidate = path.join(root, suffix);
23
- if (fs.existsSync(candidate))
24
- return candidate;
25
- }
26
- }
27
- throw new Error("找不到可用的瀏覽器(Edge / Chrome / Brave)。請確認已安裝其中一種。");
28
- }
29
- /**
30
- * Launch a browser and return an authenticated context.
31
- * Tries to restore a saved session first; falls back to fresh OAuth login.
32
- * Also acquires Moodle Web Service Token for API calls.
33
- */
34
- export async function launchAuthenticated(config, log) {
35
- const edgePath = findEdgePath();
36
- log.debug(`Using Edge: ${edgePath}`);
37
- // Wait a bit to ensure any previous browser process has fully terminated
38
- await new Promise(resolve => setTimeout(resolve, 1000));
39
- const browser = await chromium.launch({
40
- executablePath: edgePath,
41
- headless: config.headless,
42
- slowMo: config.slowMo,
43
- });
44
- // Try loading saved WS token first
45
- let wsToken = loadWsToken(config.authStatePath) ?? undefined;
46
- if (wsToken) {
47
- log.info("Loaded saved Web Service Token.");
48
- }
49
- // Try restoring a saved session
50
- const restored = await tryRestoreSession(browser, config, log);
51
- if (restored) {
52
- const page = restored.pages()[0] ?? (await restored.newPage());
53
- // If no saved WS token, try to acquire one
54
- if (!wsToken) {
55
- try {
56
- wsToken = await acquireWsToken(page, config, log);
57
- saveWsToken(config.authStatePath, wsToken);
58
- }
59
- catch {
60
- log.warn("Failed to acquire WS Token with restored session, continuing without it.");
61
- }
62
- }
63
- return { browser, context: restored, page, wsToken };
64
- }
65
- // Fresh login
66
- if (config.headless) {
67
- await browser.close().catch(() => { });
68
- throw new Error("找不到有效的 Session 或是 Session 已過期。\n" +
69
- "請先執行 `openape login` 進行手動登入,或是加上 `--headed` 參數執行目前的指令以開啟登入畫面。");
70
- }
71
- const context = await browser.newContext();
72
- const page = await context.newPage();
73
- await login(page, config, log);
74
- await saveSession(context, config.authStatePath, log);
75
- // Acquire WS Token after successful login
76
- if (!wsToken) {
77
- try {
78
- wsToken = await acquireWsToken(page, config, log);
79
- saveWsToken(config.authStatePath, wsToken);
80
- }
81
- catch {
82
- log.warn("Failed to acquire WS Token, continuing with sesskey-only auth.");
83
- }
84
- }
85
- return { browser, context, page, wsToken };
86
- }
87
- /**
88
- * Safely close browser and context with timeout.
89
- * Designed for AI agent usage - no human interaction needed.
90
- * If noWait is true, initiates cleanup but doesn't wait for completion.
91
- *
92
- * Note: Closes sequentially (context first, then browser) to avoid libuv
93
- * assertion failures on Windows when handles are closed concurrently.
94
- */
95
- export async function closeBrowserSafely(browser, context, timeoutMs = 5000, noWait = false) {
96
- const closePromises = [];
97
- // Close context first with error handling
98
- if (context) {
99
- closePromises.push(Promise.race([
100
- context.close().catch(() => { }),
101
- new Promise(resolve => setTimeout(() => resolve(), timeoutMs))
102
- ]));
103
- }
104
- // Close browser after context with error handling
105
- closePromises.push(Promise.race([
106
- browser.close().catch(() => { }),
107
- new Promise(resolve => setTimeout(() => resolve(), timeoutMs))
108
- ]));
109
- if (noWait) {
110
- // Fire and forget - don't wait for cleanup
111
- Promise.allSettled(closePromises);
112
- return;
113
- }
114
- // Wait sequentially to avoid libuv issues on Windows
115
- for (const promise of closePromises) {
116
- await promise.catch(() => { });
117
- }
118
- }
119
- /**
120
- * Attempt to restore a session from stored state.
121
- * Returns null if the stored state doesn't exist or the session is expired.
122
- */
123
- async function tryRestoreSession(browser, config, log) {
124
- const statePath = path.resolve(config.authStatePath);
125
- if (!fs.existsSync(statePath)) {
126
- log.debug("No saved session found, will perform fresh login.");
127
- return null;
128
- }
129
- log.info("Restoring saved session...");
130
- const context = await browser.newContext({ storageState: statePath });
131
- const page = await context.newPage();
132
- try {
133
- await page.goto(`${config.moodleBaseUrl}/my/`, {
134
- waitUntil: "domcontentloaded",
135
- timeout: 15000,
136
- });
137
- // If we got redirected to a login page, the session is expired
138
- const url = page.url();
139
- if (url.includes("login") || url.includes("microsoftonline")) {
140
- log.warn("Saved session expired, will re-authenticate.");
141
- await context.close();
142
- return null;
143
- }
144
- log.success("Session restored successfully.");
145
- return context;
146
- }
147
- catch {
148
- log.warn("Failed to restore session, will re-authenticate.");
149
- await context.close();
150
- return null;
151
- }
152
- }
153
- /**
154
- * Save the current session state to disk for future reuse.
155
- */
156
- async function saveSession(context, statePath, log) {
157
- try {
158
- await context.storageState({ path: statePath });
159
- log.debug("Session saved for future reuse.");
160
- }
161
- catch (err) {
162
- log.warn(`Failed to save session: ${err}`);
163
- }
164
- }
165
- /**
166
- * Perform Microsoft OAuth login flow.
167
- */
168
- async function login(page, config, log) {
169
- log.info("Starting Microsoft OAuth login...");
170
- await page.goto(`${config.moodleBaseUrl}/auth/oauth2/login.php`, {
171
- waitUntil: "domcontentloaded",
172
- timeout: 30000,
173
- });
174
- // Wait for Microsoft login page or redirect back to Moodle
175
- try {
176
- await page.waitForURL((url) => url.toString().includes("microsoftonline") ||
177
- url.toString().includes("login.microsoftonline") ||
178
- (url.toString().includes("ilearning.cycu.edu.tw") &&
179
- !url.toString().includes("auth/oauth2/login")), { timeout: 10000 });
180
- const url = page.url().toString();
181
- if (url.includes("microsoftonline") || url.includes("login.microsoftonline")) {
182
- log.info("Microsoft login page detected. Please complete login in the browser.");
183
- log.info("Waiting for redirect back to Moodle...");
184
- await page.waitForURL((u) => u.toString().includes("ilearning.cycu.edu.tw") &&
185
- !u.toString().includes("microsoftonline") &&
186
- !u.toString().includes("login.microsoftonline"), { timeout: 300000 });
187
- }
188
- }
189
- catch {
190
- // Already logged in or redirected
191
- }
192
- // Verify we're logged in
193
- const finalUrl = page.url().toString();
194
- if (finalUrl.includes("login") ||
195
- finalUrl.includes("microsoftonline") ||
196
- finalUrl === config.moodleBaseUrl + "/auth/oauth2/login.php") {
197
- throw new Error(`登入後未重新導向回 Moodle。目前 URL: ${finalUrl}`);
198
- }
199
- log.success("Login completed successfully.");
200
- }
201
- /**
202
- * Create API context for WS token operations (no browser required).
203
- * Returns null if session is invalid or WS token is missing.
204
- */
205
- export async function createApiContext(options, command) {
206
- const { createLogger } = await import("./logger.js");
207
- const { loadWsToken } = await import("./token.js");
208
- const { getOutputFormat, getSessionPath } = await import("./utils.js");
209
- const opts = command?.optsWithGlobals ? command.optsWithGlobals() : options;
210
- const outputFormat = command ? getOutputFormat(command) : "json";
211
- const silent = outputFormat === "json" && !opts.verbose;
212
- const log = createLogger(opts.verbose, silent, outputFormat);
213
- const sessionPath = getSessionPath();
214
- // Try to load WS token
215
- const wsToken = loadWsToken(sessionPath);
216
- if (!wsToken) {
217
- console.error("未找到 WS token。請先執行 'openape login' 進行登入。");
218
- return null;
219
- }
220
- return {
221
- log,
222
- session: {
223
- wsToken,
224
- moodleBaseUrl: "https://ilearning.cycu.edu.tw",
225
- },
226
- };
227
- }
@@ -1,6 +0,0 @@
1
- import type { AppConfig } from "./types.js";
2
- /**
3
- * Load config from .env file (if it exists).
4
- */
5
- export declare function loadConfig(baseDir?: string): AppConfig;
6
- //# sourceMappingURL=config.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"config.d.ts","sourceRoot":"","sources":["../../../src/src/lib/config.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AAE5C;;GAEG;AACH,wBAAgB,UAAU,CAAC,OAAO,CAAC,EAAE,MAAM,GAAG,SAAS,CAgBtD"}
@@ -1,36 +0,0 @@
1
- import fs from "node:fs";
2
- import path from "node:path";
3
- /**
4
- * Load config from .env file (if it exists).
5
- */
6
- export function loadConfig(baseDir) {
7
- const envPath = baseDir ? path.resolve(baseDir, ".env") : path.resolve(".env");
8
- if (fs.existsSync(envPath)) {
9
- const envContent = fs.readFileSync(envPath, "utf8");
10
- for (const line of envContent.split("\n")) {
11
- const trimmed = line.trim();
12
- if (!trimmed || trimmed.startsWith("#"))
13
- continue;
14
- const eqIdx = trimmed.indexOf("=");
15
- if (eqIdx === -1)
16
- continue;
17
- const key = trimmed.slice(0, eqIdx).trim();
18
- const value = trimmed.slice(eqIdx + 1).trim();
19
- if (!process.env[key])
20
- process.env[key] = value;
21
- }
22
- }
23
- return buildConfig();
24
- }
25
- function buildConfig() {
26
- const moodleBaseUrl = (process.env.MOODLE_BASE_URL ?? "https://ilearning.cycu.edu.tw").replace(/\/$/, "");
27
- return {
28
- courseUrl: "",
29
- moodleBaseUrl,
30
- headless: process.env.HEADLESS !== "false",
31
- slowMo: parseInt(process.env.SLOW_MO ?? "0", 10),
32
- authStatePath: process.env.AUTH_STATE_PATH ?? ".auth/storage-state.json",
33
- ollamaModel: process.env.MODEL,
34
- ollamaBaseUrl: (process.env.OLLAMA_BASE_URL ?? "http://localhost:11434").replace(/\/$/, ""),
35
- };
36
- }
@@ -1,3 +0,0 @@
1
- import type { Logger } from "./types.js";
2
- export declare function createLogger(verbose?: boolean, silent?: boolean, outputFormat?: string): Logger;
3
- //# sourceMappingURL=logger.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"logger.d.ts","sourceRoot":"","sources":["../../../src/src/lib/logger.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,YAAY,CAAC;AAOzC,wBAAgB,YAAY,CAAC,OAAO,UAAQ,EAAE,MAAM,UAAQ,EAAE,YAAY,GAAE,MAAe,GAAG,MAAM,CAwBnG"}
@@ -1,27 +0,0 @@
1
- const NO_COLOR = !!process.env.NO_COLOR;
2
- const c = (code, text) => NO_COLOR ? text : `\x1b[${code}m${text}\x1b[0m`;
3
- export function createLogger(verbose = false, silent = false, outputFormat = "json") {
4
- const jsonError = outputFormat === "json";
5
- const errorFn = jsonError
6
- ? (msg) => console.error(JSON.stringify({ error: msg }))
7
- : (msg) => console.error(c("31", "[ERR]") + ` ${msg}`);
8
- if (silent) {
9
- return {
10
- info: (_msg) => { },
11
- success: (_msg) => { },
12
- warn: (_msg) => { },
13
- error: errorFn,
14
- debug: (_msg) => { },
15
- };
16
- }
17
- return {
18
- info: (msg) => console.error(c("36", "[INFO]") + ` ${msg}`),
19
- success: (msg) => console.error(c("32", "[OK]") + ` ${msg}`),
20
- warn: (msg) => console.error(c("33", "[WARN]") + ` ${msg}`),
21
- error: errorFn,
22
- debug: (msg) => {
23
- if (verbose)
24
- console.error(c("90", "[DBG]") + ` ${msg}`);
25
- },
26
- };
27
- }