@nuvler/cli 0.1.0 → 0.3.0

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 (79) hide show
  1. package/README.md +50 -5
  2. package/dist/api/developer-auth.js +48 -0
  3. package/dist/api/developer-auth.js.map +1 -0
  4. package/dist/api/theme-registry.js +9 -5
  5. package/dist/api/theme-registry.js.map +1 -1
  6. package/dist/commands/auth.js +27 -0
  7. package/dist/commands/auth.js.map +1 -0
  8. package/dist/commands/theme/configure.js +79 -0
  9. package/dist/commands/theme/configure.js.map +1 -0
  10. package/dist/commands/theme/create.js +111 -22
  11. package/dist/commands/theme/create.js.map +1 -1
  12. package/dist/commands/theme/dev.js +8 -12
  13. package/dist/commands/theme/dev.js.map +1 -1
  14. package/dist/commands/theme/publish.js +38 -6
  15. package/dist/commands/theme/publish.js.map +1 -1
  16. package/dist/config/auth.js +40 -0
  17. package/dist/config/auth.js.map +1 -0
  18. package/dist/config/connection-key.js +63 -0
  19. package/dist/config/connection-key.js.map +1 -0
  20. package/dist/config/developer-session.js +25 -0
  21. package/dist/config/developer-session.js.map +1 -0
  22. package/dist/config/project.js +59 -0
  23. package/dist/config/project.js.map +1 -0
  24. package/dist/index.js +84 -18
  25. package/dist/index.js.map +1 -1
  26. package/dist/nuvler.js +592 -138
  27. package/dist/nuvler.js.map +1 -1
  28. package/dist/preview/prepare.js +19 -0
  29. package/dist/preview/prepare.js.map +1 -0
  30. package/dist/templates/nuvler-atelier/README.md +30 -0
  31. package/{templates/starter-theme → dist/templates/nuvler-atelier}/gitignore.template +1 -1
  32. package/dist/templates/nuvler-atelier/nuvler.theme.json +16 -0
  33. package/dist/templates/nuvler-atelier/package.json +29 -0
  34. package/dist/templates/nuvler-atelier/src/definition.tsx +201 -0
  35. package/dist/templates/nuvler-atelier/src/theme.css +278 -0
  36. package/dist/templates/nuvler-atelier/src/theme.tsx +105 -0
  37. package/dist/templates/nuvler-default/README.md +34 -0
  38. package/dist/templates/nuvler-default/gitignore.template +9 -0
  39. package/dist/templates/nuvler-default/nuvler.theme.json +16 -0
  40. package/dist/templates/nuvler-default/package.json +42 -0
  41. package/dist/templates/nuvler-default/scripts/clean-dist.mjs +6 -0
  42. package/dist/templates/nuvler-default/scripts/copy-assets.mjs +12 -0
  43. package/dist/templates/nuvler-default/src/banner-carousel.tsx +24 -0
  44. package/dist/templates/nuvler-default/src/definition.ts +59 -0
  45. package/dist/templates/nuvler-default/src/footer.tsx +7 -0
  46. package/dist/templates/nuvler-default/src/header-interactions.tsx +190 -0
  47. package/dist/templates/nuvler-default/src/header.tsx +14 -0
  48. package/dist/templates/nuvler-default/src/home.tsx +69 -0
  49. package/dist/templates/nuvler-default/src/index.ts +28 -0
  50. package/dist/templates/nuvler-default/src/product-carousel.tsx +12 -0
  51. package/dist/templates/nuvler-default/src/product-detail.tsx +60 -0
  52. package/dist/templates/nuvler-default/src/products.tsx +15 -0
  53. package/dist/templates/nuvler-default/src/shared.tsx +44 -0
  54. package/dist/templates/nuvler-default/src/styles.d.ts +1 -0
  55. package/dist/templates/nuvler-default/src/theme-component.tsx +97 -0
  56. package/dist/templates/nuvler-default/src/theme.css +2934 -0
  57. package/dist/templates/nuvler-default/src/theme.tsx +2 -0
  58. package/dist/templates/nuvler-default/tsconfig.json +10 -0
  59. package/{templates/starter-theme → dist/templates/starter}/README.md +3 -3
  60. package/dist/templates/starter/gitignore.template +9 -0
  61. package/dist/templates/starter/nuvler.theme.json +16 -0
  62. package/{templates/starter-theme → dist/templates/starter}/package.json +2 -2
  63. package/dist/templates/starter/src/styles.d.ts +1 -0
  64. package/dist/templates/starter/tsconfig.json +17 -0
  65. package/dist/theme/artifact.js +1 -0
  66. package/dist/theme/artifact.js.map +1 -1
  67. package/package.json +3 -4
  68. package/preview-host/package.json +1 -1
  69. package/preview-host/src/public-preview-url.d.mts +5 -0
  70. package/preview-host/src/public-preview-url.mjs +50 -0
  71. package/preview-host/vendor/theme-runtime/default-theme.tsx +1 -1
  72. package/preview-host/vite.config.ts +4 -3
  73. package/templates/starter-theme/.env.example +0 -3
  74. package/templates/starter-theme/nuvler.theme.json +0 -10
  75. /package/{templates/starter-theme → dist/templates/nuvler-atelier}/src/styles.d.ts +0 -0
  76. /package/{templates/starter-theme → dist/templates/nuvler-atelier}/tsconfig.json +0 -0
  77. /package/{templates/starter-theme → dist/templates/starter}/src/definition.tsx +0 -0
  78. /package/{templates/starter-theme → dist/templates/starter}/src/theme.css +0 -0
  79. /package/{templates/starter-theme → dist/templates/starter}/src/theme.tsx +0 -0
package/dist/nuvler.js CHANGED
@@ -1,15 +1,17 @@
1
1
  #!/usr/bin/env node
2
2
  import { Command } from "commander";
3
3
  import { existsSync } from "node:fs";
4
- import { access, cp, lstat, mkdir, mkdtemp, readFile, readdir, rename, rm, rmdir, stat, unlink, writeFile } from "node:fs/promises";
4
+ import { access, chmod, cp, lstat, mkdir, mkdtemp, readFile, readdir, rename, rm, rmdir, stat, unlink, writeFile } from "node:fs/promises";
5
5
  import path from "node:path";
6
6
  import { fileURLToPath } from "node:url";
7
7
  import { createHash, randomUUID } from "node:crypto";
8
8
  import { build, normalizePath } from "vite";
9
9
  import { THEME_API_VERSION, THEME_RUNTIME_VERSION, THEME_SCHEMA_VERSION, THEME_SCHEMA_VERSION as THEME_SCHEMA_VERSION$1 } from "@nuvler/theme-sdk";
10
10
  import { satisfies, validRange } from "semver";
11
+ import { createInterface } from "node:readline/promises";
12
+ import { stdin, stdout } from "node:process";
13
+ import os, { tmpdir } from "node:os";
11
14
  import { spawn } from "node:child_process";
12
- import { tmpdir } from "node:os";
13
15
  import { create } from "tar";
14
16
  //#region \0rolldown/runtime.js
15
17
  var __defProp = Object.defineProperty;
