@nuvler/cli 0.2.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 (52) hide show
  1. package/README.md +38 -4
  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 +11 -4
  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 +64 -15
  25. package/dist/index.js.map +1 -1
  26. package/dist/nuvler.js +492 -124
  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 +3 -3
  31. package/dist/templates/nuvler-atelier/gitignore.template +1 -1
  32. package/dist/templates/nuvler-atelier/nuvler.theme.json +8 -2
  33. package/dist/templates/nuvler-atelier/package.json +2 -2
  34. package/dist/templates/nuvler-default/README.md +1 -1
  35. package/dist/templates/nuvler-default/gitignore.template +1 -1
  36. package/dist/templates/nuvler-default/nuvler.theme.json +8 -2
  37. package/dist/templates/nuvler-default/package.json +14 -1
  38. package/dist/templates/starter/README.md +3 -3
  39. package/dist/templates/starter/gitignore.template +1 -1
  40. package/dist/templates/starter/nuvler.theme.json +8 -2
  41. package/dist/templates/starter/package.json +2 -2
  42. package/dist/theme/artifact.js +1 -0
  43. package/dist/theme/artifact.js.map +1 -1
  44. package/package.json +3 -3
  45. package/preview-host/package.json +1 -1
  46. package/preview-host/src/public-preview-url.d.mts +5 -0
  47. package/preview-host/src/public-preview-url.mjs +50 -0
  48. package/preview-host/vendor/theme-runtime/default-theme.tsx +1 -1
  49. package/preview-host/vite.config.ts +4 -3
  50. package/dist/templates/nuvler-atelier/.env.example +0 -3
  51. package/dist/templates/nuvler-default/.env.example +0 -3
  52. package/dist/templates/starter/.env.example +0 -3
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;
@@ -26,7 +28,8 @@ var __exportAll = (all, no_symbols) => {
26
28
  //#region src/commands/theme/create.ts
27
29
  var THEME_ID_PATTERN = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
28
30
  var NEW_THEME_VERSION = "0.1.0";
29
- var CLI_VERSION_RANGE = "^0.2.0";
31
+ var CLI_VERSION_RANGE = "^0.3.0";
32
+ var SDK_VERSION_RANGE = "^1.1.0";
30
33
  var THEME_TEMPLATES = [
31
34
  {
32
35
  id: "starter",
@@ -87,6 +90,11 @@ async function customizeTemplate(directory, id, name, template) {
87
90
  manifest.id = id;
88
91
  manifest.name = name;
89
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
+ };
90
98
  await writeFile(manifestFile, `${JSON.stringify(manifest, null, 2)}\n`, "utf8");
91
99
  const packageFile = path.join(directory, "package.json");
92
100
  const packageMetadata = JSON.parse(await readFile(packageFile, "utf8"));
@@ -104,7 +112,7 @@ async function customizeTemplate(directory, id, name, template) {
104
112
  };
105
113
  packageMetadata.dependencies = {
106
114
  ...packageMetadata.dependencies,
107
- "@nuvler/theme-sdk": "^1.0.0"
115
+ "@nuvler/theme-sdk": SDK_VERSION_RANGE
108
116
  };
109
117
  packageMetadata.devDependencies = {
110
118
  ...packageMetadata.devDependencies,
@@ -120,7 +128,7 @@ async function customizeTemplate(directory, id, name, template) {
120
128
  const definition = await readFile(definitionFile, "utf8");
121
129
  await writeFile(definitionFile, definition.replaceAll("__NUVLER_THEME_ID__", id).replaceAll("__NUVLER_THEME_NAME__", name), "utf8");
122
130
  }
123
- const readme = `# ${name}\n\nTema Nuvler criado a partir do template \`${template}\`.\n\n## Desenvolvimento\n\n\`\`\`bash\nnpm install\ncp .env.example .env\nnpm run validate\nnpm run dev\n\`\`\`\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`;
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`;
124
132
  await writeFile(path.join(directory, "README.md"), readme, "utf8");
125
133
  }
126
134
  async function ensureEmptyTarget(directory) {
@@ -160,7 +168,7 @@ async function themeCreate(options) {
160
168
  console.log("Próximos passos:");
161
169
  console.log(` cd ${path.relative(process.cwd(), directory) || "."}`);
162
170
  console.log(" npm install");
163
- console.log(" cp .env.example .env");
171
+ console.log(" nuvler theme configure --key CHAVE_COPIADA_DO_PAINEL");
164
172
  console.log(" npm run validate");
165
173
  console.log(" npm run dev");
166
174
  console.log(" npm run build");
@@ -200,7 +208,8 @@ function createArtifactManifest(project, build) {
200
208
  runtimeVersion: project.manifest.runtimeVersion,
201
209
  sdkVersion: project.manifest.sdkVersion,
202
210
  entry: "./theme.js",
203
- style: build.stylePath ? "./theme.css" : void 0
211
+ style: build.stylePath ? "./theme.css" : void 0,
212
+ presentation: project.manifest.presentation
204
213
  };
205
214
  }
206
215
  //#endregion
@@ -6554,6 +6563,20 @@ config(en_default());
6554
6563
  //#endregion
6555
6564
  //#region ../theme-schema/dist/index.js
6556
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();
6557
6580
  var ThemeManifestSchema = object({
6558
6581
  schemaVersion: literal(THEME_SCHEMA_VERSION),
6559
6582
  id: string$1().trim().min(2).max(80).regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/, "Use um identificador em kebab-case"),
@@ -6562,7 +6585,8 @@ var ThemeManifestSchema = object({
6562
6585
  runtimeVersion: literal(THEME_RUNTIME_VERSION),
6563
6586
  sdkVersion: string$1().trim().min(1).max(80),
6564
6587
  entry: relativeThemeFileSchema.refine((value) => /\.(?:[cm]?[jt]sx?)$/i.test(value), { message: "A entrada deve ser um arquivo JavaScript ou TypeScript" }),
6565
- 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()
6566
6590
  }).strict();
6567
6591
  var nullableStringSchema = string$1().nullable();
6568
6592
  var hexColorSchema = string$1().regex(/^#[0-9a-f]{6}$/i, "Use uma cor hexadecimal no formato #RRGGBB");
@@ -6883,6 +6907,341 @@ async function themeBuild(options) {
6883
6907
  return output;
6884
6908
  }
6885
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
6886
7245
  //#region src/api/client.ts
6887
7246
  var PublicApiError = class extends Error {
6888
7247
  endpoint;
@@ -7134,91 +7493,24 @@ async function loadThemeContext({ store, apiUrl }) {
7134
7493
  return result.data;
7135
7494
  }
7136
7495
  //#endregion
7137
- //#region src/preview/launcher.ts
7138
- async function resolvePreviewHost() {
7139
- const configured = process.env.NUVLER_PREVIEW_HOST_DIR?.trim();
7140
- const currentDirectory = path.dirname(fileURLToPath(import.meta.url));
7141
- const candidates = configured ? [path.resolve(configured)] : [
7142
- path.resolve(currentDirectory, "../preview-host"),
7143
- path.resolve(currentDirectory, "../../preview-host"),
7144
- path.resolve(currentDirectory, "../../../apps/preview-host"),
7145
- path.resolve(currentDirectory, "../../../../apps/preview-host")
7146
- ];
7147
- for (const directory of candidates) try {
7148
- await access(path.join(directory, "package.json"));
7149
- return directory;
7150
- } catch {}
7151
- throw new Error("Preview host não encontrado no package da CLI nem no monorepo. Reinstale @nuvler/cli ou defina NUVLER_PREVIEW_HOST_DIR.");
7152
- }
7153
- async function removeContextFile(directory, file) {
7154
- await unlink(file).catch(() => void 0);
7155
- await rmdir(directory).catch(() => void 0);
7156
- }
7157
- async function runLocalPreview(contextFile, project, apiUrl, store, port) {
7158
- const previewHost = await resolvePreviewHost();
7159
- return new Promise((resolve, reject) => {
7160
- const child = spawn("npm", [
7161
- "run",
7162
- "dev",
7163
- "--",
7164
- "--host",
7165
- "127.0.0.1",
7166
- "--port",
7167
- String(port),
7168
- "--strictPort"
7169
- ], {
7170
- cwd: previewHost,
7171
- stdio: "inherit",
7172
- shell: false,
7173
- env: {
7174
- ...process.env,
7175
- NUVLER_THEME_CONTEXT_FILE: contextFile,
7176
- NUVLER_THEME_DIRECTORY: project.directory,
7177
- NUVLER_THEME_ENTRY: project.entryPath,
7178
- NUVLER_THEME_STYLES: JSON.stringify(project.stylePaths),
7179
- NUVLER_API_URL: apiUrl,
7180
- NUVLER_STORE_SLUG: store
7181
- }
7182
- });
7183
- let interrupted = false;
7184
- const shutdown = (signal) => {
7185
- interrupted = true;
7186
- if (!child.killed) child.kill(signal);
7187
- };
7188
- const onSigint = () => shutdown("SIGINT");
7189
- const onSigterm = () => shutdown("SIGTERM");
7190
- const removeSignalHandlers = () => {
7191
- process.off("SIGINT", onSigint);
7192
- process.off("SIGTERM", onSigterm);
7193
- };
7194
- process.once("SIGINT", onSigint);
7195
- process.once("SIGTERM", onSigterm);
7196
- child.once("error", (error) => {
7197
- removeSignalHandlers();
7198
- reject(new Error("Não foi possível iniciar o preview.", { cause: error }));
7199
- });
7200
- child.once("exit", (code, signal) => {
7201
- removeSignalHandlers();
7202
- if (interrupted || signal || code === 0) {
7203
- resolve();
7204
- return;
7205
- }
7206
- reject(/* @__PURE__ */ new Error(`O preview foi encerrado com código ${code ?? "desconhecido"}.`));
7207
- });
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
7208
7506
  });
7209
- }
7210
- async function launchPreview(context, project, options) {
7211
- const directory = await mkdtemp(path.join(tmpdir(), "nuvler-theme-"));
7212
- const contextFile = path.join(directory, "theme-context.json");
7213
- try {
7214
- await writeFile(contextFile, JSON.stringify(context, null, 2), {
7215
- encoding: "utf8",
7216
- mode: 384
7217
- });
7218
- await runLocalPreview(contextFile, project, options.apiUrl, options.store, options.port);
7219
- } finally {
7220
- await removeContextFile(directory, contextFile);
7221
- }
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
+ };
7222
7514
  }
7223
7515
  //#endregion
7224
7516
  //#region src/commands/theme/dev.ts
@@ -7226,22 +7518,20 @@ function countCategories(categories) {
7226
7518
  return categories.reduce((total, category) => total + 1 + countCategories(category.children), 0);
7227
7519
  }
7228
7520
  async function themeDev(options) {
7229
- const store = options.store?.trim() || process.env.NUVLER_STORE_SLUG?.trim();
7230
- const apiUrl = options.apiUrl?.trim() || process.env.NUVLER_API_URL?.trim();
7231
- if (!store) throw new Error("Informe a loja usando --store ou defina NUVLER_STORE_SLUG.");
7232
- if (!apiUrl) throw new Error("Informe a API usando --api-url ou defina NUVLER_API_URL.");
7233
- 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;
7234
7527
  console.log("");
7235
7528
  console.log("Nuvler Theme Development");
7236
7529
  console.log("");
7237
7530
  console.log(`Tema: ${project.manifest.name} v${project.manifest.version}`);
7238
7531
  console.log(`Pasta: ${project.directory}`);
7532
+ console.log(`Tenant: ${tenant.name}`);
7239
7533
  console.log("");
7240
7534
  console.log("Carregando dados públicos...");
7241
- const context = await loadThemeContext({
7242
- store,
7243
- apiUrl
7244
- });
7245
7535
  console.log("");
7246
7536
  console.log(`Store: ${context.store.name}`);
7247
7537
  console.log(`Slug: ${context.store.slug}`);
@@ -7442,18 +7732,20 @@ async function registryRequest(credentials, url, init) {
7442
7732
  if (!response.ok) throw new ThemeRegistryError(payload?.error || `Theme Registry respondeu com HTTP ${response.status}`, response.status, payload?.code);
7443
7733
  return payload;
7444
7734
  }
7445
- async function createOrResolveTheme(credentials, input) {
7446
- 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`), {
7447
7737
  method: "POST",
7448
7738
  body: JSON.stringify({
7449
7739
  slug: input.slug,
7450
7740
  name: input.name,
7451
- visibility: input.visibility ?? "PRIVATE"
7741
+ visibility: input.visibility,
7742
+ ownerType: input.ownerType,
7743
+ ...input.ownerType === "TENANT" ? { ownerTenantId: input.ownerTenantId } : {}
7452
7744
  })
7453
7745
  });
7454
7746
  }
7455
- async function reserveThemeVersion(credentials, themeId, input) {
7456
- 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`), {
7457
7749
  method: "POST",
7458
7750
  body: JSON.stringify(input)
7459
7751
  });
@@ -7492,10 +7784,23 @@ function createThemeVersionRequest(input) {
7492
7784
  //#endregion
7493
7785
  //#region src/commands/theme/publish.ts
7494
7786
  async function themePublish(options) {
7495
- const apiUrl = options.apiUrl?.trim() || process.env.NUVLER_API_URL?.trim();
7496
- const token = options.token?.trim() || process.env.NUVLER_TOKEN?.trim();
7497
- if (!apiUrl) throw new Error("Informe a API usando --api-url ou defina NUVLER_API_URL.");
7498
- 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.");
7499
7804
  const artifact = await themePack({
7500
7805
  themeDirectory: options.themeDirectory,
7501
7806
  destination: options.destination,
@@ -7506,13 +7811,17 @@ async function themePublish(options) {
7506
7811
  apiUrl,
7507
7812
  token
7508
7813
  };
7814
+ const audience = options.official ? "platform" : "developer";
7509
7815
  console.log("Publicando no Nuvler Theme Registry...");
7510
7816
  const theme = await createOrResolveTheme(credentials, {
7511
7817
  slug: artifact.manifest.id,
7512
- name: artifact.manifest.name
7513
- });
7818
+ name: artifact.manifest.name,
7819
+ visibility,
7820
+ ownerType: options.official ? "PLATFORM" : tenantId ? "TENANT" : "DEVELOPER",
7821
+ ownerTenantId: tenantId
7822
+ }, audience);
7514
7823
  console.log(`✓ Tema: ${theme.name} (${theme.id})`);
7515
- const target = await reserveThemeVersion(credentials, theme.id, request);
7824
+ const target = await reserveThemeVersion(credentials, theme.id, request, audience);
7516
7825
  console.log(`✓ Versão reservada: ${artifact.manifest.version}`);
7517
7826
  await uploadThemeArtifact(target.upload, await readFile(artifact.file));
7518
7827
  console.log(`✓ Upload concluído: ${target.storageKey}`);
@@ -7538,18 +7847,61 @@ async function themeValidate(options) {
7538
7847
  console.log("");
7539
7848
  }
7540
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
7541
7876
  //#region src/index.ts
7542
- 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) => {
7543
7882
  try {
7544
- process.loadEnvFile?.();
7883
+ await authLogin(options);
7545
7884
  } catch (error) {
7546
- if (error.code !== "ENOENT") throw error;
7885
+ console.error(`Erro: ${error instanceof Error ? error.message : "Erro desconhecido."}`);
7886
+ process.exitCode = 1;
7547
7887
  }
7548
- }
7549
- loadLocalEnvironment();
7550
- var program = new Command();
7551
- program.name("nuvler").description("Nuvler Theme Development CLI").version("0.2.0");
7552
- var theme = program.command("theme").description("Manage Nuvler themes");
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
+ });
7553
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) => {
7554
7906
  try {
7555
7907
  await themeCreate({
@@ -7570,7 +7922,20 @@ theme.command("templates").description("List the templates available for theme c
7570
7922
  for (const template of THEME_TEMPLATES) console.log(` ${template.id.padEnd(16)} ${template.description}`);
7571
7923
  console.log("");
7572
7924
  });
7573
- 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) => {
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
7931
+ });
7932
+ } catch (error) {
7933
+ const message = error instanceof Error ? error.message : "Erro desconhecido.";
7934
+ console.error(`Erro: ${message}`);
7935
+ process.exitCode = 1;
7936
+ }
7937
+ });
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) => {
7574
7939
  const port = Number(value);
7575
7940
  if (!Number.isInteger(port) || port < 1 || port > 65535) throw new Error("A porta deve ser um inteiro entre 1 e 65535.");
7576
7941
  return port;
@@ -7619,13 +7984,16 @@ theme.command("pack").description("Build, validate and package a local theme").o
7619
7984
  process.exitCode = 1;
7620
7985
  }
7621
7986
  });
7622
- 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) => {
7623
7988
  try {
7624
7989
  await themePublish({
7625
7990
  themeDirectory: options.theme,
7626
7991
  destination: options.destination,
7627
7992
  apiUrl: options.apiUrl,
7628
- token: options.token
7993
+ token: options.token,
7994
+ visibility: options.visibility?.toUpperCase(),
7995
+ tenantId: options.tenantId,
7996
+ official: Boolean(options.official)
7629
7997
  });
7630
7998
  } catch (error) {
7631
7999
  const message = error instanceof Error ? error.message : "Erro desconhecido.";