@sea-ecommerce/admin-mcp-server 0.1.4 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +83 -3
- package/dist/derlux-admin-mcp.js +1080 -44
- package/package.json +4 -2
- package/skill/SKILL.md +202 -197
- package/skill/import-spec.template.json +50 -0
- package/skill/product-import-template.csv +10 -0
- package/skill//345/225/206/345/223/201/345/257/274/345/205/245/346/250/241/346/235/277-/345/241/253/345/206/231/350/257/264/346/230/216.md +150 -0
- package/skill//345/267/245/345/205/267/345/217/202/346/225/260/345/217/202/350/200/203.md +297 -0
- package/skill//350/277/220/350/220/245/344/272/272/345/221/230/346/211/213/345/206/214/01-/345/277/253/351/200/237/345/205/245/351/227/250/344/270/216/347/225/214/351/235/242/345/257/274/350/247/210.md +94 -0
- package/skill//350/277/220/350/220/245/344/272/272/345/221/230/346/211/213/345/206/214/02-/344/272/272/345/221/230/344/270/216/346/235/203/351/231/220/347/256/241/347/220/206.md +133 -0
- package/skill//350/277/220/350/220/245/344/272/272/345/221/230/346/211/213/345/206/214/03-/345/225/206/345/223/201/347/256/241/347/220/206.md +161 -0
- package/skill//350/277/220/350/220/245/344/272/272/345/221/230/346/211/213/345/206/214/04-/345/272/223/345/255/230/344/270/216/344/273/223/345/272/223.md +103 -0
- package/skill//350/277/220/350/220/245/344/272/272/345/221/230/346/211/213/345/206/214/05-/350/256/242/345/215/225/344/270/216/345/224/256/345/220/216.md +147 -0
- package/skill//350/277/220/350/220/245/344/272/272/345/221/230/346/211/213/345/206/214/06-/345/261/245/347/272/246/344/270/216/345/217/221/350/264/247.md +123 -0
- package/skill//350/277/220/350/220/245/344/272/272/345/221/230/346/211/213/345/206/214/07-/345/256/242/346/210/267/344/270/216/344/274/232/345/221/230.md +132 -0
- package/skill//350/277/220/350/220/245/344/272/272/345/221/230/346/211/213/345/206/214/08-/350/220/245/351/224/200/344/270/216/344/277/203/351/224/200.md +191 -0
- package/skill//350/277/220/350/220/245/344/272/272/345/221/230/346/211/213/345/206/214/09-/347/253/231/347/202/271/344/270/216/351/205/215/351/200/201/350/256/276/347/275/256.md +180 -0
- package/skill//350/277/220/350/220/245/344/272/272/345/221/230/346/211/213/345/206/214/10-/345/215/232/345/256/242/344/270/216/345/206/205/345/256/271.md +6 -0
- package/skill//350/277/220/350/220/245/344/272/272/345/221/230/346/211/213/345/206/214/11-/345/234/250/347/272/277/345/256/242/346/234/215.md +6 -0
- package/skill//350/277/220/350/220/245/344/272/272/345/221/230/346/211/213/345/206/214/12-/345/233/276/347/211/207/347/256/241/347/220/206.md +6 -0
- package/skill//350/277/220/350/220/245/344/272/272/345/221/230/346/211/213/345/206/214/13-/345/225/206/345/223/201/345/261/225/347/244/272/346/211/251/345/261/225.md +6 -0
- package/skill//350/277/220/350/220/245/344/272/272/345/221/230/346/211/213/345/206/214/14-/344/273/223/345/272/223/344/275/234/344/270/232/344/270/216/346/213/243/350/264/247/345/215/225.md +6 -0
- package/skill//350/277/220/350/220/245/344/272/272/345/221/230/346/211/213/345/206/214/README.md +76 -0
- package/skill//350/277/220/350/220/245/345/217/202/350/200/203.md +87 -0
package/dist/derlux-admin-mcp.js
CHANGED
|
@@ -21550,11 +21550,23 @@ var StdioServerTransport = class {
|
|
|
21550
21550
|
// src/config.ts
|
|
21551
21551
|
import { homedir } from "node:os";
|
|
21552
21552
|
import { join } from "node:path";
|
|
21553
|
+
import { createHash } from "node:crypto";
|
|
21554
|
+
function sessionScopeOf(backendUrl) {
|
|
21555
|
+
let label = "backend";
|
|
21556
|
+
try {
|
|
21557
|
+
const u = new URL(backendUrl);
|
|
21558
|
+
label = u.host.replace(/[^a-zA-Z0-9.-]/g, "_") || "backend";
|
|
21559
|
+
} catch {
|
|
21560
|
+
}
|
|
21561
|
+
const hash = createHash("sha256").update(backendUrl).digest("hex").slice(0, 10);
|
|
21562
|
+
return `${label}-${hash}`;
|
|
21563
|
+
}
|
|
21553
21564
|
function loadConfig() {
|
|
21554
21565
|
const backendUrl = (process.env.MEDUSA_BACKEND_URL || "http://localhost:9000").replace(/\/$/, "");
|
|
21555
21566
|
const docsDir = process.env.DERLUX_DOCS_DIR || join(process.cwd(), "docs");
|
|
21556
21567
|
const requiredLocales = (process.env.DERLUX_REQUIRED_LOCALES || "en,zh,ms,id").split(",").map((s) => s.trim()).filter(Boolean);
|
|
21557
|
-
const
|
|
21568
|
+
const sessionScope = sessionScopeOf(backendUrl);
|
|
21569
|
+
const sessionFile = process.env.DERLUX_SESSION_FILE || join(homedir(), ".derlux", "sessions", `${sessionScope}.json`);
|
|
21558
21570
|
const auditFile = process.env.DERLUX_AUDIT_FILE || join(homedir(), ".derlux", "mcp-audit.log");
|
|
21559
21571
|
return {
|
|
21560
21572
|
backendUrl,
|
|
@@ -21564,7 +21576,8 @@ function loadConfig() {
|
|
|
21564
21576
|
sessionFile,
|
|
21565
21577
|
auditFile,
|
|
21566
21578
|
docsDir,
|
|
21567
|
-
requiredLocales
|
|
21579
|
+
requiredLocales,
|
|
21580
|
+
sessionScope
|
|
21568
21581
|
};
|
|
21569
21582
|
}
|
|
21570
21583
|
var LOCALE_CANON = {
|
|
@@ -21586,21 +21599,46 @@ function normalizeLocale(input) {
|
|
|
21586
21599
|
}
|
|
21587
21600
|
|
|
21588
21601
|
// src/auth.ts
|
|
21589
|
-
import { readFileSync, writeFileSync, mkdirSync, existsSync } from "node:fs";
|
|
21602
|
+
import { readFileSync, writeFileSync, mkdirSync, existsSync, unlinkSync } from "node:fs";
|
|
21590
21603
|
import { dirname } from "node:path";
|
|
21604
|
+
function decodeJwtPayload(token) {
|
|
21605
|
+
try {
|
|
21606
|
+
const part = token.split(".")[1];
|
|
21607
|
+
if (!part) return null;
|
|
21608
|
+
const b64 = part.replace(/-/g, "+").replace(/_/g, "/");
|
|
21609
|
+
const padded = b64 + "=".repeat((4 - b64.length % 4) % 4);
|
|
21610
|
+
const parsed = JSON.parse(Buffer.from(padded, "base64").toString("utf8"));
|
|
21611
|
+
return parsed && typeof parsed === "object" ? parsed : null;
|
|
21612
|
+
} catch {
|
|
21613
|
+
return null;
|
|
21614
|
+
}
|
|
21615
|
+
}
|
|
21591
21616
|
var AuthManager = class {
|
|
21592
21617
|
constructor(config3) {
|
|
21593
21618
|
this.config = config3;
|
|
21594
21619
|
}
|
|
21595
21620
|
session = null;
|
|
21621
|
+
/** 会话是否仍可用于当前配置:作用域一致 + 未过期 */
|
|
21622
|
+
isUsable(s) {
|
|
21623
|
+
if (!s || !s.token && !s.cookie) return false;
|
|
21624
|
+
if (s.backendUrl !== this.config.backendUrl) return false;
|
|
21625
|
+
if (s.adminEmail !== this.config.adminEmail) return false;
|
|
21626
|
+
if (s.expiresAt && s.expiresAt - 6e4 <= Date.now()) return false;
|
|
21627
|
+
return true;
|
|
21628
|
+
}
|
|
21596
21629
|
load() {
|
|
21597
21630
|
if (this.session) return this.session;
|
|
21598
21631
|
try {
|
|
21599
21632
|
if (existsSync(this.config.sessionFile)) {
|
|
21600
|
-
|
|
21633
|
+
const parsed = JSON.parse(readFileSync(this.config.sessionFile, "utf8"));
|
|
21634
|
+
if (this.isUsable(parsed)) {
|
|
21635
|
+
this.session = parsed;
|
|
21636
|
+
} else {
|
|
21637
|
+
this.clear();
|
|
21638
|
+
}
|
|
21601
21639
|
}
|
|
21602
21640
|
} catch {
|
|
21603
|
-
this.
|
|
21641
|
+
this.clear();
|
|
21604
21642
|
}
|
|
21605
21643
|
return this.session;
|
|
21606
21644
|
}
|
|
@@ -21609,8 +21647,13 @@ var AuthManager = class {
|
|
|
21609
21647
|
mkdirSync(dirname(this.config.sessionFile), { recursive: true });
|
|
21610
21648
|
writeFileSync(this.config.sessionFile, JSON.stringify(session, null, 2), { mode: 384 });
|
|
21611
21649
|
}
|
|
21650
|
+
/** 清内存 + 删盘;client 遇 401 时会调用它再重新登录 */
|
|
21612
21651
|
clear() {
|
|
21613
21652
|
this.session = null;
|
|
21653
|
+
try {
|
|
21654
|
+
if (existsSync(this.config.sessionFile)) unlinkSync(this.config.sessionFile);
|
|
21655
|
+
} catch {
|
|
21656
|
+
}
|
|
21614
21657
|
}
|
|
21615
21658
|
/** 返回用于后续请求的鉴权头(Bearer 优先,回退 Cookie) */
|
|
21616
21659
|
headers() {
|
|
@@ -21619,6 +21662,62 @@ var AuthManager = class {
|
|
|
21619
21662
|
if (s?.cookie) return { Cookie: s.cookie };
|
|
21620
21663
|
return {};
|
|
21621
21664
|
}
|
|
21665
|
+
/** 给 get_context / --preflight 用的会话诊断(不触发登录) */
|
|
21666
|
+
describe() {
|
|
21667
|
+
const s = this.load();
|
|
21668
|
+
return {
|
|
21669
|
+
valid: Boolean(s),
|
|
21670
|
+
session_file: this.config.sessionFile,
|
|
21671
|
+
session_scope: this.config.sessionScope,
|
|
21672
|
+
session_file_exists: existsSync(this.config.sessionFile),
|
|
21673
|
+
backend_url: this.config.backendUrl,
|
|
21674
|
+
admin_email: this.config.adminEmail || "(\u672A\u914D\u7F6E)",
|
|
21675
|
+
actor_type: s?.actorType ?? null,
|
|
21676
|
+
roles: s?.roles ?? [],
|
|
21677
|
+
obtained_at: s?.obtainedAt ? new Date(s.obtainedAt).toISOString() : null,
|
|
21678
|
+
expires_at: s?.expiresAt ? new Date(s.expiresAt).toISOString() : null
|
|
21679
|
+
};
|
|
21680
|
+
}
|
|
21681
|
+
/**
|
|
21682
|
+
* 登录后立刻验证「这真的是后台管理员账号」。
|
|
21683
|
+
* 直接用 fetch(不能走 MedusaAdminClient.request,否则 401 重登会递归)。
|
|
21684
|
+
*/
|
|
21685
|
+
async preflight(token, cookie) {
|
|
21686
|
+
const { backendUrl, adminEmail } = this.config;
|
|
21687
|
+
const headers = {};
|
|
21688
|
+
if (token) headers.Authorization = `Bearer ${token}`;
|
|
21689
|
+
else if (cookie) headers.Cookie = cookie;
|
|
21690
|
+
const warnings = [];
|
|
21691
|
+
let me;
|
|
21692
|
+
try {
|
|
21693
|
+
me = await fetch(`${backendUrl}/admin/users/me`, { headers });
|
|
21694
|
+
} catch (e) {
|
|
21695
|
+
throw new Error(
|
|
21696
|
+
`\u540E\u7AEF\u4E0D\u53EF\u8FBE\uFF1A${backendUrl}\uFF08${e instanceof Error ? e.message : String(e)}\uFF09\u3002\u8BF7\u68C0\u67E5 MEDUSA_BACKEND_URL \u4E0E\u7F51\u7EDC\u3002`
|
|
21697
|
+
);
|
|
21698
|
+
}
|
|
21699
|
+
if (me.status === 401 || me.status === 403) {
|
|
21700
|
+
throw new Error(
|
|
21701
|
+
`\u8D26\u53F7 ${adminEmail} \u767B\u5F55\u6210\u529F\uFF0C\u4F46 GET /admin/users/me \u8FD4\u56DE ${me.status}\uFF1A\u8FD9\u4E0D\u662F\u540E\u53F0\u7BA1\u7406\u5458\u8D26\u53F7\uFF08\u5E38\u89C1\u539F\u56E0\uFF1A\u7528\u4E86\u524D\u53F0\u987E\u5BA2\u8D26\u53F7\uFF0CJWT \u91CC\u53EA\u6709 customer_id\uFF09\u3002\u8BF7\u6539\u7528\u6301\u6709 csr / super_admin \u89D2\u8272\u7684\u540E\u53F0\u7528\u6237\u8D26\u53F7\u3002`
|
|
21702
|
+
);
|
|
21703
|
+
}
|
|
21704
|
+
if (!me.ok) {
|
|
21705
|
+
warnings.push(`/admin/users/me \u8FD4\u56DE ${me.status}\uFF0C\u672A\u80FD\u786E\u8BA4\u540E\u53F0\u8EAB\u4EFD\uFF0C\u767B\u5F55\u7EE7\u7EED\u4F46\u8BF7\u4EBA\u5DE5\u6838\u5BF9\u3002`);
|
|
21706
|
+
}
|
|
21707
|
+
let roles = [];
|
|
21708
|
+
try {
|
|
21709
|
+
const r = await fetch(`${backendUrl}/admin/rbac-current-user`, { headers });
|
|
21710
|
+
if (r.ok) {
|
|
21711
|
+
const data = await r.json();
|
|
21712
|
+
if (Array.isArray(data.roles)) roles = data.roles.filter((x) => typeof x === "string");
|
|
21713
|
+
} else {
|
|
21714
|
+
warnings.push(`/admin/rbac-current-user \u8FD4\u56DE ${r.status}\uFF1A\u65E0\u6CD5\u8BFB\u53D6 RBAC \u89D2\u8272\uFF08\u4E0D\u5F71\u54CD\u767B\u5F55\uFF0C\u654F\u611F\u52A8\u4F5C\u53EF\u80FD\u88AB\u540E\u7AEF\u62E6\u622A\uFF09\u3002`);
|
|
21715
|
+
}
|
|
21716
|
+
} catch (e) {
|
|
21717
|
+
warnings.push(`\u8BFB\u53D6 RBAC \u89D2\u8272\u5931\u8D25\uFF1A${e instanceof Error ? e.message : String(e)}`);
|
|
21718
|
+
}
|
|
21719
|
+
return { roles, warnings };
|
|
21720
|
+
}
|
|
21622
21721
|
async login() {
|
|
21623
21722
|
const { backendUrl, authPath, adminEmail, adminPassword } = this.config;
|
|
21624
21723
|
if (!adminEmail || !adminPassword) {
|
|
@@ -21636,20 +21735,41 @@ var AuthManager = class {
|
|
|
21636
21735
|
throw new Error(`\u767B\u5F55\u5931\u8D25 (${res.status}): ${text}`);
|
|
21637
21736
|
}
|
|
21638
21737
|
const data = await res.json();
|
|
21639
|
-
const setCookie = res.headers.get("set-cookie") || void 0;
|
|
21738
|
+
const setCookie = res.headers.get("set-cookie")?.split(";")[0] || void 0;
|
|
21739
|
+
if (!data.token && !setCookie) {
|
|
21740
|
+
throw new Error("\u767B\u5F55\u54CD\u5E94\u65E2\u6CA1\u6709 token \u4E5F\u6CA1\u6709 Set-Cookie\uFF0C\u65E0\u6CD5\u5EFA\u7ACB\u540E\u53F0\u4F1A\u8BDD\u3002");
|
|
21741
|
+
}
|
|
21742
|
+
const payload = decodeJwtPayload(data.token || "");
|
|
21743
|
+
const actorType = payload?.actor_type ?? payload?.actor ?? null;
|
|
21744
|
+
if (actorType && actorType !== "user") {
|
|
21745
|
+
throw new Error(
|
|
21746
|
+
`\u8D26\u53F7 ${adminEmail} \u767B\u5F55\u6210\u529F\uFF0C\u4F46\u5B83\u662F\u524D\u53F0\u300C${actorType}\u300D\u8D26\u53F7\uFF08JWT actor_type=${actorType}\uFF09\uFF0C\u4E0D\u662F\u540E\u53F0\u7BA1\u7406\u5458\uFF0C\u6240\u6709 /admin/* \u8BF7\u6C42\u90FD\u4F1A\u8FD4\u56DE 401\u3002\u8BF7\u6539\u7528\u6301\u6709 csr / super_admin \u89D2\u8272\u7684\u540E\u53F0\u7528\u6237\u8D26\u53F7\uFF08\u4F8B\u5982 csr@sea.com\uFF09\u3002`
|
|
21747
|
+
);
|
|
21748
|
+
}
|
|
21749
|
+
const { roles, warnings } = await this.preflight(data.token, setCookie);
|
|
21750
|
+
const exp = typeof payload?.exp === "number" ? payload.exp * 1e3 : void 0;
|
|
21640
21751
|
const session = {
|
|
21641
21752
|
token: data.token,
|
|
21642
21753
|
cookie: setCookie,
|
|
21643
21754
|
user: data.user,
|
|
21644
|
-
obtainedAt: Date.now()
|
|
21755
|
+
obtainedAt: Date.now(),
|
|
21756
|
+
backendUrl,
|
|
21757
|
+
adminEmail,
|
|
21758
|
+
actorType,
|
|
21759
|
+
roles,
|
|
21760
|
+
expiresAt: exp
|
|
21645
21761
|
};
|
|
21646
21762
|
this.save(session);
|
|
21763
|
+
if (warnings.length) {
|
|
21764
|
+
process.stderr.write(`[derlux-admin] \u767B\u5F55\u81EA\u68C0\u544A\u8B66\uFF1A${warnings.join(" | ")}
|
|
21765
|
+
`);
|
|
21766
|
+
}
|
|
21647
21767
|
return session;
|
|
21648
21768
|
}
|
|
21649
|
-
/**
|
|
21769
|
+
/** 确保有可用会话;作用域不符 / 过期 / 不存在则重新登录 */
|
|
21650
21770
|
async ensure() {
|
|
21651
21771
|
const existing = this.load();
|
|
21652
|
-
if (existing
|
|
21772
|
+
if (existing) return existing;
|
|
21653
21773
|
return this.login();
|
|
21654
21774
|
}
|
|
21655
21775
|
};
|
|
@@ -21708,13 +21828,48 @@ var MedusaAdminClient = class {
|
|
|
21708
21828
|
listProducts(params = {}) {
|
|
21709
21829
|
return this.request("GET", `/admin/products${buildQuery(params)}`);
|
|
21710
21830
|
}
|
|
21711
|
-
|
|
21712
|
-
|
|
21831
|
+
/**
|
|
21832
|
+
* 把「商品 id 或 handle」解析为商品 id。
|
|
21833
|
+
* ⚠️ Medusa v2 的 GET /admin/products/{id} **只认 id**:传 handle 会 404(Product not found)。
|
|
21834
|
+
* 因此 handle 必须先走列表端点 `?handle=<h>`(精确匹配)解析成 id,再由调用方按 id 取详情。
|
|
21835
|
+
* 解析不到(id 不存在 / handle 无匹配)返回 null。
|
|
21836
|
+
*/
|
|
21837
|
+
async resolveProductId(idOrHandle) {
|
|
21838
|
+
const s = idOrHandle.trim();
|
|
21839
|
+
if (/^prod_[a-z0-9]+$/i.test(s)) return s;
|
|
21840
|
+
try {
|
|
21841
|
+
const data = await this.request("GET", `/admin/products${buildQuery({ handle: s, limit: 10 })}`);
|
|
21842
|
+
const list = data?.products || [];
|
|
21843
|
+
const exact = list.find((p) => p.handle === s);
|
|
21844
|
+
return (exact ?? list[0])?.id || null;
|
|
21845
|
+
} catch {
|
|
21846
|
+
return null;
|
|
21847
|
+
}
|
|
21848
|
+
}
|
|
21849
|
+
/** 按商品 id 或 handle 获取商品详情(handle 自动解析为 id,见 resolveProductId)。 */
|
|
21850
|
+
async getProduct(idOrHandle) {
|
|
21851
|
+
const id = await this.resolveProductId(idOrHandle);
|
|
21852
|
+
if (id) {
|
|
21853
|
+
return this.request("GET", `/admin/products/${encodeURIComponent(id)}`);
|
|
21854
|
+
}
|
|
21855
|
+
return this.request("GET", `/admin/products/${encodeURIComponent(idOrHandle.trim())}`);
|
|
21713
21856
|
}
|
|
21714
21857
|
/** 列出销售渠道(用于默认渠道解析) */
|
|
21715
21858
|
listSalesChannels(params = {}) {
|
|
21716
21859
|
return this.request("GET", `/admin/sales-channels${buildQuery(params)}`);
|
|
21717
21860
|
}
|
|
21861
|
+
/** 当前登录后台用户(登录 preflight / get_context 用) */
|
|
21862
|
+
getCurrentUser() {
|
|
21863
|
+
return this.request("GET", "/admin/users/me");
|
|
21864
|
+
}
|
|
21865
|
+
/** 当前用户持有的 RBAC 角色(本项目自定义端点,见 apps/backend/src/api/admin/rbac-current-user) */
|
|
21866
|
+
getRbacRoles() {
|
|
21867
|
+
return this.request("GET", "/admin/rbac-current-user");
|
|
21868
|
+
}
|
|
21869
|
+
/** 区域与币种(get_context 用;某些部署可能无此端点,调用方需容错) */
|
|
21870
|
+
listRegions(params = {}) {
|
|
21871
|
+
return this.request("GET", `/admin/regions${buildQuery(params)}`);
|
|
21872
|
+
}
|
|
21718
21873
|
createProduct(body) {
|
|
21719
21874
|
return this.request("POST", "/admin/products", body);
|
|
21720
21875
|
}
|
|
@@ -21769,13 +21924,35 @@ var MedusaAdminClient = class {
|
|
|
21769
21924
|
`/admin/product-contents${buildQuery({ product_id: productId, locale, status })}`
|
|
21770
21925
|
);
|
|
21771
21926
|
}
|
|
21927
|
+
/**
|
|
21928
|
+
* 提交前为缺 id 的区块补齐稳定唯一 id。
|
|
21929
|
+
* ContentBlock.id 是后台编辑器 React key 与「编辑 / 删除 / 移动」的定位依据:
|
|
21930
|
+
* AI agent 生成的 blocks 常不带 id,会让同一语言所有区块的 key 退化成同一个值,
|
|
21931
|
+
* 切换语言时旧卡片 DOM 无法回收、越切越多。规则与后端 lib/product-content-blocks 一致。
|
|
21932
|
+
*/
|
|
21933
|
+
withBlockIds(blocks) {
|
|
21934
|
+
const used = /* @__PURE__ */ new Set();
|
|
21935
|
+
return blocks.map((item, index) => {
|
|
21936
|
+
if (!item || typeof item !== "object" || Array.isArray(item)) return item;
|
|
21937
|
+
const block = item;
|
|
21938
|
+
const base = typeof block.id === "string" && block.id.trim() ? block.id.trim() : `auto-${index}-${block.type ?? "block"}`;
|
|
21939
|
+
let id = base;
|
|
21940
|
+
let suffix = 1;
|
|
21941
|
+
while (used.has(id)) id = `${base}-${suffix++}`;
|
|
21942
|
+
used.add(id);
|
|
21943
|
+
return { ...block, id };
|
|
21944
|
+
});
|
|
21945
|
+
}
|
|
21772
21946
|
/**
|
|
21773
21947
|
* 创建/更新某商品某语言的富内容块(POST /admin/product-contents)。
|
|
21774
21948
|
* body: { product_id, locale, status?, blocks };blocks 为 ContentBlock[] 数组
|
|
21775
21949
|
* (type ∈ hero/richtext/image_gallery/video/faq/specs)。按 (product_id, locale) upsert。
|
|
21776
21950
|
*/
|
|
21777
21951
|
createProductContent(body) {
|
|
21778
|
-
return this.request("POST", "/admin/product-contents",
|
|
21952
|
+
return this.request("POST", "/admin/product-contents", {
|
|
21953
|
+
...body,
|
|
21954
|
+
blocks: this.withBlockIds(body.blocks)
|
|
21955
|
+
});
|
|
21779
21956
|
}
|
|
21780
21957
|
/**
|
|
21781
21958
|
* 上传一组文件到 Medusa 文件服务(POST /admin/uploads,multipart 字段名 files),
|
|
@@ -21923,6 +22100,119 @@ var MedusaAdminClient = class {
|
|
|
21923
22100
|
}
|
|
21924
22101
|
};
|
|
21925
22102
|
|
|
22103
|
+
// src/tools/context.ts
|
|
22104
|
+
var contextTools = [
|
|
22105
|
+
{
|
|
22106
|
+
name: "get_context",
|
|
22107
|
+
description: `\u3010\u6BCF\u6B21\u4EFB\u52A1\u5F00\u5DE5\u524D\u5148\u8C03\u4E00\u6B21\u3011\u4E00\u6B21\u6027\u8FD4\u56DE\u8FD0\u884C\u73AF\u5883\u4E0E\u6743\u9650\u81EA\u68C0\uFF1A\u540E\u7AEF\u5730\u5740\u3001\u767B\u5F55\u8D26\u53F7\u3001JWT actor \u7C7B\u578B\u3001RBAC \u89D2\u8272\u3001\u4F1A\u8BDD\u662F\u5426\u6709\u6548/\u8FC7\u671F\u3001\u9500\u552E\u6E20\u9053\u3001\u4ED3\u5E93\u3001\u533A\u57DF\u5E01\u79CD\u3001\u5FC5\u9700\u8BED\u8A00\uFF0C\u4EE5\u53CA /admin/* \u8BFB\u63A5\u53E3\u662F\u5426\u53EF\u7528\uFF08\u8BFB\u901A\u4E0D\u4EE3\u8868\u6709\u5199\u6743\u9650\uFF0C\u5199\u6743\u9650\u4ECD\u53EF\u80FD\u88AB RBAC \u62E6\u622A\uFF09\u3002
|
|
22108
|
+
\u7528\u9014\uFF1A\u907F\u514D\u300C\u987E\u5BA2\u8D26\u53F7\u80FD\u767B\u5F55\u4F46 /admin/* \u5168 401\u300D\u300C\u8FDE\u7684\u662F\u672C\u5730\u5374\u4EE5\u4E3A\u5728\u5199\u7EBF\u4E0A\u300D\u300C\u6E20\u9053\u540D\u89E3\u6790\u5931\u8D25\u300D\u7B49\u8FD4\u5DE5\u3002
|
|
22109
|
+
\u53EA\u8BFB\uFF08\u767B\u5F55\u672C\u8EAB\u4E0D\u5199\u4E1A\u52A1\u6570\u636E\uFF09\uFF1B\u5931\u8D25\u65F6\u8FD4\u56DE\u53EF\u8BFB\u7684 errors / warnings \u4E0E\u4FEE\u590D\u5EFA\u8BAE\uFF0C\u4E0D\u629B\u5F02\u5E38\u3002`,
|
|
22110
|
+
schema: {
|
|
22111
|
+
probe: external_exports.boolean().default(true).describe("\u662F\u5426\u8054\u7F51\u63A2\u6D4B\u6743\u9650/\u6E20\u9053/\u4ED3\u5E93/\u533A\u57DF\uFF1Bfalse \u65F6\u53EA\u56DE\u672C\u5730\u914D\u7F6E\u4E0E\u4F1A\u8BDD\u72B6\u6001"),
|
|
22112
|
+
include_raw: external_exports.boolean().default(false).describe("\u662F\u5426\u9644\u5E26\u539F\u59CB\u7AEF\u70B9\u8FD4\u56DE\uFF08\u9ED8\u8BA4\u53EA\u56DE\u7CBE\u7B80\u6458\u8981\uFF09")
|
|
22113
|
+
},
|
|
22114
|
+
async run(input, { client: client2, config: config3, auth: auth2 }) {
|
|
22115
|
+
const out = {
|
|
22116
|
+
ok: true,
|
|
22117
|
+
environment: {
|
|
22118
|
+
backend_url: config3.backendUrl,
|
|
22119
|
+
admin_email: config3.adminEmail || "(\u672A\u914D\u7F6E)",
|
|
22120
|
+
auth_path: config3.authPath,
|
|
22121
|
+
session_scope: config3.sessionScope,
|
|
22122
|
+
session_file: config3.sessionFile,
|
|
22123
|
+
required_locales: config3.requiredLocales
|
|
22124
|
+
},
|
|
22125
|
+
session: auth2.describe(),
|
|
22126
|
+
warnings: [],
|
|
22127
|
+
errors: []
|
|
22128
|
+
};
|
|
22129
|
+
const warnings = out.warnings;
|
|
22130
|
+
const errors = out.errors;
|
|
22131
|
+
if (!config3.adminEmail || !config3.adminPassword) {
|
|
22132
|
+
errors.push("\u672A\u914D\u7F6E DERLUX_ADMIN_EMAIL / DERLUX_ADMIN_PASSWORD\uFF0C\u65E0\u6CD5\u8C03\u7528\u540E\u53F0\u63A5\u53E3\u3002");
|
|
22133
|
+
}
|
|
22134
|
+
if (!input.probe) {
|
|
22135
|
+
if (!out.session.valid) {
|
|
22136
|
+
warnings.push("\u4F1A\u8BDD\u4E0D\u53EF\u7528\uFF08\u672A\u767B\u5F55 / \u5DF2\u8FC7\u671F / \u73AF\u5883\u4E0D\u5339\u914D\uFF09\uFF1B\u9996\u6B21\u8BF7\u6C42\u4F1A\u81EA\u52A8\u767B\u5F55\u5E76\u505A\u6743\u9650\u81EA\u68C0\u3002");
|
|
22137
|
+
}
|
|
22138
|
+
out.next = ["\u786E\u8BA4 environment.backend_url \u662F\u76EE\u6807\u73AF\u5883", "\u786E\u8BA4 session.actor_type=user \u4E14 roles \u542B csr/super_admin", "\u968F\u540E\u7528 import-spec \u4E00\u6B21\u6027\u786E\u8BA4\u4E1A\u52A1\u9009\u9879"];
|
|
22139
|
+
out.ok = errors.length === 0;
|
|
22140
|
+
return out;
|
|
22141
|
+
}
|
|
22142
|
+
let probeHeadersReady = false;
|
|
22143
|
+
try {
|
|
22144
|
+
await auth2.ensure();
|
|
22145
|
+
probeHeadersReady = true;
|
|
22146
|
+
const s = auth2.describe();
|
|
22147
|
+
out.session = s;
|
|
22148
|
+
const roles = s.roles || [];
|
|
22149
|
+
if (s.actor_type && s.actor_type !== "user") {
|
|
22150
|
+
errors.push(`\u5F53\u524D\u8D26\u53F7 actor_type=${s.actor_type}\uFF0C\u4E0D\u662F\u540E\u53F0 user \u8D26\u53F7\u3002`);
|
|
22151
|
+
}
|
|
22152
|
+
if (roles.length === 0) {
|
|
22153
|
+
warnings.push("\u672A\u8BFB\u5230 RBAC \u89D2\u8272\uFF08\u53EF\u80FD\u8BE5\u7AEF\u70B9\u4E0D\u53EF\u7528\uFF09\uFF1B\u82E5\u5199\u64CD\u4F5C\u88AB 403\uFF0C\u8BF7\u68C0\u67E5 user.metadata.rbac_roles\u3002");
|
|
22154
|
+
}
|
|
22155
|
+
} catch (e) {
|
|
22156
|
+
errors.push(`\u767B\u5F55/\u6743\u9650\u81EA\u68C0\u5931\u8D25\uFF1A${e instanceof Error ? e.message : String(e)}`);
|
|
22157
|
+
}
|
|
22158
|
+
if (probeHeadersReady) {
|
|
22159
|
+
try {
|
|
22160
|
+
await client2.listProducts({ limit: 1 });
|
|
22161
|
+
out.read_api = "ok";
|
|
22162
|
+
} catch (e) {
|
|
22163
|
+
const msg = e instanceof Error ? e.message : String(e);
|
|
22164
|
+
out.read_api = `denied: ${msg.slice(0, 200)}`;
|
|
22165
|
+
errors.push(`GET /admin/products \u5931\u8D25\uFF1A${msg.slice(0, 200)}`);
|
|
22166
|
+
}
|
|
22167
|
+
try {
|
|
22168
|
+
const d = await client2.listSalesChannels({ limit: 50 });
|
|
22169
|
+
const list = (d?.sales_channels || []).map((c) => ({
|
|
22170
|
+
id: c.id,
|
|
22171
|
+
name: c.name,
|
|
22172
|
+
is_disabled: Boolean(c.is_disabled)
|
|
22173
|
+
}));
|
|
22174
|
+
out.sales_channels = list;
|
|
22175
|
+
if (input.include_raw) out.sales_channels_raw = d;
|
|
22176
|
+
if (!list.length) warnings.push("\u6CA1\u6709\u4EFB\u4F55\u9500\u552E\u6E20\u9053\uFF0C\u65B0\u5EFA\u5546\u54C1\u5C06\u65E0\u6CD5\u5728\u524D\u53F0\u53EF\u89C1\u3002");
|
|
22177
|
+
} catch (e) {
|
|
22178
|
+
errors.push(`\u6E20\u9053\u8BFB\u53D6\u5931\u8D25\uFF1A${e instanceof Error ? e.message : String(e)}`);
|
|
22179
|
+
}
|
|
22180
|
+
try {
|
|
22181
|
+
const d = await client2.listStockLocations({ limit: 50 });
|
|
22182
|
+
const list = (d?.stock_locations || []).map((l) => ({ id: l.id, name: l.name }));
|
|
22183
|
+
out.stock_locations = list;
|
|
22184
|
+
if (input.include_raw) out.stock_locations_raw = d;
|
|
22185
|
+
if (!list.length) warnings.push("\u6CA1\u6709\u4EFB\u4F55\u4ED3\u5E93\uFF0Cinitial_stock \u4F1A\u5931\u8D25\uFF1B\u8BF7\u5148 create_stock_location\u3002");
|
|
22186
|
+
} catch (e) {
|
|
22187
|
+
errors.push(`\u4ED3\u5E93\u8BFB\u53D6\u5931\u8D25\uFF1A${e instanceof Error ? e.message : String(e)}`);
|
|
22188
|
+
}
|
|
22189
|
+
try {
|
|
22190
|
+
const d = await client2.listRegions({ limit: 50 });
|
|
22191
|
+
const regions = d?.regions || [];
|
|
22192
|
+
out.currencies = Array.from(
|
|
22193
|
+
new Set(regions.map((r) => String(r.currency_code || "").toUpperCase()).filter(Boolean))
|
|
22194
|
+
);
|
|
22195
|
+
if (input.include_raw) out.regions_raw = d;
|
|
22196
|
+
if (!out.currencies.length) warnings.push("\u672A\u8BFB\u5230\u533A\u57DF\u5E01\u79CD\uFF0C\u8BF7\u4EBA\u5DE5\u6838\u5BF9 prices \u91CC\u7684 currency_code\u3002");
|
|
22197
|
+
} catch (e) {
|
|
22198
|
+
out.currencies = [];
|
|
22199
|
+
warnings.push(`\u533A\u57DF\u5E01\u79CD\u8BFB\u53D6\u5931\u8D25\uFF08\u53EF\u80FD\u662F\u65E7\u7248\u540E\u7AEF\uFF09\uFF1A${(e instanceof Error ? e.message : String(e)).slice(0, 120)}`);
|
|
22200
|
+
}
|
|
22201
|
+
}
|
|
22202
|
+
if (errors.length) {
|
|
22203
|
+
out.ok = false;
|
|
22204
|
+
out.hint = errors.some((x) => x.includes("401") || x.includes("403") || x.includes("\u987E\u5BA2")) ? "\u4F18\u5148\u68C0\u67E5\u8D26\u53F7\uFF1A\u5FC5\u987B\u662F\u540E\u53F0 user\uFF08csr/super_admin\uFF09\uFF0C\u524D\u53F0\u987E\u5BA2\u8D26\u53F7\u767B\u5F55\u6210\u529F\u4F46\u65E0 /admin/* \u6743\u9650\u3002" : "\u4F18\u5148\u68C0\u67E5 MEDUSA_BACKEND_URL \u662F\u5426\u53EF\u8FBE\u3001\u662F\u5426\u4E3A\u76EE\u6807\u73AF\u5883\u3002";
|
|
22205
|
+
}
|
|
22206
|
+
out.next = [
|
|
22207
|
+
"\u6838\u5BF9 environment.backend_url \u4E0E session.actor_type/roles",
|
|
22208
|
+
"\u7528 import-spec \u4E00\u6B21\u6027\u58F0\u660E\uFF1A\u91CD\u590D\u5546\u54C1\u7B56\u7565\u3001\u4E0A\u67B6\u72B6\u6001\u3001\u4EF7\u683C\u57FA\u51C6\u3001\u6C47\u7387\u6765\u6E90\u3001\u6E20\u9053\u3001\u5E93\u5B58",
|
|
22209
|
+
"\u6279\u91CF\u5BFC\u5165\u5148 dry-run \u62FF confirm_token\uFF0C\u518D commit"
|
|
22210
|
+
];
|
|
22211
|
+
return out;
|
|
22212
|
+
}
|
|
22213
|
+
}
|
|
22214
|
+
];
|
|
22215
|
+
|
|
21926
22216
|
// src/tools/stock.ts
|
|
21927
22217
|
async function applyProductStock(ctx2, opts) {
|
|
21928
22218
|
const { client: client2 } = ctx2;
|
|
@@ -22127,7 +22417,105 @@ location_id \u53EF\u9009\uFF1A\u4F20\u4E86\u5219\u53EA\u56DE\u8BE5\u4ED3\u5E93\u
|
|
|
22127
22417
|
}
|
|
22128
22418
|
];
|
|
22129
22419
|
|
|
22420
|
+
// src/tools/translations.ts
|
|
22421
|
+
function canonLocaleKey(locale) {
|
|
22422
|
+
return normalizeLocale(locale) ?? locale;
|
|
22423
|
+
}
|
|
22424
|
+
async function planTranslationUpsert(client2, reference, referenceId, entries) {
|
|
22425
|
+
const data = await client2.listTranslations({ reference, reference_id: referenceId, limit: 100 });
|
|
22426
|
+
const existing = data?.translations || [];
|
|
22427
|
+
const byLocale = new Map(existing.map((r) => [r.locale_code, r]));
|
|
22428
|
+
const create = [];
|
|
22429
|
+
const update = [];
|
|
22430
|
+
const matched = [];
|
|
22431
|
+
for (const e of entries) {
|
|
22432
|
+
const target = canonLocaleKey(e.locale_code);
|
|
22433
|
+
let row = byLocale.get(e.locale_code) || byLocale.get(target);
|
|
22434
|
+
if (!row) {
|
|
22435
|
+
row = existing.find((r) => canonLocaleKey(r.locale_code) === target) || null;
|
|
22436
|
+
}
|
|
22437
|
+
if (row) {
|
|
22438
|
+
const merged = { ...row.translations || {} };
|
|
22439
|
+
for (const [k, v] of Object.entries(e.translations)) {
|
|
22440
|
+
if (v !== void 0 && v !== null) merged[k] = v;
|
|
22441
|
+
}
|
|
22442
|
+
const upd = { id: row.id, translations: merged };
|
|
22443
|
+
if (row.locale_code !== target) upd.locale_code = target;
|
|
22444
|
+
update.push(upd);
|
|
22445
|
+
matched.push({ id: row.id, from_locale: row.locale_code, to_locale: target });
|
|
22446
|
+
} else {
|
|
22447
|
+
const clean = {};
|
|
22448
|
+
for (const [k, v] of Object.entries(e.translations)) {
|
|
22449
|
+
if (v !== void 0 && v !== null) clean[k] = v;
|
|
22450
|
+
}
|
|
22451
|
+
create.push({ reference, reference_id: referenceId, locale_code: target, translations: clean });
|
|
22452
|
+
}
|
|
22453
|
+
}
|
|
22454
|
+
return { create, update, matched };
|
|
22455
|
+
}
|
|
22456
|
+
async function upsertTranslations(client2, reference, referenceId, entries) {
|
|
22457
|
+
const plan = await planTranslationUpsert(client2, reference, referenceId, entries);
|
|
22458
|
+
const result = await client2.batchTranslations(plan.create, plan.update);
|
|
22459
|
+
return { created: plan.create.length, updated: plan.update.length, result };
|
|
22460
|
+
}
|
|
22461
|
+
var translationTools = [
|
|
22462
|
+
{
|
|
22463
|
+
name: "set_translations",
|
|
22464
|
+
description: `\u4E3A\u5B9E\u4F53\uFF08\u5546\u54C1\u7B49\uFF09**\u521B\u5EFA\u6216\u66F4\u65B0\uFF08upsert\uFF09**\u591A\u8BED\u8A00\u7FFB\u8BD1\uFF08title/subtitle/description\uFF09\uFF0C\u8D70 /admin/translations/batch\u3002
|
|
22465
|
+
upsert \u8BED\u4E49\uFF1A\u540C\u8BED\u8A00\u5DF2\u6709\u7FFB\u8BD1 \u2192 \u66F4\u65B0\uFF08\u5B57\u6BB5\u5408\u5E76\uFF0C\u672A\u7ED9\u7684\u65E7\u5B57\u6BB5\u4FDD\u7559\uFF0C\u7EDD\u4E0D\u4EA7\u751F\u91CD\u590D\u884C\uFF09\uFF1B\u6CA1\u6709 \u2192 \u65B0\u5EFA\u3002
|
|
22466
|
+
\u26A0\uFE0F locale \u952E\u63A5\u53D7\u77ED\u7801\uFF08en/zh/ms/id\uFF09\u6216 BCP-47 \u533A\u57DF\u7801\uFF08en-US/zh-CN/ms-MY/id-ID\uFF09\uFF0C\u5DE5\u5177\u7EDF\u4E00\u5F52\u4E00\u5316\u4E3A BCP-47 \u843D\u5E93\u2014\u2014
|
|
22467
|
+
storefront \u5BF9\u7FFB\u8BD1\u63A5\u53E3\u4E00\u5F8B\u8BF7\u6C42 BCP-47\u3001\u4E0E\u5E93\u4E2D locale_code \u7CBE\u786E\u5339\u914D\uFF1B\u5386\u53F2\u6309\u77ED\u7801\u843D\u5E93\u7684\u884C\u4F1A\u88AB\u672C\u6B21\u8C03\u7528**\u6539\u7801\u4FEE\u590D**\u3002
|
|
22468
|
+
\u7528\u9014\uFF1A\u5546\u54C1\u521B\u5EFA\u540E\u8865\u7FFB\u8BD1/\u6539\u7FFB\u8BD1/\u4FEE\u590D\u591A\u8BED\u8A00\u3002\u9ED8\u8BA4 dry_run\uFF08confirm=false\uFF09\u9884\u89C8\u5C06\u521B\u5EFA/\u66F4\u65B0\u54EA\u4E9B\u884C\u3002`,
|
|
22469
|
+
schema: {
|
|
22470
|
+
reference: external_exports.string().default("product").describe("\u5B9E\u4F53\u7C7B\u578B\uFF0C\u5546\u54C1\u7528 product"),
|
|
22471
|
+
reference_id: external_exports.string().describe("\u5B9E\u4F53 id\uFF1B\u5546\u54C1\u53EF\u4F20 handle\uFF08\u81EA\u52A8\u89E3\u6790\u4E3A id\uFF09"),
|
|
22472
|
+
translations: external_exports.record(external_exports.string(), external_exports.object({
|
|
22473
|
+
title: external_exports.string().optional(),
|
|
22474
|
+
subtitle: external_exports.string().optional(),
|
|
22475
|
+
description: external_exports.string().optional()
|
|
22476
|
+
})).describe('locale \u2192 \u7FFB\u8BD1\u5B57\u6BB5\uFF0C\u5982 {"zh-CN":{"title":"...","description":"..."}}\uFF1B\u77ED\u7801/\u533A\u57DF\u7801\u5747\u53EF'),
|
|
22477
|
+
confirm: external_exports.boolean().default(false)
|
|
22478
|
+
},
|
|
22479
|
+
async run(input, { client: client2 }) {
|
|
22480
|
+
let refId = String(input.reference_id).trim();
|
|
22481
|
+
if (input.reference === "product" && !/^prod_[a-z0-9]+$/i.test(refId)) {
|
|
22482
|
+
const id = await client2.resolveProductId(refId);
|
|
22483
|
+
if (!id) return `\u9519\u8BEF\uFF1A\u627E\u4E0D\u5230\u5546\u54C1 "${refId}"\uFF08\u8BF7\u4F20\u5546\u54C1 id \u6216\u6709\u6548 handle\uFF09`;
|
|
22484
|
+
refId = id;
|
|
22485
|
+
}
|
|
22486
|
+
const entries = Object.entries(input.translations).map(([locale, t]) => ({
|
|
22487
|
+
locale_code: canonLocaleKey(locale),
|
|
22488
|
+
translations: Object.fromEntries(
|
|
22489
|
+
Object.entries(t ?? {}).filter(([, v]) => v !== void 0 && v !== null)
|
|
22490
|
+
)
|
|
22491
|
+
}));
|
|
22492
|
+
if (!entries.length) return "\u9519\u8BEF\uFF1Atranslations \u4E3A\u7A7A\uFF0C\u65E0\u4E8B\u53EF\u505A\u3002";
|
|
22493
|
+
const plan = await planTranslationUpsert(client2, input.reference, refId, entries);
|
|
22494
|
+
if (!input.confirm) {
|
|
22495
|
+
return {
|
|
22496
|
+
dry_run: true,
|
|
22497
|
+
reference: input.reference,
|
|
22498
|
+
reference_id: refId,
|
|
22499
|
+
will_create: plan.create,
|
|
22500
|
+
will_update: plan.update,
|
|
22501
|
+
matched_existing: plan.matched,
|
|
22502
|
+
note: "\u672A confirm\uFF0C\u4EC5\u9884\u89C8\u3002\u786E\u8BA4\u8BF7\u8BBE confirm=true\u3002"
|
|
22503
|
+
};
|
|
22504
|
+
}
|
|
22505
|
+
const { created, updated, result } = await upsertTranslations(client2, input.reference, refId, entries);
|
|
22506
|
+
return { created, updated, result };
|
|
22507
|
+
}
|
|
22508
|
+
}
|
|
22509
|
+
];
|
|
22510
|
+
|
|
22130
22511
|
// src/tools/products.ts
|
|
22512
|
+
function canonicalizeTranslations(translations) {
|
|
22513
|
+
const out = {};
|
|
22514
|
+
for (const [key, val] of Object.entries(translations ?? {})) {
|
|
22515
|
+
out[normalizeLocale(key) ?? key] = val;
|
|
22516
|
+
}
|
|
22517
|
+
return out;
|
|
22518
|
+
}
|
|
22131
22519
|
var PRODUCT_STATUS = [
|
|
22132
22520
|
"draft",
|
|
22133
22521
|
"published",
|
|
@@ -22276,16 +22664,17 @@ SKU / \u89C4\u683C\uFF1Asku \u5199\u5165\u9ED8\u8BA4\u53D8\u4F53\uFF1Bmetadata \
|
|
|
22276
22664
|
confirm: external_exports.boolean().default(false),
|
|
22277
22665
|
acknowledge_missing_languages: external_exports.boolean().default(false)
|
|
22278
22666
|
},
|
|
22279
|
-
async run(input,
|
|
22667
|
+
async run(input, ctx2) {
|
|
22668
|
+
const { client: client2, config: config3 } = ctx2;
|
|
22280
22669
|
const handleRaw = input.handle || input.title;
|
|
22281
22670
|
const handle = normalizeHandle(handleRaw);
|
|
22282
22671
|
if (!HANDLE_RE.test(handle)) {
|
|
22283
22672
|
return `\u9519\u8BEF\uFF1A\u5F52\u4E00\u5316\u540E\u7684 Handle "${handle}" \u4ECD\u975E\u6CD5\uFF08\u53EA\u80FD\u5C0F\u5199\u5B57\u6BCD/\u6570\u5B57/\u8FDE\u5B57\u7B26\uFF09\u3002\u8BF7\u68C0\u67E5\u8F93\u5165\u3002`;
|
|
22284
22673
|
}
|
|
22285
|
-
const
|
|
22286
|
-
const
|
|
22287
|
-
|
|
22288
|
-
);
|
|
22674
|
+
const canon = (l) => normalizeLocale(l) ?? l;
|
|
22675
|
+
const normTranslations = canonicalizeTranslations(input.translations);
|
|
22676
|
+
const provided = Object.keys(normTranslations);
|
|
22677
|
+
const missing = config3.requiredLocales.map(canon).filter((l) => !provided.includes(l) || !normTranslations[l]?.title);
|
|
22289
22678
|
let channelIds = [];
|
|
22290
22679
|
if (input.sales_channels?.length) {
|
|
22291
22680
|
const ch = await client2.listSalesChannels({ limit: 100 });
|
|
@@ -22303,7 +22692,22 @@ SKU / \u89C4\u683C\uFF1Asku \u5199\u5165\u9ED8\u8BA4\u53D8\u4F53\uFF1Bmetadata \
|
|
|
22303
22692
|
if (!hit) return `\u9519\u8BEF\uFF1A\u627E\u4E0D\u5230\u96C6\u5408 "${collectionId}"\uFF08\u7528 list_collections \u67E5\u770B\u53EF\u7528\u96C6\u5408\uFF09`;
|
|
22304
22693
|
collectionId = hit.id;
|
|
22305
22694
|
}
|
|
22695
|
+
let handleCollision = null;
|
|
22696
|
+
try {
|
|
22697
|
+
const existing = await client2.listProducts({ handle, limit: 5 });
|
|
22698
|
+
const dup = (existing?.products || []).find((p) => p.handle === handle);
|
|
22699
|
+
if (dup) handleCollision = { id: dup.id, title: dup.title, status: dup.status };
|
|
22700
|
+
} catch {
|
|
22701
|
+
}
|
|
22306
22702
|
const warnings = [];
|
|
22703
|
+
if (handleCollision) {
|
|
22704
|
+
warnings.push(
|
|
22705
|
+
`handle \u51B2\u7A81\uFF1A\u5DF2\u5B58\u5728\u540C handle \u5546\u54C1\u300C${handleCollision.title}\u300D(id: ${handleCollision.id}, status: ${handleCollision.status})\u3002\u82E5\u662F\u5728\u91CD\u65B0\u5F55\u5165\u540C\u4E00\u5546\u54C1\uFF0C\u8BF7\u6539\u7528 update_product \u4FEE\u6539\u8BE5\u5546\u54C1\uFF0C\u800C\u975E create_product\u3002`
|
|
22706
|
+
);
|
|
22707
|
+
if (input.confirm) {
|
|
22708
|
+
return `\u9519\u8BEF\uFF1Ahandle "${handle}" \u5DF2\u88AB\u5546\u54C1 ${handleCollision.id}\uFF08\u300C${handleCollision.title}\u300D\uFF09\u5360\u7528\uFF0C\u65E0\u6CD5\u91CD\u590D\u521B\u5EFA\u3002\u82E5\u8FD9\u662F\u540C\u4E00\u5546\u54C1\u7684\u91CD\u65B0\u5F55\u5165\uFF0C\u8BF7\u7528 update_product(id=${handleCollision.id}) \u66F4\u65B0\uFF1B\u82E5\u662F\u4E0D\u540C\u5546\u54C1\uFF0C\u8BF7\u6362\u4E00\u4E2A handle \u6216\u6807\u9898\u3002`;
|
|
22709
|
+
}
|
|
22710
|
+
}
|
|
22307
22711
|
if (input.manage_inventory !== false && !input.initial_stock) {
|
|
22308
22712
|
warnings.push(
|
|
22309
22713
|
"manage_inventory=true \u4F46\u672A\u7ED9 initial_stock\uFF1A\u521B\u5EFA\u540E\u4E3A 0 \u5E93\u5B58\uFF0C\u524D\u7AEF\u5C06\u663E\u793A\u7F3A\u8D27\u3002\u6B63\u5F0F\u4E0A\u67B6\u524D\u5FC5\u987B\u8C03\u7528 set_product_stock \u5EFA\u4ED3\u3002"
|
|
@@ -22327,9 +22731,12 @@ SKU / \u89C4\u683C\uFF1Asku \u5199\u5165\u9ED8\u8BA4\u53D8\u4F53\uFF1Bmetadata \
|
|
|
22327
22731
|
weight: input.weight,
|
|
22328
22732
|
manage_inventory: input.manage_inventory,
|
|
22329
22733
|
initial_stock: input.initial_stock,
|
|
22734
|
+
// 实际将写入翻译表的 locale_code(已归一化为 BCP-47,见 canonicalizeTranslations)
|
|
22735
|
+
translation_locales: provided,
|
|
22330
22736
|
missing_translations: missing
|
|
22331
22737
|
},
|
|
22332
22738
|
warnings,
|
|
22739
|
+
handle_collision: handleCollision,
|
|
22333
22740
|
note: "\u672A confirm\uFF0C\u4EC5\u9884\u89C8\u3002\u786E\u8BA4\u8BF7\u8BBE confirm=true\u3002"
|
|
22334
22741
|
};
|
|
22335
22742
|
}
|
|
@@ -22376,15 +22783,17 @@ SKU / \u89C4\u683C\uFF1Asku \u5199\u5165\u9ED8\u8BA4\u53D8\u4F53\uFF1Bmetadata \
|
|
|
22376
22783
|
const data = await client2.createProduct(payload);
|
|
22377
22784
|
const productId = data?.product?.id || data?.id;
|
|
22378
22785
|
let translationResult = null;
|
|
22379
|
-
if (
|
|
22380
|
-
const create = Object.entries(input.translations).map(([locale, t]) => ({
|
|
22381
|
-
reference: "product",
|
|
22382
|
-
reference_id: productId,
|
|
22383
|
-
locale_code: locale,
|
|
22384
|
-
translations: { title: t?.title, description: t?.description }
|
|
22385
|
-
}));
|
|
22786
|
+
if (Object.keys(normTranslations).length) {
|
|
22386
22787
|
try {
|
|
22387
|
-
translationResult = await
|
|
22788
|
+
translationResult = await upsertTranslations(
|
|
22789
|
+
client2,
|
|
22790
|
+
"product",
|
|
22791
|
+
productId,
|
|
22792
|
+
Object.entries(normTranslations).map(([locale, t]) => ({
|
|
22793
|
+
locale_code: locale,
|
|
22794
|
+
translations: { title: t?.title, description: t?.description }
|
|
22795
|
+
}))
|
|
22796
|
+
);
|
|
22388
22797
|
} catch (e) {
|
|
22389
22798
|
return { created: data, warning_translations: `\u7FFB\u8BD1\u5199\u5165\u5931\u8D25 \u2014\u2014 ${e?.message || e}` };
|
|
22390
22799
|
}
|
|
@@ -22393,7 +22802,7 @@ SKU / \u89C4\u683C\uFF1Asku \u5199\u5165\u9ED8\u8BA4\u53D8\u4F53\uFF1Bmetadata \
|
|
|
22393
22802
|
if (input.initial_stock && productId) {
|
|
22394
22803
|
try {
|
|
22395
22804
|
stock = await applyProductStock(
|
|
22396
|
-
|
|
22805
|
+
ctx2,
|
|
22397
22806
|
{
|
|
22398
22807
|
productId,
|
|
22399
22808
|
sku: input.sku,
|
|
@@ -22435,6 +22844,7 @@ metadata \u4E3A**\u5408\u5E76**\u8BED\u4E49\uFF1A\u65B0\u952E\u8986\u76D6\u540C\
|
|
|
22435
22844
|
confirm: external_exports.boolean().default(false)
|
|
22436
22845
|
},
|
|
22437
22846
|
async run(input, { client: client2 }) {
|
|
22847
|
+
const productId = await client2.resolveProductId(input.id) || String(input.id).trim();
|
|
22438
22848
|
const patch = {};
|
|
22439
22849
|
if (input.title) patch.title = input.title;
|
|
22440
22850
|
if (input.handle) {
|
|
@@ -22462,22 +22872,25 @@ metadata \u4E3A**\u5408\u5E76**\u8BED\u4E49\uFF1A\u65B0\u952E\u8986\u76D6\u540C\
|
|
|
22462
22872
|
if (input[k]) patch[k] = input[k];
|
|
22463
22873
|
}
|
|
22464
22874
|
if (input.metadata && Object.keys(input.metadata).length) {
|
|
22465
|
-
const cur = await client2.getProduct(
|
|
22875
|
+
const cur = await client2.getProduct(productId).catch(() => null);
|
|
22466
22876
|
const existingMeta = (cur?.product ?? cur)?.metadata || {};
|
|
22467
22877
|
patch.metadata = { ...existingMeta, ...input.metadata };
|
|
22468
22878
|
}
|
|
22469
|
-
|
|
22470
|
-
|
|
22879
|
+
const normTranslations = canonicalizeTranslations(input.translations);
|
|
22880
|
+
if (!input.confirm) return { dry_run: true, will_update: { ...patch, translation_locales: Object.keys(normTranslations) } };
|
|
22881
|
+
const data = await client2.updateProduct(productId, patch);
|
|
22471
22882
|
let translationResult = null;
|
|
22472
|
-
if (
|
|
22473
|
-
const create = Object.entries(input.translations).map(([locale, t]) => ({
|
|
22474
|
-
reference: "product",
|
|
22475
|
-
reference_id: input.id,
|
|
22476
|
-
locale_code: locale,
|
|
22477
|
-
translations: { title: t?.title, description: t?.description }
|
|
22478
|
-
}));
|
|
22883
|
+
if (Object.keys(normTranslations).length) {
|
|
22479
22884
|
try {
|
|
22480
|
-
translationResult = await
|
|
22885
|
+
translationResult = await upsertTranslations(
|
|
22886
|
+
client2,
|
|
22887
|
+
"product",
|
|
22888
|
+
productId,
|
|
22889
|
+
Object.entries(normTranslations).map(([locale, t]) => ({
|
|
22890
|
+
locale_code: locale,
|
|
22891
|
+
translations: { title: t?.title, description: t?.description }
|
|
22892
|
+
}))
|
|
22893
|
+
);
|
|
22481
22894
|
} catch (e) {
|
|
22482
22895
|
return { updated: data, warning_translations: `\u7FFB\u8BD1\u5199\u5165\u5931\u8D25 \u2014\u2014 ${e?.message || e}` };
|
|
22483
22896
|
}
|
|
@@ -22505,7 +22918,8 @@ metadata \u4E3A**\u5408\u5E76**\u8BED\u4E49\uFF1A\u65B0\u952E\u8986\u76D6\u540C\
|
|
|
22505
22918
|
variant_id: input.variant_id || "(\u7B2C\u4E00\u4E2A\u53D8\u4F53)"
|
|
22506
22919
|
};
|
|
22507
22920
|
}
|
|
22508
|
-
const
|
|
22921
|
+
const productId = await client2.resolveProductId(input.product_id) || String(input.product_id).trim();
|
|
22922
|
+
const prod = await client2.getProduct(productId).catch(() => null);
|
|
22509
22923
|
const product = prod?.product ?? prod;
|
|
22510
22924
|
if (!product) return `\u9519\u8BEF\uFF1A\u627E\u4E0D\u5230\u5546\u54C1 ${input.product_id}`;
|
|
22511
22925
|
const variants = product.variants || [];
|
|
@@ -22513,7 +22927,7 @@ metadata \u4E3A**\u5408\u5E76**\u8BED\u4E49\uFF1A\u65B0\u952E\u8986\u76D6\u540C\
|
|
|
22513
22927
|
const target = input.variant_id ? variants.find((v) => v.id === input.variant_id) : variants[0];
|
|
22514
22928
|
if (!target) return `\u9519\u8BEF\uFF1A\u627E\u4E0D\u5230\u76EE\u6807\u53D8\u4F53\uFF08\u6307\u5B9A ${input.variant_id} \u6216\u7B2C\u4E00\u4E2A\u53D8\u4F53\uFF09\u3002`;
|
|
22515
22929
|
const data = await client2.updateProductPrices(
|
|
22516
|
-
|
|
22930
|
+
productId,
|
|
22517
22931
|
target.id,
|
|
22518
22932
|
input.prices.map((p) => ({ amount: p.amount, currency_code: p.currency_code }))
|
|
22519
22933
|
);
|
|
@@ -22529,7 +22943,8 @@ metadata \u4E3A**\u5408\u5E76**\u8BED\u4E49\uFF1A\u65B0\u952E\u8986\u76D6\u540C\
|
|
|
22529
22943
|
},
|
|
22530
22944
|
async run(input, { client: client2 }) {
|
|
22531
22945
|
if (!input.confirm) return { dry_run: true, will_set_status: "archived" };
|
|
22532
|
-
|
|
22946
|
+
const productId = await client2.resolveProductId(input.id) || String(input.id).trim();
|
|
22947
|
+
return client2.updateProduct(productId, { status: "archived" });
|
|
22533
22948
|
}
|
|
22534
22949
|
},
|
|
22535
22950
|
{
|
|
@@ -22821,11 +23236,539 @@ ${r.snippet}`).join("\n\n");
|
|
|
22821
23236
|
}
|
|
22822
23237
|
];
|
|
22823
23238
|
|
|
23239
|
+
// src/tools/batch.ts
|
|
23240
|
+
import { existsSync as existsSync4, readFileSync as readFileSync4 } from "node:fs";
|
|
23241
|
+
|
|
23242
|
+
// src/confirm-token.ts
|
|
23243
|
+
import { createHash as createHash2, timingSafeEqual } from "node:crypto";
|
|
23244
|
+
var VERSION = "v1";
|
|
23245
|
+
var DEFAULT_SECRET = "derlux-admin-local";
|
|
23246
|
+
function canonicalize(value) {
|
|
23247
|
+
if (value === null || value === void 0 || typeof value !== "object") {
|
|
23248
|
+
return JSON.stringify(value ?? null);
|
|
23249
|
+
}
|
|
23250
|
+
if (Array.isArray(value)) return `[${value.map(canonicalize).join(",")}]`;
|
|
23251
|
+
const obj = value;
|
|
23252
|
+
return `{${Object.keys(obj).sort().map((k) => `${JSON.stringify(k)}:${canonicalize(obj[k])}`).join(",")}}`;
|
|
23253
|
+
}
|
|
23254
|
+
function issueConfirmToken(kind, payload) {
|
|
23255
|
+
const secret = process.env.DERLUX_CONFIRM_SECRET || DEFAULT_SECRET;
|
|
23256
|
+
const digest = createHash2("sha256").update(`${VERSION}
|
|
23257
|
+
${kind}
|
|
23258
|
+
${secret}
|
|
23259
|
+
${canonicalize(payload)}`).digest("hex").slice(0, 24);
|
|
23260
|
+
return `${VERSION}:${digest}`;
|
|
23261
|
+
}
|
|
23262
|
+
function verifyConfirmToken(kind, payload, token) {
|
|
23263
|
+
if (!token || typeof token !== "string") return false;
|
|
23264
|
+
const expected = Buffer.from(issueConfirmToken(kind, payload));
|
|
23265
|
+
const actual = Buffer.from(token);
|
|
23266
|
+
return expected.length === actual.length && timingSafeEqual(expected, actual);
|
|
23267
|
+
}
|
|
23268
|
+
|
|
23269
|
+
// src/tools/batch.ts
|
|
23270
|
+
var CONTENT_TYPES = ["hero", "richtext", "image_gallery", "video", "faq", "specs"];
|
|
23271
|
+
var HANDLE_RE2 = /^[a-z0-9-]+$/;
|
|
23272
|
+
var CONFIRM_KIND = "batch_import_products";
|
|
23273
|
+
var priceShape = external_exports.object({
|
|
23274
|
+
currency_code: external_exports.string(),
|
|
23275
|
+
amount: external_exports.number().nonnegative()
|
|
23276
|
+
});
|
|
23277
|
+
var translationShape2 = external_exports.object({
|
|
23278
|
+
title: external_exports.string().optional(),
|
|
23279
|
+
description: external_exports.string().optional()
|
|
23280
|
+
});
|
|
23281
|
+
var blockShape = external_exports.object({
|
|
23282
|
+
id: external_exports.string().optional(),
|
|
23283
|
+
type: external_exports.enum(CONTENT_TYPES),
|
|
23284
|
+
data: external_exports.record(external_exports.string(), external_exports.any())
|
|
23285
|
+
});
|
|
23286
|
+
var stockShape = external_exports.object({
|
|
23287
|
+
location_id: external_exports.string().optional(),
|
|
23288
|
+
quantity: external_exports.number().int().nonnegative()
|
|
23289
|
+
});
|
|
23290
|
+
var labelsShape = external_exports.object({
|
|
23291
|
+
heading: external_exports.string(),
|
|
23292
|
+
brand: external_exports.string(),
|
|
23293
|
+
net: external_exports.string(),
|
|
23294
|
+
sku: external_exports.string(),
|
|
23295
|
+
series: external_exports.string()
|
|
23296
|
+
});
|
|
23297
|
+
var productSpecShape = external_exports.object({
|
|
23298
|
+
handle: external_exports.string(),
|
|
23299
|
+
title: external_exports.string(),
|
|
23300
|
+
sku: external_exports.string().optional(),
|
|
23301
|
+
status: external_exports.enum(PRODUCT_STATUS).optional(),
|
|
23302
|
+
subtitle: external_exports.string().optional(),
|
|
23303
|
+
description: external_exports.string().optional(),
|
|
23304
|
+
price: external_exports.number().nonnegative().optional(),
|
|
23305
|
+
currency_code: external_exports.string().optional(),
|
|
23306
|
+
prices: external_exports.array(priceShape).optional(),
|
|
23307
|
+
translations: external_exports.record(external_exports.string(), translationShape2).optional(),
|
|
23308
|
+
images: external_exports.array(external_exports.string()).optional(),
|
|
23309
|
+
metadata: external_exports.record(external_exports.string(), external_exports.string()).optional(),
|
|
23310
|
+
sales_channels: external_exports.array(external_exports.string()).optional(),
|
|
23311
|
+
collection_id: external_exports.string().optional(),
|
|
23312
|
+
weight: external_exports.number().nonnegative().optional(),
|
|
23313
|
+
length: external_exports.number().nonnegative().optional(),
|
|
23314
|
+
height: external_exports.number().nonnegative().optional(),
|
|
23315
|
+
width: external_exports.number().nonnegative().optional(),
|
|
23316
|
+
origin_country: external_exports.string().optional(),
|
|
23317
|
+
hs_code: external_exports.string().optional(),
|
|
23318
|
+
mid_code: external_exports.string().optional(),
|
|
23319
|
+
material: external_exports.string().optional(),
|
|
23320
|
+
manage_inventory: external_exports.boolean().optional(),
|
|
23321
|
+
initial_stock: stockShape.optional(),
|
|
23322
|
+
content: external_exports.record(external_exports.string(), external_exports.array(blockShape)).optional()
|
|
23323
|
+
});
|
|
23324
|
+
var optionsShape = external_exports.object({
|
|
23325
|
+
on_duplicate: external_exports.enum(["error", "skip", "update", "archive"]).default("update"),
|
|
23326
|
+
default_status: external_exports.enum(PRODUCT_STATUS).optional(),
|
|
23327
|
+
default_sales_channels: external_exports.array(external_exports.string()).optional(),
|
|
23328
|
+
default_initial_stock: stockShape.optional(),
|
|
23329
|
+
required_locales: external_exports.array(external_exports.string()).optional(),
|
|
23330
|
+
auto_content: external_exports.boolean().default(false),
|
|
23331
|
+
content_labels: external_exports.record(external_exports.string(), labelsShape).optional()
|
|
23332
|
+
});
|
|
23333
|
+
var batchSpecShape = external_exports.object({
|
|
23334
|
+
options: optionsShape.optional(),
|
|
23335
|
+
products: external_exports.array(productSpecShape).min(1).max(100)
|
|
23336
|
+
});
|
|
23337
|
+
var stripBom = (s) => s.replace(/^\uFEFF/, "");
|
|
23338
|
+
function loadBatchSpec(input) {
|
|
23339
|
+
let raw = input.spec;
|
|
23340
|
+
if (input.spec_path) {
|
|
23341
|
+
if (!existsSync4(input.spec_path)) throw new Error(`spec \u6587\u4EF6\u4E0D\u5B58\u5728: ${input.spec_path}`);
|
|
23342
|
+
raw = readFileSync4(input.spec_path, "utf8");
|
|
23343
|
+
}
|
|
23344
|
+
if (typeof raw === "string") {
|
|
23345
|
+
const s = stripBom(raw).trim();
|
|
23346
|
+
if (s.startsWith("{")) {
|
|
23347
|
+
raw = JSON.parse(s);
|
|
23348
|
+
} else if (existsSync4(s)) {
|
|
23349
|
+
raw = JSON.parse(stripBom(readFileSync4(s, "utf8")));
|
|
23350
|
+
} else {
|
|
23351
|
+
throw new Error(`spec \u4E0D\u662F JSON\uFF08\u5E94\u4EE5 { \u5F00\u5934\uFF09\uFF0C\u4E5F\u4E0D\u662F\u5B58\u5728\u7684\u6587\u4EF6\u8DEF\u5F84\uFF1A${s.slice(0, 120)}`);
|
|
23352
|
+
}
|
|
23353
|
+
}
|
|
23354
|
+
if (!raw || typeof raw !== "object") {
|
|
23355
|
+
throw new Error("\u7F3A\u5C11 spec\uFF1A\u8BF7\u4F20 spec \u5BF9\u8C61\u3001JSON \u5B57\u7B26\u4E32\uFF0C\u6216 spec / spec_path \u6307\u5411\u7684\u6587\u4EF6\u8DEF\u5F84\u3002");
|
|
23356
|
+
}
|
|
23357
|
+
return batchSpecShape.parse(raw);
|
|
23358
|
+
}
|
|
23359
|
+
var SHORT_OF = {
|
|
23360
|
+
"en-US": "en",
|
|
23361
|
+
"zh-CN": "zh",
|
|
23362
|
+
"ms-MY": "ms",
|
|
23363
|
+
"id-ID": "id"
|
|
23364
|
+
};
|
|
23365
|
+
var DEFAULT_LABELS = {
|
|
23366
|
+
en: { heading: "Product Details", brand: "Brand", net: "Net Content", sku: "SKU", series: "Series" },
|
|
23367
|
+
zh: { heading: "\u4EA7\u54C1\u8BE6\u60C5", brand: "\u54C1\u724C", net: "\u51C0\u542B\u91CF", sku: "SKU", series: "\u6240\u5C5E\u7CFB\u5217" },
|
|
23368
|
+
ms: { heading: "Butiran Produk", brand: "Jenama", net: "Kandungan Bersih", sku: "SKU", series: "Siri" },
|
|
23369
|
+
id: { heading: "Detail Produk", brand: "Merek", net: "Isi Bersih", sku: "SKU", series: "Seri" }
|
|
23370
|
+
};
|
|
23371
|
+
var HTML_ESCAPE = {
|
|
23372
|
+
"&": "&",
|
|
23373
|
+
"<": "<",
|
|
23374
|
+
">": ">",
|
|
23375
|
+
'"': """,
|
|
23376
|
+
"'": "'"
|
|
23377
|
+
};
|
|
23378
|
+
function escapeHtml(s) {
|
|
23379
|
+
return s.replace(/[&<>"']/g, (c) => HTML_ESCAPE[c] || c);
|
|
23380
|
+
}
|
|
23381
|
+
function normalizeSpec(spec) {
|
|
23382
|
+
const opts = spec.options;
|
|
23383
|
+
return {
|
|
23384
|
+
...spec,
|
|
23385
|
+
products: spec.products.map((p) => ({
|
|
23386
|
+
...p,
|
|
23387
|
+
handle: normalizeHandle(p.handle || p.title),
|
|
23388
|
+
// status / initial_stock 不在归一化阶段兜底:默认值只对「新建」生效,
|
|
23389
|
+
// 更新已有商品时绝不能静默改状态或覆盖库存(见 executeItem)。
|
|
23390
|
+
sales_channels: p.sales_channels ?? opts?.default_sales_channels ?? [],
|
|
23391
|
+
translations: canonicalizeTranslations(p.translations),
|
|
23392
|
+
content: p.content ? Object.fromEntries(Object.entries(p.content).map(([l, b]) => [normalizeLocale(l) ?? l, b])) : void 0
|
|
23393
|
+
}))
|
|
23394
|
+
};
|
|
23395
|
+
}
|
|
23396
|
+
function buildPrices(p) {
|
|
23397
|
+
if (p.prices?.length) {
|
|
23398
|
+
return p.prices.map((x) => ({ amount: x.amount, currency_code: x.currency_code }));
|
|
23399
|
+
}
|
|
23400
|
+
if (p.price != null) return [{ amount: p.price, currency_code: p.currency_code || "MYR" }];
|
|
23401
|
+
return [];
|
|
23402
|
+
}
|
|
23403
|
+
function buildAutoContent(p, opts, imageUrl) {
|
|
23404
|
+
const labelsFor = (locale) => {
|
|
23405
|
+
const short = SHORT_OF[locale] || locale.split("-")[0];
|
|
23406
|
+
return opts?.content_labels?.[short] || opts?.content_labels?.[locale] || DEFAULT_LABELS[short] || DEFAULT_LABELS.en;
|
|
23407
|
+
};
|
|
23408
|
+
const blocksFor = (description, lb) => {
|
|
23409
|
+
const rows = [
|
|
23410
|
+
{ label: lb.brand, value: p.metadata?.brand || "" },
|
|
23411
|
+
{ label: lb.net, value: p.metadata?.net_content || "" },
|
|
23412
|
+
{ label: lb.sku, value: p.sku || "" },
|
|
23413
|
+
{ label: lb.series, value: p.metadata?.series || "" }
|
|
23414
|
+
].filter((r) => r.value);
|
|
23415
|
+
const blocks = [
|
|
23416
|
+
{
|
|
23417
|
+
type: "richtext",
|
|
23418
|
+
data: { html: `<h2>${escapeHtml(lb.heading)}</h2><p>${escapeHtml(description || "")}</p>` }
|
|
23419
|
+
},
|
|
23420
|
+
{ type: "specs", data: { rows } }
|
|
23421
|
+
];
|
|
23422
|
+
if (imageUrl) blocks.push({ type: "image_gallery", data: { images: [imageUrl] } });
|
|
23423
|
+
return blocks;
|
|
23424
|
+
};
|
|
23425
|
+
const out = {};
|
|
23426
|
+
for (const [locale, t] of Object.entries(p.translations || {})) {
|
|
23427
|
+
out[locale] = blocksFor(t.description, labelsFor(locale));
|
|
23428
|
+
}
|
|
23429
|
+
if (!Object.keys(out).length) {
|
|
23430
|
+
out["en-US"] = blocksFor(p.description, labelsFor("en-US"));
|
|
23431
|
+
}
|
|
23432
|
+
return out;
|
|
23433
|
+
}
|
|
23434
|
+
async function buildPlan(ctx2, spec) {
|
|
23435
|
+
const { client: client2, config: config3 } = ctx2;
|
|
23436
|
+
const opts = spec.options;
|
|
23437
|
+
const fatal = [];
|
|
23438
|
+
const warnings = [];
|
|
23439
|
+
const channelMap = /* @__PURE__ */ new Map();
|
|
23440
|
+
const collectionMap = /* @__PURE__ */ new Map();
|
|
23441
|
+
try {
|
|
23442
|
+
const d = await client2.listSalesChannels({ limit: 100 });
|
|
23443
|
+
for (const c of d?.sales_channels || []) {
|
|
23444
|
+
channelMap.set(c.id, c.id);
|
|
23445
|
+
channelMap.set(c.name, c.id);
|
|
23446
|
+
}
|
|
23447
|
+
if (!channelMap.size) warnings.push("\u540E\u53F0\u6CA1\u6709\u4EFB\u4F55\u9500\u552E\u6E20\u9053\uFF0C\u5546\u54C1\u5C06\u4E0D\u4F1A\u5728\u524D\u53F0\u53EF\u89C1\u3002");
|
|
23448
|
+
} catch (e) {
|
|
23449
|
+
fatal.push(`\u9500\u552E\u6E20\u9053\u8BFB\u53D6\u5931\u8D25\uFF1A${e instanceof Error ? e.message : String(e)}`);
|
|
23450
|
+
}
|
|
23451
|
+
try {
|
|
23452
|
+
const d = await client2.listCollections({ limit: 100 });
|
|
23453
|
+
for (const c of d?.collections || []) {
|
|
23454
|
+
collectionMap.set(c.id, c.id);
|
|
23455
|
+
collectionMap.set(c.title, c.id);
|
|
23456
|
+
}
|
|
23457
|
+
} catch {
|
|
23458
|
+
}
|
|
23459
|
+
const required2 = (opts?.required_locales ?? config3.requiredLocales).map((l) => normalizeLocale(l) ?? l);
|
|
23460
|
+
const items = [];
|
|
23461
|
+
for (const p of spec.products) {
|
|
23462
|
+
const item = {
|
|
23463
|
+
handle: p.handle,
|
|
23464
|
+
sku: p.sku,
|
|
23465
|
+
title: p.title,
|
|
23466
|
+
action: "create",
|
|
23467
|
+
warnings: []
|
|
23468
|
+
};
|
|
23469
|
+
const block = (reason) => {
|
|
23470
|
+
item.action = "blocked";
|
|
23471
|
+
item.warnings.push(reason);
|
|
23472
|
+
};
|
|
23473
|
+
if (!HANDLE_RE2.test(p.handle)) {
|
|
23474
|
+
block(`handle "${p.handle}" \u5F52\u4E00\u5316\u540E\u975E\u6CD5\uFF0C\u8DF3\u8FC7\u8BE5\u6B3E`);
|
|
23475
|
+
}
|
|
23476
|
+
const missing = required2.filter((l) => !p.translations?.[l]?.title);
|
|
23477
|
+
if (missing.length) item.warnings.push(`\u7F3A\u8BED\u8A00 title: ${missing.join(", ")}`);
|
|
23478
|
+
for (const img of p.images || []) {
|
|
23479
|
+
if (!/^https?:\/\//i.test(img) && !existsSync4(img)) {
|
|
23480
|
+
block(`\u56FE\u7247\u4E0D\u5B58\u5728: ${img}\uFF0C\u8DF3\u8FC7\u8BE5\u6B3E`);
|
|
23481
|
+
}
|
|
23482
|
+
}
|
|
23483
|
+
if (!buildPrices(p).length) item.warnings.push("\u672A\u7ED9\u4EF7\u683C");
|
|
23484
|
+
const unknownChannels = (p.sales_channels || []).filter((n) => !channelMap.has(n));
|
|
23485
|
+
if (unknownChannels.length) {
|
|
23486
|
+
block(`\u627E\u4E0D\u5230\u6E20\u9053: ${unknownChannels.join(", ")}\uFF0C\u8DF3\u8FC7\u8BE5\u6B3E`);
|
|
23487
|
+
}
|
|
23488
|
+
if (p.collection_id && !collectionMap.has(p.collection_id)) {
|
|
23489
|
+
item.warnings.push(`\u627E\u4E0D\u5230\u96C6\u5408: ${p.collection_id}`);
|
|
23490
|
+
}
|
|
23491
|
+
let existing = null;
|
|
23492
|
+
try {
|
|
23493
|
+
const d = await client2.listProducts({ handle: p.handle, limit: 5 });
|
|
23494
|
+
existing = (d?.products || []).find((x) => x.handle === p.handle) || null;
|
|
23495
|
+
} catch (e) {
|
|
23496
|
+
item.warnings.push(`handle \u67E5\u91CD\u5931\u8D25\uFF1A${(e instanceof Error ? e.message : String(e)).slice(0, 100)}`);
|
|
23497
|
+
}
|
|
23498
|
+
if (!existing && p.sku) {
|
|
23499
|
+
try {
|
|
23500
|
+
const d = await client2.listProducts({ q: p.sku, limit: 10 });
|
|
23501
|
+
existing = (d?.products || []).find(
|
|
23502
|
+
(x) => (x.variants || []).some((v) => v.sku === p.sku)
|
|
23503
|
+
) || null;
|
|
23504
|
+
} catch {
|
|
23505
|
+
}
|
|
23506
|
+
}
|
|
23507
|
+
const strategy = opts?.on_duplicate ?? "update";
|
|
23508
|
+
if (existing) {
|
|
23509
|
+
item.existing_id = existing.id;
|
|
23510
|
+
item.warnings.push(
|
|
23511
|
+
`\u5DF2\u5B58\u5728\u540C\u6B3E\uFF1A${existing.id}\u300C${existing.title}\u300D(status=${existing.status})`
|
|
23512
|
+
);
|
|
23513
|
+
if (strategy === "error") {
|
|
23514
|
+
item.action = "blocked";
|
|
23515
|
+
fatal.push(`${p.handle}: \u5DF2\u5B58\u5728\u5546\u54C1 ${existing.id}\uFF0Con_duplicate=error \u62D2\u7EDD\u5199\u5165`);
|
|
23516
|
+
} else if (item.action === "blocked") {
|
|
23517
|
+
} else if (strategy === "skip") item.action = "skip";
|
|
23518
|
+
else if (strategy === "archive") item.action = "archive+create";
|
|
23519
|
+
else item.action = "update";
|
|
23520
|
+
}
|
|
23521
|
+
if ((item.action === "create" || item.action === "archive+create") && (p.manage_inventory ?? true) && !(p.initial_stock ?? opts?.default_initial_stock)) {
|
|
23522
|
+
item.warnings.push("\u672A\u7ED9 initial_stock\uFF0C\u521B\u5EFA\u540E 0 \u5E93\u5B58=\u524D\u53F0\u7F3A\u8D27");
|
|
23523
|
+
}
|
|
23524
|
+
items.push(item);
|
|
23525
|
+
}
|
|
23526
|
+
return { items, channelMap, collectionMap, fatal, warnings };
|
|
23527
|
+
}
|
|
23528
|
+
async function executeItem(ctx2, p, item, plan, opts) {
|
|
23529
|
+
const { client: client2 } = ctx2;
|
|
23530
|
+
const summary = {
|
|
23531
|
+
handle: p.handle,
|
|
23532
|
+
sku: p.sku || null,
|
|
23533
|
+
action: item.action,
|
|
23534
|
+
warnings: item.warnings
|
|
23535
|
+
};
|
|
23536
|
+
if (item.action === "skip" || item.action === "blocked") {
|
|
23537
|
+
summary.skipped_reason = item.action === "skip" ? "on_duplicate=skip" : "plan blocked";
|
|
23538
|
+
return summary;
|
|
23539
|
+
}
|
|
23540
|
+
if (item.action === "archive+create" && item.existing_id) {
|
|
23541
|
+
await client2.updateProduct(item.existing_id, { status: "archived" });
|
|
23542
|
+
summary.archived_existing = item.existing_id;
|
|
23543
|
+
}
|
|
23544
|
+
const imageUrls = p.images?.length ? await client2.uploadProductAssets(p.images) : [];
|
|
23545
|
+
const prices = buildPrices(p);
|
|
23546
|
+
const collectionId = p.collection_id ? plan.collectionMap.get(p.collection_id) : void 0;
|
|
23547
|
+
const physical = {};
|
|
23548
|
+
for (const k of ["weight", "length", "height", "width"]) {
|
|
23549
|
+
if (p[k] != null) physical[k] = p[k];
|
|
23550
|
+
}
|
|
23551
|
+
for (const k of ["origin_country", "hs_code", "mid_code", "material"]) {
|
|
23552
|
+
if (p[k]) physical[k] = p[k];
|
|
23553
|
+
}
|
|
23554
|
+
let productId = "";
|
|
23555
|
+
if (item.action === "update" && item.existing_id) {
|
|
23556
|
+
productId = item.existing_id;
|
|
23557
|
+
const patch = {
|
|
23558
|
+
title: p.title,
|
|
23559
|
+
...physical
|
|
23560
|
+
};
|
|
23561
|
+
if (p.status) patch.status = p.status;
|
|
23562
|
+
if (p.subtitle) patch.subtitle = p.subtitle;
|
|
23563
|
+
if (p.description) patch.description = p.description;
|
|
23564
|
+
if (collectionId) patch.collection_id = collectionId;
|
|
23565
|
+
const cur = await client2.getProduct(productId).catch(() => null);
|
|
23566
|
+
const current = cur?.product ?? cur ?? {};
|
|
23567
|
+
if (p.metadata && Object.keys(p.metadata).length) {
|
|
23568
|
+
patch.metadata = { ...current.metadata || {}, ...p.metadata };
|
|
23569
|
+
}
|
|
23570
|
+
if (imageUrls.length) {
|
|
23571
|
+
const existingUrls = (current.images || []).map((i) => i.url).filter(Boolean);
|
|
23572
|
+
patch.images = Array.from(/* @__PURE__ */ new Set([...existingUrls, ...imageUrls])).map((u) => ({ url: u }));
|
|
23573
|
+
}
|
|
23574
|
+
await client2.updateProduct(productId, patch);
|
|
23575
|
+
if (prices.length) {
|
|
23576
|
+
const v = (current.variants || [])[0];
|
|
23577
|
+
if (v) await client2.updateProductPrices(productId, v.id, prices);
|
|
23578
|
+
else summary.warnings = [...item.warnings, "\u5546\u54C1\u6CA1\u6709\u53D8\u4F53\uFF0C\u4EF7\u683C\u672A\u66F4\u65B0"];
|
|
23579
|
+
}
|
|
23580
|
+
for (const name of p.sales_channels || []) {
|
|
23581
|
+
const cid = plan.channelMap.get(name);
|
|
23582
|
+
if (!cid) continue;
|
|
23583
|
+
try {
|
|
23584
|
+
await client2.addProductsToSalesChannel(cid, [productId]);
|
|
23585
|
+
} catch {
|
|
23586
|
+
}
|
|
23587
|
+
}
|
|
23588
|
+
} else {
|
|
23589
|
+
const payload = {
|
|
23590
|
+
title: p.title,
|
|
23591
|
+
handle: p.handle,
|
|
23592
|
+
status: p.status ?? opts?.default_status ?? "draft",
|
|
23593
|
+
subtitle: p.subtitle,
|
|
23594
|
+
description: p.description,
|
|
23595
|
+
options: [{ title: "Default", values: ["Default"] }],
|
|
23596
|
+
...physical
|
|
23597
|
+
};
|
|
23598
|
+
if (p.metadata) payload.metadata = p.metadata;
|
|
23599
|
+
if (imageUrls.length) payload.images = imageUrls.map((url) => ({ url }));
|
|
23600
|
+
const channelIds = (p.sales_channels || []).map((n) => plan.channelMap.get(n)).filter(Boolean);
|
|
23601
|
+
if (channelIds.length) payload.sales_channels = channelIds.map((id) => ({ id }));
|
|
23602
|
+
if (collectionId) payload.collection_id = collectionId;
|
|
23603
|
+
if (prices.length || p.sku) {
|
|
23604
|
+
payload.variants = [
|
|
23605
|
+
{
|
|
23606
|
+
title: "Default",
|
|
23607
|
+
options: { Default: "Default" },
|
|
23608
|
+
prices,
|
|
23609
|
+
manage_inventory: p.manage_inventory ?? true,
|
|
23610
|
+
...p.sku ? { sku: p.sku } : {}
|
|
23611
|
+
}
|
|
23612
|
+
];
|
|
23613
|
+
}
|
|
23614
|
+
const data = await client2.createProduct(payload);
|
|
23615
|
+
productId = data?.product?.id || data?.id;
|
|
23616
|
+
}
|
|
23617
|
+
if (!productId) throw new Error(`${p.handle}: \u672A\u62FF\u5230\u5546\u54C1 id`);
|
|
23618
|
+
summary.id = productId;
|
|
23619
|
+
const locales = Object.keys(p.translations || {});
|
|
23620
|
+
if (locales.length) {
|
|
23621
|
+
const r = await upsertTranslations(
|
|
23622
|
+
client2,
|
|
23623
|
+
"product",
|
|
23624
|
+
productId,
|
|
23625
|
+
locales.map((locale) => ({
|
|
23626
|
+
locale_code: locale,
|
|
23627
|
+
translations: {
|
|
23628
|
+
title: p.translations?.[locale]?.title,
|
|
23629
|
+
description: p.translations?.[locale]?.description
|
|
23630
|
+
}
|
|
23631
|
+
}))
|
|
23632
|
+
);
|
|
23633
|
+
summary.translations = `${r.created} created / ${r.updated} updated`;
|
|
23634
|
+
}
|
|
23635
|
+
const effectiveStock = item.action === "update" ? p.initial_stock : p.initial_stock ?? opts?.default_initial_stock;
|
|
23636
|
+
if (effectiveStock) {
|
|
23637
|
+
await applyProductStock(ctx2, {
|
|
23638
|
+
productId,
|
|
23639
|
+
sku: p.sku,
|
|
23640
|
+
locationId: effectiveStock.location_id,
|
|
23641
|
+
quantity: effectiveStock.quantity,
|
|
23642
|
+
manageInventory: p.manage_inventory ?? true
|
|
23643
|
+
});
|
|
23644
|
+
summary.stock = effectiveStock.quantity;
|
|
23645
|
+
}
|
|
23646
|
+
const contents = p.content || (opts?.auto_content ? buildAutoContent(p, opts, imageUrls[0]) : {});
|
|
23647
|
+
const contentLocales = [];
|
|
23648
|
+
for (const [locale, blocks] of Object.entries(contents)) {
|
|
23649
|
+
await client2.createProductContent({ product_id: productId, locale, status: "published", blocks });
|
|
23650
|
+
contentLocales.push(locale);
|
|
23651
|
+
}
|
|
23652
|
+
summary.content_locales = contentLocales;
|
|
23653
|
+
summary.images = imageUrls.length;
|
|
23654
|
+
summary.prices = prices.map((x) => `${x.currency_code}:${x.amount}`);
|
|
23655
|
+
return summary;
|
|
23656
|
+
}
|
|
23657
|
+
async function runBatchImport(ctx2, rawSpec, runOpts = {}) {
|
|
23658
|
+
const spec = normalizeSpec(rawSpec);
|
|
23659
|
+
const plan = await buildPlan(ctx2, spec);
|
|
23660
|
+
const tokenPayload = {
|
|
23661
|
+
spec,
|
|
23662
|
+
plan: plan.items.map((i) => ({
|
|
23663
|
+
handle: i.handle,
|
|
23664
|
+
action: i.action,
|
|
23665
|
+
existing_id: i.existing_id ?? null
|
|
23666
|
+
}))
|
|
23667
|
+
};
|
|
23668
|
+
const token = issueConfirmToken(CONFIRM_KIND, tokenPayload);
|
|
23669
|
+
const confirm = Boolean(runOpts.confirm);
|
|
23670
|
+
const verbose = Boolean(runOpts.verbose);
|
|
23671
|
+
const blockedItems = plan.items.filter((i) => i.action === "blocked");
|
|
23672
|
+
const preview = {
|
|
23673
|
+
dry_run: !confirm,
|
|
23674
|
+
total: spec.products.length,
|
|
23675
|
+
on_duplicate: spec.options?.on_duplicate ?? "update",
|
|
23676
|
+
confirm_token: token,
|
|
23677
|
+
summary: plan.items.map((i) => ({
|
|
23678
|
+
handle: i.handle,
|
|
23679
|
+
sku: i.sku || null,
|
|
23680
|
+
action: i.action,
|
|
23681
|
+
warnings: i.warnings
|
|
23682
|
+
})),
|
|
23683
|
+
blocked: blockedItems.length,
|
|
23684
|
+
warnings: plan.warnings,
|
|
23685
|
+
fatal: plan.fatal
|
|
23686
|
+
};
|
|
23687
|
+
if (verbose) preview.plan = plan.items;
|
|
23688
|
+
if (!confirm) {
|
|
23689
|
+
preview.note = plan.fatal.length ? "\u9884\u68C0\u6709\u81F4\u547D\u95EE\u9898\uFF08\u73AF\u5883\u7EA7\uFF09\uFF0C\u4FEE\u6B63\u540E\u91CD\u65B0 dry-run\uFF1B\u672C\u6B21\u4E0D\u4F1A\u5199\u5E93\u3002" : blockedItems.length ? `\u672A\u5199\u5E93\u3002\u5176\u4E2D ${blockedItems.length} \u6B3E\u9884\u68C0\u88AB\u963B\u65AD\uFF08summary \u4E2D action=blocked\uFF09\uFF0Ccommit \u65F6\u53EA\u4F1A\u5199\u5165\u5176\u4F59\u5546\u54C1\uFF1B\u4FEE\u6B63\u540E\u91CD\u65B0 dry-run \u62FF\u65B0 token\u3002` : "\u672A\u5199\u5E93\u3002\u786E\u8BA4\u540E\u91CD\u65B0\u8C03\u7528\u5E76\u5E26 confirm=true \u4E0E\u540C\u4E00 confirm_token\u3002";
|
|
23690
|
+
return preview;
|
|
23691
|
+
}
|
|
23692
|
+
if (plan.fatal.length) {
|
|
23693
|
+
return { ...preview, dry_run: false, executed: false, error: "\u9884\u68C0\u672A\u901A\u8FC7\uFF0C\u62D2\u7EDD\u5199\u5165\u3002", note: "\u4FEE\u6B63 spec \u540E\u91CD\u65B0 dry-run\u3002" };
|
|
23694
|
+
}
|
|
23695
|
+
if (!verifyConfirmToken(CONFIRM_KIND, tokenPayload, runOpts.confirm_token)) {
|
|
23696
|
+
return {
|
|
23697
|
+
dry_run: false,
|
|
23698
|
+
executed: false,
|
|
23699
|
+
error: "confirm_token \u7F3A\u5931\u6216\u4E0D\u5339\u914D\uFF08spec \u88AB\u6539\u52A8\u3001\u540E\u53F0\u72B6\u6001\u4E0E dry-run \u65F6\u4E0D\u540C\uFF0C\u6216\u8DF3\u8FC7\u4E86 dry-run\uFF09\u3002",
|
|
23700
|
+
note: "\u8BF7\u91CD\u65B0\u8DD1\u4E00\u6B21 dry-run \u62FF\u5230\u65B0\u7684 confirm_token\uFF0C\u786E\u8BA4\u9884\u89C8\u540E\u518D commit\u3002",
|
|
23701
|
+
expected_token_prefix: token.slice(0, 12) + "\u2026"
|
|
23702
|
+
};
|
|
23703
|
+
}
|
|
23704
|
+
const results = [];
|
|
23705
|
+
const failed = [];
|
|
23706
|
+
for (let i = 0; i < spec.products.length; i++) {
|
|
23707
|
+
try {
|
|
23708
|
+
results.push(await executeItem(ctx2, spec.products[i], plan.items[i], plan, spec.options));
|
|
23709
|
+
} catch (e) {
|
|
23710
|
+
const msg = e instanceof Error ? e.message : String(e);
|
|
23711
|
+
failed.push(`${spec.products[i].handle}: ${msg}`);
|
|
23712
|
+
results.push({ handle: spec.products[i].handle, action: "failed", error: msg.slice(0, 300) });
|
|
23713
|
+
}
|
|
23714
|
+
}
|
|
23715
|
+
const actions = results.map((r) => String(r.action));
|
|
23716
|
+
const countOf = (a) => actions.filter((x) => x === a).length;
|
|
23717
|
+
const blocked = countOf("blocked");
|
|
23718
|
+
const skipped = countOf("skip");
|
|
23719
|
+
const succeeded = actions.length - failed.length - blocked - skipped;
|
|
23720
|
+
return {
|
|
23721
|
+
dry_run: false,
|
|
23722
|
+
executed: true,
|
|
23723
|
+
total: spec.products.length,
|
|
23724
|
+
succeeded,
|
|
23725
|
+
blocked,
|
|
23726
|
+
skipped,
|
|
23727
|
+
failed,
|
|
23728
|
+
results,
|
|
23729
|
+
note: failed.length ? "\u90E8\u5206\u5546\u54C1\u5931\u8D25\uFF1B\u4FEE\u6B63\u540E\u53EF\u7528 on_duplicate=update \u91CD\u8DD1\uFF08\u5DF2\u662F\u5E42\u7B49\uFF0C\u4E0D\u4F1A\u4EA7\u751F\u91CD\u590D\u5546\u54C1\uFF09\u3002" : blocked ? `${blocked} \u6B3E\u56E0\u9884\u68C0\u95EE\u9898\u88AB\u8DF3\u8FC7\uFF08\u89C1 results.action=blocked \u4E0E warnings\uFF09\uFF1B\u4FEE\u6B63\u540E\u91CD\u8DD1\u5373\u53EF\u8865\u9F50\u3002` : skipped ? `${skipped} \u6B3E\u6309 on_duplicate=skip \u8DF3\u8FC7\uFF0C\u5176\u4F59\u5B8C\u6210\u3002` : "\u5168\u90E8\u5B8C\u6210\uFF1B\u91CD\u8DD1\u8BF7\u7528 on_duplicate=update\uFF08\u5E42\u7B49\uFF09\u3002"
|
|
23730
|
+
};
|
|
23731
|
+
}
|
|
23732
|
+
var batchTools = [
|
|
23733
|
+
{
|
|
23734
|
+
name: "batch_import_products",
|
|
23735
|
+
description: `\u3010\u6279\u91CF\u5F55\u5165\u9996\u9009\u3011\u4E00\u6B21\u5BFC\u5165\u591A\u6B3E\u5B8C\u6574\u5546\u54C1\uFF1A\u67E5\u91CD \u2192 \u56FE\u7247\u4E0A\u4F20 \u2192 \u5546\u54C1\u4E0E\u591A\u5E01\u79CD\u4EF7\u683C \u2192 \u56DB\u8BED\u8A00\u7FFB\u8BD1 \u2192 \u5E93\u5B58 \u2192 \u9500\u552E\u6E20\u9053 \u2192 \u5404\u8BED\u8A00\u8BE6\u60C5\u9875\u5BCC\u5185\u5BB9 \u2192 \u6458\u8981\u56DE\u8BFB\u3002
|
|
23736
|
+
spec \u4E3A\u58F0\u660E\u5F0F JSON\uFF08\u5BF9\u8C61\u3001JSON \u5B57\u7B26\u4E32\u6216 spec_path \u6587\u4EF6\u8DEF\u5F84\uFF09\uFF0C\u5B57\u6BB5\u4E0E create_product \u57FA\u672C\u4E00\u81F4\uFF0C\u53E6\u53EF\u5E26 content(locale\u2192blocks) \u6216 options.auto_content=true \u81EA\u52A8\u751F\u6210\u5BCC\u5185\u5BB9\u3002
|
|
23737
|
+
options.on_duplicate: update(\u9ED8\u8BA4\uFF0C\u6309 handle/SKU \u5E42\u7B49 upsert) | skip | error | archive(\u65E7\u6B3E\u4E0B\u67B6\u540E\u65B0\u5EFA)\u3002
|
|
23738
|
+
\u9ED8\u8BA4 dry_run\uFF1A\u53EA\u56DE\u6BCF\u6B3E\u4E00\u884C\u6458\u8981 + warnings + confirm_token\uFF0C\u4E0D\u5199\u5E93\uFF1B\u786E\u8BA4\u540E\u7528 confirm=true \u5E76\u539F\u6837\u5E26\u56DE confirm_token \u624D\u6267\u884C\u3002
|
|
23739
|
+
\u65B0\u5EFA\u5546\u54C1\u9ED8\u8BA4 status=draft\uFF08skill \u786C\u89C4\u5219\uFF1A\u4E0D\u76F4\u63A5\u4E0A\u67B6\uFF09\uFF0C\u662F\u5426\u4E0A\u67B6\u7531 spec \u663E\u5F0F\u58F0\u660E\u3002
|
|
23740
|
+
on_duplicate=update \u547D\u4E2D\u5DF2\u6709\u5546\u54C1\u65F6**\u4E0D\u6539\u52A8\u73B0\u6709 status**\uFF0C\u53EA\u6709 spec \u663E\u5F0F\u7ED9 status \u624D\u5207\u6362\uFF08\u907F\u514D\u590D\u8DD1\u628A\u5DF2\u4E0A\u67B6\u5546\u54C1\u6253\u56DE\u8349\u7A3F\uFF09\uFF1B
|
|
23741
|
+
options.default_initial_stock \u4E5F\u53EA\u4F5C\u7528\u4E8E\u65B0\u5EFA\uFF0C\u66F4\u65B0\u4E0D\u4F1A\u8986\u76D6\u5DF2\u6709\u5E93\u5B58\uFF0C\u9700\u8865\u5E93\u5B58\u8BF7\u5728\u5BF9\u5E94\u5546\u54C1\u4E0A\u663E\u5F0F\u7ED9 initial_stock\u3002`,
|
|
23742
|
+
schema: {
|
|
23743
|
+
spec: external_exports.any().optional().describe("\u5BFC\u5165 spec \u5BF9\u8C61\u6216 JSON \u5B57\u7B26\u4E32\uFF1B\u4E5F\u53EF\u6539\u7528 spec_path"),
|
|
23744
|
+
spec_path: external_exports.string().optional().describe("spec JSON \u6587\u4EF6\u7684\u7EDD\u5BF9\u8DEF\u5F84\uFF08\u4F18\u5148\u4E8E spec\uFF09"),
|
|
23745
|
+
confirm: external_exports.boolean().default(false),
|
|
23746
|
+
confirm_token: external_exports.string().optional().describe("dry-run \u8FD4\u56DE\u7684\u4EE4\u724C\uFF0Cconfirm=true \u65F6\u5FC5\u586B"),
|
|
23747
|
+
verbose: external_exports.boolean().default(false).describe("true \u65F6\u9884\u89C8\u9644\u5E26\u5B8C\u6574 plan\uFF08\u9ED8\u8BA4\u53EA\u56DE\u6458\u8981\uFF0C\u7701 token\uFF09")
|
|
23748
|
+
},
|
|
23749
|
+
async run(input, ctx2) {
|
|
23750
|
+
try {
|
|
23751
|
+
const spec = loadBatchSpec({ spec: input.spec, spec_path: input.spec_path });
|
|
23752
|
+
return await runBatchImport(ctx2, spec, {
|
|
23753
|
+
confirm: input.confirm,
|
|
23754
|
+
confirm_token: input.confirm_token,
|
|
23755
|
+
verbose: input.verbose
|
|
23756
|
+
});
|
|
23757
|
+
} catch (e) {
|
|
23758
|
+
return { error: `spec \u89E3\u6790\u5931\u8D25\uFF1A${e instanceof Error ? e.message : String(e)}` };
|
|
23759
|
+
}
|
|
23760
|
+
}
|
|
23761
|
+
}
|
|
23762
|
+
];
|
|
23763
|
+
|
|
22824
23764
|
// src/tools/index.ts
|
|
22825
23765
|
var toolDefs = [
|
|
23766
|
+
...contextTools,
|
|
22826
23767
|
...productTools,
|
|
23768
|
+
...translationTools,
|
|
22827
23769
|
...stockTools,
|
|
22828
23770
|
...opsTools,
|
|
23771
|
+
...batchTools,
|
|
22829
23772
|
...docTools
|
|
22830
23773
|
];
|
|
22831
23774
|
|
|
@@ -22842,24 +23785,117 @@ function audit(auditFile, name, args, ok) {
|
|
|
22842
23785
|
}
|
|
22843
23786
|
}
|
|
22844
23787
|
|
|
23788
|
+
// src/cli.ts
|
|
23789
|
+
function isCliInvocation(argv2) {
|
|
23790
|
+
return argv2[0] === "import" || argv2.some((a) => a.startsWith("--"));
|
|
23791
|
+
}
|
|
23792
|
+
var USAGE = `derlux-admin-mcp CLI
|
|
23793
|
+
|
|
23794
|
+
--preflight \u4E00\u6B21\u6027\u73AF\u5883/\u8D26\u53F7/\u6743\u9650\u81EA\u68C0\uFF0C\u8F93\u51FA JSON \u540E\u9000\u51FA\uFF08\u4E0D\u542F\u52A8 MCP\uFF09
|
|
23795
|
+
import --spec <path> --dry-run \u9884\u89C8\u6574\u6279\u5BFC\u5165\uFF0C\u8F93\u51FA\u6458\u8981\u4E0E confirm_token\uFF08\u4E0D\u5199\u5E93\uFF09
|
|
23796
|
+
import --spec <path> --commit --token <confirm_token> [--verbose]
|
|
23797
|
+
\u6309 dry-run \u7684 spec \u6B63\u5F0F\u5199\u5165
|
|
23798
|
+
--help \u663E\u793A\u672C\u5E2E\u52A9
|
|
23799
|
+
|
|
23800
|
+
\u793A\u4F8B\uFF1A
|
|
23801
|
+
MEDUSA_BACKEND_URL=https://admin.example.com DERLUX_ADMIN_EMAIL=ops@... \\
|
|
23802
|
+
DERLUX_ADMIN_PASSWORD=... derlux-admin-mcp --preflight
|
|
23803
|
+
`;
|
|
23804
|
+
function argValue(args, flag) {
|
|
23805
|
+
const i = args.indexOf(flag);
|
|
23806
|
+
const v = i >= 0 ? args[i + 1] : void 0;
|
|
23807
|
+
return v && !v.startsWith("--") ? v : void 0;
|
|
23808
|
+
}
|
|
23809
|
+
var IMPORT_FLAGS = /* @__PURE__ */ new Set(["--spec", "--dry-run", "--commit", "--token", "--verbose", "--help"]);
|
|
23810
|
+
async function runCli(argv2, ctx2) {
|
|
23811
|
+
if (argv2.includes("--help")) {
|
|
23812
|
+
process.stdout.write(USAGE);
|
|
23813
|
+
return 0;
|
|
23814
|
+
}
|
|
23815
|
+
if (argv2.includes("--preflight")) {
|
|
23816
|
+
const tool = toolDefs.find((t) => t.name === "get_context");
|
|
23817
|
+
if (!tool) return 1;
|
|
23818
|
+
const out = await tool.run({ probe: true, include_raw: false }, ctx2);
|
|
23819
|
+
process.stdout.write(`${JSON.stringify(out, null, 2)}
|
|
23820
|
+
`);
|
|
23821
|
+
return out.ok ? 0 : 1;
|
|
23822
|
+
}
|
|
23823
|
+
if (argv2[0] !== "import") {
|
|
23824
|
+
process.stderr.write(`\u672A\u77E5\u547D\u4EE4/\u53C2\u6570: ${argv2.join(" ")}
|
|
23825
|
+
|
|
23826
|
+
${USAGE}`);
|
|
23827
|
+
return 1;
|
|
23828
|
+
}
|
|
23829
|
+
const args = argv2.slice(1);
|
|
23830
|
+
const unknown2 = args.filter((a) => a.startsWith("-") && !IMPORT_FLAGS.has(a));
|
|
23831
|
+
if (unknown2.length) {
|
|
23832
|
+
process.stderr.write(`\u672A\u77E5\u53C2\u6570: ${unknown2.join(", ")}
|
|
23833
|
+
|
|
23834
|
+
${USAGE}`);
|
|
23835
|
+
return 1;
|
|
23836
|
+
}
|
|
23837
|
+
const specPath = argValue(args, "--spec");
|
|
23838
|
+
if (!specPath) {
|
|
23839
|
+
process.stderr.write("\u7F3A\u5C11 --spec <path>\n");
|
|
23840
|
+
return 1;
|
|
23841
|
+
}
|
|
23842
|
+
const commit = args.includes("--commit");
|
|
23843
|
+
const token = argValue(args, "--token");
|
|
23844
|
+
if (commit && !token) {
|
|
23845
|
+
process.stderr.write("--commit \u5FC5\u987B\u5E26 --token <dry-run \u8FD4\u56DE\u7684 confirm_token>\n");
|
|
23846
|
+
return 1;
|
|
23847
|
+
}
|
|
23848
|
+
try {
|
|
23849
|
+
const spec = loadBatchSpec({ spec_path: specPath });
|
|
23850
|
+
const out = await runBatchImport(ctx2, spec, {
|
|
23851
|
+
confirm: commit,
|
|
23852
|
+
confirm_token: token,
|
|
23853
|
+
verbose: args.includes("--verbose")
|
|
23854
|
+
});
|
|
23855
|
+
process.stdout.write(`${JSON.stringify(out, null, 2)}
|
|
23856
|
+
`);
|
|
23857
|
+
if (out.error) return 1;
|
|
23858
|
+
if (commit && (out.failed?.length || out.blocked)) return 1;
|
|
23859
|
+
return 0;
|
|
23860
|
+
} catch (e) {
|
|
23861
|
+
process.stderr.write(`\u5BFC\u5165\u5931\u8D25\uFF1A${e instanceof Error ? e.message : String(e)}
|
|
23862
|
+
`);
|
|
23863
|
+
return 1;
|
|
23864
|
+
}
|
|
23865
|
+
}
|
|
23866
|
+
|
|
22845
23867
|
// src/index.ts
|
|
22846
23868
|
var config2 = loadConfig();
|
|
22847
23869
|
var auth = new AuthManager(config2);
|
|
22848
23870
|
var client = new MedusaAdminClient(config2, auth);
|
|
22849
|
-
var ctx = { client, config: config2 };
|
|
22850
|
-
var
|
|
23871
|
+
var ctx = { client, config: config2, auth };
|
|
23872
|
+
var argv = process.argv.slice(2);
|
|
23873
|
+
if (isCliInvocation(argv)) {
|
|
23874
|
+
const code = await runCli(argv, ctx);
|
|
23875
|
+
process.exit(code);
|
|
23876
|
+
}
|
|
23877
|
+
process.stderr.write(
|
|
23878
|
+
`[derlux-admin] v0.2.0 backend=${config2.backendUrl} account=${config2.adminEmail || "(\u672A\u914D\u7F6E)"} session_scope=${config2.sessionScope} tools=${toolDefs.length}
|
|
23879
|
+
`
|
|
23880
|
+
);
|
|
23881
|
+
var server = new McpServer({ name: "derlux-admin", version: "0.2.0" });
|
|
23882
|
+
function isToolSuccess(result) {
|
|
23883
|
+
if (!result || typeof result !== "object") return true;
|
|
23884
|
+
const r = result;
|
|
23885
|
+
return !("error" in r) && r.executed !== false;
|
|
23886
|
+
}
|
|
22851
23887
|
for (const def of toolDefs) {
|
|
22852
23888
|
server.tool(def.name, def.description, def.schema, async (args) => {
|
|
22853
23889
|
try {
|
|
22854
23890
|
const result = await def.run(args, ctx);
|
|
22855
|
-
audit(config2.auditFile, def.name, args,
|
|
23891
|
+
audit(config2.auditFile, def.name, args, isToolSuccess(result));
|
|
22856
23892
|
const text = typeof result === "string" ? result : JSON.stringify(result, null, 2);
|
|
22857
23893
|
return { content: [{ type: "text", text }] };
|
|
22858
23894
|
} catch (err) {
|
|
22859
23895
|
audit(config2.auditFile, def.name, args, false);
|
|
22860
23896
|
const message = err instanceof Error ? err.message : String(err);
|
|
22861
23897
|
return {
|
|
22862
|
-
content: [{ type: "text", text: `\u5DE5\u5177\u6267\u884C\u5931\u8D25\uFF1A${message}` }],
|
|
23898
|
+
content: [{ type: "text", text: `\u5DE5\u5177 ${def.name} \u6267\u884C\u5931\u8D25\uFF1A${message}` }],
|
|
22863
23899
|
isError: true
|
|
22864
23900
|
};
|
|
22865
23901
|
}
|