Repository Public
1// Explorateur d'API — exemples de code (cURL, TypeScript, Python) d'une requête. Le jeton n'y figure JAMAIS : toujours la2// variable d'environnement `$SPMAIL_API_KEY`, et tout ce qui ressemble à un jeton dans les entrées est remplacé par elle.3import type { Json } from "./openapi"45export const KEY_PLACEHOLDER = "$SPMAIL_API_KEY"6export const KEY_ENV = "SPMAIL_API_KEY"78export interface SnippetRequest {9 method: string10 /** URL absolue (origine + chemin + chaîne de requête) */11 url: string12 /** en-têtes propres à la requête (Idempotency-Key…) ; Authorization et Cookie sont toujours écartés */13 headers?: Record<string, string>14 /** corps JSON */15 body?: Json16 /** téléversement binaire : le corps est le contenu d'un fichier local */17 file?: { name: string; type: string }18 /** faux pour une route publique : aucun en-tête Authorization */19 auth?: boolean20 /** valeurs secrètes connues de l'appelant (jeton d'exploration…) à retirer si elles apparaissaient où que ce soit */21 secrets?: readonly string[]22}2324const TOKEN_RE = /sp[mx]_[A-Za-z0-9_-]{6,}/g25/** Remplace tout jeton (forme `spm_…` / `spx_…`, ou valeur secrète fournie) par le nom de la variable d'environnement. */26export function redact(text: string, secrets: readonly string[] = []): string {27 let out = text28 for (const s of [...secrets].filter((x) => x.length >= 4).sort((a, b) => b.length - a.length)) out = out.split(s).join(KEY_PLACEHOLDER)29 return out.replace(TOKEN_RE, KEY_PLACEHOLDER)30}3132const FORBIDDEN = new Set(["authorization", "cookie", "proxy-authorization", "x-spmail"])33const cleanHeaders = (h: Record<string, string> | undefined): [string, string][] => Object.entries(h ?? {}).filter(([k]) => !FORBIDDEN.has(k.toLowerCase()))34const shq = (s: string) => `'${s.replace(/'/g, `'\\''`)}'`3536export function curlSnippet(r: SnippetRequest): string {37 const lines = [`curl -sS -X ${r.method.toUpperCase()} ${shq(r.url)}`]38 if (r.auth !== false) lines.push(` -H "Authorization: Bearer ${KEY_PLACEHOLDER}"`)39 for (const [k, v] of cleanHeaders(r.headers)) lines.push(` -H ${shq(`${k}: ${v}`)}`)40 if (r.file) lines.push(` -H ${shq(`Content-Type: ${r.file.type || "application/octet-stream"}`)}`, ` --data-binary ${shq(`@${r.file.name}`)}`)41 else if (r.body !== undefined) lines.push(` -H 'Content-Type: application/json'`, ` --data ${shq(JSON.stringify(r.body, null, 2))}`)42 return redact(lines.join(" \\\n"), r.secrets)43}4445export function tsSnippet(r: SnippetRequest): string {46 const headers: string[] = []47 if (r.auth !== false) headers.push(` Authorization: \`Bearer \${process.env.${KEY_ENV}}\`,`)48 for (const [k, v] of cleanHeaders(r.headers)) headers.push(` ${JSON.stringify(k)}: ${JSON.stringify(v)},`)49 if (r.file) headers.push(` "Content-Type": ${JSON.stringify(r.file.type || "application/octet-stream")},`)50 else if (r.body !== undefined) headers.push(` "Content-Type": "application/json",`)51 const out: string[] = []52 if (r.file) out.push(`import { readFile } from "node:fs/promises"`, ``)53 out.push(`const response = await fetch(${JSON.stringify(r.url)}, {`, ` method: ${JSON.stringify(r.method.toUpperCase())},`)54 if (headers.length) out.push(` headers: {`, ...headers, ` },`)55 if (r.file) out.push(` body: await readFile(${JSON.stringify(r.file.name)}),`)56 else if (r.body !== undefined) out.push(` body: JSON.stringify(${JSON.stringify(r.body, null, 2).split("\n").join("\n ")}),`)57 out.push(`})`, `if (!response.ok) throw new Error(\`SP Mail API: \${response.status} \${await response.text()}\`)`, `console.log(response.status, response.headers.get("x-request-id"))`)58 out.push(`const data = response.headers.get("content-type")?.includes("json") ? await response.json() : await response.arrayBuffer()`, `console.log(data)`)59 return redact(out.join("\n"), r.secrets)60}6162/** Littéral Python d'une valeur JSON (True / False / None). */63export function pyLiteral(v: Json, indent = 0): string {64 const pad = " ".repeat(indent + 1)65 const end = " ".repeat(indent)66 if (v === null) return "None"67 if (typeof v === "boolean") return v ? "True" : "False"68 if (typeof v === "number") return Number.isFinite(v) ? String(v) : "None"69 if (typeof v === "string") return JSON.stringify(v)70 if (Array.isArray(v)) return v.length ? `[\n${v.map((x) => `${pad}${pyLiteral(x, indent + 1)},`).join("\n")}\n${end}]` : "[]"71 const entries = Object.entries(v)72 return entries.length ? `{\n${entries.map(([k, x]) => `${pad}${pyLiteral(k)}: ${pyLiteral(x, indent + 1)},`).join("\n")}\n${end}}` : "{}"73}7475export function pySnippet(r: SnippetRequest): string {76 const headers: string[] = []77 if (r.auth !== false) headers.push(` "Authorization": f"Bearer {os.environ['${KEY_ENV}']}",`)78 for (const [k, v] of cleanHeaders(r.headers)) headers.push(` ${pyLiteral(k)}: ${pyLiteral(v)},`)79 if (r.file) headers.push(` "Content-Type": ${pyLiteral(r.file.type || "application/octet-stream")},`)80 const out = [`import os`, `import requests`, ``]81 if (r.file) out.push(`with open(${pyLiteral(r.file.name)}, "rb") as f:`, ` payload = f.read()`, ``)82 out.push(`response = requests.request(`, ` ${pyLiteral(r.method.toUpperCase())},`, ` ${pyLiteral(r.url)},`)83 if (headers.length) out.push(` headers={`, ...headers, ` },`)84 if (r.file) out.push(` data=payload,`)85 else if (r.body !== undefined) out.push(` json=${pyLiteral(r.body, 1)},`)86 out.push(` timeout=30,`, `)`, `print(response.status_code, response.headers.get("X-Request-Id"))`, `response.raise_for_status()`)87 out.push(`print(response.json() if "json" in response.headers.get("Content-Type", "") else len(response.content))`)88 return redact(out.join("\n"), r.secrets)89}9091export type SnippetLang = "curl" | "ts" | "python"92export const snippet = (lang: SnippetLang, r: SnippetRequest): string => (lang === "curl" ? curlSnippet(r) : lang === "ts" ? tsSnippet(r) : pySnippet(r))93