@meerrec/cli 0.0.0-stage → 2.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (71) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +142 -2
  3. package/dist/args.d.ts +48 -0
  4. package/dist/args.d.ts.map +1 -0
  5. package/dist/args.js +256 -0
  6. package/dist/args.js.map +1 -0
  7. package/dist/cli.d.ts +4 -0
  8. package/dist/cli.d.ts.map +1 -0
  9. package/dist/cli.js +5 -0
  10. package/dist/cli.js.map +1 -0
  11. package/dist/convert.d.ts +27 -0
  12. package/dist/convert.d.ts.map +1 -0
  13. package/dist/convert.js +69 -0
  14. package/dist/convert.js.map +1 -0
  15. package/dist/errors.d.ts +11 -0
  16. package/dist/errors.d.ts.map +1 -0
  17. package/dist/errors.js +15 -0
  18. package/dist/errors.js.map +1 -0
  19. package/dist/expand.d.ts +25 -0
  20. package/dist/expand.d.ts.map +1 -0
  21. package/dist/expand.js +148 -0
  22. package/dist/expand.js.map +1 -0
  23. package/dist/formats.d.ts +26 -0
  24. package/dist/formats.d.ts.map +1 -0
  25. package/dist/formats.js +71 -0
  26. package/dist/formats.js.map +1 -0
  27. package/dist/index.d.ts +13 -0
  28. package/dist/index.d.ts.map +1 -0
  29. package/dist/index.js +13 -0
  30. package/dist/index.js.map +1 -0
  31. package/dist/pool.d.ts +36 -0
  32. package/dist/pool.d.ts.map +1 -0
  33. package/dist/pool.js +149 -0
  34. package/dist/pool.js.map +1 -0
  35. package/dist/progress.d.ts +30 -0
  36. package/dist/progress.d.ts.map +1 -0
  37. package/dist/progress.js +67 -0
  38. package/dist/progress.js.map +1 -0
  39. package/dist/run.d.ts +10 -0
  40. package/dist/run.d.ts.map +1 -0
  41. package/dist/run.js +138 -0
  42. package/dist/run.js.map +1 -0
  43. package/dist/runtime-deno.d.ts +17 -0
  44. package/dist/runtime-deno.d.ts.map +1 -0
  45. package/dist/runtime-deno.js +116 -0
  46. package/dist/runtime-deno.js.map +1 -0
  47. package/dist/runtime-node.d.ts +13 -0
  48. package/dist/runtime-node.d.ts.map +1 -0
  49. package/dist/runtime-node.js +30 -0
  50. package/dist/runtime-node.js.map +1 -0
  51. package/dist/runtime.d.ts +45 -0
  52. package/dist/runtime.d.ts.map +1 -0
  53. package/dist/runtime.js +41 -0
  54. package/dist/runtime.js.map +1 -0
  55. package/dist/wasm.d.ts +23 -0
  56. package/dist/wasm.d.ts.map +1 -0
  57. package/dist/wasm.js +50 -0
  58. package/dist/wasm.js.map +1 -0
  59. package/dist/worker-deno.d.ts +10 -0
  60. package/dist/worker-deno.d.ts.map +1 -0
  61. package/dist/worker-deno.js +28 -0
  62. package/dist/worker-deno.js.map +1 -0
  63. package/dist/worker-protocol.d.ts +20 -0
  64. package/dist/worker-protocol.d.ts.map +1 -0
  65. package/dist/worker-protocol.js +7 -0
  66. package/dist/worker-protocol.js.map +1 -0
  67. package/dist/worker.d.ts +10 -0
  68. package/dist/worker.d.ts.map +1 -0
  69. package/dist/worker.js +28 -0
  70. package/dist/worker.js.map +1 -0
  71. package/package.json +50 -3
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 doc-converter contributors
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,143 @@
1
- # Temporary Holding Version
1
+ # @meerrec/cli
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Конвертер OOXML из командной строки: DOCX в PDF, Markdown, HTML или текст,
4
+ XLSX в PDF. Вся конвертация — те же Rust/WASM-модули, что и в просмотрщике
5
+ (`@meerrec/wasm-pdf`, `@meerrec/wasm-docx`), поэтому результат
6
+ совпадает с тем, что отдаёт интерфейс.
7
+
8
+ ## Установка
9
+
10
+ Пакет опубликован в **GitHub Packages** этого репозитория
11
+ (`@meerrec/cli@1.0.0`) — действующем зеркале; целевой основной реестр —
12
+ `registry.npmjs.org` (публикация готовится,
13
+ [ADR-0027](https://github.com/meerrec/wasm-converter/blob/main/docs/adr/0027-npmjs-primary-registry.md)).
14
+ Реестр и токен с правом `read:packages` — в `~/.npmrc`:
15
+
16
+ ```ini
17
+ # ~/.npmrc — <токен> это personal access token (classic) с read:packages
18
+ @meerrec:registry=https://npm.pkg.github.com
19
+ //npm.pkg.github.com/:_authToken=<токен>
20
+ ```
21
+
22
+ ```bash
23
+ npm install -g @meerrec/cli --registry=https://npm.pkg.github.com
24
+ ```
25
+
26
+ Без реестра — тарбол (`meerrec-cli-1.0.0.tgz`) в ассетах релиза
27
+ [`v1.0.0`](https://github.com/meerrec/wasm-converter/releases/tag/v1.0.0).
28
+
29
+ Node ≥ 20 (как в корневом `package.json`). Из монорепозитория:
30
+
31
+ ```bash
32
+ pnpm install
33
+ pnpm build:wasm # обязательный шаг: pkg/ wasm-модулей
34
+ pnpm -F @meerrec/cli build
35
+ node packages/cli/dist/cli.js --version
36
+ # или из корня
37
+ pnpm cli convert report.docx -o report.pdf
38
+ ```
39
+
40
+ После установки пакета bin называется `doc-converter`:
41
+
42
+ ```bash
43
+ doc-converter convert report.docx -o report.pdf
44
+ ```
45
+
46
+ ## Рантаймы
47
+
48
+ CLI запускается на Node, Bun и Deno: общий код не импортирует
49
+ `node:worker_threads` и `node:os`, пул воркеров и чтение wasm-байтов спрятаны
50
+ за адаптером (`src/runtime.ts`). Bun идёт по ветке Node, Deno — по своей: пул
51
+ на веб-воркерах (`worker-deno.js`), wasm-байты через `import.meta.resolve`.
52
+
53
+ | Рантайм | Установленный пакет | Из монорепозитория |
54
+ |---|---|---|
55
+ | Node ≥ 20 | `doc-converter convert report.docx -o report.pdf` | `node packages/cli/dist/cli.js convert report.docx -o report.pdf` |
56
+ | Bun | `bunx @meerrec/cli convert report.docx -o report.pdf` | `bun packages/cli/dist/cli.js convert report.docx -o report.pdf` |
57
+ | Deno | `deno run --allow-read --allow-write npm:@meerrec/cli convert report.docx -o report.pdf` | `deno run --allow-read --allow-write packages/cli/dist/cli.js convert report.docx -o report.pdf` |
58
+
59
+ `bunx`/`npm:`-команды требуют публикации в npmjs.org (ADR-0027); пока пакет
60
+ доступен только в GitHub Packages, ставьте его npm'ом и запускайте bin
61
+ `doc-converter`. Для Deno хватает `--allow-read` (фикстуры, `package.json` и
62
+ wasm-модули) и `--allow-write` (выходной файл); сеть не нужна. Права
63
+ наследуются веб-воркерами, поэтому `batch` работает с теми же флагами.
64
+
65
+ `engines` объявляет только Node (`>=20`): совместимость с Bun и Deno
66
+ проверяет workflow `cli-runtimes.yml`.
67
+
68
+ ## Команды
69
+
70
+ ### `convert`
71
+
72
+ ```bash
73
+ doc-converter convert report.docx -o report.pdf
74
+ doc-converter convert report.docx -o report.md
75
+ doc-converter convert book.xlsx -o book.pdf --sheet 0
76
+ ```
77
+
78
+ `-o` может быть каталогом — тогда имя файла собирается из входа и формата:
79
+
80
+ ```bash
81
+ doc-converter convert report.docx -o ./out --format pdf # ./out/report.pdf
82
+ ```
83
+
84
+ ### `batch`
85
+
86
+ Входы — файлы, каталоги (обходятся рекурсивно) или glob-шаблоны. Файлы
87
+ конвертируются параллельно, пул воркеров раздаёт задачи по одному файлу на
88
+ воркер; wasm-модуль грузится в воркере один раз и переиспользуется.
89
+
90
+ ```bash
91
+ doc-converter batch ./in/*.xlsx --out ./pdf --workers 4
92
+ doc-converter batch ./in --out ./out --format pdf --workers 8 --scale 0.9
93
+ doc-converter batch './in/**/*.docx' --out ./out --format md
94
+ ```
95
+
96
+ Прогресс печатается в stderr: в терминале — перерисовываемая полоса, в пайпе
97
+ — построчный лог (`ok 5/12 ...`). `--quiet` выключает прогресс, итоговая
98
+ строка и ошибки остаются.
99
+
100
+ Имена выходных файлов — плоские (`<имя>.<формат>`); два входа с одинаковым
101
+ именем — ошибка до запуска воркеров. Существующий выход не перезаписывается
102
+ без `--force`.
103
+
104
+ ## Опции
105
+
106
+ | Опция | Команды | Смысл |
107
+ |---|---|---|
108
+ | `-o, --out <path>` | обе | выходной файл (`convert`) или каталог (`batch`) |
109
+ | `-f, --format <fmt>` | обе | `pdf`, `md`, `html`, `txt`; у `batch` по умолчанию `pdf` |
110
+ | `-w, --workers <n>` | `batch` | число воркеров, по умолчанию — ядра, не больше 8 |
111
+ | `-q, --quiet` | `batch` | без прогресса |
112
+ | `--force` | обе | перезаписывать существующие файлы |
113
+ | `--page-size <A4\|A3\|Letter\|Legal>` | обе | только XLSX |
114
+ | `--orientation <portrait\|landscape>` | обе | только XLSX |
115
+ | `--scale <factor>` | обе | только XLSX, например `0.8` |
116
+ | `--margins <top,right,bottom,left>` | обе | только XLSX, миллиметры |
117
+ | `--sheet <n>` | обе | только XLSX, лист с нуля; без неё книга целиком |
118
+
119
+ Коды возврата: `0` — успех, `1` — файлы не сконвертировались, `2` — ошибка
120
+ вызова (неизвестный флаг, неподдерживаемая пара, занятый выход).
121
+
122
+ ## Ограничения
123
+
124
+ - XLSX конвертируется только в PDF: Markdown/HTML/текст поддержаны лишь для
125
+ DOCX.
126
+ - У DOCX в PDF размер страницы, поля и ориентация берутся из `w:sectPr`, а не
127
+ из опций: страницы PDF — это страницы раскладки документа.
128
+ - `compress` PDF (в крейте `doc_converter_pdf` он включён по умолчанию) через
129
+ wasm не проброшен — флага сжатия в CLI нет.
130
+ - Легаси-форматы `.doc`/`.xls` не поддерживаются: нужен OOXML-пакет.
131
+ - Каталоги обходятся без скрытых подкаталогов.
132
+
133
+ ## Разработка
134
+
135
+ ```bash
136
+ pnpm -F @meerrec/cli build # tsc → dist/ (+ shebang +x)
137
+ pnpm -F @meerrec/cli test # vitest: аргументы, glob, пул, wasm-фикстуры, bin
138
+ pnpm -F @meerrec/cli typecheck
139
+ ```
140
+
141
+ Тесты `test/cli.e2e.spec.ts` запускают `dist/cli.js` и потому требуют сборки
142
+ (`turbo` собирает пакет перед `test`); при прямом `vitest` без `dist` файл
143
+ пропускается.
package/dist/args.d.ts ADDED
@@ -0,0 +1,48 @@
1
+ /**
2
+ * Разбор аргументов командной строки. Чистая функция без обращения к диску
3
+ * и сети: тесты дергают её напрямую, а `run` получает уже готовую команду.
4
+ *
5
+ * Своя реализация вместо `commander`/`yargs`: аргументов немного, а CLI
6
+ * должен запускаться на голом `node` без установки зависимостей, кроме
7
+ * самих wasm-модулей.
8
+ */
9
+ import type { PdfOptions } from '@meerrec/core';
10
+ import { type OutputFormat } from './formats.js';
11
+ import type { CliRuntime } from './runtime.js';
12
+ export interface ConvertCommand {
13
+ kind: 'convert';
14
+ input: string;
15
+ out: string;
16
+ /** `null` — формат берётся из расширения `--out`. */
17
+ format: OutputFormat | null;
18
+ force: boolean;
19
+ pdf: PdfOptions;
20
+ }
21
+ export interface BatchCommand {
22
+ kind: 'batch';
23
+ inputs: readonly string[];
24
+ outDir: string;
25
+ format: OutputFormat;
26
+ workers: number;
27
+ force: boolean;
28
+ quiet: boolean;
29
+ pdf: PdfOptions;
30
+ }
31
+ export type Command = ConvertCommand | BatchCommand | {
32
+ kind: 'help';
33
+ } | {
34
+ kind: 'version';
35
+ };
36
+ export declare const USAGE = "doc-converter \u2014 OOXML \u2192 PDF/Markdown/HTML/text\n\nUsage:\n doc-converter convert <input> -o <output> [options]\n doc-converter batch <input...> --out <dir> [options]\n doc-converter help | --version\n\nFormats:\n .docx \u2192 .pdf .md .html .txt\n .xlsx \u2192 .pdf\n\nConvert options:\n -o, --out <path> output file, or directory to name the file from the input\n -f, --format <format> output format when --out has no known extension\n --force overwrite existing output files\n\nBatch options:\n --out <dir> output directory (required)\n -f, --format <format> output format (default: pdf)\n -w, --workers <n> worker threads (default: cpu count, at most 8)\n -q, --quiet do not print progress\n --force overwrite existing output files\n\nPDF options (both commands):\n --page-size <A4|A3|Letter|Legal> XLSX only; DOCX keeps its section size\n --orientation <portrait|landscape> XLSX only\n --scale <factor> XLSX only, e.g. 0.8\n --fit-to-page XLSX only: fit the sheet on one page\n --fit-to-width <n> XLSX only: pages wide, 0 = unlimited\n --fit-to-height <n> XLSX only: pages tall, 0 = unlimited\n --margins <top,right,bottom,left> XLSX only, millimetres\n --sheet <n> XLSX only, 0-based; default is the whole book\n\nBatch inputs may be files, directories (searched for .docx/.xlsx recursively)\nor glob patterns like './in/**/*.xlsx'. Output files are written flat into\n--out as <name>.<format>; duplicate names are an error.\n\nExamples:\n doc-converter convert report.docx -o report.pdf\n doc-converter convert report.docx -o report.md\n doc-converter batch ./in/*.xlsx --out ./pdf --workers 4\n doc-converter batch ./in --out ./out --format pdf --workers 8 --scale 0.9\n";
37
+ /** Рантайм нужен только для умолчания `--workers`; остальное — чистый разбор. */
38
+ export type ParallelismSource = Pick<CliRuntime, 'availableParallelism'>;
39
+ export declare function parseArgs(argv: readonly string[], runtime?: ParallelismSource): Command;
40
+ /**
41
+ * Умолчание воркеров: по числу ядер, но не больше восьми — дальше выигрыша нет.
42
+ *
43
+ * CLI передаёт рантайм (Node/Bun — `os.availableParallelism`, Deno —
44
+ * `navigator.hardwareConcurrency`). Без рантайма (программный вызов, тесты)
45
+ * берётся `node:os`: его реализуют все три рантайма, включая Deno.
46
+ */
47
+ export declare function defaultWorkers(runtime?: ParallelismSource): number;
48
+ //# sourceMappingURL=args.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"args.d.ts","sourceRoot":"","sources":["../src/args.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAIH,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AAGhD,OAAO,EAAe,KAAK,YAAY,EAAE,MAAM,cAAc,CAAC;AAC9D,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAE/C,MAAM,WAAW,cAAc;IAC7B,IAAI,EAAE,SAAS,CAAC;IAChB,KAAK,EAAE,MAAM,CAAC;IACd,GAAG,EAAE,MAAM,CAAC;IACZ,qDAAqD;IACrD,MAAM,EAAE,YAAY,GAAG,IAAI,CAAC;IAC5B,KAAK,EAAE,OAAO,CAAC;IACf,GAAG,EAAE,UAAU,CAAC;CACjB;AAED,MAAM,WAAW,YAAY;IAC3B,IAAI,EAAE,OAAO,CAAC;IACd,MAAM,EAAE,SAAS,MAAM,EAAE,CAAC;IAC1B,MAAM,EAAE,MAAM,CAAC;IACf,MAAM,EAAE,YAAY,CAAC;IACrB,OAAO,EAAE,MAAM,CAAC;IAChB,KAAK,EAAE,OAAO,CAAC;IACf,KAAK,EAAE,OAAO,CAAC;IACf,GAAG,EAAE,UAAU,CAAC;CACjB;AAED,MAAM,MAAM,OAAO,GAAG,cAAc,GAAG,YAAY,GAAG;IAAE,IAAI,EAAE,MAAM,CAAA;CAAE,GAAG;IAAE,IAAI,EAAE,SAAS,CAAA;CAAE,CAAC;AAE7F,eAAO,MAAM,KAAK,83DA0CjB,CAAC;AAaF,iFAAiF;AACjF,MAAM,MAAM,iBAAiB,GAAG,IAAI,CAAC,UAAU,EAAE,sBAAsB,CAAC,CAAC;AAEzE,wBAAgB,SAAS,CAAC,IAAI,EAAE,SAAS,MAAM,EAAE,EAAE,OAAO,CAAC,EAAE,iBAAiB,GAAG,OAAO,CAgBvF;AAqID;;;;;;GAMG;AACH,wBAAgB,cAAc,CAAC,OAAO,CAAC,EAAE,iBAAiB,GAAG,MAAM,CAGlE"}
package/dist/args.js ADDED
@@ -0,0 +1,256 @@
1
+ /**
2
+ * Разбор аргументов командной строки. Чистая функция без обращения к диску
3
+ * и сети: тесты дергают её напрямую, а `run` получает уже готовую команду.
4
+ *
5
+ * Своя реализация вместо `commander`/`yargs`: аргументов немного, а CLI
6
+ * должен запускаться на голом `node` без установки зависимостей, кроме
7
+ * самих wasm-модулей.
8
+ */
9
+ import { availableParallelism } from 'node:os';
10
+ import { CliError } from './errors.js';
11
+ import { parseFormat } from './formats.js';
12
+ export const USAGE = `doc-converter — OOXML → PDF/Markdown/HTML/text
13
+
14
+ Usage:
15
+ doc-converter convert <input> -o <output> [options]
16
+ doc-converter batch <input...> --out <dir> [options]
17
+ doc-converter help | --version
18
+
19
+ Formats:
20
+ .docx → .pdf .md .html .txt
21
+ .xlsx → .pdf
22
+
23
+ Convert options:
24
+ -o, --out <path> output file, or directory to name the file from the input
25
+ -f, --format <format> output format when --out has no known extension
26
+ --force overwrite existing output files
27
+
28
+ Batch options:
29
+ --out <dir> output directory (required)
30
+ -f, --format <format> output format (default: pdf)
31
+ -w, --workers <n> worker threads (default: cpu count, at most 8)
32
+ -q, --quiet do not print progress
33
+ --force overwrite existing output files
34
+
35
+ PDF options (both commands):
36
+ --page-size <A4|A3|Letter|Legal> XLSX only; DOCX keeps its section size
37
+ --orientation <portrait|landscape> XLSX only
38
+ --scale <factor> XLSX only, e.g. 0.8
39
+ --fit-to-page XLSX only: fit the sheet on one page
40
+ --fit-to-width <n> XLSX only: pages wide, 0 = unlimited
41
+ --fit-to-height <n> XLSX only: pages tall, 0 = unlimited
42
+ --margins <top,right,bottom,left> XLSX only, millimetres
43
+ --sheet <n> XLSX only, 0-based; default is the whole book
44
+
45
+ Batch inputs may be files, directories (searched for .docx/.xlsx recursively)
46
+ or glob patterns like './in/**/*.xlsx'. Output files are written flat into
47
+ --out as <name>.<format>; duplicate names are an error.
48
+
49
+ Examples:
50
+ doc-converter convert report.docx -o report.pdf
51
+ doc-converter convert report.docx -o report.md
52
+ doc-converter batch ./in/*.xlsx --out ./pdf --workers 4
53
+ doc-converter batch ./in --out ./out --format pdf --workers 8 --scale 0.9
54
+ `;
55
+ export function parseArgs(argv, runtime) {
56
+ if (argv.length === 0)
57
+ return { kind: 'help' };
58
+ const command = argv[0];
59
+ if (command === 'help' || command === '--help' || command === '-h')
60
+ return { kind: 'help' };
61
+ if (command === 'version' || command === '--version' || command === '-V')
62
+ return { kind: 'version' };
63
+ const rest = argv.slice(1);
64
+ switch (command) {
65
+ case 'convert':
66
+ return toConvert(scan(rest));
67
+ case 'batch':
68
+ return toBatch(scan(rest), runtime);
69
+ default:
70
+ throw new CliError(`unknown command '${command}': expected 'convert', 'batch', 'help' or 'version'`);
71
+ }
72
+ }
73
+ function scan(args) {
74
+ const result = {
75
+ positionals: [],
76
+ out: null,
77
+ format: null,
78
+ workers: null,
79
+ force: false,
80
+ quiet: false,
81
+ pdf: {},
82
+ help: false,
83
+ };
84
+ let onlyPositionals = false;
85
+ for (let i = 0; i < args.length; i += 1) {
86
+ const arg = args[i];
87
+ if (onlyPositionals) {
88
+ result.positionals.push(arg);
89
+ continue;
90
+ }
91
+ if (arg === '--') {
92
+ onlyPositionals = true;
93
+ continue;
94
+ }
95
+ // `--option=value` и `--option value` равнозначны.
96
+ const eq = arg.startsWith('--') ? arg.indexOf('=') : -1;
97
+ const name = eq >= 0 ? arg.slice(0, eq) : arg;
98
+ const inline = eq >= 0 ? arg.slice(eq + 1) : null;
99
+ const take = () => {
100
+ if (inline !== null)
101
+ return inline;
102
+ i += 1;
103
+ const value = args[i];
104
+ if (value === undefined)
105
+ throw new CliError(`option '${name}' needs a value`);
106
+ return value;
107
+ };
108
+ switch (name) {
109
+ case '--help':
110
+ case '-h':
111
+ result.help = true;
112
+ break;
113
+ case '-o':
114
+ case '--out':
115
+ result.out = take();
116
+ break;
117
+ case '-f':
118
+ case '--format':
119
+ result.format = take();
120
+ break;
121
+ case '-w':
122
+ case '--workers':
123
+ result.workers = take();
124
+ break;
125
+ case '--force':
126
+ result.force = true;
127
+ break;
128
+ case '-q':
129
+ case '--quiet':
130
+ result.quiet = true;
131
+ break;
132
+ case '--page-size':
133
+ result.pdf.pageSize = parsePageSize(take());
134
+ break;
135
+ case '--orientation':
136
+ result.pdf.orientation = parseOrientation(take());
137
+ break;
138
+ case '--scale':
139
+ result.pdf.scale = parsePositiveFloat(take(), '--scale');
140
+ break;
141
+ case '--fit-to-page':
142
+ result.pdf.fitToPage = true;
143
+ break;
144
+ case '--fit-to-width':
145
+ result.pdf.fitToWidth = parseIndex(take(), '--fit-to-width');
146
+ break;
147
+ case '--fit-to-height':
148
+ result.pdf.fitToHeight = parseIndex(take(), '--fit-to-height');
149
+ break;
150
+ case '--margins':
151
+ result.pdf.margins = parseMargins(take());
152
+ break;
153
+ case '--sheet':
154
+ result.pdf.sheetIndex = parseIndex(take(), '--sheet');
155
+ break;
156
+ default:
157
+ if (name.startsWith('-') && name !== '-')
158
+ throw new CliError(`unknown option '${name}'`);
159
+ result.positionals.push(arg);
160
+ }
161
+ }
162
+ return result;
163
+ }
164
+ function toConvert(scanned) {
165
+ if (scanned.help)
166
+ return { kind: 'help' };
167
+ const input = scanned.positionals[0];
168
+ if (scanned.positionals.length === 0 || input === undefined) {
169
+ throw new CliError("'convert' needs an input file");
170
+ }
171
+ if (scanned.positionals.length > 1) {
172
+ throw new CliError("'convert' takes one input file; use 'batch' for several");
173
+ }
174
+ if (scanned.out === null)
175
+ throw new CliError("'convert' needs --out <file>");
176
+ return {
177
+ kind: 'convert',
178
+ input,
179
+ out: scanned.out,
180
+ format: scanned.format === null ? null : parseFormat(scanned.format),
181
+ force: scanned.force,
182
+ pdf: scanned.pdf,
183
+ };
184
+ }
185
+ function toBatch(scanned, runtime) {
186
+ if (scanned.help)
187
+ return { kind: 'help' };
188
+ if (scanned.positionals.length === 0)
189
+ throw new CliError("'batch' needs at least one input file, directory or glob");
190
+ if (scanned.out === null)
191
+ throw new CliError("'batch' needs --out <dir>");
192
+ const workers = scanned.workers === null ? defaultWorkers(runtime) : parseIndex(scanned.workers, '--workers');
193
+ if (workers < 1)
194
+ throw new CliError('--workers must be at least 1');
195
+ return {
196
+ kind: 'batch',
197
+ inputs: scanned.positionals,
198
+ outDir: scanned.out,
199
+ format: scanned.format === null ? 'pdf' : parseFormat(scanned.format),
200
+ workers,
201
+ force: scanned.force,
202
+ quiet: scanned.quiet,
203
+ pdf: scanned.pdf,
204
+ };
205
+ }
206
+ /**
207
+ * Умолчание воркеров: по числу ядер, но не больше восьми — дальше выигрыша нет.
208
+ *
209
+ * CLI передаёт рантайм (Node/Bun — `os.availableParallelism`, Deno —
210
+ * `navigator.hardwareConcurrency`). Без рантайма (программный вызов, тесты)
211
+ * берётся `node:os`: его реализуют все три рантайма, включая Deno.
212
+ */
213
+ export function defaultWorkers(runtime) {
214
+ const cores = runtime?.availableParallelism() ?? availableParallelism();
215
+ return Math.max(1, Math.min(8, cores));
216
+ }
217
+ function parsePageSize(value) {
218
+ const sizes = ['A4', 'A3', 'Letter', 'Legal'];
219
+ const found = sizes.find((size) => size.toLowerCase() === value.toLowerCase());
220
+ if (found === undefined)
221
+ throw new CliError(`unknown page size '${value}': expected ${sizes.join(', ')}`);
222
+ return found;
223
+ }
224
+ function parseOrientation(value) {
225
+ const lower = value.toLowerCase();
226
+ if (lower !== 'portrait' && lower !== 'landscape') {
227
+ throw new CliError(`unknown orientation '${value}': expected portrait or landscape`);
228
+ }
229
+ return lower;
230
+ }
231
+ function parsePositiveFloat(value, option) {
232
+ const parsed = Number(value);
233
+ if (!Number.isFinite(parsed) || parsed <= 0)
234
+ throw new CliError(`${option} must be a positive number, got '${value}'`);
235
+ return parsed;
236
+ }
237
+ function parseIndex(value, option) {
238
+ const parsed = Number(value);
239
+ if (!Number.isInteger(parsed) || parsed < 0) {
240
+ throw new CliError(`${option} must be a non-negative integer, got '${value}'`);
241
+ }
242
+ return parsed;
243
+ }
244
+ /** `--margins top,right,bottom,left` в миллиметрах. */
245
+ function parseMargins(value) {
246
+ const parts = value.split(',').map((part) => part.trim());
247
+ if (parts.length !== 4) {
248
+ throw new CliError(`--margins needs four comma-separated millimetres (top,right,bottom,left), got '${value}'`);
249
+ }
250
+ const [top, right, bottom, left] = parts.map((part) => Number(part));
251
+ if ([top, right, bottom, left].some((mm) => mm === undefined || !Number.isFinite(mm) || mm < 0)) {
252
+ throw new CliError(`--margins takes non-negative numbers, got '${value}'`);
253
+ }
254
+ return { top: top, right: right, bottom: bottom, left: left };
255
+ }
256
+ //# sourceMappingURL=args.js.map