diff --git a/src/action-error.ts b/src/action-error.ts index b539f19..50b2a01 100644 --- a/src/action-error.ts +++ b/src/action-error.ts @@ -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 | undefined { return value !== null && typeof value === 'object' && !Array.isArray(value) @@ -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, @@ -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); } diff --git a/src/client.ts b/src/client.ts index c6e6437..b5fae2f 100644 --- a/src/client.ts +++ b/src/client.ts @@ -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. */ @@ -448,7 +462,7 @@ export async function request( }); 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; @@ -743,7 +757,9 @@ 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)); @@ -751,6 +767,7 @@ export async function actionList( 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) }, @@ -768,6 +785,7 @@ export async function actionSearch( page?: number; page_size?: number; include_all_versions?: boolean; + include_preview?: boolean; sort?: 'default' | 'relevance' | 'price'; } = {}, ) { @@ -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[]; @@ -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) }, @@ -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 @@ -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, @@ -958,6 +978,7 @@ export async function actionStream( ...(httpMethod ? { method: httpMethod } : {}), input, stream: true, + ...previewBody(opts), }), redirect: 'manual', signal: controller.signal, @@ -1055,6 +1076,7 @@ export async function actionDownload( ...(httpMethod ? { method: httpMethod } : {}), input, response_mode: 'raw', + ...previewBody(opts), }), redirect: 'manual', signal: controller.signal, @@ -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) }, diff --git a/src/codegen.ts b/src/codegen.ts index 2975ef7..744d60f 100644 --- a/src/codegen.ts +++ b/src/codegen.ts @@ -14,6 +14,8 @@ export interface CodegenParams { input: Record; actionHost: string; method?: string; + /** --preview: the snippet must also ask for the caller's own PREVIEW services. */ + includePreview?: boolean; } interface ResolvedTarget { @@ -110,8 +112,17 @@ function baseUrl(actionHost: string): string { return `${scheme(actionHost)}://${actionHost}/v1/actions/execute`; } -function jsonBody(actionId: string, input: Record, method?: string): string { - return JSON.stringify({ action_id: actionId, ...(method ? { method } : {}), input }, null, 2); +function payloadOf(params: CodegenParams): Record { + 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 */ @@ -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)}' \\`, @@ -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', @@ -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}", {`, @@ -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', @@ -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}", {`, @@ -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', diff --git a/src/commands/action.ts b/src/commands/action.ts index 9772fc9..117f1de 100644 --- a/src/commands/action.ts +++ b/src/commands/action.ts @@ -27,6 +27,7 @@ FLAGS --service-id Filter by service --page N Page number (default: 1) --page-size N Results per page + --preview Also include your own PREVIEW services (unpublished, free to self-test) --format json|pretty|table Output format EXAMPLES @@ -49,6 +50,7 @@ FLAGS Recommended (default), strongest match, or lowest comparable price after exact-id/local-match guards --include-all-versions Include active non-default major versions + --preview Also include your own PREVIEW services (unpublished, free to self-test) --format json|pretty|table Output format EXAMPLES @@ -67,6 +69,7 @@ USAGE FLAGS --source capability|api Filter by source type + --preview Also include your own PREVIEW services (unpublished, free to self-test) --format json|pretty|table Output format `; @@ -79,6 +82,7 @@ FLAGS --category Filter by category: id, alias or name, any case --page N Page number --page-size N Results per page + --preview Also include your own PREVIEW services (unpublished, free to self-test) --format json|pretty|table Output format `; @@ -88,6 +92,7 @@ USAGE xapi-to get-batch [id ...] [flags] FLAGS + --preview Also resolve your own PREVIEW services --format json|pretty|table Output format EXAMPLES @@ -102,6 +107,7 @@ USAGE FLAGS --method GET|POST|... Filter by HTTP method --code Generate code snippet instead of showing schema + --preview Also resolve your own PREVIEW services --format json|pretty|table Output format CODE TARGETS @@ -139,6 +145,7 @@ FLAGS --output Save a raw binary response to a new file --output-json Save the full JSON response to a new private file --stream Forward the action's HTTP SSE response unchanged + --preview Allow calling your own PREVIEW service (free self-test; needs a backend with preview support) --code Generate code snippet instead of executing --format json|pretty|table Output format @@ -222,6 +229,16 @@ function positiveIntegerFlag(value: string | undefined, name: string): number | return Number(value); } +/** --preview: also show/allow the caller's own PREVIEW services (formerly SANDBOX). */ +function previewFlag(flags: Record): true | undefined { + return flags.preview === 'true' || undefined; +} + +/** Client options that carry include_preview in POST bodies when --preview is given. */ +function withPreview(cfg: T, flags: Record): T { + return previewFlag(flags) ? { ...cfg, includePreview: true } : cfg; +} + function httpMethodFlag(value: string | undefined): string | undefined { if (value === undefined) return undefined; if (value === 'true' || !/^[A-Za-z]+$/.test(value)) { @@ -241,6 +258,7 @@ export async function actionList(args: string[], flags: Record) page_size: positiveIntegerFlag(flags['page-size'], '--page-size'), category: flags.category, service_id: flags['service-id'], + include_preview: previewFlag(flags), }); const actions = (res.actions || []) as any[]; if (fmt === 'table') { @@ -288,6 +306,7 @@ export async function actionSearch(args: string[], flags: Record // Backward-compatible aliases from the original feature branch. include_all_versions: ['include-all-versions', 'all-versions', 'include-history'] .some((name) => flags[name] === 'true'), + include_preview: previewFlag(flags), sort: requestedSort, }); if (requestedSort && res.sort !== requestedSort) { @@ -313,7 +332,7 @@ export async function actionCategories(args: string[], flags: Record ({ category: c })), 'table'); } else { @@ -333,6 +352,7 @@ export async function actionServices(args: string[], flags: Record) { const methodFilter = httpMethodFlag(flags.method); const cfg = getConfig(); try { - const res = await client.actionGet(id, cfg); + const res = await client.actionGet(id, withPreview(cfg, flags)); const actions = Array.isArray(res) ? res : [res]; const filtered = methodFilter ? actions.filter((a: any) => a.method?.toUpperCase() === methodFilter) @@ -377,7 +397,7 @@ export async function actionGet(args: string[], flags: Record) { } const action = filtered[0] as any; const { method: _schemaMethod, ...cleanCodeInput } = buildDefaultInput(action.input ?? {}); - const result = generateCode(flags.code, { actionId: id, input: cleanCodeInput, actionHost: cfg.actionHost, method: action.method }); + const result = generateCode(flags.code, { actionId: id, input: cleanCodeInput, actionHost: cfg.actionHost, method: action.method, includePreview: previewFlag(flags) }); outputCode(result, flags); return; } @@ -394,7 +414,7 @@ export async function actionBatchGet(args: string[], flags: Record 100) err('get-batch accepts at most 100 action IDs'); const cfg = getConfig(); try { - const res = await client.actionBatch(args, cfg); + const res = await client.actionBatch(args, withPreview(cfg, flags)); output(res, flags.format as any); } catch (e: any) { err('get-batch failed', e.message); @@ -438,28 +458,29 @@ export async function actionCall(args: string[], flags: Record) || (typeof inputMethod === 'string' ? inputMethod.toUpperCase() : undefined); if (flags.code) { - const result = generateCode(flags.code, { actionId: id, input: cleanInput, actionHost: cfg.actionHost, method }); + const result = generateCode(flags.code, { actionId: id, input: cleanInput, actionHost: cfg.actionHost, method, includePreview: previewFlag(flags) }); outputCode(result, flags); return; } requireApiKey(cfg); + const callCfg = withPreview(cfg, flags); let res: unknown; try { if (jsonPath !== undefined) { - const saved = await client.actionSaveJson(id, cleanInput, cfg, jsonPath, method); + const saved = await client.actionSaveJson(id, cleanInput, callCfg, jsonPath, method); output({ success: true, ...saved }, flags.format as any); return; } if (stream) { - await client.actionStream(id, cleanInput, cfg, method); + await client.actionStream(id, cleanInput, callCfg, method); return; } if (flags.output) { const result = await client.actionDownload( id, cleanInput, - cfg, + callCfg, flags.output, method, ); @@ -476,7 +497,7 @@ export async function actionCall(args: string[], flags: Record) ); return; } - res = await client.actionCall(id, cleanInput, cfg, method); + res = await client.actionCall(id, cleanInput, callCfg, method); } catch (e: any) { if (e instanceof client.BusinessResponseError) output(redactActionFailure(e.responseBody, cfg.apiKey), flags.format as any); await errAfterFlush('call failed', actionErrorDetail(e, cfg.apiKey)); diff --git a/src/commands/provider-onboarding.ts b/src/commands/provider-onboarding.ts index 47de74a..63ed213 100644 --- a/src/commands/provider-onboarding.ts +++ b/src/commands/provider-onboarding.ts @@ -36,8 +36,8 @@ choice; --default-price affects only unpriced PER_CALL operations, including hidden ones, and preserves existing prices and other billing types. Merge updates to existing endpoints require their IDs. Use --mode replace to replace the endpoint list, or --allow-new-endpoints to intentionally add. -Creation with endpoints starts in SANDBOX; empty services start in DRAFT. -Saving a draft configuration moves it to SANDBOX, ready for submit. +Creation with endpoints starts in PREVIEW (formerly SANDBOX); empty services +start in DRAFT. Saving a draft configuration moves it to PREVIEW, ready for submit. PERMISSIONS import: service:create (legacy allowRegister also accepted) @@ -258,7 +258,7 @@ export async function providerOnboarding(args: string[], flags: Record Filter by category --service-id Filter by service + --preview Include your own PREVIEW services search Search actions by keyword (--all-versions: 含非默认但仍在跑的大版本) --source capability|api Filter by source type --category Filter by category --page N --page-size N Pagination --sort default|relevance|price Recommended, strongest match, or comparable price --include-all-versions Include active non-default major versions + --preview Include your own PREVIEW services categories List all action categories --source capability|api Filter by source type + --preview Include your own PREVIEW services services List all services --page N --page-size N Pagination --category Filter by category + --preview Include your own PREVIEW services get [--method GET|POST|...] Get action schema (filter by HTTP method) --code Generate code snippet (curl, py, js, ts, go) + --preview Also resolve your own PREVIEW services get-batch [id ...] Get up to 100 action schemas + --preview Also resolve your own PREVIEW services call --input '{"key":"val"}' Execute an action --method GET|POST|... Override HTTP method --output Save a raw binary response to a new file --output-json Save the full JSON response to a new private file --stream Forward HTTP SSE frames unchanged + --preview Allow calling your own PREVIEW service --code Generate code snippet instead of executing Variants: python.requests, python.httpx, javascript.fetch, javascript.axios diff --git a/src/tests/action-error.test.ts b/src/tests/action-error.test.ts index de12f3f..a5479e7 100644 --- a/src/tests/action-error.test.ts +++ b/src/tests/action-error.test.ts @@ -3,6 +3,14 @@ import { actionErrorDetail, redactActionFailure } from '../action-error.ts'; import { HttpError, RequestTimeoutError } from '../client.ts'; describe('action error details', () => { + test('call --preview against a backend without preview support explains the 400', () => { + const body = { statusCode: 400, message: ['property include_preview should not exist'], error: 'Bad Request' }; + expect(actionErrorDetail(new HttpError(400, JSON.stringify(body), undefined, body))).toMatchObject({ + status: 400, outcome: 'failed', hint: expect.stringContaining('--preview needs an xAPI backend with preview support'), + }); + const other = { statusCode: 400, message: ['name must be a string'] }; + expect(actionErrorDetail(new HttpError(400, JSON.stringify(other), undefined, other))).not.toHaveProperty('hint'); + }); test('timeout stays unknown and warns against replaying a write', () => { expect(actionErrorDetail(new RequestTimeoutError(60_000))).toMatchObject({ code: 'REQUEST_TIMEOUT', outcome: 'unknown' }); }); diff --git a/src/tests/action.test.ts b/src/tests/action.test.ts index 37c6865..ad408ba 100644 --- a/src/tests/action.test.ts +++ b/src/tests/action.test.ts @@ -3,6 +3,9 @@ */ import { describe, it, expect, beforeEach, afterEach, spyOn } from 'bun:test'; +import { mkdtemp, rm } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; import * as client from '../client.ts'; import * as format from '../format.ts'; import * as config from '../config.ts'; @@ -736,3 +739,83 @@ describe('action commands', () => { }); }); }); + +describe('--preview flag on the wire', () => { + let fetchSpy: ReturnType; + let cfgSpy: ReturnType; + let outputSpy: ReturnType; + let writeSpy: ReturnType; + let dir: string; + const requests: Array<{ url: URL; body: any }> = []; + + beforeEach(async () => { + requests.length = 0; + dir = await mkdtemp(join(tmpdir(), 'xapi-preview-')); + cfgSpy = spyOn(config, 'getConfig').mockReturnValue({ actionHost: 'action.xapi.to', apiKey: 'sk-test' }); + outputSpy = spyOn(format, 'output').mockImplementation(() => {}); + writeSpy = spyOn(process.stdout, 'write').mockImplementation(() => true); + fetchSpy = spyOn(globalThis, 'fetch').mockImplementation((async (url: any, init: RequestInit) => { + const body = init.body ? JSON.parse(String(init.body)) : undefined; + requests.push({ url: new URL(String(url)), body }); + if (String(url).endsWith('/v1/actions/batch')) { + return new Response(JSON.stringify({ actions: [{ id: 'svc.op', method: 'GET' }], missing_ids: [] }), { + status: 200, headers: { 'content-type': 'application/json' }, + }); + } + const contentType = body?.stream ? 'text/event-stream' : 'application/json'; + return new Response(body?.stream ? 'data: {}\n\n' : JSON.stringify({ success: true, data: {} }), { + status: 200, headers: { 'content-type': contentType }, + }); + }) as any); + }); + + afterEach(async () => { + fetchSpy.mockRestore(); cfgSpy.mockRestore(); outputSpy.mockRestore(); writeSpy.mockRestore(); + await rm(dir, { recursive: true, force: true }); + }); + + for (const [name, run] of [ + ['list', (flags: Record) => actionList([], flags)], + ['search', (flags: Record) => actionSearch(['x'], flags)], + ['services', (flags: Record) => actionServices([], flags)], + ['categories', (flags: Record) => actionCategories([], flags)], + ] as const) { + it(`${name} sends include_preview=true only with --preview`, async () => { + await run({}); + await run({ preview: 'true' }); + expect(requests[0].url.searchParams.has('include_preview')).toBe(false); + expect(requests[1].url.searchParams.get('include_preview')).toBe('true'); + }); + } + + for (const [name, run] of [ + ['get', (flags: Record) => actionGet(['svc.op'], flags)], + ['get-batch', (flags: Record) => actionBatchGet(['svc.op', 'svc.other'], flags)], + ] as const) { + it(`${name} sends include_preview in the batch body only with --preview`, async () => { + await run({}); + await run({ preview: 'true' }); + expect(requests.map((r) => r.url.pathname)).toEqual(['/v1/actions/batch', '/v1/actions/batch']); + expect('include_preview' in requests[0].body).toBe(false); + expect(requests[1].body.include_preview).toBe(true); + expect(requests[1].url.searchParams.has('include_preview')).toBe(false); + }); + } + + for (const [mode, flags] of [ + ['json', {}], + ['stream', { stream: 'true' }], + ['output', { output: 'out.bin' }], + ['output-json', { 'output-json': 'out.json' }], + ] as const) { + it(`call (${mode}) sends include_preview in the execute body only with --preview`, async () => { + const withPaths = (suffix: string) => Object.fromEntries(Object.entries(flags) + .map(([k, v]) => [k, k.startsWith('output') ? join(dir, suffix + v) : v])); + await actionCall(['svc.op'], { input: '{}', ...withPaths('a-') }); + await actionCall(['svc.op'], { input: '{}', preview: 'true', ...withPaths('b-') }); + expect(requests.map((r) => r.url.pathname)).toEqual(['/v1/actions/execute', '/v1/actions/execute']); + expect('include_preview' in requests[0].body).toBe(false); + expect(requests[1].body.include_preview).toBe(true); + }); + } +}); diff --git a/src/tests/client.test.ts b/src/tests/client.test.ts index e9d0f7f..491747b 100644 --- a/src/tests/client.test.ts +++ b/src/tests/client.test.ts @@ -458,3 +458,14 @@ try { expect(result.stdout).toContain('Node moving/stalled uploads: passed'); } finally {rmSync(root,{recursive:true,force:true});} }); + +import { withPreviewHint } from '../client.ts'; + +describe('withPreviewHint', () => { + it('explains the 400 an older backend returns for include_preview', () => { + const msg = '{"message":["property include_preview should not exist"],"statusCode":400}'; + expect(withPreviewHint(400, msg)).toContain('--preview needs an xAPI backend with preview support'); + expect(withPreviewHint(400, 'bad input')).toBe('bad input'); + expect(withPreviewHint(404, msg)).toBe(msg); + }); +}); diff --git a/src/tests/codegen.test.ts b/src/tests/codegen.test.ts index ea595d1..0de45a8 100644 --- a/src/tests/codegen.test.ts +++ b/src/tests/codegen.test.ts @@ -149,6 +149,15 @@ describe('generateCode', () => { }); }); + describe('--preview', () => { + it('adds include_preview to every snippet only when requested', () => { + for (const target of ['curl', 'python', 'python.httpx', 'javascript', 'javascript.axios', 'typescript', 'go']) { + expect(generateCode(target, { ...params, includePreview: true }).code).toContain('include_preview'); + expect(generateCode(target, params).code).not.toContain('include_preview'); + } + }); + }); + describe('python', () => { it('generates requests code', () => { const result = generateCode('python', params); diff --git a/src/tests/provider-onboarding.test.ts b/src/tests/provider-onboarding.test.ts index c0d2d69..62105c0 100644 --- a/src/tests/provider-onboarding.test.ts +++ b/src/tests/provider-onboarding.test.ts @@ -61,7 +61,7 @@ describe('provider lifecycle commands', () => { expect(call.url).toStartWith('https://api.xapi.to/api/api-services/agent/'); if (call.url.endsWith('register-api-service')) return json({ success: true, apiService: { id: 'svc-1', activeVersionId: 'rev-1', activeVersion: { id: 'rev-1', state: 'DRAFT' } }, validation: { warnings: [] } }, 201); - if (call.method === 'PATCH') return json({ id: 'rev-1', state: 'SANDBOX', ...call.body }); + if (call.method === 'PATCH') return json({ id: 'rev-1', state: 'PREVIEW', ...call.body }); if (call.url.endsWith('/submit')) return json({ state: 'IN_REVIEW', willReview: true }); return json(report(++polls === 1 ? 'IN_REVIEW' : 'PUBLISHED')); }; @@ -98,7 +98,7 @@ describe('provider lifecycle commands', () => { }); it('imports YAML with its schema, auth, extensions and server-side Swagger conversion intact', async () => { - respond = () => json({ success: true, apiService: { id: 'svc', activeVersion: { id: 'rev', state: 'SANDBOX' } } }); + respond = () => json({ success: true, apiService: { id: 'svc', activeVersion: { id: 'rev', state: 'PREVIEW' } } }); const path = join(dir, 'openapi.yaml'); await writeFile(path, `openapi: 3.0.3 info: @@ -197,7 +197,7 @@ paths: }); it('guards endpoint merges while allowing explicit additions and full replacements', async () => { - respond = () => json({ state: 'SANDBOX' }); + respond = () => json({ state: 'PREVIEW' }); const path = await file({ endpoints: [{ name: 'search', method: 'GET', path: '/search' }] }); await expect(provider(['update', 'svc'], { file: path, revision: 'rev-1' })).rejects.toThrow('cli error'); expect(calls).toHaveLength(0); @@ -280,7 +280,7 @@ paths: it('explains the backend immutable-revision conflict without echoing server input', async () => { respond = () => json({ code: 'REVISION_NOT_EDITABLE', message: 'private-secret', state: 'PUBLISHED' }, 409); await expect(provider(['update', 'svc'], { revision: 'rev-1', file: await file({ description: 'changed' }) })).rejects.toThrow('cli error'); - expect(errSpy.mock.calls[0][1]).toContain('Only DRAFT or SANDBOX'); + expect(errSpy.mock.calls[0][1]).toContain('Only DRAFT or PREVIEW'); expect(errSpy.mock.calls[0][1]).not.toContain('private-secret'); expect(calls).toHaveLength(1); }); @@ -293,11 +293,14 @@ paths: }); for (const [state, review, reason] of [ + ['PREVIEW', { status: 'AUTO_FAILED', outcome: 'rejected' }, 'rejected'], + ['PREVIEW', null, 'not_published'], + // Pre-rename backends still report SANDBOX during the transition. ['SANDBOX', { status: 'AUTO_FAILED', outcome: 'rejected' }, 'rejected'], ['IN_REVIEW', { status: 'PENDING_HUMAN', outcome: 'pending_human' }, 'manual_review_required'], ['DRAFT', null, 'not_published'], ['SUSPENDED', null, 'not_published'], ] as const) { - it(`returns nonzero for ${state}/${reason}`, async () => { + it(`returns nonzero for ${state}/${reason}${review ? '' : ' without review'}`, async () => { respond = () => json(report(state, review)); await provider(['wait', 'svc'], { revision: 'rev-1' }); expect(process.exitCode).toBe(1);