@hszrdm/create-commerce 1.11.0 → 1.11.2

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/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.11.0",
3
+ "version": "1.11.2",
4
4
  "description": "Create a complete HSZRDM Commerce webshop project.",
5
5
  "license": "UNLICENSED",
6
6
  "type": "module",
package/src/cli.mjs CHANGED
@@ -14,7 +14,7 @@ import { dirname, join, resolve } from "node:path"
14
14
  import { fileURLToPath } from "node:url"
15
15
  import { createInterface } from "node:readline/promises"
16
16
  import { stdin as input, stdout as output } from "node:process"
17
- import { generatedRootScripts, generatedRootOverrides, writeGeneratedManifest, upgradeFromArgs, renderEcosystemConfig } from "./upgrade.mjs"
17
+ import { generatedRootScripts, generatedRootOverrides, writeGeneratedManifest, upgradeFromArgs, frontendSyncFromArgs, renderEcosystemConfig } from "./upgrade.mjs"
18
18
 
19
19
  const packageRoot = resolve(dirname(fileURLToPath(import.meta.url)), "..")
20
20
  const packageVersion = clean(
@@ -26,6 +26,10 @@ export async function main(argv = process.argv.slice(2)) {
26
26
  upgradeFromArgs(argv.slice(1), packageVersion)
27
27
  return
28
28
  }
29
+ if (argv[0] === "frontend:sync") {
30
+ frontendSyncFromArgs(argv.slice(1), packageVersion)
31
+ return
32
+ }
29
33
  const parsed = parseArgs(argv)
30
34
  if (parsed.flags.help || parsed.flags.h) {
31
35
  printHelp()
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,6 +7,24 @@ 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 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)
10
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"])
@@ -107,6 +125,7 @@ export function generatedRootScripts() {
107
125
  "docker:up": "docker compose --env-file .env.docker up -d --wait",
108
126
  "docker:down": "docker compose --env-file .env.docker down",
109
127
  "upgrade:core": "npx --yes @hszrdm/create-commerce@latest upgrade --dir .",
128
+ "sync:frontend": "npx --yes @hszrdm/create-commerce@latest frontend:sync --dir .",
110
129
  }
111
130
  }
112
131
 
