@panomc/plugin-kit 0.0.0-stage → 1.0.0-dev.61

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (89) hide show
  1. package/assets/pano-bootstrap.css +17903 -0
  2. package/bin/__tests__/new/e2e.test.js +111 -0
  3. package/bin/__tests__/new/helpers.js +76 -0
  4. package/bin/__tests__/new/new.test.js +472 -0
  5. package/bin/new.js +530 -0
  6. package/bin/pano-plugin.js +162 -0
  7. package/bin/templates/plugin/README.md +30 -0
  8. package/bin/templates/plugin/_gitignore +15 -0
  9. package/bin/templates/plugin/build.gradle.kts +389 -0
  10. package/bin/templates/plugin/gradle/wrapper/gradle-wrapper.jar +0 -0
  11. package/bin/templates/plugin/gradle/wrapper/gradle-wrapper.properties +7 -0
  12. package/bin/templates/plugin/gradle.properties +55 -0
  13. package/bin/templates/plugin/gradlew +249 -0
  14. package/bin/templates/plugin/gradlew.bat +92 -0
  15. package/bin/templates/plugin/package.json.tpl +14 -0
  16. package/bin/templates/plugin/rollup.config.js +2 -0
  17. package/bin/templates/plugin/settings.gradle.kts +5 -0
  18. package/bin/templates/plugin/src/main/kotlin/__PKGPATH__/__CLASS__Plugin.kt +50 -0
  19. package/bin/templates/plugin/src/main/kotlin/__PKGPATH__/frontend/ExampleFallbackPage.kt +28 -0
  20. package/bin/templates/plugin/src/main/kotlin/__PKGPATH__/routes/GetHelloAPI.kt +19 -0
  21. package/bin/templates/plugin/src/main/kotlin/com/panomc/plugins/license/LicenseGuard.kt +30 -0
  22. package/bin/templates/plugin/src/main/kotlin/com/panomc/plugins/license/PluginLicenseClient.kt +144 -0
  23. package/bin/templates/plugin/src/main/resources/config.conf +1 -0
  24. package/bin/templates/plugin/src/main/resources/frontend-targets.json +1 -0
  25. package/bin/templates/plugin/src/main/resources/locales/en-US.json +3 -0
  26. package/bin/templates/plugin/src/main/resources/logo.png +0 -0
  27. package/bin/templates/plugin/src/theme/views/HelloPage.svelte +26 -0
  28. package/bin/ui.js +96 -0
  29. package/package.json +46 -4
  30. package/src/config.js +191 -0
  31. package/src/controller/__tests__/controller.test.js +647 -0
  32. package/src/controller/index.js +604 -0
  33. package/src/dev.js +208 -0
  34. package/src/index.js +22 -0
  35. package/src/rollup/__tests__/controllers/controllers.test.js +418 -0
  36. package/src/rollup/__tests__/controllers/fixture.js +143 -0
  37. package/src/rollup/__tests__/controllers/golden/controllers.json +34 -0
  38. package/src/rollup/__tests__/controllers/golden/controllers.types.js +69 -0
  39. package/src/rollup/__tests__/controllers/golden/pano-plugin.json +16 -0
  40. package/src/rollup/__tests__/controllers/golden/pano-plugin.lock.json +27 -0
  41. package/src/rollup/__tests__/controllers/golden/pano-plugin.with-views.json +54 -0
  42. package/src/rollup/__tests__/preset/preset.test.js +418 -0
  43. package/src/rollup/__tests__/rules/_build.js +39 -0
  44. package/src/rollup/__tests__/rules/_fixture.js +83 -0
  45. package/src/rollup/__tests__/rules/helpers.test.js +148 -0
  46. package/src/rollup/__tests__/rules/rules.test.js +259 -0
  47. package/src/rollup/__tests__/rules/stamp.test.js +113 -0
  48. package/src/rollup/__tests__/samples/samples.test.js +481 -0
  49. package/src/rollup/__tests__/seams/config.test.js +78 -0
  50. package/src/rollup/__tests__/seams/lock.test.js +124 -0
  51. package/src/rollup/__tests__/seams/sdk-seams.test.js +93 -0
  52. package/src/rollup/__tests__/seams/stubs.test.js +52 -0
  53. package/src/rollup/__tests__/views/helpers.js +82 -0
  54. package/src/rollup/__tests__/views/views.test.js +522 -0
  55. package/src/rollup/__tests__/widgets/helpers.js +117 -0
  56. package/src/rollup/__tests__/widgets/widgets.test.js +422 -0
  57. package/src/rollup/cli-build.js +90 -0
  58. package/src/rollup/cli-check.js +280 -0
  59. package/src/rollup/cli-classes.js +75 -0
  60. package/src/rollup/client-gen.js +72 -0
  61. package/src/rollup/controllers.js +434 -0
  62. package/src/rollup/entry.js +250 -0
  63. package/src/rollup/helpers.js +193 -0
  64. package/src/rollup/index.js +601 -0
  65. package/src/rollup/integrate.js +205 -0
  66. package/src/rollup/lock.js +230 -0
  67. package/src/rollup/meta.js +479 -0
  68. package/src/rollup/rules.js +950 -0
  69. package/src/rollup/samples.js +667 -0
  70. package/src/rollup/stamp.js +410 -0
  71. package/src/rollup/types.js +248 -0
  72. package/src/rollup/views.js +1205 -0
  73. package/src/rollup/widgets.js +1000 -0
  74. package/src/styles/__tests__/fallback/__snapshots__/build-fallback-css.test.js.snap +173 -0
  75. package/src/styles/__tests__/fallback/build-fallback-css.test.js +526 -0
  76. package/src/styles/__tests__/fallback/fixtures/base.css +247 -0
  77. package/src/styles/__tests__/fallback/plugins.test.js +301 -0
  78. package/src/styles/__tests__/lint/check-styles.test.js +423 -0
  79. package/src/styles/__tests__/lint/fixtures/ProductCard.golden.svelte +13 -0
  80. package/src/styles/__tests__/lint/fixtures/ProductCard.in.svelte +13 -0
  81. package/src/styles/__tests__/lint/semantic-classes.test.js +364 -0
  82. package/src/styles/bootstrap-classes.js +155 -0
  83. package/src/styles/check-styles.js +626 -0
  84. package/src/styles/fallback-css.js +1182 -0
  85. package/src/styles/plugin-css.js +237 -0
  86. package/src/styles/scan.js +206 -0
  87. package/src/styles/semantic-classes.js +436 -0
  88. package/src/styles/tokens.map.js +53 -0
  89. package/README.md +0 -3
