sitecms-next 0.2.1 → 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.
package/src/cli.ts CHANGED
@@ -2,19 +2,36 @@
2
2
  /**
3
3
  * sitecms-next CLI
4
4
  *
5
+ * sitecms-next init [nyckel] [--force] [--no-install] Koppla projektet till sitecms (en gång)
5
6
  * sitecms-next sync [--prune] [--strict] [--config <fil>] Synka sajtens fält till sitecms
6
7
  * sitecms-next pull Visa strukturen som finns i sitecms
7
- * sitecms-next check Kontrollera CMS_API_URL/CMS_SITE/CMS_API_KEY
8
+ * sitecms-next check Kontrollera nyckeln och webhooken
8
9
  *
9
- * Läser CMS_API_URL, CMS_SITE och CMS_API_KEY från miljön, eller från
10
- * .env.local / .env i projektroten. Lägg "prebuild": "sitecms-next sync"
11
- * i package.json så synkas strukturen vid varje bygge.
10
+ * Det enda som krävs är CMS_API_KEY. CMS_API_URL (default https://sitecms.se)
11
+ * och CMS_SITE (slug-routerna från 0.2.x) är valfria. Variablerna läses från
12
+ * miljön, eller från .env.local / .env i projektroten. `init` lägger till
13
+ * "prebuild": "sitecms-next sync" i package.json så att strukturen synkas
14
+ * vid varje bygge.
12
15
  */
13
- import { existsSync, readFileSync, rmSync, writeFileSync } from "node:fs";
14
- import { dirname, resolve } from "node:path";
15
- import { pathToFileURL } from "node:url";
16
+ import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
17
+ import { dirname, join, relative, resolve } from "node:path";
18
+ import { fileURLToPath, pathToFileURL } from "node:url";
16
19
  import { spawnSync } from "node:child_process";
17
- import type { SitecmsConfig } from "./index.js";
20
+ import { createInterface } from "node:readline/promises";
21
+ import { DEFAULT_API_URL, apiBase } from "./index.js";
22
+ import type { Health, SitecmsConfig } from "./index.js";
23
+ import {
24
+ addSyncToPrebuild,
25
+ envFileValues,
26
+ maskRevalidateUrl,
27
+ maskUrlsInText,
28
+ parseEnvValue,
29
+ parsePackageJson,
30
+ resolveSiteUrl,
31
+ shortKey,
32
+ upsertEnvText,
33
+ } from "./cli-helpers.js";
34
+ import type { JsonObject } from "./cli-helpers.js";
18
35
 
