@panomc/theme-core 1.0.0-dev.39

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/bin/bundle-internal-libs.js +104 -0
  2. package/bin/check.js +253 -0
  3. package/bin/generate-licenses.js +125 -0
  4. package/bin/generate-runtime-shims.js +180 -0
  5. package/bin/license/file-fingerprint.js +74 -0
  6. package/bin/license/finalize-fingerprint.js +72 -0
  7. package/bin/license/generate-license-constants.js +335 -0
  8. package/bin/new.js +281 -0
  9. package/bin/package-zip.js +57 -0
  10. package/bin/sync.js +326 -0
  11. package/bin/templates/app.html +59 -0
  12. package/bin/theme-core.js +103 -0
  13. package/package.json +77 -0
  14. package/src/index.js +15 -0
  15. package/src/kit/hooks-client.js +128 -0
  16. package/src/kit/hooks-server.js +319 -0
  17. package/src/kit/license-runtime.js +373 -0
  18. package/src/kit/resolve.js +71 -0
  19. package/src/kit/specifiers.js +62 -0
  20. package/src/kit/svelte-config.js +74 -0
  21. package/src/kit/vite-config.js +249 -0
  22. package/src/lib/NotificationManager.js +1 -0
  23. package/src/lib/PluginAPI.js +368 -0
  24. package/src/lib/PluginManager.js +1 -0
  25. package/src/lib/Store.js +43 -0
  26. package/src/lib/api.util.js +5 -0
  27. package/src/lib/auth.util.js +77 -0
  28. package/src/lib/components/App.svelte +10 -0
  29. package/src/lib/components/Breadcrumb.svelte +88 -0
  30. package/src/lib/components/CardHeader.svelte +42 -0
  31. package/src/lib/components/Date.svelte +34 -0
  32. package/src/lib/components/DefaultToast.svelte +11 -0
  33. package/src/lib/components/ErrorAlert.svelte +16 -0
  34. package/src/lib/components/Footer.svelte +223 -0
  35. package/src/lib/components/Header.svelte +122 -0
  36. package/src/lib/components/Hook.svelte +71 -0
  37. package/src/lib/components/LinkCodeInput.svelte +129 -0
  38. package/src/lib/components/LoginFormBody.svelte +90 -0
  39. package/src/lib/components/Main.svelte +76 -0
  40. package/src/lib/components/Navbar.svelte +462 -0
  41. package/src/lib/components/NoContent.svelte +14 -0
  42. package/src/lib/components/NotificationContainer.svelte +304 -0
  43. package/src/lib/components/OnlineAdmins.svelte +64 -0
  44. package/src/lib/components/PageActions.svelte +39 -0
  45. package/src/lib/components/PageTitle.svelte +36 -0
  46. package/src/lib/components/Pagination.svelte +65 -0
  47. package/src/lib/components/PlayerHead.svelte +58 -0
  48. package/src/lib/components/PlayerPermissionBadge.svelte +19 -0
  49. package/src/lib/components/PlayerStatusBadge.svelte +63 -0
  50. package/src/lib/components/Post.svelte +240 -0
  51. package/src/lib/components/Posts.svelte +19 -0
  52. package/src/lib/components/RegisterForm.svelte +125 -0
  53. package/src/lib/components/Sidebar.svelte +12 -0
  54. package/src/lib/components/SuccessAlert.svelte +14 -0
  55. package/src/lib/components/TicketRow.svelte +61 -0
  56. package/src/lib/components/TicketStatus.svelte +24 -0
  57. package/src/lib/components/Tickets.svelte +43 -0
  58. package/src/lib/components/Toast.svelte +13 -0
  59. package/src/lib/components/ToastContainer.svelte +83 -0
  60. package/src/lib/components/ViewComponent.svelte +8 -0
  61. package/src/lib/components/modals/CloseTicketConfirmModal.svelte +121 -0
  62. package/src/lib/components/modals/ConfirmRemoveAllNotificationsModal.svelte +93 -0
  63. package/src/lib/components/modals/LogoutSessionConfirmModal.svelte +61 -0
  64. package/src/lib/components/sidebars/HomeSidebar.svelte +333 -0
  65. package/src/lib/components/sidebars/PlayerDetailSidebar.svelte +124 -0
  66. package/src/lib/components/sidebars/ProfileSidebar.svelte +149 -0
  67. package/src/lib/components/sidebars/SupportSidebar.svelte +54 -0
  68. package/src/lib/components/sidebars/TicketCreateAndDetailSidebar.svelte +84 -0
  69. package/src/lib/csrf.js +5 -0
  70. package/src/lib/init.libs.js +2 -0
  71. package/src/lib/language.util.js +154 -0
  72. package/src/lib/layouts/AppLayout.svelte +59 -0
  73. package/src/lib/layouts/AuthLayout.svelte +29 -0
  74. package/src/lib/layouts/MainLayout.svelte +60 -0
  75. package/src/lib/layouts/ProfileLayout.svelte +29 -0
  76. package/src/lib/layouts/ThemeSettingsLayout.svelte +37 -0
  77. package/src/lib/layouts/TicketsLayout.svelte +31 -0
  78. package/src/lib/loginInput.util.js +4 -0
  79. package/src/lib/orderNavLinks.util.js +58 -0
  80. package/src/lib/pages/ActivateEmailPage.svelte +48 -0
  81. package/src/lib/pages/ConfirmNewEmailPage.svelte +48 -0
  82. package/src/lib/pages/ErrorPage.svelte +41 -0
  83. package/src/lib/pages/HomePage.svelte +35 -0
  84. package/src/lib/pages/LoginPage.svelte +448 -0
  85. package/src/lib/pages/NotificationsPage.svelte +70 -0
  86. package/src/lib/pages/PlayerDetailPage.svelte +29 -0
  87. package/src/lib/pages/PostDetailPage.svelte +36 -0
  88. package/src/lib/pages/PreviewPostPage.svelte +38 -0
  89. package/src/lib/pages/RegisterPage.svelte +144 -0
  90. package/src/lib/pages/RenewPasswordPage.svelte +49 -0
  91. package/src/lib/pages/ResetPasswordPage.svelte +55 -0
  92. package/src/lib/pages/RulesPage.svelte +52 -0
  93. package/src/lib/pages/SupportPage.svelte +36 -0
  94. package/src/lib/pages/ThemeSettingsPage.svelte +551 -0
  95. package/src/lib/pages/profile/ProfilePage.svelte +32 -0
  96. package/src/lib/pages/profile/SettingsPage.svelte +163 -0
  97. package/src/lib/pages/profile/TicketsPage.svelte +54 -0
  98. package/src/lib/pages/ticket/CreateTicketPage.svelte +48 -0
  99. package/src/lib/pages/ticket/TicketDetailPage.svelte +59 -0
  100. package/src/lib/services/auth.js +85 -0
  101. package/src/lib/services/posts.js +152 -0
  102. package/src/lib/services/profile.js +37 -0
  103. package/src/lib/services/theme-setting.js +22 -0
  104. package/src/lib/services/tickets.js +95 -0
  105. package/src/lib/siteRealtime.js +244 -0
  106. package/src/lib/string.util.js +27 -0
  107. package/src/lib/tooltip.util.js +5 -0
  108. package/src/lib/ui-logics/layout-logics/AppLayoutLogics.js +321 -0
  109. package/src/lib/ui-logics/layout-logics/AuthLayoutLogics.js +10 -0
  110. package/src/lib/ui-logics/layout-logics/MainLayoutLogics.js +19 -0
  111. package/src/lib/ui-logics/layout-logics/ProfileLayoutLogics.js +10 -0
  112. package/src/lib/ui-logics/layout-logics/ThemeSettingsLayoutLogics.js +215 -0
  113. package/src/lib/ui-logics/layout-logics/TicketsLayoutLogics.js +10 -0
  114. package/src/lib/ui-logics/page-logics/ActiveEmailPageLogics.js +45 -0
  115. package/src/lib/ui-logics/page-logics/ConfirmNewEmailPageLogics.js +42 -0
  116. package/src/lib/ui-logics/page-logics/CreateTicketPageLogics.js +83 -0
  117. package/src/lib/ui-logics/page-logics/HomePageLogics.js +65 -0
  118. package/src/lib/ui-logics/page-logics/NotificationsPageLogics.js +264 -0
  119. package/src/lib/ui-logics/page-logics/PlayerDetailPageLogics.js +40 -0
  120. package/src/lib/ui-logics/page-logics/PostDetailPageLogics.js +58 -0
  121. package/src/lib/ui-logics/page-logics/PreviewPostPageLogics.js +53 -0
  122. package/src/lib/ui-logics/page-logics/ProfilePageLogics.js +44 -0
  123. package/src/lib/ui-logics/page-logics/RenewPasswordPageLogics.js +44 -0
  124. package/src/lib/ui-logics/page-logics/ResetPasswordPageLogics.js +53 -0
  125. package/src/lib/ui-logics/page-logics/SettingsPageLogics.js +230 -0
  126. package/src/lib/ui-logics/page-logics/SupportPageLogics.js +60 -0
  127. package/src/lib/ui-logics/page-logics/TicketDetailPageLogics.js +160 -0
  128. package/src/lib/ui-logics/page-logics/TicketsPageLogics.js +132 -0
  129. package/src/lib/variables.js +1 -0
  130. package/src/lib/views/ActivateEmailView.svelte +71 -0
  131. package/src/lib/views/AppLayoutView.svelte +31 -0
  132. package/src/lib/views/AuthLayoutView.svelte +23 -0
  133. package/src/lib/views/ConfirmNewEmailView.svelte +71 -0
  134. package/src/lib/views/CreateTicketView.svelte +73 -0
  135. package/src/lib/views/ErrorView.svelte +38 -0
  136. package/src/lib/views/HomeView.svelte +72 -0
  137. package/src/lib/views/LoginView.svelte +372 -0
  138. package/src/lib/views/MainLayoutView.svelte +86 -0
  139. package/src/lib/views/NotificationsView.svelte +129 -0
  140. package/src/lib/views/PlayerDetailView.svelte +31 -0
  141. package/src/lib/views/PostDetailView.svelte +199 -0
  142. package/src/lib/views/PreviewPostView.svelte +151 -0
  143. package/src/lib/views/ProfileLayoutView.svelte +16 -0
  144. package/src/lib/views/ProfileView.svelte +68 -0
  145. package/src/lib/views/RegisterView.svelte +113 -0
  146. package/src/lib/views/RenewPasswordView.svelte +98 -0
  147. package/src/lib/views/ResetPasswordView.svelte +88 -0
  148. package/src/lib/views/RulesView.svelte +26 -0
  149. package/src/lib/views/SettingsView.svelte +471 -0
  150. package/src/lib/views/SupportView.svelte +79 -0
  151. package/src/lib/views/ThemeSettingsLayoutView.svelte +19 -0
  152. package/src/lib/views/ThemeSettingsView.svelte +1508 -0
  153. package/src/lib/views/TicketDetailView.svelte +185 -0
  154. package/src/lib/views/TicketsLayoutView.svelte +21 -0
  155. package/src/lib/views/TicketsView.svelte +87 -0
  156. package/src/plugin-engine/engine.js +484 -0
  157. package/src/registry/index.js +86 -0
  158. package/src/routes/RootLayout.svelte +21 -0
  159. package/src/routes/plugin-ui/Layout.svelte +291 -0
  160. package/src/routes/plugin-ui/Page.svelte +117 -0
  161. package/src/routes/plugin-ui/layout.js +8 -0
  162. package/src/routes/plugin-ui/page.js +8 -0
  163. package/src/routes/plugins-client-file.js +76 -0
  164. package/src/routes/root-layout-load.js +15 -0
  165. package/src/routes/theme-api-languages.js +52 -0
  166. package/src/routes/theme-api-licenses.js +28 -0
