Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
16 commits
Select commit Hold shift + click to select a range
f690c5a
Merge remote-tracking branch 'origin/main' into maanil/fe-2196-d2-con…
MaanilVerma Sep 16, 2026
a5bf629
refactor(account): own the external script loader
MaanilVerma Sep 16, 2026
c958099
refactor(account): own the region check
MaanilVerma Sep 16, 2026
f82d1da
refactor(account): inline cn for the Vue subpath
MaanilVerma Sep 16, 2026
60fe6c2
chore(account): drop the shared-frontend-utils and tailwind-utils dep…
MaanilVerma Sep 16, 2026
bc35cea
chore(ingest-types): license and publish allowlist
MaanilVerma Sep 16, 2026
ff14898
refactor(shared-frontend-utils): drop the region check now owned by a…
MaanilVerma Sep 16, 2026
e2f294f
chore(ingest-types): zod as a peer dependency
MaanilVerma Sep 16, 2026
4a4a7ed
test(account): assert publishability of sibling tarballs in the smoke…
MaanilVerma Sep 16, 2026
d964c9e
docs(account): name the copies the loader and cn must stay in sync with
MaanilVerma Sep 16, 2026
75db0b3
Merge branch 'maanil/fe-2196-d2-packaging-prep' into maanil/fe-2196-d…
MaanilVerma Sep 16, 2026
efbbf75
Merge branch 'maanil/fe-2196-d2-packaging-prep' into maanil/fe-2196-d…
MaanilVerma Sep 16, 2026
5b20731
Merge branch 'maanil/fe-2196-d2-packaging-prep' into maanil/fe-2196-d…
MaanilVerma Sep 16, 2026
141617f
Merge branch 'maanil/fe-2196-d2-packaging-prep' into maanil/fe-2196-d…
MaanilVerma Sep 16, 2026
f19758a
Merge branch 'maanil/fe-2196-d2-packaging-prep' into maanil/fe-2196-d…
MaanilVerma Sep 16, 2026
aed8ecd
Merge branch 'maanil/fe-2196-d2-packaging-prep' into maanil/fe-2196-d…
MaanilVerma Sep 16, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion apps/website/src/components/auth/AuthSignIn.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ const inChina = vi.hoisted(() => ({
}
}))
const isInChina = vi.hoisted(() => vi.fn())
vi.mock<unknown>(import('@comfyorg/shared-frontend-utils/networkUtil'), () => ({
vi.mock<unknown>(import('@comfyorg/account/region'), () => ({
isInChina
}))

Expand Down
5 changes: 3 additions & 2 deletions packages/account/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand All @@ -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": {
Expand Down
15 changes: 8 additions & 7 deletions packages/account/scripts/smokePack.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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 = `
Expand Down Expand Up @@ -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(
Expand Down
111 changes: 111 additions & 0 deletions packages/account/src/loadExternalScript.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
// Copy of packages/shared-frontend-utils/src/loadExternalScript.ts (three app callers keep that one); keep both in sync

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion (non-blocking): the copy is justified, but a comment is the weakest possible sync mechanism for 111 lines that three app callers still use from the shared package. These will drift, and the drift will be silent.

Since this one is byte-identical by construction, a tiny test that reads both files and asserts equality would turn drift into a CI failure instead of a production surprise:

// account-side test
const mine = readFileSync(resolve(__dirname, './loadExternalScript.ts'), 'utf8')
const shared = readFileSync(require.resolve('@comfyorg/shared-frontend-utils/src/loadExternalScript.ts'), 'utf8')
expect(mine).toBe(shared)

That does depend on the package still being reachable from the workspace at test time, which it is today. If you would rather not couple the test to the sibling's path, the alternative is a note on FE-2196 to delete the shared copy once its three callers move — but then the comment should say "delete after the callers move" rather than "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<T>(
src: string,
getReady: () => T | null,
timeoutMs = 10_000
): () => Promise<T> {
let scriptPromise: Promise<T> | null = null

return function loadScript(): Promise<T> {
if (scriptPromise) return scriptPromise

scriptPromise = new Promise<T>((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<HTMLScriptElement>(
`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
}
}
Original file line number Diff line number Diff line change
@@ -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`
Expand Down Expand Up @@ -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<string>(() => {})
} as Response)
fetchMock.mockResolvedValue(new Response(new ReadableStream()))

const country = getClientCountry()
expect(await settlementOf(country)).toBe('PENDING')
Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -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)
Expand Down
110 changes: 110 additions & 0 deletions packages/account/src/region.ts
Original file line number Diff line number Diff line change
@@ -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<T>(
url: string,
init: RequestInit,
read: (response: Response) => Promise<T>
): Promise<T> {
const controller = new AbortController()
let expire: ReturnType<typeof setTimeout> | undefined

const deadline = new Promise<never>((_, 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<string | undefined> {
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<boolean> {
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<boolean> {
const country = await getClientCountry()
if (country !== undefined) return country === 'CN'

return isInChinaByProbe()
}
2 changes: 1 addition & 1 deletion packages/account/src/turnstileScript.ts
Original file line number Diff line number Diff line change
@@ -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'
Expand Down
3 changes: 1 addition & 2 deletions packages/account/src/vue/PasswordRules.vue
Original file line number Diff line number Diff line change
Expand Up @@ -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<PasswordRule | 'requirements', string>
Expand Down
26 changes: 26 additions & 0 deletions packages/account/src/vue/cn.test.ts
Original file line number Diff line number Diff line change
@@ -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)
})
})
18 changes: 18 additions & 0 deletions packages/account/src/vue/cn.ts
Original file line number Diff line number Diff line change
@@ -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

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion (non-blocking): same point as loadExternalScript.ts, and slightly sharper here because the drift is silent and visual — if tailwind-utils gains a font-size key (the config currently carries text-xxs/text-xxxs and max-h-none) and this copy does not, class merging diverges and the symptom is a subtly wrong style, not an error.

Your four-row merge test covers the current config. Extending it to assert the full extendTailwindMerge option object matches the one tailwind-utils exports would catch an added key rather than just the behaviors you enumerated.

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))
}
Loading
Loading