// Drop-in Kotlin client library for the Production Board HTTP API. // // Save this file under your project as `ProdClient.kt`, in a // directory matching `package prod_client`, then call the // ProdClient class: // // import prod_client.ProdClient // // val c = ProdClient("pat_...") // val rows = c.accountList(mapOf("limit" to 20, "sort" to "-created_at")) // val fresh = c.accountCreate(mapOf("name" to "Example GmbH")) // // Every endpoint exposed by the HTTP API is wrapped as a typed method // on ProdClient. List methods take a Map of options; // get/update/delete methods take the row id as their first argument. // // Provided as-is, with no warranty. Vendor freely; modify as needed. // Targets Kotlin 1.9+ on JVM 11+; uses only the JDK (java.net.http). // // DO NOT EDIT THIS FILE MANUALLY - re-download from the docs site. // Local edits will be overwritten by the once-per-day version check. @file:Suppress("unused", "MemberVisibilityCanBePrivate", "ConstPropertyName") package prod_client import java.net.URI import java.net.URLEncoder import java.net.http.HttpClient import java.net.http.HttpRequest import java.net.http.HttpResponse import java.nio.charset.StandardCharsets import java.nio.file.Files import java.nio.file.Path import java.nio.file.Paths import java.time.Duration import java.util.UUID import java.util.concurrent.atomic.AtomicBoolean import kotlin.concurrent.thread class ApiException(val status: Int, message: String, val bodyRaw: String? = null) : RuntimeException("HTTP $status: $message") class ProdClient(token: String? = null) { companion object { const val APP_SLUG = "prod" const val APP_NAME = "Production Board" const val MODULE_NAME = "prod_client" const val CLIENT_VERSION = "0.3.12" const val LANGUAGE = "kotlin" private const val DEFAULT_BASE = "https://qtssystem.com" /** * Per-type metadata baked at generation time. Parse with your * preferred JSON library if you need the legal filters / sorts * / max_limit per model without an extra round-trip. */ const val TYPES_JSON = """{"board":{"ops":["list","read","create","update","delete"],"create_fields":["name","description","accent","settings","tags","columns"],"update_fields":["name","description","accent","settings","tags","columns"],"allowed_filters":["data__name","data__accent","data__tags","status","is_archived","owned_by"],"allowed_sorts":["created_at","updated_at","data__name"],"default_sort":"created_at","max_limit":50,"fields":[{"name":"name","type":"string","max_len":200},{"name":"tags","type":"tags"},{"name":"accent","type":"enum","values":["slate","gray","blue","indigo","violet","fuchsia","amber","orange","emerald","green","rose","red"]},{"name":"settings","type":"dict"},{"name":"description","type":"string","max_len":2000}]},"card":{"ops":["list","read","create","update","delete"],"create_fields":["title","description","status","position","priority","tags","assignee","due_date","board_id"],"update_fields":["title","description","status","position","priority","tags","assignee","due_date","board_id"],"allowed_filters":["data__status","data__priority","data__tags","data__assignee","data__board_id","status","is_archived","owned_by"],"allowed_sorts":["created_at","updated_at","data__position","data__status","data__priority","data__due_date"],"default_sort":"data__position","max_limit":200,"fields":[{"name":"tags","type":"tags"},{"name":"title","type":"string","max_len":200},{"name":"status","type":"string","max_len":64},{"name":"assignee","type":"string","max_len":64},{"name":"board_id","type":"string","max_len":64,"ref":{"type":"board","owned":true,"optional":true}},{"name":"due_date","type":"string","max_len":32},{"name":"position","type":"number"},{"name":"priority","type":"enum","values":["low","medium","high","critical"]},{"name":"description","type":"string","max_len":4000}]}}""" private val META_SENT_ONCE = AtomicBoolean(false) private val AUTOUPDATE_TRIED = AtomicBoolean(false) private val RETRYABLE = setOf(408, 425, 429, 500, 502, 503, 504) private const val MAX_RETRIES = 3 private fun stateDir(): Path? { val home = System.getProperty("user.home") ?: System.getenv("HOME") ?: System.getenv("USERPROFILE") ?: return null return try { val p = Paths.get(home, ".$MODULE_NAME") Files.createDirectories(p) p } catch (_: Exception) { null } } private fun loadOrMintDeviceId(): String { val d = stateDir() ?: return UUID.randomUUID().toString() val f = d.resolve("device.json") if (Files.exists(f)) { try { val raw = Files.readString(f, StandardCharsets.UTF_8) val did = jsonExtractString(raw, "device_id") if (!did.isNullOrEmpty() && did.length >= 32) return did } catch (_: Exception) { /* fall through */ } } val fresh = UUID.randomUUID().toString() try { Files.writeString(f, "{\"device_id\":\"$fresh\"}", StandardCharsets.UTF_8) } catch (_: Exception) {} return fresh } private fun autoupdateEnabled(): Boolean { val v = (System.getenv("XCLIENT_NO_AUTOUPDATE") ?: "").lowercase() return v != "1" && v != "true" && v != "yes" } private fun fingerprint(): Map { val tp = (System.getenv("TERM_PROGRAM") ?: "").lowercase() return mapOf( "kotlin_version" to KotlinVersion.CURRENT.toString(), "java_version" to System.getProperty("java.version"), "os" to System.getProperty("os.name"), "term_program" to System.getenv("TERM_PROGRAM"), "editor_env" to System.getenv("EDITOR"), "ci" to (System.getenv("CI") != null || System.getenv("GITHUB_ACTIONS") != null), "claude_code" to (System.getenv("CLAUDECODE") != null || System.getenv("CLAUDE_CODE_ENTRYPOINT") != null), "codex" to (System.getenv("CODEX_HOME") != null), "vscode" to (tp == "vscode" && System.getenv("CURSOR_TRACE_ID") == null), "cursor" to (System.getenv("CURSOR_TRACE_ID") != null), "antigravity" to (System.getenv("ANTIGRAVITY_TRACE_ID") != null), "jetbrains" to tp.contains("jetbrains"), ) } private fun originOf(uri: URI): String { val scheme = (uri.scheme ?: "").lowercase() val host = (uri.host ?: "").lowercase() val port = if (uri.port < 0) (if (scheme == "https") 443 else 80) else uri.port return "$scheme://$host:$port" } private fun backoffMillis(attempt: Int, retryAfter: String?): Long { if (!retryAfter.isNullOrEmpty()) { val v = retryAfter.toDoubleOrNull() if (v != null) return (minOf(v, 60.0) * 1000.0).toLong() } return (minOf(Math.pow(2.0, attempt.toDouble()), 60.0) * 1000.0).toLong() } // ── Tiny stdlib JSON helpers (encoder + extractor + decoder) ─ // The JDK ships no JSON parser. We hand-roll the bare minimum // so the library stays dependency-free; users wanting a full // model layer should plug Jackson / Moshi / kotlinx.serialization // around the Map we return. @Suppress("UNCHECKED_CAST") fun encodeJson(value: Any?): String = buildString { encodeAny(this, value) } private fun encodeAny(sb: StringBuilder, value: Any?) { when (value) { null -> sb.append("null") is String -> encodeString(sb, value) is Boolean, is Number -> sb.append(value.toString()) is Map<*, *> -> { sb.append("{") var first = true for ((k, v) in value) { if (!first) sb.append(",") encodeString(sb, k.toString()) sb.append(":") encodeAny(sb, v) first = false } sb.append("}") } is Iterable<*> -> { sb.append("[") var first = true for (v in value) { if (!first) sb.append(",") encodeAny(sb, v) first = false } sb.append("]") } is Array<*> -> encodeAny(sb, value.toList()) else -> encodeString(sb, value.toString()) } } private fun encodeString(sb: StringBuilder, s: String) { sb.append('"') for (c in s) { when (c) { '"' -> sb.append("\\\"") '\\' -> sb.append("\\\\") '\n' -> sb.append("\\n") '\r' -> sb.append("\\r") '\t' -> sb.append("\\t") else -> if (c.code < 0x20) sb.append("\\u%04x".format(c.code)) else sb.append(c) } } sb.append('"') } fun jsonExtractString(json: String?, key: String): String? { if (json == null) return null val needle = "\"$key\"" val idx = json.indexOf(needle); if (idx < 0) return null val colon = json.indexOf(':', idx + needle.length); if (colon < 0) return null var i = colon + 1 while (i < json.length && json[i].isWhitespace()) i++ if (i >= json.length || json[i] != '"') return null val out = StringBuilder() i++ while (i < json.length) { val c = json[i] if (c == '\\' && i + 1 < json.length) { val n = json[i + 1] when (n) { '"', '\\', '/' -> { out.append(n); i += 2 } 'n' -> { out.append('\n'); i += 2 } 't' -> { out.append('\t'); i += 2 } 'r' -> { out.append('\r'); i += 2 } else -> { out.append(n); i += 2 } } continue } if (c == '"') break out.append(c); i++ } return out.toString() } fun decodeJsonObject(json: String): Map { val pos = intArrayOf(0) return when (val v = parseJsonValue(json, pos)) { is Map<*, *> -> @Suppress("UNCHECKED_CAST") (v as Map) else -> mapOf("data" to v) } } private fun parseJsonValue(s: String, pos: IntArray): Any? { skipWs(s, pos) if (pos[0] >= s.length) return null return when (s[pos[0]]) { '{' -> parseJsonObject(s, pos) '[' -> parseJsonArray(s, pos) '"' -> parseJsonString(s, pos) 't', 'f' -> parseJsonBool(s, pos) 'n' -> { pos[0] += 4; null } else -> parseJsonNumber(s, pos) } } private fun parseJsonObject(s: String, pos: IntArray): MutableMap { val out = LinkedHashMap() pos[0]++ skipWs(s, pos) if (pos[0] < s.length && s[pos[0]] == '}') { pos[0]++; return out } while (pos[0] < s.length) { skipWs(s, pos) val key = parseJsonString(s, pos) ?: "" skipWs(s, pos) if (pos[0] < s.length && s[pos[0]] == ':') pos[0]++ out[key] = parseJsonValue(s, pos) skipWs(s, pos) if (pos[0] >= s.length) break val c = s[pos[0]] if (c == ',') { pos[0]++; continue } if (c == '}') { pos[0]++; break } } return out } private fun parseJsonArray(s: String, pos: IntArray): MutableList { val out = mutableListOf() pos[0]++ skipWs(s, pos) if (pos[0] < s.length && s[pos[0]] == ']') { pos[0]++; return out } while (pos[0] < s.length) { out.add(parseJsonValue(s, pos)) skipWs(s, pos) if (pos[0] >= s.length) break val c = s[pos[0]] if (c == ',') { pos[0]++; continue } if (c == ']') { pos[0]++; break } } return out } private fun parseJsonString(s: String, pos: IntArray): String? { if (pos[0] >= s.length || s[pos[0]] != '"') return null pos[0]++ val out = StringBuilder() while (pos[0] < s.length) { val c = s[pos[0]] if (c == '"') { pos[0]++; return out.toString() } if (c == '\\' && pos[0] + 1 < s.length) { val n = s[pos[0] + 1] pos[0] += 2 when (n) { '"' -> out.append('"') '\\' -> out.append('\\') '/' -> out.append('/') 'n' -> out.append('\n') 't' -> out.append('\t') 'r' -> out.append('\r') 'b' -> out.append('\b') 'f' -> out.append('\u000c') 'u' -> { if (pos[0] + 4 <= s.length) { try { out.append(Integer.parseInt(s.substring(pos[0], pos[0] + 4), 16).toChar()) pos[0] += 4 } catch (_: NumberFormatException) {} } } else -> out.append(n) } continue } out.append(c); pos[0]++ } return out.toString() } private fun parseJsonBool(s: String, pos: IntArray): Boolean? { if (s.startsWith("true", pos[0])) { pos[0] += 4; return true } if (s.startsWith("false", pos[0])) { pos[0] += 5; return false } pos[0]++ return null } private fun parseJsonNumber(s: String, pos: IntArray): Any? { val start = pos[0]; var fp = false while (pos[0] < s.length) { val c = s[pos[0]] if (c == '-' || c == '+' || c.isDigit()) pos[0]++ else if (c == '.' || c == 'e' || c == 'E') { fp = true; pos[0]++ } else break } val num = s.substring(start, pos[0]) return try { if (fp) num.toDouble() else num.toLong() } catch (_: NumberFormatException) { num } } private fun skipWs(s: String, pos: IntArray) { while (pos[0] < s.length && s[pos[0]].isWhitespace()) pos[0]++ } } private val http: HttpClient = HttpClient.newBuilder() .connectTimeout(Duration.ofSeconds(15)) .followRedirects(HttpClient.Redirect.NEVER) .build() private var baseUrl: String = (System.getenv("XCLIENT_BASE_URL")?.takeIf { it.isNotEmpty() } ?: DEFAULT_BASE).trimEnd('/') private var token: String = (token?.takeIf { it.isNotEmpty() } ?: System.getenv("XCLIENT_TOKEN") ?: "") private val deviceId: String = loadOrMintDeviceId() private val sessionId: String = UUID.randomUUID().toString() fun setToken(token: String?) { this.token = token ?: "" } fun setBaseUrl(baseUrl: String){ this.baseUrl = baseUrl.trimEnd('/') } // ── HTTP transport ─────────────────────────────────────────────── fun requestList(path: String, opts: Map?): Map? { val qs = StringBuilder() if (opts != null) { for ((k, v) in opts) { if (v == null) continue if (qs.isNotEmpty()) qs.append("&") qs.append(URLEncoder.encode(k, StandardCharsets.UTF_8)) qs.append("=") qs.append(URLEncoder.encode(v.toString(), StandardCharsets.UTF_8)) } } val full = if (qs.isNotEmpty()) "$path?$qs" else path return requestJson("GET", full, null) } fun requestJson(method: String, path: String, body: Map?): Map? { maybeAutoupdate() val url = baseUrl + path val json = body?.let { encodeJson(it) } var lastErr: Throwable? = null for (attempt in 0 until MAX_RETRIES) { try { val resp = sendFollowingRedirects(method, url, json) resp.headers().firstValue("x-auth-refresh-token").orElse(null)?.takeIf { it.isNotEmpty() }?.let { token = it } val status = resp.statusCode() if (RETRYABLE.contains(status) && attempt + 1 < MAX_RETRIES) { Thread.sleep(backoffMillis(attempt, resp.headers().firstValue("Retry-After").orElse(null))) continue } if (status >= 400) { emitCallEvent(method, path, status, false) val msg = jsonExtractString(resp.body(), "detail") ?: jsonExtractString(resp.body(), "message") ?: "HTTP $status" throw ApiException(status, msg, resp.body()) } emitCallEvent(method, path, status, true) val raw = resp.body() ?: return null return if (raw.isEmpty()) null else decodeJsonObject(raw) } catch (e: ApiException) { throw e } catch (e: Exception) { lastErr = e if (attempt + 1 < MAX_RETRIES) { Thread.sleep(backoffMillis(attempt, null)) continue } emitCallEvent(method, path, 0, false) throw ApiException(0, e.message ?: "request failed") } } emitCallEvent(method, path, 0, false) throw ApiException(0, lastErr?.message ?: "request failed") } private fun sendFollowingRedirects(method: String, url: String, json: String?): HttpResponse { var currentUrl = url var currentMethod = method.uppercase() var currentJson = json var stripAuth = false val maxHops = 5 for (hop in 0..maxHops) { val b = HttpRequest.newBuilder() .uri(URI.create(currentUrl)) .timeout(Duration.ofSeconds(30)) .header("Accept", "application/json") .header("User-Agent", userAgent()) .header("X-Client-Channel", "client_$LANGUAGE") .header("X-Client-Version", CLIENT_VERSION) .header("X-Analytics-Device-Id", deviceId) .header("X-Analytics-Session-Id", sessionId) if (!stripAuth && token.isNotEmpty()) b.header("Authorization", "Bearer $token") if (currentJson != null && currentMethod != "GET" && currentMethod != "HEAD") { b.header("Content-Type", "application/json") b.method(currentMethod, HttpRequest.BodyPublishers.ofString(currentJson, StandardCharsets.UTF_8)) } else { b.method(currentMethod, HttpRequest.BodyPublishers.noBody()) } val resp = http.send(b.build(), HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8)) val status = resp.statusCode() if (status < 300 || status >= 400 || status == 304 || hop == maxHops) return resp val loc = resp.headers().firstValue("Location").orElse(null) ?: return resp val nextUri = try { URI.create(currentUrl).resolve(loc) } catch (_: IllegalArgumentException) { return resp } if (!originOf(URI.create(currentUrl)).equals(originOf(nextUri), ignoreCase = true)) { stripAuth = true } if (status == 303 || ((status == 301 || status == 302) && currentMethod != "GET" && currentMethod != "HEAD")) { currentMethod = "GET" currentJson = null } currentUrl = nextUri.toString() } throw java.io.IOException("redirect chain exceeded max hops") } private fun userAgent() = "$MODULE_NAME/$CLIENT_VERSION (lib/$LANGUAGE; kotlin/${KotlinVersion.CURRENT}; java/${System.getProperty("java.version")})" // ── Analytics ──────────────────────────────────────────────────── private fun emitCallEvent(method: String, path: String, status: Int, ok: Boolean) { val includeEnv = META_SENT_ONCE.compareAndSet(false, true) thread(start = true, isDaemon = true, name = "$MODULE_NAME-analytics") { try { val meta = LinkedHashMap() meta["channel"] = "client_$LANGUAGE" meta["client_version"] = CLIENT_VERSION meta["module_name"] = MODULE_NAME meta["language"] = LANGUAGE meta["os"] = System.getProperty("os.name") meta["kotlin_version"] = KotlinVersion.CURRENT.toString() if (includeEnv) meta["env"] = fingerprint() val evt = mapOf( "type" to "client.call", "ts_client" to (System.currentTimeMillis() / 1000L), "meta" to mapOf( "method" to method.uppercase(), "path" to path.split('?').first(), "status" to status, "ok" to ok, ), ) val body = mapOf( "device_id" to deviceId, "session_id" to sessionId, "events" to listOf(evt), "meta" to meta, ) val req = HttpRequest.newBuilder() .uri(URI.create("$baseUrl/xapi2/analytics/track")) .timeout(Duration.ofSeconds(4)) .header("Content-Type", "application/json") .header("User-Agent", userAgent()) .POST(HttpRequest.BodyPublishers.ofString(encodeJson(body), StandardCharsets.UTF_8)) .build() http.send(req, HttpResponse.BodyHandlers.discarding()) } catch (_: Throwable) { /* fire and forget */ } } } // ── Auto-update ────────────────────────────────────────────────── private fun maybeAutoupdate() { if (!AUTOUPDATE_TRIED.compareAndSet(false, true)) return if (!autoupdateEnabled()) return thread(start = true, isDaemon = true, name = "$MODULE_NAME-autoupdate") { try { val d = stateDir() ?: return@thread val stamp = d.resolve("update_check.json") val now = System.currentTimeMillis() / 1000L if (Files.exists(stamp)) { try { val raw = Files.readString(stamp, StandardCharsets.UTF_8) val checked = jsonExtractString(raw, "checked_at")?.toLongOrNull() if (checked != null && now - checked < 86400) return@thread } catch (_: Exception) {} } Files.writeString(stamp, "{\"checked_at\":\"$now\"}", StandardCharsets.UTF_8) // Source replacement is intentionally a no-op - the // user is running compiled JVM bytecode, the .kt file // is just a record of the version they vendored. } catch (_: Throwable) {} } } // ── Generated per-type wrapper methods ─────────────────────────── // Every model that exposes an op gets one `` method // below. The runtime above does the heavy lifting; these wrappers // just pin the URL + HTTP verb. /** List `board` rows. */ fun boardList(opts: Map? = null): Map? = requestList("/xapi2/data/board", opts) /** Fetch one `board` row by id. */ fun boardGet(id: String): Map? = requestJson("GET", "/xapi2/data/board/" + id, null) /** Create a new `board` row. */ fun boardCreate(data: Map): Map? = requestJson("POST", "/xapi2/data/board", data) /** Patch a `board` row. */ fun boardUpdate(id: String, data: Map): Map? = requestJson("PATCH", "/xapi2/data/board/" + id, data) /** Delete a `board` row. */ fun boardDelete(id: String): Boolean { requestJson("DELETE", "/xapi2/data/board/" + id, null) return true } /** List `card` rows. */ fun cardList(opts: Map? = null): Map? = requestList("/xapi2/data/card", opts) /** Fetch one `card` row by id. */ fun cardGet(id: String): Map? = requestJson("GET", "/xapi2/data/card/" + id, null) /** Create a new `card` row. */ fun cardCreate(data: Map): Map? = requestJson("POST", "/xapi2/data/card", data) /** Patch a `card` row. */ fun cardUpdate(id: String, data: Map): Map? = requestJson("PATCH", "/xapi2/data/card/" + id, data) /** Delete a `card` row. */ fun cardDelete(id: String): Boolean { requestJson("DELETE", "/xapi2/data/card/" + id, null) return true } }