@markuplint/svelte-parser 4.6.1 → 4.7.0-alpha.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/CHANGELOG.md CHANGED
@@ -3,6 +3,10 @@
3
3
  All notable changes to this project will be documented in this file.
4
4
  See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
5
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
+
6
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)
7
11
 
8
12
  **Note:** Version bump only for package @markuplint/svelte-parser
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@markuplint/svelte-parser",
3
- "version": "4.6.1",
3
+ "version": "4.7.0-alpha.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>",
@@ -24,10 +24,9 @@
24
24
  "clean": "tsc --build --clean"
25
25
  },
26
26
  "dependencies": {
27
- "@markuplint/html-parser": "4.6.1",
27
+ "@markuplint/html-parser": "4.6.2",
28
28
  "@markuplint/ml-ast": "4.3.1",
29
- "@markuplint/parser-utils": "4.6.1",
30
- "svelte": "4.2.15"
31
- },
32
- "gitHead": "7a5967fce14fdf66f0d8eae9d93ae5b350648d3d"
29
+ "@markuplint/parser-utils": "4.6.2",
30
+ "svelte": "next"
31
+ }
33
32
  }
package/LICENSE DELETED
@@ -1,21 +0,0 @@
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 DELETED
@@ -1 +0,0 @@
1
- export { parser } from './parser.js';
package/lib/index.js DELETED
@@ -1 +0,0 @@
1
- export { parser } from './parser.js';
package/lib/parser.d.ts DELETED
@@ -1,63 +0,0 @@
1
- /// <reference types="svelte" />
2
- import type { SvelteNode } from './svelte-parser/index.js';
3
- import type { MLASTParentNode, MLASTPreprocessorSpecificBlock, MLASTPreprocessorSpecificBlockConditionalType } from '@markuplint/ml-ast';
4
- import type { ChildToken, ParseOptions, Token } from '@markuplint/parser-utils';
5
- import { ParserError, Parser } from '@markuplint/parser-utils';
6
- declare class SvelteParser extends Parser<SvelteNode> {
7
- #private;
8
- readonly specificBindDirective: ReadonlySet<string>;
9
- constructor();
10
- tokenize(): {
11
- ast: import("svelte/types/compiler/interfaces").TemplateNode[];
12
- isFragment: boolean;
13
- };
14
- parse(raw: string, options?: ParseOptions): import("@markuplint/ml-ast").MLASTDocument;
15
- parseError(error: any): ParserError;
16
- nodeize(originNode: SvelteNode, parentNode: MLASTParentNode | null, depth: number): readonly import("@markuplint/ml-ast").MLASTNodeTreeItem[];
17
- visitPsBlock(token: ChildToken & {
18
- readonly nodeName: string;
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 | undefined;
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 | undefined;
39
- valueType?: "string" | "number" | "boolean" | "code" | undefined;
40
- candidate?: string | undefined;
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 | undefined;
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
- visitExpression(token: ChildToken, originBlockNode: SvelteNode): MLASTPreprocessorSpecificBlock[];
61
- }
62
- export declare const parser: SvelteParser;
63
- export {};
package/lib/parser.js DELETED
@@ -1,344 +0,0 @@
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_traverseIfBlock;
7
- import { getNamespace } from '@markuplint/html-parser';
8
- import { ParserError, Parser, AttrState } from '@markuplint/parser-utils';
9
- import { svelteParse } from './svelte-parser/index.js';
10
- class SvelteParser extends Parser {
11
- constructor() {
12
- super({
13
- endTagType: 'xml',
14
- tagNameCaseSensitive: true,
15
- ignoreTags: [
16
- {
17
- type: 'Script',
18
- start: '<script',
19
- end: '</script>',
20
- },
21
- {
22
- type: 'Style',
23
- start: '<style',
24
- end: '</style>',
25
- },
26
- ],
27
- maskChar: '-',
28
- });
29
- _SvelteParser_instances.add(this);
30
- this.specificBindDirective = new Set(['group', 'this']);
31
- }
32
- tokenize() {
33
- return {
34
- ast: svelteParse(this.rawCode),
35
- isFragment: true,
36
- };
37
- }
38
- parse(raw, options) {
39
- return super.parse(raw, {
40
- ...options,
41
- ignoreFrontMatter: false,
42
- });
43
- }
44
- parseError(error) {
45
- if (error instanceof Error && 'start' in error && 'end' in error && 'frame' in error) {
46
- // @ts-ignore
47
- const token = this.sliceFragment(error.start.character, error.end.character);
48
- throw new ParserError(error.message + '\n' + error.frame, token);
49
- }
50
- return super.parseError(error);
51
- }
52
- nodeize(
53
- // eslint-disable-next-line @typescript-eslint/prefer-readonly-parameter-types
54
- originNode, parentNode, depth) {
55
- const token = this.sliceFragment(originNode.start, originNode.end);
56
- const parentNamespace = parentNode && 'namespace' in parentNode ? parentNode.namespace : 'http://www.w3.org/1999/xhtml';
57
- switch (originNode.type) {
58
- case 'Text': {
59
- return this.visitText({
60
- ...token,
61
- depth,
62
- parentNode,
63
- });
64
- }
65
- case 'Comment': {
66
- return this.visitComment({
67
- ...token,
68
- depth,
69
- parentNode,
70
- });
71
- }
72
- case 'MustacheTag': {
73
- return this.visitPsBlock({
74
- ...token,
75
- depth,
76
- parentNode,
77
- nodeName: 'MustacheTag',
78
- });
79
- }
80
- case 'InlineComponent':
81
- case 'Element': {
82
- const children = originNode.children ?? [];
83
- const reEndTag = new RegExp(`</${originNode.name}\\s*>$`, 'i');
84
- const startTagEndOffset = children.length > 0
85
- ? children[0]?.start ?? 0
86
- : token.raw.replace(reEndTag, '').length + token.startOffset;
87
- const startTagLocation = this.sliceFragment(token.startOffset, startTagEndOffset);
88
- return this.visitElement({
89
- ...startTagLocation,
90
- depth,
91
- parentNode,
92
- nodeName: originNode.name,
93
- namespace: getNamespace(originNode.name, parentNamespace),
94
- }, originNode.children, {
95
- createEndTagToken: () => {
96
- if (!reEndTag.test(token.raw)) {
97
- return null;
98
- }
99
- const endTagRawMatched = token.raw.match(reEndTag);
100
- if (!endTagRawMatched) {
101
- throw new Error('Parse error');
102
- }
103
- const endTagRaw = endTagRawMatched[0];
104
- const endTagStartOffset = token.startOffset + token.raw.lastIndexOf(endTagRaw);
105
- const endTagEndOffset = endTagStartOffset + endTagRaw.length;
106
- const endTagLocation = this.sliceFragment(endTagStartOffset, endTagEndOffset);
107
- return {
108
- ...endTagLocation,
109
- depth,
110
- parentNode,
111
- };
112
- },
113
- });
114
- }
115
- default: {
116
- return this.visitExpression({
117
- ...token,
118
- depth,
119
- parentNode,
120
- }, originNode);
121
- }
122
- }
123
- }
124
- visitPsBlock(token, childNodes = [], conditionalType = null) {
125
- const nodes = super.visitPsBlock(token, childNodes, conditionalType);
126
- const block = nodes.at(0);
127
- if (!block || block.type !== 'psblock') {
128
- throw new ParserError('Parse error', token);
129
- }
130
- if (nodes.length > 1) {
131
- throw new ParserError('Parse error', nodes.at(1));
132
- }
133
- return [block];
134
- }
135
- visitChildren(
136
- // eslint-disable-next-line @typescript-eslint/prefer-readonly-parameter-types
137
- children, parentNode) {
138
- const siblings = super.visitChildren(children, parentNode);
139
- if (siblings.length > 0) {
140
- throw new ParserError('Discovered child nodes with differing hierarchy levels', siblings[0]);
141
- }
142
- return [];
143
- }
144
- visitAttr(token) {
145
- const attr = super.visitAttr(token, {
146
- quoteSet: [
147
- { start: '"', end: '"', type: 'string' },
148
- { start: "'", end: "'", type: 'string' },
149
- { start: '{', end: '}', type: 'script' },
150
- ],
151
- startState:
152
- // is shorthand attribute
153
- token.raw.trim().startsWith('{') ? AttrState.BeforeValue : AttrState.BeforeName,
154
- });
155
- if (attr.type === 'spread') {
156
- return attr;
157
- }
158
- let isDynamicValue = attr.startQuote.raw === '{' || undefined;
159
- let potentialName;
160
- let isDirective;
161
- let isDuplicatable = false;
162
- if (isDynamicValue && attr.name.raw === '') {
163
- potentialName = attr.value.raw;
164
- }
165
- const [baseName, subName] = attr.name.raw.split(':');
166
- if (subName) {
167
- isDirective = true;
168
- if (baseName === 'bind' && !this.specificBindDirective.has(subName)) {
169
- potentialName = subName;
170
- isDirective = undefined;
171
- isDynamicValue = true;
172
- }
173
- }
174
- if (baseName?.toLowerCase() === 'class') {
175
- isDuplicatable = true;
176
- if (subName) {
177
- potentialName = 'class';
178
- isDynamicValue = true;
179
- }
180
- }
181
- if (attr.startQuote.raw === '{' && attr.endQuote.raw === '}') {
182
- isDynamicValue = true;
183
- }
184
- return {
185
- ...attr,
186
- isDynamicValue,
187
- isDirective,
188
- isDuplicatable,
189
- potentialName,
190
- };
191
- }
192
- /**
193
- * > A lowercase tag, like `<div>`, denotes a regular HTML element.
194
- * A capitalised tag, such as `<Widget>` or `<Namespace.Widget>`, indicates a component.
195
- *
196
- * @see https://svelte.io/docs/basic-markup#tags
197
- * @param nodeName
198
- * @returns
199
- */
200
- detectElementType(nodeName) {
201
- return super.detectElementType(nodeName, /^[A-Z]|\./);
202
- }
203
- visitExpression(token,
204
- // eslint-disable-next-line @typescript-eslint/prefer-readonly-parameter-types
205
- originBlockNode) {
206
- const props = ['', 'else', 'pending', 'then', 'catch'];
207
- const expressions = [];
208
- if (originBlockNode.type === 'IfBlock') {
209
- const ifElseBlocks = __classPrivateFieldGet(this, _SvelteParser_instances, "m", _SvelteParser_traverseIfBlock).call(this, originBlockNode);
210
- for (const ifElseBlock of ifElseBlocks) {
211
- const expression = this.visitPsBlock({
212
- ...ifElseBlock,
213
- depth: token.depth,
214
- parentNode: token.parentNode,
215
- nodeName: ifElseBlock.nodeName,
216
- }, ifElseBlock.children, {
217
- if: 'if',
218
- elseif: 'if:elseif',
219
- else: 'if:else',
220
- '/if': 'end',
221
- }[ifElseBlock.nodeName])[0];
222
- expressions.push(expression);
223
- }
224
- return expressions;
225
- }
226
- const blockType = originBlockNode.type.toLowerCase().replace('block', '');
227
- const nodeList = new Map();
228
- for (const prop of props) {
229
- let node = (originBlockNode[prop] ?? originBlockNode);
230
- if (nodeList.has(node)) {
231
- continue;
232
- }
233
- if (node.type === 'ElseBlock' && node.children?.[0]?.elseif) {
234
- node = node.children[0];
235
- while (node != null) {
236
- if (!['IfBlock', 'ElseBlock'].includes(node.type)) {
237
- break;
238
- }
239
- const type = node.elseif ? 'if:elseif' : 'if:else';
240
- nodeList.set(node, type);
241
- node = node.else ?? node.children?.[0] ?? null;
242
- }
243
- continue;
244
- }
245
- const typeMap = {
246
- if: 'if',
247
- else: 'if:else',
248
- each: 'each',
249
- pending: 'await',
250
- then: 'await:then', // eslint-disable-line unicorn/no-thenable
251
- catch: 'await:catch',
252
- };
253
- const type = typeMap[prop || blockType] ?? null;
254
- nodeList.set(node, type);
255
- }
256
- let lastChild = null;
257
- for (const [node, _type] of nodeList.entries()) {
258
- let type = _type;
259
- let start = node.start;
260
- let end = node.end;
261
- if (type === 'await') {
262
- start = originBlockNode.start;
263
- }
264
- end = node.children?.[0]?.start ?? end;
265
- if (type === 'if:else' && originBlockNode.type === 'EachBlock') {
266
- type = 'each:empty';
267
- start = lastChild?.end ?? start;
268
- }
269
- if (['if:else', 'if:elseif'].includes(type) &&
270
- originBlockNode.type === 'IfBlock') {
271
- start = lastChild?.end ?? start;
272
- }
273
- const tag = this.sliceFragment(start, end);
274
- if (type === 'if:else' && node.type === 'ElseBlock' && node.children?.[0]?.type === 'IfBlock') {
275
- type = 'if:elseif';
276
- }
277
- if (node.children && Array.isArray(node.children)) {
278
- lastChild = node.children.at(-1) ?? null;
279
- }
280
- if (tag.raw === '') {
281
- continue;
282
- }
283
- const expression = this.visitPsBlock({
284
- ...tag,
285
- depth: token.depth,
286
- parentNode: token.parentNode,
287
- nodeName: type ?? blockType,
288
- }, node.children, type)[0];
289
- expressions.push(expression);
290
- }
291
- const lastText = this.sliceFragment(lastChild?.end ?? originBlockNode.end, originBlockNode.end);
292
- if (lastText.raw) {
293
- // Cut before whitespace
294
- const index = lastText.raw.search(/\S/);
295
- const lastToken = this.sliceFragment(lastText.startOffset + index, originBlockNode.end);
296
- if (lastToken.raw) {
297
- const expression = this.visitPsBlock({
298
- ...lastToken,
299
- depth: token.depth,
300
- parentNode: token.parentNode,
301
- nodeName: '/' + blockType,
302
- }, [], 'end')[0];
303
- expressions.push(expression);
304
- }
305
- }
306
- return expressions;
307
- }
308
- }
309
- _SvelteParser_instances = new WeakSet(), _SvelteParser_traverseIfBlock = function _SvelteParser_traverseIfBlock(
310
- // eslint-disable-next-line @typescript-eslint/prefer-readonly-parameter-types
311
- originBlockNode, start, nodeName = 'if') {
312
- const result = [];
313
- start = start ?? originBlockNode.start;
314
- const end = originBlockNode.children?.[0]?.start ?? originBlockNode.end;
315
- const tag = this.sliceFragment(start, end);
316
- const children = originBlockNode.children ?? [];
317
- result.push({ ...tag, children, nodeName });
318
- if (originBlockNode.else) {
319
- if (originBlockNode.else.children[0].type === 'IfBlock') {
320
- const elseif = __classPrivateFieldGet(this, _SvelteParser_instances, "m", _SvelteParser_traverseIfBlock).call(this, originBlockNode.else.children[0], children.at(-1)?.end, 'elseif');
321
- result.push(...elseif);
322
- }
323
- else {
324
- const start = children.at(-1)?.end ?? originBlockNode.end;
325
- const end = originBlockNode.else.children[0].start;
326
- const tag = this.sliceFragment(start, end);
327
- result.push({
328
- ...tag,
329
- children: originBlockNode.else.children,
330
- nodeName: 'else',
331
- });
332
- }
333
- }
334
- {
335
- const start = result.at(-1)?.children.at(-1)?.end ?? originBlockNode.end;
336
- const end = originBlockNode.end;
337
- const tag = this.sliceFragment(start, end);
338
- if (tag.raw) {
339
- result.push({ ...tag, children: [], nodeName: '/if' });
340
- }
341
- }
342
- return result;
343
- };
344
- export const parser = new SvelteParser();
@@ -1,5 +0,0 @@
1
- /// <reference types="svelte" />
2
- import type { Directive, TemplateNode, Attribute, SpreadAttribute } from 'svelte/types/compiler/interfaces';
3
- export type SvelteNode = TemplateNode;
4
- export declare function svelteParse(template: string): SvelteNode[];
5
- export type SvelteDirective = Directive | Attribute | SpreadAttribute;
@@ -1,10 +0,0 @@
1
- import { parse } from 'svelte/compiler';
2
- export function svelteParse(template) {
3
- const ast = parse(template, { customElement: true });
4
- const start = ast.html.start;
5
- const children = ast.html.children ?? [];
6
- if (children[0] && children[0].end === start) {
7
- children.shift();
8
- }
9
- return children;
10
- }
@@ -1,6 +0,0 @@
1
- import { HtmlParser } from '@markuplint/html-parser';
2
- declare class SvelteKitTemplateParser extends HtmlParser {
3
- constructor();
4
- }
5
- export declare const parser: SvelteKitTemplateParser;
6
- export {};
@@ -1,15 +0,0 @@
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();