channelstack 0.0.0-placeholder.0 → 0.1.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/LICENSE +21 -0
- package/README.md +55 -1
- package/bin/channelstack.mjs +31 -0
- package/dist/integrations/checks/checks.test.d.ts +1 -0
- package/dist/integrations/checks/checks.test.js +31 -0
- package/dist/integrations/checks/index.d.ts +69 -0
- package/dist/integrations/checks/index.js +578 -0
- package/dist/integrations/matchers-core/index.d.ts +138 -0
- package/dist/integrations/matchers-core/index.js +458 -0
- package/dist/integrations/matchers-core/matchers.test.d.ts +1 -0
- package/dist/integrations/matchers-core/matchers.test.js +159 -0
- package/dist/integrations/vitest/global-setup.d.ts +3 -0
- package/dist/integrations/vitest/global-setup.js +19 -0
- package/dist/integrations/vitest/index.d.ts +80 -0
- package/dist/integrations/vitest/index.js +42 -0
- package/dist/integrations/vitest/plugin.test.d.ts +1 -0
- package/dist/integrations/vitest/plugin.test.js +19 -0
- package/dist/integrations/vitest/refused.d.ts +22 -0
- package/dist/integrations/vitest/refused.js +49 -0
- package/dist/integrations/vitest/setup.d.ts +1 -0
- package/dist/integrations/vitest/setup.js +109 -0
- package/dist/sdks/typescript/client.d.ts +13 -0
- package/dist/sdks/typescript/client.js +11 -0
- package/dist/sdks/typescript/generated/channels.d.ts +24 -0
- package/dist/sdks/typescript/generated/channels.js +2 -0
- package/dist/sdks/typescript/generated/index.d.ts +2747 -0
- package/dist/sdks/typescript/generated/index.js +3039 -0
- package/dist/sdks/typescript/runtime/client.d.ts +47 -0
- package/dist/sdks/typescript/runtime/client.js +69 -0
- package/dist/sdks/typescript/runtime/credentials.d.ts +7 -0
- package/dist/sdks/typescript/runtime/credentials.js +20 -0
- package/dist/sdks/typescript/runtime/duration.d.ts +4 -0
- package/dist/sdks/typescript/runtime/duration.js +13 -0
- package/dist/sdks/typescript/runtime/files.d.ts +32 -0
- package/dist/sdks/typescript/runtime/files.js +45 -0
- package/dist/sdks/typescript/runtime/launcher.d.ts +24 -0
- package/dist/sdks/typescript/runtime/launcher.js +121 -0
- package/dist/sdks/typescript/runtime/transport.d.ts +43 -0
- package/dist/sdks/typescript/runtime/transport.js +95 -0
- package/dist/sdks/typescript/runtime/wait.d.ts +82 -0
- package/dist/sdks/typescript/runtime/wait.js +136 -0
- package/dist/sdks/typescript/types.d.ts +72 -0
- package/dist/sdks/typescript/types.js +1 -0
- package/package.json +78 -4
- package/index.js +0 -1
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import { type LaunchOptions } from "./launcher.ts";
|
|
2
|
+
import { type ErrorClasses, Transport } from "./transport.ts";
|
|
3
|
+
import type { QuietState } from "./wait.ts";
|
|
4
|
+
/** What a handle needs to call the server: the transport, and the session it lives in. */
|
|
5
|
+
export interface HandleContext {
|
|
6
|
+
readonly transport: Transport;
|
|
7
|
+
readonly session: string | undefined;
|
|
8
|
+
}
|
|
9
|
+
/** The session a handle lives in. Only the root client has none. */
|
|
10
|
+
export declare function sessionOf(context: HandleContext): string;
|
|
11
|
+
/**
|
|
12
|
+
* Every handle that lives in a session answers this: is the agent quiet there? Matchers use it for
|
|
13
|
+
* negative and exact-count checks, whatever handle they are given.
|
|
14
|
+
*/
|
|
15
|
+
export declare const QUIET: unique symbol;
|
|
16
|
+
/** Anything a matcher can ask about quiet: any generated handle in a session. */
|
|
17
|
+
export interface InSession {
|
|
18
|
+
[QUIET](): Promise<QuietState>;
|
|
19
|
+
}
|
|
20
|
+
/** Give a value its text form: `String(value)` and `value.toString()` return `text`, and the value keeps its fields. */
|
|
21
|
+
export declare function printsAs<T extends object>(value: T, text: string): T & {
|
|
22
|
+
toString(): string;
|
|
23
|
+
};
|
|
24
|
+
/** Ask the server whether the agent is quiet in the session a handle lives in. */
|
|
25
|
+
export declare function quietOf(context: HandleContext): Promise<QuietState>;
|
|
26
|
+
/**
|
|
27
|
+
* Run a handle's disposer. Disposing only cleans up and never fails a test: when the handle is
|
|
28
|
+
* already gone on the server (closed earlier, or dropped by a reset), there is nothing left to do.
|
|
29
|
+
* An explicit call to the same method still reports that.
|
|
30
|
+
*/
|
|
31
|
+
export declare function disposeQuietly(dispose: () => Promise<void>): Promise<void>;
|
|
32
|
+
/** Base of the generated root client: closing it stops the server if this client started it. */
|
|
33
|
+
export declare abstract class ClientBase implements AsyncDisposable {
|
|
34
|
+
#private;
|
|
35
|
+
constructor(stop: () => Promise<void>);
|
|
36
|
+
close(): Promise<void>;
|
|
37
|
+
[Symbol.asyncDispose](): Promise<void>;
|
|
38
|
+
}
|
|
39
|
+
/** What the generated SDK knows about the protocol it was generated from. */
|
|
40
|
+
export interface Protocol {
|
|
41
|
+
basePath: string;
|
|
42
|
+
errors: ErrorClasses;
|
|
43
|
+
/** The server version the SDK was generated for. */
|
|
44
|
+
version: string;
|
|
45
|
+
}
|
|
46
|
+
/** Find or start the server, check that it speaks this SDK's major version, and build the root client. */
|
|
47
|
+
export declare function connectWith<T>(create: (transport: Transport, stop: () => Promise<void>) => T, protocol: Protocol, options: LaunchOptions): Promise<T>;
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import { launch } from "./launcher.js";
|
|
2
|
+
import { ChannelstackError, segment, Transport } from "./transport.js";
|
|
3
|
+
/** The session a handle lives in. Only the root client has none. */
|
|
4
|
+
export function sessionOf(context) {
|
|
5
|
+
if (context.session === undefined)
|
|
6
|
+
throw new Error("This handle doesn't belong to a session");
|
|
7
|
+
return context.session;
|
|
8
|
+
}
|
|
9
|
+
/**
|
|
10
|
+
* Every handle that lives in a session answers this: is the agent quiet there? Matchers use it for
|
|
11
|
+
* negative and exact-count checks, whatever handle they are given.
|
|
12
|
+
*/
|
|
13
|
+
export const QUIET = Symbol.for("channelstack.quiet");
|
|
14
|
+
/** Give a value its text form: `String(value)` and `value.toString()` return `text`, and the value keeps its fields. */
|
|
15
|
+
export function printsAs(value, text) {
|
|
16
|
+
return Object.defineProperty(value, "toString", { value: () => text, enumerable: false });
|
|
17
|
+
}
|
|
18
|
+
/** Ask the server whether the agent is quiet in the session a handle lives in. */
|
|
19
|
+
export async function quietOf(context) {
|
|
20
|
+
return (await context.transport.request("GET", `/sessions/${segment(sessionOf(context))}/quiet`));
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* Run a handle's disposer. Disposing only cleans up and never fails a test: when the handle is
|
|
24
|
+
* already gone on the server (closed earlier, or dropped by a reset), there is nothing left to do.
|
|
25
|
+
* An explicit call to the same method still reports that.
|
|
26
|
+
*/
|
|
27
|
+
export async function disposeQuietly(dispose) {
|
|
28
|
+
try {
|
|
29
|
+
await dispose();
|
|
30
|
+
}
|
|
31
|
+
catch (error) {
|
|
32
|
+
if (!(error instanceof ChannelstackError && error.status === 404))
|
|
33
|
+
throw error;
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
/** Base of the generated root client: closing it stops the server if this client started it. */
|
|
37
|
+
export class ClientBase {
|
|
38
|
+
#stop;
|
|
39
|
+
constructor(stop) {
|
|
40
|
+
this.#stop = stop;
|
|
41
|
+
}
|
|
42
|
+
async close() {
|
|
43
|
+
await this.#stop();
|
|
44
|
+
}
|
|
45
|
+
async [Symbol.asyncDispose]() {
|
|
46
|
+
await this.close();
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
/** Find or start the server, check that it speaks this SDK's major version, and build the root client. */
|
|
50
|
+
export async function connectWith(create, protocol, options) {
|
|
51
|
+
const server = await launch(options);
|
|
52
|
+
const transport = new Transport({
|
|
53
|
+
url: server.url,
|
|
54
|
+
token: server.token,
|
|
55
|
+
basePath: protocol.basePath,
|
|
56
|
+
errors: protocol.errors,
|
|
57
|
+
});
|
|
58
|
+
try {
|
|
59
|
+
const { version } = (await transport.request("GET", "/status"));
|
|
60
|
+
if (version.split(".")[0] !== protocol.version.split(".")[0]) {
|
|
61
|
+
throw new Error(`The channelstack server is version ${version}, but this SDK was generated for ${protocol.version}`);
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
catch (error) {
|
|
65
|
+
await server.stop();
|
|
66
|
+
throw error;
|
|
67
|
+
}
|
|
68
|
+
return create(transport, server.stop);
|
|
69
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A credential from the environment, when a test leaves it out: `CHANNELSTACK_SLACK_USER_{name}_TOKEN`
|
|
3
|
+
* with `{ name: "Ana" }` reads `CHANNELSTACK_SLACK_USER_ANA_TOKEN`. Unset (or empty), it is
|
|
4
|
+
* `undefined`, and the object is fake. So one test runs fake on every PR and live where the
|
|
5
|
+
* variables are set (live-mode.md, section 4).
|
|
6
|
+
*/
|
|
7
|
+
export declare function credential(template: string, values: Readonly<Record<string, unknown>>): string | undefined;
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
/** A name as it appears in an environment variable: `Ana` → `ANA`, `ana-smith` → `ANA_SMITH`. */
|
|
2
|
+
function envName(value) {
|
|
3
|
+
return String(value)
|
|
4
|
+
.toUpperCase()
|
|
5
|
+
.replace(/[^A-Z0-9]+/g, "_");
|
|
6
|
+
}
|
|
7
|
+
/**
|
|
8
|
+
* A credential from the environment, when a test leaves it out: `CHANNELSTACK_SLACK_USER_{name}_TOKEN`
|
|
9
|
+
* with `{ name: "Ana" }` reads `CHANNELSTACK_SLACK_USER_ANA_TOKEN`. Unset (or empty), it is
|
|
10
|
+
* `undefined`, and the object is fake. So one test runs fake on every PR and live where the
|
|
11
|
+
* variables are set (live-mode.md, section 4).
|
|
12
|
+
*/
|
|
13
|
+
export function credential(template, values) {
|
|
14
|
+
const missing = [...template.matchAll(/\{(\w+)\}/g)].some((match) => values[match[1]] === undefined);
|
|
15
|
+
if (missing)
|
|
16
|
+
return undefined;
|
|
17
|
+
const variable = template.replace(/\{(\w+)\}/g, (_, field) => envName(values[field]));
|
|
18
|
+
const env = globalThis.process?.env ?? {};
|
|
19
|
+
return env[variable] || undefined;
|
|
20
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
const UNITS = { ms: 1, s: 1000, m: 60_000 };
|
|
2
|
+
/** A duration in milliseconds. */
|
|
3
|
+
export function parseDuration(duration) {
|
|
4
|
+
if (typeof duration === "number") {
|
|
5
|
+
if (!Number.isFinite(duration) || duration < 0)
|
|
6
|
+
throw new TypeError(`Not a duration: ${duration}`);
|
|
7
|
+
return duration;
|
|
8
|
+
}
|
|
9
|
+
const match = /^(\d+(?:\.\d+)?)(ms|s|m)$/.exec(duration);
|
|
10
|
+
if (!match)
|
|
11
|
+
throw new TypeError(`Not a duration: "${duration}". Use milliseconds, or "250ms", "3s", "1m".`);
|
|
12
|
+
return Number(match[1]) * UNITS[match[2]];
|
|
13
|
+
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
/** Files in a test: inline contents, or a path to a fixture file or directory (`api/common.d.ts`). */
|
|
2
|
+
export type FileInput = {
|
|
3
|
+
name: string;
|
|
4
|
+
content: string | Uint8Array;
|
|
5
|
+
mimeType?: string;
|
|
6
|
+
} | {
|
|
7
|
+
path: string;
|
|
8
|
+
name?: string;
|
|
9
|
+
};
|
|
10
|
+
/** A file as it travels to the server: where it goes, and its bytes in base64. */
|
|
11
|
+
interface WireFile {
|
|
12
|
+
path: string;
|
|
13
|
+
content: string;
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* Where relative fixture paths start from. A test framework integration sets it to the directory
|
|
17
|
+
* of the test file, so `files: "./fixtures/web"` means what it means in an import. Without it,
|
|
18
|
+
* paths start from the working directory.
|
|
19
|
+
*/
|
|
20
|
+
export declare function setFilesRoot(directory: string | undefined): void;
|
|
21
|
+
/** A whole tree of files: a fixture directory, or a list of files. */
|
|
22
|
+
export declare function readTree(input: string | FileInput[]): WireFile[];
|
|
23
|
+
/** Changes to files: a list of files, or a map of path to its new contents, where `null` deletes the file. */
|
|
24
|
+
export declare function readChanges(input: FileInput[] | Record<string, string | null>): Array<{
|
|
25
|
+
path: string;
|
|
26
|
+
content: string | null;
|
|
27
|
+
}>;
|
|
28
|
+
/** One text a test hands over: inline, or the contents of a fixture file (`{ path }`). Structured content passes as it is. */
|
|
29
|
+
export declare function readDocument(input: string | {
|
|
30
|
+
path: string;
|
|
31
|
+
} | unknown[]): string | unknown[];
|
|
32
|
+
export {};
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import { readdirSync, readFileSync, statSync } from "node:fs";
|
|
2
|
+
import { isAbsolute, join, relative, resolve, sep } from "node:path";
|
|
3
|
+
let root;
|
|
4
|
+
/**
|
|
5
|
+
* Where relative fixture paths start from. A test framework integration sets it to the directory
|
|
6
|
+
* of the test file, so `files: "./fixtures/web"` means what it means in an import. Without it,
|
|
7
|
+
* paths start from the working directory.
|
|
8
|
+
*/
|
|
9
|
+
export function setFilesRoot(directory) {
|
|
10
|
+
root = directory;
|
|
11
|
+
}
|
|
12
|
+
const located = (path) => (isAbsolute(path) ? path : resolve(root ?? process.cwd(), path));
|
|
13
|
+
const base64 = (content) => Buffer.from(content).toString("base64");
|
|
14
|
+
/** Every file under a directory, by its path inside it, with forward slashes. */
|
|
15
|
+
function walk(directory) {
|
|
16
|
+
return readdirSync(directory, { recursive: true, withFileTypes: true })
|
|
17
|
+
.filter((entry) => entry.isFile())
|
|
18
|
+
.map((entry) => join(entry.parentPath, entry.name))
|
|
19
|
+
.sort()
|
|
20
|
+
.map((file) => ({ path: relative(directory, file).split(sep).join("/"), content: base64(readFileSync(file)) }));
|
|
21
|
+
}
|
|
22
|
+
/** One file input as wire files: inline contents, a file on disk, or everything under a directory on disk. */
|
|
23
|
+
function read(input) {
|
|
24
|
+
if ("content" in input)
|
|
25
|
+
return [{ path: input.name, content: base64(input.content) }];
|
|
26
|
+
const path = located(input.path);
|
|
27
|
+
if (statSync(path).isDirectory()) {
|
|
28
|
+
return walk(path).map((file) => ({ ...file, path: input.name ? `${input.name}/${file.path}` : file.path }));
|
|
29
|
+
}
|
|
30
|
+
return [{ path: input.name ?? input.path.split(/[\\/]/).at(-1) ?? input.path, content: base64(readFileSync(path)) }];
|
|
31
|
+
}
|
|
32
|
+
/** A whole tree of files: a fixture directory, or a list of files. */
|
|
33
|
+
export function readTree(input) {
|
|
34
|
+
return typeof input === "string" ? walk(located(input)) : input.flatMap(read);
|
|
35
|
+
}
|
|
36
|
+
/** Changes to files: a list of files, or a map of path to its new contents, where `null` deletes the file. */
|
|
37
|
+
export function readChanges(input) {
|
|
38
|
+
if (Array.isArray(input))
|
|
39
|
+
return input.flatMap(read);
|
|
40
|
+
return Object.entries(input).map(([path, content]) => ({ path, content: content === null ? null : base64(content) }));
|
|
41
|
+
}
|
|
42
|
+
/** One text a test hands over: inline, or the contents of a fixture file (`{ path }`). Structured content passes as it is. */
|
|
43
|
+
export function readDocument(input) {
|
|
44
|
+
return typeof input === "string" || Array.isArray(input) ? input : readFileSync(located(input.path), "utf8");
|
|
45
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
export interface LaunchOptions {
|
|
2
|
+
/**
|
|
3
|
+
* `auto` (default): attach if a server is running, otherwise start one for the run.
|
|
4
|
+
* `attach`: fail if none is running. `start`: always start a private one.
|
|
5
|
+
*/
|
|
6
|
+
mode?: "auto" | "attach" | "start";
|
|
7
|
+
/** Attach to this server instead of the one in `server.json`. Also `CHANNELSTACK_URL`, with `CHANNELSTACK_TOKEN`. */
|
|
8
|
+
server?: string;
|
|
9
|
+
/** The token for `server`, when the caller has it. It then never needs to be in the environment. */
|
|
10
|
+
token?: string;
|
|
11
|
+
}
|
|
12
|
+
/** A server to talk to. `stop` only stops a server this launcher started. */
|
|
13
|
+
export interface ServerConnection {
|
|
14
|
+
url: string;
|
|
15
|
+
token: string;
|
|
16
|
+
stop(): Promise<void>;
|
|
17
|
+
}
|
|
18
|
+
/** The npm package that carries the server binary for this machine. */
|
|
19
|
+
export declare function serverPackageName(platform?: string, arch?: string): string;
|
|
20
|
+
export declare function serverBinaryName(platform?: string): string;
|
|
21
|
+
/** The server binary: `CHANNELSTACK_SERVER_BIN`, or the one installed with the `channelstack` package. */
|
|
22
|
+
export declare function resolveServerBinary(env?: NodeJS.ProcessEnv): string;
|
|
23
|
+
/** Find or start the server, by `mode`. */
|
|
24
|
+
export declare function launch(options?: LaunchOptions, env?: NodeJS.ProcessEnv): Promise<ServerConnection>;
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
import { spawn } from "node:child_process";
|
|
2
|
+
import { mkdtempSync, readFileSync, rmSync } from "node:fs";
|
|
3
|
+
import { createRequire } from "node:module";
|
|
4
|
+
import { homedir, tmpdir } from "node:os";
|
|
5
|
+
import { join } from "node:path";
|
|
6
|
+
import { waitFor } from "./wait.js";
|
|
7
|
+
const STATUS_PATH = "/_channelstack/status";
|
|
8
|
+
function withoutTrailingSlash(url) {
|
|
9
|
+
return url ? url.replace(/\/+$/, "") : undefined;
|
|
10
|
+
}
|
|
11
|
+
function readServerFile(path) {
|
|
12
|
+
try {
|
|
13
|
+
const { url, token } = JSON.parse(readFileSync(path, "utf8"));
|
|
14
|
+
return typeof url === "string" && typeof token === "string" ? { url: url.replace(/\/+$/, ""), token } : undefined;
|
|
15
|
+
}
|
|
16
|
+
catch {
|
|
17
|
+
return undefined;
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
async function isUp({ url, token }) {
|
|
21
|
+
try {
|
|
22
|
+
const response = await fetch(new URL(STATUS_PATH, url), {
|
|
23
|
+
headers: { authorization: `Bearer ${token}` },
|
|
24
|
+
signal: AbortSignal.timeout(2000),
|
|
25
|
+
});
|
|
26
|
+
return response.ok;
|
|
27
|
+
}
|
|
28
|
+
catch {
|
|
29
|
+
return false;
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
/** The running server a client should attach to, if there is one: an explicit URL, or the one in `server.json`. */
|
|
33
|
+
function attachTarget(options, env) {
|
|
34
|
+
// An empty variable (an unset CI secret) counts as not set, and a trailing slash doesn't matter.
|
|
35
|
+
const url = withoutTrailingSlash(options.server || env.CHANNELSTACK_URL);
|
|
36
|
+
const home = env.CHANNELSTACK_HOME || join(homedir(), ".channelstack");
|
|
37
|
+
const file = readServerFile(join(home, "server.json"));
|
|
38
|
+
if (url === undefined)
|
|
39
|
+
return file;
|
|
40
|
+
const token = options.token || env.CHANNELSTACK_TOKEN || (file?.url === url ? file.token : undefined);
|
|
41
|
+
return token === undefined ? undefined : { url, token };
|
|
42
|
+
}
|
|
43
|
+
/** The npm package that carries the server binary for this machine. */
|
|
44
|
+
export function serverPackageName(platform = process.platform, arch = process.arch) {
|
|
45
|
+
return `@channelstack/server-${platform}-${arch}`;
|
|
46
|
+
}
|
|
47
|
+
export function serverBinaryName(platform = process.platform) {
|
|
48
|
+
return platform === "win32" ? "channelstack.exe" : "channelstack";
|
|
49
|
+
}
|
|
50
|
+
/** The server binary: `CHANNELSTACK_SERVER_BIN`, or the one installed with the `channelstack` package. */
|
|
51
|
+
export function resolveServerBinary(env = process.env) {
|
|
52
|
+
if (env.CHANNELSTACK_SERVER_BIN)
|
|
53
|
+
return env.CHANNELSTACK_SERVER_BIN;
|
|
54
|
+
const name = serverPackageName();
|
|
55
|
+
try {
|
|
56
|
+
return createRequire(import.meta.url).resolve(`${name}/bin/${serverBinaryName()}`);
|
|
57
|
+
}
|
|
58
|
+
catch {
|
|
59
|
+
throw new Error(`channelstack has no server binary for ${process.platform}-${process.arch}: the optional dependency ${name} isn't installed. ` +
|
|
60
|
+
"Reinstall without --no-optional, or set CHANNELSTACK_SERVER_BIN.");
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
/** Start a private server on a free loopback port. Its token goes to a private file, never to the shared `server.json`. */
|
|
64
|
+
async function startServer(env) {
|
|
65
|
+
const directory = mkdtempSync(join(tmpdir(), "channelstack-"));
|
|
66
|
+
const serverFile = join(directory, "server.json");
|
|
67
|
+
const child = spawn(resolveServerBinary(env), ["start", "--no-portless", "--port", "0", "--server-file", serverFile], { env, stdio: ["ignore", "ignore", "inherit"] });
|
|
68
|
+
// Set once the process is gone: how it ended, in words for the error message.
|
|
69
|
+
let ended;
|
|
70
|
+
const exit = new Promise((resolve) => {
|
|
71
|
+
child.once("exit", (code, signal) => {
|
|
72
|
+
ended = `exited with ${code ?? signal}`;
|
|
73
|
+
resolve();
|
|
74
|
+
});
|
|
75
|
+
child.once("error", (error) => {
|
|
76
|
+
ended = `could not be started: ${error.message}`;
|
|
77
|
+
resolve();
|
|
78
|
+
});
|
|
79
|
+
});
|
|
80
|
+
// If this process ends without closing the client, the server must not outlive it.
|
|
81
|
+
const onProcessExit = () => {
|
|
82
|
+
child.kill("SIGTERM");
|
|
83
|
+
rmSync(directory, { recursive: true, force: true });
|
|
84
|
+
};
|
|
85
|
+
process.once("exit", onProcessExit);
|
|
86
|
+
const stop = async () => {
|
|
87
|
+
process.removeListener("exit", onProcessExit);
|
|
88
|
+
if (ended === undefined)
|
|
89
|
+
child.kill("SIGTERM");
|
|
90
|
+
await exit;
|
|
91
|
+
rmSync(directory, { recursive: true, force: true });
|
|
92
|
+
};
|
|
93
|
+
try {
|
|
94
|
+
const server = await waitFor("the channelstack server to start", async () => {
|
|
95
|
+
if (ended !== undefined)
|
|
96
|
+
throw new Error(`The channelstack server ${ended} before it was ready`);
|
|
97
|
+
const file = readServerFile(serverFile);
|
|
98
|
+
return file && (await isUp(file)) ? file : undefined;
|
|
99
|
+
}, { timeout: "15s" });
|
|
100
|
+
return { ...server, stop };
|
|
101
|
+
}
|
|
102
|
+
catch (error) {
|
|
103
|
+
await stop();
|
|
104
|
+
throw error;
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
/** Find or start the server, by `mode`. */
|
|
108
|
+
export async function launch(options = {}, env = process.env) {
|
|
109
|
+
const mode = options.mode ?? "auto";
|
|
110
|
+
if (mode !== "start") {
|
|
111
|
+
const target = attachTarget(options, env);
|
|
112
|
+
if (target && (await isUp(target)))
|
|
113
|
+
return { ...target, stop: async () => { } };
|
|
114
|
+
if (mode === "attach") {
|
|
115
|
+
throw new Error(target
|
|
116
|
+
? `No channelstack server is answering at ${target.url}. Start one with \`npx channelstack\`.`
|
|
117
|
+
: "No running channelstack server found. Start one with `npx channelstack`, or set CHANNELSTACK_URL and CHANNELSTACK_TOKEN.");
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
return startServer(env);
|
|
121
|
+
}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
/** An error from the control API. `code` is the protocol's stable error code. */
|
|
2
|
+
export declare class ChannelstackError extends Error {
|
|
3
|
+
readonly code: string;
|
|
4
|
+
readonly status: number;
|
|
5
|
+
readonly data: Readonly<Record<string, unknown>>;
|
|
6
|
+
constructor(code: string, status: number, message: string, data?: Readonly<Record<string, unknown>>);
|
|
7
|
+
}
|
|
8
|
+
/**
|
|
9
|
+
* Called with every refusal before it is thrown. A test integration uses it to turn a refusal
|
|
10
|
+
* into its framework's own outcome: an operation live mode can't do skips the test, with the reason.
|
|
11
|
+
*/
|
|
12
|
+
type RefusalHandler = (error: ChannelstackError, path: string) => void;
|
|
13
|
+
/** Set (or, with `undefined`, clear) what sees every refusal before it is thrown. */
|
|
14
|
+
export declare function onRefusal(handler: RefusalHandler | undefined): void;
|
|
15
|
+
/**
|
|
16
|
+
* Run a read whose refusals go only to its caller, not to the refusal handler: for what is only
|
|
17
|
+
* nice to have, like the open work a failure message adds. A refused read then can't turn a
|
|
18
|
+
* failing test into a skipped one.
|
|
19
|
+
*/
|
|
20
|
+
export declare function unreportedRefusals<T>(read: () => Promise<T>): Promise<T>;
|
|
21
|
+
/** Error code → the typed exception the generated SDK declares for it. */
|
|
22
|
+
export type ErrorClasses = Readonly<Record<string, typeof ChannelstackError>>;
|
|
23
|
+
export interface TransportOptions {
|
|
24
|
+
/** The server's base URL, e.g. `https://channelstack.localhost`. */
|
|
25
|
+
url: string;
|
|
26
|
+
token: string;
|
|
27
|
+
/** The control API's path prefix on the server. */
|
|
28
|
+
basePath: string;
|
|
29
|
+
errors: ErrorClasses;
|
|
30
|
+
}
|
|
31
|
+
export interface RequestOptions {
|
|
32
|
+
body?: unknown;
|
|
33
|
+
query?: Readonly<Record<string, string | number | boolean | undefined>>;
|
|
34
|
+
}
|
|
35
|
+
/** One path segment, escaped. */
|
|
36
|
+
export declare function segment(value: string | number): string;
|
|
37
|
+
/** The HTTP client every generated method goes through: bearer token, retries while the server starts, typed errors. */
|
|
38
|
+
export declare class Transport {
|
|
39
|
+
#private;
|
|
40
|
+
constructor(options: TransportOptions);
|
|
41
|
+
request(method: string, path: string, options?: RequestOptions): Promise<unknown>;
|
|
42
|
+
}
|
|
43
|
+
export {};
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
2
|
+
/** An error from the control API. `code` is the protocol's stable error code. */
|
|
3
|
+
export class ChannelstackError extends Error {
|
|
4
|
+
code;
|
|
5
|
+
status;
|
|
6
|
+
data;
|
|
7
|
+
constructor(code, status, message, data = {}) {
|
|
8
|
+
super(message);
|
|
9
|
+
this.name = new.target.name;
|
|
10
|
+
this.code = code;
|
|
11
|
+
this.status = status;
|
|
12
|
+
this.data = data;
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
let refusalHandler;
|
|
16
|
+
/** Set (or, with `undefined`, clear) what sees every refusal before it is thrown. */
|
|
17
|
+
export function onRefusal(handler) {
|
|
18
|
+
refusalHandler = handler;
|
|
19
|
+
}
|
|
20
|
+
/** Reads whose refusals go to their caller only: scoped to their own async context, so others' still do. */
|
|
21
|
+
const unreported = new AsyncLocalStorage();
|
|
22
|
+
/**
|
|
23
|
+
* Run a read whose refusals go only to its caller, not to the refusal handler: for what is only
|
|
24
|
+
* nice to have, like the open work a failure message adds. A refused read then can't turn a
|
|
25
|
+
* failing test into a skipped one.
|
|
26
|
+
*/
|
|
27
|
+
export function unreportedRefusals(read) {
|
|
28
|
+
return unreported.run(true, read);
|
|
29
|
+
}
|
|
30
|
+
/** How long to keep retrying a connection that is refused, while the server starts. */
|
|
31
|
+
const CONNECT_RETRY_MS = 5000;
|
|
32
|
+
const CONNECT_RETRY_INTERVAL_MS = 100;
|
|
33
|
+
/** Node reports a refused connection as `cause.code === "ECONNREFUSED"`, Bun as `code === "ConnectionRefused"`. */
|
|
34
|
+
function isConnectionRefused(error) {
|
|
35
|
+
const codes = [error.code, error.cause?.code];
|
|
36
|
+
return codes.includes("ECONNREFUSED") || codes.includes("ConnectionRefused");
|
|
37
|
+
}
|
|
38
|
+
/** One path segment, escaped. */
|
|
39
|
+
export function segment(value) {
|
|
40
|
+
return encodeURIComponent(value);
|
|
41
|
+
}
|
|
42
|
+
/** The HTTP client every generated method goes through: bearer token, retries while the server starts, typed errors. */
|
|
43
|
+
export class Transport {
|
|
44
|
+
#options;
|
|
45
|
+
constructor(options) {
|
|
46
|
+
this.#options = options;
|
|
47
|
+
}
|
|
48
|
+
async request(method, path, options = {}) {
|
|
49
|
+
const url = new URL(`${this.#options.basePath}${path}`, this.#options.url);
|
|
50
|
+
for (const [name, value] of Object.entries(options.query ?? {})) {
|
|
51
|
+
if (value !== undefined)
|
|
52
|
+
url.searchParams.set(name, String(value));
|
|
53
|
+
}
|
|
54
|
+
const response = await this.#send(url, {
|
|
55
|
+
method,
|
|
56
|
+
headers: {
|
|
57
|
+
authorization: `Bearer ${this.#options.token}`,
|
|
58
|
+
...(options.body === undefined ? {} : { "content-type": "application/json" }),
|
|
59
|
+
},
|
|
60
|
+
...(options.body === undefined ? {} : { body: JSON.stringify(options.body) }),
|
|
61
|
+
});
|
|
62
|
+
const text = await response.text();
|
|
63
|
+
let payload;
|
|
64
|
+
try {
|
|
65
|
+
payload = text === "" ? undefined : JSON.parse(text);
|
|
66
|
+
}
|
|
67
|
+
catch {
|
|
68
|
+
// Not the control API talking: a proxy's error page, for example.
|
|
69
|
+
throw new ChannelstackError("internal", response.status, `HTTP ${response.status}: the response is not JSON`);
|
|
70
|
+
}
|
|
71
|
+
if (response.ok)
|
|
72
|
+
return payload;
|
|
73
|
+
const { error = "internal", message = `HTTP ${response.status}`, data = {}, } = (typeof payload === "object" && payload !== null ? payload : {});
|
|
74
|
+
const ErrorClass = this.#options.errors[error] ?? ChannelstackError;
|
|
75
|
+
const refusal = new ErrorClass(error, response.status, message, data);
|
|
76
|
+
if (!unreported.getStore())
|
|
77
|
+
refusalHandler?.(refusal, path);
|
|
78
|
+
throw refusal;
|
|
79
|
+
}
|
|
80
|
+
async #send(url, init) {
|
|
81
|
+
const deadline = Date.now() + CONNECT_RETRY_MS;
|
|
82
|
+
for (;;) {
|
|
83
|
+
try {
|
|
84
|
+
return await fetch(url, init);
|
|
85
|
+
}
|
|
86
|
+
catch (error) {
|
|
87
|
+
// Only a refused connection is retried: the server isn't listening yet, so nothing was sent.
|
|
88
|
+
// Any other failure may have happened after the request went out, and a POST must not run twice.
|
|
89
|
+
if (!isConnectionRefused(error) || Date.now() > deadline)
|
|
90
|
+
throw error;
|
|
91
|
+
await new Promise((resolve) => setTimeout(resolve, CONNECT_RETRY_INTERVAL_MS));
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
}
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
import { type Duration } from "./duration.ts";
|
|
2
|
+
export interface WaitOptions {
|
|
3
|
+
/** Give up after this long. Default: 10s, or what `setWaitDefaults` set. */
|
|
4
|
+
timeout?: Duration;
|
|
5
|
+
/** How often to read. Default: 50ms. */
|
|
6
|
+
interval?: Duration;
|
|
7
|
+
}
|
|
8
|
+
/** What every wait uses when it isn't given a `timeout` or `quietFor`. */
|
|
9
|
+
export interface WaitDefaults {
|
|
10
|
+
timeout: Duration;
|
|
11
|
+
quietFor: Duration;
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* Change the default `timeout` and `quietFor` of every wait: `waitFor…`, `latest…`, the reads that
|
|
15
|
+
* wait for quiet, and calls repeated while refused. The Vitest plugin sets them from its `timeout`
|
|
16
|
+
* and `quietFor` options. What isn't given stays as it is.
|
|
17
|
+
*/
|
|
18
|
+
export declare function setWaitDefaults(options: Partial<WaitDefaults>): void;
|
|
19
|
+
/** The defaults every wait uses now (a copy). */
|
|
20
|
+
export declare function waitDefaults(): WaitDefaults;
|
|
21
|
+
export declare class WaitTimeoutError extends Error {
|
|
22
|
+
constructor(what: string, timeoutMs: number);
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* The one polling loop: read until `read` returns something other than undefined, or the
|
|
26
|
+
* timeout passes. Every `waitFor…`, `latest…` and matcher is built on it; tests never sleep.
|
|
27
|
+
*/
|
|
28
|
+
export declare function waitFor<T>(what: string | (() => string), read: () => Promise<T | undefined>, options?: WaitOptions): Promise<T>;
|
|
29
|
+
/**
|
|
30
|
+
* Repeat a call while it is refused with one of these error codes, the way a person waits for a
|
|
31
|
+
* button to appear before clicking it. When the time is up, the last refusal is the error.
|
|
32
|
+
*/
|
|
33
|
+
export declare function retryWhile<T>(codes: readonly string[], call: () => Promise<T>, options?: WaitOptions): Promise<T>;
|
|
34
|
+
export interface QuietOptions extends WaitOptions {
|
|
35
|
+
/**
|
|
36
|
+
* How long the agent must be quiet (no call in flight, no delivery in flight or about to be retried, no open stream)
|
|
37
|
+
* before the result is read. Default: 750ms, or what `setWaitDefaults` set.
|
|
38
|
+
*/
|
|
39
|
+
quietFor?: Duration;
|
|
40
|
+
}
|
|
41
|
+
/** What the server says about the agent's activity in a session (`GET /sessions/{sid}/quiet`). */
|
|
42
|
+
export interface QuietState {
|
|
43
|
+
busy: boolean;
|
|
44
|
+
quietForMs: number;
|
|
45
|
+
/** What is still open, in words: a delivery in flight or about to be retried, a stream the agent never stopped. */
|
|
46
|
+
open: string[];
|
|
47
|
+
}
|
|
48
|
+
/** Anyone who can author something: a handle with an id and a name. */
|
|
49
|
+
interface Author {
|
|
50
|
+
readonly id: string;
|
|
51
|
+
readonly name: string;
|
|
52
|
+
}
|
|
53
|
+
/** Does an item's author match a `from` filter: a handle, a name, or nothing (anyone)? */
|
|
54
|
+
export declare function fromMatches(author: Author, from: Author | string | undefined): boolean;
|
|
55
|
+
/** Does a text match what was asked for: a string it contains, a pattern, or nothing (any text)? */
|
|
56
|
+
export declare function textMatches(text: string, expected: string | RegExp | undefined): boolean;
|
|
57
|
+
/** Text to find as it goes to the server: a string as it is, a `RegExp` as its source and flags. */
|
|
58
|
+
export declare function patternOnWire(pattern: string | RegExp): string | {
|
|
59
|
+
source: string;
|
|
60
|
+
flags: string;
|
|
61
|
+
};
|
|
62
|
+
/** "a reply" → "a reply from my-agent", for timeout messages. */
|
|
63
|
+
export declare function describeWait(what: string, from: Author | string | undefined): string;
|
|
64
|
+
/**
|
|
65
|
+
* Wait for the next new item of a list that matches, after the last one this handle returned.
|
|
66
|
+
* `seen` belongs to the handle and remembers, per wait, how far it has looked. With `startsTurn`,
|
|
67
|
+
* the wait also looks only after the newest item that starts a turn (a person's prompt).
|
|
68
|
+
*/
|
|
69
|
+
export declare function waitForNext<T>(seen: Map<string, number>, key: string, read: () => Promise<readonly T[]>, matches: (item: T) => boolean, what: string, options?: WaitOptions, startsTurn?: (item: T) => boolean): Promise<T>;
|
|
70
|
+
/**
|
|
71
|
+
* Resolve once the agent has been quiet for `quietFor`. Negative and exact-count checks read after this.
|
|
72
|
+
*
|
|
73
|
+
* With `watching`, the quiet time counts from now at the earliest: the caller wants to have looked
|
|
74
|
+
* for the whole window. An agent that is thinking makes no sound, so a session that went quiet a
|
|
75
|
+
* while ago says nothing about what arrives next.
|
|
76
|
+
*/
|
|
77
|
+
export declare function untilQuiet(quiet: () => Promise<QuietState>, options?: QuietOptions & {
|
|
78
|
+
watching?: boolean;
|
|
79
|
+
}): Promise<void>;
|
|
80
|
+
/** The last item of a list that matches, read once the agent is quiet. Waits for at least one first. */
|
|
81
|
+
export declare function latestOnceQuiet<T>(read: () => Promise<readonly T[]>, matches: (item: T) => boolean, quiet: () => Promise<QuietState>, what: string, options?: QuietOptions): Promise<T>;
|
|
82
|
+
export {};
|