@pathmx/generate 0.6.5
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.md +172 -0
- package/README.md +18 -0
- package/command.ts +31 -0
- package/data.ts +43 -0
- package/index.ts +33 -0
- package/model.ts +12 -0
- package/package.json +35 -0
- package/paths.ts +47 -0
- package/plan.ts +126 -0
- package/report.ts +49 -0
package/LICENSE.md
ADDED
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
# PathMX Proprietary Beta License
|
|
2
|
+
|
|
3
|
+
Version 0.1 — July 21, 2026
|
|
4
|
+
|
|
5
|
+
Copyright © 2026 DUO Interactive, LLC.
|
|
6
|
+
All rights reserved.
|
|
7
|
+
|
|
8
|
+
This license governs the first-party PathMX software distributed in the npm
|
|
9
|
+
package `@pathmx/core`, including its command-line interface, bundled
|
|
10
|
+
library surfaces, runtime and Player components, and accompanying
|
|
11
|
+
documentation (the “Software”). DUO Interactive, LLC is the “Licensor.” This
|
|
12
|
+
license does not cover the private PathMX source-code repository or separately
|
|
13
|
+
identified third-party materials.
|
|
14
|
+
|
|
15
|
+
“Project” means Paths, Sources, responses, data, and other content authored or
|
|
16
|
+
processed with the Software.
|
|
17
|
+
|
|
18
|
+
“Application” means software or a service created by you in which the Software
|
|
19
|
+
supports product-specific functionality but is not itself offered as a
|
|
20
|
+
general-purpose PathMX product.
|
|
21
|
+
|
|
22
|
+
“Redistributable Components” means runtime, Player, or library portions of the
|
|
23
|
+
Software incorporated into a Project, Application, or generated output through
|
|
24
|
+
ordinary use of the Software or ordinary compilation and bundling tools.
|
|
25
|
+
|
|
26
|
+
“Authorized Users” means your employees and individual contractors who use the
|
|
27
|
+
Software on your behalf, and your hosting, continuous-integration, and other
|
|
28
|
+
service providers that possess or run necessary copies solely to provide
|
|
29
|
+
services to you.
|
|
30
|
+
|
|
31
|
+
## 1. Agreement
|
|
32
|
+
|
|
33
|
+
By installing, accessing, or using the Software, you agree to this license. If
|
|
34
|
+
you use the Software on behalf of an organization, you represent that you have
|
|
35
|
+
authority to accept this license for that organization. If you do not agree,
|
|
36
|
+
do not install or use the Software.
|
|
37
|
+
|
|
38
|
+
## 2. License grant
|
|
39
|
+
|
|
40
|
+
Subject to this license, the Licensor grants you a non-exclusive, worldwide,
|
|
41
|
+
royalty-free, non-transferable, and non-sublicensable license, perpetual for
|
|
42
|
+
the version of the Software to which it applies unless terminated under
|
|
43
|
+
Section 10, to:
|
|
44
|
+
|
|
45
|
+
- install, execute, and use the Software for personal, educational,
|
|
46
|
+
internal-business, or commercial purposes;
|
|
47
|
+
- use the Software to author, integrate, build, test, serve, play, host, and
|
|
48
|
+
operate Projects and Applications;
|
|
49
|
+
- import, compile, bundle, configure, and integrate the Software through its
|
|
50
|
+
documented library and command-line interfaces;
|
|
51
|
+
- create and distribute independent Projects, Applications, plugins, and
|
|
52
|
+
integrations that use those interfaces without modifying the Software
|
|
53
|
+
itself; and
|
|
54
|
+
- make copies reasonably necessary for local development, testing, continuous
|
|
55
|
+
integration, backup, and hosted production environments.
|
|
56
|
+
|
|
57
|
+
Your Authorized Users may exercise those rights solely on your behalf. You are
|
|
58
|
+
responsible for their compliance with this license.
|
|
59
|
+
|
|
60
|
+
You may reproduce and distribute Redistributable Components only as
|
|
61
|
+
incorporated into your Project, Application, or generated output, and only when
|
|
62
|
+
you preserve applicable license and proprietary notices. You may host and
|
|
63
|
+
commercially provide access to that Project, Application, or output. You may
|
|
64
|
+
not distribute Redistributable Components as a standalone package or as a
|
|
65
|
+
general-purpose substitute for the Software.
|
|
66
|
+
|
|
67
|
+
Each lawful recipient of a Redistributable Component may execute and use that
|
|
68
|
+
component, display its output, and make technically necessary transitory copies
|
|
69
|
+
solely as incorporated into the Project, Application, or output in which they
|
|
70
|
+
received it. This limited recipient permission does not include a right to
|
|
71
|
+
extract, modify, or redistribute the component separately.
|
|
72
|
+
|
|
73
|
+
## 3. Restrictions
|
|
74
|
+
|
|
75
|
+
Except where applicable law does not allow the restriction, you may not:
|
|
76
|
+
|
|
77
|
+
- modify, adapt, translate, or create derivative works of the Software, except
|
|
78
|
+
for the compilation, bundling, configuration, and integration expressly
|
|
79
|
+
permitted in Section 2;
|
|
80
|
+
- redistribute, sublicense, sell, lease, or otherwise provide the Software to
|
|
81
|
+
another person as a standalone package, product, or service except to an
|
|
82
|
+
Authorized User or as a Redistributable Component under Section 2;
|
|
83
|
+
- resell, rebrand, or provide the Software as a hosted or managed service that
|
|
84
|
+
gives third parties general-purpose access to substantial PathMX authoring,
|
|
85
|
+
building, serving, Player-administration, or library functionality for their
|
|
86
|
+
own unrelated projects;
|
|
87
|
+
- reverse engineer, decompile, disassemble, or otherwise attempt to derive the
|
|
88
|
+
source code of the Software; or
|
|
89
|
+
- remove or alter copyright, license, trademark, or other proprietary notices.
|
|
90
|
+
|
|
91
|
+
For clarity, the managed-service restriction does not prohibit a hosted
|
|
92
|
+
Project or Application in which PathMX supports the licensee's own
|
|
93
|
+
product-specific experience and is not itself the general-purpose product
|
|
94
|
+
offered to customers.
|
|
95
|
+
|
|
96
|
+
## 4. Your content
|
|
97
|
+
|
|
98
|
+
As between you and the Licensor, you retain ownership of the Paths, Sources,
|
|
99
|
+
responses, data, independent application code, and other content that you
|
|
100
|
+
author or provide while using the Software. You are responsible for that
|
|
101
|
+
content and for having the rights needed to use it.
|
|
102
|
+
|
|
103
|
+
Generated output may contain Redistributable Components or third-party
|
|
104
|
+
materials. Your ownership of your content does not change the ownership or
|
|
105
|
+
license terms of those components and materials.
|
|
106
|
+
|
|
107
|
+
## 5. Ownership and trademarks
|
|
108
|
+
|
|
109
|
+
The Software is licensed, not sold. The Licensor and its suppliers retain all
|
|
110
|
+
rights in the Software not expressly granted by this license. This license
|
|
111
|
+
does not grant permission to use the PathMX name, logos, or other marks except
|
|
112
|
+
as reasonably necessary to identify the Software accurately.
|
|
113
|
+
|
|
114
|
+
## 6. Beta status and changes
|
|
115
|
+
|
|
116
|
+
The Software is a proprietary beta release. Its APIs, behavior, file formats,
|
|
117
|
+
and features may change or be removed without notice. The Licensor has no
|
|
118
|
+
obligation to provide support, maintenance, updates, continued availability,
|
|
119
|
+
or backward compatibility. A later version may be offered under different
|
|
120
|
+
license terms, including an open-source license. Different terms for a later
|
|
121
|
+
version do not change the license previously granted for an earlier version.
|
|
122
|
+
|
|
123
|
+
## 7. Third-party materials
|
|
124
|
+
|
|
125
|
+
The Software and Redistributable Components may include or depend on
|
|
126
|
+
third-party materials governed by their own license terms. Those terms control
|
|
127
|
+
for the applicable third-party materials. You must preserve third-party notices
|
|
128
|
+
when the applicable third-party terms require it.
|
|
129
|
+
|
|
130
|
+
## 8. Disclaimer of warranties
|
|
131
|
+
|
|
132
|
+
TO THE MAXIMUM EXTENT PERMITTED BY LAW, THE SOFTWARE IS PROVIDED “AS IS” AND
|
|
133
|
+
“AS AVAILABLE,” WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EXPRESS,
|
|
134
|
+
IMPLIED, OR STATUTORY, INCLUDING WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
|
|
135
|
+
PARTICULAR PURPOSE, TITLE, NON-INFRINGEMENT, OR THAT THE SOFTWARE WILL BE
|
|
136
|
+
SECURE, ERROR-FREE, OR UNINTERRUPTED.
|
|
137
|
+
|
|
138
|
+
## 9. Limitation of liability
|
|
139
|
+
|
|
140
|
+
TO THE MAXIMUM EXTENT PERMITTED BY LAW, THE LICENSOR AND ITS CONTRIBUTORS,
|
|
141
|
+
SUPPLIERS, AND AFFILIATES WILL NOT BE LIABLE FOR ANY INDIRECT, INCIDENTAL,
|
|
142
|
+
SPECIAL, CONSEQUENTIAL, EXEMPLARY, OR PUNITIVE DAMAGES, OR FOR LOSS OF DATA,
|
|
143
|
+
PROFITS, REVENUE, GOODWILL, OR BUSINESS OPPORTUNITY, ARISING FROM OR RELATED TO
|
|
144
|
+
THE SOFTWARE OR THIS LICENSE, EVEN IF ADVISED OF THE POSSIBILITY OF THOSE
|
|
145
|
+
DAMAGES.
|
|
146
|
+
|
|
147
|
+
TO THE MAXIMUM EXTENT PERMITTED BY LAW, THEIR TOTAL LIABILITY FOR ALL CLAIMS
|
|
148
|
+
ARISING FROM OR RELATED TO THE SOFTWARE OR THIS LICENSE WILL NOT EXCEED THE
|
|
149
|
+
GREATER OF THE AMOUNT YOU PAID FOR THE SOFTWARE DURING THE TWELVE MONTHS BEFORE
|
|
150
|
+
THE EVENT GIVING RISE TO THE CLAIM OR US$100.
|
|
151
|
+
|
|
152
|
+
## 10. Termination
|
|
153
|
+
|
|
154
|
+
This license terminates if you materially breach it and do not cure the breach
|
|
155
|
+
within thirty days after receiving written notice from the Licensor. On
|
|
156
|
+
termination, you and your Authorized Users must stop using and delete your
|
|
157
|
+
copies of the Software. Sections 4, 5, 8, 9, 10, and 11 survive termination.
|
|
158
|
+
Termination does not withdraw the limited permission already granted by
|
|
159
|
+
Section 2 to lawful recipients of Redistributable Components distributed
|
|
160
|
+
before termination.
|
|
161
|
+
|
|
162
|
+
## 11. General
|
|
163
|
+
|
|
164
|
+
If a provision of this license is unenforceable, it will be modified only to
|
|
165
|
+
the minimum extent necessary to make it enforceable, and the remaining
|
|
166
|
+
provisions will continue in effect. Failure to enforce a provision is not a
|
|
167
|
+
waiver. You may not assign or transfer this license without the Licensor's
|
|
168
|
+
written consent. The Licensor may assign this license together with ownership
|
|
169
|
+
of the Software to a successor owner. This license binds and benefits the
|
|
170
|
+
permitted successors and assigns of you and the Licensor. This license is the
|
|
171
|
+
entire agreement concerning the Software unless you and the Licensor have
|
|
172
|
+
signed a separate agreement that expressly replaces it.
|
package/README.md
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
# @pathmx/generate
|
|
2
|
+
|
|
3
|
+
Generate ordinary PathMX Sources from Knap templates and JSON or CSV data.
|
|
4
|
+
Run once with CLI arguments, or save a repeatable recipe in any Source.
|
|
5
|
+
|
|
6
|
+
```sh
|
|
7
|
+
bun run pmx plugins add generate
|
|
8
|
+
bun run pmx generate --template templates/artist.knap.md \
|
|
9
|
+
--data data/artists.json --output 'paths/artists/{{ slug }}.artist.md' --dry-run
|
|
10
|
+
```
|
|
11
|
+
|
|
12
|
+
Each input record supplies the template variables. Remove `--dry-run` to create
|
|
13
|
+
Sources; use `--overwrite --dry-run` to review replacements. Saved recipes use
|
|
14
|
+
a `generate` declaration in Source frontmatter and run with
|
|
15
|
+
`bun run pmx generate paths/artists.recipe.md`.
|
|
16
|
+
|
|
17
|
+
See the [Generate reference](https://docs.pathmx.dev/docs/authoring/generate.reference)
|
|
18
|
+
for a complete example, path rules, data formats, and replacement behavior.
|
package/command.ts
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import type { PluginCommandContext } from "@pathmx/core"
|
|
2
|
+
import { planGeneration, type Flags } from "./plan.ts"
|
|
3
|
+
import { destinationContent } from "./paths.ts"
|
|
4
|
+
import { generationReport, printReport } from "./report.ts"
|
|
5
|
+
|
|
6
|
+
export async function generate(
|
|
7
|
+
ctx: PluginCommandContext,
|
|
8
|
+
recipe: string | undefined,
|
|
9
|
+
flags: Flags,
|
|
10
|
+
) {
|
|
11
|
+
const plan = await planGeneration(ctx, recipe, flags)
|
|
12
|
+
await ctx.mutate(
|
|
13
|
+
async (tx) => {
|
|
14
|
+
for (const file of plan.outputs) {
|
|
15
|
+
const current = await destinationContent(ctx.pathsRoot, file.path)
|
|
16
|
+
if (current !== file.before)
|
|
17
|
+
throw new Error(
|
|
18
|
+
`Source changed after generation was planned: ${file.path}. Run the command again.`,
|
|
19
|
+
)
|
|
20
|
+
if (file.status === "unchanged") continue
|
|
21
|
+
// Transactions accept canonical ids; the suffix-free file path also
|
|
22
|
+
// preserves untyped filenames such as index.md when creating a Source.
|
|
23
|
+
const id = file.path.slice(0, -3)
|
|
24
|
+
if (file.status === "create") await tx.create(id, file.content)
|
|
25
|
+
else await tx.update(id, file.content)
|
|
26
|
+
}
|
|
27
|
+
},
|
|
28
|
+
{ dryRun: flags.dryRun },
|
|
29
|
+
)
|
|
30
|
+
printReport(generationReport(plan, !!flags.dryRun), !!flags.json)
|
|
31
|
+
}
|
package/data.ts
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import { readFile } from "node:fs/promises"
|
|
2
|
+
import { extname } from "node:path"
|
|
3
|
+
import { parse } from "csv-parse/sync"
|
|
4
|
+
import type { TemplateVariables } from "knap"
|
|
5
|
+
|
|
6
|
+
export async function readData(path: string, format?: "json" | "csv") {
|
|
7
|
+
const kind =
|
|
8
|
+
format ?? (extname(path).toLowerCase() === ".csv" ? "csv" : "json")
|
|
9
|
+
if (path === "-" && process.stdin.isTTY)
|
|
10
|
+
throw new Error("--data - requires piped JSON or CSV input.")
|
|
11
|
+
const text =
|
|
12
|
+
path === "-"
|
|
13
|
+
? await new Response(Bun.stdin.stream()).text()
|
|
14
|
+
: await readFile(path, "utf8")
|
|
15
|
+
let value: unknown
|
|
16
|
+
try {
|
|
17
|
+
if (kind === "csv") {
|
|
18
|
+
value = parse(text, {
|
|
19
|
+
bom: true,
|
|
20
|
+
skip_empty_lines: true,
|
|
21
|
+
columns(headers: string[]) {
|
|
22
|
+
if (
|
|
23
|
+
headers.some((header) => !header.trim()) ||
|
|
24
|
+
new Set(headers).size !== headers.length
|
|
25
|
+
)
|
|
26
|
+
throw new Error("CSV column names must be nonempty and unique.")
|
|
27
|
+
return headers
|
|
28
|
+
},
|
|
29
|
+
})
|
|
30
|
+
} else value = JSON.parse(text.replace(/^\uFEFF/, ""))
|
|
31
|
+
} catch (error) {
|
|
32
|
+
throw new Error(
|
|
33
|
+
`${path}: invalid ${kind.toUpperCase()}: ${error instanceof Error ? error.message : error}`,
|
|
34
|
+
)
|
|
35
|
+
}
|
|
36
|
+
const records = Array.isArray(value) ? value : [value]
|
|
37
|
+
if (!records.length) throw new Error(`${path}: no records to generate.`)
|
|
38
|
+
for (const [index, record] of records.entries()) {
|
|
39
|
+
if (!record || typeof record !== "object" || Array.isArray(record))
|
|
40
|
+
throw new Error(`${path}: record ${index + 1} must be an object.`)
|
|
41
|
+
}
|
|
42
|
+
return records as TemplateVariables[]
|
|
43
|
+
}
|
package/index.ts
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { definePlugin } from "@pathmx/core"
|
|
2
|
+
import * as z from "zod/mini"
|
|
3
|
+
import { Recipe } from "./model.ts"
|
|
4
|
+
|
|
5
|
+
export default definePlugin({
|
|
6
|
+
id: "generate",
|
|
7
|
+
schema: { props: { generate: z.optional(Recipe) } },
|
|
8
|
+
commands(group, context) {
|
|
9
|
+
group
|
|
10
|
+
.description("Generate Markdown Sources from a Knap template and data")
|
|
11
|
+
.argument(
|
|
12
|
+
"[recipe]",
|
|
13
|
+
"recipe Source file (any type with a generate declaration)",
|
|
14
|
+
)
|
|
15
|
+
.option("--template <file>", "Knap template file")
|
|
16
|
+
.option("--data <file>", "JSON or CSV input; - reads stdin")
|
|
17
|
+
.option("--output <pattern>", "output path template, ending in .md")
|
|
18
|
+
.option(
|
|
19
|
+
"--data-format <format>",
|
|
20
|
+
"json or csv (inferred from the data filename)",
|
|
21
|
+
)
|
|
22
|
+
.option(
|
|
23
|
+
"--dry-run",
|
|
24
|
+
"validate and preview all file changes without writing",
|
|
25
|
+
)
|
|
26
|
+
.option("--overwrite", "allow replacement of existing Sources")
|
|
27
|
+
.option("--json", "print the generation report as JSON")
|
|
28
|
+
.action(async (recipe, flags) => {
|
|
29
|
+
const { generate } = await import("./command.ts")
|
|
30
|
+
await generate(context, recipe, flags)
|
|
31
|
+
})
|
|
32
|
+
},
|
|
33
|
+
})
|
package/model.ts
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import * as z from "zod/mini"
|
|
2
|
+
|
|
3
|
+
const text = () => z.string().check(z.minLength(1))
|
|
4
|
+
|
|
5
|
+
export const Recipe = z.strictObject({
|
|
6
|
+
template: text(),
|
|
7
|
+
data: text(),
|
|
8
|
+
output: text(),
|
|
9
|
+
dataFormat: z.optional(z.enum(["json", "csv"])),
|
|
10
|
+
})
|
|
11
|
+
|
|
12
|
+
export type RecipeData = z.infer<typeof Recipe>
|
package/package.json
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@pathmx/generate",
|
|
3
|
+
"description": "Generate PathMX Sources from Knap templates and JSON or CSV data.",
|
|
4
|
+
"version": "0.6.5",
|
|
5
|
+
"license": "SEE LICENSE IN LICENSE.md",
|
|
6
|
+
"repository": {
|
|
7
|
+
"type": "git",
|
|
8
|
+
"url": "git+https://github.com/pathmx/pathmx-beta.git",
|
|
9
|
+
"directory": "pathmx/generate"
|
|
10
|
+
},
|
|
11
|
+
"homepage": "https://github.com/pathmx/pathmx-beta#readme",
|
|
12
|
+
"bugs": "https://github.com/pathmx/pathmx-beta/issues",
|
|
13
|
+
"publishConfig": {
|
|
14
|
+
"access": "public",
|
|
15
|
+
"registry": "https://registry.npmjs.org/",
|
|
16
|
+
"tag": "beta"
|
|
17
|
+
},
|
|
18
|
+
"type": "module",
|
|
19
|
+
"exports": "./index.ts",
|
|
20
|
+
"pathmx": {
|
|
21
|
+
"plugin": "."
|
|
22
|
+
},
|
|
23
|
+
"engines": {
|
|
24
|
+
"bun": ">=1.4.0"
|
|
25
|
+
},
|
|
26
|
+
"peerDependencies": {
|
|
27
|
+
"@pathmx/core": "^0.6.5",
|
|
28
|
+
"zod": "^4.4.3"
|
|
29
|
+
},
|
|
30
|
+
"dependencies": {
|
|
31
|
+
"csv-parse": "7.0.2",
|
|
32
|
+
"diff": "9.0.0",
|
|
33
|
+
"knap": "0.4.1"
|
|
34
|
+
}
|
|
35
|
+
}
|
package/paths.ts
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import { lstat, readFile } from "node:fs/promises"
|
|
2
|
+
import { isAbsolute, join, relative, resolve, sep } from "node:path"
|
|
3
|
+
|
|
4
|
+
export function sourcePath(root: string, destination: string) {
|
|
5
|
+
const path = relative(root, resolve(destination))
|
|
6
|
+
if (!path || path === ".." || path.startsWith(`..${sep}`) || isAbsolute(path))
|
|
7
|
+
throw new Error(
|
|
8
|
+
`Output must stay inside the Paths directory: ${destination}`,
|
|
9
|
+
)
|
|
10
|
+
const parts = path.split(sep)
|
|
11
|
+
if (
|
|
12
|
+
!path.endsWith(".md") ||
|
|
13
|
+
parts.some(
|
|
14
|
+
(part) =>
|
|
15
|
+
!part ||
|
|
16
|
+
part.startsWith(".") ||
|
|
17
|
+
/[\\\x00-\x1f?#%]/.test(part) ||
|
|
18
|
+
part.trim() !== part,
|
|
19
|
+
)
|
|
20
|
+
)
|
|
21
|
+
throw new Error(
|
|
22
|
+
`Output must be a visible Markdown Source path: ${destination}`,
|
|
23
|
+
)
|
|
24
|
+
return `/${parts.join("/")}`
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** Reject links and non-files before reading or staging a destination. */
|
|
28
|
+
export async function destinationContent(root: string, path: string) {
|
|
29
|
+
const parts = path.slice(1).split("/")
|
|
30
|
+
let current = root
|
|
31
|
+
for (const [index, part] of parts.entries()) {
|
|
32
|
+
current = join(current, part)
|
|
33
|
+
const stat = await lstat(current).catch((error: NodeJS.ErrnoException) => {
|
|
34
|
+
if (error.code === "ENOENT") return undefined
|
|
35
|
+
throw error
|
|
36
|
+
})
|
|
37
|
+
if (!stat) return undefined
|
|
38
|
+
if (stat.isSymbolicLink())
|
|
39
|
+
throw new Error(`Output cannot follow a symbolic link: ${current}`)
|
|
40
|
+
const leaf = index === parts.length - 1
|
|
41
|
+
if (leaf ? !stat.isFile() : !stat.isDirectory())
|
|
42
|
+
throw new Error(
|
|
43
|
+
`Output is blocked by a ${leaf ? "non-file" : "non-directory"}: ${current}`,
|
|
44
|
+
)
|
|
45
|
+
}
|
|
46
|
+
return readFile(current, "utf8")
|
|
47
|
+
}
|
package/plan.ts
ADDED
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
import { readFile, realpath } from "node:fs/promises"
|
|
2
|
+
import { dirname, resolve } from "node:path"
|
|
3
|
+
import type { PluginCommandContext } from "@pathmx/core"
|
|
4
|
+
import { createEngine, standardFilters } from "knap"
|
|
5
|
+
import { Recipe, type RecipeData } from "./model.ts"
|
|
6
|
+
import { readData } from "./data.ts"
|
|
7
|
+
import { destinationContent, sourcePath } from "./paths.ts"
|
|
8
|
+
|
|
9
|
+
export type Flags = Partial<RecipeData> & {
|
|
10
|
+
dryRun?: boolean
|
|
11
|
+
overwrite?: boolean
|
|
12
|
+
json?: boolean
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export async function planGeneration(
|
|
16
|
+
ctx: PluginCommandContext,
|
|
17
|
+
recipe: string | undefined,
|
|
18
|
+
flags: Flags,
|
|
19
|
+
) {
|
|
20
|
+
const inspection = await ctx.inspect()
|
|
21
|
+
const sources = new Map(
|
|
22
|
+
inspection.sources.all().map((source) => [source.path, source]),
|
|
23
|
+
)
|
|
24
|
+
const cwd = process.cwd()
|
|
25
|
+
let saved: Partial<RecipeData> = {}
|
|
26
|
+
let base = cwd
|
|
27
|
+
const protectedFiles = new Set<string>()
|
|
28
|
+
if (recipe) {
|
|
29
|
+
const file = await realpath(resolve(cwd, recipe))
|
|
30
|
+
const path = sourcePath(ctx.pathsRoot, file)
|
|
31
|
+
const source = sources.get(path)
|
|
32
|
+
if (!source) throw new Error(`Recipe Source not found: ${recipe}`)
|
|
33
|
+
const parsed = Recipe.safeParse(source.data.generate)
|
|
34
|
+
if (!parsed.success)
|
|
35
|
+
throw new Error(
|
|
36
|
+
`${recipe}: invalid generate declaration: ${parsed.error.message}`,
|
|
37
|
+
)
|
|
38
|
+
saved = parsed.data
|
|
39
|
+
base = dirname(file)
|
|
40
|
+
protectedFiles.add(file)
|
|
41
|
+
}
|
|
42
|
+
const merged = Recipe.safeParse({
|
|
43
|
+
template: flags.template ?? saved.template,
|
|
44
|
+
data: flags.data ?? saved.data,
|
|
45
|
+
output: flags.output ?? saved.output,
|
|
46
|
+
dataFormat: flags.dataFormat ?? saved.dataFormat,
|
|
47
|
+
})
|
|
48
|
+
if (!merged.success)
|
|
49
|
+
throw new Error(
|
|
50
|
+
`Supply --template, --data, and --output, or a valid recipe Source.\n${merged.error.message}`,
|
|
51
|
+
)
|
|
52
|
+
const request = merged.data
|
|
53
|
+
const templatePath = await realpath(
|
|
54
|
+
resolve(flags.template === undefined ? base : cwd, request.template),
|
|
55
|
+
)
|
|
56
|
+
const dataPath =
|
|
57
|
+
request.data === "-"
|
|
58
|
+
? "-"
|
|
59
|
+
: await realpath(
|
|
60
|
+
resolve(flags.data === undefined ? base : cwd, request.data),
|
|
61
|
+
)
|
|
62
|
+
protectedFiles.add(templatePath)
|
|
63
|
+
if (dataPath !== "-") protectedFiles.add(dataPath)
|
|
64
|
+
const outputBase = flags.output === undefined ? base : cwd
|
|
65
|
+
const template = await readFile(templatePath, "utf8")
|
|
66
|
+
const records = await readData(dataPath, request.dataFormat)
|
|
67
|
+
const engine = createEngine({ filters: standardFilters })
|
|
68
|
+
const warnings: string[] = []
|
|
69
|
+
async function render(
|
|
70
|
+
text: string,
|
|
71
|
+
variables: (typeof records)[number],
|
|
72
|
+
label: string,
|
|
73
|
+
row: number,
|
|
74
|
+
) {
|
|
75
|
+
const result = await engine.render(text, { variables })
|
|
76
|
+
const describe = (issue: {
|
|
77
|
+
line: number
|
|
78
|
+
column: number
|
|
79
|
+
message: string
|
|
80
|
+
}) =>
|
|
81
|
+
`${label}:${issue.line}:${issue.column} (record ${row}): ${issue.message}`
|
|
82
|
+
if (result.errors.length)
|
|
83
|
+
throw new Error(result.errors.map(describe).join("\n"))
|
|
84
|
+
warnings.push(...result.warnings.map(describe))
|
|
85
|
+
return result.output
|
|
86
|
+
}
|
|
87
|
+
const outputs = []
|
|
88
|
+
const destinations = new Set<string>()
|
|
89
|
+
for (const [index, variables] of records.entries()) {
|
|
90
|
+
const rendered = await render(
|
|
91
|
+
request.output,
|
|
92
|
+
variables,
|
|
93
|
+
"output",
|
|
94
|
+
index + 1,
|
|
95
|
+
)
|
|
96
|
+
const destination = resolve(outputBase, rendered)
|
|
97
|
+
const path = sourcePath(ctx.pathsRoot, destination)
|
|
98
|
+
const key = path.normalize("NFC").toLowerCase()
|
|
99
|
+
if (destinations.has(key))
|
|
100
|
+
throw new Error(`Duplicate output: ${path} (record ${index + 1})`)
|
|
101
|
+
destinations.add(key)
|
|
102
|
+
if (protectedFiles.has(destination))
|
|
103
|
+
throw new Error(`Output would replace an input: ${destination}`)
|
|
104
|
+
const content = await render(template, variables, templatePath, index + 1)
|
|
105
|
+
const before = await destinationContent(ctx.pathsRoot, path)
|
|
106
|
+
const existing = sources.get(path)
|
|
107
|
+
if (before !== undefined && (!existing || existing.content !== before))
|
|
108
|
+
throw new Error(`Destination is not an indexed, current Source: ${path}`)
|
|
109
|
+
if (before !== undefined && before !== content && !flags.overwrite)
|
|
110
|
+
throw new Error(
|
|
111
|
+
`Source already exists: ${path}. Use --overwrite to replace it; add --dry-run to preview.`,
|
|
112
|
+
)
|
|
113
|
+
outputs.push({
|
|
114
|
+
path,
|
|
115
|
+
content,
|
|
116
|
+
before,
|
|
117
|
+
status:
|
|
118
|
+
before === content
|
|
119
|
+
? ("unchanged" as const)
|
|
120
|
+
: before === undefined
|
|
121
|
+
? ("create" as const)
|
|
122
|
+
: ("replace" as const),
|
|
123
|
+
})
|
|
124
|
+
}
|
|
125
|
+
return { outputs, warnings }
|
|
126
|
+
}
|
package/report.ts
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import { createTwoFilesPatch } from "diff"
|
|
2
|
+
import type { planGeneration } from "./plan.ts"
|
|
3
|
+
|
|
4
|
+
export function generationReport(
|
|
5
|
+
plan: Awaited<ReturnType<typeof planGeneration>>,
|
|
6
|
+
dryRun: boolean,
|
|
7
|
+
) {
|
|
8
|
+
return {
|
|
9
|
+
dryRun,
|
|
10
|
+
warnings: plan.warnings,
|
|
11
|
+
files: plan.outputs.map(({ path, content, before, status }) => ({
|
|
12
|
+
path,
|
|
13
|
+
status,
|
|
14
|
+
...(dryRun && status !== "unchanged"
|
|
15
|
+
? {
|
|
16
|
+
diff: createTwoFilesPatch(
|
|
17
|
+
before === undefined ? "/dev/null" : path,
|
|
18
|
+
path,
|
|
19
|
+
before ?? "",
|
|
20
|
+
content,
|
|
21
|
+
),
|
|
22
|
+
}
|
|
23
|
+
: {}),
|
|
24
|
+
})),
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export function printReport(
|
|
29
|
+
report: ReturnType<typeof generationReport>,
|
|
30
|
+
json: boolean,
|
|
31
|
+
) {
|
|
32
|
+
if (json) {
|
|
33
|
+
console.log(JSON.stringify(report, null, 2))
|
|
34
|
+
return
|
|
35
|
+
}
|
|
36
|
+
for (const warning of report.warnings) console.error(`Warning: ${warning}`)
|
|
37
|
+
for (const file of report.files) {
|
|
38
|
+
console.log(`${file.status} ${file.path}`)
|
|
39
|
+
if (file.diff) console.log(file.diff)
|
|
40
|
+
}
|
|
41
|
+
const changed = report.files.filter(
|
|
42
|
+
(file) => file.status !== "unchanged",
|
|
43
|
+
).length
|
|
44
|
+
console.log(
|
|
45
|
+
report.dryRun
|
|
46
|
+
? `Preview: ${changed} change(s). No files written.`
|
|
47
|
+
: `Generated ${changed} Source(s); ${report.files.length - changed} unchanged.`,
|
|
48
|
+
)
|
|
49
|
+
}
|