@@ -0,0 +1,74 @@
1
+ /**
2
+ * Stable cumulative file fingerprint for a Pano theme.
3
+ *
4
+ * Algorithm (must stay bit-identical with the Kotlin port in
5
+ * com.panomc.platform.util.HashUtil.computeStableFileFingerprint, or every Pano host
6
+ * would refuse every theme):
7
+ *
8
+ * 1. walk the directory recursively, collecting regular files
9
+ * 2. compute each file's path relative to the root, normalised to forward slashes
10
+ * 3. drop any path in `excludeRelative` (`manifest.json` by default — it's where the
11
+ * expected fingerprint is stored, so it can't be part of its own input)
12
+ * 4. for each remaining file, build the line `<relPath>:<hex sha256 of content>`
13
+ * 5. sort lines by `<relPath>` using lexicographic byte order
14
+ * 6. join with `\n`, SHA-256 the result, return hex
15
+ *
16
+ * This is intentionally insensitive to filesystem mtimes / inode order and resilient to
17
+ * directory traversal order differences across platforms. The exclusion list is small and
18
+ * fixed so the build + runtime + host all agree without coordination.
19
+ *
20
+ * Used in three places:
21
+ * - build-time vite plugin (writes the digest into manifest.json)
22
+ * - theme runtime (src/lib/server/license-runtime.js — defence-in-depth self-check)
23
+ * - Pano host (Kotlin, before starting a premium theme's bun process)
24
+ */
25
+ import { createHash } from "node:crypto";
26
+ import { readFileSync, readdirSync } from "node:fs";
27
+ import { join, relative, sep } from "node:path";
28
+
29
+ export const DEFAULT_EXCLUDED_FILES = Object.freeze([
30
+ "manifest.json",
31
+ // Written at runtime by the Pano host (UIManager.writeThemeLicenseFile) so the theme
32
+ // runtime can pick up freshly-renewed JWTs without restarting the bun process. Must
33
+ // be excluded or every renewal would invalidate the integrity check.
34
+ ".pano-license.jwt",
35
+ ]);
36
+
37
+ export function sha256Hex(buffer) {
38
+ return createHash("sha256").update(buffer).digest("hex");
39
+ }
40
+
41
+ export function listFilesRecursive(dir) {
42
+ const out = [];
43
+ function walk(d) {
44
+ let entries;
45
+ try {
46
+ entries = readdirSync(d, { withFileTypes: true });
47
+ } catch {
48
+ return;
49
+ }
50
+ for (const entry of entries) {
51
+ const full = join(d, entry.name);
52
+ if (entry.isDirectory()) {
53
+ walk(full);
54
+ } else if (entry.isFile()) {
55
+ out.push(full);
56
+ }
57
+ }
58
+ }
59
+ walk(dir);
60
+ return out;
61
+ }
62
+
63
+ export function computeStableFileFingerprint(dir, excludeRelative = DEFAULT_EXCLUDED_FILES) {
64
+ const excludeSet = new Set(excludeRelative);
65
+ const items = listFilesRecursive(dir)
66
+ .map((full) => ({
67
+ rel: relative(dir, full).split(sep).join("/"),
68
+ full,
69
+ }))
70
+ .filter((it) => !excludeSet.has(it.rel))
71
+ .sort((a, b) => (a.rel < b.rel ? -1 : a.rel > b.rel ? 1 : 0))
72
+ .map((it) => `${it.rel}:${sha256Hex(readFileSync(it.full))}`);
73
+ return sha256Hex(items.join("\n"));
74
+ }
@@ -0,0 +1,72 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Post-build step for Pano themes — runs AFTER `vite build` has fully finished.
4
+ *
5
+ * Computes the stable cumulative SHA-256 of every file in `build/` (except manifest.json)
6
+ * and stamps it into `build/manifest.json` as the `fileFingerprint` field. The Pano host
7
+ * re-runs the same hash on install + every theme start, refusing premium themes whose
8
+ * extracted folder doesn't match.
9
+ *
10
+ * Why this is a separate node script and not a vite plugin:
11
+ * SvelteKit's adapter-node makes vite emit the SSR bundle and the client bundle in two
12
+ * passes. A vite plugin's `closeBundle` hook fires after EACH pass, so if it runs after
13
+ * the first pass the second pass's files aren't on disk yet and the digest is taken on
14
+ * an incomplete tree. Running the hash from package.json's `build` script (after
15
+ * `vite build` returns) guarantees both passes are done.
16
+ *
17
+ * Triggered by `package.json` scripts:
18
+ * "build": "vite build && node scripts/license/finalize-fingerprint.js"
19
+ */
20
+ import fs from "node:fs";
21
+ import path from "node:path";
22
+ import { computeStableFileFingerprint } from "./file-fingerprint.js";
23
+ import { collectLicenses } from "../generate-licenses.js";
24
+
25
+ const ROOT = process.cwd();
26
+ const BUILD_DIR = path.join(ROOT, "build");
27
+ const MANIFEST_FILE = path.join(BUILD_DIR, "manifest.json");
28
+
29
+ if (!fs.existsSync(BUILD_DIR) || !fs.statSync(BUILD_DIR).isDirectory()) {
30
+ console.error(`[pano-fingerprint] build/ not found at ${BUILD_DIR}. Did vite build succeed?`);
31
+ process.exit(1);
32
+ }
33
+ if (!fs.existsSync(MANIFEST_FILE)) {
34
+ console.error(`[pano-fingerprint] build/manifest.json missing. The copyManifestPlugin in vite.config.js must run first.`);
35
+ process.exit(1);
36
+ }
37
+
38
+ // licenses.json must exist BEFORE the fingerprint is computed (it is covered by
39
+ // it). Generated here, not in a vite plugin: a closeBundle hook races
40
+ // adapter-node's final build/ rewrite and the file intermittently vanishes.
41
+ if (!fs.existsSync(path.join(BUILD_DIR, "licenses.json"))) {
42
+ collectLicenses(BUILD_DIR);
43
+ }
44
+
45
+ const fingerprint = computeStableFileFingerprint(BUILD_DIR, ["manifest.json"]);
46
+
47
+ const manifest = JSON.parse(fs.readFileSync(MANIFEST_FILE, "utf-8"));
48
+ manifest.fileFingerprint = fingerprint;
49
+ fs.writeFileSync(MANIFEST_FILE, JSON.stringify(manifest, null, 2) + "\n");
50
+
51
+ console.log(
52
+ `[pano-fingerprint] manifest.fileFingerprint = ${fingerprint.slice(0, 16)}… (over ${
53
+ countFiles(BUILD_DIR, ["manifest.json"])
54
+ } files)`
55
+ );
56
+
57
+ function countFiles(dir, exclude) {
58
+ let n = 0;
59
+ const excludeSet = new Set(exclude);
60
+ function walk(d) {
61
+ for (const entry of fs.readdirSync(d, { withFileTypes: true })) {
62
+ const full = path.join(d, entry.name);
63
+ if (entry.isDirectory()) walk(full);
64
+ else if (entry.isFile()) {
65
+ const rel = path.relative(dir, full).split(path.sep).join("/");
66
+ if (!excludeSet.has(rel)) n++;
67
+ }
68
+ }
69
+ }
70
+ walk(dir);
71
+ return n;
72
+ }
@@ -0,0 +1,335 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Pre-build step for Pano themes (all themes — premium or free).
4
+ *
5
+ * Behaviour:
6
+ * - manifest.json's `premium: true` flag → fetch the panomc.com license verification
7
+ * public key (RS256, RSA-2048) and embed it into src/lib/server/license-constants.generated.js
8
+ * together with the theme's id and version. Required: build fails fast if the key cannot
9
+ * be resolved (silently building an unsigned "premium" theme would defeat DRM).
10
+ * - manifest.json without `premium: true` (or `premium: false`) → write a stub that makes
11
+ * the runtime helper a no-op, so the same code path is valid for free themes and dev.
12
+ *
13
+ * License-server selection (only matters for premium builds):
14
+ * 1. PANO_LICENSE_PUBLIC_KEY=<base64|PEM> explicit key (CI secret); wins outright
15
+ * 2. PANO_LICENSE_SERVER=prod|dev|<url> explicit server (fetches key)
16
+ * 3. Git branch auto-detect (when neither is set): `main`, `master`, `release-*` → prod;
17
+ * `dev`, `develop`, `staging`, `feat-*`, `fix-*`, `hotfix-*` → dev. The chosen server
18
+ * is logged so the operator knows where the embedded key came from.
19
+ * 4. Nothing → premium build aborts. Free build proceeds normally.
20
+ *
21
+ * `bun run dev` does NOT run this script (no prebuild hook on `dev`), so a developer can
22
+ * spin up a premium theme locally and it stays in the no-op state until the next
23
+ * `bun run build`.
24
+ *
25
+ * Configure via env vars:
26
+ * PANO_LICENSE_SERVER prod | dev | https://api.example.com
27
+ * PANO_LICENSE_PUBLIC_KEY explicit base64 / PEM (CI secret); overrides server fetch
28
+ * PANO_LICENSE_REQUIRED "true" / "false"; default = manifest.premium
29
+ * PANO_LICENSE_ISSUER override the expected JWT iss (otherwise derived from server)
30
+ */
31
+ import fs from "fs";
32
+ import path from "path";
33
+ import { execSync } from "node:child_process";
34
+
35
+ const ROOT = process.cwd();
36
+ const MANIFEST_FILE = path.join(ROOT, "manifest.json");
37
+ const PACKAGE_FILE = path.join(ROOT, "package.json");
38
+ const OUTPUT_FILE = path.join(ROOT, "src", "lib", "server", "license-constants.generated.js");
39
+
40
+ const PROD_URL = "https://api.panomc.com";
41
+ const DEV_URL = "https://api-dev.panomc.com";
42
+
43
+ function stripPemAndWhitespace(raw) {
44
+ return raw
45
+ .replace(/-----BEGIN [^-]+-----/g, "")
46
+ .replace(/-----END [^-]+-----/g, "")
47
+ .replace(/\s+/g, "");
48
+ }
49
+
50
+ function resolveServerBaseUrl(server) {
51
+ if (!server) return "";
52
+ const norm = server.trim().toLowerCase();
53
+ if (norm === "dev" || norm === "development" || norm === "staging") return DEV_URL;
54
+ if (norm === "prod" || norm === "production") return PROD_URL;
55
+ return server.trim().replace(/\/$/, "");
56
+ }
57
+
58
+ /**
59
+ * Hostname of a URL with the leading "api." or "api-<label>." stripped, so a custom
60
+ * license server URL maps to the JWT `iss` Pano host would compute via
61
+ * com.panomc.platform.config.PanoConfig.resolvedLicenseJwtIssuer:
62
+ * https://api.example.com → example.com
63
+ * https://api-dev.example.com → dev.example.com
64
+ * http://localhost:8087 → localhost
65
+ * anything malformed/empty → ""
66
+ */
67
+ function hostnameForIssuer(url) {
68
+ try {
69
+ const u = new URL(url);
70
+ const host = u.hostname;
71
+ if (!host) return "";
72
+ const apiPrefix = host.match(/^api\.(.+)$/);
73
+ if (apiPrefix) return apiPrefix[1];
74
+ const apiLabel = host.match(/^api-([^.]+)\.(.+)$/);
75
+ if (apiLabel) return `${apiLabel[1]}.${apiLabel[2]}`;
76
+ return host;
77
+ } catch {
78
+ return "";
79
+ }
80
+ }
81
+
82
+ function issuerHintFor(server, baseUrl) {
83
+ const norm = (server || "").trim().toLowerCase();
84
+ if (norm === "dev" || norm === "development" || norm === "staging") return "dev.panomc.com";
85
+ if (norm === "prod" || norm === "production") return "panomc.com";
86
+ if (baseUrl === DEV_URL) return "dev.panomc.com";
87
+ if (baseUrl === PROD_URL) return "panomc.com";
88
+ // Custom URL: derive the hostname the same way the Pano host would, so a local
89
+ // backend at http://localhost:8087 ends up with iss="localhost", matching what the
90
+ // host stamps into the JWT.
91
+ if (baseUrl) {
92
+ const fromUrl = hostnameForIssuer(baseUrl);
93
+ if (fromUrl) return fromUrl;
94
+ }
95
+ return "";
96
+ }
97
+
98
+ /**
99
+ * Inspect the current git branch and map it to a license server. Returns null when:
100
+ * - we're not in a git repo (or git is missing)
101
+ * - HEAD is detached and no branch can be inferred
102
+ * - the branch name doesn't match any known pattern (caller decides what to do)
103
+ */
104
+ function detectServerFromGitBranch() {
105
+ let branch;
106
+ try {
107
+ // --abbrev-ref returns "HEAD" on detached HEADs. Caller treats null as "unknown".
108
+ branch = execSync("git rev-parse --abbrev-ref HEAD", {
109
+ stdio: ["ignore", "pipe", "ignore"],
110
+ cwd: ROOT,
111
+ })
112
+ .toString()
113
+ .trim();
114
+ } catch {
115
+ return null;
116
+ }
117
+ if (!branch || branch === "HEAD") return null;
118
+ const lower = branch.toLowerCase();
119
+
120
+ if (
121
+ lower === "main" ||
122
+ lower === "master" ||
123
+ lower === "prod" ||
124
+ lower === "production" ||
125
+ lower.startsWith("release/") ||
126
+ lower.startsWith("release-") ||
127
+ lower.startsWith("hotfix/main")
128
+ ) {
129
+ return { server: "prod", baseUrl: PROD_URL, branch };
130
+ }
131
+
132
+ if (
133
+ lower === "dev" ||
134
+ lower === "develop" ||
135
+ lower === "development" ||
136
+ lower === "staging" ||
137
+ lower.startsWith("dev/") ||
138
+ lower.startsWith("develop/") ||
139
+ lower.startsWith("staging/") ||
140
+ lower.startsWith("feature/") ||
141
+ lower.startsWith("feat/") ||
142
+ lower.startsWith("fix/") ||
143
+ lower.startsWith("bugfix/") ||
144
+ lower.startsWith("hotfix/") ||
145
+ lower.startsWith("chore/") ||
146
+ lower.startsWith("refactor/")
147
+ ) {
148
+ return { server: "dev", baseUrl: DEV_URL, branch };
149
+ }
150
+
151
+ return { server: null, baseUrl: null, branch };
152
+ }
153
+
154
+ /**
155
+ * Resolves the final license server choice in priority order. Returns
156
+ * { source, baseUrl, serverKeyword, branch? }
157
+ * where `source` is one of: "explicit-key", "explicit-server", "branch", "none".
158
+ */
159
+ function resolveLicenseServerChoice() {
160
+ const explicitKey = (process.env.PANO_LICENSE_PUBLIC_KEY || "").trim();
161
+ if (explicitKey) {
162
+ return { source: "explicit-key", baseUrl: null, serverKeyword: null };
163
+ }
164
+
165
+ const explicitServer = (process.env.PANO_LICENSE_SERVER || "").trim();
166
+ if (explicitServer) {
167
+ return {
168
+ source: "explicit-server",
169
+ serverKeyword: explicitServer,
170
+ baseUrl: resolveServerBaseUrl(explicitServer),
171
+ };
172
+ }
173
+
174
+ const detected = detectServerFromGitBranch();
175
+ if (detected?.server) {
176
+ return {
177
+ source: "branch",
178
+ serverKeyword: detected.server,
179
+ baseUrl: detected.baseUrl,
180
+ branch: detected.branch,
181
+ };
182
+ }
183
+
184
+ return {
185
+ source: "none",
186
+ serverKeyword: null,
187
+ baseUrl: null,
188
+ branch: detected?.branch ?? null,
189
+ };
190
+ }
191
+
192
+ async function fetchPublicKeyFromServer(baseUrl) {
193
+ const url = `${baseUrl}/platform/api/licenses/public-key`;
194
+ console.log(`[pano-license] Fetching license public key from ${url}...`);
195
+ const response = await fetch(url, {
196
+ headers: { Accept: "application/json" },
197
+ });
198
+ if (!response.ok) {
199
+ throw new Error(
200
+ `License key fetch failed: ${response.status} ${response.statusText} — ` +
201
+ `bring the license server up, drop PANO_LICENSE_SERVER (builds the theme as FREE), ` +
202
+ `or set PANO_LICENSE_PUBLIC_KEY=<base64> manually.`
203
+ );
204
+ }
205
+ const payload = await response.json();
206
+ // The endpoint exposes the key at the root level, but some panomc gateways wrap success
207
+ // responses as { result: "ok", data: { ... } }. Handle both shapes.
208
+ const body = payload?.data ?? payload;
209
+ const key = body?.publicKeyBase64 || body?.publicKey;
210
+ if (!key || typeof key !== "string") {
211
+ throw new Error(
212
+ `License key response missing publicKeyBase64/publicKey: ${JSON.stringify(payload).slice(0, 200)}`
213
+ );
214
+ }
215
+ return stripPemAndWhitespace(key);
216
+ }
217
+
218
+ async function fetchPublicKey(choice) {
219
+ if (choice.source === "explicit-key") {
220
+ return stripPemAndWhitespace(process.env.PANO_LICENSE_PUBLIC_KEY);
221
+ }
222
+ if (choice.baseUrl) {
223
+ return fetchPublicKeyFromServer(choice.baseUrl);
224
+ }
225
+ return "";
226
+ }
227
+
228
+ function readJson(file) {
229
+ return JSON.parse(fs.readFileSync(file, "utf-8"));
230
+ }
231
+
232
+ async function main() {
233
+ const manifest = readJson(MANIFEST_FILE);
234
+ const pkg = readJson(PACKAGE_FILE);
235
+
236
+ // Version resolution priority (the embedded constant MUST match the `ver` claim in the
237
+ // JWT panomc.com mints for this build — otherwise the theme runtime refuses to serve):
238
+ // 1. PANO_THEME_VERSION_OVERRIDE — release workflow passes semantic-release's
239
+ // next-tag here (e.g. "1.0.0-dev.44"). Wins over everything because the manifest
240
+ // source still has the "v{version}" placeholder at this point in the pipeline.
241
+ // 2. manifest.version with "{version}" substituted from package.json (local dev).
242
+ // The leading "v" is always stripped so the constant matches ResourceVersion.tag on
243
+ // the backend, which is stored without it.
244
+ const overrideVersion = (process.env.PANO_THEME_VERSION_OVERRIDE || "").trim();
245
+ const versionRaw = overrideVersion ||
246
+ String(manifest.version || "").replace("{version}", pkg.version);
247
+ const themeVersion = versionRaw.startsWith("v") ? versionRaw.slice(1) : versionRaw;
248
+
249
+ const themeId = manifest.id;
250
+ if (!themeId) throw new Error("manifest.json is missing an `id` field");
251
+ if (!themeVersion) throw new Error("Could not resolve theme version from manifest/package.json");
252
+
253
+ const requiredEnv = (process.env.PANO_LICENSE_REQUIRED ?? "").trim();
254
+ const required = requiredEnv === ""
255
+ ? Boolean(manifest.premium)
256
+ : requiredEnv.toLowerCase() !== "false";
257
+
258
+ let publicKey = "";
259
+ let resolvedSource = "skipped-free-build";
260
+ let resolvedServer = null;
261
+ let detectedBranch = null;
262
+
263
+ if (required) {
264
+ const choice = resolveLicenseServerChoice();
265
+ detectedBranch = choice.branch ?? null;
266
+
267
+ if (choice.source === "none") {
268
+ throw new Error(
269
+ `Theme "${themeId}" is marked premium but the license server could not be resolved.\n` +
270
+ `Tried: PANO_LICENSE_PUBLIC_KEY (unset), PANO_LICENSE_SERVER (unset), git branch ` +
271
+ `auto-detect${detectedBranch ? ` (branch: "${detectedBranch}" did not match prod/dev patterns)` : " (no usable git branch)"}.\n` +
272
+ `Fix: set PANO_LICENSE_SERVER=prod|dev|<url> or PANO_LICENSE_PUBLIC_KEY=<base64>, ` +
273
+ `or build from a recognised branch (main/master/release-* → prod, dev/develop/feat-*/fix-* → dev).`
274
+ );
275
+ }
276
+
277
+ publicKey = await fetchPublicKey(choice);
278
+ if (!publicKey) {
279
+ throw new Error(
280
+ `Theme "${themeId}" is marked premium but the resolved server returned no key.`
281
+ );
282
+ }
283
+ resolvedSource = choice.source;
284
+ resolvedServer = choice.baseUrl || choice.serverKeyword || "(explicit key)";
285
+ }
286
+
287
+ // Derive expected issuer: explicit env > PANO_LICENSE_SERVER (set even when KEY is too)
288
+ // > branch detection > "". Build-time issuer hint is just a default; the Pano host
289
+ // always sets PANO_LICENSE_ISSUER on the bun process from its own config, so this only
290
+ // matters for theme runtimes that boot without the host env (e.g. local debugging).
291
+ const explicitIssuer = (process.env.PANO_LICENSE_ISSUER || "").trim();
292
+ const explicitServerForIssuer = (process.env.PANO_LICENSE_SERVER || "").trim();
293
+ const issuerHint = explicitIssuer || (required
294
+ ? (explicitServerForIssuer
295
+ ? issuerHintFor(explicitServerForIssuer, resolveServerBaseUrl(explicitServerForIssuer))
296
+ : (detectedBranch
297
+ ? issuerHintFor("", resolvedSource === "branch" ? resolvedServer : null)
298
+ : ""))
299
+ : "");
300
+
301
+ fs.mkdirSync(path.dirname(OUTPUT_FILE), { recursive: true });
302
+ // Generated file lives in src/lib/server/ so SvelteKit's adapter-node naturally bundles
303
+ // it into build/ during `vite build`. Never imported from client code (lib/server is
304
+ // server-only in SvelteKit).
305
+ const body = `// AUTO-GENERATED by scripts/license/generate-license-constants.js — DO NOT EDIT.
306
+ // Regenerated on every \`bun run build\` (prebuild hook).
307
+ export const PANO_LICENSE_PUBLIC_KEY_BASE64 = ${JSON.stringify(publicKey)};
308
+ export const PANO_LICENSE_THEME_ID = ${JSON.stringify(themeId)};
309
+ export const PANO_LICENSE_THEME_VERSION = ${JSON.stringify(themeVersion)};
310
+ export const PANO_LICENSE_REQUIRED = ${required ? "true" : "false"};
311
+ export const PANO_LICENSE_ISSUER_HINT = ${JSON.stringify(issuerHint)};
312
+ `;
313
+ fs.writeFileSync(OUTPUT_FILE, body);
314
+
315
+ const sourceLabel = (() => {
316
+ switch (resolvedSource) {
317
+ case "explicit-key": return "explicit PANO_LICENSE_PUBLIC_KEY";
318
+ case "explicit-server": return `explicit PANO_LICENSE_SERVER (${resolvedServer})`;
319
+ case "branch": return `git branch auto-detect: "${detectedBranch}" → ${resolvedServer}`;
320
+ case "skipped-free-build": return "free build — key not required";
321
+ default: return resolvedSource;
322
+ }
323
+ })();
324
+
325
+ console.log(
326
+ `[pano-license] id=${themeId} version=${themeVersion} required=${required} ` +
327
+ `keyEmbedded=${publicKey ? "yes" : "no"} issuerHint=${issuerHint || "(runtime-derived)"} ` +
328
+ `source=${sourceLabel}`
329
+ );
330
+ }
331
+
332
+ main().catch((err) => {
333
+ console.error("[pano-license] generate-license-constants failed:", err.message || err);
334
+ process.exit(1);
335
+ });