@@ -25,23 +27,110 @@ var __exportAll = (all, no_symbols) => {
25
27
  //#endregion
26
28
  //#region src/commands/theme/create.ts
27
29
  var THEME_ID_PATTERN = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
28
- var TEMPLATE_FILES = [
29
- "package.json",
30
- "README.md",
31
- "nuvler.theme.json",
32
- "src/definition.tsx",
33
- "src/theme.css"
30
+ var NEW_THEME_VERSION = "0.1.0";
31
+ var CLI_VERSION_RANGE = "^0.3.0";
32
+ var SDK_VERSION_RANGE = "^1.1.0";
33
+ var THEME_TEMPLATES = [
34
+ {
35
+ id: "starter",
36
+ name: "Starter",
37
+ description: "Base enxuta para construir um tema do zero"
38
+ },
39
+ {
40
+ id: "nuvler-default",
41
+ name: "Nuvler Default",
42
+ description: "Tema oficial completo para lojas e catálogos"
43
+ },
44
+ {
45
+ id: "nuvler-atelier",
46
+ name: "Nuvler Atelier",
47
+ description: "Tema editorial com visual premium"
48
+ }
34
49
  ];
50
+ var STANDALONE_TSCONFIG = {
51
+ compilerOptions: {
52
+ target: "ES2022",
53
+ module: "NodeNext",
54
+ moduleResolution: "NodeNext",
55
+ strict: true,
56
+ esModuleInterop: true,
57
+ skipLibCheck: true,
58
+ declaration: true,
59
+ sourceMap: true,
60
+ jsx: "react-jsx",
61
+ resolveJsonModule: true,
62
+ rootDir: ".",
63
+ outDir: "dist"
64
+ },
65
+ include: ["src/**/*", "nuvler.theme.json"]
66
+ };
35
67
  function defaultThemeName(id) {
36
68
  return id.split("-").filter(Boolean).map((part) => `${part[0]?.toUpperCase() ?? ""}${part.slice(1)}`).join(" ");
37
69
  }
38
- function resolveTemplateDirectory() {
70
+ function resolveTemplateId(input) {
71
+ const template = input?.trim().toLowerCase() || "starter";
72
+ if (THEME_TEMPLATES.some((candidate) => candidate.id === template)) return template;
73
+ throw new Error(`Template desconhecido: ${input}. Opções: ${THEME_TEMPLATES.map(({ id }) => id).join(", ")}.`);
74
+ }
75
+ function resolveTemplateDirectory(template) {
39
76
  const configured = process.env.NUVLER_THEME_TEMPLATE_DIR?.trim();
40
- if (configured) return path.resolve(configured);
77
+ if (configured) {
78
+ const root = path.resolve(configured);
79
+ const selected = path.join(root, template);
80
+ if (existsSync(selected)) return selected;
81
+ if (template === "starter") return root;
82
+ }
41
83
  const currentDirectory = path.dirname(fileURLToPath(import.meta.url));
42
- const candidates = [path.resolve(currentDirectory, "../templates/starter-theme"), path.resolve(currentDirectory, "../../../templates/starter-theme")];
84
+ const candidates = [path.resolve(currentDirectory, "templates", template), path.resolve(currentDirectory, "../../templates", template)];
43
85
  return candidates.find((directory) => existsSync(directory)) ?? candidates[0];
44
86
  }
87
+ async function customizeTemplate(directory, id, name, template) {
88
+ const manifestFile = path.join(directory, "nuvler.theme.json");
89
+ const manifest = JSON.parse(await readFile(manifestFile, "utf8"));
90
+ manifest.id = id;
91
+ manifest.name = name;
92
+ manifest.version = NEW_THEME_VERSION;
93
+ manifest.presentation = {
94
+ ...manifest.presentation,
95
+ description: `Tema ${name} criado a partir do template ${template}.`,
96
+ templateId: template
97
+ };
98
+ await writeFile(manifestFile, `${JSON.stringify(manifest, null, 2)}\n`, "utf8");
99
+ const packageFile = path.join(directory, "package.json");
100
+ const packageMetadata = JSON.parse(await readFile(packageFile, "utf8"));
101
+ packageMetadata.name = `nuvler-theme-${id}`;
102
+ packageMetadata.version = NEW_THEME_VERSION;
103
+ packageMetadata.description = `Tema Nuvler ${name}`;
104
+ packageMetadata.private = true;
105
+ packageMetadata.scripts = {
106
+ dev: "nuvler theme dev --theme .",
107
+ validate: "nuvler theme validate --theme .",
108
+ build: "nuvler theme build --theme .",
109
+ pack: "nuvler theme pack --theme .",
110
+ publish: "nuvler theme publish --theme .",
111
+ typecheck: "tsc -p tsconfig.json --noEmit"
112
+ };
113
+ packageMetadata.dependencies = {
114
+ ...packageMetadata.dependencies,
115
+ "@nuvler/theme-sdk": SDK_VERSION_RANGE
116
+ };
117
+ packageMetadata.devDependencies = {
118
+ ...packageMetadata.devDependencies,
119
+ "@nuvler/cli": CLI_VERSION_RANGE,
120
+ "@types/react": "^19.0.0",
121
+ react: "^19.0.0",
122
+ typescript: "^5.9.0"
123
+ };
124
+ await writeFile(packageFile, `${JSON.stringify(packageMetadata, null, 2)}\n`, "utf8");
125
+ await writeFile(path.join(directory, "tsconfig.json"), `${JSON.stringify(STANDALONE_TSCONFIG, null, 2)}\n`, "utf8");
126
+ if (template === "starter") {
127
+ const definitionFile = path.join(directory, "src/definition.tsx");
128
+ const definition = await readFile(definitionFile, "utf8");
129
+ await writeFile(definitionFile, definition.replaceAll("__NUVLER_THEME_ID__", id).replaceAll("__NUVLER_THEME_NAME__", name), "utf8");
130
+ }
131
+ const readme = `# ${name}\n\nTema Nuvler criado a partir do template \`${template}\`.\n\n## Desenvolvimento\n\n\`\`\`bash\nnpm install\nnuvler theme configure --key CHAVE_COPIADA_DO_PAINEL\nnpm run validate\nnpm run dev\n\`\`\`\n\nA chave configura a API e a autenticação global. A seleção local de tenant fica em \`.nuvler/config.json\`, ignorada pelo Git e sem segredos. Não é necessário criar ou editar \`.env\`.\n\nEdite \`src/\` e \`nuvler.theme.json\`. Não edite \`dist\` nem \`artifacts\`, pois essas pastas são geradas pela CLI.\n\n## Build e publicação\n\n\`\`\`bash\nnpm run typecheck\nnpm run build\nnpm run pack\nnpm run publish\n\`\`\`\n\nO artefato será gerado em \`artifacts/${id}-${NEW_THEME_VERSION}.nuvler-theme.tgz\`.\n`;
132
+ await writeFile(path.join(directory, "README.md"), readme, "utf8");
133
+ }
45
134
  async function ensureEmptyTarget(directory) {
46
135
  try {
47
136
  if (!(await stat(directory)).isDirectory()) throw new Error(`O destino já existe e não é uma pasta: ${directory}`);
@@ -54,9 +143,10 @@ async function themeCreate(options) {
54
143
  const directory = path.resolve(options.directory);
55
144
  const id = (options.id?.trim() || path.basename(directory)).toLowerCase();
56
145
  const name = options.name?.trim() || defaultThemeName(id);
146
+ const template = resolveTemplateId(options.template);
57
147
  if (!THEME_ID_PATTERN.test(id)) throw new Error("O id do tema deve estar em kebab-case, por exemplo: tema-raja.");
58
148
  if (name.length < 2 || name.length > 120) throw new Error("O nome do tema deve ter entre 2 e 120 caracteres.");
59
- const templateDirectory = resolveTemplateDirectory();
149
+ const templateDirectory = resolveTemplateDirectory(template);
60
150
  try {
61
151
  if (!(await stat(templateDirectory)).isDirectory()) throw new Error();
62
152
  } catch {
@@ -69,19 +159,16 @@ async function themeCreate(options) {
69
159
  force: false
70
160
  });
71
161
  await rename(path.join(directory, "gitignore.template"), path.join(directory, ".gitignore"));
72
- for (const relativeFile of TEMPLATE_FILES) {
73
- const file = path.join(directory, relativeFile);
74
- const content = await readFile(file, "utf8");
75
- await writeFile(file, content.replaceAll("__NUVLER_THEME_ID__", id).replaceAll("__NUVLER_THEME_NAME__", name), "utf8");
76
- }
162
+ await customizeTemplate(directory, id, name, template);
77
163
  console.log("");
78
164
  console.log(`✓ Tema criado: ${name} (${id})`);
165
+ console.log(`✓ Template: ${template}`);
79
166
  console.log(`✓ Pasta: ${directory}`);
80
167
  console.log("");
81
168
  console.log("Próximos passos:");
82
169
  console.log(` cd ${path.relative(process.cwd(), directory) || "."}`);
83
170
  console.log(" npm install");
84
- console.log(" cp .env.example .env");
171
+ console.log(" nuvler theme configure --key CHAVE_COPIADA_DO_PAINEL");
85
172
  console.log(" npm run validate");
86
173
  console.log(" npm run dev");
87
174
  console.log(" npm run build");
@@ -121,7 +208,8 @@ function createArtifactManifest(project, build) {
121
208
  runtimeVersion: project.manifest.runtimeVersion,
122
209
  sdkVersion: project.manifest.sdkVersion,
123
210
  entry: "./theme.js",
124
- style: build.stylePath ? "./theme.css" : void 0
211
+ style: build.stylePath ? "./theme.css" : void 0,
212
+ presentation: project.manifest.presentation
125
213
  };
126
214
  }
127
215
  //#endregion
@@ -6475,6 +6563,20 @@ config(en_default());
6475
6563
  //#endregion
6476
6564
  //#region ../theme-schema/dist/index.js
6477
6565
  var relativeThemeFileSchema = string$1().trim().min(1).max(240).refine((value) => !value.startsWith("/") && !value.startsWith("\\"), { message: "Use um caminho relativo à pasta do tema" }).refine((value) => !value.split(/[\\/]+/).includes(".."), { message: "O caminho não pode sair da pasta do tema" });
6566
+ var ThemePresentationSchema = object({
6567
+ description: string$1().trim().min(1).max(500),
6568
+ templateId: string$1().trim().min(1).max(80).optional(),
6569
+ colors: object({
6570
+ primary: string$1().regex(/^#[0-9a-f]{6}$/i),
6571
+ secondary: string$1().regex(/^#[0-9a-f]{6}$/i),
6572
+ background: string$1().regex(/^#[0-9a-f]{6}$/i),
6573
+ text: string$1().regex(/^#[0-9a-f]{6}$/i)
6574
+ }).strict(),
6575
+ layout: object({
6576
+ containerWidth: number$1().int().min(960).max(1600),
6577
+ borderRadius: number$1().int().min(0).max(32)
6578
+ }).strict()
6579
+ }).strict();
6478
6580
  var ThemeManifestSchema = object({
6479
6581
  schemaVersion: literal(THEME_SCHEMA_VERSION),
6480
6582
  id: string$1().trim().min(2).max(80).regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/, "Use um identificador em kebab-case"),
@@ -6483,7 +6585,8 @@ var ThemeManifestSchema = object({
6483
6585
  runtimeVersion: literal(THEME_RUNTIME_VERSION),
6484
6586
  sdkVersion: string$1().trim().min(1).max(80),
6485
6587
  entry: relativeThemeFileSchema.refine((value) => /\.(?:[cm]?[jt]sx?)$/i.test(value), { message: "A entrada deve ser um arquivo JavaScript ou TypeScript" }),
6486
- styles: array(relativeThemeFileSchema.refine((value) => /\.css$/i.test(value), { message: "Os estilos do manifesto devem ser arquivos CSS" })).max(10).optional()
6588
+ styles: array(relativeThemeFileSchema.refine((value) => /\.css$/i.test(value), { message: "Os estilos do manifesto devem ser arquivos CSS" })).max(10).optional(),
6589
+ presentation: ThemePresentationSchema.optional()
6487
6590
  }).strict();
6488
6591
  var nullableStringSchema = string$1().nullable();
6489
6592
  var hexColorSchema = string$1().regex(/^#[0-9a-f]{6}$/i, "Use uma cor hexadecimal no formato #RRGGBB");
@@ -6804,6 +6907,341 @@ async function themeBuild(options) {
6804
6907
  return output;
6805
6908
  }
6806
6909
  //#endregion
6910
+ //#region src/api/developer-auth.ts
6911
+ async function fetchDeveloperProfile(apiUrl, token) {
6912
+ let response;
6913
+ try {
6914
+ response = await fetch(`${apiUrl.replace(/\/+$/, "")}/developer/me`, { headers: {
6915
+ accept: "application/json",
6916
+ authorization: `Bearer ${token}`
6917
+ } });
6918
+ } catch (error) {
6919
+ throw new Error(`API Nuvler indisponível em ${apiUrl}.`, { cause: error });
6920
+ }
6921
+ const payload = await response.json().catch(() => null);
6922
+ if (!response.ok) {
6923
+ if (response.status === 401) {
6924
+ const code = payload && "code" in payload ? payload.code : void 0;
6925
+ throw new Error(`O developer token ${code === "DEVELOPER_TOKEN_EXPIRED" ? "expirou" : code === "DEVELOPER_TOKEN_REVOKED" ? "foi revogado" : "é inválido"}. Execute nuvler auth login novamente.`);
6926
+ }
6927
+ if (response.status === 403) throw new Error("O developer autenticado está inativo ou não possui acesso.");
6928
+ const error = payload && "error" in payload ? payload.error : void 0;
6929
+ throw new Error(error || `Falha ao validar token: HTTP ${response.status}`);
6930
+ }
6931
+ const profile = payload;
6932
+ if (!profile || typeof profile.developerId !== "string" || typeof profile.userId !== "string" || !Array.isArray(profile.scopes) || !profile.scopes.every((scope) => typeof scope === "string") || !Array.isArray(profile.tenants) || !profile.tenants.every((tenant) => tenant && typeof tenant.id === "string" && typeof tenant.name === "string" && typeof tenant.slug === "string")) throw new Error("A API retornou um perfil de developer inválido.");
6933
+ return {
6934
+ developerId: profile.developerId,
6935
+ userId: profile.userId,
6936
+ scopes: profile.scopes,
6937
+ tenants: profile.tenants.map(({ id, name, slug }) => ({
6938
+ id,
6939
+ name,
6940
+ slug
6941
+ }))
6942
+ };
6943
+ }
6944
+ //#endregion
6945
+ //#region src/config/auth.ts
6946
+ function authConfigDirectory() {
6947
+ const override = process.env.NUVLER_CONFIG_DIR?.trim();
6948
+ if (override) return path.resolve(override);
6949
+ const xdg = process.env.XDG_CONFIG_HOME?.trim();
6950
+ return xdg ? path.join(xdg, "nuvler") : path.join(os.homedir(), ".config", "nuvler");
6951
+ }
6952
+ function configFile$1() {
6953
+ return path.join(authConfigDirectory(), "auth.json");
6954
+ }
6955
+ async function readAuthConfig() {
6956
+ try {
6957
+ const parsed = JSON.parse(await readFile(configFile$1(), "utf8"));
6958
+ return typeof parsed.apiUrl === "string" && typeof parsed.token === "string" ? {
6959
+ apiUrl: parsed.apiUrl,
6960
+ token: parsed.token
6961
+ } : null;
6962
+ } catch (error) {
6963
+ if (error.code === "ENOENT") return null;
6964
+ throw error;
6965
+ }
6966
+ }
6967
+ async function writeAuthConfig(config) {
6968
+ const directory = authConfigDirectory();
6969
+ const target = configFile$1();
6970
+ const temporary = path.join(directory, `auth.${process.pid}.tmp`);
6971
+ await mkdir(directory, {
6972
+ recursive: true,
6973
+ mode: 448
6974
+ });
6975
+ await chmod(directory, 448);
6976
+ await writeFile(temporary, `${JSON.stringify(config, null, 2)}\n`, { mode: 384 });
6977
+ await rename(temporary, target);
6978
+ await chmod(target, 384);
6979
+ }
6980
+ async function clearAuthConfig() {
6981
+ await rm(configFile$1(), { force: true });
6982
+ }
6983
+ //#endregion
6984
+ //#region src/config/connection-key.ts
6985
+ var CONNECTION_KEY_PREFIX = "nuvler_connect_";
6986
+ var OFFICIAL_API_ORIGIN = "https://web-max-setedigital.datavaz.com";
6987
+ var LOOPBACK_HOSTS = /* @__PURE__ */ new Set([
6988
+ "localhost",
6989
+ "127.0.0.1",
6990
+ "[::1]"
6991
+ ]);
6992
+ function nonEmptyString$1(value) {
6993
+ return typeof value === "string" && value.trim().length > 0;
6994
+ }
6995
+ function trustedApiUrl(value) {
6996
+ let url;
6997
+ try {
6998
+ url = new URL(value);
6999
+ } catch (error) {
7000
+ throw new Error("A chave contém uma API URL inválida.", { cause: error });
7001
+ }
7002
+ const path = url.pathname.replace(/\/+$/, "") || "/";
7003
+ const official = url.origin === OFFICIAL_API_ORIGIN && path === "/api";
7004
+ const local = LOOPBACK_HOSTS.has(url.hostname) && (url.protocol === "http:" || url.protocol === "https:") && path === "/api";
7005
+ if (!official && !local) throw new Error(`A chave aponta para uma API não confiável: ${url.origin}. Use ${OFFICIAL_API_ORIGIN}/api.`);
7006
+ if (official && url.protocol !== "https:") throw new Error("A API oficial da Nuvler deve usar HTTPS.");
7007
+ return `${url.origin}/api`;
7008
+ }
7009
+ function parseDeveloperConnectionKey(value) {
7010
+ const key = value.trim();
7011
+ if (!key.startsWith(CONNECTION_KEY_PREFIX)) throw new Error("Chave de conexão Nuvler inválida.");
7012
+ let parsed;
7013
+ try {
7014
+ parsed = JSON.parse(Buffer.from(key.slice(CONNECTION_KEY_PREFIX.length), "base64url").toString("utf8"));
7015
+ } catch (error) {
7016
+ throw new Error("Chave de conexão Nuvler inválida.", { cause: error });
7017
+ }
7018
+ const candidate = parsed;
7019
+ if (!candidate || candidate.version !== 1 || !nonEmptyString$1(candidate.apiUrl) || !nonEmptyString$1(candidate.token) || !candidate.tenant || !nonEmptyString$1(candidate.tenant.id) || !nonEmptyString$1(candidate.tenant.slug) || !nonEmptyString$1(candidate.tenant.name)) throw new Error("Chave de conexão Nuvler inválida.");
7020
+ return {
7021
+ version: 1,
7022
+ apiUrl: trustedApiUrl(candidate.apiUrl),
7023
+ token: candidate.token,
7024
+ tenant: {
7025
+ id: candidate.tenant.id,
7026
+ slug: candidate.tenant.slug,
7027
+ name: candidate.tenant.name
7028
+ }
7029
+ };
7030
+ }
7031
+ //#endregion
7032
+ //#region src/config/developer-session.ts
7033
+ async function loadDeveloperSession(overrides = {}) {
7034
+ const saved = await readAuthConfig();
7035
+ const apiUrl = overrides.apiUrl?.trim() || saved?.apiUrl;
7036
+ const token = overrides.token?.trim() || saved?.token;
7037
+ if (!apiUrl || !token) throw new Error("Developer não autenticado. Execute nuvler theme configure --key CHAVE na pasta do tema.");
7038
+ return {
7039
+ apiUrl,
7040
+ token,
7041
+ profile: await fetchDeveloperProfile(apiUrl, token)
7042
+ };
7043
+ }
7044
+ function requireAuthorizedTenant(profile, identifier) {
7045
+ const normalized = identifier.trim();
7046
+ const tenant = profile.tenants.find(({ id, slug }) => id === normalized || slug === normalized);
7047
+ if (!tenant) throw new Error(`Tenant "${identifier}" não está autorizado para o developer autenticado. Execute nuvler theme configure novamente.`);
7048
+ return tenant;
7049
+ }
7050
+ //#endregion
7051
+ //#region src/config/project.ts
7052
+ var THEME_PROJECT_CONFIG_DIRECTORY = ".nuvler";
7053
+ var THEME_PROJECT_CONFIG_FILE = "config.json";
7054
+ function configFile(themeDirectory) {
7055
+ return path.join(path.resolve(themeDirectory), THEME_PROJECT_CONFIG_DIRECTORY, THEME_PROJECT_CONFIG_FILE);
7056
+ }
7057
+ function nonEmptyString(value) {
7058
+ return typeof value === "string" && value.trim().length > 0;
7059
+ }
7060
+ function parseProjectConfig(value) {
7061
+ if (!value || typeof value !== "object") throw new Error("Configuração local do tema inválida. Execute nuvler theme configure novamente.");
7062
+ const candidate = value;
7063
+ if (candidate.schemaVersion !== 1 || !candidate.tenant || !nonEmptyString(candidate.tenant.id) || !nonEmptyString(candidate.tenant.slug) || !nonEmptyString(candidate.tenant.name)) throw new Error("Configuração local do tema inválida. Execute nuvler theme configure novamente.");
7064
+ return {
7065
+ schemaVersion: 1,
7066
+ tenant: {
7067
+ id: candidate.tenant.id,
7068
+ slug: candidate.tenant.slug,
7069
+ name: candidate.tenant.name
7070
+ }
7071
+ };
7072
+ }
7073
+ async function readThemeProjectConfig(themeDirectory) {
7074
+ try {
7075
+ return parseProjectConfig(JSON.parse(await readFile(configFile(themeDirectory), "utf8")));
7076
+ } catch (error) {
7077
+ if (error.code === "ENOENT") return null;
7078
+ if (error instanceof SyntaxError) throw new Error("Configuração local do tema inválida. Execute nuvler theme configure novamente.", { cause: error });
7079
+ throw error;
7080
+ }
7081
+ }
7082
+ async function writeThemeProjectConfig(themeDirectory, config) {
7083
+ const parsed = parseProjectConfig(config);
7084
+ const directory = path.join(path.resolve(themeDirectory), THEME_PROJECT_CONFIG_DIRECTORY);
7085
+ const target = configFile(themeDirectory);
7086
+ const temporary = path.join(directory, `config.${process.pid}.tmp`);
7087
+ await mkdir(directory, {
7088
+ recursive: true,
7089
+ mode: 493
7090
+ });
7091
+ await writeFile(temporary, `${JSON.stringify(parsed, null, 2)}\n`, {
7092
+ encoding: "utf8",
7093
+ mode: 420
7094
+ });
7095
+ await rename(temporary, target);
7096
+ }
7097
+ //#endregion
7098
+ //#region src/commands/theme/configure.ts
7099
+ async function selectTenant(tenants, requested) {
7100
+ if (!tenants.length) throw new Error("O developer autenticado não possui tenants autorizados.");
7101
+ if (requested?.trim()) return requireAuthorizedTenant({
7102
+ developerId: "",
7103
+ userId: "",
7104
+ scopes: [],
7105
+ tenants
7106
+ }, requested);
7107
+ if (tenants.length === 1) return tenants[0];
7108
+ if (!stdin.isTTY || !stdout.isTTY) throw new Error("Mais de um tenant disponível. Informe --tenant <slug-ou-id>. Opções: " + tenants.map(({ slug }) => slug).join(", "));
7109
+ console.log("Tenants disponíveis:");
7110
+ tenants.forEach((tenant, index) => {
7111
+ console.log(` ${index + 1}. ${tenant.name} (${tenant.slug})`);
7112
+ });
7113
+ const prompt = createInterface({
7114
+ input: stdin,
7115
+ output: stdout
7116
+ });
7117
+ try {
7118
+ const answer = await prompt.question("Selecione o tenant: ");
7119
+ const index = Number(answer) - 1;
7120
+ if (!Number.isInteger(index) || !tenants[index]) throw new Error("Seleção de tenant inválida.");
7121
+ return tenants[index];
7122
+ } finally {
7123
+ prompt.close();
7124
+ }
7125
+ }
7126
+ async function themeConfigure(options) {
7127
+ const project = await loadThemeProject(options.themeDirectory);
7128
+ const connection = options.key?.trim() ? parseDeveloperConnectionKey(options.key) : null;
7129
+ const session = connection ? {
7130
+ apiUrl: connection.apiUrl,
7131
+ token: connection.token,
7132
+ profile: await fetchDeveloperProfile(connection.apiUrl, connection.token)
7133
+ } : await loadDeveloperSession();
7134
+ if (!session.profile.scopes.includes("themes:publish")) throw new Error("A chave não possui permissão para publicar temas.");
7135
+ const tenant = await selectTenant(session.profile.tenants, options.tenant || connection?.tenant.id);
7136
+ if (connection && tenant.slug !== connection.tenant.slug) throw new Error("A chave retornou um tenant diferente do tenant autorizado pela API.");
7137
+ if (connection) await writeAuthConfig({
7138
+ apiUrl: session.apiUrl,
7139
+ token: session.token
7140
+ });
7141
+ await writeThemeProjectConfig(project.directory, {
7142
+ schemaVersion: 1,
7143
+ tenant: {
7144
+ id: tenant.id,
7145
+ slug: tenant.slug,
7146
+ name: tenant.name
7147
+ }
7148
+ });
7149
+ console.log("");
7150
+ console.log(`✓ Developer: ${session.profile.developerId}`);
7151
+ console.log(`✓ Tenant: ${tenant.name} (${tenant.slug})`);
7152
+ console.log(`✓ API: ${session.apiUrl}`);
7153
+ if (connection) console.log("✓ Chave validada e autenticação global configurada");
7154
+ console.log("✓ Projeto configurado em .nuvler/config.json");
7155
+ console.log("");
7156
+ }
7157
+ //#endregion
7158
+ //#region src/preview/launcher.ts
7159
+ async function resolvePreviewHost() {
7160
+ const configured = process.env.NUVLER_PREVIEW_HOST_DIR?.trim();
7161
+ const currentDirectory = path.dirname(fileURLToPath(import.meta.url));
7162
+ const candidates = configured ? [path.resolve(configured)] : [
7163
+ path.resolve(currentDirectory, "../preview-host"),
7164
+ path.resolve(currentDirectory, "../../preview-host"),
7165
+ path.resolve(currentDirectory, "../../../apps/preview-host"),
7166
+ path.resolve(currentDirectory, "../../../../apps/preview-host")
7167
+ ];
7168
+ for (const directory of candidates) try {
7169
+ await access(path.join(directory, "package.json"));
7170
+ return directory;
7171
+ } catch {}
7172
+ throw new Error("Preview host não encontrado no package da CLI nem no monorepo. Reinstale @nuvler/cli ou defina NUVLER_PREVIEW_HOST_DIR.");
7173
+ }
7174
+ async function removeContextFile(directory, file) {
7175
+ await unlink(file).catch(() => void 0);
7176
+ await rmdir(directory).catch(() => void 0);
7177
+ }
7178
+ async function runLocalPreview(contextFile, project, apiUrl, store, port) {
7179
+ const previewHost = await resolvePreviewHost();
7180
+ return new Promise((resolve, reject) => {
7181
+ const child = spawn("npm", [
7182
+ "run",
7183
+ "dev",
7184
+ "--",
7185
+ "--host",
7186
+ "127.0.0.1",
7187
+ "--port",
7188
+ String(port),
7189
+ "--strictPort"
7190
+ ], {
7191
+ cwd: previewHost,
7192
+ stdio: "inherit",
7193
+ shell: false,
7194
+ env: {
7195
+ ...process.env,
7196
+ NUVLER_THEME_CONTEXT_FILE: contextFile,
7197
+ NUVLER_THEME_DIRECTORY: project.directory,
7198
+ NUVLER_THEME_ENTRY: project.entryPath,
7199
+ NUVLER_THEME_STYLES: JSON.stringify(project.stylePaths),
7200
+ NUVLER_API_URL: apiUrl,
7201
+ NUVLER_STORE_SLUG: store
7202
+ }
7203
+ });
7204
+ let interrupted = false;
7205
+ const shutdown = (signal) => {
7206
+ interrupted = true;
7207
+ if (!child.killed) child.kill(signal);
7208
+ };
7209
+ const onSigint = () => shutdown("SIGINT");
7210
+ const onSigterm = () => shutdown("SIGTERM");
7211
+ const removeSignalHandlers = () => {
7212
+ process.off("SIGINT", onSigint);
7213
+ process.off("SIGTERM", onSigterm);
7214
+ };
7215
+ process.once("SIGINT", onSigint);
7216
+ process.once("SIGTERM", onSigterm);
7217
+ child.once("error", (error) => {
7218
+ removeSignalHandlers();
7219
+ reject(new Error("Não foi possível iniciar o preview.", { cause: error }));
7220
+ });
7221
+ child.once("exit", (code, signal) => {
7222
+ removeSignalHandlers();
7223
+ if (interrupted || signal || code === 0) {
7224
+ resolve();
7225
+ return;
7226
+ }
7227
+ reject(/* @__PURE__ */ new Error(`O preview foi encerrado com código ${code ?? "desconhecido"}.`));
7228
+ });
7229
+ });
7230
+ }
7231
+ async function launchPreview(context, project, options) {
7232
+ const directory = await mkdtemp(path.join(tmpdir(), "nuvler-theme-"));
7233
+ const contextFile = path.join(directory, "theme-context.json");
7234
+ try {
7235
+ await writeFile(contextFile, JSON.stringify(context, null, 2), {
7236
+ encoding: "utf8",
7237
+ mode: 384
7238
+ });
7239
+ await runLocalPreview(contextFile, project, options.apiUrl, options.store, options.port);
7240
+ } finally {
7241
+ await removeContextFile(directory, contextFile);
7242
+ }
7243
+ }
7244
+ //#endregion
6807
7245
  //#region src/api/client.ts
6808
7246
  var PublicApiError = class extends Error {
6809
7247
  endpoint;
@@ -7055,91 +7493,24 @@ async function loadThemeContext({ store, apiUrl }) {
7055
7493
  return result.data;
7056
7494
  }
7057
7495
  //#endregion
7058
- //#region src/preview/launcher.ts
7059
- async function resolvePreviewHost() {
7060
- const configured = process.env.NUVLER_PREVIEW_HOST_DIR?.trim();
7061
- const currentDirectory = path.dirname(fileURLToPath(import.meta.url));
7062
- const candidates = configured ? [path.resolve(configured)] : [
7063
- path.resolve(currentDirectory, "../preview-host"),
7064
- path.resolve(currentDirectory, "../../preview-host"),
7065
- path.resolve(currentDirectory, "../../../apps/preview-host"),
7066
- path.resolve(currentDirectory, "../../../../apps/preview-host")
7067
- ];
7068
- for (const directory of candidates) try {
7069
- await access(path.join(directory, "package.json"));
7070
- return directory;
7071
- } catch {}
7072
- throw new Error("Preview host não encontrado no package da CLI nem no monorepo. Reinstale @nuvler/cli ou defina NUVLER_PREVIEW_HOST_DIR.");
7073
- }
7074
- async function removeContextFile(directory, file) {
7075
- await unlink(file).catch(() => void 0);
7076
- await rmdir(directory).catch(() => void 0);
7077
- }
7078
- async function runLocalPreview(contextFile, project, apiUrl, store, port) {
7079
- const previewHost = await resolvePreviewHost();
7080
- return new Promise((resolve, reject) => {
7081
- const child = spawn("npm", [
7082
- "run",
7083
- "dev",
7084
- "--",
7085
- "--host",
7086
- "127.0.0.1",
7087
- "--port",
7088
- String(port),
7089
- "--strictPort"
7090
- ], {
7091
- cwd: previewHost,
7092
- stdio: "inherit",
7093
- shell: false,
7094
- env: {
7095
- ...process.env,
7096
- NUVLER_THEME_CONTEXT_FILE: contextFile,
7097
- NUVLER_THEME_DIRECTORY: project.directory,
7098
- NUVLER_THEME_ENTRY: project.entryPath,
7099
- NUVLER_THEME_STYLES: JSON.stringify(project.stylePaths),
7100
- NUVLER_API_URL: apiUrl,
7101
- NUVLER_STORE_SLUG: store
7102
- }
7103
- });
7104
- let interrupted = false;
7105
- const shutdown = (signal) => {
7106
- interrupted = true;
7107
- if (!child.killed) child.kill(signal);
7108
- };
7109
- const onSigint = () => shutdown("SIGINT");
7110
- const onSigterm = () => shutdown("SIGTERM");
7111
- const removeSignalHandlers = () => {
7112
- process.off("SIGINT", onSigint);
7113
- process.off("SIGTERM", onSigterm);
7114
- };
7115
- process.once("SIGINT", onSigint);
7116
- process.once("SIGTERM", onSigterm);
7117
- child.once("error", (error) => {
7118
- removeSignalHandlers();
7119
- reject(new Error("Não foi possível iniciar o preview.", { cause: error }));
7120
- });
7121
- child.once("exit", (code, signal) => {
7122
- removeSignalHandlers();
7123
- if (interrupted || signal || code === 0) {
7124
- resolve();
7125
- return;
7126
- }
7127
- reject(/* @__PURE__ */ new Error(`O preview foi encerrado com código ${code ?? "desconhecido"}.`));
7128
- });
7496
+ //#region src/preview/prepare.ts
7497
+ async function prepareThemePreview(options) {
7498
+ const project = await loadThemeProject(options.themeDirectory);
7499
+ const configured = await readThemeProjectConfig(project.directory);
7500
+ if (!configured && !options.store?.trim()) throw new Error("Projeto não configurado. Execute nuvler theme configure.");
7501
+ const session = await loadDeveloperSession({ apiUrl: options.apiUrl });
7502
+ const tenant = requireAuthorizedTenant(session.profile, options.store?.trim() || configured.tenant.id);
7503
+ const context = await loadThemeContext({
7504
+ store: tenant.slug,
7505
+ apiUrl: session.apiUrl
7129
7506
  });
7130
- }
7131
- async function launchPreview(context, project, options) {
7132
- const directory = await mkdtemp(path.join(tmpdir(), "nuvler-theme-"));
7133
- const contextFile = path.join(directory, "theme-context.json");
7134
- try {
7135
- await writeFile(contextFile, JSON.stringify(context, null, 2), {
7136
- encoding: "utf8",
7137
- mode: 384
7138
- });
7139
- await runLocalPreview(contextFile, project, options.apiUrl, options.store, options.port);
7140
- } finally {
7141
- await removeContextFile(directory, contextFile);
7142
- }
7507
+ if (context.store.slug !== tenant.slug) throw new Error(`A API retornou contexto do tenant "${context.store.slug}" para "${tenant.slug}".`);
7508
+ return {
7509
+ project,
7510
+ context,
7511
+ apiUrl: session.apiUrl,
7512
+ tenant
7513
+ };
7143
7514
  }
7144
7515
  //#endregion
7145
7516
  //#region src/commands/theme/dev.ts
@@ -7147,22 +7518,20 @@ function countCategories(categories) {
7147
7518
  return categories.reduce((total, category) => total + 1 + countCategories(category.children), 0);
7148
7519
  }
7149
7520
  async function themeDev(options) {
7150
- const store = options.store?.trim() || process.env.NUVLER_STORE_SLUG?.trim();
7151
- const apiUrl = options.apiUrl?.trim() || process.env.NUVLER_API_URL?.trim();
7152
- if (!store) throw new Error("Informe a loja usando --store ou defina NUVLER_STORE_SLUG.");
7153
- if (!apiUrl) throw new Error("Informe a API usando --api-url ou defina NUVLER_API_URL.");
7154
- const project = await loadThemeProject(options.themeDirectory);
7521
+ const { project, context, apiUrl, tenant } = await prepareThemePreview({
7522
+ themeDirectory: options.themeDirectory,
7523
+ store: options.store,
7524
+ apiUrl: options.apiUrl
7525
+ });
7526
+ const store = tenant.slug;
7155
7527
  console.log("");
7156
7528
  console.log("Nuvler Theme Development");
7157
7529
  console.log("");
7158
7530
  console.log(`Tema: ${project.manifest.name} v${project.manifest.version}`);
7159
7531
  console.log(`Pasta: ${project.directory}`);
7532
+ console.log(`Tenant: ${tenant.name}`);
7160
7533
  console.log("");
7161
7534
  console.log("Carregando dados públicos...");
7162
- const context = await loadThemeContext({
7163
- store,
7164
- apiUrl
7165
- });
7166
7535
  console.log("");
7167
7536
  console.log(`Store: ${context.store.name}`);
7168
7537
  console.log(`Slug: ${context.store.slug}`);
@@ -7363,18 +7732,20 @@ async function registryRequest(credentials, url, init) {
7363
7732
  if (!response.ok) throw new ThemeRegistryError(payload?.error || `Theme Registry respondeu com HTTP ${response.status}`, response.status, payload?.code);
7364
7733
  return payload;
7365
7734
  }
7366
- async function createOrResolveTheme(credentials, input) {
7367
- return registryRequest(credentials, apiEndpoint(credentials.apiUrl, "/developer/themes"), {
7735
+ async function createOrResolveTheme(credentials, input, audience = "developer") {
7736
+ return registryRequest(credentials, apiEndpoint(credentials.apiUrl, `/${audience}/themes`), {
7368
7737
  method: "POST",
7369
7738
  body: JSON.stringify({
7370
7739
  slug: input.slug,
7371
7740
  name: input.name,
7372
- visibility: input.visibility ?? "PRIVATE"
7741
+ visibility: input.visibility,
7742
+ ownerType: input.ownerType,
7743
+ ...input.ownerType === "TENANT" ? { ownerTenantId: input.ownerTenantId } : {}
7373
7744
  })
7374
7745
  });
7375
7746
  }
7376
- async function reserveThemeVersion(credentials, themeId, input) {
7377
- return registryRequest(credentials, apiEndpoint(credentials.apiUrl, `/developer/themes/${themeId}/versions`), {
7747
+ async function reserveThemeVersion(credentials, themeId, input, audience = "developer") {
7748
+ return registryRequest(credentials, apiEndpoint(credentials.apiUrl, `/${audience}/themes/${themeId}/versions`), {
7378
7749
  method: "POST",
7379
7750
  body: JSON.stringify(input)
7380
7751
  });
@@ -7413,10 +7784,23 @@ function createThemeVersionRequest(input) {
7413
7784
  //#endregion
7414
7785
  //#region src/commands/theme/publish.ts
7415
7786
  async function themePublish(options) {
7416
- const apiUrl = options.apiUrl?.trim() || process.env.NUVLER_API_URL?.trim();
7417
- const token = options.token?.trim() || process.env.NUVLER_TOKEN?.trim();
7418
- if (!apiUrl) throw new Error("Informe a API usando --api-url ou defina NUVLER_API_URL.");
7419
- if (!token) throw new Error("Informe o token usando --token ou defina NUVLER_TOKEN.");
7787
+ const saved = await readAuthConfig();
7788
+ const configured = await readThemeProjectConfig(options.themeDirectory);
7789
+ const apiUrl = options.apiUrl?.trim() || saved?.apiUrl;
7790
+ const token = options.token?.trim() || saved?.token;
7791
+ if (!apiUrl) throw new Error("Developer não autenticado. Execute nuvler auth login.");
7792
+ if (!token) throw new Error("Autentique com nuvler auth login ou informe --token.");
7793
+ if (options.official && token.startsWith("nuvler_dev_")) throw new Error("Publicação oficial exige uma sessão de PLATFORM_ADMIN.");
7794
+ if (options.visibility && ![
7795
+ "PRIVATE",
7796
+ "UNLISTED",
7797
+ "PUBLIC"
7798
+ ].includes(options.visibility)) throw new Error("Visibilidade inválida. Use private, unlisted ou public.");
7799
+ const tenantId = options.official ? void 0 : options.tenantId?.trim() || configured?.tenant.id;
7800
+ if (tenantId && token.startsWith("nuvler_dev_")) requireAuthorizedTenant(await fetchDeveloperProfile(apiUrl, token), tenantId);
7801
+ if (options.official && options.visibility && options.visibility !== "PUBLIC") throw new Error("Tema oficial deve ter visibilidade PUBLIC.");
7802
+ const visibility = options.official ? "PUBLIC" : options.visibility ?? (tenantId ? "PRIVATE" : "UNLISTED");
7803
+ if (visibility === "PRIVATE" && !tenantId) throw new Error("Tema privado exige um tenant. Execute nuvler theme configure ou informe --tenant-id.");
7420
7804
  const artifact = await themePack({
7421
7805
  themeDirectory: options.themeDirectory,
7422
7806
  destination: options.destination,
@@ -7427,13 +7811,17 @@ async function themePublish(options) {
7427
7811
  apiUrl,
7428
7812
  token
7429
7813
  };
7814
+ const audience = options.official ? "platform" : "developer";
7430
7815
  console.log("Publicando no Nuvler Theme Registry...");
7431
7816
  const theme = await createOrResolveTheme(credentials, {
7432
7817
  slug: artifact.manifest.id,
7433
- name: artifact.manifest.name
7434
- });
7818
+ name: artifact.manifest.name,
7819
+ visibility,
7820
+ ownerType: options.official ? "PLATFORM" : tenantId ? "TENANT" : "DEVELOPER",
7821
+ ownerTenantId: tenantId
7822
+ }, audience);
7435
7823
  console.log(`✓ Tema: ${theme.name} (${theme.id})`);
7436
- const target = await reserveThemeVersion(credentials, theme.id, request);
7824
+ const target = await reserveThemeVersion(credentials, theme.id, request, audience);
7437
7825
  console.log(`✓ Versão reservada: ${artifact.manifest.version}`);
7438
7826
  await uploadThemeArtifact(target.upload, await readFile(artifact.file));
7439
7827
  console.log(`✓ Upload concluído: ${target.storageKey}`);
@@ -7459,24 +7847,87 @@ async function themeValidate(options) {
7459
7847
  console.log("");
7460
7848
  }
7461
7849
  //#endregion
7850
+ //#region src/commands/auth.ts
7851
+ async function authLogin(options) {
7852
+ const apiUrl = options.apiUrl?.trim() || process.env.NUVLER_API_URL?.trim();
7853
+ if (!apiUrl) throw new Error("Informe a API usando --api-url ou NUVLER_API_URL.");
7854
+ const token = options.token.trim();
7855
+ if (!token) throw new Error("Developer token vazio.");
7856
+ const profile = await fetchDeveloperProfile(apiUrl, token);
7857
+ await writeAuthConfig({
7858
+ apiUrl: apiUrl.replace(/\/+$/, ""),
7859
+ token
7860
+ });
7861
+ console.log(`✓ Autenticado como developer ${profile.developerId}`);
7862
+ }
7863
+ async function authStatus() {
7864
+ const config = await readAuthConfig();
7865
+ if (!config) throw new Error("Nenhuma autenticação de developer configurada.");
7866
+ const profile = await fetchDeveloperProfile(config.apiUrl, config.token);
7867
+ console.log(`Developer: ${profile.developerId}`);
7868
+ console.log(`Scopes: ${profile.scopes.join(", ") || "nenhum"}`);
7869
+ console.log(`Tenants autorizados: ${profile.tenants.length}`);
7870
+ }
7871
+ async function authLogout() {
7872
+ await clearAuthConfig();
7873
+ console.log("✓ Autenticação local removida.");
7874
+ }
7875
+ //#endregion
7462
7876
  //#region src/index.ts
7463
- function loadLocalEnvironment() {
7877
+ var program = new Command();
7878
+ program.name("nuvler").description("Nuvler Theme Development CLI").version("0.3.0");
7879
+ var theme = program.command("theme").description("Manage Nuvler themes");
7880
+ var auth = program.command("auth").description("Manage developer authentication");
7881
+ auth.command("login").requiredOption("--token <token>", "Developer token").option("--api-url <url>", "Nuvler API base URL (or use NUVLER_API_URL)").action(async (options) => {
7464
7882
  try {
7465
- process.loadEnvFile?.();
7883
+ await authLogin(options);
7466
7884
  } catch (error) {
7467
- if (error.code !== "ENOENT") throw error;
7885
+ console.error(`Erro: ${error instanceof Error ? error.message : "Erro desconhecido."}`);
7886
+ process.exitCode = 1;
7468
7887
  }
7469
- }
7470
- loadLocalEnvironment();
7471
- var program = new Command();
7472
- program.name("nuvler").description("Nuvler Theme Development CLI").version("0.1.0");
7473
- var theme = program.command("theme").description("Manage Nuvler themes");
7474
- theme.command("create").description("Create a new theme project from the official starter").argument("<directory>", "Directory that will receive the theme").option("--id <id>", "Theme id (defaults to the directory name)").option("--name <name>", "Public theme name").action(async (directory, options) => {
7888
+ });
7889
+ auth.command("status").action(async () => {
7890
+ try {
7891
+ await authStatus();
7892
+ } catch (error) {
7893
+ console.error(`Erro: ${error instanceof Error ? error.message : "Erro desconhecido."}`);
7894
+ process.exitCode = 1;
7895
+ }
7896
+ });
7897
+ auth.command("logout").action(async () => {
7898
+ try {
7899
+ await authLogout();
7900
+ } catch (error) {
7901
+ console.error(`Erro: ${error instanceof Error ? error.message : "Erro desconhecido."}`);
7902
+ process.exitCode = 1;
7903
+ }
7904
+ });
7905
+ theme.command("create").description("Create a new theme project from an official template").argument("<directory>", "Directory that will receive the theme").option("--id <id>", "Theme id (defaults to the directory name)").option("--name <name>", "Public theme name").option("--template <template>", "Base template: starter, nuvler-default or nuvler-atelier", "starter").action(async (directory, options) => {
7475
7906
  try {
7476
7907
  await themeCreate({
7477
7908
  directory,
7478
7909
  id: options.id,
7479
- name: options.name
7910
+ name: options.name,
7911
+ template: options.template
7912
+ });
7913
+ } catch (error) {
7914
+ const message = error instanceof Error ? error.message : "Erro desconhecido.";
7915
+ console.error(`Erro: ${message}`);
7916
+ process.exitCode = 1;
7917
+ }
7918
+ });
7919
+ theme.command("templates").description("List the templates available for theme create").action(() => {
7920
+ console.log("");
7921
+ console.log("Templates disponíveis:");
7922
+ for (const template of THEME_TEMPLATES) console.log(` ${template.id.padEnd(16)} ${template.description}`);
7923
+ console.log("");
7924
+ });
7925
+ theme.command("configure").description("Configure this theme project for an authorized tenant").option("--theme <directory>", "Theme directory", ".").option("--tenant <slug-or-id>", "Authorized tenant slug or ID").option("--key <connection-key>", "Nuvler connection key from the tenant panel").action(async (options) => {
7926
+ try {
7927
+ await themeConfigure({
7928
+ themeDirectory: options.theme,
7929
+ tenant: options.tenant,
7930
+ key: options.key
7480
7931
  });
7481
7932
  } catch (error) {
7482
7933
  const message = error instanceof Error ? error.message : "Erro desconhecido.";
@@ -7484,7 +7935,7 @@ theme.command("create").description("Create a new theme project from the officia
7484
7935
  process.exitCode = 1;
7485
7936
  }
7486
7937
  });
7487
- theme.command("dev").description("Start the local theme development server").option("--store <slug>", "Store slug (or use NUVLER_STORE_SLUG)").option("--theme <directory>", "Theme directory", ".").option("--api-url <url>", "Public API base URL (or use NUVLER_API_URL)").option("--port <number>", "Local preview port", (value) => {
7938
+ theme.command("dev").description("Start the local theme development server").option("--store <slug>", "Authorized store slug (overrides project configuration)").option("--theme <directory>", "Theme directory", ".").option("--api-url <url>", "Public API base URL (overrides saved auth)").option("--port <number>", "Local preview port", (value) => {
7488
7939
  const port = Number(value);
7489
7940
  if (!Number.isInteger(port) || port < 1 || port > 65535) throw new Error("A porta deve ser um inteiro entre 1 e 65535.");
7490
7941
  return port;
@@ -7533,13 +7984,16 @@ theme.command("pack").description("Build, validate and package a local theme").o
7533
7984
  process.exitCode = 1;
7534
7985
  }
7535
7986
  });
7536
- theme.command("publish").description("Publish a theme directly to the Nuvler Theme Registry").option("--theme <directory>", "Theme directory", ".").option("--destination <directory>", "Directory for the generated artifact", "artifacts").option("--api-url <url>", "Nuvler API base URL (or use NUVLER_API_URL)").option("--token <token>", "Platform access token (or use NUVLER_TOKEN)").action(async (options) => {
7987
+ theme.command("publish").description("Publish a theme directly to the Nuvler Theme Registry").option("--theme <directory>", "Theme directory", ".").option("--destination <directory>", "Directory for the generated artifact", "artifacts").option("--api-url <url>", "Nuvler API base URL (overrides saved auth)").option("--token <token>", "Developer token (or use saved auth)").option("--visibility <visibility>", "Theme visibility: private, unlisted or public").option("--tenant-id <tenantId>", "Owner tenant ID (overrides project configuration)").option("--official", "Publish a PLATFORM/PUBLIC theme (requires PLATFORM_ADMIN token)").action(async (options) => {
7537
7988
  try {
7538
7989
  await themePublish({
7539
7990
  themeDirectory: options.theme,
7540
7991
  destination: options.destination,
7541
7992
  apiUrl: options.apiUrl,
7542
- token: options.token
7993
+ token: options.token,
7994
+ visibility: options.visibility?.toUpperCase(),
7995
+ tenantId: options.tenantId,
7996
+ official: Boolean(options.official)
7543
7997
  });
7544
7998
  } catch (error) {
7545
7999
  const message = error instanceof Error ? error.message : "Erro desconhecido.";