@@ -192,6 +211,7 @@ export function writeGeneratedManifest(root, version) {
192
211
  writeFileSync(join(root, MANIFEST), json({
193
212
  schema_version: 1,
194
213
  generator_version: version,
214
+ frontend_reference_version: version,
195
215
  files,
196
216
  packages: managedPackageState(root),
197
217
  }))
@@ -223,9 +243,14 @@ export function planUpgrade(root, version) {
223
243
  }
224
244
  const previous = existsSync(join(root, MANIFEST)) ? readJson(join(root, MANIFEST)) : null
225
245
  if (previous && previous.schema_version !== 1) throw new Error("Unknown managed manifest version.")
226
- const conflicts = [], changes = [], files = {}
227
- const canonicalPaths = managedPaths()
246
+ const conflicts = [], reviews = [], changes = [], files = {}
247
+ const canonicalPaths = managedPaths().filter(path => !isFrontend(path) && !CUSTOMER_BACKUP_ENTRYPOINTS.has(path))
228
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
+ }
229
254
  for (const path of canonicalPaths) {
230
255
  try { assertManagedTarget(root, path) } catch (error) {
231
256
  conflicts.push(path + " (" + error.message + ")")
@@ -249,18 +274,21 @@ export function planUpgrade(root, version) {
249
274
  const known = previous?.files?.[path]
250
275
  if (currentHash === desiredHash) {
251
276
  files[path] = currentHash
252
- } else if (currentHash === null || (known && known === currentHash)) {
277
+ } else if ((currentHash === null && !known) || (known && known === currentHash)) {
253
278
  changes.push({ kind: "file", path, content: desired })
254
279
  files[path] = desiredHash
255
280
  } else {
256
- 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
257
285
  }
258
286
  }
259
287
 
260
288
  // Remove files retired from the canonical starter only when their original
261
289
  // content is unchanged; never remove customer-modified files.
262
290
  for (const [path, previousHash] of Object.entries(previous?.files || {})) {
263
- if (canonicalSet.has(path)) continue
291
+ if (isFrontend(path) || CUSTOMER_BACKUP_ENTRYPOINTS.has(path) || canonicalSet.has(path)) continue
264
292
  try { assertManagedTarget(root, path) } catch (error) {
265
293
  conflicts.push(path + " (" + error.message + ")")
266
294
  continue
@@ -271,24 +299,38 @@ export function planUpgrade(root, version) {
271
299
  if (stat.isFile() && hashFile(target) === previousHash) {
272
300
  changes.push({ kind: "delete", path })
273
301
  } else {
274
- conflicts.push(path + " (obsolete file modified by customer)")
302
+ reviews.push(path + " (obsolete file modified by customer; kept unchanged)")
275
303
  files[path] = previousHash
276
304
  }
277
305
  }
278
306
 
279
- const packages = {}
280
- 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"]) {
281
310
  assertManagedTarget(root, path)
282
311
  const current = readJson(join(root, path))
283
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
+ }
284
317
  const base = previous?.packages?.[path]
285
318
  const merged = structuredClone(current)
286
319
  merged.scripts ||= {}
287
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
+ }
288
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.
289
331
  if (current.scripts[key] !== nextValue && current.scripts[key] !== undefined &&
290
- (!base || (oldValue !== undefined && current.scripts[key] !== oldValue))) {
291
- conflicts.push(path + ":scripts." + key)
332
+ (oldValue === undefined || current.scripts[key] !== oldValue)) {
333
+ reviews.push(path + ":scripts." + key + " (customer script; kept unchanged)")
292
334
  } else merged.scripts[key] = nextValue
293
335
  }
294
336
  for (const group of ["dependencies", "devDependencies", "optionalDependencies", "peerDependencies"]) {
@@ -297,8 +339,10 @@ export function planUpgrade(root, version) {
297
339
  for (const [key, nextValue] of Object.entries(managed)) {
298
340
  const currentValue = current[group]?.[key]
299
341
  const oldValue = base?.deps?.[group]?.[key]
300
- if (currentValue !== nextValue && currentValue !== undefined &&
301
- (!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)) {
302
346
  conflicts.push(path + ":" + group + "." + key)
303
347
  } else merged[group][key] = nextValue
304
348
  }
@@ -306,7 +350,7 @@ export function planUpgrade(root, version) {
306
350
  for (const [key, oldValue] of Object.entries(base?.deps?.[group] || {})) {
307
351
  if (key in managed || !(key in merged[group])) continue
308
352
  if (merged[group][key] === oldValue) delete merged[group][key]
309
- else conflicts.push(path + ":obsolete " + group + "." + key)
353
+ else reviews.push(path + ":obsolete " + group + "." + key + " (customer dependency; kept unchanged)")
310
354
  }
311
355
  }
312
356
  // Root npm overrides are the only reliable way to pin deeply nested
@@ -331,9 +375,12 @@ export function planUpgrade(root, version) {
331
375
  const oldContent = readFileSync(join(root, path), "utf8")
332
376
  if (json(merged) !== oldContent) changes.push({ kind: "json", path, content: json(merged) })
333
377
  packages[path] = {
334
- 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)),
335
381
  deps: Object.fromEntries(["dependencies", "devDependencies", "optionalDependencies", "peerDependencies"].map(k => [
336
- 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)),
337
384
  ])),
338
385
  ...(path === "package.json" ? {
339
386
  overrides: Object.fromEntries(Object.keys(desired.overrides || {}).map(key => [key, merged.overrides[key]])),
@@ -341,17 +388,125 @@ export function planUpgrade(root, version) {
341
388
  }
342
389
  }
343
390
 
344
- return { root, version, previous, changes, conflicts, nextManifest: {
391
+ return { root, version, previous, changes, conflicts, reviews, nextManifest: {
345
392
  schema_version: 1,
346
393
  generator_version: version,
394
+ frontend_reference_version: previous?.frontend_reference_version || previous?.generator_version || version,
347
395
  files: Object.fromEntries([
348
- ...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)),
349
397
  ...Object.entries(files),
350
398
  ]),
351
399
  packages,
352
400
  } }
353
401
  }
354
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
+
355
510
  export function applyUpgrade(plan, { execute = true } = {}) {
356
511
  if (plan.conflicts.length) throw new Error("Upgrade blocked by customer changes:\n- " + plan.conflicts.join("\n- "))
357
512
  if (!execute) return plan
@@ -408,9 +563,11 @@ export function upgradeFromArgs(args, version) {
408
563
  const root = resolve(inline ? inline.slice(6) : index >= 0 ? args[index + 1] : ".")
409
564
  const plan = planUpgrade(root, version)
410
565
  console.log(`HSZRDM Commerce upgrade ${plan.previous?.generator_version || "legacy"} → ${version}`)
411
- 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}`)
412
567
  for (const c of plan.changes) console.log("UPDATE", c.path)
568
+ for (const c of plan.reviews) console.warn("REVIEW", c)
413
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.")
414
571
  if (!args.includes("--apply")) {
415
572
  console.log("DRY RUN: no changes made. Use --apply after reviewing the plan.")
416
573
  if (plan.conflicts.length) process.exitCode = 2
@@ -418,3 +575,36 @@ export function upgradeFromArgs(args, version) {
418
575
  }
419
576
  return applyUpgrade(plan)
420
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
+ }
@@ -23,7 +23,7 @@
23
23
  "start:prod": "cd .medusa/server && medusa start"
24
24
  },
25
25
  "dependencies": {
26
- "@hszrdm/core": "1.11.0",
26
+ "@hszrdm/core": "1.11.2",
27
27
  "@medusajs/admin-sdk": "2.22.2",
28
28
  "@medusajs/cli": "2.22.2",
29
29
  "@medusajs/draft-order": "2.22.2",