@compivia/plugin-sdk 0.0.0-stage → 0.0.1280
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +17 -2
- package/dist/const.d.ts +15 -0
- package/dist/define.d.ts +8 -0
- package/dist/harness.d.ts +148 -0
- package/dist/index.d.ts +7 -0
- package/dist/index.js +294 -0
- package/dist/parse-manifest.d.ts +49 -0
- package/dist/reporter.d.ts +35 -0
- package/dist/settings.d.ts +26 -0
- package/dist/slug.d.ts +34 -0
- package/dist/testing-factory.d.ts +48 -0
- package/dist/testing-harness.contract.d.ts +7 -0
- package/dist/testing-reporter.contract.d.ts +5 -0
- package/dist/testing-slug.contract.d.ts +5 -0
- package/dist/testing.d.ts +28 -0
- package/dist/testing.js +487 -0
- package/package.json +48 -4
package/README.md
CHANGED
|
@@ -1,3 +1,18 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @compivia/plugin-sdk
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
SDK для авторства плагинов Compivia: вклады `harness` и `reporter`, строгий
|
|
4
|
+
разбор манифеста `compivia.plugin`, набор соответствия (conformance) в
|
|
5
|
+
`./testing`.
|
|
6
|
+
|
|
7
|
+
## Установка
|
|
8
|
+
|
|
9
|
+
npm install --save-dev @compivia/plugin-sdk
|
|
10
|
+
|
|
11
|
+
Требования: Node >= 24, ESM. Для набора соответствия (`@compivia/plugin-sdk/testing`)
|
|
12
|
+
дополнительно нужен `vitest` — он peer-зависимость этого entry.
|
|
13
|
+
|
|
14
|
+
## Каноническая документация
|
|
15
|
+
|
|
16
|
+
Док автора плагина — `docs/plugin-authoring.md` в репозитории ядра:
|
|
17
|
+
манифест, вклады, conformance, версионирование (`major` пакета = `PLUGIN_API_VERSION`),
|
|
18
|
+
публикация плагина и установка пользователями (`compivia plugin add`).
|
package/dist/const.d.ts
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
/** Версия API плагинов, объявляемая этим SDK. Несовместимые изменения
|
|
2
|
+
* контракта повышают её; аддитивные возможности — нет. */
|
|
3
|
+
export declare const PLUGIN_API_VERSION = 1;
|
|
4
|
+
/** Набор версий API, поддержанных загрузчиком плагинов runner'а. */
|
|
5
|
+
export declare const SUPPORTED_PLUGIN_API_VERSIONS: readonly number[];
|
|
6
|
+
/** Закрытый набор типов вкладов: новый тип — аддитивное изменение SDK в
|
|
7
|
+
* рамках той же PLUGIN_API_VERSION (прецедент — slug, #541: загрузчик
|
|
8
|
+
* старого runner'а отвергает неизвестный kind манифеста, но контракт
|
|
9
|
+
* обработанных вкладов не ломается); ломающее изменение набора — major. */
|
|
10
|
+
export declare const CONTRIBUTION_KINDS: readonly ["harness", "reporter", "slug"];
|
|
11
|
+
export type PluginContributionKind = (typeof CONTRIBUTION_KINDS)[number];
|
|
12
|
+
/** Канонический ключ вклада везде: `kind:id` (enable-записи, CLI-аргументы,
|
|
13
|
+
* логи). */
|
|
14
|
+
export declare const CONTRIBUTION_ID_PATTERN: RegExp;
|
|
15
|
+
export declare const CONTRIBUTION_KEY_PATTERN: RegExp;
|
package/dist/define.d.ts
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import type { HarnessDefinition } from "./harness.js";
|
|
2
|
+
import type { ReporterDefinition } from "./reporter.js";
|
|
3
|
+
import type { SlugGeneratorDefinition } from "./slug.js";
|
|
4
|
+
/** Типизированные хелперы для авторов плагинов; возвращают объект вклада
|
|
5
|
+
* (валидация формы — в contract-тестах и load-check'е). */
|
|
6
|
+
export declare function defineHarness(def: HarnessDefinition): HarnessDefinition;
|
|
7
|
+
export declare function defineReporter(def: ReporterDefinition): ReporterDefinition;
|
|
8
|
+
export declare function defineSlugGenerator(def: SlugGeneratorDefinition): SlugGeneratorDefinition;
|
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
/** Дубликат CommandFailureClass (packages/runner-core/src/command-failures.ts):
|
|
2
|
+
* SDK не зависит от runner-core; форму сверяют contract-тесты. */
|
|
3
|
+
export type FailureClass = "invalid" | "unavailable" | "busy" | "rate_limited" | "route_unavailable" | "failed";
|
|
4
|
+
export type RouteScopeKind = "runner" | "route";
|
|
5
|
+
/** Непрозрачная граница turn'а (из runner-core/src/harness/types.ts). */
|
|
6
|
+
export type TurnCursor = {
|
|
7
|
+
offset: number;
|
|
8
|
+
capturedAt: string;
|
|
9
|
+
fingerprint: string | null;
|
|
10
|
+
};
|
|
11
|
+
/** Нормализованные параметры запуска (из runner-core/src/harness/types.ts). */
|
|
12
|
+
export type AgentLaunchInput = {
|
|
13
|
+
invocationId: string;
|
|
14
|
+
promptFile: string;
|
|
15
|
+
outputSchemaFile: string | null;
|
|
16
|
+
outputSchemaText?: string | null;
|
|
17
|
+
cwd: string;
|
|
18
|
+
logFile: string;
|
|
19
|
+
mode: "write" | "readonly" | "sessionless";
|
|
20
|
+
model?: string;
|
|
21
|
+
effort?: string;
|
|
22
|
+
systemPrompt?: string;
|
|
23
|
+
resume?: {
|
|
24
|
+
sessionId: string;
|
|
25
|
+
};
|
|
26
|
+
sessionId?: string;
|
|
27
|
+
};
|
|
28
|
+
/** Команда запуска (из runner-core/src/harness/types.ts). */
|
|
29
|
+
export type AgentLaunch = {
|
|
30
|
+
command: string;
|
|
31
|
+
args: string[];
|
|
32
|
+
env: Record<string, string>;
|
|
33
|
+
prepare?: () => Promise<void>;
|
|
34
|
+
transcriptPath: string | null;
|
|
35
|
+
};
|
|
36
|
+
/** События вызова shell-инструмента (из runner-core/src/harness/types.ts). */
|
|
37
|
+
export type ShellCallEvent = {
|
|
38
|
+
kind: "start";
|
|
39
|
+
callId: string;
|
|
40
|
+
startedAt?: string;
|
|
41
|
+
} | {
|
|
42
|
+
kind: "end";
|
|
43
|
+
callId: string;
|
|
44
|
+
};
|
|
45
|
+
export type HarnessLine = ({
|
|
46
|
+
kind: "start";
|
|
47
|
+
timestamp?: string;
|
|
48
|
+
} | {
|
|
49
|
+
kind: "final";
|
|
50
|
+
final: string;
|
|
51
|
+
timestamp?: string;
|
|
52
|
+
} | {
|
|
53
|
+
kind: "closed";
|
|
54
|
+
timestamp?: string;
|
|
55
|
+
} | {
|
|
56
|
+
kind: "error";
|
|
57
|
+
timestamp?: string;
|
|
58
|
+
} | {
|
|
59
|
+
kind: "other";
|
|
60
|
+
}) & {
|
|
61
|
+
shellEvents?: ShellCallEvent[];
|
|
62
|
+
};
|
|
63
|
+
export type SessionLocation = {
|
|
64
|
+
path: string;
|
|
65
|
+
};
|
|
66
|
+
export type CheckObservation = {
|
|
67
|
+
reference: string;
|
|
68
|
+
exitCode: number;
|
|
69
|
+
at: string | null;
|
|
70
|
+
};
|
|
71
|
+
export type FinalOutcome = {
|
|
72
|
+
completed: true;
|
|
73
|
+
finalMessage: string;
|
|
74
|
+
} | {
|
|
75
|
+
completed: false;
|
|
76
|
+
reason: string;
|
|
77
|
+
};
|
|
78
|
+
export type NativeFailure = {
|
|
79
|
+
exitCode?: number | null;
|
|
80
|
+
signal?: string | null;
|
|
81
|
+
spawnErrorCode?: string | null;
|
|
82
|
+
message?: string;
|
|
83
|
+
isError?: boolean;
|
|
84
|
+
};
|
|
85
|
+
export type ClassifiedFailure = {
|
|
86
|
+
class: FailureClass;
|
|
87
|
+
scope?: RouteScopeKind;
|
|
88
|
+
retryAfterMs?: number;
|
|
89
|
+
reason?: string;
|
|
90
|
+
};
|
|
91
|
+
export type OutputOutcome = {
|
|
92
|
+
finalMessage: string | null;
|
|
93
|
+
failure: NativeFailure | null;
|
|
94
|
+
};
|
|
95
|
+
/** Стадии `status`-события transcript'а (из runner-core/src/harness/types.ts). */
|
|
96
|
+
export type TranscriptStatusStage = "started" | "finished" | "failed" | "stopped" | "rate_limited" | "error" | "coalesced";
|
|
97
|
+
export type NormalizedTranscriptEvent = {
|
|
98
|
+
kind: "message";
|
|
99
|
+
text: string;
|
|
100
|
+
} | {
|
|
101
|
+
kind: "tool_call";
|
|
102
|
+
tool: string;
|
|
103
|
+
summary: string;
|
|
104
|
+
} | {
|
|
105
|
+
kind: "tool_result";
|
|
106
|
+
ok: boolean;
|
|
107
|
+
summary: string;
|
|
108
|
+
} | {
|
|
109
|
+
kind: "check";
|
|
110
|
+
reference: string;
|
|
111
|
+
exitCode: number;
|
|
112
|
+
} | {
|
|
113
|
+
kind: "status";
|
|
114
|
+
stage: TranscriptStatusStage;
|
|
115
|
+
note?: string;
|
|
116
|
+
};
|
|
117
|
+
export type PluginLogger = {
|
|
118
|
+
debug(message: string, fields?: Record<string, string | number | boolean | null>): void;
|
|
119
|
+
info(message: string, fields?: Record<string, string | number | boolean | null>): void;
|
|
120
|
+
warn(message: string, fields?: Record<string, string | number | boolean | null>): void;
|
|
121
|
+
error(message: string, fields?: Record<string, string | number | boolean | null>): void;
|
|
122
|
+
};
|
|
123
|
+
/** Контекст вызова: структурный логгер с пометкой плагина и сигнал таймаута;
|
|
124
|
+
* без токена runner'а, соли и путей машины. */
|
|
125
|
+
export type HarnessContext = {
|
|
126
|
+
logger: PluginLogger;
|
|
127
|
+
signal: AbortSignal;
|
|
128
|
+
};
|
|
129
|
+
export type DetectResult = {
|
|
130
|
+
status: "ready" | "signin_needed" | "not_installed";
|
|
131
|
+
models: string[];
|
|
132
|
+
version?: string;
|
|
133
|
+
name?: string;
|
|
134
|
+
};
|
|
135
|
+
export type HarnessDefinition = {
|
|
136
|
+
id: string;
|
|
137
|
+
detect(ctx: HarnessContext): Promise<DetectResult>;
|
|
138
|
+
launch(input: AgentLaunchInput): AgentLaunch | Promise<AgentLaunch>;
|
|
139
|
+
classifyLine(line: string): HarnessLine;
|
|
140
|
+
locateSession(sessionId: string): Promise<SessionLocation | null>;
|
|
141
|
+
finalOf(location: SessionLocation, turn?: TurnCursor): Promise<FinalOutcome>;
|
|
142
|
+
checksOf?(location: SessionLocation): Promise<CheckObservation[]>;
|
|
143
|
+
/** Состояние нормализации держит сам модуль плагина: map sessionId → свой
|
|
144
|
+
* нормализатор; host только пересылает вызовы. */
|
|
145
|
+
normalizeLine(sessionId: string, line: string): NormalizedTranscriptEvent[];
|
|
146
|
+
classify(failure: NativeFailure): ClassifiedFailure;
|
|
147
|
+
finalFromOutput(lines: string[]): OutputOutcome;
|
|
148
|
+
};
|
package/dist/index.d.ts
ADDED
package/dist/index.js
ADDED
|
@@ -0,0 +1,294 @@
|
|
|
1
|
+
// src/const.ts
|
|
2
|
+
var PLUGIN_API_VERSION = 1;
|
|
3
|
+
var SUPPORTED_PLUGIN_API_VERSIONS = [1];
|
|
4
|
+
var CONTRIBUTION_KINDS = ["harness", "reporter", "slug"];
|
|
5
|
+
var CONTRIBUTION_ID_PATTERN = /^[a-z][a-z0-9-]{0,31}$/;
|
|
6
|
+
var CONTRIBUTION_KEY_PATTERN = /^[a-z]+:[a-z][a-z0-9-]{0,31}$/;
|
|
7
|
+
|
|
8
|
+
// src/define.ts
|
|
9
|
+
function defineHarness(def) {
|
|
10
|
+
return def;
|
|
11
|
+
}
|
|
12
|
+
function defineReporter(def) {
|
|
13
|
+
return def;
|
|
14
|
+
}
|
|
15
|
+
function defineSlugGenerator(def) {
|
|
16
|
+
return def;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
// src/parse-manifest.ts
|
|
20
|
+
var PluginManifestError = class extends Error {
|
|
21
|
+
constructor(message) {
|
|
22
|
+
super(`invalid plugin manifest: ${message}`);
|
|
23
|
+
this.name = "PluginManifestError";
|
|
24
|
+
}
|
|
25
|
+
};
|
|
26
|
+
var ENV_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;
|
|
27
|
+
function isPlainObject(value) {
|
|
28
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
29
|
+
}
|
|
30
|
+
function unknownFields(value, allowed, path) {
|
|
31
|
+
for (const key of Object.keys(value)) {
|
|
32
|
+
if (!allowed.includes(key)) {
|
|
33
|
+
throw new PluginManifestError(`${path}: unknown field ${JSON.stringify(key)}`);
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
function parseOptionsSchema(value, path) {
|
|
38
|
+
if (!isPlainObject(value) || value.type !== "object") {
|
|
39
|
+
throw new PluginManifestError(`${path}: expected an object schema with type "object"`);
|
|
40
|
+
}
|
|
41
|
+
return value;
|
|
42
|
+
}
|
|
43
|
+
function parseSecrets(value, path) {
|
|
44
|
+
if (!Array.isArray(value)) throw new PluginManifestError(`${path}: expected an array of env names`);
|
|
45
|
+
const names = [];
|
|
46
|
+
for (const [index, item] of value.entries()) {
|
|
47
|
+
if (typeof item !== "string" || !ENV_NAME.test(item)) {
|
|
48
|
+
throw new PluginManifestError(`${path}[${index}]: expected a valid env name`);
|
|
49
|
+
}
|
|
50
|
+
names.push(item);
|
|
51
|
+
}
|
|
52
|
+
return names;
|
|
53
|
+
}
|
|
54
|
+
function parseContribution(value, index) {
|
|
55
|
+
const path = `contributions[${index}]`;
|
|
56
|
+
if (!isPlainObject(value)) throw new PluginManifestError(`${path}: expected an object`);
|
|
57
|
+
const kind = value.kind;
|
|
58
|
+
if (typeof kind !== "string" || !CONTRIBUTION_KINDS.includes(kind)) {
|
|
59
|
+
throw new PluginManifestError(`${path}.kind: expected one of ${CONTRIBUTION_KINDS.join(", ")}`);
|
|
60
|
+
}
|
|
61
|
+
const allowlist = kind === "harness" ? ["kind", "id", "name", "module", "optionsSchema"] : ["kind", "id", "name", "module", "optionsSchema", "secrets"];
|
|
62
|
+
unknownFields(value, allowlist, path);
|
|
63
|
+
if (typeof value.id !== "string" || !CONTRIBUTION_ID_PATTERN.test(value.id)) {
|
|
64
|
+
throw new PluginManifestError(`${path}.id: expected a lowercase identifier (max 32 chars)`);
|
|
65
|
+
}
|
|
66
|
+
if (value.name !== void 0 && (typeof value.name !== "string" || value.name === "")) {
|
|
67
|
+
throw new PluginManifestError(`${path}.name: expected a non-empty string`);
|
|
68
|
+
}
|
|
69
|
+
if (typeof value.module !== "string" || !value.module.startsWith("./") || value.module === "./" || value.module.includes("..") || value.module.includes("\\") || value.module.includes("\0") || value.module.includes("/../")) {
|
|
70
|
+
throw new PluginManifestError(`${path}.module: expected a relative path inside the package`);
|
|
71
|
+
}
|
|
72
|
+
const optionsSchema = value.optionsSchema === void 0 ? void 0 : parseOptionsSchema(value.optionsSchema, `${path}.optionsSchema`);
|
|
73
|
+
if (kind === "harness") {
|
|
74
|
+
return {
|
|
75
|
+
kind: "harness",
|
|
76
|
+
id: value.id,
|
|
77
|
+
module: value.module,
|
|
78
|
+
...value.name !== void 0 ? { name: value.name } : {},
|
|
79
|
+
...optionsSchema !== void 0 ? { optionsSchema } : {}
|
|
80
|
+
};
|
|
81
|
+
}
|
|
82
|
+
if (kind === "slug") {
|
|
83
|
+
return {
|
|
84
|
+
kind: "slug",
|
|
85
|
+
id: value.id,
|
|
86
|
+
module: value.module,
|
|
87
|
+
...value.name !== void 0 ? { name: value.name } : {},
|
|
88
|
+
...optionsSchema !== void 0 ? { optionsSchema } : {},
|
|
89
|
+
...value.secrets !== void 0 ? { secrets: parseSecrets(value.secrets, `${path}.secrets`) } : {}
|
|
90
|
+
};
|
|
91
|
+
}
|
|
92
|
+
return {
|
|
93
|
+
kind: "reporter",
|
|
94
|
+
id: value.id,
|
|
95
|
+
module: value.module,
|
|
96
|
+
...value.name !== void 0 ? { name: value.name } : {},
|
|
97
|
+
...optionsSchema !== void 0 ? { optionsSchema } : {},
|
|
98
|
+
...value.secrets !== void 0 ? { secrets: parseSecrets(value.secrets, `${path}.secrets`) } : {}
|
|
99
|
+
};
|
|
100
|
+
}
|
|
101
|
+
function parsePluginManifest(pkgJson) {
|
|
102
|
+
if (!isPlainObject(pkgJson)) throw new PluginManifestError("root: expected an object");
|
|
103
|
+
const compivia = pkgJson.compivia;
|
|
104
|
+
if (!isPlainObject(compivia) || compivia.plugin === void 0) {
|
|
105
|
+
throw new PluginManifestError("missing compivia.plugin manifest");
|
|
106
|
+
}
|
|
107
|
+
const plugin = compivia.plugin;
|
|
108
|
+
if (!isPlainObject(plugin)) throw new PluginManifestError("compivia.plugin: expected an object");
|
|
109
|
+
unknownFields(plugin, ["apiVersion", "contributions"], "compivia.plugin");
|
|
110
|
+
const apiVersion = plugin.apiVersion;
|
|
111
|
+
if (typeof apiVersion !== "number" || !Number.isInteger(apiVersion) || !SUPPORTED_PLUGIN_API_VERSIONS.includes(apiVersion)) {
|
|
112
|
+
throw new PluginManifestError(`compivia.plugin.apiVersion: supported: [${SUPPORTED_PLUGIN_API_VERSIONS.join(", ")}]`);
|
|
113
|
+
}
|
|
114
|
+
if (!Array.isArray(plugin.contributions) || plugin.contributions.length === 0) {
|
|
115
|
+
throw new PluginManifestError("compivia.plugin.contributions: expected a non-empty array");
|
|
116
|
+
}
|
|
117
|
+
const contributions = plugin.contributions.map(parseContribution);
|
|
118
|
+
const seen = /* @__PURE__ */ new Set();
|
|
119
|
+
for (const contribution of contributions) {
|
|
120
|
+
if (seen.has(contribution.id)) {
|
|
121
|
+
throw new PluginManifestError(`contributions: duplicate id ${JSON.stringify(contribution.id)}`);
|
|
122
|
+
}
|
|
123
|
+
seen.add(contribution.id);
|
|
124
|
+
}
|
|
125
|
+
return { apiVersion, contributions };
|
|
126
|
+
}
|
|
127
|
+
function contributionKey(contribution) {
|
|
128
|
+
return `${contribution.kind}:${contribution.id}`;
|
|
129
|
+
}
|
|
130
|
+
function parseContributionKey(key) {
|
|
131
|
+
const sep = key.indexOf(":");
|
|
132
|
+
if (sep <= 0 || sep !== key.lastIndexOf(":")) return null;
|
|
133
|
+
const kind = key.slice(0, sep);
|
|
134
|
+
const id = key.slice(sep + 1);
|
|
135
|
+
if (typeof kind !== "string" || !CONTRIBUTION_KINDS.includes(kind)) return null;
|
|
136
|
+
if (!CONTRIBUTION_ID_PATTERN.test(id)) return null;
|
|
137
|
+
return { kind, id };
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
// src/settings.ts
|
|
141
|
+
var ENV_NAME2 = /^[A-Za-z_][A-Za-z0-9_]*$/;
|
|
142
|
+
function isPlainObject2(value) {
|
|
143
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
144
|
+
}
|
|
145
|
+
function validatePluginsSection(value) {
|
|
146
|
+
if (!Array.isArray(value)) return ["expected an array of plugin entries"];
|
|
147
|
+
const issues = [];
|
|
148
|
+
const seen = /* @__PURE__ */ new Set();
|
|
149
|
+
for (const [index, item] of value.entries()) {
|
|
150
|
+
const path = `[${index}]`;
|
|
151
|
+
if (!isPlainObject2(item)) {
|
|
152
|
+
issues.push(`${path}: expected an object`);
|
|
153
|
+
continue;
|
|
154
|
+
}
|
|
155
|
+
for (const key of Object.keys(item)) {
|
|
156
|
+
if (!["package", "enable", "disable", "options", "env"].includes(key)) {
|
|
157
|
+
issues.push(`${path}.${key}: unknown field`);
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
if (typeof item.package !== "string" || item.package === "") {
|
|
161
|
+
issues.push(`${path}.package: expected a non-empty string`);
|
|
162
|
+
continue;
|
|
163
|
+
}
|
|
164
|
+
if (seen.has(item.package)) {
|
|
165
|
+
issues.push(`${path}.package: duplicate package ${JSON.stringify(item.package)}`);
|
|
166
|
+
}
|
|
167
|
+
seen.add(item.package);
|
|
168
|
+
for (const listField of ["enable", "disable"]) {
|
|
169
|
+
const list = item[listField];
|
|
170
|
+
if (list === void 0) continue;
|
|
171
|
+
if (!Array.isArray(list)) {
|
|
172
|
+
issues.push(`${path}.${listField}: expected an array of contribution keys`);
|
|
173
|
+
continue;
|
|
174
|
+
}
|
|
175
|
+
const keys = /* @__PURE__ */ new Set();
|
|
176
|
+
for (const [keyIndex, key] of list.entries()) {
|
|
177
|
+
if (typeof key !== "string" || !CONTRIBUTION_KEY_PATTERN.test(key) || !CONTRIBUTION_KINDS.includes(key.split(":")[0] ?? "")) {
|
|
178
|
+
issues.push(`${path}.${listField}[${keyIndex}]: expected a contribution key "kind:id"`);
|
|
179
|
+
} else if (keys.has(key)) {
|
|
180
|
+
issues.push(`${path}.${listField}[${keyIndex}]: duplicate key ${JSON.stringify(key)}`);
|
|
181
|
+
} else {
|
|
182
|
+
keys.add(key);
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
if (item.options !== void 0) {
|
|
187
|
+
if (!isPlainObject2(item.options)) {
|
|
188
|
+
issues.push(`${path}.options: expected an object`);
|
|
189
|
+
} else {
|
|
190
|
+
for (const [key, value2] of Object.entries(item.options)) {
|
|
191
|
+
if (!isPlainObject2(value2)) {
|
|
192
|
+
issues.push(`${path}.options.${JSON.stringify(key)}: expected an object`);
|
|
193
|
+
} else if (!CONTRIBUTION_KEY_PATTERN.test(key)) {
|
|
194
|
+
issues.push(`${path}.options.${JSON.stringify(key)}: expected a contribution key "kind:id"`);
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
if (item.env !== void 0) {
|
|
200
|
+
if (!Array.isArray(item.env)) {
|
|
201
|
+
issues.push(`${path}.env: expected an array of env names`);
|
|
202
|
+
} else {
|
|
203
|
+
for (const [envIndex, name] of item.env.entries()) {
|
|
204
|
+
if (typeof name !== "string" || !ENV_NAME2.test(name)) {
|
|
205
|
+
issues.push(`${path}.env[${envIndex}]: expected a valid env name`);
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
return issues;
|
|
212
|
+
}
|
|
213
|
+
function mergePluginSettings(machine, user) {
|
|
214
|
+
const result = /* @__PURE__ */ new Map();
|
|
215
|
+
const levels = [
|
|
216
|
+
{ entries: machine, level: "machine" },
|
|
217
|
+
{ entries: user, level: "user" }
|
|
218
|
+
];
|
|
219
|
+
const packages = /* @__PURE__ */ new Set([
|
|
220
|
+
...(machine ?? []).map((e) => e.package),
|
|
221
|
+
...(user ?? []).map((e) => e.package)
|
|
222
|
+
]);
|
|
223
|
+
for (const pkg of packages) {
|
|
224
|
+
const entryOf = (level) => {
|
|
225
|
+
const entries = level === "machine" ? machine : user;
|
|
226
|
+
const entry = entries?.find((e) => e.package === pkg);
|
|
227
|
+
return entry === void 0 ? void 0 : { entry, level };
|
|
228
|
+
};
|
|
229
|
+
const machineEntry = entryOf("machine");
|
|
230
|
+
const userEntry = entryOf("user");
|
|
231
|
+
const contributions = /* @__PURE__ */ new Map();
|
|
232
|
+
const options = /* @__PURE__ */ new Map();
|
|
233
|
+
const seenKeys = /* @__PURE__ */ new Set([
|
|
234
|
+
...machineEntry?.entry.enable ?? [],
|
|
235
|
+
...machineEntry?.entry.disable ?? [],
|
|
236
|
+
...Object.keys(machineEntry?.entry.options ?? {}),
|
|
237
|
+
...userEntry?.entry.enable ?? [],
|
|
238
|
+
...userEntry?.entry.disable ?? [],
|
|
239
|
+
...Object.keys(userEntry?.entry.options ?? {})
|
|
240
|
+
]);
|
|
241
|
+
for (const key of seenKeys) {
|
|
242
|
+
const rule = (e) => {
|
|
243
|
+
if (e === void 0) return void 0;
|
|
244
|
+
if (e.entry.enable?.includes(key) ?? false) return { enabled: true, level: e.level };
|
|
245
|
+
if (e.entry.disable?.includes(key) ?? false) return { enabled: false, level: null };
|
|
246
|
+
return void 0;
|
|
247
|
+
};
|
|
248
|
+
const m = rule(machineEntry);
|
|
249
|
+
const u = rule(userEntry);
|
|
250
|
+
const finalRule = u ?? m;
|
|
251
|
+
contributions.set(key, finalRule ?? { enabled: false, level: null });
|
|
252
|
+
}
|
|
253
|
+
const mergedOptionsFor = (key) => {
|
|
254
|
+
const m = machineEntry?.entry.options?.[key];
|
|
255
|
+
const u = userEntry?.entry.options?.[key];
|
|
256
|
+
if (m === void 0 && u === void 0) return void 0;
|
|
257
|
+
return { ...m, ...u };
|
|
258
|
+
};
|
|
259
|
+
for (const key of /* @__PURE__ */ new Set([
|
|
260
|
+
...Object.keys(machineEntry?.entry.options ?? {}),
|
|
261
|
+
...Object.keys(userEntry?.entry.options ?? {})
|
|
262
|
+
])) {
|
|
263
|
+
const merged = mergedOptionsFor(key);
|
|
264
|
+
if (merged !== void 0) options.set(key, merged);
|
|
265
|
+
}
|
|
266
|
+
const envNames = [];
|
|
267
|
+
for (const name of [...machineEntry?.entry.env ?? [], ...userEntry?.entry.env ?? []]) {
|
|
268
|
+
if (!envNames.includes(name)) envNames.push(name);
|
|
269
|
+
}
|
|
270
|
+
result.set(pkg, {
|
|
271
|
+
package: pkg,
|
|
272
|
+
contributions,
|
|
273
|
+
options,
|
|
274
|
+
env: envNames
|
|
275
|
+
});
|
|
276
|
+
}
|
|
277
|
+
return result;
|
|
278
|
+
}
|
|
279
|
+
export {
|
|
280
|
+
CONTRIBUTION_ID_PATTERN,
|
|
281
|
+
CONTRIBUTION_KEY_PATTERN,
|
|
282
|
+
CONTRIBUTION_KINDS,
|
|
283
|
+
PLUGIN_API_VERSION,
|
|
284
|
+
PluginManifestError,
|
|
285
|
+
SUPPORTED_PLUGIN_API_VERSIONS,
|
|
286
|
+
contributionKey,
|
|
287
|
+
defineHarness,
|
|
288
|
+
defineReporter,
|
|
289
|
+
defineSlugGenerator,
|
|
290
|
+
mergePluginSettings,
|
|
291
|
+
parseContributionKey,
|
|
292
|
+
parsePluginManifest,
|
|
293
|
+
validatePluginsSection
|
|
294
|
+
};
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import { type PluginContributionKind } from "./const.js";
|
|
2
|
+
export declare class PluginManifestError extends Error {
|
|
3
|
+
constructor(message: string);
|
|
4
|
+
}
|
|
5
|
+
export type JsonSchemaObject = {
|
|
6
|
+
type: "object";
|
|
7
|
+
properties?: Record<string, unknown>;
|
|
8
|
+
additionalProperties?: boolean;
|
|
9
|
+
required?: string[];
|
|
10
|
+
};
|
|
11
|
+
export type HarnessContribution = {
|
|
12
|
+
kind: "harness";
|
|
13
|
+
id: string;
|
|
14
|
+
name?: string;
|
|
15
|
+
module: string;
|
|
16
|
+
optionsSchema?: JsonSchemaObject;
|
|
17
|
+
};
|
|
18
|
+
export type ReporterContribution = {
|
|
19
|
+
kind: "reporter";
|
|
20
|
+
id: string;
|
|
21
|
+
name?: string;
|
|
22
|
+
module: string;
|
|
23
|
+
optionsSchema?: JsonSchemaObject;
|
|
24
|
+
secrets?: string[];
|
|
25
|
+
};
|
|
26
|
+
export type SlugContribution = {
|
|
27
|
+
kind: "slug";
|
|
28
|
+
id: string;
|
|
29
|
+
name?: string;
|
|
30
|
+
module: string;
|
|
31
|
+
optionsSchema?: JsonSchemaObject;
|
|
32
|
+
secrets?: string[];
|
|
33
|
+
};
|
|
34
|
+
export type PluginContribution = HarnessContribution | ReporterContribution | SlugContribution;
|
|
35
|
+
export type PluginManifest = {
|
|
36
|
+
apiVersion: number;
|
|
37
|
+
contributions: PluginContribution[];
|
|
38
|
+
};
|
|
39
|
+
/** Разбор поля `compivia.plugin` из package.json: строгий, лишние поля — отказ. */
|
|
40
|
+
export declare function parsePluginManifest(pkgJson: unknown): PluginManifest;
|
|
41
|
+
/** Канонический ключ вклада: `kind:id`. */
|
|
42
|
+
export declare function contributionKey(contribution: {
|
|
43
|
+
kind: PluginContributionKind;
|
|
44
|
+
id: string;
|
|
45
|
+
}): string;
|
|
46
|
+
export declare function parseContributionKey(key: string): {
|
|
47
|
+
kind: PluginContributionKind;
|
|
48
|
+
id: string;
|
|
49
|
+
} | null;
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import type { PluginLogger } from "./harness.js";
|
|
2
|
+
export type ReporterContext = {
|
|
3
|
+
subscription: string;
|
|
4
|
+
options: Record<string, unknown>;
|
|
5
|
+
env: Record<string, string>;
|
|
6
|
+
logger: PluginLogger;
|
|
7
|
+
};
|
|
8
|
+
export type UsageWindow = {
|
|
9
|
+
id: string;
|
|
10
|
+
usedPercent: number;
|
|
11
|
+
resetsAt?: string;
|
|
12
|
+
durationSec?: number;
|
|
13
|
+
label?: string;
|
|
14
|
+
};
|
|
15
|
+
export type UsageReport = {
|
|
16
|
+
windows: UsageWindow[];
|
|
17
|
+
observedAt?: string;
|
|
18
|
+
accountId?: string;
|
|
19
|
+
};
|
|
20
|
+
/** Контракт вклада `reporter` (спека usage-reporters, §4): только опрос;
|
|
21
|
+
* `probe → null` — «данных нет»; `dispose` идемпотентен. */
|
|
22
|
+
export type ReporterDefinition = {
|
|
23
|
+
apiVersion: number;
|
|
24
|
+
id: string;
|
|
25
|
+
optionsSchema?: {
|
|
26
|
+
type: "object";
|
|
27
|
+
properties?: Record<string, unknown>;
|
|
28
|
+
additionalProperties?: boolean;
|
|
29
|
+
required?: string[];
|
|
30
|
+
};
|
|
31
|
+
secrets?: string[];
|
|
32
|
+
init?(ctx: ReporterContext): Promise<void>;
|
|
33
|
+
probe(ctx: ReporterContext, signal: AbortSignal): Promise<UsageReport | null>;
|
|
34
|
+
dispose?(): Promise<void>;
|
|
35
|
+
};
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
export type PluginSettingsEntry = {
|
|
2
|
+
package: string;
|
|
3
|
+
/** Ключи вкладов "kind:id". */
|
|
4
|
+
enable?: string[];
|
|
5
|
+
disable?: string[];
|
|
6
|
+
/** Ключ вклада → опции. */
|
|
7
|
+
options?: Record<string, Record<string, unknown>>;
|
|
8
|
+
/** Имена env-переменных. */
|
|
9
|
+
env?: string[];
|
|
10
|
+
};
|
|
11
|
+
/** Валидация формы секции `plugins`; сообщения без префикса "plugins" —
|
|
12
|
+
* вызывающий добавляет путь уровня (machine-config → "plugins[0]…"). */
|
|
13
|
+
export declare function validatePluginsSection(value: unknown): string[];
|
|
14
|
+
export type EffectiveContribution = {
|
|
15
|
+
enabled: boolean;
|
|
16
|
+
level: "machine" | "user" | null;
|
|
17
|
+
};
|
|
18
|
+
export type EffectivePlugin = {
|
|
19
|
+
package: string;
|
|
20
|
+
contributions: Map<string, EffectiveContribution>;
|
|
21
|
+
options: Map<string, Record<string, unknown>>;
|
|
22
|
+
env: string[];
|
|
23
|
+
};
|
|
24
|
+
/** Мерж per package/per вклад: user — последнее слово; default — выключен;
|
|
25
|
+
* options — shallow-мерж machine → user; env — union (machine, затем user). */
|
|
26
|
+
export declare function mergePluginSettings(machine: readonly PluginSettingsEntry[] | undefined, user: readonly PluginSettingsEntry[] | undefined): Map<string, EffectivePlugin>;
|
package/dist/slug.d.ts
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import type { PluginLogger } from "./harness.js";
|
|
2
|
+
import type { JsonSchemaObject } from "./parse-manifest.js";
|
|
3
|
+
/** Класс ветки, для которой генерируется slug. */
|
|
4
|
+
export type SlugKind = "task" | "feature";
|
|
5
|
+
/** Вход генератора: заголовок и (обрезанное движком) тело issue; maxWords —
|
|
6
|
+
* подсказка плагину, жёсткий предел всё равно применяет движок
|
|
7
|
+
* (normalizeSlug). */
|
|
8
|
+
export type SlugInput = {
|
|
9
|
+
kind: SlugKind;
|
|
10
|
+
title: string;
|
|
11
|
+
body: string;
|
|
12
|
+
maxWords: number;
|
|
13
|
+
};
|
|
14
|
+
/** Контекст вызова генератора: опции вклада (смёрженные machine → user),
|
|
15
|
+
* env по белому списку хоста и логгер хоста (значения секретов маскируются). */
|
|
16
|
+
export type SlugContext = {
|
|
17
|
+
options: Record<string, unknown>;
|
|
18
|
+
env: Record<string, string>;
|
|
19
|
+
logger: PluginLogger;
|
|
20
|
+
};
|
|
21
|
+
/** Контракт вклада `slug` (спека #541 §3.1): `generate → null` — «отказываюсь»
|
|
22
|
+
* (движок делает fallback на генератор по умолчанию); бросок/таймаут — сбой.
|
|
23
|
+
* `dispose` идемпотентен. */
|
|
24
|
+
export type SlugGeneratorDefinition = {
|
|
25
|
+
apiVersion: number;
|
|
26
|
+
id: string;
|
|
27
|
+
optionsSchema?: JsonSchemaObject;
|
|
28
|
+
secrets?: string[];
|
|
29
|
+
init?(ctx: SlugContext): Promise<void>;
|
|
30
|
+
generate(ctx: SlugContext, input: SlugInput, signal: AbortSignal): Promise<{
|
|
31
|
+
slug: string;
|
|
32
|
+
} | null>;
|
|
33
|
+
dispose?(): Promise<void>;
|
|
34
|
+
};
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
/** Handle фикстуры harness-вклада: definition — структурная форма
|
|
2
|
+
* HarnessDefinition (проверяется сюитой и collectPluginHarnessIssues). */
|
|
3
|
+
export interface PluginHarnessHandle {
|
|
4
|
+
definition: unknown;
|
|
5
|
+
close(): Promise<void>;
|
|
6
|
+
/** Структурный логгер, который фикстура передаёт в ctx; оттуда же сюита
|
|
7
|
+
* читает логи для проверки секретов. */
|
|
8
|
+
logs(): string[];
|
|
9
|
+
}
|
|
10
|
+
export type PluginHarnessFactory = () => Promise<PluginHarnessHandle>;
|
|
11
|
+
/** Handle фикстуры reporter-вклада. */
|
|
12
|
+
export interface PluginReporterHandle {
|
|
13
|
+
definition: unknown;
|
|
14
|
+
logs(): string[];
|
|
15
|
+
close(): Promise<void>;
|
|
16
|
+
}
|
|
17
|
+
export type PluginReporterFactory = () => Promise<PluginReporterHandle>;
|
|
18
|
+
/** Вход генератора slug в контракте: форма зеркалит SlugInput из plugin-sdk
|
|
19
|
+
* (сюиты не зависят от SDK, решение 5 плана #410). */
|
|
20
|
+
export type SlugFixture = {
|
|
21
|
+
name: string;
|
|
22
|
+
input: {
|
|
23
|
+
kind: "task" | "feature";
|
|
24
|
+
title: string;
|
|
25
|
+
body: string;
|
|
26
|
+
maxWords: number;
|
|
27
|
+
};
|
|
28
|
+
};
|
|
29
|
+
/** Handle фикстуры slug-вклада: options/env/фикстуры сюита передаёт в
|
|
30
|
+
* ctx.generate и в тесты фикстур. */
|
|
31
|
+
export interface PluginSlugHandle {
|
|
32
|
+
definition: unknown;
|
|
33
|
+
options?: Record<string, unknown>;
|
|
34
|
+
env?: Record<string, string>;
|
|
35
|
+
fixtures?: SlugFixture[];
|
|
36
|
+
logs(): string[];
|
|
37
|
+
close(): Promise<void>;
|
|
38
|
+
}
|
|
39
|
+
export type PluginSlugFactory = () => Promise<PluginSlugHandle>;
|
|
40
|
+
type Issues = string[];
|
|
41
|
+
/** Чистая проверка формы harness-вклада (пустой список — валидно); сюита
|
|
42
|
+
* и негативные тесты авторов (спека §4.11) используют один набор правил. */
|
|
43
|
+
export declare function collectPluginHarnessIssues(definition: unknown): Issues;
|
|
44
|
+
/** Чистая проверка формы reporter-вклада. */
|
|
45
|
+
export declare function collectPluginReporterIssues(definition: unknown): Issues;
|
|
46
|
+
/** Чистая проверка формы slug-вклада (#541). */
|
|
47
|
+
export declare function collectPluginSlugIssues(definition: unknown): Issues;
|
|
48
|
+
export {};
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { type PluginHarnessFactory } from "./testing-factory.js";
|
|
2
|
+
/** Контракт harness-вклада плагина (спека #410 §4.3): форма модуля, детект,
|
|
3
|
+
* запуск, классификация, финал — тот же смысловой набор, что у встроенных
|
|
4
|
+
* адаптеров; проверка изоляции ctx живёт в host-manager тестах runner-core.
|
|
5
|
+
* Каждый кейс — отдельная функция, чтобы изменение одного правила не
|
|
6
|
+
* требовало прочитывать всю сюиту. */
|
|
7
|
+
export declare function describePluginHarnessContract(name: string, create: PluginHarnessFactory): void;
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import { type PluginReporterFactory } from "./testing-factory.js";
|
|
2
|
+
/** Контракт reporter-вклада (спека usage-reporters §4–§5, применено к
|
|
3
|
+
* plugin-вкладам #410): только опрос, окно один к одному, секреты не в
|
|
4
|
+
* логах, dispose идемпотентен, таймеры не текут. */
|
|
5
|
+
export declare function describePluginReporterContract(name: string, create: PluginReporterFactory): void;
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import { type PluginSlugFactory } from "./testing-factory.js";
|
|
2
|
+
/** Контракт slug-вклада (спека #541 §3.1): форма определения, generate на
|
|
3
|
+
* фикстурах возвращает {slug} или null, abort без зависания, секреты не в
|
|
4
|
+
* логах, dispose идемпотентен, таймеры не текут. */
|
|
5
|
+
export declare function describePluginSlugContract(name: string, create: PluginSlugFactory): void;
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { collectPluginHarnessIssues, collectPluginReporterIssues, collectPluginSlugIssues, type SlugFixture } from "./testing-factory.js";
|
|
2
|
+
import { describePluginHarnessContract } from "./testing-harness.contract.js";
|
|
3
|
+
import { describePluginReporterContract } from "./testing-reporter.contract.js";
|
|
4
|
+
import { describePluginSlugContract } from "./testing-slug.contract.js";
|
|
5
|
+
/** Conformance-прогон harness-вклада (паттерн runReporterConformance спеки
|
|
6
|
+
* usage-reporters §4): modulePath — файл ESM-модуля с default export
|
|
7
|
+
* HarnessDefinition. Вызывается автором плагина из своего vitest-теста. */
|
|
8
|
+
export declare function runPluginHarnessConformance(modulePath: string): void;
|
|
9
|
+
/** Conformance-прогон reporter-вклада: modulePath — файл ESM-модуля с
|
|
10
|
+
* default export ReporterDefinition. */
|
|
11
|
+
export declare function runPluginReporterConformance(modulePath: string): void;
|
|
12
|
+
type SlugConformanceOptions = {
|
|
13
|
+
/** Опции вклада, которые сьюта передаёт в ctx.generate. */
|
|
14
|
+
options?: Record<string, unknown>;
|
|
15
|
+
/** Env-имена и значения для ctx.generate (значения секретов — здесь). */
|
|
16
|
+
env?: Record<string, string>;
|
|
17
|
+
/** Дополнительные фикстуры поверх встроенных сюиты. */
|
|
18
|
+
fixtures?: SlugFixture[];
|
|
19
|
+
};
|
|
20
|
+
/** Conformance-прогон slug-вклада (#541): modulePath — файл ESM-модуля с
|
|
21
|
+
* default export SlugGeneratorDefinition; opts уходят в контекст вызовов и
|
|
22
|
+
* в фикстуры сюиты. */
|
|
23
|
+
export declare function runSlugConformance(modulePath: string, opts?: SlugConformanceOptions): void;
|
|
24
|
+
/** Чистые проверки форм, сырые сьюты и фабрики: канонический дом сюит — SDK
|
|
25
|
+
* (#943 §5.2); @compivia/contract-tests реэкспортит их внутренним
|
|
26
|
+
* потребителям monorepo, авторам плагинов сюда ходить не обязательно. */
|
|
27
|
+
export { collectPluginHarnessIssues, collectPluginReporterIssues, collectPluginSlugIssues, describePluginHarnessContract, describePluginReporterContract, describePluginSlugContract, };
|
|
28
|
+
export type { PluginHarnessFactory, PluginReporterFactory, PluginSlugFactory, PluginHarnessHandle, PluginReporterHandle, PluginSlugHandle, SlugFixture, } from "./testing-factory.js";
|
package/dist/testing.js
ADDED
|
@@ -0,0 +1,487 @@
|
|
|
1
|
+
// src/testing.ts
|
|
2
|
+
import { pathToFileURL } from "node:url";
|
|
3
|
+
import { expect as expect4, it as it4 } from "vitest";
|
|
4
|
+
|
|
5
|
+
// src/testing-factory.ts
|
|
6
|
+
var HARNESS_REQUIRED_METHODS = [
|
|
7
|
+
"detect",
|
|
8
|
+
"launch",
|
|
9
|
+
"classifyLine",
|
|
10
|
+
"locateSession",
|
|
11
|
+
"finalOf",
|
|
12
|
+
"normalizeLine",
|
|
13
|
+
"classify",
|
|
14
|
+
"finalFromOutput"
|
|
15
|
+
];
|
|
16
|
+
function collectPluginHarnessIssues(definition) {
|
|
17
|
+
const issues = [];
|
|
18
|
+
if (definition === null || typeof definition !== "object" || Array.isArray(definition)) {
|
|
19
|
+
return ["definition: not an object"];
|
|
20
|
+
}
|
|
21
|
+
const def = definition;
|
|
22
|
+
if (typeof def.id !== "string" || def.id === "") issues.push("id: expected a non-empty string");
|
|
23
|
+
for (const method of HARNESS_REQUIRED_METHODS) {
|
|
24
|
+
if (typeof def[method] !== "function") issues.push(`${method}: expected a function`);
|
|
25
|
+
}
|
|
26
|
+
if (def.checksOf !== void 0 && typeof def.checksOf !== "function") {
|
|
27
|
+
issues.push("checksOf: expected a function");
|
|
28
|
+
}
|
|
29
|
+
return issues;
|
|
30
|
+
}
|
|
31
|
+
function collectPluginReporterIssues(definition) {
|
|
32
|
+
const issues = [];
|
|
33
|
+
if (definition === null || typeof definition !== "object" || Array.isArray(definition)) {
|
|
34
|
+
return ["definition: not an object"];
|
|
35
|
+
}
|
|
36
|
+
const def = definition;
|
|
37
|
+
if (def.apiVersion !== 1) issues.push("apiVersion: expected 1");
|
|
38
|
+
if (typeof def.id !== "string" || def.id === "") issues.push("id: expected a non-empty string");
|
|
39
|
+
if (typeof def.probe !== "function") issues.push("probe: expected a function");
|
|
40
|
+
if (def.init !== void 0 && typeof def.init !== "function") issues.push("init: expected a function");
|
|
41
|
+
if (def.dispose !== void 0 && typeof def.dispose !== "function") issues.push("dispose: expected a function");
|
|
42
|
+
if (def.optionsSchema !== void 0) {
|
|
43
|
+
const schema = def.optionsSchema;
|
|
44
|
+
if (schema === null || typeof schema !== "object" || Array.isArray(schema) || schema.type !== "object") {
|
|
45
|
+
issues.push('optionsSchema: expected an object with type="object"');
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
if (def.secrets !== void 0 && (!Array.isArray(def.secrets) || def.secrets.some((s) => typeof s !== "string"))) {
|
|
49
|
+
issues.push("secrets: expected an array of env names");
|
|
50
|
+
}
|
|
51
|
+
return issues;
|
|
52
|
+
}
|
|
53
|
+
function collectPluginSlugIssues(definition) {
|
|
54
|
+
const issues = [];
|
|
55
|
+
if (definition === null || typeof definition !== "object" || Array.isArray(definition)) {
|
|
56
|
+
return ["definition: not an object"];
|
|
57
|
+
}
|
|
58
|
+
const def = definition;
|
|
59
|
+
if (def.apiVersion !== 1) issues.push("apiVersion: expected 1");
|
|
60
|
+
if (typeof def.id !== "string" || def.id === "") issues.push("id: expected a non-empty string");
|
|
61
|
+
if (typeof def.generate !== "function") issues.push("generate: expected a function");
|
|
62
|
+
if (def.init !== void 0 && typeof def.init !== "function") issues.push("init: expected a function");
|
|
63
|
+
if (def.dispose !== void 0 && typeof def.dispose !== "function") issues.push("dispose: expected a function");
|
|
64
|
+
if (def.optionsSchema !== void 0) {
|
|
65
|
+
const schema = def.optionsSchema;
|
|
66
|
+
if (schema === null || typeof schema !== "object" || Array.isArray(schema) || schema.type !== "object") {
|
|
67
|
+
issues.push('optionsSchema: expected an object with type="object"');
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
if (def.secrets !== void 0 && (!Array.isArray(def.secrets) || def.secrets.some((s) => typeof s !== "string"))) {
|
|
71
|
+
issues.push("secrets: expected an array of env names");
|
|
72
|
+
}
|
|
73
|
+
return issues;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
// src/testing-harness.contract.ts
|
|
77
|
+
import { describe, expect, it } from "vitest";
|
|
78
|
+
async function withHarness(create, body) {
|
|
79
|
+
const handle = await create();
|
|
80
|
+
try {
|
|
81
|
+
return await body(handle);
|
|
82
|
+
} finally {
|
|
83
|
+
await handle.close();
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
function describePluginHarnessContract(name, create) {
|
|
87
|
+
describe(`plugin harness contract: ${name}`, () => {
|
|
88
|
+
checkDefinition(create);
|
|
89
|
+
checkDetect(create);
|
|
90
|
+
checkLaunch(create);
|
|
91
|
+
checkClassifyLine(create);
|
|
92
|
+
checkLocateSession(create);
|
|
93
|
+
checkFinalOf(create);
|
|
94
|
+
checkChecksOf(create);
|
|
95
|
+
checkNormalizeLine(create);
|
|
96
|
+
checkClassify(create);
|
|
97
|
+
checkFinalFromOutput(create);
|
|
98
|
+
});
|
|
99
|
+
}
|
|
100
|
+
function checkDefinition(create) {
|
|
101
|
+
it("definition conforms to the closed harness shape", async () => {
|
|
102
|
+
await withHarness(create, (handle) => {
|
|
103
|
+
expect(collectPluginHarnessIssues(handle.definition)).toEqual([]);
|
|
104
|
+
});
|
|
105
|
+
});
|
|
106
|
+
}
|
|
107
|
+
function checkDetect(create) {
|
|
108
|
+
it("detect returns a ready/signin_needed/not_installed snapshot", async () => {
|
|
109
|
+
await withHarness(create, async (handle) => {
|
|
110
|
+
const def = handle.definition;
|
|
111
|
+
const result = await def.detect(ctxOf(handle));
|
|
112
|
+
expect(result).toBeInstanceOf(Object);
|
|
113
|
+
const { status, models } = result;
|
|
114
|
+
expect(["ready", "signin_needed", "not_installed"]).toContain(status);
|
|
115
|
+
expect(Array.isArray(models)).toBe(true);
|
|
116
|
+
});
|
|
117
|
+
});
|
|
118
|
+
}
|
|
119
|
+
function checkLaunch(create) {
|
|
120
|
+
it("launch returns a concrete launch for the fixture input", async () => {
|
|
121
|
+
await withHarness(create, async (handle) => {
|
|
122
|
+
const def = handle.definition;
|
|
123
|
+
const result = await Promise.resolve(def.launch(fixtureLaunchInput()));
|
|
124
|
+
expect(typeof result.command === "string" && result.command.length > 0).toBe(true);
|
|
125
|
+
expect(Array.isArray(result.args)).toBe(true);
|
|
126
|
+
expect(result.env).toBeInstanceOf(Object);
|
|
127
|
+
expect(result.transcriptPath === null || typeof result.transcriptPath === "string").toBe(true);
|
|
128
|
+
});
|
|
129
|
+
});
|
|
130
|
+
}
|
|
131
|
+
function checkClassifyLine(create) {
|
|
132
|
+
it("classifyLine returns a line from the closed kind set", async () => {
|
|
133
|
+
await withHarness(create, (handle) => {
|
|
134
|
+
const def = handle.definition;
|
|
135
|
+
const kinds = [
|
|
136
|
+
def.classifyLine('{"type":"task_complete","message":"x"}').kind,
|
|
137
|
+
def.classifyLine("plain").kind,
|
|
138
|
+
def.classifyLine('{"type":"task_started"}').kind
|
|
139
|
+
];
|
|
140
|
+
for (const kind of kinds) {
|
|
141
|
+
expect(["start", "final", "closed", "error", "other"]).toContain(kind);
|
|
142
|
+
}
|
|
143
|
+
});
|
|
144
|
+
});
|
|
145
|
+
}
|
|
146
|
+
function checkLocateSession(create) {
|
|
147
|
+
it("locateSession for a missing session yields null or a path", async () => {
|
|
148
|
+
await withHarness(create, async (handle) => {
|
|
149
|
+
const def = handle.definition;
|
|
150
|
+
const location = await def.locateSession("missing-session");
|
|
151
|
+
expect(location === null || typeof location.path === "string").toBe(true);
|
|
152
|
+
});
|
|
153
|
+
});
|
|
154
|
+
}
|
|
155
|
+
function checkFinalOf(create) {
|
|
156
|
+
it("finalOf yields a terminal outcome for a located or synthetic session", async () => {
|
|
157
|
+
await withHarness(create, async (handle) => {
|
|
158
|
+
const def = handle.definition;
|
|
159
|
+
const location = await def.locateSession("missing-session") ?? { path: "/nonexistent/compivia-contract.jsonl" };
|
|
160
|
+
const outcome = await def.finalOf(location);
|
|
161
|
+
expect(outcome).toBeInstanceOf(Object);
|
|
162
|
+
if (outcome.completed === true) {
|
|
163
|
+
expect(typeof outcome.finalMessage).toBe("string");
|
|
164
|
+
} else {
|
|
165
|
+
expect(outcome.completed).toBe(false);
|
|
166
|
+
expect(typeof outcome.reason).toBe("string");
|
|
167
|
+
}
|
|
168
|
+
});
|
|
169
|
+
});
|
|
170
|
+
}
|
|
171
|
+
function checkChecksOf(create) {
|
|
172
|
+
it("checksOf (if present) returns observations", async () => {
|
|
173
|
+
await withHarness(create, async (handle) => {
|
|
174
|
+
const def = handle.definition;
|
|
175
|
+
if (def.checksOf === void 0) return;
|
|
176
|
+
const checks = await def.checksOf({ path: "/nonexistent/session.jsonl" });
|
|
177
|
+
expect(Array.isArray(checks)).toBe(true);
|
|
178
|
+
for (const check of checks) {
|
|
179
|
+
expect(typeof check.reference).toBe("string");
|
|
180
|
+
expect(typeof check.exitCode).toBe("number");
|
|
181
|
+
}
|
|
182
|
+
});
|
|
183
|
+
});
|
|
184
|
+
}
|
|
185
|
+
function checkNormalizeLine(create) {
|
|
186
|
+
it("normalizeLine returns transcript events with closed kinds", async () => {
|
|
187
|
+
await withHarness(create, (handle) => {
|
|
188
|
+
const def = handle.definition;
|
|
189
|
+
const events = def.normalizeLine("s1", "line one");
|
|
190
|
+
expect(Array.isArray(events)).toBe(true);
|
|
191
|
+
for (const event of events) {
|
|
192
|
+
expect(["message", "tool_call", "tool_result", "check", "status"]).toContain(event.kind);
|
|
193
|
+
}
|
|
194
|
+
});
|
|
195
|
+
});
|
|
196
|
+
}
|
|
197
|
+
function checkClassify(create) {
|
|
198
|
+
it("classify returns a failure class from the closed set", async () => {
|
|
199
|
+
await withHarness(create, (handle) => {
|
|
200
|
+
const def = handle.definition;
|
|
201
|
+
const result = def.classify({ spawnErrorCode: "ENOENT" });
|
|
202
|
+
expect(["invalid", "unavailable", "busy", "rate_limited", "route_unavailable", "failed"]).toContain(result.class);
|
|
203
|
+
});
|
|
204
|
+
});
|
|
205
|
+
}
|
|
206
|
+
function checkFinalFromOutput(create) {
|
|
207
|
+
it("finalFromOutput yields an output outcome", async () => {
|
|
208
|
+
await withHarness(create, (handle) => {
|
|
209
|
+
const def = handle.definition;
|
|
210
|
+
const result = def.finalFromOutput(['{"type":"result","result":"done"}']);
|
|
211
|
+
expect(result.finalMessage === null || typeof result.finalMessage === "string").toBe(true);
|
|
212
|
+
expect(result.failure === null || result.failure instanceof Object).toBe(true);
|
|
213
|
+
});
|
|
214
|
+
});
|
|
215
|
+
}
|
|
216
|
+
function ctxOf(handle) {
|
|
217
|
+
return {
|
|
218
|
+
logger: {
|
|
219
|
+
debug: (message) => handle.logs().push(`debug: ${message}`),
|
|
220
|
+
info: (message) => handle.logs().push(`info: ${message}`),
|
|
221
|
+
warn: (message) => handle.logs().push(`warn: ${message}`),
|
|
222
|
+
error: (message) => handle.logs().push(`error: ${message}`)
|
|
223
|
+
},
|
|
224
|
+
signal: AbortSignal.timeout(5e3)
|
|
225
|
+
};
|
|
226
|
+
}
|
|
227
|
+
function fixtureLaunchInput() {
|
|
228
|
+
return {
|
|
229
|
+
invocationId: "inv-contract",
|
|
230
|
+
promptFile: "/tmp/compivia-contract-prompt.txt",
|
|
231
|
+
outputSchemaFile: null,
|
|
232
|
+
cwd: "/tmp",
|
|
233
|
+
logFile: "/tmp/compivia-contract-wrapper.log",
|
|
234
|
+
mode: "write",
|
|
235
|
+
sessionId: "contract-session"
|
|
236
|
+
};
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
// src/testing-reporter.contract.ts
|
|
240
|
+
import { afterEach, describe as describe2, expect as expect2, it as it2 } from "vitest";
|
|
241
|
+
var RFC3339 = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:\d{2})$/;
|
|
242
|
+
function describePluginReporterContract(name, create) {
|
|
243
|
+
let handle = null;
|
|
244
|
+
afterEach(async () => {
|
|
245
|
+
if (handle !== null) {
|
|
246
|
+
await handle.close();
|
|
247
|
+
handle = null;
|
|
248
|
+
}
|
|
249
|
+
});
|
|
250
|
+
describe2(`plugin reporter contract: ${name}`, () => {
|
|
251
|
+
it2("definition conforms to the closed reporter shape", async () => {
|
|
252
|
+
handle = await create();
|
|
253
|
+
expect2(collectPluginReporterIssues(handle.definition)).toEqual([]);
|
|
254
|
+
});
|
|
255
|
+
it2("probe returns null or a valid usage report", async () => {
|
|
256
|
+
handle = await create();
|
|
257
|
+
const def = handle.definition;
|
|
258
|
+
const report = await def.probe(ctxOf2(handle), AbortSignal.timeout(2e3));
|
|
259
|
+
if (report === null) return;
|
|
260
|
+
expect2(Array.isArray(report.windows)).toBe(true);
|
|
261
|
+
expect2(report.windows.length).toBeGreaterThan(0);
|
|
262
|
+
const ids = /* @__PURE__ */ new Set();
|
|
263
|
+
for (const window of report.windows) {
|
|
264
|
+
expect2(typeof window.id).toBe("string");
|
|
265
|
+
expect2(ids.has(String(window.id))).toBe(false);
|
|
266
|
+
ids.add(String(window.id));
|
|
267
|
+
expect2(typeof window.usedPercent).toBe("number");
|
|
268
|
+
expect2(window.usedPercent).toBeGreaterThanOrEqual(0);
|
|
269
|
+
expect2(window.usedPercent).toBeLessThanOrEqual(100);
|
|
270
|
+
if (window.resetsAt !== void 0) expect2(RFC3339.test(String(window.resetsAt))).toBe(true);
|
|
271
|
+
}
|
|
272
|
+
if (report.observedAt !== void 0) expect2(RFC3339.test(String(report.observedAt))).toBe(true);
|
|
273
|
+
});
|
|
274
|
+
it2("probe honors abort without hanging", async () => {
|
|
275
|
+
handle = await create();
|
|
276
|
+
const def = handle.definition;
|
|
277
|
+
const probe = def.probe(ctxOf2(handle), AbortSignal.timeout(200));
|
|
278
|
+
let hung = false;
|
|
279
|
+
const guard = new Promise((resolve) => {
|
|
280
|
+
setTimeout(() => {
|
|
281
|
+
hung = true;
|
|
282
|
+
resolve("hung");
|
|
283
|
+
}, 1e4).unref?.();
|
|
284
|
+
});
|
|
285
|
+
const outcome = await Promise.race([probe.then(() => "settled", () => "settled"), guard]);
|
|
286
|
+
expect2(hung).toBe(false);
|
|
287
|
+
expect2(outcome).not.toBe("hung");
|
|
288
|
+
});
|
|
289
|
+
it2("secret values never appear in logs()", async () => {
|
|
290
|
+
handle = await create();
|
|
291
|
+
const def = handle.definition;
|
|
292
|
+
await def.probe(ctxOf2(handle), AbortSignal.timeout(2e3));
|
|
293
|
+
const logs = handle.logs();
|
|
294
|
+
for (const line of logs) {
|
|
295
|
+
expect2(line.includes("compivia-contract-secret-value")).toBe(false);
|
|
296
|
+
}
|
|
297
|
+
});
|
|
298
|
+
it2("dispose is idempotent", async () => {
|
|
299
|
+
handle = await create();
|
|
300
|
+
const def = handle.definition;
|
|
301
|
+
if (def.dispose !== void 0) {
|
|
302
|
+
await def.dispose();
|
|
303
|
+
await def.dispose();
|
|
304
|
+
}
|
|
305
|
+
});
|
|
306
|
+
it2("close leaves no timers behind", async () => {
|
|
307
|
+
handle = await create();
|
|
308
|
+
const def = handle.definition;
|
|
309
|
+
if (def.init !== void 0) await def.init(ctxOf2(handle));
|
|
310
|
+
await def.probe(ctxOf2(handle), AbortSignal.timeout(2e3)).catch(() => void 0);
|
|
311
|
+
const before = process.getActiveResourcesInfo().filter((r) => r === "Timeout").length;
|
|
312
|
+
await handle.close();
|
|
313
|
+
await new Promise((resolve) => setImmediate(() => resolve()));
|
|
314
|
+
const after = process.getActiveResourcesInfo().filter((r) => r === "Timeout").length;
|
|
315
|
+
expect2(after).toBeLessThanOrEqual(before);
|
|
316
|
+
handle = null;
|
|
317
|
+
});
|
|
318
|
+
});
|
|
319
|
+
}
|
|
320
|
+
function ctxOf2(handle) {
|
|
321
|
+
return {
|
|
322
|
+
subscription: "plugin:reporter:contract",
|
|
323
|
+
options: {},
|
|
324
|
+
env: { COMPIVIA_CONTRACT_SECRET: "compivia-contract-secret-value", ...process.env.FIXTURE_TOKEN !== void 0 ? { FIXTURE_TOKEN: process.env.FIXTURE_TOKEN } : {} },
|
|
325
|
+
logger: {
|
|
326
|
+
debug: (message) => handle.logs().push(`debug: ${message}`),
|
|
327
|
+
info: (message) => handle.logs().push(`info: ${message}`),
|
|
328
|
+
warn: (message) => handle.logs().push(`warn: ${message}`),
|
|
329
|
+
error: (message) => handle.logs().push(`error: ${message}`)
|
|
330
|
+
}
|
|
331
|
+
};
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
// src/testing-slug.contract.ts
|
|
335
|
+
import { afterEach as afterEach2, describe as describe3, expect as expect3, it as it3 } from "vitest";
|
|
336
|
+
var BUILTIN_FIXTURES = [
|
|
337
|
+
{ name: "russian title", input: { kind: "task", title: "\u0414\u043E\u0431\u0430\u0432\u0438\u0442\u044C \u043F\u043B\u0430\u0433\u0438\u043D slug", body: "", maxWords: 6 } },
|
|
338
|
+
{ name: "ukrainian title", input: { kind: "feature", title: "\u0414\u043E\u0434\u0430\u0442\u0438 \u043F\u0456\u0434\u0442\u0440\u0438\u043C\u043A\u0443 slug", body: "", maxWords: 6 } },
|
|
339
|
+
{ name: "chinese title", input: { kind: "task", title: "\u6DFB\u52A0 slug \u652F\u6301", body: "", maxWords: 6 } },
|
|
340
|
+
{ name: "arabic title", input: { kind: "feature", title: "\u0625\u0636\u0627\u0641\u0629 \u062F\u0639\u0645 slug", body: "", maxWords: 6 } },
|
|
341
|
+
{ name: "mixed title with very long body", input: { kind: "task", title: "Fix bug #42 \u2014 quickly", body: "word ".repeat(2e3), maxWords: 6 } },
|
|
342
|
+
{ name: "empty body", input: { kind: "task", title: "Empty body case", body: "", maxWords: 6 } },
|
|
343
|
+
{ name: "digits-only title", input: { kind: "feature", title: "12345", body: "some body", maxWords: 6 } }
|
|
344
|
+
];
|
|
345
|
+
function defOf(handle) {
|
|
346
|
+
return handle.definition;
|
|
347
|
+
}
|
|
348
|
+
async function expectSlugOrNullForEveryFixture(handle, ctx) {
|
|
349
|
+
const def = defOf(handle);
|
|
350
|
+
for (const fixture of [...BUILTIN_FIXTURES, ...handle.fixtures ?? []]) {
|
|
351
|
+
const outcome = await def.generate(ctx, fixture.input, AbortSignal.timeout(1e4));
|
|
352
|
+
expect3(outcome === null || typeof outcome === "object").toBe(true);
|
|
353
|
+
if (outcome !== null) {
|
|
354
|
+
const shaped = outcome;
|
|
355
|
+
expect3(typeof shaped.slug).toBe("string");
|
|
356
|
+
expect3(shaped.slug.length).toBeGreaterThan(0);
|
|
357
|
+
}
|
|
358
|
+
}
|
|
359
|
+
}
|
|
360
|
+
async function expectAbortResponsive(def, ctx) {
|
|
361
|
+
const generate = def.generate(ctx, BUILTIN_FIXTURES[0].input, AbortSignal.timeout(200));
|
|
362
|
+
let hung = false;
|
|
363
|
+
const guard = new Promise((resolve) => {
|
|
364
|
+
setTimeout(() => {
|
|
365
|
+
hung = true;
|
|
366
|
+
resolve("hung");
|
|
367
|
+
}, 1e4).unref?.();
|
|
368
|
+
});
|
|
369
|
+
const outcome = await Promise.race([generate.then(() => "settled", () => "settled"), guard]);
|
|
370
|
+
expect3(hung).toBe(false);
|
|
371
|
+
expect3(outcome).not.toBe("hung");
|
|
372
|
+
}
|
|
373
|
+
async function expectNoSecretInLogs(def, ctx, logs) {
|
|
374
|
+
await def.generate(ctx, BUILTIN_FIXTURES[0].input, AbortSignal.timeout(1e4)).catch(() => void 0);
|
|
375
|
+
for (const line of logs()) {
|
|
376
|
+
expect3(line.includes("compivia-contract-secret-value")).toBe(false);
|
|
377
|
+
}
|
|
378
|
+
}
|
|
379
|
+
async function expectNoLeakedTimers(def, ctx, close) {
|
|
380
|
+
if (def.init !== void 0) await def.init(ctx);
|
|
381
|
+
await def.generate(ctx, BUILTIN_FIXTURES[0].input, AbortSignal.timeout(1e4)).catch(() => void 0);
|
|
382
|
+
const before = process.getActiveResourcesInfo().filter((r) => r === "Timeout").length;
|
|
383
|
+
await close();
|
|
384
|
+
await new Promise((resolve) => setImmediate(() => resolve()));
|
|
385
|
+
const after = process.getActiveResourcesInfo().filter((r) => r === "Timeout").length;
|
|
386
|
+
expect3(after).toBeLessThanOrEqual(before);
|
|
387
|
+
}
|
|
388
|
+
function describePluginSlugContract(name, create) {
|
|
389
|
+
let handle = null;
|
|
390
|
+
afterEach2(async () => {
|
|
391
|
+
if (handle !== null) {
|
|
392
|
+
await handle.close();
|
|
393
|
+
handle = null;
|
|
394
|
+
}
|
|
395
|
+
});
|
|
396
|
+
describe3(`plugin slug contract: ${name}`, () => {
|
|
397
|
+
it3("definition conforms to the closed slug shape", async () => {
|
|
398
|
+
handle = await create();
|
|
399
|
+
expect3(collectPluginSlugIssues(handle.definition)).toEqual([]);
|
|
400
|
+
});
|
|
401
|
+
it3("generate returns {slug: non-empty string} or null for every fixture", async () => {
|
|
402
|
+
handle = await create();
|
|
403
|
+
await expectSlugOrNullForEveryFixture(handle, ctxOf3(handle));
|
|
404
|
+
});
|
|
405
|
+
it3("generate honors abort without hanging", async () => {
|
|
406
|
+
handle = await create();
|
|
407
|
+
await expectAbortResponsive(defOf(handle), ctxOf3(handle));
|
|
408
|
+
});
|
|
409
|
+
it3("secret values never appear in logs()", async () => {
|
|
410
|
+
handle = await create();
|
|
411
|
+
await expectNoSecretInLogs(defOf(handle), ctxOf3(handle), () => handle.logs());
|
|
412
|
+
});
|
|
413
|
+
it3("dispose is idempotent", async () => {
|
|
414
|
+
handle = await create();
|
|
415
|
+
const dispose = defOf(handle).dispose;
|
|
416
|
+
if (dispose !== void 0) {
|
|
417
|
+
await dispose();
|
|
418
|
+
await dispose();
|
|
419
|
+
}
|
|
420
|
+
});
|
|
421
|
+
it3("close leaves no timers behind", async () => {
|
|
422
|
+
handle = await create();
|
|
423
|
+
const active = handle;
|
|
424
|
+
await expectNoLeakedTimers(defOf(active), ctxOf3(active), async () => {
|
|
425
|
+
await active.close();
|
|
426
|
+
handle = null;
|
|
427
|
+
});
|
|
428
|
+
});
|
|
429
|
+
});
|
|
430
|
+
}
|
|
431
|
+
function ctxOf3(handle) {
|
|
432
|
+
return {
|
|
433
|
+
options: handle.options ?? {},
|
|
434
|
+
env: { COMPIVIA_CONTRACT_SECRET: "compivia-contract-secret-value", ...handle.env ?? {} },
|
|
435
|
+
logger: {
|
|
436
|
+
debug: (message) => handle.logs().push(`debug: ${message}`),
|
|
437
|
+
info: (message) => handle.logs().push(`info: ${message}`),
|
|
438
|
+
warn: (message) => handle.logs().push(`warn: ${message}`),
|
|
439
|
+
error: (message) => handle.logs().push(`error: ${message}`)
|
|
440
|
+
}
|
|
441
|
+
};
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
// src/testing.ts
|
|
445
|
+
function moduleFactory(modulePath) {
|
|
446
|
+
const logs = [];
|
|
447
|
+
return async () => {
|
|
448
|
+
const definition = (await import(pathToFileURL(modulePath).href)).default;
|
|
449
|
+
return { definition, logs: () => logs, close: async () => {
|
|
450
|
+
} };
|
|
451
|
+
};
|
|
452
|
+
}
|
|
453
|
+
function runPluginHarnessConformance(modulePath) {
|
|
454
|
+
describePluginHarnessContract(`plugin harness ${modulePath}`, moduleFactory(modulePath));
|
|
455
|
+
it4("definition passes the shape checks", async () => {
|
|
456
|
+
const definition = (await import(pathToFileURL(modulePath).href)).default;
|
|
457
|
+
expect4(collectPluginHarnessIssues(definition)).toEqual([]);
|
|
458
|
+
});
|
|
459
|
+
}
|
|
460
|
+
function runPluginReporterConformance(modulePath) {
|
|
461
|
+
describePluginReporterContract(`plugin reporter ${modulePath}`, moduleFactory(modulePath));
|
|
462
|
+
it4("definition passes the shape checks", async () => {
|
|
463
|
+
const definition = (await import(pathToFileURL(modulePath).href)).default;
|
|
464
|
+
expect4(collectPluginReporterIssues(definition)).toEqual([]);
|
|
465
|
+
});
|
|
466
|
+
}
|
|
467
|
+
function runSlugConformance(modulePath, opts = {}) {
|
|
468
|
+
describePluginSlugContract(`plugin slug ${modulePath}`, (async () => {
|
|
469
|
+
const inner = moduleFactory(modulePath)();
|
|
470
|
+
return { ...await inner, options: opts.options, env: opts.env, fixtures: opts.fixtures };
|
|
471
|
+
}));
|
|
472
|
+
it4("definition passes the shape checks", async () => {
|
|
473
|
+
const definition = (await import(pathToFileURL(modulePath).href)).default;
|
|
474
|
+
expect4(collectPluginSlugIssues(definition)).toEqual([]);
|
|
475
|
+
});
|
|
476
|
+
}
|
|
477
|
+
export {
|
|
478
|
+
collectPluginHarnessIssues,
|
|
479
|
+
collectPluginReporterIssues,
|
|
480
|
+
collectPluginSlugIssues,
|
|
481
|
+
describePluginHarnessContract,
|
|
482
|
+
describePluginReporterContract,
|
|
483
|
+
describePluginSlugContract,
|
|
484
|
+
runPluginHarnessConformance,
|
|
485
|
+
runPluginReporterConformance,
|
|
486
|
+
runSlugConformance
|
|
487
|
+
};
|
package/package.json
CHANGED
|
@@ -1,6 +1,50 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@compivia/plugin-sdk",
|
|
3
|
-
"version": "0.0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.0.1280",
|
|
4
|
+
"description": "SDK for authoring Compivia plugins (harness and reporter contributions)",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"compivia",
|
|
7
|
+
"plugin",
|
|
8
|
+
"sdk",
|
|
9
|
+
"harness",
|
|
10
|
+
"reporter"
|
|
11
|
+
],
|
|
12
|
+
"repository": {
|
|
13
|
+
"type": "git",
|
|
14
|
+
"url": "git+https://github.com/compivia/compivia-core-dev.git",
|
|
15
|
+
"directory": "packages/plugin-sdk"
|
|
16
|
+
},
|
|
17
|
+
"type": "module",
|
|
18
|
+
"license": "FSL-1.1-ALv2",
|
|
19
|
+
"engines": {
|
|
20
|
+
"node": ">=24"
|
|
21
|
+
},
|
|
22
|
+
"exports": {
|
|
23
|
+
".": {
|
|
24
|
+
"types": "./dist/index.d.ts",
|
|
25
|
+
"default": "./dist/index.js"
|
|
26
|
+
},
|
|
27
|
+
"./testing": {
|
|
28
|
+
"types": "./dist/testing.d.ts",
|
|
29
|
+
"default": "./dist/testing.js"
|
|
30
|
+
}
|
|
31
|
+
},
|
|
32
|
+
"files": [
|
|
33
|
+
"dist",
|
|
34
|
+
"README.md"
|
|
35
|
+
],
|
|
36
|
+
"publishConfig": {
|
|
37
|
+
"registry": "https://registry.npmjs.org/",
|
|
38
|
+
"access": "public"
|
|
39
|
+
},
|
|
40
|
+
"scripts": {
|
|
41
|
+
"build": "node build.mjs && tsc -p tsconfig.build.json",
|
|
42
|
+
"test": "vitest run",
|
|
43
|
+
"typecheck": "tsc --noEmit"
|
|
44
|
+
},
|
|
45
|
+
"peerDependencies": {
|
|
46
|
+
"vitest": ">=4.1.11 <5"
|
|
47
|
+
},
|
|
48
|
+
"devDependencies": {},
|
|
49
|
+
"dependencies": {}
|
|
50
|
+
}
|