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

✨ (export): 三藏下载 /v3/tipitaka-exports + library 下载页 + 离线包

一部作品 / 一个分类 / 整个 channel 导出成 html、markdown、epub、docx,以及给 mobile 的离线包(NDJSON,gzip 传输)。
不预生成:POST 命中已有文件直接给,否则 202 排队(RabbitMQ export_tipitaka / export_tipitaka_bulk 两个 worker,
大打包不堵单部作品),轮询 GET,ready 带签名的相对下载链接。id 即内容指纹,译文改了自然换 id。
文件以二进制存 Redis 集群 7 天(RedisCache 新增 putBinary / getBinary / binaryLength / getBinaryRange,
下载按 1MB 分块 GETRANGE 流式输出,支持 Range / If-None-Match)。

- library:作品页下载按钮启用,新增作品下载页与整个 channel 下载页(只有「全部」)
- tipitaka-reading 的 markdown 句末附脚注正文(原来只有 [^n]),缓存 key 加 /fn 让旧缓存过期
- 生成器支持 @responseFile;重生成 spec、dashboard-v6 schema.d.ts、api-test 客户端与用例
- tasks.md 记两个 worker 与 consumer_timeout;CLAUDE.md 对照表加一行

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
visuddhinanda 3 часов назад
Родитель
Сommit
2269a78019
50 измененных файлов с 7061 добавлено и 13 удалено
  1. 0 0
      CLAUDE.md
  2. 82 0
      api-test/cases/26_tipitaka_exports.php
  3. 12 0
      api-test/client/.openapi-generator/FILES
  4. 1188 0
      api-test/client/lib/Api/TipitakaExportsApi.php
  5. 409 0
      api-test/client/lib/Model/PostApiV3TipitakaExports200Response.php
  6. 852 0
      api-test/client/lib/Model/PostApiV3TipitakaExports200ResponseData.php
  7. 625 0
      api-test/client/lib/Model/PostApiV3TipitakaExportsRequest.php
  8. 5 0
      api-test/fixtures.php
  9. 48 0
      api-v13/app/Console/Commands/MqExportTipitaka.php
  10. 4 0
      api-v13/app/Facades/RedisCache.php
  11. 102 0
      api-v13/app/Http/Controllers/Library/TipitakaDownloadController.php
  12. 70 0
      api-v13/app/Http/Controllers/V3/TipitakaExportController.php
  13. 43 0
      api-v13/app/Http/Controllers/V3/TipitakaExportFileController.php
  14. 35 0
      api-v13/app/Http/Requests/V3/StoreTipitakaExportRequest.php
  15. 38 0
      api-v13/app/Http/Resources/V3/TipitakaExportResource.php
  16. 3 0
      api-v13/app/Providers/AppServiceProvider.php
  17. 7 2
      api-v13/app/Services/PaliContentService.php
  18. 64 1
      api-v13/app/Services/RedisCache.php
  19. 19 2
      api-v13/app/Services/RedisCacheFake.php
  20. 574 0
      api-v13/app/Services/V3/TipitakaExportBuilder.php
  21. 85 0
      api-v13/app/Services/V3/TipitakaExportDownload.php
  22. 25 0
      api-v13/app/Services/V3/TipitakaExportQueue.php
  23. 434 0
      api-v13/app/Services/V3/TipitakaExportService.php
  24. 19 0
      api-v13/config/mint.php
  25. 403 0
      api-v13/documents/download-demo.html
  26. 12 0
      api-v13/documents/tasks.md
  27. 195 0
      api-v13/resources/css/modules/tipitaka.css
  28. 45 0
      api-v13/resources/lang/en/library.php
  29. 6 0
      api-v13/resources/lang/en/messages.php
  30. 45 0
      api-v13/resources/lang/zh-Hans/library.php
  31. 6 0
      api-v13/resources/lang/zh-Hans/messages.php
  32. 45 0
      api-v13/resources/lang/zh-Hant/library.php
  33. 5 0
      api-v13/resources/lang/zh-Hant/messages.php
  34. 9 0
      api-v13/resources/template/epub/tipitaka.css
  35. 28 0
      api-v13/resources/views/exports/tipitaka/_style.blade.php
  36. 142 0
      api-v13/resources/views/exports/tipitaka/index.blade.php
  37. 105 0
      api-v13/resources/views/exports/tipitaka/work.blade.php
  38. 3 0
      api-v13/resources/views/library/tipitaka/channels/category.blade.php
  39. 239 0
      api-v13/resources/views/library/tipitaka/download.blade.php
  40. 2 3
      api-v13/resources/views/library/tipitaka/show.blade.php
  41. 15 0
      api-v13/routes/v3/tipitaka.php
  42. 4 0
      api-v13/routes/web.php
  43. 41 0
      api-v13/tests/Feature/RedisCacheTest.php
  44. 353 0
      api-v13/tests/Feature/TipitakaExportV3Test.php
  45. 282 0
      dashboard-v6/src/api/schema.d.ts
  46. 6 0
      openapi/public/assets/protocol/main.yaml
  47. 99 0
      openapi/public/assets/protocol/resources/auto/v3-tipitaka-exports-export-file.yaml
  48. 68 0
      openapi/public/assets/protocol/resources/auto/v3-tipitaka-exports-export.yaml
  49. 141 0
      openapi/public/assets/protocol/resources/auto/v3-tipitaka-exports.yaml
  50. 19 5
      openapi/scripts/generate.php

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


