@becomeopc/trendpublish 0.1.0 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (110) hide show
  1. package/dashboard/assets/{-association-list-CE--B0dM.js → -association-list-MaFlvvF5.js} +1 -1
  2. package/dashboard/assets/-channel-templates-B0KzH4gz.js +6 -0
  3. package/dashboard/assets/{-content-package-preview-DC4PLY9G.js → -content-package-preview-Bc225W8p.js} +1 -1
  4. package/dashboard/assets/-editor-page-DIrPd6Jj.js +1 -0
  5. package/dashboard/assets/-run-detail-view-CSb6Mp_W.js +12 -0
  6. package/dashboard/assets/{AnimatePresence-OeIRE0Xw.js → AnimatePresence-dRKyi9jP.js} +1 -1
  7. package/dashboard/assets/_app-C0k3Jpvj.js +1 -0
  8. package/dashboard/assets/app-dialog-CBRjH8y0.js +1 -0
  9. package/dashboard/assets/arrow-left-B1paVsKl.js +1 -0
  10. package/dashboard/assets/arrow-right-Bm6j4CRT.js +1 -0
  11. package/dashboard/assets/{articles-Bw-jie6T.js → articles-CJ24swVV.js} +1 -1
  12. package/dashboard/assets/automations-CSqhc87N.js +2 -0
  13. package/dashboard/assets/becomeopc-EvwYWHkB.js +1 -0
  14. package/dashboard/assets/check-_AvUITNy.js +1 -0
  15. package/dashboard/assets/chevron-down-CjEG9BtO.js +1 -0
  16. package/dashboard/assets/chevron-right-BcV2-ijN.js +1 -0
  17. package/dashboard/assets/connections-CUkG-3WF.js +1 -0
  18. package/dashboard/assets/content-plans-1_S1hkDo.js +1 -0
  19. package/dashboard/assets/content-plans_._planId.edit-2sqaHVmd.js +1 -0
  20. package/dashboard/assets/content-plans_.new-2sqaHVmd.js +1 -0
  21. package/dashboard/assets/{copy-CWp2fj5q.js → copy-C4Adx2li.js} +1 -1
  22. package/dashboard/assets/dropdown-menu-mpdg8__C.js +1 -0
  23. package/dashboard/assets/empty-state-B2PGtu_a.js +1 -0
  24. package/dashboard/assets/entity-list-B2WXTDDM.js +1 -0
  25. package/dashboard/assets/external-link-B2pLgsIl.js +1 -0
  26. package/dashboard/assets/{eye-Drma9Anf.js → eye-DyaLFyNg.js} +1 -1
  27. package/dashboard/assets/{file-text-BSOvvVFv.js → file-text-BqjzSiui.js} +1 -1
  28. package/dashboard/assets/{fingerprint-pattern-C_dvDw0n.js → fingerprint-pattern-CVznkwfS.js} +1 -1
  29. package/dashboard/assets/{flask-conical-DpX8Ww6S.js → flask-conical-B9Pn4z-3.js} +1 -1
  30. package/dashboard/assets/form-field-BJITE8Lh.js +1 -0
  31. package/dashboard/assets/identities-Bpb-f7oo.js +3 -0
  32. package/dashboard/assets/index-Bx1uywm3.js +51 -0
  33. package/dashboard/assets/index-ghPnBUnR.css +2 -0
  34. package/dashboard/assets/{input-D7j_2GhD.js → input-Br6N0XCJ.js} +1 -1
  35. package/dashboard/assets/jobs-BiQwL4Yt.js +1 -0
  36. package/dashboard/assets/jobs_._runId-DQ9L-G8H.js +1 -0
  37. package/dashboard/assets/knowledge-BePtU9f6.js +1 -0
  38. package/dashboard/assets/{layers-BHAmPdjS.js → layers-B6jc9X_5.js} +1 -1
  39. package/dashboard/assets/{layout-template-_-9A39QH.js → layout-template-11JYpJ5n.js} +1 -1
  40. package/dashboard/assets/library-BlLpV8Oh.js +1 -0
  41. package/dashboard/assets/{newspaper-Dcqy9j6N.js → newspaper-BF6EkBWC.js} +1 -1
  42. package/dashboard/assets/notifications-wLr7xSyr.js +1 -0
  43. package/dashboard/assets/page-grid-BR5GG4AN.js +1 -0
  44. package/dashboard/assets/pagination-CEYfdE0s.js +1 -0
  45. package/dashboard/assets/play-DYoZjslk.js +1 -0
  46. package/dashboard/assets/plus-DewHiaw6.js +1 -0
  47. package/dashboard/assets/publication-destination-picker-DAgQcLxS.js +1 -0
  48. package/dashboard/assets/publishing-DOrwrfAd.js +1 -0
  49. package/dashboard/assets/publishing_.styles-DUnbtaS6.js +1 -0
  50. package/dashboard/assets/publishing_.templates-pMvBK24N.js +1 -0
  51. package/dashboard/assets/{publishing_.templates_.sessions._sessionId-BKbSHrpn.js → publishing_.templates_.sessions._sessionId-FkykBbtF.js} +1 -1
  52. package/dashboard/assets/{radio-tower-tBHGxqPI.js → radio-tower-CS59Tvfq.js} +1 -1
  53. package/dashboard/assets/{react-ByivFozR.js → react-OqyHmgtK.js} +1 -1
  54. package/dashboard/assets/refresh-cw-BB9_0X86.js +1 -0
  55. package/dashboard/assets/{routes-zvPXw-Ia.js → routes-15GLqJa6.js} +1 -1
  56. package/dashboard/assets/{runs-DiLk0fOQ.js → runs-Cbz28Mf6.js} +1 -1
  57. package/dashboard/assets/{select-BUT5ahxS.js → select-9cx3otc_.js} +1 -1
  58. package/dashboard/assets/{settings-BZ3KUyq9.js → settings-CeJjvt-K.js} +1 -1
  59. package/dashboard/assets/sources-CsuPzTTH.js +1 -0
  60. package/dashboard/assets/{sparkles-ws1IsiGt.js → sparkles-C9YU6Kr5.js} +1 -1
  61. package/dashboard/assets/{sse-_t5PeRmk.js → sse-DQK6eHXZ.js} +2 -2
  62. package/dashboard/assets/tabs-DdmTx_k0.js +1 -0
  63. package/dashboard/assets/{textarea-B7N7g6fl.js → textarea-zbjD4aac.js} +1 -1
  64. package/dashboard/assets/{trash-2-C3dbRhyb.js → trash-2-CcgFunKh.js} +1 -1
  65. package/dashboard/assets/{use-onboarding-muxucTEZ.js → use-onboarding-fKNsbNhX.js} +1 -1
  66. package/dashboard/assets/use-workspace-snapshot-MZKeTfAJ.js +1 -0
  67. package/dashboard/assets/{useMutation-C221JCx3.js → useMutation-Xdq_89ou.js} +1 -1
  68. package/dashboard/assets/{workspace-DGt_GyLc.js → workspace-XH4e6E59.js} +1 -1
  69. package/dashboard/assets/{wrench-BHwKK2nB.js → wrench-C9HmhR9v.js} +1 -1
  70. package/dashboard/index.html +2 -2
  71. package/dist/app.js +1248 -399
  72. package/package.json +1 -1
  73. package/dashboard/assets/-channel-templates-CdLCNDrC.js +0 -6
  74. package/dashboard/assets/-editor-page-CS5uk_2L.js +0 -1
  75. package/dashboard/assets/-run-detail-view-Csh1ek6d.js +0 -12
  76. package/dashboard/assets/_app-Bci0KgUT.js +0 -1
  77. package/dashboard/assets/app-dialog-ChNc5zc0.js +0 -1
  78. package/dashboard/assets/arrow-left-BQWrTPzt.js +0 -1
  79. package/dashboard/assets/arrow-right-Da_6qwwr.js +0 -1
  80. package/dashboard/assets/automations-JF7dpk0H.js +0 -2
  81. package/dashboard/assets/check-C6hl-XsU.js +0 -1
  82. package/dashboard/assets/chevron-down-DXrCAjpz.js +0 -1
  83. package/dashboard/assets/chevron-right-okm7Mcup.js +0 -1
  84. package/dashboard/assets/connections-D_OfbK5O.js +0 -1
  85. package/dashboard/assets/content-plans-CmaGhnXT.js +0 -1
  86. package/dashboard/assets/content-plans_._planId.edit-BPCAxR7I.js +0 -1
  87. package/dashboard/assets/content-plans_.new-BPCAxR7I.js +0 -1
  88. package/dashboard/assets/dropdown-menu-BR9kBDP8.js +0 -1
  89. package/dashboard/assets/entity-list-C7fEITZj.js +0 -1
  90. package/dashboard/assets/form-field-BbOl9sGR.js +0 -1
  91. package/dashboard/assets/identities-B2SMnjY3.js +0 -3
  92. package/dashboard/assets/index-DC7b8xgR.js +0 -51
  93. package/dashboard/assets/index-pqOc3FQv.css +0 -2
  94. package/dashboard/assets/jobs-WwmifsK9.js +0 -1
  95. package/dashboard/assets/jobs_._runId-BZsBpBT-.js +0 -1
  96. package/dashboard/assets/knowledge-CnqdN8mY.js +0 -1
  97. package/dashboard/assets/library-Bo-F96xG.js +0 -1
  98. package/dashboard/assets/notifications-Dlx9WRAf.js +0 -1
  99. package/dashboard/assets/page-grid-x4teY0Qb.js +0 -1
  100. package/dashboard/assets/pagination-BIxivGX2.js +0 -1
  101. package/dashboard/assets/play-CqRcIakP.js +0 -1
  102. package/dashboard/assets/plus-Cgi-AlzH.js +0 -1
  103. package/dashboard/assets/publication-destination-picker-p0aE3sNP.js +0 -1
  104. package/dashboard/assets/publishing-DYavJU0X.js +0 -1
  105. package/dashboard/assets/publishing_.styles-DfbwPHCg.js +0 -1
  106. package/dashboard/assets/publishing_.templates-DoOVohr6.js +0 -1
  107. package/dashboard/assets/sources-DaQA2K6Y.js +0 -1
  108. package/dashboard/assets/tabs-DT--ZcFL.js +0 -1
  109. package/dashboard/assets/use-workspace-snapshot-CZmWKC_d.js +0 -1
  110. package/dashboard/assets/useQuery-CH_PyDWC.js +0 -1
package/dist/app.js CHANGED
@@ -9,8 +9,121 @@ var __export = (target, all) => {
9
9
  __defProp(target, name, { get: all[name], enumerable: true });
10
10
  };
11
11
 
12
+ // ../../node_modules/.pnpm/jose@6.2.19/node_modules/jose/dist/webapi/lib/buffer_utils.js
13
+ function decodeBase64(encoded, url = false) {
14
+ if (Uint8Array.fromBase64)
15
+ return Uint8Array.fromBase64(encoded, { alphabet: url ? "base64url" : "base64" });
16
+ if (url) {
17
+ if (encoded.includes("+") || encoded.includes("/"))
18
+ throw new TypeError("Invalid base64url");
19
+ encoded = encoded.replace(/-/g, "+").replace(/_/g, "/");
20
+ }
21
+ const binary = atob(encoded), bytes = new Uint8Array(binary.length);
22
+ for (let i = 0; i < binary.length; i++)
23
+ bytes[i] = binary.charCodeAt(i);
24
+ return bytes;
25
+ }
26
+ var encoder, decoder, strictDecoder, UINT32_RANGE;
27
+ var init_buffer_utils = __esm({
28
+ "../../node_modules/.pnpm/jose@6.2.19/node_modules/jose/dist/webapi/lib/buffer_utils.js"() {
29
+ encoder = new TextEncoder();
30
+ decoder = new TextDecoder();
31
+ strictDecoder = new TextDecoder("utf-8", { fatal: true });
32
+ UINT32_RANGE = 2 ** 32;
33
+ }
34
+ });
35
+
36
+ // ../../node_modules/.pnpm/jose@6.2.19/node_modules/jose/dist/webapi/util/errors.js
37
+ var JOSEError, JWTInvalid;
38
+ var init_errors = __esm({
39
+ "../../node_modules/.pnpm/jose@6.2.19/node_modules/jose/dist/webapi/util/errors.js"() {
40
+ JOSEError = class extends Error {
41
+ static code = "ERR_JOSE_GENERIC";
42
+ code = "ERR_JOSE_GENERIC";
43
+ constructor(message, options2) {
44
+ super(message, options2), this.name = this.constructor.name, Error.captureStackTrace?.(this, this.constructor);
45
+ }
46
+ };
47
+ JWTInvalid = class extends JOSEError {
48
+ static code = "ERR_JWT_INVALID";
49
+ code = "ERR_JWT_INVALID";
50
+ };
51
+ }
52
+ });
53
+
54
+ // ../../node_modules/.pnpm/jose@6.2.19/node_modules/jose/dist/webapi/util/base64url.js
55
+ function decode(input) {
56
+ try {
57
+ return decodeBase64(typeof input == "string" ? input : decoder.decode(input), true);
58
+ } catch (cause) {
59
+ throw new TypeError(invalid, { cause });
60
+ }
61
+ }
62
+ var invalid;
63
+ var init_base64url = __esm({
64
+ "../../node_modules/.pnpm/jose@6.2.19/node_modules/jose/dist/webapi/util/base64url.js"() {
65
+ init_buffer_utils();
66
+ invalid = "The input to be decoded is not correctly encoded.";
67
+ }
68
+ });
69
+
70
+ // ../../node_modules/.pnpm/jose@6.2.19/node_modules/jose/dist/webapi/lib/validate.js
71
+ function isObject(input) {
72
+ if (typeof input != "object" || input === null || Object.prototype.toString.call(input) !== "[object Object]")
73
+ return false;
74
+ const prototype = Object.getPrototypeOf(input);
75
+ return prototype === null || Object.getPrototypeOf(prototype) === null;
76
+ }
77
+ var init_validate = __esm({
78
+ "../../node_modules/.pnpm/jose@6.2.19/node_modules/jose/dist/webapi/lib/validate.js"() {
79
+ }
80
+ });
81
+
82
+ // ../../node_modules/.pnpm/jose@6.2.19/node_modules/jose/dist/webapi/util/decode_jwt.js
83
+ function decodeJwt(jwt) {
84
+ if (typeof jwt != "string")
85
+ throw new JWTInvalid("JWTs must use Compact JWS serialization, JWT must be a string");
86
+ const { 1: encodedPayload, length } = jwt.split(".");
87
+ if (length === 5)
88
+ throw new JWTInvalid("Only JWTs using Compact JWS serialization can be decoded");
89
+ if (length !== 3)
90
+ throw new JWTInvalid("Invalid JWT");
91
+ if (!encodedPayload)
92
+ throw new JWTInvalid("JWTs must contain a payload");
93
+ let claimsSetBytes;
94
+ try {
95
+ claimsSetBytes = decode(encodedPayload);
96
+ } catch (cause) {
97
+ throw new JWTInvalid("Failed to base64url decode the payload", { cause });
98
+ }
99
+ let claimsSet;
100
+ try {
101
+ claimsSet = JSON.parse(strictDecoder.decode(claimsSetBytes));
102
+ } catch (cause) {
103
+ throw new JWTInvalid("Failed to parse the decoded payload as JSON", { cause });
104
+ }
105
+ if (!isObject(claimsSet))
106
+ throw new JWTInvalid("Invalid JWT Claims Set");
107
+ return claimsSet;
108
+ }
109
+ var init_decode_jwt = __esm({
110
+ "../../node_modules/.pnpm/jose@6.2.19/node_modules/jose/dist/webapi/util/decode_jwt.js"() {
111
+ init_base64url();
112
+ init_buffer_utils();
113
+ init_validate();
114
+ init_errors();
115
+ }
116
+ });
117
+
118
+ // ../../node_modules/.pnpm/jose@6.2.19/node_modules/jose/dist/webapi/index.js
119
+ var init_webapi = __esm({
120
+ "../../node_modules/.pnpm/jose@6.2.19/node_modules/jose/dist/webapi/index.js"() {
121
+ init_decode_jwt();
122
+ }
123
+ });
124
+
12
125
  // ../server/src/relay/credential.ts
13
- import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
126
+ import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
14
127
  import { homedir } from "node:os";
15
128
  import path from "node:path";
16
129
  function stateDir() {
@@ -29,27 +142,143 @@ function readRelayCredential() {
29
142
  token: parsed.token,
30
143
  refreshToken: parsed.refreshToken,
31
144
  expiresAt: parsed.expiresAt ?? "",
32
- product: parsed.product ?? "trendpublish"
145
+ product: parsed.product ?? "trendpublish",
146
+ plan: typeof parsed.plan === "string" ? parsed.plan : void 0,
147
+ status: typeof parsed.status === "string" ? parsed.status : void 0,
148
+ periodEnd: typeof parsed.periodEnd === "string" || parsed.periodEnd === null ? parsed.periodEnd : void 0,
149
+ trialEnd: typeof parsed.trialEnd === "string" || parsed.trialEnd === null ? parsed.trialEnd : void 0
33
150
  };
34
151
  } catch {
35
152
  return null;
36
153
  }
37
154
  }
38
155
  function writeRelayCredential(credential) {
39
- mkdirSync(stateDir(), { recursive: true });
156
+ mkdirSync(stateDir(), { recursive: true, mode: 448 });
40
157
  writeFileSync(relayCredentialPath(), `${JSON.stringify(credential, null, 2)}
41
158
  `, {
42
159
  mode: 384
43
160
  });
44
161
  }
