@panomc/sdk 1.0.0-dev.9 → 2.0.0-dev.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (166) hide show
  1. package/api/routes.core.json +3702 -0
  2. package/bin/api/__tests__/api-compat.test.mjs +97 -0
  3. package/bin/api/__tests__/check-paths.test.mjs +113 -0
  4. package/bin/api/__tests__/cli.test.mjs +44 -0
  5. package/bin/api/__tests__/extract-routes.test.mjs +132 -0
  6. package/bin/api/__tests__/fixtures/core-new/Pano/api/paths.old-new.json +82 -0
  7. package/bin/api/__tests__/fixtures/core-new/Pano/src/main/kotlin/com/panomc/platform/error/NotExists.kt +10 -0
  8. package/bin/api/__tests__/fixtures/core-new/Pano/src/main/kotlin/com/panomc/platform/model/Bases.kt +21 -0
  9. package/bin/api/__tests__/fixtures/core-new/Pano/src/main/kotlin/com/panomc/platform/route/api/GetSiteInfoAPI.kt +19 -0
  10. package/bin/api/__tests__/fixtures/core-new/Pano/src/main/kotlin/com/panomc/platform/route/api/auth/HostSsoAPI.kt +10 -0
  11. package/bin/api/__tests__/fixtures/core-new/Pano/src/main/kotlin/com/panomc/platform/route/api/panel/PanelAddonsAPI.kt +28 -0
  12. package/bin/api/__tests__/fixtures/core-new/Pano/src/main/kotlin/com/panomc/platform/route/api/plugins/GetPluginUiZipAPI.kt +9 -0
  13. package/bin/api/__tests__/fixtures/core-new/Pano/src/main/kotlin/com/panomc/platform/route/template/IndexTemplate.kt +9 -0
  14. package/bin/api/__tests__/fixtures/core-old/Pano/src/main/kotlin/com/panomc/platform/error/NotExists.kt +10 -0
  15. package/bin/api/__tests__/fixtures/core-old/Pano/src/main/kotlin/com/panomc/platform/model/Bases.kt +21 -0
  16. package/bin/api/__tests__/fixtures/core-old/Pano/src/main/kotlin/com/panomc/platform/route/api/GetSiteInfoAPI.kt +19 -0
  17. package/bin/api/__tests__/fixtures/core-old/Pano/src/main/kotlin/com/panomc/platform/route/api/auth/HostSsoAPI.kt +10 -0
  18. package/bin/api/__tests__/fixtures/core-old/Pano/src/main/kotlin/com/panomc/platform/route/api/panel/PanelAddonsAPI.kt +28 -0
  19. package/bin/api/__tests__/fixtures/core-old/Pano/src/main/kotlin/com/panomc/platform/route/api/plugins/GetPluginUiZipAPI.kt +9 -0
  20. package/bin/api/__tests__/fixtures/core-old/Pano/src/main/kotlin/com/panomc/platform/route/template/IndexTemplate.kt +9 -0
  21. package/bin/api/__tests__/fixtures/plugin-new/api/paths.old-new.json +66 -0
  22. package/bin/api/__tests__/fixtures/plugin-new/build.gradle.kts +42 -0
  23. package/bin/api/__tests__/fixtures/plugin-new/gradle.properties +4 -0
  24. package/bin/api/__tests__/fixtures/plugin-new/src/main/kotlin/com/example/demo/base/DemoApis.kt +13 -0
  25. package/bin/api/__tests__/fixtures/plugin-new/src/main/kotlin/com/example/demo/error/Errors.kt +16 -0
  26. package/bin/api/__tests__/fixtures/plugin-new/src/main/kotlin/com/example/demo/error/Plain.kt +4 -0
  27. package/bin/api/__tests__/fixtures/plugin-new/src/main/kotlin/com/example/demo/routes/GetThingsAPI.kt +16 -0
  28. package/bin/api/__tests__/fixtures/plugin-new/src/main/kotlin/com/example/demo/routes/PanelThingAPI.kt +11 -0
  29. package/bin/api/__tests__/fixtures/plugin-new/src/main/kotlin/com/example/demo/routes/ValidatedAPI.kt +18 -0
  30. package/bin/api/__tests__/fixtures/plugin-new/src/main/kotlin/com/example/demo/routes/WebhookAPI.kt +23 -0
  31. package/bin/api/__tests__/fixtures/plugin-new/src/panel/Things.js +4 -0
  32. package/bin/api/__tests__/fixtures/plugin-new/src/theme/Logo.svelte +9 -0
  33. package/bin/api/__tests__/fixtures/plugin-new/src/theme/api.js +29 -0
  34. package/bin/api/__tests__/fixtures/plugin-old/build.gradle.kts +22 -0
  35. package/bin/api/__tests__/fixtures/plugin-old/gradle.properties +4 -0
  36. package/bin/api/__tests__/fixtures/plugin-old/src/main/kotlin/com/example/demo/base/DemoApis.kt +13 -0
  37. package/bin/api/__tests__/fixtures/plugin-old/src/main/kotlin/com/example/demo/error/Errors.kt +16 -0
  38. package/bin/api/__tests__/fixtures/plugin-old/src/main/kotlin/com/example/demo/error/Plain.kt +4 -0
  39. package/bin/api/__tests__/fixtures/plugin-old/src/main/kotlin/com/example/demo/routes/GetThingsAPI.kt +16 -0
  40. package/bin/api/__tests__/fixtures/plugin-old/src/main/kotlin/com/example/demo/routes/PanelThingAPI.kt +11 -0
  41. package/bin/api/__tests__/fixtures/plugin-old/src/main/kotlin/com/example/demo/routes/ValidatedAPI.kt +18 -0
  42. package/bin/api/__tests__/fixtures/plugin-old/src/main/kotlin/com/example/demo/routes/WebhookAPI.kt +23 -0
  43. package/bin/api/__tests__/fixtures/plugin-old/src/panel/Things.js +4 -0
  44. package/bin/api/__tests__/fixtures/plugin-old/src/theme/Logo.svelte +9 -0
  45. package/bin/api/__tests__/fixtures/plugin-old/src/theme/api.js +29 -0
  46. package/bin/api/__tests__/fixtures/refusals/gradle.properties +1 -0
  47. package/bin/api/__tests__/fixtures/refusals/src/main/kotlin/x/Bad.kt +39 -0
  48. package/bin/api/__tests__/fixtures/unresolved/src/main/kotlin/x/Orphan.kt +19 -0
  49. package/bin/api/__tests__/helpers.mjs +48 -0
  50. package/bin/api/__tests__/migrate-v1.test.mjs +377 -0
  51. package/bin/api/__tests__/openapi-snapshot.test.mjs +120 -0
  52. package/bin/api/api-compat.mjs +204 -0
  53. package/bin/api/check-paths.mjs +135 -0
  54. package/bin/api/cli.mjs +83 -0
  55. package/bin/api/extract-routes.mjs +129 -0
  56. package/bin/api/js-scan.mjs +337 -0
  57. package/bin/api/kotlin.mjs +366 -0
  58. package/bin/api/migrate-v1.mjs +330 -0
  59. package/bin/api/openapi-snapshot.mjs +112 -0
  60. package/bin/api/project.mjs +172 -0
  61. package/bin/api/rename-table.mjs +66 -0
  62. package/bin/api/util.mjs +194 -0
  63. package/bin/pano-api.js +5 -0
  64. package/build/plugin-api-rollup.js +46 -0
  65. package/core/css/pano-tokens.css +225 -0
  66. package/core/favicon/apple-touch-icon.png +0 -0
  67. package/core/favicon/favicon-96x96.png +0 -0
  68. package/core/favicon/favicon.ico +0 -0
  69. package/core/favicon/favicon.svg +1 -0
  70. package/core/favicon/site.webmanifest +21 -0
  71. package/core/favicon/web-app-manifest-192x192.png +0 -0
  72. package/core/favicon/web-app-manifest-512x512.png +0 -0
  73. package/core/favicon_old/android-icon-144x144.png +0 -0
  74. package/core/favicon_old/android-icon-192x192.png +0 -0
  75. package/core/favicon_old/android-icon-36x36.png +0 -0
  76. package/core/favicon_old/android-icon-48x48.png +0 -0
  77. package/core/favicon_old/android-icon-72x72.png +0 -0
  78. package/core/favicon_old/android-icon-96x96.png +0 -0
  79. package/core/favicon_old/apple-icon-114x114.png +0 -0
  80. package/core/favicon_old/apple-icon-120x120.png +0 -0
  81. package/core/favicon_old/apple-icon-144x144.png +0 -0
  82. package/core/favicon_old/apple-icon-152x152.png +0 -0
  83. package/core/favicon_old/apple-icon-180x180.png +0 -0
  84. package/core/favicon_old/apple-icon-57x57.png +0 -0
  85. package/core/favicon_old/apple-icon-60x60.png +0 -0
  86. package/core/favicon_old/apple-icon-72x72.png +0 -0
  87. package/core/favicon_old/apple-icon-76x76.png +0 -0
  88. package/core/favicon_old/apple-icon-precomposed.png +0 -0
  89. package/core/favicon_old/apple-icon.png +0 -0
  90. package/core/favicon_old/browserconfig.xml +11 -0
  91. package/core/favicon_old/favicon-16x16.png +0 -0
  92. package/core/favicon_old/favicon-32x32.png +0 -0
  93. package/core/favicon_old/favicon-96x96.png +0 -0
  94. package/core/favicon_old/favicon.ico +0 -0
  95. package/core/favicon_old/manifest.json +41 -0
  96. package/core/favicon_old/ms-icon-144x144.png +0 -0
  97. package/core/favicon_old/ms-icon-150x150.png +0 -0
  98. package/core/favicon_old/ms-icon-310x310.png +0 -0
  99. package/core/favicon_old/ms-icon-70x70.png +0 -0
  100. package/core/fonts/quicksand-v8-latin-ext_latin_vietnamese-300.eot +0 -0
  101. package/core/fonts/quicksand-v8-latin-ext_latin_vietnamese-300.svg +483 -0
  102. package/core/fonts/quicksand-v8-latin-ext_latin_vietnamese-300.ttf +0 -0
  103. package/core/fonts/quicksand-v8-latin-ext_latin_vietnamese-300.woff +0 -0
  104. package/core/fonts/quicksand-v8-latin-ext_latin_vietnamese-300.woff2 +0 -0
  105. package/core/fonts/quicksand-v8-latin-ext_latin_vietnamese-500.eot +0 -0
  106. package/core/fonts/quicksand-v8-latin-ext_latin_vietnamese-500.svg +486 -0
  107. package/core/fonts/quicksand-v8-latin-ext_latin_vietnamese-500.ttf +0 -0
  108. package/core/fonts/quicksand-v8-latin-ext_latin_vietnamese-500.woff +0 -0
  109. package/core/fonts/quicksand-v8-latin-ext_latin_vietnamese-500.woff2 +0 -0
  110. package/core/fonts/quicksand-v8-latin-ext_latin_vietnamese-700.eot +0 -0
  111. package/core/fonts/quicksand-v8-latin-ext_latin_vietnamese-700.svg +484 -0
  112. package/core/fonts/quicksand-v8-latin-ext_latin_vietnamese-700.ttf +0 -0
  113. package/core/fonts/quicksand-v8-latin-ext_latin_vietnamese-700.woff +0 -0
  114. package/core/fonts/quicksand-v8-latin-ext_latin_vietnamese-700.woff2 +0 -0
  115. package/core/fonts/quicksand-v8-latin-ext_latin_vietnamese-regular.eot +0 -0
  116. package/core/fonts/quicksand-v8-latin-ext_latin_vietnamese-regular.svg +486 -0
  117. package/core/fonts/quicksand-v8-latin-ext_latin_vietnamese-regular.ttf +0 -0
  118. package/core/fonts/quicksand-v8-latin-ext_latin_vietnamese-regular.woff +0 -0
  119. package/core/fonts/quicksand-v8-latin-ext_latin_vietnamese-regular.woff2 +0 -0
  120. package/core/js/ControllerRegistry.js +421 -0
  121. package/core/js/NotificationManager.js +62 -0
  122. package/core/js/PluginAPI.js +39 -0
  123. package/core/js/PluginManager.js +851 -0
  124. package/core/js/RouteMatcher.js +142 -0
  125. package/core/js/__tests__/ControllerRegistry.test.js +378 -0
  126. package/core/js/__tests__/NotificationManager.test.js +57 -0
  127. package/core/js/__tests__/PluginAPI.test.js +25 -0
  128. package/core/js/__tests__/RouteMatcher.test.js +33 -0
  129. package/core/js/__tests__/accessClient.test.js +582 -0
  130. package/core/js/__tests__/api.util.v1.test.js +336 -0
  131. package/core/js/__tests__/appStores.test.js +47 -0
  132. package/core/js/__tests__/devBounce.test.js +28 -0
  133. package/core/js/__tests__/html.util.test.js +18 -0
  134. package/core/js/__tests__/pluginFolder.util.test.js +106 -0
  135. package/core/js/__tests__/pluginPackage.test.js +134 -0
  136. package/core/js/__tests__/pluginUiZip.test.js +47 -0
  137. package/core/js/__tests__/sdkLevel.test.js +34 -0
  138. package/core/js/api.util.js +433 -0
  139. package/core/js/appStores.js +93 -0
  140. package/core/js/basePath.js +10 -0
  141. package/core/js/html.util.js +26 -0
  142. package/core/js/pluginFolder.util.js +95 -0
  143. package/core/js/tooltip.util.js +59 -0
  144. package/core/js/variables.js +95 -0
  145. package/core/js/version.util.js +100 -0
  146. package/core/scss/_pano-tokens.scss +51 -0
  147. package/core/scss/custom-bootstrap.scss +210 -0
  148. package/core/scss/fonts.scss +85 -0
  149. package/core/scss/main.scss +389 -0
  150. package/core/scss/themes.scss +122 -0
  151. package/package.json +63 -11
  152. package/src/__tests__/controllers.test.js +220 -0
  153. package/src/__tests__/views.spike.test.js +472 -0
  154. package/src/components/{index.js → panel.js} +9 -7
  155. package/src/components/theme.js +18 -0
  156. package/src/controllers.js +127 -0
  157. package/src/index.js +1 -1
  158. package/src/runtime-specifiers.js +88 -0
  159. package/src/svelte.js +3 -2
  160. package/src/types.js +5 -3
  161. package/src/utils/api.js +42 -1
  162. package/src/utils/auth.js +8 -0
  163. package/src/utils/component.js +4 -2
  164. package/src/utils/route.js +16 -0
  165. package/src/utils/text.js +8 -0
  166. package/src/views.js +29 -0
