Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

4.9 KB
Raw Blame
// Operations -> handlers.js source text.
//
// All per-operation data (path, parameter locations, auth) is embedded as a
// JSON literal, not interpolated into executable code; the only hand-written
// logic is the single generic `callOperation` executor shared by every tool.
// That keeps spec-controlled strings (titles, descriptions, param names) out
// of anything that runs as code.

/** Pick the security scheme that applies to an operation, if any. */
function resolveAuth(op, securitySchemes) {
	for (const requirement of op.security || []) {
		for (const schemeName of Object.keys(requirement)) {
			const scheme = securitySchemes[schemeName];
			if (!scheme) continue;
			const secret = `AUTH_${schemeName}`.toUpperCase().replace(/[^A-Z0-9_]/g, '_');
			if (scheme.type === 'apiKey') {
				return { kind: 'apiKey', in: scheme.in, name: scheme.name, secret };
			}
			if (scheme.type === 'http' && scheme.scheme === 'basic') {
				return { kind: 'basic', secret };
			}
			// http bearer, oauth2, openIdConnect: all resolve to a bearer token
			// the caller obtains out of band and stores under this secret name.
			return { kind: 'bearer', secret };
		}
	}
	return null;
}

/** A server URL can be relative to the document that declared it (common for
 * specs served alongside the API they describe, e.g. Swagger's own demo). */
function resolveBaseUrl(serverUrl, sourceUrl) {
	if (!serverUrl) return sourceUrl ? new URL(sourceUrl).origin : '';
	try {
		return new URL(serverUrl, sourceUrl).toString().replace(/\/$/, '');
	} catch {
		return serverUrl;
	}
}

/**
 * @param {Array} operations from listOperations()
 * @param {object} doc parsed OpenAPI document (for servers + securitySchemes)
 * @param {{sourceUrl?: string}} opts
 * @returns {{ source: string, secrets: string[] }}
 */
export function generateHandlers(operations, doc, opts = {}) {
	const baseUrl = resolveBaseUrl(doc.servers?.[0]?.url, opts.sourceUrl);
	const securitySchemes = doc.components?.securitySchemes || {};
	const secrets = new Set();

	const specs = {};
	for (const op of operations) {
		const auth = resolveAuth(op, securitySchemes);
		if (auth) secrets.add(auth.secret);
		specs[op.operationId] = {
			method: op.method,
			path: op.path,
			parameters: op.parameters.map((p) => ({ name: p.name, in: p.in })),
			hasBody: Boolean(op.requestBody),
			auth,
		};
	}

	const exportedFns = Object.keys(specs)
		.map(
			(name) =>
				`export async function ${name}(args, ctx) {\n\treturn callOperation(OPERATIONS[${JSON.stringify(name)}], args, ctx);\n}`
		)
		.join('\n\n');

	const source = `// Generated by @three-ws/skill-import. Do not hand-edit: regenerate from the source spec instead.

const BASE_URL = ${JSON.stringify(baseUrl)};

const OPERATIONS = ${JSON.stringify(specs, null, '\t')};

function applyAuth(auth, ctx, headers, query) {
	if (!auth) return;
	const secret = ctx?.secrets?.[auth.secret];
	if (!secret) {
		throw new Error(\`missing secret "\${auth.secret}" required by this skill\`);
	}
	if (auth.kind === 'apiKey' && auth.in === 'header') headers[auth.name] = secret;
	else if (auth.kind === 'apiKey' && auth.in === 'query') query[auth.name] = secret;
	else if (auth.kind === 'basic') headers.Authorization = \`Basic \${secret}\`;
	else headers.Authorization = \`Bearer \${secret}\`;
}

async function callOperation(spec, args, ctx) {
	const params = args && typeof args === 'object' ? args : {};
	let path = spec.path;
	const query = {};
	const headers = { Accept: 'application/json' };

	for (const p of spec.parameters) {
		const value = params[p.name];
		if (value === undefined || value === null) continue;
		if (p.in === 'path') path = path.replace(\`{\${p.name}}\`, encodeURIComponent(String(value)));
		else if (p.in === 'query') query[p.name] = value;
		else if (p.in === 'header') headers[p.name] = String(value);
	}

	applyAuth(spec.auth, ctx, headers, query);

	const search = new URLSearchParams();
	for (const [key, value] of Object.entries(query)) search.set(key, String(value));
	const qs = search.toString();
	const url = \`\${BASE_URL}\${path}\${qs ? \`?\${qs}\` : ''}\`;

	const init = { method: spec.method, headers };
	if (spec.hasBody && params.body !== undefined) {
		headers['Content-Type'] = 'application/json';
		init.body = JSON.stringify(params.body);
	}

	const res = await ctx.fetch(url, init);
	const contentType = res.headers?.get?.('content-type') || '';
	const raw = await res.text();
	let body = raw;
	if (contentType.includes('application/json') && raw) {
		// Some real APIs mislabel a plain-text body as application/json; trust
		// the bytes over the header rather than throwing on a boundary we don't
		// control.
		try {
			body = JSON.parse(raw);
		} catch {
			body = raw;
		}
	}
	if (!res.ok) {
		const message = typeof body === 'string' ? body : JSON.stringify(body);
		throw new Error(\`\${spec.method} \${path} failed: \${res.status} \${message}\`);
	}
	return body;
}

${exportedFns}
`;

	return { source, secrets: [...secrets] };
}