@hszrdm/create-commerce 1.10.1 → 1.11.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/README.md +70 -46
  2. package/package.json +1 -1
  3. package/src/cli.mjs +23 -4
  4. package/src/upgrade.mjs +248 -22
  5. package/templates/backend/.env.example +8 -0
  6. package/templates/backend/package.json +1 -1
  7. package/templates/backend/scripts/commerce-instance-status.mjs +135 -0
  8. package/templates/backend/scripts/commerce-ops.mjs +58 -2
  9. package/templates/backend/scripts/core-restore.mjs +40 -5
  10. package/templates/backend/scripts/lib/core-backup-common.mjs +91 -11
  11. package/templates/backend/scripts/production-assets/backup.sh +6 -51
  12. package/templates/backend/scripts/production-assets/deploy.sh +10 -62
  13. package/templates/backend/scripts/production-assets/install.sh +23 -195
  14. package/templates/backend/scripts/production-assets/restore.sh +17 -66
  15. package/templates/storefront/package.json +5 -1
  16. package/templates/storefront/src/app/checkout/success/page.tsx +2 -0
  17. package/templates/storefront/src/app/globals.css +32 -0
  18. package/templates/storefront/src/app/layout.tsx +7 -1
  19. package/templates/storefront/src/app/legal/page.tsx +3 -3
  20. package/templates/storefront/src/components/analytics.tsx +10 -8
  21. package/templates/storefront/src/components/checkout-flow.tsx +539 -75
  22. package/templates/storefront/src/components/fogyasztobarat-embed.tsx +6 -2
  23. package/templates/storefront/src/components/google-analytics-purchase.tsx +33 -0
  24. package/templates/storefront/src/components/stripe-payment.tsx +186 -62
  25. package/templates/storefront/src/lib/core/checkout-addresses.ts +166 -0
  26. package/templates/storefront/src/lib/core/checkout.ts +12 -0
  27. package/templates/storefront/src/lib/core/commerce.ts +12 -2
  28. package/templates/storefront/src/lib/core/company-tax.ts +132 -0
  29. package/templates/storefront/src/lib/core/ga4-bootstrap.ts +35 -0
  30. package/templates/storefront/src/lib/core/legal.ts +1 -0
  31. package/templates/storefront/src/lib/core/public-error.ts +1 -0
  32. package/templates/storefront/src/lib/core/stripe-checkout-phase.ts +23 -0
  33. package/templates/storefront/src/lib/core/tracking.ts +11 -2
  34. package/templates/storefront/tests/checkout-addresses.test.mjs +148 -0
  35. package/templates/storefront/tests/company-tax.test.mjs +68 -0
  36. package/templates/storefront/tests/ga4-bootstrap.test.mjs +74 -0
  37. package/templates/storefront/tests/stripe-checkout-phase.test.mjs +92 -0
package/README.md CHANGED
@@ -39,64 +39,88 @@ my-shop/
39
39
 
40
40
  The `deploy/` directory and `ecosystem.config.cjs` are materialized automatically during the first `npm install`. If the generator is run with `--skip-install`, running `npm install` later creates them.
41
41
 
42
- ## Existing customer webshop upgrades
42
+ ## Core upgrades and customer-owned frontends
43
43
 
44
- An upgrade is **not** the same operation as redeploying an unchanged customer
45
- repository. The generator owns shared dependencies and starter files; each
46
- customer owns its business-specific code, styling, secrets and infrastructure.
44
+ **Backend Core** is the versioned `@hszrdm/core` npm dependency. The customer
45
+ adds Medusa modules, APIs, workflows, jobs and subscribers under
46
+ `backend/src/project/`. The generator's `prepare:project` step exposes them
47
+ through standard Medusa paths without duplicating the Core implementation.
47
48
 
48
- After publishing the new matching `@hszrdm/core` and
49
- `@hszrdm/create-commerce` versions, run **in the customer's Git checkout**
50
- (not on the production VPS):
49
+ **Reference frontend** lives under `starters/storefront-next/` in the Core
50
+ repository. Each generated `storefront/` is **customer-owned**: the customer
51
+ can build their own branding, layouts and pages. Changing or releasing the
52
+ reference frontend does not automatically overwrite customer files.
53
+
54
+ Backend upgrades and frontend synchronization are **separate operations**.
55
+ Run them in a clean Git checkout on a feature branch, not the live VPS.
56
+ First publish matching `@hszrdm/core` and `@hszrdm/create-commerce` versions.
57
+
58
+ ### 1. Upgrade Core backend independently
51
59
 
