@tbox.cn/app-module-mall-core 0.2.1 → 0.3.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 (71) hide show
  1. package/README.md +12 -3
  2. package/dist/HomeActivityDetailDialog-2GJFYSMZ.less +178 -0
  3. package/dist/MallHome-PABCNS6D.less +623 -0
  4. package/dist/chunk-B7ZAK6VM.js +724 -0
  5. package/dist/chunk-HMQKNJEO.js +1722 -0
  6. package/dist/client/index.d.ts +22 -0
  7. package/dist/client/index.js +8 -0
  8. package/dist/home-slot-WBZ6ONDP.less +4 -0
  9. package/dist/index-ELJ55M66.less +256 -0
  10. package/dist/index-U5YRUY7P.less +352 -0
  11. package/dist/index.d.ts +6 -1
  12. package/dist/index.js +7 -1
  13. package/dist/member-service-icon-SIGSRKE3.svg +1 -0
  14. package/dist/parking-service-icon-3A2TGUUM.svg +1 -0
  15. package/dist/server/index.d.ts +338 -6
  16. package/dist/server/index.js +3 -1
  17. package/dist/welcome-sparkle-transparent-v07-75RL4QUU.png +0 -0
  18. package/package.json +24 -6
  19. package/src/client/HomeActivityDetailDialog.less +178 -0
  20. package/src/client/HomeActivityDetailDialog.tsx +256 -0
  21. package/src/client/MallHome.less +623 -0
  22. package/src/client/MallHome.tsx +667 -0
  23. package/src/client/assets/home/member-service-icon.svg +1 -0
  24. package/src/client/assets/home/parking-service-icon.svg +1 -0
  25. package/src/client/assets/home/welcome-sparkle-transparent-v07.png +0 -0
  26. package/src/client/assets.d.ts +13 -0
  27. package/src/client/cards/mall-home/index.tsx +32 -0
  28. package/src/client/cards/overrides/BumpInActivityChatCard.tsx +81 -0
  29. package/src/client/components/ActivityDetailPresentation/index.less +352 -0
  30. package/src/client/components/ActivityDetailPresentation/index.tsx +31 -0
  31. package/src/client/components/MemberGateSheet/index.less +256 -0
  32. package/src/client/components/MemberGateSheet/index.tsx +211 -0
  33. package/src/client/components/MemberGateSheet/model.ts +42 -0
  34. package/src/client/home-runtime.ts +493 -0
  35. package/src/client/home-slot.less +4 -0
  36. package/src/client/home-slot.tsx +345 -0
  37. package/src/client/index.ts +32 -0
  38. package/src/client/member-gate.ts +337 -0
  39. package/src/client/mock-direct-gate.ts +45 -0
  40. package/src/index.ts +2 -2
  41. package/src/server/assembly.ts +19 -7
  42. package/src/server/cards/mall-home/meta.ts +61 -0
  43. package/src/server/cards/mall-home/schema.ts +73 -0
  44. package/src/server/home-config.ts +36 -0
  45. package/src/server/index.ts +45 -4
  46. package/src/server/linked-panel-member.ts +65 -0
  47. package/src/server/linked-panel-parking.ts +124 -0
  48. package/src/server/module-ports.ts +67 -0
  49. package/src/server/routes.ts +286 -0
  50. package/src/vite-env.d.ts +1 -0
  51. package/tbox.module.json +15 -5
  52. package/tests/BumpInActivityChatCard.test.tsx +214 -0
  53. package/tests/MallHome.test.tsx +481 -0
  54. package/tests/MemberGateSheet-model.test.ts +65 -0
  55. package/tests/MemberGateSheet.test.tsx +173 -0
  56. package/tests/home-config.test.ts +43 -0
  57. package/tests/home-runtime.test.ts +545 -0
  58. package/tests/home-slot.test.tsx +718 -0
  59. package/tests/linked-panel-member.test.ts +78 -0
  60. package/tests/linked-panel-parking-presence.test.ts +117 -0
  61. package/tests/linked-panel-privacy.test.ts +79 -0
  62. package/tests/linked-panel-scope.test.ts +116 -0
  63. package/tests/mall-home-preview.test.tsx +71 -0
  64. package/tests/member-gate.test.ts +384 -0
  65. package/tests/mock-direct-gate.test.ts +136 -0
  66. package/tests/module-ports.test.ts +18 -0
  67. package/tests/route-paths.test.ts +70 -0
  68. package/tests/usePullDownHistory.test.tsx +191 -0
  69. package/tsconfig.json +1 -0
  70. package/tsup.config.ts +22 -1
  71. package/dist/chunk-WSJ2HA5F.js +0 -267
