Skip to content
Source
Sign inSign up
TanStack/schemas
Open History to see the last commit

npm-pack.test.ts

302 lines9.8 KB

1import { existsSync, mkdtempSync, readFileSync, rmSync } from 'node:fs'
2import { tmpdir } from 'node:os'
3import { join, resolve, sep } from 'node:path'
4import { pathToFileURL } from 'node:url'
5​
6import { afterAll, beforeAll, describe, expect, it } from 'vitest'
7​
8import type { CardEvaluation } from '../packages/rate-card/src/evaluator.ts'
9import type { RateCard } from '../packages/rate-card/src/card.ts'
10import {
11 ESTIMATE_CASES,
12 packageExpected,
13 settle,
14} from '../packages/rate-card/src/fixtures/estimate-cases.ts'
15import {
16 assertPublishableManifest,
17 assertShipsEntryPoints,
18 assertVersionsMatchTag,
19 listPublicPackages,
20 main,
21 manifestEntryPoints,
22 packAll,
23 packedEntryNames,
24 publishManifest,
25 publishOrder,
26 readPackedManifest,
27 run,
28 tarballFileName,
29 versionFromTag,
30} from './npm-pack.ts'
31import type { PublicPackage } from './npm-pack.ts'
32​
33const EXPECTED_NAMES = [
34 '@modelschemas/client',
35 '@modelschemas/codegen',
36 '@modelschemas/rate-card',
37 '@modelschemas/vite',
38 'modelschemas',
39] as const
40​
41function sharedVersion(): string {
42 const pkgs = listPublicPackages()
43 const versions = new Set(pkgs.map((pkg) => pkg.version))
44 expect(versions.size).toBe(1)
45 const version = pkgs[0]?.version
46 if (version === undefined) throw new Error('no public packages')
47 return version
49​
50describe('listPublicPackages', () => {
51 it('returns the five public workspace packages at one shared version', () => {
52 const pkgs = listPublicPackages()
53 expect(pkgs.map((pkg) => pkg.name).sort()).toEqual([...EXPECTED_NAMES])
54 expect(new Set(pkgs.map((pkg) => pkg.version)).size).toBe(1)
55 })
56})
57​
58describe('publishOrder', () => {
59 it('puts packages with no workspace deps before their dependents', () => {
60 const ordered = publishOrder(listPublicPackages()).map((pkg) => pkg.name)
61 expect(ordered.indexOf('@modelschemas/client')).toBeLessThan(
62 ordered.indexOf('modelschemas'),
63 )
64 expect(ordered.indexOf('@modelschemas/codegen')).toBeLessThan(
65 ordered.indexOf('modelschemas'),
66 )
67 expect(ordered.indexOf('@modelschemas/codegen')).toBeLessThan(
68 ordered.indexOf('@modelschemas/vite'),
69 )
70 })
71​
72 it('throws on a workspace dependency cycle', () => {
73 expect(() =>
74 publishOrder([
75 {
76 name: 'a',
77 version: '1.0.0',
78 dir: '/tmp/a',
79 dependencies: { b: 'workspace:*' },
80 },
81 {
82 name: 'b',
83 version: '1.0.0',
84 dir: '/tmp/b',
85 dependencies: { a: 'workspace:*' },
86 },
87 ]),
88 ).toThrow(/workspace dependency cycle/)
89 })
90})
91​
92describe('tarballFileName / versionFromTag', () => {
93 it('turns scoped names into slash-free tarball filenames', () => {
94 expect(tarballFileName('@modelschemas/client', '0.1.0')).toBe(
95 'modelschemas-client-0.1.0.tgz',
96 )
97 expect(tarballFileName('modelschemas', '0.1.0')).toBe(
98 'modelschemas-0.1.0.tgz',
99 )
100 })
101​
102 it('parses v-prefixed semver tags only', () => {
103 expect(versionFromTag('v0.1.0')).toBe('0.1.0')
104 expect(versionFromTag('refs/tags/v1.2.3-rc.1')).toBe('1.2.3-rc.1')
105 expect(versionFromTag('0.1.0')).toBeUndefined()
106 expect(versionFromTag('vnext')).toBeUndefined()
107 })
108​
109 it('rejects a tag that does not match package versions', () => {
110 const pkgs = listPublicPackages()
111 const version = sharedVersion()
112 expect(() => assertVersionsMatchTag(pkgs, 'v9.9.9')).toThrow(
113 /does not match/,
114 )
115 expect(() => assertVersionsMatchTag(pkgs, `v${version}`)).not.toThrow()
116 expect(() =>
117 assertVersionsMatchTag(
118 [
119 { name: 'ok', version: '0.2.0', dir: '/tmp', dependencies: {} },
120 {
121 name: 'modelschemas',
122 version: '0.1.0',
123 dir: '/tmp',
124 dependencies: {},
125 },
126 ],
127 'v0.2.0',
128 ),
129 ).toThrow(/modelschemas@0.1.0/)
130 })
131})
132​
133describe('main', () => {
134 it('refuses --tag / RELEASE_TAG that do not match manifests', () => {
135 expect(() => main(['--tag', 'v9.9.9'])).toThrow(/does not match/)
136 const prev = process.env.RELEASE_TAG
137 process.env.RELEASE_TAG = 'v9.9.9'
138 try {
139 expect(() => main([])).toThrow(/does not match/)
140 } finally {
141 if (prev === undefined) delete process.env.RELEASE_TAG
142 else process.env.RELEASE_TAG = prev
143 }
144 })
145})
146​
147describe('assertPublishableManifest', () => {
148 it('rejects workspace: and catalog: specs', () => {
149 expect(() =>
150 assertPublishableManifest(
151 {
152 name: 'x',
153 version: '1.0.0',
154 dependencies: { '@modelschemas/client': 'workspace:*' },
155 },
156 'test',
157 ),
158 ).toThrow(/workspace:\*/)
159 })
160})
161​
162describe('publishManifest / assertShipsEntryPoints', () => {
163 it('lifts publishConfig entry points and keeps npm config there', () => {
164 expect(
165 publishManifest({
166 name: 'x',
167 main: './src/index.ts',
168 publishConfig: { access: 'public', main: './dist/index.js' },
169 }),
170 ).toEqual({
171 name: 'x',
172 main: './dist/index.js',
173 publishConfig: { access: 'public' },
174 })
175 expect(
176 publishManifest({ name: 'x', publishConfig: { access: 'public' } }),
177 ).toBeUndefined()
178 })
179​
180 it('refuses a tarball missing a file its manifest points at', () => {
181 const manifest = {
182 main: './dist/index.js',
183 exports: { '.': { types: './dist/index.d.ts' } },
184 }
185 expect(manifestEntryPoints(manifest)).toEqual([
186 'dist/index.d.ts',
187 'dist/index.js',
188 ])
189 expect(() =>
190 assertShipsEntryPoints(manifest, ['package/dist/index.js'], 'x.tgz'),
191 ).toThrow(/x.tgz: does not ship dist\/index.d.ts/)
192 })
193})
194​
195describe('packAll', () => {
196 const dest = join('dist', 'npm-pack-test')
197 const abs = resolve(dest)
198 let packed: Array<{ pkg: PublicPackage; tarball: string }> = []
199​
200 beforeAll(() => {
201 packed = packAll(publishOrder(listPublicPackages()), dest)
202 }, 120_000)
203 afterAll(() => rmSync(abs, { recursive: true, force: true }))
204​
205 it('rewrites workspace protocol, omits tests, and resolves relative dest from cwd', () => {
206 expect(packed.map((row) => row.pkg.name)).toEqual(
207 publishOrder(listPublicPackages()).map((pkg) => pkg.name),
208 )
209 const version = sharedVersion()
210 for (const { pkg, tarball } of packed) {
211 expect(tarball.startsWith(`${abs}${sep}`)).toBe(true)
212 expect(tarball.includes(`${sep}packages${sep}`)).toBe(false)
213 expect(existsSync(tarball)).toBe(true)
214 const manifest = readPackedManifest(tarball)
215 assertPublishableManifest(manifest, tarball)
216 const json = JSON.stringify(manifest)
217 expect(json).not.toContain('workspace:')
218 expect(json).not.toContain('catalog:')
219 if (pkg.name === 'modelschemas') {
220 expect(json).toContain(`"@modelschemas/client":"${version}"`)
221 expect(json).toContain(`"@modelschemas/codegen":"${version}"`)
222 }
223 if (pkg.name === '@modelschemas/vite') {
224 expect(json).toContain(`"@modelschemas/codegen":"${version}"`)
225 }
226 const entries = packedEntryNames(tarball)
227 expect(entries.some((entry) => entry.endsWith('.test.ts'))).toBe(false)
228 expect(entries).toContain('package/package.json')
229 expect(entries).toContain('package/LICENSE')
230 if (pkg.name === '@modelschemas/rate-card') {
231 expect(entries).toContain('package/dist/index.js')
232 expect(entries).toContain('package/dist/evaluator.d.ts')
233 expect(
234 entries.filter((e) => e.endsWith('.ts') && !e.endsWith('.d.ts')),
235 ).toEqual([])
236 } else {
237 expect(entries).toContain('package/src/index.ts')
238 }
239 }
240 })
241​
242 describe('the packed rate-card evaluator', () => {
243 let dir = ''
244 let evaluator = ''
245​
246 beforeAll(() => {
247 const row = packed.find((r) => r.pkg.name === '@modelschemas/rate-card')
248 if (!row) throw new Error('rate-card was not packed')
249 // No node_modules anywhere above: an import of any package fails.
250 dir = mkdtempSync(join(tmpdir(), 'rate-card-'))
251 run('tar', ['-xzf', row.tarball, '-C', dir], dir)
252 evaluator = join(dir, 'package', 'dist', 'evaluator.js')
253 })
254 afterAll(() => rmSync(dir, { recursive: true, force: true }))
255​
256 it('gives every shared estimate case its expected result', async () => {
257 const { evaluateCard } = (await import(
258 /* @vite-ignore */ pathToFileURL(evaluator).href
259 )) as {
260 evaluateCard: (
261 card: RateCard,
262 inputs: { request?: object; usage?: object },
263 ) => CardEvaluation
264 }
265 for (const c of ESTIMATE_CASES) {
266 expect(
267 settle(() =>
268 evaluateCard(c.card, { request: c.request, usage: c.usage }),
269 ),
270 c.name,
271 ).toEqual(packageExpected(c))
272 }
273 })
274 })
275})
276​
277describe('publish.yml', () => {
278 it('is the trusted-publisher workflow: OIDC, stage-only, no npm token', () => {
279 const yaml = readFileSync(
280 join(import.meta.dirname, '..', '.github', 'workflows', 'publish.yml'),
281 'utf8',
282 )
283 const withoutComments = yaml.replace(/^\s*#.*$/gm, '')
284 expect(withoutComments).toMatch(/id-token:\s*write/)
285 expect(withoutComments).toMatch(/environment:\s*npm/)
286 expect(withoutComments).toContain('npm stage publish')
287 expect(withoutComments.replaceAll('npm stage publish', '')).not.toContain(
288 'npm publish',
289 )
290 expect(withoutComments).not.toContain('NPM_TOKEN')
291 expect(withoutComments).not.toContain('NODE_AUTH_TOKEN')
292 expect(withoutComments).not.toContain('bun publish')
293 expect(withoutComments).toContain('RELEASE_TAG')
294 expect(withoutComments).toContain('scripts/npm-pack.ts')
295 expect(withoutComments).toMatch(/!inputs\.dry_run/)
296 expect(withoutComments).toMatch(/default:\s*true/)
297 expect(withoutComments).toContain('npm@11.19.0')
298 expect(withoutComments).not.toContain('npm@latest')
299 expect(withoutComments).toContain('persist-credentials: false')
300 expect(withoutComments).toMatch(/permissions:\s*\{\}/)
301 })
302})