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:
Vendored
+211
@@ -0,0 +1,211 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.ApiError = exports.Client = void 0;
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
const request_1 = require("./request");
|
||||
Object.defineProperty(exports, "ApiError", { enumerable: true, get: function () { return request_1.ApiError; } });
|
||||
class Client {
|
||||
cfg;
|
||||
constructor(cfg) {
|
||||
this.cfg = cfg;
|
||||
}
|
||||
get headers() {
|
||||
return this.cfg.token ? { Authorization: `Bearer ${this.cfg.token}` } : {};
|
||||
}
|
||||
async call(method, p, body) {
|
||||
const res = await (0, request_1.request)(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('GET', '/api/auth/user');
|
||||
}
|
||||
// ---- access tokens (PAT) ----
|
||||
listAccessTokens() {
|
||||
return this.call('GET', '/api/access-token');
|
||||
}
|
||||
createAccessToken(body) {
|
||||
return this.call('POST', '/api/access-token', body);
|
||||
}
|
||||
deleteAccessToken(id) {
|
||||
return this.call('DELETE', `/api/access-token/${id}`);
|
||||
}
|
||||
// ---- base ----
|
||||
listBases() {
|
||||
// GET /api/base/access/all — lists bases the user can access.
|
||||
return this.call('GET', '/api/base/access/all');
|
||||
}
|
||||
getBase(baseId) {
|
||||
return this.call('GET', `/api/base/${baseId}`);
|
||||
}
|
||||
// ---- table ----
|
||||
listTables(baseId) {
|
||||
return this.call('GET', `/api/base/${baseId}/table`);
|
||||
}
|
||||
getTable(tableId) {
|
||||
return this.call('GET', `/api/table/${tableId}`);
|
||||
}
|
||||
createTable(baseId, body) {
|
||||
return this.call('POST', `/api/base/${baseId}/table`, body);
|
||||
}
|
||||
updateTable(tableId, body) {
|
||||
return this.call('PUT', `/api/table/${tableId}`, body);
|
||||
}
|
||||
deleteTable(tableId) {
|
||||
return this.call('DELETE', `/api/table/${tableId}`);
|
||||
}
|
||||
// ---- field ----
|
||||
listFields(tableId) {
|
||||
return this.call('GET', `/api/table/${tableId}/field`);
|
||||
}
|
||||
getField(fieldId) {
|
||||
return this.call('GET', `/api/field/${fieldId}`);
|
||||
}
|
||||
createField(tableId, body) {
|
||||
return this.call('POST', `/api/table/${tableId}/field`, body);
|
||||
}
|
||||
updateField(fieldId, body) {
|
||||
return this.call('PUT', `/api/field/${fieldId}`, body);
|
||||
}
|
||||
deleteField(fieldId) {
|
||||
return this.call('DELETE', `/api/field/${fieldId}`);
|
||||
}
|
||||
// ---- record ----
|
||||
getRecords(tableId, query) {
|
||||
const qs = query ? '?' + new URLSearchParams(this.flattenQuery(query)).toString() : '';
|
||||
return this.call('GET', `/api/table/${tableId}/record${qs}`);
|
||||
}
|
||||
/** Flatten search[] tuple arrays into repeated query keys (Teable expects search[]=...). */
|
||||
flattenQuery(query) {
|
||||
const out = {};
|
||||
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, query) {
|
||||
const qs = query ? '?' + new URLSearchParams(this.flattenQuery(query)).toString() : '';
|
||||
return this.call('GET', `/api/record/${recordId}${qs}`);
|
||||
}
|
||||
createRecord(tableId, body) {
|
||||
return this.call('POST', `/api/table/${tableId}/record`, body);
|
||||
}
|
||||
updateRecord(tableId, body) {
|
||||
return this.call('PATCH', `/api/table/${tableId}/record`, body);
|
||||
}
|
||||
updateRecordOne(recordId, body) {
|
||||
return this.call('PATCH', `/api/record/${recordId}`, body);
|
||||
}
|
||||
deleteRecord(tableId, body) {
|
||||
return this.call('DELETE', `/api/table/${tableId}/record`, body);
|
||||
}
|
||||
// ---- view ----
|
||||
listViews(tableId) {
|
||||
return this.call('GET', `/api/table/${tableId}/view`);
|
||||
}
|
||||
getView(viewId) {
|
||||
return this.call('GET', `/api/view/${viewId}`);
|
||||
}
|
||||
createView(tableId, body) {
|
||||
return this.call('POST', `/api/table/${tableId}/view`, body);
|
||||
}
|
||||
updateView(viewId, body) {
|
||||
return this.call('PATCH', `/api/view/${viewId}`, body);
|
||||
}
|
||||
deleteView(viewId) {
|
||||
return this.call('DELETE', `/api/view/${viewId}`);
|
||||
}
|
||||
// ---- workflow (self-built contract) ----
|
||||
listWorkflows(baseId) {
|
||||
return this.call('GET', `/api/base/${baseId}/workflow`);
|
||||
}
|
||||
getWorkflow(workflowId) {
|
||||
return this.call('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, workflowId) {
|
||||
return this.call('GET', `/api/base/${baseId}/workflow/${workflowId}`);
|
||||
}
|
||||
createWorkflow(baseId, body) {
|
||||
return this.call('POST', `/api/base/${baseId}/workflow`, body);
|
||||
}
|
||||
updateWorkflow(baseId, workflowId, body) {
|
||||
return this.call('PATCH', `/api/base/${baseId}/workflow/${workflowId}`, body);
|
||||
}
|
||||
deleteWorkflow(baseId, workflowId) {
|
||||
return this.call('DELETE', `/api/base/${baseId}/workflow/${workflowId}`);
|
||||
}
|
||||
activateWorkflow(baseId, workflowId) {
|
||||
return this.call('POST', `/api/base/${baseId}/workflow/${workflowId}/activate`);
|
||||
}
|
||||
deactivateWorkflow(baseId, workflowId) {
|
||||
return this.call('POST', `/api/base/${baseId}/workflow/${workflowId}/deactivate`);
|
||||
}
|
||||
testWorkflow(baseId, workflowId) {
|
||||
return this.call('POST', `/api/base/${baseId}/workflow/${workflowId}/test`);
|
||||
}
|
||||
/** PUT /node — whole-graph replacement (delete-all + create-all in a txn). */
|
||||
replaceNodes(baseId, workflowId, body) {
|
||||
return this.call('PUT', `/api/base/${baseId}/workflow/${workflowId}/node`, body);
|
||||
}
|
||||
// ---- secrets ----
|
||||
listSecrets(baseId, workflowId) {
|
||||
return this.call('GET', `/api/base/${baseId}/workflow/${workflowId}/secret`);
|
||||
}
|
||||
createSecret(baseId, workflowId, body) {
|
||||
return this.call('POST', `/api/base/${baseId}/workflow/${workflowId}/secret`, body);
|
||||
}
|
||||
updateSecret(baseId, workflowId, secretId, body) {
|
||||
return this.call('PATCH', `/api/base/${baseId}/workflow/${workflowId}/secret/${secretId}`, body);
|
||||
}
|
||||
deleteSecret(baseId, workflowId, secretId) {
|
||||
return this.call('DELETE', `/api/base/${baseId}/workflow/${workflowId}/secret/${secretId}`);
|
||||
}
|
||||
// ---- execution history ----
|
||||
listExecutions(baseId, workflowId) {
|
||||
return this.call('GET', `/api/base/${baseId}/workflow/${workflowId}/execution`);
|
||||
}
|
||||
getExecution(baseId, workflowId, executionId) {
|
||||
return this.call('GET', `/api/base/${baseId}/workflow/${workflowId}/execution/${executionId}`);
|
||||
}
|
||||
rerunExecution(baseId, workflowId, executionId) {
|
||||
return this.call('POST', `/api/base/${baseId}/workflow/${workflowId}/execution/${executionId}/rerun`);
|
||||
}
|
||||
// ---- trigger (manual fire for testing) ----
|
||||
fireButtonClick(tableId, recordId, fieldId) {
|
||||
return this.call('POST', `/api/table/${tableId}/record/${recordId}/${fieldId}/button-click`);
|
||||
}
|
||||
fireWebhook(baseId, workflowId, body) {
|
||||
// NOTE: real backend route is /api/webhook/{baseId}/{workflowId} (no /base/ /workflow/ segments)
|
||||
return this.call('POST', `/api/webhook/${baseId}/${workflowId}`, body);
|
||||
}
|
||||
// ---- SQL (read-only) ----
|
||||
sql(baseId, sql) {
|
||||
return this.call('POST', `/api/base/${baseId}/sql`, { sql });
|
||||
}
|
||||
}
|
||||
exports.Client = Client;
|
||||
Vendored
+73
@@ -0,0 +1,73 @@
|
||||
"use strict";
|
||||
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
var desc = Object.getOwnPropertyDescriptor(m, k);
|
||||
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
||||
desc = { enumerable: true, get: function() { return m[k]; } };
|
||||
}
|
||||
Object.defineProperty(o, k2, desc);
|
||||
}) : (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
o[k2] = m[k];
|
||||
}));
|
||||
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
||||
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
||||
}) : function(o, v) {
|
||||
o["default"] = v;
|
||||
});
|
||||
var __importStar = (this && this.__importStar) || function (mod) {
|
||||
if (mod && mod.__esModule) return mod;
|
||||
var result = {};
|
||||
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
|
||||
__setModuleDefault(result, mod);
|
||||
return result;
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.configPath = exports.resolveConfig = exports.writeConfigFile = exports.readConfigFile = exports.DEFAULT_ENDPOINT = void 0;
|
||||
/**
|
||||
* 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()).
|
||||
*/
|
||||
const fs = __importStar(require("node:fs"));
|
||||
const path = __importStar(require("node:path"));
|
||||
const os = __importStar(require("node:os"));
|
||||
const CONFIG_DIR = path.join(os.homedir(), '.inkreach');
|
||||
const CONFIG_FILE = path.join(CONFIG_DIR, 'config.json');
|
||||
exports.DEFAULT_ENDPOINT = 'http://localhost:3000';
|
||||
function readConfigFile() {
|
||||
try {
|
||||
const raw = fs.readFileSync(CONFIG_FILE, 'utf8');
|
||||
return JSON.parse(raw);
|
||||
}
|
||||
catch {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
exports.readConfigFile = readConfigFile;
|
||||
function writeConfigFile(cfg) {
|
||||
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 });
|
||||
}
|
||||
exports.writeConfigFile = writeConfigFile;
|
||||
function resolveConfig(overrides) {
|
||||
const file = readConfigFile();
|
||||
return {
|
||||
endpoint: overrides?.endpoint ||
|
||||
process.env.INKREACH_ENDPOINT ||
|
||||
file.endpoint ||
|
||||
exports.DEFAULT_ENDPOINT,
|
||||
token: overrides?.token || process.env.INKREACH_TOKEN || file.token || '',
|
||||
baseId: overrides?.baseId || process.env.INKREACH_BASE_ID || file.baseId,
|
||||
};
|
||||
}
|
||||
exports.resolveConfig = resolveConfig;
|
||||
function configPath() {
|
||||
return CONFIG_FILE;
|
||||
}
|
||||
exports.configPath = configPath;
|
||||
Vendored
+72
@@ -0,0 +1,72 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.requireBaseId = exports.run = exports.makeCtx = void 0;
|
||||
const config_1 = require("./config");
|
||||
const client_1 = require("./client");
|
||||
const request_1 = require("./request");
|
||||
/**
|
||||
* Build a Ctx. `command` is the subcommand being executed (so .opts() returns
|
||||
* its local options); `program` is the top-level program (for global options).
|
||||
*/
|
||||
function makeCtx(program, command) {
|
||||
const g = program.opts();
|
||||
const cfg = (0, config_1.resolveConfig)({
|
||||
endpoint: g.endpoint,
|
||||
token: g.token,
|
||||
baseId: g.baseId,
|
||||
});
|
||||
return {
|
||||
client: new client_1.Client(cfg),
|
||||
json: !!g.json,
|
||||
baseId: cfg.baseId,
|
||||
command,
|
||||
program,
|
||||
};
|
||||
}
|
||||
exports.makeCtx = makeCtx;
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
function run(fn) {
|
||||
return async function (...cmdArgs) {
|
||||
// commander convention: last arg is the Command instance (the subcommand).
|
||||
const command = cmdArgs[cmdArgs.length - 1];
|
||||
const program = command?.parent ? findRoot(command) : command;
|
||||
const positional = cmdArgs.slice(0, -1);
|
||||
const options = (command?.opts() || {});
|
||||
const ctx = makeCtx(program, command);
|
||||
try {
|
||||
await fn(ctx, positional, options);
|
||||
}
|
||||
catch (err) {
|
||||
const { status, code, message } = (0, request_1.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;
|
||||
}
|
||||
};
|
||||
}
|
||||
exports.run = run;
|
||||
function findRoot(cmd) {
|
||||
let c = cmd;
|
||||
while (c.parent)
|
||||
c = c.parent;
|
||||
return c;
|
||||
}
|
||||
/** Require a baseId: from flag, else ctx default, else throw with guidance. */
|
||||
function requireBaseId(ctx, flagVal) {
|
||||
const baseId = flagVal || ctx.baseId;
|
||||
if (!baseId) {
|
||||
throw new client_1.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;
|
||||
}
|
||||
exports.requireBaseId = requireBaseId;
|
||||
Vendored
+34
@@ -0,0 +1,34 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.truncate = exports.printKv = exports.printTable = exports.printJson = void 0;
|
||||
/** Print as JSON (compact). Safe for agent parsing. */
|
||||
function printJson(value) {
|
||||
process.stdout.write(JSON.stringify(value) + '\n');
|
||||
}
|
||||
exports.printJson = printJson;
|
||||
/** Print a human-readable table. columns: [{key, header, width?}]; rows: object[]. */
|
||||
function printTable(columns, rows) {
|
||||
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) => 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'));
|
||||
}
|
||||
exports.printTable = printTable;
|
||||
/** Print key: value pairs vertically. */
|
||||
function printKv(pairs) {
|
||||
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`);
|
||||
});
|
||||
}
|
||||
exports.printKv = printKv;
|
||||
/** Truncate a long string to width, appending ellipsis. */
|
||||
function truncate(s, width = 40) {
|
||||
const str = String(s ?? '');
|
||||
return str.length > width ? str.slice(0, width - 1) + '…' : str;
|
||||
}
|
||||
exports.truncate = truncate;
|
||||
Vendored
+124
@@ -0,0 +1,124 @@
|
||||
"use strict";
|
||||
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
var desc = Object.getOwnPropertyDescriptor(m, k);
|
||||
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
||||
desc = { enumerable: true, get: function() { return m[k]; } };
|
||||
}
|
||||
Object.defineProperty(o, k2, desc);
|
||||
}) : (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
o[k2] = m[k];
|
||||
}));
|
||||
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
||||
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
||||
}) : function(o, v) {
|
||||
o["default"] = v;
|
||||
});
|
||||
var __importStar = (this && this.__importStar) || function (mod) {
|
||||
if (mod && mod.__esModule) return mod;
|
||||
var result = {};
|
||||
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
|
||||
__setModuleDefault(result, mod);
|
||||
return result;
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.describeError = exports.request = exports.ApiError = void 0;
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
const http = __importStar(require("node:http"));
|
||||
const https = __importStar(require("node:https"));
|
||||
class ApiError extends Error {
|
||||
status;
|
||||
body;
|
||||
constructor(status, message, body) {
|
||||
super(message);
|
||||
this.name = 'ApiError';
|
||||
this.status = status;
|
||||
this.body = body;
|
||||
}
|
||||
}
|
||||
exports.ApiError = ApiError;
|
||||
async function request(baseUrl, pathName, options = {}) {
|
||||
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 = {
|
||||
Accept: 'application/json',
|
||||
...(options.headers || {}),
|
||||
};
|
||||
let bodyData;
|
||||
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((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 = [];
|
||||
res.on('data', (chunk) => chunks.push(chunk));
|
||||
res.on('end', () => {
|
||||
const buf = Buffer.concat(chunks);
|
||||
const text = buf.toString('utf8');
|
||||
let data = 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 });
|
||||
}
|
||||
else {
|
||||
const errBody = data;
|
||||
const msg = (errBody && typeof errBody === 'object' && errBody.error?.message) ||
|
||||
(typeof errBody === 'object' && errBody.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();
|
||||
});
|
||||
}
|
||||
exports.request = request;
|
||||
/** Extract `{ code, message }` from an ApiError body for display. */
|
||||
function describeError(err) {
|
||||
if (err instanceof ApiError) {
|
||||
const b = err.body;
|
||||
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) };
|
||||
}
|
||||
exports.describeError = describeError;
|
||||
Reference in New Issue
Block a user