strategies.ts 32.3 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802
import { createSigner } from '../signing/signers';
import { createGscHeaderSigner, buildGscQuery, processGscSignParams } from './gsc';
import { prepareRpcCall } from './dispatcher';
import { RequestError } from '../core/errors';
import type { GatewayCredential, HeaderSigner, RawRequest, Signer } from '../core/types';
import type { BodySignFn, RequestConfig, ResponseOptions, SignaturePreset } from '../core/facade';

/**
 * 请求方案 / 签名两套正交策略。
 *
 * 门面 `Request` 本身不再知道「有几种网关」「有几种签名」——它只做一件事:
 * 把配置交给 `RequestStrategy.prepare()` 拼出 RawRequest,再统一走响应归一。
 *
 *  · RequestStrategy(方案):URL 怎么拼、签名放哪、该方案默认的响应语义是什么。
 *  · SignatureStrategy(签名):算法本身,可放进请求体(bodySign)或请求头(headerSigner)。
 *
 * 两套都走注册表:内置策略预注册,外部用 registerXxx 加自己的,消费层只写名字。
 * 注意与 types.ts 里的 `GatewayStrategy`(外部系统接入契约)是两层:
 * 那个描述「某个网关长什么样」,这里的 RequestStrategy 描述「请求怎么拼」。
 * rpc-gateway 方案把两者接起来:prepare 从 GatewayStrategy 取落点 / 加签 / 信封,
 * 并与小程序 createRpcDispatcher 共用 prepareRpcCall,消费层因此只传 gateway + 参数。
 */

// ---------------------------------------------------------------------------
// 契约
// ---------------------------------------------------------------------------

export interface SessionValue {
  name: string;
  value: string;
}

export interface PreparedRequest {
  url: string;
  method: RawRequest['method'];
  data: unknown;
  headers: Record<string, string>;
  timeout?: number;
  /** blob / arraybuffer 下载透传。 */
  responseType?: 'json' | 'blob' | 'arraybuffer' | 'text';
  /** host 主壳 axios 的 transformResponse 透传(自定义解包回调)。 */
  transformResponse?: Array<(raw: unknown, headers: Record<string, string>) => unknown>;
  /** 供响应归一时读取的「资源名」(rop 是 RPC 方法名)。 */
  resource: string;
  /** 透传给 RawRequest.normalize(老网关信封在主壳拦截器之前归一)。 */
  normalize?: (raw: unknown) => unknown;
  /** 透传给传输层的附加项(web 主壳需要 withCredentials / responseType)。 */
  withCredentials?: boolean;
  /** 中止信号:由门面在 prepare 之后统一并入,透传到 RawRequest / axios。 */
  signal?: AbortSignal;
}

/** 一个网关方案策略:自带默认配置 + 请求拼装。 */
export interface RequestStrategy {
  id: string;
  /** 该方案的默认配置(响应语义 / transport / Content-Type 等),构造 Request 时自动并入。 */
  defaults?: Partial<RequestConfig>;
  /** 未显式指定 strategy 时,按配置特征自动选中(按注册顺序匹配)。 */
  detect?: (config: RequestConfig) => boolean;
  /** 拼出一次原始传输请求;实现里自行决定用哪个签名策略。 */
  prepare(config: RequestConfig, session?: SessionValue): Promise<PreparedRequest>;
}

/** 一个签名算法策略:请求体签名与/或请求头签名。 */
export interface SignatureStrategy {
  id: string;
  /** 返回真正发送的完整请求体。 */
  bodySign?: BodySignFn;
  /** 返回要并入请求头的字段。 */
  headerSigner?: HeaderSigner;
}

export type SignatureSpec =
  | SignaturePreset
  | string
  | SignatureStrategy
  | Signer
  | HeaderSigner
  | BodySignFn
  | undefined;

export type RequestStrategySpec = string | RequestStrategy | undefined;

// ---------------------------------------------------------------------------
// 注册表
// ---------------------------------------------------------------------------

const requestStrategies = new Map<string, RequestStrategy>();
const signatureStrategies = new Map<string, SignatureStrategy | (() => SignatureStrategy)>();

export function defineRequestStrategy(def: RequestStrategy): RequestStrategy {
  return def;
}

export function defineSignatureStrategy(id: string, def: Omit<SignatureStrategy, 'id'>): SignatureStrategy {
  return { id, ...def };
}

