feat(mods): support Dagor-style BLK patches and include compilation

Add native-style *.blk.patch.blk and client/config-blk.patch.blk incremental patching alongside compile-time include/includeOnce and Dagor @-directive expansion (@override, @override-last, @replace, @delete, @delete-last, @delete-all, @clone, @clone-last, @inherit, @after, @before, indexed paths, unquoted @ syntax, triple-quoted strings, packed hex colors, and CDK #/develop/gameBase/ paths) while preserving full *.blk.patch.jsonc backwards compatibility.
This commit is contained in:
N0VAN0M4LY committed 2026-12-04 02:36:16 +08:00
1 parent 69d95df88e
commit 65363ce9de
12 files changed
+1684 -268

No files matched your search

+110 -90
View File
@@ -12,7 +12,7 @@ War Thunder's Dagor Engine stores nearly all game configurations in **BLK (DataB
2. **Duplicate parameter names are allowed inside the same block**: for instance, `slaveUnit:t="launcher_a"` followed immediately by `slaveUnit:t="launcher_b"` (converting naively to a plain JSON object would overwrite the first key!);
3. **Duplicate sibling block names are allowed under the same parent**: most notably in `shop.blk`, where every army/aviation branch contains multiple sibling `range { ... }` blocks side by side.
Compare this 8-line stock text `.blk` excerpt (`us_m2a4` in `wpcost.blk`) side by side with its `.blk.patch.jsonc` patch operation:
Compare this 8-line stock text `.blk` excerpt (`us_m2a4` in `wpcost.blk`) side by side with its `.blk.patch.blk` incremental patch:
```blk
// Stock readable text BLK (excerpt from char.vromfs.bin -> config/wpcost.blk)
@@ -26,18 +26,11 @@ us_m2a4 {
}
```
```jsonc
// Matching incremental patch: client/packs/char.vromfs.bin/config/wpcost.blk.patch.jsonc
```blk
// Matching incremental patch (recommended): client/packs/char.vromfs.bin/config/wpcost.blk.patch.blk
// Touches ONLY us_m2a4's Realistic reward multiplier without clobbering other fields or other mods!
{
"ops": [
{
"op": "setParam",
"path": ["us_m2a4"],
"name": "rewardMulHistorical",
"value": { "type": "real", "value": 1.2 }
}
]
"@override:us_m2a4" {
"@override:rewardMulHistorical":r = 1.2
}
```
@@ -66,17 +59,79 @@ Place your files under `client/packs/<pack-path>/` matching the target archive's
The patcher determines how to process each file under `client/packs/<pack>/` by its filename suffix:
1. **`<target-path>.patch.jsonc` → Structured Incremental BLK Patch**: decodes the target `.blk` into a type-preserving tree, applies `ops` in order, and re-encodes a self-contained binary BLK;
1. **`<target-path>.patch.blk` (Recommended) or `<target-path>.patch.jsonc` → Incremental BLK Patch**: decodes the target `.blk` into a type-preserving tree, applies the patch in order, and re-encodes a self-contained binary BLK. Different mods may mix `.patch.blk` and `.patch.jsonc` on the same target and stack cleanly; within a single mod, pick one format per target file;
2. **`<target-path>.patch.csv` → Incremental Localization CSV Merge**: merges rows by column 0 (updating only the non-empty language columns you provide on existing keys, and appending new keys at the end);
3. **Any other file (e.g. `us_m2a4_mod_demo.blk`, `us_m2a4_mod_demo_ico.svg`) → Add or Replace File**:
- If the path ends with `.blk` and your source file is **plain text BLK** (for example, extracted and edited from your stock client), the builder automatically compiles it into **binary BLK** for the engine;
- If the path ends with `.blk` and your source file is **plain text BLK**, the builder automatically expands `include` / `includeOnce` and Dagor `@override:` / `@delete:` directives and compiles it into **binary BLK** for the engine;
- Binary `.blk` files and other assets (`.svg`, `.ddsx`, `.nut`, `.tpl`, `.css`) are written into the archive as-is.
---
## 4. Complete BLK Incremental Patch (`*.blk.patch.jsonc`) Reference
## 4. Complete BLK Incremental Patch Reference
### 4.1 Document Format & Path Addressing
Two incremental BLK patch formats are supported:
- **`*.blk.patch.blk` (Recommended)**: native Dagor BLK syntax with `include`, `@override:`, `@delete:`, and `@clone:`—compact and lets you paste stock BLK blocks directly;
- **`*.blk.patch.jsonc` (Compatible / Programmatic)**: structured JSONC op list, kept for backwards compatibility and automated generators.
### 4.1 Dagor-Style BLK Patches (`*.blk.patch.blk`) & `include` Compilation
Statements execute **strictly top-to-bottom in source order**, with identical rules in both `*.blk.patch.blk` and standalone text `.blk` files (unprefixed items always append/add; modifying existing items explicitly uses `@` directives).
#### ① File Inheritance (`include` / `includeOnce`)
| Syntax | Behavior |
| --- | --- |
| `include "germ_pzkpfw_maus.blk"` | Loads and expands the target `.blk` into the current block (resolved relative to the current pack directory; supports `../`, `/gamedata/...`, `#/gamedata/...`, and War Thunder CDK `#/develop/gameBase/...`). |
| `includeOnce "../common/smoke.blk"` | Same as `include`, but expands a given normalized path at most once per compilation. |
- `include` resolves against the live in-memory pack archive (stock files + earlier mods) as well as sibling `.blk` files in the same mod, with automatic circular-include detection;
- All `@` directives accept **both quoted** (`"@override:model":t = "..."`) and **unquoted** (`@override:model:t = "..."`, `@override:ikPilot { ... }`) Dagor syntax;
- Ideal for derived vehicles without copying thousands of stock lines:
```blk
// client/packs/aces.vromfs.bin/gamedata/units/tankmodels/germ_pzkpfw_walross.blk
include "germ_pzkpfw_maus.blk"
"@override:model":t = "pzkpfw_VIII_walross"
"@delete:commonWeapons" {}
commonWeapons {
// Paste new weapon blocks directly here
}
```
#### ② Parameter Directives
| Syntax | Behavior | Notes |
| --- | --- | --- |
| `slaveUnit:t = "extra"` | **Append param** | Preserves existing same-named params (for repeated keys) |
| `"@override:economicRankArcade":i = 18` | **Set / overwrite** | Replaces first match and deduplicates, or appends if absent (do not quote `:i` / `:r` numbers) |
| `"@override-last:slaveUnit":t = "new"` | **Overwrite last match** | Replaces only the last same-named param without touching earlier entries (appends if absent) |
| `"@delete:showOnlyWhenBought":b = no` | **Delete first** matching param | Dummy type/value is ignored; no-op if absent |
| `"@delete-last:slaveUnit":t = ""` | **Delete last** matching param | Removes only the last same-named param |
| `"@delete-all:slaveUnit":t = ""` | **Delete all** matching params | Removes every param with that name in the current block |
#### ③ Block Directives
| Syntax | Behavior | Notes |
| --- | --- | --- |
| `Weapon { ... }` | **Add child block** | Appends a new sibling block without clobbering existing same-named blocks |
| `"@override:us_m2a4" { ... }` | **Edit existing block** | Supports `name[index]` (e.g. `"@override:range[0]"`); creates the block when absent without an index |
| `"@override-last:Weapon" { ... }` | **Edit last matching block** | Edits the last sibling with that name (creates if absent) |
| `"@replace:commonWeapons" { ... }` | **Replace block in place** | Replaces the matched block in place (preserving sibling order); supports `name[index]` |
| `"@delete:commonWeapons" {}` | **Delete first** matching block | Supports `name[index]`; body must be empty |
| `"@delete-last:Weapon" {}` | **Delete last** matching block | Removes only the last sibling with that name; body must be empty |
| `"@delete-all:Weapon" {}` | **Delete all** same-named blocks | Removes all sibling blocks with that name; body must be empty |
| `"@clone:Weapon" { ... }` / `"@clone-last:Weapon" { ... }` | **Same-name clone** | Deep-clones the first/last sibling with that name, appends it, and applies body edits |
| `"@clone:us_m2a4->us_m2a4_mod" { ... }` | **Clone under new name** | Deep-clones source (supports relative `a/b/src` or root `/src`) into `newName` (replacing existing `newName` in place) and applies body edits |
| `"@inherit:base_weapon" {}` | **Inherit into block** | Copies params/blocks from a sibling or root template block into the current block (optional body applies overrides) |
| `"@after:<anchor>:<newName>" { ... }` / `"@before:<anchor>:<newName>" { ... }` | **Anchored insertion** | Inserts right after/before a sibling anchor (supports `anchor[index]` and `@clone:src->dst` as target) |
> **Typo Guard & Escaping**: Any unknown `"@xxx:..."` prefix fails immediately with a line number so misspelled directives are never silently baked into binary BLKs. Use `@@` to escape a literal leading `@`.
---
### 4.2 Structured JSONC Patches (`*.blk.patch.jsonc`, Backwards-Compatible Format)
#### Document Format & Path Addressing
```jsonc
{
@@ -302,21 +357,14 @@ Example `client/packs/lang.vromfs.bin/lang/units.csv.patch.csv`:
---
## 7. Patching Root `config.blk` (`client/config-blk.patch.jsonc`)
## 7. Patching Root `config.blk` (`client/config-blk.patch.blk` / `.jsonc`)
If your mod needs to adjust the client root `config.blk` (for example enabling sound mods via `sound{ enable_mod:b=yes }` or setting a custom hangar `hangarBlk:t="..."`), place a standard BLK patch at `client/config-blk.patch.jsonc`:
If your mod needs to adjust the client root `config.blk` (for example enabling sound mods via `sound{ enable_mod:b=yes }` or setting a custom hangar `hangarBlk:t="..."`), place a BLK patch at `client/config-blk.patch.blk` (recommended; `client/config-blk.patch.jsonc` is also supported):
```jsonc
{
"ops": [
{
"op": "setParam",
"path": ["sound"],
"name": "enable_mod",
"value": { "type": "bool", "value": true },
"createBlocks": true
}
]
```blk
// client/config-blk.patch.blk
"@override:sound" {
"@override:enable_mod":b = yes
}
```
@@ -339,12 +387,12 @@ mods/demo-standalone-m2a4/
└─ packs/
├─ aces.vromfs.bin/
│ └─ gamedata/units/tankmodels/
│ └─ us_m2a4_mod_demo.blk # ① Tank physics/armor/weapons (copied from stock us_m2a4.blk)
│ └─ us_m2a4_mod_demo.blk # ① Inherits stock us_m2a4.blk via include & boosts speed
├─ char.vromfs.bin/
│ └─ config/
│ ├─ wpcost.blk.patch.jsonc # ② Clone economy, BR, modifications & ammo racks
│ ├─ shop.blk.patch.jsonc # ③ Insert into US Army column 0 (Rank I)
│ └─ unittags.blk.patch.jsonc # ④ Clone unit class tags & test-drive mission
│ ├─ wpcost.blk.patch.blk # ② Clone economy, BR, modifications & ammo racks
│ ├─ shop.blk.patch.blk # ③ Insert into US Army column 0 (Rank I)
│ └─ unittags.blk.patch.blk # ④ Clone unit class tags & test-drive mission
└─ lang.vromfs.bin/
└─ lang/
└─ units.csv.patch.csv # ⑤ Localized _shop / _0 / _1 / _2 names
@@ -375,82 +423,54 @@ mods/demo-standalone-m2a4/
#### ① Tank Model Definition `client/packs/aces.vromfs.bin/gamedata/units/tankmodels/us_m2a4_mod_demo.blk`
Extract stock `gamedata/units/tankmodels/us_m2a4.blk` from `aces.vromfs.bin` using any method from Chapter 01 Section 2, and save it as `us_m2a4_mod_demo.blk`. Keep `model:t="m2a4"` at the top (so the engine reuses the stock M2A4 3D mesh and textures) and raise its speed and acceleration (plain text `.blk` compiles to binary automatically on build):
Inherit stock `us_m2a4.blk` directly via `include` (no need to unpack or copy thousands of stock lines) and override just its speed and acceleration (compiled to binary automatically on build):
```blk
model:t="m2a4"
// ... (keep the rest of stock us_m2a4.blk unchanged; tweak mobility below to feel the difference) ...
maxFwdSpeed:r=90.0
maxRevSpeed:r=25.0
maxAccel:r=12.0
include "us_m2a4.blk"
"@override:maxFwdSpeed":r = 90.0
"@override:maxRevSpeed":r = 25.0
"@override:maxAccel":r = 12.0
```
#### ② Economy & BR Patch `client/packs/char.vromfs.bin/config/wpcost.blk.patch.jsonc`
#### ② Economy & BR Patch `client/packs/char.vromfs.bin/config/wpcost.blk.patch.blk`
Use `cloneBlock` to copy `us_m2a4` (inheriting all weapons, shells, modifications, and backup settings), and set `reqAir` to `"us_m2a4"`, RP cost to `1000`, SL price to `500`, and all mode `mrank` values to `1` (displayed BR **1.3**):
Use `@clone:` to copy `us_m2a4` (inheriting all weapons, shells, modifications, and backup settings), and set `reqAir` to `"us_m2a4"`, RP cost to `1000`, SL price to `500`, and all mode `mrank` values to `1` (displayed BR **1.3**):
```jsonc
{
"ops": [
{
"op": "cloneBlock",
"from": ["us_m2a4"],
"toParent": [],
"newName": "us_m2a4_mod_demo",
"replaceExisting": true,
"ops": [
{ "op": "setParam", "path": [], "name": "reqAir", "value": "us_m2a4" },
{ "op": "setParam", "path": [], "name": "reqExp", "value": { "type": "int", "value": 1000 } },
{ "op": "setParam", "path": [], "name": "value", "value": { "type": "int", "value": 500 } },
{ "op": "setParam", "path": [], "name": "economicRank", "value": { "type": "int", "value": 1 } },
{ "op": "setParam", "path": [], "name": "economicRankArcade", "value": { "type": "int", "value": 1 } },
{ "op": "setParam", "path": [], "name": "economicRankHistorical", "value": { "type": "int", "value": 1 } },
{ "op": "setParam", "path": [], "name": "economicRankSimulation", "value": { "type": "int", "value": 1 } }
]
}
]
```blk
"@clone:us_m2a4->us_m2a4_mod_demo" {
"@override:reqAir":t = "us_m2a4"
"@override:reqExp":i = 1000
"@override:value":i = 500
"@override:economicRank":i = 1
"@override:economicRankArcade":i = 1
"@override:economicRankHistorical":i = 1
"@override:economicRankSimulation":i = 1
}
```
#### ③ Tech-Tree Slot Patch `client/packs/char.vromfs.bin/config/shop.blk.patch.jsonc`
#### ③ Tech-Tree Slot Patch `client/packs/char.vromfs.bin/config/shop.blk.patch.blk`
Insert `us_m2a4_mod_demo` into `country_usa -> army -> range[0]` right after `us_m3a1_stuart` (just before the `us_m5a1_stuart` Rank II break) with an explicit `reqAir: "us_m2a4"`, creating a clean Rank I side-branch arrow from `M2A4` without disturbing the stock Stuart chain:
Insert `us_m2a4_mod_demo` into `country_usa -> army -> range[0]` right after `us_m3a1_stuart` (just before the `us_m5a1_stuart` Rank II break) with an explicit `reqAir:t = "us_m2a4"`, creating a clean Rank I side-branch arrow from `M2A4` without disturbing the stock Stuart chain:
```jsonc
{
"ops": [
{
"op": "addBlock",
"path": ["country_usa", "army", "range[0]"],
"name": "us_m2a4_mod_demo",
"after": "us_m3a1_stuart",
"block": {
"params": [
{ "name": "rank", "value": { "type": "int", "value": 1 } },
{ "name": "reqAir", "value": "us_m2a4" }
]
```blk
"@override:country_usa" {
"@override:army" {
"@override:range[0]" {
"@after:us_m3a1_stuart:us_m2a4_mod_demo" {
rank:i = 1
reqAir:t = "us_m2a4"
}
}
]
}
}
```
#### ④ Unit Tags & Test-Drive Patch `client/packs/char.vromfs.bin/config/unittags.blk.patch.jsonc`
#### ④ Unit Tags & Test-Drive Patch `client/packs/char.vromfs.bin/config/unittags.blk.patch.blk`
Clone `us_m2a4` in `unittags.blk` so the new ID inherits `type:t="tank"`, `hangar_place:t="tank"`, the ground `testFlight` mission, and light-tank tags:
```jsonc
{
"ops": [
{
"op": "cloneBlock",
"from": ["us_m2a4"],
"toParent": [],
"newName": "us_m2a4_mod_demo",
"replaceExisting": true
}
]
}
```blk
"@clone:us_m2a4->us_m2a4_mod_demo" {}
```
#### ⑤ Localization Patch `client/packs/lang.vromfs.bin/lang/units.csv.patch.csv`
+111 -91
View File
@@ -12,7 +12,7 @@ Dagor 引擎使用自研的 **BLK(DataBlock)** 格式存储几乎所有游
2. **同一个块内允许出现多个同名参数**:例如 `slaveUnit:t="launcher_a"` 下面紧跟第二行 `slaveUnit:t="launcher_b"`(如果直接转成普通 JSON 对象,前一行就会被后一行覆盖丢失!);
3. **同一个父块下允许并列多个同名子块**:最典型的就是科技树 `shop.blk`,每个陆军/空军分支下并列着好几个同名的 `range { ... }` 子块。
对比下面这段 8 行原版文本 `.blk`(节选自 `wpcost.blk` 的 `us_m2a4`)与对应的 `.blk.patch.jsonc` 增量补丁,你立刻就能看懂两者的对应关系:
对比下面这段 8 行原版文本 `.blk`(节选自 `wpcost.blk` 的 `us_m2a4`)与对应的 `.blk.patch.blk` 增量补丁,你立刻就能看懂两者的对应关系:
```blk
// 原版可读文本 BLK(char.vromfs.bin -> config/wpcost.blk 节选)
@@ -26,18 +26,11 @@ us_m2a4 {
}
```
```jsonc
// 对应的增量补丁:client/packs/char.vromfs.bin/config/wpcost.blk.patch.jsonc
```blk
// 对应的增量补丁(推荐格式):client/packs/char.vromfs.bin/config/wpcost.blk.patch.blk
// 只修改 us_m2a4 的历史模式收益倍率,不会影响其他模组对别的字段或载具的改动
{
"ops": [
{
"op": "setParam",
"path": ["us_m2a4"],
"name": "rewardMulHistorical",
"value": { "type": "real", "value": 1.2 }
}
]
"@override:us_m2a4" {
"@override:rewardMulHistorical":r = 1.2
}
```
@@ -66,17 +59,79 @@ us_m2a4 {
构建器根据你在 `client/packs/<包>/` 下放置的文件名自动决定处理方式:
1. **`<原路径>.patch.jsonc` → BLK 结构化增量补丁**:解析目标 `.blk` 为保留完整类型的内存树,按 `ops` 逐条修改后重新编码为自包含二进制 BLK 写回;
1. **`<原路径>.patch.blk`(推荐)或 `<原路径>.patch.jsonc` → BLK 增量补丁**:解析目标 `.blk` 为保留完整类型的内存树,按顺序应用补丁并重新编码为自包含二进制 BLK 写回。不同模组可对同一目标混用 `.patch.blk` 与 `.patch.jsonc` 并按加载顺序叠加;单个模组内对同一目标请二选一;
2. **`<原路径>.patch.csv` → CSV 本地化增量合并**:按第 1 列词条键合并进目标 `.csv`(已有键只更新你填写的语言列,新键追加到表尾);
3. **其余文件(如 `us_m2a4_mod_demo.blk`、`us_m2a4_mod_demo_ico.svg`)→ 新增或替换文件**:
- 如果路径以 `.blk` 结尾且你的源文件是**可读文本 BLK**(如从原版客户端解包修改得到的),构建器会自动将其编译为游戏引擎所需的**二进制 BLK** 写进包内;
- 如果路径以 `.blk` 结尾且你的源文件是**可读文本 BLK**,构建器会自动展开其中的 `include` / `includeOnce` 与 `@override:` / `@delete:` 等 Dagor 指令,并编译为游戏引擎所需的**二进制 BLK** 写进包内;
- 如果已经是二进制 BLK,或是 `.svg` / `.ddsx` / `.nut` / `.tpl` / `.css`,则原样写入包内。
---
## 4. BLK 增量补丁(`*.blk.patch.jsonc`)完整手册
## 4. BLK 增量补丁完整手册
### 4.1 基本格式与路径寻址
构建器同时支持两套 BLK 增量补丁格式:
- **`*.blk.patch.blk`(首选推荐)**:Dagor 原生 BLK 语法,直接支持粘贴原版 BLK 子块、`include` 继承与 `@override:` / `@delete:` / `@clone:` 指令,写法最紧凑;
- **`*.blk.patch.jsonc`(向后兼容 / 脚本生成)**:结构化 JSONC 操作列表,适合自动化脚本生成与已有旧模组兼容。
### 4.1 Dagor 风格 BLK 增量补丁(`*.blk.patch.blk`)与 `include` 编译
所有语句**严格按源码从上到下顺序执行**,且在 `*.blk.patch.blk` 与新增文本 `.blk` 中**语义完全统一**(无前缀永远表示新增/追加,修改已有项显式使用 `@` 指令)。
#### ① 文件引入指令(`include` / `includeOnce`)
| 语法 | 作用 |
| --- | --- |
| `include "germ_pzkpfw_maus.blk"` | 在当前块位置读取并展开目标 `.blk`(相对当前文件在 pack 内的目录;也支持 `../`、包根路径 `/gamedata/...`、`#/gamedata/...` 及战雷 CDK 路径 `#/develop/gameBase/...`)。 |
| `includeOnce "../common/smoke.blk"` | 同 `include`,但在同一次编译链路中同一文件只展开一次。 |
- `include` 会直接查找当前 pack 内存档案(包含原版文件与前置模组修改后的结果)以及同模组内其他待写入 `.blk` 文件,且自动检测循环引用;
- 所有 `@` 指令同时支持**带引号**(`"@override:model":t = "..."`)和**不带引号**(`@override:model:t = "..."`、`@override:ikPilot { ... }`)两种战雷原生写法;
- 非常适合基于原版载具派生新车,无需复制几千行原版 `.blk`:
```blk
// client/packs/aces.vromfs.bin/gamedata/units/tankmodels/germ_pzkpfw_walross.blk
include "germ_pzkpfw_maus.blk"
"@override:model":t = "pzkpfw_VIII_walross"
"@delete:commonWeapons" {}
commonWeapons {
// 直接粘贴新的武器块即可
}
```
#### ② 参数(Param)指令
| 语法 | 作用 | 说明 |
| --- | --- | --- |
| `slaveUnit:t = "extra"` | **追加参数** | 保留已有同名参数,适合可重复键 |
| `"@override:economicRankArcade":i = 18` | **覆盖/设值** | 存在则覆盖首个并去重,不存在则新增(注意数值 `:i` / `:r` 不要加引号) |
| `"@override-last:slaveUnit":t = "new"` | **覆盖末项** | 只替换最后一个同名参数,不动前面同名项(不存在则追加) |
| `"@delete:showOnlyWhenBought":b = no` | **删除首个**同名参数 | 占位类型/值会被忽略,不存在则静默跳过 |
| `"@delete-last:slaveUnit":t = ""` | **删除末项**同名参数 | 只删最后一个同名参数 |
| `"@delete-all:slaveUnit":t = ""` | **删除全部**同名参数 | 清空当前块内全部同名参数 |
#### ③ 子块(Block)指令
| 语法 | 作用 | 说明 |
| --- | --- | --- |
| `Weapon { ... }` | **新增子块** | 追加同名子块(不会覆盖已有同名块) |
| `"@override:us_m2a4" { ... }` | **进入已有块修改** | 支持 `name[index]`(如 `"@override:range[0]"`);不带索引且块不存在时自动新建 |
| `"@override-last:Weapon" { ... }` | **进入末个同名块修改** | 修改最后一个同名子块(不存在则新建) |
| `"@replace:commonWeapons" { ... }` | **原地整块替换** | 原地替换为全新子块(保持原本排序位置);支持 `name[index]` |
| `"@delete:commonWeapons" {}` | **删除首个**匹配子块 | 支持 `name[index]`;花括号必须为空 |
| `"@delete-last:Weapon" {}` | **删除末个**同名子块 | 只删最后一个同名子块;花括号必须为空 |
| `"@delete-all:Weapon" {}` | **删除全部**同名子块 | 清空全部同名子块;花括号必须为空 |
| `"@clone:Weapon" { ... }` / `"@clone-last:Weapon" { ... }` | **同名克隆** | 深拷贝首个/末个同名子块并追加,在花括号内微调 |
| `"@clone:us_m2a4->us_m2a4_mod" { ... }` | **改名克隆** | 深拷贝源块(支持 `a/b/src` 相对路径与 `/root/src` 根路径)为新名(若目标已存在则原地替换),并在花括号内微调 |
| `"@inherit:base_weapon" {}` | **块内继承** | 将同级或根级模板块的内容拷入当前块(花括号内可继续写覆写语句) |
| `"@after:<锚点>:<新块名>" { ... }` / `"@before:<锚点>:<新块名>" { ... }` | **科技树锚点插队** | 插在指定兄弟块之后/之前(锚点支持 `name[index]`;也可写 `"@after:us_m2a4:@clone:us_m2a4->new_tank"`) |
> **拼写保护与转义**:任何未注册的 `"@xxx:..."` 前缀都会直接报带行号的错误(防止拼错指令被静默写入二进制);若极少数情况需要字面量以 `@` 开头,可用 `@@` 转义为单个 `@`。
---
### 4.2 JSONC 结构化增量补丁(`*.blk.patch.jsonc`,兼容与脚本生成格式)
#### 基本格式与路径寻址
```jsonc
{
@@ -302,21 +357,14 @@ CSV 补丁文件写法示例(`client/packs/lang.vromfs.bin/lang/units.csv.patc
---
## 7. 修改游戏根目录 `config.blk`(`client/config-blk.patch.jsonc`)
## 7. 修改游戏根目录 `config.blk`(`client/config-blk.patch.blk` / `.jsonc`)
如果模组需要调整游戏根目录的 `config.blk`(例如开启音效模组开关 `sound{ enable_mod:b=yes }` 或指定自定义机库 `hangarBlk:t="..."`),放一份标准 BLK 补丁到 `client/config-blk.patch.jsonc` 即可:
如果模组需要调整游戏根目录的 `config.blk`(例如开启音效模组开关 `sound{ enable_mod:b=yes }` 或指定自定义机库 `hangarBlk:t="..."`),放一份 BLK 补丁到 `client/config-blk.patch.blk`(推荐,同样兼容 `client/config-blk.patch.jsonc`)即可:
```jsonc
{
"ops": [
{
"op": "setParam",
"path": ["sound"],
"name": "enable_mod",
"value": { "type": "bool", "value": true },
"createBlocks": true
}
]
```blk
// client/config-blk.patch.blk
"@override:sound" {
"@override:enable_mod":b = yes
}
```
@@ -339,12 +387,12 @@ mods/demo-standalone-m2a4/
└─ packs/
├─ aces.vromfs.bin/
│ └─ gamedata/units/tankmodels/
│ └─ us_m2a4_mod_demo.blk # ① 载具物理/装甲/武器定义(基于原版 us_m2a4.blk 修改)
│ └─ us_m2a4_mod_demo.blk # ① 通过 include 继承原版 us_m2a4.blk 并调高极速
├─ char.vromfs.bin/
│ └─ config/
│ ├─ wpcost.blk.patch.jsonc # ② 克隆经济、分房权重、改装件与弹药架
│ ├─ shop.blk.patch.jsonc # ③ 挂入美系陆军第 1 列 I 级科技树
│ └─ unittags.blk.patch.jsonc # ④ 克隆载具分类标签与试车场配置
│ ├─ wpcost.blk.patch.blk # ② 克隆经济、分房权重、改装件与弹药架
│ ├─ shop.blk.patch.blk # ③ 挂入美系陆军第 1 列 I 级科技树
│ └─ unittags.blk.patch.blk # ④ 克隆载具分类标签与试车场配置
└─ lang.vromfs.bin/
└─ lang/
└─ units.csv.patch.csv # ⑤ 注册 _shop / _0 / _1 / _2 中英文名称
@@ -375,82 +423,54 @@ mods/demo-standalone-m2a4/
#### ① 载具实体参数 `client/packs/aces.vromfs.bin/gamedata/units/tankmodels/us_m2a4_mod_demo.blk`
按第 01 章第 2 节任一方式取出原版 `aces.vromfs.bin` 中的 `gamedata/units/tankmodels/us_m2a4.blk`(文本或二进制均可),另存为 `us_m2a4_mod_demo.blk`。保持顶部的 `model:t="m2a4"` 不变(这样它会直接复用原版 M2A4 的 3D 模型和贴图),把里面的最大前进速度和加速改快即可(文本 `.blk` 在构建时会自动编译为二进制 `.blk`):
直接用 `include "us_m2a4.blk"` 继承原版 `aces.vromfs.bin` 中的同目录 `us_m2a4.blk`(无需手工解包复制几千行原版文件),只用 `@override:` 调高最大前进速度和加速(构建时会自动展开并编译为二进制 `.blk`):
```blk
model:t="m2a4"
// ...(保留原版 us_m2a4.blk 其余内容不变,仅调高以下机动参数体验效果)...
maxFwdSpeed:r=90.0
maxRevSpeed:r=25.0
maxAccel:r=12.0
include "us_m2a4.blk"
"@override:maxFwdSpeed":r = 90.0
"@override:maxRevSpeed":r = 25.0
"@override:maxAccel":r = 12.0
```
#### ② 经济与权重补丁 `client/packs/char.vromfs.bin/config/wpcost.blk.patch.jsonc`
#### ② 经济与权重补丁 `client/packs/char.vromfs.bin/config/wpcost.blk.patch.blk`
用 `cloneBlock` 一键复制 `us_m2a4`(自动继承全部武器、弹种、改装件与备用车配置),并把研发前提设为 `us_m2a4`、研发点设为 `1000`、银狮价格设为 `500`、三模式分房权重设为 `1`(即面板 **1.3**):
用 `@clone:` 一键复制 `us_m2a4`(自动继承全部武器、弹种、改装件与备用车配置),并把研发前提设为 `us_m2a4`、研发点设为 `1000`、银狮价格设为 `500`、三模式分房权重设为 `1`(即面板 **1.3**):
```jsonc
{
"ops": [
{
"op": "cloneBlock",
"from": ["us_m2a4"],
"toParent": [],
"newName": "us_m2a4_mod_demo",
"replaceExisting": true,
"ops": [
{ "op": "setParam", "path": [], "name": "reqAir", "value": "us_m2a4" },
{ "op": "setParam", "path": [], "name": "reqExp", "value": { "type": "int", "value": 1000 } },
{ "op": "setParam", "path": [], "name": "value", "value": { "type": "int", "value": 500 } },
{ "op": "setParam", "path": [], "name": "economicRank", "value": { "type": "int", "value": 1 } },
{ "op": "setParam", "path": [], "name": "economicRankArcade", "value": { "type": "int", "value": 1 } },
{ "op": "setParam", "path": [], "name": "economicRankHistorical", "value": { "type": "int", "value": 1 } },
{ "op": "setParam", "path": [], "name": "economicRankSimulation", "value": { "type": "int", "value": 1 } }
]
}
]
```blk
"@clone:us_m2a4->us_m2a4_mod_demo" {
"@override:reqAir":t = "us_m2a4"
"@override:reqExp":i = 1000
"@override:value":i = 500
"@override:economicRank":i = 1
"@override:economicRankArcade":i = 1
"@override:economicRankHistorical":i = 1
"@override:economicRankSimulation":i = 1
}
```
#### ③ 科技树位置补丁 `client/packs/char.vromfs.bin/config/shop.blk.patch.jsonc`
#### ③ 科技树位置补丁 `client/packs/char.vromfs.bin/config/shop.blk.patch.blk`
在 `country_usa -> army -> range[0]` 的 I 级段末尾(`us_m3a1_stuart` 之后、`us_m5a1_stuart` 断线之前)插入新车块,并显式声明 `reqAir: "us_m2a4"`,游戏就会在不打断原有斯图亚特研发线的前提下,从 `M2A4` 连出一条侧支研发箭头指向你的新车:
在 `country_usa -> army -> range[0]` 的 I 级段末尾(`us_m3a1_stuart` 之后、`us_m5a1_stuart` 断线之前)插入新车块,并显式声明 `reqAir:t = "us_m2a4"`,游戏就会在不打断原有斯图亚特研发线的前提下,从 `M2A4` 连出一条侧支研发箭头指向你的新车:
```jsonc
{
"ops": [
{
"op": "addBlock",
"path": ["country_usa", "army", "range[0]"],
"name": "us_m2a4_mod_demo",
"after": "us_m3a1_stuart",
"block": {
"params": [
{ "name": "rank", "value": { "type": "int", "value": 1 } },
{ "name": "reqAir", "value": "us_m2a4" }
]
```blk
"@override:country_usa" {
"@override:army" {
"@override:range[0]" {
"@after:us_m3a1_stuart:us_m2a4_mod_demo" {
rank:i = 1
reqAir:t = "us_m2a4"
}
}
]
}
}
```
#### ④ 载具标签与试驾场补丁 `client/packs/char.vromfs.bin/config/unittags.blk.patch.jsonc`
#### ④ 载具标签与试驾场补丁 `client/packs/char.vromfs.bin/config/unittags.blk.patch.blk`
同样用 `cloneBlock` 从 `us_m2a4` 克隆出 `type:t="tank"`、机库车位 `hangar_place:t="tank"`、陆战试车场 `testFlight` 与轻坦标签:
同样用 `@clone:` 从 `us_m2a4` 克隆出 `type:t="tank"`、机库车位 `hangar_place:t="tank"`、陆战试车场 `testFlight` 与轻坦标签:
```jsonc
{
"ops": [
{
"op": "cloneBlock",
"from": ["us_m2a4"],
"toParent": [],
"newName": "us_m2a4_mod_demo",
"replaceExisting": true
}
]
}
```blk
"@clone:us_m2a4->us_m2a4_mod_demo" {}
```
#### ⑤ 多语言名称补丁 `client/packs/lang.vromfs.bin/lang/units.csv.patch.csv`
+1 -1
View File
@@ -12,5 +12,5 @@ export { BlkLabel, decodeBlk, encodeBlk, type SharedNameContext } from './binary
export { parseSharedNameMap, type SharedNameMap } from './shared-name-map.ts';
export { appendParam, cloneBlock, ensureBlock, findBlock, findParam, setParam, visitParams } from './tree.ts';
export { formatBlkText } from './text/format-text.ts';
export { isBinaryBlk, parseBlkText } from './text/parse-text.ts';
export { isBinaryBlk, parseBlkStatements, parseBlkText, type BlkStatement } from './text/parse-text.ts';
export { singleVehiclePackId, stableGuid } from './stable-guid.ts';
+121 -30
View File
@@ -8,6 +8,11 @@
import { BlkFormatError } from '../errors.ts';
import { emptyBlock, type BlkBlock, type BlkValue } from '../model.ts';
export type BlkStatement =
| { readonly kind: 'include'; readonly path: string; readonly once: boolean; readonly line: number }
| { readonly kind: 'param'; readonly name: string; readonly value: BlkValue; readonly line: number }
| { readonly kind: 'block'; readonly name: string; readonly body: readonly BlkStatement[]; readonly line: number };
export function isBinaryBlk(bytes: Uint8Array): boolean {
if (bytes.length === 0) return false;
const first = bytes[0]!;
@@ -15,42 +20,69 @@ export function isBinaryBlk(bytes: Uint8Array): boolean {
return first <= 0x06 || first === 0x28;
}
export function parseBlkText(source: string): BlkBlock {
export function parseBlkStatements(source: string): BlkStatement[] {
const parser = new BlkTextParser(source);
return parser.readStatements(false);
}
export function parseBlkText(source: string): BlkBlock {
const root = emptyBlock('');
parser.readBlockBody(root, false);
appendStatementsToBlock(root, parseBlkStatements(source));
return root;
}
function appendStatementsToBlock(target: BlkBlock, statements: readonly BlkStatement[]): void {
for (const stmt of statements) {
switch (stmt.kind) {
case 'include':
target.params.push({ name: stmt.once ? 'includeOnce' : 'include', value: { type: 'string', value: stmt.path } });
break;
case 'param':
target.params.push({ name: stmt.name, value: stmt.value });
break;
case 'block': {
const child = emptyBlock(stmt.name);
appendStatementsToBlock(child, stmt.body);
target.blocks.push(child);
break;
}
}
}
}
class BlkTextParser {
readonly #text: string;
#pos = 0;
#linePos = 0;
#lineNumber = 1;
constructor(text: string) {
// Strip UTF-8 BOM if present.
this.#text = text.startsWith('\uFEFF') ? text.slice(1) : text;
}
readBlockBody(target: BlkBlock, expectClosingBrace: boolean): void {
readStatements(expectClosingBrace: boolean): BlkStatement[] {
const out: BlkStatement[] = [];
while (true) {
this.#skipIgnored();
if (this.#eof()) {
if (expectClosingBrace) this.#fail('unexpected end of BLK text inside block');
return;
return out;
}
if (this.#peek() === '}') {
if (!expectClosingBrace) this.#fail('unexpected closing brace "}" at root');
this.#pos += 1;
return;
return out;
}
const key = this.#readIdentifierOrString();
const line = this.#currentLine();
const keyQuoted = this.#peek() === '"' || this.#peek() === "'";
const rawKey = this.#readKeyToken(keyQuoted);
this.#skipIgnored();
const ch = this.#peek();
if (ch === '{') {
this.#pos += 1;
const child = emptyBlock(key);
this.readBlockBody(child, true);
target.blocks.push(child);
const body = this.readStatements(true);
out.push({ kind: 'block', name: rawKey, body, line });
continue;
}
if (ch === ':') {
@@ -60,30 +92,45 @@ class BlkTextParser {
if (this.#peek() !== '=') this.#fail(`expected "=" after type suffix ":${suffix}"`);
this.#pos += 1;
const value = this.#readValue(suffix);
target.params.push({ name: key, value });
out.push({ kind: 'param', name: rawKey, value, line });
continue;
}
// Untyped `include "..."` directive or unknown syntax.
if (key === 'include' && (ch === '"' || ch === "'")) {
// Unquoted `@directive:name:type = value` where the type suffix was attached to the @ token.
if (!keyQuoted && ch === '=' && rawKey.startsWith('@')) {
const lastColon = rawKey.lastIndexOf(':');
if (lastColon <= 0 || lastColon === rawKey.length - 1) {
this.#fail(`expected type suffix before "=" in "${rawKey}"`);
}
const key = rawKey.slice(0, lastColon);
const suffix = rawKey.slice(lastColon + 1);
this.#pos += 1;
const value = this.#readValue(suffix);
out.push({ kind: 'param', name: key, value, line });
continue;
}
// Untyped `include "..."` / `includeOnce "..."` directive.
if (!keyQuoted && (rawKey === 'include' || rawKey === 'includeOnce') && (ch === '"' || ch === "'")) {
const included = this.#readQuotedString();
target.params.push({ name: 'include', value: { type: 'string', value: included } });
out.push({ kind: 'include', path: included, once: rawKey === 'includeOnce', line });
continue;
}
this.#fail(`expected "{" or ":" after "${key}"`);
this.#fail(`expected "{" or ":" after "${rawKey}"`);
}
}
#readIdentifierOrString(): string {
const ch = this.#peek();
if (ch === '"' || ch === "'") return this.#readQuotedString();
#readKeyToken(quoted: boolean): string {
if (quoted) return this.#readQuotedString();
const start = this.#pos;
// Unquoted `@` directive keys (e.g. `@override:ikPilot`, `@override:model:t`, `@after:a:b`)
// may contain `:` inside the directive token and stop at `{`, `}`, `=`, `;`, whitespace, or comments.
const allowColon = this.#peek() === '@';
while (!this.#eof()) {
const c = this.#text[this.#pos]!;
if (c === ':' || c === '{' || c === '}' || c === '=' || c === ';' || /\s/.test(c)) break;
if ((!allowColon && c === ':') || c === '{' || c === '}' || c === '=' || c === ';' || /\s/.test(c)) break;
if (c === '/' && (this.#text[this.#pos + 1] === '/' || this.#text[this.#pos + 1] === '*')) break;
this.#pos += 1;
}
if (this.#pos === start) this.#fail(`unexpected character "${ch ?? ''}"`);
if (this.#pos === start) this.#fail(`unexpected character "${this.#peek() ?? ''}"`);
return this.#text.slice(start, this.#pos);
}
@@ -131,12 +178,23 @@ class BlkTextParser {
#readQuotedString(): string {
const quote = this.#text[this.#pos]!;
this.#pos += 1;
const isTriple =
this.#text[this.#pos + 1] === quote && this.#text[this.#pos + 2] === quote;
this.#pos += isTriple ? 3 : 1;
let out = '';
while (!this.#eof()) {
if (
isTriple &&
this.#text[this.#pos] === quote &&
this.#text[this.#pos + 1] === quote &&
this.#text[this.#pos + 2] === quote
) {
this.#pos += 3;
return out;
}
const c = this.#text[this.#pos]!;
this.#pos += 1;
if (c === quote) return out;
if (!isTriple && c === quote) return out;
if (c === '~' && !this.#eof()) {
const next = this.#text[this.#pos]!;
this.#pos += 1;
@@ -153,7 +211,7 @@ class BlkTextParser {
}
out += c;
}
this.#fail('unterminated string literal');
this.#fail(isTriple ? 'unterminated triple-quoted string literal' : 'unterminated string literal');
}
#readToken(): string {
@@ -172,7 +230,10 @@ class BlkTextParser {
#readInt(): number {
const raw = this.#readToken();
const parsed = raw.startsWith('0x') || raw.startsWith('0X') ? Number.parseInt(raw, 16) : Number(raw);
if (!Number.isFinite(parsed) || !Number.isInteger(parsed)) this.#fail(`invalid integer "${raw}"`);
if (!Number.isFinite(parsed) || !Number.isInteger(parsed)) {
const hint = isQuotedToken(raw) ? ' (do not quote numeric :i values)' : '';
this.#fail(`invalid integer "${raw}"${hint}`);
}
return parsed | 0;
}
@@ -181,14 +242,18 @@ class BlkTextParser {
try {
return BigInt(raw);
} catch {
this.#fail(`invalid int64 "${raw}"`);
const hint = isQuotedToken(raw) ? ' (do not quote numeric :i64 values)' : '';
this.#fail(`invalid int64 "${raw}"${hint}`);
}
}
#readReal(): number {
const raw = this.#readToken();
const parsed = Number(raw);
if (!Number.isFinite(parsed)) this.#fail(`invalid real "${raw}"`);
if (!Number.isFinite(parsed)) {
const hint = isQuotedToken(raw) ? ' (do not quote numeric :r values)' : '';
this.#fail(`invalid real "${raw}"${hint}`);
}
return parsed;
}
@@ -196,7 +261,8 @@ class BlkTextParser {
const raw = this.#readToken().toLowerCase();
if (raw === 'yes' || raw === 'true' || raw === '1') return true;
if (raw === 'no' || raw === 'false' || raw === '0') return false;
this.#fail(`invalid bool "${raw}"`);
const hint = isQuotedToken(raw) ? ' (do not quote boolean :b values; use yes/no or true/false)' : '';
this.#fail(`invalid bool "${raw}"${hint}`);
}
#readReals(count: number): number[] {
@@ -218,8 +284,22 @@ class BlkTextParser {
}
#readColor(): number {
const channels = this.#readInts(4);
const [r, g, b, a] = channels as [number, number, number, number];
const firstRaw = this.#readToken();
const firstParsed =
firstRaw.startsWith('0x') || firstRaw.startsWith('0X')
? Number.parseInt(firstRaw, 16)
: Number(firstRaw);
if (!Number.isFinite(firstParsed) || !Number.isInteger(firstParsed)) {
this.#fail(`invalid color component "${firstRaw}"`);
}
this.#skipHorizontalAndComments();
if (this.#peek() !== ',') {
// Single packed 32-bit ARGB color (e.g. 0xffff8000).
return firstParsed >>> 0;
}
this.#pos += 1;
const rest = this.#readInts(3);
const [r, g, b, a] = [firstParsed | 0, rest[0]!, rest[1]!, rest[2]!];
return (((a & 0xff) << 24) | ((r & 0xff) << 16) | ((g & 0xff) << 8) | (b & 0xff)) >>> 0;
}
@@ -309,9 +389,20 @@ class BlkTextParser {
return this.#pos >= this.#text.length;
}
#currentLine(): number {
while (this.#linePos < this.#pos) {
if (this.#text[this.#linePos] === '\n') this.#lineNumber += 1;
this.#linePos += 1;
}
return this.#lineNumber;
}
#fail(message: string): never {
const prefix = this.#text.slice(0, this.#pos);
const line = prefix.split('\n').length;
const line = this.#currentLine();
throw new BlkFormatError(`BLK text parse error on line ${line}: ${message}`);
}
}
function isQuotedToken(raw: string): boolean {
return (raw.startsWith('"') && raw.endsWith('"')) || (raw.startsWith("'") && raw.endsWith("'"));
}
+396
View File
@@ -0,0 +1,396 @@
import assert from 'node:assert/strict';
import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { describe, it } from 'node:test';
import { findBlock, findParam, parseBlkStatements, parseBlkText } from '@wto/blk';
import {
BlkPatchError,
applyBlkTextPatch,
compileBlkText,
discoverMods,
resolvePackRelativePath,
type BlkIncludeResolver,
} from './index.ts';
describe('parseBlkStatements', () => {
it('preserves strict source order across includes, params, and blocks with line numbers', () => {
const stmts = parseBlkStatements(`
include "germ_pzkpfw_maus.blk"
"@override:model":t="pzkpfw_VIII_walross"
"@delete:commonWeapons" {}
commonWeapons {
Weapon {
trigger:t="gunner0"
}
}
includeOnce "../common/extra.blk"
`);
assert.deepEqual(
stmts.map((s) => [s.kind, s.kind === 'include' ? `${s.once ? 'once:' : ''}${s.path}` : s.name, s.line]),
[
['include', 'germ_pzkpfw_maus.blk', 2],
['param', '@override:model', 3],
['block', '@delete:commonWeapons', 4],
['block', 'commonWeapons', 5],
['include', 'once:../common/extra.blk', 10],
],
);
});
it('gives a helpful hint when numeric values are accidentally quoted', () => {
assert.throws(
() => parseBlkStatements('"@override:economicRankArcade":i="18"'),
/do not quote numeric :i values/,
);
});
it('parses unquoted @ directives, triple-quoted strings, and packed hex colors', () => {
const root = parseBlkText(`
title:t = """line 1
"quoted" line 2"""
single:t = '''it's multiline'''
tintHex:c = 0xffff8000
tintRgba:c = 255, 128, 0, 255
`);
assert.deepEqual(findParam(root, 'title')?.value, { type: 'string', value: 'line 1\n"quoted" line 2' });
assert.deepEqual(findParam(root, 'single')?.value, { type: 'string', value: "it's multiline" });
assert.deepEqual(findParam(root, 'tintHex')?.value, { type: 'color', value: 0xffff8000 });
assert.deepEqual(findParam(root, 'tintRgba')?.value, { type: 'color', value: 0xffff8000 });
const stmts = parseBlkStatements(`
@override:ikPilot {
@override:model:t = "pilot_japan_late_char"
@override:count:i = 2
}
@delete:oldBlock {}
@after:a:b { rank:i = 1 }
`);
assert.equal(stmts[0]!.kind, 'block');
assert.equal(stmts[0]!.kind === 'block' && stmts[0]!.name, '@override:ikPilot');
assert.equal(stmts[0]!.kind === 'block' && stmts[0]!.body[0]!.kind === 'param' && stmts[0]!.body[0]!.name, '@override:model');
assert.equal(stmts[1]!.kind === 'block' && stmts[1]!.name, '@delete:oldBlock');
assert.equal(stmts[2]!.kind === 'block' && stmts[2]!.name, '@after:a:b');
});
});
describe('Dagor full directive coverage (@override-last, @delete-last, @clone, @inherit, CDK paths)', () => {
it('supports unquoted directives, @override-last, @delete-last, native @clone, @inherit, and #/develop/gameBase/ includes', () => {
const baseFiles: Record<string, string> = {
'gameData/Weapons/gunBrowning50_turret_late.blk': `
caliber:r = 12.7
fireRate:i = 600
tag:t = "first"
tag:t = "middle"
tag:t = "last"
ikPilot {
model:t = "pilot_us"
}
Weapon {
trigger:t = "gunner0"
ammo:i = 100
}
Weapon {
trigger:t = "gunner1"
ammo:i = 200
}
`,
};
const resolveInclude: BlkIncludeResolver = (includePath, fromPath) => {
const target = resolvePackRelativePath(fromPath, includePath);
const text = baseFiles[target];
return text !== undefined ? { resolvedPath: target, content: { kind: 'text', text } } : undefined;
};
const compiled = compileBlkText(
`
include "#/develop/gameBase/gameData/Weapons/gunBrowning50_turret_late.blk"
@override:ikPilot {
@override:model:t = "pilot_japan_late_char"
}
@override-last:tag:t = "last_edited"
@delete-last:tag:t = ""
@override-last:Weapon {
@override:ammo:i = 250
}
@clone:Weapon {
@override:trigger:t = "gunner2"
}
@delete-last:Weapon {}
@clone:Weapon {
@override:trigger:t = "gunner_cloned_first"
}
heavy_weapon {
@inherit:Weapon {}
@override:ammo:i = 500
}
`,
{
sourcePath: 'gamedata/units/tankmodels/custom_tank.blk',
resolveInclude,
},
);
assert.deepEqual(findParam(findBlock(compiled, 'ikPilot')!, 'model')?.value, {
type: 'string',
value: 'pilot_japan_late_char',
});
// `tag` had ["first", "middle", "last"] -> override-last -> ["first", "middle", "last_edited"] -> delete-last -> ["first", "middle"]
assert.deepEqual(
compiled.params.filter((p) => p.name === 'tag').map((p) => p.value),
[
{ type: 'string', value: 'first' },
{ type: 'string', value: 'middle' },
],
);
// `Weapon` blocks: [gunner0 (100), gunner1 (250), gunner_cloned_first (100)] (since gunner2 was deleted by @delete-last)
const weapons = compiled.blocks.filter((b) => b.name === 'Weapon');
assert.equal(weapons.length, 3);
assert.deepEqual(findParam(weapons[0]!, 'ammo')?.value, { type: 'int', value: 100 });
assert.deepEqual(findParam(weapons[1]!, 'ammo')?.value, { type: 'int', value: 250 });
assert.deepEqual(findParam(weapons[2]!, 'trigger')?.value, { type: 'string', value: 'gunner_cloned_first' });
assert.deepEqual(findParam(weapons[2]!, 'ammo')?.value, { type: 'int', value: 100 });
// `heavy_weapon` inherited from sibling `Weapon` (gunner0, ammo=100) and overrode ammo=500
const heavy = findBlock(compiled, 'heavy_weapon');
assert.ok(heavy);
assert.deepEqual(findParam(heavy, 'trigger')?.value, { type: 'string', value: 'gunner0' });
assert.deepEqual(findParam(heavy, 'ammo')?.value, { type: 'int', value: 500 });
});
});
describe('applyBlkTextPatch & compileBlkText', () => {
it('supports @override, @delete, @delete-all, @@ escape, and plain append on params', () => {
const root = parseBlkText(`
pzkpfw_VIII_walross {
economicRankArcade:i = 15
economicRankArcade:i = 16
slaveUnit:t = "a"
slaveUnit:t = "b"
obsolete:b = yes
obsolete:b = no
}
`);
applyBlkTextPatch(
root,
`
"@override:pzkpfw_VIII_walross" {
"@override:economicRankArcade":i = 18
slaveUnit:t = "c"
"@delete:slaveUnit":t = ""
"@delete-all:obsolete":b = no
newReal:r = 2.5
"@@literal:key":t = "kept"
}
`,
);
const tank = findBlock(root, 'pzkpfw_VIII_walross');
assert.ok(tank);
assert.deepEqual(
tank.params.filter((p) => p.name === 'economicRankArcade').map((p) => p.value),
[{ type: 'int', value: 18 }],
);
assert.deepEqual(
tank.params.filter((p) => p.name === 'slaveUnit').map((p) => p.value),
[
{ type: 'string', value: 'b' },
{ type: 'string', value: 'c' },
],
);
assert.equal(tank.params.filter((p) => p.name === 'obsolete').length, 0);
assert.deepEqual(findParam(tank, 'newReal')?.value, { type: 'real', value: 2.5 });
assert.deepEqual(findParam(tank, '@literal:key')?.value, { type: 'string', value: 'kept' });
});
it('supports @replace, @delete, @delete-all, @clone-last, @clone, indexed paths, and @after/@before', () => {
const root = parseBlkText(`
country_usa {
army {
range {
us_m2a4 { rank:i = 1 }
us_m3_stuart { rank:i = 1 }
}
range {
us_m2_medium { rank:i = 1 }
}
}
}
us_m2a4 {
value:i = 0
reqExp:i = 0
economicRankArcade:i = 0
weapons { gun:t = "37mm" }
}
`);
applyBlkTextPatch(
root,
`
"@clone:us_m2a4->us_m2a4_mod" {
"@override:value":i = 500
"@override:reqExp":i = 1000
"@override:economicRankArcade":i = 1
"@replace:weapons" {
gun:t = "75mm"
}
}
"@override:country_usa" {
"@override:army" {
"@override:range[0]" {
"@after:us_m2a4:us_m2a4_mod" {
rank:i = 1
reqAir:t = "us_m2a4"
}
"@before:us_m2a4:us_m2a4_before" {
rank:i = 1
}
}
"@override:range[1]" {
"@clone-last:us_m2_medium" {
"@override:rank":i = 2
}
}
}
}
`,
);
const cloned = findBlock(root, 'us_m2a4_mod');
assert.ok(cloned);
assert.deepEqual(findParam(cloned, 'value')?.value, { type: 'int', value: 500 });
assert.deepEqual(findParam(cloned, 'economicRankArcade')?.value, { type: 'int', value: 1 });
assert.deepEqual(findParam(findBlock(cloned, 'weapons')!, 'gun')?.value, { type: 'string', value: '75mm' });
// Original must remain untouched.
assert.deepEqual(findParam(findBlock(root, 'us_m2a4')!, 'value')?.value, { type: 'int', value: 0 });
const army = findBlock(findBlock(root, 'country_usa')!, 'army')!;
const range0 = army.blocks[0]!;
assert.deepEqual(
range0.blocks.map((b) => b.name),
['us_m2a4_before', 'us_m2a4', 'us_m2a4_mod', 'us_m3_stuart'],
);
const range1 = army.blocks[1]!;
assert.equal(range1.blocks.length, 2);
assert.deepEqual(findParam(range1.blocks[0]!, 'rank')?.value, { type: 'int', value: 1 });
assert.deepEqual(findParam(range1.blocks[1]!, 'rank')?.value, { type: 'int', value: 2 });
});
it('compiles standalone BLK with include, includeOnce, @override, @delete, and replacement block in order', () => {
const files: Record<string, string> = {
'gamedata/units/tankmodels/germ_pzkpfw_maus.blk': `
model:t = "pzkpfw_VIII_maus"
maxFwdSpeed:r = 20.0
commonWeapons {
Weapon { blk:t = "128mm" }
}
`,
'gamedata/units/common/smoke.blk': `
hasSmoke:b = yes
`,
};
const resolveInclude: BlkIncludeResolver = (includePath, fromPath) => {
const target = resolvePackRelativePath(fromPath, includePath);
const text = files[target];
return text !== undefined ? { resolvedPath: target, content: { kind: 'text', text } } : undefined;
};
const compiled = compileBlkText(
`
include "germ_pzkpfw_maus.blk"
includeOnce "../common/smoke.blk"
includeOnce "../common/smoke.blk"
"@override:model":t = "pzkpfw_VIII_walross"
"@delete:commonWeapons" {}
commonWeapons {
Weapon { blk:t = "150mm" }
}
`,
{
sourcePath: 'gamedata/units/tankmodels/germ_pzkpfw_walross.blk',
resolveInclude,
},
);
assert.deepEqual(findParam(compiled, 'model')?.value, { type: 'string', value: 'pzkpfw_VIII_walross' });
assert.deepEqual(findParam(compiled, 'maxFwdSpeed')?.value, { type: 'real', value: 20 });
assert.equal(compiled.params.filter((p) => p.name === 'hasSmoke').length, 1);
const cw = compiled.blocks.filter((b) => b.name === 'commonWeapons');
assert.equal(cw.length, 1);
assert.deepEqual(findParam(cw[0]!.blocks[0]!, 'blk')?.value, { type: 'string', value: '150mm' });
});
it('rejects unknown @ directives, non-empty @delete blocks, path traversal, and circular includes', () => {
const root = parseBlkText('foo:i = 1');
assert.throws(
() => applyBlkTextPatch(root, '"@overide:foo":i = 2'),
(err) => err instanceof BlkPatchError && /unknown or invalid parameter directive/.test(err.message),
);
assert.throws(
() => applyBlkTextPatch(root, '"@delete:bar" { x:i = 1 }'),
(err) => err instanceof BlkPatchError && /block body must be empty/.test(err.message),
);
assert.throws(
() => resolvePackRelativePath('config/wpcost.blk', '../../escape.blk'),
(err) => err instanceof BlkPatchError && /escapes archive root/.test(err.message),
);
const cyclic: Record<string, string> = {
'a.blk': 'include "b.blk"',
'b.blk': 'include "a.blk"',
};
assert.throws(
() =>
compileBlkText('include "a.blk"', {
sourcePath: 'root.blk',
resolveInclude: (p, from) => {
const target = resolvePackRelativePath(from, p);
return cyclic[target] ? { resolvedPath: target, content: { kind: 'text', text: cyclic[target]! } } : undefined;
},
}),
(err) => err instanceof BlkPatchError && /circular include detected/.test(err.message),
);
});
it('discovers .patch.blk and rejects dual formats for the same target within one mod', () => {
const tempRoot = mkdtempSync(join(tmpdir(), 'wto-discovery-blk-'));
try {
const modValid = join(tempRoot, 'valid');
mkdirSync(join(modValid, 'client', 'packs', 'char.vromfs.bin', 'config'), { recursive: true });
writeFileSync(
join(modValid, 'mod.jsonc'),
JSON.stringify({ format: 1, id: 'test.valid', name: 'Valid', version: '0.1.0', author: 'T', api_version: '0.1-experimental' }),
);
writeFileSync(join(modValid, 'client', 'packs', 'char.vromfs.bin', 'config', 'wpcost.blk.patch.blk'), '');
writeFileSync(join(modValid, 'client', 'config-blk.patch.blk'), '');
const modDualPack = join(tempRoot, 'dual-pack');
mkdirSync(join(modDualPack, 'client', 'packs', 'char.vromfs.bin', 'config'), { recursive: true });
writeFileSync(
join(modDualPack, 'mod.jsonc'),
JSON.stringify({ format: 1, id: 'test.dual-pack', name: 'Dual', version: '0.1.0', author: 'T', api_version: '0.1-experimental' }),
);
writeFileSync(join(modDualPack, 'client', 'packs', 'char.vromfs.bin', 'config', 'wpcost.blk.patch.blk'), '');
writeFileSync(join(modDualPack, 'client', 'packs', 'char.vromfs.bin', 'config', 'wpcost.blk.patch.jsonc'), '{"ops":[]}');
const modDualConfig = join(tempRoot, 'dual-config');
mkdirSync(join(modDualConfig, 'client'), { recursive: true });
writeFileSync(
join(modDualConfig, 'mod.jsonc'),
JSON.stringify({ format: 1, id: 'test.dual-config', name: 'DualCfg', version: '0.1.0', author: 'T', api_version: '0.1-experimental' }),
);
writeFileSync(join(modDualConfig, 'client', 'config-blk.patch.blk'), '');
writeFileSync(join(modDualConfig, 'client', 'config-blk.patch.jsonc'), '{"ops":[]}');
const res = discoverMods(tempRoot);
assert.equal(res.mods.length, 1);
assert.equal(res.mods[0]!.content.configBlkPatch, 'client/config-blk.patch.blk');
assert.equal(res.mods[0]!.content.packOperations[0]!.action, 'blk-patch');
assert.equal(res.mods[0]!.content.packOperations[0]!.targetPath, 'config/wpcost.blk');
assert.equal(res.errors.length, 2);
assert.ok(res.errors.every((e) => /choose one format/.test(e.reason)));
} finally {
rmSync(tempRoot, { recursive: true, force: true });
}
});
});
+591
View File
@@ -0,0 +1,591 @@
/**
* Dagor-style declarative text BLK patches (`*.blk.patch.blk`, `client/config-blk.patch.blk`)
* and directive-aware BLK compilation (`include` / `includeOnce` + `@override:` / `@delete:` / etc.).
*
* Statements are executed strictly in source order so `include`, deletes, overrides, and appended
* blocks compose deterministically just like DagorEngine's DataBlock text loader.
*/
import {
BlkFormatError,
appendParam,
cloneBlock,
emptyBlock,
parseBlkStatements,
setParam,
type BlkBlock,
type BlkStatement,
} from '@wto/blk';
import { BlkPatchError, type BlkPathStep } from './blk-patch.ts';
export interface BlkIncludeTarget {
/** Normalized identifier for cycle detection and `includeOnce` deduplication. */
readonly resolvedPath: string;
/** Either an already-decoded binary BLK tree or raw BLK text to parse recursively. */
readonly content:
| { readonly kind: 'block'; readonly block: BlkBlock }
| { readonly kind: 'text'; readonly text: string };
}
export type BlkIncludeResolver = (
includePath: string,
fromPath: string | undefined,
) => BlkIncludeTarget | undefined;
export interface BlkTextPatchOptions {
/** Human-readable origin used in error messages. */
readonly where?: string;
/** Logical path of the current BLK inside the pack (for relative `include` resolution). */
readonly sourcePath?: string;
/** Optional resolver for `include` / `includeOnce` statements. */
readonly resolveInclude?: BlkIncludeResolver;
/** Maximum nested include depth (default: 32). */
readonly maxIncludeDepth?: number;
}
const DEFAULT_MAX_INCLUDE_DEPTH = 32;
const DIRECTIVE_PATTERN = /^@([a-zA-Z0-9_-]+):(.*)$/;
const SUPPORTED_PARAM_DIRECTIVES = '@override:, @override-last:, @delete:, @delete-last:, @delete-all:';
const SUPPORTED_BLOCK_DIRECTIVES =
'@override:, @override-last:, @replace:, @delete:, @delete-last:, @delete-all:, @clone:, @clone-last:, @inherit:, @after:, @before:';
interface ExecutionContext {
readonly docRoot: BlkBlock;
readonly parentBlock: BlkBlock | undefined;
readonly where: string;
readonly sourcePath: string | undefined;
readonly resolveInclude: BlkIncludeResolver | undefined;
readonly maxIncludeDepth: number;
readonly includeStack: string[];
readonly includedOnce: Set<string>;
}
/**
* Apply a Dagor-style text BLK patch onto an existing `BlkBlock` tree in place.
*/
export function applyBlkTextPatch(
root: BlkBlock,
source: string,
options: BlkTextPatchOptions = {},
): void {
const where = options.where ?? 'blk text patch';
const statements = parseStatementsOrThrow(source, where);
const ctx: ExecutionContext = {
docRoot: root,
parentBlock: undefined,
where,
sourcePath: options.sourcePath,
resolveInclude: options.resolveInclude,
maxIncludeDepth: options.maxIncludeDepth ?? DEFAULT_MAX_INCLUDE_DEPTH,
includeStack: options.sourcePath ? [normalizeIncludeKey(options.sourcePath)] : [],
includedOnce: new Set(options.sourcePath ? [normalizeIncludeKey(options.sourcePath)] : []),
};
executeStatements(root, statements, ctx);
}
/**
* Compile a standalone text BLK (which may use `include` and `@override:` / `@delete:` directives)
* into a self-contained `BlkBlock` ready for binary encoding.
*/
export function compileBlkText(
source: string,
options: BlkTextPatchOptions = {},
): BlkBlock {
const root = emptyBlock('');
applyBlkTextPatch(root, source, options);
return root;
}
/**
* Resolve a pack-internal `include` path against the current BLK's pack-relative path.
* Supports relative paths (`"germ_pzkpfw_maus.blk"`, `"../common/guns.blk"`) as well as
* pack-root paths (`"/gamedata/..."`, `"#/gamedata/..."`).
*/
export function resolvePackRelativePath(
fromPath: string | undefined,
includePath: string,
where = 'include',
): string {
const normalized = includePath.trim().replaceAll('\\', '/');
if (!normalized) {
throw new BlkPatchError(`${where}: include path must not be empty`);
}
let rawPath: string;
if (normalized.toLowerCase().startsWith('#/develop/gamebase/')) {
rawPath = normalized.slice('#/develop/gamebase/'.length);
} else if (normalized.startsWith('#/')) {
rawPath = normalized.slice(2);
} else if (normalized.startsWith('/')) {
rawPath = normalized.slice(1);
} else if (fromPath) {
const base = fromPath.replaceAll('\\', '/');
const lastSlash = base.lastIndexOf('/');
const baseDir = lastSlash >= 0 ? base.slice(0, lastSlash) : '';
rawPath = baseDir ? `${baseDir}/${normalized}` : normalized;
} else {
rawPath = normalized;
}
const resolvedSegments: string[] = [];
for (const segment of rawPath.split('/')) {
if (!segment || segment === '.') continue;
if (segment === '..') {
if (resolvedSegments.length === 0) {
throw new BlkPatchError(`${where}: include path "${includePath}" escapes archive root`);
}
resolvedSegments.pop();
} else {
resolvedSegments.push(segment);
}
}
if (resolvedSegments.length === 0) {
throw new BlkPatchError(`${where}: include path "${includePath}" resolves to empty path`);
}
return resolvedSegments.join('/');
}
function parseStatementsOrThrow(source: string, where: string): BlkStatement[] {
try {
return parseBlkStatements(source);
} catch (error) {
const detail = error instanceof BlkFormatError || error instanceof Error ? error.message : String(error);
throw new BlkPatchError(`${where}: ${detail}`);
}
}
function executeStatements(
target: BlkBlock,
statements: readonly BlkStatement[],
ctx: ExecutionContext,
): void {
for (const stmt of statements) {
switch (stmt.kind) {
case 'include':
executeInclude(target, stmt, ctx);
break;
case 'param':
executeParam(target, stmt, ctx);
break;
case 'block':
executeBlock(target, stmt, ctx);
break;
}
}
}
function executeInclude(
target: BlkBlock,
stmt: Extract<BlkStatement, { kind: 'include' }>,
ctx: ExecutionContext,
): void {
const loc = `${ctx.where}:${stmt.line}`;
if (!ctx.resolveInclude) {
throw new BlkPatchError(`${loc}: include "${stmt.path}" is not supported in this context`);
}
const resolved = ctx.resolveInclude(stmt.path, ctx.sourcePath);
if (!resolved) {
throw new BlkPatchError(`${loc}: included BLK "${stmt.path}" not found`);
}
const key = normalizeIncludeKey(resolved.resolvedPath);
if (stmt.once && ctx.includedOnce.has(key)) return;
if (ctx.includeStack.includes(key)) {
throw new BlkPatchError(
`${loc}: circular include detected: ${[...ctx.includeStack, key].join(' -> ')}`,
);
}
if (ctx.includeStack.length >= ctx.maxIncludeDepth) {
throw new BlkPatchError(
`${loc}: include depth limit (${ctx.maxIncludeDepth}) exceeded at "${resolved.resolvedPath}"`,
);
}
ctx.includedOnce.add(key);
ctx.includeStack.push(key);
try {
if (resolved.content.kind === 'block') {
const cloned = cloneBlock(resolved.content.block);
target.params.push(...cloned.params);
target.blocks.push(...cloned.blocks);
} else {
const childWhere = `${ctx.where} -> include "${resolved.resolvedPath}"`;
const childStatements = parseStatementsOrThrow(resolved.content.text, childWhere);
executeStatements(target, childStatements, {
...ctx,
where: childWhere,
sourcePath: resolved.resolvedPath,
});
}
} finally {
ctx.includeStack.pop();
}
}
function executeParam(
target: BlkBlock,
stmt: Extract<BlkStatement, { kind: 'param' }>,
ctx: ExecutionContext,
): void {
const loc = `${ctx.where}:${stmt.line}`;
const parsed = parseDirectiveName(stmt.name);
if (!parsed) {
appendParam(target, unescapeAtPrefix(stmt.name), stmt.value);
return;
}
const { directive, rest } = parsed;
if (!rest) {
throw new BlkPatchError(`${loc}: missing parameter name after "@${directive}:"`);
}
switch (directive) {
case 'override':
setParam(target, rest, stmt.value);
return;
case 'override-last': {
let lastIdx = -1;
for (let i = target.params.length - 1; i >= 0; i -= 1) {
if (target.params[i]!.name === rest) {
lastIdx = i;
break;
}
}
if (lastIdx >= 0) {
target.params[lastIdx] = { name: rest, value: stmt.value };
} else {
appendParam(target, rest, stmt.value);
}
return;
}
case 'delete': {
const idx = target.params.findIndex((param) => param.name === rest);
if (idx >= 0) target.params.splice(idx, 1);
return;
}
case 'delete-last': {
for (let i = target.params.length - 1; i >= 0; i -= 1) {
if (target.params[i]!.name === rest) {
target.params.splice(i, 1);
break;
}
}
return;
}
case 'delete-all':
target.params = target.params.filter((param) => param.name !== rest);
return;
default:
throw new BlkPatchError(
`${loc}: unknown or invalid parameter directive "@${directive}:" (supported: ${SUPPORTED_PARAM_DIRECTIVES})`,
);
}
}
function executeBlock(
target: BlkBlock,
stmt: Extract<BlkStatement, { kind: 'block' }>,
ctx: ExecutionContext,
): void {
const loc = `${ctx.where}:${stmt.line}`;
const childCtx: ExecutionContext = { ...ctx, parentBlock: target };
const parsed = parseDirectiveName(stmt.name);
if (!parsed) {
const child = emptyBlock(unescapeAtPrefix(stmt.name));
executeStatements(child, stmt.body, childCtx);
target.blocks.push(child);
return;
}
const { directive, rest } = parsed;
if (!rest) {
throw new BlkPatchError(`${loc}: missing target name after "@${directive}:"`);
}
switch (directive) {
case 'override': {
const step = parseStep(rest, loc);
const idx = findChildBlockIndex(target, step);
if (idx >= 0) {
executeStatements(target.blocks[idx]!, stmt.body, childCtx);
return;
}
if (step.index !== undefined) {
throw new BlkPatchError(`${loc}: block "${rest}" not found`);
}
const created = emptyBlock(step.name);
target.blocks.push(created);
executeStatements(created, stmt.body, childCtx);
return;
}
case 'override-last': {
if (hasIndexSuffix(rest)) {
throw new BlkPatchError(`${loc}: "@override-last:" does not accept an index suffix ("${rest}")`);
}
const lastIdx = findLastChildBlockIndex(target, rest);
if (lastIdx >= 0) {
executeStatements(target.blocks[lastIdx]!, stmt.body, childCtx);
return;
}
const created = emptyBlock(rest);
target.blocks.push(created);
executeStatements(created, stmt.body, childCtx);
return;
}
case 'replace': {
const step = parseStep(rest, loc);
const idx = findChildBlockIndex(target, step);
if (idx < 0 && step.index !== undefined) {
throw new BlkPatchError(`${loc}: block "${rest}" not found`);
}
const replacement = emptyBlock(step.name);
executeStatements(replacement, stmt.body, childCtx);
if (idx >= 0) {
target.blocks[idx] = replacement;
} else {
target.blocks.push(replacement);
}
return;
}
case 'delete': {
if (stmt.body.length > 0) {
throw new BlkPatchError(`${loc}: "@delete:${rest}" block body must be empty (use "@replace:${rest}" to replace)`);
}
const step = parseStep(rest, loc);
const idx = findChildBlockIndex(target, step);
if (idx >= 0) target.blocks.splice(idx, 1);
return;
}
case 'delete-last': {
if (stmt.body.length > 0) {
throw new BlkPatchError(`${loc}: "@delete-last:${rest}" block body must be empty`);
}
if (hasIndexSuffix(rest)) {
throw new BlkPatchError(`${loc}: "@delete-last:" does not accept an index suffix ("${rest}")`);
}
const lastIdx = findLastChildBlockIndex(target, rest);
if (lastIdx >= 0) target.blocks.splice(lastIdx, 1);
return;
}
case 'delete-all': {
if (stmt.body.length > 0) {
throw new BlkPatchError(`${loc}: "@delete-all:${rest}" block body must be empty`);
}
if (hasIndexSuffix(rest)) {
throw new BlkPatchError(`${loc}: "@delete-all:" does not accept an index suffix ("${rest}")`);
}
target.blocks = target.blocks.filter((child) => child.name !== rest);
return;
}
case 'clone-last': {
if (hasIndexSuffix(rest)) {
throw new BlkPatchError(`${loc}: "@clone-last:" does not accept an index suffix ("${rest}")`);
}
const lastIdx = findLastChildBlockIndex(target, rest);
if (lastIdx < 0) {
throw new BlkPatchError(`${loc}: "@clone-last:${rest}" source block not found`);
}
const cloned = cloneBlock(target.blocks[lastIdx]!, rest);
executeStatements(cloned, stmt.body, childCtx);
target.blocks.push(cloned);
return;
}
case 'clone': {
if (rest.includes('->')) {
const cloned = buildClonedBlock(target, rest, stmt.body, loc, childCtx);
const existingIdx = target.blocks.findIndex((child) => child.name === cloned.name);
if (existingIdx >= 0) {
target.blocks[existingIdx] = cloned;
} else {
target.blocks.push(cloned);
}
return;
}
// Dagor-native `@clone:<sourcePath> { ... }`: deep-clone source keeping its name and append.
const source = resolveSourceBlock(target, rest, loc, ctx, '@clone:');
const cloned = cloneBlock(source, source.name);
executeStatements(cloned, stmt.body, childCtx);
target.blocks.push(cloned);
return;
}
case 'inherit': {
const source = resolveInheritSource(target, rest, loc, ctx);
const cloned = cloneBlock(source);
target.params.push(...cloned.params);
target.blocks.push(...cloned.blocks);
if (stmt.body.length > 0) {
executeStatements(target, stmt.body, ctx);
}
return;
}
case 'after':
case 'before': {
const colonIdx = rest.indexOf(':');
if (colonIdx <= 0 || colonIdx === rest.length - 1) {
throw new BlkPatchError(
`${loc}: "@${directive}:" must be formatted as "@${directive}:<anchor>:<newBlockName>"`,
);
}
const anchorRaw = rest.slice(0, colonIdx);
const specRaw = rest.slice(colonIdx + 1);
const anchorStep = parseStep(anchorRaw, loc);
let created: BlkBlock;
if (specRaw.startsWith('@clone:')) {
created = buildClonedBlock(target, specRaw.slice('@clone:'.length), stmt.body, loc, childCtx);
} else {
const nestedDirective = parseDirectiveName(specRaw);
if (nestedDirective) {
throw new BlkPatchError(
`${loc}: "@${directive}:" only supports a block name or "@clone:<source>-><newName>" after anchor`,
);
}
created = emptyBlock(unescapeAtPrefix(specRaw));
executeStatements(created, stmt.body, childCtx);
}
const anchorIdx = findChildBlockIndex(target, anchorStep);
if (anchorIdx < 0) {
target.blocks.push(created);
} else {
const insertAt = directive === 'after' ? anchorIdx + 1 : anchorIdx;
target.blocks.splice(insertAt, 0, created);
}
return;
}
default:
throw new BlkPatchError(
`${loc}: unknown or invalid block directive "@${directive}:" (supported: ${SUPPORTED_BLOCK_DIRECTIVES})`,
);
}
}
function buildClonedBlock(
target: BlkBlock,
spec: string,
body: readonly BlkStatement[],
loc: string,
childCtx: ExecutionContext,
): BlkBlock {
const arrowIdx = spec.indexOf('->');
if (arrowIdx <= 0 || arrowIdx + 2 >= spec.length) {
throw new BlkPatchError(
`${loc}: "@clone:" must be formatted as "@clone:<sourcePath>-><newBlockName>"`,
);
}
const sourceSpec = spec.slice(0, arrowIdx);
const newName = spec.slice(arrowIdx + 2);
if (newName.includes('/') || hasIndexSuffix(newName)) {
throw new BlkPatchError(`${loc}: "@clone:" target name "${newName}" must be a plain block name`);
}
const source = resolveSourceBlock(target, sourceSpec, loc, childCtx, '@clone:');
const cloned = cloneBlock(source, unescapeAtPrefix(newName));
executeStatements(cloned, body, childCtx);
return cloned;
}
function resolveSourceBlock(
base: BlkBlock,
sourceSpec: string,
loc: string,
ctx: ExecutionContext,
directiveLabel: string,
): BlkBlock {
const fromRoot = sourceSpec.startsWith('/');
const pathText = fromRoot ? sourceSpec.slice(1) : sourceSpec;
const segments = pathText.split('/').filter((segment) => segment.length > 0);
if (segments.length === 0) {
throw new BlkPatchError(`${loc}: "${directiveLabel}" source path must not be empty`);
}
const found = tryResolveBlockPath(fromRoot ? ctx.docRoot : base, segments, loc);
if (!found) {
throw new BlkPatchError(`${loc}: "${directiveLabel}" source block "${sourceSpec}" not found`);
}
return found;
}
function resolveInheritSource(
target: BlkBlock,
sourceSpec: string,
loc: string,
ctx: ExecutionContext,
): BlkBlock {
const fromRoot = sourceSpec.startsWith('/');
const pathText = fromRoot ? sourceSpec.slice(1) : sourceSpec;
const segments = pathText.split('/').filter((segment) => segment.length > 0);
if (segments.length === 0) {
throw new BlkPatchError(`${loc}: "@inherit:" source path must not be empty`);
}
if (fromRoot) {
const found = tryResolveBlockPath(ctx.docRoot, segments, loc);
if (found) return found;
} else {
// Prefer sibling in parent block (typical template inheritance), then document root, then child.
if (ctx.parentBlock) {
const fromParent = tryResolveBlockPath(ctx.parentBlock, segments, loc);
if (fromParent && fromParent !== target) return fromParent;
}
const fromDocRoot = tryResolveBlockPath(ctx.docRoot, segments, loc);
if (fromDocRoot && fromDocRoot !== target) return fromDocRoot;
const fromSelf = tryResolveBlockPath(target, segments, loc);
if (fromSelf) return fromSelf;
}
throw new BlkPatchError(`${loc}: "@inherit:" source block "${sourceSpec}" not found`);
}
function tryResolveBlockPath(start: BlkBlock, segments: readonly string[], loc: string): BlkBlock | undefined {
let current = start;
for (const segment of segments) {
const step = parseStep(segment, loc);
const idx = findChildBlockIndex(current, step);
if (idx < 0) return undefined;
current = current.blocks[idx]!;
}
return current;
}
function findLastChildBlockIndex(parent: BlkBlock, name: string): number {
for (let i = parent.blocks.length - 1; i >= 0; i -= 1) {
if (parent.blocks[i]!.name === name) return i;
}
return -1;
}
function parseDirectiveName(rawName: string): { readonly directive: string; readonly rest: string } | undefined {
if (rawName.startsWith('@@')) return undefined;
const match = DIRECTIVE_PATTERN.exec(rawName);
if (!match) return undefined;
return { directive: match[1]!, rest: match[2]! };
}
function unescapeAtPrefix(rawName: string): string {
return rawName.startsWith('@@') ? rawName.slice(1) : rawName;
}
function hasIndexSuffix(raw: string): boolean {
return /^.+\[\d+\]$/.test(raw);
}
function parseStep(raw: string, loc: string): BlkPathStep {
const match = /^(.+)\[(\d+)\]$/.exec(raw);
if (!match) {
if (!raw) throw new BlkPatchError(`${loc}: empty block name`);
return { name: unescapeAtPrefix(raw) };
}
return { name: unescapeAtPrefix(match[1]!), index: Number(match[2]!) };
}
function findChildBlockIndex(parent: BlkBlock, step: BlkPathStep): number {
const wanted = step.index ?? 0;
let seen = 0;
for (let i = 0; i < parent.blocks.length; i += 1) {
if (parent.blocks[i]!.name !== step.name) continue;
if (seen === wanted) return i;
seen += 1;
}
return -1;
}
function normalizeIncludeKey(path: string): string {
return path.replaceAll('\\', '/').toLowerCase();
}
+33 -8
View File
@@ -20,9 +20,11 @@ import {
const DEFAULT_SERVER_ENTRIES = ['server/index.ts', 'server/index.mjs', 'server/index.js'] as const;
const DEFAULT_SERVER_TUNING_DIR = 'server/tuning';
const BLK_PATCH_SUFFIX = '.patch.jsonc';
const BLK_JSONC_PATCH_SUFFIX = '.patch.jsonc';
const BLK_TEXT_PATCH_SUFFIX = '.patch.blk';
const CSV_PATCH_SUFFIX = '.patch.csv';
const CONFIG_BLK_PATCH_PATH = 'client/config-blk.patch.jsonc';
const CONFIG_BLK_JSONC_PATCH_PATH = 'client/config-blk.patch.jsonc';
const CONFIG_BLK_TEXT_PATCH_PATH = 'client/config-blk.patch.blk';
export function discoverMods(modsRootDir: string): ModDiscoveryResult {
if (!existsSync(modsRootDir)) return { mods: [], errors: [] };
@@ -93,9 +95,18 @@ export function inspectModContent(rootDir: string, manifest: ModManifest): ModCo
? listRelativeFiles(filesDir)
: [];
const configBlkPatch = isFile(join(rootDir, ...CONFIG_BLK_PATCH_PATH.split('/')))
? CONFIG_BLK_PATCH_PATH
: undefined;
const hasConfigJsonc = isFile(join(rootDir, ...CONFIG_BLK_JSONC_PATCH_PATH.split('/')));
const hasConfigBlk = isFile(join(rootDir, ...CONFIG_BLK_TEXT_PATCH_PATH.split('/')));
if (hasConfigJsonc && hasConfigBlk) {
throw new Error(
`cannot provide both "${CONFIG_BLK_JSONC_PATCH_PATH}" and "${CONFIG_BLK_TEXT_PATCH_PATH}"; choose one format`,
);
}
const configBlkPatch = hasConfigBlk
? CONFIG_BLK_TEXT_PATCH_PATH
: hasConfigJsonc
? CONFIG_BLK_JSONC_PATCH_PATH
: undefined;
const badges = computeRiskBadges({
hasData: serverTuningFiles.length > 0 || packOperations.length > 0 || hasClientAddon || clientFiles.length > 0 || configBlkPatch !== undefined,
@@ -147,19 +158,33 @@ function scanClientPackOperations(rootDir: string): ModPackOperation[] {
if (!isDirectory(packsRoot)) return [];
const ops: ModPackOperation[] = [];
const seenBlkPatchTargets = new Map<string, string>();
for (const pack of MODDABLE_CLIENT_PACKS) {
const packDir = join(packsRoot, ...pack.split('/'));
if (!isDirectory(packDir)) continue;
for (const rel of listRelativeFiles(packDir)) {
const sourceRelativePath = `client/packs/${pack}/${rel}`;
if (rel.toLowerCase().endsWith(BLK_PATCH_SUFFIX)) {
const lower = rel.toLowerCase();
if (lower.endsWith(BLK_JSONC_PATCH_SUFFIX) || lower.endsWith(BLK_TEXT_PATCH_SUFFIX)) {
const suffixLen = lower.endsWith(BLK_TEXT_PATCH_SUFFIX)
? BLK_TEXT_PATCH_SUFFIX.length
: BLK_JSONC_PATCH_SUFFIX.length;
const targetPath = rel.slice(0, -suffixLen);
const key = `${pack}:${targetPath.toLowerCase()}`;
const existingSource = seenBlkPatchTargets.get(key);
if (existingSource) {
throw new Error(
`cannot provide both "${existingSource}" and "${sourceRelativePath}" for "${pack}/${targetPath}"; choose one format`,
);
}
seenBlkPatchTargets.set(key, sourceRelativePath);
ops.push({
pack,
targetPath: rel.slice(0, -BLK_PATCH_SUFFIX.length),
targetPath,
action: 'blk-patch',
sourceRelativePath,
});
} else if (rel.toLowerCase().endsWith(CSV_PATCH_SUFFIX)) {
} else if (lower.endsWith(CSV_PATCH_SUFFIX)) {
ops.push({
pack,
targetPath: rel.slice(0, -CSV_PATCH_SUFFIX.length),
+8
View File
@@ -51,6 +51,14 @@ export {
type BlkPatchValueInput,
type BlkPathStep,
} from './blk-patch.ts';
export {
applyBlkTextPatch,
compileBlkText,
resolvePackRelativePath,
type BlkIncludeResolver,
type BlkIncludeTarget,
type BlkTextPatchOptions,
} from './blk-text-patch.ts';
export { mergeLocalizationCsv } from './csv-patch.ts';
export { mergeTuningLayer, type TuningListOp } from './tuning-merge.ts';
export type {
+2 -2
View File
@@ -53,7 +53,7 @@ export type PackFileAction = 'blk-patch' | 'csv-patch' | 'file';
export interface ModPackOperation {
readonly pack: ModdableClientPack;
/** Target path inside the pack (without .patch.jsonc / .patch.csv suffix). */
/** Target path inside the pack (without .patch.blk / .patch.jsonc / .patch.csv suffix). */
readonly targetPath: string;
readonly action: PackFileAction;
/** Path relative to the mod root folder. */
@@ -72,7 +72,7 @@ export interface ModContentSummary {
readonly addonRelativeFiles: readonly string[];
/** Relative paths under client/files (mapped into the game copy root). */
readonly clientFiles: readonly string[];
/** Optional relative path to client/config-blk.patch.jsonc. */
/** Optional relative path to client/config-blk.patch.blk or client/config-blk.patch.jsonc. */
readonly configBlkPatch?: string;
readonly badges: readonly ModRiskBadge[];
}
@@ -0,0 +1,168 @@
import assert from 'node:assert/strict';
import { mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { describe, it } from 'node:test';
import { decodeBlk, encodeBlk, findBlock, findParam, parseBlkText } from '@wto/blk';
import { discoverMods } from '@wto/mods';
import { PackType, getFile, readArchive, writeArchive, type Archive } from '@wto/vromfs';
import { syncExternalModFiles } from './deploy-external.ts';
import { applyModPackOverlays } from './pack-overlay.ts';
function makeTestArchive(files: ReadonlyArray<readonly [string, Uint8Array]>): Archive {
return {
container: {
magic: 'VRFs',
platform: Buffer.from('PC\0\0', 'latin1'),
packType: PackType.Plain,
extended: null,
signature: new Uint8Array(0),
},
layout: { hasDigestHeader: false, hasDigests: false },
files: new Map(files),
};
}
describe('pack-overlay & config.blk integration for .patch.blk and include', () => {
it('stacks .patch.blk and .patch.jsonc across mods, resolves out-of-order intra-mod includes, and patches config.blk', () => {
const tempRoot = mkdtempSync(join(tmpdir(), 'wto-patcher-blk-test-'));
try {
const modsRoot = join(tempRoot, 'mods');
// Mod A: .patch.blk + standalone .blk with chained include (a_walross -> z_shared_base -> stock maus)
const modA = join(modsRoot, 'mod-a');
mkdirSync(join(modA, 'client', 'packs', 'char.vromfs.bin', 'config'), { recursive: true });
mkdirSync(join(modA, 'client', 'packs', 'aces.vromfs.bin', 'gamedata', 'units', 'tankmodels'), { recursive: true });
writeFileSync(
join(modA, 'mod.jsonc'),
JSON.stringify({
format: 1,
id: 'test.mod-a',
name: 'Mod A',
version: '0.1.0',
author: 'Test',
api_version: '0.1-experimental',
}),
);
writeFileSync(
join(modA, 'client', 'packs', 'char.vromfs.bin', 'config', 'wpcost.blk.patch.blk'),
`
"@clone:germ_pzkpfw_maus->germ_walross" {
"@override:economicRankArcade":i = 18
}
`,
);
writeFileSync(
join(modA, 'client', 'packs', 'aces.vromfs.bin', 'gamedata', 'units', 'tankmodels', 'a_walross.blk'),
`
include "z_shared_base.blk"
"@override:model":t = "pzkpfw_VIII_walross"
"@delete:commonWeapons" {}
commonWeapons {
Weapon { blk:t = "150mm" }
}
`,
);
writeFileSync(
join(modA, 'client', 'packs', 'aces.vromfs.bin', 'gamedata', 'units', 'tankmodels', 'z_shared_base.blk'),
`
include "germ_pzkpfw_maus.blk"
"@override:maxFwdSpeed":r = 35.0
`,
);
writeFileSync(
join(modA, 'client', 'config-blk.patch.blk'),
`
"@override:sound" {
"@override:enable_mod":b = yes
}
`,
);
// Mod B: patches the same wpcost.blk using .patch.jsonc after Mod A
const modB = join(modsRoot, 'mod-b');
mkdirSync(join(modB, 'client', 'packs', 'char.vromfs.bin', 'config'), { recursive: true });
writeFileSync(
join(modB, 'mod.jsonc'),
JSON.stringify({
format: 1,
id: 'test.mod-b',
name: 'Mod B',
version: '0.1.0',
author: 'Test',
api_version: '0.1-experimental',
}),
);
writeFileSync(
join(modB, 'client', 'packs', 'char.vromfs.bin', 'config', 'wpcost.blk.patch.jsonc'),
JSON.stringify({
ops: [
{
op: 'setParam',
path: ['germ_walross'],
name: 'economicRankHistorical',
value: { type: 'int', value: 21 },
},
],
}),
);
const discovered = discoverMods(modsRoot);
assert.equal(discovered.errors.length, 0);
assert.equal(discovered.mods.length, 2);
// Verify stacked char.vromfs.bin overlay (.patch.blk + .patch.jsonc)
const charArchive = makeTestArchive([
[
'config/wpcost.blk',
encodeBlk(parseBlkText('germ_pzkpfw_maus { economicRankArcade:i = 20; economicRankHistorical:i = 20 }')),
],
]);
const charResult = applyModPackOverlays(writeArchive(charArchive), 'char.vromfs.bin', discovered.mods);
const outChar = readArchive(charResult.pack);
const outWpcost = decodeBlk(getFile(outChar, 'config/wpcost.blk'));
const walrossCost = findBlock(outWpcost, 'germ_walross');
assert.ok(walrossCost);
assert.deepEqual(findParam(walrossCost, 'economicRankArcade')?.value, { type: 'int', value: 18 });
assert.deepEqual(findParam(walrossCost, 'economicRankHistorical')?.value, { type: 'int', value: 21 });
// Verify aces.vromfs.bin include compilation
const acesArchive = makeTestArchive([
[
'gamedata/units/tankmodels/germ_pzkpfw_maus.blk',
encodeBlk(
parseBlkText(`
model:t = "pzkpfw_VIII_maus"
maxFwdSpeed:r = 20.0
armor:i = 200
commonWeapons {
Weapon { blk:t = "128mm" }
}
`),
),
],
]);
const acesResult = applyModPackOverlays(writeArchive(acesArchive), 'aces.vromfs.bin', discovered.mods);
const outAces = readArchive(acesResult.pack);
const outWalross = decodeBlk(getFile(outAces, 'gamedata/units/tankmodels/a_walross.blk'));
assert.deepEqual(findParam(outWalross, 'model')?.value, { type: 'string', value: 'pzkpfw_VIII_walross' });
assert.deepEqual(findParam(outWalross, 'maxFwdSpeed')?.value, { type: 'real', value: 35 });
assert.deepEqual(findParam(outWalross, 'armor')?.value, { type: 'int', value: 200 });
const cw = outWalross.blocks.filter((b) => b.name === 'commonWeapons');
assert.equal(cw.length, 1);
assert.deepEqual(findParam(cw[0]!.blocks[0]!, 'blk')?.value, { type: 'string', value: '150mm' });
// Verify client/config-blk.patch.blk
const copyDir = join(tempRoot, 'copy');
const stockDir = join(copyDir, 'wtoffline', 'stock');
mkdirSync(copyDir, { recursive: true });
writeFileSync(join(copyDir, 'config.blk'), 'sound {\n enable_mod:b = no\n}\n', 'utf8');
const deployRes = syncExternalModFiles(copyDir, stockDir, discovered.mods, []);
assert.equal(deployRes.configBlkPatched, true);
const patchedConfig = parseBlkText(readFileSync(join(copyDir, 'config.blk'), 'utf8'));
assert.deepEqual(findParam(findBlock(patchedConfig, 'sound')!, 'enable_mod')?.value, { type: 'bool', value: true });
} finally {
rmSync(tempRoot, { recursive: true, force: true });
}
});
});
+11 -3
View File
@@ -32,6 +32,7 @@ import { dirname, join, relative } from 'node:path';
import { formatBlkText, parseBlkText } from '@wto/blk';
import {
applyBlkPatch,
applyBlkTextPatch,
parseBlkPatchDocument,
type DiscoveredMod,
type ModdableClientPack,
@@ -501,9 +502,16 @@ function syncConfigBlkPatches(
const root = parseBlkText(sourceText);
for (const mod of patchingMods) {
const patchPath = join(mod.rootDir, ...mod.content.configBlkPatch!.split('/'));
const patch = parseBlkPatchDocument(readFileSync(patchPath, 'utf8'), `mod "${mod.manifest.id}" config.blk patch`);
applyBlkPatch(root, patch, `mod "${mod.manifest.id}" config.blk patch`);
const relPatchPath = mod.content.configBlkPatch!;
const patchPath = join(mod.rootDir, ...relPatchPath.split('/'));
const where = `mod "${mod.manifest.id}" config.blk patch`;
const patchText = readFileSync(patchPath, 'utf8');
if (relPatchPath.toLowerCase().endsWith('.patch.blk')) {
applyBlkTextPatch(root, patchText, { where });
} else {
const patch = parseBlkPatchDocument(patchText, where);
applyBlkPatch(root, patch, where);
}
}
unlinkIfExists(liveConfig);
+132 -43
View File
@@ -7,9 +7,14 @@ import { join } from 'node:path';
import { decodeBlk, encodeBlk, isBinaryBlk, parseBlkText, parseSharedNameMap } from '@wto/blk';
import {
applyBlkPatch,
applyBlkTextPatch,
compileBlkText,
mergeLocalizationCsv,
parseBlkPatchDocument,
resolvePackRelativePath,
type BlkIncludeResolver,
type DiscoveredMod,
type ModPackOperation,
type ModdableClientPack,
} from '@wto/mods';
import { getFile, NAME_MAP_PATH, putFile, readArchive, writeArchive, type Archive } from '@wto/vromfs';
@@ -24,12 +29,14 @@ export function applyModPackOverlays(
packName: ModdableClientPack,
mods: readonly DiscoveredMod[],
): { readonly pack: Uint8Array; readonly report: PackOverlayReport } {
const relevant = mods.flatMap((mod) =>
mod.content.packOperations
.filter((op) => op.pack === packName)
.map((op) => ({ mod, op })),
);
if (relevant.length === 0) {
const relevantMods = mods
.map((mod) => ({
mod,
ops: mod.content.packOperations.filter((op) => op.pack === packName),
}))
.filter((entry) => entry.ops.length > 0);
const totalOps = relevantMods.reduce((sum, entry) => sum + entry.ops.length, 0);
if (totalOps === 0) {
return { pack: basePack, report: { pack: packName, operationsApplied: 0 } };
}
@@ -39,52 +46,134 @@ export function applyModPackOverlays(
? parseSharedNameMap(getFile(archive, NAME_MAP_PATH), dictionary).names
: [];
for (const { mod, op } of relevant) {
const sourcePath = join(mod.rootDir, ...op.sourceRelativePath.split('/'));
const where = `mod "${mod.manifest.id}" (${op.sourceRelativePath})`;
switch (op.action) {
case 'blk-patch': {
const resolvedPath = findArchivePath(archive, op.targetPath);
if (!resolvedPath) {
throw new Error(`${where}: target BLK "${op.targetPath}" not found in ${packName}`);
}
const raw = getFile(archive, resolvedPath);
const root = isBinaryBlk(raw)
? decodeBlk(raw, { names, dictionary })
: parseBlkText(Buffer.from(raw).toString('utf8'));
const patch = parseBlkPatchDocument(readFileSync(sourcePath, 'utf8'), where);
applyBlkPatch(root, patch, where);
putFile(archive, resolvedPath, encodeBlk(root));
break;
for (const { mod, ops } of relevantMods) {
const pendingModFiles = new Map<string, ModPackOperation>();
for (const op of ops) {
if (op.action === 'file') {
pendingModFiles.set(op.targetPath.toLowerCase(), op);
}
case 'csv-patch': {
const resolvedPath = findArchivePath(archive, op.targetPath);
if (!resolvedPath) {
throw new Error(`${where}: target CSV "${op.targetPath}" not found in ${packName}`);
}
for (const op of ops) {
const sourcePath = join(mod.rootDir, ...op.sourceRelativePath.split('/'));
const where = `mod "${mod.manifest.id}" (${op.sourceRelativePath})`;
const currentTargetKey = op.targetPath.toLowerCase();
const resolveInclude = createArchiveIncludeResolver({
archive,
names,
dictionary,
mod,
pendingModFiles,
currentTargetKey: op.action === 'file' ? currentTargetKey : undefined,
where,
});
switch (op.action) {
case 'blk-patch': {
const resolvedPath = findArchivePath(archive, op.targetPath);
if (!resolvedPath) {
throw new Error(`${where}: target BLK "${op.targetPath}" not found in ${packName}`);
}
const raw = getFile(archive, resolvedPath);
const root = isBinaryBlk(raw)
? decodeBlk(raw, { names, dictionary })
: parseBlkText(Buffer.from(raw).toString('utf8'));
const patchText = readFileSync(sourcePath, 'utf8');
if (op.sourceRelativePath.toLowerCase().endsWith('.patch.blk')) {
applyBlkTextPatch(root, patchText, {
where,
sourcePath: `${resolvedPath}.patch.blk`,
resolveInclude,
});
} else {
const patch = parseBlkPatchDocument(patchText, where);
applyBlkPatch(root, patch, where);
}
putFile(archive, resolvedPath, encodeBlk(root));
break;
}
const baseText = Buffer.from(getFile(archive, resolvedPath)).toString('utf8');
const patchText = readFileSync(sourcePath, 'utf8');
const merged = mergeLocalizationCsv(baseText, patchText);
putFile(archive, resolvedPath, Buffer.from(merged, 'utf8'));
break;
}
case 'file': {
const bytes = readFileSync(sourcePath);
const resolvedPath = findArchivePath(archive, op.targetPath) ?? op.targetPath;
if (op.targetPath.toLowerCase().endsWith('.blk') && !isBinaryBlk(bytes)) {
const parsed = parseBlkText(bytes.toString('utf8'));
putFile(archive, resolvedPath, encodeBlk(parsed));
} else {
putFile(archive, resolvedPath, bytes);
case 'csv-patch': {
const resolvedPath = findArchivePath(archive, op.targetPath);
if (!resolvedPath) {
throw new Error(`${where}: target CSV "${op.targetPath}" not found in ${packName}`);
}
const baseText = Buffer.from(getFile(archive, resolvedPath)).toString('utf8');
const patchText = readFileSync(sourcePath, 'utf8');
const merged = mergeLocalizationCsv(baseText, patchText);
putFile(archive, resolvedPath, Buffer.from(merged, 'utf8'));
break;
}
case 'file': {
const bytes = readFileSync(sourcePath);
const resolvedPath = findArchivePath(archive, op.targetPath) ?? op.targetPath;
if (op.targetPath.toLowerCase().endsWith('.blk') && !isBinaryBlk(bytes)) {
const compiled = compileBlkText(bytes.toString('utf8'), {
where,
sourcePath: resolvedPath,
resolveInclude,
});
putFile(archive, resolvedPath, encodeBlk(compiled));
} else {
putFile(archive, resolvedPath, bytes);
}
pendingModFiles.delete(currentTargetKey);
break;
}
break;
}
}
}
return {
pack: writeArchive(archive),
report: { pack: packName, operationsApplied: relevant.length },
report: { pack: packName, operationsApplied: totalOps },
};
}
function createArchiveIncludeResolver(params: {
readonly archive: Archive;
readonly names: readonly string[];
readonly dictionary: Uint8Array | undefined;
readonly mod: DiscoveredMod;
readonly pendingModFiles: ReadonlyMap<string, ModPackOperation>;
readonly currentTargetKey: string | undefined;
readonly where: string;
}): BlkIncludeResolver {
return (includePath, fromPath) => {
const resolvedTarget = resolvePackRelativePath(fromPath, includePath, params.where);
const key = resolvedTarget.toLowerCase();
// Allow intra-mod includes regardless of alphabetical filename order, without self-including.
if (key !== params.currentTargetKey) {
const pendingOp = params.pendingModFiles.get(key);
if (pendingOp) {
const pendingDiskPath = join(params.mod.rootDir, ...pendingOp.sourceRelativePath.split('/'));
const bytes = readFileSync(pendingDiskPath);
if (isBinaryBlk(bytes)) {
return {
resolvedPath: pendingOp.targetPath,
content: { kind: 'block', block: decodeBlk(bytes, { names: params.names, dictionary: params.dictionary }) },
};
}
return {
resolvedPath: pendingOp.targetPath,
content: { kind: 'text', text: bytes.toString('utf8') },
};
}
}
const archivePath = findArchivePath(params.archive, resolvedTarget);
if (!archivePath) return undefined;
const raw = getFile(params.archive, archivePath);
if (isBinaryBlk(raw)) {
return {
resolvedPath: archivePath,
content: { kind: 'block', block: decodeBlk(raw, { names: params.names, dictionary: params.dictionary }) },
};
}
return {
resolvedPath: archivePath,
content: { kind: 'text', text: Buffer.from(raw).toString('utf8') },
};
};
}