19
36
  const CONFIG_NAMES = [
20
37
  "sitecms.config.ts",
@@ -24,9 +41,25 @@ const CONFIG_NAMES = [
24
41
  "sitecms.config.json",
25
42
  ];
26
43
 
44
+ const DOCS_URL = "https://sitecms.se/docs";
45
+ const CLI_FILE = fileURLToPath(import.meta.url);
46
+
27
47
  const cwd = process.cwd();
28
48
  const args = process.argv.slice(2);
29
- const command = args.find((a) => !a.startsWith("-")) ?? "help";
49
+ /** Variabler som var satta innan .env.local/.env lästes in. */
50
+ const shellEnv = new Set(Object.keys(process.env).filter((k) => (process.env[k] ?? "").trim() !== ""));
51
+ const VALUE_OPTIONS = new Set(["config"]);
52
+ const positionals: string[] = [];
53
+ for (let i = 0; i < args.length; i++) {
54
+ const a = args[i];
55
+ if (a.startsWith("--")) {
56
+ if (VALUE_OPTIONS.has(a.slice(2))) i++;
57
+ continue;
58
+ }
59
+ if (a.startsWith("-")) continue;
60
+ positionals.push(a);
61
+ }
62
+ const command = args.includes("--help") || args.includes("-h") ? "help" : (positionals[0] ?? "help");
30
63
  const flag = (name: string) => args.includes(`--${name}`);
31
64
  const option = (name: string) => {
32
65
  const i = args.indexOf(`--${name}`);
@@ -35,16 +68,25 @@ const option = (name: string) => {
35
68
 
36
69
  const c = {
37
70
  dim: (s: string) => (process.stdout.isTTY ? `\x1b[2m${s}\x1b[0m` : s),
71
+ bold: (s: string) => (process.stdout.isTTY ? `\x1b[1m${s}\x1b[0m` : s),
38
72
  green: (s: string) => (process.stdout.isTTY ? `\x1b[32m${s}\x1b[0m` : s),
39
73
  red: (s: string) => (process.stderr.isTTY ? `\x1b[31m${s}\x1b[0m` : s),
40
74
  yellow: (s: string) => (process.stdout.isTTY ? `\x1b[33m${s}\x1b[0m` : s),
75
+ yellowErr: (s: string) => (process.stderr.isTTY ? `\x1b[33m${s}\x1b[0m` : s),
41
76
  };
42
77
  const log = (s = "") => console.log(s);
78
+
79
+ class CliError extends Error {}
43
80
  const fail = (s: string): never => {
44
- console.error(c.red(`✖ ${s}`));
45
- process.exit(1);
81
+ throw new CliError(s);
46
82
  };
47
83
 
84
+ const rel = (path: string) => relative(cwd, path).split("\\").join("/") || ".";
85
+
86
+ function envVar(name: string): string {
87
+ return (process.env[name] ?? "").trim();
88
+ }
89
+
48
90
  /** Laddar .env.local och .env utan att skriva över befintliga variabler. */
49
91
  function loadEnvFiles() {
50
92
  for (const file of [".env.local", ".env"]) {
@@ -57,37 +99,30 @@ function loadEnvFiles() {
57
99
  if (!m) continue;
58
100
  const [, key, rawValue] = m;
59
101
  if (process.env[key] !== undefined) continue;
60
- let value = rawValue.trim();
61
- if ((value.startsWith('"') && value.endsWith('"')) || (value.startsWith("'") && value.endsWith("'"))) {
62
- value = value.slice(1, -1);
63
- } else {
64
- value = value.replace(/\s+#.*$/, "");
65
- }
66
- process.env[key] = value;
102
+ process.env[key] = parseEnvValue(rawValue);
67
103
  }
68
104
  }
69
105
  }
70
106
 
71
107
  type Env = { apiUrl: string; site: string; apiKey: string };
72
108
 
109
+ /** CMS_API_KEY krävs; CMS_API_URL och CMS_SITE är valfria. null om nyckeln saknas. */
73
110
  function readEnv(): Env | null {
74
- const apiUrl = (process.env.CMS_API_URL ?? "").trim().replace(/\/+$/, "");
75
- const site = (process.env.CMS_SITE ?? "").trim();
76
- const apiKey = (process.env.CMS_API_KEY ?? "").trim();
77
- const missing = [
78
- !apiUrl && "CMS_API_URL",
79
- !site && "CMS_SITE",
80
- !apiKey && "CMS_API_KEY",
81
- ].filter(Boolean);
82
- if (missing.length) {
83
- console.error(c.yellow(`⚠ Saknar ${missing.join(", ")} (miljövariabler eller .env.local).`));
84
- return null;
85
- }
86
- return { apiUrl, site, apiKey };
111
+ const apiKey = envVar("CMS_API_KEY");
112
+ if (!apiKey) return null;
113
+ return {
114
+ apiUrl: (envVar("CMS_API_URL") || DEFAULT_API_URL).replace(/\/+$/, ""),
115
+ site: envVar("CMS_SITE"),
116
+ apiKey,
117
+ };
118
+ }
119
+
120
+ function describeTarget(env: Env): string {
121
+ return env.site ? `${env.apiUrl} (${env.site})` : env.apiUrl;
87
122
  }
88
123
 
89
124
  async function api(env: Env, method: "GET" | "POST", path: string, body?: unknown) {
90
- const res = await fetch(`${env.apiUrl}/api/v1/sites/${encodeURIComponent(env.site)}${path}`, {
125
+ const res = await fetch(`${apiBase(env.apiUrl, env.site)}${path}`, {
91
126
  method,
92
127
  headers: { "x-api-key": env.apiKey, "content-type": "application/json" },
93
128
  body: body === undefined ? undefined : JSON.stringify(body),
@@ -96,6 +131,52 @@ async function api(env: Env, method: "GET" | "POST", path: string, body?: unknow
96
131
  return { status: res.status, json };
97
132
  }
98
133
 
134
+ const CI_VARS = [
135
+ "CI",
136
+ "CONTINUOUS_INTEGRATION",
137
+ "BUILD_NUMBER",
138
+ "VERCEL",
139
+ "NETLIFY",
140
+ "CF_PAGES",
141
+ "RENDER",
142
+ "GITHUB_ACTIONS",
143
+ "GITLAB_CI",
144
+ "CIRCLECI",
145
+ "BUILDKITE",
146
+ "TRAVIS",
147
+ "JENKINS_URL",
148
+ "TEAMCITY_VERSION",
149
+ "BITBUCKET_BUILD_NUMBER",
150
+ "CODEBUILD_BUILD_ID",
151
+ "TF_BUILD",
152
+ "RAILWAY_ENVIRONMENT",
153
+ "DIGITALOCEAN_APP_ID",
154
+ "AMPLIFY_APP_ID",
155
+ ];
156
+
157
+ function isCI(): boolean {
158
+ return CI_VARS.some((name) => {
159
+ const value = envVar(name).toLowerCase();
160
+ return value !== "" && value !== "false" && value !== "0";
161
+ });
162
+ }
163
+
164
+ /** Tydlig ruta på stderr, syns även i långa bygg-loggar. */
165
+ function warnBox(lines: string[]) {
166
+ const width = Math.max(...lines.map((l) => l.length));
167
+ const border = "─".repeat(width + 2);
168
+ const out = [`┌${border}┐`, ...lines.map((l) => `│ ${l.padEnd(width)} │`), `└${border}┘`];
169
+ console.error(c.yellowErr(out.join("\n")));
170
+ }
171
+
172
+ function findConfigPath(): string | null {
173
+ for (const name of CONFIG_NAMES) {
174
+ const path = resolve(cwd, name);
175
+ if (existsSync(path)) return path;
176
+ }
177
+ return null;
178
+ }
179
+
99
180
  function findConfig(): string {
100
181
  const explicit = option("config");
101
182
  if (explicit) {
@@ -103,11 +184,7 @@ function findConfig(): string {
103
184
  if (!existsSync(path)) fail(`Hittar inte ${explicit}.`);
104
185
  return path;
105
186
  }
106
- for (const name of CONFIG_NAMES) {
107
- const path = resolve(cwd, name);
108
- if (existsSync(path)) return path;
109
- }
110
- return fail(`Hittar ingen ${CONFIG_NAMES.slice(0, 1)} (eller .mjs/.js/.json) i ${cwd}.`);
187
+ return findConfigPath() ?? fail(`Hittar ingen ${CONFIG_NAMES[0]} (eller .mjs/.js/.json) i ${cwd}. Kör \`npx sitecms-next init\`.`);
111
188
  }
112
189
 
113
190
  async function loadConfig(path: string): Promise<SitecmsConfig> {
@@ -126,14 +203,14 @@ async function loadConfig(path: string): Promise<SitecmsConfig> {
126
203
 
127
204
  try {
128
205
  const mod = (await import(pathToFileURL(importPath).href)) as { default?: SitecmsConfig };
129
- if (!mod.default) fail(`${path} måste ha en default-export (export default defineConfig({...})).`);
206
+ if (!mod.default) fail(`${rel(path)} måste ha en default-export (export default defineConfig({...})).`);
130
207
  return mod.default!;
131
208
  } catch (err) {
132
209
  const code = (err as { code?: string }).code;
133
210
  // Äldre Node utan inbyggd TypeScript-stöd: kör om med --experimental-strip-types.
134
211
  if (code === "ERR_UNKNOWN_FILE_EXTENSION" && /\.m?ts$/.test(path) && !process.env.__SITECMS_REEXEC) {
135
212
  if (tempCopy) rmSync(tempCopy, { force: true });
136
- const r = spawnSync(process.execPath, ["--experimental-strip-types", "--no-warnings", process.argv[1], ...args], {
213
+ const r = spawnSync(process.execPath, ["--experimental-strip-types", "--no-warnings", CLI_FILE, ...args], {
137
214
  stdio: "inherit",
138
215
  env: { ...process.env, __SITECMS_REEXEC: "1" },
139
216
  });
@@ -145,34 +222,60 @@ async function loadConfig(path: string): Promise<SitecmsConfig> {
145
222
  }
146
223
  }
147
224
 
225
+ // ---------------------------------------------------------------------------
226
+ // sync / pull / check
227
+ // ---------------------------------------------------------------------------
228
+
148
229
  async function sync() {
149
230
  const env = readEnv();
150
231
  if (!env) {
232
+ if (isCI()) {
233
+ warnBox([
234
+ "⚠ sitecms: CMS_API_KEY saknas i byggmiljön.",
235
+ "",
236
+ "Innehållsstrukturen (sitecms.config) synkades INTE till sitecms,",
237
+ "och sajten kan inte hämta innehåll från sitecms utan nyckeln.",
238
+ "",
239
+ "Lägg in CMS_API_KEY som miljövariabel hos ditt webbhotell",
240
+ "(Vercel, Netlify, Cloudflare, egen server …) och deploya om.",
241
+ "Nyckeln finns under Integration för sajten i sitecms-panelen.",
242
+ ]);
243
+ } else {
244
+ console.error(c.yellowErr("⚠ CMS_API_KEY saknas (miljövariabel eller .env.local)."));
245
+ }
151
246
  if (flag("strict")) fail("Avbryter (--strict).");
152
- log(c.dim("Hoppar över schema-sync. Sätt variablerna (eller --strict för att låta bygget faila)."));
247
+ log(c.dim("Hoppar över schema-sync. Kör `npx sitecms-next init`, eller använd --strict för att låta bygget faila."));
153
248
  return;
154
249
  }
155
250
  const configPath = findConfig();
156
251
  const config = await loadConfig(configPath);
157
- const body = { version: 1, ...config, ...(flag("prune") ? { prune: true } : {}) };
252
+ // Sajtens adress skickas bara från produktionsbyggen: sitecms sätter
253
+ // revalidate-URL:en från den när den är tom, och en preview-adress skulle
254
+ // annars bli kvar för alltid.
255
+ const { siteUrl: site, skipped } = resolveSiteUrl(process.env);
256
+ const body = {
257
+ version: 1,
258
+ ...config,
259
+ ...(flag("prune") ? { prune: true } : {}),
260
+ ...(site ? { siteUrl: site.url } : {}),
261
+ };
158
262
 
159
- log(c.dim(`sitecms: synkar ${configPath.replace(cwd + "/", "")} → ${env.apiUrl} (${env.site})`));
263
+ log(c.dim(`sitecms: synkar ${rel(configPath)} → ${describeTarget(env)}`));
264
+ if (site) log(c.dim(`sitecms: sajtens adress ${site.url} (från ${site.source})`));
265
+ for (const s of skipped) log(c.dim(`sitecms: ${s.source} skickas inte som sajtens adress (${s.reason}).`));
266
+ const previewSkipped = !site && skipped.some((s) => s.reason !== "ogiltig adress");
160
267
  const { status, json } = await api(env, "POST", "/schema", body);
161
268
 
162
269
  if (status !== 200 || !json?.ok) {
163
- console.error(c.red(`✖ Schema-sync misslyckades (HTTP ${status}): ${String(json?.error ?? "okänt fel")}`));
164
270
  const issues = Array.isArray(json?.issues) ? (json!.issues as unknown[]) : [];
165
- for (const issue of issues) {
166
- const text = typeof issue === "string" ? issue : JSON.stringify(issue);
167
- console.error(c.red(` • ${text}`));
168
- }
169
- process.exit(1);
271
+ const lines = issues.map((issue) => ` • ${typeof issue === "string" ? issue : JSON.stringify(issue)}`);
272
+ fail([`Schema-sync misslyckades (HTTP ${status}): ${String(json?.error ?? "okänt fel")}`, ...lines].join("\n"));
170
273
  }
171
274
 
172
- const created = json.created as { pages: number; blocks: number };
173
- const updated = json.updated as { pages: number; blocks: number };
174
- const pruned = (json.pruned as { pages: number; blocks: number } | undefined) ?? { pages: 0, blocks: 0 };
175
- const orphans = (json.orphans as { pageSlug: string; key: string }[] | undefined) ?? [];
275
+ const created = json!.created as { pages: number; blocks: number };
276
+ const updated = json!.updated as { pages: number; blocks: number };
277
+ const pruned = (json!.pruned as { pages: number; blocks: number } | undefined) ?? { pages: 0, blocks: 0 };
278
+ const orphans = (json!.orphans as { pageSlug: string; key: string }[] | undefined) ?? [];
176
279
 
177
280
  log(
178
281
  c.green("✔ ") +
@@ -185,37 +288,499 @@ async function sync() {
185
288
  for (const o of orphans.slice(0, 20)) log(c.yellow(` • ${o.pageSlug} / ${o.key}`));
186
289
  if (orphans.length > 20) log(c.yellow(` … och ${orphans.length - 20} till`));
187
290
  }
291
+
292
+ if (typeof json!.revalidateUrl === "string" && json!.revalidateUrl) {
293
+ // Maskas: en deploy hook-URL är en hemlighet och byggloggar kan vara publika.
294
+ log(c.green("✔ ") + `Revalidate-URL: ${maskRevalidateUrl(json!.revalidateUrl)}`);
295
+ } else if (json!.revalidateUrl === null && (site || isCI())) {
296
+ log(c.yellow("⚠ Ingen revalidate-URL i sitecms — ändringar syns först vid nästa deploy."));
297
+ log(
298
+ c.dim(
299
+ site
300
+ ? ` ${site.url} godtogs inte (måste vara en publik https-adress). Fyll i URL:en under Integration i panelen.`
301
+ : previewSkipped
302
+ ? " Preview-bygge: sajtens adress skickas bara från produktionsbygget. Sätt SITE_URL=https://din-domän.se\n" +
303
+ " i produktionsmiljön, eller fyll i URL:en under Integration i panelen."
304
+ : " Sätt SITE_URL=https://din-domän.se i byggmiljön, eller fyll i URL:en under Integration i panelen.",
305
+ ),
306
+ );
307
+ }
188
308
  }
189
309
 
190
310
  async function pull() {
191
- const env = readEnv() ?? fail("Kan inte hämta strukturen utan miljövariablerna.");
311
+ const env = readEnv() ?? fail("CMS_API_KEY saknas. Kör `npx sitecms-next init` eller sätt CMS_API_KEY.");
192
312
  const { status, json } = await api(env, "GET", "/schema");
193
313
  if (status !== 200) fail(`HTTP ${status}: ${String(json?.error ?? "okänt fel")}`);
194
314
  log(JSON.stringify(json, null, 2));
195
315
  }
196
316
 
317
+ /** Skriver ut webhook-status från health (om sitecms-versionen skickar den). */
318
+ function printWebhookStatus(health: Partial<Health>) {
319
+ if (!("revalidateUrl" in health) && !health.webhook) return; // äldre sitecms
320
+ const url = health.revalidateUrl;
321
+ if (!url) {
322
+ log(c.yellow("⚠ Ingen revalidate-URL — ändringar syns först vid nästa deploy."));
323
+ log(c.dim(" Fyll i den under Integration i sitecms-panelen (eller kör sync i byggmiljön med SITE_URL satt)."));
324
+ return;
325
+ }
326
+ const w = health.webhook;
327
+ let last = "inget anrop ännu";
328
+ if (w?.lastStatus === "ok") last = `ok${w.lastAt ? ` (${w.lastAt})` : ""}`;
329
+ else if (w?.lastStatus === "failed") last = `failed${w.lastError ? ` (${maskUrlsInText(w.lastError)})` : ""}`;
330
+ // Maskas: en deploy hook-URL är en hemlighet och loggar kan vara publika.
331
+ const line = `Revalidate-URL: ${maskRevalidateUrl(url)} — senaste anrop: ${last}`;
332
+ log(w?.lastStatus === "failed" ? c.yellow(`⚠ ${line}`) : c.green("✔ ") + line);
333
+ }
334
+
197
335
  async function check() {
198
- const env = readEnv() ?? fail("Sätt CMS_API_URL, CMS_SITE och CMS_API_KEY.");
336
+ const env =
337
+ readEnv() ?? fail("CMS_API_KEY saknas. Kör `npx sitecms-next init` eller sätt CMS_API_KEY (miljövariabel eller .env.local).");
199
338
  const { status, json } = await api(env, "GET", "/health");
339
+ if (status === 401) fail(`API-nyckeln godkändes inte av ${describeTarget(env)} (HTTP 401): ${String(json?.error ?? "")}`);
200
340
  if (status !== 200) fail(`HTTP ${status}: ${String(json?.error ?? "okänt fel")}`);
201
- const site = json?.site as { name: string; slug: string };
202
- log(c.green("✔ ") + `Ansluten till "${site.name}" (${site.slug}) — ${json?.pages} sidor, senaste sync: ${json?.lastSchemaSyncAt ?? "aldrig"}.`);
341
+ const health = json as unknown as Health;
342
+ log(
343
+ c.green("✔ ") +
344
+ `Ansluten till "${health.site.name}" (${health.site.slug}) via ${env.apiUrl} — ${health.pages} sidor, senaste sync: ${health.lastSchemaSyncAt ?? "aldrig"}.`,
345
+ );
346
+ printWebhookStatus(health);
347
+ }
348
+
349
+ // ---------------------------------------------------------------------------
350
+ // init
351
+ // ---------------------------------------------------------------------------
352
+
353
+ function readPackageJson(path: string): JsonObject | null {
354
+ if (!existsSync(path)) return null;
355
+ try {
356
+ return parsePackageJson(readFileSync(path, "utf8")).data;
357
+ } catch (err) {
358
+ return fail(
359
+ `${rel(path)} är inte giltig JSON (${err instanceof Error ? err.message : String(err)}).\n` +
360
+ " Rätta filen och kör init igen — inget har ändrats.",
361
+ );
362
+ }
363
+ }
364
+
365
+ function dependencies(pkg: JsonObject | null): Record<string, string> {
366
+ return {
367
+ ...((pkg?.dependencies as Record<string, string> | undefined) ?? {}),
368
+ ...((pkg?.devDependencies as Record<string, string> | undefined) ?? {}),
369
+ };
370
+ }
371
+
372
+ function ownVersion(): string {
373
+ try {
374
+ const pkg = JSON.parse(readFileSync(resolve(dirname(CLI_FILE), "../package.json"), "utf8")) as { version?: string };
375
+ return pkg.version ?? "0.3.0";
376
+ } catch {
377
+ return "0.3.0";
378
+ }
379
+ }
380
+
381
+ async function promptKey(): Promise<string> {
382
+ if (!process.stdin.isTTY) {
383
+ fail(
384
+ "Ingen API-nyckel angiven.\n" +
385
+ " Kör `npx sitecms-next init <nyckel>` eller sätt CMS_API_KEY i miljön/.env.local.\n" +
386
+ " Nyckeln finns under Integration för sajten i sitecms-panelen.",
387
+ );
388
+ }
389
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
390
+ try {
391
+ const answer = (await rl.question("API-nyckel (Integration för sajten i sitecms-panelen): ")).trim();
392
+ return answer || fail("Ingen nyckel angiven.");
393
+ } finally {
394
+ rl.close();
395
+ }
396
+ }
397
+
398
+ async function confirm(question: string): Promise<boolean> {
399
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
400
+ try {
401
+ return /^(j|ja|y|yes)$/i.test((await rl.question(`${question} [j/N] `)).trim());
402
+ } finally {
403
+ rl.close();
404
+ }
405
+ }
406
+
407
+ function today(): string {
408
+ const d = new Date();
409
+ const pad = (n: number) => String(n).padStart(2, "0");
410
+ return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;
411
+ }
412
+
413
+ /** Enkel .gitignore-matchning för filer i projektroten. */
414
+ function gitignoreMatches(pattern: string, file: string): boolean {
415
+ if (pattern.endsWith("/")) return false;
416
+ const p = pattern.replace(/^\//, "").replace(/^\*\*\//, "");
417
+ if (p.includes("/")) return false;
418
+ const source = p
419
+ .split("")
420
+ .map((ch) => (ch === "*" ? "[^/]*" : ch === "?" ? "[^/]" : ch.replace(/[.+^${}()|[\]\\]/g, "\\$&")))
421
+ .join("");
422
+ return new RegExp(`^${source}$`).test(file);
423
+ }
424
+
425
+ function ensureGitignore(path: string): "created" | "appended" | "ok" {
426
+ if (!existsSync(path)) {
427
+ writeFileSync(path, ".env.local\n");
428
+ return "created";
429
+ }
430
+ const text = readFileSync(path, "utf8");
431
+ const covered = text
432
+ .split(/\r?\n/)
433
+ .map((l) => l.trim())
434
+ .filter((l) => l && !l.startsWith("#") && !l.startsWith("!"))
435
+ .some((p) => gitignoreMatches(p, ".env.local"));
436
+ if (covered) return "ok";
437
+ const eol = text.includes("\r\n") ? "\r\n" : "\n";
438
+ const sep = text === "" || text.endsWith("\n") ? "" : eol;
439
+ writeFileSync(path, `${text}${sep}.env.local${eol}`);
440
+ return "appended";
441
+ }
442
+
443
+ type SchemaPageLike = {
444
+ slug: string;
445
+ title: string;
446
+ description?: string | null;
447
+ blocks?: { key: string; type?: string; label?: string | null; help?: string | null; default?: string }[];
448
+ };
449
+
450
+ const EXAMPLE_PAGES: SchemaPageLike[] = [
451
+ {
452
+ slug: "home",
453
+ title: "Startsida",
454
+ blocks: [
455
+ { key: "hero.title", label: "Rubrik", help: "Max 60 tecken", default: "Välkommen" },
456
+ { key: "hero.image", type: "image", label: "Hero-bild" },
457
+ { key: "intro.body", type: "richtext", label: "Ingress" },
458
+ ],
459
+ },
460
+ ];
461
+
462
+ function renderConfig(pages: SchemaPageLike[], fromSchema: boolean): string {
463
+ const s = (v: string) => JSON.stringify(v);
464
+ const out = [`import { defineConfig } from "sitecms-next";`, ""];
465
+ out.push(
466
+ fromSchema
467
+ ? "// Skapad av `sitecms-next init` från strukturen som redan finns i sitecms."
468
+ : "// Exempel skapat av `sitecms-next init` — byt mot sajtens egna sidor och fält.",
469
+ "// `sitecms-next sync` (körs före varje bygge) skapar det som saknas i sitecms.",
470
+ "// Kundens innehåll skrivs aldrig över.",
471
+ "export default defineConfig({",
472
+ " pages: [",
473
+ );
474
+ for (const page of pages) {
475
+ out.push(" {", ` slug: ${s(page.slug)},`, ` title: ${s(page.title)},`);
476
+ if (page.description) out.push(` description: ${s(page.description)},`);
477
+ out.push(" blocks: [");
478
+ for (const b of page.blocks ?? []) {
479
+ const fields = [`key: ${s(b.key)}`];
480
+ if (b.type && b.type !== "text") fields.push(`type: ${s(b.type)}`);
481
+ if (b.label) fields.push(`label: ${s(b.label)}`);
482
+ if (b.help) fields.push(`help: ${s(b.help)}`);
483
+ if (b.default) fields.push(`default: ${s(b.default)}`);
484
+ out.push(` { ${fields.join(", ")} },`);
485
+ }
486
+ out.push(" ],", " },");
487
+ }
488
+ out.push(" ],", "});", "");
489
+ return out.join("\n");
490
+ }
491
+
492
+ function installCommand(): { cmd: string; args: string[] } {
493
+ // cmd.exe tolkar ^ som escape-tecken utanför citattecken.
494
+ const spec = process.platform === "win32" ? `"sitecms-next@^${ownVersion()}"` : `sitecms-next@^${ownVersion()}`;
495
+ const has = (f: string) => existsSync(resolve(cwd, f));
496
+ if (has("pnpm-lock.yaml")) return { cmd: "pnpm", args: ["add", spec] };
497
+ if (has("yarn.lock")) return { cmd: "yarn", args: ["add", spec] };
498
+ if (has("bun.lockb") || has("bun.lock")) return { cmd: "bun", args: ["add", spec] };
499
+ return { cmd: "npm", args: ["install", spec] };
500
+ }
501
+
502
+ /** Var CMS_SITE kommer ifrån: miljön, eller .env.local/.env. */
503
+ function cmsSiteSource(): string {
504
+ if (shellEnv.has("CMS_SITE")) return "miljön";
505
+ const where: string[] = [];
506
+ for (const file of [".env.local", ".env"]) {
507
+ const path = resolve(cwd, file);
508
+ if (existsSync(path) && envFileValues(readFileSync(path, "utf8"), "CMS_SITE").some(Boolean)) where.push(file);
509
+ }
510
+ return where.length ? where.join(" och ") : "miljön";
511
+ }
512
+
513
+ async function init() {
514
+ const done: string[] = [];
515
+ const skipped: string[] = [];
516
+ const notes: string[] = [];
517
+ const force = flag("force");
518
+
519
+ // 1. package.json kontrolleras (och parsas) innan något skrivs, så att ett
520
+ // fel aldrig lämnar ett halvfärdigt resultat efter sig.
521
+ const pkgPath = resolve(cwd, "package.json");
522
+ let pkg = readPackageJson(pkgPath);
523
+ if (!pkg && !force) {
524
+ fail(
525
+ `Hittar ingen package.json i ${cwd}.\n` +
526
+ " Kör `npx sitecms-next init` i projektets rotkatalog (där package.json finns).\n" +
527
+ " Vill du ändå bara spara CMS_API_KEY i .env.local här: lägg till --force.",
528
+ );
529
+ }
530
+
531
+ // 2. Nyckel: argument → CMS_API_KEY (miljö/.env.local) → fråga.
532
+ const key = (positionals[1] ?? "").trim() || envVar("CMS_API_KEY") || (await promptKey());
533
+
534
+ // 3. Validera mot sitecms. Allt init gör använder nyckel-routerna
535
+ // (/api/v1/site/…), aldrig CMS_SITE: en ny nyckel för en annan sajt får
536
+ // inte krocka med en gammal CMS_SITE.
537
+ const keyEnv: Env = { apiUrl: (envVar("CMS_API_URL") || DEFAULT_API_URL).replace(/\/+$/, ""), site: "", apiKey: key };
538
+ log(c.dim(`sitecms: kontrollerar nyckeln mot ${keyEnv.apiUrl} …`));
539
+ const health = await api(keyEnv, "GET", "/health");
540
+ if (health.status === 401) {
541
+ fail(
542
+ "API-nyckeln godkändes inte av sitecms (HTTP 401).\n" +
543
+ " Kopiera nyckeln igen under Integration för sajten i sitecms-panelen och kör\n" +
544
+ " `npx sitecms-next init <nyckel>`.",
545
+ );
546
+ }
547
+ if (health.status !== 200 || !health.json?.ok) {
548
+ fail(`Kunde inte verifiera nyckeln (HTTP ${health.status}): ${String(health.json?.error ?? "okänt fel")}`);
549
+ }
550
+ const info = health.json as unknown as Health;
551
+ log(c.green("✔ ") + `Nyckeln gäller sajten "${info.site.name}" (${info.site.slug}).`);
552
+
553
+ // 4. 0.2-projekt: CMS_SITE gör att sajten använder slug-routerna.
554
+ const cmsSite = envVar("CMS_SITE");
555
+ if (cmsSite) {
556
+ const where = cmsSiteSource();
557
+ const lines =
558
+ cmsSite === info.site.slug
559
+ ? [
560
+ `⚠ CMS_SITE=${cmsSite} är satt (${where}).`,
561
+ "",
562
+ "Den behövs inte längre — nyckeln identifierar sajten. Med CMS_SITE satt",
563
+ "använder sajten de äldre slug-routerna (fungerar, men ta gärna bort",
564
+ `CMS_SITE från ${where} och hos webbhotellet).`,
565
+ ]
566
+ : [
567
+ `⚠ CMS_SITE=${cmsSite} är satt (${where}), men nyckeln gäller sajten "${info.site.slug}".`,
568
+ "",
569
+ "Med CMS_SITE satt hämtar sajten innehåll via /api/v1/sites/" + cmsSite + "/…,",
570
+ "och den nya nyckeln godkänns inte där. Ta bort CMS_SITE från",
571
+ `${where} och hos webbhotellet — nyckeln identifierar sajten.`,
572
+ "(init använder nyckeln och påverkas inte.)",
573
+ ];
574
+ warnBox(lines);
575
+ notes.push(`Ta bort CMS_SITE (${where} och hos webbhotellet) — nyckeln identifierar sajten.`);
576
+ }
577
+
578
+ // 5. En annan CMS_API_KEY i .env.local ersätts bara efter bekräftelse.
579
+ const envPath = resolve(cwd, ".env.local");
580
+ const envText = existsSync(envPath) ? readFileSync(envPath, "utf8") : null;
581
+ const otherKeys = envText === null ? [] : envFileValues(envText, "CMS_API_KEY").filter((v) => v !== key);
582
+ if (otherKeys.length && !force) {
583
+ const question = `.env.local har redan en annan CMS_API_KEY (${shortKey(otherKeys[0])}). Ersätta den? Den gamla raden kommenteras ut.`;
584
+ if (!process.stdin.isTTY) {
585
+ fail(
586
+ `.env.local har redan en annan CMS_API_KEY (${shortKey(otherKeys[0])}).\n` +
587
+ " Kör med --force för att ersätta den (den gamla raden kommenteras ut, inget raderas).\n" +
588
+ " Inget har ändrats.",
589
+ );
590
+ }
591
+ if (!(await confirm(question))) fail("Avbrutet — inget har ändrats.");
592
+ }
593
+
594
+ process.env.CMS_API_KEY = key;
595
+
596
+ // 6. .env.local
597
+ const envEdit = upsertEnvText(envText, "CMS_API_KEY", key, today());
598
+ if (envEdit.result !== "unchanged") writeFileSync(envPath, envEdit.text);
599
+ if (envEdit.result === "created") done.push(".env.local (CMS_API_KEY)");
600
+ else if (envEdit.result === "appended") done.push("CMS_API_KEY i .env.local");
601
+ else if (envEdit.result === "replaced") done.push("CMS_API_KEY i .env.local (ny nyckel; den gamla raden är utkommenterad)");
602
+ else skipped.push("CMS_API_KEY i .env.local (fanns redan)");
603
+
604
+ // 7. .gitignore
605
+ const gitResult = ensureGitignore(resolve(cwd, ".gitignore"));
606
+ if (gitResult === "created") done.push(".gitignore (med .env.local)");
607
+ else if (gitResult === "appended") done.push(".env.local i .gitignore");
608
+ else skipped.push(".gitignore (täcker redan .env.local)");
609
+
610
+ // 8. Projekttyp
611
+ const appDir = existsSync(resolve(cwd, "src/app")) ? "src/app" : existsSync(resolve(cwd, "app")) ? "app" : null;
612
+ const isAppRouter = Boolean(dependencies(pkg).next) && appDir !== null;
613
+ const useTs = existsSync(resolve(cwd, "tsconfig.json"));
614
+
615
+ // 9. Paketet (behövs för revalidate-routen och configen)
616
+ if (pkg) {
617
+ const current = dependencies(pkg)["sitecms-next"];
618
+ const outdated = typeof current === "string" && /^[\^~>=v\s]*0\.[0-2](\.|$)/.test(current);
619
+ if (current && !outdated) {
620
+ skipped.push(`sitecms-next i package.json (${current})`);
621
+ } else if (flag("no-install")) {
622
+ notes.push(`Installera paketet: npm install sitecms-next@^${ownVersion()}`);
623
+ } else {
624
+ const { cmd, args: installArgs } = installCommand();
625
+ log(c.dim(`sitecms: ${cmd} ${installArgs.join(" ")}`));
626
+ const r = spawnSync(cmd, installArgs, { stdio: "inherit", shell: process.platform === "win32" });
627
+ if (r.status === 0) {
628
+ done.push(`sitecms-next@^${ownVersion()} (${cmd})`);
629
+ pkg = readPackageJson(pkgPath);
630
+ } else {
631
+ notes.push(`Installationen misslyckades — kör: ${cmd} ${installArgs.join(" ")}`);
632
+ }
633
+ }
634
+ }
635
+
636
+ // 10. Revalidate-route (bara Next.js App Router)
637
+ if (isAppRouter) {
638
+ const routeDir = resolve(cwd, appDir!, "api/sitecms/revalidate");
639
+ const existing = ["route.ts", "route.tsx", "route.js", "route.jsx", "route.mjs"].find((f) => existsSync(join(routeDir, f)));
640
+ if (existing) {
641
+ skipped.push(`${rel(join(routeDir, existing))} (fanns redan)`);
642
+ } else {
643
+ const routePath = join(routeDir, useTs ? "route.ts" : "route.js");
644
+ mkdirSync(routeDir, { recursive: true });
645
+ writeFileSync(
646
+ routePath,
647
+ [
648
+ "// sitecms anropar den här routen när kunden sparar; cachen töms och sajten",
649
+ "// visar det nya innehållet direkt. Anropet är signerat med CMS_API_KEY.",
650
+ 'export { POST } from "sitecms-next/revalidate";',
651
+ "",
652
+ ].join("\n"),
653
+ );
654
+ done.push(rel(routePath));
655
+ }
656
+ }
657
+
658
+ // 11. sitecms.config (+ prebuild + sync) — bara i Node-projekt
659
+ let configPath = findConfigPath();
660
+ let syncOk: boolean | null = null;
661
+ if (!pkg) {
662
+ notes.push("Ingen package.json (--force) — hoppade över paketet, revalidate-routen, sitecms.config, prebuild och sync.");
663
+ } else {
664
+ if (configPath) {
665
+ skipped.push(`${rel(configPath)} (fanns redan)`);
666
+ } else {
667
+ const schema = await api(keyEnv, "GET", "/schema").catch(() => null);
668
+ const pages = schema?.status === 200 && Array.isArray(schema.json?.pages) ? (schema.json!.pages as SchemaPageLike[]) : [];
669
+ const fromSchema = pages.length > 0;
670
+ configPath = resolve(cwd, useTs ? "sitecms.config.ts" : "sitecms.config.mjs");
671
+ writeFileSync(configPath, renderConfig(fromSchema ? pages : EXAMPLE_PAGES, fromSchema));
672
+ done.push(
673
+ `${rel(configPath)} (${fromSchema ? `${pages.length} ${pages.length === 1 ? "sida" : "sidor"} från sitecms` : "exempel"})`,
674
+ );
675
+ }
676
+
677
+ const prebuild = addSyncToPrebuild(readFileSync(pkgPath, "utf8"));
678
+ if (prebuild.result === "ok") {
679
+ skipped.push(`prebuild (scripts.${prebuild.foundIn} kör redan sitecms-next sync)`);
680
+ } else {
681
+ writeFileSync(pkgPath, prebuild.text);
682
+ done.push(
683
+ prebuild.result === "added" ? '"prebuild": "sitecms-next sync" i package.json' : "sitecms-next sync i befintlig prebuild",
684
+ );
685
+ }
686
+ if (existsSync(resolve(cwd, ".yarnrc.yml")) && (prebuild.result !== "ok" || prebuild.foundIn === "prebuild")) {
687
+ notes.push('Yarn 2+ kör inte prebuild — ändra build till "sitecms-next sync && next build".');
688
+ }
689
+
690
+ // 12. Synka direkt (egen process: läser .env.local och configen som ett
691
+ // vanligt bygge). CMS_SITE="" → nyckel-routerna även om en gammal
692
+ // CMS_SITE finns kvar (en tom variabel skrivs inte över från .env.local).
693
+ log("");
694
+ const r = spawnSync(process.execPath, [CLI_FILE, "sync"], {
695
+ stdio: "inherit",
696
+ env: { ...process.env, CMS_API_KEY: key, CMS_SITE: "" },
697
+ });
698
+ syncOk = r.status === 0;
699
+ if (!syncOk) notes.push("Synken misslyckades (se ovan). Rätta och kör `npx sitecms-next sync`.");
700
+ }
701
+
702
+ // 13. Sammanfattning
703
+ log("");
704
+ log(c.bold(`sitecms är kopplat till "${info.site.name}".`));
705
+ if (done.length) {
706
+ log("");
707
+ log(" Skapat/uppdaterat:");
708
+ for (const d of done) log(` ${c.green("✔")} ${d}`);
709
+ }
710
+ if (skipped.length) {
711
+ log("");
712
+ log(" Hoppade över:");
713
+ for (const s of skipped) log(c.dim(` • ${s}`));
714
+ }
715
+ if (notes.length) {
716
+ log("");
717
+ for (const n of notes) log(c.yellow(` ⚠ ${n}`));
718
+ }
719
+ log("");
720
+ if (isAppRouter) {
721
+ if (info.revalidateUrl) {
722
+ log(` Revalidate-URL i sitecms: ${maskRevalidateUrl(info.revalidateUrl)}`);
723
+ } else {
724
+ log(" Revalidate-URL:en sätts automatiskt när produktionsbygget körs hos webbhotellet (om det");
725
+ log(" anger sajtens adress; annars sätt SITE_URL=https://din-domän.se eller fyll i");
726
+ log(" https://din-domän.se/api/sitecms/revalidate under Integration i panelen).");
727
+ }
728
+ } else if (pkg) {
729
+ log(" Det här ser inte ut som ett Next.js-projekt med App Router (ingen next i package.json");
730
+ log(" eller ingen app-katalog), så ingen revalidate-route skapades. Skapa i stället en");
731
+ log(" deploy hook (build hook) hos ditt webbhotell och klistra in dess URL som revalidate-URL");
732
+ log(" under Integration i sitecms-panelen — då byggs sajten om när kunden sparar.");
733
+ }
734
+ log("");
735
+ log(
736
+ c.bold("Nästa steg: ") +
737
+ "Lägg CMS_API_KEY=… som miljövariabel hos ditt webbhotell (Vercel, Netlify, Cloudflare, egen server …) och deploya.",
738
+ );
739
+ if (syncOk === false) process.exitCode = 1;
203
740
  }
204
741
 
205
742
  function help() {
206
- log(`sitecms-next — koppla en Next.js-sajt till sitecms
743
+ log(`sitecms-next — koppla en sajt till sitecms
207
744
 
745
+ sitecms-next init [nyckel] [--force] [--no-install]
746
+ Kopplar projektet: verifierar API-nyckeln, sparar CMS_API_KEY i
747
+ .env.local, skapar revalidate-routen (Next.js App Router) och
748
+ sitecms.config.ts, lägger till "prebuild": "sitecms-next sync" och synkar.
749
+ Körs i katalogen med package.json (--force: spara ändå bara nyckeln).
750
+ Kan köras flera gånger. Revalidate-routen och sitecms.config skrivs
751
+ aldrig över; .env.local, .gitignore och package.json kompletteras med
752
+ en rad var utan att annat ändras. En annan CMS_API_KEY i .env.local
753
+ ersätts bara efter bekräftelse eller med --force, och den gamla raden
754
+ kommenteras ut i stället för att raderas.
208
755
  sitecms-next sync [--prune] [--strict] [--config <fil>]
209
756
  Skickar sitecms.config.ts till sitecms. Saknade sidor och fält skapas,
210
- kundens innehåll skrivs aldrig över. Saknas miljövariablerna hoppas
211
- steget över (exit 0) om inte --strict anges.
757
+ kundens innehåll skrivs aldrig över. Saknas CMS_API_KEY hoppas steget
758
+ över (exit 0, med varning i CI) om inte --strict anges.
212
759
  sitecms-next pull Skriver ut strukturen som finns i sitecms (JSON).
213
- sitecms-next check Verifierar CMS_API_URL, CMS_SITE och CMS_API_KEY.
760
+ sitecms-next check Verifierar nyckeln och visar webhook-status.
214
761
 
215
- Dokumentation: https://sitecms-zeta.vercel.app/docs`);
762
+ Miljövariabler
763
+ CMS_API_KEY Krävs. Finns under Integration i sitecms-panelen.
764
+ CMS_API_URL Valfri, default ${DEFAULT_API_URL}.
765
+ CMS_SITE Valfri (äldre slug-routes, som 0.2.x).
766
+ CMS_REVALIDATE_SECRET Valfri (äldre revalidate-hemlighet).
767
+ SITE_URL Valfri. Sajtens adress; skickas vid sync så att
768
+ sitecms kan sätta revalidate-URL:en (om den är tom).
769
+ Utan SITE_URL/CMS_SITE_URL används webbhotellets
770
+ adress, men bara i produktionsbyggen:
771
+ VERCEL_PROJECT_PRODUCTION_URL (VERCEL_ENV=production),
772
+ URL på Netlify (CONTEXT=production) och
773
+ RENDER_EXTERNAL_URL (inte pull request-previews).
774
+
775
+ Dokumentation: ${DOCS_URL}`);
216
776
  }
217
777
 
218
778
  loadEnvFiles();
219
- const commands: Record<string, () => Promise<void> | void> = { sync, pull, check, help };
779
+ const commands: Record<string, () => Promise<void> | void> = { init, sync, pull, check, help };
220
780
  const run = commands[command] ?? (() => fail(`Okänt kommando "${command}". Kör sitecms-next help.`));
221
- Promise.resolve(run()).catch((err: unknown) => fail(err instanceof Error ? err.message : String(err)));
781
+ Promise.resolve()
782
+ .then(run)
783
+ .catch((err: unknown) => {
784
+ console.error(c.red(`✖ ${err instanceof Error ? err.message : String(err)}`));
785
+ process.exit(1);
786
+ });