+ 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 未收录作品');
+});

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

@@ -37,6 +37,7 @@ docs/Api/TermsApi.md
 docs/Api/TipitakaChannelsApi.md
 docs/Api/TipitakaChannelsApi.md
 docs/Api/TipitakaChapterChannelsApi.md
 docs/Api/TipitakaChapterChannelsApi.md
 docs/Api/TipitakaDiscussionsApi.md
 docs/Api/TipitakaDiscussionsApi.md
+docs/Api/TipitakaExportsApi.md
 docs/Api/TipitakaPageNumbersApi.md
 docs/Api/TipitakaPageNumbersApi.md
 docs/Api/TipitakaParagraphChannelsApi.md
 docs/Api/TipitakaParagraphChannelsApi.md
 docs/Api/TipitakaReadingApi.md
 docs/Api/TipitakaReadingApi.md
@@ -264,6 +265,9 @@ docs/Model/PostApiV3Sessions200ResponseData.md
 docs/Model/PostApiV3SessionsRequest.md
 docs/Model/PostApiV3SessionsRequest.md
 docs/Model/PostApiV3StudiosStudioChannelsRequest.md
 docs/Model/PostApiV3StudiosStudioChannelsRequest.md
 docs/Model/PostApiV3StudiosStudioTermsRequest.md
 docs/Model/PostApiV3StudiosStudioTermsRequest.md
+docs/Model/PostApiV3TipitakaExports200Response.md
+docs/Model/PostApiV3TipitakaExports200ResponseData.md
+docs/Model/PostApiV3TipitakaExportsRequest.md
 docs/Model/PostApiV3Users200Response.md
 docs/Model/PostApiV3Users200Response.md
 docs/Model/PostApiV3Users200ResponseData.md
 docs/Model/PostApiV3Users200ResponseData.md
 docs/Model/PostApiV3UsersRequest.md
 docs/Model/PostApiV3UsersRequest.md
@@ -302,6 +306,7 @@ lib/Api/TermsApi.php
 lib/Api/TipitakaChannelsApi.php
 lib/Api/TipitakaChannelsApi.php
 lib/Api/TipitakaChapterChannelsApi.php
 lib/Api/TipitakaChapterChannelsApi.php
 lib/Api/TipitakaDiscussionsApi.php
 lib/Api/TipitakaDiscussionsApi.php
+lib/Api/TipitakaExportsApi.php
 lib/Api/TipitakaPageNumbersApi.php
 lib/Api/TipitakaPageNumbersApi.php
 lib/Api/TipitakaParagraphChannelsApi.php
 lib/Api/TipitakaParagraphChannelsApi.php
 lib/Api/TipitakaReadingApi.php
 lib/Api/TipitakaReadingApi.php
@@ -534,6 +539,9 @@ lib/Model/PostApiV3Sessions200ResponseData.php
 lib/Model/PostApiV3SessionsRequest.php
 lib/Model/PostApiV3SessionsRequest.php
 lib/Model/PostApiV3StudiosStudioChannelsRequest.php
 lib/Model/PostApiV3StudiosStudioChannelsRequest.php
 lib/Model/PostApiV3StudiosStudioTermsRequest.php
 lib/Model/PostApiV3StudiosStudioTermsRequest.php
+lib/Model/PostApiV3TipitakaExports200Response.php
+lib/Model/PostApiV3TipitakaExports200ResponseData.php
+lib/Model/PostApiV3TipitakaExportsRequest.php
 lib/Model/PostApiV3Users200Response.php
 lib/Model/PostApiV3Users200Response.php
 lib/Model/PostApiV3Users200ResponseData.php
 lib/Model/PostApiV3Users200ResponseData.php
 lib/Model/PostApiV3UsersRequest.php
 lib/Model/PostApiV3UsersRequest.php
@@ -573,6 +581,7 @@ test/Api/TermsApiTest.php
 test/Api/TipitakaChannelsApiTest.php
 test/Api/TipitakaChannelsApiTest.php
 test/Api/TipitakaChapterChannelsApiTest.php
 test/Api/TipitakaChapterChannelsApiTest.php
 test/Api/TipitakaDiscussionsApiTest.php
 test/Api/TipitakaDiscussionsApiTest.php
+test/Api/TipitakaExportsApiTest.php
 test/Api/TipitakaPageNumbersApiTest.php
 test/Api/TipitakaPageNumbersApiTest.php
 test/Api/TipitakaParagraphChannelsApiTest.php
 test/Api/TipitakaParagraphChannelsApiTest.php
 test/Api/TipitakaReadingApiTest.php
 test/Api/TipitakaReadingApiTest.php
