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..d4d82c1d195 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" @@ -48,8 +49,8 @@ }, "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:" }, "devDependencies": { diff --git a/packages/account/scripts/smokePack.ts b/packages/account/scripts/smokePack.ts index 7cf1790c8ba..aec0274b24e 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 { @@ -153,7 +153,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 = ` @@ -225,10 +225,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( diff --git a/packages/account/src/loadExternalScript.ts b/packages/account/src/loadExternalScript.ts new file mode 100644 index 00000000000..dc5f3eba48b --- /dev/null +++ b/packages/account/src/loadExternalScript.ts @@ -0,0 +1,111 @@ +// Copy of packages/shared-frontend-utils/src/loadExternalScript.ts (three app callers keep that one); keep both in sync +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/shared-frontend-utils/src/networkUtil.test.ts b/packages/account/src/region.test.ts similarity index 93% rename from packages/shared-frontend-utils/src/networkUtil.test.ts rename to packages/account/src/region.test.ts index fd68637bdfe..b373021818a 100644 --- a/packages/shared-frontend-utils/src/networkUtil.test.ts +++ b/packages/account/src/region.test.ts @@ -1,9 +1,9 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' -import { getClientCountry, isInChina } from './networkUtil' +import { getClientCountry, isInChina } from './region' const traceResponse = (body: string, ok = true) => - ({ ok, text: () => Promise.resolve(body) }) as Response + new Response(body, { status: ok ? 200 : 503 }) const TRACE_BODY = (loc: string) => `fl=1187f27\nh=cloud.comfy.org\nloc=${loc}\ntls=TLSv1.3\n` @@ -66,10 +66,7 @@ describe('getClientCountry', () => { 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) + fetchMock.mockResolvedValue(new Response(new ReadableStream())) const country = getClientCountry() expect(await settlementOf(country)).toBe('PENDING') @@ -98,7 +95,7 @@ describe('isInChina', () => { fetchMock.mockImplementation((url: string) => url.includes('cdn-cgi') || url.includes('google') ? Promise.reject(new Error('blocked')) - : Promise.resolve({ ok: true } as Response) + : Promise.resolve(new Response()) ) await expect( @@ -128,7 +125,7 @@ describe('isInChina', () => { fetchMock.mockImplementation((url: string) => url.includes('cdn-cgi') ? Promise.reject(new Error('edge down')) - : Promise.resolve({ ok: true } as Response) + : Promise.resolve(new Response()) ) await expect(isInChina()).resolves.toBe(false) 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/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' 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..56fbd2c6d25 --- /dev/null +++ b/packages/account/src/vue/cn.ts @@ -0,0 +1,18 @@ +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: { + '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/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/packages/ingest-types/package.json b/packages/ingest-types/package.json index 42a4f81d6bc..c6bc7869af9 100644 --- a/packages/ingest-types/package.json +++ b/packages/ingest-types/package.json @@ -2,18 +2,26 @@ "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'\\\")));\"" }, - "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/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.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() -} diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 0a3507abe54..7edf87db58e 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -1168,12 +1168,12 @@ 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 + tailwind-merge: + specifier: ^2.2.0 + version: 2.6.1 zod: specifier: 'catalog:' version: 3.25.76 @@ -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: 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) }))