Skip to content

PWA Manifest Generator — Swift source

Assemble a valid Web App Manifest — name, colors, display mode, icon sizes, maskable purpose — with a stable key order and instant JSON you can copy or download.

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

// pwa-manifest — build a fixed-key-order manifest.json from form fields.
//
// Language: Swift (5.9+), Foundation only (this manifest builder is pure
// string work — no external packages exist to link)
// CosmoDev polyglot showcase port of the `pwa-manifest-generator` tool.
// Ported from src/lib/pwa-manifest.ts — display source, part of CosmoDev's
// polyglot tool pages. Same logic as this dir's typescript.ts and the live
// Go twin at cli/pwa-manifest-generator/pwa-manifest-generator.go.

import Foundation

/// Mirrors the ManifestInput interface in src/lib/pwa-manifest.ts.
struct ManifestInput {
    var name: String = ""
    var shortName: String = ""
    var description: String = ""
    var startUrl: String = ""
    var display: String = ""         // "" means absent
    var orientation: String = ""     // "" means absent
    var backgroundColor: String = ""
    var themeColor: String = ""
    /// Nil means "not provided" → default [192, 512]; an explicit empty
    /// array emits an empty icons array — the same distinction the TS lib
    /// draws with `??`.
    var iconSizes: [Int]? = nil
    /// Marks every icon purpose "maskable" instead of "any".
    var maskable: Bool = false
}

/// Mirrors the ManifestResult interface in src/lib/pwa-manifest.ts.
struct ManifestResult {
    var ok: Bool
    var errors: [String] = []
    var warnings: [String] = []
    var json: String = ""
}

/// Same contract as TS HEX = /^#[0-9a-fA-F]{6}$/. CharacterSet for the hex digits.
private let hexRe = try! NSRegularExpression(pattern: "^#[0-9a-fA-F]{6}$")

private func isHexColor(_ s: String) -> Bool {
    hexRe.firstMatch(in: s, range: NSRange(s.startIndex..., in: s)) != nil
}

/// Double-quote s exactly like JavaScript's JSON.stringify: escape ", \, and
/// the control characters (short escapes for \b \f \n \r \t, \u00xx for the
/// rest), leave everything else — including non-ASCII — untouched.
func jsonString(_ s: String) -> String {
    var out = "\""
    for scalar in s.unicodeScalars {
        switch scalar {
        case "\"": out += "\\\""
        case "\\": out += "\\\\"
        case "\u{0008}": out += "\\b"
        case "\u{000C}": out += "\\f"
        case "\n": out += "\\n"
        case "\r": out += "\\r"
        case "\t": out += "\\t"
        default:
            if scalar.value < 0x20 {
                out += String(format: "\\u%04x", scalar.value)
            } else {
                out.unicodeScalars.append(scalar)
            }
        }
    }
    out += "\""
    return out
}

/// The Swift twin of buildManifest() in src/lib/pwa-manifest.ts.
func buildManifest(_ input: ManifestInput) -> ManifestResult {
    var errors: [String] = []
    var warnings: [String] = []

    let name = input.name.trimmingCharacters(in: .whitespacesAndNewlines)
    let shortName = input.shortName.trimmingCharacters(in: .whitespacesAndNewlines)
    let description = input.description.trimmingCharacters(in: .whitespacesAndNewlines)
    let startUrl = input.startUrl.trimmingCharacters(in: .whitespacesAndNewlines)
    let backgroundColor = input.backgroundColor.trimmingCharacters(in: .whitespacesAndNewlines)
    let themeColor = input.themeColor.trimmingCharacters(in: .whitespacesAndNewlines)
    let sizes = input.iconSizes ?? [192, 512]

    if name.isEmpty { errors.append("name is required.") }
    if !backgroundColor.isEmpty && !isHexColor(backgroundColor) {
        errors.append("background_color must be a #rrggbb hex value.")
    }
    if !themeColor.isEmpty && !isHexColor(themeColor) {
        errors.append("theme_color must be a #rrggbb hex value.")
    }
    if sizes.contains(where: { $0 <= 0 }) {
        errors.append("icon sizes must be positive integers.")
    }
    var seenSizes = Set<Int>()
    for s in sizes {
        if !seenSizes.insert(s).inserted {
            errors.append("icon size \(s) is listed twice.")
        }
    }
    if !errors.isEmpty {
        return ManifestResult(ok: false, errors: errors, warnings: [], json: "")
    }

    let shortNameLen = shortName.unicodeScalars.count
    if shortNameLen > 12 {
        warnings.append("short_name is \(shortNameLen) characters — home-screen labels truncate around 12.")
    }

    var lines: [String] = []
    func add(_ key: String, _ value: String) {
        lines.append("  " + jsonString(key) + ": " + jsonString(value))
    }
    add("name", name)
    if !shortName.isEmpty { add("short_name", shortName) }
    if !description.isEmpty { add("description", description) }
    if !startUrl.isEmpty { add("start_url", startUrl) }
    if !input.display.isEmpty { add("display", input.display) }
    if !input.orientation.isEmpty { add("orientation", input.orientation) }
    if !backgroundColor.isEmpty { add("background_color", backgroundColor) }
    if !themeColor.isEmpty { add("theme_color", themeColor) }

    let purpose = input.maskable ? "maskable" : "any"
    let iconEntries: [String] = sizes.map { s in
        "    {\n"
            + "      \"src\": " + jsonString("icons/icon-\(s)x\(s).png") + ",\n"
            + "      \"sizes\": " + jsonString("\(s)x\(s)") + ",\n"
            + "      \"type\": \"image/png\",\n"
            + "      \"purpose\": " + jsonString(purpose) + "\n"
            + "    }"
    }

    var doc = "{\n"
    for line in lines { doc += line + ",\n" }
    if iconEntries.isEmpty {
        doc += "  \"icons\": []" // JSON.stringify renders an empty array inline
    } else {
        doc += "  \"icons\": [\n"
        doc += iconEntries.joined(separator: ",\n")
        doc += "\n  ]"
    }
    doc += "\n}\n"

    return ManifestResult(ok: true, errors: errors, warnings: warnings, json: doc)
}

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 →