refactor flows into canonical runtime architecture

This commit is contained in:
QLHazyCoder
2026-05-21 07:21:34 +08:00
parent e2485d2e64
commit a7b35ee11a
167 changed files with 9034 additions and 3032 deletions
-688
View File
@@ -1,688 +0,0 @@
(function attachMultiPageFlowCapabilities(root, factory) {
root.MultiPageFlowCapabilities = factory();
})(typeof self !== 'undefined' ? self : globalThis, function createFlowCapabilitiesModule() {
const rootScope = typeof self !== 'undefined' ? self : globalThis;
const flowRegistryApi = rootScope.MultiPageFlowRegistry || {};
const contributionRegistryApi = rootScope.MultiPageContributionRegistry || {};
const settingsSchemaApi = rootScope.MultiPageSettingsSchema || {};
const DEFAULT_FLOW_ID = flowRegistryApi.DEFAULT_FLOW_ID || 'openai';
const DEFAULT_OPENAI_TARGET_ID = flowRegistryApi.DEFAULT_OPENAI_TARGET_ID || 'cpa';
const SIGNUP_METHOD_EMAIL = 'email';
const SIGNUP_METHOD_PHONE = 'phone';
const PLUS_ACCOUNT_ACCESS_STRATEGY_OAUTH = 'oauth';
const PLUS_ACCOUNT_ACCESS_STRATEGY_SUB2API_CODEX_SESSION = 'sub2api_codex_session';
const PLUS_ACCOUNT_ACCESS_STRATEGY_CPA_CODEX_SESSION = 'cpa_codex_session';
const VALID_OPENAI_TARGET_IDS = Array.isArray(flowRegistryApi.OPENAI_TARGET_IDS)
? flowRegistryApi.OPENAI_TARGET_IDS.slice()
: ['cpa', 'sub2api', 'codex2api'];
const REGISTERED_FLOW_IDS = Array.isArray(flowRegistryApi.getRegisteredFlowIds?.())
? flowRegistryApi.getRegisteredFlowIds().map((flowId) => String(flowId || '').trim().toLowerCase()).filter(Boolean)
: [DEFAULT_FLOW_ID];
const REGISTERED_FLOW_ID_SET = new Set(REGISTERED_FLOW_IDS);
const DEFAULT_FLOW_CAPABILITIES = Object.freeze({
supportsEmailSignup: true,
supportsPhoneSignup: false,
supportsPhoneVerificationSettings: false,
supportsPlusMode: false,
supportsContributionMode: false,
supportsAccountContribution: false,
supportsOpenAiOAuthContribution: false,
contributionAdapterIds: [],
supportedTargetIds: [],
supportsLuckmail: false,
supportsOauthTimeoutBudget: false,
canSwitchFlow: true,
stepDefinitionMode: 'default',
targetSelectorLabel: '来源',
});
const FLOW_CAPABILITIES = Object.freeze(
Object.fromEntries(
(typeof flowRegistryApi.getRegisteredFlowIds === 'function'
? flowRegistryApi.getRegisteredFlowIds()
: [DEFAULT_FLOW_ID]
).map((flowId) => [
flowId,
Object.freeze({
...DEFAULT_FLOW_CAPABILITIES,
...(typeof flowRegistryApi.getFlowCapabilities === 'function'
? flowRegistryApi.getFlowCapabilities(flowId)
: {}),
}),
])
)
);
const DEFAULT_TARGET_CAPABILITIES = Object.freeze({
supportsPhoneSignup: true,
requiresPhoneSignupWarning: false,
supportedPlusAccountAccessStrategies: Object.freeze([PLUS_ACCOUNT_ACCESS_STRATEGY_OAUTH]),
});
const MODE_SWITCH_RELEVANT_KEYS = Object.freeze([
'activeFlowId',
'accountContributionEnabled',
'panelMode',
'phoneVerificationEnabled',
'plusModeEnabled',
'signupMethod',
'plusAccountAccessStrategy',
'openaiIntegrationTargetId',
'kiroTargetId',
]);
const OPENAI_TARGET_CAPABILITIES = Object.freeze({
cpa: Object.freeze({
supportsPhoneSignup: true,
requiresPhoneSignupWarning: true,
supportedPlusAccountAccessStrategies: Object.freeze([
PLUS_ACCOUNT_ACCESS_STRATEGY_OAUTH,
PLUS_ACCOUNT_ACCESS_STRATEGY_CPA_CODEX_SESSION,
]),
}),
sub2api: Object.freeze({
supportsPhoneSignup: true,
requiresPhoneSignupWarning: false,
supportedPlusAccountAccessStrategies: Object.freeze([
PLUS_ACCOUNT_ACCESS_STRATEGY_OAUTH,
PLUS_ACCOUNT_ACCESS_STRATEGY_SUB2API_CODEX_SESSION,
]),
}),
codex2api: Object.freeze({
supportsPhoneSignup: true,
requiresPhoneSignupWarning: false,
supportedPlusAccountAccessStrategies: Object.freeze([PLUS_ACCOUNT_ACCESS_STRATEGY_OAUTH]),
}),
});
function normalizeFlowId(value = '', fallback = DEFAULT_FLOW_ID) {
if (typeof flowRegistryApi.normalizeFlowId === 'function') {
return flowRegistryApi.normalizeFlowId(value, fallback);
}
const normalized = String(value || '').trim().toLowerCase();
return normalized || String(fallback || '').trim().toLowerCase() || DEFAULT_FLOW_ID;
}
function normalizeCapabilityFlowId(value = '', fallback = DEFAULT_FLOW_ID) {
const normalized = String(value || '').trim().toLowerCase();
if (normalized) {
return normalized;
}
return normalizeFlowId(fallback, DEFAULT_FLOW_ID);
}
function isRegisteredFlowId(flowId = '') {
const normalized = String(flowId || '').trim().toLowerCase();
return Boolean(normalized) && REGISTERED_FLOW_ID_SET.has(normalized);
}
function normalizeOpenAiTargetId(value = '', fallback = DEFAULT_OPENAI_TARGET_ID) {
const normalized = String(value || '').trim().toLowerCase();
if (VALID_OPENAI_TARGET_IDS.includes(normalized)) {
return normalized;
}
const fallbackValue = String(fallback || '').trim().toLowerCase();
return VALID_OPENAI_TARGET_IDS.includes(fallbackValue)
? fallbackValue
: DEFAULT_OPENAI_TARGET_ID;
}
function normalizeSignupMethod(value = '') {
return String(value || '').trim().toLowerCase() === SIGNUP_METHOD_PHONE
? SIGNUP_METHOD_PHONE
: SIGNUP_METHOD_EMAIL;
}
function normalizePlusAccountAccessStrategy(value = '') {
const normalized = String(value || '').trim().toLowerCase();
if (normalized === PLUS_ACCOUNT_ACCESS_STRATEGY_SUB2API_CODEX_SESSION) {
return PLUS_ACCOUNT_ACCESS_STRATEGY_SUB2API_CODEX_SESSION;
}
if (normalized === PLUS_ACCOUNT_ACCESS_STRATEGY_CPA_CODEX_SESSION) {
return PLUS_ACCOUNT_ACCESS_STRATEGY_CPA_CODEX_SESSION;
}
return PLUS_ACCOUNT_ACCESS_STRATEGY_OAUTH;
}
function getPlusAccountSessionStrategyForTarget(targetId = '') {
const normalizedTargetId = String(targetId || '').trim().toLowerCase();
if (normalizedTargetId === 'sub2api') {
return PLUS_ACCOUNT_ACCESS_STRATEGY_SUB2API_CODEX_SESSION;
}
if (normalizedTargetId === 'cpa') {
return PLUS_ACCOUNT_ACCESS_STRATEGY_CPA_CODEX_SESSION;
}
return PLUS_ACCOUNT_ACCESS_STRATEGY_OAUTH;
}
function normalizePlusAccountAccessStrategyForTarget(value = '', targetId = '') {
const normalizedStrategy = normalizePlusAccountAccessStrategy(value);
if (
normalizedStrategy === PLUS_ACCOUNT_ACCESS_STRATEGY_SUB2API_CODEX_SESSION
|| normalizedStrategy === PLUS_ACCOUNT_ACCESS_STRATEGY_CPA_CODEX_SESSION
) {
return getPlusAccountSessionStrategyForTarget(targetId);
}
return normalizedStrategy;
}
function normalizeOpenAiTargetList(values = []) {
if (!Array.isArray(values)) {
return [];
}
const seen = new Set();
const normalized = [];
values.forEach((value) => {
const targetId = normalizeOpenAiTargetId(value, '');
if (!targetId || seen.has(targetId)) {
return;
}
seen.add(targetId);
normalized.push(targetId);
});
return normalized;
}
function getTargetLabel(flowId = DEFAULT_FLOW_ID, targetId = '') {
if (
isRegisteredFlowId(flowId)
&& typeof flowRegistryApi.getTargetLabel === 'function'
) {
return flowRegistryApi.getTargetLabel(flowId, targetId);
}
const normalized = String(targetId || '').trim().toLowerCase();
if (normalized === 'sub2api') {
return 'SUB2API';
}
if (normalized === 'codex2api') {
return 'Codex2API';
}
if (normalized === 'cpa') {
return 'CPA';
}
return normalized || String(targetId || '').trim();
}
function createFlowCapabilityRegistry(deps = {}) {
const {
defaultFlowCapabilities = DEFAULT_FLOW_CAPABILITIES,
defaultFlowId = DEFAULT_FLOW_ID,
defaultTargetCapabilities = DEFAULT_TARGET_CAPABILITIES,
flowCapabilities = FLOW_CAPABILITIES,
targetCapabilities = OPENAI_TARGET_CAPABILITIES,
} = deps;
const settingsSchema = settingsSchemaApi.createSettingsSchema
? settingsSchemaApi.createSettingsSchema({
defaultFlowId,
})
: null;
function getFlowCapabilities(flowId) {
const normalizedFlowId = normalizeCapabilityFlowId(flowId, defaultFlowId);
const entry = flowCapabilities[normalizedFlowId] || null;
const registryAdapterIds = typeof contributionRegistryApi.getContributionAdapterIds === 'function'
? contributionRegistryApi.getContributionAdapterIds(normalizedFlowId)
: [];
const contributionAdapterIds = registryAdapterIds.length
? registryAdapterIds
: (Array.isArray(entry?.contributionAdapterIds)
? entry.contributionAdapterIds.map((value) => String(value || '').trim()).filter(Boolean)
: []);
const supportedTargetIds = normalizedFlowId === 'openai'
? normalizeOpenAiTargetList(
entry?.supportedTargetIds || defaultFlowCapabilities.supportedTargetIds
)
: (Array.isArray(entry?.supportedTargetIds)
? entry.supportedTargetIds.map((value) => String(value || '').trim().toLowerCase()).filter(Boolean)
: []);
return {
...defaultFlowCapabilities,
...(entry || {}),
supportedTargetIds,
contributionAdapterIds,
supportsAccountContribution: Boolean(entry?.supportsAccountContribution || contributionAdapterIds.length > 0),
};
}
function getOpenAiTargetCapabilities(targetId) {
const normalizedTargetId = normalizeOpenAiTargetId(targetId);
return {
...defaultTargetCapabilities,
...(targetCapabilities[normalizedTargetId] || {}),
};
}
function normalizeRequestedTargetId(activeFlowId, state = {}, options = {}) {
if (activeFlowId === 'openai') {
return normalizeOpenAiTargetId(
options?.targetId
?? options?.integrationTargetId
?? options?.panelMode
?? state?.openaiIntegrationTargetId
?? state?.panelMode,
DEFAULT_OPENAI_TARGET_ID
);
}
const rawTargetId = activeFlowId === 'kiro'
? (
options?.targetId
?? state?.kiroTargetId
?? flowRegistryApi.getDefaultTargetId?.(activeFlowId)
?? ''
)
: (
options?.targetId
?? state?.targetId
?? state?.openaiIntegrationTargetId
?? state?.panelMode
?? state?.kiroTargetId
?? flowRegistryApi.getDefaultTargetId?.(activeFlowId)
?? ''
);
if (
isRegisteredFlowId(activeFlowId)
&& typeof flowRegistryApi.normalizeTargetId === 'function'
) {
return flowRegistryApi.normalizeTargetId(
activeFlowId,
rawTargetId,
flowRegistryApi.getDefaultTargetId?.(activeFlowId)
);
}
return String(rawTargetId || '').trim().toLowerCase();
}
function normalizeChangedKeys(values = []) {
const list = Array.isArray(values) ? values : [];
const seen = new Set();
const normalized = [];
list.forEach((value) => {
const key = String(value || '').trim();
if (!key || seen.has(key)) {
return;
}
seen.add(key);
normalized.push(key);
});
return normalized;
}
function resolveEffectiveTargetId(activeFlowId, state = {}, requestedTargetId = DEFAULT_OPENAI_TARGET_ID) {
if (!isRegisteredFlowId(activeFlowId)) {
return normalizeRequestedTargetId(activeFlowId, state, {
targetId: requestedTargetId,
});
}
if (settingsSchema?.getSelectedTargetId) {
const targetId = settingsSchema.getSelectedTargetId({
...state,
activeFlowId,
}, activeFlowId);
if (targetId) {
return targetId;
}
}
if (typeof flowRegistryApi.normalizeTargetId === 'function') {
return flowRegistryApi.normalizeTargetId(
activeFlowId,
activeFlowId === 'openai'
? (state?.openaiIntegrationTargetId || state?.panelMode || requestedTargetId)
: (state?.kiroTargetId || requestedTargetId),
flowRegistryApi.getDefaultTargetId?.(activeFlowId)
);
}
return activeFlowId === 'openai'
? normalizeOpenAiTargetId(requestedTargetId)
: String(requestedTargetId || '').trim().toLowerCase();
}
function resolveSidepanelCapabilities(options = {}) {
const state = options?.state || {};
const activeFlowId = normalizeCapabilityFlowId(
options?.activeFlowId ?? state?.activeFlowId,
defaultFlowId
);
const flowState = getFlowCapabilities(activeFlowId);
const requestedTargetId = normalizeRequestedTargetId(
activeFlowId,
state,
options
);
const supportedTargetIds = activeFlowId === 'openai'
? normalizeOpenAiTargetList(flowState.supportedTargetIds)
: (Array.isArray(flowState.supportedTargetIds)
? flowState.supportedTargetIds.slice()
: []);
const targetSupported = supportedTargetIds.length === 0
? true
: supportedTargetIds.includes(requestedTargetId);
const effectiveTargetId = targetSupported
? requestedTargetId
: (supportedTargetIds[0] || requestedTargetId);
const targetState = activeFlowId === 'openai'
? getOpenAiTargetCapabilities(effectiveTargetId)
: defaultTargetCapabilities;
const runtimeLocks = {
autoRunLocked: Boolean(options?.autoRunLocked ?? state?.autoRunLocked),
accountContribution: Boolean(flowState.supportsAccountContribution) && Boolean(state?.accountContributionEnabled),
phoneVerificationEnabled: activeFlowId === 'openai' && flowState.supportsPhoneVerificationSettings && Boolean(state?.phoneVerificationEnabled),
plusModeEnabled: activeFlowId === 'openai' && flowState.supportsPlusMode && Boolean(state?.plusModeEnabled),
settingsMenuLocked: Boolean(options?.settingsMenuLocked ?? state?.settingsMenuLocked),
};
const effectiveSignupMethods = [];
if (flowState.supportsEmailSignup !== false) {
effectiveSignupMethods.push(SIGNUP_METHOD_EMAIL);
}
const canSelectPhoneSignup = activeFlowId === 'openai'
&& Boolean(flowState.supportsPhoneSignup)
&& Boolean(targetState.supportsPhoneSignup)
&& runtimeLocks.phoneVerificationEnabled
&& !runtimeLocks.plusModeEnabled
&& !runtimeLocks.accountContribution;
if (canSelectPhoneSignup) {
effectiveSignupMethods.push(SIGNUP_METHOD_PHONE);
}
if (!effectiveSignupMethods.length) {
effectiveSignupMethods.push(SIGNUP_METHOD_EMAIL);
}
const requestedSignupMethod = normalizeSignupMethod(
options?.signupMethod ?? state?.signupMethod
);
const effectiveSignupMethod = requestedSignupMethod === SIGNUP_METHOD_PHONE && canSelectPhoneSignup
? SIGNUP_METHOD_PHONE
: (effectiveSignupMethods.includes(SIGNUP_METHOD_EMAIL)
? SIGNUP_METHOD_EMAIL
: effectiveSignupMethods[0]);
const requestedPlusAccountAccessStrategy = normalizePlusAccountAccessStrategyForTarget(
options?.plusAccountAccessStrategy ?? state?.plusAccountAccessStrategy,
effectiveTargetId
);
const targetPlusAccountAccessStrategies = (Array.isArray(targetState.supportedPlusAccountAccessStrategies)
&& targetState.supportedPlusAccountAccessStrategies.length > 0
? targetState.supportedPlusAccountAccessStrategies
: [PLUS_ACCOUNT_ACCESS_STRATEGY_OAUTH])
.map(normalizePlusAccountAccessStrategy)
.filter((strategy, index, strategies) => strategy && strategies.indexOf(strategy) === index);
const availablePlusAccountAccessStrategies = activeFlowId === 'openai'
&& Boolean(flowState.supportsPlusMode)
&& Boolean(runtimeLocks.plusModeEnabled)
&& effectiveSignupMethod === SIGNUP_METHOD_EMAIL
? (runtimeLocks.accountContribution
? [PLUS_ACCOUNT_ACCESS_STRATEGY_SUB2API_CODEX_SESSION]
: targetPlusAccountAccessStrategies)
: [PLUS_ACCOUNT_ACCESS_STRATEGY_OAUTH];
const effectivePlusAccountAccessStrategy = runtimeLocks.accountContribution
&& runtimeLocks.plusModeEnabled
&& effectiveSignupMethod === SIGNUP_METHOD_EMAIL
? PLUS_ACCOUNT_ACCESS_STRATEGY_SUB2API_CODEX_SESSION
: availablePlusAccountAccessStrategies.includes(requestedPlusAccountAccessStrategy)
? requestedPlusAccountAccessStrategy
: PLUS_ACCOUNT_ACCESS_STRATEGY_OAUTH;
const canEditPlusAccountAccessStrategy = activeFlowId === 'openai'
&& Boolean(flowState.supportsPlusMode)
&& Boolean(runtimeLocks.plusModeEnabled)
&& effectiveSignupMethod === SIGNUP_METHOD_EMAIL
&& !runtimeLocks.accountContribution
&& availablePlusAccountAccessStrategies.length > 1;
const visibleGroupIds = typeof flowRegistryApi.getVisibleGroupIds === 'function'
&& isRegisteredFlowId(activeFlowId)
? flowRegistryApi.getVisibleGroupIds(activeFlowId, effectiveTargetId)
: [];
return {
activeFlowId,
canShowContributionMode: Boolean(flowState.supportsAccountContribution),
canShowLuckmail: activeFlowId === 'openai' && Boolean(flowState.supportsLuckmail),
canShowPhoneSettings: activeFlowId === 'openai' && Boolean(flowState.supportsPhoneVerificationSettings),
canShowPlusSettings: activeFlowId === 'openai' && Boolean(flowState.supportsPlusMode),
canSwitchFlow: Boolean(flowState.canSwitchFlow),
canEditPlusAccountAccessStrategy,
canUsePhoneSignup: canSelectPhoneSignup,
canUseSelectedTarget: targetSupported,
effectivePlusAccountAccessStrategy,
effectivePanelMode: effectiveTargetId,
effectiveSignupMethod,
effectiveSignupMethods,
effectiveTargetId,
flowCapabilities: flowState,
panelCapabilities: targetState,
panelMode: effectiveTargetId,
requestedPlusAccountAccessStrategy,
requestedSignupMethod,
requestedTargetId,
runtimeLocks,
availablePlusAccountAccessStrategies,
shouldWarnCpaPhoneSignup: effectiveSignupMethod === SIGNUP_METHOD_PHONE
&& Boolean(targetState.requiresPhoneSignupWarning),
stepDefinitionOptions: {
activeFlowId,
integrationTargetId: effectiveTargetId,
panelMode: effectiveTargetId,
targetId: effectiveTargetId,
plusAccountAccessStrategy: effectivePlusAccountAccessStrategy,
plusModeEnabled: runtimeLocks.plusModeEnabled,
signupMethod: effectiveSignupMethod,
},
supportedPanelModes: supportedTargetIds,
supportedTargetIds,
targetCapabilities: targetState,
targetId: effectiveTargetId,
visibleGroupIds,
};
}
function buildPhoneSignupValidationError(capabilityState = {}) {
const flowState = capabilityState.flowCapabilities || {};
const targetState = capabilityState.targetCapabilities || {};
const runtimeLocks = capabilityState.runtimeLocks || {};
if (!flowState.supportsPhoneSignup) {
return {
code: 'phone_signup_flow_unsupported',
message: '当前 flow 不支持手机号注册。',
};
}
if (!targetState.supportsPhoneSignup) {
return {
code: 'phone_signup_panel_unsupported',
message: `当前来源 ${getTargetLabel(capabilityState.activeFlowId, capabilityState.requestedTargetId)} 不支持手机号注册。`,
};
}
if (!runtimeLocks.phoneVerificationEnabled) {
return {
code: 'phone_signup_phone_verification_disabled',
message: '请先开启接码设置后再使用手机号注册。',
};
}
if (runtimeLocks.plusModeEnabled) {
return {
code: 'phone_signup_plus_mode_locked',
message: 'Plus 模式开启时不能使用手机号注册。',
};
}
if (runtimeLocks.accountContribution) {
return {
code: 'phone_signup_contribution_mode_locked',
message: '贡献模式开启时不能使用手机号注册。',
};
}
return {
code: 'phone_signup_unavailable',
message: '当前设置暂不支持手机号注册。',
};
}
function validateAutoRunStart(options = {}) {
const state = options?.state || {};
const capabilityState = resolveSidepanelCapabilities(options);
const errors = [];
if (
Array.isArray(capabilityState.supportedTargetIds)
&& capabilityState.supportedTargetIds.length > 0
&& capabilityState.canUseSelectedTarget === false
) {
errors.push({
code: 'panel_mode_unsupported',
message: `当前 flow 不支持 ${getTargetLabel(capabilityState.activeFlowId, capabilityState.requestedTargetId)} 来源。`,
});
}
if (Boolean(state?.plusModeEnabled) && !capabilityState.flowCapabilities?.supportsPlusMode) {
errors.push({
code: 'plus_mode_unsupported',
message: '当前 flow 不支持 Plus 模式。',
});
}
if (Boolean(state?.accountContributionEnabled) && !capabilityState.flowCapabilities?.supportsAccountContribution) {
errors.push({
code: 'contribution_mode_unsupported',
message: '当前 flow 不支持贡献模式。',
});
}
if (
capabilityState.requestedSignupMethod === SIGNUP_METHOD_PHONE
&& capabilityState.effectiveSignupMethod !== SIGNUP_METHOD_PHONE
) {
errors.push(buildPhoneSignupValidationError(capabilityState));
}
return {
ok: errors.length === 0,
errors,
capabilityState,
};
}
function validateModeSwitch(options = {}) {
const state = options?.state || {};
const changedKeys = normalizeChangedKeys(
options?.changedKeys !== undefined
? options.changedKeys
: Object.keys(state || {})
);
const changedKeySet = new Set(changedKeys);
const capabilityState = resolveSidepanelCapabilities(options);
const errors = [];
const normalizedUpdates = {};
const flowState = capabilityState.flowCapabilities || {};
const requestedPhoneSignup = capabilityState.requestedSignupMethod === SIGNUP_METHOD_PHONE;
const shouldReconcileSignupMethod = MODE_SWITCH_RELEVANT_KEYS.some((key) => changedKeySet.has(key));
if (
(changedKeySet.has('panelMode') || changedKeySet.has('openaiIntegrationTargetId') || changedKeySet.has('kiroTargetId'))
&& Array.isArray(capabilityState.supportedTargetIds)
&& capabilityState.supportedTargetIds.length > 0
&& capabilityState.canUseSelectedTarget === false
) {
normalizedUpdates.panelMode = capabilityState.effectiveTargetId;
normalizedUpdates.openaiIntegrationTargetId = capabilityState.effectiveTargetId;
normalizedUpdates.kiroTargetId = capabilityState.effectiveTargetId;
errors.push({
code: 'panel_mode_unsupported',
message: `当前 flow 不支持 ${getTargetLabel(capabilityState.activeFlowId, capabilityState.requestedTargetId)} 来源。`,
});
}
if (changedKeySet.has('plusModeEnabled') && Boolean(state?.plusModeEnabled) && !flowState.supportsPlusMode) {
normalizedUpdates.plusModeEnabled = false;
errors.push({
code: 'plus_mode_unsupported',
message: '当前 flow 不支持 Plus 模式。',
});
}
if (
changedKeySet.has('accountContributionEnabled')
&& Boolean(state?.accountContributionEnabled)
&& !flowState.supportsAccountContribution
) {
normalizedUpdates.accountContributionEnabled = false;
errors.push({
code: 'contribution_mode_unsupported',
message: '当前 flow 不支持贡献模式。',
});
}
if (
changedKeySet.has('phoneVerificationEnabled')
&& Boolean(state?.phoneVerificationEnabled)
&& !flowState.supportsPhoneVerificationSettings
) {
normalizedUpdates.phoneVerificationEnabled = false;
errors.push({
code: 'phone_verification_unsupported',
message: '当前 flow 不支持接码设置。',
});
}
if (
shouldReconcileSignupMethod
&& requestedPhoneSignup
&& capabilityState.effectiveSignupMethod !== SIGNUP_METHOD_PHONE
) {
normalizedUpdates.signupMethod = capabilityState.effectiveSignupMethod;
errors.push(buildPhoneSignupValidationError(capabilityState));
}
return {
ok: errors.length === 0,
changedKeys,
capabilityState,
errors,
normalizedUpdates,
};
}
function canUsePhoneSignup(state = {}) {
return resolveSidepanelCapabilities({ state }).canUsePhoneSignup;
}
function resolveSignupMethod(state = {}, signupMethod = undefined) {
return resolveSidepanelCapabilities({
signupMethod,
state,
}).effectiveSignupMethod;
}
return {
canUsePhoneSignup,
getFlowCapabilities,
getOpenAiTargetCapabilities,
normalizeFlowId,
normalizeOpenAiTargetId,
normalizePlusAccountAccessStrategy,
normalizeSignupMethod,
resolveSidepanelCapabilities,
resolveSignupMethod,
validateAutoRunStart,
validateModeSwitch,
};
}
return {
createFlowCapabilityRegistry,
DEFAULT_FLOW_CAPABILITIES,
DEFAULT_FLOW_ID,
DEFAULT_TARGET_CAPABILITIES,
DEFAULT_OPENAI_TARGET_ID,
FLOW_CAPABILITIES,
OPENAI_TARGET_CAPABILITIES,
PLUS_ACCOUNT_ACCESS_STRATEGY_OAUTH,
PLUS_ACCOUNT_ACCESS_STRATEGY_SUB2API_CODEX_SESSION,
PLUS_ACCOUNT_ACCESS_STRATEGY_CPA_CODEX_SESSION,
SIGNUP_METHOD_EMAIL,
SIGNUP_METHOD_PHONE,
VALID_OPENAI_TARGET_IDS,
normalizeFlowId,
normalizeOpenAiTargetId,
normalizePlusAccountAccessStrategy,
normalizeSignupMethod,
};
});
-582
View File
@@ -1,582 +0,0 @@
(function attachMultiPageFlowRegistry(root, factory) {
root.MultiPageFlowRegistry = factory();
})(typeof self !== 'undefined' ? self : globalThis, function createFlowRegistryModule() {
const DEFAULT_FLOW_ID = 'openai';
const DEFAULT_OPENAI_TARGET_ID = 'cpa';
const DEFAULT_KIRO_TARGET_ID = 'kiro-rs';
const DEFAULT_KIRO_PUBLICATION_TARGET_ID = 'kiro-rs';
const DEFAULT_KIRO_RS_URL = '';
const OPENAI_TARGET_IDS = Object.freeze(['cpa', 'sub2api', 'codex2api']);
const SHARED_SERVICE_IDS = Object.freeze(['account', 'email', 'proxy']);
const DEFAULT_FLOW_CAPABILITIES = Object.freeze({
supportsEmailSignup: true,
supportsPhoneSignup: false,
supportsPhoneVerificationSettings: false,
supportsPlusMode: false,
supportsContributionMode: false,
supportsAccountContribution: false,
supportsOpenAiOAuthContribution: false,
contributionAdapterIds: [],
supportedTargetIds: [],
supportsLuckmail: false,
supportsOauthTimeoutBudget: false,
canSwitchFlow: true,
stepDefinitionMode: 'default',
targetSelectorLabel: '来源',
});
function freezeDeep(value) {
if (!value || typeof value !== 'object' || Object.isFrozen(value)) {
return value;
}
Object.getOwnPropertyNames(value).forEach((key) => {
freezeDeep(value[key]);
});
return Object.freeze(value);
}
const FLOW_DEFINITIONS = freezeDeep({
openai: {
id: 'openai',
label: 'Codex / OpenAI',
services: ['account', 'email', 'proxy'],
capabilities: {
...DEFAULT_FLOW_CAPABILITIES,
supportsPhoneSignup: true,
supportsPhoneVerificationSettings: true,
supportsPlusMode: true,
supportsContributionMode: true,
supportsAccountContribution: true,
supportsOpenAiOAuthContribution: true,
contributionAdapterIds: ['openai-oauth', 'openai-codex-file', 'openai-sub2api-file'],
supportedTargetIds: [...OPENAI_TARGET_IDS],
supportsLuckmail: true,
supportsOauthTimeoutBudget: true,
stepDefinitionMode: 'openai-dynamic',
},
baseGroups: [
'openai-plus',
'openai-phone',
'openai-oauth',
'openai-step6',
],
targets: {
cpa: {
id: 'cpa',
label: 'CPA 面板',
groups: ['openai-target-cpa'],
},
sub2api: {
id: 'sub2api',
label: 'SUB2API',
groups: ['openai-target-sub2api'],
},
codex2api: {
id: 'codex2api',
label: 'Codex2API',
groups: ['openai-target-codex2api'],
},
},
runtimeSources: {
'openai-auth': {
flowId: 'openai',
kind: 'flow-page',
label: '认证页',
readyPolicy: 'allow-child-frame',
family: 'openai-auth-family',
driverId: 'content/signup-page',
cleanupScopes: ['oauth-localhost-callback'],
},
chatgpt: {
flowId: 'openai',
kind: 'flow-entry',
label: 'ChatGPT 首页',
readyPolicy: 'allow-child-frame',
family: 'chatgpt-entry-family',
driverId: null,
cleanupScopes: [],
},
'vps-panel': {
flowId: 'openai',
kind: 'panel-page',
label: 'CPA 面板',
readyPolicy: 'allow-child-frame',
family: 'vps-panel-family',
driverId: 'content/vps-panel',
cleanupScopes: [],
},
'platform-panel': {
flowId: 'openai',
kind: 'virtual-page',
label: '平台回调面板',
readyPolicy: 'disabled',
family: 'platform-panel-family',
driverId: 'content/platform-panel',
cleanupScopes: [],
},
'sub2api-panel': {
flowId: 'openai',
kind: 'panel-page',
label: 'SUB2API 后台',
readyPolicy: 'allow-child-frame',
family: 'sub2api-panel-family',
driverId: 'content/sub2api-panel',
cleanupScopes: [],
},
'codex2api-panel': {
flowId: 'openai',
kind: 'panel-page',
label: 'Codex2API 后台',
readyPolicy: 'allow-child-frame',
family: 'codex2api-panel-family',
driverId: 'content/sub2api-panel',
cleanupScopes: [],
},
'plus-checkout': {
flowId: 'openai',
kind: 'flow-page',
label: 'Plus Checkout',
readyPolicy: 'top-frame-only',
family: 'plus-checkout-family',
driverId: 'content/plus-checkout',
cleanupScopes: [],
},
'paypal-flow': {
flowId: 'openai',
kind: 'flow-page',
label: 'PayPal 授权页',
readyPolicy: 'allow-child-frame',
family: 'paypal-flow-family',
driverId: 'content/paypal-flow',
cleanupScopes: [],
},
'gopay-flow': {
flowId: 'openai',
kind: 'flow-page',
label: 'GoPay 授权页',
readyPolicy: 'allow-child-frame',
family: 'gopay-flow-family',
driverId: 'content/gopay-flow',
cleanupScopes: [],
},
},
driverDefinitions: {
'content/signup-page': {
sourceId: 'openai-auth',
commands: [
'submit-signup-email',
'fill-password',
'fill-profile',
'oauth-login',
'submit-verification-code',
'post-login-phone-verification',
'bind-email',
'fetch-bind-email-code',
'confirm-oauth',
'detect-auth-state',
],
},
'content/sub2api-panel': {
sourceId: 'sub2api-panel',
commands: ['open-panel', 'fetch-oauth-url', 'platform-verify'],
},
'content/vps-panel': {
sourceId: 'vps-panel',
commands: ['open-panel', 'fetch-oauth-url', 'platform-verify'],
},
'content/platform-panel': {
sourceId: 'platform-panel',
commands: ['platform-verify', 'fetch-oauth-url'],
},
'content/plus-checkout': {
sourceId: 'plus-checkout',
commands: [
'plus-checkout-create',
'paypal-hosted-openai-checkout',
'plus-checkout-billing',
'plus-checkout-return',
],
},
'content/paypal-flow': {
sourceId: 'paypal-flow',
commands: [
'paypal-approve',
'paypal-hosted-email',
'paypal-hosted-card',
'paypal-hosted-create-account',
'paypal-hosted-review',
],
},
'content/gopay-flow': {
sourceId: 'gopay-flow',
commands: ['gopay-subscription-confirm'],
},
},
},
kiro: {
id: 'kiro',
label: 'Kiro',
services: ['account', 'email', 'proxy'],
capabilities: {
...DEFAULT_FLOW_CAPABILITIES,
supportsAccountContribution: true,
contributionAdapterIds: ['kiro-builder-id'],
supportedTargetIds: [DEFAULT_KIRO_TARGET_ID],
stepDefinitionMode: 'kiro',
},
baseGroups: [
'kiro-runtime-status',
],
targets: {
'kiro-rs': {
id: 'kiro-rs',
label: 'kiro.rs',
groups: ['kiro-target-kiro-rs'],
},
},
publicationTargets: {
'kiro-rs': {
id: 'kiro-rs',
label: 'kiro.rs',
},
},
runtimeSources: {
'kiro-register-page': {
flowId: 'kiro',
kind: 'flow-page',
label: 'Kiro 注册页',
readyPolicy: 'top-frame-only',
family: 'kiro-register-page-family',
driverId: 'content/kiro/register-page',
cleanupScopes: [],
},
'kiro-desktop-authorize': {
flowId: 'kiro',
kind: 'flow-page',
label: 'Kiro 桌面授权页',
readyPolicy: 'top-frame-only',
family: 'kiro-desktop-authorize-family',
driverId: 'content/kiro/desktop-authorize-page',
cleanupScopes: [],
},
'kiro-rs-admin': {
flowId: 'kiro',
kind: 'virtual-page',
label: 'kiro.rs Admin',
readyPolicy: 'disabled',
family: 'kiro-rs-admin-family',
driverId: null,
cleanupScopes: [],
},
},
driverDefinitions: {
'content/kiro/register-page': {
sourceId: 'kiro-register-page',
commands: [
'kiro-open-register-page',
'kiro-submit-email',
'kiro-submit-name',
'kiro-submit-verification-code',
'kiro-submit-password',
'kiro-complete-register-consent',
],
},
'content/kiro/desktop-authorize-page': {
sourceId: 'kiro-desktop-authorize',
commands: [
'kiro-complete-desktop-authorize',
],
},
'background/kiro-register': {
sourceId: 'kiro-register-page',
commands: [
'kiro-open-register-page',
'kiro-submit-email',
'kiro-submit-name',
'kiro-submit-verification-code',
'kiro-submit-password',
'kiro-complete-register-consent',
],
},
'background/kiro-desktop-authorize': {
sourceId: 'kiro-desktop-authorize',
commands: [
'kiro-start-desktop-authorize',
'kiro-complete-desktop-authorize',
],
},
'background/kiro-publisher-kiro-rs': {
sourceId: 'kiro-rs-admin',
commands: [
'kiro-upload-credential',
],
},
},
},
});
const SETTINGS_GROUP_DEFINITIONS = freezeDeep({
'service-account': {
id: 'service-account',
label: '账户',
rowIds: ['row-custom-password'],
},
'service-email': {
id: 'service-email',
label: '邮箱服务',
},
'service-proxy': {
id: 'service-proxy',
label: 'IP 代理',
sectionIds: ['ip-proxy-section'],
},
'openai-target-cpa': {
id: 'openai-target-cpa',
label: 'CPA 来源',
rowIds: ['row-vps-url', 'row-vps-password', 'row-local-cpa-step9-mode'],
},
'openai-target-sub2api': {
id: 'openai-target-sub2api',
label: 'SUB2API 来源',
rowIds: [
'row-sub2api-url',
'row-sub2api-email',
'row-sub2api-password',
'row-sub2api-group',
'row-sub2api-account-priority',
'row-sub2api-default-proxy',
],
},
'openai-target-codex2api': {
id: 'openai-target-codex2api',
label: 'Codex2API 来源',
rowIds: ['row-codex2api-url', 'row-codex2api-admin-key'],
},
'openai-plus': {
id: 'openai-plus',
label: 'Plus',
rowIds: ['row-plus-mode', 'row-plus-account-access-strategy', 'row-plus-payment-method'],
},
'openai-phone': {
id: 'openai-phone',
label: '接码设置',
sectionIds: ['phone-verification-section'],
rowIds: [],
},
'openai-oauth': {
id: 'openai-oauth',
label: 'OAuth',
rowIds: ['row-oauth-flow-timeout', 'row-oauth-display'],
},
'openai-step6': {
id: 'openai-step6',
label: '第六步',
rowIds: ['row-step6-cookie-settings'],
},
'kiro-target-kiro-rs': {
id: 'kiro-target-kiro-rs',
label: 'kiro.rs 配置',
rowIds: ['row-kiro-rs-url', 'row-kiro-rs-key', 'row-kiro-rs-test-status'],
},
'kiro-runtime-status': {
id: 'kiro-runtime-status',
label: 'Kiro 运行态',
rowIds: ['row-kiro-web-status', 'row-kiro-login-url', 'row-kiro-upload-status'],
},
});
function normalizeFlowId(value = '', fallback = DEFAULT_FLOW_ID) {
const normalized = String(value || '').trim().toLowerCase();
if (normalized && Object.prototype.hasOwnProperty.call(FLOW_DEFINITIONS, normalized)) {
return normalized;
}
const fallbackValue = String(fallback || '').trim().toLowerCase();
return Object.prototype.hasOwnProperty.call(FLOW_DEFINITIONS, fallbackValue)
? fallbackValue
: DEFAULT_FLOW_ID;
}
function getRegisteredFlowIds() {
return Object.keys(FLOW_DEFINITIONS);
}
function getFlowDefinition(flowId) {
return FLOW_DEFINITIONS[normalizeFlowId(flowId)] || FLOW_DEFINITIONS[DEFAULT_FLOW_ID];
}
function getFlowLabel(flowId) {
return getFlowDefinition(flowId)?.label || normalizeFlowId(flowId);
}
function getDefaultTargetId(flowId) {
return normalizeFlowId(flowId) === 'kiro'
? DEFAULT_KIRO_TARGET_ID
: DEFAULT_OPENAI_TARGET_ID;
}
function normalizeOpenAiTargetId(value = '', fallback = DEFAULT_OPENAI_TARGET_ID) {
const normalized = String(value || '').trim().toLowerCase();
if (OPENAI_TARGET_IDS.includes(normalized)) {
return normalized;
}
const fallbackValue = String(fallback || '').trim().toLowerCase();
return OPENAI_TARGET_IDS.includes(fallbackValue)
? fallbackValue
: DEFAULT_OPENAI_TARGET_ID;
}
function normalizeKiroTargetId(value = '', fallback = DEFAULT_KIRO_TARGET_ID) {
const normalized = String(value || '').trim().toLowerCase();
if (normalized === DEFAULT_KIRO_TARGET_ID) {
return normalized;
}
const fallbackValue = String(fallback || '').trim().toLowerCase();
return fallbackValue === DEFAULT_KIRO_TARGET_ID
? fallbackValue
: DEFAULT_KIRO_TARGET_ID;
}
function normalizeTargetId(flowId, targetId = '', fallback = undefined) {
const normalizedFlowId = normalizeFlowId(flowId);
if (normalizedFlowId === 'kiro') {
return normalizeKiroTargetId(
targetId,
fallback || DEFAULT_KIRO_TARGET_ID
);
}
return normalizeOpenAiTargetId(
targetId,
fallback || DEFAULT_OPENAI_TARGET_ID
);
}
function getTargetDefinitions(flowId) {
return getFlowDefinition(flowId)?.targets || {};
}
function getTargetDefinition(flowId, targetId) {
const normalizedFlowId = normalizeFlowId(flowId);
const normalizedTargetId = normalizeTargetId(
normalizedFlowId,
targetId,
getDefaultTargetId(normalizedFlowId)
);
return getTargetDefinitions(normalizedFlowId)[normalizedTargetId] || null;
}
function getTargetOptions(flowId) {
return Object.values(getTargetDefinitions(flowId));
}
function getTargetLabel(flowId, targetId) {
return getTargetDefinition(flowId, targetId)?.label
|| normalizeTargetId(flowId, targetId);
}
function getPublicationTargetDefinitions(flowId) {
return getFlowDefinition(flowId)?.publicationTargets || {};
}
function getPublicationTargetDefinition(flowId, publicationTargetId) {
const normalizedFlowId = normalizeFlowId(flowId);
const normalizedPublicationTargetId = String(
publicationTargetId || (
normalizedFlowId === 'kiro'
? DEFAULT_KIRO_PUBLICATION_TARGET_ID
: ''
)
).trim().toLowerCase();
return getPublicationTargetDefinitions(normalizedFlowId)[normalizedPublicationTargetId] || null;
}
function getFlowCapabilities(flowId) {
return {
...DEFAULT_FLOW_CAPABILITIES,
...(getFlowDefinition(flowId)?.capabilities || {}),
};
}
function getVisibleGroupIds(flowId, targetId, options = {}) {
const normalizedFlowId = normalizeFlowId(flowId);
const flowDefinition = getFlowDefinition(normalizedFlowId);
const normalizedTargetId = normalizeTargetId(
normalizedFlowId,
targetId,
getDefaultTargetId(normalizedFlowId)
);
const targetDefinition = getTargetDefinition(
normalizedFlowId,
normalizedTargetId
);
const includeSharedServices = options?.includeSharedServices !== false;
const serviceGroups = includeSharedServices
? (Array.isArray(flowDefinition?.services)
? flowDefinition.services.map((serviceId) => `service-${serviceId}`)
: [])
: [];
return Array.from(new Set([
...(Array.isArray(flowDefinition?.baseGroups) ? flowDefinition.baseGroups : []),
...(Array.isArray(targetDefinition?.groups) ? targetDefinition.groups : []),
...serviceGroups,
]));
}
function getSettingsGroupDefinition(groupId) {
const normalizedGroupId = String(groupId || '').trim();
return SETTINGS_GROUP_DEFINITIONS[normalizedGroupId] || null;
}
function getSettingsGroupDefinitions() {
return SETTINGS_GROUP_DEFINITIONS;
}
function getRuntimeSourceDefinitions() {
const next = {};
Object.values(FLOW_DEFINITIONS).forEach((flowDefinition) => {
Object.assign(next, flowDefinition.runtimeSources || {});
});
return next;
}
function getDriverDefinitions() {
const next = {};
Object.values(FLOW_DEFINITIONS).forEach((flowDefinition) => {
Object.assign(next, flowDefinition.driverDefinitions || {});
});
return next;
}
return {
DEFAULT_FLOW_CAPABILITIES,
DEFAULT_FLOW_ID,
DEFAULT_KIRO_TARGET_ID,
DEFAULT_KIRO_PUBLICATION_TARGET_ID,
DEFAULT_KIRO_RS_URL,
DEFAULT_OPENAI_TARGET_ID,
FLOW_DEFINITIONS,
OPENAI_TARGET_IDS,
SETTINGS_GROUP_DEFINITIONS,
SHARED_SERVICE_IDS,
getDriverDefinitions,
getDefaultTargetId,
getFlowCapabilities,
getFlowDefinition,
getFlowLabel,
getPublicationTargetDefinition,
getPublicationTargetDefinitions,
getRegisteredFlowIds,
getRuntimeSourceDefinitions,
getSettingsGroupDefinition,
getSettingsGroupDefinitions,
getTargetDefinition,
getTargetDefinitions,
getTargetLabel,
getTargetOptions,
getVisibleGroupIds,
normalizeFlowId,
normalizeKiroTargetId,
normalizeOpenAiTargetId,
normalizeTargetId,
};
});
-528
View File
@@ -1,528 +0,0 @@
(function attachMultiPageSettingsSchema(root, factory) {
root.MultiPageSettingsSchema = factory();
})(typeof self !== 'undefined' ? self : globalThis, function createSettingsSchemaModule() {
function isPlainObject(value) {
return Boolean(value) && typeof value === 'object' && !Array.isArray(value);
}
function cloneValue(value) {
if (Array.isArray(value)) {
return value.map((entry) => cloneValue(entry));
}
if (isPlainObject(value)) {
return Object.fromEntries(
Object.entries(value).map(([key, entryValue]) => [key, cloneValue(entryValue)])
);
}
return value;
}
function normalizeStepExecutionRangeEntry(value = {}, fallback = {}) {
const source = isPlainObject(value) ? value : {};
const fallbackSource = isPlainObject(fallback) ? fallback : {};
const fromStep = Math.max(1, Number(source.fromStep ?? fallbackSource.fromStep ?? 1) || 1);
const toStep = Math.max(fromStep, Number(source.toStep ?? fallbackSource.toStep ?? fromStep) || fromStep);
return {
enabled: Boolean(source.enabled ?? fallbackSource.enabled),
fromStep,
toStep,
};
}
function createSettingsSchema(deps = {}) {
const rootScope = typeof self !== 'undefined' ? self : globalThis;
const flowRegistry = deps.flowRegistry || rootScope.MultiPageFlowRegistry || {};
const defaultFlowId = String(
deps.defaultFlowId || flowRegistry.DEFAULT_FLOW_ID || 'openai'
).trim().toLowerCase() || 'openai';
const defaultOpenAiTargetId = flowRegistry.DEFAULT_OPENAI_TARGET_ID || 'cpa';
const defaultKiroTargetId = flowRegistry.DEFAULT_KIRO_TARGET_ID || 'kiro-rs';
const defaultKiroRsUrl = String(flowRegistry.DEFAULT_KIRO_RS_URL || '').trim();
const normalizeFlowId = typeof flowRegistry.normalizeFlowId === 'function'
? flowRegistry.normalizeFlowId
: ((value = '', fallback = defaultFlowId) => {
const normalized = String(value || '').trim().toLowerCase();
return normalized || String(fallback || '').trim().toLowerCase() || defaultFlowId;
});
const normalizeTargetId = typeof flowRegistry.normalizeTargetId === 'function'
? flowRegistry.normalizeTargetId
: ((_flowId, value = '', fallback = '') => String(value || fallback || '').trim().toLowerCase());
const normalizePlusAccountAccessStrategy = (value = '') => {
const normalized = String(value || '').trim().toLowerCase();
if (normalized === 'sub2api_codex_session') {
return 'sub2api_codex_session';
}
if (normalized === 'cpa_codex_session') {
return 'cpa_codex_session';
}
return 'oauth';
};
function buildDefaultSettingsState() {
return {
schemaVersion: 4,
activeFlowId: defaultFlowId,
services: {
account: {
customPassword: '',
},
email: {
provider: '163',
},
proxy: {
enabled: false,
provider: '711proxy',
mode: 'account',
},
},
flows: {
openai: {
integrationTargetId: defaultOpenAiTargetId,
integrationTargets: {
cpa: {
vpsUrl: '',
vpsPassword: '',
localCpaStep9Mode: 'submit',
},
sub2api: {
sub2apiUrl: '',
sub2apiEmail: '',
sub2apiPassword: '',
sub2apiGroupName: 'codex',
sub2apiGroupNames: ['codex', 'openai-plus'],
sub2apiAccountPriority: 1,
sub2apiDefaultProxyName: '',
},
codex2api: {
codex2apiUrl: '',
codex2apiAdminKey: '',
},
},
signup: {
signupMethod: 'email',
phoneVerificationEnabled: false,
phoneSignupReloginAfterBindEmailEnabled: false,
},
plus: {
plusModeEnabled: false,
plusPaymentMethod: 'paypal-hosted',
plusAccountAccessStrategy: 'oauth',
hostedCheckoutVerificationUrl: '',
hostedCheckoutPhoneNumber: '',
plusHostedCheckoutOauthDelaySeconds: 3,
},
autoRun: {
stepExecutionRange: {
enabled: false,
fromStep: 1,
toStep: 11,
},
},
},
kiro: {
targetId: defaultKiroTargetId,
targets: {
'kiro-rs': {
baseUrl: defaultKiroRsUrl,
apiKey: '',
},
},
autoRun: {
stepExecutionRange: {
enabled: false,
fromStep: 1,
toStep: 9,
},
},
},
},
};
}
function getIntegrationTargetValue(settingsState, pathGetter, fallback = {}) {
return cloneValue(pathGetter(isPlainObject(settingsState) ? settingsState : {}) || fallback);
}
function normalizeSettingsState(input = {}, options = {}) {
const defaults = buildDefaultSettingsState();
const nested = isPlainObject(input?.settingsState)
? input.settingsState
: (isPlainObject(input) && isPlainObject(input.flows) && isPlainObject(input.services) ? input : {});
const activeFlowId = normalizeFlowId(
input?.activeFlowId
?? nested?.activeFlowId
?? options?.activeFlowId
?? defaults.activeFlowId,
defaults.activeFlowId
);
const openaiIntegrationTargetId = normalizeTargetId(
'openai',
nested?.flows?.openai?.integrationTargetId
?? input?.openaiIntegrationTargetId
?? input?.panelMode
?? defaults.flows.openai.integrationTargetId,
defaults.flows.openai.integrationTargetId
);
const kiroTargetId = normalizeTargetId(
'kiro',
nested?.flows?.kiro?.targetId
?? input?.kiroTargetId
?? defaults.flows.kiro.targetId,
defaults.flows.kiro.targetId
);
const stepExecutionRangeByFlow = isPlainObject(input?.stepExecutionRangeByFlow)
? input.stepExecutionRangeByFlow
: {};
return {
schemaVersion: Number(input?.settingsSchemaVersion || nested?.schemaVersion || defaults.schemaVersion) || defaults.schemaVersion,
activeFlowId,
services: {
email: {
provider: String(
nested?.services?.email?.provider
?? input?.mailProvider
?? defaults.services.email.provider
).trim() || defaults.services.email.provider,
},
proxy: {
enabled: Boolean(
nested?.services?.proxy?.enabled
?? input?.ipProxyEnabled
?? defaults.services.proxy.enabled
),
provider: String(
nested?.services?.proxy?.provider
?? input?.ipProxyService
?? defaults.services.proxy.provider
).trim() || defaults.services.proxy.provider,
mode: String(
nested?.services?.proxy?.mode
?? input?.ipProxyMode
?? defaults.services.proxy.mode
).trim() || defaults.services.proxy.mode,
},
account: {
customPassword: String(
input?.customPassword
?? nested?.services?.account?.customPassword
?? defaults.services.account.customPassword
).trim(),
},
},
flows: {
openai: {
integrationTargetId: openaiIntegrationTargetId,
integrationTargets: {
cpa: {
...defaults.flows.openai.integrationTargets.cpa,
...getIntegrationTargetValue(nested, (state) => state.flows?.openai?.integrationTargets?.cpa),
vpsUrl: String(
input?.vpsUrl
?? nested?.flows?.openai?.integrationTargets?.cpa?.vpsUrl
?? ''
).trim(),
vpsPassword: String(
input?.vpsPassword
?? nested?.flows?.openai?.integrationTargets?.cpa?.vpsPassword
?? ''
),
localCpaStep9Mode: String(
input?.localCpaStep9Mode
?? nested?.flows?.openai?.integrationTargets?.cpa?.localCpaStep9Mode
?? defaults.flows.openai.integrationTargets.cpa.localCpaStep9Mode
).trim() || defaults.flows.openai.integrationTargets.cpa.localCpaStep9Mode,
},
sub2api: {
...defaults.flows.openai.integrationTargets.sub2api,
...getIntegrationTargetValue(nested, (state) => state.flows?.openai?.integrationTargets?.sub2api),
sub2apiUrl: String(
input?.sub2apiUrl
?? nested?.flows?.openai?.integrationTargets?.sub2api?.sub2apiUrl
?? ''
).trim(),
sub2apiEmail: String(
input?.sub2apiEmail
?? nested?.flows?.openai?.integrationTargets?.sub2api?.sub2apiEmail
?? ''
).trim(),
sub2apiPassword: String(
input?.sub2apiPassword
?? nested?.flows?.openai?.integrationTargets?.sub2api?.sub2apiPassword
?? ''
),
sub2apiGroupName: String(
input?.sub2apiGroupName
?? nested?.flows?.openai?.integrationTargets?.sub2api?.sub2apiGroupName
?? defaults.flows.openai.integrationTargets.sub2api.sub2apiGroupName
).trim() || defaults.flows.openai.integrationTargets.sub2api.sub2apiGroupName,
sub2apiGroupNames: Array.isArray(input?.sub2apiGroupNames)
? input.sub2apiGroupNames.map((entry) => String(entry || '').trim()).filter(Boolean)
: (Array.isArray(nested?.flows?.openai?.integrationTargets?.sub2api?.sub2apiGroupNames)
? nested.flows.openai.integrationTargets.sub2api.sub2apiGroupNames.map((entry) => String(entry || '').trim()).filter(Boolean)
: [...defaults.flows.openai.integrationTargets.sub2api.sub2apiGroupNames]),
sub2apiAccountPriority: Math.max(1, Number(
input?.sub2apiAccountPriority
?? nested?.flows?.openai?.integrationTargets?.sub2api?.sub2apiAccountPriority
?? defaults.flows.openai.integrationTargets.sub2api.sub2apiAccountPriority
) || defaults.flows.openai.integrationTargets.sub2api.sub2apiAccountPriority),
sub2apiDefaultProxyName: String(
input?.sub2apiDefaultProxyName
?? nested?.flows?.openai?.integrationTargets?.sub2api?.sub2apiDefaultProxyName
?? ''
).trim(),
},
codex2api: {
...defaults.flows.openai.integrationTargets.codex2api,
...getIntegrationTargetValue(nested, (state) => state.flows?.openai?.integrationTargets?.codex2api),
codex2apiUrl: String(
input?.codex2apiUrl
?? nested?.flows?.openai?.integrationTargets?.codex2api?.codex2apiUrl
?? ''
).trim(),
codex2apiAdminKey: String(
input?.codex2apiAdminKey
?? nested?.flows?.openai?.integrationTargets?.codex2api?.codex2apiAdminKey
?? ''
).trim(),
},
},
signup: {
signupMethod: String(
input?.signupMethod
?? nested?.flows?.openai?.signup?.signupMethod
?? defaults.flows.openai.signup.signupMethod
).trim().toLowerCase() === 'phone' ? 'phone' : 'email',
phoneVerificationEnabled: Boolean(
input?.phoneVerificationEnabled
?? nested?.flows?.openai?.signup?.phoneVerificationEnabled
?? defaults.flows.openai.signup.phoneVerificationEnabled
),
phoneSignupReloginAfterBindEmailEnabled: Boolean(
input?.phoneSignupReloginAfterBindEmailEnabled
?? nested?.flows?.openai?.signup?.phoneSignupReloginAfterBindEmailEnabled
?? defaults.flows.openai.signup.phoneSignupReloginAfterBindEmailEnabled
),
},
plus: {
plusModeEnabled: Boolean(
input?.plusModeEnabled
?? nested?.flows?.openai?.plus?.plusModeEnabled
?? defaults.flows.openai.plus.plusModeEnabled
),
plusPaymentMethod: String(
input?.plusPaymentMethod
?? nested?.flows?.openai?.plus?.plusPaymentMethod
?? defaults.flows.openai.plus.plusPaymentMethod
).trim() || defaults.flows.openai.plus.plusPaymentMethod,
plusAccountAccessStrategy: normalizePlusAccountAccessStrategy(
input?.plusAccountAccessStrategy
?? nested?.flows?.openai?.plus?.plusAccountAccessStrategy
?? defaults.flows.openai.plus.plusAccountAccessStrategy
),
hostedCheckoutVerificationUrl: String(
input?.hostedCheckoutVerificationUrl
?? nested?.flows?.openai?.plus?.hostedCheckoutVerificationUrl
?? defaults.flows.openai.plus.hostedCheckoutVerificationUrl
).trim(),
hostedCheckoutPhoneNumber: String(
input?.hostedCheckoutPhoneNumber
?? nested?.flows?.openai?.plus?.hostedCheckoutPhoneNumber
?? defaults.flows.openai.plus.hostedCheckoutPhoneNumber
).trim(),
plusHostedCheckoutOauthDelaySeconds: (() => {
const numeric = Number(
input?.plusHostedCheckoutOauthDelaySeconds
?? nested?.flows?.openai?.plus?.plusHostedCheckoutOauthDelaySeconds
?? defaults.flows.openai.plus.plusHostedCheckoutOauthDelaySeconds
);
return Math.min(120, Math.max(0, Math.floor(Number.isFinite(numeric) ? numeric : defaults.flows.openai.plus.plusHostedCheckoutOauthDelaySeconds)));
})(),
},
autoRun: {
stepExecutionRange: normalizeStepExecutionRangeEntry(
stepExecutionRangeByFlow.openai
?? nested?.flows?.openai?.autoRun?.stepExecutionRange
?? {},
defaults.flows.openai.autoRun.stepExecutionRange
),
},
},
kiro: {
targetId: kiroTargetId,
targets: {
'kiro-rs': {
...defaults.flows.kiro.targets['kiro-rs'],
...getIntegrationTargetValue(nested, (state) => state.flows?.kiro?.targets?.['kiro-rs']),
baseUrl: String(
input?.kiroRsUrl
?? input?.kiroRsBaseUrl
?? nested?.flows?.kiro?.targets?.['kiro-rs']?.baseUrl
?? defaults.flows.kiro.targets['kiro-rs'].baseUrl
).trim() || defaults.flows.kiro.targets['kiro-rs'].baseUrl,
apiKey: String(
input?.kiroRsKey
?? input?.kiroRsApiKey
?? nested?.flows?.kiro?.targets?.['kiro-rs']?.apiKey
?? defaults.flows.kiro.targets['kiro-rs'].apiKey
),
},
},
autoRun: {
stepExecutionRange: normalizeStepExecutionRangeEntry(
stepExecutionRangeByFlow.kiro
?? nested?.flows?.kiro?.autoRun?.stepExecutionRange
?? {},
defaults.flows.kiro.autoRun.stepExecutionRange
),
},
},
},
};
}
function mergeSettingsState(baseValue = {}, patchValue = {}) {
const baseSettingsState = normalizeSettingsState(baseValue);
const patchSettingsState = normalizeSettingsState({
settingsState: patchValue,
activeFlowId: patchValue?.activeFlowId ?? baseSettingsState.activeFlowId,
});
function mergeRecursive(baseNode, patchNode) {
if (Array.isArray(patchNode)) {
return patchNode.map((entry) => cloneValue(entry));
}
if (!isPlainObject(patchNode)) {
return patchNode === undefined ? cloneValue(baseNode) : patchNode;
}
const next = {
...cloneValue(isPlainObject(baseNode) ? baseNode : {}),
};
Object.entries(patchNode).forEach(([key, value]) => {
next[key] = mergeRecursive(baseNode?.[key], value);
});
return next;
}
return normalizeSettingsState({
settingsState: mergeRecursive(baseSettingsState, patchSettingsState),
});
}
function getFlowSettings(settingsState = {}, flowId) {
const normalizedState = normalizeSettingsState(settingsState);
const normalizedFlowId = normalizeFlowId(flowId, normalizedState.activeFlowId);
return cloneValue(normalizedState?.flows?.[normalizedFlowId] || {});
}
function getSelectedTargetId(settingsState = {}, flowId) {
const normalizedState = normalizeSettingsState(settingsState);
const normalizedFlowId = normalizeFlowId(flowId, normalizedState.activeFlowId);
const flowSettings = normalizedState?.flows?.[normalizedFlowId] || {};
if (normalizedFlowId === 'kiro') {
return normalizeTargetId(
normalizedFlowId,
flowSettings?.targetId,
defaultKiroTargetId
);
}
return normalizeTargetId(
normalizedFlowId,
flowSettings?.integrationTargetId,
defaultOpenAiTargetId
);
}
function buildStepExecutionRangeByFlow(settingsState = {}) {
const normalizedState = normalizeSettingsState(settingsState);
return {
openai: normalizeStepExecutionRangeEntry(
normalizedState?.flows?.openai?.autoRun?.stepExecutionRange,
buildDefaultSettingsState().flows.openai.autoRun.stepExecutionRange
),
kiro: normalizeStepExecutionRangeEntry(
normalizedState?.flows?.kiro?.autoRun?.stepExecutionRange,
buildDefaultSettingsState().flows.kiro.autoRun.stepExecutionRange
),
};
}
function buildSettingsView(settingsState = {}, baseInput = {}) {
const normalizedState = normalizeSettingsState(settingsState);
const next = {
...(isPlainObject(baseInput) ? cloneValue(baseInput) : {}),
};
const openaiState = normalizedState.flows.openai;
const kiroState = normalizedState.flows.kiro;
next.activeFlowId = normalizedState.activeFlowId;
next.openaiIntegrationTargetId = getSelectedTargetId(normalizedState, 'openai');
next.kiroTargetId = getSelectedTargetId(normalizedState, 'kiro');
next.panelMode = next.openaiIntegrationTargetId;
next.vpsUrl = openaiState.integrationTargets.cpa.vpsUrl;
next.vpsPassword = openaiState.integrationTargets.cpa.vpsPassword;
next.localCpaStep9Mode = openaiState.integrationTargets.cpa.localCpaStep9Mode;
next.sub2apiUrl = openaiState.integrationTargets.sub2api.sub2apiUrl;
next.sub2apiEmail = openaiState.integrationTargets.sub2api.sub2apiEmail;
next.sub2apiPassword = openaiState.integrationTargets.sub2api.sub2apiPassword;
next.sub2apiGroupName = openaiState.integrationTargets.sub2api.sub2apiGroupName;
next.sub2apiGroupNames = cloneValue(openaiState.integrationTargets.sub2api.sub2apiGroupNames);
next.sub2apiAccountPriority = openaiState.integrationTargets.sub2api.sub2apiAccountPriority;
next.sub2apiDefaultProxyName = openaiState.integrationTargets.sub2api.sub2apiDefaultProxyName;
next.codex2apiUrl = openaiState.integrationTargets.codex2api.codex2apiUrl;
next.codex2apiAdminKey = openaiState.integrationTargets.codex2api.codex2apiAdminKey;
next.customPassword = normalizedState.services.account.customPassword;
next.signupMethod = openaiState.signup.signupMethod;
next.phoneVerificationEnabled = openaiState.signup.phoneVerificationEnabled;
next.phoneSignupReloginAfterBindEmailEnabled = openaiState.signup.phoneSignupReloginAfterBindEmailEnabled;
next.plusModeEnabled = openaiState.plus.plusModeEnabled;
next.plusPaymentMethod = openaiState.plus.plusPaymentMethod;
next.plusAccountAccessStrategy = openaiState.plus.plusAccountAccessStrategy;
next.hostedCheckoutVerificationUrl = openaiState.plus.hostedCheckoutVerificationUrl;
next.hostedCheckoutPhoneNumber = openaiState.plus.hostedCheckoutPhoneNumber;
next.plusHostedCheckoutOauthDelaySeconds = openaiState.plus.plusHostedCheckoutOauthDelaySeconds;
next.mailProvider = normalizedState.services.email.provider;
next.ipProxyEnabled = normalizedState.services.proxy.enabled;
next.ipProxyService = normalizedState.services.proxy.provider;
next.ipProxyMode = normalizedState.services.proxy.mode;
next.kiroRsUrl = kiroState.targets['kiro-rs'].baseUrl;
next.kiroRsKey = kiroState.targets['kiro-rs'].apiKey;
next.stepExecutionRangeByFlow = buildStepExecutionRangeByFlow(normalizedState);
next.settingsSchemaVersion = normalizedState.schemaVersion;
next.settingsState = cloneValue(normalizedState);
return next;
}
function getFlowInputState(settingsState = {}, flowId) {
const normalizedState = normalizeSettingsState(settingsState);
const normalizedFlowId = normalizeFlowId(flowId, normalizedState.activeFlowId);
const targetId = getSelectedTargetId(normalizedState, normalizedFlowId);
if (normalizedFlowId === 'kiro') {
return {
activeFlowId: normalizedFlowId,
targetId,
kiroRsUrl: normalizedState.flows.kiro.targets['kiro-rs'].baseUrl,
kiroRsKey: normalizedState.flows.kiro.targets['kiro-rs'].apiKey,
};
}
return {
activeFlowId: normalizedFlowId,
targetId,
};
}
return {
buildDefaultSettingsState,
buildSettingsView,
buildStepExecutionRangeByFlow,
getFlowInputState,
getFlowSettings,
getSelectedTargetId,
mergeSettingsState,
normalizeSettingsState,
};
}
return {
createSettingsSchema,
};
});
-406
View File
@@ -1,406 +0,0 @@
(function attachMultiPageSourceRegistry(root, factory) {
root.MultiPageSourceRegistry = factory();
})(typeof self !== 'undefined' ? self : globalThis, function createSourceRegistryModule() {
const rootScope = typeof self !== 'undefined' ? self : globalThis;
const flowRegistryApi = rootScope.MultiPageFlowRegistry || {};
const SOURCE_ALIASES = Object.freeze({
'signup-page': 'openai-auth',
});
const SHARED_SOURCE_DEFINITIONS = Object.freeze({
'qq-mail': {
flowId: null,
kind: 'mail-provider',
label: 'QQ 邮箱',
readyPolicy: 'top-frame-only',
family: 'qq-mail-family',
driverId: 'content/qq-mail',
cleanupScopes: [],
},
'mail-163': {
flowId: null,
kind: 'mail-provider',
label: '163 邮箱',
readyPolicy: 'top-frame-only',
family: 'mail-163-family',
driverId: 'content/mail-163',
cleanupScopes: [],
},
'gmail-mail': {
flowId: null,
kind: 'mail-provider',
label: 'Gmail 邮箱',
readyPolicy: 'top-frame-only',
family: 'gmail-mail-family',
driverId: 'content/gmail-mail',
cleanupScopes: [],
},
'icloud-mail': {
flowId: null,
kind: 'mail-provider',
label: 'iCloud 邮箱',
readyPolicy: 'allow-child-frame',
family: 'icloud-mail-family',
driverId: 'content/icloud-mail',
cleanupScopes: [],
},
'inbucket-mail': {
flowId: null,
kind: 'mail-provider',
label: 'Inbucket 邮箱',
readyPolicy: 'top-frame-only',
family: 'inbucket-mail-family',
driverId: 'content/inbucket-mail',
cleanupScopes: [],
},
'mail-2925': {
flowId: null,
kind: 'mail-provider',
label: '2925 邮箱',
readyPolicy: 'top-frame-only',
family: 'mail-2925-family',
driverId: 'content/mail-2925',
cleanupScopes: [],
},
'duck-mail': {
flowId: null,
kind: 'mail-provider',
label: 'Duck 邮箱',
readyPolicy: 'allow-child-frame',
family: 'duck-mail-family',
driverId: 'content/duck-mail',
cleanupScopes: [],
},
'unknown-source': {
flowId: null,
kind: 'unknown',
label: '未知来源',
readyPolicy: 'disabled',
family: 'unknown-family',
driverId: null,
cleanupScopes: [],
},
});
const SHARED_DRIVER_DEFINITIONS = Object.freeze({
'content/qq-mail': {
sourceId: 'qq-mail',
commands: ['POLL_EMAIL'],
},
'content/mail-163': {
sourceId: 'mail-163',
commands: ['POLL_EMAIL'],
},
'content/gmail-mail': {
sourceId: 'gmail-mail',
commands: ['POLL_EMAIL'],
},
'content/icloud-mail': {
sourceId: 'icloud-mail',
commands: ['POLL_EMAIL'],
},
'content/mail-2925': {
sourceId: 'mail-2925',
commands: ['POLL_EMAIL'],
},
'content/duck-mail': {
sourceId: 'duck-mail',
commands: ['FETCH_ALIAS_EMAIL'],
},
});
const CLEANUP_SCOPE_OWNERS = Object.freeze({
'oauth-localhost-callback': 'openai-auth',
});
const AUTH_PAGE_HOSTS = new Set(['auth0.openai.com', 'auth.openai.com', 'accounts.openai.com']);
const ENTRY_PAGE_HOSTS = new Set(['chatgpt.com', 'www.chatgpt.com', 'chat.openai.com']);
const CHILD_FRAME_BLOCKED_SOURCES = new Set([
'qq-mail',
'mail-163',
'gmail-mail',
'mail-2925',
'inbucket-mail',
'plus-checkout',
'kiro-register-page',
'kiro-desktop-authorize',
]);
function normalizeHostname(hostname = '') {
return String(hostname || '').trim().toLowerCase();
}
function matchesNamedHostFamily(hostname = '', family = '') {
const normalizedHost = normalizeHostname(hostname);
const normalizedFamily = normalizeHostname(family);
if (!normalizedHost || !normalizedFamily) {
return false;
}
return normalizedHost === normalizedFamily
|| normalizedHost.endsWith(`.${normalizedFamily}`)
|| normalizedHost.startsWith(`${normalizedFamily}.`)
|| normalizedHost.includes(`.${normalizedFamily}.`);
}
function isKiroWebHost(hostname = '') {
const normalized = normalizeHostname(hostname);
return normalized === 'app.kiro.dev'
|| normalized === 'kiro.dev';
}
function isKiroAwsAuthHost(hostname = '') {
const normalized = normalizeHostname(hostname);
return normalized === 'view.awsapps.com'
|| normalized === 'login.awsapps.com'
|| matchesNamedHostFamily(normalized, 'signin.aws')
|| matchesNamedHostFamily(normalized, 'profile.aws')
|| normalized === 'amazonaws.com'
|| normalized.endsWith('.amazonaws.com');
}
function isKiroRegisterHost(hostname = '') {
return isKiroWebHost(hostname) || isKiroAwsAuthHost(hostname);
}
function getRuntimeSourceDefinitions() {
return {
...(typeof flowRegistryApi.getRuntimeSourceDefinitions === 'function'
? flowRegistryApi.getRuntimeSourceDefinitions()
: {}),
...SHARED_SOURCE_DEFINITIONS,
};
}
function getDriverDefinitions() {
return {
...(typeof flowRegistryApi.getDriverDefinitions === 'function'
? flowRegistryApi.getDriverDefinitions()
: {}),
...SHARED_DRIVER_DEFINITIONS,
};
}
function createSourceRegistry() {
const SOURCE_DEFINITIONS = getRuntimeSourceDefinitions();
const DRIVER_DEFINITIONS = getDriverDefinitions();
function parseUrlSafely(rawUrl) {
if (!rawUrl) return null;
try {
return new URL(rawUrl);
} catch {
return null;
}
}
function normalizeSourceId(source) {
return String(source || '').trim();
}
function resolveCanonicalSource(source) {
const normalized = normalizeSourceId(source);
if (!normalized) return '';
return SOURCE_ALIASES[normalized] || normalized;
}
function getAliasKeysForCanonicalSource(source) {
const canonical = resolveCanonicalSource(source);
return Object.keys(SOURCE_ALIASES).filter((alias) => SOURCE_ALIASES[alias] === canonical);
}
function getSourceKeys(source) {
const normalized = normalizeSourceId(source);
const canonical = resolveCanonicalSource(normalized);
return Array.from(new Set([
canonical,
...getAliasKeysForCanonicalSource(canonical),
normalized,
].filter(Boolean)));
}
function getSourceMeta(source) {
const canonical = resolveCanonicalSource(source);
const definition = SOURCE_DEFINITIONS[canonical];
if (!definition) {
return null;
}
return {
id: canonical,
aliases: getAliasKeysForCanonicalSource(canonical),
...definition,
};
}
function getSourceLabel(source) {
return getSourceMeta(source)?.label || normalizeSourceId(source) || '未知来源';
}
function getDriverIdForSource(source) {
return getSourceMeta(source)?.driverId || null;
}
function getDriverMeta(sourceOrDriverId) {
const directDriverId = normalizeSourceId(sourceOrDriverId);
const driverId = Object.prototype.hasOwnProperty.call(DRIVER_DEFINITIONS, directDriverId)
? directDriverId
: getDriverIdForSource(sourceOrDriverId);
if (!driverId || !Object.prototype.hasOwnProperty.call(DRIVER_DEFINITIONS, driverId)) {
return null;
}
return {
id: driverId,
...DRIVER_DEFINITIONS[driverId],
};
}
function driverAcceptsCommand(sourceOrDriverId, command) {
const normalizedCommand = normalizeSourceId(command);
if (!normalizedCommand) {
return false;
}
const driver = getDriverMeta(sourceOrDriverId);
return Array.isArray(driver?.commands) && driver.commands.includes(normalizedCommand);
}
function isSignupPageHost(hostname = '') {
return AUTH_PAGE_HOSTS.has(normalizeHostname(hostname));
}
function isSignupEntryHost(hostname = '') {
return ENTRY_PAGE_HOSTS.has(normalizeHostname(hostname));
}
function is163MailHost(hostname = '') {
const normalized = normalizeHostname(hostname);
return normalized === 'mail.163.com'
|| normalized.endsWith('.mail.163.com')
|| normalized === 'mail.126.com'
|| normalized.endsWith('.mail.126.com')
|| normalized === 'webmail.vip.163.com';
}
function matchesSourceUrlFamily(source, candidateUrl, referenceUrl) {
const candidate = parseUrlSafely(candidateUrl);
if (!candidate) return false;
const canonical = resolveCanonicalSource(source);
const reference = parseUrlSafely(referenceUrl);
switch (canonical) {
case 'openai-auth':
return isSignupPageHost(candidate.hostname) || isSignupEntryHost(candidate.hostname);
case 'chatgpt':
return isSignupEntryHost(candidate.hostname);
case 'duck-mail':
return candidate.hostname === 'duckduckgo.com' && candidate.pathname.startsWith('/email/');
case 'qq-mail':
return candidate.hostname === 'mail.qq.com' || candidate.hostname === 'wx.mail.qq.com';
case 'mail-163':
return is163MailHost(candidate.hostname);
case 'gmail-mail':
return candidate.hostname === 'mail.google.com';
case 'icloud-mail':
return candidate.hostname === 'www.icloud.com'
|| candidate.hostname === 'www.icloud.com.cn';
case 'inbucket-mail':
return Boolean(reference)
&& candidate.origin === reference.origin
&& candidate.pathname.startsWith('/m/');
case 'mail-2925':
return candidate.hostname === '2925.com' || candidate.hostname === 'www.2925.com';
case 'vps-panel':
return Boolean(reference)
&& candidate.origin === reference.origin
&& candidate.pathname === reference.pathname;
case 'sub2api-panel':
return Boolean(reference)
&& candidate.origin === reference.origin
&& (
candidate.pathname.startsWith('/admin/accounts')
|| candidate.pathname.startsWith('/login')
|| candidate.pathname === '/'
);
case 'codex2api-panel':
return Boolean(reference)
&& candidate.origin === reference.origin
&& (
candidate.pathname.startsWith('/admin/accounts')
|| candidate.pathname === '/admin'
|| candidate.pathname === '/'
);
case 'plus-checkout':
return candidate.hostname === 'chatgpt.com'
&& candidate.pathname.startsWith('/checkout/');
case 'paypal-flow':
return candidate.hostname.endsWith('paypal.com');
case 'gopay-flow':
return /gopay|gojek/i.test(candidate.hostname);
case 'kiro-register-page':
return isKiroRegisterHost(candidate.hostname);
case 'kiro-desktop-authorize':
return isKiroAwsAuthHost(candidate.hostname);
default:
return false;
}
}
function detectSourceFromLocation({
injectedSource,
url = '',
hostname = '',
} = {}) {
if (injectedSource) return resolveCanonicalSource(injectedSource);
const normalizedHostname = String(hostname || '').toLowerCase();
const normalizedUrl = String(url || '');
if (isSignupPageHost(normalizedHostname)) return 'openai-auth';
if (normalizedHostname === 'mail.qq.com' || normalizedHostname === 'wx.mail.qq.com') return 'qq-mail';
if (is163MailHost(normalizedHostname)) return 'mail-163';
if (normalizedHostname === 'mail.google.com') return 'gmail-mail';
if (normalizedHostname === 'www.icloud.com' || normalizedHostname === 'www.icloud.com.cn') return 'icloud-mail';
if (normalizedUrl.includes('duckduckgo.com/email/settings/autofill')) return 'duck-mail';
if (normalizedUrl.includes('2925.com')) return 'mail-2925';
if (isKiroRegisterHost(normalizedHostname)) return 'kiro-register-page';
if (isSignupEntryHost(normalizedHostname)) return 'chatgpt';
return 'unknown-source';
}
function shouldReportReadyForFrame(source, isChildFrame) {
const canonical = resolveCanonicalSource(source);
const readyPolicy = getSourceMeta(canonical)?.readyPolicy || 'allow-child-frame';
if (readyPolicy === 'disabled') return false;
if (!isChildFrame) return true;
if (readyPolicy === 'top-frame-only') return false;
if (CHILD_FRAME_BLOCKED_SOURCES.has(canonical)) return false;
return true;
}
function getCleanupOwnerSource(cleanupScope) {
return resolveCanonicalSource(CLEANUP_SCOPE_OWNERS[String(cleanupScope || '').trim()] || '');
}
return {
detectSourceFromLocation,
driverAcceptsCommand,
getCleanupOwnerSource,
getDriverIdForSource,
getDriverMeta,
getSourceKeys,
getSourceLabel,
getSourceMeta,
is163MailHost,
isSignupEntryHost,
isSignupPageHost,
matchesSourceUrlFamily,
parseUrlSafely,
resolveCanonicalSource,
shouldReportReadyForFrame,
};
}
return {
createSourceRegistry,
};
});