162
+ function clearRelayCredential() {
163
+ const file = relayCredentialPath();
164
+ if (!existsSync(file)) return false;
165
+ rmSync(file, { force: true });
166
+ return true;
167
+ }
168
+ function inspectRelayCredential(credential, nowMs = Date.now()) {
169
+ let claims = {};
170
+ try {
171
+ claims = decodeJwt(credential.token);
172
+ } catch {
173
+ claims = {};
174
+ }
175
+ const claimStr = (key) => typeof claims[key] === "string" && claims[key].trim() ? claims[key].trim() : null;
176
+ const product = credential.product || claimStr("product") || "trendpublish";
177
+ const plan = credential.plan ?? claimStr("plan");
178
+ const status = credential.status ?? claimStr("status");
179
+ const periodEnd = credential.periodEnd ?? claimStr("period_end");
180
+ const trialEnd = credential.trialEnd ?? claimStr("trial_end");
181
+ const expFromClaim = typeof claims.exp === "number" && Number.isFinite(claims.exp) ? new Date(claims.exp * 1e3).toISOString() : null;
182
+ const expiresAt = credential.expiresAt?.trim() || expFromClaim;
183
+ const expiresMs = expiresAt ? Date.parse(expiresAt) : Number.NaN;
184
+ const expired = Number.isFinite(expiresMs) ? expiresMs <= nowMs : false;
185
+ const statusAllows = status ? LIVE_SUBSCRIPTION_STATUSES.has(status) : true;
186
+ return {
187
+ product,
188
+ plan,
189
+ status,
190
+ expiresAt,
191
+ periodEnd,
192
+ trialEnd,
193
+ expired,
194
+ entitled: !expired && statusAllows,
195
+ hasRefreshToken: Boolean(credential.refreshToken)
196
+ };
197
+ }
198
+ var LIVE_SUBSCRIPTION_STATUSES;
45
199
  var init_credential = __esm({
46
200
  "../server/src/relay/credential.ts"() {
47
201
  "use strict";
202
+ init_webapi();
203
+ LIVE_SUBSCRIPTION_STATUSES = /* @__PURE__ */ new Set(["active", "trialing", "canceling", "past_due"]);
204
+ }
205
+ });
206
+
207
+ // ../server/src/cli/state.ts
208
+ import { chmodSync, existsSync as existsSync2, mkdirSync as mkdirSync2, readFileSync as readFileSync2, writeFileSync as writeFileSync2 } from "node:fs";
209
+ import { homedir as homedir2 } from "node:os";
210
+ import path2 from "node:path";
211
+ function stateDir2() {
212
+ return process.env.TRENDPUBLISH_HOME?.trim() || path2.join(homedir2(), ".trendpublish");
213
+ }
214
+ function configPath() {
215
+ return path2.join(stateDir2(), "config.json");
216
+ }
217
+ function readConfig() {
218
+ const file = configPath();
219
+ if (!existsSync2(file)) return null;
220
+ try {
221
+ const parsed = JSON.parse(readFileSync2(file, "utf8"));
222
+ if (typeof parsed.apiKey !== "string" || !parsed.apiKey) return null;
223
+ return { apiKey: parsed.apiKey, port: parsed.port ?? CLI_PORT };
224
+ } catch {
225
+ return null;
226
+ }
227
+ }
228
+ function initConfig() {
229
+ const existing = readConfig();
230
+ if (existing) return existing;
231
+ const dir = stateDir2();
232
+ mkdirSync2(dir, { recursive: true, mode: 448 });
233
+ mkdirSync2(path2.join(dir, "objects"), { recursive: true, mode: 448 });
234
+ try {
235
+ chmodSync(dir, 448);
236
+ } catch {
237
+ }
238
+ const config = { apiKey: crypto.randomUUID(), port: CLI_PORT };
239
+ writeFileSync2(configPath(), `${JSON.stringify(config, null, 2)}
240
+ `, { mode: 384 });
241
+ return config;
242
+ }
243
+ function applyConfigToEnv(config) {
244
+ const dir = stateDir2();
245
+ process.env.TRENDPUBLISH_API_KEY = config.apiKey;
246
+ process.env.TRENDPUBLISH_PORT = String(config.port);
247
+ process.env.TRENDPUBLISH_SQLITE_PATH = path2.join(dir, "trendpublish.sqlite3");
248
+ process.env.TRENDPUBLISH_OBJECT_STORAGE = "local";
249
+ process.env.TRENDPUBLISH_OBJECT_STORAGE_PATH = path2.join(dir, "objects");
250
+ }
251
+ function dashboardUrl(config) {
252
+ return `http://127.0.0.1:${config.port}/dashboard`;
253
+ }
254
+ var CLI_PORT, CLI_PROCESS_NAME;
255
+ var init_state = __esm({
256
+ "../server/src/cli/state.ts"() {
257
+ "use strict";
258
+ init_credential();
259
+ CLI_PORT = 53683;
260
+ CLI_PROCESS_NAME = "trendpublish";
48
261
  }
49
262
  });
50
263
 
51
264
  // ../server/src/relay/oauth.ts
52
265
  import { createHash, randomBytes } from "node:crypto";
266
+ function resolveBecomeOpcUrls(issuer = DEFAULT_ISSUER) {
267
+ let origin = "https://becomeopc.com";
268
+ try {
269
+ origin = new URL(issuer).origin;
270
+ } catch {
271
+ origin = "https://becomeopc.com";
272
+ }
273
+ return {
274
+ home: origin,
275
+ subscribe: `${origin}/trendpublish/zh#pricing`,
276
+ manage: `${origin}/account?product=${RELAY_PRODUCT}&lang=zh`
277
+ };
278
+ }
279
+ function resolveManagedRelayUrl() {
280
+ return process.env.TRENDPUBLISH_MANAGED_RELAY_URL?.trim() || DEFAULT_MANAGED_RELAY_URL;
281
+ }
53
282
  function createPkce() {
54
283
  const verifier = randomBytes(48).toString("base64url");
55
284
  const challenge = createHash("sha256").update(verifier).digest("base64url");
@@ -113,19 +342,27 @@ async function fetchEntitlement(options2, fetchImpl = fetch) {
113
342
  });
114
343
  const data = await response.json();
115
344
  if (!response.ok || !data.token) {
116
- throw new Error(
117
- data.error === "not_entitled" ? "\u5F53\u524D\u8D26\u6237\u6CA1\u6709 TrendPublish \u8BA2\u9605\uFF0C\u8BF7\u5148\u5728 becomeopc.com \u8BA2\u9605\u6216\u5F00\u59CB\u8BD5\u7528" : `\u83B7\u53D6 entitlement \u5931\u8D25\uFF1A${data.error ?? `HTTP ${response.status}`}`
118
- );
345
+ if (data.error === "not_entitled") {
346
+ throw new NotEntitledError();
347
+ }
348
+ throw new Error(`\u83B7\u53D6 entitlement \u5931\u8D25\uFF1A${data.error ?? `HTTP ${response.status}`}`);
119
349
  }
120
350
  return data;
121
351
  }
122
- var DEFAULT_ISSUER, CLI_CLIENT_ID, RELAY_PRODUCT;
352
+ var DEFAULT_ISSUER, DEFAULT_MANAGED_RELAY_URL, CLI_CLIENT_ID, RELAY_PRODUCT, NotEntitledError;
123
353
  var init_oauth = __esm({
124
354
  "../server/src/relay/oauth.ts"() {
125
355
  "use strict";
126
356
  DEFAULT_ISSUER = "https://becomeopc.com/auth";
357
+ DEFAULT_MANAGED_RELAY_URL = "https://weixin.liuyaowen.cn";
127
358
  CLI_CLIENT_ID = "trendpublish-cli";
128
359
  RELAY_PRODUCT = "trendpublish";
360
+ NotEntitledError = class extends Error {
361
+ constructor(message = "\u5F53\u524D\u8D26\u6237\u6CA1\u6709 TrendPublish \u8BA2\u9605\uFF0C\u8BF7\u5148\u5728 becomeopc.com \u8BA2\u9605\u6216\u5F00\u59CB\u8BD5\u7528") {
362
+ super(message);
363
+ this.name = "NotEntitledError";
364
+ }
365
+ };
129
366
  }
130
367
  });
131
368
 
@@ -319,13 +556,13 @@ var init_url = __esm({
319
556
  }
320
557
  return null;
321
558
  };
