Skip to content

cURL Command Builder — Swift source

Compose a copy-paste curl command from a form: method, headers, body, auth and flags — values POSIX-quoted safely. Paste an existing command to import it back. Runs locally with a shareable link.

This is the Swift implementation — the same logic the interactive tool runs, in a shareable, citable form.

// curl-builder — structured input → copy-paste curl command + reverse parser.
// Swift port (canonical TS: src/lib/curl-builder.ts; Go twin:
// cli/curl-builder). Swift standard library only, no Foundation. Composes a
// copy-paste curl command from structured input; also parses an existing
// command back into the structure (round-trip). Values are single-quoted
// with embedded quotes escaped (' → '\'') — safe for POSIX shells. The flag
// order is fixed and deterministic: method (-X) → headers (-H, insertion
// order) → auth (-u) → data (-d) → boolean flags (-I -k -L --compressed) →
// the URL last. Absent optional fields are nil; nil data is treated like ""
// (omitted). Never traps on malformed input — errors travel in the result's
// optional error (nil on success).

struct CurlHeader { var key: String; var value: String }
struct CurlAuth { var user: String; var password: String }

struct CurlRequest {
    var url = ""
    var method: String?              // nil = GET
    var headers: [CurlHeader] = []   // insertion order kept
    var data: String?                // nil or "" → omitted
    var auth: CurlAuth?              // nil = absent
    var headOnly = false
    var insecure = false
    var followRedirects = false
    var compressed = false
}

struct CurlBuildResult { var command = ""; var error: String? }
struct ParsedCurl { var request: CurlRequest; var unknownFlags: [String] }
struct CurlParseResult { var parsed: ParsedCurl?; var error: String? }

private let methods = ["GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"]

private func trimWS(_ s: String) -> String {
    let ws: Set<Character> = [" ", "\t", "\n", "\r"]
    var chars = Array(s)
    while let f = chars.first, ws.contains(f) { chars.removeFirst() }
    while let l = chars.last, ws.contains(l) { chars.removeLast() }
    return String(chars)
}

private func isHeaderKey(_ k: String) -> Bool {
    !k.isEmpty && k.allSatisfy { c in (c.isASCII && (c.isLetter || c.isNumber)) || c == "-" }
}

/// POSIX single-quote a value: ' → '\'' (close, escaped quote, reopen).
func shellQuote(_ value: String) -> String {
    var out = "'"
    for ch in value { out += ch == "'" ? "'\\''" : String(ch) }
    return out + "'"
}

/// Build the curl command. URL required; method/header names validated.
func buildCurlCommand(_ req: CurlRequest) -> CurlBuildResult {
    func fail(_ e: String) -> CurlBuildResult { CurlBuildResult(command: "", error: e) }
    let url = trimWS(req.url)
    if url.isEmpty { return fail("A URL is required") }
    let ok = url.hasPrefix("http://") || url.hasPrefix("https://") ||
        url.hasPrefix("/") || url.hasPrefix("$")
    if !ok { return fail("URL must start with http://, https://, / or $ (a variable)") }
    let rawMethod = req.method ?? "GET"
    let method = rawMethod.uppercased()
    if !methods.contains(method) {
        // TS prints the raw method in the message ("undefined" when absent).
        return fail("unsupported method \(rawMethod) (use \(methods.joined(separator: ", ")))")
    }
    for h in req.headers where !isHeaderKey(h.key) {
        return fail("invalid header name \"\(h.key)\" (letters, digits and hyphens only)")
    }
    var parts = ["curl"]
    if method != "GET" { parts.append("-X \(method)") }
    for h in req.headers { parts.append("-H " + shellQuote("\(h.key): \(h.value)")) }
    if let a = req.auth { parts.append("-u " + shellQuote("\(a.user):\(a.password)")) }
    if let d = req.data, !d.isEmpty { parts.append("-d " + shellQuote(d)) }
    if req.headOnly { parts.append("-I") }
    if req.insecure { parts.append("-k") }
    if req.followRedirects { parts.append("-L") }
    if req.compressed { parts.append("--compressed") }
    parts.append(shellQuote(url))
    return CurlBuildResult(command: parts.joined(separator: " "), error: nil)
}