@@ -0,0 +1,724 @@
1
+ // src/server/index.ts
2
+ import path from "path";
3
+ import { existsSync } from "fs";
4
+ import { SCOPE_ASSEMBLY_KIND as SCOPE_ASSEMBLY_KIND2 } from "@tbox.cn/app-contracts";
5
+ import { MALL_INFO_CACHE_SERVICE } from "@tbox.cn/app-contracts-mall";
6
+
7
+ // src/server/assembly.ts
8
+ import { createLogger } from "@tbox.cn/app-agent-sdk-server";
9
+ import { SCOPE_ASSEMBLY_KIND } from "@tbox.cn/app-contracts";
10
+ import {
11
+ createMallRuntimeAssembly,
12
+ withMallName
13
+ } from "@tbox.cn/app-contracts-mall";
14
+ import { mallControlPlaneOf } from "@tbox.cn/app-contracts-mall/server";
15
+
16
+ // src/server/mall-info-cache.ts
17
+ var CACHE_TTL_MS = 30 * 60 * 1e3;
18
+ var NEGATIVE_TTL_MS = 5 * 60 * 1e3;
19
+ var CACHE_MAX_ENTRIES = 1024;
20
+ var MALL_ID_RE = /^[\w-]{1,32}$/;
21
+ var cache = /* @__PURE__ */ new Map();
22
+ var inFlight = /* @__PURE__ */ new Map();
23
+ var ANON_REQUEST = {
24
+ identity: { userId: "", source: "anonymous" },
25
+ credentials: { provider: "anonymous", token: "" },
26
+ attributes: {}
27
+ };
28
+ function cachedMallName(mallId) {
29
+ const entry = cache.get(mallId);
30
+ if (!entry || entry.expiresAt <= Date.now()) {
31
+ cache.delete(mallId);
32
+ return void 0;
33
+ }
34
+ return entry.negative ? void 0 : entry.mallInfo?.name;
35
+ }
36
+ async function resolveMallInfoService(mallId, integrations) {
37
+ if (!integrations) return null;
38
+ try {
39
+ const svc = await integrations.resolveService({
40
+ service: "mall.info",
41
+ scope: { mallId },
42
+ request: ANON_REQUEST
43
+ });
44
+ return svc ?? null;
45
+ } catch {
46
+ return null;
47
+ }
48
+ }
49
+ async function resolveMallInfo(mallId, integrations) {
50
+ if (!MALL_ID_RE.test(mallId)) return void 0;
51
+ const entry = cache.get(mallId);
52
+ if (entry && entry.expiresAt > Date.now()) {
53
+ return entry.negative ? void 0 : entry.mallInfo;
54
+ }
55
+ if (entry) cache.delete(mallId);
56
+ const existing = inFlight.get(mallId);
57
+ if (existing) return existing;
58
+ const promise = (async () => {
59
+ const service = await resolveMallInfoService(mallId, integrations);
60
+ if (!service) {
61
+ cache.set(mallId, { negative: true, expiresAt: Date.now() + NEGATIVE_TTL_MS });
62
+ trimCache();
63
+ return void 0;
64
+ }
65
+ try {
66
+ const info = await service.getMallInfo(mallId);
67
+ if (!info) {
68
+ cache.set(mallId, { negative: true, expiresAt: Date.now() + NEGATIVE_TTL_MS });
69
+ } else {
70
+ cache.set(mallId, { mallInfo: info, expiresAt: Date.now() + CACHE_TTL_MS });
71
+ }
72
+ trimCache();
73
+ return info;
74
+ } catch {
75
+ cache.set(mallId, { negative: true, expiresAt: Date.now() + NEGATIVE_TTL_MS });
76
+ trimCache();
77
+ return void 0;
78
+ }
79
+ })();
80
+ inFlight.set(mallId, promise);
81
+ try {
82
+ return await promise;
83
+ } finally {
84
+ inFlight.delete(mallId);
85
+ }
86
+ }
87
+ function trimCache() {
88
+ while (cache.size > CACHE_MAX_ENTRIES) {
89
+ const firstKey = cache.keys().next().value;
90
+ if (firstKey === void 0) break;
91
+ cache.delete(firstKey);
92
+ }
93
+ }
94
+
95
+ // src/server/assembly.ts
96
+ var deploymentLogger = createLogger("DEPLOYMENT");
97
+ var WARM_TIMEOUT_MS = 2e3;
98
+ var NO_DECLARATIONS = Object.freeze({});
99
+ function resolveMallScopeAssembly(ctx) {
100
+ return ctx.domainAssemblies.resolve(SCOPE_ASSEMBLY_KIND);
101
+ }
102
+ function createScopeAssembly(raw, ctx) {
103
+ if (!raw) return void 0;
104
+ const rootMiniAppId = typeof raw.config.config?.miniAppId === "string" && raw.config.config.miniAppId ? raw.config.config.miniAppId : void 0;
105
+ let projectionRef;
106
+ let projection;
107
+ const project = () => {
108
+ const declared = ctx.integrations?.providerInstanceDeclarations?.() ?? NO_DECLARATIONS;
109
+ if (!projection || projectionRef !== declared) {
110
+ const controlPlane = mallControlPlaneOf(raw.config, declared);
111
+ const runtime = createMallRuntimeAssembly(controlPlane);
112
+ projection = {
113
+ controlPlane,
114
+ runtime,
115
+ buildScopeWithMallName: withMallName(runtime, controlPlane, cachedMallName)
116
+ };
117
+ projectionRef = declared;
118
+ }
119
+ return projection;
120
+ };
121
+ return {
122
+ // 数据成员 getter:访问期读投影(家页面 routes / mall-directory 闭包自动生效)
123
+ get controlPlane() {
124
+ return project().controlPlane;
125
+ },
126
+ rootMiniAppId,
127
+ // 函数成员稳定包装(register 期定型——消费方捕获引用恒安全;调用时才读投影)
128
+ extractScopeKey: (c) => project().runtime.extractScopeKey(c),
129
+ validateScope: (a) => project().runtime.validateScope(a),
130
+ extractMallScope: (c) => project().runtime.extractMallScope(c),
131
+ buildScope: (a) => project().runtime.buildScope(a),
132
+ buildScopeWithMallName: (a) => project().buildScopeWithMallName(a),
133
+ instanceIdOf: (scope) => scope["mallId"] ?? "",
134
+ get scopeDefaults() {
135
+ const defaultMallId = project().controlPlane.defaultMallId;
136
+ return defaultMallId ? { defaultMallId } : void 0;
137
+ },
138
+ defaultMallContext() {
139
+ return buildDefaultMallContext(project().controlPlane, rootMiniAppId);
140
+ },
141
+ async enhanceHelloContext(context) {
142
+ const mall = context["mall"];
143
+ const mallId = typeof mall?.mallId === "string" && mall.mallId ? mall.mallId : void 0;
144
+ if (!mallId) return context;
145
+ const nextMall = { ...mall };
146
+ if (!nextMall.miniAppId && rootMiniAppId) {
147
+ nextMall.miniAppId = rootMiniAppId;
148
+ deploymentLogger.warn(`[MALL] HELLO context \u7F3A miniAppId\uFF0C\u6309 root config \u56DE\u586B\uFF08mallId=${mallId}\uFF09`);
149
+ }
150
+ if (!project().controlPlane.malls.some((m) => m.mallId === mallId)) {
151
+ const warm = resolveMallInfo(mallId, ctx.integrations);
152
+ await Promise.race([warm, new Promise((r) => setTimeout(r, WARM_TIMEOUT_MS))]).catch(
153
+ () => void 0
154
+ );
155
+ }
156
+ return { ...context, mall: nextMall };
157
+ }
158
+ };
159
+ }
160
+ function resolveMallMiniAppId(controlPlane, rootMiniAppId, mallId) {
161
+ return rootMiniAppId ?? controlPlane.malls.find((m) => m.mallId === mallId)?.miniAppId;
162
+ }
163
+ function buildDefaultMallContext(controlPlane, rootMiniAppId) {
164
+ if (!controlPlane.defaultMallId) return void 0;
165
+ const miniAppId = resolveMallMiniAppId(controlPlane, rootMiniAppId, controlPlane.defaultMallId);
166
+ if (!miniAppId) {
167
+ deploymentLogger.warn(
168
+ `defaultMallId=${controlPlane.defaultMallId} \u65E0 miniAppId \u771F\u6E90\uFF08root config \u4E0E\u53C2\u8003\u8868\u53CC\u7F3A\uFF09\u2014\u2014\u6309 mallId-only \u6CE8\u5165\u9ED8\u8BA4\u5546\u5708`
169
+ );
170
+ }
171
+ return { mall: { mallId: controlPlane.defaultMallId, ...miniAppId ? { miniAppId } : {} } };
172
+ }
173
+
174
+ // src/server/mall-info-tool.ts
175
+ import { createTool } from "@tbox.cn/app-agent-sdk-server";
176
+ import { z } from "zod";
177
+ var ctxRef;
178
+ function bindMallInfoContext(ctx) {
179
+ ctxRef = ctx;
180
+ }
181
+ var mallInfoTool = createTool({
182
+ id: "mall-info",
183
+ description: "\u67E5\u8BE2\u5546\u573A\u57FA\u672C\u4FE1\u606F\uFF08\u540D\u79F0/\u5730\u5740/\u7ECF\u7EAC\u5EA6\uFF09\u3002\u7528\u6237\u95EE\u67D0\u5546\u573A\u53EB\u4EC0\u4E48\u3001\u5728\u54EA\u513F\u3001\u5730\u5740\u65F6\u8C03\u7528\uFF1B\u5F53\u524D\u4F1A\u8BDD\u5546\u573A ID \u53EF\u4ECE mall-info \u6CE8\u5165\u5757\u53D6\u3002",
184
+ // D11 参数规范:纯 string(preTool decide 注入 / 模型直传入参)
185
+ inputSchema: z.object({ mallId: z.string().describe("\u5546\u573A ID") }),
186
+ // 无 outputSchema:可选字段动态形状(对齐 mall-context;出卡工具建议省略的约定此处同理由)
187
+ execute: async (input) => {
188
+ const mallId = typeof input.mallId === "string" ? input.mallId.trim() : "";
189
+ if (!mallId) return { found: false, reason: "mallId \u7F3A\u5931" };
190
+ const info = await resolveMallInfo(mallId, ctxRef?.integrations);
191
+ if (!info) {
192
+ return {
193
+ found: false,
194
+ mallId,
195
+ reason: "\u5546\u573A\u4FE1\u606F\u4E0D\u53EF\u7528\uFF08mall.info \u69FD\u672A\u88C5\u914D/\u672A\u914D\u7F6E/\u672A\u77E5 mallId\uFF09"
196
+ };
197
+ }
198
+ return {
199
+ found: true,
200
+ mallId: info.mallId,
201
+ name: info.name,
202
+ ...info.address ? { address: info.address } : {},
203
+ ...info.latitude != null ? { latitude: info.latitude } : {},
204
+ ...info.longitude != null ? { longitude: info.longitude } : {},
205
+ ...info.cityId ? { cityId: info.cityId } : {}
206
+ };
207
+ }
208
+ });
209
+
210
+ // src/server/pre-tools.ts
211
+ import { definePreTool } from "@tbox.cn/app-agent-sdk-server";
212
+ import { mallSlot } from "@tbox.cn/app-contracts-mall";
213
+ var preTools = {
214
+ "mall-info": definePreTool(mallInfoTool, {
215
+ routing: { mode: "always" },
216
+ // 上下文统一化:连接级领域属性经 decide 入参 attributes 判定(与 mall-context 同通道)
217
+ decide: ({ attributes }) => {
218
+ const scope = mallSlot.read(attributes);
219
+ if (!scope) return { decision: "skip", reason: "\u65E0 mall scope\uFF08attributes \u7F3A\u5E2D/\u89E3\u6790\u5931\u8D25\uFF09" };
220
+ return { decision: "run", args: { mallId: scope.mallId } };
221
+ },
222
+ silent: true,
223
+ dedup: {
224
+ accepts: (result) => result?.found === true
225
+ }
226
+ })
227
+ };
228
+
229
+ // src/server/routes.ts
230
+ import { Router } from "express";
231
+ import { createLogger as createLogger4, getRequestContext } from "@tbox.cn/app-agent-sdk-server";
232
+ import {
233
+ MEMBER_SNAPSHOT_SERVICE,
234
+ PARKING_SNAPSHOT_SERVICE,
235
+ mallScopeOrEmpty,
236
+ withMallScopeFromQuery
237
+ } from "@tbox.cn/app-contracts-mall";
238
+
239
+ // src/server/module-ports.ts
240
+ import { createLogger as createLogger2 } from "@tbox.cn/app-agent-sdk-server";
241
+ var portsLogger = createLogger2("server");
242
+ function warnUnassembled(specifier, e) {
243
+ portsLogger.warn(
244
+ "module ports \u672A\u88C5\u914D\uFF08tbox-app module add \u540E\u751F\u6548\uFF09",
245
+ specifier,
246
+ String(e?.message ?? e).slice(0, 120)
247
+ );
248
+ }
249
+ async function loadBumpinPorts() {
250
+ try {
251
+ const imported = await import("@tbox.cn/app-module-alipay-activity/server");
252
+ return imported;
253
+ } catch (e) {
254
+ warnUnassembled("@app/module-alipay-activity/server", e);
255
+ return null;
256
+ }
257
+ }
258
+
259
+ // src/server/linked-panel-parking.ts
260
+ async function probeLinkedPanelPresence(service, query, plateNos, log) {
261
+ const probe = service?.probeParkedVehicles;
262
+ if (typeof probe !== "function") return [];
263
+ try {
264
+ return await probe.call(service, query, plateNos);
265
+ } catch (e) {
266
+ log?.("LinkedPanel presence probe fail", { plateCount: plateNos.length, err: e.message });
267
+ return [];
268
+ }
269
+ }
270
+ async function loadLinkedPanelParking(service, query, load) {
271
+ const requiresMembership = service?.requiresMembership;
272
+ if (typeof requiresMembership === "function" && requiresMembership.call(service, query)) {
273
+ return { status: "membership_required" };
274
+ }
275
+ return load();
276
+ }
277
+ var PLATE_PATTERN = /^[\u3400-\u9fff][A-HJ-NP-Z][A-HJ-NP-Z0-9]{5,6}$/;
278
+ function normalizePlate(value) {
279
+ if (typeof value !== "string") return null;
280
+ const plate = value.trim().toUpperCase();
281
+ return PLATE_PATTERN.test(plate) ? plate : null;
282
+ }
283
+ function buildLinkedPanelParking(plates, presence = []) {
284
+ const normalized = [
285
+ ...new Set(
286
+ plates.map(normalizePlate).filter((plate) => plate !== null)
287
+ )
288
+ ];
289
+ if (normalized.length === 0) return { status: "empty", plateCount: 0 };
290
+ const presenceByPlate = /* @__PURE__ */ new Map();
291
+ for (const p of presence) {
292
+ const plate = normalizePlate(p.plateNo);
293
+ if (plate && !presenceByPlate.has(plate)) presenceByPlate.set(plate, p);
294
+ }
295
+ const inLot = normalized.map((plate) => presenceByPlate.get(plate)).filter((p) => p !== void 0);
296
+ const primaryPlate = inLot[0]?.plateNo ?? normalized[0];
297
+ if (!primaryPlate) return { status: "empty", plateCount: 0 };
298
+ return {
299
+ status: "ready",
300
+ primaryPlate,
301
+ plateCount: normalized.length,
302
+ ...inLot.length > 0 ? {
303
+ parkedPlates: inLot.map((p) => p.plateNo),
304
+ freeMinutesRemaining: 0,
305
+ ...inLot[0].parkedMinutes !== void 0 ? { parkedMinutes: inLot[0].parkedMinutes } : {}
306
+ } : {}
307
+ };
308
+ }
309
+
310
+ // src/server/linked-panel-member.ts
311
+ function buildLinkedPanelMember(account, points) {
312
+ if (account.authState === "unauthenticated") {
313
+ return { authState: "unauthenticated", state: "unknown" };
314
+ }
315
+ if (account.state !== "active") {
316
+ return { authState: "authenticated", state: account.state };
317
+ }
318
+ return {
319
+ authState: "authenticated",
320
+ state: "active",
321
+ ...points && Number.isSafeInteger(points.balance) && points.balance >= 0 ? { balance: points.balance } : {},
322
+ ...points?.membershipLabel ? { membershipLabel: points.membershipLabel } : {}
323
+ };
324
+ }
325
+ async function loadLinkedPanelMember(service, userId, onError) {
326
+ const account = await service.getAccount(userId).catch((error) => {
327
+ onError?.("getAccount", error);
328
+ return null;
329
+ });
330
+ if (!account) return { authState: "authenticated", state: "unknown" };
331
+ const points = account.authState === "authenticated" && account.state === "active" ? await service.queryPoints(userId).catch((error) => {
332
+ onError?.("queryPoints", error);
333
+ return null;
334
+ }) : null;
335
+ return buildLinkedPanelMember(account, points);
336
+ }
337
+
338
+ // src/server/home-config.ts
339
+ import { createLogger as createLogger3 } from "@tbox.cn/app-agent-sdk-server";
340
+ var logger = createLogger3("HOME-CONFIG");
341
+ var LEGAL_OFF_VALUES = /* @__PURE__ */ new Set(["false", "0"]);
342
+ function resolveHomeConfig(env) {
343
+ const raw = env["MALL_HOME_DEV_SERVICES"];
344
+ const showDevServices = raw === "true" || raw === "1";
345
+ if (!showDevServices && raw !== void 0 && !LEGAL_OFF_VALUES.has(raw)) {
346
+ logger.warn(
347
+ `MALL_HOME_DEV_SERVICES \u975E\u6CD5\u503C ${JSON.stringify(raw)}\u2014\u2014\u6309\u9690\u85CF\u5904\u7406\uFF08\u5408\u6CD5\u503C\uFF1Atrue / 1 / false / 0\uFF09`
348
+ );
349
+ }
350
+ logger.info(
351
+ `showDevServices=${showDevServices} (MALL_HOME_DEV_SERVICES=${raw === void 0 ? "unset" : JSON.stringify(raw)})`
352
+ );
353
+ return { showDevServices };
354
+ }
355
+
356
+ // src/server/routes.ts
357
+ var serverLogger = createLogger4("mall-core");
358
+ function createMallHomeRouter(ctx) {
359
+ const HOME_CONFIG = resolveHomeConfig(process.env);
360
+ const router = Router();
361
+ router.get("/config", (_req, res) => {
362
+ res.set("Cache-Control", "no-store");
363
+ res.json(HOME_CONFIG);
364
+ });
365
+ router.get("/linked-panel", async (req, res) => {
366
+ try {
367
+ const authCtx = getRequestContext(req);
368
+ if (!authCtx || authCtx.identity.source === "anonymous") {
369
+ serverLogger.info("LinkedPanel anonymous \u2192 unauthenticated stub", { source: authCtx?.identity.source ?? "none" });
370
+ res.json({
371
+ member: { authState: "unauthenticated", state: "unknown" },
372
+ parking: { status: "unauthenticated" }
373
+ });
374
+ return;
375
+ }
376
+ const mallId = typeof req.query["mallId"] === "string" ? req.query["mallId"] : void 0;
377
+ const userId = authCtx.identity.userId;
378
+ serverLogger.info("LinkedPanel start", { userId, mallId: mallId ?? "(none)" });
379
+ if (!mallId) {
380
+ serverLogger.info("LinkedPanel no mallId \u2192 skip member query");
381
+ res.json({ member: null, parking: { status: "unavailable" } });
382
+ return;
383
+ }
384
+ const assembly = resolveMallScopeAssembly(ctx);
385
+ const mallMiniAppId = assembly ? resolveMallMiniAppId(assembly.controlPlane, assembly.rootMiniAppId, mallId) : void 0;
386
+ if (!mallMiniAppId) {
387
+ serverLogger.warn(
388
+ `[MALL] linked-panel mallId=${mallId} \u65E0 miniAppId \u771F\u6E90\uFF08root config \u4E0E malls \u8868\u53CC\u7F3A\uFF09\u2014\u2014\u6309 mallId-only \u964D\u7EA7\u7EE7\u7EED`
389
+ );
390
+ }
391
+ const reqCtxWithMall = withMallScopeFromQuery(authCtx, req.query, { miniAppId: mallMiniAppId });
392
+ const [memberResult, parkingResult] = await Promise.allSettled([
393
+ // 会员积分(W3-3 服务化消费:member.snapshot 工厂缺席 = member 模块未装 → null,
394
+ // 与迁移前 loader null 同语义;工厂执行失败 → null——与迁移前端口 resolve 失败同语义)
395
+ (async () => {
396
+ const memberStartedAt = Date.now();
397
+ const factory = ctx.resolveService(MEMBER_SNAPSHOT_SERVICE);
398
+ const port = factory ? await factory(reqCtxWithMall).catch((e) => {
399
+ serverLogger.warn("LinkedPanel resolveMemberSnapshot fail", e);
400
+ return null;
401
+ }) : null;
402
+ if (!port) return null;
403
+ const member2 = await loadLinkedPanelMember(
404
+ { getAccount: (uid) => port.getAccount(uid), queryPoints: (uid) => port.queryPoints(uid) },
405
+ userId,
406
+ (operation, error) => {
407
+ serverLogger.warn(`LinkedPanel ${operation} fail`, error);
408
+ }
409
+ );
410
+ serverLogger.info("LinkedPanel member result", {
411
+ userId,
412
+ durationMs: Date.now() - memberStartedAt,
413
+ accountState: member2.state,
414
+ balance: member2.state === "active" ? member2.balance ?? null : null
415
+ });
416
+ return {
417
+ ...member2,
418
+ enrollUrl: port.enrollUrl || null
419
+ };
420
+ })(),
421
+ // 停车车辆(W3-3 服务化消费:parking.snapshot 工厂;缺席 → unavailable,执行失败 → error)
422
+ (async () => {
423
+ const parkingStartedAt = Date.now();
424
+ const factory = ctx.resolveService(PARKING_SNAPSHOT_SERVICE);
425
+ if (!factory) return { status: "unavailable" };
426
+ const service = await factory(reqCtxWithMall).catch((e) => {
427
+ serverLogger.warn("LinkedPanel resolveParkingSnapshot fail", e);
428
+ return null;
429
+ });
430
+ if (!service) return { status: "error" };
431
+ const query = {
432
+ scope: mallScopeOrEmpty(reqCtxWithMall),
433
+ requestContext: reqCtxWithMall
434
+ };
435
+ return loadLinkedPanelParking(service, query, async () => {
436
+ const vehicles = await service.listVehicles(query).catch((e) => {
437
+ serverLogger.warn("LinkedPanel listVehicles fail", e);
438
+ return null;
439
+ });
440
+ if (!vehicles) return { status: "error" };
441
+ const plates = vehicles.bound.map((v) => v.plateNo);
442
+ const presence = await probeLinkedPanelPresence(service, query, plates, (msg, meta2) => serverLogger.warn(msg, meta2));
443
+ const parking2 = buildLinkedPanelParking(plates, presence);
444
+ serverLogger.info("LinkedPanel parking result", {
445
+ userId,
446
+ durationMs: Date.now() - parkingStartedAt,
447
+ status: parking2.status,
448
+ plateCount: parking2.status === "ready" ? parking2.plateCount : 0,
449
+ inLotCount: presence.length
450
+ });
451
+ return parking2;
452
+ });
453
+ })()
454
+ ]);
455
+ const member = memberResult.status === "fulfilled" ? memberResult.value : null;
456
+ const parking = parkingResult.status === "fulfilled" ? parkingResult.value : null;
457
+ if (memberResult.status === "rejected") serverLogger.warn("LinkedPanel member rejected", memberResult.reason);
458
+ if (parkingResult.status === "rejected") serverLogger.warn("LinkedPanel parking rejected", parkingResult.reason);
459
+ const parkingState = parking ?? { status: "error" };
460
+ serverLogger.info("LinkedPanel response", {
461
+ userId,
462
+ memberState: member?.state ?? null,
463
+ parkingStatus: parkingState.status,
464
+ plateCount: parkingState.status === "ready" ? parkingState.plateCount : 0
465
+ });
466
+ res.json({ member, parking: parkingState });
467
+ } catch (err) {
468
+ serverLogger.warn("LinkedPanel error", err);
469
+ res.json({ member: null, parking: { status: "error" } });
470
+ }
471
+ });
472
+ router.get("/nearby-mall", (req, res) => {
473
+ const latParam = typeof req.query["lat"] === "string" ? parseFloat(req.query["lat"]) : NaN;
474
+ const lonParam = typeof req.query["lon"] === "string" ? parseFloat(req.query["lon"]) : NaN;
475
+ if (isNaN(latParam) || isNaN(lonParam)) {
476
+ res.status(400).json({ error: "lat/lon required" });
477
+ return;
478
+ }
479
+ const malls = resolveMallScopeAssembly(ctx)?.controlPlane.malls ?? [];
480
+ const mallsWithLocation = malls.filter((m) => m.location != null);
481
+ if (mallsWithLocation.length === 0) {
482
+ res.json({ mallId: null, name: null, distanceKm: null });
483
+ return;
484
+ }
485
+ const toRad = (deg) => deg * Math.PI / 180;
486
+ const haversine = (lat1, lon1, lat2, lon2) => {
487
+ const R = 6371;
488
+ const dLat = toRad(lat2 - lat1);
489
+ const dLon = toRad(lon2 - lon1);
490
+ const a = Math.sin(dLat / 2) ** 2 + Math.cos(toRad(lat1)) * Math.cos(toRad(lat2)) * Math.sin(dLon / 2) ** 2;
491
+ return R * 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
492
+ };
493
+ const RECOMMEND_THRESHOLD_KM = 50;
494
+ let nearest = null;
495
+ for (const mall of mallsWithLocation) {
496
+ const dist = haversine(latParam, lonParam, mall.location.lat, mall.location.lon);
497
+ if (!nearest || dist < nearest.distanceKm) {
498
+ nearest = { mallId: mall.mallId, name: mall.name, distanceKm: Math.round(dist * 10) / 10, address: mall.location.address };
499
+ }
500
+ }
501
+ if (!nearest || nearest.distanceKm > RECOMMEND_THRESHOLD_KM) {
502
+ res.json({ mallId: null, name: null, distanceKm: null });
503
+ return;
504
+ }
505
+ serverLogger.info("nearby-mall result", { lat: latParam, lon: lonParam, mallId: nearest.mallId, distanceKm: nearest.distanceKm });
506
+ res.json({ mallId: nearest.mallId, name: nearest.name, distanceKm: nearest.distanceKm, address: nearest.address ?? null });
507
+ });
508
+ router.get("/bumpin-banner", async (req, res) => {
509
+ try {
510
+ const ports = await loadBumpinPorts();
511
+ if (!ports) {
512
+ res.json({ supported: false, banner: null });
513
+ return;
514
+ }
515
+ const service = await ports.resolveAlipayBumpInService(ctx);
516
+ if (!service) {
517
+ res.json({ supported: false, banner: null });
518
+ return;
519
+ }
520
+ const authCtx = getRequestContext(req);
521
+ if (!authCtx || authCtx.identity.source === "anonymous") {
522
+ res.json({ supported: false, banner: null });
523
+ return;
524
+ }
525
+ const q = {
526
+ scope: { miniAppId: "", mallId: "" },
527
+ requestContext: { ...authCtx, attributes: { ...authCtx.attributes, mall: { miniAppId: "", mallId: "" } } }
528
+ };
529
+ const page = await service.listActivities(q, {});
530
+ const detail = page.items[0] ?? null;
531
+ if (!detail) {
532
+ res.json({ supported: true, banner: null });
533
+ return;
534
+ }
535
+ const linkedCardBackgroundUrl = ports.readAlipayBumpInConfig()?.linkedCardBackgroundUrl;
536
+ const banner = ports.toBumpInCardData(detail, "banner", linkedCardBackgroundUrl);
537
+ const detailCard = {
538
+ id: `home-bumpin:${detail.activityRef}`,
539
+ cardType: "promotion-bumpin-activity",
540
+ data: ports.toBumpInCardData(detail, "detail", linkedCardBackgroundUrl),
541
+ status: "ready",
542
+ schemaVersion: 1
543
+ };
544
+ res.json({ supported: true, banner, detailCard });
545
+ } catch (err) {
546
+ serverLogger.warn("/api/m/mall-core/bumpin-banner error:", err);
547
+ res.status(500).json({ supported: false, banner: null });
548
+ }
549
+ });
550
+ return router;
551
+ }
552
+
553
+ // src/server/cards/mall-home/schema.ts
554
+ import { z as z2 } from "zod";
555
+ var bumpInBannerSchema = z2.object({
556
+ title: z2.string(),
557
+ progressStyle: z2.enum(["bar", "steps"]).optional(),
558
+ totalProgress: z2.string().optional(),
559
+ currentProgress: z2.string().optional(),
560
+ progressUnit: z2.string().optional()
561
+ });
562
+ var memberLoadStateSchema = z2.discriminatedUnion("status", [
563
+ z2.object({ status: z2.literal("loading") }),
564
+ z2.object({ status: z2.literal("unauthenticated") }),
565
+ z2.object({ status: z2.literal("not_enrolled") }),
566
+ z2.object({ status: z2.literal("closed") }),
567
+ z2.object({ status: z2.literal("unknown") }),
568
+ z2.object({
569
+ status: z2.literal("active"),
570
+ balance: z2.number().optional(),
571
+ membershipLabel: z2.string().optional()
572
+ }),
573
+ z2.object({ status: z2.literal("unavailable") }),
574
+ z2.object({ status: z2.literal("error") })
575
+ ]);
576
+ var parkingLoadStateSchema = z2.discriminatedUnion("status", [
577
+ z2.object({ status: z2.literal("loading") }),
578
+ z2.object({ status: z2.literal("unauthenticated") }),
579
+ z2.object({ status: z2.literal("membership_required") }),
580
+ z2.object({ status: z2.literal("empty") }),
581
+ z2.object({
582
+ status: z2.literal("ready"),
583
+ primaryPlate: z2.string(),
584
+ plateCount: z2.number(),
585
+ parkedPlates: z2.array(z2.string()).optional(),
586
+ freeMinutesRemaining: z2.number().optional(),
587
+ parkedMinutes: z2.number().optional()
588
+ }),
589
+ z2.object({ status: z2.literal("unavailable") }),
590
+ z2.object({ status: z2.literal("error") })
591
+ ]);
592
+ var linkedOrderLoadStateSchema = z2.discriminatedUnion("status", [
593
+ z2.object({ status: z2.literal("loading") }),
594
+ z2.object({ status: z2.literal("ready"), banner: bumpInBannerSchema }),
595
+ z2.object({ status: z2.literal("unauthenticated") }),
596
+ z2.object({ status: z2.literal("forbidden") }),
597
+ z2.object({ status: z2.literal("unavailable") }),
598
+ z2.object({ status: z2.literal("error") })
599
+ ]);
600
+ var mallHomePreviewSchema = z2.object({
601
+ mallName: z2.string().optional(),
602
+ showDevServices: z2.boolean().optional(),
603
+ enrollUrl: z2.string().nullable().optional(),
604
+ member: memberLoadStateSchema,
605
+ parking: parkingLoadStateSchema,
606
+ linkedOrder: linkedOrderLoadStateSchema
607
+ });
608
+
609
+ // src/server/cards/mall-home/meta.ts
610
+ var READY_MEMBER = { status: "active", balance: 12860, membershipLabel: "\u9EC4\u91D1\u4F1A\u5458" };
611
+ var READY_PARKING = {
612
+ status: "ready",
613
+ primaryPlate: "\u6D59A12345",
614
+ plateCount: 1,
615
+ parkedPlates: ["\u6D59A12345"],
616
+ freeMinutesRemaining: 86
617
+ };
618
+ var READY_LINKED = {
619
+ status: "ready",
620
+ banner: { title: "\u78B0\u51FA\u60CA\u559C", progressStyle: "steps", totalProgress: "5", currentProgress: "3", progressUnit: "\u7B14" }
621
+ };
622
+ var meta = {
623
+ cardType: "mall-home",
624
+ dataSchema: mallHomePreviewSchema,
625
+ displayName: "\u5546\u5708\u9996\u9875",
626
+ description: "\u9996\u9875\u4E3B\u5C4F\uFF08\u8054\u5355\u8FDB\u5EA6 + \u4F1A\u5458/\u505C\u8F66\u5FEB\u89C8 + \u5F00\u53D1\u6D4B\u8BD5\u5165\u53E3\uFF09\u2014\u2014dev \u9884\u89C8\u4E13\u7528\uFF0C\u4E0D\u51FA\u5361",
627
+ schemaVersion: 1,
628
+ sampleData: {
629
+ mallName: "\u793A\u4F8B\u5546\u573A",
630
+ member: READY_MEMBER,
631
+ parking: READY_PARKING,
632
+ linkedOrder: READY_LINKED
633
+ },
634
+ samples: [
635
+ // ── 会员轴(停车/联单保持就绪)──
636
+ { label: "\u672A\u5165\u4F1A", group: "\u4F1A\u5458\u8F74", data: { mallName: "\u793A\u4F8B\u5546\u573A", member: { status: "not_enrolled" }, parking: READY_PARKING, linkedOrder: READY_LINKED } },
637
+ { label: "\u5DF2\u9000\u4F1A", group: "\u4F1A\u5458\u8F74", note: "\u4E0E\u672A\u5165\u4F1A\u540C\u6E32\u67D3\u5206\u652F", data: { mallName: "\u793A\u4F8B\u5546\u573A", member: { status: "closed" }, parking: READY_PARKING, linkedOrder: READY_LINKED } },
638
+ { label: "\u672A\u767B\u5F55", group: "\u4F1A\u5458\u8F74", data: { mallName: "\u793A\u4F8B\u5546\u573A", member: { status: "unauthenticated" }, parking: READY_PARKING, linkedOrder: READY_LINKED } },
639
+ { label: "\u4F1A\u5458\u5F02\u5E38", group: "\u4F1A\u5458\u8F74", note: "error/unavailable/unknown \u540C\u6E32\u67D3\u5206\u652F", data: { mallName: "\u793A\u4F8B\u5546\u573A", member: { status: "error" }, parking: READY_PARKING, linkedOrder: READY_LINKED } },
640
+ { label: "\u4F1A\u5458\u52A0\u8F7D\u4E2D", group: "\u4F1A\u5458\u8F74", data: { mallName: "\u793A\u4F8B\u5546\u573A", member: { status: "loading" }, parking: READY_PARKING, linkedOrder: READY_LINKED } },
641
+ // ── 停车轴(会员/联单保持就绪)──
642
+ { label: "\u5DF2\u5165\u573A\u8BA1\u8D39\u4E2D", group: "\u505C\u8F66\u8F74", data: { mallName: "\u793A\u4F8B\u5546\u573A", member: READY_MEMBER, parking: { status: "ready", primaryPlate: "\u6D59A12345", plateCount: 1, parkedPlates: ["\u6D59A12345"], parkedMinutes: 95 }, linkedOrder: READY_LINKED } },
643
+ { label: "\u591A\u8F86\u8F66\u5165\u573A", group: "\u505C\u8F66\u8F74", note: "\u53CC\u8F66\u5728\u573A\uFF08freeMinutesRemaining \u7F3A\u5E2D\u4E0D\u6E32\u67D3 N \u8F86\u5206\u652F\uFF09", data: { mallName: "\u793A\u4F8B\u5546\u573A", member: READY_MEMBER, parking: { status: "ready", primaryPlate: "\u6D59A12345", plateCount: 2, parkedPlates: ["\u6D59A12345", "\u6D59B67890"], freeMinutesRemaining: 30 }, linkedOrder: READY_LINKED } },
644
+ { label: "\u8F66\u8F86\u672A\u5165\u573A", group: "\u505C\u8F66\u8F74", data: { mallName: "\u793A\u4F8B\u5546\u573A", member: READY_MEMBER, parking: { status: "ready", primaryPlate: "\u6D59A12345", plateCount: 1 }, linkedOrder: READY_LINKED } },
645
+ { label: "\u8F66\u8F86\u672A\u7ED1\u5B9A", group: "\u505C\u8F66\u8F74", data: { mallName: "\u793A\u4F8B\u5546\u573A", member: READY_MEMBER, parking: { status: "empty" }, linkedOrder: READY_LINKED } },
646
+ { label: "\u9700\u5165\u4F1A", group: "\u505C\u8F66\u8F74", data: { mallName: "\u793A\u4F8B\u5546\u573A", member: READY_MEMBER, parking: { status: "membership_required" }, linkedOrder: READY_LINKED } },
647
+ { label: "\u505C\u8F66\u5F02\u5E38", group: "\u505C\u8F66\u8F74", note: "error/unavailable \u540C\u6E32\u67D3\u5206\u652F", data: { mallName: "\u793A\u4F8B\u5546\u573A", member: READY_MEMBER, parking: { status: "error" }, linkedOrder: READY_LINKED } },
648
+ { label: "\u505C\u8F66\u52A0\u8F7D\u4E2D", group: "\u505C\u8F66\u8F74", data: { mallName: "\u793A\u4F8B\u5546\u573A", member: READY_MEMBER, parking: { status: "loading" }, linkedOrder: READY_LINKED } },
649
+ // ── 联单轴(会员/停车保持就绪)──
650
+ { label: "\u6682\u65E0\u8FDB\u884C\u4E2D\u8054\u5355", group: "\u8054\u5355\u8F74", note: "banner \u65E0\u8FDB\u5EA6\u5B57\u6BB5 = \u6682\u65E0\u53EF\u67E5\u770B\u8054\u5355", data: { mallName: "\u793A\u4F8B\u5546\u573A", member: READY_MEMBER, parking: READY_PARKING, linkedOrder: { status: "ready", banner: { title: "\u78B0\u51FA\u60CA\u559C" } } } },
651
+ { label: "\u8054\u5355\u52A0\u8F7D\u4E2D", group: "\u8054\u5355\u8F74", data: { mallName: "\u793A\u4F8B\u5546\u573A", member: READY_MEMBER, parking: READY_PARKING, linkedOrder: { status: "loading" } } },
652
+ { label: "\u8054\u5355\u672A\u767B\u5F55", group: "\u8054\u5355\u8F74", data: { mallName: "\u793A\u4F8B\u5546\u573A", member: READY_MEMBER, parking: READY_PARKING, linkedOrder: { status: "unauthenticated" } } },
653
+ { label: "\u8054\u5355\u5F02\u5E38", group: "\u8054\u5355\u8F74", note: "error/forbidden/unavailable \u540C\u6E32\u67D3\u5206\u652F", data: { mallName: "\u793A\u4F8B\u5546\u573A", member: READY_MEMBER, parking: READY_PARKING, linkedOrder: { status: "error" } } },
654
+ // ── 组合态 ──
655
+ { label: "\u5168\u90E8\u52A0\u8F7D\u4E2D", group: "\u7EC4\u5408\u6001", data: { mallName: "\u793A\u4F8B\u5546\u573A", member: { status: "loading" }, parking: { status: "loading" }, linkedOrder: { status: "loading" } } },
656
+ { label: "\u5F00\u53D1\u5165\u53E3\u5C55\u5F00", group: "\u7EC4\u5408\u6001", note: "showDevServices = true\uFF08MALL_HOME_DEV_SERVICES \u8BED\u4E49\uFF09", data: { mallName: "\u793A\u4F8B\u5546\u573A", showDevServices: true, member: READY_MEMBER, parking: READY_PARKING, linkedOrder: READY_LINKED } }
657
+ ]
658
+ };
659
+ var meta_default = meta;
660
+
661
+ // src/server/index.ts
662
+ function appRoot() {
663
+ let dir = path.resolve(process.cwd());
664
+ for (let i = 0; i < 4; i++) {
665
+ if (existsSync(path.join(dir, ".tbox", "app.json"))) return dir;
666
+ const parent = path.dirname(dir);
667
+ if (parent === dir) break;
668
+ dir = parent;
669
+ }
670
+ return path.resolve(process.cwd());
671
+ }
672
+ function configDir() {
673
+ return process.env.TBOX_CONFIG_DIR ? path.resolve(process.env.TBOX_CONFIG_DIR) : path.resolve(appRoot(), "config");
674
+ }
675
+ var serverModule = {
676
+ declaration: {
677
+ moduleId: "mall-core"
678
+ },
679
+ // 首页预览卡(dev 预览专用——/_tbox/card-preview 目录收录;无工具出卡路径,chat 零出场)
680
+ cards: {
681
+ "mall-home": meta_default
682
+ },
683
+ preTools,
684
+ async register(ctx) {
685
+ ctx.routes.register("mall-core", createMallHomeRouter(ctx));
686
+ ctx.cards.registerMap(serverModule.cards);
687
+ bindMallInfoContext(ctx);
688
+ const assembly = createScopeAssembly(ctx.integrations?.raw, ctx);
689
+ if (assembly) {
690
+ ctx.domainAssemblies.register(SCOPE_ASSEMBLY_KIND2, assembly);
691
+ ctx.services.register("mall-directory", {
692
+ nearbyMalls: () => assembly.controlPlane.malls.map((m) => ({
693
+ mallId: m.mallId,
694
+ name: m.name,
695
+ address: `${m.name}\uFF08deployment \u914D\u7F6E\uFF09`,
696
+ status: { code: "open", label: "\u8425\u4E1A\u4E2D" }
697
+ })),
698
+ contactPhone: (mallId) => assembly.controlPlane.malls.find((m) => m.mallId === mallId)?.contactPhone
699
+ });
700
+ }
701
+ ctx.services.register(MALL_INFO_CACHE_SERVICE, {
702
+ cachedMallName: (mallId) => cachedMallName(mallId),
703
+ resolveMallInfo: (mallId) => resolveMallInfo(mallId, ctx.integrations)
704
+ });
705
+ ctx.tools.register(mallInfoTool);
706
+ const bumpinPorts = await loadBumpinPorts();
707
+ bumpinPorts?.configureAlipayBumpIn(path.join(configDir(), "bumpin.json"));
708
+ }
709
+ };
710
+ var server_default = serverModule;
711
+
712
+ export {
713
+ cachedMallName,
714
+ resolveMallInfo,
715
+ resolveMallScopeAssembly,
716
+ createScopeAssembly,
717
+ buildDefaultMallContext,
718
+ bindMallInfoContext,
719
+ mallInfoTool,
720
+ preTools,
721
+ createMallHomeRouter,
722
+ serverModule,
723
+ server_default
724
+ };