verify-client-packages.ts 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711
  1. /**
  2. * Verify client package modes and the synchronous browser module-request graph.
  3. */
  4. import { globSync, readFileSync, writeFileSync } from 'node:fs'
  5. import { dirname, resolve, sep } from 'node:path'
  6. import { pathToFileURL } from 'node:url'
  7. import ts from 'typescript'
  8. import { TypeScriptProject } from './ts-project.ts'
  9. const GATE = 'verify-client-packages'
  10. const CLIENT_MANIFEST_GLOB = 'packages/client/*/package.json'
  11. const MANIFEST_GLOBS = ['packages/*/*/package.json', 'apps/*/package.json', 'vendor/*/package.json']
  12. const CONFIG_GLOB = 'packages/*/*/tsdown.config.ts'
  13. const PLATFORM_SOURCE = 'packages/client/web/src/platform.ts'
  14. const PARSER_PRELOAD_SOURCE = 'packages/client/modules/src/index.ts'
  15. const STATIC_PRESET_SOURCE = 'packages/client/tsdown.client.ts'
  16. const CORDIS = '@deepseek-ai/cordis'
  17. /** One workspace package's browser-module declaration. */
  18. export interface ClientDeclaration {
  19. readonly name: string
  20. readonly manifest: string
  21. readonly dynamic: boolean
  22. readonly external: readonly string[]
  23. readonly runtimeSourceUses: Readonly<Record<string, readonly string[]>>
  24. /** Exact runtime specifiers used to validate `dsh.client.external` declarations. */
  25. readonly runtimeSourceSpecifiers: Readonly<Record<string, readonly string[]>>
  26. /** Informational package dependencies declared by the row. */
  27. readonly inject: readonly string[]
  28. }
  29. /** One package directly under packages/client. */
  30. export interface ClientPackage extends ClientDeclaration {
  31. readonly staticLinked: boolean
  32. readonly sourceUses: Readonly<Record<string, readonly string[]>>
  33. readonly dependencies: Readonly<Record<string, string>>
  34. readonly peerDependencies: Readonly<Record<string, string>>
  35. readonly devDependencies: Readonly<Record<string, string>>
  36. }
  37. /** Complete source-plane input to the client package verifier. */
  38. export interface ClientPackageFacts {
  39. readonly packages: readonly ClientPackage[]
  40. readonly declarations: readonly ClientDeclaration[]
  41. readonly staticLinkedPackages: ReadonlySet<string>
  42. readonly platformModules: readonly string[]
  43. readonly preloadedExternals: readonly string[]
  44. readonly parserPreloadIds: readonly string[]
  45. readonly malformed: readonly string[]
  46. }
  47. /** Result of reading every workspace browser-module declaration. */
  48. export interface ClientDeclarations {
  49. readonly declarations: ClientDeclaration[]
  50. readonly malformed: string[]
  51. }
  52. /**
  53. * Collect bare packages referenced by one production source file.
  54. * @param path - File path used to select TypeScript's parser mode.
  55. * @param source - Source text to inspect.
  56. * @returns Bare package names referenced by imports, declarations, or JSX.
  57. */
  58. export function collectSourcePackageUses(path: string, source: string): Set<string> {
  59. const sourceFile = ts.createSourceFile(path, source, ts.ScriptTarget.Latest, true)
  60. return collectSourceFileUses(sourceFile, false, 'package')
  61. }
  62. /**
  63. * Collect bare packages whose values one production source file reaches at runtime.
  64. * @param path - File path used to select TypeScript's parser mode.
  65. * @param source - Source text to inspect.
  66. * @returns Bare package names retained by runtime imports, exports, requires, or JSX.
  67. */
  68. export function collectRuntimeSourcePackageUses(path: string, source: string): Set<string> {
  69. const sourceFile = ts.createSourceFile(path, source, ts.ScriptTarget.Latest, true)
  70. return collectSourceFileUses(sourceFile, true, 'package')
  71. }
  72. /**
  73. * Collect exact bare specifiers retained by one production source file.
  74. * @param path - File path used to select TypeScript's parser mode.
  75. * @param source - Source text to inspect.
  76. * @returns Exact specifiers retained by runtime imports, exports, requires, or JSX.
  77. */
  78. export function collectRuntimeSourceSpecifiers(path: string, source: string): Set<string> {
  79. const sourceFile = ts.createSourceFile(path, source, ts.ScriptTarget.Latest, true)
  80. return collectSourceFileUses(sourceFile, true, 'specifier')
  81. }
  82. /**
  83. * Collect relative module specifiers used to follow one source entry's local closure.
  84. * @param path - File path used to select TypeScript's parser mode.
  85. * @param source - Source text to inspect.
  86. * @returns Relative imports, exports, requires, and import types.
  87. */
  88. export function collectLocalSourceSpecifiers(path: string, source: string): Set<string> {
  89. const sourceFile = ts.createSourceFile(path, source, ts.ScriptTarget.Latest, true)
  90. return collectSourceFileUses(sourceFile, false, 'local')
  91. }
  92. /**
  93. * Collect relative module specifiers retained by one production source file.
  94. * @param path - File path used to select TypeScript's parser mode.
  95. * @param source - Source text to inspect.
  96. * @returns Relative imports, exports, and requires that survive compilation.
  97. */
  98. export function collectRuntimeLocalSourceSpecifiers(path: string, source: string): Set<string> {
  99. const sourceFile = ts.createSourceFile(path, source, ts.ScriptTarget.Latest, true)
  100. return collectSourceFileUses(sourceFile, true, 'local')
  101. }
  102. function importCarriesRuntimeValue(node: ts.ImportDeclaration): boolean {
  103. const clause = node.importClause
  104. if (clause === undefined) return true
  105. if (clause.phaseModifier === ts.SyntaxKind.TypeKeyword) return false
  106. const bindings = clause.namedBindings
  107. return clause.name !== undefined
  108. || bindings === undefined
  109. || ts.isNamespaceImport(bindings)
  110. || bindings.elements.length === 0
  111. || bindings.elements.some(element => !element.isTypeOnly)
  112. }
  113. function exportCarriesRuntimeValue(node: ts.ExportDeclaration): boolean {
  114. if (node.isTypeOnly) return false
  115. const clause = node.exportClause
  116. if (clause === undefined || ts.isNamespaceExport(clause)) return true
  117. return clause.elements.length === 0 || clause.elements.some(element => !element.isTypeOnly)
  118. }
  119. function collectSourceFileUses(
  120. sourceFile: ts.SourceFile,
  121. runtimeOnly: boolean,
  122. key: 'local' | 'package' | 'specifier',
  123. ): Set<string> {
  124. const uses = new Set<string>()
  125. const add = (specifier: ts.Expression | undefined): void => {
  126. if (specifier === undefined || !ts.isStringLiteralLike(specifier)) return
  127. if (key === 'local') {
  128. if (specifier.text.startsWith('.')) uses.add(specifier.text)
  129. return
  130. }
  131. if (!isBareSpecifier(specifier.text)) return
  132. uses.add(key === 'package' ? packageNameOf(specifier.text) : specifier.text)
  133. }
  134. const visit = (node: ts.Node): void => {
  135. if (ts.isImportDeclaration(node)) {
  136. if (!runtimeOnly || importCarriesRuntimeValue(node)) add(node.moduleSpecifier)
  137. } else if (ts.isExportDeclaration(node)) {
  138. if (!runtimeOnly || exportCarriesRuntimeValue(node)) add(node.moduleSpecifier)
  139. } else if (ts.isImportEqualsDeclaration(node) && ts.isExternalModuleReference(node.moduleReference)) {
  140. if (!runtimeOnly || !node.isTypeOnly) add(node.moduleReference.expression)
  141. } else if (!runtimeOnly && ts.isImportTypeNode(node) && ts.isLiteralTypeNode(node.argument)) {
  142. add(node.argument.literal)
  143. } else if (ts.isCallExpression(node)
  144. && (node.expression.kind === ts.SyntaxKind.ImportKeyword
  145. || ts.isIdentifier(node.expression) && node.expression.text === 'require')) {
  146. add(node.arguments[0])
  147. } else if (!runtimeOnly && key !== 'local' && ts.isModuleDeclaration(node) && ts.isStringLiteral(node.name)) {
  148. add(node.name)
  149. } else if (key !== 'local'
  150. && (ts.isJsxElement(node) || ts.isJsxSelfClosingElement(node) || ts.isJsxFragment(node))) {
  151. uses.add('react')
  152. }
  153. ts.forEachChild(node, visit)
  154. }
  155. visit(sourceFile)
  156. return uses
  157. }
  158. /**
  159. * Read browser-module declarations from workspace manifests.
  160. * @param root - Absolute repository root.
  161. * @returns Declarations and malformed dsh.client fields.
  162. */
  163. export function readClientDeclarations(root: string): ClientDeclarations {
  164. const malformed: string[] = []
  165. const declarations = globSync(MANIFEST_GLOBS, { cwd: root })
  166. .map(normalizePath)
  167. .sort()
  168. .flatMap(path => readDeclaration(root, path, malformed) ?? [])
  169. return { declarations, malformed }
  170. }
  171. /**
  172. * Return every client package policy violation.
  173. * @param facts - Package modes, manifests, source uses, and platform module lists.
  174. * @returns Stable self-contained diagnostics.
  175. */
  176. export function collectClientPackageViolations(facts: ClientPackageFacts): string[] {
  177. return [
  178. ...facts.malformed,
  179. ...collectModeViolations(facts),
  180. ...collectModuleViolations(facts),
  181. ].sort((left, right) => left.localeCompare(right))
  182. }
  183. interface ManifestDocument {
  184. readonly path: string
  185. readonly manifest: Manifest
  186. changed: boolean
  187. }
  188. /**
  189. * Repair malformed or redundant `dsh.client` declaration entries.
  190. * @param root - Absolute repository root.
  191. * @param facts - Facts used by the verification pass.
  192. * @returns Repository-relative manifests written by the fixer.
  193. */
  194. export function fixClientPackageManifests(root: string, facts: ClientPackageFacts): string[] {
  195. const documents = new Map<string, ManifestDocument>()
  196. const document = (path: string): ManifestDocument => {
  197. const cached = documents.get(path)
  198. if (cached !== undefined) return cached
  199. const loaded: ManifestDocument = {
  200. path,
  201. manifest: JSON.parse(readFileSync(resolve(root, path), 'utf8')) as Manifest,
  202. changed: false,
  203. }
  204. documents.set(path, loaded)
  205. return loaded
  206. }
  207. const baseline = new Set([...facts.platformModules, ...facts.preloadedExternals])
  208. for (const declaration of facts.declarations.filter(entry => entry.dynamic)) {
  209. const target = document(declaration.manifest)
  210. const dsh = isRecord(target.manifest.dsh) ? target.manifest.dsh : undefined
  211. const client = isRecord(dsh?.client) ? dsh.client : undefined
  212. if (client === undefined) continue
  213. target.changed = normalizeClientArray(client, 'inject', () => false) || target.changed
  214. target.changed = normalizeClientArray(
  215. client,
  216. 'external',
  217. value => baseline.has(value) || rowPackageOf(value, new Set([declaration.name])) === declaration.name,
  218. ) || target.changed
  219. }
  220. const changed = [...documents.values()].filter(target => target.changed).sort((left, right) =>
  221. left.path.localeCompare(right.path))
  222. for (const target of changed) {
  223. writeFileSync(resolve(root, target.path), JSON.stringify(target.manifest, null, 2) + '\n')
  224. }
  225. return changed.map(target => target.path)
  226. }
  227. function normalizeClientArray(
  228. client: Record<string, unknown>,
  229. field: 'external' | 'inject',
  230. remove: (value: string) => boolean,
  231. ): boolean {
  232. const value = client[field]
  233. if (!Array.isArray(value) || value.some(entry => typeof entry !== 'string')) return false
  234. const seen = new Set<string>()
  235. const normalized = value.filter((entry: string) => {
  236. if (entry === '' || seen.has(entry) || remove(entry)) return false
  237. seen.add(entry)
  238. return true
  239. })
  240. if (normalized.length === value.length && normalized.every((entry, index) => entry === value[index])) return false
  241. if (normalized.length === 0) {
  242. if (field === 'external') delete client.external
  243. else delete client.inject
  244. } else {
  245. client[field] = normalized
  246. }
  247. return true
  248. }
  249. function collectModeViolations(facts: ClientPackageFacts): string[] {
  250. const violations: string[] = []
  251. for (const pkg of facts.packages) {
  252. if (pkg.dynamic && pkg.staticLinked) {
  253. violations.push(
  254. pkg.manifest + ': ' + pkg.name + ' declares dsh.client and uses the staticLinked preset;'
  255. + ' a client package must be dynamic or statically linked, not both',
  256. )
  257. } else if (!pkg.dynamic && !pkg.staticLinked) {
  258. violations.push(
  259. pkg.manifest + ': ' + pkg.name + ' has no supported client package mode;'
  260. + ' declare dsh.client or use the staticLinked preset',
  261. )
  262. }
  263. }
  264. const workspaceNames = new Set(facts.declarations.map(entry => entry.name))
  265. for (const specifier of facts.platformModules) {
  266. const owner = packageNameOf(specifier)
  267. if (!workspaceNames.has(owner) || owner === CORDIS || facts.staticLinkedPackages.has(owner)) continue
  268. violations.push(
  269. PLATFORM_SOURCE + ': seeded workspace module ' + JSON.stringify(specifier)
  270. + ' belongs to ' + owner + ', whose build does not use the staticLinked preset',
  271. )
  272. }
  273. const rows = rowNames(facts.declarations)
  274. for (const specifier of facts.preloadedExternals) {
  275. if (rowPackageOf(specifier, rows) === undefined) {
  276. violations.push(
  277. PLATFORM_SOURCE + ': parser-preloaded external ' + JSON.stringify(specifier)
  278. + ' has no dynamic dsh.client row',
  279. )
  280. }
  281. if (!facts.parserPreloadIds.includes(stripClientSuffix(specifier))) {
  282. violations.push(
  283. PLATFORM_SOURCE + ': parser-preloaded external ' + JSON.stringify(specifier)
  284. + ' has no matching PARSER_PRELOAD_IDS row in ' + PARSER_PRELOAD_SOURCE,
  285. )
  286. }
  287. }
  288. return violations
  289. }
  290. interface ModuleEdge {
  291. readonly from: string
  292. readonly to: string
  293. readonly specifier: string
  294. }
  295. function collectModuleViolations(facts: ClientPackageFacts): string[] {
  296. const violations: string[] = []
  297. const baseline = new Set([...facts.platformModules, ...facts.preloadedExternals])
  298. const rows = rowNames(facts.declarations)
  299. const byName = new Map(facts.declarations.map(entry => [entry.name, entry]))
  300. const edges: ModuleEdge[] = []
  301. for (const pkg of facts.declarations.filter(entry => entry.dynamic)) {
  302. for (const field of ['external', 'inject'] as const) {
  303. const seen = new Set<string>()
  304. for (const value of pkg[field]) {
  305. if (value === '') violations.push(pkg.manifest + ': dsh.client.' + field + ' contains an empty value')
  306. else if (seen.has(value)) {
  307. violations.push(pkg.manifest + ': dsh.client.' + field + ' lists ' + JSON.stringify(value) + ' twice')
  308. }
  309. seen.add(value)
  310. }
  311. }
  312. for (const specifier of new Set(pkg.external)) {
  313. if (specifier === '') continue
  314. if (baseline.has(specifier)) {
  315. violations.push(
  316. pkg.manifest + ': dsh.client.external repeats baseline module ' + JSON.stringify(specifier)
  317. + '; remove the explicit declaration',
  318. )
  319. continue
  320. }
  321. const supplier = rowPackageOf(specifier, rows)
  322. if (supplier === pkg.name) {
  323. violations.push(pkg.manifest + ': dsh.client.external names its own row ' + JSON.stringify(specifier))
  324. } else if (supplier !== undefined) {
  325. if (pkg.manifest.startsWith('packages/client/')) {
  326. violations.push(
  327. pkg.manifest + ': client feature package requests runtime external ' + JSON.stringify(specifier)
  328. + '; import shared types only or call an injected Cordis service',
  329. )
  330. continue
  331. }
  332. if (pkg.runtimeSourceSpecifiers[specifier] === undefined) {
  333. violations.push(
  334. pkg.manifest + ': dsh.client.external ' + JSON.stringify(specifier)
  335. + ' has no runtime import or re-export in production source; remove the stale declaration',
  336. )
  337. continue
  338. }
  339. edges.push({ from: pkg.name, to: supplier, specifier })
  340. } else {
  341. const owner = stripClientSuffix(specifier)
  342. violations.push(
  343. pkg.manifest + ': dsh.client.external ' + JSON.stringify(specifier) + ' has no supplier;'
  344. + (byName.has(owner)
  345. ? ' workspace package ' + owner
  346. + ' declares no dynamic dsh.client row and the shell does not seed this specifier'
  347. : ' no dynamic row or PLATFORM_MODULES entry answers it'),
  348. )
  349. }
  350. }
  351. }
  352. violations.push(...collectModuleCycles(edges, byName))
  353. return violations
  354. }
  355. function collectModuleCycles(
  356. edges: readonly ModuleEdge[],
  357. byName: ReadonlyMap<string, ClientDeclaration>,
  358. ): string[] {
  359. const outgoing = new Map<string, ModuleEdge[]>()
  360. for (const edge of [...edges].sort((left, right) => left.specifier.localeCompare(right.specifier))) {
  361. outgoing.set(edge.from, [...outgoing.get(edge.from) ?? [], edge])
  362. }
  363. const finished = new Set<string>()
  364. const onPath = new Set<string>()
  365. const path: ModuleEdge[] = []
  366. const reported = new Map<string, string>()
  367. const walk = (name: string): void => {
  368. onPath.add(name)
  369. for (const edge of outgoing.get(name) ?? []) {
  370. if (onPath.has(edge.to)) {
  371. const start = path.findIndex(entry => entry.from === edge.to)
  372. const cycle = start === -1 ? [edge] : [...path.slice(start), edge]
  373. const key = cycleKey(cycle)
  374. if (!reported.has(key)) reported.set(key, formatCycle(cycle, byName))
  375. } else if (!finished.has(edge.to)) {
  376. path.push(edge)
  377. walk(edge.to)
  378. path.pop()
  379. }
  380. }
  381. onPath.delete(name)
  382. finished.add(name)
  383. }
  384. for (const name of [...outgoing.keys()].sort()) {
  385. if (!finished.has(name)) walk(name)
  386. }
  387. return [...reported.values()]
  388. }
  389. function cycleKey(cycle: readonly ModuleEdge[]): string {
  390. const labels = cycle.map(edge => edge.from + ' ' + edge.specifier)
  391. const first = [...labels].sort()[0]
  392. const offset = first === undefined ? 0 : labels.indexOf(first)
  393. return [...labels.slice(offset), ...labels.slice(0, offset)].join(' -> ')
  394. }
  395. function formatCycle(
  396. cycle: readonly ModuleEdge[],
  397. byName: ReadonlyMap<string, ClientDeclaration>,
  398. ): string {
  399. const entry = cycle[0]
  400. const chain = cycle.map(edge => edge.from + ' --(' + edge.specifier + ')-->').join(' ')
  401. const manifest = entry === undefined ? 'packages/client' : byName.get(entry.from)?.manifest ?? entry.from
  402. return manifest + ': synchronous dsh.client.external cycle: ' + chain + ' ' + (entry?.from ?? '')
  403. }
  404. interface Manifest {
  405. name?: unknown
  406. dsh?: unknown
  407. dependencies?: Record<string, string>
  408. peerDependencies?: Record<string, string>
  409. devDependencies?: Record<string, string>
  410. }
  411. function readDeclaration(
  412. root: string,
  413. manifestPath: string,
  414. malformed: string[],
  415. ): ClientDeclaration | undefined {
  416. const manifest = JSON.parse(readFileSync(resolve(root, manifestPath), 'utf8')) as Manifest
  417. if (typeof manifest.name !== 'string') return undefined
  418. const dsh = isRecord(manifest.dsh) ? manifest.dsh : undefined
  419. const rawClient = dsh?.client
  420. if (rawClient === undefined) {
  421. return {
  422. name: manifest.name, manifest: manifestPath, dynamic: false, external: [], inject: [],
  423. runtimeSourceUses: {}, runtimeSourceSpecifiers: {},
  424. }
  425. }
  426. if (!isRecord(rawClient)) {
  427. malformed.push(manifestPath + ': ' + manifest.name + ' dsh.client must be an object')
  428. return {
  429. name: manifest.name, manifest: manifestPath, dynamic: false, external: [], inject: [],
  430. runtimeSourceUses: {}, runtimeSourceSpecifiers: {},
  431. }
  432. }
  433. return {
  434. name: manifest.name,
  435. manifest: manifestPath,
  436. dynamic: true,
  437. external: stringArray(rawClient.external, manifest.name, manifestPath, 'external', malformed),
  438. inject: stringArray(rawClient.inject, manifest.name, manifestPath, 'inject', malformed),
  439. runtimeSourceUses: {},
  440. runtimeSourceSpecifiers: {},
  441. }
  442. }
  443. function stringArray(
  444. value: unknown,
  445. packageName: string,
  446. manifestPath: string,
  447. field: string,
  448. malformed: string[],
  449. ): readonly string[] {
  450. if (value === undefined) return []
  451. if (!Array.isArray(value) || value.some(entry => typeof entry !== 'string')) {
  452. malformed.push(manifestPath + ': ' + packageName + ' dsh.client.' + field + ' must be a string array')
  453. return []
  454. }
  455. return value as string[]
  456. }
  457. async function readStaticLinkedRoster(root: string): Promise<Set<string>> {
  458. const presetUrl = pathToFileURL(resolve(import.meta.dirname, '..', STATIC_PRESET_SOURCE)).href
  459. const preset = await import(presetUrl) as { isStaticLinkedConfig?: unknown }
  460. if (typeof preset.isStaticLinkedConfig !== 'function') {
  461. throw new Error(GATE + ': ' + STATIC_PRESET_SOURCE + ' exports no isStaticLinkedConfig')
  462. }
  463. const predicate = preset.isStaticLinkedConfig as (configs: readonly unknown[]) => boolean
  464. const roster = new Set<string>()
  465. for (const configPath of globSync(CONFIG_GLOB, { cwd: root }).map(normalizePath).sort()) {
  466. const loaded = await import(pathToFileURL(resolve(root, configPath)).href) as { default?: unknown }
  467. if (typeof loaded.default !== 'function') continue
  468. const configs = (loaded.default as (input: { env: Record<string, string> }) => unknown)({
  469. env: { DSH_BUILD_FACE: 'client' },
  470. })
  471. if (!Array.isArray(configs) || !predicate(configs)) continue
  472. const manifest = JSON.parse(
  473. readFileSync(resolve(root, configPath.replace(/tsdown\.config\.ts$/, 'package.json')), 'utf8'),
  474. ) as Manifest
  475. if (typeof manifest.name === 'string') roster.add(manifest.name)
  476. }
  477. return roster
  478. }
  479. function unwrapExpression(expression: ts.Expression): ts.Expression {
  480. let current = expression
  481. while (ts.isAsExpression(current) || ts.isSatisfiesExpression(current) || ts.isParenthesizedExpression(current)) {
  482. current = current.expression
  483. }
  484. return current
  485. }
  486. function readStringLiteralArray(root: string, sourcePath: string, name: string): string[] {
  487. const path = resolve(root, sourcePath)
  488. const source = ts.createSourceFile(path, readFileSync(path, 'utf8'), ts.ScriptTarget.Latest, false, ts.ScriptKind.TS)
  489. const constants = new Map<string, string>()
  490. for (const statement of source.statements) {
  491. if (!ts.isVariableStatement(statement)) continue
  492. for (const declaration of statement.declarationList.declarations) {
  493. if (!ts.isIdentifier(declaration.name) || declaration.initializer === undefined) continue
  494. const initializer = unwrapExpression(declaration.initializer)
  495. if (ts.isStringLiteral(initializer)) constants.set(declaration.name.text, initializer.text)
  496. }
  497. }
  498. for (const statement of source.statements) {
  499. if (!ts.isVariableStatement(statement)) continue
  500. for (const declaration of statement.declarationList.declarations) {
  501. if (!ts.isIdentifier(declaration.name) || declaration.name.text !== name) continue
  502. const expression = declaration.initializer === undefined ? undefined : unwrapExpression(declaration.initializer)
  503. if (expression === undefined || !ts.isArrayLiteralExpression(expression)) {
  504. throw new Error(GATE + ': ' + name + ' in ' + sourcePath + ' must be an array literal')
  505. }
  506. return expression.elements.map((element) => {
  507. const value = unwrapExpression(element)
  508. if (ts.isStringLiteral(value)) return value.text
  509. if (ts.isIdentifier(value) && constants.has(value.text)) return constants.get(value.text) as string
  510. throw new Error(GATE + ': ' + name + ' in ' + sourcePath + ' must contain only string constants')
  511. })
  512. }
  513. }
  514. throw new Error(GATE + ': ' + sourcePath + ' declares no ' + name)
  515. }
  516. async function readFacts(root: string): Promise<ClientPackageFacts> {
  517. const { declarations: bareDeclarations, malformed } = readClientDeclarations(root)
  518. const staticLinkedPackages = await readStaticLinkedRoster(root)
  519. const project = new TypeScriptProject(root, 'client')
  520. const sourceFiles = project.sourceFiles()
  521. const declarations = bareDeclarations.map((declaration): ClientDeclaration => {
  522. const runtimeSourceUses = new Map<string, Set<string>>()
  523. const runtimeSourceSpecifiers = new Map<string, Set<string>>()
  524. const sourcePrefix = dirname(declaration.manifest) + '/src/'
  525. for (const sourceFile of sourceFiles) {
  526. if (sourceFile.isDeclarationFile) continue
  527. const file = project.relativePath(sourceFile)
  528. if (!file.startsWith(sourcePrefix)) continue
  529. for (const name of collectSourceFileUses(sourceFile, true, 'package')) {
  530. const locations = runtimeSourceUses.get(name) ?? new Set<string>()
  531. locations.add(file)
  532. runtimeSourceUses.set(name, locations)
  533. }
  534. for (const specifier of collectSourceFileUses(sourceFile, true, 'specifier')) {
  535. const locations = runtimeSourceSpecifiers.get(specifier) ?? new Set<string>()
  536. locations.add(file)
  537. runtimeSourceSpecifiers.set(specifier, locations)
  538. }
  539. }
  540. return {
  541. ...declaration,
  542. runtimeSourceUses: Object.fromEntries(
  543. [...runtimeSourceUses].sort(([left], [right]) => left.localeCompare(right))
  544. .map(([name, locations]) => [name, [...locations].sort()]),
  545. ),
  546. runtimeSourceSpecifiers: Object.fromEntries(
  547. [...runtimeSourceSpecifiers].sort(([left], [right]) => left.localeCompare(right))
  548. .map(([specifier, locations]) => [specifier, [...locations].sort()]),
  549. ),
  550. }
  551. })
  552. const byManifest = new Map(declarations.map(entry => [entry.manifest, entry]))
  553. const packages: ClientPackage[] = []
  554. for (const manifestPath of globSync(CLIENT_MANIFEST_GLOB, { cwd: root }).map(normalizePath).sort()) {
  555. const declaration = byManifest.get(manifestPath)
  556. if (declaration === undefined) throw new Error(GATE + ': no declaration facts for ' + manifestPath)
  557. const manifest = JSON.parse(readFileSync(resolve(root, manifestPath), 'utf8')) as Manifest
  558. if (typeof manifest.name !== 'string') throw new Error(GATE + ': ' + manifestPath + ' has no package name')
  559. const sourceUses = new Map<string, Set<string>>()
  560. const runtimeSourceUses = new Map<string, Set<string>>()
  561. const packageDirectory = dirname(manifestPath)
  562. const sourcePrefix = packageDirectory + '/src/'
  563. for (const sourceFile of sourceFiles) {
  564. if (sourceFile.isDeclarationFile) continue
  565. const file = project.relativePath(sourceFile)
  566. if (!file.startsWith(sourcePrefix)) continue
  567. for (const name of collectSourceFileUses(sourceFile, false, 'package')) {
  568. const locations = sourceUses.get(name) ?? new Set<string>()
  569. locations.add(file)
  570. sourceUses.set(name, locations)
  571. }
  572. for (const name of collectSourceFileUses(sourceFile, true, 'package')) {
  573. const locations = runtimeSourceUses.get(name) ?? new Set<string>()
  574. locations.add(file)
  575. runtimeSourceUses.set(name, locations)
  576. }
  577. }
  578. packages.push({
  579. ...declaration,
  580. staticLinked: staticLinkedPackages.has(declaration.name),
  581. sourceUses: Object.fromEntries(
  582. [...sourceUses].sort(([left], [right]) => left.localeCompare(right))
  583. .map(([name, locations]) => [name, [...locations].sort()]),
  584. ),
  585. runtimeSourceUses: Object.fromEntries(
  586. [...runtimeSourceUses].sort(([left], [right]) => left.localeCompare(right))
  587. .map(([name, locations]) => [name, [...locations].sort()]),
  588. ),
  589. dependencies: manifest.dependencies ?? {},
  590. peerDependencies: manifest.peerDependencies ?? {},
  591. devDependencies: manifest.devDependencies ?? {},
  592. })
  593. }
  594. return {
  595. packages,
  596. declarations,
  597. staticLinkedPackages,
  598. platformModules: readStringLiteralArray(root, PLATFORM_SOURCE, 'PLATFORM_MODULES'),
  599. preloadedExternals: readStringLiteralArray(root, PLATFORM_SOURCE, 'PRELOADED_CLIENT_EXTERNALS'),
  600. parserPreloadIds: readStringLiteralArray(root, PARSER_PRELOAD_SOURCE, 'PARSER_PRELOAD_IDS'),
  601. malformed,
  602. }
  603. }
  604. function packageNameOf(specifier: string): string {
  605. const segments = specifier.split('/')
  606. return segments.slice(0, specifier.startsWith('@') ? 2 : 1).join('/')
  607. }
  608. function stripClientSuffix(specifier: string): string {
  609. return specifier.endsWith('/client') ? specifier.slice(0, -'/client'.length) : specifier
  610. }
  611. function rowNames(declarations: readonly ClientDeclaration[]): Set<string> {
  612. return new Set(declarations.filter(entry => entry.dynamic).map(entry => entry.name))
  613. }
  614. function rowPackageOf(specifier: string, rows: ReadonlySet<string>): string | undefined {
  615. if (rows.has(specifier)) return specifier
  616. const stripped = stripClientSuffix(specifier)
  617. return rows.has(stripped) ? stripped : undefined
  618. }
  619. function isBareSpecifier(specifier: string): boolean {
  620. return !specifier.startsWith('.') && !specifier.startsWith('/') && !specifier.startsWith('#')
  621. }
  622. function isRecord(value: unknown): value is Record<string, unknown> {
  623. return typeof value === 'object' && value !== null && !Array.isArray(value)
  624. }
  625. function normalizePath(path: string): string {
  626. return path.split(sep).join('/')
  627. }
  628. async function main(): Promise<void> {
  629. const root = resolve(import.meta.dirname, '..')
  630. let facts = await readFacts(root)
  631. if (process.argv.includes('--fix')) {
  632. const changed = fixClientPackageManifests(root, facts)
  633. console.log(
  634. changed.length === 0
  635. ? GATE + ': no mechanically fixable manifest changes.'
  636. : GATE + ': fixed ' + String(changed.length) + ' manifest(s): ' + changed.join(', '),
  637. )
  638. facts = await readFacts(root)
  639. }
  640. const violations = collectClientPackageViolations(facts)
  641. if (violations.length > 0) {
  642. console.error(GATE + ': ' + String(violations.length) + ' violation(s):')
  643. for (const violation of violations) console.error(' ' + violation)
  644. process.exit(1)
  645. }
  646. const dynamic = facts.packages.filter(pkg => pkg.dynamic).length
  647. const requests = facts.declarations.reduce((total, pkg) => total + pkg.external.length, 0)
  648. console.log(
  649. GATE + ': ' + String(facts.packages.length) + ' client packages (' + String(dynamic) + ' dynamic, '
  650. + String(facts.packages.length - dynamic) + ' statically linked) satisfy package-mode and module-request rules; '
  651. + String(requests) + ' explicit external request(s).',
  652. )
  653. }
  654. if (process.argv[1] !== undefined && import.meta.filename === resolve(process.argv[1])) {
  655. await main()
  656. }