Files
zeekayandHanzo Dev 57f9435929 Keep every package in one directory
The workspace declared pkg/* and pkgs/* both, so one repo had two names
for one concept and a package's home was a coin toss. The shared build
tooling already lived in pkg/ui/scripts and pkgs reached back into it
two levels up; now it is a sibling. hanzo.yml gates on pkg/ui, so the
published library stays where CI already looks and the rest joins it.

The publish glob follows: one root, one pattern, nothing invisible to it.

Co-authored-by: Hanzo Dev <[email protected]>
2026-09-08 23:50:28 -07:00

246 lines
10 KiB
JavaScript

#!/usr/bin/env node
/**
* Copy the taxonomy down from the catalog that owns it.
*
* WHICH categories exist, in WHICH order, and which of them each brand's console
* admits are one question with one owner: hanzoai/commerce, which answers it at
* GET /v1/commerce/catalog. This package used to answer it a second time, by
* hand, and the two answers disagreed — commerce sold `Dev` (eight products) and
* this package sold `Commerce` (none), so `normalizeEntry` dropped every Dev row
* the live catalog served and no test noticed, because the test asserted the
* hand answer.
*
* So the hand answer is gone. `src/taxonomy.generated.ts` and
* `snapshot/catalog.json` are both written here, from the API, and everything
* else in the package reads them. A category is renamed, added or retired in
* commerce; this script carries it; nothing here is edited.
*
* Three rules, the same three as the marketing site's scripts/sync-catalog.mjs,
* for the same reasons:
*
* NEVER FAIL ON AN UNREACHABLE API. The checked-in copy is the designed
* fallback — that is what a snapshot IS — so a commerce blip must not stop a
* build or a release.
*
* NEVER REGRESS. A payload carrying fewer products or fewer categories than
* the committed copy is far more likely to be a degraded response than a
* product line being retired, and writing it would silently empty a nav. It is
* refused, and what it would have dropped is printed. A genuine retirement is
* accepted by deleting those rows from the committed copy and re-running.
*
* NEVER GO QUIET. Print what was fetched, what was written, and what changed.
* The failure this package actually had was not a wrong list; it was a stale
* one that nothing announced.
*
* Usage:
* node scripts/sync.mjs refresh the generated files
* node scripts/sync.mjs --check fail if they disagree with the API (CI)
*/
import { readFileSync, writeFileSync } from "fs"
import { dirname, resolve } from "path"
import { fileURLToPath } from "url"
const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), "..")
const GENERATED = resolve(ROOT, "src/taxonomy.generated.ts")
const SNAPSHOT = resolve(ROOT, "snapshot/catalog.json")
const ORIGIN = process.env.HANZO_CATALOG_ORIGIN ?? "https://api.hanzo.ai"
const CATALOG = (brand) => `${ORIGIN}/v1/commerce/catalog?brand=${brand}`
/** Every brand whose console shows a category-scoped slice of the catalog. */
const BRANDS = ["hanzo", "lux", "zoo", "pars"]
const read = (path) => {
try {
return readFileSync(path, "utf8")
} catch {
return null
}
}
/** One brand's slice, or null when the catalog cannot be reached. */
async function slice(brand) {
const res = await fetch(CATALOG(brand), { headers: { accept: "application/json" } })
if (!res.ok) throw new Error(`${CATALOG(brand)} → HTTP ${res.status}`)
const body = await res.json()
const served = body?.categories ?? []
const categories = served.map((c) => c.label)
const colors = Object.fromEntries(served.filter((c) => c.color).map((c) => [c.label, c.color]))
const products = body?.products ?? []
if (!categories.length) throw new Error(`${brand} served no categories`)
return { categories, colors, products }
}
/** The accents the committed file already carries, so a deploy that predates
* Category.color keeps them instead of writing an empty map. */
const heldColors = (src) =>
Object.fromEntries([...(src ?? "").matchAll(/^ {2}"([^"]+)": "([^"]+)",$/gm)].map((m) => [m[1], m[2]]))
/**
* The generated module. A `const` tuple rather than a plain array, because the
* union every consumer types against is read off it — so a category that is not
* in the catalog cannot be named anywhere in the package, and a category that IS
* cannot be left without its display copy. That is the whole enforcement; there
* is no list to keep in step with it.
*/
const emit = (categories, scope, colors) =>
// The canonical source is named, not whatever origin happened to run the sync:
// the file's content must not depend on the host it was fetched from, or a
// check run against a staging origin reports a diff that is only the header.
`// Generated by scripts/sync.mjs from https://api.hanzo.ai/v1/commerce/catalog. Do not edit.
//
// hanzoai/commerce owns this taxonomy — it is the catalog admin.hanzo.ai edits
// and the API every surface reads. Run \`pnpm sync\` to carry a change down.
/** Every product category, in the catalog's display order. */
export const CATEGORIES = [
${categories.map((c) => ` ${JSON.stringify(c)},`).join("\n")}
] as const
/** The categories each brand's console admits. \`null\` = all of them. */
export const BRAND_SCOPE = {
${BRANDS.map((b) => ` ${b}: ${scope[b] === null ? "null" : `[${scope[b].map((c) => JSON.stringify(c)).join(", ")}]`},`).join("\n")}
} as const
/**
* The accent each category reads as — a swatch key, resolved to css by
* \`swatchHex\`, exactly like a product's \`brandColor\`.
*
* Served by the catalog, not chosen per surface: a category drawn teal in the
* console and indigo on the site is two different categories to anyone looking
* at both, which is what happened while this mapping lived in two files and was
* owned by neither.
*/
export const COLORS = {
${categories.map((c) => ` ${JSON.stringify(c)}: ${JSON.stringify(colors[c])},`).join("\n")}
} as const
`
/** The snapshot row — the package's contract, filled from the catalog's answer. */
const row = (p) => ({
id: p.id,
name: p.name,
category: p.category,
brandColor: p.brandColor,
iconKey: p.iconKey,
slug: p.slug,
route: p.route,
docsUrl: p.docsUrl,
apiPath: p.apiPath ?? "",
kind: p.kind ?? "service",
pricingId: p.pricingId ?? null,
brands: p.brands ?? [],
repo: p.repo ?? null,
admin: p.admin === true,
status: p.status === "soon" ? "soon" : "enabled",
gcp: p.gcp ?? null,
})
async function main() {
const check = process.argv.includes("--check")
console.log(`[taxonomy] reading ${CATALOG("hanzo")}`)
let hanzo
const scope = {}
try {
hanzo = await slice("hanzo")
for (const brand of BRANDS) {
if (brand === "hanzo") {
scope[brand] = null
continue
}
const s = await slice(brand)
// A brand admitting every category is `null`, not a copy of the whole
// list: "all of them" is one fact, and spelling it out is a second place
// the list has to be right.
scope[brand] = s.categories.length === hanzo.categories.length ? null : s.categories
}
} catch (err) {
// Unreachable is not disagreement. The committed copy stands, and a check
// that could not read the source reports that rather than inventing a pass
// or a failure.
console.warn(`[taxonomy] keeping the committed copy — ${err.message}`)
return 0
}
const heldGenerated = read(GENERATED)
const heldSnapshot = read(SNAPSHOT)
const held = heldSnapshot ? JSON.parse(heldSnapshot) : []
// A category's accent comes from the catalog like everything else here. A
// deployment older than Category.color serves none, and the committed accents
// stand rather than being blanked — the same rule as an unreachable API, for
// the same reason. Said out loud, because a copy that quietly stops being
// checked is exactly how this package drifted in the first place.
const carried = heldColors(heldGenerated)
const colors = Object.fromEntries(hanzo.categories.map((c) => [c, hanzo.colors[c] ?? carried[c]]))
const missing = hanzo.categories.filter((c) => !colors[c])
if (missing.length) {
console.error(`[taxonomy] no accent for ${missing.join(", ")} — the catalog serves none and none is committed`)
return 1
}
if (!Object.keys(hanzo.colors).length) {
console.warn(
"[taxonomy] the catalog serves no category colour yet — keeping the committed accents.\n" +
" They are enforced once a commerce carrying Category.color is deployed."
)
}
const nextGenerated = emit(hanzo.categories, scope, colors)
const nextSnapshot = JSON.stringify(hanzo.products.map(row), null, 2) + "\n"
console.log(
`[taxonomy] ${hanzo.categories.length} categories · ${hanzo.products.length} products` +
(heldSnapshot ? ` (committed copy holds ${held.length})` : "")
)
// What the committed generated file claims, read back out of it, so the check
// can name the category that disagrees instead of just reporting a byte diff.
const heldCategories = [...(heldGenerated ?? "").matchAll(/^ {2}"([^"]+)",$/gm)].map((m) => m[1])
if (heldSnapshot && hanzo.products.length < held.length) {
const kept = new Set(hanzo.products.map((p) => p.id))
const dropped = held.map((p) => p.id).filter((id) => !kept.has(id))
console.warn(
`[taxonomy] keeping the committed copy — the catalog serves ${hanzo.products.length}, ` +
`fewer than the committed ${held.length}. Would have dropped: ${dropped.join(", ")}.\n` +
` If that is a real retirement, delete those rows from ${SNAPSHOT} and re-run.`
)
return 0
}
const same = nextGenerated === heldGenerated && nextSnapshot === heldSnapshot
if (check) {
if (same) {
console.log("[taxonomy] the committed copy matches the catalog")
return 0
}
const gone = heldCategories.filter((c) => !hanzo.categories.includes(c))
const added = hanzo.categories.filter((c) => !heldCategories.includes(c))
const recolored = hanzo.categories
.filter((c) => carried[c] && hanzo.colors[c] && carried[c] !== hanzo.colors[c])
.map((c) => `${c} is ${carried[c]} here and ${hanzo.colors[c]} in the catalog`)
console.error(
`[taxonomy] the committed copy DISAGREES with ${CATALOG("hanzo")}.\n` +
(gone.length ? ` committed categories the catalog does not serve: ${gone.join(", ")}\n` : "") +
(added.length ? ` categories the catalog serves that are not committed: ${added.join(", ")}\n` : "") +
(recolored.length ? ` accents differ: ${recolored.join("; ")}\n` : "") +
(nextSnapshot !== heldSnapshot ? ` the product snapshot differs too\n` : "") +
` Run \`pnpm sync\` and commit the result.`
)
return 1
}
writeFileSync(GENERATED, nextGenerated)
writeFileSync(SNAPSHOT, nextSnapshot)
console.log(same ? "[taxonomy] already current" : `[taxonomy] wrote ${GENERATED} and ${SNAPSHOT}`)
console.log(`[taxonomy] ${hanzo.categories.join(" · ")}`)
return 0
}
main()
.then((code) => process.exit(code))
.catch((err) => {
console.error(`[taxonomy] ${err.message}`)
process.exit(1)
})