@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,950 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { DEFAULT_VIEW_DIRS, loadConfig } from "../config.js";
4
+
5
+ /**
6
+ * Build rules V1-V3 and V5 (doc 02 section 5.4, doc 01 section 2), plus the source
7
+ * analysis that the helper copy (`helpers.js`) and the version stamp (`stamp.js`) share.
8
+ *
9
+ * - V1 view imports: a view imports `svelte`, `svelte/*`, `svelte-i18n`, `@panomc/sdk`,
10
+ * `@panomc/sdk/*`, other view files and view helpers (relative `.js` under `src/theme/`,
11
+ * outside `src/theme/controllers/`, whose own imports are only other view helpers).
12
+ * - V2 controller purity: nothing reachable from a controller imports Svelte, the SDK,
13
+ * `$app/*` or a `.svelte` file. The error shows the import chain.
14
+ * - V3 sample purity: `*.samples.js` import only relative `.js` files, and so do those.
15
+ * - V5 no `setContext` / `getContext` / `hasContext` from `svelte` in a view.
16
+ *
17
+ * `PANO_VIEW_IMPORTS=warn` (or the `viewImports: 'warn'` option) turns V1 and V5 into
18
+ * warnings for plugins that are not migrated yet (doc 02 section 3); V2 and V3 always fail.
19
+ * The rule plugin exposes `api` (rollup's plugin-to-plugin channel):
20
+ * `api.viewImports` is `'warn'` or `'error'`, `api.manifestFlags()` is `{ viewImports: 'warn' }`
21
+ * in migration mode and `{}` otherwise (spread it into `pano-plugin.json`), `api.violations`
22
+ * is the list found by the last build start.
23
+ */
24
+
25
+ /** Packages a view may import (V1). */
26
+ const VIEW_PACKAGES = ["svelte", "svelte-i18n", "@panomc/sdk"];
27
+
28
+ /** Names whose use between views is refused (V5). */
29
+ const CONTEXT_FUNCTIONS = new Set(["setContext", "getContext", "hasContext"]);
30
+
31
+ /** Default folder of the view helpers and controllers, relative to the plugin root. */
32
+ export const DEFAULT_THEME_DIR = "src/theme";
33
+
34
+ const SKIPPED_DIRS = new Set(["node_modules", "__tests__"]);
35
+
36
+ /**
37
+ * @typedef {object} RulesOptions
38
+ * @property {string} [root] plugin root, default the current directory
39
+ * @property {string[]} [viewDirs] view folders relative to `root`; default from `pano.plugin.js`
40
+ * @property {string} [controllersDir] controllers folder (absolute or relative to `root`), default `<themeDir>/controllers`
41
+ * @property {string} [themeDir] folder that holds helpers and controllers, default `src/theme`
42
+ * @property {string} [namespace] plugin namespace, used in the messages; default from the plugin config
43
+ * @property {'warn' | 'error'} [viewImports] overrides `PANO_VIEW_IMPORTS`
44
+ * @property {Record<string, any>} [context] shared build context: gets `viewImports`, `violations`
45
+ */
46
+
47
+ /**
48
+ * @typedef {object} KitProject
49
+ * @property {string} root absolute plugin root
50
+ * @property {string} themeDir absolute
51
+ * @property {string} controllersDir absolute
52
+ * @property {string[]} viewDirs absolute
53
+ * @property {string} namespace
54
+ */
55
+
56
+ /**
57
+ * @typedef {object} Violation
58
+ * @property {'V1' | 'V2' | 'V3' | 'V5'} rule
59
+ * @property {string} file absolute path of the file the message is about
60
+ * @property {number} line 1-based
61
+ * @property {string} message full error text, file and line included
62
+ */
63
+
64
+ /**
65
+ * @typedef {object} Analysis
66
+ * @property {Map<string, string>} views view name (file name without `.svelte`) -> absolute file
67
+ * @property {Map<string, string[]>} helpers view name -> absolute helper files (transitive closure)
68
+ * @property {Violation[]} violations
69
+ */
70
+
71
+ /** @param {string} file */
72
+ export function toPosix(file) {
73
+ return file.split(path.sep).join("/");
74
+ }
75
+
76
+ /**
77
+ * @param {string} dir
78
+ * @param {string} file
79
+ */
80
+ function isInside(dir, file) {
81
+ const relative = path.relative(dir, file);
82
+ return relative !== "" && !relative.startsWith("..") && !path.isAbsolute(relative);
83
+ }
84
+
85
+ /**
86
+ * Resolves the project folders of the rules, stamp and helper plugins.
87
+ *
88
+ * @param {RulesOptions} [options]
89
+ * @returns {Promise<KitProject>}
90
+ */
91
+ export async function resolveProject(options = {}) {
92
+ const root = path.resolve(options.root ?? process.cwd());
93
+ let viewDirs = options.viewDirs;
94
+ let namespace = options.namespace;
95
+
96
+ if (!viewDirs || !namespace) {
97
+ let config = null;
98
+
99
+ try {
100
+ config = await loadConfig(root);
101
+ } catch {
102
+ config = null;
103
+ }
104
+
105
+ viewDirs ??= config?.viewDirs ?? [...DEFAULT_VIEW_DIRS];
106
+ namespace ??= config?.namespace ?? "<namespace>";
107
+ }
108
+
109
+ const themeDir = path.resolve(root, options.themeDir ?? DEFAULT_THEME_DIR);
110
+
111
+ return {
112
+ root,
113
+ themeDir,
114
+ controllersDir: path.resolve(root, options.controllersDir ?? path.join(themeDir, "controllers")),
115
+ viewDirs: viewDirs.map((dir) => path.resolve(root, dir)),
116
+ namespace,
117
+ };
118
+ }
119
+
120
+ /**
121
+ * Display name of a file in a message: relative to the theme folder when inside it
122
+ * (`lib/sale.js`), else relative to the plugin root.
123
+ *
124
+ * @param {KitProject} project
125
+ * @param {string} file
126
+ */
127
+ export function displayPath(project, file) {
128
+ return toPosix(
129
+ isInside(project.themeDir, file)
130
+ ? path.relative(project.themeDir, file)
131
+ : path.relative(project.root, file),
132
+ );
133
+ }
134
+
135
+ /**
136
+ * Walks every node of an ESTree-like tree.
137
+ *
138
+ * @param {any} root
139
+ * @param {(node: any, parent: any) => void} visit
140
+ */
141
+ export function walk(root, visit) {
142
+ const seen = new Set();
143
+
144
+ /** @param {any} node @param {any} parent */
145
+ function step(node, parent) {
146
+ if (!node || typeof node !== "object" || seen.has(node)) return;
147
+ seen.add(node);
148
+
149
+ if (Array.isArray(node)) {
150
+ for (const child of node) step(child, parent);
151
+ return;
152
+ }
153
+
154
+ if (typeof node.type === "string") visit(node, parent);
155
+
156
+ for (const key of Object.keys(node)) {
157
+ if (key === "loc" || key === "parent" || key === "metadata" || key === "range") continue;
158
+ const child = node[key];
159
+ if (child && typeof child === "object") step(child, typeof node.type === "string" ? node : parent);
160
+ }
161
+ }
162
+
163
+ step(root, null);
164
+ }
165
+
166
+ /**
167
+ * 1-based line of an offset.
168
+ *
169
+ * @param {string} source
170
+ * @param {number} offset
171
+ */
172
+ export function lineOf(source, offset) {
173
+ let line = 1;
174
+ const end = Math.min(offset, source.length);
175
+
176
+ for (let index = 0; index < end; index++) {
177
+ if (source.charCodeAt(index) === 10) line++;
178
+ }
179
+
180
+ return line;
181
+ }
182
+
183
+ /**
184
+ * Parses a `.svelte` file into its script programs (module first, then instance) or a
185
+ * `.js` file into one program. Offsets are absolute in `source`.
186
+ *
187
+ * @param {string} file
188
+ * @param {string} source
189
+ * @returns {Promise<any[]>}
190
+ */
191
+ export async function parsePrograms(file, source) {
192
+ try {
193
+ if (file.endsWith(".svelte")) {
194
+ const { parse } = await import("svelte/compiler");
195
+ const ast = parse(source, { modern: true, filename: file });
196
+ return [ast.module?.content, ast.instance?.content].filter(Boolean);
197
+ }
198
+
199
+ const { parseAst } = await import("rollup/parseAst");
200
+ return [parseAst(source)];
201
+ } catch (error) {
202
+ throw new Error(
203
+ `[pano-plugin] cannot parse ${file}: ${/** @type {Error} */ (error).message}`,
204
+ { cause: error },
205
+ );
206
+ }
207
+ }
208
+
209
+ /**
210
+ * @typedef {object} ImportRef
211
+ * @property {string} spec the specifier as written
212
+ * @property {number} line
213
+ * @property {number} start offset of the opening quote of the specifier
214
+ * @property {number} end offset after the closing quote
215
+ */
216
+
217
+ /**
218
+ * Every static import, `export ... from` and literal `import()` of the programs.
219
+ *
220
+ * @param {any[]} programs
221
+ * @param {string} source
222
+ * @returns {ImportRef[]}
223
+ */
224
+ export function collectImports(programs, source) {
225
+ /** @type {ImportRef[]} */
226
+ const imports = [];
227
+
228
+ for (const program of programs) {
229
+ walk(program, (node) => {
230
+ const isStatic =
231
+ node.type === "ImportDeclaration" ||
232
+ ((node.type === "ExportNamedDeclaration" || node.type === "ExportAllDeclaration") && node.source) ||
233
+ node.type === "ImportExpression";
234
+
235
+ if (!isStatic) return;
236
+
237
+ const literal = node.source;
238
+
239
+ if (!literal || literal.type !== "Literal" || typeof literal.value !== "string") return;
240
+
241
+ imports.push({
242
+ spec: literal.value,
243
+ line: lineOf(source, literal.start),
244
+ start: literal.start,
245
+ end: literal.end,
246
+ });
247
+ });
248
+ }
249
+
250
+ imports.sort((a, b) => a.start - b.start);
251
+ return imports;
252
+ }
253
+
254
+ /**
255
+ * Resolves a relative specifier the way a bundler would for plain source files.
256
+ *
257
+ * @param {string} fromFile
258
+ * @param {string} spec
259
+ * @returns {string | null} absolute file or null when nothing matches
260
+ */
261
+ export function resolveRelative(fromFile, spec) {
262
+ const clean = spec.replace(/[?#].*$/, "");
263
+ const base = path.resolve(path.dirname(fromFile), clean);
264
+ const candidates = [base, `${base}.js`, `${base}.svelte`, path.join(base, "index.js")];
265
+
266
+ for (const candidate of candidates) {
267
+ try {
268
+ if (fs.statSync(candidate).isFile()) return candidate;
269
+ } catch {
270
+ // try the next candidate
271
+ }
272
+ }
273
+
274
+ return null;
275
+ }
276
+
277
+ /** @param {string} spec */
278
+ function isRelative(spec) {
279
+ return spec.startsWith("./") || spec.startsWith("../") || spec === "." || spec === "..";
280
+ }
281
+
282
+ /**
283
+ * @param {string} spec
284
+ * @param {string[]} packages
285
+ */
286
+ function isPackageOrSubpath(spec, packages) {
287
+ return packages.some((name) => spec === name || spec.startsWith(`${name}/`));
288
+ }
289
+
290
+ /**
291
+ * Files below `dirs` (recursively) accepted by `accept`, sorted.
292
+ *
293
+ * @param {string[]} dirs
294
+ * @param {(file: string) => boolean} accept
295
+ * @returns {string[]}
296
+ */
297
+ export function listFiles(dirs, accept) {
298
+ /** @type {string[]} */
299
+ const found = [];
300
+
301
+ /** @param {string} dir */
302
+ function visit(dir) {
303
+ let entries;
304
+
305
+ try {
306
+ entries = fs.readdirSync(dir, { withFileTypes: true });
307
+ } catch {
308
+ return;
309
+ }
310
+
311
+ for (const entry of entries) {
312
+ if (entry.name.startsWith(".") || SKIPPED_DIRS.has(entry.name)) continue;
313
+
314
+ const full = path.join(dir, entry.name);
315
+
316
+ if (entry.isDirectory()) visit(full);
317
+ else if (entry.isFile() && accept(full)) found.push(full);
318
+ }
319
+ }
320
+
321
+ for (const dir of dirs) visit(dir);
322
+
323
+ return [...new Set(found)].sort();
324
+ }
325
+
326
+ /**
327
+ * The public controller files: `.js` files directly under the controllers folder, without
328
+ * `_*.js` (private code) and `types.js` (typedefs).
329
+ *
330
+ * @param {KitProject} project
331
+ * @returns {string[]}
332
+ */
333
+ export function controllerFiles(project) {
334
+ let entries;
335
+
336
+ try {
337
+ entries = fs.readdirSync(project.controllersDir, { withFileTypes: true });
338
+ } catch {
339
+ return [];
340
+ }
341
+
342
+ return entries
343
+ .filter(
344
+ (entry) =>
345
+ entry.isFile() &&
346
+ entry.name.endsWith(".js") &&
347
+ !entry.name.startsWith("_") &&
348
+ entry.name !== "types.js",
349
+ )
350
+ .map((entry) => path.join(project.controllersDir, entry.name))
351
+ .sort();
352
+ }
353
+
354
+ /**
355
+ * Per-analysis cache of file contents, parsed programs and imports.
356
+ *
357
+ * @param {KitProject} _project
358
+ */
359
+ function createSourceCache(_project) {
360
+ /** @type {Map<string, Promise<{ source: string, programs: any[], imports: ImportRef[] }>>} */
361
+ const cache = new Map();
362
+
363
+ return {
364
+ /** @param {string} file */
365
+ load(file) {
366
+ let entry = cache.get(file);
367
+
368
+ if (!entry) {
369
+ entry = (async () => {
370
+ const source = fs.readFileSync(file, "utf8");
371
+ const programs = await parsePrograms(file, source);
372
+ return { source, programs, imports: collectImports(programs, source) };
373
+ })();
374
+ cache.set(file, entry);
375
+ }
376
+
377
+ return entry;
378
+ },
379
+ };
380
+ }
381
+
382
+ /**
383
+ * Finds `setContext` / `getContext` / `hasContext` imported from `svelte` and used in a view.
384
+ *
385
+ * @param {any[]} programs
386
+ * @param {string} source
387
+ * @returns {{ line: number, text: string }[]}
388
+ */
389
+ function findContextUses(programs, source) {
390
+ /** @type {Map<string, string>} local name -> imported name */
391
+ const locals = new Map();
392
+ /** @type {Map<string, { line: number, imported: string }>} */
393
+ const importedAt = new Map();
394
+ /** @type {Set<string>} */
395
+ const namespaces = new Set();
396
+ /** @type {{ line: number, text: string }[]} */
397
+ const uses = [];
398
+ const calledLocals = new Set();
399
+
400
+ for (const program of programs) {
401
+ walk(program, (node) => {
402
+ if (node.type !== "ImportDeclaration" || node.source?.value !== "svelte") return;
403
+
404
+ for (const specifier of node.specifiers) {
405
+ if (specifier.type === "ImportSpecifier") {
406
+ const imported = specifier.imported.name ?? specifier.imported.value;
407
+
408
+ if (CONTEXT_FUNCTIONS.has(imported)) {
409
+ locals.set(specifier.local.name, imported);
410
+ importedAt.set(specifier.local.name, {
411
+ line: lineOf(source, specifier.start),
412
+ imported,
413
+ });
414
+ }
415
+ } else {
416
+ namespaces.add(specifier.local.name);
417
+ }
418
+ }
419
+ });
420
+ }
421
+
422
+ if (locals.size === 0 && namespaces.size === 0) return uses;
423
+
424
+ for (const program of programs) {
425
+ walk(program, (node) => {
426
+ if (node.type !== "CallExpression") return;
427
+
428
+ let name = null;
429
+ const callee = node.callee;
430
+
431
+ if (callee.type === "Identifier" && locals.has(callee.name)) {
432
+ name = /** @type {string} */ (locals.get(callee.name));
433
+ calledLocals.add(callee.name);
434
+ } else if (
435
+ callee.type === "MemberExpression" &&
436
+ !callee.computed &&
437
+ callee.object.type === "Identifier" &&
438
+ namespaces.has(callee.object.name) &&
439
+ CONTEXT_FUNCTIONS.has(callee.property.name)
440
+ ) {
441
+ name = callee.property.name;
442
+ }
443
+
444
+ if (!name) return;
445
+
446
+ const first = node.arguments[0];
447
+ const argument = first ? source.slice(first.start, first.end) : "";
448
+ uses.push({ line: lineOf(source, node.start), text: `${name}(${argument})` });
449
+ });
450
+ }
451
+
452
+ for (const [local, info] of importedAt) {
453
+ if (!calledLocals.has(local)) {
454
+ uses.push({ line: info.line, text: `${info.imported} (imported from "svelte")` });
455
+ }
456
+ }
457
+
458
+ return uses.sort((a, b) => a.line - b.line);
459
+ }
460
+
461
+ /**
462
+ * Runs the checks of V1, V2, V3 and V5 and collects the view-to-helper closures.
463
+ *
464
+ * @param {KitProject} project
465
+ * @returns {Promise<Analysis>}
466
+ */
467
+ export async function analyzeProject(project) {
468
+ const { root, themeDir, controllersDir, viewDirs, namespace } = project;
469
+ const files = createSourceCache(project);
470
+ /** @type {Violation[]} */
471
+ const violations = [];
472
+ const reported = new Set();
473
+
474
+ /**
475
+ * @param {Violation} violation
476
+ * @param {string} spec
477
+ */
478
+ function report(violation, spec) {
479
+ const key = `${violation.rule}|${violation.file}|${violation.line}|${spec}|${violation.message}`;
480
+
481
+ if (reported.has(key)) return;
482
+
483
+ reported.add(key);
484
+ violations.push(violation);
485
+ }
486
+
487
+ const controllersRel = `${toPosix(path.relative(root, controllersDir))}/`;
488
+
489
+ /** @param {string} target */
490
+ function controllerNameOf(target) {
491
+ return toPosix(path.relative(controllersDir, target)).replace(/\.js$/, "");
492
+ }
493
+
494
+ /** @type {Map<string, string>} */
495
+ const views = new Map();
496
+ const viewFiles = listFiles(viewDirs, (file) => file.endsWith(".svelte"));
497
+
498
+ for (const file of viewFiles) views.set(path.basename(file, ".svelte"), file);
499
+
500
+ /** @type {Map<string, Set<string>>} helper file -> helpers it imports */
501
+ const helperDeps = new Map();
502
+ /** @type {Map<string, string>} helper file -> name of the first view that uses it */
503
+ const firstUser = new Map();
504
+
505
+ /**
506
+ * Checks the imports of a helper file once and records its dependencies.
507
+ *
508
+ * @param {string} helper
509
+ * @param {string} usedBy view file name
510
+ */
511
+ async function checkHelper(helper, usedBy) {
512
+ if (helperDeps.has(helper)) return;
513
+
514
+ const deps = new Set();
515
+ helperDeps.set(helper, deps);
516
+ firstUser.set(helper, usedBy);
517
+
518
+ const { imports } = await files.load(helper);
519
+ const where = (/** @type {number} */ line) =>
520
+ `${displayPath(project, helper)}:${line} (used by ${usedBy})`;
521
+
522
+ for (const imp of imports) {
523
+ if (!isRelative(imp.spec)) {
524
+ report(
525
+ {
526
+ rule: "V1",
527
+ file: helper,
528
+ line: imp.line,
529
+ message: `${where(imp.line)} imports ${imp.spec} — view helpers ship as readable source and cannot import packages; move that code to ${controllersRel} (packages are bundled there)`,
530
+ },
531
+ imp.spec,
532
+ );
533
+ continue;
534
+ }
535
+
536
+ const target = resolveRelative(helper, imp.spec);
537
+
538
+ if (!target) continue;
539
+
540
+ if (target === controllersDir || isInside(controllersDir, target)) {
541
+ report(
542
+ {
543
+ rule: "V1",
544
+ file: helper,
545
+ line: imp.line,
546
+ message: `${where(imp.line)} imports ${imp.spec} — controllers are compiled and closed; read it from the view with plugin('${namespace}').require('${controllerNameOf(target)}')`,
547
+ },
548
+ imp.spec,
549
+ );
550
+ continue;
551
+ }
552
+
553
+ if (target.endsWith(".svelte")) {
554
+ report(
555
+ {
556
+ rule: "V1",
557
+ file: helper,
558
+ line: imp.line,
559
+ message: `${where(imp.line)} imports ${imp.spec} — view helpers are plain .js and cannot import views`,
560
+ },
561
+ imp.spec,
562
+ );
563
+ continue;
564
+ }
565
+
566
+ if (!target.endsWith(".js")) {
567
+ report(
568
+ {
569
+ rule: "V1",
570
+ file: helper,
571
+ line: imp.line,
572
+ message: `${where(imp.line)} imports ${imp.spec} — view helpers import only other relative .js view helpers`,
573
+ },
574
+ imp.spec,
575
+ );
576
+ continue;
577
+ }
578
+
579
+ if (!isInside(themeDir, target)) {
580
+ report(
581
+ {
582
+ rule: "V1",
583
+ file: helper,
584
+ line: imp.line,
585
+ message: `${where(imp.line)} imports ${imp.spec} — view helpers must live under ${toPosix(path.relative(root, themeDir))}/ so they ship with the views`,
586
+ },
587
+ imp.spec,
588
+ );
589
+ continue;
590
+ }
591
+
592
+ deps.add(target);
593
+ await checkHelper(target, usedBy);
594
+ }
595
+ }
596
+
597
+ /** @type {Map<string, Set<string>>} */
598
+ const closures = new Map();
599
+
600
+ for (const [name, viewFile] of views) {
601
+ const { source, programs, imports } = await files.load(viewFile);
602
+ const base = path.basename(viewFile);
603
+ const direct = new Set();
604
+
605
+ for (const imp of imports) {
606
+ const at = `${base}:${imp.line}`;
607
+
608
+ if (!isRelative(imp.spec)) {
609
+ if (isPackageOrSubpath(imp.spec, VIEW_PACKAGES)) continue;
610
+
611
+ report(
612
+ {
613
+ rule: "V1",
614
+ file: viewFile,
615
+ line: imp.line,
616
+ message: `${at} imports ${imp.spec} — view helpers ship as readable source and cannot import packages; move that code to ${controllersRel} (packages are bundled there)`,
617
+ },
618
+ imp.spec,
619
+ );
620
+ continue;
621
+ }
622
+
623
+ const target = resolveRelative(viewFile, imp.spec);
624
+
625
+ if (!target) continue;
626
+
627
+ if (target === controllersDir || isInside(controllersDir, target)) {
628
+ report(
629
+ {
630
+ rule: "V1",
631
+ file: viewFile,
632
+ line: imp.line,
633
+ message: `${at} imports ${imp.spec} — controllers are compiled and closed; read it with plugin('${namespace}').require('${controllerNameOf(target)}')`,
634
+ },
635
+ imp.spec,
636
+ );
637
+ continue;
638
+ }
639
+
640
+ if (target.endsWith(".svelte")) {
641
+ if (!viewDirs.some((dir) => isInside(dir, target))) {
642
+ report(
643
+ {
644
+ rule: "V1",
645
+ file: viewFile,
646
+ line: imp.line,
647
+ message: `${at} imports ${imp.spec} — ${path.basename(target)} is not under a view folder (${viewDirs.map((dir) => toPosix(path.relative(root, dir))).join(", ")}); move it there so it ships as a view`,
648
+ },
649
+ imp.spec,
650
+ );
651
+ }
652
+ continue;
653
+ }
654
+
655
+ if (!target.endsWith(".js")) {
656
+ report(
657
+ {
658
+ rule: "V1",
659
+ file: viewFile,
660
+ line: imp.line,
661
+ message: `${at} imports ${imp.spec} — views import only .svelte files and relative .js view helpers`,
662
+ },
663
+ imp.spec,
664
+ );
665
+ continue;
666
+ }
667
+
668
+ if (!isInside(themeDir, target)) {
669
+ report(
670
+ {
671
+ rule: "V1",
672
+ file: viewFile,
673
+ line: imp.line,
674
+ message: `${at} imports ${imp.spec} — view helpers must live under ${toPosix(path.relative(root, themeDir))}/ so they ship with the views`,
675
+ },
676
+ imp.spec,
677
+ );
678
+ continue;
679
+ }
680
+
681
+ direct.add(target);
682
+ await checkHelper(target, base);
683
+ }
684
+
685
+ const closure = new Set();
686
+ const pending = [...direct];
687
+
688
+ while (pending.length > 0) {
689
+ const next = /** @type {string} */ (pending.pop());
690
+
691
+ if (closure.has(next)) continue;
692
+
693
+ closure.add(next);
694
+ for (const dep of helperDeps.get(next) ?? []) pending.push(dep);
695
+ }
696
+
697
+ closures.set(name, closure);
698
+
699
+ for (const use of findContextUses(programs, source)) {
700
+ report(
701
+ {
702
+ rule: "V5",
703
+ file: viewFile,
704
+ line: use.line,
705
+ message: `${base}:${use.line} ${use.text}: views run in two Svelte copies on the server; take it as a prop or read host data through @panomc/sdk`,
706
+ },
707
+ use.text,
708
+ );
709
+ }
710
+ }
711
+
712
+ await checkControllers(project, files, report);
713
+ await checkSamples(project, files, report);
714
+
715
+ violations.sort(
716
+ (a, b) => a.rule.localeCompare(b.rule) || a.file.localeCompare(b.file) || a.line - b.line,
717
+ );
718
+
719
+ return {
720
+ views,
721
+ helpers: new Map([...closures].map(([name, set]) => [name, [...set].sort()])),
722
+ violations,
723
+ };
724
+ }
725
+
726
+ /** Packages and prefixes a controller (and everything it imports) may not touch (V2). */
727
+ function isFrameworkSpecifier(spec) {
728
+ return (
729
+ isPackageOrSubpath(spec, ["svelte", "svelte-i18n", "@panomc/sdk"]) ||
730
+ spec === "$app" ||
731
+ spec.startsWith("$app/")
732
+ );
733
+ }
734
+
735
+ /**
736
+ * V2: walks the relative imports from every public controller.
737
+ *
738
+ * @param {KitProject} project
739
+ * @param {ReturnType<typeof createSourceCache>} files
740
+ * @param {(violation: Violation, spec: string) => void} report
741
+ */
742
+ async function checkControllers(project, files, report) {
743
+ /** @type {Map<string, string | null>} module -> module that first reached it */
744
+ const parents = new Map();
745
+ /** @type {string[]} */
746
+ const queue = [];
747
+
748
+ for (const entry of controllerFiles(project)) {
749
+ parents.set(entry, null);
750
+ queue.push(entry);
751
+ }
752
+
753
+ /** @param {string} file */
754
+ function chainTo(file) {
755
+ const chain = [];
756
+ /** @type {string | null | undefined} */
757
+ let current = file;
758
+
759
+ while (current) {
760
+ chain.unshift(current);
761
+ current = parents.get(current);
762
+ }
763
+
764
+ return chain;
765
+ }
766
+
767
+ for (let index = 0; index < queue.length; index++) {
768
+ const file = queue[index];
769
+ const { imports } = await files.load(file);
770
+
771
+ for (const imp of imports) {
772
+ let offender = null;
773
+
774
+ if (!isRelative(imp.spec)) {
775
+ if (isFrameworkSpecifier(imp.spec)) offender = imp.spec;
776
+ } else {
777
+ const target = resolveRelative(file, imp.spec);
778
+
779
+ if (!target) continue;
780
+
781
+ if (target.endsWith(".svelte")) offender = imp.spec;
782
+ else if (target.endsWith(".js") && !parents.has(target)) {
783
+ parents.set(target, file);
784
+ queue.push(target);
785
+ }
786
+ }
787
+
788
+ if (offender === null) continue;
789
+
790
+ const chain = chainTo(file).map((module) => displayPath(project, module));
791
+ chain[chain.length - 1] += `:${imp.line}`;
792
+
793
+ report(
794
+ {
795
+ rule: "V2",
796
+ file,
797
+ line: imp.line,
798
+ message: `${chain.join(" -> ")} imports ${offender} — controllers are framework-free; use host.session().`,
799
+ },
800
+ imp.spec,
801
+ );
802
+ }
803
+ }
804
+ }
805
+
806
+ /**
807
+ * V3: walks the relative imports from every `*.samples.js`.
808
+ *
809
+ * @param {KitProject} project
810
+ * @param {ReturnType<typeof createSourceCache>} files
811
+ * @param {(violation: Violation, spec: string) => void} report
812
+ */
813
+ async function checkSamples(project, files, report) {
814
+ const samples = listFiles(project.viewDirs, (file) => file.endsWith(".samples.js"));
815
+
816
+ for (const entry of samples) {
817
+ /** @type {Map<string, string | null>} */
818
+ const parents = new Map([[entry, null]]);
819
+ const queue = [entry];
820
+
821
+ /** @param {string} file */
822
+ const chainTo = (file) => {
823
+ const chain = [];
824
+ /** @type {string | null | undefined} */
825
+ let current = file;
826
+
827
+ while (current) {
828
+ chain.unshift(current);
829
+ current = parents.get(current);
830
+ }
831
+
832
+ return chain;
833
+ };
834
+
835
+ for (let index = 0; index < queue.length; index++) {
836
+ const file = queue[index];
837
+ const { imports } = await files.load(file);
838
+
839
+ for (const imp of imports) {
840
+ let offender = false;
841
+
842
+ if (!isRelative(imp.spec)) {
843
+ offender = true;
844
+ } else {
845
+ const target = resolveRelative(file, imp.spec);
846
+
847
+ if (!target) continue;
848
+
849
+ if (!target.endsWith(".js")) offender = true;
850
+ else if (!parents.has(target)) {
851
+ parents.set(target, file);
852
+ queue.push(target);
853
+ }
854
+ }
855
+
856
+ if (!offender) continue;
857
+
858
+ const chain = chainTo(file).map((module) => displayPath(project, module));
859
+ chain[chain.length - 1] += `:${imp.line}`;
860
+
861
+ report(
862
+ {
863
+ rule: "V3",
864
+ file,
865
+ line: imp.line,
866
+ message: `${chain.join(" -> ")} imports ${imp.spec} — sample files are pure data: import only view helpers and other relative .js fixtures (no packages, no Svelte, no @panomc/sdk)`,
867
+ },
868
+ imp.spec,
869
+ );
870
+ }
871
+ }
872
+ }
873
+ }
874
+
875
+ /**
876
+ * Whether the rules run in migration mode.
877
+ *
878
+ * @param {RulesOptions} options
879
+ * @returns {'warn' | 'error'}
880
+ */
881
+ export function viewImportsMode(options = {}) {
882
+ if (options.viewImports) return options.viewImports;
883
+ return process.env.PANO_VIEW_IMPORTS === "warn" ? "warn" : "error";
884
+ }
885
+
886
+ /**
887
+ * Build rules V1-V3 and V5 (doc 02 section 5.4, doc 01 section 2).
888
+ *
889
+ * @param {RulesOptions} [options]
890
+ * @returns {import('rollup').Plugin & { api: { readonly viewImports: 'warn' | 'error', manifestFlags(): { viewImports?: 'warn' }, violations: Violation[] } }}
891
+ */
892
+ export function panoRules(options = {}) {
893
+ /** @type {Violation[]} */
894
+ let violations = [];
895
+
896
+ const api = {
897
+ get viewImports() {
898
+ return viewImportsMode(options);
899
+ },
900
+ manifestFlags() {
901
+ return viewImportsMode(options) === "warn" ? { viewImports: /** @type {'warn'} */ ("warn") } : {};
902
+ },
903
+ get violations() {
904
+ return violations;
905
+ },
906
+ };
907
+
908
+ return {
909
+ name: "pano-rules",
910
+ api,
911
+
912
+ async buildStart() {
913
+ const project = await resolveProject(options);
914
+ const analysis = await analyzeProject(project);
915
+ const mode = viewImportsMode(options);
916
+
917
+ violations = analysis.violations;
918
+
919
+ if (options.context) {
920
+ options.context.viewImports = mode;
921
+ options.context.violations = violations;
922
+ }
923
+
924
+ for (const file of listFiles(project.viewDirs, (name) => name.endsWith(".samples.js"))) {
925
+ this.addWatchFile(file);
926
+ }
927
+
928
+ for (const file of controllerFiles(project)) this.addWatchFile(file);
929
+
930
+ /** @type {Violation[]} */
931
+ const failing = [];
932
+
933
+ for (const violation of violations) {
934
+ if (mode === "warn" && (violation.rule === "V1" || violation.rule === "V5")) {
935
+ this.warn(`${violation.message} (PANO_VIEW_IMPORTS=warn: migration mode, this will be an error)`);
936
+ } else {
937
+ failing.push(violation);
938
+ }
939
+ }
940
+
941
+ if (failing.length === 1) {
942
+ this.error(failing[0].message);
943
+ } else if (failing.length > 1) {
944
+ this.error(
945
+ `${failing.length} build rule violations:\n${failing.map((violation) => ` ${violation.rule} ${violation.message}`).join("\n")}`,
946
+ );
947
+ }
948
+ },
949
+ };
950
+ }