UNPKG

@deepgram/deepdown-utils

Version:

Utility functions for Deepdown markdown templating

271 lines (270 loc) 10.2 kB
"use strict"; /** * Utility for generating curl authentication examples * Compatible with both OpenAPI and AsyncAPI security schemes */ Object.defineProperty(exports, "__esModule", { value: true }); exports.generateCurlAuth = generateCurlAuth; exports.formatCurlAuthArgs = formatCurlAuthArgs; exports.formatCurlCommand = formatCurlCommand; exports.createCurlAuthHelper = createCurlAuthHelper; const defaultOptions = { includeComments: true, placeholderStyle: 'uppercase', useShortFlags: true, indentSize: 2 }; /** * Creates a placeholder value based on the name and style preference */ function createPlaceholder(name, style) { switch (style) { case 'uppercase': return `YOUR_${name.toUpperCase().replace(/[^A-Z0-9]/g, '_')}`; case 'camelCase': return `your${name.charAt(0).toUpperCase() + name.slice(1).replace(/[^a-zA-Z0-9]/g, '')}`; case 'placeholder': return `{${name}}`; default: return `YOUR_${name.toUpperCase().replace(/[^A-Z0-9]/g, '_')}`; } } /** * Generates curl authentication examples for a security scheme */ function generateCurlAuth(securityRequirement, options = {}) { const opts = { ...defaultOptions, ...options }; const scheme = securityRequirement.scheme; const schemeType = scheme.type.toLowerCase(); // Check if its an OpenAPI-style API key if (schemeType === 'apikey') { return generateApiKeyCurlAuth(scheme, opts); } // AsyncAPI-specific httpApiKey if (schemeType === 'httpapikey') { return generateApiKeyCurlAuth(scheme, opts); } // HTTP auth (both OpenAPI and AsyncAPI) if (schemeType === 'http') { return generateHttpCurlAuth(scheme, opts); } // OAuth2 (both OpenAPI and AsyncAPI) if (schemeType === 'oauth2') { return generateOAuth2CurlAuth(securityRequirement, opts); } // OpenID Connect (both OpenAPI and AsyncAPI) if (schemeType === 'openidconnect') { return { headers: [{ name: 'Authorization', value: `Bearer ${createPlaceholder('access_token', opts.placeholderStyle)}` }], description: `OpenID Connect: Uses an OAuth2 token retrieved from ${scheme.openIdConnectUrl}` }; } // AsyncAPI specific types if (['symmetric', 'asymmetric', 'plain', 'x509'].includes(schemeType)) { return generateAsyncAPISpecificAuth(scheme, opts); } // Default fallback return { description: `Authentication type "${schemeType}" with scheme name "${securityRequirement.name}"` }; } /** * Generates curl auth for API key schemes */ function generateApiKeyCurlAuth(scheme, options) { const location = scheme.in?.toLowerCase() || 'header'; const keyName = scheme.name || 'api_key'; const keyValue = createPlaceholder(keyName.replace(/[-_]/g, ''), options.placeholderStyle); switch (location) { case 'header': return { headers: [{ name: keyName, value: keyValue }], description: `API key authentication via ${keyName} header` }; case 'query': return { queryParams: [{ name: keyName, value: keyValue }], description: `API key authentication via ${keyName} query parameter` }; case 'cookie': return { cookies: [{ name: keyName, value: keyValue }], description: `API key authentication via ${keyName} cookie` }; default: return { description: `API key authentication in unknown location: ${location}` }; } } /** * Generates curl auth for HTTP authentication schemes */ function generateHttpCurlAuth(scheme, options) { const httpScheme = scheme.scheme?.toLowerCase() || 'bearer'; switch (httpScheme) { case 'basic': return { basicAuth: { username: createPlaceholder('username', options.placeholderStyle), password: createPlaceholder('password', options.placeholderStyle) }, description: 'HTTP Basic authentication' }; case 'bearer': const format = scheme.bearerFormat ? ` (${scheme.bearerFormat})` : ''; return { headers: [{ name: 'Authorization', value: `Bearer ${createPlaceholder('token', options.placeholderStyle)}` }], description: `HTTP Bearer${format} authentication` }; case 'digest': return { headers: [{ name: 'Authorization', value: `Digest ${createPlaceholder('digest_credentials', options.placeholderStyle)}` }], description: 'HTTP Digest authentication' }; default: return { headers: [{ name: 'Authorization', value: `${httpScheme.charAt(0).toUpperCase() + httpScheme.slice(1)} ${createPlaceholder('credentials', options.placeholderStyle)}` }], description: `HTTP ${httpScheme} authentication` }; } } /** * Generates curl auth for OAuth2 authentication */ function generateOAuth2CurlAuth(securityRequirement, options) { const scheme = securityRequirement.scheme; const scopes = securityRequirement.scopes || []; const scopeText = scopes.length > 0 ? ` with scopes: ${scopes.join(', ')}` : ''; return { headers: [{ name: 'Authorization', value: `Bearer ${createPlaceholder('access_token', options.placeholderStyle)}` }], description: `OAuth 2.0 authentication${scopeText}` }; } /** * Generates curl auth for AsyncAPI-specific authentication types */ function generateAsyncAPISpecificAuth(scheme, options) { const schemeType = scheme.type.toLowerCase(); switch (schemeType) { case 'plain': // Plain authentication typically uses username/password return { headers: [{ name: 'Authorization', value: `Plain ${createPlaceholder('credentials', options.placeholderStyle)}` }], description: 'Plain text authentication' }; case 'symmetric': // Symmetric encryption typically uses a shared secret return { headers: [{ name: 'Authorization', value: `${createPlaceholder('symmetric_key', options.placeholderStyle)}` }], description: 'Symmetric key authentication' }; case 'asymmetric': // Asymmetric encryption typically uses public/private keys return { headers: [{ name: 'Authorization', value: `${createPlaceholder('signature', options.placeholderStyle)}` }], description: 'Asymmetric key signature authentication' }; case 'x509': // X.509 certificates are typically provided as client certificates return { description: 'X.509 client certificate authentication (requires -E/--cert option in curl)' }; default: return { description: `AsyncAPI-specific ${schemeType} authentication` }; } } /** * Formats auth information as curl command-line arguments */ function formatCurlAuthArgs(auth, options = {}) { const opts = { ...defaultOptions, ...options }; const parts = []; const indent = ' '.repeat(opts.indentSize || 2); // Add basic auth if present if (auth.basicAuth) { const flag = opts.useShortFlags ? '-u' : '--user'; parts.push(`${flag} ${auth.basicAuth.username}:${auth.basicAuth.password}`); } // Add headers if present if (auth.headers && auth.headers.length > 0) { const flag = opts.useShortFlags ? '-H' : '--header'; auth.headers.forEach(header => { parts.push(`${flag} "${header.name}: ${header.value}"`); }); } // Add cookies if present if (auth.cookies && auth.cookies.length > 0) { const flag = opts.useShortFlags ? '-b' : '--cookie'; const cookies = auth.cookies.map(cookie => `${cookie.name}=${cookie.value}`).join('; '); parts.push(`${flag} "${cookies}"`); } // Return formatted curl args return parts.join(` \\\n${indent}`); } /** * Formats the full curl command including URL and query parameters */ function formatCurlCommand(url, auth, options = {}) { const opts = { ...defaultOptions, ...options }; const indent = ' '.repeat(opts.indentSize || 2); const authArgs = formatCurlAuthArgs(auth, opts); let fullUrl = url; // Add query parameters if present if (auth.queryParams && auth.queryParams.length > 0) { const separator = url.includes('?') ? '&' : '?'; const queryString = auth.queryParams .map(param => `${param.name}=${encodeURIComponent(param.value)}`) .join('&'); fullUrl = `${url}${separator}${queryString}`; } // Format final command const command = [`curl${authArgs ? ` \\\n${indent}${authArgs}` : ''} \\\n${indent}"${fullUrl}"`]; // Add description as comment if enabled if (opts.includeComments && auth.description) { command.unshift(`# ${auth.description}`); } return command.join('\n'); } /** * Creates a Handlebars helper function for use in templates */ function createCurlAuthHelper() { return function (securityScheme, securityName, scopes = []) { const requirement = { name: securityName, scopes: scopes, scheme: securityScheme }; return formatCurlAuthArgs(generateCurlAuth(requirement)); }; } exports.default = { generateCurlAuth, formatCurlAuthArgs, formatCurlCommand, createCurlAuthHelper };