@@ -800,6 +809,9 @@ test/Model/PostApiV3Sessions200ResponseTest.php
 test/Model/PostApiV3SessionsRequestTest.php
 test/Model/PostApiV3SessionsRequestTest.php
 test/Model/PostApiV3StudiosStudioChannelsRequestTest.php
 test/Model/PostApiV3StudiosStudioChannelsRequestTest.php
 test/Model/PostApiV3StudiosStudioTermsRequestTest.php
 test/Model/PostApiV3StudiosStudioTermsRequestTest.php
+test/Model/PostApiV3TipitakaExports200ResponseDataTest.php
+test/Model/PostApiV3TipitakaExports200ResponseTest.php
+test/Model/PostApiV3TipitakaExportsRequestTest.php
 test/Model/PostApiV3Users200ResponseDataTest.php
 test/Model/PostApiV3Users200ResponseDataTest.php
 test/Model/PostApiV3Users200ResponseTest.php
 test/Model/PostApiV3Users200ResponseTest.php
 test/Model/PostApiV3UsersRequestTest.php
 test/Model/PostApiV3UsersRequestTest.php

+ 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/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));
+    }
+}
+
+

+ 5 - 0
api-test/fixtures.php

@@ -42,6 +42,11 @@ return [
     'group_name' => 'api-test 团队',
     'group_name' => 'api-test 团队',
     'group_member_username' => 'test162',
     '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 的「已注册」用例;只校验、不发信)。
     // 一个已注册账号的邮箱(email-certifications 的「已注册」用例;只校验、不发信)。
     // 留空则该用例 SKIP。
     // 留空则该用例 SKIP。
     'registered_email' => getenv('API_TEST_REGISTERED_EMAIL') ?: null,
     'registered_email' => getenv('API_TEST_REGISTERED_EMAIL') ?: null,

+ 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 - 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 has(string $key)
  * @method static bool forget(string $key)
  * @method static bool forget(string $key)
  * @method static int increment(string $key, int $value = 1)
  * @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
  * @see \App\Services\RedisCache
  */
  */

+ 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);
+    }
+}

+ 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'));
+    }
+}

+ 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)],
+        ];
+    }
+}

+ 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);
+    }
+}

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