/** 注册(或覆盖)一个网关方案策略。内置名也可覆盖,用于灰度替换实现。 */
export function registerRequestStrategy(def: RequestStrategy): RequestStrategy {
  requestStrategies.set(def.id, def);
  return def;
}

/** 注册(或覆盖)一个签名策略。可传对象,也可传惰性工厂(WebCrypto 之类在调用时才初始化)。 */
export function registerSignatureStrategy(
  id: string,
  def: Omit<SignatureStrategy, 'id'> | SignatureStrategy | (() => SignatureStrategy),
): void {
  signatureStrategies.set(
    id,
    typeof def === 'function' ? (def as () => SignatureStrategy) : { id, ...(def as Omit<SignatureStrategy, 'id'>) },
  );
}

export function listRequestStrategies(): string[] {
  return [...requestStrategies.keys()];
}

export function listSignatureStrategies(): string[] {
  return [...signatureStrategies.keys()];
}

/** 按名字或实例解析方案策略;省略时按 detect 自动匹配,兜底 plain。 */
export function resolveRequestStrategy(configOrSpec: RequestConfig | RequestStrategySpec): RequestStrategy {
  const config = (configOrSpec ?? {}) as RequestConfig;
  const spec: RequestStrategySpec =
    typeof configOrSpec === 'string' || (configOrSpec && typeof configOrSpec === 'object' && 'prepare' in configOrSpec)
      ? (configOrSpec as RequestStrategySpec)
      : config.strategy ?? config.profile;

  if (spec && typeof spec === 'object') return spec as RequestStrategy;
  if (typeof spec === 'string') {
    const found = requestStrategies.get(spec);
    if (!found) {
      throw new RequestError(`未知的网关方案策略「${spec}」,已注册:${listRequestStrategies().join(', ')}`, {
        code: 'UNKNOWN_REQUEST_STRATEGY',
      });
    }
    return found;
  }

  for (const candidate of requestStrategies.values()) {
    if (candidate.detect?.(config)) return candidate;
  }
  return requestStrategies.get('plain') as RequestStrategy;
}

/** 按名字 / 实例 / 老式 Signer 解析签名策略。未知名字直接报错,避免悄悄退化成错误算法。 */
export function resolveSignatureStrategy(spec: SignatureSpec): SignatureStrategy | undefined {
  if (spec === undefined || spec === null) return undefined;
  if (typeof spec === 'string') {
    const entry = signatureStrategies.get(spec);
    if (!entry) {
      throw new RequestError(`未知的签名策略「${spec}」,已注册:${listSignatureStrategies().join(', ')}`, {
        code: 'UNKNOWN_SIGNATURE_STRATEGY',
      });
    }
    // 注册项可能是惰性工厂(WebCrypto 之类调用时才初始化)。
    return typeof entry === 'function' ? (entry as () => SignatureStrategy)() : entry;
  }
  // 直接给函数:视作一个内联的 bodySign 策略。消费层传 `signature: sign` 即可,
  // 不需要先 strategies.signature.register 起一个名字。
  if (typeof spec === 'function') return { id: 'inline-body-sign', bodySign: spec as BodySignFn };
  if ('bodySign' in spec || 'headerSigner' in spec) return spec as SignatureStrategy;
  if ('fields' in spec) return { id: (spec as Signer).id, bodySign: bodySignFromSigner(spec as Signer) };
  if ('headers' in spec) return { id: (spec as HeaderSigner).id, headerSigner: spec as HeaderSigner };
  return undefined;
}

// ---------------------------------------------------------------------------
// 内部工具(从 facade 原样搬入,保证 canonical / URL / 签名原文逐字节不变)
// ---------------------------------------------------------------------------

const DEFAULT_FIXED = { v: '1.0.0', format: 'json', locale: 'zh_CN', source: 'dj-wechat' };

/** 平铺字符串化:字符串原样、数/布尔 String、其它 JSON.stringify。嵌套结构请用自定义签名策略。 */
function flattenSimple(params: Record<string, unknown>): Record<string, string> {
  const out: Record<string, string> = {};
  for (const [key, value] of Object.entries(params)) {
    if (value === null || value === undefined) continue;
    out[key] = typeof value === 'string' ? value : typeof value === 'object' ? JSON.stringify(value) : String(value);
  }
  return out;
}

