@markuplint/svelte-parser 4.7.0-alpha.0 → 4.7.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2017-2024 Yusuke Hirao
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/lib/index.d.ts ADDED
@@ -0,0 +1 @@
1
+ export { parser } from './parser.js';
package/lib/index.js ADDED
@@ -0,0 +1 @@
1
+ export { parser } from './parser.js';
@@ -0,0 +1,7 @@
1
+ import type { SvelteParser } from './parser.js';
2
+ import type { ChildToken, Token } from '@markuplint/parser-utils';
3
+ import type { SvelteBlock } from './svelte-parser/index.js';
4
+ export declare function parseBlock(parser: SvelteParser, token: ChildToken, originBlockNode: SvelteBlock): {
5
+ openToken: Token;
6
+ closeToken: Token;
7
+ };
@@ -0,0 +1,47 @@
1
+ export function parseBlock(
2
+ // eslint-disable-next-line @typescript-eslint/prefer-readonly-parameter-types
3
+ parser, token,
4
+ // eslint-disable-next-line @typescript-eslint/prefer-readonly-parameter-types
5
+ originBlockNode) {
6
+ const range = token.raw;
7
+ /**
8
+ * `{#xxx}...{:xxx}...{/xxx}`
9
+ * find___^
10
+ */
11
+ // eslint-disable-next-line regexp/strict
12
+ const eachCloseStartIndex = range.match(/{\s*\/[a-z]+\s*}$/)?.index;
13
+ if (eachCloseStartIndex == null) {
14
+ throw new SyntaxError('Block close tag not found');
15
+ }
16
+ /**
17
+ * `{/xxx}`
18
+ */
19
+ const closeToken = parser.sliceFragment(token.startOffset + eachCloseStartIndex, originBlockNode.end);
20
+ const fragment = originBlockNode.type === 'IfBlock'
21
+ ? originBlockNode.consequent.nodes
22
+ : originBlockNode.type === 'AwaitBlock'
23
+ ? originBlockNode.pending?.nodes
24
+ : originBlockNode.type === 'KeyBlock'
25
+ ? originBlockNode.fragment.nodes
26
+ : originBlockNode.body.nodes;
27
+ const fragStart = fragment?.at(0)?.start;
28
+ const fragEnd = fragment?.at(-1)?.end;
29
+ /**
30
+ * This token does not guarantee an open tag.
31
+ * For example, it might include `:then` or `:else`.
32
+ * Therefore, this variable is not used in
33
+ * `EachBlock` or `AwaitBlock`.
34
+ * It is only used in `KeyBlock` and `SnippetBlock`.
35
+ */
36
+ let openToken;
37
+ if (fragStart != null && fragEnd != null) {
38
+ openToken = parser.sliceFragment(token.startOffset, fragStart);
39
+ }
40
+ else {
41
+ openToken = parser.sliceFragment(token.startOffset, eachCloseStartIndex);
42
+ }
43
+ return {
44
+ openToken,
45
+ closeToken,
46
+ };
47
+ }
@@ -0,0 +1,61 @@
1
+ import type { SvelteNode } from './svelte-parser/index.js';
2
+ import type { MLASTParentNode, MLASTPreprocessorSpecificBlock, MLASTPreprocessorSpecificBlockConditionalType } from '@markuplint/ml-ast';
3
+ import type { ChildToken, ParseOptions, Token } from '@markuplint/parser-utils';
4
+ import { ParserError, Parser } from '@markuplint/parser-utils';
5
+ export declare class SvelteParser extends Parser<SvelteNode> {
6
+ #private;
7
+ readonly specificBindDirective: ReadonlySet<string>;
8
+ constructor();
9
+ tokenize(): {
10
+ ast: SvelteNode[];
11
+ isFragment: boolean;
12
+ };
13
+ parse(raw: string, options?: ParseOptions): import("@markuplint/ml-ast").MLASTDocument;
14
+ parseError(error: any): ParserError;
15
+ nodeize(originNode: SvelteNode, parentNode: MLASTParentNode | null, depth: number): readonly import("@markuplint/ml-ast").MLASTNodeTreeItem[];
16
+ visitPsBlock(token: ChildToken & {
17
+ readonly nodeName: string;
18
+ readonly isFragment: boolean;
19
+ }, childNodes?: readonly SvelteNode[], conditionalType?: MLASTPreprocessorSpecificBlockConditionalType): readonly [MLASTPreprocessorSpecificBlock];
20
+ visitChildren(children: readonly SvelteNode[], parentNode: MLASTParentNode | null): never[];
21
+ visitAttr(token: Token): (import("@markuplint/ml-ast").MLASTSpreadAttr & {
22
+ __rightText?: string;
23
+ }) | {
24
+ isDynamicValue: true | undefined;
25
+ isDirective: true | undefined;
26
+ isDuplicatable: boolean;
27
+ potentialName: string | undefined;
28
+ type: "attr";
29
+ nodeName: string;
30
+ spacesBeforeName: import("@markuplint/ml-ast").MLASTToken;
31
+ name: import("@markuplint/ml-ast").MLASTToken;
32
+ spacesBeforeEqual: import("@markuplint/ml-ast").MLASTToken;
33
+ equal: import("@markuplint/ml-ast").MLASTToken;
34
+ spacesAfterEqual: import("@markuplint/ml-ast").MLASTToken;
35
+ startQuote: import("@markuplint/ml-ast").MLASTToken;
36
+ value: import("@markuplint/ml-ast").MLASTToken;
37
+ endQuote: import("@markuplint/ml-ast").MLASTToken;
38
+ potentialValue?: string;
39
+ valueType?: "string" | "number" | "boolean" | "code";
40
+ candidate?: string;
41
+ uuid: string;
42
+ raw: string;
43
+ startOffset: number;
44
+ endOffset: number;
45
+ startLine: number;
46
+ endLine: number;
47
+ startCol: number;
48
+ endCol: number;
49
+ __rightText?: string;
50
+ };
51
+ /**
52
+ * > A lowercase tag, like `<div>`, denotes a regular HTML element.
53
+ * A capitalised tag, such as `<Widget>` or `<Namespace.Widget>`, indicates a component.
54
+ *
55
+ * @see https://svelte.io/docs/basic-markup#tags
56
+ * @param nodeName
57
+ * @returns
58
+ */
59
+ detectElementType(nodeName: string): import("@markuplint/ml-ast").ElementType;
60
+ }
61
+ export declare const parser: SvelteParser;
package/lib/parser.js ADDED
@@ -0,0 +1,501 @@
1
+ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
2
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
3
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
4
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
5
+ };
6
+ var _SvelteParser_instances, _SvelteParser_parseAwaitBlock, _SvelteParser_parseEachBlock, _SvelteParser_traverseIfBlock;
7
+ import { getNamespace } from '@markuplint/html-parser';
8
+ import { ParserError, Parser, AttrState } from '@markuplint/parser-utils';
9
+ import { parseBlock } from './parse-block.js';
10
+ import { svelteParse } from './svelte-parser/index.js';
11
+ export class SvelteParser extends Parser {
12
+ constructor() {
13
+ super({
14
+ endTagType: 'xml',
15
+ tagNameCaseSensitive: true,
16
+ ignoreTags: [
17
+ {
18
+ type: 'Script',
19
+ start: '<script',
20
+ end: '</script>',
21
+ },
22
+ {
23
+ type: 'Style',
24
+ start: '<style',
25
+ end: '</style>',
26
+ },
27
+ ],
28
+ maskChar: '-',
29
+ });
30
+ _SvelteParser_instances.add(this);
31
+ this.specificBindDirective = new Set(['group', 'this']);
32
+ }
33
+ tokenize() {
34
+ return {
35
+ ast: svelteParse(this.rawCode),
36
+ isFragment: true,
37
+ };
38
+ }
39
+ parse(raw, options) {
40
+ return super.parse(raw, {
41
+ ...options,
42
+ ignoreFrontMatter: false,
43
+ });
44
+ }
45
+ parseError(error) {
46
+ if (error instanceof Error && 'start' in error && 'end' in error && 'frame' in error) {
47
+ // @ts-ignore
48
+ const token = this.sliceFragment(error.start.character, error.end.character);
49
+ throw new ParserError(error.message + '\n' + error.frame, token);
50
+ }
51
+ return super.parseError(error);
52
+ }
53
+ nodeize(
54
+ // eslint-disable-next-line @typescript-eslint/prefer-readonly-parameter-types
55
+ originNode, parentNode, depth) {
56
+ const token = this.sliceFragment(originNode.start, originNode.end);
57
+ const parentNamespace = parentNode && 'namespace' in parentNode ? parentNode.namespace : 'http://www.w3.org/1999/xhtml';
58
+ switch (originNode.type) {
59
+ case 'Text': {
60
+ return this.visitText({
61
+ ...token,
62
+ depth,
63
+ parentNode,
64
+ });
65
+ }
66
+ case 'Comment': {
67
+ return this.visitComment({
68
+ ...token,
69
+ depth,
70
+ parentNode,
71
+ });
72
+ }
73
+ case 'ExpressionTag': {
74
+ return this.visitPsBlock({
75
+ ...token,
76
+ depth,
77
+ parentNode,
78
+ nodeName: 'ExpressionTag',
79
+ isFragment: false,
80
+ });
81
+ }
82
+ case 'Component':
83
+ case 'RegularElement': {
84
+ const children = originNode.fragment.nodes ?? [];
85
+ const reEndTag = new RegExp(`</${originNode.name}\\s*>$`, 'i');
86
+ const startTagEndOffset = children.length > 0
87
+ ? (children[0]?.start ?? 0)
88
+ : token.raw.replace(reEndTag, '').length + token.startOffset;
89
+ const startTagLocation = this.sliceFragment(token.startOffset, startTagEndOffset);
90
+ return this.visitElement({
91
+ ...startTagLocation,
92
+ depth,
93
+ parentNode,
94
+ nodeName: originNode.name,
95
+ namespace: getNamespace(originNode.name, parentNamespace),
96
+ }, originNode.fragment.nodes, {
97
+ createEndTagToken: () => {
98
+ if (!reEndTag.test(token.raw)) {
99
+ return null;
100
+ }
101
+ const endTagRawMatched = token.raw.match(reEndTag);
102
+ if (!endTagRawMatched) {
103
+ throw new Error('Parse error');
104
+ }
105
+ const endTagRaw = endTagRawMatched[0];
106
+ const endTagStartOffset = token.startOffset + token.raw.lastIndexOf(endTagRaw);
107
+ const endTagEndOffset = endTagStartOffset + endTagRaw.length;
108
+ const endTagLocation = this.sliceFragment(endTagStartOffset, endTagEndOffset);
109
+ return {
110
+ ...endTagLocation,
111
+ depth,
112
+ parentNode,
113
+ };
114
+ },
115
+ });
116
+ }
117
+ case 'IfBlock': {
118
+ const expressions = [];
119
+ const ifElseBlocks = __classPrivateFieldGet(this, _SvelteParser_instances, "m", _SvelteParser_traverseIfBlock).call(this, originNode, token.startOffset);
120
+ for (const ifElseBlock of ifElseBlocks) {
121
+ const expression = this.visitPsBlock({
122
+ ...ifElseBlock,
123
+ depth,
124
+ parentNode,
125
+ nodeName: ifElseBlock.type,
126
+ isFragment: false,
127
+ }, ifElseBlock.children, {
128
+ if: 'if',
129
+ elseif: 'if:elseif',
130
+ else: 'if:else',
131
+ '/if': 'end',
132
+ }[ifElseBlock.type])[0];
133
+ expressions.push(expression);
134
+ }
135
+ return expressions;
136
+ }
137
+ case 'EachBlock': {
138
+ return __classPrivateFieldGet(this, _SvelteParser_instances, "m", _SvelteParser_parseEachBlock).call(this, {
139
+ ...token,
140
+ depth,
141
+ parentNode,
142
+ }, originNode);
143
+ }
144
+ case 'AwaitBlock': {
145
+ return __classPrivateFieldGet(this, _SvelteParser_instances, "m", _SvelteParser_parseAwaitBlock).call(this, {
146
+ ...token,
147
+ depth,
148
+ parentNode,
149
+ }, originNode);
150
+ }
151
+ case 'KeyBlock': {
152
+ const { openToken, closeToken } = parseBlock(this, {
153
+ ...token,
154
+ depth,
155
+ parentNode,
156
+ }, originNode);
157
+ return [
158
+ this.visitPsBlock({
159
+ ...openToken,
160
+ depth,
161
+ parentNode,
162
+ nodeName: 'key',
163
+ isFragment: true,
164
+ }, originNode.fragment.nodes)[0],
165
+ this.visitPsBlock({
166
+ ...closeToken,
167
+ depth,
168
+ parentNode,
169
+ nodeName: '/key',
170
+ isFragment: true,
171
+ })[0],
172
+ ];
173
+ }
174
+ case 'SnippetBlock': {
175
+ const { openToken, closeToken } = parseBlock(this, {
176
+ ...token,
177
+ depth,
178
+ parentNode,
179
+ }, originNode);
180
+ return [
181
+ this.visitPsBlock({
182
+ ...openToken,
183
+ depth,
184
+ parentNode,
185
+ nodeName: 'snippet',
186
+ isFragment: false,
187
+ }, originNode.body.nodes)[0],
188
+ this.visitPsBlock({
189
+ ...closeToken,
190
+ depth,
191
+ parentNode,
192
+ nodeName: '/snippet',
193
+ isFragment: false,
194
+ })[0],
195
+ ];
196
+ }
197
+ default: {
198
+ const childNodes = 'fragment' in originNode ? originNode.fragment.nodes : [];
199
+ return this.visitPsBlock({
200
+ ...token,
201
+ depth,
202
+ parentNode,
203
+ nodeName: originNode.type,
204
+ isFragment: true,
205
+ }, childNodes);
206
+ }
207
+ }
208
+ }
209
+ visitPsBlock(token, childNodes = [], conditionalType = null) {
210
+ const nodes = super.visitPsBlock(token, childNodes, conditionalType);
211
+ const block = nodes.at(0);
212
+ if (!block || block.type !== 'psblock') {
213
+ throw new ParserError('Parse error', token);
214
+ }
215
+ if (nodes.length > 1) {
216
+ throw new ParserError('Parse error', nodes.at(1));
217
+ }
218
+ return [block];
219
+ }
220
+ visitChildren(
221
+ // eslint-disable-next-line @typescript-eslint/prefer-readonly-parameter-types
222
+ children, parentNode) {
223
+ const siblings = super.visitChildren(children, parentNode);
224
+ if (siblings.length > 0) {
225
+ throw new ParserError('Discovered child nodes with differing hierarchy levels', siblings[0]);
226
+ }
227
+ return [];
228
+ }
229
+ visitAttr(token) {
230
+ const attr = super.visitAttr(token, {
231
+ quoteSet: [
232
+ { start: '"', end: '"', type: 'string' },
233
+ { start: "'", end: "'", type: 'string' },
234
+ { start: '{', end: '}', type: 'script' },
235
+ ],
236
+ startState:
237
+ // is shorthand attribute
238
+ token.raw.trim().startsWith('{') ? AttrState.BeforeValue : AttrState.BeforeName,
239
+ });
240
+ if (attr.type === 'spread') {
241
+ return attr;
242
+ }
243
+ let isDynamicValue = attr.startQuote.raw === '{' || undefined;
244
+ let potentialName;
245
+ let isDirective;
246
+ let isDuplicatable = false;
247
+ if (isDynamicValue && attr.name.raw === '') {
248
+ potentialName = attr.value.raw;
249
+ }
250
+ const [baseName, subName] = attr.name.raw.split(':');
251
+ if (subName) {
252
+ isDirective = true;
253
+ if (baseName === 'bind' && !this.specificBindDirective.has(subName)) {
254
+ potentialName = subName;
255
+ isDirective = undefined;
256
+ isDynamicValue = true;
257
+ }
258
+ }
259
+ if (baseName?.toLowerCase() === 'class') {
260
+ isDuplicatable = true;
261
+ if (subName) {
262
+ potentialName = 'class';
263
+ isDynamicValue = true;
264
+ }
265
+ }
266
+ if (attr.startQuote.raw === '{' && attr.endQuote.raw === '}') {
267
+ isDynamicValue = true;
268
+ }
269
+ return {
270
+ ...attr,
271
+ isDynamicValue,
272
+ isDirective,
273
+ isDuplicatable,
274
+ potentialName,
275
+ };
276
+ }
277
+ /**
278
+ * > A lowercase tag, like `<div>`, denotes a regular HTML element.
279
+ * A capitalised tag, such as `<Widget>` or `<Namespace.Widget>`, indicates a component.
280
+ *
281
+ * @see https://svelte.io/docs/basic-markup#tags
282
+ * @param nodeName
283
+ * @returns
284
+ */
285
+ detectElementType(nodeName) {
286
+ return super.detectElementType(nodeName, /^[A-Z]|\./);
287
+ }
288
+ }
289
+ _SvelteParser_instances = new WeakSet(), _SvelteParser_parseAwaitBlock = function _SvelteParser_parseAwaitBlock(token,
290
+ // eslint-disable-next-line @typescript-eslint/prefer-readonly-parameter-types
291
+ originBlockNode) {
292
+ const { closeToken } = parseBlock(this, token, originBlockNode);
293
+ const pendingNodes = originBlockNode.pending?.nodes ?? [];
294
+ const thenNodes = originBlockNode.then?.nodes ?? [];
295
+ const pendingEnd = pendingNodes.at(-1)?.end;
296
+ const thenEnd = thenNodes.at(-1)?.end;
297
+ // @ts-ignore - new Svelte Compiler Type doesn't support `start` and `end` yet.
298
+ const awaitConditionEnd = originBlockNode.expression.end;
299
+ /**
300
+ * `{#await expression}...{:then name}...{:catch name}...{/await}`
301
+ * find___^ and cut
302
+ *
303
+ * `}...{:then name}...{:catch name}...{/await}`
304
+ */
305
+ const rawAwaitConditionBelow = this.rawCode.slice(awaitConditionEnd, originBlockNode.end);
306
+ /**
307
+ * `}...{:then name}...{:catch name}...{/await}`
308
+ * ^___find
309
+ */
310
+ const awaitExpEnd = awaitConditionEnd + rawAwaitConditionBelow.indexOf('}') + 1;
311
+ /**
312
+ * `{#await expression}`
313
+ */
314
+ const awaitExpToken = this.sliceFragment(token.startOffset, awaitExpEnd);
315
+ let thenToken = null;
316
+ /**
317
+ * `{#await expression}...{:then name}...{:catch name}...{/await}`
318
+ * find___^
319
+ */
320
+ const thenExpStart = pendingEnd ?? awaitExpEnd;
321
+ /**
322
+ * `{:then name}...{:catch name}...{/await}`
323
+ */
324
+ const rawPendingNodesBelow = this.rawCode.slice(thenExpStart, originBlockNode.end);
325
+ if (
326
+ // eslint-disable-next-line regexp/strict
327
+ /^{\s*:then[\s|}]/.test(rawPendingNodesBelow)) {
328
+ let thenExpEndCharOffset;
329
+ if (originBlockNode.value) {
330
+ const thenIdentifierEnd =
331
+ // @ts-ignore - new Svelte Compiler Type doesn't support `start` and `end` yet.
332
+ originBlockNode.value.end;
333
+ const rawThenExpCloseCharAndBelow = this.rawCode.slice(thenIdentifierEnd, originBlockNode.end);
334
+ const thenExpEndCharIndex = rawThenExpCloseCharAndBelow.indexOf('}') + 1;
335
+ thenExpEndCharOffset = thenIdentifierEnd + thenExpEndCharIndex;
336
+ }
337
+ else {
338
+ thenExpEndCharOffset = thenExpStart + rawPendingNodesBelow.indexOf('}') + 1;
339
+ }
340
+ thenToken = this.sliceFragment(token.startOffset + thenExpStart, thenExpEndCharOffset);
341
+ }
342
+ let catchToken = null;
343
+ /**
344
+ * `{#await expression}...{:then name}...{:catch name}...{/await}`
345
+ * find___^
346
+ *
347
+ * If `then` block is not found:
348
+ *
349
+ * `{#await expression}...{:catch name}...{/await}`
350
+ * find___^
351
+ */
352
+ const catchExpStart = thenToken
353
+ ? (thenEnd ?? thenToken.startOffset + thenToken.raw.length)
354
+ : (pendingEnd ?? awaitExpEnd);
355
+ /**
356
+ * `{:catch name}...{/await}`
357
+ */
358
+ const rawThenNodesBelow = this.rawCode.slice(catchExpStart, originBlockNode.end);
359
+ if (
360
+ // eslint-disable-next-line regexp/strict
361
+ /^{\s*:catch[\s|}]/.test(rawThenNodesBelow)) {
362
+ let catchExpEndCharOffset;
363
+ if (originBlockNode.error) {
364
+ const catchIdentifierEnd =
365
+ // @ts-ignore - new Svelte Compiler Type doesn't support `start` and `end` yet.
366
+ originBlockNode.error.end;
367
+ const rawCatchExpCloseCharAndBelow = this.rawCode.slice(catchIdentifierEnd, originBlockNode.end);
368
+ const catchExpEndCharIndex = rawCatchExpCloseCharAndBelow.indexOf('}') + 1;
369
+ catchExpEndCharOffset = catchIdentifierEnd + catchExpEndCharIndex;
370
+ }
371
+ else {
372
+ catchExpEndCharOffset = catchExpStart + rawThenNodesBelow.indexOf('}') + 1;
373
+ }
374
+ catchToken = this.sliceFragment(token.startOffset + catchExpStart, catchExpEndCharOffset);
375
+ }
376
+ const expressions = [];
377
+ expressions.push(this.visitPsBlock({
378
+ ...awaitExpToken,
379
+ depth: token.depth,
380
+ parentNode: token.parentNode,
381
+ nodeName: 'await',
382
+ isFragment: false,
383
+ }, originBlockNode.pending?.nodes, 'await')[0]);
384
+ if (thenToken) {
385
+ expressions.push(this.visitPsBlock({
386
+ ...thenToken,
387
+ depth: token.depth,
388
+ parentNode: token.parentNode,
389
+ nodeName: 'await:then',
390
+ isFragment: false,
391
+ }, originBlockNode.then?.nodes, 'await:then')[0]);
392
+ }
393
+ if (catchToken) {
394
+ expressions.push(this.visitPsBlock({
395
+ ...catchToken,
396
+ depth: token.depth,
397
+ parentNode: token.parentNode,
398
+ nodeName: 'await:catch',
399
+ isFragment: false,
400
+ }, originBlockNode.catch?.nodes, 'await:catch')[0]);
401
+ }
402
+ expressions.push(this.visitPsBlock({
403
+ ...closeToken,
404
+ depth: token.depth,
405
+ parentNode: token.parentNode,
406
+ nodeName: '/await',
407
+ isFragment: false,
408
+ }, undefined, 'end')[0]);
409
+ return expressions;
410
+ }, _SvelteParser_parseEachBlock = function _SvelteParser_parseEachBlock(token,
411
+ // eslint-disable-next-line @typescript-eslint/prefer-readonly-parameter-types
412
+ originBlockNode) {
413
+ const expressions = [];
414
+ /**
415
+ * `{/each}`
416
+ */
417
+ const { closeToken } = parseBlock(this, token, originBlockNode);
418
+ /**
419
+ * `{#each expression as name}...{:else}...{/each}`
420
+ * find___^
421
+ */
422
+ const bodyStart = originBlockNode.body.nodes.at(0)?.start ?? closeToken.startOffset;
423
+ /**
424
+ * `{#each expression as name}...{:else}...{/each}`
425
+ * find___^
426
+ */
427
+ const fallbackScopeStart = originBlockNode.fallback?.nodes.at(0)?.start ?? closeToken.startOffset;
428
+ /**
429
+ * `{#each expression as name}...{:else}`
430
+ */
431
+ const rawUntilFallbackScope = this.rawCode.slice(token.startOffset, fallbackScopeStart);
432
+ let elseToken = null;
433
+ /**
434
+ * `{#each expression as name}...{:else}`
435
+ * find___^
436
+ */
437
+ // eslint-disable-next-line regexp/strict
438
+ const elseTokenStart = rawUntilFallbackScope.match(/{\s*:else\s*}$/)?.index;
439
+ if (elseTokenStart != null) {
440
+ elseToken = this.sliceFragment(token.startOffset + elseTokenStart, fallbackScopeStart);
441
+ }
442
+ const eachToken = this.sliceFragment(token.startOffset, bodyStart);
443
+ expressions.push(this.visitPsBlock({
444
+ ...eachToken,
445
+ depth: token.depth,
446
+ parentNode: token.parentNode,
447
+ nodeName: 'each',
448
+ isFragment: false,
449
+ }, originBlockNode.body.nodes, 'each')[0]);
450
+ if (elseToken) {
451
+ expressions.push(this.visitPsBlock({
452
+ ...elseToken,
453
+ depth: token.depth,
454
+ parentNode: token.parentNode,
455
+ nodeName: 'each:empty',
456
+ isFragment: false,
457
+ }, originBlockNode.fallback?.nodes, 'each:empty')[0]);
458
+ }
459
+ expressions.push(this.visitPsBlock({
460
+ ...closeToken,
461
+ depth: token.depth,
462
+ parentNode: token.parentNode,
463
+ nodeName: '/each',
464
+ isFragment: false,
465
+ }, undefined, 'end')[0]);
466
+ return expressions;
467
+ }, _SvelteParser_traverseIfBlock = function _SvelteParser_traverseIfBlock(
468
+ // eslint-disable-next-line @typescript-eslint/prefer-readonly-parameter-types
469
+ originBlockNode, start, type = 'if') {
470
+ const result = [];
471
+ const end = originBlockNode.consequent.nodes?.[0]?.start ?? originBlockNode.end;
472
+ const tag = this.sliceFragment(start, end);
473
+ const children = originBlockNode.consequent.nodes;
474
+ result.push({ ...tag, children, type });
475
+ if (originBlockNode.alternate) {
476
+ if (originBlockNode.alternate.nodes?.[0]?.type === 'IfBlock') {
477
+ const elseif = __classPrivateFieldGet(this, _SvelteParser_instances, "m", _SvelteParser_traverseIfBlock).call(this, originBlockNode.alternate.nodes[0], children.at(-1)?.end ?? start, 'elseif');
478
+ result.push(...elseif);
479
+ }
480
+ else {
481
+ const start = children.at(-1)?.end ?? originBlockNode.end;
482
+ const end = originBlockNode.alternate.nodes?.[0]?.start;
483
+ const tag = this.sliceFragment(start, end);
484
+ result.push({
485
+ ...tag,
486
+ children: originBlockNode.alternate.nodes,
487
+ type: 'else',
488
+ });
489
+ }
490
+ }
491
+ {
492
+ const start = result.at(-1)?.children.at(-1)?.end ?? originBlockNode.end;
493
+ const end = originBlockNode.end;
494
+ const tag = this.sliceFragment(start, end);
495
+ if (tag.raw) {
496
+ result.push({ ...tag, children: [], type: '/if' });
497
+ }
498
+ }
499
+ return result;
500
+ };
501
+ export const parser = new SvelteParser();
@@ -0,0 +1,12 @@
1
+ import type { AST } from 'svelte/compiler';
2
+ export type SvelteNode = AST.Text | Tag | ElementLike | AST.Comment | SvelteBlock;
3
+ export type SvelteIfBlock = AST.IfBlock;
4
+ export type SvelteEachBlock = AST.EachBlock;
5
+ export type SvelteAwaitBlock = AST.AwaitBlock;
6
+ export declare function svelteParse(template: string): SvelteNode[];
7
+ export type SvelteDirective = Directive | AST.Attribute | AST.SpreadAttribute;
8
+ export type SvelteBlock = AST.EachBlock | AST.IfBlock | AST.AwaitBlock | AST.KeyBlock | AST.SnippetBlock;
9
+ type Tag = AST.ExpressionTag | AST.HtmlTag | AST.ConstTag | AST.DebugTag | AST.RenderTag;
10
+ type Directive = AST.AnimateDirective | AST.BindDirective | AST.ClassDirective | AST.LetDirective | AST.OnDirective | AST.StyleDirective | AST.TransitionDirective | AST.UseDirective;
11
+ type ElementLike = AST.Component | AST.TitleElement | AST.SlotElement | AST.RegularElement | AST.SvelteBody | AST.SvelteComponent | AST.SvelteDocument | AST.SvelteElement | AST.SvelteFragment | AST.SvelteHead | AST.SvelteOptionsRaw | AST.SvelteSelf | AST.SvelteWindow;
12
+ export {};
@@ -0,0 +1,5 @@
1
+ import { parse } from 'svelte/compiler';
2
+ export function svelteParse(template) {
3
+ const ast = parse(template, { modern: true });
4
+ return ast.fragment.nodes ?? [];
5
+ }
@@ -0,0 +1,6 @@
1
+ import { HtmlParser } from '@markuplint/html-parser';
2
+ declare class SvelteKitTemplateParser extends HtmlParser {
3
+ constructor();
4
+ }
5
+ export declare const parser: SvelteKitTemplateParser;
6
+ export {};
@@ -0,0 +1,15 @@
1
+ import { HtmlParser } from '@markuplint/html-parser';
2
+ class SvelteKitTemplateParser extends HtmlParser {
3
+ constructor() {
4
+ super({
5
+ ignoreTags: [
6
+ {
7
+ type: 'sveltekit-placeholder',
8
+ start: '%sveltekit.',
9
+ end: '%',
10
+ },
11
+ ],
12
+ });
13
+ }
14
+ }
15
+ export const parser = new SvelteKitTemplateParser();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@markuplint/svelte-parser",
3
- "version": "4.7.0-alpha.0",
3
+ "version": "4.7.0",
4
4
  "description": "Svelte parser for markuplint",
