@cybermp-community/resource-builder 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +303 -2
  3. package/dist/cli.d.ts +1 -0
  4. package/dist/cli.js +584 -0
  5. package/dist/cli.js.map +1 -0
  6. package/dist/index.d.ts +1040 -0
  7. package/dist/index.js +1 -0
  8. package/dist/run-CmhtmY2x.js +7018 -0
  9. package/dist/run-CmhtmY2x.js.map +1 -0
  10. package/package.json +64 -3
  11. package/schema/config.json +122 -0
  12. package/templates/project-default/Dockerfile +17 -0
  13. package/templates/project-default/README.md +57 -0
  14. package/templates/project-default/_dockerignore +26 -0
  15. package/templates/project-default/_gitignore +32 -0
  16. package/templates/project-default/addons/gamemode/browser/env.d.ts +1 -0
  17. package/templates/project-default/addons/gamemode/browser/index.html +12 -0
  18. package/templates/project-default/addons/gamemode/browser/package.json +21 -0
  19. package/templates/project-default/addons/gamemode/browser/src/App.vue +40 -0
  20. package/templates/project-default/addons/gamemode/browser/src/global.d.ts +7 -0
  21. package/templates/project-default/addons/gamemode/browser/src/main.ts +4 -0
  22. package/templates/project-default/addons/gamemode/browser/tsconfig.json +7 -0
  23. package/templates/project-default/addons/gamemode/browser/vite.config.ts +15 -0
  24. package/templates/project-default/addons/gamemode/client/src/global.d.ts +5 -0
  25. package/templates/project-default/addons/gamemode/client/src/index.ts +11 -0
  26. package/templates/project-default/addons/gamemode/client/tsconfig.json +4 -0
  27. package/templates/project-default/addons/gamemode/package.json +22 -0
  28. package/templates/project-default/addons/gamemode/resource.toml +12 -0
  29. package/templates/project-default/addons/gamemode/server/src/global.d.ts +5 -0
  30. package/templates/project-default/addons/gamemode/server/src/index.ts +13 -0
  31. package/templates/project-default/addons/gamemode/server/tsconfig.json +7 -0
  32. package/templates/project-default/addons/gamemode/shared/src/index.ts +2 -0
  33. package/templates/project-default/biome.json +43 -0
  34. package/templates/project-default/cybermp.config.json +6 -0
  35. package/templates/project-default/docker-compose.yml +19 -0
  36. package/templates/project-default/package.json +25 -0
  37. package/templates/project-default/pnpm-workspace.yaml +6 -0
  38. package/templates/project-default/server.toml +21 -0
  39. package/templates/project-default/tsconfig.json +7 -0
  40. package/templates/types.json +15 -0
  41. package/tsconfig.base.json +17 -0
@@ -0,0 +1 @@
1
+ {"version":3,"file":"run-CmhtmY2x.js","names":["realDirectory","isDirectory","isInside","readPackage","errorMessage","requireTable","describe","parseAddons","compareStrings","errorMessage","isErrno","compareStrings","errorMessage","isInside","isErrno","OVERRIDE_KEYS","BROWSER_DIR","exists","rewriteManifest","compareStrings","errorMessage","isErrno","isInside","describe","isDirectory","readPackage","errorMessage","GITHUB_API","download","extractArchive","stringField","errorMessage","safeEntry","listTar","extractTar","isErrno","errorMessage","BROWSER_DIR","KILL_GRACE_MS","KILL_POLL_MS","MAX_OUTPUT","isDirectory","isErrno","message","isRecord","signalTree","isTreeAlive","tail","readManifest","isInside","errorMessage","isDirectory","errorMessage","isInside","PLATFORMS","rejectUnknownKeys","optionalString","errorMessage","isErrno","optionalBoolean","hostPlatform","describe","errorMessage","isErrno","errorMessage","errorMessage","describe","isErrno","isInside","isFile","SERVERTOML_FILENAME","isErrno","isErrno","isInside","isErrno","errorMessage","errorMessage","readText","errorMessage","errorMessage","errorMessage","errorMessage"],"sources":["../src/errors.ts","../src/addons/local.ts","../src/addons/lock.ts","../src/addons/files.ts","../src/addons/materialize.ts","../src/addons/order.ts","../src/zip.ts","../src/addons/installRecord.ts","../src/addons/sources/path.ts","../src/addons/sources/release.ts","../src/addons/sources/spec.ts","../src/addons/sources/npm.ts","../src/build/browser.ts","../src/addons/npm.ts","../src/addons/release.ts","../src/config.ts","../src/project.ts","../src/redscripts/build.ts","../src/redscripts/compilers.ts","../src/redscripts/compiler.ts","../src/serverToml.ts","../src/build/local.ts","../src/build/index.ts","../src/check.ts","../src/commands/addons.ts","../src/scaffold/render.ts","../src/scaffold/types.ts","../src/commands/init.ts","../src/commands/create.ts","../src/server/download.ts","../src/server/run.ts"],"sourcesContent":["/**\n * The builder's error type.\n *\n * Same contract as `AddonError` in `@cybermp-community/addon`: a stable,\n * machine-readable `code` of the shape `area.reason` (for example\n * `config.unknown-key`) and a message formatted as `<code>: <human message>`,\n * so callers can match codes with a regex and still print something readable.\n */\nexport class BuilderError extends Error {\n /** Stable code, e.g. `config.parse`. Never localized. */\n readonly code: string;\n\n constructor(code: string, message: string) {\n super(`${code}: ${message}`);\n this.name = 'BuilderError';\n this.code = code;\n }\n}\n\n/**\n * The subset of the addon validator's `Issue` this module needs. Declared\n * structurally so the builder does not depend on the addon package here.\n */\nexport interface AddonIssueLike {\n code: string;\n level: string;\n message: string;\n}\n\n/**\n * Turn a failed `validateAddon` pass into a {@link BuilderError}.\n *\n * The first error's code is kept as the builder error's code, so an install\n * that fails because the package has no marker still reports\n * `package.missing-marker` — the code the author's own `cybermp-addon check`\n * printed — and every other error is appended to the message so one command\n * run names every reason.\n */\nexport function invalidAddonError(label: string, issues: readonly AddonIssueLike[]): BuilderError {\n const errors = issues.filter((issue) => issue.level === 'error');\n const [first] = errors;\n const detail = errors.map((issue) => `${issue.code}: ${issue.message}`).join('; ');\n return new BuilderError(\n first?.code ?? 'addon.invalid',\n `${label} is not a valid addon${detail === '' ? '' : `: ${detail}`}`,\n );\n}\n","/**\n * Local addon discovery: expand `addons.local` globs and read each directory's\n * `cybermp` package marker.\n *\n * A glob may match files as well as directories (`addons/*` also sees a README),\n * so anything that is not a directory is ignored. Every directory that is kept\n * must be a valid addon: a directory without a `cybermp.resource` marker, or\n * with a malformed marker, fails with the addon package's own error code rather\n * than being skipped, because a silently missing addon is much harder to debug\n * than a failed build.\n *\n * Returned directories are absolute real paths, so symlinked addons and\n * overlapping globs collapse to one entry.\n */\nimport { globSync, realpathSync, statSync } from 'node:fs';\nimport { isAbsolute, join, relative, resolve, sep } from 'node:path';\nimport { AddonError, type AddonPackage, readAddonPackage } from '@cybermp-community/addon';\nimport { BuilderError } from '../errors.js';\nimport type { ResolvedAddon } from './types.js';\n\n/**\n * Resolve every local addon matching `patterns`.\n *\n * Globs are expanded relative to `root`. Non-directory matches are skipped,\n * duplicates (the same directory matched twice, directly or through a symlink)\n * are returned once, and the result is sorted by real path for a deterministic\n * order independent of the filesystem.\n *\n * Errors: glob expansion failures are `addons.glob`, stat/realpath failures are\n * `addons.stat` / `addons.realpath`, a matched directory whose real path leaves\n * the project root is `addons.outside-root`, and a matched directory that is not\n * a valid addon rethrows the addon package's error (`package.missing`,\n * `package.bad-json`, `package.missing-marker`, …) with the directory named in\n * the message.\n */\nexport async function resolveLocalAddons(\n root: string,\n patterns: string[],\n): Promise<ResolvedAddon[]> {\n const projectRoot = resolve(root);\n if (patterns.length === 0) return [];\n\n const matches = globAddons(patterns, projectRoot);\n if (matches.length === 0) return [];\n\n const projectRealRoot = realDirectory(projectRoot);\n const seen = new Set<string>();\n const addons: ResolvedAddon[] = [];\n\n for (const match of matches) {\n const candidate = isAbsolute(match) ? match : join(projectRoot, match);\n if (!isDirectory(candidate)) continue;\n\n const dir = realDirectory(candidate);\n if (!isInside(projectRealRoot, dir)) {\n throw new BuilderError(\n 'addons.outside-root',\n `addon directory \\`${dir}\\` resolves outside the project root \\`${projectRealRoot}\\``,\n );\n }\n if (seen.has(dir)) continue;\n seen.add(dir);\n\n const addon = readPackage(dir);\n addons.push({\n name: addon.resource,\n dir,\n version: addon.version,\n source: 'local',\n requires: addon.requires,\n kind: addon.build === false ? 'prebuilt' : 'source',\n });\n }\n\n return addons.sort((left, right) => (left.dir < right.dir ? -1 : left.dir > right.dir ? 1 : 0));\n}\n\nfunction globAddons(patterns: string[], cwd: string): string[] {\n try {\n // Sorted before stat/read so a broken addon fails the same way on every run.\n return [...new Set(globSync(patterns, { cwd }))].sort();\n } catch (error) {\n throw new BuilderError(\n 'addons.glob',\n `cannot expand addon globs in \\`${cwd}\\`: ${errorMessage(error)}`,\n );\n }\n}\n\nfunction isDirectory(path: string): boolean {\n try {\n return statSync(path, { throwIfNoEntry: false })?.isDirectory() ?? false;\n } catch (error) {\n throw new BuilderError('addons.stat', `cannot inspect \\`${path}\\`: ${errorMessage(error)}`);\n }\n}\n\nfunction realDirectory(path: string): string {\n try {\n return realpathSync(path);\n } catch (error) {\n throw new BuilderError('addons.realpath', `cannot resolve \\`${path}\\`: ${errorMessage(error)}`);\n }\n}\n\n/**\n * True when `target` is `root` or a descendant of it. `path.relative` returns\n * an absolute path for a different Windows drive, hence both checks.\n */\nfunction isInside(root: string, target: string): boolean {\n const path = relative(root, target);\n return path === '' || (!isAbsolute(path) && path !== '..' && !path.startsWith(`..${sep}`));\n}\n\nfunction readPackage(dir: string): AddonPackage {\n try {\n return readAddonPackage(dir);\n } catch (error) {\n if (error instanceof AddonError) {\n // Keep the addon package's code but add the directory: the raw message\n // describes the marker, not which addon carries it.\n throw new AddonError(error.code, `in \\`${dir}\\`: ${errorDetail(error)}`);\n }\n throw error;\n }\n}\n\n/** Message without the `<code>: ` prefix the error type already adds. */\nfunction errorDetail(error: AddonError): string {\n const prefix = `${error.code}: `;\n return error.message.startsWith(prefix) ? error.message.slice(prefix.length) : error.message;\n}\n\nfunction errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n","/**\n * `cybermp.lock.json` — the committed record of addons that did not come from\n * npm (release archives and local paths).\n *\n * npm addons are pinned by the package manager's own lockfile, so duplicating\n * them here would only create two sources of truth that can disagree. This file\n * therefore never records npm-sourced addons, and this module never reads or\n * writes npm resolution — that belongs entirely to the package manager lockfile.\n * Every other source is recorded with the exact resolved version plus the\n * evidence needed to reinstall it: the archive URL and integrity hash for a\n * release, the path for a local addon, the tag when the source was a moving\n * reference.\n *\n * The file is committed, so it is serialized deterministically — addon keys\n * sorted, two-space indent, trailing newline — and a missing file reads as an\n * empty lock, which is what a project with only npm addons has.\n */\nimport { readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';\nimport { join } from 'node:path';\nimport {\n isValidResourceName,\n RESERVED_RESOURCE_NAMES,\n RESOURCE_NAME_PATTERN,\n} from '@cybermp-community/addon';\nimport { BuilderError } from '../errors.js';\n\n/** Name of the lock file, relative to the project root. */\nexport const LOCK_FILENAME = 'cybermp.lock.json';\n\n/** The only lock format this version of the builder understands. */\nexport const LOCK_VERSION = 1;\n\n/**\n * Where a locked addon came from.\n *\n * The contract's entry shape admits `npm`, but npm addons are pinned by the\n * package manager and are never recorded here: installers write only `release`\n * and `path` entries, and nothing in this module resolves npm packages.\n */\nexport type LockSource = 'release' | 'path' | 'npm';\n\n/**\n * One locked addon, keyed by resource name — deliberately not by package name:\n * one package may ship a differently named resource, and the lock follows the\n * resource the project loads.\n */\nexport interface LockEntry {\n /** How the addon was installed. */\n source: LockSource;\n /** Exact installed version. */\n resolved: string;\n /** `sha256-…` digest of the downloaded archive, for `release` entries. */\n integrity?: string;\n /** Archive URL the addon was downloaded from, for `release` entries. */\n url?: string;\n /** Project-relative path the addon was installed from, for `path` entries. */\n path?: string;\n /** Release tag requested at install time, when it was not a fixed version. */\n tag?: string;\n /** Whether the entry asked for a pinned tag instead of the latest release. */\n pinned?: boolean;\n}\n\n/** The parsed contents of `cybermp.lock.json`. */\nexport interface AddonLock {\n version: typeof LOCK_VERSION;\n addons: Record<string, LockEntry>;\n}\n\nconst SOURCES: ReadonlySet<string> = new Set<LockSource>(['release', 'path', 'npm']);\n\nconst STRING_FIELDS = ['integrity', 'url', 'path', 'tag'] as const;\n\nconst ROOT_KEYS: ReadonlySet<string> = new Set(['version', 'addons']);\n\nconst ENTRY_KEYS: ReadonlySet<string> = new Set([\n 'source',\n 'resolved',\n 'integrity',\n 'url',\n 'path',\n 'tag',\n 'pinned',\n]);\n\n/**\n * Read `<root>/cybermp.lock.json`.\n *\n * A missing file is an empty lock (a project may have no non-npm addons).\n * Malformed JSON or an entry of the wrong shape is `lock.parse`; both the root\n * key set (`version`, `addons`) and the entry key set are closed, so a hand-edit\n * typo is reported instead of being dropped on the next write — a misspelled\n * `addons` must not read as an empty lock. Every `addons` key must be a\n * non-reserved resource name (`lock.parse` otherwise): the key becomes a\n * directory under the work dir and `ResolvedAddon.name`, so it is validated\n * like one. A `version` other than `1` is\n * `lock.unsupported-version`, so an older builder refuses a newer lock instead\n * of silently reading it partially; the version is checked before the root keys\n * so a future format reports its version, not its new fields.\n */\nexport function readLock(root: string): AddonLock {\n const file = join(root, LOCK_FILENAME);\n const text = readLockText(file);\n if (text === undefined) return { version: LOCK_VERSION, addons: {} };\n\n const table = requireTable(parseJson(text, file), LOCK_FILENAME);\n if (table.version !== LOCK_VERSION) {\n throw new BuilderError(\n 'lock.unsupported-version',\n `${LOCK_FILENAME} has version ${describe(table.version)}; ` +\n `this builder supports version ${LOCK_VERSION}`,\n );\n }\n\n for (const key of Object.keys(table)) {\n if (ROOT_KEYS.has(key)) continue;\n throw new BuilderError('lock.parse', `unknown key \\`${key}\\` in ${LOCK_FILENAME}`);\n }\n\n return { version: LOCK_VERSION, addons: parseAddons(table.addons) };\n}\n\n/**\n * Write `<root>/cybermp.lock.json` deterministically.\n *\n * Entries are sorted by resource name and the file is replaced atomically, so a\n * crashed write cannot leave a half-written lock behind for the next build to\n * parse.\n */\nexport function writeLock(root: string, lock: AddonLock): void {\n const file = join(root, LOCK_FILENAME);\n const addons: Record<string, LockEntry> = {};\n\n for (const name of Object.keys(lock.addons).sort(compareStrings)) {\n const entry = lock.addons[name];\n if (entry === undefined) continue;\n addons[name] = serializeEntry(entry);\n }\n\n const text = `${JSON.stringify({ version: LOCK_VERSION, addons }, null, 2)}\\n`;\n const temporary = `${file}.${process.pid}.tmp`;\n\n try {\n writeFileSync(temporary, text);\n renameSync(temporary, file);\n } catch (error) {\n rmSync(temporary, { force: true });\n throw new BuilderError(\n 'lock.write',\n `cannot write ${LOCK_FILENAME}: ${errorMessage(error)}`,\n );\n }\n}\n\n/**\n * Field order in the file is canonical rather than whatever order the caller\n * happened to build the object in, so writing an entry read back from disk (or\n * merged from two sources) never reorders a committed line.\n */\nfunction serializeEntry(entry: LockEntry): LockEntry {\n const serialized: LockEntry = { source: entry.source, resolved: entry.resolved };\n for (const field of STRING_FIELDS) {\n const value = entry[field];\n if (value !== undefined) serialized[field] = value;\n }\n if (entry.pinned !== undefined) serialized.pinned = entry.pinned;\n return serialized;\n}\n\nfunction readLockText(file: string): string | undefined {\n try {\n return readFileSync(file, 'utf8');\n } catch (error) {\n if (isErrno(error, 'ENOENT')) return undefined;\n throw new BuilderError('lock.read', `cannot read ${LOCK_FILENAME}: ${errorMessage(error)}`);\n }\n}\n\nfunction parseJson(text: string, file: string): unknown {\n try {\n return JSON.parse(text);\n } catch (error) {\n throw new BuilderError('lock.parse', `invalid JSON in ${file}: ${errorMessage(error)}`);\n }\n}\n\nfunction parseAddons(value: unknown): Record<string, LockEntry> {\n if (value === undefined) return {};\n const table = requireTable(value, 'addons');\n const addons: Record<string, LockEntry> = {};\n\n for (const [name, raw] of Object.entries(table)) {\n validateKey(name);\n addons[name] = parseEntry(name, raw);\n }\n\n return addons;\n}\n\n/**\n * A lock key is a resource name, not free text: `resolveReleaseAddons` uses it\n * as the resource directory under the work dir and as `ResolvedAddon.name`, so\n * `../x`, `a/b` or a name the toolchain reserves (`final_redscripts`, `core`,\n * …) would write somewhere the builder does not own. A malformed key is\n * `lock.parse`, the same code as any other hand-edit the reader refuses.\n */\nfunction validateKey(name: string): void {\n if (!isValidResourceName(name)) {\n throw new BuilderError(\n 'lock.parse',\n `invalid \\`addons\\` key ${JSON.stringify(name)} in ${LOCK_FILENAME}: ` +\n `a key must be a resource name matching \\`${RESOURCE_NAME_PATTERN.source}\\``,\n );\n }\n if (RESERVED_RESOURCE_NAMES.includes(name)) {\n throw new BuilderError(\n 'lock.parse',\n `invalid \\`addons\\` key \\`${name}\\` in ${LOCK_FILENAME}: ` +\n 'that name is reserved by the toolchain',\n );\n }\n}\n\nfunction parseEntry(name: string, value: unknown): LockEntry {\n const path = `addons.${name}`;\n const table = requireTable(value, path);\n\n for (const key of Object.keys(table)) {\n if (ENTRY_KEYS.has(key)) continue;\n throw badEntry(path, `unknown key \\`${key}\\``);\n }\n\n const source = table.source;\n if (typeof source !== 'string' || !SOURCES.has(source)) {\n throw badEntry(\n path,\n `\\`source\\` must be \\`release\\`, \\`path\\` or \\`npm\\`, got ${describe(source)}`,\n );\n }\n\n const resolved = table.resolved;\n if (typeof resolved !== 'string' || resolved === '') {\n throw badEntry(\n path,\n `\\`resolved\\` must be a non-empty string, got ${describe(resolved)}`,\n );\n }\n\n const entry: LockEntry = { source: source as LockSource, resolved };\n for (const field of STRING_FIELDS) {\n const fieldValue = table[field];\n if (fieldValue === undefined) continue;\n if (typeof fieldValue !== 'string') {\n throw badEntry(path, `\\`${field}\\` must be a string, got ${describe(fieldValue)}`);\n }\n entry[field] = fieldValue;\n }\n\n const pinned = table.pinned;\n if (pinned !== undefined) {\n if (typeof pinned !== 'boolean') {\n throw badEntry(path, `\\`pinned\\` must be a boolean, got ${describe(pinned)}`);\n }\n entry.pinned = pinned;\n }\n\n return entry;\n}\n\nfunction requireTable(value: unknown, path: string): Record<string, unknown> {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) {\n throw badEntry(path, `must be an object, got ${describe(value)}`);\n }\n return value as Record<string, unknown>;\n}\n\nfunction badEntry(path: string, problem: string): BuilderError {\n return new BuilderError('lock.parse', `invalid \\`${path}\\` in ${LOCK_FILENAME}: ${problem}`);\n}\n\nfunction describe(value: unknown): string {\n if (value === undefined) return 'nothing';\n if (value === null) return 'null';\n if (Array.isArray(value)) return 'an array';\n if (typeof value === 'object') return 'an object';\n if (typeof value === 'string') return `a string (${JSON.stringify(value)})`;\n return `a ${typeof value}`;\n}\n\nfunction compareStrings(left: string, right: string): number {\n if (left === right) return 0;\n return left < right ? -1 : 1;\n}\n\nfunction errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\nfunction isErrno(error: unknown, code: string): boolean {\n return (\n typeof error === 'object' &&\n error !== null &&\n (error as { code?: unknown }).code === code\n );\n}\n","/**\n * Expansion of a manifest's `file` patterns, shared by materialization and\n * redscript collection.\n *\n * Both stages have to agree on what a manifest ships: if materialization\n * expands globs while the collector treats them as literals, an addon with\n * `file = [\"scripts/*.reds\"]` ships scripts that never get compiled. This is\n * the one place a `file` pattern is resolved, so the two cannot drift.\n *\n * The screen is the same for every pattern, whatever the area: an absolute\n * path or a `..` segment would reach outside the addon and is refused before\n * anything is read from disk, and every match is resolved through\n * `realpath` so a symlink cannot smuggle a file from outside the package.\n * Broken symlinks are skipped — a glob legitimately matches them, and there is\n * nothing to copy or compile.\n *\n * Errors are reported under the caller's area: `<area>.path-outside` for a\n * pattern or match that leaves the addon, `<area>.bad-pattern` for a glob the\n * platform rejects, `<area>.addon-missing` for an addon root that cannot be\n * resolved, and `<area>.read` for a match that exists but cannot be inspected.\n */\nimport { globSync, realpathSync, statSync } from 'node:fs';\nimport { isAbsolute, join, relative, sep } from 'node:path';\nimport { BuilderError } from '../errors.js';\n\n/** One file matched by a `file` pattern. */\nexport interface ExpandedFile {\n /** Path relative to the addon root, as matched by the glob. */\n path: string;\n /** Real path, verified to be inside the addon root. */\n real: string;\n}\n\n/**\n * Expand one `file` pattern inside `addonRoot`, returning every match that\n * stays inside it, sorted for a deterministic order.\n *\n * `area` prefixes the error codes (`materialize`, `redscripts`), so each stage\n * keeps its own stable namespace while sharing the rules.\n */\nexport function expandFilePattern(\n addonRoot: string,\n pattern: string,\n area: string,\n): ExpandedFile[] {\n const safe = manifestPath(pattern, 'file', area);\n const root = realRoot(addonRoot, area);\n\n let matches: string[];\n try {\n matches = globSync(safe, { cwd: root }).sort(compareStrings);\n } catch (error) {\n throw new BuilderError(\n `${area}.bad-pattern`,\n `\\`file\\` pattern \\`${pattern}\\` is not a valid glob: ${errorMessage(error)}`,\n );\n }\n\n const files: ExpandedFile[] = [];\n const seen = new Set<string>();\n for (const match of matches) {\n // `globSync` returns the platform separator; every consumer compares these\n // paths against `/`-separated manifest strings, so normalize once here —\n // on Windows `browser\\index.html` must read as `browser/index.html`.\n const path = match.split(sep).join('/');\n if (seen.has(path)) continue;\n seen.add(path);\n\n const real = realMatch(root, path, area);\n if (real === undefined) continue;\n if (!isInside(root, real)) {\n throw new BuilderError(\n `${area}.path-outside`,\n `\\`file\\` pattern \\`${pattern}\\` matches \\`${path}\\`, which resolves outside the addon ` +\n `directory \\`${root}\\`; paths must stay inside the addon package`,\n );\n }\n files.push({ path, real });\n }\n return files;\n}\n\n/**\n * Normalize one manifest path to a relative POSIX path.\n *\n * The screen is lexical and runs before anything is read from disk: an\n * absolute path or a `..` segment would let a manifest copy an arbitrary file\n * into the resources dir. A Windows-authored `\\` is a separator on any host, so\n * the same manifest behaves identically everywhere.\n */\nexport function manifestPath(value: string, key: string, area: string): string {\n const posix = value.replace(/\\\\/g, '/');\n if (isAbsolute(value) || /^[a-zA-Z]:\\//.test(posix) || posix.startsWith('//')) {\n throw pathOutside(area, key, value, 'is absolute');\n }\n\n const segments = posix.split('/').filter((segment) => segment !== '' && segment !== '.');\n if (segments.length === 0) {\n throw pathOutside(area, key, value, 'names no file');\n }\n if (segments.includes('..')) {\n throw pathOutside(area, key, value, 'escapes the addon');\n }\n return segments.join('/');\n}\n\n/** Real path of the addon root, shared by every pattern of that addon. */\nfunction realRoot(addonRoot: string, area: string): string {\n try {\n return realpathSync(addonRoot);\n } catch (error) {\n throw new BuilderError(\n `${area}.addon-missing`,\n `cannot resolve addon directory \\`${addonRoot}\\`: ${errorMessage(error)}`,\n );\n }\n}\n\n/**\n * Real path of one match, or undefined when it is a broken symlink. Glob\n * matches are optional by nature — a directory or a dangling link is simply\n * not a file the addon ships.\n */\nfunction realMatch(root: string, match: string, area: string): string | undefined {\n try {\n return realpathSync(join(root, match));\n } catch (error) {\n if (isErrno(error, 'ENOENT') || isErrno(error, 'ENOTDIR')) return undefined;\n throw new BuilderError(\n `${area}.read`,\n `cannot resolve \\`file\\` match \\`${match}\\` in addon \\`${root}\\`: ${errorMessage(error)}`,\n );\n }\n}\n\n/** True when `match` names an existing regular file, not a directory. */\nexport function isFileMatch(file: ExpandedFile): boolean {\n try {\n return statSync(file.real).isFile();\n } catch {\n return false;\n }\n}\n\nfunction pathOutside(area: string, key: string, value: string, reason: string): BuilderError {\n return new BuilderError(\n `${area}.path-outside`,\n `\\`${key}\\` \\`${value}\\` ${reason}; paths must stay inside the addon package`,\n );\n}\n\n/**\n * True when `target` is `root` or a descendant of it. `path.relative` returns\n * an absolute path for a different Windows drive, hence both checks.\n */\nfunction isInside(root: string, target: string): boolean {\n const path = relative(root, target);\n return path === '' || (!isAbsolute(path) && path !== '..' && !path.startsWith(`..${sep}`));\n}\n\n/** Code-unit comparison: the same answer on every host and locale. */\nfunction compareStrings(left: string, right: string): number {\n if (left === right) return 0;\n return left < right ? -1 : 1;\n}\n\nfunction isErrno(error: unknown, code: string): boolean {\n return typeof error === 'object' && error !== null && (error as { code?: unknown }).code === code;\n}\n\nfunction errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n","/**\n * Materialization: copy one resolved addon into the resources directory the\n * server loads with `-rdir`.\n *\n * The copy is exactly what the addon declares — `resource.toml`, every `file`\n * glob match, every script and a local `cef_url` target — never the whole\n * package, so sources, tests and build leftovers cannot leak into a client's\n * resources. Relative paths are preserved. A `source` addon never ships its\n * `browser/` subtree nor its scripts: the build step writes the browser\n * directory and the `client.js`/`server.js`/`shared.js` bundles into the copy\n * in a later stage, and copying the authored versions over them would ship\n * stale assets.\n *\n * Project overrides (`cef_url`, `hotreload`, `use_game_natives`) rewrite the\n * copied TOML text only; the addon package is read-only input and is never\n * modified. Rewriting the text rather than re-serializing the manifest keeps\n * comments and formatting of the copy intact.\n *\n * The builder deletes only directories it created. Ownership lives in the work\n * directory (`<workDir>/built.json`, `join(config.workDir, REGISTRY_FILENAME)`),\n * outside `-rdir` so the server never loads it and `readdir` of the resources\n * dir lists resources only. The registry is a sorted array of `{ name, owner }`\n * claims — `addon` for a materialized copy, `redscripts` for the generated\n * scripts — so a directory each stage legitimately names twice is only removed\n * once the last claim is gone. A directory in the resources dir that the\n * registry does not name is refused (`materialize.not-owned`) rather than\n * overwritten. Cleanup prunes an entry only once its directory is really gone,\n * so a half-finished build keeps its leftovers attributed to the builder and\n * the next build replaces them.\n *\n * The generated redscripts directory is owned the same way: {@link\n * claimOwnedDir} and {@link dropOwnedDir} are the claim-and-release pair this\n * module uses internally, and the redscripts stage calls them with its own\n * `redscripts.*` codes. A hand-written `resources/final_redscripts/` is\n * therefore refused exactly like a hand-written addon copy, and a build that\n * turns the stage off cannot leave the previous compile behind.\n *\n * Every manifest path is relative to the addon root and must stay inside it,\n * lexically and through symlinks; anything that escapes is `path-outside`\n * rather than copied.\n */\nimport {\n existsSync,\n readFileSync,\n renameSync,\n rmSync,\n type Stats,\n writeFileSync,\n} from 'node:fs';\nimport { copyFile, mkdir, readFile, realpath, rename, rm, stat, writeFile } from 'node:fs/promises';\nimport { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';\nimport {\n filePatterns,\n isRemoteCefUrl,\n parseManifest,\n type ResourceManifest,\n SCRIPT_KEYS,\n scriptList,\n} from '@cybermp-community/addon';\nimport { BuilderError } from '../errors.js';\nimport { expandFilePattern, manifestPath } from './files.js';\nimport type { AddonKind, ResolvedAddon } from './types.js';\n\n/** The manifest every addon carries; always part of a materialized copy. */\nexport const MANIFEST_FILENAME = 'resource.toml';\n\n/** File name of the ownership registry, for `join(config.workDir, …)`. */\nexport const REGISTRY_FILENAME = 'built.json';\n\n/**\n * Who owns a resource directory: an addon copy (`materializeAddon`) or the\n * generated scripts (the redscripts stage). The registry records the owner of\n * every claim, because two stages can name one directory and a stage may only\n * delete what nobody else still claims.\n */\nexport type Owner = 'addon' | 'redscripts';\n\n/** One claim in the registry, as written to `built.json`. */\nexport interface RegistryEntry {\n /** Resource name — the directory under the resources dir. */\n name: string;\n /** The stage that owns it. */\n owner: Owner;\n}\n\n/**\n * The error area each owner reports under, so a collision names the stage the\n * user has to fix: an addon copy is `materialize.*`, the generated scripts\n * `redscripts.*`.\n */\nconst OWNER_AREA: Record<Owner, string> = {\n addon: 'materialize',\n redscripts: 'redscripts',\n};\n\n/** What to tell the user when a directory belongs to someone else. */\nconst NOT_OWNED_REMEDY: Record<Owner, string> = {\n addon: 'move or delete it by hand',\n redscripts: 'remove it, or set `redscripts.output` to another name',\n};\n\n/** Manifest fields a project may override on the materialized copy. */\nexport type Overrides = Partial<\n Pick<ResourceManifest, 'cef_url' | 'hotreload' | 'use_game_natives'>\n>;\n\n/** Top-level manifest keys an override may touch, in rewrite order. */\nconst OVERRIDE_KEYS = ['cef_url', 'hotreload', 'use_game_natives'] as const;\n\n/** The directory only the browser build supplies, for `source` addons. */\nconst BROWSER_DIR = 'browser';\n\n/**\n * Materialize `addon` into `<outRoot>/<addon.name>` and return the copied\n * paths, relative to the resource directory, with `resource.toml` first.\n *\n * The target directory is replaced when the registry already owns it, which is\n * what makes a rebuild remove files the addon no longer ships. `overrides`\n * rewrites the copied manifest only.\n *\n * `registryPath` is the ownership list (`<workDir>/built.json`) and is required:\n * it is not derivable from `outRoot`, since the resources dir and the work dir\n * are configured independently. Build it as\n * `join(config.workDir, REGISTRY_FILENAME)` and pass the same path to\n * {@link cleanOwnedDirs}; both read and write it.\n *\n * Precondition: resource names are already unique. Duplicate detection lives in\n * `orderAddons`, which rejects two addons claiming one name; calling this twice\n * for the same name overwrites the earlier copy instead of reporting a clash.\n *\n * Errors: a target directory the registry does not own is\n * `materialize.not-owned`, a resource name that is not a single path segment is\n * `materialize.bad-name`, an unreadable or malformed addon root is\n * `materialize.addon-missing`, a missing manifest is `materialize.no-manifest`,\n * a declared script or `cef_url` that does not exist is `materialize.missing`,\n * a path that leaves the addon root is `materialize.path-outside`, an\n * unreadable glob is `materialize.bad-pattern`, and a malformed registry is\n * `materialize.registry`. A manifest that does not parse keeps the addon\n * package's `manifest.*` code.\n */\nexport async function materializeAddon(\n addon: ResolvedAddon,\n outRoot: string,\n registryPath: string,\n overrides: Overrides = {},\n): Promise<string[]> {\n // Claim the directory before writing into it: a copy that fails halfway\n // leaves an owned directory the next build replaces instead of refusing, and\n // a directory someone else created is refused here, before anything is lost.\n const dest = await claimOwnedDir(registryPath, outRoot, addon.name);\n if (await exists(dest)) await rm(dest, { recursive: true, force: true });\n\n const root = await addonRoot(addon);\n const text = await readManifestText(root, addon.name);\n const manifest = parseManifest(text);\n const candidates = collectCandidates(root, manifest, addon.kind);\n\n await mkdir(dest, { recursive: true });\n const copied: string[] = [];\n for (const candidate of candidates) {\n if (await copyCandidate(root, dest, candidate)) copied.push(candidate.path);\n }\n await writeFile(join(dest, MANIFEST_FILENAME), rewriteManifest(text, overrides));\n\n return [MANIFEST_FILENAME, ...copied.sort(compareStrings)];\n}\n\n/**\n * Claim `<outRoot>/<name>` for `owner` in the ownership registry and return the\n * directory's path.\n *\n * Materialization and the redscripts stage both write a resource directory the\n * builder owns; this is the shared step. A directory that already exists but\n * has no registry entry belongs to someone else and is refused\n * (`<area>.not-owned`) instead of taken over. The entry is written before the\n * caller writes anything, so a stage that fails halfway leaves an owned\n * directory that the next build replaces and `cleanOwnedDirs` still finds.\n *\n * `owner` is recorded with the claim and picks both the error code and the\n * remedy: an addon copy reports `materialize.not-owned` and tells the user to\n * move or delete the directory, the generated scripts `redscripts.not-owned`\n * and points at `redscripts.output`.\n *\n * Errors: a name that is not one path segment is `<area>.bad-name`; registry\n * read and write failures are `materialize.registry`.\n */\nexport async function claimOwnedDir(\n registryPath: string,\n outRoot: string,\n name: string,\n owner: Owner = 'addon',\n): Promise<string> {\n const dest = join(resolve(outRoot), safeResourceName(name, owner));\n const registry = await readRegistry(registryPath);\n\n if ((await exists(dest)) && !registry.some((entry) => entry.name === name)) {\n throw new BuilderError(\n `${OWNER_AREA[owner]}.not-owned`,\n `resources directory \\`${dest}\\` is not owned by the builder (no entry in ` +\n `\\`${registryPath}\\`); ${NOT_OWNED_REMEDY[owner]}`,\n );\n }\n\n await writeRegistry(registryPath, [...registry, { name, owner }]);\n return dest;\n}\n\n/**\n * Give up `owner`'s claim on `<outRoot>/<name>`.\n *\n * A stage that is skipped or turned off must not leave the output a previous\n * build wrote, or the server keeps loading resources the build no longer\n * produces. The directory is removed only once the claim being dropped was the\n * last one: while another owner still names it — an addon copy that happens to\n * share the generated name — the directory is that owner's and only our entry\n * goes. A directory nobody claims is left untouched (the builder deletes only\n * what it created), and a directory that is already gone is not an error: the\n * claim is pruned either way.\n *\n * Errors: `<area>.clean` when the last claim's directory cannot be removed (the\n * entry stays, so the next build still owns the leftovers), and\n * `materialize.registry` for registry read and write failures.\n */\nexport async function dropOwnedDir(\n registryPath: string,\n outRoot: string,\n name: string,\n owner: Owner = 'addon',\n): Promise<void> {\n const registry = await readRegistry(registryPath);\n // A hand-edited registry must not be able to delete outside `outRoot`.\n if (!isSafeResourceName(name)) return;\n\n const remaining = registry.filter((entry) => entry.name !== name || entry.owner !== owner);\n // We hold no claim: nothing to drop, and nothing of ours to delete.\n if (remaining.length === registry.length) return;\n\n // Another owner still names this directory: release the claim, keep the copy.\n if (remaining.some((entry) => entry.name === name)) {\n await writeRegistry(registryPath, remaining);\n return;\n }\n\n const dir = join(resolve(outRoot), name);\n try {\n await rm(dir, { recursive: true, force: true });\n } catch (error) {\n throw new BuilderError(\n `${OWNER_AREA[owner]}.clean`,\n `cannot remove the generated resource directory \\`${dir}\\`: ${errorMessage(error)}`,\n );\n }\n\n await writeRegistry(registryPath, remaining);\n}\n\n/**\n * Remove the resource directories named by the registry — and nothing else.\n *\n * A hand-managed resource next to the generated ones is never touched: it has\n * no registry entry, so `materializeAddon` would have refused to take it over\n * as well. A missing registry is a no-op.\n *\n * `names`, when given, limits the sweep to that subset of the registry. A\n * filtered build (`--filter`) rebuilds only the named addons, so it must clean\n * only their directories; an entry outside the subset is left in the registry\n * and its directory is left in place, so a partial build never deletes the\n * output of the addons it did not rebuild.\n *\n * An entry is pruned once its directory has been removed, so a directory the\n * user creates later under that name is foreign: the next build refuses it with\n * `materialize.not-owned` instead of silently deleting it. An entry whose\n * directory is already gone — or whose removal failed — is kept, because the\n * builder may still own that path and a half-finished build must not turn its\n * leftovers into foreign directories. The registry is rewritten atomically, and\n * only when an entry was actually pruned.\n *\n * Errors: a registry that cannot be read, parsed or rewritten is\n * `materialize.registry`.\n */\nexport function cleanOwnedDirs(\n registryPath: string,\n outRoot: string,\n names?: ReadonlySet<string>,\n): void {\n let text: string;\n try {\n text = readFileSync(registryPath, 'utf8');\n } catch (error) {\n if (isErrno(error, 'ENOENT')) return;\n throw new BuilderError(\n 'materialize.registry',\n `cannot read the ownership registry \\`${registryPath}\\`: ${errorMessage(error)}`,\n );\n }\n\n const out = resolve(outRoot);\n const remaining: RegistryEntry[] = [];\n let pruned = false;\n\n // Grouped by name: every claim on one directory is answered together, and\n // removing the directory prunes all of them.\n const claims = new Map<string, RegistryEntry[]>();\n for (const entry of parseRegistry(text, registryPath)) {\n const group = claims.get(entry.name);\n if (group === undefined) claims.set(entry.name, [entry]);\n else group.push(entry);\n }\n\n for (const [name, group] of claims) {\n // Outside the requested subset, the directory stays owned and untouched.\n if (names !== undefined && !names.has(name)) {\n remaining.push(...group);\n continue;\n }\n // A hand-edited registry must not be able to delete outside `outRoot`.\n if (!isSafeResourceName(name)) {\n remaining.push(...group);\n continue;\n }\n\n const dir = join(out, name);\n if (!existsSync(dir)) {\n remaining.push(...group);\n continue;\n }\n\n try {\n rmSync(dir, { recursive: true, force: true });\n } catch {\n remaining.push(...group);\n continue;\n }\n pruned = true;\n }\n\n if (pruned) writeRegistrySync(registryPath, remaining);\n}\n\n/** One file the manifest asks for; `required` entries must exist. */\ninterface Candidate {\n path: string;\n required: boolean;\n}\n\n/**\n * Every path the manifest references, in a deterministic order.\n *\n * `file` glob matches are optional: a broad glob legitimately sweeps up\n * directories, which are skipped. Scripts and a local `cef_url` name one file\n * each, so a match that is missing or not a file is an error. The manifest\n * itself is always copied separately and is filtered out here, since `file`\n * may name it.\n */\nfunction collectCandidates(root: string, manifest: ResourceManifest, kind: AddonKind): Candidate[] {\n const candidates = new Map<string, Candidate>();\n\n const add = (path: string, required: boolean): void => {\n if (kind === 'source' && isBrowserPath(path)) return;\n if (path === MANIFEST_FILENAME) return;\n const existing = candidates.get(path);\n if (existing !== undefined) existing.required ||= required;\n else candidates.set(path, { path, required });\n };\n\n for (const pattern of filePatterns(manifest)) {\n for (const match of expandFilePattern(root, pattern, 'materialize')) add(match.path, false);\n }\n\n // A `source` addon's scripts are build outputs, not shipped files: the build\n // step writes them into the copy. Copying them from the addon root would both\n // fail (they do not exist yet) and clobber the freshly built bundle, so they\n // are skipped for source addons exactly like the `browser/` subtree above.\n if (kind !== 'source') {\n for (const key of SCRIPT_KEYS) {\n for (const value of scriptList(manifest, key)) {\n add(manifestPath(value, key, 'materialize'), true);\n }\n }\n }\n\n const cefUrl = manifest.cef_url;\n if (cefUrl !== undefined && !isRemoteCefUrl(cefUrl)) {\n add(manifestPath(cefUrl, 'cef_url', 'materialize'), true);\n }\n\n return [...candidates.values()].sort((left, right) => compareStrings(left.path, right.path));\n}\n\n/** Copy one candidate; returns false when an optional match is not a file. */\nasync function copyCandidate(root: string, dest: string, candidate: Candidate): Promise<boolean> {\n const source = await realSource(root, candidate);\n if (source === undefined) return false;\n\n let info: Stats;\n try {\n info = await stat(source);\n } catch {\n if (candidate.required) {\n throw new BuilderError(\n 'materialize.missing',\n `\\`${candidate.path}\\` does not exist in addon \\`${root}\\``,\n );\n }\n return false;\n }\n\n if (!info.isFile()) {\n if (candidate.required) {\n throw new BuilderError(\n 'materialize.missing',\n `\\`${candidate.path}\\` is not a regular file in addon \\`${root}\\``,\n );\n }\n return false;\n }\n\n const target = join(dest, candidate.path);\n await mkdir(dirname(target), { recursive: true });\n await copyFile(source, target);\n return true;\n}\n\n/** Real path of a candidate, refusing one that resolves outside the addon. */\nasync function realSource(root: string, candidate: Candidate): Promise<string | undefined> {\n let real: string;\n try {\n real = await realpath(join(root, candidate.path));\n } catch {\n if (candidate.required) {\n throw new BuilderError(\n 'materialize.missing',\n `\\`${candidate.path}\\` does not exist in addon \\`${root}\\``,\n );\n }\n return undefined;\n }\n\n if (!isInside(root, real)) {\n throw new BuilderError(\n 'materialize.path-outside',\n `\\`${candidate.path}\\` resolves outside the addon directory \\`${root}\\``,\n );\n }\n return real;\n}\n\n/** The addon's real root, or `materialize.addon-missing`. */\nasync function addonRoot(addon: ResolvedAddon): Promise<string> {\n try {\n return await realpath(addon.dir);\n } catch (error) {\n throw new BuilderError(\n 'materialize.addon-missing',\n `cannot resolve addon directory \\`${addon.dir}\\`: ${errorMessage(error)}`,\n );\n }\n}\n\nasync function readManifestText(root: string, name: string): Promise<string> {\n try {\n return await readFile(join(root, MANIFEST_FILENAME), 'utf8');\n } catch (error) {\n if (isErrno(error, 'ENOENT')) {\n throw new BuilderError(\n 'materialize.no-manifest',\n `addon \\`${name}\\` has no ${MANIFEST_FILENAME} in \\`${root}\\``,\n );\n }\n throw new BuilderError(\n 'materialize.read',\n `cannot read ${MANIFEST_FILENAME} of addon \\`${name}\\`: ${errorMessage(error)}`,\n );\n }\n}\n\n/** Rewrite the three overridable keys of a manifest text, keeping its layout. */\nfunction rewriteManifest(text: string, overrides: Overrides): string {\n let out = text;\n for (const key of OVERRIDE_KEYS) {\n const value = overrides[key];\n if (value === undefined) continue;\n out = setManifestValue(out, key, renderValue(value));\n }\n return out;\n}\n\n/** A TOML scalar for an override: a basic string or a boolean. */\nfunction renderValue(value: string | boolean): string {\n return typeof value === 'boolean' ? String(value) : JSON.stringify(value);\n}\n\n/**\n * Set a top-level key, replacing its assignment when present and inserting it\n * before the first table otherwise — the key must stay top-level to have any\n * effect. Values are single-line scalars here, so nothing else is touched.\n */\nfunction setManifestValue(text: string, key: string, rendered: string): string {\n const lines = text.split('\\n');\n const assignment = new RegExp(`^\\\\s*${key}\\\\s*=`);\n const firstTable = lines.findIndex((line) => /^\\s*\\[/.test(line));\n\n for (let index = 0; index < lines.length; index += 1) {\n if (firstTable !== -1 && index >= firstTable) break;\n if (!assignment.test(lines[index] ?? '')) continue;\n lines[index] = `${key} = ${rendered}`;\n return lines.join('\\n');\n }\n\n return insertKey(lines, firstTable, `${key} = ${rendered}`);\n}\n\n/** Insert a top-level assignment, keeping one blank line before a table. */\nfunction insertKey(lines: string[], firstTable: number, assignment: string): string {\n if (firstTable === -1) {\n const body = lines.join('\\n').replace(/\\s*$/, '');\n return body === '' ? `${assignment}\\n` : `${body}\\n${assignment}\\n`;\n }\n\n const before = lines.slice(0, firstTable);\n while (before.length > 0 && (before[before.length - 1] ?? '').trim() === '') before.pop();\n const table = lines.slice(firstTable);\n return [...before, assignment, '', ...table].join('\\n');\n}\n\n/** Registry claims in file order, sorted by name then owner, deduplicated. */\nasync function readRegistry(registryPath: string): Promise<RegistryEntry[]> {\n let text: string;\n try {\n text = await readFile(registryPath, 'utf8');\n } catch (error) {\n if (isErrno(error, 'ENOENT')) return [];\n throw new BuilderError(\n 'materialize.registry',\n `cannot read the ownership registry \\`${registryPath}\\`: ${errorMessage(error)}`,\n );\n }\n return parseRegistry(text, registryPath);\n}\n\nfunction parseRegistry(text: string, registryPath: string): RegistryEntry[] {\n let value: unknown;\n try {\n value = JSON.parse(text);\n } catch (error) {\n throw new BuilderError(\n 'materialize.registry',\n `invalid JSON in the ownership registry \\`${registryPath}\\`: ${errorMessage(error)}`,\n );\n }\n if (!Array.isArray(value)) {\n throw new BuilderError(\n 'materialize.registry',\n `\\`${registryPath}\\` must be an array of ownership entries`,\n );\n }\n return sortEntries(value.map((entry, index) => parseRegistryEntry(entry, index, registryPath)));\n}\n\n/**\n * One registry entry. A bare name is the format older builders wrote, and every\n * entry they could write was an addon copy (the generated scripts had no entry\n * at all), so it reads as `addon` — a work directory from an older build keeps\n * working instead of failing the next one.\n */\nfunction parseRegistryEntry(entry: unknown, index: number, registryPath: string): RegistryEntry {\n if (typeof entry === 'string') return { name: entry, owner: 'addon' };\n\n if (typeof entry === 'object' && entry !== null && !Array.isArray(entry)) {\n const { name, owner } = entry as Record<string, unknown>;\n if (typeof name === 'string' && (owner === 'addon' || owner === 'redscripts')) {\n return { name, owner };\n }\n }\n\n throw new BuilderError(\n 'materialize.registry',\n `\\`${registryPath}\\` entry ${index} must be a resource name or { name, owner } with ` +\n 'owner `addon` or `redscripts`',\n );\n}\n\n/** Sort by name then owner, dropping duplicates: one claim per name and owner. */\nfunction sortEntries(entries: RegistryEntry[]): RegistryEntry[] {\n const seen = new Set<string>();\n return [...entries]\n .sort(\n (left, right) =>\n compareStrings(left.name, right.name) || compareStrings(left.owner, right.owner),\n )\n .filter((entry) => {\n const key = `${entry.owner}:${entry.name}`;\n if (seen.has(key)) return false;\n seen.add(key);\n return true;\n });\n}\n\n/** Write the registry atomically: a torn file would read as an unknown owner. */\nasync function writeRegistry(registryPath: string, entries: RegistryEntry[]): Promise<void> {\n const body = registryText(entries);\n const temporary = `${registryPath}.${process.pid}.tmp`;\n\n try {\n await mkdir(dirname(registryPath), { recursive: true });\n await writeFile(temporary, body);\n await rename(temporary, registryPath);\n } catch (error) {\n await rm(temporary, { force: true }).catch(() => undefined);\n throw new BuilderError(\n 'materialize.registry',\n `cannot write the ownership registry \\`${registryPath}\\`: ${errorMessage(error)}`,\n );\n }\n}\n\n/** Synchronous twin of {@link writeRegistry}, for the sync cleanup pass. */\nfunction writeRegistrySync(registryPath: string, entries: RegistryEntry[]): void {\n const body = registryText(entries);\n const temporary = `${registryPath}.${process.pid}.tmp`;\n\n try {\n writeFileSync(temporary, body);\n renameSync(temporary, registryPath);\n } catch (error) {\n rmSync(temporary, { force: true });\n throw new BuilderError(\n 'materialize.registry',\n `cannot write the ownership registry \\`${registryPath}\\`: ${errorMessage(error)}`,\n );\n }\n}\n\n/** The on-disk form: a sorted array of `{ name, owner }`, one per line. */\nfunction registryText(entries: RegistryEntry[]): string {\n return `${JSON.stringify(\n sortEntries(entries).map((entry) => ({ name: entry.name, owner: entry.owner })),\n null,\n 2,\n )}\\n`;\n}\n\nasync function exists(path: string): Promise<boolean> {\n try {\n await stat(path);\n return true;\n } catch (error) {\n if (isErrno(error, 'ENOENT')) return false;\n throw new BuilderError(\n 'materialize.stat',\n `cannot inspect \\`${path}\\`: ${errorMessage(error)}`,\n );\n }\n}\n\n/** True when `path` is exactly the `browser` directory or lies inside it. */\nfunction isBrowserPath(path: string): boolean {\n return path === BROWSER_DIR || path.startsWith(`${BROWSER_DIR}/`);\n}\n\n/** A resource name is the directory's own name, never a path. */\nfunction safeResourceName(name: string, owner: Owner = 'addon'): string {\n if (!isSafeResourceName(name)) {\n throw new BuilderError(\n `${OWNER_AREA[owner]}.bad-name`,\n `\\`${name}\\` is not a usable resource name: it must be one path segment`,\n );\n }\n return name;\n}\n\nfunction isSafeResourceName(name: string): boolean {\n return (\n name !== '' &&\n name !== '.' &&\n name !== '..' &&\n !name.includes('/') &&\n !name.includes('\\\\') &&\n !isAbsolute(name)\n );\n}\n\n/**\n * True when `target` is `root` or a descendant of it. `path.relative` returns\n * an absolute path for a different Windows drive, hence both checks.\n */\nfunction isInside(root: string, target: string): boolean {\n const path = relative(root, target);\n return path === '' || (!isAbsolute(path) && path !== '..' && !path.startsWith(`..${sep}`));\n}\n\n/** Code-unit comparison: the same answer on every host and locale. */\nfunction compareStrings(left: string, right: string): number {\n if (left === right) return 0;\n return left < right ? -1 : 1;\n}\n\nfunction isErrno(error: unknown, code: string): boolean {\n return typeof error === 'object' && error !== null && (error as { code?: unknown }).code === code;\n}\n\nfunction errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n","/**\n * Load order: the sequence addons appear in `server.toml.resources`.\n *\n * The order is a topological sort over the `requires` edges, and it is fully\n * deterministic — `cybermp check` compares the resolved order against the file\n * on disk, so any environmental wobble would flap CI. Ties between addons that\n * are ready at the same time break on their index in `addons.order`, then on\n * the resource name (plain code-unit order, not locale-aware).\n *\n * Disabled addons still take part in validation: a requirement they carry must\n * resolve, and a cycle that runs through them is still a broken graph. They are\n * dropped from the result afterwards, so nothing downstream builds or lists\n * them — which is also why an enabled addon may not require one.\n */\nimport { BuilderError } from '../errors.js';\nimport type { ResolvedAddon } from './types.js';\n\n/**\n * Return the addons in load order: a dependency precedes every addon that\n * requires it, independent addons follow `order` and then their names, and\n * disabled addons are removed.\n *\n * Errors: a resource name supplied by two addons is `addon.duplicate-name`\n * (both sources are named), an `addons.order`, `addons.disabled` or\n * `addons.overrides` entry that names no resolved addon is `order.unknown-name`,\n * a requirement that no addon provides is `order.unknown-requires`, an enabled\n * addon requiring a disabled one is `order.disabled-requires`, and a cycle is\n * `order.cycle` with its members in edge order.\n */\nexport function orderAddons(\n addons: ResolvedAddon[],\n order: string[],\n disabled: string[],\n overrides: readonly string[] = [],\n): ResolvedAddon[] {\n const byName = indexByName(addons);\n validateConfigNames(byName, order, disabled, overrides);\n validateRequires(addons, byName);\n validateDependenciesEnabled(addons, disabled);\n\n const ordered = sortTopologically(addons, byName, order);\n const skipped = new Set(disabled);\n return ordered.filter((addon) => !skipped.has(addon.name));\n}\n\n/**\n * Map resource name to addon, rejecting a name that two addons both provide.\n *\n * A collision is never last-one-wins: which addon won would depend on the\n * discovery order of two unrelated sources.\n */\nfunction indexByName(addons: ResolvedAddon[]): Map<string, ResolvedAddon> {\n const byName = new Map<string, ResolvedAddon>();\n\n for (const addon of addons) {\n const existing = byName.get(addon.name);\n if (existing !== undefined) {\n throw new BuilderError(\n 'addon.duplicate-name',\n `resource \\`${addon.name}\\` is provided by both ${describe(existing)} and ${describe(addon)}`,\n );\n }\n byName.set(addon.name, addon);\n }\n\n return byName;\n}\n\n/** `npm addon at \\`/path\\`` — enough to tell two same-named addons apart. */\nfunction describe(addon: ResolvedAddon): string {\n return `${addon.source} addon at \\`${addon.dir}\\``;\n}\n\n/**\n * `addons.order`, `addons.disabled` and `addons.overrides` all carry explicit\n * user intent: a name there that nothing resolves is a typo or a leftover after\n * a manual edit, and ignoring it would silently change the order, keep an addon\n * enabled, or validate an override that is never applied.\n */\nfunction validateConfigNames(\n byName: Map<string, ResolvedAddon>,\n order: string[],\n disabled: string[],\n overrides: readonly string[],\n): void {\n for (const name of order) {\n if (byName.has(name)) continue;\n throw new BuilderError(\n 'order.unknown-name',\n `\\`addons.order\\` entry \\`${name}\\` does not name a resolved addon`,\n );\n }\n\n for (const name of disabled) {\n if (byName.has(name)) continue;\n throw new BuilderError(\n 'order.unknown-name',\n `\\`addons.disabled\\` entry \\`${name}\\` does not name a resolved addon`,\n );\n }\n\n for (const name of overrides) {\n if (byName.has(name)) continue;\n throw new BuilderError(\n 'order.unknown-name',\n `\\`addons.overrides\\` entry \\`${name}\\` does not name a resolved addon`,\n );\n }\n}\n\n/**\n * Every `requires` entry must name a resolved addon. Disabled addons count as\n * resolved: they are installed, so a dependency on one is a configuration\n * mistake to report, not an unknown name.\n */\nfunction validateRequires(addons: ResolvedAddon[], byName: Map<string, ResolvedAddon>): void {\n for (const addon of [...addons].sort((left, right) => compareStrings(left.name, right.name))) {\n for (const requirement of addon.requires) {\n if (byName.has(requirement)) continue;\n throw new BuilderError(\n 'order.unknown-requires',\n `addon \\`${addon.name}\\` requires \\`${requirement}\\`, which is not installed; add it with \\`cybermp add ${requirement}\\``,\n );\n }\n }\n}\n\n/**\n * `requires` is a hard dependency: a disabled addon never reaches\n * `server.toml`, so a list that orders its dependent looks valid but cannot work\n * at runtime. Disabled addons may still require each other or enabled addons —\n * they are not part of the output.\n */\nfunction validateDependenciesEnabled(addons: ResolvedAddon[], disabled: string[]): void {\n const skipped = new Set(disabled);\n const sorted = [...addons].sort((left, right) => compareStrings(left.name, right.name));\n\n for (const addon of sorted) {\n if (skipped.has(addon.name)) continue;\n for (const requirement of addon.requires) {\n if (!skipped.has(requirement)) continue;\n throw new BuilderError(\n 'order.disabled-requires',\n `addon \\`${addon.name}\\` requires \\`${requirement}\\`, which is disabled by the \\`addons.disabled\\` entry \\`${requirement}\\``,\n );\n }\n }\n}\n\n/**\n * Kahn's algorithm over `requires` edges (requirement → dependent).\n *\n * The ready set is kept sorted by the tie-break rule, so the result depends\n * only on the addon set, the configured order and the names — never on the\n * order the addons were discovered in.\n */\nfunction sortTopologically(\n addons: ResolvedAddon[],\n byName: Map<string, ResolvedAddon>,\n order: string[],\n): ResolvedAddon[] {\n const compare = tieBreaker(order);\n const incoming = new Map<string, number>();\n const dependents = new Map<string, string[]>();\n\n for (const name of byName.keys()) {\n incoming.set(name, 0);\n }\n for (const addon of addons) {\n // A repeated `requires` entry is one edge; the validator normally rejects\n // duplicates, but ordering must not depend on that guarantee.\n const requirements = new Set(addon.requires);\n for (const requirement of requirements) {\n const list = dependents.get(requirement);\n if (list === undefined) dependents.set(requirement, [addon.name]);\n else list.push(addon.name);\n }\n incoming.set(addon.name, requirements.size);\n }\n\n const ready: string[] = [];\n for (const [name, count] of incoming) {\n if (count === 0) ready.push(name);\n }\n ready.sort(compare);\n\n const ordered: ResolvedAddon[] = [];\n while (ready.length > 0) {\n const name = ready.shift();\n if (name === undefined) break;\n\n const addon = byName.get(name);\n if (addon !== undefined) ordered.push(addon);\n\n for (const dependent of dependents.get(name) ?? []) {\n const remaining = (incoming.get(dependent) ?? 0) - 1;\n incoming.set(dependent, remaining);\n if (remaining === 0) {\n ready.push(dependent);\n ready.sort(compare);\n }\n }\n }\n\n if (ordered.length < byName.size) {\n throw cycleError(incoming, addons);\n }\n\n return ordered;\n}\n\n/**\n * Ready-set comparator: index in `addons.order` first (unlisted addons last),\n * then the resource name.\n */\nfunction tieBreaker(order: string[]): (left: string, right: string) => number {\n const positions = new Map<string, number>();\n order.forEach((name, index) => {\n if (!positions.has(name)) positions.set(name, index);\n });\n\n const rank = (name: string): number => positions.get(name) ?? Number.POSITIVE_INFINITY;\n\n return (left, right) => {\n const leftRank = rank(left);\n const rightRank = rank(right);\n if (leftRank !== rightRank) return leftRank < rightRank ? -1 : 1;\n return compareStrings(left, right);\n };\n}\n\n/** Code-unit comparison: the same answer on every host and locale. */\nfunction compareStrings(left: string, right: string): number {\n if (left === right) return 0;\n return left < right ? -1 : 1;\n}\n\n/**\n * Report a cycle by printing it as the chain of edges that actually exists:\n * `a -> b -> a` means `a` requires `b`, which requires `a`. Members follow the\n * `requires` direction, not the alphabetical order used to pick which cycle to\n * report, so the arrows never imply an edge the addons do not declare.\n *\n * Only addons left with unresolved requirements can be in or behind a cycle, so\n * the search starts there; the first cycle found in name order is reported.\n */\nfunction cycleError(incoming: Map<string, number>, addons: ResolvedAddon[]): BuilderError {\n const requiresOf = new Map<string, string[]>();\n for (const addon of addons) requiresOf.set(addon.name, addon.requires);\n\n const stuck = [...incoming.entries()]\n .filter(([, count]) => count > 0)\n .map(([name]) => name)\n .sort(compareStrings);\n\n const cycle = findCycle(stuck, requiresOf);\n if (cycle === undefined || cycle.length === 0) {\n // Unreachable: Kahn leaves at least one requirement unresolved only when a\n // cycle exists, and the search finds one.\n throw new BuilderError(\n 'order.cycle',\n `requires cycle: ${stuck.join(', ')} cannot be ordered`,\n );\n }\n\n // Each member appears once in the chain; the first is repeated as the closing\n // node so the final arrow is the edge that closes the loop.\n return new BuilderError('order.cycle', `requires cycle: ${[...cycle, cycle[0]].join(' -> ')}`);\n}\n\n/**\n * Depth-first search for one cycle among `candidates`. Requirements outside the\n * candidate set are ignored: they already sorted, so they cannot be in a cycle.\n */\nfunction findCycle(\n candidates: string[],\n requiresOf: Map<string, string[]>,\n): string[] | undefined {\n const allowed = new Set(candidates);\n const state = new Map<string, 'visiting' | 'done'>();\n const path: string[] = [];\n\n const visit = (name: string): string[] | undefined => {\n state.set(name, 'visiting');\n path.push(name);\n\n for (const requirement of requiresOf.get(name) ?? []) {\n if (!allowed.has(requirement)) continue;\n const seen = state.get(requirement);\n if (seen === 'visiting') return path.slice(path.indexOf(requirement));\n if (seen === undefined) {\n const cycle = visit(requirement);\n if (cycle !== undefined) return cycle;\n }\n }\n\n path.pop();\n state.set(name, 'done');\n return undefined;\n };\n\n for (const name of candidates) {\n if (state.has(name)) continue;\n const cycle = visit(name);\n if (cycle !== undefined) return cycle;\n }\n\n return undefined;\n}\n","/**\n * Zip-entry screening shared by the toolchain's two archive consumers.\n *\n * `server/download.ts` unpacks server builds and `addons/sources/release.ts`\n * unpacks addon archives. Both accept plain files and directories only, and\n * both refuse a symbolic link entry by its unix mode — a link can point outside\n * the tree that is being unpacked. Keeping the one mode test here means the two\n * screens cannot drift apart again.\n */\nimport type AdmZip from 'adm-zip';\n\n/**\n * True when the entry's unix mode marks it as a symbolic link.\n *\n * `attr` packs the unix mode into its high 16 bits; the file-type field is the\n * four octal digits at `0o170000`. A link entry is refused by both screens, not\n * extracted, because its target is resolved on the host after unpacking.\n */\nexport function isSymlinkEntry(entry: AdmZip.IZipEntry): boolean {\n const mode = (entry.header.attr >>> 16) & 0o170000;\n return mode === 0o120000;\n}\n","/**\n * The install record of a release addon: which archive it was unpacked from and\n * what its files hashed to at that moment.\n *\n * The lock pins the sha256 of the *archive* (`LockEntry.integrity`), and that\n * digest cannot be recomputed from an unpacked tree: compression and archive\n * metadata do not survive extraction. A build therefore cannot compare an\n * installed directory against the lock entry directly. `installRelease` writes\n * this record into the unpacked tree instead, binding the two together:\n *\n * - `integrity` is the archive digest the lock entry carries, so a build can\n * tell that the tree belongs to the locked release and not to another one;\n * - `digest` is {@link hashAddonDirectory} over the unpacked files, so a build\n * can tell whether the files changed after installation.\n *\n * The record is builder state, not addon content. It lives inside the addon\n * directory so it appears and disappears with the installation — it is written\n * into the staging tree, so the rename that installs the addon publishes it\n * atomically — and it is skipped by the directory hash and never materialized\n * (only the files the manifest names are copied into the resources dir).\n *\n * The trust it provides is the trust of an index: it detects drift and edits\n * that do not also rewrite the record. Anything that can rewrite files under\n * the work directory can forge it, exactly as it can edit `cybermp.lock.json`;\n * the archive digest remains the authority `cybermp install` re-verifies\n * against the download.\n */\nimport { readFileSync, writeFileSync } from 'node:fs';\nimport { join } from 'node:path';\n\n/** File name of the record, relative to an installed addon's root. */\nexport const INSTALL_RECORD_FILENAME = '.cybermp-install.json';\n\n/** The only record format this version of the builder writes and reads. */\nconst INSTALL_RECORD_VERSION = 1;\n\n/** What a release installation was unpacked from, and what it hashed to. */\nexport interface InstallRecord {\n /** `sha256-<hex>` digest of the downloaded archive, as the lock records it. */\n integrity: string;\n /** `sha256-<hex>` digest of the installed tree (see `hashAddonDirectory`). */\n digest: string;\n}\n\n/**\n * Write the record of the installation at `dir`.\n *\n * Deterministic (two-space indent, trailing newline), so a reinstalled addon\n * that produced the same tree writes the same bytes.\n */\nexport function writeInstallRecord(dir: string, record: InstallRecord): void {\n const body = {\n version: INSTALL_RECORD_VERSION,\n integrity: record.integrity,\n digest: record.digest,\n };\n writeFileSync(join(dir, INSTALL_RECORD_FILENAME), `${JSON.stringify(body, null, 2)}\\n`);\n}\n\n/**\n * The record of the installation at `dir`, or `undefined` when there is none\n * this builder can use: absent, unreadable, invalid JSON, another version, or a\n * field that is not a non-empty string. The caller reports an unusable tree as\n * unverifiable either way — it cannot be trusted just because it is quiet.\n */\nexport function readInstallRecord(dir: string): InstallRecord | undefined {\n let text: string;\n try {\n text = readFileSync(join(dir, INSTALL_RECORD_FILENAME), 'utf8');\n } catch {\n return undefined;\n }\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(text);\n } catch {\n return undefined;\n }\n if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) return undefined;\n\n const record = parsed as Record<string, unknown>;\n if (record['version'] !== INSTALL_RECORD_VERSION) return undefined;\n const integrity = record['integrity'];\n const digest = record['digest'];\n if (typeof integrity !== 'string' || integrity === '') return undefined;\n if (typeof digest !== 'string' || digest === '') return undefined;\n\n return { integrity, digest };\n}\n","/**\n * Local path addons: register a directory that is already in the project, or\n * snapshot one into it with `--copy`.\n *\n * A path addon is not an installation. Without `--copy` the project only gains\n * a glob in `addons.local` — the directory keeps living where the author put\n * it, and edits are picked up on the next build. The spec's spelling is stored\n * verbatim (`./addons/hud` stays `./addons/hud`), because `cybermp.config.json`\n * is committed and the recorded entry should read exactly like the command that\n * wrote it. `addons.local` is a list of project-relative globs, so a path that\n * leaves the project (`../shared/hud`) cannot be registered that way; it is\n * `add.path-outside`, with `--copy` named as the way to bring it in.\n *\n * `--copy` takes a snapshot into `<root>/addons/<resource>`: sources, tests and\n * build leftovers are part of the addon, but `node_modules` and `.git` are\n * installation state, not content, and are skipped. An existing destination is\n * never overwritten — replacing a directory the user may have edited is\n * `add.exists` rather than a silent merge.\n *\n * Every addon is validated before the config is touched, and a copied tree is\n * validated again in place so a failed copy is removed instead of being left\n * half-registered. The returned addon is `source: 'local'`; the directory hash\n * (`sha256-…` over sorted relative paths and their bytes) is what the lock file\n * records so `cybermp update` can tell a changed local addon.\n */\nimport { createHash } from 'node:crypto';\nimport { existsSync, readdirSync, readFileSync, readlinkSync, statSync } from 'node:fs';\nimport { cp, mkdir, realpath, rm } from 'node:fs/promises';\nimport { basename, isAbsolute, join, relative, resolve, sep } from 'node:path';\nimport {\n AddonError,\n type AddonPackage,\n readAddonPackage,\n validateAddon,\n} from '@cybermp-community/addon';\nimport { BuilderError, invalidAddonError } from '../../errors.js';\nimport { INSTALL_RECORD_FILENAME } from '../installRecord.js';\nimport type { ResolvedAddon } from '../types.js';\nimport type { PathAddonSpec } from './spec.js';\n\n/** Options for {@link registerPathAddon}. */\nexport interface PathAddonOptions {\n /** Copy a snapshot into `<root>/addons/<resource>` instead of registering a glob. */\n copy?: boolean;\n}\n\n/** A registered path addon plus what the caller needs for config and lock. */\nexport interface RegisteredPathAddon {\n addon: ResolvedAddon;\n /** `addons.local` entry to record: the spec spelling, or `./addons/<name>`. */\n entry: string;\n /** `sha256-<hex>` hash of the addon directory. */\n integrity: string;\n}\n\n/** Directories that are installation state, never addon content. */\nconst SKIPPED_DIRECTORIES: ReadonlySet<string> = new Set(['node_modules', '.git']);\n\n/**\n * Register the addon at `spec.path` and return it.\n *\n * Errors: the path is missing or not a directory (`add.path`), leaves the\n * project without `--copy` (`add.path-outside`), a copy target already exists\n * (`add.exists`), the copy itself fails (`add.copy`), and a failed validation\n * keeps the validator's own code (`package.*`, `manifest.*`, `path.*`).\n */\nexport async function registerPathAddon(\n root: string,\n spec: PathAddonSpec,\n options: PathAddonOptions = {},\n): Promise<RegisteredPathAddon> {\n const projectRoot = resolve(root);\n const source = resolve(projectRoot, spec.path);\n\n if (!isDirectory(source)) {\n throw new BuilderError(\n 'add.path',\n `\\`${spec.path}\\` is not a directory${existsSync(source) ? '' : ' (it does not exist)'}`,\n );\n }\n\n const addonPackage = readPackage(source);\n const kind = addonPackage.build === false ? 'prebuilt' : 'source';\n const validation = await validateAddon(source, { kind });\n if (!validation.ok) {\n throw invalidAddonError(`\\`${spec.path}\\``, validation.issues);\n }\n\n if (options.copy === true) {\n return copyPathAddon(projectRoot, source, addonPackage, kind);\n }\n\n const path = relative(projectRoot, source);\n if (isOutside(path)) {\n throw new BuilderError(\n 'add.path-outside',\n `\\`${spec.path}\\` is outside the project root; \\`addons.local\\` accepts project-relative ` +\n 'globs only — pass --copy to snapshot it into ./addons/',\n );\n }\n\n return {\n addon: resolved(source, addonPackage, kind),\n entry: entrySpelling(spec.path, path),\n integrity: await hashAddonDirectory(source),\n };\n}\n\n/**\n * Copy `source` into `<root>/addons/<resource>` and validate the copy in place.\n *\n * The copy is a snapshot: `node_modules` and `.git` are skipped, an existing\n * target is refused, and a validation failure on the copied tree removes it so\n * a broken addon is never left registered.\n */\nasync function copyPathAddon(\n projectRoot: string,\n source: string,\n addonPackage: AddonPackage,\n kind: 'source' | 'prebuilt',\n): Promise<RegisteredPathAddon> {\n const destination = join(projectRoot, 'addons', addonPackage.resource);\n\n if (existsSync(destination)) {\n if (await sameDirectory(source, destination)) {\n throw new BuilderError(\n 'add.copy',\n `\\`${addonPackage.resource}\\` is already at \\`${destination}\\`; it is the source itself`,\n );\n }\n throw new BuilderError(\n 'add.exists',\n `\\`${destination}\\` already exists; remove it before copying this addon over it`,\n );\n }\n\n try {\n await mkdir(join(projectRoot, 'addons'), { recursive: true });\n await cp(source, destination, {\n recursive: true,\n filter: (from) => !SKIPPED_DIRECTORIES.has(basename(from)),\n });\n } catch (error) {\n await rm(destination, { recursive: true, force: true }).catch(() => undefined);\n throw new BuilderError(\n 'add.copy',\n `cannot copy \\`${source}\\` to \\`${destination}\\`: ${errorMessage(error)}`,\n );\n }\n\n const validation = await validateAddon(destination, { kind });\n if (!validation.ok) {\n await rm(destination, { recursive: true, force: true }).catch(() => undefined);\n throw invalidAddonError(`\\`${addonPackage.resource}\\``, validation.issues);\n }\n\n return {\n addon: resolved(destination, addonPackage, kind),\n entry: `./addons/${addonPackage.resource}`,\n integrity: await hashAddonDirectory(destination),\n };\n}\n\n/**\n * The `sha256-<hex>` identity of a directory: sorted relative paths plus file\n * bytes (and symlink targets), so a renamed file or an edited byte changes the\n * hash and a checkout on another machine does not.\n *\n * A release installation's record (`INSTALL_RECORD_FILENAME`) is builder state,\n * not content: it is skipped, so hashing an installed tree gives the digest the\n * record itself stores. A path addon that happens to carry the file is hashed\n * the same way — the name is reserved for the builder.\n */\nexport async function hashAddonDirectory(dir: string): Promise<string> {\n const hash = createHash('sha256');\n const root = resolve(dir);\n\n const walk = (current: string): void => {\n const entries = readdirSync(current, { withFileTypes: true }).sort((left, right) =>\n left.name < right.name ? -1 : left.name > right.name ? 1 : 0,\n );\n\n for (const entry of entries) {\n const path = join(current, entry.name);\n const relativePath = relative(root, path).split(sep).join('/');\n\n // Installation state, not content; see the doc comment above.\n if (entry.name === INSTALL_RECORD_FILENAME && entry.isFile()) continue;\n\n if (entry.isDirectory()) {\n if (SKIPPED_DIRECTORIES.has(entry.name)) continue;\n hash.update(`dir:${relativePath}\\0`);\n walk(path);\n continue;\n }\n if (entry.isSymbolicLink()) {\n hash.update(`link:${relativePath}\\0${readlinkSync(path)}\\0`);\n continue;\n }\n hash.update(`file:${relativePath}\\0`);\n hash.update(readFileSync(path));\n hash.update('\\0');\n }\n };\n\n try {\n walk(root);\n } catch (error) {\n throw new BuilderError('add.hash', `cannot hash \\`${root}\\`: ${errorMessage(error)}`);\n }\n return `sha256-${hash.digest('hex')}`;\n}\n\n/**\n * The `addons.local` spelling of a path addon. An explicit relative spelling is\n * kept as typed; an absolute path or a bare name is rewritten relative to the\n * project root, because the config must stay portable.\n */\nfunction entrySpelling(spec: string, relativePath: string): string {\n if (spec.startsWith('./') || spec.startsWith('.\\\\')) return spec.replace(/\\\\/g, '/');\n return `./${relativePath.split(sep).join('/')}`;\n}\n\n/** A relative path that escapes the root: `..`, or another drive (absolute). */\nfunction isOutside(relativePath: string): boolean {\n return (\n relativePath === '' ||\n isAbsolute(relativePath) ||\n relativePath === '..' ||\n relativePath.startsWith(`..${sep}`)\n );\n}\n\n/** The `AddonPackage` of `dir`, with the addon package's own code preserved. */\nfunction readPackage(dir: string): AddonPackage {\n try {\n return readAddonPackage(dir);\n } catch (error) {\n if (error instanceof AddonError) {\n const prefix = `${error.code}: `;\n const detail = error.message.startsWith(prefix)\n ? error.message.slice(prefix.length)\n : error.message;\n throw new BuilderError(error.code, `\\`${dir}\\`: ${detail}`);\n }\n throw error;\n }\n}\n\n/** The `ResolvedAddon` for a validated local directory. */\nfunction resolved(\n dir: string,\n addonPackage: AddonPackage,\n kind: 'source' | 'prebuilt',\n): ResolvedAddon {\n return {\n name: addonPackage.resource,\n dir,\n version: addonPackage.version,\n source: 'local',\n requires: addonPackage.requires,\n kind,\n };\n}\n\n/** True when `target` is a directory (a broken symlink is not). */\nfunction isDirectory(target: string): boolean {\n try {\n return statSync(target).isDirectory();\n } catch {\n return false;\n }\n}\n\nasync function sameDirectory(left: string, right: string): Promise<boolean> {\n try {\n const [a, b] = await Promise.all([realpath(left), realpath(right)]);\n return a === b;\n } catch {\n return false;\n }\n}\n\nfunction errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n","/**\n * Release installation: download an addon archive from a GitHub/GitLab release\n * or a direct URL, verify it, and unpack it under `<workDir>/addons/<resource>`.\n *\n * A release archive is the distributed form of an addon, so it must carry the\n * same contract an installed package does: `package.json` with a\n * `cybermp.resource` marker and `resource.toml` at the archive root. Nothing is\n * unwrapped and nothing is guessed — an archive that wraps the addon in a\n * top-level directory, or ships no marker, is `release.not-an-addon` rather\n * than a half-installed resource.\n *\n * Asset selection is deliberately strict. A release with exactly one `.zip` or\n * `.tar.gz` asset installs without asking; several archives are an error that\n * names `--asset`, because picking one by size or name order would silently\n * install the wrong platform's build; no archive is an error that points at a\n * direct URL. `--asset` accepts a name or a `*`/`?` glob and must narrow the\n * candidates to exactly one.\n *\n * Integrity is the sha256 of the downloaded bytes, recorded as\n * `sha256-<hex>`. When the release metadata carries a `sha256:` digest (GitHub\n * assets do), the computed hash is checked against it before anything is\n * unpacked; a mismatch is `release.integrity`. The unpacked tree also carries an\n * install record (`.cybermp-install.json`, see `installRecord.ts`) holding that\n * archive digest and the tree's own digest, so a later build can verify the\n * installation without the archive; the record is written into the staging tree\n * before the rename, so it installs atomically with the addon. The archive is\n * downloaded into the work directory and unpacked into a temporary directory\n * there, so the final move into `addons/<resource>` is a rename on one\n * filesystem and a failed install never leaves a partial addon behind.\n *\n * Private repositories and rate limits are handled with `GITHUB_TOKEN` /\n * `GITLAB_TOKEN`; the GitLab host comes from `GITLAB_HOST` (default\n * `gitlab.com`). A token is only attached to a download whose host is the\n * configured API host (or a GitHub-owned host): release assets may live on a\n * mirror or object store, and a credential must not travel there. `apiBase`\n * replaces the API root entirely so tests can run against a local server.\n */\nimport { createHash, randomUUID } from 'node:crypto';\nimport { createWriteStream, existsSync, type Stats, statSync } from 'node:fs';\nimport { mkdir, mkdtemp, readdir, realpath, rename, rm } from 'node:fs/promises';\nimport { join, resolve } from 'node:path';\nimport { Readable, Transform } from 'node:stream';\nimport { pipeline } from 'node:stream/promises';\nimport {\n AddonError,\n type AddonPackage,\n readAddonPackage,\n validateAddon,\n} from '@cybermp-community/addon';\nimport AdmZip from 'adm-zip';\nimport { x as extractTar, t as listTar, type ReadEntry } from 'tar';\nimport { BuilderError, invalidAddonError } from '../../errors.js';\nimport { isSymlinkEntry } from '../../zip.js';\nimport { writeInstallRecord } from '../installRecord.js';\nimport type { ResolvedAddon } from '../types.js';\nimport { hashAddonDirectory } from './path.js';\nimport type { AddonSpec, ReleaseAddonSpec, ReleaseHost } from './spec.js';\n\n/** The public GitHub API root, used when `apiBase` is not given. */\nconst GITHUB_API = 'https://api.github.com';\n\n/** The GitLab host used when `GITLAB_HOST` is not set. */\nconst GITLAB_HOST = 'gitlab.com';\n\ntype ArchiveFormat = 'tar.gz' | 'zip';\n\n/**\n * Tar entry types an addon archive may contain: plain files and directories,\n * plus the PAX metadata headers GNU tar and other packers emit for long or\n * non-ASCII names. Every other type — symlink, hard link, device, FIFO, sparse\n * or vendor-specific — is refused.\n */\nconst TAR_ENTRY_TYPES: ReadonlySet<string> = new Set([\n 'File',\n 'OldFile',\n 'ContiguousFile',\n 'Directory',\n 'GNUDumpDir',\n 'ExtendedHeader',\n 'GlobalExtendedHeader',\n 'OldExtendedHeader',\n]);\n\n/** Types that carry content or a directory; metadata types carry neither. */\nconst TAR_FILE_TYPES: ReadonlySet<string> = new Set([\n 'File',\n 'OldFile',\n 'ContiguousFile',\n 'Directory',\n 'GNUDumpDir',\n]);\n\n/** Statuses an asset download may answer with before serving the archive. */\nconst REDIRECT_STATUSES: ReadonlySet<number> = new Set([301, 302, 303, 307, 308]);\n\n/** Cap on requests for one asset, the first download included. */\nconst MAX_DOWNLOAD_REQUESTS = 10;\n\n/** Options for {@link installRelease}. */\nexport interface ReleaseInstallOptions {\n /** Project root; a relative `workDir` is resolved against it. */\n root: string;\n /** Build work directory — the addon is installed under `<workDir>/addons`. */\n workDir: string;\n /** Asset name or glob, required when a release ships several archives. */\n asset?: string;\n /** API root override, e.g. a local HTTP server in tests. */\n apiBase?: string;\n /**\n * Run the full addon validator over the staged tree before replacing an\n * existing installation. `add` and `update` set this so a rejected addon\n * never destroys the version already installed; `install` leaves it off\n * because it restores a lock entry whose integrity is verified against the\n * archive.\n */\n validate?: boolean;\n}\n\n/** An installed release addon, with the archive integrity for the lock file. */\nexport interface InstalledRelease extends ResolvedAddon {\n /** `sha256-<hex>` digest of the downloaded archive. */\n integrity: string;\n /** URL the archive was downloaded from. */\n url: string;\n /** Release tag the host resolved (or the spec named); absent for a direct URL. */\n tag?: string;\n /** True when the spec named a tag instead of following the latest release. */\n pinned?: boolean;\n}\n\n/** One downloadable asset of a release. */\ninterface ReleaseAsset {\n name: string;\n url: string;\n /** `sha256:<hex>` when the host publishes one. */\n digest?: string;\n}\n\n/** The assets a release offers, plus the host its tokens belong to. */\ninterface ReleaseSource {\n label: string;\n assets: ReleaseAsset[];\n /**\n * Host whose token applies to the API and to downloads. Undefined for a\n * direct URL: the URL points at an arbitrary server, and handing it\n * `GITHUB_TOKEN` would leak a credential to a third party.\n */\n host?: ReleaseHost;\n /**\n * Hosts a token may be sent to, as `host[:port]`. A release host may serve\n * assets from another host (a mirror, object storage, a CDN), so the token\n * is scoped per asset URL instead of per release.\n */\n tokenHosts?: readonly string[];\n /** Tag the release resolved to, when the spec came from a release host. */\n tag?: string;\n /** True when the spec pinned a tag rather than following the latest release. */\n pinned?: boolean;\n}\n\n/**\n * Install the addon described by `spec` and return it with its integrity.\n *\n * Only `release` and `url` specs are handled; npm packages belong to the\n * package manager and paths are already in the project, so both are\n * `release.unsupported-spec` here.\n *\n * The returned addon is `source: 'release'` and `kind: 'prebuilt'`: an archive\n * ships the files to copy, so it is never built. `packageName` stays undefined\n * — the archive's `package.json` name is not an npm dependency, exactly as for\n * a local addon. `url`, `tag` and `pinned` carry what a lock entry needs, so\n * the caller never has to re-resolve the release.\n *\n * Errors: `release.unsupported-spec`, `release.ambiguous-asset`,\n * `release.no-asset`, `release.unsupported-archive`, `release.not-found`,\n * `release.auth`, `release.rate-limit`, `release.http`, `release.network`,\n * `release.bad-response`, `release.download`, `release.integrity`,\n * `release.bad-archive`, `release.extract`, `release.not-an-addon`,\n * `release.install`, `release.redirect`.\n */\nexport async function installRelease(\n spec: AddonSpec,\n opts: ReleaseInstallOptions,\n): Promise<InstalledRelease> {\n const work = resolve(opts.root, opts.workDir);\n\n const source = await resolveSource(spec, opts);\n const asset = spec.kind === 'url' ? source.assets[0] : pickAsset(source, opts.asset);\n if (asset === undefined) {\n throw new BuilderError('release.no-asset', `${source.label} has no archive to install`);\n }\n const format = archiveFormat(asset.name);\n if (format === undefined) {\n throw new BuilderError(\n 'release.unsupported-archive',\n `\\`${asset.name}\\` is not a .zip or .tar.gz archive; addon releases must be one of those`,\n );\n }\n\n await mkdir(work, { recursive: true });\n const temporary = await mkdtemp(join(work, '.release-'));\n\n try {\n const archive = join(temporary, format === 'zip' ? 'archive.zip' : 'archive.tar.gz');\n const digest = await download(asset, archive, source, source.label);\n verifyDigest(asset, digest, source.label);\n\n const staging = join(temporary, 'extract');\n await extractArchive(archive, format, staging, source.label);\n const addon = readReleaseAddon(staging, source.label);\n if (opts.validate === true) await validateStagedAddon(staging, addon);\n\n // Record what the tree came from and what it hashed to while it is still\n // staged, so the record installs atomically with the addon and a lock entry\n // can be verified later without the archive (see `installRecord.ts`).\n const integrity = `sha256-${digest}`;\n writeInstallRecord(staging, { integrity, digest: await hashAddonDirectory(staging) });\n const dir = await installAddon(work, staging, addon);\n\n const installed: InstalledRelease = {\n name: addon.resource,\n dir,\n version: addon.version,\n source: 'release',\n requires: addon.requires,\n kind: 'prebuilt',\n integrity,\n url: asset.url,\n };\n if (source.tag !== undefined) installed.tag = source.tag;\n if (source.pinned !== undefined) installed.pinned = source.pinned;\n return installed;\n } finally {\n // The archive, the staging tree and anything extracted on a failure path.\n await rm(temporary, { recursive: true, force: true }).catch(() => undefined);\n }\n}\n\n/**\n * Turn a spec into the list of assets it offers. A direct URL is a one-asset\n * release; `gh:`/`gl:` ask the host's API, using `apiBase` when given.\n */\nasync function resolveSource(spec: AddonSpec, opts: ReleaseInstallOptions): Promise<ReleaseSource> {\n if (spec.kind === 'url') {\n return {\n label: spec.url,\n assets: [{ name: archiveName(spec.url), url: spec.url }],\n };\n }\n if (spec.kind === 'release') {\n return spec.host === 'github'\n ? fetchGitHubRelease(spec, opts.apiBase)\n : fetchGitLabRelease(spec, opts.apiBase);\n }\n throw new BuilderError(\n 'release.unsupported-spec',\n `\\`installRelease\\` installs release archives, not a \\`${spec.kind}\\` spec`,\n );\n}\n\n/** File name of a direct URL, decoded and stripped of its query. */\nfunction archiveName(url: string): string {\n const pathname = new URL(url).pathname;\n const segment = pathname.slice(pathname.lastIndexOf('/') + 1);\n if (segment === '') return 'archive';\n try {\n return decodeURIComponent(segment);\n } catch {\n return segment;\n }\n}\n\n/**\n * Resolve `gh:<owner>/<repo>[@<tag>]` through the GitHub REST API.\n *\n * Without a tag the repository's latest release is used. Assets expose\n * `browser_download_url` and, on newer API versions, a `digest` such as\n * `sha256:<hex>`.\n */\nasync function fetchGitHubRelease(\n spec: ReleaseAddonSpec,\n apiBase: string | undefined,\n): Promise<ReleaseSource> {\n const base = trimSlash(apiBase ?? GITHUB_API);\n const path =\n spec.tag === undefined\n ? `/repos/${spec.repo}/releases/latest`\n : `/repos/${spec.repo}/releases/tags/${encodeURIComponent(spec.tag)}`;\n const label = `release ${spec.repo}${spec.tag === undefined ? ' (latest)' : `@${spec.tag}`}`;\n\n const payload = await requestJson(\n `${base}${path}`,\n requestHeaders('github', false, true),\n label,\n 'github',\n );\n const release = requireRecord(payload, label);\n const assets = release.assets;\n if (assets !== undefined && !Array.isArray(assets)) {\n throw badResponse(label, 'an `assets` field that is not an array');\n }\n const tag = stringField(release.tag_name) ?? spec.tag;\n\n return {\n host: 'github',\n label,\n tag,\n pinned: spec.tag !== undefined,\n // GitHub serves assets from `github.com` (then redirects to object\n // storage); the API host is trusted too, which keeps an injected\n // `apiBase` working.\n tokenHosts: unique([...hostsOf(base), 'github.com', 'api.github.com']),\n assets: (assets ?? []).map((item) => {\n const asset = requireRecord(item, label);\n const name = stringField(asset.name);\n const url = stringField(asset.browser_download_url);\n if (name === undefined || url === undefined) {\n throw badResponse(label, 'an asset without `name`/`browser_download_url`');\n }\n const digest = stringField(asset.digest);\n return digest === undefined ? { name, url } : { name, url, digest };\n }),\n };\n}\n\n/**\n * Resolve `gl:<group>/<repo>[@<tag>]` through the GitLab API.\n *\n * GitLab publishes release files as `assets.links`; the source tarball GitLab\n * itself offers is not an addon asset and is never picked. Without a tag the\n * newest release from `/releases` is used.\n */\nasync function fetchGitLabRelease(\n spec: ReleaseAddonSpec,\n apiBase: string | undefined,\n): Promise<ReleaseSource> {\n const base = trimSlash(apiBase ?? `https://${process.env.GITLAB_HOST || GITLAB_HOST}/api/v4`);\n const project = encodeURIComponent(spec.repo);\n const path =\n spec.tag === undefined\n ? `/projects/${project}/releases?per_page=1`\n : `/projects/${project}/releases/${encodeURIComponent(spec.tag)}`;\n const label = `release ${spec.repo}${spec.tag === undefined ? ' (latest)' : `@${spec.tag}`}`;\n\n let payload = await requestJson(\n `${base}${path}`,\n requestHeaders('gitlab', false, true),\n label,\n 'gitlab',\n );\n if (Array.isArray(payload)) {\n const latest = payload[0];\n if (latest === undefined)\n throw new BuilderError('release.not-found', `${label} has no releases`);\n payload = latest;\n }\n const release = requireRecord(payload, label);\n const assets = release.assets;\n const links = assets === undefined ? undefined : requireRecord(assets, label).links;\n if (links !== undefined && !Array.isArray(links)) {\n throw badResponse(label, 'an `assets.links` field that is not an array');\n }\n const tag = stringField(release.tag_name) ?? spec.tag;\n\n return {\n host: 'gitlab',\n label,\n tag,\n pinned: spec.tag !== undefined,\n // Only the configured GitLab host owns the token: GitLab release links may\n // point at an object store or a mirror, and `PRIVATE-TOKEN` must not travel\n // there.\n tokenHosts: hostsOf(base),\n assets: (links ?? []).map((item) => {\n const link = requireRecord(item, label);\n const url = stringField(link.direct_asset_url) ?? stringField(link.url);\n const name = stringField(link.name) ?? (url === undefined ? undefined : archiveName(url));\n if (name === undefined || url === undefined) {\n throw badResponse(label, 'an asset link without `name`/`url`');\n }\n return { name, url };\n }),\n };\n}\n\n/**\n * Pick the one archive to install.\n *\n * Without `--asset` a release must offer exactly one supported archive; with\n * `--asset` the pattern must match exactly one. Both \"nothing to pick\" and\n * \"too much to pick\" name the candidates, because the next action is a\n * different command line.\n */\nfunction pickAsset(source: ReleaseSource, requested: string | undefined): ReleaseAsset {\n const archives = source.assets.filter((asset) => archiveFormat(asset.name) !== undefined);\n const available = archives.map((asset) => asset.name);\n\n if (requested !== undefined) {\n const matches = archives.filter((asset) => matchesAssetName(asset.name, requested));\n const [match] = matches;\n if (matches.length === 1 && match !== undefined) return match;\n if (matches.length === 0) {\n throw new BuilderError(\n 'release.no-asset',\n `${source.label} has no archive matching --asset=${requested}` +\n (available.length === 0\n ? '; it ships no .zip or .tar.gz asset'\n : `; available: ${available.join(', ')}`),\n );\n }\n throw new BuilderError(\n 'release.ambiguous-asset',\n `${source.label} has ${matches.length} archives matching --asset=${requested} ` +\n `(${matches.map((asset) => asset.name).join(', ')}); pass a narrower --asset=<name|glob>`,\n );\n }\n\n if (archives.length === 0) {\n throw new BuilderError(\n 'release.no-asset',\n `${source.label} has no .zip or .tar.gz asset; pass the archive URL directly instead`,\n );\n }\n if (archives.length > 1) {\n throw new BuilderError(\n 'release.ambiguous-asset',\n `${source.label} has ${archives.length} archives (${available.join(', ')}); ` +\n 'pass --asset=<name|glob> to choose one',\n );\n }\n const [asset] = archives;\n if (asset === undefined) {\n throw new BuilderError('release.no-asset', `${source.label} has no .zip or .tar.gz asset`);\n }\n return asset;\n}\n\n/** The supported archive format of `name`, judged by its suffix. */\nfunction archiveFormat(name: string): ArchiveFormat | undefined {\n const lower = name.toLowerCase();\n if (lower.endsWith('.tar.gz')) return 'tar.gz';\n if (lower.endsWith('.zip')) return 'zip';\n return undefined;\n}\n\n/** `*`/`?` glob (or exact name) match for `--asset`. */\nfunction matchesAssetName(name: string, pattern: string): boolean {\n if (!/[*?]/.test(pattern)) return name === pattern;\n const expression = pattern\n .split('')\n .map((character) => {\n if (character === '*') return '.*';\n if (character === '?') return '.';\n return character.replace(/[.+^${}()|[\\]\\\\]/g, '\\\\$&');\n })\n .join('');\n return new RegExp(`^${expression}$`).test(name);\n}\n\n/**\n * Ask a release API for JSON, turning transport and status failures into\n * `release.*` errors. The token env var is named in the message so the fix is\n * obvious.\n */\nasync function requestJson(\n url: string,\n headers: Record<string, string>,\n label: string,\n host: ReleaseHost,\n): Promise<unknown> {\n let response: Response;\n try {\n response = await fetch(url, { headers });\n } catch (error) {\n throw new BuilderError(\n 'release.network',\n `cannot reach ${label} at \\`${url}\\`: ${errorMessage(error)}`,\n );\n }\n if (!response.ok) {\n throw httpFailure(\n response.status,\n label,\n url,\n host,\n response.headers.get('x-ratelimit-remaining'),\n );\n }\n try {\n return await response.json();\n } catch (error) {\n throw badResponse(label, `invalid JSON (${errorMessage(error)})`);\n }\n}\n\n/**\n * Stream one asset into `file`, hashing the bytes on the way. The digest is\n * returned rather than read back, so a truncated response cannot be recorded\n * as complete.\n */\nasync function download(\n asset: ReleaseAsset,\n file: string,\n source: ReleaseSource,\n label: string,\n): Promise<string> {\n const response = await openAsset(asset, source, label);\n if (!response.ok) {\n throw httpFailure(\n response.status,\n `download of \\`${asset.name}\\` for ${label}`,\n asset.url,\n source.host,\n response.headers.get('x-ratelimit-remaining'),\n );\n }\n\n const body = response.body;\n if (body === null) {\n throw new BuilderError(\n 'release.download',\n `the download of \\`${asset.name}\\` for ${label} returned no body`,\n );\n }\n\n const hash = createHash('sha256');\n try {\n await pipeline(\n Readable.fromWeb(body as unknown as Parameters<typeof Readable.fromWeb>[0]),\n new Transform({\n transform(chunk, _encoding, callback) {\n hash.update(chunk as Buffer);\n callback(null, chunk);\n },\n }),\n createWriteStream(file),\n );\n } catch (error) {\n throw new BuilderError(\n 'release.download',\n `cannot save the archive of ${label}: ${errorMessage(error)}`,\n );\n }\n return hash.digest('hex');\n}\n\n/**\n * Open an asset download, following redirects by hand.\n *\n * A trusted asset URL may answer with a redirect to a mirror or object store,\n * and the credential decision has to be made again for the redirect target.\n * `fetch` strips `authorization` on a cross-origin redirect but forwards\n * custom headers such as `private-token`, so redirects are never left to it:\n * with `redirect: 'manual'` every hop passes through\n * {@link isTrustedDownload}, and a hop that leaves the trusted hosts is\n * requested without the token.\n */\nasync function openAsset(\n asset: ReleaseAsset,\n source: ReleaseSource,\n label: string,\n): Promise<Response> {\n let url = asset.url;\n\n for (let request = 0; request < MAX_DOWNLOAD_REQUESTS; request += 1) {\n let response: Response;\n try {\n response = await fetch(url, {\n redirect: 'manual',\n headers: requestHeaders(source.host, true, isTrustedDownload(url, source.tokenHosts)),\n });\n } catch (error) {\n throw new BuilderError(\n 'release.network',\n `cannot download \\`${asset.name}\\` of ${label}: ${errorMessage(error)}`,\n );\n }\n\n if (!REDIRECT_STATUSES.has(response.status)) return response;\n\n const location = response.headers.get('location');\n await discardBody(response);\n\n if (location === null || location === '') {\n throw new BuilderError(\n 'release.redirect',\n `the download of \\`${asset.name}\\` for ${label} answered ${response.status} ` +\n 'without a Location header',\n );\n }\n let target: URL;\n try {\n target = new URL(location, url);\n } catch (error) {\n throw new BuilderError(\n 'release.redirect',\n `the download of \\`${asset.name}\\` for ${label} redirected to ` +\n `\\`${location}\\`, which is not a valid URL: ${errorMessage(error)}`,\n );\n }\n // A `file:` (or any other non-http) target is not a download the builder\n // can make: following it would either fail as a network error or, worse,\n // read the local filesystem. Name the URL and refuse it as a redirect.\n if (target.protocol !== 'http:' && target.protocol !== 'https:') {\n throw new BuilderError(\n 'release.redirect',\n `the download of \\`${asset.name}\\` for ${label} redirected to ` +\n `\\`${target.toString()}\\`, which is not an http(s) URL`,\n );\n }\n url = target.toString();\n }\n\n throw new BuilderError(\n 'release.redirect',\n `the download of \\`${asset.name}\\` for ${label} did not finish within ` +\n `${MAX_DOWNLOAD_REQUESTS} requests; the mirror is probably redirecting in a loop`,\n );\n}\n\n/** Drop a redirect response's body so the connection can be reused. */\nasync function discardBody(response: Response): Promise<void> {\n if (response.body === null) return;\n await response.body.cancel().catch(() => undefined);\n}\n\n/**\n * Check the computed digest against a `sha256:<hex>` published by the host.\n *\n * A release may publish a digest in another algorithm (`sha512:`), which this\n * builder cannot check. Silently skipping it would trust bytes nobody verified,\n * so an unusable algorithm is `release.integrity` — the same code as a\n * mismatch, since the download cannot be verified either way.\n */\nfunction verifyDigest(asset: ReleaseAsset, digest: string, label: string): void {\n if (asset.digest === undefined) return;\n\n const separator = asset.digest.indexOf(':');\n if (separator === -1) {\n throw new BuilderError(\n 'release.integrity',\n `\\`${asset.name}\\` of ${label} publishes a malformed digest ${JSON.stringify(asset.digest)}; ` +\n 'expected `sha256:<hex>`',\n );\n }\n\n const algorithm = asset.digest.slice(0, separator).toLowerCase();\n if (algorithm !== 'sha256') {\n throw new BuilderError(\n 'release.integrity',\n `\\`${asset.name}\\` of ${label} publishes a \\`${algorithm}\\` digest, but only sha256 can be ` +\n 'verified; refusing to install bytes nothing can check',\n );\n }\n\n const declared = asset.digest.slice(separator + 1).toLowerCase();\n if (!/^[0-9a-f]{64}$/.test(declared)) {\n throw new BuilderError(\n 'release.integrity',\n `\\`${asset.name}\\` of ${label} publishes a malformed sha256 digest ${JSON.stringify(asset.digest)}`,\n );\n }\n if (declared !== digest) {\n throw new BuilderError(\n 'release.integrity',\n `\\`${asset.name}\\` of ${label} has sha256 ${digest}, but the release declares ${declared}`,\n );\n }\n}\n\n/** Unpack `file` into `target`, rejecting entries that would leave it. */\nasync function extractArchive(\n file: string,\n format: ArchiveFormat,\n target: string,\n label: string,\n): Promise<void> {\n await mkdir(target, { recursive: true });\n try {\n if (format === 'zip') extractZip(file, target, label);\n else await extractTarball(file, target, label);\n } catch (error) {\n if (error instanceof BuilderError) throw error;\n throw new BuilderError(\n 'release.extract',\n `cannot extract the archive of ${label}: ${errorMessage(error)}`,\n );\n }\n}\n\n/**\n * Extract a `.zip` after screening every entry name and mode.\n *\n * A symlink entry is refused exactly as the server download's screen refuses\n * it: the link target would be resolved on the host after unpacking, so a\n * \"file\" in the archive could be any path outside the staging tree.\n */\nfunction extractZip(file: string, target: string, label: string): void {\n let archive: AdmZip;\n try {\n archive = new AdmZip(file);\n } catch (error) {\n throw new BuilderError(\n 'release.bad-archive',\n `the archive of ${label} is not a readable zip: ${errorMessage(error)}`,\n );\n }\n\n for (const entry of archive.getEntries()) {\n safeEntry(entry.entryName, label);\n if (isSymlinkEntry(entry)) {\n throw new BuilderError(\n 'release.bad-archive',\n `the archive of ${label} contains the symlink \\`${entry.entryName}\\`; ` +\n 'addon archives may hold regular files and directories only',\n );\n }\n }\n archive.extractAllTo(target, true);\n}\n\n/**\n * Extract a `.tar.gz`: list and screen every entry first, so a link or a\n * traversal entry is refused before anything is written, then unpack with\n * `preservePaths` off as a second line of defence.\n *\n * The list pass only records entries; the checks run on the recorded list\n * rather than inside tar's callbacks, where a thrown error has no defined\n * destination. PAX metadata entries are allowed through the screen — they are\n * how long and non-ASCII names travel — but the extraction filter writes only\n * files and directories, so a metadata entry can never touch the disk.\n */\nasync function extractTarball(file: string, target: string, label: string): Promise<void> {\n const entries: { path: string; type: string }[] = [];\n await listTar({\n file,\n onReadEntry: (entry) => {\n entries.push({ path: entry.path, type: entry.type });\n },\n });\n\n for (const entry of entries) {\n safeEntry(entry.path, label);\n if (!TAR_ENTRY_TYPES.has(entry.type)) {\n throw new BuilderError(\n 'release.bad-archive',\n `the archive of ${label} contains \\`${entry.path}\\` of type \\`${entry.type}\\`; ` +\n 'addon archives may hold regular files and directories only',\n );\n }\n }\n\n await extractTar({\n file,\n cwd: target,\n preservePaths: false,\n strict: true,\n // Already screened above; skip rather than throw from inside tar if the\n // second parse ever disagrees. Metadata entries are skipped here too.\n filter: (path, entry) => isPlainEntry(path) && isExtractableEntry(entry),\n });\n}\n\n/** True for entries the unpacker should write: files and directories only. */\nfunction isExtractableEntry(entry: Stats | ReadEntry): boolean {\n return 'type' in entry && TAR_FILE_TYPES.has(entry.type);\n}\n\n/** True when an entry name is a plain relative path; see {@link safeEntry}. */\nfunction isPlainEntry(entry: string): boolean {\n const posix = entry.replace(/\\\\/g, '/');\n const segments = posix.split('/').filter((segment) => segment !== '' && segment !== '.');\n return (\n !posix.startsWith('/') &&\n !/^[a-zA-Z]:\\//.test(posix) &&\n !posix.startsWith('//') &&\n segments.length > 0 &&\n !segments.includes('..')\n );\n}\n\n/**\n * Normalize an archive entry name and refuse anything that is not a plain\n * relative path: an absolute entry, a Windows drive, or a `..` segment could\n * write outside the staging tree.\n */\nfunction safeEntry(entry: string, label: string): void {\n const posix = entry.replace(/\\\\/g, '/');\n if (posix.startsWith('/') || /^[a-zA-Z]:\\//.test(posix) || posix.startsWith('//')) {\n throw new BuilderError(\n 'release.bad-archive',\n `the archive of ${label} contains the absolute path \\`${entry}\\``,\n );\n }\n\n const segments = posix.split('/').filter((segment) => segment !== '' && segment !== '.');\n if (segments.includes('..')) {\n throw new BuilderError(\n 'release.bad-archive',\n `the archive of ${label} contains \\`${entry}\\`, which escapes the archive root`,\n );\n }\n if (segments.length === 0) {\n throw new BuilderError(\n 'release.bad-archive',\n `the archive of ${label} contains an entry with no path`,\n );\n }\n}\n\n/**\n * Read the addon contract out of the unpacked archive: a `package.json` marker\n * and `resource.toml`, both at the root. Every missing or malformed piece is\n * reported as `release.not-an-addon`, because from the project's point of view\n * the archive simply is not an addon.\n *\n * The marker is read first: an archive that has `resource.toml` but no marker\n * is a package that is not an addon, and saying so (`package.missing-marker`)\n * is more useful than reporting a manifest that is actually there.\n */\nfunction readReleaseAddon(root: string, label: string): AddonPackage {\n let addon: AddonPackage;\n try {\n addon = readAddonPackage(root);\n } catch (error) {\n if (error instanceof AddonError) {\n throw new BuilderError(\n 'release.not-an-addon',\n `the archive of ${label} is not a CyberMP addon: ${error.message}`,\n );\n }\n throw error;\n }\n\n if (!isRegularFile(join(root, 'resource.toml'))) {\n throw new BuilderError(\n 'release.not-an-addon',\n `the archive of ${label} has no resource.toml at its root; ` +\n 'an addon archive must contain package.json and resource.toml at the top level',\n );\n }\n\n return addon;\n}\n\n/**\n * Validate the unpacked addon while it is still in the staging directory.\n *\n * `readReleaseAddon` only checks the archive contract (`package.json` marker and\n * `resource.toml` at the root); the manifest and every path it references are\n * checked here, before {@link installAddon} moves the old installation aside.\n * A rejected archive therefore cannot destroy the version already installed.\n */\nasync function validateStagedAddon(staging: string, addon: AddonPackage): Promise<void> {\n const validation = await validateAddon(staging, { kind: 'prebuilt' });\n if (!validation.ok) {\n throw invalidAddonError(`\\`${addon.resource}\\``, validation.issues);\n }\n}\n\n/**\n * Move the unpacked tree to `<workDir>/addons/<resource>`, replacing a previous\n * installation of the same resource.\n *\n * The replacement is a two-step rename: the old directory is moved aside, then\n * the new one is renamed into place, and only then is the old one deleted. If\n * the second rename fails the old directory is put back, so a failed\n * reinstall leaves the previous addon usable. Both paths live under the work\n * directory, so neither rename copies data.\n *\n * Leftover `.previous-*` trees from a run that died mid-swap are swept first:\n * they are debris at best and a hidden copy of an addon at worst.\n */\nasync function installAddon(work: string, staging: string, addon: AddonPackage): Promise<string> {\n const addonsDir = join(work, 'addons');\n const destination = join(addonsDir, addon.resource);\n\n await mkdir(addonsDir, { recursive: true });\n await sweepStaleInstalls(addonsDir);\n\n let previous: string | undefined;\n if (existsSync(destination)) {\n previous = join(addonsDir, `.previous-${addon.resource}-${randomUUID()}`);\n try {\n await rename(destination, previous);\n } catch (error) {\n throw new BuilderError(\n 'release.install',\n `cannot move the previous install of \\`${addon.resource}\\` aside: ${errorMessage(error)}`,\n );\n }\n }\n\n try {\n await rename(staging, destination);\n } catch (error) {\n if (previous !== undefined) {\n // Restore the old install; if even that fails, the directory is still\n // under its `.previous-*` name inside the work directory.\n await rename(previous, destination).catch(() => undefined);\n }\n throw new BuilderError(\n 'release.install',\n `cannot install \\`${addon.resource}\\` into \\`${destination}\\`: ${errorMessage(error)}`,\n );\n }\n\n if (previous !== undefined) {\n // The new install is already in place; failing to delete the old copy must\n // not fail the install.\n await rm(previous, { recursive: true, force: true }).catch(() => undefined);\n }\n\n try {\n return await realpath(destination);\n } catch {\n return destination;\n }\n}\n\n/**\n * Remove `.previous-*` trees left under `addonsDir` by a run that died between\n * the two renames of {@link installAddon}.\n *\n * Only that shape is removed: every other entry is an installation (or\n * somebody else's file) and stays. Best effort, like the server sweep — a tree\n * that cannot be removed must not fail an otherwise good install.\n */\nasync function sweepStaleInstalls(addonsDir: string): Promise<void> {\n let entries: string[];\n try {\n entries = await readdir(addonsDir);\n } catch {\n return;\n }\n\n for (const name of entries) {\n if (!name.startsWith('.previous-')) continue;\n await rm(join(addonsDir, name), { recursive: true, force: true }).catch(() => undefined);\n }\n}\n\n/** Headers for an API call or an asset download, including the host token. */\nfunction requestHeaders(\n host: ReleaseHost | undefined,\n download: boolean,\n sendToken: boolean,\n): Record<string, string> {\n const headers: Record<string, string> = { 'user-agent': 'cybermp-resource-builder' };\n\n if (host === 'github') {\n headers.accept = download ? 'application/octet-stream' : 'application/vnd.github+json';\n headers['x-github-api-version'] = '2022-11-28';\n const token = process.env.GITHUB_TOKEN;\n if (sendToken && token !== undefined && token !== '') {\n headers.authorization = `Bearer ${token}`;\n }\n } else if (host === 'gitlab') {\n headers.accept = download ? 'application/octet-stream' : 'application/json';\n const token = process.env.GITLAB_TOKEN;\n if (sendToken && token !== undefined && token !== '') {\n headers['private-token'] = token;\n }\n } else if (download) {\n // A direct URL: no token is ever sent to an arbitrary host.\n headers.accept = 'application/octet-stream';\n }\n\n return headers;\n}\n\n/**\n * True when a token may be sent to `url`. Release hosts may point an asset at\n * a mirror or object store; the credential is scoped to the hosts the release\n * API was configured with.\n */\nfunction isTrustedDownload(url: string, tokenHosts: readonly string[] | undefined): boolean {\n if (tokenHosts === undefined) return false;\n const [host] = hostsOf(url);\n return host !== undefined && tokenHosts.includes(host);\n}\n\n/** `host[:port]` of a URL, or `[]` when it does not parse. */\nfunction hostsOf(url: string): string[] {\n try {\n return [new URL(url).host];\n } catch {\n return [];\n }\n}\n\nfunction unique(values: readonly string[]): string[] {\n return [...new Set(values)];\n}\n\n/**\n * Map an HTTP failure onto a code the user can act on: a token for a private\n * repository or a rate limit, the repository/tag for a 404, and a plain status\n * otherwise.\n */\nfunction httpFailure(\n status: number,\n what: string,\n url: string,\n host: ReleaseHost | undefined,\n remaining: string | null,\n): BuilderError {\n let token: string | undefined;\n if (host === 'github') token = 'GITHUB_TOKEN';\n else if (host === 'gitlab') token = 'GITLAB_TOKEN';\n\n if (status === 429 || (status === 403 && remaining === '0')) {\n return new BuilderError(\n 'release.rate-limit',\n `${what} was rate limited at \\`${url}\\`` +\n (token === undefined ? '' : `; set ${token} to raise the limit`),\n );\n }\n if (status === 401 || status === 403) {\n return new BuilderError(\n 'release.auth',\n `${what} is not readable anonymously at \\`${url}\\` (status ${status})` +\n (token === undefined\n ? '; the link may be private, expired or need a signed URL'\n : `; set ${token} when the repository is private`),\n );\n }\n if (status === 404) {\n return new BuilderError(\n 'release.not-found',\n `${what} was not found at \\`${url}\\`; check the repository name and tag`,\n );\n }\n return new BuilderError('release.http', `${what} failed with status ${status} at \\`${url}\\``);\n}\n\nfunction requireRecord(value: unknown, label: string): Record<string, unknown> {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) {\n throw badResponse(label, 'a payload that is not an object');\n }\n return value as Record<string, unknown>;\n}\n\nfunction badResponse(label: string, detail: string): BuilderError {\n return new BuilderError('release.bad-response', `${label} returned ${detail}`);\n}\n\nfunction stringField(value: unknown): string | undefined {\n return typeof value === 'string' && value !== '' ? value : undefined;\n}\n\nfunction trimSlash(value: string): string {\n return value.replace(/\\/+$/, '');\n}\n\nfunction isRegularFile(path: string): boolean {\n try {\n return statSync(path).isFile();\n } catch {\n return false;\n }\n}\n\nfunction errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n","/**\n * Addon specs: the one-line forms `cybermp add` accepts, and what each one\n * means.\n *\n * | Input | Kind |\n * | ------------------------------ | --------- |\n * | `@scope/pkg`, `pkg@1.2.0` | `npm` |\n * | `gh:owner/repo@v1.2.0` | `release` |\n * | `gl:group/repo@v1.2.0` | `release` |\n * | `https://host/addon.zip` | `url` |\n * | `./addons/hud`, `../shared` | `path` |\n *\n * Parsing is pure apart from the path check, which looks at the filesystem so a\n * bare name that happens to be a directory (`addons/hud`) is still read as a\n * path. That check resolves against the project root when the caller passes\n * one — the directory `registerPathAddon` will use — and never against the\n * process working directory, so `cybermp add addons/hud` behaves the same from\n * any subdirectory. Relative path specs keep the exact spelling the user typed:\n * the project config stores `addons.local` as authored, so normalizing here\n * would make the committed entry differ from the command.\n *\n * Every failure is a `BuilderError` with a `spec.*` code: a bare name that is\n * not a package name (`spec.npm`), a `gh:`/`gl:` spec without `<owner>/<repo>`\n * or with an empty tag (`spec.release`), an `http(s)` URL that is not one\n * (`spec.url`), and an empty spec (`spec.empty`).\n */\nimport { existsSync } from 'node:fs';\nimport { isAbsolute, resolve } from 'node:path';\nimport { BuilderError } from '../../errors.js';\n\n/** Release hosts the toolchain knows how to talk to. */\nexport type ReleaseHost = 'github' | 'gitlab';\n\n/** An npm package, optionally at a range; the package manager pins it. */\nexport interface NpmAddonSpec {\n kind: 'npm';\n /** Package name, scoped or not: `@scope/pkg` or `pkg`. */\n name: string;\n /** Requested range or version, when the spec carried one. */\n range?: string;\n}\n\n/** A release archive on GitHub or GitLab. */\nexport interface ReleaseAddonSpec {\n kind: 'release';\n host: ReleaseHost;\n /** `owner/repo`; a GitLab subgroup keeps its extra segments. */\n repo: string;\n /** Release tag, or omitted for the repository's latest release. */\n tag?: string;\n}\n\n/** A direct link to a release archive. */\nexport interface UrlAddonSpec {\n kind: 'url';\n url: string;\n}\n\n/** A directory in the project, or next to it. */\nexport interface PathAddonSpec {\n kind: 'path';\n path: string;\n}\n\n/** One parsed addon spec. */\nexport type AddonSpec = NpmAddonSpec | ReleaseAddonSpec | UrlAddonSpec | PathAddonSpec;\n\n/** Options of {@link parseAddonSpec}. */\nexport interface ParseAddonSpecOptions {\n /** Project root a bare name is checked against; defaults to the process cwd. */\n root?: string;\n}\n\nconst URL_PATTERN = /^https?:\\/\\//i;\n\n/** npm names: one lowercase-ish segment, or `@scope/segment`. */\nconst PACKAGE_NAME_PATTERN = /^(?:@[^/@\\s]+\\/)?[^/@\\s]+$/;\n\n/**\n * A semver range and nothing else.\n *\n * Deliberately narrower than npm's grammar: no `&`, `|`, `%`, quotes or\n * backslashes, because the range is handed to a package manager process and on\n * Windows that means a `cmd.exe` command line. Everything a real range needs —\n * `^ ~ * x X - . + < > =` and spaces — is allowed.\n */\nconst RANGE_PATTERN = /^[A-Za-z0-9.+~^*<>=| -]+$/;\n\n/**\n * Parse an addon spec.\n *\n * Prefixes and URLs are recognized first, then a filesystem path (explicit `./`,\n * `../`, an absolute path, or a name that exists as a directory), and anything\n * else must be an npm package name. `options.root` is the project root the\n * existence check resolves against; without it the process working directory is\n * used, which is only correct for callers that have no project (the tests).\n *\n * Errors: `spec.empty`, `spec.release`, `spec.url`, `spec.npm`.\n */\nexport function parseAddonSpec(input: string, options: ParseAddonSpecOptions = {}): AddonSpec {\n const value = input.trim();\n if (value === '') {\n throw new BuilderError('spec.empty', 'an addon spec is required');\n }\n\n if (value.startsWith('gh:')) return parseRelease('github', value.slice('gh:'.length), value);\n if (value.startsWith('gl:')) return parseRelease('gitlab', value.slice('gl:'.length), value);\n if (URL_PATTERN.test(value)) return parseUrl(value);\n if (looksLikePath(value, options.root)) return { kind: 'path', path: value };\n\n return parseNpm(value);\n}\n\n/**\n * `owner/repo[@tag]`. The tag is split at the last `@`, so a tag may itself\n * contain one; `.git` is dropped because the API names the repository, not the\n * clone URL.\n */\nfunction parseRelease(host: ReleaseHost, rest: string, original: string): ReleaseAddonSpec {\n const separator = rest.lastIndexOf('@');\n const repoPart = separator === -1 ? rest : rest.slice(0, separator);\n const tag = separator === -1 ? undefined : rest.slice(separator + 1);\n\n if (tag === '') {\n throw new BuilderError(\n 'spec.release',\n `\\`${original}\\` has an empty tag; drop the \\`@\\` to follow the latest release`,\n );\n }\n\n const repo = repoPart.replace(/^\\/+|\\/+$/g, '').replace(/\\.git$/, '');\n const segments = repo.split('/');\n if (\n segments.length < 2 ||\n segments.some(\n (segment) => segment === '' || segment === '.' || segment === '..' || /\\s/.test(segment),\n )\n ) {\n const prefix = host === 'github' ? 'gh' : 'gl';\n throw new BuilderError(\n 'spec.release',\n `\\`${original}\\` must name a repository as \\`${prefix}:<owner>/<repo>[@<tag>]\\``,\n );\n }\n\n return tag === undefined ? { kind: 'release', host, repo } : { kind: 'release', host, repo, tag };\n}\n\n/** A direct archive URL; the download step rejects a non-archive target. */\nfunction parseUrl(value: string): UrlAddonSpec {\n let url: URL;\n try {\n url = new URL(value);\n } catch (error) {\n throw new BuilderError(\n 'spec.url',\n `\\`${value}\\` is not a valid URL: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n if (url.protocol !== 'http:' && url.protocol !== 'https:') {\n throw new BuilderError('spec.url', `\\`${value}\\` must be an http(s) URL`);\n }\n return { kind: 'url', url: value };\n}\n\n/**\n * True for the spellings that can only be a path. A bare relative name that\n * exists under `root` is a path too, which keeps `cybermp add addons/hud`\n * working without a `./` prefix from any working directory; the exception is a\n * scoped npm name, whose `@` cannot start a path segment.\n */\nfunction looksLikePath(value: string, root: string | undefined): boolean {\n if (value.startsWith('./') || value.startsWith('../')) return true;\n if (value.startsWith('.\\\\') || value.startsWith('..\\\\')) return true;\n if (isAbsolute(value) || /^[a-zA-Z]:[\\\\/]/.test(value)) return true;\n if (value.startsWith('@')) return false;\n return existsSync(resolve(root ?? process.cwd(), value));\n}\n\n/**\n * `name[@range]`. A scoped name starts with `@`, so the range separator is the\n * next `@`, never the first character.\n */\nfunction parseNpm(value: string): NpmAddonSpec {\n const separator = value.indexOf('@', 1);\n const name = separator === -1 ? value : value.slice(0, separator);\n const range = separator === -1 ? undefined : value.slice(separator + 1);\n\n if (!PACKAGE_NAME_PATTERN.test(name) || name.includes('\\\\')) {\n throw new BuilderError(\n 'spec.npm',\n `\\`${value}\\` is not an addon spec: expected an npm package, ` +\n '`gh:<owner>/<repo>[@<tag>]`, `gl:<group>/<repo>[@<tag>]`, an http(s) URL or a path',\n );\n }\n if (range === '') {\n throw new BuilderError('spec.npm', `\\`${value}\\` has an empty version range`);\n }\n if (range !== undefined && !RANGE_PATTERN.test(range)) {\n // The range reaches the package manager as an argv entry, and on Windows it\n // is pasted into a `cmd.exe` command line where `&`, `|`, `%` and friends\n // are syntax. A semver range never needs them, so refuse the shape outright\n // instead of escaping per platform.\n throw new BuilderError(\n 'spec.npm',\n `\\`${range}\\` is not a version range: use semver (\\`^1.2.0\\`, \\`~1.2\\`, \\`1.x\\`, \\`>=1 <2\\`)`,\n );\n }\n\n return range === undefined ? { kind: 'npm', name } : { kind: 'npm', name, range };\n}\n","/**\n * npm addons: delegate the install to the project's own package manager.\n *\n * npm addons are ordinary dependencies, so the builder never writes\n * `package.json` or a node_modules layout itself: it runs `<pm> add <spec>` in\n * the project and lets the package manager resolve, link and lock the package.\n * That also means npm integrity is the package manager's lockfile, not\n * `cybermp.lock.json`.\n *\n * The package manager is taken from an explicit `--pm` when given, otherwise\n * from the root `package.json` `packageManager` field, otherwise from the\n * lockfile on disk (`pnpm-lock.yaml`, `yarn.lock`, `package-lock.json` /\n * `npm-shrinkwrap.json`, `bun.lock` / `bun.lockb`). A project with none of those\n * defaults to npm, which ships with Node; a `packageManager` naming something\n * else is `pm.unsupported` rather than a guess.\n *\n * Every manager is driven through its own CLI — `<pm> add`, `<pm> remove`,\n * `<pm> install` — so the commands are the manager's own and the lockfile it\n * writes is the only record of the resolution.\n *\n * After the install the package is validated with the same `validateAddon` the\n * author CLI runs. A failure is not left installed: `<pm> remove <name>` undoes\n * the dependency before the error is rethrown, so a broken addon never sits in\n * `package.json` making every later build fail.\n */\nimport { spawn } from 'node:child_process';\nimport { existsSync, readFileSync, realpathSync } from 'node:fs';\nimport { join } from 'node:path';\nimport {\n AddonError,\n type AddonPackage,\n readAddonPackage,\n validateAddon,\n} from '@cybermp-community/addon';\nimport { BuilderError, invalidAddonError } from '../../errors.js';\nimport type { ResolvedAddon } from '../types.js';\nimport type { NpmAddonSpec } from './spec.js';\n\n/** Package managers the builder knows how to drive. */\nexport type PackageManager = 'pnpm' | 'npm' | 'yarn' | 'bun';\n\n/** Options for {@link addNpmAddon}. */\nexport interface NpmAddonOptions {\n /** Package manager override, as passed to `--pm`. */\n pm?: PackageManager;\n}\n\n/** Where a dependency the add replaced was declared. */\ninterface PreviousDependency {\n section: 'dependencies' | 'devDependencies';\n /** Range exactly as the project declared it. */\n range: string;\n}\n\n/** Every supported package manager, for error messages and CLI choices. */\nexport const PACKAGE_MANAGERS: readonly PackageManager[] = ['pnpm', 'npm', 'yarn', 'bun'];\n\n/**\n * Lockfiles in detection order, each naming its package manager.\n *\n * Bun has two: `bun.lock` (text, since 1.2) and the older binary `bun.lockb`.\n */\nconst LOCKFILES: readonly { file: string; pm: PackageManager }[] = [\n { file: 'pnpm-lock.yaml', pm: 'pnpm' },\n { file: 'yarn.lock', pm: 'yarn' },\n { file: 'bun.lock', pm: 'bun' },\n { file: 'bun.lockb', pm: 'bun' },\n { file: 'package-lock.json', pm: 'npm' },\n { file: 'npm-shrinkwrap.json', pm: 'npm' },\n];\n\n/**\n * Pick the package manager for `root`.\n *\n * Explicit wins; then the root `package.json` `packageManager` field; then a\n * lockfile; then npm. A `packageManager` such as `deno@2` is `pm.unsupported`\n * instead of silently falling back, because driving a project with another\n * manager would leave two lockfiles disagreeing.\n */\nexport function detectPackageManager(root: string, explicit?: PackageManager): PackageManager {\n if (explicit !== undefined) return explicit;\n\n const declared = declaredPackageManager(root);\n if (declared !== undefined) {\n if ((PACKAGE_MANAGERS as readonly string[]).includes(declared)) {\n return declared as PackageManager;\n }\n throw new BuilderError(\n 'pm.unsupported',\n `\\`packageManager\\` names \\`${declared}\\`; this builder drives ` +\n `${PACKAGE_MANAGERS.join(', ')} only — pass --pm=<${PACKAGE_MANAGERS.join('|')}>`,\n );\n }\n\n for (const lockfile of LOCKFILES) {\n if (existsSync(join(root, lockfile.file))) return lockfile.pm;\n }\n return 'npm';\n}\n\n/**\n * Read the package manager name out of `<root>/package.json`'s\n * `packageManager` field (`pnpm@9.0.0` → `pnpm`).\n */\nfunction declaredPackageManager(root: string): string | undefined {\n const manifest = readProjectManifest(root);\n if (manifest === undefined) return undefined;\n\n const value = manifest['packageManager'];\n if (typeof value !== 'string' || value === '') return undefined;\n const name = value.split('@')[0];\n return name === '' ? undefined : name;\n}\n\n/**\n * The root `package.json`, or `undefined` when the project has none. A malformed\n * manifest is `pm.manifest`: the dependency state cannot be recorded or\n * restored without it.\n */\nfunction readProjectManifest(root: string): Record<string, unknown> | undefined {\n const file = join(root, 'package.json');\n let text: string;\n try {\n text = readFileSync(file, 'utf8');\n } catch (error) {\n if (isErrno(error, 'ENOENT')) return undefined;\n throw new BuilderError('pm.manifest', `cannot read \\`${file}\\`: ${errorMessage(error)}`);\n }\n\n let manifest: unknown;\n try {\n manifest = JSON.parse(text);\n } catch (error) {\n throw new BuilderError('pm.manifest', `invalid JSON in \\`${file}\\`: ${errorMessage(error)}`);\n }\n if (typeof manifest !== 'object' || manifest === null || Array.isArray(manifest)) {\n throw new BuilderError('pm.manifest', `\\`${file}\\` must contain a JSON object`);\n }\n return manifest as Record<string, unknown>;\n}\n\n/**\n * The dependency entry `name` already had before an add, with its section and\n * exact range, so a rejected install can put it back instead of deleting it.\n */\nfunction previousDependency(root: string, name: string): PreviousDependency | undefined {\n const manifest = readProjectManifest(root);\n if (manifest === undefined) return undefined;\n\n for (const section of ['dependencies', 'devDependencies'] as const) {\n const table = manifest[section];\n if (typeof table !== 'object' || table === null || Array.isArray(table)) continue;\n const range = (table as Record<string, unknown>)[name];\n if (typeof range === 'string') return { section, range };\n }\n return undefined;\n}\n\n/**\n * Install `spec` with the project's package manager, validate it and return the\n * resolved addon.\n *\n * Errors: `pm.missing` when the binary cannot be spawned, `pm.failed` when it\n * exits non-zero, `pm.manifest` when the root `package.json` is unreadable,\n * `npm.not-installed` when the package is not in `node_modules` afterwards,\n * `npm.bad-package` when it is installed but its own `package.json` cannot be\n * read back, and the validator's own code when the installed package is not a\n * valid addon.\n * A rejected install is rolled back to the dependency state recorded before the\n * add: a package the project already declared gets its previous range back, and\n * one that was absent is removed.\n */\nexport async function addNpmAddon(\n root: string,\n spec: NpmAddonSpec,\n options: NpmAddonOptions = {},\n): Promise<ResolvedAddon> {\n const pm = detectPackageManager(root, options.pm);\n const argument = spec.range === undefined ? spec.name : `${spec.name}@${spec.range}`;\n\n // Record what `add` is about to replace: `pnpm add name@2` on a project that\n // already depends on `name@1` overwrites the entry, and a failed validation\n // must put `name@1` back rather than delete the dependency.\n const previous = previousDependency(root, spec.name);\n await runPackageManager(root, pm, ['add', argument]);\n\n const dir = installedDirectory(root, spec.name);\n if (dir === undefined) {\n throw new BuilderError(\n 'npm.not-installed',\n `\\`${pm} add ${argument}\\` succeeded, but \\`${spec.name}\\` is not in the project's node_modules`,\n );\n }\n\n const validation = await validateAddon(dir, { kind: 'prebuilt' });\n const addonPackage = validation.ok ? tryReadPackage(dir) : undefined;\n if (!validation.ok || addonPackage === undefined) {\n const rollbackError = await rollback(root, pm, spec.name, previous);\n const failure = validation.ok\n ? new BuilderError(\n 'npm.bad-package',\n `\\`${spec.name}\\` was installed but its package.json could not be read`,\n )\n : invalidAddonError(`\\`${spec.name}\\``, validation.issues);\n throw rollbackError === undefined\n ? failure\n : new BuilderError(failure.code, `${failure.message} (rollback failed: ${rollbackError})`);\n }\n\n return {\n name: addonPackage.resource,\n packageName: addonPackage.name,\n dir,\n version: addonPackage.version,\n source: 'npm',\n requires: addonPackage.requires,\n kind: 'prebuilt',\n };\n}\n\n/**\n * Run `<pm> <args…>` in `root`.\n *\n * Output is captured so a failure can show the package manager's own reason.\n *\n * Windows needs care: the binaries are `.cmd` shims, so `shell` is on, and Node\n * then joins the argument array with spaces for `cmd.exe` to parse. That makes\n * `@acme/hud@^1.0.0` arrive as `@acme/hud@1.0.0` — the caret escapes the `1` —\n * and lets `&`, `|` or `>` split the command. The command line is therefore\n * assembled here with every cmd metacharacter escaped, and the spec parser\n * refuses a range containing anything `^` cannot protect (`%`, quotes, `&`).\n *\n * Errors: `pm.missing` and `pm.failed`.\n */\nexport async function runPackageManager(\n root: string,\n pm: PackageManager,\n args: readonly string[],\n): Promise<void> {\n const windows = process.platform === 'win32';\n const command = [pm, ...args].join(' ');\n const result = await new Promise<{ code: number | null; stdout: string; stderr: string }>(\n (resolveRun, rejectRun) => {\n const child = windows\n ? spawn([pm, ...args.map(quoteForCmd)].join(' '), {\n cwd: root,\n env: process.env,\n shell: true,\n })\n : spawn(pm, [...args], { cwd: root, env: process.env });\n let stdout = '';\n let stderr = '';\n\n child.stdout?.on('data', (chunk: Buffer) => {\n stdout += chunk.toString();\n });\n child.stderr?.on('data', (chunk: Buffer) => {\n stderr += chunk.toString();\n });\n child.once('error', rejectRun);\n child.once('close', (code) => resolveRun({ code, stdout, stderr }));\n },\n ).catch((error: unknown) => {\n throw new BuilderError(\n 'pm.missing',\n `cannot run \\`${pm}\\`: ${errorMessage(error)}; install it or pass --pm`,\n );\n });\n\n if (result.code !== 0) {\n const detail = (result.stderr.trim() || result.stdout.trim()).split('\\n').slice(-5).join('\\n');\n const status =\n result.code === null\n ? 'was terminated by a signal'\n : `failed with exit code ${result.code}`;\n throw new BuilderError(\n 'pm.failed',\n `\\`${command}\\` ${status}` + (detail === '' ? '' : `:\\n${detail}`),\n );\n }\n}\n\n/**\n * Undo an install after a validation failure.\n *\n * The target is the state recorded before the add: a dependency the project\n * already declared is re-added at its previous range (in the same section), and\n * one that was absent is removed. Best effort — the original validation error is\n * what the user needs, so a failing rollback is reported as a detail, never as\n * the outcome.\n */\nasync function rollback(\n root: string,\n pm: PackageManager,\n name: string,\n previous: PreviousDependency | undefined,\n): Promise<string | undefined> {\n try {\n if (previous === undefined) {\n await runPackageManager(root, pm, ['remove', name]);\n return undefined;\n }\n\n const args = ['add'];\n if (previous.section === 'devDependencies') args.push(devFlag(pm));\n args.push(`${name}@${previous.range}`);\n await runPackageManager(root, pm, args);\n return undefined;\n } catch (error) {\n return errorMessage(error);\n }\n}\n\n/**\n * The flag that adds a dependency to the dev section for `pm`.\n *\n * `bun` rejects npm's `-D`; its own spelling is `--dev` (or `-d`), so a\n * rollback of a dev dependency under bun must not be the npm command line.\n */\nfunction devFlag(pm: PackageManager): string {\n return pm === 'bun' ? '--dev' : '-D';\n}\n\n/**\n * The package directory after an install, resolved through symlinks (pnpm's\n * layout links into a store). A dependency hoisted above the project root is\n * deliberately out of scope, exactly as in discovery.\n */\nfunction installedDirectory(root: string, name: string): string | undefined {\n const dir = join(root, 'node_modules', ...name.split('/'));\n if (!existsSync(join(dir, 'package.json'))) return undefined;\n try {\n return realpathSync(dir);\n } catch {\n return undefined;\n }\n}\n\nfunction tryReadPackage(dir: string): AddonPackage | undefined {\n try {\n return readAddonPackage(dir);\n } catch (error) {\n if (error instanceof AddonError) return undefined;\n throw error;\n }\n}\n\nfunction isErrno(error: unknown, code: string): boolean {\n return (\n typeof error === 'object' &&\n error !== null &&\n (error as { code?: unknown }).code === code\n );\n}\n\nfunction errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\n/**\n * Quote one argument for a `cmd.exe` command line.\n *\n * Quoting, not caret-escaping: a caret survives `cmd.exe` but is consumed again\n * by the batch layer — `npm.cmd` ends with `node ... %*`, and `%*` re-expands\n * the raw line — so `@acme/hud@^^1.0.0` still arrives as `@acme/hud@1.0.0`.\n * Inside double quotes `cmd` leaves the caret alone, which is why `npm i\n * \"pkg@^1\"` works on Windows. `%` still expands inside quotes, so the spec\n * parser refuses a range containing it instead of relying on this function.\n */\nfunction quoteForCmd(argument: string): string {\n if (argument === '') return '\"\"';\n if (!/[\\s&|<>^()\"%]/.test(argument)) return argument;\n return `\"${argument.replace(/\"/g, '\"\"')}\"`;\n}\n","/**\n * The browser (CEF) half of a local addon's build.\n *\n * A source addon may ship a `browser/` directory. Some addons author it as a\n * static page, others compile it (Vue + Vite in the template) with a command of\n * their own. The command is run in `<addon>/browser` with a shell, and the\n * directory it emits (`dist` by default) is copied to `<out>/<name>/browser`.\n * Without a command the authored directory is the artifact and is copied as it\n * is.\n *\n * The command comes from `cybermp.build.browser.build` when declared. When it\n * is not, a `scripts.build` in `<addon>/browser/package.json` is run through the\n * package manager detected in that directory (`packageManager` field, then a\n * lockfile, then npm), so a pnpm/yarn/bun browser app builds with the manager\n * that installed it. An addon building with another manager declares the\n * command explicitly, since only the addon knows how its dependencies are\n * installed.\n *\n * The command is bounded: `cybermp.build.browser.timeout` (milliseconds,\n * default 600000) caps how long it may run, so a build command that is really a\n * watch server cannot hang the CLI. On expiry the whole process tree is\n * signalled, and the call waits until the tree is gone or SIGKILL has been\n * sent, so no part of the command survives the build.\n *\n * Errors: a command that exits non-zero, cannot start or times out is\n * `build.browser-failed`, a command that exits zero but leaves no `dist`\n * directory is `build.browser-dist` (otherwise the failure would present as a\n * missing UI at runtime), a `dist` that leaves the browser directory or a\n * malformed `browser` block is `build.bad-config`, an uninspectable browser\n * directory is `build.browser-read`, and a failed copy is `build.copy`.\n */\nimport { type ChildProcess, spawn } from 'node:child_process';\nimport { cp, mkdir, readFile, rm, stat } from 'node:fs/promises';\nimport { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';\nimport type { BrowserBuildConfig } from '@cybermp-community/addon';\nimport { detectPackageManager } from '../addons/sources/npm.js';\nimport { BuilderError } from '../errors.js';\n\n/** The authored browser app, relative to the addon root. */\nexport const BROWSER_DIR = 'browser';\n\n/** Directory the browser build emits when `browser.dist` is not set. */\nexport const DEFAULT_BROWSER_DIST = 'dist';\n\n/** How long a browser build command may run when `browser.timeout` is not set. */\nexport const DEFAULT_BROWSER_TIMEOUT = 600_000;\n\n/** How long a timed-out command gets to exit after SIGTERM before SIGKILL. */\nconst KILL_GRACE_MS = 5000;\n\n/** How often a timed-out command's process group is checked for survivors. */\nconst KILL_POLL_MS = 100;\n\n/** Cap on captured build output; a minifier can be chatty. */\nconst MAX_OUTPUT = 10 * 1024 * 1024;\n\n/** How much of a failed command's output ends up in the error message. */\nconst MAX_DETAIL = 2000;\n\n/**\n * Produce `<resourceDir>/browser` from the `browser/` directory of `addonDir`.\n *\n * `resourceDir` is the addon's own output directory (`<out>/<name>`), not the\n * resources directory. A missing `browser/` directory is not an error: the\n * addon simply has no browser UI and `<resourceDir>/browser` is left untouched,\n * since materialization never writes one for a source addon.\n */\nexport async function runBrowserBuild(\n addonDir: string,\n resourceDir: string,\n browser: BrowserBuildConfig | undefined,\n): Promise<void> {\n const root = resolve(addonDir);\n const browserDir = join(root, BROWSER_DIR);\n if (!(await isDirectory(browserDir))) return;\n\n const target = join(resolve(resourceDir), BROWSER_DIR);\n const command = browser?.build ?? (await packageBuildScript(browserDir));\n\n if (command === undefined) {\n await copyDirectory(browserDir, target);\n return;\n }\n\n await runCommand(\n command,\n browserDir,\n root,\n browser?.timeout ?? DEFAULT_BROWSER_TIMEOUT,\n );\n\n const dist = distDirectory(browserDir, browser?.dist);\n if (!(await isDirectory(dist))) {\n throw new BuilderError(\n 'build.browser-dist',\n `browser build command \\`${command}\\` in \\`${browserDir}\\` succeeded ` +\n `but did not create \\`${dist}\\``,\n );\n }\n await copyDirectory(dist, target);\n}\n\n/**\n * The `scripts.build` of the browser app, rendered as a command, or undefined\n * when the app has no package.json or no build script (the static case).\n *\n * The script is run through the package manager the browser app itself\n * declares — `<pm> run build` — because that is the manager whose lockfile and\n * node_modules layout the app was installed with. The validation is unchanged:\n * a build script that is not a non-empty string is still `build.bad-config`.\n */\nasync function packageBuildScript(browserDir: string): Promise<string | undefined> {\n const file = join(browserDir, 'package.json');\n let text: string;\n try {\n text = await readFile(file, 'utf8');\n } catch (error) {\n if (isErrno(error, 'ENOENT')) return undefined;\n throw new BuilderError('build.bad-config', `cannot read \\`${file}\\`: ${message(error)}`);\n }\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(text);\n } catch (error) {\n throw new BuilderError('build.bad-config', `invalid JSON in \\`${file}\\`: ${message(error)}`);\n }\n\n const scripts = isRecord(parsed) ? parsed['scripts'] : undefined;\n const build = isRecord(scripts) ? scripts['build'] : undefined;\n if (build === undefined) return undefined;\n if (typeof build !== 'string' || build.trim() === '') {\n throw new BuilderError(\n 'build.bad-config',\n `\\`scripts.build\\` in \\`${file}\\` must be a non-empty string`,\n );\n }\n return `${detectPackageManager(browserDir)} run build`;\n}\n\n/** Resolve `browser.dist`, refusing a path that leaves the browser directory. */\nfunction distDirectory(browserDir: string, dist: string | undefined): string {\n const configured = dist ?? DEFAULT_BROWSER_DIST;\n const resolved = resolve(browserDir, configured);\n const path = relative(browserDir, resolved);\n if (path !== '' && (isAbsolute(path) || path === '..' || path.startsWith(`..${sep}`))) {\n throw new BuilderError(\n 'build.bad-config',\n `\\`cybermp.build.browser.dist\\` must stay inside \\`browser/\\`, ` +\n `got ${JSON.stringify(configured)}`,\n );\n }\n return resolved;\n}\n\n/**\n * Run `command` in `browserDir` through a shell, the way a package manager runs\n * a script. Output is captured so a failure can quote the command's own message.\n *\n * The command is bounded by `timeoutMs`; on expiry the whole process tree is\n * signalled (SIGTERM, then SIGKILL after {@link KILL_GRACE_MS}). The promise\n * settles only once the tree is gone or SIGKILL has been sent, and the\n * escalation timer stays referenced, so a build that ignores SIGTERM cannot\n * outlive the call and Node cannot exit before the escalation is delivered.\n */\nfunction runCommand(\n command: string,\n browserDir: string,\n addonDir: string,\n timeoutMs: number,\n): Promise<void> {\n return new Promise((resolveRun, rejectRun) => {\n const child = spawn(command, {\n cwd: browserDir,\n shell: true,\n stdio: ['ignore', 'pipe', 'pipe'],\n // Its own process group, so a timeout takes down the shell and whatever it\n // started (package manager, compiler, dev server), not just the shell.\n detached: process.platform !== 'win32',\n });\n const { pid } = child;\n\n let stdout = '';\n let stderr = '';\n let settled = false;\n let timedOut: BuilderError | undefined;\n let timeout: NodeJS.Timeout | undefined;\n let escalation: NodeJS.Timeout | undefined;\n let poll: NodeJS.Timeout | undefined;\n\n const finish = (error?: BuilderError): void => {\n if (settled) return;\n settled = true;\n clearTimeout(timeout);\n clearTimeout(escalation);\n clearInterval(poll);\n if (error === undefined) resolveRun();\n else rejectRun(error);\n };\n\n timeout = setTimeout(() => {\n timedOut = new BuilderError(\n 'build.browser-failed',\n `browser build command \\`${command}\\` in \\`${browserDir}\\` (addon \\`${addonDir}\\`) ` +\n `timed out after ${timeoutMs} ms`,\n );\n signalTree(child, pid, 'SIGTERM');\n\n escalation = setTimeout(() => {\n signalTree(child, pid, 'SIGKILL');\n finish(timedOut);\n }, KILL_GRACE_MS);\n\n // Most trees die on SIGTERM: settle as soon as the group is empty instead\n // of always waiting out the grace period. The poll is unref'd so the\n // escalation timer is what keeps the loop alive while a kill is pending.\n poll = setInterval(() => {\n if (!isTreeAlive(child, pid)) finish(timedOut);\n }, KILL_POLL_MS);\n poll.unref();\n }, timeoutMs);\n\n child.stdout?.on('data', (chunk: Buffer) => {\n stdout = tail(stdout + chunk.toString(), MAX_OUTPUT);\n });\n child.stderr?.on('data', (chunk: Buffer) => {\n stderr = tail(stderr + chunk.toString(), MAX_OUTPUT);\n });\n\n child.on('error', (error) => {\n finish(\n new BuilderError(\n 'build.browser-failed',\n `browser build command \\`${command}\\` in \\`${browserDir}\\` could not start: ` +\n error.message,\n ),\n );\n });\n\n child.on('close', (code, signal) => {\n if (settled) return;\n if (timedOut !== undefined) {\n // The shell is gone; a grandchild that ignored SIGTERM keeps the group\n // alive, and the poll / SIGKILL escalation settles the call instead.\n if (!isTreeAlive(child, pid)) finish(timedOut);\n return;\n }\n if (code === 0) {\n finish();\n return;\n }\n const how = code === null ? `signal ${signal ?? 'unknown'}` : `exit code ${code}`;\n finish(\n new BuilderError(\n 'build.browser-failed',\n `browser build command \\`${command}\\` in \\`${browserDir}\\` failed (${how}): ` +\n `${commandOutput(stderr, stdout)}`,\n ),\n );\n });\n });\n}\n\n/** True while the command — on POSIX, its whole process group — still exists. */\nfunction isTreeAlive(child: ChildProcess, pid: number | undefined): boolean {\n if (process.platform === 'win32' || pid === undefined) {\n return child.exitCode === null && child.signalCode === null;\n }\n try {\n process.kill(-pid, 0);\n return true;\n } catch {\n return false;\n }\n}\n\nfunction signalTree(\n child: ChildProcess,\n pid: number | undefined,\n signal: NodeJS.Signals,\n): void {\n try {\n // `detached` made the child a group leader on POSIX, so -pid is its tree;\n // Windows has no process groups, and child.kill is all there is.\n if (process.platform === 'win32' || pid === undefined) child.kill(signal);\n else process.kill(-pid, signal);\n } catch {\n // Already gone, or the group was never created: nothing left to signal.\n }\n}\n\nasync function copyDirectory(from: string, to: string): Promise<void> {\n try {\n await rm(to, { recursive: true, force: true });\n await mkdir(dirname(to), { recursive: true });\n await cp(from, to, { recursive: true });\n } catch (error) {\n throw new BuilderError('build.copy', `cannot copy \\`${from}\\` to \\`${to}\\`: ${message(error)}`);\n }\n}\n\nasync function isDirectory(path: string): Promise<boolean> {\n try {\n return (await stat(path)).isDirectory();\n } catch (error) {\n if (isErrno(error, 'ENOENT') || isErrno(error, 'ENOTDIR')) return false;\n throw new BuilderError('build.browser-read', `cannot inspect \\`${path}\\`: ${message(error)}`);\n }\n}\n\n/** Keep the end of captured output: that is where the failure is reported. */\nfunction tail(text: string, limit: number): string {\n return text.length > limit ? text.slice(-limit) : text;\n}\n\n/** stderr when the command wrote any, else stdout, else a placeholder. */\nfunction commandOutput(stderr: string, stdout: string): string {\n const detail = nonEmpty(stderr) ?? nonEmpty(stdout) ?? '';\n return detail === '' ? 'no output' : tail(detail, MAX_DETAIL);\n}\n\nfunction nonEmpty(value: unknown): string | undefined {\n if (typeof value !== 'string') return undefined;\n const text = value.trim();\n return text === '' ? undefined : text;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction isErrno(error: unknown, code: string): boolean {\n return (\n typeof error === 'object' &&\n error !== null &&\n (error as { code?: unknown }).code === code\n );\n}\n\nfunction message(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n","/**\n * Installed npm addon discovery: walk the project's `dependencies` transitively\n * and keep every package that carries a `cybermp` marker.\n *\n * Discovery starts from the project root's `package.json` `dependencies`. Each\n * dependency name is looked up by probing `node_modules/<name>/package.json`\n * from the depending package's directory upwards, stopping at the project root:\n * nested and hoisted layouts inside the project both work, but an installation\n * above the project root is deliberately out of scope. The probe reads the file\n * path directly, so a package's `exports` map cannot hide its own\n * `package.json`. A declared dependency that is not installed inside the\n * project is an error rather than a silently missing addon, because the project\n * asked for it.\n *\n * Packages without a marker are traversed but not returned: they are ordinary\n * libraries an addon depends on. A `cybermp` field that is not an object\n * (`false`, a string, an array) is metadata, not a marker: it is ignored rather\n * than read as a broken addon, so a package may carry the key for its own\n * purposes. Addons are keyed by real path, so one package\n * reached through several dependency paths (or a symlink) appears once, and the\n * visited set makes a dependency cycle terminate.\n */\nimport { readFileSync, realpathSync, statSync } from 'node:fs';\nimport { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';\nimport { AddonError, readAddonPackage } from '@cybermp-community/addon';\nimport { BuilderError } from '../errors.js';\nimport type { ResolvedAddon } from './types.js';\n\n/**\n * Resolve every installed npm addon reachable from `root`.\n *\n * The result is sorted by real path for a deterministic order independent of the\n * dependency declaration order, and every addon is `source: 'npm'` and\n * `kind: 'prebuilt'`: installed packages ship the files to copy.\n *\n * Errors: a declared dependency that is not installed at or below the project\n * root is `npm.missing-dependency`; a `package.json` that exists but cannot be\n * read or parsed is `npm.bad-package`; a malformed `cybermp` marker rethrows the\n * addon package's error (`package.bad-json`, `package.bad-resource-name`, …)\n * with the package directory named in the message.\n */\nexport async function resolveNpmAddons(root: string): Promise<ResolvedAddon[]> {\n const projectRoot = realpathSync(resolve(root));\n const addons = new Map<string, ResolvedAddon>();\n const visited = new Set<string>([projectRoot]);\n const pending: string[] = [projectRoot];\n\n for (let from = pending.pop(); from !== undefined; from = pending.pop()) {\n for (const name of readDependencies(from)) {\n const dir = resolveDependency(projectRoot, from, name);\n if (visited.has(dir)) continue;\n visited.add(dir);\n\n const manifest = readManifest(dir);\n if (isRecord(manifest['cybermp'])) {\n const addon = readAddon(dir);\n addons.set(dir, {\n name: addon.resource,\n packageName: addon.name,\n dir,\n version: addon.version,\n source: 'npm',\n requires: addon.requires,\n kind: 'prebuilt',\n });\n }\n pending.push(dir);\n }\n }\n\n return [...addons.values()].sort((left, right) =>\n left.dir < right.dir ? -1 : left.dir > right.dir ? 1 : 0,\n );\n}\n\n/**\n * `dependencies` keys declared by the package at `dir`, sorted so discovery\n * order does not depend on how the manifest happens to be written. A missing\n * `package.json` or `dependencies` field declares nothing.\n */\nfunction readDependencies(dir: string): string[] {\n const manifest = readManifest(dir);\n const dependencies = manifest['dependencies'];\n if (dependencies === undefined) return [];\n if (!isRecord(dependencies)) {\n throw new BuilderError(\n 'npm.bad-package',\n `\\`dependencies\\` in \\`${join(dir, 'package.json')}\\` must be an object`,\n );\n }\n return Object.keys(dependencies).sort();\n}\n\n/**\n * Resolve `name` from `from` within the project: probe\n * `<ancestor>/node_modules/<name>/package.json` for `from` and each ancestor up\n * to and including the project root, first hit wins. Beyond the root the walk\n * stops, so a package installed only above the project cannot satisfy the\n * dependency. The probe deliberately ignores `exports` — an addon that hides\n * `package.json` from it is still an installed addon, and `exports` describes\n * entry points, not the package root.\n */\nfunction resolveDependency(projectRoot: string, from: string, name: string): string {\n const probe = join('node_modules', ...name.split('/'), 'package.json');\n\n for (let dir = resolve(from); isInside(projectRoot, dir); dir = dirname(dir)) {\n const manifest = join(dir, probe);\n try {\n if (statSync(manifest, { throwIfNoEntry: false })?.isFile() === true) {\n return realpathSync(dirname(manifest));\n }\n } catch (error) {\n throw new BuilderError(\n 'npm.bad-package',\n `cannot inspect \\`${manifest}\\`: ${errorMessage(error)}`,\n );\n }\n // The project root is the last directory whose `node_modules` is in scope.\n if (dir === projectRoot) break;\n }\n\n const declaredBy = join(from, 'package.json');\n throw new BuilderError(\n 'npm.missing-dependency',\n `cannot resolve \\`${name}\\` declared by \\`${declaredBy}\\`: ` +\n 'not found in the project\\'s node_modules directories',\n );\n}\n\n/**\n * True when `target` is `root` or a descendant of it. `path.relative` returns\n * an absolute path for a different Windows drive, hence both checks.\n */\nfunction isInside(root: string, target: string): boolean {\n const path = relative(root, target);\n return path === '' || (!isAbsolute(path) && path !== '..' && !path.startsWith(`..${sep}`));\n}\n\n/** Raw `package.json` of the package at `dir`, or `{}` when it has none. */\nfunction readManifest(dir: string): Record<string, unknown> {\n const file = join(dir, 'package.json');\n let text: string;\n try {\n text = readFileSync(file, 'utf8');\n } catch (error) {\n if (isMissingFile(error)) return {};\n throw new BuilderError('npm.bad-package', `cannot read \\`${file}\\`: ${errorMessage(error)}`);\n }\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(text);\n } catch (error) {\n throw new BuilderError(\n 'npm.bad-package',\n `invalid JSON in \\`${file}\\`: ${errorMessage(error)}`,\n );\n }\n if (!isRecord(parsed)) {\n throw new BuilderError('npm.bad-package', `\\`${file}\\` must contain a JSON object`);\n }\n return parsed;\n}\n\nfunction readAddon(dir: string) {\n try {\n return readAddonPackage(dir);\n } catch (error) {\n if (error instanceof AddonError) {\n // Same treatment as local discovery: keep the addon code, name the package.\n const prefix = `${error.code}: `;\n const detail = error.message.startsWith(prefix)\n ? error.message.slice(prefix.length)\n : error.message;\n throw new AddonError(error.code, `in \\`${dir}\\`: ${detail}`);\n }\n throw error;\n }\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction isMissingFile(error: unknown): boolean {\n return (\n typeof error === 'object' &&\n error !== null &&\n (error as { code?: unknown }).code === 'ENOENT'\n );\n}\n\nfunction errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n","/**\n * Release addon discovery: lock entries of `source: 'release'` become\n * `ResolvedAddon`s read from `<workDir>/addons/<resource>`.\n *\n * Release addons are installed by `cybermp add` / `cybermp install` and pinned\n * in `cybermp.lock.json`; resolution never downloads anything. A lock entry the\n * builder cannot see, or cannot trust, fails the build rather than being\n * skipped — a silently missing addon changes what the server loads, and building\n * files nobody verified is worse. Both failures name `cybermp install`, which\n * restores the locked archive (and replaces content that no longer verifies).\n *\n * Verification has two halves, because the lock pins the archive and the\n * installation is a directory:\n *\n * 1. the install record written by `installRelease` (see `installRecord.ts`)\n * must name the archive digest the lock entry carries;\n * 2. every file under the addon must still hash to the digest the record stored.\n *\n * The result is `kind: 'prebuilt'` (`source: 'release'`): an archive ships the\n * files to copy. `version` and `requires` come from the installed package's own\n * marker; `name` is the resource name the lock entry is keyed by — the name the\n * addon was installed as. That key must equal the package's `cybermp.resource`\n * too: a hand-edited lock key that names another resource is\n * `addons.name-mismatch`, because the installation no longer matches what the\n * lock records.\n *\n * Errors: `addons.missing-release` when the directory is absent, `addons.stat`\n * when it cannot be inspected, `addons.outside-root` when it resolves outside\n * the work directory, `addons.integrity` when the record is missing,\n * names another archive or the files changed, `addons.name-mismatch` when the\n * marker names another resource, `lock.incomplete` when the entry\n * has no `integrity` to verify against, and the addon package's own error\n * (`package.bad-json`, `package.missing-marker`, …) with the directory named for\n * a malformed marker.\n */\nimport { realpathSync, statSync } from 'node:fs';\nimport { isAbsolute, join, relative, sep } from 'node:path';\nimport { AddonError, type AddonPackage, readAddonPackage } from '@cybermp-community/addon';\nimport { BuilderError } from '../errors.js';\nimport { readInstallRecord } from './installRecord.js';\nimport { readLock, type LockEntry } from './lock.js';\nimport { hashAddonDirectory } from './sources/path.js';\nimport type { ResolvedAddon } from './types.js';\n\n/** The hint every release-state error carries: restore it from the lock. */\nconst INSTALL_HINT = 'run `cybermp install` to restore it from cybermp.lock.json';\n\n/**\n * Resolve every `release` entry of the project's lock, sorted by resource name\n * for a deterministic order independent of the lock file's key order.\n *\n * `workDir` is the project's build work directory (absolute, as\n * `ProjectConfig.workDir` provides it); addons live under `<workDir>/addons/`.\n */\nexport async function resolveReleaseAddons(\n root: string,\n workDir: string,\n): Promise<ResolvedAddon[]> {\n const lock = readLock(root);\n const addons: ResolvedAddon[] = [];\n\n for (const name of Object.keys(lock.addons).sort()) {\n const entry = lock.addons[name];\n if (entry === undefined || entry.source !== 'release') continue;\n addons.push(await resolveReleaseAddon(name, entry, join(workDir, 'addons', name), workDir));\n }\n\n return addons;\n}\n\n/**\n * Verify the installation at `dir` against `entry` and return the archive\n * digest it proves. Throws the `addons.*` / `lock.*` codes of the module\n * comment, so the build can fail on it and `install` can repair on it.\n *\n * `workDir` is the project's build work directory. The installation's real path\n * must stay inside it, exactly as a local addon must stay inside the project\n * root (`addons.outside-root`): an installation replaced by a symlink to some\n * other tree must not be able to make the build copy files from outside the\n * project.\n */\nexport async function verifyReleaseInstall(\n name: string,\n dir: string,\n entry: LockEntry,\n workDir: string,\n): Promise<string> {\n if (!isDirectory(dir)) {\n throw new BuilderError(\n 'addons.missing-release',\n `the release addon \\`${name}\\` is not installed at \\`${dir}\\`; ${INSTALL_HINT}`,\n );\n }\n\n const installedDir = containedDirectory(name, dir, workDir);\n\n if (entry.integrity === undefined) {\n throw new BuilderError(\n 'lock.incomplete',\n `the release lock entry \\`${name}\\` has no \\`integrity\\`; re-add it with \\`cybermp add\\``,\n );\n }\n\n const record = readInstallRecord(dir);\n if (record === undefined) {\n throw new BuilderError(\n 'addons.integrity',\n `the installation of \\`${name}\\` at \\`${dir}\\` carries no usable install record; ` +\n INSTALL_HINT,\n );\n }\n\n if (record.integrity !== entry.integrity) {\n throw new BuilderError(\n 'addons.integrity',\n `\\`${name}\\` was installed from ${record.integrity}, but cybermp.lock.json records ` +\n `${entry.integrity}; ${INSTALL_HINT}`,\n );\n }\n\n const digest = await hashAddonDirectory(installedDir);\n if (digest !== record.digest) {\n throw new BuilderError(\n 'addons.integrity',\n `the files installed for \\`${name}\\` at \\`${dir}\\` hash to ${digest}, but the ` +\n `installation recorded ${record.digest}; ${INSTALL_HINT}`,\n );\n }\n\n return entry.integrity;\n}\n\n/** One verified release addon, with its package marker read from the tree. */\nasync function resolveReleaseAddon(\n name: string,\n entry: LockEntry,\n dir: string,\n workDir: string,\n): Promise<ResolvedAddon> {\n const integrity = await verifyReleaseInstall(name, dir, entry, workDir);\n const addon = readPackage(dir);\n\n // The lock key is the resource name the project loads, and it is also the\n // directory the install lives in; the package's own marker is the authority\n // on what the addon materializes as. If the two disagree, rendering would\n // write `resources/<key>` while the manifest describes another resource, so\n // the mismatch is refused as `addons.name-mismatch` — the lock and the\n // package disagree about the name, which is not a hash problem.\n if (addon.resource !== name) {\n throw new BuilderError(\n 'addons.name-mismatch',\n `the release addon locked as \\`${name}\\` is installed from a package whose ` +\n `\\`cybermp.resource\\` is \\`${addon.resource}\\`; the lock and the installation disagree — ` +\n INSTALL_HINT,\n );\n }\n\n return {\n name,\n dir,\n version: addon.version,\n source: 'release',\n requires: addon.requires,\n kind: 'prebuilt',\n integrity,\n resolved: entry.resolved,\n };\n}\n\n/** True when `path` is a directory (a broken symlink is not). */\nfunction isDirectory(path: string): boolean {\n try {\n return statSync(path, { throwIfNoEntry: false })?.isDirectory() ?? false;\n } catch (error) {\n throw new BuilderError('addons.stat', `cannot inspect \\`${path}\\`: ${errorMessage(error)}`);\n }\n}\n\n/**\n * `dir`'s real path, refused with `addons.outside-root` when it leaves\n * `workDir`.\n *\n * `statSync` follows a symlinked directory, so an installation swapped for a\n * link to `/somewhere/else` would otherwise verify and hash a tree the project\n * does not own. The check is the release counterpart of the local addon\n * screen's realpath containment.\n */\nfunction containedDirectory(name: string, dir: string, workDir: string): string {\n let realWorkDir: string;\n let realDir: string;\n try {\n realWorkDir = realpathSync(workDir);\n realDir = realpathSync(dir);\n } catch (error) {\n throw new BuilderError('addons.stat', `cannot inspect \\`${dir}\\`: ${errorMessage(error)}`);\n }\n\n if (!isInside(realWorkDir, realDir)) {\n throw new BuilderError(\n 'addons.outside-root',\n `the release addon \\`${name}\\` at \\`${dir}\\` resolves outside the work directory ` +\n `\\`${realWorkDir}\\`; reinstall it with \\`cybermp install\\``,\n );\n }\n return realDir;\n}\n\n/**\n * True when `target` is `root` or a descendant of it. `path.relative` returns\n * an absolute path for a different Windows drive, hence both checks.\n */\nfunction isInside(root: string, target: string): boolean {\n const path = relative(root, target);\n return path === '' || (!isAbsolute(path) && path !== '..' && !path.startsWith(`..${sep}`));\n}\n\n/** The addon package of `dir`, with the addon's own code and the directory named. */\nfunction readPackage(dir: string): AddonPackage {\n try {\n return readAddonPackage(dir);\n } catch (error) {\n if (error instanceof AddonError) {\n // Keep the addon package's code but add the directory: the raw message\n // describes the marker, not which addon carries it.\n const prefix = `${error.code}: `;\n const detail = error.message.startsWith(prefix)\n ? error.message.slice(prefix.length)\n : error.message;\n throw new AddonError(error.code, `in \\`${dir}\\`: ${detail}`);\n }\n throw error;\n }\n}\n\nfunction errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n","/**\n * `cybermp.config.json` — project-wide configuration (spec §8).\n *\n * The file is optional: without it every field falls back to the defaults\n * below. The key set is closed — `serverToml` and `build` are explicitly not\n * project keys (the former is always `<root>/server.toml`, the latter lives in\n * each addon's own `package.json`) and are reported as `config.unknown-key`\n * like any other typo.\n *\n * Every path on the returned object is absolute: file values and built-in\n * defaults are both resolved against the real path of the project root.\n */\nimport { readFileSync, realpathSync, renameSync, rmSync, writeFileSync } from 'node:fs';\nimport { readFile } from 'node:fs/promises';\nimport { isAbsolute, join, resolve } from 'node:path';\nimport {\n RESERVED_RESOURCE_NAMES,\n RESOURCE_NAME_PATTERN,\n type ResourceManifest,\n} from '@cybermp-community/addon';\nimport { BuilderError } from './errors.js';\n\n/** Name of the optional project configuration file, relative to the root. */\nexport const CONFIG_FILENAME = 'cybermp.config.json';\n\n/** Manifest fields a project may override on a materialized addon copy. */\nexport type AddonOverride = Partial<\n Pick<ResourceManifest, 'cef_url' | 'hotreload' | 'use_game_natives'>\n>;\n\nexport interface ProjectConfig {\n /** Real path of the project root. */\n root: string;\n /**\n * Directory passed to `-rdir`. Always absolute; defaults to\n * `<root>/resources`.\n */\n resourcesDir: string;\n /**\n * Build state directory (compiler cache, unpacked release addons). Always\n * absolute; defaults to `<root>/.cybermp`.\n */\n workDir: string;\n addons: {\n /**\n * Directory globs, relative to `root`; absolute globs and `..` segments\n * are rejected. Default `['addons/*']`.\n */\n local: string[];\n /** Explicit load order; unlisted addons follow in graph order. */\n order: string[];\n /** Manifest edits applied to the materialized copy, keyed by addon name. */\n overrides: Record<string, AddonOverride>;\n /** Addons kept installed but neither built nor listed in `server.toml`. */\n disabled: string[];\n /** Hand-managed resources in `resourcesDir`, copied into `server.toml` as-is. */\n extraResources: string[];\n };\n redscripts: {\n /** Whether `final_redscripts` is built at all. Default `true`. */\n enabled: boolean;\n /** Pinned `redscript-cli` version. Default `'0.5.31'`. */\n compilerVersion: string;\n /**\n * Optional platform whose compiler and core baseline are used. Consumers\n * resolve the effective platform: this field, then `server.platforms[0]`,\n * then the host platform.\n */\n platform?: 'win' | 'linux';\n /**\n * `'core'` (core baseline), `'none'` (compile with core sources; refused\n * without `CYBERMP_REDSCRIPT_COMPILER` because the pinned compiler needs\n * `-b`) or a path.\n */\n baseline: 'core' | 'none' | string;\n /** Output resource name. Default `'final_redscripts'`. */\n output: string;\n };\n server: {\n /** Platform builds to keep downloaded. Default: the host platform. */\n platforms: Array<'win' | 'linux'>;\n /** Pinned server release tag; latest when absent. */\n version?: string;\n };\n}\n\ntype Table = Record<string, unknown>;\n\nconst TOP_LEVEL_KEYS: ReadonlySet<string> = new Set([\n '$schema',\n 'resourcesDir',\n 'workDir',\n 'addons',\n 'redscripts',\n 'server',\n]);\n\nconst ADDON_KEYS: ReadonlySet<string> = new Set([\n 'local',\n 'order',\n 'overrides',\n 'disabled',\n 'extraResources',\n]);\n\nconst OVERRIDE_KEYS: ReadonlySet<string> = new Set([\n 'cef_url',\n 'hotreload',\n 'use_game_natives',\n]);\n\nconst REDSCRIPT_KEYS: ReadonlySet<string> = new Set([\n 'enabled',\n 'compilerVersion',\n 'platform',\n 'baseline',\n 'output',\n]);\n\nconst SERVER_KEYS: ReadonlySet<string> = new Set(['platforms', 'version']);\n\nconst PLATFORMS: ReadonlySet<string> = new Set(['win', 'linux']);\n\n/**\n * Resource names the generated scripts may not take: every name the toolchain\n * reserves, minus the one this stage exists to write. `final_redscripts` is\n * reserved for *addons* — an addon may not claim it — but it is exactly the\n * directory the redscripts stage produces, so it is allowed here and refused\n * only when the project already uses that name for something else.\n */\nconst RESERVED_OUTPUT_NAMES: ReadonlySet<string> = new Set(\n RESERVED_RESOURCE_NAMES.filter((name) => name !== 'final_redscripts'),\n);\n\n/**\n * Read and validate `<root>/cybermp.config.json`, synchronously.\n *\n * Same contract as {@link loadConfig}. The addon commands write the config\n * through {@link writeAddonConfig}, and a caller (or a test) that has just run\n * one can read the result back without awaiting.\n */\nexport function loadConfigSync(root: string): ProjectConfig {\n const projectRoot = resolveProjectRoot(root);\n const text = readConfigTextSync(projectRoot);\n return buildConfig(projectRoot, text);\n}\n\n/**\n * Read and validate `<root>/cybermp.config.json`.\n *\n * A missing file yields the defaults; malformed JSON is `config.parse`, an\n * unknown key (at any level) is `config.unknown-key`, and a value of the wrong\n * shape is `config.bad-type`.\n */\nexport async function loadConfig(root: string): Promise<ProjectConfig> {\n const projectRoot = resolveProjectRoot(root);\n const text = await readConfigText(projectRoot);\n return buildConfig(projectRoot, text);\n}\n\n/** Turn the raw file text (or `undefined`) into a validated config. */\nfunction buildConfig(projectRoot: string, text: string | undefined): ProjectConfig {\n const file = text === undefined ? {} : parseConfigJson(text);\n\n rejectUnknownKeys(file, TOP_LEVEL_KEYS, '');\n optionalString(file, '$schema', '');\n\n return {\n root: projectRoot,\n resourcesDir: resolvePathField(file, 'resourcesDir', projectRoot, 'resources'),\n workDir: resolvePathField(file, 'workDir', projectRoot, '.cybermp'),\n addons: parseAddons(file.addons),\n redscripts: parseRedscripts(file.redscripts),\n server: parseServer(file.server),\n };\n}\n\n/**\n * The `addons` fields the addon commands may rewrite in\n * `cybermp.config.json`.\n *\n * The writer touches only these documented keys: every other key in the file\n * (including `$schema`, `addons.overrides` and the build settings) is preserved\n * exactly as written, so `cybermp add` never re-serializes a hand-tuned config\n * from the defaults it resolves.\n */\nexport interface AddonConfigEdit {\n /** Replace `addons.local` when given. */\n local?: string[];\n /** Replace `addons.order` when given. */\n order?: string[];\n /** Replace `addons.disabled` when given. */\n disabled?: string[];\n}\n\n/**\n * Rewrite the documented `addons` keys of `<root>/cybermp.config.json`.\n *\n * The file is re-read as raw JSON first, so keys this version of the builder\n * does not understand yet survive the edit; only the given keys are replaced.\n * The write is atomic (temporary file plus rename), and a failed write is\n * `config.write`.\n *\n * Errors: `config.read`, `config.parse`, `config.bad-type` from reading the\n * existing file, and `config.write` when it cannot be replaced.\n */\nexport function writeAddonConfig(root: string, edit: AddonConfigEdit): void {\n const projectRoot = resolveProjectRoot(root);\n const file = join(projectRoot, CONFIG_FILENAME);\n const text = readConfigTextSync(projectRoot);\n const document = text === undefined ? {} : parseConfigJson(text);\n\n let addons: Table;\n const existing = document.addons;\n if (existing === undefined) {\n addons = {};\n document.addons = addons;\n } else {\n addons = requireTable(existing, 'addons');\n }\n\n if (edit.local !== undefined) addons.local = edit.local;\n if (edit.order !== undefined) addons.order = edit.order;\n if (edit.disabled !== undefined) addons.disabled = edit.disabled;\n\n const serialized = `${JSON.stringify(document, null, 2)}\\n`;\n const temporary = `${file}.${process.pid}.tmp`;\n try {\n writeFileSync(temporary, serialized);\n renameSync(temporary, file);\n } catch (error) {\n rmSync(temporary, { force: true });\n throw new BuilderError(\n 'config.write',\n `cannot write ${CONFIG_FILENAME}: ${errorMessage(error)}`,\n );\n }\n}\n\nfunction resolveProjectRoot(root: string): string {\n try {\n return realpathSync(root);\n } catch (error) {\n throw new BuilderError(\n 'config.root',\n `cannot resolve project root \\`${root}\\`: ${errorMessage(error)}`,\n );\n }\n}\n\nasync function readConfigText(root: string): Promise<string | undefined> {\n try {\n return await readFile(join(root, CONFIG_FILENAME), 'utf8');\n } catch (error) {\n if (isErrno(error, 'ENOENT')) return undefined;\n throw new BuilderError(\n 'config.read',\n `cannot read ${CONFIG_FILENAME}: ${errorMessage(error)}`,\n );\n }\n}\n\n/** {@link readConfigText}, synchronously, for the addon commands. */\nfunction readConfigTextSync(root: string): string | undefined {\n try {\n return readFileSync(join(root, CONFIG_FILENAME), 'utf8');\n } catch (error) {\n if (isErrno(error, 'ENOENT')) return undefined;\n throw new BuilderError(\n 'config.read',\n `cannot read ${CONFIG_FILENAME}: ${errorMessage(error)}`,\n );\n }\n}\n\nfunction parseConfigJson(text: string): Table {\n let parsed: unknown;\n try {\n parsed = JSON.parse(text);\n } catch (error) {\n throw new BuilderError(\n 'config.parse',\n `invalid JSON in ${CONFIG_FILENAME}: ${errorMessage(error)}`,\n );\n }\n return requireTable(parsed, CONFIG_FILENAME);\n}\n\nfunction parseAddons(value: unknown): ProjectConfig['addons'] {\n const table = optionalTable(value, 'addons');\n rejectUnknownKeys(table, ADDON_KEYS, 'addons');\n\n const local = stringListField(table, 'local', 'addons', ['addons/*']);\n for (const pattern of local) {\n if (!isRelativeGlob(pattern)) {\n throw new BuilderError(\n 'config.bad-type',\n `\\`addons.local\\` entry ${JSON.stringify(pattern)} must be a relative glob inside the project root`,\n );\n }\n }\n\n return {\n local,\n order: stringListField(table, 'order', 'addons', []),\n overrides: parseOverrides(table.overrides),\n disabled: stringListField(table, 'disabled', 'addons', []),\n extraResources: stringListField(table, 'extraResources', 'addons', []),\n };\n}\n\n/**\n * `addons.local` globs are expanded relative to the project root. An absolute\n * glob or a `..` segment would let a config read, build and materialize addons\n * anywhere on disk, so both are rejected.\n */\nfunction isRelativeGlob(pattern: string): boolean {\n if (isAbsolute(pattern)) return false;\n return !pattern.split(/[\\\\/]/).includes('..');\n}\n\nfunction parseOverrides(value: unknown): Record<string, AddonOverride> {\n if (value === undefined) return {};\n const table = requireTable(value, 'addons.overrides');\n const overrides: Record<string, AddonOverride> = {};\n\n for (const [name, entry] of Object.entries(table)) {\n const path = `addons.overrides.${name}`;\n const fields = requireTable(entry, path);\n rejectUnknownKeys(fields, OVERRIDE_KEYS, path);\n\n const override: AddonOverride = {};\n const cefUrl = optionalString(fields, 'cef_url', path);\n if (cefUrl !== undefined) override.cef_url = cefUrl;\n const hotreload = optionalBoolean(fields, 'hotreload', path);\n if (hotreload !== undefined) override.hotreload = hotreload;\n const useGameNatives = optionalBoolean(fields, 'use_game_natives', path);\n if (useGameNatives !== undefined) override.use_game_natives = useGameNatives;\n overrides[name] = override;\n }\n\n return overrides;\n}\n\nfunction parseRedscripts(value: unknown): ProjectConfig['redscripts'] {\n const table = optionalTable(value, 'redscripts');\n rejectUnknownKeys(table, REDSCRIPT_KEYS, 'redscripts');\n\n const config: ProjectConfig['redscripts'] = {\n enabled: booleanField(table, 'enabled', 'redscripts', true),\n compilerVersion: stringField(table, 'compilerVersion', 'redscripts', '0.5.31'),\n baseline: baselineField(table, 'baseline', 'redscripts', 'core'),\n output: outputNameField(table, 'output', 'redscripts', 'final_redscripts'),\n };\n\n const platform = optionalPlatform(table, 'platform', 'redscripts');\n if (platform !== undefined) config.platform = platform;\n return config;\n}\n\n/**\n * The `redscripts.baseline` field.\n *\n * `'none'` compiles the core's own `.reds` sources instead of a precompiled\n * bundle, which the pinned `redscript-cli` 0.5.31 cannot do: it declares `-b`\n * required, so the build would fail inside the compiler after every other stage\n * ran. Only a compiler override makes the mode usable, and the message says\n * exactly that — the same variable the compiler resolver honours.\n */\nfunction baselineField(\n table: Table,\n key: string,\n prefix: string,\n fallback: string,\n): string {\n const value = stringField(table, key, prefix, fallback);\n if (value !== 'none') return value;\n\n const override = process.env.CYBERMP_REDSCRIPT_COMPILER;\n if (override !== undefined && override !== '') return value;\n\n throw new BuilderError(\n 'config.bad-value',\n `\\`${fieldPath(prefix, key)}\\` cannot be \\`none\\`: the pinned redscript-cli 0.5.31 ` +\n 'requires `-b`, so a build cannot compile without a baseline; set ' +\n 'CYBERMP_REDSCRIPT_COMPILER to a compiler that supports it, or point ' +\n `\\`${fieldPath(prefix, key)}\\` at a baseline`,\n );\n}\n\n/**\n * The `redscripts.output` field: a resource name the stage may create.\n *\n * Anything that is not one lowercase path segment is `config.bad-value` — the\n * stage joins the value onto the resources directory, so `../evil`, `a/b` and\n * an absolute path would write outside it — and so is a name the core or the\n * builder already owns. The message always states the accepted shape, so the\n * fix needs no reference to the docs.\n */\nfunction outputNameField(\n table: Table,\n key: string,\n prefix: string,\n fallback: string,\n): string {\n const value = stringField(table, key, prefix, fallback);\n\n if (!RESOURCE_NAME_PATTERN.test(value)) {\n throw new BuilderError(\n 'config.bad-value',\n `\\`${fieldPath(prefix, key)}\\` must be a resource name matching ` +\n `\\`${RESOURCE_NAME_PATTERN.source}\\`, got ${JSON.stringify(value)}`,\n );\n }\n if (RESERVED_OUTPUT_NAMES.has(value)) {\n throw new BuilderError(\n 'config.bad-value',\n `\\`${fieldPath(prefix, key)}\\` cannot be \\`${value}\\`: that name is reserved by the ` +\n `toolchain; choose a name matching \\`${RESOURCE_NAME_PATTERN.source}\\``,\n );\n }\n return value;\n}\n\nfunction parseServer(value: unknown): ProjectConfig['server'] {\n const table = optionalTable(value, 'server');\n rejectUnknownKeys(table, SERVER_KEYS, 'server');\n\n const config: ProjectConfig['server'] = {\n platforms: platformListField(table, 'platforms', 'server', [hostPlatform()]),\n };\n\n const version = optionalString(table, 'version', 'server');\n if (version !== undefined) config.version = version;\n return config;\n}\n\n/** The only build targets CyberMP ships binaries for; other hosts use Linux. */\nfunction hostPlatform(): 'win' | 'linux' {\n return process.platform === 'win32' ? 'win' : 'linux';\n}\n\nfunction resolvePathField(\n table: Table,\n key: string,\n root: string,\n fallback: string,\n): string {\n const value = optionalString(table, key, '');\n return resolve(root, value ?? fallback);\n}\n\nfunction rejectUnknownKeys(\n table: Table,\n allowed: ReadonlySet<string>,\n prefix: string,\n): void {\n for (const key of Object.keys(table)) {\n if (allowed.has(key)) continue;\n const path = fieldPath(prefix, key);\n throw new BuilderError(\n 'config.unknown-key',\n `unknown key \\`${path}\\` in ${CONFIG_FILENAME}`,\n );\n }\n}\n\nfunction optionalTable(value: unknown, path: string): Table {\n return value === undefined ? {} : requireTable(value, path);\n}\n\nfunction requireTable(value: unknown, path: string): Table {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) {\n throw badType(path, 'an object', value);\n }\n return value as Table;\n}\n\nfunction stringField(\n table: Table,\n key: string,\n prefix: string,\n fallback: string,\n): string {\n return optionalString(table, key, prefix) ?? fallback;\n}\n\nfunction optionalString(table: Table, key: string, prefix: string): string | undefined {\n const value = table[key];\n if (value === undefined) return undefined;\n if (typeof value !== 'string') {\n throw badType(fieldPath(prefix, key), 'a string', value);\n }\n return value;\n}\n\nfunction booleanField(\n table: Table,\n key: string,\n prefix: string,\n fallback: boolean,\n): boolean {\n return optionalBoolean(table, key, prefix) ?? fallback;\n}\n\nfunction optionalBoolean(\n table: Table,\n key: string,\n prefix: string,\n): boolean | undefined {\n const value = table[key];\n if (value === undefined) return undefined;\n if (typeof value !== 'boolean') {\n throw badType(fieldPath(prefix, key), 'a boolean', value);\n }\n return value;\n}\n\nfunction stringListField(\n table: Table,\n key: string,\n prefix: string,\n fallback: string[],\n): string[] {\n const value = table[key];\n const path = fieldPath(prefix, key);\n if (value === undefined) return [...fallback];\n if (!Array.isArray(value)) throw badType(path, 'an array of strings', value);\n\n return value.map((entry, index) => {\n if (typeof entry !== 'string') {\n throw badType(`${path}[${index}]`, 'a string', entry);\n }\n return entry;\n });\n}\n\nfunction optionalPlatform(\n table: Table,\n key: string,\n prefix: string,\n): 'win' | 'linux' | undefined {\n const value = table[key];\n if (value === undefined) return undefined;\n const path = fieldPath(prefix, key);\n if (typeof value !== 'string' || !PLATFORMS.has(value)) {\n throw badType(path, `one of ${[...PLATFORMS].map((p) => `\\`${p}\\``).join(', ')}`, value);\n }\n return value as 'win' | 'linux';\n}\n\nfunction platformListField(\n table: Table,\n key: string,\n prefix: string,\n fallback: Array<'win' | 'linux'>,\n): Array<'win' | 'linux'> {\n const value = table[key];\n const path = fieldPath(prefix, key);\n if (value === undefined) return [...fallback];\n if (!Array.isArray(value)) throw badType(path, 'an array of platforms', value);\n\n return value.map((entry, index) => {\n if (typeof entry !== 'string' || !PLATFORMS.has(entry)) {\n throw badType(`${path}[${index}]`, '`win` or `linux`', entry);\n }\n return entry as 'win' | 'linux';\n });\n}\n\nfunction fieldPath(prefix: string, key: string): string {\n return prefix === '' ? key : `${prefix}.${key}`;\n}\n\nfunction badType(path: string, expected: string, value: unknown): BuilderError {\n return new BuilderError(\n 'config.bad-type',\n `\\`${path}\\` must be ${expected}, got ${describe(value)}`,\n );\n}\n\nfunction describe(value: unknown): string {\n if (value === null) return 'null';\n if (value === undefined) return 'undefined';\n if (Array.isArray(value)) return 'an array';\n if (typeof value === 'object') return 'an object';\n if (typeof value === 'string') return `a string (${JSON.stringify(value)})`;\n return `a ${typeof value}`;\n}\n\nfunction errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\nfunction isErrno(error: unknown, code: string): boolean {\n return (\n typeof error === 'object' &&\n error !== null &&\n (error as { code?: unknown }).code === code\n );\n}\n","/**\n * Project resolution: configuration plus every addon the project pulls in, in\n * the order they load.\n *\n * The three sources are composed here and nowhere else: local directories from\n * `addons.local`, npm dependencies of the project, and the installations\n * `cybermp.lock.json` pins as releases. `build` and `check` both call\n * {@link resolveProject}, so a build and a check of one tree cannot disagree\n * about what the project contains.\n *\n * npm addons are resolved through {@link resolveNpmAddonsChecked}: a missing\n * dependency is a state error with a `cybermp install` hint, exactly as the\n * build's stage 0 promises. A name that both npm and the lock provide is\n * refused by `orderAddons` (`addon.duplicate-name`), never resolved twice.\n */\n\nimport { resolveLocalAddons } from './addons/local.js';\nimport { resolveNpmAddons } from './addons/npm.js';\nimport { orderAddons } from './addons/order.js';\nimport { resolveReleaseAddons } from './addons/release.js';\nimport type { ResolvedAddon } from './addons/types.js';\nimport type { ProjectConfig } from './config.js';\nimport { loadConfig } from './config.js';\nimport { BuilderError } from './errors.js';\n\nexport interface ResolvedProject {\n /** Validated project configuration; every path is absolute. */\n config: ProjectConfig;\n /** Every resolved addon, disabled ones included, in discovery order. */\n addons: ResolvedAddon[];\n /**\n * The enabled addons in load order — dependencies before their dependents,\n * ties broken by `addons.order` then resource name. This is the order the\n * `resources` array of `server.toml` must follow.\n */\n ordered: ResolvedAddon[];\n}\n\n/**\n * Read `<root>/cybermp.config.json` and resolve every source of addons.\n *\n * The globs come from the config and are expanded relative to the real project\n * root, so a project relocated on disk keeps working. Resolution also orders\n * the addons: a duplicate resource name, an `addons.order` or `addons.disabled`\n * entry that names nothing, an unknown or disabled requirement, or a `requires`\n * cycle fails the whole project rather than being reported later by the build.\n *\n * Errors: `config.*` while the config is read, `addons.*` from local\n * resolution, `npm.missing-dependency` (with an install hint) when a declared\n * dependency is not installed, the release verifier's codes when a locked\n * installation is missing, unverifiable or outside the work directory, and\n * `addon.*` from ordering.\n */\nexport async function resolveProject(root: string): Promise<ResolvedProject> {\n const config = await loadConfig(root);\n const local = await resolveLocalAddons(config.root, config.addons.local);\n const npm = await resolveNpmAddonsChecked(config.root);\n const release = await resolveReleaseAddons(config.root, config.workDir);\n const addons = [...local, ...npm, ...release];\n const ordered = orderAddons(\n addons,\n config.addons.order,\n config.addons.disabled,\n Object.keys(config.addons.overrides),\n );\n\n return { config, addons, ordered };\n}\n\n/**\n * Resolve npm addons, turning a missing dependency into an actionable error.\n *\n * `resolveNpmAddons` reports a missing dependency as `npm.missing-dependency`;\n * the project adds the `cybermp install` hint the build's stage 0 promises, so\n * the message alone tells the user how to recover. Exported because\n * `listAddons` must resolve the same way a build does: a listing that skips the\n * hint would tell the user what is installed but not how to fix it.\n */\nexport async function resolveNpmAddonsChecked(root: string): Promise<ResolvedAddon[]> {\n try {\n return await resolveNpmAddons(root);\n } catch (error) {\n if (error instanceof BuilderError && error.code === 'npm.missing-dependency') {\n throw new BuilderError(\n error.code,\n `${detailOf(error)} — run \\`cybermp install\\` to install the project's dependencies`,\n );\n }\n throw error;\n }\n}\n\n/** The message of a `BuilderError` without its `<code>: ` prefix. */\nfunction detailOf(error: BuilderError): string {\n const prefix = `${error.code}: `;\n return error.message.startsWith(prefix) ? error.message.slice(prefix.length) : error.message;\n}\n","/**\n * REDscript compilation: collect the `.reds` sources every addon ships, stage\n * them into one directory and compile them against the core baseline.\n *\n * `redscript-cli` stages its inputs into a single flat directory, so two\n * sources with the same file name cannot both be compiled — and which one won\n * would silently depend on addon order. Collection therefore refuses a name\n * that two sources share (`redscripts.collision`, naming both addons and both\n * original file names) instead of letting one shadow the other. The comparison\n * is case-insensitive: the compiler's module namespace and Windows filesystems\n * do not distinguish `Shared.reds` from `shared.reds`.\n *\n * Manifest `file` patterns are expanded by the shared `expandFilePattern`\n * helper — the same one materialization uses — so a glob such as\n * `scripts/*.reds` compiles exactly the files it ships, and a pattern or match\n * that escapes the addon is refused rather than resolved.\n *\n * Staging copies each source under a numeric name (`000000.reds`, `000001.reds`,\n * …) in a fresh `mkdtemp` directory under `<workDir>/redscripts`, which keeps\n * the compiler's input free of names that could carry characters it treats\n * specially, and keeps the addon packages untouched. The staged directory is\n * removed afterwards; only the log survives.\n *\n * The compiler is invoked as\n * `redscript-cli compile -s <staged> -b <baseline> -o <out>`. Its combined\n * output is always logged to `<workDir>/redscripts/compile.log` when there is\n * something to compile, so a failed build leaves the compiler's own diagnosis\n * behind. The exit code is authoritative; a zero exit is still a failure when\n * the output carries an explicit `error:` diagnostic, and never merely because\n * it contains the word \"error\" (a successful run may print \"0 errors\"). The run\n * is bounded by `timeoutMs` (ten minutes by default): on expiry the whole\n * process tree is signalled, escalated to SIGKILL, and the captured output is\n * written to the log before the call rejects — a hung compiler can neither\n * block the build nor leave no evidence.\n *\n * On success the output is checked for the `REDS` magic before it is copied\n * into `<outputDir>/final.redscripts`; anything else is `redscripts.output` and\n * is never published.\n *\n * `<outputDir>` is created only once there is something to write, and a run\n * that created it and then failed removes it again: a failed compile must not\n * leave an empty resource directory behind. A directory that already existed —\n * a rebuild — is left as it was, since the caller owns it.\n *\n * With no sources there is nothing to compile: the baseline is copied as-is\n * and no log is written. Whether the baseline exists at all is checked by the\n * caller (the build pipeline), not here. `baseline` is optional only for the\n * `baseline: 'none'` setting: then the invocation carries no `-b` and the\n * compiler decides whether it can compile without one.\n */\nimport { type ChildProcess, spawn } from 'node:child_process';\nimport { readFileSync } from 'node:fs';\nimport { copyFile, mkdir, mkdtemp, open, rm, stat, writeFile } from 'node:fs/promises';\nimport { basename, join } from 'node:path';\nimport { filePatterns, parseManifest } from '@cybermp-community/addon';\nimport { expandFilePattern, isFileMatch } from '../addons/files.js';\nimport { MANIFEST_FILENAME } from '../addons/materialize.js';\nimport type { ResolvedAddon } from '../addons/types.js';\nimport { BuilderError } from '../errors.js';\n\n/** One `.reds` source: the addon that ships it and the absolute file path. */\nexport interface RedscriptSource {\n /** Resource name of the addon that owns the file. */\n addon: string;\n /** Absolute path of the `.reds` file. */\n file: string;\n}\n\n/** Options for {@link buildRedscripts}. */\nexport interface BuildRedscriptsOptions {\n /** Sources collected by {@link collectRedscripts}; empty copies the baseline. */\n sources: RedscriptSource[];\n /**\n * Compiled baseline (a `REDS` cache) the sources are compiled against.\n *\n * Omitted only for the `baseline: 'none'` project setting, where the core\n * sources are compiled without a precompiled bundle. `redscript-cli` 0.5.31\n * requires `-b`, so that mode needs a compiler that accepts a baseline-less\n * compile; the pinned compiler reports the missing bundle itself.\n */\n baseline?: string;\n /** Directory that receives `final.redscripts` and `resource.toml`. */\n outputDir: string;\n /**\n * Path of the `redscript-cli` binary to run. Required as soon as `sources` is\n * non-empty; a source-free run only copies the baseline, so the caller that\n * skips compiler resolution passes nothing.\n */\n compiler?: string;\n /** Build work directory; staging and the compile log live under `redscripts/`. */\n workDir: string;\n /** How long the compiler may run, in milliseconds; defaults to ten minutes. */\n timeoutMs?: number;\n}\n\n/** File name of the compiled cache inside the resource directory. */\nexport const REDSCRIPTS_FILENAME = 'final.redscripts';\n\n/** How long a compiler run may take when `timeoutMs` is not given. */\nexport const DEFAULT_COMPILE_TIMEOUT = 600_000;\n\n/** Subdirectory of the work directory that holds staging and the log. */\nconst WORK_SUBDIR = 'redscripts';\n\n/** Name of the compiler log, relative to {@link WORK_SUBDIR}. */\nexport const LOG_FILENAME = 'compile.log';\n\n/** Magic every compiled redscripts cache starts with. */\nconst MAGIC = 'REDS';\n\n/** How long a timed-out compiler gets to exit after SIGTERM before SIGKILL. */\nconst KILL_GRACE_MS = 5000;\n\n/** How often a timed-out compiler's process group is checked for survivors. */\nconst KILL_POLL_MS = 100;\n\n/** Cap on captured compiler output; a diagnostic-heavy run is still bounded. */\nconst MAX_OUTPUT = 10 * 1024 * 1024;\n\n/**\n * A textual failure marker for a compiler that exits zero but reports a\n * diagnostic. Deliberately narrow (`error:`), never a bare `error`: output such\n * as \"0 errors\" is success.\n */\nconst DIAGNOSTIC = /\\berror\\s*:/i;\n\n/**\n * Collect every `.reds` file the addons' manifests reference, in addon order.\n *\n * Patterns are expanded by {@link expandFilePattern}, so globs and literal\n * paths behave exactly as they do during materialization, and a pattern or\n * match that resolves outside the addon is `redscripts.path-outside`.\n *\n * A name shared by two different files — compared case-insensitively — is\n * `redscripts.collision`; the compiler's flat staging directory would drop one\n * of them otherwise.\n *\n * Errors: an unreadable manifest is `redscripts.no-manifest`; manifest syntax\n * and shape errors keep the addon package's `manifest.*` codes; pattern and\n * containment failures are `redscripts.path-outside`, `redscripts.bad-pattern`,\n * `redscripts.addon-missing` and `redscripts.read`.\n */\nexport function collectRedscripts(addons: ResolvedAddon[]): RedscriptSource[] {\n const sources: RedscriptSource[] = [];\n const byName = new Map<string, Collected>();\n\n for (const addon of addons) {\n const manifest = readManifest(addon);\n for (const pattern of filePatterns(manifest)) {\n for (const match of expandFilePattern(addon.dir, pattern, 'redscripts')) {\n if (!match.path.endsWith('.reds')) continue;\n if (!isFileMatch(match)) continue;\n\n const name = basename(match.path);\n // Case-insensitive: the compiler's module namespace and Windows file\n // systems fold case, so `Shared.reds` and `shared.reds` are one name.\n const key = name.toLowerCase();\n const existing = byName.get(key);\n if (existing !== undefined) {\n // The same physical file reached twice (two patterns, or a symlink)\n // is one source, not a collision.\n if (existing.file === match.real) continue;\n throw collisionError(existing, addon.name, name, match.real);\n }\n\n byName.set(key, { addon: addon.name, name, file: match.real });\n sources.push({ addon: addon.name, file: match.real });\n }\n }\n }\n\n return sources;\n}\n\n/** A collected source plus the manifest name it was matched under. */\ninterface Collected {\n addon: string;\n name: string;\n file: string;\n}\n\n/** `redscripts.collision`, naming both addons, both file names and both paths. */\nfunction collisionError(\n existing: Collected,\n addon: string,\n name: string,\n file: string,\n): BuilderError {\n const detail =\n existing.name === name\n ? `both ship a redscript named \\`${name}\\``\n : `ship redscripts \\`${existing.name}\\` and \\`${name}\\`, whose names differ only by case`;\n return new BuilderError(\n 'redscripts.collision',\n `addons \\`${existing.addon}\\` and \\`${addon}\\` ${detail} ` +\n `(${existing.file} and ${file}); redscript-cli stages every source in one directory, ` +\n 'so rename one of them',\n );\n}\n\n/**\n * Compile `sources` against `baseline` into `outputDir`.\n *\n * Writes `<outputDir>/final.redscripts` and a `resource.toml` that lists it,\n * with `hotreload = false` (the cache is a build artifact, not something the\n * game reloads in place). The compile log is written under\n * `<workDir>/redscripts/compile.log` whenever sources were compiled.\n *\n * Errors: `redscripts.compile-failed` (non-zero exit, timeout, spawn failure,\n * or an explicit `error:` diagnostic) with the log path in the message,\n * `redscripts.output` (missing or non-`REDS` output), `redscripts.missing`\n * (a collected source that is no longer on disk), and `compiler.missing`\n * (sources to compile but no `redscript-cli` path).\n */\nexport async function buildRedscripts(opts: BuildRedscriptsOptions): Promise<void> {\n // Remember whether the directory is ours to create: a run that fails must\n // not leave the empty directory it just made. The caller may already have\n // claimed the name in the ownership registry, but the entry on disk is this\n // function's to withdraw, so a failed compile leaves nothing behind.\n const created = !(await exists(opts.outputDir));\n\n try {\n await publish(opts);\n } catch (error) {\n if (created) {\n await rm(opts.outputDir, { recursive: true, force: true }).catch(() => undefined);\n }\n throw error;\n }\n}\n\n/** Write the resource into `opts.outputDir`, creating it only when publishing. */\nasync function publish(opts: BuildRedscriptsOptions): Promise<void> {\n if (opts.sources.length === 0) {\n if (opts.baseline === undefined) {\n throw new BuilderError(\n 'redscripts.baseline-missing',\n 'there is nothing to compile and no baseline was given; set ' +\n '`redscripts.baseline` to `core` or a path',\n );\n }\n await mkdir(opts.outputDir, { recursive: true });\n await copyFile(opts.baseline, join(opts.outputDir, REDSCRIPTS_FILENAME));\n await writeManifest(opts.outputDir);\n return;\n }\n\n const compiler = opts.compiler;\n if (compiler === undefined) {\n // Only the caller can resolve one, and it resolves it exactly when sources\n // exist; reaching here means the two disagree about the work to do.\n throw new BuilderError(\n 'compiler.missing',\n `there are ${opts.sources.length} redscript source${opts.sources.length === 1 ? '' : 's'} ` +\n 'to compile but no `redscript-cli` was resolved',\n );\n }\n\n const timeoutMs = opts.timeoutMs ?? DEFAULT_COMPILE_TIMEOUT;\n const workDir = join(opts.workDir, WORK_SUBDIR);\n await mkdir(workDir, { recursive: true });\n const staged = await mkdtemp(join(workDir, 'stage-'));\n const logPath = join(workDir, LOG_FILENAME);\n\n try {\n await stageSources(opts.sources, staged);\n\n const output = join(staged, REDSCRIPTS_FILENAME);\n const args = ['compile', '-s', staged];\n // `baseline: 'none'` compiles without a bundle; redscript-cli then reports\n // the missing `-b` itself, with the log path in the build error.\n if (opts.baseline !== undefined) args.push('-b', opts.baseline);\n args.push('-o', output);\n const result = await runCompiler(compiler, args, timeoutMs);\n // Log before any rejection: a timeout, a crash and a non-zero exit all\n // leave the compiler's own output behind.\n await writeFile(logPath, logText(compiler, args, result.output));\n\n const count = `${opts.sources.length} redscript source${opts.sources.length === 1 ? '' : 's'}`;\n if (result.timedOut) {\n throw new BuilderError(\n 'redscripts.compile-failed',\n `\\`redscript-cli\\` timed out after ${timeoutMs} ms while compiling ${count}; ` +\n `see \\`${logPath}\\``,\n );\n }\n if (result.code !== 0) {\n throw new BuilderError(\n 'redscripts.compile-failed',\n `\\`redscript-cli\\` exited with status ${result.code} while compiling ${count}; ` +\n `see \\`${logPath}\\``,\n );\n }\n if (DIAGNOSTIC.test(result.output)) {\n throw new BuilderError(\n 'redscripts.compile-failed',\n `\\`redscript-cli\\` exited with status 0 but reported an error while compiling ` +\n `${count}; see \\`${logPath}\\``,\n );\n }\n\n await verifyMagic(output);\n await mkdir(opts.outputDir, { recursive: true });\n await copyFile(output, join(opts.outputDir, REDSCRIPTS_FILENAME));\n await writeManifest(opts.outputDir);\n } finally {\n await rm(staged, { recursive: true, force: true });\n }\n}\n\n/** Read and parse one addon's `resource.toml`. */\nfunction readManifest(addon: ResolvedAddon) {\n const path = join(addon.dir, MANIFEST_FILENAME);\n let text: string;\n try {\n text = readFileSync(path, 'utf8');\n } catch (error) {\n throw new BuilderError(\n 'redscripts.no-manifest',\n `cannot read the manifest of addon \\`${addon.name}\\` at \\`${path}\\`: ${errorMessage(error)}`,\n );\n }\n return parseManifest(text);\n}\n\n/** Copy every source into `staged` as `000000.reds`, `000001.reds`, … */\nasync function stageSources(sources: RedscriptSource[], staged: string): Promise<void> {\n for (const [index, source] of sources.entries()) {\n const target = join(staged, `${String(index).padStart(6, '0')}.reds`);\n try {\n await copyFile(source.file, target);\n } catch (error) {\n throw new BuilderError(\n 'redscripts.missing',\n `cannot stage redscript \\`${source.file}\\` from addon \\`${source.addon}\\`: ` +\n errorMessage(error),\n );\n }\n }\n}\n\n/** What running the compiler produced. */\ninterface CompileResult {\n /** Exit status, or `-1` when the process could not start or timed out. */\n code: number;\n /** Combined stdout and stderr. */\n output: string;\n /** True when the run was killed for exceeding its timeout. */\n timedOut: boolean;\n}\n\n/**\n * Run the compiler and capture its combined output, bounded by `timeoutMs`.\n *\n * The child gets its own process group so a timeout takes down the compiler and\n * anything it started. On expiry the group is signalled with SIGTERM, then\n * SIGKILL after {@link KILL_GRACE_MS}, and the promise settles once the group\n * is gone or SIGKILL has been sent; the escalation timer stays referenced, so a\n * stubborn child cannot outlive the build.\n *\n * A spawn failure is reported as a result rather than thrown: it goes through\n * the same log-and-`compile-failed` path as a non-zero exit, so the log always\n * explains what happened.\n */\nfunction runCompiler(compiler: string, args: string[], timeoutMs: number): Promise<CompileResult> {\n return new Promise((resolve) => {\n const child = spawn(compiler, args, {\n stdio: ['ignore', 'pipe', 'pipe'],\n // A `.cmd`/`.bat` target is a batch file, not an executable: Windows can\n // only run it through the command interpreter and `spawn` refuses it\n // outright (`EFTYPE`). The real compiler is a binary and is spawned\n // directly, so its process group and the timeout's tree kill are\n // unchanged; the argument array is still passed as an array either way.\n shell: isBatchFile(compiler),\n // Its own process group, so a timeout kills whatever the compiler started.\n detached: process.platform !== 'win32',\n });\n const pid = child.pid;\n\n let output = '';\n let settled = false;\n let timedOut = false;\n let timeout: NodeJS.Timeout | undefined;\n let escalation: NodeJS.Timeout | undefined;\n let poll: NodeJS.Timeout | undefined;\n\n const finish = (code: number): void => {\n if (settled) return;\n settled = true;\n clearTimeout(timeout);\n clearTimeout(escalation);\n clearInterval(poll);\n resolve({ code, output, timedOut });\n };\n\n timeout = setTimeout(() => {\n timedOut = true;\n signalTree(child, pid, 'SIGTERM');\n\n escalation = setTimeout(() => {\n signalTree(child, pid, 'SIGKILL');\n // Settle only now: the captured output is complete enough to log, and\n // the call never hangs on a compiler that ignores SIGTERM.\n finish(-1);\n }, KILL_GRACE_MS);\n\n // Most compilers die on SIGTERM: settle as soon as the group is empty\n // instead of always waiting out the grace period.\n poll = setInterval(() => {\n if (!isTreeAlive(child, pid)) finish(-1);\n }, KILL_POLL_MS);\n poll.unref();\n }, timeoutMs);\n\n child.stdout?.setEncoding('utf8');\n child.stderr?.setEncoding('utf8');\n child.stdout?.on('data', (chunk: string) => {\n output = tail(output + chunk);\n });\n child.stderr?.on('data', (chunk: string) => {\n output = tail(output + chunk);\n });\n\n child.on('error', (error) => {\n output = `${output}cannot run \\`${compiler}\\`: ${error.message}\\n`;\n finish(-1);\n });\n\n child.on('close', (code) => {\n if (settled) return;\n if (timedOut) {\n // The process is gone; a grandchild that ignored SIGTERM keeps the\n // group alive, and the poll / SIGKILL escalation settles the call.\n if (!isTreeAlive(child, pid)) finish(-1);\n return;\n }\n finish(code ?? -1);\n });\n });\n}\n\n/**\n * True for a Windows batch wrapper (`.cmd`/`.bat`). Windows has no shebang and\n * `CreateProcess` will not start a batch file itself, so it must go through\n * `cmd.exe`; a real `.exe` compiler must not, or it would gain a shell in its\n * process tree.\n */\nfunction isBatchFile(file: string): boolean {\n return process.platform === 'win32' && /\\.(?:cmd|bat)$/i.test(file);\n}\n\n/** True while the compiler — on POSIX, its whole process group — still exists. */\nfunction isTreeAlive(child: ChildProcess, pid: number | undefined): boolean {\n if (process.platform === 'win32' || pid === undefined) {\n return child.exitCode === null && child.signalCode === null;\n }\n try {\n process.kill(-pid, 0);\n return true;\n } catch {\n return false;\n }\n}\n\n/** Signal the compiler's process group, falling back to the child itself. */\nfunction signalTree(child: ChildProcess, pid: number | undefined, signal: NodeJS.Signals): void {\n try {\n // `detached` made the child a group leader on POSIX, so -pid is its tree;\n // Windows has no process groups, and child.kill is all there is.\n if (process.platform === 'win32' || pid === undefined) child.kill(signal);\n else process.kill(-pid, signal);\n } catch {\n // Already gone, or the group was never created: nothing left to signal.\n }\n}\n\n/** Keep the end of captured output: that is where the failure is reported. */\nfunction tail(text: string): string {\n return text.length > MAX_OUTPUT ? text.slice(-MAX_OUTPUT) : text;\n}\n\n/** The log body: the command that ran, then everything it printed. */\nfunction logText(compiler: string, args: string[], output: string): string {\n const command = [compiler, ...args].map(quoteArg).join(' ');\n return `$ ${command}\\n${output}`;\n}\n\n/** Quote one argument for display only; this text is never executed. */\nfunction quoteArg(arg: string): string {\n return /^[\\w./-]+$/.test(arg) ? arg : JSON.stringify(arg);\n}\n\n/**\n * Refuse an output whose first four bytes are not the `REDS` magic — a\n * compiler that silently wrote something else (or nothing) must not be\n * published as a cache the server would load.\n */\nasync function verifyMagic(file: string): Promise<void> {\n let magic: string;\n try {\n const handle = await open(file, 'r');\n try {\n const head = Buffer.alloc(MAGIC.length);\n const { bytesRead } = await handle.read(head, 0, head.length, 0);\n magic = head.subarray(0, bytesRead).toString('latin1');\n } finally {\n await handle.close();\n }\n } catch (error) {\n throw new BuilderError(\n 'redscripts.output',\n `\\`redscript-cli\\` reported success but \\`${file}\\` cannot be read: ${errorMessage(error)}`,\n );\n }\n\n if (magic !== MAGIC) {\n throw new BuilderError(\n 'redscripts.output',\n `\\`redscript-cli\\` reported success but wrote \\`${file}\\` with magic ` +\n `${JSON.stringify(magic)} instead of \\`${MAGIC}\\`; the compiler output is not a ` +\n 'redscripts cache',\n );\n }\n}\n\n/** Write the resource manifest that lists the compiled cache. */\nasync function writeManifest(outputDir: string): Promise<void> {\n await writeFile(\n join(outputDir, MANIFEST_FILENAME),\n `file = [\"./${REDSCRIPTS_FILENAME}\"]\\nhotreload = false\\n`,\n );\n}\n\n/** True when `path` exists; only `ENOENT` means it does not. */\nasync function exists(path: string): Promise<boolean> {\n try {\n await stat(path);\n return true;\n } catch (error) {\n if (isErrno(error, 'ENOENT')) return false;\n throw new BuilderError(\n 'redscripts.read',\n `cannot inspect the output directory \\`${path}\\`: ${errorMessage(error)}`,\n );\n }\n}\n\nfunction isErrno(error: unknown, code: string): boolean {\n return typeof error === 'object' && error !== null && (error as { code?: unknown }).code === code;\n}\n\nfunction errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n","/**\n * Pinned compiler artifacts — internal to the package.\n *\n * The digest pin is the security boundary for the downloaded binary, so this\n * module is deliberately not re-exported from the package entry point:\n * `resolveCompiler` is the only public way to reach it. Keeping the table in\n * its own module also leaves exactly one seam for the tests, which point the\n * entry at a binary they generate in-flight instead of committing one.\n */\n\n/** Platforms with a pinned compiler binary. Other values are an error. */\nexport type CompilerPlatform = 'win' | 'linux';\n\n/** One published compiler binary: its release asset name and pinned digest. */\nexport interface CompilerArtifact {\n /** Asset name under the `v<version>` release tag. */\n file: string;\n /** sha256 of the published bytes, lowercase hex. */\n sha256: string;\n}\n\n/**\n * Pinned compiler artifacts by version and platform.\n *\n * `0.5.31` Linux is a from-source build\n * (`cargo build --release -p redscript-cli` at tag `v0.5.31`, commit\n * `e419382`), published as a toolchain release asset; `0.5.31` Windows is the\n * upstream `redscript-cli.exe`. Both digests are the sha256 of the artifact\n * bytes as published.\n */\nexport const COMPILERS: Record<string, Partial<Record<CompilerPlatform, CompilerArtifact>>> = {\n '0.5.31': {\n win: {\n file: 'redscript-cli.exe',\n sha256: 'cdcbed2e0c943322bbcbbac4a9c62ef29adc5620e4b0934f0d2a31a8282b5b62',\n },\n linux: {\n file: 'redscript-cli-linux-x64',\n sha256: 'abe7848233eb1701f92355813ffd00c11032b149ab70d94d29befe67d616f07a',\n },\n },\n};\n\n/** Upstream releases, which ship the Windows binary. */\nexport const UPSTREAM_RELEASE_BASE = 'https://github.com/jac3km4/redscript/releases/download';\n\n/** Toolchain releases, which carry the from-source Linux build. */\nexport const TOOLCHAIN_RELEASE_BASE =\n 'https://github.com/cybermp-community/resource-toolchain/releases/download';\n\n/**\n * Tag prefix for a compiler release in this repository.\n *\n * The package releases tag `v<version>` with their own numbering, so the\n * compiler artifacts live behind `redscript-v<upstream version>` and a package\n * release can never shadow them.\n */\nexport const TOOLCHAIN_TAG_PREFIX = 'redscript-v';\n","/**\n * Compiler resolution: which `redscript-cli` binary to run, and where it caches.\n *\n * `0.5.31` reproduces the CyberMP core baseline byte-for-byte, while `1.0.2`\n * cannot read the shipped cache at all (it changed the pool format).\n * Upstream publishes a Windows `redscript-cli.exe` but no Linux x86_64 binary,\n * so Linux uses the same build published as a toolchain release artifact.\n *\n * `resolveCompiler` returns a path under\n * `<workDir>/redscript-cli/<version>/<platform>/redscript-cli[.exe]`, the\n * location the whole build shares, and downloads the artifact at most once.\n * The download is streamed into a temporary file in that same directory,\n * hashed on the way, checked against the pinned table, made executable on\n * POSIX, and only then renamed into place — a failed or tampered download\n * never leaves a binary behind that a later build would trust.\n *\n * A cached binary is re-hashed on every reuse. If the file on disk no longer\n * matches the pin, that is `compiler.integrity` naming the cache path rather\n * than a silent re-download: a substituted or corrupted compiler is exactly\n * what the user needs to see, and a silent repair would hide it.\n *\n * The download has a hard timeout, so a hung mirror fails the build instead of\n * blocking it forever.\n *\n * `downloadBase` replaces the release base URL (mirrors, offline caches, the\n * local server in tests); the asset path `<base>/v<version>/<file>` is\n * unchanged. `CYBERMP_REDSCRIPT_COMPILER` short-circuits everything and is\n * returned as-is, so a locally built compiler needs no download and no entry\n * in the table.\n *\n * Errors: `compiler.unsupported-platform` (no pinned binary for the platform),\n * `compiler.unsupported-version` (no pinned binary for the version),\n * `compiler.download` (transport, timeout, HTTP status, or writing the cache),\n * `compiler.integrity` (the bytes do not match the pinned sha256).\n */\nimport { createHash, randomBytes } from 'node:crypto';\nimport { createReadStream, createWriteStream, existsSync } from 'node:fs';\nimport { chmod, mkdir, rename, rm } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { Readable, Transform } from 'node:stream';\nimport { pipeline } from 'node:stream/promises';\nimport { BuilderError } from '../errors.js';\nimport {\n type CompilerArtifact,\n type CompilerPlatform,\n COMPILERS,\n TOOLCHAIN_RELEASE_BASE,\n TOOLCHAIN_TAG_PREFIX,\n UPSTREAM_RELEASE_BASE,\n} from './compilers.js';\n\nexport type { CompilerPlatform } from './compilers.js';\n\n/** How long a compiler download may take before the build gives up. */\nconst DOWNLOAD_TIMEOUT_MS = 30_000;\n\n/** The escape hatch every failure message names. */\nconst OVERRIDE_HINT = 'set CYBERMP_REDSCRIPT_COMPILER to use a local redscript-cli binary';\n\n/** Options for {@link resolveCompiler}. */\nexport interface CompilerOptions {\n /** Build work directory; the compiler caches under `<workDir>/redscript-cli`. */\n workDir: string;\n /** Pinned compiler version, e.g. `0.5.31`. */\n version: string;\n /** Platform the compiler runs on. */\n platform: CompilerPlatform;\n /** Release base URL override, e.g. a local HTTP server in tests. */\n downloadBase?: string;\n}\n\n/**\n * Return the path of the pinned compiler for `version`/`platform`, downloading\n * and verifying it into the cache on first use.\n *\n * `CYBERMP_REDSCRIPT_COMPILER` wins over everything: it is returned verbatim\n * without touching the filesystem or the network, which is also how a locally\n * built compiler is used.\n */\nexport async function resolveCompiler(opts: CompilerOptions): Promise<string> {\n const override = process.env.CYBERMP_REDSCRIPT_COMPILER;\n if (override !== undefined && override !== '') return override;\n\n const platform = requirePlatform(opts.platform);\n const artifact = requireArtifact(opts.version, platform);\n\n const file = platform === 'win' ? 'redscript-cli.exe' : 'redscript-cli';\n const dir = join(opts.workDir, 'redscript-cli', opts.version, platform);\n const cached = join(dir, file);\n if (existsSync(cached)) {\n await verifyCached(cached, artifact.sha256);\n return cached;\n }\n\n await mkdir(dir, { recursive: true });\n\n const temporary = join(dir, `.${file}.${randomBytes(6).toString('hex')}.tmp`);\n try {\n const digest = await download(assetUrl(opts, platform, artifact), temporary, platform);\n if (digest !== artifact.sha256.toLowerCase()) {\n throw new BuilderError(\n 'compiler.integrity',\n `the redscript compiler ${opts.version} for ${platform} has sha256 ${digest}, ` +\n `but ${artifact.sha256} is pinned; refusing to cache it — the ${platform} build ` +\n `may not be published yet or may have been replaced, so ${OVERRIDE_HINT}`,\n );\n }\n if (process.platform !== 'win32') await chmod(temporary, 0o755);\n await install(temporary, cached);\n } catch (error) {\n await rm(temporary, { force: true }).catch(() => undefined);\n throw error;\n }\n\n return cached;\n}\n\n/** The platform, or `compiler.unsupported-platform` — never a guess. */\nfunction requirePlatform(value: string): CompilerPlatform {\n if (value === 'win' || value === 'linux') return value;\n throw new BuilderError(\n 'compiler.unsupported-platform',\n `${JSON.stringify(value)} has no pinned redscript compiler; ` +\n 'supported platforms are win and linux. Set CYBERMP_REDSCRIPT_COMPILER to use a local binary',\n );\n}\n\n/**\n * The pinned artifact for `version`/`platform`, or\n * `compiler.unsupported-version`.\n *\n * The version doubles as a cache directory name, so it must be a plain\n * identifier: a value with a separator could point the cache outside\n * `<workDir>`.\n */\nfunction requireArtifact(version: string, platform: CompilerPlatform): CompilerArtifact {\n const artifact = /^[0-9A-Za-z][0-9A-Za-z._-]*$/.test(version)\n ? COMPILERS[version]?.[platform]\n : undefined;\n if (artifact === undefined) {\n throw new BuilderError(\n 'compiler.unsupported-version',\n `no redscript compiler is pinned for version \\`${version}\\` on ${platform} ` +\n `(pinned: ${Object.keys(COMPILERS).join(', ')}); ` +\n 'set CYBERMP_REDSCRIPT_COMPILER to use a local binary',\n );\n }\n return artifact;\n}\n\n/**\n * `<base>/<tag>/<file>`: the upstream release for Windows, this repository's\n * `redscript-v<version>` release for Linux. `downloadBase` only replaces the\n * base, so a test can serve the same layout from a local directory.\n */\nfunction assetUrl(\n opts: CompilerOptions,\n platform: CompilerPlatform,\n artifact: CompilerArtifact,\n): string {\n const base =\n opts.downloadBase ?? (platform === 'win' ? UPSTREAM_RELEASE_BASE : TOOLCHAIN_RELEASE_BASE);\n const tag = platform === 'win' ? `v${opts.version}` : `${TOOLCHAIN_TAG_PREFIX}${opts.version}`;\n return `${base.replace(/\\/+$/, '')}/${tag}/${artifact.file}`;\n}\n\n/**\n * Check a binary already in the cache against the pin. The message names the\n * cached path and never re-downloads: a mismatch on disk means something\n * replaced or corrupted the file, and the user has to decide to remove it.\n */\nasync function verifyCached(cached: string, pinned: string): Promise<void> {\n let digest: string;\n try {\n digest = await fileDigest(cached);\n } catch (error) {\n throw new BuilderError(\n 'compiler.download',\n `cannot read the cached redscript compiler at \\`${cached}\\`: ${errorMessage(error)}`,\n );\n }\n if (digest !== pinned.toLowerCase()) {\n throw new BuilderError(\n 'compiler.integrity',\n `the cached redscript compiler at \\`${cached}\\` has sha256 ${digest}, ` +\n `but ${pinned} is pinned; delete it to download it again, or ${OVERRIDE_HINT}`,\n );\n }\n}\n\n/** sha256 of a file, read in chunks so a large binary is never buffered whole. */\nasync function fileDigest(file: string): Promise<string> {\n const hash = createHash('sha256');\n for await (const chunk of createReadStream(file)) {\n hash.update(chunk as Buffer);\n }\n return hash.digest('hex');\n}\n\n/**\n * Stream `url` into `file`, hashing the bytes on the way. The digest is\n * returned rather than read back, so a truncated response cannot be recorded\n * as complete.\n *\n * The request carries a timeout: a mirror that accepts the connection and then\n * stalls must fail the build, not hang it.\n */\nasync function download(\n url: string,\n file: string,\n platform: CompilerPlatform,\n): Promise<string> {\n let response: Response;\n try {\n response = await fetch(url, {\n headers: { accept: 'application/octet-stream', 'user-agent': 'cybermp-resource-builder' },\n signal: AbortSignal.timeout(DOWNLOAD_TIMEOUT_MS),\n });\n } catch (error) {\n if (isTimeout(error)) {\n throw new BuilderError(\n 'compiler.download',\n `the download of the redscript compiler from \\`${url}\\` timed out after ` +\n `${DOWNLOAD_TIMEOUT_MS / 1000}s; check the mirror, or ${OVERRIDE_HINT}`,\n );\n }\n throw new BuilderError(\n 'compiler.download',\n `cannot download the redscript compiler from \\`${url}\\`: ${errorMessage(error)}`,\n );\n }\n if (!response.ok) {\n const hint =\n response.status === 404\n ? `; the ${platform} build may not be published yet, or ${OVERRIDE_HINT}`\n : '';\n throw new BuilderError(\n 'compiler.download',\n `cannot download the redscript compiler from \\`${url}\\` (status ${response.status})${hint}`,\n );\n }\n\n const body = response.body;\n if (body === null) {\n throw new BuilderError(\n 'compiler.download',\n `the download of the redscript compiler from \\`${url}\\` returned no body`,\n );\n }\n\n const hash = createHash('sha256');\n try {\n await pipeline(\n Readable.fromWeb(body as unknown as Parameters<typeof Readable.fromWeb>[0]),\n new Transform({\n transform(chunk, _encoding, callback) {\n hash.update(chunk as Buffer);\n callback(null, chunk);\n },\n }),\n createWriteStream(file, { flags: 'wx', mode: 0o600 }),\n );\n } catch (error) {\n throw new BuilderError(\n 'compiler.download',\n `cannot save the redscript compiler from \\`${url}\\`: ${errorMessage(error)}`,\n );\n }\n return hash.digest('hex');\n}\n\n/** True when `fetch` was aborted by its timeout rather than failing to connect. */\nfunction isTimeout(error: unknown): boolean {\n if (typeof error !== 'object' || error === null) return false;\n const { name } = error as { name?: unknown };\n return name === 'TimeoutError' || name === 'AbortError';\n}\n\n/**\n * Rename the verified temporary file onto the cache path. Both live in the\n * cache directory, so this is an atomic rename on one filesystem.\n */\nasync function install(temporary: string, cached: string): Promise<void> {\n try {\n await rename(temporary, cached);\n } catch (error) {\n throw new BuilderError(\n 'compiler.download',\n `cannot install the redscript compiler at \\`${cached}\\`: ${errorMessage(error)}`,\n );\n }\n}\n\nfunction errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n","/**\n * `server.toml` — the resource list editor (spec §9.5).\n *\n * `server.toml` is hand-edited and decides what the server loads, so the\n * builder never re-serializes it: it locates the top-level `resources` array in\n * the text, remembers its exact character span and replaces only that span with\n * a freshly formatted multiline array. Comments, other keys, tables and line\n * endings outside the span survive byte-for-byte. A missing key is inserted\n * before the first table, where it stays top-level.\n *\n * The array is located with a small TOML-aware scanner (strings and comments\n * are skipped, so a `]` inside a quoted name or a comment does not end it) and\n * validated by parsing only the span with `smol-toml`; the rest of the file is\n * never parsed, so an unrelated table the builder does not understand cannot\n * block the edit.\n */\nimport { parse } from 'smol-toml';\nimport { BuilderError } from './errors.js';\n\n/** A parsed `resources` list together with the span of its array in the text. */\nexport interface ResourceList {\n /** Resource names, in load order. */\n names: string[];\n /** Offset of the opening `[` of the array. */\n start: number;\n /** Offset just past the closing `]` of the array. */\n end: number;\n}\n\ninterface Span {\n start: number;\n end: number;\n}\n\ninterface TopLevelScan {\n /** The `resources` array, when the key is present before the first table. */\n array?: Span;\n /** Offset of the line that opens the first `[table]`, when there is one. */\n firstTable?: number;\n}\n\nconst KEY = 'resources';\n\n/**\n * Read the top-level `resources` array of `server.toml`.\n *\n * Throws `serverToml.missing-resources` when the key is absent (or only\n * appears after the first table, where TOML would not read it as top-level),\n * `serverToml.invalid` when it is not an array of strings, and\n * `serverToml.parse` when the array itself is not valid TOML.\n */\nexport function readResourceList(text: string): ResourceList {\n const { array } = scanTopLevel(text);\n if (array === undefined) {\n throw new BuilderError(\n 'serverToml.missing-resources',\n `missing top-level \\`${KEY}\\` key in server.toml`,\n );\n }\n\n return { names: parseNames(text, array), start: array.start, end: array.end };\n}\n\n/**\n * Replace the top-level `resources` array with `names`.\n *\n * Only the array span changes; everything else in the file is returned\n * untouched. With no key, the list is inserted before the first table (or\n * appended when the file has none), using the file's own line ending.\n */\nexport function writeResourceList(text: string, names: string[]): string {\n const { array, firstTable } = scanTopLevel(text);\n const eol = lineEnding(text);\n\n if (array === undefined) {\n const block = `${KEY} = ${formatArray(names, eol, '')}${eol}`;\n if (firstTable === undefined) return appendBlock(text, block, eol);\n\n const at = insertionOffset(text, firstTable);\n return `${text.slice(0, at)}${block}${eol}${text.slice(at)}`;\n }\n\n // Validate the value being replaced, so a hand-broken array is reported with\n // the same error it would raise when read instead of being silently dropped.\n parseNames(text, array);\n\n const indent = lineIndent(text, array.start);\n return text.slice(0, array.start) + formatArray(names, eol, indent) + text.slice(array.end);\n}\n\n/**\n * Walk the top level of the document once, stopping at the first table header.\n *\n * The scanner understands comments and all four TOML string forms, so\n * `resources =` inside a comment or a multiline string is not mistaken for the\n * key. Both key spellings are accepted — `resources` and a quoted\n * `\"resources\"`/`'resources'` — because TOML treats them as the same key; the\n * key text is never rewritten, only the array span is. Brace depth ignores keys\n * inside a multiline inline table (`x = { ... }`), and the scan stops at the\n * first `[table]`, where TOML stops reading top-level keys.\n */\nfunction scanTopLevel(text: string): TopLevelScan {\n let lineStart = 0;\n let atLineStart = true;\n let braceDepth = 0;\n\n for (let i = 0; i < text.length; ) {\n const ch = text.charAt(i);\n\n if (ch === '\\n') {\n i += 1;\n lineStart = i;\n atLineStart = true;\n continue;\n }\n if (ch === ' ' || ch === '\\t' || ch === '\\r') {\n i += 1;\n continue;\n }\n if (ch === '#') {\n const newline = text.indexOf('\\n', i);\n if (newline < 0) break;\n i = newline;\n continue;\n }\n if (ch === '{') {\n braceDepth += 1;\n i += 1;\n atLineStart = false;\n continue;\n }\n if (ch === '}') {\n if (braceDepth > 0) braceDepth -= 1;\n i += 1;\n atLineStart = false;\n continue;\n }\n if (braceDepth === 0 && atLineStart && ch === '[') return { firstTable: lineStart };\n if (ch === '\"' || ch === \"'\") {\n // A quoted key is only a key at the start of a top-level line; anywhere\n // else the string is part of a value and is skipped whole.\n if (braceDepth === 0 && atLineStart) {\n const quoted = readQuotedKey(text, i);\n if (quoted !== undefined && quoted.key === KEY) {\n const equals = skipBlanks(text, quoted.end);\n if (text.charAt(equals) === '=') return { array: readArrayValue(text, equals) };\n }\n }\n i = skipString(text, i);\n atLineStart = false;\n continue;\n }\n if (braceDepth === 0 && atLineStart && isBareKeyChar(ch)) {\n let keyEnd = i;\n while (keyEnd < text.length && isBareKeyChar(text.charAt(keyEnd))) keyEnd += 1;\n\n const equals = skipBlanks(text, keyEnd);\n if (text.slice(i, keyEnd) === KEY && text.charAt(equals) === '=') {\n return { array: readArrayValue(text, equals) };\n }\n\n i = keyEnd;\n atLineStart = false;\n continue;\n }\n\n atLineStart = false;\n i += 1;\n }\n\n return {};\n}\n\nfunction isBareKeyChar(ch: string): boolean {\n return /[A-Za-z0-9_-]/.test(ch);\n}\n\n/**\n * Read a single-line quoted key at `start`, if there is one.\n *\n * Returns the raw inner text (no unescaping) and the offset just past the\n * closing quote; `undefined` for a multiline string, an unterminated quote or a\n * quoted value. A quoted key is only meaningful at the start of a top-level\n * line, which is where the scanner calls this.\n */\nfunction readQuotedKey(text: string, start: number): { key: string; end: number } | undefined {\n const quote = text.charAt(start);\n if (text.startsWith(quote.repeat(3), start)) return undefined;\n\n let key = '';\n for (let i = start + 1; i < text.length; i += 1) {\n const ch = text.charAt(i);\n if (ch === '\\n') return undefined;\n if (ch === '\\\\' && quote === '\"') {\n key += ch + text.charAt(i + 1);\n i += 1;\n continue;\n }\n if (ch === quote) return { key, end: i + 1 };\n key += ch;\n }\n\n return undefined;\n}\n\nfunction skipBlanks(text: string, start: number): number {\n let i = start;\n while (text.charAt(i) === ' ' || text.charAt(i) === '\\t') i += 1;\n return i;\n}\n\n/** Span of the array that follows the `=` at `equals`; not an array is invalid. */\nfunction readArrayValue(text: string, equals: number): Span {\n const start = skipTrivia(text, equals + 1);\n if (text.charAt(start) !== '[') {\n throw new BuilderError(\n 'serverToml.invalid',\n `\\`${KEY}\\` must be an array of strings in server.toml`,\n );\n }\n\n return { start, end: findArrayEnd(text, start) };\n}\n\n/**\n * Offset just past the `]` that closes the array opened at `start`.\n *\n * Bracket depth is tracked outside strings and comments, so names such as\n * `\"a]b\"` and comments such as `# see [docs]` cannot terminate the array early.\n */\nfunction findArrayEnd(text: string, start: number): number {\n let depth = 0;\n\n for (let i = start; i < text.length; ) {\n const ch = text.charAt(i);\n\n if (ch === '\"' || ch === \"'\") {\n i = skipString(text, i);\n continue;\n }\n if (ch === '#') {\n const newline = text.indexOf('\\n', i);\n if (newline < 0) break;\n i = newline;\n continue;\n }\n if (ch === '[') {\n depth += 1;\n i += 1;\n continue;\n }\n if (ch === ']') {\n depth -= 1;\n i += 1;\n if (depth === 0) return i;\n continue;\n }\n i += 1;\n }\n\n throw new BuilderError(\n 'serverToml.parse',\n `unterminated \\`${KEY}\\` array in server.toml`,\n );\n}\n\n/** Offset just past the string that opens at `start`; handles `\"\"\"`/`'''`. */\nfunction skipString(text: string, start: number): number {\n const quote = text.charAt(start);\n const triple = text.startsWith(quote.repeat(3), start);\n const delimiter = triple ? quote.repeat(3) : quote;\n\n for (let i = start + delimiter.length; i < text.length; i += 1) {\n const ch = text.charAt(i);\n if (ch === '\\\\' && quote === '\"') {\n i += 1;\n continue;\n }\n if (text.startsWith(delimiter, i)) return i + delimiter.length;\n // An unterminated single-line string ends at the newline; the caller keeps\n // scanning from there and the TOML parse reports the real error.\n if (!triple && ch === '\\n') return i;\n }\n\n return text.length;\n}\n\n/** Skip whitespace and comments between a key's `=` and its value. */\nfunction skipTrivia(text: string, start: number): number {\n let i = start;\n\n while (i < text.length) {\n const ch = text.charAt(i);\n if (ch === ' ' || ch === '\\t' || ch === '\\r' || ch === '\\n') {\n i += 1;\n continue;\n }\n if (ch === '#') {\n const newline = text.indexOf('\\n', i);\n if (newline < 0) return text.length;\n i = newline;\n continue;\n }\n break;\n }\n\n return i;\n}\n\n/** Parse and validate the array slice in a synthetic single-key document. */\nfunction parseNames(text: string, span: Span): string[] {\n const source = `${KEY} = ${text.slice(span.start, span.end)}`;\n\n let value: unknown;\n try {\n value = (parse(source) as Record<string, unknown>)[KEY];\n } catch (error) {\n throw new BuilderError(\n 'serverToml.parse',\n `invalid \\`${KEY}\\` array in server.toml: ${errorMessage(error)}`,\n );\n }\n\n if (!Array.isArray(value)) {\n throw new BuilderError(\n 'serverToml.invalid',\n `\\`${KEY}\\` must be an array of strings in server.toml`,\n );\n }\n\n return value.map((entry, index) => {\n if (typeof entry !== 'string') {\n throw new BuilderError(\n 'serverToml.invalid',\n `\\`${KEY}[${index}]\\` must be a string, got ${describe(entry)}`,\n );\n }\n return entry;\n });\n}\n\n/** The file's line ending; CRLF wins when the file uses it anywhere. */\nfunction lineEnding(text: string): string {\n return text.includes('\\r\\n') ? '\\r\\n' : '\\n';\n}\n\nfunction formatArray(names: readonly string[], eol: string, indent: string): string {\n if (names.length === 0) return '[]';\n\n const itemIndent = `${indent} `;\n const items = names.map((name) => `${itemIndent}${quote(name)},`);\n return `[${eol}${items.join(eol)}${eol}${indent}]`;\n}\n\n/** Space between the start of the key's line and the array. */\nfunction lineIndent(text: string, offset: number): string {\n const line = text.slice(lineStartOf(text, offset), offset);\n const match = /^[ \\t]*/.exec(line);\n return match === null ? '' : match[0];\n}\n\nfunction lineStartOf(text: string, offset: number): number {\n return text.lastIndexOf('\\n', offset - 1) + 1;\n}\n\n/**\n * Where a missing key is inserted: the first table's line, moved up over the\n * comment lines directly above it so a comment stays attached to its table.\n */\nfunction insertionOffset(text: string, tableStart: number): number {\n let offset = lineStartOf(text, tableStart);\n\n while (offset > 0) {\n const previous = lineStartOf(text, offset - 1);\n const line = text.slice(previous, offset).replace(/\\r?\\n$/, '');\n if (!line.trimStart().startsWith('#')) break;\n offset = previous;\n }\n\n return offset;\n}\n\n/** Append the block, keeping one blank line between it and the existing text. */\nfunction appendBlock(text: string, block: string, eol: string): string {\n if (text === '') return block;\n if (text.endsWith(eol + eol)) return text + block;\n if (text.endsWith('\\n') || text.endsWith('\\r')) return text + eol + block;\n return text + eol + eol + block;\n}\n\nconst ESCAPES: Record<string, string> = {\n '\\\\': '\\\\\\\\',\n '\"': '\\\\\"',\n '\\b': '\\\\b',\n '\\t': '\\\\t',\n '\\n': '\\\\n',\n '\\f': '\\\\f',\n '\\r': '\\\\r',\n};\n\n/** Quote a name as a TOML basic string. */\nfunction quote(value: string): string {\n let out = '\"';\n\n for (const ch of value) {\n const escaped = ESCAPES[ch];\n if (escaped !== undefined) {\n out += escaped;\n continue;\n }\n\n const code = ch.codePointAt(0) ?? 0;\n out += code < 0x20 || code === 0x7f ? `\\\\u${code.toString(16).padStart(4, '0')}` : ch;\n }\n\n return `${out}\"`;\n}\n\nfunction describe(value: unknown): string {\n if (value === null) return 'null';\n if (Array.isArray(value)) return 'an array';\n if (typeof value === 'string') return `a string (${JSON.stringify(value)})`;\n return `a ${typeof value}`;\n}\n\nfunction errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n","/**\n * Build of a local (source) addon: bundle its TypeScript entries with esbuild\n * into the resources layout, then produce the browser directory.\n *\n * The defaults mirror the addon template: `client/src/index.ts` becomes\n * `<out>/<name>/client.js` (`iife`, browser platform, `esnext`) and\n * `server/src/index.ts` becomes `<out>/<name>/server.js` (`cjs`, node platform,\n * `node22`), both bundled without a source map. Every field — `entry`,\n * `format`, `platform`, `target`, `sourcemap` — is overridable per entry from\n * `cybermp.build` in the addon's `package.json`, and `define` applies to both.\n *\n * A missing entry is not an error: an addon may be client-only or\n * server-only, so the convention is skipped. Only the files the build produces\n * are written; `resource.toml` and the `file` globs arrive through\n * materialization, and `browser/` through {@link runBrowserBuild}.\n *\n * Options: `noBrowser` skips only the browser build — the client and server\n * bundles still run, so a server-only iteration does not wait on a front-end\n * toolchain.\n *\n * Errors: a malformed `cybermp.build` block is `build.bad-config` (field shapes\n * are checked here rather than when the package is read, so a typo is a build\n * failure with a precise path), an entry that leaves the addon directory is\n * `build.entry`, a manifest whose `shared_script` the build cannot produce is\n * `build.shared-unsupported`, and esbuild failures are `build.client-failed` /\n * `build.server-failed`. Reading the marker keeps the addon package's own\n * `package.*` codes. A prebuilt addon (`build: false`) has nothing to build and\n * is copied like an installed one.\n */\nimport { readFile, stat } from 'node:fs/promises';\nimport { isAbsolute, join, relative, resolve, sep } from 'node:path';\nimport {\n type BrowserBuildConfig,\n hasUnsupportedSharedScript,\n parseManifest,\n readAddonPackage,\n SHARED_SCRIPT_UNSUPPORTED,\n} from '@cybermp-community/addon';\nimport { build } from 'esbuild';\nimport { MANIFEST_FILENAME } from '../addons/materialize.js';\nimport type { ResolvedAddon } from '../addons/types.js';\nimport type { ProjectConfig } from '../config.js';\nimport { BuilderError } from '../errors.js';\nimport { runBrowserBuild } from './browser.js';\n\ntype BundleFormat = 'iife' | 'cjs' | 'esm';\ntype BundlePlatform = 'browser' | 'node' | 'neutral';\n\ninterface BundleOptions {\n entry: string;\n format: BundleFormat;\n platform: BundlePlatform;\n target: string;\n sourcemap: boolean;\n}\n\nconst FORMATS: readonly BundleFormat[] = ['iife', 'cjs', 'esm'];\nconst PLATFORMS: readonly BundlePlatform[] = ['browser', 'node', 'neutral'];\n\nconst CLIENT_DEFAULTS: BundleOptions = {\n entry: 'client/src/index.ts',\n format: 'iife',\n platform: 'browser',\n target: 'esnext',\n sourcemap: false,\n};\n\nconst SERVER_DEFAULTS: BundleOptions = {\n entry: 'server/src/index.ts',\n format: 'cjs',\n platform: 'node',\n target: 'node22',\n sourcemap: false,\n};\n\nconst BUILD_PATH = 'cybermp.build';\nconst BUILD_KEYS: ReadonlySet<string> = new Set(['client', 'server', 'browser', 'define']);\nconst BUNDLE_KEYS: ReadonlySet<string> = new Set([\n 'entry',\n 'format',\n 'platform',\n 'target',\n 'sourcemap',\n]);\nconst BROWSER_KEYS: ReadonlySet<string> = new Set(['build', 'dev', 'dist', 'timeout']);\n\n/** Options for {@link buildLocalAddon}. */\nexport interface BuildLocalOptions {\n /** Skip only the browser (CEF) build; client and server still bundle. */\n noBrowser?: boolean;\n}\n\n/**\n * Build one local addon into `<outDir>/<addon.name>`.\n *\n * `outDir` is resolved against `config.root` when relative, so callers may pass\n * either the configured resources directory or a path produced by joining it.\n * The resource name is used as a single directory name; uniqueness is already\n * enforced by ordering before the build runs.\n */\nexport async function buildLocalAddon(\n addon: ResolvedAddon,\n outDir: string,\n config: ProjectConfig,\n options: BuildLocalOptions = {},\n): Promise<void> {\n if (addon.kind === 'prebuilt') return;\n\n const addonPackage = readAddonPackage(addon.dir);\n if (addonPackage.build === false) return;\n\n await assertSourceManifestSupported(addon);\n\n const buildConfig = table(addonPackage.build, BUILD_PATH);\n rejectUnknownKeys(buildConfig, BUILD_KEYS, BUILD_PATH);\n\n const define = readDefine(buildConfig['define']);\n const resourceDir = join(resolve(config.root, outDir), addon.name);\n\n await bundle(addon, buildConfig['client'], 'client', CLIENT_DEFAULTS, define, resourceDir);\n await bundle(addon, buildConfig['server'], 'server', SERVER_DEFAULTS, define, resourceDir);\n if (options.noBrowser !== true) {\n await runBrowserBuild(addon.dir, resourceDir, readBrowser(buildConfig['browser']));\n }\n}\n\n/**\n * Refuse a source addon whose manifest declares `shared_script`.\n *\n * The build writes `client.js` and `server.js` only, so the materialized\n * manifest would carry a line no file ever satisfies. The validator runs the\n * same check for `kind: 'source'`; running it here as well means a plain\n * `cybermp build` refuses the manifest instead of shipping it. A missing\n * manifest is not this check's business — materialization reports it first.\n *\n * Exported because `buildProject` runs it before the cleanup stage: a manifest\n * the build cannot honour must fail the run before anything is deleted, not\n * halfway through the tree.\n */\nexport async function assertSourceManifestSupported(addon: ResolvedAddon): Promise<void> {\n let text: string;\n try {\n text = await readFile(join(addon.dir, MANIFEST_FILENAME), 'utf8');\n } catch (error) {\n if (isErrno(error, 'ENOENT')) return;\n throw error;\n }\n\n if (hasUnsupportedSharedScript(parseManifest(text))) {\n throw new BuilderError('build.shared-unsupported', SHARED_SCRIPT_UNSUPPORTED);\n }\n}\n\n/** Bundle one entry, if it exists, to `<resourceDir>/<side>.js`. */\nasync function bundle(\n addon: ResolvedAddon,\n value: unknown,\n side: 'client' | 'server',\n defaults: BundleOptions,\n define: Record<string, string>,\n resourceDir: string,\n): Promise<void> {\n const options = readBundle(value, `${BUILD_PATH}.${side}`, defaults);\n const entry = resolve(addon.dir, options.entry);\n\n if (!isInside(addon.dir, entry)) {\n throw new BuilderError(\n 'build.entry',\n `\\`${BUILD_PATH}.${side}.entry\\` must stay inside the addon, ` +\n `got ${JSON.stringify(options.entry)}`,\n );\n }\n if (!(await isFile(entry))) return;\n\n try {\n await build({\n absWorkingDir: addon.dir,\n entryPoints: [entry],\n outfile: join(resourceDir, `${side}.js`),\n bundle: true,\n format: options.format,\n platform: options.platform,\n target: options.target,\n sourcemap: options.sourcemap,\n define,\n logLevel: 'silent',\n });\n } catch (error) {\n throw new BuilderError(\n `build.${side}-failed`,\n `${side} bundle of \\`${addon.name}\\` from \\`${entry}\\` failed: ${message(error)}`,\n );\n }\n}\n\nfunction readBundle(value: unknown, path: string, defaults: BundleOptions): BundleOptions {\n const raw = table(value, path);\n rejectUnknownKeys(raw, BUNDLE_KEYS, path);\n\n return {\n entry: optionalString(raw['entry'], `${path}.entry`) ?? defaults.entry,\n format: optionalOneOf(raw['format'], `${path}.format`, FORMATS) ?? defaults.format,\n platform: optionalOneOf(raw['platform'], `${path}.platform`, PLATFORMS) ?? defaults.platform,\n target: optionalString(raw['target'], `${path}.target`) ?? defaults.target,\n sourcemap: optionalBoolean(raw['sourcemap'], `${path}.sourcemap`) ?? defaults.sourcemap,\n };\n}\n\nfunction readDefine(value: unknown): Record<string, string> {\n if (value === undefined) return {};\n const raw = table(value, `${BUILD_PATH}.define`);\n const define: Record<string, string> = {};\n\n for (const [key, entry] of Object.entries(raw)) {\n if (typeof entry !== 'string') {\n throw badConfig(`${BUILD_PATH}.define.${key}`, 'a string', entry);\n }\n define[key] = entry;\n }\n return define;\n}\n\nfunction readBrowser(value: unknown): BrowserBuildConfig | undefined {\n if (value === undefined) return undefined;\n\n const path = `${BUILD_PATH}.browser`;\n const raw = table(value, path);\n rejectUnknownKeys(raw, BROWSER_KEYS, path);\n\n const browser: BrowserBuildConfig = {};\n const command = optionalString(raw['build'], `${path}.build`);\n if (command !== undefined) browser.build = command;\n const dev = optionalString(raw['dev'], `${path}.dev`);\n if (dev !== undefined) browser.dev = dev;\n const dist = optionalString(raw['dist'], `${path}.dist`);\n if (dist !== undefined) browser.dist = dist;\n const timeout = optionalPositiveInteger(raw['timeout'], `${path}.timeout`);\n if (timeout !== undefined) browser.timeout = timeout;\n return browser;\n}\n\nfunction table(value: unknown, path: string): Record<string, unknown> {\n if (value === undefined) return {};\n if (typeof value !== 'object' || value === null || Array.isArray(value)) {\n throw badConfig(path, 'an object', value);\n }\n return value as Record<string, unknown>;\n}\n\nfunction rejectUnknownKeys(\n table: Record<string, unknown>,\n allowed: ReadonlySet<string>,\n prefix: string,\n): void {\n for (const key of Object.keys(table)) {\n if (allowed.has(key)) continue;\n throw new BuilderError(\n 'build.bad-config',\n `unknown key \\`${prefix}.${key}\\` in \\`package.json\\``,\n );\n }\n}\n\nfunction optionalString(value: unknown, path: string): string | undefined {\n if (value === undefined) return undefined;\n if (typeof value !== 'string') throw badConfig(path, 'a string', value);\n return value;\n}\n\nfunction optionalBoolean(value: unknown, path: string): boolean | undefined {\n if (value === undefined) return undefined;\n if (typeof value !== 'boolean') throw badConfig(path, 'a boolean', value);\n return value;\n}\n\nfunction optionalPositiveInteger(value: unknown, path: string): number | undefined {\n if (value === undefined) return undefined;\n if (typeof value !== 'number' || !Number.isInteger(value) || value <= 0) {\n throw badConfig(path, 'a positive integer of milliseconds', value);\n }\n return value;\n}\n\nfunction optionalOneOf<T extends string>(\n value: unknown,\n path: string,\n allowed: readonly T[],\n): T | undefined {\n if (value === undefined) return undefined;\n if (typeof value !== 'string' || !allowed.includes(value as T)) {\n throw badConfig(path, `one of ${allowed.map((entry) => `\\`${entry}\\``).join(', ')}`, value);\n }\n return value as T;\n}\n\nfunction badConfig(path: string, expected: string, value: unknown): BuilderError {\n return new BuilderError(\n 'build.bad-config',\n `\\`${path}\\` must be ${expected}, got ${describe(value)}`,\n );\n}\n\nfunction describe(value: unknown): string {\n if (value === undefined) return 'undefined';\n if (value === null) return 'null';\n if (Array.isArray(value)) return 'an array';\n if (typeof value === 'object') return 'an object';\n if (typeof value === 'string') return `a string (${JSON.stringify(value)})`;\n return `a ${typeof value}`;\n}\n\n/** A regular file; a missing entry is skipped, an uninspectable one is an error. */\nasync function isFile(path: string): Promise<boolean> {\n try {\n return (await stat(path)).isFile();\n } catch (error) {\n if (isErrno(error, 'ENOENT') || isErrno(error, 'ENOTDIR')) return false;\n throw new BuilderError('build.entry', `cannot inspect \\`${path}\\`: ${message(error)}`);\n }\n}\n\n/** True when `target` is `root` or a descendant of it. */\nfunction isInside(root: string, target: string): boolean {\n const path = relative(root, target);\n return path === '' || (!isAbsolute(path) && path !== '..' && !path.startsWith(`..${sep}`));\n}\n\nfunction isErrno(error: unknown, code: string): boolean {\n return (\n typeof error === 'object' &&\n error !== null &&\n (error as { code?: unknown }).code === code\n );\n}\n\nfunction message(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n","/**\n * The build pipeline (spec §9.3): resolve the project, materialize and build\n * every addon into the resources directory, then rewrite `server.toml` and\n * record the result in `.addons.json`.\n *\n * The stages run in the order the design fixes:\n *\n * 0. state check — npm dependencies and the locked release installations are\n * resolved so a missing or unverifiable one fails early with a `cybermp\n * install` hint;\n * 1. resolution — local, npm and release addons, ordered by `requires`; a\n * `--filter` that names no resolved addon is refused (`build.unknown-filter`),\n * and one that names a resolved-but-disabled addon is refused with the same\n * code and a message that says it is disabled;\n * 2. cleanup — only the directories the ownership registry names are removed;\n * with `--no-browser` a built `browser/` is moved aside first and restored\n * after the build, so a server-only iteration keeps the UI;\n * 3. local builds — `source` addons are bundled with esbuild and their browser\n * directory is produced (or skipped with `noBrowser`);\n * 4. materialization — every addon's `resource.toml` and referenced files are\n * copied into the resources dir; a `source` addon's scripts and `browser/`\n * come from the build, so materialization leaves them alone;\n * 5. builtins — the `hotreload` builtin is not implemented yet (no-op);\n * 6. redscripts — the core baseline is resolved, every addon's `.reds` are\n * compiled into `final_redscripts` (or the configured output name) after the\n * directory is claimed in the ownership registry, and a missing baseline, a\n * disabled-but-present source, a foreign directory and a compile failure all\n * fail the build with their own stable code; a stage that is skipped or\n * disabled gives the directory back instead of leaving a stale copy;\n * 7. `server.toml` — the `resources` array is replaced with `final_redscripts`\n * first (when that stage ran) followed by the ordered addons and then\n * `addons.extraResources`;\n * 8. `.addons.json` — the resolved addons (name, version, source, requires)\n * are written into the work directory.\n */\nimport { existsSync, readdirSync } from 'node:fs';\nimport { chmod, cp, mkdir, readFile, rename, rm, stat, writeFile } from 'node:fs/promises';\nimport { basename, dirname, join, resolve } from 'node:path';\nimport {\n claimOwnedDir,\n cleanOwnedDirs,\n dropOwnedDir,\n materializeAddon,\n REGISTRY_FILENAME,\n} from '../addons/materialize.js';\nimport type { ResolvedAddon } from '../addons/types.js';\nimport type { ProjectConfig } from '../config.js';\nimport { BuilderError } from '../errors.js';\nimport { resolveProject } from '../project.js';\nimport {\n buildRedscripts,\n collectRedscripts,\n type RedscriptSource,\n} from '../redscripts/build.js';\nimport { type CompilerPlatform, resolveCompiler } from '../redscripts/compiler.js';\nimport { writeResourceList } from '../serverToml.js';\nimport { assertSourceManifestSupported, buildLocalAddon } from './local.js';\n\n/** Name of the project's server configuration file, relative to the root. */\nconst SERVERTOML_FILENAME = 'server.toml';\n\n/** Name of the build record written into the work directory. */\nconst ADDONS_JSON_FILENAME = '.addons.json';\n\n/**\n * Core layout under `<workDir>/mp/<platform>/` (spec §9.4, §9.7): the compiled\n * baseline the addons compile against, and the core's own `.reds` sources that\n * `baseline: 'none'` compiles together with them.\n */\nconst CORE_BASELINE_PATH = ['data', 'cybermp_core', 'files', 'final.redscripts'];\nconst CORE_SOURCES_PATH = ['data', 'cybermp_core', 'files', 'src_scripts'];\n\n/** The addon name the core's `.reds` sources are attributed to. */\nconst CORE_ADDON_NAME = 'core';\n\n/** Flags accepted by `buildProject`; only `filter` and `noBrowser` act today. */\nexport interface BuildOptions {\n /** Build only the addon whose resource name matches exactly. */\n filter?: string;\n /** Skip the browser (CEF) build of local addons; an existing `browser/` is kept. */\n noBrowser?: boolean;\n /** Skip the redscripts stage — no compile, no `final_redscripts` in the list. */\n noRedscripts?: boolean;\n}\n\n/** What one build did, for the CLI to print and for callers to inspect. */\nexport interface BuildReport {\n /** Real path of the project root. */\n root: string;\n /**\n * Resource names in load order, exactly as written to `server.toml` — the\n * full resolved list even on a filtered build.\n */\n resources: string[];\n /** The addons this run built or materialized, in load order (a filtered build lists only the selected subset). */\n addons: ResolvedAddon[];\n}\n\n/**\n * Build `root` end to end (spec §9.3) and report what was written.\n *\n * Errors keep the stable `area.reason` codes of the modules they come from:\n * resolution and ordering failures, `materialize.*`, `build.*`, `serverToml.*`\n * and `redscripts.*` all surface unchanged, so a caller can match them the same\n * way it matches any other builder error.\n */\nexport async function buildProject(\n root: string,\n options: BuildOptions = {},\n): Promise<BuildReport> {\n const { config, addons, ordered } = await resolveProject(root);\n\n // A filter that names nothing is a bad invocation, not a build that quietly\n // did nothing: the user asked for one addon and would otherwise read\n // `built 0 resources` as success. Name the known set so a typo is obvious;\n // an addon that is resolved but disabled is a different mistake (the name is\n // right, `addons.disabled` keeps it out of the build) and says so instead.\n if (options.filter !== undefined && !ordered.some((addon) => addon.name === options.filter)) {\n const disabled = addons.some((addon) => addon.name === options.filter);\n throw new BuilderError(\n 'build.unknown-filter',\n disabled\n ? `\\`--filter=${options.filter}\\` names an addon disabled by an ` +\n '`addons.disabled` entry; remove it from that list to build it'\n : `\\`--filter=${options.filter}\\` matches no addon; known resources: ${listNames(ordered)}`,\n );\n }\n\n const selected =\n options.filter === undefined\n ? ordered\n : ordered.filter((addon) => addon.name === options.filter);\n\n // Validate what this run will act on before anything is deleted or written:\n // a settings clash is a project error, not a broken tree to clean up after.\n validateProjectSettings(config, ordered, options);\n\n // A source manifest the build cannot honour — today a `shared_script`, which\n // no bundle produces — must fail before the cleanup stage, not after the\n // dangling line has been materialized.\n for (const addon of selected) {\n if (addon.kind === 'source') await assertSourceManifestSupported(addon);\n }\n\n const registryPath = join(config.workDir, REGISTRY_FILENAME);\n\n // `--no-browser` skips the build of the browser directory, but the resources\n // dir is cleaned first and materialization never writes one for a source\n // addon. Move any built `browser/` aside before the cleanup and put it back\n // afterwards, so a server-only iteration keeps the UI the last full build\n // produced (resource.toml and a local cef_url still point at it).\n //\n // The move itself happens inside the `try`, with the same `finally` that\n // cleans up: a failure part-way through the phase (the second of two moves,\n // say) must put back the directories already moved, or the resources dir\n // stays missing a UI and the backup is orphaned in the work dir.\n const preserved: PreservedBrowsers | undefined =\n options.noBrowser === true\n ? { root: join(config.workDir, `.browser-preserve-${process.pid}`), entries: [] }\n : undefined;\n\n try {\n if (preserved !== undefined) await preserveBrowserDirs(selected, config, preserved);\n\n // Stage 2: remove only the directories the builder owns — and, on a filtered\n // build, only the ones it is about to rebuild, so a partial build never\n // deletes the output of an addon it left alone.\n cleanOwnedDirs(\n registryPath,\n config.resourcesDir,\n options.filter === undefined ? undefined : new Set(selected.map((addon) => addon.name)),\n );\n\n // Stages 3 and 4: materialize every selected addon, then build the source\n // ones. The materialized copy owns the directory (so a rebuild replaces it),\n // and the build writes the client/server/browser artifacts into it afterwards.\n const overrides = config.addons.overrides;\n for (const addon of selected) {\n await materializeAddon(addon, config.resourcesDir, registryPath, overrides[addon.name]);\n if (addon.kind === 'source') {\n await buildLocalAddon(addon, config.resourcesDir, config, {\n noBrowser: options.noBrowser,\n });\n }\n }\n } finally {\n if (preserved !== undefined) await restoreBrowserDirs(preserved, config);\n }\n\n // Stage 5: builtins — the `hotreload` builtin is not implemented yet.\n // Stage 6: redscripts — compile every addon's `.reds` into the output resource.\n await buildFinalRedscripts(config, ordered, options, registryPath);\n\n // Stage 7: rewrite the `resources` array with the FULL ordered list, led by\n // `final_redscripts` when this run produced it. A filtered build rebuilds\n // only a subset; it must not drop the addons it left alone from the server's\n // load order.\n const resources = plannedResources(config, ordered, options);\n await writeServerToml(config.root, resources);\n\n // Stage 8: record the resolved addons for reproducibility and diagnostics —\n // the whole ordered list, not just the subset this run rebuilt.\n await writeAddonsJson(config.workDir, ordered);\n\n return { root: config.root, resources, addons: selected };\n}\n\n/**\n * True when this run builds the generated scripts rather than skipping them.\n *\n * The one place the decision is made: the stage, the `resources` list and\n * `checkProject` all ask this question, so a build and a check of the same\n * project can never disagree about whether the resource belongs in\n * `server.toml`.\n */\nexport function redscriptsStageRuns(\n config: ProjectConfig,\n options: { noRedscripts?: boolean } = {},\n): boolean {\n return options.noRedscripts !== true && config.redscripts.enabled;\n}\n\n/**\n * The resource names a build writes to `server.toml`, in load order: the\n * generated scripts when the stage runs, then every addon, then\n * `addons.extraResources`.\n *\n * Pure — no compile, no compiler resolution, no filesystem access — so\n * `checkProject` can compute the same list the build would write without\n * building anything.\n */\nexport function plannedResources(\n config: ProjectConfig,\n addons: ResolvedAddon[],\n options: { noRedscripts?: boolean } = {},\n): string[] {\n return [\n ...(redscriptsStageRuns(config, options) ? [config.redscripts.output] : []),\n ...addons.map((addon) => addon.name),\n ...config.addons.extraResources,\n ];\n}\n\n/**\n * Refuse settings a run cannot honour, before anything is written.\n *\n * The one check today is the generated resource's name: `redscripts.output`\n * may not be a name the project already uses as an addon or a hand-managed\n * resource, because the stage would write the compiled scripts over it\n * (`config.bad-value`).\n *\n * Shared by `buildProject` and `checkProject` so both report the same code and\n * message for the same project, and gated by {@link redscriptsStageRuns}: a run\n * that skips the stage — `--no-redscripts`, `redscripts.enabled: false` — never\n * acts on the name, so a project whose redscripts are broken must still build\n * with the stage switched off. The flag is the escape hatch, not a config\n * repair.\n *\n * Errors: `config.bad-value`.\n */\nexport function validateProjectSettings(\n config: ProjectConfig,\n addons: ResolvedAddon[],\n options: { noRedscripts?: boolean } = {},\n): void {\n if (!redscriptsStageRuns(config, options)) return;\n rejectOutputNameClash(config.redscripts.output, addons, config.addons.extraResources);\n}\n\n/**\n * Which baseline and source files the redscripts stage compiles (spec §9.4).\n *\n * `baseline` is absent only for `'none'`, where the core sources replace it.\n */\ninterface BaselinePlan {\n /** The `REDS` bundle to compile against, if there is one. */\n baseline?: string;\n /** Extra sources to compile: the core's own `.reds` for `'none'`. */\n sources: RedscriptSource[];\n}\n\n/**\n * Stage 6: build the `final_redscripts` resource.\n *\n * The generated directory is owned like any materialized addon: it is claimed\n * in the registry (`claimOwnedDir`, `redscripts.not-owned` for a directory the\n * builder did not create) before anything is written, so cleanup can find it\n * and a hand-written `resources/final_redscripts/` is never overwritten.\n *\n * Every run that does not produce the resource gives its claim back\n * (`dropOwnedDir`). The registry records the owner, so a drop never deletes a\n * directory another stage owns — an addon copy that happens to carry the same\n * name survives. A skipped stage therefore never refuses the project: with\n * `--no-redscripts` (or `redscripts.enabled: false`) the name's clash with an\n * addon is irrelevant, because nothing is written under it. The clash is\n * refused up front by {@link validateProjectSettings}, which only runs when\n * this stage will write.\n *\n * `--no-redscripts` skips the stage outright, before the disabled check, so a\n * project that can only be built with the stage off is still buildable with\n * the flag. With `redscripts.enabled` false the stage runs only its check: a\n * project that ships `.reds` sources cannot be built while the compiler is\n * off, because the server would silently keep the core's cache and the\n * addons' scripts would never load (`redscripts.disabled-with-sources`).\n *\n * The compiler is resolved only when there is something to compile: with no\n * sources the baseline is copied as-is, and resolving a binary that is never\n * run would make an offline baseline-only build download one just to fail.\n *\n * The baseline is `'core'` (the platform's shipped cache), `'none'` (the core\n * `src_scripts` compiled together with the addons, no precompiled bundle) or a\n * path used as configured (a relative path resolves against the project root).\n * A missing baseline is `redscripts.baseline-missing`, with the `cybermp\n * download` hint when the missing file is the core one.\n *\n * Errors from the compile itself (`redscripts.collision`, `.compile-failed`,\n * `.output`, …) surface unchanged.\n */\nasync function buildFinalRedscripts(\n config: ProjectConfig,\n addons: ResolvedAddon[],\n options: BuildOptions,\n registryPath: string,\n): Promise<void> {\n const settings = config.redscripts;\n\n if (options.noRedscripts === true) {\n await dropOwnedDir(registryPath, config.resourcesDir, settings.output, 'redscripts');\n return;\n }\n\n const sources = collectRedscripts(addons);\n\n if (!settings.enabled) {\n if (sources.length > 0) {\n throw new BuilderError(\n 'redscripts.disabled-with-sources',\n `the project declares ${describeSources(sources)}, but \\`redscripts.enabled\\` is ` +\n 'false in cybermp.config.json; set it to true, or remove the .reds sources from ' +\n 'the addon manifests',\n );\n }\n await dropOwnedDir(registryPath, config.resourcesDir, settings.output, 'redscripts');\n return;\n }\n\n const outputDir = await claimOwnedDir(\n registryPath,\n config.resourcesDir,\n settings.output,\n 'redscripts',\n );\n\n const platform = redscriptsPlatform(settings.platform, config.server.platforms);\n const plan = baselinePlan(config, platform);\n const compiled = [...plan.sources, ...sources];\n\n // No sources at all: the stage publishes the baseline. Resolving a compiler\n // for that would download one on a cold work dir and fail offline for a\n // binary that is never run, so it is only resolved when there is work.\n const compiler =\n compiled.length === 0\n ? undefined\n : await resolveCompiler({\n workDir: config.workDir,\n version: settings.compilerVersion,\n platform,\n });\n\n await buildRedscripts({\n sources: compiled,\n baseline: plan.baseline,\n outputDir,\n compiler,\n workDir: config.workDir,\n });\n}\n\n/**\n * Refuse an output name the project already uses.\n *\n * The stage claims `resources/<output>/` and compiles into it, so a name that\n * belongs to an addon copy or a hand-managed resource would be overwritten —\n * the registry can record both claims but one directory cannot hold two\n * resources. Renaming the resource or `redscripts.output` is the fix, so the\n * error says both.\n */\nfunction rejectOutputNameClash(\n output: string,\n addons: ResolvedAddon[],\n extraResources: string[],\n): void {\n const clash =\n addons.find((addon) => addon.name === output)?.name ??\n extraResources.find((name) => name === output);\n if (clash === undefined) return;\n\n throw new BuilderError(\n 'config.bad-value',\n `\\`redscripts.output\\` is \\`${output}\\`, which the project also uses as a resource; ` +\n 'the compiled scripts would overwrite it — rename that resource, or set ' +\n '`redscripts.output` to another name',\n );\n}\n\n/**\n * The platform whose core baseline is used: `redscripts.platform`, then the\n * first `server.platforms` entry, then the host (win32 is `win`, anything else\n * `linux` — the only targets CyberMP ships).\n */\nfunction redscriptsPlatform(\n configured: CompilerPlatform | undefined,\n platforms: CompilerPlatform[],\n): CompilerPlatform {\n if (configured !== undefined) return configured;\n const [first] = platforms;\n if (first !== undefined) return first;\n return process.platform === 'win32' ? 'win' : 'linux';\n}\n\n/** Resolve the configured baseline to a file, or to the core sources. */\nfunction baselinePlan(config: ProjectConfig, platform: CompilerPlatform): BaselinePlan {\n const { baseline } = config.redscripts;\n\n if (baseline === 'none') {\n return { sources: coreSources(config.workDir, platform) };\n }\n\n const core = baseline === 'core';\n const path = core\n ? join(config.workDir, 'mp', platform, ...CORE_BASELINE_PATH)\n : resolve(config.root, baseline);\n\n if (!existsSync(path)) {\n throw new BuilderError(\n 'redscripts.baseline-missing',\n core\n ? `the core redscript baseline for ${platform} is missing at \\`${path}\\`; ` +\n 'run `cybermp download` to fetch the server binaries, or point ' +\n '`redscripts.baseline` at a baseline of your own'\n : `the redscript baseline \\`${baseline}\\` is missing at \\`${path}\\`; ` +\n 'check `redscripts.baseline` in cybermp.config.json',\n );\n }\n\n return { baseline: path, sources: [] };\n}\n\n/**\n * The core's own `.reds` sources, for `baseline: 'none'`.\n *\n * They live in the downloaded server build next to the core cache\n * (`<workDir>/mp/<platform>/data/cybermp_core/files/src_scripts`), so their\n * absence is the same download problem as a missing baseline. Sorted by name\n * so staging — and therefore the compiler's input — is deterministic.\n */\nfunction coreSources(workDir: string, platform: CompilerPlatform): RedscriptSource[] {\n const dir = join(workDir, 'mp', platform, ...CORE_SOURCES_PATH);\n const missing = new BuilderError(\n 'redscripts.baseline-missing',\n `the core redscript sources for ${platform} are missing at \\`${dir}\\`; ` +\n 'run `cybermp download` to fetch the server binaries',\n );\n\n let names: string[];\n try {\n names = readdirSync(dir, { withFileTypes: true })\n .filter((entry) => entry.isFile() && entry.name.endsWith('.reds'))\n .map((entry) => entry.name)\n .sort();\n } catch {\n throw missing;\n }\n\n if (names.length === 0) throw missing;\n\n return names.map((name) => ({ addon: CORE_ADDON_NAME, file: join(dir, name) }));\n}\n\n/** `3 redscript sources (`a/x.reds`, `b/y.reds`, and 1 more)`, for messages. */\nfunction describeSources(sources: RedscriptSource[]): string {\n const shown = sources\n .slice(0, 3)\n .map((source) => `\\`${source.addon}/${basename(source.file)}\\``);\n const rest = sources.length - shown.length;\n const suffix = rest > 0 ? `, and ${rest} more` : '';\n const noun = sources.length === 1 ? 'redscript source' : 'redscript sources';\n return `${sources.length} ${noun} (${shown.join(', ')}${suffix})`;\n}\n\n/** The browser directory a source addon's build produces. */\nconst BROWSER_DIR = 'browser';\n\n/** Browser directories moved aside for a `--no-browser` build. */\ninterface PreservedBrowsers {\n /** Scratch root under the work dir holding the moved directories. */\n root: string;\n /** Backup path per resource name, in the order they were moved. */\n entries: Array<{ name: string; backup: string }>;\n}\n\n/**\n * Move every built `browser/` of `addons` into the scratch root `preserved`\n * carries.\n *\n * Runs before the cleanup stage: the resources dir is about to be emptied, and\n * `--no-browser` will not produce a new one. A directory that is absent is\n * simply not preserved — the addon has no UI yet, and the next full build\n * creates it.\n *\n * Each entry is recorded as soon as its move succeeds and the caller runs this\n * inside the `try` whose `finally` calls {@link restoreBrowserDirs}, so a move\n * that fails half-way restores the directories already moved instead of\n * leaving them in scratch.\n */\nasync function preserveBrowserDirs(\n addons: readonly ResolvedAddon[],\n config: ProjectConfig,\n preserved: PreservedBrowsers,\n): Promise<void> {\n for (const addon of addons) {\n const built = join(config.resourcesDir, addon.name, BROWSER_DIR);\n if (!existsSync(built)) continue;\n const backup = join(preserved.root, addon.name);\n await mkdir(dirname(backup), { recursive: true });\n await moveDirectory(built, backup);\n preserved.entries.push({ name: addon.name, backup });\n }\n}\n\n/**\n * Put the preserved directories back and remove the scratch root.\n *\n * A directory the build did produce wins over the backup (a source addon with a\n * `browser/` still builds when `--no-browser` is not set, and this function is\n * only reached for runs that moved something). A resource dir that is gone —\n * the addon was filtered out or materialization failed — is left alone; the\n * backup is discarded with the scratch root rather than recreating a tree the\n * build did not write.\n */\nasync function restoreBrowserDirs(\n preserved: PreservedBrowsers,\n config: ProjectConfig,\n): Promise<void> {\n try {\n for (const { name, backup } of preserved.entries) {\n const resourceDir = join(config.resourcesDir, name);\n if (!existsSync(resourceDir)) continue;\n const target = join(resourceDir, BROWSER_DIR);\n if (existsSync(target)) continue;\n await moveDirectory(backup, target);\n }\n } finally {\n await rm(preserved.root, { recursive: true, force: true }).catch(() => undefined);\n }\n}\n\n/** Rename a directory, falling back to copy-and-delete across filesystems. */\nasync function moveDirectory(from: string, to: string): Promise<void> {\n try {\n await rename(from, to);\n } catch (error) {\n if (!isErrno(error, 'EXDEV')) throw error;\n await cp(from, to, { recursive: true });\n await rm(from, { recursive: true, force: true });\n }\n}\n\n/** The known resource names, for a message that makes a typo obvious. */\nfunction listNames(addons: readonly ResolvedAddon[]): string {\n return addons.length === 0 ? '(none)' : addons.map((addon) => addon.name).join(', ');\n}\n\n/**\n * Rewrite the `resources` array of `<root>/server.toml`, preserving the rest.\n *\n * The read is wrapped so a missing file is the same `serverToml.missing`\n * finding `cybermp check` reports, and the write is atomic like every other\n * generated file: a sibling temp file renamed into place, removed on failure,\n * so a crash can never leave a half-written `server.toml`. The temp file is\n * created with the process umask, so an existing file's mode is applied to it\n * before the rename — a `server.toml` that was `0600` must not come back\n * group- or world-readable.\n */\nasync function writeServerToml(root: string, resources: string[]): Promise<void> {\n const path = join(root, SERVERTOML_FILENAME);\n\n let text: string;\n try {\n text = await readFile(path, 'utf8');\n } catch (error) {\n if (isErrno(error, 'ENOENT')) {\n throw new BuilderError(\n 'serverToml.missing',\n `missing \\`${SERVERTOML_FILENAME}\\` in \\`${root}\\``,\n );\n }\n throw new BuilderError(\n 'serverToml.read',\n `cannot read \\`${path}\\`: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n\n const temporary = `${path}.${process.pid}.tmp`;\n try {\n await writeFile(temporary, writeResourceList(text, resources));\n // Keep the file's own permissions when it already exists; a new file keeps\n // the default the umask gave the temp file.\n const mode = (await stat(path, { throwIfNoEntry: false }))?.mode;\n if (mode !== undefined) await chmod(temporary, mode & 0o777);\n await rename(temporary, path);\n } catch (error) {\n await rm(temporary, { force: true }).catch(() => undefined);\n throw error;\n }\n}\n\n/** Write the build record: one entry per addon, in load order. */\nasync function writeAddonsJson(workDir: string, addons: ResolvedAddon[]): Promise<void> {\n const entries = addons.map((addon) => ({\n name: addon.name,\n version: addon.version,\n source: addon.source,\n requires: addon.requires,\n }));\n const path = join(workDir, ADDONS_JSON_FILENAME);\n // Atomic, like the ownership registry: a torn `.addons.json` must not read as\n // a valid record, so write a sibling temp file and rename it into place.\n const temporary = `${path}.${process.pid}.tmp`;\n await mkdir(workDir, { recursive: true });\n try {\n await writeFile(temporary, `${JSON.stringify(entries, null, 2)}\\n`);\n await rename(temporary, path);\n } catch (error) {\n await rm(temporary, { force: true }).catch(() => undefined);\n throw error;\n }\n}\n\nfunction isErrno(error: unknown, code: string): boolean {\n return (\n typeof error === 'object' &&\n error !== null &&\n (error as { code?: unknown }).code === code\n );\n}\n\n","/**\n * `checkProject` — validate a whole project without writing anything.\n *\n * The check re-resolves the project exactly the way {@link buildProject} does\n * and compares the result against what is on disk, so a clean `cybermp check`\n * is the guarantee CI needs that the next `cybermp build` would not rewrite\n * `server.toml`.\n *\n * Two checks run:\n *\n * 1. the top-level `resources` array of `server.toml` must equal the planned\n * order — {@link plannedResources}, the same function the build writes from:\n * the generated scripts when the stage would run, then the ordered addons\n * and `addons.extraResources`; a mismatch is `serverToml.stale`;\n * 2. every addon must pass the addon package's `validateAddon`, so a broken\n * manifest or a path that escapes the package is reported with its own\n * `path.*` / `manifest.*` / `package.*` code.\n *\n * Nothing is compiled and no compiler is resolved, so a check never downloads a\n * compiler; `--no-redscripts` and `redscripts.enabled` are honoured through the\n * same predicate the build uses.\n *\n * The result is total: a missing or malformed `server.toml` becomes an issue\n * instead of a throw, the same way the addon validator reports rather than\n * throws, so one run lists everything that is wrong. A project the resolver\n * cannot resolve at all — a missing npm dependency, or a release addon whose\n * locked installation is gone or no longer verifies — is a `BuilderError` out of\n * the shared resolution, so `check` exits 1 with the same code `build` reports.\n * Settings a build could not honour are reported the same way and with the same\n * code, because both commands run the same validation: a `redscripts.output`\n * that collides with an addon is `config.bad-value` here too.\n */\nimport { validateAddon, type Issue } from '@cybermp-community/addon';\nimport { readFile } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { plannedResources, validateProjectSettings } from './build/index.js';\nimport { BuilderError } from './errors.js';\nimport { resolveProject } from './project.js';\nimport { readResourceList } from './serverToml.js';\n\n/** Name of the project's server configuration file, relative to the root. */\nconst SERVERTOML_FILENAME = 'server.toml';\n\n/** The result of one project check. */\nexport interface CheckResult {\n /** True when no issue is at error level; warnings never fail the check. */\n ok: boolean;\n /** Every issue, in discovery order: server.toml first, then per addon. */\n issues: Issue[];\n}\n\n/** Build flags that change what the next build would write. */\nexport interface CheckOptions {\n /** Expect the list `build --no-redscripts` writes: no generated resource. */\n noRedscripts?: boolean;\n}\n\n/**\n * Re-resolve `root` and compare it against the on-disk state.\n *\n * See the module comment for the two checks and the error contract.\n */\nexport async function checkProject(\n root: string,\n options: CheckOptions = {},\n): Promise<CheckResult> {\n const { config, ordered } = await resolveProject(root);\n const issues: Issue[] = [];\n\n // The same settings validation the build runs, before comparing anything:\n // a colliding `redscripts.output` is a config error in both commands, not a\n // stale list in one and a config error in the other.\n validateProjectSettings(config, ordered, options);\n\n const expected = plannedResources(config, ordered, options);\n const onDisk = await readServerTomlNames(config.root, issues);\n if (onDisk !== undefined && !sameOrder(onDisk, expected)) {\n issues.push({\n code: 'serverToml.stale',\n level: 'error',\n message:\n `server.toml \\`resources\\` does not match the resolved order: ` +\n `on disk ${JSON.stringify(onDisk)}, expected ${JSON.stringify(expected)}; ` +\n 'run `cybermp build` to refresh it',\n });\n }\n\n for (const addon of ordered) {\n const result = await validateAddon(addon.dir, { kind: addon.kind });\n issues.push(...result.issues);\n }\n\n return { ok: issues.every((issue) => issue.level !== 'error'), issues };\n}\n\n/**\n * The `resources` names of `<root>/server.toml`, or `undefined` when the file\n * cannot be read or parsed (in which case an issue has been recorded).\n */\nasync function readServerTomlNames(root: string, issues: Issue[]): Promise<string[] | undefined> {\n const path = join(root, SERVERTOML_FILENAME);\n\n let text: string;\n try {\n text = await readFile(path, 'utf8');\n } catch (error) {\n if (isErrno(error, 'ENOENT')) {\n issues.push({\n code: 'serverToml.missing',\n level: 'error',\n message: `missing \\`${SERVERTOML_FILENAME}\\` in \\`${root}\\``,\n });\n return undefined;\n }\n throw error;\n }\n\n try {\n return readResourceList(text).names;\n } catch (error) {\n if (error instanceof BuilderError) {\n issues.push({ code: error.code, level: 'error', message: error.message });\n return undefined;\n }\n throw error;\n }\n}\n\n/** Load order is significant: the arrays must be equal element by element. */\nfunction sameOrder(left: string[], right: string[]): boolean {\n return left.length === right.length && left.every((name, index) => name === right[index]);\n}\n\nfunction isErrno(error: unknown, code: string): boolean {\n return (\n typeof error === 'object' &&\n error !== null &&\n (error as { code?: unknown }).code === code\n );\n}\n","/**\n * The addon management commands: `add`, `remove`, `list`, `install`, `update`.\n *\n * They are the only code that writes `cybermp.config.json` and\n * `cybermp.lock.json` on the user's behalf, and they write each of them through\n * its documented surface: the `addons` keys of the config (via\n * {@link writeAddonConfig}) and the closed entry shape of the lock (via\n * {@link writeLock}). Nothing here re-serializes the rest of a project's\n * configuration.\n *\n * Source-specific work lives beside this module: `addons/sources/path.ts`\n * registers or snapshots local directories, `addons/sources/npm.ts` drives the\n * project's package manager and rolls a failed install back, and\n * `addons/sources/release.ts` downloads and verifies release archives. This\n * module decides what a successful install *means*: the order entry, the lock\n * entry, and what survives a failure.\n *\n * Failures never leave a half-installed addon: an npm install that fails\n * validation is removed by the package manager, a release that fails validation\n * is deleted from the work directory and never written to the lock, and a\n * copied local addon is removed if the copy does not validate.\n */\nimport { existsSync, globSync, readFileSync, realpathSync, statSync } from 'node:fs';\nimport { rm } from 'node:fs/promises';\nimport { isAbsolute, join, relative, resolve, sep } from 'node:path';\nimport {\n AddonError,\n type AddonPackage,\n readAddonPackage,\n} from '@cybermp-community/addon';\nimport { readLock, writeLock, type LockEntry, type LockSource } from '../addons/lock.js';\nimport { resolveLocalAddons } from '../addons/local.js';\nimport { orderAddons } from '../addons/order.js';\nimport { verifyReleaseInstall } from '../addons/release.js';\nimport {\n addNpmAddon,\n detectPackageManager,\n runPackageManager,\n type PackageManager,\n} from '../addons/sources/npm.js';\nimport { hashAddonDirectory, registerPathAddon } from '../addons/sources/path.js';\nimport { installRelease } from '../addons/sources/release.js';\nimport { parseAddonSpec, type AddonSpec } from '../addons/sources/spec.js';\nimport type { AddonSource, ResolvedAddon } from '../addons/types.js';\nimport {\n loadConfig,\n writeAddonConfig,\n type AddonConfigEdit,\n type ProjectConfig,\n} from '../config.js';\nimport { BuilderError } from '../errors.js';\nimport { resolveNpmAddonsChecked } from '../project.js';\n\n/** Options of {@link addAddon}, mirroring the `add` flags. */\nexport interface AddAddonOptions {\n /** Insert the addon first in `addons.order`. */\n first?: boolean;\n /** Insert the addon directly before this `addons.order` name. */\n before?: string;\n /** Insert the addon directly after this `addons.order` name. */\n after?: string;\n /** Release asset name or glob, required when a release ships several archives. */\n asset?: string;\n /** Snapshot a local path into `<root>/addons/<resource>` instead of registering it. */\n copy?: boolean;\n /** Package manager override for npm specs. */\n pm?: PackageManager;\n /** Release API root override (a local server in tests). */\n apiBase?: string;\n}\n\n/** A removed addon, for the CLI's one-line report. */\nexport interface RemovedAddon {\n name: string;\n source: LockSource | 'npm' | 'local';\n}\n\n/** One row of {@link listAddons}. */\nexport interface AddonListing {\n name: string;\n version: string;\n source: AddonSource;\n /** 1-based position in the resolved load order; absent for a disabled addon. */\n order?: number;\n}\n\n/** Options of {@link installProject}. */\nexport interface InstallOptions {\n /** Package manager override. */\n pm?: PackageManager;\n}\n\n/** What {@link installProject} did. */\nexport interface InstallReport {\n /** Package manager that would run (or ran) the dependency install. */\n packageManager: PackageManager;\n /** False when the project has no `package.json` and the package manager was skipped. */\n ranPackageManager: boolean;\n /** Release addons that were missing and restored from the lock. */\n restored: string[];\n}\n\n/** Options of {@link updateAddon}. */\nexport interface UpdateOptions {\n /** Release API root override (a local server in tests). */\n apiBase?: string;\n}\n\n/** What {@link updateAddon} did to one addon. */\nexport interface UpdateResult {\n name: string;\n /** `resolved` before the update. */\n from: string;\n /** `resolved` after the update. */\n to: string;\n /** False when the entry was pinned or already at the resolved version. */\n changed: boolean;\n /** True when the lock entry now pins a tag. */\n pinned: boolean;\n}\n\n/**\n * Install one addon from any source and record it in the project.\n *\n * - a path is validated and registered in `addons.local` (or snapshotted with\n * `copy`), and gets a `path` lock entry with the directory hash;\n * - an npm package is installed with the project's package manager;\n * - a release or direct URL goes through `installRelease`, is validated in\n * place, and gets a `release` lock entry with its URL, integrity and tag.\n *\n * The resource name is appended to `addons.order` unless it is already there;\n * `first`/`before`/`after` reposition it. Nothing is recorded until the addon\n * has validated.\n *\n * Errors keep the source's own codes (`spec.*`, `add.*`, `pm.*`, `npm.*`,\n * `release.*`) and validation failures keep the validator's code\n * (`package.missing-marker`, `manifest.*`, `path.*`, …).\n */\nexport async function addAddon(\n root: string,\n spec: string,\n options: AddAddonOptions = {},\n): Promise<ResolvedAddon> {\n const config = await loadConfig(root);\n const parsed = parseAddonSpec(spec, { root: config.root });\n rejectMisplacedFlags(parsed, options);\n rejectPlacement(config.addons.order, options);\n\n let addon: ResolvedAddon;\n let localEntry: string | undefined;\n let lockEntry: LockEntry | undefined;\n\n switch (parsed.kind) {\n case 'path': {\n const registered = await registerPathAddon(config.root, parsed, {\n copy: options.copy === true,\n });\n addon = registered.addon;\n localEntry = registered.entry;\n lockEntry = {\n source: 'path',\n resolved: addon.version,\n path: registered.entry,\n integrity: registered.integrity,\n };\n break;\n }\n case 'npm': {\n addon = await addNpmAddon(config.root, parsed, { pm: options.pm });\n break;\n }\n case 'release':\n case 'url': {\n const installed = await installRelease(parsed, {\n root: config.root,\n workDir: config.workDir,\n asset: options.asset,\n apiBase: options.apiBase,\n // Validate while the archive is staged, before it replaces an existing\n // install: a rejected addon never destroys the previous one.\n validate: true,\n });\n\n addon = {\n name: installed.name,\n dir: installed.dir,\n version: installed.version,\n source: 'release',\n requires: installed.requires,\n kind: 'prebuilt',\n };\n lockEntry = {\n source: 'release',\n resolved: installed.version,\n integrity: installed.integrity,\n url: installed.url,\n };\n if (installed.tag !== undefined) lockEntry.tag = installed.tag;\n if (installed.pinned !== undefined) lockEntry.pinned = installed.pinned;\n break;\n }\n }\n\n const edit: AddonConfigEdit = { order: insertOrder(config.addons.order, addon.name, options) };\n if (localEntry !== undefined) {\n edit.local = withEntry(config.addons.local, localEntry);\n }\n writeAddonConfig(config.root, edit);\n\n if (lockEntry !== undefined) {\n const lock = readLock(config.root);\n lock.addons[addon.name] = lockEntry;\n writeLock(config.root, lock);\n }\n\n return addon;\n}\n\n/**\n * Remove an addon by resource name or by npm package name.\n *\n * A lock entry (release or path) is deleted; an npm dependency is removed with\n * the package manager; a local addon that `cybermp create addon` registered is\n * dropped from `addons.local` and its directory deleted once no remaining glob\n * matches it. The resource name is dropped from `addons.order` and\n * `addons.disabled`, and a path entry that was registered in `addons.local` is\n * dropped from it — a broad glob that still matches the directory is left\n * alone, because it also covers other addons.\n *\n * Errors: `remove.not-found` when the lock, the project's `dependencies` and\n * `addons.local` all lack the name; `remove.outside-root` when a matched local\n * entry resolves outside the project; `pm.*` when the package manager fails.\n */\nexport async function removeAddon(\n root: string,\n nameOrPackage: string,\n options: { pm?: PackageManager } = {},\n): Promise<RemovedAddon> {\n const config = await loadConfig(root);\n const lock = readLock(config.root);\n\n let removed: RemovedAddon;\n let localEntry: string | undefined;\n let dependencyName: string | undefined;\n let localDir: string | undefined;\n\n const entry = lock.addons[nameOrPackage];\n if (entry !== undefined) {\n delete lock.addons[nameOrPackage];\n localEntry = entry.source === 'path' ? entry.path : undefined;\n writeLock(config.root, lock);\n removed = { name: nameOrPackage, source: entry.source };\n } else {\n const packageName = npmPackageFor(config.root, nameOrPackage);\n if (packageName !== undefined) {\n const pm = detectPackageManager(config.root, options.pm);\n const resourceName = installedResourceName(config.root, packageName);\n await runPackageManager(config.root, pm, ['remove', packageName]);\n dependencyName = packageName;\n removed = { name: resourceName ?? nameOrPackage, source: 'npm' };\n } else {\n // `create addon` registers `./addons/<name>` in `addons.local` and writes\n // no lock entry: without this branch the addon could only be removed by\n // hand-editing the config.\n const local = localAddonFor(config.root, config.addons.local, nameOrPackage);\n if (local === undefined) {\n throw new BuilderError(\n 'remove.not-found',\n `\\`${nameOrPackage}\\` is not a lock entry, a dependency or an \\`addons.local\\` addon of this project`,\n );\n }\n const realLocal = realDirectory(local.dir);\n if (realLocal === undefined || !isInside(config.root, realLocal)) {\n throw new BuilderError(\n 'remove.outside-root',\n `the \\`addons.local\\` entry \\`${local.entry}\\` resolves outside the project root`,\n );\n }\n localEntry = local.entry;\n localDir = local.dir;\n removed = { name: nameOrPackage, source: 'local' };\n }\n }\n\n const names = new Set(\n [nameOrPackage, removed.name, dependencyName].filter(\n (name): name is string => name !== undefined,\n ),\n );\n const edit: AddonConfigEdit = {};\n const order = config.addons.order.filter((name) => !names.has(name));\n if (order.length !== config.addons.order.length) edit.order = order;\n const disabled = config.addons.disabled.filter((name) => !names.has(name));\n if (disabled.length !== config.addons.disabled.length) edit.disabled = disabled;\n let remainingLocal: string[] | undefined;\n if (localEntry !== undefined) {\n remainingLocal = config.addons.local.filter((pattern) => pattern !== localEntry);\n if (remainingLocal.length !== config.addons.local.length) edit.local = remainingLocal;\n }\n if (Object.keys(edit).length > 0) writeAddonConfig(config.root, edit);\n\n // Delete the directory only when the config no longer references it: a broad\n // glob such as `addons/*` still installs it, and deleting a directory the\n // config names would leave the project resolving an addon from nothing.\n if (localDir !== undefined && !isReferenced(config.root, remainingLocal ?? [], localDir)) {\n await rm(localDir, { recursive: true, force: true });\n }\n\n return removed;\n}\n\n/**\n * Resolve every installed addon with its load-order position.\n *\n * Local and npm addons are resolved the way a build resolves them — through\n * {@link resolveNpmAddonsChecked}, so a missing npm dependency fails with the\n * same `cybermp install` hint here as it does from `build`; release addons come\n * from the lock (their installed directory supplies the version and\n * requirements when it is still present). A stale\n * `addons.order`/`disabled`/`overrides` entry is ignored here instead of\n * failing the listing — `cybermp check` is the command that reports it.\n */\nexport async function listAddons(root: string): Promise<AddonListing[]> {\n const config = await loadConfig(root);\n const local = await resolveLocalAddons(config.root, config.addons.local);\n const npm = await resolveNpmAddonsChecked(config.root);\n const release = await releaseAddons(config);\n const addons = [...local, ...npm, ...release];\n\n const known = new Set(addons.map((addon) => addon.name));\n const order = config.addons.order.filter((name) => known.has(name));\n const disabled = config.addons.disabled.filter((name) => known.has(name));\n const ordered = orderAddons(addons, order, disabled);\n\n const position = new Map(ordered.map((addon, index) => [addon.name, index + 1]));\n const rows: AddonListing[] = ordered.map((addon) => ({\n name: addon.name,\n version: addon.version,\n source: addon.source,\n order: position.get(addon.name),\n }));\n\n for (const addon of addons\n .filter((candidate) => !position.has(candidate.name))\n .sort((left, right) => (left.name < right.name ? -1 : left.name > right.name ? 1 : 0))) {\n rows.push({ name: addon.name, version: addon.version, source: addon.source });\n }\n\n return rows;\n}\n\n/**\n * Install the project's dependencies and restore missing release addons.\n *\n * `<pm> install` restores npm addons from the package manager lockfile (and is\n * skipped when the project has no `package.json`). Every\n * `release` lock entry whose installation under `<workDir>/addons/` is gone or\n * no longer verifies — no install record, another archive, or files that changed\n * after installation — is downloaded again from the URL the lock recorded and\n * checked against the recorded integrity; a mismatch is `lock.integrity` and the\n * downloaded addon is removed. A `path` entry whose directory no longer exists is\n * `lock.path-missing` (re-add it, or remove it from the lock).\n */\nexport async function installProject(\n root: string,\n options: InstallOptions = {},\n): Promise<InstallReport> {\n const config = await loadConfig(root);\n const pm = detectPackageManager(config.root, options.pm);\n // A project with only local addons has no `package.json`; running the package\n // manager there would fail on the missing manifest for nothing to install.\n const ranPackageManager = existsSync(join(config.root, 'package.json'));\n if (ranPackageManager) {\n await runPackageManager(config.root, pm, ['install']);\n }\n\n const lock = readLock(config.root);\n const restored: string[] = [];\n\n for (const name of Object.keys(lock.addons).sort()) {\n const entry = lock.addons[name];\n if (entry === undefined || entry.source !== 'release') continue;\n\n const dir = join(config.workDir, 'addons', name);\n if (await verifiesReleaseInstall(name, dir, entry, config.workDir)) continue;\n if (entry.url === undefined) {\n throw new BuilderError(\n 'lock.incomplete',\n `the release lock entry \\`${name}\\` has no \\`url\\`; re-add it with \\`cybermp add\\``,\n );\n }\n if (entry.integrity === undefined) {\n throw new BuilderError(\n 'lock.incomplete',\n `the release lock entry \\`${name}\\` has no \\`integrity\\`; re-add it with \\`cybermp add\\` ` +\n 'so the restored archive can be verified',\n );\n }\n\n const installed = await installRelease(parseAddonSpec(entry.url), {\n root: config.root,\n workDir: config.workDir,\n });\n if (installed.integrity !== entry.integrity) {\n await rm(installed.dir, { recursive: true, force: true }).catch(() => undefined);\n throw new BuilderError(\n 'lock.integrity',\n `\\`${name}\\` from \\`${entry.url}\\` has ${installed.integrity}, but cybermp.lock.json ` +\n `records ${entry.integrity}; the release changed — run \\`cybermp update ${name}\\` ` +\n 'once you trust it',\n );\n }\n restored.push(name);\n }\n\n for (const [name, entry] of Object.entries(lock.addons)) {\n if (entry.source !== 'path' || entry.path === undefined) continue;\n if (existsSync(resolve(config.root, entry.path))) continue;\n throw new BuilderError(\n 'lock.path-missing',\n `the path addon \\`${name}\\` is missing at \\`${entry.path}\\`; restore the directory or remove the lock entry`,\n );\n }\n\n return { packageManager: pm, ranPackageManager, restored };\n}\n\n/**\n * True when the release installation at `dir` verifies against `entry`.\n *\n * `install` is the repair command the build's release-state errors name, so it\n * replaces an installation whose files no longer hash to its record instead of\n * leaving content nobody verified in place. Any failure — gone, no record,\n * another archive, changed files — means \"install it from the lock below\".\n */\nasync function verifiesReleaseInstall(\n name: string,\n dir: string,\n entry: LockEntry,\n workDir: string,\n): Promise<boolean> {\n try {\n await verifyReleaseInstall(name, dir, entry, workDir);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Re-resolve addons from their source and rewrite the lock.\n *\n * Releases follow their source: an unpinned entry re-resolves the latest\n * release (or re-downloads a direct URL, whose content may move), `--to`\n * installs and pins that tag, and a pinned entry stays put without `--to`.\n * Path entries recompute their directory hash and version. With no name every\n * lock entry is updated.\n *\n * Errors: `update.unknown-addon` for a name the lock does not hold,\n * `update.unsupported` for `--to` on a source whose repository cannot be\n * derived, `lock.incomplete`/`lock.path-missing` for a broken entry, and the\n * release/validator codes for a failed install.\n */\nexport async function updateAddon(\n root: string,\n name?: string,\n to?: string,\n options: UpdateOptions = {},\n): Promise<UpdateResult[]> {\n const config = await loadConfig(root);\n const lock = readLock(config.root);\n\n const names = name === undefined ? Object.keys(lock.addons).sort() : [name];\n if (names.length === 0) return [];\n\n const results: UpdateResult[] = [];\n\n for (const key of names) {\n const entry = lock.addons[key];\n if (entry === undefined) {\n throw new BuilderError(\n 'update.unknown-addon',\n `\\`${key}\\` has no \\`cybermp.lock.json\\` entry; npm addons are updated by the ` +\n 'package manager, and a new addon is installed with `cybermp add`',\n );\n }\n results.push(await updateEntry(config, key, entry, to, options));\n }\n\n writeLock(config.root, lock);\n return results;\n}\n\n/** Update one lock entry in place and report the change. */\nasync function updateEntry(\n config: ProjectConfig,\n name: string,\n entry: LockEntry,\n to: string | undefined,\n options: UpdateOptions,\n): Promise<UpdateResult> {\n const from = entry.resolved;\n\n if (entry.source === 'path') {\n return updatePathEntry(config, name, entry, from, to);\n }\n\n if (entry.source !== 'release') {\n throw new BuilderError(\n 'update.unsupported',\n `\\`${name}\\` is an \\`${entry.source}\\` entry; only release and path entries are updated here`,\n );\n }\n\n if (to === undefined && entry.pinned === true) {\n return { name, from, to: from, changed: false, pinned: true };\n }\n\n const installed = await installRelease(releaseSpecFor(entry, name, to), {\n root: config.root,\n workDir: config.workDir,\n apiBase: options.apiBase,\n // Same rule as `add`: the staged tree is validated before the update\n // replaces the working installation.\n validate: true,\n });\n\n const changed =\n from !== installed.version ||\n entry.integrity !== installed.integrity ||\n entry.url !== installed.url ||\n entry.tag !== installed.tag ||\n (entry.pinned === true) !== (installed.pinned === true);\n\n entry.resolved = installed.version;\n entry.integrity = installed.integrity;\n entry.url = installed.url;\n if (installed.tag !== undefined) entry.tag = installed.tag;\n else delete entry.tag;\n entry.pinned = installed.pinned === true;\n\n return { name, from, to: entry.resolved, changed, pinned: entry.pinned };\n}\n\n/** Recompute the hash and version of a local path entry. */\nasync function updatePathEntry(\n config: ProjectConfig,\n name: string,\n entry: LockEntry,\n from: string,\n to: string | undefined,\n): Promise<UpdateResult> {\n if (to !== undefined) {\n throw new BuilderError(\n 'update.unsupported',\n `\\`${name}\\` is a local path addon; check out the tag in its own repository and rerun ` +\n '`cybermp update` instead of passing --to',\n );\n }\n if (entry.path === undefined) {\n throw new BuilderError(\n 'lock.incomplete',\n `the path lock entry \\`${name}\\` has no \\`path\\`; re-add it with \\`cybermp add\\``,\n );\n }\n\n const dir = resolve(config.root, entry.path);\n if (!existsSync(dir)) {\n throw new BuilderError(\n 'lock.path-missing',\n `the path addon \\`${name}\\` is missing at \\`${entry.path}\\`; restore the directory`,\n );\n }\n\n let addonPackage: AddonPackage;\n try {\n addonPackage = readAddonPackage(dir);\n } catch (error) {\n if (error instanceof AddonError) {\n // `AddonError.message` already carries `<code>: `; the builder error adds\n // it again, so print the detail without its own prefix.\n const prefix = `${error.code}: `;\n const detail = error.message.startsWith(prefix)\n ? error.message.slice(prefix.length)\n : error.message;\n throw new BuilderError(error.code, `\\`${entry.path}\\`: ${detail}`);\n }\n throw error;\n }\n\n const integrity = await hashAddonDirectory(dir);\n const changed = from !== addonPackage.version || entry.integrity !== integrity;\n entry.resolved = addonPackage.version;\n entry.integrity = integrity;\n\n return { name, from, to: entry.resolved, changed, pinned: false };\n}\n\n/**\n * The spec to install for a release lock entry.\n *\n * `--to` needs the repository: it is derived from a GitHub/GitLab asset URL\n * (`owner/repo` in the path), because the lock intentionally stores only the\n * asset URL. Without `--to`, a repository URL re-resolves the latest release;\n * any other URL is re-downloaded as-is, which is the only \"latest\" a direct\n * link can have.\n */\nfunction releaseSpecFor(entry: LockEntry, name: string, to: string | undefined): AddonSpec {\n const repository = entry.url === undefined ? undefined : repositoryFromUrl(entry.url);\n\n if (repository !== undefined) {\n return to === undefined\n ? { kind: 'release', host: repository.host, repo: repository.repo }\n : { kind: 'release', host: repository.host, repo: repository.repo, tag: to };\n }\n\n if (to !== undefined) {\n throw new BuilderError(\n 'update.unsupported',\n `cannot resolve the repository of \\`${name}\\` from \\`${entry.url ?? 'the lock'}\\`; ` +\n `pin the tag explicitly with \\`cybermp add gh:<owner>/<repo>@${to}\\``,\n );\n }\n if (entry.url === undefined) {\n throw new BuilderError(\n 'lock.incomplete',\n `the release lock entry \\`${name}\\` has no \\`url\\`; re-add it with \\`cybermp add\\``,\n );\n }\n return parseAddonSpec(entry.url);\n}\n\n/**\n * `owner/repo` (and host) encoded in a release asset URL. GitHub puts it in\n * `/owner/repo/releases/…`, GitLab in `/group/repo/-/releases/…` or in the API\n * project path; anything else has no derivable repository.\n */\nfunction repositoryFromUrl(url: string): { host: 'github' | 'gitlab'; repo: string } | undefined {\n let parsed: URL;\n try {\n parsed = new URL(url);\n } catch {\n return undefined;\n }\n const segments = parsed.pathname.split('/').filter((segment) => segment !== '');\n\n if (parsed.hostname === 'api.github.com') {\n if (segments[0] !== 'repos' || segments.length < 3) return undefined;\n return { host: 'github', repo: `${segments[1]}/${segments[2]}` };\n }\n if (parsed.hostname === 'github.com') {\n if (segments.length < 3 || segments[2] !== 'releases') return undefined;\n return { host: 'github', repo: `${segments[0]}/${segments[1]}` };\n }\n\n const gitlabHost = process.env.GITLAB_HOST || 'gitlab.com';\n if (parsed.hostname !== gitlabHost) return undefined;\n\n if (segments[0] === 'api' && segments[1] === 'v4' && segments[2] === 'projects') {\n const project = segments[3];\n if (project === undefined) return undefined;\n return { host: 'gitlab', repo: decodeURIComponent(project) };\n }\n const releases = segments.indexOf('-');\n if (releases < 2 || segments[releases + 1] !== 'releases') return undefined;\n return { host: 'gitlab', repo: segments.slice(0, releases).join('/') };\n}\n\n/** Release lock entries as resolved addons, for {@link listAddons}. */\nasync function releaseAddons(config: ProjectConfig): Promise<ResolvedAddon[]> {\n const lock = readLock(config.root);\n const addons: ResolvedAddon[] = [];\n\n for (const [name, entry] of Object.entries(lock.addons)) {\n if (entry.source !== 'release') continue;\n const dir = join(config.workDir, 'addons', name);\n let installed: AddonPackage | undefined;\n try {\n installed = readAddonPackage(dir);\n } catch {\n installed = undefined;\n }\n\n addons.push({\n name,\n dir,\n version: installed?.version ?? entry.resolved,\n source: 'release',\n requires: installed?.requires ?? [],\n kind: 'prebuilt',\n });\n }\n\n return addons;\n}\n\n/** True when `--copy`/`--asset` was passed for a source that cannot use it. */\nfunction rejectMisplacedFlags(spec: AddonSpec, options: AddAddonOptions): void {\n if (options.copy === true && spec.kind !== 'path') {\n throw new BuilderError('add.options', '--copy applies to a local path spec only');\n }\n if (\n options.asset !== undefined &&\n spec.kind !== 'release' &&\n spec.kind !== 'url'\n ) {\n throw new BuilderError('add.options', '--asset applies to a release or URL spec only');\n }\n}\n\n/**\n * Reject an ambiguous or dangling order placement before anything is installed,\n * so a bad flag cannot leave an addon installed and then fail on the ordering.\n */\nfunction rejectPlacement(order: string[], options: AddAddonOptions): void {\n const placements = [\n options.first === true,\n options.before !== undefined,\n options.after !== undefined,\n ].filter(Boolean).length;\n if (placements > 1) {\n throw new BuilderError('add.options', '--first, --before and --after are mutually exclusive');\n }\n\n const anchor = options.before ?? options.after;\n if (anchor !== undefined && !order.includes(anchor)) {\n throw new BuilderError(\n 'add.order-name',\n `\\`${anchor}\\` is not in \\`addons.order\\`; pass an existing resource name`,\n );\n }\n}\n\n/**\n * `order` with `name` inserted once. Without a placement flag an already listed\n * name keeps its position (re-adding must not reshuffle the project); with one,\n * the name moves to the requested spot.\n */\nfunction insertOrder(order: string[], name: string, options: AddAddonOptions): string[] {\n const rest = order.filter((entry) => entry !== name);\n\n if (options.first === true) return [name, ...rest];\n if (options.before === undefined && options.after === undefined) {\n // Re-adding an addon keeps its position; only a placement flag moves it.\n return order.includes(name) ? order : [...order, name];\n }\n\n const anchor = options.before ?? options.after;\n if (anchor === undefined) return [...rest, name];\n const index = rest.indexOf(anchor);\n if (index === -1) {\n throw new BuilderError(\n 'add.order-name',\n `\\`${anchor}\\` is not in \\`addons.order\\`; pass an existing resource name`,\n );\n }\n\n const at = options.before !== undefined ? index : index + 1;\n return [...rest.slice(0, at), name, ...rest.slice(at)];\n}\n\n/** `entries` with `entry` appended once, preserving the authored order. */\nfunction withEntry(entries: string[], entry: string): string[] {\n return entries.includes(entry) ? entries : [...entries, entry];\n}\n\n/**\n * The root `package.json` `dependencies`, or `{}` when the project has none.\n * A malformed manifest is `remove.manifest`: the name being removed cannot be\n * classified without it.\n */\nfunction projectDependencies(root: string): Record<string, unknown> {\n const file = join(root, 'package.json');\n let text: string;\n try {\n text = readFileSync(file, 'utf8');\n } catch (error) {\n if (isErrno(error, 'ENOENT')) return {};\n throw new BuilderError('remove.manifest', `cannot read \\`${file}\\`: ${errorMessage(error)}`);\n }\n\n let manifest: unknown;\n try {\n manifest = JSON.parse(text);\n } catch (error) {\n throw new BuilderError(\n 'remove.manifest',\n `invalid JSON in \\`${file}\\`: ${errorMessage(error)}`,\n );\n }\n if (typeof manifest !== 'object' || manifest === null || Array.isArray(manifest)) {\n throw new BuilderError('remove.manifest', `\\`${file}\\` must contain a JSON object`);\n }\n const dependencies = (manifest as Record<string, unknown>)['dependencies'];\n if (dependencies === undefined) return {};\n if (typeof dependencies !== 'object' || dependencies === null || Array.isArray(dependencies)) {\n throw new BuilderError('remove.manifest', `\\`dependencies\\` in \\`${file}\\` must be an object`);\n }\n return dependencies as Record<string, unknown>;\n}\n\n/**\n * The npm package to remove for `nameOrPackage`.\n *\n * A declared package name is used as-is; a resource name is mapped to the\n * package whose installed `package.json` marker names it. The scan reads\n * `node_modules` directly instead of resolving the whole dependency graph, so\n * one unrelated missing dependency cannot stop `remove` from cleaning up the\n * name it was asked to remove.\n */\nfunction npmPackageFor(root: string, nameOrPackage: string): string | undefined {\n const dependencies = projectDependencies(root);\n if (dependencies[nameOrPackage] !== undefined) return nameOrPackage;\n\n for (const packageName of Object.keys(dependencies)) {\n if (installedResourceName(root, packageName) === nameOrPackage) return packageName;\n }\n return undefined;\n}\n\n/** Resource name of the installed package `packageName`, from its own marker. */\nfunction installedResourceName(root: string, packageName: string): string | undefined {\n const dir = join(root, 'node_modules', ...packageName.split('/'));\n try {\n return readAddonPackage(dir).resource;\n } catch {\n return undefined;\n }\n}\n\nfunction isErrno(error: unknown, code: string): boolean {\n return (\n typeof error === 'object' &&\n error !== null &&\n (error as { code?: unknown }).code === code\n );\n}\n\n/**\n * A literal `addons.local` entry whose addon marker names `name`.\n *\n * Only a literal path is a candidate: a glob (`addons/*`) describes a set of\n * addons and removing it would take the others with it, so a project that\n * registers an addon only through a glob is not removable by name. The entry\n * `cybermp create addon` writes is literal, which is the case this handles.\n */\nfunction localAddonFor(\n root: string,\n patterns: readonly string[],\n name: string,\n): { entry: string; dir: string } | undefined {\n for (const entry of patterns) {\n if (/[*?[\\]{}()!]/.test(entry)) continue;\n const dir = resolve(root, entry);\n if (!isDirectory(dir)) continue;\n try {\n if (readAddonPackage(dir).resource === name) return { entry, dir };\n } catch {\n continue;\n }\n }\n return undefined;\n}\n\nfunction isDirectory(path: string): boolean {\n try {\n return statSync(path).isDirectory();\n } catch {\n return false;\n }\n}\n\n/** Real path of `path`, or `undefined` when it cannot be resolved. */\nfunction realDirectory(path: string): string | undefined {\n try {\n return realpathSync(path);\n } catch {\n return undefined;\n }\n}\n\n/**\n * True when one of `patterns` still resolves to `dir`.\n *\n * A glob the platform refuses counts as a reference: refusing to delete is the\n * safe answer when the config cannot be evaluated.\n */\nfunction isReferenced(root: string, patterns: readonly string[], dir: string): boolean {\n if (patterns.length === 0) return false;\n const target = realDirectory(dir);\n if (target === undefined) return false;\n\n let matches: string[];\n try {\n matches = globSync([...patterns], { cwd: root });\n } catch {\n return true;\n }\n return matches.some((match) => realDirectory(resolve(root, match)) === target);\n}\n\n/** True when `target` is `root` or a descendant of it. */\nfunction isInside(root: string, target: string): boolean {\n const path = relative(root, target);\n return path === '' || (!isAbsolute(path) && path !== '..' && !path.startsWith(`..${sep}`));\n}\n\nfunction errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n","/**\n * `renderTemplate` — copy a template tree into a project directory, filling in\n * its placeholders.\n *\n * A template is a directory of plain text files inside this package\n * (`templates/<name>/**`). Every regular file is read, each `__PLACEHOLDER__`\n * token is replaced with the caller's value and the result is written under\n * `destDir` at the same relative path. Two naming rules keep the tree portable:\n *\n * - a file or directory whose name starts with `_` is written with a leading\n * dot (`_gitignore` → `.gitignore`), because `npm pack` rewrites a real\n * `.gitignore` in a tarball and the template must ship exactly what it\n * renders;\n * - entries are visited in sorted order, so a render that fails half-way leaves\n * the same partial tree on every platform.\n *\n * Only regular files and directories are supported. A symlink would let a\n * template read outside the package, so it is refused instead of followed.\n *\n * Errors: `init.template-missing` for an unreadable source directory,\n * `init.template-invalid` for an unexpected entry or a token no value fills,\n * and `init.write` when the destination cannot be written.\n */\nimport type { Dirent } from 'node:fs';\nimport {\n mkdir,\n readdir,\n readFile,\n writeFile,\n} from 'node:fs/promises';\nimport { dirname, join } from 'node:path';\nimport { BuilderError } from '../errors.js';\n\n/** Tokens are `__UPPER_SNAKE__`; everything else is template text. */\nconst PLACEHOLDER = /__[A-Z][A-Z0-9_]*__/g;\n\n/**\n * Render `srcDir` into `destDir`, replacing `__NAME__` with `vars.NAME`.\n *\n * `vars` is keyed by the bare token name (`PROJECT_NAME` for\n * `__PROJECT_NAME__`); a token without a value is an error rather than a\n * literal left in the generated project, because a placeholder that reaches a\n * user is a broken scaffold.\n *\n * Files that already exist under `destDir` are overwritten — `init` refuses a\n * non-empty target on its own, and `--force` means \"render over it\".\n */\nexport async function renderTemplate(\n srcDir: string,\n destDir: string,\n vars: Record<string, string>,\n): Promise<void> {\n await mkdir(destDir, { recursive: true }).catch((error: unknown) => {\n throw writeError(destDir, error);\n });\n\n await walk(srcDir, destDir, '', vars);\n}\n\n/** Render one directory, then recurse into it. `relative` is the report path. */\nasync function walk(\n srcDir: string,\n destDir: string,\n relative: string,\n vars: Record<string, string>,\n): Promise<void> {\n for (const entry of await entries(srcDir, relative)) {\n const path = relative === '' ? entry.name : `${relative}/${entry.name}`;\n const from = join(srcDir, entry.name);\n const to = join(destDir, renderedName(entry.name));\n\n if (entry.isSymbolicLink()) {\n throw new BuilderError(\n 'init.template-invalid',\n `template entry \\`${path}\\` is a symbolic link; templates ship real files only`,\n );\n }\n\n if (entry.isDirectory()) {\n await mkdir(to, { recursive: true }).catch((error: unknown) => {\n throw writeError(to, error);\n });\n await walk(from, to, path, vars);\n continue;\n }\n\n if (!entry.isFile()) {\n throw new BuilderError(\n 'init.template-invalid',\n `template entry \\`${path}\\` is not a regular file`,\n );\n }\n\n let text: string;\n try {\n text = await readFile(from, 'utf8');\n } catch (error) {\n throw new BuilderError(\n 'init.template-missing',\n `cannot read template file \\`${path}\\`: ${errorMessage(error)}`,\n );\n }\n\n const rendered = substitute(text, vars, path);\n await mkdir(dirname(to), { recursive: true }).catch((error: unknown) => {\n throw writeError(to, error);\n });\n await writeFile(to, rendered).catch((error: unknown) => {\n throw writeError(to, error);\n });\n }\n}\n\n/** `srcDir`'s entries, sorted by name; a missing directory is `init.template-missing`. */\nasync function entries(srcDir: string, relative: string): Promise<Dirent[]> {\n try {\n const found = await readdir(srcDir, { withFileTypes: true });\n return found.sort((left, right) => (left.name < right.name ? -1 : left.name > right.name ? 1 : 0));\n } catch (error) {\n throw new BuilderError(\n 'init.template-missing',\n `cannot read template directory \\`${relative === '' ? srcDir : relative}\\`: ${errorMessage(error)}`,\n );\n }\n}\n\n/** `_gitignore` → `.gitignore`; every other name is kept as written. */\nfunction renderedName(name: string): string {\n return name.startsWith('_') ? `.${name.slice(1)}` : name;\n}\n\n/** Replace every provided token; a token left behind fails the render. */\nfunction substitute(text: string, vars: Record<string, string>, path: string): string {\n let rendered = text;\n for (const [name, value] of Object.entries(vars)) {\n rendered = rendered.split(`__${name}__`).join(value);\n }\n\n const missing = [...new Set(rendered.match(PLACEHOLDER) ?? [])];\n if (missing.length > 0) {\n throw new BuilderError(\n 'init.template-invalid',\n `template file \\`${path}\\` has no value for ${missing.join(', ')}`,\n );\n }\n return rendered;\n}\n\nfunction writeError(path: string, error: unknown): BuilderError {\n return new BuilderError('init.write', `cannot write \\`${path}\\`: ${errorMessage(error)}`);\n}\n\nfunction errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n","/**\n * Type-package pins — `templates/types.json` and the rules for choosing one\n * (spec §11.1).\n *\n * Every typed realm (client, server, browser) needs a package that declares its\n * `mp` global. The toolchain ships two independent sets of those packages:\n *\n * - `official` — the vendor packages, the default for every scaffold;\n * - `community` — the community rewrite, opt-in with `--types=community`.\n *\n * The sets are independent releases, so a version number means nothing across\n * them; only `tsc` decides whether a package is usable. `templates/types.json`\n * is the typecheck gate's output (`scripts/types-smoke.mjs`): it carries both\n * sets and a `blocked` table for community packages the gate proved broken.\n *\n * `--types` pins one set for everything:\n *\n * - `community` refuses a blocked realm (`types.blocked`) instead of silently\n * substituting another package — the caller asked for that set;\n * - `official` uses the official set for every realm and is what an absent\n * `--types` resolves to;\n * - `none` installs no type package and leaves the scaffold's `mp` global\n * declared as `unknown`.\n *\n * Errors, all `BuilderError` with a stable code: `types.file` when the table\n * cannot be read or lacks a set, `types.missing` when a set pins no version for\n * a realm, `types.blocked` when the community set is asked for a blocked realm.\n */\nimport { existsSync, readFileSync } from 'node:fs';\nimport { dirname, join } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { BuilderError } from '../errors.js';\n\n/** Realms that run against an `mp` global and therefore need a type package. */\nexport const TYPED_REALMS = ['client', 'server', 'browser'] as const;\n\n/** One realm with an `mp` global (`shared` is plain TypeScript). */\nexport type TypedRealm = (typeof TYPED_REALMS)[number];\n\n/** One published set of type packages. */\nexport type TypeSet = 'community' | 'official';\n\n/**\n * Which type packages to pin.\n *\n * `none` installs no package at all: the scaffold declares the `mp` global as\n * `unknown` so an addon that does not need the API still typechecks.\n */\nexport type TypesMode = TypeSet | 'none';\n\n/** Every mode `--types` accepts, in the order the CLI lists them. */\nexport const TYPES_MODES: readonly TypesMode[] = ['community', 'official', 'none'];\n\n/** Package scope of each set. */\nconst PREFIXES: Record<TypeSet, string> = {\n community: '@cybermp-community/',\n official: '@cybermp/',\n};\n\n/** The parsed table: both sets plus the gate's blocker notes. */\nexport interface TypeTable {\n community: Readonly<Record<string, string>>;\n official: Readonly<Record<string, string>>;\n /** Community package suffix → why the gate could not accept it. */\n blocked: Readonly<Record<string, string>>;\n}\n\n/** One resolved type package. */\nexport interface TypePin {\n realm: TypedRealm;\n /** Package name, e.g. `@cybermp/client-types`. */\n name: string;\n /** Version without a range operator, e.g. `2.7.1`. */\n version: string;\n /** The set the pin came from. */\n set: TypeSet;\n}\n\n/** Pins of the realms a caller asked for. */\nexport type TypePins = ReadonlyMap<TypedRealm, TypePin>;\n\n/**\n * Resolve one pin per requested realm.\n *\n * `mode` selects a set; `none` pins nothing and returns an empty map. Without a\n * mode every realm uses the official set — the community set is opt-in with\n * `--types=community` until the gate accepts it for every realm.\n *\n * Errors: `types.file`, `types.missing`, `types.blocked`.\n */\nexport function resolveTypePins(\n realms: readonly TypedRealm[],\n mode?: TypesMode,\n): TypePins {\n if (mode === 'none') return new Map();\n const table = readTypeTable();\n const pins = new Map<TypedRealm, TypePin>();\n for (const realm of realms) pins.set(realm, resolveTypePin(table, realm, mode));\n return pins;\n}\n\n/**\n * The pin for `realm`, or a `types.missing` error when the caller asked for it\n * without going through {@link resolveTypePins}.\n */\nexport function requireTypePin(pins: TypePins, realm: TypedRealm): TypePin {\n const pin = pins.get(realm);\n if (pin === undefined) {\n throw new BuilderError('types.missing', `no type package requested for realm \\`${realm}\\``);\n }\n return pin;\n}\n\n/** Read `templates/types.json` from this package. */\nexport function readTypeTable(): TypeTable {\n const file = join(packageRoot(), 'templates', 'types.json');\n return parseTypeTable(file, readText(file));\n}\n\n/**\n * The package directory, found by walking up from this module to the nearest\n * `package.json`.\n *\n * Works both from `src/` in the repository and from the bundled `dist/cli.js`,\n * where `templates/` sits one level above the bundle. Templates and pins are\n * always read from here, never from the project being scaffolded.\n */\nexport function packageRoot(): string {\n const start = dirname(fileURLToPath(import.meta.url));\n let dir = start;\n\n for (;;) {\n if (existsSync(join(dir, 'package.json'))) return dir;\n const parent = dirname(dir);\n if (parent === dir) {\n throw new BuilderError('types.file', `cannot find the package root above \\`${start}\\``);\n }\n dir = parent;\n }\n}\n\n/** Resolve one realm against an already-parsed table. */\nfunction resolveTypePin(table: TypeTable, realm: TypedRealm, mode?: TypeSet): TypePin {\n const suffix = `${realm}-types`;\n\n if (mode !== 'community') return pinFrom(table, realm, 'official', mode ?? 'default');\n\n const blocker = table.blocked[suffix];\n if (blocker !== undefined) {\n throw new BuilderError(\n 'types.blocked',\n `\\`${suffix}\\` ${table.community[suffix]} is blocked for \\`--types=community\\`: ${blocker}; ` +\n 'pass `--types=official` to use the official package',\n );\n }\n return pinFrom(table, realm, 'community', mode);\n}\n\n/** Build one pin from `set`, or fail with `types.missing`. */\nfunction pinFrom(\n table: TypeTable,\n realm: TypedRealm,\n set: TypeSet,\n requested: TypeSet | 'default',\n): TypePin {\n const suffix = `${realm}-types`;\n const version = table[set][suffix];\n if (version === undefined) {\n const how = requested === 'default' ? 'default' : `--types=${requested}`;\n throw new BuilderError(\n 'types.missing',\n `\\`templates/types.json\\` pins no \\`${suffix}\\` version in the \\`${set}\\` set (${how})`,\n );\n }\n return { realm, name: `${PREFIXES[set]}${suffix}`, version, set };\n}\n\n/** Turn the file text into a validated table. */\nfunction parseTypeTable(file: string, text: string): TypeTable {\n let document: unknown;\n try {\n document = JSON.parse(text);\n } catch (error) {\n throw new BuilderError('types.file', `cannot read \\`${file}\\`: ${errorMessage(error)}`);\n }\n\n const table = document as { community?: unknown; official?: unknown; blocked?: unknown } | null;\n return {\n community: setOf(table?.community, file, 'community'),\n official: setOf(table?.official, file, 'official'),\n blocked: setOf(table?.blocked ?? {}, file, 'blocked'),\n };\n}\n\n/** One version table of the file; every entry must be a non-empty string. */\nfunction setOf(value: unknown, file: string, name: string): Record<string, string> {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) {\n throw new BuilderError('types.file', `\\`${file}\\` needs a \\`${name}\\` object`);\n }\n\n const entries: Record<string, string> = {};\n for (const [key, version] of Object.entries(value as Record<string, unknown>)) {\n if (typeof version !== 'string' || version === '') {\n throw new BuilderError(\n 'types.file',\n `\\`${file}\\` has no string version for \\`${name}.${key}\\``,\n );\n }\n entries[key] = version;\n }\n return entries;\n}\n\nfunction readText(file: string): string {\n try {\n return readFileSync(file, 'utf8');\n } catch (error) {\n throw new BuilderError('types.file', `cannot read \\`${file}\\`: ${errorMessage(error)}`);\n }\n}\n\nfunction errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n","/**\n * `cybermp init` — scaffold a new project from a template shipped inside this\n * package (spec §10, §11).\n *\n * `init` replaces the deprecated `typescript-template` repository: the templates\n * live under `templates/` in this package, are rendered with the project's name\n * and the detected package manager, and are pinned to the type packages the\n * template's addon uses (`templates/types.json`, the file the typecheck gate\n * maintains).\n *\n * The order of operations is the contract:\n *\n * 1. the project name (the target directory's own name) is validated;\n * 2. the package manager, the template and the type versions are resolved;\n * 3. a target that exists is refused when it is not a directory or, unless\n * `force`, when it holds anything at all;\n * 4. the tree is rendered, then the root `package.json` is adjusted for the\n * package manager and the lint choice;\n * 5. `<pm> install` runs unless `install: false`.\n *\n * Steps 1–2 write nothing, and the target directory is not even created for a\n * project that fails them; a rejected invocation leaves the filesystem exactly\n * as it was. The package manager is `--pm` when given, otherwise the one the\n * target already declares, otherwise `pnpm` — an empty directory has nothing to\n * detect, and the shipped template is a pnpm workspace.\n *\n * The type packages come from `templates/types.json` (see `scaffold/types.ts`):\n * the official set by default, the community set with `--types=community`, or\n * no package at all with `--types=none`.\n *\n * Errors, all `BuilderError` with a stable code: `init.directory-not-empty`,\n * `init.not-directory`, `init.bad-name`, `init.package-manager`,\n * `init.template`, `init.template-missing`, `init.template-invalid`,\n * `init.types` (`--types=none` belongs to `create addon`), `init.write`, the\n * `types.*` codes, plus `pm.missing` / `pm.failed` from the install.\n */\nimport { spawnSync } from 'node:child_process';\nimport { existsSync, readFileSync, realpathSync } from 'node:fs';\nimport { mkdir, readdir, rm, stat, writeFile } from 'node:fs/promises';\nimport { basename, isAbsolute, join, relative, resolve, sep } from 'node:path';\nimport {\n detectPackageManager,\n PACKAGE_MANAGERS,\n runPackageManager,\n type PackageManager,\n} from '../addons/sources/npm.js';\nimport { BuilderError } from '../errors.js';\nimport { renderTemplate } from '../scaffold/render.js';\nimport {\n packageRoot,\n resolveTypePins,\n TYPED_REALMS,\n type TypePins,\n type TypesMode,\n type TypedRealm,\n} from '../scaffold/types.js';\n\n/** The template used when `--template` is not given. */\nexport const DEFAULT_TEMPLATE = 'project-default';\n\n/** Package name of a project whose directory has none (or `init .` at a root). */\nconst DEFAULT_PROJECT_NAME = 'cybermp-project';\n\n/** A template name is one lowercase directory inside `templates/`. */\nconst TEMPLATE_NAME = /^[a-z][a-z0-9-]*$/;\n\n/** A project name doubles as an npm package name (scoped addon names derive from it). */\nconst PROJECT_NAME = /^[a-z0-9][a-z0-9._-]*$/;\n\n/** Workspace members: every addon and every browser app inside one. */\nconst WORKSPACES = ['addons/*', 'addons/*/browser'];\n\n/** Options of {@link initProject}. */\nexport interface InitOptions {\n /** Project directory to create or fill; `.` is the current directory. */\n dir: string;\n /** Template directory name inside the package; defaults to `project-default`. */\n template?: string;\n /** Package manager override, as passed to `--pm`. */\n pm?: string;\n /** Run `<pm> install` after rendering. Defaults to `true`. */\n install?: boolean;\n /** Include the biome config and its dev dependency. Defaults to `true`. */\n lint?: boolean;\n /**\n * Which type-package set to pin (`--types`). Absent pins the official set;\n * `community` opts into the community packages, `none` into no package.\n */\n types?: TypesMode;\n /** Render into a non-empty directory, overwriting the files the template names. */\n force?: boolean;\n}\n\n/** What the install step did, for the CLI's next-steps output. */\nexport interface InitReport {\n /** Absolute path of the project root. */\n dir: string;\n /** Project name written into `package.json`. */\n name: string;\n /** Package manager the project was written for. */\n packageManager: PackageManager;\n /** Whether `<pm> install` ran. */\n installed: boolean;\n}\n\n/**\n * Scaffold a project into `options.dir`.\n *\n * See the module comment for the order of operations and the error contract.\n */\nexport async function initProject(options: InitOptions): Promise<InitReport> {\n const target = resolve(options.dir);\n const name = projectName(target);\n const lint = options.lint !== false;\n const installed = options.install !== false;\n\n if (options.types === 'none') {\n throw new BuilderError(\n 'init.types',\n '`--types=none` is for `cybermp create addon`: the project template ships typed addons, ' +\n 'so scaffold the project with a type set and use `create addon --types=none` for an ' +\n 'untyped addon inside it',\n );\n }\n\n // Everything that can reject the invocation is resolved before the target is\n // touched: an unsupported package manager or an unknown template must leave\n // the directory exactly as it was, so nothing is even created for it.\n const packageManager = initPackageManager(target, options.pm);\n const template = templateDirectory(options.template ?? DEFAULT_TEMPLATE);\n const pins = resolveTypePins(TYPED_REALMS, options.types);\n const vars = templateVars(name, packageManager, pins);\n\n await prepareTarget(target, options.force === true);\n await renderTemplate(template, target, vars);\n await finalizeProject(target, { packageManager, lint });\n\n if (installed) await runPackageManager(target, packageManager, ['install']);\n\n return { dir: target, name, packageManager, installed };\n}\n\n/**\n * The package manager `init` writes into the project.\n *\n * An explicit `--pm` wins and must be one the builder drives. Otherwise the\n * target's own manifest or lockfile decides, so `init --force` inside an\n * existing project keeps that project's manager; a brand-new directory has\n * nothing to detect and gets `pnpm`, which the shipped template's workspace\n * layout and lockfile examples assume.\n *\n * Errors: `init.package-manager` for an unsupported name, `pm.unsupported` when\n * the target's `packageManager` field names one.\n */\nexport function initPackageManager(dir: string, explicit?: string): PackageManager {\n if (explicit !== undefined) {\n if (!(PACKAGE_MANAGERS as readonly string[]).includes(explicit)) {\n throw new BuilderError(\n 'init.package-manager',\n `\\`${explicit}\\` is not one of ${PACKAGE_MANAGERS.join(', ')}`,\n );\n }\n return explicit as PackageManager;\n }\n\n return declaresPackageManagerState(dir) ? detectPackageManager(dir) : 'pnpm';\n}\n\n/**\n * The lines `cybermp init` prints after a successful scaffold: what was created\n * and the three commands that take the project to a running server.\n */\nexport function initNextSteps(report: InitReport): string {\n const installed = report.installed\n ? `installed dependencies with ${report.packageManager}`\n : `skipped the install; run \\`${report.packageManager} install\\` when ready`;\n return [\n `created ${report.name} in ${report.dir} (${installed})`,\n 'next steps:',\n ' cybermp download # fetch the CyberMP server binaries',\n ' cybermp build # build the addons and rewrite server.toml',\n ' cybermp run # start the server against this project',\n '',\n ].join('\\n');\n}\n\n/**\n * `target`'s project name: the directory name when it is a valid package name.\n *\n * `cybermp init my-gamemode` creates `./my-gamemode` named `my-gamemode`; with\n * `--force` inside an existing project the directory name is kept too, so a\n * re-scaffold never renames anything.\n *\n * Errors: `init.bad-name` when the directory name cannot be a package name —\n * the scaffold's addon packages are scoped after it.\n */\nfunction projectName(target: string): string {\n const name = basename(target);\n if (name === '' || name === '.') return DEFAULT_PROJECT_NAME;\n if (PROJECT_NAME.test(name)) return name;\n throw new BuilderError(\n 'init.bad-name',\n `\\`${name}\\` cannot be a project name: use lowercase letters, digits, \\`.\\`, \\`_\\` and ` +\n '`-`, or scaffold into a directory with such a name',\n );\n}\n\n/**\n * Create the target if it is missing; refuse it when it is a file or, unless\n * `force`, when it already holds anything at all.\n *\n * Nothing is written here beyond the directory itself, and only when it was\n * absent, so a rejected target stays exactly as it was found.\n */\nasync function prepareTarget(target: string, force: boolean): Promise<void> {\n let info;\n try {\n info = await stat(target);\n } catch (error) {\n if (isErrno(error, 'ENOENT')) {\n await mkdir(target, { recursive: true }).catch((failure: unknown) => {\n throw new BuilderError('init.write', `cannot create \\`${target}\\`: ${errorMessage(failure)}`);\n });\n return;\n }\n throw new BuilderError('init.write', `cannot inspect \\`${target}\\`: ${errorMessage(error)}`);\n }\n\n if (!info.isDirectory()) {\n throw new BuilderError('init.not-directory', `\\`${target}\\` exists and is not a directory`);\n }\n if (force) return;\n\n const entries = await readdir(target).catch((error: unknown) => {\n throw new BuilderError('init.write', `cannot read \\`${target}\\`: ${errorMessage(error)}`);\n });\n if (entries.length === 0) return;\n\n throw new BuilderError(\n 'init.directory-not-empty',\n `\\`${target}\\` is not empty; scaffold into an empty directory or pass --force to overwrite`,\n );\n}\n\n/**\n * Locate a template directory inside the package.\n *\n * The name is screened first (one lowercase segment), then both paths are\n * resolved and the template must stay inside the package's `templates/`\n * directory. A template is never taken from the current directory or from an\n * absolute path a caller supplies.\n *\n * Errors: `init.template` for a name that is not a template name or a directory\n * that resolves outside the package, `init.template-missing` when the directory\n * or the package itself cannot be found.\n */\nfunction templateDirectory(name: string): string {\n if (!TEMPLATE_NAME.test(name)) {\n throw new BuilderError(\n 'init.template',\n `\\`${name}\\` is not a template name; templates are lowercase directories shipped with the package`,\n );\n }\n\n const root = join(packageRoot(), 'templates');\n const dir = join(root, name);\n\n let realRoot: string;\n let realDir: string;\n try {\n realRoot = realpathSync(root);\n realDir = realpathSync(dir);\n } catch (error) {\n throw new BuilderError(\n 'init.template-missing',\n `no \\`${name}\\` template in \\`${root}\\`: ${errorMessage(error)}`,\n );\n }\n\n if (!isInside(realRoot, realDir)) {\n throw new BuilderError(\n 'init.template',\n `template \\`${name}\\` resolves outside the package's templates directory`,\n );\n }\n return realDir;\n}\n\n/** The package's own version, or `undefined` when its manifest is unreadable. */\nfunction ownVersion(root: string): string | undefined {\n try {\n const manifest: unknown = JSON.parse(readText(join(root, 'package.json')));\n if (typeof manifest !== 'object' || manifest === null) return undefined;\n const version = (manifest as Record<string, unknown>)['version'];\n return typeof version === 'string' && version !== '' ? version : undefined;\n } catch {\n return undefined;\n }\n}\n\n/**\n * The value of the project's `packageManager` field: `<pm>@<version>`.\n *\n * The version comes from the manager itself (`<pm> --version`), because a\n * guessed pin is worse than none and both corepack and pnpm validate the field.\n * When the binary is absent or answers something unexpected the bare name is\n * written: the builder's own detector accepts either form, and the install\n * reports `pm.missing` with the real reason.\n */\nfunction packageManagerPin(pm: PackageManager): string {\n const version = probeVersion(pm);\n return version === undefined ? pm : `${pm}@${version}`;\n}\n\n/** `<pm> --version`, normalised to `X.Y.Z`, or `undefined`. */\nfunction probeVersion(pm: PackageManager): string | undefined {\n const probe = spawnSync(pm, ['--version'], {\n encoding: 'utf8',\n timeout: 5000,\n shell: process.platform === 'win32',\n });\n if (probe.status !== 0 || typeof probe.stdout !== 'string') return undefined;\n const match = /^v?(\\d+\\.\\d+\\.\\d+)/.exec(probe.stdout.trim());\n return match?.[1];\n}\n\n/** The range the scaffold depends on the builder itself with. */\nfunction builderRange(root: string): string {\n const version = ownVersion(root);\n // An unreleased working copy (0.0.0) has no version to pin; the install's\n // lockfile is what fixes the version either way.\n return version === undefined || version === '0.0.0' ? 'latest' : `^${version}`;\n}\n\n/**\n * Values every template renders with, including one type package per realm.\n *\n * A project can be scaffolded with either published set and a realm can be left\n * untyped (`--types=none` on `create addon`), so the name and the version are\n * separate variables rather than one prefix applied to every declaration.\n */\nfunction templateVars(\n name: string,\n packageManager: PackageManager,\n pins: TypePins,\n): Record<string, string> {\n const root = packageRoot();\n const vars: Record<string, string> = {\n PROJECT_NAME: name,\n PACKAGE_MANAGER: packageManager,\n PACKAGE_MANAGER_PIN: packageManagerPin(packageManager),\n BUILDER_RANGE: builderRange(root),\n };\n\n for (const [realm, pin] of pins) {\n vars[`${realm.toUpperCase()}_TYPES_PACKAGE`] = pin.name;\n vars[`${realm.toUpperCase()}_TYPES_VERSION`] = pin.version;\n }\n return vars;\n}\n\n/**\n * Adjust the rendered tree for the package manager and the lint choice.\n *\n * Two template files are conditional and are simply not part of the project\n * when they do not apply; `package.json` gains `workspaces` for every manager\n * except pnpm (which reads `pnpm-workspace.yaml`) and loses the lint wiring when\n * `--no-lint` was passed.\n */\nasync function finalizeProject(\n target: string,\n setup: { packageManager: PackageManager; lint: boolean },\n): Promise<void> {\n const conditional: ReadonlyArray<{ path: string; keep: boolean }> = [\n { path: 'pnpm-workspace.yaml', keep: setup.packageManager === 'pnpm' },\n { path: 'biome.json', keep: setup.lint },\n ];\n\n for (const { path, keep } of conditional) {\n if (keep) continue;\n await rm(join(target, path), { force: true }).catch((error: unknown) => {\n throw new BuilderError('init.write', `cannot remove \\`${path}\\`: ${errorMessage(error)}`);\n });\n }\n\n await rewriteManifest(target, setup);\n}\n\n/** Apply the package-manager and lint choices to the rendered root manifest. */\nasync function rewriteManifest(\n target: string,\n setup: { packageManager: PackageManager; lint: boolean },\n): Promise<void> {\n const file = join(target, 'package.json');\n let manifest: Record<string, unknown>;\n try {\n const parsed: unknown = JSON.parse(readText(file));\n if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {\n throw new Error('the template package.json is not an object');\n }\n manifest = parsed as Record<string, unknown>;\n } catch (error) {\n throw new BuilderError('init.write', `cannot read \\`${file}\\`: ${errorMessage(error)}`);\n }\n\n if (setup.packageManager !== 'pnpm') {\n manifest['workspaces'] = [...WORKSPACES];\n }\n if (!setup.lint) {\n dropTableEntry(manifest, 'scripts', 'lint');\n dropTableEntry(manifest, 'devDependencies', '@biomejs/biome');\n }\n\n await writeFile(file, `${JSON.stringify(manifest, null, 2)}\\n`).catch((error: unknown) => {\n throw new BuilderError('init.write', `cannot write \\`${file}\\`: ${errorMessage(error)}`);\n });\n}\n\n/**\n * True when the target already has a manifest or a lockfile to detect from.\n *\n * A brand-new directory has none of them, and that is what selects the default\n * manager rather than a detection result.\n */\nfunction declaresPackageManagerState(dir: string): boolean {\n const markers = [\n 'package.json',\n 'pnpm-lock.yaml',\n 'yarn.lock',\n 'bun.lock',\n 'bun.lockb',\n 'package-lock.json',\n 'npm-shrinkwrap.json',\n ];\n return markers.some((marker) => existsSync(join(dir, marker)));\n}\n\n/** Delete `table[key]`, leaving every other value untouched. */\nfunction dropTableEntry(manifest: Record<string, unknown>, table: string, key: string): void {\n const value = manifest[table];\n if (typeof value === 'object' && value !== null && !Array.isArray(value)) {\n delete (value as Record<string, unknown>)[key];\n }\n}\n\n/** `isInside` for real paths: `target` is `root` or a descendant of it. */\nfunction isInside(root: string, target: string): boolean {\n const path = relative(root, target);\n return path === '' || (!isAbsolute(path) && path !== '..' && !path.startsWith(`..${sep}`));\n}\n\n/** One small file (a manifest or the type table); read synchronously. */\nfunction readText(file: string): string {\n return readFileSync(file, 'utf8');\n}\n\nfunction isErrno(error: unknown, code: string): boolean {\n return (\n typeof error === 'object' &&\n error !== null &&\n (error as { code?: unknown }).code === code\n );\n}\n\nfunction errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\n","/**\n * `cybermp create addon` — scaffold a local addon inside an existing project\n * (spec §10, §11.1).\n *\n * The addon is created at `<root>/addons/<name>` and is immediately a valid\n * local addon: a `package.json` with the `cybermp` marker, a `resource.toml`\n * whose scripts the build produces, the build entries the validator looks for,\n * one `tsconfig.json` per realm and the pinned type packages.\n *\n * Realms are the build targets the addon ships. `client` and `server` are the\n * defaults; `shared` holds code both sides import and has no type package of\n * its own; `browser` is the CEF page side. A realm's own `tsconfig.json`\n * extends the addon's root config because the `mp` global is typed differently\n * per realm — one program cannot include two declarations of it.\n *\n * The order of operations is the contract:\n *\n * 1. the project root and its package name are read, and the addon name is\n * validated (pattern, then the toolchain's reserved names);\n * 2. the realms are normalized, the type packages resolved from\n * `templates/types.json` (community, official, or the mixed default), and the\n * package manager resolved;\n * 3. the project's addons are resolved so a name another addon already uses is\n * refused, and an existing `addons/<name>` directory is refused;\n * 4. the tree is written and the addon is appended to `addons.local`;\n * 5. `<pm> install` runs at the project root unless `install: false`.\n *\n * Steps 1–3 write nothing, so a rejected invocation leaves the project exactly\n * as it was. The package name is `@<scope>/<name>` when the project is scoped\n * and `<project>-<name>` otherwise.\n *\n * Errors, all `BuilderError` with a stable code: `create.project`,\n * `create.bad-name`, `create.reserved-name`, `create.bad-realm`,\n * `create.duplicate-name`, `create.write`, the `types.*` codes of\n * `scaffold/types.ts`, plus the project config codes while the config is read\n * and `pm.missing` / `pm.failed` from the install.\n */\nimport { existsSync, readFileSync, realpathSync } from 'node:fs';\nimport { mkdir, writeFile } from 'node:fs/promises';\nimport { dirname, join, resolve } from 'node:path';\nimport {\n RESERVED_RESOURCE_NAMES,\n RESOURCE_NAME_PATTERN,\n} from '@cybermp-community/addon';\nimport { resolveLocalAddons } from '../addons/local.js';\nimport {\n detectPackageManager,\n runPackageManager,\n type PackageManager,\n} from '../addons/sources/npm.js';\nimport { loadConfigSync, writeAddonConfig } from '../config.js';\nimport { BuilderError } from '../errors.js';\nimport {\n requireTypePin,\n resolveTypePins,\n TYPED_REALMS,\n type TypePin,\n type TypePins,\n type TypesMode,\n} from '../scaffold/types.js';\n\n/** Every build target an addon may ship. */\nexport const ADDON_REALMS = ['client', 'server', 'shared', 'browser'] as const;\n\n/** One build target of an addon. */\nexport type AddonRealm = (typeof ADDON_REALMS)[number];\n\n/** The realms a bare `create addon` scaffolds. */\nconst DEFAULT_REALMS: readonly AddonRealm[] = ['client', 'server'];\n\n/** A realm with an `mp` global (`shared` is plain TypeScript). */\ntype TypedRealm = (typeof TYPED_REALMS)[number];\n\n/** The global each type package declares, per realm. */\nconst REALM_GLOBALS: Record<TypedRealm, string> = {\n client: 'MpClient',\n server: 'MpServer',\n browser: 'MpBrowser',\n};\n\n/** Options of {@link createAddon}. */\nexport interface CreateAddonOptions {\n /** Resource name and directory name under `<project>/addons`. */\n name: string;\n /** Project root the addon is created in; defaults to the current directory. */\n dir?: string;\n /** Realms to scaffold; defaults to client and server. */\n realms?: readonly AddonRealm[];\n /** Include the shared realm without having to name it in `realms`. */\n shared?: boolean;\n /** Run `<pm> install` after writing. Defaults to `true`. */\n install?: boolean;\n /** Package manager override, as passed to `--pm`. */\n pm?: PackageManager;\n /**\n * Which type-package set to pin (`--types`). Absent pins the official set;\n * `community` opts into the community packages, `none` installs no type\n * package and declares `mp` as `unknown`.\n */\n types?: TypesMode;\n}\n\n/**\n * Scaffold `options.name` into `<project>/addons` and return the new addon\n * directory.\n *\n * See the module comment for the order of operations and the error contract.\n */\nexport async function createAddon(options: CreateAddonOptions): Promise<string> {\n const root = projectRoot(options.dir ?? process.cwd());\n const projectName = readProjectName(root);\n\n validateName(options.name);\n const realms = normalizeRealms(options);\n const untyped = options.types === 'none';\n const pins = resolveTypePins(realms.filter(isTypedRealm), options.types);\n const packageManager = detectPackageManager(root, options.pm);\n\n const config = loadConfigSync(root);\n const addonDir = join(root, 'addons', options.name);\n await rejectExistingAddon(root, config.addons.local, options.name, addonDir);\n\n const packageName = addonPackageName(projectName, options.name);\n const files = addonFiles(options.name, packageName, projectName, realms, pins, untyped);\n await writeTree(addonDir, files);\n\n const entry = `./addons/${options.name}`;\n if (!config.addons.local.includes(entry)) {\n writeAddonConfig(root, { local: [...config.addons.local, entry] });\n }\n\n if (options.install !== false) {\n await runPackageManager(root, packageManager, ['install']);\n }\n\n return addonDir;\n}\n\n/**\n * Reject a name another addon in the project already uses, or a directory that\n * is already there but not (yet) a valid addon.\n *\n * Every local addon the config globs cover is resolved, so a name taken by an\n * addon outside `addons/*` is refused too. A *broken* addon in the project\n * fails this step with the addon package's own code rather than being skipped:\n * creating a second addon cannot be made safe without knowing the first one's\n * resource name.\n */\nasync function rejectExistingAddon(\n root: string,\n patterns: string[],\n name: string,\n addonDir: string,\n): Promise<void> {\n if (existsSync(addonDir)) {\n throw new BuilderError(\n 'create.duplicate-name',\n `\\`${addonDir}\\` already exists; pick another name or remove the directory`,\n );\n }\n\n const addons = await resolveLocalAddons(root, patterns);\n const taken = addons.find((addon) => addon.name === name);\n if (taken !== undefined) {\n throw new BuilderError(\n 'create.duplicate-name',\n `\\`${name}\\` is already the resource of the addon in \\`${taken.dir}\\`; pick another name`,\n );\n }\n}\n\n/** Resolve the project root; a path that is not a directory is `create.project`. */\nfunction projectRoot(dir: string): string {\n try {\n return realpathSync(resolve(dir));\n } catch (error) {\n throw new BuilderError(\n 'create.project',\n `\\`${resolve(dir)}\\` is not a project directory: ${errorMessage(error)}`,\n );\n }\n}\n\n/**\n * The project's package name, which decides the addon's package name.\n *\n * A project without a readable `package.json` is `create.project`: the addon's\n * package name and its dependency placement both derive from it.\n */\nfunction readProjectName(root: string): string {\n const file = join(root, 'package.json');\n let document: unknown;\n try {\n document = JSON.parse(readFileSync(file, 'utf8'));\n } catch (error) {\n throw new BuilderError(\n 'create.project',\n `\\`${root}\\` is not a project: cannot read \\`package.json\\`: ${errorMessage(error)}`,\n );\n }\n\n const name = (document as { name?: unknown } | null)?.name;\n if (typeof name !== 'string' || name === '') {\n throw new BuilderError(\n 'create.project',\n `\\`${file}\\` must have a \\`name\\` to name the addon package after`,\n );\n }\n return name;\n}\n\n/** Validate the resource name: the addon contract's pattern, then the reserved list. */\nfunction validateName(name: string): void {\n if (!RESOURCE_NAME_PATTERN.test(name)) {\n throw new BuilderError(\n 'create.bad-name',\n `\\`${name}\\` is not an addon name: use lowercase letters, digits, \\`_\\` and \\`-\\`, ` +\n `starting with a letter or digit (${RESOURCE_NAME_PATTERN.source})`,\n );\n }\n if (RESERVED_RESOURCE_NAMES.includes(name)) {\n throw new BuilderError(\n 'create.reserved-name',\n `\\`${name}\\` is reserved by the toolchain; pick another name`,\n );\n }\n}\n\n/**\n * The realms to scaffold, in declaration order.\n *\n * `--shared` is shorthand for adding `shared` to whichever realms were named,\n * so `--realms=client --shared` and `--realms=client,shared` are the same.\n */\nfunction normalizeRealms(options: CreateAddonOptions): AddonRealm[] {\n const requested = options.realms ?? DEFAULT_REALMS;\n for (const realm of requested) {\n if (!ADDON_REALMS.includes(realm)) {\n throw new BuilderError(\n 'create.bad-realm',\n `\\`${realm}\\` is not an addon realm; use ${ADDON_REALMS.join(', ')}`,\n );\n }\n }\n\n const wanted = new Set<AddonRealm>(requested);\n if (options.shared === true) wanted.add('shared');\n if (wanted.size === 0) {\n throw new BuilderError('create.bad-realm', `an addon needs at least one realm`);\n }\n return ADDON_REALMS.filter((realm) => wanted.has(realm));\n}\n\n/** The `@<scope>/<name>` or `<project>-<name>` package name of the addon. */\nfunction addonPackageName(projectName: string, name: string): string {\n const scope = /^@([^/]+)\\//.exec(projectName)?.[1];\n return scope === undefined ? `${projectName}-${name}` : `@${scope}/${name}`;\n}\n\n/**\n * The addon tree as `relative path → file text`.\n *\n * Building it before writing anything keeps a failed scaffold from leaving a\n * half-written package, and makes the shape of a generated addon one readable\n * place. With `untyped` (`--types=none`) no type package is declared and every\n * realm's `global.d.ts` declares `mp` as `unknown`.\n */\nfunction addonFiles(\n name: string,\n packageName: string,\n projectName: string,\n realms: readonly AddonRealm[],\n pins: TypePins,\n untyped: boolean,\n): Map<string, string> {\n const files = new Map<string, string>();\n const document = manifest(name, packageName, realms, pins);\n files.set('package.json', `${JSON.stringify(document, null, 2)}\\n`);\n files.set('resource.toml', manifestToml(name, projectName, realms));\n files.set('tsconfig.json', `${JSON.stringify(rootTsconfig(), null, 2)}\\n`);\n\n for (const realm of realms) {\n files.set(`${realm}/tsconfig.json`, `${JSON.stringify(realmTsconfig(), null, 2)}\\n`);\n files.set(`${realm}/src/index.ts`, stub(name, realm, realms, untyped));\n if (isTypedRealm(realm)) {\n files.set(\n `${realm}/src/global.d.ts`,\n untyped\n ? untypedGlobalDeclaration()\n : globalDeclaration(realm, requireTypePin(pins, realm)),\n );\n }\n }\n return files;\n}\n\n/** `package.json` of the generated addon. */\nfunction manifest(\n name: string,\n packageName: string,\n realms: readonly AddonRealm[],\n pins: TypePins,\n): Record<string, unknown> {\n const build: Record<string, unknown> = {};\n if (realms.includes('client')) build['client'] = { entry: 'client/src/index.ts' };\n if (realms.includes('server')) build['server'] = { entry: 'server/src/index.ts' };\n\n const devDependencies: Record<string, string> = {};\n for (const pin of pins.values()) {\n devDependencies[pin.name] = `^${pin.version}`;\n }\n\n const typecheck = realms.map((realm) => `tsc --noEmit -p ${realm}`).join(' && ');\n const document: Record<string, unknown> = {\n name: packageName,\n version: '0.1.0',\n private: true,\n description: `CyberMP addon \\`${name}\\`.`,\n type: 'module',\n scripts: { typecheck },\n cybermp: { resource: name, build },\n };\n if (Object.keys(devDependencies).length > 0) document['devDependencies'] = devDependencies;\n return document;\n}\n\n/**\n * `resource.toml` of the generated addon.\n *\n * Only the scripts the build actually produces are declared: `client_script`\n * and `server_script` point at the bundle outputs, while `shared` is source the\n * two sides import and has no manifest key. `browser` is source for the CEF\n * page and declares no `cef_url` until the addon ships a page.\n */\nfunction manifestToml(\n name: string,\n projectName: string,\n realms: readonly AddonRealm[],\n): string {\n const lines = [\n '#:schema https://schemas.cyber.mp/resource/schema.json',\n '',\n `# ${name}: generated by \\`cybermp create addon\\`.`,\n ];\n if (realms.includes('client')) lines.push('client_script = [\"./client.js\"]');\n if (realms.includes('server')) lines.push('server_script = [\"./server.js\"]');\n lines.push('', `author = ${JSON.stringify(projectName)}`, 'version = \"0.1.0\"', '');\n return lines.join('\\n');\n}\n\n/**\n * The addon's root tsconfig: the compiler options every realm program shares.\n *\n * `files` is empty so running `tsc` at the addon root has no program of its\n * own — the realm configs supply `include`. Extending the package base config\n * keeps the target, lib and strictness in one place.\n */\nfunction rootTsconfig(): Record<string, unknown> {\n return {\n extends: '@cybermp-community/resource-builder/tsconfig.base.json',\n compilerOptions: {\n module: 'ESNext',\n moduleResolution: 'bundler',\n skipLibCheck: true,\n noEmit: true,\n },\n files: [],\n };\n}\n\n/** One realm's program: its own sources, inheriting the root options. */\nfunction realmTsconfig(): Record<string, unknown> {\n return { extends: '../tsconfig.json', include: ['src/**/*.ts'] };\n}\n\n/** The realm's `global.d.ts`: the `mp` global typed by the realm's pinned package. */\nfunction globalDeclaration(realm: TypedRealm, pin: TypePin): string {\n const global = REALM_GLOBALS[realm];\n const lines = [\n `import type { ${global} } from '${pin.name}';`,\n '',\n 'declare global {',\n ` const mp: ${global};`,\n '}',\n ];\n // The browser page is a module of its own; `export {}` makes that explicit.\n if (realm === 'browser') lines.push('', 'export {};');\n lines.push('');\n return lines.join('\\n');\n}\n\n/**\n * The realm's `global.d.ts` with `--types=none`: no type package is installed,\n * so `mp` is declared as `unknown`.\n *\n * The stub exists so `mp` still resolves (without it every use is `TS2304`);\n * using it requires an explicit cast, which is the point of asking for no\n * packages.\n */\nfunction untypedGlobalDeclaration(): string {\n const lines = [\n '// `--types=none`: no type package is installed, so `mp` is untyped.',\n '// Cast it where you use it, or scaffold again with a type package.',\n 'declare global {',\n ' const mp: unknown;',\n '}',\n ];\n // `declare global` needs a module to augment, so the file exports nothing.\n lines.push('', 'export {};');\n lines.push('');\n return lines.join('\\n');\n}\n\n/**\n * A typed entry stub for one realm; it compiles and does nothing else.\n *\n * With the `shared` realm, the client and server stubs import it, so the\n * scaffold shows the wiring instead of leaving `shared/src` dead code — the\n * import is relative because the addon is one package, not a workspace of its\n * own.\n *\n * With `untyped` (`--types=none`) the `mp` global is `unknown`, so the client\n * and server stubs cast it to the one event method they use; the scaffold still\n * typechecks and still shows where the API is reached.\n */\nfunction stub(\n name: string,\n realm: AddonRealm,\n realms: readonly AddonRealm[],\n untyped: boolean,\n): string {\n const sharedImport = realms.includes('shared')\n ? [\"import { greeting } from '../../shared/src/index.js';\", '']\n : [];\n const sharedBody = ' console.log(greeting());';\n\n switch (realm) {\n case 'client':\n return [\n ...sharedImport,\n `console.log('[${name}] client initialized');`,\n '',\n ...eventStub(\n 'resourceStart',\n '',\n realms.includes('shared') ? sharedBody : ` console.log('[${name}] client started');`,\n untyped,\n ),\n '',\n ].join('\\n');\n case 'server':\n return [\n ...sharedImport,\n `console.log('[${name}] server initialized');`,\n '',\n ...eventStub(\n 'playerConnected',\n 'playerId: number',\n realms.includes('shared')\n ? sharedBody\n : ` console.log(\\`[${name}] player \\${playerId} connected\\`);`,\n untyped,\n ),\n '',\n ].join('\\n');\n case 'browser':\n return [\n `console.log('[${name}] browser initialized');`,\n '',\n ].join('\\n');\n case 'shared':\n return [\n '/** Values the client and server both import. */',\n `export const ADDON_NAME = '${name}';`,\n '',\n 'export function greeting(): string {',\n ' return `[${ADDON_NAME}] ready`;',\n '}',\n '',\n ].join('\\n');\n }\n}\n\n/**\n * The `mp.events.on(...)` block of a client or server stub.\n *\n * A typed scaffold calls the global directly. An untyped one first casts the\n * `unknown` global to just the shape it uses, so `--types=none` stays\n * type-correct without pretending `mp` has a type.\n */\nfunction eventStub(\n event: string,\n parameters: string,\n body: string,\n untyped: boolean,\n): string[] {\n if (!untyped) {\n return [`mp.events.on('${event}', (${parameters}) => {`, body, '});'];\n }\n return [\n '// `--types=none`: `mp` is `unknown`; cast it to the API you use.',\n 'const api = mp as {',\n ' events: {',\n ` on(event: '${event}', handler: (${parameters}) => void): void;`,\n ' };',\n '};',\n '',\n `api.events.on('${event}', (${parameters}) => {`,\n body,\n '});',\n ];\n}\n\nfunction isTypedRealm(realm: AddonRealm): realm is TypedRealm {\n return (TYPED_REALMS as readonly string[]).includes(realm);\n}\n\n/** Write every file of the addon tree; I/O failures are `create.write`. */\nasync function writeTree(base: string, files: Map<string, string>): Promise<void> {\n try {\n await mkdir(base, { recursive: true });\n } catch (error) {\n throw new BuilderError('create.write', `cannot create \\`${base}\\`: ${errorMessage(error)}`);\n }\n\n for (const [path, content] of files) {\n const target = join(base, path);\n try {\n await mkdir(dirname(target), { recursive: true });\n await writeFile(target, content);\n } catch (error) {\n throw new BuilderError('create.write', `cannot write \\`${target}\\`: ${errorMessage(error)}`);\n }\n }\n}\n\nfunction errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n","/**\n * `cybermp download` — fetch the CyberMP server binaries into the work\n * directory.\n *\n * The server is distributed as platform zips on GitHub Releases\n * (`Cyber-MP/CyberMP-Server-Releases`): `cybermp-server-win64-build-<tag>.zip`\n * and `cybermp-server-linux-build-<tag>.zip`. One tag is used for every\n * platform, so a run resolves `latest` once — through\n * `api.github.com/repos/.../releases/latest` — and then downloads the same tag\n * everywhere.\n *\n * The tag is `version`, else `CYBERMP_VERSION`, else `latest`. The platform is\n * always the one requested, never the host: a Linux machine can fetch the\n * Windows build, which is what `server.platforms` exists for.\n *\n * Layout: every build is unpacked into `<workDir>/mp/<win|linux>/` and marked\n * with `<workDir>/mp/<platform>/.cybermp-version` holding the tag it came from.\n * The Linux binary is made executable (`0o755`) because zip archives carry no\n * usable permission bits for it.\n *\n * Integrity: CyberMP publishes no sha256 manifest, so a download is trusted\n * only when (a) the bytes received match the `content-length` the host\n * declared and (b) the archive unpacks. Both checks run before anything is\n * moved into place. A host that declares no length (a chunked mirror) skips\n * only check (a) — the unpack still has to succeed.\n *\n * Atomicity: each platform is unpacked into a temporary directory beside its\n * target and moved in only after the archive arrived whole and unpacked. A\n * failed download therefore leaves no half-unpacked tree — and never destroys\n * the build already installed. Leftovers a crashed run left behind (a\n * `.previous-*` tree or a `.<platform>-*` staging directory) are swept when the\n * download starts, so they can neither accumulate nor hide a build.\n *\n * `base` (or `CYBERMP_DOWNLOAD_BASE`) replaces the download root for mirrors\n * and offline caches; `apiBase` replaces the GitHub API root, so both can be\n * pointed at a local server in tests.\n *\n * Errors: `server.platforms` (nothing requested), `server.version` (the latest\n * release cannot be resolved), `server.download` (network, HTTP status, or the\n * body could not be saved), `server.integrity` (truncated body), and\n * `server.extract` (unreadable archive, or an entry that is not a plain file or\n * directory inside the build — traversal, absolute path, empty name, symlink).\n */\n\nimport { randomUUID } from 'node:crypto';\nimport { createWriteStream, existsSync } from 'node:fs';\nimport { chmod, mkdir, mkdtemp, readdir, readFile, rename, rm, writeFile } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { Readable, Transform } from 'node:stream';\nimport { pipeline } from 'node:stream/promises';\nimport AdmZip from 'adm-zip';\nimport { BuilderError } from '../errors.js';\nimport { isSymlinkEntry } from '../zip.js';\n\n/** The release repository every server build comes from. */\nconst RELEASES_REPO = 'Cyber-MP/CyberMP-Server-Releases';\n\n/** The GitHub API root used to resolve `latest`. */\nconst GITHUB_API = 'https://api.github.com';\n\n/** The download root GitHub serves release assets from. */\nconst GITHUB_DOWNLOAD = `https://github.com/${RELEASES_REPO}/releases/download`;\n\n/** Environment variable pinning the release tag. */\nconst VERSION_ENV = 'CYBERMP_VERSION';\n\n/** Environment variable replacing the download root (mirrors, offline caches). */\nconst BASE_ENV = 'CYBERMP_DOWNLOAD_BASE';\n\n/** The build targets CyberMP ships binaries for. */\nexport type ServerPlatform = 'win' | 'linux';\n\n/** Marker file written into `<workDir>/mp/<platform>/`; holds the tag. */\nexport const VERSION_MARKER = '.cybermp-version';\n\n/** Name of the Linux server binary inside an unpacked build. */\nexport const SERVER_BINARY = 'cybermp-server';\n\n/** Name of the Windows server binary inside an unpacked build. */\nexport const SERVER_BINARY_WIN = 'cybermp-server.exe';\n\n/** The tag `latest` stands for before it is resolved. */\nconst LATEST = 'latest';\n\n/**\n * The leftovers a crashed run can leave under `<workDir>/mp/`: a tree moved\n * aside by {@link replaceTree} and a staging directory from\n * {@link downloadPlatform}. Only these shapes are swept; anything else in `mp/`\n * belongs to someone else.\n */\nconst STALE_ENTRY = /^(?:\\.previous-|\\.(?:win|linux)-)/;\n\n/** Options for {@link downloadServer}. */\nexport interface DownloadOptions {\n /** Build work directory; builds land under `<workDir>/mp/<platform>`. */\n workDir: string;\n /** Release tag to install; `version`, else `CYBERMP_VERSION`, else latest. */\n version?: string;\n /** Platforms to install; the caller decides, never the host. */\n platforms: ServerPlatform[];\n /** Download root override, e.g. a mirror or a local server in tests. */\n base?: string;\n /** GitHub API root override, used only to resolve `latest`. */\n apiBase?: string;\n}\n\n/**\n * Download the requested server builds into `<workDir>/mp/<platform>`.\n *\n * Platforms are fetched one after another; a failure stops the run and leaves\n * the platforms already installed untouched. The tag is resolved once, so a\n * multi-platform run installs one consistent version.\n *\n * Errors: `server.platforms`, `server.version`, `server.download`,\n * `server.integrity`, `server.extract`.\n */\nexport async function downloadServer(opts: DownloadOptions): Promise<void> {\n const platforms = [...new Set(opts.platforms)];\n if (platforms.length === 0) {\n throw new BuilderError(\n 'server.platforms',\n 'no server platform to download; set `server.platforms` in cybermp.config.json ' +\n 'or pass `--platform=<win|linux>`',\n );\n }\n\n // A crashed earlier run may have left a tree moved aside or a staging\n // directory behind. Sweeping before anything else keeps that debris from\n // accumulating and, more importantly, from hiding a build under a\n // `.previous-*` name where no later run would look.\n await sweepStaleTrees(join(opts.workDir, 'mp'));\n\n const apiBase = trimTrailingSlash(opts.apiBase ?? GITHUB_API);\n const tag = await resolveTag(opts.version, apiBase);\n const base = trimTrailingSlash(opts.base ?? process.env[BASE_ENV] ?? GITHUB_DOWNLOAD);\n\n for (const platform of platforms) {\n await downloadPlatform(opts.workDir, platform, tag, base);\n }\n}\n\n/**\n * Remove the `.previous-*` and `.<platform>-*` entries a crashed run can leave\n * under `mpRoot`.\n *\n * Best effort: the directory may not exist yet, and a debris tree that cannot\n * be removed must not fail an otherwise good download — the new build is\n * installed beside it either way.\n */\nasync function sweepStaleTrees(mpRoot: string): Promise<void> {\n let entries: string[];\n try {\n entries = await readdir(mpRoot);\n } catch {\n return;\n }\n\n for (const name of entries) {\n if (!STALE_ENTRY.test(name)) continue;\n await rm(join(mpRoot, name), { recursive: true, force: true }).catch(() => undefined);\n }\n}\n\n/** The directory one platform's build occupies. */\nexport function serverDir(workDir: string, platform: ServerPlatform): string {\n return join(workDir, 'mp', platform);\n}\n\n/** The platform the host runs, matching the only two targets CyberMP ships. */\nexport function hostPlatform(): ServerPlatform {\n return process.platform === 'win32' ? 'win' : 'linux';\n}\n\n/** Resolve the tag to install: explicit version, then env, then the API. */\nasync function resolveTag(version: string | undefined, apiBase: string): Promise<string> {\n const requested = version ?? process.env[VERSION_ENV] ?? LATEST;\n if (requested !== LATEST) return requested;\n\n const url = `${apiBase}/repos/${RELEASES_REPO}/releases/latest`;\n let response: Response;\n try {\n response = await fetch(url);\n } catch (error) {\n throw new BuilderError(\n 'server.version',\n `cannot resolve the latest server release from \\`${url}\\`: ${errorMessage(error)}; ` +\n 'pass `--version=<tag>` to pin one',\n );\n }\n if (!response.ok) {\n throw new BuilderError(\n 'server.version',\n `\\`${url}\\` answered ${response.status} ${response.statusText}; ` +\n 'pass `--version=<tag>` to pin a release',\n );\n }\n\n let body: unknown;\n try {\n body = await response.json();\n } catch (error) {\n throw new BuilderError(\n 'server.version',\n `the latest server release response is not valid JSON: ${errorMessage(error)}`,\n );\n }\n\n const tag = (body as { tag_name?: unknown } | null)?.tag_name;\n if (typeof tag !== 'string' || tag === '') {\n throw new BuilderError(\n 'server.version',\n `the latest server release response carries no \\`tag_name\\`; ` +\n 'pass `--version=<tag>` to pin a release',\n );\n }\n return tag;\n}\n\n/**\n * Download and install one platform.\n *\n * Everything happens inside a staging directory under `<workDir>/mp/`, so the\n * archive, the unpacked files and the previous installation all live on one\n * filesystem; the final move is a rename and a failure removes the staging\n * directory.\n */\nasync function downloadPlatform(\n workDir: string,\n platform: ServerPlatform,\n tag: string,\n base: string,\n): Promise<void> {\n const mpRoot = join(workDir, 'mp');\n await mkdir(mpRoot, { recursive: true });\n\n const staging = await mkdtemp(join(mpRoot, `.${platform}-`));\n try {\n const asset = assetName(platform, tag);\n const archive = join(staging, asset);\n const payload = join(staging, 'payload');\n await mkdir(payload, { recursive: true });\n\n await fetchArchive(\n `${base}/${encodeURIComponent(tag)}/${encodeURIComponent(asset)}`,\n archive,\n platform,\n tag,\n );\n extractArchive(archive, payload, platform, tag);\n await finishBuild(payload, platform, tag);\n await replaceTree(payload, serverDir(workDir, platform), mpRoot);\n } finally {\n await rm(staging, { recursive: true, force: true });\n }\n}\n\n/** The release asset name for `platform` at `tag`. */\nfunction assetName(platform: ServerPlatform, tag: string): string {\n const build = platform === 'win' ? 'win64' : 'linux';\n return `cybermp-server-${build}-build-${tag}.zip`;\n}\n\n/**\n * Stream `url` into `file`, checking the declared `content-length`.\n *\n * The body is written to a file the caller owns; a short or failed transfer\n * throws and leaves the caller to discard the staging directory. `fetch`\n * follows redirects, which GitHub asset URLs need.\n */\nasync function fetchArchive(\n url: string,\n file: string,\n platform: ServerPlatform,\n tag: string,\n): Promise<void> {\n const label = `the ${platform} server build ${tag}`;\n let response: Response;\n try {\n response = await fetch(url);\n } catch (error) {\n throw new BuilderError(\n 'server.download',\n `cannot reach ${url} for ${label}: ${errorMessage(error)}`,\n );\n }\n\n if (!response.ok) {\n throw new BuilderError(\n 'server.download',\n `${url} answered ${response.status} ${response.statusText} for ${label}; ` +\n 'check `server.version` and `CYBERMP_DOWNLOAD_BASE`',\n );\n }\n\n const body = response.body;\n if (body === null) {\n throw new BuilderError('server.download', `the download of ${label} returned no body`);\n }\n\n const declared = declaredLength(response);\n let received = 0;\n try {\n await pipeline(\n Readable.fromWeb(body as unknown as Parameters<typeof Readable.fromWeb>[0]),\n new Transform({\n transform(chunk: Buffer, _encoding, callback) {\n received += chunk.length;\n callback(null, chunk);\n },\n }),\n createWriteStream(file),\n );\n } catch (error) {\n throw new BuilderError('server.download', `cannot save ${label}: ${errorMessage(error)}`);\n }\n\n if (declared !== undefined && received !== declared) {\n throw new BuilderError(\n 'server.integrity',\n `${label} declared ${declared} bytes but ${received} arrived; retry the download`,\n );\n }\n}\n\n/**\n * The `content-length` a response declares, or `undefined` when the host does\n * not say (or says it for an encoded body, where the two lengths differ).\n *\n * A host that sends no length is not an error: CyberMP publishes no sha256\n * manifest, so the only integrity signal available is the declared length and a\n * successful unpack, and a chunked response simply has no length to compare.\n * The body still has to unpack, which is checked next.\n */\nfunction declaredLength(response: Response): number | undefined {\n const encoding = response.headers.get('content-encoding');\n if (encoding !== null && encoding.toLowerCase() !== 'identity') return undefined;\n\n const header = response.headers.get('content-length');\n if (header === null) return undefined;\n const value = Number(header);\n return Number.isSafeInteger(value) && value >= 0 ? value : undefined;\n}\n\n/** Unpack a zip at `file` into `target`, refusing entries that would escape. */\nfunction extractArchive(file: string, target: string, platform: ServerPlatform, tag: string): void {\n let archive: AdmZip;\n try {\n archive = new AdmZip(file);\n } catch (error) {\n throw new BuilderError(\n 'server.extract',\n `the ${platform} server build ${tag} is not a readable zip: ${errorMessage(error)}`,\n );\n }\n\n for (const entry of archive.getEntries()) {\n safeEntry(entry, platform, tag);\n }\n\n try {\n archive.extractAllTo(target, true);\n } catch (error) {\n throw new BuilderError(\n 'server.extract',\n `cannot extract the ${platform} server build ${tag}: ${errorMessage(error)}`,\n );\n }\n}\n\n/**\n * Refuse anything that is not a plain file or directory inside the build:\n * absolute entries, `..` segments, empty paths and symlink entries. Screening\n * runs over every entry before extraction, so a bad archive never touches the\n * disk — the same contract `release.ts` applies to addon zips.\n */\nfunction safeEntry(entry: AdmZip.IZipEntry, platform: ServerPlatform, tag: string): void {\n const name = entry.entryName;\n const posix = name.replace(/\\\\/g, '/');\n const label = `the ${platform} server build ${tag}`;\n\n if (posix.startsWith('/') || posix.startsWith('//') || /^[a-zA-Z]:\\//.test(posix)) {\n throw new BuilderError('server.extract', `${label} contains the absolute path \\`${name}\\``);\n }\n\n const segments = posix.split('/').filter((segment) => segment !== '' && segment !== '.');\n if (segments.includes('..')) {\n throw new BuilderError(\n 'server.extract',\n `${label} contains \\`${name}\\`, which escapes the build directory`,\n );\n }\n if (segments.length === 0) {\n throw new BuilderError('server.extract', `${label} contains an entry with no path`);\n }\n if (isSymlinkEntry(entry)) {\n throw new BuilderError(\n 'server.extract',\n `${label} contains the symlink \\`${name}\\`; a server build may hold plain files and ` +\n 'directories only',\n );\n }\n}\n\n/**\n * Prepare the unpacked build: make the Linux binary executable and write the\n * version marker the rest of the toolchain reads.\n */\nasync function finishBuild(payload: string, platform: ServerPlatform, tag: string): Promise<void> {\n if (platform === 'linux') {\n const binary = join(payload, SERVER_BINARY);\n if (existsSync(binary)) await chmod(binary, 0o755);\n }\n await writeFile(join(payload, VERSION_MARKER), `${tag}\\n`);\n}\n\n/**\n * Move `payload` onto `target`, keeping the installed build until the new one\n * is in place.\n *\n * The old tree is renamed aside to a sibling of the target — not into the\n * staging directory, which is deleted in a `finally` — and restored if the swap\n * fails, so even a failed restore leaves the previous build recoverable under\n * its `.previous-*` name inside the work directory. Every step is a rename on\n * one filesystem.\n */\nasync function replaceTree(payload: string, target: string, mpRoot: string): Promise<void> {\n let previous: string | undefined;\n if (existsSync(target)) {\n previous = join(mpRoot, `.previous-${randomUUID()}`);\n try {\n await rename(target, previous);\n } catch (error) {\n throw new BuilderError(\n 'server.extract',\n `cannot move the previous build at \\`${target}\\` aside: ${errorMessage(error)}`,\n );\n }\n }\n\n try {\n await rename(payload, target);\n } catch (error) {\n if (previous !== undefined) {\n // Restore the old build; if even that fails, the tree is still under its\n // `.previous-*` name inside the work directory.\n await rename(previous, target).catch(() => undefined);\n }\n throw new BuilderError(\n 'server.extract',\n `cannot install the build at \\`${target}\\`: ${errorMessage(error)}`,\n );\n }\n\n if (previous !== undefined) {\n // The new build is already in place; failing to delete the old copy must\n // not fail the install.\n await rm(previous, { recursive: true, force: true }).catch(() => undefined);\n }\n}\n\n/** Read the tag installed for `platform`, or `undefined` when there is none. */\nexport async function readInstalledVersion(\n workDir: string,\n platform: ServerPlatform,\n): Promise<string | undefined> {\n try {\n return (await readFile(join(serverDir(workDir, platform), VERSION_MARKER), 'utf8')).trim();\n } catch {\n return undefined;\n }\n}\n\nfunction trimTrailingSlash(value: string): string {\n return value.replace(/\\/+$/, '');\n}\n\nfunction errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n","/**\n * `cybermp run` — start the downloaded CyberMP server against the project.\n *\n * The server reads `server.toml` from its working directory and takes only the\n * resources directory as a flag, so the child runs with the project root as\n * cwd and `-rdir=<resourcesDir>`. `--prod` sets `NODE_ENV=production`, matching\n * the template's `start-server.mjs`; without it the server starts in\n * `development`.\n *\n * The build is chosen by platform: the caller passes one, and the CLI resolves\n * it as `redscripts.platform`, then `server.platforms[0]`, then the host — the\n * same rule the redscripts baseline uses, so `run` serves what was just built.\n *\n * Nothing is started from a missing build: a platform with no server binary is\n * `server.binary-missing` naming `cybermp download`, because downloading is\n * the only way to get one.\n *\n * Output is forwarded to this process's stdout and stderr as it arrives, and\n * the child's exit code becomes this process's exit code. The combined output\n * is also returned, so a caller (and the test suite) can inspect what the\n * server said without scraping the terminal.\n *\n * Errors: `server.binary-missing` (no build for the platform),\n * `server.spawn` (the binary exists but cannot be started).\n */\nimport { spawn } from 'node:child_process';\nimport { accessSync, constants, statSync } from 'node:fs';\nimport { join } from 'node:path';\nimport { BuilderError } from '../errors.js';\nimport {\n hostPlatform,\n SERVER_BINARY,\n SERVER_BINARY_WIN,\n type ServerPlatform,\n serverDir,\n} from './download.js';\n\n/** Options for {@link runServer}. */\nexport interface RunOptions {\n /** Project root; the server's working directory. */\n root: string;\n /** Build work directory holding `mp/<platform>`. */\n workDir: string;\n /** Directory passed to `-rdir` (the project's `resourcesDir`). */\n resourcesDir: string;\n /** Run with `NODE_ENV=production` instead of `development`. */\n prod?: boolean;\n /** Build to start; defaults to the host platform. */\n platform?: ServerPlatform;\n}\n\n/**\n * Start the server for `platform` and resolve with its combined output once it\n * exits.\n *\n * A non-zero exit is applied to `process.exitCode`, so the CLI exits with the\n * child's code; a successful run leaves the exit code alone.\n *\n * Errors: `server.binary-missing`, `server.spawn`.\n */\nexport async function runServer(opts: RunOptions): Promise<string> {\n const platform = opts.platform ?? hostPlatform();\n const binary = findBinary(opts.workDir, platform);\n\n const env = {\n ...process.env,\n NODE_ENV: opts.prod === true ? 'production' : 'development',\n };\n\n const child = spawn(binary, ['-run', `-rdir=${opts.resourcesDir}`], {\n cwd: opts.root,\n env,\n // stdin stays the terminal so the server's console keeps working; the two\n // output streams are piped and mirrored to ours.\n stdio: ['inherit', 'pipe', 'pipe'],\n });\n\n let output = '';\n child.stdout.setEncoding('utf8');\n child.stderr.setEncoding('utf8');\n child.stdout.on('data', (chunk: string) => {\n output += chunk;\n process.stdout.write(chunk);\n });\n child.stderr.on('data', (chunk: string) => {\n output += chunk;\n process.stderr.write(chunk);\n });\n\n const code = await new Promise<number>((resolve, reject) => {\n child.once('error', (error) => {\n reject(\n new BuilderError(\n 'server.spawn',\n `cannot start \\`${binary}\\`: ${errorMessage(error)}; ` +\n 'run `cybermp download` to reinstall the server binaries',\n ),\n );\n });\n // `close` waits for both output streams to drain, so no line is lost.\n child.once('close', (exitCode, signal) => resolve(exitCode ?? signalCode(signal)));\n });\n\n if (code !== 0) process.exitCode = code;\n return output;\n}\n\n/**\n * The server binary for `platform`, or `server.binary-missing`.\n *\n * Both names are tried in platform order: a Windows build ships\n * `cybermp-server.exe`, a Linux one `cybermp-server`, and a hand-made archive\n * may carry either. A file that exists but cannot be executed is reported as\n * missing too — the fix is the same `cybermp download`.\n */\nfunction findBinary(workDir: string, platform: ServerPlatform): string {\n const dir = serverDir(workDir, platform);\n const candidates =\n platform === 'win' ? [SERVER_BINARY_WIN, SERVER_BINARY] : [SERVER_BINARY, SERVER_BINARY_WIN];\n\n for (const name of candidates) {\n const path = join(dir, name);\n if (!isFile(path)) continue;\n try {\n accessSync(path, constants.X_OK);\n return path;\n } catch {\n if (platform === 'win') return path;\n throw new BuilderError(\n 'server.binary-missing',\n `the server binary at \\`${path}\\` is not executable; ` +\n 'run `cybermp download` to restore it',\n );\n }\n }\n\n throw new BuilderError(\n 'server.binary-missing',\n `the ${platform} server binaries are missing at \\`${dir}\\`; ` +\n 'run `cybermp download` to fetch them',\n );\n}\n\nfunction isFile(path: string): boolean {\n try {\n return statSync(path, { throwIfNoEntry: false })?.isFile() ?? false;\n } catch {\n return false;\n }\n}\n\n/** Conventional exit code for a child killed by `signal`. */\nfunction signalCode(signal: NodeJS.Signals | null): number {\n if (signal === 'SIGINT') return 130;\n if (signal === 'SIGTERM') return 143;\n return 1;\n}\n\nfunction errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAQA,IAAa,eAAb,cAAkC,MAAM;;CAE7B;CAET,YAAY,MAAc,SAAiB;EACzC,MAAM,GAAG,KAAK,IAAI,SAAS;EAC3B,KAAK,OAAO;EACZ,KAAK,OAAO;CACd;AACF;;;;;;;;;;AAqBA,SAAgB,kBAAkB,OAAe,QAAiD;CAChG,MAAM,SAAS,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