@champions-digital-game/mod-sdk 0.45.0 → 0.47.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.
- package/README.md +3 -3
- package/dist/build.js +1 -1
- package/dist/chunks/{chunk-MS5INQIY.js → chunk-6WFYI6O7.js} +1 -1
- package/dist/chunks/{chunk-WX7AFXND.js → chunk-C2OAZ3V7.js} +1 -1
- package/dist/chunks/{chunk-VSWWKMOU.js → chunk-EQL5OYKH.js} +2 -2
- package/dist/chunks/{chunk-JAFPA7PX.js → chunk-Q57JMRMI.js} +2 -2
- package/dist/chunks/chunk-QM4LCKP5.js +7 -0
- package/dist/chunks/{chunk-PAYEJUZX.js → chunk-SSVC7TJ6.js} +1 -1
- package/dist/chunks/{chunk-W45IQDAE.js → chunk-V5MJXIOQ.js} +1 -1
- package/dist/import.js +1 -1
- package/dist/index.js +1 -1
- package/dist/mc-pack.js +2 -2
- package/dist/testing.js +1 -1
- package/package.json +1 -1
- package/types/content/src/index.d.ts +1 -1
- package/types/content/src/schema/packs.d.ts +55 -0
- package/types/engine/src/index.d.ts +1 -1
- package/types/mod-sdk/src/build.d.ts +1 -1
- package/dist/chunks/chunk-GDZAIM46.js +0 -7
package/dist/mc-pack.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{src_exports}from"./chunks/chunk-
|
|
2
|
+
import{src_exports}from"./chunks/chunk-C2OAZ3V7.js";import{formatImportReport,importMarvelCdbPack}from"./chunks/chunk-6WFYI6O7.js";import{PackBuildError,assemblePack,buildPack,loadPackSource}from"./chunks/chunk-Q57JMRMI.js";import{publishIssues,readPackInput,splitIssues,validatePack}from"./chunks/chunk-QM4LCKP5.js";import{SMOKE_BASE_DECK,SMOKE_SCENARIOS,smokeTestPack}from"./chunks/chunk-V5MJXIOQ.js";import"./chunks/chunk-SSVC7TJ6.js";import"./chunks/chunk-EQL5OYKH.js";import{existsSync}from"node:fs";import{join,resolve}from"node:path";import{createJiti}from"jiti";function sdkModuleNames(){let published="@champions-digital-game/mod-sdk";return published&&published!=="@mc/mod-sdk"?["@mc/mod-sdk",published]:["@mc/mod-sdk"]}function packModuleImporter(){let virtualModules=Object.fromEntries(sdkModuleNames().map(name=>[name,src_exports]));return path=>createJiti(path,{virtualModules,fsCache:!1,moduleCache:!1,interopDefault:!1}).import(path)}var EXIT_OK=0,EXIT_PACK_PROBLEM=1,EXIT_USAGE=2,consoleIo={out:line=>process.stdout.write(`${line}
|
|
3
3
|
`),err:line=>process.stderr.write(`${line}
|
|
4
4
|
`)},USAGE=`mc-pack: build, check and test Marvel Champions Digital content packs
|
|
5
5
|
|
|
@@ -23,4 +23,4 @@ validate, build and test run the pack's own code: they import its abilities/inde
|
|
|
23
23
|
user's access to files, the network and the environment. Run them only on a pack you trust, or in a sandbox (a CI
|
|
24
24
|
job with no secrets).
|
|
25
25
|
|
|
26
|
-
Exit codes: 0 success, 1 the pack has a problem, 2 usage error.`,UsageError=class extends Error{},VALUE_FLAGS=new Set(["out","games","scenario","max-commands","id","app"]),BOOLEAN_FLAGS=new Set(["allow-unscripted","publish","help","version"]);function parseArgs(argv){let positional=[],flags=new Map;for(let i=0;i<argv.length;i++){let arg=argv[i];if(arg==="-h")flags.set("help",!0);else if(arg==="-v")flags.set("version",!0);else if(arg.startsWith("--")){let eq=arg.indexOf("="),name=eq<0?arg.slice(2):arg.slice(2,eq);if(BOOLEAN_FLAGS.has(name)){if(eq>=0)throw new UsageError(`--${name} takes no value`);flags.set(name,!0)}else if(VALUE_FLAGS.has(name)){let value2=eq>=0?arg.slice(eq+1):argv[++i];if(value2===void 0||value2==="")throw new UsageError(`--${name} needs a value`);flags.set(name,value2)}else throw new UsageError(`unknown option --${name}`)}else positional.push(arg)}return{positional,flags}}var value=(parsed,name)=>{let v=parsed.flags.get(name);return typeof v=="string"?v:void 0};function positiveInt(parsed,name){let raw=value(parsed,name);if(raw===void 0)return;let n=Number(raw);if(!Number.isInteger(n)||n<1)throw new UsageError(`--${name} must be a whole number of at least 1`);return n}function packDir(parsed,command){let[dir,...extra]=parsed.positional;if(dir===void 0)throw new UsageError(`${command} needs a folder`);if(extra.length>0)throw new UsageError(`${command} takes one folder, got ${parsed.positional.length}`);let full=resolve(dir);if(!existsSync(full))throw new UsageError(`${dir}: no such folder`);return full}function allowOnly(parsed,command,allowed){for(let name of parsed.flags.keys())if(!allowed.includes(name))throw new UsageError(`${command} does not take --${name}`)}var errorText=error=>error instanceof Error?error.message:String(error);async function loadBuilt(dir){let pack=assemblePack(await loadPackSource(dir,{importModule:packModuleImporter()}));return readPackInput(pack.manifest,pack.files)}function formatIssues(issues){let{defects,unscripted}=splitIssues(issues),lines=[];if(defects.length>0){lines.push(`${defects.length} problem${defects.length===1?"":"s"}:`);for(let issue of defects)lines.push(` ${issue.path}: ${issue.message}`)}if(unscripted.length>0){lines.push(`${unscripted.length} unscripted abilit${unscripted.length===1?"y":"ies"} (write them in abilities/):`);for(let issue of unscripted)lines.push(` ${issue.path}: ${issue.message}`)}return lines}async function validateCommand(parsed,io){allowOnly(parsed,"validate",["allow-unscripted","publish"]);let dir=packDir(parsed,"validate"),pack=await loadBuilt(dir),publish=parsed.flags.has("publish"),draft=existsSync(join(dir,"DRAFT"));publish&&draft&&io.out(`${pack.manifest.id}: a DRAFT, never published; the publish check is skipped`);let issues=[...validatePack(pack),...publish&&!draft?publishIssues(pack.manifest):[]],{defects,unscripted}=splitIssues(issues),name=`${pack.manifest.id}@${pack.manifest.version}`;if(issues.length===0)return io.out(`${name}: valid (${pack.cards.length} cards, ${Object.keys(pack.abilities).length} abilities)`),EXIT_OK;let lines=formatIssues(issues);if(defects.length===0&&parsed.flags.has("allow-unscripted")){io.out(`${name}: valid, ${unscripted.length} abilit${unscripted.length===1?"y":"ies"} to script`);for(let line of lines)io.out(line);return EXIT_OK}io.err(`${name}: invalid`);for(let line of lines)io.err(line);return EXIT_PACK_PROBLEM}async function buildCommand(parsed,io){allowOnly(parsed,"build",["out"]);let dir=packDir(parsed,"build"),out=value(parsed,"out");if(out===void 0)throw new UsageError("build needs --out <dir>");try{let result=await buildPack(dir,resolve(out),{importModule:packModuleImporter()}),{manifest}=result;return io.out(`${manifest.id}@${manifest.version}: built ${result.zipPath}`),io.out(` ${result.zipBytes} bytes, sha256 ${result.zipSha256}`),io.out(` ${manifest.files.length} files, ${manifest.totalBytes} bytes unzipped`),io.out(` requires app ${manifest.requires.app}; DSL features: ${manifest.requires.dslFeatures.join(", ")||"none"}`),EXIT_OK}catch(error){if(!(error instanceof PackBuildError))throw error;io.err("build failed: the pack is invalid");for(let line of formatIssues(error.issues))io.err(line);return EXIT_PACK_PROBLEM}}var describeGame=game=>{let where=game.deck===SMOKE_BASE_DECK?` at ${game.campaign?`${game.campaign}/${game.node} (${game.scenario})`:game.scenario}${game.modularSet?` with ${game.modularSet}`:""}${game.difficulty?`, ${game.difficulty}`:""}`:"",head=` ${game.deck}${where} seed ${game.seed}: `;if(!game.ok)return`${head}FAILED: ${game.error??"unknown error"}`;let played=game.packCardsPlayed.length>0?`; pack cards played or revealed: ${game.packCardsPlayed.join(", ")}`:"";return`${head}${game.outcome??"ended"} in round ${game.rounds} (${game.commands} commands)${played}`};async function testCommand(parsed,io){allowOnly(parsed,"test",["games","scenario","max-commands"]);let dir=packDir(parsed,"test"),scenario=value(parsed,"scenario")??"rhino";if(!SMOKE_SCENARIOS.includes(scenario))throw new UsageError(`--scenario must be one of ${SMOKE_SCENARIOS.join(", ")}`);let games=positiveInt(parsed,"games")??3,maxCommands=positiveInt(parsed,"max-commands"),pack=await loadBuilt(dir),issues=validatePack(pack);if(issues.length>0){io.err(`${pack.manifest.id}: not tested, the pack is invalid (run mc-pack validate)`);for(let line of formatIssues(issues))io.err(line);return EXIT_PACK_PROBLEM}io.out(`${pack.manifest.id}@${pack.manifest.version}: ${games} game(s) per deck, scenario and modular set (Core scenario: ${scenario})`);let result=smokeTestPack(pack,{games,scenario,...maxCommands!==void 0?{maxCommands}:{},onGame:game=>(game.ok?io.out:io.err)(describeGame(game))});for(let note of result.notes)io.out(`note: ${note}`);let failed=result.games.filter(g=>!g.ok).length;return failed>0?(io.err(`${failed} of ${result.games.length} game(s) failed`),EXIT_PACK_PROBLEM):(io.out(`all ${result.games.length} game(s) passed`),EXIT_OK)}async function importCommand(parsed,io){allowOnly(parsed,"import-marvelcdb",["out","id","app"]);let src=packDir(parsed,"import-marvelcdb"),out=value(parsed,"out"),packId=value(parsed,"id"),app=value(parsed,"app"),report=await importMarvelCdbPack(src,{...out!==void 0?{outDir:resolve(out)}:{},...packId!==void 0?{packId}:{},...app!==void 0?{app}:{}}),text=formatImportReport(report);if(!report.normalized||report.validationIssues.length>0)return io.err(text),EXIT_PACK_PROBLEM;if(io.out(text),report.unscriptedIssues.length>0){io.out(`${report.unscriptedIssues.length} abilities to script, listed in abilities/index.ts:`);for(let issue of report.unscriptedIssues)io.out(` ${issue.path}: ${issue.message}`)}return io.out(report.outDir?`written to ${report.outDir}`:"dry run: nothing written (pass --out <dir>)"),EXIT_OK}var COMMANDS={validate:validateCommand,build:buildCommand,test:testCommand,"import-marvelcdb":importCommand};async function runCli(argv,io=consoleIo){let[command,...rest]=argv;try{if(command===void 0||command==="--help"||command==="-h"||command==="help")return io.out(USAGE),command===void 0?EXIT_USAGE:EXIT_OK;if(command==="--version"||command==="-v")return io.out("0.
|
|
26
|
+
Exit codes: 0 success, 1 the pack has a problem, 2 usage error.`,UsageError=class extends Error{},VALUE_FLAGS=new Set(["out","games","scenario","max-commands","id","app"]),BOOLEAN_FLAGS=new Set(["allow-unscripted","publish","help","version"]);function parseArgs(argv){let positional=[],flags=new Map;for(let i=0;i<argv.length;i++){let arg=argv[i];if(arg==="-h")flags.set("help",!0);else if(arg==="-v")flags.set("version",!0);else if(arg.startsWith("--")){let eq=arg.indexOf("="),name=eq<0?arg.slice(2):arg.slice(2,eq);if(BOOLEAN_FLAGS.has(name)){if(eq>=0)throw new UsageError(`--${name} takes no value`);flags.set(name,!0)}else if(VALUE_FLAGS.has(name)){let value2=eq>=0?arg.slice(eq+1):argv[++i];if(value2===void 0||value2==="")throw new UsageError(`--${name} needs a value`);flags.set(name,value2)}else throw new UsageError(`unknown option --${name}`)}else positional.push(arg)}return{positional,flags}}var value=(parsed,name)=>{let v=parsed.flags.get(name);return typeof v=="string"?v:void 0};function positiveInt(parsed,name){let raw=value(parsed,name);if(raw===void 0)return;let n=Number(raw);if(!Number.isInteger(n)||n<1)throw new UsageError(`--${name} must be a whole number of at least 1`);return n}function packDir(parsed,command){let[dir,...extra]=parsed.positional;if(dir===void 0)throw new UsageError(`${command} needs a folder`);if(extra.length>0)throw new UsageError(`${command} takes one folder, got ${parsed.positional.length}`);let full=resolve(dir);if(!existsSync(full))throw new UsageError(`${dir}: no such folder`);return full}function allowOnly(parsed,command,allowed){for(let name of parsed.flags.keys())if(!allowed.includes(name))throw new UsageError(`${command} does not take --${name}`)}var errorText=error=>error instanceof Error?error.message:String(error);async function loadBuilt(dir){let pack=assemblePack(await loadPackSource(dir,{importModule:packModuleImporter()}));return readPackInput(pack.manifest,pack.files)}function formatIssues(issues){let{defects,unscripted}=splitIssues(issues),lines=[];if(defects.length>0){lines.push(`${defects.length} problem${defects.length===1?"":"s"}:`);for(let issue of defects)lines.push(` ${issue.path}: ${issue.message}`)}if(unscripted.length>0){lines.push(`${unscripted.length} unscripted abilit${unscripted.length===1?"y":"ies"} (write them in abilities/):`);for(let issue of unscripted)lines.push(` ${issue.path}: ${issue.message}`)}return lines}async function validateCommand(parsed,io){allowOnly(parsed,"validate",["allow-unscripted","publish"]);let dir=packDir(parsed,"validate"),pack=await loadBuilt(dir),publish=parsed.flags.has("publish"),draft=existsSync(join(dir,"DRAFT"));publish&&draft&&io.out(`${pack.manifest.id}: a DRAFT, never published; the publish check is skipped`);let issues=[...validatePack(pack),...publish&&!draft?publishIssues(pack.manifest):[]],{defects,unscripted}=splitIssues(issues),name=`${pack.manifest.id}@${pack.manifest.version}`;if(issues.length===0)return io.out(`${name}: valid (${pack.cards.length} cards, ${Object.keys(pack.abilities).length} abilities)`),EXIT_OK;let lines=formatIssues(issues);if(defects.length===0&&parsed.flags.has("allow-unscripted")){io.out(`${name}: valid, ${unscripted.length} abilit${unscripted.length===1?"y":"ies"} to script`);for(let line of lines)io.out(line);return EXIT_OK}io.err(`${name}: invalid`);for(let line of lines)io.err(line);return EXIT_PACK_PROBLEM}async function buildCommand(parsed,io){allowOnly(parsed,"build",["out"]);let dir=packDir(parsed,"build"),out=value(parsed,"out");if(out===void 0)throw new UsageError("build needs --out <dir>");try{let result=await buildPack(dir,resolve(out),{importModule:packModuleImporter()}),{manifest}=result;return io.out(`${manifest.id}@${manifest.version}: built ${result.zipPath}`),io.out(` ${result.zipBytes} bytes, sha256 ${result.zipSha256}`),io.out(` ${manifest.files.length} files, ${manifest.totalBytes} bytes unzipped`),io.out(` requires app ${manifest.requires.app}; DSL features: ${manifest.requires.dslFeatures.join(", ")||"none"}`),EXIT_OK}catch(error){if(!(error instanceof PackBuildError))throw error;io.err("build failed: the pack is invalid");for(let line of formatIssues(error.issues))io.err(line);return EXIT_PACK_PROBLEM}}var describeGame=game=>{let where=game.deck===SMOKE_BASE_DECK?` at ${game.campaign?`${game.campaign}/${game.node} (${game.scenario})`:game.scenario}${game.modularSet?` with ${game.modularSet}`:""}${game.difficulty?`, ${game.difficulty}`:""}`:"",head=` ${game.deck}${where} seed ${game.seed}: `;if(!game.ok)return`${head}FAILED: ${game.error??"unknown error"}`;let played=game.packCardsPlayed.length>0?`; pack cards played or revealed: ${game.packCardsPlayed.join(", ")}`:"";return`${head}${game.outcome??"ended"} in round ${game.rounds} (${game.commands} commands)${played}`};async function testCommand(parsed,io){allowOnly(parsed,"test",["games","scenario","max-commands"]);let dir=packDir(parsed,"test"),scenario=value(parsed,"scenario")??"rhino";if(!SMOKE_SCENARIOS.includes(scenario))throw new UsageError(`--scenario must be one of ${SMOKE_SCENARIOS.join(", ")}`);let games=positiveInt(parsed,"games")??3,maxCommands=positiveInt(parsed,"max-commands"),pack=await loadBuilt(dir),issues=validatePack(pack);if(issues.length>0){io.err(`${pack.manifest.id}: not tested, the pack is invalid (run mc-pack validate)`);for(let line of formatIssues(issues))io.err(line);return EXIT_PACK_PROBLEM}io.out(`${pack.manifest.id}@${pack.manifest.version}: ${games} game(s) per deck, scenario and modular set (Core scenario: ${scenario})`);let result=smokeTestPack(pack,{games,scenario,...maxCommands!==void 0?{maxCommands}:{},onGame:game=>(game.ok?io.out:io.err)(describeGame(game))});for(let note of result.notes)io.out(`note: ${note}`);let failed=result.games.filter(g=>!g.ok).length;return failed>0?(io.err(`${failed} of ${result.games.length} game(s) failed`),EXIT_PACK_PROBLEM):(io.out(`all ${result.games.length} game(s) passed`),EXIT_OK)}async function importCommand(parsed,io){allowOnly(parsed,"import-marvelcdb",["out","id","app"]);let src=packDir(parsed,"import-marvelcdb"),out=value(parsed,"out"),packId=value(parsed,"id"),app=value(parsed,"app"),report=await importMarvelCdbPack(src,{...out!==void 0?{outDir:resolve(out)}:{},...packId!==void 0?{packId}:{},...app!==void 0?{app}:{}}),text=formatImportReport(report);if(!report.normalized||report.validationIssues.length>0)return io.err(text),EXIT_PACK_PROBLEM;if(io.out(text),report.unscriptedIssues.length>0){io.out(`${report.unscriptedIssues.length} abilities to script, listed in abilities/index.ts:`);for(let issue of report.unscriptedIssues)io.out(` ${issue.path}: ${issue.message}`)}return io.out(report.outDir?`written to ${report.outDir}`:"dry run: nothing written (pass --out <dir>)"),EXIT_OK}var COMMANDS={validate:validateCommand,build:buildCommand,test:testCommand,"import-marvelcdb":importCommand};async function runCli(argv,io=consoleIo){let[command,...rest]=argv;try{if(command===void 0||command==="--help"||command==="-h"||command==="help")return io.out(USAGE),command===void 0?EXIT_USAGE:EXIT_OK;if(command==="--version"||command==="-v")return io.out("0.47.0"),EXIT_OK;let run=COMMANDS[command];if(!run)throw new UsageError(`unknown command "${command}"`);let parsed=parseArgs(rest);return parsed.flags.has("help")?(io.out(USAGE),EXIT_OK):await run(parsed,io)}catch(error){return error instanceof UsageError?(io.err(`mc-pack: ${error.message}`),io.err("run mc-pack --help for usage"),EXIT_USAGE):(io.err(`mc-pack ${command}: ${errorText(error)}`),EXIT_PACK_PROBLEM)}}process.exitCode=await runCli(process.argv.slice(2));
|
package/dist/testing.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{SMOKE_BASE_DECK,SMOKE_SCENARIOS,playToOutcome,smokeTestPack}from"./chunks/chunk-
|
|
1
|
+
import{SMOKE_BASE_DECK,SMOKE_SCENARIOS,playToOutcome,smokeTestPack}from"./chunks/chunk-V5MJXIOQ.js";import"./chunks/chunk-SSVC7TJ6.js";import"./chunks/chunk-EQL5OYKH.js";export{SMOKE_BASE_DECK,SMOKE_SCENARIOS,playToOutcome,smokeTestPack};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@champions-digital-game/mod-sdk",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.47.0",
|
|
4
4
|
"description": "The mod SDK for Marvel Champions Digital content packs: the pack schema, the ability DSL, and the mc-pack validate, build, test and import-marvelcdb tools.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"card-game",
|
|
@@ -3,7 +3,7 @@ export declare const CONTENT_VERSION = "0.0.0";
|
|
|
3
3
|
* Schema version for the card data shape itself (independent of how many
|
|
4
4
|
* cards/cycles have been ingested). Bump when a breaking shape change lands.
|
|
5
5
|
*/
|
|
6
|
-
export declare const SCHEMA_VERSION = "0.
|
|
6
|
+
export declare const SCHEMA_VERSION = "0.47.0";
|
|
7
7
|
export * from "./schema/index.js";
|
|
8
8
|
export * from "./data/index.js";
|
|
9
9
|
export * from "./import/index.js";
|
|
@@ -252,6 +252,41 @@ export declare function packAchievementProblems(achievements: unknown, context:
|
|
|
252
252
|
* shape check, ids unique, at most `PACK_ACHIEVEMENTS_MAX`. The rest are dropped, never thrown on.
|
|
253
253
|
*/
|
|
254
254
|
export declare function parsePackAchievements(data: unknown): readonly PackAchievement[];
|
|
255
|
+
/** The most search tags one pack may carry, and the longest one (after trimming). */
|
|
256
|
+
export declare const PACK_TAGS_MAX = 8;
|
|
257
|
+
export declare const PACK_TAG_MAX_LENGTH = 24;
|
|
258
|
+
/**
|
|
259
|
+
* The creator's tags of untrusted data (a `pack.json`, a `preview.json`): each entry is text, trimmed, 1 to
|
|
260
|
+
* `PACK_TAG_MAX_LENGTH` characters, unique ignoring case (the first spelling stays), at most `PACK_TAGS_MAX`. The rest
|
|
261
|
+
* are dropped, never thrown on; anything but a list gives `[]`.
|
|
262
|
+
*/
|
|
263
|
+
export declare function parsePackTags(data: unknown): readonly string[];
|
|
264
|
+
/**
|
|
265
|
+
* The release waves (`Cycle.id`s) a pack may sit beside, in release order: the same ids as the client's unlock path
|
|
266
|
+
* (`UNLOCK_WAVES` in the client's `progression/unlocks.ts`) and the `cycleId` of every official hero and scenario pack.
|
|
267
|
+
* `core` is the Core Set, `wave1` the first hero packs, `cycle1` The Rise of Red Skull, then `cycle3` to `cycle11`.
|
|
268
|
+
*/
|
|
269
|
+
export declare const PACK_WAVE_IDS: readonly string[];
|
|
270
|
+
/** The wave of untrusted data: a known `PACK_WAVE_IDS` entry, else `undefined`. */
|
|
271
|
+
export declare function parsePackWave(data: unknown): string | undefined;
|
|
272
|
+
/**
|
|
273
|
+
* How a pack's heroes and scenarios unlock when the player has turned "Custom content starts unlocked" off.
|
|
274
|
+
* `open` is always playable, `points` needs champion points spent by hand like an official hero, `wins` opens free
|
|
275
|
+
* after winning games (or by points).
|
|
276
|
+
*/
|
|
277
|
+
export type PackUnlockMode = "open" | "points" | "wins";
|
|
278
|
+
export declare const PACK_UNLOCK_MODES: readonly PackUnlockMode[];
|
|
279
|
+
/** The unlock mode of untrusted data: a known mode, else `"open"`. */
|
|
280
|
+
export declare function parsePackUnlock(data: unknown): PackUnlockMode;
|
|
281
|
+
/**
|
|
282
|
+
* Everything wrong with a pack's `tags`, `wave` and `unlock`, as messages starting with the field name (the caller adds
|
|
283
|
+
* the `pack.json` path). Each field is optional.
|
|
284
|
+
*/
|
|
285
|
+
export declare function packCatalogFieldProblems(manifest: {
|
|
286
|
+
readonly tags?: unknown;
|
|
287
|
+
readonly wave?: unknown;
|
|
288
|
+
readonly unlock?: unknown;
|
|
289
|
+
}): string[];
|
|
255
290
|
/** A pack's `pack.json` (§5.1). */
|
|
256
291
|
export interface PackManifest {
|
|
257
292
|
readonly schema: typeof PACK_SCHEMA_VERSION;
|
|
@@ -277,6 +312,21 @@ export interface PackManifest {
|
|
|
277
312
|
readonly permission?: PackPermission;
|
|
278
313
|
/** The pack's own achievements (§11.12): worth no points, conditions are data only (`PackAchievementWhen`). */
|
|
279
314
|
readonly achievements?: readonly PackAchievement[];
|
|
315
|
+
/**
|
|
316
|
+
* The creator's own search tags for the Mod Store ("Symbiote", "Aggression"): at most `PACK_TAGS_MAX`, each 1 to
|
|
317
|
+
* `PACK_TAG_MAX_LENGTH` characters, unique ignoring case. The catalog lists them after the pack's kind.
|
|
318
|
+
*/
|
|
319
|
+
readonly tags?: readonly string[];
|
|
320
|
+
/**
|
|
321
|
+
* The release wave (one of `PACK_WAVE_IDS`, a `Cycle.id`) whose shelf the pack's heroes and scenarios sit beside when
|
|
322
|
+
* the player mixes custom content in with the official content.
|
|
323
|
+
*/
|
|
324
|
+
readonly wave?: string;
|
|
325
|
+
/**
|
|
326
|
+
* How the pack's heroes and scenarios unlock when the player has turned "Custom content starts unlocked" off
|
|
327
|
+
* (`PackUnlockMode`). Absent means `"open"`.
|
|
328
|
+
*/
|
|
329
|
+
readonly unlock?: PackUnlockMode;
|
|
280
330
|
/** Who made the card template the pack's cards are laid out on ("Hitch", "G.Triskelion"). */
|
|
281
331
|
readonly templateCredit?: string;
|
|
282
332
|
/** Who translated the pack, by language: `{ es: "Francisco Merchán" }`. */
|
|
@@ -358,6 +408,11 @@ export interface PackIndexEntry {
|
|
|
358
408
|
readonly kind: PackKind;
|
|
359
409
|
readonly name: string;
|
|
360
410
|
readonly creator: string;
|
|
411
|
+
/**
|
|
412
|
+
* Everyone the pack's `pack.json` credits (`authors`), for the store's Credits tab (issue #734): `creator` is one
|
|
413
|
+
* line and may name only the lead. Absent on an entry written before the field existed.
|
|
414
|
+
*/
|
|
415
|
+
readonly authors?: readonly string[];
|
|
361
416
|
/** One line for the store list. */
|
|
362
417
|
readonly summary: string;
|
|
363
418
|
readonly tags: readonly string[];
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export declare const ENGINE_VERSION = "0.
|
|
1
|
+
export declare const ENGINE_VERSION = "0.47.0";
|
|
2
2
|
export type { PlayerId, InstanceId, ChoiceId, EncounterDeckId, FrameId, GroupId, TeamId } from "./ids.js";
|
|
3
3
|
export { playerId, instanceId, choiceId, encounterDeckId, frameId, groupId, teamId } from "./ids.js";
|
|
4
4
|
export type { GroupRef, PodNeutralArea, PodNeutralSetup, PodSetup, PodState, SharedEvent, SharedPodState, SharedResult, SharedThreatCause, } from "./pod.js";
|
|
@@ -2,7 +2,7 @@ import { type AnyCard, type EncounterSet, type PackManifest, type StarterDeck }
|
|
|
2
2
|
import type { AbilityRegistry } from "../../engine/src/index.js";
|
|
3
3
|
import { type PackInput, type PackIssue, type ValidateOptions } from "./validate.js";
|
|
4
4
|
/** The author-written part of `pack.json`. The build fills in everything else. */
|
|
5
|
-
export type PackAuthorManifest = Pick<PackManifest, "id" | "version" | "kind" | "name" | "authors" | "description" | "license" | "pictures" | "languages" | "altArt" | "houseRule" | "permission" | "templateCredit" | "translators" | "cover" | "achievements"> & {
|
|
5
|
+
export type PackAuthorManifest = Pick<PackManifest, "id" | "version" | "kind" | "name" | "authors" | "description" | "license" | "pictures" | "languages" | "altArt" | "houseRule" | "permission" | "templateCredit" | "translators" | "cover" | "achievements" | "tags" | "wave" | "unlock"> & {
|
|
6
6
|
readonly requires: {
|
|
7
7
|
readonly app: string;
|
|
8
8
|
readonly packs?: readonly string[];
|
|
@@ -1,7 +0,0 @@
|
|
|
1
|
-
import{CAMPAIGNS,ENGINE_ONLY_DSL_EXAMPLES,PACK_COVER_MAX_BYTES,PACK_HOUSE_RULE_MODES,PACK_KINDS,PACK_PERMISSION_STATUSES,PLAYABLE_CARDS,PLAYABLE_DEPS,campaignDefinitionProblems,campaignInstructionsOf,customCardPrefix,customScenarioProblems,houseRuleMayRebuild,isBaseEncounterSetId,isBaseScenarioId,isLanguageTag,isPackCoverPath,isPackId,isSafePackPath,officialCardsByPictureCode,officialFaceOfCode,opsOfKind,packAchievementProblems,packStagedPictureCodes,parsePackCardImagePath,validateCard,validateDefinition,validateEncounterSet,validateScenario,validateStarterDeck,webpSize}from"./chunk-VSWWKMOU.js";function dslFeatures(registry,campaigns=[]){let found=new Set;for(let definition of Object.values(registry??{}))isRecord(definition)&&collectDefinition(definition,found);for(let definition of campaigns)isRecord(definition)&&collectCampaign(definition,found);return[...found].sort()}function campaignDefinitionsOf(campaigns){return(campaigns??[]).flatMap(entry=>isRecord(entry)&&isRecord(entry.definition)?[entry.definition]:[])}function collectCampaignExprs(value,found){if(Array.isArray(value)){for(let item of value)collectCampaignExprs(item,found);return}if(isRecord(value)){typeof value.kind=="string"&&(found.add(`campaign:${value.kind}`),recordFields(`campaign:${value.kind}`,value,found));for(let child of Object.values(value))collectCampaignExprs(child,found)}}function collectCampaign(definition,found){let graph=definition.graph;isRecord(graph)&&typeof graph.kind=="string"&&found.add(`campaign-graph:${graph.kind}`);for(let field of Array.isArray(definition.logFields)?definition.logFields:[])isRecord(field)&&isRecord(field.type)&&typeof field.type.kind=="string"&&found.add(`campaign-field:${field.type.kind}`);let instructions=[];try{instructions=campaignInstructionsOf(definition)}catch{}for(let instruction of instructions){if(!isRecord(instruction))continue;collectCampaignExprs([instruction.when,instruction.whenModes],found);let step=instruction.step;isRecord(step)&&(step.kind==="inGame"?(typeof step.window=="string"&&found.add(`campaign-window:${step.window}`),visit(step.effects,"effect",found)):collectCampaignExprs(step,found))}let nodes=isRecord(graph)&&Array.isArray(graph.nodes)?graph.nodes:[];for(let node of nodes)isRecord(node)&&node.scenarioRuleSpecs!==void 0&&visit(node.scenarioRuleSpecs,"rule",found);collectCampaignExprs([definition.elimination,definition.loss],found)}var isRecord=value=>typeof value=="object"&&value!==null&&!Array.isArray(value),isStringArray=value=>Array.isArray(value)&&value.length>0&&value.every(item=>typeof item=="string"),EFFECT_SLOTS={if:["then","otherwise"],replaceTriggeringEvent:["with"],enemyScheme:["wouldPlaceThreat"]};function slotFor(kind,slot,key){return key==="effects"?"effect":key==="rules"?"rule":slot==="effect"&&kind!==void 0&&EFFECT_SLOTS[kind]?.includes(key)?"effect":"expr"}function collectDefinition(definition,found){for(let[key,value]of Object.entries(definition))value!==void 0&&(key==="trigger"?collectTrigger(value,found):key==="cost"?collectCost(value,found):key==="effects"?visit(value,"effect",found):(found.add(`ability:${key}`),recordFields(`ability:${key}`,value,found),visit(value,slotFor(void 0,"expr",key),found)))}function recordFields(prefix,value,found,skip="kind"){if(isRecord(value))for(let[field,child]of Object.entries(value))field!==skip&&child!==void 0&&found.add(`${prefix}.${field}`)}function collectTrigger(trigger,found){if(isRecord(trigger)){typeof trigger.kind=="string"&&found.add(`trigger:${trigger.kind}`);for(let[key,value]of Object.entries(trigger))if(!(key==="kind"||value===void 0)){if(key==="on"){visit(value,"expr",found,!0);continue}found.add(`trigger-option:${key}`),recordFields(`trigger-option:${key}`,value,found),visit(value,slotFor(void 0,"expr",key),found)}}}function collectCost(cost,found){if(isRecord(cost)){for(let[key,value]of Object.entries(cost))if(value!==void 0)if(found.add(`cost:${key}`),key==="either"&&Array.isArray(value))for(let branch of value)collectCost(branch,found);else if(key==="conditional"&&isRecord(value)){collectCost(value.then,found),collectCost(value.else,found);let{then:_then,else:_else,...rest}=value;recordFields("cost:conditional",rest,found),visit(rest,"expr",found)}else recordFields(`cost:${key}`,value,found),visit(value,"expr",found)}}var TARGET_QUERY_FIELDS=["categories","inScenarioPlayArea","controller","engagedWith","trait","withoutTrait","anyTrait","withKeyword","withoutKeyword","anyOf","not","cardTypeIs","playerSideScheme","accusation","chosenVillain","name","printedId","hostOfSelf","host","hasAttachment","canHaveAttached","canAttachTo","canAttachToCategory","canEnterPlay","canEnterPlayControllerStated","canFlip","facedown","starIcon","boostCard","printsBoostAbility","unique","printedResource","anyPrintedResource","printedResourceNamed","owner","aspect","anyAspect","exhausted","hasThreat","hasCounter","hasAccelerationToken","damaged","hasStatus","hasAnyStatus","canTakeStatus","self","maxPrintedHp","statCompare","remainingHpCompare","maxPrintedCost","minPrintedCost","attackableBy","canTakeAttackInProgress","canAttackOneOf","excludeSlots","excluding","inSlot","controlledBy","extensionOf","actsFor","engagedWithPlayer","inPlayAreaOf","signatureSideScheme","identitySetOf","nemesisMinionOf","obligationOf","nemesisSideSchemeOf","nemesisSetOf","sharesTraitWith","sharesTraitWithHeroOf","sharesTitleWith","otherFaceOf","encounterSetOf","scenarioSpecific","inEncounterSet","inCampaignLogField","titled","identitySetTitled","sameClassificationAs","classification","printedForm","abilityTiming","printsAbility","hasTaggedAbility"],SHARED_QUERY_FIELDS=new Set(["name","trait","aspect","self","owner","host","unique","exhausted","facedown","damaged","controller","not","anyOf","inSlot","excluding","titled","anyTrait","classification","printedForm"]),QUERY_FIELD_SET=new Set(TARGET_QUERY_FIELDS);function recordQueryFields(value,found){if(typeof value.kind=="string")return;let own=Object.keys(value).filter(key=>value[key]!==void 0&&QUERY_FIELD_SET.has(key));if(own.some(key=>!SHARED_QUERY_FIELDS.has(key)))for(let key of own)found.add(`query:${key}`)}function visit(value,slot,found,isPattern=!1){if(Array.isArray(value)){for(let item of value)visit(item,slot,found,isPattern);return}if(!isRecord(value))return;let kind=typeof value.kind=="string"?value.kind:void 0;recordQueryFields(value,found),kind!==void 0&&(found.add(`${slot}:${kind}`),recordFields(`${slot}:${kind}`,value,found));let on=value.on,hearsEvents=(isPattern||kind===void 0)&&(typeof on=="string"||isStringArray(on));if(hearsEvents)for(let event of typeof on=="string"?[on]:on)found.add(`event:${event}`);for(let[childKey,child]of Object.entries(value))hearsEvents&&childKey==="on"||visit(child,slotFor(kind,slot,childKey),found,childKey==="anyOf")}var SUPPORTED_DSL_FEATURES=dslFeatures({...PLAYABLE_DEPS.abilities,...ENGINE_ONLY_DSL_EXAMPLES},Object.values(CAMPAIGNS));var PACK_ABILITY_ID=/^x\.[a-z0-9]+(?:-[a-z0-9]+)*\.\d+[a-z]?\.[a-z0-9-]+$/;function definePackAbilities(definitions){let problems=[];for(let[id,definition]of Object.entries(definitions)){PACK_ABILITY_ID.test(id)||problems.push(`${id}: not an x.<pack-id>.<card number>.<slug> ability id`);for(let problem of validateDefinition(definition))problems.push(`${id}: ${problem}`)}if(problems.length>0)throw new Error(`invalid pack ability definitions:
|
|
2
|
-
${problems.join(`
|
|
3
|
-
`)}`);return definitions}var K=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),rotr=(x,n)=>x>>>n|x<<32-n;function sha256Hex(data){let h=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),length=data.length,padded=new Uint8Array(length+9+63>>6<<6);padded.set(data),padded[length]=128;let view=new DataView(padded.buffer);view.setUint32(padded.length-8,Math.floor(length/536870912),!1),view.setUint32(padded.length-4,length<<3>>>0,!1);let w=new Uint32Array(64);for(let offset=0;offset<padded.length;offset+=64){for(let i=0;i<16;i++)w[i]=view.getUint32(offset+i*4,!1);for(let i=16;i<64;i++){let s0=rotr(w[i-15],7)^rotr(w[i-15],18)^w[i-15]>>>3,s1=rotr(w[i-2],17)^rotr(w[i-2],19)^w[i-2]>>>10;w[i]=w[i-16]+s0+w[i-7]+s1|0}let[a,b,c,d,e,f,g,hh]=[h[0],h[1],h[2],h[3],h[4],h[5],h[6],h[7]];for(let i=0;i<64;i++){let s1=rotr(e,6)^rotr(e,11)^rotr(e,25),ch=e&f^~e&g,t1=hh+s1+ch+K[i]+w[i]|0,s0=rotr(a,2)^rotr(a,13)^rotr(a,22),maj=a&b^a&c^b&c,t2=s0+maj|0;hh=g,g=f,f=e,e=d+t1|0,d=c,c=b,b=a,a=t1+t2|0}h[0]=h[0]+a|0,h[1]=h[1]+b|0,h[2]=h[2]+c|0,h[3]=h[3]+d|0,h[4]=h[4]+e|0,h[5]=h[5]+f|0,h[6]=h[6]+g|0,h[7]=h[7]+hh|0}return[...h].map(n=>(n>>>0).toString(16).padStart(8,"0")).join("")}var isObj=value=>typeof value=="object"&&value!==null&&!Array.isArray(value),text=value=>typeof value=="string"&&value.trim()!=="";function isPlainJson(value){if(value===null||typeof value=="string"||typeof value=="boolean")return!0;if(typeof value=="number")return Number.isFinite(value);if(Array.isArray(value))return value.every(isPlainJson);if(isObj(value)){let proto=Object.getPrototypeOf(value);return(proto===Object.prototype||proto===null)&&Object.values(value).every(isPlainJson)}return!1}var LIMITED_OPS={spend:"spending a currency (a market or shop) is not available to a pack campaign yet",composeVillain:"choosing a villain between games is not available to a pack campaign yet",composeEncounterSets:"composing encounter sets between games is not available to a pack campaign yet",setAsideCards:"setting cards aside between games is not available to a pack campaign yet"};function checkPackCampaigns(input){let{add}=input,ids=new Set,requiredScenarioIds=new Set(input.required.scenarios.map(scenario=>scenario.id)),requiredSetIds=new Set(input.required.encounterSets.map(set=>set.id));for(let[index,entry]of input.campaigns.entries()){if(!isObj(entry)){add(`campaigns[${index}]`,"must be a campaign object");continue}let id=typeof entry.id=="string"?entry.id:"",at=`campaigns/${id||index}`;(input.packId===""||!id.startsWith(`${input.packId}-`)||id.length===input.packId.length+1)&&add(at,`campaign id must be "${input.packId}-<name>"`),Object.hasOwn(CAMPAIGNS,id)&&add(at,"campaign id is a base-game campaign id (the base game always wins)"),ids.has(id)&&add(at,"campaign id is used by two campaigns"),ids.add(id);for(let field of["name","description"])text(entry[field])||add(at,`${field} must be a non-empty string`);entry.tagline!==void 0&&!text(entry.tagline)&&add(at,"tagline must be a non-empty string"),text(entry.version)||add(at,"version must be a non-empty string");let definition=entry.definition;if(!isObj(definition)){add(at,"definition must be a campaign definition object");continue}isPlainJson(definition)||add(at,"definition must be plain JSON (no undefined, functions or NaN)"),definition.campaignId!==id&&add(at,`definition.campaignId must equal the campaign's id "${id}"`),definition.version!==entry.version&&add(at,"definition.version must equal the campaign's version");let problems=campaignDefinitionProblems(definition,{isCardId:input.isCardId,isScenarioId:scenarioId=>input.packScenarioIds.has(scenarioId)||isBaseScenarioId(scenarioId)||requiredScenarioIds.has(scenarioId)});for(let problem of problems)add(at,problem);if(!isReadable(definition))continue;let readable=definition;try{checkLimits(at,readable,add),checkRecord(at,entry,readable,input,requiredSetIds),checkStory(at,entry,readable,add)}catch(error){add(at,`could not be checked: ${error instanceof Error?error.message:String(error)}`)}if(entry.art!==void 0){let cover=isObj(entry.art)?entry.art.cover:void 0;!isObj(entry.art)||cover!==void 0&&(typeof cover!="string"||!isSafePackPath(cover))?add(at,"art must be { cover?: a pack file path }"):typeof cover=="string"&&!input.listedFiles.has(cover)&&add(at,`art.cover "${cover}" is not a listed file`)}}}function isReadable(definition){let graph=definition.graph,listOfObjects=value=>Array.isArray(value)&&value.every(isObj);return isObj(graph)&&listOfObjects(graph.nodes)&&graph.nodes.every(node=>Array.isArray(node.setup)&&Array.isArray(node.victory))&&listOfObjects(definition.logFields)}function checkLimits(at,definition,add){let graph=definition.graph;graph.kind!=="linear"&&add(at,`the graph must be "linear" (a "${String(graph.kind)}" graph is not available yet)`);for(let node of graph.nodes){let name=`node "${String(node.id)}"`;node.scenario?.kind!=="fixed"&&add(at,`${name}: the scenario must be "fixed" (a named scenario record)`),node.composition!==void 0&&node.composition.length>0&&add(at,`${name}: composition (choosing a villain or sets between games) is not available yet`),node.requiredModularSetIds!==void 0&&node.requiredModularSetIds.length>0&&add(at,`${name}: requiredModularSetIds is not available yet`)}definition.elimination!==void 0&&add(at,"an elimination policy is not available yet (it is part of an expert campaign)");let everything=[definition.everyNodeSetup,definition.everyNodeVictory,definition.conditionalInstructions,definition.loss,graph.nodes];for(let[kind,message]of Object.entries(LIMITED_OPS))opsOfKind(everything,kind).length>0&&add(at,message);opsOfKind(everything,"perSeatSet").length>0&&add(at,"a per-seat set (an expert campaign's numbered sets) is not available yet"),JSON.stringify(everything).includes('"unitCostExactly"')&&add(at,"a Unit Cost filter (a market) is not available yet"),JSON.stringify(everything).includes('"expertCampaign"')&&add(at,"an instruction gated by expertCampaign is not available yet (no expert campaign rules)"),definition.logFields.some(field=>field.whenModes!==void 0)&&add(at,"a log field gated by modes (whenModes) is not available yet")}function checkRecord(at,entry,definition,input,requiredSetIds){let{add}=input,record=entry.record;if(!isObj(record)){add(at,"record must be { scenarioIds, campaignSetIds }");return}let nodeScenarios=definition.graph.nodes.flatMap(node=>node.scenario?.kind==="fixed"?[String(node.scenario.scenarioId)]:[]),listed=record.scenarioIds;!Array.isArray(listed)||listed.some(scenarioId=>typeof scenarioId!="string")?add(at,"record.scenarioIds must be a list of scenario ids"):listed.join(`
|
|
4
|
-
`)!==nodeScenarios.join(`
|
|
5
|
-
`)&&add(at,`record.scenarioIds must list the nodes' scenarios in order: ${nodeScenarios.join(", ")}`);let sets=record.campaignSetIds;if(!Array.isArray(sets)||sets.some(setId=>typeof setId!="string"))add(at,"record.campaignSetIds must be a list of encounter set ids (empty is fine)");else{for(let setId of sets)isBaseEncounterSetId(setId)?add(at,`record.campaignSetIds: "${setId}" is a base-game set`):!input.packSetIds.has(setId)&&!requiredSetIds.has(setId)&&add(at,`record.campaignSetIds: "${setId}" is not an encounter set of this pack or a required pack`);let own=new Set(sets);for(let source of opsOfKind([definition.everyNodeSetup,definition.everyNodeVictory,definition.conditionalInstructions,definition.graph],"campaignSet"))own.has(String(source.encounterSetId))||add(at,`draws from "${String(source.encounterSetId)}", which is not in record.campaignSetIds`)}record.prohibited!==void 0&&!isObj(record.prohibited)&&add(at,"record.prohibited must be an object")}var SPEAKERS=["narrator","villain","npc"];function checkStory(at,entry,definition,add){let story=entry.story;if(story===void 0)return;if(!isObj(story)){add(at,"story must be an object");return}text(story.blurb)||add(at,"story.blurb must be a non-empty string"),story.rosterBanner!==void 0&&!text(story.rosterBanner)&&add(at,"story.rosterBanner must be text");let nodeIds=new Set(definition.graph.nodes.map(node=>String(node.id))),line=(where,value)=>{!isObj(value)||!text(value.text)||!isObj(value.speaker)||!SPEAKERS.includes(String(value.speaker.kind))?add(at,`${where} must be { speaker: narrator | villain | npc, text }`):value.speaker.kind==="npc"&&!text(value.speaker.name)&&add(at,`${where}: an npc speaker needs a name`)};if(story.issues!==void 0){Array.isArray(story.issues)||add(at,"story.issues must be a list");let seen=new Set;for(let issue of Array.isArray(story.issues)?story.issues:[]){if(!isObj(issue)){add(at,"every story issue must be an object");continue}let nodeId=String(issue.nodeId);nodeIds.has(nodeId)||add(at,`story issue names node "${nodeId}", which the campaign does not have`),seen.has(nodeId)&&add(at,`story has two issues for node "${nodeId}"`),seen.add(nodeId);for(let field of["title","villain"])text(issue[field])||add(at,`story issue "${nodeId}": ${field} must be text`);for(let field of["blurb","rewindTaunt"])issue[field]!==void 0&&!text(issue[field])&&add(at,`story issue "${nodeId}": ${field} must be text`);for(let field of["briefing","aftermath"])issue[field]!==void 0&&line(`story issue "${nodeId}": ${field}`,issue[field])}}let finale=story.finale;finale!==void 0&&(!isObj(finale)||!text(finale.caption)||!text(finale.headline)||!text(finale.villainLine)||!Array.isArray(finale.heroLines)||finale.heroLines.length===0||finale.heroLines.some(heroLine=>!text(heroLine)))&&add(at,"story.finale must be { caption, headline, villainLine, heroLines: [text, ...] }")}function packCampaignsOf(campaigns){return(campaigns??[]).filter(entry=>isObj(entry)&&typeof entry.id=="string"&&isObj(entry.definition)&&isObj(entry.record))}var isUnscriptedAbilityIssue=issue=>issue.category==="unscripted-ability";function splitIssues(issues){return{unscripted:issues.filter(isUnscriptedAbilityIssue),defects:issues.filter(issue=>!isUnscriptedAbilityIssue(issue))}}var REQUIRED_PACK_FILES=["CREDITS.md","PERMISSION.md"],SEMVER=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/,CARD_NUMBER=/^\d+[a-z]?$/,SHA256=/^[0-9a-f]{64}$/,defaultBaseCodes,baseCodes=()=>defaultBaseCodes??=new Set(PLAYABLE_CARDS.map(card=>card.id)),defaultBaseCards,baseCardsById=cards=>cards?new Map(cards.map(card=>[card.id,card])):defaultBaseCards??=new Map(PLAYABLE_CARDS.map(card=>[card.id,card])),isObj2=value=>typeof value=="object"&&value!==null&&!Array.isArray(value),has=(record,key)=>Object.hasOwn(record,key),errorText=error=>error instanceof Error?error.message:String(error);function validatePack(input,options={}){let issues=[],add=(path,message,category)=>{issues.push(category?{path,message,category}:{path,message})};try{validateInto(input,options,add)}catch(error){add("pack",`could not be checked: ${errorText(error)}`)}return issues}function validateInto(input,options,add){if(!isObj2(input)||!isObj2(input.manifest)){add("pack.json","must be a JSON object");return}let baseAbilities=options.baseAbilities??PLAYABLE_DEPS.abilities,baseCardCodes=options.baseCardCodes??baseCodes(),supported=new Set(options.supportedFeatures??SUPPORTED_DSL_FEATURES),{manifest}=input;checkManifestFields(manifest,add);let packId=typeof manifest.id=="string"?manifest.id:"",prefix=customCardPrefix(packId),cards=[];Array.isArray(input.cards)?input.cards.forEach((card,index)=>{isObj2(card)?cards.push(card):add(`cards[${index}]`,"must be a card object")}):add("data/cards.json","must be a list of cards");let packCodes=new Set;for(let card of cards){let code=typeof card.id=="string"?card.id:"",at=`cards/${code||"?"}`;code===""?add(at,"card needs an id"):code.startsWith(prefix)?CARD_NUMBER.test(code.slice(prefix.length))||add(at,`card code must be "${prefix}<number>" with an optional face letter, e.g. "${prefix}01a"`):add(at,`card code must start with "${prefix}"`),packCodes.has(code)&&add(at,"card code is used by two cards"),packCodes.add(code),runContentCheck(at,()=>validateCard(card),add)}let knownCard=code=>packCodes.has(code)||baseCardCodes.has(code)||(options.requiredPackCards?.has(code)??!1);for(let card of cards){let at=`cards/${String(card.id)}`;card.type==="hero_identity"&&!knownCard(String(card.obligationCardId))&&add(at,`obligationCardId "${String(card.obligationCardId)}" is in neither the pack nor the base game`),card.otherFaceId!==void 0&&!knownCard(String(card.otherFaceId))&&add(at,`otherFaceId "${String(card.otherFaceId)}" is in neither the pack nor the base game`)}let cardNumbers=new Set([...packCodes].map(code=>digitsOf(code.slice(prefix.length)))),abilities=isObj2(input.abilities)?input.abilities:{};input.abilities!==void 0&&!isObj2(input.abilities)&&add("data/abilities.json","must be a JSON object");for(let[id,definition]of Object.entries(abilities)){let at=`abilities/${id}`;if(!PACK_ABILITY_ID.test(id)||!id.startsWith(prefix)?add(at,`ability id must be "${prefix}<card number>.<slug>"`):cardNumbers.has(digitsOf(id.slice(prefix.length).split(".")[0]))||add(at,"ability id names a card number the pack has no card for"),has(baseAbilities,id)&&add(at,"ability id is already defined by the base game"),!isObj2(definition)){add(at,"must be an ability definition object");continue}try{for(let problem of validateDefinition(definition))add(at,problem)}catch(error){add(at,`could not be checked: ${errorText(error)}`)}}for(let card of cards)for(let ref of abilityRefsOf(card))!has(abilities,ref)&&!has(baseAbilities,ref)&&add(`cards/${String(card.id)}`,`ability "${ref}" is defined by neither the pack nor the base game (not scripted yet)`,"unscripted-ability");let features=dslFeatures(abilities,campaignDefinitionsOf(Array.isArray(input.campaigns)?input.campaigns:void 0));for(let feature of features)supported.has(feature)||add("abilities",`uses DSL feature "${feature}", which this game version lacks`);let declared=manifest.requires?.dslFeatures;Array.isArray(declared)&&declared.join(`
|
|
6
|
-
`)!==features.join(`
|
|
7
|
-
`)&&add("pack.json requires.dslFeatures",`must list exactly the features the abilities use: ${features.join(", ")}`),checkFiles(input,add),checkCover(input,add);let isPackFace=code=>code.startsWith(prefix)&&CARD_NUMBER.test(code.slice(prefix.length))&&cardNumbers.has(digitsOf(code.slice(prefix.length))),officialById=baseCardsById(options.baseCards),officialPictures=officialCardsByPictureCode(options.baseCards??PLAYABLE_CARDS),ruleBlock=manifest.houseRule,isRuleFace=code=>manifest.kind==="house-rule"&&officialPictures.has(code)&&isObj2(ruleBlock)&&houseRuleMayRebuild(ruleBlock,code);checkLanguagesAndArt(input,code=>knownCard(code)||isPackFace(code),code=>isPackFace(code)||isRuleFace(code),add),checkHouseRule(input,officialById,add),checkStagePictures(input,cards,add);let deckIds=new Set,decks=input.decks;decks!==void 0&&!Array.isArray(decks)&&add("data/decks.json","must be a list of decks");for(let[index,deck]of(Array.isArray(decks)?decks:[]).entries()){if(!isObj2(deck)){add(`decks[${index}]`,"must be a deck object");continue}let id=typeof deck.id=="string"?deck.id:"",at=`decks/${id||index}`;(!id.startsWith(`${packId}-`)||packId==="")&&add(at,`deck id must start with "${packId}-"`),deckIds.has(id)&&add(at,"deck id is used by two decks"),deckIds.add(id),runContentCheck(at,()=>validateStarterDeck(deck),add),knownCard(String(deck.identityCardId))||add(at,`identity "${String(deck.identityCardId)}" is in neither the pack nor the base game`);for(let entry of Array.isArray(deck.cards)?deck.cards:[]){if(!isObj2(entry)){add(at,"every deck line must be an object");continue}knownCard(String(entry.cardId))||add(at,`card "${String(entry.cardId)}" is in neither the pack nor the base game`),(typeof entry.quantity!="number"||!Number.isInteger(entry.quantity)||entry.quantity<1)&&add(at,`card "${String(entry.cardId)}" needs a whole quantity of at least 1`)}}checkEncounterSets(input,cards,packId,options,add),checkScenarios(input,cards,packId,options,add);let campaigns=input.campaigns;if(campaigns!==void 0&&!Array.isArray(campaigns))add("data/campaigns.json","must be a list of campaigns");else if(campaigns!==void 0){let required=options.requiredPackContent,requiredCards=new Set((required?.cards??[]).map(card=>card.id));checkPackCampaigns({packId,campaigns,packScenarioIds:new Set((Array.isArray(input.scenarios)?input.scenarios:[]).flatMap(scenario=>isObj2(scenario)&&typeof scenario.id=="string"?[scenario.id]:[])),packSetIds:new Set((Array.isArray(input.encounterSets)?input.encounterSets:[]).flatMap(set=>isObj2(set)&&typeof set.id=="string"?[set.id]:[])),isCardId:code=>knownCard(code)||requiredCards.has(code),required:{scenarios:required?.scenarios??[],encounterSets:required?.encounterSets??[]},listedFiles:new Set(Array.isArray(manifest.files)?manifest.files.flatMap(f=>isObj2(f)&&typeof f.path=="string"?[f.path]:[]):[]),add})}checkAchievements(input,cards,packId,add)}function checkAchievements(input,cards,packId,add){let{manifest}=input,idsOf=list=>new Set((Array.isArray(list)?list:[]).flatMap(one=>isObj2(one)&&typeof one.id=="string"?[one.id]:[])),rule=manifest.houseRule,toggle=manifest.kind==="house-rule"&&isObj2(rule)&&Array.isArray(rule.traitAdditions)&&rule.traitAdditions.length>0&&rule.enablesMode===void 0,problems=packAchievementProblems(manifest.achievements,{packId,heroIds:new Set(cards.filter(card=>card.type==="hero_identity").map(card=>String(card.id))),scenarioIds:idsOf(input.scenarios),campaignIds:idsOf(input.campaigns),houseRuleToggle:toggle});for(let message of problems)add("pack.json achievements",message)}function checkEncounterSets(input,cards,packId,options,add){let sets=input.encounterSets;sets!==void 0&&!Array.isArray(sets)&&add("data/encounter-sets.json","must be a list of encounter sets");let ids=new Set;for(let[index,set]of(Array.isArray(sets)?sets:[]).entries()){if(!isObj2(set)){add(`encounterSets[${index}]`,"must be an encounter set object");continue}let id=typeof set.id=="string"?set.id:"",at=`encounterSets/${id||index}`;(!id.startsWith(`${packId}-`)||packId==="")&&add(at,`encounter set id must start with "${packId}-"`),ids.has(id)&&add(at,"encounter set id is used by two sets"),isBaseEncounterSetId(id)&&add(at,"encounter set id is a base-game set id (the base game always wins)"),ids.add(id),runContentCheck(at,()=>validateEncounterSet(set),add),Array.isArray(set.packCodes)||add(at,"packCodes must be a list");for(let field of UNSUPPORTED_SET_FIELDS)set[field]!==void 0&&add(at,`"${field}" is not available to a pack's encounter set yet`);let nemesisOf=cards.find(card=>card.type==="hero_identity"&&card.nemesisEncounterSetId===id);if(set.nemesisOfIdentityId!==void 0){let owner=cards.find(card=>card.id===set.nemesisOfIdentityId);!owner||owner.type!=="hero_identity"?add(at,`nemesisOfIdentityId "${String(set.nemesisOfIdentityId)}" is not a hero identity of this pack`):owner.nemesisEncounterSetId!==id&&add(at,`the identity names "${String(owner.nemesisEncounterSetId)}" as its nemesis set, not this one`)}else nemesisOf&&add(at,`is ${String(nemesisOf.id)}'s nemesis set, so it needs nemesisOfIdentityId (or it is offered as a modular set)`)}let required=new Set((options.requiredPackContent?.encounterSets??[]).map(set=>set.id)),belongsToPack=id=>id===packId||id.startsWith(`${packId}-`);for(let card of cards){let at=`cards/${String(card.id)}`;for(let id of Array.isArray(card.encounterSetIds)?card.encounterSetIds:[])typeof id=="string"&&(belongsToPack(id)?ids.has(id)||add(at,`encounter set "${id}" has no record in the pack's encounter sets`):required.has(id)||add(at,`encounter set "${id}" is not this pack's: a card may not join a base-game set (RRG 1.8 p. 29)`));let nemesis=card.type==="hero_identity"?card.nemesisEncounterSetId:void 0;typeof nemesis=="string"&&belongsToPack(nemesis)&&!ids.has(nemesis)&&add(at,`nemesis set "${nemesis}" has no record in the pack's encounter sets`)}}function checkHouseRule(input,officialById,add){let{manifest}=input,at=field=>`pack.json ${field}`,rule=manifest.houseRule;if(manifest.kind!=="house-rule"){rule!==void 0&&add(at("houseRule"),'only a "house-rule" pack may carry a house rule');return}if(!isObj2(rule)){add(at("houseRule"),"a house-rule pack needs its houseRule: { traitAdditions?, enablesMode? }");return}for(let key of Object.keys(rule))key!=="traitAdditions"&&key!=="enablesMode"&&add(at(`houseRule.${key}`),"is not a house rule field");let lengthOf=value=>Array.isArray(value)?value.length:0;lengthOf(input.cards)>0&&add("data/cards.json","a house-rule pack adds no cards: it changes official ones"),Object.keys(isObj2(input.abilities)?input.abilities:{}).length>0&&add("data/abilities.json","a house-rule pack carries no abilities (its rules are data, or the game's own)");for(let[field,path]of[["decks","data/decks.json"],["scenarios","data/scenarios.json"],["encounterSets","data/encounter-sets.json"],["campaigns","data/campaigns.json"]])lengthOf(input[field])>0&&add(path,"a house-rule pack carries none");manifest.altArt!==void 0&&add(at("altArt"),"a house rule's faces are its cards/<lang>/<code>.webp pictures, not altArt");let mode=rule.enablesMode;mode!==void 0&&!PACK_HOUSE_RULE_MODES.includes(mode)&&add(at("houseRule.enablesMode"),`must be one of ${PACK_HOUSE_RULE_MODES.join(", ")}`);let additions=rule.traitAdditions;if(mode!==void 0&&lengthOf(additions)>0&&add(at("houseRule"),"enablesMode and traitAdditions cannot be combined: make two packs"),additions!==void 0&&!Array.isArray(additions)){add(at("houseRule.traitAdditions"),"must be a list of { code, traits }");return}mode===void 0&&lengthOf(additions)===0&&add(at("houseRule"),"does nothing: give it traitAdditions or enablesMode");let seen=new Set;for(let[index,addition]of(Array.isArray(additions)?additions:[]).entries()){let where=at(`houseRule.traitAdditions[${index}]`);if(!isObj2(addition)){add(where,"must be { code, traits }");continue}for(let key of Object.keys(addition))key!=="code"&&key!=="traits"&&add(`${where}.${key}`,"is not a trait addition field (traits are only added)");let code=typeof addition.code=="string"?addition.code:"";(code===""||officialFaceOfCode(code,officialById)===void 0)&&add(where,`code "${code}" is not a face of an official card (a card code, or a hero identity's alter-ego "b")`),seen.has(code)&&add(where,`code "${code}" is listed twice`),seen.add(code);let traits=addition.traits;(!Array.isArray(traits)||traits.length===0||traits.some(name=>typeof name!="string"||name.trim()===""||name.length>40))&&add(where,"traits must list at least one trait name")}}var UNSUPPORTED_SET_FIELDS=["campaignSpecific","competitiveOnly","side","separateDecks","singleVillainOnly","extraModular","autoIncluded"];function checkScenarios(input,cards,packId,options,add){let scenarios=input.scenarios;scenarios!==void 0&&!Array.isArray(scenarios)&&add("data/scenarios.json","must be a list of scenarios");let ids=new Set,checked=[];for(let[index,scenario]of(Array.isArray(scenarios)?scenarios:[]).entries()){if(!isObj2(scenario)){add(`scenarios[${index}]`,"must be a scenario object");continue}let id=typeof scenario.id=="string"?scenario.id:"",at=`scenarios/${id||index}`;(!id.startsWith(`${packId}-`)||packId==="")&&add(at,`scenario id must start with "${packId}-"`),ids.has(id)&&add(at,"scenario id is used by two scenarios"),isBaseScenarioId(id)&&add(at,"scenario id is a base-game scenario id (the base game always wins)"),ids.add(id),typeof scenario.packCode=="string"&&scenario.packCode!==packId&&add(at,`packCode must be the pack's id "${packId}"`);let problems=0;runContentCheck(at,()=>{let result=validateScenario(scenario);return problems=result.errors.length,result},add),problems===0&&checked.push(scenario)}let custom={cards:[...cards,...options.requiredPackContent?.cards??[]],encounterSets:[...(Array.isArray(input.encounterSets)?input.encounterSets:[]).filter(isObj2),...options.requiredPackContent?.encounterSets??[]],scenarios:checked};for(let scenario of checked)try{for(let problem of customScenarioProblems(scenario,custom))add(`scenarios/${String(scenario.id)}`,problem)}catch(error){add(`scenarios/${String(scenario.id)}`,`could not be checked: ${errorText(error)}`)}}var digitsOf=cardNumber=>cardNumber.replace(/[a-z]$/,"");function runContentCheck(path,check,add){try{for(let message of check().errors)add(path,message)}catch(error){add(path,`could not be checked: ${errorText(error)}`)}}function checkManifestFields(manifest,add){let at=field=>`pack.json ${field}`;manifest.schema!==1&&add(at("schema"),`must be ${1}`),(typeof manifest.id!="string"||!isPackId(manifest.id))&&add(at("id"),"must be lowercase letters, digits and single dashes, at most 64 characters"),(typeof manifest.version!="string"||!SEMVER.test(manifest.version))&&add(at("version"),"must be semver"),PACK_KINDS.includes(manifest.kind)||add(at("kind"),`must be one of ${PACK_KINDS.join(", ")}`);for(let field of["name","description","license"])(typeof manifest[field]!="string"||manifest[field].trim()==="")&&add(at(field),"must be a non-empty string");(!Array.isArray(manifest.authors)||manifest.authors.length===0||manifest.authors.some(a=>typeof a!="string"||a.trim()===""))&&add(at("authors"),"must list at least one author");let requires=manifest.requires;isObj2(requires)?((typeof requires.app!="string"||requires.app.trim()==="")&&add(at("requires.app"),"must be a semver range"),Array.isArray(requires.dslFeatures)||add(at("requires.dslFeatures"),"must be a list"),!Array.isArray(requires.packs)||requires.packs.some(p=>typeof p!="string"||!isPackId(p))?add(at("requires.packs"),"must be a list of pack ids"):requires.packs.includes(manifest.id)&&add(at("requires.packs"),"a pack cannot require itself")):add(at("requires"),"is required");let contents=manifest.contents;(!isObj2(contents)||typeof contents.cards!="string")&&add(at("contents.cards"),"must name the cards file"),Array.isArray(manifest.files)||add(at("files"),"must be a list"),(typeof manifest.totalBytes!="number"||!Number.isInteger(manifest.totalBytes)||manifest.totalBytes<0)&&add(at("totalBytes"),"must be a whole number"),manifest.pictures!==void 0&&!isObj2(manifest.pictures)&&add(at("pictures"),"must be an object"),checkCredits(manifest,add)}var ISO_DATE=/^\d{4}-\d{2}-\d{2}$/;function checkCredits(manifest,add){let at=field=>`pack.json ${field}`,text2=value=>typeof value=="string"&&value.trim()!=="",permission=manifest.permission;if(permission!==void 0)if(!isObj2(permission))add(at("permission"),"must be an object");else{text2(permission.by)||add(at("permission.by"),"must say who gave permission"),permission.date!==void 0&&(typeof permission.date!="string"||!ISO_DATE.test(permission.date))&&add(at("permission.date"),"must be YYYY-MM-DD");for(let field of["evidence","scope","note"])permission[field]!==void 0&&!text2(permission[field])&&add(at(`permission.${field}`),"must be text");let status=permission.status;status!==void 0&&!PACK_PERMISSION_STATUSES.includes(status)&&add(at("permission.status"),`must be one of ${PACK_PERMISSION_STATUSES.join(", ")}`);let languages=permission.languages;if(languages!==void 0&&(!Array.isArray(languages)||languages.some(lang=>typeof lang!="string"||!isLanguageTag(lang)))&&add(at("permission.languages"),"must be a list of language tags"),status==="granted"){for(let field of["date","evidence","scope"])permission[field]===void 0&&add(at(`permission.${field}`),"is required when the status is granted");languages===void 0&&add(at("permission.languages"),"is required when the status is granted")}}manifest.templateCredit!==void 0&&!text2(manifest.templateCredit)&&add(at("templateCredit"),"must be text");let translators=manifest.translators;if(translators!==void 0)if(!isObj2(translators))add(at("translators"),"must map language tags to names");else for(let[lang,name]of Object.entries(translators))(!isLanguageTag(lang)||!text2(name))&&add(at(`translators.${lang}`),"needs a language tag and a name")}function publishIssues(manifest){let issues=[],add=(path,message)=>{issues.push({path:`pack.json ${path}`,message})},permission=manifest.permission;if(!isObj2(permission))return add("permission","is required to publish: record the creator's grant (status, by, date, evidence, scope, languages)"),issues;if(permission.status!=="granted"){let status=typeof permission.status=="string"?permission.status:"missing",note=typeof permission.note=="string"&&permission.note.trim()!==""?`: ${permission.note}`:"";return add("permission.status",`is ${status}, not granted, so the pack is not published${note}`),issues}let covered=new Set(Array.isArray(permission.languages)?permission.languages:[]),missing=(manifest.languages?.available??[]).filter(lang=>!covered.has(lang));return missing.length>0&&add("permission.languages",`does not cover ${missing.join(", ")}: a translation needs the creator's permission too`),issues}function checkLanguagesAndArt(input,knownCard,isPackFace,add){let{manifest}=input,at=field=>`pack.json ${field}`,languages=manifest.languages,available;if(languages!==void 0)if(!isObj2(languages))add(at("languages"),"must be { base, available }");else{let list=languages.available;!Array.isArray(list)||list.length===0||list.some(l=>typeof l!="string"||!isLanguageTag(l))?add(at("languages.available"),'must list language tags such as "en"'):(available=new Set(list),available.size!==list.length&&add(at("languages.available"),"lists a language twice"),(typeof languages.base!="string"||!available.has(languages.base))&&add(at("languages.base"),"must be one of the available languages")),languages.text!==void 0&&(typeof languages.text!="string"||!isLanguageTag(languages.text))&&add(at("languages.text"),"must be a language tag")}let listed=new Set(Array.isArray(manifest.files)?manifest.files.flatMap(f=>isObj2(f)&&typeof f.path=="string"?[f.path]:[]):[]);for(let path of listed){let picture=parsePackCardImagePath(path);picture&&(available?available.has(picture.lang)||add(path,`language "${picture.lang}" is not in languages.available`):add(path,'card pictures need "languages" in pack.json'),isPackFace(picture.code)||add(path,`"${picture.code}" is not a card of this pack`+(manifest.kind==="house-rule"?" (a house rule rebuilds only its trait additions' faces, or the Balanced cards for enablesMode balanced)":"")))}let altArt=manifest.altArt;if(altArt!==void 0){if(!isObj2(altArt)){add(at("altArt"),"must map languages to card codes to file paths");return}for(let[lang,byCode]of Object.entries(altArt)){if(!isObj2(byCode)){add(at(`altArt.${lang}`),"must map card codes to file paths");continue}(!isLanguageTag(lang)||available&&!available.has(lang))&&add(at(`altArt.${lang}`),"language is not in languages.available");for(let[code,path]of Object.entries(byCode))knownCard(code)||add(at(`altArt.${lang}.${code}`),"is a card neither the pack nor the base game has"),(typeof path!="string"||!listed.has(path))&&add(at(`altArt.${lang}.${code}`),`"${String(path)}" is not a listed file`)}}}function checkStagePictures(input,cards,add){let languages=input.manifest.languages,base=isObj2(languages)&&typeof languages.base=="string"?languages.base:void 0;if(!base||!Array.isArray(input.manifest.files))return;let shipped=new Set;for(let f of input.manifest.files){let picture=isObj2(f)&&typeof f.path=="string"?parsePackCardImagePath(f.path):void 0;picture?.lang===base&&shipped.add(picture.code)}for(let card of cards){let id=String(card.id),wanted=packStagedPictureCodes(card);if(wanted.length<2)continue;let number=digitsOf(id);if([...shipped].some(code=>digitsOf(code)===number))for(let code of wanted)shipped.has(code)||add(`cards/${id}`,`stage picture "cards/${base}/${code}.webp" is not a listed file`)}}var COVER_ASPECT={min:.5,max:.8},COVER_HEIGHT={min:300,max:4096};function checkCover(input,add){let cover=input.manifest.cover;if(cover===void 0)return;let at="pack.json cover";if(typeof cover!="string"||!isPackCoverPath(cover)){add(at,'must be the path of a .webp file in the pack, such as "cover.webp"');return}let bytes=input.files instanceof Map?input.files.get(cover):void 0;if(!(bytes instanceof Uint8Array)){add(at,`"${cover}" is not a file of the pack`);return}bytes.length>PACK_COVER_MAX_BYTES&&add(at,`"${cover}" is ${bytes.length} bytes, more than a cover's ${PACK_COVER_MAX_BYTES}`);let size=webpSize(bytes);if(!size){add(at,`"${cover}" is not a WebP picture`);return}let{width,height}=size,aspect=width/height;(aspect<COVER_ASPECT.min||aspect>COVER_ASPECT.max)&&add(at,`"${cover}" is ${width}x${height}: a cover is portrait, about 600x984 (width/height 0.5 to 0.8)`),(height<COVER_HEIGHT.min||height>COVER_HEIGHT.max)&&add(at,`"${cover}" is ${width}x${height}: its height must be ${COVER_HEIGHT.min} to ${COVER_HEIGHT.max} pixels`)}function checkFiles(input,add){let{manifest,files}=input;if(!(files instanceof Map)){add("files","the pack's files must be a Map of path to bytes");return}for(let[path,bytes]of files)bytes instanceof Uint8Array||add(String(path),"file content must be bytes");if(!Array.isArray(manifest.files))return;let listed=new Set,total=0;for(let entry of manifest.files){if(!isObj2(entry)||typeof entry.path!="string"){add("pack.json files","every entry needs a string path");continue}let path=entry.path;if(!isSafePackPath(path)){add(path,"unsafe file path (must be relative, with / separators and no .. or empty parts)");continue}if(path==="pack.json"&&add(path,"pack.json does not list itself"),listed.has(path)&&add(path,"listed twice"),listed.add(path),typeof entry.sha256!="string"||!SHA256.test(entry.sha256)){add(path,"sha256 must be 64 lowercase hex characters");continue}if(typeof entry.bytes!="number"||!Number.isInteger(entry.bytes)||entry.bytes<0){add(path,"bytes must be a whole number");continue}let bytes=files.get(path);if(!(bytes instanceof Uint8Array)){add(path,"listed in pack.json but missing from the pack");continue}total+=entry.bytes,bytes.length!==entry.bytes?add(path,`size is ${bytes.length} bytes, pack.json says ${entry.bytes}`):sha256Hex(bytes)!==entry.sha256&&add(path,"sha256 does not match pack.json")}for(let path of files.keys())listed.has(path)||add(path,"in the pack but not listed in pack.json");Number.isInteger(manifest.totalBytes)&&manifest.totalBytes!==total&&add("pack.json totalBytes",`is ${manifest.totalBytes}, the listed files add up to ${total}`);for(let required of REQUIRED_PACK_FILES){let bytes=files.get(required);bytes instanceof Uint8Array?bytes.length===0&&add(required,"required file is empty"):add(required,"required file is missing")}if(isObj2(manifest.contents))for(let[role,path]of Object.entries(manifest.contents))typeof path=="string"&&!listed.has(path)&&add(`pack.json contents.${role}`,`"${path}" is not a listed file`);if(isObj2(manifest.pictures))for(let[role,byCard]of Object.entries(manifest.pictures)){if(!isObj2(byCard)){add(`pack.json pictures.${role}`,"must map card codes to file paths");continue}for(let[code,path]of Object.entries(byCard))(typeof path!="string"||!listed.has(path))&&add(`pack.json pictures.${role}.${code}`,`"${String(path)}" is not a listed file`)}}function abilityRefsOf(value){let refs=[],visit2=(node,key)=>{if(Array.isArray(node))for(let item of node)visit2(item,key);else if(isObj2(node)){key==="abilities"&&typeof node.id=="string"&&refs.push(node.id);for(let[childKey,child]of Object.entries(node))visit2(child,childKey)}};return visit2(value,""),refs}var decoder=new TextDecoder;function readPackInput(manifest,files){let parse=path=>{if(path===void 0)return;let bytes=files.get(path);if(!bytes)throw new Error(`${path}: missing from the pack`);try{return JSON.parse(decoder.decode(bytes))}catch{throw new Error(`${path}: not valid JSON`)}},list=path=>{let parsed=parse(path);if(parsed!==void 0){if(!Array.isArray(parsed))throw new Error(`${path}: must be a JSON array`);return parsed}},abilities=parse(manifest.contents.abilities)??{};if(typeof abilities!="object"||abilities===null||Array.isArray(abilities))throw new Error(`${manifest.contents.abilities}: must be a JSON object`);let decks=list(manifest.contents.decks),scenarios=list(manifest.contents.scenarios),encounterSets=list(manifest.contents.encounterSets),campaigns=list(manifest.contents.campaigns);return{manifest,files,cards:list(manifest.contents.cards)??[],abilities,...decks?{decks}:{},...scenarios?{scenarios}:{},...encounterSets?{encounterSets}:{},...campaigns?{campaigns}:{}}}export{dslFeatures,campaignDefinitionsOf,SUPPORTED_DSL_FEATURES,PACK_ABILITY_ID,definePackAbilities,sha256Hex,isPlainJson,checkPackCampaigns,packCampaignsOf,isUnscriptedAbilityIssue,splitIssues,REQUIRED_PACK_FILES,validatePack,publishIssues,abilityRefsOf,readPackInput};
|