5
5
  "repository": "git@github.com:markuplint/markuplint.git",
6
6
  "author": "Yusuke Hirao <yusukehirao@me.com>",
@@ -9,13 +9,18 @@
9
9
  "type": "module",
10
10
  "exports": {
11
11
  ".": {
12
- "import": "./lib/index.js"
12
+ "import": "./lib/index.js",
13
+ "types": "./lib/index.d.ts"
13
14
  },
14
15
  "./kit": {
15
- "import": "./lib/sveltekit-parser.js"
16
+ "import": "./lib/sveltekit-parser.js",
17
+ "types": "./lib/sveltekit-parser.d.ts"
16
18
  }
17
19
  },
18
20
  "types": "lib/index.d.ts",
21
+ "files": [
22
+ "lib"
23
+ ],
19
24
  "publishConfig": {
20
25
  "access": "public"
21
26
  },
@@ -24,9 +29,10 @@
24
29
  "clean": "tsc --build --clean"
25
30
  },
26
31
  "dependencies": {
27
- "@markuplint/html-parser": "4.6.2",
28
- "@markuplint/ml-ast": "4.3.1",
29
- "@markuplint/parser-utils": "4.6.2",
30
- "svelte": "next"
31
- }
32
+ "@markuplint/html-parser": "4.6.10",
33
+ "@markuplint/ml-ast": "4.4.7",
34
+ "@markuplint/parser-utils": "4.7.1",
35
+ "svelte": "5.1.3"
36
+ },
37
+ "gitHead": "fab5b494f0bdc491aa83cb2c8722738d557fbefd"
32
38
  }
package/CHANGELOG.md DELETED
@@ -1,16 +0,0 @@
1
- # Change Log
2
-
3
- All notable changes to this project will be documented in this file.
4
- See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
5
-
6
- ## [4.6.2](https://github.com/markuplint/markuplint/compare/@markuplint/svelte-parser@4.6.1...@markuplint/svelte-parser@4.6.2) (2024-05-12)
7
-
8
- **Note:** Version bump only for package @markuplint/svelte-parser
9
-
10
- ## [4.6.1](https://github.com/markuplint/markuplint/compare/@markuplint/svelte-parser@4.6.1-alpha.0...@markuplint/svelte-parser@4.6.1) (2024-05-04)
11
-
12
- **Note:** Version bump only for package @markuplint/svelte-parser
13
-
14
- ## [4.6.1-alpha.0](https://github.com/markuplint/markuplint/compare/@markuplint/svelte-parser@4.6.0...@markuplint/svelte-parser@4.6.1-alpha.0) (2024-05-04)
15
-
16
- **Note:** Version bump only for package @markuplint/svelte-parser