322
- tryDecode = (str, decoder) => {
559
+ tryDecode = (str, decoder2) => {
323
560
  try {
324
- return decoder(str);
561
+ return decoder2(str);
325
562
  } catch {
326
563
  return str.replace(/(?:%[0-9A-Fa-f]{2})+/g, (match2) => {
327
564
  try {
328
- return decoder(match2);
565
+ return decoder2(match2);
329
566
  } catch {
330
567
  return match2;
331
568
  }
@@ -2180,21 +2417,43 @@ var init_dist = __esm({
2180
2417
  import { createServer } from "node:http";
2181
2418
  function serveFetch(options2, handler) {
2182
2419
  const server = createServer(async (incoming, outgoing) => {
2420
+ const abortController = new AbortController();
2421
+ const abort = () => {
2422
+ if (!abortController.signal.aborted) abortController.abort();
2423
+ };
2424
+ const onOutgoingClose = () => {
2425
+ if (!outgoing.writableEnded) abort();
2426
+ };
2427
+ incoming.on("aborted", abort);
2428
+ outgoing.on("close", onOutgoingClose);
2183
2429
  try {
2184
- const request = toFetchRequest(incoming, options2);
2430
+ const request = toFetchRequest(incoming, options2, abortController.signal);
2185
2431
  const response = await handler(request);
2186
- await writeFetchResponse(outgoing, response);
2432
+ if (outgoing.destroyed || outgoing.writableEnded) {
2433
+ await response.body?.cancel().catch(() => void 0);
2434
+ return;
2435
+ }
2436
+ await writeFetchResponse(outgoing, response, abortController.signal);
2187
2437
  } catch (error) {
2188
- console.error("[serve-fetch] request failed", error);
2189
- outgoing.statusCode = 500;
2190
- outgoing.setHeader("Content-Type", "application/json");
2191
- outgoing.end(JSON.stringify({ error: "Internal Server Error" }));
2438
+ if (!abortController.signal.aborted) {
2439
+ console.error("[serve-fetch] request failed", error);
2440
+ }
2441
+ if (!outgoing.headersSent && !outgoing.writableEnded) {
2442
+ outgoing.statusCode = 500;
2443
+ outgoing.setHeader("Content-Type", "application/json");
2444
+ outgoing.end(JSON.stringify({ error: "Internal Server Error" }));
2445
+ } else if (!outgoing.writableEnded && !outgoing.destroyed) {
2446
+ outgoing.end();
2447
+ }
2448
+ } finally {
2449
+ incoming.off("aborted", abort);
2450
+ outgoing.off("close", onOutgoingClose);
2192
2451
  }
2193
2452
  });
2194
2453
  server.listen(options2.port, options2.hostname ?? "0.0.0.0");
2195
2454
  return server;
2196
2455
  }
2197
- function toFetchRequest(incoming, options2) {
2456
+ function toFetchRequest(incoming, options2, signal) {
2198
2457
  const host = incoming.headers.host ?? `localhost:${options2.port}`;
2199
2458
  const url = new URL(incoming.url ?? "/", `http://${host}`);
2200
2459
  const headers = new Headers();
@@ -2210,26 +2469,50 @@ function toFetchRequest(incoming, options2) {
2210
2469
  return new Request(url, {
2211
2470
  method,
2212
2471
  headers,
2472
+ signal,
2213
2473
  body: hasBody ? incoming : void 0,
2214
2474
  duplex: hasBody ? "half" : void 0
2215
2475
  });
2216
2476
  }
2217
- async function writeFetchResponse(outgoing, response) {
2477
+ async function writeFetchResponse(outgoing, response, signal) {
2218
2478
  outgoing.statusCode = response.status;
2219
- response.headers.forEach((value, name) => outgoing.setHeader(name, value));
2479
+ const setCookies = typeof response.headers.getSetCookie === "function" ? response.headers.getSetCookie() : [];
2480
+ response.headers.forEach((value, name) => {
2481
+ if (name.toLowerCase() === "set-cookie" && setCookies.length > 0) return;
2482
+ outgoing.setHeader(name, value);
2483
+ });
2484
+ if (setCookies.length > 0) {
2485
+ outgoing.setHeader("set-cookie", setCookies);
2486
+ }
2220
2487
  if (!response.body) {
2221
2488
  outgoing.end();
2222
2489
  return;
2223
2490
  }
2224
2491
  const reader = response.body.getReader();
2492
+ const cancelReader = () => {
2493
+ void reader.cancel().catch(() => void 0);
2494
+ };
2495
+ signal.addEventListener("abort", cancelReader, { once: true });
2496
+ outgoing.flushHeaders();
2225
2497
  try {
2226
2498
  while (true) {
2499
+ if (signal.aborted || outgoing.destroyed || outgoing.writableEnded) {
2500
+ await reader.cancel().catch(() => void 0);
2501
+ break;
2502
+ }
2227
2503
  const { done, value } = await reader.read();
2228
2504
  if (done) break;
2505
+ if (signal.aborted || outgoing.destroyed || outgoing.writableEnded) {
2506
+ await reader.cancel().catch(() => void 0);
2507
+ break;
2508
+ }
2229
2509
  outgoing.write(value);
2230
2510
  }
2231
- outgoing.end();
2511
+ if (!outgoing.writableEnded && !outgoing.destroyed) {
2512
+ outgoing.end();
2513
+ }
2232
2514
  } finally {
2515
+ signal.removeEventListener("abort", cancelReader);
2233
2516
  reader.releaseLock();
2234
2517
  }
2235
2518
  }
@@ -3160,7 +3443,7 @@ function getErrorMap() {
3160
3443
  return overrideErrorMap;
3161
3444
  }
3162
3445
  var overrideErrorMap;
3163
- var init_errors = __esm({
3446
+ var init_errors2 = __esm({
3164
3447
  "../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/errors.js"() {
3165
3448
  init_en();
3166
3449
  overrideErrorMap = en_default;
@@ -3190,7 +3473,7 @@ function addIssueToContext(ctx, issueData) {
3190
3473
  var makeIssue, EMPTY_PATH, ParseStatus, INVALID, DIRTY, OK, isAborted, isDirty, isValid, isAsync;
3191
3474
  var init_parseUtil = __esm({
3192
3475
  "../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/helpers/parseUtil.js"() {
3193
- init_errors();
3476
+ init_errors2();
3194
3477
  init_en();
3195
3478
  makeIssue = (params) => {
3196
3479
  const { data, path: path7, errorMaps, issueData } = params;
@@ -3497,7 +3780,7 @@ var ParseInputLazyPath, handleResult, ZodType, cuidRegex, cuid2Regex, ulidRegex,
3497
3780
  var init_types = __esm({
3498
3781
  "../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/types.js"() {
3499
3782
  init_ZodError();
3500
- init_errors();
3783
+ init_errors2();
3501
3784
  init_errorUtil();
3502
3785
  init_parseUtil();
3503
3786
  init_util();
@@ -6870,7 +7153,7 @@ __export(external_exports, {
6870
7153
  });
6871
7154
  var init_external = __esm({
6872
7155
  "../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/external.js"() {
6873
- init_errors();
7156
+ init_errors2();
6874
7157
  init_parseUtil();
6875
7158
  init_typeAliases();
6876
7159
  init_util();
@@ -8500,7 +8783,7 @@ function describeConnectorError(value) {
8500
8783
  }
8501
8784
  }
8502
8785
  var ConnectorOutcome, ConnectorError;
8503
- var init_errors2 = __esm({
8786
+ var init_errors3 = __esm({
8504
8787
  "../server/src/connectors/errors.ts"() {
8505
8788
  "use strict";
8506
8789
  ConnectorOutcome = {
@@ -8706,7 +8989,7 @@ var HttpResponse, HttpStreamResponse, FetchHttpTransport, undiciModuleName, Http
8706
8989
  var init_http = __esm({
8707
8990
  "../server/src/connectors/http.ts"() {
8708
8991
  "use strict";
8709
- init_errors2();
8992
+ init_errors3();
8710
8993
  HttpResponse = class {
8711
8994
  constructor(status, headers, bytes, statusText = "") {
8712
8995
  this.status = status;
@@ -9222,7 +9505,7 @@ var ConnectorClientResolver, ConnectorManager;
9222
9505
  var init_runtime = __esm({
9223
9506
  "../server/src/connectors/runtime.ts"() {
9224
9507
  "use strict";
9225
- init_errors2();
9508
+ init_errors3();
9226
9509
  init_definition();
9227
9510
  init_http();
9228
9511
  ConnectorClientResolver = class {
@@ -9534,6 +9817,85 @@ var init_types2 = __esm({
9534
9817
  }
9535
9818
  });
9536
9819
 
9820
+ // ../server/src/connectors/url-policy.ts
9821
+ function assertPublicHttpUrl(value) {
9822
+ let url;
9823
+ try {
9824
+ url = new URL(value);
9825
+ } catch {
9826
+ throw new ConnectorError({ kind: "configuration", message: "\u6765\u6E90 URL \u65E0\u6548" });
9827
+ }
9828
+ if (url.protocol !== "http:" && url.protocol !== "https:") {
9829
+ throw new ConnectorError({
9830
+ kind: "configuration",
9831
+ message: "\u6765\u6E90 URL \u53EA\u652F\u6301 http:// \u6216 https://"
9832
+ });
9833
+ }
9834
+ const hostname = url.hostname.toLowerCase().replace(/^\[|\]$/g, "");
9835
+ if (isReservedHostname(hostname) || isPrivateAddress(hostname)) {
9836
+ throw new ConnectorError({
9837
+ kind: "configuration",
9838
+ message: "\u6765\u6E90 URL \u6307\u5411\u5185\u7F51\u6216\u4FDD\u7559\u5730\u5740\uFF0C\u5DF2\u62D2\u7EDD\u6293\u53D6"
9839
+ });
9840
+ }
9841
+ }
9842
+ function isReservedHostname(hostname) {
9843
+ if (!hostname) return true;
9844
+ if (hostname === "localhost" || hostname === "metadata.google.internal") return true;
9845
+ if (/^\d+$/.test(hostname)) return true;
9846
+ return reservedHostnameSuffixes.some((suffix) => hostname.endsWith(suffix));
9847
+ }
9848
+ function isPrivateAddress(hostname) {
9849
+ if (hostname.includes(":")) return isPrivateIpv6(hostname);
9850
+ const octets = hostname.split(".");
9851
+ if (octets.length !== 4 || octets.some((part) => !/^\d{1,3}$/.test(part))) return false;
9852
+ const numbers = octets.map((part) => Number(part));
9853
+ if (numbers.some((value) => value > 255)) return false;
9854
+ return isPrivateIpv4(numbers);
9855
+ }
9856
+ function isPrivateIpv4([a, b2]) {
9857
+ if (a === 0 || a === 10 || a === 127) return true;
9858
+ if (a === 169 && b2 === 254) return true;
9859
+ if (a === 172 && b2 >= 16 && b2 <= 31) return true;
9860
+ if (a === 192 && b2 === 168) return true;
9861
+ if (a === 100 && b2 >= 64 && b2 <= 127) return true;
9862
+ if (a === 192 && b2 === 0) return true;
9863
+ if (a === 198 && (b2 === 18 || b2 === 19)) return true;
9864
+ if (a === 198 && b2 === 51) return true;
9865
+ if (a === 203 && b2 === 0) return true;
9866
+ if (a >= 224) return true;
9867
+ return false;
9868
+ }
9869
+ function isPrivateIpv6(hostname) {
9870
+ const address = hostname.toLowerCase();
9871
+ if (address === "::" || address === "::1") return true;
9872
+ const mapped = address.match(/^::ffff:(\d{1,3}(?:\.\d{1,3}){3})$/);
9873
+ if (mapped) return isPrivateAddress(mapped[1]);
9874
+ if (address.startsWith("::ffff:")) return true;
9875
+ const firstGroup = address.split(":")[0] ?? "";
9876
+ if (/^f[cd]/.test(firstGroup)) return true;
9877
+ if (/^fe[89ab]/.test(firstGroup)) return true;
9878
+ return false;
9879
+ }
9880
+ var reservedHostnameSuffixes;
9881
+ var init_url_policy = __esm({
9882
+ "../server/src/connectors/url-policy.ts"() {
9883
+ "use strict";
9884
+ init_errors3();
9885
+ reservedHostnameSuffixes = [
9886
+ ".localhost",
9887
+ ".local",
9888
+ ".internal",
9889
+ ".corp",
9890
+ ".lan",
9891
+ ".home",
9892
+ ".invalid",
9893
+ ".test",
9894
+ ".example"
9895
+ ];
9896
+ }
9897
+ });
9898
+
9537
9899
  // ../server/src/connectors/builtins/dashscope.ts
9538
9900
  function extractMultimodalImages(data) {
9539
9901
  return (data.output?.choices ?? []).flatMap(
@@ -9551,7 +9913,7 @@ var init_dashscope = __esm({
9551
9913
  "../server/src/connectors/builtins/dashscope.ts"() {
9552
9914
  "use strict";
9553
9915
  init_zod();
9554
- init_errors2();
9916
+ init_errors3();
9555
9917
  init_definition();
9556
9918
  settingsSchema = external_exports.object({
9557
9919
  apiHost: external_exports.string().url().default("https://dashscope.aliyuncs.com"),
@@ -9854,7 +10216,7 @@ var init_openai_compatible = __esm({
9854
10216
  "../server/src/connectors/builtins/openai-compatible.ts"() {
9855
10217
  "use strict";
9856
10218
  init_zod();
9857
- init_errors2();
10219
+ init_errors3();
9858
10220
  init_definition();
9859
10221
  settingsSchema2 = external_exports.object({
9860
10222
  baseUrl: external_exports.string().url(),
@@ -10003,7 +10365,7 @@ var init_openai_compatible = __esm({
10003
10365
  authorization2(this.context.credentials.apiKey)
10004
10366
  );
10005
10367
  const reader = response.body.getReader();
10006
- const decoder = new TextDecoder();
10368
+ const decoder2 = new TextDecoder();
10007
10369
  let pending = "";
10008
10370
  let content = "";
10009
10371
  let model;
@@ -10128,12 +10490,12 @@ var init_openai_compatible = __esm({
10128
10490
  while (!terminated) {
10129
10491
  const { value, done } = await reader.read();
10130
10492
  if (done) {
10131
- pending += decoder.decode();
10493
+ pending += decoder2.decode();
10132
10494
  consumePendingLines(true);
10133
10495
  flushEvent();
10134
10496
  break;
10135
10497
  }
10136
- pending += decoder.decode(value, { stream: true });
10498
+ pending += decoder2.decode(value, { stream: true });
10137
10499
  consumePendingLines();
10138
10500
  }
10139
10501
  if (!terminated) {
@@ -10283,7 +10645,7 @@ var init_minimax = __esm({
10283
10645
  "../server/src/connectors/builtins/minimax.ts"() {
10284
10646
  "use strict";
10285
10647
  init_zod();
10286
- init_errors2();
10648
+ init_errors3();
10287
10649
  init_definition();
10288
10650
  settingsSchema3 = external_exports.object({
10289
10651
  apiHost: external_exports.string().url().default("https://api.minimaxi.com"),
@@ -10447,7 +10809,7 @@ var init_notifications = __esm({
10447
10809
  "../server/src/connectors/builtins/notifications.ts"() {
10448
10810
  "use strict";
10449
10811
  init_zod();
10450
- init_errors2();
10812
+ init_errors3();
10451
10813
  init_definition();
10452
10814
  emptySettingsSchema = external_exports.object({});
10453
10815
  barkCredentialsSchema = external_exports.object({ url: external_exports.string().url() });
@@ -11293,7 +11655,7 @@ var init_weixin = __esm({
11293
11655
  "use strict";
11294
11656
  init_zod();
11295
11657
  init_src();
11296
- init_errors2();
11658
+ init_errors3();
11297
11659
  init_definition();
11298
11660
  init_types2();
11299
11661
  WeixinCapability = defineCapability("weixin");
@@ -11703,85 +12065,6 @@ var init_weixin = __esm({
11703
12065
  }
11704
12066
  });
11705
12067
 
11706
- // ../server/src/connectors/url-policy.ts
11707
- function assertPublicHttpUrl(value) {
11708
- let url;
11709
- try {
11710
- url = new URL(value);
11711
- } catch {
11712
- throw new ConnectorError({ kind: "configuration", message: "\u6765\u6E90 URL \u65E0\u6548" });
11713
- }
11714
- if (url.protocol !== "http:" && url.protocol !== "https:") {
11715
- throw new ConnectorError({
11716
- kind: "configuration",
11717
- message: "\u6765\u6E90 URL \u53EA\u652F\u6301 http:// \u6216 https://"
11718
- });
11719
- }
11720
- const hostname = url.hostname.toLowerCase().replace(/^\[|\]$/g, "");
11721
- if (isReservedHostname(hostname) || isPrivateAddress(hostname)) {
11722
- throw new ConnectorError({
11723
- kind: "configuration",
11724
- message: "\u6765\u6E90 URL \u6307\u5411\u5185\u7F51\u6216\u4FDD\u7559\u5730\u5740\uFF0C\u5DF2\u62D2\u7EDD\u6293\u53D6"
11725
- });
11726
- }
11727
- }
11728
- function isReservedHostname(hostname) {
11729
- if (!hostname) return true;
11730
- if (hostname === "localhost" || hostname === "metadata.google.internal") return true;
11731
- if (/^\d+$/.test(hostname)) return true;
11732
- return reservedHostnameSuffixes.some((suffix) => hostname.endsWith(suffix));
11733
- }
11734
- function isPrivateAddress(hostname) {
11735
- if (hostname.includes(":")) return isPrivateIpv6(hostname);
11736
- const octets = hostname.split(".");
11737
- if (octets.length !== 4 || octets.some((part) => !/^\d{1,3}$/.test(part))) return false;
11738
- const numbers = octets.map((part) => Number(part));
11739
- if (numbers.some((value) => value > 255)) return false;
11740
- return isPrivateIpv4(numbers);
11741
- }
11742
- function isPrivateIpv4([a, b2]) {
11743
- if (a === 0 || a === 10 || a === 127) return true;
11744
- if (a === 169 && b2 === 254) return true;
11745
- if (a === 172 && b2 >= 16 && b2 <= 31) return true;
11746
- if (a === 192 && b2 === 168) return true;
11747
- if (a === 100 && b2 >= 64 && b2 <= 127) return true;
11748
- if (a === 192 && b2 === 0) return true;
11749
- if (a === 198 && (b2 === 18 || b2 === 19)) return true;
11750
- if (a === 198 && b2 === 51) return true;
11751
- if (a === 203 && b2 === 0) return true;
11752
- if (a >= 224) return true;
11753
- return false;
11754
- }
11755
- function isPrivateIpv6(hostname) {
11756
- const address = hostname.toLowerCase();
11757
- if (address === "::" || address === "::1") return true;
11758
- const mapped = address.match(/^::ffff:(\d{1,3}(?:\.\d{1,3}){3})$/);
11759
- if (mapped) return isPrivateAddress(mapped[1]);
11760
- if (address.startsWith("::ffff:")) return true;
11761
- const firstGroup = address.split(":")[0] ?? "";
11762
- if (/^f[cd]/.test(firstGroup)) return true;
11763
- if (/^fe[89ab]/.test(firstGroup)) return true;
11764
- return false;
11765
- }
11766
- var reservedHostnameSuffixes;
11767
- var init_url_policy = __esm({
11768
- "../server/src/connectors/url-policy.ts"() {
11769
- "use strict";
11770
- init_errors2();
11771
- reservedHostnameSuffixes = [
11772
- ".localhost",
11773
- ".local",
11774
- ".internal",
11775
- ".corp",
11776
- ".lan",
11777
- ".home",
11778
- ".invalid",
11779
- ".test",
11780
- ".example"
11781
- ];
11782
- }
11783
- });
11784
-
11785
12068
  // ../server/src/connectors/builtins/sources.ts
11786
12069
  function normalizeFetchedDocuments(provider, url, raw2) {
11787
12070
  if (typeof raw2 === "string") {
@@ -11852,7 +12135,7 @@ function bearerHeader(value) {
11852
12135
  function atomCandidates(xml, provider) {
11853
12136
  return [...xml.matchAll(/<entry>([\s\S]*?)<\/entry>/g)].map((match2, index2) => {
11854
12137
  const entry = match2[1];
11855
- const text2 = (tag) => decode(entry.match(new RegExp(`<${tag}[^>]*>([\\s\\S]*?)<\\/${tag}>`))?.[1] ?? "");
12138
+ const text2 = (tag) => decode2(entry.match(new RegExp(`<${tag}[^>]*>([\\s\\S]*?)<\\/${tag}>`))?.[1] ?? "");
11856
12139
  return {
11857
12140
  id: `${provider}-${index2}-${crypto.randomUUID()}`,
11858
12141
  title: text2("title"),
@@ -11881,7 +12164,7 @@ function markdownCandidates(markdown, provider) {
11881
12164
  }
11882
12165
  return candidates;
11883
12166
  }
11884
- function decode(value) {
12167
+ function decode2(value) {
11885
12168
  return value.replace(/<[^>]+>/g, " ").replace(/&amp;/g, "&").replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/\s+/g, " ").trim();
11886
12169
  }
11887
12170
  var empty, apiKey, optionalApiKey, bearer, urlProviders, providers, sourceConnectors, searchOperation, fetchOperation, BuiltInSourceClient;
@@ -12173,11 +12456,12 @@ var init_connectors2 = __esm({
12173
12456
  "use strict";
12174
12457
  init_connection();
12175
12458
  init_definition();
12176
- init_errors2();
12459
+ init_errors3();
12177
12460
  init_http();
12178
12461
  init_registry();
12179
12462
  init_runtime();
12180
12463
  init_types2();
12464
+ init_url_policy();
12181
12465
  init_builtins();
12182
12466
  }
12183
12467
  });
@@ -12694,7 +12978,7 @@ var init_run = __esm({
12694
12978
  async createRun(input) {
12695
12979
  const timestamp = this.now().toISOString();
12696
12980
  const run2 = {
12697
- id: `run-${crypto.randomUUID()}`,
12981
+ id: input.id ?? `run-${crypto.randomUUID()}`,
12698
12982
  kind: input.kind,
12699
12983
  status: RunStatus2.Queued,
12700
12984
  trigger: structuredClone(input.trigger),
@@ -14437,6 +14721,16 @@ var init_croner = __esm({
14437
14721
  }
14438
14722
  });
14439
14723
 
14724
+ // ../server/src/shared/logging.ts
14725
+ var init_logging = __esm({
14726
+ "../server/src/shared/logging.ts"() {
14727
+ "use strict";
14728
+ init_configure_logger_observability();
14729
+ init_logger_context();
14730
+ init_logger();
14731
+ }
14732
+ });
14733
+
14440
14734
  // ../server/src/domain/automation/publication-sessions.ts
14441
14735
  async function createPublicationSessions(runs, workspace2, runId, destinations) {
14442
14736
  return await Promise.all(
@@ -14489,13 +14783,15 @@ function assertValidScheduleTrigger(cron, timezone) {
14489
14783
  );
14490
14784
  }
14491
14785
  }
14492
- var AutomationScheduler;
14786
+ var logger, AutomationScheduler;
14493
14787
  var init_automation_scheduler = __esm({
14494
14788
  "../server/src/domain/automation/automation-scheduler.ts"() {
14495
14789
  "use strict";
14496
14790
  init_croner();
14497
14791
  init_src();
14792
+ init_logging();
14498
14793
  init_publication_sessions();
14794
+ logger = new Logger("automation-scheduler");
14499
14795
  AutomationScheduler = class {
14500
14796
  constructor(options2) {
14501
14797
  this.options = options2;
@@ -14507,33 +14803,53 @@ var init_automation_scheduler = __esm({
14507
14803
  intervalMs;
14508
14804
  catchUpWindowMs;
14509
14805
  timer;
14806
+ ticking = false;
14510
14807
  start() {
14511
14808
  if (this.timer) return;
14512
14809
  this.timer = setInterval(() => {
14513
- void this.tick().catch(() => void 0);
14810
+ void this.tick().catch((error) => {
14811
+ logger.error("\u5B9A\u65F6\u8C03\u5EA6\u626B\u63CF\u5931\u8D25:", error instanceof Error ? error.message : String(error));
14812
+ });
14514
14813
  }, this.intervalMs);
14814
+ this.timer.unref?.();
14515
14815
  }
14516
14816
  stop() {
14517
14817
  if (this.timer) clearInterval(this.timer);
14518
14818
  this.timer = void 0;
14519
14819
  }
14520
14820
  async tick() {
14521
- const now = this.now();
14522
- const automations2 = await this.options.workspace.list(WorkspaceKind.Automation);
14523
- for (const automation of automations2) {
14524
- if (!automation.enabled || automation.trigger.type !== "schedule") continue;
14525
- const fireAt = previousFireTime(automation.trigger.cron, automation.trigger.timezone, now);
14526
- if (!fireAt) continue;
14527
- if (now.getTime() - fireAt.getTime() > this.catchUpWindowMs) continue;
14528
- const jobId = scheduledJobId(automation.id, fireAt);
14529
- if (await this.options.jobs.get(jobId)) continue;
14530
- await this.fire(automation.id, automation.contentPlanId, jobId);
14821
+ if (this.ticking) return;
14822
+ this.ticking = true;
14823
+ try {
14824
+ const now = this.now();
14825
+ const automations2 = await this.options.workspace.list(WorkspaceKind.Automation);
14826
+ for (const automation of automations2) {
14827
+ if (!automation.enabled || automation.trigger.type !== "schedule") continue;
14828
+ const fireAt = previousFireTime(automation.trigger.cron, automation.trigger.timezone, now);
14829
+ if (!fireAt) continue;
14830
+ if (now.getTime() - fireAt.getTime() > this.catchUpWindowMs) continue;
14831
+ const jobId = scheduledJobId(automation.id, fireAt);
14832
+ if (await this.options.jobs.get(jobId)) continue;
14833
+ await this.fire(automation.id, automation.contentPlanId, jobId);
14834
+ }
14835
+ } finally {
14836
+ this.ticking = false;
14531
14837
  }
14532
14838
  }
14533
14839
  async fire(automationId, contentPlanId, jobId) {
14534
14840
  const plan = await this.options.workspace.get(WorkspaceKind.ContentPlan, contentPlanId);
14535
14841
  if (!plan || !plan.enabled) return;
14842
+ const runId = `run-${crypto.randomUUID()}`;
14843
+ try {
14844
+ await this.options.automations.createRunJob(
14845
+ { automationId, destinations: plan.publishing.destinations },
14846
+ { runId, jobId }
14847
+ );
14848
+ } catch {
14849
+ return;
14850
+ }
14536
14851
  const run2 = await this.options.runs.createRun({
14852
+ id: runId,
14537
14853
  kind: RunKind.Content,
14538
14854
  trigger: { kind: RunTriggerKind.Automation, automationId },
14539
14855
  planId: plan.id,
@@ -14547,14 +14863,6 @@ var init_automation_scheduler = __esm({
14547
14863
  run2.id,
14548
14864
  plan.publishing.destinations
14549
14865
  );
14550
- try {
14551
- await this.options.automations.createRunJob(
14552
- { automationId, destinations: plan.publishing.destinations },
14553
- { runId: run2.id, jobId }
14554
- );
14555
- } catch {
14556
- return;
14557
- }
14558
14866
  this.options.background.start(
14559
14867
  `automation:${jobId}`,
14560
14868
  () => this.options.automations.resume(jobId)
@@ -14614,8 +14922,8 @@ var init_background_tasks2 = __esm({
14614
14922
  init_logger();
14615
14923
  init_runtime2();
14616
14924
  InProcessBackgroundTasks = class {
14617
- constructor(logger5 = new Logger("background-tasks")) {
14618
- this.logger = logger5;
14925
+ constructor(logger6 = new Logger("background-tasks")) {
14926
+ this.logger = logger6;
14619
14927
  }
14620
14928
  active = /* @__PURE__ */ new Map();
14621
14929
  start(name, task) {
@@ -16824,7 +17132,7 @@ function selectPublishableEvidence(materials, evidence) {
16824
17132
  }
16825
17133
  function evidenceLocatorIssues(evidence, material) {
16826
17134
  const issues = [];
16827
- const invalid = (message) => {
17135
+ const invalid2 = (message) => {
16828
17136
  issues.push({ code: EvidenceDiagnosticCode.LocatorInvalid, message });
16829
17137
  };
16830
17138
  const mismatch = (message) => {
@@ -16834,7 +17142,7 @@ function evidenceLocatorIssues(evidence, material) {
16834
17142
  case "text": {
16835
17143
  const excerpt = evidence.locator.excerpt;
16836
17144
  if (!excerpt.trim()) {
16837
- invalid(`\u8BC1\u636E ${evidence.id} \u7684\u6587\u672C\u5B9A\u4F4D\u7F3A\u5C11\u6458\u5F55`);
17145
+ invalid2(`\u8BC1\u636E ${evidence.id} \u7684\u6587\u672C\u5B9A\u4F4D\u7F3A\u5C11\u6458\u5F55`);
16838
17146
  break;
16839
17147
  }
16840
17148
  const searchableText = [material?.content, material?.transcript].filter(
@@ -16848,14 +17156,14 @@ function evidenceLocatorIssues(evidence, material) {
16848
17156
  case "time-range": {
16849
17157
  const { startMs, endMs, transcript } = evidence.locator;
16850
17158
  if (!Number.isFinite(startMs) || startMs < 0) {
16851
- invalid(`\u8BC1\u636E ${evidence.id} \u7684\u65F6\u95F4\u8D77\u70B9\u5FC5\u987B\u662F\u975E\u8D1F\u6709\u9650\u6570`);
17159
+ invalid2(`\u8BC1\u636E ${evidence.id} \u7684\u65F6\u95F4\u8D77\u70B9\u5FC5\u987B\u662F\u975E\u8D1F\u6709\u9650\u6570`);
16852
17160
  }
16853
17161
  if (endMs !== void 0 && (!Number.isFinite(endMs) || endMs < startMs)) {
16854
- invalid(`\u8BC1\u636E ${evidence.id} \u7684\u65F6\u95F4\u7EC8\u70B9\u5FC5\u987B\u662F\u6709\u9650\u6570\u4E14\u4E0D\u65E9\u4E8E\u8D77\u70B9`);
17162
+ invalid2(`\u8BC1\u636E ${evidence.id} \u7684\u65F6\u95F4\u7EC8\u70B9\u5FC5\u987B\u662F\u6709\u9650\u6570\u4E14\u4E0D\u65E9\u4E8E\u8D77\u70B9`);
16855
17163
  }
16856
17164
  if (transcript !== void 0) {
16857
17165
  if (!transcript.trim()) {
16858
- invalid(`\u8BC1\u636E ${evidence.id} \u7684\u65F6\u95F4\u5B9A\u4F4D\u5305\u542B\u7A7A\u8F6C\u5F55\u6458\u5F55`);
17166
+ invalid2(`\u8BC1\u636E ${evidence.id} \u7684\u65F6\u95F4\u5B9A\u4F4D\u5305\u542B\u7A7A\u8F6C\u5F55\u6458\u5F55`);
16859
17167
  } else if (material?.transcript && !material.transcript.includes(transcript)) {
16860
17168
  mismatch(`\u8BC1\u636E ${evidence.id} \u7684\u8F6C\u5F55\u6458\u5F55\u4E0D\u5728\u7D20\u6750 ${evidence.materialId} \u4E2D`);
16861
17169
  }
@@ -16865,11 +17173,11 @@ function evidenceLocatorIssues(evidence, material) {
16865
17173
  case "page": {
16866
17174
  const { page, excerpt } = evidence.locator;
16867
17175
  if (!Number.isInteger(page) || page < 1) {
16868
- invalid(`\u8BC1\u636E ${evidence.id} \u7684\u9875\u7801\u5FC5\u987B\u662F\u6B63\u6574\u6570`);
17176
+ invalid2(`\u8BC1\u636E ${evidence.id} \u7684\u9875\u7801\u5FC5\u987B\u662F\u6B63\u6574\u6570`);
16869
17177
  }
16870
17178
  if (excerpt !== void 0) {
16871
17179
  if (!excerpt.trim()) {
16872
- invalid(`\u8BC1\u636E ${evidence.id} \u7684\u9875\u7801\u5B9A\u4F4D\u5305\u542B\u7A7A\u6458\u5F55`);
17180
+ invalid2(`\u8BC1\u636E ${evidence.id} \u7684\u9875\u7801\u5B9A\u4F4D\u5305\u542B\u7A7A\u6458\u5F55`);
16873
17181
  } else if (material?.content && !material.content.includes(excerpt)) {
16874
17182
  mismatch(`\u8BC1\u636E ${evidence.id} \u7684\u9875\u9762\u6458\u5F55\u4E0D\u5728\u7D20\u6750 ${evidence.materialId} \u4E2D`);
16875
17183
  }
@@ -20192,7 +20500,7 @@ function parseWeixinLayoutDsl(value) {
20192
20500
  }
20193
20501
  function validateWeixinLayoutDsl(value) {
20194
20502
  const diagnostics = [];
20195
- if (!isObject(value)) return [{ pointer: "", message: "DSL \u5FC5\u987B\u662F JSON \u5BF9\u8C61" }];
20503
+ if (!isObject2(value)) return [{ pointer: "", message: "DSL \u5FC5\u987B\u662F JSON \u5BF9\u8C61" }];
20196
20504
  rejectUnknownKeys(
20197
20505
  value,
20198
20506
  /* @__PURE__ */ new Set([
@@ -20221,11 +20529,11 @@ function validateWeixinLayoutDsl(value) {
20221
20529
  validateConstraints(value.constraints, diagnostics);
20222
20530
  return diagnostics;
20223
20531
  }
20224
- function isObject(value) {
20532
+ function isObject2(value) {
20225
20533
  return Boolean(value) && typeof value === "object" && !Array.isArray(value);
20226
20534
  }
20227
20535
  function validateTokens(value, diagnostics) {
20228
- if (!isObject(value)) {
20536
+ if (!isObject2(value)) {
20229
20537
  diagnostics.push({ pointer: "/tokens", message: "\u5FC5\u987B\u662F\u5BF9\u8C61" });
20230
20538
  return;
20231
20539
  }
@@ -20251,7 +20559,7 @@ function validateTokens(value, diagnostics) {
20251
20559
  );
20252
20560
  }
20253
20561
  function validateTokenRecord(value, pointer, diagnostics, predicate) {
20254
- if (!isObject(value) || !Object.keys(value).length) {
20562
+ if (!isObject2(value) || !Object.keys(value).length) {
20255
20563
  diagnostics.push({ pointer, message: "\u5FC5\u987B\u662F\u975E\u7A7A\u5BF9\u8C61" });
20256
20564
  return;
20257
20565
  }
@@ -20269,14 +20577,14 @@ function validateTokenRecord(value, pointer, diagnostics, predicate) {
20269
20577
  }
20270
20578
  }
20271
20579
  function validateStyles(value, diagnostics) {
20272
- if (!isObject(value) || !Object.keys(value).length) {
20580
+ if (!isObject2(value) || !Object.keys(value).length) {
20273
20581
  diagnostics.push({ pointer: "/styles", message: "\u81F3\u5C11\u9700\u8981\u4E00\u4E2A\u6837\u5F0F" });
20274
20582
  return;
20275
20583
  }
20276
20584
  for (const [id, candidate] of Object.entries(value)) {
20277
20585
  const pointer = `/styles/${escapePointer(id)}`;
20278
20586
  if (!validId(id)) diagnostics.push({ pointer, message: "\u6837\u5F0F ID \u4E0D\u5408\u6CD5" });
20279
- if (!isObject(candidate)) {
20587
+ if (!isObject2(candidate)) {
20280
20588
  diagnostics.push({ pointer, message: "\u6837\u5F0F\u5FC5\u987B\u662F\u5BF9\u8C61" });
20281
20589
  continue;
20282
20590
  }
@@ -20326,7 +20634,7 @@ function validateStyles(value, diagnostics) {
20326
20634
  }
20327
20635
  function validateStyleSection(value, allowed, pointer, diagnostics) {
20328
20636
  if (value === void 0) return;
20329
- if (!isObject(value)) {
20637
+ if (!isObject2(value)) {
20330
20638
  diagnostics.push({ pointer, message: "\u5FC5\u987B\u662F\u5BF9\u8C61" });
20331
20639
  return;
20332
20640
  }
@@ -20349,7 +20657,7 @@ function validateStyleSection(value, allowed, pointer, diagnostics) {
20349
20657
  }
20350
20658
  function validateBackground(value, pointer, diagnostics) {
20351
20659
  if (value === void 0) return;
20352
- if (!isObject(value)) {
20660
+ if (!isObject2(value)) {
20353
20661
  diagnostics.push({ pointer, message: "\u5FC5\u987B\u662F\u5BF9\u8C61" });
20354
20662
  return;
20355
20663
  }
@@ -20357,7 +20665,7 @@ function validateBackground(value, pointer, diagnostics) {
20357
20665
  if (value.color !== void 0 && !isSafeStyleString(value.color))
20358
20666
  diagnostics.push({ pointer: `${pointer}/color`, message: "\u80CC\u666F\u8272\u4E0D\u5B89\u5168" });
20359
20667
  if (value.gradient !== void 0) {
20360
- if (!isObject(value.gradient) || !Array.isArray(value.gradient.stops) || value.gradient.stops.length < 2 || value.gradient.stops.length > 8)
20668
+ if (!isObject2(value.gradient) || !Array.isArray(value.gradient.stops) || value.gradient.stops.length < 2 || value.gradient.stops.length > 8)
20361
20669
  diagnostics.push({ pointer: `${pointer}/gradient`, message: "\u6E10\u53D8\u5FC5\u987B\u5305\u542B 2-8 \u4E2A\u8272\u6807" });
20362
20670
  else {
20363
20671
  rejectUnknownKeys(
@@ -20376,7 +20684,7 @@ function validateBackground(value, pointer, diagnostics) {
20376
20684
  });
20377
20685
  }
20378
20686
  for (const [index2, stop] of value.gradient.stops.entries())
20379
- if (!isObject(stop))
20687
+ if (!isObject2(stop))
20380
20688
  diagnostics.push({
20381
20689
  pointer: `${pointer}/gradient/stops/${index2}`,
20382
20690
  message: "\u6E10\u53D8\u8272\u6807\u65E0\u6548"
@@ -20397,7 +20705,7 @@ function validateBackground(value, pointer, diagnostics) {
20397
20705
  }
20398
20706
  }
20399
20707
  if (value.image !== void 0) {
20400
- if (!isObject(value.image))
20708
+ if (!isObject2(value.image))
20401
20709
  diagnostics.push({ pointer: `${pointer}/image`, message: "\u5FC5\u987B\u662F\u5BF9\u8C61" });
20402
20710
  else {
20403
20711
  rejectUnknownKeys(
@@ -20427,14 +20735,14 @@ function validateBackground(value, pointer, diagnostics) {
20427
20735
  }
20428
20736
  }
20429
20737
  function validateComponents(value, styles, diagnostics) {
20430
- if (!isObject(value) || !Object.keys(value).length) {
20738
+ if (!isObject2(value) || !Object.keys(value).length) {
20431
20739
  diagnostics.push({ pointer: "/components", message: "\u81F3\u5C11\u9700\u8981\u4E00\u4E2A\u7EC4\u4EF6" });
20432
20740
  return;
20433
20741
  }
20434
20742
  for (const [id, candidate] of Object.entries(value)) {
20435
20743
  const pointer = `/components/${escapePointer(id)}`;
20436
20744
  if (!validId(id)) diagnostics.push({ pointer, message: "\u7EC4\u4EF6 ID \u4E0D\u5408\u6CD5" });
20437
- if (!isObject(candidate)) {
20745
+ if (!isObject2(candidate)) {
20438
20746
  diagnostics.push({ pointer, message: "\u7EC4\u4EF6\u5FC5\u987B\u662F\u5BF9\u8C61" });
20439
20747
  continue;
20440
20748
  }
@@ -20450,7 +20758,7 @@ function validateComponents(value, styles, diagnostics) {
20450
20758
  diagnostics.push({ pointer: `${pointer}/styleIds`, message: "\u5FC5\u987B\u662F\u6570\u7EC4" });
20451
20759
  else
20452
20760
  for (const [index2, styleId] of candidate.styleIds.entries())
20453
- if (typeof styleId !== "string" || !isObject(styles) || !isObject(styles[styleId]))
20761
+ if (typeof styleId !== "string" || !isObject2(styles) || !isObject2(styles[styleId]))
20454
20762
  diagnostics.push({
20455
20763
  pointer: `${pointer}/styleIds/${index2}`,
20456
20764
  message: "\u5FC5\u987B\u5F15\u7528\u5DF2\u767B\u8BB0\u6837\u5F0F"
@@ -20462,7 +20770,7 @@ function validateAssets(assets, slots, diagnostics) {
20462
20770
  else
20463
20771
  for (const [index2, asset] of assets.entries()) {
20464
20772
  const pointer = `/assets/${index2}`;
20465
- if (!isObject(asset)) {
20773
+ if (!isObject2(asset)) {
20466
20774
  diagnostics.push({ pointer, message: "\u56FA\u5B9A\u7D20\u6750\u683C\u5F0F\u65E0\u6548" });
20467
20775
  continue;
20468
20776
  }
@@ -20479,7 +20787,7 @@ function validateAssets(assets, slots, diagnostics) {
20479
20787
  else
20480
20788
  for (const [index2, slot] of slots.entries()) {
20481
20789
  const pointer = `/assetSlots/${index2}`;
20482
- if (!isObject(slot)) {
20790
+ if (!isObject2(slot)) {
20483
20791
  diagnostics.push({ pointer, message: "\u52A8\u6001\u7D20\u6750\u69FD\u4F4D\u683C\u5F0F\u65E0\u6548" });
20484
20792
  continue;
20485
20793
  }
@@ -20497,20 +20805,20 @@ function validateAssets(assets, slots, diagnostics) {
20497
20805
  [slots, "/assetSlots"]
20498
20806
  ])
20499
20807
  if (Array.isArray(values)) {
20500
- const ids = values.map((item) => isObject(item) ? item.id : void 0).filter((item) => typeof item === "string");
20808
+ const ids = values.map((item) => isObject2(item) ? item.id : void 0).filter((item) => typeof item === "string");
20501
20809
  if (new Set(ids).size !== ids.length) diagnostics.push({ pointer, message: "ID \u4E0D\u80FD\u91CD\u590D" });
20502
20810
  }
20503
20811
  }
20504
20812
  function validateStyleAssetReferences(styles, assets, slots, diagnostics) {
20505
- if (!isObject(styles)) return;
20813
+ if (!isObject2(styles)) return;
20506
20814
  const assetIds = new Set(
20507
- Array.isArray(assets) ? assets.filter(isObject).map((item) => item.id) : []
20815
+ Array.isArray(assets) ? assets.filter(isObject2).map((item) => item.id) : []
20508
20816
  );
20509
20817
  const slotIds = new Set(
20510
- Array.isArray(slots) ? slots.filter(isObject).map((item) => item.id) : []
20818
+ Array.isArray(slots) ? slots.filter(isObject2).map((item) => item.id) : []
20511
20819
  );
20512
20820
  for (const [id, candidate] of Object.entries(styles)) {
20513
- if (!isObject(candidate) || !isObject(candidate.background) || !isObject(candidate.background.image))
20821
+ if (!isObject2(candidate) || !isObject2(candidate.background) || !isObject2(candidate.background.image))
20514
20822
  continue;
20515
20823
  const image = candidate.background.image;
20516
20824
  if (typeof image.assetId === "string" && !assetIds.has(image.assetId))
@@ -20526,7 +20834,7 @@ function validateStyleAssetReferences(styles, assets, slots, diagnostics) {
20526
20834
  }
20527
20835
  }
20528
20836
  function validateConstraints(value, diagnostics) {
20529
- if (!isObject(value)) {
20837
+ if (!isObject2(value)) {
20530
20838
  diagnostics.push({ pointer: "/constraints", message: "\u5FC5\u987B\u662F\u5BF9\u8C61" });
20531
20839
  return;
20532
20840
  }
@@ -20851,7 +21159,7 @@ function renderReferences(context) {
20851
21159
  return `<section style="${escapeHtmlAttribute(css)}"><h3>\u53C2\u8003\u8D44\u6599</h3>${context.references.map((reference, index2) => `<p>[${index2 + 1}] ${escapeHtml2(reference.label)}<br><span>${escapeHtml2(reference.url)}</span></p>`).join("")}</section>`;
20852
21160
  }
20853
21161
  function validateLayoutPlan(contentPackage, dsl, plan, additionalAssets) {
20854
- if (!isObject(plan) || !isObject(plan.root) || !isObject(plan.assetBindings)) {
21162
+ if (!isObject2(plan) || !isObject2(plan.root) || !isObject2(plan.assetBindings)) {
20855
21163
  throw new Error("\u5E03\u5C40\u8BA1\u5212\u5FC5\u987B\u5305\u542B root \u548C assetBindings");
20856
21164
  }
20857
21165
  const expected = contentPackage.document.root.children.map((node) => node.id);
@@ -20860,7 +21168,7 @@ function validateLayoutPlan(contentPackage, dsl, plan, additionalAssets) {
20860
21168
  const seen = /* @__PURE__ */ new Set();
20861
21169
  while (stack.length) {
20862
21170
  const { node, pointer } = stack.pop();
20863
- if (!isObject(node)) throw new Error(`\u5E03\u5C40\u8BA1\u5212 ${pointer} \u5FC5\u987B\u662F\u5BF9\u8C61`);
21171
+ if (!isObject2(node)) throw new Error(`\u5E03\u5C40\u8BA1\u5212 ${pointer} \u5FC5\u987B\u662F\u5BF9\u8C61`);
20864
21172
  if (seen.has(node)) throw new Error(`\u5E03\u5C40\u8BA1\u5212 ${pointer} \u5305\u542B\u5FAA\u73AF\u5F15\u7528`);
20865
21173
  seen.add(node);
20866
21174
  if (node.type === "content") {
@@ -21295,7 +21603,7 @@ async function resolvePublicationLayout(input) {
21295
21603
  if (version2.compilerVersion !== WEIXIN_LAYOUT_COMPILER_VERSION) {
21296
21604
  throw new Error("\u56FA\u5B9A\u6A21\u677F\u7248\u672C\u4E0E\u5F53\u524D\u5FAE\u4FE1\u7F16\u8BD1\u5668\u4E0D\u517C\u5BB9");
21297
21605
  }
21298
- if (!version2.artifact || !isObject2(version2.artifact)) {
21606
+ if (!version2.artifact || !isObject3(version2.artifact)) {
21299
21607
  throw new Error("\u56FA\u5B9A\u6A21\u677F\u7248\u672C\u6CA1\u6709\u65B0\u534F\u8BAE Artifact\uFF1B\u8BF7\u5148\u5B8C\u6210\u6A21\u677F\u8FC1\u79FB");
21300
21608
  }
21301
21609
  const actualChecksum = await fingerprint({
@@ -21322,7 +21630,7 @@ async function resolvePublicationLayout(input) {
21322
21630
  };
21323
21631
  }
21324
21632
  function parseLayoutSelection(value) {
21325
- if (!isObject2(value)) return void 0;
21633
+ if (!isObject3(value)) return void 0;
21326
21634
  if (!Object.values(PublicationLayoutMode).includes(value.mode)) {
21327
21635
  throw new Error("\u672A\u77E5\u6216\u5DF2\u505C\u7528\u7684\u6392\u7248\u6A21\u5F0F\uFF1B\u8BF7\u5B8C\u6210\u6A21\u677F\u8FC1\u79FB");
21328
21636
  }
@@ -21354,7 +21662,7 @@ function firstConcreteLayout(candidates) {
21354
21662
  (candidate) => candidate && candidate.layout.mode !== PublicationLayoutMode.Inherit
21355
21663
  );
21356
21664
  }
21357
- function isObject2(value) {
21665
+ function isObject3(value) {
21358
21666
  return Boolean(value) && typeof value === "object" && !Array.isArray(value);
21359
21667
  }
21360
21668
  var WEIXIN_ADAPTIVE_LAYOUT_PROMPT;
@@ -33603,8 +33911,8 @@ var init_sql = __esm({
33603
33911
  }
33604
33912
  return new _SQL.Aliased(this, alias);
33605
33913
  }
33606
- mapWith(decoder) {
33607
- this.decoder = typeof decoder === "function" ? { mapFromDriverValue: decoder } : decoder;
33914
+ mapWith(decoder2) {
33915
+ this.decoder = typeof decoder2 === "function" ? { mapFromDriverValue: decoder2 } : decoder2;
33608
33916
  return this;
33609
33917
  }
33610
33918
  inlineParams() {
@@ -33646,9 +33954,9 @@ var init_sql = __esm({
33646
33954
  * @param value - Parameter value
33647
33955
  * @param encoder - Encoder to convert the value to a driver parameter
33648
33956
  */
33649
- constructor(value, encoder = noopEncoder) {
33957
+ constructor(value, encoder2 = noopEncoder) {
33650
33958
  this.value = value;
33651
- this.encoder = encoder;
33959
+ this.encoder = encoder2;
33652
33960
  }
33653
33961
  static [entityKind] = "Param";
33654
33962
  brand;
@@ -33688,8 +33996,8 @@ var init_sql = __esm({
33688
33996
  return new Placeholder(name2);
33689
33997
  }
33690
33998
  sql2.placeholder = placeholder2;
33691
- function param2(value, encoder) {
33692
- return new Param(value, encoder);
33999
+ function param2(value, encoder2) {
34000
+ return new Param(value, encoder2);
33693
34001
  }
33694
34002
  sql2.param = param2;
33695
34003
  })(sql || (sql = {}));
@@ -33760,15 +34068,15 @@ function mapResultRow(columns, row, joinsNotNullableMap) {
33760
34068
  const nullifyMap = {};
33761
34069
  const result = columns.reduce(
33762
34070
  (result2, { path: path7, field }, columnIndex) => {
33763
- let decoder;
34071
+ let decoder2;
33764
34072
  if (is(field, Column)) {
33765
- decoder = field;
34073
+ decoder2 = field;
33766
34074
  } else if (is(field, SQL)) {
33767
- decoder = field.decoder;
34075
+ decoder2 = field.decoder;
33768
34076
  } else if (is(field, Subquery)) {
33769
- decoder = field._.sql.decoder;
34077
+ decoder2 = field._.sql.decoder;
33770
34078
  } else {
33771
- decoder = field.sql.decoder;
34079
+ decoder2 = field.sql.decoder;
33772
34080
  }
33773
34081
  let node = result2;
33774
34082
  for (const [pathChunkIndex, pathChunk] of path7.entries()) {
@@ -33779,7 +34087,7 @@ function mapResultRow(columns, row, joinsNotNullableMap) {
33779
34087
  node = node[pathChunk];
33780
34088
  } else {
33781
34089
  const rawValue = row[columnIndex];
33782
- const value = node[pathChunk] = rawValue === null ? null : decoder.mapFromDriverValue(rawValue);
34090
+ const value = node[pathChunk] = rawValue === null ? null : decoder2.mapFromDriverValue(rawValue);
33783
34091
  if (joinsNotNullableMap && is(field, Column) && path7.length === 2) {
33784
34092
  const objectName = path7[0];
33785
34093
  if (!(objectName in nullifyMap)) {
@@ -34321,15 +34629,15 @@ function mapRelationalRow(tablesConfig, tableConfig, row, buildQueryResultSelect
34321
34629
  } else {
34322
34630
  const value = mapColumnValue(row[selectionItemIndex]);
34323
34631
  const field = selectionItem.field;
34324
- let decoder;
34632
+ let decoder2;
34325
34633
  if (is(field, Column)) {
34326
- decoder = field;
34634
+ decoder2 = field;
34327
34635
  } else if (is(field, SQL)) {
34328
- decoder = field.decoder;
34636
+ decoder2 = field.decoder;
34329
34637
  } else {
34330
- decoder = field.sql.decoder;
34638
+ decoder2 = field.sql.decoder;
34331
34639
  }
34332
- result[selectionItem.tsKey] = value === null ? null : decoder.mapFromDriverValue(value);
34640
+ result[selectionItem.tsKey] = value === null ? null : decoder2.mapFromDriverValue(value);
34333
34641
  }
34334
34642
  }
34335
34643
  return result;
@@ -35643,7 +35951,7 @@ var init_casing = __esm({
35643
35951
 
35644
35952
  // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@types+better-sqlite3@9.6.0_better-sqlite3@13.2.0/node_modules/drizzle-orm/errors.js
35645
35953
  var DrizzleError, DrizzleQueryError, TransactionRollbackError;
35646
- var init_errors3 = __esm({
35954
+ var init_errors4 = __esm({
35647
35955
  "../../node_modules/.pnpm/drizzle-orm@0.45.4_@types+better-sqlite3@9.6.0_better-sqlite3@13.2.0/node_modules/drizzle-orm/errors.js"() {
35648
35956
  init_entity();
35649
35957
  DrizzleError = class extends Error {
@@ -35745,7 +36053,7 @@ var init_dialect = __esm({
35745
36053
  init_casing();
35746
36054
  init_column();
35747
36055
  init_entity();
35748
- init_errors3();
36056
+ init_errors4();
35749
36057
  init_relations();
35750
36058
  init_sql2();
35751
36059
  init_sql();
@@ -38151,8 +38459,8 @@ var init_db = __esm({
38151
38459
  // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@types+better-sqlite3@9.6.0_better-sqlite3@13.2.0/node_modules/drizzle-orm/cache/core/cache.js
38152
38460
  async function hashQuery(sql2, params) {
38153
38461
  const dataToHash = `${sql2}-${JSON.stringify(params)}`;
38154
- const encoder = new TextEncoder();
38155
- const data = encoder.encode(dataToHash);
38462
+ const encoder2 = new TextEncoder();
38463
+ const data = encoder2.encode(dataToHash);
38156
38464
  const hashBuffer = await crypto.subtle.digest("SHA-256", data);
38157
38465
  const hashArray = [...new Uint8Array(hashBuffer)];
38158
38466
  const hashHex = hashArray.map((b2) => b2.toString(16).padStart(2, "0")).join("");
@@ -38200,7 +38508,7 @@ var init_session = __esm({
38200
38508
  "../../node_modules/.pnpm/drizzle-orm@0.45.4_@types+better-sqlite3@9.6.0_better-sqlite3@13.2.0/node_modules/drizzle-orm/sqlite-core/session.js"() {
38201
38509
  init_cache();
38202
38510
  init_entity();
38203
- init_errors3();
38511
+ init_errors4();
38204
38512
  init_query_promise();
38205
38513
  init_db();
38206
38514
  ExecuteResultSync = class extends QueryPromise {
@@ -38584,10 +38892,10 @@ var init_session2 = __esm({
38584
38892
  }
38585
38893
  };
38586
38894
  PreparedQuery = class extends SQLitePreparedQuery {
38587
- constructor(stmt, query, logger5, cache, queryMetadata, cacheConfig, fields, executeMethod, _isResponseInArrayMode, customResultMapper) {
38895
+ constructor(stmt, query, logger6, cache, queryMetadata, cacheConfig, fields, executeMethod, _isResponseInArrayMode, customResultMapper) {
38588
38896
  super("sync", executeMethod, query, cache, queryMetadata, cacheConfig);
38589
38897
  this.stmt = stmt;
38590
- this.logger = logger5;
38898
+ this.logger = logger6;
38591
38899
  this.fields = fields;
38592
38900
  this._isResponseInArrayMode = _isResponseInArrayMode;
38593
38901
  this.customResultMapper = customResultMapper;
@@ -38599,10 +38907,10 @@ var init_session2 = __esm({
38599
38907
  return this.stmt.run(...params);
38600
38908
  }
38601
38909
  all(placeholderValues) {
38602
- const { fields, joinsNotNullableMap, query, logger: logger5, stmt, customResultMapper } = this;
38910
+ const { fields, joinsNotNullableMap, query, logger: logger6, stmt, customResultMapper } = this;
38603
38911
  if (!fields && !customResultMapper) {
38604
38912
  const params = fillPlaceholders(query.params, placeholderValues ?? {});
38605
- logger5.logQuery(query.sql, params);
38913
+ logger6.logQuery(query.sql, params);
38606
38914
  return stmt.all(...params);
38607
38915
  }
38608
38916
  const rows = this.values(placeholderValues);
@@ -38644,11 +38952,11 @@ var init_session2 = __esm({
38644
38952
  import Client from "better-sqlite3";
38645
38953
  function construct(client, config = {}) {
38646
38954
  const dialect = new SQLiteSyncDialect({ casing: config.casing });
38647
- let logger5;
38955
+ let logger6;
38648
38956
  if (config.logger === true) {
38649
- logger5 = new DefaultLogger();
38957
+ logger6 = new DefaultLogger();
38650
38958
  } else if (config.logger !== false) {
38651
- logger5 = config.logger;
38959
+ logger6 = config.logger;
38652
38960
  }
38653
38961
  let schema;
38654
38962
  if (config.schema) {
@@ -38662,7 +38970,7 @@ function construct(client, config = {}) {
38662
38970
  tableNamesMap: tablesConfig.tableNamesMap
38663
38971
  };
38664
38972
  }
38665
- const session = new BetterSQLiteSession(client, dialect, schema, { logger: logger5 });
38973
+ const session = new BetterSQLiteSession(client, dialect, schema, { logger: logger6 });
38666
38974
  const db = new BetterSQLite3Database("sync", dialect, session, schema);
38667
38975
  db.$client = client;
38668
38976
  return db;
@@ -39247,16 +39555,23 @@ var init_schema2 = __esm({
39247
39555
  });
39248
39556
 
39249
39557
  // ../server/src/db/client.ts
39250
- import { mkdirSync as mkdirSync3 } from "node:fs";
39558
+ import { chmodSync as chmodSync2, mkdirSync as mkdirSync3 } from "node:fs";
39251
39559
  import { dirname, resolve as resolve2 } from "node:path";
39252
39560
  import Database from "better-sqlite3";
39253
39561
  function openSqliteDatabase(databasePath) {
39254
39562
  if (databasePath !== ":memory:") {
39255
- mkdirSync3(dirname(databasePath), { recursive: true });
39563
+ mkdirSync3(dirname(databasePath), { recursive: true, mode: 448 });
39256
39564
  }
39257
39565
  const sqlite = new Database(databasePath);
39258
39566
  sqlite.pragma("journal_mode = WAL");
39567
+ sqlite.pragma("busy_timeout = 5000");
39259
39568
  sqlite.pragma("foreign_keys = ON");
39569
+ if (databasePath !== ":memory:") {
39570
+ try {
39571
+ chmodSync2(databasePath, 384);
39572
+ } catch {
39573
+ }
39574
+ }
39260
39575
  const db = drizzle(sqlite, { schema: schema_exports });
39261
39576
  let migrated = false;
39262
39577
  return {
@@ -39298,7 +39613,7 @@ var init_drizzle_orm = __esm({
39298
39613
  init_column_builder();
39299
39614
  init_column();
39300
39615
  init_entity();
39301
- init_errors3();
39616
+ init_errors4();
39302
39617
  init_logger2();
39303
39618
  init_operations();
39304
39619
  init_query_promise();
@@ -42135,6 +42450,14 @@ var init_runtime_repository = __esm({
42135
42450
  const rows = conditions.length ? this.handle.db.select().from(runtimeRuns).where(and(...conditions)).orderBy(desc(runtimeRuns.createdAt)).limit(limit).offset(offset).all() : this.handle.db.select().from(runtimeRuns).orderBy(desc(runtimeRuns.createdAt)).limit(limit).offset(offset).all();
42136
42451
  return Promise.resolve(rows.map((row) => structuredClone(row.data)));
42137
42452
  }
42453
+ countRuns(filter = {}) {
42454
+ const conditions = [];
42455
+ if (filter.planId) conditions.push(eq(runtimeRuns.planId, filter.planId));
42456
+ if (filter.kind) conditions.push(eq(runtimeRuns.kind, filter.kind));
42457
+ if (filter.status) conditions.push(eq(runtimeRuns.status, filter.status));
42458
+ const row = conditions.length ? this.handle.db.select({ total: count() }).from(runtimeRuns).where(and(...conditions)).get() : this.handle.db.select({ total: count() }).from(runtimeRuns).get();
42459
+ return Promise.resolve(row?.total ?? 0);
42460
+ }
42138
42461
  updateRun(run2) {
42139
42462
  const result = this.handle.db.update(runtimeRuns).set({
42140
42463
  status: run2.status,
@@ -43071,7 +43394,11 @@ async function createLocalApplicationRuntime(databasePath, objects) {
43071
43394
  scheduler,
43072
43395
  background,
43073
43396
  objects,
43074
- chatbots
43397
+ chatbots,
43398
+ close() {
43399
+ scheduler.stop();
43400
+ database.close();
43401
+ }
43075
43402
  };
43076
43403
  await recoverBackgroundJobs({
43077
43404
  jobs,
@@ -43452,16 +43779,6 @@ var init_deps = __esm({
43452
43779
  }
43453
43780
  });
43454
43781
 
43455
- // ../server/src/shared/logging.ts
43456
- var init_logging = __esm({
43457
- "../server/src/shared/logging.ts"() {
43458
- "use strict";
43459
- init_configure_logger_observability();
43460
- init_logger_context();
43461
- init_logger();
43462
- }
43463
- });
43464
-
43465
43782
  // ../server/src/http/middleware/errors.ts
43466
43783
  function jsonValidator(result, c2) {
43467
43784
  if (result.success) return void 0;
@@ -43480,8 +43797,8 @@ function jsonValidator(result, c2) {
43480
43797
  function unauthorizedResponse(c2) {
43481
43798
  return c2.json({ error: "\u672A\u6388\u6743\u7684\u8BBF\u95EE" }, 401);
43482
43799
  }
43483
- var logger, HttpError, errorMapper;
43484
- var init_errors4 = __esm({
43800
+ var logger2, HttpError, errorMapper;
43801
+ var init_errors5 = __esm({
43485
43802
  "../server/src/http/middleware/errors.ts"() {
43486
43803
  "use strict";
43487
43804
  init_http_exception();
@@ -43489,7 +43806,7 @@ var init_errors4 = __esm({
43489
43806
  init_connectors2();
43490
43807
  init_workspace3();
43491
43808
  init_zod();
43492
- logger = new Logger("http");
43809
+ logger2 = new Logger("http");
43493
43810
  HttpError = class extends Error {
43494
43811
  constructor(message, status = 400) {
43495
43812
  super(message);
@@ -43525,7 +43842,7 @@ var init_errors4 = __esm({
43525
43842
  error.kind === "configuration" || error.kind === "invalid_request" ? 400 : 502
43526
43843
  );
43527
43844
  }
43528
- logger.error("\u672A\u6355\u83B7\u7684\u8DEF\u7531\u5F02\u5E38:", error);
43845
+ logger2.error("\u672A\u6355\u83B7\u7684\u8DEF\u7531\u5F02\u5E38:", error);
43529
43846
  const message = error instanceof Error ? error.message : String(error);
43530
43847
  return c2.json(
43531
43848
  {
@@ -43539,21 +43856,18 @@ var init_errors4 = __esm({
43539
43856
  });
43540
43857
 
43541
43858
  // ../server/src/http/middleware/auth.ts
43542
- import { timingSafeEqual } from "node:crypto";
43859
+ import { createHash as createHash2, timingSafeEqual } from "node:crypto";
43543
43860
  function safeEqual(a, b2) {
43544
- if (a.length !== b2.length) {
43545
- const padded = b2 + "\0".repeat(Math.max(0, a.length - b2.length));
43546
- timingSafeEqual(Buffer.from(a), Buffer.from(padded.slice(0, a.length)));
43547
- return false;
43548
- }
43549
- return timingSafeEqual(Buffer.from(a), Buffer.from(b2));
43861
+ const left = createHash2("sha256").update(a, "utf8").digest();
43862
+ const right = createHash2("sha256").update(b2, "utf8").digest();
43863
+ return timingSafeEqual(left, right);
43550
43864
  }
43551
43865
  var requireBearer;
43552
43866
  var init_auth = __esm({
43553
43867
  "../server/src/http/middleware/auth.ts"() {
43554
43868
  "use strict";
43555
43869
  init_deps();
43556
- init_errors4();
43870
+ init_errors5();
43557
43871
  requireBearer = factory.createMiddleware(async (c2, next) => {
43558
43872
  if (!c2.req.path.startsWith("/api/")) {
43559
43873
  return next();
@@ -43579,13 +43893,13 @@ var init_auth = __esm({
43579
43893
  function cryptoRandomId() {
43580
43894
  return `req-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
43581
43895
  }
43582
- var logger2, requestContext;
43896
+ var logger3, requestContext;
43583
43897
  var init_logger3 = __esm({
43584
43898
  "../server/src/http/middleware/logger.ts"() {
43585
43899
  "use strict";
43586
43900
  init_deps();
43587
43901
  init_logging();
43588
- logger2 = new Logger("http-request");
43902
+ logger3 = new Logger("http-request");
43589
43903
  requestContext = factory.createMiddleware(async (c2, next) => {
43590
43904
  const requestId = c2.req.header("X-Request-Id") ?? cryptoRandomId();
43591
43905
  c2.set("requestId", requestId);
@@ -43598,7 +43912,7 @@ var init_logger3 = __esm({
43598
43912
  } finally {
43599
43913
  const status = c2.res.status;
43600
43914
  const ms = Date.now() - start;
43601
- logger2.info(`${method} ${path7} -> ${status} (${ms}ms) requestId=${requestId}`);
43915
+ logger3.info(`${method} ${path7} -> ${status} (${ms}ms) requestId=${requestId}`);
43602
43916
  }
43603
43917
  });
43604
43918
  }
@@ -43812,7 +44126,7 @@ var init_helpers = __esm({
43812
44126
  "../server/src/http/routes/helpers.ts"() {
43813
44127
  "use strict";
43814
44128
  init_workspace3();
43815
- init_errors4();
44129
+ init_errors5();
43816
44130
  }
43817
44131
  });
43818
44132
 
@@ -43838,7 +44152,7 @@ var init_automations = __esm({
43838
44152
  init_automation();
43839
44153
  init_workspace3();
43840
44154
  init_deps();
43841
- init_errors4();
44155
+ init_errors5();
43842
44156
  init_helpers();
43843
44157
  listAutomations = factory.createHandlers(async (c2) => {
43844
44158
  const { page, pageSize } = parsePage(c2.req.queries());
@@ -43890,6 +44204,235 @@ var init_automations = __esm({
43890
44204
  }
43891
44205
  });
43892
44206
 
44207
+ // ../server/src/relay/entitlement-sync.ts
44208
+ async function refreshEntitlementCredential(issuer, credential, fetchImpl = fetch, nowMs = Date.now(), forceRefresh = false) {
44209
+ const expiresMs = Date.parse(credential.expiresAt);
44210
+ if (!forceRefresh && Number.isFinite(expiresMs) && expiresMs - nowMs > REFRESH_THRESHOLD_MS) {
44211
+ return credential;
44212
+ }
44213
+ if (!credential.refreshToken) return credential;
44214
+ const tokens = await refreshTokens({ issuer, refreshToken: credential.refreshToken }, fetchImpl);
44215
+ const entitlement = await fetchEntitlement(
44216
+ { issuer, accessToken: tokens.access_token },
44217
+ fetchImpl
44218
+ );
44219
+ return {
44220
+ token: entitlement.token,
44221
+ refreshToken: tokens.refresh_token ?? credential.refreshToken,
44222
+ expiresAt: entitlement.expires_at,
44223
+ product: entitlement.product,
44224
+ plan: entitlement.plan,
44225
+ status: entitlement.status,
44226
+ periodEnd: entitlement.period_end,
44227
+ trialEnd: entitlement.trial_end
44228
+ };
44229
+ }
44230
+ async function syncRelayConnections(connections2, token) {
44231
+ const all = await connections2.list();
44232
+ let updated = 0;
44233
+ for (const connection of all.filter((item) => item.connectorId === WEIXIN_RELAY_CONNECTOR)) {
44234
+ await connections2.save({
44235
+ id: connection.id,
44236
+ revision: connection.revision,
44237
+ connectorId: connection.connectorId,
44238
+ name: connection.name,
44239
+ enabled: connection.enabled,
44240
+ settings: connection.settings,
44241
+ credentials: { relayToken: token },
44242
+ metadata: connection.metadata
44243
+ });
44244
+ updated += 1;
44245
+ }
44246
+ return updated;
44247
+ }
44248
+ async function runEntitlementSync(options2) {
44249
+ const credential = readRelayCredential();
44250
+ if (!credential) return null;
44251
+ const refreshed = await refreshEntitlementCredential(
44252
+ options2.issuer,
44253
+ credential,
44254
+ options2.fetchImpl,
44255
+ options2.nowMs,
44256
+ options2.forceRefresh
44257
+ );
44258
+ const didRefresh = refreshed.token !== credential.token || refreshed.plan !== credential.plan || refreshed.status !== credential.status || refreshed.expiresAt !== credential.expiresAt;
44259
+ if (didRefresh) writeRelayCredential(refreshed);
44260
+ const synced = await syncRelayConnections(options2.connections, refreshed.token);
44261
+ return { refreshed: didRefresh, synced };
44262
+ }
44263
+ function startEntitlementSync(connections2, intervalMs = 6 * 60 * 60 * 1e3) {
44264
+ const configuredIssuer = process.env.TRENDPUBLISH_BECOMEOPC_ISSUER?.trim();
44265
+ const issuer = configuredIssuer || (readRelayCredential() ? DEFAULT_ISSUER : "");
44266
+ if (!issuer) return () => void 0;
44267
+ const sync = () => {
44268
+ void runEntitlementSync({ issuer, connections: connections2 }).catch((error) => {
44269
+ logger4.warn("entitlement \u540C\u6B65\u5931\u8D25:", error instanceof Error ? error.message : String(error));
44270
+ });
44271
+ };
44272
+ sync();
44273
+ const timer = setInterval(sync, intervalMs);
44274
+ timer.unref?.();
44275
+ return () => clearInterval(timer);
44276
+ }
44277
+ var logger4, REFRESH_THRESHOLD_MS, WEIXIN_RELAY_CONNECTOR;
44278
+ var init_entitlement_sync = __esm({
44279
+ "../server/src/relay/entitlement-sync.ts"() {
44280
+ "use strict";
44281
+ init_logging();
44282
+ init_credential();
44283
+ init_oauth();
44284
+ logger4 = new Logger("relay-entitlement");
44285
+ REFRESH_THRESHOLD_MS = 24 * 60 * 60 * 1e3;
44286
+ WEIXIN_RELAY_CONNECTOR = "weixin-relay";
44287
+ }
44288
+ });
44289
+
44290
+ // ../server/src/http/routes/becomeopc.ts
44291
+ function resolveIssuer() {
44292
+ return process.env.TRENDPUBLISH_BECOMEOPC_ISSUER?.trim() || DEFAULT_ISSUER;
44293
+ }
44294
+ function isLoopbackCliOrigin(requestUrl) {
44295
+ try {
44296
+ const parsed = new URL(requestUrl);
44297
+ const isLoopback = parsed.hostname === "127.0.0.1" || parsed.hostname === "localhost";
44298
+ const port = parsed.port || (parsed.protocol === "https:" ? "443" : "80");
44299
+ if (isLoopback && Number(port) === CLI_PORT) return true;
44300
+ } catch {
44301
+ }
44302
+ return Number(process.env.PORT) === CLI_PORT;
44303
+ }
44304
+ async function buildStatusPayload(deps, requestUrl) {
44305
+ const issuer = resolveIssuer();
44306
+ const urls = resolveBecomeOpcUrls(issuer);
44307
+ const managedRelayUrl = resolveManagedRelayUrl();
44308
+ const runtime = await deps.getRuntime();
44309
+ const connections2 = await runtime.connectionManager.list();
44310
+ const syncedRelayCount = connections2.filter(
44311
+ (item) => item.connectorId === WEIXIN_RELAY_CONNECTOR2
44312
+ ).length;
44313
+ const credential = readRelayCredential();
44314
+ const summary = credential ? inspectRelayCredential(credential) : null;
44315
+ return {
44316
+ connected: Boolean(summary),
44317
+ entitled: summary?.entitled ?? false,
44318
+ expired: summary?.expired ?? false,
44319
+ hasRefreshToken: summary?.hasRefreshToken ?? false,
44320
+ product: summary?.product ?? RELAY_PRODUCT,
44321
+ plan: summary?.plan ?? null,
44322
+ status: summary?.status ?? null,
44323
+ expiresAt: summary?.expiresAt ?? null,
44324
+ periodEnd: summary?.periodEnd ?? null,
44325
+ trialEnd: summary?.trialEnd ?? null,
44326
+ syncedRelayCount,
44327
+ canBrowserLogin: isLoopbackCliOrigin(requestUrl),
44328
+ managedRelayUrl,
44329
+ urls
44330
+ };
44331
+ }
44332
+ function createBecomeOpcRoutes(oauthHub, fetchImpl = fetch) {
44333
+ const getStatus = factory.createHandlers(async (c2) => {
44334
+ return c2.json(await buildStatusPayload(c2.var.deps, c2.req.url));
44335
+ });
44336
+ const sync = factory.createHandlers(async (c2) => {
44337
+ const runtime = await c2.var.deps.getRuntime();
44338
+ const issuer = resolveIssuer();
44339
+ try {
44340
+ const result = await runEntitlementSync({
44341
+ issuer,
44342
+ connections: runtime.connectionManager,
44343
+ fetchImpl,
44344
+ forceRefresh: true
44345
+ });
44346
+ const subscription = await buildStatusPayload(c2.var.deps, c2.req.url);
44347
+ if (!result) {
44348
+ return c2.json(
44349
+ {
44350
+ ok: false,
44351
+ error: "\u5C1A\u672A\u8FDE\u63A5 BecomeOPC \u8BA2\u9605\u51ED\u8BC1",
44352
+ refreshed: false,
44353
+ synced: 0,
44354
+ subscription
44355
+ },
44356
+ 404
44357
+ );
44358
+ }
44359
+ return c2.json({
44360
+ ok: true,
44361
+ refreshed: result.refreshed,
44362
+ synced: result.synced,
44363
+ subscription
44364
+ });
44365
+ } catch (error) {
44366
+ if (error instanceof NotEntitledError) {
44367
+ return c2.json(
44368
+ {
44369
+ ok: false,
44370
+ code: "not_entitled",
44371
+ error: error.message,
44372
+ subscription: await buildStatusPayload(c2.var.deps, c2.req.url)
44373
+ },
44374
+ 402
44375
+ );
44376
+ }
44377
+ throw error;
44378
+ }
44379
+ });
44380
+ const disconnect = factory.createHandlers(async (c2) => {
44381
+ const cleared = clearRelayCredential();
44382
+ return c2.json({
44383
+ ok: true,
44384
+ cleared,
44385
+ subscription: await buildStatusPayload(c2.var.deps, c2.req.url)
44386
+ });
44387
+ });
44388
+ const startOAuth = factory.createHandlers((c2) => {
44389
+ if (!isLoopbackCliOrigin(c2.req.url)) {
44390
+ return c2.json(
44391
+ {
44392
+ error: `\u6D4F\u89C8\u5668\u76F4\u8FDE BecomeOPC \u4EC5\u652F\u6301\u672C\u5730 CLI \u7AEF\u53E3\uFF08127.0.0.1:${CLI_PORT}\uFF09\uFF1B\u5F53\u524D\u90E8\u7F72\u8BF7\u4F7F\u7528 CLI \u8FD0\u884C trendpublish login \u6216\u76F4\u63A5\u524D\u5F80 BecomeOPC \u7F51\u7AD9\u7BA1\u7406\u8BA2\u9605\u3002`
44393
+ },
44394
+ 400
44395
+ );
44396
+ }
44397
+ const issuer = resolveIssuer();
44398
+ const redirectUri = `http://127.0.0.1:${CLI_PORT}/callback`;
44399
+ const pkce = createPkce();
44400
+ const state = createState();
44401
+ const authorizeUrl = buildAuthorizeUrl({
44402
+ issuer,
44403
+ redirectUri,
44404
+ challenge: pkce.challenge,
44405
+ state
44406
+ });
44407
+ oauthHub.registerDashboardSession({
44408
+ state,
44409
+ verifier: pkce.verifier,
44410
+ redirectUri,
44411
+ issuer
44412
+ });
44413
+ return c2.json({ state, authorizeUrl });
44414
+ });
44415
+ const getOAuthStatus = factory.createHandlers((c2) => {
44416
+ const state = c2.req.query("state")?.trim() ?? "";
44417
+ if (!state) return c2.json({ error: "state \u5FC5\u586B" }, 400);
44418
+ return c2.json(oauthHub.getDashboardSession(state));
44419
+ });
44420
+ return new Hono3().get("/api/becomeopc/status", ...getStatus).post("/api/becomeopc/sync", ...sync).delete("/api/becomeopc/connection", ...disconnect).post("/api/becomeopc/oauth/start", ...startOAuth).get("/api/becomeopc/oauth/status", ...getOAuthStatus);
44421
+ }
44422
+ var WEIXIN_RELAY_CONNECTOR2;
44423
+ var init_becomeopc = __esm({
44424
+ "../server/src/http/routes/becomeopc.ts"() {
44425
+ "use strict";
44426
+ init_dist();
44427
+ init_deps();
44428
+ init_state();
44429
+ init_credential();
44430
+ init_entitlement_sync();
44431
+ init_oauth();
44432
+ WEIXIN_RELAY_CONNECTOR2 = "weixin-relay";
44433
+ }
44434
+ });
44435
+
43893
44436
  // ../../node_modules/.pnpm/hono@4.13.23/node_modules/hono/dist/utils/stream.js
43894
44437
  var StreamingApi;
43895
44438
  var init_stream = __esm({
@@ -44134,7 +44677,7 @@ var init_chatbots = __esm({
44134
44677
  init_dist3();
44135
44678
  init_src();
44136
44679
  init_deps();
44137
- init_errors4();
44680
+ init_errors5();
44138
44681
  init_sse2();
44139
44682
  profileParam = chatProfileParamSchema;
44140
44683
  sessionParam = chatSessionParamSchema;
@@ -44444,6 +44987,313 @@ var init_chatbots = __esm({
44444
44987
  }
44445
44988
  });
44446
44989
 
44990
+ // ../server/src/http/routes/cli-oauth.ts
44991
+ function escapeHtml3(text2) {
44992
+ return text2.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll('"', "&quot;").replaceAll("'", "&#39;");
44993
+ }
44994
+ function renderCallbackPage(options2) {
44995
+ const ctaHtml = options2.cta ? `<p style="margin-top:20px"><a href="${escapeHtml3(options2.cta.href)}" style="display:inline-block;padding:10px 18px;border-radius:8px;background:#1d1b18;color:#fff;text-decoration:none;font-weight:500">${escapeHtml3(options2.cta.label)}</a></p>` : "";
44996
+ const scriptHtml = options2.autoClose ? `<script>setTimeout(function(){try{window.close();}catch(e){}},1200);</script>` : "";
44997
+ return `<!doctype html>
44998
+ <html lang="zh-CN">
44999
+ <head>
45000
+ <meta charset="utf-8" />
45001
+ <meta name="viewport" content="width=device-width,initial-scale=1" />
45002
+ <title>${escapeHtml3(options2.title)} \xB7 TrendPublish</title>
45003
+ </head>
45004
+ <body style="margin:0;min-height:100vh;display:grid;place-items:center;background:#f7f5f0;color:#1d1b18;font-family:-apple-system,BlinkMacSystemFont,'PingFang SC','Segoe UI',sans-serif;padding:24px">
45005
+ <main style="max-width:420px;width:100%;background:#fff;border:1px solid #e6e0d6;border-radius:14px;padding:28px;box-shadow:0 8px 24px rgba(29,27,24,0.06);text-align:center">
45006
+ <h2 style="margin:0 0 10px;font-size:18px;font-weight:600">${escapeHtml3(options2.title)}</h2>
45007
+ <p style="margin:0;font-size:14px;line-height:1.6;color:#5c564e">${escapeHtml3(options2.message)}</p>
45008
+ ${ctaHtml}
45009
+ </main>
45010
+ ${scriptHtml}
45011
+ </body>
45012
+ </html>`;
45013
+ }
45014
+ function createCliOAuthRoutes(fetchImpl = fetch) {
45015
+ const pending = /* @__PURE__ */ new Map();
45016
+ const dashboardSessions = /* @__PURE__ */ new Map();
45017
+ function clearWaiter(state) {
45018
+ const entry = pending.get(state);
45019
+ if (!entry) return;
45020
+ clearTimeout(entry.timer);
45021
+ pending.delete(state);
45022
+ }
45023
+ function clearDashboardSession(state) {
45024
+ const entry = dashboardSessions.get(state);
45025
+ if (!entry) return;
45026
+ clearTimeout(entry.timer);
45027
+ dashboardSessions.delete(state);
45028
+ }
45029
+ function scheduleDashboardCleanup(state, delayMs) {
45030
+ const entry = dashboardSessions.get(state);
45031
+ if (!entry) return;
45032
+ clearTimeout(entry.timer);
45033
+ entry.timer = setTimeout(() => {
45034
+ dashboardSessions.delete(state);
45035
+ }, delayMs);
45036
+ entry.timer.unref?.();
45037
+ }
45038
+ function settle(state, outcome) {
45039
+ const entry = pending.get(state);
45040
+ if (!entry) return false;
45041
+ entry.outcome = outcome;
45042
+ if (entry.resolve) {
45043
+ const resolve3 = entry.resolve;
45044
+ clearWaiter(state);
45045
+ resolve3(outcome);
45046
+ }
45047
+ return true;
45048
+ }
45049
+ const hub = {
45050
+ registerDashboardSession(input) {
45051
+ clearDashboardSession(input.state);
45052
+ const timeoutMs = Math.min(
45053
+ Math.max(1e3, input.timeoutMs ?? MAX_TIMEOUT_MS),
45054
+ MAX_TIMEOUT_MS
45055
+ );
45056
+ const timer = setTimeout(() => {
45057
+ dashboardSessions.delete(input.state);
45058
+ }, timeoutMs);
45059
+ timer.unref?.();
45060
+ dashboardSessions.set(input.state, {
45061
+ status: "pending",
45062
+ verifier: input.verifier,
45063
+ redirectUri: input.redirectUri,
45064
+ issuer: input.issuer,
45065
+ timer
45066
+ });
45067
+ },
45068
+ getDashboardSession(state) {
45069
+ const entry = dashboardSessions.get(state);
45070
+ if (!entry) {
45071
+ return { status: "expired", error: "\u767B\u5F55\u4F1A\u8BDD\u5DF2\u8FC7\u671F\uFF0C\u8BF7\u91CD\u65B0\u53D1\u8D77\u8FDE\u63A5" };
45072
+ }
45073
+ return {
45074
+ status: entry.status,
45075
+ error: entry.error,
45076
+ synced: entry.synced
45077
+ };
45078
+ }
45079
+ };
45080
+ const register = factory.createHandlers(async (c2) => {
45081
+ const body = await c2.req.json().catch(() => ({}));
45082
+ const state = typeof body.state === "string" ? body.state.trim() : "";
45083
+ if (!state) return c2.json({ error: "state \u5FC5\u586B" }, 400);
45084
+ const rawTimeout = typeof body.timeoutMs === "number" ? body.timeoutMs : DEFAULT_TIMEOUT_MS;
45085
+ const timeoutMs = Math.min(Math.max(1e3, rawTimeout), MAX_TIMEOUT_MS);
45086
+ clearWaiter(state);
45087
+ const timer = setTimeout(() => {
45088
+ settle(state, { error: "\u767B\u5F55\u8D85\u65F6\uFF08180 \u79D2\u672A\u6536\u5230\u56DE\u8C03\uFF09" });
45089
+ clearWaiter(state);
45090
+ }, timeoutMs);
45091
+ timer.unref?.();
45092
+ pending.set(state, { timer });
45093
+ return c2.json({ ok: true });
45094
+ });
45095
+ const wait = factory.createHandlers(async (c2) => {
45096
+ const state = c2.req.query("state")?.trim() ?? "";
45097
+ if (!state) return c2.json({ error: "state \u5FC5\u586B" }, 400);
45098
+ const entry = pending.get(state);
45099
+ if (!entry) return c2.json({ error: "\u767B\u5F55\u4F1A\u8BDD\u4E0D\u5B58\u5728\u6216\u5DF2\u8FC7\u671F" }, 404);
45100
+ let outcome = entry.outcome;
45101
+ if (!outcome) {
45102
+ outcome = await new Promise((resolve3) => {
45103
+ entry.resolve = resolve3;
45104
+ c2.req.raw.signal.addEventListener(
45105
+ "abort",
45106
+ () => {
45107
+ clearWaiter(state);
45108
+ resolve3({ error: "\u5BA2\u6237\u7AEF\u5DF2\u53D6\u6D88\u7B49\u5F85" });
45109
+ },
45110
+ { once: true }
45111
+ );
45112
+ });
45113
+ } else {
45114
+ clearWaiter(state);
45115
+ }
45116
+ if (outcome.error) {
45117
+ const status = outcome.error.includes("\u8D85\u65F6") ? 408 : 400;
45118
+ return c2.json({ error: outcome.error }, status);
45119
+ }
45120
+ return c2.json({ code: outcome.code });
45121
+ });
45122
+ const relaySync = factory.createHandlers(async (c2) => {
45123
+ const runtime = await c2.var.deps.getRuntime();
45124
+ const issuer = process.env.TRENDPUBLISH_BECOMEOPC_ISSUER?.trim() || DEFAULT_ISSUER;
45125
+ const result = await runEntitlementSync({
45126
+ issuer,
45127
+ connections: runtime.connectionManager,
45128
+ fetchImpl
45129
+ });
45130
+ return c2.json({ ok: true, result });
45131
+ });
45132
+ const callback = factory.createHandlers(async (c2) => {
45133
+ const state = c2.req.query("state")?.trim() ?? "";
45134
+ const code = c2.req.query("code")?.trim() ?? "";
45135
+ const oauthError = c2.req.query("error")?.trim() ?? "";
45136
+ if (state && pending.has(state)) {
45137
+ if (oauthError) {
45138
+ settle(state, { error: `OAuth \u9519\u8BEF\uFF1A${oauthError}` });
45139
+ return c2.html(
45140
+ renderCallbackPage({
45141
+ title: "\u767B\u5F55\u5931\u8D25",
45142
+ message: `OAuth \u9519\u8BEF\uFF1A${oauthError}\uFF0C\u53EF\u5173\u95ED\u6B64\u9875\u9762\u3002`
45143
+ }),
45144
+ 400
45145
+ );
45146
+ }
45147
+ if (!code) {
45148
+ settle(state, { error: "OAuth \u56DE\u8C03\u7F3A\u5C11 code" });
45149
+ return c2.html(
45150
+ renderCallbackPage({
45151
+ title: "\u767B\u5F55\u56DE\u8C03\u65E0\u6548",
45152
+ message: "\u56DE\u8C03\u7F3A\u5C11\u6388\u6743\u7801\uFF0C\u53EF\u5173\u95ED\u6B64\u9875\u9762\u91CD\u8BD5\u3002"
45153
+ }),
45154
+ 400
45155
+ );
45156
+ }
45157
+ settle(state, { code });
45158
+ return c2.html(
45159
+ renderCallbackPage({
45160
+ title: "\u767B\u5F55\u6210\u529F",
45161
+ message: "\u53EF\u5173\u95ED\u6B64\u9875\u9762\u8FD4\u56DE TrendPublish\u3002",
45162
+ autoClose: true
45163
+ }),
45164
+ 200
45165
+ );
45166
+ }
45167
+ const dashboardSession = state ? dashboardSessions.get(state) : void 0;
45168
+ if (dashboardSession) {
45169
+ if (dashboardSession.status !== "pending") {
45170
+ return c2.html(
45171
+ renderCallbackPage({
45172
+ title: "\u767B\u5F55\u5DF2\u5904\u7406",
45173
+ message: "\u8BF7\u8FD4\u56DE TrendPublish \u5DE5\u4F5C\u53F0\u67E5\u770B\u72B6\u6001\u3002",
45174
+ autoClose: true
45175
+ }),
45176
+ 200
45177
+ );
45178
+ }
45179
+ if (oauthError) {
45180
+ dashboardSession.status = "error";
45181
+ dashboardSession.error = `OAuth \u9519\u8BEF\uFF1A${oauthError}`;
45182
+ scheduleDashboardCleanup(state, COMPLETED_RETENTION_MS);
45183
+ return c2.html(
45184
+ renderCallbackPage({
45185
+ title: "\u767B\u5F55\u5DF2\u53D6\u6D88\u6216\u5931\u8D25",
45186
+ message: dashboardSession.error
45187
+ }),
45188
+ 400
45189
+ );
45190
+ }
45191
+ if (!code) {
45192
+ dashboardSession.status = "error";
45193
+ dashboardSession.error = "OAuth \u56DE\u8C03\u7F3A\u5C11 code";
45194
+ scheduleDashboardCleanup(state, COMPLETED_RETENTION_MS);
45195
+ return c2.html(
45196
+ renderCallbackPage({
45197
+ title: "\u767B\u5F55\u56DE\u8C03\u65E0\u6548",
45198
+ message: "\u56DE\u8C03\u7F3A\u5C11\u6388\u6743\u7801\uFF0C\u8BF7\u8FD4\u56DE\u5DE5\u4F5C\u53F0\u91CD\u8BD5\u3002"
45199
+ }),
45200
+ 400
45201
+ );
45202
+ }
45203
+ try {
45204
+ const tokens = await exchangeCode(
45205
+ {
45206
+ issuer: dashboardSession.issuer,
45207
+ redirectUri: dashboardSession.redirectUri,
45208
+ code,
45209
+ verifier: dashboardSession.verifier
45210
+ },
45211
+ fetchImpl
45212
+ );
45213
+ const entitlement = await fetchEntitlement(
45214
+ {
45215
+ issuer: dashboardSession.issuer,
45216
+ accessToken: tokens.access_token
45217
+ },
45218
+ fetchImpl
45219
+ );
45220
+ writeRelayCredential({
45221
+ token: entitlement.token,
45222
+ refreshToken: tokens.refresh_token,
45223
+ expiresAt: entitlement.expires_at,
45224
+ product: entitlement.product,
45225
+ plan: entitlement.plan,
45226
+ status: entitlement.status,
45227
+ periodEnd: entitlement.period_end,
45228
+ trialEnd: entitlement.trial_end
45229
+ });
45230
+ const runtime = await c2.var.deps.getRuntime();
45231
+ const synced = await syncRelayConnections(runtime.connectionManager, entitlement.token);
45232
+ dashboardSession.status = "completed";
45233
+ dashboardSession.synced = synced;
45234
+ scheduleDashboardCleanup(state, COMPLETED_RETENTION_MS);
45235
+ return c2.html(
45236
+ renderCallbackPage({
45237
+ title: "BecomeOPC \u8BA2\u9605\u5DF2\u8FDE\u63A5",
45238
+ message: "\u51ED\u8BC1\u5DF2\u81EA\u52A8\u540C\u6B65\u5230 TrendPublish \u5DE5\u4F5C\u53F0\uFF0C\u6B64\u9875\u9762\u5C06\u81EA\u52A8\u5173\u95ED\u3002",
45239
+ autoClose: true
45240
+ }),
45241
+ 200
45242
+ );
45243
+ } catch (error) {
45244
+ if (error instanceof NotEntitledError) {
45245
+ dashboardSession.status = "not_entitled";
45246
+ dashboardSession.error = error.message;
45247
+ scheduleDashboardCleanup(state, COMPLETED_RETENTION_MS);
45248
+ const urls = resolveBecomeOpcUrls(dashboardSession.issuer);
45249
+ return c2.html(
45250
+ renderCallbackPage({
45251
+ title: "\u5C1A\u672A\u8BA2\u9605 TrendPublish",
45252
+ message: "\u4F60\u5DF2\u767B\u5F55 BecomeOPC\uFF0C\u4F46\u5F53\u524D\u8D26\u6237\u5C1A\u672A\u5F00\u901A TrendPublish \u8BA2\u9605\u6216\u8BD5\u7528\u3002",
45253
+ cta: { label: "\u524D\u5F80 BecomeOPC \u8BA2\u9605 / \u5F00\u59CB\u8BD5\u7528", href: urls.subscribe }
45254
+ }),
45255
+ 200
45256
+ );
45257
+ }
45258
+ dashboardSession.status = "error";
45259
+ dashboardSession.error = error instanceof Error ? error.message : String(error);
45260
+ scheduleDashboardCleanup(state, COMPLETED_RETENTION_MS);
45261
+ return c2.html(
45262
+ renderCallbackPage({
45263
+ title: "\u8FDE\u63A5 BecomeOPC \u5931\u8D25",
45264
+ message: dashboardSession.error
45265
+ }),
45266
+ 400
45267
+ );
45268
+ }
45269
+ }
45270
+ return c2.html(
45271
+ renderCallbackPage({
45272
+ title: "\u767B\u5F55\u4F1A\u8BDD\u5DF2\u8FC7\u671F",
45273
+ message: "state \u4E0D\u5339\u914D\u6216\u767B\u5F55\u4F1A\u8BDD\u5DF2\u8FC7\u671F\uFF0C\u53EF\u5173\u95ED\u6B64\u9875\u9762\u3002"
45274
+ }),
45275
+ 400
45276
+ );
45277
+ });
45278
+ const apiRoutes = new Hono3().post("/api/cli/oauth-callback/register", ...register).get("/api/cli/oauth-callback/wait", ...wait).post("/api/cli/relay-sync", ...relaySync);
45279
+ const callbackRoute = new Hono3().get("/callback", ...callback);
45280
+ return { apiRoutes, callbackRoute, hub };
45281
+ }
45282
+ var DEFAULT_TIMEOUT_MS, MAX_TIMEOUT_MS, COMPLETED_RETENTION_MS;
45283
+ var init_cli_oauth = __esm({
45284
+ "../server/src/http/routes/cli-oauth.ts"() {
45285
+ "use strict";
45286
+ init_dist();
45287
+ init_deps();
45288
+ init_credential();
45289
+ init_entitlement_sync();
45290
+ init_oauth();
45291
+ DEFAULT_TIMEOUT_MS = 18e4;
45292
+ MAX_TIMEOUT_MS = 3e5;
45293
+ COMPLETED_RETENTION_MS = 12e4;
45294
+ }
45295
+ });
45296
+
44447
45297
  // ../server/src/http/routes/connections.ts
44448
45298
  var list, create, update, remove, test, connectionRoutes;
44449
45299
  var init_connections = __esm({
@@ -44453,7 +45303,7 @@ var init_connections = __esm({
44453
45303
  init_src();
44454
45304
  init_dist3();
44455
45305
  init_deps();
44456
- init_errors4();
45306
+ init_errors5();
44457
45307
  init_helpers();
44458
45308
  list = factory.createHandlers(async (c2) => {
44459
45309
  const runtime = await c2.var.deps.getRuntime();
@@ -44669,7 +45519,7 @@ var init_content_config = __esm({
44669
45519
  init_publishing2();
44670
45520
  init_workspace3();
44671
45521
  init_deps();
44672
- init_errors4();
45522
+ init_errors5();
44673
45523
  init_helpers();
44674
45524
  listIdentities = factory.createHandlers(async (c2) => {
44675
45525
  const { page, pageSize } = parsePage(c2.req.queries());
@@ -44924,7 +45774,7 @@ var init_executions = __esm({
44924
45774
  init_runtime2();
44925
45775
  init_automation();
44926
45776
  init_deps();
44927
- init_errors4();
45777
+ init_errors5();
44928
45778
  init_helpers();
44929
45779
  listJobs = factory.createHandlers(async (c2) => {
44930
45780
  const { page, pageSize } = parsePage(c2.req.queries());
@@ -45271,6 +46121,20 @@ var init_health = __esm({
45271
46121
  });
45272
46122
 
45273
46123
  // ../server/src/http/routes/publishing-config.ts
46124
+ function normalizeRelayUrl(value) {
46125
+ return typeof value === "string" ? value.trim().replace(/\/+$/, "").toLowerCase() : "";
46126
+ }
46127
+ function withManagedRelayToken(connectorId, settings2, credentials) {
46128
+ if (connectorId !== "weixin-relay") return credentials;
46129
+ const providedToken = typeof credentials?.relayToken === "string" ? credentials.relayToken.trim() : "";
46130
+ if (providedToken) return credentials;
46131
+ if (normalizeRelayUrl(settings2.relayUrl) !== normalizeRelayUrl(resolveManagedRelayUrl())) {
46132
+ return credentials;
46133
+ }
46134
+ const stored = readRelayCredential();
46135
+ if (!stored || !inspectRelayCredential(stored).entitled) return credentials;
46136
+ return { ...credentials, relayToken: stored.token };
46137
+ }
45274
46138
  function formText(value) {
45275
46139
  return typeof value === "string" ? value.trim() : "";
45276
46140
  }
@@ -45405,9 +46269,11 @@ var init_publishing_config = __esm({
45405
46269
  init_connectors2();
45406
46270
  init_workspace3();
45407
46271
  init_publishing2();
46272
+ init_credential();
46273
+ init_oauth();
45408
46274
  init_storage();
45409
46275
  init_deps();
45410
- init_errors4();
46276
+ init_errors5();
45411
46277
  init_helpers();
45412
46278
  listAccounts = factory.createHandlers(async (c2) => {
45413
46279
  const runtime = await c2.var.deps.getRuntime();
@@ -45451,7 +46317,7 @@ var init_publishing_config = __esm({
45451
46317
  name: body.name,
45452
46318
  enabled: body.enabled,
45453
46319
  settings: body.settings,
45454
- credentials: body.credentials,
46320
+ credentials: withManagedRelayToken(body.connectorId, body.settings, body.credentials),
45455
46321
  clearCredentials: body.clearCredentials,
45456
46322
  metadata: managedMetadata(id)
45457
46323
  });
@@ -45502,7 +46368,7 @@ var init_publishing_config = __esm({
45502
46368
  name: body.name,
45503
46369
  enabled: body.enabled,
45504
46370
  settings: body.settings,
45505
- credentials: body.credentials,
46371
+ credentials: withManagedRelayToken(body.connectorId, body.settings, body.credentials),
45506
46372
  clearCredentials: body.clearCredentials,
45507
46373
  metadata: managedMetadata(id)
45508
46374
  });
@@ -45574,6 +46440,7 @@ var init_publishing_config = __esm({
45574
46440
  return c2.json({
45575
46441
  test: await runtime.connectionManager.check({
45576
46442
  ...body,
46443
+ credentials: withManagedRelayToken(body.connectorId, body.settings, body.credentials),
45577
46444
  id: connectionId,
45578
46445
  enabled: true
45579
46446
  })
@@ -45902,7 +46769,7 @@ var init_runs = __esm({
45902
46769
  init_article2();
45903
46770
  init_storage();
45904
46771
  init_deps();
45905
- init_errors4();
46772
+ init_errors5();
45906
46773
  init_helpers();
45907
46774
  init_sse2();
45908
46775
  runParam = external_exports.object({ runId: external_exports.string().min(1) });
@@ -45919,14 +46786,20 @@ var init_runs = __esm({
45919
46786
  listRuns = factory.createHandlers(async (c2) => {
45920
46787
  const { page, pageSize } = parsePage(c2.req.queries());
45921
46788
  const runtime = await c2.var.deps.getRuntime();
45922
- const all = await runtime.runs.store.listRuns(
45923
- {
45924
- planId: c2.req.query("planId") || void 0,
45925
- kind: runKind(c2.req.query("kind")),
45926
- status: runStatus(c2.req.query("status"))
45927
- },
45928
- 5e4
45929
- );
46789
+ const filter = {
46790
+ planId: c2.req.query("planId") || void 0,
46791
+ kind: runKind(c2.req.query("kind")),
46792
+ status: runStatus(c2.req.query("status"))
46793
+ };
46794
+ if (runtime.runs.store.countRuns) {
46795
+ const offset = (page - 1) * pageSize;
46796
+ const [items, total] = await Promise.all([
46797
+ runtime.runs.store.listRuns(filter, pageSize, offset),
46798
+ runtime.runs.store.countRuns(filter)
46799
+ ]);
46800
+ return c2.json({ items, page, pageSize, total });
46801
+ }
46802
+ const all = await runtime.runs.store.listRuns(filter, 5e4);
45930
46803
  return c2.json(paginate(all, page, pageSize));
45931
46804
  });
45932
46805
  getRun = factory.createHandlers(zValidator("param", runParam, jsonValidator), async (c2) => {
@@ -46156,15 +47029,16 @@ var init_runs = __esm({
46156
47029
  });
46157
47030
 
46158
47031
  // ../server/src/http/app.ts
46159
- function createApiRoutes() {
46160
- return new Hono3().route("/", healthRoutes).route("/", connectionRoutes).route("/", chatbotRoutes).route("/", contentConfigRoutes).route("/", publishingConfigRoutes).route("/", automationRoutes).route("/", executionRoutes).route("/", runRoutes);
47032
+ function createApiRoutes(oauthHub) {
47033
+ return new Hono3().route("/", healthRoutes).route("/", createBecomeOpcRoutes(oauthHub)).route("/", connectionRoutes).route("/", chatbotRoutes).route("/", contentConfigRoutes).route("/", publishingConfigRoutes).route("/", automationRoutes).route("/", executionRoutes).route("/", runRoutes);
46161
47034
  }
46162
47035
  function createHttpApp(deps) {
46163
47036
  const inject = factory.createMiddleware(async (c2, next) => {
46164
47037
  c2.set("deps", deps);
46165
47038
  return next();
46166
47039
  });
46167
- return new Hono3().use("*", requestContext).use("*", inject).use("/api/*", requireBearer).onError(errorMapper).route("/", deps.dashboardApp).route("/", createApiRoutes()).notFound(
47040
+ const cliOAuth = createCliOAuthRoutes();
47041
+ return new Hono3().use("*", requestContext).use("*", inject).use("/api/*", requireBearer).onError(errorMapper).route("/", deps.dashboardApp).route("/", cliOAuth.callbackRoute).route("/", cliOAuth.apiRoutes).route("/", createApiRoutes(cliOAuth.hub)).notFound(
46168
47042
  (c2) => c2.json({ error: "\u65E0\u6548\u7684 API \u8DEF\u5F84", data: { path: c2.req.path, method: c2.req.method } }, 404)
46169
47043
  );
46170
47044
  }
@@ -46174,10 +47048,12 @@ var init_app = __esm({
46174
47048
  init_dist();
46175
47049
  init_deps();
46176
47050
  init_auth();
46177
- init_errors4();
47051
+ init_errors5();
46178
47052
  init_logger3();
46179
47053
  init_automations();
47054
+ init_becomeopc();
46180
47055
  init_chatbots();
47056
+ init_cli_oauth();
46181
47057
  init_connections();
46182
47058
  init_content_config();
46183
47059
  init_executions();
@@ -46269,81 +47145,6 @@ var init_dashboard_assets = __esm({
46269
47145
  }
46270
47146
  });
46271
47147
 
46272
- // ../server/src/relay/entitlement-sync.ts
46273
- async function refreshEntitlementCredential(issuer, credential, fetchImpl = fetch, nowMs = Date.now()) {
46274
- const expiresMs = Date.parse(credential.expiresAt);
46275
- if (Number.isFinite(expiresMs) && expiresMs - nowMs > REFRESH_THRESHOLD_MS) return credential;
46276
- if (!credential.refreshToken) return credential;
46277
- const tokens = await refreshTokens({ issuer, refreshToken: credential.refreshToken }, fetchImpl);
46278
- const entitlement = await fetchEntitlement(
46279
- { issuer, accessToken: tokens.access_token },
46280
- fetchImpl
46281
- );
46282
- return {
46283
- token: entitlement.token,
46284
- refreshToken: tokens.refresh_token ?? credential.refreshToken,
46285
- expiresAt: entitlement.expires_at,
46286
- product: entitlement.product
46287
- };
46288
- }
46289
- async function syncRelayConnections(connections2, token) {
46290
- const all = await connections2.list();
46291
- let updated = 0;
46292
- for (const connection of all.filter((item) => item.connectorId === WEIXIN_RELAY_CONNECTOR)) {
46293
- await connections2.save({
46294
- id: connection.id,
46295
- revision: connection.revision,
46296
- connectorId: connection.connectorId,
46297
- name: connection.name,
46298
- enabled: connection.enabled,
46299
- settings: connection.settings,
46300
- credentials: { relayToken: token },
46301
- metadata: connection.metadata
46302
- });
46303
- updated += 1;
46304
- }
46305
- return updated;
46306
- }
46307
- async function runEntitlementSync(options2) {
46308
- const credential = readRelayCredential();
46309
- if (!credential) return null;
46310
- const refreshed = await refreshEntitlementCredential(
46311
- options2.issuer,
46312
- credential,
46313
- options2.fetchImpl,
46314
- options2.nowMs
46315
- );
46316
- const didRefresh = refreshed.token !== credential.token;
46317
- if (didRefresh) writeRelayCredential(refreshed);
46318
- const synced = await syncRelayConnections(options2.connections, refreshed.token);
46319
- return { refreshed: didRefresh, synced };
46320
- }
46321
- function startEntitlementSync(connections2, intervalMs = 6 * 60 * 60 * 1e3) {
46322
- const issuer = process.env.TRENDPUBLISH_BECOMEOPC_ISSUER?.trim();
46323
- if (!issuer) return () => void 0;
46324
- const sync = () => {
46325
- void runEntitlementSync({ issuer, connections: connections2 }).catch((error) => {
46326
- logger3.warn("entitlement \u540C\u6B65\u5931\u8D25:", error instanceof Error ? error.message : String(error));
46327
- });
46328
- };
46329
- sync();
46330
- const timer = setInterval(sync, intervalMs);
46331
- timer.unref?.();
46332
- return () => clearInterval(timer);
46333
- }
46334
- var logger3, REFRESH_THRESHOLD_MS, WEIXIN_RELAY_CONNECTOR;
46335
- var init_entitlement_sync = __esm({
46336
- "../server/src/relay/entitlement-sync.ts"() {
46337
- "use strict";
46338
- init_logging();
46339
- init_credential();
46340
- init_oauth();
46341
- logger3 = new Logger("relay-entitlement");
46342
- REFRESH_THRESHOLD_MS = 24 * 60 * 60 * 1e3;
46343
- WEIXIN_RELAY_CONNECTOR = "weixin-relay";
46344
- }
46345
- });
46346
-
46347
47148
  // ../server/src/server.ts
46348
47149
  var server_exports = {};
46349
47150
  __export(server_exports, {
@@ -46462,16 +47263,30 @@ async function startServer(port = 8e3) {
46462
47263
  const deps = buildLocalDeps();
46463
47264
  const runtime = await deps.getRuntime();
46464
47265
  runtime.scheduler.start();
46465
- startEntitlementSync(runtime.connectionManager);
47266
+ const stopEntitlementSync = startEntitlementSync(runtime.connectionManager);
46466
47267
  const app = createHttpApp(deps);
46467
- serveFetch({ port }, (req) => app.fetch(req));
46468
- logger4.info(`\u670D\u52A1\u76D1\u542C\u5728 http://0.0.0.0:${port}`);
46469
- logger4.info(`dashboard \u5730\u5740: http://localhost:${port}/dashboard`);
47268
+ const server = serveFetch({ port }, (req) => app.fetch(req));
47269
+ let shuttingDown = false;
47270
+ const shutdown = (signal) => {
47271
+ if (shuttingDown) return;
47272
+ shuttingDown = true;
47273
+ logger5.info(`\u6536\u5230 ${signal}\uFF0C\u6B63\u5728\u4F18\u96C5\u5173\u95ED\u670D\u52A1\u2026`);
47274
+ stopEntitlementSync();
47275
+ runtime.scheduler.stop();
47276
+ server.close(() => {
47277
+ runtime.close?.();
47278
+ process.exit(0);
47279
+ });
47280
+ };
47281
+ process.on("SIGINT", () => shutdown("SIGINT"));
47282
+ process.on("SIGTERM", () => shutdown("SIGTERM"));
47283
+ logger5.info(`\u670D\u52A1\u76D1\u542C\u5728 http://0.0.0.0:${port}`);
47284
+ logger5.info(`dashboard \u5730\u5740: http://localhost:${port}/dashboard`);
46470
47285
  if (process.env.TRENDPUBLISH_DASHBOARD_DEV_SERVER_URL) {
46471
- logger4.info(`dashboard \u5F00\u53D1\u4EE3\u7406: ${process.env.TRENDPUBLISH_DASHBOARD_DEV_SERVER_URL}`);
47286
+ logger5.info(`dashboard \u5F00\u53D1\u4EE3\u7406: ${process.env.TRENDPUBLISH_DASHBOARD_DEV_SERVER_URL}`);
46472
47287
  }
46473
47288
  }
46474
- var logger4, LocalDashboardAssetStore;
47289
+ var logger5, LocalDashboardAssetStore;
46475
47290
  var init_server = __esm({
46476
47291
  "../server/src/server.ts"() {
46477
47292
  "use strict";
@@ -46485,7 +47300,7 @@ var init_server = __esm({
46485
47300
  init_dashboard_routing();
46486
47301
  init_logging();
46487
47302
  init_entitlement_sync();
46488
- logger4 = new Logger("server");
47303
+ logger5 = new Logger("server");
46489
47304
  LocalDashboardAssetStore = class {
46490
47305
  constructor(distDir) {
46491
47306
  this.distDir = distDir;
@@ -46498,62 +47313,15 @@ var init_server = __esm({
46498
47313
  });
46499
47314
 
46500
47315
  // ../server/src/cli/main.ts
47316
+ init_state();
47317
+ init_oauth();
46501
47318
  import { spawn } from "node:child_process";
46502
47319
  import { existsSync as existsSync6 } from "node:fs";
46503
47320
  import { createServer as createServer2 } from "node:http";
46504
47321
  import path6 from "node:path";
46505
47322
 
46506
- // ../server/src/cli/state.ts
46507
- init_credential();
46508
- import { existsSync as existsSync2, mkdirSync as mkdirSync2, readFileSync as readFileSync2, writeFileSync as writeFileSync2 } from "node:fs";
46509
- import { homedir as homedir2 } from "node:os";
46510
- import path2 from "node:path";
46511
- var CLI_PORT = 53683;
46512
- var CLI_PROCESS_NAME = "trendpublish";
46513
- function stateDir2() {
46514
- return process.env.TRENDPUBLISH_HOME?.trim() || path2.join(homedir2(), ".trendpublish");
46515
- }
46516
- function configPath() {
46517
- return path2.join(stateDir2(), "config.json");
46518
- }
46519
- function readConfig() {
46520
- const file = configPath();
46521
- if (!existsSync2(file)) return null;
46522
- try {
46523
- const parsed = JSON.parse(readFileSync2(file, "utf8"));
46524
- if (typeof parsed.apiKey !== "string" || !parsed.apiKey) return null;
46525
- return { apiKey: parsed.apiKey, port: parsed.port ?? CLI_PORT };
46526
- } catch {
46527
- return null;
46528
- }
46529
- }
46530
- function initConfig() {
46531
- const existing = readConfig();
46532
- if (existing) return existing;
46533
- const dir = stateDir2();
46534
- mkdirSync2(dir, { recursive: true });
46535
- mkdirSync2(path2.join(dir, "objects"), { recursive: true });
46536
- const config = { apiKey: crypto.randomUUID(), port: CLI_PORT };
46537
- writeFileSync2(configPath(), `${JSON.stringify(config, null, 2)}
46538
- `, { mode: 384 });
46539
- return config;
46540
- }
46541
- function applyConfigToEnv(config) {
46542
- const dir = stateDir2();
46543
- process.env.TRENDPUBLISH_API_KEY = config.apiKey;
46544
- process.env.TRENDPUBLISH_PORT = String(config.port);
46545
- process.env.TRENDPUBLISH_SQLITE_PATH = path2.join(dir, "trendpublish.sqlite3");
46546
- process.env.TRENDPUBLISH_OBJECT_STORAGE = "local";
46547
- process.env.TRENDPUBLISH_OBJECT_STORAGE_PATH = path2.join(dir, "objects");
46548
- }
46549
- function dashboardUrl(config) {
46550
- return `http://127.0.0.1:${config.port}/dashboard`;
46551
- }
46552
-
46553
- // ../server/src/cli/main.ts
46554
- init_oauth();
46555
-
46556
47323
  // ../server/src/cli/daemon.ts
47324
+ init_state();
46557
47325
  import { existsSync as existsSync3 } from "node:fs";
46558
47326
  import path3 from "node:path";
46559
47327
  import { fileURLToPath } from "node:url";
@@ -46567,8 +47335,8 @@ function call(method, ...args) {
46567
47335
  );
46568
47336
  });
46569
47337
  }
46570
- function resolveInterpreter() {
46571
- let dir = here;
47338
+ function resolveInterpreter(startDir = here) {
47339
+ let dir = startDir;
46572
47340
  for (let depth = 0; depth < 6; depth += 1) {
46573
47341
  const candidate = path3.join(dir, "node_modules", ".bin", "tsx");
46574
47342
  if (existsSync3(candidate)) return candidate;
@@ -46576,6 +47344,13 @@ function resolveInterpreter() {
46576
47344
  }
46577
47345
  return "tsx";
46578
47346
  }
47347
+ function resolveDaemonEntry(dir = here) {
47348
+ const bundledCli = path3.join(dir, "cli.js");
47349
+ if (existsSync3(bundledCli)) {
47350
+ return { script: bundledCli, interpreter: process.execPath };
47351
+ }
47352
+ return { script: path3.join(dir, "main.ts"), interpreter: resolveInterpreter(dir) };
47353
+ }
46579
47354
  async function withConnection(run2) {
46580
47355
  await call("connect");
46581
47356
  try {
@@ -46586,19 +47361,34 @@ async function withConnection(run2) {
46586
47361
  }
46587
47362
  async function daemonStart() {
46588
47363
  initConfig();
46589
- const script = path3.join(here, "main.ts");
47364
+ const entry = resolveDaemonEntry();
47365
+ const env = { TRENDPUBLISH_HOME: stateDir2() };
47366
+ for (const key of [
47367
+ "TRENDPUBLISH_MIGRATIONS_DIR",
47368
+ "TRENDPUBLISH_DASHBOARD_DIR",
47369
+ "TRENDPUBLISH_BECOMEOPC_ISSUER"
47370
+ ]) {
47371
+ if (process.env[key]?.trim()) env[key] = process.env[key].trim();
47372
+ }
46590
47373
  await withConnection(async () => {
46591
- const existing = await call("describe", CLI_PROCESS_NAME);
47374
+ const existing = await call(
47375
+ "describe",
47376
+ CLI_PROCESS_NAME
47377
+ );
46592
47378
  if (Array.isArray(existing) && existing.length > 0) {
46593
- await call("restart", CLI_PROCESS_NAME);
46594
- return;
47379
+ const execPath = existing[0]?.pm2_env?.pm_exec_path;
47380
+ if (execPath === entry.script) {
47381
+ await call("restart", CLI_PROCESS_NAME);
47382
+ return;
47383
+ }
47384
+ await call("delete", CLI_PROCESS_NAME);
46595
47385
  }
46596
47386
  await call("start", {
46597
47387
  name: CLI_PROCESS_NAME,
46598
- script,
47388
+ script: entry.script,
46599
47389
  args: ["start"],
46600
- interpreter: resolveInterpreter(),
46601
- env: { TRENDPUBLISH_HOME: stateDir2() },
47390
+ interpreter: entry.interpreter,
47391
+ env,
46602
47392
  autorestart: true,
46603
47393
  max_restarts: 10
46604
47394
  });
@@ -46737,6 +47527,58 @@ function waitForLoopbackCode(port, expectedState, authorizeUrl, timeoutMs = 18e4
46737
47527
  server.listen(port, "127.0.0.1", () => openBrowser(authorizeUrl));
46738
47528
  });
46739
47529
  }
47530
+ async function waitForRunningServerCallback(port, expectedState, authorizeUrl, timeoutMs = 18e4) {
47531
+ const config = readConfig();
47532
+ if (!config) {
47533
+ throw new Error(
47534
+ `\u7AEF\u53E3 ${port} \u5DF2\u88AB\u5360\u7528\uFF0C\u4E14\u672A\u627E\u5230\u672C\u5730 TrendPublish \u914D\u7F6E\u3002\u8BF7\u5148\u91CA\u653E\u7AEF\u53E3 ${port} \u540E\u91CD\u8BD5\u3002`
47535
+ );
47536
+ }
47537
+ const baseUrl = `http://127.0.0.1:${port}`;
47538
+ const headers = {
47539
+ authorization: `Bearer ${config.apiKey}`,
47540
+ "content-type": "application/json"
47541
+ };
47542
+ const registerResponse = await fetch(`${baseUrl}/api/cli/oauth-callback/register`, {
47543
+ method: "POST",
47544
+ headers,
47545
+ body: JSON.stringify({ state: expectedState, timeoutMs })
47546
+ }).catch(() => null);
47547
+ if (!registerResponse?.ok) {
47548
+ throw new Error(
47549
+ `\u7AEF\u53E3 ${port} \u5DF2\u88AB\u5360\u7528\uFF08\u5F53\u524D\u8FD0\u884C\u7684\u670D\u52A1\u4E0D\u652F\u6301\u63A5\u7BA1 OAuth \u56DE\u8C03\uFF09\u3002\u8BF7\u5148\u505C\u6B62\u5360\u7528 ${port} \u7684\u8FDB\u7A0B\u540E\u518D\u6267\u884C trendpublish login\u3002`
47550
+ );
47551
+ }
47552
+ openBrowser(authorizeUrl);
47553
+ const waitResponse = await fetch(
47554
+ `${baseUrl}/api/cli/oauth-callback/wait?state=${encodeURIComponent(expectedState)}`,
47555
+ { headers }
47556
+ );
47557
+ const body = await waitResponse.json().catch(() => ({}));
47558
+ if (!waitResponse.ok || !body.code) {
47559
+ throw new Error(body.error || `\u7B49\u5F85 OAuth \u56DE\u8C03\u5931\u8D25\uFF08HTTP ${waitResponse.status}\uFF09`);
47560
+ }
47561
+ return body.code;
47562
+ }
47563
+ async function acquireOAuthCode(port, expectedState, authorizeUrl) {
47564
+ try {
47565
+ const code = await waitForLoopbackCode(port, expectedState, authorizeUrl);
47566
+ return { code, viaRunningServer: false };
47567
+ } catch (error) {
47568
+ const errno = error?.code;
47569
+ if (errno !== "EADDRINUSE") throw error;
47570
+ const code = await waitForRunningServerCallback(port, expectedState, authorizeUrl);
47571
+ return { code, viaRunningServer: true };
47572
+ }
47573
+ }
47574
+ async function notifyRunningServerRelaySync(port) {
47575
+ const config = readConfig();
47576
+ if (!config) return;
47577
+ await fetch(`http://127.0.0.1:${port}/api/cli/relay-sync`, {
47578
+ method: "POST",
47579
+ headers: { authorization: `Bearer ${config.apiKey}` }
47580
+ }).catch(() => void 0);
47581
+ }
46740
47582
  async function runCommand(argv) {
46741
47583
  const [command, ...rest] = argv;
46742
47584
  switch (command) {
@@ -46756,7 +47598,7 @@ async function runCommand(argv) {
46756
47598
  }
46757
47599
  case "open": {
46758
47600
  const config = readConfig() ?? initConfig();
46759
- const url = `${dashboardUrl(config)}?token=${encodeURIComponent(config.apiKey)}`;
47601
+ const url = `${dashboardUrl(config)}/workspace?token=${encodeURIComponent(config.apiKey)}`;
46760
47602
  openBrowser(url);
46761
47603
  out(url);
46762
47604
  return 0;
@@ -46773,15 +47615,22 @@ async function runCommand(argv) {
46773
47615
  state
46774
47616
  });
46775
47617
  out("\u6B63\u5728\u6253\u5F00\u6D4F\u89C8\u5668\u767B\u5F55 becomeopc\u2026");
46776
- const code = await waitForLoopbackCode(CLI_PORT, state, authorizeUrl);
47618
+ const { code, viaRunningServer } = await acquireOAuthCode(CLI_PORT, state, authorizeUrl);
46777
47619
  const tokens = await exchangeCode({ issuer, redirectUri, code, verifier: pkce.verifier });
46778
47620
  const entitlement = await fetchEntitlement({ issuer, accessToken: tokens.access_token });
46779
47621
  writeRelayCredential({
46780
47622
  token: entitlement.token,
46781
47623
  refreshToken: tokens.refresh_token,
46782
47624
  expiresAt: entitlement.expires_at,
46783
- product: entitlement.product
47625
+ product: entitlement.product,
47626
+ plan: entitlement.plan,
47627
+ status: entitlement.status,
47628
+ periodEnd: entitlement.period_end,
47629
+ trialEnd: entitlement.trial_end
46784
47630
  });
47631
+ if (viaRunningServer) {
47632
+ await notifyRunningServerRelaySync(CLI_PORT);
47633
+ }
46785
47634
  out(`\u5DF2\u767B\u5F55\uFF0Crelay \u51ED\u8BC1\u5DF2\u4FDD\u5B58\uFF08${entitlement.plan}\uFF0C\u5230\u671F ${entitlement.expires_at}\uFF09`);
46786
47635
  return 0;
46787
47636
  }