refactor(onebot): declarative action-kit for param coercion + validation
Introduce packages/onebot/src/action-kit.ts — a zero-dependency,
type-inferring declarative layer for OneBot action params. Each action
declares its param contract (f.* coercers + optional cross-field rules)
and a `run` handler that receives typed, already-validated params.
Validation failures now return BAD_REQUEST naming the offending field
instead of falling through to ApiHandler's INTERNAL_ERROR catch.
- 141/142 actions migrated to defineAction/groupAction/groupUserAction
across info/message/friend/group-*/request/extended; only
.handle_quick_operation stays legacy (it needs the ApiHandler instance,
which run() does not receive).
- f.messageId() distinguishes signed/non-zero message ids from positive
group/user ids (f.uint()); int({min:0}).default(1800) fixes duration=0
(unmute), which the old `|| 1800` silently swallowed.
- run(p, ctx, raw) exposes the raw params as an escape hatch for the
irregular tail (alias-key fallbacks, arbitrary objects).
- action-docs.ts renders self-generated API docs from describe().
- ApiHandler dispatch / try-catch / response-wrapping unchanged (narrow seam).
Registered action name set is byte-identical before/after (142, verified
by runtime enumeration). Typecheck clean; onebot suite green (the
pre-existing websocket native-addon test failure is unrelated).
This commit is contained in:
13 files changed
+2729
-1651
No files matched your search
@@ -0,0 +1,80 @@
|
||||
// action-docs — self-generated OneBot API docs (D4).
|
||||
//
|
||||
// Walks `ActionSpec.describe()` over every declarative action and renders a
|
||||
// structured doc list + a Markdown view. The metadata is carried on the same
|
||||
// values that drive runtime validation, so docs cannot drift from behavior.
|
||||
//
|
||||
// Coverage note: the ~15 genuinely irregular actions in `actions/extended.ts`
|
||||
// that remain on the legacy `h.registerAction(...)` path are NOT ActionSpecs
|
||||
// and so do not appear here — that is the documented irregular tail.
|
||||
//
|
||||
// The serving SURFACE (WebUI panel / OpenAPI export / static markdown) is a
|
||||
// deferred product decision; this module produces format-agnostic data plus a
|
||||
// Markdown default. Point any renderer at `collectActionDocs()`.
|
||||
|
||||
import type { ActionDoc, ActionSpec, Field } from './action-kit';
|
||||
import { actions as infoActions } from './actions/info';
|
||||
import { actions as messageActions } from './actions/message';
|
||||
import { actions as friendActions } from './actions/friend';
|
||||
import { actions as groupInfoActions } from './actions/group-info';
|
||||
import { actions as groupAdminActions } from './actions/group-admin';
|
||||
import { actions as groupFileActions } from './actions/group-file';
|
||||
import { actions as requestActions } from './actions/request';
|
||||
import { actions as extendedActions } from './actions/extended';
|
||||
import { actions as groupAlbumActions } from './actions/group-album';
|
||||
|
||||
type AnySpec = ActionSpec<Record<string, Field<unknown>>>;
|
||||
|
||||
const ALL_SPECS: readonly AnySpec[] = [
|
||||
...infoActions,
|
||||
...messageActions,
|
||||
...friendActions,
|
||||
...groupInfoActions,
|
||||
...groupAdminActions,
|
||||
...groupFileActions,
|
||||
...requestActions,
|
||||
...extendedActions,
|
||||
...groupAlbumActions,
|
||||
];
|
||||
|
||||
/** Every declarative action's doc, sorted by name. */
|
||||
export function collectActionDocs(specs: readonly AnySpec[] = ALL_SPECS): ActionDoc[] {
|
||||
return specs.map((s) => s.describe()).sort((a, b) => a.name.localeCompare(b.name));
|
||||
}
|
||||
|
||||
function paramRow(p: ActionDoc['params'][number]): string {
|
||||
const type = p.values ? p.values.map((v) => JSON.stringify(v)).join(' \\| ') : p.type;
|
||||
const required = p.required ? '✓' : '–';
|
||||
const def = !p.required && p.default !== undefined ? `\`${JSON.stringify(p.default)}\`` : '';
|
||||
return `| \`${p.name}\` | ${type} | ${required} | ${def} | ${p.desc ?? ''} |`;
|
||||
}
|
||||
|
||||
function renderAction(doc: ActionDoc): string {
|
||||
const lines: string[] = [];
|
||||
const alias = doc.aliases.length ? ` _(别名: ${doc.aliases.map((a) => `\`${a}\``).join(', ')})_` : '';
|
||||
lines.push(`### \`${doc.name}\`${alias}`);
|
||||
if (doc.summary) lines.push('', doc.summary);
|
||||
if (doc.params.length) {
|
||||
lines.push('', '| 参数 | 类型 | 必填 | 默认 | 说明 |', '| --- | --- | --- | --- | --- |');
|
||||
for (const p of doc.params) lines.push(paramRow(p));
|
||||
} else {
|
||||
lines.push('', '_无参数_');
|
||||
}
|
||||
if (doc.invariants.length) lines.push('', `**约束:** ${doc.invariants.map((i) => `\`${i}\``).join(';')}`);
|
||||
if (doc.returns) lines.push('', `**返回:** \`${doc.returns}\``);
|
||||
return lines.join('\n');
|
||||
}
|
||||
|
||||
/** Render the full Markdown doc. */
|
||||
export function renderActionDocsMarkdown(docs: readonly ActionDoc[] = collectActionDocs()): string {
|
||||
const header = [
|
||||
'# OneBot Actions',
|
||||
'',
|
||||
'> 由 `packages/onebot/src/action-docs.ts` 从各 `ActionSpec.describe()` 自动生成,请勿手改。',
|
||||
'> 仅覆盖声明式 action;`extended.ts` 中少量走 legacy `registerAction` 的不规则 action 不在此列。',
|
||||
'',
|
||||
`共 ${docs.length} 个声明式 action。`,
|
||||
'',
|
||||
];
|
||||
return header.concat(docs.map(renderAction)).join('\n') + '\n';
|
||||
}
|
||||
@@ -0,0 +1,418 @@
|
||||
// action-kit — declarative OneBot Action definitions.
|
||||
//
|
||||
// One Action declares its param contract once (a record of `Field`s + optional
|
||||
// cross-field `rules`) and a `run` handler. The kit owns param coercion +
|
||||
// validation + the `BAD_REQUEST` shaping (naming the offending field) +
|
||||
// doc metadata. The handler receives typed, already-validated params.
|
||||
//
|
||||
// Narrow seam (ADR-0006): `ApiHandler` keeps dispatch / try-catch / response
|
||||
// wrapping. `defineAction(...).register(h, ctx)` ultimately registers a plain
|
||||
// `(params) => Promise<ApiResponse>` via `ApiHandler.registerAction`, exactly
|
||||
// like the legacy style — so old and new actions coexist during migration.
|
||||
//
|
||||
// Zero runtime npm deps (ADR-0004). Type inference via `InferParams` — no
|
||||
// hand-written param interface. Param contract is intentionally a second
|
||||
// definition from the SDK's client-side types (ADR-0005).
|
||||
//
|
||||
// Guard-rail (ADR-0007): the built-in coercers below are strict. Do NOT add a
|
||||
// lenient `union`/`refine` escape that re-introduces the silent coercion this
|
||||
// module exists to remove.
|
||||
|
||||
import { RETCODE, failedResponse } from './types';
|
||||
import type { ApiResponse, JsonObject, JsonValue } from './types';
|
||||
import type { ApiActionContext, ApiHandler } from './api-handler';
|
||||
|
||||
// ─────────────────────────── result currency ───────────────────────────
|
||||
|
||||
export type Ok<T> = { ok: true; value: T };
|
||||
/** `field` is the offending param ('' for a cross-field rule). */
|
||||
export type Err = { ok: false; field: string; reason: string };
|
||||
export type CoerceResult<T> = Ok<T> | Err;
|
||||
|
||||
const ok = <T>(value: T): Ok<T> => ({ ok: true, value });
|
||||
const err = (field: string, reason: string): Err => ({ ok: false, field, reason });
|
||||
|
||||
/** Only an absent key produces MISSING — this is what lets a present `0` /
|
||||
* `''` / `false` be distinguished from "not provided". */
|
||||
const MISSING = Symbol('missing');
|
||||
type Raw = JsonValue | typeof MISSING;
|
||||
|
||||
// ─────────────────────────── Field (param coercer) ───────────────────────────
|
||||
|
||||
export interface FieldDoc {
|
||||
type: string;
|
||||
required: boolean;
|
||||
default?: JsonValue;
|
||||
desc?: string;
|
||||
values?: readonly (string | number)[];
|
||||
}
|
||||
|
||||
export interface Field<T> {
|
||||
readonly doc: FieldDoc;
|
||||
/** Coerce the raw value at this field's key (MISSING when the key is absent). */
|
||||
coerce(raw: Raw, field: string): CoerceResult<T>;
|
||||
/** Absent ⇒ value is `undefined`; a present value still must coerce. */
|
||||
optional(): Field<T | undefined>;
|
||||
/** Absent ⇒ `value`; a present value still must coerce (so `"abc"` for a
|
||||
* numeric field is an error, not a silent fallback). */
|
||||
default(value: T): Field<T>;
|
||||
describe(text: string): Field<T>;
|
||||
}
|
||||
|
||||
/** Core coerces a PRESENT value (never MISSING). Presence policy is applied
|
||||
* by the wrapping Field. */
|
||||
type Core<T> = (raw: JsonValue, field: string) => CoerceResult<T>;
|
||||
|
||||
class FieldImpl<T> implements Field<T> {
|
||||
constructor(
|
||||
private readonly core: Core<T>,
|
||||
readonly doc: FieldDoc,
|
||||
) {}
|
||||
|
||||
coerce(raw: Raw, field: string): CoerceResult<T> {
|
||||
if (raw === MISSING) {
|
||||
if (this.doc.required) return err(field, 'is required');
|
||||
return ok(this.doc.default as T); // default value, or undefined when optional
|
||||
}
|
||||
return this.core(raw, field);
|
||||
}
|
||||
|
||||
optional(): Field<T | undefined> {
|
||||
return new FieldImpl<T | undefined>(this.core as Core<T | undefined>, {
|
||||
...this.doc,
|
||||
required: false,
|
||||
default: undefined,
|
||||
});
|
||||
}
|
||||
|
||||
default(value: T): Field<T> {
|
||||
return new FieldImpl<T>(this.core, { ...this.doc, required: false, default: value as JsonValue });
|
||||
}
|
||||
|
||||
describe(text: string): Field<T> {
|
||||
return new FieldImpl<T>(this.core, { ...this.doc, desc: text });
|
||||
}
|
||||
}
|
||||
|
||||
// ─────────────────────────── coercer vocabulary `f` ───────────────────────────
|
||||
|
||||
interface IntOpts { min?: number; max?: number; nonZero?: boolean }
|
||||
|
||||
/** Accept a number or numeric string, truncate to integer (matches the legacy
|
||||
* `asNumber`), then apply bounds. Non-numeric / blank ⇒ Err. */
|
||||
function intCore(typeName: string, opts: IntOpts): Core<number> {
|
||||
return (raw, field) => {
|
||||
let n: number;
|
||||
if (typeof raw === 'number' && Number.isFinite(raw)) n = Math.trunc(raw);
|
||||
else if (typeof raw === 'string' && raw.trim() !== '' && Number.isFinite(Number(raw))) n = Math.trunc(Number(raw));
|
||||
else return err(field, `expected ${typeName}`);
|
||||
if (opts.nonZero && n === 0) return err(field, 'must not be 0');
|
||||
if (opts.min !== undefined && n < opts.min) return err(field, `must be >= ${opts.min}`);
|
||||
if (opts.max !== undefined && n > opts.max) return err(field, `must be <= ${opts.max}`);
|
||||
return ok(n);
|
||||
};
|
||||
}
|
||||
|
||||
interface StrOpts { allowEmpty?: boolean; maxLen?: number }
|
||||
|
||||
function arrayField<E>(el: Field<E>, mustBeNonEmpty: boolean): Field<E[]> & { nonEmpty(): Field<E[]> } {
|
||||
const core: Core<E[]> = (raw, field) => {
|
||||
if (!Array.isArray(raw)) return err(field, 'expected an array');
|
||||
const out: E[] = [];
|
||||
for (let i = 0; i < raw.length; i++) {
|
||||
const r = el.coerce(raw[i] as JsonValue, `${field}[${i}]`);
|
||||
if (!r.ok) return r;
|
||||
out.push(r.value);
|
||||
}
|
||||
if (mustBeNonEmpty && out.length === 0) return err(field, 'must not be empty');
|
||||
return ok(out);
|
||||
};
|
||||
const base = new FieldImpl<E[]>(core, { type: `${el.doc.type}[]`, required: true });
|
||||
return Object.assign(base, { nonEmpty: () => arrayField(el, true) });
|
||||
}
|
||||
|
||||
export const f = {
|
||||
/** Positive integer (>0): group_id / user_id / message_id. */
|
||||
uint(): Field<number> {
|
||||
return new FieldImpl<number>(intCore('a positive integer', { min: 1 }), { type: 'uint', required: true });
|
||||
},
|
||||
/** Integer with optional bounds; allows 0 / negatives unless bounded.
|
||||
* e.g. a duration where 0 is meaningful: `f.int({ min: 0 })`. */
|
||||
int(opts: IntOpts = {}): Field<number> {
|
||||
return new FieldImpl<number>(intCore('an integer', opts), { type: 'int', required: true });
|
||||
},
|
||||
/** OneBot message id: a non-zero integer. NEGATIVES ARE VALID (ids are a
|
||||
* signed int32 hash) — do NOT use `uint()` for message_id. */
|
||||
messageId(): Field<number> {
|
||||
return new FieldImpl<number>(intCore('a message id', { nonZero: true }), { type: 'messageId', required: true });
|
||||
},
|
||||
/** Finite number (fractions allowed). */
|
||||
number(): Field<number> {
|
||||
return new FieldImpl<number>((raw, field) => {
|
||||
if (typeof raw === 'number' && Number.isFinite(raw)) return ok(raw);
|
||||
if (typeof raw === 'string' && raw.trim() !== '' && Number.isFinite(Number(raw))) return ok(Number(raw));
|
||||
return err(field, 'expected a number');
|
||||
}, { type: 'number', required: true });
|
||||
},
|
||||
/** String. Numbers/booleans stringify (matches legacy `asString`). Empty
|
||||
* allowed by default; `{ allowEmpty: false }` rejects ''. */
|
||||
string(opts: StrOpts = {}): Field<string> {
|
||||
return new FieldImpl<string>((raw, field) => {
|
||||
let s: string;
|
||||
if (typeof raw === 'string') s = raw;
|
||||
else if (typeof raw === 'number' || typeof raw === 'boolean') s = String(raw);
|
||||
else return err(field, 'expected a string');
|
||||
if (opts.allowEmpty === false && s === '') return err(field, 'must not be empty');
|
||||
if (opts.maxLen !== undefined && s.length > opts.maxLen) return err(field, `must be <= ${opts.maxLen} chars`);
|
||||
return ok(s);
|
||||
}, { type: 'string', required: true });
|
||||
},
|
||||
/** true/1/yes/on ⇒ true; false/0/no/off ⇒ false (matches legacy `asBoolean`). */
|
||||
bool(): Field<boolean> {
|
||||
return new FieldImpl<boolean>((raw, field) => {
|
||||
if (typeof raw === 'boolean') return ok(raw);
|
||||
if (typeof raw === 'number') return ok(raw !== 0);
|
||||
if (typeof raw === 'string') {
|
||||
const t = raw.trim().toLowerCase();
|
||||
if (t === 'true' || t === '1' || t === 'yes' || t === 'on') return ok(true);
|
||||
if (t === 'false' || t === '0' || t === 'no' || t === 'off') return ok(false);
|
||||
}
|
||||
return err(field, 'expected a boolean');
|
||||
}, { type: 'bool', required: true });
|
||||
},
|
||||
/** OneBot message union: string | segment[] | object. A string that looks
|
||||
* like a JSON array is parsed (matches legacy `asMessage`); otherwise the
|
||||
* value passes through. Output stays `JsonValue` — downstream ctx.* accept it. */
|
||||
message(): Field<JsonValue> {
|
||||
return new FieldImpl<JsonValue>((raw, _field) => {
|
||||
if (typeof raw === 'string') {
|
||||
const t = raw.trim();
|
||||
if (t.startsWith('[') && t.endsWith(']')) {
|
||||
try {
|
||||
const parsed: unknown = JSON.parse(t);
|
||||
if (Array.isArray(parsed)) return ok(parsed as JsonValue);
|
||||
} catch {
|
||||
// fall through to literal text
|
||||
}
|
||||
}
|
||||
}
|
||||
return ok(raw);
|
||||
}, { type: 'message', required: true });
|
||||
},
|
||||
/** Homogeneous array; `.nonEmpty()` rejects []. */
|
||||
array<E>(el: Field<E>): Field<E[]> & { nonEmpty(): Field<E[]> } {
|
||||
return arrayField(el, false);
|
||||
},
|
||||
/** Constrained literal set. */
|
||||
enum<const V extends readonly (string | number)[]>(...values: V): Field<V[number]> {
|
||||
return new FieldImpl<V[number]>((raw, field) => {
|
||||
if ((typeof raw === 'string' || typeof raw === 'number') && (values as readonly (string | number)[]).includes(raw)) {
|
||||
return ok(raw as V[number]);
|
||||
}
|
||||
return err(field, `expected one of: ${values.join(', ')}`);
|
||||
}, { type: 'enum', required: true, values });
|
||||
},
|
||||
/** Escape hatch — pass the raw value (or undefined) through, validate nothing. */
|
||||
raw(): Field<JsonValue | undefined> {
|
||||
return new FieldImpl<JsonValue | undefined>((raw) => ok(raw), { type: 'raw', required: false, default: undefined });
|
||||
},
|
||||
};
|
||||
|
||||
// ─────────────────────────── type inference ───────────────────────────
|
||||
|
||||
type Spec = Record<string, Field<unknown>>;
|
||||
type FieldType<F> = F extends Field<infer T> ? T : never;
|
||||
/** Post-validation every key is present; optional/raw fields carry `undefined`
|
||||
* in their value type. */
|
||||
export type InferParams<S extends Spec> = { [K in keyof S]: FieldType<S[K]> };
|
||||
|
||||
// ─────────────────────────── cross-field rules ───────────────────────────
|
||||
|
||||
export interface CrossFieldRule {
|
||||
readonly doc: string;
|
||||
check(params: Record<string, unknown>): Err | null;
|
||||
}
|
||||
|
||||
type Key<P> = Extract<keyof P, string>;
|
||||
type Group<P> = Key<P> | Key<P>[];
|
||||
|
||||
export interface RuleBuilders<P> {
|
||||
/** Exactly one group satisfied. A group is a key, or an array of keys that
|
||||
* must ALL be present. e.g. `exactlyOneOf('message_id', ['group_id','user_id'])`. */
|
||||
exactlyOneOf(...groups: Group<P>[]): CrossFieldRule;
|
||||
atLeastOneOf(...keys: Key<P>[]): CrossFieldRule;
|
||||
requiredTogether(...keys: Key<P>[]): CrossFieldRule;
|
||||
mutuallyExclusive(...keys: Key<P>[]): CrossFieldRule;
|
||||
/** Arbitrary predicate; fails with `doc` as the reason. */
|
||||
rule(doc: string, ok: (p: P) => boolean): CrossFieldRule;
|
||||
}
|
||||
|
||||
const present = (p: Record<string, unknown>, key: string): boolean => p[key] !== undefined;
|
||||
const groupOk = (p: Record<string, unknown>, g: string | string[]): boolean =>
|
||||
Array.isArray(g) ? g.every((k) => present(p, k)) : present(p, g);
|
||||
const groupLabel = (g: string | string[]): string => (Array.isArray(g) ? `(${g.join('+')})` : g);
|
||||
|
||||
const RULES: RuleBuilders<Record<string, unknown>> = {
|
||||
exactlyOneOf(...groups) {
|
||||
const doc = `exactly one of: ${groups.map(groupLabel).join(' | ')}`;
|
||||
return {
|
||||
doc,
|
||||
check: (p) => (groups.filter((g) => groupOk(p, g)).length === 1 ? null : err('', doc)),
|
||||
};
|
||||
},
|
||||
atLeastOneOf(...keys) {
|
||||
const doc = `at least one of: ${keys.join(', ')}`;
|
||||
return { doc, check: (p) => (keys.some((k) => present(p, k)) ? null : err('', doc)) };
|
||||
},
|
||||
requiredTogether(...keys) {
|
||||
const doc = `all or none of: ${keys.join(', ')}`;
|
||||
return {
|
||||
doc,
|
||||
check: (p) => {
|
||||
const n = keys.filter((k) => present(p, k)).length;
|
||||
return n === 0 || n === keys.length ? null : err('', doc);
|
||||
},
|
||||
};
|
||||
},
|
||||
mutuallyExclusive(...keys) {
|
||||
const doc = `at most one of: ${keys.join(', ')}`;
|
||||
return { doc, check: (p) => (keys.filter((k) => present(p, k)).length <= 1 ? null : err('', doc)) };
|
||||
},
|
||||
rule(doc, okFn) {
|
||||
return { doc, check: (p) => (okFn(p as never) ? null : err('', doc)) };
|
||||
},
|
||||
};
|
||||
|
||||
// ─────────────────────────── defineAction ───────────────────────────
|
||||
|
||||
export interface ParamDoc extends FieldDoc {
|
||||
name: string;
|
||||
}
|
||||
export interface ActionDoc {
|
||||
name: string;
|
||||
aliases: string[];
|
||||
summary?: string;
|
||||
returns?: string;
|
||||
params: ParamDoc[];
|
||||
invariants: string[];
|
||||
}
|
||||
|
||||
type Handler = (params: JsonObject) => Promise<ApiResponse>;
|
||||
|
||||
export interface ActionSpec<S extends Spec> {
|
||||
readonly names: string[];
|
||||
readonly params: S;
|
||||
/** Pure: coerce + validate + cross-field, no ctx, no I/O. The test surface. */
|
||||
parse(raw: JsonObject): CoerceResult<InferParams<S>>;
|
||||
/** Bind ctx and produce the `(params) => ApiResponse` for `registerAction`. */
|
||||
toHandler(ctx: ApiActionContext): Handler;
|
||||
/** Doc metadata (D4); a renderer walks this. */
|
||||
describe(): ActionDoc;
|
||||
register(h: ApiHandler, ctx: ApiActionContext): void;
|
||||
}
|
||||
|
||||
interface ActionDef<S extends Spec> {
|
||||
name: string | readonly [string, ...string[]];
|
||||
summary?: string;
|
||||
returns?: string;
|
||||
params: S;
|
||||
rules?: (r: RuleBuilders<InferParams<S>>) => readonly CrossFieldRule[];
|
||||
/** `raw` is the original untouched params — an escape hatch for the
|
||||
* irregular tail (alias-key fallbacks, arbitrary nested objects). Declared
|
||||
* fields in `p` remain the validated path; reach for `raw` only for keys
|
||||
* the spec can't express. */
|
||||
run: (p: InferParams<S>, ctx: ApiActionContext, raw: JsonObject) => Promise<ApiResponse> | ApiResponse;
|
||||
}
|
||||
|
||||
const wording = (e: Err): string => (e.field ? `${e.field}: ${e.reason}` : e.reason);
|
||||
|
||||
export function defineAction<S extends Spec>(def: ActionDef<S>): ActionSpec<S> {
|
||||
const names = typeof def.name === 'string' ? [def.name] : [...def.name];
|
||||
const rules: readonly CrossFieldRule[] = def.rules
|
||||
? def.rules(RULES as unknown as RuleBuilders<InferParams<S>>)
|
||||
: [];
|
||||
|
||||
const parse = (raw: JsonObject): CoerceResult<InferParams<S>> => {
|
||||
const out: Record<string, unknown> = {};
|
||||
for (const key of Object.keys(def.params)) {
|
||||
const field = def.params[key];
|
||||
const value = Object.prototype.hasOwnProperty.call(raw, key) ? (raw[key] as JsonValue) : MISSING;
|
||||
const r = field.coerce(value, key);
|
||||
if (!r.ok) return r;
|
||||
out[key] = r.value;
|
||||
}
|
||||
for (const rule of rules) {
|
||||
const e = rule.check(out);
|
||||
if (e) return e;
|
||||
}
|
||||
return ok(out as InferParams<S>);
|
||||
};
|
||||
|
||||
const toHandler = (ctx: ApiActionContext): Handler => async (params: JsonObject) => {
|
||||
const r = parse(params);
|
||||
if (!r.ok) return failedResponse(RETCODE.BAD_REQUEST, wording(r));
|
||||
return def.run(r.value, ctx, params);
|
||||
};
|
||||
|
||||
return {
|
||||
names,
|
||||
params: def.params,
|
||||
parse,
|
||||
toHandler,
|
||||
describe: () => ({
|
||||
name: names[0],
|
||||
aliases: names.slice(1),
|
||||
summary: def.summary,
|
||||
returns: def.returns,
|
||||
params: Object.entries(def.params).map(([name, field]) => ({ name, ...field.doc })),
|
||||
invariants: rules.map((rule) => rule.doc),
|
||||
}),
|
||||
register: (h, ctx) => {
|
||||
const handler = toHandler(ctx);
|
||||
for (const name of names) h.registerAction(name, handler);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
// ─────────────────────────── presets ───────────────────────────
|
||||
// `group_id` appears in 61/142 actions, `user_id` in 27 — these collapse the
|
||||
// dominant shape. The injected fields are surfaced in `describe()` so docs
|
||||
// list them even though the caller never typed them (ADR-0006 trade-off).
|
||||
|
||||
type WithGroup<S extends Spec> = S & { group_id: Field<number> };
|
||||
type WithGroupUser<S extends Spec> = S & { group_id: Field<number>; user_id: Field<number> };
|
||||
|
||||
interface PresetDef<S extends Spec, Extra> {
|
||||
name: string | readonly [string, ...string[]];
|
||||
summary?: string;
|
||||
returns?: string;
|
||||
params?: S;
|
||||
rules?: (r: RuleBuilders<InferParams<S> & Extra>) => readonly CrossFieldRule[];
|
||||
run: (p: InferParams<S> & Extra, ctx: ApiActionContext, raw: JsonObject) => Promise<ApiResponse> | ApiResponse;
|
||||
}
|
||||
|
||||
/** Pre-seeds `group_id` (uint, required). */
|
||||
export function groupAction<S extends Spec>(def: PresetDef<S, { group_id: number }>): ActionSpec<WithGroup<S>> {
|
||||
const params = { group_id: f.uint().describe('群号'), ...(def.params ?? {}) } as WithGroup<S>;
|
||||
return defineAction({ ...def, params } as unknown as ActionDef<WithGroup<S>>);
|
||||
}
|
||||
|
||||
/** Pre-seeds `group_id` + `user_id` (both uint, required). */
|
||||
export function groupUserAction<S extends Spec>(
|
||||
def: PresetDef<S, { group_id: number; user_id: number }>,
|
||||
): ActionSpec<WithGroupUser<S>> {
|
||||
const params = {
|
||||
group_id: f.uint().describe('群号'),
|
||||
user_id: f.uint().describe('QQ 号'),
|
||||
...(def.params ?? {}),
|
||||
} as WithGroupUser<S>;
|
||||
return defineAction({ ...def, params } as unknown as ActionDef<WithGroupUser<S>>);
|
||||
}
|
||||
|
||||
// ─────────────────────────── registration helper ───────────────────────────
|
||||
|
||||
/** Register many specs onto an ApiHandler. Coexists with legacy
|
||||
* `h.registerAction(name, fn)` in the same `register(h, ctx)`. */
|
||||
export function registerActions(h: ApiHandler, ctx: ApiActionContext, specs: ReadonlyArray<ActionSpec<Spec>>): void {
|
||||
for (const spec of specs) spec.register(h, ctx);
|
||||
}
|
||||
+1314
-1077
File diff suppressed because it is too large.
Load diff
@@ -1,30 +1,45 @@
|
||||
import type { ApiHandler, ApiActionContext } from '../api-handler';
|
||||
import { asNumber, asBoolean } from '../api-handler';
|
||||
import { RETCODE, failedResponse, okResponse } from '../types';
|
||||
import { defineAction, registerActions, f } from '../action-kit';
|
||||
import type { ApiActionContext, ApiHandler } from '../api-handler';
|
||||
import { okResponse } from '../types';
|
||||
|
||||
export const actions = [
|
||||
defineAction({
|
||||
name: 'get_friend_list',
|
||||
summary: '获取好友列表',
|
||||
params: {},
|
||||
run: async (_p, ctx) => {
|
||||
if (ctx.getFriendList) {
|
||||
return okResponse(await ctx.getFriendList());
|
||||
}
|
||||
return okResponse([]);
|
||||
},
|
||||
}),
|
||||
|
||||
defineAction({
|
||||
name: 'get_stranger_info',
|
||||
summary: '获取陌生人信息',
|
||||
params: { user_id: f.uint().describe('QQ 号') },
|
||||
run: async (p, ctx) => {
|
||||
const userId = p.user_id;
|
||||
if (ctx.getStrangerInfo) {
|
||||
const info = await ctx.getStrangerInfo(userId);
|
||||
return okResponse(info ?? { user_id: userId, nickname: '', sex: 'unknown', age: 0 });
|
||||
}
|
||||
return okResponse({ user_id: userId, nickname: '', sex: 'unknown', age: 0 });
|
||||
},
|
||||
}),
|
||||
|
||||
defineAction({
|
||||
name: 'delete_friend',
|
||||
summary: '删除好友',
|
||||
params: { user_id: f.uint().describe('QQ 号'), block: f.bool().default(false) },
|
||||
run: async (p, ctx) => {
|
||||
await ctx.bridge.apis.friend.delete(p.user_id, p.block);
|
||||
return okResponse();
|
||||
},
|
||||
}),
|
||||
];
|
||||
|
||||
export function register(h: ApiHandler, ctx: ApiActionContext): void {
|
||||
h.registerAction('get_friend_list', async () => {
|
||||
if (ctx.getFriendList) {
|
||||
return okResponse(await ctx.getFriendList());
|
||||
}
|
||||
return okResponse([]);
|
||||
});
|
||||
|
||||
h.registerAction('get_stranger_info', async (params) => {
|
||||
const userId = asNumber(params.user_id);
|
||||
if (!userId) return failedResponse(RETCODE.BAD_REQUEST, 'user_id is required');
|
||||
if (ctx.getStrangerInfo) {
|
||||
const info = await ctx.getStrangerInfo(userId);
|
||||
return okResponse(info ?? { user_id: userId, nickname: '', sex: 'unknown', age: 0 });
|
||||
}
|
||||
return okResponse({ user_id: userId, nickname: '', sex: 'unknown', age: 0 });
|
||||
});
|
||||
|
||||
h.registerAction('delete_friend', async (params) => {
|
||||
const userId = asNumber(params.user_id);
|
||||
const block = asBoolean(params.block, false);
|
||||
if (!userId) return failedResponse(RETCODE.BAD_REQUEST, 'user_id is required');
|
||||
await ctx.bridge.apis.friend.delete(userId, block);
|
||||
return okResponse();
|
||||
});
|
||||
registerActions(h, ctx, actions);
|
||||
}
|
||||
@@ -1,118 +1,135 @@
|
||||
import { defineAction, groupAction, groupUserAction, registerActions, f } from '../action-kit';
|
||||
import type { ApiActionContext, ApiHandler } from '../api-handler';
|
||||
import { asBoolean, asNumber, asString } from '../api-handler';
|
||||
import { RETCODE, failedResponse, okResponse } from '../types';
|
||||
|
||||
export function register(h: ApiHandler, ctx: ApiActionContext): void {
|
||||
h.registerAction('set_group_kick', async (params) => {
|
||||
const groupId = asNumber(params.group_id);
|
||||
const userId = asNumber(params.user_id);
|
||||
const reject = asBoolean(params.reject_add_request, false);
|
||||
if (!groupId || !userId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id and user_id are required');
|
||||
await ctx.bridge.apis.groupAdmin.kickMember(groupId, userId, reject);
|
||||
return okResponse();
|
||||
});
|
||||
|
||||
h.registerAction('set_group_kick_members', async (params) => {
|
||||
const groupId = asNumber(params.group_id);
|
||||
const userIds = Array.isArray(params.user_id) ? params.user_id.map(asNumber).filter(Boolean) : [];
|
||||
const reject = asBoolean(params.reject_add_request, false);
|
||||
if (!groupId || userIds.length === 0) return failedResponse(RETCODE.BAD_REQUEST, 'group_id and user_id array are required');
|
||||
await ctx.bridge.apis.groupAdmin.kickMembers(groupId, userIds, reject);
|
||||
return okResponse();
|
||||
});
|
||||
|
||||
h.registerAction('set_group_ban', async (params) => {
|
||||
const groupId = asNumber(params.group_id);
|
||||
const userId = asNumber(params.user_id);
|
||||
const duration = asNumber(params.duration) || 1800;
|
||||
if (!groupId || !userId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id and user_id are required');
|
||||
await ctx.bridge.apis.groupAdmin.muteMember(groupId, userId, duration);
|
||||
return okResponse();
|
||||
});
|
||||
|
||||
h.registerAction('set_group_whole_ban', async (params) => {
|
||||
const groupId = asNumber(params.group_id);
|
||||
const enable = asBoolean(params.enable, true);
|
||||
if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
|
||||
await ctx.bridge.apis.groupAdmin.muteAll(groupId, enable);
|
||||
return okResponse();
|
||||
});
|
||||
|
||||
h.registerAction('set_group_add_option', async (params) => {
|
||||
const groupId = asNumber(params.group_id);
|
||||
const addType = asNumber(params.add_type);
|
||||
if (!groupId || addType === undefined) return failedResponse(RETCODE.BAD_REQUEST, 'group_id and add_type are required');
|
||||
await ctx.bridge.apis.groupAdmin.setAddOption(groupId, addType);
|
||||
return okResponse();
|
||||
});
|
||||
|
||||
h.registerAction('set_group_search', async (params) => {
|
||||
const groupId = asNumber(params.group_id);
|
||||
if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
|
||||
await ctx.bridge.apis.groupAdmin.setSearch(groupId);
|
||||
return okResponse();
|
||||
});
|
||||
|
||||
h.registerAction('set_group_admin', async (params) => {
|
||||
const groupId = asNumber(params.group_id);
|
||||
const userId = asNumber(params.user_id);
|
||||
const enable = asBoolean(params.enable, true);
|
||||
if (!groupId || !userId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id and user_id are required');
|
||||
await ctx.bridge.apis.groupAdmin.setAdmin(groupId, userId, enable);
|
||||
return okResponse();
|
||||
});
|
||||
|
||||
h.registerAction('set_group_card', async (params) => {
|
||||
const groupId = asNumber(params.group_id);
|
||||
const userId = asNumber(params.user_id);
|
||||
const card = asString(params.card);
|
||||
if (!groupId || !userId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id and user_id are required');
|
||||
await ctx.bridge.apis.groupAdmin.setCard(groupId, userId, card);
|
||||
return okResponse();
|
||||
});
|
||||
|
||||
h.registerAction('set_group_name', async (params) => {
|
||||
const groupId = asNumber(params.group_id);
|
||||
const name = asString(params.group_name);
|
||||
if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
|
||||
await ctx.bridge.apis.groupAdmin.setName(groupId, name);
|
||||
return okResponse();
|
||||
});
|
||||
|
||||
h.registerAction('set_group_leave', async (params) => {
|
||||
const groupId = asNumber(params.group_id);
|
||||
if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
|
||||
await ctx.bridge.apis.groupAdmin.leave(groupId);
|
||||
return okResponse();
|
||||
});
|
||||
|
||||
h.registerAction('set_group_special_title', async (params) => {
|
||||
const groupId = asNumber(params.group_id);
|
||||
const userId = asNumber(params.user_id);
|
||||
const title = asString(params.special_title);
|
||||
if (!groupId || !userId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id and user_id are required');
|
||||
await ctx.bridge.apis.groupAdmin.setSpecialTitle(groupId, userId, title);
|
||||
return okResponse();
|
||||
});
|
||||
|
||||
h.registerAction('set_group_anonymous', async () => {
|
||||
return okResponse();
|
||||
});
|
||||
|
||||
h.registerAction('set_group_anonymous_ban', async () => {
|
||||
return okResponse();
|
||||
});
|
||||
|
||||
h.registerAction('set_group_portrait', async (params) => {
|
||||
const groupId = asNumber(params.group_id);
|
||||
const file = asString(params.file);
|
||||
if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
|
||||
if (!file) return failedResponse(RETCODE.BAD_REQUEST, 'file is required');
|
||||
try {
|
||||
await ctx.bridge.apis.profile.setGroupAvatar(groupId, file);
|
||||
export const actions = [
|
||||
groupUserAction({
|
||||
name: 'set_group_kick',
|
||||
summary: '踢出群成员',
|
||||
params: { reject_add_request: f.bool().default(false) },
|
||||
run: async (p, ctx) => {
|
||||
await ctx.bridge.apis.groupAdmin.kickMember(p.group_id, p.user_id, p.reject_add_request);
|
||||
return okResponse();
|
||||
} catch (err) {
|
||||
return failedResponse(RETCODE.ACTION_FAILED, err instanceof Error ? err.message : String(err));
|
||||
}
|
||||
});
|
||||
},
|
||||
}),
|
||||
|
||||
groupAction({
|
||||
name: 'set_group_kick_members',
|
||||
summary: '批量踢出群成员',
|
||||
params: { user_id: f.array(f.uint()).nonEmpty(), reject_add_request: f.bool().default(false) },
|
||||
run: async (p, ctx) => {
|
||||
await ctx.bridge.apis.groupAdmin.kickMembers(p.group_id, p.user_id, p.reject_add_request);
|
||||
return okResponse();
|
||||
},
|
||||
}),
|
||||
|
||||
groupUserAction({
|
||||
name: 'set_group_ban',
|
||||
summary: '禁言群成员(duration=0 解除)',
|
||||
params: { duration: f.int({ min: 0 }).default(1800) },
|
||||
run: async (p, ctx) => {
|
||||
await ctx.bridge.apis.groupAdmin.muteMember(p.group_id, p.user_id, p.duration);
|
||||
return okResponse();
|
||||
},
|
||||
}),
|
||||
|
||||
groupAction({
|
||||
name: 'set_group_whole_ban',
|
||||
summary: '全员禁言开关',
|
||||
params: { enable: f.bool().default(true) },
|
||||
run: async (p, ctx) => {
|
||||
await ctx.bridge.apis.groupAdmin.muteAll(p.group_id, p.enable);
|
||||
return okResponse();
|
||||
},
|
||||
}),
|
||||
|
||||
groupAction({
|
||||
name: 'set_group_add_option',
|
||||
summary: '设置加群选项',
|
||||
params: { add_type: f.int({ min: 0 }).default(0) },
|
||||
run: async (p, ctx) => {
|
||||
await ctx.bridge.apis.groupAdmin.setAddOption(p.group_id, p.add_type);
|
||||
return okResponse();
|
||||
},
|
||||
}),
|
||||
|
||||
groupAction({
|
||||
name: 'set_group_search',
|
||||
summary: '允许群被搜索',
|
||||
run: async (p, ctx) => {
|
||||
await ctx.bridge.apis.groupAdmin.setSearch(p.group_id);
|
||||
return okResponse();
|
||||
},
|
||||
}),
|
||||
|
||||
groupUserAction({
|
||||
name: 'set_group_admin',
|
||||
summary: '设置/取消管理员',
|
||||
params: { enable: f.bool().default(true) },
|
||||
run: async (p, ctx) => {
|
||||
await ctx.bridge.apis.groupAdmin.setAdmin(p.group_id, p.user_id, p.enable);
|
||||
return okResponse();
|
||||
},
|
||||
}),
|
||||
|
||||
groupUserAction({
|
||||
name: 'set_group_card',
|
||||
summary: '设置群名片(空字符串清除)',
|
||||
params: { card: f.string().default('') },
|
||||
run: async (p, ctx) => {
|
||||
await ctx.bridge.apis.groupAdmin.setCard(p.group_id, p.user_id, p.card);
|
||||
return okResponse();
|
||||
},
|
||||
}),
|
||||
|
||||
groupAction({
|
||||
name: 'set_group_name',
|
||||
summary: '设置群名',
|
||||
params: { group_name: f.string().default('') },
|
||||
run: async (p, ctx) => {
|
||||
await ctx.bridge.apis.groupAdmin.setName(p.group_id, p.group_name);
|
||||
return okResponse();
|
||||
},
|
||||
}),
|
||||
|
||||
groupAction({
|
||||
name: 'set_group_leave',
|
||||
summary: '退群',
|
||||
run: async (p, ctx) => {
|
||||
await ctx.bridge.apis.groupAdmin.leave(p.group_id);
|
||||
return okResponse();
|
||||
},
|
||||
}),
|
||||
|
||||
groupUserAction({
|
||||
name: 'set_group_special_title',
|
||||
summary: '设置群头衔',
|
||||
params: { special_title: f.string().default('') },
|
||||
run: async (p, ctx) => {
|
||||
await ctx.bridge.apis.groupAdmin.setSpecialTitle(p.group_id, p.user_id, p.special_title);
|
||||
return okResponse();
|
||||
},
|
||||
}),
|
||||
|
||||
// No-op stubs (accept and ignore any params, as before).
|
||||
defineAction({ name: 'set_group_anonymous', summary: '匿名开关(未实现,返回 ok)', params: {}, run: () => okResponse() }),
|
||||
defineAction({ name: 'set_group_anonymous_ban', summary: '匿名禁言(未实现,返回 ok)', params: {}, run: () => okResponse() }),
|
||||
|
||||
groupAction({
|
||||
name: 'set_group_portrait',
|
||||
summary: '设置群头像',
|
||||
params: { file: f.string({ allowEmpty: false }) },
|
||||
run: async (p, ctx) => {
|
||||
try {
|
||||
await ctx.bridge.apis.profile.setGroupAvatar(p.group_id, p.file);
|
||||
return okResponse();
|
||||
} catch (err) {
|
||||
return failedResponse(RETCODE.ACTION_FAILED, err instanceof Error ? err.message : String(err));
|
||||
}
|
||||
},
|
||||
}),
|
||||
];
|
||||
|
||||
export function register(h: ApiHandler, ctx: ApiActionContext): void {
|
||||
registerActions(h, ctx, actions);
|
||||
}
|
||||
@@ -1,133 +1,130 @@
|
||||
import { groupAction, registerActions, f } from '../action-kit';
|
||||
import type { ApiActionContext, ApiHandler } from '../api-handler';
|
||||
import { asNumber, asString } from '../api-handler';
|
||||
import type { JsonValue } from '../types';
|
||||
import { RETCODE, failedResponse, okResponse } from '../types';
|
||||
|
||||
export function register(h: ApiHandler, ctx: ApiActionContext): void {
|
||||
h.registerAction('get_group_album_list', async (params) => {
|
||||
const groupId = asNumber(params.group_id);
|
||||
if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
|
||||
export const actions = [
|
||||
groupAction({
|
||||
name: 'get_group_album_list',
|
||||
run: async (p, ctx) => {
|
||||
try {
|
||||
const albumList = await ctx.bridge.apis.groupAlbum.list(p.group_id);
|
||||
return okResponse(albumList);
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : 'failed to get group album list';
|
||||
return failedResponse(RETCODE.INTERNAL_ERROR, message);
|
||||
}
|
||||
},
|
||||
}),
|
||||
|
||||
try {
|
||||
const albumList = await ctx.bridge.apis.groupAlbum.list(groupId);
|
||||
return okResponse(albumList);
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : 'failed to get group album list';
|
||||
return failedResponse(RETCODE.INTERNAL_ERROR, message);
|
||||
}
|
||||
});
|
||||
groupAction({
|
||||
name: 'upload_image_to_qun_album',
|
||||
params: {
|
||||
album_id: f.string({ allowEmpty: false }),
|
||||
album_name: f.string({ allowEmpty: false }),
|
||||
file: f.string({ allowEmpty: false }),
|
||||
},
|
||||
run: async (p, ctx) => {
|
||||
try {
|
||||
await ctx.bridge.apis.groupAlbum.upload(p.group_id, p.album_id, p.album_name, p.file);
|
||||
return okResponse(null);
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : 'failed to upload image to group album';
|
||||
return failedResponse(RETCODE.INTERNAL_ERROR, message);
|
||||
}
|
||||
},
|
||||
}),
|
||||
|
||||
h.registerAction('upload_image_to_qun_album', async (params) => {
|
||||
const groupId = asNumber(params.group_id);
|
||||
const albumId = asString(params.album_id);
|
||||
const albumName = asString(params.album_name);
|
||||
const file = asString(params.file);
|
||||
groupAction({
|
||||
name: 'get_group_album_media_list',
|
||||
params: {
|
||||
album_id: f.string({ allowEmpty: false }),
|
||||
attach_info: f.string().default(''),
|
||||
},
|
||||
run: async (p, ctx) => {
|
||||
try {
|
||||
const mediaList = await ctx.bridge.apis.groupAlbum.getMediaList(p.group_id, p.album_id, p.attach_info);
|
||||
return okResponse(mediaList as unknown as JsonValue);
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : 'failed to get group album media list';
|
||||
return failedResponse(RETCODE.INTERNAL_ERROR, message);
|
||||
}
|
||||
},
|
||||
}),
|
||||
|
||||
if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
|
||||
if (!albumId) return failedResponse(RETCODE.BAD_REQUEST, 'album_id is required');
|
||||
if (!albumName) return failedResponse(RETCODE.BAD_REQUEST, 'album_name is required');
|
||||
if (!file) return failedResponse(RETCODE.BAD_REQUEST, 'file is required');
|
||||
groupAction({
|
||||
name: 'do_group_album_comment',
|
||||
params: {
|
||||
album_id: f.string({ allowEmpty: false }),
|
||||
lloc: f.string({ allowEmpty: false }),
|
||||
content: f.string({ allowEmpty: false }),
|
||||
},
|
||||
run: async (p, ctx) => {
|
||||
try {
|
||||
const comment = await ctx.bridge.apis.groupAlbum.comment(p.group_id, p.album_id, p.lloc, p.content);
|
||||
return okResponse(comment as unknown as JsonValue);
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : 'failed to comment on album media';
|
||||
return failedResponse(RETCODE.INTERNAL_ERROR, message);
|
||||
}
|
||||
},
|
||||
}),
|
||||
|
||||
try {
|
||||
await ctx.bridge.apis.groupAlbum.upload(groupId, albumId, albumName, file);
|
||||
return okResponse(null);
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : 'failed to upload image to group album';
|
||||
return failedResponse(RETCODE.INTERNAL_ERROR, message);
|
||||
}
|
||||
});
|
||||
|
||||
h.registerAction('get_group_album_media_list', async (params) => {
|
||||
const groupId = asNumber(params.group_id);
|
||||
const albumId = asString(params.album_id);
|
||||
const attachInfo = asString(params.attach_info) || '';
|
||||
|
||||
if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
|
||||
if (!albumId) return failedResponse(RETCODE.BAD_REQUEST, 'album_id is required');
|
||||
|
||||
try {
|
||||
const mediaList = await ctx.bridge.apis.groupAlbum.getMediaList(groupId, albumId, attachInfo);
|
||||
return okResponse(mediaList as unknown as JsonValue);
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : 'failed to get group album media list';
|
||||
return failedResponse(RETCODE.INTERNAL_ERROR, message);
|
||||
}
|
||||
});
|
||||
|
||||
h.registerAction('do_group_album_comment', async (params) => {
|
||||
const groupId = asNumber(params.group_id);
|
||||
const albumId = asString(params.album_id);
|
||||
const lloc = asString(params.lloc);
|
||||
const content = asString(params.content);
|
||||
|
||||
if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
|
||||
if (!albumId) return failedResponse(RETCODE.BAD_REQUEST, 'album_id is required');
|
||||
if (!lloc) return failedResponse(RETCODE.BAD_REQUEST, 'lloc is required');
|
||||
if (!content) return failedResponse(RETCODE.BAD_REQUEST, 'content is required');
|
||||
|
||||
try {
|
||||
const comment = await ctx.bridge.apis.groupAlbum.comment(groupId, albumId, lloc, content);
|
||||
return okResponse(comment as unknown as JsonValue);
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : 'failed to comment on album media';
|
||||
return failedResponse(RETCODE.INTERNAL_ERROR, message);
|
||||
}
|
||||
});
|
||||
|
||||
h.registerAction('set_group_album_media_like', async (params) => {
|
||||
const groupId = asNumber(params.group_id);
|
||||
const albumId = asString(params.album_id);
|
||||
const batchId = asString(params.batch_id);
|
||||
const lloc = params.lloc ? asString(params.lloc) : undefined; // 可选参数
|
||||
|
||||
if (!groupId || !albumId || !batchId) {
|
||||
return failedResponse(RETCODE.BAD_REQUEST, 'group_id, album_id and batch_id are required');
|
||||
}
|
||||
|
||||
try {
|
||||
const res = await ctx.bridge.apis.groupAlbum.like(groupId, albumId, batchId, lloc, true);
|
||||
return okResponse(res);
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : 'failed to set like on album media';
|
||||
return failedResponse(RETCODE.INTERNAL_ERROR, message);
|
||||
}
|
||||
});
|
||||
groupAction({
|
||||
name: 'set_group_album_media_like',
|
||||
params: {
|
||||
album_id: f.string({ allowEmpty: false }),
|
||||
batch_id: f.string({ allowEmpty: false }),
|
||||
lloc: f.string().optional(), // 可选参数(空串按未传处理)
|
||||
},
|
||||
run: async (p, ctx) => {
|
||||
try {
|
||||
const res = await ctx.bridge.apis.groupAlbum.like(p.group_id, p.album_id, p.batch_id, p.lloc || undefined, true);
|
||||
return okResponse(res);
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : 'failed to set like on album media';
|
||||
return failedResponse(RETCODE.INTERNAL_ERROR, message);
|
||||
}
|
||||
},
|
||||
}),
|
||||
|
||||
// 取消点赞群相册媒体
|
||||
h.registerAction('cancel_group_album_media_like', async (params) => {
|
||||
const groupId = asNumber(params.group_id);
|
||||
const albumId = asString(params.album_id);
|
||||
const batchId = asString(params.batch_id);
|
||||
const lloc = params.lloc ? asString(params.lloc) : undefined; // 可选参数
|
||||
groupAction({
|
||||
name: 'cancel_group_album_media_like',
|
||||
params: {
|
||||
album_id: f.string({ allowEmpty: false }),
|
||||
batch_id: f.string({ allowEmpty: false }),
|
||||
lloc: f.string().optional(), // 可选参数(空串按未传处理)
|
||||
},
|
||||
run: async (p, ctx) => {
|
||||
try {
|
||||
const res = await ctx.bridge.apis.groupAlbum.like(p.group_id, p.album_id, p.batch_id, p.lloc || undefined, false);
|
||||
return okResponse(res);
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : 'failed to cancel like on album media';
|
||||
return failedResponse(RETCODE.INTERNAL_ERROR, message);
|
||||
}
|
||||
},
|
||||
}),
|
||||
|
||||
if (!groupId || !albumId || !batchId) {
|
||||
return failedResponse(RETCODE.BAD_REQUEST, 'group_id, album_id and batch_id are required');
|
||||
}
|
||||
groupAction({
|
||||
name: 'del_group_album_media',
|
||||
params: {
|
||||
album_id: f.string({ allowEmpty: false }),
|
||||
lloc: f.string({ allowEmpty: false }),
|
||||
},
|
||||
run: async (p, ctx) => {
|
||||
try {
|
||||
const res = await ctx.bridge.apis.groupAlbum.delete(p.group_id, p.album_id, p.lloc);
|
||||
return okResponse(res);
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : 'failed to delete album media';
|
||||
return failedResponse(RETCODE.INTERNAL_ERROR, message);
|
||||
}
|
||||
},
|
||||
}),
|
||||
];
|
||||
|
||||
try {
|
||||
const res = await ctx.bridge.apis.groupAlbum.like(groupId, albumId, batchId, lloc, false);
|
||||
return okResponse(res);
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : 'failed to cancel like on album media';
|
||||
return failedResponse(RETCODE.INTERNAL_ERROR, message);
|
||||
}
|
||||
});
|
||||
|
||||
h.registerAction('del_group_album_media', async (params) => {
|
||||
const groupId = asNumber(params.group_id);
|
||||
const albumId = asString(params.album_id);
|
||||
const lloc = asString(params.lloc);
|
||||
|
||||
if (!groupId || !albumId || !lloc) {
|
||||
return failedResponse(RETCODE.BAD_REQUEST, 'group_id, album_id and lloc are required');
|
||||
}
|
||||
|
||||
try {
|
||||
const res = await ctx.bridge.apis.groupAlbum.delete(groupId, albumId, lloc);
|
||||
return okResponse(res);
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : 'failed to delete album media';
|
||||
return failedResponse(RETCODE.INTERNAL_ERROR, message);
|
||||
}
|
||||
});
|
||||
export function register(h: ApiHandler, ctx: ApiActionContext): void {
|
||||
registerActions(h, ctx, actions);
|
||||
}
|
||||
@@ -1,118 +1,153 @@
|
||||
import { defineAction, groupAction, registerActions, f } from '../action-kit';
|
||||
import type { ApiHandler, ApiActionContext } from '../api-handler';
|
||||
import { asBoolean, asNumber, asString } from '../api-handler';
|
||||
import { RETCODE, failedResponse } from '../types';
|
||||
import { okResponse } from '../types';
|
||||
import { RETCODE, failedResponse, okResponse } from '../types';
|
||||
|
||||
export const actions = [
|
||||
groupAction({
|
||||
name: 'upload_group_file',
|
||||
summary: '上传群文件',
|
||||
returns: '{ file_id: string }',
|
||||
// `folder` / `folder_id` are two aliases for one target dir; the first
|
||||
// non-empty wins, else '/'. Both default '' so the `||` chain matches the
|
||||
// legacy `asString(folder) || asString(folder_id) || '/'`.
|
||||
params: {
|
||||
file: f.string({ allowEmpty: false }),
|
||||
name: f.string().default(''),
|
||||
folder: f.string().default(''),
|
||||
folder_id: f.string().default(''),
|
||||
upload_file: f.bool().default(true),
|
||||
},
|
||||
run: async (p, ctx) => {
|
||||
const folderId = p.folder || p.folder_id || '/';
|
||||
const result = await ctx.bridge.apis.groupFile.upload(p.group_id, p.file, p.name, folderId, p.upload_file);
|
||||
return okResponse({ file_id: result.fileId });
|
||||
},
|
||||
}),
|
||||
|
||||
defineAction({
|
||||
name: 'upload_private_file',
|
||||
summary: '上传私聊文件',
|
||||
returns: '{ file_id: string }',
|
||||
params: {
|
||||
user_id: f.uint(),
|
||||
file: f.string({ allowEmpty: false }),
|
||||
name: f.string().default(''),
|
||||
upload_file: f.bool().default(true),
|
||||
},
|
||||
run: async (p, ctx) => {
|
||||
const result = await ctx.bridge.apis.groupFile.uploadPrivate(p.user_id, p.file, p.name, p.upload_file);
|
||||
return okResponse({ file_id: result.fileId });
|
||||
},
|
||||
}),
|
||||
|
||||
groupAction({
|
||||
name: 'get_group_file_url',
|
||||
summary: '获取群文件下载链接',
|
||||
returns: '{ url: string }',
|
||||
// busid: legacy `asNumber(busid) || 102` mapped absent/0/invalid → 102.
|
||||
// f.int({min:0}).default(102) keeps absent → 102, but a present 0 now
|
||||
// stays 0 and a non-numeric busid is now rejected (BAD_REQUEST) instead
|
||||
// of silently becoming 102.
|
||||
params: { file_id: f.string({ allowEmpty: false }), busid: f.int({ min: 0 }).default(102) },
|
||||
run: async (p, ctx) => {
|
||||
return okResponse({ url: await ctx.bridge.apis.groupFile.getUrl(p.group_id, p.file_id, p.busid) });
|
||||
},
|
||||
}),
|
||||
|
||||
groupAction({
|
||||
name: 'get_group_root_files',
|
||||
summary: '获取群根目录文件列表',
|
||||
run: async (p, ctx) => {
|
||||
return okResponse(await ctx.getGroupFiles(p.group_id, '/'));
|
||||
},
|
||||
}),
|
||||
|
||||
groupAction({
|
||||
name: 'get_group_files_by_folder',
|
||||
summary: '获取群子目录文件列表',
|
||||
// folder_id / folder are aliases; first non-empty wins, else '/'.
|
||||
params: { folder_id: f.string().default(''), folder: f.string().default('') },
|
||||
run: async (p, ctx) => {
|
||||
const folderId = p.folder_id || p.folder || '/';
|
||||
return okResponse(await ctx.getGroupFiles(p.group_id, folderId));
|
||||
},
|
||||
}),
|
||||
|
||||
groupAction({
|
||||
name: 'delete_group_file',
|
||||
summary: '删除群文件',
|
||||
params: { file_id: f.string({ allowEmpty: false }) },
|
||||
run: async (p, ctx) => {
|
||||
await ctx.bridge.apis.groupFile.delete(p.group_id, p.file_id);
|
||||
return okResponse();
|
||||
},
|
||||
}),
|
||||
|
||||
groupAction({
|
||||
name: 'move_group_file',
|
||||
summary: '移动群文件',
|
||||
params: {
|
||||
file_id: f.string({ allowEmpty: false }),
|
||||
parent_directory: f.string({ allowEmpty: false }),
|
||||
target_directory: f.string({ allowEmpty: false }),
|
||||
},
|
||||
run: async (p, ctx) => {
|
||||
await ctx.bridge.apis.groupFile.move(p.group_id, p.file_id, p.parent_directory, p.target_directory);
|
||||
return okResponse();
|
||||
},
|
||||
}),
|
||||
|
||||
groupAction({
|
||||
name: 'create_group_file_folder',
|
||||
summary: '创建群文件夹',
|
||||
params: { name: f.string({ allowEmpty: false }), parent_id: f.string().default('/') },
|
||||
run: async (p, ctx) => {
|
||||
await ctx.bridge.apis.groupFile.createFolder(p.group_id, p.name, p.parent_id || '/');
|
||||
return okResponse();
|
||||
},
|
||||
}),
|
||||
|
||||
groupAction({
|
||||
name: 'delete_group_file_folder',
|
||||
summary: '删除群文件夹',
|
||||
params: { folder_id: f.string({ allowEmpty: false }) },
|
||||
run: async (p, ctx) => {
|
||||
await ctx.bridge.apis.groupFile.deleteFolder(p.group_id, p.folder_id);
|
||||
return okResponse();
|
||||
},
|
||||
}),
|
||||
|
||||
groupAction({
|
||||
name: 'rename_group_file_folder',
|
||||
summary: '重命名群文件夹',
|
||||
// new_folder_name / name are aliases; first non-empty wins and must be
|
||||
// non-empty (legacy `asString(new_folder_name) || asString(name)` + `!newName`).
|
||||
params: { folder_id: f.string({ allowEmpty: false }), new_folder_name: f.string().default(''), name: f.string().default('') },
|
||||
run: async (p, ctx) => {
|
||||
const newName = p.new_folder_name || p.name;
|
||||
if (!newName) {
|
||||
return failedResponse(RETCODE.BAD_REQUEST, 'group_id, folder_id and new_folder_name are required');
|
||||
}
|
||||
await ctx.bridge.apis.groupFile.renameFolder(p.group_id, p.folder_id, newName);
|
||||
return okResponse();
|
||||
},
|
||||
}),
|
||||
|
||||
defineAction({
|
||||
name: 'get_private_file_url',
|
||||
summary: '获取私聊文件下载链接',
|
||||
returns: '{ url: string }',
|
||||
params: {
|
||||
user_id: f.uint(),
|
||||
file_id: f.string({ allowEmpty: false }),
|
||||
file_hash: f.string({ allowEmpty: false }),
|
||||
},
|
||||
run: async (p, ctx) => {
|
||||
return okResponse({ url: await ctx.bridge.apis.groupFile.getPrivateUrl(p.user_id, p.file_id, p.file_hash) });
|
||||
},
|
||||
}),
|
||||
];
|
||||
|
||||
export function register(h: ApiHandler, ctx: ApiActionContext): void {
|
||||
h.registerAction('upload_group_file', async (params) => {
|
||||
const groupId = asNumber(params.group_id);
|
||||
const file = asString(params.file);
|
||||
const name = asString(params.name);
|
||||
const folderId = asString(params.folder) || asString(params.folder_id) || '/';
|
||||
const uploadFile = asBoolean(params.upload_file, true);
|
||||
if (!groupId || !file) return failedResponse(RETCODE.BAD_REQUEST, 'group_id and file are required');
|
||||
const result = await ctx.bridge.apis.groupFile.upload(groupId, file, name, folderId, uploadFile);
|
||||
return okResponse({ file_id: result.fileId });
|
||||
});
|
||||
|
||||
h.registerAction('upload_private_file', async (params) => {
|
||||
const userId = asNumber(params.user_id);
|
||||
const file = asString(params.file);
|
||||
const name = asString(params.name);
|
||||
const uploadFile = asBoolean(params.upload_file, true);
|
||||
if (!userId || !file) return failedResponse(RETCODE.BAD_REQUEST, 'user_id and file are required');
|
||||
const result = await ctx.bridge.apis.groupFile.uploadPrivate(userId, file, name, uploadFile);
|
||||
return okResponse({ file_id: result.fileId });
|
||||
});
|
||||
|
||||
h.registerAction('get_group_file_url', async (params) => {
|
||||
const groupId = asNumber(params.group_id);
|
||||
const fileId = asString(params.file_id);
|
||||
const busId = asNumber(params.busid) || 102;
|
||||
if (!groupId || !fileId) {
|
||||
return failedResponse(RETCODE.BAD_REQUEST, 'group_id and file_id are required');
|
||||
}
|
||||
return okResponse({ url: await ctx.bridge.apis.groupFile.getUrl(groupId, fileId, busId) });
|
||||
});
|
||||
|
||||
h.registerAction('get_group_root_files', async (params) => {
|
||||
const groupId = asNumber(params.group_id);
|
||||
if (!groupId) {
|
||||
return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
|
||||
}
|
||||
return okResponse(await ctx.getGroupFiles(groupId, '/'));
|
||||
});
|
||||
|
||||
h.registerAction('get_group_files_by_folder', async (params) => {
|
||||
const groupId = asNumber(params.group_id);
|
||||
const folderId = asString(params.folder_id) || asString(params.folder) || '/';
|
||||
if (!groupId) {
|
||||
return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
|
||||
}
|
||||
return okResponse(await ctx.getGroupFiles(groupId, folderId));
|
||||
});
|
||||
|
||||
h.registerAction('delete_group_file', async (params) => {
|
||||
const groupId = asNumber(params.group_id);
|
||||
const fileId = asString(params.file_id);
|
||||
if (!groupId || !fileId) {
|
||||
return failedResponse(RETCODE.BAD_REQUEST, 'group_id and file_id are required');
|
||||
}
|
||||
await ctx.bridge.apis.groupFile.delete(groupId, fileId);
|
||||
return okResponse();
|
||||
});
|
||||
|
||||
h.registerAction('move_group_file', async (params) => {
|
||||
const groupId = asNumber(params.group_id);
|
||||
const fileId = asString(params.file_id);
|
||||
const parentDirectory = asString(params.parent_directory);
|
||||
const targetDirectory = asString(params.target_directory);
|
||||
if (!groupId || !fileId || !parentDirectory || !targetDirectory) {
|
||||
return failedResponse(RETCODE.BAD_REQUEST, 'group_id, file_id, parent_directory and target_directory are required');
|
||||
}
|
||||
await ctx.bridge.apis.groupFile.move(groupId, fileId, parentDirectory, targetDirectory);
|
||||
return okResponse();
|
||||
});
|
||||
|
||||
h.registerAction('create_group_file_folder', async (params) => {
|
||||
const groupId = asNumber(params.group_id);
|
||||
const name = asString(params.name);
|
||||
const parentId = asString(params.parent_id) || '/';
|
||||
if (!groupId || !name) {
|
||||
return failedResponse(RETCODE.BAD_REQUEST, 'group_id and name are required');
|
||||
}
|
||||
await ctx.bridge.apis.groupFile.createFolder(groupId, name, parentId);
|
||||
return okResponse();
|
||||
});
|
||||
|
||||
h.registerAction('delete_group_file_folder', async (params) => {
|
||||
const groupId = asNumber(params.group_id);
|
||||
const folderId = asString(params.folder_id);
|
||||
if (!groupId || !folderId) {
|
||||
return failedResponse(RETCODE.BAD_REQUEST, 'group_id and folder_id are required');
|
||||
}
|
||||
await ctx.bridge.apis.groupFile.deleteFolder(groupId, folderId);
|
||||
return okResponse();
|
||||
});
|
||||
|
||||
h.registerAction('rename_group_file_folder', async (params) => {
|
||||
const groupId = asNumber(params.group_id);
|
||||
const folderId = asString(params.folder_id);
|
||||
const newName = asString(params.new_folder_name) || asString(params.name);
|
||||
if (!groupId || !folderId || !newName) {
|
||||
return failedResponse(RETCODE.BAD_REQUEST, 'group_id, folder_id and new_folder_name are required');
|
||||
}
|
||||
await ctx.bridge.apis.groupFile.renameFolder(groupId, folderId, newName);
|
||||
return okResponse();
|
||||
});
|
||||
|
||||
h.registerAction('get_private_file_url', async (params) => {
|
||||
const userId = asNumber(params.user_id);
|
||||
const fileId = asString(params.file_id);
|
||||
const fileHash = asString(params.file_hash);
|
||||
if (!userId || !fileId || !fileHash) {
|
||||
return failedResponse(RETCODE.BAD_REQUEST, 'user_id, file_id and file_hash are required');
|
||||
}
|
||||
return okResponse({ url: await ctx.bridge.apis.groupFile.getPrivateUrl(userId, fileId, fileHash) });
|
||||
});
|
||||
registerActions(h, ctx, actions);
|
||||
}
|
||||
@@ -1,84 +1,114 @@
|
||||
import { defineAction, groupAction, groupUserAction, registerActions, f } from '../action-kit';
|
||||
import type { ApiHandler, ApiActionContext } from '../api-handler';
|
||||
import { asNumber, asBoolean, asString } from '../api-handler';
|
||||
import { asString } from '../api-handler';
|
||||
import { RETCODE, failedResponse, okResponse } from '../types';
|
||||
import { WebHonorType } from '@snowluma/protocol/web/group-honor';
|
||||
|
||||
export function register(h: ApiHandler, ctx: ApiActionContext): void {
|
||||
h.registerAction('get_group_list', async (params) => {
|
||||
const noCache = asBoolean(params.no_cache, false);
|
||||
if (ctx.getGroupList) {
|
||||
return okResponse(await ctx.getGroupList(noCache));
|
||||
}
|
||||
return okResponse([]);
|
||||
});
|
||||
export const actions = [
|
||||
defineAction({
|
||||
name: 'get_group_list',
|
||||
summary: '获取群列表',
|
||||
params: { no_cache: f.bool().default(false) },
|
||||
run: async (p, ctx) => {
|
||||
const noCache = p.no_cache;
|
||||
if (ctx.getGroupList) {
|
||||
return okResponse(await ctx.getGroupList(noCache));
|
||||
}
|
||||
return okResponse([]);
|
||||
},
|
||||
}),
|
||||
|
||||
h.registerAction('get_group_info', async (params) => {
|
||||
const groupId = asNumber(params.group_id);
|
||||
if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
|
||||
const noCache = asBoolean(params.no_cache, false);
|
||||
if (ctx.getGroupInfo) {
|
||||
const info = await ctx.getGroupInfo(groupId, noCache);
|
||||
return okResponse(info ?? { group_id: groupId, group_name: '', member_count: 0, max_member_count: 0 });
|
||||
}
|
||||
return okResponse({ group_id: groupId, group_name: '', member_count: 0, max_member_count: 0 });
|
||||
});
|
||||
groupAction({
|
||||
name: 'get_group_info',
|
||||
summary: '获取群信息',
|
||||
params: { no_cache: f.bool().default(false) },
|
||||
run: async (p, ctx) => {
|
||||
const groupId = p.group_id;
|
||||
const noCache = p.no_cache;
|
||||
if (ctx.getGroupInfo) {
|
||||
const info = await ctx.getGroupInfo(groupId, noCache);
|
||||
return okResponse(info ?? { group_id: groupId, group_name: '', member_count: 0, max_member_count: 0 });
|
||||
}
|
||||
return okResponse({ group_id: groupId, group_name: '', member_count: 0, max_member_count: 0 });
|
||||
},
|
||||
}),
|
||||
|
||||
h.registerAction('get_group_member_list', async (params) => {
|
||||
const groupId = asNumber(params.group_id);
|
||||
if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
|
||||
const noCache = asBoolean(params.no_cache, false);
|
||||
if (ctx.getGroupMemberList) {
|
||||
return okResponse(await ctx.getGroupMemberList(groupId, noCache));
|
||||
}
|
||||
return okResponse([]);
|
||||
});
|
||||
groupAction({
|
||||
name: 'get_group_member_list',
|
||||
summary: '获取群成员列表',
|
||||
params: { no_cache: f.bool().default(false) },
|
||||
run: async (p, ctx) => {
|
||||
const groupId = p.group_id;
|
||||
const noCache = p.no_cache;
|
||||
if (ctx.getGroupMemberList) {
|
||||
return okResponse(await ctx.getGroupMemberList(groupId, noCache));
|
||||
}
|
||||
return okResponse([]);
|
||||
},
|
||||
}),
|
||||
|
||||
h.registerAction('get_group_member_info', async (params) => {
|
||||
const groupId = asNumber(params.group_id);
|
||||
const userId = asNumber(params.user_id);
|
||||
if (!groupId || !userId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id and user_id are required');
|
||||
const noCache = asBoolean(params.no_cache, false);
|
||||
if (ctx.getGroupMemberInfo) {
|
||||
const info = await ctx.getGroupMemberInfo(groupId, userId, noCache);
|
||||
return okResponse(info ?? {
|
||||
groupUserAction({
|
||||
name: 'get_group_member_info',
|
||||
summary: '获取群成员信息',
|
||||
params: { no_cache: f.bool().default(false) },
|
||||
run: async (p, ctx) => {
|
||||
const groupId = p.group_id;
|
||||
const userId = p.user_id;
|
||||
const noCache = p.no_cache;
|
||||
if (ctx.getGroupMemberInfo) {
|
||||
const info = await ctx.getGroupMemberInfo(groupId, userId, noCache);
|
||||
return okResponse(info ?? {
|
||||
group_id: groupId, user_id: userId, nickname: '', card: '',
|
||||
sex: 'unknown', age: 0, join_time: 0, last_sent_time: 0,
|
||||
level: '0', role: 'member', title: '',
|
||||
});
|
||||
}
|
||||
return okResponse({
|
||||
group_id: groupId, user_id: userId, nickname: '', card: '',
|
||||
sex: 'unknown', age: 0, join_time: 0, last_sent_time: 0,
|
||||
level: '0', role: 'member', title: '',
|
||||
});
|
||||
}
|
||||
return okResponse({
|
||||
group_id: groupId, user_id: userId, nickname: '', card: '',
|
||||
sex: 'unknown', age: 0, join_time: 0, last_sent_time: 0,
|
||||
level: '0', role: 'member', title: '',
|
||||
});
|
||||
});
|
||||
},
|
||||
}),
|
||||
|
||||
h.registerAction('get_group_honor_info', async (params) => {
|
||||
const groupId = asNumber(params.group_id);
|
||||
const typeStr = asString(params.type) || 'all';
|
||||
// `type` keeps the legacy `asString(x) || 'all'` semantics (absent / non-string
|
||||
// / empty-string all collapse to 'all'), which a typed string field can't
|
||||
// replicate exactly — so it stays a raw param coerced in run().
|
||||
groupAction({
|
||||
name: 'get_group_honor_info',
|
||||
summary: '获取群荣誉信息',
|
||||
params: { type: f.raw() },
|
||||
run: async (p, ctx) => {
|
||||
const groupId = p.group_id;
|
||||
const typeStr = asString(p.type) || 'all';
|
||||
|
||||
if (!groupId) {
|
||||
return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
|
||||
}
|
||||
const typeValues = Object.values(WebHonorType) as string[];
|
||||
if (!typeValues.includes(typeStr)) {
|
||||
return failedResponse(RETCODE.BAD_REQUEST, `invalid type, must be one of ${typeValues.join(', ')}`);
|
||||
}
|
||||
|
||||
try {
|
||||
const honorInfo = await ctx.bridge.apis.web.getHonorInfo(groupId, typeStr as WebHonorType);
|
||||
return okResponse(honorInfo);
|
||||
} catch (e) {
|
||||
return failedResponse(RETCODE.ACTION_FAILED, `failed to get group honor info: ${(e as Error).message}`);
|
||||
}
|
||||
},
|
||||
}),
|
||||
|
||||
const typeValues = Object.values(WebHonorType) as string[];
|
||||
if (!typeValues.includes(typeStr)) {
|
||||
return failedResponse(RETCODE.BAD_REQUEST, `invalid type, must be one of ${typeValues.join(', ')}`);
|
||||
}
|
||||
defineAction({
|
||||
name: 'get_group_system_msg',
|
||||
summary: '获取群系统消息',
|
||||
params: {},
|
||||
run: async (_p, ctx) => {
|
||||
if (ctx.handleGetGroupSystemMsg) {
|
||||
return okResponse(await ctx.handleGetGroupSystemMsg());
|
||||
}
|
||||
return okResponse([]);
|
||||
},
|
||||
}),
|
||||
];
|
||||
|
||||
try {
|
||||
const honorInfo = await ctx.bridge.apis.web.getHonorInfo(groupId, typeStr as WebHonorType);
|
||||
return okResponse(honorInfo);
|
||||
} catch (e) {
|
||||
return failedResponse(RETCODE.ACTION_FAILED, `failed to get group honor info: ${(e as Error).message}`);
|
||||
}
|
||||
});
|
||||
|
||||
h.registerAction('get_group_system_msg', async () => {
|
||||
if (ctx.handleGetGroupSystemMsg) {
|
||||
return okResponse(await ctx.handleGetGroupSystemMsg());
|
||||
}
|
||||
return okResponse([]);
|
||||
});
|
||||
export function register(h: ApiHandler, ctx: ApiActionContext): void {
|
||||
registerActions(h, ctx, actions);
|
||||
}
|
||||
@@ -1,32 +1,58 @@
|
||||
import { defineAction, registerActions } from '../action-kit';
|
||||
import type { ApiActionContext, ApiHandler } from '../api-handler';
|
||||
import { okResponse } from '../types';
|
||||
|
||||
// 后续考虑移动到一个统一的地方构建,避免版本信息分散在各个模块中。
|
||||
const appVersion = typeof __APP_VERSION__ !== 'undefined' ? __APP_VERSION__ : 'dev';
|
||||
|
||||
export const actions = [
|
||||
defineAction({
|
||||
name: 'get_login_info',
|
||||
params: {},
|
||||
run: (_p, ctx) => {
|
||||
const login = ctx.getLoginInfo();
|
||||
return okResponse({ user_id: login.userId, nickname: login.nickname });
|
||||
},
|
||||
}),
|
||||
|
||||
defineAction({
|
||||
name: 'get_status',
|
||||
params: {},
|
||||
run: (_p, ctx) => {
|
||||
const online = ctx.isOnline();
|
||||
return okResponse({ online, good: online });
|
||||
},
|
||||
}),
|
||||
|
||||
defineAction({
|
||||
name: 'get_version_info',
|
||||
params: {},
|
||||
run: () => {
|
||||
return okResponse({
|
||||
app_name: 'SnowLuma',
|
||||
app_version: `${appVersion}-node`,
|
||||
protocol_version: 'v11',
|
||||
});
|
||||
},
|
||||
}),
|
||||
|
||||
defineAction({
|
||||
name: 'can_send_image',
|
||||
params: {},
|
||||
run: (_p, ctx) => {
|
||||
return okResponse({ yes: ctx.canSendImage?.() ?? false });
|
||||
},
|
||||
}),
|
||||
|
||||
defineAction({
|
||||
name: 'can_send_record',
|
||||
params: {},
|
||||
run: (_p, ctx) => {
|
||||
return okResponse({ yes: ctx.canSendRecord?.() ?? false });
|
||||
},
|
||||
}),
|
||||
];
|
||||
|
||||
export function register(h: ApiHandler, ctx: ApiActionContext): void {
|
||||
h.registerAction('get_login_info', async () => {
|
||||
const login = ctx.getLoginInfo();
|
||||
return okResponse({ user_id: login.userId, nickname: login.nickname });
|
||||
});
|
||||
|
||||
h.registerAction('get_status', async () => {
|
||||
const online = ctx.isOnline();
|
||||
return okResponse({ online, good: online });
|
||||
});
|
||||
|
||||
// 后续考虑移动到一个统一的地方构建,避免版本信息分散在各个模块中。
|
||||
const appVersion = typeof __APP_VERSION__ !== 'undefined' ? __APP_VERSION__ : 'dev';
|
||||
h.registerAction('get_version_info', async () => {
|
||||
return okResponse({
|
||||
app_name: 'SnowLuma',
|
||||
app_version: `${appVersion}-node`,
|
||||
protocol_version: 'v11',
|
||||
});
|
||||
});
|
||||
|
||||
h.registerAction('can_send_image', async () => {
|
||||
return okResponse({ yes: ctx.canSendImage?.() ?? false });
|
||||
});
|
||||
|
||||
h.registerAction('can_send_record', async () => {
|
||||
return okResponse({ yes: ctx.canSendRecord?.() ?? false });
|
||||
});
|
||||
registerActions(h, ctx, actions);
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
import type { JsonObject, JsonValue } from '../types';
|
||||
import type { ApiHandler, ApiActionContext } from '../api-handler';
|
||||
import { asNumber, asString, asBoolean, asMessage } from '../api-handler';
|
||||
import { defineAction, groupAction, registerActions, f } from '../action-kit';
|
||||
import { RETCODE, failedResponse, okResponse } from '../types';
|
||||
|
||||
/**
|
||||
@@ -32,96 +32,85 @@ async function refreshStoredImageUrls(event: JsonObject, ctx: ApiActionContext):
|
||||
}
|
||||
}
|
||||
|
||||
export function register(h: ApiHandler, ctx: ApiActionContext): void {
|
||||
h.registerAction('send_msg', async (params) => {
|
||||
const messageType = asString(params.message_type);
|
||||
const message = asMessage(params.message);
|
||||
const autoEscape = asBoolean(params.auto_escape, false);
|
||||
|
||||
if (message === undefined) {
|
||||
return failedResponse(RETCODE.BAD_REQUEST, 'message is required');
|
||||
}
|
||||
|
||||
if (messageType === 'group' || params.group_id !== undefined) {
|
||||
const groupId = asNumber(params.group_id);
|
||||
if (!Number.isInteger(groupId) || groupId <= 0) {
|
||||
return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
|
||||
export const actions = [
|
||||
// send_msg routes on message_type / group_id presence, so the *required*
|
||||
// id is conditional — that branch stays in run(). The fields themselves
|
||||
// (message required; group_id/user_id valid uints when present) are
|
||||
// validated by the spec; message_type is left lenient for parity.
|
||||
defineAction({
|
||||
name: 'send_msg',
|
||||
summary: '发送消息(按 message_type/群号 自动路由群聊或私聊)',
|
||||
returns: '{ message_id: number }',
|
||||
params: {
|
||||
message: f.message(),
|
||||
message_type: f.string().optional(),
|
||||
group_id: f.uint().optional(),
|
||||
user_id: f.uint().optional(),
|
||||
auto_escape: f.bool().default(false),
|
||||
},
|
||||
run: async (p, ctx) => {
|
||||
if (p.message_type === 'group' || p.group_id !== undefined) {
|
||||
if (p.group_id === undefined) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
|
||||
const result = await ctx.sendGroupMessage(p.group_id, p.message, p.auto_escape);
|
||||
return okResponse({ message_id: result.messageId });
|
||||
}
|
||||
const result = await ctx.sendGroupMessage(groupId, message, autoEscape);
|
||||
if (p.user_id === undefined) return failedResponse(RETCODE.BAD_REQUEST, 'user_id is required');
|
||||
const result = await ctx.sendPrivateMessage(p.user_id, p.message, p.auto_escape);
|
||||
return okResponse({ message_id: result.messageId });
|
||||
}
|
||||
},
|
||||
}),
|
||||
|
||||
const userId = asNumber(params.user_id);
|
||||
if (!Number.isInteger(userId) || userId <= 0) {
|
||||
return failedResponse(RETCODE.BAD_REQUEST, 'user_id is required');
|
||||
}
|
||||
const result = await ctx.sendPrivateMessage(userId, message, autoEscape);
|
||||
return okResponse({ message_id: result.messageId });
|
||||
});
|
||||
defineAction({
|
||||
name: 'send_private_msg',
|
||||
summary: '发送私聊消息',
|
||||
returns: '{ message_id: number }',
|
||||
params: { user_id: f.uint(), message: f.message(), auto_escape: f.bool().default(false) },
|
||||
run: async (p, ctx) => {
|
||||
const result = await ctx.sendPrivateMessage(p.user_id, p.message, p.auto_escape);
|
||||
return okResponse({ message_id: result.messageId });
|
||||
},
|
||||
}),
|
||||
|
||||
h.registerAction('send_private_msg', async (params) => {
|
||||
const userId = asNumber(params.user_id);
|
||||
const message = asMessage(params.message);
|
||||
const autoEscape = asBoolean(params.auto_escape, false);
|
||||
groupAction({
|
||||
name: 'send_group_msg',
|
||||
summary: '发送群消息',
|
||||
returns: '{ message_id: number }',
|
||||
params: { message: f.message(), auto_escape: f.bool().default(false) },
|
||||
run: async (p, ctx) => {
|
||||
const result = await ctx.sendGroupMessage(p.group_id, p.message, p.auto_escape);
|
||||
return okResponse({ message_id: result.messageId });
|
||||
},
|
||||
}),
|
||||
|
||||
if (!Number.isInteger(userId) || userId <= 0) {
|
||||
return failedResponse(RETCODE.BAD_REQUEST, 'user_id is required');
|
||||
}
|
||||
if (message === undefined) {
|
||||
return failedResponse(RETCODE.BAD_REQUEST, 'message is required');
|
||||
}
|
||||
defineAction({
|
||||
name: 'get_msg',
|
||||
summary: '获取消息',
|
||||
params: { message_id: f.messageId() },
|
||||
run: async (p, ctx) => {
|
||||
const data = ctx.getMessage(p.message_id);
|
||||
if (!data) return failedResponse(RETCODE.ACTION_FAILED, 'message not found');
|
||||
const result: JsonObject = { ...data };
|
||||
delete result.post_type;
|
||||
delete result.self_id;
|
||||
result.real_id = (result.message_id ?? p.message_id) as JsonValue;
|
||||
await refreshStoredImageUrls(result, ctx);
|
||||
return okResponse(result);
|
||||
},
|
||||
}),
|
||||
|
||||
const result = await ctx.sendPrivateMessage(userId, message, autoEscape);
|
||||
return okResponse({ message_id: result.messageId });
|
||||
});
|
||||
defineAction({
|
||||
name: 'delete_msg',
|
||||
summary: '撤回消息',
|
||||
params: { message_id: f.messageId() },
|
||||
run: async (p, ctx) => {
|
||||
const meta = ctx.getMessageMeta(p.message_id);
|
||||
if (!meta) return failedResponse(RETCODE.ACTION_FAILED, 'message not found or not retractable');
|
||||
await ctx.deleteMessage(p.message_id, meta);
|
||||
return okResponse();
|
||||
},
|
||||
}),
|
||||
];
|
||||
|
||||
h.registerAction('send_group_msg', async (params) => {
|
||||
const groupId = asNumber(params.group_id);
|
||||
const message = asMessage(params.message);
|
||||
const autoEscape = asBoolean(params.auto_escape, false);
|
||||
|
||||
if (!Number.isInteger(groupId) || groupId <= 0) {
|
||||
return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
|
||||
}
|
||||
if (message === undefined) {
|
||||
return failedResponse(RETCODE.BAD_REQUEST, 'message is required');
|
||||
}
|
||||
|
||||
const result = await ctx.sendGroupMessage(groupId, message, autoEscape);
|
||||
return okResponse({ message_id: result.messageId });
|
||||
});
|
||||
|
||||
h.registerAction('get_msg', async (params) => {
|
||||
const messageId = asNumber(params.message_id);
|
||||
if (!Number.isInteger(messageId) || messageId === 0) {
|
||||
return failedResponse(RETCODE.BAD_REQUEST, 'message_id is required');
|
||||
}
|
||||
|
||||
const data = ctx.getMessage(messageId);
|
||||
if (!data) {
|
||||
return failedResponse(RETCODE.ACTION_FAILED, 'message not found');
|
||||
}
|
||||
|
||||
const result: JsonObject = { ...data };
|
||||
delete result.post_type;
|
||||
delete result.self_id;
|
||||
result.real_id = (result.message_id ?? messageId) as JsonValue;
|
||||
await refreshStoredImageUrls(result, ctx);
|
||||
return okResponse(result);
|
||||
});
|
||||
|
||||
h.registerAction('delete_msg', async (params) => {
|
||||
const messageId = asNumber(params.message_id);
|
||||
if (!Number.isInteger(messageId) || messageId === 0) {
|
||||
return failedResponse(RETCODE.BAD_REQUEST, 'message_id is required');
|
||||
}
|
||||
|
||||
const meta = ctx.getMessageMeta(messageId);
|
||||
if (!meta) {
|
||||
return failedResponse(RETCODE.ACTION_FAILED, 'message not found or not retractable');
|
||||
}
|
||||
|
||||
await ctx.deleteMessage(messageId, meta);
|
||||
return okResponse();
|
||||
});
|
||||
export function register(h: ApiHandler, ctx: ApiActionContext): void {
|
||||
registerActions(h, ctx, actions);
|
||||
}
|
||||
@@ -1,23 +1,42 @@
|
||||
import type { ApiHandler, ApiActionContext } from '../api-handler';
|
||||
import { asString, asBoolean } from '../api-handler';
|
||||
import { RETCODE, failedResponse, okResponse } from '../types';
|
||||
import { defineAction, registerActions, f } from '../action-kit';
|
||||
import type { ApiActionContext, ApiHandler } from '../api-handler';
|
||||
import { asString } from '../api-handler';
|
||||
import { okResponse } from '../types';
|
||||
|
||||
export const actions = [
|
||||
defineAction({
|
||||
name: 'set_friend_add_request',
|
||||
summary: '处理好友添加请求',
|
||||
params: {
|
||||
flag: f.string({ allowEmpty: false }),
|
||||
approve: f.bool().default(true),
|
||||
},
|
||||
run: async (p, ctx) => {
|
||||
await ctx.bridge.apis.friend.handleRequest(p.flag, p.approve);
|
||||
return okResponse();
|
||||
},
|
||||
}),
|
||||
|
||||
defineAction({
|
||||
name: 'set_group_add_request',
|
||||
summary: '处理加群请求',
|
||||
params: {
|
||||
flag: f.string({ allowEmpty: false }),
|
||||
// sub_type/type pass through with a nested fallback (sub_type → type → 'add');
|
||||
// kept raw so the original asString resolution is preserved verbatim.
|
||||
sub_type: f.raw(),
|
||||
type: f.raw(),
|
||||
approve: f.bool().default(true),
|
||||
reason: f.string().default(''),
|
||||
},
|
||||
run: async (p, ctx) => {
|
||||
const subType = asString(p.sub_type, asString(p.type, 'add'));
|
||||
await ctx.handleGroupRequest(p.flag, subType, p.approve, p.reason);
|
||||
return okResponse();
|
||||
},
|
||||
}),
|
||||
];
|
||||
|
||||
export function register(h: ApiHandler, ctx: ApiActionContext): void {
|
||||
h.registerAction('set_friend_add_request', async (params) => {
|
||||
const flag = asString(params.flag);
|
||||
const approve = asBoolean(params.approve, true);
|
||||
if (!flag) return failedResponse(RETCODE.BAD_REQUEST, 'flag is required');
|
||||
await ctx.bridge.apis.friend.handleRequest(flag, approve);
|
||||
return okResponse();
|
||||
});
|
||||
|
||||
h.registerAction('set_group_add_request', async (params) => {
|
||||
const flag = asString(params.flag);
|
||||
const subType = asString(params.sub_type, asString(params.type, 'add'));
|
||||
const approve = asBoolean(params.approve, true);
|
||||
const reason = asString(params.reason);
|
||||
if (!flag) return failedResponse(RETCODE.BAD_REQUEST, 'flag is required');
|
||||
await ctx.handleGroupRequest(flag, subType, approve, reason);
|
||||
return okResponse();
|
||||
});
|
||||
registerActions(h, ctx, actions);
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
// Tests the self-generated docs (D4): the describe()-walker aggregates every
|
||||
// declarative action and renders coherent metadata/markdown.
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { collectActionDocs, renderActionDocsMarkdown } from '../src/action-docs';
|
||||
|
||||
describe('action-docs', () => {
|
||||
const docs = collectActionDocs();
|
||||
|
||||
it('covers the migrated declarative actions with unique names', () => {
|
||||
expect(docs.length).toBeGreaterThanOrEqual(120);
|
||||
const names = docs.map((d) => d.name);
|
||||
expect(new Set(names).size).toBe(names.length); // no duplicates
|
||||
});
|
||||
|
||||
it('surfaces preset-injected fields + defaults (set_group_ban)', () => {
|
||||
const ban = docs.find((d) => d.name === 'set_group_ban');
|
||||
expect(ban).toBeDefined();
|
||||
expect(ban!.params.map((p) => p.name)).toEqual(['group_id', 'user_id', 'duration']);
|
||||
const groupId = ban!.params.find((p) => p.name === 'group_id')!;
|
||||
expect(groupId).toMatchObject({ type: 'uint', required: true });
|
||||
const duration = ban!.params.find((p) => p.name === 'duration')!;
|
||||
expect(duration).toMatchObject({ type: 'int', required: false, default: 1800 });
|
||||
});
|
||||
|
||||
it('renders markdown with header + an action section', () => {
|
||||
const md = renderActionDocsMarkdown(docs);
|
||||
expect(md).toContain('# OneBot Actions');
|
||||
expect(md).toContain('`set_group_ban`');
|
||||
expect(md).toContain('| 参数 | 类型 | 必填 | 默认 | 说明 |');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,184 @@
|
||||
// Interface tests for action-kit — the deepened param-validation module.
|
||||
// The interface IS the test surface: we drive `parse()` (pure, no ctx) for
|
||||
// coercion/validation/cross-field, `describe()` for doc metadata, and
|
||||
// `toHandler()` for the BAD_REQUEST shaping + ctx threading.
|
||||
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { f, defineAction, groupUserAction, type CoerceResult } from '../src/action-kit';
|
||||
import type { ApiActionContext } from '../src/api-handler';
|
||||
import { RETCODE, okResponse } from '../src/types';
|
||||
|
||||
const ctx = {} as unknown as ApiActionContext;
|
||||
|
||||
function expectErr<T>(r: CoerceResult<T>): { field: string; reason: string } {
|
||||
if (r.ok) throw new Error(`expected Err, got Ok(${JSON.stringify(r.value)})`);
|
||||
return { field: r.field, reason: r.reason };
|
||||
}
|
||||
function expectOk<T>(r: CoerceResult<T>): T {
|
||||
if (!r.ok) throw new Error(`expected Ok, got Err(${r.field}: ${r.reason})`);
|
||||
return r.value;
|
||||
}
|
||||
|
||||
describe('f.uint — positive integer, missing≠0', () => {
|
||||
const spec = defineAction({ name: 't', params: { x: f.uint() }, run: () => okResponse() });
|
||||
it('accepts number and numeric string, truncates', () => {
|
||||
expect(expectOk(spec.parse({ x: 123 }))).toEqual({ x: 123 });
|
||||
expect(expectOk(spec.parse({ x: '456' }))).toEqual({ x: 456 });
|
||||
expect(expectOk(spec.parse({ x: 5.7 }))).toEqual({ x: 5 });
|
||||
});
|
||||
it('rejects missing / 0 / negative / garbage, naming the field', () => {
|
||||
expect(expectErr(spec.parse({})).field).toBe('x');
|
||||
expect(expectErr(spec.parse({})).reason).toBe('is required');
|
||||
expect(expectErr(spec.parse({ x: 0 })).field).toBe('x'); // 0 is not a valid id
|
||||
expect(expectErr(spec.parse({ x: -3 })).field).toBe('x');
|
||||
expect(expectErr(spec.parse({ x: 'abc' })).field).toBe('x');
|
||||
});
|
||||
});
|
||||
|
||||
describe('f.int({min:0}).default — the duration / unmute fix', () => {
|
||||
const spec = defineAction({ name: 't', params: { d: f.int({ min: 0 }).default(1800) }, run: () => okResponse() });
|
||||
it('missing ⇒ default; present 0 ⇒ 0 (not the default); negative ⇒ err', () => {
|
||||
expect(expectOk(spec.parse({}))).toEqual({ d: 1800 });
|
||||
expect(expectOk(spec.parse({ d: 0 }))).toEqual({ d: 0 }); // the bug the old `|| 1800` had
|
||||
expect(expectErr(spec.parse({ d: -1 })).field).toBe('d');
|
||||
});
|
||||
it('present garbage is an error, not a silent fallback', () => {
|
||||
expect(expectErr(spec.parse({ d: 'abc' })).field).toBe('d');
|
||||
});
|
||||
});
|
||||
|
||||
describe('f.messageId — non-zero integer, negatives allowed', () => {
|
||||
const spec = defineAction({ name: 't', params: { id: f.messageId() }, run: () => okResponse() });
|
||||
it('accepts negative ids (signed int32 hash), rejects 0 and garbage', () => {
|
||||
expect(expectOk(spec.parse({ id: -2147483648 }))).toEqual({ id: -2147483648 });
|
||||
expect(expectOk(spec.parse({ id: 123 }))).toEqual({ id: 123 });
|
||||
expect(expectErr(spec.parse({ id: 0 })).reason).toBe('must not be 0');
|
||||
expect(expectErr(spec.parse({ id: 'x' })).field).toBe('id');
|
||||
});
|
||||
});
|
||||
|
||||
describe('f.bool / f.string / f.enum', () => {
|
||||
it('bool synonyms', () => {
|
||||
const s = defineAction({ name: 't', params: { b: f.bool() }, run: () => okResponse() });
|
||||
expect(expectOk(s.parse({ b: 'on' }))).toEqual({ b: true });
|
||||
expect(expectOk(s.parse({ b: 0 }))).toEqual({ b: false });
|
||||
expect(expectErr(s.parse({ b: 'maybe' })).field).toBe('b');
|
||||
});
|
||||
it('string allowEmpty toggle', () => {
|
||||
const s = defineAction({ name: 't', params: { c: f.string({ allowEmpty: false }) }, run: () => okResponse() });
|
||||
expect(expectErr(s.parse({ c: '' })).field).toBe('c');
|
||||
expect(expectOk(s.parse({ c: 'x' }))).toEqual({ c: 'x' });
|
||||
});
|
||||
it('enum literal set', () => {
|
||||
const s = defineAction({ name: 't', params: { e: f.enum('a', 'b') }, run: () => okResponse() });
|
||||
expect(expectOk(s.parse({ e: 'a' }))).toEqual({ e: 'a' });
|
||||
expect(expectErr(s.parse({ e: 'c' })).field).toBe('e');
|
||||
});
|
||||
});
|
||||
|
||||
describe('f.array(...).nonEmpty — per-element + non-empty', () => {
|
||||
const spec = defineAction({ name: 't', params: { ids: f.array(f.uint()).nonEmpty() }, run: () => okResponse() });
|
||||
it('accepts a non-empty uint array', () => {
|
||||
expect(expectOk(spec.parse({ ids: [1, 2, 3] }))).toEqual({ ids: [1, 2, 3] });
|
||||
});
|
||||
it('rejects empty and names the bad element index', () => {
|
||||
expect(expectErr(spec.parse({ ids: [] })).field).toBe('ids');
|
||||
expect(expectErr(spec.parse({ ids: [1, 'x'] })).field).toBe('ids[1]');
|
||||
});
|
||||
});
|
||||
|
||||
describe('f.message — union passthrough + JSON-array string', () => {
|
||||
const spec = defineAction({ name: 't', params: { m: f.message() }, run: () => okResponse() });
|
||||
it('parses a JSON-array string, passes plain string / array through', () => {
|
||||
expect(expectOk(spec.parse({ m: '[{"type":"text","data":{"text":"hi"}}]' })).m).toEqual([
|
||||
{ type: 'text', data: { text: 'hi' } },
|
||||
]);
|
||||
expect(expectOk(spec.parse({ m: 'hello' })).m).toBe('hello');
|
||||
expect(expectOk(spec.parse({ m: [{ type: 'face' }] })).m).toEqual([{ type: 'face' }]);
|
||||
});
|
||||
it('required when missing', () => {
|
||||
expect(expectErr(spec.parse({})).reason).toBe('is required');
|
||||
});
|
||||
});
|
||||
|
||||
describe('optional fields', () => {
|
||||
const spec = defineAction({ name: 't', params: { x: f.uint().optional() }, run: () => okResponse() });
|
||||
it('missing ⇒ undefined value, present-invalid ⇒ err', () => {
|
||||
expect(expectOk(spec.parse({}))).toEqual({ x: undefined });
|
||||
expect(expectErr(spec.parse({ x: 'abc' })).field).toBe('x');
|
||||
});
|
||||
});
|
||||
|
||||
describe('cross-field rules', () => {
|
||||
const spec = defineAction({
|
||||
name: 'set_msg_emoji_like',
|
||||
params: {
|
||||
message_id: f.uint().optional(),
|
||||
group_id: f.uint().optional(),
|
||||
user_id: f.uint().optional(),
|
||||
emoji_id: f.uint(),
|
||||
},
|
||||
rules: (r) => [r.exactlyOneOf('message_id', ['group_id', 'user_id'])],
|
||||
run: () => okResponse(),
|
||||
});
|
||||
it('passes when exactly one locator group present', () => {
|
||||
expect(spec.parse({ message_id: 5, emoji_id: 1 }).ok).toBe(true);
|
||||
expect(spec.parse({ group_id: 9, user_id: 8, emoji_id: 1 }).ok).toBe(true);
|
||||
});
|
||||
it('fails when zero or both groups present', () => {
|
||||
expect(expectErr(spec.parse({ emoji_id: 1 })).reason).toContain('exactly one of');
|
||||
expect(expectErr(spec.parse({ message_id: 5, group_id: 9, user_id: 8, emoji_id: 1 })).reason).toContain('exactly one of');
|
||||
});
|
||||
it('field errors take priority over rule errors (per-field first)', () => {
|
||||
expect(expectErr(spec.parse({ emoji_id: 0 })).field).toBe('emoji_id');
|
||||
});
|
||||
});
|
||||
|
||||
describe('toHandler — BAD_REQUEST shaping + ctx threading', () => {
|
||||
const spec = groupUserAction({
|
||||
name: 'set_group_ban',
|
||||
params: { duration: f.int({ min: 0 }).default(1800) },
|
||||
run: (p) => okResponse({ seen: [p.group_id, p.user_id, p.duration] }),
|
||||
});
|
||||
it('success path returns run output with typed/defaulted params', async () => {
|
||||
const res = await spec.toHandler(ctx)({ group_id: 10, user_id: 20 });
|
||||
expect(res).toMatchObject({ status: 'ok', retcode: 0, data: { seen: [10, 20, 1800] } });
|
||||
});
|
||||
it('bad params ⇒ BAD_REQUEST naming the field (not INTERNAL_ERROR)', async () => {
|
||||
const res = await spec.toHandler(ctx)({ user_id: 20 }); // missing group_id
|
||||
expect(res.retcode).toBe(RETCODE.BAD_REQUEST);
|
||||
expect(res.status).toBe('failed');
|
||||
expect(res.wording).toContain('group_id');
|
||||
});
|
||||
});
|
||||
|
||||
describe('run raw escape hatch — original params as 3rd arg', () => {
|
||||
it('exposes untouched params for undeclared keys (alias fallbacks etc.)', async () => {
|
||||
const spec = defineAction({
|
||||
name: 't',
|
||||
params: { user_id: f.uint() },
|
||||
run: (_p, _ctx, raw) => okResponse({ extra: (raw.long_nick ?? raw.longNick ?? null) as never }),
|
||||
});
|
||||
const res = await spec.toHandler(ctx)({ user_id: 1, longNick: 'hi' });
|
||||
expect(res).toMatchObject({ status: 'ok', data: { extra: 'hi' } });
|
||||
});
|
||||
});
|
||||
|
||||
describe('describe — doc metadata for self-generated docs (D4)', () => {
|
||||
const spec = groupUserAction({
|
||||
name: ['set_group_ban', 'ban'],
|
||||
summary: 'Mute a member',
|
||||
params: { duration: f.int({ min: 0 }).default(1800).describe('seconds; 0 unmutes') },
|
||||
run: () => okResponse(),
|
||||
});
|
||||
it('exposes name, aliases, and per-param metadata (incl. preset-injected fields)', () => {
|
||||
const doc = spec.describe();
|
||||
expect(doc.name).toBe('set_group_ban');
|
||||
expect(doc.aliases).toEqual(['ban']);
|
||||
expect(doc.summary).toBe('Mute a member');
|
||||
const names = doc.params.map((p) => p.name);
|
||||
expect(names).toEqual(['group_id', 'user_id', 'duration']); // presets surfaced
|
||||
const duration = doc.params.find((p) => p.name === 'duration');
|
||||
expect(duration).toMatchObject({ type: 'int', required: false, default: 1800, desc: 'seconds; 0 unmutes' });
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user