@hszrdm/create-commerce 1.9.1 → 1.10.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.
package/README.md CHANGED
@@ -39,6 +39,65 @@ 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
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.
47
+
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):
51
+
52
+ ```bash
53
+ # Preview changes; never writes to the repository or database:
54
+ npx @hszrdm/create-commerce@<new-version> upgrade --dir .
55
+
56
+ # After reviewing and resolving any conflicts:
57
+ npx @hszrdm/create-commerce@<new-version> upgrade --dir . --apply
58
+
59
+ # Confirm the regenerated complete npm dependency tree:
60
+ npm ci
61
+ npm run verify
62
+ 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
+ ```
67
+
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.
100
+
42
101
  ## Production commands
43
102
 
44
103
  ### Fresh server install
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hszrdm/create-commerce",
3
- "version": "1.9.1",
3
+ "version": "1.10.1",
4
4
  "description": "Create a complete HSZRDM Commerce webshop project.",
5
5
  "license": "UNLICENSED",
6
6
  "type": "module",
package/src/cli.mjs CHANGED
@@ -12,6 +12,7 @@ import { dirname, join, resolve } from "node:path"
12
12
  import { fileURLToPath } from "node:url"
13
13
  import { createInterface } from "node:readline/promises"
14
14
  import { stdin as input, stdout as output } from "node:process"
15
+ import { generatedRootScripts, generatedRootOverrides, writeGeneratedManifest, upgradeFromArgs, renderEcosystemConfig } from "./upgrade.mjs"
15
16
 
16
17
  const packageRoot = resolve(dirname(fileURLToPath(import.meta.url)), "..")
