@matra/cli 0.0.0-stage → 0.3.2-alpha.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 ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) Matra contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/package.json CHANGED
@@ -1,6 +1,38 @@
1
1
  {
2
2
  "name": "@matra/cli",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.3.2-alpha.1",
4
+ "description": "Matra project initialization and HTML build tools",
5
+ "type": "module",
6
+ "bin": {
7
+ "matra": "src/cli.mjs"
8
+ },
9
+ "files": [
10
+ "src",
11
+ "templates"
12
+ ],
13
+ "dependencies": {
14
+ "@matra/command": "0.1.0",
15
+ "@matra/core": "0.3.1-site.1",
16
+ "@matra/html": "0.3.1-site.0",
17
+ "@matra/site-generation": "0.1.0-site.3",
18
+ "@matra/styles": "0.1.0"
19
+ },
20
+ "engines": {
21
+ "node": "^22.0.0 || ^24.0.0"
22
+ },
23
+ "repository": {
24
+ "type": "git",
25
+ "url": "git+https://github.com/matralang/matra.git",
26
+ "directory": "packages/cli"
27
+ },
28
+ "publishConfig": {
29
+ "access": "public",
30
+ "registry": "https://registry.npmjs.org"
31
+ },
32
+ "license": "MIT",
33
+ "scripts": {
34
+ "build": "node --check src/cli.mjs && node --check src/project.mjs && node --check src/deps.mjs && node --check src/dev.mjs && node --check scripts/build-distribution.mjs && node --check scripts/verify-distribution.mjs && node --check scripts/distribution-platform.mjs && node --check scripts/verify-release.mjs",
35
+ "check": "pnpm run build",
36
+ "test": "node --test tests/*.test.mjs"
37
+ }
6
38
  }