52
60
  ```bash
53
- # Preview changes; never writes to the repository or database:
54
61
  npx @hszrdm/create-commerce@<new-version> upgrade --dir .
55
-
56
- # After reviewing and resolving any conflicts:
62
+ # Review the UPDATE, REVIEW and CONFLICT output:
57
63
  npx @hszrdm/create-commerce@<new-version> upgrade --dir . --apply
64
+ npm ci
65
+ npm run verify
66
+ git diff --check
67
+ ```
68
+
69
+ The backend command updates verified, unchanged starter infrastructure,
70
+ package versions (including older shops that pin Core at workspace and root
71
+ level), the Core-owned npm root security overrides, and the lockfile. It
72
+ preserves `backend/src/project/` and customer-owned files. Production backup entry points (`deploy/backup.sh` and `backend/scripts/production-assets/backup.sh`) always remain customer-owned and appear as `REVIEW` even when an older manifest tracks them, because automatic replacement could switch the backup format or environment contract. Changed or
73
+ untracked backend starter overlays are kept unchanged and marked `REVIEW`
74
+ for compatibility checks. Unsafe paths, mismatched Core pins and overridden
75
+ security pins are `CONFLICT` and block application. **Never deploy before
76
+ resolving compatibility reviews and running the full test suite.**
77
+
78
+ The backend command deliberately does **not** modify `storefront/` or
79
+ `storefront/package.json`. Updating the backend package and database
80
+ migrations does not, by itself, guarantee custom frontend compatibility.
81
+
82
+ ### 2. Compare and optionally sync the reference frontend
83
+
84
+ ```bash
85
+ npx @hszrdm/create-commerce@<new-version> frontend:sync --dir .
86
+ # Optional unified diffs for modified client files:
87
+ npx @hszrdm/create-commerce@<new-version> frontend:sync --dir . --diff
88
+ # Explicit opt-in: copies only provably unmodified reference files and
89
+ # adds missing reference files; leaves customer-modified paths untouched.
90
+ npx @hszrdm/create-commerce@<new-version> frontend:sync --dir . --apply
58
91
 
59
- # Confirm the regenerated complete npm dependency tree:
60
92
  npm ci
61
93
  npm run verify
62
94
  git diff --check
63
- git add package.json package-lock.json backend storefront deploy scripts ecosystem.config.cjs hszrdm-commerce.json hszrdm-managed.json
64
- git commit -m "chore: upgrade HSZRDM Commerce"
65
- git push
66
95
  ```
67
96
 
68
- Newly generated projects also expose `npm run upgrade:core` for the **dry run**
69
- and `npm run upgrade:core -- --apply` to apply the latest released generator
70
- templates. Use an explicit `@<new-version>` instead of `@latest` for
71
- reproducible production change requests.
72
-
73
- The updater synchronizes the canonical backend and storefront dependencies,
74
- their scripts and shared template files, generated deployment utilities, PM2
75
- configuration, and regenerates the **full transitive** `package-lock.json`.
76
- It also synchronizes the Core's **root npm `overrides`** (Lodash, GraphQL
77
- Tools and Nodemailer security pins), because npm uses overrides only from the
78
- customer project's root manifest. Customer-only overrides are preserved; a
79
- modified Core-managed override reports a conflict rather than being overwritten.
80
- Use `npm audit --omit=dev --audit-level=high` after the lockfile refresh and
81
- review any remaining Medusa transitive vulnerabilities before production.
82
- It preserves customer-only package dependencies, routes, application code,
83
- customized files, and secret-bearing `.env*` files. Nothing modifies the
84
- database, running PM2 processes, or the live deployment during this operation.
85
-
86
- To avoid losing customer changes, the updater keeps `hszrdm-managed.json`
87
- with the last generated file hashes and dependency baseline. When a customer
88
- has edited a managed file or dependency, it **blocks** and reports a conflict
89
- to merge manually; it never silently overwrites such changes.
90
-
91
- **Existing older shops:** Shops created before the managed-file manifest
92
- cannot safely auto-merge older, customized starter files. A dry run lists
93
- the conflicts. Resolve them explicitly and establish a reviewed baseline;
94
- do not use the new-project `--force` option on an existing shop, because that
95
- option deletes the destination.
96
-
97
- The production deploy then checks out the committed customer release and
98
- uses `npm ci` against its committed lockfile. Merely publishing a new Core
99
- package does not update existing customer checkouts automatically.
97
+ The preview lists `SAFE` files, `REVIEW` customer changes and
98
+ `PACKAGE REVIEW` Next/React dependency differences. Existing customer edits
99
+ and deleted files with known baselines are never force-restored. The frontend
100
+ package dependencies, theme, layout and any modified pages/components remain
101
+ owned by the customer and must be reconciled manually where necessary.
102
+ The preview/apply does not bump `hszrdm-commerce.json` Core backend version,
103
+ touch the DB, change secrets or deploy anything.
104
+
105
+ The `hszrdm-managed.json` manifest stores the last accepted file hashes;
106
+ frontend baselines are not falsely advanced by a backend-only upgrade.
107
+ Avoid re-baselining modified customer files as if they were canonical.
108
+
109
+ New projects expose `npm run upgrade:core` and `npm run sync:frontend`
110
+ as previews, with `npm run <script> -- --apply` for the explicit operation.
111
+ For reproducible releases pin the generator version, not `@latest`.
112
+
113
+ ### 3. Review, commit and deploy
114
+
115
+ Commit `package.json`, `package-lock.json`, `backend/`,
116
+ `storefront/`, `hszrdm-commerce.json` and `hszrdm-managed.json` only
117
+ after reviewing all changes and passing `npm run verify`. Test checkout,
118
+ payments, order fulfillment, shipping and customer modules in staging, then
119
+ deploy the committed customer branch.
120
+
121
+ Legacy shops without a reliable manifest must **not** treat customized
122
+ starter files as Core-owned. Run previews first and manually review existing
123
+ overlays. Never use `--force` to regenerate an existing webshop.
100
124
 
