@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
@@ -0,0 +1,667 @@
1
+ import fs from "node:fs";
2
+ import os from "node:os";
3
+ import path from "node:path";
4
+ import { pathToFileURL } from "node:url";
5
+ import { rollup } from "rollup";
6
+ import { loadConfig } from "../config.js";
7
+ import { listFiles } from "./rules.js";
8
+ import { scanViews } from "./views.js";
9
+ import { getBuildContext } from "./meta.js";
10
+ import { writeIfChanged } from "./controllers.js";
11
+
12
+ /**
13
+ * Sample data of the views (doc 02 section 7).
14
+ *
15
+ * `<Name>.samples.js` sits next to `<Name>.svelte` (or anywhere in the view folders) and is pure data
16
+ * (build rule V3: it imports only view helpers and other relative `.js` fixtures):
17
+ *
18
+ * export const notApplicable = ['loading', 'error']; // optional: standard states this view has not
19
+ * export default { filled: { props: { ... }, controllers: { 'market/cart': { count: 2 } } }, empty: { ... } };
20
+ *
21
+ * `panoSamples()` compiles every samples file into ONE self-contained module,
22
+ * `<outDir>/samples/samples.mjs`:
23
+ *
24
+ * export default { ProductCard: { filled: {...}, empty: {...} }, ... } view name -> samples
25
+ * export const notApplicable = { ProductCard: ['loading', 'error'], ... } view name -> standard states left out
26
+ *
27
+ * It is a separate rollup build with its own entry, so nothing of it can reach the `client` or `server`
28
+ * bundles; only the view catalogue loads it. The build records the state names in `pano-plugin.json`
29
+ * (`views.<Name>.samples`) and sets `badges.samples` when every page and block view has `filled`.
30
+ *
31
+ * The command line side lives here as well: `samplesStub` / `runSamples` (`pano-plugin samples <View>`) and
32
+ * `runCheckWithSamples` (`pano-plugin check [--strict]`, the samples part of the check).
33
+ */
34
+
35
+ /** The four state names the catalogue knows; other keys are allowed and listed. */
36
+ export const STANDARD_STATES = Object.freeze(["empty", "filled", "error", "loading"]);
37
+
38
+ /** Suffix of a samples file. */
39
+ export const SAMPLES_SUFFIX = ".samples.js";
40
+
41
+ /** Where the compiled module is written, relative to the package folder. */
42
+ export const SAMPLES_OUTPUT = "samples/samples.mjs";
43
+
44
+ /** Default package folder, relative to the plugin root. */
45
+ const DEFAULT_OUT_DIR = "src/main/resources/plugin-ui";
46
+
47
+ const ENTRY_ID = "\0pano-samples-entry";
48
+
49
+ /**
50
+ * @typedef {object} SampleState
51
+ * @property {Record<string, any>} [props] props handed to the view
52
+ * @property {Record<string, Record<string, any>>} [controllers] controller name -> patch merged over its initial state
53
+ * @property {'guest' | 'user'} [session] session the stage simulates
54
+ * @property {string} [label] title in the catalogue
55
+ */
56
+
57
+ /**
58
+ * A state is an object or a function returning one.
59
+ *
60
+ * @typedef {SampleState | (() => SampleState)} SampleEntry
61
+ */
62
+
63
+ /**
64
+ * The default export of a `*.samples.js`: state name -> state. Standard names: `empty`, `filled`, `error`,
65
+ * `loading`.
66
+ *
67
+ * @typedef {{ [state: string]: SampleEntry | undefined, empty?: SampleEntry, filled?: SampleEntry, error?: SampleEntry, loading?: SampleEntry }} Samples
68
+ */
69
+
70
+ /**
71
+ * @typedef {object} SamplesOptions
72
+ * @property {string} [root] plugin root, default the current directory
73
+ * @property {string[]} [viewDirs] view folders (relative to `root`, or absolute), default from `pano.plugin.js`
74
+ * @property {string} [outDir] package folder, default `src/main/resources/plugin-ui`
75
+ * @property {string} [pluginId] default: `pluginId` of gradle.properties
76
+ * @property {string} [namespace] default: derived like the rest of the kit
77
+ * @property {'server' | 'client' | 'controllers' | 'widgets'} [side] the preset passes it; the package is written by `client` only
78
+ */
79
+
80
+ /** @param {string} value */
81
+ const slash = (value) => value.split(path.sep).join("/");
82
+
83
+ /**
84
+ * Every `*.samples.js` under the view folders, sorted, as `{ name, file }` (the name is the view name).
85
+ *
86
+ * @param {string[]} viewDirs absolute folders
87
+ * @returns {{ name: string, file: string }[]}
88
+ */
89
+ export function findSampleFiles(viewDirs) {
90
+ return listFiles(viewDirs, (file) => file.endsWith(SAMPLES_SUFFIX))
91
+ .map((file) => ({ name: path.basename(file, SAMPLES_SUFFIX), file }))
92
+ .sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : a.file < b.file ? -1 : 1));
93
+ }
94
+
95
+ /**
96
+ * Compiles the samples files into one self-contained ES module (not written anywhere).
97
+ *
98
+ * @param {{ name: string, file: string }[]} files
99
+ * @param {string} [root] for the file names in messages
100
+ * @returns {Promise<{ code: string, warnings: string[] }>}
101
+ * @throws {Error} a file imports a package, or has no default export
102
+ */
103
+ export async function compileSamples(files, root = process.cwd()) {
104
+ /** @param {string} file */
105
+ const display = (file) => slash(path.relative(root, file));
106
+ const lines = files.map(({ file }, index) => `import * as s${index} from ${JSON.stringify(file)};`);
107
+
108
+ lines.push("export default {");
109
+ files.forEach(({ name }, index) => lines.push(` ${JSON.stringify(name)}: s${index}.default,`));
110
+ lines.push("};", "export const notApplicable = {");
111
+ files.forEach(({ name }, index) => lines.push(` ${JSON.stringify(name)}: s${index}.notApplicable ?? [],`));
112
+ lines.push("};", "");
113
+
114
+ const entry = lines.join("\n");
115
+ /** @type {string[]} */
116
+ const warnings = [];
117
+ const bundle = await rollup({
118
+ input: ENTRY_ID,
119
+ external: [],
120
+ onwarn(warning) {
121
+ if (warning.code === "UNRESOLVED_IMPORT") {
122
+ const importer = warning.ids?.[0] ?? warning.id;
123
+
124
+ throw new Error(
125
+ `[pano-plugin] ${importer ? display(importer) : "a samples file"} imports '${warning.exporter}' — sample files are pure data: import only view helpers and other relative .js fixtures (no packages, no Svelte, no @panomc/sdk)`,
126
+ );
127
+ }
128
+
129
+ if (warning.code === "MISSING_EXPORT") {
130
+ if (warning.binding === "notApplicable") return; // optional
131
+
132
+ if (warning.binding === "default") {
133
+ throw new Error(
134
+ `[pano-plugin] ${display(warning.exporter ?? "")} has no default export — add: export default { filled: { props: { ... } } }`,
135
+ );
136
+ }
137
+ }
138
+
139
+ if (warning.code === "CIRCULAR_DEPENDENCY" || warning.code === "EMPTY_BUNDLE") return;
140
+
141
+ warnings.push(warning.message);
142
+ },
143
+ plugins: [
144
+ {
145
+ name: "pano-samples-entry",
146
+ resolveId: (source) => (source === ENTRY_ID ? ENTRY_ID : null),
147
+ load: (id) => (id === ENTRY_ID ? entry : null),
148
+ },
149
+ ],
150
+ });
151
+
152
+ try {
153
+ const { output } = await bundle.generate({ format: "es", inlineDynamicImports: true });
154
+ const chunk = output.find((item) => item.type === "chunk");
155
+
156
+ if (!chunk || chunk.type !== "chunk") {
157
+ throw new Error("[pano-plugin] samples: the build produced no module");
158
+ }
159
+
160
+ return { code: chunk.code.endsWith("\n") ? chunk.code : chunk.code + "\n", warnings };
161
+ } finally {
162
+ await bundle.close();
163
+ }
164
+ }
165
+
166
+ /**
167
+ * Imports a copy of the module under a name never used before (some runtimes ignore a query string in their
168
+ * module cache); the module is self-contained, so it runs from the temporary folder.
169
+ *
170
+ * @param {string} code
171
+ * @returns {Promise<any>}
172
+ */
173
+ export async function importSamples(code) {
174
+ const folder = fs.mkdtempSync(path.join(os.tmpdir(), "pano-kit-samples-"));
175
+ const file = path.join(folder, "samples.mjs");
176
+
177
+ try {
178
+ fs.writeFileSync(file, code);
179
+
180
+ return await import(pathToFileURL(file).href);
181
+ } finally {
182
+ fs.rmSync(folder, { recursive: true, force: true });
183
+ }
184
+ }
185
+
186
+ /**
187
+ * @typedef {object} SamplesInfo
188
+ * @property {Record<string, string[]>} states view name -> state names, in source order
189
+ * @property {Record<string, string[]>} notApplicable view name -> standard states the view leaves out
190
+ * @property {string[]} problems what is wrong with the content of the files
191
+ */
192
+
193
+ /**
194
+ * Reads the compiled module: state names and the shape check (`default` is an object of objects or functions,
195
+ * `notApplicable` an array of strings).
196
+ *
197
+ * @param {any} mod
198
+ * @param {{ name: string, file: string }[]} files
199
+ * @param {string} [root]
200
+ * @returns {SamplesInfo}
201
+ */
202
+ export function describeSamples(mod, files, root = process.cwd()) {
203
+ /** @type {SamplesInfo} */
204
+ const info = { states: {}, notApplicable: {}, problems: [] };
205
+
206
+ for (const { name, file } of files) {
207
+ const where = slash(path.relative(root, file));
208
+ const samples = mod.default?.[name];
209
+ const skipped = mod.notApplicable?.[name];
210
+
211
+ if (!samples || typeof samples !== "object" || Array.isArray(samples)) {
212
+ info.problems.push(
213
+ `${where}: the default export must be an object of states — export default { filled: { props: { ... } } }`,
214
+ );
215
+ info.states[name] = [];
216
+ } else {
217
+ info.states[name] = Object.keys(samples);
218
+
219
+ for (const [state, value] of Object.entries(samples)) {
220
+ if (value === null || (typeof value !== "object" && typeof value !== "function") || Array.isArray(value)) {
221
+ info.problems.push(
222
+ `${where}: state '${state}' must be an object { props?, controllers?, session?, label? } or a function returning one`,
223
+ );
224
+ }
225
+ }
226
+ }
227
+
228
+ if (!Array.isArray(skipped) || skipped.some((state) => typeof state !== "string")) {
229
+ info.problems.push(`${where}: notApplicable must be an array of state names, for example ['loading', 'error']`);
230
+ info.notApplicable[name] = [];
231
+ } else {
232
+ info.notApplicable[name] = skipped;
233
+ }
234
+ }
235
+
236
+ return info;
237
+ }
238
+
239
+ /**
240
+ * Finds, compiles and reads the samples of a plugin.
241
+ *
242
+ * @param {{ root: string, viewDirs: string[] }} options viewDirs absolute
243
+ * @returns {Promise<{ files: { name: string, file: string }[], code: string | null, info: SamplesInfo, warnings: string[], duplicates: string[] }>}
244
+ */
245
+ export async function buildSamples({ root, viewDirs }) {
246
+ const all = findSampleFiles(viewDirs);
247
+ /** @type {string[]} */
248
+ const duplicates = [];
249
+ /** @type {Map<string, { name: string, file: string }>} */
250
+ const byName = new Map();
251
+
252
+ for (const entry of all) {
253
+ const earlier = byName.get(entry.name);
254
+
255
+ if (earlier) {
256
+ duplicates.push(
257
+ `${slash(path.relative(root, entry.file))} and ${slash(path.relative(root, earlier.file))} both hold the samples of ${entry.name} — keep one`,
258
+ );
259
+ } else {
260
+ byName.set(entry.name, entry);
261
+ }
262
+ }
263
+
264
+ const files = [...byName.values()];
265
+
266
+ if (files.length === 0) {
267
+ return { files, code: null, info: { states: {}, notApplicable: {}, problems: [] }, warnings: [], duplicates };
268
+ }
269
+
270
+ const { code, warnings } = await compileSamples(files, root);
271
+ const info = describeSamples(await importSamples(code), files, root);
272
+
273
+ return { files, code, info, warnings, duplicates };
274
+ }
275
+
276
+ /**
277
+ * Which views must have a `filled` sample for the badge: pages and blocks.
278
+ *
279
+ * @param {Awaited<ReturnType<typeof scanViews>>} scan
280
+ * @returns {string[]} view names
281
+ */
282
+ function badgeViews(scan) {
283
+ return [...scan.views.values()]
284
+ .filter((view) => view.record.kind === "page" || view.record.block === true)
285
+ .map((view) => view.name);
286
+ }
287
+
288
+ /**
289
+ * Compiles `*.samples.js` into `samples/samples.mjs` (doc 02 section 7). List it in the client build only (the
290
+ * preset does); a `server` side does nothing. The folder is removed when the plugin has no samples left.
291
+ *
292
+ * `api.states` is the last result (view name -> state names).
293
+ *
294
+ * @param {SamplesOptions} [options]
295
+ * @returns {import('rollup').Plugin & { api: { readonly states: Record<string, string[]> } }}
296
+ */
297
+ export function panoSamples(options = {}) {
298
+ const root = path.resolve(options.root ?? process.cwd());
299
+ const outDir = path.resolve(root, options.outDir ?? DEFAULT_OUT_DIR);
300
+ const target = path.join(outDir, SAMPLES_OUTPUT);
301
+ /** @type {Record<string, string[]>} */
302
+ let states = {};
303
+
304
+ /** @returns {Promise<string[]>} absolute view folders */
305
+ async function viewDirsOf() {
306
+ const given = options.viewDirs ?? (await loadConfig(root)).viewDirs;
307
+
308
+ return given.map((dir) => path.resolve(root, dir));
309
+ }
310
+
311
+ return {
312
+ name: "pano-samples",
313
+
314
+ api: {
315
+ get states() {
316
+ return states;
317
+ },
318
+ },
319
+
320
+ async buildStart() {
321
+ if (options.side && options.side !== "client") return;
322
+
323
+ for (const { file } of findSampleFiles(await viewDirsOf())) this.addWatchFile(file);
324
+ },
325
+
326
+ async writeBundle() {
327
+ if (options.side && options.side !== "client") return;
328
+
329
+ const viewDirs = await viewDirsOf();
330
+ const built = await buildSamples({ root, viewDirs }).catch((error) => this.error(error.message));
331
+
332
+ for (const message of built.duplicates) this.error(`[pano-plugin] ${message}`);
333
+ for (const message of built.info.problems) this.error(`[pano-plugin] ${message}`);
334
+ for (const message of built.warnings) this.warn(`[pano-plugin] samples: ${message}`);
335
+
336
+ // the views of the plugin (page/block kind for the badge)
337
+ /** @type {Awaited<ReturnType<typeof scanViews>> | null} */
338
+ let scan = null;
339
+
340
+ try {
341
+ const config = options.pluginId && options.namespace ? options : await loadConfig(root);
342
+
343
+ scan = await scanViews({
344
+ dirs: viewDirs,
345
+ namespace: options.namespace ?? config.namespace,
346
+ pluginId: options.pluginId ?? /** @type {any} */ (config).pluginId,
347
+ root,
348
+ });
349
+ } catch (error) {
350
+ this.warn(`[pano-plugin] samples: the views could not be read for the badge (${/** @type {Error} */ (error).message})`);
351
+ }
352
+
353
+ const names = scan ? [...scan.views.keys()] : [];
354
+
355
+ for (const entry of built.files) {
356
+ if (scan && !scan.views.has(entry.name)) {
357
+ this.warn(
358
+ `[pano-plugin] ${slash(path.relative(root, entry.file))} belongs to no view — there is no ${entry.name}.svelte; rename the file or remove it`,
359
+ );
360
+ }
361
+ }
362
+
363
+ if (built.code) writeIfChanged(target, built.code);
364
+ else if (fs.existsSync(target)) {
365
+ fs.rmSync(path.dirname(target), { recursive: true, force: true });
366
+ }
367
+
368
+ states = built.info.states;
369
+
370
+ // hand the state names over to pano-plugin.json
371
+ const shared = getBuildContext(root);
372
+
373
+ for (const name of new Set([...names, ...Object.keys(shared.views)])) {
374
+ shared.views[name] = { ...(shared.views[name] ?? {}), samples: built.info.states[name] ?? [] };
375
+ }
376
+
377
+ for (const name of Object.keys(built.info.states)) {
378
+ shared.views[name] = { ...(shared.views[name] ?? {}), samples: built.info.states[name] };
379
+ }
380
+
381
+ if (scan) {
382
+ const required = badgeViews(scan);
383
+
384
+ shared.badges.samples =
385
+ required.length > 0
386
+ ? required.every((name) => built.info.states[name]?.includes("filled"))
387
+ : Object.keys(built.info.states).length > 0;
388
+ } else {
389
+ shared.badges.samples = false;
390
+ }
391
+ },
392
+ };
393
+ }
394
+
395
+ // ---------------------------------------------------------------------------------------------
396
+ // pano-plugin samples <View>
397
+ // ---------------------------------------------------------------------------------------------
398
+
399
+ /**
400
+ * A placeholder value for a prop of this JSDoc type.
401
+ *
402
+ * @param {string | undefined} type
403
+ * @returns {string} JavaScript source
404
+ */
405
+ function placeholder(type) {
406
+ const text = type ?? "any";
407
+
408
+ if (/\[\]|\bArray\b/i.test(text)) return "[]";
409
+ if (/\bstring\b/i.test(text)) return "''";
410
+ if (/\bnumber\b|\bint(eger)?\b/i.test(text)) return "0";
411
+ if (/\bboolean\b/i.test(text)) return "false";
412
+ if (/\bobject\b|^\s*\{/i.test(text)) return "{}";
413
+
414
+ return "null";
415
+ }
416
+
417
+ /**
418
+ * The text of a new samples file: the four standard states and one line per required prop in each.
419
+ *
420
+ * @param {string} name view name
421
+ * @param {Record<string, { type?: string, required: boolean }>} props the props contract of the view
422
+ * @returns {string}
423
+ */
424
+ export function samplesStub(name, props) {
425
+ const required = Object.entries(props).filter(([, prop]) => prop.required);
426
+ const propLines = required.length
427
+ ? required.map(([prop, { type }]) => ` ${prop}: ${placeholder(type)}, // ${type ?? "any"}, required`)
428
+ : [];
429
+ const state = (/** @type {string} */ key) => {
430
+ const body = propLines.length ? `{\n${propLines.join("\n")}\n }` : "{}";
431
+
432
+ return ` ${key}: {\n props: ${body},\n },`;
433
+ };
434
+
435
+ return [
436
+ `// Sample data of ${name} for the view catalogue (doc 02 section 7). Pure data: import only view helpers and`,
437
+ `// relative .js fixtures. Fill in the props; a state the view cannot show is left out and listed in notApplicable.`,
438
+ `/** @type {string[]} */`,
439
+ `export const notApplicable = [];`,
440
+ ``,
441
+ `/** @type {import('@panomc/plugin-kit').Samples} */`,
442
+ `export default {`,
443
+ ...["filled", "empty", "error", "loading"].map(state),
444
+ `};`,
445
+ ``,
446
+ ].join("\n");
447
+ }
448
+
449
+ /**
450
+ * @typedef {object} SamplesCommandOptions
451
+ * @property {string} [root] plugin root, default the current directory
452
+ * @property {string} [view] view name (`ProductCard` or `market:ProductCard`); none lists every view
453
+ * @property {(line: string) => void} [out]
454
+ * @property {(line: string) => void} [err]
455
+ */
456
+
457
+ /**
458
+ * `pano-plugin samples [<View>]`: writes `<View>.samples.js` next to the view; without a name lists the views
459
+ * and their samples.
460
+ *
461
+ * @param {SamplesCommandOptions} [options]
462
+ * @returns {Promise<number>} the exit code
463
+ */
464
+ export async function runSamples(options = {}) {
465
+ const root = path.resolve(options.root ?? process.cwd());
466
+ const out = options.out ?? ((line) => process.stdout.write(`${line}\n`));
467
+ const err = options.err ?? ((line) => process.stderr.write(`${line}\n`));
468
+
469
+ try {
470
+ const config = await loadConfig(root);
471
+ const dirs = config.viewDirs.map((dir) => path.resolve(root, dir));
472
+ const scan = await scanViews({ dirs, namespace: config.namespace, pluginId: config.pluginId, root });
473
+ const existing = new Map(findSampleFiles(dirs).map((entry) => [entry.name, entry.file]));
474
+
475
+ if (!options.view) {
476
+ for (const view of [...scan.views.values()].sort((a, b) => (a.name < b.name ? -1 : 1))) {
477
+ const file = existing.get(view.name);
478
+
479
+ out(file ? `${view.name} ${slash(path.relative(root, file))}` : `${view.name} no samples — pano-plugin samples ${view.name}`);
480
+ }
481
+
482
+ return 0;
483
+ }
484
+
485
+ const name = options.view.includes(":") ? options.view.slice(options.view.indexOf(":") + 1) : options.view;
486
+ const info = scan.views.get(name);
487
+
488
+ if (!info) {
489
+ const known = [...scan.views.keys()].sort();
490
+
491
+ err(`error: no view named ${name} — ${known.length ? `the views are ${known.join(", ")}` : "this plugin has no views yet"}`);
492
+
493
+ return 1;
494
+ }
495
+
496
+ const found = existing.get(name);
497
+
498
+ if (found) {
499
+ err(`error: ${slash(path.relative(root, found))} exists already — edit it, or delete it first to start over`);
500
+
501
+ return 1;
502
+ }
503
+
504
+ const file = path.join(path.dirname(info.file), `${name}${SAMPLES_SUFFIX}`);
505
+
506
+ fs.writeFileSync(file, samplesStub(name, info.record.props), { flag: "wx" });
507
+ out(`wrote ${slash(path.relative(root, file))}`);
508
+
509
+ return 0;
510
+ } catch (error) {
511
+ err(`error: ${String(/** @type {Error} */ (error).message).replace(/^\[pano-plugin\] /, "")}`);
512
+
513
+ return 1;
514
+ }
515
+ }
516
+
517
+ // ---------------------------------------------------------------------------------------------
518
+ // pano-plugin check [--strict]: the samples part
519
+ // ---------------------------------------------------------------------------------------------
520
+
521
+ /**
522
+ * @typedef {object} SamplesCheck
523
+ * @property {string[]} errors always failing: a file that does not compile, a malformed file
524
+ * @property {string[]} problems failing under `--strict` only: a missing file, a missing state
525
+ * @property {string[]} notes views without samples, with the command that writes them
526
+ */
527
+
528
+ /**
529
+ * The samples rules of `check`: a view without samples is a note; under `strict` every view needs a samples file
530
+ * with `filled` and each standard state that its `notApplicable` does not name.
531
+ *
532
+ * @param {{ root?: string }} [options]
533
+ * @returns {Promise<SamplesCheck>}
534
+ */
535
+ export async function checkSamples(options = {}) {
536
+ const root = path.resolve(options.root ?? process.cwd());
537
+ /** @type {SamplesCheck} */
538
+ const result = { errors: [], problems: [], notes: [] };
539
+ const config = await loadConfig(root);
540
+ const dirs = config.viewDirs.map((dir) => path.resolve(root, dir));
541
+ const scan = await scanViews({ dirs, namespace: config.namespace, pluginId: config.pluginId, root });
542
+ /** @type {Awaited<ReturnType<typeof buildSamples>>} */
543
+ let built;
544
+
545
+ try {
546
+ built = await buildSamples({ root, viewDirs: dirs });
547
+ } catch (error) {
548
+ result.errors.push(String(/** @type {Error} */ (error).message).replace(/^\[pano-plugin\] /, ""));
549
+
550
+ return result;
551
+ }
552
+
553
+ result.errors.push(...built.duplicates, ...built.info.problems);
554
+
555
+ for (const view of [...scan.views.values()].sort((a, b) => (a.name < b.name ? -1 : 1))) {
556
+ const states = built.info.states[view.name];
557
+
558
+ if (!states) {
559
+ const hint = `pano-plugin samples ${view.name}`;
560
+
561
+ result.notes.push(`${view.name} has no samples — ${hint}`);
562
+ result.problems.push(`${view.rel}: ${view.name} has no samples file — run: ${hint}`);
563
+ continue;
564
+ }
565
+
566
+ const file = built.files.find((entry) => entry.name === view.name)?.file ?? "";
567
+ const where = slash(path.relative(root, file));
568
+ const skipped = built.info.notApplicable[view.name] ?? [];
569
+
570
+ for (const state of skipped) {
571
+ if (!STANDARD_STATES.includes(state)) {
572
+ result.problems.push(`${where}: notApplicable names '${state}', which is not a standard state (${STANDARD_STATES.join(", ")})`);
573
+ } else if (state === "filled") {
574
+ result.problems.push(`${where}: 'filled' cannot be listed in notApplicable — every view needs a filled sample`);
575
+ } else if (states.includes(state)) {
576
+ result.problems.push(`${where}: '${state}' is both a sample and in notApplicable — keep one`);
577
+ }
578
+ }
579
+
580
+ for (const state of STANDARD_STATES) {
581
+ if (!states.includes(state) && !skipped.includes(state)) {
582
+ result.problems.push(
583
+ state === "filled"
584
+ ? `${where}: ${view.name} has no 'filled' sample — add filled: { props: { ... } }`
585
+ : `${where}: ${view.name} has no '${state}' sample — add it, or list '${state}' in notApplicable`,
586
+ );
587
+ }
588
+ }
589
+ }
590
+
591
+ for (const entry of built.files) {
592
+ if (!scan.views.has(entry.name)) {
593
+ result.problems.push(
594
+ `${slash(path.relative(root, entry.file))} belongs to no view — there is no ${entry.name}.svelte; rename the file or remove it`,
595
+ );
596
+ }
597
+ }
598
+
599
+ return result;
600
+ }
601
+
602
+ /**
603
+ * `pano-plugin check [--strict] [--styles badge]`: the check of `cli-check.js` plus the samples rules above.
604
+ * The lines of the base check are replayed; the verdict line is recomputed with the samples problems in it.
605
+ *
606
+ * @param {{ root?: string, strict?: boolean, styles?: 'core' | 'badge', out?: (line: string) => void, err?: (line: string) => void }} [options]
607
+ * @returns {Promise<number>} the exit code
608
+ */
609
+ export async function runCheckWithSamples(options = {}) {
610
+ const root = path.resolve(options.root ?? process.cwd());
611
+ const out = options.out ?? ((line) => process.stdout.write(`${line}\n`));
612
+ const err = options.err ?? ((line) => process.stderr.write(`${line}\n`));
613
+ const strict = options.strict === true;
614
+ const { runCheck } = await import("./cli-check.js");
615
+ /** @type {string[]} */
616
+ const outLines = [];
617
+ /** @type {string[]} */
618
+ const errLines = [];
619
+ const code = await runCheck({
620
+ root,
621
+ strict,
622
+ styles: options.styles,
623
+ out: (line) => outLines.push(line),
624
+ err: (line) => errLines.push(line),
625
+ });
626
+
627
+ /** @type {SamplesCheck} */
628
+ let samples = { errors: [], problems: [], notes: [] };
629
+ /** @type {string | null} */
630
+ let failure = null;
631
+
632
+ try {
633
+ samples = await checkSamples({ root });
634
+ } catch (error) {
635
+ // the base check reports a broken plugin folder (no pluginId, unreadable views) on its own
636
+ failure = code === 0 ? String(/** @type {Error} */ (error).message).replace(/^\[pano-plugin\] /, "") : null;
637
+ }
638
+
639
+ const failing = [...samples.errors, ...(strict ? samples.problems : [])];
640
+
641
+ if (failure) failing.push(failure);
642
+
643
+ for (const line of errLines) err(line);
644
+ for (const message of failing) err(strict && !samples.errors.includes(message) ? `error (--strict): ${message}` : `error: ${message}`);
645
+
646
+ if (!strict) for (const note of samples.notes) out(`note: ${note}`);
647
+
648
+ for (const line of outLines) {
649
+ const passed = /^check passed \((\d+) warnings?\)$/.exec(line);
650
+ const failed = /^check failed: (\d+) problems?$/.exec(line);
651
+
652
+ if (passed || failed) {
653
+ const before = failed ? Number(failed[1]) : 0;
654
+ const total = before + failing.length;
655
+
656
+ out(
657
+ total === 0
658
+ ? line
659
+ : `check failed: ${total} problem${total === 1 ? "" : "s"}`,
660
+ );
661
+ } else {
662
+ out(line);
663
+ }
664
+ }
665
+
666
+ return code !== 0 || failing.length > 0 ? 1 : 0;
667
+ }