function joinURL(baseURL: string | undefined, resource: string): string {
  if (!baseURL) return resource;
  if (/^https?:\/\//i.test(resource)) return resource;
  return `${baseURL.replace(/\/$/, '')}${resource.startsWith('/') ? resource : `/${resource}`}`;
}

/** 拼接上下文路径与资源路径:去掉多余前导斜杠后合并,仅在段间补一个 /(不碰协议里的 //)。 */
function joinUrlSegments(prefix: string, resource: string): string {
  const seg = [prefix.replace(/\/+$/, ''), resource.replace(/^\//, '')].filter(Boolean).join('/');
  if (!seg) return '';
  // prefix 本身就带前导 /(context-path 常规形态),此时不能再补,否则会拼出 //youjia/...
  return seg.startsWith('/') ? seg : `/${seg}`;
}

/** 确定性查询串:按 key 升序、过滤 undefined/null、encodeURIComponent 逐键值编码后用 & 连接。 */
function buildPlainQuery(params: Record<string, unknown>): string {
  const keys = Object.keys(params)
    .filter((k) => params[k] !== undefined && params[k] !== null)
    .sort();
  if (!keys.length) return '';
  return keys
    .map((k) => `${encodeURIComponent(k)}=${encodeURIComponent(String(params[k]))}`)
    .join('&');
}

/** 把 resource 拆成「路径段」与「内联查询串」(URL 里自带的 ?x=y)。 */
function splitResource(resource: string): { path: string; inlineQuery: string } {
  const qIdx = resource.indexOf('?');
  if (qIdx < 0) return { path: resource, inlineQuery: '' };
  return { path: resource.slice(0, qIdx), inlineQuery: resource.slice(qIdx + 1) };
}

/** 内联 ?x=y 与 params 合并后整体按 token 排序(对齐 buildCanonicalTarget)。 */
function composeQuery(inlineQuery: string, params: Record<string, unknown>): string {
  const inlineTokens = inlineQuery ? inlineQuery.split('&').filter(Boolean) : [];
  const paramQuery = buildPlainQuery(params);
  const paramTokens = paramQuery ? paramQuery.split('&') : [];
  return [...inlineTokens, ...paramTokens].sort().join('&');
}

/** Signer → 请求体签名函数(内置 sha1 / md5 / sdk / hmac 预设共用)。 */
function bodySignFromSigner(signer: Signer): BodySignFn {
  return async (params, secret, noSignAttr = []) => {
    const flat = flattenSimple(params);
    const fields = await Promise.resolve(
      signer.fields({
        method: flat.method ?? '',
        appKey: flat.appKey ?? '',
        secret,
        version: flat.v ?? '1.0.0',
        format: flat.format ?? 'json',
        params: flat,
        timestamp: Date.now(),
        exclude: noSignAttr,
      }),
    );
    return { ...flat, ...fields };
  };
}

/** 一次请求里真正生效的签名策略:config.signature 优先,config.sign 兼容旧写法。 */
function signatureOf(config: RequestConfig): SignatureStrategy | undefined {
  return resolveSignatureStrategy(config.signature ?? config.sign);
}

/** 请求体签名:signBody 是最高优先级的逃生口(各 app 已有的 qs 摊平实现)。 */
function bodySignOf(config: RequestConfig): BodySignFn | undefined {
  return config.signBody ?? signatureOf(config)?.bodySign;
}

function headerSignerOf(config: RequestConfig): HeaderSigner | undefined {
  return signatureOf(config)?.headerSigner;
}

// ---------------------------------------------------------------------------
// 内置签名策略(六个预设 + rop-sha1)
// ---------------------------------------------------------------------------

registerSignatureStrategy('none', {});
registerSignatureStrategy('sha1', () => ({ id: 'sha1', bodySign: bodySignFromSigner(createSigner({ kind: 'rop' })) }));
registerSignatureStrategy('md5', () => ({ id: 'md5', bodySign: bodySignFromSigner(createSigner({ kind: 'md5' })) }));
registerSignatureStrategy('sdk', () => ({ id: 'sdk', bodySign: bodySignFromSigner(createSigner({ kind: 'sdk' })) }));
registerSignatureStrategy('hmac-sha256', () => {
  const inner = createSigner({ kind: 'hmac' });
  return {
    id: 'hmac-sha256',
    bodySign: bodySignFromSigner(inner),
    headerSigner: {
      id: 'hmac-sha256',
      async headers(input) {
        const fields = await Promise.resolve(
          inner.fields({
            method: input.method,
            params: input.params ?? {},
            appKey: input.appKey,
            secret: input.secret,
            timestamp: Date.now(),
            version: '1.0.0',
            format: 'json',
            exclude: input.exclude,
          }),
        );
        const out: Record<string, string> = {};
        for (const [key, value] of Object.entries(fields)) out[key] = String(value);
        return out;
      },
    },
  };
});
registerSignatureStrategy('gsc-hmac', () => ({ id: 'gsc-hmac', headerSigner: createGscHeaderSigner() }));

/**
 * ROP 网关的「原样 params」SHA1 签名(points 老壳 getData 的口径):
 * 不摊平、只取回 sign 字段,与 bodySignFromSigner 的摊平版是两种不同策略。
 */
registerSignatureStrategy('rop-sha1', () => {
  const signer = createSigner({ kind: 'rop', id: 'rop-sha1' });
  return {
    id: 'rop-sha1',
    bodySign: async (params, secret, noSignAttr = []) => {
      const signed = await Promise.resolve(
        signer.fields({
          method: String(params.method ?? ''),
          appKey: String(params.appKey ?? ''),
          secret,
          version: String(params.v ?? '1.0.0'),
          format: String(params.format ?? 'json'),
          params,
          // SHA1 预设的 excludeDefaults 已剔除 timestamp,此值只是满足 SignInput 契约,
          // 不进签名原文(与 points 旧 getData 逐字节一致)。
          timestamp: Date.now(),
          exclude: noSignAttr,
        }),
      );
      return { ...params, sign: signed.sign };
    },
  };
});

// ---------------------------------------------------------------------------
// 内置网关方案策略
// ---------------------------------------------------------------------------

const ROP_RESPONSE: ResponseOptions = {
  codeKey: 'code',
  successCodes: ['0'],
  logoutCodes: [20, 21],
};

/** rop:method 名作资源,落点 = host + 路径段 + router?method=,签名进请求体。 */
const ropStrategy: RequestStrategy = defineRequestStrategy({
  id: 'rop',
  defaults: { transport: 'auto', response: ROP_RESPONSE },
  detect: (config) => Boolean(config.hosts || config.pathEnum || config.defaultPath),
  async prepare(config, session) {
    const method = String(config.url ?? '');
    const hostType = String(config.hostType ?? 'scrm');
    const project = config.projectName ?? config.getProjectName?.(method) ?? method.split('.')[2] ?? '';
    const origin = config.hosts?.[hostType] ?? config.baseURL ?? '';
    if (!origin) throw new RequestError(`未配置 hostType「${hostType}」的网关域名`, { config });

    const pathSegment = config.path
      ?? (config.pathEnum?.[project] ?? config.defaultPath ?? `/rop-${hostType}-${project}/`) + 'router';
    const url = `${origin}${pathSegment}?method=${method}`;

    const djCred = hostType === 'dj' ? config.djSecretKey : undefined;
    const cred = config.resolveCredential?.(project, hostType)
      ?? djCred
      ?? config.secretKey?.[project]
      ?? config.defaultCredential
      ?? { appKey: config.appKey ?? '', secret: config.appSecret ?? '' };

    const fixed = { ...DEFAULT_FIXED, ...config.fixedParams };
    const business = { ...((config.data ?? config.params ?? {}) as Record<string, unknown>) };
    // 控制字段只参与编排,不进请求体/签名原文(老壳 getData 里也是先摘掉再签)。
    const inlineNoSignAttr = business.noSignAttr as string[] | undefined;
    delete business.projectName;
    delete business.apiProjectName;
    delete business.noSignAttr;
    const delSessionId = Boolean(business.delSessionId);
    delete business.delSessionId;
    const body: Record<string, unknown> = {
      ...business,
      method,
      v: fixed.v,
      format: fixed.format,
      locale: fixed.locale,
      source: fixed.source,
      appKey: cred.appKey,
    };
    if (delSessionId) delete body.sessionId;
    else if (session && !body[session.name]) body[session.name] = session.value;

    const noSignAttr = config.noSignAttr ?? inlineNoSignAttr;
    const signFn: BodySignFn = bodySignOf(config) ?? ((p) => flattenSimple(p));
    const signed = await signFn(body, cred.secret, noSignAttr);

    // POST 走表单体;GET 由 wx 把 data 拼进 query,不带 content-type(对齐老壳 get() 的 header)。
    const httpMethod = String(config.method ?? 'POST').toUpperCase();
    const headers: Record<string, string> = {
      ...(httpMethod === 'GET' || config.contentType === false
        ? {}
        : { 'content-type': config.contentType ?? 'application/x-www-form-urlencoded' }),
      ...(config.headers ?? {}),
    };
    const merchantId = config.getMerchantId?.();
    if (merchantId) headers.merchantId = merchantId;

    return {
      url,
      method: (config.method ?? 'POST') as RawRequest['method'],
      data: signed,
      headers,
      timeout: config.timeout,
      resource: method,
      normalize: config.normalize,
    };
  },
});

/** gsc:REST + 查询串参数 + HMAC 头部签名 + JSON body。 */
const gscStrategy: RequestStrategy = defineRequestStrategy({
  id: 'gsc',
  defaults: { response: ROP_RESPONSE },
  detect: (config) => config.sign === 'gsc-hmac' || config.signature === 'gsc-hmac',
  async prepare(config, session) {
    const resource = String(config.url ?? '');
    const method = String(config.method ?? 'GET').toUpperCase();
    const params: Record<string, unknown> = { ...(config.params ?? {}) };
    if (session) params[session.name] = session.value;
    const data = config.data ?? {};
    const headers: Record<string, string> = {
      ...(config.contentType === false
        ? {}
        : { 'Content-Type': config.contentType ?? 'application/json;charset=UTF-8' }),
      ...(config.headers ?? {}),
    };

    const signer = headerSignerOf(config) ?? createGscHeaderSigner();
    Object.assign(headers, await Promise.resolve(signer.headers({
      method,
      params: config.signature === 'gsc-hmac' || config.sign === 'gsc-hmac'
        ? processGscSignParams(method, params, data as Record<string, unknown>)
        : params,
      data,
      appKey: config.appKey ?? '',
      secret: config.appSecret ?? '',
      exclude: config.noSignAttr,
    })));

    const path = joinURL(config.baseURL, resource);
    const query = buildGscQuery(params);
    return {
      url: `${path}${query ? `${path.includes('?') ? '&' : '?'}${query}` : ''}`,
      method: method as RawRequest['method'],
      data,
      headers,
      timeout: config.timeout,
      resource,
      normalize: config.normalize,
    };
  },
});

/** plain:baseURL + context-path + 路径 + 查询参数,可选签名(头部或请求体)。 */
async function preparePlain(config: RequestConfig, session?: SessionValue): Promise<PreparedRequest> {
  const resource = String(config.url ?? '');
  const method = String(config.method ?? 'GET').toUpperCase();
  const params: Record<string, unknown> = { ...(config.params ?? {}) };
  if (session) params[session.name] = session.value;
  const headers: Record<string, string> = {
    ...(config.contentType === false
      ? {}
      : { 'Content-Type': config.contentType ?? 'application/json;charset=UTF-8' }),
    ...(config.headers ?? {}),
  };

  // canonical 第 2 行 path(相对 baseURL,已含 context-path)与第 3 行 query;
  // 同一份 query 既拼进线上 URL、又透传给头部签名器,保证「线上发什么 == 签名算什么」。
  // query 需并入 resource 内联的 ?x=y 并与 params 合并后整体排序(对齐老 host 的 buildCanonicalTarget)。
  const isAbsolute = /^https?:\/\//i.test(resource);
  const { path: resPath, inlineQuery } = splitResource(resource);
  const contextPath = config.contextPath ?? '';
  const path = isAbsolute
    ? resPath
    : contextPath && resPath.startsWith(`${contextPath}/`)
      // 调用方已自带 context-path:不再重复拼一次(老壳 interceptor 的同款守卫)。
      ? resPath
      : joinUrlSegments(contextPath, resPath);
  const query = composeQuery(inlineQuery, params);

  // 头部签名器(RSA / gsc-hmac / hmac)需要 path/query/media/body 来构造 canonical。
  // media / body 的口径必须与老 web 拦截器逐字节一致:
  //   · 只有「存在请求体」时才默认 application/json,GET 无体 → 空串;
  //   · 有请求体时统一 JSON.stringify 后发字符串,签名原文与实际字节同源。
  const headerSigner = headerSignerOf(config);
  const isForm = typeof FormData !== 'undefined' && config.data instanceof FormData;
  const ctHeader = headers['Content-Type'] ?? headers['content-type'];
  const ctVal = typeof ctHeader === 'string' ? ctHeader : '';
  const hasBody = isForm || Boolean(config.data);
  const mediaType = isForm
    ? 'multipart/form-data'
    : (ctVal || (hasBody ? 'application/json' : ''))
      .split(';')[0]
      .trim()
      .toLowerCase();
  const bodyString = isForm
    ? ''
    : typeof config.data === 'string'
      ? config.data
      : config.data && typeof config.data === 'object'
        ? JSON.stringify(config.data)
        : config.data
          ? String(config.data)
          : '';
  if (headerSigner) {
    Object.assign(headers, await Promise.resolve(headerSigner.headers({
      method, params, data: config.data,
      appKey: config.appKey ?? '', secret: config.appSecret ?? '',
      exclude: config.noSignAttr,
      url: joinURL(config.baseURL, path) + (query ? `?${query}` : ''),
      path, query, mediaType, bodyString,
    })));
  }

  let payload: unknown = config.data;
  const bodySign = bodySignOf(config);
  if (bodySign && !isForm && typeof payload === 'object' && payload !== null) {
    payload = await bodySign(
      { ...(payload as Record<string, unknown>), appKey: config.appKey ?? '' },
      config.appSecret ?? '',
      config.noSignAttr,
    );
  }

  // 有请求体且调用方没显式指定 Content-Type 时补 application/json(老 web 拦截器在加签之后做,
  // 因此不参与 canonical 的 media 计算)。contentType:false 只是「不预置默认头」,不是「永不带头」。
  if (hasBody && !isForm && !headers['Content-Type'] && !headers['content-type']) {
    headers['Content-Type'] = 'application/json';
  }

  // 请求体原样交给传输层(wx 直接发对象、axios / fetch 各自 JSON 化)。
  // 签名原文 bodyString 与「对象 JSON.stringify」逐字节一致,因此不必在此提前序列化。
  const wireUrl = joinURL(config.baseURL, path) + (query ? `${path.includes('?') ? '&' : '?'}${query}` : '');
  return {
    url: wireUrl,
    method: method as RawRequest['method'],
    data: payload,
    headers,
    timeout: config.timeout,
    responseType: config.responseType,
    transformResponse: config.transformResponse,
    withCredentials: config.withCredentials === true,
    resource,
    normalize: config.normalize,
  };
}

const plainStrategy: RequestStrategy = defineRequestStrategy({
  id: 'plain',
  prepare: preparePlain,
});

/** web 主壳方案:plain 的 URL/canonical 口径 + 主壳那套响应语义(ApiResult 信封 / 401 登出 / blob)。 */
const webHostStrategy: RequestStrategy = defineRequestStrategy({
  id: 'web-host',
  defaults: {
    contentType: false,
    timeout: 20000,
    response: {
      codeKey: 'code',
      successCodes: [200],
      logoutCodes: [401, 10002],
      dataMode: 'envelope',
      messageKey: 'message',
      toastOnError: false,
      binaryHeaders: true,
    },
    // 还原成调用方熟悉的老错误对象:传输层错误给出原始 AxiosError;
    // 业务错误给出带 code / message / data 的 RequestError。
    errorHandler: (err) => {
      throw err.cause ?? err;
    },
  },
  prepare: preparePlain,
});

/**
 * rpc-gateway:业务只说「哪个网关 + 方法名 + 业务参数」。
 *
 * 落点 / fixedParams 合并 / 加签 / 令牌头 / 信封归一全部来自 registerGateway 登记的
 * GatewayStrategy,装配知识一丝不泄漏到消费层。组装实现与小程序 createRpcDispatcher
 * 共用 prepareRpcCall,两条链路因此永远字节一致。
 */
const rpcGatewayStrategy: RequestStrategy = defineRequestStrategy({
  id: 'rpc-gateway',
  async prepare(config, session) {
    const gateway = String(config.gateway ?? '');
    if (!gateway) {
      throw new RequestError(
        'rpc-gateway 方案需要指定 gateway(单次调用传 { gateway },或在预设里固定)',
        { code: 'GATEWAY_REQUIRED' },
      );
    }
    const resolveCredential = config.gatewayCredential;
    if (!resolveCredential) {
      throw new RequestError('rpc-gateway 方案需要 gatewayCredential(凭据注入函数)', {
        code: 'GATEWAY_CREDENTIAL_REQUIRED',
      });
    }

    const method = String(config.url ?? '');
    const params = (config.data ?? config.params ?? {}) as Record<string, unknown>;
    const raw = await prepareRpcCall(
      {
        gateway,
        method,
        params,
        signed: config.signed,
        unsignedKeys: config.unsignedKeys ?? config.noSignAttr,
      },
      {
        resolveCredential,
        resolveToken: config.gatewayToken,
        timeout: config.timeout,
        session,
      },
    );

    return {
      url: raw.url,
      method: raw.method,
      data: raw.data,
      headers: { ...(config.headers ?? {}), ...(raw.headers ?? {}) },
      timeout: raw.timeout,
      resource: method,
      normalize: raw.normalize,
    };
  },
});

registerRequestStrategy(plainStrategy);
registerRequestStrategy(ropStrategy);
registerRequestStrategy(gscStrategy);
registerRequestStrategy(webHostStrategy);
registerRequestStrategy(rpcGatewayStrategy);

// ---------------------------------------------------------------------------
// 消费层预设:前端只传环境参数 / 业务语义,不碰实现开关
// ---------------------------------------------------------------------------

function withDefaults(defaults: RequestConfig, env: RequestConfig): RequestConfig {
  return {
    ...defaults,
    ...env,
    ...(defaults.response || env.response
      ? { response: { ...defaults.response, ...env.response } }
      : {}),
  };
}

export interface RopPresetOptions extends RequestConfig {
  /** 登录态失效后由页面重发(小程序老壳语义):自动置 logoutPending / errorPending。 */
  loginReplay?: boolean;
  /** 成功仍返回完整信封、其它业务码一律 resolve(usedcar 老壳语义)。 */
  legacyEnvelope?: boolean;
}

/** ROP-router 方案:老网关的 code/登出码/transport 已内置,只需给域名、凭据、签名与环境钩子。 */
export function ropPreset(options: RopPresetOptions = {}): RequestConfig {
  const { loginReplay, legacyEnvelope, ...env } = options;
  return withDefaults(
    {
      strategy: 'rop',
      response: {
        ...(loginReplay ? { logoutPending: true, errorPending: true } : {}),
        ...(legacyEnvelope ? { dataMode: 'envelope' as const, resolveOnOther: true } : {}),
      },
    },
    env,
  );
}

/** GSC / glsk 方案:HMAC 头签名 + REST,credential 由 appKey/appSecret 传入。 */
export function gscPreset(options: RequestConfig = {}): RequestConfig {
  return withDefaults({ strategy: 'gsc', signature: 'gsc-hmac' }, options);
}

/** web 主壳方案:plain canonical + ApiResult 信封 + 401 登出 + 文件流 headers;注入 RSA 签名策略即可。 */
export function webHostPreset(options: RequestConfig = {}): RequestConfig {
  return withDefaults({ strategy: 'web-host' }, options);
}

/** 普通 REST:不带任何方案假设,只剩「选 plain」这一件事,其余走门面默认。 */
export function restPreset(options: RequestConfig = {}): RequestConfig {
  return withDefaults({ strategy: 'plain' }, options);
}

export interface RpcGatewayPresetOptions extends RequestConfig {
  /** 运行时凭据注入:密钥 / 域名留在本域,包内不持有任何字面量。 */
  gatewayCredential: (id: string) => GatewayCredential;
  /** 会话令牌提供器(主壳登录态 / 网关侧令牌)。 */
  gatewayToken?: () => string;
  /** 单网关应用可固定默认 gateway,单次调用就不必再传。 */
  gateway?: string;
}

/**
 * RPC 网关方案:消费层只写 `request.post(method, params, { gateway })`。
 *
 * 装配层只给环境参数(transport / 凭据注入 / 令牌 / 超时);网关怎么加签、落在哪个
 * router、信封怎么读,全由 registerGateway 登记的 GatewayStrategy 决定。
 */
export function rpcGatewayPreset(options: RpcGatewayPresetOptions): RequestConfig {
  return withDefaults({ strategy: 'rpc-gateway' }, options);
}

/**
 * 注册表与高级装配入口。常规消费请直接用 `clients.ts` 的 createXxxClient 工厂;
 * 只有「注册自定义方案 / 覆盖内置实现 / 按名字复用已注册签名」时才需要碰这里:
 *
 * ```js
 * import { createRequest, strategies } from '@uj/api-core'
 * strategies.signature.register('ours', { bodySign: sign })
 * const api = createRequest(strategies.rop({ hosts, secretKey, signature: 'ours', onLoginRequired }))
 * api.post('scrm.api.shopmall.order.list', { pageNo: 1 })
 * ```
 */
export const strategies = {
  rop: ropPreset,
  gsc: gscPreset,
  webHost: webHostPreset,
  rest: restPreset,
  rpcGateway: rpcGatewayPreset,
  request: {
    define: defineRequestStrategy,
    register: registerRequestStrategy,
    resolve: resolveRequestStrategy,
    list: listRequestStrategies,
  },
  signature: {
    define: defineSignatureStrategy,
    register: registerSignatureStrategy,
    resolve: resolveSignatureStrategy,
    list: listSignatureStrategies,
  },
};

// ---------------------------------------------------------------------------
// 新版统一策略入口:createStrategy / createClient 共用这一套 kind 映射
// ---------------------------------------------------------------------------

/** 方案种类 —— 不传即最新版 'rpc-gateway';其余都是老系统,必须显式传。 */
export type StrategyKind = 'rpc-gateway' | 'rop' | 'gsc' | 'web-host' | 'rest';

/** createStrategy / createClient 的公共入参:选型靠 kind,其余就是普通的 RequestConfig。 */
export interface CreateStrategyOptions extends RequestConfig {
  /** 方案种类,默认 'rpc-gateway'。 */
  kind?: StrategyKind;
  /** kind='rop':小程序老壳的登录重发语义。 */
  loginReplay?: boolean;
  /** kind='rop':usedcar 老壳的完整信封语义。 */
  legacyEnvelope?: boolean;
  /** kind='rpc-gateway':运行时凭据注入(请求时才真正需要)。 */
  gatewayCredential?: (id: string) => GatewayCredential;
  /** kind='rpc-gateway':会话令牌提供器。 */
  gatewayToken?: () => string;
  /** kind='rpc-gateway':单网关应用可固定默认 gateway。 */
  gateway?: string;
}

function strategyConfig(options: CreateStrategyOptions): RequestConfig {
  const { kind = 'rpc-gateway', loginReplay, legacyEnvelope, ...env } = options;
  switch (kind) {
    case 'rpc-gateway':
      return rpcGatewayPreset(env as RpcGatewayPresetOptions);
    case 'rop':
      return ropPreset({ ...env, loginReplay, legacyEnvelope } as RopPresetOptions);
    case 'gsc':
      return gscPreset(env);
    case 'web-host':
      return webHostPreset(env);
    case 'rest':
      return restPreset(env);
    default:
      throw new RequestError(`未知的策略 kind: ${String(kind)}`, { code: 'UNKNOWN_STRATEGY' });
  }
}

/**
 * 【新版统一策略入口】生成一份 RequestConfig;常规消费直接用 createClient,不需要碰这里。
 *
 * ```ts
 * createStrategy()                                  // 最新:rpc-gateway
 * createStrategy({ kind: 'rop', hosts, secretKey }) // 老系统:ROP-router
 * createStrategy({ kind: 'web-host', sender })      // 老系统:web 主壳
 * ```
 *
 * 注册自定义方案 / 覆盖内置实现的高级能力挂在同名静态属性上:
 * `createStrategy.define/register/resolve/list`、`createStrategy.signature.*`。
 */
export const createStrategy = Object.assign(
  (options: CreateStrategyOptions = {}): RequestConfig => strategyConfig(options),
  {
    define: defineRequestStrategy,
    register: registerRequestStrategy,
    resolve: resolveRequestStrategy,
    list: listRequestStrategies,
    signature: {
      define: defineSignatureStrategy,
      register: registerSignatureStrategy,
      resolve: resolveSignatureStrategy,
      list: listSignatureStrategies,
    },
  },
);