feat: add inkreach CLI + inkreach-teable-ops skill
A self-built CLI and companion agent skill for operating a deployed
inkreach-teable instance — configuring tables, fields, records, views, and
the project's OWN automation engine.
Why not the official 'teable' CLI:
inkreach-teable's automation is self-built with a different contract:
- conditions (not filter), fieldIds (not watchFieldIds)
- recordCondition (not recordMatchesConditions)
- webhook route /api/webhook/{baseId}/{wfId} (not the /base//workflow/ form)
- scheduledTime backend honors only timing.type + timing.interval
The official CLI targets the upstream contract and 404s/misconfigures here.
Table/field/record/view APIs ARE upstream-compatible, but automation is not.
inkreach CLI (packages/inkreach-cli/):
- Node.js + commander, zero extra runtime deps
- Uses node:http (NOT fetch — Node 24 fetch drops Authorization header)
- Commands: auth (login/status/token), base/table/field/record/view,
workflow (list/get/create/update/delete/activate/deactivate/test),
trigger set (8 types, builds correct config keys), action add/update/delete
(6 types), secret, runs (list/get/rerun), fire (button-click/webhook), sql
- --json mode for agent parsing; GET->modify->PUT whole-graph for node edits
- Verified end-to-end: create workflow -> set webhook trigger -> add script
action -> activate -> fire webhook -> runs list (succeeded)
inkreach-teable-ops skill (.agents/skills/inkreach-teable-ops/):
- SKILL.md entry: module map, routing rules, 11 key constraints (the real
contract keys), execution rules, error recovery
- guides/: cli-reference, automation-guide, tables-fields, instance-access,
development (build/restart, known gotchas)
- api-reference/: trigger-types (8 triggers, exact config), action-types
(6 actions, sandbox globals), field-types (21 types incl. Button)
- metadata.json + install.sh
This commit is contained in:
@@ -0,0 +1,272 @@
|
||||
/**
|
||||
* High-level API client. Each method maps to one REST endpoint of the
|
||||
* inkreach-teable backend, using the SELF-BUILT contract (not official teable).
|
||||
*
|
||||
* Base/table/field/record/view endpoints are compatible with official teable
|
||||
* open-api; workflow/automation endpoints use the project's own contract.
|
||||
*/
|
||||
import { request, ApiError } from './request';
|
||||
import { IConfig } from './config';
|
||||
|
||||
export class Client {
|
||||
constructor(private cfg: IConfig) {}
|
||||
|
||||
private get headers(): Record<string, string> {
|
||||
return this.cfg.token ? { Authorization: `Bearer ${this.cfg.token}` } : {};
|
||||
}
|
||||
|
||||
private async call<T>(method: string, p: string, body?: unknown): Promise<T> {
|
||||
const res = await request<T>(this.cfg.endpoint, p, { method, headers: this.headers, body });
|
||||
return res.data;
|
||||
}
|
||||
|
||||
// ---- auth / user ----
|
||||
getMe() {
|
||||
// GET /api/auth/user — @TokenAccess() enabled, works with PAT.
|
||||
// (/api/auth/user/me is session-only and 403s for PAT.)
|
||||
return this.call<unknown>('GET', '/api/auth/user');
|
||||
}
|
||||
|
||||
// ---- access tokens (PAT) ----
|
||||
listAccessTokens() {
|
||||
return this.call<unknown[]>('GET', '/api/access-token');
|
||||
}
|
||||
createAccessToken(body: {
|
||||
name: string;
|
||||
description?: string;
|
||||
scopes: string[];
|
||||
baseIds?: string[];
|
||||
spaceIds?: string[];
|
||||
hasFullAccess?: boolean;
|
||||
expiredTime: string;
|
||||
}) {
|
||||
return this.call<{ id: string; token: string }>('POST', '/api/access-token', body);
|
||||
}
|
||||
deleteAccessToken(id: string) {
|
||||
return this.call<{ id: string }>('DELETE', `/api/access-token/${id}`);
|
||||
}
|
||||
|
||||
// ---- base ----
|
||||
listBases() {
|
||||
// GET /api/base/access/all — lists bases the user can access.
|
||||
return this.call<unknown[]>('GET', '/api/base/access/all');
|
||||
}
|
||||
getBase(baseId: string) {
|
||||
return this.call<unknown>('GET', `/api/base/${baseId}`);
|
||||
}
|
||||
|
||||
// ---- table ----
|
||||
listTables(baseId: string) {
|
||||
return this.call<unknown[]>('GET', `/api/base/${baseId}/table`);
|
||||
}
|
||||
getTable(tableId: string) {
|
||||
return this.call<unknown>('GET', `/api/table/${tableId}`);
|
||||
}
|
||||
createTable(baseId: string, body: unknown) {
|
||||
return this.call<unknown>('POST', `/api/base/${baseId}/table`, body);
|
||||
}
|
||||
updateTable(tableId: string, body: unknown) {
|
||||
return this.call<unknown>('PUT', `/api/table/${tableId}`, body);
|
||||
}
|
||||
deleteTable(tableId: string) {
|
||||
return this.call<{ id: string }>('DELETE', `/api/table/${tableId}`);
|
||||
}
|
||||
|
||||
// ---- field ----
|
||||
listFields(tableId: string) {
|
||||
return this.call<unknown[]>('GET', `/api/table/${tableId}/field`);
|
||||
}
|
||||
getField(fieldId: string) {
|
||||
return this.call<unknown>('GET', `/api/field/${fieldId}`);
|
||||
}
|
||||
createField(tableId: string, body: unknown) {
|
||||
return this.call<unknown>('POST', `/api/table/${tableId}/field`, body);
|
||||
}
|
||||
updateField(fieldId: string, body: unknown) {
|
||||
return this.call<unknown>('PUT', `/api/field/${fieldId}`, body);
|
||||
}
|
||||
deleteField(fieldId: string) {
|
||||
return this.call<{ id: string }>('DELETE', `/api/field/${fieldId}`);
|
||||
}
|
||||
|
||||
// ---- record ----
|
||||
getRecords(tableId: string, query?: Record<string, unknown>) {
|
||||
const qs = query ? '?' + new URLSearchParams(this.flattenQuery(query)).toString() : '';
|
||||
return this.call<unknown>('GET', `/api/table/${tableId}/record${qs}`);
|
||||
}
|
||||
/** Flatten search[] tuple arrays into repeated query keys (Teable expects search[]=...). */
|
||||
private flattenQuery(query: Record<string, unknown>): Record<string, string> {
|
||||
const out: Record<string, string> = {};
|
||||
for (const [k, v] of Object.entries(query)) {
|
||||
if (v === undefined || v === null) continue;
|
||||
if (Array.isArray(v)) {
|
||||
v.forEach((item) => {
|
||||
out[`${k}[]`] = typeof item === 'object' ? JSON.stringify(item) : String(item);
|
||||
});
|
||||
} else if (typeof v === 'object') {
|
||||
out[k] = JSON.stringify(v);
|
||||
} else {
|
||||
out[k] = String(v);
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
getRecord(recordId: string, query?: Record<string, unknown>) {
|
||||
const qs = query ? '?' + new URLSearchParams(this.flattenQuery(query)).toString() : '';
|
||||
return this.call<unknown>('GET', `/api/record/${recordId}${qs}`);
|
||||
}
|
||||
createRecord(tableId: string, body: unknown) {
|
||||
return this.call<unknown>('POST', `/api/table/${tableId}/record`, body);
|
||||
}
|
||||
updateRecord(tableId: string, body: unknown) {
|
||||
return this.call<unknown>('PATCH', `/api/table/${tableId}/record`, body);
|
||||
}
|
||||
updateRecordOne(recordId: string, body: unknown) {
|
||||
return this.call<unknown>('PATCH', `/api/record/${recordId}`, body);
|
||||
}
|
||||
deleteRecord(tableId: string, body: unknown) {
|
||||
return this.call<unknown>('DELETE', `/api/table/${tableId}/record`, body);
|
||||
}
|
||||
|
||||
// ---- view ----
|
||||
listViews(tableId: string) {
|
||||
return this.call<unknown[]>('GET', `/api/table/${tableId}/view`);
|
||||
}
|
||||
getView(viewId: string) {
|
||||
return this.call<unknown>('GET', `/api/view/${viewId}`);
|
||||
}
|
||||
createView(tableId: string, body: unknown) {
|
||||
return this.call<unknown>('POST', `/api/table/${tableId}/view`, body);
|
||||
}
|
||||
updateView(viewId: string, body: unknown) {
|
||||
return this.call<unknown>('PATCH', `/api/view/${viewId}`, body);
|
||||
}
|
||||
deleteView(viewId: string) {
|
||||
return this.call<{ id: string }>('DELETE', `/api/view/${viewId}`);
|
||||
}
|
||||
|
||||
// ---- workflow (self-built contract) ----
|
||||
listWorkflows(baseId: string) {
|
||||
return this.call<unknown[]>('GET', `/api/base/${baseId}/workflow`);
|
||||
}
|
||||
getWorkflow(workflowId: string) {
|
||||
return this.call<IWorkflowVo>('GET', `/api/base/any/workflow/${workflowId}`);
|
||||
}
|
||||
/**
|
||||
* Get workflow by explicit baseId + workflowId. getWorkflow() above hits a
|
||||
* route that resolves base from the workflow itself, but some auth/permission
|
||||
* paths need the base-scoped route. Prefer this when baseId is known.
|
||||
*/
|
||||
getWorkflowInBase(baseId: string, workflowId: string) {
|
||||
return this.call<IWorkflowVo>('GET', `/api/base/${baseId}/workflow/${workflowId}`);
|
||||
}
|
||||
createWorkflow(baseId: string, body: { name: string; description?: string }) {
|
||||
return this.call<IWorkflowVo>('POST', `/api/base/${baseId}/workflow`, body);
|
||||
}
|
||||
updateWorkflow(baseId: string, workflowId: string, body: { name?: string; description?: string }) {
|
||||
return this.call<IWorkflowVo>('PATCH', `/api/base/${baseId}/workflow/${workflowId}`, body);
|
||||
}
|
||||
deleteWorkflow(baseId: string, workflowId: string) {
|
||||
return this.call<unknown>('DELETE', `/api/base/${baseId}/workflow/${workflowId}`);
|
||||
}
|
||||
activateWorkflow(baseId: string, workflowId: string) {
|
||||
return this.call<{ snapshotId: string }>('POST', `/api/base/${baseId}/workflow/${workflowId}/activate`);
|
||||
}
|
||||
deactivateWorkflow(baseId: string, workflowId: string) {
|
||||
return this.call<unknown>('POST', `/api/base/${baseId}/workflow/${workflowId}/deactivate`);
|
||||
}
|
||||
testWorkflow(baseId: string, workflowId: string) {
|
||||
return this.call<{ nodeResults: unknown[] }>('POST', `/api/base/${baseId}/workflow/${workflowId}/test`);
|
||||
}
|
||||
/** PUT /node — whole-graph replacement (delete-all + create-all in a txn). */
|
||||
replaceNodes(baseId: string, workflowId: string, body: { nodes: IWorkflowNodeVo[]; edges: IWorkflowEdgeVo[] }) {
|
||||
return this.call<IWorkflowVo>('PUT', `/api/base/${baseId}/workflow/${workflowId}/node`, body);
|
||||
}
|
||||
|
||||
// ---- secrets ----
|
||||
listSecrets(baseId: string, workflowId: string) {
|
||||
return this.call<unknown[]>('GET', `/api/base/${baseId}/workflow/${workflowId}/secret`);
|
||||
}
|
||||
createSecret(baseId: string, workflowId: string, body: { name: string; description?: string; value: string }) {
|
||||
return this.call<unknown>('POST', `/api/base/${baseId}/workflow/${workflowId}/secret`, body);
|
||||
}
|
||||
updateSecret(baseId: string, workflowId: string, secretId: string, body: { name?: string; description?: string; value?: string }) {
|
||||
return this.call<unknown>('PATCH', `/api/base/${baseId}/workflow/${workflowId}/secret/${secretId}`, body);
|
||||
}
|
||||
deleteSecret(baseId: string, workflowId: string, secretId: string) {
|
||||
return this.call<unknown>('DELETE', `/api/base/${baseId}/workflow/${workflowId}/secret/${secretId}`);
|
||||
}
|
||||
|
||||
// ---- execution history ----
|
||||
listExecutions(baseId: string, workflowId: string) {
|
||||
return this.call<unknown[]>('GET', `/api/base/${baseId}/workflow/${workflowId}/execution`);
|
||||
}
|
||||
getExecution(baseId: string, workflowId: string, executionId: string) {
|
||||
return this.call<unknown>('GET', `/api/base/${baseId}/workflow/${workflowId}/execution/${executionId}`);
|
||||
}
|
||||
rerunExecution(baseId: string, workflowId: string, executionId: string) {
|
||||
return this.call<unknown>('POST', `/api/base/${baseId}/workflow/${workflowId}/execution/${executionId}/rerun`);
|
||||
}
|
||||
|
||||
// ---- trigger (manual fire for testing) ----
|
||||
fireButtonClick(tableId: string, recordId: string, fieldId: string) {
|
||||
return this.call<{ runId: string; tableId: string; fieldId: string; record: unknown }>(
|
||||
'POST',
|
||||
`/api/table/${tableId}/record/${recordId}/${fieldId}/button-click`
|
||||
);
|
||||
}
|
||||
fireWebhook(baseId: string, workflowId: string, body?: unknown) {
|
||||
// NOTE: real backend route is /api/webhook/{baseId}/{workflowId} (no /base/ /workflow/ segments)
|
||||
return this.call<unknown>('POST', `/api/webhook/${baseId}/${workflowId}`, body);
|
||||
}
|
||||
|
||||
// ---- SQL (read-only) ----
|
||||
sql(baseId: string, sql: string) {
|
||||
return this.call<unknown[]>('POST', `/api/base/${baseId}/sql`, { sql });
|
||||
}
|
||||
}
|
||||
|
||||
// ---- shared types (mirror backend workflow_node / workflow_edge shapes) ----
|
||||
export type WorkflowNodeType = 'trigger' | 'action' | 'control';
|
||||
export type WorkflowNodeCategory =
|
||||
| 'recordCreated' | 'recordUpdated' | 'recordCondition' | 'recordCreatedOrUpdated'
|
||||
| 'formSubmitted' | 'scheduledTime' | 'buttonClick' | 'webhook'
|
||||
| 'script' | 'sendEmail' | 'httpRequest'
|
||||
| 'createRecord' | 'updateRecord' | 'getRecords'
|
||||
| 'triggerEnd';
|
||||
|
||||
export interface IWorkflowNodeVo {
|
||||
id: string;
|
||||
workflowId?: string;
|
||||
type: WorkflowNodeType;
|
||||
category: WorkflowNodeCategory | string;
|
||||
config: Record<string, unknown> | null;
|
||||
name?: string | null;
|
||||
testResult?: Record<string, unknown> | null;
|
||||
inputVariables?: unknown;
|
||||
outputVariables?: unknown;
|
||||
}
|
||||
|
||||
export interface IWorkflowEdgeVo {
|
||||
id: string;
|
||||
workflowId?: string;
|
||||
sourceNodeId: string;
|
||||
targetNodeId: string;
|
||||
}
|
||||
|
||||
export interface IWorkflowVo {
|
||||
id: string;
|
||||
baseId: string;
|
||||
name: string;
|
||||
description?: string | null;
|
||||
isActive: boolean;
|
||||
hasDraft: boolean;
|
||||
nodes: IWorkflowNodeVo[];
|
||||
edges: IWorkflowEdgeVo[];
|
||||
createdBy?: string;
|
||||
createdTime?: string;
|
||||
lastModifiedBy?: string | null;
|
||||
lastModifiedTime?: string | null;
|
||||
}
|
||||
|
||||
export { ApiError };
|
||||
@@ -0,0 +1,55 @@
|
||||
/**
|
||||
* Config storage for inkreach CLI.
|
||||
*
|
||||
* Stores endpoint + token at ~/.inkreach/config.json, with environment variable
|
||||
* overrides INKREACH_ENDPOINT / INKREACH_TOKEN. The --endpoint / --token / --base-id
|
||||
* global flags take the highest precedence (handled by resolveOptions()).
|
||||
*/
|
||||
import * as fs from 'node:fs';
|
||||
import * as path from 'node:path';
|
||||
import * as os from 'node:os';
|
||||
|
||||
export interface IConfig {
|
||||
endpoint: string;
|
||||
token: string;
|
||||
baseId?: string;
|
||||
}
|
||||
|
||||
const CONFIG_DIR = path.join(os.homedir(), '.inkreach');
|
||||
const CONFIG_FILE = path.join(CONFIG_DIR, 'config.json');
|
||||
|
||||
export const DEFAULT_ENDPOINT = 'http://localhost:3000';
|
||||
|
||||
export function readConfigFile(): Partial<IConfig> {
|
||||
try {
|
||||
const raw = fs.readFileSync(CONFIG_FILE, 'utf8');
|
||||
return JSON.parse(raw);
|
||||
} catch {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
export function writeConfigFile(cfg: Partial<IConfig>): void {
|
||||
if (!fs.existsSync(CONFIG_DIR)) {
|
||||
fs.mkdirSync(CONFIG_DIR, { recursive: true });
|
||||
}
|
||||
const merged = { ...readConfigFile(), ...cfg };
|
||||
fs.writeFileSync(CONFIG_FILE, JSON.stringify(merged, null, 2) + '\n', { mode: 0o600 });
|
||||
}
|
||||
|
||||
export function resolveConfig(overrides?: Partial<IConfig>): IConfig {
|
||||
const file = readConfigFile();
|
||||
return {
|
||||
endpoint:
|
||||
overrides?.endpoint ||
|
||||
process.env.INKREACH_ENDPOINT ||
|
||||
file.endpoint ||
|
||||
DEFAULT_ENDPOINT,
|
||||
token: overrides?.token || process.env.INKREACH_TOKEN || file.token || '',
|
||||
baseId: overrides?.baseId || process.env.INKREACH_BASE_ID || file.baseId,
|
||||
};
|
||||
}
|
||||
|
||||
export function configPath(): string {
|
||||
return CONFIG_FILE;
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
/**
|
||||
* Shared command context: resolves config from global flags + file + env,
|
||||
* builds a Client, and normalizes error handling.
|
||||
*/
|
||||
import { Command } from 'commander';
|
||||
import { resolveConfig } from './config';
|
||||
import { Client, ApiError } from './client';
|
||||
import { describeError } from './request';
|
||||
|
||||
export interface Ctx {
|
||||
client: Client;
|
||||
json: boolean;
|
||||
baseId?: string;
|
||||
/** The running subcommand (last in the chain). Use .opts() for its options. */
|
||||
command: Command;
|
||||
program: Command;
|
||||
}
|
||||
|
||||
/**
|
||||
* Build a Ctx. `command` is the subcommand being executed (so .opts() returns
|
||||
* its local options); `program` is the top-level program (for global options).
|
||||
*/
|
||||
export function makeCtx(program: Command, command: Command): Ctx {
|
||||
const g = program.opts() as {
|
||||
endpoint?: string;
|
||||
token?: string;
|
||||
baseId?: string;
|
||||
json?: boolean;
|
||||
};
|
||||
const cfg = resolveConfig({
|
||||
endpoint: g.endpoint,
|
||||
token: g.token,
|
||||
baseId: g.baseId,
|
||||
});
|
||||
return {
|
||||
client: new Client(cfg),
|
||||
json: !!g.json,
|
||||
baseId: cfg.baseId,
|
||||
command,
|
||||
program,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Wrap an async command action with normalized error handling.
|
||||
*
|
||||
* The wrapped fn receives (ctx, positionalArgs[], options). commander passes
|
||||
* positional args before the trailing Command; we detect the trailing Command
|
||||
* and forward everything else as positional, plus parsed options.
|
||||
*/
|
||||
export function run<TArgs extends unknown[] = unknown[]>(
|
||||
fn: (ctx: Ctx, args: TArgs, options: Record<string, unknown>) => Promise<void>
|
||||
): (this: Command, ...cmdArgs: unknown[]) => Promise<void> {
|
||||
return async function (this: Command, ...cmdArgs: unknown[]) {
|
||||
// commander convention: last arg is the Command instance (the subcommand).
|
||||
const command = cmdArgs[cmdArgs.length - 1] as Command;
|
||||
const program = command?.parent ? findRoot(command) : command;
|
||||
const positional = cmdArgs.slice(0, -1) as TArgs;
|
||||
const options = (command?.opts() || {}) as Record<string, unknown>;
|
||||
const ctx = makeCtx(program, command);
|
||||
try {
|
||||
await fn(ctx, positional, options);
|
||||
} catch (err) {
|
||||
const { status, code, message } = describeError(err);
|
||||
if (ctx.json) {
|
||||
process.stdout.write(JSON.stringify({ error: { status, code, message } }) + '\n');
|
||||
} else {
|
||||
process.stderr.write(`✗ ${code}${status ? ` (${status})` : ''}: ${message}\n`);
|
||||
}
|
||||
process.exitCode = 1;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
function findRoot(cmd: Command): Command {
|
||||
let c = cmd;
|
||||
while (c.parent) c = c.parent;
|
||||
return c;
|
||||
}
|
||||
|
||||
/** Require a baseId: from flag, else ctx default, else throw with guidance. */
|
||||
export function requireBaseId(ctx: Ctx, flagVal?: string): string {
|
||||
const baseId = flagVal || ctx.baseId;
|
||||
if (!baseId) {
|
||||
throw new ApiError(
|
||||
0,
|
||||
'MISSING_BASE_ID',
|
||||
'No base id. Pass --base-id <id>, set a default with `inkreach auth login --base-id <id>`, or export INKREACH_BASE_ID.'
|
||||
);
|
||||
}
|
||||
return baseId;
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
/**
|
||||
* Output formatting helpers.
|
||||
*
|
||||
* Two modes:
|
||||
* - JSON mode (--json flag): print raw JSON, nothing else.
|
||||
* - Human mode (default): pretty-print tables / key-values.
|
||||
*/
|
||||
export interface OutputOptions {
|
||||
json: boolean;
|
||||
}
|
||||
|
||||
/** Print as JSON (compact). Safe for agent parsing. */
|
||||
export function printJson(value: unknown): void {
|
||||
process.stdout.write(JSON.stringify(value) + '\n');
|
||||
}
|
||||
|
||||
/** Print a human-readable table. columns: [{key, header, width?}]; rows: object[]. */
|
||||
export function printTable(
|
||||
columns: Array<{ key: string; header: string }>,
|
||||
rows: Array<Record<string, unknown>>
|
||||
): void {
|
||||
const headers = columns.map((c) => c.header);
|
||||
const widths = columns.map((c) => Math.max(c.header.length, ...rows.map((r) => String(r[c.key] ?? '').length)));
|
||||
const sep = widths.map((w) => '-'.repeat(w)).join(' ');
|
||||
const fmtRow = (r: Record<string, unknown>) =>
|
||||
columns.map((c, i) => String(r[c.key] ?? '').padEnd(widths[i])).join(' ');
|
||||
process.stdout.write(headers.map((h, i) => h.padEnd(widths[i])).join(' ') + '\n');
|
||||
process.stdout.write(sep + '\n');
|
||||
rows.forEach((r) => process.stdout.write(fmtRow(r) + '\n'));
|
||||
}
|
||||
|
||||
/** Print key: value pairs vertically. */
|
||||
export function printKv(pairs: Array<[string, unknown]>): void {
|
||||
const width = Math.max(...pairs.map(([k]) => k.length));
|
||||
pairs.forEach(([k, v]) => {
|
||||
const val = typeof v === 'object' && v !== null ? JSON.stringify(v) : String(v ?? '');
|
||||
process.stdout.write(`${k.padEnd(width)} ${val}\n`);
|
||||
});
|
||||
}
|
||||
|
||||
/** Truncate a long string to width, appending ellipsis. */
|
||||
export function truncate(s: unknown, width = 40): string {
|
||||
const str = String(s ?? '');
|
||||
return str.length > width ? str.slice(0, width - 1) + '…' : str;
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
/**
|
||||
* HTTP request helper using node:http / node:https.
|
||||
*
|
||||
* IMPORTANT: we deliberately avoid global fetch() on Node.js — the Node 24
|
||||
* undici fetch drops the Authorization header in some redirect/proxy scenarios
|
||||
* (confirmed bug in this project). Using the built-in http(s) module keeps the
|
||||
* Authorization: Bearer header intact end-to-end.
|
||||
*/
|
||||
import * as http from 'node:http';
|
||||
import * as https from 'node:https';
|
||||
|
||||
export interface IRequestOptions {
|
||||
method?: string;
|
||||
headers?: Record<string, string>;
|
||||
body?: unknown;
|
||||
/** Abort signal for timeouts. */
|
||||
signal?: AbortSignal;
|
||||
}
|
||||
|
||||
export interface IResponse<T = unknown> {
|
||||
status: number;
|
||||
headers: http.IncomingHttpHeaders;
|
||||
data: T;
|
||||
}
|
||||
|
||||
export class ApiError extends Error {
|
||||
status: number;
|
||||
body: unknown;
|
||||
constructor(status: number, message: string, body: unknown) {
|
||||
super(message);
|
||||
this.name = 'ApiError';
|
||||
this.status = status;
|
||||
this.body = body;
|
||||
}
|
||||
}
|
||||
|
||||
export async function request<T = unknown>(
|
||||
baseUrl: string,
|
||||
pathName: string,
|
||||
options: IRequestOptions = {}
|
||||
): Promise<IResponse<T>> {
|
||||
const url = new URL(
|
||||
pathName.startsWith('http') ? pathName : pathName.replace(/^\//, ''),
|
||||
baseUrl.endsWith('/') ? baseUrl : baseUrl + '/'
|
||||
);
|
||||
|
||||
const isHttps = url.protocol === 'https:';
|
||||
const lib = isHttps ? https : http;
|
||||
const method = options.method || 'GET';
|
||||
const headers: Record<string, string> = {
|
||||
Accept: 'application/json',
|
||||
...(options.headers || {}),
|
||||
};
|
||||
let bodyData: string | undefined;
|
||||
if (options.body !== undefined && options.body !== null) {
|
||||
bodyData = JSON.stringify(options.body);
|
||||
headers['Content-Type'] = headers['Content-Type'] || 'application/json';
|
||||
headers['Content-Length'] = Buffer.byteLength(bodyData).toString();
|
||||
}
|
||||
|
||||
return new Promise<IResponse<T>>((resolve, reject) => {
|
||||
const req = lib.request(
|
||||
{
|
||||
hostname: url.hostname,
|
||||
port: url.port || (isHttps ? 443 : 80),
|
||||
path: url.pathname + url.search,
|
||||
method,
|
||||
headers,
|
||||
},
|
||||
(res) => {
|
||||
const chunks: Buffer[] = [];
|
||||
res.on('data', (chunk: Buffer) => chunks.push(chunk));
|
||||
res.on('end', () => {
|
||||
const buf = Buffer.concat(chunks);
|
||||
const text = buf.toString('utf8');
|
||||
let data: unknown = text;
|
||||
const ct = res.headers['content-type'] || '';
|
||||
if (ct.includes('application/json') || text.trim().startsWith('{') || text.trim().startsWith('[')) {
|
||||
try {
|
||||
data = text ? JSON.parse(text) : null;
|
||||
} catch {
|
||||
data = text;
|
||||
}
|
||||
}
|
||||
const status = res.statusCode || 200;
|
||||
if (status >= 200 && status < 300) {
|
||||
resolve({ status, headers: res.headers, data: data as T });
|
||||
} else {
|
||||
const errBody = data;
|
||||
const msg =
|
||||
(errBody && typeof errBody === 'object' && (errBody as { error?: { message?: string } }).error?.message) ||
|
||||
(typeof errBody === 'object' && (errBody as { message?: string }).message) ||
|
||||
`HTTP ${status}`;
|
||||
reject(new ApiError(status, String(msg), errBody));
|
||||
}
|
||||
});
|
||||
}
|
||||
);
|
||||
if (options.signal) {
|
||||
options.signal.addEventListener('abort', () => req.destroy(new Error('aborted')));
|
||||
}
|
||||
req.on('error', reject);
|
||||
if (bodyData !== undefined) req.write(bodyData);
|
||||
req.end();
|
||||
});
|
||||
}
|
||||
|
||||
/** Extract `{ code, message }` from an ApiError body for display. */
|
||||
export function describeError(err: unknown): { status: number; code: string; message: string } {
|
||||
if (err instanceof ApiError) {
|
||||
const b = err.body as { error?: { code?: string; message?: string } } | undefined;
|
||||
return {
|
||||
status: err.status,
|
||||
code: b?.error?.code || `HTTP_${err.status}`,
|
||||
message: b?.error?.message || err.message,
|
||||
};
|
||||
}
|
||||
if (err instanceof Error) {
|
||||
return { status: 0, code: 'ERROR', message: err.message };
|
||||
}
|
||||
return { status: 0, code: 'UNKNOWN', message: String(err) };
|
||||
}
|
||||
Reference in New Issue
Block a user