diff --git a/packages/account/package.json b/packages/account/package.json index c320a0ea6cc..6b6e60c0c16 100644 --- a/packages/account/package.json +++ b/packages/account/package.json @@ -5,6 +5,11 @@ "description": "Shared account layer: a framework-free session core that exchanges a signed-in identity for the workspace-scoped Cloud JWT with valid-on-read freshness, the package-owned Firebase identity entry, and an optional Vue subpath for the shared sign-in pieces", "keywords": [], "license": "MIT", + "files": [ + "src", + "!src/**/*.test.ts", + "!src/**/__fixtures__" + ], "type": "module", "exports": { "./boundedOperation": "./src/core/boundedOperation.ts", @@ -29,12 +34,17 @@ "./provisioning": "./src/provisioning.ts", "./redirect": "./src/redirect.ts", "./telemetry": "./src/telemetry.ts", - "./webviewDetection": "./src/webviewDetection.ts" + "./webviewDetection": "./src/webviewDetection.ts", + "./package.json": "./package.json" + }, + "publishConfig": { + "access": "public" }, "scripts": { "lint": "oxlint src --type-aware && eslint src", + "smoke:pack": "tsx scripts/smokePack.ts", "test": "vitest run", - "typecheck": "vue-tsc --noEmit" + "typecheck": "vue-tsc --noEmit && vue-tsc --noEmit --project scripts/tsconfig.json" }, "dependencies": { "@comfyorg/ingest-types": "workspace:*", diff --git a/packages/account/scripts/smokePack.ts b/packages/account/scripts/smokePack.ts new file mode 100644 index 00000000000..7cf1790c8ba --- /dev/null +++ b/packages/account/scripts/smokePack.ts @@ -0,0 +1,273 @@ +/** + * Packs @comfyorg/account with `pnpm pack`, installs the tarball into a + * throwaway npm project alongside the declared peers, and imports every + * 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. + */ +import { execFileSync } from 'node:child_process' +import { + existsSync, + mkdirSync, + mkdtempSync, + readdirSync, + readFileSync, + rmSync, + writeFileSync +} from 'node:fs' +import { tmpdir } from 'node:os' +import { join, resolve } from 'node:path' +import { fileURLToPath } from 'node:url' +import { z } from 'zod' + +const zSpecifiers = z.record(z.string(), z.string()) + +const zManifest = z.object({ + name: z.string(), + version: z.string(), + exports: zSpecifiers, + dependencies: zSpecifiers.optional(), + peerDependencies: zSpecifiers.optional() +}) + +const zPackResult = z.object({ + filename: z.string(), + files: z.array(z.object({ path: z.string() })) +}) + +type Manifest = z.infer +type PackResult = z.infer + +const packageDir = fileURLToPath(new URL('..', import.meta.url)) +const workspaceRoot = resolve(packageDir, '..', '..') +const packagesDir = resolve(packageDir, '..') +const keep = process.argv.includes('--keep') + +const WORKSPACE_ONLY_SPECIFIER = /^(catalog|workspace):/ +const NON_PUBLIC_FILE = /(\.test\.ts$|(^|\/)__fixtures__\/)/ + +function run(command: string, args: string[], cwd: string): string { + return execFileSync(command, args, { + cwd, + encoding: 'utf8', + stdio: ['ignore', 'pipe', 'inherit'] + }) +} + +function parseJson(schema: z.ZodType, text: string, origin: string): T { + const result = schema.safeParse(JSON.parse(text)) + return result.success + ? result.data + : fail(`${origin}: ${result.error.message}`) +} + +function readManifest(dir: string): Manifest { + const path = join(dir, 'package.json') + return parseJson(zManifest, readFileSync(path, 'utf8'), path) +} + +function workspacePackageDirs(): Map { + return new Map( + readdirSync(packagesDir) + .map((entry) => join(packagesDir, entry)) + .filter((dir) => existsSync(join(dir, 'package.json'))) + .map((dir) => [readManifest(dir).name, dir]) + ) +} + +function workspaceDependencies( + dir: string, + dirsByName: Map +): Array<[string, string]> { + return Object.entries(readManifest(dir).dependencies ?? {}) + .filter(([, specifier]) => specifier.startsWith('workspace:')) + .map(([name]) => [ + name, + dirsByName.get(name) ?? fail(`workspace dependency ${name} not found`) + ]) +} + +function workspaceDependencyClosure( + dir: string, + dirsByName: Map +): Map { + const closure = new Map() + const queue = workspaceDependencies(dir, dirsByName) + for (const [name, depDir] of queue) { + if (closure.has(name)) continue + closure.set(name, depDir) + queue.push(...workspaceDependencies(depDir, dirsByName)) + } + return closure +} + +function pack(dir: string, destination: string): PackResult { + return parseJson( + zPackResult, + run('pnpm', ['pack', '--json', '--pack-destination', destination], dir), + `pnpm pack --json in ${dir}` + ) +} + +function packedManifest(tarball: string): Manifest { + return parseJson( + zManifest, + run('tar', ['-xzOf', tarball, 'package/package.json'], packageDir), + `package/package.json in ${tarball}` + ) +} + +function log(line: string): void { + process.stdout.write(`${line}\n`) +} + +function fail(message: string): never { + throw new Error(message) +} + +function assertPublishable(source: Manifest, packed: PackResult): void { + const shipped = new Set(packed.files.map((file) => file.path)) + const missingTargets = Object.values(source.exports) + .map((target) => target.replace(/^\.\//, '')) + .filter((target) => !shipped.has(target)) + if (missingTargets.length > 0) { + fail( + `export targets missing from the tarball:\n${missingTargets.join('\n')}` + ) + } + const nonPublic = [...shipped].filter((path) => NON_PUBLIC_FILE.test(path)) + if (nonPublic.length > 0) { + fail(`test-only files in the tarball:\n${nonPublic.join('\n')}`) + } + const manifest = packedManifest(packed.filename) + const unrewritten = Object.entries({ + ...manifest.dependencies, + ...manifest.peerDependencies + }).filter(([, specifier]) => WORKSPACE_ONLY_SPECIFIER.test(specifier)) + if (unrewritten.length > 0) { + fail( + `specifiers only pnpm can rewrite survived packing:\n${unrewritten + .map(([name, specifier]) => `${name}: ${specifier}`) + .join('\n')}` + ) + } + log(`packed ${shipped.size} files, specifiers rewritten`) +} + +const CONSUMER_SOURCE = ` +import { existsSync } from 'node:fs' +import { fileURLToPath } from 'node:url' +import { createLazyIdentity } from '@comfyorg/account/lazyIdentity' +import type { AccountUser } from '@comfyorg/account/session' +import { createSessionClient } from '@comfyorg/account/session' +import { createTestIdentity } from '@comfyorg/account/testing' + +const identity = createTestIdentity({ + onUserChanged: (callback) => { + callback(null) + return () => {} + } +}) +const lazyIdentity = createLazyIdentity(async () => identity) +const memory = new Map() +const client = createSessionClient( + { + exchangeUrl: 'https://example.invalid/api/auth/token', + storage: { + read: () => memory.get('credential') ?? null, + write: (value) => memory.set('credential', value), + clear: () => memory.delete('credential') + } + }, + lazyIdentity +) +const beforeActivation = client.getSnapshot().phase +await lazyIdentity.activate() +const afterActivation = client.getSnapshot().phase +client.dispose() +if (beforeActivation !== 'pending' || afterActivation !== 'signed-out') { + throw new Error( + \`session client phases \${beforeActivation} -> \${afterActivation}\` + ) +} +console.log(\`session client: \${beforeActivation} -> \${afterActivation}\`) + +const { default: manifest } = await import('@comfyorg/account/package.json', { + with: { type: 'json' } +}) +for (const subpath of Object.keys(manifest.exports)) { + const specifier = subpath.replace(/^\\./, '@comfyorg/account') + const target = fileURLToPath(import.meta.resolve(specifier)) + if (!existsSync(target)) throw new Error(\`\${specifier} resolves to a missing file\`) + if (target.endsWith('.vue')) { + console.log(\`\${specifier}: resolved (Vue SFC, needs a bundler to load)\`) + continue + } + if (target.endsWith('.json')) await import(specifier, { with: { type: 'json' } }) + else await import(specifier) + console.log(\`\${specifier}: imported\`) +} +` + +function main(): void { + const source = readManifest(packageDir) + const consumerDir = mkdtempSync(join(tmpdir(), 'comfyorg-account-smoke-')) + const tarballDir = join(consumerDir, 'tarballs') + mkdirSync(tarballDir) + try { + const packed = pack(packageDir, tarballDir) + assertPublishable(source, packed) + + const siblings = workspaceDependencyClosure( + packageDir, + workspacePackageDirs() + ) + const overrides = Object.fromEntries( + [...siblings].map(([name, dir]) => [ + name, + `file:${pack(dir, tarballDir).filename}` + ]) + ) + const peers = packedManifest(packed.filename).peerDependencies ?? {} + writeFileSync( + join(consumerDir, 'package.json'), + JSON.stringify( + { + name: 'comfyorg-account-smoke', + private: true, + type: 'module', + dependencies: { + [source.name]: `file:${packed.filename}`, + ...peers + }, + overrides + }, + null, + 2 + ) + ) + log(`installing into ${consumerDir}`) + run( + 'npm', + ['install', '--no-audit', '--no-fund', '--loglevel=error'], + consumerDir + ) + + writeFileSync(join(consumerDir, 'consumer.ts'), CONSUMER_SOURCE) + const tsx = join(workspaceRoot, 'node_modules', '.bin', 'tsx') + process.stdout.write(run(tsx, ['consumer.ts'], consumerDir)) + log('packed tarball smoke test passed') + } finally { + if (keep) log(`kept ${consumerDir}`) + else rmSync(consumerDir, { recursive: true, force: true }) + } +} + +try { + main() +} catch (error) { + console.error(error instanceof Error ? error.message : error) + process.exitCode = 1 +} diff --git a/packages/account/scripts/tsconfig.json b/packages/account/scripts/tsconfig.json new file mode 100644 index 00000000000..33482f082fb --- /dev/null +++ b/packages/account/scripts/tsconfig.json @@ -0,0 +1,9 @@ +{ + "extends": "../../../tsconfig.json", + "compilerOptions": { + "noEmit": true, + "incremental": false, + "types": ["node"] + }, + "include": ["**/*.ts"] +}