@celljs/ta-extensions 4.8.0 → 4.9.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,239 +0,0 @@
1
- /** What the market tells by the keywords of a package: pi's gallery has no other mark of the kind. */
2
- export type MarketKind = 'extensions' | 'skills' | 'prompts' | 'themes';
3
-
4
- /** A pi package of npm, as the market lists it. */
5
- export interface MarketPackage {
6
- name: string;
7
- version: string;
8
- description?: string;
9
- /** Who published it last, by npm user name. */
10
- publisher?: string;
11
- /** Downloads of the last month. */
12
- downloads?: number;
13
- /** When its version was published (ISO). */
14
- date?: string;
15
- kinds: MarketKind[];
16
- links: MarketLinks;
17
- }
18
-
19
- export interface MarketLinks {
20
- npm: string;
21
- repository?: string;
22
- homepage?: string;
23
- }
24
-
25
- /** One page of a search. */
26
- export interface MarketPage {
27
- /** How many there are, when the search has no words: npm counts every package of the keyword. */
28
- total?: number;
29
- packages: MarketPackage[];
30
- /** Where the next page starts; undefined at the end. */
31
- next?: number;
32
- }
33
-
34
- /** A package of the market with what its page shows: its README and the previews of pi's gallery. */
35
- export interface MarketDetail extends MarketPackage {
36
- license?: string;
37
- /** Links and images of the README made absolute, to its repository. */
38
- readme?: string;
39
- /** `pi.image` and `pi.video` of its package.json, as pi's gallery shows them. */
40
- image?: string;
41
- video?: string;
42
- /** What it holds, by `pi` of its package.json; empty when it has none and the kinds tell. */
43
- resources: ('extensions' | 'web' | 'skills' | 'prompts' | 'themes')[];
44
- }
45
-
46
- const KIND_WORDS: Record<string, MarketKind> = {
47
- extension: 'extensions',
48
- extensions: 'extensions',
49
- 'pi-extension': 'extensions',
50
- skill: 'skills',
51
- skills: 'skills',
52
- 'pi-skill': 'skills',
53
- prompt: 'prompts',
54
- prompts: 'prompts',
55
- 'pi-prompt': 'prompts',
56
- 'prompt-template': 'prompts',
57
- theme: 'themes',
58
- themes: 'themes',
59
- 'pi-theme': 'themes',
60
- };
61
-
62
- const KIND_ORDER: MarketKind[] = ['extensions', 'skills', 'prompts', 'themes'];
63
-
64
- export namespace MarketUtil {
65
- export function kindsOf(keywords: unknown): MarketKind[] {
66
- const found = new Set<MarketKind>();
67
- for (const keyword of Array.isArray(keywords) ? keywords : []) {
68
- const kind = typeof keyword === 'string' ? KIND_WORDS[keyword.toLowerCase()] : undefined;
69
- if (kind) {
70
- found.add(kind);
71
- }
72
- }
73
- return KIND_ORDER.filter(kind => found.has(kind));
74
- }
75
-
76
- /** 1234 → 1.2K, 3284659 → 3.3M: as galleries count downloads. */
77
- export function compact(count: number): string {
78
- const units: [number, string][] = [
79
- [1e9, 'B'],
80
- [1e6, 'M'],
81
- [1e3, 'K'],
82
- ];
83
- for (const [size, unit] of units) {
84
- if (count >= size) {
85
- const value = count / size;
86
- return `${value >= 100 ? Math.round(value) : Number(value.toFixed(1))}${unit}`;
87
- }
88
- }
89
- return String(count);
90
- }
91
-
92
- /** How long ago, in the largest unit that fits; `now` for the tests. */
93
- export function ago(iso: string | undefined, language: string, now = Date.now()): string | undefined {
94
- const time = iso ? Date.parse(iso) : Number.NaN;
95
- if (Number.isNaN(time)) {
96
- return undefined;
97
- }
98
- const seconds = Math.round((time - now) / 1000);
99
- const steps: [Intl.RelativeTimeFormatUnit, number][] = [
100
- ['year', 31536000],
101
- ['month', 2592000],
102
- ['week', 604800],
103
- ['day', 86400],
104
- ['hour', 3600],
105
- ['minute', 60],
106
- ];
107
- const format = new Intl.RelativeTimeFormat(language, { numeric: 'auto' });
108
- for (const [unit, size] of steps) {
109
- if (Math.abs(seconds) >= size) {
110
- return format.format(Math.round(seconds / size), unit);
111
- }
112
- }
113
- return format.format(0, 'minute');
114
- }
115
-
116
- /** Who to name for a package: an owner of it, not the robot of CI that published it last. */
117
- export function person(...names: (string | undefined)[]): string | undefined {
118
- return names.find(name => !!name && !/^github[ -]actions$|\[bot\]$|^npm-?bot$/i.test(name)) ?? undefined;
119
- }
120
-
121
- /** The name a person reads: without its scope, and without a `pi-` that every one has. */
122
- export function shortName(name: string): string {
123
- const plain = name.slice(name.lastIndexOf('/') + 1);
124
- return plain.replace(/^pi-(?=.)/, '');
125
- }
126
-
127
- /** One or two letters and a hue, the same for a name every time: the face of a package that has no picture. */
128
- export function monogram(name: string): { letters: string; hue: number } {
129
- const words = shortName(name)
130
- .split(/[-_.\s]+/)
131
- .filter(Boolean);
132
- const letters = (words.length > 1 ? words[0][0] + words[1][0] : (words[0] ?? name).slice(0, 2)).toUpperCase();
133
- let hash = 0;
134
- for (let i = 0; i < name.length; i++) {
135
- hash = (hash * 31 + name.charCodeAt(i)) | 0;
136
- }
137
- return { letters, hue: Math.abs(hash) % 360 };
138
- }
139
-
140
- /** `git+https://github.com/a/b.git` → `https://github.com/a/b`; undefined when it is not a page of the web. */
141
- export function repositoryUrl(repository: unknown): string | undefined {
142
- const raw = typeof repository === 'string' ? repository : (repository as { url?: unknown } | undefined)?.url;
143
- if (typeof raw !== 'string') {
144
- return undefined;
145
- }
146
- const github = /^github:(.+)$/.exec(raw) ?? /^([\w.-]+\/[\w.-]+)$/.exec(raw);
147
- const url = github
148
- ? `https://github.com/${github[1]}`
149
- : raw
150
- .replace(/^git\+/, '')
151
- .replace(/^git:\/\//, 'https://')
152
- .replace(/^ssh:\/\/git@/, 'https://');
153
- return /^https?:\/\//.test(url) ? url.replace(/\.git$/, '').replace(/\/$/, '') : undefined;
154
- }
155
-
156
- /** Whether a package has each word of a search, in its name, description or keywords (`themes` finds `theme`). */
157
- export function matches(pkg: Pick<MarketPackage, 'name' | 'description'> & { keywords?: string[] }, query: string): boolean {
158
- const text = [pkg.name, pkg.description ?? '', ...(pkg.keywords ?? [])].join(' ').toLowerCase();
159
- return query
160
- .toLowerCase()
161
- .split(/\s+/)
162
- .filter(Boolean)
163
- .every(word => text.includes(word) || (word.length > 3 && word.endsWith('s') && text.includes(word.slice(0, -1))));
164
- }
165
-
166
- /**
167
- * A README as the page shows it, in the Markdown of Ta, which shows no HTML: images, links and
168
- * headings of HTML become Markdown, badges go, other tags leave their text; code stays as it is.
169
- * Links and images relative to the package point into its repository on GitHub.
170
- */
171
- export function readableReadme(readme: string, repository: string | undefined): string {
172
- const parts = readme.split(/(^[ \t]*(?:```|~~~)[^\n]*\n[\s\S]*?^[ \t]*(?:```|~~~)[ \t]*$)/m);
173
- return parts
174
- .map((part, index) => (index % 2 === 1 ? part : absoluteReadme(fromHtml(part), repository).replace(/\n{3,}/g, '\n\n')))
175
- .join('')
176
- .trim();
177
- }
178
-
179
- function attribute(tag: string, name: string): string | undefined {
180
- return new RegExp(`\\b${name}\\s*=\\s*(["'])(.*?)\\1`, 'i').exec(tag)?.[2];
181
- }
182
-
183
- function isBadge(src: string): boolean {
184
- return /shields\.io|badgen\.net|badge/i.test(src);
185
- }
186
-
187
- function fromHtml(text: string): string {
188
- return text
189
- .replace(/<!--[\s\S]*?-->/g, '')
190
- .replace(/<(source|meta|link)\b[^>]*>/gi, '')
191
- .replace(/<img\b[^>]*>/gi, tag => {
192
- const src = attribute(tag, 'src');
193
- return src && !isBadge(src) ? `\n\n![${attribute(tag, 'alt') ?? ''}](${src})\n\n` : '';
194
- })
195
- .replace(/!\[[^\]]*\]\(([^)\s]+)[^)]*\)/g, (whole, src: string) => (isBadge(src) ? '' : whole))
196
- .replace(/<a\b[^>]*>([\s\S]*?)<\/a>/gi, (tag, inner: string) => {
197
- const href = attribute(tag, 'href');
198
- const label = inner.trim();
199
- return !label ? '' : href && !label.includes('![') ? `[${label}](${href})` : label;
200
- })
201
- .replace(/\[\s*\]\([^)]*\)/g, '')
202
- .replace(
203
- /<h([1-6])\b[^>]*>([\s\S]*?)<\/h\1>/gi,
204
- (_whole, level: string, inner: string) => `\n\n${'#'.repeat(Number(level))} ${inner.replace(/<[^>]+>/g, '').trim()}\n\n`,
205
- )
206
- .replace(/<br\s*\/?>/gi, '\n')
207
- .replace(
208
- /<\/?(p|div|span|center|picture|details|summary|b|strong|em|i|u|sub|sup|kbd|small|big|font|table|thead|tbody|tr|td|th|hr|section|article|figure|figcaption)\b[^>]*>/gi,
209
- '',
210
- )
211
- .replace(/^[ \t]+$/gm, '');
212
- }
213
-
214
- /**
215
- * The links and images of a README made absolute: those relative to the package point into its
216
- * repository on GitHub, where npm shows them too. Others are left as they are.
217
- */
218
- export function absoluteReadme(readme: string, repository: string | undefined): string {
219
- const github = repository ? /^https:\/\/github\.com\/([^/]+\/[^/#?]+)/.exec(repository)?.[1] : undefined;
220
- if (!github) {
221
- return readme;
222
- }
223
- const resolve = (target: string, image: boolean) => {
224
- if (/^([a-z][a-z0-9+.-]*:|#|\/\/)/i.test(target)) {
225
- return target;
226
- }
227
- const path = target.replace(/^\.?\//, '');
228
- return image ? `https://raw.githubusercontent.com/${github}/HEAD/${path}` : `https://github.com/${github}/blob/HEAD/${path}`;
229
- };
230
- return readme
231
- .replace(/(!?)\[([^\]]*)\]\(\s*<?([^)\s>]+)>?(\s+"[^"]*")?\s*\)/g, (_whole, bang: string, text: string, target: string, title = '') => {
232
- return `${bang}[${text}](${resolve(target, bang === '!')}${title})`;
233
- })
234
- .replace(
235
- /(<img\b[^>]*\bsrc=)(["'])([^"']+)\2/gi,
236
- (_whole, head: string, quote: string, target: string) => `${head}${quote}${resolve(target, true)}${quote}`,
237
- );
238
- }
239
- }
@@ -1,245 +0,0 @@
1
- import { type ExtensionsContext, icon } from './context';
2
- import { ExtensionWords } from './i18n';
3
- import { MarketDetailView } from './market-detail';
4
- import { InstallButton, PackageFace, PackageName } from './market-parts';
5
- import { type MarketPackage, MarketUtil } from './market-util';
6
- import { React } from './react';
7
-
8
- /** How long the market waits for the user to stop typing before it asks npm. */
9
- const DEBOUNCE = 300;
10
-
11
- /**
12
- * The market: a search of the pi packages of npm, the most used first, with topics to start from; a
13
- * package installs in one click, or opens on a page of its own with its README.
14
- */
15
- export function MarketView({ context }: { context: ExtensionsContext }): React.ReactElement {
16
- const { market, selected } = context;
17
- const name = selected.use();
18
- const list = React.useRef<HTMLDivElement>(null);
19
- // The list stays below the page of a package, scrolled where it was.
20
- const scroll = React.useRef(0);
21
- const scroller = () => list.current?.closest('.tax-page') ?? undefined;
22
- const open = (next: string) => {
23
- scroll.current = scroller()?.scrollTop ?? 0;
24
- selected.set(next);
25
- };
26
- React.useLayoutEffect(() => {
27
- const element = scroller();
28
- if (element) {
29
- element.scrollTop = name ? 0 : scroll.current;
30
- }
31
- }, [name]);
32
- React.useEffect(() => {
33
- void market.search(market.state.query);
34
- }, [market]);
35
- return (
36
- <>
37
- <div ref={list} hidden={!!name}>
38
- <MarketList context={context} onOpen={open} />
39
- </div>
40
- {name && <MarketDetailView key={name} context={context} name={name} onBack={() => selected.set(undefined)} />}
41
- </>
42
- );
43
- }
44
-
45
- function MarketList({ context, onOpen }: { context: ExtensionsContext; onOpen(name: string): void }): React.ReactElement {
46
- const { pi, market, actions } = context;
47
- const words = actions.words;
48
- const state = React.useSyncExternalStore(
49
- listener => market.subscribe(listener),
50
- () => market.state,
51
- );
52
- const [text, setText] = React.useState(state.query);
53
- const input = React.useRef<HTMLInputElement>(null);
54
- React.useEffect(() => {
55
- const timer = setTimeout(() => void market.search(text), DEBOUNCE);
56
- return () => clearTimeout(timer);
57
- }, [market, text]);
58
- const pick = (query: string) => {
59
- setText(query);
60
- void market.search(query);
61
- };
62
- const Search = icon(pi, 'Search');
63
- const X = icon(pi, 'X');
64
- const { packages, loading, error, query, total, next } = state;
65
- const count = query ? (next === undefined ? packages?.length : undefined) : total;
66
- const first = loading && !packages;
67
- return (
68
- <div className="tax-market">
69
- <form
70
- className="tax-search"
71
- onSubmit={event => {
72
- event.preventDefault();
73
- void market.search(text);
74
- }}
75
- >
76
- <Search size={16} />
77
- <input
78
- ref={input}
79
- type="search"
80
- value={text}
81
- placeholder={words.marketSearch}
82
- aria-label={words.marketSearch}
83
- spellCheck={false}
84
- onChange={event => setText(event.target.value)}
85
- onKeyDown={event => {
86
- if (event.key === 'Escape' && text) {
87
- event.preventDefault();
88
- pick('');
89
- }
90
- }}
91
- />
92
- {text && (
93
- <button
94
- type="button"
95
- className="tax-search-clear"
96
- aria-label={words.marketClear}
97
- title={words.marketClear}
98
- onClick={() => {
99
- pick('');
100
- input.current?.focus();
101
- }}
102
- >
103
- <X size={14} />
104
- </button>
105
- )}
106
- </form>
107
- <div className="tax-topics">
108
- {words.topics.map(topic => (
109
- <button
110
- key={topic.query}
111
- type="button"
112
- className={`tax-topic${query === topic.query ? ' tax-active' : ''}`}
113
- aria-pressed={query === topic.query}
114
- onClick={() => pick(query === topic.query ? '' : topic.query)}
115
- >
116
- {topic.label}
117
- </button>
118
- ))}
119
- </div>
120
- <div className="tax-section-head">
121
- <h2>
122
- {query ? words.marketResults : words.marketPopular}
123
- {loading && packages && <span className="tax-spin tax-head-spin">{React.createElement(icon(pi, 'LoaderCircle'), { size: 13 })}</span>}
124
- </h2>
125
- {count !== undefined && !error && (
126
- <span className="tax-count-note">{ExtensionWords.fill(words.marketCount, { count: count.toLocaleString(pi.ui.language) })}</span>
127
- )}
128
- </div>
129
- {error ? (
130
- <div className="tax-empty tax-market-error">
131
- <strong>{words.marketError}</strong>
132
- <span>{error}</span>
133
- <button type="button" className="tax-button" onClick={() => void market.search(text)}>
134
- {words.retry}
135
- </button>
136
- </div>
137
- ) : first ? (
138
- <div className="tax-grid" aria-busy="true">
139
- {Array.from({ length: 6 }, (_, index) => (
140
- <div key={index} className="tax-card tax-skeleton" />
141
- ))}
142
- </div>
143
- ) : packages?.length === 0 ? (
144
- <div className="tax-empty">{ExtensionWords.fill(words.marketEmpty, { query })}</div>
145
- ) : (
146
- <>
147
- <div className="tax-grid">
148
- {packages?.map(pkg => (
149
- <MarketCard key={pkg.name} context={context} pkg={pkg} onOpen={onOpen} />
150
- ))}
151
- </div>
152
- <MoreSentinel context={context} />
153
- </>
154
- )}
155
- <div className="tax-note tax-market-note">{words.marketNote}</div>
156
- </div>
157
- );
158
- }
159
-
160
- /** Asks for the next page as the end of the list comes near, as feeds do. */
161
- function MoreSentinel({ context }: { context: ExtensionsContext }): React.ReactElement | null {
162
- const { market, actions } = context;
163
- const words = actions.words;
164
- const state = React.useSyncExternalStore(
165
- listener => market.subscribe(listener),
166
- () => market.state,
167
- );
168
- const ref = React.useRef<HTMLDivElement>(null);
169
- const more = !!state.packages && state.next !== undefined;
170
- React.useEffect(() => {
171
- const element = ref.current;
172
- if (!element || !more) {
173
- return undefined;
174
- }
175
- const observer = new IntersectionObserver(entries => entries.some(entry => entry.isIntersecting) && void market.more(), { rootMargin: '480px 0px' });
176
- observer.observe(element);
177
- return () => observer.disconnect();
178
- }, [market, more, state.packages?.length]);
179
- if (!state.packages?.length) {
180
- return null;
181
- }
182
- return (
183
- <div ref={ref} className="tax-more">
184
- {more ? words.loadingMore : words.allShown}
185
- </div>
186
- );
187
- }
188
-
189
- interface MarketCardProps {
190
- context: ExtensionsContext;
191
- pkg: MarketPackage;
192
- onOpen(name: string): void;
193
- }
194
-
195
- /** A package: its face, name, who made it and how much it is used; what it does; a button to install it. */
196
- function MarketCard({ context, pkg, onOpen }: MarketCardProps): React.ReactElement {
197
- const { pi, actions } = context;
198
- const words = actions.words;
199
- const Down = icon(pi, 'ArrowDown');
200
- const ago = MarketUtil.ago(pkg.date, pi.ui.language);
201
- return (
202
- // biome-ignore lint/a11y/useSemanticElements: a card holds a button of its own, which a button cannot
203
- <div
204
- className="tax-card"
205
- role="button"
206
- tabIndex={0}
207
- aria-label={pkg.name}
208
- onClick={() => onOpen(pkg.name)}
209
- onKeyDown={event => {
210
- if (event.target === event.currentTarget && (event.key === 'Enter' || event.key === ' ')) {
211
- event.preventDefault();
212
- onOpen(pkg.name);
213
- }
214
- }}
215
- >
216
- <div className="tax-card-head">
217
- <PackageFace name={pkg.name} size={40} />
218
- <div className="tax-card-title">
219
- <div className="tax-card-name" title={pkg.name}>
220
- <PackageName name={pkg.name} />
221
- </div>
222
- <div className="tax-card-meta">
223
- {pkg.publisher && <span className="tax-ellipsis">{ExtensionWords.fill(words.by, { name: pkg.publisher })}</span>}
224
- {pkg.downloads !== undefined && pkg.downloads > 0 && (
225
- <span className="tax-downloads">
226
- <Down size={11} />
227
- {ExtensionWords.fill(words.perMonth, { count: MarketUtil.compact(pkg.downloads) })}
228
- </span>
229
- )}
230
- </div>
231
- </div>
232
- <InstallButton context={context} name={pkg.name} />
233
- </div>
234
- <p className="tax-card-description">{pkg.description}</p>
235
- <div className="tax-card-foot">
236
- {pkg.kinds.map(kind => (
237
- <span key={kind} className="tax-tag">
238
- {words.marketKinds[kind]}
239
- </span>
240
- ))}
241
- {ago && <span className="tax-card-time">{ago}</span>}
242
- </div>
243
- </div>
244
- );
245
- }
@@ -1,154 +0,0 @@
1
- import { describe, expect, it } from 'bun:test';
2
- import { type Fetch, NpmMarket, PAGE_SIZE } from './market';
3
-
4
- function found(name: string, extra: Record<string, unknown> = {}) {
5
- return {
6
- downloads: { monthly: 1200 },
7
- package: {
8
- name,
9
- version: '1.0.0',
10
- description: `${name} for pi`,
11
- keywords: ['pi-package', 'extension'],
12
- date: '2026-11-01T00:00:00Z',
13
- publisher: { username: 'you' },
14
- links: {},
15
- ...extra,
16
- },
17
- };
18
- }
19
-
20
- /** npm, answering each URL by the function; it keeps the URLs asked. */
21
- function registry(answer: (url: URL) => unknown) {
22
- const urls: string[] = [];
23
- const fetch: Fetch = async url => {
24
- urls.push(url);
25
- const body = answer(new URL(url));
26
- if (body === undefined) {
27
- return new Response('', { status: 404 });
28
- }
29
- return typeof body === 'string' ? new Response(body) : Response.json(body);
30
- };
31
- return { fetch, urls };
32
- }
33
-
34
- describe('NpmMarket', () => {
35
- it('searches the pi packages of npm, and pages on until the end', async () => {
36
- const npm = registry(url => {
37
- expect(url.searchParams.get('text')).toBe('keywords:pi-package');
38
- const from = Number(url.searchParams.get('from'));
39
- const count = from === 0 ? PAGE_SIZE : 3;
40
- return { total: PAGE_SIZE + 3, objects: Array.from({ length: count }, (_, i) => found(`pkg-${from + i}`)) };
41
- });
42
- const market = new NpmMarket(npm.fetch, 'https://npm.test');
43
- const first = await market.search('');
44
- expect(first).toMatchObject({ total: PAGE_SIZE + 3, next: PAGE_SIZE });
45
- expect(first.packages[0]).toEqual({
46
- name: 'pkg-0',
47
- version: '1.0.0',
48
- description: 'pkg-0 for pi',
49
- publisher: 'you',
50
- downloads: 1200,
51
- date: '2026-11-01T00:00:00Z',
52
- kinds: ['extensions'],
53
- links: { npm: 'https://www.npmjs.com/package/pkg-0', repository: undefined, homepage: undefined },
54
- });
55
- const last = await market.search('', first.next);
56
- expect(last.packages).toHaveLength(3);
57
- expect(last.next).toBeUndefined();
58
- });
59
-
60
- it('leaves out what does not match the words, and ends the search there', async () => {
61
- const npm = registry(url => {
62
- expect(url.searchParams.get('text')).toBe('pomodoro keywords:pi-package');
63
- return { total: 9999, objects: [found('pi-pomodoro'), found('timer', { description: 'A Pomodoro timer' }), found('pi-web-access')] };
64
- });
65
- const page = await new NpmMarket(npm.fetch).search(' pomodoro ');
66
- expect(page.packages.map(pkg => pkg.name)).toEqual(['pi-pomodoro', 'timer']);
67
- expect(page.total).toBeUndefined();
68
- expect(page.next).toBeUndefined();
69
- });
70
-
71
- it('asks npm once in a few minutes for the same search, and again after a failure', async () => {
72
- let now = 0;
73
- let fail = true;
74
- const npm = registry(() => (fail ? undefined : { total: 1, objects: [found('a')] }));
75
- const market = new NpmMarket(npm.fetch, 'https://npm.test', () => now);
76
- await expect(market.search('a')).rejects.toThrow('npm has no such package');
77
- fail = false;
78
- await market.search('a');
79
- await market.search('a');
80
- expect(npm.urls).toHaveLength(2);
81
- now += 6 * 60_000;
82
- await market.search('a');
83
- expect(npm.urls).toHaveLength(3);
84
- });
85
-
86
- it('gives a package with its README as published, previews and what it holds', async () => {
87
- const npm = registry(url => {
88
- switch (url.origin + url.pathname) {
89
- case 'https://npm.test/@you%2fpi-tools/latest':
90
- return {
91
- name: '@you/pi-tools',
92
- version: '2.0.0',
93
- description: 'Tools',
94
- license: 'MIT',
95
- keywords: ['pi-package'],
96
- repository: { url: 'git+https://github.com/you/pi-tools.git' },
97
- maintainers: [{ name: 'you' }],
98
- _npmUser: { name: 'GitHub Actions' },
99
- pi: { extensions: ['./a.ts'], skills: ['./skills'], image: 'https://x.dev/a.png', video: 'http://insecure/a.mp4' },
100
- };
101
- case 'https://api.npmjs.org/downloads/point/last-month/@you/pi-tools':
102
- return { downloads: 4321 };
103
- case 'https://cdn.jsdelivr.net/npm/@you/pi-tools@2.0.0/README.md':
104
- return '<img src="./shot.png" alt="Shot">';
105
- default:
106
- return undefined;
107
- }
108
- });
109
- const detail = await new NpmMarket(npm.fetch, 'https://npm.test').detail('@you/pi-tools');
110
- expect(detail).toMatchObject({
111
- name: '@you/pi-tools',
112
- version: '2.0.0',
113
- description: 'Tools',
114
- license: 'MIT',
115
- publisher: 'you',
116
- downloads: 4321,
117
- image: 'https://x.dev/a.png',
118
- resources: ['extensions', 'skills'],
119
- readme: '![Shot](https://raw.githubusercontent.com/you/pi-tools/HEAD/shot.png)',
120
- links: { npm: 'https://www.npmjs.com/package/@you/pi-tools', repository: 'https://github.com/you/pi-tools' },
121
- });
122
- expect(detail.video).toBeUndefined();
123
- expect(npm.urls.some(url => url.includes('raw.githubusercontent'))).toBe(false);
124
- });
125
-
126
- it('takes the README of the repository when the CDN has none, and shows the package without one', async () => {
127
- const manifest = { name: 'tools', version: '1.0.0', repository: { url: 'https://github.com/you/mono', directory: 'packages/tools' } };
128
- const withRepository = registry(url => {
129
- if (url.pathname === '/tools/latest') return manifest;
130
- if (url.href === 'https://raw.githubusercontent.com/you/mono/HEAD/packages/tools/README.md') return '# Tools';
131
- return undefined;
132
- });
133
- expect((await new NpmMarket(withRepository.fetch, 'https://npm.test').detail('tools')).readme).toBe('# Tools');
134
- const without = registry(url => (url.pathname === '/tools/latest' ? { name: 'tools', version: '1.0.0' } : undefined));
135
- expect(await new NpmMarket(without.fetch, 'https://npm.test').detail('tools')).toMatchObject({
136
- name: 'tools',
137
- readme: undefined,
138
- downloads: undefined,
139
- });
140
- });
141
-
142
- it('refuses what is not the name of a package, before asking npm', async () => {
143
- const npm = registry(() => ({}));
144
- await expect(new NpmMarket(npm.fetch).detail('../../etc')).rejects.toThrow('is not the name of an npm package');
145
- expect(npm.urls).toHaveLength(0);
146
- });
147
-
148
- it('says when npm cannot be reached', async () => {
149
- const market = new NpmMarket(async () => {
150
- throw new Error('getaddrinfo ENOTFOUND');
151
- });
152
- await expect(market.search('')).rejects.toThrow('npm cannot be reached: getaddrinfo ENOTFOUND');
153
- });
154
- });