package/bin/new.js ADDED
@@ -0,0 +1,530 @@
1
+ /**
2
+ * pano-plugin new — scaffold a working Pano plugin (doc 02 section 8, decision 42).
3
+ *
4
+ * bunx @panomc/plugin-kit new interactive: id, name, author, Kotlin package, install now
5
+ * bunx @panomc/plugin-kit new my-plugin no questions, installs
6
+ * pano-plugin new my-plugin --package com.me.shop Kotlin package (default com.example.<id without dashes>)
7
+ * pano-plugin new my-plugin --local <theme-core dir> file: links to a local theme-core checkout
8
+ * pano-plugin new my-plugin --name "My Plugin" --author "Me" --no-install
9
+ *
10
+ * Run it inside Pano's `plugins/` folder: the folder is always the plugin id, because Pano finds a
11
+ * plugin's dev sources at `plugins/<pluginId>`. An existing folder is refused.
12
+ *
13
+ * Everything the scaffold contains lives under `bin/templates/plugin/` and nowhere else: add a file
14
+ * there, with `@@KEY@@` where a value goes, and every new plugin gets it. Special names:
15
+ * `__PKGPATH__` the Kotlin package as a folder path `_gitignore` becomes `.gitignore`
16
+ * `__CLASS__` the plugin class name without `Plugin` `*.tpl` loses its suffix
17
+ * `.jar` and `.png` files are copied as they are.
18
+ */
19
+ import fs from "node:fs";
20
+ import path from "node:path";
21
+ import readline from "node:readline/promises";
22
+ import { spawnSync } from "node:child_process";
23
+ import { fileURLToPath } from "node:url";
24
+ import { namespaceOf } from "../src/config.js";
25
+
26
+ const binDir = path.dirname(fileURLToPath(import.meta.url));
27
+ const kitDir = path.join(binDir, "..");
28
+ export const TEMPLATE_DIR = path.join(binDir, "templates", "plugin");
29
+
30
+ const ID_PATTERN = /^[a-z][a-z0-9]*(-[a-z0-9]+)*$/;
31
+ const PACKAGE_PATTERN = /^[a-z][a-z0-9_]*(\.[a-z][a-z0-9_]*)*$/;
32
+ /** Characters that would break a JSON string, a Svelte text, a properties value or a Kotlin string. */
33
+ const FORBIDDEN_TEXT = /[\u0000-\u001f"\\<>{}$`]|@@/;
34
+ const COPY_AS_IS = new Set([".jar", ".png"]);
35
+ const DEFAULT_AUTHOR = "CHANGE-ME";
36
+
37
+ const JAVA_KEYWORDS = new Set(
38
+ (
39
+ "abstract assert boolean break byte case catch char class const continue default do double else enum extends " +
40
+ "final finally float for goto if implements import instanceof int interface long native new package private " +
41
+ "protected public return short static strictfp super switch synchronized this throw throws transient try void " +
42
+ "volatile while true false null fun val var when object is in as typealias"
43
+ ).split(" "),
44
+ );
45
+
46
+ export const NEW_HELP = `pano-plugin new - scaffold a Pano plugin
47
+
48
+ Usage: pano-plugin new [<id>] [options]
49
+
50
+ <id> plugin id and folder name (kebab-case); asked for when left out
51
+ --package <x.y> Kotlin package (default com.example.<id without dashes>)
52
+ --name <text> display name (default: the id as a title)
53
+ --author <text> developer name (default ${DEFAULT_AUTHOR})
54
+ --local [<dir>] link @panomc/plugin-kit and @panomc/sdk from a local theme-core checkout
55
+ (the default while the kit is unpublished)
56
+ --no-install do not run bun install
57
+
58
+ Run it inside Pano's plugins/ folder. Without an id it asks five questions.
59
+ `;
60
+
61
+ /**
62
+ * @typedef {object} NewOptions
63
+ * @property {string} id
64
+ * @property {string} name
65
+ * @property {string} author
66
+ * @property {string} pkg Kotlin package
67
+ * @property {string | null} local absolute theme-core folder for file: links, or null for published versions
68
+ * @property {boolean} install
69
+ */
70
+
71
+ /**
72
+ * @typedef {object} Prompts
73
+ * @property {(question: { message: string, initial?: string, validate?: (value: string) => string | null }) => Promise<string>} text
74
+ * @property {(question: { message: string, initial?: boolean }) => Promise<boolean>} confirm
75
+ */
76
+
77
+ /**
78
+ * @typedef {object} RunNewOptions
79
+ * @property {string} [cwd] where the plugin folder is created, default the current directory
80
+ * @property {boolean} [interactive] ask the questions when no id is given, default a TTY outside CI
81
+ * @property {Prompts} [prompts] question source (tests), default clack or readline
82
+ * @property {(dir: string) => number} [install] runs the dependency install, returns its exit code
83
+ * @property {(line: string) => void} [out]
84
+ * @property {(line: string) => void} [err]
85
+ */
86
+
87
+ /** `my-plugin` -> `My Plugin`. */
88
+ export function titleFrom(id) {
89
+ return id
90
+ .split("-")
91
+ .filter(Boolean)
92
+ .map((word) => word[0].toUpperCase() + word.slice(1))
93
+ .join(" ");
94
+ }
95
+
96
+ /**
97
+ * The plugin class name without its `Plugin` suffix: `my-plugin` -> `My`, `pano-plugin-market` -> `Market`,
98
+ * `shop` -> `Shop`. The scaffold adds the suffix back (`MyPlugin`, `MarketPlugin`, `ShopPlugin`), so a
99
+ * plugin called "...-plugin" does not end up as `MyPluginPlugin`.
100
+ *
101
+ * @param {string} id
102
+ * @returns {string}
103
+ */
104
+ export function classNameOf(id) {
105
+ const words = id
106
+ .replace(/^pano-plugin-/, "")
107
+ .split("-")
108
+ .filter(Boolean);
109
+
110
+ if (words.length > 1 && words[words.length - 1] === "plugin") words.pop();
111
+
112
+ const name = words.map((word) => word[0].toUpperCase() + word.slice(1)).join("");
113
+
114
+ // a Kotlin class name cannot start with a digit; ids start with a letter, but `pano-plugin-3d` would not
115
+ return /^[0-9]/.test(name) ? `P${name}` : name;
116
+ }
117
+
118
+ /** `my-plugin` -> `com.example.myplugin`. */
119
+ export function defaultPackage(id) {
120
+ return `com.example.${id.replace(/-/g, "")}`;
121
+ }
122
+
123
+ /**
124
+ * @param {string} id
125
+ * @param {string} cwd
126
+ * @returns {string | null} the problem, or null
127
+ */
128
+ export function checkId(id, cwd) {
129
+ if (!ID_PATTERN.test(id) || id.length > 64) {
130
+ return "the id must be kebab-case: lowercase letters, digits and single dashes, starting with a letter (my-plugin)";
131
+ }
132
+
133
+ try {
134
+ namespaceOf(id);
135
+ } catch (error) {
136
+ return /** @type {Error} */ (error).message.replace(/^\[pano-plugin\] /, "");
137
+ }
138
+
139
+ if (fs.existsSync(path.resolve(cwd, id))) {
140
+ return `${path.resolve(cwd, id)} already exists - refusing to overwrite; pick another id or remove the folder`;
141
+ }
142
+
143
+ return null;
144
+ }
145
+
146
+ /** @param {string} value @returns {string | null} */
147
+ export function checkPackage(value) {
148
+ if (!PACKAGE_PATTERN.test(value)) {
149
+ return `"${value}" is not a Kotlin package: lowercase letters, digits and "_" in dot-separated parts (com.example.shop)`;
150
+ }
151
+
152
+ const keyword = value.split(".").find((part) => JAVA_KEYWORDS.has(part));
153
+
154
+ return keyword ? `"${keyword}" in the package is a reserved word: choose another part name` : null;
155
+ }
156
+
157
+ /**
158
+ * @param {string} value
159
+ * @param {string} label
160
+ * @returns {string | null}
161
+ */
162
+ export function checkText(value, label) {
163
+ if (!value || value.length > 80) return `${label} must be 1 to 80 characters`;
164
+
165
+ return FORBIDDEN_TEXT.test(value)
166
+ ? `${label} may not contain quotes, backslashes, < > { } $, backticks or control characters`
167
+ : null;
168
+ }
169
+
170
+ /**
171
+ * @param {string} dir
172
+ * @returns {string | null} the problem, or null
173
+ */
174
+ function checkLocalDir(dir) {
175
+ for (const sub of ["packages/plugin-kit/package.json", "packages/sdk/package.json"]) {
176
+ if (!fs.existsSync(path.join(dir, sub))) {
177
+ return `--local ${dir} is not a theme-core checkout (${sub} is missing)`;
178
+ }
179
+ }
180
+
181
+ return null;
182
+ }
183
+
184
+ /**
185
+ * @param {string[]} args
186
+ * @returns {{ id: string | null, flags: Record<string, string | boolean> }}
187
+ */
188
+ export function parseNewArgs(args) {
189
+ /** @type {Record<string, string | boolean>} */
190
+ const flags = {};
191
+ /** @type {string[]} */
192
+ const rest = [];
193
+
194
+ for (let i = 0; i < args.length; i++) {
195
+ const arg = args[i];
196
+
197
+ if (!arg.startsWith("--")) {
198
+ rest.push(arg);
199
+ continue;
200
+ }
201
+
202
+ const [name, inline] = arg.slice(2).split(/=(.*)/s);
203
+
204
+ if (name === "no-install") flags.install = false;
205
+ else if (name === "install") flags.install = true;
206
+ else if (name === "help") flags.help = true;
207
+ else if (name === "local") {
208
+ // the directory is optional: `--local` alone means the checkout this kit sits in
209
+ const next = args[i + 1];
210
+
211
+ if (inline !== undefined) flags.local = inline;
212
+ else if (next !== undefined && !next.startsWith("--")) flags.local = args[++i];
213
+ else flags.local = true;
214
+ } else if (name === "package" || name === "name" || name === "author") {
215
+ const value = inline ?? args[++i];
216
+
217
+ if (value === undefined) throw new Error(`--${name} needs a value`);
218
+
219
+ flags[name] = value;
220
+ } else throw new Error(`unknown option ${arg} (see pano-plugin new --help)`);
221
+ }
222
+
223
+ if (rest.length > 1) throw new Error(`one plugin id at most, got: ${rest.join(" ")}`);
224
+
225
+ return { id: rest[0] ?? null, flags };
226
+ }
227
+
228
+ /**
229
+ * The checkout a plain `--local` points at: the theme-core this kit lives in.
230
+ *
231
+ * @returns {string}
232
+ */
233
+ function ownCheckout() {
234
+ return path.resolve(kitDir, "..", "..");
235
+ }
236
+
237
+ /**
238
+ * Template values for a plugin.
239
+ *
240
+ * @param {NewOptions} options
241
+ * @param {string} kitVersion
242
+ * @returns {Record<string, string>}
243
+ */
244
+ export function templateValues(options, kitVersion) {
245
+ const { id, name, author, pkg, local } = options;
246
+ const org = author === DEFAULT_AUTHOR ? DEFAULT_AUTHOR : author.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "") || DEFAULT_AUTHOR;
247
+
248
+ return {
249
+ ID: id,
250
+ NS: namespaceOf(id),
251
+ NAME: name,
252
+ AUTHOR: author,
253
+ ORG: org,
254
+ PACKAGE: pkg,
255
+ PKGPATH: pkg.split(".").join("/"),
256
+ CLASS: classNameOf(id),
257
+ KIT_DEP: local ? `file:${path.join(local, "packages", "plugin-kit")}` : `^${kitVersion}`,
258
+ SDK_DEP: local ? `file:${path.join(local, "packages", "sdk")}` : `^${kitVersion}`,
259
+ };
260
+ }
261
+
262
+ /** @param {string} dir @returns {string[]} files below `dir`, relative, sorted */
263
+ function listFiles(dir) {
264
+ /** @type {string[]} */
265
+ const found = [];
266
+
267
+ /** @param {string} current */
268
+ const visit = (current) => {
269
+ for (const entry of fs.readdirSync(current, { withFileTypes: true })) {
270
+ const full = path.join(current, entry.name);
271
+
272
+ if (entry.isDirectory()) visit(full);
273
+ else found.push(path.relative(dir, full).split(path.sep).join("/"));
274
+ }
275
+ };
276
+
277
+ visit(dir);
278
+
279
+ return found.sort();
280
+ }
281
+
282
+ /** @param {string} value @returns {string} non-ASCII as \uXXXX, the way a .properties file wants it */
283
+ function propertiesEscape(value) {
284
+ return value.replace(/[^\u0000-\u007f]/g, (char) => `\\u${char.charCodeAt(0).toString(16).padStart(4, "0")}`);
285
+ }
286
+
287
+ /**
288
+ * Where a template file lands, relative to the new plugin folder.
289
+ *
290
+ * @param {string} relative
291
+ * @param {Record<string, string>} values
292
+ * @returns {string}
293
+ */
294
+ export function targetPath(relative, values) {
295
+ let target = relative.replaceAll("__PKGPATH__", values.PKGPATH).replaceAll("__CLASS__", values.CLASS);
296
+
297
+ if (target === "_gitignore") target = ".gitignore";
298
+ if (target.endsWith(".tpl")) target = target.slice(0, -".tpl".length);
299
+
300
+ return target;
301
+ }
302
+
303
+ /**
304
+ * Writes the scaffold into `dir` (created) and returns the files written, relative.
305
+ *
306
+ * @param {string} dir
307
+ * @param {Record<string, string>} values
308
+ * @returns {string[]}
309
+ */
310
+ export function writeScaffold(dir, values) {
311
+ const written = [];
312
+
313
+ for (const relative of listFiles(TEMPLATE_DIR)) {
314
+ const source = path.join(TEMPLATE_DIR, relative);
315
+ const target = path.join(dir, targetPath(relative, values));
316
+ const mode = fs.statSync(source).mode;
317
+
318
+ fs.mkdirSync(path.dirname(target), { recursive: true });
319
+
320
+ if (COPY_AS_IS.has(path.extname(relative))) {
321
+ fs.copyFileSync(source, target);
322
+ } else {
323
+ const escape = target.endsWith(".properties") ? propertiesEscape : (value) => value;
324
+ const content = fs
325
+ .readFileSync(source, "utf8")
326
+ .replace(/@@([A-Z_]+)@@/g, (match, key) => {
327
+ if (!(key in values)) throw new Error(`template ${relative}: unknown placeholder ${match}`);
328
+
329
+ return escape(values[key]);
330
+ });
331
+
332
+ fs.writeFileSync(target, content);
333
+ }
334
+
335
+ fs.chmodSync(target, mode & 0o777);
336
+ written.push(path.relative(dir, target).split(path.sep).join("/"));
337
+ }
338
+
339
+ return written;
340
+ }
341
+
342
+ /**
343
+ * Prompts through clack when it is installed, readline otherwise.
344
+ *
345
+ * @returns {Promise<Prompts>}
346
+ */
347
+ async function defaultPrompts() {
348
+ let clack = null;
349
+
350
+ try {
351
+ // computed specifier: the package is optional, and bun must not resolve it while loading this file
352
+ clack = await import("@clack/" + "prompts");
353
+ } catch {
354
+ // plain questions below
355
+ }
356
+
357
+ if (clack) {
358
+ const { cancelGuard } = await import("./ui.js");
359
+
360
+ return {
361
+ text: async ({ message, initial, validate }) =>
362
+ String(
363
+ cancelGuard(
364
+ await clack.text({
365
+ message,
366
+ placeholder: initial,
367
+ defaultValue: initial,
368
+ validate: (value) => validate?.((value || initial || "").trim()) ?? undefined,
369
+ }),
370
+ ) || initial || "",
371
+ ).trim(),
372
+ confirm: async ({ message, initial }) =>
373
+ Boolean(cancelGuard(await clack.confirm({ message, initialValue: initial ?? true }))),
374
+ };
375
+ }
376
+
377
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
378
+
379
+ return {
380
+ async text({ message, initial, validate }) {
381
+ for (;;) {
382
+ const answer = (await rl.question(`${message}${initial ? ` (${initial})` : ""} `)).trim() || initial || "";
383
+ const problem = validate?.(answer) ?? null;
384
+
385
+ if (!problem) return answer;
386
+
387
+ process.stdout.write(` ${problem}\n`);
388
+ }
389
+ },
390
+ async confirm({ message, initial = true }) {
391
+ const answer = (await rl.question(`${message} (${initial ? "Y/n" : "y/N"}) `)).trim().toLowerCase();
392
+
393
+ return answer ? answer.startsWith("y") : initial;
394
+ },
395
+ };
396
+ }
397
+
398
+ /**
399
+ * @param {string} dir
400
+ * @returns {number}
401
+ */
402
+ function bunInstall(dir) {
403
+ const result = spawnSync("bun", ["install", "--backend=copyfile"], { cwd: dir, stdio: "ignore" });
404
+
405
+ return result.status ?? 1;
406
+ }
407
+
408
+ /**
409
+ * `pano-plugin new`. Returns the exit code.
410
+ *
411
+ * @param {string[]} argv arguments after `new`
412
+ * @param {RunNewOptions} [options]
413
+ * @returns {Promise<number>}
414
+ */
415
+ export async function runNew(argv, options = {}) {
416
+ const cwd = path.resolve(options.cwd ?? process.cwd());
417
+ const out = options.out ?? ((line) => process.stdout.write(`${line}\n`));
418
+ const err = options.err ?? ((line) => process.stderr.write(`${line}\n`));
419
+ const kitPkg = JSON.parse(fs.readFileSync(path.join(kitDir, "package.json"), "utf8"));
420
+
421
+ try {
422
+ const { id: idArg, flags } = parseNewArgs(argv);
423
+
424
+ if (flags.help) {
425
+ out(NEW_HELP.trimEnd());
426
+
427
+ return 0;
428
+ }
429
+
430
+ const interactive = options.interactive ?? (Boolean(process.stdout.isTTY) && !process.env.CI);
431
+
432
+ // ---- inputs: everything is asked before a file is written, so cancelling leaves nothing behind
433
+ /** @type {string} */
434
+ let id;
435
+ /** @type {string} */
436
+ let name;
437
+ /** @type {string} */
438
+ let author;
439
+ /** @type {string} */
440
+ let pkg;
441
+ let install = flags.install !== false;
442
+
443
+ if (idArg === null) {
444
+ if (!interactive) {
445
+ throw new Error("a plugin id is required when there is no terminal: pano-plugin new <id> [--package x.y]");
446
+ }
447
+
448
+ const prompts = options.prompts ?? (await defaultPrompts());
449
+
450
+ id = await prompts.text({
451
+ message: "Plugin id (the folder name)?",
452
+ initial: "my-plugin",
453
+ validate: (value) => checkId(value, cwd),
454
+ });
455
+ name = await prompts.text({
456
+ message: "Display name?",
457
+ initial: /** @type {string} */ (flags.name) ?? titleFrom(id),
458
+ validate: (value) => checkText(value, "the name"),
459
+ });
460
+ author = await prompts.text({
461
+ message: "Author?",
462
+ initial: /** @type {string} */ (flags.author) ?? DEFAULT_AUTHOR,
463
+ validate: (value) => checkText(value, "the author"),
464
+ });
465
+ pkg = await prompts.text({
466
+ message: "Kotlin package?",
467
+ initial: /** @type {string} */ (flags.package) ?? defaultPackage(id),
468
+ validate: checkPackage,
469
+ });
470
+ install = flags.install === undefined ? await prompts.confirm({ message: "Install dependencies with bun now?", initial: true }) : install;
471
+ } else {
472
+ id = idArg;
473
+ name = /** @type {string | undefined} */ (flags.name) ?? titleFrom(id);
474
+ author = /** @type {string | undefined} */ (flags.author) ?? DEFAULT_AUTHOR;
475
+ pkg = /** @type {string | undefined} */ (flags.package) ?? defaultPackage(id);
476
+ }
477
+
478
+ for (const problem of [checkId(id, cwd), checkText(name, "the name"), checkText(author, "the author"), checkPackage(pkg)]) {
479
+ if (problem) throw new Error(problem);
480
+ }
481
+
482
+ // ---- where the packages come from
483
+ /** @type {string | null} */
484
+ let local = null;
485
+
486
+ if (typeof flags.local === "string") local = path.resolve(cwd, flags.local);
487
+ else if (flags.local === true || kitPkg.version === "0.0.0-development") local = ownCheckout();
488
+
489
+ if (local) {
490
+ const problem = checkLocalDir(local);
491
+
492
+ if (problem) throw new Error(problem);
493
+ }
494
+
495
+ // ---- write
496
+ const dir = path.join(cwd, id);
497
+ const values = templateValues({ id, name, author, pkg, local, install }, kitPkg.version);
498
+ const files = writeScaffold(dir, values);
499
+
500
+ out(`scaffolded ${id}/ (${files.length} files, ${local ? "local workspace links" : `kit ^${kitPkg.version}`})`);
501
+
502
+ if (path.basename(cwd) !== "plugins") {
503
+ out(`note: Pano finds a plugin's dev sources at <pano>/plugins/${id}; move the folder there before bun run dev`);
504
+ }
505
+
506
+ let installed = false;
507
+
508
+ if (install) {
509
+ out("installing dependencies (bun install)...");
510
+ installed = (options.install ?? bunInstall)(dir) === 0;
511
+
512
+ if (!installed) out("bun install did not complete: run it yourself in the plugin folder (add --backend=copyfile if it hangs)");
513
+ }
514
+
515
+ // The numbered lines are the "steps to first result" of doc 02 section 8: scaffold (this command), dev,
516
+ // restart Pano. The install is part of the scaffold, not a step of its own.
517
+ out("");
518
+ out("Next:");
519
+ out(` 1. cd ${id}${installed ? "" : " && bun install"} && bun run dev (the first run builds the jar, it takes minutes)`);
520
+ out(` 2. restart Pano once, then open /${id}`);
521
+ out("");
522
+ out("Steps to first result: 3 (scaffold, dev, restart Pano), 0 files written");
523
+
524
+ return 0;
525
+ } catch (error) {
526
+ err(`pano-plugin new: ${/** @type {Error} */ (error).message}`);
527
+
528
+ return 1;
529
+ }
530
+ }
@@ -0,0 +1,162 @@
1
+ #!/usr/bin/env node
2
+ // pano-plugin: the command line of @panomc/plugin-kit (doc 02 section 8).
3
+ // Every command is imported on demand, so `pano-plugin --help` loads neither rollup nor svelte.
4
+ import { realpathSync } from 'node:fs';
5
+ import { fileURLToPath } from 'node:url';
6
+
7
+ const HELP = `pano-plugin - build and check a Pano plugin
8
+
9
+ Usage: pano-plugin <command> [options]
10
+
11
+ Commands
12
+ dev [--pano <url>] Build the jar once when none exists, then rollup watch.
13
+ build Build the plugin UI package (src/main/resources/plugin-ui).
14
+ check [--strict] [--styles badge]
15
+ Build rules, lock, style lint, Svelte pin and API paths.
16
+ --strict fails on warnings too and needs a samples file with 'filled' (and
17
+ every standard state not in notApplicable) for every view;
18
+ --styles badge runs the badge lint.
19
+ classes [--fix] List the semantic classes the sources lack; --fix writes them.
20
+ new [<id>] [--package x.y] [--local <dir>]
21
+ Scaffold a plugin in ./<id> (run it in Pano's plugins folder).
22
+ samples [<View>] Write <View>.samples.js next to the view (the four standard states, one line
23
+ per required prop); without a name list the views and their samples.
24
+ publish-controllers Not available yet.
25
+
26
+ Run it in the plugin folder (the one with gradle.properties and rollup.config.js).
27
+ `;
28
+
29
+ const NOT_YET = new Set(['publish-controllers']);
30
+ const FLAGS = {
31
+ dev: { value: ['pano'], bool: [] },
32
+ build: { value: ['config'], bool: [] },
33
+ check: { value: ['styles'], bool: ['strict'] },
34
+ classes: { value: [], bool: ['fix'] },
35
+ samples: { value: [], bool: [] },
36
+ };
37
+
38
+ /**
39
+ * @param {string[]} args
40
+ * @param {{ value: string[], bool: string[] }} spec
41
+ * @returns {{ flags: Record<string, string | boolean>, rest: string[] }}
42
+ */
43
+ function parse(args, spec) {
44
+ /** @type {Record<string, string | boolean>} */
45
+ const flags = {};
46
+ /** @type {string[]} */
47
+ const rest = [];
48
+
49
+ for (let i = 0; i < args.length; i++) {
50
+ const arg = args[i];
51
+
52
+ if (!arg.startsWith('--')) {
53
+ rest.push(arg);
54
+ continue;
55
+ }
56
+
57
+ const [name, inline] = arg.slice(2).split(/=(.*)/s);
58
+
59
+ if (spec.bool.includes(name)) flags[name] = true;
60
+ else if (spec.value.includes(name)) {
61
+ const value = inline ?? args[++i];
62
+
63
+ if (value === undefined) throw new Error(`--${name} needs a value`);
64
+
65
+ flags[name] = value;
66
+ } else throw new Error(`unknown option ${arg} (see pano-plugin --help)`);
67
+ }
68
+
69
+ return { flags, rest };
70
+ }
71
+
72
+ /** @param {string[]} argv @returns {Promise<number>} */
73
+ export async function main(argv) {
74
+ const [command, ...args] = argv;
75
+
76
+ if (!command || command === '--help' || command === '-h' || command === 'help') {
77
+ process.stdout.write(HELP);
78
+
79
+ return command ? 0 : 1;
80
+ }
81
+
82
+ if (NOT_YET.has(command)) {
83
+ process.stderr.write(`pano-plugin ${command}: not available yet\n`);
84
+
85
+ return 1;
86
+ }
87
+
88
+ if (command === 'new') {
89
+ // own argument parser: the id comes first and --local takes an optional folder
90
+ const { runNew } = await import('./new.js');
91
+
92
+ return await runNew(args);
93
+ }
94
+
95
+ if (!(command in FLAGS)) {
96
+ process.stderr.write(`pano-plugin: unknown command "${command}"\n\n${HELP}`);
97
+
98
+ return 1;
99
+ }
100
+
101
+ try {
102
+ const { flags, rest } = parse(args, FLAGS[/** @type {keyof typeof FLAGS} */ (command)]);
103
+
104
+ switch (command) {
105
+ case 'dev': {
106
+ const { runDev } = await import('../src/dev.js');
107
+
108
+ return await runDev({ pano: /** @type {string | undefined} */ (flags.pano) });
109
+ }
110
+ case 'build': {
111
+ const { runBuild } = await import('../src/rollup/cli-build.js');
112
+
113
+ return await runBuild({ config: /** @type {string | undefined} */ (flags.config) });
114
+ }
115
+ case 'check': {
116
+ if (flags.styles !== undefined && flags.styles !== 'badge' && flags.styles !== 'core') {
117
+ throw new Error('--styles takes "badge" (or "core")');
118
+ }
119
+
120
+ const { runCheckWithSamples } = await import('../src/rollup/samples.js');
121
+
122
+ return await runCheckWithSamples({
123
+ strict: flags.strict === true,
124
+ styles: flags.styles === 'badge' ? 'badge' : 'core',
125
+ });
126
+ }
127
+ case 'classes': {
128
+ const { runClasses } = await import('../src/rollup/cli-classes.js');
129
+
130
+ return await runClasses({ fix: flags.fix === true });
131
+ }
132
+ case 'samples': {
133
+ if (rest.length > 1) throw new Error('samples takes one view name');
134
+
135
+ const { runSamples } = await import('../src/rollup/samples.js');
136
+
137
+ return await runSamples({ view: rest[0] });
138
+ }
139
+ }
140
+ } catch (error) {
141
+ process.stderr.write(`pano-plugin ${command}: ${/** @type {Error} */ (error).message}\n`);
142
+
143
+ return 1;
144
+ }
145
+
146
+ return 1;
147
+ }
148
+
149
+ /** True when this file is the program being run (also through a `node_modules/.bin` link). */
150
+ function isMain() {
151
+ if (typeof import.meta.main === 'boolean') return import.meta.main;
152
+
153
+ try {
154
+ return realpathSync(process.argv[1]) === realpathSync(fileURLToPath(import.meta.url));
155
+ } catch {
156
+ return false;
157
+ }
158
+ }
159
+
160
+ if (isMain()) {
161
+ process.exitCode = await main(process.argv.slice(2));
162
+ }