Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion src/action-error.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { BusinessResponseError, HttpError, RequestTimeoutError } from './client.ts';
import { BusinessResponseError, HttpError, PREVIEW_UNSUPPORTED_HINT, RequestTimeoutError } from './client.ts';

function record(value: unknown): Record<string, any> | undefined {
return value !== null && typeof value === 'object' && !Array.isArray(value)
Expand Down Expand Up @@ -41,6 +41,8 @@ export function actionErrorDetail(error: unknown, apiKey?: string, envelope?: un
?? (error instanceof RequestTimeoutError ? 'REQUEST_TIMEOUT'
: status ? `HTTP_${status}` : unknown ? 'EXECUTION_OUTCOME_UNKNOWN' : 'ACTION_FAILED');
const details = inner?.details ?? body?.details ?? (Array.isArray(message) ? message : undefined);
// call errors are rebuilt from the response body, so the client's message hint is lost here.
const previewUnsupported = status === 400 && JSON.stringify([message, details]).includes('include_preview');
return redactActionFailure({
...(status ? { status } : {}),
code,
Expand All @@ -49,5 +51,6 @@ export function actionErrorDetail(error: unknown, apiKey?: string, envelope?: un
...(error instanceof HttpError && error.retryAfterMs !== undefined ? { retry_after_ms: error.retryAfterMs } : {}),
outcome: unknown ? 'unknown' : 'failed',
...(unknown ? { hint: 'The upstream may have completed the action. Check its result before retrying a write.' } : {}),
...(previewUnsupported ? { hint: PREVIEW_UNSUPPORTED_HINT } : {}),
}, apiKey);
}
35 changes: 29 additions & 6 deletions src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,20 @@ const RETRY_MAX_DELAY_MS = 8_000;
export interface ClientOptions {
actionHost: string;
apiKey?: string;
/** POST execute/batch bodies: send include_preview so the caller can reach their own PREVIEW services. */
includePreview?: boolean;
}

/** Backends that predate preview reject the body field (`property include_preview should not exist`). */
export const PREVIEW_UNSUPPORTED_HINT = '--preview needs an xAPI backend with preview support; on older backends a key with the legacy sandbox permission reaches your own unpublished services without --preview';

export function withPreviewHint(status: number, message: string): string {
return status === 400 && message.includes('include_preview') ? `${message} (${PREVIEW_UNSUPPORTED_HINT})` : message;
}

/** Older backends may reject unknown body fields, so send include_preview only when requested. */
function previewBody(opts: ClientOptions): { include_preview?: true } {
return opts.includePreview ? { include_preview: true } : {};
}

/** Optional Action metadata from supporting backends; source is not review evidence. */
Expand Down Expand Up @@ -448,7 +462,7 @@ export async function request<T>(
});
let responseBody: unknown;
try { responseBody = JSON.parse(text); } catch { /* Plain upstream errors stay plain. */ }
throw new HttpError(res.status, text.slice(0, 300), retryAfterMs, responseBody);
throw new HttpError(res.status, withPreviewHint(res.status, text.slice(0, 300)), retryAfterMs, responseBody);
}
if (res.status === 204) {
return undefined as T;
Expand Down Expand Up @@ -743,14 +757,17 @@ function baseUrl(opts: ClientOptions): string {

export async function actionList(
opts: ClientOptions,
params: { page?: number; page_size?: number; category?: string; source?: string; service_id?: string } = {},
params: {
page?: number; page_size?: number; category?: string; source?: string; service_id?: string; include_preview?: boolean;
} = {},
) {
const url = new URL(`${baseUrl(opts)}/v1/actions`);
if (params.page) url.searchParams.set('page', String(params.page));
if (params.page_size) url.searchParams.set('page_size', String(params.page_size));
if (params.category) url.searchParams.set('category', params.category);
if (params.source) url.searchParams.set('source', params.source);
if (params.service_id) url.searchParams.set('service_id', params.service_id);
if (params.include_preview) url.searchParams.set('include_preview', 'true');
return request<{ actions: unknown[]; pagination: unknown }>(
url.toString(),
{ method: 'GET', headers: headers(opts.apiKey) },
Expand All @@ -768,6 +785,7 @@ export async function actionSearch(
page?: number;
page_size?: number;
include_all_versions?: boolean;
include_preview?: boolean;
sort?: 'default' | 'relevance' | 'price';
} = {},
) {
Expand All @@ -778,6 +796,7 @@ export async function actionSearch(
if (params.page) url.searchParams.set('page', String(params.page));
if (params.page_size) url.searchParams.set('page_size', String(params.page_size));
if (params.include_all_versions) url.searchParams.set('include_all_versions', 'true');
if (params.include_preview) url.searchParams.set('include_preview', 'true');
if (params.sort) url.searchParams.set('sort', params.sort);
return request<{
results: unknown[];
Expand All @@ -793,9 +812,10 @@ export async function actionSearch(
);
}

export async function actionCategories(opts: ClientOptions, params: { source?: string } = {}) {
export async function actionCategories(opts: ClientOptions, params: { source?: string; include_preview?: boolean } = {}) {
const url = new URL(`${baseUrl(opts)}/v1/actions/categories`);
if (params.source) url.searchParams.set('source', params.source);
if (params.include_preview) url.searchParams.set('include_preview', 'true');
return request<{ categories: string[]; total: number }>(
url.toString(),
{ method: 'GET', headers: headers(opts.apiKey) },
Expand Down Expand Up @@ -824,7 +844,7 @@ export async function actionBatch(ids: string[], opts: ClientOptions) {
{
method: 'POST',
headers: headers(opts.apiKey),
body: JSON.stringify({ ids }),
body: JSON.stringify({ ids, ...previewBody(opts) }),
},
DEFAULT_TIMEOUT_MS,
IDEMPOTENT_RETRIES, // read-only metadata fetch — safe to retry
Expand All @@ -851,7 +871,7 @@ export async function actionCall(
{
method: 'POST',
headers: headers(opts.apiKey),
body: JSON.stringify({ action_id: actionId, ...(httpMethod ? { method: httpMethod } : {}), input }),
body: JSON.stringify({ action_id: actionId, ...(httpMethod ? { method: httpMethod } : {}), input, ...previewBody(opts) }),
},
Math.min(timeoutMs, EXECUTE_TIMEOUT_MS),
retries,
Expand Down Expand Up @@ -958,6 +978,7 @@ export async function actionStream(
...(httpMethod ? { method: httpMethod } : {}),
input,
stream: true,
...previewBody(opts),
}),
redirect: 'manual',
signal: controller.signal,
Expand Down Expand Up @@ -1055,6 +1076,7 @@ export async function actionDownload(
...(httpMethod ? { method: httpMethod } : {}),
input,
response_mode: 'raw',
...previewBody(opts),
}),
redirect: 'manual',
signal: controller.signal,
Expand Down Expand Up @@ -1113,12 +1135,13 @@ export async function actionDownload(

export async function actionServices(
opts: ClientOptions,
params: { page?: number; page_size?: number; category?: string } = {},
params: { page?: number; page_size?: number; category?: string; include_preview?: boolean } = {},
) {
const url = new URL(`${baseUrl(opts)}/v1/actions/services`);
if (params.page) url.searchParams.set('page', String(params.page));
if (params.page_size) url.searchParams.set('page_size', String(params.page_size));
if (params.category) url.searchParams.set('category', params.category);
if (params.include_preview) url.searchParams.set('include_preview', 'true');
return request<{ services: unknown[]; pagination: unknown }>(
url.toString(),
{ method: 'GET', headers: headers(opts.apiKey) },
Expand Down
27 changes: 19 additions & 8 deletions src/codegen.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ export interface CodegenParams {
input: Record<string, unknown>;
actionHost: string;
method?: string;
/** --preview: the snippet must also ask for the caller's own PREVIEW services. */
includePreview?: boolean;
}

interface ResolvedTarget {
Expand Down Expand Up @@ -110,8 +112,17 @@ function baseUrl(actionHost: string): string {
return `${scheme(actionHost)}://${actionHost}/v1/actions/execute`;
}

function jsonBody(actionId: string, input: Record<string, unknown>, method?: string): string {
return JSON.stringify({ action_id: actionId, ...(method ? { method } : {}), input }, null, 2);
function payloadOf(params: CodegenParams): Record<string, unknown> {
return {
action_id: params.actionId,
...(params.method ? { method: params.method } : {}),
input: params.input,
...(params.includePreview ? { include_preview: true } : {}),
};
}

function jsonBody(params: CodegenParams): string {
return JSON.stringify(payloadOf(params), null, 2);
}

/** Re-indent a multi-line string so continuation lines are aligned */
Expand All @@ -128,7 +139,7 @@ function shellEscape(s: string): string {

function genCurl(params: CodegenParams): string {
const url = baseUrl(params.actionHost);
const body = jsonBody(params.actionId, params.input, params.method);
const body = jsonBody(params);
return [
'# Set XAPI_KEY env var or replace with your key',
`curl -X POST '${shellEscape(url)}' \\`,
Expand All @@ -140,7 +151,7 @@ function genCurl(params: CodegenParams): string {

function genPython(lib: 'requests' | 'httpx', params: CodegenParams): string {
const url = baseUrl(params.actionHost);
const payload = { action_id: params.actionId, ...(params.method ? { method: params.method } : {}), input: params.input };
const payload = payloadOf(params);
return [
`# pip install ${lib}`,
'# Set XAPI_KEY env var or replace with your key',
Expand All @@ -161,7 +172,7 @@ function genPython(lib: 'requests' | 'httpx', params: CodegenParams): string {

function genJavaScriptFetch(params: CodegenParams): string {
const url = baseUrl(params.actionHost);
const body = jsonBody(params.actionId, params.input, params.method);
const body = jsonBody(params);
return [
'// Set XAPI_KEY env var or replace with your key',
`const resp = await fetch("${url}", {`,
Expand All @@ -178,7 +189,7 @@ function genJavaScriptFetch(params: CodegenParams): string {

function genJavaScriptAxios(params: CodegenParams): string {
const url = baseUrl(params.actionHost);
const body = jsonBody(params.actionId, params.input, params.method);
const body = jsonBody(params);
return [
'// npm install axios',
'// Set XAPI_KEY env var or replace with your key',
Expand All @@ -200,7 +211,7 @@ function genJavaScriptAxios(params: CodegenParams): string {

function genTypescriptFetch(params: CodegenParams): string {
const url = baseUrl(params.actionHost);
const body = jsonBody(params.actionId, params.input, params.method);
const body = jsonBody(params);
return [
'// Set XAPI_KEY env var or replace with your key',
`const resp: Response = await fetch("${url}", {`,
Expand All @@ -218,7 +229,7 @@ function genTypescriptFetch(params: CodegenParams): string {

function genGo(params: CodegenParams): string {
const url = baseUrl(params.actionHost);
const body = jsonBody(params.actionId, params.input, params.method);
const body = jsonBody(params);
const escaped = body.replace(/`/g, '` + "`" + `');
return [
'// Set XAPI_KEY env var or replace with your key',
Expand Down
Loading
Loading