@capybara-hq/testing 0.1.0-rc.1 → 0.1.0-rc.11
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/dist/dual-replica.d.ts +10 -6
- package/dist/dual-replica.js +3 -1
- package/dist/fake-channel.d.ts +15 -2
- package/dist/fake-channel.js +11 -2
- package/dist/fake-e2b.d.ts +36 -1
- package/dist/fake-e2b.js +95 -1
- package/dist/fake-git-server.js +3 -1
- package/dist/fake-oauth-server.d.ts +16 -2
- package/dist/fake-oauth-server.js +21 -1
- package/dist/fake-telegram.d.ts +165 -0
- package/dist/fake-telegram.js +569 -0
- package/dist/fixtures.d.ts +16 -3
- package/dist/fixtures.js +21 -3
- package/dist/index.d.ts +4 -3
- package/dist/index.js +2 -1
- package/dist/kernel-helpers.d.ts +38 -16
- package/dist/kernel-helpers.js +42 -13
- package/dist/model-conformance.d.ts +5 -0
- package/dist/model-conformance.js +33 -1
- package/dist/replica-runner.js +17 -9
- package/fixtures/extensions/fake-config-form/.capybara-plugin/plugin.json +11 -0
- package/fixtures/extensions/fake-config-form/package.json +12 -0
- package/fixtures/extensions/fake-config-form/src/index.ts +205 -0
- package/fixtures/extensions/fake-im/.capybara-plugin/plugin.json +33 -1
- package/fixtures/extensions/fake-im/guides/app.long-connection.yaml.tmpl +5 -0
- package/fixtures/extensions/fake-im/guides/app.webhook.json.tmpl +8 -0
- package/fixtures/extensions/fake-storage-user/src/index.ts +1 -1
- package/fixtures/extensions/fake-tools-ui/skills/fake-notes/SKILL.md +1 -1
- package/fixtures/extensions/fake-tools-ui/src/index.ts +1 -1
- package/fixtures/extensions/fake-web/.capybara-plugin/plugin.json +7 -0
- package/fixtures/extensions/fake-web/package.json +12 -0
- package/fixtures/extensions/fake-web/src/index.ts +22 -0
- package/fixtures/extensions/fake-web/src/web.ts +183 -0
- package/fixtures/extensions/fake-web-2/.capybara-plugin/plugin.json +7 -0
- package/fixtures/extensions/fake-web-2/package.json +12 -0
- package/fixtures/extensions/fake-web-2/src/index.ts +16 -0
- package/fixtures/extensions/fake-web-2/src/web.ts +183 -0
- package/fixtures/plugins/fake-theme/.capybara-plugin/plugin.json +7 -0
- package/fixtures/plugins/fake-theme/fonts/FakeSans.woff2 +1 -0
- package/fixtures/plugins/fake-theme/logo.svg +1 -0
- package/fixtures/plugins/fake-theme/package.json +8 -0
- package/fixtures/plugins/fake-theme/themes/night-city.json +13 -0
- package/fixtures/plugins/fake-theme/themes/paper.json +12 -0
- package/package.json +5 -5
package/dist/dual-replica.d.ts
CHANGED
|
@@ -8,19 +8,23 @@ export interface DualReplicaOptions {
|
|
|
8
8
|
* this package is installed from npm; nothing needs to be set in `NODE_OPTIONS`.
|
|
9
9
|
*/
|
|
10
10
|
extensions: string[];
|
|
11
|
-
/**
|
|
11
|
+
/**
|
|
12
|
+
* Where extensions named by package resolve from; default the caller's `process.cwd()` (the
|
|
13
|
+
* `resolveFrom` of `createKernelApp`).
|
|
14
|
+
*/
|
|
12
15
|
resolveFrom?: string;
|
|
13
16
|
/** 部署级插件配置,按插件名索引。 */
|
|
14
17
|
extensionConfig?: Record<string, unknown>;
|
|
15
18
|
/**
|
|
16
|
-
* The bootstrap step (package ecosystem spec §7): every replica's kernel gets `
|
|
19
|
+
* The bootstrap step (package ecosystem spec §7): every replica's kernel gets `bootstrap: { dir }`
|
|
17
20
|
* and `bootstrapManifest: manifest`, so the replicas run it at start (once across them, under the
|
|
18
|
-
* advisory lock) before loading extensions, as
|
|
19
|
-
*
|
|
20
|
-
*
|
|
21
|
+
* advisory lock) before loading extensions, as `capybara start` does. `dir` is the optional
|
|
22
|
+
* offline directory (its `*.tgz` files are matched to the entries by sha512); the other entries
|
|
23
|
+
* are downloaded from `packages.npmRegistry` (set it in `config`, e.g. to a
|
|
24
|
+
* `startFakeNpmRegistry`). Build both with the kernel tests' `bootstrapFixture` helper.
|
|
21
25
|
*/
|
|
22
26
|
bootstrap?: {
|
|
23
|
-
dir
|
|
27
|
+
dir?: string;
|
|
24
28
|
manifest: BootstrapManifest;
|
|
25
29
|
};
|
|
26
30
|
/**
|
package/dist/dual-replica.js
CHANGED
|
@@ -167,7 +167,9 @@ export async function createDualReplicaHarness(opts) {
|
|
|
167
167
|
masterKey: randomBytes(32).toString("base64"),
|
|
168
168
|
extensions: opts.extensions,
|
|
169
169
|
...(opts.bootstrap !== undefined && {
|
|
170
|
-
|
|
170
|
+
bootstrap: {
|
|
171
|
+
...(opts.bootstrap.dir !== undefined && { dir: resolve(opts.bootstrap.dir) }),
|
|
172
|
+
},
|
|
171
173
|
bootstrapManifest: opts.bootstrap.manifest,
|
|
172
174
|
}),
|
|
173
175
|
// 副本进程的 cwd 不是调用方的 cwd,相对路径必须先按调用方 cwd 绝对化再经 IPC 传过去
|
package/dist/fake-channel.d.ts
CHANGED
|
@@ -40,7 +40,7 @@ export interface FakeChannelSent {
|
|
|
40
40
|
pid: number;
|
|
41
41
|
/** 内核给的幂等键(`ChannelSendArgs.idempotencyKey`)。 */
|
|
42
42
|
idempotencyKey?: string;
|
|
43
|
-
/**
|
|
43
|
+
/** The language the kernel gave (`ChannelSendArgs.locale`: the recipient's, else the org's). */
|
|
44
44
|
locale?: "zh" | "en";
|
|
45
45
|
at: number;
|
|
46
46
|
}
|
|
@@ -71,6 +71,12 @@ export interface FakeDirectoryBook {
|
|
|
71
71
|
/** 整轮同步开始的次数(不带游标的请求数)。 */
|
|
72
72
|
starts(): number;
|
|
73
73
|
}
|
|
74
|
+
/** Which `/send` or `/update` requests a {@link FakeChannelServer.failNext} failure applies to. */
|
|
75
|
+
export interface FakeChannelFailMatch {
|
|
76
|
+
chatId?: string;
|
|
77
|
+
/** The message's text contains it. */
|
|
78
|
+
textIncludes?: string;
|
|
79
|
+
}
|
|
74
80
|
/** 插件工具经 `POST /posts` 发出的一条记录。 */
|
|
75
81
|
export interface FakeChannelPost {
|
|
76
82
|
body: Record<string, unknown>;
|
|
@@ -101,8 +107,11 @@ export interface FakeChannelServer {
|
|
|
101
107
|
* 让接下来 `count` 次 `/send`(或 `/update`)返回该状态码(不记录);`retryAfterMs` 与 `reason` 放进响应体,
|
|
102
108
|
* 测试插件据此抛 `ChannelSendError`(429 / 5xx 可重试,带等待时长;其他不可重试,带失败原因)。
|
|
103
109
|
* `delayMs`:失败响应推迟这么久才返回(模拟慢的失败请求,让会话的后续事件在投递任务持锁期间到达)。
|
|
110
|
+
* `match`: only matching requests count and fail; a string is a chat id, an object also matches
|
|
111
|
+
* text (`textIncludes`: the message's text contains it). Without it the next requests to any chat
|
|
112
|
+
* fail, so a late delivery from an earlier test can take the failure meant for the request under test.
|
|
104
113
|
*/
|
|
105
|
-
failNext(path: "/send" | "/update", status: number, count?: number, retryAfterMs?: number, reason?: "auth" | "target_gone" | "rejected" | "too_large", delayMs?: number): void;
|
|
114
|
+
failNext(path: "/send" | "/update", status: number, count?: number, retryAfterMs?: number, reason?: "auth" | "target_gone" | "rejected" | "too_large", delayMs?: number, match?: string | FakeChannelFailMatch): void;
|
|
106
115
|
/**
|
|
107
116
|
* Delay the response of the next `count` successful `/send` (or `/update`) requests by `delayMs`.
|
|
108
117
|
* The message is recorded (visible in `sent` / `updated`) as soon as the request arrives; only the
|
|
@@ -135,6 +144,10 @@ export declare function startFakeChannelServer(opts?: FakeChannelServerOptions):
|
|
|
135
144
|
export interface FakeSenderProfile {
|
|
136
145
|
displayName?: string;
|
|
137
146
|
avatarUrl?: string;
|
|
147
|
+
/** The sender's IANA time zone on the platform (channel@1 `sender.timeZone`). */
|
|
148
|
+
timeZone?: string;
|
|
149
|
+
/** The sender's language tag on the platform (channel@1 `sender.locale`). */
|
|
150
|
+
locale?: string;
|
|
138
151
|
}
|
|
139
152
|
/** 私聊文本消息(chat id 为 `dm-<externalId>`);`profile` 给了就带上发言人的显示名 / 头像。 */
|
|
140
153
|
export declare function fakeDm(messageId: string, externalId: string, text: string, tenantId?: string, profile?: FakeSenderProfile): InboundEvent;
|
package/dist/fake-channel.js
CHANGED
|
@@ -61,7 +61,11 @@ export async function startFakeChannelServer(opts = {}) {
|
|
|
61
61
|
};
|
|
62
62
|
const sendOrUpdate = async (req, res, path) => {
|
|
63
63
|
const body = await readBody(req);
|
|
64
|
-
const
|
|
64
|
+
const parsed = JSON.parse(body);
|
|
65
|
+
const matches = (m) => m === undefined ||
|
|
66
|
+
((m.chatId === undefined || m.chatId === parsed.target?.chatId) &&
|
|
67
|
+
(m.textIncludes === undefined || (parsed.message?.text ?? "").includes(m.textIncludes)));
|
|
68
|
+
const f = failures.find((x) => x.path === path && x.left > 0 && matches(x.match));
|
|
65
69
|
if (f) {
|
|
66
70
|
f.left--;
|
|
67
71
|
if (f.delayMs !== undefined)
|
|
@@ -203,7 +207,7 @@ export async function startFakeChannelServer(opts = {}) {
|
|
|
203
207
|
duplicateSends,
|
|
204
208
|
posts,
|
|
205
209
|
users,
|
|
206
|
-
failNext(path, status, count = 1, retryAfterMs, reason, delayMs) {
|
|
210
|
+
failNext(path, status, count = 1, retryAfterMs, reason, delayMs, match) {
|
|
207
211
|
failures.push({
|
|
208
212
|
path,
|
|
209
213
|
status,
|
|
@@ -211,6 +215,9 @@ export async function startFakeChannelServer(opts = {}) {
|
|
|
211
215
|
...(retryAfterMs !== undefined && { retryAfterMs }),
|
|
212
216
|
...(reason !== undefined && { reason }),
|
|
213
217
|
...(delayMs !== undefined && { delayMs }),
|
|
218
|
+
...(match !== undefined && {
|
|
219
|
+
match: typeof match === "string" ? { chatId: match } : match,
|
|
220
|
+
}),
|
|
214
221
|
});
|
|
215
222
|
},
|
|
216
223
|
delayNext(path, delayMs, opts = {}) {
|
|
@@ -261,6 +268,8 @@ const senderOf = (externalId, tenantId, profile = {}) => ({
|
|
|
261
268
|
tenantId,
|
|
262
269
|
...(profile.displayName !== undefined && { displayName: profile.displayName }),
|
|
263
270
|
...(profile.avatarUrl !== undefined && { avatarUrl: profile.avatarUrl }),
|
|
271
|
+
...(profile.timeZone !== undefined && { timeZone: profile.timeZone }),
|
|
272
|
+
...(profile.locale !== undefined && { locale: profile.locale }),
|
|
264
273
|
});
|
|
265
274
|
/** 私聊文本消息(chat id 为 `dm-<externalId>`);`profile` 给了就带上发言人的显示名 / 头像。 */
|
|
266
275
|
export function fakeDm(messageId, externalId, text, tenantId = "t1", profile) {
|
package/dist/fake-e2b.d.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
/**
|
|
2
|
-
*
|
|
2
|
+
* A programmable fake E2B (for the tests of the sandbox-e2b plugin in capybara-hq/plugins), following
|
|
3
|
+
* the `e2b` JS SDK 2.58.0 and the E2B docs (checked 2026-10-21):
|
|
3
4
|
*
|
|
4
5
|
* - **控制面 API**(请求头 `X-API-KEY`,不符 → 401 `{code, message}`):
|
|
5
6
|
* `POST /v2/sandboxes`(建沙箱,回 201 `{sandboxID, templateID, envdVersion, envdAccessToken, domain}`)、
|
|
@@ -18,6 +19,21 @@
|
|
|
18
19
|
* 本机只有一个用户,权限隔离测不了,测试改为核对请求里的用户)。进程以新会话启动(与 setsid 等价),
|
|
19
20
|
* 客户端断开**不会**结束进程(与 envd 一致),只有 SendSignal、杀进程脚本或删沙箱才会。
|
|
20
21
|
*
|
|
22
|
+
* - **Template build** (the routes `Template.build(Template().fromImage(image), alias)` calls, e2b 2.58.0
|
|
23
|
+
* `buildApi`; all need `X-API-KEY`): `POST /v3/templates` (body `{name, tags?, cpuCount?, memoryMB?}`,
|
|
24
|
+
* `name` may carry `:tag`; 202 `{templateID, buildID, names, aliases, tags, public}`),
|
|
25
|
+
* `GET /templates/{templateID}/files/{hash}` (upload link of a COPY step; `{present: true}`),
|
|
26
|
+
* `POST /v2/templates/{templateID}/builds/{buildID}` (body `{fromImage, steps, force, startCmd?,
|
|
27
|
+
* readyCmd?}`; 202, and {@link FakeE2BOptions.templateBuildMs} starts counting), `GET
|
|
28
|
+
* /templates/{templateID}/builds/{buildID}/status?logsOffset=` (`{buildID, templateID, status:
|
|
29
|
+
* waiting | building | ready, logEntries, logs}`), `GET /templates/aliases/{alias}` (200
|
|
30
|
+
* `{templateID, public}`, else 404). A template (including the seeded `templates`) creates
|
|
31
|
+
* sandboxes by alias or templateID; one still building answers 404; template names never
|
|
32
|
+
* registered are accepted as before.
|
|
33
|
+
* - **Pause**: `POST /sandboxes/{id}/pause` with `{memory: false}` (the SDK's `mode: "filesystem"`)
|
|
34
|
+
* ends all processes and keeps the files; otherwise (also an empty body) processes stay.
|
|
35
|
+
* {@link FakeE2BServer.removeSandbox} simulates a lost paused sandbox.
|
|
36
|
+
*
|
|
21
37
|
* `connect` 带 `memory: false`(SDK 的 `onResume: "reboot"`)时结束该沙箱的全部进程(冷启动)。
|
|
22
38
|
* SendSignal 只杀指定进程(不是进程组)。
|
|
23
39
|
*
|
|
@@ -31,6 +47,19 @@ export interface FakeE2BOptions {
|
|
|
31
47
|
pageSize?: number;
|
|
32
48
|
/** create / connect 返回的沙箱 `domain`(默认 null,即用客户端配置的域名)。 */
|
|
33
49
|
domain?: string | null;
|
|
50
|
+
/** Existing template aliases (treated as built). */
|
|
51
|
+
templates?: string[];
|
|
52
|
+
/** Milliseconds from triggering a template build to `ready` (default 0). */
|
|
53
|
+
templateBuildMs?: number;
|
|
54
|
+
}
|
|
55
|
+
export interface FakeE2BTemplate {
|
|
56
|
+
templateID: string;
|
|
57
|
+
alias: string;
|
|
58
|
+
/** The image it was built from (undefined for a seeded template). */
|
|
59
|
+
image?: string | undefined;
|
|
60
|
+
buildID?: string | undefined;
|
|
61
|
+
/** When it becomes `ready` (ms timestamp); undefined until the build is triggered (waiting). */
|
|
62
|
+
readyAt?: number | undefined;
|
|
34
63
|
}
|
|
35
64
|
export interface FakeE2BSandbox {
|
|
36
65
|
id: string;
|
|
@@ -40,6 +69,8 @@ export interface FakeE2BSandbox {
|
|
|
40
69
|
/** 当前的超时(秒):建沙箱时给的,connect 只会把它调大。 */
|
|
41
70
|
timeout: number;
|
|
42
71
|
autoPause: boolean;
|
|
72
|
+
/** Whether the last pause kept memory (`pause` body `memory` is not false). */
|
|
73
|
+
pausedWithMemory?: boolean;
|
|
43
74
|
/** 建沙箱请求体里的出站设置(原样记录)。 */
|
|
44
75
|
allowInternetAccess?: boolean;
|
|
45
76
|
network?: unknown;
|
|
@@ -70,6 +101,8 @@ export interface FakeE2BServer {
|
|
|
70
101
|
url: string;
|
|
71
102
|
apiKey: string;
|
|
72
103
|
sandboxes: Map<string, FakeE2BSandbox>;
|
|
104
|
+
/** Templates by alias. */
|
|
105
|
+
templates: Map<string, FakeE2BTemplate>;
|
|
73
106
|
calls: FakeE2BCall[];
|
|
74
107
|
/**
|
|
75
108
|
* 下一个匹配的请求回 `status`:默认 E2B 的错误格式 JSON `{code: status, message}`;`raw` 时回纯文本
|
|
@@ -89,6 +122,8 @@ export interface FakeE2BServer {
|
|
|
89
122
|
withholdAccessToken: boolean;
|
|
90
123
|
/** 沙箱直接消失(杀掉它的进程、删掉根目录)。 */
|
|
91
124
|
expire(id: string): Promise<void>;
|
|
125
|
+
/** Same as {@link FakeE2BServer.expire}: simulates a lost paused sandbox (connect then answers 404). */
|
|
126
|
+
removeSandbox(id: string): Promise<void>;
|
|
92
127
|
/** 沙箱内路径在本机上的位置。 */
|
|
93
128
|
hostPath(id: string, sandboxPath: string): string;
|
|
94
129
|
/** 沙箱里还在跑的进程(由 Start 启动、尚未退出的)。 */
|
package/dist/fake-e2b.js
CHANGED
|
@@ -84,6 +84,12 @@ export async function startFakeE2B(opts = {}) {
|
|
|
84
84
|
await chmod(join(shims, "setsid"), 0o755);
|
|
85
85
|
const sandboxes = new Map();
|
|
86
86
|
const procs = new Map();
|
|
87
|
+
const templates = new Map();
|
|
88
|
+
for (const alias of opts.templates ?? [])
|
|
89
|
+
templates.set(alias, { templateID: `t${randomBytes(6).toString("hex")}`, alias });
|
|
90
|
+
const buildMs = opts.templateBuildMs ?? 0;
|
|
91
|
+
const templateByRef = (ref) => templates.get(ref) ?? [...templates.values()].find((t) => t.templateID === ref);
|
|
92
|
+
const ready = (t) => t.readyAt !== undefined && Date.now() >= t.readyAt;
|
|
87
93
|
const calls = [];
|
|
88
94
|
const fails = [];
|
|
89
95
|
const reboots = new Map();
|
|
@@ -122,12 +128,13 @@ export async function startFakeE2B(opts = {}) {
|
|
|
122
128
|
};
|
|
123
129
|
const newSandbox = async (body) => {
|
|
124
130
|
const id = `i${randomBytes(9).toString("hex")}`;
|
|
131
|
+
const tpl = templateByRef(String(body.templateID));
|
|
125
132
|
const root = join(base, id);
|
|
126
133
|
for (const d of ROOT_DIRS)
|
|
127
134
|
await mkdir(join(root, d), { recursive: true });
|
|
128
135
|
const s = {
|
|
129
136
|
id,
|
|
130
|
-
templateID: String(body.templateID),
|
|
137
|
+
templateID: tpl?.templateID ?? String(body.templateID),
|
|
131
138
|
metadata: body.metadata ?? {},
|
|
132
139
|
state: "running",
|
|
133
140
|
timeout: typeof body.timeout === "number" ? body.timeout : 300,
|
|
@@ -160,6 +167,11 @@ export async function startFakeE2B(opts = {}) {
|
|
|
160
167
|
sendJson(res, 400, { code: 400, message: "templateID is required" });
|
|
161
168
|
return;
|
|
162
169
|
}
|
|
170
|
+
const tpl = templateByRef(body.templateID);
|
|
171
|
+
if (tpl?.buildID !== undefined && !ready(tpl)) {
|
|
172
|
+
sendJson(res, 404, { code: 404, message: `template '${body.templateID}' is not ready` });
|
|
173
|
+
return;
|
|
174
|
+
}
|
|
163
175
|
const s = await newSandbox(body);
|
|
164
176
|
sendJson(res, 201, {
|
|
165
177
|
sandboxID: s.id,
|
|
@@ -235,9 +247,89 @@ export async function startFakeE2B(opts = {}) {
|
|
|
235
247
|
return;
|
|
236
248
|
}
|
|
237
249
|
s.state = "paused";
|
|
250
|
+
s.pausedWithMemory = body.memory !== false;
|
|
251
|
+
if (!s.pausedWithMemory) {
|
|
252
|
+
// filesystem-only snapshot: the processes are gone, the files stay
|
|
253
|
+
for (const p of procs.get(s.id) ?? [])
|
|
254
|
+
killGroup(p);
|
|
255
|
+
procs.delete(s.id);
|
|
256
|
+
}
|
|
238
257
|
sendJson(res, 204);
|
|
239
258
|
return;
|
|
240
259
|
}
|
|
260
|
+
if (method === "POST" && path === "/v3/templates") {
|
|
261
|
+
const name = typeof body.name === "string" ? body.name : "";
|
|
262
|
+
if (name === "") {
|
|
263
|
+
sendJson(res, 400, { code: 400, message: "name is required" });
|
|
264
|
+
return;
|
|
265
|
+
}
|
|
266
|
+
const alias = name.split(":")[0];
|
|
267
|
+
const tags = Array.isArray(body.tags) ? body.tags : [];
|
|
268
|
+
const t = templates.get(alias) ?? {
|
|
269
|
+
templateID: `t${randomBytes(6).toString("hex")}`,
|
|
270
|
+
alias,
|
|
271
|
+
};
|
|
272
|
+
t.buildID = randomBytes(8).toString("hex");
|
|
273
|
+
t.readyAt = undefined;
|
|
274
|
+
t.image = undefined;
|
|
275
|
+
templates.set(alias, t);
|
|
276
|
+
sendJson(res, 202, {
|
|
277
|
+
templateID: t.templateID,
|
|
278
|
+
buildID: t.buildID,
|
|
279
|
+
names: [name],
|
|
280
|
+
aliases: [alias],
|
|
281
|
+
tags,
|
|
282
|
+
public: false,
|
|
283
|
+
});
|
|
284
|
+
return;
|
|
285
|
+
}
|
|
286
|
+
m = /^\/templates\/([^/]+)\/files\/([^/]+)$/.exec(path);
|
|
287
|
+
if (m && method === "GET") {
|
|
288
|
+
sendJson(res, 200, { present: true });
|
|
289
|
+
return;
|
|
290
|
+
}
|
|
291
|
+
m = /^\/v2\/templates\/([^/]+)\/builds\/([^/]+)$/.exec(path);
|
|
292
|
+
if (m && method === "POST") {
|
|
293
|
+
const t = templateByRef(m[1]);
|
|
294
|
+
if (!t || t.buildID !== m[2]) {
|
|
295
|
+
sendJson(res, 404, { code: 404, message: "build not found" });
|
|
296
|
+
return;
|
|
297
|
+
}
|
|
298
|
+
if (typeof body.fromImage !== "string") {
|
|
299
|
+
sendJson(res, 400, { code: 400, message: "fromImage is required" });
|
|
300
|
+
return;
|
|
301
|
+
}
|
|
302
|
+
t.image = body.fromImage;
|
|
303
|
+
t.readyAt = Date.now() + buildMs;
|
|
304
|
+
sendJson(res, 202);
|
|
305
|
+
return;
|
|
306
|
+
}
|
|
307
|
+
m = /^\/templates\/([^/]+)\/builds\/([^/]+)\/status$/.exec(path);
|
|
308
|
+
if (m && method === "GET") {
|
|
309
|
+
const t = templateByRef(m[1]);
|
|
310
|
+
if (!t || t.buildID !== m[2]) {
|
|
311
|
+
sendJson(res, 404, { code: 404, message: "build not found" });
|
|
312
|
+
return;
|
|
313
|
+
}
|
|
314
|
+
sendJson(res, 200, {
|
|
315
|
+
buildID: t.buildID,
|
|
316
|
+
templateID: t.templateID,
|
|
317
|
+
status: t.readyAt === undefined ? "waiting" : ready(t) ? "ready" : "building",
|
|
318
|
+
logEntries: [],
|
|
319
|
+
logs: [],
|
|
320
|
+
});
|
|
321
|
+
return;
|
|
322
|
+
}
|
|
323
|
+
m = /^\/templates\/aliases\/([^/]+)$/.exec(path);
|
|
324
|
+
if (m && method === "GET") {
|
|
325
|
+
const t = templates.get(decodeURIComponent(m[1]));
|
|
326
|
+
if (!t) {
|
|
327
|
+
sendJson(res, 404, { code: 404, message: `template '${m[1]}' not found` });
|
|
328
|
+
return;
|
|
329
|
+
}
|
|
330
|
+
sendJson(res, 200, { templateID: t.templateID, public: false });
|
|
331
|
+
return;
|
|
332
|
+
}
|
|
241
333
|
m = /^\/sandboxes\/([^/]+)$/.exec(path);
|
|
242
334
|
if (m && method === "DELETE") {
|
|
243
335
|
if (!sandboxes.has(m[1]))
|
|
@@ -454,6 +546,7 @@ export async function startFakeE2B(opts = {}) {
|
|
|
454
546
|
url,
|
|
455
547
|
apiKey,
|
|
456
548
|
sandboxes,
|
|
549
|
+
templates,
|
|
457
550
|
calls,
|
|
458
551
|
failNext(match, status, message = `fake failure ${status}`, opts = {}) {
|
|
459
552
|
fails.push({ match, status, message, raw: opts.raw === true });
|
|
@@ -469,6 +562,7 @@ export async function startFakeE2B(opts = {}) {
|
|
|
469
562
|
hangs.push(match);
|
|
470
563
|
},
|
|
471
564
|
expire: destroy,
|
|
565
|
+
removeSandbox: destroy,
|
|
472
566
|
hostPath(id, sandboxPath) {
|
|
473
567
|
const s = sandboxes.get(id);
|
|
474
568
|
if (!s)
|
package/dist/fake-git-server.js
CHANGED
|
@@ -129,8 +129,10 @@ function serveCgi(root, req, res) {
|
|
|
129
129
|
res.writeHead(h.status, h.headers);
|
|
130
130
|
res.write(head.subarray(h.bodyStart));
|
|
131
131
|
});
|
|
132
|
+
// A child that could not be spawned emits 'error' and then 'close': only the first writes a head
|
|
133
|
+
// (a second writeHead throws ERR_HTTP_HEADERS_SENT, an uncaught exception).
|
|
132
134
|
p.on("close", () => {
|
|
133
|
-
if (!headDone)
|
|
135
|
+
if (!headDone && !res.headersSent)
|
|
134
136
|
res.writeHead(502);
|
|
135
137
|
res.end();
|
|
136
138
|
});
|
|
@@ -19,6 +19,15 @@ export interface FakeOAuthServerOptions {
|
|
|
19
19
|
scopesSupported?: string[];
|
|
20
20
|
/** 元数据里的 `code_challenge_methods_supported`;null = 不声明。默认 `["S256"]`。 */
|
|
21
21
|
pkceMethods?: string[] | null;
|
|
22
|
+
/**
|
|
23
|
+
* How the token endpoint answers. `"oauth"` (default): RFC 6749 (`token_type: "Bearer"`, errors
|
|
24
|
+
* as 400 / 401 `{ error }`). `"slack"`: like Slack's `oauth.v2.user.access`: success is
|
|
25
|
+
* `{ ok: true, token_type: "user", ... }`, every error is HTTP 200 `{ ok: false, error }` with
|
|
26
|
+
* Slack's codes where they differ (`invalid_code`, `invalid_refresh_token`, `invalid_client_id`).
|
|
27
|
+
*/
|
|
28
|
+
dialect?: "oauth" | "slack";
|
|
29
|
+
/** The `token_type` of successful token responses (default: `Bearer`; `user` with dialect slack). */
|
|
30
|
+
tokenType?: string;
|
|
22
31
|
}
|
|
23
32
|
/** 令牌端点收到的一次请求(不含任何密钥)。 */
|
|
24
33
|
export interface FakeTokenRequest {
|
|
@@ -28,8 +37,10 @@ export interface FakeTokenRequest {
|
|
|
28
37
|
scope: string | undefined;
|
|
29
38
|
/** 客户端认证方式:Basic 头、表单里的 client_secret、或只有 client_id。 */
|
|
30
39
|
clientAuth: "basic" | "post" | "none";
|
|
31
|
-
/** 本次响应的 HTTP
|
|
40
|
+
/** 本次响应的 HTTP 状态(dialect slack: errors are 200 too). */
|
|
32
41
|
status: number;
|
|
42
|
+
/** The error code answered, if any (as sent: Slack's code with dialect slack). */
|
|
43
|
+
error?: string;
|
|
33
44
|
}
|
|
34
45
|
export interface FakeOAuthServer {
|
|
35
46
|
/** issuer(`http://127.0.0.1:<port>`),也是各端点的基址。 */
|
|
@@ -45,7 +56,10 @@ export interface FakeOAuthServer {
|
|
|
45
56
|
issuedSecrets(): string[];
|
|
46
57
|
/** 作废全部 access token(refresh token 仍有效):资源服务随之返回 401。 */
|
|
47
58
|
revokeAccessTokens(): void;
|
|
48
|
-
/**
|
|
59
|
+
/**
|
|
60
|
+
* 作废全部 refresh token:之后的刷新返回 `invalid_grant`(dialect slack: HTTP 200
|
|
61
|
+
* `{ ok: false, error: "invalid_refresh_token" }`)。
|
|
62
|
+
*/
|
|
49
63
|
revokeRefreshTokens(): void;
|
|
50
64
|
/** 下一次授权请求以该 OAuth 错误回跳。 */
|
|
51
65
|
denyNext(error: string, description?: string): void;
|
|
@@ -19,6 +19,16 @@ const json = (res, status, body) => {
|
|
|
19
19
|
*/
|
|
20
20
|
export async function startFakeOAuthServer(opts = {}) {
|
|
21
21
|
let dcr = opts.dcr ?? true;
|
|
22
|
+
const slack = opts.dialect === "slack";
|
|
23
|
+
const tokenType = opts.tokenType ?? (slack ? "user" : "Bearer");
|
|
24
|
+
/** RFC 6749 error code -> Slack's code for the same failure (dialect slack). */
|
|
25
|
+
const slackCode = (error, grantType) => {
|
|
26
|
+
if (error === "invalid_grant")
|
|
27
|
+
return grantType === "refresh_token" ? "invalid_refresh_token" : "invalid_code";
|
|
28
|
+
if (error === "invalid_client")
|
|
29
|
+
return "invalid_client_id";
|
|
30
|
+
return error;
|
|
31
|
+
};
|
|
22
32
|
const ttl = opts.accessTokenTtl ?? 3600;
|
|
23
33
|
const clients = new Map((opts.clients ?? []).map((c) => [
|
|
24
34
|
c.clientId,
|
|
@@ -53,7 +63,11 @@ export async function startFakeOAuthServer(opts = {}) {
|
|
|
53
63
|
const accessToken = rand("at_");
|
|
54
64
|
access.set(accessToken, { expiresAt: ttl > 0 ? Date.now() + ttl * 1000 : null });
|
|
55
65
|
secrets.add(accessToken);
|
|
56
|
-
const body = {
|
|
66
|
+
const body = {
|
|
67
|
+
...(slack && { ok: true }),
|
|
68
|
+
access_token: accessToken,
|
|
69
|
+
token_type: tokenType,
|
|
70
|
+
};
|
|
57
71
|
if (ttl > 0)
|
|
58
72
|
body.expires_in = ttl;
|
|
59
73
|
if (scope !== undefined)
|
|
@@ -108,7 +122,13 @@ export async function startFakeOAuthServer(opts = {}) {
|
|
|
108
122
|
return json(res, tokenFailures.status, tokenFailures.body ?? { message: "fake failure" });
|
|
109
123
|
}
|
|
110
124
|
const fail = (status, error) => {
|
|
125
|
+
if (slack) {
|
|
126
|
+
entry.status = 200;
|
|
127
|
+
entry.error = slackCode(error, grantType);
|
|
128
|
+
return json(res, 200, { ok: false, error: entry.error });
|
|
129
|
+
}
|
|
111
130
|
entry.status = status;
|
|
131
|
+
entry.error = error;
|
|
112
132
|
json(res, status, { error, error_description: `fake: ${error}` });
|
|
113
133
|
};
|
|
114
134
|
const client = authenticate(req, form);
|
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A programmable fake Telegram Bot API (for the Telegram channel plugin's tests).
|
|
3
|
+
*
|
|
4
|
+
* - **Routing**: `GET|POST /bot<token>/<method>` (method names are case-insensitive, like Telegram);
|
|
5
|
+
* parameters come from the query string and a JSON or form-urlencoded body. Every answer is the
|
|
6
|
+
* Bot API envelope: `{ ok: true, result }` or `{ ok: false, error_code, description, parameters? }`.
|
|
7
|
+
* An unknown token → 401 `Unauthorized`; an unknown method → 404 `Not Found`. Point a client at
|
|
8
|
+
* `apiUrl` (it appends `/bot<token>/<method>`).
|
|
9
|
+
* - **Methods**: `getMe`, `getWebhookInfo` (the url given to {@link FakeTelegramServer.setWebhook}),
|
|
10
|
+
* `getUpdates`, `sendMessage`, `editMessageText`, `answerCallbackQuery`.
|
|
11
|
+
* - **Long polling**: {@link FakeTelegramServer.push} queues an update per bot and assigns its
|
|
12
|
+
* `update_id`. `getUpdates` with `offset` confirms (drops) the lower ids; with `timeout` it waits
|
|
13
|
+
* until a push or the timeout; `allowed_updates` is remembered per bot like Telegram and updates of
|
|
14
|
+
* other types are dropped. While a webhook is set `getUpdates` answers 409; a second concurrent
|
|
15
|
+
* `getUpdates` for the same token ends the earlier one with 409 "Conflict: terminated by other
|
|
16
|
+
* getUpdates request", as Telegram does.
|
|
17
|
+
* - **Several bots**: {@link FakeTelegramOptions.bots}; each token has its own queue, offset, webhook
|
|
18
|
+
* and pollers.
|
|
19
|
+
* - **Failures**: {@link FakeTelegramServer.failNext} answers a method with an error envelope
|
|
20
|
+
* (`parameters.retry_after` / `migrate_to_chat_id`), {@link FakeTelegramServer.delay} holds it.
|
|
21
|
+
*
|
|
22
|
+
* Records: `messages` (sendMessage), `edits` (successful editMessageText), `calls` (every call with
|
|
23
|
+
* a known token), `callbackAnswers` (answerCallbackQuery ids).
|
|
24
|
+
*/
|
|
25
|
+
export interface FakeTelegramBot {
|
|
26
|
+
/** `<id>:<secret>`, as BotFather issues it. */
|
|
27
|
+
token: string;
|
|
28
|
+
id: number;
|
|
29
|
+
username: string;
|
|
30
|
+
firstName?: string;
|
|
31
|
+
/** getMe `can_read_all_group_messages` (privacy mode off); default false. */
|
|
32
|
+
canReadAllGroupMessages?: boolean;
|
|
33
|
+
/** getMe `has_topics_enabled` (forum topics in private chats); default false. */
|
|
34
|
+
hasTopicsEnabled?: boolean;
|
|
35
|
+
}
|
|
36
|
+
/** One Bot API call with a known token (parameters merged from query string and body). */
|
|
37
|
+
export interface FakeTelegramCall {
|
|
38
|
+
method: string;
|
|
39
|
+
token: string;
|
|
40
|
+
params: Record<string, unknown>;
|
|
41
|
+
at: number;
|
|
42
|
+
}
|
|
43
|
+
/** A message the bot sent (`sendMessage`) or an edit of one (`editMessageText`). */
|
|
44
|
+
export interface FakeTelegramMessage {
|
|
45
|
+
chatId: number;
|
|
46
|
+
messageId: number;
|
|
47
|
+
text: string;
|
|
48
|
+
parseMode?: string;
|
|
49
|
+
replyMarkup?: unknown;
|
|
50
|
+
messageThreadId?: number;
|
|
51
|
+
replyToMessageId?: number;
|
|
52
|
+
at: number;
|
|
53
|
+
}
|
|
54
|
+
/** An injected error answer: `status` is the HTTP status, `errorCode` defaults to it. */
|
|
55
|
+
export interface FakeTelegramFailure {
|
|
56
|
+
status: number;
|
|
57
|
+
errorCode?: number;
|
|
58
|
+
description: string;
|
|
59
|
+
retryAfter?: number;
|
|
60
|
+
migrateToChatId?: number;
|
|
61
|
+
}
|
|
62
|
+
export interface FakeTelegramOptions {
|
|
63
|
+
/** The bots this fake serves; default one bot (`123456:fake-telegram-token`, `capybara_bot`). */
|
|
64
|
+
bots?: FakeTelegramBot[];
|
|
65
|
+
}
|
|
66
|
+
export interface FakeTelegramServer {
|
|
67
|
+
url: string;
|
|
68
|
+
/** Same as `url`: the client appends `/bot<token>/<method>`. */
|
|
69
|
+
apiUrl: string;
|
|
70
|
+
/** The first bot (the default for every `token?` argument). */
|
|
71
|
+
bot: FakeTelegramBot;
|
|
72
|
+
bots: FakeTelegramBot[];
|
|
73
|
+
/** sendMessage results, in order. */
|
|
74
|
+
messages: FakeTelegramMessage[];
|
|
75
|
+
/** Successful editMessageText calls, in order (markup-only edits are recorded too). */
|
|
76
|
+
edits: FakeTelegramMessage[];
|
|
77
|
+
calls: FakeTelegramCall[];
|
|
78
|
+
/** answerCallbackQuery `callback_query_id`s, in order. */
|
|
79
|
+
callbackAnswers: string[];
|
|
80
|
+
/** Queues an update for the bot, assigns its `update_id` and returns it; wakes a long poll. */
|
|
81
|
+
push(update: Record<string, unknown>, token?: string): number;
|
|
82
|
+
/** The highest offset passed to getUpdates (0 before any). */
|
|
83
|
+
confirmedOffset(token?: string): number;
|
|
84
|
+
/** Updates pushed and not yet confirmed. */
|
|
85
|
+
pending(token?: string): number;
|
|
86
|
+
/** In-flight getUpdates requests. */
|
|
87
|
+
activePollers(token?: string): number;
|
|
88
|
+
/**
|
|
89
|
+
* The peak number of overlapping getUpdates requests: a request that arrives while another is in
|
|
90
|
+
* flight counts as concurrent with it, although it ends the earlier one with 409.
|
|
91
|
+
*/
|
|
92
|
+
maxConcurrentPollers(token?: string): number;
|
|
93
|
+
/**
|
|
94
|
+
* The client TCP ports of the in-flight getUpdates requests; dual-replica tests map them to the
|
|
95
|
+
* replica process holding the poll.
|
|
96
|
+
*/
|
|
97
|
+
pollerPeerPorts(token?: string): number[];
|
|
98
|
+
/** Sets (or clears with null) the webhook getWebhookInfo reports; while set, getUpdates is 409. */
|
|
99
|
+
setWebhook(url: string | null, token?: string): void;
|
|
100
|
+
/** The next `count` (default 1) calls of `method` answer with `failure`. */
|
|
101
|
+
failNext(method: string, failure: FakeTelegramFailure, count?: number): void;
|
|
102
|
+
/** Every later call of `method` waits `ms` before answering (0 cancels). */
|
|
103
|
+
delay(method: string, ms: number): void;
|
|
104
|
+
close(): Promise<void>;
|
|
105
|
+
}
|
|
106
|
+
export type TgUser = {
|
|
107
|
+
id: number;
|
|
108
|
+
first_name: string;
|
|
109
|
+
last_name?: string;
|
|
110
|
+
username?: string;
|
|
111
|
+
is_bot?: boolean;
|
|
112
|
+
};
|
|
113
|
+
export type TgChat = {
|
|
114
|
+
id: number;
|
|
115
|
+
type: "private" | "group" | "supergroup";
|
|
116
|
+
title?: string;
|
|
117
|
+
is_forum?: boolean;
|
|
118
|
+
};
|
|
119
|
+
/** Starts the fake Telegram Bot API (listens on a random 127.0.0.1 port). */
|
|
120
|
+
export declare function startFakeTelegram(opts?: FakeTelegramOptions): Promise<FakeTelegramServer>;
|
|
121
|
+
/** An update with a private (direct) message from `from`. */
|
|
122
|
+
export declare function telegramPrivateMessage(from: TgUser, text: string, o?: {
|
|
123
|
+
messageId?: number;
|
|
124
|
+
date?: number;
|
|
125
|
+
}): Record<string, unknown>;
|
|
126
|
+
/**
|
|
127
|
+
* An update with a group message. `mention` (with or without `@`) adds a `mention` entity at its
|
|
128
|
+
* UTF-16 offset, prefixing `@<mention> ` when the text lacks it; `replyTo` sets `reply_to_message`
|
|
129
|
+
* (from the bot when `fromBot` is given); `messageThreadId` sets the thread, with
|
|
130
|
+
* `is_topic_message` defaulting to the chat's `is_forum`; `caption` turns the message into a photo
|
|
131
|
+
* whose caption carries the text and entities.
|
|
132
|
+
*/
|
|
133
|
+
export declare function telegramGroupMessage(chat: TgChat, from: TgUser, text: string, o?: {
|
|
134
|
+
messageId?: number;
|
|
135
|
+
mention?: string;
|
|
136
|
+
replyTo?: {
|
|
137
|
+
messageId: number;
|
|
138
|
+
fromBot?: FakeTelegramBot;
|
|
139
|
+
text?: string;
|
|
140
|
+
};
|
|
141
|
+
messageThreadId?: number;
|
|
142
|
+
isTopicMessage?: boolean;
|
|
143
|
+
caption?: boolean;
|
|
144
|
+
}): Record<string, unknown>;
|
|
145
|
+
/** An update with a callback query: `from` pressed an inline button with `data` on a bot message. */
|
|
146
|
+
export declare function telegramCallback(from: TgUser, message: {
|
|
147
|
+
chatId: number;
|
|
148
|
+
messageId: number;
|
|
149
|
+
chatType?: string;
|
|
150
|
+
messageThreadId?: number;
|
|
151
|
+
}, data: string, o?: {
|
|
152
|
+
id?: string;
|
|
153
|
+
}): Record<string, unknown>;
|
|
154
|
+
/** Finds an inline keyboard button in a `reply_markup` (object or JSON string). */
|
|
155
|
+
export declare function findTelegramButton(replyMarkup: unknown, pred: (b: {
|
|
156
|
+
text: string;
|
|
157
|
+
callback_data?: string;
|
|
158
|
+
url?: string;
|
|
159
|
+
}) => boolean): {
|
|
160
|
+
text: string;
|
|
161
|
+
callback_data?: string;
|
|
162
|
+
url?: string;
|
|
163
|
+
} | undefined;
|
|
164
|
+
/** The headers Telegram sends to a webhook set with `secret_token`. */
|
|
165
|
+
export declare function telegramWebhookHeaders(secret: string): Record<string, string>;
|