101
125
  ## Production commands
102
126
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hszrdm/create-commerce",
3
- "version": "1.10.1",
3
+ "version": "1.11.1",
4
4
  "description": "Create a complete HSZRDM Commerce webshop project.",
5
5
  "license": "UNLICENSED",
6
6
  "type": "module",
package/src/cli.mjs CHANGED
@@ -4,6 +4,8 @@ import {
4
4
  cpSync,
5
5
  existsSync,
6
6
  mkdirSync,
7
+ lstatSync,
8
+ readdirSync,
7
9
  readFileSync,
8
10
  rmSync,
9
11
  writeFileSync,
@@ -12,7 +14,7 @@ import { dirname, join, resolve } from "node:path"
12
14
  import { fileURLToPath } from "node:url"
13
15
  import { createInterface } from "node:readline/promises"
14
16
  import { stdin as input, stdout as output } from "node:process"
15
- import { generatedRootScripts, generatedRootOverrides, writeGeneratedManifest, upgradeFromArgs, renderEcosystemConfig } from "./upgrade.mjs"
17
+ import { generatedRootScripts, generatedRootOverrides, writeGeneratedManifest, upgradeFromArgs, frontendSyncFromArgs, renderEcosystemConfig } from "./upgrade.mjs"
16
18
 
17
19
  const packageRoot = resolve(dirname(fileURLToPath(import.meta.url)), "..")
18
20
  const packageVersion = clean(
@@ -24,6 +26,10 @@ export async function main(argv = process.argv.slice(2)) {
24
26
  upgradeFromArgs(argv.slice(1), packageVersion)
25
27
  return
26
28
  }
29
+ if (argv[0] === "frontend:sync") {
30
+ frontendSyncFromArgs(argv.slice(1), packageVersion)
31
+ return
32
+ }
27
33
  const parsed = parseArgs(argv)
28
34
  if (parsed.flags.help || parsed.flags.h) {
29
35
  printHelp()
@@ -35,9 +41,20 @@ export async function main(argv = process.argv.slice(2)) {
35
41
 
36
42
  const destination = resolve(parsed.flags.dir || projectName)
37
43
  const force = bool(parsed.flags.force)
38
- if (existsSync(destination)) {
39
- if (!force) throw new Error(`A célkönyvtár már létezik: ${destination}. Tudatos felülíráshoz: --force`)
40
- rmSync(destination, { recursive: true, force: true })
44
+ const targetStat = lstatSync(destination, { throwIfNoEntry: false })
45
+ if (targetStat) {
46
+ if (!targetStat.isDirectory() || targetStat.isSymbolicLink()) {
47
+ throw new Error(`A cél nem egy valódi könyvtár (vagy szimbolikus link): ${destination}`)
48
+ }
49
+ // --force must NEVER destroy a customer checkout, data or secrets.
50
+ // Existing projects are updated by the non-destructive upgrade command.
51
+ if (readdirSync(destination).length > 0) {
52
+ throw new Error(
53
+ `A célkönyvtár nem üres, ezért nem írható felül: ${destination}. ` +
54
+ "Meglévő webshophoz használd a create-commerce upgrade parancsot."
55
+ )
56
+ }
57
+ if (!force) throw new Error(`A célkönyvtár már létezik: ${destination}. Üres célhoz add meg a --force kapcsolót.`)
41
58
  }
42
59
 
43
60
  const settings = await collectSettings(projectName, parsed.flags)
@@ -236,6 +253,8 @@ function configureProject(root, settings) {
236
253
  mkdirSync(join(root, "scripts"), { recursive: true })
237
254
  cpSync(join(root, "backend", "scripts", "commerce-ops.mjs"),
238
255
  join(root, "scripts", "commerce-ops.mjs"))
256
+ cpSync(join(root, "backend", "scripts", "commerce-instance-status.mjs"),
257
+ join(root, "scripts", "commerce-instance-status.mjs"))
239
258
  // Materialize generated operational assets before recording their baseline.
240
259
  // Future Core upgrades can then replace only unchanged, Core-owned files.
241
260
  mkdirSync(join(root, "deploy"), { recursive: true })
package/src/upgrade.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  import { createHash } from "node:crypto"
2
- import { execFileSync } from "node:child_process"
2
+ import { execFileSync, spawnSync } from "node:child_process"
3
3
  import { cpSync, existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs"
4
4
  import { tmpdir } from "node:os"
5
5
  import { dirname, join, resolve } from "node:path"
@@ -7,7 +7,25 @@ import { fileURLToPath } from "node:url"
7
7
 
8
8
  const PACKAGE_ROOT = resolve(dirname(fileURLToPath(import.meta.url)), "..")
9
9
  const MANIFEST = "hszrdm-managed.json"
10
- const MANAGED_EXTRA_FILES = ["ecosystem.config.cjs", "scripts/commerce-ops.mjs", ...["install.sh", "deploy.sh", "backup.sh", "restore.sh"].map(name => "deploy/" + name)]
10
+ const isFrontend = path => path.startsWith("storefront/")
11
+ // Production backup entry points have deployment-specific env and backup formats.
12
+ // Even when a historical manifest marks them generator-owned, overwriting them
13
+ // could silently switch the customer backup format or break rollback readiness.
14
+ const CUSTOMER_BACKUP_ENTRYPOINTS = new Set([
15
+ "backend/scripts/production-assets/backup.sh",
16
+ "deploy/backup.sh",
17
+ ])
18
+ // The production deployment contract and customer's build/test runners can
19
+ // depend on customer-only scripts and environment selection. Never change
20
+ // these entry points during a backend Core dependency upgrade, including when
21
+ // they were marked managed in an older manifest.
22
+ const CUSTOMER_OWNED_SCRIPT_KEYS = new Set([
23
+ "package.json:test",
24
+ "package.json:deploy:production",
25
+ "backend/package.json:verify:build",
26
+ ])
27
+ const isCustomerOwnedScript = (path, key) => CUSTOMER_OWNED_SCRIPT_KEYS.has(path + ":" + key)
28
+ const MANAGED_EXTRA_FILES = ["ecosystem.config.cjs", "scripts/commerce-ops.mjs", "scripts/commerce-instance-status.mjs", ...["install.sh", "deploy.sh", "backup.sh", "restore.sh"].map(name => "deploy/" + name)]
11
29
  const SKIP_SEGMENTS = new Set(["node_modules", ".next", ".medusa", ".cache", ".git", "out", "static"])
12
30
  const SKIP_FILES = new Set(["package.json", "package-lock.json", ".env", ".env.production", ".env.staging", ".env.local", ".env.docker"])
13
31
 
@@ -82,8 +100,9 @@ export function generatedRootScripts() {
82
100
  "dev:backend": "npm --workspace backend run dev",
83
101
  "dev:storefront": "npm --workspace storefront run dev",
84
102
  "typecheck": "npm --workspace backend run typecheck && npm --workspace storefront run typecheck",
85
- "test": "npm --workspace backend run test",
103
+ "test": "npm --workspace backend run test && npm --workspace storefront run test:addresses && npm --workspace storefront run test:stripe && npm --workspace storefront run test:company-tax",
86
104
  "build": "npm --workspace backend run verify:build && npm --workspace storefront run build",
105
+ "build:deploy": "npm --workspace backend run build && npm --workspace storefront run build",
87
106
  "verify": "npm run typecheck && npm run test && npm run build",
88
107
  "db:migrate": "npm --workspace backend run db:migrate",
89
108
  "core:init": "npm --workspace backend run core:init --",
@@ -96,6 +115,7 @@ export function generatedRootScripts() {
96
115
  "deploy:prod": "node ./scripts/commerce-ops.mjs deploy prod",
97
116
  "deploy:staging": "node ./scripts/commerce-ops.mjs deploy staging",
98
117
  "deploy:production": "npm run deploy:prod",
118
+ "commerce:status": "node ./scripts/commerce-instance-status.mjs",
99
119
  "backup:dev": "node ./scripts/commerce-ops.mjs backup dev",
100
120
  "backup:prod": "node ./scripts/commerce-ops.mjs backup prod",
101
121
  "backup:staging": "node ./scripts/commerce-ops.mjs backup staging",
@@ -105,6 +125,28 @@ export function generatedRootScripts() {
105
125
  "docker:up": "docker compose --env-file .env.docker up -d --wait",
106
126
  "docker:down": "docker compose --env-file .env.docker down",
107
127
  "upgrade:core": "npx --yes @hszrdm/create-commerce@latest upgrade --dir .",
128
+ "sync:frontend": "npx --yes @hszrdm/create-commerce@latest frontend:sync --dir .",
129
+ }
130
+ }
131
+
132
+ // A generated-project upgrade may update customer files, but must never
133
+ // traverse a symlink into an unrelated checkout, secret store or upload root.
134
+ function assertManagedTarget(root, relativePath) {
135
+ if (!relativePath || relativePath.startsWith("/") ||
136
+ relativePath.split("/").some(part => !part || part === "." || part === "..")) {
137
+ throw new Error("Invalid managed target: " + relativePath)
138
+ }
139
+ const resolvedRoot = resolve(root)
140
+ if (lstatSync(resolvedRoot, { throwIfNoEntry: false })?.isSymbolicLink()) {
141
+ throw new Error("Symlink project root is not supported for Core upgrades.")
142
+ }
143
+ let current = resolvedRoot
144
+ for (const part of relativePath.split("/")) {
145
+ current = join(current, part)
146
+ const info = lstatSync(current, { throwIfNoEntry: false })
147
+ if (info?.isSymbolicLink()) {
148
+ throw new Error("Symlink in managed upgrade path: " + relativePath)
149
+ }
108
150
  }
109
151
  }
110
152
 
@@ -113,7 +155,7 @@ function json(value) { return JSON.stringify(value, null, 2) + "\n" }
113
155
  function sha(data) { return createHash("sha256").update(data).digest("hex") }
114
156
  function hashFile(path) { return sha(readFileSync(path)) }
115
157
  function canonicalSource(path) {
116
- if (path === "scripts/commerce-ops.mjs") return join(PACKAGE_ROOT, "templates", "backend", "scripts", "commerce-ops.mjs")
158
+ if (path === "scripts/commerce-ops.mjs" || path === "scripts/commerce-instance-status.mjs") return join(PACKAGE_ROOT, "templates", "backend", "scripts", path.slice("scripts/".length))
117
159
  if (path.startsWith("deploy/")) return join(PACKAGE_ROOT, "templates", "backend", "scripts", "production-assets", path.slice("deploy/".length))
118
160
  return join(PACKAGE_ROOT, "templates", path)
119
161
  }
@@ -169,6 +211,7 @@ export function writeGeneratedManifest(root, version) {
169
211
  writeFileSync(join(root, MANIFEST), json({
170
212
  schema_version: 1,
171
213
  generator_version: version,
214
+ frontend_reference_version: version,
172
215
  files,
173
216
  packages: managedPackageState(root),
174
217
  }))
@@ -200,10 +243,19 @@ export function planUpgrade(root, version) {
200
243
  }
201
244
  const previous = existsSync(join(root, MANIFEST)) ? readJson(join(root, MANIFEST)) : null
202
245
  if (previous && previous.schema_version !== 1) throw new Error("Unknown managed manifest version.")
203
- const conflicts = [], changes = [], files = {}
204
- const canonicalPaths = managedPaths()
246
+ const conflicts = [], reviews = [], changes = [], files = {}
247
+ const canonicalPaths = managedPaths().filter(path => !isFrontend(path) && !CUSTOMER_BACKUP_ENTRYPOINTS.has(path))
205
248
  const canonicalSet = new Set(canonicalPaths)
249
+ for (const path of CUSTOMER_BACKUP_ENTRYPOINTS) {
250
+ if (existsSync(join(root, path))) {
251
+ reviews.push(path + " (backup entry point; customer-owned; review production backup migration manually)")
252
+ }
253
+ }
206
254
  for (const path of canonicalPaths) {
255
+ try { assertManagedTarget(root, path) } catch (error) {
256
+ conflicts.push(path + " (" + error.message + ")")
257
+ continue
258
+ }
207
259
  const source = path === "ecosystem.config.cjs" ? null : canonicalSource(path)
208
260
  const target = join(root, path)
209
261
  const metadata = path === "ecosystem.config.cjs" ? readJson(metadataPath) : null
@@ -222,41 +274,63 @@ export function planUpgrade(root, version) {
222
274
  const known = previous?.files?.[path]
223
275
  if (currentHash === desiredHash) {
224
276
  files[path] = currentHash
225
- } else if (currentHash === null || (known && known === currentHash)) {
277
+ } else if ((currentHash === null && !known) || (known && known === currentHash)) {
226
278
  changes.push({ kind: "file", path, content: desired })
227
279
  files[path] = desiredHash
228
280
  } else {
229
- conflicts.push(path + " (customer-modified or missing baseline)")
281
+ // Preserve project-owned overlays. Warn for manual compatibility review,
282
+ // but do not block an independent @hszrdm/core package upgrade.
283
+ reviews.push(path + " (customer-modified or missing baseline; kept unchanged)")
284
+ if (known) files[path] = known
230
285
  }
231
286
  }
232
287
 
233
288
  // Remove files retired from the canonical starter only when their original
234
289
  // content is unchanged; never remove customer-modified files.
235
290
  for (const [path, previousHash] of Object.entries(previous?.files || {})) {
236
- if (canonicalSet.has(path)) continue
291
+ if (isFrontend(path) || CUSTOMER_BACKUP_ENTRYPOINTS.has(path) || canonicalSet.has(path)) continue
292
+ try { assertManagedTarget(root, path) } catch (error) {
293
+ conflicts.push(path + " (" + error.message + ")")
294
+ continue
295
+ }
237
296
  const target = join(root, path)
238
297
  const stat = lstatSync(target, { throwIfNoEntry: false })
239
298
  if (!stat) continue
240
299
  if (stat.isFile() && hashFile(target) === previousHash) {
241
300
  changes.push({ kind: "delete", path })
242
301
  } else {
243
- conflicts.push(path + " (obsolete file modified by customer)")
302
+ reviews.push(path + " (obsolete file modified by customer; kept unchanged)")
244
303
  files[path] = previousHash
245
304
  }
246
305
  }
247
306
 
248
- const packages = {}
249
- for (const path of ["package.json", "backend/package.json", "storefront/package.json"]) {
307
+ const packages = { ...(previous?.packages || {}) }
308
+ const oldCoreVersion = readJson(metadataPath).core_version
309
+ for (const path of ["package.json", "backend/package.json"]) {
310
+ assertManagedTarget(root, path)
250
311
  const current = readJson(join(root, path))
251
312
  const desired = expectedPackage(path, version)
313
+ // Older projects may have @hszrdm/core at both workspace and root level.
314
+ if (path === "package.json" && current.dependencies?.["@hszrdm/core"]) {
315
+ desired.dependencies = { "@hszrdm/core": version }
316
+ }
252
317
  const base = previous?.packages?.[path]
253
318
  const merged = structuredClone(current)
254
319
  merged.scripts ||= {}
255
320
  for (const [key, nextValue] of Object.entries(desired.scripts || {})) {
321
+ // Existing customer entry points are not backend Core ownership.
322
+ if (isCustomerOwnedScript(path, key) && current.scripts[key] !== undefined) {
323
+ if (current.scripts[key] !== nextValue) {
324
+ reviews.push(path + ":scripts." + key + " (customer entry point; kept unchanged)")
325
+ }
326
+ continue
327
+ }
256
328
  const oldValue = base?.scripts?.[key]
329
+ // Missing ownership in an existing manifest means customer-owned, not
330
+ // permission to overwrite it on the next idempotent upgrade.
257
331
  if (current.scripts[key] !== nextValue && current.scripts[key] !== undefined &&
258
- (!base || (oldValue !== undefined && current.scripts[key] !== oldValue))) {
259
- conflicts.push(path + ":scripts." + key)
332
+ (oldValue === undefined || current.scripts[key] !== oldValue)) {
333
+ reviews.push(path + ":scripts." + key + " (customer script; kept unchanged)")
260
334
  } else merged.scripts[key] = nextValue
261
335
  }
262
336
  for (const group of ["dependencies", "devDependencies", "optionalDependencies", "peerDependencies"]) {
@@ -265,8 +339,10 @@ export function planUpgrade(root, version) {
265
339
  for (const [key, nextValue] of Object.entries(managed)) {
266
340
  const currentValue = current[group]?.[key]
267
341
  const oldValue = base?.deps?.[group]?.[key]
268
- if (currentValue !== nextValue && currentValue !== undefined &&
269
- (!base || (oldValue !== undefined && currentValue !== oldValue))) {
342
+ const trackedCorePin = key === "@hszrdm/core" && typeof oldCoreVersion === "string" &&
343
+ currentValue === oldCoreVersion
344
+ if (currentValue !== nextValue && currentValue !== undefined && !trackedCorePin &&
345
+ (oldValue === undefined || currentValue !== oldValue)) {
270
346
  conflicts.push(path + ":" + group + "." + key)
271
347
  } else merged[group][key] = nextValue
272
348
  }
@@ -274,7 +350,7 @@ export function planUpgrade(root, version) {
274
350
  for (const [key, oldValue] of Object.entries(base?.deps?.[group] || {})) {
275
351
  if (key in managed || !(key in merged[group])) continue
276
352
  if (merged[group][key] === oldValue) delete merged[group][key]
277
- else conflicts.push(path + ":obsolete " + group + "." + key)
353
+ else reviews.push(path + ":obsolete " + group + "." + key + " (customer dependency; kept unchanged)")
278
354
  }
279
355
  }
280
356
  // Root npm overrides are the only reliable way to pin deeply nested
@@ -299,9 +375,12 @@ export function planUpgrade(root, version) {
299
375
  const oldContent = readFileSync(join(root, path), "utf8")
300
376
  if (json(merged) !== oldContent) changes.push({ kind: "json", path, content: json(merged) })
301
377
  packages[path] = {
302
- scripts: Object.fromEntries(Object.entries(desired.scripts || {}).map(([k]) => [k, merged.scripts[k]])),
378
+ // Never mark a customer-modified setting as generator-owned.
379
+ scripts: Object.fromEntries(Object.entries(desired.scripts || {})
380
+ .filter(([k, v]) => !isCustomerOwnedScript(path, k) && merged.scripts[k] === v)),
303
381
  deps: Object.fromEntries(["dependencies", "devDependencies", "optionalDependencies", "peerDependencies"].map(k => [
304
- k, Object.fromEntries(Object.keys(desired[k] || {}).map(dep => [dep, merged[k][dep]])),
382
+ k, Object.fromEntries(Object.entries(desired[k] || {})
383
+ .filter(([dep, v]) => merged[k][dep] === v)),
305
384
  ])),
306
385
  ...(path === "package.json" ? {
307
386
  overrides: Object.fromEntries(Object.keys(desired.overrides || {}).map(key => [key, merged.overrides[key]])),
@@ -309,21 +388,133 @@ export function planUpgrade(root, version) {
309
388
  }
310
389
  }
311
390
 
312
- return { root, version, previous, changes, conflicts, nextManifest: {
391
+ return { root, version, previous, changes, conflicts, reviews, nextManifest: {
313
392
  schema_version: 1,
314
393
  generator_version: version,
394
+ frontend_reference_version: previous?.frontend_reference_version || previous?.generator_version || version,
315
395
  files: Object.fromEntries([
316
- ...Object.entries(previous?.files || {}).filter(([path]) => canonicalSet.has(path)),
396
+ ...Object.entries(previous?.files || {}).filter(([path]) => isFrontend(path) || CUSTOMER_BACKUP_ENTRYPOINTS.has(path) || canonicalSet.has(path)),
317
397
  ...Object.entries(files),
318
398
  ]),
319
399
  packages,
320
400
  } }
321
401
  }
322
402
 
403
+
404
+ /**
405
+ * The reference frontend is an editable customer-owned application, not a
406
+ * backend upgrade dependency. Sync its unchanged files in an explicit step;
407
+ * modified and untracked files are reported for manual integration.
408
+ */
409
+ export function planFrontendSync(root, version) {
410
+ if (!existsSync(join(root, "hszrdm-commerce.json")) ||
411
+ !existsSync(join(root, "storefront/package.json"))) {
412
+ throw new Error("This is not a generated HSZRDM Commerce project.")
413
+ }
414
+ const previous = existsSync(join(root, MANIFEST)) ? readJson(join(root, MANIFEST)) : null
415
+ if (previous && previous.schema_version !== 1) throw new Error("Unknown managed manifest version.")
416
+ const conflicts = [], reviews = [], changes = [], files = {}
417
+ const canonicalPaths = managedPaths().filter(isFrontend)
418
+ const canonicalSet = new Set(canonicalPaths)
419
+ for (const path of canonicalPaths) {
420
+ try { assertManagedTarget(root, path) } catch (error) {
421
+ conflicts.push(path + " (" + error.message + ")")
422
+ continue
423
+ }
424
+ const desired = readFileSync(canonicalSource(path))
425
+ const target = join(root, path)
426
+ const stat = lstatSync(target, { throwIfNoEntry: false })
427
+ if (stat && !stat.isFile()) {
428
+ conflicts.push(path + " (not a regular file; refusing to overwrite)")
429
+ continue
430
+ }
431
+ const actualHash = stat ? hashFile(target) : null
432
+ const desiredHash = sha(desired)
433
+ const baseline = previous?.files?.[path]
434
+ if (actualHash === desiredHash) {
435
+ files[path] = desiredHash
436
+ } else if ((actualHash === null && !baseline) || (baseline && actualHash === baseline)) {
437
+ changes.push({ kind: "file", path, content: desired })
438
+ files[path] = desiredHash
439
+ } else {
440
+ reviews.push(path + (actualHash === null
441
+ ? " (customer-deleted; do not recreate automatically)"
442
+ : " (customer-modified or unknown baseline; integrate manually)"))
443
+ }
444
+ }
445
+ // Never automatically delete a customer route or component because the
446
+ // reference frontend retired it.
447
+ for (const path of Object.keys(previous?.files || {})) {
448
+ if (isFrontend(path) && !canonicalSet.has(path) && existsSync(join(root, path))) {
449
+ reviews.push(path + " (removed from reference; review manually)")
450
+ }
451
+ }
452
+ // Dependencies and scripts of the storefront belong to the customer. List
453
+ // differences, but never force Next/React upgrades through Core deploys.
454
+ const currentPackage = readJson(join(root, "storefront/package.json"))
455
+ const referencePackage = expectedPackage("storefront/package.json", version)
456
+ const packageReview = []
457
+ for (const group of ["dependencies", "devDependencies"]) {
458
+ for (const [name, expected] of Object.entries(referencePackage[group] || {})) {
459
+ const actual = currentPackage[group]?.[name]
460
+ if (actual !== expected) packageReview.push(group + "." + name + ": " +
461
+ (actual ?? "(missing)") + " → " + expected)
462
+ }
463
+ }
464
+ return { root, version, previous, changes, conflicts, reviews, packageReview, nextManifest: {
465
+ schema_version: 1,
466
+ generator_version: previous?.generator_version || version,
467
+ frontend_reference_version: version,
468
+ files: { ...(previous?.files || {}), ...files },
469
+ packages: previous?.packages || {},
470
+ } }
471
+ }
472
+
473
+ export function applyFrontendSync(plan, { execute = true } = {}) {
474
+ if (execute && readJson(join(plan.root, "hszrdm-commerce.json")).core_version !== plan.version) {
475
+ throw new Error("Reference frontend sync requires the matching Core backend version; upgrade the backend first.")
476
+ }
477
+ if (plan.conflicts.length) throw new Error("Frontend sync blocked by unsafe targets:\\n- " + plan.conflicts.join("\\n- "))
478
+ if (!execute) return plan
479
+ const staged = [...plan.changes, { kind: "json", path: MANIFEST, content: json(plan.nextManifest) }]
480
+ for (const item of staged) assertManagedTarget(plan.root, item.path)
481
+ const backupDir = mkdtempSync(join(tmpdir(), "hszrdm-frontend-rollback-"))
482
+ const originals = []
483
+ try {
484
+ for (const item of staged) {
485
+ const target = join(plan.root, item.path)
486
+ const existed = existsSync(target)
487
+ if (existed) {
488
+ if (!lstatSync(target).isFile()) throw new Error("Cannot overwrite non-regular file: " + item.path)
489
+ const original = join(backupDir, item.path)
490
+ mkdirSync(dirname(original), { recursive: true })
491
+ cpSync(target, original)
492
+ }
493
+ originals.push({ path: item.path, target, existed })
494
+ mkdirSync(dirname(target), { recursive: true })
495
+ writeFileSync(target, item.content)
496
+ }
497
+ } catch (error) {
498
+ for (const item of originals.reverse()) {
499
+ if (item.existed) cpSync(join(backupDir, item.path), item.target)
500
+ else rmSync(item.target, { force: true })
501
+ }
502
+ throw error
503
+ } finally {
504
+ rmSync(backupDir, { force: true, recursive: true })
505
+ }
506
+ console.log("Reference frontend sync prepared. Review customer overlays and run the full frontend test/build suite.")
507
+ return plan
508
+ }
509
+
323
510
  export function applyUpgrade(plan, { execute = true } = {}) {
324
511
  if (plan.conflicts.length) throw new Error("Upgrade blocked by customer changes:\n- " + plan.conflicts.join("\n- "))
325
512
  if (!execute) return plan
326
513
  const staged = [...plan.changes, { kind: "json", path: MANIFEST, content: json(plan.nextManifest) }]
514
+ // Preflight every file that can be modified, before the first write.
515
+ for (const change of staged) assertManagedTarget(plan.root, change.path)
516
+ assertManagedTarget(plan.root, "hszrdm-commerce.json")
517
+ assertManagedTarget(plan.root, "package-lock.json")
327
518
  const metadataPath = join(plan.root, "hszrdm-commerce.json")
328
519
  const metadata = readJson(metadataPath)
329
520
  metadata.core_version = plan.version
@@ -372,9 +563,11 @@ export function upgradeFromArgs(args, version) {
372
563
  const root = resolve(inline ? inline.slice(6) : index >= 0 ? args[index + 1] : ".")
373
564
  const plan = planUpgrade(root, version)
374
565
  console.log(`HSZRDM Commerce upgrade ${plan.previous?.generator_version || "legacy"} → ${version}`)
375
- console.log(`Changes: ${plan.changes.length}; conflicts: ${plan.conflicts.length}`)
566
+ console.log(`Backend/infra changes: ${plan.changes.length}; reviews: ${plan.reviews.length}; blocking conflicts: ${plan.conflicts.length}`)
376
567
  for (const c of plan.changes) console.log("UPDATE", c.path)
568
+ for (const c of plan.reviews) console.warn("REVIEW", c)
377
569
  for (const c of plan.conflicts) console.error("CONFLICT", c)
570
+ console.log("Customer storefront files were not touched; use frontend:sync to preview reference updates.")
378
571
  if (!args.includes("--apply")) {
379
572
  console.log("DRY RUN: no changes made. Use --apply after reviewing the plan.")
380
573
  if (plan.conflicts.length) process.exitCode = 2
@@ -382,3 +575,36 @@ export function upgradeFromArgs(args, version) {
382
575
  }
383
576
  return applyUpgrade(plan)
384
577
  }
578
+
579
+ export function frontendSyncFromArgs(args, version) {
580
+ const index = args.indexOf("--dir")
581
+ const inline = args.find(x => x.startsWith("--dir="))
582
+ const root = resolve(inline ? inline.slice(6) : index >= 0 ? args[index + 1] : ".")
583
+ const plan = planFrontendSync(root, version)
584
+ console.log(`HSZRDM reference frontend sync → ${version}`)
585
+ console.log(`Safe updates: ${plan.changes.length}; manual reviews: ${plan.reviews.length}; unsafe targets: ${plan.conflicts.length}`)
586
+ for (const item of plan.changes) console.log("SAFE", item.path)
587
+ for (const item of plan.reviews) console.warn("REVIEW", item)
588
+ for (const item of plan.packageReview) console.warn("PACKAGE REVIEW", item)
589
+ for (const item of plan.conflicts) console.error("CONFLICT", item)
590
+ if (args.includes("--diff")) {
591
+ for (const item of plan.reviews) {
592
+ const path = item.split(" (")[0]
593
+ if (!isFrontend(path)) continue
594
+ const current = join(root, path)
595
+ const reference = canonicalSource(path)
596
+ if (!existsSync(current) || !existsSync(reference)) continue
597
+ try { assertManagedTarget(root, path) } catch { continue }
598
+ const result = spawnSync("git", ["diff", "--no-index", "--", current, reference],
599
+ { cwd: root, encoding: "utf8", maxBuffer: 8 * 1024 * 1024 })
600
+ if (result.status === 1 && result.stdout) console.log(result.stdout)
601
+ else if (result.status !== 0) console.warn("DIFF UNAVAILABLE", path)
602
+ }
603
+ }
604
+ if (!args.includes("--apply")) {
605
+ console.log("DRY RUN: reference comparison only; use frontend:sync --apply to copy unchanged files.")
606
+ if (plan.conflicts.length) process.exitCode = 2
607
+ return plan
608
+ }
609
+ return applyFrontendSync(plan)
610
+ }