package-invariants.spec.ts 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187
  1. import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
  2. import { tmpdir } from 'node:os'
  3. import { join } from 'node:path'
  4. import { afterEach, describe, expect, it } from 'vitest'
  5. import {
  6. collectPackageInvariantViolations,
  7. } from './package-invariants.ts'
  8. const roots: string[] = []
  9. afterEach(() => {
  10. for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true })
  11. })
  12. function handwrittenInvariant(packageName: string): string {
  13. return `
  14. export const name = 'probe-invariant'
  15. export const inject = ['invariants']
  16. const install = (ctx: { on(name: string, listener: (value: number) => void): void }, fail: (message: string) => never) => {
  17. ctx.on('probe/value', (value) => {
  18. if (value < 0) fail('observed values must be non-negative')
  19. })
  20. }
  21. export const apply = (ctx: { invariants: { register(name: string, install: typeof install): () => void } }) =>
  22. Promise.resolve(ctx.invariants.register(${JSON.stringify(packageName)}, install))
  23. `
  24. }
  25. function fixture(options: {
  26. packageName?: string
  27. source?: string
  28. invariantExport?: boolean
  29. invariantDependency?: boolean
  30. invariantReference?: boolean
  31. buildEntry?: boolean
  32. } = {}): string {
  33. const root = mkdtempSync(join(tmpdir(), 'dsh-package-invariants-'))
  34. roots.push(root)
  35. const dir = join(root, 'packages/core/probe')
  36. mkdirSync(join(dir, 'src'), { recursive: true })
  37. const packageName = options.packageName ?? '@deepseek-ai/dsh-probe'
  38. const manifest = {
  39. name: packageName,
  40. exports: options.invariantExport === false ? {} : {
  41. './invariant': {
  42. types: './lib/types/invariant.d.ts',
  43. default: './lib/invariant.js',
  44. },
  45. },
  46. files: ['lib/index.js', 'lib/invariant.js', 'src'],
  47. peerDependencies: options.invariantDependency === false ? {} : {
  48. '@deepseek-ai/dsh-invariants': '^0.0.1',
  49. },
  50. devDependencies: options.invariantDependency === false ? {} : {
  51. '@deepseek-ai/dsh-invariants': 'workspace:^',
  52. },
  53. }
  54. writeFileSync(join(dir, 'package.json'), `${JSON.stringify(manifest, null, 2)}\n`)
  55. writeFileSync(join(dir, 'tsconfig.json'), `${JSON.stringify({
  56. references: options.invariantReference === false ? [] : [{ path: '../../support/invariants' }],
  57. }, null, 2)}\n`)
  58. writeFileSync(join(dir, 'src/invariant.ts'), options.source ?? handwrittenInvariant(packageName))
  59. writeFileSync(
  60. join(dir, 'tsdown.config.ts'),
  61. options.buildEntry === false ? "export default { entry: ['lib/types/index.js'] }\n" : "export default { entry: ['lib/types/index.js', 'lib/types/invariant.js'] }\n",
  62. )
  63. return root
  64. }
  65. describe('package invariant gate', () => {
  66. it('accepts a hand-owned checking companion with publication metadata', () => {
  67. expect(collectPackageInvariantViolations(fixture())).toEqual([])
  68. })
  69. it('rejects missing publication metadata and build output', () => {
  70. const violations = collectPackageInvariantViolations(fixture({
  71. invariantExport: false,
  72. invariantDependency: false,
  73. invariantReference: false,
  74. buildEntry: false,
  75. }))
  76. expect(violations.map(violation => violation.message)).toEqual(expect.arrayContaining([
  77. expect.stringContaining('exports["./invariant"]'),
  78. expect.stringContaining('peerDependency'),
  79. expect.stringContaining('devDependency'),
  80. expect.stringContaining('TypeScript project references'),
  81. expect.stringContaining('must bundle lib/types/invariant.js'),
  82. ]))
  83. })
  84. it('rejects foreign, duplicate, and unresolved registrations', () => {
  85. const source = `
  86. export const name = 'probe-invariant'
  87. export const inject = ['invariants']
  88. const selected = process.env.PACKAGE_NAME
  89. const install = (_ctx: unknown, fail: (message: string) => never) => { fail('probe') }
  90. export const apply = (ctx: { invariants: { register(name: string, install: typeof install): () => void } }) => {
  91. ctx.invariants.register('@deepseek-ai/dsh-foreign', install)
  92. return ctx.invariants.register(selected!, install)
  93. }
  94. `
  95. const violations = collectPackageInvariantViolations(fixture({ source }))
  96. expect(violations.map(violation => violation.message)).toEqual(expect.arrayContaining([
  97. expect.stringContaining('must resolve to a local string constant'),
  98. expect.stringContaining('must register exactly its own package name'),
  99. ]))
  100. })
  101. it('rejects generated markers and reporter-free executable installers', () => {
  102. const generated = fixture({
  103. source: `/** @generated */\n${handwrittenInvariant('@deepseek-ai/dsh-probe')}`,
  104. })
  105. expect(collectPackageInvariantViolations(generated).map(violation => violation.message))
  106. .toContain('invariant companions must be hand-owned and may not carry @generated markers')
  107. const reporterFree = fixture({
  108. source: `
  109. export const name = 'probe-invariant'
  110. export const inject = ['invariants']
  111. const install = () => { void 0 }
  112. export const apply = (ctx: { invariants: { register(name: string, install: typeof install): () => void } }) =>
  113. Promise.resolve(ctx.invariants.register('@deepseek-ai/dsh-probe', install))
  114. `,
  115. })
  116. expect(collectPackageInvariantViolations(reporterFree).map(violation => violation.message))
  117. .toContain('install function must accept the bound failure reporter as its second parameter')
  118. const unused = fixture({
  119. source: `
  120. export const name = 'probe-invariant'
  121. export const inject = ['invariants']
  122. const install = (_ctx: unknown, _fail: (message: string) => never) => { void 0 }
  123. export const apply = (ctx: { invariants: { register(name: string, install: typeof install): () => void } }) =>
  124. Promise.resolve(ctx.invariants.register('@deepseek-ai/dsh-probe', install))
  125. `,
  126. })
  127. expect(collectPackageInvariantViolations(unused).map(violation => violation.message))
  128. .toContain('install function must use its bound failure reporter')
  129. })
  130. it('rejects registering a different installer than the checked local function', () => {
  131. const decoy = fixture({
  132. source: `
  133. export const name = 'probe-invariant'
  134. export const inject = ['invariants']
  135. const install = (_ctx: unknown, fail: (message: string) => never) => { fail('checked decoy') }
  136. export const apply = (ctx: { invariants: { register(name: string, install: () => void): () => void } }) =>
  137. ctx.invariants.register('@deepseek-ai/dsh-probe', () => {})
  138. `,
  139. })
  140. expect(collectPackageInvariantViolations(decoy).map(violation => violation.message))
  141. .toContain('line 6: ctx.invariants.register must use the checked local install function')
  142. })
  143. it.each([
  144. 'export default { name, inject, apply }',
  145. "export * as default from './probe.ts'",
  146. ])('rejects a default export that would collapse the Loader namespace', (defaultExport) => {
  147. const source = `${handwrittenInvariant('@deepseek-ai/dsh-probe')}\n${defaultExport}\n`
  148. expect(collectPackageInvariantViolations(fixture({ source })).map(violation => violation.message))
  149. .toContain('must not default-export; Loader must retain the companion namespace')
  150. })
  151. it('accepts explained empty installers and rejects unexplained ones', () => {
  152. const explained = `
  153. export const name = 'probe-invariant'
  154. export const inject = ['invariants']
  155. const PACKAGE_NAME = '@deepseek-ai/dsh-probe'
  156. /** No runtime invariant: this pure package owns no events or mutable data. */
  157. const install = () => {}
  158. export const apply = (ctx: { invariants: { register(name: string, install: () => void): () => void } }) =>
  159. ctx.invariants.register(PACKAGE_NAME, install)
  160. `
  161. expect(collectPackageInvariantViolations(fixture({ source: explained }))).toEqual([])
  162. const unexplained = `
  163. export const name = 'probe-invariant'
  164. export const inject = ['invariants']
  165. const PACKAGE_NAME = '@deepseek-ai/dsh-probe'
  166. const install = () => {}
  167. export const apply = (ctx: { invariants: { register(name: string, install: () => void): () => void } }) =>
  168. ctx.invariants.register(PACKAGE_NAME, install)
  169. `
  170. expect(collectPackageInvariantViolations(fixture({ source: unexplained })).map(violation => violation.message))
  171. .toContain('empty install function must explain why with a "No runtime invariant:" comment')
  172. })
  173. })