17
18
  const packageVersion = clean(
@@ -19,6 +20,10 @@ const packageVersion = clean(
19
20
  )
20
21
 
21
22
  export async function main(argv = process.argv.slice(2)) {
23
+ if (argv[0] === "upgrade") {
24
+ upgradeFromArgs(argv.slice(1), packageVersion)
25
+ return
26
+ }
22
27
  const parsed = parseArgs(argv)
23
28
  if (parsed.flags.help || parsed.flags.h) {
24
29
  printHelp()
@@ -52,6 +57,7 @@ export async function main(argv = process.argv.slice(2)) {
52
57
  configureBackend(destination, settings)
53
58
  configureStorefront(destination, settings)
54
59
  writeMetadata(destination, settings)
60
+ writeGeneratedManifest(destination, packageVersion)
55
61
 
56
62
  if (!bool(parsed.flags["skip-install"])) {
57
63
  run("npm", ["install"], destination)
@@ -223,62 +229,21 @@ function configureProject(root, settings) {
223
229
  packageManager: "npm@10.9.4",
224
230
  engines: { node: "22.x" },
225
231
  workspaces: ["backend", "storefront"],
226
- scripts: {
227
- "dev:backend": "npm --workspace backend run dev",
228
- "dev:storefront": "npm --workspace storefront run dev",
229
- "typecheck": "npm --workspace backend run typecheck && npm --workspace storefront run typecheck",
230
- "test": "npm --workspace backend run test",
231
- "build": "npm --workspace backend run verify:build && npm --workspace storefront run build",
232
- "verify": "npm run typecheck && npm run test && npm run build",
233
- "db:migrate": "npm --workspace backend run db:migrate",
234
- "core:init": "npm --workspace backend run core:init --",
235
- "storefront:key": "npm --workspace backend run storefront:key --",
236
- "bootstrap:assert": "npm --workspace backend run bootstrap:assert",
237
- "install:dev": "node ./scripts/commerce-ops.mjs install dev",
238
- "install:prod": "node ./scripts/commerce-ops.mjs install prod",
239
- "deploy:dev": "node ./scripts/commerce-ops.mjs deploy dev",
240
- "deploy:prod": "node ./scripts/commerce-ops.mjs deploy prod",
241
- "backup:dev": "node ./scripts/commerce-ops.mjs backup dev",
242
- "backup:prod": "node ./scripts/commerce-ops.mjs backup prod",
243
- "restore:dev": "node ./scripts/commerce-ops.mjs restore dev",
244
- "restore:prod": "node ./scripts/commerce-ops.mjs restore prod",
245
- "docker:up": "docker compose --env-file .env.docker up -d --wait",
246
- "docker:down": "docker compose --env-file .env.docker down"
247
- },
232
+ scripts: generatedRootScripts(),
233
+ overrides: generatedRootOverrides(),
248
234
  }
249
235
  writeJson(join(root, "package.json"), rootPackage)
250
236
  mkdirSync(join(root, "scripts"), { recursive: true })
251
237
  cpSync(join(root, "backend", "scripts", "commerce-ops.mjs"),
252
238
  join(root, "scripts", "commerce-ops.mjs"))
253
- writeFileSync(join(root, "ecosystem.config.cjs"), `module.exports = {
254
- apps: [
255
- {
256
- name: ${JSON.stringify(settings.slug + "-backend")},
257
- cwd: __dirname,
258
- script: "npm",
259
- args: "--workspace backend run start:prod",
260
- env_production: {
261
- NODE_ENV: "production",
262
- APP_ENV: "production",
263
- PORT: ${JSON.stringify(new URL(settings.backendUrl).port || "9000")},
264
- HOST: "127.0.0.1",
265
- },
266
- },
267
- {
268
- name: ${JSON.stringify(settings.slug + "-storefront")},
269
- cwd: __dirname,
270
- script: "npm",
271
- args: "--workspace storefront run start",
272
- env_production: {
273
- NODE_ENV: "production",
274
- APP_ENV: "production",
275
- PORT: ${JSON.stringify(new URL(settings.storefrontUrl).port || "3000")},
276
- HOSTNAME: "127.0.0.1",
277
- },
278
- },
279
- ],
280
- }
281
- `)
239
+ // Materialize generated operational assets before recording their baseline.
240
+ // Future Core upgrades can then replace only unchanged, Core-owned files.
241
+ mkdirSync(join(root, "deploy"), { recursive: true })
242
+ for (const name of ["install.sh", "deploy.sh", "backup.sh", "restore.sh"]) {
243
+ cpSync(join(root, "backend", "scripts", "production-assets", name),
244
+ join(root, "deploy", name))
245
+ }
246
+ writeFileSync(join(root, "ecosystem.config.cjs"), renderEcosystemConfig(settings))
282
247
 
283
248
  writeFileSync(join(root, ".nvmrc"), "22\n")
284
249
  writeFileSync(
@@ -287,6 +252,8 @@ function configureProject(root, settings) {
287
252
  "node_modules/",
288
253
  "backend/.env",
289
254
  "backend/.env.production",
255
+ "backend/.env.staging",
256
+ "storefront/.env.staging",
290
257
  "storefront/.env.production",
291
258
  "backend/.medusa/",
292
259
  "backend/src/api",
@@ -301,6 +268,7 @@ function configureProject(root, settings) {
301
268
  ".DS_Store",
302
269
  "*.log",
303
270
  "backups/",
271
+ ".core/deployment-environment",
304
272
  "",
305
273
  ].join("\n"),
306
274
  )
@@ -330,7 +298,7 @@ Production requires an independently configured \`backend/.env.production\` and
330
298
  Restore is dry-run by default: \`npm run restore:dev -- --from backups/dev/<bundle>\`
331
299
  or \`npm run restore:prod -- --from backups/prod/<bundle>\`.
332
300
  Only add \`--yes\` after checking the target database; a restore can delete existing data.
333
- Do not point development and production at the same PostgreSQL database.
301
+ Do not point any environments at the same PostgreSQL database. Use separate checkout directories for staging and production to avoid overwriting build files.
334
302
 
335
303
  Project-specific backend code belongs in \`backend/src/project/\`. Shared commerce behavior comes from \`@hszrdm/core\`.\n`,
336
304
  )
@@ -642,5 +610,5 @@ function bool(value) {
642
610
  }
643
611
 
644
612
  function printHelp() {
645
- console.log(`HSZRDM Commerce project generator\n\nHasználat:\n npx @hszrdm/create-commerce <project-name> [opciók]\n\nFő opciók:\n --name <név>\n --slug <slug>\n --locale hu-HU\n --country HU\n --currency HUF\n --backend-url http://localhost:9000\n --storefront-url http://localhost:3000\n --admin-email <email>\n --admin-password <password>\n --database-url postgres://...\n --redis-url redis://...\n --postgres-port <port>\n --redis-port <port>\n --core-version <verzió> (alapértelmezett: a generator package verziója)\n --non-interactive\n --force\n\nInfrastruktúra:\n Ha --database-url és --redis-url meg van adva, a generátor Dockert nem használ.\n Ha nincsenek megadva, Docker Compose a fallback.\n\nFejlesztői kapcsolók:\n --skip-install\n --skip-docker\n --skip-bootstrap\n --skip-verify\n --skip-git\n\nLokális Core package teszthez:\n HSZRDM_CORE_PACKAGE=/abs/path/to/packages/core npx @hszrdm/create-commerce test-shop\n`)
613
+ console.log(`HSZRDM Commerce project generator\n\nHasználat:\n npx @hszrdm/create-commerce <project-name> [opciók]\n npx @hszrdm/create-commerce@<verzió> upgrade --dir . [--apply]\n\nAz upgrade alapból dry-run: frissíti a kezelt függőségeket, közös forrásfájlokat, deploy-eszközöket és a teljes npm lockfile-t, de csak --apply használatakor ír a projektbe.\n\nFő opciók:\n --name <név>\n --slug <slug>\n --locale hu-HU\n --country HU\n --currency HUF\n --backend-url http://localhost:9000\n --storefront-url http://localhost:3000\n --admin-email <email>\n --admin-password <password>\n --database-url postgres://...\n --redis-url redis://...\n --postgres-port <port>\n --redis-port <port>\n --core-version <verzió> (alapértelmezett: a generator package verziója)\n --non-interactive\n --force\n\nInfrastruktúra:\n Ha --database-url és --redis-url meg van adva, a generátor Dockert nem használ.\n Ha nincsenek megadva, Docker Compose a fallback.\n\nFejlesztői kapcsolók:\n --skip-install\n --skip-docker\n --skip-bootstrap\n --skip-verify\n --skip-git\n\nLokális Core package teszthez:\n HSZRDM_CORE_PACKAGE=/abs/path/to/packages/core npx @hszrdm/create-commerce test-shop\n`)
646
614
  }
@@ -0,0 +1,384 @@
1
+ import { createHash } from "node:crypto"
2
+ import { execFileSync } from "node:child_process"
3
+ import { cpSync, existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs"
4
+ import { tmpdir } from "node:os"
5
+ import { dirname, join, resolve } from "node:path"
6
+ import { fileURLToPath } from "node:url"
7
+
8
+ const PACKAGE_ROOT = resolve(dirname(fileURLToPath(import.meta.url)), "..")
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)]
11
+ const SKIP_SEGMENTS = new Set(["node_modules", ".next", ".medusa", ".cache", ".git", "out", "static"])
12
+ const SKIP_FILES = new Set(["package.json", "package-lock.json", ".env", ".env.production", ".env.staging", ".env.local", ".env.docker"])
13
+
14
+ export function renderEcosystemConfig(settings) {
15
+ return `module.exports = {
16
+ apps: [
17
+ {
18
+ name: ${JSON.stringify(settings.slug + "-backend")},
19
+ cwd: __dirname,
20
+ script: "npm",
21
+ args: "--workspace backend run start:prod",
22
+ env_production: {
23
+ NODE_ENV: "production",
24
+ APP_ENV: "production",
25
+ PORT: ${JSON.stringify(new URL(settings.backendUrl).port || "9000")},
26
+ HOST: "127.0.0.1",
27
+ },
28
+ },
29
+ {
30
+ name: ${JSON.stringify(settings.slug + "-storefront")},
31
+ cwd: __dirname,
32
+ script: "npm",
33
+ args: "--workspace storefront run start",
34
+ env_production: {
35
+ NODE_ENV: "production",
36
+ APP_ENV: "production",
37
+ PORT: ${JSON.stringify(new URL(settings.storefrontUrl).port || "3000")},
38
+ HOSTNAME: "127.0.0.1",
39
+ },
40
+ },
41
+ {
42
+ name: ${JSON.stringify(settings.slug + "-staging-backend")},
43
+ cwd: __dirname,
44
+ script: "npm",
45
+ args: "--workspace backend run start:prod",
46
+ env_staging: {
47
+ NODE_ENV: "production",
48
+ APP_ENV: "staging",
49
+ PORT: "9101",
50
+ HOST: "127.0.0.1",
51
+ },
52
+ },
53
+ {
54
+ name: ${JSON.stringify(settings.slug + "-staging-storefront")},
55
+ cwd: __dirname,
56
+ script: "npm",
57
+ args: "--workspace storefront run start",
58
+ env_staging: {
59
+ NODE_ENV: "production",
60
+ APP_ENV: "staging",
61
+ PORT: "3101",
62
+ HOSTNAME: "127.0.0.1",
63
+ },
64
+ },
65
+ ],
66
+ }
67
+ `
68
+ }
69
+
70
+ // Root-level npm overrides are required to secure the full transitive dependency
71
+ // graph. npm does not inherit overrides from @hszrdm/core's package.json.
72
+ export function generatedRootOverrides() {
73
+ return {
74
+ "lodash": "4.18.1",
75
+ "@graphql-tools/utils": "12.1.0",
76
+ "nodemailer": "10.3.1",
77
+ }
78
+ }
79
+
80
+ export function generatedRootScripts() {
81
+ return {
82
+ "dev:backend": "npm --workspace backend run dev",
83
+ "dev:storefront": "npm --workspace storefront run dev",
84
+ "typecheck": "npm --workspace backend run typecheck && npm --workspace storefront run typecheck",
85
+ "test": "npm --workspace backend run test",
86
+ "build": "npm --workspace backend run verify:build && npm --workspace storefront run build",
87
+ "verify": "npm run typecheck && npm run test && npm run build",
88
+ "db:migrate": "npm --workspace backend run db:migrate",
89
+ "core:init": "npm --workspace backend run core:init --",
90
+ "storefront:key": "npm --workspace backend run storefront:key --",
91
+ "bootstrap:assert": "npm --workspace backend run bootstrap:assert",
92
+ "install:dev": "node ./scripts/commerce-ops.mjs install dev",
93
+ "install:prod": "node ./scripts/commerce-ops.mjs install prod",
94
+ "install:staging": "node ./scripts/commerce-ops.mjs install staging",
95
+ "deploy:dev": "node ./scripts/commerce-ops.mjs deploy dev",
96
+ "deploy:prod": "node ./scripts/commerce-ops.mjs deploy prod",
97
+ "deploy:staging": "node ./scripts/commerce-ops.mjs deploy staging",
98
+ "deploy:production": "npm run deploy:prod",
99
+ "backup:dev": "node ./scripts/commerce-ops.mjs backup dev",
100
+ "backup:prod": "node ./scripts/commerce-ops.mjs backup prod",
101
+ "backup:staging": "node ./scripts/commerce-ops.mjs backup staging",
102
+ "restore:dev": "node ./scripts/commerce-ops.mjs restore dev",
103
+ "restore:prod": "node ./scripts/commerce-ops.mjs restore prod",
104
+ "restore:staging": "node ./scripts/commerce-ops.mjs restore staging",
105
+ "docker:up": "docker compose --env-file .env.docker up -d --wait",
106
+ "docker:down": "docker compose --env-file .env.docker down",
107
+ "upgrade:core": "npx --yes @hszrdm/create-commerce@latest upgrade --dir .",
108
+ }
109
+ }
110
+
111
+ function readJson(path) { return JSON.parse(readFileSync(path, "utf8")) }
112
+ function json(value) { return JSON.stringify(value, null, 2) + "\n" }
113
+ function sha(data) { return createHash("sha256").update(data).digest("hex") }
114
+ function hashFile(path) { return sha(readFileSync(path)) }
115
+ function canonicalSource(path) {
116
+ if (path === "scripts/commerce-ops.mjs") return join(PACKAGE_ROOT, "templates", "backend", "scripts", "commerce-ops.mjs")
117
+ if (path.startsWith("deploy/")) return join(PACKAGE_ROOT, "templates", "backend", "scripts", "production-assets", path.slice("deploy/".length))
118
+ return join(PACKAGE_ROOT, "templates", path)
119
+ }
120
+ function walk(dir, prefix, result) {
121
+ if (!existsSync(dir)) return
122
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
123
+ if (SKIP_SEGMENTS.has(entry.name)) continue
124
+ const rel = prefix ? prefix + "/" + entry.name : entry.name
125
+ const abs = join(dir, entry.name)
126
+ if (entry.isSymbolicLink()) continue
127
+ if (entry.isDirectory()) walk(abs, rel, result)
128
+ else if (entry.isFile() && !SKIP_FILES.has(entry.name) && !rel.startsWith("backend/src/project/")) result.push(rel)
129
+ }
130
+ }
131
+ function managedPaths() {
132
+ const files = []
133
+ for (const name of ["backend", "storefront"]) walk(join(PACKAGE_ROOT, "templates", name), name, files)
134
+ return [...files, ...MANAGED_EXTRA_FILES].sort()
135
+ }
136
+ function packageDeps(pkg) {
137
+ const result = {}
138
+ for (const key of ["dependencies", "devDependencies", "optionalDependencies", "peerDependencies"]) {
139
+ result[key] = { ...(pkg[key] || {}) }
140
+ }
141
+ return result
142
+ }
143
+ function managedPackageState(root) {
144
+ const result = {}
145
+ for (const path of ["package.json", "backend/package.json", "storefront/package.json"]) {
146
+ const full = join(root, path)
147
+ if (!existsSync(full)) continue
148
+ const p = readJson(full)
149
+ result[path] = {
150
+ scripts: { ...(p.scripts || {}) },
151
+ deps: packageDeps(p),
152
+ ...(path === "package.json" ? {
153
+ // Only Core-owned pins are part of the managed baseline. Customer-only
154
+ // overrides are never owned by this generator.
155
+ overrides: Object.fromEntries(Object.keys(generatedRootOverrides())
156
+ .filter((key) => Object.prototype.hasOwnProperty.call(p.overrides || {}, key))
157
+ .map((key) => [key, p.overrides[key]])),
158
+ } : {}),
159
+ }
160
+ }
161
+ return result
162
+ }
163
+ export function writeGeneratedManifest(root, version) {
164
+ const files = {}
165
+ for (const file of managedPaths()) {
166
+ const full = join(root, file)
167
+ if (existsSync(full)) files[file] = hashFile(full)
168
+ }
169
+ writeFileSync(join(root, MANIFEST), json({
170
+ schema_version: 1,
171
+ generator_version: version,
172
+ files,
173
+ packages: managedPackageState(root),
174
+ }))
175
+ }
176
+
177
+ function expectedPackage(path, version) {
178
+ if (path === "package.json") return { scripts: generatedRootScripts(), overrides: generatedRootOverrides() }
179
+ const packagePath = join(PACKAGE_ROOT, "templates", path)
180
+ const pkg = readJson(packagePath)
181
+ if (path === "backend/package.json") {
182
+ pkg.dependencies ||= {}
183
+ pkg.dependencies["@hszrdm/core"] = version
184
+ pkg.scripts ||= {}
185
+ pkg.scripts.test = "npm run typecheck"
186
+ }
187
+ return pkg
188
+ }
189
+
190
+ /**
191
+ * Dry-run unless --apply. Three-way merge of generated files based on hashes
192
+ * captured at project generation or the previous successful upgrade.
193
+ * Customer additions and changes are never silently replaced.
194
+ */
195
+ export function planUpgrade(root, version) {
196
+ const metadataPath = join(root, "hszrdm-commerce.json")
197
+ if (!existsSync(metadataPath) || !existsSync(join(root, "backend/package.json")) ||
198
+ !existsSync(join(root, "storefront/package.json"))) {
199
+ throw new Error("This is not a generated HSZRDM Commerce project.")
200
+ }
201
+ const previous = existsSync(join(root, MANIFEST)) ? readJson(join(root, MANIFEST)) : null
202
+ if (previous && previous.schema_version !== 1) throw new Error("Unknown managed manifest version.")
203
+ const conflicts = [], changes = [], files = {}
204
+ const canonicalPaths = managedPaths()
205
+ const canonicalSet = new Set(canonicalPaths)
206
+ for (const path of canonicalPaths) {
207
+ const source = path === "ecosystem.config.cjs" ? null : canonicalSource(path)
208
+ const target = join(root, path)
209
+ const metadata = path === "ecosystem.config.cjs" ? readJson(metadataPath) : null
210
+ const desired = source ? readFileSync(source) : Buffer.from(renderEcosystemConfig({
211
+ slug: metadata.project.slug,
212
+ backendUrl: metadata.urls.backend,
213
+ storefrontUrl: metadata.urls.storefront,
214
+ }))
215
+ const desiredHash = sha(desired)
216
+ const targetStat = lstatSync(target, { throwIfNoEntry: false })
217
+ if (targetStat && !targetStat.isFile()) {
218
+ conflicts.push(path + " (not a regular file; refusing to overwrite)")
219
+ continue
220
+ }
221
+ const currentHash = targetStat ? hashFile(target) : null
222
+ const known = previous?.files?.[path]
223
+ if (currentHash === desiredHash) {
224
+ files[path] = currentHash
225
+ } else if (currentHash === null || (known && known === currentHash)) {
226
+ changes.push({ kind: "file", path, content: desired })
227
+ files[path] = desiredHash
228
+ } else {
229
+ conflicts.push(path + " (customer-modified or missing baseline)")
230
+ }
231
+ }
232
+
233
+ // Remove files retired from the canonical starter only when their original
234
+ // content is unchanged; never remove customer-modified files.
235
+ for (const [path, previousHash] of Object.entries(previous?.files || {})) {
236
+ if (canonicalSet.has(path)) continue
237
+ const target = join(root, path)
238
+ const stat = lstatSync(target, { throwIfNoEntry: false })
239
+ if (!stat) continue
240
+ if (stat.isFile() && hashFile(target) === previousHash) {
241
+ changes.push({ kind: "delete", path })
242
+ } else {
243
+ conflicts.push(path + " (obsolete file modified by customer)")
244
+ files[path] = previousHash
245
+ }
246
+ }
247
+
248
+ const packages = {}
249
+ for (const path of ["package.json", "backend/package.json", "storefront/package.json"]) {
250
+ const current = readJson(join(root, path))
251
+ const desired = expectedPackage(path, version)
252
+ const base = previous?.packages?.[path]
253
+ const merged = structuredClone(current)
254
+ merged.scripts ||= {}
255
+ for (const [key, nextValue] of Object.entries(desired.scripts || {})) {
256
+ const oldValue = base?.scripts?.[key]
257
+ if (current.scripts[key] !== nextValue && current.scripts[key] !== undefined &&
258
+ (!base || (oldValue !== undefined && current.scripts[key] !== oldValue))) {
259
+ conflicts.push(path + ":scripts." + key)
260
+ } else merged.scripts[key] = nextValue
261
+ }
262
+ for (const group of ["dependencies", "devDependencies", "optionalDependencies", "peerDependencies"]) {
263
+ merged[group] ||= {}
264
+ const managed = { ...(desired[group] || {}) }
265
+ for (const [key, nextValue] of Object.entries(managed)) {
266
+ const currentValue = current[group]?.[key]
267
+ const oldValue = base?.deps?.[group]?.[key]
268
+ if (currentValue !== nextValue && currentValue !== undefined &&
269
+ (!base || (oldValue !== undefined && currentValue !== oldValue))) {
270
+ conflicts.push(path + ":" + group + "." + key)
271
+ } else merged[group][key] = nextValue
272
+ }
273
+ // Remove dependencies dropped by the canonical starter only if untouched.
274
+ for (const [key, oldValue] of Object.entries(base?.deps?.[group] || {})) {
275
+ if (key in managed || !(key in merged[group])) continue
276
+ if (merged[group][key] === oldValue) delete merged[group][key]
277
+ else conflicts.push(path + ":obsolete " + group + "." + key)
278
+ }
279
+ }
280
+ // Root npm overrides are the only reliable way to pin deeply nested
281
+ // vulnerable dependencies in generated customer shops.
282
+ if (path === "package.json") {
283
+ merged.overrides ||= {}
284
+ for (const [key, nextValue] of Object.entries(desired.overrides || {})) {
285
+ const currentValue = current.overrides?.[key]
286
+ const oldValue = base?.overrides?.[key]
287
+ // A pre-existing override with no Core-owned baseline is a customer
288
+ // choice, not a safe value to silently replace. If Core previously
289
+ // owned the key, update only when its value is still unchanged.
290
+ if (currentValue !== undefined && currentValue !== nextValue &&
291
+ (oldValue === undefined || currentValue !== oldValue)) {
292
+ conflicts.push(path + ":overrides." + key)
293
+ } else merged.overrides[key] = nextValue
294
+ }
295
+ // Do not auto-remove a key merely because it appeared in an older
296
+ // manifest: historical manifests may include unrelated customer pins.
297
+ // Unknown/custom overrides must always survive Core upgrades.
298
+ }
299
+ const oldContent = readFileSync(join(root, path), "utf8")
300
+ if (json(merged) !== oldContent) changes.push({ kind: "json", path, content: json(merged) })
301
+ packages[path] = {
302
+ scripts: Object.fromEntries(Object.entries(desired.scripts || {}).map(([k]) => [k, merged.scripts[k]])),
303
+ deps: Object.fromEntries(["dependencies", "devDependencies", "optionalDependencies", "peerDependencies"].map(k => [
304
+ k, Object.fromEntries(Object.keys(desired[k] || {}).map(dep => [dep, merged[k][dep]])),
305
+ ])),
306
+ ...(path === "package.json" ? {
307
+ overrides: Object.fromEntries(Object.keys(desired.overrides || {}).map(key => [key, merged.overrides[key]])),
308
+ } : {}),
309
+ }
310
+ }
311
+
312
+ return { root, version, previous, changes, conflicts, nextManifest: {
313
+ schema_version: 1,
314
+ generator_version: version,
315
+ files: Object.fromEntries([
316
+ ...Object.entries(previous?.files || {}).filter(([path]) => canonicalSet.has(path)),
317
+ ...Object.entries(files),
318
+ ]),
319
+ packages,
320
+ } }
321
+ }
322
+
323
+ export function applyUpgrade(plan, { execute = true } = {}) {
324
+ if (plan.conflicts.length) throw new Error("Upgrade blocked by customer changes:\n- " + plan.conflicts.join("\n- "))
325
+ if (!execute) return plan
326
+ const staged = [...plan.changes, { kind: "json", path: MANIFEST, content: json(plan.nextManifest) }]
327
+ const metadataPath = join(plan.root, "hszrdm-commerce.json")
328
+ const metadata = readJson(metadataPath)
329
+ metadata.core_version = plan.version
330
+ staged.push({ kind: "json", path: "hszrdm-commerce.json", content: json(metadata) })
331
+ // Preserve the old full lock graph if npm resolution fails.
332
+ const lockPath = join(plan.root, "package-lock.json")
333
+ const lockExisted = existsSync(lockPath)
334
+ const oldLock = lockExisted ? readFileSync(lockPath) : null
335
+ const backupDir = mkdtempSync(join(tmpdir(), "hszrdm-upgrade-rollback-"))
336
+ const originals = []
337
+ try {
338
+ for (const change of staged) {
339
+ const full = join(plan.root, change.path)
340
+ if (existsSync(full)) {
341
+ if (!lstatSync(full).isFile()) throw new Error("Cannot overwrite non-regular file: " + change.path)
342
+ const old = join(backupDir, change.path)
343
+ mkdirSync(dirname(old), { recursive: true })
344
+ cpSync(full, old)
345
+ }
346
+ originals.push({ full, path: change.path, existed: existsSync(full) })
347
+ mkdirSync(dirname(full), { recursive: true })
348
+ if (change.kind === "delete") rmSync(full, { force: true })
349
+ else writeFileSync(full, change.content)
350
+ }
351
+ // This refreshes the full transitive dependency graph without executing
352
+ // install hooks or touching application secrets, DBs or running processes.
353
+ execFileSync(process.platform === "win32" ? "npm.cmd" : "npm",
354
+ ["install", "--package-lock-only", "--ignore-scripts", "--no-audit", "--no-fund"],
355
+ { cwd: plan.root, stdio: "inherit" })
356
+ console.log("Upgrade prepared; verify npm ci, typecheck, tests and build before deploying.")
357
+ } catch (error) {
358
+ if (lockExisted) writeFileSync(lockPath, oldLock)
359
+ else rmSync(lockPath, { force: true })
360
+ for (const item of originals.reverse()) {
361
+ if (item.existed) cpSync(join(backupDir, item.path), item.full)
362
+ else rmSync(item.full, { force: true })
363
+ }
364
+ throw error
365
+ } finally { rmSync(backupDir, { force: true, recursive: true }) }
366
+ return plan
367
+ }
368
+
369
+ export function upgradeFromArgs(args, version) {
370
+ const index = args.indexOf("--dir")
371
+ const inline = args.find(x => x.startsWith("--dir="))
372
+ const root = resolve(inline ? inline.slice(6) : index >= 0 ? args[index + 1] : ".")
373
+ const plan = planUpgrade(root, version)
374
+ console.log(`HSZRDM Commerce upgrade ${plan.previous?.generator_version || "legacy"} → ${version}`)
375
+ console.log(`Changes: ${plan.changes.length}; conflicts: ${plan.conflicts.length}`)
376
+ for (const c of plan.changes) console.log("UPDATE", c.path)
377
+ for (const c of plan.conflicts) console.error("CONFLICT", c)
378
+ if (!args.includes("--apply")) {
379
+ console.log("DRY RUN: no changes made. Use --apply after reviewing the plan.")
380
+ if (plan.conflicts.length) process.exitCode = 2
381
+ return plan
382
+ }
383
+ return applyUpgrade(plan)
384
+ }
@@ -80,16 +80,21 @@ OPENAI_BASE_URL=https://api.openai.com/v1
80
80
  # Email Center / transactional email
81
81
  # -----------------------------------------------------------------------------
82
82
  EMAIL_CENTER_ENABLED=true
83
- # Supported provider values: sendgrid, resend. Empty = local Medusa provider.
84
- EMAIL_PROVIDER=
85
- EMAIL_API_KEY=
86
- EMAIL_FROM=
87
- EMAIL_REPLY_TO=
88
- # Optional provider-specific fallbacks.
89
- RESEND_API_KEY=
90
- RESEND_FROM_EMAIL=
91
- SENDGRID_API_KEY=
92
- SENDGRID_FROM_EMAIL=
83
+ # SMTP is the only supported email transport. This legacy selector is optional.
84
+ EMAIL_PROVIDER=smtp
85
+ # New stores have no SMTP host yet; enable after configuring and verifying SMTP in Admin.
86
+ SMTP_ENABLED=false
87
+ EMAIL_FROM="Example Store <system@example.com>"
88
+ EMAIL_REPLY_TO=support@example.com
89
+ SMTP_HOST=
90
+ SMTP_PORT=587
91
+ # true for implicit TLS (typically 465), false for STARTTLS (typically 587)
92
+ SMTP_SECURE=false
93
+ SMTP_REQUIRE_TLS=true
94
+ SMTP_USER=
95
+ SMTP_PASSWORD=
96
+ SMTP_FROM="Example Store <system@example.com>"
97
+ SMTP_REPLY_TO=
93
98
 
94
99
  EMAIL_CUSTOMER_WELCOME_ENABLED=
95
100
  EMAIL_REGISTRATION_VERIFICATION_ENABLED=
@@ -104,6 +109,11 @@ EMAIL_FULFILLMENT_CREATED_ENABLED=
104
109
  EMAIL_SHIPMENT_CREATED_ENABLED=
105
110
  EMAIL_ORDER_CANCELED_ENABLED=
106
111
  EMAIL_PAYMENT_REFUNDED_ENABLED=
112
+ EMAIL_AFTER_SALES_SUBMITTED_ENABLED=
113
+ EMAIL_AFTER_SALES_APPROVED_ENABLED=
114
+ EMAIL_AFTER_SALES_REJECTED_ENABLED=
115
+ EMAIL_RETURN_INSTRUCTIONS_ENABLED=
116
+ EMAIL_RETURN_RECEIVED_ENABLED=
107
117
 
108
118
  EMAIL_LOGO_URL=
109
119
  EMAIL_TRACKING_ENABLED=true
@@ -12,6 +12,7 @@
12
12
  "start": "medusa start",
13
13
  "typecheck": "npm run env:verify && npm run prepare:project && tsc --noEmit",
14
14
  "core:init": "npm run prepare:project && medusa exec ./src/scripts/core-init.ts",
15
+ "integrations:sync": "npm run prepare:project && medusa exec ./src/scripts/sync-integration-runtime.ts",
15
16
  "core:backup": "node ./scripts/core-backup.mjs --project-dir .",
16
17
  "core:restore": "node ./scripts/core-restore.mjs --project-dir .",
17
18
  "storefront:key": "npm run prepare:project && medusa exec ./src/scripts/create-storefront-key.ts",
@@ -22,7 +23,7 @@
22
23
  "start:prod": "cd .medusa/server && medusa start"
23
24
  },
24
25
  "dependencies": {
25
- "@hszrdm/core": "1.9.1",
26
+ "@hszrdm/core": "1.10.1",
26
27
  "@medusajs/admin-sdk": "2.22.2",
27
28
  "@medusajs/cli": "2.22.2",
28
29
  "@medusajs/draft-order": "2.22.2",