Open History to see the last commit
1import { useAtomValue } from "@effect/atom-react";
2import { npmReleaseDatabaseMigration } from "@t3tools/shared/cliRelease";
3import * as Effect from "effect/Effect";
4import { FetchHttpClient, HttpClient, HttpClientResponse } from "effect/http";
5import { AsyncResult, Atom } from "effect/reactivity";
6
7export interface NpmRelease {
8 readonly version: string;
9 /** Absent on releases published before npm manifests carried it. */
10 readonly databaseMigration: number | undefined;
11}
12
13/** `spec` is an exact version or a dist-tag such as `nightly`. Null when npm has no such release.
14 * Refreshes only while mounted; the published check below keeps its own versions alive. */
15export const npmReleaseAtom = Atom.family((spec: string) =>
16 Atom.make(
17 Effect.gen(function* () {
18 const response = yield* HttpClient.get(
19 `https://registry.npmjs.org/t3/${encodeURIComponent(spec)}`,
20 );
21 if (response.status === 404) return null;
22 const body = yield* HttpClientResponse.filterStatusOk(response).pipe(
23 Effect.flatMap((ok) => ok.json),
24 );
25 if (
26 typeof body !== "object" ||
27 body === null ||
28 !("version" in body) ||
29 typeof body.version !== "string"
30 ) {
31 return null;
32 }
33 return {
34 version: body.version,
35 databaseMigration: npmReleaseDatabaseMigration(body),
36 } satisfies NpmRelease;
37 }).pipe(
38 // Tracing headers would make the browser send a CORS preflight, which npm rejects.
39 Effect.provideService(HttpClient.TracerPropagationEnabled, false),
40 Effect.provide(FetchHttpClient.layer),
41 ),
42 ).pipe(Atom.withRefresh("5 minutes"), Atom.withLabel(`npm-release:${spec}`)),
43);
44
45export const npmReleasePublishedAtom = Atom.family((version: string) =>
46 Atom.make((get) =>
47 get.result(npmReleaseAtom(version)).pipe(Effect.map((release) => release?.version === version)),
48 ).pipe(Atom.keepAlive, Atom.withLabel(`npm-release-published:${version}`)),
49);
50
51const NO_VERSION_ATOM = Atom.make(AsyncResult.success(false)).pipe(
52 Atom.withLabel("npm-release-published:none"),
53);
54
55export function useNpmReleasePublished(version: string | null): boolean {
56 const result = useAtomValue(version ? npmReleasePublishedAtom(version) : NO_VERSION_ATOM);
57 return AsyncResult.getOrElse(result, () => false);
58}