@@ -0,0 +1,330 @@
1
+ // migrate-v1: the /api/v1 cutover codemod (doc 04 section 9). Steps:
2
+ // a Kotlin paths b Error codes c validation import prefix
3
+ // d api-level helper e client path literals f client result reads
4
+ // Every step is idempotent; `check` changes nothing and says what would change.
5
+ import fs from 'node:fs';
6
+ import path from 'node:path';
7
+ import { loadKotlinProject, layoutOf } from './project.mjs';
8
+ import { maskKotlin, splitArgs } from './kotlin.mjs';
9
+ import { applyRenames } from './rename-table.mjs';
10
+ import { resolvePath, isLegacy, API_ROOT, PLUGINS_ROOT } from './extract-routes.mjs';
11
+ import { rewritePathLiterals, rewriteResults, findJsLeftovers } from './js-scan.mjs';
12
+ import { walk, readText, rel, applyEdits, lineIndex, prettyJson, pluginIdFor } from './util.mjs';
13
+
14
+ export const ALL_STEPS = ['a', 'b', 'c', 'd', 'e', 'f'];
15
+ // Files that hold /api text which is not a Pano route. DatabaseMigration58to59.kt is the migration's own description
16
+ // text (it names the old paths on purpose), not a request path.
17
+ const OUTBOUND_ALLOWLIST = new Set(['ApiPaths.kt', 'PanoApiManager.kt', 'ServerSoftwareUrls.kt', 'PluginSourceCatalog.kt', 'DatabaseMigration58to59.kt']);
18
+
19
+ /** `TextUtil.convertToSnakeCase().uppercase()` of the platform. @param {string} name */
20
+ export const errorCodeOf = (name) => name.replace(/([a-z])([A-Z])/g, (_m, a, b) => `${a}_${b.toLowerCase()}`).toUpperCase();
21
+
22
+ /**
23
+ * New declared path of a legacy one (step a).
24
+ * @param {string} old declared path with the `/api` prefix
25
+ * @param {{ isCore: boolean, strip?: string | null, namespace: 'SITE' | 'PANEL' }} ctx
26
+ */
27
+ export function newDeclared(old, ctx) {
28
+ let p = old.slice('/api'.length) || '/';
29
+ if (ctx.isCore) p = applyRenames(p).path;
30
+ if (ctx.namespace === 'PANEL' && (p === '/panel' || p.startsWith('/panel/'))) p = p.slice('/panel'.length) || '/';
31
+ if (!ctx.isCore && ctx.strip) {
32
+ if (p === `/${ctx.strip}`) p = '/';
33
+ else if (p.startsWith(`/${ctx.strip}/`)) p = p.slice(ctx.strip.length + 1);
34
+ }
35
+ return p;
36
+ }
37
+
38
+ const GRADLE_HELPER = `
39
+ // api-level (pano-api migrate-v1): "panoApiLevel" of the pano-web-platform tree this plugin is built in, else "current" from
40
+ // the pano-api-level.properties inside the Pano jar on compileClasspath. \`apiLevel=\` in gradle.properties lowers it.
41
+ val panoApiLevel: String? by lazy {
42
+ (findProperty("apiLevel") as String?)
43
+ ?: (rootProject.findProperty("panoApiLevel") as String?)
44
+ ?: configurations.findByName("compileClasspath")?.files?.firstNotNullOfOrNull { jar ->
45
+ if (!jar.isFile || !jar.name.endsWith(".jar")) null
46
+ else ZipFile(jar).use { zip ->
47
+ zip.getEntry("pano-api-level.properties")?.let { entry ->
48
+ Properties().apply { load(zip.getInputStream(entry)) }.getProperty("current")
49
+ }
50
+ }
51
+ }
52
+ }
53
+ `;
54
+
55
+ const GRADLE_IMPORTS = ['import java.util.Properties', 'import java.util.zip.ZipFile'];
56
+
57
+ /**
58
+ * Puts the missing `import` lines at the top of a build script (below leading comments, blank lines and
59
+ * `@file:` / `package` lines). Inside a Gradle script `java.` is the `java {}` extension, so the helper
60
+ * has to use the short class names.
61
+ * @param {string} src
62
+ * @returns {string}
63
+ */
64
+ function withGradleImports(src) {
65
+ const missing = GRADLE_IMPORTS.filter((line) => !new RegExp(`^\\s*${line}\\s*$`, 'm').test(src));
66
+ if (!missing.length) return src;
67
+ const lines = src.split('\n');
68
+ let at = 0;
69
+ let inBlock = false;
70
+ while (at < lines.length) {
71
+ const t = lines[at].trim();
72
+ if (inBlock) {
73
+ if (t.includes('*/')) inBlock = false;
74
+ } else if (t.startsWith('/*')) {
75
+ inBlock = !t.includes('*/');
76
+ } else if (!(t === '' || t.startsWith('//') || t.startsWith('@file:') || t.startsWith('package '))) {
77
+ break;
78
+ }
79
+ at++;
80
+ }
81
+ lines.splice(at, 0, ...missing, ...(at < lines.length && lines[at].trim() !== '' && !/^\s*import\s/.test(lines[at]) ? [''] : []));
82
+ return lines.join('\n');
83
+ }
84
+
85
+ /**
86
+ * Step d on one build.gradle.kts.
87
+ * @param {string} src
88
+ * @returns {{ text: string, changed: boolean, warning?: string }}
89
+ */
90
+ export function addApiLevelHelper(src) {
91
+ if (/api-level/.test(src)) {
92
+ // a helper written by an earlier run used fully qualified names, which do not compile in a Gradle script
93
+ if (!/java\.util\.(?:zip\.ZipFile|Properties)\(/.test(src)) return { text: src, changed: false };
94
+ const fixed = withGradleImports(src.replace(/java\.util\.zip\.ZipFile\(/g, 'ZipFile(').replace(/java\.util\.Properties\(/g, 'Properties('));
95
+ return { text: fixed, changed: fixed !== src };
96
+ }
97
+ const manifest = /^([ \t]*)attributes\["(?:pano-version|id)"\]\s*=.*$/m.exec(src);
98
+ if (!manifest) {
99
+ if (/\bpluginId\b/.test(src) && /shadowJar|attributes\[/.test(src)) return { text: src, changed: false, warning: 'no jar manifest block with attributes["id"] found; add attributes["api-level"] by hand' };
100
+ return { text: src, changed: false };
101
+ }
102
+ const line = `${manifest[1]}panoApiLevel?.let { attributes["api-level"] = it }`;
103
+ const manifestEnd = manifest.index + manifest[0].length;
104
+ let out = src.slice(0, manifestEnd) + '\n' + line + src.slice(manifestEnd);
105
+ const anchor = /^val pluginId: String by project.*$/m.exec(out);
106
+ if (anchor) {
107
+ const at = anchor.index + anchor[0].length;
108
+ out = out.slice(0, at) + '\n' + GRADLE_HELPER + out.slice(at);
109
+ } else {
110
+ out = out.replace(/\s*$/, '\n') + GRADLE_HELPER;
111
+ }
112
+ return { text: withGradleImports(out), changed: true };
113
+ }
114
+
115
+ /**
116
+ * @typedef {{
117
+ * root: string, check?: boolean, only?: string[], strip?: string | null, pluginId?: string | null,
118
+ * quiet?: boolean
119
+ * }} MigrateOptions
120
+ * @typedef {{
121
+ * changes: Map<string, Set<string>>, leftovers: { file: string, line: number, what: string, text: string }[],
122
+ * warnings: string[], errors: string[], pairs: import('./js-scan.mjs').PathPair[]
123
+ * }} MigrateResult
124
+ */
125
+
126
+ /**
127
+ * @param {MigrateOptions} o
128
+ * @returns {MigrateResult}
129
+ */
130
+ export function migrateV1(o) {
131
+ const rootAbs = path.resolve(o.root);
132
+ const steps = new Set(o.only && o.only.length ? o.only : ALL_STEPS);
133
+ const layout = layoutOf(rootAbs);
134
+ /** @type {MigrateResult} */
135
+ const res = { changes: new Map(), leftovers: [], warnings: [], errors: [], pairs: [] };
136
+ const mark = (file, step) => {
137
+ if (!res.changes.has(file)) res.changes.set(file, new Set());
138
+ res.changes.get(file).add(step);
139
+ };
140
+ /** @type {Map<string, string>} absolute path -> new content */
141
+ const writes = new Map();
142
+ const pluginId = o.pluginId ?? (layout.core ? null : pluginIdFor(rootAbs, rootAbs));
143
+
144
+ // ---- Kotlin: steps a, b, c and the leftover scan ----
145
+ const project = loadKotlinProject(layout.kotlinRoot, { pluginId: o.pluginId ?? undefined, labelRoot: rootAbs });
146
+ /** @type {Map<string, { start: number, end: number, text: string }[]>} */
147
+ const edits = new Map();
148
+ const addEdit = (file, e, step) => {
149
+ const list = edits.get(file.path) || [];
150
+ const dup = list.find((x) => x.start === e.start && x.end === e.end);
151
+ if (dup) {
152
+ if (dup.text !== e.text) res.warnings.push(`${file.rel}: two endpoints want different rewrites of the same path text; kept the first`);
153
+ return;
154
+ }
155
+ list.push(e);
156
+ edits.set(file.path, list);
157
+ mark(file.rel, step);
158
+ };
159
+
160
+ if (steps.has('a')) {
161
+ if (project.errors.length) {
162
+ for (const e of project.errors) res.errors.push(`${e.file}:${e.line} ${e.message}`);
163
+ }
164
+ for (const ep of project.endpoints) {
165
+ if (ep.mount === 'ROOT') continue;
166
+ let namespace = ep.namespace;
167
+ const first = ep.calls.find((c) => isLegacy(c.value));
168
+ if (first && namespace === 'SITE' && !ep.namespaceExplicit && /^\/api\/panel(\/|$)/.test(first.value)) {
169
+ namespace = 'PANEL';
170
+ res.warnings.push(`${ep.file.rel}:${ep.cls.line} ${ep.cls.name} extends ${ep.terminal} but serves ${first.value}; add "override val namespace = Namespace.PANEL"`);
171
+ }
172
+ if (ep.terminal === 'PanelApi' && !ep.namespaceExplicit && first && !/^\/api\/panel(\/|$)/.test(first.value)) {
173
+ res.warnings.push(`${ep.file.rel}:${ep.cls.line} ${ep.cls.name} is a PanelApi serving ${first.value}; add "override val namespace = Namespace.SITE"`);
174
+ }
175
+ for (const call of ep.calls) {
176
+ if (!isLegacy(call.value)) continue;
177
+ const fresh = newDeclared(call.value, { isCore: !ep.pluginId, strip: o.strip, namespace });
178
+ const p0 = call.pieces.find((p) => p.value.length > 0);
179
+ if (!p0) continue;
180
+ const restText = call.value.slice(p0.value.length);
181
+ if (!fresh.endsWith(restText)) {
182
+ res.warnings.push(`${ep.file.rel}:${call.line} ${ep.cls.name}: cannot rewrite "${call.value}" (the path is built from several parts); edit it by hand to "${fresh}"`);
183
+ } else {
184
+ const text = fresh.slice(0, fresh.length - restText.length);
185
+ if (text !== p0.value) addEdit(p0.file, { start: p0.start, end: p0.end, text }, 'a');
186
+ }
187
+ const mounted = resolvePath(fresh, 'API', namespace, ep.pluginId);
188
+ res.pairs.push({
189
+ method: call.method, old: call.value, new: mounted, relative: (mounted.startsWith(PLUGINS_ROOT + '/') ? mounted.slice('/api'.length) : mounted.slice(API_ROOT.length)) || '/',
190
+ class: ep.cls.name, file: ep.file.rel,
191
+ });
192
+ }
193
+ }
194
+ }
195
+
196
+ if (steps.has('b')) {
197
+ const errorClasses = new Set();
198
+ for (const f of project.files) {
199
+ const usesPlatformError = f.pkg === 'com.panomc.platform.model' || f.imports.includes('com.panomc.platform.model.Error') || f.imports.includes('com.panomc.platform.model.*');
200
+ for (const c of f.classes) {
201
+ const sup = c.supers.find((s) => s.call && s.name === 'Error');
202
+ if (!sup || !usesPlatformError) continue;
203
+ errorClasses.add(c.name);
204
+ const args = splitArgs(f.code, sup.open + 1, sup.close);
205
+ const first = args.length ? f.text.slice(args[0].start, args[0].end).trim() : '';
206
+ if (/^"[A-Z][A-Z0-9_]*"$/.test(first) || /^code\s*=/.test(first)) continue;
207
+ const inner = f.code.slice(sup.open + 1, sup.close);
208
+ const lit = `"${errorCodeOf(c.name)}"`;
209
+ const text = inner.trim() === '' ? lit : /^\s*\n/.test(inner) ? `${lit},` : `${lit}, `;
210
+ addEdit(f, { start: sup.open + 1, end: sup.open + 1, text }, 'b');
211
+ }
212
+ }
213
+ for (const f of project.files) {
214
+ for (const c of f.classes) {
215
+ const sup = c.supers.find((s) => s.call && errorClasses.has(s.name));
216
+ if (sup) res.warnings.push(`${f.rel}:${c.line} ${c.name} extends the error class ${sup.name}; it inherits that code now (before: ${errorCodeOf(c.name)}); give it its own Error("${errorCodeOf(c.name)}", ...)`);
217
+ }
218
+ }
219
+ }
220
+
221
+ if (steps.has('c')) {
222
+ for (const f of project.files) {
223
+ const re = /io\.vertx\.ext\.web\.validation\.builder\./g;
224
+ let m;
225
+ while ((m = re.exec(f.code))) addEdit(f, { start: m.index, end: m.index + m[0].length, text: 'com.panomc.platform.schema.dsl.' }, 'c');
226
+ }
227
+ }
228
+
229
+ for (const f of project.files) {
230
+ const list = edits.get(f.path);
231
+ const next = list ? applyEdits(f.src, list) : f.src;
232
+ if (list && !o.check) writes.set(f.path, next);
233
+ // leftover Kotlin literals, measured on the result
234
+ if (OUTBOUND_ALLOWLIST.has(path.basename(f.path))) continue;
235
+ const text = list ? maskKotlin(next).text : f.text;
236
+ const lineOf = list ? lineIndex(next) : f.lineOf;
237
+ for (const m of text.matchAll(/"(\/api(?:\/|")|\/panel\/api(?:\/|"))/g)) {
238
+ res.leftovers.push({ file: f.rel, line: lineOf(m.index), what: '"/api/ literal', text: text.slice(m.index, m.index + 50).split('\n')[0] });
239
+ }
240
+ }
241
+
242
+ // ---- Gradle: step d ----
243
+ if (steps.has('d') && !layout.core) {
244
+ for (const p of walk(rootAbs, { exts: ['build.gradle.kts'] })) {
245
+ const src = readText(p);
246
+ const r = addApiLevelHelper(src);
247
+ if (r.warning) res.warnings.push(`${rel(rootAbs, p)}: ${r.warning}`);
248
+ if (r.changed) {
249
+ mark(rel(rootAbs, p), 'd');
250
+ if (!o.check) writes.set(p, r.text);
251
+ }
252
+ }
253
+ }
254
+
255
+ // ---- pairs file ----
256
+ const pairsFile = path.join(layout.apiDir, 'paths.old-new.json');
257
+ /** @type {import('./js-scan.mjs').PathPair[]} */
258
+ let existing = [];
259
+ if (fs.existsSync(pairsFile)) {
260
+ try {
261
+ existing = JSON.parse(readText(pairsFile));
262
+ } catch {
263
+ res.errors.push(`${rel(rootAbs, pairsFile)} is not valid JSON`);
264
+ }
265
+ }
266
+ const key = (p) => `${p.method || ''} ${p.old}`;
267
+ const merged = new Map(existing.map((p) => [key(p), p]));
268
+ for (const p of res.pairs) if (!merged.has(key(p))) merged.set(key(p), p);
269
+ const mergedList = [...merged.values()].sort((a, b) => a.old.localeCompare(b.old) || String(a.method).localeCompare(String(b.method)));
270
+ if (steps.has('a') && res.pairs.length && prettyJson(mergedList) !== (fs.existsSync(pairsFile) ? readText(pairsFile) : '')) {
271
+ mark(rel(rootAbs, pairsFile), 'a');
272
+ if (!o.check) writes.set(pairsFile, prettyJson(mergedList));
273
+ }
274
+
275
+ // ---- JS / Svelte: steps e, f and the leftover scan ----
276
+ if (!layout.core) {
277
+ const ctx = { pairs: mergedList, strip: o.strip ?? null, pluginId };
278
+ for (const p of walk(rootAbs, { exts: ['.js', '.mjs', '.cjs', '.svelte', '.ts'] })) {
279
+ if (path.basename(p) === 'pano-api.js') continue;
280
+ const src = readText(p);
281
+ let next = src;
282
+ if (steps.has('e')) {
283
+ const r = rewritePathLiterals(next, ctx);
284
+ // in a UI-only repo a plain "drop /api" is the normal case; in a plugin repo it may be a missed own route
285
+ if (mergedList.length || o.strip) for (const g of r.generic) res.warnings.push(`${rel(rootAbs, p)}: "${g}" matched no known route; only the /api prefix was dropped`);
286
+ if (r.count) {
287
+ next = r.text;
288
+ mark(rel(rootAbs, p), 'e');
289
+ }
290
+ }
291
+ if (steps.has('f')) {
292
+ const r = rewriteResults(next);
293
+ if (r.count) {
294
+ next = r.text;
295
+ mark(rel(rootAbs, p), 'f');
296
+ }
297
+ }
298
+ if (next !== src && !o.check) writes.set(p, next);
299
+ for (const l of findJsLeftovers(next)) res.leftovers.push({ file: rel(rootAbs, p), ...l });
300
+ }
301
+ }
302
+
303
+ if (!o.check && !res.errors.length) {
304
+ for (const [p, content] of writes) {
305
+ fs.mkdirSync(path.dirname(p), { recursive: true });
306
+ fs.writeFileSync(p, content);
307
+ }
308
+ }
309
+ return res;
310
+ }
311
+
312
+ /**
313
+ * CLI entry.
314
+ * @param {MigrateOptions} o
315
+ * @returns {number}
316
+ */
317
+ export function runMigrateV1(o) {
318
+ const r = migrateV1(o);
319
+ for (const e of r.errors) console.error(`error: ${e}`);
320
+ for (const w of r.warnings) console.error(`warning: ${w}`);
321
+ const files = [...r.changes.entries()].sort((a, b) => a[0].localeCompare(b[0]));
322
+ for (const [file, steps] of files) console.error(`${o.check ? 'would change' : 'changed'}: ${file} [${[...steps].sort().join(',')}]`);
323
+ for (const l of r.leftovers) console.error(`leftover: ${l.file}:${l.line} ${l.what} ${l.text}`);
324
+ console.error(
325
+ `migrate-v1: ${files.length} file(s) ${o.check ? 'would change' : 'changed'}, ${r.leftovers.length} leftover(s), ${r.warnings.length} warning(s)`,
326
+ );
327
+ if (r.errors.length) return 2;
328
+ if (o.check) return files.length || r.leftovers.length ? 1 : 0;
329
+ return 0;
330
+ }
@@ -0,0 +1,112 @@
1
+ // openapi-snapshot: fetch the OpenAPI documents of a booted Pano and write / check the committed snapshots.
2
+ // core GET /api/v1/openapi.json -> <core-dir>/openapi-core.json (default Pano/api)
3
+ // internal GET /api/v1/panel/openapi.json -> <core-dir>/openapi-internal.json
4
+ // plugin GET /api/v1/plugins/<id>/_/openapi.json -> <plugins-dir>/<id>/api/openapi.json
5
+ // --check exits 1 when a snapshot differs; breaking differences are listed through api-compat.
6
+ import fs from 'node:fs';
7
+ import path from 'node:path';
8
+ import { breaks } from './api-compat.mjs';
9
+ import { stableJson, pluginIdFor } from './util.mjs';
10
+
11
+ /**
12
+ * @param {string} base
13
+ * @param {string} p
14
+ * @param {typeof fetch} fetchImpl
15
+ * @returns {Promise<any | null>} null on 404
16
+ */
17
+ async function getJson(base, p, fetchImpl) {
18
+ const res = await fetchImpl(base.replace(/\/+$/, '') + p, { headers: { accept: 'application/json' } });
19
+ if (res.status === 404) return null;
20
+ if (!res.ok) throw new Error(`GET ${p} answered ${res.status}`);
21
+ return res.json();
22
+ }
23
+
24
+ /**
25
+ * Plugin repositories below a directory: folders with a gradle.properties holding a pluginId.
26
+ * @param {string} dir
27
+ * @returns {{ id: string, dir: string }[]}
28
+ */
29
+ export function findPluginRepos(dir) {
30
+ if (!fs.existsSync(dir)) return [];
31
+ const out = [];
32
+ for (const e of fs.readdirSync(dir, { withFileTypes: true })) {
33
+ if (!e.isDirectory()) continue;
34
+ const d = path.join(dir, e.name);
35
+ if (!fs.existsSync(path.join(d, 'gradle.properties'))) continue;
36
+ const id = pluginIdFor(d, d);
37
+ if (id) out.push({ id, dir: d });
38
+ }
39
+ return out.sort((a, b) => a.id.localeCompare(b.id));
40
+ }
41
+
42
+ /**
43
+ * @typedef {{
44
+ * url: string, write?: boolean, check?: boolean, coreDir: string, pluginsDir?: string, plugins?: string[],
45
+ * today?: string, allowBreaks?: boolean, fetch?: typeof fetch, repo?: string
46
+ * }} SnapshotOptions
47
+ */
48
+
49
+ /**
50
+ * @param {SnapshotOptions} o
51
+ * @returns {Promise<number>} exit code
52
+ */
53
+ export async function runOpenapiSnapshot(o) {
54
+ const f = o.fetch || fetch;
55
+ const today = o.today || new Date().toISOString().slice(0, 10);
56
+ /** @type {{ label: string, file: string, spec: any | null, optional?: boolean }[]} */
57
+ const targets = [];
58
+ try {
59
+ targets.push({ label: 'core', file: path.join(o.coreDir, 'openapi-core.json'), spec: await getJson(o.url, '/api/v1/openapi.json', f) });
60
+ targets.push({ label: 'internal', file: path.join(o.coreDir, 'openapi-internal.json'), spec: await getJson(o.url, '/api/v1/panel/openapi.json', f) });
61
+ /** @type {{ id: string, dir: string }[]} */
62
+ let repos = [];
63
+ if (o.pluginsDir) repos = findPluginRepos(o.pluginsDir);
64
+ if (o.repo) {
65
+ const id = pluginIdFor(o.repo, o.repo);
66
+ if (id) repos.push({ id, dir: path.resolve(o.repo) });
67
+ }
68
+ if (o.plugins && o.plugins.length) repos = repos.filter((r) => o.plugins.includes(r.id));
69
+ for (const r of repos) {
70
+ const spec = await getJson(o.url, `/api/v1/plugins/${r.id}/_/openapi.json`, f);
71
+ targets.push({ label: `plugin ${r.id}`, file: path.join(r.dir, 'api', 'openapi.json'), spec, optional: true });
72
+ }
73
+ } catch (e) {
74
+ console.error(`openapi-snapshot: ${e.message}`);
75
+ return 2;
76
+ }
77
+
78
+ let code = 0;
79
+ for (const t of targets) {
80
+ if (!t.spec) {
81
+ if (t.optional) console.error(`skipped: ${t.label} (the instance serves no OpenAPI document for it; plugin stopped or without endpoints)`);
82
+ else {
83
+ console.error(`error: ${t.label} document not served`);
84
+ code = 2;
85
+ }
86
+ continue;
87
+ }
88
+ const next = stableJson(t.spec);
89
+ const exists = fs.existsSync(t.file);
90
+ const current = exists ? fs.readFileSync(t.file, 'utf8') : null;
91
+ const list = exists ? breaks(JSON.parse(current), t.spec, today) : [];
92
+ for (const b of list) console.error(`break: ${t.label}: ${b}`);
93
+ if (current === next) {
94
+ console.error(`unchanged: ${t.label}`);
95
+ continue;
96
+ }
97
+ if (o.check) {
98
+ console.error(`${exists ? 'differs' : 'missing'}: ${t.label} snapshot ${t.file}`);
99
+ code = Math.max(code, 1);
100
+ } else if (o.write) {
101
+ if (list.length && !o.allowBreaks) {
102
+ console.error(`refused: ${t.label} has ${list.length} break(s); deprecate first or pass --allow-breaks`);
103
+ code = Math.max(code, 1);
104
+ continue;
105
+ }
106
+ fs.mkdirSync(path.dirname(t.file), { recursive: true });
107
+ fs.writeFileSync(t.file, next);
108
+ console.error(`wrote: ${t.label} -> ${t.file}`);
109
+ }
110
+ }
111
+ return code;
112
+ }
@@ -0,0 +1,172 @@
1
+ // Loads a tree of Kotlin sources and resolves its @Endpoint classes: base class through supertypes,
2
+ // namespace / mount overrides, `Path(...)` declarations with constants. Used by extract-routes and migrate-v1.
3
+ import fs from 'node:fs';
4
+ import path from 'node:path';
5
+ import { walk, readText, rel, pluginIdFor } from './util.mjs';
6
+ import { parseKotlin, findPathCalls, evalPathExpr } from './kotlin.mjs';
7
+
8
+ /** Base classes of the platform an endpoint finally has to extend. */
9
+ export const TERMINALS = new Set(['Api', 'LoggedInApi', 'PanelApi', 'SetupApi', 'Template']);
10
+
11
+ /**
12
+ * Where the Kotlin sources of `root` live: a pano-web-platform checkout is scanned at `Pano/src/main/kotlin`
13
+ * (core only, its plugins are separate repositories).
14
+ * @param {string} root
15
+ * @returns {{ kotlinRoot: string, apiDir: string, core: boolean }}
16
+ */
17
+ export function layoutOf(root) {
18
+ const abs = path.resolve(root);
19
+ const core = path.join(abs, 'Pano', 'src', 'main', 'kotlin');
20
+ if (fs.existsSync(core)) return { kotlinRoot: core, apiDir: path.join(abs, 'Pano', 'api'), core: true };
21
+ return { kotlinRoot: abs, apiDir: path.join(abs, 'api'), core: false };
22
+ }
23
+
24
+ /**
25
+ * @typedef {import('./kotlin.mjs').KotlinFile} KotlinFile
26
+ * @typedef {import('./kotlin.mjs').ClassInfo} ClassInfo
27
+ * @typedef {{
28
+ * cls: ClassInfo, file: KotlinFile, pluginId: string | null, terminal: string, namespace: 'SITE' | 'PANEL',
29
+ * namespaceExplicit: boolean, mount: 'API' | 'ROOT',
30
+ * calls: { method: string, line: number, file: KotlinFile, value: string, pieces: import('./kotlin.mjs').Piece[] }[]
31
+ * }} Endpoint
32
+ */
33
+
34
+ /**
35
+ * @param {string} root directory holding the Kotlin sources
36
+ * @param {{ pluginId?: string | null, labelRoot?: string }} [opts] `labelRoot` is what file labels are relative to
37
+ */
38
+ export function loadKotlinProject(root, opts = {}) {
39
+ const rootAbs = path.resolve(root);
40
+ const labelRoot = path.resolve(opts.labelRoot || root);
41
+ const files = walk(rootAbs, { exts: ['.kt'], kotlinMain: true }).map((p) => parseKotlin(readText(p), p, rel(labelRoot, p)));
42
+ /** @type {Map<string, ClassInfo[]>} */
43
+ const classes = new Map();
44
+ /** @type {Map<string, import('./kotlin.mjs').ConstInfo[]>} */
45
+ const consts = new Map();
46
+ for (const f of files) {
47
+ for (const c of f.classes) {
48
+ if (!classes.has(c.name)) classes.set(c.name, []);
49
+ classes.get(c.name).push(c);
50
+ }
51
+ for (const k of f.consts) {
52
+ if (!consts.has(k.name)) consts.set(k.name, []);
53
+ consts.get(k.name).push(k);
54
+ }
55
+ }
56
+ const idCache = new Map();
57
+ const pluginIdOf = (f) => opts.pluginId ?? pluginIdFor(path.dirname(f.path), rootAbs, idCache);
58
+
59
+ /** @type {(file: KotlinFile, ref: string) => import('./kotlin.mjs').ConstInfo | null} */
60
+ const resolveConst = (file, ref) => {
61
+ const parts = ref.split('.').filter((p) => p !== 'Companion');
62
+ const name = parts[parts.length - 1];
63
+ const ownerName = parts.length > 1 ? parts[parts.length - 2] : null;
64
+ const cands = consts.get(name) || [];
65
+ if (!cands.length) return null;
66
+ if (ownerName) {
67
+ const hit = cands.find((k) => k.owner === ownerName);
68
+ if (hit) return hit;
69
+ }
70
+ const same = cands.filter((k) => k.file === file);
71
+ if (same.length === 1) return same[0];
72
+ if (same.length > 1) return same.find((k) => k.owner === null) || same[0];
73
+ const samePkg = cands.filter((k) => k.file.pkg === file.pkg);
74
+ if (samePkg.length === 1) return samePkg[0];
75
+ return cands.length === 1 ? cands[0] : ownerName ? null : cands[0];
76
+ };
77
+
78
+ /** @param {string} name @param {KotlinFile} from */
79
+ const findClass = (name, from) => {
80
+ const cands = classes.get(name) || [];
81
+ if (cands.length <= 1) return cands[0] || null;
82
+ return cands.find((c) => c.file === from) || cands.find((c) => c.file.pkg === from.pkg) || cands[0];
83
+ };
84
+
85
+ /**
86
+ * @param {ClassInfo} cls
87
+ * @param {Set<ClassInfo>} [seen]
88
+ * @returns {{ terminal: string | null, chain: ClassInfo[] }}
89
+ */
90
+ const resolveBase = (cls, seen = new Set()) => {
91
+ if (seen.has(cls)) return { terminal: null, chain: [cls] };
92
+ seen.add(cls);
93
+ const ordered = [...cls.supers.filter((s) => s.call), ...cls.supers.filter((s) => !s.call)];
94
+ for (const sup of ordered) {
95
+ if (TERMINALS.has(sup.name)) return { terminal: sup.name, chain: [cls] };
96
+ const next = findClass(sup.name, cls.file);
97
+ if (next && next.kind !== 'interface') {
98
+ const r = resolveBase(next, seen);
99
+ if (r.terminal) return { terminal: r.terminal, chain: [cls, ...r.chain] };
100
+ }
101
+ }
102
+ return { terminal: null, chain: [cls] };
103
+ };
104
+
105
+ /** @type {{ file: string, line: number, message: string }[]} */
106
+ const errors = [];
107
+ /** @type {Endpoint[]} */
108
+ const endpoints = [];
109
+ for (const f of files) {
110
+ for (const cls of f.classes) {
111
+ if (!cls.annotations.includes('Endpoint') || cls.kind !== 'class' || cls.abstract) continue;
112
+ const fail = (message, line = cls.line) => errors.push({ file: f.rel, line, message: `${cls.name}: ${message}` });
113
+ const { terminal, chain } = resolveBase(cls);
114
+ if (!terminal) {
115
+ fail(
116
+ `cannot resolve its base class (supertypes: ${cls.supers.map((s) => s.name).join(', ') || 'none'}); ` +
117
+ `it has to reach ${[...TERMINALS].filter((t) => t !== 'Template').join(', ')} or Template through classes in the scanned sources`,
118
+ );
119
+ continue;
120
+ }
121
+ let namespace = terminal === 'PanelApi' ? 'PANEL' : 'SITE';
122
+ let namespaceExplicit = false;
123
+ let mount = terminal === 'Template' ? 'ROOT' : 'API';
124
+ let nsFound = false;
125
+ let mountFound = false;
126
+ for (const c of chain) {
127
+ if (!c.body) continue;
128
+ const bodyText = c.file.text.slice(c.body[0], c.body[1]);
129
+ const ns = /override\s+val\s+namespace\s*(?::\s*\w+\s*)?=\s*(?:[\w.]*\.)?Namespace\.(SITE|PANEL)\b/.exec(bodyText);
130
+ const mo = /override\s+val\s+mount\s*(?::\s*\w+\s*)?=\s*(?:[\w.]*\.)?Mount\.(API|ROOT)\b/.exec(bodyText);
131
+ if (ns && !nsFound) {
132
+ namespace = ns[1];
133
+ namespaceExplicit = true;
134
+ nsFound = true;
135
+ }
136
+ if (mo && !mountFound) {
137
+ mount = mo[1];
138
+ mountFound = true;
139
+ }
140
+ }
141
+ let calls = [];
142
+ let declaredIn = null;
143
+ for (const c of chain) {
144
+ if (!c.body) continue;
145
+ const found = findPathCalls(c.file, c.body[0], c.body[1]);
146
+ if (found.length) {
147
+ calls = found.map((p) => ({ ...p, file: c.file }));
148
+ declaredIn = c;
149
+ break;
150
+ }
151
+ }
152
+ if (!calls.length || !declaredIn) {
153
+ fail('no Path(...) declaration found in the class or its base classes');
154
+ continue;
155
+ }
156
+ const resolved = [];
157
+ let bad = false;
158
+ for (const call of calls) {
159
+ try {
160
+ const ev = evalPathExpr(call.file, call.expr, resolveConst);
161
+ resolved.push({ method: call.method, line: call.line, file: call.file, value: ev.value, pieces: ev.pieces });
162
+ } catch (e) {
163
+ fail(e.message, call.line);
164
+ bad = true;
165
+ }
166
+ }
167
+ if (bad) continue;
168
+ endpoints.push({ cls, file: f, pluginId: pluginIdOf(f), terminal, namespace, namespaceExplicit, mount, calls: resolved });
169
+ }
170
+ }
171
+ return { rootAbs, files, classes, consts, endpoints, errors, resolveConst, findClass, pluginIdOf };
172
+ }
@@ -0,0 +1,66 @@
1
+ // The core path renames of doc 04 section 1 (kebab-case normalisation) plus the addon and plugin-zip moves.
2
+ // Paths are written in today's form relative to /api (so panel paths keep their /panel segment).
3
+ import { escapeRe } from './util.mjs';
4
+
5
+ /** @type {ReadonlyArray<readonly [string, string]>} old prefix -> new prefix, matched per segment */
6
+ export const CORE_RENAMES = [
7
+ ['/siteInfo', '/site-info'],
8
+ ['/websiteLogo', '/website-logo'],
9
+ ['/visitorVisit', '/visitor-visit'],
10
+ ['/registerAgreement', '/register-agreement'],
11
+ ['/auth/renewPassword', '/auth/renew-password'],
12
+ ['/auth/resetPassword', '/auth/reset-password'],
13
+ ['/auth/verifyEmail', '/auth/verify-email'],
14
+ ['/auth/verifyLinkCode', '/auth/verify-link-code'],
15
+ ['/auth/verifyNewEmail', '/auth/verify-new-email'],
16
+ ['/profile/changeEmail', '/profile/change-email'],
17
+ ['/profile/resetPassword', '/profile/reset-password'],
18
+ ['/notifications/quick/markAsRead', '/notifications/quick/mark-as-read'],
19
+ ['/post/thumbnail/:filename', '/posts/thumbnails/:filename'],
20
+ ['/ticket/categories', '/ticket-categories'],
21
+ ['/panel/plugins', '/panel/addons'],
22
+ ['/plugins/:pluginId/resources/plugin-ui.zip', '/plugins/:pluginId/_/ui.zip'],
23
+ ];
24
+
25
+ /** @param {string} p */
26
+ export const segments = (p) => p.split('/').filter((s) => s.length > 0);
27
+
28
+ /**
29
+ * Does a (possibly template-holed) path segment fit a route segment?
30
+ * A route parameter (`:id`) fits anything; `${...}` holes fit any text.
31
+ * @param {string} lit @param {string} pat
32
+ */
33
+ export function segMatch(lit, pat) {
34
+ if (pat.startsWith(':')) return lit.length > 0;
35
+ if (!lit.includes('${')) return lit === pat;
36
+ const re = new RegExp('^' + lit.split(/\$\{[^}]*\}/).map(escapeRe).join('.*') + '$');
37
+ return re.test(pat);
38
+ }
39
+
40
+ /**
41
+ * Applies the first matching core rename to a path in today's form (relative to /api).
42
+ * Prefix semantics per segment: `/panel/plugins` also renames `/panel/plugins/search`.
43
+ * @param {string} p
44
+ * @param {(lit: string, pat: string) => boolean} [match] segment test, default {@link segMatch}
45
+ * @returns {{ path: string, renamed: boolean }}
46
+ */
47
+ export function applyRenames(p, match = segMatch) {
48
+ const segs = segments(p);
49
+ for (const [from, to] of CORE_RENAMES) {
50
+ const f = segments(from);
51
+ if (segs.length < f.length) continue;
52
+ const captured = {};
53
+ let ok = true;
54
+ for (let i = 0; i < f.length; i++) {
55
+ if (f[i].startsWith(':')) captured[f[i]] = segs[i];
56
+ else if (!match(segs[i], f[i])) {
57
+ ok = false;
58
+ break;
59
+ }
60
+ }
61
+ if (!ok) continue;
62
+ const t = segments(to).map((s) => (s.startsWith(':') ? captured[s] ?? s : s));
63
+ return { path: '/' + [...t, ...segs.slice(f.length)].join('/'), renamed: true };
64
+ }
65
+ return { path: p, renamed: false };
66
+ }