package/src/cli.mjs ADDED
@@ -0,0 +1,121 @@
1
+ #!/usr/bin/env node
2
+ import { readFile } from "node:fs/promises"
3
+ import { buildSite, getSiteProgramDocuments } from "@matra/site-generation"
4
+ import { installDependencies } from "./deps.mjs"
5
+ import { startDev } from "./dev.mjs"
6
+ import { buildProject, initProject } from "./project.mjs"
7
+
8
+ const usage = `Usage: matra init DIRECTORY
9
+ matra build
10
+ matra install [DOCUMENT] [--yes]
11
+ matra deps install [DOCUMENT] [--yes]
12
+ matra deps install (npm|python) DOCUMENT [--yes]
13
+ matra deps update (npm|python) DOCUMENT [--yes]
14
+ matra site install [--yes]
15
+ matra site build
16
+ matra dev [--port PORT]
17
+ matra --version
18
+
19
+ init Create a new project directory.
20
+ build Build index.md and matra.css into dist/ in the current directory.
21
+ site install Install dependencies for executable site pages and layouts.
22
+ site Build the configured multi-page site into dist/.
23
+ dev Serve on 127.0.0.1:3000 and rebuild on changes. Refresh the browser to view changes.
24
+ deps Install or update npm/Python packages declared by the selected document.
25
+ install Install both ecosystems (default document: index.md); alias of deps install.
26
+
27
+ matra build executes selected JavaScript and Python in index.md.
28
+ matra site build executes only explicitly named .matra.md pages and layouts.
29
+ matra deps install prompts before network access; npm lifecycle scripts are disabled.
30
+ Only build trusted programs; JavaScript and Python execution has no OS sandbox or timeout.`
31
+
32
+ const args = process.argv.slice(2)
33
+ if (args[0] === "--") args.shift()
34
+
35
+ try {
36
+ if (args.length === 1 && (args[0] === "--help" || args[0] === "-h")) {
37
+ console.log(usage)
38
+ } else if (args.length === 1 && (args[0] === "--version" || args[0] === "-v")) {
39
+ const { version } = JSON.parse(
40
+ await readFile(new URL("../package.json", import.meta.url), "utf8"),
41
+ )
42
+ console.log(version)
43
+ } else if (args[0] === "init" && args.length === 2 && !args[1].startsWith("-")) {
44
+ const root = await initProject(args[1])
45
+ console.log(`Created: ${root}\nNext: cd ${JSON.stringify(args[1])}\n matra build`)
46
+ } else if (args[0] === "build" && args.length === 1) {
47
+ const output = await buildProject(process.cwd())
48
+ console.log(`Generated: ${output}`)
49
+ } else if (
50
+ args[0] === "site" &&
51
+ args[1] === "install" &&
52
+ (args.length === 2 || (args.length === 3 && args[2] === "--yes"))
53
+ ) {
54
+ const yes = args.length === 3
55
+ const documents = await getSiteProgramDocuments(process.cwd())
56
+ if (documents.length === 0) {
57
+ console.log("No executable site pages or layouts found.")
58
+ } else {
59
+ for (const document of documents) {
60
+ console.log(`Installing dependencies for ${document}`)
61
+ await installDependencies(process.cwd(), "all", document, yes)
62
+ }
63
+ }
64
+ } else if (
65
+ args[0] === "install" ||
66
+ (args[0] === "deps" && ["install", "update"].includes(args[1]))
67
+ ) {
68
+ const update = args[0] === "deps" && args[1] === "update"
69
+ const operands = args.slice(args[0] === "deps" ? 2 : 1)
70
+ const yes = operands.at(-1) === "--yes"
71
+ if (yes) operands.pop()
72
+ const ecosystem = ["npm", "python"].includes(operands[0]) ? operands.shift() : "all"
73
+ if (
74
+ operands.length > 1 ||
75
+ operands.some(value => !value || value.startsWith("-")) ||
76
+ (ecosystem !== "all" && operands.length !== 1) ||
77
+ (update && ecosystem === "all")
78
+ ) {
79
+ throw new Error(usage)
80
+ }
81
+ await installDependencies(process.cwd(), ecosystem, operands[0] ?? "index.md", yes, update)
82
+ } else if (args[0] === "site" && args[1] === "build" && args.length === 2) {
83
+ const outputs = await buildSite(process.cwd())
84
+ console.log(`Generated ${outputs.length} site file(s)`)
85
+ } else if (
86
+ args[0] === "dev" &&
87
+ (args.length === 1 || (args.length === 3 && args[1] === "--port" && /^[0-9]+$/.test(args[2])))
88
+ ) {
89
+ const port = args.length === 1 ? 3000 : Number(args[2])
90
+ if (!Number.isInteger(port) || port < 1 || port > 65535) {
91
+ throw new Error("Port must be an integer between 1 and 65535")
92
+ }
93
+ const dev = await startDev(process.cwd(), { port })
94
+ console.log(`Serving: ${dev.url}\nWatching for changes. Refresh the browser. Ctrl+C to stop.`)
95
+ let stop
96
+ try {
97
+ await new Promise(resolve => {
98
+ stop = resolve
99
+ process.once("SIGINT", stop)
100
+ process.once("SIGTERM", stop)
101
+ })
102
+ } finally {
103
+ process.removeListener("SIGINT", stop)
104
+ process.removeListener("SIGTERM", stop)
105
+ await dev.close()
106
+ }
107
+ } else {
108
+ throw new Error(usage)
109
+ }
110
+ } catch (error) {
111
+ let message = error.message
112
+ const missingDependencies =
113
+ (error.code === "PY_PACKAGE_LOCK" &&
114
+ /Cannot read matra\.python\.lock\.json|Package is not locked/.test(message)) ||
115
+ (error.code === "JS_INITIALIZE" && /Cannot find package/.test(message))
116
+ if (missingDependencies && error.document) {
117
+ message += `\nRun \`matra install ${error.document}\` to prepare its dependencies.`
118
+ }
119
+ console.error(`${error.code ? `${error.code}: ` : ""}${message}`)
120
+ process.exitCode = 1
121
+ }
package/src/deps.mjs ADDED
@@ -0,0 +1,453 @@
1
+ import { createHash, randomUUID } from "node:crypto"
2
+ import { constants } from "node:fs"
3
+ import {
4
+ access,
5
+ copyFile,
6
+ lstat,
7
+ mkdir,
8
+ mkdtemp,
9
+ readdir,
10
+ readFile,
11
+ realpath,
12
+ rename,
13
+ rm,
14
+ writeFile,
15
+ } from "node:fs/promises"
16
+ import { tmpdir } from "node:os"
17
+ import { delimiter, dirname, isAbsolute, join, relative, resolve, sep } from "node:path"
18
+ import { env, execPath, platform, stdin, stdout } from "node:process"
19
+ import { createInterface } from "node:readline/promises"
20
+ import { authorizePlan, executePlan, planCommands } from "@matra/command"
21
+ import {
22
+ getLiterateDependencyDirectory,
23
+ getPythonPackageTarget,
24
+ readLiteratePackages,
25
+ validatePythonWheels,
26
+ } from "@matra/core/experimental/literate"
27
+
28
+ const lockFile = "matra.python.lock.json"
29
+ const wheelDirectory = "wheels"
30
+
31
+ function packageNameKey(name) {
32
+ return name.replaceAll(/[-_.]+/g, "-").toLowerCase()
33
+ }
34
+
35
+ function parsePackageNames(packages, ecosystem, document) {
36
+ const parsed = []
37
+ for (const value of packages) {
38
+ const valid =
39
+ typeof value === "string" &&
40
+ (ecosystem === "javascript"
41
+ ? /^(?:@[a-z0-9][a-z0-9._~-]*\/)?[a-z0-9][a-z0-9._~-]*$/.test(value)
42
+ : /^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(value))
43
+ if (!valid) {
44
+ throw new Error(`${document}: ${ecosystem} dependencies must be package names only: ${value}`)
45
+ }
46
+ if (!parsed.includes(value)) parsed.push(value)
47
+ }
48
+ return parsed
49
+ }
50
+
51
+ function validWheelPath(file) {
52
+ return (
53
+ typeof file === "string" &&
54
+ file.endsWith(".whl") &&
55
+ !isAbsolute(file) &&
56
+ !file.includes("\\") &&
57
+ file.split("/").every(part => part && part !== "." && part !== "..")
58
+ )
59
+ }
60
+
61
+ function inside(root, target) {
62
+ const path = relative(root, target)
63
+ return path !== ".." && !path.startsWith(`..${sep}`) && !isAbsolute(path)
64
+ }
65
+
66
+ async function readExistingLock(root, pyodide) {
67
+ const path = join(root, lockFile)
68
+ let info
69
+ try {
70
+ info = await lstat(path)
71
+ } catch (error) {
72
+ if (error.code === "ENOENT") return new Map()
73
+ throw error
74
+ }
75
+ if (!info.isFile() || info.isSymbolicLink()) {
76
+ throw new Error(`${lockFile} must be a regular file`)
77
+ }
78
+ const lock = JSON.parse(await readFile(path, "utf8"))
79
+ if (
80
+ lock?.format !== "matra-python-wheels-1" ||
81
+ lock.pyodide !== pyodide ||
82
+ !Array.isArray(lock.packages)
83
+ ) {
84
+ throw new Error(`${lockFile} must use matra-python-wheels-1 for Pyodide ${pyodide}`)
85
+ }
86
+ const rootPath = await realpath(root)
87
+ const packages = new Map()
88
+ const files = new Set()
89
+ for (const entry of lock.packages) {
90
+ const name = packageNameKey(entry?.name ?? "")
91
+ if (
92
+ !/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(name) ||
93
+ typeof entry.version !== "string" ||
94
+ !/^[A-Za-z0-9][A-Za-z0-9.+!_-]*$/.test(entry.version) ||
95
+ !validWheelPath(entry.file) ||
96
+ entry.name !== name ||
97
+ !/^[a-f0-9]{64}$/.test(entry.sha256) ||
98
+ packages.has(name) ||
99
+ files.has(entry.file)
100
+ ) {
101
+ throw new Error(`Invalid or duplicate package entry in ${lockFile}`)
102
+ }
103
+ const path = resolve(rootPath, ...entry.file.split("/"))
104
+ const resolvedPath = await realpath(path)
105
+ const wheel = await lstat(resolvedPath)
106
+ if (!inside(rootPath, resolvedPath) || !wheel.isFile()) {
107
+ throw new Error(`Invalid local wheel path in ${lockFile}: ${entry.file}`)
108
+ }
109
+ const bytes = await readFile(resolvedPath)
110
+ if (createHash("sha256").update(bytes).digest("hex") !== entry.sha256) {
111
+ throw new Error(`Wheel hash mismatch in ${lockFile}: ${entry.file}`)
112
+ }
113
+ const filename = entry.file.split("/").at(-1)
114
+ const wheelParts = filename.match(
115
+ /^(.+)-([0-9][A-Za-z0-9.+!_]*)(?:-[0-9][A-Za-z0-9.]*)?-py3-none-any\.whl$/,
116
+ )
117
+ if (!wheelParts || packageNameKey(wheelParts[1]) !== name || wheelParts[2] !== entry.version) {
118
+ throw new Error(`Wheel filename does not match package entry: ${entry.file}`)
119
+ }
120
+ packages.set(name, { ...entry, bytes })
121
+ files.add(entry.file)
122
+ }
123
+ return packages
124
+ }
125
+
126
+ function packageFromWheel(file, bytes) {
127
+ const match = file.match(
128
+ /^(.+)-([0-9][A-Za-z0-9.+!_]*)(?:-[0-9][A-Za-z0-9.]*)?-py3-none-any\.whl$/,
129
+ )
130
+ if (!match) throw new Error(`Only py3-none-any wheels are supported: ${file}`)
131
+ const name = packageNameKey(match[1])
132
+ if (!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(name)) {
133
+ throw new Error(`Invalid Python wheel package name: ${file}`)
134
+ }
135
+ return {
136
+ name,
137
+ version: match[2],
138
+ file: `${wheelDirectory}/${file}`,
139
+ sha256: createHash("sha256").update(bytes).digest("hex"),
140
+ bytes,
141
+ }
142
+ }
143
+
144
+ function executionPlan(specs) {
145
+ const children = specs.map(({ id, program, args, cwd, writes, requires = [] }) => ({
146
+ tag: "command",
147
+ props: {
148
+ id,
149
+ program,
150
+ args,
151
+ cwd,
152
+ produces: writes,
153
+ requires,
154
+ capabilities: {
155
+ read: [cwd],
156
+ write: writes,
157
+ network: true,
158
+ },
159
+ },
160
+ children: [],
161
+ }))
162
+ return planCommands({ tag: "root", props: {}, children: children })
163
+ }
164
+
165
+ async function npmInvocation() {
166
+ if (platform !== "win32") return { program: "npm", args: [] }
167
+ const candidates = [
168
+ ...(env.npm_execpath?.endsWith(".js") ? [env.npm_execpath] : []),
169
+ ...(env.PATH ?? "")
170
+ .split(delimiter)
171
+ .filter(Boolean)
172
+ .map(directory => join(directory, "node_modules", "npm", "bin", "npm-cli.js")),
173
+ ]
174
+ for (const candidate of candidates) {
175
+ try {
176
+ await access(candidate)
177
+ return { program: execPath, args: [candidate] }
178
+ } catch (error) {
179
+ if (error.code !== "ENOENT") throw error
180
+ }
181
+ }
182
+ throw new Error("Cannot locate npm-cli.js; install npm and ensure it is available on PATH")
183
+ }
184
+
185
+ async function confirmPlan(plan, yes) {
186
+ console.log("The following external commands will run with network access:")
187
+ for (const command of plan.commands) {
188
+ console.log(` ${command.program} ${command.args.map(arg => JSON.stringify(arg)).join(" ")}`)
189
+ }
190
+ if (yes) return
191
+ if (!stdin.isTTY || !stdout.isTTY) {
192
+ throw new Error("Cannot prompt for dependency installation; rerun with --yes to confirm")
193
+ }
194
+ const prompt = createInterface({ input: stdin, output: stdout })
195
+ try {
196
+ const answer = await prompt.question("Continue? [y/N] ")
197
+ if (!/^(y|yes)$/i.test(answer.trim())) throw new Error("Dependency installation cancelled")
198
+ } finally {
199
+ prompt.close()
200
+ }
201
+ }
202
+
203
+ async function ensureDirectory(path) {
204
+ const target = resolve(path)
205
+ const missing = []
206
+ let current = target
207
+ while (true) {
208
+ try {
209
+ const info = await lstat(current)
210
+ if (!info.isDirectory() || info.isSymbolicLink()) {
211
+ throw new Error(`Expected a regular directory, not a file or symlink: ${current}`)
212
+ }
213
+ break
214
+ } catch (error) {
215
+ if (error.code !== "ENOENT") throw error
216
+ missing.push(current)
217
+ const parent = dirname(current)
218
+ if (parent === current) throw new Error(`Cannot find a parent directory for ${target}`)
219
+ current = parent
220
+ }
221
+ }
222
+ for (const directory of missing.reverse()) {
223
+ try {
224
+ await mkdir(directory)
225
+ } catch (error) {
226
+ if (error.code !== "EEXIST") throw error
227
+ }
228
+ const info = await lstat(directory)
229
+ if (!info.isDirectory() || info.isSymbolicLink()) {
230
+ throw new Error(`Expected a regular directory, not a file or symlink: ${directory}`)
231
+ }
232
+ }
233
+ }
234
+
235
+ async function prepareNpmManifest(directory, packages) {
236
+ await ensureDirectory(directory)
237
+ const manifest = join(directory, "package.json")
238
+ try {
239
+ const info = await lstat(manifest)
240
+ if (!info.isFile() || info.isSymbolicLink()) {
241
+ throw new Error("Generated package.json must be a regular file")
242
+ }
243
+ } catch (error) {
244
+ if (error.code !== "ENOENT") throw error
245
+ }
246
+ const contents = {
247
+ private: true,
248
+ type: "module",
249
+ dependencies: Object.fromEntries(packages.map(name => [name, "*"])),
250
+ }
251
+ await writeFile(manifest, `${JSON.stringify(contents, null, 2)}\n`)
252
+ }
253
+
254
+ async function installPythonPackages(root, requirements, staging, document) {
255
+ const requested = new Set(requirements.map(packageNameKey))
256
+ const wheels = []
257
+ for (const file of await readdir(staging)) {
258
+ if (!file.endsWith(".whl")) continue
259
+ const bytes = await readFile(join(staging, file))
260
+ wheels.push(packageFromWheel(file, bytes))
261
+ }
262
+ if (wheels.length === 0) throw new Error("pip download completed without producing any wheels")
263
+ const names = new Set()
264
+ for (const wheel of wheels) {
265
+ if (names.has(wheel.name)) throw new Error(`pip produced duplicate wheels for ${wheel.name}`)
266
+ names.add(wheel.name)
267
+ }
268
+ for (const name of requested) {
269
+ if (!names.has(name)) {
270
+ throw new Error(`pip did not produce the requested Python package: ${name}`)
271
+ }
272
+ }
273
+ await validatePythonWheels(wheels, document)
274
+
275
+ const wheelRoot = join(root, wheelDirectory)
276
+ await ensureDirectory(wheelRoot)
277
+ for (const wheel of wheels) {
278
+ const destination = join(wheelRoot, wheel.file.split("/").at(-1))
279
+ try {
280
+ await copyFile(
281
+ join(staging, wheel.file.split("/").at(-1)),
282
+ destination,
283
+ constants.COPYFILE_EXCL,
284
+ )
285
+ } catch (error) {
286
+ if (error.code !== "EEXIST") throw error
287
+ const info = await lstat(destination)
288
+ if (!info.isFile() || info.isSymbolicLink()) {
289
+ throw new Error(`Refusing to overwrite a non-regular wheel file: ${wheel.file}`)
290
+ }
291
+ const existing = await readFile(destination)
292
+ if (!existing.equals(wheel.bytes)) {
293
+ throw new Error(`Refusing to overwrite a different wheel file: ${wheel.file}`)
294
+ }
295
+ }
296
+ }
297
+ const lock = {
298
+ format: "matra-python-wheels-1",
299
+ pyodide: getPythonPackageTarget().pyodide,
300
+ packages: wheels
301
+ .map(({ bytes: _bytes, ...entry }) => entry)
302
+ .sort((left, right) => left.name.localeCompare(right.name)),
303
+ }
304
+ const temporary = join(root, `.${lockFile}.${randomUUID()}.tmp`)
305
+ try {
306
+ await writeFile(temporary, `${JSON.stringify(lock, null, 2)}\n`, { flag: "wx" })
307
+ await rename(temporary, join(root, lockFile))
308
+ } finally {
309
+ await rm(temporary, { force: true })
310
+ }
311
+ console.log(`Updated: ${lockFile} (${wheels.length} wheel(s) downloaded)`)
312
+ }
313
+
314
+ export async function installDependencies(
315
+ root,
316
+ ecosystem,
317
+ documentPath,
318
+ yes = false,
319
+ update = false,
320
+ ) {
321
+ if (!["all", "npm", "python"].includes(ecosystem)) {
322
+ throw new Error("Specify an ecosystem: all, npm or python")
323
+ }
324
+ root = await realpath(resolve(root))
325
+ if (!documentPath || isAbsolute(documentPath) || documentPath.split(/[\\/]/).includes("..")) {
326
+ throw new Error("Specify a Markdown document path relative to the project root")
327
+ }
328
+ const document = resolve(root, documentPath)
329
+ if (!inside(root, document)) throw new Error("Document path must remain inside the project root")
330
+ const documentInfo = await lstat(document)
331
+ if (!documentInfo.isFile() || documentInfo.isSymbolicLink()) {
332
+ throw new Error("Document path must be a regular file inside the project root")
333
+ }
334
+ const documentName = relative(root, document)
335
+ const markdown = await readFile(document, "utf8")
336
+ const declared = readLiteratePackages(markdown, { document: documentName })
337
+ const npmPackages =
338
+ ecosystem === "python" ? [] : parsePackageNames(declared.javascript, "javascript", documentName)
339
+ const pythonPackages =
340
+ ecosystem === "npm" ? [] : parsePackageNames(declared.python, "python", documentName)
341
+ if (npmPackages.length === 0 && pythonPackages.length === 0) {
342
+ const label = ecosystem === "all" ? "" : `${ecosystem} `
343
+ console.log(`No ${label}dependencies declared in ${documentName}.`)
344
+ return
345
+ }
346
+
347
+ const npmRoot = getLiterateDependencyDirectory(root, documentName, "javascript")
348
+ const pythonRoot = getLiterateDependencyDirectory(root, documentName, "python")
349
+ if (npmPackages.length) await ensureDirectory(npmRoot)
350
+ if (pythonPackages.length) await ensureDirectory(pythonRoot)
351
+ const stagingRoot = pythonPackages.length ? await mkdtemp(join(tmpdir(), "matra-python-")) : null
352
+ try {
353
+ const specs = []
354
+ let npmCommand
355
+ let pythonWheels
356
+ let pythonConstraints
357
+ if (npmPackages.length) {
358
+ npmCommand = await npmInvocation()
359
+ specs.push({
360
+ id: update ? "npm-update" : "npm-install",
361
+ program: npmCommand.program,
362
+ args: [
363
+ ...npmCommand.args,
364
+ update ? "update" : "install",
365
+ "--prefix",
366
+ npmRoot,
367
+ "--ignore-scripts",
368
+ "--no-audit",
369
+ "--no-fund",
370
+ ],
371
+ cwd: root,
372
+ writes: [npmRoot],
373
+ })
374
+ }
375
+ if (pythonPackages.length) {
376
+ const target = getPythonPackageTarget()
377
+ const oldPackages = update ? new Map() : await readExistingLock(pythonRoot, target.pyodide)
378
+ pythonWheels = join(stagingRoot, "wheels")
379
+ await mkdir(pythonWheels)
380
+ const args = [
381
+ "-m",
382
+ "pip",
383
+ "download",
384
+ "--only-binary=:all:",
385
+ "--implementation",
386
+ "py",
387
+ "--python-version",
388
+ target.python.split(".").slice(0, 2).join("."),
389
+ "--abi",
390
+ "none",
391
+ "--platform",
392
+ "any",
393
+ "--dest",
394
+ pythonWheels,
395
+ ]
396
+ if (oldPackages.size) {
397
+ pythonConstraints = join(stagingRoot, "constraints.txt")
398
+ await writeFile(
399
+ pythonConstraints,
400
+ [...oldPackages.values()].map(({ name, version }) => `${name}==${version}\n`).join(""),
401
+ )
402
+ args.push("--constraint", pythonConstraints)
403
+ }
404
+ args.push(...pythonPackages)
405
+ const python =
406
+ process.env.MATRA_PYTHON ?? (process.platform === "win32" ? "python" : "python3")
407
+ specs.push({
408
+ id: "python-wheels",
409
+ program: python,
410
+ args,
411
+ cwd: root,
412
+ writes: [stagingRoot, pythonRoot],
413
+ requires: npmPackages.length ? [update ? "npm-update" : "npm-install"] : [],
414
+ })
415
+ }
416
+ const plan = executionPlan(specs)
417
+ await confirmPlan(plan, yes)
418
+ if (npmPackages.length) await prepareNpmManifest(npmRoot, npmPackages)
419
+ const authorized = authorizePlan(plan, {
420
+ commands: plan.capabilities.commands,
421
+ read: plan.capabilities.read,
422
+ write: plan.capabilities.write,
423
+ network: true,
424
+ })
425
+ const controller = new AbortController()
426
+ const abort = () => controller.abort()
427
+ process.once("SIGINT", abort)
428
+ process.once("SIGTERM", abort)
429
+ let result
430
+ try {
431
+ result = await executePlan(authorized, {
432
+ signal: controller.signal,
433
+ onEvent: event => {
434
+ if (event.type === "finish" && event.result?.status !== "ok") {
435
+ const details = [event.result?.error, event.result?.stderr?.trim()]
436
+ .filter(Boolean)
437
+ .join(": ")
438
+ console.error(`${event.command.id}: ${details || "failed"}`)
439
+ }
440
+ },
441
+ })
442
+ } finally {
443
+ process.removeListener("SIGINT", abort)
444
+ process.removeListener("SIGTERM", abort)
445
+ }
446
+ if (result.status !== "ok") throw new Error("Dependency command failed")
447
+ if (pythonPackages.length) {
448
+ await installPythonPackages(pythonRoot, pythonPackages, pythonWheels, documentName)
449
+ }
450
+ } finally {
451
+ if (stagingRoot) await rm(stagingRoot, { recursive: true, force: true })
452
+ }
453
+ }
package/src/dev.mjs ADDED
@@ -0,0 +1,116 @@
1
+ import { unwatchFile, watchFile } from "node:fs"
2
+ import { readFile } from "node:fs/promises"
3
+ import { createServer } from "node:http"
4
+ import { join, resolve } from "node:path"
5
+ import { buildProject } from "./project.mjs"
6
+
7
+ const assets = [
8
+ ["index.html", "text/html; charset=utf-8"],
9
+ ["matra.css", "text/css; charset=utf-8"],
10
+ ["matra.css.LICENSE", "text/plain; charset=utf-8"],
11
+ ]
12
+
13
+ export async function startDev(
14
+ directory,
15
+ { port = 3000, onBuild = console.log, onError = console.error } = {},
16
+ ) {
17
+ const root = resolve(directory)
18
+ let snapshot
19
+ let failure
20
+ let timer
21
+ let building
22
+ let pending = false
23
+ let closed = false
24
+
25
+ async function refresh() {
26
+ const output = await buildProject(root)
27
+ const entries = await Promise.all(
28
+ assets.map(async ([name, type]) => [
29
+ `/${name}`,
30
+ { type, body: await readFile(join(root, "dist", name)) },
31
+ ]),
32
+ )
33
+ snapshot = new Map(entries)
34
+ failure = undefined
35
+ onBuild(`Generated: ${output}`)
36
+ }
37
+
38
+ async function rebuild() {
39
+ pending = false
40
+ try {
41
+ await refresh()
42
+ } catch (error) {
43
+ failure = `${error.code ? `${error.code}: ` : ""}${error.message}`
44
+ onError(`Build failed: ${failure}\nWaiting for changes.`)
45
+ }
46
+ }
47
+
48
+ function schedule() {
49
+ if (closed) return
50
+ pending = true
51
+ clearTimeout(timer)
52
+ timer = setTimeout(() => {
53
+ if (building) return
54
+ building = rebuild().finally(() => {
55
+ building = undefined
56
+ if (pending && !closed) schedule()
57
+ })
58
+ }, 100)
59
+ }
60
+
61
+ const server = createServer((request, response) => {
62
+ response.setHeader("Cache-Control", "no-store")
63
+ response.setHeader("X-Content-Type-Options", "nosniff")
64
+ if (request.method !== "GET" && request.method !== "HEAD") {
65
+ response.writeHead(405, { Allow: "GET, HEAD" })
66
+ response.end()
67
+ return
68
+ }
69
+ const path = request.url.split("?")[0]
70
+ const asset = snapshot?.get(path === "/" ? "/index.html" : path)
71
+ const status = !asset ? 404 : failure ? 503 : 200
72
+ const body = !asset ? "Not found\n" : failure ? `Build failed: ${failure}\n` : asset.body
73
+ response.writeHead(status, {
74
+ "Content-Type": status === 200 ? asset.type : "text/plain; charset=utf-8",
75
+ })
76
+ response.end(request.method === "HEAD" ? undefined : body)
77
+ })
78
+
79
+ const watched = ["index.md", "matra.css", "matra.css.LICENSE"].map(name => join(root, name))
80
+ for (const path of watched) watchFile(path, { interval: 200 }, schedule)
81
+
82
+ async function close() {
83
+ closed = true
84
+ clearTimeout(timer)
85
+ for (const path of watched) unwatchFile(path, schedule)
86
+ if (building) await building
87
+ if (server.listening) {
88
+ await new Promise((resolveClose, reject) => {
89
+ server.close(error => (error ? reject(error) : resolveClose()))
90
+ server.closeAllConnections()
91
+ })
92
+ }
93
+ }
94
+
95
+ try {
96
+ building = refresh()
97
+ try {
98
+ await building
99
+ } finally {
100
+ building = undefined
101
+ }
102
+ if (pending) schedule()
103
+ await new Promise((resolveListen, reject) => {
104
+ server.once("error", reject)
105
+ server.listen(port, "127.0.0.1", () => {
106
+ server.removeListener("error", reject)
107
+ resolveListen()
108
+ })
109
+ })
110
+ } catch (error) {
111
+ await close()
112
+ throw error
113
+ }
114
+ server.on("error", onError)
115
+ return { url: `http://127.0.0.1:${server.address().port}/`, close }
116
+ }
@@ -0,0 +1,68 @@
1
+ import { copyFile, lstat, mkdir, readFile, writeFile } from "node:fs/promises"
2
+ import { join, resolve } from "node:path"
3
+ import { toHTML } from "@matra/html"
4
+ import { renderLiterateDocument } from "@matra/site-generation"
5
+
6
+ const template = new URL("../templates/basic/", import.meta.url)
7
+ const stylesheet = new URL(import.meta.resolve("@matra/styles/matra.css"))
8
+
9
+ export async function initProject(directory) {
10
+ const root = resolve(directory)
11
+ const files = [
12
+ ["index.md", await readFile(new URL("index.md", template))],
13
+ [".gitignore", await readFile(new URL("gitignore", template))],
14
+ ["matra.css", await readFile(stylesheet)],
15
+ ["matra.css.LICENSE", await readFile(new URL("LICENSE", stylesheet))],
16
+ ]
17
+ await mkdir(root)
18
+ for (const [name, content] of files) {
19
+ await writeFile(join(root, name), content, { flag: "wx" })
20
+ }
21
+ return root
22
+ }
23
+
24
+ async function regularFile(path) {
25
+ if (!(await lstat(path)).isFile()) {
26
+ throw new Error(`Expected a regular file, not a directory or symlink: ${path}`)
27
+ }
28
+ }
29
+
30
+ async function outputFile(path) {
31
+ try {
32
+ await regularFile(path)
33
+ } catch (error) {
34
+ if (error.code !== "ENOENT") throw error
35
+ }
36
+ }
37
+
38
+ export async function buildProject(directory) {
39
+ const root = resolve(directory)
40
+ const source = join(root, "index.md")
41
+ const css = join(root, "matra.css")
42
+ const license = join(root, "matra.css.LICENSE")
43
+ await regularFile(source)
44
+ await regularFile(css)
45
+ await regularFile(license)
46
+ const ast = await renderLiterateDocument(await readFile(source, "utf8"), {
47
+ document: "index.md",
48
+ moduleRoot: root,
49
+ })
50
+ const html = `<!doctype html>\n${toHTML(ast)}\n`
51
+ const output = join(root, "dist")
52
+ try {
53
+ await mkdir(output)
54
+ } catch (error) {
55
+ if (error.code !== "EEXIST") throw error
56
+ if (!(await lstat(output)).isDirectory()) {
57
+ throw new Error(`Expected an output directory, not a file or symlink: ${output}`)
58
+ }
59
+ }
60
+ const htmlOutput = join(output, "index.html")
61
+ const cssOutput = join(output, "matra.css")
62
+ const licenseOutput = join(output, "matra.css.LICENSE")
63
+ for (const path of [htmlOutput, cssOutput, licenseOutput]) await outputFile(path)
64
+ await writeFile(htmlOutput, html, "utf8")
65
+ await copyFile(css, cssOutput)
66
+ await copyFile(license, licenseOutput)
67
+ return htmlOutput
68
+ }
@@ -0,0 +1,11 @@
1
+ /dist/
2
+ .matra/*
3
+ !.matra/deps/
4
+ .matra/deps/*
5
+ !.matra/deps/*/
6
+ .matra/deps/*/javascript/**
7
+ !.matra/deps/*/javascript/package-lock.json
8
+ .matra/deps/*/python/**
9
+ !.matra/deps/*/python/matra.python.lock.json
10
+ !.matra/deps/*/python/wheels/
11
+ !.matra/deps/*/python/wheels/*.whl
@@ -0,0 +1,60 @@
1
+ ---
2
+ matra:
3
+ entry: main.matra
4
+ values:
5
+ - content.js.part
6
+ ---
7
+
8
+ # Hello, Matra
9
+
10
+ Edit this document, then run `matra build`.
11
+ Open `dist/index.html` in a browser. No network connection is needed to view it.
12
+ For a local preview, run `matra dev` and open the URL printed in the terminal.
13
+ Changes rebuild automatically; refresh the browser to see them. Press Ctrl+C to stop.
14
+
15
+ ## Page structure
16
+
17
+ ```main.matra
18
+ html(lang="en") {
19
+ head {
20
+ meta(charset="utf-8") {}
21
+ meta(name="viewport" content="width=device-width, initial-scale=1") {}
22
+ title { content.title }
23
+ link(rel="stylesheet" href="./matra.css") {}
24
+ }
25
+ body {
26
+ header {
27
+ h1 { content.title }
28
+ }
29
+ main {
30
+ p { content.message }
31
+ h2 { "Get started" }
32
+ ol {
33
+ ...for (step in content.steps) {
34
+ li { step }
35
+ }
36
+ }
37
+ }
38
+ footer {
39
+ p { "Built with Matra." }
40
+ }
41
+ }
42
+ }
43
+ ```
44
+
45
+ ## Page content
46
+
47
+ The selected JavaScript expression below supplies the page data.
48
+ Only build documents you trust: their JavaScript is executed during the build.
49
+
50
+ ```content.js.part
51
+ ({
52
+ title: "Hello, Matra!",
53
+ message: "Your first Matra page is ready.",
54
+ steps: [
55
+ "Edit index.md to change the structure and content.",
56
+ "Edit matra.css to customize the appearance.",
57
+ "Run matra build and open dist/index.html."
58
+ ]
59
+ })
60
+ ```
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
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.