/// Shell word-split respecting single and double quotes.
func splitWords(_ line: String) -> [String] {
    var words: [String] = []
    var cur = ""
    var quote: Character?
    var has = false
    for ch in line {
        if let q = quote {
            if ch == q { quote = nil } else { cur.append(ch) }
        } else if ch == "'" || ch == "\"" {
            quote = ch
            has = true
        } else if ch == " " || ch == "\t" {
            if !cur.isEmpty || has { words.append(cur) }
            cur = ""
            has = false
        } else {
            cur.append(ch)
            has = true
        }
    }
    if has { words.append(cur) } // any accumulated characters imply has
    return words
}

/// TS replace(/\\\n/g, ' '): a backslash-newline becomes one space.
private func replacingBackslashNewline(_ s: String) -> String {
    var out = ""
    var pending = false
    for ch in s {
        if pending {
            if ch == "\n" { out.append(" ") } else { out.append("\\"); out.append(ch) }
            pending = false
        } else if ch == "\\" {
            pending = true
        } else {
            out.append(ch)
        }
    }
    if pending { out.append("\\") }
    return out
}

/// Parse a curl command line back into a request (best effort, ordered).
func parseCurlCommand(_ line: String) -> CurlParseResult {
    let trimmed = trimWS(line)
    if trimmed.isEmpty { return CurlParseResult(parsed: nil, error: "A command is required") }
    let words = splitWords(replacingBackslashNewline(trimmed))
    guard words.first == "curl" else {
        return CurlParseResult(parsed: nil, error: "command must start with curl")
    }
    var req = CurlRequest()
    var unknownFlags: [String] = []
    var i = 1
    func next() -> String? { i += 1; return i < words.count ? words[i] : nil }
    while i < words.count {
        let w = words[i]
        if w == "-X" || w == "--request" {
            req.method = next()
        } else if w == "-H" || w == "--header" {
            if let raw = next() {
                if let at = raw.firstIndex(of: ":"), at != raw.startIndex {
                    req.headers.append(CurlHeader(
                        key: trimWS(String(raw[raw.startIndex..<at])),
                        value: trimWS(String(raw[raw.index(after: at)...]))))
                }
            }
        } else if w == "-u" || w == "--user" {
            if let raw = next() {
                if let at = raw.firstIndex(of: ":") {
                    req.auth = CurlAuth(user: String(raw[raw.startIndex..<at]),
                                        password: String(raw[raw.index(after: at)...]))
                } else {
                    req.auth = CurlAuth(user: raw, password: "")
                }
            }
        } else if w == "-d" || w == "--data" {
            req.data = next()
        } else if w == "-I" || w == "--head" {
            req.headOnly = true
        } else if w == "-k" || w == "--insecure" {
            req.insecure = true
        } else if w == "-L" || w == "--location" {
            req.followRedirects = true
        } else if w == "--compressed" {
            req.compressed = true
        } else if w.hasPrefix("-") {
            unknownFlags.append(w)
        } else {
            req.url = w
        }
        i += 1
    }
    if req.url.isEmpty { return CurlParseResult(parsed: nil, error: "no URL found in command") }
    return CurlParseResult(parsed: ParsedCurl(request: req, unknownFlags: unknownFlags), error: nil)
}

// Example:
// shellQuote("it's") → "'it'\\''s'"
// buildCurlCommand(CurlRequest(url: "https://api.example.com", method: "post",
//     headers: [CurlHeader(key: "X-Tag", value: "it's")], data: "k=v")).command
// → "curl -X POST -H 'X-Tag: it'\\''s' -d 'k=v' 'https://api.example.com'"

Also available in 13 other languages

Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →