@harrylabsj/kiwi-merchant-cloud 0.12.14 → 0.12.16
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/app/a2a/node.d.ts +5 -0
- package/app/a2a/node.js +69 -2
- package/app/a2a/node.js.map +1 -1
- package/app/a2a/server/merchant-handler.d.ts +8 -0
- package/app/a2a/server/merchant-handler.js +105 -14
- package/app/a2a/server/merchant-handler.js.map +1 -1
- package/app/a2a/server/negotiation-advisor.d.ts +54 -0
- package/app/a2a/server/negotiation-advisor.js +107 -0
- package/app/a2a/server/negotiation-advisor.js.map +1 -0
- package/app/a2a/server/negotiation-approvals.d.ts +114 -0
- package/app/a2a/server/negotiation-approvals.js +240 -0
- package/app/a2a/server/negotiation-approvals.js.map +1 -0
- package/app/buyer-core/a2a-knp.d.ts +14 -0
- package/app/buyer-core/a2a-knp.js +24 -0
- package/app/buyer-core/a2a-knp.js.map +1 -1
- package/app/buyer-core/a2a-negotiator.js +66 -11
- package/app/buyer-core/a2a-negotiator.js.map +1 -1
- package/app/buyer-core/protocol-recovery.d.ts +1 -1
- package/app/buyer-core/receive-gate.js +7 -0
- package/app/buyer-core/receive-gate.js.map +1 -1
- package/app/buyer-core/service.d.ts +13 -0
- package/app/buyer-core/service.js +73 -10
- package/app/buyer-core/service.js.map +1 -1
- package/app/cli.js +247 -0
- package/app/cli.js.map +1 -1
- package/app/cloud/bootstrap.js +12 -0
- package/app/cloud/bootstrap.js.map +1 -1
- package/app/cloud-sample/products.json +3 -3
- package/app/http/merchant-management/api.d.ts +3 -0
- package/app/http/merchant-management/api.js +419 -0
- package/app/http/merchant-management/api.js.map +1 -1
- package/app/http/merchant-management/page.js +95 -1
- package/app/http/merchant-management/page.js.map +1 -1
- package/app/mcp/merchant-ops-server.d.ts +38 -0
- package/app/mcp/merchant-ops-server.js +283 -0
- package/app/mcp/merchant-ops-server.js.map +1 -0
- package/app/mcp/merchant-runtime-assembly.js +28 -0
- package/app/mcp/merchant-runtime-assembly.js.map +1 -1
- package/app/mcp/merchant-server.d.ts +16 -0
- package/app/mcp/merchant-server.js +24 -0
- package/app/mcp/merchant-server.js.map +1 -1
- package/app/merchant/application/actor.d.ts +1 -1
- package/app/merchant/application/actor.js +43 -1
- package/app/merchant/application/actor.js.map +1 -1
- package/app/merchant/negotiation-observer.d.ts +35 -0
- package/app/merchant/negotiation-observer.js +159 -51
- package/app/merchant/negotiation-observer.js.map +1 -1
- package/app/merchant/negotiation-ops.d.ts +77 -0
- package/app/merchant/negotiation-ops.js +203 -0
- package/app/merchant/negotiation-ops.js.map +1 -0
- package/app/merchant/quote-calculator.d.ts +7 -0
- package/app/merchant/quote-calculator.js +35 -24
- package/app/merchant/quote-calculator.js.map +1 -1
- package/app/merchant/watch/detect.d.ts +37 -0
- package/app/merchant/watch/detect.js +147 -0
- package/app/merchant/watch/detect.js.map +1 -0
- package/app/merchant/watch/notify.d.ts +48 -0
- package/app/merchant/watch/notify.js +108 -0
- package/app/merchant/watch/notify.js.map +1 -0
- package/app/merchant/watch/service.d.ts +43 -0
- package/app/merchant/watch/service.js +167 -0
- package/app/merchant/watch/service.js.map +1 -0
- package/app/merchant/watch/state.d.ts +49 -0
- package/app/merchant/watch/state.js +68 -0
- package/app/merchant/watch/state.js.map +1 -0
- package/app/merchant/watch/weixin.d.ts +54 -0
- package/app/merchant/watch/weixin.js +271 -0
- package/app/merchant/watch/weixin.js.map +1 -0
- package/app/merchant-core/commercial/calculate.d.ts +18 -0
- package/app/merchant-core/commercial/calculate.js +196 -0
- package/app/merchant-core/commercial/calculate.js.map +1 -0
- package/app/merchant-core/commercial/types.d.ts +91 -0
- package/app/merchant-core/commercial/types.js +17 -0
- package/app/merchant-core/commercial/types.js.map +1 -0
- package/app/merchant-core/contribution/calculate.d.ts +24 -0
- package/app/merchant-core/contribution/calculate.js +172 -0
- package/app/merchant-core/contribution/calculate.js.map +1 -0
- package/app/merchant-core/contribution/repository.d.ts +60 -0
- package/app/merchant-core/contribution/repository.js +121 -0
- package/app/merchant-core/contribution/repository.js.map +1 -0
- package/app/merchant-core/contribution/types.d.ts +97 -0
- package/app/merchant-core/contribution/types.js +24 -0
- package/app/merchant-core/contribution/types.js.map +1 -0
- package/app/merchant-core/followup/lease.d.ts +27 -0
- package/app/merchant-core/followup/lease.js +45 -0
- package/app/merchant-core/followup/lease.js.map +1 -0
- package/app/merchant-core/followup/repository.d.ts +141 -0
- package/app/merchant-core/followup/repository.js +280 -0
- package/app/merchant-core/followup/repository.js.map +1 -0
- package/app/merchant-core/followup/retry.d.ts +27 -0
- package/app/merchant-core/followup/retry.js +61 -0
- package/app/merchant-core/followup/retry.js.map +1 -0
- package/app/merchant-core/followup/service.d.ts +114 -0
- package/app/merchant-core/followup/service.js +191 -0
- package/app/merchant-core/followup/service.js.map +1 -0
- package/app/merchant-core/followup/state.d.ts +25 -0
- package/app/merchant-core/followup/state.js +126 -0
- package/app/merchant-core/followup/state.js.map +1 -0
- package/app/merchant-core/followup/types.d.ts +75 -0
- package/app/merchant-core/followup/types.js +41 -0
- package/app/merchant-core/followup/types.js.map +1 -0
- package/app/merchant-core/metrics/timing.d.ts +63 -0
- package/app/merchant-core/metrics/timing.js +125 -0
- package/app/merchant-core/metrics/timing.js.map +1 -0
- package/app/merchant-core/operating/repository.d.ts +97 -0
- package/app/merchant-core/operating/repository.js +266 -0
- package/app/merchant-core/operating/repository.js.map +1 -0
- package/app/merchant-core/operating/service.d.ts +63 -0
- package/app/merchant-core/operating/service.js +336 -0
- package/app/merchant-core/operating/service.js.map +1 -0
- package/app/merchant-core/operating/types.d.ts +102 -0
- package/app/merchant-core/operating/types.js +24 -0
- package/app/merchant-core/operating/types.js.map +1 -0
- package/app/merchant-core/opportunity/repository.d.ts +128 -0
- package/app/merchant-core/opportunity/repository.js +251 -0
- package/app/merchant-core/opportunity/repository.js.map +1 -0
- package/app/merchant-core/opportunity/service.d.ts +117 -0
- package/app/merchant-core/opportunity/service.js +388 -0
- package/app/merchant-core/opportunity/service.js.map +1 -0
- package/app/merchant-core/opportunity/state.d.ts +33 -0
- package/app/merchant-core/opportunity/state.js +166 -0
- package/app/merchant-core/opportunity/state.js.map +1 -0
- package/app/merchant-core/opportunity/types.d.ts +141 -0
- package/app/merchant-core/opportunity/types.js +42 -0
- package/app/merchant-core/opportunity/types.js.map +1 -0
- package/app/merchant-core/ops/facade.d.ts +159 -0
- package/app/merchant-core/ops/facade.js +213 -0
- package/app/merchant-core/ops/facade.js.map +1 -0
- package/app/merchant-core/ops/schema.d.ts +25 -0
- package/app/merchant-core/ops/schema.js +448 -0
- package/app/merchant-core/ops/schema.js.map +1 -0
- package/app/merchant-core/ops/surface.d.ts +49 -0
- package/app/merchant-core/ops/surface.js +304 -0
- package/app/merchant-core/ops/surface.js.map +1 -0
- package/app/merchant-core/orders/csv.d.ts +36 -0
- package/app/merchant-core/orders/csv.js +173 -0
- package/app/merchant-core/orders/csv.js.map +1 -0
- package/app/merchant-core/orders/model.d.ts +155 -0
- package/app/merchant-core/orders/model.js +237 -0
- package/app/merchant-core/orders/model.js.map +1 -0
- package/app/merchant-core/orders/repository.d.ts +99 -0
- package/app/merchant-core/orders/repository.js +221 -0
- package/app/merchant-core/orders/repository.js.map +1 -0
- package/app/merchant-core/orders/service.d.ts +84 -0
- package/app/merchant-core/orders/service.js +121 -0
- package/app/merchant-core/orders/service.js.map +1 -0
- package/app/merchant-core/orders/shopping-cli-source.d.ts +58 -0
- package/app/merchant-core/orders/shopping-cli-source.js +164 -0
- package/app/merchant-core/orders/shopping-cli-source.js.map +1 -0
- package/app/merchant-core/proposal/engine.d.ts +31 -0
- package/app/merchant-core/proposal/engine.js +348 -0
- package/app/merchant-core/proposal/engine.js.map +1 -0
- package/app/merchant-core/proposal/publish.d.ts +46 -0
- package/app/merchant-core/proposal/publish.js +79 -0
- package/app/merchant-core/proposal/publish.js.map +1 -0
- package/app/merchant-core/proposal/repository.d.ts +60 -0
- package/app/merchant-core/proposal/repository.js +186 -0
- package/app/merchant-core/proposal/repository.js.map +1 -0
- package/app/merchant-core/proposal/service.d.ts +73 -0
- package/app/merchant-core/proposal/service.js +149 -0
- package/app/merchant-core/proposal/service.js.map +1 -0
- package/app/merchant-core/proposal/types.d.ts +163 -0
- package/app/merchant-core/proposal/types.js +25 -0
- package/app/merchant-core/proposal/types.js.map +1 -0
- package/app/merchant-runtime/services.d.ts +0 -8
- package/app/merchant-runtime/services.js +38 -0
- package/app/merchant-runtime/services.js.map +1 -1
- package/app/product-cli.js +5 -0
- package/app/product-cli.js.map +1 -1
- package/build-manifest.json +717 -102
- package/package.json +1 -1
- package/runtime-package.json +1 -1
- package/shipping-sbom.cdx.json +6 -6
- package/shipping-source.json +12 -12
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Copyright 2026 harrylabsj
|
|
3
|
+
*
|
|
4
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
5
|
+
* you may not use this file except in compliance with the License.
|
|
6
|
+
* You may obtain a copy of the License at
|
|
7
|
+
*
|
|
8
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
9
|
+
*
|
|
10
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
11
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
12
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
13
|
+
* See the License for the specific language governing permissions and
|
|
14
|
+
* limitations under the License.
|
|
15
|
+
*/
|
|
16
|
+
const DEFAULT_APPROVAL_COOLDOWN_MS = 10 * 60 * 1000;
|
|
17
|
+
export function money(currency, minor) {
|
|
18
|
+
const whole = Math.trunc(minor / 100);
|
|
19
|
+
const cents = String(minor % 100).padStart(2, "0");
|
|
20
|
+
return `${currency === "CNY" ? "¥" : currency}${whole}.${cents}`;
|
|
21
|
+
}
|
|
22
|
+
function shortId(id) {
|
|
23
|
+
return id.length <= 24 ? id : `${id.slice(0, 21)}…`;
|
|
24
|
+
}
|
|
25
|
+
function approvalTexts(record, channels, kind) {
|
|
26
|
+
const texts = {};
|
|
27
|
+
const base = [
|
|
28
|
+
`【Kiwi 商家】待审批还价`,
|
|
29
|
+
`SKU ${record.sku} × ${record.quantity}${record.unit !== undefined ? ` ${record.unit}` : ""}`,
|
|
30
|
+
`买家还价 ${money(record.currency, record.buyer_offer_minor)}`,
|
|
31
|
+
...(record.public_bound_minor !== undefined
|
|
32
|
+
? [`公开边界 ${money(record.currency, record.public_bound_minor)}`]
|
|
33
|
+
: []),
|
|
34
|
+
`审批 ${record.approval_id}`,
|
|
35
|
+
`磋商 ${shortId(record.negotiation_id)}`,
|
|
36
|
+
"批准后需买家再次还价才会生效。",
|
|
37
|
+
];
|
|
38
|
+
if (kind !== "pending") {
|
|
39
|
+
const label = kind === "approved" ? "已批准" : kind === "consumed" ? "已生效" : kind === "rejected" ? "已拒绝" : "已过期";
|
|
40
|
+
base[0] = `【Kiwi 商家】审批${label}`;
|
|
41
|
+
if (record.approved_minor !== undefined && kind !== "rejected") {
|
|
42
|
+
base.splice(2, 0, `批准价 ${money(record.currency, record.approved_minor)}`);
|
|
43
|
+
}
|
|
44
|
+
base[base.length - 1] = kind === "expired" ? "授权已过期,需重新还价/审批。" : "状态已更新。";
|
|
45
|
+
}
|
|
46
|
+
for (const channel of channels) {
|
|
47
|
+
const lines = [...base];
|
|
48
|
+
if (kind === "pending" && channel === "weixin" && record.floor_minor !== undefined) {
|
|
49
|
+
lines.splice(3, 0, `私有底价 ${money(record.currency, record.floor_minor)}`);
|
|
50
|
+
}
|
|
51
|
+
texts[channel] = lines.join("\n");
|
|
52
|
+
}
|
|
53
|
+
return texts;
|
|
54
|
+
}
|
|
55
|
+
function negotiationTexts(row, channels, kind) {
|
|
56
|
+
const text = kind === "agreement"
|
|
57
|
+
? `【Kiwi 商家】磋商已达成非绑定协议\nSKU ${row.sku}${row.quantity !== undefined ? ` × ${row.quantity}` : ""}\n磋商 ${shortId(row.negotiation_id)}`
|
|
58
|
+
: `【Kiwi 商家】买家等待回应\nSKU ${row.sku}${row.quantity !== undefined ? ` × ${row.quantity}` : ""}${row.last_action !== "" ? `\n最近动作 ${row.last_action}` : ""}\n磋商 ${shortId(row.negotiation_id)}`;
|
|
59
|
+
return Object.fromEntries(channels.map((channel) => [channel, text]));
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* 对比状态与快照,返回待投递通知与推进后的状态。
|
|
63
|
+
* 首次运行(initialized_at 缺省)不回放历史磋商,但现存 pending 审批仍通知。
|
|
64
|
+
*/
|
|
65
|
+
export function detectNotifications(state, snapshot, options) {
|
|
66
|
+
const nowIso = options.now.toISOString();
|
|
67
|
+
const cooldown = options.approvalCooldownMs ?? DEFAULT_APPROVAL_COOLDOWN_MS;
|
|
68
|
+
const firstRun = state.initialized_at === undefined;
|
|
69
|
+
const next = {
|
|
70
|
+
version: 1,
|
|
71
|
+
updated_at: nowIso,
|
|
72
|
+
...(state.initialized_at !== undefined ? { initialized_at: state.initialized_at } : { initialized_at: nowIso }),
|
|
73
|
+
negotiations: { ...state.negotiations },
|
|
74
|
+
approvals: { ...state.approvals },
|
|
75
|
+
queue: state.queue,
|
|
76
|
+
};
|
|
77
|
+
const notifications = [];
|
|
78
|
+
for (const row of snapshot.negotiations) {
|
|
79
|
+
const previous = state.negotiations[row.negotiation_id];
|
|
80
|
+
const newDigest = row.last_event_digest !== "" && previous?.last_event_digest !== row.last_event_digest;
|
|
81
|
+
if (newDigest && !firstRun) {
|
|
82
|
+
if (row.needs_attention) {
|
|
83
|
+
notifications.push({
|
|
84
|
+
key: `neg:${row.negotiation_id}:${row.last_event_digest}`,
|
|
85
|
+
texts: negotiationTexts(row, options.channels, "attention"),
|
|
86
|
+
});
|
|
87
|
+
}
|
|
88
|
+
else if (row.agreement && !previous?.agreement) {
|
|
89
|
+
notifications.push({
|
|
90
|
+
key: `neg:${row.negotiation_id}:${row.last_event_digest}:agreement`,
|
|
91
|
+
texts: negotiationTexts(row, options.channels, "agreement"),
|
|
92
|
+
});
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
next.negotiations[row.negotiation_id] = {
|
|
96
|
+
last_event_digest: row.last_event_digest,
|
|
97
|
+
agreement: row.agreement,
|
|
98
|
+
...(previous?.last_notified_at !== undefined
|
|
99
|
+
? { last_notified_at: previous.last_notified_at }
|
|
100
|
+
: {}),
|
|
101
|
+
};
|
|
102
|
+
}
|
|
103
|
+
for (const record of snapshot.approvals) {
|
|
104
|
+
const previous = state.approvals[record.approval_id];
|
|
105
|
+
const changed = previous === undefined ||
|
|
106
|
+
previous.status !== record.status ||
|
|
107
|
+
previous.updated_at !== record.updated_at;
|
|
108
|
+
if (!changed)
|
|
109
|
+
continue;
|
|
110
|
+
const transitionKind = record.status === "pending"
|
|
111
|
+
? "pending"
|
|
112
|
+
: previous?.status === "approved" && record.status === "consumed"
|
|
113
|
+
? "consumed"
|
|
114
|
+
: previous?.status === "approved" && record.status === "expired"
|
|
115
|
+
? "expired"
|
|
116
|
+
: record.status === "rejected"
|
|
117
|
+
? "rejected"
|
|
118
|
+
: undefined;
|
|
119
|
+
let notifiedAt = previous?.notified_at;
|
|
120
|
+
if (transitionKind !== undefined) {
|
|
121
|
+
const recentSameSku = Object.values(state.approvals).some((entry) => entry.negotiation_id === record.negotiation_id &&
|
|
122
|
+
entry.sku === record.sku &&
|
|
123
|
+
entry.notified_at !== undefined &&
|
|
124
|
+
options.now.getTime() - Date.parse(entry.notified_at) < cooldown);
|
|
125
|
+
const cooling = transitionKind === "pending" &&
|
|
126
|
+
(recentSameSku ||
|
|
127
|
+
(previous?.notified_at !== undefined &&
|
|
128
|
+
options.now.getTime() - Date.parse(previous.notified_at) < cooldown));
|
|
129
|
+
if (!cooling) {
|
|
130
|
+
notifications.push({
|
|
131
|
+
key: `nap:${record.approval_id}:${record.status}:${record.updated_at}`,
|
|
132
|
+
texts: approvalTexts(record, options.channels, transitionKind),
|
|
133
|
+
});
|
|
134
|
+
notifiedAt = nowIso;
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
next.approvals[record.approval_id] = {
|
|
138
|
+
status: record.status,
|
|
139
|
+
updated_at: record.updated_at,
|
|
140
|
+
negotiation_id: record.negotiation_id,
|
|
141
|
+
sku: record.sku,
|
|
142
|
+
...(notifiedAt !== undefined ? { notified_at: notifiedAt } : {}),
|
|
143
|
+
};
|
|
144
|
+
}
|
|
145
|
+
return { notifications, next };
|
|
146
|
+
}
|
|
147
|
+
//# sourceMappingURL=detect.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"detect.js","sourceRoot":"","sources":["../../../src/merchant/watch/detect.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AA0BH,MAAM,4BAA4B,GAAG,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC;AAEpD,MAAM,UAAU,KAAK,CAAC,QAAgB,EAAE,KAAa;IACnD,MAAM,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,KAAK,GAAG,GAAG,CAAC,CAAC;IACtC,MAAM,KAAK,GAAG,MAAM,CAAC,KAAK,GAAG,GAAG,CAAC,CAAC,QAAQ,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC;IACnD,OAAO,GAAG,QAAQ,KAAK,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,QAAQ,GAAG,KAAK,IAAI,KAAK,EAAE,CAAC;AACnE,CAAC;AAED,SAAS,OAAO,CAAC,EAAU;IACzB,OAAO,EAAE,CAAC,MAAM,IAAI,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,GAAG,EAAE,CAAC,KAAK,CAAC,CAAC,EAAE,EAAE,CAAC,GAAG,CAAC;AACtD,CAAC;AAED,SAAS,aAAa,CACpB,MAAiC,EACjC,QAA2B,EAC3B,IAAkE;IAElE,MAAM,KAAK,GAA2B,EAAE,CAAC;IACzC,MAAM,IAAI,GAAG;QACX,gBAAgB;QAChB,OAAO,MAAM,CAAC,GAAG,MAAM,MAAM,CAA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W,CAAC,GAAG;YACnC,MAAM,EAAE,MAAM,CAAC,MAAM;YACrB,UAAU,EAAE,MAAM,CAAC,UAAU;YAC7B,cAAc,EAAE,MAAM,CAAC,cAAc;YACrC,GAAG,EAAE,MAAM,CAAC,GAAG;YACf,GAAG,CAAC,UAAU,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,WAAW,EAAE,UAAU,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;SACjE,CAAC;IACJ,CAAC;IAED,OAAO,EAAE,aAAa,EAAE,IAAI,EAAE,CAAC;AACjC,CAAC"}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Copyright 2026 harrylabsj
|
|
3
|
+
*
|
|
4
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
5
|
+
* you may not use this file except in compliance with the License.
|
|
6
|
+
* You may obtain a copy of the License at
|
|
7
|
+
*
|
|
8
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
9
|
+
*
|
|
10
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
11
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
12
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
13
|
+
* See the License for the specific language governing permissions and
|
|
14
|
+
* limitations under the License.
|
|
15
|
+
*/
|
|
16
|
+
/**
|
|
17
|
+
* watch 通知渠道。
|
|
18
|
+
*
|
|
19
|
+
* - 企业微信群机器人 webhook:主通道;只接受 https + 显式主机白名单,
|
|
20
|
+
* 禁止重定向,5s 超时,响应 ≤256 KiB;文本由调用方保证不含私有底价。
|
|
21
|
+
* - 个人微信 iLink:增强通道;主动发送尽量带上最近一次入站 context_token,
|
|
22
|
+
* 无 token 时仍尝试一次,失败由调用方按“通道降级”处理。
|
|
23
|
+
*/
|
|
24
|
+
import type { BotCredentials } from "../../weixin/types.js";
|
|
25
|
+
import type { IlinkClient } from "../../weixin/ilink-client.js";
|
|
26
|
+
export interface WatchChannel {
|
|
27
|
+
readonly name: string;
|
|
28
|
+
send(text: string): Promise<void>;
|
|
29
|
+
}
|
|
30
|
+
export declare class WecomWebhookChannel implements WatchChannel {
|
|
31
|
+
private readonly options;
|
|
32
|
+
readonly name = "wecom";
|
|
33
|
+
private readonly url;
|
|
34
|
+
constructor(webhookUrl: string, options?: {
|
|
35
|
+
allowedHosts?: readonly string[];
|
|
36
|
+
fetchImpl?: typeof fetch;
|
|
37
|
+
});
|
|
38
|
+
send(text: string): Promise<void>;
|
|
39
|
+
}
|
|
40
|
+
export declare class IlinkWatchChannel implements WatchChannel {
|
|
41
|
+
private readonly client;
|
|
42
|
+
private readonly credentials;
|
|
43
|
+
private readonly recipients;
|
|
44
|
+
private readonly contextTokenFor;
|
|
45
|
+
readonly name = "weixin";
|
|
46
|
+
constructor(client: IlinkClient, credentials: BotCredentials, recipients: readonly string[], contextTokenFor: (userId: string) => string | undefined);
|
|
47
|
+
send(text: string): Promise<void>;
|
|
48
|
+
}
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Copyright 2026 harrylabsj
|
|
3
|
+
*
|
|
4
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
5
|
+
* you may not use this file except in compliance with the License.
|
|
6
|
+
* You may obtain a copy of the License at
|
|
7
|
+
*
|
|
8
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
9
|
+
*
|
|
10
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
11
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
12
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
13
|
+
* See the License for the specific language governing permissions and
|
|
14
|
+
* limitations under the License.
|
|
15
|
+
*/
|
|
16
|
+
const MAX_RESPONSE_BYTES = 256 * 1024;
|
|
17
|
+
const SEND_TIMEOUT_MS = 5_000;
|
|
18
|
+
export class WecomWebhookChannel {
|
|
19
|
+
options;
|
|
20
|
+
name = "wecom";
|
|
21
|
+
url;
|
|
22
|
+
constructor(webhookUrl, options = {}) {
|
|
23
|
+
this.options = options;
|
|
24
|
+
let parsed;
|
|
25
|
+
try {
|
|
26
|
+
parsed = new URL(webhookUrl);
|
|
27
|
+
}
|
|
28
|
+
catch {
|
|
29
|
+
throw new Error("企业微信 webhook URL 不合法");
|
|
30
|
+
}
|
|
31
|
+
if (parsed.protocol !== "https:") {
|
|
32
|
+
throw new Error("企业微信 webhook 必须是 https");
|
|
33
|
+
}
|
|
34
|
+
if (parsed.username !== "" || parsed.password !== "") {
|
|
35
|
+
throw new Error("企业微信 webhook 不允许 userinfo");
|
|
36
|
+
}
|
|
37
|
+
const allowed = options.allowedHosts ?? ["qyapi.weixin.qq.com"];
|
|
38
|
+
if (!allowed.includes(parsed.hostname)) {
|
|
39
|
+
throw new Error(`企业微信 webhook 主机不在白名单:${parsed.hostname}`);
|
|
40
|
+
}
|
|
41
|
+
this.url = parsed;
|
|
42
|
+
}
|
|
43
|
+
async send(text) {
|
|
44
|
+
const fetchImpl = this.options.fetchImpl ?? fetch;
|
|
45
|
+
const response = await fetchImpl(this.url, {
|
|
46
|
+
method: "POST",
|
|
47
|
+
headers: { "content-type": "application/json" },
|
|
48
|
+
body: JSON.stringify({ msgtype: "text", text: { content: text } }),
|
|
49
|
+
redirect: "error",
|
|
50
|
+
signal: AbortSignal.timeout(SEND_TIMEOUT_MS),
|
|
51
|
+
});
|
|
52
|
+
const body = await response.text();
|
|
53
|
+
if (Buffer.byteLength(body) > MAX_RESPONSE_BYTES) {
|
|
54
|
+
throw new Error("企业微信 webhook 响应过大");
|
|
55
|
+
}
|
|
56
|
+
if (!response.ok) {
|
|
57
|
+
throw new Error(`企业微信 webhook HTTP ${response.status}`);
|
|
58
|
+
}
|
|
59
|
+
let parsed;
|
|
60
|
+
try {
|
|
61
|
+
parsed = JSON.parse(body);
|
|
62
|
+
}
|
|
63
|
+
catch {
|
|
64
|
+
throw new Error("企业微信 webhook 响应不是 JSON");
|
|
65
|
+
}
|
|
66
|
+
const errcode = parsed.errcode;
|
|
67
|
+
if (typeof errcode === "number" && errcode !== 0) {
|
|
68
|
+
throw new Error(`企业微信 webhook errcode ${errcode}`);
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
export class IlinkWatchChannel {
|
|
73
|
+
client;
|
|
74
|
+
credentials;
|
|
75
|
+
recipients;
|
|
76
|
+
contextTokenFor;
|
|
77
|
+
name = "weixin";
|
|
78
|
+
constructor(client, credentials, recipients, contextTokenFor) {
|
|
79
|
+
this.client = client;
|
|
80
|
+
this.credentials = credentials;
|
|
81
|
+
this.recipients = recipients;
|
|
82
|
+
this.contextTokenFor = contextTokenFor;
|
|
83
|
+
}
|
|
84
|
+
async send(text) {
|
|
85
|
+
if (this.recipients.length === 0) {
|
|
86
|
+
throw new Error("个人微信通道没有授权接收人");
|
|
87
|
+
}
|
|
88
|
+
const failures = [];
|
|
89
|
+
for (const userId of this.recipients) {
|
|
90
|
+
try {
|
|
91
|
+
await this.client.sendMessage({
|
|
92
|
+
to_user_id: userId,
|
|
93
|
+
text: text.length > 2000 ? `${text.slice(0, 2000)}…` : text,
|
|
94
|
+
...(this.contextTokenFor(userId) !== undefined
|
|
95
|
+
? { context_token: this.contextTokenFor(userId) }
|
|
96
|
+
: {}),
|
|
97
|
+
}, this.credentials);
|
|
98
|
+
}
|
|
99
|
+
catch (err) {
|
|
100
|
+
failures.push(`${userId}: ${err instanceof Error ? err.message : String(err)}`);
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
if (failures.length > 0) {
|
|
104
|
+
throw new Error(`个人微信发送失败(${failures.length}/${this.recipients.length})`);
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
//# sourceMappingURL=notify.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"notify.js","sourceRoot":"","sources":["../../../src/merchant/watch/notify.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;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
|
+
* Copyright 2026 harrylabsj
|
|
3
|
+
*
|
|
4
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
5
|
+
* you may not use this file except in compliance with the License.
|
|
6
|
+
* You may obtain a copy of the License at
|
|
7
|
+
*
|
|
8
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
9
|
+
*
|
|
10
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
11
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
12
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
13
|
+
* See the License for the specific language governing permissions and
|
|
14
|
+
* limitations under the License.
|
|
15
|
+
*/
|
|
16
|
+
import type { NegotiationOps } from "../negotiation-ops.js";
|
|
17
|
+
import type { WatchChannel } from "./notify.js";
|
|
18
|
+
export interface MerchantWatchServiceOptions {
|
|
19
|
+
dataDir: string;
|
|
20
|
+
ops: NegotiationOps;
|
|
21
|
+
channels: readonly WatchChannel[];
|
|
22
|
+
intervalMs?: number;
|
|
23
|
+
now?: () => Date;
|
|
24
|
+
log?: (line: string) => void;
|
|
25
|
+
}
|
|
26
|
+
export declare class MerchantWatchService {
|
|
27
|
+
private readonly options;
|
|
28
|
+
private readonly statePath;
|
|
29
|
+
private readonly channels;
|
|
30
|
+
private readonly intervalMs;
|
|
31
|
+
private readonly now;
|
|
32
|
+
private readonly log;
|
|
33
|
+
private timer;
|
|
34
|
+
private running;
|
|
35
|
+
private ticking;
|
|
36
|
+
constructor(options: MerchantWatchServiceOptions);
|
|
37
|
+
start(): void;
|
|
38
|
+
stop(): void;
|
|
39
|
+
tick(): Promise<void>;
|
|
40
|
+
private runTick;
|
|
41
|
+
private deliver;
|
|
42
|
+
private retryQueue;
|
|
43
|
+
}
|
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Copyright 2026 harrylabsj
|
|
3
|
+
*
|
|
4
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
5
|
+
* you may not use this file except in compliance with the License.
|
|
6
|
+
* You may obtain a copy of the License at
|
|
7
|
+
*
|
|
8
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
9
|
+
*
|
|
10
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
11
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
12
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
13
|
+
* See the License for the specific language governing permissions and
|
|
14
|
+
* limitations under the License.
|
|
15
|
+
*/
|
|
16
|
+
/**
|
|
17
|
+
* watch 守护循环:轮询磋商/审批快照 → 检测可行动事件 → 多渠道投递。
|
|
18
|
+
*
|
|
19
|
+
* 投递语义至少一次:发送成功/失败的渠道分别记账;失败进持久化队列,
|
|
20
|
+
* 5s/30s/2m/10m 退避,5 次后放弃并记日志。单渠道失败不影响其他渠道。
|
|
21
|
+
*/
|
|
22
|
+
import path from "node:path";
|
|
23
|
+
import { detectNotifications } from "./detect.js";
|
|
24
|
+
import { loadWatchState, saveWatchState, watchStatePath, } from "./state.js";
|
|
25
|
+
const RETRY_DELAYS_MS = [5_000, 30_000, 120_000, 600_000];
|
|
26
|
+
const MAX_ATTEMPTS = 5;
|
|
27
|
+
export class MerchantWatchService {
|
|
28
|
+
options;
|
|
29
|
+
statePath;
|
|
30
|
+
channels;
|
|
31
|
+
intervalMs;
|
|
32
|
+
now;
|
|
33
|
+
log;
|
|
34
|
+
timer;
|
|
35
|
+
running = false;
|
|
36
|
+
ticking = null;
|
|
37
|
+
constructor(options) {
|
|
38
|
+
this.options = options;
|
|
39
|
+
this.channels = options.channels;
|
|
40
|
+
this.intervalMs = Math.max(5_000, options.intervalMs ?? 10_000);
|
|
41
|
+
this.now = options.now ?? (() => new Date());
|
|
42
|
+
this.log = options.log ?? ((line) => process.stderr.write(`${line}\n`));
|
|
43
|
+
this.statePath = watchStatePath(path.resolve(options.dataDir));
|
|
44
|
+
}
|
|
45
|
+
start() {
|
|
46
|
+
if (this.running)
|
|
47
|
+
return;
|
|
48
|
+
this.running = true;
|
|
49
|
+
void this.tick();
|
|
50
|
+
this.timer = setInterval(() => void this.tick(), this.intervalMs);
|
|
51
|
+
this.timer.unref();
|
|
52
|
+
}
|
|
53
|
+
stop() {
|
|
54
|
+
this.running = false;
|
|
55
|
+
if (this.timer !== undefined)
|
|
56
|
+
clearInterval(this.timer);
|
|
57
|
+
this.timer = undefined;
|
|
58
|
+
}
|
|
59
|
+
tick() {
|
|
60
|
+
if (!this.running)
|
|
61
|
+
return Promise.resolve();
|
|
62
|
+
if (this.ticking !== null)
|
|
63
|
+
return this.ticking;
|
|
64
|
+
this.ticking = this.runTick().finally(() => {
|
|
65
|
+
this.ticking = null;
|
|
66
|
+
});
|
|
67
|
+
return this.ticking;
|
|
68
|
+
}
|
|
69
|
+
async runTick() {
|
|
70
|
+
let state;
|
|
71
|
+
try {
|
|
72
|
+
state = loadWatchState(this.statePath, this.now().toISOString());
|
|
73
|
+
}
|
|
74
|
+
catch (err) {
|
|
75
|
+
this.log(`[watch] ${err instanceof Error ? err.message : String(err)}`);
|
|
76
|
+
this.running = false;
|
|
77
|
+
if (this.timer !== undefined)
|
|
78
|
+
clearInterval(this.timer);
|
|
79
|
+
this.timer = undefined;
|
|
80
|
+
return;
|
|
81
|
+
}
|
|
82
|
+
let snapshot;
|
|
83
|
+
try {
|
|
84
|
+
snapshot = this.options.ops.snapshot();
|
|
85
|
+
}
|
|
86
|
+
catch (err) {
|
|
87
|
+
this.log(`[watch] 读取磋商快照失败:${err instanceof Error ? err.message : String(err)}`);
|
|
88
|
+
return;
|
|
89
|
+
}
|
|
90
|
+
const detected = detectNotifications(state, snapshot, {
|
|
91
|
+
channels: this.channels.map((channel) => channel.name),
|
|
92
|
+
now: this.now(),
|
|
93
|
+
});
|
|
94
|
+
state = detected.next;
|
|
95
|
+
for (const notification of detected.notifications) {
|
|
96
|
+
await this.deliver(state, notification);
|
|
97
|
+
}
|
|
98
|
+
await this.retryQueue(state);
|
|
99
|
+
state.updated_at = this.now().toISOString();
|
|
100
|
+
try {
|
|
101
|
+
saveWatchState(this.statePath, state);
|
|
102
|
+
}
|
|
103
|
+
catch (err) {
|
|
104
|
+
this.log(`[watch] 状态写入失败:${err instanceof Error ? err.message : String(err)}`);
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
async deliver(state, notification) {
|
|
108
|
+
const failed = {};
|
|
109
|
+
for (const channel of this.channels) {
|
|
110
|
+
const text = notification.texts[channel.name];
|
|
111
|
+
if (text === undefined)
|
|
112
|
+
continue;
|
|
113
|
+
try {
|
|
114
|
+
await channel.send(text);
|
|
115
|
+
}
|
|
116
|
+
catch (err) {
|
|
117
|
+
failed[channel.name] = text;
|
|
118
|
+
this.log(`[watch] ${channel.name} 投递失败 ${notification.key}:${err instanceof Error ? err.message : String(err)}`);
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
if (Object.keys(failed).length > 0) {
|
|
122
|
+
state.queue.push({
|
|
123
|
+
key: notification.key,
|
|
124
|
+
texts: failed,
|
|
125
|
+
attempts: 0,
|
|
126
|
+
next_at: new Date(this.now().getTime() + RETRY_DELAYS_MS[0]).toISOString(),
|
|
127
|
+
});
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
async retryQueue(state) {
|
|
131
|
+
const now = this.now().getTime();
|
|
132
|
+
const pending = [];
|
|
133
|
+
for (const item of state.queue) {
|
|
134
|
+
if (Date.parse(item.next_at) > now) {
|
|
135
|
+
pending.push(item);
|
|
136
|
+
continue;
|
|
137
|
+
}
|
|
138
|
+
const failed = {};
|
|
139
|
+
for (const [name, text] of Object.entries(item.texts)) {
|
|
140
|
+
const channel = this.channels.find((candidate) => candidate.name === name);
|
|
141
|
+
if (channel === undefined)
|
|
142
|
+
continue;
|
|
143
|
+
try {
|
|
144
|
+
await channel.send(text);
|
|
145
|
+
}
|
|
146
|
+
catch {
|
|
147
|
+
failed[name] = text;
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
if (Object.keys(failed).length === 0)
|
|
151
|
+
continue;
|
|
152
|
+
const attempts = item.attempts + 1;
|
|
153
|
+
if (attempts >= MAX_ATTEMPTS) {
|
|
154
|
+
this.log(`[watch] 放弃投递 ${item.key}(${attempts} 次失败)`);
|
|
155
|
+
continue;
|
|
156
|
+
}
|
|
157
|
+
pending.push({
|
|
158
|
+
...item,
|
|
159
|
+
texts: failed,
|
|
160
|
+
attempts,
|
|
161
|
+
next_at: new Date(now + RETRY_DELAYS_MS[Math.min(attempts, RETRY_DELAYS_MS.length - 1)]).toISOString(),
|
|
162
|
+
});
|
|
163
|
+
}
|
|
164
|
+
state.queue = pending;
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
//# sourceMappingURL=service.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"service.js","sourceRoot":"","sources":["../../../src/merchant/watch/service.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH;;;;;GAKG;AAEH,OAAO,IAAI,MAAM,WAAW,CAAC;AAG7B,OAAO,EAAE,mBAAmB,EAA0B,MAAM,aAAa,CAAC;AAE1E,OAAO,EACL,cAAc,EACd,cAAc,EACd,cAAc,GAGf,MAAM,YAAY,CAAC;AAEpB,MAAM,eAAe,GAAG,CAAC,KAAK,EAAE,MAAM,EAAE,OAAO,EAAE,OAAO,CAAC,CAAC;AAC1D,MAAM,YAAY,GAAG,CAAC,CAAC;AAWvB,MAAM,OAAO,oBAAoB;IAUF;IATZ,SAAS,CAAS;IAClB,QAAQ,CAA0B;IAClC,UAAU,CAAS;IACnB,GAAG,CAAa;IAChB,GAAG,CAAyB;IACrC,KAAK,CAA6C;IAClD,OAAO,GAAG,KAAK,CAAC;IAChB,OAAO,GAAyB,IAAI,CAAC;IAE7C,YAA6B,OAAoC;QAApC,YAAO,GAAP,OAAO,CAA6B;QAC/D,IAAI,CAAC,QAAQ,GAAG,OAAO,CAAC,QAAQ,CAAC;QACjC,IAAI,CA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CAAC;gBAC3B,CAAC;gBAAC,MAAM,CAAC;oBACP,MAAM,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC;gBACtB,CAAC;YACH,CAAC;YACD,IAAI,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,MAAM,KAAK,CAAC;gBAAE,SAAS;YAC/C,MAAM,QAAQ,GAAG,IAAI,CAAC,QAAQ,GAAG,CAAC,CAAC;YACnC,IAAI,QAAQ,IAAI,YAAY,EAAE,CAAC;gBAC7B,IAAI,CAAC,GAAG,CAAC,gBAAgB,IAAI,CAAC,GAAG,IAAI,QAAQ,OAAO,CAAC,CAAC;gBACtD,SAAS;YACX,CAAC;YACD,OAAO,CAAC,IAAI,CAAC;gBACX,GAAG,IAAI;gBACP,KAAK,EAAE,MAAM;gBACb,QAAQ;gBACR,OAAO,EAAE,IAAI,IAAI,CAAC,GAAG,GAAG,eAAe,CAAC,IAAI,CAAC,GAAG,CAAC,QAAQ,EAAE,eAAe,CAAC,MAAM,GAAG,CAAC,CAAC,CAAE,CAAC,CAAC,WAAW,EAAE;aACxG,CAAC,CAAC;QACL,CAAC;QACD,KAAK,CAAC,KAAK,GAAG,OAAO,CAAC;IACxB,CAAC;CACF"}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Copyright 2026 harrylabsj
|
|
3
|
+
*
|
|
4
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
5
|
+
* you may not use this file except in compliance with the License.
|
|
6
|
+
* You may obtain a copy of the License at
|
|
7
|
+
*
|
|
8
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
9
|
+
*
|
|
10
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
11
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
12
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
13
|
+
* See the License for the specific language governing permissions and
|
|
14
|
+
* limitations under the License.
|
|
15
|
+
*/
|
|
16
|
+
export interface WatchNegotiationState {
|
|
17
|
+
last_event_digest: string;
|
|
18
|
+
agreement: boolean;
|
|
19
|
+
last_notified_at?: string;
|
|
20
|
+
}
|
|
21
|
+
export interface WatchApprovalState {
|
|
22
|
+
status: string;
|
|
23
|
+
updated_at: string;
|
|
24
|
+
negotiation_id?: string;
|
|
25
|
+
sku?: string;
|
|
26
|
+
notified_at?: string;
|
|
27
|
+
}
|
|
28
|
+
export interface WatchQueueItem {
|
|
29
|
+
key: string;
|
|
30
|
+
/** 每个渠道各自的文本(已渲染;0600 文件内可能含金额)。 */
|
|
31
|
+
texts: Record<string, string>;
|
|
32
|
+
attempts: number;
|
|
33
|
+
next_at: string;
|
|
34
|
+
}
|
|
35
|
+
export interface WatchState {
|
|
36
|
+
version: 1;
|
|
37
|
+
updated_at: string;
|
|
38
|
+
initialized_at?: string;
|
|
39
|
+
negotiations: Record<string, WatchNegotiationState>;
|
|
40
|
+
approvals: Record<string, WatchApprovalState>;
|
|
41
|
+
queue: WatchQueueItem[];
|
|
42
|
+
}
|
|
43
|
+
export declare function emptyWatchState(now: string): WatchState;
|
|
44
|
+
export declare class WatchStateError extends Error {
|
|
45
|
+
constructor(message: string);
|
|
46
|
+
}
|
|
47
|
+
export declare function watchStatePath(dataDir: string): string;
|
|
48
|
+
export declare function loadWatchState(file: string, now: string): WatchState;
|
|
49
|
+
export declare function saveWatchState(file: string, state: WatchState): void;
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Copyright 2026 harrylabsj
|
|
3
|
+
*
|
|
4
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
5
|
+
* you may not use this file except in compliance with the License.
|
|
6
|
+
* You may obtain a copy of the License at
|
|
7
|
+
*
|
|
8
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
9
|
+
*
|
|
10
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
11
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
12
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
13
|
+
* See the License for the specific language governing permissions and
|
|
14
|
+
* limitations under the License.
|
|
15
|
+
*/
|
|
16
|
+
/**
|
|
17
|
+
* watch 去重/投递状态(`<dataDir>/watch/state.json`,0600 原子写)。
|
|
18
|
+
*
|
|
19
|
+
* 损坏状态 fail-closed:不从头回放历史(会把 61 场旧磋商重新通知一遍),
|
|
20
|
+
* 由调用方提示修复或删除文件。目录 0700。
|
|
21
|
+
*/
|
|
22
|
+
import { chmodSync, existsSync, mkdirSync, readFileSync } from "node:fs";
|
|
23
|
+
import path from "node:path";
|
|
24
|
+
import { writeFileAtomic } from "../../fs/atomic-write.js";
|
|
25
|
+
export function emptyWatchState(now) {
|
|
26
|
+
return { version: 1, updated_at: now, negotiations: {}, approvals: {}, queue: [] };
|
|
27
|
+
}
|
|
28
|
+
export class WatchStateError extends Error {
|
|
29
|
+
constructor(message) {
|
|
30
|
+
super(message);
|
|
31
|
+
this.name = "WatchStateError";
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
export function watchStatePath(dataDir) {
|
|
35
|
+
return path.join(dataDir, "watch", "state.json");
|
|
36
|
+
}
|
|
37
|
+
export function loadWatchState(file, now) {
|
|
38
|
+
if (!existsSync(file))
|
|
39
|
+
return emptyWatchState(now);
|
|
40
|
+
let parsed;
|
|
41
|
+
try {
|
|
42
|
+
parsed = JSON.parse(readFileSync(file, "utf8"));
|
|
43
|
+
}
|
|
44
|
+
catch (err) {
|
|
45
|
+
throw new WatchStateError(`watch 状态文件损坏(${file});修复或删除后重启:${err instanceof Error ? err.message : String(err)}`);
|
|
46
|
+
}
|
|
47
|
+
if (parsed === null || typeof parsed !== "object") {
|
|
48
|
+
throw new WatchStateError(`watch 状态文件损坏(${file});修复或删除后重启`);
|
|
49
|
+
}
|
|
50
|
+
const raw = parsed;
|
|
51
|
+
if (raw.version !== 1 || typeof raw.negotiations !== "object" || typeof raw.approvals !== "object") {
|
|
52
|
+
throw new WatchStateError(`watch 状态文件版本/形状不受支持(${file})`);
|
|
53
|
+
}
|
|
54
|
+
return {
|
|
55
|
+
version: 1,
|
|
56
|
+
updated_at: typeof raw.updated_at === "string" ? raw.updated_at : now,
|
|
57
|
+
...(typeof raw.initialized_at === "string" ? { initialized_at: raw.initialized_at } : {}),
|
|
58
|
+
negotiations: raw.negotiations ?? {},
|
|
59
|
+
approvals: raw.approvals ?? {},
|
|
60
|
+
queue: Array.isArray(raw.queue) ? raw.queue : [],
|
|
61
|
+
};
|
|
62
|
+
}
|
|
63
|
+
export function saveWatchState(file, state) {
|
|
64
|
+
mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
|
|
65
|
+
chmodSync(path.dirname(file), 0o700);
|
|
66
|
+
writeFileAtomic(file, `${JSON.stringify(state, null, 2)}\n`, { mode: 0o600 });
|
|
67
|
+
}
|
|
68
|
+
//# sourceMappingURL=state.js.map
|