@@ -140,6 +140,9 @@ class AppServiceProvider extends ServiceProvider
         // 比对验证码、建账号:按 IP 限,挡住对 6 位验证码的穷举(单个码另有 5 次试错上限)
         // 比对验证码、建账号:按 IP 限,挡住对 6 位验证码的穷举(单个码另有 5 次试错上限)
         RateLimiter::for('sign-up', fn (Request $request): Limit => Limit::perMinute(20)->by('ip:'.$request->ip()));
         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 挡住换着账号撞库
         // 登录:按「账号 + IP」挡住对单个账号的猜密码,按 IP 挡住换着账号撞库
         RateLimiter::for('sessions', fn (Request $request): array => [
         RateLimiter::for('sessions', fn (Request $request): array => [
             Limit::perMinute(5)->by('login:'.mb_strtolower((string) $request->input('login')).'|'.$request->ip()),
             Limit::perMinute(5)->by('login:'.mb_strtolower((string) $request->input('login')).'|'.$request->ip()),

+ 7 - 2
api-v13/app/Services/PaliContentService.php

@@ -746,7 +746,10 @@ class PaliContentService
     public static function paragraphCacheKey(int $book, int $para, string $channelUid, string $format): string
     public static function paragraphCacheKey(int $book, int $para, string $channelUid, string $format): string
     {
     {
         // markup:App\Services\Markup 渲染的缓存,与 MdRender 时代的旧缓存分开(旧 key 自然过期)
         // markup:App\Services\Markup 渲染的缓存,与 MdRender 时代的旧缓存分开(旧 key 自然过期)
-        return "/read-para/markup/{$book}-{$para}/{$channelUid}/{$format}";
+        // markdown 2026-11-21 起句末附脚注正文,换 key 让旧缓存(不带脚注正文)自然过期
+        $suffix = $format === 'markdown' ? '/fn' : '';
+
+        return "/read-para/markup/{$book}-{$para}/{$channelUid}/{$format}{$suffix}";
     }
     }
 
 
     /**
     /**
@@ -1009,7 +1012,9 @@ class PaliContentService
         // 整段一起渲染:各句里的术语、句子模板(含义注对应)合在一起批量查
         // 整段一起渲染:各句里的术语、句子模板(含义注对应)合在一起批量查
         $rendered = $sources === [] ? [] : app(MarkupService::class)->renderMany(
         $rendered = $sources === [] ? [] : app(MarkupService::class)->renderMany(
             $sources,
             $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'),
         );
         );
         foreach ($records as $i => $row) {
         foreach ($records as $i => $row) {
             $html = $rendered[$i] ?? '';
             $html = $rendered[$i] ?? '';

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

@@ -28,6 +28,12 @@ use RedisCluster;
  *
  *
  * 集群与 Laravel Cache 用的单机 Redis 不是同一个库,旧缓存不迁移,切换后冷启动。
  * 集群与 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()
  * 业务代码通过门面 App\Facades\RedisCache 调用;测试用 RedisCache::fake()
  * 换成内存实现(见 RedisCacheFake)。
  * 换成内存实现(见 RedisCacheFake)。
  */
  */
@@ -121,6 +127,44 @@ class RedisCache
         return $this->incrementBy($this->key($key), $value);
         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`。
      * 前缀与 key 之间用 / 隔开:`dev` + `foo` → `dev/foo`;`/task/1` 本身带 /,得 `dev/task/1`。
      */
      */
@@ -130,7 +174,7 @@ class RedisCache
     }
     }
 
 
     /**
     /**
-     * 以下四个是仅有的 Redis 存取原语,RedisCacheFake 只需覆盖它们。
+     * 以下六个是仅有的 Redis 存取原语,RedisCacheFake 只需覆盖它们。
      * 参数 $key 已带前缀。
      * 参数 $key 已带前缀。
      */
      */
     protected function read(string $key): ?string
     protected function read(string $key): ?string
@@ -160,6 +204,25 @@ class RedisCache
         return (int) $this->redis()->incrby($key, $value);
         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 里的具名集群,直接用种子节点。
      * 第一个参数 null 表示不读 php.ini 里的具名集群,直接用种子节点。
      */
      */

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

@@ -5,8 +5,8 @@ namespace App\Services;
 /**
 /**
  * RedisCache 的内存实现,供测试使用(相当于 Laravel Cache 的 array store)。
  * 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
 class RedisCacheFake extends RedisCache
 {
 {
@@ -60,4 +60,21 @@ class RedisCacheFake extends RedisCache
 
 
         return $next;
         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);
+    }
 }
 }

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

@@ -0,0 +1,574 @@
+<?php
+
+namespace App\Services\V3;
+
+use App\Models\Channel;
+use App\Models\PaliText;
+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,
+    ) {}
+
+    /**
+     * 生成文件,返回文件字节。
+     *
+     * @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 PaliText::where('book', $work['book'])
+            ->whereBetween('paragraph', [$work['para'], $work['end']])
+            ->where('level', '<', 8)
+            ->pluck('level', 'paragraph')
+            ->map(fn ($level) => (int) $level)
+            ->all();
+    }
+
+    /**
+     * 作品区间里的标题:段落号 => [级别, 巴利标题]。译文没有译出标题时拿巴利标题顶上。
+     *
+     * @param  array<string, mixed>  $work
+     * @return array<int, array{int, string}>
+     */
+    private function headings(array $work): array
+    {
+        return PaliText::where('book', $work['book'])
+            ->whereBetween('paragraph', [$work['para'], $work['end']])
+            ->where('level', '<', 8)
+            ->orderBy('paragraph')
+            ->get(['paragraph', 'level', 'toc'])
+            ->mapWithKeys(fn ($row) => [(int) $row->paragraph => [(int) $row->level, (string) $row->toc]])
+            ->all();
+    }
+
+    /**
+     * @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');
+    }
+}

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

@@ -199,8 +199,27 @@ return [
             'suggestion' => [],
             'suggestion' => [],
             'wbw-analyses' => [],
             'wbw-analyses' => [],
             'ai_translate_v2' => [],
             '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' => [
     'opensearch' => [
         'index' => 'wikipali_global_20261119',
         'index' => 'wikipali_global_20261119',
         // 索引 settings + mappings 定义文件所在目录,文件名为「{index}.json」
         // 索引 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>

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

@@ -35,8 +35,20 @@ php artisan mq:task
 # 队列 wbw-analyses
 # 队列 wbw-analyses
 php artisan mq: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)。
 `ai_translate_v2`(`rabbitmq:consume`)待第二阶段重构 worker 后补上。`content` 队列已移除(无消费者,发送端已注释,见 `SentenceController@update` 的 FIXME)。
 
 
 ## every five minutes
 ## every five minutes

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

@@ -873,3 +873,198 @@ a.tipitaka-tree__work:hover {
     color: var(--tblr-primary);
     color: var(--tblr-primary);
     font-weight: 600;
     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; }
+}

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

@@ -205,4 +205,49 @@ return [
     'show_missing' => 'Show missing works',
     'show_missing' => 'Show missing works',
     'no_works_in_category' => 'This translation has no works in this category',
     'no_works_in_category' => 'This translation has no works in this category',
     'not_included' => 'not included',
     '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_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_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.',
     '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' => '显示未收录作品',
     'show_missing' => '显示未收录作品',
     'no_works_in_category' => '该译本在此分类下没有作品',
     'no_works_in_category' => '该译本在此分类下没有作品',
     'not_included' => '未收录',
     '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_unreadable' => '读不了这个文件,请上传 xlsx 格式的表格。',
     'term_import_header_required' => '表格第一行要有列名,至少包含 word 与 meaning。',
     'term_import_header_required' => '表格第一行要有列名,至少包含 word 与 meaning。',
     'term_import_too_many' => '一次最多导入 :max 行。',
     '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_no_history' => '暫無歷史課程',
     'course_history_title' => '歷史課程',
     'course_history_title' => '歷史課程',
     'course_history_subtitle' => '已結束的公開課程,回顧往期研讀',
     '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' => '驗證碼不正確或已過期。',
     'sign_up_code_invalid' => '驗證碼不正確或已過期。',
     'invite_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]) }}">
                 <a class="btn btn-sm" href="{{ request()->fullUrlWithQuery(['all' => $showAll ? null : 1]) }}">
                     {{ $showAll ? __('library.only_included') : __('library.show_missing') }}
                     {{ $showAll ? __('library.only_included') : __('library.show_missing') }}
                 </a>
                 </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>
         </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>
                         <i class="ti ti-book-2 me-1"></i>
                         {{ __('library.read_online') }}
                         {{ __('library.read_online') }}
                     </a>
                     </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>
                         <i class="ti ti-download me-1"></i>
                         {{ __('library.download') }}
                         {{ __('library.download') }}
-                    </button>
+                    </a>
                 </div>
                 </div>
 
 
             </div>
             </div>

+ 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\TipitakaChannelController;
 use App\Http\Controllers\V3\TipitakaChapterChannelController;
 use App\Http\Controllers\V3\TipitakaChapterChannelController;
 use App\Http\Controllers\V3\TipitakaDiscussionController;
 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\TipitakaPageNumberController;
 use App\Http\Controllers\V3\TipitakaParagraphChannelController;
 use App\Http\Controllers\V3\TipitakaParagraphChannelController;
 use App\Http\Controllers\V3\TipitakaReadingController;
 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)
 Route::get('tipitaka-page-numbers/{page}', TipitakaPageNumberController::class)
     ->whereNumber('page')
     ->whereNumber('page')
     ->name('tipitaka-page-numbers.show');
     ->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\SearchController;
 use App\Http\Controllers\Library\TipitakaChannelController;
 use App\Http\Controllers\Library\TipitakaChannelController;
 use App\Http\Controllers\Library\TipitakaController;
 use App\Http\Controllers\Library\TipitakaController;
+use App\Http\Controllers\Library\TipitakaDownloadController;
 use App\Http\Controllers\Library\WikiController;
 use App\Http\Controllers\Library\WikiController;
 use App\Http\Controllers\PageIndexController;
 use App\Http\Controllers\PageIndexController;
 use App\Http\Controllers\WbwAnalysisController;
 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('/category/{id?}', [TipitakaChannelController::class, 'category'])->whereNumber('id')->name('category');
         Route::get('/work/{sn}', [BookController::class, 'show'])->whereNumber('sn')->name('work');
         Route::get('/work/{sn}', [BookController::class, 'show'])->whereNumber('sn')->name('work');
         Route::get('/work/{sn}/read', [BookController::class, 'readWork'])->whereNumber('sn')->name('work.read');
         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'])
         Route::get('/chapter/{chapter}', [BookController::class, 'read'])
             ->where('chapter', '\d+-\d+')->name('chapter');
             ->where('chapter', '\d+-\d+')->name('chapter');
     });
     });

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

@@ -131,6 +131,30 @@ test('increment 从 0 开始累加,返回新值', function () {
         ->and(RedisCache::get('c'))->toBe(6);
         ->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 名带前缀、
 | 第二部分:契约。连真实 Redis Cluster(mint.redis_cluster),证明 key 名带前缀、
 | 值是 JSON、整数是纯文本(ai-translate 用 int() 读 /task/{id}/pointer)、TTL 与写值一条命令落地,
 | 值是 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->get('missing', 'd'))->toBe('d')
         ->and($cache->forget('missing'))->toBeFalse();
         ->and($cache->forget('missing'))->toBeFalse();
 })->skip(fn () => ! realRedisAvailable(), '没有可用的 Redis Cluster');
 })->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();
+});

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

@@ -9562,6 +9562,82 @@ export interface paths {
         patch?: never;
         patch?: never;
         trace?: 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}": {
     "/v3/tipitaka-page-numbers/{page}": {
         parameters: {
         parameters: {
             query?: never;
             query?: never;
@@ -42688,6 +42764,212 @@ export interface operations {
             422: components["responses"]["ProblemValidation"];
             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_: {
     get_api_v3_tipitaka_page_numbers_page_: {
         parameters: {
         parameters: {
             query?: {
             query?: {

+ 6 - 0
openapi/public/assets/protocol/main.yaml

@@ -891,6 +891,12 @@ paths:
     $ref: ./resources/auto/v3-tipitaka-chapter-channels-book-para.yaml
     $ref: ./resources/auto/v3-tipitaka-chapter-channels-book-para.yaml
   '/v3/tipitaka-discussions/{channel}':
   '/v3/tipitaka-discussions/{channel}':
     $ref: ./resources/auto/v3-tipitaka-discussions-channel.yaml
     $ref: ./resources/auto/v3-tipitaka-discussions-channel.yaml
+  /v3/tipitaka-exports:
+    $ref: ./resources/auto/v3-tipitaka-exports.yaml
+  '/v3/tipitaka-exports/{export}':
+    $ref: ./resources/auto/v3-tipitaka-exports-export.yaml
+  '/v3/tipitaka-exports/{export}/file':
+    $ref: ./resources/auto/v3-tipitaka-exports-export-file.yaml
   '/v3/tipitaka-page-numbers/{page}':
   '/v3/tipitaka-page-numbers/{page}':
     $ref: ./resources/auto/v3-tipitaka-page-numbers-page.yaml
     $ref: ./resources/auto/v3-tipitaka-page-numbers-page.yaml
   '/v3/tipitaka-paragraph-channels/{book}/{para}':
   '/v3/tipitaka-paragraph-channels/{book}/{para}':

+ 99 - 0
openapi/public/assets/protocol/resources/auto/v3-tipitaka-exports-export-file.yaml

@@ -0,0 +1,99 @@
+# 由 openapi/scripts/generate.php 生成,请勿手改;补充写到 overrides/v3-tipitaka-exports-export-file.yaml
+get:
+  summary: 下载文件
+  tags:
+    - tipitaka-exports
+  operationId: get_api_v3_tipitaka_exports_export_file
+  description: |-
+    支持 `Range`(206,断点续传)与 `If-None-Match`(304,ETag 就是导出 id)。
+    离线包(offline)是 NDJSON,带 `Content-Encoding: gzip`,HTTP 客户端会自动解压。
+    签名无效或过期 403,文件已过期 404。
+
+    实现:`V3\TipitakaExportFileController@__invoke`
+  security:
+    - {  }
+    -
+      bearerAuth: []
+  parameters:
+    -
+      name: export
+      in: path
+      required: true
+      schema:
+        type: string
+      description: '导出 id'
+    -
+      name: expires
+      in: query
+      schema:
+        type: integer
+      description: '签名的过期时间(download_url 里自带)'
+      required: true
+    -
+      name: signature
+      in: query
+      schema:
+        type: string
+      description: '签名(download_url 里自带)'
+      required: true
+  responses:
+    200:
+      description: 成功
+      content:
+        application/zip:
+          schema:
+            type: string
+            format: binary
+        application/epub+zip:
+          schema:
+            type: string
+            format: binary
+        application/vnd.openxmlformats-officedocument.wordprocessingml.document:
+          schema:
+            type: string
+            format: binary
+        application/x-ndjson:
+          schema:
+            type: string
+            format: binary
+    206:
+      description: 'Range 请求的部分内容'
+      content:
+        application/zip:
+          schema:
+            type: string
+            format: binary
+        application/epub+zip:
+          schema:
+            type: string
+            format: binary
+        application/vnd.openxmlformats-officedocument.wordprocessingml.document:
+          schema:
+            type: string
+            format: binary
+        application/x-ndjson:
+          schema:
+            type: string
+            format: binary
+    304:
+      description: 'If-None-Match 命中,本地文件就是最新的'
+    403:
+      description: 签名无效或已过期
+      content:
+        application/problem+json:
+          schema:
+            $ref: '../../main.yaml#/components/schemas/ProblemDetails'
+    404:
+      description: 文件已过期
+      content:
+        application/problem+json:
+          schema:
+            $ref: '../../main.yaml#/components/schemas/ProblemDetails'
+    416:
+      description: 'Range 超出文件大小'
+      content:
+        application/problem+json:
+          schema:
+            $ref: '../../main.yaml#/components/schemas/ProblemDetails'
+    422:
+      $ref: '../../main.yaml#/components/responses/ProblemValidation'

+ 68 - 0
openapi/public/assets/protocol/resources/auto/v3-tipitaka-exports-export.yaml

@@ -0,0 +1,68 @@
+# 由 openapi/scripts/generate.php 生成,请勿手改;补充写到 overrides/v3-tipitaka-exports-export.yaml
+get:
+  summary: 查看下载状态
+  tags:
+    - tipitaka-exports
+  operationId: get_api_v3_tipitaka_exports_export_
+  description: |-
+    `status`:`queued` 排队中 / `running` 生成中(`progress` 0–1,`message` 说明当前在哪部作品)/
+    `ready` 可下载(带 `download_url`)/ `failed` 失败(重新 POST 即可重试)。
+    不存在或已过期 404。
+
+    实现:`V3\TipitakaExportController@show`
+  security:
+    - {  }
+    -
+      bearerAuth: []
+  parameters:
+    -
+      name: export
+      in: path
+      required: true
+      schema:
+        type: string
+      description: '导出 id(POST 返回的 id)'
+  responses:
+    200:
+      description: 成功
+      content:
+        application/json:
+          schema:
+            type: object
+            properties:
+              data:
+                type: object
+                properties:
+                  id:
+                    type: string
+                  status:
+                    type: string
+                  format:
+                    type: string
+                  progress:
+                    type: number
+                  message:
+                    type: string
+                    nullable: true
+                  title:
+                    type: string
+                  works:
+                    type: integer
+                  filename:
+                    type: string
+                  content_type:
+                    type: string
+                  size:
+                    type: integer
+                    nullable: true
+                  ready_at:
+                    type: string
+                    nullable: true
+                  expires_at:
+                    type: string
+                    nullable: true
+                  download_url:
+                    type: string
+                    nullable: true
+    422:
+      $ref: '../../main.yaml#/components/responses/ProblemValidation'

+ 141 - 0
openapi/public/assets/protocol/resources/auto/v3-tipitaka-exports.yaml

@@ -0,0 +1,141 @@
+# 由 openapi/scripts/generate.php 生成,请勿手改;补充写到 overrides/v3-tipitaka-exports.yaml
+post:
+  summary: 发起下载
+  tags:
+    - tipitaka-exports
+  operationId: post_api_v3_tipitaka_exports
+  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`
+  security:
+    - {  }
+    -
+      bearerAuth: []
+  requestBody:
+    required: true
+    content:
+      application/json:
+        schema:
+          type: object
+          properties:
+            channel:
+              type: string
+              description: 'channel uid'
+              example: a19eaf75-c63f-4b84-8125-1bce18311e23
+            work:
+              type: integer
+              description: '作品(library 作品页 URL 里的 sn)。作品、category 只能给一个,都不给 = 整个 channel'
+              example: 275
+            book:
+              type: integer
+              description: '用坐标指定作品:book + para 所在的那部作品(mobile 用,它不知道 sn)。与 para 同时给'
+            para:
+              type: integer
+              description: '与 book 同时给,作品里的任一段落号(通常是作品起始段)'
+            category:
+              type: integer
+              description: '分类 id(library 分类页 URL 里的 id),含后代分类'
+            format:
+              type: string
+              description: 文件格式
+              enum:
+                - html
+                - markdown
+                - epub
+                - docx
+                - offline
+          required:
+            - channel
+            - format
+  responses:
+    200:
+      description: 成功
+      content:
+        application/json:
+          schema:
+            type: object
+            properties:
+              data:
+                type: object
+                properties:
+                  id:
+                    type: string
+                  status:
+                    type: string
+                  format:
+                    type: string
+                  progress:
+                    type: number
+                  message:
+                    type: string
+                    nullable: true
+                  title:
+                    type: string
+                  works:
+                    type: integer
+                  filename:
+                    type: string
+                  content_type:
+                    type: string
+                  size:
+                    type: integer
+                    nullable: true
+                  ready_at:
+                    type: string
+                    nullable: true
+                  expires_at:
+                    type: string
+                    nullable: true
+                  download_url:
+                    type: string
+                    nullable: true
+    202:
+      description: '已排队生成,响应体同 200'
+      content:
+        application/json:
+          schema:
+            type: object
+            properties:
+              data:
+                type: object
+                properties:
+                  id:
+                    type: string
+                  status:
+                    type: string
+                  format:
+                    type: string
+                  progress:
+                    type: number
+                  message:
+                    type: string
+                    nullable: true
+                  title:
+                    type: string
+                  works:
+                    type: integer
+                  filename:
+                    type: string
+                  content_type:
+                    type: string
+                  size:
+                    type: integer
+                    nullable: true
+                  ready_at:
+                    type: string
+                    nullable: true
+                  expires_at:
+                    type: string
+                    nullable: true
+                  download_url:
+                    type: string
+                    nullable: true
+    422:
+      $ref: '../../main.yaml#/components/responses/ProblemValidation'

+ 19 - 5
openapi/scripts/generate.php

@@ -260,6 +260,8 @@ function castToType(string $value, string $type): mixed
  *   @unauthenticated       该端点无需登录,不挂 401
  *   @unauthenticated       该端点无需登录,不挂 401
  *   @responseStatus 码 描述  额外的状态码。v3 下 2xx 视为另一种成功口径(响应体与 200
  *   @responseStatus 码 描述  额外的状态码。v3 下 2xx 视为另一种成功口径(响应体与 200
  *                          同形,如 201 Created),非 2xx 的响应体是 Problem Details
  *                          同形,如 201 Created),非 2xx 的响应体是 Problem Details
+ *   @responseFile mime …   成功响应是文件(二进制)而不是 JSON,列出可能的 media type(空格分隔),
+ *                          如下载接口。2xx 的响应体都按它生成
  *   @meta name type 描述     v3 列表响应的手工分页 meta 字段(如游标式阅读接口)。
  *   @meta name type 描述     v3 列表响应的手工分页 meta 字段(如游标式阅读接口)。
  *                           声明后 meta 不再套通用 PaginationMeta,而是按声明生成专用 schema
  *                           声明后 meta 不再套通用 PaginationMeta,而是按声明生成专用 schema
  *
  *
@@ -267,7 +269,7 @@ function castToType(string $value, string $type): mixed
  */
  */
 function parseDocTags(array $tagLines): array
 function parseDocTags(array $tagLines): array
 {
 {
-    $result = ['params' => [], 'deprecated' => false, 'unauthenticated' => false, 'responses' => [], 'meta' => []];
+    $result = ['params' => [], 'deprecated' => false, 'unauthenticated' => false, 'responses' => [], 'meta' => [], 'file' => []];
     foreach ($tagLines as $line) {
     foreach ($tagLines as $line) {
         if (str_starts_with($line, '@deprecated')) {
         if (str_starts_with($line, '@deprecated')) {
             $result['deprecated'] = true;
             $result['deprecated'] = true;
@@ -285,6 +287,12 @@ function parseDocTags(array $tagLines): array
 
 
             continue;
             continue;
         }
         }
+        // @responseFile application/zip application/epub+zip —— 成功响应是文件
+        if (preg_match('/^@responseFile\s+(.+)$/u', $line, $r)) {
+            $result['file'] = preg_split('/\s+/', trim($r[1])) ?: [];
+
+            continue;
+        }
         // @meta name type 描述 —— 手工分页的 meta 字段
         // @meta name type 描述 —— 手工分页的 meta 字段
         if (preg_match('/^@meta\s+(\S+)\s+(\S+)\s*(.*)$/u', $line, $m)) {
         if (preg_match('/^@meta\s+(\S+)\s+(\S+)\s*(.*)$/u', $line, $m)) {
             [, $name, $type, $rest] = $m;
             [, $name, $type, $rest] = $m;
@@ -992,13 +1000,19 @@ function buildOperation(array $route, string $httpMethod): array
             $success['properties']['meta'] = metaSchema($info);
             $success['properties']['meta'] = metaSchema($info);
         }
         }
 
 
+        // 成功的响应体:JSON,或 @responseFile 声明的文件(每种 media type 都是二进制串)
+        $files = $info['tags']['file'] ?? [];
+        $successContent = $files === []
+            ? ['application/json' => ['schema' => $success]]
+            : array_fill_keys($files, ['schema' => ['type' => 'string', 'format' => 'binary']]);
+
         // 声明了 204 就不再输出默认的 200——控制器 return response()->noContent()
         // 声明了 204 就不再输出默认的 200——控制器 return response()->noContent()
         // 的端点没有 200 这个口径,留着会让前端以为可以读 body
         // 的端点没有 200 这个口径,留着会让前端以为可以读 body
         $declared = $info['tags']['responses'] ?? [];
         $declared = $info['tags']['responses'] ?? [];
         $responses = isset($declared[204]) ? [] : [
         $responses = isset($declared[204]) ? [] : [
             '200' => [
             '200' => [
                 'description' => '成功',
                 'description' => '成功',
-                'content' => ['application/json' => ['schema' => $success]],
+                'content' => $successContent,
             ],
             ],
         ];
         ];
         // 无鉴权的端点用 @unauthenticated 标注,就不再挂 401
         // 无鉴权的端点用 @unauthenticated 标注,就不再挂 401
@@ -1013,8 +1027,8 @@ function buildOperation(array $route, string $httpMethod): array
         // 响应体与 200 同形;其余是错误,响应体是 Problem Details。
         // 响应体与 200 同形;其余是错误,响应体是 Problem Details。
         foreach ($declared as $code => $desc) {
         foreach ($declared as $code => $desc) {
             $isSuccess = $code >= 200 && $code < 300;
             $isSuccess = $code >= 200 && $code < 300;
-            // 204 / 205 按 RFC 9110 MUST NOT 带消息体,不给 content
-            if ((int) $code === 204 || (int) $code === 205) {
+            // 204 / 205 / 304 按 RFC 9110 MUST NOT 带消息体,不给 content
+            if (in_array((int) $code, [204, 205, 304], true)) {
                 $responses[(string) $code] = ['description' => $desc !== '' ? $desc : '成功,无响应体'];
                 $responses[(string) $code] = ['description' => $desc !== '' ? $desc : '成功,无响应体'];
 
 
                 continue;
                 continue;
@@ -1022,7 +1036,7 @@ function buildOperation(array $route, string $httpMethod): array
             $responses[(string) $code] = $isSuccess
             $responses[(string) $code] = $isSuccess
                 ? [
                 ? [
                     'description' => $desc !== '' ? $desc : '成功',
                     'description' => $desc !== '' ? $desc : '成功',
-                    'content' => ['application/json' => ['schema' => $success]],
+                    'content' => $successContent,
                 ]
                 ]
                 : [
                 : [
                     'description' => $desc !== '' ? $desc : 'Problem Details',
                     'description' => $desc !== '' ? $desc : 'Problem Details',

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