Skip to content

AI Image Generator — Go source

Turn a text prompt into a 1024×1024 image with FLUX.1 [schnell] on Cloudflare Workers AI. No account, no API key — rate-limited for fair use. Your prompt goes to the model through our Worker; we store no prompts and no images.

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

// Package aiimagegenerator is the Go twin of CosmoDev's
// src/lib/image-gen.ts (dual source: the web lib is TypeScript, the CLI lib
// is Go — kept in lock-step). Pure + deterministic, never panics, no
// network and no D1 — the same boundary as the breach-checker twin. The
// table-driven tests in ai_image_generator_test.go share vectors with
// src/lib/image-gen.test.ts so the two implementations are held to the
// same contract.
//
// Model facts (2026-09-10): @cf/black-forest-labs/flux-1-schnell accepts
// only prompt + steps (no width/height; output fixed 1024×1024). v1 pins
// steps at the schnell design point of 4 → a flat 57.6 neurons per image
// (4 tiles × 4.8 + 4 steps × 9.6) inside Cloudflare's 10,000/day free
// allocation.
package aiimagegenerator

import (
	"net/url"
	"strings"
	"time"
	"unicode/utf8"
)

// Model is the Workers AI text-to-image model the route calls.
const Model = "@cf/black-forest-labs/flux-1-schnell"

// Steps is schnell's design point. The model max is 8, but cost scales at
// 9.6 neurons/step, so v1 pins 4.
const Steps = 4

// PromptMaxChars is our UX clamp — deliberately below the model's 2048.
const PromptMaxChars = 600

// Rate caps: per-IP per-UTC-hour and shared global per-UTC-day. DailyCap
// reflects the EMPIRICAL cost (2026-09-10, live usage.neurons: 172.8 per
// image) — 40/day stays inside the 10,000-neuron free allocation.
const (
	IPHourCap = 10
	DailyCap  = 40
)

// ModelParams is what the route hands env.AI.run.
type ModelParams struct {
	Prompt string
	Steps  int
}

// ValidatePrompt mirrors the TS validatePrompt: trims, normalizes line
// endings (\r\n and \r → \n), enforces 1..PromptMaxChars runes, and
// rejects control characters other than \n (C0 minus U+000A, DEL, C1).
// Returns the cleaned prompt and a reason string; reason "" means ok.
func ValidatePrompt(raw string) (prompt string, reason string) {
	p := strings.ReplaceAll(raw, "\r\n", "\n")
	p = strings.ReplaceAll(p, "\r", "\n")
	p = strings.TrimSpace(p)
	if len(p) == 0 {
		return "", "empty"
	}
	if utf8.RuneCountInString(p) > PromptMaxChars {
		return "", "tooLong"
	}
	for _, r := range p {
		if r == '\n' {
			continue
		}
		// utf8.RuneError here means an invalid byte — raw C1 bytes land in
		// this branch too (JS cannot express them; Go can, so reject).
		if r == utf8.RuneError || r <= 0x1F || (r >= 0x7F && r <= 0x9F) {
			return "", "controlChars"
		}
	}
	return p, ""
}

// BuildModelParams pins steps and passes the prompt through.
func BuildModelParams(prompt string) ModelParams {
	return ModelParams{Prompt: prompt, Steps: Steps}
}

// GateVerdict is CheckGate's result. OK true ⇒ generate; otherwise Err is
// RATE_LIMITED_IP or RATE_LIMITED_DAILY and RetryAfterMinutes tells the UI
// when the window resets.
type GateVerdict struct {
	OK                bool
	Err               string
	RetryAfterMinutes int
}

// CheckGate mirrors the TS checkGate: the daily cap wins over the IP cap;
// the daily retry is the minutes to 00:00 UTC (minimum 1), the IP retry is
// the fixed 60-minute hourly bucket.
func CheckGate(ipCount, dailyCount int, now time.Time) GateVerdict {
	if dailyCount >= DailyCap {
		return GateVerdict{false, "RATE_LIMITED_DAILY", minutesToUTCMidnight(now)}
	}
	if ipCount >= IPHourCap {
		return GateVerdict{false, "RATE_LIMITED_IP", 60}
	}
	return GateVerdict{OK: true}
}

func minutesToUTCMidnight(now time.Time) int {
	u := now.UTC()
	midnight := time.Date(u.Year(), u.Month(), u.Day(), 0, 0, 0, 0, time.UTC).AddDate(0, 0, 1)
	mins := int(midnight.Sub(u).Minutes())
	// Ceil sub-minute remainders, then clamp to a minimum of 1.
	if midnight.Sub(u)%time.Minute != 0 {
		mins++
	}
	if mins < 1 {
		mins = 1
	}
	return mins
}

// encodeURIComponentUnreserved mirrors JS encodeURIComponent's unreserved
// set (A-Za-z0-9 - _ . ! ~ * ' ( )) so share URLs are byte-identical
// across the TS and Go implementations.
func encodeURIComponentUnreserved(r rune) bool {
	switch {
	case r >= 'A' && r <= 'Z', r >= 'a' && r <= 'z', r >= '0' && r <= '9':
		return true
	}
	switch r {
	case '-', '_', '.', '!', '~', '*', '\'', '(', ')':
		return true
	}
	return false
}

// EncodeURLState mirrors the TS encodeUrlState: empty prompt → no fragment;
// otherwise "#prompt=" + encodeURIComponent(prompt). Never '+' for spaces.
// ROAD-009: share state rides the URL hash, never the query string.
func EncodeURLState(prompt string) string {
	if prompt == "" {
		return ""
	}
	var b strings.Builder
	b.WriteString("#prompt=")
	for _, r := range prompt {
		if encodeURIComponentUnreserved(r) {
			b.WriteRune(r)
		} else {
			for _, byteVal := range []byte(string(r)) {
				const hex = "0123456789ABCDEF"
				b.WriteByte('%')
				b.WriteByte(hex[byteVal>>4])
				b.WriteByte(hex[byteVal&0xF])
			}
		}
	}
	return b.String()
}

// DecodeURLState mirrors the TS decodeUrlState: pull `prompt` from a
// fragment or query string (leading '#' or '?' optional); "" when absent.
func DecodeURLState(fragment string) string {
	s := strings.TrimPrefix(fragment, "#")
	s = strings.TrimPrefix(s, "?")
	if s == "" {
		return ""
	}
	vals, err := url.ParseQuery(s)
	if err != nil {
		return ""
	}
	return vals.Get("prompt")
}

Also available in 14 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 →