@vltpkg/query 1.3.8 → 1.5.0

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.
package/src/types.ts CHANGED
@@ -4,7 +4,7 @@ import type {
4
4
  PackageScore,
5
5
  } from '@vltpkg/security-archive'
6
6
  import type { DepID } from '@vltpkg/dep-id'
7
- import type { PostcssNode } from '@vltpkg/dss-parser'
7
+ import type { PartPseudoName, PostcssNode } from '@vltpkg/dss-parser'
8
8
 
9
9
  export type HostContextsMapResult = {
10
10
  initialEdges: EdgeLike[]
@@ -46,6 +46,24 @@ export type GetAuthHeader = (
46
46
  url: string,
47
47
  ) => Promise<string | undefined>
48
48
 
49
+ /**
50
+ * Whether an installed package ships agent skills; for `:skills`.
51
+ * Keeps fs out of this package.
52
+ */
53
+ export type HasSkills = (node: NodeLike) => Promise<boolean>
54
+
55
+ /**
56
+ * One top-level selector of a query and the nodes it matched. `name`
57
+ * and `patterns` are set when it ends in a part selector, e.g.
58
+ * `#a:skill(x, y*)`.
59
+ */
60
+ export type QueryPart<N = QueryResponseNode> = {
61
+ name?: PartPseudoName
62
+ /** as typed, `*` = glob; for matching only, never paths */
63
+ patterns?: string[]
64
+ nodes: N[]
65
+ }
66
+
49
67
  export type ParserState = {
50
68
  cancellable: () => Promise<void>
51
69
  collect: GraphSelectionState
@@ -53,6 +71,7 @@ export type ParserState = {
53
71
  current: PostcssNode
54
72
  diffFiles?: DiffFilesProvider
55
73
  getAuthHeader?: GetAuthHeader
74
+ hasSkills?: HasSkills
56
75
  hostContexts?: HostContextsMap
57
76
  importers: Set<NodeLike>
58
77
  initial: GraphSelectionState
@@ -63,6 +82,12 @@ export type ParserState = {
63
82
  signal: AbortSignal
64
83
  walk: ParserFn
65
84
  partial: GraphSelectionState
85
+ /** set by `:skill()`, read and cleared by `walk()` */
86
+ part?: Pick<QueryPart, 'name' | 'patterns'>
87
+ /** one entry per top-level selector, only when opted in */
88
+ parts?: QueryPart<NodeLike>[]
89
+ /** part selectors this consumer allows */
90
+ partSelectors?: ReadonlySet<PartPseudoName>
66
91
  retries: number
67
92
  securityArchive: SecurityArchiveLike | undefined
68
93
  scopeIDs?: DepID[]
@@ -75,6 +100,11 @@ export type QueryResponse = {
75
100
  importers: QueryResponseNode[]
76
101
  comment: string
77
102
  specificity: Specificity
103
+ /**
104
+ * one entry per top-level selector, only with `partSelectors` and
105
+ * a non-empty query
106
+ */
107
+ parts?: QueryPart[]
78
108
  }
79
109
 
80
110
  export type QueryResponseEdge = Omit<EdgeLike, 'from' | 'to'> & {
@@ -0,0 +1,19 @@
1
+ /* IMPORTANT
2
+ * This snapshot file is auto-generated, but designed for humans.
3
+ * It should be checked into source control and tracked carefully.
4
+ * Re-generate by setting TAP_SNAPSHOT=1 and running tests.
5
+ * Make sure to inspect the output below. Do not ignore changes!
6
+ */
7
+ 'use strict'
8
+ exports[`test/pseudo/skills.ts > TAP > matches packages the provider says ship skills > must match snapshot 1`] = `
9
+ Object {
10
+ "edges": Array [
11
+ "a",
12
+ "d",
13
+ ],
14
+ "nodes": Array [
15
+ "a",
16
+ "d",
17
+ ],
18
+ }
19
+ `
package/test/index.ts CHANGED
@@ -289,6 +289,99 @@ t.test('insights', async t => {
289
289
  }
290
290
  })
291
291
 
292
+ t.test('parts', async t => {
293
+ const graph = getSimpleGraph()
294
+ const opts = {
295
+ nodes: new Set(graph.nodes.values()),
296
+ edges: graph.edges,
297
+ importers: graph.importers,
298
+ securityArchive: undefined,
299
+ }
300
+ const query = new Query({ ...opts, partSelectors: ['skill'] })
301
+ const search = (q: string) => query.search(q, mockSearchOptions)
302
+ const parts = async (q: string) =>
303
+ (await search(q)).parts?.map(({ nodes, ...p }) => ({
304
+ ...p,
305
+ nodes: nodes.map(n => n.name).sort(),
306
+ }))
307
+
308
+ t.strictSame(await parts(':root > *, #b:skill(x)'), [
309
+ { nodes: ['@x/y', 'a', 'b', 'e'] },
310
+ { name: 'skill', patterns: ['x'], nodes: ['b'] },
311
+ ])
312
+ const res = await search(':root > *, #b:skill(x)')
313
+ const [plain, b] = res.parts ?? []
314
+ t.notOk(plain && 'name' in plain, 'plain part has no name')
315
+ t.notOk(plain && 'patterns' in plain, 'plain part has no patterns')
316
+ t.equal(
317
+ b?.nodes[0],
318
+ res.nodes.find(n => n.name === 'b'),
319
+ 'part nodes are response nodes',
320
+ )
321
+ t.ok(b?.nodes[0]?.insights, 'part nodes are hydrated')
322
+ t.equal(
323
+ await search(':root > *, #b:skill(x)'),
324
+ res,
325
+ 'cache hit keeps parts',
326
+ )
327
+
328
+ t.strictSame(await parts(':root > *:not(#b), #b:skill(x)'), [
329
+ { nodes: ['@x/y', 'a', 'e'] },
330
+ { name: 'skill', patterns: ['x'], nodes: ['b'] },
331
+ ])
332
+ t.strictSame(await parts('#a, #b:skill(x), #c:skill(y)'), [
333
+ { nodes: ['a'] },
334
+ { name: 'skill', patterns: ['x'], nodes: ['b'] },
335
+ { name: 'skill', patterns: ['y'], nodes: ['c'] },
336
+ ])
337
+ t.strictSame(await parts('#b:skill(x), #a'), [
338
+ { name: 'skill', patterns: ['x'], nodes: ['b'] },
339
+ { nodes: ['a'] },
340
+ ])
341
+ t.strictSame(await parts('#nope:skill(x)'), [
342
+ { name: 'skill', patterns: ['x'], nodes: [] },
343
+ ])
344
+ t.strictSame(await parts('#a, #b:skills(x)'), [
345
+ { nodes: ['a'] },
346
+ { nodes: [] },
347
+ ])
348
+ t.notOk('parts' in (await search('')), 'empty query')
349
+
350
+ const plainQuery = new Query(opts)
351
+ t.notOk(
352
+ 'parts' in
353
+ (await plainQuery.search(':root > *', mockSearchOptions)),
354
+ 'no parts without partSelectors',
355
+ )
356
+ })
357
+
358
+ t.test(':skills', async t => {
359
+ const graph = getSimpleGraph()
360
+ const query = new Query({
361
+ nodes: new Set(graph.nodes.values()),
362
+ edges: graph.edges,
363
+ importers: graph.importers,
364
+ securityArchive: undefined,
365
+ hasSkills: async node => node.name === 'c' || node.name === 'e',
366
+ })
367
+ const names = async (q: string) =>
368
+ (await query.search(q, mockSearchOptions)).nodes
369
+ .map(n => n.name)
370
+ .sort()
371
+ t.strictSame(await names(':skills'), ['c', 'e'])
372
+ t.strictSame(await names(':root > :skills'), ['e'])
373
+ t.strictSame(await names(':not(:skills)'), [
374
+ '@x/y',
375
+ 'a',
376
+ 'b',
377
+ 'd',
378
+ 'f',
379
+ 'my-project',
380
+ ])
381
+ t.strictSame(await names(':is(:skills)'), ['c', 'e'])
382
+ t.strictSame(await names(':has(:skills)'), ['b', 'd', 'my-project'])
383
+ })
384
+
292
385
  t.test('bad selector type', async t => {
293
386
  await t.rejects(
294
387
  walk(testBrokenState()),
@@ -333,6 +426,12 @@ t.test('trying to use tag selectors', async t => {
333
426
  'should suggest the pseudo-class of the same name',
334
427
  )
335
428
 
429
+ await t.rejects(
430
+ search('skill'),
431
+ { cause: { code: 'EQUERY', found: 'skill', wanted: '#skill' } },
432
+ 'should not suggest a part selector',
433
+ )
434
+
336
435
  await t.rejects(
337
436
  search('.foo'),
338
437
  { cause: { code: 'EQUERY', found: '.foo', wanted: '#foo' } },
@@ -0,0 +1,189 @@
1
+ import t from 'tap'
2
+ import { Query } from '../../src/index.ts'
3
+ import { getSimpleGraph } from '../fixtures/graph.ts'
4
+ import type { Test } from 'tap'
5
+ import type { QueryOptions } from '../../src/index.ts'
6
+
7
+ type Opts = Pick<QueryOptions, 'partSelectors'>
8
+
9
+ const search = (
10
+ q: string,
11
+ opts: Opts = { partSelectors: ['skill'] },
12
+ ) => {
13
+ const graph = getSimpleGraph()
14
+ return new Query({
15
+ edges: graph.edges,
16
+ nodes: new Set(graph.nodes.values()),
17
+ importers: graph.importers,
18
+ securityArchive: undefined,
19
+ ...opts,
20
+ }).search(q, { signal: new AbortController().signal })
21
+ }
22
+
23
+ const parts = async (q: string) =>
24
+ (await search(q)).parts?.map(({ nodes, ...p }) => ({
25
+ ...p,
26
+ nodes: nodes.map(n => n.name).sort(),
27
+ }))
28
+
29
+ type QueryErr = Error & {
30
+ cause: { code: string; found: string; wanted?: string }
31
+ }
32
+ const errorOf = async (q: string, opts?: Opts) =>
33
+ search(q, opts).then(
34
+ () => {
35
+ throw new Error(`expected ${q} to throw`)
36
+ },
37
+ (er: unknown) => er as QueryErr,
38
+ )
39
+
40
+ const fails = async (
41
+ t: Test,
42
+ queries: string[],
43
+ message: string,
44
+ opts?: Opts,
45
+ ) => {
46
+ for (const q of queries) {
47
+ const er = await errorOf(q, opts)
48
+ t.equal(er.message, message, q)
49
+ t.equal(er.cause.code, 'EQUERY', q)
50
+ }
51
+ }
52
+
53
+ t.test('patterns', async t => {
54
+ const cases: [string, string[]][] = [
55
+ ['#a:skill(find-skills)', ['find-skills']],
56
+ ['#a:skill("my skill")', ['my skill']],
57
+ [
58
+ '#a:skill(vercel*, *-review, a*b*c, *, **)',
59
+ ['vercel*', '*-review', 'a*b*c', '*', '**'],
60
+ ],
61
+ [
62
+ '#a:skill(X, my.skill, a_b, 3d-print, -x)',
63
+ ['X', 'my.skill', 'a_b', '3d-print', '-x'],
64
+ ],
65
+ ['#a:skill("my "*)', ['my *']],
66
+ ['#a:skill(a\\ b)', ['a b']],
67
+ ['#a:skill(/* c */ a)', ['a']],
68
+ ['#a:skill("it\'s")', ["it's"]],
69
+ ['#a:skill(x)/* c */ /* d */', ['x']],
70
+ ]
71
+ for (const [q, patterns] of cases) {
72
+ t.strictSame(
73
+ await parts(q),
74
+ [{ name: 'skill', patterns, nodes: ['a'] }],
75
+ q,
76
+ )
77
+ }
78
+ })
79
+
80
+ t.test('never filters nodes', async t => {
81
+ const nodesOf = async (q: string) => (await parts(q))?.[0]?.nodes
82
+ t.strictSame(await nodesOf(':skill(x)'), [
83
+ '@x/y',
84
+ 'a',
85
+ 'b',
86
+ 'c',
87
+ 'd',
88
+ 'e',
89
+ 'f',
90
+ 'my-project',
91
+ ])
92
+ t.strictSame(await nodesOf('#b :skill(x)'), ['c', 'd', 'e', 'f'])
93
+ t.strictSame(await nodesOf(':root > :skill(x)'), [
94
+ '@x/y',
95
+ 'a',
96
+ 'b',
97
+ 'e',
98
+ ])
99
+ })
100
+
101
+ t.test('specificity', async t => {
102
+ t.strictSame((await search('#a:skill(x)')).specificity, {
103
+ idCounter: 1,
104
+ commonCounter: 1,
105
+ })
106
+ })
107
+
108
+ t.test('errors', async t => {
109
+ await fails(
110
+ t,
111
+ [
112
+ '#a:skill(x) > #b',
113
+ '#a:skill(x):prod',
114
+ '#a:skill(x):skill(y)',
115
+ ':not(#a:skill(x))',
116
+ ':is(#a:skill(x))',
117
+ ':has(#a:skill(x))',
118
+ '#b, #a:skill(x) > *',
119
+ ],
120
+ ':skill() must end a top-level selector',
121
+ )
122
+ await fails(
123
+ t,
124
+ [
125
+ '#a:skill',
126
+ '#a:skill()',
127
+ '#a:skill( )',
128
+ '#a:skill(a,)',
129
+ '#a:skill(/* c */)',
130
+ '#a:skill("")',
131
+ ],
132
+ 'Missing skill name in :skill()',
133
+ )
134
+ await fails(
135
+ t,
136
+ ['#a:skill(a b)', '#a:skill(x > y)', '#b, #a:skill(a b)'],
137
+ 'Invalid skill name in :skill(), quote names with spaces',
138
+ )
139
+ await fails(
140
+ t,
141
+ ["#a:skill('b c')", "#a:skill(x, 'y')", "#a:skill('y'*)"],
142
+ 'Invalid skill name in :skill(), use double quotes',
143
+ )
144
+ await fails(
145
+ t,
146
+ [
147
+ '#a:skill(#x)',
148
+ '#a:skill(:prod)',
149
+ '#a:skill([x])',
150
+ '#a:skill(a|b)',
151
+ '#a:skill(|a)',
152
+ '#a:skill(a|*)',
153
+ '#a:skill(a&b)',
154
+ ],
155
+ 'Invalid skill name in :skill()',
156
+ )
157
+ t.equal((await errorOf('#a:skill(a b)')).cause.found, ':skill(a b)')
158
+ t.equal(
159
+ (await errorOf('#a:skill(x) > #b')).cause.found,
160
+ ':skill(x)',
161
+ )
162
+ })
163
+
164
+ t.test('opt-in', async t => {
165
+ const queries = ['#a:skill(x)', '#a, #b:skill(x)', '#a:skill()']
166
+ const message =
167
+ ':skill() only applies to --allow-skills and vlt skills'
168
+ for (const opts of [{}, { partSelectors: [] }]) {
169
+ await fails(t, queries, message, opts)
170
+ // position is checked first
171
+ await fails(
172
+ t,
173
+ [':not(#a:skill(x))'],
174
+ ':skill() must end a top-level selector',
175
+ opts,
176
+ )
177
+ }
178
+ })
179
+
180
+ t.test('typo', async t => {
181
+ const er = await errorOf('#a:skills(x)')
182
+ t.equal(er.message, ':skills takes no arguments')
183
+ t.equal(er.cause.wanted, ':skill')
184
+ // loose in a comma list: silently empty
185
+ t.strictSame(await parts('#a, #b:skills(x)'), [
186
+ { nodes: ['a'] },
187
+ { nodes: [] },
188
+ ])
189
+ })
@@ -0,0 +1,90 @@
1
+ import t from 'tap'
2
+ import postcssSelectorParser from 'postcss-selector-parser'
3
+ import type { EdgeLike, NodeLike } from '@vltpkg/types'
4
+ import type { HasSkills, ParserState } from '../../src/types.ts'
5
+ import { skills } from '../../src/pseudo/skills.ts'
6
+ import { getSimpleGraph } from '../fixtures/graph.ts'
7
+
8
+ const getState = (
9
+ query: string,
10
+ hasSkills?: HasSkills,
11
+ loose?: boolean,
12
+ ) => {
13
+ const graph = getSimpleGraph()
14
+ const current = postcssSelectorParser().astSync(query).first.first
15
+ const state: ParserState = {
16
+ comment: '',
17
+ current,
18
+ initial: {
19
+ edges: new Set(graph.edges.values()),
20
+ nodes: new Set(graph.nodes.values()),
21
+ },
22
+ partial: {
23
+ edges: new Set(graph.edges.values()),
24
+ nodes: new Set(graph.nodes.values()),
25
+ },
26
+ collect: { edges: new Set(), nodes: new Set() },
27
+ cancellable: async () => {},
28
+ walk: async i => i,
29
+ retries: 0,
30
+ securityArchive: undefined,
31
+ importers: new Set(graph.importers),
32
+ signal: new AbortController().signal,
33
+ specificity: { idCounter: 0, commonCounter: 0 },
34
+ hasSkills,
35
+ loose,
36
+ }
37
+ return state
38
+ }
39
+
40
+ const names = (state: ParserState) => ({
41
+ nodes: [...state.partial.nodes].map(n => n.name).sort(),
42
+ edges: [...state.partial.edges].map(e => e.name).sort(),
43
+ })
44
+
45
+ t.test('matches packages the provider says ship skills', async t => {
46
+ const asked: string[] = []
47
+ const hasSkills: HasSkills = async (node: NodeLike) => {
48
+ asked.push(String(node.name))
49
+ await new Promise(r => setTimeout(r, 0))
50
+ return node.name === 'a' || node.name === 'd'
51
+ }
52
+ const state = getState(':skills', hasSkills)
53
+ // edge with no node: dropped
54
+ state.partial.edges.add({ name: 'gone' } as EdgeLike)
55
+ const res = await skills(state)
56
+ t.strictSame(names(res), { nodes: ['a', 'd'], edges: ['a', 'd'] })
57
+ t.matchSnapshot(names(res))
58
+ t.strictSame(
59
+ asked.sort(),
60
+ ['@x/y', 'a', 'b', 'c', 'd', 'e', 'f', 'my-project'],
61
+ 'asked once per node',
62
+ )
63
+ })
64
+
65
+ t.test('none', async t => {
66
+ const res = await skills(getState(':skills', async () => false))
67
+ t.strictSame(names(res), { nodes: [], edges: [] })
68
+ })
69
+
70
+ t.test('no provider', async t => {
71
+ await t.rejects(skills(getState(':skills')), {
72
+ message: 'The :skills selector is not supported here',
73
+ cause: { code: 'EQUERY', found: ':skills' },
74
+ })
75
+ })
76
+
77
+ t.test('arguments', async t => {
78
+ for (const q of [':skills(x)', ':skills()']) {
79
+ await t.rejects(
80
+ skills(getState(q, async () => true)),
81
+ {
82
+ message: ':skills takes no arguments',
83
+ cause: { code: 'EQUERY', found: q, wanted: ':skill' },
84
+ },
85
+ q,
86
+ )
87
+ const res = await skills(getState(q, async () => true, true))
88
+ t.strictSame(names(res), { nodes: [], edges: [] }, `${q} loose`)
89
+ }
90
+ })