@lincyaw/cli 0.0.0-stage → 1.0.0-rc.1
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 +202 -0
- package/README.md +51 -2
- package/bin/presmium.mjs +12 -0
- package/package.json +42 -3
- package/src/check.ts +91 -0
- package/src/cli.ts +399 -0
- package/src/dev-host.ts +30 -0
- package/src/index.ts +2 -0
- package/src/messages.ts +219 -0
- package/src/testing.ts +24 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
package/README.md
CHANGED
|
@@ -1,3 +1,52 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @lincyaw/cli
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
The `presmium` command: `new`, `check`, `ir`, `build`, `dev` and `serve` for Presmium documents and workspaces.
|
|
4
|
+
|
|
5
|
+
Part of [Presmium](https://github.com/Lincyaw/presmium), which turns structured teaching documents into web pages, slides, Jupyter notebooks and narrated lectures.
|
|
6
|
+
|
|
7
|
+
## Install
|
|
8
|
+
|
|
9
|
+
Most people install the `presmium` package, which brings this command with the renderers and the official plugins:
|
|
10
|
+
|
|
11
|
+
```sh
|
|
12
|
+
pnpm add -g @lincyaw/presmium
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
In a project that picks its own renderers and plugins, install the CLI with them (Node.js 22.19 or later):
|
|
16
|
+
|
|
17
|
+
```sh
|
|
18
|
+
pnpm add -D @lincyaw/cli @lincyaw/web @lincyaw/render-slides @lincyaw/render-notebook
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
## Commands
|
|
22
|
+
|
|
23
|
+
| Command | What it does |
|
|
24
|
+
|---|---|
|
|
25
|
+
| `presmium check [deck]` | Compile and run the checks and publication checks (`--json`, `--update-lock`, `--env`, `--audience`, `--external-links`) |
|
|
26
|
+
| `presmium ir [deck]` | Print the IR as JSON (`--out`) |
|
|
27
|
+
| `presmium build [deck]` | Build `dist/ir.json` and `dist/<renderer>/` (`--to`, `--out`, `--audience`); at a workspace root, the workspace site in `dist/web/` |
|
|
28
|
+
| `presmium dev [deck]` | Dev servers that update on save (`--to`, `--out`, `--server-port`, `--allow`) |
|
|
29
|
+
| `presmium new [dir]` | A new lecture, workspace or plugin project (`--type`, `--title`, `--name`, `--no-git`); from `create-presmium`, which the `presmium` package brings |
|
|
30
|
+
| `presmium serve [dir]` | The workspace service, on this machine: the documents and their sites, compiled on demand (`--port`, `--host`, `--operator-dir`, `--preview-origin`) |
|
|
31
|
+
| `presmium studio [dir]` | The workbench (experimental), from `@lincyaw/studio` installed in the project (`--port`, `--host`); installed globally, it is `presmium-studio` |
|
|
32
|
+
|
|
33
|
+
`[deck]` is a directory with `lecture.json` or an entry file, by default the current directory. Exit codes: 0 no errors, 1 error findings, 2 usage or internal error. `presmium --help` lists every option.
|
|
34
|
+
|
|
35
|
+
## Testing plugins
|
|
36
|
+
|
|
37
|
+
`@lincyaw/cli/testing` runs the real command in a child process, for integration tests:
|
|
38
|
+
|
|
39
|
+
```ts
|
|
40
|
+
import { presmium } from '@lincyaw/cli/testing'
|
|
41
|
+
|
|
42
|
+
const { code, stdout } = await presmium(dir, ['build', '--to', 'web'])
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
## Documentation
|
|
46
|
+
|
|
47
|
+
- [Author guide](https://github.com/Lincyaw/presmium/blob/main/site/guide/locales/en/lecture.json)
|
|
48
|
+
- [Plugin guide](https://github.com/Lincyaw/presmium/blob/main/site/plugins/locales/en/lecture.json)
|
|
49
|
+
|
|
50
|
+
## License
|
|
51
|
+
|
|
52
|
+
Apache-2.0
|
package/bin/presmium.mjs
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { createJiti } from 'jiti'
|
|
3
|
+
|
|
4
|
+
const emitWarning = process.emitWarning
|
|
5
|
+
process.emitWarning = (warning, ...args) => {
|
|
6
|
+
const code = typeof args[0] === 'object' ? args[0]?.code : args[1]
|
|
7
|
+
if (code !== 'DEP0040') emitWarning.call(process, warning, ...args)
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
const jiti = createJiti(import.meta.url)
|
|
11
|
+
const { main } = await jiti.import('../src/cli.ts')
|
|
12
|
+
process.exitCode = await main(process.argv.slice(2))
|
package/package.json
CHANGED
|
@@ -1,6 +1,45 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lincyaw/cli",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "1.0.0-rc.1",
|
|
4
|
+
"description": "The presmium command: build, dev, ir, check and serve for Presmium documents",
|
|
5
|
+
"license": "Apache-2.0",
|
|
6
|
+
"repository": {
|
|
7
|
+
"type": "git",
|
|
8
|
+
"url": "git+https://github.com/Lincyaw/presmium.git",
|
|
9
|
+
"directory": "packages/cli"
|
|
10
|
+
},
|
|
11
|
+
"homepage": "https://github.com/Lincyaw/presmium/tree/main/packages/cli#readme",
|
|
12
|
+
"bugs": "https://github.com/Lincyaw/presmium/issues",
|
|
13
|
+
"keywords": [
|
|
14
|
+
"presmium",
|
|
15
|
+
"cli",
|
|
16
|
+
"myst",
|
|
17
|
+
"slides"
|
|
18
|
+
],
|
|
19
|
+
"type": "module",
|
|
20
|
+
"engines": {
|
|
21
|
+
"node": ">=22.19"
|
|
22
|
+
},
|
|
23
|
+
"publishConfig": {
|
|
24
|
+
"access": "public"
|
|
25
|
+
},
|
|
26
|
+
"bin": {
|
|
27
|
+
"presmium": "./bin/presmium.mjs"
|
|
28
|
+
},
|
|
29
|
+
"exports": {
|
|
30
|
+
".": "./src/index.ts",
|
|
31
|
+
"./testing": "./src/testing.ts"
|
|
32
|
+
},
|
|
33
|
+
"files": [
|
|
34
|
+
"bin",
|
|
35
|
+
"src"
|
|
36
|
+
],
|
|
37
|
+
"dependencies": {
|
|
38
|
+
"jiti": "^2.7.0",
|
|
39
|
+
"@lincyaw/kernel": "1.0.0-rc.1",
|
|
40
|
+
"@lincyaw/compiler": "1.0.0-rc.1",
|
|
41
|
+
"@lincyaw/server": "1.0.0-rc.1",
|
|
42
|
+
"@lincyaw/workspace": "1.0.0-rc.1",
|
|
43
|
+
"@lincyaw/skills": "1.0.0-rc.1"
|
|
44
|
+
}
|
|
6
45
|
}
|
package/src/check.ts
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
import { mkdir, readFile, writeFile } from 'node:fs/promises'
|
|
2
|
+
import { dirname, join } from 'node:path'
|
|
3
|
+
import { ANCHOR_LOCK_PATH, errorMessage } from '@lincyaw/kernel'
|
|
4
|
+
import type { AnchorString, Finding } from '@lincyaw/kernel'
|
|
5
|
+
import { checkContext, Compiler, sortFindings } from '@lincyaw/compiler'
|
|
6
|
+
import type { Compilation, CompilerOptions } from '@lincyaw/compiler'
|
|
7
|
+
|
|
8
|
+
export interface CheckOptions {
|
|
9
|
+
deck: string
|
|
10
|
+
updateLock?: boolean
|
|
11
|
+
compiler?: CompilerOptions
|
|
12
|
+
environments?: boolean
|
|
13
|
+
externalLinks?: boolean
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export interface LockUpdate {
|
|
17
|
+
file: string
|
|
18
|
+
anchors: number
|
|
19
|
+
changed: boolean
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export interface CheckResult {
|
|
23
|
+
entry: string
|
|
24
|
+
findings: Finding[]
|
|
25
|
+
lock?: LockUpdate
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export async function runCheck(options: CheckOptions): Promise<CheckResult> {
|
|
29
|
+
const compiler = new Compiler(options.deck, options.compiler)
|
|
30
|
+
let compilation = await compiler.compile()
|
|
31
|
+
const entryText = await readFile(compilation.entry, 'utf8')
|
|
32
|
+
const findings: Finding[] = []
|
|
33
|
+
const fail = (message: string, line: number) =>
|
|
34
|
+
findings.push({ checkId: 'presmium.plugins', severity: 'error', message, source: { file: compilation.entry, line } })
|
|
35
|
+
|
|
36
|
+
let lock: LockUpdate | undefined
|
|
37
|
+
if (options.updateLock) {
|
|
38
|
+
lock = await updateLock(compilation, (name, error) => fail(`plugin "${name}" failed to list anchors: ${errorMessage(error)}`, jsonLine(entryText, name)))
|
|
39
|
+
compilation = await compiler.compile()
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
findings.push(...await compilation.check({ externalLinks: options.externalLinks }))
|
|
43
|
+
if (options.environments) findings.push(...await probeEnvironments(compilation, entryText))
|
|
44
|
+
const all = [...compilation.doc.diagnostics, ...findings].map(f => f.source ? f : { ...f, source: { file: compilation.entry, line: 1 } })
|
|
45
|
+
return { entry: compilation.entry, findings: sortFindings(all), lock }
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export async function probeEnvironments(compilation: Compilation, text: string): Promise<Finding[]> {
|
|
49
|
+
const findings: Finding[] = []
|
|
50
|
+
for (const { name, spec, provider, context } of compilation.environments) {
|
|
51
|
+
let reason: string | undefined
|
|
52
|
+
try {
|
|
53
|
+
reason = await provider.probe?.(name, spec, context)
|
|
54
|
+
} catch (error) {
|
|
55
|
+
reason = errorMessage(error)
|
|
56
|
+
}
|
|
57
|
+
if (reason) findings.push({ checkId: 'presmium.execute', severity: 'error', message: `environment "${name}" (${spec.kind}) is not reachable: ${reason}`, source: { file: compilation.entry, line: jsonLine(text, name) } })
|
|
58
|
+
}
|
|
59
|
+
return findings
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
async function updateLock(compilation: Compilation, onError: (plugin: string, error: unknown) => void): Promise<LockUpdate> {
|
|
63
|
+
const file = join(compilation.deckDir, ANCHOR_LOCK_PATH)
|
|
64
|
+
const before = await readFile(file, 'utf8').catch(() => undefined)
|
|
65
|
+
const ctx = checkContext(compilation)
|
|
66
|
+
const anchors = new Set<AnchorString>()
|
|
67
|
+
let complete = true
|
|
68
|
+
for (const { name, plugin } of compilation.plugins) {
|
|
69
|
+
try {
|
|
70
|
+
for (const anchor of await plugin?.anchors?.(ctx) ?? []) anchors.add(anchor)
|
|
71
|
+
} catch (error) {
|
|
72
|
+
complete = false
|
|
73
|
+
onError(name, error)
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
const { lock } = compilation
|
|
77
|
+
for (const anchor of [...anchors].sort()) lock.record(anchor, await compilation.resolvers.resolve(anchor, ctx.src, lock.get(anchor)))
|
|
78
|
+
if (complete) lock.retain(anchors)
|
|
79
|
+
const text = lock.serialize()
|
|
80
|
+
if (text !== before) {
|
|
81
|
+
await mkdir(dirname(file), { recursive: true })
|
|
82
|
+
await writeFile(file, text)
|
|
83
|
+
}
|
|
84
|
+
return { file, anchors: lock.size, changed: text !== before }
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** JSON property locations are diagnostic hints; entity paths are supplied by document validation. */
|
|
88
|
+
function jsonLine(text: string, property: string): number {
|
|
89
|
+
const index = text.indexOf(JSON.stringify(property))
|
|
90
|
+
return index < 0 ? 1 : text.slice(0, index).split("\n").length
|
|
91
|
+
}
|
package/src/cli.ts
ADDED
|
@@ -0,0 +1,399 @@
|
|
|
1
|
+
import { existsSync, statSync } from 'node:fs'
|
|
2
|
+
import { mkdir, writeFile } from 'node:fs/promises'
|
|
3
|
+
import { createRequire } from 'node:module'
|
|
4
|
+
import { dirname, join, relative, resolve } from 'node:path'
|
|
5
|
+
import { fileURLToPath, pathToFileURL } from 'node:url'
|
|
6
|
+
import { parseArgs } from 'node:util'
|
|
7
|
+
import { createJiti } from 'jiti'
|
|
8
|
+
import { APPROVAL_KINDS, errorMessage } from '@lincyaw/kernel'
|
|
9
|
+
import { bracketIPv6, ffmpegInstallCommand, findFfmpeg, irRevision, lanAddresses } from '@lincyaw/kernel/node'
|
|
10
|
+
import type { ApprovalKind, Finding, Severity } from '@lincyaw/kernel'
|
|
11
|
+
import { build, Compiler, dev, resolveEntry } from '@lincyaw/compiler'
|
|
12
|
+
import type { BuildReport, Compilation, RunStats } from '@lincyaw/compiler'
|
|
13
|
+
import { isAnyAddress, isLoopback, serverConfigKey, servedDocument, startServer } from '@lincyaw/server'
|
|
14
|
+
import type { ApprovalPolicy } from '@lincyaw/server'
|
|
15
|
+
import { buildWorkspace, isWorkspaceRoot, serveWorkspace } from '@lincyaw/workspace'
|
|
16
|
+
import type { WorkspaceBuild } from '@lincyaw/workspace'
|
|
17
|
+
import { runCheck } from './check.ts'
|
|
18
|
+
import type { CheckResult } from './check.ts'
|
|
19
|
+
import { devHost } from './dev-host.ts'
|
|
20
|
+
import { CLI_MESSAGES, systemLocale } from './messages.ts'
|
|
21
|
+
|
|
22
|
+
const BUNDLED = fileURLToPath(new URL('..', import.meta.url))
|
|
23
|
+
const PRESMIUM_BIN = fileURLToPath(new URL('../bin/presmium.mjs', import.meta.url))
|
|
24
|
+
|
|
25
|
+
export interface MainOptions {
|
|
26
|
+
/** The package whose dependencies hold the renderers and plugins a document does not install itself. */
|
|
27
|
+
bundled?: string
|
|
28
|
+
/** The presmium command that presmium studio starts. */
|
|
29
|
+
bin?: string
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
const t = CLI_MESSAGES[systemLocale()]
|
|
33
|
+
|
|
34
|
+
const OPTIONS = {
|
|
35
|
+
'build': ['to', 'out', 'audience'],
|
|
36
|
+
'dev': ['to', 'out', 'server-port', 'allow'],
|
|
37
|
+
'ir': ['out'],
|
|
38
|
+
'check': ['json', 'update-lock', 'env', 'audience', 'external-links'],
|
|
39
|
+
'serve': ['port', 'host', 'operator-dir', 'preview-origin', 'public-url'],
|
|
40
|
+
} as const
|
|
41
|
+
|
|
42
|
+
type Name = keyof typeof OPTIONS
|
|
43
|
+
|
|
44
|
+
interface Command {
|
|
45
|
+
name: Name
|
|
46
|
+
entry: string
|
|
47
|
+
workspace?: string
|
|
48
|
+
to?: string[]
|
|
49
|
+
out?: string
|
|
50
|
+
json: boolean
|
|
51
|
+
updateLock: boolean
|
|
52
|
+
env: boolean
|
|
53
|
+
audience?: string
|
|
54
|
+
externalLinks: boolean
|
|
55
|
+
serverPort?: number
|
|
56
|
+
allow: ApprovalKind[]
|
|
57
|
+
operatorDir?: string
|
|
58
|
+
port?: number
|
|
59
|
+
listenAddress?: string
|
|
60
|
+
previewOrigins: string[]
|
|
61
|
+
publicUrl?: string
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export async function main(argv: string[], options: MainOptions = {}): Promise<number> {
|
|
65
|
+
const bundled = options.bundled ?? BUNDLED
|
|
66
|
+
if (argv[0] === 'new') return runNewCommand(argv.slice(1), bundled)
|
|
67
|
+
if (argv[0] === 'skills') return (await import('@lincyaw/skills')).main(argv.slice(1))
|
|
68
|
+
if (argv[0] === 'studio') return runStudioCommand(argv.slice(1), bundled, options.bin ?? PRESMIUM_BIN)
|
|
69
|
+
let command: Command | 'help'
|
|
70
|
+
try {
|
|
71
|
+
command = parseCommand(argv)
|
|
72
|
+
} catch (error) {
|
|
73
|
+
process.stderr.write(`presmium: ${errorMessage(error)}\n\n${t.usage}\n`)
|
|
74
|
+
return 2
|
|
75
|
+
}
|
|
76
|
+
if (command === 'help') {
|
|
77
|
+
process.stdout.write(`${t.usage}\n`)
|
|
78
|
+
return 0
|
|
79
|
+
}
|
|
80
|
+
try {
|
|
81
|
+
switch (command.name) {
|
|
82
|
+
case 'check': return await runCheckCommand(command, bundled)
|
|
83
|
+
case 'ir': return await runIrCommand(command, bundled)
|
|
84
|
+
case 'build': return await runBuildCommand(command, bundled)
|
|
85
|
+
case 'dev': return await runDevCommand(command, bundled)
|
|
86
|
+
case 'serve': return await runServeCommand(command, bundled)
|
|
87
|
+
}
|
|
88
|
+
} catch (error) {
|
|
89
|
+
process.stderr.write(`presmium: ${errorMessage(error)}\n`)
|
|
90
|
+
return 2
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
function parseCommand(argv: string[]): Command | 'help' {
|
|
95
|
+
const { values, positionals } = parseArgs({
|
|
96
|
+
args: argv,
|
|
97
|
+
allowPositionals: true,
|
|
98
|
+
options: {
|
|
99
|
+
'to': { type: 'string' },
|
|
100
|
+
'out': { type: 'string' },
|
|
101
|
+
'json': { type: 'boolean', default: false },
|
|
102
|
+
'update-lock': { type: 'boolean', default: false },
|
|
103
|
+
'env': { type: 'boolean', default: false },
|
|
104
|
+
'audience': { type: 'string' },
|
|
105
|
+
'external-links': { type: 'boolean', default: false },
|
|
106
|
+
'server-port': { type: 'string' },
|
|
107
|
+
'allow': { type: 'string' },
|
|
108
|
+
'operator-dir': { type: 'string' },
|
|
109
|
+
'port': { type: 'string' },
|
|
110
|
+
'host': { type: 'string' },
|
|
111
|
+
'preview-origin': { type: 'string', multiple: true },
|
|
112
|
+
'public-url': { type: 'string' },
|
|
113
|
+
'help': { type: 'boolean', short: 'h', default: false },
|
|
114
|
+
},
|
|
115
|
+
})
|
|
116
|
+
if (values.help) return 'help'
|
|
117
|
+
const [name, deck = '.', ...extra] = positionals
|
|
118
|
+
if (!name) throw new Error(t.missingCommand)
|
|
119
|
+
if (!(name in OPTIONS)) throw new Error(t.unknownCommand(name))
|
|
120
|
+
const allowed: readonly string[] = OPTIONS[name as Name]
|
|
121
|
+
const given = Object.entries(values).filter(([key, value]) => key !== 'help' && value !== undefined && value !== false)
|
|
122
|
+
const wrong = given.find(([key]) => !allowed.includes(key))
|
|
123
|
+
if (wrong) throw new Error(t.optionNotFor(wrong[0], name))
|
|
124
|
+
if (extra.length > 0) throw new Error(t.unexpectedArgument(extra[0]!))
|
|
125
|
+
const workspace = name === 'build' && existsSync(deck) && statSync(deck).isDirectory() && isWorkspaceRoot(resolve(deck)) ? resolve(deck) : undefined
|
|
126
|
+
if (workspace && values.to) throw new Error(t.toNotForWorkspace)
|
|
127
|
+
if (workspace && values.audience !== undefined) throw new Error(t.audienceNotForWorkspace)
|
|
128
|
+
const audience = values.audience?.trim()
|
|
129
|
+
if (values.audience !== undefined && !/^[\w.-]+$/.test(audience ?? '')) throw new Error(t.badAudience(values.audience))
|
|
130
|
+
const directory = name === 'serve'
|
|
131
|
+
const entry = directory || workspace ? resolve(deck) : resolveEntry(deck)
|
|
132
|
+
if (!existsSync(entry) || (directory && !statSync(entry).isDirectory())) throw new Error(t.notFound(entry))
|
|
133
|
+
const to = values.to?.split(',').map(id => id.trim()).filter(Boolean)
|
|
134
|
+
if (to?.length === 0) throw new Error(t.emptyTo)
|
|
135
|
+
const allow = values.allow?.split(',').map(kind => kind.trim()).filter(Boolean) ?? []
|
|
136
|
+
const unknown = allow.find(kind => !(APPROVAL_KINDS as readonly string[]).includes(kind))
|
|
137
|
+
if (unknown) throw new Error(t.badAllow(APPROVAL_KINDS, unknown))
|
|
138
|
+
const previewOrigins = values['preview-origin'] ?? []
|
|
139
|
+
const notOrigin = previewOrigins.find(origin => !isOrigin(origin))
|
|
140
|
+
if (notOrigin !== undefined) throw new Error(t.badPreviewOrigin(notOrigin))
|
|
141
|
+
const publicUrl = values['public-url']
|
|
142
|
+
if (publicUrl !== undefined && !isPublicUrl(publicUrl)) throw new Error(t.badPublicUrl(publicUrl))
|
|
143
|
+
return {
|
|
144
|
+
name: name as Name,
|
|
145
|
+
entry,
|
|
146
|
+
...workspace ? { workspace } : {},
|
|
147
|
+
to,
|
|
148
|
+
out: values.out,
|
|
149
|
+
json: values.json,
|
|
150
|
+
updateLock: values['update-lock'],
|
|
151
|
+
env: values.env,
|
|
152
|
+
...audience ? { audience } : {},
|
|
153
|
+
externalLinks: values['external-links'],
|
|
154
|
+
serverPort: parsePort(values['server-port'], '--server-port'),
|
|
155
|
+
allow: allow as ApprovalKind[],
|
|
156
|
+
operatorDir: values['operator-dir'],
|
|
157
|
+
port: parsePort(values.port, '--port'),
|
|
158
|
+
listenAddress: values.host,
|
|
159
|
+
previewOrigins,
|
|
160
|
+
...publicUrl ? { publicUrl } : {},
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/** An http(s) address, optionally with the path a proxy forwards; no credentials, query or fragment. */
|
|
165
|
+
function isPublicUrl(value: string): boolean {
|
|
166
|
+
try {
|
|
167
|
+
const url = new URL(value)
|
|
168
|
+
return /^https?:$/.test(url.protocol) && !url.username && !url.password && !url.search && !url.hash
|
|
169
|
+
} catch {
|
|
170
|
+
return false
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
function isOrigin(value: string): boolean {
|
|
175
|
+
try {
|
|
176
|
+
const url = new URL(value)
|
|
177
|
+
return /^https?:$/.test(url.protocol) && url.origin === value
|
|
178
|
+
} catch {
|
|
179
|
+
return false
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
function parsePort(value: string | undefined, option: string): number | undefined {
|
|
184
|
+
if (value === undefined) return undefined
|
|
185
|
+
const n = Number(value)
|
|
186
|
+
if (!Number.isInteger(n) || n < 0 || n > 65535) throw new Error(t.badPort(option, value))
|
|
187
|
+
return n
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
async function runCheckCommand(command: Command, bundled: string): Promise<number> {
|
|
191
|
+
const result = await runCheck({
|
|
192
|
+
deck: command.entry,
|
|
193
|
+
updateLock: command.updateLock,
|
|
194
|
+
environments: command.env,
|
|
195
|
+
externalLinks: command.externalLinks,
|
|
196
|
+
compiler: { bundled, ...command.audience ? { audience: command.audience } : {} },
|
|
197
|
+
})
|
|
198
|
+
process.stdout.write(command.json ? `${JSON.stringify(checkJson(result), null, 2)}\n` : checkText(result))
|
|
199
|
+
return exitCode(result.findings)
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
async function runIrCommand(command: Command, bundled: string): Promise<number> {
|
|
203
|
+
const { doc } = await new Compiler(command.entry, { bundled }).compile()
|
|
204
|
+
const json = `${JSON.stringify(doc, null, 2)}\n`
|
|
205
|
+
if (command.out) {
|
|
206
|
+
const file = resolve(command.out)
|
|
207
|
+
await mkdir(dirname(file), { recursive: true })
|
|
208
|
+
await writeFile(file, json)
|
|
209
|
+
} else {
|
|
210
|
+
process.stdout.write(json)
|
|
211
|
+
}
|
|
212
|
+
process.stderr.write(findingLines(doc.diagnostics).join('\n') + (doc.diagnostics.length ? '\n' : ''))
|
|
213
|
+
return exitCode(doc.diagnostics)
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
async function runBuildCommand(command: Command, bundled: string): Promise<number> {
|
|
217
|
+
if (command.workspace) {
|
|
218
|
+
const report = await buildWorkspace(command.workspace, { outDir: command.out, bundled })
|
|
219
|
+
process.stdout.write(workspaceText(report))
|
|
220
|
+
return exitCode(report.findings)
|
|
221
|
+
}
|
|
222
|
+
const compilation = await new Compiler(command.entry, { bundled, ...command.audience ? { audience: command.audience } : {} }).compile({ pruneCache: true })
|
|
223
|
+
const outDir = resolve(command.out ?? join(compilation.deckDir, 'dist'))
|
|
224
|
+
const report = await build(compilation, { outDir, to: command.to })
|
|
225
|
+
process.stdout.write(buildText(report, compilation.runStats, compilation.audience?.name))
|
|
226
|
+
return exitCode(report.findings)
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
async function runDevCommand(command: Command, bundled: string): Promise<number> {
|
|
230
|
+
let latest: Compilation | undefined
|
|
231
|
+
const deckDir = dirname(command.entry)
|
|
232
|
+
const approvals: Partial<Record<ApprovalKind, ApprovalPolicy>> = Object.fromEntries(command.allow.map(kind => [kind, 'allow']))
|
|
233
|
+
const host = devHost(() => latest)
|
|
234
|
+
const server = await startServer({
|
|
235
|
+
mode: 'dev',
|
|
236
|
+
port: command.serverPort,
|
|
237
|
+
approvals,
|
|
238
|
+
serverHost: host,
|
|
239
|
+
document: async dir => (dir === '' && latest ? servedDocument(latest) : undefined),
|
|
240
|
+
stateFile: join(deckDir, '.presmium', 'server.json'),
|
|
241
|
+
})
|
|
242
|
+
const compiler = new Compiler(command.entry, { bundled, priority: 'interactive', services: server.services })
|
|
243
|
+
const outDir = resolve(command.out ?? join(compiler.deckDir, '.presmium', 'dev'))
|
|
244
|
+
await mkdir(outDir, { recursive: true })
|
|
245
|
+
await writeFile(join(outDir, '.gitignore'), '*\n')
|
|
246
|
+
let devServers
|
|
247
|
+
try {
|
|
248
|
+
devServers = await dev(compiler, {
|
|
249
|
+
outDir,
|
|
250
|
+
to: command.to,
|
|
251
|
+
server: { url: server.url },
|
|
252
|
+
onCompile(compilation, findings) {
|
|
253
|
+
const changed = latest && serverConfigKey(latest) !== serverConfigKey(compilation)
|
|
254
|
+
latest = compilation
|
|
255
|
+
const revision = irRevision(compilation.doc)
|
|
256
|
+
server.diagnostics.compiled('', compilation.doc, compilation.workspaceRoot, revision)
|
|
257
|
+
server.diagnostics.replace({ document: '', origin: 'preview' }, findings.filter(finding => finding.checkId === 'presmium.render'), { root: compilation.workspaceRoot, irRevision: revision })
|
|
258
|
+
if (changed) void server.unmount('', { preserveFocus: true }).catch((error: unknown) => {
|
|
259
|
+
process.stderr.write(`${t.unmountFailed(errorMessage(error))}\n`)
|
|
260
|
+
})
|
|
261
|
+
const lines = findingLines(findings)
|
|
262
|
+
lines.push(t.compiled(compilation.doc.sections.length, summary(findings)))
|
|
263
|
+
process.stdout.write(`${lines.join('\n')}\n`)
|
|
264
|
+
},
|
|
265
|
+
})
|
|
266
|
+
} catch (error) {
|
|
267
|
+
await server.close()
|
|
268
|
+
throw error
|
|
269
|
+
}
|
|
270
|
+
for (const { renderer, url } of devServers.servers) process.stdout.write(`${renderer} ${url}\n`)
|
|
271
|
+
process.stdout.write(`server ${server.url}\nmcp ${server.url}/mcp${t.token(relative(process.cwd(), join(deckDir, '.presmium', 'server.json')))}\n`)
|
|
272
|
+
process.stdout.write(`${t.watching(relative(process.cwd(), devServers.ir))}\n`)
|
|
273
|
+
await new Promise<void>((done) => {
|
|
274
|
+
process.once('SIGINT', done)
|
|
275
|
+
process.once('SIGTERM', done)
|
|
276
|
+
})
|
|
277
|
+
await devServers.close()
|
|
278
|
+
await server.close()
|
|
279
|
+
return 0
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
async function runServeCommand(command: Command, bundled: string): Promise<number> {
|
|
283
|
+
const started = await serveWorkspace({
|
|
284
|
+
dir: command.entry,
|
|
285
|
+
listenAddress: command.listenAddress,
|
|
286
|
+
port: command.port,
|
|
287
|
+
...command.operatorDir ? { operatorDir: resolve(command.operatorDir) } : {},
|
|
288
|
+
bundled,
|
|
289
|
+
check: compilation => compilation.check(),
|
|
290
|
+
previewOrigins: command.previewOrigins,
|
|
291
|
+
...command.publicUrl ? { publicUrl: command.publicUrl } : {},
|
|
292
|
+
})
|
|
293
|
+
process.stdout.write(`serve ${started.url}\n${networkLines(command.listenAddress, started.url)}workspace ${started.root}\nmcp ${started.mcp.url}${t.token(started.mcp.stateFile)}\n`)
|
|
294
|
+
if (command.listenAddress && !isLoopback(command.listenAddress)) {
|
|
295
|
+
process.stderr.write(`${t.serveOpen(command.listenAddress, new URL(started.url).port)}\n`)
|
|
296
|
+
}
|
|
297
|
+
if (!findFfmpeg()) process.stderr.write(`${t.noFfmpeg(ffmpegInstallCommand())}\n`)
|
|
298
|
+
await new Promise<void>((done) => {
|
|
299
|
+
process.once('SIGINT', done)
|
|
300
|
+
process.once('SIGTERM', done)
|
|
301
|
+
})
|
|
302
|
+
await started.close()
|
|
303
|
+
return 0
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
function resolveInstalled(name: string, bundled: string): string | undefined {
|
|
307
|
+
for (const from of [pathToFileURL(join(bundled, 'package.json')).href, import.meta.url, pathToFileURL(join(process.cwd(), 'package.json')).href]) {
|
|
308
|
+
try {
|
|
309
|
+
return createRequire(from).resolve(name)
|
|
310
|
+
} catch {
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
return undefined
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
async function runNewCommand(argv: string[], bundled: string): Promise<number> {
|
|
317
|
+
const entry = resolveInstalled('create-presmium', bundled)
|
|
318
|
+
if (!entry) {
|
|
319
|
+
process.stderr.write(`${t.newMissing}\n`)
|
|
320
|
+
return 2
|
|
321
|
+
}
|
|
322
|
+
const { main: createMain } = await createJiti(import.meta.url).import<{ main(argv: string[]): Promise<number> }>(entry)
|
|
323
|
+
return createMain(argv)
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
async function runStudioCommand(argv: string[], bundled: string, presmiumBin: string): Promise<number> {
|
|
327
|
+
const entry = resolveInstalled('@lincyaw/studio', bundled)
|
|
328
|
+
if (!entry) {
|
|
329
|
+
process.stderr.write(`${t.studioMissing}\n`)
|
|
330
|
+
return 2
|
|
331
|
+
}
|
|
332
|
+
const { main: studioMain } = await createJiti(import.meta.url).import<{ main(argv: string[], options: { presmium: string }): Promise<number> }>(entry)
|
|
333
|
+
return studioMain(argv, { presmium: presmiumBin })
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
function networkLines(listenAddress: string | undefined, url: string): string {
|
|
337
|
+
if (!listenAddress || isLoopback(listenAddress)) return ''
|
|
338
|
+
const { port } = new URL(url)
|
|
339
|
+
const addresses = isAnyAddress(listenAddress) ? lanAddresses() : [bracketIPv6(listenAddress)]
|
|
340
|
+
return addresses.map(address => `network http://${address}:${port}/\n`).join('')
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
function exitCode(findings: Finding[]): number {
|
|
344
|
+
return findings.some(f => f.severity === 'error') ? 1 : 0
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
function counts(findings: Finding[]): Record<Severity, number> {
|
|
348
|
+
const result: Record<Severity, number> = { error: 0, warning: 0, info: 0 }
|
|
349
|
+
for (const f of findings) result[f.severity]++
|
|
350
|
+
return result
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
function summary(findings: Finding[]): string {
|
|
354
|
+
const n = counts(findings)
|
|
355
|
+
return findings.length === 0 ? t.noProblems : t.counts(n.error, n.warning, n.info)
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
function findingLines(findings: Finding[], cwd = process.cwd()): string[] {
|
|
359
|
+
return findings.flatMap((f) => {
|
|
360
|
+
const where = f.source ? `${relative(cwd, f.source.file)}${f.source.line ? `:${f.source.line}` : ''}` : ''
|
|
361
|
+
return [`${where} ${t.severity[f.severity]} ${f.message} (${f.checkId})`, ...f.hint ? [t.hint(f.hint)] : []]
|
|
362
|
+
})
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
function checkJson(result: CheckResult) {
|
|
366
|
+
return { entry: result.entry, counts: counts(result.findings), findings: result.findings, lock: result.lock }
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
function checkText(result: CheckResult, cwd = process.cwd()): string {
|
|
370
|
+
const out = findingLines(result.findings, cwd)
|
|
371
|
+
if (result.lock) {
|
|
372
|
+
out.push(t.lock(relative(cwd, result.lock.file), result.lock.changed, result.lock.anchors))
|
|
373
|
+
}
|
|
374
|
+
out.push(summary(result.findings))
|
|
375
|
+
return `${out.join('\n')}\n`
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
function workspaceText(report: WorkspaceBuild, cwd = process.cwd()): string {
|
|
379
|
+
const out = findingLines(report.findings, cwd)
|
|
380
|
+
for (const { dir, title, runs } of report.documents) {
|
|
381
|
+
out.push(`document ${dir || '.'} ${title}${runs.executed + runs.cached > 0 ? t.documentRuns(runs.executed, runs.cached) : ''}`)
|
|
382
|
+
}
|
|
383
|
+
out.push(`web ${relative(cwd, report.outDir)}`)
|
|
384
|
+
out.push(summary(report.findings))
|
|
385
|
+
return `${out.join('\n')}\n`
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
function buildText(report: BuildReport, runs: RunStats, audience?: string, cwd = process.cwd()): string {
|
|
389
|
+
const out = findingLines(report.findings, cwd)
|
|
390
|
+
if (audience) out.push(`audience ${audience}`)
|
|
391
|
+
out.push(`ir ${relative(cwd, report.ir)}`)
|
|
392
|
+
for (const { renderer, outDir, skipped } of report.outputs) {
|
|
393
|
+
out.push(`${renderer} ${relative(cwd, outDir)}${skipped.length ? t.notRendered(skipped.length) : ''}`)
|
|
394
|
+
for (const s of skipped) out.push(` ${s.section}#${s.block}: ${s.reason}`)
|
|
395
|
+
}
|
|
396
|
+
if (runs.executed + runs.cached > 0) out.push(t.codeRuns(runs.executed, runs.cached, runs.sandbox && runs.executed > 0 ? runs.sandbox : undefined))
|
|
397
|
+
out.push(summary(report.findings))
|
|
398
|
+
return `${out.join('\n')}\n`
|
|
399
|
+
}
|
package/src/dev-host.ts
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { buildSummary, buildToDist, runBlock } from '@lincyaw/compiler'
|
|
2
|
+
import type { Compilation } from '@lincyaw/compiler'
|
|
3
|
+
import type { ServerHost } from '@lincyaw/server'
|
|
4
|
+
|
|
5
|
+
export function devHost(latest: () => Compilation | undefined): ServerHost {
|
|
6
|
+
const current = (document: string): Compilation => {
|
|
7
|
+
const compilation = latest()
|
|
8
|
+
if (document !== '' || !compilation) throw new Error(document === '' ? 'the deck is still compiling' : `no document ${JSON.stringify(document)} in presmium dev`)
|
|
9
|
+
return compilation
|
|
10
|
+
}
|
|
11
|
+
return {
|
|
12
|
+
get workspaceRoot() { return latest()?.workspaceRoot },
|
|
13
|
+
async documents() {
|
|
14
|
+
const compilation = latest()
|
|
15
|
+
return compilation ? [{ dir: '', title: compilation.doc.meta.title, lang: compilation.doc.meta.lang }] : []
|
|
16
|
+
},
|
|
17
|
+
async compile(document) {
|
|
18
|
+
const { doc } = current(document)
|
|
19
|
+
return { doc, diagnostics: doc.diagnostics }
|
|
20
|
+
},
|
|
21
|
+
async check(document) {
|
|
22
|
+
const compilation = current(document)
|
|
23
|
+
return [...compilation.doc.diagnostics, ...await compilation.check()]
|
|
24
|
+
},
|
|
25
|
+
async build(document, options = {}) {
|
|
26
|
+
return buildSummary(await buildToDist(current(document), options))
|
|
27
|
+
},
|
|
28
|
+
run: async (document, target, signal) => runBlock(current(document), target, signal),
|
|
29
|
+
}
|
|
30
|
+
}
|
package/src/index.ts
ADDED
package/src/messages.ts
ADDED
|
@@ -0,0 +1,219 @@
|
|
|
1
|
+
export { systemLocale } from '@lincyaw/kernel/node'
|
|
2
|
+
import { DOCUMENT_ENTRY } from '@lincyaw/kernel'
|
|
3
|
+
import type { Locale } from '@lincyaw/kernel'
|
|
4
|
+
|
|
5
|
+
// The lines that start with a key and two spaces (`serve <url>`, `workspace <root>`, `mcp <url>`, `<renderer> <url>`)
|
|
6
|
+
// are read by programs (`@lincyaw/dsh/launch`, the tests): their keys, URLs and paths stay the same in both languages.
|
|
7
|
+
export interface CliMessages {
|
|
8
|
+
usage: string
|
|
9
|
+
missingCommand: string
|
|
10
|
+
unknownCommand(name: string): string
|
|
11
|
+
optionNotFor(option: string, command: string): string
|
|
12
|
+
unexpectedArgument(argument: string): string
|
|
13
|
+
toNotForWorkspace: string
|
|
14
|
+
audienceNotForWorkspace: string
|
|
15
|
+
badAudience(value: string): string
|
|
16
|
+
notFound(entry: string): string
|
|
17
|
+
emptyTo: string
|
|
18
|
+
badAllow(kinds: readonly string[], value: string): string
|
|
19
|
+
badPreviewOrigin(value: string): string
|
|
20
|
+
badPublicUrl(value: string): string
|
|
21
|
+
badPort(option: string, value: string): string
|
|
22
|
+
unmountFailed(error: string): string
|
|
23
|
+
compiled(sections: number, summary: string): string
|
|
24
|
+
token(file: string): string
|
|
25
|
+
watching(ir: string): string
|
|
26
|
+
serveOpen(address: string, port: string): string
|
|
27
|
+
noFfmpeg(command: string): string
|
|
28
|
+
newMissing: string
|
|
29
|
+
studioMissing: string
|
|
30
|
+
noProblems: string
|
|
31
|
+
counts(errors: number, warnings: number, infos: number): string
|
|
32
|
+
severity: Record<'error' | 'warning' | 'info', string>
|
|
33
|
+
hint(text: string): string
|
|
34
|
+
lock(file: string, changed: boolean, anchors: number): string
|
|
35
|
+
documentRuns(executed: number, cached: number): string
|
|
36
|
+
notRendered(blocks: number): string
|
|
37
|
+
codeRuns(executed: number, cached: number, sandbox?: string): string
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export const CLI_MESSAGES: Record<Locale, CliMessages> = {
|
|
41
|
+
'zh-CN': {
|
|
42
|
+
usage: `用法:presmium <命令> [<文稿>] [<选项>]
|
|
43
|
+
|
|
44
|
+
<文稿> 是含有 ${DOCUMENT_ENTRY} 的目录,或这个文件本身(默认为 .)。
|
|
45
|
+
|
|
46
|
+
命令:
|
|
47
|
+
new 在目录中新建项目(没有给出时逐项询问),由 create-presmium 完成
|
|
48
|
+
--type <种类> lecture、workspace、site 或 plugin(默认询问)
|
|
49
|
+
--theme <主题> site 的主题:course、docs 或 showcase(默认 course)
|
|
50
|
+
--title <标题> 讲义、工作区或网站的标题
|
|
51
|
+
--name <包名> 插件的包名
|
|
52
|
+
--no-git 不运行 git init
|
|
53
|
+
skills 安装内置技能(与 MCP 和可视化编辑器共用)
|
|
54
|
+
install <目录> [--json] 安装缺少的 .agents/skills,保留已有技能
|
|
55
|
+
--name <技能> 只安装指定技能,可重复
|
|
56
|
+
--json 以 JSON 打印安装结果
|
|
57
|
+
build 导出文稿:写出 <输出>/ir.json 与 <输出>/<形态>/;在工作区的根目录
|
|
58
|
+
(有 presmium.workspace.yaml)把整个工作区导出为网站,写到 <输出>/web/
|
|
59
|
+
--to <形态> 要导出的形态,以逗号分隔(默认为文稿声明的形态)
|
|
60
|
+
--out <目录> 输出目录(默认为 <文稿>/dist)
|
|
61
|
+
--audience <名称> 只导出面向这类读者的内容(例如 student),并在写出的每个
|
|
62
|
+
文件中查找被略去内容的句子
|
|
63
|
+
dev 实时预览:启动 Presmium 服务与各形态的预览服务器,保存后自动更新
|
|
64
|
+
--to <形态> 要预览的形态,以逗号分隔
|
|
65
|
+
--out <目录> 工作目录(默认为 <文稿>/.presmium/dev)
|
|
66
|
+
--server-port <端口> Presmium 服务的端口(默认为空闲端口)
|
|
67
|
+
--allow <种类> 无需询问即允许的操作:operate、spend、write、agent
|
|
68
|
+
ir 以 JSON 打印文稿的运行快照
|
|
69
|
+
--out <文件> 写入文件,而不是打印
|
|
70
|
+
check 检查文稿并运行插件的检查
|
|
71
|
+
--json 以 JSON 打印结果
|
|
72
|
+
--update-lock 重新定位代码锚点,并重写 .presmium/anchors.lock.json
|
|
73
|
+
--env 同时连接 execute.environments 中的运行环境
|
|
74
|
+
--audience <名称> 按面向这类读者的内容检查
|
|
75
|
+
--external-links 同时检查外部链接(装有 lychee 时用它)
|
|
76
|
+
serve 在本机提供工作区服务(参数是工作区的根目录或一份文稿):工作区网站、
|
|
77
|
+
各文稿与其版本历史、审阅、插件的服务端路由与课堂同步;不加 --host 时
|
|
78
|
+
只在本机监听
|
|
79
|
+
--port <端口> 端口(默认为 4310)
|
|
80
|
+
--host <地址> 监听的地址(默认为 127.0.0.1);0.0.0.0 或局域网中的地址
|
|
81
|
+
让同一网络中的其他设备也能使用,且没有登录:任何能访问
|
|
82
|
+
这个端口的人都以你的身份操作
|
|
83
|
+
--operator-dir <目录> 运营者目录(默认为用户的状态目录)
|
|
84
|
+
--preview-origin <来源> (可重复)嵌入预览的 Presmium Studio 页面的来源,
|
|
85
|
+
例如 http://127.0.0.1:4320;设置 PRESMIUM_SERVICE_TOKEN 时,
|
|
86
|
+
工作区的路由要求它(Authorization: Bearer)
|
|
87
|
+
--public-url <网址> 反向代理在前面时浏览器使用的地址:信任它的主机,预览与产物
|
|
88
|
+
的地址用它给出;带路径时代理原样转发该路径,服务的全部内容都在它下面
|
|
89
|
+
studio 启动 Presmium Studio(实验性):浏览器中的编辑应用与这个目录(工作区的
|
|
90
|
+
根目录或一份文稿)的工作区服务,只打印一个要打开的网址。需要另外安装
|
|
91
|
+
@lincyaw/studio(约 865 MB)
|
|
92
|
+
--port <端口> Presmium Studio 的端口(默认为 4320,被占用时取空闲端口)
|
|
93
|
+
--host <地址> 改为监听本机在局域网中的这个地址,而不是 127.0.0.1,且没有
|
|
94
|
+
登录:任何能访问这个端口的人都以你的身份操作
|
|
95
|
+
|
|
96
|
+
-h, --help 显示本说明
|
|
97
|
+
|
|
98
|
+
退出码:0 没有错误,1 有错误级别的问题,2 用法错误或内部错误。`,
|
|
99
|
+
missingCommand: '缺少命令。请在 presmium 之后给出命令,例如 presmium build。',
|
|
100
|
+
unknownCommand: name => `没有命令“${name}”。可用的命令见 presmium --help。`,
|
|
101
|
+
optionNotFor: (option, command) => `选项 --${option} 不能用于 presmium ${command}。可用的选项见 presmium --help。`,
|
|
102
|
+
unexpectedArgument: argument => `多余的参数“${argument}”。每个命令只接受一个文稿或目录。`,
|
|
103
|
+
toNotForWorkspace: '--to 不能用于工作区:工作区总是导出为网站。',
|
|
104
|
+
audienceNotForWorkspace: '--audience 暂不能用于工作区。请分别为每份文稿加 --audience 导出。',
|
|
105
|
+
badAudience: value => `“${value}”不是读者类别的名称。请给出字母、数字、.、_ 或 - 组成的名称,例如 student。`,
|
|
106
|
+
notFound: entry => `找不到 ${entry}。请检查路径,或用 presmium new 新建文稿。`,
|
|
107
|
+
emptyTo: '--to 至少需要一个形态,例如 --to web。',
|
|
108
|
+
badAllow: (kinds, value) => `--allow 不接受“${value}”。可用的种类:${kinds.join('、')}。`,
|
|
109
|
+
badPreviewOrigin: value => `“${value}”不是来源。请给出协议、主机与端口,例如 http://127.0.0.1:4320。`,
|
|
110
|
+
badPublicUrl: value => `“${value}”不是可用的网址。请给出浏览器访问的地址,例如 https://preview.example.com 或 https://example.com/user/a/preview/。`,
|
|
111
|
+
badPort: (option, value) => `${option} 需要 0 到 65535 之间的端口号,而不是“${value}”。`,
|
|
112
|
+
unmountFailed: error => `presmium: 无法关闭上一次加载的服务端扩展:${error}`,
|
|
113
|
+
compiled: (sections, summary) => `已更新 ${sections} 个页面;${summary}`,
|
|
114
|
+
token: file => ` (访问令牌在 ${file} 中)`,
|
|
115
|
+
watching: ir => `正在监视修改;运行快照在 ${ir}`,
|
|
116
|
+
noFfmpeg: command => `presmium serve: 没有找到 FFmpeg,讲授视频只能由浏览器导出为 WebM,画质较低。安装后可导出清晰的 MP4:${command}`,
|
|
117
|
+
serveOpen: (address, port) => `presmium serve: 正在 ${address} 上监听,局域网中的设备可以访问,且没有登录:任何能访问端口 ${port} 的人都以你的身份使用这个工作区(编辑、运行代码、允许操作)。请只在可信的网络中使用;不加 --host 时只在本机监听。`,
|
|
118
|
+
newMissing: 'presmium new: 没有安装 create-presmium。它随 presmium 一起安装,请运行 pnpm add -g @lincyaw/presmium。',
|
|
119
|
+
studioMissing: 'presmium studio: 这里没有安装 Presmium Studio(实验性,约 865 MB)。请运行 pnpm add -g @lincyaw/studio 后使用 presmium-studio,或在本项目中运行 pnpm add -D @lincyaw/studio。',
|
|
120
|
+
noProblems: '没有问题',
|
|
121
|
+
counts: (errors, warnings, infos) => `${errors} 个错误,${warnings} 个警告,${infos} 条信息`,
|
|
122
|
+
severity: { error: '错误', warning: '警告', info: '信息' },
|
|
123
|
+
hint: text => ` 建议:${text}`,
|
|
124
|
+
lock: (file, changed, anchors) => `${file} ${changed ? '已更新' : '没有变化'}(${anchors} 个锚点)`,
|
|
125
|
+
documentRuns: (executed, cached) => ` (代码运行:执行 ${executed} 个,取自缓存 ${cached} 个)`,
|
|
126
|
+
notRendered: blocks => ` (${blocks} 个内容块未显示)`,
|
|
127
|
+
codeRuns: (executed, cached, sandbox) => `代码运行:执行 ${executed} 个,取自缓存 ${cached} 个${sandbox ? `,隔离方式为 ${sandbox}` : ''}`,
|
|
128
|
+
},
|
|
129
|
+
'en': {
|
|
130
|
+
usage: `Usage: presmium <command> [deck] [options]
|
|
131
|
+
|
|
132
|
+
The deck is a directory holding ${DOCUMENT_ENTRY}, or that entry file (default: .).
|
|
133
|
+
|
|
134
|
+
Commands:
|
|
135
|
+
new a new project in the directory (default: asks), from create-presmium
|
|
136
|
+
--type <kind> lecture, workspace, site, or plugin (default: asks)
|
|
137
|
+
--theme <name> site theme: course, docs, or showcase (default: course)
|
|
138
|
+
--title <text> the lecture, workspace, or site title
|
|
139
|
+
--name <name> the plugin’s package name
|
|
140
|
+
--no-git do not run git init
|
|
141
|
+
skills install bundled skills, shared with MCP and the visual editor
|
|
142
|
+
install <dir> [--json] install missing .agents/skills; keep existing skills
|
|
143
|
+
--name <skill> install only the named skill; repeat for more
|
|
144
|
+
--json print the installation result as JSON
|
|
145
|
+
build export the deck: writes <out>/ir.json and <out>/<renderer>/; at a workspace root
|
|
146
|
+
(presmium.workspace.yaml) exports the workspace as a website into <out>/web/
|
|
147
|
+
--to <ids> forms to export, comma-separated (default: the deck’s renderers)
|
|
148
|
+
--out <dir> output directory (default: <deck>/dist)
|
|
149
|
+
--audience <name> only the content for this audience (e.g. student); then every file
|
|
150
|
+
written is scanned for the sentences of the content left out
|
|
151
|
+
dev live preview: starts the Presmium server and the renderers’ dev servers, updates on save
|
|
152
|
+
--to <ids> forms to preview, comma-separated
|
|
153
|
+
--out <dir> working directory (default: <deck>/.presmium/dev)
|
|
154
|
+
--server-port <n> port of the Presmium server (default: a free port)
|
|
155
|
+
--allow <kinds> approvals given without asking: operate, spend, write, agent
|
|
156
|
+
ir print the runtime snapshot as JSON
|
|
157
|
+
--out <file> write it to a file instead
|
|
158
|
+
check check the deck and run the plugins’ checks
|
|
159
|
+
--json print the result as JSON
|
|
160
|
+
--update-lock re-resolve anchors and rewrite .presmium/anchors.lock.json
|
|
161
|
+
--env also connect to the environments of execute.environments
|
|
162
|
+
--audience <name> check the content for this audience
|
|
163
|
+
--external-links also check the external links, with lychee when it is installed
|
|
164
|
+
serve the workspace service for you on this machine (the argument is the workspace root, or
|
|
165
|
+
a deck): the workspace site, the documents and their history, the reviews, the plugins’
|
|
166
|
+
routes, and the classroom sync; without --host it listens on this machine only
|
|
167
|
+
--port <n> port (default: 4310)
|
|
168
|
+
--host <addr> address to listen on (default: 127.0.0.1); 0.0.0.0 or an address on the
|
|
169
|
+
local network opens it to your other devices there, with no login:
|
|
170
|
+
whoever reaches the port works as you
|
|
171
|
+
--operator-dir <dir> the operator directory (default: the user’s state directory)
|
|
172
|
+
--preview-origin <origin> (repeatable) the origin of a Presmium Studio whose pages embed
|
|
173
|
+
the previews, e.g. http://127.0.0.1:4320; with PRESMIUM_SERVICE_TOKEN set,
|
|
174
|
+
the workspace’s routes ask for it (Authorization: Bearer)
|
|
175
|
+
--public-url <url> the address browsers use when a reverse proxy fronts the service: its
|
|
176
|
+
host is trusted, and previews and outputs are linked under it; with a path, the
|
|
177
|
+
proxy forwards that path unchanged and everything the service serves is below it
|
|
178
|
+
studio Presmium Studio (experimental): the editing app in the browser and the workspace service
|
|
179
|
+
of the directory (the workspace root, or a deck); prints the one address to open. It is
|
|
180
|
+
the package @lincyaw/studio (about 865 MB), installed beside this one
|
|
181
|
+
--port <n> Presmium Studio’s port (default: 4320, or a free one when that is in use)
|
|
182
|
+
--host <addr> listen on this address of the machine on the local network instead of
|
|
183
|
+
127.0.0.1, with no login: whoever reaches the port works as you
|
|
184
|
+
|
|
185
|
+
-h, --help show this help
|
|
186
|
+
|
|
187
|
+
Exit Codes: 0 no errors, 1 error findings, 2 usage or internal error.`,
|
|
188
|
+
missingCommand: 'No command given. Put a command after presmium, for example presmium build.',
|
|
189
|
+
unknownCommand: name => `There is no command “${name}”. See presmium --help for the commands.`,
|
|
190
|
+
optionNotFor: (option, command) => `The option --${option} does not apply to presmium ${command}. See presmium --help for its options.`,
|
|
191
|
+
unexpectedArgument: argument => `Unexpected argument “${argument}”. Each command takes one deck or directory.`,
|
|
192
|
+
toNotForWorkspace: '--to does not apply to a workspace: its site is the web form.',
|
|
193
|
+
audienceNotForWorkspace: '--audience does not apply to a workspace yet. Export each document with --audience instead.',
|
|
194
|
+
badAudience: value => `“${value}” is not the name of an audience. Give a name of letters, digits, ., _, or -, such as student.`,
|
|
195
|
+
notFound: entry => `Couldn’t find ${entry}. Check the path, or make a document with presmium new.`,
|
|
196
|
+
emptyTo: '--to needs at least one renderer, such as --to web.',
|
|
197
|
+
badAllow: (kinds, value) => `--allow does not take “${value}”. The kinds are ${kinds.join(', ')}.`,
|
|
198
|
+
badPreviewOrigin: value => `“${value}” is not an origin. Give a scheme, host, and port, such as http://127.0.0.1:4320.`,
|
|
199
|
+
badPublicUrl: value => `“${value}” is not a usable address. Give the address browsers use, such as https://preview.example.com or https://example.com/user/a/preview/.`,
|
|
200
|
+
badPort: (option, value) => `${option} takes a port number from 0 to 65535, not “${value}”.`,
|
|
201
|
+
unmountFailed: error => `presmium: couldn’t close the previous server contributions: ${error}`,
|
|
202
|
+
compiled: (sections, summary) => `compiled ${sections} sections; ${summary}`,
|
|
203
|
+
token: file => ` (its token is in ${file})`,
|
|
204
|
+
watching: ir => `watching; runtime snapshot in ${ir}`,
|
|
205
|
+
noFfmpeg: command => `presmium serve: FFmpeg was not found, so lecture videos export from the browser as WebM, at a lower quality. Install it for sharp MP4 videos: ${command}`,
|
|
206
|
+
serveOpen: (address, port) => `presmium serve: listening on ${address}, on the local network, with no login: anyone who reaches port ${port} uses this workspace as you (edits, runs code, approves). Use it on a network you trust; without --host it listens on this machine only.`,
|
|
207
|
+
newMissing: 'presmium new: create-presmium is not installed. It comes with the presmium package: run pnpm add -g @lincyaw/presmium.',
|
|
208
|
+
studioMissing: 'presmium studio: Presmium Studio is not installed here (experimental, about 865 MB). Run pnpm add -g @lincyaw/studio, then presmium-studio; or run pnpm add -D @lincyaw/studio in this project.',
|
|
209
|
+
noProblems: 'no problems',
|
|
210
|
+
counts: (errors, warnings, infos) => `${errors} errors, ${warnings} warnings, ${infos} infos`,
|
|
211
|
+
severity: { error: 'error', warning: 'warning', info: 'info' },
|
|
212
|
+
hint: text => ` hint: ${text}`,
|
|
213
|
+
lock: (file, changed, anchors) => `${file} ${changed ? 'updated' : 'unchanged'} (${anchors} anchors)`,
|
|
214
|
+
documentRuns: (executed, cached) => ` (code runs: ${executed} executed, ${cached} from cache)`,
|
|
215
|
+
notRendered: blocks => ` (${blocks} blocks not rendered)`,
|
|
216
|
+
codeRuns: (executed, cached, sandbox) => `code runs: ${executed} executed, ${cached} from cache${sandbox ? `, isolated by ${sandbox}` : ''}`,
|
|
217
|
+
},
|
|
218
|
+
}
|
|
219
|
+
|
package/src/testing.ts
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { execFile } from 'node:child_process'
|
|
2
|
+
import { fileURLToPath } from 'node:url'
|
|
3
|
+
|
|
4
|
+
export const PRESMIUM_BIN = fileURLToPath(new URL('../bin/presmium.mjs', import.meta.url))
|
|
5
|
+
|
|
6
|
+
export interface Run {
|
|
7
|
+
code: number
|
|
8
|
+
stdout: string
|
|
9
|
+
stderr: string
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export function run(command: string, args: string[], options: { cwd?: string, env?: NodeJS.ProcessEnv } = {}): Promise<Run> {
|
|
13
|
+
return new Promise((resolve) => {
|
|
14
|
+
execFile(command, args, { cwd: options.cwd, env: options.env, maxBuffer: 256 << 20 }, (error, stdout, stderr) => {
|
|
15
|
+
resolve({ code: !error ? 0 : typeof error.code === 'number' ? error.code : -1, stdout, stderr })
|
|
16
|
+
})
|
|
17
|
+
})
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export function presmium(cwd: string, args: string[], env: Record<string, string> = {}): Promise<Run> {
|
|
21
|
+
const { NODE_ENV: _test, ...inherited } = process.env
|
|
22
|
+
return run(process.execPath, [PRESMIUM_BIN, ...args], { cwd, env: { ...inherited, ...env } })
|
|
23
|
+
}
|
|
24
|
+
|