-
-
Notifications
You must be signed in to change notification settings - Fork 48
/
Copy pathno-navigation-without-base.ts
378 lines (354 loc) · 10.4 KB
/
no-navigation-without-base.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
import type { TSESTree } from '@typescript-eslint/types';
import { createRule } from '../utils/index.js';
import { ReferenceTracker } from '@eslint-community/eslint-utils';
import { findVariable } from '../utils/ast-utils.js';
import type { RuleContext } from '../types.js';
import type { SvelteLiteral } from 'svelte-eslint-parser/lib/ast';
export default createRule('no-navigation-without-base', {
meta: {
docs: {
description:
'disallow using navigation (links, goto, pushState, replaceState) without the base path',
category: 'SvelteKit',
recommended: false
},
schema: [
{
type: 'object',
properties: {
ignoreGoto: {
type: 'boolean'
},
ignoreLinks: {
type: 'boolean'
},
ignorePushState: {
type: 'boolean'
},
ignoreReplaceState: {
type: 'boolean'
}
},
additionalProperties: false
}
],
messages: {
gotoNotPrefixed: "Found a goto() call with a url that isn't prefixed with the base path.",
linkNotPrefixed: "Found a link with a url that isn't prefixed with the base path.",
pushStateNotPrefixed:
"Found a pushState() call with a url that isn't prefixed with the base path.",
replaceStateNotPrefixed:
"Found a replaceState() call with a url that isn't prefixed with the base path."
},
type: 'suggestion'
},
create(context) {
let basePathNames: Set<TSESTree.Identifier> = new Set<TSESTree.Identifier>();
return {
Program() {
const referenceTracker = new ReferenceTracker(context.sourceCode.scopeManager.globalScope!);
basePathNames = extractBasePathReferences(referenceTracker, context);
const {
goto: gotoCalls,
pushState: pushStateCalls,
replaceState: replaceStateCalls
} = extractFunctionCallReferences(referenceTracker);
if (context.options[0]?.ignoreGoto !== true) {
for (const gotoCall of gotoCalls) {
checkGotoCall(context, gotoCall, basePathNames);
}
}
if (context.options[0]?.ignorePushState !== true) {
for (const pushStateCall of pushStateCalls) {
checkShallowNavigationCall(
context,
pushStateCall,
basePathNames,
'pushStateNotPrefixed'
);
}
}
if (context.options[0]?.ignoreReplaceState !== true) {
for (const replaceStateCall of replaceStateCalls) {
checkShallowNavigationCall(
context,
replaceStateCall,
basePathNames,
'replaceStateNotPrefixed'
);
}
}
},
SvelteAttribute(node) {
if (
context.options[0]?.ignoreLinks === true ||
node.parent.parent.type !== 'SvelteElement' ||
node.parent.parent.kind !== 'html' ||
node.parent.parent.name.type !== 'SvelteName' ||
node.parent.parent.name.name !== 'a' ||
node.key.name !== 'href'
) {
return;
}
const hrefValue = node.value[0];
if (hrefValue.type === 'SvelteLiteral') {
if (!expressionIsAbsolute(hrefValue) && !expressionIsFragment(hrefValue)) {
context.report({ loc: hrefValue.loc, messageId: 'linkNotPrefixed' });
}
return;
}
if (
!expressionStartsWithBase(context, hrefValue.expression, basePathNames) &&
!expressionIsAbsolute(hrefValue.expression) &&
!expressionIsFragment(hrefValue.expression)
) {
context.report({ loc: hrefValue.loc, messageId: 'linkNotPrefixed' });
}
}
};
}
});
// Extract all imports of the base path
function extractBasePathReferences(
referenceTracker: ReferenceTracker,
context: RuleContext
): Set<TSESTree.Identifier> {
const set = new Set<TSESTree.Identifier>();
for (const { node } of referenceTracker.iterateEsmReferences({
'$app/paths': {
[ReferenceTracker.ESM]: true,
base: {
[ReferenceTracker.READ]: true
}
}
})) {
if (node.type === 'ImportSpecifier') {
const variable = findVariable(context, node.local);
if (variable === null) {
continue;
}
for (const reference of variable.references) {
if (reference.identifier.type === 'Identifier') set.add(reference.identifier);
}
} else if (
node.type === 'MemberExpression' &&
node.property.type === 'Identifier' &&
node.property.name === 'base'
) {
set.add(node.property);
}
}
return set;
}
// Extract all references to goto, pushState and replaceState
function extractFunctionCallReferences(referenceTracker: ReferenceTracker): {
goto: TSESTree.CallExpression[];
pushState: TSESTree.CallExpression[];
replaceState: TSESTree.CallExpression[];
} {
const rawReferences = Array.from(
referenceTracker.iterateEsmReferences({
'$app/navigation': {
[ReferenceTracker.ESM]: true,
goto: {
[ReferenceTracker.CALL]: true
},
pushState: {
[ReferenceTracker.CALL]: true
},
replaceState: {
[ReferenceTracker.CALL]: true
}
}
})
);
return {
goto: rawReferences
.filter(({ path }) => path[path.length - 1] === 'goto')
.map(({ node }) => node),
pushState: rawReferences
.filter(({ path }) => path[path.length - 1] === 'pushState')
.map(({ node }) => node),
replaceState: rawReferences
.filter(({ path }) => path[path.length - 1] === 'replaceState')
.map(({ node }) => node)
};
}
// Actual function checking
function checkGotoCall(
context: RuleContext,
call: TSESTree.CallExpression,
basePathNames: Set<TSESTree.Identifier>
): void {
if (call.arguments.length < 1) {
return;
}
const url = call.arguments[0];
if (url.type === 'SpreadElement' || !expressionStartsWithBase(context, url, basePathNames)) {
context.report({ loc: url.loc, messageId: 'gotoNotPrefixed' });
}
}
function checkShallowNavigationCall(
context: RuleContext,
call: TSESTree.CallExpression,
basePathNames: Set<TSESTree.Identifier>,
messageId: string
): void {
if (call.arguments.length < 1) {
return;
}
const url = call.arguments[0];
if (
url.type === 'SpreadElement' ||
(!expressionIsEmpty(url) && !expressionStartsWithBase(context, url, basePathNames))
) {
context.report({ loc: url.loc, messageId });
}
}
// Helper functions
function expressionStartsWithBase(
context: RuleContext,
url: TSESTree.Expression,
basePathNames: Set<TSESTree.Identifier>
): boolean {
switch (url.type) {
case 'BinaryExpression':
return binaryExpressionStartsWithBase(context, url, basePathNames);
case 'Identifier':
return variableStartsWithBase(context, url, basePathNames);
case 'MemberExpression':
return memberExpressionStartsWithBase(url, basePathNames);
case 'TemplateLiteral':
return templateLiteralStartsWithBase(context, url, basePathNames);
default:
return false;
}
}
function binaryExpressionStartsWithBase(
context: RuleContext,
url: TSESTree.BinaryExpression,
basePathNames: Set<TSESTree.Identifier>
): boolean {
return (
url.left.type !== 'PrivateIdentifier' &&
expressionStartsWithBase(context, url.left, basePathNames)
);
}
function memberExpressionStartsWithBase(
url: TSESTree.MemberExpression,
basePathNames: Set<TSESTree.Identifier>
): boolean {
return url.property.type === 'Identifier' && basePathNames.has(url.property);
}
function variableStartsWithBase(
context: RuleContext,
url: TSESTree.Identifier,
basePathNames: Set<TSESTree.Identifier>
): boolean {
if (basePathNames.has(url)) {
return true;
}
const variable = findVariable(context, url);
if (
variable === null ||
variable.identifiers.length !== 1 ||
variable.identifiers[0].parent.type !== 'VariableDeclarator' ||
variable.identifiers[0].parent.init === null
) {
return false;
}
return expressionStartsWithBase(context, variable.identifiers[0].parent.init, basePathNames);
}
function templateLiteralStartsWithBase(
context: RuleContext,
url: TSESTree.TemplateLiteral,
basePathNames: Set<TSESTree.Identifier>
): boolean {
const startingIdentifier = extractLiteralStartingExpression(url);
return (
startingIdentifier !== undefined &&
expressionStartsWithBase(context, startingIdentifier, basePathNames)
);
}
function extractLiteralStartingExpression(
templateLiteral: TSESTree.TemplateLiteral
): TSESTree.Expression | undefined {
const literalParts = [...templateLiteral.expressions, ...templateLiteral.quasis].sort((a, b) =>
a.range[0] < b.range[0] ? -1 : 1
);
for (const part of literalParts) {
if (part.type === 'TemplateElement' && part.value.raw === '') {
// Skip empty quasi in the begining
continue;
}
if (part.type !== 'TemplateElement') {
return part;
}
return undefined;
}
return undefined;
}
function expressionIsEmpty(url: TSESTree.Expression): boolean {
return (
(url.type === 'Literal' && url.value === '') ||
(url.type === 'TemplateLiteral' &&
url.expressions.length === 0 &&
url.quasis.length === 1 &&
url.quasis[0].value.raw === '')
);
}
function expressionIsAbsolute(url: SvelteLiteral | TSESTree.Expression): boolean {
switch (url.type) {
case 'BinaryExpression':
return binaryExpressionIsAbsolute(url);
case 'Literal':
return typeof url.value === 'string' && urlValueIsAbsolute(url.value);
case 'SvelteLiteral':
return urlValueIsAbsolute(url.value);
case 'TemplateLiteral':
return templateLiteralIsAbsolute(url);
default:
return false;
}
}
function binaryExpressionIsAbsolute(url: TSESTree.BinaryExpression): boolean {
return (
(url.left.type !== 'PrivateIdentifier' && expressionIsAbsolute(url.left)) ||
expressionIsAbsolute(url.right)
);
}
function templateLiteralIsAbsolute(url: TSESTree.TemplateLiteral): boolean {
return (
url.expressions.some(expressionIsAbsolute) ||
url.quasis.some((quasi) => urlValueIsAbsolute(quasi.value.raw))
);
}
function urlValueIsAbsolute(url: string): boolean {
return url.includes('://');
}
function expressionIsFragment(url: SvelteLiteral | TSESTree.Expression): boolean {
switch (url.type) {
case 'BinaryExpression':
return binaryExpressionIsFragment(url);
case 'Literal':
return typeof url.value === 'string' && urlValueIsFragment(url.value);
case 'SvelteLiteral':
return urlValueIsFragment(url.value);
case 'TemplateLiteral':
return templateLiteralIsFragment(url);
default:
return false;
}
}
function binaryExpressionIsFragment(url: TSESTree.BinaryExpression): boolean {
return url.left.type !== 'PrivateIdentifier' && expressionIsFragment(url.left);
}
function templateLiteralIsFragment(url: TSESTree.TemplateLiteral): boolean {
return (
(url.expressions.length >= 1 && expressionIsFragment(url.expressions[0])) ||
(url.quasis.length >= 1 && urlValueIsFragment(url.quasis[0].value.raw))
);
}
function urlValueIsFragment(url: string): boolean {
return url.startsWith('#');
}