From a5bf6295e35190bb02fec30c3675d60bb47038b0 Mon Sep 17 00:00:00 2001 From: Maanil Verma Date: Wed, 16 Sep 2026 18:14:02 +0530 Subject: [PATCH 1/9] refactor(account): own the external script loader --- packages/account/src/loadExternalScript.ts | 110 +++++++++++++++++++++ packages/account/src/turnstileScript.ts | 2 +- 2 files changed, 111 insertions(+), 1 deletion(-) create mode 100644 packages/account/src/loadExternalScript.ts diff --git a/packages/account/src/loadExternalScript.ts b/packages/account/src/loadExternalScript.ts new file mode 100644 index 00000000000..d82b0bb00d5 --- /dev/null +++ b/packages/account/src/loadExternalScript.ts @@ -0,0 +1,110 @@ +const POLL_INTERVAL_MS = 50 + +/** + * Returns a singleton loader for an external script. `getReady` should return + * the resolved value when the script's global is available, or `null` when not. + * The returned function caches the in-flight Promise so concurrent callers share + * one load, and resets on failure so a later caller can retry. + */ +export function createScriptLoader( + src: string, + getReady: () => T | null, + timeoutMs = 10_000 +): () => Promise { + let scriptPromise: Promise | null = null + + return function loadScript(): Promise { + if (scriptPromise) return scriptPromise + + scriptPromise = new Promise((resolve, reject) => { + let settled = false + let cancelPoll: (() => void) | undefined + + function trySettle(fn: () => void) { + if (settled) return + settled = true + fn() + } + + const ready = getReady() + if (ready !== null) { + resolve(ready) + return + } + + const existing = document.querySelector( + `script[src="${src}"]` + ) + + function startPoll(onSuccess: () => void): () => void { + const pollId = window.setInterval(() => { + const value = getReady() + if (value !== null) { + window.clearInterval(pollId) + onSuccess() + trySettle(() => resolve(value)) + } + }, POLL_INTERVAL_MS) + return () => window.clearInterval(pollId) + } + + if (existing) { + // load/error may have already fired on the pre-existing tag; poll for readiness + const timeoutId = window.setTimeout(() => { + cancelPoll?.() + trySettle(() => { + scriptPromise = null + reject(new Error(`Script load timed out: ${src}`)) + }) + }, timeoutMs) + cancelPoll = startPoll(() => window.clearTimeout(timeoutId)) + return + } + + const scriptEl = document.createElement('script') + + const timeoutId = window.setTimeout(() => { + cancelPoll?.() + scriptEl.remove() + trySettle(() => { + scriptPromise = null + reject(new Error(`Script load timed out: ${src}`)) + }) + }, timeoutMs) + + scriptEl.addEventListener( + 'load', + () => { + if (settled) return + const value = getReady() + if (value !== null) { + window.clearTimeout(timeoutId) + trySettle(() => resolve(value)) + } else { + // global may arrive asynchronously after load; poll under the shared timeout + cancelPoll = startPoll(() => window.clearTimeout(timeoutId)) + } + }, + { once: true } + ) + scriptEl.addEventListener( + 'error', + () => { + window.clearTimeout(timeoutId) + scriptEl.remove() + trySettle(() => { + scriptPromise = null + reject(new Error(`Script failed to load: ${src}`)) + }) + }, + { once: true } + ) + + scriptEl.src = src + scriptEl.async = true + document.head.appendChild(scriptEl) + }) + + return scriptPromise + } +} diff --git a/packages/account/src/turnstileScript.ts b/packages/account/src/turnstileScript.ts index 0e64f1735af..e80dfa54537 100644 --- a/packages/account/src/turnstileScript.ts +++ b/packages/account/src/turnstileScript.ts @@ -1,4 +1,4 @@ -import { createScriptLoader } from '@comfyorg/shared-frontend-utils/loadExternalScript' +import { createScriptLoader } from './loadExternalScript' const TURNSTILE_SRC = 'https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit' From c9580994e22b38d332727a0bf196a45962f671f4 Mon Sep 17 00:00:00 2001 From: Maanil Verma Date: Wed, 16 Sep 2026 18:17:07 +0530 Subject: [PATCH 2/9] refactor(account): own the region check --- .../src/components/auth/AuthSignIn.test.ts | 2 +- packages/account/package.json | 1 + packages/account/src/region.test.ts | 161 ++++++++++++++++++ packages/account/src/region.ts | 110 ++++++++++++ packages/account/src/vue/regionGate.test.ts | 2 +- packages/account/src/vue/regionGate.ts | 2 +- .../dialog/content/SignInContent.test.ts | 2 +- .../cloud/onboarding/CloudSignupView.test.ts | 2 +- 8 files changed, 277 insertions(+), 5 deletions(-) create mode 100644 packages/account/src/region.test.ts create mode 100644 packages/account/src/region.ts diff --git a/apps/website/src/components/auth/AuthSignIn.test.ts b/apps/website/src/components/auth/AuthSignIn.test.ts index a4aaa03a258..9edd6b4f9be 100644 --- a/apps/website/src/components/auth/AuthSignIn.test.ts +++ b/apps/website/src/components/auth/AuthSignIn.test.ts @@ -82,7 +82,7 @@ const inChina = vi.hoisted(() => ({ } })) const isInChina = vi.hoisted(() => vi.fn()) -vi.mock(import('@comfyorg/shared-frontend-utils/networkUtil'), () => ({ +vi.mock(import('@comfyorg/account/region'), () => ({ isInChina })) diff --git a/packages/account/package.json b/packages/account/package.json index 6b6e60c0c16..4143f000d87 100644 --- a/packages/account/package.json +++ b/packages/account/package.json @@ -33,6 +33,7 @@ "./firebaseAuthError": "./src/firebaseAuthError.ts", "./provisioning": "./src/provisioning.ts", "./redirect": "./src/redirect.ts", + "./region": "./src/region.ts", "./telemetry": "./src/telemetry.ts", "./webviewDetection": "./src/webviewDetection.ts", "./package.json": "./package.json" diff --git a/packages/account/src/region.test.ts b/packages/account/src/region.test.ts new file mode 100644 index 00000000000..b373021818a --- /dev/null +++ b/packages/account/src/region.test.ts @@ -0,0 +1,161 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' + +import { getClientCountry, isInChina } from './region' + +const traceResponse = (body: string, ok = true) => + new Response(body, { status: ok ? 200 : 503 }) + +const TRACE_BODY = (loc: string) => + `fl=1187f27\nh=cloud.comfy.org\nloc=${loc}\ntls=TLSv1.3\n` + +/** Blackholes: never settles and ignores the abort signal. */ +const neverSettles = () => new Promise(() => {}) + +/** Resolves to the settled value, or to `PENDING` if the promise has not. */ +const settlementOf = (promise: Promise) => + Promise.race([promise, Promise.resolve().then(() => 'PENDING' as const)]) + +const fetchMock = vi.fn() + +beforeEach(() => { + vi.stubGlobal('fetch', fetchMock) + vi.stubGlobal('navigator', { language: 'en-US' }) + fetchMock.mockReset() +}) + +describe('getClientCountry', () => { + it('returns the uppercased loc value from the edge trace', async () => { + fetchMock.mockResolvedValue(traceResponse(TRACE_BODY('cn'))) + + await expect(getClientCountry()).resolves.toBe('CN') + }) + + it.for([ + [ + 'a non-200 response', + () => Promise.resolve(traceResponse('loc=CN', false)) + ], + [ + 'a body with no loc line', + () => Promise.resolve(traceResponse('h=x\nts=1')) + ], + ['an empty loc value', () => Promise.resolve(traceResponse('loc=\n'))], + [ + 'an unknown-country sentinel', + () => Promise.resolve(traceResponse(TRACE_BODY('XX'))) + ], + ['a Tor sentinel', () => Promise.resolve(traceResponse(TRACE_BODY('T1')))], + ['a network error', () => Promise.reject(new Error('offline'))] + ] as const)('returns undefined for %s', async ([, respond]) => { + fetchMock.mockImplementation(respond) + + await expect(getClientCountry()).resolves.toBeUndefined() + }) + + it('gives up rather than hanging when the edge never answers', async () => { + vi.useFakeTimers() + fetchMock.mockImplementation(neverSettles) + + const country = getClientCountry() + expect(await settlementOf(country)).toBe('PENDING') + + await vi.advanceTimersByTimeAsync(2000) + + expect(await settlementOf(country)).toBeUndefined() + }) + + it('gives up when the edge sends headers and then stalls the body', async () => { + vi.useFakeTimers() + fetchMock.mockResolvedValue(new Response(new ReadableStream())) + + const country = getClientCountry() + expect(await settlementOf(country)).toBe('PENDING') + + await vi.advanceTimersByTimeAsync(2000) + + expect(await settlementOf(country)).toBeUndefined() + }) +}) + +describe('isInChina', () => { + it('trusts the edge answer over the reachability heuristic', async () => { + fetchMock.mockResolvedValue(traceResponse(TRACE_BODY('CN'))) + + await expect(isInChina()).resolves.toBe(true) + expect(fetchMock).toHaveBeenCalledTimes(1) + }) + + it('reports outside China when the edge names another country', async () => { + fetchMock.mockResolvedValue(traceResponse(TRACE_BODY('IN'))) + + await expect(isInChina()).resolves.toBe(false) + }) + + it('reports inside China when only Baidu answers, and fast', async () => { + fetchMock.mockImplementation((url: string) => + url.includes('cdn-cgi') || url.includes('google') + ? Promise.reject(new Error('blocked')) + : Promise.resolve(new Response()) + ) + + await expect( + isInChina(), + 'a China-routed client on a non-zh locale is only detectable by Baidu latency' + ).resolves.toBe(true) + }) + + it.for(['XX', 'T1'] as const)( + 'falls back to the heuristic when the edge answers %s', + async (sentinel) => { + vi.stubGlobal('navigator', { language: 'zh-CN' }) + fetchMock.mockImplementation((url: string) => + url.includes('cdn-cgi') + ? Promise.resolve(traceResponse(TRACE_BODY(sentinel))) + : Promise.reject(new Error('blocked')) + ) + + await expect( + isInChina(), + 'a sentinel names no country, so treating it as "not China" would wave through Tor and unknown-IP clients' + ).resolves.toBe(true) + } + ) + + it('reports outside China when the edge is down but Google answers', async () => { + fetchMock.mockImplementation((url: string) => + url.includes('cdn-cgi') + ? Promise.reject(new Error('edge down')) + : Promise.resolve(new Response()) + ) + + await expect(isInChina()).resolves.toBe(false) + }) + + it('falls back to the locale when neither probe answers', async () => { + fetchMock.mockRejectedValue(new Error('blocked')) + + await expect(isInChina()).resolves.toBe(false) + }) + + it('falls back to the reachability heuristic when the edge cannot answer', async () => { + vi.stubGlobal('navigator', { language: 'zh-CN' }) + fetchMock.mockImplementation((url: string) => + url.includes('cdn-cgi') + ? Promise.reject(new Error('edge down')) + : Promise.reject(new Error('blocked')) + ) + + await expect(isInChina()).resolves.toBe(true) + }) + + it('settles even when every probe hangs forever', async () => { + vi.useFakeTimers() + fetchMock.mockImplementation(neverSettles) + + const verdict = isInChina() + for (const _ of [0, 1, 2]) await vi.advanceTimersByTimeAsync(2000) + + expect(await settlementOf(verdict)).toBe(false) + expect(fetchMock).toHaveBeenCalledTimes(3) + }) +}) diff --git a/packages/account/src/region.ts b/packages/account/src/region.ts new file mode 100644 index 00000000000..703a10e7f1d --- /dev/null +++ b/packages/account/src/region.ts @@ -0,0 +1,110 @@ +/** + * A CDN implementation detail, not a contract we own. The durable form is a + * first-party endpoint echoing `CF-IPCountry`. + */ +const CLIENT_COUNTRY_URL = 'https://cloud.comfy.org/cdn-cgi/trace' + +/** Bounds every probe leg; two previously had none. */ +const PROBE_TIMEOUT_MS = 2000 + +/** Baidu answering this fast implies a China route. */ +const CHINA_LATENCY_MS = 150 + +/** `XX` is an unknown country and `T1` is Tor: neither names where the client is. */ +const UNRESOLVED_COUNTRIES = new Set(['XX', 'T1']) + +const parseTraceCountry = (body: string): string | undefined => { + const country = + body + .split('\n') + .find((line) => line.startsWith('loc=')) + ?.slice('loc='.length) + .trim() + .toUpperCase() || undefined + + return country && UNRESOLVED_COUNTRIES.has(country) ? undefined : country +} + +/** + * The abort signal alone is not enough: a request the browser never resolves + * nor rejects would hang forever, so the deadline rejects independently. + * + * `read` runs inside the deadline so a response that sends headers and then + * stalls its body is bounded too. + */ +async function fetchWithin( + url: string, + init: RequestInit, + read: (response: Response) => Promise +): Promise { + const controller = new AbortController() + let expire: ReturnType | undefined + + const deadline = new Promise((_, reject) => { + expire = setTimeout(() => { + controller.abort() + reject(new Error(`Timed out after ${PROBE_TIMEOUT_MS}ms: ${url}`)) + }, PROBE_TIMEOUT_MS) + }) + + try { + return await Promise.race([ + fetch(url, { ...init, signal: controller.signal }).then(read), + deadline + ]) + } finally { + clearTimeout(expire) + } +} + +/** ISO country from the CDN edge, or `undefined` when it cannot answer. */ +export async function getClientCountry(): Promise { + try { + const body = await fetchWithin( + CLIENT_COUNTRY_URL, + { cache: 'no-store' }, + async (response) => (response.ok ? response.text() : undefined) + ) + return body === undefined ? undefined : parseTraceCountry(body) + } catch { + return undefined + } +} + +const probe = (url: string) => + fetchWithin(url, { mode: 'no-cors', cache: 'no-cache' }, async () => {}) + +/** + * Fallback for when the edge cannot answer. Unsound both ways: a VPN user in + * China reaches Google, and a `zh-CN` user anywhere is blocked whenever Google + * is briefly unreachable. + */ +async function isInChinaByProbe(): Promise { + const isChineseLocale = navigator.language.toLowerCase().startsWith('zh-cn') + + try { + await probe('https://www.google.com') + return false + } catch { + if (isChineseLocale) return true + + try { + const start = performance.now() + await probe('https://www.baidu.com') + return performance.now() - start < CHINA_LATENCY_MS + } catch { + return isChineseLocale + } + } +} + +/** + * Prefers the edge's geo-IP, falling back to the heuristic. Always settles, so + * callers must not add a timeout that could pre-empt a slow but real answer. + */ +export async function isInChina(): Promise { + const country = await getClientCountry() + if (country !== undefined) return country === 'CN' + + return isInChinaByProbe() +} diff --git a/packages/account/src/vue/regionGate.test.ts b/packages/account/src/vue/regionGate.test.ts index f8cf9c12313..26ef4e30475 100644 --- a/packages/account/src/vue/regionGate.test.ts +++ b/packages/account/src/vue/regionGate.test.ts @@ -8,7 +8,7 @@ const detection = vi.hoisted(() => ({ outcome: Promise.resolve(false), probes: 0 })) -vi.mock(import('@comfyorg/shared-frontend-utils/networkUtil'), () => ({ +vi.mock(import('@comfyorg/account/region'), () => ({ isInChina: () => { detection.probes += 1 return detection.outcome diff --git a/packages/account/src/vue/regionGate.ts b/packages/account/src/vue/regionGate.ts index c53096df9e2..184decb3858 100644 --- a/packages/account/src/vue/regionGate.ts +++ b/packages/account/src/vue/regionGate.ts @@ -1,7 +1,7 @@ import { onMounted, readonly, ref, watch } from 'vue' import type { Ref } from 'vue' -import { isInChina } from '@comfyorg/shared-frontend-utils/networkUtil' +import { isInChina } from '../region' export type RegionGateStatus = 'pending' | 'blocked' | 'allowed' diff --git a/src/components/dialog/content/SignInContent.test.ts b/src/components/dialog/content/SignInContent.test.ts index 61bae5bb5a2..6eac9f96751 100644 --- a/src/components/dialog/content/SignInContent.test.ts +++ b/src/components/dialog/content/SignInContent.test.ts @@ -39,7 +39,7 @@ const inChina = vi.hoisted(() => ({ this.pending = Promise.reject(error) } })) -vi.mock(import('@comfyorg/shared-frontend-utils/networkUtil'), () => ({ +vi.mock(import('@comfyorg/account/region'), () => ({ isInChina: () => inChina.pending ?? Promise.resolve(inChina.value) })) diff --git a/src/platform/cloud/onboarding/CloudSignupView.test.ts b/src/platform/cloud/onboarding/CloudSignupView.test.ts index 8a33f68e558..23d4e3b3d93 100644 --- a/src/platform/cloud/onboarding/CloudSignupView.test.ts +++ b/src/platform/cloud/onboarding/CloudSignupView.test.ts @@ -38,7 +38,7 @@ const inChina = vi.hoisted(() => ({ this.pending = Promise.reject(error) } })) -vi.mock(import('@comfyorg/shared-frontend-utils/networkUtil'), () => ({ +vi.mock(import('@comfyorg/account/region'), () => ({ isInChina: () => inChina.pending ?? Promise.resolve(inChina.value) })) From f82d1daf241f290ea35daa3bfcb6f6e580dc3adc Mon Sep 17 00:00:00 2001 From: Maanil Verma Date: Wed, 16 Sep 2026 18:21:03 +0530 Subject: [PATCH 3/9] refactor(account): inline cn for the Vue subpath --- packages/account/package.json | 2 ++ packages/account/src/vue/PasswordRules.vue | 3 +-- packages/account/src/vue/cn.test.ts | 26 ++++++++++++++++++++++ packages/account/src/vue/cn.ts | 17 ++++++++++++++ pnpm-lock.yaml | 6 +++++ 5 files changed, 52 insertions(+), 2 deletions(-) create mode 100644 packages/account/src/vue/cn.test.ts create mode 100644 packages/account/src/vue/cn.ts diff --git a/packages/account/package.json b/packages/account/package.json index 4143f000d87..9dd9ec7f953 100644 --- a/packages/account/package.json +++ b/packages/account/package.json @@ -51,6 +51,8 @@ "@comfyorg/ingest-types": "workspace:*", "@comfyorg/shared-frontend-utils": "workspace:*", "@comfyorg/tailwind-utils": "workspace:*", + "clsx": "^2.1.1", + "tailwind-merge": "^2.2.0", "zod": "catalog:" }, "devDependencies": { diff --git a/packages/account/src/vue/PasswordRules.vue b/packages/account/src/vue/PasswordRules.vue index 85289159f7b..85c3030f85c 100644 --- a/packages/account/src/vue/PasswordRules.vue +++ b/packages/account/src/vue/PasswordRules.vue @@ -30,10 +30,9 @@ */ import { computed } from 'vue' -import { cn } from '@comfyorg/tailwind-utils' - import type { PasswordRule } from '../signInSchemas' import { passwordRuleChecks } from '../signInSchemas' +import { cn } from './cn' export type PasswordRulesCopy = Readonly< Record diff --git a/packages/account/src/vue/cn.test.ts b/packages/account/src/vue/cn.test.ts new file mode 100644 index 00000000000..e0f1b8ed9dd --- /dev/null +++ b/packages/account/src/vue/cn.test.ts @@ -0,0 +1,26 @@ +import { describe, expect, it } from 'vitest' + +import { cn } from './cn' + +describe('cn', () => { + it.for([ + [ + 'a custom font size overrides a stock one', + 'text-sm text-xxs', + 'text-xxs' + ], + [ + 'a stock font size overrides a custom one', + 'text-xxxs text-lg', + 'text-lg' + ], + [ + 'max-h-none overrides an arbitrary max height', + 'max-h-[80vh] max-h-none', + 'max-h-none' + ], + ['a falsy entry is dropped', ['p-2', false, 'm-1'], 'p-2 m-1'] + ] as const)('%s', ([, input, expected]) => { + expect(cn(input)).toBe(expected) + }) +}) diff --git a/packages/account/src/vue/cn.ts b/packages/account/src/vue/cn.ts new file mode 100644 index 00000000000..a52975a8e6a --- /dev/null +++ b/packages/account/src/vue/cn.ts @@ -0,0 +1,17 @@ +import { clsx } from 'clsx' +import type { ClassArray } from 'clsx' +import { extendTailwindMerge } from 'tailwind-merge' + +const twMerge = extendTailwindMerge({ + extend: { + classGroups: { + 'font-size': ['text-xxs', 'text-xxxs'], + // tailwind-merge does not know `max-h-none`, so `max-h-[80vh] max-h-none` would keep both + 'max-h': [{ 'max-h': ['none'] }] + } + } +}) + +export function cn(...inputs: ClassArray): string { + return twMerge(clsx(inputs)) +} diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 0a3507abe54..1ec7ff7c5a7 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -1174,6 +1174,12 @@ importers: '@comfyorg/tailwind-utils': specifier: workspace:* version: link:../tailwind-utils + clsx: + specifier: ^2.1.1 + version: 2.1.1 + tailwind-merge: + specifier: ^2.2.0 + version: 2.6.1 zod: specifier: 'catalog:' version: 3.25.76 From 60fe6c2d83af9d860d6aeb42cd5806176b2d8938 Mon Sep 17 00:00:00 2001 From: Maanil Verma Date: Wed, 16 Sep 2026 18:22:53 +0530 Subject: [PATCH 4/9] chore(account): drop the shared-frontend-utils and tailwind-utils dependencies --- packages/account/package.json | 2 -- packages/account/scripts/smokePack.ts | 4 ++-- pnpm-lock.yaml | 6 ------ 3 files changed, 2 insertions(+), 10 deletions(-) diff --git a/packages/account/package.json b/packages/account/package.json index 9dd9ec7f953..d4d82c1d195 100644 --- a/packages/account/package.json +++ b/packages/account/package.json @@ -49,8 +49,6 @@ }, "dependencies": { "@comfyorg/ingest-types": "workspace:*", - "@comfyorg/shared-frontend-utils": "workspace:*", - "@comfyorg/tailwind-utils": "workspace:*", "clsx": "^2.1.1", "tailwind-merge": "^2.2.0", "zod": "catalog:" diff --git a/packages/account/scripts/smokePack.ts b/packages/account/scripts/smokePack.ts index d571b876c3a..3451f27567f 100644 --- a/packages/account/scripts/smokePack.ts +++ b/packages/account/scripts/smokePack.ts @@ -4,8 +4,8 @@ * export entry from there: the consumer path where an unrewritten * `catalog:` specifier or an export target missing from `files` first fails. * - * Workspace siblings are not on npm yet, so they are packed too and pinned - * through npm `overrides`; drop that once they are published. + * ingest-types is not on npm yet, so it is packed too and pinned through npm + * `overrides`; drop that once it is published. */ import { execFileSync } from 'node:child_process' import { diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 1ec7ff7c5a7..08dd7c7e54a 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -1168,12 +1168,6 @@ importers: '@comfyorg/ingest-types': specifier: workspace:* version: link:../ingest-types - '@comfyorg/shared-frontend-utils': - specifier: workspace:* - version: link:../shared-frontend-utils - '@comfyorg/tailwind-utils': - specifier: workspace:* - version: link:../tailwind-utils clsx: specifier: ^2.1.1 version: 2.1.1 From bc35ceadd538710bfd238c2456b17829085116c9 Mon Sep 17 00:00:00 2001 From: Maanil Verma Date: Wed, 16 Sep 2026 18:23:21 +0530 Subject: [PATCH 5/9] chore(ingest-types): license and publish allowlist --- packages/ingest-types/package.json | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/packages/ingest-types/package.json b/packages/ingest-types/package.json index 42a4f81d6bc..d23b0bdd0d5 100644 --- a/packages/ingest-types/package.json +++ b/packages/ingest-types/package.json @@ -2,11 +2,18 @@ "name": "@comfyorg/ingest-types", "version": "1.0.0", "description": "Comfy Cloud Ingest API TypeScript types and Zod schemas", + "license": "MIT", + "files": [ + "src" + ], "type": "module", "exports": { ".": "./src/index.ts", "./zod": "./src/zod.gen.ts" }, + "publishConfig": { + "access": "public" + }, "scripts": { "generate": "openapi-ts && node -e \"const fs=require('fs'); ['src/zod.gen.ts'].forEach(f => fs.writeFileSync(f, fs.readFileSync(f,'utf8').replaceAll(\\\"from 'zod/v3'\\\", \\\"from 'zod'\\\")));\"" }, From ff148988e68c7e7cbbfb9efc99eb49325c247818 Mon Sep 17 00:00:00 2001 From: Maanil Verma Date: Wed, 16 Sep 2026 18:35:41 +0530 Subject: [PATCH 6/9] refactor(shared-frontend-utils): drop the region check now owned by account --- packages/shared-frontend-utils/package.json | 1 - .../src/networkUtil.test.ts | 164 ------------------ .../shared-frontend-utils/src/networkUtil.ts | 111 ------------ 3 files changed, 276 deletions(-) delete mode 100644 packages/shared-frontend-utils/src/networkUtil.test.ts diff --git a/packages/shared-frontend-utils/package.json b/packages/shared-frontend-utils/package.json index de2148e5bd3..098ce7245ce 100644 --- a/packages/shared-frontend-utils/package.json +++ b/packages/shared-frontend-utils/package.json @@ -9,7 +9,6 @@ "./creditsUtil": "./src/creditsUtil.ts", "./formatUtil": "./src/formatUtil.ts", "./loadExternalScript": "./src/loadExternalScript.ts", - "./networkUtil": "./src/networkUtil.ts", "./nodePricing": "./src/nodePricing.ts", "./piiUtil": "./src/piiUtil.ts" }, diff --git a/packages/shared-frontend-utils/src/networkUtil.test.ts b/packages/shared-frontend-utils/src/networkUtil.test.ts deleted file mode 100644 index fd68637bdfe..00000000000 --- a/packages/shared-frontend-utils/src/networkUtil.test.ts +++ /dev/null @@ -1,164 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' - -import { getClientCountry, isInChina } from './networkUtil' - -const traceResponse = (body: string, ok = true) => - ({ ok, text: () => Promise.resolve(body) }) as Response - -const TRACE_BODY = (loc: string) => - `fl=1187f27\nh=cloud.comfy.org\nloc=${loc}\ntls=TLSv1.3\n` - -/** Blackholes: never settles and ignores the abort signal. */ -const neverSettles = () => new Promise(() => {}) - -/** Resolves to the settled value, or to `PENDING` if the promise has not. */ -const settlementOf = (promise: Promise) => - Promise.race([promise, Promise.resolve().then(() => 'PENDING' as const)]) - -const fetchMock = vi.fn() - -beforeEach(() => { - vi.stubGlobal('fetch', fetchMock) - vi.stubGlobal('navigator', { language: 'en-US' }) - fetchMock.mockReset() -}) - -describe('getClientCountry', () => { - it('returns the uppercased loc value from the edge trace', async () => { - fetchMock.mockResolvedValue(traceResponse(TRACE_BODY('cn'))) - - await expect(getClientCountry()).resolves.toBe('CN') - }) - - it.for([ - [ - 'a non-200 response', - () => Promise.resolve(traceResponse('loc=CN', false)) - ], - [ - 'a body with no loc line', - () => Promise.resolve(traceResponse('h=x\nts=1')) - ], - ['an empty loc value', () => Promise.resolve(traceResponse('loc=\n'))], - [ - 'an unknown-country sentinel', - () => Promise.resolve(traceResponse(TRACE_BODY('XX'))) - ], - ['a Tor sentinel', () => Promise.resolve(traceResponse(TRACE_BODY('T1')))], - ['a network error', () => Promise.reject(new Error('offline'))] - ] as const)('returns undefined for %s', async ([, respond]) => { - fetchMock.mockImplementation(respond) - - await expect(getClientCountry()).resolves.toBeUndefined() - }) - - it('gives up rather than hanging when the edge never answers', async () => { - vi.useFakeTimers() - fetchMock.mockImplementation(neverSettles) - - const country = getClientCountry() - expect(await settlementOf(country)).toBe('PENDING') - - await vi.advanceTimersByTimeAsync(2000) - - expect(await settlementOf(country)).toBeUndefined() - }) - - it('gives up when the edge sends headers and then stalls the body', async () => { - vi.useFakeTimers() - fetchMock.mockResolvedValue({ - ok: true, - text: () => new Promise(() => {}) - } as Response) - - const country = getClientCountry() - expect(await settlementOf(country)).toBe('PENDING') - - await vi.advanceTimersByTimeAsync(2000) - - expect(await settlementOf(country)).toBeUndefined() - }) -}) - -describe('isInChina', () => { - it('trusts the edge answer over the reachability heuristic', async () => { - fetchMock.mockResolvedValue(traceResponse(TRACE_BODY('CN'))) - - await expect(isInChina()).resolves.toBe(true) - expect(fetchMock).toHaveBeenCalledTimes(1) - }) - - it('reports outside China when the edge names another country', async () => { - fetchMock.mockResolvedValue(traceResponse(TRACE_BODY('IN'))) - - await expect(isInChina()).resolves.toBe(false) - }) - - it('reports inside China when only Baidu answers, and fast', async () => { - fetchMock.mockImplementation((url: string) => - url.includes('cdn-cgi') || url.includes('google') - ? Promise.reject(new Error('blocked')) - : Promise.resolve({ ok: true } as Response) - ) - - await expect( - isInChina(), - 'a China-routed client on a non-zh locale is only detectable by Baidu latency' - ).resolves.toBe(true) - }) - - it.for(['XX', 'T1'] as const)( - 'falls back to the heuristic when the edge answers %s', - async (sentinel) => { - vi.stubGlobal('navigator', { language: 'zh-CN' }) - fetchMock.mockImplementation((url: string) => - url.includes('cdn-cgi') - ? Promise.resolve(traceResponse(TRACE_BODY(sentinel))) - : Promise.reject(new Error('blocked')) - ) - - await expect( - isInChina(), - 'a sentinel names no country, so treating it as "not China" would wave through Tor and unknown-IP clients' - ).resolves.toBe(true) - } - ) - - it('reports outside China when the edge is down but Google answers', async () => { - fetchMock.mockImplementation((url: string) => - url.includes('cdn-cgi') - ? Promise.reject(new Error('edge down')) - : Promise.resolve({ ok: true } as Response) - ) - - await expect(isInChina()).resolves.toBe(false) - }) - - it('falls back to the locale when neither probe answers', async () => { - fetchMock.mockRejectedValue(new Error('blocked')) - - await expect(isInChina()).resolves.toBe(false) - }) - - it('falls back to the reachability heuristic when the edge cannot answer', async () => { - vi.stubGlobal('navigator', { language: 'zh-CN' }) - fetchMock.mockImplementation((url: string) => - url.includes('cdn-cgi') - ? Promise.reject(new Error('edge down')) - : Promise.reject(new Error('blocked')) - ) - - await expect(isInChina()).resolves.toBe(true) - }) - - it('settles even when every probe hangs forever', async () => { - vi.useFakeTimers() - fetchMock.mockImplementation(neverSettles) - - const verdict = isInChina() - for (const _ of [0, 1, 2]) await vi.advanceTimersByTimeAsync(2000) - - expect(await settlementOf(verdict)).toBe(false) - expect(fetchMock).toHaveBeenCalledTimes(3) - }) -}) diff --git a/packages/shared-frontend-utils/src/networkUtil.ts b/packages/shared-frontend-utils/src/networkUtil.ts index 2f3c2ef32db..ad159a4b015 100644 --- a/packages/shared-frontend-utils/src/networkUtil.ts +++ b/packages/shared-frontend-utils/src/networkUtil.ts @@ -9,114 +9,3 @@ export const checkUrlReachable = async (url: string): Promise => { return false } } - -/** - * A CDN implementation detail, not a contract we own. The durable form is a - * first-party endpoint echoing `CF-IPCountry`. - */ -const CLIENT_COUNTRY_URL = 'https://cloud.comfy.org/cdn-cgi/trace' - -/** Bounds every probe leg; two previously had none. */ -const PROBE_TIMEOUT_MS = 2000 - -/** Baidu answering this fast implies a China route. */ -const CHINA_LATENCY_MS = 150 - -/** `XX` is an unknown country and `T1` is Tor: neither names where the client is. */ -const UNRESOLVED_COUNTRIES = new Set(['XX', 'T1']) - -const parseTraceCountry = (body: string): string | undefined => { - const country = - body - .split('\n') - .find((line) => line.startsWith('loc=')) - ?.slice('loc='.length) - .trim() - .toUpperCase() || undefined - - return country && UNRESOLVED_COUNTRIES.has(country) ? undefined : country -} - -/** - * The abort signal alone is not enough: a request the browser never resolves - * nor rejects would hang forever, so the deadline rejects independently. - * - * `read` runs inside the deadline so a response that sends headers and then - * stalls its body is bounded too. - */ -async function fetchWithin( - url: string, - init: RequestInit, - read: (response: Response) => Promise -): Promise { - const controller = new AbortController() - let expire: ReturnType | undefined - - const deadline = new Promise((_, reject) => { - expire = setTimeout(() => { - controller.abort() - reject(new Error(`Timed out after ${PROBE_TIMEOUT_MS}ms: ${url}`)) - }, PROBE_TIMEOUT_MS) - }) - - try { - return await Promise.race([ - fetch(url, { ...init, signal: controller.signal }).then(read), - deadline - ]) - } finally { - clearTimeout(expire) - } -} - -/** ISO country from the CDN edge, or `undefined` when it cannot answer. */ -export async function getClientCountry(): Promise { - try { - const body = await fetchWithin( - CLIENT_COUNTRY_URL, - { cache: 'no-store' }, - async (response) => (response.ok ? response.text() : undefined) - ) - return body === undefined ? undefined : parseTraceCountry(body) - } catch { - return undefined - } -} - -const probe = (url: string) => - fetchWithin(url, { mode: 'no-cors', cache: 'no-cache' }, async () => {}) - -/** - * Fallback for when the edge cannot answer. Unsound both ways: a VPN user in - * China reaches Google, and a `zh-CN` user anywhere is blocked whenever Google - * is briefly unreachable. - */ -async function isInChinaByProbe(): Promise { - const isChineseLocale = navigator.language.toLowerCase().startsWith('zh-cn') - - try { - await probe('https://www.google.com') - return false - } catch { - if (isChineseLocale) return true - - try { - const start = performance.now() - await probe('https://www.baidu.com') - return performance.now() - start < CHINA_LATENCY_MS - } catch { - return isChineseLocale - } - } -} - -/** - * Prefers the edge's geo-IP, falling back to the heuristic. Always settles, so - * callers must not add a timeout that could pre-empt a slow but real answer. - */ -export async function isInChina(): Promise { - const country = await getClientCountry() - if (country !== undefined) return country === 'CN' - - return isInChinaByProbe() -} From e2f294fdd2732b2f1ec689ea360b51719ebf93d1 Mon Sep 17 00:00:00 2001 From: Maanil Verma Date: Wed, 16 Sep 2026 18:37:31 +0530 Subject: [PATCH 7/9] chore(ingest-types): zod as a peer dependency --- packages/ingest-types/package.json | 7 ++++--- pnpm-lock.yaml | 7 +++---- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/packages/ingest-types/package.json b/packages/ingest-types/package.json index d23b0bdd0d5..c6bc7869af9 100644 --- a/packages/ingest-types/package.json +++ b/packages/ingest-types/package.json @@ -17,10 +17,11 @@ "scripts": { "generate": "openapi-ts && node -e \"const fs=require('fs'); ['src/zod.gen.ts'].forEach(f => fs.writeFileSync(f, fs.readFileSync(f,'utf8').replaceAll(\\\"from 'zod/v3'\\\", \\\"from 'zod'\\\")));\"" }, - "dependencies": { + "devDependencies": { + "@hey-api/openapi-ts": "0.97.3", "zod": "catalog:" }, - "devDependencies": { - "@hey-api/openapi-ts": "0.97.3" + "peerDependencies": { + "zod": "^3.23.8" } } diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 08dd7c7e54a..7edf87db58e 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -1305,14 +1305,13 @@ importers: version: 4.1.11(@types/node@25.9.5)(@vitest/coverage-v8@4.1.11)(@vitest/ui@4.1.11)(happy-dom@20.10.6)(jsdom@29.1.1)(vite@8.2.2(@types/node@25.9.5)(esbuild@0.28.1)(jiti@2.7.0)(terser@5.49.0)(tsx@4.23.1)(yaml@2.9.0)) packages/ingest-types: - dependencies: - zod: - specifier: 'catalog:' - version: 3.25.76 devDependencies: '@hey-api/openapi-ts': specifier: 0.97.3 version: 0.97.3(magicast@0.5.4)(typescript@6.0.3) + zod: + specifier: 'catalog:' + version: 3.25.76 packages/object-info-parser: dependencies: From 4a4a7ed3d32149ea9c23c63733b4390d67253fb8 Mon Sep 17 00:00:00 2001 From: Maanil Verma Date: Wed, 16 Sep 2026 18:38:22 +0530 Subject: [PATCH 8/9] test(account): assert publishability of sibling tarballs in the smoke test --- packages/account/scripts/smokePack.ts | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/packages/account/scripts/smokePack.ts b/packages/account/scripts/smokePack.ts index 3451f27567f..e67b648200b 100644 --- a/packages/account/scripts/smokePack.ts +++ b/packages/account/scripts/smokePack.ts @@ -126,7 +126,7 @@ function assertPublishable(source: Manifest, packed: PackResult): void { .join('\n')}` ) } - log(`packed ${shipped.size} files, specifiers rewritten`) + log(`packed ${source.name}: ${shipped.size} files, specifiers rewritten`) } const CONSUMER_SOURCE = ` @@ -198,10 +198,11 @@ function main(): void { workspacePackageDirs() ) const overrides = Object.fromEntries( - [...siblings].map(([name, dir]) => [ - name, - `file:${pack(dir, tarballDir).filename}` - ]) + [...siblings].map(([name, dir]) => { + const packedSibling = pack(dir, tarballDir) + assertPublishable(readManifest(dir), packedSibling) + return [name, `file:${packedSibling.filename}`] + }) ) const peers = packedManifest(packed.filename).peerDependencies ?? {} writeFileSync( From d964c9e19d3517ea2a9fc6c026e807053f2367ac Mon Sep 17 00:00:00 2001 From: Maanil Verma Date: Wed, 16 Sep 2026 18:39:38 +0530 Subject: [PATCH 9/9] docs(account): name the copies the loader and cn must stay in sync with --- packages/account/src/loadExternalScript.ts | 1 + packages/account/src/vue/cn.ts | 1 + 2 files changed, 2 insertions(+) diff --git a/packages/account/src/loadExternalScript.ts b/packages/account/src/loadExternalScript.ts index d82b0bb00d5..dc5f3eba48b 100644 --- a/packages/account/src/loadExternalScript.ts +++ b/packages/account/src/loadExternalScript.ts @@ -1,3 +1,4 @@ +// Copy of packages/shared-frontend-utils/src/loadExternalScript.ts (three app callers keep that one); keep both in sync const POLL_INTERVAL_MS = 50 /** diff --git a/packages/account/src/vue/cn.ts b/packages/account/src/vue/cn.ts index a52975a8e6a..56fbd2c6d25 100644 --- a/packages/account/src/vue/cn.ts +++ b/packages/account/src/vue/cn.ts @@ -2,6 +2,7 @@ import { clsx } from 'clsx' import type { ClassArray } from 'clsx' import { extendTailwindMerge } from 'tailwind-merge' +// Mirrors packages/tailwind-utils/src/index.ts; keep both configs in sync const twMerge = extendTailwindMerge({ extend: { classGroups: {