Просмотр исходного кода

Merge pull request #2505 from visuddhinanda/development

Development
visuddhinanda 2 дней назад
Родитель
Сommit
1f21934903
100 измененных файлов с 11583 добавлено и 630 удалено
  1. 0 0
      CLAUDE.md
  2. 8 0
      api-test/README.md
  3. 1 0
      api-test/cases/18_term_exchange.php
  4. 15 34
      api-test/cases/24_admin_credits.php
  5. 29 0
      api-test/cases/25_markup_previews.php
  6. 82 0
      api-test/cases/26_tipitaka_exports.php
  7. 24 0
      api-test/client/.openapi-generator/FILES
  8. 532 0
      api-test/client/lib/Api/MarkupPreviewsApi.php
  9. 1188 0
      api-test/client/lib/Api/TipitakaExportsApi.php
  10. 409 0
      api-test/client/lib/Model/PostApiV3MarkupPreviews200Response.php
  11. 409 0
      api-test/client/lib/Model/PostApiV3MarkupPreviews200ResponseData.php
  12. 548 0
      api-test/client/lib/Model/PostApiV3MarkupPreviewsRequest.php
  13. 409 0
      api-test/client/lib/Model/PostApiV3TipitakaExports200Response.php
  14. 852 0
      api-test/client/lib/Model/PostApiV3TipitakaExports200ResponseData.php
  15. 625 0
      api-test/client/lib/Model/PostApiV3TipitakaExportsRequest.php
  16. 7 0
      api-test/config.local.example.php
  17. 13 0
      api-test/config.php
  18. 6 1
      api-test/fixtures.php
  19. 15 1
      api-test/run.php
  20. 55 0
      api-test/src/bootstrap.php
  21. 3 3
      api-v13/app/Console/Commands/ExportAiTrainingData.php
  22. 5 5
      api-v13/app/Console/Commands/ExportChapter.php
  23. 3 3
      api-v13/app/Console/Commands/ExportDiscussion.php
  24. 4 4
      api-v13/app/Console/Commands/ExportSentence.php
  25. 4 3
      api-v13/app/Console/Commands/ExtractPaliTerm.php
  26. 4 3
      api-v13/app/Console/Commands/IndexTipitaka.php
  27. 3 3
      api-v13/app/Console/Commands/InitCs6sentence.php
  28. 3 0
      api-v13/app/Console/Commands/InstallPaliText.php
  29. 48 0
      api-v13/app/Console/Commands/MqExportTipitaka.php
  30. 4 3
      api-v13/app/Console/Commands/UpgradeAITranslation.php
  31. 4 4
      api-v13/app/Console/Commands/UpgradeGrammarBook.php
  32. 3 0
      api-v13/app/Console/Commands/UpgradePaliText.php
  33. 3 3
      api-v13/app/Console/Commands/UpgradeQuote.php
  34. 3 3
      api-v13/app/Console/Commands/UpgradeSystemCommentary.php
  35. 3 3
      api-v13/app/Console/Commands/UpgradeWbwTemplate.php
  36. 4 0
      api-v13/app/Facades/RedisCache.php
  37. 25 31
      api-v13/app/Http/Controllers/Library/BookController.php
  38. 102 0
      api-v13/app/Http/Controllers/Library/TipitakaDownloadController.php
  39. 46 0
      api-v13/app/Http/Controllers/V3/MarkupPreviewController.php
  40. 70 0
      api-v13/app/Http/Controllers/V3/TipitakaExportController.php
  41. 43 0
      api-v13/app/Http/Controllers/V3/TipitakaExportFileController.php
  42. 30 0
      api-v13/app/Http/Requests/V3/StoreMarkupPreviewRequest.php
  43. 35 0
      api-v13/app/Http/Requests/V3/StoreTipitakaExportRequest.php
  44. 20 0
      api-v13/app/Http/Resources/V3/MarkupPreviewResource.php
  45. 38 0
      api-v13/app/Http/Resources/V3/TipitakaExportResource.php
  46. 16 10
      api-v13/app/Models/Discussion.php
  47. 38 10
      api-v13/app/Models/Sentence.php
  48. 3 0
      api-v13/app/Providers/AppServiceProvider.php
  49. 290 91
      api-v13/app/Services/PaliContentService.php
  50. 129 0
      api-v13/app/Services/ReadingIndexService.php
  51. 64 1
      api-v13/app/Services/RedisCache.php
  52. 19 2
      api-v13/app/Services/RedisCacheFake.php
  53. 47 0
      api-v13/app/Services/V3/MarkupPreviewService.php
  54. 260 0
      api-v13/app/Services/V3/PaliTextService.php
  55. 1 1
      api-v13/app/Services/V3/TipitakaBookService.php
  56. 578 0
      api-v13/app/Services/V3/TipitakaExportBuilder.php
  57. 85 0
      api-v13/app/Services/V3/TipitakaExportDownload.php
  58. 25 0
      api-v13/app/Services/V3/TipitakaExportQueue.php
  59. 434 0
      api-v13/app/Services/V3/TipitakaExportService.php
  60. 105 68
      api-v13/app/Services/V3/TipitakaReadingService.php
  61. 1 1
      api-v13/app/Services/V3/TipitakaTitleService.php
  62. 5 0
      api-v13/bootstrap/app.php
  63. 24 0
      api-v13/config/mint.php
  64. 403 0
      api-v13/documents/download-demo.html
  65. 354 0
      api-v13/documents/reading-cache-plan.html
  66. 12 0
      api-v13/documents/tasks.md
  67. 8 12
      api-v13/public/data/category/default.json
  68. 195 0
      api-v13/resources/css/modules/tipitaka.css
  69. 5 0
      api-v13/resources/data/pali_serieses.php
  70. 45 0
      api-v13/resources/lang/en/library.php
  71. 6 0
      api-v13/resources/lang/en/messages.php
  72. 45 0
      api-v13/resources/lang/zh-Hans/library.php
  73. 6 0
      api-v13/resources/lang/zh-Hans/messages.php
  74. 45 0
      api-v13/resources/lang/zh-Hant/library.php
  75. 5 0
      api-v13/resources/lang/zh-Hant/messages.php
  76. 9 0
      api-v13/resources/template/epub/tipitaka.css
  77. 28 0
      api-v13/resources/views/exports/tipitaka/_style.blade.php
  78. 142 0
      api-v13/resources/views/exports/tipitaka/index.blade.php
  79. 105 0
      api-v13/resources/views/exports/tipitaka/work.blade.php
  80. 3 0
      api-v13/resources/views/library/tipitaka/channels/category.blade.php
  81. 239 0
      api-v13/resources/views/library/tipitaka/download.blade.php
  82. 2 3
      api-v13/resources/views/library/tipitaka/show.blade.php
  83. 1 0
      api-v13/routes/api.php
  84. 16 0
      api-v13/routes/v3/markup.php
  85. 15 0
      api-v13/routes/v3/tipitaka.php
  86. 4 0
      api-v13/routes/web.php
  87. 64 0
      api-v13/tests/Feature/MarkupPreviewV3Test.php
  88. 246 0
      api-v13/tests/Feature/ReadingCacheTest.php
  89. 41 0
      api-v13/tests/Feature/RedisCacheTest.php
  90. 353 0
      api-v13/tests/Feature/TipitakaExportV3Test.php
  91. 7 3
      api-v13/tests/Feature/TipitakaReadingRenderTest.php
  92. 55 4
      dashboard-test/src/tests/term.spec.ts
  93. 72 0
      dashboard-test/src/tests/tpl-builder.spec.ts
  94. 19 0
      dashboard-v6/src/api/markup.ts
  95. 367 0
      dashboard-v6/src/api/schema.d.ts
  96. 488 253
      dashboard-v6/src/components/term/TermEdit.tsx
  97. 7 2
      dashboard-v6/src/components/term/TermModal.tsx
  98. 0 29
      dashboard-v6/src/components/tpl-builder/ArticleTpl.tsx
  99. 135 33
      dashboard-v6/src/components/tpl-builder/TplBuilder.tsx
  100. 175 0
      dashboard-v6/src/components/tpl-builder/TplForm.tsx

Разница между файлами не показана из-за своего большого размера
+ 0 - 0
CLAUDE.md


+ 8 - 0
api-test/README.md

@@ -88,6 +88,14 @@ php run.php --username=alice --password=secret                 # 调 /v3/session
   所以跑全量前要带 `--token=` 或 `--username/--password`。
 - **写操作在所有服务器上都真实执行**(POST 建 / DELETE 删,用垃圾 target_id,测完即删),
   包括 prod。会产生少量垃圾数据,由测试账号定期清理。
+- **管理员用例(`/v3/admin/*`)用单独的管理员账号**,不用上面的测试账号(测试账号会写垃圾数据,
+  不给它管理员权限)。在 `config.local.php` 的 `servers[alias]` 里配 `admin_username` /
+  `admin_password`(或 `admin_token`),也可以用 `--admin-username= --admin-password=` /
+  `--admin-token=` 或环境变量 `API_TEST_ADMIN_*`。没配就 SKIP;配了但账号没有
+  administrator / root 角色就 FAIL。只在跑到管理员用例时才登录。
+  - **管理员在生产上只读**:admin 路由的写入用例(POST,含 422 校验)只在 `config.php` 的
+    `admin_write_servers` 白名单(默认 `local`、`staging`)上跑,其余服务器(含 next / next-cn
+    与未登记的完整 URL)一律 SKIP。401 / 403 用例仍用普通测试账号,各服务器都跑。
 - 登录接口 `POST /v3/sessions {login, password}`:`login` 可以是用户名或邮箱;成功 201
   `{data:{token, user}}`,账号或密码不对 422。**目标服务器还没部署 v3 登录时**,
   改用 `--token=` 直接给 token(v2 / v3 签的 token 一样,可以从 v4 登录后拿)。

+ 1 - 0
api-test/cases/18_term_exchange.php

@@ -23,6 +23,7 @@ test('POST /v3/channels/{channel}/terms/imports(无 token)→ 401', function
 test('术语导出 → 原样导入一轮:xlsx 200 → 导入 200(未变 1)→ 坏文件 422', function () {
     $token = required_token();
     $me = raw('GET', '/v3/me', null, null, $token);
+    assert_status(200, $me, 'me');
     $body = new PostApiV3StudiosStudioChannelsRequest();
     $body->setName('e2e-tmp-exchange-'.time());
     $body->setType('translation');

+ 15 - 34
api-test/cases/24_admin_credits.php

@@ -8,29 +8,12 @@ use \WikipaliApi\Model\PostApiV3AdminCreditSettlementsRequest;
  * v3 管理后台 · AI 对话积分:/v3/admin/credit-overview、credit-accounts、credit-ledger、
  * credit-adjustments、credit-settlements(仅 root / administrator)。
  *
- * 测试账号是普通用户时只测 401 / 403;是管理员时再测读、422 与写。
+ * 两个账号:401 / 403 用普通测试账号;读与写用单独配置的管理员账号(admin_token(),没配就 SKIP)。
+ * 管理员在生产上只读:写入用例(POST,含 422 校验)走 admin_write_token(),
+ * 只在 config.php 的 admin_write_servers 白名单服务器上跑。
  * 写都是幂等的:结算重复执行结果覆盖;给自己 +1 再 -1 用固定的 ref,每台服务器只入账一次、净额为 0。
  */
 
-/** 测试账号是不是管理员(看 /v3/me 的 roles) */
-function credit_admin(string $token): bool
-{
-    $me = raw('GET', '/v3/me', null, null, $token);
-    $roles = $me['body']['data']['roles'] ?? [];
-
-    return (bool) array_intersect(['administrator', 'root'], $roles);
-}
-
-function admin_token_or_skip(): string
-{
-    $token = required_token();
-    if (! credit_admin($token)) {
-        skip('测试账号不是管理员');
-    }
-
-    return $token;
-}
-
 /* ---- 无 token → 401 ---- */
 
 test('GET /v3/admin/credit-overview(无 token)→ 401', function () {
@@ -47,11 +30,7 @@ test('POST /v3/admin/credit-settlements(无 token)→ 401', function () {
 /* ---- 普通用户 → 403 ---- */
 
 test('GET /v3/admin/credit-accounts(非管理员)→ 403', function () {
-    $token = required_token();
-    if (credit_admin($token)) {
-        skip('测试账号是管理员');
-    }
-    $res = request(fn () => api(AdminApi::class, $token)->getApiV3AdminCreditAccountsWithHttpInfo());
+    $res = request(fn () => api(AdminApi::class, required_token())->getApiV3AdminCreditAccountsWithHttpInfo());
     assert_status(403, $res, 'credit-accounts');
     assert_problem($res, 'credit-accounts');
 });
@@ -59,7 +38,7 @@ test('GET /v3/admin/credit-accounts(非管理员)→ 403', function () {
 /* ---- 管理员:读 ---- */
 
 test('GET /v3/admin/credit-overview → 200', function () {
-    $res = request(fn () => api(AdminApi::class, admin_token_or_skip())->getApiV3AdminCreditOverviewWithHttpInfo());
+    $res = request(fn () => api(AdminApi::class, admin_token())->getApiV3AdminCreditOverviewWithHttpInfo());
     assert_status(200, $res, 'credit-overview');
     foreach (['today', 'earn_since', 'policy_version', 'policy', 'totals', 'recent_days', 'last_settlement'] as $key) {
         assert_has_key($key, $res['body']['data'], 'credit-overview.data');
@@ -68,7 +47,7 @@ test('GET /v3/admin/credit-overview → 200', function () {
 });
 
 test('GET /v3/admin/credit-accounts → 200 分页', function () {
-    $res = request(fn () => api(AdminApi::class, admin_token_or_skip())->getApiV3AdminCreditAccountsWithHttpInfo(per_page: 5));
+    $res = request(fn () => api(AdminApi::class, admin_token())->getApiV3AdminCreditAccountsWithHttpInfo(per_page: 5));
     assert_status(200, $res, 'credit-accounts');
     assert_has_key('total', $res['body']['meta'], 'credit-accounts.meta');
     foreach ($res['body']['data'] as $row) {
@@ -79,17 +58,17 @@ test('GET /v3/admin/credit-accounts → 200 分页', function () {
 });
 
 test('GET /v3/admin/credit-ledger(只给 account_id)→ 422', function () {
-    $res = request(fn () => api(AdminApi::class, admin_token_or_skip())->getApiV3AdminCreditLedgerWithHttpInfo(
+    $res = request(fn () => api(AdminApi::class, admin_token())->getApiV3AdminCreditLedgerWithHttpInfo(
         filter_account_id: '00000000-0000-4000-8000-000000000000',
     ));
     assert_status(422, $res, 'credit-ledger');
     assert_field_error('filter.account_type', $res, 'credit-ledger');
 });
 
-/* ---- 管理员:写(幂等) ---- */
+/* ---- 管理员:写(幂等;只在 admin_write_servers 上跑) ---- */
 
 test('POST /v3/admin/credit-settlements → 201(可重复执行)', function () {
-    $res = request(fn () => api(AdminApi::class, admin_token_or_skip())->postApiV3AdminCreditSettlementsWithHttpInfo(
+    $res = request(fn () => api(AdminApi::class, admin_write_token())->postApiV3AdminCreditSettlementsWithHttpInfo(
         new PostApiV3AdminCreditSettlementsRequest(),
     ));
     assert_status(201, $res, 'credit-settlements');
@@ -99,14 +78,16 @@ test('POST /v3/admin/credit-settlements → 201(可重复执行)', function
 test('POST /v3/admin/credit-settlements(未来日期)→ 422', function () {
     $body = new PostApiV3AdminCreditSettlementsRequest();
     $body->setDate(gmdate('Y-m-d', time() + 86400 * 2));
-    $res = request(fn () => api(AdminApi::class, admin_token_or_skip())->postApiV3AdminCreditSettlementsWithHttpInfo($body));
+    $res = request(fn () => api(AdminApi::class, admin_write_token())->postApiV3AdminCreditSettlementsWithHttpInfo($body));
     assert_status(422, $res, 'credit-settlements');
     assert_field_error('date', $res, 'credit-settlements');
 });
 
 test('POST /v3/admin/credit-adjustments:给自己 +1 再 -1(固定 ref,只入账一次)', function () {
-    $token = admin_token_or_skip();
-    $me = raw('GET', '/v3/me', null, null, $token)['body']['data']['id'];
+    $token = admin_write_token();
+    $me = raw('GET', '/v3/me', null, null, $token);
+    assert_status(200, $me, 'me');
+    $me = $me['body']['data']['id'];
     foreach ([['8f0b5a52-3c1e-4e0a-9d7a-5b1f0c2e0001', 1], ['8f0b5a52-3c1e-4e0a-9d7a-5b1f0c2e0002', -1]] as [$ref, $delta]) {
         $body = new PostApiV3AdminCreditAdjustmentsRequest();
         $body->setUser($me);
@@ -126,7 +107,7 @@ test('POST /v3/admin/credit-adjustments(delta 为 0、缺原因)→ 422', fu
     $body->setUser('nobody');
     $body->setDelta(0);
     $body->setNote('');
-    $res = request(fn () => api(AdminApi::class, admin_token_or_skip())->postApiV3AdminCreditAdjustmentsWithHttpInfo($body));
+    $res = request(fn () => api(AdminApi::class, admin_write_token())->postApiV3AdminCreditAdjustmentsWithHttpInfo($body));
     assert_status(422, $res, 'credit-adjustments');
     assert_field_error('delta', $res, 'credit-adjustments');
 });

+ 29 - 0
api-test/cases/25_markup_previews.php

@@ -0,0 +1,29 @@
+<?php
+
+use \WikipaliApi\Api\MarkupPreviewsApi;
+use \WikipaliApi\Model\PostApiV3MarkupPreviewsRequest;
+
+/*
+ * 源码预览:POST /v3/markup-previews(模板生成器的预览)。要登录,不写库。
+ * 各服务器数据不同,只核对形状;按 channel 查术语、私有 channel 403 由 api-v13 的 MarkupPreviewV3Test 覆盖。
+ */
+
+test('POST /v3/markup-previews → 200,body 是节点树', function () {
+    $token = required_token();
+    $body = new PostApiV3MarkupPreviewsRequest();
+    $body->setContent("**粗体** {{quality|featured}}\n\n{{v|url=https://example.com/a.mp4|title=x}}");
+    $res = request(fn () => api(MarkupPreviewsApi::class, $token)->postApiV3MarkupPreviewsWithHttpInfo($body));
+    assert_status(200, $res, 'markup preview');
+    $nodes = $res['body']['data']['body'] ?? null;
+    assert_eq(true, is_array($nodes) && count($nodes) > 0, 'body 不为空');
+    $json = json_encode($nodes);
+    assert_eq([true, true], [str_contains($json, '"name":"quality"'), str_contains($json, '"name":"video"')], '模板节点');
+});
+
+test('POST /v3/markup-previews:无 token → 401,缺 content → 422', function () {
+    $anon = raw('POST', '/v3/markup-previews', null, ['content' => 'x']);
+    assert_status(401, $anon, '无 token');
+    $bad = raw('POST', '/v3/markup-previews', null, ['content_type' => 'html'], required_token());
+    assert_status(422, $bad, '缺 content');
+    assert_field_error('content', $bad, '缺 content');
+});

+ 82 - 0
api-test/cases/26_tipitaka_exports.php

@@ -0,0 +1,82 @@
+<?php
+
+use \WikipaliApi\Api\TipitakaExportsApi;
+use \WikipaliApi\Model\PostApiV3TipitakaExportsRequest;
+
+/*
+| 三藏下载 /v3/tipitaka-exports:发起 → 轮询 → 签名链接下载。
+| 发起是公开的(公开 channel 不用登录);生成要服务器上的 worker(mq:export.tipitaka)在跑,
+| 60 秒内没做完算失败。生成的文件留在 Redis 里 7 天,同一份再跑直接命中,不累积。
+*/
+
+test('POST /v3/tipitaka-exports(作品 markdown)→ 200/202,轮询到 ready,签名链接能下载、支持 Range', function () {
+    $body = new PostApiV3TipitakaExportsRequest([
+        'channel' => fixtures()['export_channel'],
+        'work' => fixtures()['export_work'],
+        'format' => 'markdown',
+    ]);
+    $res = request(fn () => api(TipitakaExportsApi::class)->postApiV3TipitakaExportsWithHttpInfo($body));
+    if (! in_array($res['status'], [200, 202], true)) {
+        assert_status(202, $res, 'tipitaka-exports POST');
+    }
+    $data = $res['body']['data'] ?? [];
+    assert_has_key('id', $data, 'tipitaka-exports.data');
+    assert_eq('markdown', $data['format'] ?? null, 'tipitaka-exports.data.format');
+
+    $deadline = time() + 60;
+    while (($data['status'] ?? null) !== 'ready') {
+        if (($data['status'] ?? null) === 'failed') {
+            fail('tipitaka-exports 生成失败:' . ($data['message'] ?? ''));
+        }
+        if (time() > $deadline) {
+            fail('tipitaka-exports 60 秒内没有生成好(worker mq:export.tipitaka 在跑吗?)status=' . ($data['status'] ?? '?'));
+        }
+        sleep(2);
+        $poll = request(fn () => api(TipitakaExportsApi::class)->getApiV3TipitakaExportsExportWithHttpInfo($data['id']));
+        assert_status(200, $poll, 'tipitaka-exports GET');
+        $data = $poll['body']['data'];
+    }
+    if (! str_starts_with((string) ($data['download_url'] ?? ''), '/api/v3/tipitaka-exports/')) {
+        fail('tipitaka-exports.download_url 应是相对地址,实际 ' . ($data['download_url'] ?? 'null'));
+    }
+
+    // download_url 已带 /api 前缀,base_url 也带,去掉一层
+    $path = substr($data['download_url'], strlen('/api'));
+    $file = raw('GET', $path);
+    assert_status(200, $file, 'tipitaka-exports file');
+    assert_eq('application/zip', $file['headers']['content-type'][0] ?? null, 'tipitaka-exports file content-type');
+    assert_eq((string) $data['size'], $file['headers']['content-length'][0] ?? null, 'tipitaka-exports file content-length');
+
+    $part = raw('GET', $path, null, null, null, ['Range' => 'bytes=0-1']);
+    assert_status(206, $part, 'tipitaka-exports file Range');
+    assert_eq('bytes 0-1/' . $data['size'], $part['headers']['content-range'][0] ?? null, 'tipitaka-exports Content-Range');
+});
+
+test('GET /v3/tipitaka-exports/{id}/file 没有签名 → 403', function () {
+    $res = raw('GET', '/v3/tipitaka-exports/' . str_repeat('0', 40) . '/file');
+    assert_status(403, $res, 'tipitaka-exports file 无签名');
+});
+
+test('GET /v3/tipitaka-exports/{不存在} → 404', function () {
+    $res = raw('GET', '/v3/tipitaka-exports/' . str_repeat('0', 40));
+    assert_status(404, $res, 'tipitaka-exports 不存在');
+    assert_problem($res, 'tipitaka-exports 不存在');
+});
+
+test('POST /v3/tipitaka-exports 缺 format → 422', function () {
+    $res = raw('POST', '/v3/tipitaka-exports', null, ['channel' => fixtures()['export_channel']]);
+    assert_status(422, $res, 'tipitaka-exports 缺 format');
+    assert_field_error('format', $res, 'tipitaka-exports 缺 format');
+});
+
+test('POST /v3/tipitaka-exports 离线包不按作品 → 422', function () {
+    $res = raw('POST', '/v3/tipitaka-exports', null, ['channel' => fixtures()['export_channel'], 'format' => 'offline']);
+    assert_status(422, $res, 'tipitaka-exports offline 无 work');
+    assert_field_error('format', $res, 'tipitaka-exports offline 无 work');
+});
+
+test('POST /v3/tipitaka-exports 没收录的作品 → 404', function () {
+    $res = raw('POST', '/v3/tipitaka-exports', null, ['channel' => fixtures()['export_channel'], 'work' => 999999, 'format' => 'html']);
+    assert_status(404, $res, 'tipitaka-exports 未收录作品');
+    assert_problem($res, 'tipitaka-exports 未收录作品');
+});

+ 24 - 0
api-test/client/.openapi-generator/FILES

@@ -20,6 +20,7 @@ docs/Api/GlossariesApi.md
 docs/Api/GroupsApi.md
 docs/Api/HeartbeatApi.md
 docs/Api/InvitesApi.md
+docs/Api/MarkupPreviewsApi.md
 docs/Api/MeApi.md
 docs/Api/NissayaCardsApi.md
 docs/Api/PaliWordFormsApi.md
@@ -36,6 +37,7 @@ docs/Api/TermsApi.md
 docs/Api/TipitakaChannelsApi.md
 docs/Api/TipitakaChapterChannelsApi.md
 docs/Api/TipitakaDiscussionsApi.md
+docs/Api/TipitakaExportsApi.md
 docs/Api/TipitakaPageNumbersApi.md
 docs/Api/TipitakaParagraphChannelsApi.md
 docs/Api/TipitakaReadingApi.md
@@ -246,6 +248,9 @@ docs/Model/PostApiV3GroupsRequest.md
 docs/Model/PostApiV3Invites200Response.md
 docs/Model/PostApiV3Invites200ResponseData.md
 docs/Model/PostApiV3InvitesRequest.md
+docs/Model/PostApiV3MarkupPreviews200Response.md
+docs/Model/PostApiV3MarkupPreviews200ResponseData.md
+docs/Model/PostApiV3MarkupPreviewsRequest.md
 docs/Model/PostApiV3MeReactions200Response.md
 docs/Model/PostApiV3MeReactionsRequest.md
 docs/Model/PostApiV3MeReadingTime200Response.md
@@ -260,6 +265,9 @@ docs/Model/PostApiV3Sessions200ResponseData.md
 docs/Model/PostApiV3SessionsRequest.md
 docs/Model/PostApiV3StudiosStudioChannelsRequest.md
 docs/Model/PostApiV3StudiosStudioTermsRequest.md
+docs/Model/PostApiV3TipitakaExports200Response.md
+docs/Model/PostApiV3TipitakaExports200ResponseData.md
+docs/Model/PostApiV3TipitakaExportsRequest.md
 docs/Model/PostApiV3Users200Response.md
 docs/Model/PostApiV3Users200ResponseData.md
 docs/Model/PostApiV3UsersRequest.md
@@ -281,6 +289,7 @@ lib/Api/GlossariesApi.php
 lib/Api/GroupsApi.php
 lib/Api/HeartbeatApi.php
 lib/Api/InvitesApi.php
+lib/Api/MarkupPreviewsApi.php
 lib/Api/MeApi.php
 lib/Api/NissayaCardsApi.php
 lib/Api/PaliWordFormsApi.php
@@ -297,6 +306,7 @@ lib/Api/TermsApi.php
 lib/Api/TipitakaChannelsApi.php
 lib/Api/TipitakaChapterChannelsApi.php
 lib/Api/TipitakaDiscussionsApi.php
+lib/Api/TipitakaExportsApi.php
 lib/Api/TipitakaPageNumbersApi.php
 lib/Api/TipitakaParagraphChannelsApi.php
 lib/Api/TipitakaReadingApi.php
@@ -512,6 +522,9 @@ lib/Model/PostApiV3GroupsRequest.php
 lib/Model/PostApiV3Invites200Response.php
 lib/Model/PostApiV3Invites200ResponseData.php
 lib/Model/PostApiV3InvitesRequest.php
+lib/Model/PostApiV3MarkupPreviews200Response.php
+lib/Model/PostApiV3MarkupPreviews200ResponseData.php
+lib/Model/PostApiV3MarkupPreviewsRequest.php
 lib/Model/PostApiV3MeReactions200Response.php
 lib/Model/PostApiV3MeReactionsRequest.php
 lib/Model/PostApiV3MeReadingTime200Response.php
@@ -526,6 +539,9 @@ lib/Model/PostApiV3Sessions200ResponseData.php
 lib/Model/PostApiV3SessionsRequest.php
 lib/Model/PostApiV3StudiosStudioChannelsRequest.php
 lib/Model/PostApiV3StudiosStudioTermsRequest.php
+lib/Model/PostApiV3TipitakaExports200Response.php
+lib/Model/PostApiV3TipitakaExports200ResponseData.php
+lib/Model/PostApiV3TipitakaExportsRequest.php
 lib/Model/PostApiV3Users200Response.php
 lib/Model/PostApiV3Users200ResponseData.php
 lib/Model/PostApiV3UsersRequest.php
@@ -548,6 +564,7 @@ test/Api/GlossariesApiTest.php
 test/Api/GroupsApiTest.php
 test/Api/HeartbeatApiTest.php
 test/Api/InvitesApiTest.php
+test/Api/MarkupPreviewsApiTest.php
 test/Api/MeApiTest.php
 test/Api/NissayaCardsApiTest.php
 test/Api/PaliWordFormsApiTest.php
@@ -564,6 +581,7 @@ test/Api/TermsApiTest.php
 test/Api/TipitakaChannelsApiTest.php
 test/Api/TipitakaChapterChannelsApiTest.php
 test/Api/TipitakaDiscussionsApiTest.php
+test/Api/TipitakaExportsApiTest.php
 test/Api/TipitakaPageNumbersApiTest.php
 test/Api/TipitakaParagraphChannelsApiTest.php
 test/Api/TipitakaReadingApiTest.php
@@ -774,6 +792,9 @@ test/Model/PostApiV3GroupsRequestTest.php
 test/Model/PostApiV3Invites200ResponseDataTest.php
 test/Model/PostApiV3Invites200ResponseTest.php
 test/Model/PostApiV3InvitesRequestTest.php
+test/Model/PostApiV3MarkupPreviews200ResponseDataTest.php
+test/Model/PostApiV3MarkupPreviews200ResponseTest.php
+test/Model/PostApiV3MarkupPreviewsRequestTest.php
 test/Model/PostApiV3MeReactions200ResponseTest.php
 test/Model/PostApiV3MeReactionsRequestTest.php
 test/Model/PostApiV3MeReadingTime200ResponseDataTest.php
@@ -788,6 +809,9 @@ test/Model/PostApiV3Sessions200ResponseTest.php
 test/Model/PostApiV3SessionsRequestTest.php
 test/Model/PostApiV3StudiosStudioChannelsRequestTest.php
 test/Model/PostApiV3StudiosStudioTermsRequestTest.php
+test/Model/PostApiV3TipitakaExports200ResponseDataTest.php
+test/Model/PostApiV3TipitakaExports200ResponseTest.php
+test/Model/PostApiV3TipitakaExportsRequestTest.php
 test/Model/PostApiV3Users200ResponseDataTest.php
 test/Model/PostApiV3Users200ResponseTest.php
 test/Model/PostApiV3UsersRequestTest.php

+ 532 - 0
api-test/client/lib/Api/MarkupPreviewsApi.php

@@ -0,0 +1,532 @@
+<?php
+/**
+ * MarkupPreviewsApi
+ * PHP version 8.1
+ *
+ * @category Class
+ * @package  WikipaliApi
+ * @author   OpenAPI Generator team
+ * @link     https://openapi-generator.tech
+ */
+
+/**
+ * MINT API
+ *
+ * International Academy Of Pali Tipitaka(国际巴利三藏学院)  由 `php openapi/scripts/generate.php` 依据 api-v13 的路由与控制器源码生成。 响应统一封装为 `{ok, message, data}`;`ok=false` 时 `message` 为错误信息。
+ *
+ * The version of the OpenAPI document: 1.0.0
+ * Generated by: https://openapi-generator.tech
+ * Generator version: 7.25.0
+ */
+
+/**
+ * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
+ * https://openapi-generator.tech
+ * Do not edit the class manually.
+ */
+
+namespace WikipaliApi\Api;
+
+use GuzzleHttp\Client;
+use GuzzleHttp\ClientInterface;
+use GuzzleHttp\Exception\ConnectException;
+use GuzzleHttp\Exception\RequestException;
+use GuzzleHttp\Psr7\MultipartStream;
+use GuzzleHttp\Psr7\Request;
+use GuzzleHttp\RequestOptions;
+use Psr\Http\Message\RequestInterface;
+use Psr\Http\Message\ResponseInterface;
+use WikipaliApi\ApiException;
+use WikipaliApi\Configuration;
+use WikipaliApi\FormDataProcessor;
+use WikipaliApi\HeaderSelector;
+use WikipaliApi\ObjectSerializer;
+
+/**
+ * MarkupPreviewsApi Class Doc Comment
+ *
+ * @category Class
+ * @package  WikipaliApi
+ * @author   OpenAPI Generator team
+ * @link     https://openapi-generator.tech
+ */
+class MarkupPreviewsApi
+{
+    /**
+     * @var ClientInterface
+     */
+    protected $client;
+
+    /**
+     * @var Configuration
+     */
+    protected $config;
+
+    /**
+     * @var HeaderSelector
+     */
+    protected $headerSelector;
+
+    /**
+     * @var int Host index
+     */
+    protected $hostIndex;
+
+    /** @var string[] $contentTypes **/
+    public const contentTypes = [
+        'postApiV3MarkupPreviews' => [
+            'application/json',
+        ],
+    ];
+
+    /**
+     * @param ClientInterface $client
+     * @param Configuration   $config
+     * @param HeaderSelector  $selector
+     * @param int             $hostIndex (Optional) host index to select the list of hosts if defined in the OpenAPI spec
+     */
+    public function __construct(
+        ?ClientInterface $client = null,
+        ?Configuration $config = null,
+        ?HeaderSelector $selector = null,
+        int $hostIndex = 0
+    ) {
+        $this->client = $client ?: new Client();
+        $this->config = $config ?: Configuration::getDefaultConfiguration();
+        $this->headerSelector = $selector ?: new HeaderSelector();
+        $this->hostIndex = $hostIndex;
+    }
+
+    /**
+     * Set the host index
+     *
+     * @param int $hostIndex Host index (required)
+     */
+    public function setHostIndex($hostIndex): void
+    {
+        $this->hostIndex = $hostIndex;
+    }
+
+    /**
+     * Get the host index
+     *
+     * @return int Host index
+     */
+    public function getHostIndex()
+    {
+        return $this->hostIndex;
+    }
+
+    /**
+     * @return Configuration
+     */
+    public function getConfig()
+    {
+        return $this->config;
+    }
+
+    /**
+     * Operation postApiV3MarkupPreviews
+     *
+     * 预览一段源码
+     *
+     * @param  \WikipaliApi\Model\PostApiV3MarkupPreviewsRequest $post_api_v3_markup_previews_request post_api_v3_markup_previews_request (required)
+     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['postApiV3MarkupPreviews'] to see the possible values for this operation
+     *
+     * @throws \WikipaliApi\ApiException on non-2xx response or if the response body is not in the expected format
+     * @throws \InvalidArgumentException
+     * @return \WikipaliApi\Model\PostApiV3MarkupPreviews200Response|\WikipaliApi\Model\ProblemDetails|\WikipaliApi\Model\ProblemDetails|\WikipaliApi\Model\ProblemDetails|\WikipaliApi\Model\ProblemDetails
+     */
+    public function postApiV3MarkupPreviews($post_api_v3_markup_previews_request, string $contentType = self::contentTypes['postApiV3MarkupPreviews'][0])
+    {
+        list($response) = $this->postApiV3MarkupPreviewsWithHttpInfo($post_api_v3_markup_previews_request, $contentType);
+        return $response;
+    }
+
+    /**
+     * Operation postApiV3MarkupPreviewsWithHttpInfo
+     *
+     * 预览一段源码
+     *
+     * @param  \WikipaliApi\Model\PostApiV3MarkupPreviewsRequest $post_api_v3_markup_previews_request (required)
+     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['postApiV3MarkupPreviews'] to see the possible values for this operation
+     *
+     * @throws \WikipaliApi\ApiException on non-2xx response or if the response body is not in the expected format
+     * @throws \InvalidArgumentException
+     * @return array of \WikipaliApi\Model\PostApiV3MarkupPreviews200Response|\WikipaliApi\Model\ProblemDetails|\WikipaliApi\Model\ProblemDetails|\WikipaliApi\Model\ProblemDetails|\WikipaliApi\Model\ProblemDetails, HTTP status code, HTTP response headers (array of strings)
+     */
+    public function postApiV3MarkupPreviewsWithHttpInfo($post_api_v3_markup_previews_request, string $contentType = self::contentTypes['postApiV3MarkupPreviews'][0])
+    {
+        $request = $this->postApiV3MarkupPreviewsRequest($post_api_v3_markup_previews_request, $contentType);
+
+        try {
+            $options = $this->createHttpClientOption();
+            try {
+                $response = $this->client->send($request, $options);
+            } catch (RequestException $e) {
+                throw new ApiException(
+                    "[{$e->getCode()}] {$e->getMessage()}",
+                    (int) $e->getCode(),
+                    $e->getResponse() ? $e->getResponse()->getHeaders() : null,
+                    $e->getResponse() ? (string) $e->getResponse()->getBody() : null
+                );
+            } catch (ConnectException $e) {
+                throw new ApiException(
+                    "[{$e->getCode()}] {$e->getMessage()}",
+                    (int) $e->getCode(),
+                    null,
+                    null
+                );
+            }
+
+            $statusCode = $response->getStatusCode();
+
+
+            switch($statusCode) {
+                case 200:
+                    return $this->handleResponseWithDataType(
+                        '\WikipaliApi\Model\PostApiV3MarkupPreviews200Response',
+                        $request,
+                        $response,
+                    );
+                case 401:
+                    return $this->handleResponseWithDataType(
+                        '\WikipaliApi\Model\ProblemDetails',
+                        $request,
+                        $response,
+                    );
+                case 403:
+                    return $this->handleResponseWithDataType(
+                        '\WikipaliApi\Model\ProblemDetails',
+                        $request,
+                        $response,
+                    );
+                case 404:
+                    return $this->handleResponseWithDataType(
+                        '\WikipaliApi\Model\ProblemDetails',
+                        $request,
+                        $response,
+                    );
+                case 422:
+                    return $this->handleResponseWithDataType(
+                        '\WikipaliApi\Model\ProblemDetails',
+                        $request,
+                        $response,
+                    );
+            }
+
+            
+
+            if ($statusCode < 200 || $statusCode > 299) {
+                throw new ApiException(
+                    sprintf(
+                        '[%d] Error connecting to the API (%s)',
+                        $statusCode,
+                        (string) $request->getUri()
+                    ),
+                    $statusCode,
+                    $response->getHeaders(),
+                    (string) $response->getBody()
+                );
+            }
+
+            return $this->handleResponseWithDataType(
+                '\WikipaliApi\Model\PostApiV3MarkupPreviews200Response',
+                $request,
+                $response,
+            );
+        } catch (ApiException $e) {
+            switch ($e->getCode()) {
+                case 200:
+                    $data = ObjectSerializer::deserialize(
+                        $e->getResponseBody(),
+                        '\WikipaliApi\Model\PostApiV3MarkupPreviews200Response',
+                        $e->getResponseHeaders()
+                    );
+                    $e->setResponseObject($data);
+                    throw $e;
+                case 401:
+                    $data = ObjectSerializer::deserialize(
+                        $e->getResponseBody(),
+                        '\WikipaliApi\Model\ProblemDetails',
+                        $e->getResponseHeaders()
+                    );
+                    $e->setResponseObject($data);
+                    throw $e;
+                case 403:
+                    $data = ObjectSerializer::deserialize(
+                        $e->getResponseBody(),
+                        '\WikipaliApi\Model\ProblemDetails',
+                        $e->getResponseHeaders()
+                    );
+                    $e->setResponseObject($data);
+                    throw $e;
+                case 404:
+                    $data = ObjectSerializer::deserialize(
+                        $e->getResponseBody(),
+                        '\WikipaliApi\Model\ProblemDetails',
+                        $e->getResponseHeaders()
+                    );
+                    $e->setResponseObject($data);
+                    throw $e;
+                case 422:
+                    $data = ObjectSerializer::deserialize(
+                        $e->getResponseBody(),
+                        '\WikipaliApi\Model\ProblemDetails',
+                        $e->getResponseHeaders()
+                    );
+                    $e->setResponseObject($data);
+                    throw $e;
+            }
+        
+
+            throw $e;
+        }
+    }
+
+    /**
+     * Operation postApiV3MarkupPreviewsAsync
+     *
+     * 预览一段源码
+     *
+     * @param  \WikipaliApi\Model\PostApiV3MarkupPreviewsRequest $post_api_v3_markup_previews_request (required)
+     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['postApiV3MarkupPreviews'] to see the possible values for this operation
+     *
+     * @throws \InvalidArgumentException
+     * @return \GuzzleHttp\Promise\PromiseInterface
+     */
+    public function postApiV3MarkupPreviewsAsync($post_api_v3_markup_previews_request, string $contentType = self::contentTypes['postApiV3MarkupPreviews'][0])
+    {
+        return $this->postApiV3MarkupPreviewsAsyncWithHttpInfo($post_api_v3_markup_previews_request, $contentType)
+            ->then(
+                function ($response) {
+                    return $response[0];
+                }
+            );
+    }
+
+    /**
+     * Operation postApiV3MarkupPreviewsAsyncWithHttpInfo
+     *
+     * 预览一段源码
+     *
+     * @param  \WikipaliApi\Model\PostApiV3MarkupPreviewsRequest $post_api_v3_markup_previews_request (required)
+     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['postApiV3MarkupPreviews'] to see the possible values for this operation
+     *
+     * @throws \InvalidArgumentException
+     * @return \GuzzleHttp\Promise\PromiseInterface
+     */
+    public function postApiV3MarkupPreviewsAsyncWithHttpInfo($post_api_v3_markup_previews_request, string $contentType = self::contentTypes['postApiV3MarkupPreviews'][0])
+    {
+        $returnType = '\WikipaliApi\Model\PostApiV3MarkupPreviews200Response';
+        $request = $this->postApiV3MarkupPreviewsRequest($post_api_v3_markup_previews_request, $contentType);
+
+        return $this->client
+            ->sendAsync($request, $this->createHttpClientOption())
+            ->then(
+                function ($response) use ($returnType) {
+                    if ($returnType === '\SplFileObject') {
+                        $content = $response->getBody(); //stream goes to serializer
+                    } else {
+                        $content = (string) $response->getBody();
+                        if ($returnType !== 'string') {
+                            $content = json_decode($content);
+                        }
+                    }
+
+                    return [
+                        ObjectSerializer::deserialize($content, $returnType, []),
+                        $response->getStatusCode(),
+                        $response->getHeaders()
+                    ];
+                },
+                function ($exception) {
+                    $response = $exception->getResponse();
+                    $statusCode = $response->getStatusCode();
+                    throw new ApiException(
+                        sprintf(
+                            '[%d] Error connecting to the API (%s)',
+                            $statusCode,
+                            $exception->getRequest()->getUri()
+                        ),
+                        $statusCode,
+                        $response->getHeaders(),
+                        (string) $response->getBody()
+                    );
+                }
+            );
+    }
+
+    /**
+     * Create request for operation 'postApiV3MarkupPreviews'
+     *
+     * @param  \WikipaliApi\Model\PostApiV3MarkupPreviewsRequest $post_api_v3_markup_previews_request (required)
+     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['postApiV3MarkupPreviews'] to see the possible values for this operation
+     *
+     * @throws \InvalidArgumentException
+     * @return \GuzzleHttp\Psr7\Request
+     */
+    public function postApiV3MarkupPreviewsRequest($post_api_v3_markup_previews_request, string $contentType = self::contentTypes['postApiV3MarkupPreviews'][0])
+    {
+
+        // verify the required parameter 'post_api_v3_markup_previews_request' is set
+        if ($post_api_v3_markup_previews_request === null || (is_array($post_api_v3_markup_previews_request) && count($post_api_v3_markup_previews_request) === 0)) {
+            throw new \InvalidArgumentException(
+                'Missing the required parameter $post_api_v3_markup_previews_request when calling postApiV3MarkupPreviews'
+            );
+        }
+
+
+        $resourcePath = '/v3/markup-previews';
+        $formParams = [];
+        $queryParams = [];
+        $headerParams = [];
+        $httpBody = '';
+        $multipart = false;
+
+
+
+
+
+        $headers = $this->headerSelector->selectHeaders(
+            ['application/json', 'application/problem+json', ],
+            $contentType,
+            $multipart
+        );
+
+        // for model (json/xml)
+        if (isset($post_api_v3_markup_previews_request)) {
+            if (stripos($headers['Content-Type'], 'application/json') !== false) {
+                # if Content-Type contains "application/json", json_encode the body
+                try {
+                    $httpBody = json_encode(ObjectSerializer::sanitizeForSerialization($post_api_v3_markup_previews_request), JSON_THROW_ON_ERROR);
+                } catch (\JsonException $e) {
+                    throw new \InvalidArgumentException('json_encode error: ' . $e->getMessage(), 0, $e);
+                }
+            } else {
+                $httpBody = $post_api_v3_markup_previews_request;
+            }
+        } elseif (count($formParams) > 0) {
+            if ($multipart) {
+                $multipartContents = [];
+                foreach ($formParams as $formParamName => $formParamValue) {
+                    $formParamValueItems = is_array($formParamValue) ? $formParamValue : [$formParamValue];
+                    foreach ($formParamValueItems as $formParamValueItem) {
+                        $multipartContents[] = [
+                            'name' => $formParamName,
+                            'contents' => $formParamValueItem
+                        ];
+                    }
+                }
+                // for HTTP post (form)
+                $httpBody = new MultipartStream($multipartContents);
+
+            } elseif (stripos($headers['Content-Type'], 'application/json') !== false) {
+                # if Content-Type contains "application/json", json_encode the form parameters
+                try {
+                    $httpBody = json_encode($formParams, JSON_THROW_ON_ERROR);
+                } catch (\JsonException $e) {
+                    throw new \InvalidArgumentException('json_encode error: ' . $e->getMessage(), 0, $e);
+                }
+            } else {
+                // for HTTP post (form)
+                $httpBody = ObjectSerializer::buildQuery($formParams);
+            }
+        }
+
+        // this endpoint requires Bearer authentication (access token)
+        if (!empty($this->config->getAccessToken())) {
+            $headers['Authorization'] = 'Bearer ' . $this->config->getAccessToken();
+        }
+
+        $defaultHeaders = [];
+        if ($this->config->getUserAgent()) {
+            $defaultHeaders['User-Agent'] = $this->config->getUserAgent();
+        }
+
+        $headers = array_merge(
+            $defaultHeaders,
+            $headerParams,
+            $headers
+        );
+
+        $operationHost = $this->config->getHost();
+        $query = ObjectSerializer::buildQuery($queryParams);
+        return new Request(
+            'POST',
+            $operationHost . $resourcePath . ($query ? "?{$query}" : ''),
+            $headers,
+            $httpBody
+        );
+    }
+
+    /**
+     * Create http client option
+     *
+     * @throws \RuntimeException on file opening failure
+     * @return array of http client options
+     */
+    protected function createHttpClientOption()
+    {
+        $options = [];
+        if ($this->config->getDebug()) {
+            $options[RequestOptions::DEBUG] = fopen($this->config->getDebugFile(), 'a');
+            if (!$options[RequestOptions::DEBUG]) {
+                throw new \RuntimeException('Failed to open the debug file: ' . $this->config->getDebugFile());
+            }
+        }
+
+        if ($this->config->getCertFile()) {
+            $options[RequestOptions::CERT] = $this->config->getCertFile();
+        }
+
+        if ($this->config->getKeyFile()) {
+            $options[RequestOptions::SSL_KEY] = $this->config->getKeyFile();
+        }
+
+        return $options;
+    }
+
+    private function handleResponseWithDataType(
+        string $dataType,
+        RequestInterface $request,
+        ResponseInterface $response
+    ): array {
+        if ($dataType === '\SplFileObject') {
+            $content = $response->getBody(); //stream goes to serializer
+        } else {
+            $content = (string) $response->getBody();
+            if ($dataType !== 'string') {
+                try {
+                    $content = json_decode($content, false, 512, JSON_THROW_ON_ERROR);
+                } catch (\JsonException $exception) {
+                    throw new ApiException(
+                        sprintf(
+                            'Error JSON decoding server response (%s)',
+                            $request->getUri()
+                        ),
+                        $response->getStatusCode(),
+                        $response->getHeaders(),
+                        $content
+                    );
+                }
+            }
+        }
+
+        return [
+            ObjectSerializer::deserialize($content, $dataType, []),
+            $response->getStatusCode(),
+            $response->getHeaders()
+        ];
+    }
+
+    private function responseWithinRangeCode(
+        string $rangeCode,
+        int $statusCode
+    ): bool {
+        $left = (int) ($rangeCode[0].'00');
+        $right = (int) ($rangeCode[0].'99');
+
+        return $statusCode >= $left && $statusCode <= $right;
+    }
+}

+ 1188 - 0
api-test/client/lib/Api/TipitakaExportsApi.php

@@ -0,0 +1,1188 @@
+<?php
+/**
+ * TipitakaExportsApi
+ * PHP version 8.1
+ *
+ * @category Class
+ * @package  WikipaliApi
+ * @author   OpenAPI Generator team
+ * @link     https://openapi-generator.tech
+ */
+
+/**
+ * MINT API
+ *
+ * International Academy Of Pali Tipitaka(国际巴利三藏学院)  由 `php openapi/scripts/generate.php` 依据 api-v13 的路由与控制器源码生成。 响应统一封装为 `{ok, message, data}`;`ok=false` 时 `message` 为错误信息。
+ *
+ * The version of the OpenAPI document: 1.0.0
+ * Generated by: https://openapi-generator.tech
+ * Generator version: 7.25.0
+ */
+
+/**
+ * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
+ * https://openapi-generator.tech
+ * Do not edit the class manually.
+ */
+
+namespace WikipaliApi\Api;
+
+use GuzzleHttp\Client;
+use GuzzleHttp\ClientInterface;
+use GuzzleHttp\Exception\ConnectException;
+use GuzzleHttp\Exception\RequestException;
+use GuzzleHttp\Psr7\MultipartStream;
+use GuzzleHttp\Psr7\Request;
+use GuzzleHttp\RequestOptions;
+use Psr\Http\Message\RequestInterface;
+use Psr\Http\Message\ResponseInterface;
+use WikipaliApi\ApiException;
+use WikipaliApi\Configuration;
+use WikipaliApi\FormDataProcessor;
+use WikipaliApi\HeaderSelector;
+use WikipaliApi\ObjectSerializer;
+
+/**
+ * TipitakaExportsApi Class Doc Comment
+ *
+ * @category Class
+ * @package  WikipaliApi
+ * @author   OpenAPI Generator team
+ * @link     https://openapi-generator.tech
+ */
+class TipitakaExportsApi
+{
+    /**
+     * @var ClientInterface
+     */
+    protected $client;
+
+    /**
+     * @var Configuration
+     */
+    protected $config;
+
+    /**
+     * @var HeaderSelector
+     */
+    protected $headerSelector;
+
+    /**
+     * @var int Host index
+     */
+    protected $hostIndex;
+
+    /** @var string[] $contentTypes **/
+    public const contentTypes = [
+        'getApiV3TipitakaExportsExport' => [
+            'application/json',
+        ],
+        'getApiV3TipitakaExportsExportFile' => [
+            'application/json',
+        ],
+        'postApiV3TipitakaExports' => [
+            'application/json',
+        ],
+    ];
+
+    /**
+     * @param ClientInterface $client
+     * @param Configuration   $config
+     * @param HeaderSelector  $selector
+     * @param int             $hostIndex (Optional) host index to select the list of hosts if defined in the OpenAPI spec
+     */
+    public function __construct(
+        ?ClientInterface $client = null,
+        ?Configuration $config = null,
+        ?HeaderSelector $selector = null,
+        int $hostIndex = 0
+    ) {
+        $this->client = $client ?: new Client();
+        $this->config = $config ?: Configuration::getDefaultConfiguration();
+        $this->headerSelector = $selector ?: new HeaderSelector();
+        $this->hostIndex = $hostIndex;
+    }
+
+    /**
+     * Set the host index
+     *
+     * @param int $hostIndex Host index (required)
+     */
+    public function setHostIndex($hostIndex): void
+    {
+        $this->hostIndex = $hostIndex;
+    }
+
+    /**
+     * Get the host index
+     *
+     * @return int Host index
+     */
+    public function getHostIndex()
+    {
+        return $this->hostIndex;
+    }
+
+    /**
+     * @return Configuration
+     */
+    public function getConfig()
+    {
+        return $this->config;
+    }
+
+    /**
+     * Operation getApiV3TipitakaExportsExport
+     *
+     * 查看下载状态
+     *
+     * @param  string $export 导出 id(POST 返回的 id) (required)
+     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['getApiV3TipitakaExportsExport'] to see the possible values for this operation
+     *
+     * @throws \WikipaliApi\ApiException on non-2xx response or if the response body is not in the expected format
+     * @throws \InvalidArgumentException
+     * @return \WikipaliApi\Model\PostApiV3TipitakaExports200Response|\WikipaliApi\Model\ProblemDetails
+     */
+    public function getApiV3TipitakaExportsExport($export, string $contentType = self::contentTypes['getApiV3TipitakaExportsExport'][0])
+    {
+        list($response) = $this->getApiV3TipitakaExportsExportWithHttpInfo($export, $contentType);
+        return $response;
+    }
+
+    /**
+     * Operation getApiV3TipitakaExportsExportWithHttpInfo
+     *
+     * 查看下载状态
+     *
+     * @param  string $export 导出 id(POST 返回的 id) (required)
+     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['getApiV3TipitakaExportsExport'] to see the possible values for this operation
+     *
+     * @throws \WikipaliApi\ApiException on non-2xx response or if the response body is not in the expected format
+     * @throws \InvalidArgumentException
+     * @return array of \WikipaliApi\Model\PostApiV3TipitakaExports200Response|\WikipaliApi\Model\ProblemDetails, HTTP status code, HTTP response headers (array of strings)
+     */
+    public function getApiV3TipitakaExportsExportWithHttpInfo($export, string $contentType = self::contentTypes['getApiV3TipitakaExportsExport'][0])
+    {
+        $request = $this->getApiV3TipitakaExportsExportRequest($export, $contentType);
+
+        try {
+            $options = $this->createHttpClientOption();
+            try {
+                $response = $this->client->send($request, $options);
+            } catch (RequestException $e) {
+                throw new ApiException(
+                    "[{$e->getCode()}] {$e->getMessage()}",
+                    (int) $e->getCode(),
+                    $e->getResponse() ? $e->getResponse()->getHeaders() : null,
+                    $e->getResponse() ? (string) $e->getResponse()->getBody() : null
+                );
+            } catch (ConnectException $e) {
+                throw new ApiException(
+                    "[{$e->getCode()}] {$e->getMessage()}",
+                    (int) $e->getCode(),
+                    null,
+                    null
+                );
+            }
+
+            $statusCode = $response->getStatusCode();
+
+
+            switch($statusCode) {
+                case 200:
+                    return $this->handleResponseWithDataType(
+                        '\WikipaliApi\Model\PostApiV3TipitakaExports200Response',
+                        $request,
+                        $response,
+                    );
+                case 422:
+                    return $this->handleResponseWithDataType(
+                        '\WikipaliApi\Model\ProblemDetails',
+                        $request,
+                        $response,
+                    );
+            }
+
+            
+
+            if ($statusCode < 200 || $statusCode > 299) {
+                throw new ApiException(
+                    sprintf(
+                        '[%d] Error connecting to the API (%s)',
+                        $statusCode,
+                        (string) $request->getUri()
+                    ),
+                    $statusCode,
+                    $response->getHeaders(),
+                    (string) $response->getBody()
+                );
+            }
+
+            return $this->handleResponseWithDataType(
+                '\WikipaliApi\Model\PostApiV3TipitakaExports200Response',
+                $request,
+                $response,
+            );
+        } catch (ApiException $e) {
+            switch ($e->getCode()) {
+                case 200:
+                    $data = ObjectSerializer::deserialize(
+                        $e->getResponseBody(),
+                        '\WikipaliApi\Model\PostApiV3TipitakaExports200Response',
+                        $e->getResponseHeaders()
+                    );
+                    $e->setResponseObject($data);
+                    throw $e;
+                case 422:
+                    $data = ObjectSerializer::deserialize(
+                        $e->getResponseBody(),
+                        '\WikipaliApi\Model\ProblemDetails',
+                        $e->getResponseHeaders()
+                    );
+                    $e->setResponseObject($data);
+                    throw $e;
+            }
+        
+
+            throw $e;
+        }
+    }
+
+    /**
+     * Operation getApiV3TipitakaExportsExportAsync
+     *
+     * 查看下载状态
+     *
+     * @param  string $export 导出 id(POST 返回的 id) (required)
+     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['getApiV3TipitakaExportsExport'] to see the possible values for this operation
+     *
+     * @throws \InvalidArgumentException
+     * @return \GuzzleHttp\Promise\PromiseInterface
+     */
+    public function getApiV3TipitakaExportsExportAsync($export, string $contentType = self::contentTypes['getApiV3TipitakaExportsExport'][0])
+    {
+        return $this->getApiV3TipitakaExportsExportAsyncWithHttpInfo($export, $contentType)
+            ->then(
+                function ($response) {
+                    return $response[0];
+                }
+            );
+    }
+
+    /**
+     * Operation getApiV3TipitakaExportsExportAsyncWithHttpInfo
+     *
+     * 查看下载状态
+     *
+     * @param  string $export 导出 id(POST 返回的 id) (required)
+     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['getApiV3TipitakaExportsExport'] to see the possible values for this operation
+     *
+     * @throws \InvalidArgumentException
+     * @return \GuzzleHttp\Promise\PromiseInterface
+     */
+    public function getApiV3TipitakaExportsExportAsyncWithHttpInfo($export, string $contentType = self::contentTypes['getApiV3TipitakaExportsExport'][0])
+    {
+        $returnType = '\WikipaliApi\Model\PostApiV3TipitakaExports200Response';
+        $request = $this->getApiV3TipitakaExportsExportRequest($export, $contentType);
+
+        return $this->client
+            ->sendAsync($request, $this->createHttpClientOption())
+            ->then(
+                function ($response) use ($returnType) {
+                    if ($returnType === '\SplFileObject') {
+                        $content = $response->getBody(); //stream goes to serializer
+                    } else {
+                        $content = (string) $response->getBody();
+                        if ($returnType !== 'string') {
+                            $content = json_decode($content);
+                        }
+                    }
+
+                    return [
+                        ObjectSerializer::deserialize($content, $returnType, []),
+                        $response->getStatusCode(),
+                        $response->getHeaders()
+                    ];
+                },
+                function ($exception) {
+                    $response = $exception->getResponse();
+                    $statusCode = $response->getStatusCode();
+                    throw new ApiException(
+                        sprintf(
+                            '[%d] Error connecting to the API (%s)',
+                            $statusCode,
+                            $exception->getRequest()->getUri()
+                        ),
+                        $statusCode,
+                        $response->getHeaders(),
+                        (string) $response->getBody()
+                    );
+                }
+            );
+    }
+
+    /**
+     * Create request for operation 'getApiV3TipitakaExportsExport'
+     *
+     * @param  string $export 导出 id(POST 返回的 id) (required)
+     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['getApiV3TipitakaExportsExport'] to see the possible values for this operation
+     *
+     * @throws \InvalidArgumentException
+     * @return \GuzzleHttp\Psr7\Request
+     */
+    public function getApiV3TipitakaExportsExportRequest($export, string $contentType = self::contentTypes['getApiV3TipitakaExportsExport'][0])
+    {
+
+        // verify the required parameter 'export' is set
+        if ($export === null || (is_array($export) && count($export) === 0)) {
+            throw new \InvalidArgumentException(
+                'Missing the required parameter $export when calling getApiV3TipitakaExportsExport'
+            );
+        }
+
+
+        $resourcePath = '/v3/tipitaka-exports/{export}';
+        $formParams = [];
+        $queryParams = [];
+        $headerParams = [];
+        $httpBody = '';
+        $multipart = false;
+
+
+
+        // path params
+        if ($export !== null) {
+            $resourcePath = str_replace(
+                '{export}',
+                ObjectSerializer::toPathValue($export),
+                $resourcePath
+            );
+        }
+
+
+        $headers = $this->headerSelector->selectHeaders(
+            ['application/json', 'application/problem+json', ],
+            $contentType,
+            $multipart
+        );
+
+        // for model (json/xml)
+        if (count($formParams) > 0) {
+            if ($multipart) {
+                $multipartContents = [];
+                foreach ($formParams as $formParamName => $formParamValue) {
+                    $formParamValueItems = is_array($formParamValue) ? $formParamValue : [$formParamValue];
+                    foreach ($formParamValueItems as $formParamValueItem) {
+                        $multipartContents[] = [
+                            'name' => $formParamName,
+                            'contents' => $formParamValueItem
+                        ];
+                    }
+                }
+                // for HTTP post (form)
+                $httpBody = new MultipartStream($multipartContents);
+
+            } elseif (stripos($headers['Content-Type'], 'application/json') !== false) {
+                # if Content-Type contains "application/json", json_encode the form parameters
+                try {
+                    $httpBody = json_encode($formParams, JSON_THROW_ON_ERROR);
+                } catch (\JsonException $e) {
+                    throw new \InvalidArgumentException('json_encode error: ' . $e->getMessage(), 0, $e);
+                }
+            } else {
+                // for HTTP post (form)
+                $httpBody = ObjectSerializer::buildQuery($formParams);
+            }
+        }
+
+        // this endpoint requires Bearer authentication (access token)
+        if (!empty($this->config->getAccessToken())) {
+            $headers['Authorization'] = 'Bearer ' . $this->config->getAccessToken();
+        }
+
+        $defaultHeaders = [];
+        if ($this->config->getUserAgent()) {
+            $defaultHeaders['User-Agent'] = $this->config->getUserAgent();
+        }
+
+        $headers = array_merge(
+            $defaultHeaders,
+            $headerParams,
+            $headers
+        );
+
+        $operationHost = $this->config->getHost();
+        $query = ObjectSerializer::buildQuery($queryParams);
+        return new Request(
+            'GET',
+            $operationHost . $resourcePath . ($query ? "?{$query}" : ''),
+            $headers,
+            $httpBody
+        );
+    }
+
+    /**
+     * Operation getApiV3TipitakaExportsExportFile
+     *
+     * 下载文件
+     *
+     * @param  string $export 导出 id (required)
+     * @param  int $expires 签名的过期时间(download_url 里自带) (required)
+     * @param  string $signature 签名(download_url 里自带) (required)
+     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['getApiV3TipitakaExportsExportFile'] to see the possible values for this operation
+     *
+     * @throws \WikipaliApi\ApiException on non-2xx response or if the response body is not in the expected format
+     * @throws \InvalidArgumentException
+     * @return \SplFileObject|\SplFileObject|\WikipaliApi\Model\ProblemDetails|\WikipaliApi\Model\ProblemDetails|\WikipaliApi\Model\ProblemDetails|\WikipaliApi\Model\ProblemDetails
+     */
+    public function getApiV3TipitakaExportsExportFile($export, $expires, $signature, string $contentType = self::contentTypes['getApiV3TipitakaExportsExportFile'][0])
+    {
+        list($response) = $this->getApiV3TipitakaExportsExportFileWithHttpInfo($export, $expires, $signature, $contentType);
+        return $response;
+    }
+
+    /**
+     * Operation getApiV3TipitakaExportsExportFileWithHttpInfo
+     *
+     * 下载文件
+     *
+     * @param  string $export 导出 id (required)
+     * @param  int $expires 签名的过期时间(download_url 里自带) (required)
+     * @param  string $signature 签名(download_url 里自带) (required)
+     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['getApiV3TipitakaExportsExportFile'] to see the possible values for this operation
+     *
+     * @throws \WikipaliApi\ApiException on non-2xx response or if the response body is not in the expected format
+     * @throws \InvalidArgumentException
+     * @return array of \SplFileObject|\SplFileObject|\WikipaliApi\Model\ProblemDetails|\WikipaliApi\Model\ProblemDetails|\WikipaliApi\Model\ProblemDetails|\WikipaliApi\Model\ProblemDetails, HTTP status code, HTTP response headers (array of strings)
+     */
+    public function getApiV3TipitakaExportsExportFileWithHttpInfo($export, $expires, $signature, string $contentType = self::contentTypes['getApiV3TipitakaExportsExportFile'][0])
+    {
+        $request = $this->getApiV3TipitakaExportsExportFileRequest($export, $expires, $signature, $contentType);
+
+        try {
+            $options = $this->createHttpClientOption();
+            try {
+                $response = $this->client->send($request, $options);
+            } catch (RequestException $e) {
+                throw new ApiException(
+                    "[{$e->getCode()}] {$e->getMessage()}",
+                    (int) $e->getCode(),
+                    $e->getResponse() ? $e->getResponse()->getHeaders() : null,
+                    $e->getResponse() ? (string) $e->getResponse()->getBody() : null
+                );
+            } catch (ConnectException $e) {
+                throw new ApiException(
+                    "[{$e->getCode()}] {$e->getMessage()}",
+                    (int) $e->getCode(),
+                    null,
+                    null
+                );
+            }
+
+            $statusCode = $response->getStatusCode();
+
+
+            switch($statusCode) {
+                case 200:
+                    return $this->handleResponseWithDataType(
+                        '\SplFileObject',
+                        $request,
+                        $response,
+                    );
+                case 206:
+                    return $this->handleResponseWithDataType(
+                        '\SplFileObject',
+                        $request,
+                        $response,
+                    );
+                case 403:
+                    return $this->handleResponseWithDataType(
+                        '\WikipaliApi\Model\ProblemDetails',
+                        $request,
+                        $response,
+                    );
+                case 404:
+                    return $this->handleResponseWithDataType(
+                        '\WikipaliApi\Model\ProblemDetails',
+                        $request,
+                        $response,
+                    );
+                case 416:
+                    return $this->handleResponseWithDataType(
+                        '\WikipaliApi\Model\ProblemDetails',
+                        $request,
+                        $response,
+                    );
+                case 422:
+                    return $this->handleResponseWithDataType(
+                        '\WikipaliApi\Model\ProblemDetails',
+                        $request,
+                        $response,
+                    );
+            }
+
+            
+
+            if ($statusCode < 200 || $statusCode > 299) {
+                throw new ApiException(
+                    sprintf(
+                        '[%d] Error connecting to the API (%s)',
+                        $statusCode,
+                        (string) $request->getUri()
+                    ),
+                    $statusCode,
+                    $response->getHeaders(),
+                    (string) $response->getBody()
+                );
+            }
+
+            return $this->handleResponseWithDataType(
+                '\SplFileObject',
+                $request,
+                $response,
+            );
+        } catch (ApiException $e) {
+            switch ($e->getCode()) {
+                case 200:
+                    $data = ObjectSerializer::deserialize(
+                        $e->getResponseBody(),
+                        '\SplFileObject',
+                        $e->getResponseHeaders()
+                    );
+                    $e->setResponseObject($data);
+                    throw $e;
+                case 206:
+                    $data = ObjectSerializer::deserialize(
+                        $e->getResponseBody(),
+                        '\SplFileObject',
+                        $e->getResponseHeaders()
+                    );
+                    $e->setResponseObject($data);
+                    throw $e;
+                case 403:
+                    $data = ObjectSerializer::deserialize(
+                        $e->getResponseBody(),
+                        '\WikipaliApi\Model\ProblemDetails',
+                        $e->getResponseHeaders()
+                    );
+                    $e->setResponseObject($data);
+                    throw $e;
+                case 404:
+                    $data = ObjectSerializer::deserialize(
+                        $e->getResponseBody(),
+                        '\WikipaliApi\Model\ProblemDetails',
+                        $e->getResponseHeaders()
+                    );
+                    $e->setResponseObject($data);
+                    throw $e;
+                case 416:
+                    $data = ObjectSerializer::deserialize(
+                        $e->getResponseBody(),
+                        '\WikipaliApi\Model\ProblemDetails',
+                        $e->getResponseHeaders()
+                    );
+                    $e->setResponseObject($data);
+                    throw $e;
+                case 422:
+                    $data = ObjectSerializer::deserialize(
+                        $e->getResponseBody(),
+                        '\WikipaliApi\Model\ProblemDetails',
+                        $e->getResponseHeaders()
+                    );
+                    $e->setResponseObject($data);
+                    throw $e;
+            }
+        
+
+            throw $e;
+        }
+    }
+
+    /**
+     * Operation getApiV3TipitakaExportsExportFileAsync
+     *
+     * 下载文件
+     *
+     * @param  string $export 导出 id (required)
+     * @param  int $expires 签名的过期时间(download_url 里自带) (required)
+     * @param  string $signature 签名(download_url 里自带) (required)
+     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['getApiV3TipitakaExportsExportFile'] to see the possible values for this operation
+     *
+     * @throws \InvalidArgumentException
+     * @return \GuzzleHttp\Promise\PromiseInterface
+     */
+    public function getApiV3TipitakaExportsExportFileAsync($export, $expires, $signature, string $contentType = self::contentTypes['getApiV3TipitakaExportsExportFile'][0])
+    {
+        return $this->getApiV3TipitakaExportsExportFileAsyncWithHttpInfo($export, $expires, $signature, $contentType)
+            ->then(
+                function ($response) {
+                    return $response[0];
+                }
+            );
+    }
+
+    /**
+     * Operation getApiV3TipitakaExportsExportFileAsyncWithHttpInfo
+     *
+     * 下载文件
+     *
+     * @param  string $export 导出 id (required)
+     * @param  int $expires 签名的过期时间(download_url 里自带) (required)
+     * @param  string $signature 签名(download_url 里自带) (required)
+     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['getApiV3TipitakaExportsExportFile'] to see the possible values for this operation
+     *
+     * @throws \InvalidArgumentException
+     * @return \GuzzleHttp\Promise\PromiseInterface
+     */
+    public function getApiV3TipitakaExportsExportFileAsyncWithHttpInfo($export, $expires, $signature, string $contentType = self::contentTypes['getApiV3TipitakaExportsExportFile'][0])
+    {
+        $returnType = '\SplFileObject';
+        $request = $this->getApiV3TipitakaExportsExportFileRequest($export, $expires, $signature, $contentType);
+
+        return $this->client
+            ->sendAsync($request, $this->createHttpClientOption())
+            ->then(
+                function ($response) use ($returnType) {
+                    if ($returnType === '\SplFileObject') {
+                        $content = $response->getBody(); //stream goes to serializer
+                    } else {
+                        $content = (string) $response->getBody();
+                        if ($returnType !== 'string') {
+                            $content = json_decode($content);
+                        }
+                    }
+
+                    return [
+                        ObjectSerializer::deserialize($content, $returnType, []),
+                        $response->getStatusCode(),
+                        $response->getHeaders()
+                    ];
+                },
+                function ($exception) {
+                    $response = $exception->getResponse();
+                    $statusCode = $response->getStatusCode();
+                    throw new ApiException(
+                        sprintf(
+                            '[%d] Error connecting to the API (%s)',
+                            $statusCode,
+                            $exception->getRequest()->getUri()
+                        ),
+                        $statusCode,
+                        $response->getHeaders(),
+                        (string) $response->getBody()
+                    );
+                }
+            );
+    }
+
+    /**
+     * Create request for operation 'getApiV3TipitakaExportsExportFile'
+     *
+     * @param  string $export 导出 id (required)
+     * @param  int $expires 签名的过期时间(download_url 里自带) (required)
+     * @param  string $signature 签名(download_url 里自带) (required)
+     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['getApiV3TipitakaExportsExportFile'] to see the possible values for this operation
+     *
+     * @throws \InvalidArgumentException
+     * @return \GuzzleHttp\Psr7\Request
+     */
+    public function getApiV3TipitakaExportsExportFileRequest($export, $expires, $signature, string $contentType = self::contentTypes['getApiV3TipitakaExportsExportFile'][0])
+    {
+
+        // verify the required parameter 'export' is set
+        if ($export === null || (is_array($export) && count($export) === 0)) {
+            throw new \InvalidArgumentException(
+                'Missing the required parameter $export when calling getApiV3TipitakaExportsExportFile'
+            );
+        }
+
+        // verify the required parameter 'expires' is set
+        if ($expires === null || (is_array($expires) && count($expires) === 0)) {
+            throw new \InvalidArgumentException(
+                'Missing the required parameter $expires when calling getApiV3TipitakaExportsExportFile'
+            );
+        }
+
+        // verify the required parameter 'signature' is set
+        if ($signature === null || (is_array($signature) && count($signature) === 0)) {
+            throw new \InvalidArgumentException(
+                'Missing the required parameter $signature when calling getApiV3TipitakaExportsExportFile'
+            );
+        }
+
+
+        $resourcePath = '/v3/tipitaka-exports/{export}/file';
+        $formParams = [];
+        $queryParams = [];
+        $headerParams = [];
+        $httpBody = '';
+        $multipart = false;
+
+        // query params
+        $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue(
+            $expires,
+            'expires', // param base name
+            'integer', // openApiType
+            'form', // style
+            true, // explode
+            true // required
+        ) ?? []);
+        // query params
+        $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue(
+            $signature,
+            'signature', // param base name
+            'string', // openApiType
+            'form', // style
+            true, // explode
+            true // required
+        ) ?? []);
+
+
+        // path params
+        if ($export !== null) {
+            $resourcePath = str_replace(
+                '{export}',
+                ObjectSerializer::toPathValue($export),
+                $resourcePath
+            );
+        }
+
+
+        $headers = $this->headerSelector->selectHeaders(
+            ['application/zip', 'application/epub+zip', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'application/x-ndjson', 'application/problem+json', ],
+            $contentType,
+            $multipart
+        );
+
+        // for model (json/xml)
+        if (count($formParams) > 0) {
+            if ($multipart) {
+                $multipartContents = [];
+                foreach ($formParams as $formParamName => $formParamValue) {
+                    $formParamValueItems = is_array($formParamValue) ? $formParamValue : [$formParamValue];
+                    foreach ($formParamValueItems as $formParamValueItem) {
+                        $multipartContents[] = [
+                            'name' => $formParamName,
+                            'contents' => $formParamValueItem
+                        ];
+                    }
+                }
+                // for HTTP post (form)
+                $httpBody = new MultipartStream($multipartContents);
+
+            } elseif (stripos($headers['Content-Type'], 'application/json') !== false) {
+                # if Content-Type contains "application/json", json_encode the form parameters
+                try {
+                    $httpBody = json_encode($formParams, JSON_THROW_ON_ERROR);
+                } catch (\JsonException $e) {
+                    throw new \InvalidArgumentException('json_encode error: ' . $e->getMessage(), 0, $e);
+                }
+            } else {
+                // for HTTP post (form)
+                $httpBody = ObjectSerializer::buildQuery($formParams);
+            }
+        }
+
+        // this endpoint requires Bearer authentication (access token)
+        if (!empty($this->config->getAccessToken())) {
+            $headers['Authorization'] = 'Bearer ' . $this->config->getAccessToken();
+        }
+
+        $defaultHeaders = [];
+        if ($this->config->getUserAgent()) {
+            $defaultHeaders['User-Agent'] = $this->config->getUserAgent();
+        }
+
+        $headers = array_merge(
+            $defaultHeaders,
+            $headerParams,
+            $headers
+        );
+
+        $operationHost = $this->config->getHost();
+        $query = ObjectSerializer::buildQuery($queryParams);
+        return new Request(
+            'GET',
+            $operationHost . $resourcePath . ($query ? "?{$query}" : ''),
+            $headers,
+            $httpBody
+        );
+    }
+
+    /**
+     * Operation postApiV3TipitakaExports
+     *
+     * 发起下载
+     *
+     * @param  \WikipaliApi\Model\PostApiV3TipitakaExportsRequest $post_api_v3_tipitaka_exports_request post_api_v3_tipitaka_exports_request (required)
+     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['postApiV3TipitakaExports'] to see the possible values for this operation
+     *
+     * @throws \WikipaliApi\ApiException on non-2xx response or if the response body is not in the expected format
+     * @throws \InvalidArgumentException
+     * @return \WikipaliApi\Model\PostApiV3TipitakaExports200Response|\WikipaliApi\Model\PostApiV3TipitakaExports200Response|\WikipaliApi\Model\ProblemDetails
+     */
+    public function postApiV3TipitakaExports($post_api_v3_tipitaka_exports_request, string $contentType = self::contentTypes['postApiV3TipitakaExports'][0])
+    {
+        list($response) = $this->postApiV3TipitakaExportsWithHttpInfo($post_api_v3_tipitaka_exports_request, $contentType);
+        return $response;
+    }
+
+    /**
+     * Operation postApiV3TipitakaExportsWithHttpInfo
+     *
+     * 发起下载
+     *
+     * @param  \WikipaliApi\Model\PostApiV3TipitakaExportsRequest $post_api_v3_tipitaka_exports_request (required)
+     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['postApiV3TipitakaExports'] to see the possible values for this operation
+     *
+     * @throws \WikipaliApi\ApiException on non-2xx response or if the response body is not in the expected format
+     * @throws \InvalidArgumentException
+     * @return array of \WikipaliApi\Model\PostApiV3TipitakaExports200Response|\WikipaliApi\Model\PostApiV3TipitakaExports200Response|\WikipaliApi\Model\ProblemDetails, HTTP status code, HTTP response headers (array of strings)
+     */
+    public function postApiV3TipitakaExportsWithHttpInfo($post_api_v3_tipitaka_exports_request, string $contentType = self::contentTypes['postApiV3TipitakaExports'][0])
+    {
+        $request = $this->postApiV3TipitakaExportsRequest($post_api_v3_tipitaka_exports_request, $contentType);
+
+        try {
+            $options = $this->createHttpClientOption();
+            try {
+                $response = $this->client->send($request, $options);
+            } catch (RequestException $e) {
+                throw new ApiException(
+                    "[{$e->getCode()}] {$e->getMessage()}",
+                    (int) $e->getCode(),
+                    $e->getResponse() ? $e->getResponse()->getHeaders() : null,
+                    $e->getResponse() ? (string) $e->getResponse()->getBody() : null
+                );
+            } catch (ConnectException $e) {
+                throw new ApiException(
+                    "[{$e->getCode()}] {$e->getMessage()}",
+                    (int) $e->getCode(),
+                    null,
+                    null
+                );
+            }
+
+            $statusCode = $response->getStatusCode();
+
+
+            switch($statusCode) {
+                case 200:
+                    return $this->handleResponseWithDataType(
+                        '\WikipaliApi\Model\PostApiV3TipitakaExports200Response',
+                        $request,
+                        $response,
+                    );
+                case 202:
+                    return $this->handleResponseWithDataType(
+                        '\WikipaliApi\Model\PostApiV3TipitakaExports200Response',
+                        $request,
+                        $response,
+                    );
+                case 422:
+                    return $this->handleResponseWithDataType(
+                        '\WikipaliApi\Model\ProblemDetails',
+                        $request,
+                        $response,
+                    );
+            }
+
+            
+
+            if ($statusCode < 200 || $statusCode > 299) {
+                throw new ApiException(
+                    sprintf(
+                        '[%d] Error connecting to the API (%s)',
+                        $statusCode,
+                        (string) $request->getUri()
+                    ),
+                    $statusCode,
+                    $response->getHeaders(),
+                    (string) $response->getBody()
+                );
+            }
+
+            return $this->handleResponseWithDataType(
+                '\WikipaliApi\Model\PostApiV3TipitakaExports200Response',
+                $request,
+                $response,
+            );
+        } catch (ApiException $e) {
+            switch ($e->getCode()) {
+                case 200:
+                    $data = ObjectSerializer::deserialize(
+                        $e->getResponseBody(),
+                        '\WikipaliApi\Model\PostApiV3TipitakaExports200Response',
+                        $e->getResponseHeaders()
+                    );
+                    $e->setResponseObject($data);
+                    throw $e;
+                case 202:
+                    $data = ObjectSerializer::deserialize(
+                        $e->getResponseBody(),
+                        '\WikipaliApi\Model\PostApiV3TipitakaExports200Response',
+                        $e->getResponseHeaders()
+                    );
+                    $e->setResponseObject($data);
+                    throw $e;
+                case 422:
+                    $data = ObjectSerializer::deserialize(
+                        $e->getResponseBody(),
+                        '\WikipaliApi\Model\ProblemDetails',
+                        $e->getResponseHeaders()
+                    );
+                    $e->setResponseObject($data);
+                    throw $e;
+            }
+        
+
+            throw $e;
+        }
+    }
+
+    /**
+     * Operation postApiV3TipitakaExportsAsync
+     *
+     * 发起下载
+     *
+     * @param  \WikipaliApi\Model\PostApiV3TipitakaExportsRequest $post_api_v3_tipitaka_exports_request (required)
+     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['postApiV3TipitakaExports'] to see the possible values for this operation
+     *
+     * @throws \InvalidArgumentException
+     * @return \GuzzleHttp\Promise\PromiseInterface
+     */
+    public function postApiV3TipitakaExportsAsync($post_api_v3_tipitaka_exports_request, string $contentType = self::contentTypes['postApiV3TipitakaExports'][0])
+    {
+        return $this->postApiV3TipitakaExportsAsyncWithHttpInfo($post_api_v3_tipitaka_exports_request, $contentType)
+            ->then(
+                function ($response) {
+                    return $response[0];
+                }
+            );
+    }
+
+    /**
+     * Operation postApiV3TipitakaExportsAsyncWithHttpInfo
+     *
+     * 发起下载
+     *
+     * @param  \WikipaliApi\Model\PostApiV3TipitakaExportsRequest $post_api_v3_tipitaka_exports_request (required)
+     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['postApiV3TipitakaExports'] to see the possible values for this operation
+     *
+     * @throws \InvalidArgumentException
+     * @return \GuzzleHttp\Promise\PromiseInterface
+     */
+    public function postApiV3TipitakaExportsAsyncWithHttpInfo($post_api_v3_tipitaka_exports_request, string $contentType = self::contentTypes['postApiV3TipitakaExports'][0])
+    {
+        $returnType = '\WikipaliApi\Model\PostApiV3TipitakaExports200Response';
+        $request = $this->postApiV3TipitakaExportsRequest($post_api_v3_tipitaka_exports_request, $contentType);
+
+        return $this->client
+            ->sendAsync($request, $this->createHttpClientOption())
+            ->then(
+                function ($response) use ($returnType) {
+                    if ($returnType === '\SplFileObject') {
+                        $content = $response->getBody(); //stream goes to serializer
+                    } else {
+                        $content = (string) $response->getBody();
+                        if ($returnType !== 'string') {
+                            $content = json_decode($content);
+                        }
+                    }
+
+                    return [
+                        ObjectSerializer::deserialize($content, $returnType, []),
+                        $response->getStatusCode(),
+                        $response->getHeaders()
+                    ];
+                },
+                function ($exception) {
+                    $response = $exception->getResponse();
+                    $statusCode = $response->getStatusCode();
+                    throw new ApiException(
+                        sprintf(
+                            '[%d] Error connecting to the API (%s)',
+                            $statusCode,
+                            $exception->getRequest()->getUri()
+                        ),
+                        $statusCode,
+                        $response->getHeaders(),
+                        (string) $response->getBody()
+                    );
+                }
+            );
+    }
+
+    /**
+     * Create request for operation 'postApiV3TipitakaExports'
+     *
+     * @param  \WikipaliApi\Model\PostApiV3TipitakaExportsRequest $post_api_v3_tipitaka_exports_request (required)
+     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['postApiV3TipitakaExports'] to see the possible values for this operation
+     *
+     * @throws \InvalidArgumentException
+     * @return \GuzzleHttp\Psr7\Request
+     */
+    public function postApiV3TipitakaExportsRequest($post_api_v3_tipitaka_exports_request, string $contentType = self::contentTypes['postApiV3TipitakaExports'][0])
+    {
+
+        // verify the required parameter 'post_api_v3_tipitaka_exports_request' is set
+        if ($post_api_v3_tipitaka_exports_request === null || (is_array($post_api_v3_tipitaka_exports_request) && count($post_api_v3_tipitaka_exports_request) === 0)) {
+            throw new \InvalidArgumentException(
+                'Missing the required parameter $post_api_v3_tipitaka_exports_request when calling postApiV3TipitakaExports'
+            );
+        }
+
+
+        $resourcePath = '/v3/tipitaka-exports';
+        $formParams = [];
+        $queryParams = [];
+        $headerParams = [];
+        $httpBody = '';
+        $multipart = false;
+
+
+
+
+
+        $headers = $this->headerSelector->selectHeaders(
+            ['application/json', 'application/problem+json', ],
+            $contentType,
+            $multipart
+        );
+
+        // for model (json/xml)
+        if (isset($post_api_v3_tipitaka_exports_request)) {
+            if (stripos($headers['Content-Type'], 'application/json') !== false) {
+                # if Content-Type contains "application/json", json_encode the body
+                try {
+                    $httpBody = json_encode(ObjectSerializer::sanitizeForSerialization($post_api_v3_tipitaka_exports_request), JSON_THROW_ON_ERROR);
+                } catch (\JsonException $e) {
+                    throw new \InvalidArgumentException('json_encode error: ' . $e->getMessage(), 0, $e);
+                }
+            } else {
+                $httpBody = $post_api_v3_tipitaka_exports_request;
+            }
+        } elseif (count($formParams) > 0) {
+            if ($multipart) {
+                $multipartContents = [];
+                foreach ($formParams as $formParamName => $formParamValue) {
+                    $formParamValueItems = is_array($formParamValue) ? $formParamValue : [$formParamValue];
+                    foreach ($formParamValueItems as $formParamValueItem) {
+                        $multipartContents[] = [
+                            'name' => $formParamName,
+                            'contents' => $formParamValueItem
+                        ];
+                    }
+                }
+                // for HTTP post (form)
+                $httpBody = new MultipartStream($multipartContents);
+
+            } elseif (stripos($headers['Content-Type'], 'application/json') !== false) {
+                # if Content-Type contains "application/json", json_encode the form parameters
+                try {
+                    $httpBody = json_encode($formParams, JSON_THROW_ON_ERROR);
+                } catch (\JsonException $e) {
+                    throw new \InvalidArgumentException('json_encode error: ' . $e->getMessage(), 0, $e);
+                }
+            } else {
+                // for HTTP post (form)
+                $httpBody = ObjectSerializer::buildQuery($formParams);
+            }
+        }
+
+        // this endpoint requires Bearer authentication (access token)
+        if (!empty($this->config->getAccessToken())) {
+            $headers['Authorization'] = 'Bearer ' . $this->config->getAccessToken();
+        }
+
+        $defaultHeaders = [];
+        if ($this->config->getUserAgent()) {
+            $defaultHeaders['User-Agent'] = $this->config->getUserAgent();
+        }
+
+        $headers = array_merge(
+            $defaultHeaders,
+            $headerParams,
+            $headers
+        );
+
+        $operationHost = $this->config->getHost();
+        $query = ObjectSerializer::buildQuery($queryParams);
+        return new Request(
+            'POST',
+            $operationHost . $resourcePath . ($query ? "?{$query}" : ''),
+            $headers,
+            $httpBody
+        );
+    }
+
+    /**
+     * Create http client option
+     *
+     * @throws \RuntimeException on file opening failure
+     * @return array of http client options
+     */
+    protected function createHttpClientOption()
+    {
+        $options = [];
+        if ($this->config->getDebug()) {
+            $options[RequestOptions::DEBUG] = fopen($this->config->getDebugFile(), 'a');
+            if (!$options[RequestOptions::DEBUG]) {
+                throw new \RuntimeException('Failed to open the debug file: ' . $this->config->getDebugFile());
+            }
+        }
+
+        if ($this->config->getCertFile()) {
+            $options[RequestOptions::CERT] = $this->config->getCertFile();
+        }
+
+        if ($this->config->getKeyFile()) {
+            $options[RequestOptions::SSL_KEY] = $this->config->getKeyFile();
+        }
+
+        return $options;
+    }
+
+    private function handleResponseWithDataType(
+        string $dataType,
+        RequestInterface $request,
+        ResponseInterface $response
+    ): array {
+        if ($dataType === '\SplFileObject') {
+            $content = $response->getBody(); //stream goes to serializer
+        } else {
+            $content = (string) $response->getBody();
+            if ($dataType !== 'string') {
+                try {
+                    $content = json_decode($content, false, 512, JSON_THROW_ON_ERROR);
+                } catch (\JsonException $exception) {
+                    throw new ApiException(
+                        sprintf(
+                            'Error JSON decoding server response (%s)',
+                            $request->getUri()
+                        ),
+                        $response->getStatusCode(),
+                        $response->getHeaders(),
+                        $content
+                    );
+                }
+            }
+        }
+
+        return [
+            ObjectSerializer::deserialize($content, $dataType, []),
+            $response->getStatusCode(),
+            $response->getHeaders()
+        ];
+    }
+
+    private function responseWithinRangeCode(
+        string $rangeCode,
+        int $statusCode
+    ): bool {
+        $left = (int) ($rangeCode[0].'00');
+        $right = (int) ($rangeCode[0].'99');
+
+        return $statusCode >= $left && $statusCode <= $right;
+    }
+}

+ 409 - 0
api-test/client/lib/Model/PostApiV3MarkupPreviews200Response.php

@@ -0,0 +1,409 @@
+<?php
+/**
+ * PostApiV3MarkupPreviews200Response
+ *
+ * PHP version 8.1
+ *
+ * @category Class
+ * @package  WikipaliApi
+ * @author   OpenAPI Generator team
+ * @link     https://openapi-generator.tech
+ */
+
+/**
+ * MINT API
+ *
+ * International Academy Of Pali Tipitaka(国际巴利三藏学院)  由 `php openapi/scripts/generate.php` 依据 api-v13 的路由与控制器源码生成。 响应统一封装为 `{ok, message, data}`;`ok=false` 时 `message` 为错误信息。
+ *
+ * The version of the OpenAPI document: 1.0.0
+ * Generated by: https://openapi-generator.tech
+ * Generator version: 7.25.0
+ */
+
+/**
+ * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
+ * https://openapi-generator.tech
+ * Do not edit the class manually.
+ */
+
+namespace WikipaliApi\Model;
+
+use \ArrayAccess;
+use \WikipaliApi\ObjectSerializer;
+
+/**
+ * PostApiV3MarkupPreviews200Response Class Doc Comment
+ *
+ * @category Class
+ * @package  WikipaliApi
+ * @author   OpenAPI Generator team
+ * @link     https://openapi-generator.tech
+ * @implements \ArrayAccess<string, mixed>
+ */
+class PostApiV3MarkupPreviews200Response implements ModelInterface, ArrayAccess, \JsonSerializable
+{
+    public const DISCRIMINATOR = null;
+
+    /**
+     * The original name of the model.
+     *
+     * @var string
+     */
+    protected static $openAPIModelName = 'post_api_v3_markup_previews_200_response';
+
+    /**
+     * Array of property to type mappings. Used for (de)serialization
+     *
+     * @var string[]
+     */
+    protected static $openAPITypes = [
+        'data' => '\WikipaliApi\Model\PostApiV3MarkupPreviews200ResponseData'
+    ];
+
+    /**
+     * Array of property to format mappings. Used for (de)serialization
+     *
+     * @var string[]
+     * @phpstan-var array<string, string|null>
+     * @psalm-var array<string, string|null>
+     */
+    protected static $openAPIFormats = [
+        'data' => null
+    ];
+
+    /**
+     * Array of nullable properties. Used for (de)serialization
+     *
+     * @var boolean[]
+     */
+    protected static array $openAPINullables = [
+        'data' => false
+    ];
+
+    /**
+     * If a nullable field gets set to null, insert it here
+     *
+     * @var boolean[]
+     */
+    protected array $openAPINullablesSetToNull = [];
+
+    /**
+     * Array of property to type mappings. Used for (de)serialization
+     *
+     * @return array
+     */
+    public static function openAPITypes()
+    {
+        return self::$openAPITypes;
+    }
+
+    /**
+     * Array of property to format mappings. Used for (de)serialization
+     *
+     * @return array
+     */
+    public static function openAPIFormats()
+    {
+        return self::$openAPIFormats;
+    }
+
+    /**
+     * Array of nullable properties
+     *
+     * @return array
+     */
+    protected static function openAPINullables(): array
+    {
+        return self::$openAPINullables;
+    }
+
+    /**
+     * Array of nullable field names deliberately set to null
+     *
+     * @return boolean[]
+     */
+    private function getOpenAPINullablesSetToNull(): array
+    {
+        return $this->openAPINullablesSetToNull;
+    }
+
+    /**
+     * Setter - Array of nullable field names deliberately set to null
+     *
+     * @param boolean[] $openAPINullablesSetToNull
+     */
+    private function setOpenAPINullablesSetToNull(array $openAPINullablesSetToNull): void
+    {
+        $this->openAPINullablesSetToNull = $openAPINullablesSetToNull;
+    }
+
+    /**
+     * Checks if a property is nullable
+     *
+     * @param string $property
+     * @return bool
+     */
+    public static function isNullable(string $property): bool
+    {
+        return self::openAPINullables()[$property] ?? false;
+    }
+
+    /**
+     * Checks if a nullable property is set to null.
+     *
+     * @param string $property
+     * @return bool
+     */
+    public function isNullableSetToNull(string $property): bool
+    {
+        return in_array($property, $this->getOpenAPINullablesSetToNull(), true);
+    }
+
+    /**
+     * Array of attributes where the key is the local name,
+     * and the value is the original name
+     *
+     * @var string[]
+     */
+    protected static $attributeMap = [
+        'data' => 'data'
+    ];
+
+    /**
+     * Array of attributes to setter functions (for deserialization of responses)
+     *
+     * @var string[]
+     */
+    protected static $setters = [
+        'data' => 'setData'
+    ];
+
+    /**
+     * Array of attributes to getter functions (for serialization of requests)
+     *
+     * @var string[]
+     */
+    protected static $getters = [
+        'data' => 'getData'
+    ];
+
+    /**
+     * Array of attributes where the key is the local name,
+     * and the value is the original name
+     *
+     * @return array
+     */
+    public static function attributeMap()
+    {
+        return self::$attributeMap;
+    }
+
+    /**
+     * Array of attributes to setter functions (for deserialization of responses)
+     *
+     * @return array
+     */
+    public static function setters()
+    {
+        return self::$setters;
+    }
+
+    /**
+     * Array of attributes to getter functions (for serialization of requests)
+     *
+     * @return array
+     */
+    public static function getters()
+    {
+        return self::$getters;
+    }
+
+    /**
+     * The original name of the model.
+     *
+     * @return string
+     */
+    public function getModelName()
+    {
+        return self::$openAPIModelName;
+    }
+
+
+    /**
+     * Associative array for storing property values
+     *
+     * @var mixed[]
+     */
+    protected $container = [];
+
+    /**
+     * Constructor
+     *
+     * @param mixed[]|null $data Associated array of property values
+     *                      initializing the model
+     */
+    public function __construct(?array $data = null)
+    {
+        $this->setIfExists('data', $data ?? [], null);
+    }
+
+    /**
+     * Sets $this->container[$variableName] to the given data or to the given default Value; if $variableName
+     * is nullable and its value is set to null in the $fields array, then mark it as "set to null" in the
+     * $this->openAPINullablesSetToNull array
+     *
+     * @param string $variableName
+     * @param array  $fields
+     * @param mixed  $defaultValue
+     */
+    private function setIfExists(string $variableName, array $fields, $defaultValue): void
+    {
+        if (self::isNullable($variableName) && array_key_exists($variableName, $fields) && is_null($fields[$variableName])) {
+            $this->openAPINullablesSetToNull[] = $variableName;
+        }
+
+        $this->container[$variableName] = $fields[$variableName] ?? $defaultValue;
+    }
+
+    /**
+     * Show all the invalid properties with reasons.
+     *
+     * @return array invalid properties with reasons
+     */
+    public function listInvalidProperties()
+    {
+        $invalidProperties = [];
+
+        return $invalidProperties;
+    }
+
+    /**
+     * Validate all the properties in the model
+     * return true if all passed
+     *
+     * @return bool True if all properties are valid
+     */
+    public function valid()
+    {
+        return count($this->listInvalidProperties()) === 0;
+    }
+
+
+    /**
+     * Gets data
+     *
+     * @return \WikipaliApi\Model\PostApiV3MarkupPreviews200ResponseData|null
+     */
+    public function getData()
+    {
+        return $this->container['data'];
+    }
+
+    /**
+     * Sets data
+     *
+     * @param \WikipaliApi\Model\PostApiV3MarkupPreviews200ResponseData|null $data data
+     *
+     * @return self
+     */
+    public function setData($data)
+    {
+        if (is_null($data)) {
+            throw new \InvalidArgumentException('non-nullable data cannot be null');
+        }
+        $this->container['data'] = $data;
+
+        return $this;
+    }
+    /**
+     * Returns true if offset exists. False otherwise.
+     *
+     * @param integer|string $offset Offset
+     *
+     * @return boolean
+     */
+    public function offsetExists(mixed $offset): bool
+    {
+        return isset($this->container[$offset]);
+    }
+
+    /**
+     * Gets offset.
+     *
+     * @param integer|string $offset Offset
+     *
+     * @return mixed|null
+     */
+    #[\ReturnTypeWillChange]
+    public function offsetGet(mixed $offset)
+    {
+        return $this->container[$offset] ?? null;
+    }
+
+    /**
+     * Sets value based on offset.
+     *
+     * @param int|null $offset Offset
+     * @param mixed    $value  Value to be set
+     *
+     * @return void
+     */
+    public function offsetSet($offset, $value): void
+    {
+        if (is_null($offset)) {
+            $this->container[] = $value;
+        } else {
+            $this->container[$offset] = $value;
+        }
+    }
+
+    /**
+     * Unsets offset.
+     *
+     * @param integer|string $offset Offset
+     *
+     * @return void
+     */
+    public function offsetUnset(mixed $offset): void
+    {
+        unset($this->container[$offset]);
+    }
+
+    /**
+     * Serializes the object to a value that can be serialized natively by json_encode().
+     * @link https://www.php.net/manual/en/jsonserializable.jsonserialize.php
+     *
+     * @return mixed Returns data which can be serialized by json_encode(), which is a value
+     * of any type other than a resource.
+     */
+    #[\ReturnTypeWillChange]
+    public function jsonSerialize()
+    {
+       return ObjectSerializer::sanitizeForSerialization($this);
+    }
+
+    /**
+     * Gets the string presentation of the object
+     *
+     * @return string
+     */
+    public function __toString()
+    {
+        return json_encode(
+            ObjectSerializer::sanitizeForSerialization($this),
+            JSON_PRETTY_PRINT
+        );
+    }
+
+    /**
+     * Gets a header-safe presentation of the object
+     *
+     * @return string
+     */
+    public function toHeaderValue()
+    {
+        return json_encode(ObjectSerializer::sanitizeForSerialization($this));
+    }
+}
+
+

+ 409 - 0
api-test/client/lib/Model/PostApiV3MarkupPreviews200ResponseData.php

@@ -0,0 +1,409 @@
+<?php
+/**
+ * PostApiV3MarkupPreviews200ResponseData
+ *
+ * PHP version 8.1
+ *
+ * @category Class
+ * @package  WikipaliApi
+ * @author   OpenAPI Generator team
+ * @link     https://openapi-generator.tech
+ */
+
+/**
+ * MINT API
+ *
+ * International Academy Of Pali Tipitaka(国际巴利三藏学院)  由 `php openapi/scripts/generate.php` 依据 api-v13 的路由与控制器源码生成。 响应统一封装为 `{ok, message, data}`;`ok=false` 时 `message` 为错误信息。
+ *
+ * The version of the OpenAPI document: 1.0.0
+ * Generated by: https://openapi-generator.tech
+ * Generator version: 7.25.0
+ */
+
+/**
+ * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
+ * https://openapi-generator.tech
+ * Do not edit the class manually.
+ */
+
+namespace WikipaliApi\Model;
+
+use \ArrayAccess;
+use \WikipaliApi\ObjectSerializer;
+
+/**
+ * PostApiV3MarkupPreviews200ResponseData Class Doc Comment
+ *
+ * @category Class
+ * @package  WikipaliApi
+ * @author   OpenAPI Generator team
+ * @link     https://openapi-generator.tech
+ * @implements \ArrayAccess<string, mixed>
+ */
+class PostApiV3MarkupPreviews200ResponseData implements ModelInterface, ArrayAccess, \JsonSerializable
+{
+    public const DISCRIMINATOR = null;
+
+    /**
+     * The original name of the model.
+     *
+     * @var string
+     */
+    protected static $openAPIModelName = 'post_api_v3_markup_previews_200_response_data';
+
+    /**
+     * Array of property to type mappings. Used for (de)serialization
+     *
+     * @var string[]
+     */
+    protected static $openAPITypes = [
+        'body' => '\WikipaliApi\Model\MarkupNode[]'
+    ];
+
+    /**
+     * Array of property to format mappings. Used for (de)serialization
+     *
+     * @var string[]
+     * @phpstan-var array<string, string|null>
+     * @psalm-var array<string, string|null>
+     */
+    protected static $openAPIFormats = [
+        'body' => null
+    ];
+
+    /**
+     * Array of nullable properties. Used for (de)serialization
+     *
+     * @var boolean[]
+     */
+    protected static array $openAPINullables = [
+        'body' => false
+    ];
+
+    /**
+     * If a nullable field gets set to null, insert it here
+     *
+     * @var boolean[]
+     */
+    protected array $openAPINullablesSetToNull = [];
+
+    /**
+     * Array of property to type mappings. Used for (de)serialization
+     *
+     * @return array
+     */
+    public static function openAPITypes()
+    {
+        return self::$openAPITypes;
+    }
+
+    /**
+     * Array of property to format mappings. Used for (de)serialization
+     *
+     * @return array
+     */
+    public static function openAPIFormats()
+    {
+        return self::$openAPIFormats;
+    }
+
+    /**
+     * Array of nullable properties
+     *
+     * @return array
+     */
+    protected static function openAPINullables(): array
+    {
+        return self::$openAPINullables;
+    }
+
+    /**
+     * Array of nullable field names deliberately set to null
+     *
+     * @return boolean[]
+     */
+    private function getOpenAPINullablesSetToNull(): array
+    {
+        return $this->openAPINullablesSetToNull;
+    }
+
+    /**
+     * Setter - Array of nullable field names deliberately set to null
+     *
+     * @param boolean[] $openAPINullablesSetToNull
+     */
+    private function setOpenAPINullablesSetToNull(array $openAPINullablesSetToNull): void
+    {
+        $this->openAPINullablesSetToNull = $openAPINullablesSetToNull;
+    }
+
+    /**
+     * Checks if a property is nullable
+     *
+     * @param string $property
+     * @return bool
+     */
+    public static function isNullable(string $property): bool
+    {
+        return self::openAPINullables()[$property] ?? false;
+    }
+
+    /**
+     * Checks if a nullable property is set to null.
+     *
+     * @param string $property
+     * @return bool
+     */
+    public function isNullableSetToNull(string $property): bool
+    {
+        return in_array($property, $this->getOpenAPINullablesSetToNull(), true);
+    }
+
+    /**
+     * Array of attributes where the key is the local name,
+     * and the value is the original name
+     *
+     * @var string[]
+     */
+    protected static $attributeMap = [
+        'body' => 'body'
+    ];
+
+    /**
+     * Array of attributes to setter functions (for deserialization of responses)
+     *
+     * @var string[]
+     */
+    protected static $setters = [
+        'body' => 'setBody'
+    ];
+
+    /**
+     * Array of attributes to getter functions (for serialization of requests)
+     *
+     * @var string[]
+     */
+    protected static $getters = [
+        'body' => 'getBody'
+    ];
+
+    /**
+     * Array of attributes where the key is the local name,
+     * and the value is the original name
+     *
+     * @return array
+     */
+    public static function attributeMap()
+    {
+        return self::$attributeMap;
+    }
+
+    /**
+     * Array of attributes to setter functions (for deserialization of responses)
+     *
+     * @return array
+     */
+    public static function setters()
+    {
+        return self::$setters;
+    }
+
+    /**
+     * Array of attributes to getter functions (for serialization of requests)
+     *
+     * @return array
+     */
+    public static function getters()
+    {
+        return self::$getters;
+    }
+
+    /**
+     * The original name of the model.
+     *
+     * @return string
+     */
+    public function getModelName()
+    {
+        return self::$openAPIModelName;
+    }
+
+
+    /**
+     * Associative array for storing property values
+     *
+     * @var mixed[]
+     */
+    protected $container = [];
+
+    /**
+     * Constructor
+     *
+     * @param mixed[]|null $data Associated array of property values
+     *                      initializing the model
+     */
+    public function __construct(?array $data = null)
+    {
+        $this->setIfExists('body', $data ?? [], null);
+    }
+
+    /**
+     * Sets $this->container[$variableName] to the given data or to the given default Value; if $variableName
+     * is nullable and its value is set to null in the $fields array, then mark it as "set to null" in the
+     * $this->openAPINullablesSetToNull array
+     *
+     * @param string $variableName
+     * @param array  $fields
+     * @param mixed  $defaultValue
+     */
+    private function setIfExists(string $variableName, array $fields, $defaultValue): void
+    {
+        if (self::isNullable($variableName) && array_key_exists($variableName, $fields) && is_null($fields[$variableName])) {
+            $this->openAPINullablesSetToNull[] = $variableName;
+        }
+
+        $this->container[$variableName] = $fields[$variableName] ?? $defaultValue;
+    }
+
+    /**
+     * Show all the invalid properties with reasons.
+     *
+     * @return array invalid properties with reasons
+     */
+    public function listInvalidProperties()
+    {
+        $invalidProperties = [];
+
+        return $invalidProperties;
+    }
+
+    /**
+     * Validate all the properties in the model
+     * return true if all passed
+     *
+     * @return bool True if all properties are valid
+     */
+    public function valid()
+    {
+        return count($this->listInvalidProperties()) === 0;
+    }
+
+
+    /**
+     * Gets body
+     *
+     * @return \WikipaliApi\Model\MarkupNode[]|null
+     */
+    public function getBody()
+    {
+        return $this->container['body'];
+    }
+
+    /**
+     * Sets body
+     *
+     * @param \WikipaliApi\Model\MarkupNode[]|null $body body
+     *
+     * @return self
+     */
+    public function setBody($body)
+    {
+        if (is_null($body)) {
+            throw new \InvalidArgumentException('non-nullable body cannot be null');
+        }
+        $this->container['body'] = $body;
+
+        return $this;
+    }
+    /**
+     * Returns true if offset exists. False otherwise.
+     *
+     * @param integer|string $offset Offset
+     *
+     * @return boolean
+     */
+    public function offsetExists(mixed $offset): bool
+    {
+        return isset($this->container[$offset]);
+    }
+
+    /**
+     * Gets offset.
+     *
+     * @param integer|string $offset Offset
+     *
+     * @return mixed|null
+     */
+    #[\ReturnTypeWillChange]
+    public function offsetGet(mixed $offset)
+    {
+        return $this->container[$offset] ?? null;
+    }
+
+    /**
+     * Sets value based on offset.
+     *
+     * @param int|null $offset Offset
+     * @param mixed    $value  Value to be set
+     *
+     * @return void
+     */
+    public function offsetSet($offset, $value): void
+    {
+        if (is_null($offset)) {
+            $this->container[] = $value;
+        } else {
+            $this->container[$offset] = $value;
+        }
+    }
+
+    /**
+     * Unsets offset.
+     *
+     * @param integer|string $offset Offset
+     *
+     * @return void
+     */
+    public function offsetUnset(mixed $offset): void
+    {
+        unset($this->container[$offset]);
+    }
+
+    /**
+     * Serializes the object to a value that can be serialized natively by json_encode().
+     * @link https://www.php.net/manual/en/jsonserializable.jsonserialize.php
+     *
+     * @return mixed Returns data which can be serialized by json_encode(), which is a value
+     * of any type other than a resource.
+     */
+    #[\ReturnTypeWillChange]
+    public function jsonSerialize()
+    {
+       return ObjectSerializer::sanitizeForSerialization($this);
+    }
+
+    /**
+     * Gets the string presentation of the object
+     *
+     * @return string
+     */
+    public function __toString()
+    {
+        return json_encode(
+            ObjectSerializer::sanitizeForSerialization($this),
+            JSON_PRETTY_PRINT
+        );
+    }
+
+    /**
+     * Gets a header-safe presentation of the object
+     *
+     * @return string
+     */
+    public function toHeaderValue()
+    {
+        return json_encode(ObjectSerializer::sanitizeForSerialization($this));
+    }
+}
+
+

+ 548 - 0
api-test/client/lib/Model/PostApiV3MarkupPreviewsRequest.php

@@ -0,0 +1,548 @@
+<?php
+/**
+ * PostApiV3MarkupPreviewsRequest
+ *
+ * PHP version 8.1
+ *
+ * @category Class
+ * @package  WikipaliApi
+ * @author   OpenAPI Generator team
+ * @link     https://openapi-generator.tech
+ */
+
+/**
+ * MINT API
+ *
+ * International Academy Of Pali Tipitaka(国际巴利三藏学院)  由 `php openapi/scripts/generate.php` 依据 api-v13 的路由与控制器源码生成。 响应统一封装为 `{ok, message, data}`;`ok=false` 时 `message` 为错误信息。
+ *
+ * The version of the OpenAPI document: 1.0.0
+ * Generated by: https://openapi-generator.tech
+ * Generator version: 7.25.0
+ */
+
+/**
+ * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
+ * https://openapi-generator.tech
+ * Do not edit the class manually.
+ */
+
+namespace WikipaliApi\Model;
+
+use \ArrayAccess;
+use \WikipaliApi\ObjectSerializer;
+
+/**
+ * PostApiV3MarkupPreviewsRequest Class Doc Comment
+ *
+ * @category Class
+ * @package  WikipaliApi
+ * @author   OpenAPI Generator team
+ * @link     https://openapi-generator.tech
+ * @implements \ArrayAccess<string, mixed>
+ */
+class PostApiV3MarkupPreviewsRequest implements ModelInterface, ArrayAccess, \JsonSerializable
+{
+    public const DISCRIMINATOR = null;
+
+    /**
+     * The original name of the model.
+     *
+     * @var string
+     */
+    protected static $openAPIModelName = 'post_api_v3_markup_previews_request';
+
+    /**
+     * Array of property to type mappings. Used for (de)serialization
+     *
+     * @var string[]
+     */
+    protected static $openAPITypes = [
+        'content' => 'string',
+        'content_type' => 'string',
+        'channels' => 'string[]',
+        'lang' => 'string'
+    ];
+
+    /**
+     * Array of property to format mappings. Used for (de)serialization
+     *
+     * @var string[]
+     * @phpstan-var array<string, string|null>
+     * @psalm-var array<string, string|null>
+     */
+    protected static $openAPIFormats = [
+        'content' => null,
+        'content_type' => null,
+        'channels' => null,
+        'lang' => null
+    ];
+
+    /**
+     * Array of nullable properties. Used for (de)serialization
+     *
+     * @var boolean[]
+     */
+    protected static array $openAPINullables = [
+        'content' => false,
+        'content_type' => false,
+        'channels' => false,
+        'lang' => false
+    ];
+
+    /**
+     * If a nullable field gets set to null, insert it here
+     *
+     * @var boolean[]
+     */
+    protected array $openAPINullablesSetToNull = [];
+
+    /**
+     * Array of property to type mappings. Used for (de)serialization
+     *
+     * @return array
+     */
+    public static function openAPITypes()
+    {
+        return self::$openAPITypes;
+    }
+
+    /**
+     * Array of property to format mappings. Used for (de)serialization
+     *
+     * @return array
+     */
+    public static function openAPIFormats()
+    {
+        return self::$openAPIFormats;
+    }
+
+    /**
+     * Array of nullable properties
+     *
+     * @return array
+     */
+    protected static function openAPINullables(): array
+    {
+        return self::$openAPINullables;
+    }
+
+    /**
+     * Array of nullable field names deliberately set to null
+     *
+     * @return boolean[]
+     */
+    private function getOpenAPINullablesSetToNull(): array
+    {
+        return $this->openAPINullablesSetToNull;
+    }
+
+    /**
+     * Setter - Array of nullable field names deliberately set to null
+     *
+     * @param boolean[] $openAPINullablesSetToNull
+     */
+    private function setOpenAPINullablesSetToNull(array $openAPINullablesSetToNull): void
+    {
+        $this->openAPINullablesSetToNull = $openAPINullablesSetToNull;
+    }
+
+    /**
+     * Checks if a property is nullable
+     *
+     * @param string $property
+     * @return bool
+     */
+    public static function isNullable(string $property): bool
+    {
+        return self::openAPINullables()[$property] ?? false;
+    }
+
+    /**
+     * Checks if a nullable property is set to null.
+     *
+     * @param string $property
+     * @return bool
+     */
+    public function isNullableSetToNull(string $property): bool
+    {
+        return in_array($property, $this->getOpenAPINullablesSetToNull(), true);
+    }
+
+    /**
+     * Array of attributes where the key is the local name,
+     * and the value is the original name
+     *
+     * @var string[]
+     */
+    protected static $attributeMap = [
+        'content' => 'content',
+        'content_type' => 'content_type',
+        'channels' => 'channels',
+        'lang' => 'lang'
+    ];
+
+    /**
+     * Array of attributes to setter functions (for deserialization of responses)
+     *
+     * @var string[]
+     */
+    protected static $setters = [
+        'content' => 'setContent',
+        'content_type' => 'setContentType',
+        'channels' => 'setChannels',
+        'lang' => 'setLang'
+    ];
+
+    /**
+     * Array of attributes to getter functions (for serialization of requests)
+     *
+     * @var string[]
+     */
+    protected static $getters = [
+        'content' => 'getContent',
+        'content_type' => 'getContentType',
+        'channels' => 'getChannels',
+        'lang' => 'getLang'
+    ];
+
+    /**
+     * Array of attributes where the key is the local name,
+     * and the value is the original name
+     *
+     * @return array
+     */
+    public static function attributeMap()
+    {
+        return self::$attributeMap;
+    }
+
+    /**
+     * Array of attributes to setter functions (for deserialization of responses)
+     *
+     * @return array
+     */
+    public static function setters()
+    {
+        return self::$setters;
+    }
+
+    /**
+     * Array of attributes to getter functions (for serialization of requests)
+     *
+     * @return array
+     */
+    public static function getters()
+    {
+        return self::$getters;
+    }
+
+    /**
+     * The original name of the model.
+     *
+     * @return string
+     */
+    public function getModelName()
+    {
+        return self::$openAPIModelName;
+    }
+
+    public const CONTENT_TYPE_MARKDOWN = 'markdown';
+    public const CONTENT_TYPE_MARKDOWN_E2 = 'markdown-e2';
+
+    /**
+     * Gets allowable values of the enum
+     *
+     * @return string[]
+     */
+    public function getContentTypeAllowableValues()
+    {
+        return [
+            self::CONTENT_TYPE_MARKDOWN,
+            self::CONTENT_TYPE_MARKDOWN_E2,
+        ];
+    }
+
+    /**
+     * Associative array for storing property values
+     *
+     * @var mixed[]
+     */
+    protected $container = [];
+
+    /**
+     * Constructor
+     *
+     * @param mixed[]|null $data Associated array of property values
+     *                      initializing the model
+     */
+    public function __construct(?array $data = null)
+    {
+        $this->setIfExists('content', $data ?? [], null);
+        $this->setIfExists('content_type', $data ?? [], 'markdown');
+        $this->setIfExists('channels', $data ?? [], null);
+        $this->setIfExists('lang', $data ?? [], null);
+    }
+
+    /**
+     * Sets $this->container[$variableName] to the given data or to the given default Value; if $variableName
+     * is nullable and its value is set to null in the $fields array, then mark it as "set to null" in the
+     * $this->openAPINullablesSetToNull array
+     *
+     * @param string $variableName
+     * @param array  $fields
+     * @param mixed  $defaultValue
+     */
+    private function setIfExists(string $variableName, array $fields, $defaultValue): void
+    {
+        if (self::isNullable($variableName) && array_key_exists($variableName, $fields) && is_null($fields[$variableName])) {
+            $this->openAPINullablesSetToNull[] = $variableName;
+        }
+
+        $this->container[$variableName] = $fields[$variableName] ?? $defaultValue;
+    }
+
+    /**
+     * Show all the invalid properties with reasons.
+     *
+     * @return array invalid properties with reasons
+     */
+    public function listInvalidProperties()
+    {
+        $invalidProperties = [];
+
+        if ($this->container['content'] === null) {
+            $invalidProperties[] = "'content' can't be null";
+        }
+        $allowedValues = $this->getContentTypeAllowableValues();
+        if (!is_null($this->container['content_type']) && !in_array($this->container['content_type'], $allowedValues, true)) {
+            $invalidProperties[] = sprintf(
+                "invalid value '%s' for 'content_type', must be one of '%s'",
+                $this->container['content_type'],
+                implode("', '", $allowedValues)
+            );
+        }
+
+        return $invalidProperties;
+    }
+
+    /**
+     * Validate all the properties in the model
+     * return true if all passed
+     *
+     * @return bool True if all properties are valid
+     */
+    public function valid()
+    {
+        return count($this->listInvalidProperties()) === 0;
+    }
+
+
+    /**
+     * Gets content
+     *
+     * @return string
+     */
+    public function getContent()
+    {
+        return $this->container['content'];
+    }
+
+    /**
+     * Sets content
+     *
+     * @param string $content 源码,最多 20000 字
+     *
+     * @return self
+     */
+    public function setContent($content)
+    {
+        if (is_null($content)) {
+            throw new \InvalidArgumentException('non-nullable content cannot be null');
+        }
+        $this->container['content'] = $content;
+
+        return $this;
+    }
+
+    /**
+     * Gets content_type
+     *
+     * @return string|null
+     */
+    public function getContentType()
+    {
+        return $this->container['content_type'];
+    }
+
+    /**
+     * Sets content_type
+     *
+     * @param string|null $content_type 方言
+     *
+     * @return self
+     */
+    public function setContentType($content_type)
+    {
+        if (is_null($content_type)) {
+            throw new \InvalidArgumentException('non-nullable content_type cannot be null');
+        }
+        $allowedValues = $this->getContentTypeAllowableValues();
+        if (!in_array($content_type, $allowedValues, true)) {
+            throw new \InvalidArgumentException(
+                sprintf(
+                    "Invalid value '%s' for 'content_type', must be one of '%s'",
+                    $content_type,
+                    implode("', '", $allowedValues)
+                )
+            );
+        }
+        $this->container['content_type'] = $content_type;
+
+        return $this;
+    }
+
+    /**
+     * Gets channels
+     *
+     * @return string[]|null
+     */
+    public function getChannels()
+    {
+        return $this->container['channels'];
+    }
+
+    /**
+     * Sets channels
+     *
+     * @param string[]|null $channels 内容所属的 channel uid,最多 10 个
+     *
+     * @return self
+     */
+    public function setChannels($channels)
+    {
+        if (is_null($channels)) {
+            throw new \InvalidArgumentException('non-nullable channels cannot be null');
+        }
+        $this->container['channels'] = $channels;
+
+        return $this;
+    }
+
+    /**
+     * Gets lang
+     *
+     * @return string|null
+     */
+    public function getLang()
+    {
+        return $this->container['lang'];
+    }
+
+    /**
+     * Sets lang
+     *
+     * @param string|null $lang 没给 channel 时用的语言,如 zh-Hans。缺省用界面语言(Accept-Language 协商的结果)
+     *
+     * @return self
+     */
+    public function setLang($lang)
+    {
+        if (is_null($lang)) {
+            throw new \InvalidArgumentException('non-nullable lang cannot be null');
+        }
+        $this->container['lang'] = $lang;
+
+        return $this;
+    }
+    /**
+     * Returns true if offset exists. False otherwise.
+     *
+     * @param integer|string $offset Offset
+     *
+     * @return boolean
+     */
+    public function offsetExists(mixed $offset): bool
+    {
+        return isset($this->container[$offset]);
+    }
+
+    /**
+     * Gets offset.
+     *
+     * @param integer|string $offset Offset
+     *
+     * @return mixed|null
+     */
+    #[\ReturnTypeWillChange]
+    public function offsetGet(mixed $offset)
+    {
+        return $this->container[$offset] ?? null;
+    }
+
+    /**
+     * Sets value based on offset.
+     *
+     * @param int|null $offset Offset
+     * @param mixed    $value  Value to be set
+     *
+     * @return void
+     */
+    public function offsetSet($offset, $value): void
+    {
+        if (is_null($offset)) {
+            $this->container[] = $value;
+        } else {
+            $this->container[$offset] = $value;
+        }
+    }
+
+    /**
+     * Unsets offset.
+     *
+     * @param integer|string $offset Offset
+     *
+     * @return void
+     */
+    public function offsetUnset(mixed $offset): void
+    {
+        unset($this->container[$offset]);
+    }
+
+    /**
+     * Serializes the object to a value that can be serialized natively by json_encode().
+     * @link https://www.php.net/manual/en/jsonserializable.jsonserialize.php
+     *
+     * @return mixed Returns data which can be serialized by json_encode(), which is a value
+     * of any type other than a resource.
+     */
+    #[\ReturnTypeWillChange]
+    public function jsonSerialize()
+    {
+       return ObjectSerializer::sanitizeForSerialization($this);
+    }
+
+    /**
+     * Gets the string presentation of the object
+     *
+     * @return string
+     */
+    public function __toString()
+    {
+        return json_encode(
+            ObjectSerializer::sanitizeForSerialization($this),
+            JSON_PRETTY_PRINT
+        );
+    }
+
+    /**
+     * Gets a header-safe presentation of the object
+     *
+     * @return string
+     */
+    public function toHeaderValue()
+    {
+        return json_encode(ObjectSerializer::sanitizeForSerialization($this));
+    }
+}
+
+

+ 409 - 0
api-test/client/lib/Model/PostApiV3TipitakaExports200Response.php

@@ -0,0 +1,409 @@
+<?php
+/**
+ * PostApiV3TipitakaExports200Response
+ *
+ * PHP version 8.1
+ *
+ * @category Class
+ * @package  WikipaliApi
+ * @author   OpenAPI Generator team
+ * @link     https://openapi-generator.tech
+ */
+
+/**
+ * MINT API
+ *
+ * International Academy Of Pali Tipitaka(国际巴利三藏学院)  由 `php openapi/scripts/generate.php` 依据 api-v13 的路由与控制器源码生成。 响应统一封装为 `{ok, message, data}`;`ok=false` 时 `message` 为错误信息。
+ *
+ * The version of the OpenAPI document: 1.0.0
+ * Generated by: https://openapi-generator.tech
+ * Generator version: 7.25.0
+ */
+
+/**
+ * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
+ * https://openapi-generator.tech
+ * Do not edit the class manually.
+ */
+
+namespace WikipaliApi\Model;
+
+use \ArrayAccess;
+use \WikipaliApi\ObjectSerializer;
+
+/**
+ * PostApiV3TipitakaExports200Response Class Doc Comment
+ *
+ * @category Class
+ * @package  WikipaliApi
+ * @author   OpenAPI Generator team
+ * @link     https://openapi-generator.tech
+ * @implements \ArrayAccess<string, mixed>
+ */
+class PostApiV3TipitakaExports200Response implements ModelInterface, ArrayAccess, \JsonSerializable
+{
+    public const DISCRIMINATOR = null;
+
+    /**
+     * The original name of the model.
+     *
+     * @var string
+     */
+    protected static $openAPIModelName = 'post_api_v3_tipitaka_exports_200_response';
+
+    /**
+     * Array of property to type mappings. Used for (de)serialization
+     *
+     * @var string[]
+     */
+    protected static $openAPITypes = [
+        'data' => '\WikipaliApi\Model\PostApiV3TipitakaExports200ResponseData'
+    ];
+
+    /**
+     * Array of property to format mappings. Used for (de)serialization
+     *
+     * @var string[]
+     * @phpstan-var array<string, string|null>
+     * @psalm-var array<string, string|null>
+     */
+    protected static $openAPIFormats = [
+        'data' => null
+    ];
+
+    /**
+     * Array of nullable properties. Used for (de)serialization
+     *
+     * @var boolean[]
+     */
+    protected static array $openAPINullables = [
+        'data' => false
+    ];
+
+    /**
+     * If a nullable field gets set to null, insert it here
+     *
+     * @var boolean[]
+     */
+    protected array $openAPINullablesSetToNull = [];
+
+    /**
+     * Array of property to type mappings. Used for (de)serialization
+     *
+     * @return array
+     */
+    public static function openAPITypes()
+    {
+        return self::$openAPITypes;
+    }
+
+    /**
+     * Array of property to format mappings. Used for (de)serialization
+     *
+     * @return array
+     */
+    public static function openAPIFormats()
+    {
+        return self::$openAPIFormats;
+    }
+
+    /**
+     * Array of nullable properties
+     *
+     * @return array
+     */
+    protected static function openAPINullables(): array
+    {
+        return self::$openAPINullables;
+    }
+
+    /**
+     * Array of nullable field names deliberately set to null
+     *
+     * @return boolean[]
+     */
+    private function getOpenAPINullablesSetToNull(): array
+    {
+        return $this->openAPINullablesSetToNull;
+    }
+
+    /**
+     * Setter - Array of nullable field names deliberately set to null
+     *
+     * @param boolean[] $openAPINullablesSetToNull
+     */
+    private function setOpenAPINullablesSetToNull(array $openAPINullablesSetToNull): void
+    {
+        $this->openAPINullablesSetToNull = $openAPINullablesSetToNull;
+    }
+
+    /**
+     * Checks if a property is nullable
+     *
+     * @param string $property
+     * @return bool
+     */
+    public static function isNullable(string $property): bool
+    {
+        return self::openAPINullables()[$property] ?? false;
+    }
+
+    /**
+     * Checks if a nullable property is set to null.
+     *
+     * @param string $property
+     * @return bool
+     */
+    public function isNullableSetToNull(string $property): bool
+    {
+        return in_array($property, $this->getOpenAPINullablesSetToNull(), true);
+    }
+
+    /**
+     * Array of attributes where the key is the local name,
+     * and the value is the original name
+     *
+     * @var string[]
+     */
+    protected static $attributeMap = [
+        'data' => 'data'
+    ];
+
+    /**
+     * Array of attributes to setter functions (for deserialization of responses)
+     *
+     * @var string[]
+     */
+    protected static $setters = [
+        'data' => 'setData'
+    ];
+
+    /**
+     * Array of attributes to getter functions (for serialization of requests)
+     *
+     * @var string[]
+     */
+    protected static $getters = [
+        'data' => 'getData'
+    ];
+
+    /**
+     * Array of attributes where the key is the local name,
+     * and the value is the original name
+     *
+     * @return array
+     */
+    public static function attributeMap()
+    {
+        return self::$attributeMap;
+    }
+
+    /**
+     * Array of attributes to setter functions (for deserialization of responses)
+     *
+     * @return array
+     */
+    public static function setters()
+    {
+        return self::$setters;
+    }
+
+    /**
+     * Array of attributes to getter functions (for serialization of requests)
+     *
+     * @return array
+     */
+    public static function getters()
+    {
+        return self::$getters;
+    }
+
+    /**
+     * The original name of the model.
+     *
+     * @return string
+     */
+    public function getModelName()
+    {
+        return self::$openAPIModelName;
+    }
+
+
+    /**
+     * Associative array for storing property values
+     *
+     * @var mixed[]
+     */
+    protected $container = [];
+
+    /**
+     * Constructor
+     *
+     * @param mixed[]|null $data Associated array of property values
+     *                      initializing the model
+     */
+    public function __construct(?array $data = null)
+    {
+        $this->setIfExists('data', $data ?? [], null);
+    }
+
+    /**
+     * Sets $this->container[$variableName] to the given data or to the given default Value; if $variableName
+     * is nullable and its value is set to null in the $fields array, then mark it as "set to null" in the
+     * $this->openAPINullablesSetToNull array
+     *
+     * @param string $variableName
+     * @param array  $fields
+     * @param mixed  $defaultValue
+     */
+    private function setIfExists(string $variableName, array $fields, $defaultValue): void
+    {
+        if (self::isNullable($variableName) && array_key_exists($variableName, $fields) && is_null($fields[$variableName])) {
+            $this->openAPINullablesSetToNull[] = $variableName;
+        }
+
+        $this->container[$variableName] = $fields[$variableName] ?? $defaultValue;
+    }
+
+    /**
+     * Show all the invalid properties with reasons.
+     *
+     * @return array invalid properties with reasons
+     */
+    public function listInvalidProperties()
+    {
+        $invalidProperties = [];
+
+        return $invalidProperties;
+    }
+
+    /**
+     * Validate all the properties in the model
+     * return true if all passed
+     *
+     * @return bool True if all properties are valid
+     */
+    public function valid()
+    {
+        return count($this->listInvalidProperties()) === 0;
+    }
+
+
+    /**
+     * Gets data
+     *
+     * @return \WikipaliApi\Model\PostApiV3TipitakaExports200ResponseData|null
+     */
+    public function getData()
+    {
+        return $this->container['data'];
+    }
+
+    /**
+     * Sets data
+     *
+     * @param \WikipaliApi\Model\PostApiV3TipitakaExports200ResponseData|null $data data
+     *
+     * @return self
+     */
+    public function setData($data)
+    {
+        if (is_null($data)) {
+            throw new \InvalidArgumentException('non-nullable data cannot be null');
+        }
+        $this->container['data'] = $data;
+
+        return $this;
+    }
+    /**
+     * Returns true if offset exists. False otherwise.
+     *
+     * @param integer|string $offset Offset
+     *
+     * @return boolean
+     */
+    public function offsetExists(mixed $offset): bool
+    {
+        return isset($this->container[$offset]);
+    }
+
+    /**
+     * Gets offset.
+     *
+     * @param integer|string $offset Offset
+     *
+     * @return mixed|null
+     */
+    #[\ReturnTypeWillChange]
+    public function offsetGet(mixed $offset)
+    {
+        return $this->container[$offset] ?? null;
+    }
+
+    /**
+     * Sets value based on offset.
+     *
+     * @param int|null $offset Offset
+     * @param mixed    $value  Value to be set
+     *
+     * @return void
+     */
+    public function offsetSet($offset, $value): void
+    {
+        if (is_null($offset)) {
+            $this->container[] = $value;
+        } else {
+            $this->container[$offset] = $value;
+        }
+    }
+
+    /**
+     * Unsets offset.
+     *
+     * @param integer|string $offset Offset
+     *
+     * @return void
+     */
+    public function offsetUnset(mixed $offset): void
+    {
+        unset($this->container[$offset]);
+    }
+
+    /**
+     * Serializes the object to a value that can be serialized natively by json_encode().
+     * @link https://www.php.net/manual/en/jsonserializable.jsonserialize.php
+     *
+     * @return mixed Returns data which can be serialized by json_encode(), which is a value
+     * of any type other than a resource.
+     */
+    #[\ReturnTypeWillChange]
+    public function jsonSerialize()
+    {
+       return ObjectSerializer::sanitizeForSerialization($this);
+    }
+
+    /**
+     * Gets the string presentation of the object
+     *
+     * @return string
+     */
+    public function __toString()
+    {
+        return json_encode(
+            ObjectSerializer::sanitizeForSerialization($this),
+            JSON_PRETTY_PRINT
+        );
+    }
+
+    /**
+     * Gets a header-safe presentation of the object
+     *
+     * @return string
+     */
+    public function toHeaderValue()
+    {
+        return json_encode(ObjectSerializer::sanitizeForSerialization($this));
+    }
+}
+
+

+ 852 - 0
api-test/client/lib/Model/PostApiV3TipitakaExports200ResponseData.php

@@ -0,0 +1,852 @@
+<?php
+/**
+ * PostApiV3TipitakaExports200ResponseData
+ *
+ * PHP version 8.1
+ *
+ * @category Class
+ * @package  WikipaliApi
+ * @author   OpenAPI Generator team
+ * @link     https://openapi-generator.tech
+ */
+
+/**
+ * MINT API
+ *
+ * International Academy Of Pali Tipitaka(国际巴利三藏学院)  由 `php openapi/scripts/generate.php` 依据 api-v13 的路由与控制器源码生成。 响应统一封装为 `{ok, message, data}`;`ok=false` 时 `message` 为错误信息。
+ *
+ * The version of the OpenAPI document: 1.0.0
+ * Generated by: https://openapi-generator.tech
+ * Generator version: 7.25.0
+ */
+
+/**
+ * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
+ * https://openapi-generator.tech
+ * Do not edit the class manually.
+ */
+
+namespace WikipaliApi\Model;
+
+use \ArrayAccess;
+use \WikipaliApi\ObjectSerializer;
+
+/**
+ * PostApiV3TipitakaExports200ResponseData Class Doc Comment
+ *
+ * @category Class
+ * @package  WikipaliApi
+ * @author   OpenAPI Generator team
+ * @link     https://openapi-generator.tech
+ * @implements \ArrayAccess<string, mixed>
+ */
+class PostApiV3TipitakaExports200ResponseData implements ModelInterface, ArrayAccess, \JsonSerializable
+{
+    public const DISCRIMINATOR = null;
+
+    /**
+     * The original name of the model.
+     *
+     * @var string
+     */
+    protected static $openAPIModelName = 'post_api_v3_tipitaka_exports_200_response_data';
+
+    /**
+     * Array of property to type mappings. Used for (de)serialization
+     *
+     * @var string[]
+     */
+    protected static $openAPITypes = [
+        'id' => 'string',
+        'status' => 'string',
+        'format' => 'string',
+        'progress' => 'float',
+        'message' => 'string',
+        'title' => 'string',
+        'works' => 'int',
+        'filename' => 'string',
+        'content_type' => 'string',
+        'size' => 'int',
+        'ready_at' => 'string',
+        'expires_at' => 'string',
+        'download_url' => 'string'
+    ];
+
+    /**
+     * Array of property to format mappings. Used for (de)serialization
+     *
+     * @var string[]
+     * @phpstan-var array<string, string|null>
+     * @psalm-var array<string, string|null>
+     */
+    protected static $openAPIFormats = [
+        'id' => null,
+        'status' => null,
+        'format' => null,
+        'progress' => null,
+        'message' => null,
+        'title' => null,
+        'works' => null,
+        'filename' => null,
+        'content_type' => null,
+        'size' => null,
+        'ready_at' => null,
+        'expires_at' => null,
+        'download_url' => null
+    ];
+
+    /**
+     * Array of nullable properties. Used for (de)serialization
+     *
+     * @var boolean[]
+     */
+    protected static array $openAPINullables = [
+        'id' => false,
+        'status' => false,
+        'format' => false,
+        'progress' => false,
+        'message' => true,
+        'title' => false,
+        'works' => false,
+        'filename' => false,
+        'content_type' => false,
+        'size' => true,
+        'ready_at' => true,
+        'expires_at' => true,
+        'download_url' => true
+    ];
+
+    /**
+     * If a nullable field gets set to null, insert it here
+     *
+     * @var boolean[]
+     */
+    protected array $openAPINullablesSetToNull = [];
+
+    /**
+     * Array of property to type mappings. Used for (de)serialization
+     *
+     * @return array
+     */
+    public static function openAPITypes()
+    {
+        return self::$openAPITypes;
+    }
+
+    /**
+     * Array of property to format mappings. Used for (de)serialization
+     *
+     * @return array
+     */
+    public static function openAPIFormats()
+    {
+        return self::$openAPIFormats;
+    }
+
+    /**
+     * Array of nullable properties
+     *
+     * @return array
+     */
+    protected static function openAPINullables(): array
+    {
+        return self::$openAPINullables;
+    }
+
+    /**
+     * Array of nullable field names deliberately set to null
+     *
+     * @return boolean[]
+     */
+    private function getOpenAPINullablesSetToNull(): array
+    {
+        return $this->openAPINullablesSetToNull;
+    }
+
+    /**
+     * Setter - Array of nullable field names deliberately set to null
+     *
+     * @param boolean[] $openAPINullablesSetToNull
+     */
+    private function setOpenAPINullablesSetToNull(array $openAPINullablesSetToNull): void
+    {
+        $this->openAPINullablesSetToNull = $openAPINullablesSetToNull;
+    }
+
+    /**
+     * Checks if a property is nullable
+     *
+     * @param string $property
+     * @return bool
+     */
+    public static function isNullable(string $property): bool
+    {
+        return self::openAPINullables()[$property] ?? false;
+    }
+
+    /**
+     * Checks if a nullable property is set to null.
+     *
+     * @param string $property
+     * @return bool
+     */
+    public function isNullableSetToNull(string $property): bool
+    {
+        return in_array($property, $this->getOpenAPINullablesSetToNull(), true);
+    }
+
+    /**
+     * Array of attributes where the key is the local name,
+     * and the value is the original name
+     *
+     * @var string[]
+     */
+    protected static $attributeMap = [
+        'id' => 'id',
+        'status' => 'status',
+        'format' => 'format',
+        'progress' => 'progress',
+        'message' => 'message',
+        'title' => 'title',
+        'works' => 'works',
+        'filename' => 'filename',
+        'content_type' => 'content_type',
+        'size' => 'size',
+        'ready_at' => 'ready_at',
+        'expires_at' => 'expires_at',
+        'download_url' => 'download_url'
+    ];
+
+    /**
+     * Array of attributes to setter functions (for deserialization of responses)
+     *
+     * @var string[]
+     */
+    protected static $setters = [
+        'id' => 'setId',
+        'status' => 'setStatus',
+        'format' => 'setFormat',
+        'progress' => 'setProgress',
+        'message' => 'setMessage',
+        'title' => 'setTitle',
+        'works' => 'setWorks',
+        'filename' => 'setFilename',
+        'content_type' => 'setContentType',
+        'size' => 'setSize',
+        'ready_at' => 'setReadyAt',
+        'expires_at' => 'setExpiresAt',
+        'download_url' => 'setDownloadUrl'
+    ];
+
+    /**
+     * Array of attributes to getter functions (for serialization of requests)
+     *
+     * @var string[]
+     */
+    protected static $getters = [
+        'id' => 'getId',
+        'status' => 'getStatus',
+        'format' => 'getFormat',
+        'progress' => 'getProgress',
+        'message' => 'getMessage',
+        'title' => 'getTitle',
+        'works' => 'getWorks',
+        'filename' => 'getFilename',
+        'content_type' => 'getContentType',
+        'size' => 'getSize',
+        'ready_at' => 'getReadyAt',
+        'expires_at' => 'getExpiresAt',
+        'download_url' => 'getDownloadUrl'
+    ];
+
+    /**
+     * Array of attributes where the key is the local name,
+     * and the value is the original name
+     *
+     * @return array
+     */
+    public static function attributeMap()
+    {
+        return self::$attributeMap;
+    }
+
+    /**
+     * Array of attributes to setter functions (for deserialization of responses)
+     *
+     * @return array
+     */
+    public static function setters()
+    {
+        return self::$setters;
+    }
+
+    /**
+     * Array of attributes to getter functions (for serialization of requests)
+     *
+     * @return array
+     */
+    public static function getters()
+    {
+        return self::$getters;
+    }
+
+    /**
+     * The original name of the model.
+     *
+     * @return string
+     */
+    public function getModelName()
+    {
+        return self::$openAPIModelName;
+    }
+
+
+    /**
+     * Associative array for storing property values
+     *
+     * @var mixed[]
+     */
+    protected $container = [];
+
+    /**
+     * Constructor
+     *
+     * @param mixed[]|null $data Associated array of property values
+     *                      initializing the model
+     */
+    public function __construct(?array $data = null)
+    {
+        $this->setIfExists('id', $data ?? [], null);
+        $this->setIfExists('status', $data ?? [], null);
+        $this->setIfExists('format', $data ?? [], null);
+        $this->setIfExists('progress', $data ?? [], null);
+        $this->setIfExists('message', $data ?? [], null);
+        $this->setIfExists('title', $data ?? [], null);
+        $this->setIfExists('works', $data ?? [], null);
+        $this->setIfExists('filename', $data ?? [], null);
+        $this->setIfExists('content_type', $data ?? [], null);
+        $this->setIfExists('size', $data ?? [], null);
+        $this->setIfExists('ready_at', $data ?? [], null);
+        $this->setIfExists('expires_at', $data ?? [], null);
+        $this->setIfExists('download_url', $data ?? [], null);
+    }
+
+    /**
+     * Sets $this->container[$variableName] to the given data or to the given default Value; if $variableName
+     * is nullable and its value is set to null in the $fields array, then mark it as "set to null" in the
+     * $this->openAPINullablesSetToNull array
+     *
+     * @param string $variableName
+     * @param array  $fields
+     * @param mixed  $defaultValue
+     */
+    private function setIfExists(string $variableName, array $fields, $defaultValue): void
+    {
+        if (self::isNullable($variableName) && array_key_exists($variableName, $fields) && is_null($fields[$variableName])) {
+            $this->openAPINullablesSetToNull[] = $variableName;
+        }
+
+        $this->container[$variableName] = $fields[$variableName] ?? $defaultValue;
+    }
+
+    /**
+     * Show all the invalid properties with reasons.
+     *
+     * @return array invalid properties with reasons
+     */
+    public function listInvalidProperties()
+    {
+        $invalidProperties = [];
+
+        return $invalidProperties;
+    }
+
+    /**
+     * Validate all the properties in the model
+     * return true if all passed
+     *
+     * @return bool True if all properties are valid
+     */
+    public function valid()
+    {
+        return count($this->listInvalidProperties()) === 0;
+    }
+
+
+    /**
+     * Gets id
+     *
+     * @return string|null
+     */
+    public function getId()
+    {
+        return $this->container['id'];
+    }
+
+    /**
+     * Sets id
+     *
+     * @param string|null $id id
+     *
+     * @return self
+     */
+    public function setId($id)
+    {
+        if (is_null($id)) {
+            throw new \InvalidArgumentException('non-nullable id cannot be null');
+        }
+        $this->container['id'] = $id;
+
+        return $this;
+    }
+
+    /**
+     * Gets status
+     *
+     * @return string|null
+     */
+    public function getStatus()
+    {
+        return $this->container['status'];
+    }
+
+    /**
+     * Sets status
+     *
+     * @param string|null $status status
+     *
+     * @return self
+     */
+    public function setStatus($status)
+    {
+        if (is_null($status)) {
+            throw new \InvalidArgumentException('non-nullable status cannot be null');
+        }
+        $this->container['status'] = $status;
+
+        return $this;
+    }
+
+    /**
+     * Gets format
+     *
+     * @return string|null
+     */
+    public function getFormat()
+    {
+        return $this->container['format'];
+    }
+
+    /**
+     * Sets format
+     *
+     * @param string|null $format format
+     *
+     * @return self
+     */
+    public function setFormat($format)
+    {
+        if (is_null($format)) {
+            throw new \InvalidArgumentException('non-nullable format cannot be null');
+        }
+        $this->container['format'] = $format;
+
+        return $this;
+    }
+
+    /**
+     * Gets progress
+     *
+     * @return float|null
+     */
+    public function getProgress()
+    {
+        return $this->container['progress'];
+    }
+
+    /**
+     * Sets progress
+     *
+     * @param float|null $progress progress
+     *
+     * @return self
+     */
+    public function setProgress($progress)
+    {
+        if (is_null($progress)) {
+            throw new \InvalidArgumentException('non-nullable progress cannot be null');
+        }
+        $this->container['progress'] = $progress;
+
+        return $this;
+    }
+
+    /**
+     * Gets message
+     *
+     * @return string|null
+     */
+    public function getMessage()
+    {
+        return $this->container['message'];
+    }
+
+    /**
+     * Sets message
+     *
+     * @param string|null $message message
+     *
+     * @return self
+     */
+    public function setMessage($message)
+    {
+        if (is_null($message)) {
+            array_push($this->openAPINullablesSetToNull, 'message');
+        } else {
+            $nullablesSetToNull = $this->getOpenAPINullablesSetToNull();
+            $index = array_search('message', $nullablesSetToNull);
+            if ($index !== FALSE) {
+                unset($nullablesSetToNull[$index]);
+                $this->setOpenAPINullablesSetToNull($nullablesSetToNull);
+            }
+        }
+        $this->container['message'] = $message;
+
+        return $this;
+    }
+
+    /**
+     * Gets title
+     *
+     * @return string|null
+     */
+    public function getTitle()
+    {
+        return $this->container['title'];
+    }
+
+    /**
+     * Sets title
+     *
+     * @param string|null $title title
+     *
+     * @return self
+     */
+    public function setTitle($title)
+    {
+        if (is_null($title)) {
+            throw new \InvalidArgumentException('non-nullable title cannot be null');
+        }
+        $this->container['title'] = $title;
+
+        return $this;
+    }
+
+    /**
+     * Gets works
+     *
+     * @return int|null
+     */
+    public function getWorks()
+    {
+        return $this->container['works'];
+    }
+
+    /**
+     * Sets works
+     *
+     * @param int|null $works works
+     *
+     * @return self
+     */
+    public function setWorks($works)
+    {
+        if (is_null($works)) {
+            throw new \InvalidArgumentException('non-nullable works cannot be null');
+        }
+        $this->container['works'] = $works;
+
+        return $this;
+    }
+
+    /**
+     * Gets filename
+     *
+     * @return string|null
+     */
+    public function getFilename()
+    {
+        return $this->container['filename'];
+    }
+
+    /**
+     * Sets filename
+     *
+     * @param string|null $filename filename
+     *
+     * @return self
+     */
+    public function setFilename($filename)
+    {
+        if (is_null($filename)) {
+            throw new \InvalidArgumentException('non-nullable filename cannot be null');
+        }
+        $this->container['filename'] = $filename;
+
+        return $this;
+    }
+
+    /**
+     * Gets content_type
+     *
+     * @return string|null
+     */
+    public function getContentType()
+    {
+        return $this->container['content_type'];
+    }
+
+    /**
+     * Sets content_type
+     *
+     * @param string|null $content_type content_type
+     *
+     * @return self
+     */
+    public function setContentType($content_type)
+    {
+        if (is_null($content_type)) {
+            throw new \InvalidArgumentException('non-nullable content_type cannot be null');
+        }
+        $this->container['content_type'] = $content_type;
+
+        return $this;
+    }
+
+    /**
+     * Gets size
+     *
+     * @return int|null
+     */
+    public function getSize()
+    {
+        return $this->container['size'];
+    }
+
+    /**
+     * Sets size
+     *
+     * @param int|null $size size
+     *
+     * @return self
+     */
+    public function setSize($size)
+    {
+        if (is_null($size)) {
+            array_push($this->openAPINullablesSetToNull, 'size');
+        } else {
+            $nullablesSetToNull = $this->getOpenAPINullablesSetToNull();
+            $index = array_search('size', $nullablesSetToNull);
+            if ($index !== FALSE) {
+                unset($nullablesSetToNull[$index]);
+                $this->setOpenAPINullablesSetToNull($nullablesSetToNull);
+            }
+        }
+        $this->container['size'] = $size;
+
+        return $this;
+    }
+
+    /**
+     * Gets ready_at
+     *
+     * @return string|null
+     */
+    public function getReadyAt()
+    {
+        return $this->container['ready_at'];
+    }
+
+    /**
+     * Sets ready_at
+     *
+     * @param string|null $ready_at ready_at
+     *
+     * @return self
+     */
+    public function setReadyAt($ready_at)
+    {
+        if (is_null($ready_at)) {
+            array_push($this->openAPINullablesSetToNull, 'ready_at');
+        } else {
+            $nullablesSetToNull = $this->getOpenAPINullablesSetToNull();
+            $index = array_search('ready_at', $nullablesSetToNull);
+            if ($index !== FALSE) {
+                unset($nullablesSetToNull[$index]);
+                $this->setOpenAPINullablesSetToNull($nullablesSetToNull);
+            }
+        }
+        $this->container['ready_at'] = $ready_at;
+
+        return $this;
+    }
+
+    /**
+     * Gets expires_at
+     *
+     * @return string|null
+     */
+    public function getExpiresAt()
+    {
+        return $this->container['expires_at'];
+    }
+
+    /**
+     * Sets expires_at
+     *
+     * @param string|null $expires_at expires_at
+     *
+     * @return self
+     */
+    public function setExpiresAt($expires_at)
+    {
+        if (is_null($expires_at)) {
+            array_push($this->openAPINullablesSetToNull, 'expires_at');
+        } else {
+            $nullablesSetToNull = $this->getOpenAPINullablesSetToNull();
+            $index = array_search('expires_at', $nullablesSetToNull);
+            if ($index !== FALSE) {
+                unset($nullablesSetToNull[$index]);
+                $this->setOpenAPINullablesSetToNull($nullablesSetToNull);
+            }
+        }
+        $this->container['expires_at'] = $expires_at;
+
+        return $this;
+    }
+
+    /**
+     * Gets download_url
+     *
+     * @return string|null
+     */
+    public function getDownloadUrl()
+    {
+        return $this->container['download_url'];
+    }
+
+    /**
+     * Sets download_url
+     *
+     * @param string|null $download_url download_url
+     *
+     * @return self
+     */
+    public function setDownloadUrl($download_url)
+    {
+        if (is_null($download_url)) {
+            array_push($this->openAPINullablesSetToNull, 'download_url');
+        } else {
+            $nullablesSetToNull = $this->getOpenAPINullablesSetToNull();
+            $index = array_search('download_url', $nullablesSetToNull);
+            if ($index !== FALSE) {
+                unset($nullablesSetToNull[$index]);
+                $this->setOpenAPINullablesSetToNull($nullablesSetToNull);
+            }
+        }
+        $this->container['download_url'] = $download_url;
+
+        return $this;
+    }
+    /**
+     * Returns true if offset exists. False otherwise.
+     *
+     * @param integer|string $offset Offset
+     *
+     * @return boolean
+     */
+    public function offsetExists(mixed $offset): bool
+    {
+        return isset($this->container[$offset]);
+    }
+
+    /**
+     * Gets offset.
+     *
+     * @param integer|string $offset Offset
+     *
+     * @return mixed|null
+     */
+    #[\ReturnTypeWillChange]
+    public function offsetGet(mixed $offset)
+    {
+        return $this->container[$offset] ?? null;
+    }
+
+    /**
+     * Sets value based on offset.
+     *
+     * @param int|null $offset Offset
+     * @param mixed    $value  Value to be set
+     *
+     * @return void
+     */
+    public function offsetSet($offset, $value): void
+    {
+        if (is_null($offset)) {
+            $this->container[] = $value;
+        } else {
+            $this->container[$offset] = $value;
+        }
+    }
+
+    /**
+     * Unsets offset.
+     *
+     * @param integer|string $offset Offset
+     *
+     * @return void
+     */
+    public function offsetUnset(mixed $offset): void
+    {
+        unset($this->container[$offset]);
+    }
+
+    /**
+     * Serializes the object to a value that can be serialized natively by json_encode().
+     * @link https://www.php.net/manual/en/jsonserializable.jsonserialize.php
+     *
+     * @return mixed Returns data which can be serialized by json_encode(), which is a value
+     * of any type other than a resource.
+     */
+    #[\ReturnTypeWillChange]
+    public function jsonSerialize()
+    {
+       return ObjectSerializer::sanitizeForSerialization($this);
+    }
+
+    /**
+     * Gets the string presentation of the object
+     *
+     * @return string
+     */
+    public function __toString()
+    {
+        return json_encode(
+            ObjectSerializer::sanitizeForSerialization($this),
+            JSON_PRETTY_PRINT
+        );
+    }
+
+    /**
+     * Gets a header-safe presentation of the object
+     *
+     * @return string
+     */
+    public function toHeaderValue()
+    {
+        return json_encode(ObjectSerializer::sanitizeForSerialization($this));
+    }
+}
+
+

+ 625 - 0
api-test/client/lib/Model/PostApiV3TipitakaExportsRequest.php

@@ -0,0 +1,625 @@
+<?php
+/**
+ * PostApiV3TipitakaExportsRequest
+ *
+ * PHP version 8.1
+ *
+ * @category Class
+ * @package  WikipaliApi
+ * @author   OpenAPI Generator team
+ * @link     https://openapi-generator.tech
+ */
+
+/**
+ * MINT API
+ *
+ * International Academy Of Pali Tipitaka(国际巴利三藏学院)  由 `php openapi/scripts/generate.php` 依据 api-v13 的路由与控制器源码生成。 响应统一封装为 `{ok, message, data}`;`ok=false` 时 `message` 为错误信息。
+ *
+ * The version of the OpenAPI document: 1.0.0
+ * Generated by: https://openapi-generator.tech
+ * Generator version: 7.25.0
+ */
+
+/**
+ * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
+ * https://openapi-generator.tech
+ * Do not edit the class manually.
+ */
+
+namespace WikipaliApi\Model;
+
+use \ArrayAccess;
+use \WikipaliApi\ObjectSerializer;
+
+/**
+ * PostApiV3TipitakaExportsRequest Class Doc Comment
+ *
+ * @category Class
+ * @package  WikipaliApi
+ * @author   OpenAPI Generator team
+ * @link     https://openapi-generator.tech
+ * @implements \ArrayAccess<string, mixed>
+ */
+class PostApiV3TipitakaExportsRequest implements ModelInterface, ArrayAccess, \JsonSerializable
+{
+    public const DISCRIMINATOR = null;
+
+    /**
+     * The original name of the model.
+     *
+     * @var string
+     */
+    protected static $openAPIModelName = 'post_api_v3_tipitaka_exports_request';
+
+    /**
+     * Array of property to type mappings. Used for (de)serialization
+     *
+     * @var string[]
+     */
+    protected static $openAPITypes = [
+        'channel' => 'string',
+        'work' => 'int',
+        'book' => 'int',
+        'para' => 'int',
+        'category' => 'int',
+        'format' => 'string'
+    ];
+
+    /**
+     * Array of property to format mappings. Used for (de)serialization
+     *
+     * @var string[]
+     * @phpstan-var array<string, string|null>
+     * @psalm-var array<string, string|null>
+     */
+    protected static $openAPIFormats = [
+        'channel' => null,
+        'work' => null,
+        'book' => null,
+        'para' => null,
+        'category' => null,
+        'format' => null
+    ];
+
+    /**
+     * Array of nullable properties. Used for (de)serialization
+     *
+     * @var boolean[]
+     */
+    protected static array $openAPINullables = [
+        'channel' => false,
+        'work' => false,
+        'book' => false,
+        'para' => false,
+        'category' => false,
+        'format' => false
+    ];
+
+    /**
+     * If a nullable field gets set to null, insert it here
+     *
+     * @var boolean[]
+     */
+    protected array $openAPINullablesSetToNull = [];
+
+    /**
+     * Array of property to type mappings. Used for (de)serialization
+     *
+     * @return array
+     */
+    public static function openAPITypes()
+    {
+        return self::$openAPITypes;
+    }
+
+    /**
+     * Array of property to format mappings. Used for (de)serialization
+     *
+     * @return array
+     */
+    public static function openAPIFormats()
+    {
+        return self::$openAPIFormats;
+    }
+
+    /**
+     * Array of nullable properties
+     *
+     * @return array
+     */
+    protected static function openAPINullables(): array
+    {
+        return self::$openAPINullables;
+    }
+
+    /**
+     * Array of nullable field names deliberately set to null
+     *
+     * @return boolean[]
+     */
+    private function getOpenAPINullablesSetToNull(): array
+    {
+        return $this->openAPINullablesSetToNull;
+    }
+
+    /**
+     * Setter - Array of nullable field names deliberately set to null
+     *
+     * @param boolean[] $openAPINullablesSetToNull
+     */
+    private function setOpenAPINullablesSetToNull(array $openAPINullablesSetToNull): void
+    {
+        $this->openAPINullablesSetToNull = $openAPINullablesSetToNull;
+    }
+
+    /**
+     * Checks if a property is nullable
+     *
+     * @param string $property
+     * @return bool
+     */
+    public static function isNullable(string $property): bool
+    {
+        return self::openAPINullables()[$property] ?? false;
+    }
+
+    /**
+     * Checks if a nullable property is set to null.
+     *
+     * @param string $property
+     * @return bool
+     */
+    public function isNullableSetToNull(string $property): bool
+    {
+        return in_array($property, $this->getOpenAPINullablesSetToNull(), true);
+    }
+
+    /**
+     * Array of attributes where the key is the local name,
+     * and the value is the original name
+     *
+     * @var string[]
+     */
+    protected static $attributeMap = [
+        'channel' => 'channel',
+        'work' => 'work',
+        'book' => 'book',
+        'para' => 'para',
+        'category' => 'category',
+        'format' => 'format'
+    ];
+
+    /**
+     * Array of attributes to setter functions (for deserialization of responses)
+     *
+     * @var string[]
+     */
+    protected static $setters = [
+        'channel' => 'setChannel',
+        'work' => 'setWork',
+        'book' => 'setBook',
+        'para' => 'setPara',
+        'category' => 'setCategory',
+        'format' => 'setFormat'
+    ];
+
+    /**
+     * Array of attributes to getter functions (for serialization of requests)
+     *
+     * @var string[]
+     */
+    protected static $getters = [
+        'channel' => 'getChannel',
+        'work' => 'getWork',
+        'book' => 'getBook',
+        'para' => 'getPara',
+        'category' => 'getCategory',
+        'format' => 'getFormat'
+    ];
+
+    /**
+     * Array of attributes where the key is the local name,
+     * and the value is the original name
+     *
+     * @return array
+     */
+    public static function attributeMap()
+    {
+        return self::$attributeMap;
+    }
+
+    /**
+     * Array of attributes to setter functions (for deserialization of responses)
+     *
+     * @return array
+     */
+    public static function setters()
+    {
+        return self::$setters;
+    }
+
+    /**
+     * Array of attributes to getter functions (for serialization of requests)
+     *
+     * @return array
+     */
+    public static function getters()
+    {
+        return self::$getters;
+    }
+
+    /**
+     * The original name of the model.
+     *
+     * @return string
+     */
+    public function getModelName()
+    {
+        return self::$openAPIModelName;
+    }
+
+    public const FORMAT_HTML = 'html';
+    public const FORMAT_MARKDOWN = 'markdown';
+    public const FORMAT_EPUB = 'epub';
+    public const FORMAT_DOCX = 'docx';
+    public const FORMAT_OFFLINE = 'offline';
+
+    /**
+     * Gets allowable values of the enum
+     *
+     * @return string[]
+     */
+    public function getFormatAllowableValues()
+    {
+        return [
+            self::FORMAT_HTML,
+            self::FORMAT_MARKDOWN,
+            self::FORMAT_EPUB,
+            self::FORMAT_DOCX,
+            self::FORMAT_OFFLINE,
+        ];
+    }
+
+    /**
+     * Associative array for storing property values
+     *
+     * @var mixed[]
+     */
+    protected $container = [];
+
+    /**
+     * Constructor
+     *
+     * @param mixed[]|null $data Associated array of property values
+     *                      initializing the model
+     */
+    public function __construct(?array $data = null)
+    {
+        $this->setIfExists('channel', $data ?? [], null);
+        $this->setIfExists('work', $data ?? [], null);
+        $this->setIfExists('book', $data ?? [], null);
+        $this->setIfExists('para', $data ?? [], null);
+        $this->setIfExists('category', $data ?? [], null);
+        $this->setIfExists('format', $data ?? [], null);
+    }
+
+    /**
+     * Sets $this->container[$variableName] to the given data or to the given default Value; if $variableName
+     * is nullable and its value is set to null in the $fields array, then mark it as "set to null" in the
+     * $this->openAPINullablesSetToNull array
+     *
+     * @param string $variableName
+     * @param array  $fields
+     * @param mixed  $defaultValue
+     */
+    private function setIfExists(string $variableName, array $fields, $defaultValue): void
+    {
+        if (self::isNullable($variableName) && array_key_exists($variableName, $fields) && is_null($fields[$variableName])) {
+            $this->openAPINullablesSetToNull[] = $variableName;
+        }
+
+        $this->container[$variableName] = $fields[$variableName] ?? $defaultValue;
+    }
+
+    /**
+     * Show all the invalid properties with reasons.
+     *
+     * @return array invalid properties with reasons
+     */
+    public function listInvalidProperties()
+    {
+        $invalidProperties = [];
+
+        if ($this->container['channel'] === null) {
+            $invalidProperties[] = "'channel' can't be null";
+        }
+        if ($this->container['format'] === null) {
+            $invalidProperties[] = "'format' can't be null";
+        }
+        $allowedValues = $this->getFormatAllowableValues();
+        if (!is_null($this->container['format']) && !in_array($this->container['format'], $allowedValues, true)) {
+            $invalidProperties[] = sprintf(
+                "invalid value '%s' for 'format', must be one of '%s'",
+                $this->container['format'],
+                implode("', '", $allowedValues)
+            );
+        }
+
+        return $invalidProperties;
+    }
+
+    /**
+     * Validate all the properties in the model
+     * return true if all passed
+     *
+     * @return bool True if all properties are valid
+     */
+    public function valid()
+    {
+        return count($this->listInvalidProperties()) === 0;
+    }
+
+
+    /**
+     * Gets channel
+     *
+     * @return string
+     */
+    public function getChannel()
+    {
+        return $this->container['channel'];
+    }
+
+    /**
+     * Sets channel
+     *
+     * @param string $channel channel uid
+     *
+     * @return self
+     */
+    public function setChannel($channel)
+    {
+        if (is_null($channel)) {
+            throw new \InvalidArgumentException('non-nullable channel cannot be null');
+        }
+        $this->container['channel'] = $channel;
+
+        return $this;
+    }
+
+    /**
+     * Gets work
+     *
+     * @return int|null
+     */
+    public function getWork()
+    {
+        return $this->container['work'];
+    }
+
+    /**
+     * Sets work
+     *
+     * @param int|null $work 作品(library 作品页 URL 里的 sn)。作品、category 只能给一个,都不给 = 整个 channel
+     *
+     * @return self
+     */
+    public function setWork($work)
+    {
+        if (is_null($work)) {
+            throw new \InvalidArgumentException('non-nullable work cannot be null');
+        }
+        $this->container['work'] = $work;
+
+        return $this;
+    }
+
+    /**
+     * Gets book
+     *
+     * @return int|null
+     */
+    public function getBook()
+    {
+        return $this->container['book'];
+    }
+
+    /**
+     * Sets book
+     *
+     * @param int|null $book 用坐标指定作品:book + para 所在的那部作品(mobile 用,它不知道 sn)。与 para 同时给
+     *
+     * @return self
+     */
+    public function setBook($book)
+    {
+        if (is_null($book)) {
+            throw new \InvalidArgumentException('non-nullable book cannot be null');
+        }
+        $this->container['book'] = $book;
+
+        return $this;
+    }
+
+    /**
+     * Gets para
+     *
+     * @return int|null
+     */
+    public function getPara()
+    {
+        return $this->container['para'];
+    }
+
+    /**
+     * Sets para
+     *
+     * @param int|null $para 与 book 同时给,作品里的任一段落号(通常是作品起始段)
+     *
+     * @return self
+     */
+    public function setPara($para)
+    {
+        if (is_null($para)) {
+            throw new \InvalidArgumentException('non-nullable para cannot be null');
+        }
+        $this->container['para'] = $para;
+
+        return $this;
+    }
+
+    /**
+     * Gets category
+     *
+     * @return int|null
+     */
+    public function getCategory()
+    {
+        return $this->container['category'];
+    }
+
+    /**
+     * Sets category
+     *
+     * @param int|null $category 分类 id(library 分类页 URL 里的 id),含后代分类
+     *
+     * @return self
+     */
+    public function setCategory($category)
+    {
+        if (is_null($category)) {
+            throw new \InvalidArgumentException('non-nullable category cannot be null');
+        }
+        $this->container['category'] = $category;
+
+        return $this;
+    }
+
+    /**
+     * Gets format
+     *
+     * @return string
+     */
+    public function getFormat()
+    {
+        return $this->container['format'];
+    }
+
+    /**
+     * Sets format
+     *
+     * @param string $format 文件格式
+     *
+     * @return self
+     */
+    public function setFormat($format)
+    {
+        if (is_null($format)) {
+            throw new \InvalidArgumentException('non-nullable format cannot be null');
+        }
+        $allowedValues = $this->getFormatAllowableValues();
+        if (!in_array($format, $allowedValues, true)) {
+            throw new \InvalidArgumentException(
+                sprintf(
+                    "Invalid value '%s' for 'format', must be one of '%s'",
+                    $format,
+                    implode("', '", $allowedValues)
+                )
+            );
+        }
+        $this->container['format'] = $format;
+
+        return $this;
+    }
+    /**
+     * Returns true if offset exists. False otherwise.
+     *
+     * @param integer|string $offset Offset
+     *
+     * @return boolean
+     */
+    public function offsetExists(mixed $offset): bool
+    {
+        return isset($this->container[$offset]);
+    }
+
+    /**
+     * Gets offset.
+     *
+     * @param integer|string $offset Offset
+     *
+     * @return mixed|null
+     */
+    #[\ReturnTypeWillChange]
+    public function offsetGet(mixed $offset)
+    {
+        return $this->container[$offset] ?? null;
+    }
+
+    /**
+     * Sets value based on offset.
+     *
+     * @param int|null $offset Offset
+     * @param mixed    $value  Value to be set
+     *
+     * @return void
+     */
+    public function offsetSet($offset, $value): void
+    {
+        if (is_null($offset)) {
+            $this->container[] = $value;
+        } else {
+            $this->container[$offset] = $value;
+        }
+    }
+
+    /**
+     * Unsets offset.
+     *
+     * @param integer|string $offset Offset
+     *
+     * @return void
+     */
+    public function offsetUnset(mixed $offset): void
+    {
+        unset($this->container[$offset]);
+    }
+
+    /**
+     * Serializes the object to a value that can be serialized natively by json_encode().
+     * @link https://www.php.net/manual/en/jsonserializable.jsonserialize.php
+     *
+     * @return mixed Returns data which can be serialized by json_encode(), which is a value
+     * of any type other than a resource.
+     */
+    #[\ReturnTypeWillChange]
+    public function jsonSerialize()
+    {
+       return ObjectSerializer::sanitizeForSerialization($this);
+    }
+
+    /**
+     * Gets the string presentation of the object
+     *
+     * @return string
+     */
+    public function __toString()
+    {
+        return json_encode(
+            ObjectSerializer::sanitizeForSerialization($this),
+            JSON_PRETTY_PRINT
+        );
+    }
+
+    /**
+     * Gets a header-safe presentation of the object
+     *
+     * @return string
+     */
+    public function toHeaderValue()
+    {
+        return json_encode(ObjectSerializer::sanitizeForSerialization($this));
+    }
+}
+
+

+ 7 - 0
api-test/config.local.example.php

@@ -20,6 +20,11 @@ $servers = [
         'username' => 'test',
         'password' => null,
         'token' => null,                       // 填了就直接用,跳过登录
+        // 管理员账号:只给 /v3/admin/* 用例用,与上面的测试账号分开;不配则 SKIP。
+        // 生产上只跑只读用例,写入用例只在 config.php 的 admin_write_servers 上跑。
+        'admin_username' => null,
+        'admin_password' => null,
+        'admin_token' => null,
         'fixtures' => [
             // 讨论写用例挂的句子:必须在测试账号自己的 channel 里、由测试账号编辑过
             // 'discussion_sentence' => 'ee5259be-5d1e-4408-a2a6-566a5773eef1',
@@ -61,6 +66,8 @@ $servers = [
     'next-cn' => [
         'username' => null,
         'password' => null,
+        'admin_username' => null,
+        'admin_password' => null,
         'token' => null,
         'fixtures' => [],
     ],

+ 13 - 0
api-test/config.php

@@ -26,6 +26,13 @@
  *
  * 写操作(POST/DELETE)在**所有服务器上都真实执行**,包括 prod——会产生垃圾数据,
  * 由测试账号定期清理。
+ *
+ * 管理员账号(/v3/admin/* 用例专用,与上面的测试账号分开):
+ *   admin_token > admin_username/admin_password 现登录;来源优先级同上
+ *   (--admin-token / --admin-username / --admin-password > API_TEST_ADMIN_* > servers[alias])。
+ *   没配就 SKIP 管理员用例。只在用到时才登录,不占测试账号的登录限流。
+ *   管理员**只读**;admin 路由的写入用例只在 `admin_write_servers` 里的服务器上跑,
+ *   其余(生产、生产预览、未登记的完整 URL)一律 SKIP。
  */
 
 $local = is_file(__DIR__ . '/config.local.php') ? require __DIR__ . '/config.local.php' : [];
@@ -47,10 +54,16 @@ return [
     'username' => $local['username'] ?? null,
     'password' => $local['password'] ?? null,
     'fixtures' => $local['fixtures'] ?? [],
+    'admin_token' => $local['admin_token'] ?? null,
+    'admin_username' => $local['admin_username'] ?? null,
+    'admin_password' => $local['admin_password'] ?? null,
 
     // 新分组结构:per-server 配置块(username/password/token/fixtures),
     // run.php 解析出实际 server 后从这里选对应那套。
     'local_servers' => $local['servers'] ?? null,
 
+    // 允许跑 admin 路由写入用例的服务器(白名单,按 alias)。不在这里的一律只读。
+    'admin_write_servers' => ['local', 'staging'],
+
     'timeout' => 20,
 ];

+ 6 - 1
api-test/fixtures.php

@@ -26,7 +26,7 @@ return [
     'cs_para'   => 4,
 
     // 搜索关键词(search/{id} 的 200 用例从它的检索结果里取文档 id)
-    'search_q'       => 'dukkha',
+    'search_q'       => 'nama',
 
     // discussions 写用例挂的句子:放在测试账号自己的 channel 里、由测试账号编辑,
     // 这样即便有通知也只发给自己(用例本身还会带 notify=false)。换环境时按需覆盖。
@@ -42,6 +42,11 @@ return [
     'group_name' => 'api-test 团队',
     'group_member_username' => 'test162',
 
+    // tipitaka-exports(三藏下载):一个公开 channel 与它收录的一部小作品(library 作品页 URL 里的 sn)。
+    // 用例会真的排队生成并等 worker 做完(mq:export.tipitaka 要在跑),文件留在 Redis 里 7 天,不清理
+    'export_channel' => 'a19eaf75-c63f-4b84-8125-1bce18311e23',
+    'export_work' => 276,
+
     // 一个已注册账号的邮箱(email-certifications 的「已注册」用例;只校验、不发信)。
     // 留空则该用例 SKIP。
     'registered_email' => getenv('API_TEST_REGISTERED_EMAIL') ?: null,

+ 15 - 1
api-test/run.php

@@ -4,7 +4,8 @@
  * api-test 入口:装配配置 → 加载用例 → 运行 → 报告。
  *
  * 用法:
- *   php run.php [--server=<alias|URL>] [--token=<bearer>] [--username=<u> --password=<p>] [--filter=<子串>] [--list]
+ *   php run.php [--server=<alias|URL>] [--token=<bearer>] [--username=<u> --password=<p>]
+ *               [--admin-token=<bearer>] [--admin-username=<u> --admin-password=<p>] [--filter=<子串>] [--list]
  *
  * 例:
  *   php run.php                          # 默认 local
@@ -72,12 +73,19 @@ if (is_array($localServers) && $serverKey !== null && isset($localServers[$serve
     $config['username'] = $block['username'] ?? $config['username'];
     $config['password'] = $block['password'] ?? $config['password'];
     $config['fixtures'] = $block['fixtures'] ?? $config['fixtures'];
+    foreach (['admin_token', 'admin_username', 'admin_password'] as $key) {
+        $config[$key] = $block[$key] ?? $config[$key];
+    }
 }
+$config['server_key'] = $serverKey;
 
 // 环境变量覆盖(高于 config.local.php,低于命令行)
 $config['token'] = getenv('API_TEST_TOKEN') ?: $config['token'];
 $config['username'] = getenv('API_TEST_USERNAME') ?: $config['username'];
 $config['password'] = getenv('API_TEST_PASSWORD') ?: $config['password'];
+$config['admin_token'] = getenv('API_TEST_ADMIN_TOKEN') ?: $config['admin_token'];
+$config['admin_username'] = getenv('API_TEST_ADMIN_USERNAME') ?: $config['admin_username'];
+$config['admin_password'] = getenv('API_TEST_ADMIN_PASSWORD') ?: $config['admin_password'];
 
 // 命令行覆盖(最高优先级)
 if (is_string($opts['token'] ?? null) && $opts['token'] !== '') {
@@ -89,6 +97,12 @@ if (is_string($opts['username'] ?? null) && $opts['username'] !== '') {
 if (is_string($opts['password'] ?? null) && $opts['password'] !== '') {
     $config['password'] = $opts['password'];
 }
+foreach (['admin_token', 'admin_username', 'admin_password'] as $key) {
+    $flag = str_replace('_', '-', $key);
+    if (is_string($opts[$flag] ?? null) && $opts[$flag] !== '') {
+        $config[$key] = $opts[$flag];
+    }
+}
 
 $GLOBALS['config'] = $config;
 $GLOBALS['fixtures'] = array_replace(require __DIR__ . '/fixtures.php', $config['fixtures']);

+ 55 - 0
api-test/src/bootstrap.php

@@ -164,6 +164,61 @@ function required_token(): string
     return $token;
 }
 
+/**
+ * 取管理员 token(/v3/admin/* 用例专用,与测试账号分开)。
+ * 没配管理员账号 → SKIP;配了但登录不上、或 /v3/me 的 roles 里没有 administrator / root → FAIL。
+ * 第一次调用时才登录,结果缓存到本次运行结束。
+ */
+function admin_token(): string
+{
+    static $token = null, $error = null;
+    if ($token !== null) {
+        return $token;
+    }
+    if ($error !== null) {
+        throw $error;   // 登录失败只试一次,免得每条用例都去撞登录限流
+    }
+    try {
+        return $token = resolve_admin_token();
+    } catch (Fail|Skip $e) {
+        throw $error = $e;
+    }
+}
+
+function resolve_admin_token(): string
+{
+    $cfg = config();
+    $candidate = $cfg['admin_token'] ?? null;
+    if (! $candidate) {
+        if (! ($cfg['admin_username'] ?? null) || ! ($cfg['admin_password'] ?? null)) {
+            skip('没配管理员账号(admin_username/admin_password 或 admin_token)');
+        }
+        $candidate = login($cfg['admin_username'], $cfg['admin_password']);
+    }
+    $me = raw('GET', '/v3/me', null, null, $candidate);
+    assert_status(200, $me, '管理员账号 /v3/me');
+    $roles = $me['body']['data']['roles'] ?? [];
+    if (! array_intersect(['administrator', 'root'], $roles)) {
+        fail('配置的管理员账号没有 administrator / root 角色');
+    }
+
+    return $candidate;
+}
+
+/**
+ * 取管理员 token,用于 admin 路由的写入用例。
+ * 目标服务器不在 config.php 的 admin_write_servers 白名单里(生产等)→ SKIP,管理员在那里只读。
+ */
+function admin_write_token(): string
+{
+    $cfg = config();
+    if (! in_array($cfg['server_key'] ?? null, $cfg['admin_write_servers'] ?? [], true)) {
+        skip('该服务器禁止 admin 写入(只在 ' . implode(' / ', $cfg['admin_write_servers'] ?? []) . ' 上跑)');
+    }
+
+    return admin_token();
+}
+
 /* ---- 断言 ---- */
 
 function assert_status(int $expected, array $res, string $what): void

+ 3 - 3
api-v13/app/Console/Commands/ExportAiTrainingData.php

@@ -2,10 +2,10 @@
 
 namespace App\Console\Commands;
 
-use App\Http\Api\ChannelApi;
 use App\Http\Api\MdRender;
 use App\Models\PaliSentence;
 use App\Models\Sentence;
+use App\Services\ChannelService;
 use App\Services\PaliTextService;
 use Illuminate\Console\Command;
 use Illuminate\Support\Facades\File;
@@ -45,7 +45,7 @@ class ExportAiTrainingData extends Command
      *
      * @return int
      */
-    public function handle()
+    public function handle(ChannelService $channelService)
     {
         Log::info('task export offline sentence-table start');
         // 创建文件夹
@@ -95,7 +95,7 @@ class ExportAiTrainingData extends Command
                 break;
             }
             fwrite($fpIndex, "# {$channel}\n");
-            $channelInfo = ChannelApi::getById($channel);
+            $channelInfo = $channelService->summary($channel);
             if ($channelInfo) {
                 fwrite($fpIndex, "- 版本名称:{$channelInfo['name']}\n");
                 fwrite($fpIndex, "- 语言:{$channelInfo['lang']}\n");

+ 5 - 5
api-v13/app/Console/Commands/ExportChapter.php

@@ -2,11 +2,11 @@
 
 namespace App\Console\Commands;
 
-use App\Http\Api\ChannelApi;
 use App\Http\Api\MdRender;
 use App\Models\PaliText;
 use App\Models\ProgressChapter;
 use App\Models\Sentence;
+use App\Services\ChannelService;
 use App\Tools\Export;
 use App\Tools\ExportDownload;
 use App\Tools\Tools;
@@ -47,7 +47,7 @@ class ExportChapter extends Command
      *
      * @return int
      */
-    public function handle()
+    public function handle(ChannelService $channelService)
     {
         $this->info('task export chapter start');
         Log::debug('task export chapter start');
@@ -79,7 +79,7 @@ class ExportChapter extends Command
         $renderFormat = 'markdown';
 
         // 获取原文channel
-        $orgChannelId = ChannelApi::getSysChannel('_System_Pali_VRI_');
+        $orgChannelId = $channelService->systemUid('_System_Pali_VRI_');
 
         $tranChannelsId = explode('_', $this->argument('channel'));
 
@@ -88,8 +88,8 @@ class ExportChapter extends Command
         $channels = [];
         $channelsIndex = [];
         foreach ($channelsId as $key => $id) {
-            $channels[] = ChannelApi::getById($id);
-            $channelsIndex[$id] = ChannelApi::getById($id);
+            $channels[] = $channelService->summary($id);
+            $channelsIndex[$id] = $channelService->summary($id);
         }
 
         $bookMeta = [];

+ 3 - 3
api-v13/app/Console/Commands/ExportDiscussion.php

@@ -2,7 +2,7 @@
 
 namespace App\Console\Commands;
 
-use App\Http\Api\ChannelApi;
+use App\Services\ChannelService;
 use Carbon\Carbon;
 use Illuminate\Console\Command;
 use Illuminate\Support\Collection;
@@ -33,14 +33,14 @@ class ExportDiscussion extends Command
     /**
      * Execute the console command.
      */
-    public function handle(): int
+    public function handle(ChannelService $channelService): int
     {
         $editorUid = $this->argument('editor');
 
         $this->info("Fetching discussions for editor: {$editorUid}");
 
         // 1. 获取巴利原文 channel_uid
-        $this->orgChannelId = ChannelApi::getSysChannel('_System_Pali_VRI_');
+        $this->orgChannelId = $channelService->systemUid('_System_Pali_VRI_');
         if (! $this->orgChannelId) {
             $this->error('Failed to retrieve Pali source channel ID.');
 

+ 4 - 4
api-v13/app/Console/Commands/ExportSentence.php

@@ -2,10 +2,10 @@
 
 namespace App\Console\Commands;
 
-use App\Http\Api\ChannelApi;
 use App\Http\Api\MdRender;
 use App\Models\Channel;
 use App\Models\Sentence;
+use App\Services\ChannelService;
 use App\Tools\Markdown;
 use App\Tools\Tools;
 use Illuminate\Console\Command;
@@ -43,7 +43,7 @@ class ExportSentence extends Command
      *
      * @return int
      */
-    public function handle()
+    public function handle(ChannelService $channelService)
     {
         Log::debug('task export offline sentence-table start');
         if (Tools::isStop()) {
@@ -59,7 +59,7 @@ class ExportSentence extends Command
             $channel_type = $this->option('type');
             $file_suf = $channel_type;
             if ($channel_type === 'original') {
-                $pali_channel = ChannelApi::getSysChannel('_System_Pali_VRI_');
+                $pali_channel = $channelService->systemUid('_System_Pali_VRI_');
                 if ($pali_channel === false) {
                     return 0;
                 }
@@ -112,7 +112,7 @@ class ExportSentence extends Command
         ])->cursor();
         foreach ($srcDb as $sent) {
             if (Str::isUuid($sent->channel_uid)) {
-                $channel = ChannelApi::getById($sent->channel_uid);
+                $channel = $channelService->summary($sent->channel_uid);
                 $currData = [
                     $sent->book_id,
                     $sent->paragraph,

+ 4 - 3
api-v13/app/Console/Commands/ExtractPaliTerm.php

@@ -4,10 +4,10 @@ namespace App\Console\Commands;
 
 use App\Facades\RedisCache;
 use App\Helpers\LlmResponseParser;
-use App\Http\Api\ChannelApi;
 use App\Http\Resources\AiModelResource;
 use App\Models\PaliText;
 use App\Services\AIModelService;
+use App\Services\ChannelService;
 use App\Services\OpenAIService;
 use App\Services\SentenceService;
 use App\Services\TermService;
@@ -69,6 +69,7 @@ class ExtractPaliTerm extends Command
     protected ?bool $thinking = null;
 
     public function __construct(
+        protected ChannelService $channelService,
         protected AIModelService $modelService,
         protected OpenAIService $openAIService,
         protected SentenceService $sentenceService,
@@ -97,13 +98,13 @@ class ExtractPaliTerm extends Command
         }
 
         // ---------- 保存目标 channel ----------
-        $channelId = ChannelApi::getSysChannel('_system_glossary_');
+        $channelId = $this->channelService->systemUid('_system_glossary_');
         if (! $channelId) {
             $this->error('system glossary channel "_system_glossary_" not found');
 
             return 1;
         }
-        $this->glossaryChannel = ChannelApi::getById($channelId);
+        $this->glossaryChannel = $this->channelService->summary($channelId);
         Log::info('extract:pali.term glossary channel', ['channel' => $channelId]);
 
         // ---------- 完整术语表(一次性加载,所有 chapter 共用)----------

+ 4 - 3
api-v13/app/Console/Commands/IndexTipitaka.php

@@ -3,10 +3,10 @@
 namespace App\Console\Commands;
 
 use App\Facades\RedisCache;
-use App\Http\Api\ChannelApi;
 use App\Models\PaliText;
 use App\Models\ProgressChapter;
 use App\Models\Sentence;
+use App\Services\ChannelService;
 use App\Services\OpenSearchService;
 use App\Services\PaliContentService;
 use App\Services\SearchPaliDataService;
@@ -49,6 +49,7 @@ class IndexTipitaka extends Command
      * @return void
      */
     public function __construct(
+        protected ChannelService $channelService,
         protected SearchPaliDataService $searchPaliDataService,
         protected OpenSearchService $openSearchService,
         protected SummaryService $summaryService,
@@ -307,7 +308,7 @@ class IndexTipitaka extends Command
             foreach ($channels as $channel) {
                 $display = [];
                 $content = [];
-                $channelInfo = ChannelApi::getById($channel->channel_uid);
+                $channelInfo = $this->channelService->summary($channel->channel_uid);
                 if (! $channelInfo) {
                     Log::error('invalid channel', ['id' => $channel->channel_uid]);
 
@@ -364,7 +365,7 @@ class IndexTipitaka extends Command
             ->where('para', $param['para'])
             ->where('channel_id', $param['channel'])
             ->first();
-        $channel = ChannelApi::getById($param['channel']);
+        $channel = $this->channelService->summary($param['channel']);
         $docId = "tipitaka_chapter_{$param['book']}-{$param['para']}_{$param['channel']}";
         $document = [
             'id' => $docId,

+ 3 - 3
api-v13/app/Console/Commands/InitCs6sentence.php

@@ -2,10 +2,10 @@
 
 namespace App\Console\Commands;
 
-use App\Http\Api\ChannelApi;
 use App\Models\PaliSentence;
 use App\Models\Sentence;
 use App\Models\WbwTemplate;
+use App\Services\ChannelService;
 use App\Tools\Tools;
 use Illuminate\Console\Command;
 use Illuminate\Support\Str;
@@ -41,13 +41,13 @@ class InitCs6sentence extends Command
      *
      * @return int
      */
-    public function handle()
+    public function handle(ChannelService $channelService)
     {
         if (Tools::isStop()) {
             return 0;
         }
         $start = time();
-        $channelId = ChannelApi::getSysChannel('_System_Pali_VRI_');
+        $channelId = $channelService->systemUid('_System_Pali_VRI_');
         if ($channelId === false) {
             $this->error('no channel');
 

+ 3 - 0
api-v13/app/Console/Commands/InstallPaliText.php

@@ -3,6 +3,7 @@
 namespace App\Console\Commands;
 
 use App\Models\PaliText;
+use App\Services\V3\PaliTextService;
 use App\Tools\Tools;
 use Illuminate\Console\Command;
 use Illuminate\Support\Facades\DB;
@@ -143,6 +144,8 @@ class InstallPaliText extends Command
                 }
 
             });
+            // 阅读、导出缓存的 pali_texts(按书缓存一个月)
+            app(PaliTextService::class)->forgetBook((int) $from);
 
             $bar->advance();
         }

+ 48 - 0
api-v13/app/Console/Commands/MqExportTipitaka.php

@@ -0,0 +1,48 @@
+<?php
+
+namespace App\Console\Commands;
+
+use App\Http\Api\Mq;
+use App\Services\V3\TipitakaExportQueue;
+use App\Services\V3\TipitakaExportService;
+use Illuminate\Console\Attributes\Description;
+use Illuminate\Console\Attributes\Signature;
+use Illuminate\Console\Command;
+
+/**
+ * 三藏下载(`/v3/tipitaka-exports`)的 worker:生成文件存进 Redis。单部作品的队列 `export_tipitaka`
+ * 与打包的队列 `export_tipitaka_bulk`(`--bulk`)各跑一个,大打包不会堵住单部作品的下载。
+ *
+ * 一次只处理一条(prefetch 1),生成完才 ack。最大的 channel 整个打包约 4 分钟(实测 cs6 html 217 秒,2026-11-22),
+ * RabbitMQ 的 `consumer_timeout` 必须比它长(开发机 rabbitmq.conf 里是 92 小时),否则
+ * 跑到一半连接被服务端断开。失败只写进导出状态(status = failed),用户可以重新发起。
+ *
+ * 不走队列直接生成一份(排查用):`php artisan mq:export.tipitaka --id=<导出 id>`。
+ */
+#[Signature('mq:export.tipitaka {--bulk : 消费打包队列 export_tipitaka_bulk} {--id= : 不连队列,直接生成这一份}')]
+#[Description('三藏下载:生成导出文件(队列 export_tipitaka / export_tipitaka_bulk)')]
+class MqExportTipitaka extends Command
+{
+    public function handle(TipitakaExportService $exports): int
+    {
+        if ($id = $this->option('id')) {
+            $exports->run((string) $id);
+
+            return self::SUCCESS;
+        }
+
+        $queue = $this->option('bulk') ? TipitakaExportQueue::BULK_QUEUE : TipitakaExportQueue::QUEUE;
+        $this->info(" [*] Waiting for {$queue}. To exit press CTRL+C");
+        Mq::worker($queue, function ($message) use ($exports) {
+            if (! is_object($message) || ! is_string($message->id ?? null)) {
+                return 1;
+            }
+            $exports->run($message->id);
+            $this->info("done {$message->id}");
+
+            return 0;
+        });
+
+        return self::SUCCESS;
+    }
+}

+ 4 - 3
api-v13/app/Console/Commands/UpgradeAITranslation.php

@@ -4,7 +4,6 @@ namespace App\Console\Commands;
 
 use App\Facades\RedisCache;
 use App\Helpers\LlmResponseParser;
-use App\Http\Api\ChannelApi;
 use App\Http\Resources\AiModelResource;
 use App\Models\PaliText;
 use App\Models\Sentence;
@@ -12,6 +11,7 @@ use App\Services\AIAssistant\NissayaTranslateService;
 use App\Services\AIAssistant\PaliTranslateService;
 use App\Services\AIModelService;
 use App\Services\AuthService;
+use App\Services\ChannelService;
 use App\Services\OpenAIService;
 use App\Services\SentenceService;
 use Illuminate\Console\Command;
@@ -74,6 +74,7 @@ class UpgradeAITranslation extends Command
      * @return void
      */
     public function __construct(
+        protected ChannelService $channelService,
         protected AIModelService $modelService,
         protected SentenceService $sentenceService,
         protected OpenAIService $openAIService,
@@ -108,7 +109,7 @@ class UpgradeAITranslation extends Command
         $this->modelToken = AuthService::getUserToken($this->model['uid']);
 
         // channel
-        $this->workChannel = ChannelApi::getById($this->argument('channel'));
+        $this->workChannel = $this->channelService->summary($this->argument('channel'));
         // 需要判断输入channel 与翻译类型是否一致 nissaya -> nissaya channel
         if ($this->workChannel['type'] !== $this->argument('type')) {
             $this->error('channel type not match request '.$this->argument('type').' input is '.$this->workChannel['type']);
@@ -265,7 +266,7 @@ class UpgradeAITranslation extends Command
 
         直接输出jsonl, 无需其他内容
         md;
-        $channelId = ChannelApi::getSysChannel('_System_Wbw_VRI_');
+        $channelId = $this->channelService->systemUid('_System_Wbw_VRI_');
         $sentences = Sentence::where('channel_uid', $channelId)
             ->where('book_id', $book)
             ->where('paragraph', $para)

+ 4 - 4
api-v13/app/Console/Commands/UpgradeGrammarBook.php

@@ -2,9 +2,9 @@
 
 namespace App\Console\Commands;
 
-use App\Http\Api\ChannelApi;
 use App\Models\DhammaTerm;
 use App\Models\Relation;
+use App\Services\ChannelService;
 use Illuminate\Console\Command;
 use Illuminate\Support\Str;
 
@@ -40,10 +40,10 @@ class UpgradeGrammarBook extends Command
      *
      * @return int
      */
-    public function handle()
+    public function handle(ChannelService $channelService)
     {
         $lang = 'zh-Hans';
-        $channelId = ChannelApi::getSysChannel('_System_Grammar_Term_'.strtolower($lang).'_');
+        $channelId = $channelService->systemUid('_System_Grammar_Term_'.strtolower($lang).'_');
         if ($channelId === false) {
             $this->error('no channel');
 
@@ -120,7 +120,7 @@ class UpgradeGrammarBook extends Command
             if (empty($caseLocal)) {
                 $caseLocal = $key;
             }
-            $owner = ChannelApi::getById($channelId);
+            $owner = $channelService->summary($channelId);
             if (! $owner) {
                 $this->error('channel id error '.$channelId);
 

+ 3 - 0
api-v13/app/Console/Commands/UpgradePaliText.php

@@ -9,6 +9,7 @@ namespace App\Console\Commands;
 
 use App\Models\BookTitle;
 use App\Models\PaliText;
+use App\Services\V3\PaliTextService;
 use App\Tools\Tools;
 use Illuminate\Console\Command;
 use Illuminate\Support\Facades\Log;
@@ -243,6 +244,8 @@ class UpgradePaliText extends Command
                     $paragraph_info[] = [$book, $paragraph, $length, $prev, $next, $parent];
                 }
             }
+            // 阅读、导出缓存的 pali_texts(按书缓存一个月)
+            app(PaliTextService::class)->forgetBook($from);
         }
 
         $this->info('all done in '.time() - $startTime.'s');

+ 3 - 3
api-v13/app/Console/Commands/UpgradeQuote.php

@@ -2,10 +2,10 @@
 
 namespace App\Console\Commands;
 
-use App\Http\Api\ChannelApi;
 use App\Models\PaliSentence;
 use App\Models\Sentence;
 use App\Models\WbwTemplate;
+use App\Services\ChannelService;
 use App\Tools\Tools;
 use Illuminate\Console\Command;
 use Illuminate\Support\Str;
@@ -41,13 +41,13 @@ class UpgradeQuote extends Command
      *
      * @return int
      */
-    public function handle()
+    public function handle(ChannelService $channelService)
     {
         if (Tools::isStop()) {
             return 0;
         }
         $start = time();
-        $channelId = ChannelApi::getSysChannel('_System_Quote_');
+        $channelId = $channelService->systemUid('_System_Quote_');
         if ($channelId === false) {
             $this->error('no channel');
 

+ 3 - 3
api-v13/app/Console/Commands/UpgradeSystemCommentary.php

@@ -4,7 +4,6 @@ namespace App\Console\Commands;
 
 use App\Facades\RedisCache;
 use App\Helpers\LlmResponseParser;
-use App\Http\Api\ChannelApi;
 use App\Http\Resources\AiModelResource;
 use App\Models\BookTitle;
 use App\Models\PaliSentence;
@@ -13,6 +12,7 @@ use App\Models\RelatedParagraph;
 use App\Models\Tag;
 use App\Models\TagMap;
 use App\Services\AIModelService;
+use App\Services\ChannelService;
 use App\Services\OpenAIService;
 use App\Services\SearchPaliDataService;
 use App\Services\SentenceService;
@@ -99,7 +99,7 @@ class UpgradeSystemCommentary extends Command
      *
      * @return int
      */
-    public function handle()
+    public function handle(ChannelService $channelService)
     {
         if ($this->option('list')) {
             $result = RelatedParagraph::whereNotNull('book_name')
@@ -145,7 +145,7 @@ class UpgradeSystemCommentary extends Command
             $skipPatterns = array_values(array_filter(array_map('trim', explode(',', $this->option('skip')))));
         }
 
-        $channel = ChannelApi::getChannelByName('_System_commentary_');
+        $channel = $channelService->byNameOrFail('_System_commentary_');
 
         $books = [];
         if ($this->option('book')) {

+ 3 - 3
api-v13/app/Console/Commands/UpgradeWbwTemplate.php

@@ -2,10 +2,10 @@
 
 namespace App\Console\Commands;
 
-use App\Http\Api\ChannelApi;
 use App\Models\PaliSentence;
 use App\Models\Sentence;
 use App\Models\WbwTemplate;
+use App\Services\ChannelService;
 use App\Tools\Tools;
 use Illuminate\Console\Command;
 use Illuminate\Support\Str;
@@ -42,7 +42,7 @@ class UpgradeWbwTemplate extends Command
      *
      * @return int
      */
-    public function handle()
+    public function handle(ChannelService $channelService)
     {
         if (Tools::isStop()) {
             return 0;
@@ -56,7 +56,7 @@ class UpgradeWbwTemplate extends Command
             $pali = $pali->where('paragraph', $this->argument('para'));
         }
         $bar = $this->output->createProgressBar($pali->count());
-        $channelId = ChannelApi::getSysChannel('_System_Wbw_VRI_');
+        $channelId = $channelService->systemUid('_System_Wbw_VRI_');
         if ($channelId === false) {
             $this->error('no channel');
 

+ 4 - 0
api-v13/app/Facades/RedisCache.php

@@ -14,6 +14,10 @@ use Illuminate\Support\Facades\Facade;
  * @method static bool has(string $key)
  * @method static bool forget(string $key)
  * @method static int increment(string $key, int $value = 1)
+ * @method static bool putBinary(string $key, string $bytes, \DateTimeInterface|\DateInterval|int|null $ttl = null)
+ * @method static string|null getBinary(string $key)
+ * @method static int|null binaryLength(string $key)
+ * @method static string getBinaryRange(string $key, int $start, int $end)
  *
  * @see \App\Services\RedisCache
  */

+ 25 - 31
api-v13/app/Http/Controllers/Library/BookController.php

@@ -12,6 +12,7 @@ use App\Services\ChapterService;
 use App\Services\PaliContentService;
 use App\Services\PaliTextService;
 use App\Services\TipitakaCatalogService;
+use App\Services\V3\PaliTextService as PaliTexts;
 use Illuminate\Http\RedirectResponse;
 use Illuminate\Http\Request;
 use Illuminate\Support\Facades\Cookie;
@@ -39,6 +40,7 @@ class BookController extends Controller
         protected PaliTextService $paliTextService,
         protected PaliContentService $paliContentService,
         protected TipitakaCatalogService $catalog,
+        protected PaliTexts $paliTexts,
     ) {}
 
     /**
@@ -267,43 +269,45 @@ class BookController extends Controller
      */
     private function resolveDisplayRange(int $book, int $para): array
     {
-        $currBook = $this->bookStart($book, $para);
+        // 标题段取自缓存的经文静态数据(V3\PaliTextService),不查库
+        $currBook = $this->paliTexts->bookStart($book, $para);
         abort_if($currBook === null, 404);
-        $bookStart = $currBook->paragraph;
-        $bookEnd = $currBook->paragraph + $currBook->chapter_len - 1;
+        $bookStart = $currBook['para'];
+        $bookEnd = $currBook['para'] + $currBook['chapter_len'] - 1;
 
         // 本书内全部 chapter 节点(level < 8,即 book/chapter/subhead 等可导航节点)
-        $paragraphs = PaliText::where('book', $book)
-            ->whereBetween('paragraph', [$bookStart, $bookEnd])
-            ->where('level', '<', 8)
-            ->orderBy('paragraph')
-            ->get();
+        $paragraphs = [];
+        foreach ($this->paliTexts->headings($book) as $paragraph => $heading) {
+            if ($paragraph >= $bookStart && $paragraph <= $bookEnd) {
+                $paragraphs[] = ['paragraph' => $paragraph] + $heading;
+            }
+        }
 
-        $curr = $paragraphs->firstWhere('paragraph', $para);
+        $curr = collect($paragraphs)->firstWhere('paragraph', $para);
         // 选中的不是可导航的 chapter 节点(如正文段落 level=100)
         abort_if($curr === null, 404);
-        $endParagraph = $curr->paragraph + $curr->chapter_len - 1;
+        $endParagraph = $curr['paragraph'] + $curr['chapter_len'] - 1;
 
-        if ($curr->chapter_strlen > $this->maxChapterStrlen) {
+        if ($curr['chapter_strlen'] > $this->maxChapterStrlen) {
             // 选中节点过大:向后下钻,找到第一个不超过阈值的子 chapter
             foreach ($paragraphs as $key => $paragraph) {
-                if ($paragraph->paragraph <= $curr->paragraph) {
+                if ($paragraph['paragraph'] <= $curr['paragraph']) {
                     continue;
                 }
-                if ($paragraph->chapter_strlen <= $this->maxChapterStrlen) {
-                    $endParagraph = $paragraph->paragraph + $paragraph->chapter_len - 1;
+                if ($paragraph['chapter_strlen'] <= $this->maxChapterStrlen) {
+                    $endParagraph = $paragraph['paragraph'] + $paragraph['chapter_len'] - 1;
                     break;
                 }
-                if ($paragraph->level <= $curr->level) {
+                if ($paragraph['level'] <= $curr['level']) {
                     // 已离开选中节点的子树,无法继续下钻,止步于上一个节点
-                    $endParagraph = $paragraphs[$key - 1]->paragraph + $paragraphs[$key - 1]->chapter_len - 1;
+                    $endParagraph = $paragraphs[$key - 1]['paragraph'] + $paragraphs[$key - 1]['chapter_len'] - 1;
                     break;
                 }
             }
         }
 
         return [
-            'start' => $curr->paragraph,
+            'start' => $curr['paragraph'],
             'end' => $endParagraph,
         ];
     }
@@ -311,31 +315,21 @@ class BookController extends Controller
     /**
      * 聚合区间内全部段落的阅读模式 HTML。
      *
-     * 与 TipitakaReadParaController 一致,逐段调用 PaliContentService::readParagraph
-     * 获取 HTML 并按段落顺序拼接;缺失或获取失败的段落跳过。章节标题优先取
-     * ProgressChapter.title,回退到 PaliText.toc。
+     * 交给 PaliContentService::readChapters():按平铺章节缓存,命中时每章一次 GET、不查库,
+     * 没命中的一起渲染。章节标题不进缓存:优先取 ProgressChapter.title,回退到巴利标题(toc)。
      *
      * @return array{display: string, title: string, category: array}
      */
     private function fetchRangeContent(int $book, string $channelId, int $start, int $end, int $selectedPara): array
     {
-        $display = '';
-        foreach (range($start, $end) as $para) {
-            $paragraph = $this->paliContentService->readParagraph($book, $para, $channelId, 'html');
-            if (empty($paragraph['display'])) {
-                continue;
-            }
-            $display .= $paragraph['display'];
-        }
+        $display = $this->paliContentService->readChapters($book, $start, $end, $channelId, 'html');
 
         $title = ProgressChapter::where('book', $book)
             ->where('para', $selectedPara)
             ->where('channel_id', $channelId)
             ->value('title');
         if (empty($title)) {
-            $title = PaliText::where('book', $book)
-                ->where('paragraph', $selectedPara)
-                ->value('toc');
+            $title = $this->paliTexts->heading($book, $selectedPara)['toc'] ?? null;
         }
 
         return [

+ 102 - 0
api-v13/app/Http/Controllers/Library/TipitakaDownloadController.php

@@ -0,0 +1,102 @@
+<?php
+
+namespace App\Http\Controllers\Library;
+
+use App\Http\Controllers\Controller;
+use App\Services\TipitakaCatalogService;
+use App\Services\V3\TipitakaExportService;
+use Illuminate\Support\Facades\Cookie;
+use Illuminate\View\View;
+
+/**
+ * library 三藏的下载页:一部作品,或整个 channel 打包。
+ *
+ * 页面只负责展示四种格式现在的状态(已就绪的直接给链接);点击后由页面里的脚本调
+ * `POST /api/v3/tipitaka-exports` 发起、轮询 `GET /api/v3/tipitaka-exports/{id}`,就绪后自动下载。
+ */
+class TipitakaDownloadController extends Controller
+{
+    /**
+     * 下载页上的格式及顺序。离线包(offline)是给 mobile 的,不在网页上出现。
+     */
+    private const FORMATS = ['epub', 'html', 'docx', 'markdown'];
+
+    public function __construct(
+        private readonly TipitakaCatalogService $catalog,
+        private readonly TipitakaExportService $exports,
+    ) {}
+
+    public function work(string $channel, int $sn): View
+    {
+        $channelModel = $this->catalog->channel($channel);
+        abort_unless($channelModel, 404);
+        $scope = $this->exports->scope($channel, $sn, null);
+        $work = $scope['works'][0];
+        $progress = $this->catalog->channelProgress($channel)["{$work['book']}-{$work['para']}"] ?? null;
+        $channelInfo = $this->channelInfo($channelModel);
+
+        return view('library.tipitaka.download', [
+            'mode' => 'work',
+            'channelInfo' => $channelInfo,
+            'book' => $this->catalog->bookCard($work, $channelInfo, $progress) + ['pali_title' => $work['title'], 'updated_at' => $progress['updated_at'] ?? null],
+            'request' => ['channel' => $channel, 'work' => $sn],
+            'formats' => $this->formats($this->exports->describe($channel, $scope, null), true),
+            'backUrl' => route('library.tipitaka.channels.work', ['channel' => $channel, 'sn' => $sn]),
+        ]);
+    }
+
+    /**
+     * 整个 channel 打包下载。只有「全部」一种范围(用户定:不按藏 / 分类分开下)。
+     */
+    public function channel(string $channel): View
+    {
+        $channelModel = $this->catalog->channel($channel);
+        abort_unless($channelModel, 404);
+        $scope = $this->exports->scope($channel, null, null);
+        $names = $this->catalog->localNames($this->catalog->categories(), Cookie::get('language') ?? 'en');
+
+        $groups = [];
+        foreach ($scope['works'] as $work) {
+            $path = $work['category_id'] === null ? [] : $this->catalog->categoryPath($work['category_id']);
+            $label = implode(' · ', array_map(fn ($c) => $names[$c['name']] ?? $c['name'], $path)) ?: __('library.export_uncategorized');
+            $groups[$label][] = [
+                'title' => $work['local_title'],
+                'progress' => (int) round($work['progress'] * 100),
+                'url' => route('library.tipitaka.channels.work', ['channel' => $channel, 'sn' => $work['sn']]),
+            ];
+        }
+
+        return view('library.tipitaka.download', [
+            'mode' => 'channel',
+            'channelInfo' => $this->channelInfo($channelModel),
+            'groups' => $groups,
+            'request' => ['channel' => $channel],
+            'formats' => $this->formats($this->exports->describe($channel, $scope, null), false),
+            'backUrl' => route('library.tipitaka.channels.category', ['channel' => $channel]),
+        ]);
+    }
+
+    /**
+     * @return array{uid: string, name: string, type: string, lang: string, owner: mixed}
+     */
+    private function channelInfo(object $channel): array
+    {
+        return ['uid' => $channel->uid, 'name' => $channel->name, 'type' => $channel->type, 'lang' => $channel->lang, 'owner' => $channel->owner];
+    }
+
+    /**
+     * 格式卡片:名字、说明(单部作品 / 打包两种口径)与当前状态。
+     *
+     * @param  array<string, array<string, mixed>>  $states
+     * @return list<array<string, mixed>>
+     */
+    private function formats(array $states, bool $single): array
+    {
+        return array_map(fn (string $format) => [
+            'key' => $format,
+            'name' => __("library.download_format_{$format}"),
+            'description' => __($single ? "library.download_format_{$format}_desc" : "library.download_format_{$format}_bundle"),
+            'state' => $states[$format],
+        ], self::FORMATS);
+    }
+}

+ 46 - 0
api-v13/app/Http/Controllers/V3/MarkupPreviewController.php

@@ -0,0 +1,46 @@
+<?php
+
+namespace App\Http\Controllers\V3;
+
+use App\Http\Controllers\Concerns\ResolvesCurrentUser;
+use App\Http\Controllers\Controller;
+use App\Http\Requests\V3\StoreMarkupPreviewRequest;
+use App\Http\Resources\V3\MarkupPreviewResource;
+use App\Services\V3\MarkupPreviewService;
+
+/**
+ * 源码预览(模板生成器、编辑器的「预览」)。
+ *
+ * 新能力,没有一一对应的 v2 端点:v2 只有绑定在某篇文章上、走旧渲染器的 `PUT /v2/article-preview/{id}`
+ * (`ArticleController@preview`),那份在 dashboard-v4 下线前原样保留,不要改动。
+ */
+class MarkupPreviewController extends Controller
+{
+    use ResolvesCurrentUser;
+
+    public function __construct(private readonly MarkupPreviewService $previews) {}
+
+    /**
+     * 预览一段源码
+     *
+     * 把还没保存的 markdown 渲染成节点树(与术语、批注的 `body` 同形),不写库,所以是 200 而不是 201。
+     * 口径同阅读页的读模式:术语按第一个 channel 查,句子模板缺省读这些 channel 的译文。
+     * 给了 `channels` 的,每个都要有读权限:不存在 404,看不见 403。
+     *
+     * @bodyParam content string required 源码,最多 20000 字
+     * @bodyParam content_type string 方言。Enum: markdown, markdown-e2。Default: markdown
+     * @bodyParam channels string[] 内容所属的 channel uid,最多 10 个
+     * @bodyParam lang string 没给 channel 时用的语言,如 zh-Hans。缺省用界面语言(Accept-Language 协商的结果)
+     *
+     * @responseStatus 403 给的 channel 没有读权限
+     * @responseStatus 404 给的 channel 不存在
+     */
+    public function __invoke(StoreMarkupPreviewRequest $request)
+    {
+        return MarkupPreviewResource::make($this->previews->preview(
+            $request->validated(),
+            $this->currentUser($request)['user_uid'],
+            app()->getLocale(),
+        ));
+    }
+}

+ 70 - 0
api-v13/app/Http/Controllers/V3/TipitakaExportController.php

@@ -0,0 +1,70 @@
+<?php
+
+namespace App\Http\Controllers\V3;
+
+use App\Http\Controllers\Concerns\ResolvesCurrentUser;
+use App\Http\Controllers\Controller;
+use App\Http\Requests\V3\StoreTipitakaExportRequest;
+use App\Http\Resources\V3\TipitakaExportResource;
+use App\Services\V3\TipitakaExportService;
+use Illuminate\Http\Request;
+
+/**
+ * 三藏下载:把一个 channel 的一部作品、一个分类或整个 channel 导出成文件。
+ *
+ * 新能力,没有对应的 v2 端点(v2 的 `export` / `MqExportPaliChapter` 是按章节导出的另一套,原样保留)。
+ * library 的作品页 / 分类页下载按钮与 wikipali-mobile 都走这里。
+ */
+class TipitakaExportController extends Controller
+{
+    use ResolvesCurrentUser;
+
+    public function __construct(private readonly TipitakaExportService $exports) {}
+
+    /**
+     * 发起下载
+     *
+     * 同一份文件(同一 channel、范围、格式,且译文没改过)已经生成好就直接返回 `status = ready`
+     * 与 `download_url`(200);否则排队生成,返回 `queued`(202,带 `Retry-After`),
+     * 之后轮询 `GET /v3/tipitaka-exports/{id}`。同一份正在生成时不会重复排队。
+     *
+     * 格式:`html`、`markdown`、`epub`、`docx`、`offline`(mobile 离线包,NDJSON,下载时 gzip 传输编码,
+     * 每行一段,`html` 与 `tipitaka-reading` 的 display 相同;只能按作品,首行头里有作品的段落区间
+     * `para` / `end`,客户端按它判断是否覆盖了自己要的范围)。单部作品的 epub / docx
+     * 直接给文件,其余是 zip。私有 channel 只有能读它的人能下载。范围太大(超过全三藏的量)422。
+     *
+     * @unauthenticated
+     *
+     * @bodyParam channel string required channel uid。Example: a19eaf75-c63f-4b84-8125-1bce18311e23
+     * @bodyParam work integer 作品(library 作品页 URL 里的 sn)。作品、category 只能给一个,都不给 = 整个 channel。Example: 275
+     * @bodyParam book integer 用坐标指定作品:book + para 所在的那部作品(mobile 用,它不知道 sn)。与 para 同时给。
+     * @bodyParam para integer 与 book 同时给,作品里的任一段落号(通常是作品起始段)。
+     * @bodyParam category integer 分类 id(library 分类页 URL 里的 id),含后代分类。
+     * @bodyParam format string required 文件格式。Enum: html, markdown, epub, docx, offline
+     *
+     * @responseStatus 202 已排队生成,响应体同 200
+     */
+    public function store(StoreTipitakaExportRequest $request)
+    {
+        $export = $this->exports->request($request->validated(), $this->currentUserUid($request));
+        $response = TipitakaExportResource::make($export)->response();
+
+        return $export['status'] === 'ready' ? $response : $response->setStatusCode(202)->header('Retry-After', '2');
+    }
+
+    /**
+     * 查看下载状态
+     *
+     * `status`:`queued` 排队中 / `running` 生成中(`progress` 0–1,`message` 说明当前在哪部作品)/
+     * `ready` 可下载(带 `download_url`)/ `failed` 失败(重新 POST 即可重试)。
+     * 不存在或已过期 404。
+     *
+     * @unauthenticated
+     *
+     * @urlParam export string required 导出 id(POST 返回的 id)。
+     */
+    public function show(Request $request, string $export)
+    {
+        return TipitakaExportResource::make($this->exports->show($export, $this->currentUserUid($request)));
+    }
+}

+ 43 - 0
api-v13/app/Http/Controllers/V3/TipitakaExportFileController.php

@@ -0,0 +1,43 @@
+<?php
+
+namespace App\Http\Controllers\V3;
+
+use App\Http\Controllers\Controller;
+use App\Services\V3\TipitakaExportDownload;
+use Illuminate\Http\Request;
+
+/**
+ * 三藏下载的文件本身。只认签名链接(`GET /v3/tipitaka-exports/{id}` 的 `download_url`),
+ * 不需要 token:浏览器直接跳转、mobile 交给系统下载器都能用。
+ */
+class TipitakaExportFileController extends Controller
+{
+    public function __construct(private readonly TipitakaExportDownload $download) {}
+
+    /**
+     * 下载文件
+     *
+     * 支持 `Range`(206,断点续传)与 `If-None-Match`(304,ETag 就是导出 id)。
+     * 离线包(offline)是 NDJSON,带 `Content-Encoding: gzip`,HTTP 客户端会自动解压。
+     * 签名无效或过期 403,文件已过期 404。
+     *
+     * @unauthenticated
+     *
+     * @urlParam export string required 导出 id。
+     *
+     * @queryParam expires integer required 签名的过期时间(download_url 里自带)。
+     * @queryParam signature string required 签名(download_url 里自带)。
+     *
+     * @responseFile application/zip application/epub+zip application/vnd.openxmlformats-officedocument.wordprocessingml.document application/x-ndjson
+     *
+     * @responseStatus 206 Range 请求的部分内容
+     * @responseStatus 304 If-None-Match 命中,本地文件就是最新的
+     * @responseStatus 403 签名无效或已过期
+     * @responseStatus 404 文件已过期
+     * @responseStatus 416 Range 超出文件大小
+     */
+    public function __invoke(Request $request, string $export)
+    {
+        return $this->download->respond($export, $request->header('Range'), $request->header('If-None-Match'));
+    }
+}

+ 30 - 0
api-v13/app/Http/Requests/V3/StoreMarkupPreviewRequest.php

@@ -0,0 +1,30 @@
+<?php
+
+namespace App\Http\Requests\V3;
+
+use Illuminate\Foundation\Http\FormRequest;
+
+/**
+ * `POST /v3/markup-previews`:要预览的源码与渲染口径。
+ */
+class StoreMarkupPreviewRequest extends FormRequest
+{
+    public function authorize(): bool
+    {
+        return true;
+    }
+
+    /**
+     * @return array<string, array<int, mixed>>
+     */
+    public function rules(): array
+    {
+        return [
+            'content' => ['required', 'string', 'max:20000'],
+            'content_type' => ['sometimes', 'string', 'in:markdown,markdown-e2'],
+            'channels' => ['sometimes', 'array', 'max:10'],
+            'channels.*' => ['uuid'],
+            'lang' => ['sometimes', 'string', 'max:16', 'regex:/^[A-Za-z]{2,3}(-[A-Za-z0-9]{2,8})*$/'],
+        ];
+    }
+}

+ 35 - 0
api-v13/app/Http/Requests/V3/StoreTipitakaExportRequest.php

@@ -0,0 +1,35 @@
+<?php
+
+namespace App\Http\Requests\V3;
+
+use App\Services\V3\TipitakaExportService;
+use Illuminate\Foundation\Http\FormRequest;
+use Illuminate\Validation\Rule;
+
+/**
+ * 发起三藏下载。作品用 work(sn)或 book + para(该段所在的作品,给只认坐标的 mobile 用)指定;
+ * 与 category 三选一,都不给 = 整个 channel。
+ */
+class StoreTipitakaExportRequest extends FormRequest
+{
+    public function authorize(): bool
+    {
+        return true;
+    }
+
+    /**
+     * @return array<string, array<int, mixed>>
+     */
+    public function rules(): array
+    {
+        return [
+            'channel' => ['required', 'uuid'],
+            'work' => ['sometimes', 'integer', 'min:1', 'prohibits:category,book,para'],
+            // 不加 sometimes:缺了另一半时 required_with 要能跑到
+            'book' => ['integer', 'min:1', 'required_with:para', 'prohibits:category'],
+            'para' => ['integer', 'min:1', 'required_with:book'],
+            'category' => ['sometimes', 'integer', 'min:1'],
+            'format' => ['required', 'string', Rule::in(TipitakaExportService::FORMATS)],
+        ];
+    }
+}

+ 20 - 0
api-v13/app/Http/Resources/V3/MarkupPreviewResource.php

@@ -0,0 +1,20 @@
+<?php
+
+namespace App\Http\Resources\V3;
+
+use App\Services\V3\MarkupPreviewService;
+use Illuminate\Http\Request;
+
+/**
+ * 源码预览结果({@see MarkupPreviewService}):`body` 是新渲染器的节点树,与术语、批注的 `body` 同形。
+ */
+class MarkupPreviewResource extends BaseResource
+{
+    /**
+     * @return array{body: list<MarkupNode>}
+     */
+    public function toArray(Request $request): array
+    {
+        return $this->resource;
+    }
+}

+ 38 - 0
api-v13/app/Http/Resources/V3/TipitakaExportResource.php

@@ -0,0 +1,38 @@
+<?php
+
+namespace App\Http\Resources\V3;
+
+use Illuminate\Http\Request;
+
+/**
+ * 一次三藏下载的状态(`/v3/tipitaka-exports`)。载荷是 TipitakaExportService::present() 的数组。
+ *
+ * `id` 是内容指纹:同一 channel、范围、格式,译文没改过就是同一个 id——客户端(mobile 离线包)
+ * 可以拿它判断已下载的内容是否过时。`download_url` 是签名的相对地址,`status = ready` 时才有,
+ * 到 `expires_at` 失效。
+ */
+class TipitakaExportResource extends BaseResource
+{
+    /**
+     * @param  Request  $request
+     * @return array{
+     *     id: string,
+     *     status: string,
+     *     format: string,
+     *     progress: float,
+     *     message: string|null,
+     *     title: string,
+     *     works: int,
+     *     filename: string,
+     *     content_type: string,
+     *     size: int|null,
+     *     ready_at: string|null,
+     *     expires_at: string|null,
+     *     download_url: string|null
+     * }
+     */
+    public function toArray($request)
+    {
+        return parent::toArray($request);
+    }
+}

+ 16 - 10
api-v13/app/Models/Discussion.php

@@ -9,6 +9,7 @@ use Illuminate\Database\Eloquent\Model;
 use Illuminate\Database\Eloquent\Relations\BelongsTo;
 use Illuminate\Database\Eloquent\Relations\HasMany;
 use Illuminate\Database\Eloquent\SoftDeletes;
+use Illuminate\Support\Facades\DB;
 
 /**
  * 表 `discussions`。
@@ -224,16 +225,21 @@ class Discussion extends Model
             if ($discussion->res_type !== 'sentence' || empty($discussion->res_id)) {
                 return;
             }
-            $sentence = Sentence::where('uid', $discussion->res_id)
-                ->first(['book_id', 'paragraph', 'channel_uid']);
-            if (! $sentence) {
-                return;
-            }
-            PaliContentService::forgetParagraph(
-                (int) $sentence->book_id,
-                (int) $sentence->paragraph,
-                (string) $sentence->channel_uid
-            );
+            $sentenceId = $discussion->res_id;
+            // 提交之后才清,免得并发的读在提交前把旧数据写回缓存
+            DB::afterCommit(function () use ($sentenceId) {
+                $sentence = Sentence::where('uid', $sentenceId)
+                    ->first(['book_id', 'paragraph', 'channel_uid']);
+                if (! $sentence) {
+                    return;
+                }
+                // 只删段落成品;批注不影响内容索引
+                PaliContentService::forgetParagraph(
+                    (int) $sentence->book_id,
+                    (int) $sentence->paragraph,
+                    (string) $sentence->channel_uid
+                );
+            });
         };
         static::saved($forget);
         static::deleted($forget);

+ 38 - 10
api-v13/app/Models/Sentence.php

@@ -6,6 +6,7 @@ use App\Services\PaliContentService;
 use Illuminate\Database\Eloquent\Factories\HasFactory;
 use Illuminate\Database\Eloquent\Model;
 use Illuminate\Database\Eloquent\SoftDeletes;
+use Illuminate\Support\Facades\DB;
 
 class Sentence extends Model
 {
@@ -37,19 +38,46 @@ class Sentence extends Model
         'channel_uid' => 'string',
     ];
 
+    /**
+     * 增改删句子时清阅读缓存:段落成品(L1)删掉;「有译文的段」可能变了才删内容索引(L2)。
+     * 见 {@see PaliContentService::paragraphChanged()}。改了 book / paragraph / channel 的,新旧两处都要清。
+     * 提交之后才清,免得并发的读在提交前把旧数据写回缓存。
+     */
     protected static function booted(): void
     {
-        $forget = function (Sentence $sentence) {
-            PaliContentService::forgetParagraph(
-                (int) $sentence->book_id,
-                (int) $sentence->paragraph,
-                (string) $sentence->channel_uid
-            );
+        $created = function (Sentence $sentence) {
+            $now = [(int) $sentence->book_id, (int) $sentence->paragraph, (string) $sentence->channel_uid];
+            $hasText = (int) $sentence->strlen > 0;
+            DB::afterCommit(fn () => PaliContentService::paragraphChanged(...$now, indexChanged: true, mayAddBook: $hasText));
+        };
+        // updated 事件里 getOriginal() 还是改之前的值(含软删恢复:deleted_at 从有到无)
+        $updated = function (Sentence $sentence) {
+            $now = [(int) $sentence->book_id, (int) $sentence->paragraph, (string) $sentence->channel_uid];
+            $before = [(int) $sentence->getOriginal('book_id'), (int) $sentence->getOriginal('paragraph'), (string) $sentence->getOriginal('channel_uid')];
+            $hasText = (int) $sentence->strlen > 0;
+            $hadText = (int) $sentence->getOriginal('strlen') > 0;
+            $restored = $sentence->getOriginal('deleted_at') !== null && $sentence->deleted_at === null;
+            DB::afterCommit(function () use ($now, $before, $hasText, $hadText, $restored) {
+                $moved = $before !== $now;
+                PaliContentService::paragraphChanged(
+                    ...$now,
+                    indexChanged: $restored || $moved || $hasText !== $hadText,
+                    mayAddBook: $hasText,
+                    mayRemoveBook: ! $moved && $hadText && ! $hasText,
+                );
+                if ($moved) {
+                    PaliContentService::paragraphChanged(...$before, indexChanged: true, mayRemoveBook: $hadText);
+                }
+            });
+        };
+        $removed = function (Sentence $sentence) {
+            $now = [(int) $sentence->book_id, (int) $sentence->paragraph, (string) $sentence->channel_uid];
+            DB::afterCommit(fn () => PaliContentService::paragraphChanged(...$now, indexChanged: true, mayRemoveBook: true));
         };
-        static::saved($forget);
-        static::deleted($forget);
-        static::restored($forget);
-        static::forceDeleted($forget);
+        static::created($created);
+        static::updated($updated);
+        static::deleted($removed);
+        static::forceDeleted($removed);
     }
 
     protected $dates = [

+ 3 - 0
api-v13/app/Providers/AppServiceProvider.php

@@ -146,6 +146,9 @@ class AppServiceProvider extends ServiceProvider
         // 比对验证码、建账号:按 IP 限,挡住对 6 位验证码的穷举(单个码另有 5 次试错上限)
         RateLimiter::for('sign-up', fn (Request $request): Limit => Limit::perMinute(20)->by('ip:'.$request->ip()));
 
+        // 三藏下载:发起请求要查库统计范围,按 IP 限一下(轮询状态的 GET 不限)
+        RateLimiter::for('tipitaka-exports', fn (Request $request): Limit => Limit::perMinute(30)->by('ip:'.$request->ip()));
+
         // 登录:按「账号 + IP」挡住对单个账号的猜密码,按 IP 挡住换着账号撞库
         RateLimiter::for('sessions', fn (Request $request): array => [
             Limit::perMinute(5)->by('login:'.mb_strtolower((string) $request->input('login')).'|'.$request->ip()),

+ 290 - 91
api-v13/app/Services/PaliContentService.php

@@ -22,7 +22,9 @@ use App\Services\Markup\Annotation\AnnotationSet;
 use App\Services\Markup\Format;
 use App\Services\Markup\MarkupService;
 use App\Services\Markup\RenderOptions;
+use App\Services\V3\PaliTextService;
 use Illuminate\Support\Arr;
+use Illuminate\Support\Collection;
 use Illuminate\Support\Facades\Log;
 use Illuminate\Support\Str;
 
@@ -656,50 +658,121 @@ class PaliContentService
     }
 
     /**
-     * 阅读模式渲染单个段落。
-     * 直接从 sentences 表取单个 channel 的记录,渲染成 html。
-     * 与 paragraphs() 不同:没有译文的句子不保留占位,有多少句子输出多少句子。
+     * 阅读模式渲染单个段落,即只给一段的 {@see self::readParagraphs()}。
+     * 直接从 sentences 表取单个 channel 的记录。与 paragraphs() 不同:没有译文的句子不保留占位,
+     * 有多少句子输出多少句子。
      *
-     * @return array{para: int, display: string, sentences: array<int, array{sid: string, html: string}>}
+     * @return array{para: int, display: string, sentences: list<array{sid: string, html: string}>}
      */
     public function readParagraph(int $book, int $para, string $channelUid, string $format = 'html'): array
     {
-        $level = $this->paragraphLevel($book, $para);
-        // 缓存句子,段落外壳与标题级别有关,不进缓存
-        $key = self::paragraphCacheKey($book, $para, $channelUid, $format);
-        $cached = RedisCache::remember(
-            $key,
-            config('mint.cache.expire'),
-            function () use ($book, $para, $channelUid, $format) {
-                return $this->renderReadSentences($book, $para, $channelUid, $format);
+        return $this->readParagraphs($book, [$para], $channelUid, $format)[$para];
+    }
+
+    /**
+     * 阅读模式渲染同一本书的多个段落。v3 阅读、Laravel 阅读器、三藏下载都从这里取正文。
+     *
+     * 每段的**完整结果**(含段落外壳与段后脚注列表)按 (book, para, channel, format) 缓存,
+     * 命中时不查库;没有译文的段也缓存(display 为空)。没命中的段一起渲染
+     * ({@see self::renderReadParagraphs()}):channel、句子、批注各查一次,全部句子一次交给 Markup,
+     * 术语、引用句子等每类只查一次。
+     *
+     * 缓存由 Sentence / Discussion 的模型事件删除({@see self::paragraphChanged()}、{@see self::forgetParagraph()});术语释义、
+     * 引用的句子、channel 名称改了没有失效信号,最多旧 `mint.cache.read_paragraph_ttl`。
+     *
+     * @param  list<int>  $paras
+     * @return array<int, array{para: int, display: string, sentences: list<array{sid: string, html: string}>}> 段落号 => 结果,顺序同 $paras
+     */
+    public function readParagraphs(int $book, array $paras, string $channelUid, string $format = 'html'): array
+    {
+        $results = [];
+        $misses = [];
+        foreach (array_unique($paras) as $para) {
+            $cached = RedisCache::get(self::paragraphCacheKey($book, $para, $channelUid, $format));
+            $results[$para] = is_array($cached) ? $cached : null;
+            if ($results[$para] === null) {
+                $misses[] = $para;
             }
-        );
+        }
+        if ($misses === []) {
+            return $results;
+        }
 
-        $result = [
-            'para' => $para,
-            'display' => '',
-            'sentences' => $cached['sentences'],
-        ];
-        if (count($cached['display']) === 0) {
-            return $result;
+        $ttl = (int) config('mint.cache.read_paragraph_ttl');
+        foreach ($this->renderReadParagraphs($book, $misses, $channelUid, $format) as $para => $result) {
+            RedisCache::put(self::paragraphCacheKey($book, $para, $channelUid, $format), $result, $ttl);
+            $results[$para] = $result;
         }
 
-        $pClass = PaliText::where('book', $book)
-            ->where('paragraph', $para)
-            ->value('class');
+        return $results;
+    }
 
-        if ($format === 'html') {
-            // html 格式加段落外壳;段后追加段落脚注列表(本段义注/复注条目)
-            $content = implode('', $cached['display']);
-            $inner = $level > 0 ? "<h{$level}>{$content}</h{$level}>" : "<div class='para-block'>{$content}</div>";
-            $footnoteList = $this->renderFootnoteList($cached['notes'] ?? []);
-            $result['display'] = "<div id='para-{$para}' class='{$cached['area']} {$pClass}' data-para='{$para}'>{$inner}{$footnoteList}</div>";
-        } else {
-            // 其他格式一行一句
-            $result['display'] = implode("\n", $cached['display']);
+    /**
+     * 区间 [start, end] 的阅读模式正文(html),阅读器按章读用。
+     *
+     * 按平铺章节缓存({@see PaliTextService::flatChapters()}:标题段到下一个标题段之前是一章,不嵌套),
+     * 一章一个 key,命中时整章一次 GET、不查库。区间完整覆盖的章走章节缓存,没命中的章一起交给
+     * {@see self::readParagraphs()}(各段多半已在段落成品缓存里)拼好回写;区间边缘没盖全的章、
+     * 第一个标题段之前的段直接逐段取。章节缓存与段落成品一起失效({@see self::forgetParagraph()})。
+     */
+    public function readChapters(int $book, int $start, int $end, string $channelUid, string $format = 'html'): string
+    {
+        // 区间切成片:[起, 止, 是否整章]
+        $pieces = [];
+        $cursor = $start;
+        foreach (app(PaliTextService::class)->flatChapters($book) as $chapterStart => $chapterEnd) {
+            if ($chapterEnd < $cursor || $chapterStart > $end) {
+                continue;
+            }
+            if ($chapterStart > $cursor) {
+                $pieces[] = [$cursor, $chapterStart - 1, false];
+                $cursor = $chapterStart;
+            }
+            $whole = $chapterStart >= $start && $chapterEnd <= $end;
+            $pieces[] = [$cursor, min($chapterEnd, $end), $whole];
+            $cursor = min($chapterEnd, $end) + 1;
+        }
+        if ($cursor <= $end) {
+            $pieces[] = [$cursor, $end, false];
         }
 
-        return $result;
+        $chapters = [];
+        $paras = [];
+        foreach ($pieces as $i => [$from, $to, $whole]) {
+            if ($whole) {
+                $cached = RedisCache::get(self::chapterCacheKey($book, $from, $channelUid, $format));
+                if (is_string($cached)) {
+                    $chapters[$i] = $cached;
+
+                    continue;
+                }
+            }
+            array_push($paras, ...range($from, $to));
+        }
+        $rendered = $paras === [] ? [] : $this->readParagraphs($book, $paras, $channelUid, $format);
+
+        $ttl = (int) config('mint.cache.read_paragraph_ttl');
+        $separator = $format === 'html' ? '' : "\n";
+        $display = [];
+        foreach ($pieces as $i => [$from, $to, $whole]) {
+            if (! isset($chapters[$i])) {
+                $parts = [];
+                foreach (range($from, $to) as $para) {
+                    if (($rendered[$para]['display'] ?? '') !== '') {
+                        $parts[] = $rendered[$para]['display'];
+                    }
+                }
+                $chapters[$i] = implode($separator, $parts);
+                if ($whole) {
+                    RedisCache::put(self::chapterCacheKey($book, $from, $channelUid, $format), $chapters[$i], $ttl);
+                }
+            }
+            if ($chapters[$i] !== '') {
+                $display[] = $chapters[$i];
+            }
+        }
+
+        return implode($separator, $display);
     }
 
     /**
@@ -707,12 +780,7 @@ class PaliContentService
      */
     public function paragraphLevel(int $book, int $para): int
     {
-        $level = PaliText::where('book', $book)
-            ->where('paragraph', $para)
-            ->where('level', '<', 8)
-            ->value('level');
-
-        return $level ? (int) $level : 0;
+        return app(PaliTextService::class)->headingLevel($book, $para);
     }
 
     /**
@@ -741,21 +809,46 @@ class PaliContentService
     private const MAX_COMMENTARY_SENTENCES = 3;
 
     /**
-     * 段落阅读模式缓存的 key
+     * 段落阅读模式缓存的 key(段落成品:含外壳与脚注列表)。
      */
     public static function paragraphCacheKey(int $book, int $para, string $channelUid, string $format): string
     {
-        // markup:App\Services\Markup 渲染的缓存,与 MdRender 时代的旧缓存分开(旧 key 自然过期)
-        return "/read-para/markup/{$book}-{$para}/{$channelUid}/{$format}";
+        // v4:2026-11-22 起缓存整段成品(原来只缓存句子、外壳每次现查),换前缀让旧缓存自然过期
+        return "/read-para/v4/{$book}-{$para}/{$channelUid}/{$format}";
     }
 
     /**
-     * 删除某个段落的阅读模式缓存。句子有增改删时调用,下次 readParagraph 自动重建。
+     * 平铺章节的阅读正文缓存 key({@see self::readChapters()})。
+     */
+    public static function chapterCacheKey(int $book, int $chapter, string $channelUid, string $format): string
+    {
+        return "/read-chapter/v1/{$book}-{$chapter}/{$channelUid}/{$format}";
+    }
+
+    /**
+     * 删除某个段落的阅读模式缓存(段落成品,及它所在平铺章节的章节缓存),下次读时自动重建。
      */
     public static function forgetParagraph(int $book, int $para, string $channelUid): void
     {
+        $chapter = app(PaliTextService::class)->flatChapterOf($book, $para);
         foreach (self::FORMATS as $format) {
             RedisCache::forget(self::paragraphCacheKey($book, $para, $channelUid, $format));
+            if ($chapter !== null) {
+                RedisCache::forget(self::chapterCacheKey($book, $chapter, $channelUid, $format));
+            }
+        }
+    }
+
+    /**
+     * 某段的句子变了(Sentence 的模型事件调用):删段落成品与所在章节的缓存;「有译文的段」可能变了
+     * ($indexChanged:新建 / 删除句子、strlen 在 0 与非 0 之间变化、句子搬了家)时再删内容索引。
+     * 书号索引的两个参数见 {@see ReadingIndexService::forget()}。
+     */
+    public static function paragraphChanged(int $book, int $para, string $channelUid, bool $indexChanged = false, bool $mayAddBook = false, bool $mayRemoveBook = false): void
+    {
+        self::forgetParagraph($book, $para, $channelUid);
+        if ($indexChanged) {
+            app(ReadingIndexService::class)->forget($channelUid, $book, $mayAddBook, $mayRemoveBook);
         }
     }
 
@@ -771,7 +864,7 @@ class PaliContentService
      *   没有位置的合成一个三角叹号图标放在句尾。纯文本 / markdown 里不显示。
      * - `assessment`(译文评估):句尾一个对勾图标,颜色按分数分档,带 discussion id,
      *   阅读器点击看分数与理由。一句只有一条(有并发残留时取最近更新的)。纯文本 / markdown 里不显示。
-     *   同段里其它没有评估的句子由 {@see self::renderReadSentences()} 补灰色对勾。
+     *   同段里其它没有评估的句子由 {@see self::renderReadParagraphs()} 补灰色对勾。
      * issue / glossary 只注入未关闭的;批注与评估没有开关状态。
      *
      * 位置按 pos_* 定位,与 quote_exact 对不上(正文改过)时按摘录重新定位。
@@ -779,23 +872,19 @@ class PaliContentService
      * 插入点写的是结构化标记({@see AnnotationSet})而不是 HTML:content 里留下占位符,渲染时变成
      * anno-issue / anno-issue-mark / anno-assessment / note 模板节点,任意格式都能输出。
      *
-     * @return array{content: string, notes: list<array{fnId: string, noteHtml: string, citeHtml: string}>, assessed: bool, annotations: AnnotationSet}
+     * 批注由调用方一次查好传进来({@see self::readingAnnotations()})。段后脚注列表的正文(纯文本)
+     * 这里不渲染,只给出待渲染的源码(`text`),由调用方整块一次渲染后填进 `noteHtml`。
+     *
+     * @param  list<Discussion>  $records  挂在这句上、要注入阅读页的批注,按创建时间升序
+     * @return array{content: string, notes: list<array{fnId: string, noteHtml: string, citeHtml: string, text: array{source: string, channels: list<string>, contentType: string}, truncated: bool}>, assessed: bool, annotations: AnnotationSet}
      */
-    protected function injectAnnotationNotes(Sentence $row, string $channelType, string $format = 'html'): array
+    protected function injectAnnotationNotes(Sentence $row, string $channelType, array $records): array
     {
         $content = (string) $row->content;
         $annotations = new AnnotationSet;
         $result = ['content' => $content, 'notes' => [], 'assessed' => false, 'annotations' => $annotations];
-        $records = Discussion::where('res_type', 'sentence')
-            ->where('res_id', $row->uid)
-            ->whereIn('type', Discussion::READING_TYPES)
-            // 只注入话题本身;回复(类型跟随话题)不进阅读页
-            ->whereNull('parent')
-            ->where(fn ($q) => $q->whereIn('type', Discussion::STATELESS_TYPES)->orWhere('status', 'active'))
-            ->orderBy('created_at')
-            ->get();
 
-        if ($records->isEmpty()) {
+        if ($records === []) {
             return $result;
         }
 
@@ -830,7 +919,7 @@ class PaliContentService
 
                 continue;
             }
-            $note = $this->renderAnnotationNote($record, $row, $channelType);
+            $note = $this->renderAnnotationNote($record, $row);
             if ($note === null) {
                 continue;
             }
@@ -848,8 +937,10 @@ class PaliContentService
             ];
             $footnotes[$record->id] = [
                 'fnId' => 'fn-'.$record->id,
-                'noteHtml' => $note['noteHtml'],
+                'noteHtml' => '',
                 'citeHtml' => $note['citeHtml'],
+                'text' => $note['text'],
+                'truncated' => $note['truncated'],
             ];
         }
 
@@ -874,9 +965,12 @@ class PaliContentService
      * 把一条批注(commentary / note)整理成要插入正文的 note 模板(正文 + 参数)与段后脚注条目。
      * 不合格的(正文为空、commentary 不是句子模板)返回 null,不插角标也不进脚注列表。
      *
-     * @return array{body: string, params: array<string, string>, noteHtml: string, citeHtml: string, order: array<int, int>}|null
+     * 脚注条目的正文(纯文本)不在这里渲染:`text` 是待渲染的源码,`truncated` 表示义注被截断、
+     * 渲染后要补省略号。整块一起渲染见 {@see self::renderFootnoteTexts()}。
+     *
+     * @return array{body: string, params: array<string, string>, text: array{source: string, channels: list<string>, contentType: string}, truncated: bool, citeHtml: string, order: array<int, int>}|null
      */
-    protected function renderAnnotationNote(Discussion $note, Sentence $row, string $channelType): ?array
+    protected function renderAnnotationNote(Discussion $note, Sentence $row): ?array
     {
         $noteContent = trim((string) $note->content);
         if ($noteContent === '') {
@@ -903,15 +997,14 @@ class PaliContentService
             $source = $noteContent;
         }
         // 段后脚注列表用的纯文本(边注本身是结构化的 note 节点,正文照 markdown 渲染)
-        $noteHtml = (string) app(MarkupService::class)->render($source, new RenderOptions(
-            format: Format::Text,
-            channels: [(string) $row->channel_uid],
-            channelType: $channelType,
-            contentType: $note->effectiveContentType(),
-        ));
+        $text = [
+            'source' => $source,
+            'channels' => [(string) $row->channel_uid],
+            'contentType' => $note->effectiveContentType(),
+        ];
         // 义注被截断时补省略号,提示后面还有;想看全文点 <cite> 跳过去。
-        if (count($sents) > self::MAX_COMMENTARY_SENTENCES) {
-            $noteHtml = rtrim($noteHtml).'...';
+        $truncated = count($sents) > self::MAX_COMMENTARY_SENTENCES;
+        if ($truncated) {
             $source .= '...';
         }
         // 出处只有 commentary 有。跳转目标(义注书-段-起-止)同时挂在 <cite> 和角标
@@ -930,7 +1023,8 @@ class PaliContentService
             // note 模板的正文(markdown)与参数:渲染成 tufte sidenote(label + input + span.sidenote)
             'body' => $source,
             'params' => $params,
-            'noteHtml' => $noteHtml,
+            'text' => $text,
+            'truncated' => $truncated,
             'citeHtml' => $citeHtml,
             // 同一插入点上的先后:按义注原文的先后;普通 note 没有坐标,取 0,排在义注对应之前
             'order' => $sents ? [(int) $sents[0][1], (int) $sents[0][2], (int) $sents[0][3]] : [0, 0, 0],
@@ -939,6 +1033,8 @@ class PaliContentService
 
     /**
      * 段落脚注列表:把本段的注释条目逐条列在段后,每条默认收起为可配置行数(见阅读器 CSS)。
+     *
+     * @param  list<array{fnId: string, noteHtml: string, citeHtml: string}>  $notes
      */
     protected function renderFootnoteList(array $notes): string
     {
@@ -961,42 +1057,114 @@ class PaliContentService
     }
 
     /**
-     * 渲染段落里的句子。不含段落外壳,可直接缓存。
+     * 一次查回这些句子上要注入阅读页的批注,按句子 uid 分组、组内按创建时间升序。
+     *
+     * @param  Collection<int, Sentence>  $records
+     * @return array<string, list<Discussion>>
+     */
+    protected function readingAnnotations(Collection $records): array
+    {
+        $grouped = [];
+        foreach ($records->pluck('uid')->unique()->chunk(1000) as $uids) {
+            Discussion::where('res_type', 'sentence')
+                ->whereIn('res_id', $uids->values()->all())
+                ->whereIn('type', Discussion::READING_TYPES)
+                // 只注入话题本身;回复(类型跟随话题)不进阅读页
+                ->whereNull('parent')
+                ->where(fn ($q) => $q->whereIn('type', Discussion::STATELESS_TYPES)->orWhere('status', 'active'))
+                ->orderBy('created_at')
+                ->get()
+                ->each(function (Discussion $discussion) use (&$grouped) {
+                    $grouped[(string) $discussion->res_id][] = $discussion;
+                });
+        }
+
+        return $grouped;
+    }
+
+    /**
+     * 整块的段后脚注正文(纯文本)一次渲染:批注里的术语、义注句子合在一起查。
+     *
+     * @param  array<int, array{notes: list<array<string, mixed>>}>  $injections
+     * @return array<string, string> "句序号:脚注序号" => 纯文本
+     */
+    protected function renderFootnoteTexts(array $injections, string $channelType): array
+    {
+        $items = [];
+        foreach ($injections as $i => $injected) {
+            foreach ($injected['notes'] as $n => $note) {
+                $items["{$i}:{$n}"] = $note['text'];
+            }
+        }
+        if ($items === []) {
+            return [];
+        }
+        $texts = app(MarkupService::class)->renderMany($items, new RenderOptions(format: Format::Text, channelType: $channelType));
+        foreach ($injections as $i => $injected) {
+            foreach ($injected['notes'] as $n => $note) {
+                $text = (string) ($texts["{$i}:{$n}"] ?? '');
+                $texts["{$i}:{$n}"] = $note['truncated'] ? rtrim($text).'...' : $text;
+            }
+        }
+
+        return $texts;
+    }
+
+    /**
+     * 渲染同一本书的若干段落(没命中缓存的那些),结果含段落外壳,可直接缓存。
      *
-     * @return array{area: string, display: array<int, string>, sentences: array<int, array{sid: string, html: string}>}
+     * 整块只查三次库:channel、句子(按段、word_start 排序)、批注;全部句子一次交给 Markup 渲染,
+     * 脚注正文再一次。标题级别与段落 class 取自 {@see PaliTextService}(缓存的经文静态数据)。
+     *
+     * @param  list<int>  $paras
+     * @return array<int, array{para: int, display: string, sentences: list<array{sid: string, html: string}>}>
      */
-    protected function renderReadSentences(int $book, int $para, string $channelUid, string $format): array
+    protected function renderReadParagraphs(int $book, array $paras, string $channelUid, string $format): array
     {
-        $result = ['area' => 'translation', 'display' => [], 'sentences' => []];
+        $results = [];
+        foreach ($paras as $para) {
+            $results[$para] = ['para' => $para, 'display' => '', 'sentences' => []];
+        }
         $channel = Channel::where('uid', $channelUid)
             ->select(['uid', 'type', 'lang', 'name'])->first();
         if (! $channel) {
-            return $result;
+            return $results;
         }
         $isOrigin = $channel->type === 'original' || $channel->type === 'wbw';
         $channelType = $channel->type === 'nissaya' ? 'nissaya' : 'translation';
-        $result['area'] = $isOrigin ? 'original' : 'translation';
+        $area = $isOrigin ? 'original' : 'translation';
 
         $records = Sentence::select($this->selectCol)
             ->where('book_id', $book)
-            ->where('paragraph', $para)
             ->where('channel_uid', $channelUid)
+            ->whereIn('paragraph', $paras)
+            ->orderBy('paragraph')
             ->orderBy('word_start')
-            ->get();
+            ->get()
+            ->values();
+        if ($records->isEmpty()) {
+            return $results;
+        }
+
+        $annotations = $this->readingAnnotations($records);
+        $injections = [];
+        $assessedParas = [];
+        foreach ($records as $i => $row) {
+            $injections[$i] = $this->injectAnnotationNotes($row, $channelType, $annotations[(string) $row->uid] ?? []);
+            if ($injections[$i]['assessed']) {
+                $assessedParas[(int) $row->paragraph] = true;
+            }
+        }
 
-        $allNotes = [];
-        $injections = $records->map(fn (Sentence $row) => $this->injectAnnotationNotes($row, $channelType, $format));
-        // 段里有句子评估过,其余没评估的句子在句尾补灰色对勾:不然读者会把它与下一句的
-        // 对勾连起来,误以为是一句。整段都没评估就都不补(段落本身有分隔)。
-        $markUnassessed = $injections->contains('assessed', true);
         $sources = [];
         foreach ($records as $i => $row) {
             $injected = $injections[$i];
             $content = $injected['content'];
-            if ($markUnassessed && ! $injected['assessed'] && trim($content) !== '') {
+            // 段里有句子评估过,其余没评估的句子在句尾补灰色对勾:不然读者会把它与下一句的
+            // 对勾连起来,误以为是一句。整段都没评估就都不补(段落本身有分隔)。按段算,不是按整块
+            if (isset($assessedParas[(int) $row->paragraph]) && ! $injected['assessed'] && trim($content) !== '') {
                 $content .= $injected['annotations']->unassessedMark();
             }
-            $allNotes = array_merge($allNotes, $injected['notes']);
             $sources[$i] = [
                 'source' => $content,
                 'channels' => [(string) $row->channel_uid],
@@ -1006,27 +1174,58 @@ class PaliContentService
                 'idPrefix' => "{$row->book_id}-{$row->paragraph}-{$row->word_start}-{$row->word_end}",
             ];
         }
-        // 整段一起渲染:各句里的术语、句子模板(含义注对应)合在一起批量查
-        $rendered = $sources === [] ? [] : app(MarkupService::class)->renderMany(
+        // 整块一起渲染:各句里的术语、句子模板(含义注对应)合在一起批量查
+        $rendered = app(MarkupService::class)->renderMany(
             $sources,
-            new RenderOptions(format: self::markupFormat($format), channelType: $channelType),
+            // markdown 每句末尾附自己的脚注正文(`[^n]: …`)。编号每句从 1 起,跨句会重号,
+            // 整章导出时由 V3\TipitakaExportBuilder 逐句重新编号;不附正文的话 `[^n]` 无处可指
+            new RenderOptions(format: self::markupFormat($format), channelType: $channelType, footnote: $format === 'markdown'),
         );
+        // 段后脚注列表只有 html 有
+        $noteTexts = $format === 'html' ? $this->renderFootnoteTexts($injections, $channelType) : [];
+
+        $display = [];
+        $notes = [];
         foreach ($records as $i => $row) {
+            $para = (int) $row->paragraph;
+            foreach ($injections[$i]['notes'] as $n => $note) {
+                $notes[$para][] = [
+                    'fnId' => $note['fnId'],
+                    'noteHtml' => $noteTexts["{$i}:{$n}"] ?? '',
+                    'citeHtml' => $note['citeHtml'],
+                ];
+            }
             $html = $rendered[$i] ?? '';
             if (empty($html)) {
                 continue;
             }
             $sid = "{$row->book_id}-{$row->paragraph}-{$row->word_start}-{$row->word_end}";
-            $result['sentences'][] = ['sid' => $sid, 'html' => $html];
+            $results[$para]['sentences'][] = ['sid' => $sid, 'html' => $html];
             if ($format === 'html') {
                 $class = $isOrigin ? 'sentence origin' : 'sentence';
-                $result['display'][] = "<div class='{$class}' lang='{$channel->lang}' data-sid='{$sid}'>{$html}</div>";
+                $display[$para][] = "<div class='{$class}' lang='{$channel->lang}' data-sid='{$sid}'>{$html}</div>";
             } else {
-                $result['display'][] = $html;
+                $display[$para][] = $html;
             }
         }
-        $result['notes'] = $allNotes;
 
-        return $result;
+        $paliTexts = app(PaliTextService::class);
+        foreach ($display as $para => $lines) {
+            if ($format !== 'html') {
+                // 其他格式一行一句
+                $results[$para]['display'] = implode("\n", $lines);
+
+                continue;
+            }
+            // html 格式加段落外壳;段后追加段落脚注列表(本段义注/复注条目)
+            $content = implode('', $lines);
+            $level = $paliTexts->headingLevel($book, $para);
+            $pClass = $paliTexts->paragraph($book, $para)['class'] ?? '';
+            $inner = $level > 0 ? "<h{$level}>{$content}</h{$level}>" : "<div class='para-block'>{$content}</div>";
+            $footnoteList = $this->renderFootnoteList($notes[$para] ?? []);
+            $results[$para]['display'] = "<div id='para-{$para}' class='{$area} {$pClass}' data-para='{$para}'>{$inner}{$footnoteList}</div>";
+        }
+
+        return $results;
     }
 }

+ 129 - 0
api-v13/app/Services/ReadingIndexService.php

@@ -0,0 +1,129 @@
+<?php
+
+namespace App\Services;
+
+use App\Facades\RedisCache;
+use App\Models\Sentence;
+
+/**
+ * 阅读的内容索引(纯能力,v3 阅读与三藏下载共用):某 channel 哪些书、哪些段有译文(句子 strlen > 0)。
+ *
+ * - **段号索引** `/read-index/{channel}/{book}`:这本书里有译文的段,存成连续区间;
+ * - **书号索引** `/read-index/{channel}/books`:有译文的书。整 channel 重建要几百毫秒,只在
+ *   「新出现一本书」或「可能少了一本书」时删。
+ *
+ * 只随句子失效({@see PaliContentService::paragraphChanged()},Sentence 的模型事件调用):
+ * 只有「有译文的段」可能变了才删,改一句译文的内容不动索引。批注不影响索引。
+ * **绕过模型事件的批量写入(`Sentence::where()->update()/delete()`、`DB::table('sentences')`)要自己调
+ * paragraphChanged()**,否则会读到旧索引直到过期。
+ */
+class ReadingIndexService
+{
+    /** @var array<string, list<int>> */
+    private array $paragraphs = [];
+
+    /**
+     * 有译文的书号,升序。
+     *
+     * @return list<int>
+     */
+    public function books(string $channel): array
+    {
+        return RedisCache::remember(
+            self::booksKey($channel),
+            (int) config('mint.cache.read_index_ttl'),
+            fn () => Sentence::where('channel_uid', $channel)
+                ->where('strlen', '>', 0)
+                ->distinct()
+                ->orderBy('book_id')
+                ->pluck('book_id')
+                ->map(fn ($book) => (int) $book)
+                ->all()
+        );
+    }
+
+    /**
+     * 这本书里有译文的段落号,升序。
+     *
+     * @return list<int>
+     */
+    public function paragraphs(string $channel, int $book): array
+    {
+        $key = self::paragraphsKey($channel, $book);
+        if (isset($this->paragraphs[$key])) {
+            return $this->paragraphs[$key];
+        }
+        // 存成连续区间 [[起, 止], …]:整本译完的书只有一个区间,展开成段号列表要八十多 KB
+        $ranges = RedisCache::remember(
+            $key,
+            (int) config('mint.cache.read_index_ttl'),
+            fn () => self::toRanges(Sentence::where('channel_uid', $channel)
+                ->where('book_id', $book)
+                ->where('strlen', '>', 0)
+                ->distinct()
+                ->orderBy('paragraph')
+                ->pluck('paragraph')
+                ->map(fn ($para) => (int) $para)
+                ->all())
+        );
+        $paras = [];
+        foreach ($ranges as [$from, $to]) {
+            array_push($paras, ...range($from, $to));
+        }
+
+        return $this->paragraphs[$key] = $paras;
+    }
+
+    /**
+     * 这本书「有译文的段」可能变了:删段号索引;书号索引按两个参数决定删不删。
+     *
+     * $mayAddBook(这本书现在有了译文)时,只有它不在已缓存的书号里才删;
+     * $mayRemoveBook(删了句子、strlen 变成 0、句子搬去了别的书或 channel)时一律删,下次重建。
+     */
+    public function forget(string $channel, int $book, bool $mayAddBook = false, bool $mayRemoveBook = false): void
+    {
+        $key = self::paragraphsKey($channel, $book);
+        RedisCache::forget($key);
+        unset($this->paragraphs[$key]);
+
+        if ($mayRemoveBook) {
+            RedisCache::forget(self::booksKey($channel));
+        } elseif ($mayAddBook) {
+            $books = RedisCache::get(self::booksKey($channel));
+            if (is_array($books) && ! in_array($book, $books, true)) {
+                RedisCache::forget(self::booksKey($channel));
+            }
+        }
+    }
+
+    /**
+     * 升序段号 → 连续区间。
+     *
+     * @param  list<int>  $paras
+     * @return list<array{int, int}>
+     */
+    public static function toRanges(array $paras): array
+    {
+        $ranges = [];
+        foreach ($paras as $para) {
+            $last = count($ranges) - 1;
+            if ($last >= 0 && $ranges[$last][1] === $para - 1) {
+                $ranges[$last][1] = $para;
+            } else {
+                $ranges[] = [$para, $para];
+            }
+        }
+
+        return $ranges;
+    }
+
+    private static function booksKey(string $channel): string
+    {
+        return "/read-index/{$channel}/books";
+    }
+
+    private static function paragraphsKey(string $channel, int $book): string
+    {
+        return "/read-index/{$channel}/{$book}";
+    }
+}

+ 64 - 1
api-v13/app/Services/RedisCache.php

@@ -28,6 +28,12 @@ use RedisCluster;
  *
  * 集群与 Laravel Cache 用的单机 Redis 不是同一个库,旧缓存不迁移,切换后冷启动。
  *
+ * 二进制(导出的 zip、epub 等)走另一组方法 putBinary / getBinary / binaryLength / getBinaryRange:
+ * 原样存字节,不经 JSON。同一个 key 只能用一组方法读写——用 get() 读二进制 key 会抛 JsonException,
+ * 所以二进制 key 要放在自己的命名空间下(如 `/tipitaka-export/file/…`)。大文件用 getBinaryRange
+ * 分块读(GETRANGE),不必把整个值读进 PHP 内存,也正好支持 HTTP Range。
+ * 2026-11-21 在 3 主 3 从集群上实测 40MB:SET 95ms、GET 76ms、1MB×40 次 GETRANGE 共 74ms,字节完整。
+ *
  * 业务代码通过门面 App\Facades\RedisCache 调用;测试用 RedisCache::fake()
  * 换成内存实现(见 RedisCacheFake)。
  */
@@ -121,6 +127,44 @@ class RedisCache
         return $this->incrementBy($this->key($key), $value);
     }
 
+    /**
+     * 原样写入字节(不经 JSON)。TTL 语义同 put()。
+     */
+    public function putBinary(string $key, string $bytes, DateTimeInterface|DateInterval|int|null $ttl = null): bool
+    {
+        $seconds = $this->secondsUntil($ttl ?? static::$defaultTtl);
+
+        if ($seconds <= 0) {
+            return $this->forget($key);
+        }
+
+        return $this->write($this->key($key), $bytes, $seconds);
+    }
+
+    /**
+     * 原样读回 putBinary() 写入的字节;不存在返回 null。
+     */
+    public function getBinary(string $key): ?string
+    {
+        return $this->read($this->key($key));
+    }
+
+    /**
+     * 值的字节数(STRLEN);不存在返回 null。
+     */
+    public function binaryLength(string $key): ?int
+    {
+        return $this->length($this->key($key));
+    }
+
+    /**
+     * 读字节闭区间 [$start, $end](GETRANGE),越界部分截掉;不存在返回空串。
+     */
+    public function getBinaryRange(string $key, int $start, int $end): string
+    {
+        return $this->range($this->key($key), $start, $end);
+    }
+
     /**
      * 前缀与 key 之间用 / 隔开:`dev` + `foo` → `dev/foo`;`/task/1` 本身带 /,得 `dev/task/1`。
      */
@@ -130,7 +174,7 @@ class RedisCache
     }
 
     /**
-     * 以下四个是仅有的 Redis 存取原语,RedisCacheFake 只需覆盖它们。
+     * 以下六个是仅有的 Redis 存取原语,RedisCacheFake 只需覆盖它们。
      * 参数 $key 已带前缀。
      */
     protected function read(string $key): ?string
@@ -160,6 +204,25 @@ class RedisCache
         return (int) $this->redis()->incrby($key, $value);
     }
 
+    /**
+     * STRLEN 对不存在的 key 返回 0,与空值分不清,所以先看 EXISTS。
+     */
+    protected function length(string $key): ?int
+    {
+        if (! $this->redis()->exists($key)) {
+            return null;
+        }
+
+        return (int) $this->redis()->strlen($key);
+    }
+
+    protected function range(string $key, int $start, int $end): string
+    {
+        $value = $this->redis()->getRange($key, $start, $end);
+
+        return is_string($value) ? $value : '';
+    }
+
     /**
      * 第一个参数 null 表示不读 php.ini 里的具名集群,直接用种子节点。
      */

+ 19 - 2
api-v13/app/Services/RedisCacheFake.php

@@ -5,8 +5,8 @@ namespace App\Services;
 /**
  * RedisCache 的内存实现,供测试使用(相当于 Laravel Cache 的 array store)。
  *
- * 只替换四个存取原语,序列化、TTL 换算、null 语义仍走 RedisCache 本身,
- * 所以测试覆盖到的是真实逻辑。通过 App\Facades\RedisCache::fake() 启用。
+ * 只替换存取原语,序列化、TTL 换算、null 语义仍走 RedisCache 本身,
+ * 所以测试覆盖到的是真实逻辑。二进制的 length / range 两个原语也在这里覆盖。通过 App\Facades\RedisCache::fake() 启用。
  */
 class RedisCacheFake extends RedisCache
 {
@@ -60,4 +60,21 @@ class RedisCacheFake extends RedisCache
 
         return $next;
     }
+
+    protected function length(string $key): ?int
+    {
+        $value = $this->read($key);
+
+        return $value === null ? null : strlen($value);
+    }
+
+    protected function range(string $key, int $start, int $end): string
+    {
+        $value = $this->read($key) ?? '';
+        if ($start >= strlen($value) || $end < $start) {
+            return '';
+        }
+
+        return substr($value, $start, $end - $start + 1);
+    }
 }

+ 47 - 0
api-v13/app/Services/V3/MarkupPreviewService.php

@@ -0,0 +1,47 @@
+<?php
+
+namespace App\Services\V3;
+
+use App\Services\Markup\MarkupService;
+use App\Services\Markup\RenderOptions;
+use Illuminate\Auth\Access\AuthorizationException;
+
+/**
+ * 源码预览:把一段还没保存的 markdown(模板生成器、编辑器里写到一半的内容)渲染成节点树。
+ *
+ * 渲染口径与保存后的阅读页相同({@see MarkupService},读模式)。
+ */
+class MarkupPreviewService
+{
+    public function __construct(
+        private readonly MarkupService $markup,
+        private readonly ChannelAbilityService $channels,
+    ) {}
+
+    /**
+     * 给了 channels 的,每个都要看得见(不存在 404、看不见 403),否则就能借预览读私有 channel 的译文。
+     *
+     * FIXME: 源码里模板自带的 channel(`{{sent|…|channel=…}}`、`{{65-464-2-27@channel}}`)在渲染器内部取数,
+     * 这里拦不到;SentenceLoader 不判可见性,存量的术语 / 批注正文也有同样的口子,要在 Markup 的取数层统一补。
+     *
+     * @param  array{content: string, content_type?: string, channels?: list<string>, lang?: string}  $input
+     * @return array{body: list<array<string, mixed>>}
+     *
+     * @throws AuthorizationException
+     */
+    public function preview(array $input, string $userUid, string $defaultLang): array
+    {
+        $channels = array_values(array_unique($input['channels'] ?? []));
+        foreach ($channels as $channel) {
+            $this->channels->assertReadable($channel, $userUid);
+        }
+
+        $body = $this->markup->render($input['content'], new RenderOptions(
+            channels: $channels,
+            contentType: $input['content_type'] ?? 'markdown',
+            lang: $input['lang'] ?? $defaultLang,
+        ));
+
+        return ['body' => is_array($body) ? $body : []];
+    }
+}

+ 260 - 0
api-v13/app/Services/V3/PaliTextService.php

@@ -0,0 +1,260 @@
+<?php
+
+namespace App\Services\V3;
+
+use App\Facades\RedisCache;
+use App\Models\PaliText;
+use App\Services\PaliContentService;
+
+/**
+ * 巴利原文段落表 `pali_texts` 的业务逻辑(2026-11-22 起,新代码里 pali_texts 的读取都放这里)。
+ *
+ * 这张表是经文静态数据,只有重新导入(`install:palitext` / `upgrade:palitext`)才会变,
+ * 所以按书缓存一个月,进程内再记一份:
+ *
+ * - 标题行(level < 8):一本书一个 key,阅读器算章节区间、导出排标题、章节范围都从这里取;
+ * - 全部段落的 level / class / 字节数:按 {@see self::CHUNK} 段一块,一本书最多一万六千段,
+ *   整本放一个 key 有四百多 KB,读一章只要其中一两块。
+ *
+ * 重新导入后调 {@see self::forgetBook()};改了缓存的结构就把 {@see self::VERSION} 加一(旧 key 自然过期)。
+ *
+ * 旧的 `App\Services\PaliTextService`(v2 在用)原样保留,不往那边加东西。
+ */
+class PaliTextService
+{
+    /** 缓存结构版本,改了缓存里存的字段就加一。 */
+    public const VERSION = 1;
+
+    /** 一个月。 */
+    public const TTL = 30 * 24 * 3600;
+
+    /** 段落按多少段一块缓存。 */
+    public const CHUNK = 1000;
+
+    /** 标题段的 level 上限(不含):1–7 是书 / 章 / 节等可导航节点,100 是正文。 */
+    public const HEADING_MAX_LEVEL = 8;
+
+    /** @var array<int, array<int, array{level: int, chapter_len: int, chapter_strlen: int, parent: int, toc: string}>> */
+    private array $headings = [];
+
+    /** @var array<string, array<int, array{int, string, int}>> */
+    private array $chunks = [];
+
+    /** @var array<int, array<int, int>> */
+    private array $flatChapters = [];
+
+    /**
+     * 一本书的全部标题段(level < 8),按段落号升序:段落号 => 标题信息。
+     *
+     * @return array<int, array{level: int, chapter_len: int, chapter_strlen: int, parent: int, toc: string}>
+     */
+    public function headings(int $book): array
+    {
+        if (isset($this->headings[$book])) {
+            return $this->headings[$book];
+        }
+        // 存成列表(段落号放在行里):键值对的 JSON 在键恰好是 0、1、2… 时会变成数组、读回来丢键
+        $rows = RedisCache::remember(
+            self::headingsKey($book),
+            self::TTL,
+            fn () => PaliText::where('book', $book)
+                ->where('level', '<', self::HEADING_MAX_LEVEL)
+                ->orderBy('paragraph')
+                ->get(['paragraph', 'level', 'chapter_len', 'chapter_strlen', 'parent', 'toc'])
+                ->map(fn (PaliText $row) => [
+                    (int) $row->paragraph, (int) $row->level, (int) $row->chapter_len,
+                    (int) $row->chapter_strlen, (int) $row->parent, (string) $row->toc,
+                ])
+                ->all()
+        );
+        $headings = [];
+        foreach ($rows as [$para, $level, $chapterLen, $chapterStrlen, $parent, $toc]) {
+            $headings[$para] = [
+                'level' => $level,
+                'chapter_len' => $chapterLen,
+                'chapter_strlen' => $chapterStrlen,
+                'parent' => $parent,
+                'toc' => $toc,
+            ];
+        }
+
+        return $this->headings[$book] = $headings;
+    }
+
+    /**
+     * 某段是标题段时返回它的标题信息,否则 null。
+     *
+     * @return array{level: int, chapter_len: int, chapter_strlen: int, parent: int, toc: string}|null
+     */
+    public function heading(int $book, int $para): ?array
+    {
+        return $this->headings($book)[$para] ?? null;
+    }
+
+    /**
+     * 段落是章节标题时返回标题级别(1–7),否则 0。
+     */
+    public function headingLevel(int $book, int $para): int
+    {
+        return $this->heading($book, $para)['level'] ?? 0;
+    }
+
+    /**
+     * 某段所在的书(level = 1 且段落号不大于它的最后一个标题段),没有返回 null。
+     *
+     * @return array{para: int, level: int, chapter_len: int, chapter_strlen: int, parent: int, toc: string}|null
+     */
+    public function bookStart(int $book, int $para): ?array
+    {
+        $found = null;
+        foreach ($this->headings($book) as $paragraph => $heading) {
+            if ($paragraph > $para) {
+                break;
+            }
+            if ($heading['level'] === 1) {
+                $found = ['para' => $paragraph] + $heading;
+            }
+        }
+
+        return $found;
+    }
+
+    /**
+     * 章节起始段落号 → 段落闭区间 [起, 止],长度取 chapter_len。
+     * 正文段(不是标题)没有 chapter_len,区间只有它自己;pali_texts 里没有这段返回 null。
+     *
+     * @return array{int, int}|null
+     */
+    public function chapterRange(int $book, int $chapter): ?array
+    {
+        $heading = $this->heading($book, $chapter);
+        if ($heading === null) {
+            return $this->paragraph($book, $chapter) === null ? null : [$chapter, $chapter];
+        }
+
+        return [$chapter, $chapter + max(1, $heading['chapter_len']) - 1];
+    }
+
+    /**
+     * 平铺的章节:每个标题段(level < 8)是一章的开头,到下一个标题段之前为止;章节按顺序排、不嵌套,
+     * 一段只属于一章。最后一章到它自己的 chapter_len 为止。章节起点 => 终点(含)。
+     *
+     * 与 chapter_len 的「父章包含子章」不同,这是阅读缓存用的切法({@see PaliContentService::readChapters()})。
+     *
+     * @return array<int, int>
+     */
+    public function flatChapters(int $book): array
+    {
+        if (isset($this->flatChapters[$book])) {
+            return $this->flatChapters[$book];
+        }
+        $chapters = [];
+        $starts = array_keys($this->headings($book));
+        foreach ($starts as $i => $start) {
+            $chapters[$start] = isset($starts[$i + 1])
+                ? $starts[$i + 1] - 1
+                : $start + max(1, $this->headings($book)[$start]['chapter_len']) - 1;
+        }
+
+        return $this->flatChapters[$book] = $chapters;
+    }
+
+    /**
+     * 某段所在平铺章节的起点({@see self::flatChapters()});排在第一个标题段之前、或超出最后一章的返回 null。
+     */
+    public function flatChapterOf(int $book, int $para): ?int
+    {
+        $found = null;
+        foreach ($this->flatChapters($book) as $start => $end) {
+            if ($start > $para) {
+                break;
+            }
+            $found = $para <= $end ? $start : null;
+        }
+
+        return $found;
+    }
+
+    /**
+     * 区间内各段的 level / class / 字节数:段落号 => 信息。pali_texts 里没有的段不出现。
+     *
+     * @return array<int, array{level: int, class: string, length: int}>
+     */
+    public function paragraphs(int $book, int $from, int $to): array
+    {
+        $result = [];
+        for ($chunk = intdiv(max(0, $from), self::CHUNK); $chunk <= intdiv(max(0, $to), self::CHUNK); $chunk++) {
+            foreach ($this->chunk($book, $chunk) as $para => [$level, $class, $length]) {
+                if ($para >= $from && $para <= $to) {
+                    $result[$para] = ['level' => $level, 'class' => $class, 'length' => $length];
+                }
+            }
+        }
+
+        return $result;
+    }
+
+    /**
+     * 单段的 level / class / 字节数,pali_texts 里没有返回 null。
+     *
+     * @return array{level: int, class: string, length: int}|null
+     */
+    public function paragraph(int $book, int $para): ?array
+    {
+        return $this->paragraphs($book, $para, $para)[$para] ?? null;
+    }
+
+    /**
+     * 重新导入某本书后调用,删掉它的全部缓存。
+     */
+    public function forgetBook(int $book): void
+    {
+        RedisCache::forget(self::headingsKey($book));
+        $max = (int) PaliText::where('book', $book)->max('paragraph');
+        // 段数可能变少,多删一块兜底
+        for ($chunk = 0; $chunk <= intdiv($max, self::CHUNK) + 1; $chunk++) {
+            RedisCache::forget(self::chunkKey($book, $chunk));
+        }
+        unset($this->headings[$book], $this->flatChapters[$book]);
+        $this->chunks = array_filter($this->chunks, fn ($key) => ! str_starts_with($key, "{$book}-"), ARRAY_FILTER_USE_KEY);
+    }
+
+    /**
+     * 一块段落:段落号 => [level, class, 字节数]。缓存里存成 [段落号, level, class, 字节数] 的列表。
+     *
+     * @return array<int, array{int, string, int}>
+     */
+    private function chunk(int $book, int $chunk): array
+    {
+        $memo = "{$book}-{$chunk}";
+        if (isset($this->chunks[$memo])) {
+            return $this->chunks[$memo];
+        }
+        $rows = RedisCache::remember(
+            self::chunkKey($book, $chunk),
+            self::TTL,
+            fn () => PaliText::where('book', $book)
+                ->whereBetween('paragraph', [$chunk * self::CHUNK, ($chunk + 1) * self::CHUNK - 1])
+                ->orderBy('paragraph')
+                ->get(['paragraph', 'level', 'class', 'lenght'])
+                ->map(fn (PaliText $row) => [(int) $row->paragraph, (int) $row->level, (string) $row->class, (int) $row->lenght])
+                ->all()
+        );
+        $paragraphs = [];
+        foreach ($rows as [$para, $level, $class, $length]) {
+            $paragraphs[$para] = [$level, $class, $length];
+        }
+
+        return $this->chunks[$memo] = $paragraphs;
+    }
+
+    private static function headingsKey(int $book): string
+    {
+        return '/pali-text/v'.self::VERSION."/{$book}/headings";
+    }
+
+    private static function chunkKey(int $book, int $chunk): string
+    {
+        return '/pali-text/v'.self::VERSION."/{$book}/paragraphs/{$chunk}";
+    }
+}

+ 1 - 1
api-v13/app/Services/V3/TipitakaBookService.php

@@ -15,7 +15,7 @@ use Illuminate\Support\Collection;
 class TipitakaBookService
 {
     /** 书的 tag → layer(同 TipitakaTitleService),一本书有多个时按这个顺序取第一个 */
-    private const LAYER_TAGS = ['mūla' => 'mula', 'aṭṭhakathā' => 'atthakatha', 'ṭīkā' => 'tika', 'añña' => 'anna'];
+    private const LAYER_TAGS = ['mūla' => 'mula', 'aṭṭhakathā' => 'atthakatha', 'ṭīkā' => 'tika', 'vinaya-añña' => 'tika', 'añña' => 'anna'];
 
     /**
      * 结果以 book_id 为键;book_titles 里没有的书不在其中。

+ 578 - 0
api-v13/app/Services/V3/TipitakaExportBuilder.php

@@ -0,0 +1,578 @@
+<?php
+
+namespace App\Services\V3;
+
+use App\Models\Channel;
+use App\Services\TipitakaCatalogService;
+use DOMDocument;
+use DOMXPath;
+use Illuminate\Support\Facades\App;
+use Illuminate\Support\Facades\File;
+use Illuminate\Support\Str;
+use RuntimeException;
+use Symfony\Component\Process\Process;
+use ZipArchive;
+
+/**
+ * 生成三藏下载的文件(由 TipitakaExportService::run() 在 worker 里调用)。
+ *
+ * 正文一律经 TipitakaReadingService::page() 取,和 `/v3/tipitaka-reading` 是同一份渲染:
+ * html / offline 用 display(段落 HTML),markdown / epub / docx 用逐句的 markdown
+ * (句末附脚注正文,这里整章重新编号)。epub、docx 由 pandoc 从 markdown 转换,
+ * 这样脚注能变成电子书 / Word 里真正的脚注。
+ *
+ * 中间文件写在 storage/app/tmp/tipitaka-export/ 下的临时目录,每部作品写完就落盘,
+ * zip 最后用 addFile 收集——整个 channel 的正文不会同时留在内存里。
+ */
+class TipitakaExportBuilder
+{
+    public function __construct(
+        private readonly TipitakaReadingService $reading,
+        private readonly TipitakaCatalogService $catalog,
+        private readonly PaliTextService $paliTexts,
+    ) {}
+
+    /**
+     * 生成文件,返回文件字节。
+     *
+     * @param  array<string, mixed>  $status  导出状态(TipitakaExportService::spec() 的字段)
+     * @param  array{kind: string, works: list<array<string, mixed>>, title: string}  $scope
+     * @param  callable(float, string): void  $progress  进度 0–1 与说明
+     */
+    public function build(array $status, array $scope, callable $progress): string
+    {
+        $dir = storage_path('app/tmp/tipitaka-export/'.$status['id'].'-'.Str::random(6));
+        File::ensureDirectoryExists($dir);
+        $context = $this->context($status['channel']);
+        // 文件里的界面文字(目录、生成日期…)跟着译文的语言走,而不是 worker 进程的默认语言
+        $previousLocale = App::getLocale();
+        App::setLocale(self::locale($context['lang']));
+
+        try {
+            $format = $status['format'];
+            $single = $scope['kind'] === 'work';
+            $works = $scope['works'];
+            $count = count($works);
+            // 打包时 zip 里套一层与文件名同名的目录,解压后不会散落一地
+            $root = $single ? '' : pathinfo(pathinfo($status['filename'], PATHINFO_FILENAME), PATHINFO_FILENAME).'/';
+            $entries = [];
+
+            foreach ($works as $i => $work) {
+                $tick = function (float $fraction) use ($progress, $i, $count, $work): void {
+                    $progress(0.9 * ($i + $fraction) / $count, ($i + 1)."/{$count} {$work['local_title']}");
+                };
+                $path = $single ? '' : $this->categoryFolder($work, $context['lang']).'/';
+                $name = self::safeName("{$work['sn']}-{$work['local_title']}");
+
+                match ($format) {
+                    'offline' => $entries[''] = $this->offline($dir, $status, $work, $tick),
+                    'html' => $entries[$single ? self::safeName($work['local_title']).'.html' : "{$root}works/{$name}.html"]
+                        = $this->writeFile($dir, "w{$i}.html", $this->htmlWork($context, $work, $this->paragraphs($context['uid'], $work, 'html', $tick), $single ? null : '../index.html')),
+                    'markdown' => $entries += $this->markdownWork($dir, $i, $context, $work, $this->paragraphs($context['uid'], $work, 'markdown', $tick), $single ? self::safeName($work['local_title']).'/' : "{$root}{$path}{$name}/"),
+                    'epub', 'docx' => $entries[$single ? '' : "{$root}{$path}{$name}.{$format}"]
+                        = $this->pandoc($dir, $i, $format, $context, $work, $this->paragraphs($context['uid'], $work, 'markdown', $tick)),
+                };
+            }
+
+            $progress(0.92, 'packing');
+            if ($format === 'offline' || ($single && in_array($format, ['epub', 'docx'], true))) {
+                return (string) file_get_contents($entries['']);
+            }
+            if (! $single) {
+                $entries += match ($format) {
+                    'html' => ["{$root}index.html" => $this->writeFile($dir, 'index.html', $this->htmlIndex($context, $scope))],
+                    default => ["{$root}README.md" => $this->writeFile($dir, 'index.md', $this->markdownIndex($context, $scope, $format))],
+                };
+            }
+
+            return $this->zip($dir, $entries);
+        } finally {
+            App::setLocale($previousLocale);
+            File::deleteDirectory($dir);
+        }
+    }
+
+    /**
+     * channel 的语言(如 zh、zh-Hant、en-US)→ 受支持的界面语言,匹配不上用 en。
+     */
+    public static function locale(string $lang): string
+    {
+        $tag = strtolower($lang);
+        if (str_starts_with($tag, 'zh')) {
+            return preg_match('/hant|tw|hk|mo/', $tag) ? 'zh-Hant' : 'zh-Hans';
+        }
+        $primary = explode('-', $tag)[0];
+
+        return array_key_exists($primary, (array) config('mint.languages')) ? $primary : 'en';
+    }
+
+    /**
+     * 文件 / 目录名:去掉文件系统不允许的字符,限长。
+     */
+    public static function safeName(string $name): string
+    {
+        $name = trim((string) preg_replace('/[\\\\\/:*?"<>|\x00-\x1f]+/u', ' ', $name));
+        $name = (string) preg_replace('/\s+/u', ' ', $name);
+
+        return mb_substr($name === '' ? 'untitled' : $name, 0, 80);
+    }
+
+    /**
+     * 一部作品的全部段落(按经文顺序),附上标题级别。没有译文的段落不在其中。
+     *
+     * @param  array<string, mixed>  $work
+     * @param  callable(float): void  $tick
+     * @return list<array{para: int, level: int, display?: string, sentences?: list<array{sid: string, html: string}>}>
+     */
+    private function paragraphs(string $channel, array $work, string $format, callable $tick): array
+    {
+        $levels = $this->headingLevels($work);
+        $items = [];
+        $after = null;
+        do {
+            $page = $this->reading->page($channel, array_filter([
+                'book' => $work['book'],
+                'para' => $work['para'],
+                'to' => $work['end'],
+                'unit' => 'para',
+                'page_size' => TipitakaReadingService::MAX_PARAGRAPHS_PER_PAGE,
+                'format' => $format,
+                'include' => $format === 'html' ? 'display' : 'sentences',
+                'after' => $after,
+            ]));
+            foreach ($page['items'] as $item) {
+                unset($item['book']);
+                $items[] = $item + ['level' => $levels[$item['para']] ?? 0];
+            }
+            $total = (int) ($page['meta']['total'] ?? 0);
+            $tick($total > 0 ? 1 - ((int) ($page['meta']['remaining'] ?? 0)) / $total : 1.0);
+            $after = $page['meta']['next_cursor'];
+        } while ($after !== null);
+
+        return $items;
+    }
+
+    /**
+     * 作品区间里的标题段落:段落号 => 级别(1–7)。
+     *
+     * @param  array<string, mixed>  $work
+     * @return array<int, int>
+     */
+    private function headingLevels(array $work): array
+    {
+        return array_map(fn (array $heading) => $heading['level'], $this->headingsIn($work));
+    }
+
+    /**
+     * 作品区间里的标题:段落号 => [级别, 巴利标题]。译文没有译出标题时拿巴利标题顶上。
+     *
+     * @param  array<string, mixed>  $work
+     * @return array<int, array{int, string}>
+     */
+    private function headings(array $work): array
+    {
+        return array_map(fn (array $heading) => [$heading['level'], $heading['toc']], $this->headingsIn($work));
+    }
+
+    /**
+     * 作品区间里的标题段(缓存的经文静态数据),按段落号升序。
+     *
+     * @param  array<string, mixed>  $work
+     * @return array<int, array{level: int, chapter_len: int, chapter_strlen: int, parent: int, toc: string}>
+     */
+    private function headingsIn(array $work): array
+    {
+        return array_filter(
+            $this->paliTexts->headings((int) $work['book']),
+            fn (int $para) => $para >= $work['para'] && $para <= $work['end'],
+            ARRAY_FILTER_USE_KEY,
+        );
+    }
+
+    /**
+     * @return array{uid: string, name: string, lang: string, generated_at: string}
+     */
+    private function context(string $channel): array
+    {
+        $row = Channel::where('uid', $channel)->first(['uid', 'name', 'lang']);
+
+        return [
+            'uid' => $channel,
+            'name' => (string) $row?->name,
+            'lang' => (string) ($row?->lang ?: 'en'),
+            'generated_at' => now()->toDateString(),
+        ];
+    }
+
+    /**
+     * 打包时作品所在的目录:分类路径(本地化名字),没有分类的放「其他」。
+     *
+     * @param  array<string, mixed>  $work
+     */
+    private function categoryFolder(array $work, string $lang): string
+    {
+        return implode('/', array_map(self::safeName(...), $this->categoryNames($work, $lang)));
+    }
+
+    /**
+     * @param  array<string, mixed>  $work
+     * @return list<string>
+     */
+    private function categoryNames(array $work, string $lang): array
+    {
+        if ($work['category_id'] === null) {
+            return [__('library.export_uncategorized')];
+        }
+        $path = $this->catalog->categoryPath($work['category_id']);
+        // 分类名查术语表要用界面语言(zh-Hans),channel 的语言常写成 zh
+        $names = $this->catalog->localNames($this->catalog->categories(), self::locale($lang));
+
+        return array_map(fn ($c) => $names[$c['name']] ?? $c['name'], $path);
+    }
+
+    // ── html ────────────────────────────────────────────────────────────
+
+    /**
+     * 一部作品的单个 HTML 文件(样式内联,离线可用)。
+     *
+     * @param  array<string, mixed>  $context
+     * @param  array<string, mixed>  $work
+     * @param  list<array{para: int, level: int, display?: string}>  $paragraphs
+     */
+    private function htmlWork(array $context, array $work, array $paragraphs, ?string $indexHref): string
+    {
+        $baseLevel = $paragraphs === [] ? 1 : min(array_map(fn ($p) => $p['level'] ?: 99, $paragraphs));
+        $toc = [];
+        $body = '';
+        foreach ($paragraphs as $p) {
+            // pali_texts 的级别到 7,html 只有 h1–h6
+            $body .= preg_replace('#<(/?)h7>#', '<$1h6>', $p['display']);
+            if ($p['level'] > 0 && $p['level'] <= $baseLevel + 2) {
+                $toc[] = ['id' => "para-{$p['para']}", 'depth' => $p['level'] - $baseLevel, 'title' => $this->plainText($p['display'])];
+            }
+        }
+
+        return view('exports.tipitaka.work', [
+            'context' => $context,
+            'work' => $work,
+            'toc' => $toc,
+            'body' => $body,
+            'indexHref' => $indexHref,
+            'sourceUrl' => route('library.tipitaka.channels.work', ['channel' => $context['uid'], 'sn' => $work['sn']]),
+        ])->render();
+    }
+
+    /**
+     * 打包时的 index.html:按藏 / 分类分组列出作品,可搜索。
+     *
+     * @param  array<string, mixed>  $context
+     * @param  array{kind: string, works: list<array<string, mixed>>, title: string}  $scope
+     */
+    private function htmlIndex(array $context, array $scope): string
+    {
+        $groups = [];
+        foreach ($scope['works'] as $work) {
+            $names = $this->categoryNames($work, $context['lang']);
+            $top = $names[0];
+            $sub = implode(' · ', array_slice($names, 1)) ?: $top;
+            $groups[$top][$sub][] = [
+                'title' => $work['local_title'],
+                'pali' => $work['title'],
+                'progress' => (int) round($work['progress'] * 100),
+                'href' => 'works/'.rawurlencode(self::safeName("{$work['sn']}-{$work['local_title']}")).'.html',
+            ];
+        }
+
+        return view('exports.tipitaka.index', [
+            'context' => $context,
+            'scope' => $scope,
+            'groups' => $groups,
+            'averageProgress' => (int) round(100 * array_sum(array_column($scope['works'], 'progress')) / max(1, count($scope['works']))),
+            'sourceUrl' => route('library.tipitaka.channels.show', ['channel' => $context['uid']]),
+        ])->render();
+    }
+
+    /**
+     * HTML 片段的纯文字(目录用):去掉边注、脚注列表这些不属于标题的部分。
+     */
+    private function plainText(string $html): string
+    {
+        $doc = new DOMDocument;
+        @$doc->loadHTML('<?xml encoding="UTF-8"><div>'.$html.'</div>', LIBXML_NOERROR);
+        $xpath = new DOMXPath($doc);
+        foreach ($xpath->query('//*[contains(@class,"sidenote") or contains(@class,"anno-footnotes") or contains(@class,"margin-toggle")]') ?: [] as $node) {
+            $node->parentNode?->removeChild($node);
+        }
+
+        return trim((string) preg_replace('/\s+/u', ' ', $doc->textContent));
+    }
+
+    // ── markdown ────────────────────────────────────────────────────────
+
+    /**
+     * 一部作品的 markdown:README.md(目录)+ 每章一个文件。返回 zip 条目 => 临时文件。
+     *
+     * @param  array<string, mixed>  $context
+     * @param  array<string, mixed>  $work
+     * @param  list<array{para: int, level: int, sentences?: list<array{sid: string, html: string}>}>  $paragraphs
+     * @return array<string, string>
+     */
+    private function markdownWork(string $dir, int $index, array $context, array $work, array $paragraphs, string $prefix): array
+    {
+        $chapters = $this->chapters($work, $paragraphs);
+        $entries = [];
+        $toc = [];
+        // 00 只给序言(第一章之前的段落),正式的章从 01 起
+        $offset = ($chapters[0]['start'] ?? null) === 0 ? 0 : 1;
+        foreach ($chapters as $i => $chapter) {
+            $file = sprintf('%02d-%s.md', $i + $offset, self::safeName($chapter['title']));
+            $entries[$prefix.$file] = $this->writeFile($dir, "w{$index}-{$i}.md", $this->markdown($chapter['paragraphs'], $chapter['level']));
+            $toc[] = '- ['.$this->escapeLink($chapter['title']).'](<'.$file.'>)';
+        }
+        $readme = "# {$work['local_title']}\n\n*{$work['title']}* · {$context['name']}\n\n"
+            .__('library.export_generated_at', ['date' => $context['generated_at']])."\n\n"
+            .implode("\n", $toc)."\n";
+        $entries[$prefix.'README.md'] = $this->writeFile($dir, "w{$index}-readme.md", $readme);
+
+        return $entries;
+    }
+
+    /**
+     * 打包时的总目录 README.md:按分类列出各部作品(markdown 指向作品目录,epub / docx 指向文件)。
+     *
+     * @param  array<string, mixed>  $context
+     * @param  array{kind: string, works: list<array<string, mixed>>, title: string}  $scope
+     */
+    private function markdownIndex(array $context, array $scope, string $format): string
+    {
+        $lines = ["# {$scope['title']}", '', "{$context['name']} · ".__('library.export_generated_at', ['date' => $context['generated_at']])];
+        $current = null;
+        foreach ($scope['works'] as $work) {
+            $folder = $this->categoryFolder($work, $context['lang']);
+            if ($folder !== $current) {
+                $lines[] = '';
+                $lines[] = '## '.str_replace('/', ' / ', $folder);
+                $lines[] = '';
+                $current = $folder;
+            }
+            $name = self::safeName("{$work['sn']}-{$work['local_title']}");
+            $target = $format === 'markdown' ? "{$folder}/{$name}/README.md" : "{$folder}/{$name}.{$format}";
+            $lines[] = '- ['.$this->escapeLink($work['local_title']).'](<'.$target.'>) · *'.$work['title'].'*';
+        }
+
+        return implode("\n", $lines)."\n";
+    }
+
+    /**
+     * 按章切分:作品区间里比作品本身低一级的标题(实际出现的最高一级)各成一章;
+     * 第一章之前的段落(作品标题、序言)归到第 0 章。没有译文的章不出现。
+     *
+     * @param  array<string, mixed>  $work
+     * @param  list<array{para: int, level: int, sentences?: list<array{sid: string, html: string}>}>  $paragraphs
+     * @return list<array{start: int, title: string, level: int, paragraphs: list<array<string, mixed>>}>
+     */
+    private function chapters(array $work, array $paragraphs): array
+    {
+        $headings = $this->headings($work);
+        $inner = array_filter($headings, fn ($h, $para) => $para > $work['para'], ARRAY_FILTER_USE_BOTH);
+        $splitLevel = $inner === [] ? 99 : min(array_column($inner, 0));
+        $starts = array_keys(array_filter($inner, fn ($h) => $h[0] === $splitLevel));
+
+        $chapters = [];
+        foreach ($paragraphs as $p) {
+            $start = 0;
+            foreach ($starts as $s) {
+                if ($s > $p['para']) {
+                    break;
+                }
+                $start = $s;
+            }
+            $chapters[$start] ??= ['start' => $start, 'title' => $start === 0 ? $work['local_title'] : $headings[$start][1], 'level' => $splitLevel, 'paragraphs' => []];
+            if ($p['para'] === $start) {
+                // 章标题段有译文就用译文作章名
+                $chapters[$start]['title'] = $this->markdownPlain($p) ?: $chapters[$start]['title'];
+            }
+            if ($start === 0 && $p['para'] === $work['para']) {
+                // 作品标题是 README 的标题,不在第 0 章里重复
+                continue;
+            }
+            $chapters[$start]['paragraphs'][] = $p;
+        }
+
+        return array_values(array_filter($chapters, fn ($c) => $c['paragraphs'] !== []));
+    }
+
+    /**
+     * 把段落拼成一篇 markdown:标题段加 #($baseLevel 那一级是 #),脚注整篇重新编号、正文放在文末。
+     *
+     * @param  list<array{para: int, level: int, sentences?: list<array{sid: string, html: string}>}>  $paragraphs
+     */
+    private function markdown(array $paragraphs, int $baseLevel): string
+    {
+        $number = 0;
+        $notes = [];
+        $blocks = [];
+        foreach ($paragraphs as $p) {
+            $parts = [];
+            foreach ($p['sentences'] ?? [] as $sentence) {
+                $pieces = preg_split('/\n\n(?=\[\^\d+\]: )/', $sentence['html']) ?: [$sentence['html']];
+                $map = [];
+                foreach (array_slice($pieces, 1) as $piece) {
+                    if (preg_match('/^\[\^(\d+)\]: (.*)$/s', $piece, $m)) {
+                        $map[$m[1]] = ++$number;
+                        // 脚注正文多行时后续行要缩进,否则 pandoc 只认第一行
+                        $notes[] = "[^{$number}]: ".str_replace("\n", "\n    ", trim($m[2]));
+                    }
+                }
+                $parts[] = preg_replace_callback('/\[\^(\d+)\]/', fn ($m) => isset($map[$m[1]]) ? "[^{$map[$m[1]]}]" : '', $pieces[0]);
+            }
+            $text = trim(implode("\n", $parts));
+            if ($text === '') {
+                continue;
+            }
+            if ($p['level'] > 0) {
+                $text = str_repeat('#', max(1, min(6, $p['level'] - $baseLevel + 1))).' '.str_replace("\n", ' ', $text);
+            }
+            $blocks[] = $text;
+        }
+
+        return implode("\n\n", $blocks)."\n".($notes === [] ? '' : "\n".implode("\n\n", $notes)."\n");
+    }
+
+    /**
+     * 段落 markdown 的纯文字(章名用):去掉脚注标记与正文。
+     *
+     * @param  array{sentences?: list<array{html: string}>}  $paragraph
+     */
+    private function markdownPlain(array $paragraph): string
+    {
+        $text = implode(' ', array_map(
+            fn ($s) => (string) preg_replace('/\[\^\d+\]/', '', (preg_split('/\n\n(?=\[\^\d+\]: )/', $s['html']) ?: [''])[0]),
+            $paragraph['sentences'] ?? [],
+        ));
+
+        return trim((string) preg_replace('/[*_`#]+|\s+/u', ' ', $text));
+    }
+
+    private function escapeLink(string $text): string
+    {
+        return str_replace(['[', ']'], ['\\[', '\\]'], $text);
+    }
+
+    // ── pandoc ──────────────────────────────────────────────────────────
+
+    /**
+     * 整部作品拼成一篇 markdown,交给 pandoc 转 epub / docx,返回生成的临时文件路径。
+     *
+     * @param  array<string, mixed>  $context
+     * @param  array<string, mixed>  $work
+     * @param  list<array<string, mixed>>  $paragraphs
+     */
+    private function pandoc(string $dir, int $index, string $format, array $context, array $work, array $paragraphs): string
+    {
+        $chapters = $this->chapters($work, $paragraphs);
+        $source = '';
+        foreach ($chapters as $chapter) {
+            // 第 0 章(序言)没有自己的标题段,补一个,epub 目录里才有它
+            $first = $chapter['paragraphs'][0];
+            $needsTitle = $first['level'] !== $chapter['level'] && $chapter['level'] !== 99;
+            $source .= ($needsTitle ? '# '.$chapter['title']."\n\n" : '').$this->markdown($chapter['paragraphs'], $chapter['level'])."\n";
+        }
+        $input = $this->writeFile($dir, "w{$index}.md", $source === '' ? "\n" : $source);
+        $output = "{$dir}/w{$index}.{$format}";
+
+        $command = [
+            (string) config('mint.tipitaka_export.pandoc'),
+            $input,
+            // 译文里的 $、~、^ 与 --- 不是数学公式 / 上下标 / 元数据块
+            '--from=markdown+east_asian_line_breaks-tex_math_dollars-raw_tex-subscript-superscript-yaml_metadata_block',
+            '--output='.$output,
+            '--toc',
+            '--toc-depth=2',
+            '--metadata=title:'.$work['local_title'],
+            '--metadata=subtitle:'.$work['title'],
+            '--metadata=author:'.$context['name'],
+            '--metadata=lang:'.$context['lang'],
+            '--metadata=date:'.$context['generated_at'],
+        ];
+        if ($format === 'epub') {
+            $command[] = '--css='.resource_path('template/epub/tipitaka.css');
+            $command[] = '--split-level=1';
+        } else {
+            $command[] = '--reference-doc='.resource_path('template/docx/paper.docx');
+        }
+
+        $process = new Process($command, $dir, null, null, (float) config('mint.tipitaka_export.pandoc_timeout'));
+        $process->run();
+        if (! $process->isSuccessful()) {
+            throw new RuntimeException('pandoc failed: '.mb_substr($process->getErrorOutput(), 0, 2000));
+        }
+
+        return $output;
+    }
+
+    // ── offline ─────────────────────────────────────────────────────────
+
+    /**
+     * mobile 离线包:NDJSON,首行头、每段一行、末行 end(客户端用 count 校验完整)。
+     * 存的是 gzip 后的字节,下载接口以 `Content-Encoding: gzip` 发出。
+     * `html` 与 `/v3/tipitaka-reading?format=html&include=display` 的 display 完全相同。
+     *
+     * @param  array<string, mixed>  $status
+     * @param  array<string, mixed>  $work
+     * @param  callable(float): void  $tick
+     */
+    private function offline(string $dir, array $status, array $work, callable $tick): string
+    {
+        $paragraphs = $this->paragraphs($status['channel'], $work, 'html', $tick);
+        $flags = JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES;
+        $lines = [json_encode([
+            'type' => 'header',
+            'format' => 1,
+            'id' => $status['id'],
+            'channel' => $status['channel'],
+            'sn' => $work['sn'],
+            'book' => $work['book'],
+            'para' => $work['para'],
+            'end' => $work['end'],
+            'paragraphs' => count($paragraphs),
+        ], $flags)];
+        foreach ($paragraphs as $p) {
+            $lines[] = json_encode(['type' => 'para', 'book' => $work['book'], 'para' => $p['para'], 'html' => $p['display']], $flags);
+        }
+        $lines[] = json_encode(['type' => 'end', 'count' => count($paragraphs)], $flags);
+
+        return $this->writeFile($dir, 'offline.ndjson.gz', (string) gzencode(implode("\n", $lines)."\n", 6));
+    }
+
+    // ── files ───────────────────────────────────────────────────────────
+
+    private function writeFile(string $dir, string $name, string $content): string
+    {
+        $path = "{$dir}/{$name}";
+        file_put_contents($path, $content);
+
+        return $path;
+    }
+
+    /**
+     * 把临时文件按条目名打成 zip,返回 zip 字节。条目名按 UTF-8 标记,中文文件名解压不乱码。
+     *
+     * @param  array<string, string>  $entries  zip 里的路径 => 临时文件
+     */
+    private function zip(string $dir, array $entries): string
+    {
+        $path = "{$dir}/_bundle.zip";
+        $zip = new ZipArchive;
+        if ($zip->open($path, ZipArchive::CREATE | ZipArchive::OVERWRITE) !== true) {
+            throw new RuntimeException("cannot create zip {$path}");
+        }
+        ksort($entries, SORT_NATURAL);
+        foreach ($entries as $name => $file) {
+            $zip->addFile($file, $name, 0, 0, ZipArchive::FL_OVERWRITE | ZipArchive::FL_ENC_UTF_8);
+        }
+        $zip->close();
+
+        return (string) file_get_contents($path);
+    }
+}

+ 85 - 0
api-v13/app/Services/V3/TipitakaExportDownload.php

@@ -0,0 +1,85 @@
+<?php
+
+namespace App\Services\V3;
+
+use App\Facades\RedisCache;
+use Symfony\Component\HttpFoundation\HeaderUtils;
+use Symfony\Component\HttpFoundation\Response;
+use Symfony\Component\HttpFoundation\StreamedResponse;
+
+/**
+ * 把 Redis 里的导出文件流给客户端:按 1MB 分块 GETRANGE 读,不把整个文件读进 PHP 内存;
+ * 支持单段 `Range`(mobile 断点续传)与 `If-None-Match`(id 即内容指纹,可当强 ETag)。
+ */
+class TipitakaExportDownload
+{
+    private const CHUNK = 1024 * 1024;
+
+    public function __construct(private readonly TipitakaExportService $exports) {}
+
+    public function respond(string $id, ?string $range, ?string $ifNoneMatch): Response
+    {
+        $file = $this->exports->file($id);
+        if ($file === null) {
+            abort(404, __('messages.export_not_found'));
+        }
+        $etag = '"'.$id.'"';
+        $headers = [
+            'Content-Type' => $file['content_type'],
+            'Content-Disposition' => HeaderUtils::makeDisposition(
+                HeaderUtils::DISPOSITION_ATTACHMENT,
+                $file['filename'],
+                $this->asciiFallback($file['filename']),
+            ),
+            'Accept-Ranges' => 'bytes',
+            'ETag' => $etag,
+            'Cache-Control' => 'private, max-age=0, must-revalidate',
+        ];
+        if ($file['content_encoding'] !== null) {
+            // 离线包:表示是 NDJSON,传输编码 gzip。Range / Content-Length 都按 gzip 后的字节算
+            $headers['Content-Encoding'] = $file['content_encoding'];
+            $headers['Vary'] = 'Accept-Encoding';
+        }
+        if ($ifNoneMatch !== null && in_array($etag, array_map('trim', explode(',', $ifNoneMatch)), true)) {
+            return new Response('', 304, $headers);
+        }
+
+        $size = $file['size'];
+        [$start, $end] = [0, $size - 1];
+        $status = 200;
+        if ($range !== null && preg_match('/^bytes=(\d*)-(\d*)$/', trim($range), $m) && ($m[1] !== '' || $m[2] !== '')) {
+            if ($m[1] === '') {
+                // bytes=-500:最后 500 字节
+                $start = max(0, $size - (int) $m[2]);
+            } else {
+                $start = (int) $m[1];
+                $end = $m[2] === '' ? $size - 1 : min($size - 1, (int) $m[2]);
+            }
+            if ($start > $end || $start >= $size) {
+                return new Response('', 416, $headers + ['Content-Range' => "bytes */{$size}"]);
+            }
+            $status = 206;
+            $headers['Content-Range'] = "bytes {$start}-{$end}/{$size}";
+        }
+        $headers['Content-Length'] = (string) ($end - $start + 1);
+        $key = $this->exports->fileKey($id);
+
+        return new StreamedResponse(function () use ($key, $start, $end) {
+            for ($offset = $start; $offset <= $end; $offset += self::CHUNK) {
+                echo RedisCache::getBinaryRange($key, $offset, min($end, $offset + self::CHUNK - 1));
+                flush();
+            }
+        }, $status, $headers);
+    }
+
+    /**
+     * Content-Disposition 的 filename= 只能是 ASCII,中文名放在 filename*= 里。
+     */
+    private function asciiFallback(string $filename): string
+    {
+        $ascii = (string) preg_replace('/[^\x20-\x7e]+/', '_', $filename);
+        $ascii = str_replace(['"', '\\', '/', '%'], '_', $ascii);
+
+        return trim($ascii, '_ ') === '' || str_starts_with($ascii, '_.') ? 'tipitaka'.strrchr($filename, '.') : $ascii;
+    }
+}

+ 25 - 0
api-v13/app/Services/V3/TipitakaExportQueue.php

@@ -0,0 +1,25 @@
+<?php
+
+namespace App\Services\V3;
+
+use App\Http\Api\Mq;
+
+/**
+ * 三藏下载的生成任务投递到 RabbitMQ,由 `mq:export.tipitaka` 消费。
+ *
+ * 分两个队列:单部作品(几秒钟)走 `export_tipitaka`,打包(分类 / 整个 channel,大的要一个多小时)
+ * 走 `export_tipitaka_bulk`,各有自己的 worker——否则一个整库打包会把后面所有单部作品的下载堵上一小时。
+ *
+ * 单独成类只为测试能换掉它(`$this->mock(TipitakaExportQueue::class)`),不连真的 RabbitMQ。
+ */
+class TipitakaExportQueue
+{
+    public const QUEUE = 'export_tipitaka';
+
+    public const BULK_QUEUE = 'export_tipitaka_bulk';
+
+    public function push(string $exportId, bool $bulk): void
+    {
+        Mq::publish($bulk ? self::BULK_QUEUE : self::QUEUE, ['id' => $exportId]);
+    }
+}

+ 434 - 0
api-v13/app/Services/V3/TipitakaExportService.php

@@ -0,0 +1,434 @@
+<?php
+
+namespace App\Services\V3;
+
+use App\Exceptions\BusinessException;
+use App\Facades\RedisCache;
+use App\Models\Channel;
+use App\Models\Sentence;
+use App\Services\TipitakaCatalogService;
+use Illuminate\Database\Eloquent\Builder;
+use Illuminate\Support\Carbon;
+use Illuminate\Support\Facades\Log;
+use Illuminate\Support\Facades\URL;
+use Illuminate\Validation\ValidationException;
+use Throwable;
+
+/**
+ * 三藏下载:把一个 channel 的一部作品、一个分类或整个 channel 导出成文件。
+ *
+ * 流程:请求方 request() → 已有同一份文件就直接给;没有就写一条 queued 状态、投递到 RabbitMQ
+ * (TipitakaExportQueue:单部作品与打包分两个队列)→ worker `mq:export.tipitaka` 调 run() 生成(TipitakaExportBuilder)→
+ * 文件以二进制存进 Redis 集群(RedisCache::putBinary),保留 `mint.tipitaka_export.ttl`。
+ *
+ * **id 就是内容指纹**:channel + 范围 + 格式 + 模板版本 + 范围内句子的最后修改时间与条数。
+ * 所以谁先生成谁就给后来的人用;译文一改,指纹就变,自然重新生成,不需要失效逻辑。
+ *
+ * 格式:html(单部作品一个文件,打包时加 index.html)、markdown(每章一个文件 + 目录)、
+ * epub / docx(pandoc 生成;单部作品直接给文件,打包时一部一个)、offline(mobile 离线包,
+ * gzip 的 NDJSON,一行一段,`html` 与 `tipitaka-reading` 的 display 一致;只按作品)。
+ */
+class TipitakaExportService
+{
+    public const FORMATS = ['html', 'markdown', 'epub', 'docx', 'offline'];
+
+    /**
+     * 模板 / 文件结构改了就加一,让已经生成好的旧文件不再命中。
+     */
+    public const TEMPLATE_VERSION = 2;
+
+    /**
+     * 范围统计(字数、最后修改时间)缓存多久。整个大 channel 求 max(updated_at) 要两秒,
+     * 下载页每次打开都算不划算;代价是五分钟内的修改要等缓存过期才会触发重新生成。
+     */
+    private const STATS_TTL = 300;
+
+    public function __construct(
+        private readonly TipitakaCatalogService $catalog,
+        private readonly ChannelAbilityService $abilities,
+        private readonly TipitakaExportQueue $queue,
+        private readonly TipitakaExportBuilder $builder,
+    ) {}
+
+    /**
+     * 发起一次导出。已有可用的文件,或同一份正在生成,就直接返回它的状态,不重复排队。
+     *
+     * @param  array{channel: string, work?: int, book?: int, para?: int, category?: int, format: string}  $input
+     * @return array<string, mixed> present() 的结果
+     */
+    public function request(array $input, ?string $userUid): array
+    {
+        $channel = $input['channel'];
+        $this->abilities->assertReadable($channel, $userUid);
+        $format = $input['format'];
+        $work = $input['work'] ?? (isset($input['book']) ? $this->workAt((int) $input['book'], (int) $input['para']) : null);
+        $scope = $this->scope($channel, $work, $input['category'] ?? null);
+        if ($format === 'offline' && $scope['kind'] !== 'work') {
+            throw ValidationException::withMessages(['format' => __('messages.export_offline_work_only')]);
+        }
+
+        $spec = $this->spec($channel, $scope, $format);
+        $status = $this->find($spec['id']);
+        if ($status !== null && $this->reusable($status)) {
+            return $this->present($status);
+        }
+
+        $status = $spec + ['status' => 'queued', 'progress' => 0.0, 'message' => null, 'updated_at' => now()->toIso8601ZuluString()];
+        $this->save($status);
+        $this->queue->push($spec['id'], $scope['kind'] !== 'work');
+
+        return $this->present($status);
+    }
+
+    /**
+     * 下载页用:这个范围四种文件格式各自现在的状态,不排队。范围里没有作品时返回 null。
+     *
+     * @param  array{kind: string, works: list<array<string, mixed>>, title: string, work?: int, category?: int|null}  $scope
+     * @return array<string, array<string, mixed>> 格式 => present()(可下载)或 {id, format, status: absent|stale, filename, too_large}
+     */
+    public function describe(string $channel, array $scope, ?string $userUid): array
+    {
+        $this->abilities->assertReadable($channel, $userUid);
+        $formats = array_values(array_filter(self::FORMATS, fn ($f) => $f !== 'offline'));
+        $result = [];
+        foreach ($formats as $format) {
+            $spec = $this->spec($channel, $scope, $format, false);
+            $status = $this->find($spec['id']);
+            $result[$format] = $status !== null && $this->reusable($status)
+                ? $this->present($status)
+                : [
+                    'id' => $spec['id'],
+                    'format' => $format,
+                    // 失败、失联的按「没有」给:页面上都是点一下重新生成
+                    'status' => in_array($status['status'] ?? null, ['queued', 'running'], true) ? 'stale' : 'absent',
+                    'filename' => $spec['filename'],
+                    'too_large' => $spec['too_large'],
+                ];
+        }
+
+        return $result;
+    }
+
+    /**
+     * 查一次导出的状态。不存在(或已过期)404。看不见那个 channel 403。
+     *
+     * @return array<string, mixed> present() 的结果
+     */
+    public function show(string $id, ?string $userUid): array
+    {
+        $status = $this->find($id);
+        if ($status === null) {
+            abort(404, __('messages.export_not_found'));
+        }
+        $this->abilities->assertReadable($status['channel'], $userUid);
+        if ($status['status'] === 'ready' && ! $this->fileExists($id)) {
+            // 文件被 Redis 淘汰了,状态还在:当作没生成过,让客户端重新发起
+            abort(404, __('messages.export_not_found'));
+        }
+
+        return $this->present($status);
+    }
+
+    /**
+     * 按 work / category 解析导出范围:哪些作品、叫什么名字。
+     *
+     * - 给 work:那一部作品,该 channel 没有收录它就 404
+     * - 给 category:分类(含后代)下该 channel 收录的作品
+     * - 都不给:该 channel 收录的全部作品
+     *
+     * @return array{kind: string, works: list<array<string, mixed>>, title: string, work?: int, category?: int|null}
+     */
+    public function scope(string $channel, ?int $work, ?int $category): array
+    {
+        $progress = $this->catalog->channelProgress($channel);
+        $withTitle = function (array $w) use ($progress): array {
+            $row = $progress["{$w['book']}-{$w['para']}"] ?? null;
+
+            return $w + [
+                'local_title' => ! empty($row['title']) ? $row['title'] : $w['title'],
+                'progress' => $row ? (float) $row['progress'] : 0.0,
+            ];
+        };
+        $included = fn (array $w): bool => isset($progress["{$w['book']}-{$w['para']}"]);
+
+        if ($work !== null) {
+            $found = $this->catalog->work($work);
+            if (! $found || ! $included($found)) {
+                abort(404, __('site.not_found'));
+            }
+            $item = $withTitle($found);
+
+            return ['kind' => 'work', 'work' => $work, 'works' => [$item], 'title' => $item['local_title']];
+        }
+
+        if ($category !== null) {
+            $node = $this->catalog->category($category);
+            if (! $node) {
+                abort(404, __('site.not_found'));
+            }
+            $works = array_values(array_map($withTitle, array_filter($this->catalog->worksInCategory($category), $included)));
+            $title = $this->catalog->localNames([$node], TipitakaExportBuilder::locale($this->channelLang($channel)))[$node['name']] ?? $node['name'];
+            $kind = 'category';
+        } else {
+            $works = array_values(array_map($withTitle, array_filter($this->catalog->works(), $included)));
+            $title = (string) Channel::where('uid', $channel)->value('name');
+            $kind = 'channel';
+        }
+        if ($works === []) {
+            abort(404, __('site.not_found'));
+        }
+        // 分类 id 是分类树深度优先的流水号:按它排,同一分类的作品挨在一起,律 → 经 → 论 → 藏外
+        usort($works, fn ($a, $b) => [$a['category_id'] ?? PHP_INT_MAX, $a['sn']] <=> [$b['category_id'] ?? PHP_INT_MAX, $b['sn']]);
+
+        return ['kind' => $kind, 'category' => $category, 'works' => $works, 'title' => $title];
+    }
+
+    /**
+     * 段落所在作品的 sn。不在任何作品里 404。
+     */
+    private function workAt(int $book, int $para): int
+    {
+        $work = $this->catalog->workAt($book, $para);
+        if ($work === null) {
+            abort(404, __('site.not_found'));
+        }
+
+        return $work['sn'];
+    }
+
+    /**
+     * worker 入口:生成一份导出并存进 Redis。已经生成好、或状态已过期被清掉的直接跳过。
+     */
+    public function run(string $id): void
+    {
+        $status = $this->find($id);
+        if ($status === null || ($status['status'] === 'ready' && $this->fileExists($id))) {
+            return;
+        }
+        $status = $this->save(['status' => 'running', 'progress' => 0.0, 'message' => null] + $status);
+        $started = microtime(true);
+
+        try {
+            $scope = $this->scope($status['channel'], $status['scope']['work'] ?? null, $status['scope']['category'] ?? null);
+            $file = $this->builder->build($status, $scope, function (float $progress, string $message) use (&$status): void {
+                $status = $this->save(['progress' => round($progress, 3), 'message' => $message] + $status);
+            });
+            $maxBytes = (int) config('mint.tipitaka_export.max_file_bytes');
+            if (strlen($file) > $maxBytes) {
+                throw new BusinessException(__('messages.export_too_large'), 422, 'export-too-large');
+            }
+            $ttl = (int) config('mint.tipitaka_export.ttl');
+            RedisCache::putBinary($this->fileKey($id), $file, $ttl);
+            $this->save([
+                'status' => 'ready',
+                'progress' => 1.0,
+                'message' => null,
+                'size' => strlen($file),
+                'ready_at' => now()->toIso8601ZuluString(),
+                'expires_at' => now()->addSeconds($ttl)->toIso8601ZuluString(),
+            ] + $status, $ttl);
+            Log::info('tipitaka-export: ready', ['id' => $id, 'format' => $status['format'], 'scope' => $status['scope'], 'bytes' => strlen($file), 'seconds' => round(microtime(true) - $started, 1)]);
+        } catch (Throwable $e) {
+            $this->save(['status' => 'failed', 'message' => $e instanceof BusinessException ? $e->getMessage() : __('messages.export_failed')] + $status);
+            Log::error('tipitaka-export: failed', ['id' => $id, 'exception' => $e]);
+        }
+    }
+
+    /**
+     * 文件在 Redis 里的 key。下载接口按它分块读。
+     */
+    public function fileKey(string $id): string
+    {
+        return "/tipitaka-export/file/{$id}";
+    }
+
+    /**
+     * 已生成的文件的元数据;没有(或不可下载)返回 null。
+     *
+     * @return array{filename: string, content_type: string, content_encoding: string|null, size: int}|null
+     */
+    public function file(string $id): ?array
+    {
+        $status = $this->find($id);
+        $size = RedisCache::binaryLength($this->fileKey($id));
+        if ($status === null || $status['status'] !== 'ready' || $size === null) {
+            return null;
+        }
+
+        return [
+            'filename' => $status['filename'],
+            'content_type' => $status['content_type'],
+            'content_encoding' => $status['format'] === 'offline' ? 'gzip' : null,
+            'size' => $size,
+        ];
+    }
+
+    /**
+     * 导出的不变部分:id(内容指纹)、范围、文件名。超过字数上限时 $strict 抛 422,否则标 too_large。
+     *
+     * @param  array{kind: string, works: list<array<string, mixed>>, title: string, work?: int, category?: int|null}  $scope
+     * @return array<string, mixed>
+     */
+    private function spec(string $channel, array $scope, string $format, bool $strict = true): array
+    {
+        $stats = $this->stats($channel, $scope);
+        $max = (int) config('mint.tipitaka_export.max_source_chars');
+        $tooLarge = $stats['chars'] > $max;
+        if ($tooLarge && $strict) {
+            throw new BusinessException(__('messages.export_too_large'), 422, 'export-too-large', ['chars' => $stats['chars'], 'limit' => $max]);
+        }
+        $scopeKey = match ($scope['kind']) {
+            'work' => ['kind' => 'work', 'work' => $scope['work']],
+            'category' => ['kind' => 'category', 'category' => $scope['category']],
+            default => ['kind' => 'channel'],
+        };
+        $id = sha1(json_encode([$channel, $scopeKey, $format, self::TEMPLATE_VERSION, $stats['updated_at'], $stats['count']]));
+        $channelName = (string) Channel::where('uid', $channel)->value('name');
+        [$filename, $contentType] = $this->filename($scope, $format, $channelName);
+
+        return [
+            'id' => $id,
+            'channel' => $channel,
+            'scope' => $scopeKey,
+            'format' => $format,
+            'title' => $scope['title'],
+            'works' => count($scope['works']),
+            'filename' => $filename,
+            'content_type' => $contentType,
+            'too_large' => $tooLarge,
+        ];
+    }
+
+    /**
+     * 下载时的文件名与 MIME。单部作品的 epub / docx 直接给文件,其余打 zip;离线包是 gzip 的 NDJSON。
+     *
+     * @param  array{kind: string, works: list<array<string, mixed>>, title: string}  $scope
+     * @return array{string, string}
+     */
+    private function filename(array $scope, string $format, string $channelName): array
+    {
+        $base = TipitakaExportBuilder::safeName($scope['kind'] === 'channel' ? $channelName : "{$scope['title']}-{$channelName}");
+        if ($format === 'offline') {
+            // 存的是 gzip 字节,下载时带 Content-Encoding: gzip:客户端的 HTTP 栈
+            // (OkHttp / NSURLSession / 浏览器)自己解压,App 不用另装解压库
+            return ["{$base}.ndjson", 'application/x-ndjson'];
+        }
+        if ($scope['kind'] === 'work' && $format === 'epub') {
+            return ["{$base}.epub", 'application/epub+zip'];
+        }
+        if ($scope['kind'] === 'work' && $format === 'docx') {
+            return ["{$base}.docx", 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'];
+        }
+
+        return ["{$base}-{$format}.zip", 'application/zip'];
+    }
+
+    /**
+     * 范围内的句子:条数、字数(strlen 之和)、最后修改时间。指纹与大小上限都靠它。
+     *
+     * @param  array{kind: string, works: list<array<string, mixed>>}  $scope
+     * @return array{count: int, chars: int, updated_at: string|null}
+     */
+    private function stats(string $channel, array $scope): array
+    {
+        $key = '/tipitaka-export/stats/'.sha1($channel.'|'.json_encode(array_map(fn ($w) => [$w['book'], $w['para'], $w['end']], $scope['works'])));
+
+        return RedisCache::remember($key, self::STATS_TTL, function () use ($channel, $scope) {
+            $query = Sentence::query()->where('channel_uid', $channel)->where('strlen', '>', 0);
+            if ($scope['kind'] !== 'channel') {
+                $query->where(function (Builder $q) use ($scope) {
+                    foreach ($scope['works'] as $work) {
+                        $q->orWhere(fn (Builder $w) => $w->where('book_id', $work['book'])
+                            ->whereBetween('paragraph', [$work['para'], $work['end']]));
+                    }
+                });
+            }
+            $row = $query->selectRaw('count(*) as c, coalesce(sum(strlen), 0) as s, max(updated_at) as m')->first();
+
+            return ['count' => (int) $row->c, 'chars' => (int) $row->s, 'updated_at' => $row->m ? (string) $row->m : null];
+        });
+    }
+
+    /**
+     * 已完成且文件还在的,或正在排队 / 生成且没有失联的,可以直接给请求方用。失败的允许重试。
+     *
+     * @param  array<string, mixed>  $status
+     */
+    private function reusable(array $status): bool
+    {
+        return match ($status['status']) {
+            'ready' => $this->fileExists($status['id']),
+            'queued', 'running' => now()->diffInSeconds($status['updated_at'], true) < (int) config('mint.tipitaka_export.stale_after'),
+            default => false,
+        };
+    }
+
+    /**
+     * 对外的状态:去掉内部字段,ready 时附带签名的下载链接(相对地址,反代下不拼错域名;7 天内有效)。
+     *
+     * @param  array<string, mixed>  $status
+     * @return array<string, mixed>
+     */
+    private function present(array $status): array
+    {
+        $ready = $status['status'] === 'ready';
+
+        return [
+            'id' => $status['id'],
+            'status' => $status['status'],
+            'format' => $status['format'],
+            'progress' => (float) $status['progress'],
+            'message' => $status['message'] ?? null,
+            'title' => $status['title'],
+            'works' => (int) $status['works'],
+            'filename' => $status['filename'],
+            'content_type' => $status['content_type'],
+            'size' => $ready ? (int) $status['size'] : null,
+            'ready_at' => $status['ready_at'] ?? null,
+            'expires_at' => $status['expires_at'] ?? null,
+            'download_url' => $ready ? URL::temporarySignedRoute(
+                'v3.tipitaka-exports.file',
+                Carbon::parse($status['expires_at']),
+                ['export' => $status['id']],
+                absolute: false,
+            ) : null,
+        ];
+    }
+
+    /**
+     * @return array<string, mixed>|null
+     */
+    private function find(string $id): ?array
+    {
+        return RedisCache::get($this->statusKey($id));
+    }
+
+    /**
+     * 写状态,顺带刷新 updated_at(失联判断看它)。返回写入的值。
+     *
+     * @param  array<string, mixed>  $status
+     * @return array<string, mixed>
+     */
+    private function save(array $status, ?int $ttl = null): array
+    {
+        $status['updated_at'] = now()->toIso8601ZuluString();
+        RedisCache::put($this->statusKey($status['id']), $status, $ttl ?? (int) config('mint.tipitaka_export.ttl'));
+
+        return $status;
+    }
+
+    private function fileExists(string $id): bool
+    {
+        return RedisCache::binaryLength($this->fileKey($id)) !== null;
+    }
+
+    private function statusKey(string $id): string
+    {
+        return "/tipitaka-export/status/{$id}";
+    }
+
+    private function channelLang(string $channel): string
+    {
+        return (string) (Channel::where('uid', $channel)->value('lang') ?? 'en');
+    }
+}

+ 105 - 68
api-v13/app/Services/V3/TipitakaReadingService.php

@@ -2,10 +2,8 @@
 
 namespace App\Services\V3;
 
-use App\Models\PaliText;
-use App\Models\Sentence;
 use App\Services\PaliContentService;
-use Illuminate\Database\Eloquent\Builder;
+use App\Services\ReadingIndexService;
 use Illuminate\Validation\ValidationException;
 
 /**
@@ -33,11 +31,18 @@ class TipitakaReadingService
      */
     public const MAX_PARAGRAPHS_PER_PAGE = 200;
 
-    public function __construct(private readonly PaliContentService $paliService) {}
+    public function __construct(
+        private readonly PaliContentService $paliService,
+        private readonly PaliTextService $paliTexts,
+        private readonly ReadingIndexService $index,
+    ) {}
 
     /**
      * 取一块译文。
      *
+     * 候选段、游标、进度都在「有译文的段号」索引上算({@see ReadingIndexService},命中时不查库),
+     * 正文按书一次交给 {@see PaliContentService::readParagraphs()}。
+     *
      * @param  array<string, mixed>  $filters  已经过 FormRequest 校验的查询参数
      * @return array{items: array<int, array<string, mixed>>, meta: array<string, mixed>}
      */
@@ -49,24 +54,15 @@ class TipitakaReadingService
             $unit === 'byte' ? self::MAX_BYTES_PER_PAGE : self::MAX_PARAGRAPHS_PER_PAGE
         );
 
-        $scope = $this->scopedQuery($channel, $filters);
+        $range = $this->scopeRange($filters);
+        $after = isset($filters['after']) ? $this->parseCursor((string) $filters['after']) : null;
 
-        // 多取一行用来判断后面还有没有,不必再查一次
+        // 多取一段用来判断后面还有没有
         $want = $unit === 'byte'
             ? self::MAX_PARAGRAPHS_PER_PAGE
             : min($pageSize, self::MAX_PARAGRAPHS_PER_PAGE);
 
-        $candidates = (clone $scope)
-            ->when($filters['after'] ?? null, fn (Builder $q, string $after) => $this->applyCursor($q, $after))
-            ->distinct()
-            ->select(['book_id', 'paragraph'])
-            ->orderBy('book_id')
-            ->orderBy('paragraph')
-            ->limit($want + 1)
-            ->get()
-            ->map(fn ($row) => ['book' => (int) $row->book_id, 'para' => (int) $row->paragraph])
-            ->all();
-
+        $candidates = $this->candidates($channel, $range, $after, $want + 1);
         $hasMoreBeyondWant = count($candidates) > $want;
         $candidates = array_slice($candidates, 0, $want);
 
@@ -78,9 +74,19 @@ class TipitakaReadingService
         $format = $filters['format'] ?? 'html';
         $include = $filters['include'] ?? 'display';
 
+        // 结果可以跨书:按书分组,一本书一次批量取
+        $byBook = [];
+        foreach ($slice as $coord) {
+            $byBook[$coord['book']][] = $coord['para'];
+        }
+        $rendered = [];
+        foreach ($byBook as $book => $paras) {
+            $rendered[$book] = $this->paliService->readParagraphs($book, $paras, $channel, $format);
+        }
+
         $items = [];
         foreach ($slice as $coord) {
-            $paragraph = $this->paliService->readParagraph($coord['book'], $coord['para'], $channel, $format);
+            $paragraph = $rendered[$coord['book']][$coord['para']];
             if (empty($paragraph['display'])) {
                 continue;
             }
@@ -98,36 +104,27 @@ class TipitakaReadingService
                 // 本块覆盖的最后一段。渲染为空的段落会被剔出 data 但仍算在块内,
                 // 所以游标按 slice 推进而不是按 data 推进,否则会卡在那一段上打转
                 'next_cursor' => $hasMore && $last ? "{$last['book']}-{$last['para']}" : null,
-            ] + $this->progressMeta($scope, $filters, $last),
+            ] + $this->progressMeta($channel, $range, $last),
         ];
     }
 
     /**
-     * 按 filter 收窄的**基础查询**:只有 where,不带 select / distinct / order。
-     *
-     * 分页取数和 count 两边对它的要求不一样(一个要去重的两列,一个要聚合),
-     * 混在一起会拼出 `select distinct book_id, paragraph, count(...)` 这种非法 SQL。
-     * 所以基础查询保持干净,各自 clone 之后再加自己那套。
+     * 按 filter 收窄的范围:不带 book 是整个 channel(null),带 book 是这本书里的段落闭区间。
      *
      * @param  array<string, mixed>  $filters
-     * @return Builder<Sentence>
+     * @return array{book: int, from: int, to: int}|null
      */
-    private function scopedQuery(string $channel, array $filters): Builder
+    private function scopeRange(array $filters): ?array
     {
-        $query = Sentence::query()
-            ->where('channel_uid', $channel)
-            ->where('strlen', '>', 0);
-
         if (! isset($filters['book'])) {
-            return $query;
+            return null;
         }
         $book = (int) $filters['book'];
-        $query->where('book_id', $book);
 
         if (isset($filters['chapter'])) {
             [$from, $to] = $this->chapterRange($book, (int) $filters['chapter']);
 
-            return $query->whereBetween('paragraph', [$from, $to]);
+            return ['book' => $book, 'from' => $from, 'to' => $to];
         }
         if (isset($filters['para'])) {
             $from = (int) $filters['para'];
@@ -136,10 +133,55 @@ class TipitakaReadingService
                 throw ValidationException::withMessages(['to' => __('site.invalid_parameter')]);
             }
 
-            return $query->whereBetween('paragraph', [$from, $to]);
+            return ['book' => $book, 'from' => $from, 'to' => $to];
+        }
+
+        return ['book' => $book, 'from' => PHP_INT_MIN, 'to' => PHP_INT_MAX];
+    }
+
+    /**
+     * 范围内有译文的段(句子 strlen > 0),按 (book, para) 升序,排在游标之后,最多 $limit 段。
+     *
+     * @param  array{book: int, from: int, to: int}|null  $range
+     * @param  array{int, int}|null  $after
+     * @return list<array{book: int, para: int}>
+     */
+    private function candidates(string $channel, ?array $range, ?array $after, int $limit): array
+    {
+        $books = $range === null ? $this->index->books($channel) : [$range['book']];
+        $result = [];
+        foreach ($books as $book) {
+            if ($after !== null && $book < $after[0]) {
+                continue;
+            }
+            foreach ($this->paragraphsIn($channel, $book, $range) as $para) {
+                if ($after !== null && $book === $after[0] && $para <= $after[1]) {
+                    continue;
+                }
+                $result[] = ['book' => $book, 'para' => $para];
+                if (count($result) >= $limit) {
+                    return $result;
+                }
+            }
+        }
+
+        return $result;
+    }
+
+    /**
+     * 这本书里有译文、且在范围内的段号,升序。
+     *
+     * @param  array{book: int, from: int, to: int}|null  $range
+     * @return list<int>
+     */
+    private function paragraphsIn(string $channel, int $book, ?array $range): array
+    {
+        $paras = $this->index->paragraphs($channel, $book);
+        if ($range === null) {
+            return $paras;
         }
 
-        return $query;
+        return array_values(array_filter($paras, fn (int $para) => $para >= $range['from'] && $para <= $range['to']));
     }
 
     /**
@@ -151,28 +193,24 @@ class TipitakaReadingService
      */
     public function chapterRange(int $book, int $chapter): array
     {
-        $head = PaliText::where('book', $book)->where('paragraph', $chapter)->first();
-        if (! $head) {
+        $range = $this->paliTexts->chapterRange($book, $chapter);
+        if ($range === null) {
             abort(404, __('site.not_found'));
         }
 
-        return [$chapter, $chapter + max(1, (int) $head->chapter_len) - 1];
+        return $range;
     }
 
     /**
-     * 游标 `{book}-{para}`:取排在它之后的行。
-     *
-     * 用行值比较 `(book_id, paragraph) > (?, ?)` 而不是 `book > ? or (book = ? and para > ?)`,
-     * 一是短,二是 Postgres 能直接走 (book_id, paragraph, …) 那条复合索引。
+     * 游标 `{book}-{para}` → [book, para]。
      *
-     * @param  Builder<Sentence>  $query
-     * @return Builder<Sentence>
+     * @return array{int, int}
      */
-    private function applyCursor(Builder $query, string $after): Builder
+    private function parseCursor(string $after): array
     {
-        [$book, $para] = array_map('intval', explode('-', $after, 2));
+        [$book, $para] = array_map('intval', explode('-', $after, 2)) + [0, 0];
 
-        return $query->whereRaw('(book_id, paragraph) > (?, ?)', [$book, $para]);
+        return [$book, $para];
     }
 
     /**
@@ -201,8 +239,7 @@ class TipitakaReadingService
     }
 
     /**
-     * 取这些段落的原文字节数。按书分组、每本用首尾段落号一次查回整段区间,
-     * 避免几百个值的 IN 列表;区间里多查回来几行比拼 IN 便宜。
+     * 取这些段落的原文字节数({@see PaliTextService},缓存的经文静态数据)。
      *
      * @param  array<int, array{book: int, para: int}>  $candidates
      * @return array<int, array<int, int>> book => (para => 字节数)
@@ -216,10 +253,10 @@ class TipitakaReadingService
 
         $lengths = [];
         foreach ($byBook as $book => $paras) {
-            $lengths[$book] = PaliText::where('book', $book)
-                ->whereBetween('paragraph', [min($paras), max($paras)])
-                ->pluck('lenght', 'paragraph')
-                ->all();
+            $lengths[$book] = array_map(
+                fn (array $row) => $row['length'],
+                $this->paliTexts->paragraphs($book, min($paras), max($paras))
+            );
         }
 
         return $lengths;
@@ -228,30 +265,30 @@ class TipitakaReadingService
     /**
      * 进度用的 total / remaining,**只在带了 book 过滤时给**。
      *
-     * 不带过滤时结果集是整个 channel(实测最大的 52 万段),每页 count 一次要
-     * 八百毫秒、两百多 MB,不值得。那种场景用 next_cursor 判断结束。
+     * 不带过滤时结果集是整个 channel(实测最大的 52 万段),要把每本书的段号索引都读一遍,
+     * 不值得。那种场景用 next_cursor 判断结束。
      *
-     * @param  Builder<Sentence>  $scope
-     * @param  array<string, mixed>  $filters
+     * @param  array{book: int, from: int, to: int}|null  $range
      * @param  array{book: int, para: int}|null  $last
      * @return array<string, int>
      */
-    private function progressMeta(Builder $scope, array $filters, ?array $last): array
+    private function progressMeta(string $channel, ?array $range, ?array $last): array
     {
-        if (! isset($filters['book'])) {
+        if ($range === null) {
             return [];
         }
 
-        $countIn = fn (Builder $q): int => (int) (
-            $q->selectRaw('count(distinct (book_id, paragraph)) as aggregate')->first()?->aggregate ?? 0
-        );
-
-        $total = $countIn(clone $scope);
-        $remaining = $last === null
-            ? 0
-            : $countIn($this->applyCursor(clone $scope, "{$last['book']}-{$last['para']}"));
+        $paras = $this->paragraphsIn($channel, $range['book'], $range);
+        $remaining = 0;
+        if ($last !== null) {
+            foreach ($paras as $para) {
+                if ($para > $last['para']) {
+                    $remaining++;
+                }
+            }
+        }
 
-        return ['total' => $total, 'remaining' => $remaining];
+        return ['total' => count($paras), 'remaining' => $remaining];
     }
 
     /**

+ 1 - 1
api-v13/app/Services/V3/TipitakaTitleService.php

@@ -44,7 +44,7 @@ class TipitakaTitleService
     private const STATUS_PUBLIC = 30;
 
     /** 书的 tag → layer。一本书有多个时按这个顺序取第一个 */
-    private const LAYER_TAGS = ['mūla' => 'mula', 'aṭṭhakathā' => 'atthakatha', 'ṭīkā' => 'tika', 'añña' => 'anna'];
+    private const LAYER_TAGS = ['mūla' => 'mula', 'aṭṭhakathā' => 'atthakatha', 'ṭīkā' => 'tika', 'vinaya-añña' => 'tika', 'añña' => 'anna'];
 
     /** 没有任何 layer tag 的书 */
     private const DEFAULT_LAYER = 'anna';

+ 5 - 0
api-v13/bootstrap/app.php

@@ -40,6 +40,11 @@ return Application::configure(basePath: dirname(__DIR__))
             SetLocale::class,
         ]);
 
+        // 界面语言 cookie 不加密:前端 JS 要直接读 document.cookie
+        $middleware->encryptCookies(except: [
+            'language',
+        ]);
+
         $middleware->alias([
             'ops.token' => OpsToken::class,
             // v3 的登录闸。只认 bearer,未登录在进控制器前就 401——

+ 24 - 0
api-v13/config/mint.php

@@ -122,6 +122,11 @@ return [
     'cache' => [
         // 这个值prod,staging无需设置
         'expire' => env('CACHE_EXPIRE', 36000),
+        // 阅读段落成品与章节缓存(PaliContentService::readParagraphs / readChapters):句子、批注改动有精确失效,
+        // 术语释义、引用句子、channel 名称等没有,改了最多旧这么久
+        'read_paragraph_ttl' => env('CACHE_READ_PARAGRAPH_TTL', 7 * 86400),
+        // 有译文的书号 / 段号索引(ReadingIndexService):随句子改动失效,过期只为回收空间
+        'read_index_ttl' => env('CACHE_READ_INDEX_TTL', 7 * 86400),
     ],
 
     /**
@@ -199,8 +204,27 @@ return [
             'suggestion' => [],
             'wbw-analyses' => [],
             'ai_translate_v2' => [],
+            // 三藏下载(/v3/tipitaka-exports):单部作品 / 打包分开,worker:mq:export.tipitaka [--bulk]
+            'export_tipitaka' => [],
+            'export_tipitaka_bulk' => [],
         ],
     ],
+    /*
+     * 三藏下载(/v3/tipitaka-exports)。生成好的文件以二进制存在 Redis 集群里(RedisCache::putBinary)。
+     * 上限参照全三藏巴利 html(clove/pali_html:148MB,zip 后 33MB),正常数据到不了。
+     */
+    'tipitaka_export' => [
+        // 生成前按范围内句子的 strlen 之和估算,超过就 422,不排队
+        'max_source_chars' => (int) env('TIPITAKA_EXPORT_MAX_SOURCE_CHARS', 160 * 1024 * 1024),
+        // 生成后的文件超过就判失败、不写 Redis(单个值太大会撑爆从库同步缓冲,见 RedisCache 类注释)
+        'max_file_bytes' => (int) env('TIPITAKA_EXPORT_MAX_FILE_BYTES', 64 * 1024 * 1024),
+        // 文件与状态在 Redis 里保留多久
+        'ttl' => 7 * 24 * 3600,
+        // 排队 / 生成中的状态多久没更新就当作 worker 丢了,下次请求重新排队
+        'stale_after' => 1800,
+        'pandoc' => env('PANDOC_PATH', 'pandoc'),
+        'pandoc_timeout' => 1200,
+    ],
     'opensearch' => [
         'index' => 'wikipali_global_20261119',
         // 索引 settings + mappings 定义文件所在目录,文件名为「{index}.json」

+ 403 - 0
api-v13/documents/download-demo.html

@@ -0,0 +1,403 @@
+<!doctype html>
+<html lang="zh-Hans">
+<head>
+<meta charset="utf-8">
+<meta name="viewport" content="width=device-width, initial-scale=1">
+<title>三藏下载设计</title>
+<style>
+:root{
+  --bg:#f6f8fb; --surface:#fff; --surface-2:#f1f4f8; --border:#e3e8ef; --text:#1d2733; --muted:#66758a;
+  --primary:#066fd1; --primary-lt:#e7f1fc; --ok:#2fb344; --ok-lt:#e9f7ec; --warn:#f59f00; --warn-lt:#fff4e0; --danger:#d63939;
+  --epub:#7b4bd1; --html:#e8590c; --docx:#1f5fbf; --md:#2b8a3e;
+  --radius:10px; --shadow:0 1px 2px rgba(16,24,40,.06),0 1px 3px rgba(16,24,40,.08);
+  --serif:"Noto Serif SC","Source Han Serif SC","Songti SC",serif;
+}
+@media (prefers-color-scheme: dark){:root:not([data-theme="light"]){
+  --bg:#11161d; --surface:#18202a; --surface-2:#1f2935; --border:#2b3644; --text:#e4e9f0; --muted:#93a1b3;
+  --primary:#4c9bf0; --primary-lt:#1b3150; --ok:#4cc35e; --ok-lt:#1b3323; --warn:#f7b23b; --warn-lt:#3a2e15;
+  --shadow:none;
+}}
+:root[data-theme="dark"]{
+  --bg:#11161d; --surface:#18202a; --surface-2:#1f2935; --border:#2b3644; --text:#e4e9f0; --muted:#93a1b3;
+  --primary:#4c9bf0; --primary-lt:#1b3150; --ok:#4cc35e; --ok-lt:#1b3323; --warn:#f7b23b; --warn-lt:#3a2e15; --shadow:none;
+}
+*{box-sizing:border-box}
+body{margin:0;background:var(--bg);color:var(--text);font:14px/1.6 -apple-system,BlinkMacSystemFont,"Segoe UI","PingFang SC","Microsoft YaHei",sans-serif}
+a{color:var(--primary);text-decoration:none}
+button{font:inherit;color:inherit}
+.demo-nav{position:sticky;top:0;z-index:20;background:#1d2733;color:#fff;display:flex;gap:4px;padding:8px 16px;overflow-x:auto;align-items:center}
+.demo-nav b{margin-right:12px;white-space:nowrap;font-weight:600;opacity:.8}
+.demo-nav button{background:transparent;border:0;color:#c8d2de;padding:6px 12px;border-radius:6px;cursor:pointer;white-space:nowrap}
+.demo-nav button.on{background:#fff;color:#1d2733}
+.screen{display:none}.screen.on{display:block}
+.wrap{max-width:1080px;margin:0 auto;padding:20px 16px 60px}
+.crumb{color:var(--muted);font-size:13px;margin-bottom:14px}.crumb a{color:var(--muted)}.crumb span{margin:0 6px}
+.card{background:var(--surface);border:1px solid var(--border);border-radius:var(--radius);box-shadow:var(--shadow)}
+.head{display:flex;gap:20px;padding:20px;align-items:center}
+.cover{width:92px;height:124px;border-radius:6px;flex:none;background:linear-gradient(150deg,#8a5a2b,#4a2c14);color:#f6e7cf;display:flex;align-items:flex-end;padding:10px;font:600 13px/1.3 var(--serif);box-shadow:inset -4px 0 0 rgba(0,0,0,.15)}
+.head h1{margin:0;font:600 22px/1.3 var(--serif)}
+.head .pali{color:var(--muted);font-style:italic}
+.meta{display:flex;flex-wrap:wrap;gap:6px 16px;margin-top:8px;color:var(--muted);font-size:13px}
+.badge{display:inline-block;font-size:12px;padding:1px 8px;border-radius:20px;background:var(--surface-2);color:var(--muted)}
+h2.sec{font-size:15px;margin:26px 0 10px;display:flex;align-items:center;gap:8px}
+h2.sec small{font-weight:400;color:var(--muted)}
+.formats{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:12px}
+@media(max-width:720px){.formats{grid-template-columns:1fr}.head{flex-direction:column;align-items:flex-start}}
+.fmt{padding:16px;display:flex;flex-direction:column;gap:10px;transition:border-color .15s}
+.fmt:hover{border-color:var(--primary)}
+.fmt-top{display:flex;gap:12px;align-items:flex-start}
+.ficon{width:42px;height:50px;border-radius:5px 12px 5px 5px;color:#fff;font:700 10px/1 monospace;display:flex;align-items:flex-end;justify-content:center;padding-bottom:7px;flex:none;letter-spacing:.5px}
+.fmt h3{margin:0;font-size:15px}.fmt p{margin:2px 0 0;color:var(--muted);font-size:13px}
+.zipline{font:12px/1.5 ui-monospace,Menlo,monospace;color:var(--muted);background:var(--surface-2);border-radius:6px;padding:6px 10px;overflow-x:auto;white-space:pre}
+.fmt-foot{display:flex;align-items:center;gap:10px;justify-content:space-between;flex-wrap:wrap}
+.state{font-size:12.5px;display:flex;align-items:center;gap:6px;color:var(--muted)}
+.dot{width:8px;height:8px;border-radius:50%;background:var(--muted)}
+.state.ready .dot{background:var(--ok)}.state.ready{color:var(--ok)}
+.state.cold .dot{background:var(--warn)}
+.state.fail{color:var(--danger)}.state.fail .dot{background:var(--danger)}
+.btn{display:inline-flex;align-items:center;gap:6px;border:1px solid var(--border);background:var(--surface);padding:6px 14px;border-radius:6px;cursor:pointer;font-size:13.5px;white-space:nowrap}
+.btn:hover{border-color:var(--primary);color:var(--primary)}
+.btn.primary{background:var(--primary);border-color:var(--primary);color:#fff}
+.btn.primary:hover{filter:brightness(1.08);color:#fff}
+.btn[disabled]{opacity:.55;cursor:default}
+.prog{display:none;flex-direction:column;gap:6px}
+.fmt.busy .prog{display:flex}.fmt.busy .fmt-foot .btn{display:none}
+.bar{height:6px;background:var(--surface-2);border-radius:4px;overflow:hidden}.bar i{display:block;height:100%;width:0;background:var(--primary);transition:width .4s}
+.prog-txt{display:flex;justify-content:space-between;font-size:12.5px;color:var(--muted)}
+.hint{margin-top:14px;padding:10px 14px;border-radius:8px;background:var(--primary-lt);font-size:13px;color:var(--text);display:flex;gap:8px}
+.toast{position:fixed;right:16px;bottom:16px;z-index:50;background:#1d2733;color:#fff;padding:12px 16px;border-radius:8px;box-shadow:0 6px 20px rgba(0,0,0,.25);max-width:340px;font-size:13.5px;transform:translateY(120%);transition:transform .25s}
+.toast.on{transform:none}.toast a{color:#8cc4ff}
+.pills{display:flex;flex-wrap:wrap;gap:6px}
+.pill{border:1px solid var(--border);background:var(--surface);border-radius:20px;padding:3px 12px;font-size:13px;cursor:pointer}
+.pill b{font-weight:400;color:var(--muted);margin-left:4px}
+.pill.on{background:var(--primary);border-color:var(--primary);color:#fff}.pill.on b{color:#dbe9fb}
+.sum{display:grid;grid-template-columns:repeat(4,1fr);gap:1px;background:var(--border);border-radius:var(--radius);overflow:hidden;border:1px solid var(--border);margin-top:14px}
+.sum div{background:var(--surface);padding:12px 16px}.sum b{display:block;font-size:20px;font-weight:600}.sum span{color:var(--muted);font-size:12px}
+@media(max-width:720px){.sum{grid-template-columns:repeat(2,1fr)}}
+.incl{padding:6px 0}
+.incl details{border-top:1px solid var(--border)}.incl details:first-child{border-top:0}
+.incl summary{padding:10px 16px;cursor:pointer;display:flex;gap:10px;align-items:center;list-style:none}
+.incl summary::-webkit-details-marker{display:none}
+.incl summary:before{content:"▸";color:var(--muted);width:10px}.incl details[open] summary:before{content:"▾"}
+.incl summary .n{margin-left:auto;color:var(--muted);font-size:12.5px}
+.incl ul{margin:0;padding:0 16px 12px 36px;columns:2;column-gap:24px}
+.incl li{font-size:13px;list-style:none;padding:2px 0;break-inside:avoid;display:flex;justify-content:space-between;gap:8px}
+.incl li span{color:var(--muted);font-size:12px}
+@media(max-width:720px){.incl ul{columns:1}}
+
+/* ===== 导出包 index.html ===== */
+.x-index{background:#faf7f1;color:#2a2219;min-height:100vh}
+:root[data-theme="dark"] .x-index{background:#16130f;color:#e8dfd2}
+@media (prefers-color-scheme: dark){:root:not([data-theme="light"]) .x-index{background:#16130f;color:#e8dfd2}}
+.x-hero{padding:48px 16px 32px;text-align:center;border-bottom:1px solid rgba(120,90,50,.18)}
+.x-hero .kicker{letter-spacing:.3em;font-size:12px;color:#9a7b52;text-transform:uppercase}
+.x-hero h1{font:600 34px/1.25 var(--serif);margin:10px 0 6px}
+.x-hero p{margin:0;color:#8a7760}
+.x-stats{display:flex;justify-content:center;gap:28px;margin-top:18px;flex-wrap:wrap;font-size:13px;color:#8a7760}
+.x-stats b{display:block;font:600 22px var(--serif);color:inherit}
+.x-tools{max-width:960px;margin:0 auto;padding:20px 16px 4px;display:flex;gap:10px;flex-wrap:wrap;align-items:center}
+.x-search{flex:1;min-width:220px;position:relative}
+.x-search input{width:100%;padding:10px 14px 10px 36px;border-radius:24px;border:1px solid rgba(120,90,50,.28);background:rgba(255,255,255,.7);font:inherit;color:inherit}
+:root[data-theme="dark"] .x-search input{background:rgba(255,255,255,.05)}
+.x-search:before{content:"⌕";position:absolute;left:14px;top:7px;font-size:18px;color:#9a7b52}
+.x-seg{display:flex;gap:4px}
+.x-seg button{border:1px solid rgba(120,90,50,.28);background:transparent;border-radius:20px;padding:6px 12px;cursor:pointer;font-size:13px}
+.x-seg button.on{background:#6b4a26;border-color:#6b4a26;color:#fff8ec}
+.x-body{max-width:960px;margin:0 auto;padding:8px 16px 60px}
+.x-pitaka{margin-top:26px}
+.x-pitaka>h2{font:600 20px var(--serif);display:flex;align-items:baseline;gap:10px;margin:0 0 4px;border-bottom:2px solid #c9a66b;padding-bottom:6px}
+.x-pitaka>h2 small{font:italic 400 13px var(--serif);color:#9a7b52}
+.x-cat{margin:16px 0 6px;font-size:13px;color:#9a7b52;letter-spacing:.05em}
+.x-works{display:grid;grid-template-columns:repeat(auto-fill,minmax(270px,1fr));gap:10px}
+.x-work{display:block;padding:12px 14px;border-radius:8px;background:rgba(255,255,255,.75);border:1px solid rgba(120,90,50,.16);color:inherit;transition:transform .12s,box-shadow .12s}
+:root[data-theme="dark"] .x-work{background:rgba(255,255,255,.04)}
+.x-work:hover{transform:translateY(-1px);box-shadow:0 4px 14px rgba(90,60,20,.12)}
+.x-work .t{font:600 15px/1.35 var(--serif)}
+.x-work .p{font:italic 12.5px var(--serif);color:#9a7b52}
+.x-work .m{display:flex;align-items:center;gap:8px;margin-top:8px;font-size:12px;color:#8a7760}
+.x-work .m .pb{flex:1;height:4px;border-radius:2px;background:rgba(120,90,50,.15);overflow:hidden}.x-work .m .pb i{display:block;height:100%;background:#c9a66b}
+.x-empty{text-align:center;color:#8a7760;padding:40px 0;display:none}
+.x-foot{text-align:center;font-size:12px;color:#9a8a74;padding:20px}
+
+/* ===== 导出包 作品 html ===== */
+.x-read{background:#fdfbf7;color:#2a2219;min-height:100vh}
+:root[data-theme="dark"] .x-read{background:#15120f;color:#e6ddcf}
+@media (prefers-color-scheme: dark){:root:not([data-theme="light"]) .x-read{background:#15120f;color:#e6ddcf}}
+.x-read-top{position:sticky;top:44px;z-index:5;display:flex;gap:12px;align-items:center;padding:10px 16px;border-bottom:1px solid rgba(120,90,50,.18);background:inherit;font-size:13px}
+.x-read-top .sp{flex:1;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;font-family:var(--serif)}
+.x-read-top button{border:1px solid rgba(120,90,50,.28);background:transparent;border-radius:6px;padding:3px 10px;cursor:pointer}
+.x-read-grid{display:grid;grid-template-columns:240px minmax(0,1fr);gap:40px;max-width:1040px;margin:0 auto;padding:24px 16px 80px}
+@media(max-width:820px){.x-read-grid{grid-template-columns:1fr}.x-toc{display:none}.x-toc.on{display:block}}
+.x-toc{position:sticky;top:100px;align-self:start;font-size:13px;max-height:calc(100vh - 120px);overflow:auto}
+.x-toc h4{margin:0 0 8px;font-size:12px;letter-spacing:.15em;color:#9a7b52}
+.x-toc a{display:block;color:inherit;padding:4px 10px;border-left:2px solid rgba(120,90,50,.18);opacity:.8}
+.x-toc a.l2{padding-left:22px;font-size:12.5px}
+.x-toc a:hover,.x-toc a.on{opacity:1;border-color:#c9a66b;color:#8a5a2b}
+.x-article{font:17px/1.95 var(--serif);max-width:42em}
+.x-article .titlepage{text-align:center;padding:20px 0 40px;border-bottom:1px solid rgba(120,90,50,.18);margin-bottom:30px}
+.x-article .titlepage h1{font-size:30px;margin:0}
+.x-article .titlepage div{font-size:14px;color:#9a7b52}
+.x-article h2{font-size:23px;margin:2.2em 0 .6em;scroll-margin-top:110px}
+.x-article h3{font-size:19px;margin:1.6em 0 .5em;scroll-margin-top:110px}
+.x-article p{margin:0 0 1em;text-align:justify}
+.x-article .pn{font:11px ui-monospace,monospace;color:#b39a76;margin-right:6px;user-select:none;vertical-align:2px}
+.x-article sup a{font-size:11px}
+.x-article .fn{font-size:13.5px;line-height:1.7;border-top:1px dashed rgba(120,90,50,.3);padding-top:6px;margin:-.4em 0 1.2em;color:#7a6650}
+@media print{.demo-nav,.x-read-top,.x-toc{display:none}.x-read-grid{display:block}}
+
+.doc{font-size:14px}.doc h3{margin:22px 0 8px;font-size:15px}.doc table{border-collapse:collapse;width:100%;font-size:13px}.doc td,.doc th{border:1px solid var(--border);padding:6px 10px;text-align:left;vertical-align:top}.doc th{background:var(--surface-2)}
+.doc code{font-size:12.5px;background:var(--surface-2);padding:1px 5px;border-radius:4px}
+.flow{display:flex;flex-wrap:wrap;gap:8px;align-items:center;margin:10px 0}
+.flow span{padding:6px 10px;border-radius:6px;background:var(--surface-2);font-size:13px}.flow i{color:var(--muted);font-style:normal}
+</style>
+</head>
+<body>
+
+<nav class="demo-nav">
+  <b>下载功能 demo</b>
+  <button data-go="work" class="on">① 作品下载页</button>
+  <button data-go="all">② 分类 · 下载全部</button>
+  <button data-go="xindex">③ 导出包 index.html</button>
+  <button data-go="xread">④ 导出包 作品.html</button>
+  <button data-go="flow">⑤ 流程与接口</button>
+  <span style="flex:1"></span>
+  <button id="theme" title="切换深浅色">◐</button>
+</nav>
+
+<!-- ============ ① 作品下载页 ============ -->
+<section class="screen on" id="s-work">
+<div class="wrap">
+  <div class="crumb"><a>首页</a><span>›</span><a>三藏</a><span>›</span><a>译本</a><span>›</span><a>元亨寺·CBETA</a><span>›</span><a>律藏</a><span>›</span>下载</div>
+  <div class="card head">
+    <div class="cover">Vinaya­piṭaka</div>
+    <div style="flex:1;min-width:0">
+      <h1>律藏</h1>
+      <div class="pali">Vinayapiṭaka</div>
+      <div class="meta">
+        <span>译本 <a>元亨寺·CBETA</a> <span class="badge">translation</span></span>
+        <span>语言 zh</span><span>完成度 86%</span><span>12 章 · 约 184,000 字</span><span>最近更新 2026-11-20</span>
+      </div>
+    </div>
+    <a class="btn" href="#">‹ 返回作品页</a>
+  </div>
+
+  <h2 class="sec">选择格式 <small>都打包成 .zip,生成后保留 7 天,期间任何人下载都直接给文件</small></h2>
+  <div class="formats" data-formats></div>
+
+  <div class="hint">ⓘ <span>首次生成需要几秒到一两分钟。可以离开本页:7 天内回来,或在其他设备、手机 App 里下载同一译本同一格式,都直接拿到文件。译文有更新时会自动重新生成。</span></div>
+</div>
+</section>
+
+<!-- ============ ② 分类 · 下载全部 ============ -->
+<section class="screen" id="s-all">
+<div class="wrap">
+  <div class="crumb"><a>首页</a><span>›</span><a>三藏</a><span>›</span><a>译本</a><span>›</span><a>元亨寺·CBETA</a><span>›</span><a>分类</a><span>›</span>下载</div>
+  <div class="card head" style="align-items:flex-start">
+    <div style="flex:1;min-width:0">
+      <h1>下载元亨寺·CBETA</h1>
+      <div class="meta" style="margin-bottom:12px"><span>按分类打包本译本收录的全部作品。只含已有译文的作品,未收录的不打包。</span></div>
+      <div class="pills" data-scope>
+        <button class="pill on" data-k="all">全部<b>32</b></button>
+        <button class="pill" data-k="vinaya">律藏<b>5</b></button>
+        <button class="pill" data-k="sutta">经藏<b>19</b></button>
+        <button class="pill" data-k="abhi">论藏<b>7</b></button>
+        <button class="pill" data-k="anna">藏外<b>1</b></button>
+      </div>
+      <div class="sum" data-sum></div>
+    </div>
+  </div>
+
+  <h2 class="sec">选择格式 <small data-scope-label>范围:全部</small></h2>
+  <div class="formats" data-formats></div>
+
+  <h2 class="sec">包含的作品 <small>与上方范围同步</small></h2>
+  <div class="card incl" data-incl></div>
+</div>
+</section>
+
+<!-- ============ ③ 导出包 index.html ============ -->
+<section class="screen" id="s-xindex">
+<div class="x-index">
+  <header class="x-hero">
+    <div class="kicker">WikiPāli · Tipiṭaka</div>
+    <h1>元亨寺·CBETA</h1>
+    <p>巴利三藏汉译 · 导出于 2026-11-21 · 本地离线阅读</p>
+    <div class="x-stats"><div><b>32</b>部作品</div><div><b>263</b>章</div><div><b>2.1M</b>字</div><div><b>86%</b>平均完成度</div></div>
+  </header>
+  <div class="x-tools">
+    <div class="x-search"><input data-xq placeholder="搜作品名、巴利名,如 长部 / dīgha / 法句"></div>
+    <div class="x-seg" data-xseg>
+      <button class="on" data-k="">全部</button><button data-k="律藏">律</button><button data-k="经藏">经</button><button data-k="论藏">论</button>
+    </div>
+  </div>
+  <div class="x-body" data-xbody></div>
+  <div class="x-empty" data-xempty>没有匹配的作品</div>
+  <div class="x-foot">本文件离线可用,无需联网 · 来源 wikipali.org/library/tipitaka/channels/a19eaf75…</div>
+</div>
+</section>
+
+<!-- ============ ④ 导出包 作品.html ============ -->
+<section class="screen" id="s-xread">
+<div class="x-read">
+  <div class="x-read-top">
+    <a data-go="xindex" style="cursor:pointer">‹ 目录</a>
+    <span class="sp">律藏 · 元亨寺·CBETA</span>
+    <button data-toc-toggle>章节</button>
+    <button data-font>A±</button>
+  </div>
+  <div class="x-read-grid">
+    <nav class="x-toc" data-toc>
+      <h4>章节</h4>
+      <a href="#c1" class="on">一、波罗夷</a><a href="#c1-1" class="l2">第一 淫戒</a><a href="#c1-2" class="l2">第二 盗戒</a>
+      <a href="#c2">二、僧残</a><a href="#c2-1" class="l2">第一 故出精</a>
+      <a href="#c3">三、不定</a>
+    </nav>
+    <article class="x-article">
+      <div class="titlepage"><h1>律藏</h1><div>Vinayapiṭaka · 经分别 · 元亨寺·CBETA</div></div>
+      <h2 id="c1">一、波罗夷</h2>
+      <h3 id="c1-1">第一 淫戒</h3>
+      <p><span class="pn">1</span>(示例正文)尔时,佛世尊住毗兰若那邻罗树下,与五百大比丘众俱。<sup><a href="#fn1">1</a></sup>毗兰若婆罗门闻:「沙门瞿昙释子,从释迦族出家……」</p>
+      <div class="fn" id="fn1">1. 示例脚注:读取段落时 PaliContentService 渲染的段后注释列表,原样保留在导出文件中。</div>
+      <p><span class="pn">2</span>(示例正文)时,毗兰若婆罗门往诣世尊处,与世尊互相问讯,交谈庆慰之语后,坐于一面。坐于一面之毗兰若婆罗门白世尊言……</p>
+      <h3 id="c1-2">第二 盗戒</h3>
+      <p><span class="pn">84</span>(示例正文)尔时,佛世尊住王舍城耆阇崛山。其时,众多相识之比丘于仙人山侧,结草庵而入雨安居……</p>
+      <h2 id="c2">二、僧残</h2>
+      <h3 id="c2-1">第一 故出精</h3>
+      <p><span class="pn">234</span>(示例正文)尔时,佛世尊住舍卫城祇树给孤独园。其时,具寿施越……</p>
+      <h2 id="c3">三、不定</h2>
+      <p><span class="pn">443</span>(示例正文)尔时,佛世尊住舍卫城祇树给孤独园……</p>
+    </article>
+  </div>
+</div>
+</section>
+
+<!-- ============ ⑤ 流程与接口 ============ -->
+<section class="screen" id="s-flow">
+<div class="wrap doc">
+  <div class="card" style="padding:20px">
+    <h3 style="margin-top:0">一次下载的流程</h3>
+    <div class="flow"><span>点击下载</span><i>→</i><span>POST /v3/tipitaka-exports</span><i>→</i><span>Redis 里有同指纹的包?</span></div>
+    <div class="flow"><i>有 →</i><span>200 ready + 下载链接</span><i>→</i><span>直接下载</span></div>
+    <div class="flow"><i>没有 →</i><span>202 queued,发 RabbitMQ</span><i>→</i><span>worker 生成 → 打包 → 写 Redis</span><i>→</i><span>前端轮询到 ready</span><i>→</i><span>自动下载 / 手动按钮兜底</span></div>
+    <h3>接口</h3>
+    <table>
+      <tr><th>请求</th><th>作用</th></tr>
+      <tr><td><code>POST /v3/tipitaka-exports</code><br><code>{channel, work?: sn, category?: id, format}</code></td><td>没有 work 和 category = 整个译本。命中缓存 200,否则 202 + <code>Retry-After</code>。同一份包同时只排一次队</td></tr>
+      <tr><td><code>GET /v3/tipitaka-exports/{id}</code></td><td>轮询状态:<code>queued / running / ready / failed</code>、<code>progress</code>、<code>size</code>、<code>expires_at</code>、<code>download_url</code></td></tr>
+      <tr><td><code>GET /v3/tipitaka-exports/{id}/file?signature=…</code></td><td>带签名的链接,浏览器与 App 都能直接下载;<code>Content-Disposition: attachment</code></td></tr>
+    </table>
+    <h3>zip 里的内容</h3>
+    <table>
+      <tr><th>格式</th><th>单部作品</th><th>整个译本 / 一个分类</th></tr>
+      <tr><td>EPUB</td><td><code>律藏.epub</code></td><td>每部作品一个 epub,按藏 / 分类放进文件夹</td></tr>
+      <tr><td>HTML</td><td><code>律藏.html</code>(CSS 内联的单个文件)</td><td><code>index.html</code>(③)+ <code>works/*.html</code>(④)</td></tr>
+      <tr><td>Word</td><td><code>律藏.docx</code></td><td>每部作品一个 docx,按文件夹分组</td></tr>
+      <tr><td>Markdown</td><td><code>README.md</code> + 每章一个 <code>01-波罗夷.md</code></td><td>根目录 <code>README.md</code> 总目录 + 每部作品一个文件夹</td></tr>
+    </table>
+  </div>
+</div>
+</section>
+
+<div class="toast" data-toast></div>
+
+<script>
+(function(){
+const $=(s,r=document)=>r.querySelector(s), $$=(s,r=document)=>[...r.querySelectorAll(s)];
+// 导航
+const go=k=>{$$('.screen').forEach(s=>s.classList.toggle('on',s.id==='s-'+k));$$('.demo-nav [data-go]').forEach(b=>b.classList.toggle('on',b.dataset.go===k));scrollTo(0,0)};
+$$('[data-go]').forEach(b=>b.addEventListener('click',()=>go(b.dataset.go)));
+$('#theme').onclick=()=>{const r=document.documentElement;const dark=r.dataset.theme?r.dataset.theme==='dark':matchMedia('(prefers-color-scheme: dark)').matches;r.dataset.theme=dark?'light':'dark'};
+
+const toast=$('[data-toast]');let tt;
+const say=h=>{toast.innerHTML=h;toast.classList.add('on');clearTimeout(tt);tt=setTimeout(()=>toast.classList.remove('on'),4200)};
+
+// 格式卡片
+const FORMATS=[
+ {k:'epub',name:'EPUB 电子书',ext:'EPUB',color:'var(--epub)',desc:'单个 .epub,适合手机、Kindle、Apple Books。pandoc 生成,带目录与脚注',zip:{work:'律藏-元亨寺CBETA-epub.zip\n└─ 律藏.epub',all:'元亨寺CBETA-全部-epub.zip\n├─ 律藏/律藏.epub\n├─ 经藏/长部.epub  中部.epub …\n└─ README.txt'}},
+ {k:'html',name:'HTML 网页',ext:'HTML',color:'var(--html)',desc:'单个网页文件,浏览器打开即读,可打印;样式内联、离线可用',zip:{work:'律藏-元亨寺CBETA-html.zip\n└─ 律藏.html',all:'元亨寺CBETA-全部-html.zip\n├─ index.html        ← 总目录,可搜索\n└─ works/律藏.html  长部.html …'}},
+ {k:'docx',name:'Word 文档',ext:'DOCX',color:'var(--docx)',desc:'单个 .docx,可编辑、排版、打印。pandoc 按 Word 模板生成',zip:{work:'律藏-元亨寺CBETA-docx.zip\n└─ 律藏.docx',all:'元亨寺CBETA-全部-docx.zip\n├─ 律藏/律藏.docx\n└─ 经藏/长部.docx …'}},
+ {k:'md',name:'Markdown',ext:'MD',color:'var(--md)',desc:'每章一个 .md,带目录文件。适合 Obsidian、Git、二次编辑',zip:{work:'律藏-元亨寺CBETA-markdown.zip\n├─ README.md      ← 目录\n├─ 01-波罗夷.md\n└─ 02-僧残.md …',all:'元亨寺CBETA-全部-markdown.zip\n├─ README.md      ← 总目录\n├─ 律藏/README.md  01-波罗夷.md …\n└─ 经藏/长部/README.md …'}},
+];
+// 演示状态:哪些已经有人生成过
+const STATE={work:{epub:{ready:true,size:'1.4 MB',age:'2 天前',left:'5 天'},html:{ready:true,size:'0.9 MB',age:'今天',left:'7 天'},docx:{ready:false,eta:'约 40 秒'},md:{ready:false,eta:'约 10 秒'}},
+             all:{epub:{ready:false,eta:'约 3 分钟'},html:{ready:true,size:'6.8 MB',age:'1 天前',left:'6 天'},docx:{ready:false,eta:'约 5 分钟'},md:{ready:false,eta:'约 1 分钟'}}};
+
+function render(screen){
+  const box=$('#s-'+screen+' [data-formats]');box.innerHTML='';
+  FORMATS.forEach(f=>{
+    const st=STATE[screen][f.k];
+    const el=document.createElement('div');el.className='card fmt';
+    el.innerHTML=`<div class="fmt-top"><div class="ficon" style="background:${f.color}">${f.ext}</div><div><h3>${f.name}</h3><p>${f.desc}</p></div></div>
+      <div class="zipline">${f.zip[screen]}</div>
+      <div class="fmt-foot">${stateHtml(st)}<button class="btn ${st.ready?'primary':''}">⤓ ${st.ready?'下载':'生成并下载'}</button></div>
+      <div class="prog"><div class="prog-txt"><span data-msg>排队中…</span><span data-pct>0%</span></div><div class="bar"><i></i></div></div>`;
+    $('.btn',el).onclick=()=>start(screen,f,el);
+    box.appendChild(el);
+  });
+}
+const stateHtml=st=>st.failed?`<span class="state fail"><span class="dot"></span>生成失败,可重试</span>`:st.ready?`<span class="state ready"><span class="dot"></span>已就绪 · ${st.size} · ${st.age}生成 · ${st.left}后过期</span>`:`<span class="state cold"><span class="dot"></span>首次下载需生成 · ${st.eta}</span>`;
+
+function start(screen,f,el){
+  const st=STATE[screen][f.k];
+  if(st.ready){say(`开始下载 <b>${f.ext}</b>(${st.size})`);return}
+  el.classList.add('busy');
+  const steps=screen==='work'?['排队中…','读取第 1/12 章','读取第 4/12 章','读取第 9/12 章',f.k==='docx'||f.k==='epub'?'pandoc 转换中':'套用模板','打包 zip']
+                            :['排队中…','律藏(1/32)','经藏 · 长部(6/32)','经藏 · 小部(18/32)','论藏(27/32)',f.k==='docx'||f.k==='epub'?'pandoc 转换中':'生成总目录','打包 zip'];
+  let i=0;const bar=$('.bar i',el),msg=$('[data-msg]',el),pct=$('[data-pct]',el);
+  const tick=()=>{
+    if(i>=steps.length){
+      el.classList.remove('busy');
+      Object.assign(st,{ready:true,size:screen==='work'?'1.1 MB':'7.2 MB',age:'刚刚',left:'7 天'});
+      render(screen);
+      say(`<b>${f.ext}</b> 已生成,下载已自动开始。<br>没有开始?<a href="#" onclick="return false">点此下载</a>`);
+      return}
+    const p=Math.round(i/(steps.length)*100);msg.textContent=steps[i];pct.textContent=p+'%';bar.style.width=p+'%';i++;
+    setTimeout(tick,i===1?900:700);
+  };tick();
+}
+render('work');render('all');
+
+// 分类范围
+const TREE={vinaya:{name:'律藏',works:[['经分别·大分别',3],['经分别·比丘尼分别',2],['大品',3],['小品',3],['附随',1]]},
+ sutta:{name:'经藏',works:[['长部',34],['中部',15],['相应部',56],['增支部',11],['小诵',9],['法句经',26],['自说',8],['如是语',4],['经集',5],['天宫事',7],['饿鬼事',4],['长老偈',21],['长老尼偈',16],['本生',22],['义释',2],['无碍解道',3],['譬喻',2],['佛种姓',3],['所行藏',3]]},
+ abhi:{name:'论藏',works:[['法集论',4],['分别论',18],['界论',14],['人施设论',10],['论事',23],['双论',10],['发趣论',24]]},
+ anna:{name:'藏外',works:[['清净道论',23]]}};
+function scope(k){
+  $$('[data-scope] .pill').forEach(p=>p.classList.toggle('on',p.dataset.k===k));
+  const keys=k==='all'?Object.keys(TREE):[k];
+  const works=keys.flatMap(x=>TREE[x].works);const ch=works.reduce((a,w)=>a+w[1],0);
+  $('[data-sum]').innerHTML=`<div><b>${works.length}</b><span>部作品</span></div><div><b>${ch}</b><span>章</span></div><div><b>${(ch*0.0081).toFixed(1)}M</b><span>字</span></div><div><b>${(ch*0.019).toFixed(1)} MB</b><span>预计 zip 大小(HTML)</span></div>`;
+  $('[data-scope-label]').textContent='范围:'+(k==='all'?'全部':TREE[k].name);
+  $('[data-incl]').innerHTML=keys.map((x,i)=>`<details ${i===0?'open':''}><summary><b>${TREE[x].name}</b><span class="n">${TREE[x].works.length} 部</span></summary><ul>${TREE[x].works.map(w=>`<li>${w[0]}<span>${w[1]} 章</span></li>`).join('')}</ul></details>`).join('');
+}
+$$('[data-scope] .pill').forEach(p=>p.onclick=()=>scope(p.dataset.k));scope('all');
+
+// 导出包 index
+const PALI={'经分别·大分别':'Mahāvibhaṅga','经分别·比丘尼分别':'Bhikkhunīvibhaṅga','大品':'Mahāvagga','小品':'Cūḷavagga','附随':'Parivāra','长部':'Dīghanikāya','中部':'Majjhimanikāya','相应部':'Saṃyuttanikāya','增支部':'Aṅguttaranikāya','小诵':'Khuddakapāṭha','法句经':'Dhammapada','自说':'Udāna','如是语':'Itivuttaka','经集':'Suttanipāta','天宫事':'Vimānavatthu','饿鬼事':'Petavatthu','长老偈':'Theragāthā','长老尼偈':'Therīgāthā','本生':'Jātaka','义释':'Niddesa','无碍解道':'Paṭisambhidāmagga','譬喻':'Apadāna','佛种姓':'Buddhavaṃsa','所行藏':'Cariyāpiṭaka','法集论':'Dhammasaṅgaṇī','分别论':'Vibhaṅga','界论':'Dhātukathā','人施设论':'Puggalapaññatti','论事':'Kathāvatthu','双论':'Yamaka','发趣论':'Paṭṭhāna','清净道论':'Visuddhimagga'};
+const GROUPS={律藏:[['经分别',0,2],['犍度',2,4],['附随',4,5]],经藏:[['长部 · 中部 · 相应部 · 增支部',0,4],['小部',4,19]],论藏:[['论',0,7]],藏外:[['注释与论著',0,1]]};
+const PAL={律藏:'Vinayapiṭaka',经藏:'Suttapiṭaka',论藏:'Abhidhammapiṭaka',藏外:'Aññā'};
+let seed=7;const rnd=()=>(seed=(seed*9301+49297)%233280)/233280;
+const body=$('[data-xbody]');
+Object.values(TREE).forEach(t=>{
+  const sec=document.createElement('section');sec.className='x-pitaka';sec.dataset.p=t.name;
+  sec.innerHTML=`<h2>${t.name}<small>${PAL[t.name]}</small></h2>`+GROUPS[t.name].map(g=>`<div class="x-cat" data-cat>${g[0]}</div><div class="x-works">${t.works.slice(g[1],g[2]).map(w=>{const p=Math.round(40+rnd()*60);return `<a class="x-work"><div class="t">${w[0]}</div><div class="p">${PALI[w[0]]}</div><div class="m"><span>${w[1]} 章</span><span class="pb"><i style="width:${p}%"></i></span><span>${p}%</span></div></a>`}).join('')}</div>`).join('');
+  body.appendChild(sec);
+});
+$$('.x-work',body).forEach(a=>{a.dataset.s=(a.textContent).toLowerCase();a.onclick=()=>go('xread')});
+let seg='';
+const filter=()=>{const q=$('[data-xq]').value.trim().toLowerCase().normalize('NFD').replace(/[̀-ͯ]/g,'');let n=0;
+  $$('.x-pitaka').forEach(s=>{let any=0;$$('.x-work',s).forEach(w=>{const ok=(!q||w.dataset.s.normalize('NFD').replace(/[̀-ͯ]/g,'').includes(q));w.style.display=ok?'':'none';any+=ok});
+    $$('.x-works',s).forEach(g=>{const v=[...g.children].some(c=>c.style.display!=='none');g.style.display=v?'':'none';g.previousElementSibling.style.display=v?'':'none'});
+    const show=any&&(!seg||s.dataset.p===seg);s.style.display=show?'':'none';n+=show});
+  $('[data-xempty]').style.display=n?'none':'block'};
+$('[data-xq]').oninput=filter;
+$$('[data-xseg] button').forEach(b=>b.onclick=()=>{seg=b.dataset.k;$$('[data-xseg] button').forEach(x=>x.classList.toggle('on',x===b));filter()});
+
+// 作品 html
+$('[data-toc-toggle]').onclick=()=>$('[data-toc]').classList.toggle('on');
+let fs=17;$('[data-font]').onclick=()=>{fs=fs>=21?15:fs+2;$('.x-article').style.fontSize=fs+'px'};
+$$('[data-toc] a').forEach(a=>a.addEventListener('click',()=>{$$('[data-toc] a').forEach(x=>x.classList.toggle('on',x===a))}));
+})();
+</script>
+</body>
+</html>

+ 354 - 0
api-v13/documents/reading-cache-plan.html

@@ -0,0 +1,354 @@
+<!doctype html>
+<html lang="zh-Hans">
+<head>
+<meta charset="utf-8">
+<meta name="viewport" content="width=device-width, initial-scale=1">
+<title>段落缓存方案</title>
+<style>
+:root{
+  --bg:#f6f8fb; --surface:#fff; --surface-2:#f1f4f8; --border:#dfe5ec; --text:#1d2733; --muted:#5f6f83;
+  --primary:#066fd1; --primary-lt:#e7f1fc; --ok:#2f9e44; --ok-lt:#e8f6eb; --warn:#e67700; --warn-lt:#fff3e0;
+  --danger:#d63939; --danger-lt:#fdecec; --violet:#7048e8; --violet-lt:#f0ebff;
+  --mono:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;
+}
+@media (prefers-color-scheme: dark){:root:not([data-theme="light"]){
+  --bg:#11161d; --surface:#18202a; --surface-2:#1f2935; --border:#2c3746; --text:#e4e9f0; --muted:#97a6b8;
+  --primary:#4c9bf0; --primary-lt:#1a2f4d; --ok:#51cf66; --ok-lt:#16301d; --warn:#ffa94d; --warn-lt:#3a2a12;
+  --danger:#ff6b6b; --danger-lt:#3a1a1a; --violet:#9775fa; --violet-lt:#271f45;
+}}
+:root[data-theme="dark"]{
+  --bg:#11161d; --surface:#18202a; --surface-2:#1f2935; --border:#2c3746; --text:#e4e9f0; --muted:#97a6b8;
+  --primary:#4c9bf0; --primary-lt:#1a2f4d; --ok:#51cf66; --ok-lt:#16301d; --warn:#ffa94d; --warn-lt:#3a2a12;
+  --danger:#ff6b6b; --danger-lt:#3a1a1a; --violet:#9775fa; --violet-lt:#271f45;
+}
+*{box-sizing:border-box}
+body{margin:0;background:var(--bg);color:var(--text);font:15px/1.7 -apple-system,BlinkMacSystemFont,"Segoe UI","PingFang SC","Microsoft YaHei",sans-serif}
+.wrap{max-width:1100px;margin:0 auto;padding:28px 16px 80px}
+h1{font-size:26px;margin:0 0 4px}
+.sub{color:var(--muted);margin:0 0 24px}
+h2{font-size:19px;margin:40px 0 12px;padding-bottom:6px;border-bottom:2px solid var(--border)}
+h3{font-size:16px;margin:22px 0 8px}
+p{margin:0 0 12px}
+code{font:13px var(--mono);background:var(--surface-2);padding:1px 5px;border-radius:4px}
+.card{background:var(--surface);border:1px solid var(--border);border-radius:10px;padding:16px 18px;margin:12px 0}
+table{border-collapse:collapse;width:100%;font-size:14px;background:var(--surface)}
+th,td{border:1px solid var(--border);padding:7px 10px;text-align:left;vertical-align:top}
+th{background:var(--surface-2);font-weight:600}
+td.num{text-align:right;font-variant-numeric:tabular-nums;white-space:nowrap}
+.tbl{overflow-x:auto;margin:10px 0}
+.pill{display:inline-block;font-size:12px;padding:0 8px;border-radius:10px;font-weight:600}
+.l0{background:var(--violet-lt);color:var(--violet)}
+.l1{background:var(--ok-lt);color:var(--ok)}
+.l2{background:var(--primary-lt);color:var(--primary)}
+.l3{background:var(--ok-lt);color:var(--ok)}
+.l4{background:var(--violet-lt);color:var(--violet)}
+.gen{background:var(--warn-lt);color:var(--warn)}
+.cold{background:var(--danger-lt);color:var(--danger)}
+.bad{color:var(--danger);font-weight:600}
+.good{color:var(--ok);font-weight:600}
+.kpis{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:10px;margin:14px 0}
+.kpi{background:var(--surface);border:1px solid var(--border);border-radius:10px;padding:12px 14px}
+.kpi b{display:block;font-size:24px;line-height:1.2}
+.kpi span{color:var(--muted);font-size:13px}
+@media(max-width:720px){.kpis{grid-template-columns:repeat(2,minmax(0,1fr))}}
+.diagram{background:var(--surface);border:1px solid var(--border);border-radius:10px;padding:10px;overflow-x:auto}
+.diagram svg{display:block;min-width:900px;width:100%;height:auto}
+.legend{display:flex;flex-wrap:wrap;gap:8px 18px;font-size:13px;color:var(--muted);margin:10px 4px 0}
+.legend i{display:inline-block;width:26px;height:0;border-top:3px solid;vertical-align:middle;margin-right:6px}
+ol li,ul li{margin:4px 0}
+.note{border-left:4px solid var(--warn);background:var(--warn-lt);padding:10px 14px;border-radius:6px;margin:12px 0}
+.decide{border-left:4px solid var(--primary);background:var(--primary-lt);padding:10px 14px;border-radius:6px;margin:12px 0}
+</style>
+</head>
+<body>
+<div class="wrap">
+
+<h1>阅读段落:冷启动与缓存</h1>
+<p class="sub">范围:<code>/v3/tipitaka-reading</code>、Laravel library 阅读器、三藏下载打包(含 mobile 离线包)。两大块:<b>A. 冷启动</b>(没命中时一块只查几次库)与 <b>B. 缓存</b>(命中时不查库)。2026-11-22,方案稿,未动代码。</p>
+
+<h2>现状(实测)</h2>
+<p>同一块 200 段(book 213),<code>TipitakaReadingService::page()</code>:</p>
+<div class="kpis">
+  <div class="kpi"><b class="bad">1954</b><span>cs6 冷启动查询 · 1215 ms</span></div>
+  <div class="kpi"><b class="bad">2009</b><span>元亨寺·CBETA 冷启动查询 · 1384 ms(库 617 ms)</span></div>
+  <div class="kpi"><b class="bad">403</b><span>cs6 缓存全部命中仍要查 · 164 ms</span></div>
+  <div class="kpi"><b class="good">≈4 / 0</b><span>目标:冷启动 / 命中时查询次数</span></div>
+</div>
+
+<h3>冷启动(没命中)在查什么</h3>
+<div class="tbl"><table>
+<tr><th>查询</th><th>cs6</th><th>CBETA</th><th>为什么这么多</th></tr>
+<tr><td><code>discussions</code>(挂在句子上的批注)</td><td class="num">1151</td><td class="num">1207(343 ms)</td><td><code>injectAnnotationNotes()</code> <b>逐句</b>查一次</td></tr>
+<tr><td><code>sentences</code>(该段句子)</td><td class="num">200</td><td class="num">200</td><td><code>renderReadSentences()</code> 逐段查</td></tr>
+<tr><td><code>channels</code>(同一个 channel)</td><td class="num">200</td><td class="num">200</td><td>逐段把同一行查 200 遍</td></tr>
+<tr><td><code>pali_texts.level</code> / <code>.class</code></td><td class="num">400</td><td class="num">399</td><td>逐段两次,经文静态数据</td></tr>
+<tr><td><code>page()</code> 候选段 + 两次 count</td><td class="num">3</td><td class="num">3</td><td>每块</td></tr>
+</table></div>
+<p>CBETA 那块 1384 ms 里数据库占 617 ms,其余约 770 ms 是 PHP 渲染与写缓存。另外两处这两个样本没触发、但模板多的 channel 会放大:</p>
+<ul>
+<li><b>Markup 的取数是「一次 <code>renderMany</code> 一批」</b>(术语 <code>TermLoader</code>、引用句子 <code>SentenceLoader</code>、channel 名 <code>ChannelDirectory</code>、<code>QaLoader</code>、<code>TplLoader</code> 都是 <code>whereIn</code>),但现在一段调用一次 <code>renderMany</code>,所以是<b>每段一批</b>:200 段带术语就是 200 次术语查询。</li>
+<li><b>批注正文逐条渲染</b>:<code>renderAnnotationNote()</code> 每条批注单独调一次 <code>MarkupService::render()</code>,批注里有术语就每条各查一次。</li>
+</ul>
+
+<h3>命中时还在查什么</h3>
+<div class="tbl"><table>
+<tr><th>查询</th><th>次数 / 200 段</th><th>出处</th><th>性质</th></tr>
+<tr><td><code>pali_texts.level</code>(是不是标题段)</td><td class="num">200</td><td><code>readParagraph()</code> 进缓存前的 <code>paragraphLevel()</code></td><td>经文静态数据</td></tr>
+<tr><td><code>pali_texts.class</code>(段落外壳的 class)</td><td class="num">200</td><td><code>readParagraph()</code> 命中后拼外壳</td><td>经文静态数据</td></tr>
+<tr><td><code>distinct (book_id, paragraph)</code> 候选段</td><td class="num">1</td><td><code>page()</code></td><td>随译文变化</td></tr>
+<tr><td><code>count(distinct …)</code> 进度 total / remaining</td><td class="num">2</td><td><code>page()</code> 的 <code>progressMeta()</code></td><td>随译文变化</td></tr>
+<tr><td>(字节模式)<code>pali_texts.lenght</code></td><td class="num">每书 1</td><td><code>page()</code> 的 <code>paragraphLengths()</code></td><td>经文静态数据</td></tr>
+</table></div>
+<ul>
+<li><b>Laravel 阅读器</b>按章读:<code>resolveDisplayRange()</code> 算区间,<code>fetchRangeContent()</code> 对 <code>range($start, $end)</code> 逐段调 <code>readParagraph()</code>,整章一次,不切块。实测 213-34(下钻后 27 段):第一次 384 次查询(批注 247 次),第二次 83 次(正文 51 次 + 页面外围约 32 次)。</li>
+<li><b>TTL</b> 用的是通用的 <code>mint.cache.expire</code>:本地 10 秒、默认 10 小时,过期就整段重渲。</li>
+<li>一块 200 段就是 200 次 Redis 往返(本机看不出,生产上乘以网络延迟)。</li>
+</ul>
+
+<h2>A. 冷启动:按块渲染,一块只查几次库</h2>
+
+<div class="card">
+<p><span class="pill cold">A1 批量渲染</span> &nbsp;<code>PaliContentService</code> 新增 <code>readParagraphs(int $book, array $paras, string $channel, string $format)</code>,单段的 <code>readParagraph()</code> 改为调它(传一段)——<b>只有一份渲染逻辑</b>。没命中的那些段一起渲染:</p>
+<ol>
+<li><b>channel 查一次</b>(现在每段一次)。</li>
+<li><b>句子查一次</b>:<code>where book, channel, paragraph in (未命中的段) order by paragraph, word_start</code>。</li>
+<li><b>批注查一次</b>:所有句子的 uid 一次 <code>whereIn('res_id', …)</code>,在 PHP 里按句分组;<code>injectAnnotationNotes()</code> 改为接收已取好的批注,不再自己查。</li>
+<li><b>标题级别与 class 查 L0</b>(见 B 部分),不落库。</li>
+<li><b>一次 <code>renderManyAs()</code> 渲染全部句子</b>:Resolver 收集整块的术语 / 引用 / 模板,各类只查一次。</li>
+<li><b>批注正文也合并成一次 <code>renderMany()</code></b>(现在每条批注一次 <code>render()</code>)。</li>
+</ol>
+<p>结果:200 段从约 2000 次查询降到<b>约 4 次</b>(channel、句子、批注、<code>page()</code> 的候选),外加每类模板数据各一次。CBETA 那块的 617 ms 库时间预计降到几十 ms;剩下的是渲染本身的 CPU,改完再量。</p>
+</div>
+
+<div class="card">
+<p><span class="pill cold">A2 谁受益</span></p>
+<ul>
+<li><code>page()</code>:一块里没命中的段交给 <code>readParagraphs()</code> 一次渲染(与 B 的批量读同一个入口)。</li>
+<li>阅读器:L3 章节缓存没命中时,整章的段一次交给 <code>readParagraphs()</code>。</li>
+<li>下载打包:经 <code>page()</code> 自动受益。cs6 整 channel html 打包 2286 s,大部分花在逐句批注与逐段查询上,这一步对它影响最大。</li>
+</ul>
+<p>注意:批量取句子时要保持现有口径——<code>strlen &gt; 0</code>、句子按 <code>word_start</code> 排、段内「有评估的句子之外补灰色对勾」的规则按段计算,不能变成按块计算。</p>
+</div>
+
+<h2>B. 缓存</h2>
+<h3>B 的方案:五块缓存,只给 readParagraph 改内部、不套外层</h3>
+
+<p>两个调用形状不同,缓存也分开:</p>
+<ul>
+<li><b>阅读器</b>按章读:<code>resolveDisplayRange()</code> 算出整章区间,<code>fetchRangeContent()</code> 一次拼完,<b>不切块</b>。区间只由经文静态数据决定,同一章每次都一样 → 缓存整章成品,一次 GET。</li>
+<li><b><code>/v3/tipitaka-reading</code> 与下载打包</b>按块读:块的边界取决于调用方的 <code>page_size</code> / <code>unit</code> / 游标,各不相同 → 缓存段落与索引,按块现拼。</li>
+</ul>
+
+<div class="card">
+<p><span class="pill l0">L0 书目元数据</span> &nbsp;<code>pali_texts</code> 的静态列按书缓存:<code>para → [level, class, lenght, chapter_len, chapter_strlen, toc]</code>。</p>
+<ul>
+<li>key:<code>/pali-meta/{book}/v{N}</code>,<b>30 天</b>;经文重新导入时把代码里的 <code>N</code> 加一(与 <code>TipitakaCatalogService::CACHE_KEY</code> 同一做法)。同一进程内再用数组记住。</li>
+<li>使用方:<code>readParagraph()</code> 未命中时取标题级别与 class;<code>page()</code> 的字节模式;阅读器的 <code>resolveDisplayRange()</code>(现在每次查本书全部章节行);导出的 <code>headingLevels()</code>。</li>
+</ul>
+</div>
+
+<div class="card">
+<p><span class="pill l1">L1 段落成品</span> &nbsp;<code>readParagraph()</code> 直接缓存<b>完整结果</b>(含外壳 <code>&lt;div id='para-N'&gt;</code> / <code>&lt;hN&gt;</code> 与段后脚注列表)。</p>
+<ul>
+<li>外壳只依赖 L0 的 level / class(经文静态数据),放进缓存不会过时,所以<b>不需要外层</b>:把那两次查询挪进缓存闭包、改查 L0,签名与返回形状不变。</li>
+<li>key:<code>/read-para/v4/{book}-{para}/{channel}/{format}</code>(换版本号,旧 key 自然过期)。没有译文的段也缓存(空 display)。</li>
+<li>失效:沿用 <code>forgetParagraph()</code>(句子、批注的模型事件已接好),改成删新 key。TTL 改用专门配置 <code>mint.cache.read_paragraph_ttl</code>(见「需要你定的」)。</li>
+</ul>
+</div>
+
+<div class="card">
+<p><span class="pill gen">版本号</span> &nbsp;每个 (channel, book) 一个递增计数 <code>/read-gen/{channel}/{book}</code>(<code>RedisCache::increment</code>,不过期)。</p>
+<ul>
+<li>句子、批注的模型事件里,在 <code>forgetParagraph()</code> 旁边加一次 <code>increment</code>:这本书的译文变了。</li>
+<li>L2、L3 的 key 都带上它。版本一变,旧 key 不再被读到、自然过期,<b>不用去找「哪些章包含这一段」再逐个删</b>(父章、子章、下钻后的区间互相重叠,精确删除很难)。</li>
+<li>代价:一次多读一个小 key;编辑某本书时只有这本书的索引和章节缓存失效,别的书不受影响。</li>
+</ul>
+</div>
+
+<div class="card">
+<p><span class="pill l2">L2 内容索引</span> &nbsp;「某 channel 哪些段有译文」,给 <code>page()</code> 用:</p>
+<ul>
+<li><code>/read-index/{channel}/books/g…</code>:有译文的书号;<code>/read-index/{channel}/{book}/g{gen}</code>:该书有译文的段号(升序)。书号列表用 channel 级版本号(同样在句子事件里加一)。</li>
+<li><code>page()</code> 的候选段、游标、<code>total</code> / <code>remaining</code> 全在 PHP 里对这个数组算,<b>命中时 0 查询</b>;游标格式 <code>{book}-{para}</code> 与响应不变。</li>
+<li>重建只需一条 <code>select distinct paragraph</code>;cs6 最大的一本书一万多段,几十 KB;TTL 7 天。</li>
+</ul>
+</div>
+
+<div class="card">
+<p><span class="pill l3">L3 章节成品</span> &nbsp;给阅读器:整章拼好的 HTML 一次存、一次取。</p>
+<ul>
+<li>key:<code>/read-chapter/{channel}/{book}-{start}-{end}/g{gen}</code>,值 <code>{display, title}</code>。<code>start</code> / <code>end</code> 由 <code>resolveDisplayRange()</code> 算(查 L0,不落库)。</li>
+<li>命中:读版本号 1 次 + 读章节 1 次,<b>正文部分 0 查询</b>。未命中才逐段 <code>readParagraph()</code>(各段多半已在 L1)拼好回写。</li>
+<li>只动 <code>BookController::fetchRangeContent()</code> 这一个方法:先查 L3,没有再走原来的拼接。</li>
+<li><code>?comm=</code> 注释注入(<code>injectNoteMarkers</code>)在取出后做,不进缓存,不影响命中。</li>
+</ul>
+</div>
+
+<div class="card">
+<p><span class="pill l4">L4 批量读</span> &nbsp;只给 <code>page()</code>:一块最多 200 段,逐段 GET 是 200 次往返。</p>
+<ul>
+<li><code>RedisCache</code> 加 <code>many()</code>(phpredis 的 <code>RedisCluster::mget</code>,按 slot 拆到各节点);<code>readParagraph</code> 加批量版 <code>readParagraphs()</code>:先 <code>many()</code> 拿命中的,没命中的逐段渲染回写。</li>
+<li>已在开发集群验证:200 个 key 落在 200 个 slot,<code>mget</code> 全部取对。本机往返近乎为零,看不出差别;收益与生产上 PHP 到 Redis 的往返延迟成正比(1 ms 往返时一块省约 200 ms)。</li>
+<li><b>阅读器不需要它</b>:整章已有 L3。可以放到最后做,或先测生产延迟再决定。</li>
+</ul>
+</div>
+
+<h2>数据流(冷启动 + 缓存)</h2>
+<div class="diagram">
+<svg viewBox="0 0 1060 600" role="img" aria-labelledby="t d">
+<title id="t">段落数据流</title>
+<desc id="d">mobile 与下载打包经 TipitakaReadingService 读内容索引 L2 与段落成品 L1;阅读器经 BookController 读章节成品 L3,未命中才落到 L2 与 L1;L1 未命中才渲染、查 L0 与数据库;写入事件删 L1 并给本书版本号加一,L2、L3 的 key 带版本号。</desc>
+<defs>
+<marker id="ah" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto-start-reverse"><path d="M0,0 L10,5 L0,10 z" fill="var(--muted)"/></marker>
+<marker id="ahg" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto-start-reverse"><path d="M0,0 L10,5 L0,10 z" fill="var(--ok)"/></marker>
+<marker id="ahr" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto-start-reverse"><path d="M0,0 L10,5 L0,10 z" fill="var(--danger)"/></marker>
+<marker id="ahw" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto-start-reverse"><path d="M0,0 L10,5 L0,10 z" fill="var(--warn)"/></marker>
+</defs>
+<style>
+.bx{fill:var(--surface);stroke:var(--border);stroke-width:1.5}
+.tx{fill:var(--text);font:600 14px -apple-system,"PingFang SC","Microsoft YaHei",sans-serif}
+.sm{fill:var(--muted);font:12px -apple-system,"PingFang SC","Microsoft YaHei",sans-serif}
+.mono{fill:var(--muted);font:11px ui-monospace,Menlo,monospace}
+.ln{stroke:var(--muted);stroke-width:1.6;fill:none}
+.hit{stroke:var(--ok);stroke-width:2.4;fill:none}
+.miss{stroke:var(--danger);stroke-width:1.8;fill:none;stroke-dasharray:6 4}
+.inv{stroke:var(--warn);stroke-width:1.6;fill:none;stroke-dasharray:3 4}
+</style>
+
+<text x="20" y="26" class="sm">调用方</text>
+<rect class="bx" x="20" y="40" width="200" height="54" rx="8"/><text class="tx" x="34" y="63">mobile / v6</text><text class="mono" x="34" y="82">GET /v3/tipitaka-reading</text>
+<rect class="bx" x="20" y="106" width="200" height="54" rx="8"/><text class="tx" x="34" y="129">下载打包 worker</text><text class="mono" x="34" y="148">TipitakaExportBuilder</text>
+<rect class="bx" x="20" y="200" width="200" height="54" rx="8"/><text class="tx" x="34" y="223">Laravel 阅读器</text><text class="mono" x="34" y="242">按章,整章一次</text>
+
+<!-- B 列 -->
+<rect class="bx" x="270" y="50" width="220" height="80" rx="8"/>
+<text class="tx" x="284" y="76">TipitakaReadingService</text><text class="mono" x="284" y="96">::page() 按块</text><text class="sm" x="284" y="116">候选 / 游标 / 进度 → L2</text>
+<line class="ln" x1="220" y1="67" x2="268" y2="80" marker-end="url(#ah)"/>
+<line class="ln" x1="220" y1="133" x2="268" y2="108" marker-end="url(#ah)"/>
+
+<rect class="bx" x="270" y="190" width="220" height="74" rx="8"/>
+<text class="tx" x="284" y="216">BookController</text><text class="mono" x="284" y="236">fetchRangeContent()</text><text class="sm" x="284" y="254">区间由 L0 算</text>
+<line class="ln" x1="220" y1="227" x2="268" y2="227" marker-end="url(#ah)"/>
+
+<rect x="270" y="300" width="220" height="86" rx="8" fill="var(--ok-lt)" stroke="var(--ok)" stroke-width="1.5"/>
+<text class="tx" x="284" y="324">L3 章节成品</text><text class="mono" x="284" y="344">/read-chapter/{ch}/</text><text class="mono" x="284" y="360">{book}-{start}-{end}/g{gen}</text><text class="sm" x="284" y="378">命中:整章 1 次 GET</text>
+<line class="hit" x1="380" y1="264" x2="380" y2="298" marker-end="url(#ahg)"/>
+
+<rect x="270" y="450" width="220" height="80" rx="8" fill="var(--warn-lt)" stroke="var(--warn)" stroke-width="1.5"/>
+<text class="tx" x="284" y="474">本书版本号</text><text class="mono" x="284" y="494">/read-gen/{ch}/{book}</text><text class="sm" x="284" y="514">INCR,不过期</text>
+
+<!-- C 列 -->
+<rect x="540" y="40" width="220" height="78" rx="8" fill="var(--primary-lt)" stroke="var(--primary)" stroke-width="1.5"/>
+<text class="tx" x="554" y="64">L2 内容索引</text><text class="mono" x="554" y="84">/read-index/{ch}/books</text><text class="mono" x="554" y="102">/read-index/{ch}/{book}/g{gen}</text>
+<line class="hit" x1="490" y1="80" x2="538" y2="78" marker-end="url(#ahg)"/>
+
+<rect x="540" y="170" width="220" height="96" rx="8" fill="var(--ok-lt)" stroke="var(--ok)" stroke-width="1.5"/>
+<text class="tx" x="554" y="194">L1 段落成品</text><text class="mono" x="554" y="214">/read-para/v4/{b}-{p}/</text><text class="mono" x="554" y="230">{ch}/{fmt}</text><text class="sm" x="554" y="252">含外壳与脚注,空段也存</text>
+<path class="hit" d="M490,112 C516,112 516,200 538,204" marker-end="url(#ahg)"/>
+<path class="miss" d="M490,340 C516,340 516,250 538,248" marker-end="url(#ahr)"/>
+<text class="sm" x="284" y="406" style="fill:var(--danger)">L3 未命中 → 逐段取 L1,拼好回写</text>
+
+<rect class="bx" x="540" y="320" width="220" height="86" rx="8"/>
+<text class="tx" x="554" y="344">A1 批量渲染</text><text class="sm" x="554" y="364">未命中的段一起:句子 1 次、</text><text class="sm" x="554" y="382">批注 1 次、renderMany 1 次</text><text class="sm" x="554" y="400">回写 L1</text>
+<line class="miss" x1="650" y1="266" x2="650" y2="318" marker-end="url(#ahr)"/>
+<text class="sm" x="658" y="312" style="fill:var(--danger)">L1 未命中</text>
+
+<!-- D 列 -->
+<rect x="820" y="170" width="220" height="96" rx="8" fill="var(--violet-lt)" stroke="var(--violet)" stroke-width="1.5"/>
+<text class="tx" x="834" y="194">L4 批量读(仅 page)</text><text class="mono" x="834" y="214">RedisCache::many()</text><text class="sm" x="834" y="234">一块 200 段 = 1 次 MGET</text><text class="sm" x="834" y="252">(按节点拆)</text>
+<line class="hit" x1="760" y1="218" x2="818" y2="218" marker-end="url(#ahg)"/>
+
+<rect x="820" y="320" width="220" height="86" rx="8" fill="var(--violet-lt)" stroke="var(--violet)" stroke-width="1.5"/>
+<text class="tx" x="834" y="344">L0 书目元数据</text><text class="mono" x="834" y="364">/pali-meta/{book}/v{N}</text><text class="sm" x="834" y="384">level · class · chapter_len…</text>
+<line class="miss" x1="760" y1="363" x2="818" y2="363" marker-end="url(#ahr)"/>
+<path class="ln" d="M490,240 H504 V292 H880 V318" marker-end="url(#ah)" style="stroke-dasharray:2 3"/>
+<text class="sm" x="780" y="286">章节区间</text>
+
+<rect x="540" y="470" width="500" height="66" rx="8" fill="var(--danger-lt)" stroke="var(--danger)" stroke-width="1.5"/>
+<text class="tx" x="554" y="495">PostgreSQL</text><text class="mono" x="554" y="516">sentences · discussions · channels · terms · pali_texts</text>
+<line class="miss" x1="650" y1="406" x2="650" y2="468" marker-end="url(#ahr)"/>
+<line class="miss" x1="930" y1="406" x2="930" y2="468" marker-end="url(#ahr)"/>
+<path class="miss" d="M760,58 H1048 V503 H1044" marker-end="url(#ahr)"/>
+<text class="sm" x="800" y="52" style="fill:var(--danger)">L2 未命中:select distinct</text>
+
+<!-- 写入 -->
+<rect class="bx" x="20" y="450" width="200" height="80" rx="8"/>
+<text class="tx" x="34" y="474">写入事件</text><text class="mono" x="34" y="494">Sentence saved/deleted…</text><text class="mono" x="34" y="512">Discussion saved/deleted</text>
+<line class="inv" x1="220" y1="480" x2="268" y2="480" marker-end="url(#ahw)"/>
+<text class="sm" x="226" y="470" style="fill:var(--warn)">+1</text>
+<line class="inv" x1="380" y1="450" x2="380" y2="388" marker-end="url(#ahw)"/>
+<path class="inv" d="M490,470 H516 V100 H538" marker-end="url(#ahw)"/>
+<path class="inv" d="M220,520 H528 V260 H538" marker-end="url(#ahw)"/>
+<text class="sm" x="226" y="548" style="fill:var(--warn)">删 L1(forgetParagraph);版本号 +1 → L2、L3 换 key</text>
+</svg>
+</div>
+<div class="legend">
+<span><i style="border-color:var(--ok)"></i>命中路径(0 次查询)</span>
+<span><i style="border-color:var(--danger);border-top-style:dashed"></i>未命中才走</span>
+<span><i style="border-color:var(--warn);border-top-style:dotted"></i>失效</span>
+<span><i style="border-color:var(--muted)"></i>调用</span>
+</div>
+
+<h2>改完后的效果</h2>
+<div class="tbl"><table>
+<tr><th></th><th>现在</th><th>改后</th></tr>
+<tr><td><code>page()</code> 一块 200 段:<b>冷启动</b>数据库</td><td class="num bad">≈2000 次(CBETA 库 617 ms)</td><td class="num good">≈4 次 + 每类模板数据 1 次</td></tr>
+<tr><td>阅读器打开一章(27 段):<b>冷启动</b>正文</td><td class="num bad">约 330 次</td><td class="num good">≈3 次</td></tr>
+<tr><td><code>page()</code> 一块 200 段:<b>命中</b>数据库</td><td class="num bad">403 次</td><td class="num good">0</td></tr>
+<tr><td><code>page()</code> 一块 200 段:Redis</td><td class="num">200 次 GET</td><td class="num">版本号 + 索引 2~3 次,段落 1 次 MGET(做了 L4)或 200 次 GET(没做)</td></tr>
+<tr><td>阅读器打开一章(213-34,27 段):正文部分</td><td class="num bad">51 次查询 + 27 次 GET</td><td class="num good">0 查询 + 2 次 GET</td></tr>
+<tr><td>阅读器打开一章:整页</td><td class="num">83 次查询(实测)</td><td class="num">约 32 次:目录、翻页、版本列表、标题等外围,不在本方案内</td></tr>
+</table></div>
+
+<h2>改动清单</h2>
+<div class="tbl"><table>
+<tr><th>文件</th><th>改什么</th><th>规模</th></tr>
+<tr><td><code>Services/PaliContentService.php</code>(冷启动)</td><td><span class="pill cold">A1</span> 新 <code>readParagraphs()</code>:channel / 句子 / 批注各查一次,整块一次 <code>renderManyAs()</code>;<code>injectAnnotationNotes()</code> 接收预取的批注;批注正文合并渲染;<code>readParagraph()</code> 改为调它</td><td>中~大</td></tr>
+<tr><td>新 <code>Services/PaliTextMetaService.php</code>(根命名空间,纯能力)</td><td><span class="pill l0">L0</span> 按书取静态列,进程内记住</td><td>小</td></tr>
+<tr><td><code>Services/PaliContentService.php</code></td><td><span class="pill l1">L1</span> <code>readParagraph()</code> 缓存完整结果、level / class 改查 L0、key 换 v4、TTL 用新配置;<code>forgetParagraph()</code> 删新 key;<code>paragraphLevel()</code> 改查 L0</td><td>中</td></tr>
+<tr><td><code>Models/Sentence.php</code>、<code>Models/Discussion.php</code></td><td><span class="pill gen">版本号</span> 事件里在 <code>forgetParagraph()</code> 旁边加 <code>increment</code>(句子改 book 时新旧两本都加)</td><td>小</td></tr>
+<tr><td>新 <code>Services/ParagraphIndexService.php</code>(根命名空间,纯能力)</td><td><span class="pill l2">L2</span> 书号列表、段号列表(带版本号)、按游标切片、total / remaining</td><td>中</td></tr>
+<tr><td><code>Services/V3/TipitakaReadingService.php</code></td><td><code>page()</code> 的 candidates / applyCursor / progressMeta / paragraphLengths 改用 L2 + L0;对外响应不变</td><td>中</td></tr>
+<tr><td><code>Http/Controllers/Library/BookController.php</code></td><td><span class="pill l3">L3</span> <code>fetchRangeContent()</code> 先查章节缓存;<code>resolveDisplayRange()</code> 改查 L0(只动这两个方法)</td><td>小</td></tr>
+<tr><td><code>Services/RedisCache.php</code> + Fake + 门面</td><td><span class="pill l4">L4</span> <code>many()</code>;<code>PaliContentService::readParagraphs()</code> 批量版</td><td>小</td></tr>
+<tr><td><code>Services/V3/TipitakaExportBuilder.php</code></td><td><code>headingLevels()</code> / <code>headings()</code> 改查 L0;取段经 <code>page()</code> 自动受益</td><td>小</td></tr>
+<tr><td><code>Console/Commands/InitCommentary.php</code></td><td>批量 <code>delete()</code> 绕过模型事件,删完后给涉及的 (channel, book) 版本号加一</td><td>小</td></tr>
+<tr><td><code>config/mint.php</code></td><td><code>cache.read_paragraph_ttl</code>、<code>cache.read_index_ttl</code>、<code>cache.read_chapter_ttl</code></td><td>小</td></tr>
+<tr><td>测试</td><td>命中时 0 查询(<code>DB::enableQueryLog</code> 断言);句子 / 批注增删改后 L1 删除、版本号加一、L2 / L3 读到新内容;游标、total / remaining 与改前一致;阅读器同一章第二次打开正文 0 查询</td><td>中</td></tr>
+</table></div>
+<p>不改的:v2 的 <code>chapter-content</code> / <code>paragraph-content</code>(走 <code>makeContentObj()</code>,v4 下线前不动);<code>tipitaka-reading</code> 的响应形状与游标格式;阅读器页面外围的查询。</p>
+
+<h2>风险与需要你定的</h2>
+<div class="decide">
+<p><b>待定 1:L1、L3 的 TTL。</b>段落与章节成品除了句子与批注(有精确失效),还依赖<b>没有失效信号的数据</b>:术语释义(<code>{{term}}</code>)、引用的其他句子(<code>{{sent}}</code>、义注对应)、channel 名称等。它们改了,缓存会旧到过期为止。</p>
+<ul>
+<li>A(推荐):<b>24 小时</b>。现在默认是 10 小时,旧内容最多多留半天;命中率大幅提高。</li>
+<li>B:7 天,另加一个全局「渲染代号」,术语保存时加一,所有段落与章节按需重渲。术语编辑很频繁时会反复整库失效。</li>
+<li>C:维持现状(跟 <code>mint.cache.expire</code>)。</li>
+</ul>
+</div>
+<div class="decide">
+<p><b>待定 2:L4 做不做。</b>阅读器不需要;只对 <code>page()</code> 有用,收益取决于生产上 PHP 到 Redis 的往返延迟。可以先上 L0–L3,量一下生产延迟再定。</p>
+</div>
+<div class="note">
+<ul>
+<li><b>绕过模型事件的写入</b>:全仓库只找到 <code>InitCommentary</code> 一处对 sentences 批量 <code>delete()</code>;以后新增批量写入要手动加版本号,在 <code>ParagraphIndexService</code> 类注释里写明。</li>
+<li><b>Redis 占用</b>:L1 key 数与现在相同,只是活得更久;L3 每个被打开过的 (channel, 章) 一个 key,正文几十 KB;版本号每个 (channel, book) 一个小 key、不过期;L0 共 217 个。</li>
+<li><b>v4</b>:v2 不读这些缓存,不受影响。</li>
+</ul>
+</div>
+
+<h2>分步实施</h2>
+<ol>
+<li><span class="pill l0">L0</span> 书目元数据(A、B 都要用)。</li>
+<li><span class="pill cold">A1</span> 批量渲染 <code>readParagraphs()</code>:冷启动从约 2000 次降到约 4 次;同时它就是 B 的批量入口。</li>
+<li><span class="pill l1">L1</span> 段落成品(含外壳):命中时 <code>page()</code> 403 → 3,阅读器正文 51 → 0。</li>
+<li><span class="pill gen">版本号</span> + <span class="pill l3">L3</span> 章节成品:阅读器整章一次 GET。</li>
+<li><span class="pill l2">L2</span> 内容索引:<code>page()</code> 命中 3 → 0。</li>
+<li>(视生产延迟)<span class="pill l4">L4</span> 批量读。</li>
+</ol>
+<p>每步单独可测、可回退。</p>
+
+</div>
+</body>
+</html>

+ 12 - 0
api-v13/documents/tasks.md

@@ -35,8 +35,20 @@ php artisan mq:task
 # 队列 wbw-analyses
 php artisan mq:wbw.analyses
 
+# 队列 export_tipitaka:三藏下载,单部作品(几秒钟)
+php artisan mq:export.tipitaka
+
+# 队列 export_tipitaka_bulk:三藏下载,分类 / 整个 channel 打包(最大的 channel 约 4 分钟)
+php artisan mq:export.tipitaka --bulk
+
 ```
 
+三藏下载的两个 worker 要分开跑,打包才不会堵住单部作品。它们处理完一条才 ack。实测 cs6 整个 channel(282 部作品)的 html 打包 217 秒、zip 43.7 MiB、
+内存峰值 172 MB(2026-11-22,段落缓存全冷;阅读段落冷启动优化之前是 2286 秒)。
+数据库或渲染变慢时仍可能超过 RabbitMQ 的 `consumer_timeout`(默认 30 分钟),建议调大,否则跑到一半被服务端断开(开发机 `rabbitmq.conf` 是 333600000,约 92 小时)。
+生成的文件存在 Redis 集群里(7 天,`mint.tipitaka_export`),中间文件在 `storage/app/tmp/tipitaka-export/`,跑完即删。
+epub / docx 依赖服务器上的 `pandoc`(3.x,路径可用 `PANDOC_PATH` 指定)。
+
 `ai_translate_v2`(`rabbitmq:consume`)待第二阶段重构 worker 后补上。`content` 队列已移除(无消费者,发送端已注释,见 `SentenceController@update` 的 FIXME)。
 
 ## every five minutes

+ 8 - 12
api-v13/public/data/category/default.json

@@ -224,8 +224,8 @@
                 "tag": ["vinaya", "parivāra"]
             },
             {
-                "name": "ṭīkā",
-                "tag": ["vinaya", "ṭīkā"],
+                "name": "añña",
+                "tag": ["vinaya", "vinaya-añña"],
                 "children": [
                     {
                         "name": "sāratthadīpanī",
@@ -233,7 +233,7 @@
                     },
                     {
                         "name": "pātimokkha",
-                        "tag": ["vinaya", "ṭīkā", "pātimokkha"]
+                        "tag": ["vinaya", "pātimokkha"]
                     },
                     {
                         "name": "vajirabuddhi",
@@ -245,19 +245,15 @@
                     },
                     {
                         "name": "vinayavinicchayo",
-                        "tag": ["vinaya", "ṭīkā", "vinayavinicchaya"]
+                        "tag": ["vinaya", "vinaya-añña", "vinayavinicchaya"]
                     },
                     {
                         "name": "vinayasaṅgaha",
-                        "tag": ["vinaya", "ṭīkā", "vinayasaṅgaha"]
-                    },
-                    {
-                        "name": "vinayālaṅkāra",
-                        "tag": ["vinaya", "ṭīkā", "vinayālaṅkāra"]
+                        "tag": ["vinaya", "vinaya-añña", "vinayasaṅgaha"]
                     },
                     {
                         "name": "uttaravinicchaya",
-                        "tag": ["vinaya", "ṭīkā", "uttaravinicchaya"]
+                        "tag": ["vinaya", "vinaya-añña", "uttaravinicchaya"]
                     },
                     {
                         "name": "pācityādiyojanā",
@@ -265,11 +261,11 @@
                     },
                     {
                         "name": "khuddasikkhā",
-                        "tag": ["vinaya", "ṭīkā", "khuddasikkhā"]
+                        "tag": ["vinaya", "vinaya-añña", "khuddasikkhā"]
                     },
                     {
                         "name": "mūlasikkhā",
-                        "tag": ["vinaya", "ṭīkā", "mūlasikkhā"]
+                        "tag": ["vinaya", "vinaya-añña", "mūlasikkhā"]
                     }
                 ]
             }

+ 195 - 0
api-v13/resources/css/modules/tipitaka.css

@@ -873,3 +873,198 @@ a.tipitaka-tree__work:hover {
     color: var(--tblr-primary);
     font-weight: 600;
 }
+
+/* ══════════════════════════════════════════
+   下载页(library/tipitaka/download.blade.php)
+   ══════════════════════════════════════════ */
+.tipitaka-download__head {
+    display: flex;
+    gap: 1.25rem;
+    align-items: center;
+    padding: 1.25rem;
+}
+.tipitaka-download__cover {
+    width: 96px;
+    min-width: 96px;
+    height: 128px;
+}
+.tipitaka-download__info {
+    flex: 1;
+    min-width: 0;
+}
+.tipitaka-download__title {
+    font-size: 1.375rem;
+    font-weight: 600;
+    margin: 0;
+}
+.tipitaka-download__meta {
+    display: flex;
+    flex-wrap: wrap;
+    gap: 4px 16px;
+    margin-top: 0.5rem;
+    color: var(--tblr-secondary);
+    font-size: 0.8125rem;
+}
+.tipitaka-download__back {
+    align-self: flex-start;
+}
+.tipitaka-download__section {
+    display: flex;
+    flex-wrap: wrap;
+    align-items: baseline;
+    gap: 4px 10px;
+    font-size: 0.9375rem;
+    font-weight: 600;
+    margin: 1.5rem 0 0.75rem;
+}
+.tipitaka-download__section small {
+    font-weight: 400;
+    color: var(--tblr-secondary);
+}
+.tipitaka-download__formats {
+    display: grid;
+    grid-template-columns: repeat(2, minmax(0, 1fr));
+    gap: 12px;
+}
+.tipitaka-download__format {
+    display: flex;
+    flex-direction: column;
+    gap: 10px;
+    padding: 1rem;
+    margin: 0;
+    transition: border-color 0.15s;
+}
+.tipitaka-download__format:hover {
+    border-color: var(--tblr-primary);
+}
+.tipitaka-download__format-top {
+    display: flex;
+    gap: 12px;
+    align-items: flex-start;
+}
+.tipitaka-download__format h3 {
+    margin: 0;
+    font-size: 0.9375rem;
+}
+.tipitaka-download__format p {
+    margin: 2px 0 0;
+    color: var(--tblr-secondary);
+    font-size: 0.8125rem;
+}
+.tipitaka-download__icon {
+    flex: none;
+    width: 42px;
+    height: 50px;
+    border-radius: 5px 12px 5px 5px;
+    color: #fff;
+    font: 700 10px/1 var(--tblr-font-monospace, monospace);
+    letter-spacing: 0.5px;
+    display: flex;
+    align-items: flex-end;
+    justify-content: center;
+    padding-bottom: 7px;
+}
+.tipitaka-download__icon--epub { background: #7b4bd1; }
+.tipitaka-download__icon--html { background: #e8590c; }
+.tipitaka-download__icon--docx { background: #1f5fbf; }
+.tipitaka-download__icon--markdown { background: #2b8a3e; }
+.tipitaka-download__file {
+    font: 0.75rem/1.5 var(--tblr-font-monospace, monospace);
+    color: var(--tblr-secondary);
+    background: var(--tblr-bg-surface-secondary);
+    border-radius: 6px;
+    padding: 6px 10px;
+    overflow-wrap: anywhere;
+}
+.tipitaka-download__foot {
+    display: flex;
+    flex-wrap: wrap;
+    align-items: center;
+    justify-content: space-between;
+    gap: 10px;
+}
+.tipitaka-download__state {
+    display: flex;
+    align-items: center;
+    gap: 6px;
+    font-size: 0.8125rem;
+    color: var(--tblr-secondary);
+}
+.tipitaka-download__dot {
+    width: 8px;
+    height: 8px;
+    border-radius: 50%;
+    background: var(--tblr-warning);
+}
+[data-state="ready"] .tipitaka-download__state,
+.tipitaka-download__state--ready { color: var(--tblr-success); }
+[data-state="ready"] .tipitaka-download__dot,
+.tipitaka-download__state--ready .tipitaka-download__dot { background: var(--tblr-success); }
+.tipitaka-download__state--failed { color: var(--tblr-danger); }
+.tipitaka-download__state--failed .tipitaka-download__dot,
+[data-state="too_large"] .tipitaka-download__dot { background: var(--tblr-danger); }
+.tipitaka-download__progress-text {
+    display: flex;
+    justify-content: space-between;
+    gap: 8px;
+    font-size: 0.8125rem;
+    color: var(--tblr-secondary);
+    margin-bottom: 4px;
+}
+.tipitaka-download__progress-text span:first-child {
+    overflow: hidden;
+    text-overflow: ellipsis;
+    white-space: nowrap;
+}
+.tipitaka-download__manual {
+    font-size: 0.8125rem;
+    cursor: pointer;
+}
+.tipitaka-download__hint {
+    display: flex;
+    gap: 8px;
+    margin-top: 14px;
+    padding: 10px 14px;
+    border-radius: 8px;
+    background: var(--tblr-primary-lt, #e8f0fa);
+    font-size: 0.8125rem;
+}
+.tipitaka-download__works {
+    padding: 0.25rem 0;
+}
+.tipitaka-download__works details + details {
+    border-top: 1px solid var(--tblr-border-color);
+}
+.tipitaka-download__works summary {
+    display: flex;
+    gap: 10px;
+    padding: 10px 16px;
+    cursor: pointer;
+}
+.tipitaka-download__works summary span {
+    margin-left: auto;
+    color: var(--tblr-secondary);
+    font-size: 0.8125rem;
+}
+.tipitaka-download__works ul {
+    margin: 0;
+    padding: 0 16px 12px 36px;
+    columns: 2;
+    column-gap: 24px;
+}
+.tipitaka-download__works li {
+    display: flex;
+    justify-content: space-between;
+    gap: 8px;
+    padding: 2px 0;
+    font-size: 0.8125rem;
+    break-inside: avoid;
+}
+.tipitaka-download__works li span {
+    color: var(--tblr-secondary);
+}
+@media (max-width: 767px) {
+    .tipitaka-download__formats { grid-template-columns: 1fr; }
+    .tipitaka-download__head { flex-wrap: wrap; }
+    .tipitaka-download__works ul { columns: 1; }
+}

+ 5 - 0
api-v13/resources/data/pali_serieses.php

@@ -1738,6 +1738,11 @@ return [
             'abbr_pts' => 'VjbT',
             'abbr_wp' => 'vajira.ṭī.pāci.',
         ],
+        1433 => [
+            'abbr_my' => 'vajira-ṭī',
+            'abbr_pts' => 'VjbT',
+            'abbr_wp' => 'vajira.ṭī.bhikkhunī.',
+        ],
         1708 => [
             'abbr_my' => 'vajira-ṭī',
             'abbr_pts' => 'VjbT',

+ 45 - 0
api-v13/resources/lang/en/library.php

@@ -205,4 +205,49 @@ return [
     'show_missing' => 'Show missing works',
     'no_works_in_category' => 'This translation has no works in this category',
     'not_included' => 'not included',
+
+    // 三藏下载:下载页与导出文件里的文字
+    'export_uncategorized' => 'Other',
+    'export_index' => 'Contents',
+    'export_show_notes' => 'Notes',
+    'export_generated_at' => 'Exported :date',
+    'export_source' => 'Source:',
+    'export_works' => 'works',
+    'export_groups' => 'collections',
+    'export_average_progress' => 'average progress',
+    'export_search_placeholder' => 'Search by title or Pali name, e.g. dīgha',
+    'export_no_match' => 'No matching works',
+    'download_title' => 'Download',
+    'download_all' => 'Download all',
+    'download_all_title' => 'Download :name',
+    'download_all_hint' => 'Bundle the works of this translation by category. Only works that have a translation are included.',
+    'download_choose_format' => 'Choose a format',
+    'download_format_note' => 'Files are kept for 7 days. Anyone downloading the same file in that time gets it instantly.',
+    'download_hint' => 'The first time, generating takes from a few seconds to several minutes. You can leave this page: come back within 7 days, or download the same file in the mobile app, and it is ready. When the translation changes, the file is generated again.',
+    'download_format_epub' => 'EPUB e-book',
+    'download_format_epub_desc' => 'A single .epub for phones, Kindle and Apple Books, with contents and footnotes.',
+    'download_format_epub_bundle' => 'One .epub per work, grouped in folders by category.',
+    'download_format_html' => 'HTML web page',
+    'download_format_html_desc' => 'A single web page that opens in any browser, prints well and works offline.',
+    'download_format_html_bundle' => 'A searchable index.html plus one page per work.',
+    'download_format_docx' => 'Word document',
+    'download_format_docx_desc' => 'A single .docx you can edit, lay out and print.',
+    'download_format_docx_bundle' => 'One .docx per work, grouped in folders by category.',
+    'download_format_markdown' => 'Markdown',
+    'download_format_markdown_desc' => 'One .md file per chapter plus a README index. For Obsidian, Git and editing.',
+    'download_format_markdown_bundle' => 'A README.md index plus one folder per work.',
+    'download_state_ready' => 'Ready · :size · until :date',
+    'download_state_absent' => 'Needs to be generated first',
+    'download_state_queued' => 'Queued…',
+    'download_state_running' => 'Generating…',
+    'download_state_failed' => 'Generation failed, please retry',
+    'download_state_too_large' => 'Too large to export',
+    'download_button' => 'Download',
+    'download_generate_button' => 'Generate & download',
+    'download_started' => 'Download started.',
+    'download_manual' => 'Not started? Click to download',
+    'download_retry' => 'Retry',
+    'download_works_count' => ':count works',
+    'download_included_works' => 'Included works',
+    'download_back' => 'Back',
 ];

+ 6 - 0
api-v13/resources/lang/en/messages.php

@@ -91,4 +91,10 @@ return [
     'term_import_unreadable' => 'This file cannot be read. Upload an xlsx spreadsheet.',
     'term_import_header_required' => 'The first row must hold column names, including at least word and meaning.',
     'term_import_too_many' => 'At most :max rows can be imported at a time.',
+
+    // 三藏下载(/v3/tipitaka-exports)
+    'export_not_found' => 'This download does not exist or has expired. Please start it again.',
+    'export_too_large' => 'This selection is too large to export.',
+    'export_failed' => 'Generating the file failed. Please try again later.',
+    'export_offline_work_only' => 'Offline packages are only available per work.',
 ];

+ 45 - 0
api-v13/resources/lang/zh-Hans/library.php

@@ -204,4 +204,49 @@ return [
     'show_missing' => '显示未收录作品',
     'no_works_in_category' => '该译本在此分类下没有作品',
     'not_included' => '未收录',
+
+    // 三藏下载:下载页与导出文件里的文字
+    'export_uncategorized' => '其他',
+    'export_index' => '总目录',
+    'export_show_notes' => '显示注释',
+    'export_generated_at' => '导出于 :date',
+    'export_source' => '来源:',
+    'export_works' => '部作品',
+    'export_groups' => '个藏',
+    'export_average_progress' => '平均完成度',
+    'export_search_placeholder' => '搜作品名、巴利名,如 长部 / dīgha',
+    'export_no_match' => '没有匹配的作品',
+    'download_title' => '下载',
+    'download_all' => '下载全部',
+    'download_all_title' => '下载 :name',
+    'download_all_hint' => '按分类打包本译本收录的作品,只含已有译文的作品。',
+    'download_choose_format' => '选择格式',
+    'download_format_note' => '生成后保留 7 天,期间任何人下载同一份都直接拿到文件',
+    'download_hint' => '首次生成需要几秒到几分钟。可以离开本页:7 天内回来,或在手机 App 里下载同一份,都直接拿到文件。译文有更新时会自动重新生成。',
+    'download_format_epub' => 'EPUB 电子书',
+    'download_format_epub_desc' => '单个 .epub,适合手机、Kindle、Apple Books,带目录与脚注。',
+    'download_format_epub_bundle' => '每部作品一个 .epub,按分类放进文件夹。',
+    'download_format_html' => 'HTML 网页',
+    'download_format_html_desc' => '单个网页文件,浏览器打开即读,可打印,离线可用。',
+    'download_format_html_bundle' => '可搜索的 index.html 总目录,每部作品一个网页。',
+    'download_format_docx' => 'Word 文档',
+    'download_format_docx_desc' => '单个 .docx,可编辑、排版、打印。',
+    'download_format_docx_bundle' => '每部作品一个 .docx,按分类放进文件夹。',
+    'download_format_markdown' => 'Markdown',
+    'download_format_markdown_desc' => '每章一个 .md,带 README 目录。适合 Obsidian、Git、二次编辑。',
+    'download_format_markdown_bundle' => 'README.md 总目录,每部作品一个文件夹。',
+    'download_state_ready' => '已就绪 · :size · :date 前有效',
+    'download_state_absent' => '首次下载需生成',
+    'download_state_queued' => '排队中…',
+    'download_state_running' => '生成中…',
+    'download_state_failed' => '生成失败,可重试',
+    'download_state_too_large' => '范围太大,无法导出',
+    'download_button' => '下载',
+    'download_generate_button' => '生成并下载',
+    'download_started' => '已开始下载。',
+    'download_manual' => '没有自动开始?点此下载',
+    'download_retry' => '重试',
+    'download_works_count' => ':count 部作品',
+    'download_included_works' => '包含的作品',
+    'download_back' => '返回',
 ];

+ 6 - 0
api-v13/resources/lang/zh-Hans/messages.php

@@ -91,4 +91,10 @@ return [
     'term_import_unreadable' => '读不了这个文件,请上传 xlsx 格式的表格。',
     'term_import_header_required' => '表格第一行要有列名,至少包含 word 与 meaning。',
     'term_import_too_many' => '一次最多导入 :max 行。',
+
+    // 三藏下载(/v3/tipitaka-exports)
+    'export_not_found' => '这个下载不存在或已过期,请重新发起。',
+    'export_too_large' => '范围太大,无法导出。',
+    'export_failed' => '文件生成失败,请稍后重试。',
+    'export_offline_work_only' => '离线包只能按作品下载。',
 ];

+ 45 - 0
api-v13/resources/lang/zh-Hant/library.php

@@ -165,4 +165,49 @@ return [
     'course_no_history' => '暫無歷史課程',
     'course_history_title' => '歷史課程',
     'course_history_subtitle' => '已結束的公開課程,回顧往期研讀',
+
+    // 三藏下载:下载页与导出文件里的文字
+    'export_uncategorized' => '其他',
+    'export_index' => '總目錄',
+    'export_show_notes' => '顯示註釋',
+    'export_generated_at' => '匯出於 :date',
+    'export_source' => '來源:',
+    'export_works' => '部作品',
+    'export_groups' => '個藏',
+    'export_average_progress' => '平均完成度',
+    'export_search_placeholder' => '搜作品名、巴利名,如 長部 / dīgha',
+    'export_no_match' => '沒有符合的作品',
+    'download_title' => '下載',
+    'download_all' => '下載全部',
+    'download_all_title' => '下載 :name',
+    'download_all_hint' => '按分類打包本譯本收錄的作品,只含已有譯文的作品。',
+    'download_choose_format' => '選擇格式',
+    'download_format_note' => '生成後保留 7 天,期間任何人下載同一份都直接拿到檔案',
+    'download_hint' => '首次生成需要幾秒到幾分鐘。可以離開本頁:7 天內回來,或在手機 App 裡下載同一份,都直接拿到檔案。譯文有更新時會自動重新生成。',
+    'download_format_epub' => 'EPUB 電子書',
+    'download_format_epub_desc' => '單個 .epub,適合手機、Kindle、Apple Books,帶目錄與腳註。',
+    'download_format_epub_bundle' => '每部作品一個 .epub,按分類放進資料夾。',
+    'download_format_html' => 'HTML 網頁',
+    'download_format_html_desc' => '單個網頁檔案,瀏覽器打開即讀,可列印,離線可用。',
+    'download_format_html_bundle' => '可搜尋的 index.html 總目錄,每部作品一個網頁。',
+    'download_format_docx' => 'Word 文件',
+    'download_format_docx_desc' => '單個 .docx,可編輯、排版、列印。',
+    'download_format_docx_bundle' => '每部作品一個 .docx,按分類放進資料夾。',
+    'download_format_markdown' => 'Markdown',
+    'download_format_markdown_desc' => '每章一個 .md,帶 README 目錄。適合 Obsidian、Git、二次編輯。',
+    'download_format_markdown_bundle' => 'README.md 總目錄,每部作品一個資料夾。',
+    'download_state_ready' => '已就緒 · :size · :date 前有效',
+    'download_state_absent' => '首次下載需生成',
+    'download_state_queued' => '排隊中…',
+    'download_state_running' => '生成中…',
+    'download_state_failed' => '生成失敗,可重試',
+    'download_state_too_large' => '範圍太大,無法匯出',
+    'download_button' => '下載',
+    'download_generate_button' => '生成並下載',
+    'download_started' => '已開始下載。',
+    'download_manual' => '沒有自動開始?點此下載',
+    'download_retry' => '重試',
+    'download_works_count' => ':count 部作品',
+    'download_included_works' => '包含的作品',
+    'download_back' => '返回',
 ];

+ 5 - 0
api-v13/resources/lang/zh-Hant/messages.php

@@ -17,4 +17,9 @@ return [
     'sign_up_code_invalid' => '驗證碼不正確或已過期。',
     'invite_invalid' => '邀請無效或已被使用。',
 
+    // 三藏下载(/v3/tipitaka-exports)
+    'export_not_found' => '這個下載不存在或已過期,請重新發起。',
+    'export_too_large' => '範圍太大,無法匯出。',
+    'export_failed' => '檔案生成失敗,請稍後重試。',
+    'export_offline_work_only' => '離線包只能按作品下載。',
 ];

+ 9 - 0
api-v13/resources/template/epub/tipitaka.css

@@ -0,0 +1,9 @@
+/* 三藏下载 epub 的样式(pandoc --css)。阅读器大多会覆盖字体与字号,这里只定基本排版。 */
+body { font-family: "Noto Serif SC", "Noto Serif", serif; line-height: 1.8; }
+h1, h2, h3, h4, h5, h6 { line-height: 1.35; font-weight: 600; page-break-after: avoid; }
+h1 { font-size: 1.5em; margin: 1.2em 0 .8em; text-align: center; }
+h2 { font-size: 1.25em; margin: 1.4em 0 .6em; }
+h3 { font-size: 1.1em; margin: 1.2em 0 .5em; }
+p { margin: 0 0 .9em; text-align: justify; }
+section.footnotes, aside.footnote { font-size: .88em; }
+nav#toc ol { list-style: none; padding-left: 1em; }

+ 28 - 0
api-v13/resources/views/exports/tipitaka/_style.blade.php

@@ -0,0 +1,28 @@
+{{-- 三藏下载导出 HTML 的公共样式(work / index 共用),全部内联:文件要能离线单独打开。 --}}
+<style>
+:root{
+  --paper:#fdfbf7; --ink:#2a2219; --muted:#8a7760; --accent:#9a7b52; --gold:#c9a66b; --line:rgba(120,90,50,.18);
+  --card:rgba(255,255,255,.75); --note-bg:#f5deb330; --note-line:wheat; --link:#8a5a2b;
+  --serif:"Noto Serif SC","Noto Serif","Source Han Serif SC","Songti SC",Georgia,serif;
+  --sans:-apple-system,BlinkMacSystemFont,"Segoe UI","PingFang SC","Microsoft YaHei",sans-serif;
+}
+@media (prefers-color-scheme: dark){:root:not([data-theme="light"]){
+  --paper:#15120f; --ink:#e6ddcf; --muted:#a8977f; --accent:#c4a172; --line:rgba(200,170,120,.18);
+  --card:rgba(255,255,255,.04); --note-bg:rgba(139,109,56,.15); --note-line:#6b5a3e; --link:#d9b27c;
+}}
+:root[data-theme="dark"]{
+  --paper:#15120f; --ink:#e6ddcf; --muted:#a8977f; --accent:#c4a172; --line:rgba(200,170,120,.18);
+  --card:rgba(255,255,255,.04); --note-bg:rgba(139,109,56,.15); --note-line:#6b5a3e; --link:#d9b27c;
+}
+*{box-sizing:border-box}
+html{scroll-behavior:smooth}
+body{margin:0;background:var(--paper);color:var(--ink);font:15px/1.6 var(--sans)}
+a{color:var(--link);text-decoration:none}
+a:hover{text-decoration:underline}
+button{font:inherit;color:inherit}
+.topbar{position:sticky;top:0;z-index:5;display:flex;gap:12px;align-items:center;padding:10px 16px;border-bottom:1px solid var(--line);background:var(--paper);font-size:13px}
+.topbar .title{flex:1;min-width:0;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;font-family:var(--serif)}
+.topbar button{border:1px solid var(--line);background:transparent;border-radius:6px;padding:3px 10px;cursor:pointer}
+.foot{text-align:center;font-size:12px;color:var(--muted);padding:24px 16px}
+@media print{.topbar,.toc,.no-print{display:none!important}.layout{display:block!important}}
+</style>

+ 142 - 0
api-v13/resources/views/exports/tipitaka/index.blade.php

@@ -0,0 +1,142 @@
+{{-- 三藏下载:打包下载时的总目录 index.html(TipitakaExportBuilder::htmlIndex())。
+     按藏 → 分类分组列出作品,可搜索(不分大小写与变音符号)、可按藏筛选。样式与脚本全部内联,离线可用。
+     变量:$context{uid,name,lang,generated_at}、$scope{kind,title,works}、
+           $groups[藏][分类][{title,pali,progress,href}]、$averageProgress、$sourceUrl
+--}}
+<!doctype html>
+<html lang="{{ $context['lang'] }}">
+<head>
+<meta charset="utf-8">
+<meta name="viewport" content="width=device-width, initial-scale=1">
+<meta name="generator" content="WikiPāli">
+<title>{{ $scope['title'] }} · {{ $context['name'] }}</title>
+@include('exports.tipitaka._style')
+<style>
+body{background:#faf7f1}
+@media (prefers-color-scheme: dark){:root:not([data-theme="light"]) body{background:#16130f}}
+:root[data-theme="dark"] body{background:#16130f}
+.hero{position:relative;padding:48px 16px 32px;text-align:center;border-bottom:1px solid var(--line)}
+.hero .kicker{letter-spacing:.3em;font-size:12px;color:var(--accent);text-transform:uppercase}
+.hero h1{font:600 34px/1.25 var(--serif);margin:10px 0 6px}
+.hero p{margin:0;color:var(--muted)}
+.hero [data-theme-toggle]{position:absolute;right:16px;top:16px;border:1px solid var(--line);background:transparent;border-radius:6px;padding:3px 10px;cursor:pointer}
+.stats{display:flex;justify-content:center;gap:28px;margin-top:18px;flex-wrap:wrap;font-size:13px;color:var(--muted)}
+.stats b{display:block;font:600 22px var(--serif);color:var(--ink)}
+.tools{max-width:980px;margin:0 auto;padding:20px 16px 4px;display:flex;gap:10px;flex-wrap:wrap;align-items:center}
+.search{flex:1;min-width:220px;position:relative}
+.search input{width:100%;padding:10px 14px 10px 36px;border-radius:24px;border:1px solid var(--line);background:var(--card);font:inherit;color:inherit}
+.search::before{content:"⌕";position:absolute;left:14px;top:7px;font-size:18px;color:var(--accent)}
+.seg{display:flex;gap:4px;flex-wrap:wrap}
+.seg button{border:1px solid var(--line);background:transparent;border-radius:20px;padding:6px 12px;cursor:pointer;font-size:13px}
+.seg button.on{background:#6b4a26;border-color:#6b4a26;color:#fff8ec}
+main{max-width:980px;margin:0 auto;padding:8px 16px 40px}
+.pitaka{margin-top:26px}
+.pitaka>h2{font:600 20px var(--serif);display:flex;align-items:baseline;gap:10px;margin:0 0 4px;border-bottom:2px solid var(--gold);padding-bottom:6px}
+.pitaka>h2 small{font:13px var(--sans);color:var(--muted)}
+.cat{margin:16px 0 6px;font-size:13px;color:var(--accent);letter-spacing:.05em}
+.works{display:grid;grid-template-columns:repeat(auto-fill,minmax(270px,1fr));gap:10px}
+.work{display:block;padding:12px 14px;border-radius:8px;background:var(--card);border:1px solid var(--line);color:inherit;transition:transform .12s,box-shadow .12s}
+.work:hover{transform:translateY(-1px);box-shadow:0 4px 14px rgba(90,60,20,.12);text-decoration:none}
+.work .t{font:600 15px/1.35 var(--serif)}
+.work .p{font:italic 12.5px var(--serif);color:var(--accent)}
+.work .m{display:flex;align-items:center;gap:8px;margin-top:8px;font-size:12px;color:var(--muted)}
+.work .pb{flex:1;height:4px;border-radius:2px;background:var(--line);overflow:hidden}
+.work .pb i{display:block;height:100%;background:var(--gold)}
+.empty{text-align:center;color:var(--muted);padding:40px 0;display:none}
+</style>
+</head>
+<body>
+<header class="hero">
+    <button type="button" data-theme-toggle aria-label="theme">◐</button>
+    <div class="kicker">WikiPāli · Tipiṭaka</div>
+    <h1>{{ $scope['title'] }}</h1>
+    <p>{{ $context['name'] }} · {{ __('library.export_generated_at', ['date' => $context['generated_at']]) }}</p>
+    <div class="stats">
+        <div><b>{{ count($scope['works']) }}</b>{{ __('library.export_works') }}</div>
+        <div><b>{{ count($groups) }}</b>{{ __('library.export_groups') }}</div>
+        <div><b>{{ $averageProgress }}%</b>{{ __('library.export_average_progress') }}</div>
+    </div>
+</header>
+<div class="tools">
+    <div class="search"><input type="search" data-q placeholder="{{ __('library.export_search_placeholder') }}"></div>
+    @if(count($groups) > 1)
+    <div class="seg" data-seg>
+        <button type="button" class="on" data-k="">{{ __('library.all') }}</button>
+        @foreach(array_keys($groups) as $top)
+        <button type="button" data-k="{{ $top }}">{{ $top }}</button>
+        @endforeach
+    </div>
+    @endif
+</div>
+<main data-body>
+    @foreach($groups as $top => $subs)
+    <section class="pitaka" data-pitaka="{{ $top }}">
+        <h2>{{ $top }} <small>{{ array_sum(array_map('count', $subs)) }} {{ __('library.export_works') }}</small></h2>
+        @foreach($subs as $sub => $works)
+        @if($sub !== $top)
+        <div class="cat">{{ $sub }}</div>
+        @endif
+        <div class="works">
+            @foreach($works as $w)
+            <a class="work" href="{{ $w['href'] }}" data-s="{{ mb_strtolower($w['title'].' '.$w['pali'].' '.$top.' '.$sub) }}">
+                <div class="t">{{ $w['title'] }}</div>
+                @if($w['pali'] !== $w['title'])
+                <div class="p">{{ $w['pali'] }}</div>
+                @endif
+                <div class="m"><span class="pb"><i style="width: {{ $w['progress'] }}%"></i></span><span>{{ $w['progress'] }}%</span></div>
+            </a>
+            @endforeach
+        </div>
+        @endforeach
+    </section>
+    @endforeach
+</main>
+<div class="empty" data-empty>{{ __('library.export_no_match') }}</div>
+<div class="foot">{{ __('library.export_source') }} <a href="{{ $sourceUrl }}">{{ $sourceUrl }}</a></div>
+<script>
+(function () {
+    var fold = function (s) { return s.toLowerCase().normalize('NFD').replace(/[̀-ͯ]/g, ''); };
+    var input = document.querySelector('[data-q]');
+    var seg = '';
+    var cards = Array.prototype.slice.call(document.querySelectorAll('.work'));
+    cards.forEach(function (c) { c.dataset.f = fold(c.dataset.s); });
+    var apply = function () {
+        var q = fold(input.value.trim());
+        var shown = 0;
+        document.querySelectorAll('[data-pitaka]').forEach(function (section) {
+            var any = 0;
+            section.querySelectorAll('.works').forEach(function (grid) {
+                var visible = 0;
+                grid.querySelectorAll('.work').forEach(function (card) {
+                    var ok = !q || card.dataset.f.indexOf(q) !== -1;
+                    card.style.display = ok ? '' : 'none';
+                    visible += ok ? 1 : 0;
+                });
+                grid.style.display = visible ? '' : 'none';
+                var label = grid.previousElementSibling;
+                if (label && label.classList.contains('cat')) label.style.display = visible ? '' : 'none';
+                any += visible;
+            });
+            var show = any > 0 && (!seg || section.dataset.pitaka === seg);
+            section.style.display = show ? '' : 'none';
+            shown += show ? 1 : 0;
+        });
+        document.querySelector('[data-empty]').style.display = shown ? 'none' : 'block';
+    };
+    input.addEventListener('input', apply);
+    document.querySelectorAll('[data-seg] button').forEach(function (b) {
+        b.addEventListener('click', function () {
+            seg = b.dataset.k;
+            document.querySelectorAll('[data-seg] button').forEach(function (x) { x.classList.toggle('on', x === b); });
+            apply();
+        });
+    });
+    document.querySelector('[data-theme-toggle]').onclick = function () {
+        var root = document.documentElement;
+        var dark = root.dataset.theme ? root.dataset.theme === 'dark' : matchMedia('(prefers-color-scheme: dark)').matches;
+        root.dataset.theme = dark ? 'light' : 'dark';
+    };
+})();
+</script>
+</body>
+</html>

+ 105 - 0
api-v13/resources/views/exports/tipitaka/work.blade.php

@@ -0,0 +1,105 @@
+{{-- 三藏下载:一部作品的单个 HTML 文件(TipitakaExportBuilder::htmlWork())。
+     样式与脚本全部内联,离线可用。正文 $body 是 PaliContentService::readParagraph() 的 display,原样输出。
+     变量:$context{uid,name,lang,generated_at}、$work(作品 + local_title)、$toc[{id,depth,title}]、
+           $body、$indexHref(打包时指回 index.html,单独下载时为 null)、$sourceUrl
+--}}
+<!doctype html>
+<html lang="{{ $context['lang'] }}">
+<head>
+<meta charset="utf-8">
+<meta name="viewport" content="width=device-width, initial-scale=1">
+<meta name="generator" content="WikiPāli">
+<title>{{ $work['local_title'] }} · {{ $context['name'] }}</title>
+@include('exports.tipitaka._style')
+<style>
+.layout{display:grid;grid-template-columns:240px minmax(0,1fr);gap:40px;max-width:1080px;margin:0 auto;padding:24px 16px 80px}
+@media(max-width:860px){.layout{grid-template-columns:1fr}.toc{display:none}.toc.open{display:block;position:static;max-height:none}}
+.toc{position:sticky;top:60px;align-self:start;font-size:13px;max-height:calc(100vh - 80px);overflow:auto}
+.toc h4{margin:0 0 8px;font-size:12px;letter-spacing:.15em;color:var(--accent)}
+.toc a{display:block;color:inherit;padding:4px 10px;border-left:2px solid var(--line);opacity:.82}
+.toc a.d1{padding-left:22px;font-size:12.5px}
+.toc a.d2{padding-left:34px;font-size:12px}
+.toc a:hover,.toc a.on{opacity:1;border-color:var(--gold);color:var(--link);text-decoration:none}
+article{font:17px/1.95 var(--serif);max-width:42em;counter-reset:sn}
+.titlepage{text-align:center;padding:16px 0 36px;border-bottom:1px solid var(--line);margin-bottom:28px}
+.titlepage h1{font-size:30px;margin:0;line-height:1.3}
+.titlepage .pali{font-style:italic;color:var(--accent);margin-top:4px}
+.titlepage .meta{font:13px var(--sans);color:var(--muted);margin-top:12px}
+article h1,article h2,article h3,article h4,article h5,article h6{line-height:1.35;margin:1.8em 0 .6em;scroll-margin-top:64px;font-weight:600}
+article h1{font-size:26px}article h2{font-size:23px}article h3{font-size:19px}article h4,article h5,article h6{font-size:17px}
+article div.sentence{display:inline}
+article .para-block{margin:0 0 1em;text-align:justify}
+article .origin{color:#8b2a1e}
+article input.margin-toggle,article .anno-fn-toggle{display:none}
+article label.sidenote-number{cursor:pointer;counter-increment:sn}
+article label.sidenote-number::after{content:"[" counter(sn) "]";font:11px var(--sans);color:var(--link);vertical-align:.5em;margin:0 1px}
+article .sidenote,article .marginnote{display:none}
+article .margin-toggle:checked + .sidenote,article .margin-toggle:checked + .marginnote{display:block;margin:.6em 0;padding:6px 10px;border:1px solid var(--note-line);border-radius:8px;background:var(--note-bg);font-size:14px;line-height:1.65}
+article.notes-open .sidenote,article.notes-open .marginnote{display:block;margin:.6em 0;padding:6px 10px;border:1px solid var(--note-line);border-radius:8px;background:var(--note-bg);font-size:14px;line-height:1.65}
+article .anno-footnotes{margin:.4em 0 1em}
+article .anno-footnote{margin:.3em 0;padding:5px 10px;font:13.5px/1.6 var(--sans);color:var(--muted);border:1px solid var(--line);border-radius:6px}
+article .anno-fn-label{display:block;cursor:pointer}
+article .anno-jump{display:none}
+</style>
+</head>
+<body>
+<div class="topbar">
+    @if($indexHref)
+    <a href="{{ $indexHref }}">‹ {{ __('library.export_index') }}</a>
+    @endif
+    <span class="title">{{ $work['local_title'] }} · {{ $context['name'] }}</span>
+    <button type="button" data-toc-toggle class="no-print">{{ __('library.toc') }}</button>
+    <button type="button" data-notes-toggle class="no-print">{{ __('library.export_show_notes') }}</button>
+    <button type="button" data-font class="no-print">A±</button>
+    <button type="button" data-theme-toggle class="no-print" aria-label="theme">◐</button>
+</div>
+<div class="layout">
+    <nav class="toc" data-toc>
+        <h4>{{ __('library.toc') }}</h4>
+        @foreach($toc as $item)
+        <a href="#{{ $item['id'] }}" class="d{{ min(2, max(0, $item['depth'])) }}">{{ $item['title'] }}</a>
+        @endforeach
+    </nav>
+    <article data-article>
+        <div class="titlepage">
+            <h1>{{ $work['local_title'] }}</h1>
+            @if($work['title'] !== $work['local_title'])
+            <div class="pali">{{ $work['title'] }}</div>
+            @endif
+            <div class="meta">{{ $context['name'] }} · {{ __('library.export_generated_at', ['date' => $context['generated_at']]) }}</div>
+        </div>
+        {!! $body !!}
+    </article>
+</div>
+<div class="foot">{{ __('library.export_source') }} <a href="{{ $sourceUrl }}">{{ $sourceUrl }}</a></div>
+<script>
+(function () {
+    var q = function (s) { return document.querySelector(s); };
+    q('[data-toc-toggle]').onclick = function () { q('[data-toc]').classList.toggle('open'); };
+    q('[data-notes-toggle]').onclick = function () { q('[data-article]').classList.toggle('notes-open'); };
+    var size = 17;
+    q('[data-font]').onclick = function () { size = size >= 21 ? 15 : size + 2; q('[data-article]').style.fontSize = size + 'px'; };
+    q('[data-theme-toggle]').onclick = function () {
+        var root = document.documentElement;
+        var dark = root.dataset.theme ? root.dataset.theme === 'dark' : matchMedia('(prefers-color-scheme: dark)').matches;
+        root.dataset.theme = dark ? 'light' : 'dark';
+    };
+    var links = document.querySelectorAll('[data-toc] a');
+    if (!('IntersectionObserver' in window) || !links.length) return;
+    var byId = {};
+    links.forEach(function (a) { byId[a.getAttribute('href').slice(1)] = a; });
+    var observer = new IntersectionObserver(function (entries) {
+        entries.forEach(function (e) {
+            if (!e.isIntersecting) return;
+            links.forEach(function (a) { a.classList.remove('on'); });
+            byId[e.target.id].classList.add('on');
+        });
+    }, { rootMargin: '0px 0px -70% 0px' });
+    Object.keys(byId).forEach(function (id) {
+        var el = document.getElementById(id);
+        if (el) observer.observe(el);
+    });
+})();
+</script>
+</body>
+</html>

+ 3 - 0
api-v13/resources/views/library/tipitaka/channels/category.blade.php

@@ -45,6 +45,9 @@
                 <a class="btn btn-sm" href="{{ request()->fullUrlWithQuery(['all' => $showAll ? null : 1]) }}">
                     {{ $showAll ? __('library.only_included') : __('library.show_missing') }}
                 </a>
+                <a class="btn btn-sm btn-primary" href="{{ route('library.tipitaka.channels.download', ['channel' => $channelInfo['uid']]) }}">
+                    <i class="ti ti-download me-1"></i>{{ __('library.download_all') }}
+                </a>
             </div>
         </div>
 

+ 239 - 0
api-v13/resources/views/library/tipitaka/download.blade.php

@@ -0,0 +1,239 @@
+{{-- resources/views/library/tipitaka/download.blade.php
+     下载页(TipitakaDownloadController):一部作品($mode = work),或整个 channel 打包($mode = channel,只有「全部」一种范围)。
+     四种格式各一张卡片。已就绪的直接下载;其余点击后调 POST /api/v3/tipitaka-exports 发起,轮询状态,
+     就绪后自动下载(同时给一个手动下载的链接兜底)。
+     变量:$mode、$channelInfo、$request(POST 的 channel / work)、$formats[{key,name,description,state}]、$backUrl;
+           work:$book(bookCard() + pali_title / updated_at);
+           channel:$groups[分类路径 => [{title,progress,url}]]
+--}}
+@extends('layouts.library')
+
+@section('title', ($mode === 'work' ? $book['title'] : $channelInfo['name']) . ' · ' . __('library.download_title') . ' · ' . __('library.site_name'))
+
+@push('styles')
+@vite('resources/css/modules/tipitaka.css')
+@endpush
+
+@section('breadcrumb')
+<li class="breadcrumb-item"><a href="{{ route('library.home') }}">{{ __('library.home') }}</a></li>
+<li class="breadcrumb-item"><a href="{{ route('library.tipitaka.index') }}">{{ __('library.tipitaka') }}</a></li>
+<li class="breadcrumb-item"><a href="{{ route('library.tipitaka.channels.index') }}">{{ __('library.channels') }}</a></li>
+<li class="breadcrumb-item"><a href="{{ route('library.tipitaka.channels.show', ['channel' => $channelInfo['uid']]) }}">{{ $channelInfo['name'] }}</a></li>
+@if($mode === 'work')
+<li class="breadcrumb-item"><a href="{{ $backUrl }}">{{ $book['title'] }}</a></li>
+@endif
+<li class="breadcrumb-item active">{{ __('library.download_title') }}</li>
+@endsection
+
+@section('content')
+<div class="page-body">
+    <div class="container-xl tipitaka-download">
+
+        <div class="wiki-card tipitaka-download__head">
+            @if($mode === 'work')
+            <x-ui.book-cover
+                :image="$book['cover']"
+                :gradient="$book['cover_gradient']"
+                :title="$book['pali_title']"
+                :subtitle="$book['subTitle'] ?? ''"
+                size="md"
+                :style3d="false"
+                class="tipitaka-download__cover" />
+            <div class="tipitaka-download__info">
+                <h1 class="tipitaka-download__title">{{ $book['title'] }}</h1>
+                @if($book['pali_title'] !== $book['title'])
+                <div class="tipitaka-work-pali">{{ $book['pali_title'] }}</div>
+                @endif
+                <div class="tipitaka-download__meta">
+                    <span>{{ __('library.channel') }} <a href="{{ route('library.tipitaka.channels.show', ['channel' => $channelInfo['uid']]) }}">{{ $channelInfo['name'] }}</a></span>
+                    <span>{{ $book['language'] }}</span>
+                    @if($book['progress'] !== null)
+                    <span>{{ __('library.progress') }} {{ $book['progress'] }}%</span>
+                    @endif
+                    @if(!empty($book['updated_at']))
+                    <span>{{ __('library.updated') }} {{ $book['updated_at'] }}</span>
+                    @endif
+                </div>
+            </div>
+            @else
+            <div class="tipitaka-download__info">
+                <h1 class="tipitaka-download__title">{{ __('library.download_all_title', ['name' => $channelInfo['name']]) }}</h1>
+                <div class="tipitaka-download__meta"><span>{{ __('library.download_all_hint') }}</span></div>
+            </div>
+            @endif
+            <a href="{{ $backUrl }}" class="btn btn-sm tipitaka-download__back">‹ {{ __('library.download_back') }}</a>
+        </div>
+
+        <h2 class="tipitaka-download__section">
+            {{ __('library.download_choose_format') }}
+            <small>{{ __('library.download_format_note') }}</small>
+        </h2>
+
+        @php
+        $i18n = [
+            'ready' => __('library.download_state_ready'),
+            'queued' => __('library.download_state_queued'),
+            'running' => __('library.download_state_running'),
+            'failed' => __('library.download_state_failed'),
+            'download' => __('library.download_button'),
+            'retry' => __('library.download_retry'),
+        ];
+        @endphp
+        <div class="tipitaka-download__formats" data-download data-request='@json($request)' data-i18n='@json($i18n)'>
+            @foreach($formats as $format)
+            @php
+            $state = $format['state'];
+            $ready = $state['status'] === 'ready';
+            @endphp
+            <div class="wiki-card tipitaka-download__format" data-format="{{ $format['key'] }}"
+                data-state="{{ $ready ? 'ready' : ($state['too_large'] ?? false ? 'too_large' : 'absent') }}"
+                @if($ready) data-url="{{ $state['download_url'] }}" @endif>
+                <div class="tipitaka-download__format-top">
+                    <span class="tipitaka-download__icon tipitaka-download__icon--{{ $format['key'] }}">{{ $format['key'] === 'markdown' ? 'MD' : strtoupper($format['key']) }}</span>
+                    <div>
+                        <h3>{{ $format['name'] }}</h3>
+                        <p>{{ $format['description'] }}</p>
+                    </div>
+                </div>
+                <div class="tipitaka-download__file"><i class="ti ti-file-zip"></i> {{ $state['filename'] }}</div>
+                <div class="tipitaka-download__foot">
+                    <span class="tipitaka-download__state" data-state-text>
+                        <span class="tipitaka-download__dot"></span>
+                        @if($ready)
+                        {{ __('library.download_state_ready', ['size' => \Illuminate\Support\Number::fileSize($state['size'], 1), 'date' => substr((string) $state['expires_at'], 0, 10)]) }}
+                        @elseif($state['too_large'] ?? false)
+                        {{ __('library.download_state_too_large') }}
+                        @else
+                        {{ __('library.download_state_absent') }}
+                        @endif
+                    </span>
+                    <button type="button" class="btn btn-sm {{ $ready ? 'btn-primary' : '' }}" data-start @disabled($state['too_large'] ?? false)>
+                        <i class="ti ti-download me-1"></i>{{ $ready ? __('library.download_button') : __('library.download_generate_button') }}
+                    </button>
+                </div>
+                <div class="tipitaka-download__progress" data-progress hidden>
+                    <div class="tipitaka-download__progress-text"><span data-progress-message></span><span data-progress-percent></span></div>
+                    <div class="progress progress-sm"><div class="progress-bar" data-progress-bar style="width: 0%"></div></div>
+                </div>
+                <a class="tipitaka-download__manual" data-manual hidden>{{ __('library.download_manual') }}</a>
+            </div>
+            @endforeach
+        </div>
+
+        <div class="tipitaka-download__hint"><i class="ti ti-info-circle"></i><span>{{ __('library.download_hint') }}</span></div>
+
+        @if($mode === 'channel')
+        <h2 class="tipitaka-download__section">
+            {{ __('library.download_included_works') }}
+            <small>{{ __('library.download_works_count', ['count' => array_sum(array_map('count', $groups))]) }}</small>
+        </h2>
+        <div class="wiki-card tipitaka-download__works">
+            @foreach($groups as $label => $works)
+            <details @if($loop->first) open @endif>
+                <summary><b>{{ $label }}</b><span>{{ __('library.download_works_count', ['count' => count($works)]) }}</span></summary>
+                <ul>
+                    @foreach($works as $work)
+                    <li><a href="{{ $work['url'] }}">{{ $work['title'] }}</a><span>{{ $work['progress'] }}%</span></li>
+                    @endforeach
+                </ul>
+            </details>
+            @endforeach
+        </div>
+        @endif
+    </div>
+</div>
+@endsection
+
+@push('scripts')
+<script>
+    (function() {
+        const root = document.querySelector('[data-download]');
+        if (!root) return;
+        const request = JSON.parse(root.dataset.request);
+        const t = JSON.parse(root.dataset.i18n);
+        const fill = (text, values) => text.replace(/:(\w+)/g, (m, k) => values[k] ?? m);
+        const fileSize = (bytes) => bytes >= 1048576 ? (bytes / 1048576).toFixed(1) + ' MB' : Math.max(1, Math.round(bytes / 1024)) + ' KB';
+        const json = async (response) => {
+            const body = await response.json().catch(() => ({}));
+            if (!response.ok) throw new Error(body.detail || response.statusText);
+            return body.data;
+        };
+
+        const setState = (card, cls, text) => {
+            const el = card.querySelector('[data-state-text]');
+            el.className = 'tipitaka-download__state tipitaka-download__state--' + cls;
+            el.innerHTML = '<span class="tipitaka-download__dot"></span>';
+            el.append(text);
+        };
+        const showProgress = (card, data) => {
+            card.querySelector('[data-progress]').hidden = false;
+            const percent = Math.round((data.progress || 0) * 100);
+            card.querySelector('[data-progress-bar]').style.width = percent + '%';
+            card.querySelector('[data-progress-percent]').textContent = data.status === 'running' ? percent + '%' : '';
+            card.querySelector('[data-progress-message]').textContent = data.status === 'running' ? (data.message || t.running) : t.queued;
+        };
+        // 浏览器下载附件不会离开本页;被拦下时还有手动链接
+        const deliver = (card, data, auto) => {
+            card.dataset.state = 'ready';
+            card.dataset.url = data.download_url;
+            card.querySelector('[data-progress]').hidden = true;
+            setState(card, 'ready', fill(t.ready, { size: fileSize(data.size), date: (data.expires_at || '').slice(0, 10) }));
+            const button = card.querySelector('[data-start]');
+            button.disabled = false;
+            button.classList.add('btn-primary');
+            button.lastChild.textContent = t.download;
+            if (auto) {
+                const manual = card.querySelector('[data-manual]');
+                manual.href = data.download_url;
+                manual.hidden = false;
+                window.location.href = data.download_url;
+            }
+        };
+        const fail = (card, message) => {
+            card.querySelector('[data-progress]').hidden = true;
+            setState(card, 'failed', message || t.failed);
+            const button = card.querySelector('[data-start]');
+            button.disabled = false;
+            button.lastChild.textContent = t.retry;
+        };
+
+        const poll = async (card, id, attempt) => {
+            try {
+                const data = await json(await fetch('/api/v3/tipitaka-exports/' + id, { headers: { Accept: 'application/json' } }));
+                if (data.status === 'ready') return deliver(card, data, true);
+                if (data.status === 'failed') return fail(card, data.message);
+                showProgress(card, data);
+            } catch (e) {
+                return fail(card, e.message);
+            }
+            // 1s, 2s, 3s,之后每 5 秒
+            setTimeout(() => poll(card, id, attempt + 1), [1000, 2000, 3000][attempt] ?? 5000);
+        };
+
+        root.addEventListener('click', async (event) => {
+            const button = event.target.closest('[data-start]');
+            if (!button) return;
+            const card = button.closest('[data-format]');
+            if (card.dataset.state === 'ready' && card.dataset.url) {
+                window.location.href = card.dataset.url;
+                return;
+            }
+            button.disabled = true;
+            card.querySelector('[data-manual]').hidden = true;
+            try {
+                const data = await json(await fetch('/api/v3/tipitaka-exports', {
+                    method: 'POST',
+                    headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
+                    body: JSON.stringify({ ...request, format: card.dataset.format }),
+                }));
+                if (data.status === 'ready') return deliver(card, data, true);
+                card.dataset.state = 'busy';
+                showProgress(card, data);
+                setTimeout(() => poll(card, data.id, 0), 1000);
+            } catch (e) {
+                fail(card, e.message);
+            }
+        });
+    })();
+</script>
+@endpush

+ 2 - 3
api-v13/resources/views/library/tipitaka/show.blade.php

@@ -49,11 +49,10 @@
                         <i class="ti ti-book-2 me-1"></i>
                         {{ __('library.read_online') }}
                     </a>
-                    {{-- FIXME: 下载还没有实现 --}}
-                    <button class="btn btn-outline-secondary w-100" disabled>
+                    <a href="{{ route('library.tipitaka.channels.work.download', ['channel' => $book['channel']['uid'], 'sn' => $book['id']]) }}" class="btn btn-outline-secondary w-100">
                         <i class="ti ti-download me-1"></i>
                         {{ __('library.download') }}
-                    </button>
+                    </a>
                 </div>
 
             </div>

+ 1 - 0
api-v13/routes/api.php

@@ -356,6 +356,7 @@ Route::prefix('v3')->as('v3.')->middleware(NegotiateLocale::class)->group(functi
     require __DIR__.'/v3/channel.php';
     require __DIR__.'/v3/term.php';
     require __DIR__.'/v3/nissaya.php';
+    require __DIR__.'/v3/markup.php';
     require __DIR__.'/v3/group.php';
     require __DIR__.'/v3/interaction.php';
     require __DIR__.'/v3/auth.php';

+ 16 - 0
api-v13/routes/v3/markup.php

@@ -0,0 +1,16 @@
+<?php
+
+/*
+|--------------------------------------------------------------------------
+| v3 · markup —— 正文源码的渲染
+|--------------------------------------------------------------------------
+|
+| 由 routes/api.php 的 v3 组 require 进来,前缀已在那边加好。
+|
+*/
+
+use App\Http\Controllers\V3\MarkupPreviewController;
+use Illuminate\Support\Facades\Route;
+
+// 源码预览:不写库,要登录
+Route::post('markup-previews', MarkupPreviewController::class)->middleware('auth.v3')->name('markup-previews.store');

+ 15 - 0
api-v13/routes/v3/tipitaka.php

@@ -23,6 +23,8 @@ use App\Http\Controllers\V3\PaliWordSuggestionController;
 use App\Http\Controllers\V3\TipitakaChannelController;
 use App\Http\Controllers\V3\TipitakaChapterChannelController;
 use App\Http\Controllers\V3\TipitakaDiscussionController;
+use App\Http\Controllers\V3\TipitakaExportController;
+use App\Http\Controllers\V3\TipitakaExportFileController;
 use App\Http\Controllers\V3\TipitakaPageNumberController;
 use App\Http\Controllers\V3\TipitakaParagraphChannelController;
 use App\Http\Controllers\V3\TipitakaReadingController;
@@ -90,3 +92,16 @@ Route::get('tipitaka-word-paragraphs', [TipitakaWordParagraphController::class,
 Route::get('tipitaka-page-numbers/{page}', TipitakaPageNumberController::class)
     ->whereNumber('page')
     ->name('tipitaka-page-numbers.show');
+
+// 三藏下载:一部作品 / 一个分类 / 整个 channel 导出成文件,排队生成、存 Redis 7 天。
+// id 是 40 位十六进制的内容指纹;文件只认签名链接(相对签名,反代下不受域名影响)
+Route::post('tipitaka-exports', [TipitakaExportController::class, 'store'])
+    ->middleware('throttle:tipitaka-exports')
+    ->name('tipitaka-exports.store');
+Route::get('tipitaka-exports/{export}', [TipitakaExportController::class, 'show'])
+    ->where('export', '[0-9a-f]{40}')
+    ->name('tipitaka-exports.show');
+Route::get('tipitaka-exports/{export}/file', TipitakaExportFileController::class)
+    ->where('export', '[0-9a-f]{40}')
+    ->middleware('signed:relative')
+    ->name('tipitaka-exports.file');

+ 4 - 0
api-v13/routes/web.php

@@ -11,6 +11,7 @@ use App\Http\Controllers\Library\HomeController;
 use App\Http\Controllers\Library\SearchController;
 use App\Http\Controllers\Library\TipitakaChannelController;
 use App\Http\Controllers\Library\TipitakaController;
+use App\Http\Controllers\Library\TipitakaDownloadController;
 use App\Http\Controllers\Library\WikiController;
 use App\Http\Controllers\PageIndexController;
 use App\Http\Controllers\WbwAnalysisController;
@@ -79,6 +80,9 @@ Route::prefix('library')->name('library.')->group(function () {
         Route::get('/category/{id?}', [TipitakaChannelController::class, 'category'])->whereNumber('id')->name('category');
         Route::get('/work/{sn}', [BookController::class, 'show'])->whereNumber('sn')->name('work');
         Route::get('/work/{sn}/read', [BookController::class, 'readWork'])->whereNumber('sn')->name('work.read');
+        // 下载页:一部作品;或整个 channel 打包
+        Route::get('/work/{sn}/download', [TipitakaDownloadController::class, 'work'])->whereNumber('sn')->name('work.download');
+        Route::get('/download', [TipitakaDownloadController::class, 'channel'])->name('download');
         Route::get('/chapter/{chapter}', [BookController::class, 'read'])
             ->where('chapter', '\d+-\d+')->name('chapter');
     });

+ 64 - 0
api-v13/tests/Feature/MarkupPreviewV3Test.php

@@ -0,0 +1,64 @@
+<?php
+
+use App\Models\Channel;
+use App\Models\DhammaTerm;
+use Illuminate\Foundation\Testing\RefreshDatabase;
+use Illuminate\Support\Str;
+
+uses(RefreshDatabase::class);
+
+/*
+ * POST /v3/markup-previews:把还没保存的源码渲染成节点树(模板生成器的预览)。
+ * 这里断言的是形状而非契约(spectator 未安装,见 v3-resource skill 第 3 步)。
+ */
+
+beforeEach(function () {
+    $this->me = makeStudio('preview-me');
+    $this->channel = makeChannel($this->me, 'preview channel');
+});
+
+it('renders the source into a node tree, resolving templates against the given channel', function () {
+    (new DhammaTerm)->forceFill([
+        'id' => random_int(1, PHP_INT_MAX), 'guid' => (string) Str::uuid(), 'word' => 'dhamma', 'word_en' => 'dhamma',
+        'meaning' => '法', 'language' => 'zh-Hans', 'channal' => $this->channel, 'owner' => $this->me,
+        'editor_id' => 0, 'create_time' => time() * 1000, 'modify_time' => time() * 1000,
+    ])->save();
+
+    $body = $this->postJson('/api/v3/markup-previews', [
+        'content' => '{{term|dhamma}}',
+        'channels' => [$this->channel],
+    ], authHeader($this->me))->assertOk()->json('data.body');
+
+    expect($body[0])->toMatchArray(['type' => 'tpl', 'name' => 'term'])
+        ->and($body[0]['props'])->toMatchArray(['word' => 'dhamma', 'meaning' => '法', 'channel' => $this->channel]);
+});
+
+it('renders without channels, and keeps unknown templates as their source', function () {
+    $body = $this->postJson('/api/v3/markup-previews', [
+        'content' => "{{v|url=https://example.com/a.mp4|style=card|title=视频}}\n\n{{nope|x}}",
+        'content_type' => 'markdown-e2',
+    ], authHeader($this->me))->assertOk()->json('data.body');
+
+    expect(json_encode($body))->toContain('"name":"video"')->toContain('"name":"unknown"');
+});
+
+it('requires login', function () {
+    $this->postJson('/api/v3/markup-previews', ['content' => 'x'])->assertUnauthorized();
+});
+
+it('rejects a missing content, a bad content type and a non-uuid channel', function () {
+    $this->postJson('/api/v3/markup-previews', [
+        'content_type' => 'html', 'channels' => ['nope'],
+    ], authHeader($this->me))->assertUnprocessable()->assertJsonValidationErrors(['content', 'content_type', 'channels.0']);
+});
+
+it('refuses a private channel the user cannot read, and 404s an unknown one', function () {
+    $other = makeStudio('preview-other');
+    $private = makeChannel($other, 'private channel');
+    Channel::where('uid', $private)->update(['status' => 10]);
+
+    $this->postJson('/api/v3/markup-previews', ['content' => 'x', 'channels' => [$private]], authHeader($this->me))
+        ->assertForbidden();
+    $this->postJson('/api/v3/markup-previews', ['content' => 'x', 'channels' => [(string) Str::uuid()]], authHeader($this->me))
+        ->assertNotFound();
+});

+ 246 - 0
api-v13/tests/Feature/ReadingCacheTest.php

@@ -0,0 +1,246 @@
+<?php
+
+use App\Facades\RedisCache;
+use App\Models\Discussion;
+use App\Models\PaliText;
+use App\Services\PaliContentService;
+use App\Services\ReadingIndexService;
+use App\Services\V3\PaliTextService;
+use Illuminate\Foundation\Testing\RefreshDatabase;
+use Illuminate\Support\Facades\DB;
+use Illuminate\Support\Str;
+
+uses(RefreshDatabase::class);
+
+/**
+ * 阅读缓存(api-v13/documents/reading-cache-plan.html):
+ * L0 pali_texts 按书缓存、A1 整块批量渲染、L1 段落成品、L2 段号 / 书号索引。
+ */
+function makePaliRow(int $book, int $para, int $level, int $chapterLen = 0, string $class = 'bodytext', string $toc = ''): void
+{
+    (new PaliText)->forceFill([
+        'book' => $book,
+        'paragraph' => $para,
+        'level' => $level,
+        'class' => $class,
+        'toc' => $toc,
+        'text' => '',
+        'html' => '',
+        'lenght' => 10 * $para,
+        'chapter_len' => $chapterLen,
+        'chapter_strlen' => 100,
+        'parent' => 0,
+        'pcd_book_id' => 0,
+        'uid' => (string) Str::uuid(),
+    ])->save();
+}
+
+function makeReadingNote(string $sentenceUid, string $type, string $content, ?int $score = null): Discussion
+{
+    $discussion = new Discussion;
+    $discussion->forceFill([
+        'res_id' => $sentenceUid,
+        'res_type' => 'sentence',
+        'type' => $type,
+        'title' => $content,
+        'content' => $content,
+        'content_type' => 'markdown',
+        'editor_uid' => makeStudio('note-'.Str::random(6)),
+        'score' => $score,
+        'pos_start' => 0,
+        'pos_end' => 1,
+    ])->save();
+
+    return $discussion;
+}
+
+/**
+ * 计数这段代码查了几次库。
+ */
+function countQueries(Closure $callback): int
+{
+    DB::flushQueryLog();
+    DB::enableQueryLog();
+    $callback();
+    $count = count(DB::getQueryLog());
+    DB::disableQueryLog();
+
+    return $count;
+}
+
+it('caches pali_texts per book and serves headings, levels and classes without queries', function () {
+    makePaliRow(9301, 1, 1, 5, 'book', 'Book');
+    makePaliRow(9301, 2, 2, 4, 'chapter', 'Chapter');
+    makePaliRow(9301, 3, 100, 0, 'gatha1');
+
+    app(PaliTextService::class)->headings(9301);
+    app(PaliTextService::class)->paragraphs(9301, 1, 3);
+
+    // 新实例(没有进程内记忆)也只读缓存
+    $service = new PaliTextService;
+    expect(countQueries(function () use ($service) {
+        expect($service->headingLevel(9301, 2))->toBe(2)
+            ->and($service->headingLevel(9301, 3))->toBe(0)
+            ->and($service->paragraph(9301, 3))->toBe(['level' => 100, 'class' => 'gatha1', 'length' => 30])
+            ->and($service->chapterRange(9301, 2))->toBe([2, 5])
+            ->and($service->chapterRange(9301, 3))->toBe([3, 3])
+            ->and($service->bookStart(9301, 3))->toMatchArray(['para' => 1, 'toc' => 'Book']);
+    }))->toBe(0);
+
+    expect($service->chapterRange(9301, 99))->toBeNull();
+});
+
+it('renders a block exactly like rendering each paragraph alone', function () {
+    $channel = makeChannel(makeStudio('cache-owner'), 'cache channel');
+    makePaliRow(9302, 1, 2, 3, 'chapter');
+    foreach ([1, 2, 3] as $para) {
+        $sentence = makeSentence($channel, 9302, $para, 1, "first of {$para}");
+        makeSentence($channel, 9302, $para, 2, "second of {$para}");
+        makeReadingNote($sentence->uid, 'note', "note of {$para}");
+    }
+    // 只有第 2 段有评估:第 2 段的另一句补灰色对勾,别的段不补(按段算,不是按整块)
+    $assessed = makeSentence($channel, 9302, 2, 3, 'assessed');
+    makeReadingNote($assessed->uid, 'assessment', 'ok', 90);
+
+    $service = app(PaliContentService::class);
+    $block = $service->readParagraphs(9302, [1, 2, 3], $channel);
+
+    foreach ([1, 2, 3] as $para) {
+        PaliContentService::forgetParagraph(9302, $para, $channel);
+    }
+    foreach ([1, 2, 3] as $para) {
+        expect($service->readParagraph(9302, $para, $channel))->toBe($block[$para]);
+    }
+    expect($block[1]['display'])->toContain('<h2>')->toContain('note of 1')->toContain('anno-footnotes')
+        ->and($block[2]['display'])->toContain('anno-assessment')
+        ->and($block[1]['display'])->not->toContain('anno-assessment')
+        ->and($block[3]['display'])->not->toContain('anno-assessment');
+});
+
+it('renders a block with a fixed number of queries however many paragraphs it has', function () {
+    $channel = makeChannel(makeStudio('cache-owner'), 'cache channel');
+    $render = function (int $book, int $count) use ($channel) {
+        foreach (range(1, $count) as $para) {
+            $sentence = makeSentence($channel, $book, $para, 1, "text {$para}");
+            makeReadingNote($sentence->uid, 'note', "note {$para}");
+        }
+        app(PaliTextService::class)->headings($book);
+        app(PaliTextService::class)->paragraphs($book, 1, $count);
+
+        return countQueries(fn () => app(PaliContentService::class)->readParagraphs($book, range(1, $count), $channel));
+    };
+
+    expect($render(9303, 20))->toBe($render(9304, 2));
+});
+
+it('serves cached paragraphs without touching the database', function () {
+    $channel = makeChannel(makeStudio('cache-owner'), 'cache channel');
+    makeSentence($channel, 9305, 1, 1, 'cached');
+    $url = "/api/v3/tipitaka-reading/{$channel}?book=9305";
+    $first = $this->getJson($url)->assertOk()->json();
+
+    // 鉴权中间件等外围查询之外,正文、候选、进度都不查库
+    $queries = countQueries(fn () => expect($this->getJson($url)->assertOk()->json())->toBe($first));
+    $baseline = countQueries(fn () => $this->getJson("/api/v3/tipitaka-reading/{$channel}?book=9305&para=999")->assertOk());
+    expect($queries)->toBe($baseline);
+});
+
+it('refreshes the paragraph index only when the set of translated paragraphs changes', function () {
+    $channel = makeChannel(makeStudio('cache-owner'), 'cache channel');
+    $first = makeSentence($channel, 9306, 1, 1, 'one');
+    $index = fn () => new ReadingIndexService;
+    expect($index()->paragraphs($channel, 9306))->toBe([1]);
+
+    $sentence = makeSentence($channel, 9306, 3, 1, 'three');
+    expect($index()->paragraphs($channel, 9306))->toBe([1, 3]);
+
+    // 只改内容:段落成品删掉,索引不动(不重建)
+    app(PaliContentService::class)->readParagraph(9306, 1, $channel);
+    $first->forceFill(['content' => 'one again', 'strlen' => 9])->save();
+    expect(RedisCache::has(PaliContentService::paragraphCacheKey(9306, 1, $channel, 'html')))->toBeFalse()
+        ->and(countQueries(fn () => expect($index()->paragraphs($channel, 9306))->toBe([1, 3])))->toBe(0);
+
+    // strlen 变成 0 就不算有译文
+    $sentence->forceFill(['content' => '', 'strlen' => 0])->save();
+    expect($index()->paragraphs($channel, 9306))->toBe([1]);
+
+    // 批注不碰索引
+    makeReadingNote($first->uid, 'note', 'n');
+    expect(countQueries(fn () => $index()->paragraphs($channel, 9306)))->toBe(0);
+});
+
+it('keeps the book index in step with books gaining or losing translations', function () {
+    $channel = makeChannel(makeStudio('cache-owner'), 'cache channel');
+    makeSentence($channel, 9307, 1, 1, 'a');
+    expect((new ReadingIndexService)->books($channel))->toBe([9307]);
+
+    $other = makeSentence($channel, 9308, 1, 1, 'b');
+    expect((new ReadingIndexService)->books($channel))->toBe([9307, 9308]);
+
+    // 搬去别的书:旧书少了、新书多了
+    $other->forceFill(['book_id' => 9309])->save();
+    expect((new ReadingIndexService)->books($channel))->toBe([9307, 9309]);
+
+    $other->delete();
+    expect((new ReadingIndexService)->books($channel))->toBe([9307]);
+});
+
+it('walks a whole channel across books with the cursor', function () {
+    $channel = makeChannel(makeStudio('cache-owner'), 'cache channel');
+    makeSentence($channel, 9310, 1, 1, 'a');
+    makeSentence($channel, 9310, 2, 1, 'b');
+    makeSentence($channel, 9311, 5, 1, 'c');
+
+    $page = $this->getJson("/api/v3/tipitaka-reading/{$channel}?page_size=2")->assertOk();
+    expect(array_column($page->json('data'), 'para'))->toBe([1, 2])
+        ->and($page->json('meta.next_cursor'))->toBe('9310-2');
+
+    $page = $this->getJson("/api/v3/tipitaka-reading/{$channel}?page_size=2&after=9310-2")->assertOk();
+    expect($page->json('data.0'))->toMatchArray(['book' => 9311, 'para' => 5])
+        ->and($page->json('meta.next_cursor'))->toBeNull();
+});
+
+it('clears the paragraph cache only after the transaction commits', function () {
+    $channel = makeChannel(makeStudio('cache-owner'), 'cache channel');
+    $sentence = makeSentence($channel, 9313, 1, 1, 'before');
+    app(PaliContentService::class)->readParagraph(9313, 1, $channel);
+    $key = PaliContentService::paragraphCacheKey(9313, 1, $channel, 'html');
+
+    DB::transaction(function () use ($sentence, $key) {
+        $sentence->forceFill(['content' => 'after'])->save();
+        expect(RedisCache::has($key))->toBeTrue();
+    });
+    expect(RedisCache::has($key))->toBeFalse();
+});
+
+it('splits a book into flat chapters, each running up to the next heading', function () {
+    makePaliRow(9320, 1, 1, 10);
+    makePaliRow(9320, 2, 2, 5);
+    makePaliRow(9320, 4, 3, 3);
+    makePaliRow(9320, 7, 2, 4);
+
+    $service = app(PaliTextService::class);
+    expect($service->flatChapters(9320))->toBe([1 => 1, 2 => 3, 4 => 6, 7 => 10])
+        ->and($service->flatChapterOf(9320, 5))->toBe(4)
+        ->and($service->flatChapterOf(9320, 10))->toBe(7)
+        ->and($service->flatChapterOf(9320, 11))->toBeNull();
+});
+
+it('caches the reader chapters and drops only the chapter whose sentence changed', function () {
+    $channel = makeChannel(makeStudio('cache-owner'), 'cache channel');
+    makePaliRow(9321, 1, 2, 2);
+    makePaliRow(9321, 3, 2, 2);
+    makeSentence($channel, 9321, 1, 1, 'chapter one');
+    $changed = makeSentence($channel, 9321, 4, 1, 'chapter two');
+
+    $service = app(PaliContentService::class);
+    $display = $service->readChapters(9321, 1, 4, $channel);
+    expect($display)->toContain('chapter one')->toContain('chapter two')
+        ->and($display)->toBe(implode('', array_column($service->readParagraphs(9321, [1, 2, 3, 4], $channel), 'display')))
+        ->and(countQueries(fn () => $service->readChapters(9321, 1, 4, $channel)))->toBe(0);
+
+    $changed->forceFill(['content' => 'chapter two edited'])->save();
+    expect(RedisCache::has(PaliContentService::chapterCacheKey(9321, 1, $channel, 'html')))->toBeTrue()
+        ->and(RedisCache::has(PaliContentService::chapterCacheKey(9321, 3, $channel, 'html')))->toBeFalse()
+        ->and($service->readChapters(9321, 1, 4, $channel))->toContain('chapter two edited');
+});

+ 41 - 0
api-v13/tests/Feature/RedisCacheTest.php

@@ -131,6 +131,30 @@ test('increment 从 0 开始累加,返回新值', function () {
         ->and(RedisCache::get('c'))->toBe(6);
 });
 
+test('二进制原样往返,长度与区间读取正确', function () {
+    $bytes = "\x00\xff\x80PK\x03\x04".random_bytes(1000);
+    RedisCache::putBinary('/bin/a', $bytes, 60);
+
+    expect(RedisCache::getBinary('/bin/a'))->toBe($bytes)
+        ->and(RedisCache::binaryLength('/bin/a'))->toBe(strlen($bytes))
+        ->and(RedisCache::getBinaryRange('/bin/a', 2, 5))->toBe(substr($bytes, 2, 4))
+        ->and(RedisCache::getBinaryRange('/bin/a', 1000, 9999))->toBe(substr($bytes, 1000))
+        ->and(RedisCache::getBinaryRange('/bin/a', 99999, 100000))->toBe('');
+});
+
+test('二进制 key 不存在时读到 null,TTL <= 0 等同 forget', function () {
+    RedisCache::putBinary('/bin/b', 'x', 60);
+    RedisCache::putBinary('/bin/b', 'y', 0);
+
+    expect(RedisCache::getBinary('/bin/b'))->toBeNull()
+        ->and(RedisCache::binaryLength('/bin/b'))->toBeNull()
+        ->and(RedisCache::getBinaryRange('/bin/b', 0, 10))->toBe('');
+});
+
+test('非 UTF-8 字节用 put 存不了,必须走 putBinary', function () {
+    expect(fn () => RedisCache::put('/bin/c', "\xff\xfe"))->toThrow(JsonException::class);
+});
+
 /*
 | 第二部分:契约。连真实 Redis Cluster(mint.redis_cluster),证明 key 名带前缀、
 | 值是 JSON、整数是纯文本(ai-translate 用 int() 读 /task/{id}/pointer)、TTL 与写值一条命令落地,
@@ -209,3 +233,20 @@ test('不存在的 key 读到 null / 默认值,forget 返回 false', function
         ->and($cache->get('missing', 'd'))->toBe('d')
         ->and($cache->forget('missing'))->toBeFalse();
 })->skip(fn () => ! realRedisAvailable(), '没有可用的 Redis Cluster');
+
+test('二进制在集群里原样落地、带 TTL,可按区间读', function () {
+    $cache = new RedisCacheService(prefix: redisCacheTestPrefix());
+    $bytes = random_bytes(3 * 1024 * 1024);
+    $cache->putBinary('bin', $bytes, 60);
+
+    $chunks = '';
+    for ($offset = 0; $offset < strlen($bytes); $offset += 1048576) {
+        $chunks .= $cache->getBinaryRange('bin', $offset, $offset + 1048575);
+    }
+
+    expect(rawRedisCluster()->get(redisCacheTestPrefix().'/bin'))->toBe($bytes)
+        ->and(rawRedisCluster()->ttl(redisCacheTestPrefix().'/bin'))->toBeGreaterThan(0)->toBeLessThanOrEqual(60)
+        ->and($cache->binaryLength('bin'))->toBe(strlen($bytes))
+        ->and($chunks)->toBe($bytes)
+        ->and($cache->binaryLength('missing-bin'))->toBeNull();
+})->skip(fn () => ! realRedisAvailable(), '没有可用的 Redis Cluster');

+ 353 - 0
api-v13/tests/Feature/TipitakaExportV3Test.php

@@ -0,0 +1,353 @@
+<?php
+
+use App\Models\BookTitle;
+use App\Models\Channel;
+use App\Models\PaliText;
+use App\Models\ProgressChapter;
+use App\Models\Tag;
+use App\Models\TagMap;
+use App\Services\V3\TipitakaExportQueue;
+use App\Services\V3\TipitakaExportService;
+use Illuminate\Foundation\Testing\RefreshDatabase;
+use Illuminate\Support\Str;
+
+/*
+| 三藏下载 /v3/tipitaka-exports。这里断言的是形状而非契约(spectator 未安装)。
+| 生成在测试里同步调 TipitakaExportService::run(),队列换成 mock,不连 RabbitMQ;
+| 文件进的是 RedisCacheFake(TestCase 已换好)。
+*/
+
+uses(RefreshDatabase::class);
+
+function exportPaliText(int $book, int $paragraph, int $level, int $chapterLen, string $toc = ''): PaliText
+{
+    $row = new PaliText;
+    $row->forceFill([
+        'book' => $book, 'paragraph' => $paragraph, 'level' => $level, 'class' => '', 'toc' => $toc,
+        'text' => '', 'html' => '', 'pcd_book_id' => 0, 'chapter_len' => $chapterLen, 'chapter_strlen' => 100,
+        'uid' => (string) Str::uuid(),
+    ])->save();
+
+    return $row;
+}
+
+function exportProgress(string $channel, int $book, int $para, float $progress, ?string $title = null): void
+{
+    (new ProgressChapter)->forceFill([
+        'id' => random_int(1, PHP_INT_MAX), 'uid' => (string) Str::uuid(), 'book' => $book, 'para' => $para,
+        'lang' => 'zh-Hans', 'channel_id' => $channel, 'progress' => $progress, 'title' => $title,
+        'all_trans' => 0, 'public' => 0,
+    ])->save();
+}
+
+/**
+ * 一部作品 sn 9100 = book 9100 的 3–102 段(两章:4、50),归入长部 › 戒蕴品(分类 3)。
+ * channel 收录了它,有作品标题、两个章标题和带脚注的正文。
+ *
+ * @return array{channel: string, owner: string, sn: int}
+ */
+function exportFixture(): array
+{
+    $root = exportPaliText(9100, 3, 1, 100, 'Sīlakkhandhavaggapāḷi');
+    exportPaliText(9100, 4, 2, 46, '1. Brahmajālasuttaṃ');
+    exportPaliText(9100, 50, 2, 53, '2. Sāmaññaphalasuttaṃ');
+    foreach (['sutta', 'dīghanikāya', 'sīlakkhandhavagga', 'pāḷi'] as $name) {
+        $tag = Tag::where('name', $name)->first();
+        if (! $tag) {
+            $tag = new Tag;
+            $tag->forceFill(['id' => (string) Str::uuid(), 'name' => $name, 'color' => 0, 'owner_id' => (string) Str::uuid()])->save();
+        }
+        (new TagMap)->forceFill(['id' => (string) Str::uuid(), 'table_name' => 'pali_texts', 'anchor_id' => $root->uid, 'tag_id' => $tag->id])->save();
+    }
+    (new BookTitle)->forceFill(['sn' => 9100, 'book' => 9100, 'paragraph' => 3, 'title' => 'dīghanikāyapāḷi'])->save();
+
+    $owner = makeStudio('export-owner');
+    $channel = makeChannel($owner, 'export channel');
+    exportProgress($channel, 9100, 3, 0.4, '戒蕴品');
+    makeSentence($channel, 9100, 3, 1, '戒蕴品');
+    makeSentence($channel, 9100, 4, 1, '梵网经');
+    makeSentence($channel, 9100, 5, 1, '如是我闻{{note|第一条注}}。');
+    makeSentence($channel, 9100, 5, 2, '一时佛住{{note|第二条注}}。');
+    makeSentence($channel, 9100, 50, 1, '沙门果经');
+    makeSentence($channel, 9100, 51, 1, '尔时国王{{note|第三条注}}。');
+
+    return ['channel' => $channel, 'owner' => $owner, 'sn' => 9100];
+}
+
+/**
+ * 换掉队列,返回收到的 [id, bulk] 列表。
+ */
+function fakeExportQueue(): ArrayObject
+{
+    $pushed = new ArrayObject;
+    test()->mock(TipitakaExportQueue::class, function ($mock) use ($pushed) {
+        $mock->shouldReceive('push')->andReturnUsing(function (string $id, bool $bulk) use ($pushed) {
+            $pushed[] = [$id, $bulk];
+        });
+    });
+
+    return $pushed;
+}
+
+/**
+ * 发起并同步生成,返回就绪后的 data。
+ *
+ * @param  array<string, mixed>  $body
+ * @return array<string, mixed>
+ */
+function exportReady(array $body): array
+{
+    $id = test()->postJson('/api/v3/tipitaka-exports', $body)->assertStatus(202)->json('data.id');
+    app(TipitakaExportService::class)->run($id);
+
+    return test()->postJson('/api/v3/tipitaka-exports', $body)->assertOk()->json('data');
+}
+
+/**
+ * zip 字节 → [条目名 => 内容]
+ *
+ * @return array<string, string>
+ */
+function unzipExport(string $bytes): array
+{
+    $path = tempnam(sys_get_temp_dir(), 'export');
+    file_put_contents($path, $bytes);
+    $zip = new ZipArchive;
+    $zip->open($path);
+    $files = [];
+    for ($i = 0; $i < $zip->numFiles; $i++) {
+        $files[$zip->getNameIndex($i)] = $zip->getFromIndex($i);
+    }
+    $zip->close();
+    unlink($path);
+
+    return $files;
+}
+
+it('queues a work export and does not queue the same one twice', function () {
+    $pushed = fakeExportQueue();
+    ['channel' => $channel, 'sn' => $sn] = exportFixture();
+
+    $response = $this->postJson('/api/v3/tipitaka-exports', ['channel' => $channel, 'work' => $sn, 'format' => 'html'])
+        ->assertStatus(202)
+        ->assertHeader('Retry-After', '2');
+    expect($response->json('data'))->toMatchArray([
+        'status' => 'queued', 'format' => 'html', 'title' => '戒蕴品', 'works' => 1, 'size' => null, 'download_url' => null,
+    ])->and($response->json('data.id'))->toMatch('/^[0-9a-f]{40}$/')
+        ->and($response->json('data.filename'))->toBe('戒蕴品-export channel-html.zip');
+
+    $this->postJson('/api/v3/tipitaka-exports', ['channel' => $channel, 'work' => $sn, 'format' => 'html'])->assertStatus(202);
+
+    expect($pushed->getArrayCopy())->toBe([[$response->json('data.id'), false]]);
+});
+
+it('generates an html work export and serves it through the signed link', function () {
+    fakeExportQueue();
+    ['channel' => $channel, 'sn' => $sn] = exportFixture();
+
+    $data = exportReady(['channel' => $channel, 'work' => $sn, 'format' => 'html']);
+    expect($data['status'])->toBe('ready')
+        ->and($data['size'])->toBeInt()->toBeGreaterThan(0)
+        ->and($data['download_url'])->toStartWith("/api/v3/tipitaka-exports/{$data['id']}/file?expires=");
+
+    $this->getJson("/api/v3/tipitaka-exports/{$data['id']}")->assertOk()->assertJsonPath('data.status', 'ready');
+
+    $file = $this->get($data['download_url'])
+        ->assertOk()
+        ->assertHeader('Content-Type', 'application/zip')
+        ->assertHeader('ETag', '"'.$data['id'].'"')
+        ->assertHeader('Accept-Ranges', 'bytes');
+    expect($file->headers->get('Content-Disposition'))->toContain("filename*=utf-8''");
+    $bytes = $file->streamedContent();
+    expect(strlen($bytes))->toBe($data['size']);
+
+    $files = unzipExport($bytes);
+    expect(array_keys($files))->toBe(['戒蕴品.html']);
+    expect($files['戒蕴品.html'])
+        ->toContain('<!doctype html>')
+        ->toContain('梵网经')
+        ->toContain('如是我闻')
+        ->toContain('href="#para-4"');
+
+    // 断点续传与条件请求
+    $part = $this->get($data['download_url'], ['Range' => 'bytes=10-19'])->assertStatus(206)
+        ->assertHeader('Content-Range', "bytes 10-19/{$data['size']}");
+    expect($part->streamedContent())->toBe(substr($bytes, 10, 10));
+    $this->get($data['download_url'], ['Range' => 'bytes=999999999-'])->assertStatus(416);
+    $this->get($data['download_url'], ['If-None-Match' => '"'.$data['id'].'"'])->assertStatus(304);
+});
+
+it('rejects the file link without a valid signature', function () {
+    fakeExportQueue();
+    ['channel' => $channel, 'sn' => $sn] = exportFixture();
+    $data = exportReady(['channel' => $channel, 'work' => $sn, 'format' => 'html']);
+
+    $this->get("/api/v3/tipitaka-exports/{$data['id']}/file")->assertForbidden();
+    $this->get($data['download_url'].'0')->assertForbidden();
+});
+
+it('splits markdown by chapter and renumbers footnotes per file', function () {
+    fakeExportQueue();
+    ['channel' => $channel, 'sn' => $sn] = exportFixture();
+    $data = exportReady(['channel' => $channel, 'work' => $sn, 'format' => 'markdown']);
+
+    $files = unzipExport($this->get($data['download_url'])->streamedContent());
+    expect(array_keys($files))->toEqualCanonicalizing(['戒蕴品/01-梵网经.md', '戒蕴品/02-沙门果经.md', '戒蕴品/README.md']);
+    expect($files['戒蕴品/README.md'])->toContain('# 戒蕴品')->toContain('(<01-梵网经.md>)');
+    // 两句各自从 [^1] 起编号,合进一章后是 1、2
+    expect($files['戒蕴品/01-梵网经.md'])
+        ->toStartWith("# 梵网经\n")
+        ->toContain('如是我闻[^1]')
+        ->toContain('一时佛住[^2]')
+        ->toContain('[^1]: 第一条注')
+        ->toContain('[^2]: 第二条注');
+    expect($files['戒蕴品/02-沙门果经.md'])->toContain('尔时国王[^1]')->toContain('[^1]: 第三条注');
+});
+
+it('gives single-work epub and docx as the file itself', function (string $format, string $type, string $magic) {
+    fakeExportQueue();
+    ['channel' => $channel, 'sn' => $sn] = exportFixture();
+    $data = exportReady(['channel' => $channel, 'work' => $sn, 'format' => $format]);
+
+    expect($data['filename'])->toBe("戒蕴品-export channel.{$format}")
+        ->and($data['content_type'])->toBe($type);
+    $bytes = $this->get($data['download_url'])->assertOk()->assertHeader('Content-Type', $type)->streamedContent();
+    // epub 与 docx 本身都是 zip 容器
+    expect(substr($bytes, 0, 2))->toBe($magic);
+})->with([
+    'epub' => ['epub', 'application/epub+zip', 'PK'],
+    'docx' => ['docx', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'PK'],
+])->skip(fn () => trim((string) shell_exec('command -v pandoc')) === '', 'pandoc 不可用');
+
+it('builds the mobile offline package as gzip-encoded ndjson, only per work', function () {
+    fakeExportQueue();
+    ['channel' => $channel, 'sn' => $sn] = exportFixture();
+
+    $this->postJson('/api/v3/tipitaka-exports', ['channel' => $channel, 'format' => 'offline'])
+        ->assertStatus(422)
+        ->assertJsonValidationErrors('format');
+
+    $data = exportReady(['channel' => $channel, 'work' => $sn, 'format' => 'offline']);
+    expect($data['content_type'])->toBe('application/x-ndjson')
+        ->and($data['filename'])->toBe('戒蕴品-export channel.ndjson');
+    $file = $this->get($data['download_url'])
+        ->assertHeader('Content-Type', 'application/x-ndjson')
+        ->assertHeader('Content-Encoding', 'gzip');
+    $lines = array_map(fn ($l) => json_decode($l, true), explode("\n", trim(gzdecode($file->streamedContent()))));
+
+    expect($lines[0])->toMatchArray(['type' => 'header', 'format' => 1, 'id' => $data['id'], 'channel' => $channel, 'sn' => $sn, 'book' => 9100, 'para' => 3, 'paragraphs' => 5])
+        ->and(end($lines))->toBe(['type' => 'end', 'count' => 5])
+        ->and($lines[1])->toMatchArray(['type' => 'para', 'book' => 9100, 'para' => 3]);
+    // 与阅读接口的 display 一字不差
+    $display = $this->getJson("/api/v3/tipitaka-reading/{$channel}?book=9100&para=5")->json('data.0.display');
+    expect(collect($lines)->firstWhere('para', 5)['html'])->toBe($display);
+});
+
+it('bundles the whole channel with an index page on the bulk queue', function () {
+    $pushed = fakeExportQueue();
+    ['channel' => $channel] = exportFixture();
+
+    $data = exportReady(['channel' => $channel, 'format' => 'html']);
+    expect($pushed[0][1])->toBeTrue()
+        ->and($data['filename'])->toBe('export channel-html.zip');
+
+    $files = unzipExport($this->get($data['download_url'])->streamedContent());
+    expect(array_keys($files))->toEqualCanonicalizing(['export channel-html/index.html', 'export channel-html/works/9100-戒蕴品.html']);
+    expect($files['export channel-html/index.html'])->toContain('href="works/9100-%E6%88%92%E8%95%B4%E5%93%81.html"')->toContain('data-q');
+    expect($files['export channel-html/works/9100-戒蕴品.html'])->toContain('href="../index.html"');
+});
+
+it('keeps private channels to people who can read them', function () {
+    $pushed = fakeExportQueue();
+    ['channel' => $channel, 'owner' => $owner, 'sn' => $sn] = exportFixture();
+    Channel::where('uid', $channel)->update(['status' => 10]);
+
+    $this->postJson('/api/v3/tipitaka-exports', ['channel' => $channel, 'work' => $sn, 'format' => 'html'])->assertForbidden();
+    $this->postJson('/api/v3/tipitaka-exports', ['channel' => $channel, 'work' => $sn, 'format' => 'html'], authHeader(makeStudio('stranger')))->assertForbidden();
+    $id = $this->postJson('/api/v3/tipitaka-exports', ['channel' => $channel, 'work' => $sn, 'format' => 'html'], authHeader($owner))
+        ->assertStatus(202)->json('data.id');
+
+    // 状态也只给看得见的人
+    $this->getJson("/api/v3/tipitaka-exports/{$id}")->assertForbidden();
+    $this->getJson("/api/v3/tipitaka-exports/{$id}", authHeader($owner))->assertOk();
+    expect($pushed)->toHaveCount(1);
+});
+
+it('validates the request', function () {
+    fakeExportQueue();
+    ['channel' => $channel, 'sn' => $sn] = exportFixture();
+
+    $this->postJson('/api/v3/tipitaka-exports', [])->assertStatus(422)->assertJsonValidationErrors(['channel', 'format']);
+    $this->postJson('/api/v3/tipitaka-exports', ['channel' => $channel, 'format' => 'pdf'])->assertStatus(422)->assertJsonValidationErrors('format');
+    $this->postJson('/api/v3/tipitaka-exports', ['channel' => $channel, 'work' => $sn, 'category' => 3, 'format' => 'html'])
+        ->assertStatus(422)->assertJsonValidationErrors('work');
+    // 没有收录的作品、不存在的 channel
+    $this->postJson('/api/v3/tipitaka-exports', ['channel' => $channel, 'work' => 1, 'format' => 'html'])->assertNotFound();
+    $this->postJson('/api/v3/tipitaka-exports', ['channel' => (string) Str::uuid(), 'work' => $sn, 'format' => 'html'])->assertNotFound();
+    $this->getJson('/api/v3/tipitaka-exports/'.str_repeat('a', 40))->assertNotFound();
+});
+
+it('refuses selections larger than the limit', function () {
+    $pushed = fakeExportQueue();
+    ['channel' => $channel, 'sn' => $sn] = exportFixture();
+    config(['mint.tipitaka_export.max_source_chars' => 5]);
+
+    $this->postJson('/api/v3/tipitaka-exports', ['channel' => $channel, 'work' => $sn, 'format' => 'html'])
+        ->assertStatus(422)
+        ->assertJsonPath('type', fn ($type) => str_ends_with($type, 'export-too-large'));
+    expect($pushed)->toHaveCount(0);
+});
+
+it('marks the export failed when the file is too big, and retries on the next request', function () {
+    $pushed = fakeExportQueue();
+    ['channel' => $channel, 'sn' => $sn] = exportFixture();
+    config(['mint.tipitaka_export.max_file_bytes' => 10]);
+
+    $id = $this->postJson('/api/v3/tipitaka-exports', ['channel' => $channel, 'work' => $sn, 'format' => 'html'])->json('data.id');
+    app(TipitakaExportService::class)->run($id);
+
+    $this->getJson("/api/v3/tipitaka-exports/{$id}")->assertOk()->assertJsonPath('data.status', 'failed');
+    $this->postJson('/api/v3/tipitaka-exports', ['channel' => $channel, 'work' => $sn, 'format' => 'html'])
+        ->assertStatus(202)->assertJsonPath('data.status', 'queued');
+    expect($pushed)->toHaveCount(2);
+});
+
+it('shows the library download pages', function () {
+    fakeExportQueue();
+    ['channel' => $channel, 'sn' => $sn] = exportFixture();
+    exportReady(['channel' => $channel, 'work' => $sn, 'format' => 'epub']);
+
+    $this->get("/library/tipitaka/channels/{$channel}/work/{$sn}")
+        ->assertOk()
+        ->assertSee("/library/tipitaka/channels/{$channel}/work/{$sn}/download", false);
+
+    $page = $this->get("/library/tipitaka/channels/{$channel}/work/{$sn}/download")->assertOk();
+    $page->assertSee('data-format="epub"', false)
+        ->assertSee('data-format="markdown"', false)
+        ->assertDontSee('data-format="offline"', false)
+        ->assertSee('/api/v3/tipitaka-exports/', false);
+    expect(substr_count($page->getContent(), 'data-state="ready"'))->toBe(1);
+
+    $this->get("/library/tipitaka/channels/{$channel}/download")->assertOk()->assertSee('戒蕴品');
+    // 打包只有「全部」,没有按藏 / 分类的切换
+    $this->get("/library/tipitaka/channels/{$channel}/download")->assertDontSee('tipitaka-pill', false);
+    $this->get("/library/tipitaka/channels/{$channel}/work/1/download")->assertNotFound();
+})->skip(fn () => ! file_exists(public_path('build/manifest.json')), '需要先 npm run build');
+
+it('finds the work by book and paragraph for clients that only know coordinates', function () {
+    fakeExportQueue();
+    ['channel' => $channel, 'sn' => $sn] = exportFixture();
+
+    $bySn = $this->postJson('/api/v3/tipitaka-exports', ['channel' => $channel, 'work' => $sn, 'format' => 'offline'])->json('data.id');
+    // 作品里的任一段都指向同一份(id 相同)
+    $this->postJson('/api/v3/tipitaka-exports', ['channel' => $channel, 'book' => 9100, 'para' => 51, 'format' => 'offline'])
+        ->assertStatus(202)
+        ->assertJsonPath('data.id', $bySn);
+
+    $this->postJson('/api/v3/tipitaka-exports', ['channel' => $channel, 'book' => 9100, 'format' => 'offline'])
+        ->assertStatus(422)->assertJsonValidationErrors('para');
+    $this->postJson('/api/v3/tipitaka-exports', ['channel' => $channel, 'book' => 9100, 'para' => 3, 'work' => $sn, 'format' => 'offline'])
+        ->assertStatus(422)->assertJsonValidationErrors('work');
+    // 不在任何作品里的段
+    $this->postJson('/api/v3/tipitaka-exports', ['channel' => $channel, 'book' => 9100, 'para' => 999, 'format' => 'offline'])->assertNotFound();
+});

+ 7 - 3
api-v13/tests/Feature/TipitakaReadingRenderTest.php

@@ -4,6 +4,7 @@ use App\Facades\RedisCache;
 use App\Models\PaliText;
 use App\Models\Sentence;
 use App\Services\PaliContentService;
+use App\Services\V3\PaliTextService;
 use Illuminate\Foundation\Testing\RefreshDatabase;
 use Illuminate\Support\Str;
 
@@ -32,9 +33,10 @@ it('renders every sentence of a paragraph wrapped in divs', function () {
     // 默认只输出 display
     expect($data)->not->toHaveKey('sentences');
     expect($data['display'])
-        ->toContain("<div id='para-1' class='translation' data-para='1'>")
-        ->toContain("<div class='sentence' data-sid='9001-1-1-1'>")
-        ->toContain("<div class='sentence' data-sid='9001-1-2-2'>")
+        // 段落 class 后面拼 pali_texts.class,这里为空,所以允许末尾空白
+        ->toMatch("/<div id='para-1' class='translation\\s*' data-para='1'>/")
+        ->toContain("<div class='sentence' lang='zh-Hans' data-sid='9001-1-1-1'>")
+        ->toContain("<div class='sentence' lang='zh-Hans' data-sid='9001-1-2-2'>")
         ->toContain("<div class='para-block'>");
 });
 
@@ -51,6 +53,8 @@ it('wraps a chapter title paragraph in a heading', function () {
         'pcd_book_id' => 0,
         'uid' => (string) Str::uuid(),
     ])->save();
+    // pali_texts 按书缓存;生产上只有导入命令改它,导入后同样要 forgetBook()
+    app(PaliTextService::class)->forgetBook(9001);
 
     $display = $this->getJson("/api/v3/tipitaka-reading/{$channel}?book=9001&para=1")
         ->assertOk()

+ 55 - 4
dashboard-test/src/tests/term.spec.ts

@@ -22,7 +22,7 @@ const submit = async (page: Page, method: 'POST' | 'PATCH') => {
   const saved = page.waitForResponse(
     (r) => /\/api\/v3\/(channels\/[^/]+\/terms|terms\/[^/?]+)$/.test(new URL(r.url()).pathname) && r.request().method() === method,
   );
-  await modal(page).getByRole('button', { name: /提 *交/ }).click();
+  await modal(page).getByRole('button', { name: /^保\s*存/ }).click();
   return saved;
 };
 
@@ -54,10 +54,13 @@ test('channel 的术语:新建、编辑、并发修改提示、删除', async
       await expect(modal(page)).toBeVisible();
       await field(page, '词头').locator('input').fill(word);
       await field(page, '意思').locator('input').fill('测试释义');
-      await field(page, '所属版本').count(); // 版本下拉已预选本版本
+      await field(page, '注解').locator('textarea').fill('第一段。\n\n{{category|e2e分类}}');
+      // 版本、语言、质量、正文格式、重定向在「设置」页签
+      await modal(page).getByRole('tab', { name: '设置' }).click();
+      await expect(field(page, '所属版本')).toBeVisible(); // 版本下拉已预选本版本
       await field(page, '质量').locator('.ant-select').click();
       await page.locator('.ant-select-dropdown:visible .ant-select-item-option').filter({ hasText: '草稿' }).click();
-      await field(page, '注解').locator('textarea').fill('第一段。\n\n{{category|e2e分类}}');
+      await expect(modal(page).getByRole('button', { name: /^提\s*交$|^重\s*置$/ })).toHaveCount(0);
       const res = await submit(page, 'POST');
       expect(res.status()).toBe(201);
       const data = (await res.json()).data;
@@ -83,9 +86,53 @@ test('channel 的术语:新建、编辑、并发修改提示、删除', async
       await shot(page, '03-edited');
     });
 
+    await test.step('3b. 编辑页:右上角取消 / 保存,脏文档提示,另存为弹出版本选择', async () => {
+      await page.goto(`workspace/term/${termId}/edit`, { waitUntil: 'networkidle' });
+      const meaning = page.locator('.ant-form-item').filter({ has: page.locator('label', { hasText: /^意思$/ }) }).locator('input');
+      await expect(meaning).toHaveValue('改过的释义');
+      // 没改就取消:直接回预览
+      await page.getByRole('button', { name: /^取\s*消$/ }).click();
+      await expect(page).toHaveURL(new RegExp(`/workspace/term/${termId}$`));
+
+      // 从预览页点「编辑」站内进入,这样后退是路由跳转而不是整页离开
+      await page.getByText(/^编\s*辑$/).first().click();
+      await expect(page).toHaveURL(/\/edit$/);
+      await expect(meaning).toHaveValue('改过的释义');
+      await meaning.fill('在页面上改的');
+      // 改了再取消:提示保存,选「继续编辑」留在原页
+      await page.getByRole('button', { name: /^取\s*消$/ }).click();
+      const confirm = page.locator('.ant-modal-confirm:not(.ant-zoom-leave)');
+      await expect(confirm).toContainText('有未保存的修改');
+      await confirm.getByRole('button', { name: '继续编辑' }).click();
+      await expect(page).toHaveURL(/\/edit$/);
+      // 浏览器后退也被拦下
+      await page.goBack();
+      await expect(confirm).toContainText('有未保存的修改');
+      await confirm.getByRole('button', { name: '继续编辑' }).click();
+      await expect(page).toHaveURL(/\/edit$/);
+
+      // 另存为:下拉里点「另存为」弹出版本选择,取消不保存
+      await page.locator('.ant-space-compact .ant-btn-icon-only').click();
+      await page.locator('.ant-dropdown:visible .ant-dropdown-menu-item').filter({ hasText: '另存为' }).click();
+      const saveAs = page.locator('.ant-modal:visible').filter({ hasText: '另存为' });
+      await expect(saveAs.locator('label', { hasText: '所属版本' })).toBeVisible();
+      await shot(page, '03b-save-as');
+      await saveAs.getByRole('button', { name: /^取\s*消$/ }).click();
+      await expect(saveAs).toHaveCount(0);
+
+      // 保存:回到预览
+      const saved = page.waitForResponse((r) => r.url().endsWith(`/api/v3/terms/${termId}`) && r.request().method() === 'PATCH');
+      await page.getByRole('button', { name: /^保\s*存/ }).click();
+      expect((await saved).status()).toBe(200);
+      await expect(page).toHaveURL(new RegExp(`/workspace/term/${termId}$`));
+      await page.goto(`workspace/channel/${channel}`, { waitUntil: 'networkidle' });
+      await page.getByRole('tab', { name: 'term' }).click();
+      await expect(pane(page).locator('.ant-table-row').filter({ hasText: '在页面上改的' })).toBeVisible();
+    });
+
     await test.step('4. 编辑期间被别人改过:提示 412,不覆盖', async () => {
       await pane(page).locator('.ant-table-row').filter({ hasText: word }).getByText('编辑').click();
-      await expect(field(page, '意思').locator('input')).toHaveValue('改过的释义');
+      await expect(field(page, '意思').locator('input')).toHaveValue('在页面上改的');
       // 别人(这里用同一账号的另一个请求)先改了一次
       const fresh = (await call(request, 'GET', `/v3/terms/${termId}`)).body.data;
       const other = await call(request, 'PATCH', `/v3/terms/${termId}`, { meaning: '别人改的' }, 'user', { 'If-Match': fresh.etag });
@@ -97,7 +144,11 @@ test('channel 的术语:新建、编辑、并发修改提示、删除', async
       await expect(page.getByText(/被别人改过/).first()).toBeVisible();
       expect((await call(request, 'GET', `/v3/terms/${termId}`)).body.data.meaning).toBe('别人改的');
       await shot(page, '04-conflict');
+      // 没保存成功、表单还是脏的:Esc(同 ×)先提示,选「不保存」才关
       await page.keyboard.press('Escape');
+      const confirm = page.locator('.ant-modal-confirm:not(.ant-zoom-leave)');
+      await expect(confirm).toContainText('有未保存的修改');
+      await confirm.getByRole('button', { name: '不保存' }).click();
       await expect(modal(page)).toHaveCount(0);
     });
 

+ 72 - 0
dashboard-test/src/tests/tpl-builder.spec.ts

@@ -0,0 +1,72 @@
+import { test, expect } from '@playwright/test';
+import { collect } from '../lib/collect.js';
+
+/**
+ * 模板生成器(components/tpl-builder,后端 Markup/Templates 的全部可手写模板):
+ * 从文章阅读工具栏的「获取引用模版」打开,article 页签按这篇文章预填;切到其它模板填参数,代码随之变化,
+ * 预览走 v3 /markup-previews(后端渲染,与阅读页一致)。
+ */
+test('文章「获取引用模版」:预填 article 模板,切换模板生成代码并预览', async ({ page }) => {
+  const log = collect(page);
+  const list = page.waitForResponse((r) => /\/api\/v2\/article\?/.test(r.url()));
+  await page.goto('workspace/article', { waitUntil: 'networkidle' });
+  const rows = (await (await list).json()).data?.rows ?? [];
+  if (rows.length === 0) test.skip(true, '测试账号没有文章');
+  // 打开第一篇文章,阅读工具栏「更多」→「获取引用模版」
+  await page.goto(`workspace/article/${rows[0].uid}`, { waitUntil: 'networkidle' });
+  await page.getByRole('img', { name: 'more' }).first().click();
+  const preview1 = page.waitForResponse((r) => r.url().includes('/api/v3/markup-previews'));
+  await page.getByRole('menuitem', { name: '获取引用模版' }).click();
+
+  const dialog = page.getByRole('dialog').filter({ hasText: '模板生成器' });
+  await expect(dialog).toBeVisible();
+  const code = dialog.locator('textarea[readonly]');
+
+  // 弹窗不超出浏览器;换模板时修改区高度不变(内容多的 article 与内容少的 quality 同高)
+  const viewport = page.viewportSize()!.height;
+  const panelHeight = async () => (await dialog.locator('.tpl-builder-panel').boundingBox())!.height;
+
+  // article:按入口预填 type 与 id
+  await expect(code).toHaveValue(/^\{\{article\|type=article\|id=[0-9a-f-]{36}/);
+  expect((await preview1).status()).toBe(200);
+  await page.waitForTimeout(500); // 等弹窗的打开动画结束再量
+  const box = (await dialog.boundingBox())!;
+  expect(box.y + box.height).toBeLessThanOrEqual(viewport);
+  const articleHeight = await panelHeight();
+
+  // quality:缺省 pending,改成 featured,预览出标签
+  await dialog.getByRole('menuitem', { name: /quality/ }).click();
+  await expect(code).toHaveValue('{{quality|pending}}');
+  expect(await panelHeight()).toBe(articleHeight);
+  await dialog.locator('.ant-select').first().click();
+  const featured = page.waitForResponse(
+    (r) => r.url().includes('/api/v3/markup-previews') && (r.request().postData() ?? '').includes('featured'),
+  );
+  await page.locator('.ant-select-item-option', { hasText: 'featured' }).click();
+  await expect(code).toHaveValue('{{quality|featured}}');
+  const res = await featured;
+  expect(res.status()).toBe(200);
+  const body = (await res.json()).data.body;
+  expect(JSON.stringify(body)).toContain('"name":"quality"');
+  await expect(dialog.locator('.ant-tag').last()).toBeVisible();
+
+  // note:正文放第一个位置参数,其余写名字
+  await dialog.getByRole('menuitem', { name: /note/ }).click();
+  await dialog.locator('textarea:not([readonly])').first().fill('脚注正文 a=b');
+  await dialog.getByRole('textbox').nth(1).fill('*');
+  await expect(code).toHaveValue('{{note|脚注正文 a=b|trigger=*}}');
+
+  // mermaid:生成围栏
+  await dialog.getByRole('menuitem', { name: /mermaid/ }).click();
+  const mermaid = page.waitForResponse(
+    (r) => r.url().includes('/api/v3/markup-previews') && (r.request().postData() ?? '').includes('mermaid'),
+  );
+  await dialog.locator('textarea:not([readonly])').first().fill('graph LR\n  A --> B');
+  await expect(code).toHaveValue('```mermaid\ngraph LR\n  A --> B\n```');
+  expect(JSON.stringify((await (await mermaid).json()).data.body)).toContain('"name":"mermaid"');
+  // mermaid 异步渲染出的图(不是图标的 svg)
+  await expect(dialog.locator('svg[aria-roledescription]')).toBeVisible();
+
+  await page.screenshot({ path: 'testlog/assets/tpl-builder.png', fullPage: true });
+  log.dump('模板生成器');
+});

+ 19 - 0
dashboard-v6/src/api/markup.ts

@@ -0,0 +1,19 @@
+// src/api/markup.ts
+import { api, unwrapQuiet } from "./client";
+import type { paths } from "./schema";
+import type { MarkupNode } from "../components/markup/types";
+
+/* ─── v3 源码预览:把还没保存的 markdown 渲染成节点树(模板生成器的预览) ─── */
+
+export type MarkupPreviewInput = NonNullable<
+  paths["/v3/markup-previews"]["post"]["requestBody"]
+>["content"]["application/json"];
+
+/**
+ * 预览一段源码。失败不弹提示(unwrapQuiet):边输入边预览,由调用方在预览区里显示错误。
+ */
+export const previewMarkup = async (
+  input: MarkupPreviewInput,
+): Promise<MarkupNode[]> =>
+  unwrapQuiet(await api.POST("/v3/markup-previews", { body: input })).data
+    ?.body ?? [];

+ 367 - 0
dashboard-v6/src/api/schema.d.ts

@@ -8818,6 +8818,30 @@ export interface paths {
         patch?: never;
         trace?: never;
     };
+    "/v3/markup-previews": {
+        parameters: {
+            query?: never;
+            header?: never;
+            path?: never;
+            cookie?: never;
+        };
+        get?: never;
+        put?: never;
+        /**
+         * 预览一段源码
+         * @description 把还没保存的 markdown 渲染成节点树(与术语、批注的 `body` 同形),不写库,所以是 200 而不是 201。
+         *     口径同阅读页的读模式:术语按第一个 channel 查,句子模板缺省读这些 channel 的译文。
+         *     给了 `channels` 的,每个都要有读权限:不存在 404,看不见 403。
+         *
+         *     实现:`V3\MarkupPreviewController@__invoke`
+         */
+        post: operations["post_api_v3_markup_previews"];
+        delete?: never;
+        options?: never;
+        head?: never;
+        patch?: never;
+        trace?: never;
+    };
     "/v3/me": {
         parameters: {
             query?: never;
@@ -9538,6 +9562,82 @@ export interface paths {
         patch?: never;
         trace?: never;
     };
+    "/v3/tipitaka-exports": {
+        parameters: {
+            query?: never;
+            header?: never;
+            path?: never;
+            cookie?: never;
+        };
+        get?: never;
+        put?: never;
+        /**
+         * 发起下载
+         * @description 同一份文件(同一 channel、范围、格式,且译文没改过)已经生成好就直接返回 `status = ready`
+         *     与 `download_url`(200);否则排队生成,返回 `queued`(202,带 `Retry-After`),
+         *     之后轮询 `GET /v3/tipitaka-exports/{id}`。同一份正在生成时不会重复排队。
+         *     格式:`html`、`markdown`、`epub`、`docx`、`offline`(mobile 离线包,NDJSON,下载时 gzip 传输编码,
+         *     每行一段,`html` 与 `tipitaka-reading` 的 display 相同;只能按作品,首行头里有作品的段落区间
+         *     `para` / `end`,客户端按它判断是否覆盖了自己要的范围)。单部作品的 epub / docx
+         *     直接给文件,其余是 zip。私有 channel 只有能读它的人能下载。范围太大(超过全三藏的量)422。
+         *
+         *     实现:`V3\TipitakaExportController@store`
+         */
+        post: operations["post_api_v3_tipitaka_exports"];
+        delete?: never;
+        options?: never;
+        head?: never;
+        patch?: never;
+        trace?: never;
+    };
+    "/v3/tipitaka-exports/{export}": {
+        parameters: {
+            query?: never;
+            header?: never;
+            path?: never;
+            cookie?: never;
+        };
+        /**
+         * 查看下载状态
+         * @description `status`:`queued` 排队中 / `running` 生成中(`progress` 0–1,`message` 说明当前在哪部作品)/
+         *     `ready` 可下载(带 `download_url`)/ `failed` 失败(重新 POST 即可重试)。
+         *     不存在或已过期 404。
+         *
+         *     实现:`V3\TipitakaExportController@show`
+         */
+        get: operations["get_api_v3_tipitaka_exports_export_"];
+        put?: never;
+        post?: never;
+        delete?: never;
+        options?: never;
+        head?: never;
+        patch?: never;
+        trace?: never;
+    };
+    "/v3/tipitaka-exports/{export}/file": {
+        parameters: {
+            query?: never;
+            header?: never;
+            path?: never;
+            cookie?: never;
+        };
+        /**
+         * 下载文件
+         * @description 支持 `Range`(206,断点续传)与 `If-None-Match`(304,ETag 就是导出 id)。
+         *     离线包(offline)是 NDJSON,带 `Content-Encoding: gzip`,HTTP 客户端会自动解压。
+         *     签名无效或过期 403,文件已过期 404。
+         *
+         *     实现:`V3\TipitakaExportFileController@__invoke`
+         */
+        get: operations["get_api_v3_tipitaka_exports_export_file"];
+        put?: never;
+        post?: never;
+        delete?: never;
+        options?: never;
+        head?: never;
+        patch?: never;
+        trace?: never;
+    };
     "/v3/tipitaka-page-numbers/{page}": {
         parameters: {
             query?: never;
@@ -39952,6 +40052,67 @@ export interface operations {
             422: components["responses"]["ProblemValidation"];
         };
     };
+    post_api_v3_markup_previews: {
+        parameters: {
+            query?: never;
+            header?: never;
+            path?: never;
+            cookie?: never;
+        };
+        requestBody: {
+            content: {
+                "application/json": {
+                    /** @description 源码,最多 20000 字 */
+                    content: string;
+                    /**
+                     * @description 方言
+                     * @default markdown
+                     * @enum {string}
+                     */
+                    content_type?: "markdown" | "markdown-e2";
+                    /** @description 内容所属的 channel uid,最多 10 个 */
+                    channels?: unknown[];
+                    /** @description 没给 channel 时用的语言,如 zh-Hans。缺省用界面语言(Accept-Language 协商的结果) */
+                    lang?: string;
+                };
+            };
+        };
+        responses: {
+            /** @description 成功 */
+            200: {
+                headers: {
+                    [name: string]: unknown;
+                };
+                content: {
+                    "application/json": {
+                        data?: {
+                            body?: components["schemas"]["MarkupNode"][];
+                        };
+                    };
+                };
+            };
+            401: components["responses"]["ProblemUnauthorized"];
+            /** @description 给的 channel 没有读权限 */
+            403: {
+                headers: {
+                    [name: string]: unknown;
+                };
+                content: {
+                    "application/problem+json": components["schemas"]["ProblemDetails"];
+                };
+            };
+            /** @description 给的 channel 不存在 */
+            404: {
+                headers: {
+                    [name: string]: unknown;
+                };
+                content: {
+                    "application/problem+json": components["schemas"]["ProblemDetails"];
+                };
+            };
+            422: components["responses"]["ProblemValidation"];
+        };
+    };
     get_api_v3_me: {
         parameters: {
             query?: never;
@@ -42603,6 +42764,212 @@ export interface operations {
             422: components["responses"]["ProblemValidation"];
         };
     };
+    post_api_v3_tipitaka_exports: {
+        parameters: {
+            query?: never;
+            header?: never;
+            path?: never;
+            cookie?: never;
+        };
+        requestBody: {
+            content: {
+                "application/json": {
+                    /**
+                     * @description channel uid
+                     * @example a19eaf75-c63f-4b84-8125-1bce18311e23
+                     */
+                    channel: string;
+                    /**
+                     * @description 作品(library 作品页 URL 里的 sn)。作品、category 只能给一个,都不给 = 整个 channel
+                     * @example 275
+                     */
+                    work?: number;
+                    /** @description 用坐标指定作品:book + para 所在的那部作品(mobile 用,它不知道 sn)。与 para 同时给 */
+                    book?: number;
+                    /** @description 与 book 同时给,作品里的任一段落号(通常是作品起始段) */
+                    para?: number;
+                    /** @description 分类 id(library 分类页 URL 里的 id),含后代分类 */
+                    category?: number;
+                    /**
+                     * @description 文件格式
+                     * @enum {string}
+                     */
+                    format: "html" | "markdown" | "epub" | "docx" | "offline";
+                };
+            };
+        };
+        responses: {
+            /** @description 成功 */
+            200: {
+                headers: {
+                    [name: string]: unknown;
+                };
+                content: {
+                    "application/json": {
+                        data?: {
+                            id?: string;
+                            status?: string;
+                            format?: string;
+                            progress?: number;
+                            message?: string | null;
+                            title?: string;
+                            works?: number;
+                            filename?: string;
+                            content_type?: string;
+                            size?: number | null;
+                            ready_at?: string | null;
+                            expires_at?: string | null;
+                            download_url?: string | null;
+                        };
+                    };
+                };
+            };
+            /** @description 已排队生成,响应体同 200 */
+            202: {
+                headers: {
+                    [name: string]: unknown;
+                };
+                content: {
+                    "application/json": {
+                        data?: {
+                            id?: string;
+                            status?: string;
+                            format?: string;
+                            progress?: number;
+                            message?: string | null;
+                            title?: string;
+                            works?: number;
+                            filename?: string;
+                            content_type?: string;
+                            size?: number | null;
+                            ready_at?: string | null;
+                            expires_at?: string | null;
+                            download_url?: string | null;
+                        };
+                    };
+                };
+            };
+            422: components["responses"]["ProblemValidation"];
+        };
+    };
+    get_api_v3_tipitaka_exports_export_: {
+        parameters: {
+            query?: never;
+            header?: never;
+            path: {
+                /** @description 导出 id(POST 返回的 id) */
+                export: string;
+            };
+            cookie?: never;
+        };
+        requestBody?: never;
+        responses: {
+            /** @description 成功 */
+            200: {
+                headers: {
+                    [name: string]: unknown;
+                };
+                content: {
+                    "application/json": {
+                        data?: {
+                            id?: string;
+                            status?: string;
+                            format?: string;
+                            progress?: number;
+                            message?: string | null;
+                            title?: string;
+                            works?: number;
+                            filename?: string;
+                            content_type?: string;
+                            size?: number | null;
+                            ready_at?: string | null;
+                            expires_at?: string | null;
+                            download_url?: string | null;
+                        };
+                    };
+                };
+            };
+            422: components["responses"]["ProblemValidation"];
+        };
+    };
+    get_api_v3_tipitaka_exports_export_file: {
+        parameters: {
+            query: {
+                /** @description 签名的过期时间(download_url 里自带) */
+                expires: number;
+                /** @description 签名(download_url 里自带) */
+                signature: string;
+            };
+            header?: never;
+            path: {
+                /** @description 导出 id */
+                export: string;
+            };
+            cookie?: never;
+        };
+        requestBody?: never;
+        responses: {
+            /** @description 成功 */
+            200: {
+                headers: {
+                    [name: string]: unknown;
+                };
+                content: {
+                    "application/zip": string;
+                    "application/epub+zip": string;
+                    "application/vnd.openxmlformats-officedocument.wordprocessingml.document": string;
+                    "application/x-ndjson": string;
+                };
+            };
+            /** @description Range 请求的部分内容 */
+            206: {
+                headers: {
+                    [name: string]: unknown;
+                };
+                content: {
+                    "application/zip": string;
+                    "application/epub+zip": string;
+                    "application/vnd.openxmlformats-officedocument.wordprocessingml.document": string;
+                    "application/x-ndjson": string;
+                };
+            };
+            /** @description If-None-Match 命中,本地文件就是最新的 */
+            304: {
+                headers: {
+                    [name: string]: unknown;
+                };
+                content?: never;
+            };
+            /** @description 签名无效或已过期 */
+            403: {
+                headers: {
+                    [name: string]: unknown;
+                };
+                content: {
+                    "application/problem+json": components["schemas"]["ProblemDetails"];
+                };
+            };
+            /** @description 文件已过期 */
+            404: {
+                headers: {
+                    [name: string]: unknown;
+                };
+                content: {
+                    "application/problem+json": components["schemas"]["ProblemDetails"];
+                };
+            };
+            /** @description Range 超出文件大小 */
+            416: {
+                headers: {
+                    [name: string]: unknown;
+                };
+                content: {
+                    "application/problem+json": components["schemas"]["ProblemDetails"];
+                };
+            };
+            422: components["responses"]["ProblemValidation"];
+        };
+    };
     get_api_v3_tipitaka_page_numbers_page_: {
         parameters: {
             query?: {

+ 488 - 253
dashboard-v6/src/components/term/TermEdit.tsx

@@ -1,18 +1,36 @@
 import { useIntl } from "react-intl";
 import {
+  ModalForm,
   ProForm,
-  ProFormCheckbox,
   ProFormDependency,
   type ProFormInstance,
   ProFormSelect,
-  ProFormSwitch,
   ProFormText,
 } from "@ant-design/pro-components";
 
 import LangSelect from "../general/LangSelect";
 import ChannelSelect from "../channel/ChannelSelect";
-import { Alert, App, AutoComplete, Form, Space, Tag } from "antd";
-import { useEffect, useRef, useState } from "react";
+import {
+  Alert,
+  App,
+  AutoComplete,
+  Button,
+  Dropdown,
+  Form,
+  Space,
+  Tabs,
+  Tag,
+} from "antd";
+import { DownOutlined } from "@ant-design/icons";
+import {
+  useEffect,
+  useImperativeHandle,
+  useRef,
+  useState,
+  type Ref,
+  type RefObject,
+} from "react";
+import { useBlocker } from "react-router";
 import {
   createChannelTerm,
   createStudioTerm,
@@ -52,12 +70,17 @@ interface IFormValues {
   redirect?: string;
   channelId?: string;
   lang?: string;
-  save_as?: boolean;
+}
+
+/** 另存为对话框的字段 */
+interface ISaveAsValues {
   copy_channel?: string[];
   copy_lang?: string;
-  pr?: boolean;
 }
 
+/** 有未保存修改时用户的选择 */
+type LeaveChoice = "save" | "discard" | "stay";
+
 interface IWidget {
   id?: string;
   word?: string;
@@ -68,9 +91,70 @@ interface IWidget {
   parentChannelId?: string;
   parentStudioId?: string;
   community?: boolean;
+  /** 拦截路由跳转与关闭 / 刷新标签页(独立编辑页用;Modal 里不开,一个 router 只能有一个 blocker) */
+  blockNavigation?: boolean;
   onUpdate?: (data: Term) => void;
+  onCancel?: () => void;
+  /** 外层容器(如 Modal 的 ×、Esc)要关闭时调 `ref.current.cancel()`,走同一套未保存提示 */
+  ref?: Ref<TermEditHandle>;
 }
 
+export interface TermEditHandle {
+  /** 同点「取消」:有未保存的修改先提示,确认后调 onCancel / onUpdate */
+  cancel: () => void;
+}
+
+/**
+ * 有未保存修改时拦截离开:站内跳转弹出保存提示,关闭 / 刷新标签页走浏览器自带的提示。
+ * 单独成组件,只在 `blockNavigation` 时挂载,免得 Modal 里的实例也注册 blocker。
+ */
+const LeaveGuard = ({
+  dirtyRef,
+  confirmLeave,
+  save,
+}: {
+  dirtyRef: RefObject<boolean>;
+  confirmLeave: () => Promise<LeaveChoice>;
+  save: () => Promise<Term | undefined>;
+}) => {
+  const blocker = useBlocker(() => dirtyRef.current);
+  const handlers = useRef({ confirmLeave, save });
+  useEffect(() => {
+    handlers.current = { confirmLeave, save };
+  });
+
+  useEffect(() => {
+    if (blocker.state !== "blocked") {
+      return;
+    }
+    handlers.current.confirmLeave().then(async (choice) => {
+      if (choice === "stay") {
+        blocker.reset();
+        return;
+      }
+      if (choice === "save" && !(await handlers.current.save())) {
+        blocker.reset();
+        return;
+      }
+      dirtyRef.current = false;
+      blocker.proceed();
+    });
+  }, [blocker, dirtyRef]);
+
+  useEffect(() => {
+    const onBeforeUnload = (e: BeforeUnloadEvent) => {
+      if (dirtyRef.current) {
+        e.preventDefault();
+        e.returnValue = "";
+      }
+    };
+    window.addEventListener("beforeunload", onBeforeUnload);
+    return () => window.removeEventListener("beforeunload", onBeforeUnload);
+  }, [dirtyRef]);
+
+  return null;
+};
+
 /**
  * 术语编辑 / 新建(v3)。
  *
@@ -79,6 +163,9 @@ interface IWidget {
  * - 词头与标签建立后不能改(引用方写 `[[word@tag]]`);要改就新建一条,把旧的重定向过去
  * - 新建:选了版本就建在版本里(语言跟版本),选「通用于此 studio」就建 studio 级术语(要选语言)
  * - 分类写在正文的 `{{category|…}}` 里,由后端抽取
+ * - 右上角「取消」「保存」,保存的下拉是「另存为」(弹出版本选择,复制成一条新术语);
+ *   两者完成后都调回调,由调用方决定去哪(编辑页回到预览)
+ * - 有未保存的修改时,取消 / 离开会提示保存
  */
 const TermEditWidget = ({
   id,
@@ -88,24 +175,36 @@ const TermEditWidget = ({
   parentChannelId,
   parentStudioId,
   community = false,
+  blockNavigation = false,
   onUpdate,
+  onCancel,
+  ref,
 }: IWidget) => {
   const intl = useIntl();
   const [meaningOptions, setMeaningOptions] = useState<ValueType[]>([]);
   const [readonly, setReadonly] = useState(false);
-  const [isSaveAs, setIsSaveAs] = useState(false);
+  const [saveAsOpen, setSaveAsOpen] = useState(false);
+  const [copyToChannel, setCopyToChannel] = useState<string[]>([]);
+  const [saving, setSaving] = useState(false);
+  const [dirty, setDirtyState] = useState(false);
+  const dirtyRef = useRef(false);
   const [currChannel, setCurrChannel] = useState<ValueType[]>([]);
   const [etag, setEtag] = useState<string>();
   const [isGeneral, setIsGeneral] = useState(false);
   const user = useAppSelector(_currentUser);
   const { studioId: activeStudioId } = useActiveStudio();
-  const { message } = App.useApp();
+  const { message, modal } = App.useApp();
 
   const [form] = Form.useForm<IFormValues>();
   const formRef = useRef<ProFormInstance | undefined>(undefined);
   const isEdit = typeof id !== "undefined" && !community;
   const label = (key: string) => intl.formatMessage({ id: key });
 
+  const setDirty = (value: boolean) => {
+    dirtyRef.current = value;
+    setDirtyState(value);
+  };
+
   useEffect(() => {
     if (!word) {
       return;
@@ -152,8 +251,168 @@ const TermEditWidget = ({
     return createStudioTerm(studio, { ...body, language: language ?? "" });
   };
 
+  /**
+   * 校验并保存。`saveAs` 给了就复制成新术语建到所选版本;否则编辑时改原条、新建时按「版本」字段建。
+   * 校验不过(会自动切不到别的 tab,字段下面有红字)或保存失败返回 undefined。
+   */
+  const save = async (saveAs?: ISaveAsValues): Promise<Term | undefined> => {
+    let values: IFormValues;
+    try {
+      values = await form.validateFields();
+    } catch {
+      return undefined;
+    }
+    if (!values.word || !values.meaning) {
+      return undefined;
+    }
+    const content: TermPatch = {
+      meaning: values.meaning,
+      other_meaning: values.meaning2?.join() || null,
+      note: values.note || null,
+      summary: values.summary || null,
+      quality: (values.quality || null) as TermPatch["quality"],
+      content_type: values.content_type as TermPatch["content_type"],
+      redirect: values.redirect || null,
+    };
+
+    setSaving(true);
+    let saved: Term | undefined;
+    try {
+      if (isEdit && !saveAs && id) {
+        if (!etag) {
+          return undefined;
+        }
+        saved = await updateTerm(
+          id,
+          etag,
+          isGeneral && values.lang
+            ? { ...content, language: values.lang }
+            : content,
+        );
+      } else {
+        const target = saveAs
+          ? (saveAs.copy_channel?.[saveAs.copy_channel.length - 1] ?? "")
+          : (values.channelId ?? "");
+        saved = await create(target, saveAs ? saveAs.copy_lang : values.lang, {
+          ...content,
+          meaning: values.meaning,
+          word: values.word,
+          tag: values.tag || null,
+        });
+      }
+    } finally {
+      setSaving(false);
+    }
+    if (!saved) {
+      return undefined;
+    }
+    message.success(label("term.edit.saved"));
+    setEtag(saved.etag);
+    setDirty(false);
+    store.dispatch(
+      push({ word: saved.word ?? "", meaning: saved.meaning ?? "" }),
+    );
+    return saved;
+  };
+
+  /** 有未保存的修改时问用户:保存 / 不保存 / 继续编辑 */
+  const confirmLeave = () =>
+    new Promise<LeaveChoice>((resolve) => {
+      const instance = modal.confirm({
+        title: label("term.edit.unsaved.title"),
+        content: label("term.edit.unsaved.content"),
+        okText: label("buttons.save"),
+        cancelText: label("term.edit.unsaved.keep"),
+        onOk: () => resolve("save"),
+        onCancel: () => resolve("stay"),
+        footer: (_, { OkBtn, CancelBtn }) => (
+          <>
+            <CancelBtn />
+            <Button
+              danger
+              onClick={() => {
+                instance.destroy();
+                resolve("discard");
+              }}
+            >
+              {label("term.edit.unsaved.discard")}
+            </Button>
+            <OkBtn />
+          </>
+        ),
+      });
+    });
+
+  const handleSave = async () => {
+    const saved = await save();
+    if (saved) {
+      onUpdate?.(saved);
+    }
+  };
+
+  const handleCancel = async () => {
+    if (!dirtyRef.current) {
+      onCancel?.();
+      return;
+    }
+    const choice = await confirmLeave();
+    if (choice === "save") {
+      const saved = await save();
+      if (saved) {
+        onUpdate?.(saved);
+      }
+    } else if (choice === "discard") {
+      setDirty(false);
+      onCancel?.();
+    }
+  };
+
+  useImperativeHandle(ref, () => ({ cancel: handleCancel }));
+
   return (
     <>
+      {blockNavigation && (
+        <LeaveGuard
+          dirtyRef={dirtyRef}
+          confirmLeave={confirmLeave}
+          save={save}
+        />
+      )}
+      <div
+        style={{
+          display: "flex",
+          justifyContent: "flex-end",
+          marginBottom: 12,
+        }}
+      >
+        <Space>
+          <Button onClick={handleCancel}>{label("buttons.cancel")}</Button>
+          <Space.Compact>
+            <Button
+              type="primary"
+              loading={saving}
+              disabled={isEdit && readonly}
+              onClick={handleSave}
+            >
+              {label("buttons.save")}
+              {dirty ? " *" : ""}
+            </Button>
+            <Dropdown
+              trigger={["click"]}
+              menu={{
+                items: [{ key: "save-as", label: label("term.edit.save-as") }],
+                onClick: () => setSaveAsOpen(true),
+              }}
+            >
+              <Button
+                type="primary"
+                icon={<DownOutlined />}
+                disabled={saving}
+              />
+            </Dropdown>
+          </Space.Compact>
+        </Space>
+      </div>
       {community ? (
         <Alert
           title="该资源为社区数据,您可以修改并保存到一个您有修改权限的版本中。"
@@ -162,7 +421,7 @@ const TermEditWidget = ({
         />
       ) : readonly ? (
         <Alert
-          title="该资源为只读,如果需要修改,请联络拥有者分配权限。或者您可以在下面的版本选择中选择另一个版本,将该术语保存到一个您有修改权限的版本中。"
+          title="该资源为只读,如果需要修改,请联络拥有者分配权限。或者您可以用「另存为」将该术语保存到一个您有修改权限的版本中。"
           type="warning"
           closable
         />
@@ -171,58 +430,8 @@ const TermEditWidget = ({
         form={form}
         formRef={formRef}
         autoFocusFirstInput={true}
-        onFinish={async (values: IFormValues) => {
-          if (!values.word || !values.meaning) {
-            return;
-          }
-          const content: TermPatch = {
-            meaning: values.meaning,
-            other_meaning: values.meaning2?.join() || null,
-            note: values.note || null,
-            summary: values.summary || null,
-            quality: (values.quality || null) as TermPatch["quality"],
-            content_type: values.content_type as TermPatch["content_type"],
-            redirect: values.redirect || null,
-          };
-
-          let saved: Term | undefined;
-          if (isEdit && !values.save_as && id) {
-            if (!etag) {
-              return;
-            }
-            saved = await updateTerm(
-              id,
-              etag,
-              isGeneral && values.lang
-                ? { ...content, language: values.lang }
-                : content,
-            );
-          } else {
-            const target = values.save_as
-              ? (values.copy_channel?.[values.copy_channel.length - 1] ?? "")
-              : (values.channelId ?? "");
-            saved = await create(
-              target,
-              values.save_as ? values.copy_lang : values.lang,
-              {
-                ...content,
-                meaning: values.meaning,
-                word: values.word,
-                tag: values.tag || null,
-              },
-            );
-          }
-          if (!saved) {
-            return;
-          }
-          message.success("提交成功");
-          setEtag(saved.etag);
-          store.dispatch(
-            push({ word: saved.word ?? "", meaning: saved.meaning ?? "" }),
-          );
-          onUpdate?.(saved);
-          return true;
-        }}
+        submitter={false}
+        onValuesChange={() => setDirty(true)}
         request={async () => {
           let data: IFormValues = {
             word: word ? word : "",
@@ -235,7 +444,6 @@ const TermEditWidget = ({
             content_type: TERM_CONTENT_TYPES[0],
             redirect: "",
             lang: "",
-            copy_channel: [],
           };
           if (typeof id !== "undefined") {
             // 编辑:从服务器拉取
@@ -250,11 +458,10 @@ const TermEditWidget = ({
                 { label: term.channel.name, value: term.channel.id ?? "" },
               ]);
             }
-            let copyToChannel: string[] = [];
             if (parentChannelId) {
-              copyToChannel = user?.roles?.includes("basic")
-                ? [parentChannelId]
-                : [""];
+              setCopyToChannel(
+                user?.roles?.includes("basic") ? [parentChannelId] : [""],
+              );
             }
             data = {
               id: community ? undefined : term.id,
@@ -271,7 +478,6 @@ const TermEditWidget = ({
               channelId: community
                 ? (parentChannelId ?? "")
                 : (term.channel_id ?? ""),
-              copy_channel: copyToChannel,
             };
             if (!community && !term.abilities?.update) {
               setReadonly(true);
@@ -284,19 +490,17 @@ const TermEditWidget = ({
              */
             const channel = await fetchChannel(parentChannelId);
             let target = "";
-            let copyToChannel: string[] = [];
             if (user?.roles?.includes("basic")) {
               target = parentChannelId;
-              copyToChannel = [parentChannelId];
+              setCopyToChannel([parentChannelId]);
             } else {
               target = user?.id === parentStudioId ? "" : parentChannelId;
-              copyToChannel = [channel?.owner?.id ?? "", parentChannelId];
+              setCopyToChannel([channel?.owner?.id ?? "", parentChannelId]);
             }
             data = {
               ...data,
               lang: channel?.lang ?? "",
               channelId: target,
-              copy_channel: copyToChannel,
             };
           } else if (channelId) {
             // 从版本的术语列表新建
@@ -305,192 +509,223 @@ const TermEditWidget = ({
           return data;
         }}
       >
-        <ProForm.Group>
-          <ProFormText width="md" name="id" hidden />
+        <Tabs
+          items={[
+            {
+              key: "content",
+              label: label("term.edit.tab.content"),
+              forceRender: true,
+              children: (
+                <>
+                  <ProForm.Group>
+                    <ProFormText width="md" name="id" hidden />
 
-          <ProFormText
-            width="md"
-            name="word"
-            initialValue={word}
-            required
-            disabled={isEdit}
-            tooltip={
-              isEdit ? label("term.fields.immutable.tooltip") : undefined
-            }
-            label={label("term.fields.word.label")}
-            rules={[{ required: true }]}
-            fieldProps={{ showCount: true, maxLength: 128 }}
-          />
-          <ProFormText
-            width="md"
-            name="tag"
-            disabled={isEdit}
-            tooltip={
-              isEdit
-                ? label("term.fields.immutable.tooltip")
-                : label("term.fields.description.tooltip")
-            }
-            label={label("term.fields.description.label")}
-            rules={[{ pattern: /^[^@]*$/, message: "@" }]}
-          />
-        </ProForm.Group>
-        <ProForm.Group>
-          <ProForm.Item
-            width="md"
-            name="meaning"
-            label={label("term.fields.meaning.label")}
-            rules={[{ required: true }]}
-          >
-            <AutoComplete
-              options={meaningOptions}
-              style={{ width: "328px" }}
-              allowClear
-              maxLength={128}
-            />
-          </ProForm.Item>
+                    <ProFormText
+                      width="md"
+                      name="word"
+                      initialValue={word}
+                      required
+                      disabled={isEdit}
+                      tooltip={
+                        isEdit
+                          ? label("term.fields.immutable.tooltip")
+                          : undefined
+                      }
+                      label={label("term.fields.word.label")}
+                      rules={[{ required: true }]}
+                      fieldProps={{ showCount: true, maxLength: 128 }}
+                    />
+                    <ProFormText
+                      width="md"
+                      name="tag"
+                      disabled={isEdit}
+                      tooltip={
+                        isEdit
+                          ? label("term.fields.immutable.tooltip")
+                          : label("term.fields.description.tooltip")
+                      }
+                      label={label("term.fields.description.label")}
+                      rules={[{ pattern: /^[^@]*$/, message: "@" }]}
+                    />
+                  </ProForm.Group>
+                  <ProForm.Group>
+                    <ProForm.Item
+                      width="md"
+                      name="meaning"
+                      label={label("term.fields.meaning.label")}
+                      rules={[{ required: true }]}
+                    >
+                      <AutoComplete
+                        options={meaningOptions}
+                        style={{ width: "328px" }}
+                        allowClear
+                        maxLength={128}
+                      />
+                    </ProForm.Item>
 
-          <ProFormSelect
-            width="md"
-            name="meaning2"
-            label={label("term.fields.meaning2.label")}
-            fieldProps={{ mode: "tags", tokenSeparators: [",", ","] }}
-            placeholder="Please select other meanings"
-            rules={[{ type: "array" }]}
-          />
-        </ProForm.Group>
-        <ProForm.Group>
-          <ProFormSelect
-            name="channelId"
-            allowClear
-            label="版本(已经建立的术语,版本不可修改。可以选择另存为复制到另一个版本。)"
-            width="md"
-            placeholder={label("term.general-in-studio")}
-            disabled={channelDisable}
-            options={[
-              {
-                value: "",
-                label: label("term.general-in-studio"),
-                disabled:
-                  (parentStudioId !== undefined &&
-                    user?.id !== parentStudioId) ||
-                  user?.roles?.includes("basic"),
-              },
-              ...((parentChannelId ?? channelId)
-                ? [
-                    {
-                      value: parentChannelId ?? channelId ?? "",
-                      label: "仅用于此版本",
-                      disabled: !community && readonly,
-                    },
-                  ]
-                : []),
-              ...currChannel,
-            ]}
-          />
+                    <ProFormSelect
+                      width="md"
+                      name="meaning2"
+                      label={label("term.fields.meaning2.label")}
+                      fieldProps={{
+                        mode: "tags",
+                        tokenSeparators: [",", ","],
+                      }}
+                      placeholder="Please select other meanings"
+                      rules={[{ type: "array" }]}
+                    />
+                  </ProForm.Group>
+                  <ProForm.Group>
+                    <Form.Item
+                      style={{ width: "100%" }}
+                      name="summary"
+                      label={label("term.fields.summary.label")}
+                      tooltip={label("term.fields.summary.tooltip")}
+                    >
+                      <MDEditor height={120} preview="edit" />
+                    </Form.Item>
+                  </ProForm.Group>
+                  <ProForm.Group>
+                    <Form.Item
+                      style={{ width: "100%" }}
+                      name="note"
+                      label={label("forms.fields.note.label")}
+                    >
+                      <MDEditor />
+                    </Form.Item>
+                  </ProForm.Group>
+                </>
+              ),
+            },
+            {
+              key: "settings",
+              label: label("term.edit.tab.settings"),
+              forceRender: true,
+              children: (
+                <>
+                  <ProForm.Group>
+                    <ProFormSelect
+                      name="channelId"
+                      allowClear
+                      label={label("term.fields.channel.label")}
+                      tooltip={label("term.edit.channel.tooltip")}
+                      width="md"
+                      placeholder={label("term.general-in-studio")}
+                      disabled={channelDisable}
+                      options={[
+                        {
+                          value: "",
+                          label: label("term.general-in-studio"),
+                          disabled:
+                            (parentStudioId !== undefined &&
+                              user?.id !== parentStudioId) ||
+                            user?.roles?.includes("basic"),
+                        },
+                        ...((parentChannelId ?? channelId)
+                          ? [
+                              {
+                                value: parentChannelId ?? channelId ?? "",
+                                label: "仅用于此版本",
+                                disabled: !community && readonly,
+                              },
+                            ]
+                          : []),
+                        ...currChannel,
+                      ]}
+                    />
 
-          <ProFormDependency name={["channelId"]}>
-            {({ channelId }) => {
-              const hasChannel = !!channelId;
-              return (
-                <LangSelect
-                  disabled={hasChannel || (channelDisable && !isGeneral)}
-                  required={!hasChannel}
-                />
-              );
-            }}
-          </ProFormDependency>
-        </ProForm.Group>
-        <ProForm.Group>
-          <ProFormSelect
-            width="sm"
-            name="quality"
-            allowClear
-            label={label("term.fields.quality.label")}
-            placeholder={label("term.fields.quality.pending")}
-            options={TERM_QUALITIES.map((q) => ({
-              value: q,
-              label: label(`term.fields.quality.${q}`),
-            }))}
-          />
-          <ProFormSelect
-            width="sm"
-            name="content_type"
-            label={label("term.fields.content_type.label")}
-            allowClear={false}
-            options={TERM_CONTENT_TYPES.map((t) => ({ value: t, label: t }))}
-          />
-          <ProFormText
-            width="md"
-            name="redirect"
-            label={label("term.fields.redirect.label")}
-            tooltip={label("term.fields.redirect.tooltip")}
-          />
-        </ProForm.Group>
-        <ProForm.Group>
-          <Form.Item
-            style={{ width: "100%" }}
-            name="summary"
-            label={label("term.fields.summary.label")}
-            tooltip={label("term.fields.summary.tooltip")}
-          >
-            <MDEditor height={120} preview="edit" />
-          </Form.Item>
-        </ProForm.Group>
-        <ProForm.Group>
-          <Form.Item
-            style={{ width: "100%" }}
-            name="note"
-            label={label("forms.fields.note.label")}
-          >
-            <MDEditor />
-          </Form.Item>
-        </ProForm.Group>
-        <ProForm.Group>
-          <ProFormSwitch
-            name="save_as"
-            label="另存为"
-            fieldProps={{
-              onChange: (checked: boolean) => {
-                setIsSaveAs(checked);
-              },
-            }}
-          />
-        </ProForm.Group>
-        <ProForm.Group style={{ display: isSaveAs ? "block" : "none" }}>
-          <ChannelSelect
-            channelId={channelId}
-            parentChannelId={parentChannelId}
-            parentStudioId={parentStudioId}
-            width="md"
-            name="copy_channel"
-            placeholder={label("term.general-in-studio")}
-            allowClear={user?.roles?.includes("basic") ? false : true}
-            tooltip={label("term.fields.channel.tooltip")}
-            label={label("term.fields.channel.label")}
-          />
-          <ProFormDependency name={["copy_channel"]}>
-            {({ copy_channel }) => {
-              const hasChannel = copy_channel
-                ? copy_channel.length === 0 || copy_channel[0] === ""
-                  ? false
-                  : true
-                : false;
-              return (
-                <LangSelect
-                  name="copy_lang"
-                  disabled={hasChannel}
-                  required={isSaveAs && !hasChannel}
-                />
-              );
-            }}
-          </ProFormDependency>
-        </ProForm.Group>
-        <ProForm.Group style={{ display: isSaveAs ? "block" : "none" }}>
-          <ProFormCheckbox disabled name="pr">
-            同时提交修改建议
-          </ProFormCheckbox>
-        </ProForm.Group>
+                    <ProFormDependency name={["channelId"]}>
+                      {({ channelId }) => {
+                        const hasChannel = !!channelId;
+                        return (
+                          <LangSelect
+                            disabled={
+                              hasChannel || (channelDisable && !isGeneral)
+                            }
+                            required={!hasChannel}
+                          />
+                        );
+                      }}
+                    </ProFormDependency>
+                  </ProForm.Group>
+                  <ProForm.Group>
+                    <ProFormSelect
+                      width="sm"
+                      name="quality"
+                      allowClear
+                      label={label("term.fields.quality.label")}
+                      placeholder={label("term.fields.quality.pending")}
+                      options={TERM_QUALITIES.map((q) => ({
+                        value: q,
+                        label: label(`term.fields.quality.${q}`),
+                      }))}
+                    />
+                    <ProFormSelect
+                      width="sm"
+                      name="content_type"
+                      label={label("term.fields.content_type.label")}
+                      allowClear={false}
+                      options={TERM_CONTENT_TYPES.map((t) => ({
+                        value: t,
+                        label: t,
+                      }))}
+                    />
+                    <ProFormText
+                      width="md"
+                      name="redirect"
+                      label={label("term.fields.redirect.label")}
+                      tooltip={label("term.fields.redirect.tooltip")}
+                    />
+                  </ProForm.Group>
+                </>
+              ),
+            },
+          ]}
+        />
       </ProForm>
+      <ModalForm<ISaveAsValues>
+        title={label("term.edit.save-as.title")}
+        width={480}
+        open={saveAsOpen}
+        onOpenChange={setSaveAsOpen}
+        modalProps={{ destroyOnHidden: true }}
+        initialValues={{ copy_channel: copyToChannel }}
+        onFinish={async (values) => {
+          const saved = await save(values);
+          if (!saved) {
+            return false;
+          }
+          onUpdate?.(saved);
+          return true;
+        }}
+      >
+        <ChannelSelect
+          channelId={channelId}
+          parentChannelId={parentChannelId}
+          parentStudioId={parentStudioId}
+          width="md"
+          name="copy_channel"
+          placeholder={label("term.general-in-studio")}
+          allowClear={user?.roles?.includes("basic") ? false : true}
+          tooltip={label("term.fields.channel.tooltip")}
+          label={label("term.fields.channel.label")}
+        />
+        <ProFormDependency name={["copy_channel"]}>
+          {({ copy_channel }) => {
+            const hasChannel =
+              !!copy_channel &&
+              copy_channel.length > 0 &&
+              copy_channel[0] !== "";
+            return (
+              <LangSelect
+                name="copy_lang"
+                disabled={hasChannel}
+                required={!hasChannel}
+              />
+            );
+          }}
+        </ProFormDependency>
+      </ModalForm>
     </>
   );
 };

+ 7 - 2
dashboard-v6/src/components/term/TermModal.tsx

@@ -1,6 +1,7 @@
 import { Modal, Space } from "antd";
 import { Link } from "react-router";
-import TermEdit from "./TermEdit";
+import { useRef } from "react";
+import TermEdit, { type TermEditHandle } from "./TermEdit";
 import type { Term } from "../../api/Term";
 import useMergedState from "../../hooks/useMergedState"; // 确保路径正确
 
@@ -37,6 +38,7 @@ const TermModalWidget = (props: IWidget) => {
     },
   });
 
+  const editRef = useRef<TermEditHandle>(null);
   const close = () => setIsModalOpen(false);
   const show = () => setIsModalOpen(true);
 
@@ -65,11 +67,14 @@ const TermModalWidget = (props: IWidget) => {
         mask={{ closable: false }}
         destroyOnHidden // 关闭时销毁内部组件,防止数据残留
         open={isModalOpen}
-        onCancel={close}
+        // × 与 Esc 走编辑组件的「取消」:有未保存的修改先提示
+        onCancel={() => (editRef.current ? editRef.current.cancel() : close())}
       >
         <TermEdit
+          ref={editRef}
           {...restEditProps}
           studioName={studioName}
+          onCancel={close}
           onUpdate={(value: Term) => {
             close();
             onUpdate?.(value);

+ 0 - 29
dashboard-v6/src/components/tpl-builder/ArticleTpl.tsx

@@ -1,29 +0,0 @@
-import type { JSX } from "react";
-import type { ArticleType } from "../../api/article";
-import type { TDisplayStyle } from "../../types/template";
-
-interface IWidget {
-  type?: ArticleType;
-  articleId?: string;
-  title?: string;
-  style?: TDisplayStyle;
-  channel?: string | null;
-}
-
-export const ArticleTplMock = ({ title }: IWidget) => {
-  return <span>{"ArticleTplMock" + title}</span>;
-};
-
-interface IModalWidget {
-  open?: boolean;
-  type?: ArticleType;
-  articleId?: string;
-  channelsId?: string | null;
-  title?: string;
-  style?: TDisplayStyle;
-  trigger?: JSX.Element;
-  onClose?: () => void;
-}
-export const ArticleTplModalMock = ({ trigger }: IModalWidget) => {
-  return <>{trigger}</>;
-};

+ 135 - 33
dashboard-v6/src/components/tpl-builder/TplBuilder.tsx

@@ -1,66 +1,168 @@
-import { useEffect, useState } from "react";
-import { Modal, Tabs } from "antd";
+import { useMemo, useState } from "react";
+import { Divider, Input, Menu, Modal, Typography } from "antd";
+import { useIntl } from "react-intl";
+
 import type { ArticleType } from "../../api/article";
-import { ArticleTplMock } from "./ArticleTpl";
-import { VideoTplMock } from "./VideoTpl";
+import TplForm from "./TplForm";
+import TplPreview from "./TplPreview";
+import {
+  buildTplCode,
+  initialValues,
+  TEMPLATES,
+  tplKey,
+  type TplValues,
+} from "./templates";
+
+const { Paragraph, Text } = Typography;
+
+/** article 模板的 type 能取的值;入口传来的其它类型(series、term…)按 article 处理 */
+const ARTICLE_TYPES: string[] = ["article", "chapter", "para", "anthology"];
+
+/** 弹窗内容区高度:视口减去上边距 20、标题约 40、上下内边距 40、下边距 20 */
+const BODY_HEIGHT = "calc(100vh - 140px)";
 
 interface IWidget {
   trigger?: React.ReactNode;
   open?: boolean;
+  /** 从文章 / 章节入口打开时:article 模板预填的类型、id、标题、channel */
   tpl?: ArticleType;
   articleId?: string;
+  /** channel uid,多个用 `_` 连接(与阅读页地址的 channel 参数相同) */
   channelsId?: string | null;
   title?: string;
   onClose?: () => void;
 }
+
+/**
+ * 模板生成器:选模板 → 填参数 → 得到模板代码(可复制)与后端渲染的预览。
+ * 能生成的模板见 ./templates.ts(与后端 App\Services\Markup\Templates 对应)。
+ */
 const TplBuilderWidget = ({
   trigger,
   open = false,
   tpl,
   articleId,
+  channelsId,
+  title,
   onClose,
 }: IWidget) => {
-  const [isModalOpen, setIsModalOpen] = useState(open);
+  const intl = useIntl();
+  /** 点 trigger 打开的;受控打开(open)由调用方在 onClose 里关 */
+  const [innerOpen, setInnerOpen] = useState(false);
+  const [active, setActive] = useState("article");
 
-  useEffect(() => {
-    setIsModalOpen(open);
-  }, [open]);
+  /** 每个模板各自的参数值,切换页签不丢 */
+  const prefilled = useMemo<Record<string, TplValues>>(() => {
+    const all = Object.fromEntries(
+      TEMPLATES.map((spec) => [spec.name, initialValues(spec)]),
+    );
+    if (articleId) {
+      all.article = {
+        ...all.article,
+        type: tpl && ARTICLE_TYPES.includes(tpl) ? tpl : "article",
+        id: articleId,
+        title,
+        channel: channelsId ?? undefined,
+      };
+    }
+    return all;
+  }, [tpl, articleId, title, channelsId]);
+  // 入口换了文章 / 章节就丢掉改过的值,回到新的预填值
+  const [state, setState] = useState({ base: prefilled, values: prefilled });
+  const values = state.base === prefilled ? state.values : prefilled;
+  const setValues = (next: Record<string, TplValues>) =>
+    setState({ base: prefilled, values: next });
 
-  const showModal = () => {
-    setIsModalOpen(true);
-  };
+  const spec = TEMPLATES.find((t) => t.name === active) ?? TEMPLATES[0];
+  const current = values[spec.name] ?? {};
+  const code = buildTplCode(spec, current);
+
+  /** 预览按哪些 channel 渲染:表单里填的优先,其次是入口传来的 */
+  const previewChannels = (current.channel ?? channelsId ?? "")
+    .split(/[_,]/)
+    .filter((c) => c !== "");
 
   const handleCancel = () => {
-    if (onClose) {
-      onClose();
-    } else {
-      setIsModalOpen(false);
-    }
+    setInnerOpen(false);
+    onClose?.();
+  };
+
+  const tabLabel = (name: string) => {
+    const id = `tpl-builder.tpl.${tplKey(name)}`;
+    return intl.messages[id] ? `${intl.formatMessage({ id })} ${name}` : name;
   };
 
+  const panel = (
+    <div>
+      {intl.messages[`tpl-builder.desc.${tplKey(spec.name)}`] ? (
+        <Paragraph type="secondary">
+          {intl.formatMessage({ id: `tpl-builder.desc.${tplKey(spec.name)}` })}
+        </Paragraph>
+      ) : null}
+      <TplForm
+        spec={spec}
+        values={current}
+        onChange={(v) => setValues({ ...values, [spec.name]: v })}
+      />
+      <Divider titlePlacement="start" plain>
+        {intl.formatMessage({ id: "tpl-builder.code" })}
+      </Divider>
+      <Input.TextArea
+        value={code}
+        readOnly
+        autoSize={{ minRows: 1, maxRows: 8 }}
+        style={{ fontFamily: "monospace" }}
+      />
+      <Text copyable={{ text: code }}>
+        {intl.formatMessage({ id: "buttons.copy" })}
+      </Text>
+      <Divider titlePlacement="start" plain>
+        {intl.formatMessage({ id: "buttons.preview" })}
+      </Divider>
+      <TplPreview code={code} channels={previewChannels} />
+    </div>
+  );
+
   return (
     <>
-      <span onClick={showModal}>{trigger}</span>
+      <span onClick={() => setInnerOpen(true)}>{trigger}</span>
       <Modal
-        style={{ top: 20 }}
-        width={900}
+        style={{ top: 20, paddingBottom: 0 }}
+        width={1000}
         footer={false}
-        title="template builder"
-        open={isModalOpen}
+        title={intl.formatMessage({ id: "tpl-builder.title" })}
+        open={open || innerOpen}
         onCancel={handleCancel}
       >
-        <Tabs
-          tabPosition="left"
-          defaultActiveKey="article"
-          items={[
-            {
-              label: "article",
-              key: "article",
-              children: <ArticleTplMock articleId={articleId} type={tpl} />,
-            }, // 务必填写 key
-            { label: "video", key: "video", children: <VideoTplMock /> },
-          ]}
-        />
+        {/*
+          弹窗不超出浏览器:内容区高度 = 视口 − 弹窗上下边距、标题与内边距。
+          模板列表与修改区同高、各自滚动,换模板时修改区高度不变。
+          不用竖排 Tabs:限高后它把放不下的页签收进「更多」下拉,二十个模板大半看不见。
+        */}
+        <div style={{ display: "flex", height: BODY_HEIGHT }}>
+          <Menu
+            mode="inline"
+            selectedKeys={[spec.name]}
+            onClick={({ key }) => setActive(key)}
+            style={{ width: 200, flexShrink: 0, overflowY: "auto" }}
+            items={TEMPLATES.map((t) => ({
+              key: t.name,
+              label: tabLabel(t.name),
+            }))}
+          />
+          {/* 只渲染当前模板:预览会请求后端 */}
+          <div
+            className="tpl-builder-panel"
+            style={{
+              flex: 1,
+              minWidth: 0,
+              overflowY: "auto",
+              padding: "0 8px 0 24px",
+            }}
+          >
+            {panel}
+          </div>
+        </div>
       </Modal>
     </>
   );

+ 175 - 0
dashboard-v6/src/components/tpl-builder/TplForm.tsx

@@ -0,0 +1,175 @@
+import { Button, Form, Input, InputNumber, Select, Space } from "antd";
+import { FolderOpenOutlined } from "@ant-design/icons";
+import { useIntl } from "react-intl";
+
+import { useAppSelector } from "../../hooks";
+import { currentUser } from "../../reducers/current-user";
+import ArticleListModal from "../article/ArticleListModal";
+import ChannelTableModal from "../channel/ChannelTableModal";
+import AttachmentDialog from "../attachment/AttachmentDialog";
+import {
+  isVisible,
+  tplKey,
+  type TplField,
+  type TplSpec,
+  type TplValues,
+} from "./templates";
+
+interface IWidget {
+  spec: TplSpec;
+  values: TplValues;
+  onChange: (values: TplValues) => void;
+}
+
+/**
+ * 一个模板的参数表单。受控:值由 TplBuilder 按模板分别保存,切换页签不丢。
+ */
+const TplForm = ({ spec, values, onChange }: IWidget) => {
+  const intl = useIntl();
+  const user = useAppSelector(currentUser);
+
+  /** 参数的显示名:先找模板专用的(同名参数在不同模板里意思不同,如 text),再找通用的 */
+  const label = (field: TplField) => {
+    const own = `tpl-builder.field.${tplKey(spec.name)}.${field.name}`;
+    const id = intl.messages[own] ? own : `tpl-builder.field.${field.name}`;
+    return intl.messages[id]
+      ? `${intl.formatMessage({ id })} (${field.name})`
+      : field.name;
+  };
+
+  const set = (name: string, value: string | undefined) =>
+    onChange({ ...values, [name]: value });
+
+  const control = (field: TplField) => {
+    const value = values[field.name];
+    const text = (
+      <Input
+        value={value}
+        placeholder={field.placeholder}
+        allowClear
+        onChange={(e) => set(field.name, e.target.value)}
+      />
+    );
+    switch (field.kind) {
+      case "select":
+        return (
+          <Select
+            value={value}
+            allowClear={!field.required}
+            style={{ width: 200 }}
+            options={field.options?.map((o) => ({ value: o, label: o }))}
+            onChange={(v: string | undefined) => set(field.name, v)}
+          />
+        );
+      case "textarea":
+        return (
+          <Input.TextArea
+            value={value}
+            placeholder={field.placeholder}
+            autoSize={{ minRows: 3, maxRows: 10 }}
+            onChange={(e) => set(field.name, e.target.value)}
+          />
+        );
+      case "number":
+        return (
+          <InputNumber
+            value={value === undefined || value === "" ? null : Number(value)}
+            min={0}
+            style={{ width: 200 }}
+            onChange={(v) =>
+              set(field.name, v === null ? undefined : String(v))
+            }
+          />
+        );
+      case "article":
+        return (
+          <Space.Compact style={{ width: "100%" }}>
+            {text}
+            {/* 只有 type=article 能从文章列表里挑;章节、段落的 id 是经文坐标 */}
+            {(values.type ?? "article") === "article" ? (
+              <ArticleListModal
+                studioName={user?.realName}
+                multiple={false}
+                trigger={
+                  <Button
+                    icon={<FolderOpenOutlined />}
+                    title={intl.formatMessage({
+                      id: "tpl-builder.select.article",
+                    })}
+                  />
+                }
+                onSelect={(id: string, title: string) =>
+                  onChange({
+                    ...values,
+                    id,
+                    title: values.title ? values.title : title,
+                  })
+                }
+              />
+            ) : null}
+          </Space.Compact>
+        );
+      case "channel":
+        return (
+          <Space.Compact style={{ width: "100%" }}>
+            {text}
+            <ChannelTableModal
+              trigger={
+                <Button
+                  icon={<FolderOpenOutlined />}
+                  title={intl.formatMessage({
+                    id: "tpl-builder.select.channel",
+                  })}
+                />
+              }
+              onSelect={(channel) => set(field.name, channel.id)}
+            />
+          </Space.Compact>
+        );
+      case "attachment":
+        return (
+          <Space.Compact style={{ width: "100%" }}>
+            {text}
+            <AttachmentDialog
+              trigger={
+                <Button
+                  icon={<FolderOpenOutlined />}
+                  title={intl.formatMessage({
+                    id: "tpl-builder.select.attachment",
+                  })}
+                />
+              }
+              onSelect={(file) =>
+                onChange({
+                  ...values,
+                  [field.name]: file.url,
+                  title: values.title ? values.title : file.title,
+                })
+              }
+            />
+          </Space.Compact>
+        );
+      default:
+        return text;
+    }
+  };
+
+  return (
+    <Form layout="vertical" size="small">
+      {spec.fields
+        .filter((f) => isVisible(f, values))
+        .map((field) => (
+          <Form.Item
+            key={field.name}
+            label={label(field)}
+            required={field.required}
+            style={{ marginBottom: 8 }}
+          >
+            {control(field)}
+          </Form.Item>
+        ))}
+    </Form>
+  );
+};
+
+export default TplForm;

Некоторые файлы не были показаны из-за большого количества измененных файлов