@openmoca/moca-convert 0.0.0-stage → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/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 Modular Ontology & Content Assembly (MOCA) Standard 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,192 @@
1
- # Temporary Holding Version
1
+ # @openmoca/moca-convert
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
+ Creates MOCA packages from existing sources, including PDFs and YouTube
4
+ videos and playlists. Every node it writes is an OKF
5
+ concept document with a `type`, and the package id must be an absolute URI.
6
+
7
+ ```sh
8
+ moca-convert <input> -o <dir> --id <uri> [--title text] [--version semver] [--type type]
9
+ [--language bcp47] [--license spdx] [--from directory|markdown|obsidian|openapi|pdf|youtube]
10
+ [--exclude glob...] [--chunker operation|tag] [--min-description-ratio 0-1]
11
+ [--sources copy|link] [--max-pdf-mb n] [--max-pdf-pages n] [--pdf-timeout seconds]
12
+ [--force] [--strict] [--format text|json] [--log-file file]
13
+ ```
14
+
15
+ | Adapter | Input | Default `type` |
16
+ | --- | --- | --- |
17
+ | `directory` | A folder of Markdown, structure preserved: the folders become `structure.ttl` (parts and folder order), each file bound to its concept; `--no-structure` to leave it out | `Document` |
18
+ | `markdown` | One file or a glob; names from titles | `Document` |
19
+ | `obsidian` | A vault (has `.obsidian/`); wikilinks become Markdown links | `Note` |
20
+ | `openapi` | An OpenAPI 3.x document with real descriptions | `API Operation` or `API Tag` |
21
+ | `pdf` | A PDF, a folder of PDFs, or a folder with a `pdfs.json` | `Document` |
22
+ | `youtube` | A capture folder written by `moca-youtube` | `Video` |
23
+
24
+ - Existing frontmatter is kept byte for byte. A file without a `type` gets
25
+ `type` (and `title`, if missing) added at the top of its frontmatter.
26
+ - The adapter is detected from the input unless `--from` is given; ambiguous
27
+ input is refused, not guessed.
28
+ - Hidden files and folders (`.git/`, `.obsidian/`, Obsidian's `.trash/` of
29
+ deleted notes) and symbolic links in an input folder are not read.
30
+ - Obsidian wikilinks are rewritten in the note's body only, never in its
31
+ front matter, and each link target is percent-encoded.
32
+ - OpenAPI: each operation's parameters include its path's and those it
33
+ references (`$ref`). Schema references are expanded up to 1,000 objects a
34
+ schema; beyond that they are shown as `{"$ref": ...}`. Two operations whose
35
+ paths give the same file name get distinct files (`get-a-b.md`,
36
+ `get-a-b-2.md`).
37
+ - Output is written to a folder beside `-o`, read back with the reference
38
+ Reader, and only then moved into place. If it would be invalid, nothing is
39
+ written.
40
+ - `--force` replaces an output folder only when it holds a previous package
41
+ (it has a `moca.json`); it refuses any other folder. The previous package is
42
+ moved aside, the new one moved in, and only then is the old one deleted.
43
+ - `--log-file <file>` records the adapter, timings and any failure, on every
44
+ exit.
45
+
46
+ ## PDF
47
+
48
+ PDFs with a text layer become one node per section:
49
+
50
+ - Headings come from the PDF's bookmarks when they cover the document, and
51
+ otherwise from the type: sizes clearly larger than the body text are
52
+ heading levels, and a whole line in bold at body size is one level below.
53
+ A document is split at the first heading level that occurs more than once
54
+ (the sections of a chapter, or the chapters of a book); deeper headings stay
55
+ inside the node, where `moca-index --chunk headings` can split them.
56
+ - Running headers and footers, page numbers and small figure labels are
57
+ dropped. Paragraphs run on across columns and pages, words hyphenated at a
58
+ line end are rejoined, and bullets, numbered items and figure captions are
59
+ kept as lists and captions.
60
+ - Each node cites every page it came from as an RFC 3778 `page=` fragment,
61
+ with the printed page number (`p. 4-12`) as the note when the PDF has page
62
+ labels or prints numbers in its footer. `structure.ttl` keeps the documents
63
+ and their sections in order, and each node is bound to its section.
64
+ - `--sources copy` (the default) puts each PDF under `sources/`, so the
65
+ package is `self-contained-evidence`. `--sources link` cites each PDF by
66
+ its `url` instead, for PDFs too large to carry.
67
+ - A PDF without a text layer (a scan) is reported and left out; run OCR on
68
+ it first.
69
+ - A PDF over 256 MB or 2,000 pages, or that takes over 10 minutes to read, is
70
+ refused; `--max-pdf-mb`, `--max-pdf-pages` and `--pdf-timeout` raise the
71
+ limits.
72
+ - Text from the PDF itself (headings, paragraphs, page labels) is written as
73
+ text: characters Markdown would read as links or HTML are escaped. Page
74
+ labels are kept short and on one line.
75
+
76
+ A folder may list its documents, in order, in `pdfs.json`:
77
+
78
+ ```json
79
+ {
80
+ "title": "Workshop Manual",
81
+ "description": "Brakes and torque settings.",
82
+ "documents": [
83
+ { "file": "ch7.pdf", "title": "Chapter 7: Brakes", "url": "https://example.com/ch7.pdf", "sha256": "…" }
84
+ ]
85
+ }
86
+ ```
87
+
88
+ Only `file` is required: a regular file inside the folder, not a symbolic
89
+ link. `title` falls back to the PDF's own title. `url` is the published copy
90
+ that `--sources link` cites: an `http` or `https` URL with no user name,
91
+ password or `#fragment`, parsed and written back in its normal form. A file whose SHA-256 is
92
+ not `sha256` is refused, so a conversion never silently uses a changed
93
+ document. Without `pdfs.json`, every PDF in the folder is converted in path
94
+ order. moca-spec's [`scripts/fetch-pdfs.mjs`](https://github.com/openmoca/moca-spec/blob/main/scripts/fetch-pdfs.mjs) downloads the
95
+ listed files and pins their digests.
96
+
97
+ See [`examples/pdf`](https://github.com/openmoca/moca-spec/blob/main/examples/pdf).
98
+
99
+ ## YouTube
100
+
101
+ `moca-youtube` captures a video or a playlist with
102
+ [yt-dlp](https://github.com/yt-dlp/yt-dlp), which must be installed, and then
103
+ runs `moca-convert --from youtube` on the capture:
104
+
105
+ ```sh
106
+ moca-youtube <url> -o <dir> --id <uri> [--title text] [--version semver] [--type type]
107
+ [--language bcp47] [--license spdx] [--capture-dir dir] [--no-convert]
108
+ [--yt-dlp path] [--force] [--quiet]
109
+ ```
110
+
111
+ - Each video becomes one node: its description, and a transcript from its
112
+ captions grouped by chapter. The captions are written under `media/` as
113
+ WebVTT and the description under `sources/`, and the node cites each
114
+ chapter as a time range (`t=start,end`) and quotes the description, so the
115
+ package is `self-contained-evidence`. The node describes the video in
116
+ `moca.media`: its page's type (`text/html`), its length and its captions, so
117
+ the last chapter can run past the last caption.
118
+ - A playlist also gets `content/index.md` and a `structure.ttl` that keeps the
119
+ videos in playlist order.
120
+ - Captions the creator supplied in `--language` (default `en`) are preferred,
121
+ then YouTube's automatic ones. A video without captions is kept, without a
122
+ transcript, and reported.
123
+ - `--capture-dir` keeps the capture (`youtube-capture.json` and
124
+ `videos/<id>/`); converting it again gives the same package. Without it the
125
+ capture goes to a temporary directory.
126
+ - yt-dlp is run directly, without a shell, so this works on macOS, Linux and
127
+ Windows. Point at it with `--yt-dlp` or `$YT_DLP` when it is not on `PATH`.
128
+ It runs with `--ignore-config`, so your yt-dlp configuration files are not
129
+ used, and each run is stopped after 5 minutes.
130
+ - The URL must be on `youtube.com` (with `www.`, `m.` or `music.`) or
131
+ `youtu.be`. Video and playlist ids must be plain ids (letters, digits, `-`
132
+ and `_`); an entry with any other id is skipped and reported.
133
+ - When a capture is converted, it is checked as it is read: video ids, URLs
134
+ (parsed and rebuilt; `http` and `https` only), the upload date and the
135
+ caption language. A value that fails is left out, or the capture is
136
+ refused.
137
+
138
+ See [`examples/youtube`](https://github.com/openmoca/moca-spec/blob/main/examples/youtube).
139
+
140
+ ## Develop
141
+
142
+ The tests read moca-spec's examples and fixtures. Check out moca-spec beside
143
+ this repository, or set `MOCA_SPEC_DIR`. CI uses the tags pinned at the top of `.github/workflows/test.yml`
144
+ (`MOCA_SPEC_REF` and the like); check out the same tags to match it.
145
+
146
+ ```sh
147
+ npm install
148
+ npm test
149
+ ```
150
+
151
+ ## Release
152
+
153
+ 1. Publish `@openmoca/moca-core` first if it changed.
154
+ 2. Name its released range in `package.json` in place of the `file:` path,
155
+ and run `npm install`.
156
+ 3. Add a dated section to [CHANGELOG.md](CHANGELOG.md) and update the version.
157
+ 4. Point the `MOCA_*_REF` pins in `.github/workflows/test.yml` at the release tags
158
+ ([moca-spec docs/releasing.md](https://github.com/openmoca/moca-spec/blob/main/docs/releasing.md#moving-the-pins)).
159
+ 5. `npm test` passes.
160
+ 6. Tag `vX.Y.Z` on main and publish a GitHub release whose notes are the
161
+ changelog section. The release workflow publishes to npm through trusted
162
+ publishing, with provenance; it stops if the tag is not on main, the
163
+ version does not match, or `@openmoca/moca-core` is not on npm.
164
+
165
+ ## Standards
166
+
167
+ What moca-convert reads and writes, and how strongly. **Follow** means it
168
+ implements the standard and the tests check it where they can.
169
+
170
+ | Standard | Where | How strongly |
171
+ | --- | --- | --- |
172
+ | MOCA ([moca-spec](https://github.com/openmoca/moca-spec)) 0.7 | every package it writes, checked with the reference Reader | follow |
173
+ | [Open Knowledge Format](https://github.com/GoogleCloudPlatform/open-knowledge-format/blob/ad30107c31c06aec8a7d5636e0d1058118604e6f/SPEC.md) v0.2, pinned at commit `ad30107` | `content/`: each node an OKF concept document with a `type` | follow (pinned) |
174
+ | [CommonMark](https://spec.commonmark.org/) | node bodies; text from input is escaped, link destinations percent-encoded | follow |
175
+ | [YAML 1.2](https://yaml.org/spec/1.2.2/) | front matter, and OpenAPI documents in YAML | follow |
176
+ | [SKOS](https://www.w3.org/TR/skos-reference/) and [Dublin Core terms](https://www.dublincore.org/specifications/dublin-core/dcmi-terms/) in [RDF 1.1 Turtle](https://www.w3.org/TR/turtle/) | `structure.ttl`; IRIs percent-encoded ([RFC 3987](https://www.rfc-editor.org/rfc/rfc3987)) | follow (the named terms) |
177
+ | [RFC 3778](https://www.rfc-editor.org/rfc/rfc3778) `page=` fragments | PDF evidence | follow |
178
+ | [Media Fragments](https://www.w3.org/TR/media-frags/) `t=` | YouTube evidence | follow |
179
+ | [WebVTT](https://www.w3.org/TR/webvtt1/) | YouTube captions under `media/` | follow |
180
+ | [OpenAPI 3.x](https://spec.openapis.org/oas/v3.1.0) | the `openapi` adapter's input; local `$ref` only | follow (the parts it reads) |
181
+ | [WHATWG URL](https://url.spec.whatwg.org/) | URLs from input, parsed and rebuilt; `http` and `https` only | follow |
182
+ | [BCP 47](https://www.rfc-editor.org/info/bcp47) | `--language`, and caption languages | follow |
183
+
184
+ Built with the help of AI assistants; every change is reviewed and accepted by the maintainer.
185
+
186
+ ## Licence
187
+
188
+ Apache-2.0. See [LICENSE](LICENSE) and [NOTICE](NOTICE).
189
+
190
+ OpenMOCA™ is a trade mark of PI & Mash Solutions Ltd. The licence covers the
191
+ code, not the name: see the
192
+ [trade mark policy](https://github.com/openmoca/moca-spec/blob/main/TRADEMARKS.md).
@@ -0,0 +1,198 @@
1
+ #!/usr/bin/env node
2
+ import { Command, InvalidArgumentError } from 'commander';
3
+ import { appendFileSync, readFileSync, writeFileSync } from 'node:fs';
4
+ import { formatText, formatJson } from '@openmoca/moca-core';
5
+ import { resolveInputTarget, UsageError } from '../lib/target.js';
6
+ import { resolveAdapterName } from '../lib/detect.js';
7
+ import { getAdapter } from '../lib/adapters/index.js';
8
+ import { writeDraft, ConversionFailedError } from '../lib/write.js';
9
+
10
+ const ADAPTER_ONLY_FLAGS = {
11
+ exclude: 'obsidian',
12
+ minDescriptionRatio: 'openapi',
13
+ chunker: 'openapi',
14
+ sources: 'pdf',
15
+ maxPdfMb: 'pdf',
16
+ maxPdfPages: 'pdf',
17
+ pdfTimeout: 'pdf',
18
+ };
19
+
20
+ function parsePositive(value) {
21
+ if (!/^[0-9]+$/.test(value) || Number(value) < 1 || !Number.isSafeInteger(Number(value))) {
22
+ throw new InvalidArgumentError('must be a positive whole number.');
23
+ }
24
+ return Number(value);
25
+ }
26
+
27
+ function parseRatio(value) {
28
+ const num = Number(value);
29
+ if (Number.isNaN(num) || num < 0 || num > 1) {
30
+ throw new InvalidArgumentError('must be a number between 0 and 1.');
31
+ }
32
+ return num;
33
+ }
34
+
35
+ // npm always includes package.json in a published tarball, regardless of the
36
+ // "files" field, so reading the version from it works once installed.
37
+ const { version } = JSON.parse(
38
+ readFileSync(new URL('../package.json', import.meta.url), 'utf8')
39
+ );
40
+
41
+ const program = new Command();
42
+ program
43
+ .name('moca-convert')
44
+ .description('Create a MOCA package, with an OKF content bundle, from a directory, Markdown files, an Obsidian vault, a suitable OpenAPI document, PDFs, or a YouTube capture folder.')
45
+ // `--version <semver>` already sets the *generated package's* version, so the
46
+ // CLI's own version is exposed as --cli-version rather than redefining it.
47
+ .version(version, '-V, --cli-version', "output moca-convert's own version")
48
+ .argument('<input>', 'source file or directory to convert')
49
+ .requiredOption('-o, --output <dir>', 'output package directory')
50
+ .requiredOption('--id <uri>', 'package id: an absolute URI, e.g. https://example.com/kb/support')
51
+ .option('--title <string>', 'manifest title for the converted package')
52
+ .option('--version <semver>', 'manifest version for the converted package', '1.0.0')
53
+ .option('--type <type>', 'OKF type for nodes that lack one (default per adapter: Document, Note, API Operation)')
54
+ .option('--language <bcp47>', 'default content language, e.g. en')
55
+ .option('--license <spdx>', 'SPDX license expression for the package')
56
+ .option('--from <format>', 'source format: directory|markdown|obsidian|openapi|pdf|youtube (auto-detected if omitted)')
57
+ .option('--exclude <glob...>', 'obsidian only: note paths to exclude from conversion (still indexed for wikilink resolution)')
58
+ .option('--min-description-ratio <ratio>', 'openapi only: minimum fraction of operations needing a summary/description, 0-1 (default 0.5)', parseRatio)
59
+ .option('--chunker <mode>', 'openapi only: operation|tag content-node grouping (default operation)')
60
+ .option('--sources <mode>', 'pdf only: copy the PDFs into sources/ (copy, the default) or cite each by its pdfs.json url (link)')
61
+ .option('--max-pdf-mb <n>', 'pdf only: the largest PDF to read, in MB (default 256)', parsePositive)
62
+ .option('--max-pdf-pages <n>', 'pdf only: the most pages a PDF may have (default 2000)', parsePositive)
63
+ .option('--pdf-timeout <seconds>', 'pdf only: the longest one PDF may take to read (default 600)', parsePositive)
64
+ .option('--no-structure', 'directory only: do not write structure.ttl from the folders, or bind nodes to it')
65
+ .option('--force', 'replace the output directory when it holds a previous package', false)
66
+ .option('--strict', 'escalate warning-level output-validation findings to errors', false)
67
+ .option('--format <fmt>', 'summary output format: text|json', 'text')
68
+ .option('--report <file>', 'write the formatted summary to a file (in addition to console output)')
69
+ .option('--log-file <file>', 'write a full debug trace (pass timings) regardless of verbosity')
70
+ .option('-v, --verbose', 'increase console verbosity (repeatable)', (_, prev) => prev + 1, 0)
71
+ .option('-q, --quiet', 'suppress non-error console output', false)
72
+ .option('--no-color', 'disable colored output')
73
+ .action(async (input, options) => {
74
+ await run(input, options);
75
+ // The log file is written by now; exit even if a library left a handle open.
76
+ process.exit(process.exitCode ?? 0);
77
+ });
78
+
79
+ // Commander's own usage errors (missing required options, unknown flags,
80
+ // --help) default to exit code 1; override so they participate in the same
81
+ // 0/2 usage-error convention as everything this CLI throws itself.
82
+ program.exitOverride();
83
+
84
+ program.parseAsync(process.argv).catch((err) => {
85
+ if (err.code && err.code.startsWith('commander.')) {
86
+ process.exit(err.code === 'commander.helpDisplayed' ? 0 : 2);
87
+ }
88
+ throw err;
89
+ });
90
+
91
+ function makeLogger(options) {
92
+ const lines = [];
93
+ return {
94
+ log: (line) => {
95
+ lines.push(line);
96
+ if (options.verbose > 0) console.error(`[trace] ${line}`);
97
+ },
98
+ flush: () => {
99
+ if (options.logFile) {
100
+ appendFileSync(options.logFile, lines.join('\n') + '\n');
101
+ }
102
+ },
103
+ };
104
+ }
105
+
106
+ function writeReport(options, formatted) {
107
+ if (options.report) {
108
+ writeFileSync(options.report, formatted);
109
+ }
110
+ if (!options.quiet && (!options.report || options.format === 'text')) {
111
+ console.log(formatted);
112
+ }
113
+ }
114
+
115
+ async function run(input, options) {
116
+ const logger = makeLogger(options);
117
+ try {
118
+ const target = resolveInputTarget(input);
119
+ const adapterName = resolveAdapterName(target, options.from);
120
+ assertAdapterSpecificFlags(adapterName, options);
121
+ const adapter = getAdapter(adapterName);
122
+ logger.log(`adapter ${adapterName}`);
123
+ const started = performance.now();
124
+
125
+ const draft = await adapter.convert({
126
+ inputPath: input,
127
+ options: {
128
+ id: options.id,
129
+ title: options.title,
130
+ version: options.version,
131
+ exclude: options.exclude,
132
+ minDescriptionRatio: options.minDescriptionRatio,
133
+ chunker: options.chunker,
134
+ sources: options.sources,
135
+ ...(options.maxPdfMb ? { maxPdfBytes: options.maxPdfMb * 1024 * 1024 } : {}),
136
+ ...(options.maxPdfPages ? { maxPdfPages: options.maxPdfPages } : {}),
137
+ ...(options.pdfTimeout ? { pdfTimeoutMs: options.pdfTimeout * 1000 } : {}),
138
+ structure: options.structure,
139
+ type: options.type,
140
+ language: options.language,
141
+ license: options.license,
142
+ },
143
+ });
144
+
145
+ logger.log(`converted ${draft.contentNodes.length} content node(s) in ${Math.round(performance.now() - started)} ms`);
146
+ const { findings, digest } = await writeDraft({
147
+ draft,
148
+ outDir: options.output,
149
+ force: options.force,
150
+ strict: options.strict,
151
+ onLog: logger.log,
152
+ });
153
+
154
+ logger.log(`wrote ${options.output} in ${Math.round(performance.now() - started)} ms in all`);
155
+ if (!options.quiet) {
156
+ console.log(`Wrote ${options.output} (${draft.contentNodes.length} content node(s), ${draft.warnings.length} warning(s))\n${digest}`);
157
+ }
158
+ for (const warning of draft.warnings) {
159
+ console.error(`moca-convert: WARNING ${warning.code} ${warning.file ? `${warning.file}: ` : ''}${warning.message}`);
160
+ }
161
+ if (findings.length > 0) {
162
+ writeReport(options, formatFindings(findings, options.format));
163
+ }
164
+ process.exitCode = 0;
165
+ } catch (err) {
166
+ // Set the exit code and return, so the finally block below writes the log
167
+ // file on every path.
168
+ if (err instanceof UsageError) {
169
+ console.error(`moca-convert: ${err.message}`);
170
+ process.exitCode = 2;
171
+ return;
172
+ }
173
+ if (err instanceof ConversionFailedError) {
174
+ console.error(`moca-convert: ${err.message}`);
175
+ writeReport(options, formatFindings(err.findings, options.format));
176
+ process.exitCode = 1;
177
+ return;
178
+ }
179
+ logger.log(`failed: ${err?.stack ?? err}`);
180
+ console.error(`moca-convert: failed: ${err?.message ?? err}`);
181
+ process.exitCode = 1;
182
+ } finally {
183
+ logger.flush();
184
+ }
185
+ }
186
+
187
+ function assertAdapterSpecificFlags(adapterName, options) {
188
+ for (const [flag, owner] of Object.entries(ADAPTER_ONLY_FLAGS)) {
189
+ if (options[flag] !== undefined && adapterName !== owner) {
190
+ throw new UsageError(`--${flag} is only valid with the ${owner} adapter (resolved adapter: ${adapterName}).`);
191
+ }
192
+ }
193
+ }
194
+
195
+ function formatFindings(findings, format) {
196
+ if (format === 'json') return formatJson(findings);
197
+ return formatText(findings);
198
+ }