Open-source agentic AI Search Execution Platform. Track AI visibility, find opportunities, and let agents turn signals into prioritized actions and drafted fixes across ChatGPT, Claude, Gemini, Google AI Overviews, Google AI Mode, Perplexity, Grok, and Microsoft Copilot.
TypeScript aeoai-agentai-searchanswer-engine-optimizationbrand-monitoringchatgptclaudecopilotdockergeminigeogoogle-ai-overviewsgrokmcpnextjsopen-sourceperplexityseosupabasetypescript
feat(prompts): target prompts at multiple countries and US states (#783)
Gökhan Geyik79da93b75f00
diff --git a/server/src/lib/anthropic-tracker.js b/server/src/lib/anthropic-tracker.jsindex 1cbf9f11e..a513a5403 100644--- a/server/src/lib/anthropic-tracker.js+++ b/server/src/lib/anthropic-tracker.js@@ -4,6 +4,7 @@*/import Anthropic from '@anthropic-ai/sdk';+import { userLocationFor } from './locations.js';let client = null;@@ -21,7 +22,9 @@ function getClient() {* Run a single prompt through Anthropic Messages API with web_search enabled.* @param {string} promptText* @param {string} model - e.g. "claude-sonnet-5"- * @param {string} [region] - ISO 2-letter country code for web_search user_location+ * @param {string} [region] - Location code for web_search user_location: an+ * ISO country (`DE`) or a US state (`US-CA`, #691). Country-only codes+ * produce exactly the payload they did before states existed.* @returns {Promise<{ text: string, citations: Array<{ url: string, title: string, startIndex: number, endIndex: number }>, model: string }>}*/export async function runPromptAnthropic(promptText, model, region) {@@ -33,8 +36,9 @@ export async function runPromptAnthropic(promptText, model, region) {max_uses: 5,};- if (region) {- webSearchTool.user_location = { type: 'approximate', country: region };+ const userLocation = userLocationFor(region);+ if (userLocation) {+ webSearchTool.user_location = userLocation;}const response = await anthropic.messages.create({diff --git a/server/src/lib/cloro-scraper.js b/server/src/lib/cloro-scraper.jsindex dae484a8f..7f7699d39 100644--- a/server/src/lib/cloro-scraper.js+++ b/server/src/lib/cloro-scraper.js@@ -37,7 +37,8 @@ export function buildRequestBody(promptText, scraperId, region, state) {// State-level geo-targeting (#554): the AI endpoints accept a USPS state// code alongside country US and route through an in-state proxy. Google// AIO / AI Mode use location/uule for sub-country targeting instead and- // must never receive it — their branches below skip this spread.+ // must never receive it — their branches below skip this spread, and since+ // #691 the caller never even submits a per-state task for them.const stateField = country === 'US' && state ? { state } : {};if (scraperId === 'chatgpt-shopping') {@@ -232,7 +233,8 @@ export function parseScraperResponse(result, scraperId) {* @param {string} scraperId* @param {string} [region]* @param {{ webhookUrl?: string, state?: string }} [opts] - `state` is the- * brand's optional USPS code (#554); only forwarded on US AI-endpoint tasks.+ * USPS code of the location this task targets (#554, per-prompt since+ * #691); only forwarded on US AI-endpoint tasks.* @returns {Promise<{ taskId: string, scraperId: string }>}*/export async function submitScraperTask(promptText, scraperId, region, opts = {}) {diff --git a/server/src/lib/locations.js b/server/src/lib/locations.jsnew file mode 100644index 000000000..7a5c4f0e3--- /dev/null+++ b/server/src/lib/locations.js@@ -0,0 +1,141 @@+/**+ * Tracking locations (#691).+ *+ * A prompt's `regions` column holds location codes, not plain countries: a+ * bare ISO country (`DE`) or an ISO 3166-2 US state (`US-CA`). One code is+ * one tracked location — one set of scraper and model calls, one plan-quota+ * unit, one `prompt_results.region` value.+ *+ * Parsing lives here so exactly one definition decides what a code means.+ * The web tier keeps a deliberately identical copy in `web/src/lib/region.ts`+ * (same rule as the citation hostname split): both sides must agree on which+ * codes are valid, or the app would offer targeting the worker cannot run.+ */++/**+ * USPS code → full state name, for the AI providers' `user_location.region`,+ * which takes a human-readable region rather than a code.+ */+export const US_STATE_NAMES = {+ AL: 'Alabama',+ AK: 'Alaska',+ AZ: 'Arizona',+ AR: 'Arkansas',+ CA: 'California',+ CO: 'Colorado',+ CT: 'Connecticut',+ DE: 'Delaware',+ FL: 'Florida',+ GA: 'Georgia',+ HI: 'Hawaii',+ ID: 'Idaho',+ IL: 'Illinois',+ IN: 'Indiana',+ IA: 'Iowa',+ KS: 'Kansas',+ KY: 'Kentucky',+ LA: 'Louisiana',+ ME: 'Maine',+ MD: 'Maryland',+ MA: 'Massachusetts',+ MI: 'Michigan',+ MN: 'Minnesota',+ MS: 'Mississippi',+ MO: 'Missouri',+ MT: 'Montana',+ NE: 'Nebraska',+ NV: 'Nevada',+ NH: 'New Hampshire',+ NJ: 'New Jersey',+ NM: 'New Mexico',+ NY: 'New York',+ NC: 'North Carolina',+ ND: 'North Dakota',+ OH: 'Ohio',+ OK: 'Oklahoma',+ OR: 'Oregon',+ PA: 'Pennsylvania',+ RI: 'Rhode Island',+ SC: 'South Carolina',+ SD: 'South Dakota',+ TN: 'Tennessee',+ TX: 'Texas',+ UT: 'Utah',+ VT: 'Vermont',+ VA: 'Virginia',+ WA: 'Washington',+ WV: 'West Virginia',+ WI: 'Wisconsin',+ WY: 'Wyoming',+ DC: 'District of Columbia',+};++/**+ * Scrapers with no sub-country targeting mechanism. Google AIO / AI Mode+ * locate through location/uule parameters Cloro's AI endpoints don't accept,+ * so a state code means nothing to them: they can only be run country-wide+ * (#691, carried over from #554).+ */+const COUNTRY_ONLY_SCRAPERS = new Set(['google-aio', 'google-aimode']);++/**+ * Split a location code into what the providers actually take.+ * `US-CA` → `{ country: 'US', state: 'CA' }`; `DE` → `{ country: 'DE',+ * state: null }`. Unparsable or empty input yields a null country, which the+ * callers treat as "no targeting" — the same as a prompt with no regions.+ */+export function parseLocation(code) {+ if (typeof code !== 'string') return { country: null, state: null };+ const trimmed = code.trim().toUpperCase();+ if (!trimmed) return { country: null, state: null };++ const [country, state] = trimmed.split('-');+ if (!/^[A-Z]{2}$/.test(country || '')) return { country: null, state: null };+ if (state === undefined) return { country, state: null };+ // Sub-country targeting exists for US states only; anything else is+ // treated as the bare country rather than silently sent as a bad code.+ if (country === 'US' && US_STATE_NAMES[state]) return { country, state };+ return { country, state: null };+}++/**+ * The locations one scraper should actually be run for.+ *+ * Every code a state-capable engine can use survives as-is. For the+ * country-only engines the list collapses to its distinct countries, so a+ * prompt targeting California and Texas submits ONE country-wide Google task+ * instead of two identical ones — which would have doubled the spend and+ * written two rows differing only in a state label neither run honoured.+ *+ * Order is preserved so task submission stays deterministic.+ */+export function locationsForScraper(locations, scraperId) {+ const list = Array.isArray(locations) && locations.length > 0 ? locations : [null];+ if (!COUNTRY_ONLY_SCRAPERS.has(scraperId)) return list;++ const seen = new Set();+ const collapsed = [];+ for (const code of list) {+ const { country } = parseLocation(code);+ const key = country ?? '';+ if (seen.has(key)) continue;+ seen.add(key);+ collapsed.push(country);+ }+ return collapsed;+}++/**+ * `user_location` for the API models' web-search tool, or null when the+ * prompt is untargeted. `region` carries the full state name because that is+ * what both providers document for the field — a USPS code is not a region+ * name. Country-only locations produce exactly the payload they did before+ * states existed, so untargeted and country-targeted runs are unchanged.+ */+export function userLocationFor(code) {+ const { country, state } = parseLocation(code);+ if (!country) return null;+ const location = { type: 'approximate', country };+ if (state) location.region = US_STATE_NAMES[state];+ return location;+}diff --git a/server/src/lib/locations.test.js b/server/src/lib/locations.test.jsnew file mode 100644index 000000000..fbac27e4a--- /dev/null+++ b/server/src/lib/locations.test.js@@ -0,0 +1,74 @@+import { describe, it, expect } from 'vitest';+import { parseLocation, locationsForScraper, userLocationFor } from './locations.js';++describe('parseLocation', () => {+ it('splits a US state code into country and state', () => {+ expect(parseLocation('US-CA')).toEqual({ country: 'US', state: 'CA' });+ });++ it('reads a bare country as country-only', () => {+ expect(parseLocation('DE')).toEqual({ country: 'DE', state: null });+ });++ it('normalizes case and surrounding space', () => {+ expect(parseLocation(' us-ca ')).toEqual({ country: 'US', state: 'CA' });+ });++ it('falls back to the country for sub-country codes we cannot target', () => {+ // Non-US sub-country targeting has no mechanism, and US-ZZ is not a state.+ expect(parseLocation('DE-BY')).toEqual({ country: 'DE', state: null });+ expect(parseLocation('US-ZZ')).toEqual({ country: 'US', state: null });+ });++ it('treats empty and malformed input as untargeted', () => {+ for (const value of ['', ' ', 'USA', 'U', null, undefined, 42]) {+ expect(parseLocation(value)).toEqual({ country: null, state: null });+ }+ });+});++describe('locationsForScraper', () => {+ it('keeps every location for state-capable engines', () => {+ expect(locationsForScraper(['US-CA', 'US-TX', 'DE'], 'chatgpt')).toEqual([+ 'US-CA',+ 'US-TX',+ 'DE',+ ]);+ });++ it('collapses states to one country-wide run for Google engines', () => {+ // Two states of the same country would otherwise submit two identical+ // country-wide tasks — double spend, and two rows that differ only by a+ // state label neither run honoured.+ expect(locationsForScraper(['US-CA', 'US-TX', 'DE'], 'google-aio')).toEqual(['US', 'DE']);+ expect(locationsForScraper(['US-CA', 'US-TX'], 'google-aimode')).toEqual(['US']);+ });++ it('leaves country-only targeting untouched for Google engines', () => {+ expect(locationsForScraper(['US', 'DE'], 'google-aio')).toEqual(['US', 'DE']);+ });++ it('runs once with no targeting when the prompt has no locations', () => {+ expect(locationsForScraper([], 'chatgpt')).toEqual([null]);+ expect(locationsForScraper(undefined, 'google-aio')).toEqual([null]);+ });+});++describe('userLocationFor', () => {+ it('sends country only for a country location, exactly as before states', () => {+ expect(userLocationFor('DE')).toEqual({ type: 'approximate', country: 'DE' });+ });++ it('adds the full state name as the region for a state location', () => {+ expect(userLocationFor('US-CA')).toEqual({+ type: 'approximate',+ country: 'US',+ region: 'California',+ });+ });++ it('is null for untargeted runs so the tool config stays untouched', () => {+ expect(userLocationFor(null)).toBeNull();+ expect(userLocationFor('')).toBeNull();+ });+});diff --git a/server/src/lib/openai-tracker.js b/server/src/lib/openai-tracker.jsindex 1e044d844..b89570180 100644--- a/server/src/lib/openai-tracker.js+++ b/server/src/lib/openai-tracker.js@@ -5,6 +5,7 @@import OpenAI from 'openai';import { logger } from './logger.js';+import { userLocationFor } from './locations.js';const DEFAULT_MODEL = 'gpt-5-chat-latest';@@ -24,7 +25,9 @@ function getClient() {* Run a single prompt through OpenAI Responses API with web_search enabled.* @param {string} promptText - The prompt to send* @param {string} [model] - OpenAI model name (defaults to gpt-5-chat-latest)- * @param {string} [region] - ISO 2-letter country code for web_search user_location+ * @param {string} [region] - Location code for web_search user_location: an+ * ISO country (`DE`) or a US state (`US-CA`, #691). Country-only codes+ * produce exactly the payload they did before states existed.* @returns {Promise<{ text: string, citations: Array<{ url: string, title: string, startIndex: number, endIndex: number }>, model: string }>}*/export async function runPrompt(promptText, model, region) {@@ -32,8 +35,9 @@ export async function runPrompt(promptText, model, region) {const modelName = model || DEFAULT_MODEL;const webSearchTool = { type: 'web_search' };- if (region) {- webSearchTool.user_location = { type: 'approximate', country: region };+ const userLocation = userLocationFor(region);+ if (userLocation) {+ webSearchTool.user_location = userLocation;}const response = await openai.responses.create({diff --git a/server/src/workers/tracking-worker.js b/server/src/workers/tracking-worker.jsindex 69653f464..8187c3f48 100644--- a/server/src/workers/tracking-worker.js+++ b/server/src/workers/tracking-worker.js@@ -12,6 +12,7 @@ import { applyPlanOverrides } from '../lib/plan-guard.js';import { generateContentOpportunities } from '../lib/opportunity-generator.js';import { updateTargetUrlStats } from '../lib/target-url-stats.js';import { persistCitationRows } from '../lib/citation-rows.js';+import { parseLocation, locationsForScraper } from '../lib/locations.js';import { refreshForCompletedRun } from '../lib/insights-rollups.js';import logger from '../lib/logger.js';@@ -161,7 +162,9 @@ export async function processTrackingJob({ brandId, promptId, promptIds, source,// 1. Fetch brand info with domainsconst { data: brand, error: brandErr } = await supabaseAdmin.from('brands')- .select('id, name, organization_id, shopping_mode_enabled, state')+ // `state` is deliberately not read: it is the default location offered+ // when new prompts are created, not a tracking-time override (#691).+ .select('id, name, organization_id, shopping_mode_enabled').eq('id', brandId).single();if (brandErr || !brand) throw new Error(`Brand not found: ${brandId}`);@@ -283,13 +286,23 @@ export async function processTrackingJob({ brandId, promptId, promptIds, source,const allowedPlatformsFor = (prompt) =>runnablePlatforms(prompt.platforms, { shoppingEnabled: brand.shopping_mode_enabled });- // 4. Count total tasks: prompt × (models + scrapers) × regions+ // A prompt's tracked locations (#691): country codes and US state codes+ // (`US-CA`) alike. No locations means one untargeted run, which is what an+ // empty list has always meant here.+ const locationsFor = (prompt) =>+ prompt.regions && prompt.regions.length > 0 ? prompt.regions : [null];++ // 4. Count total tasks: one per prompt × engine × location that engine can+ // actually run. Google AIO / AI Mode have no sub-country mechanism, so+ // their state locations collapse to one country-wide task — counting them+ // per state would promise the progress bar work that is never submitted.let totalTasks = 0;for (const prompt of prompts) {- const mc = allowedModelsFor(prompt).length;- const sc = allowedPlatformsFor(prompt).length;- const rc = prompt.regions && prompt.regions.length > 0 ? prompt.regions.length : 1;- totalTasks += (mc + sc) * rc;+ const locations = locationsFor(prompt);+ totalTasks += allowedModelsFor(prompt).length * locations.length;+ for (const scraperId of allowedPlatformsFor(prompt)) {+ totalTasks += locationsForScraper(locations, scraperId).length;+ }}// 5. Shared counters & helper@@ -327,10 +340,12 @@ export async function processTrackingJob({ brandId, promptId, promptIds, source,const scraperTasks = [];for (const prompt of prompts) {const scrapersToRun = allowedPlatformsFor(prompt);- const regionsToRun = prompt.regions && prompt.regions.length > 0 ? prompt.regions : [null];for (const scraperId of scrapersToRun) {- for (const region of regionsToRun) {+ // `region` carries the full location code — it is what gets stamped on+ // the result row, so a Google run collapsed to its country is recorded+ // as the country it actually ran in, not the state that was asked for.+ for (const region of locationsForScraper(locationsFor(prompt), scraperId)) {scraperTasks.push({ prompt, scraperId, region });}}@@ -356,15 +371,20 @@ export async function processTrackingJob({ brandId, promptId, promptIds, source,// Submit all tasks concurrentlyconst submissions = await Promise.allSettled(- scraperTasks.map((t) =>- submitScraperTask(t.prompt.text, t.scraperId, t.region, {+ scraperTasks.map((t) => {+ // Targeting comes from the prompt's own location, not from the+ // brand's single state column (#691): different prompts can target+ // different places, and a brand-wide override would silently win+ // over them.+ const { country, state } = parseLocation(t.region);+ return submitScraperTask(t.prompt.text, t.scraperId, country, {webhookUrl,- state: brand.state,+ state,}).then((res) => ({...res,meta: t,- })),- ),+ }));+ }),);const submitted = [];@@ -728,10 +748,10 @@ export async function processTrackingJob({ brandId, promptId, promptIds, source,const modelTasks = [];for (const prompt of prompts) {const modelsToRun = allowedModelsFor(prompt);- const regionsToRun = prompt.regions && prompt.regions.length > 0 ? prompt.regions : [null];+ const locations = locationsFor(prompt);for (const modelName of modelsToRun) {- for (const region of regionsToRun) {+ for (const region of locations) {modelTasks.push({ prompt, modelName, region });}}diff --git a/supabase/migrations/00071_prompt_state_locations.sql b/supabase/migrations/00071_prompt_state_locations.sqlnew file mode 100644index 000000000..e23a7caea--- /dev/null+++ b/supabase/migrations/00071_prompt_state_locations.sql@@ -0,0 +1,43 @@+-- Move state targeting from the brand onto the prompt (#691 part 2).+--+-- APPLY AFTER DEPLOYING THE SERVER, not before. The running worker passes a+-- prompt's region straight through as the Cloro `country` field, so a row+-- reading `US-DE` would be submitted as country "US-DE" and rejected — this+-- brand's tracking would fail until the deploy landed. The new worker parses+-- the code first, so once it is live the order no longer matters.+--+-- `brands.state` was a single USPS code the tracking worker applied to every+-- US task the brand ran (#554). Targeting now lives on the prompt, as a+-- location code in `prompts.regions` (`US-CA`), so different prompts can+-- track different places — and the worker no longer reads `brands.state` at+-- all. Left alone, that would silently downgrade the brands that had a state+-- set: their prompts would keep saying `US` and start running country-wide.+--+-- So fold the brand's state into its own prompts' `US` entries, once. Other+-- countries are untouched: the state only ever applied to US tasks.+--+-- Quota is unaffected — a prompt targeting `US-DE` tracks exactly one+-- location, the same as one targeting `US` (#691 part 1 counts entries, not+-- codes), so no org's usage or limit standing moves.+--+-- The column itself stays, with a narrower job: it is the DEFAULT location+-- offered to prompts created for that brand, not a tracking-time override.+-- Two sources of truth for "where does this prompt run" is exactly the+-- conflict this migration removes.+update public.prompts p+set regions = (+ select array_agg(+ case when r = 'US' then 'US-' || b.state else r end+ order by idx+ )+ from unnest(p.regions) with ordinality as t(r, idx)+)+from public.prompt_sets ps, public.brands b+where ps.id = p.prompt_set_id+ and b.id = ps.brand_id+ and b.state is not null+ and b.state ~ '^[A-Z]{2}$'+ and 'US' = any(p.regions);++comment on column public.brands.state is+ 'Default US state for prompts created for this brand (#691). Targeting itself lives in prompts.regions as location codes (US-CA); the tracking worker does not read this column.';diff --git a/supabase/schema.sql b/supabase/schema.sqlindex 0ec856dd7..ecf416b5b 100644--- a/supabase/schema.sql+++ b/supabase/schema.sql@@ -8444,3 +8444,50 @@ grant execute on function public.org_prompt_location_usage(uuid) to authenticatecomment on function public.org_prompt_location_usage(uuid) is'Tracked prompt locations per brand for one org (#691) — the plan-quota unit, one per region entry per prompt, minimum one. Security invoker: RLS scopes it to the caller''s org.';+-- ─────────────────────────────────────────────────────────────────────────+-- migrations/00071_prompt_state_locations.sql+-- ─────────────────────────────────────────────────────────────────────────+-- Move state targeting from the brand onto the prompt (#691 part 2).+--+-- APPLY AFTER DEPLOYING THE SERVER, not before. The running worker passes a+-- prompt's region straight through as the Cloro `country` field, so a row+-- reading `US-DE` would be submitted as country "US-DE" and rejected — this+-- brand's tracking would fail until the deploy landed. The new worker parses+-- the code first, so once it is live the order no longer matters.+--+-- `brands.state` was a single USPS code the tracking worker applied to every+-- US task the brand ran (#554). Targeting now lives on the prompt, as a+-- location code in `prompts.regions` (`US-CA`), so different prompts can+-- track different places — and the worker no longer reads `brands.state` at+-- all. Left alone, that would silently downgrade the brands that had a state+-- set: their prompts would keep saying `US` and start running country-wide.+--+-- So fold the brand's state into its own prompts' `US` entries, once. Other+-- countries are untouched: the state only ever applied to US tasks.+--+-- Quota is unaffected — a prompt targeting `US-DE` tracks exactly one+-- location, the same as one targeting `US` (#691 part 1 counts entries, not+-- codes), so no org's usage or limit standing moves.+--+-- The column itself stays, with a narrower job: it is the DEFAULT location+-- offered to prompts created for that brand, not a tracking-time override.+-- Two sources of truth for "where does this prompt run" is exactly the+-- conflict this migration removes.+update public.prompts p+set regions = (+ select array_agg(+ case when r = 'US' then 'US-' || b.state else r end+ order by idx+ )+ from unnest(p.regions) with ordinality as t(r, idx)+)+from public.prompt_sets ps, public.brands b+where ps.id = p.prompt_set_id+ and b.id = ps.brand_id+ and b.state is not null+ and b.state ~ '^[A-Z]{2}$'+ and 'US' = any(p.regions);++comment on column public.brands.state is+ 'Default US state for prompts created for this brand (#691). Targeting itself lives in prompts.regions as location codes (US-CA); the tracking worker does not read this column.';+diff --git a/web/messages/en.json b/web/messages/en.jsonindex c0eacbbc3..2d42400f3 100644--- a/web/messages/en.json+++ b/web/messages/en.json@@ -680,7 +680,7 @@"year": "yr","unlimited": "Unlimited","brands": "brands",- "prompts": "prompts tracked",+ "prompts": "prompt locations tracked","platforms": "answer engines","teamMembers": "team members","renewsOn": "Renews on {date}",diff --git a/web/src/app/[locale]/(dashboard)/dashboard/brands/[id]/prompts/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/brands/[id]/prompts/page.tsxindex fdb755454..b92e443b4 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/brands/[id]/prompts/page.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/brands/[id]/prompts/page.tsx@@ -8,6 +8,8 @@ import {savePromptSet,addPromptToSet,updatePrompt,+ updatePromptLocations,+ getLocationQuota,deletePrompt,} from '@/lib/actions/prompt';import { getBrandById } from '@/lib/actions/brand';@@ -67,6 +69,12 @@ export default function PromptsPage() {const [brand, setBrand] = useState<Brand | null>(null);const [topics, setTopics] = useState<Topic[]>([]);const [promptSets, setPromptSets] = useState<PromptSet[]>([]);+ // Org-wide location usage, so each card's picker can stop at the plan cap+ // with a reason instead of letting the save fail afterwards (#691).+ const [locationQuota, setLocationQuota] = useState<{+ maxPrompts: number;+ used: number;+ } | null>(null);const [suggestions, setSuggestions] = useState<SuggestedPrompt[]>([]);const [isLoading, setIsLoading] = useState(true);const [isGenerating, setIsGenerating] = useState(false);@@ -136,13 +144,15 @@ export default function PromptsPage() {const loadData = useCallback(async (isCancelled?: () => boolean) => {try {- const [brandData, sets, topicsData] = await Promise.all([+ const [brandData, sets, topicsData, quota] = await Promise.all([getBrandById(brandId),getPromptSets(brandId),getTopics(brandId),+ getLocationQuota(brandId).catch(() => null),]);if (isCancelled?.()) return;setBrand(brandData);+ setLocationQuota(quota);setTopics(topicsData);if (topicsData.length > 0 && !manualCategory) {setManualCategory(topicsData[0].name);@@ -400,6 +410,22 @@ export default function PromptsPage() {[updatePromptLocal, loadData],);+ const handleRegionsChange = useCallback(+ async (promptId: string, regions: string[]) => {+ const result = await updatePromptLocations(promptId, regions);+ if ('error' in result) {+ toast.error(result.error);+ // The refusal means our usage figure was stale (a parallel edit, or+ // another tab): reload so the pickers bound themselves correctly.+ await loadData();+ return;+ }+ updatePromptLocal(promptId, { regions: result.prompt.regions });+ setLocationQuota(await getLocationQuota(brandId).catch(() => null));+ },+ [brandId, updatePromptLocal, loadData],+ );+const handlePlatformsChange = useCallback(async (promptId: string, platforms: string[]) => {updatePromptLocal(promptId, { platforms: platforms as Prompt['platforms'] });@@ -888,6 +914,15 @@ export default function PromptsPage() {onCategoryChange={(category) => handleCategoryChange(prompt.id, category)}onModelsChange={(models) => handleModelsChange(prompt.id, models)}onPlatformsChange={(platforms) => handlePlatformsChange(prompt.id, platforms)}+ onRegionsChange={(regions) => handleRegionsChange(prompt.id, regions)}+ maxLocations={+ locationQuota && locationQuota.maxPrompts !== -1+ ? Math.max(+ prompt.regions.length,+ locationQuota.maxPrompts - locationQuota.used + prompt.regions.length,+ )+ : null+ }onDelete={() => handleDeletePrompt(prompt.id)}mode="manage"/>diff --git a/web/src/app/[locale]/(onboarding)/dashboard/onboarding/page.tsx b/web/src/app/[locale]/(onboarding)/dashboard/onboarding/page.tsxindex 69513fb25..8b5d46ed6 100644--- a/web/src/app/[locale]/(onboarding)/dashboard/onboarding/page.tsx+++ b/web/src/app/[locale]/(onboarding)/dashboard/onboarding/page.tsx@@ -1668,7 +1668,7 @@ export default function OnboardingPage() {<strong>{plan.limits.maxPrompts === -1 ? 'Unlimited' : plan.limits.maxPrompts}</strong>{' '}- prompts tracked+ prompt locations tracked</PlanFeatureItem><PlanFeatureItem><strong>{plan.limits.maxPlatforms}</strong> answer enginesdiff --git a/web/src/components/dashboard/location-picker.tsx b/web/src/components/dashboard/location-picker.tsxnew file mode 100644index 000000000..138310a7c--- /dev/null+++ b/web/src/components/dashboard/location-picker.tsx@@ -0,0 +1,164 @@+'use client';++import { useMemo } from 'react';+import { X } from 'lucide-react';++import { REGIONS, US_STATES } from '@/config/prompt-options';+import { formatRegionDisplay, locationCode, parseLocation } from '@/lib/region';+import { Badge } from '@/components/ui/badge';+import {+ Combobox,+ ComboboxCollection,+ ComboboxContent,+ ComboboxEmpty,+ ComboboxInput,+ ComboboxItem,+ ComboboxList,+ ComboboxTrigger,+} from '@/components/ui/combobox';++interface LocationOption {+ value: string;+ /** What base-ui filters the search box against. */+ label: string;+ sublabel: string;+}++export interface LocationPickerProps {+ value: string[];+ onChange: (locations: string[]) => void;+ /**+ * Most locations this prompt may hold before the org hits its plan cap —+ * null when the plan is unlimited. The caller derives it from org usage so+ * the picker can refuse a pick with a reason instead of letting the save+ * fail afterwards.+ */+ maxSelectable: number | null;+ /** Engines the prompt runs, to warn where state targeting doesn't apply. */+ platforms?: string[];+}++/** Engines with no sub-country mechanism — mirrors the worker's collapse. */+const COUNTRY_ONLY_PLATFORMS = new Set(['google-aio', 'google-aimode']);++/**+ * Per-prompt tracking locations (#691).+ *+ * Follows the card's existing "add, then chip" idiom (the Platform & Models+ * picker): the list adds, the chips below remove. It is a Combobox rather+ * than a Select because the list is 18 countries plus 50 states — long+ * enough that scrolling to a known name is worse than typing it.+ *+ * Two things this picker must say out loud, because both cost money or+ * mislead if left implicit: every location is a plan-quota unit (the trigger+ * carries the count, and picks stop at the cap with the reason on screen),+ * and Google's engines have no state targeting, so a state pick runs them+ * country-wide instead of twice.+ */+export function LocationPicker({ value, onChange, maxSelectable, platforms }: LocationPickerProps) {+ const options = useMemo<LocationOption[]>(+ () => [+ ...REGIONS.map((region) => ({+ value: region.code,+ label: region.label,+ sublabel: 'Country',+ })),+ ...US_STATES.map((state) => ({+ value: locationCode('US', state.code),+ label: state.label,+ sublabel: 'United States · state',+ })),+ ],+ [],+ );++ const selected = new Set(value);+ const atCap = maxSelectable !== null && value.length >= maxSelectable;++ // A prompt with no location cannot be tracked, so the last chip keeps its+ // remove control hidden rather than failing server-side.+ const canRemove = value.length > 1;++ const hasStatePick = value.some((code) => parseLocation(code)?.state);+ const countryOnlyEngines = (platforms ?? []).filter((id) => COUNTRY_ONLY_PLATFORMS.has(id));+ const showCountryOnlyNote = hasStatePick && countryOnlyEngines.length > 0;++ const add = (option: LocationOption | null) => {+ if (!option || selected.has(option.value) || atCap) return;+ onChange([...value, option.value]);+ };++ const remove = (code: string) => {+ if (!canRemove) return;+ onChange(value.filter((entry) => entry !== code));+ };++ return (+ <div>+ <label className="mb-1.5 block text-xs font-medium text-muted-foreground">+ Locations+ <span className="ml-1 font-normal">+ {maxSelectable === null+ ? `· ${value.length} tracked`+ : `· ${value.length} of ${maxSelectable} available`}+ </span>+ </label>++ <Combobox items={options} value={null} onValueChange={add}>+ <ComboboxTrigger className="w-full">+ <span className="truncate text-muted-foreground">+ {atCap ? 'Plan limit reached' : 'Add a country or US state'}+ </span>+ </ComboboxTrigger>+ <ComboboxContent>+ <ComboboxInput placeholder="Search locations…" />+ <ComboboxList>+ <ComboboxEmpty>No locations match.</ComboboxEmpty>+ <ComboboxCollection>+ {(option: LocationOption) => (+ <ComboboxItem+ key={option.value}+ value={option}+ disabled={selected.has(option.value) || atCap}+ >+ <div>+ <div>{formatRegionDisplay(option.value)}</div>+ <div className="text-[10px] text-muted-foreground">+ {selected.has(option.value)+ ? 'Already tracked'+ : atCap+ ? 'Plan limit reached — remove a location or upgrade'+ : option.sublabel}+ </div>+ </div>+ </ComboboxItem>+ )}+ </ComboboxCollection>+ </ComboboxList>+ </ComboboxContent>+ </Combobox>++ {value.length > 0 && (+ <div className="mt-1.5 flex flex-wrap gap-1">+ {value.map((code) => (+ <Badge key={code} variant="outline" className="gap-1 text-xs">+ {formatRegionDisplay(code)}+ {canRemove && (+ <button type="button" onClick={() => remove(code)} aria-label={`Remove ${code}`}>+ <X className="h-3 w-3" />+ </button>+ )}+ </Badge>+ ))}+ </div>+ )}++ {showCountryOnlyNote && (+ <p className="mt-1.5 text-[11px] text-muted-foreground">+ Google AI Overview and AI Mode have no state-level targeting — they run once per country,+ so your state picks cost one location each but are answered country-wide there.+ </p>+ )}+ </div>+ );+}diff --git a/web/src/components/dashboard/prompt-suggestion-card.tsx b/web/src/components/dashboard/prompt-suggestion-card.tsxindex 1e4388c84..b0258b54e 100644--- a/web/src/components/dashboard/prompt-suggestion-card.tsx+++ b/web/src/components/dashboard/prompt-suggestion-card.tsx@@ -24,6 +24,8 @@ import {import { cn } from '@/lib/utils';import { Check, Pencil, Trash2, X } from 'lucide-react';import { MODEL_GROUPS, ALL_MODELS, SCRAPER_GROUPS, ALL_SCRAPERS } from '@/config/prompt-options';+import { formatRegionDisplay } from '@/lib/region';+import { LocationPicker } from '@/components/dashboard/location-picker';interface TopicOption {id: string;@@ -45,6 +47,12 @@ interface PromptSuggestionCardProps {allowedModelIds?: string[];onModelsChange?: (models: string[]) => void;onPlatformsChange?: (platforms: string[]) => void;+ onRegionsChange?: (regions: string[]) => void;+ /**+ * Most locations this prompt may hold under the org's plan (null =+ * unlimited). Only supplied where editing locations is offered.+ */+ maxLocations?: number | null;onCategoryChange?: (category: string) => void;mode?: 'review' | 'manage';}@@ -62,6 +70,14 @@ const TOPIC_COLOR_PALETTE = ['bg-teal-100 text-teal-800 dark:bg-teal-900/30 dark:text-teal-400',];+/** Order-insensitive comparison — reordering is not a location change. */+function sameLocations(a: string[], b: string[]): boolean {+ if (a.length !== b.length) return false;+ const left = [...a].sort();+ const right = [...b].sort();+ return left.every((code, i) => code === right[i]);+}+function getTopicColor(name: string): string {let hash = 0;for (let i = 0; i < name.length; i++) {@@ -85,6 +101,8 @@ export const PromptSuggestionCard = memo(function PromptSuggestionCard({allowedModelIds,onModelsChange,onPlatformsChange,+ onRegionsChange,+ maxLocations,onCategoryChange,mode = 'review',}: PromptSuggestionCardProps) {@@ -93,6 +111,7 @@ export const PromptSuggestionCard = memo(function PromptSuggestionCard({const [editCategory, setEditCategory] = useState(category);const [editModels, setEditModels] = useState<string[]>(models ?? []);const [editPlatforms, setEditPlatforms] = useState<string[]>(platforms ?? []);+ const [editRegions, setEditRegions] = useState<string[]>(regions ?? []);const visibleScrapers = allowedScraperIds? ALL_SCRAPERS.filter((s) => allowedScraperIds.includes(s.id))@@ -108,6 +127,11 @@ export const PromptSuggestionCard = memo(function PromptSuggestionCard({if (onCategoryChange && editCategory !== category) onCategoryChange(editCategory);if (onModelsChange) onModelsChange(editModels);if (onPlatformsChange) onPlatformsChange(editPlatforms);+ // Locations meter against the plan, so only send a real change — an+ // untouched prompt must never spend a quota check on save.+ if (onRegionsChange && !sameLocations(editRegions, regions ?? [])) {+ onRegionsChange(editRegions);+ }setIsEditing(false);};@@ -116,6 +140,7 @@ export const PromptSuggestionCard = memo(function PromptSuggestionCard({setEditCategory(category);setEditModels(models ?? []);setEditPlatforms(platforms ?? []);+ setEditRegions(regions ?? []);setIsEditing(false);};@@ -317,6 +342,15 @@ export const PromptSuggestionCard = memo(function PromptSuggestionCard({)}</div>)}++ {onRegionsChange && (+ <LocationPicker+ value={editRegions}+ onChange={setEditRegions}+ maxSelectable={maxLocations ?? null}+ platforms={editPlatforms}+ />+ )}</div>)}</div>@@ -383,7 +417,7 @@ export const PromptSuggestionCard = memo(function PromptSuggestionCard({regions.length > 0 &®ions.map((r) => (<Badge key={r} variant="outline" className="text-[10px]">- {r}+ {formatRegionDisplay(r)}</Badge>))}{models &&diff --git a/web/src/lib/actions/prompt.ts b/web/src/lib/actions/prompt.tsindex 2a6f7db4d..5981fb545 100644--- a/web/src/lib/actions/prompt.ts+++ b/web/src/lib/actions/prompt.ts@@ -3,18 +3,14 @@import { createClient } from '@/lib/supabase/server';import { revalidatePath } from 'next/cache';import type { PromptSet, Prompt, AIPlatform, PromptVolume } from '@/types';-import { getOrgPlan, PlanLimitError } from '@/lib/guards/plan-guard';+import { getOrgPlan } from '@/lib/guards/plan-guard';import {getOrgLocationUsage,locationLimitMessage,promptLocationCount,} from '@/lib/prompt-locations';-import {- ALL_MODELS,- ALL_SCRAPERS,- DEFAULT_PROMPT_RANGE_DAYS,- REGIONS,-} from '@/config/prompt-options';+import { ALL_MODELS, ALL_SCRAPERS, DEFAULT_PROMPT_RANGE_DAYS } from '@/config/prompt-options';+import { isValidLocation, locationCode } from '@/lib/region';import type { Plan } from '@/config/plans';import { getPromptVolumes, type VolumeQuota } from '@/lib/actions/volumes';import { getPromptVisibilitySummaries, type PromptVisibilitySummary } from '@/lib/actions/tracking';@@ -84,20 +80,29 @@ function mapPromptSetRow(};}+/**+ * `region` is the location new prompts start at — the brand's country, or+ * its state when one is set (#691). The brand's state is a DEFAULT here, not+ * a tracking-time override: the worker targets each prompt's own locations,+ * so a brand-wide setting that silently won over them would leave two+ * sources of truth for the same question.+ */async function getBrandContext(supabase: Awaited<ReturnType<typeof createClient>>,brandId: string,): Promise<{ organizationId: string; region: string }> {const { data } = await supabase.from('brands')- .select('organization_id, region')+ .select('organization_id, region, state').eq('id', brandId).single();if (!data?.organization_id) throw new Error('Brand not found');+ const country = (data.region as string | null) ?? 'US';+ const candidate = locationCode(country, data.state as string | null);return {organizationId: data.organization_id as string,- region: (data.region as string | null) ?? 'US',+ region: isValidLocation(candidate) ? candidate : country,};}@@ -289,7 +294,6 @@ export async function updatePrompt(category?: string;platforms?: string[];models?: string[];- regions?: string[];isActive?: boolean;},): Promise<Prompt> {@@ -300,11 +304,9 @@ export async function updatePrompt(if (updates.category !== undefined) payload.category = updates.category || null;if (updates.isActive !== undefined) payload.is_active = updates.isActive;- // Category, platform/model and region updates all need context from the- // prompt's row (its current regions, brand, org and shopping pref) — one- // fetch serves every branch below.+ // Both the category and the platform/model branch need context from the+ // prompt's row (its brand, org and shopping pref) — one fetch serves them.let ctx: {- regions: string[] | null;brandId: string;organizationId: string;shoppingEnabled: boolean | null;@@ -312,14 +314,11 @@ export async function updatePrompt(if (updates.category !== undefined ||updates.platforms !== undefined ||- updates.models !== undefined ||- updates.regions !== undefined+ updates.models !== undefined) {const { data: promptRow } = await supabase.from('prompts')- .select(- 'regions, prompt_sets!inner(brand_id, brands!inner(organization_id, shopping_mode_enabled))',- )+ .select('prompt_sets!inner(brand_id, brands!inner(organization_id, shopping_mode_enabled))').eq('id', id).single();const set = promptRow?.prompt_sets as unknown as {@@ -328,7 +327,6 @@ export async function updatePrompt(} | null;if (!set?.brands?.organization_id) throw new Error('Prompt not found');ctx = {- regions: (promptRow?.regions as string[] | null) ?? null,brandId: set.brand_id,organizationId: set.brands.organization_id,shoppingEnabled: set.brands.shopping_mode_enabled,@@ -350,39 +348,6 @@ export async function updatePrompt(if (updates.models !== undefined) payload.models = filtered.models;}- // Changing a prompt's locations changes what the plan meters (#691): an- // edit that grows the list from 1 to 3 locations costs exactly what adding- // two more single-location prompts would, so it passes the same guard with- // the same message. Only the DELTA is checked — re-saving unchanged at the- // limit succeeds, and removing locations always frees capacity.- //- // Throwing PlanLimitError here follows this function's existing error- // style; nothing in the UI can send `regions` yet, and the region editor- // that will (#691 follow-up) must surface this as a value, since- // production masks thrown server-action messages (#427).- if (updates.regions !== undefined && ctx) {- const regions = [...new Set(updates.regions.map((r) => r.trim().toUpperCase()))];- if (regions.length === 0) {- throw new Error('Select at least one location.');- }- const known = new Set<string>(REGIONS.map((r) => r.code));- const unknown = regions.filter((r) => !known.has(r));- if (unknown.length > 0) {- throw new Error(- `Unknown location code${unknown.length === 1 ? '' : 's'}: ${unknown.join(', ')}`,- );- }-- const delta = regions.length - promptLocationCount(ctx.regions);- if (delta > 0) {- const plan = await getOrgPlan(ctx.organizationId);- const usage = await getOrgLocationUsage(supabase, ctx.organizationId);- const limitError = locationLimitMessage(plan, usage.total, delta);- if (limitError) throw new PlanLimitError(limitError, plan.name);- }- payload.regions = regions;- }-const { data, error } = await supabase.from('prompts').update(payload)@@ -397,6 +362,92 @@ export async function updatePrompt(return mapPromptRow(data as Record<string, unknown>);}+export type UpdatePromptLocationsResult =+ | { prompt: Prompt }+ | { error: string; code?: 'plan_limit' };++/**+ * Retarget a prompt's tracking locations (#691).+ *+ * Its own action rather than a field on `updatePrompt` because locations are+ * the only prompt edit that meters against the plan, so this is the one that+ * can be REFUSED — and a refusal has to reach the user as a value: every+ * error thrown from a server action reaches production as a meaningless+ * digest string (#427).+ *+ * The guard measures the DELTA, not the total: an edit that grows the list+ * from one location to three costs exactly what adding two more+ * single-location prompts would, and fails the same way with the same+ * message. Re-saving an unchanged list at the cap succeeds, and removing+ * locations frees capacity immediately — including for an org left over its+ * limit by a plan downgrade.+ */+export async function updatePromptLocations(+ id: string,+ regionsInput: string[],+): Promise<UpdatePromptLocationsResult> {+ const supabase = await createClient();++ const regions = [...new Set(regionsInput.map((r) => r.trim().toUpperCase()))];+ if (regions.length === 0) {+ return { error: 'Select at least one location.' };+ }+ const unknown = regions.filter((r) => !isValidLocation(r));+ if (unknown.length > 0) {+ return {+ error: `Unknown location code${unknown.length === 1 ? '' : 's'}: ${unknown.join(', ')}`,+ };+ }++ const { data: promptRow } = await supabase+ .from('prompts')+ .select('regions, prompt_sets!inner(brands!inner(organization_id))')+ .eq('id', id)+ .single();+ const orgId = (+ promptRow?.prompt_sets as unknown as { brands: { organization_id: string } } | null+ )?.brands?.organization_id;+ if (!orgId) return { error: 'Prompt not found' };++ const delta = regions.length - promptLocationCount(promptRow?.regions as string[] | null);+ if (delta > 0) {+ const plan = await getOrgPlan(orgId);+ const usage = await getOrgLocationUsage(supabase, orgId);+ const limitError = locationLimitMessage(plan, usage.total, delta);+ if (limitError) return { error: limitError, code: 'plan_limit' };+ }++ const { data, error } = await supabase+ .from('prompts')+ .update({ regions })+ .eq('id', id)+ .select()+ .single();++ if (error || !data) {+ return { error: error?.message ?? 'Failed to update locations' };+ }++ revalidatePath('/dashboard/brands');+ return { prompt: mapPromptRow(data as Record<string, unknown>) };+}++/**+ * Org-wide tracked-location usage against the plan cap, for the prompts page+ * to bound its location pickers before a save can fail.+ */+export async function getLocationQuota(+ brandId: string,+): Promise<{ maxPrompts: number; used: number }> {+ const supabase = await createClient();+ const { organizationId: orgId } = await getBrandContext(supabase, brandId);+ const [plan, usage] = await Promise.all([+ getOrgPlan(orgId),+ getOrgLocationUsage(supabase, orgId),+ ]);+ return { maxPrompts: plan.limits.maxPrompts, used: usage.total };+}+interface AddPromptInput {promptSetId: string;text: string;diff --git a/web/src/lib/region.test.ts b/web/src/lib/region.test.tsindex ef149fbca..460dea340 100644--- a/web/src/lib/region.test.ts+++ b/web/src/lib/region.test.ts@@ -1,11 +1,18 @@import { describe, expect, it } from 'vitest';-import { formatRegionDisplay, regionFlag, regionLabel } from './region';+import {+ formatRegionDisplay,+ isValidLocation,+ locationCode,+ parseLocation,+ regionFlag,+ regionLabel,+} from './region';++const usFlag = String.fromCodePoint(0x1f1fa, 0x1f1f8);describe('region display helpers', () => {it('shows a known region as flag plus country name', () => {- const usFlag = String.fromCodePoint(0x1f1fa, 0x1f1f8);-expect(regionLabel('US')).toBe('United States');expect(regionFlag('US')).toBe(usFlag);expect(formatRegionDisplay('US')).toBe(`${usFlag} United States`);@@ -24,3 +31,44 @@ describe('region display helpers', () => {expect(formatRegionDisplay('USA')).toBe('USA');});});++describe('location codes', () => {+ it('shows a US state under its country flag, named by the state', () => {+ expect(regionLabel('US-CA')).toBe('California');+ expect(regionFlag('US-CA')).toBe(usFlag);+ expect(formatRegionDisplay('US-CA')).toBe(`${usFlag} California`);+ });++ it('parses countries and US states', () => {+ expect(parseLocation('DE')).toEqual({ country: 'DE', state: null });+ expect(parseLocation('us-ca')).toEqual({ country: 'US', state: 'CA' });+ });++ it('keeps Delaware distinct from Germany', () => {+ // 'DE' is both a country code and a USPS code; only the prefix decides.+ expect(regionLabel('DE')).toBe('Germany');+ expect(regionLabel('US-DE')).toBe('Delaware');+ });++ it('rejects sub-country codes the product cannot track', () => {+ // No non-US sub-country mechanism, and US-ZZ is not a state. Rejecting+ // beats silently degrading to the country: the picker must not offer+ // targeting the worker would quietly ignore.+ expect(parseLocation('DE-BY')).toBeNull();+ expect(parseLocation('US-ZZ')).toBeNull();+ expect(parseLocation('US-CA-1')).toBeNull();+ expect(isValidLocation('DE-BY')).toBe(false);+ });++ it('validates the codes it accepts', () => {+ expect(isValidLocation('US')).toBe(true);+ expect(isValidLocation('US-TX')).toBe(true);+ expect(isValidLocation('ZZ')).toBe(false);+ });++ it('builds codes from a country and optional state', () => {+ expect(locationCode('US')).toBe('US');+ expect(locationCode('US', null)).toBe('US');+ expect(locationCode('us', 'ca')).toBe('US-CA');+ });+});diff --git a/web/src/lib/region.ts b/web/src/lib/region.tsindex 672b7ea43..60db8a034 100644--- a/web/src/lib/region.ts+++ b/web/src/lib/region.ts@@ -1,25 +1,78 @@-import { REGIONS } from '@/config/prompt-options';+import { REGIONS, US_STATES } from '@/config/prompt-options';++/**+ * Tracking locations (#691).+ *+ * A location code is either a bare ISO country (`DE`) or an ISO 3166-2 US+ * state (`US-CA`). One code is one tracked location: one set of scraper and+ * model calls, one plan-quota unit, one `prompt_results.region` value.+ *+ * `server/src/lib/locations.js` keeps a deliberately identical parse — both+ * sides must agree on which codes are valid, or the picker would offer+ * targeting the worker cannot run.+ */const REGION_LABELS: ReadonlyMap<string, string> = new Map(REGIONS.map((region) => [region.code, region.label]),);+const STATE_LABELS: ReadonlyMap<string, string> = new Map(+ US_STATES.map((state) => [state.code, state.label]),+);+function normalizeRegionCode(code: string): string {return code.trim().toUpperCase();}-export function regionLabel(code: string): string {+export interface ParsedLocation {+ country: string;+ /** USPS code when the location targets a US state, else null. */+ state: string | null;+}++/**+ * Split a location code into country and state, or null when it is neither a+ * country we track nor a US state. Sub-country targeting exists for US+ * states only — every other engine mechanism is country-wide.+ */+export function parseLocation(code: string): ParsedLocation | null {const normalized = normalizeRegionCode(code);- return REGION_LABELS.get(normalized) ?? code.trim();+ const [country, state, ...rest] = normalized.split('-');+ if (rest.length > 0 || !REGION_LABELS.has(country)) return null;+ if (state === undefined) return { country, state: null };+ if (country !== 'US' || !STATE_LABELS.has(state)) return null;+ return { country, state };+}++/** True when a code names a location the product can actually track. */+export function isValidLocation(code: string): boolean {+ return parseLocation(code) !== null;+}++/** Build the code for a country, or for one of its states. */+export function locationCode(country: string, state?: string | null): string {+ const normalizedCountry = normalizeRegionCode(country);+ if (!state) return normalizedCountry;+ return `${normalizedCountry}-${normalizeRegionCode(state)}`;+}++/**+ * The location's own name: the state for a state code, the country+ * otherwise. States are shown without their country because the flag beside+ * them already carries it, and lists group them under a country heading.+ */+export function regionLabel(code: string): string {+ const parsed = parseLocation(code);+ if (!parsed) return code.trim();+ if (parsed.state) return STATE_LABELS.get(parsed.state) ?? parsed.state;+ return REGION_LABELS.get(parsed.country) ?? parsed.country;}export function regionFlag(code: string): string {- const normalized = normalizeRegionCode(code);- if (!REGION_LABELS.has(normalized) || !/^[A-Z]{2}$/.test(normalized)) {- return '';- }+ const parsed = parseLocation(code);+ if (!parsed) return '';- const [first, second] = normalized;+ const [first, second] = parsed.country;return String.fromCodePoint(0x1f1e6 + first.charCodeAt(0) - 65,0x1f1e6 + second.charCodeAt(0) - 65,