Elffuss BraidHub

kikocis/continue public

Merge pull request #5693 from continuedev/nate/prettier-ci

ci: :art: run prettier check for all PRs
Changesetc7baac6d06d15befac8bc609333c24ddfefaeef8548d041a2b575cd5cdb18305
AuthorTomasz Stefaniak <tomasz.p.stefaniak@gmail.com> · 2025-06-02 15:24 -07:00
CommitterGitHub <noreply@github.com> · 2025-06-02 15:24 -07:00
Parents528167808f19, 84f6959ab67f

Browse the files at this changeset

226 files changed

modified .continue/rules/documentation-standards.md +1 −1
@@ -13,4 +13,4 @@
1313 - Include cross-references to related documentation
1414 - Reference other docs with relative paths
1515 - Keep paragraphs concise and scannable
16-- Use code blocks with appropriate language tags
No newline at the end of the file
16+- Use code blocks with appropriate language tags
modified .github/workflows/pr_checks.yaml +19 −0
@@ -30,6 +30,24 @@
3030 if: steps.root-cache.outputs.cache-hit != 'true'
3131 run: npm ci
3232
33+ prettier-check:
34+ needs: install-root
35+ runs-on: ubuntu-latest
36+ steps:
37+ - uses: actions/checkout@v4
38+
39+ - uses: actions/setup-node@v4
40+ with:
41+ node-version-file: ".nvmrc"
42+
43+ - uses: actions/cache@v4
44+ with:
45+ path: node_modules
46+ key: ${{ runner.os }}-root-node-modules-${{ hashFiles('package-lock.json') }}
47+
48+ - name: Check code formatting with Prettier
49+ run: npx prettier --check "**/*.{js,jsx,ts,tsx,json,css,md}" --ignore-path .gitignore --ignore-path .prettierignore
50+
3351 install-config-yaml:
3452 needs: install-root
3553 runs-on: ubuntu-latest
@@ -860,6 +878,7 @@
860878 runs-on: ubuntu-latest
861879 needs:
862880 - install-root
881+ - prettier-check
863882 - install-core
864883 - core-checks
865884 - install-gui
modified .prettierignore +8 −1
@@ -15,4 +15,11 @@
1515 CHANGELOG.md
1616 **/continue_tutorial.py
1717 **/node_modules
18-**/CODEOWNERS
No newline at the end of the file
18+**/CODEOWNERS
19+core/vendor
20+coverage
21+e2e
22+extensions/vscode/gui
23+extensions/vscode/models
24+extensions/intellij/src/main/resources
25+packages/continue-sdk
No newline at the end of the file
modified CODE_OF_CONDUCT.md +10 −10
@@ -14,21 +14,21 @@
1414 Examples of behavior that contributes to creating a positive environment
1515 include:
1616
17-* Using welcoming and inclusive language
18-* Being respectful of differing viewpoints and experiences
19-* Gracefully accepting constructive criticism
20-* Focusing on what is best for the community
21-* Showing empathy towards other community members
17+- Using welcoming and inclusive language
18+- Being respectful of differing viewpoints and experiences
19+- Gracefully accepting constructive criticism
20+- Focusing on what is best for the community
21+- Showing empathy towards other community members
2222
2323 Examples of unacceptable behavior by participants include:
2424
25-* The use of sexualized language or imagery and unwelcome sexual attention or
25+- The use of sexualized language or imagery and unwelcome sexual attention or
2626 advances
27-* Trolling, insulting/derogatory comments, and personal or political attacks
28-* Public or private harassment
29-* Publishing others' private information, such as a physical or electronic
27+- Trolling, insulting/derogatory comments, and personal or political attacks
28+- Public or private harassment
29+- Publishing others' private information, such as a physical or electronic
3030 address, without explicit permission
31-* Other conduct which could reasonably be considered inappropriate in a
31+- Other conduct which could reasonably be considered inappropriate in a
3232 professional setting
3333
3434 ## Our Responsibilities
modified README.md +0 −1
@@ -58,7 +58,6 @@
5858
5959 ![edit](docs/static/img/edit.gif)
6060
61-
6261 </div>
6362
6463 ## Getting Started
modified binary/core-dev-server.js +7 −3
@@ -1,6 +1,10 @@
1-const path = require('path');
1+const path = require("path");
22 process.env.CONTINUE_DEVELOPMENT = true;
33
4-process.env.CONTINUE_GLOBAL_DIR = path.join(process.env.PROJECT_DIR, 'extensions', '.continue-debug');
4+process.env.CONTINUE_GLOBAL_DIR = path.join(
5+ process.env.PROJECT_DIR,
6+ "extensions",
7+ ".continue-debug",
8+);
59
6-require('./out/index.js');
No newline at the end of the file
10+require("./out/index.js");
modified binary/prompt-logs.js +18 −10
@@ -1,7 +1,13 @@
1-const fs = require('fs');
2-const path = require('path');
1+const fs = require("fs");
2+const path = require("path");
33
4-const logDirPath = path.join(__dirname, '..', 'extensions', '.continue-debug', 'logs');
4+const logDirPath = path.join(
5+ __dirname,
6+ "..",
7+ "extensions",
8+ ".continue-debug",
9+ "logs",
10+);
511 const logFilePath = path.join(logDirPath, "prompt.log");
612
713 // Ensure the log directory exists
@@ -12,7 +18,7 @@
1218
1319 // Create the log file if it doesn't exist
1420 if (!fs.existsSync(logFilePath)) {
15- fs.writeFileSync(logFilePath, ''); // Create an empty file synchronously
21+ fs.writeFileSync(logFilePath, ""); // Create an empty file synchronously
1622 console.log("Created empty log file at " + logFilePath);
1723 }
1824
@@ -25,14 +31,16 @@
2531 // console.clear();
2632 const stream = fs.createReadStream(logFilePath);
2733 stream.pipe(process.stdout);
28- stream.on('error', (err) => {
29- console.error('Error reading log file:', err.message);
34+ stream.on("error", (err) => {
35+ console.error("Error reading log file:", err.message);
3036 });
3137 } catch (err) {
32- console.error('Error while handling file change:', err.message);
38+ console.error("Error while handling file change:", err.message);
3339 }
3440 });
3541 } catch (err) {
36- console.error('Error setting up file watcher:', err.message);
37- console.log('You may need to restart the script after the extension generates the first log entry.');
38-}
No newline at the end of the file
42+ console.error("Error setting up file watcher:", err.message);
43+ console.log(
44+ "You may need to restart the script after the extension generates the first log entry.",
45+ );
46+}
modified binary/utils/targets.js +1 −1
@@ -39,4 +39,4 @@
3939 TARGET_TO_RIPGREP_RELEASE,
4040 TARGET_TO_LANCEDB,
4141 RIPGREP_VERSION,
42-};
No newline at the end of the file
42+};
modified core/autocomplete/filtering/streamTransforms/StreamTransformPipeline.ts +0 −1
@@ -74,7 +74,6 @@
7474
7575 const timeoutValue = helper.options.modelTimeout;
7676
77-
7877 lineGenerator = showWhateverWeHaveAtXMs(lineGenerator, timeoutValue!);
7978
8079 const finalGenerator = streamWithNewLines(lineGenerator);
modified core/autocomplete/filtering/streamTransforms/lineStream.test.ts +116 −15
@@ -215,21 +215,47 @@
215215 });
216216
217217 it("should handle unfenced code with a code block", async () => {
218- const linesGenerator = await getLineGenerator(["const x = 5;","```bash","ls -al","```"]);
218+ const linesGenerator = await getLineGenerator([
219+ "const x = 5;",
220+ "```bash",
221+ "ls -al",
222+ "```",
223+ ]);
219224
220225 const result = lineStream.filterCodeBlockLines(linesGenerator);
221226 const filteredLines = await getFilteredLines(result);
222227
223- expect(filteredLines).toEqual(["const x = 5;","```bash","ls -al","```"]);
228+ expect(filteredLines).toEqual([
229+ "const x = 5;",
230+ "```bash",
231+ "ls -al",
232+ "```",
233+ ]);
224234 });
225235
226236 it("should handle unfenced code with two code blocks", async () => {
227- const linesGenerator = await getLineGenerator(["const x = 5;","```bash","ls -al","```","```bash","ls -al","```"]);
237+ const linesGenerator = await getLineGenerator([
238+ "const x = 5;",
239+ "```bash",
240+ "ls -al",
241+ "```",
242+ "```bash",
243+ "ls -al",
244+ "```",
245+ ]);
228246
229247 const result = lineStream.filterCodeBlockLines(linesGenerator);
230248 const filteredLines = await getFilteredLines(result);
231249
232- expect(filteredLines).toEqual(["const x = 5;","```bash","ls -al","```","```bash","ls -al","```"]);
250+ expect(filteredLines).toEqual([
251+ "const x = 5;",
252+ "```bash",
253+ "ls -al",
254+ "```",
255+ "```bash",
256+ "ls -al",
257+ "```",
258+ ]);
233259 });
234260
235261 it("should remove lines before the first valid line", async () => {
@@ -242,7 +268,11 @@
242268 });
243269
244270 it("should remove outer blocks", async () => {
245- const linesGenerator = await getLineGenerator(["```ts", "const x = 5;","```"]);
271+ const linesGenerator = await getLineGenerator([
272+ "```ts",
273+ "const x = 5;",
274+ "```",
275+ ]);
246276
247277 const result = lineStream.filterCodeBlockLines(linesGenerator);
248278 const filteredLines = await getFilteredLines(result);
@@ -251,48 +281,119 @@
251281 });
252282
253283 it("should leave inner blocks intact", async () => {
254- const linesGenerator = await getLineGenerator(["```md", "const x = 5;", "```bash","ls -al","```","```"]);
284+ const linesGenerator = await getLineGenerator([
285+ "```md",
286+ "const x = 5;",
287+ "```bash",
288+ "ls -al",
289+ "```",
290+ "```",
291+ ]);
255292
256293 const result = lineStream.filterCodeBlockLines(linesGenerator);
257294 const filteredLines = await getFilteredLines(result);
258295
259- expect(filteredLines).toEqual(["const x = 5;","```bash","ls -al","```"]);
296+ expect(filteredLines).toEqual([
297+ "const x = 5;",
298+ "```bash",
299+ "ls -al",
300+ "```",
301+ ]);
260302 });
261303
262304 it("should handle included inner ticks", async () => {
263- const linesGenerator = await getLineGenerator(["```md", "const x = 5;", "```bash","echo ```test```","```","```"]);
305+ const linesGenerator = await getLineGenerator([
306+ "```md",
307+ "const x = 5;",
308+ "```bash",
309+ "echo ```test```",
310+ "```",
311+ "```",
312+ ]);
264313
265314 const result = lineStream.filterCodeBlockLines(linesGenerator);
266315 const filteredLines = await getFilteredLines(result);
267316
268- expect(filteredLines).toEqual(["const x = 5;","```bash","echo ```test```","```"]);
317+ expect(filteredLines).toEqual([
318+ "const x = 5;",
319+ "```bash",
320+ "echo ```test```",
321+ "```",
322+ ]);
269323 });
270324
271325 it("should leave single inner blocks intact but not return trailing text", async () => {
272- const linesGenerator = await getLineGenerator(["```md", "const x = 5;", "```bash","ls -al","```","```","trailing text"]);
326+ const linesGenerator = await getLineGenerator([
327+ "```md",
328+ "const x = 5;",
329+ "```bash",
330+ "ls -al",
331+ "```",
332+ "```",
333+ "trailing text",
334+ ]);
273335
274336 const result = lineStream.filterCodeBlockLines(linesGenerator);
275337 const filteredLines = await getFilteredLines(result);
276338
277- expect(filteredLines).toEqual(["const x = 5;","```bash","ls -al","```"]);
339+ expect(filteredLines).toEqual([
340+ "const x = 5;",
341+ "```bash",
342+ "ls -al",
343+ "```",
344+ ]);
278345 });
279346
280347 it("should leave double inner blocks intact but not return trailing text", async () => {
281- const linesGenerator = await getLineGenerator(["```md", "const x = 5;", "```bash","ls -al","```","const y = 10;","```sh","echo `hello world`","```","```","trailing text"]);
348+ const linesGenerator = await getLineGenerator([
349+ "```md",
350+ "const x = 5;",
351+ "```bash",
352+ "ls -al",
353+ "```",
354+ "const y = 10;",
355+ "```sh",
356+ "echo `hello world`",
357+ "```",
358+ "```",
359+ "trailing text",
360+ ]);
282361
283362 const result = lineStream.filterCodeBlockLines(linesGenerator);
284363 const filteredLines = await getFilteredLines(result);
285364
286- expect(filteredLines).toEqual(["const x = 5;","```bash","ls -al","```","const y = 10;","```sh","echo `hello world`","```"]);
365+ expect(filteredLines).toEqual([
366+ "const x = 5;",
367+ "```bash",
368+ "ls -al",
369+ "```",
370+ "const y = 10;",
371+ "```sh",
372+ "echo `hello world`",
373+ "```",
374+ ]);
287375 });
288376
289377 it("should leave inner blocks intact but not return trailing or leading text", async () => {
290- const linesGenerator = await getLineGenerator(["[CODE]", "const x = 5;", "```bash","ls -al","```","[/CODE]","trailing text"]);
378+ const linesGenerator = await getLineGenerator([
379+ "[CODE]",
380+ "const x = 5;",
381+ "```bash",
382+ "ls -al",
383+ "```",
384+ "[/CODE]",
385+ "trailing text",
386+ ]);
291387
292388 const result = lineStream.filterCodeBlockLines(linesGenerator);
293389 const filteredLines = await getFilteredLines(result);
294390
295- expect(filteredLines).toEqual(["const x = 5;","```bash","ls -al","```"]);
391+ expect(filteredLines).toEqual([
392+ "const x = 5;",
393+ "```bash",
394+ "ls -al",
395+ "```",
396+ ]);
296397 });
297398 });
298399
modified core/autocomplete/filtering/streamTransforms/lineStream.ts +1 −3
@@ -350,12 +350,10 @@
350350 let nestCount = 0;
351351
352352 for await (const line of rawLines) {
353-
354-
355353 if (!seenFirstFence) {
356354 if (shouldRemoveLineBeforeStart(line)) {
357355 // Filter out starting ``` or START block
358- continue
356+ continue;
359357 }
360358 // Regardless of a fence or START block start tracking the nesting level
361359 seenFirstFence = true;
modified core/autocomplete/generation/GeneratorReuseManager.ts +10 −2
@@ -14,7 +14,11 @@
1414 ) {
1515 this.currentGenerator?.cancel();
1616
17- const listenableGen = new ListenableGenerator(gen, this.onError, abortController);
17+ const listenableGen = new ListenableGenerator(
18+ gen,
19+ this.onError,
20+ abortController,
21+ );
1822 listenableGen.listen((chunk) => (this.pendingCompletion += chunk ?? ""));
1923
2024 this.pendingGeneratorPrefix = prefix;
@@ -43,7 +47,11 @@
4347 if (!this.shouldReuseExistingGenerator(prefix)) {
4448 // Create a wrapper over the current generator to fix the prompt
4549 const abortController = new AbortController();
46- this._createListenableGenerator(abortController, newGenerator(abortController.signal), prefix);
50+ this._createListenableGenerator(
51+ abortController,
52+ newGenerator(abortController.signal),
53+ prefix,
54+ );
4755 }
4856
4957 // Already typed characters are those that are new in the prefix from the old generator
modified core/autocomplete/templating/AutocompleteTemplate.ts +2 −1
@@ -72,7 +72,8 @@
7272 };
7373
7474 const seedCoderFimTemplate: AutocompleteTemplate = {
75- template: "<[fim-prefix]>{{{prefix}}}<[fim-suffix]>{{{suffix}}}<[fim-middle]>",
75+ template:
76+ "<[fim-prefix]>{{{prefix}}}<[fim-suffix]>{{{suffix}}}<[fim-middle]>",
7677 completionOptions: {
7778 stop: [
7879 "<[end▁of▁sentence]>",
modified core/autocomplete/templating/filtering.ts +62 −50
@@ -42,17 +42,18 @@
4242 helper: HelperVars,
4343 payload: SnippetPayload,
4444 ): AutocompleteSnippet[] => {
45-
4645 const snippets = {
47- "clipboard": payload.clipboardSnippets,
48- "recentlyVisitedRanges": payload.recentlyVisitedRangesSnippets,
49- "recentlyEditedRanges": payload.recentlyEditedRangeSnippets,
50- "diff": payload.diffSnippets,
51- "base": shuffleArray(filterSnippetsAlreadyInCaretWindow(
52- [...payload.rootPathSnippets, ...payload.importDefinitionSnippets],
53- helper.prunedCaretWindow,
54- )),
55- }
46+ clipboard: payload.clipboardSnippets,
47+ recentlyVisitedRanges: payload.recentlyVisitedRangesSnippets,
48+ recentlyEditedRanges: payload.recentlyEditedRangeSnippets,
49+ diff: payload.diffSnippets,
50+ base: shuffleArray(
51+ filterSnippetsAlreadyInCaretWindow(
52+ [...payload.rootPathSnippets, ...payload.importDefinitionSnippets],
53+ helper.prunedCaretWindow,
54+ ),
55+ ),
56+ };
5657
5758 // Define snippets with their priorities
5859 const snippetConfigs: {
@@ -61,53 +62,60 @@
6162 defaultPriority: number;
6263 snippets: AutocompleteSnippet[];
6364 }[] = [
64- {
65- key: "clipboard",
66- enabledOrPriority: helper.options.experimental_includeClipboard,
67- defaultPriority: 1,
68- snippets: payload.clipboardSnippets,
69- },
70- {
71- key: "recentlyVisitedRanges",
72- enabledOrPriority: helper.options.experimental_includeRecentlyVisitedRanges,
73- defaultPriority: 2,
74- snippets: payload.recentlyVisitedRangesSnippets,
75- /* TODO: recentlyVisitedRanges also contain contents from other windows like terminal or output
65+ {
66+ key: "clipboard",
67+ enabledOrPriority: helper.options.experimental_includeClipboard,
68+ defaultPriority: 1,
69+ snippets: payload.clipboardSnippets,
70+ },
71+ {
72+ key: "recentlyVisitedRanges",
73+ enabledOrPriority:
74+ helper.options.experimental_includeRecentlyVisitedRanges,
75+ defaultPriority: 2,
76+ snippets: payload.recentlyVisitedRangesSnippets,
77+ /* TODO: recentlyVisitedRanges also contain contents from other windows like terminal or output
7678 if they are visible. We should handle them separately so that we can control their priority
7779 and whether they should be included or not. */
78- },
79- {
80- key: "recentlyEditedRanges",
81- enabledOrPriority: helper.options.experimental_includeRecentlyEditedRanges,
82- defaultPriority: 3,
83- snippets: payload.recentlyEditedRangeSnippets,
84- },
85- {
86- key: "diff",
87- enabledOrPriority: helper.options.experimental_includeDiff,
88- defaultPriority: 4,
89- snippets: payload.diffSnippets,
90- // TODO: diff is commonly too large, thus anything lower in priority is not included.
91- },
92- {
93- key: "base",
94- enabledOrPriority: true,
95- defaultPriority: 99, // make sure it's the last one to be processed, but still possible to override
96- snippets: shuffleArray(filterSnippetsAlreadyInCaretWindow(
80+ },
81+ {
82+ key: "recentlyEditedRanges",
83+ enabledOrPriority:
84+ helper.options.experimental_includeRecentlyEditedRanges,
85+ defaultPriority: 3,
86+ snippets: payload.recentlyEditedRangeSnippets,
87+ },
88+ {
89+ key: "diff",
90+ enabledOrPriority: helper.options.experimental_includeDiff,
91+ defaultPriority: 4,
92+ snippets: payload.diffSnippets,
93+ // TODO: diff is commonly too large, thus anything lower in priority is not included.
94+ },
95+ {
96+ key: "base",
97+ enabledOrPriority: true,
98+ defaultPriority: 99, // make sure it's the last one to be processed, but still possible to override
99+ snippets: shuffleArray(
100+ filterSnippetsAlreadyInCaretWindow(
97101 [...payload.rootPathSnippets, ...payload.importDefinitionSnippets],
98102 helper.prunedCaretWindow,
99- )),
100- // TODO: Add this too to experimental config, maybe move upper in the order, since it's almost
101- // always not inlucded due to diff being commonly large
102- },
103- ];
103+ ),
104+ ),
105+ // TODO: Add this too to experimental config, maybe move upper in the order, since it's almost
106+ // always not inlucded due to diff being commonly large
107+ },
108+ ];
104109
105110 // Create a readable order of enabled snippets
106111 const snippetOrder = snippetConfigs
107112 .filter(({ enabledOrPriority }) => enabledOrPriority)
108113 .map(({ key, enabledOrPriority, defaultPriority }) => ({
109114 key,
110- priority: typeof enabledOrPriority === 'number' ? enabledOrPriority : defaultPriority,
115+ priority:
116+ typeof enabledOrPriority === "number"
117+ ? enabledOrPriority
118+ : defaultPriority,
111119 }))
112120 .sort((a, b) => a.priority - b.priority);
113121
@@ -121,15 +129,19 @@
121129 // Convert configs to prioritized snippets
122130 let prioritizedSnippets = snippetOrder
123131 .flatMap(({ key, priority }) =>
124- snippets[key].map(snippet => ({ snippet, priority }))
132+ snippets[key].map((snippet) => ({ snippet, priority })),
125133 )
126134 .sort((a, b) => a.priority - b.priority)
127135 .map(({ snippet }) => snippet);
128136
129137 // Exclude Continue's own output as it makes it super-hard for users to test the autocomplete feature
130138 // while looking at the prompts in the Continue's output
131- prioritizedSnippets = prioritizedSnippets.filter((snippet) =>
132- !(snippet as AutocompleteCodeSnippet).filepath?.startsWith("output:extension-output-Continue.continue"));
139+ prioritizedSnippets = prioritizedSnippets.filter(
140+ (snippet) =>
141+ !(snippet as AutocompleteCodeSnippet).filepath?.startsWith(
142+ "output:extension-output-Continue.continue",
143+ ),
144+ );
133145
134146 const finalSnippets = [];
135147 let remainingTokenCount = getRemainingTokenCount(helper);
modified core/autocomplete/util/AutocompleteDebouncer.ts +4 −4
@@ -8,23 +8,23 @@
88 // Generate a unique ID for this request
99 const requestId = uuidv4();
1010 this.currentRequestId = requestId;
11-
11+
1212 // Clear any existing timeout
1313 if (this.debounceTimeout) {
1414 clearTimeout(this.debounceTimeout);
1515 }
16-
16+
1717 // Create a new promise that resolves after the debounce delay
1818 return new Promise<boolean>((resolve) => {
1919 this.debounceTimeout = setTimeout(() => {
2020 // When the timeout completes, check if this is still the most recent request
2121 const shouldDebounce = this.currentRequestId !== requestId;
22-
22+
2323 // If this is the most recent request, it shouldn't be debounced
2424 if (!shouldDebounce) {
2525 this.currentRequestId = undefined;
2626 }
27-
27+
2828 resolve(shouldDebounce);
2929 }, debounceDelay);
3030 });
modified core/autocomplete/util/completionTestUtils.test.ts +52 −52
@@ -1,65 +1,65 @@
11 import {
2- processTestCase,
3- type CompletionTestCase,
2+ processTestCase,
3+ type CompletionTestCase,
44 } from "./completionTestUtils";
55
66 describe("processTestCase utility", () => {
7- it("processes simple console.log completion", () => {
8- const testCase: CompletionTestCase = {
9- original: "console.log(|cur||till|)",
10- completion: "\"foo,\", bar",
11- };
7+ it("processes simple console.log completion", () => {
8+ const testCase: CompletionTestCase = {
9+ original: "console.log(|cur||till|)",
10+ completion: '"foo,", bar',
11+ };
1212
13- expect(processTestCase(testCase)).toEqual({
14- input: {
15- lastLineOfCompletionText: "\"foo,\", bar",
16- currentText: ")",
17- cursorPosition: "console.log(".length,
18- },
19- expectedResult: {
20- completionText: "\"foo,\", bar",
21- },
22- });
13+ expect(processTestCase(testCase)).toEqual({
14+ input: {
15+ lastLineOfCompletionText: '"foo,", bar',
16+ currentText: ")",
17+ cursorPosition: "console.log(".length,
18+ },
19+ expectedResult: {
20+ completionText: '"foo,", bar',
21+ },
2322 });
23+ });
2424
25- it("processes simple console.log completion with overwriting", () => {
26- const testCase: CompletionTestCase = {
27- original: "console.log(|cur|)|till|",
28- completion: "\"foo,\", bar);",
29- };
25+ it("processes simple console.log completion with overwriting", () => {
26+ const testCase: CompletionTestCase = {
27+ original: "console.log(|cur|)|till|",
28+ completion: '"foo,", bar);',
29+ };
3030
31- expect(processTestCase(testCase)).toEqual({
32- input: {
33- lastLineOfCompletionText: "\"foo,\", bar);",
34- currentText: ")",
35- cursorPosition: "console.log(".length,
36- },
37- expectedResult: {
38- completionText: "\"foo,\", bar);",
39- range: {
40- start: "console.log(".length,
41- end: "console.log()".length,
42- },
43- },
44- });
31+ expect(processTestCase(testCase)).toEqual({
32+ input: {
33+ lastLineOfCompletionText: '"foo,", bar);',
34+ currentText: ")",
35+ cursorPosition: "console.log(".length,
36+ },
37+ expectedResult: {
38+ completionText: '"foo,", bar);',
39+ range: {
40+ start: "console.log(".length,
41+ end: "console.log()".length,
42+ },
43+ },
4544 });
45+ });
4646
47- it("partially applying completion", () => {
48- const testCase: CompletionTestCase = {
49- original: "|cur||till|fetch(\"https://example.com\");",
50- completion: "await fetch(\"https://example.com\");",
51- appliedCompletion: "await ",
52- };
47+ it("partially applying completion", () => {
48+ const testCase: CompletionTestCase = {
49+ original: '|cur||till|fetch("https://example.com");',
50+ completion: 'await fetch("https://example.com");',
51+ appliedCompletion: "await ",
52+ };
5353
54- expect(processTestCase(testCase)).toEqual({
55- input: {
56- lastLineOfCompletionText: "await fetch(\"https://example.com\");",
57- currentText: "fetch(\"https://example.com\");",
58- cursorPosition: 0,
59- },
60- expectedResult: {
61- completionText: "await ",
62- },
63- });
54+ expect(processTestCase(testCase)).toEqual({
55+ input: {
56+ lastLineOfCompletionText: 'await fetch("https://example.com");',
57+ currentText: 'fetch("https://example.com");',
58+ cursorPosition: 0,
59+ },
60+ expectedResult: {
61+ completionText: "await ",
62+ },
6463 });
64+ });
6565 });
modified core/autocomplete/util/completionTestUtils.ts +61 −58
@@ -1,91 +1,94 @@
11 export interface CompletionTestCase {
2- original: string; // Text with |cur| and |till| markers
3- completion: string; // Text to insert/overwrite
4- appliedCompletion?: string | null;
5- cursorMarker?: string;
6- tillMarker?: string;
2+ original: string; // Text with |cur| and |till| markers
3+ completion: string; // Text to insert/overwrite
4+ appliedCompletion?: string | null;
5+ cursorMarker?: string;
6+ tillMarker?: string;
77 }
88
99 export interface ProcessedTestCase {
10- input: {
11- lastLineOfCompletionText: string;
12- currentText: string;
13- cursorPosition: number;
14- };
15- expectedResult: {
16- completionText: string;
17- range?: {
18- start: number;
19- end: number;
20- };
10+ input: {
11+ lastLineOfCompletionText: string;
12+ currentText: string;
13+ cursorPosition: number;
14+ };
15+ expectedResult: {
16+ completionText: string;
17+ range?: {
18+ start: number;
19+ end: number;
2120 };
21+ };
2222 }
2323
2424 /**
2525 * Transforms human-readable test case into input and expected results.
26- *
26+ *
2727 * - `original`: Your original text with |cur| marking where the cursor is before completion,
2828 * and |till| marking where the cursor should be after accepting completion (and this is
2929 * the end of the actual applied completion)
3030 * - `completion`: LLM completion output
3131 * - `appliedCompletion` (optional): part of the LLM completion output that is actually applied
3232 * (written between |cur| and |till| in the original)
33- *
33+ *
3434 * For example, you have this line:
35- *
35+ *
3636 * console.log("<cursor here>");
37- *
37+ *
3838 * and expect it to be completed this way:
39- *
39+ *
4040 * console.log("foo: ", bar<cursor here>);
41- *
41+ *
4242 * with your completion coming from LLM being: `'foo: ", bar<cursor here>);'`
43- *
43+ *
4444 * Your input to this function should be:
4545 * - original: `'console.log("|cur|"|till|);'`
4646 * - completion: `'foo: ", bar);'`
4747 * - appliedCompletion: `'foo: ", bar'`
48- *
48+ *
4949 * Output: input and expected output of {@link core/autocomplete/util/processSingleLineCompletion/processSingleLineCompletion|processSingleLineCompletion()}
50- *
50+ *
5151 */
5252 export function processTestCase({
53- original,
54- completion,
55- appliedCompletion = null,
56- cursorMarker = "|cur|",
57- tillMarker = "|till|",
53+ original,
54+ completion,
55+ appliedCompletion = null,
56+ cursorMarker = "|cur|",
57+ tillMarker = "|till|",
5858 }: CompletionTestCase): ProcessedTestCase {
59- // Validate cursor marker
60- if (!original.includes(cursorMarker)) {
61- throw new Error("Cursor marker not found in original text");
62- }
59+ // Validate cursor marker
60+ if (!original.includes(cursorMarker)) {
61+ throw new Error("Cursor marker not found in original text");
62+ }
6363
64- const cursorPos = original.indexOf(cursorMarker);
65- original = original.replace(cursorMarker, "");
64+ const cursorPos = original.indexOf(cursorMarker);
65+ original = original.replace(cursorMarker, "");
6666
67- let tillPos = original.indexOf(tillMarker);
68- if (tillPos < 0) {
69- tillPos = cursorPos;
70- } else {
71- original = original.replace(tillMarker, "")
72- }
67+ let tillPos = original.indexOf(tillMarker);
68+ if (tillPos < 0) {
69+ tillPos = cursorPos;
70+ } else {
71+ original = original.replace(tillMarker, "");
72+ }
7373
74- // Calculate currentText based on what's between cursor and till marker
75- const currentText = original.substring(cursorPos);
74+ // Calculate currentText based on what's between cursor and till marker
75+ const currentText = original.substring(cursorPos);
7676
77- return {
78- input: {
79- lastLineOfCompletionText: completion,
80- currentText,
81- cursorPosition: cursorPos,
82- },
83- expectedResult: {
84- completionText: appliedCompletion || completion,
85- range: cursorPos === tillPos ? undefined : {
86- start: cursorPos,
87- end: tillPos,
77+ return {
78+ input: {
79+ lastLineOfCompletionText: completion,
80+ currentText,
81+ cursorPosition: cursorPos,
82+ },
83+ expectedResult: {
84+ completionText: appliedCompletion || completion,
85+ range:
86+ cursorPos === tillPos
87+ ? undefined
88+ : {
89+ start: cursorPos,
90+ end: tillPos,
8891 },
89- },
90- };
91-}
No newline at the end of the file
92+ },
93+ };
94+}
modified core/autocomplete/util/processSingleLineCompletion.test.ts +78 −80
@@ -2,96 +2,94 @@
22 import { processSingleLineCompletion } from "./processSingleLineCompletion";
33
44 describe("processSingleLineCompletion", () => {
5-
6- it("should handle simple end of line completion", () => {
7- const testCase = processTestCase({
8- original: "console.log(|cur|",
9- completion: "\"Hello, world!\")",
10- });
11-
12- const result = processSingleLineCompletion(
13- testCase.input.lastLineOfCompletionText,
14- testCase.input.currentText,
15- testCase.input.cursorPosition
16- );
17-
18- expect(result).toEqual(testCase.expectedResult);
5+ it("should handle simple end of line completion", () => {
6+ const testCase = processTestCase({
7+ original: "console.log(|cur|",
8+ completion: '"Hello, world!")',
199 });
2010
21- it("should handle midline insert repeating the end of line", () => {
22- const testCase = processTestCase({
23- original: "console.log(|cur|);|till|",
24- completion: "\"Hello, world!\");",
25- });
26-
27- const result = processSingleLineCompletion(
28- testCase.input.lastLineOfCompletionText,
29- testCase.input.currentText,
30- testCase.input.cursorPosition
31- );
32-
33- expect(result).toEqual(testCase.expectedResult);
11+ const result = processSingleLineCompletion(
12+ testCase.input.lastLineOfCompletionText,
13+ testCase.input.currentText,
14+ testCase.input.cursorPosition,
15+ );
16+
17+ expect(result).toEqual(testCase.expectedResult);
18+ });
19+
20+ it("should handle midline insert repeating the end of line", () => {
21+ const testCase = processTestCase({
22+ original: "console.log(|cur|);|till|",
23+ completion: '"Hello, world!");',
3424 });
3525
36- it("should handle midline insert repeating the end of line plus adding a semicolon", () => {
37- const testCase = processTestCase({
38- original: "console.log(|cur|)|till|",
39- completion: "\"Hello, world!\");",
40- });
41-
42- const result = processSingleLineCompletion(
43- testCase.input.lastLineOfCompletionText,
44- testCase.input.currentText,
45- testCase.input.cursorPosition
46- );
47-
48- expect(result).toEqual(testCase.expectedResult);
26+ const result = processSingleLineCompletion(
27+ testCase.input.lastLineOfCompletionText,
28+ testCase.input.currentText,
29+ testCase.input.cursorPosition,
30+ );
31+
32+ expect(result).toEqual(testCase.expectedResult);
33+ });
34+
35+ it("should handle midline insert repeating the end of line plus adding a semicolon", () => {
36+ const testCase = processTestCase({
37+ original: "console.log(|cur|)|till|",
38+ completion: '"Hello, world!");',
4939 });
5040
51- it("should handle simple midline insert", () => {
52- const testCase = processTestCase({
53- original: "console.log(|cur|)",
54- completion: "\"Hello, world!\"",
55- });
56-
57- const result = processSingleLineCompletion(
58- testCase.input.lastLineOfCompletionText,
59- testCase.input.currentText,
60- testCase.input.cursorPosition
61- );
62-
63- expect(result).toEqual(testCase.expectedResult);
41+ const result = processSingleLineCompletion(
42+ testCase.input.lastLineOfCompletionText,
43+ testCase.input.currentText,
44+ testCase.input.cursorPosition,
45+ );
46+
47+ expect(result).toEqual(testCase.expectedResult);
48+ });
49+
50+ it("should handle simple midline insert", () => {
51+ const testCase = processTestCase({
52+ original: "console.log(|cur|)",
53+ completion: '"Hello, world!"',
6454 });
6555
66- it("should handle complex dif with addition in the beginning", () => {
67- const testCase = processTestCase({
68- original: "console.log(|cur||till|, \"param1\", )", // TODO
69- completion: "\"Hello world!\", \"param1\", param1);",
70- appliedCompletion: "\"Hello world!\""
71- });
72-
73- const result = processSingleLineCompletion(
74- testCase.input.lastLineOfCompletionText,
75- testCase.input.currentText,
76- testCase.input.cursorPosition
77- );
78-
79- expect(result).toEqual(testCase.expectedResult);
56+ const result = processSingleLineCompletion(
57+ testCase.input.lastLineOfCompletionText,
58+ testCase.input.currentText,
59+ testCase.input.cursorPosition,
60+ );
61+
62+ expect(result).toEqual(testCase.expectedResult);
63+ });
64+
65+ it("should handle complex dif with addition in the beginning", () => {
66+ const testCase = processTestCase({
67+ original: 'console.log(|cur||till|, "param1", )', // TODO
68+ completion: '"Hello world!", "param1", param1);',
69+ appliedCompletion: '"Hello world!"',
8070 });
8171
82- it("should handle simple insertion even with random equality", () => {
83- const testCase = processTestCase({
84- original: "print(f\"Foobar length: |cur||till|\")",
85- completion: "{len(foobar)}",
86- });
87-
88- const result = processSingleLineCompletion(
89- testCase.input.lastLineOfCompletionText,
90- testCase.input.currentText,
91- testCase.input.cursorPosition
92- );
93-
94- expect(result).toEqual(testCase.expectedResult);
72+ const result = processSingleLineCompletion(
73+ testCase.input.lastLineOfCompletionText,
74+ testCase.input.currentText,
75+ testCase.input.cursorPosition,
76+ );
77+
78+ expect(result).toEqual(testCase.expectedResult);
79+ });
80+
81+ it("should handle simple insertion even with random equality", () => {
82+ const testCase = processTestCase({
83+ original: 'print(f"Foobar length: |cur||till|")',
84+ completion: "{len(foobar)}",
9585 });
9686
87+ const result = processSingleLineCompletion(
88+ testCase.input.lastLineOfCompletionText,
89+ testCase.input.currentText,
90+ testCase.input.cursorPosition,
91+ );
92+
93+ expect(result).toEqual(testCase.expectedResult);
94+ });
9795 });
modified core/autocomplete/util/processSingleLineCompletion.ts +71 −70
@@ -1,92 +1,93 @@
11 import * as Diff from "diff";
22
33 interface SingleLineCompletionResult {
4- completionText: string;
5- range?: {
6- start: number;
7- end: number;
8- };
4+ completionText: string;
5+ range?: {
6+ start: number;
7+ end: number;
8+ };
99 }
1010
11-
1211 interface DiffType {
13- count?: number;
14- added?: boolean;
15- removed?: boolean;
16- value: string;
12+ count?: number;
13+ added?: boolean;
14+ removed?: boolean;
15+ value: string;
1716 }
1817
19-
2018 function diffPatternMatches(
21- diffs: DiffType[],
22- pattern: DiffPartType[],
19+ diffs: DiffType[],
20+ pattern: DiffPartType[],
2321 ): boolean {
24- if (diffs.length !== pattern.length) {
25- return false;
26- }
27-
28- for (let i = 0; i < diffs.length; i++) {
29- const diff = diffs[i];
30- const diffPartType: DiffPartType =
31- !diff.added && !diff.removed ? "=" : diff.added ? "+" : "-";
32-
33- if (diffPartType !== pattern[i]) {
34- return false;
35- }
22+ if (diffs.length !== pattern.length) {
23+ return false;
24+ }
25+
26+ for (let i = 0; i < diffs.length; i++) {
27+ const diff = diffs[i];
28+ const diffPartType: DiffPartType =
29+ !diff.added && !diff.removed ? "=" : diff.added ? "+" : "-";
30+
31+ if (diffPartType !== pattern[i]) {
32+ return false;
3633 }
34+ }
3735
38- return true;
36+ return true;
3937 }
4038
4139 type DiffPartType = "+" | "-" | "=";
4240
4341 export function processSingleLineCompletion(
44- lastLineOfCompletionText: string,
45- currentText: string,
46- cursorPosition: number
42+ lastLineOfCompletionText: string,
43+ currentText: string,
44+ cursorPosition: number,
4745 ): SingleLineCompletionResult | undefined {
48- const diffs: DiffType[] = Diff.diffWords(currentText, lastLineOfCompletionText);
49-
50- if (diffPatternMatches(diffs, ["+"])) {
51- // Just insert, we're already at the end of the line
52- return {
53- completionText: lastLineOfCompletionText,
54- };
55- }
56-
57- if (
58- diffPatternMatches(diffs, ["+", "="]) ||
59- diffPatternMatches(diffs, ["+", "=", "+"])
60- ) {
61- // The model repeated the text after the cursor to the end of the line
62- return {
63- completionText: lastLineOfCompletionText,
64- range: {
65- start: cursorPosition,
66- end: currentText.length + cursorPosition,
67- },
68- };
69- }
70-
71- if (
72- diffPatternMatches(diffs, ["+", "-"]) ||
73- diffPatternMatches(diffs, ["-", "+"])
74- ) {
75- // We are midline and the model just inserted without repeating to the end of the line
76- return {
77- completionText: lastLineOfCompletionText,
78- };
79- }
80-
81- // For any other diff pattern, just use the first added part if available
82- if (diffs[0]?.added) {
83- return {
84- completionText: diffs[0].value,
85- };
86- }
46+ const diffs: DiffType[] = Diff.diffWords(
47+ currentText,
48+ lastLineOfCompletionText,
49+ );
50+
51+ if (diffPatternMatches(diffs, ["+"])) {
52+ // Just insert, we're already at the end of the line
53+ return {
54+ completionText: lastLineOfCompletionText,
55+ };
56+ }
57+
58+ if (
59+ diffPatternMatches(diffs, ["+", "="]) ||
60+ diffPatternMatches(diffs, ["+", "=", "+"])
61+ ) {
62+ // The model repeated the text after the cursor to the end of the line
63+ return {
64+ completionText: lastLineOfCompletionText,
65+ range: {
66+ start: cursorPosition,
67+ end: currentText.length + cursorPosition,
68+ },
69+ };
70+ }
71+
72+ if (
73+ diffPatternMatches(diffs, ["+", "-"]) ||
74+ diffPatternMatches(diffs, ["-", "+"])
75+ ) {
76+ // We are midline and the model just inserted without repeating to the end of the line
77+ return {
78+ completionText: lastLineOfCompletionText,
79+ };
80+ }
8781
88- // Default case: treat as simple insertion
82+ // For any other diff pattern, just use the first added part if available
83+ if (diffs[0]?.added) {
8984 return {
90- completionText: lastLineOfCompletionText,
85+ completionText: diffs[0].value,
9186 };
87+ }
88+
89+ // Default case: treat as simple insertion
90+ return {
91+ completionText: lastLineOfCompletionText,
92+ };
9293 }
modified core/commands/slash/cmd.ts +4 −4
@@ -19,14 +19,14 @@
1919 return;
2020 }
2121
22- const gen =
23- llm.streamComplete(`The user has made a request to run a shell command. Their description of what it should do is:
22+ const gen = llm.streamComplete(
23+ `The user has made a request to run a shell command. Their description of what it should do is:
2424
2525 "${input}"
2626
2727 Please write a shell command that will do what the user requested. Your output should consist of only the command itself, without any explanation or example output. Do not use any newlines. Only output the command that when inserted into the terminal will do precisely what was requested. Here is the command:`,
28- new AbortController().signal
29- );
28+ new AbortController().signal,
29+ );
3030
3131 const lines = streamLines(gen);
3232 let cmd = "";
modified core/context/providers/ContinueProxyContextProvider.ts +1 −1
@@ -24,7 +24,7 @@
2424 this.options.title || ContinueProxyContextProvider.description.title,
2525 displayTitle:
2626 this.options.displayTitle ||
27- this.options.name ||
27+ this.options.name ||
2828 ContinueProxyContextProvider.description.displayTitle,
2929 description:
3030 this.options.description ||
modified core/context/providers/GitLabMergeRequestContextProvider.ts +2 −2
@@ -124,10 +124,10 @@
124124 let urlMatches: RegExpExecArray | null;
125125 if (/https?.*/.test(remoteUrl)) {
126126 const pathname = new URL(remoteUrl).pathname;
127- urlMatches = /\/(?<projectPath>.*?)(?:(?=\.git)|$)/.exec(pathname)
127+ urlMatches = /\/(?<projectPath>.*?)(?:(?=\.git)|$)/.exec(pathname);
128128 } else {
129129 // ssh
130- urlMatches = /:(?<projectPath>.*).git/.exec(remoteUrl)
130+ urlMatches = /:(?<projectPath>.*).git/.exec(remoteUrl);
131131 }
132132
133133 const project = urlMatches?.groups?.projectPath ?? null;
modified core/context/providers/HttpContextProvider.ts +7 −6
@@ -20,10 +20,11 @@
2020 try {
2121 const currentFile = await ide.getCurrentFile();
2222 // `isLocalhost` actually also returns true for other local addresses, not just localhost
23- return await isLocalhost(url.hostname) ?
24- (await ide.getWorkspaceDirs()).find(workspaceDirectory => {
25- return currentFile?.path.startsWith(workspaceDirectory)
26- }) : undefined
23+ return (await isLocalhost(url.hostname))
24+ ? (await ide.getWorkspaceDirs()).find((workspaceDirectory) => {
25+ return currentFile?.path.startsWith(workspaceDirectory);
26+ })
27+ : undefined;
2728 } catch (e) {
2829 return undefined;
2930 }
@@ -44,12 +45,12 @@
4445 HttpContextProvider.description.renderInlineAs,
4546 };
4647 }
47-
48+
4849 async getContextItems(
4950 query: string,
5051 extras: ContextProviderExtras,
5152 ): Promise<ContextItem[]> {
52- const parsedUrl = new URL(this.options.url)
53+ const parsedUrl = new URL(this.options.url);
5354 const response = await extras.fetch(parsedUrl, {
5455 method: "POST",
5556 headers: {
modified core/context/providers/JiraIssuesContextProvider/index.ts +1 −1
@@ -25,7 +25,7 @@
2525 issueQuery: this.options.issueQuery,
2626 apiVersion: this.options.apiVersion,
2727 requestOptions: this.options.requestOptions,
28- maxResults: this.options.maxResults
28+ maxResults: this.options.maxResults,
2929 });
3030 }
3131
modified core/context/retrieval/pipelines/BaseRetrievalPipeline.ts +1 −1
@@ -85,7 +85,7 @@
8585 }
8686
8787 const tokens = this.getCleanedTrigrams(args.query).join(" OR ");
88-
88+
8989 return await this.ftsIndex.retrieve({
9090 n,
9191 text: tokens,
modified core/edit/lazy/replace.ts +7 −4
@@ -83,10 +83,13 @@
8383 \`\`\`
8484 `;
8585
86- const completion = await llm.streamChat([
87- { role: "user", content: userPrompt },
88- { role: "assistant", content: assistantPrompt },
89- ], new AbortController().signal);
86+ const completion = await llm.streamChat(
87+ [
88+ { role: "user", content: userPrompt },
89+ { role: "assistant", content: assistantPrompt },
90+ ],
91+ new AbortController().signal,
92+ );
9093
9194 let lines = streamLines(completion);
9295 lines = filterLeadingNewline(lines);
modified core/edit/lazy/unifiedDiffApply.test.ts +69 −41
@@ -43,7 +43,7 @@
4343 expect(isUnifiedDiffFormat(diffWithoutFileHeaders)).toBe(true);
4444 });
4545
46- it("should return true in case of empty lines", () => {
46+ it("should return true in case of empty lines", () => {
4747 const diffWithoutFileHeaders = `@@ -1,3 +1,4 @@
4848 line1
4949
@@ -83,16 +83,25 @@
8383 const expected = [
8484 { type: "same", line: "func main() {" },
8585 { type: "same", line: " scanner := bufio.NewScanner(os.Stdin)" },
86- { type: "same", line: " fmt.Println(\"Calculator started! Available operations:\")" },
87- { type: "same", line: " fmt.Println(\" + : Addition\")" },
88- { type: "same", line: " fmt.Println(\" - : Subtraction\")" },
89- { type: "same", line: " fmt.Println(\" * : Multiplication\")" },
90- { type: "same", line: " fmt.Println(\" / : Division\")" },
91- { type: "same", line: " fmt.Println(\" ^ : Power\")" },
92- { type: "same", line: " fmt.Println(\" √ : Square root (use only one number)\")" },
93- { type: "new", line: " fmt.Println(\" log: Logarithm (use 'log base number')\")" },
86+ {
87+ type: "same",
88+ line: ' fmt.Println("Calculator started! Available operations:")',
89+ },
90+ { type: "same", line: ' fmt.Println(" + : Addition")' },
91+ { type: "same", line: ' fmt.Println(" - : Subtraction")' },
92+ { type: "same", line: ' fmt.Println(" * : Multiplication")' },
93+ { type: "same", line: ' fmt.Println(" / : Division")' },
94+ { type: "same", line: ' fmt.Println(" ^ : Power")' },
95+ {
96+ type: "same",
97+ line: ' fmt.Println(" √ : Square root (use only one number)")',
98+ },
99+ {
100+ type: "new",
101+ line: " fmt.Println(\" log: Logarithm (use 'log base number')\")",
102+ },
94103 { type: "same", line: "}" },
95- { type: "same", line: "// End of file" }
104+ { type: "same", line: "// End of file" },
96105 ];
97106
98107 expect(result).toEqual(expected);
@@ -130,18 +139,18 @@
130139 const expected = [
131140 { type: "same", line: "package main" },
132141 { type: "same", line: "" },
133- { type: "old", line: "import \"fmt\"" },
142+ { type: "old", line: 'import "fmt"' },
134143 { type: "new", line: "import (" },
135- { type: "new", line: " \"fmt\"" },
136- { type: "new", line: " \"time\"" },
144+ { type: "new", line: ' "fmt"' },
145+ { type: "new", line: ' "time"' },
137146 { type: "new", line: ")" },
138147 { type: "same", line: "" },
139148 { type: "same", line: "func main() {" },
140- { type: "old", line: " fmt.Println(\"Hello\")" },
141- { type: "new", line: " fmt.Printf(\"The time is: %v\\n\", time.Now())" },
142- { type: "old", line: " fmt.Println(\"World\")" },
143- { type: "new", line: " fmt.Println(\"Goodbye!\")" },
144- { type: "same", line: "}" }
149+ { type: "old", line: ' fmt.Println("Hello")' },
150+ { type: "new", line: ' fmt.Printf("The time is: %v\\n", time.Now())' },
151+ { type: "old", line: ' fmt.Println("World")' },
152+ { type: "new", line: ' fmt.Println("Goodbye!")' },
153+ { type: "same", line: "}" },
145154 ];
146155
147156 expect(result).toEqual(expected);
@@ -379,29 +388,47 @@
379388
380389 expect(result[0].line).toEqual("package main");
381390 // 1st block
382- expect(result[18].line).toEqual("\tfmt.Println(\" √ : Square root (use only one number)\")");
383- expect(result[19].line).toEqual(" fmt.Println(\" log: Logarithm (use 'log base number')\")");
384- expect(result[20].line).toEqual(" fmt.Println(\" Base must be > 0 and != 1, number must be > 0\")");
385- // 2nd block
386- expect(result[56]).toEqual({type: "same", line: "\t}"});
387- expect(result[57]).toEqual({type: "new", line: "\t"});
388- expect(result[58]).toEqual({type: "new", line: "\t// Handle logarithmic operations"});
389- expect(result[73]).toEqual({type: "new", line: ""});
390- expect(result[74]).toEqual({type: "same", line: "\tif len(parts) != 3 {"});
391- // 3rd block
392- expect(result[140]).toEqual({type: "same", line: "}"});
393- expect(result[141]).toEqual({type: "new", line: ""});
394- expect(result[142]).toEqual({type: "new", line: "func TestLogarithmicCases(t *testing.T) {"});
395- expect(result[153]).toEqual({type: "new", line: "\t}"});
396- expect(result[154]).toEqual({type: "same", line: "func TestSpecialCases(t *testing.T) {"});
397- });
398-
399- it("should throw error when hunk cannot be matched to source", () => {
400- const sourceCode = `line1
391+ expect(result[18].line).toEqual(
392+ '\tfmt.Println(" √ : Square root (use only one number)")',
393+ );
394+ expect(result[19].line).toEqual(
395+ " fmt.Println(\" log: Logarithm (use 'log base number')\")",
396+ );
397+ expect(result[20].line).toEqual(
398+ ' fmt.Println(" Base must be > 0 and != 1, number must be > 0")',
399+ );
400+ // 2nd block
401+ expect(result[56]).toEqual({ type: "same", line: "\t}" });
402+ expect(result[57]).toEqual({ type: "new", line: "\t" });
403+ expect(result[58]).toEqual({
404+ type: "new",
405+ line: "\t// Handle logarithmic operations",
406+ });
407+ expect(result[73]).toEqual({ type: "new", line: "" });
408+ expect(result[74]).toEqual({
409+ type: "same",
410+ line: "\tif len(parts) != 3 {",
411+ });
412+ // 3rd block
413+ expect(result[140]).toEqual({ type: "same", line: "}" });
414+ expect(result[141]).toEqual({ type: "new", line: "" });
415+ expect(result[142]).toEqual({
416+ type: "new",
417+ line: "func TestLogarithmicCases(t *testing.T) {",
418+ });
419+ expect(result[153]).toEqual({ type: "new", line: "\t}" });
420+ expect(result[154]).toEqual({
421+ type: "same",
422+ line: "func TestSpecialCases(t *testing.T) {",
423+ });
424+ });
425+
426+ it("should throw error when hunk cannot be matched to source", () => {
427+ const sourceCode = `line1
401428 line2
402429 line3`;
403430
404- const diffText = `--- a.txt
431+ const diffText = `--- a.txt
405432 +++ b.txt
406433 @@ -1,3 +1,4 @@
407434 missing1
@@ -409,7 +436,8 @@
409436 +newline2
410437 missing3`;
411438
412- expect(() => applyUnifiedDiff(sourceCode, diffText))
413- .toThrow("Hunk could not be applied cleanly to source code.");
414- });
439+ expect(() => applyUnifiedDiff(sourceCode, diffText)).toThrow(
440+ "Hunk could not be applied cleanly to source code.",
441+ );
442+ });
415443 });
modified core/edit/lazy/unifiedDiffApply.ts +23 −6
@@ -8,7 +8,9 @@
88 export function isUnifiedDiffFormat(diff: string): boolean {
99 const lines = diff.trim().split("\n");
1010
11- if (lines.length < 3) {return false;}
11+ if (lines.length < 3) {
12+ return false;
13+ }
1214
1315 let hasHunkHeader = false;
1416 let hasValidContent = false;
@@ -35,10 +37,13 @@
3537 /**
3638 * Applies a unified diff to source code and returns an array of DiffLine objects.
3739 * Each DiffLine contains a type ("same", "new", or "old") and the line content.
38- *
40+ *
3941 * @throws Error if the diff cannot be cleanly applied to the source
4042 */
41-export function applyUnifiedDiff(sourceCode: string, unifiedDiffText: string): DiffLine[] {
43+export function applyUnifiedDiff(
44+ sourceCode: string,
45+ unifiedDiffText: string,
46+): DiffLine[] {
4247 const sourceLines = sourceCode.split(/\r?\n/);
4348 const hunks = parseUnifiedDiff(unifiedDiffText);
4449 const diffResult: DiffLine[] = [];
@@ -46,7 +51,11 @@
4651
4752 for (const hunk of hunks) {
4853 const hunkBeforeLines = extractBeforeLines(hunk.lines);
49- const hunkStart = findHunkInSource(sourceLines, hunkBeforeLines, currentPos);
54+ const hunkStart = findHunkInSource(
55+ sourceLines,
56+ hunkBeforeLines,
57+ currentPos,
58+ );
5059 if (hunkStart === -1) {
5160 // All hunks must be found in the source code. If not, throw an error.
5261 throw new Error("Hunk could not be applied cleanly to source code.");
@@ -124,8 +133,16 @@
124133 *
125134 * Returns the index in sourceLines where the block begins, or -1 if no match is found.
126135 */
127-function findHunkInSource(sourceLines: string[], hunkBeforeLines: string[], startIndex: number): number {
128- for (let i = startIndex; i <= sourceLines.length - hunkBeforeLines.length; i++) {
136+function findHunkInSource(
137+ sourceLines: string[],
138+ hunkBeforeLines: string[],
139+ startIndex: number,
140+): number {
141+ for (
142+ let i = startIndex;
143+ i <= sourceLines.length - hunkBeforeLines.length;
144+ i++
145+ ) {
129146 let match = true;
130147 for (let j = 0; j < hunkBeforeLines.length; j++) {
131148 const sl = sourceLines[i + j];
modified core/indexing/chunk/basic.ts +8 −6
@@ -14,12 +14,14 @@
1414 let startLine = 0;
1515 let currLine = 0;
1616
17- const lineTokens = await Promise.all(contents.split("\n").map(async l => {
18- return {
19- line: l,
20- tokenCount: await countTokensAsync(l),
21- };
22- }));
17+ const lineTokens = await Promise.all(
18+ contents.split("\n").map(async (l) => {
19+ return {
20+ line: l,
21+ tokenCount: await countTokensAsync(l),
22+ };
23+ }),
24+ );
2325
2426 for (const lt of lineTokens) {
2527 if (chunkTokens + lt.tokenCount > maxChunkSize - 5) {
modified core/indexing/chunk/code.test.ts +3 −3
@@ -30,7 +30,7 @@
3030 test("should capture small class and function from large python file", async () => {
3131 const extraLine = "# This is a comment";
3232 const myClass = "class MyClass:\n def __init__(self):\n pass";
33- const myFunction = "def my_function():\n return \"Hello, World!\"";
33+ const myFunction = 'def my_function():\n return "Hello, World!"';
3434
3535 const file =
3636 Array(100).fill(extraLine).join("\n") +
@@ -67,7 +67,7 @@
6767 chunks[0].startsWith("class MyClass:\n def method1():\n ..."),
6868 ).toBe(true);
6969 // The extra spaces seem to be a bug with tree-sitter-python
70- expect(chunks).toContain("def method1():\n return \"Hello, 1!\"");
71- expect(chunks).toContain("def method20():\n return \"Hello, 20!\"");
70+ expect(chunks).toContain('def method1():\n return "Hello, 1!"');
71+ expect(chunks).toContain('def method20():\n return "Hello, 20!"');
7272 });
7373 });
modified core/llm/countTokens.ts +1 −1
@@ -480,5 +480,5 @@
480480 pruneLinesFromTop,
481481 pruneRawPromptFromTop,
482482 pruneStringFromBottom,
483- pruneStringFromTop
483+ pruneStringFromTop,
484484 };
modified core/llm/llamaTokenizer.d.ts +17 −8
@@ -1,11 +1,20 @@
11 export declare class LlamaTokenizer {
2- vocabById: string[];
3- vocabByString: Map<string, number>;
4- merges: Map<string, number>;
5- constructor(vocab_base64?: string, merges_binary?: string);
6- encode(prompt: string, add_bos_token?: boolean, add_preceding_space?: boolean, log_performance?: boolean): number[];
7- decode(tokenIds: number[], add_bos_token?: boolean, add_preceding_space?: boolean): string;
8- runTests(tests?: (tokenizer: LlamaTokenizer) => boolean): void
2+ vocabById: string[];
3+ vocabByString: Map<string, number>;
4+ merges: Map<string, number>;
5+ constructor(vocab_base64?: string, merges_binary?: string);
6+ encode(
7+ prompt: string,
8+ add_bos_token?: boolean,
9+ add_preceding_space?: boolean,
10+ log_performance?: boolean,
11+ ): number[];
12+ decode(
13+ tokenIds: number[],
14+ add_bos_token?: boolean,
15+ add_preceding_space?: boolean,
16+ ): string;
17+ runTests(tests?: (tokenizer: LlamaTokenizer) => boolean): void;
918 }
1019 declare const llamaTokenizer: LlamaTokenizer;
11-export default llamaTokenizer;
No newline at the end of the file
20+export default llamaTokenizer;
modified core/llm/llamaTokenizer.js +0 −0

Not shown: the file is larger than the hub shows, or this page holds as much as it shows. View the file.

modified core/llm/llms/Bedrock.test.ts +100 −63
@@ -1,7 +1,12 @@
11 import { BedrockRuntimeClient } from "@aws-sdk/client-bedrock-runtime";
22 import { fromNodeProviderChain } from "@aws-sdk/credential-providers";
33 import Bedrock from "./Bedrock.js";
4-import { ChatMessage, Chunk, CompletionOptions, UserChatMessage } from "../../index.js";
4+import {
5+ ChatMessage,
6+ Chunk,
7+ CompletionOptions,
8+ UserChatMessage,
9+} from "../../index.js";
510
611 // Mock AWS SDK
712 jest.mock("@aws-sdk/client-bedrock-runtime", () => ({
@@ -34,7 +39,7 @@
3439 public async *streamChat(
3540 messages: ChatMessage[],
3641 signal: AbortSignal,
37- options: TestCompletionOptions
42+ options: TestCompletionOptions,
3843 ): AsyncGenerator<ChatMessage> {
3944 if (options.mockError) {
4045 throw new Error(options.mockError);
@@ -44,14 +49,16 @@
4449 yield {
4550 role: "assistant",
4651 content: "",
47- toolCalls: [{
48- id: "tool-1",
49- type: "function",
50- function: {
51- name: "test_tool",
52- arguments: '{"arg1":"value1"}'
53- }
54- }],
52+ toolCalls: [
53+ {
54+ id: "tool-1",
55+ type: "function",
56+ function: {
57+ name: "test_tool",
58+ arguments: '{"arg1":"value1"}',
59+ },
60+ },
61+ ],
5562 };
5663 return;
5764 }
@@ -97,7 +104,9 @@
97104
98105 expect(bedrock.region).toBe("us-east-1");
99106 expect(bedrock.profile).toBe("bedrock");
100- expect(bedrock.apiBase).toBe("https://bedrock-runtime.us-east-1.amazonaws.com");
107+ expect(bedrock.apiBase).toBe(
108+ "https://bedrock-runtime.us-east-1.amazonaws.com",
109+ );
101110 });
102111
103112 it("should use custom options when provided", () => {
@@ -131,14 +140,20 @@
131140 });
132141
133142 it("should handle text streaming correctly", async () => {
134- const messages: ChatMessage[] = [{
135- role: "user",
136- content: "Hi"
137- } as UserChatMessage];
143+ const messages: ChatMessage[] = [
144+ {
145+ role: "user",
146+ content: "Hi",
147+ } as UserChatMessage,
148+ ];
138149
139150 const results = [];
140151
141- for await (const message of bedrock.streamChat(messages, mockAbortSignal, defaultOptions)) {
152+ for await (const message of bedrock.streamChat(
153+ messages,
154+ mockAbortSignal,
155+ defaultOptions,
156+ )) {
142157 results.push(message);
143158 }
144159
@@ -149,18 +164,24 @@
149164 });
150165
151166 it("should handle tool use streaming correctly", async () => {
152- const messages: ChatMessage[] = [{
153- role: "user",
154- content: "Use a tool"
155- } as UserChatMessage];
167+ const messages: ChatMessage[] = [
168+ {
169+ role: "user",
170+ content: "Use a tool",
171+ } as UserChatMessage,
172+ ];
156173
157174 const results = [];
158175 const options: TestCompletionOptions = {
159176 ...defaultOptions,
160- mockToolUse: true
177+ mockToolUse: true,
161178 };
162179
163- for await (const message of bedrock.streamChat(messages, mockAbortSignal, options)) {
180+ for await (const message of bedrock.streamChat(
181+ messages,
182+ mockAbortSignal,
183+ options,
184+ )) {
164185 results.push(message);
165186 }
166187
@@ -168,31 +189,39 @@
168189 {
169190 role: "assistant",
170191 content: "",
171- toolCalls: [{
172- id: "tool-1",
173- type: "function",
174- function: {
175- name: "test_tool",
176- arguments: '{"arg1":"value1"}'
177- }
178- }],
192+ toolCalls: [
193+ {
194+ id: "tool-1",
195+ type: "function",
196+ function: {
197+ name: "test_tool",
198+ arguments: '{"arg1":"value1"}',
199+ },
200+ },
201+ ],
179202 },
180203 ]);
181204 });
182205
183206 it("should handle API errors", async () => {
184- const messages: ChatMessage[] = [{
185- role: "user",
186- content: "Hi"
187- } as UserChatMessage];
207+ const messages: ChatMessage[] = [
208+ {
209+ role: "user",
210+ content: "Hi",
211+ } as UserChatMessage,
212+ ];
188213
189214 const options: TestCompletionOptions = {
190215 ...defaultOptions,
191- mockError: "API Error"
216+ mockError: "API Error",
192217 };
193218
194219 await expect(async () => {
195- for await (const _ of bedrock.streamChat(messages, mockAbortSignal, options)) {
220+ for await (const _ of bedrock.streamChat(
221+ messages,
222+ mockAbortSignal,
223+ options,
224+ )) {
196225 // consume generator
197226 }
198227 }).rejects.toThrow("API Error");
@@ -239,7 +268,7 @@
239268 filepath: "file1",
240269 index: 0,
241270 startLine: 1,
242- endLine: 1
271+ endLine: 1,
243272 },
244273 {
245274 content: "doc2",
@@ -247,8 +276,8 @@
247276 filepath: "file2",
248277 index: 1,
249278 startLine: 1,
250- endLine: 1
251- }
279+ endLine: 1,
280+ },
252281 ];
253282
254283 const result = await bedrock.rerank("query", chunks);
@@ -262,16 +291,18 @@
262291 filepath: "file1",
263292 index: 0,
264293 startLine: 1,
265- endLine: 1
294+ endLine: 1,
266295 };
267296
268- await expect(
269- bedrock.rerank("error", [chunk])
270- ).rejects.toThrow("Reranking Error");
297+ await expect(bedrock.rerank("error", [chunk])).rejects.toThrow(
298+ "Reranking Error",
299+ );
271300 });
272301
273302 it("should throw error for empty input", async () => {
274- await expect(bedrock.rerank("", [])).rejects.toThrow("Query and chunks must not be empty");
303+ await expect(bedrock.rerank("", [])).rejects.toThrow(
304+ "Query and chunks must not be empty",
305+ );
275306 });
276307 });
277308
@@ -289,7 +320,7 @@
289320 it("should convert text messages correctly", () => {
290321 const message: ChatMessage = {
291322 role: "user",
292- content: "Hello"
323+ content: "Hello",
293324 } as UserChatMessage;
294325 const converted = bedrock["_convertMessage"](message);
295326 expect(converted).toEqual({
@@ -307,12 +338,14 @@
307338 const converted = bedrock["_convertMessage"](message);
308339 expect(converted).toEqual({
309340 role: "user",
310- content: [{
311- toolResult: {
312- toolUseId: "tool-1",
313- content: [{ text: "Tool result" }],
341+ content: [
342+ {
343+ toolResult: {
344+ toolUseId: "tool-1",
345+ content: [{ text: "Tool result" }],
346+ },
314347 },
315- }],
348+ ],
316349 });
317350 });
318351
@@ -320,25 +353,29 @@
320353 const message: ChatMessage = {
321354 role: "assistant",
322355 content: "",
323- toolCalls: [{
324- id: "tool-1",
325- type: "function" as const,
326- function: {
327- name: "test_tool",
328- arguments: '{"arg":"value"}',
356+ toolCalls: [
357+ {
358+ id: "tool-1",
359+ type: "function" as const,
360+ function: {
361+ name: "test_tool",
362+ arguments: '{"arg":"value"}',
363+ },
329364 },
330- }],
365+ ],
331366 };
332367 const converted = bedrock["_convertMessage"](message);
333368 expect(converted).toEqual({
334369 role: "assistant",
335- content: [{
336- toolUse: {
337- toolUseId: "tool-1",
338- name: "test_tool",
339- input: { arg: "value" },
370+ content: [
371+ {
372+ toolUse: {
373+ toolUseId: "tool-1",
374+ name: "test_tool",
375+ input: { arg: "value" },
376+ },
340377 },
341- }],
378+ ],
342379 });
343380 });
344381
modified core/llm/llms/Bedrock.ts +22 −16
@@ -292,9 +292,12 @@
292292 const convertedMessages = this._convertMessages(messages);
293293
294294 const shouldCacheSystemMessage =
295- !!systemMessage && this.cacheBehavior?.cacheSystemMessage || this.completionOptions.promptCaching;
295+ (!!systemMessage && this.cacheBehavior?.cacheSystemMessage) ||
296+ this.completionOptions.promptCaching;
296297 const enablePromptCaching =
297- shouldCacheSystemMessage || this.cacheBehavior?.cacheConversation || this.completionOptions.promptCaching;
298+ shouldCacheSystemMessage ||
299+ this.cacheBehavior?.cacheConversation ||
300+ this.completionOptions.promptCaching;
298301 const shouldCacheToolsConfig = this.completionOptions.promptCaching;
299302
300303 // Add header for prompt caching
@@ -306,21 +309,24 @@
306309 }
307310
308311 const supportsTools =
309- (this.capabilities?.tools || PROVIDER_TOOL_SUPPORT.bedrock?.(options.model)) ?? false;
312+ (this.capabilities?.tools ||
313+ PROVIDER_TOOL_SUPPORT.bedrock?.(options.model)) ??
314+ false;
310315
311- let toolConfig = supportsTools && options.tools
312- ? {
313- tools: options.tools.map((tool) => ({
314- toolSpec: {
315- name: tool.function.name,
316- description: tool.function.description,
317- inputSchema: {
318- json: tool.function.parameters,
319- },
320- },
321- })),
322- } as ToolConfiguration
323- : undefined;
316+ let toolConfig =
317+ supportsTools && options.tools
318+ ? ({
319+ tools: options.tools.map((tool) => ({
320+ toolSpec: {
321+ name: tool.function.name,
322+ description: tool.function.description,
323+ inputSchema: {
324+ json: tool.function.parameters,
325+ },
326+ },
327+ })),
328+ } as ToolConfiguration)
329+ : undefined;
324330
325331 if (toolConfig?.tools && shouldCacheToolsConfig) {
326332 toolConfig.tools.push({ cachePoint: { type: "default" } });
modified core/llm/llms/BedrockImport.ts +2 −2
@@ -1,6 +1,6 @@
11 import {
2- BedrockRuntimeClient,
3- InvokeModelWithResponseStreamCommand,
2+ BedrockRuntimeClient,
3+ InvokeModelWithResponseStreamCommand,
44 } from "@aws-sdk/client-bedrock-runtime";
55 import { fromNodeProviderChain } from "@aws-sdk/credential-providers";
66
modified core/llm/llms/Cerebras.ts +1 −1
@@ -12,7 +12,7 @@
1212 private static modelConversion: { [key: string]: string } = {
1313 "llama3.1-8b": "llama3.1-8b",
1414 "llama3.1-70b": "llama3.1-70b",
15- "llama-4-scout-17b-16e-instruct": "llama-4-scout-17b-16e-instruct"
15+ "llama-4-scout-17b-16e-instruct": "llama-4-scout-17b-16e-instruct",
1616 };
1717 protected _convertModelName(model: string): string {
1818 return Cerebras.modelConversion[model] ?? model;
modified core/llm/llms/HuggingFaceTEI.ts +2 −2
@@ -38,11 +38,11 @@
3838 const headers: Record<string, string> = {
3939 "Content-Type": "application/json",
4040 };
41-
41+
4242 if (this.apiKey) {
4343 headers["Authorization"] = `Bearer ${this.apiKey}`;
4444 }
45-
45+
4646 const resp = await this.fetch(new URL("embed", this.apiBase), {
4747 method: "POST",
4848 body: JSON.stringify({
modified core/llm/llms/NCompass.ts +8 −4
@@ -6,9 +6,9 @@
66 class NCompass extends OpenAI {
77 static providerName = "ncompass";
88 static defaultOptions: Partial<LLMOptions> = {
9- apiBase: "https://api.ncompass.tech/v1"
9+ apiBase: "https://api.ncompass.tech/v1",
1010 };
11- static embeddingsApiEndpoint: "https://api.gcp.ncompass.tech/v1/embeddings"
11+ static embeddingsApiEndpoint: "https://api.gcp.ncompass.tech/v1/embeddings";
1212
1313 private static modelConversion: { [key: string]: string } = {
1414 "qwen2.5-coder-7b": "Qwen/Qwen2.5-Coder-7B-Instruct",
@@ -30,7 +30,12 @@
3030 }
3131
3232 protected _getHeaders() {
33- const headers = super._getHeaders() as { "Content-Type": string; Authorization: string; "api-key": string; Accept?: string };
33+ const headers = super._getHeaders() as {
34+ "Content-Type": string;
35+ Authorization: string;
36+ "api-key": string;
37+ Accept?: string;
38+ };
3439 headers["Accept"] = "text/event-stream";
3540 return headers;
3641 }
@@ -56,7 +61,6 @@
5661 const data = (await resp.json()) as any;
5762 return data.data.map((result: { embedding: number[] }) => result.embedding);
5863 }
59-
6064 }
6165
6266 export default NCompass;
modified core/llm/llms/Novita.ts +1 −1
@@ -10,7 +10,7 @@
1010
1111 private static MODEL_IDS: { [name: string]: string } = {
1212 "deepseek-r1": "deepseek/deepseek-r1",
13- "deepseek_v3": "deepseek/deepseek_v3",
13+ deepseek_v3: "deepseek/deepseek_v3",
1414 "llama3-8b": "meta-llama/llama-3-8b-instruct",
1515 "llama3-70b": "meta-llama/llama-3-70b-instruct",
1616 "llama3.1-8b": "meta-llama/llama-3.1-8b-instruct",
modified core/llm/llms/OVHcloud.ts +7 −4
@@ -20,20 +20,23 @@
2020 "mistral-7b": "Mistral-7B-Instruct-v0.3",
2121 "mistral-8x7b": "Mixtral-8x7B-Instruct-v0.1",
2222 "mistral-nemo": "Mistral-Nemo-Instruct-2407",
23- "DeepSeek-R1-Distill-Llama-70B": "DeepSeek-R1-Distill-Llama-70B"
23+ "DeepSeek-R1-Distill-Llama-70B": "DeepSeek-R1-Distill-Llama-70B",
2424 };
2525
2626 protected _convertModelName(model: string) {
2727 return OVHcloud.MODEL_IDS[model] || this.model;
2828 }
2929
30- protected _convertArgs(options: CompletionOptions, messages: ChatMessage[]): ChatCompletionCreateParams {
30+ protected _convertArgs(
31+ options: CompletionOptions,
32+ messages: ChatMessage[],
33+ ): ChatCompletionCreateParams {
3134 const modifiedOptions = {
3235 ...options,
33- model: this._convertModelName(options.model)
36+ model: this._convertModelName(options.model),
3437 };
3538 return super._convertArgs(modifiedOptions, messages);
3639 }
3740 }
3841
39-export default OVHcloud;
No newline at the end of the file
42+export default OVHcloud;
modified core/llm/llms/SageMaker.ts +3 −3
@@ -1,7 +1,7 @@
11 import {
2- InvokeEndpointCommand,
3- InvokeEndpointWithResponseStreamCommand,
4- SageMakerRuntimeClient,
2+ InvokeEndpointCommand,
3+ InvokeEndpointWithResponseStreamCommand,
4+ SageMakerRuntimeClient,
55 } from "@aws-sdk/client-sagemaker-runtime";
66 import { fromNodeProviderChain } from "@aws-sdk/credential-providers";
77
modified core/llm/llms/Scaleway.ts +6 −4
@@ -3,7 +3,6 @@
33 import { LLMOptions, CompletionOptions, ChatMessage } from "../../index.js";
44 import { ChatCompletionCreateParams } from "openai/resources/index";
55
6-
76 class Scaleway extends OpenAI {
87 static providerName = "scaleway";
98 static defaultOptions: Partial<LLMOptions> = {
@@ -17,17 +16,20 @@
1716 "llama3.1-70b": "llama-3.1-70b-instruct",
1817 "mistral-nemo": "mistral-nemo-instruct-2407",
1918 "qwen2.5-coder-32b": "qwen2.5-coder-32b-instruct",
20- "pixtral": "pixtral-12b-2409",
19+ pixtral: "pixtral-12b-2409",
2120 };
2221
2322 protected _convertModelName(model: string) {
2423 return Scaleway.MODEL_IDS[model] || this.model;
2524 }
26- protected _convertArgs(options: CompletionOptions, messages: ChatMessage[]): ChatCompletionCreateParams {
25+ protected _convertArgs(
26+ options: CompletionOptions,
27+ messages: ChatMessage[],
28+ ): ChatCompletionCreateParams {
2729 // Convert model name in the options before passing to parent
2830 const modifiedOptions = {
2931 ...options,
30- model: this._convertModelName(options.model)
32+ model: this._convertModelName(options.model),
3133 };
3234 return super._convertArgs(modifiedOptions, messages);
3335 }
modified core/llm/llms/Venice.ts +13 −5
@@ -9,14 +9,22 @@
99 apiBase: "https://api.venice.ai/api/v1",
1010 };
1111
12- protected _convertArgs(options: CompletionOptions, messages: ChatMessage[]): ChatCompletionCreateParams {
13- const finalOptions = super._convertArgs(options, messages) as ChatCompletionCreateParams & { venice_parameters?: any };
14- if ("venice_parameters" in options && typeof options.venice_parameters === "object") {
12+ protected _convertArgs(
13+ options: CompletionOptions,
14+ messages: ChatMessage[],
15+ ): ChatCompletionCreateParams {
16+ const finalOptions = super._convertArgs(
17+ options,
18+ messages,
19+ ) as ChatCompletionCreateParams & { venice_parameters?: any };
20+ if (
21+ "venice_parameters" in options &&
22+ typeof options.venice_parameters === "object"
23+ ) {
1524 finalOptions.venice_parameters = { ...options.venice_parameters };
1625 }
1726 return finalOptions;
1827 }
19-
2028 }
2129
22-export default Venice;
No newline at the end of the file
30+export default Venice;
modified core/llm/rules/getSystemMessageWithRules.test.ts +53 −17
@@ -1,6 +1,9 @@
11 /* eslint-disable max-lines-per-function */
22 import { ContextItemWithId, RuleWithSource, UserChatMessage } from "../..";
3-import { getSystemMessageWithRules, shouldApplyRule } from "./getSystemMessageWithRules";
3+import {
4+ getSystemMessageWithRules,
5+ shouldApplyRule,
6+} from "./getSystemMessageWithRules";
47
58 describe("getSystemMessageWithRules", () => {
69 const baseSystemMessage = "Base system message";
@@ -450,7 +453,8 @@
450453 it("should include rules with alwaysApply: false when globs match", () => {
451454 const userMessage: UserChatMessage = {
452455 role: "user",
453- content: "```tsx Component.tsx\nexport const Component = () => <div>Hello</div>;\n```",
456+ content:
457+ "```tsx Component.tsx\nexport const Component = () => <div>Hello</div>;\n```",
454458 };
455459
456460 const result = getSystemMessageWithRules({
@@ -701,14 +705,18 @@
701705 it("should return true when alwaysApply is true, regardless of file paths", () => {
702706 expect(shouldApplyRule(ruleAlwaysApplyTrue, [])).toBe(true);
703707 expect(shouldApplyRule(ruleAlwaysApplyTrue, ["src/main.js"])).toBe(true);
704- expect(shouldApplyRule(ruleAlwaysApplyTrue, ["Component.tsx"])).toBe(true);
708+ expect(shouldApplyRule(ruleAlwaysApplyTrue, ["Component.tsx"])).toBe(
709+ true,
710+ );
705711 });
706712
707713 it("should use glob matching when alwaysApply is false", () => {
708714 // Should apply when globs match
709715 expect(shouldApplyRule(ruleAlwaysApplyFalse, ["src/main.ts"])).toBe(true);
710- expect(shouldApplyRule(ruleAlwaysApplyFalse, ["Component.tsx"])).toBe(true);
711-
716+ expect(shouldApplyRule(ruleAlwaysApplyFalse, ["Component.tsx"])).toBe(
717+ true,
718+ );
719+
712720 // Should not apply when globs don't match
713721 expect(shouldApplyRule(ruleAlwaysApplyFalse, ["script.py"])).toBe(false);
714722 expect(shouldApplyRule(ruleAlwaysApplyFalse, [])).toBe(false);
@@ -716,7 +724,9 @@
716724
717725 it("should return false when alwaysApply is false and no globs specified", () => {
718726 expect(shouldApplyRule(ruleAlwaysApplyFalseNoGlobs, [])).toBe(false);
719- expect(shouldApplyRule(ruleAlwaysApplyFalseNoGlobs, ["any-file.js"])).toBe(false);
727+ expect(
728+ shouldApplyRule(ruleAlwaysApplyFalseNoGlobs, ["any-file.js"]),
729+ ).toBe(false);
720730 });
721731 });
722732
@@ -724,7 +734,9 @@
724734 it("should return true for rules without globs regardless of file paths", () => {
725735 expect(shouldApplyRule(ruleWithoutGlobs, [])).toBe(true);
726736 expect(shouldApplyRule(ruleWithoutGlobs, ["src/main.js"])).toBe(true);
727- expect(shouldApplyRule(ruleWithoutGlobs, ["Component.tsx", "utils.py"])).toBe(true);
737+ expect(
738+ shouldApplyRule(ruleWithoutGlobs, ["Component.tsx", "utils.py"]),
739+ ).toBe(true);
728740 });
729741
730742 it("should return false for rules with globs when no file paths are provided", () => {
@@ -734,12 +746,16 @@
734746 it("should return true for rules with globs when matching file paths are provided", () => {
735747 expect(shouldApplyRule(ruleWithGlobs, ["Component.tsx"])).toBe(true);
736748 expect(shouldApplyRule(ruleWithGlobs, ["src/main.ts"])).toBe(true);
737- expect(shouldApplyRule(ruleWithGlobs, ["utils.js", "Component.tsx"])).toBe(true);
749+ expect(
750+ shouldApplyRule(ruleWithGlobs, ["utils.js", "Component.tsx"]),
751+ ).toBe(true);
738752 });
739753
740754 it("should return false for rules with globs when no matching file paths are provided", () => {
741755 expect(shouldApplyRule(ruleWithGlobs, ["utils.py"])).toBe(false);
742- expect(shouldApplyRule(ruleWithGlobs, ["main.js", "script.rb"])).toBe(false);
756+ expect(shouldApplyRule(ruleWithGlobs, ["main.js", "script.rb"])).toBe(
757+ false,
758+ );
743759 });
744760 });
745761
@@ -760,19 +776,39 @@
760776
761777 it("should handle array of glob patterns", () => {
762778 expect(shouldApplyRule(ruleWithArrayGlobs, ["src/main.ts"])).toBe(true);
763- expect(shouldApplyRule(ruleWithArrayGlobs, ["tests/unit.test.js"])).toBe(true);
764- expect(shouldApplyRule(ruleWithArrayGlobs, ["config/settings.json"])).toBe(false);
779+ expect(shouldApplyRule(ruleWithArrayGlobs, ["tests/unit.test.js"])).toBe(
780+ true,
781+ );
782+ expect(
783+ shouldApplyRule(ruleWithArrayGlobs, ["config/settings.json"]),
784+ ).toBe(false);
765785 });
766786
767787 it("should handle string glob patterns", () => {
768788 expect(shouldApplyRule(ruleWithSpecificPattern, ["utils.py"])).toBe(true);
769- expect(shouldApplyRule(ruleWithSpecificPattern, ["src/models/user.py"])).toBe(true);
770- expect(shouldApplyRule(ruleWithSpecificPattern, ["utils.js"])).toBe(false);
789+ expect(
790+ shouldApplyRule(ruleWithSpecificPattern, ["src/models/user.py"]),
791+ ).toBe(true);
792+ expect(shouldApplyRule(ruleWithSpecificPattern, ["utils.js"])).toBe(
793+ false,
794+ );
771795 });
772796
773797 it("should return true if any file path matches when multiple paths provided", () => {
774- expect(shouldApplyRule(ruleWithSpecificPattern, ["utils.js", "models.py", "config.json"])).toBe(true);
775- expect(shouldApplyRule(ruleWithGlobs, ["utils.py", "Component.tsx", "script.rb"])).toBe(true);
798+ expect(
799+ shouldApplyRule(ruleWithSpecificPattern, [
800+ "utils.js",
801+ "models.py",
802+ "config.json",
803+ ]),
804+ ).toBe(true);
805+ expect(
806+ shouldApplyRule(ruleWithGlobs, [
807+ "utils.py",
808+ "Component.tsx",
809+ "script.rb",
810+ ]),
811+ ).toBe(true);
776812 });
777813 });
778814
@@ -784,7 +820,7 @@
784820 globs: [],
785821 source: "rules-block",
786822 };
787-
823+
788824 // Empty array should be treated as "no globs" (truthy check fails)
789825 expect(shouldApplyRule(ruleWithEmptyGlobs, ["any-file.js"])).toBe(false);
790826 });
@@ -796,7 +832,7 @@
796832 globs: undefined,
797833 source: "rules-block",
798834 };
799-
835+
800836 expect(shouldApplyRule(ruleUndefinedGlobs, ["any-file.js"])).toBe(true);
801837 expect(shouldApplyRule(ruleUndefinedGlobs, [])).toBe(true);
802838 });
modified core/llm/templates/chat.ts +5 −5
@@ -95,11 +95,11 @@
9595
9696 // Llama2 template with added \n to prevent Codestral from continuing user message
9797 function codestralTemplateMessages(msgs: ChatMessage[]): string {
98- let template = llama2TemplateMessages(msgs);
99- if (template.length === 0) {
100- return template;
101- }
102- return template + "\n";
98+ let template = llama2TemplateMessages(msgs);
99+ if (template.length === 0) {
100+ return template;
101+ }
102+ return template + "\n";
103103 }
104104
105105 function anthropicTemplateMessages(messages: ChatMessage[]): string {
modified core/llm/utils/__tests__/getSecureID.test.ts +12 −12
@@ -1,13 +1,13 @@
1-import { getSecureID } from '../getSecureID';
1+import { getSecureID } from "../getSecureID";
22
33 // Mock the crypto.randomUUID function
44 const mockRandomUUID = jest.fn();
55 global.crypto = {
66 ...global.crypto,
7- randomUUID: mockRandomUUID
7+ randomUUID: mockRandomUUID,
88 };
99
10-describe('getSecureID', () => {
10+describe("getSecureID", () => {
1111 beforeEach(() => {
1212 // Reset the static property before each test
1313 (getSecureID as any).uuid = undefined;
@@ -15,16 +15,16 @@
1515 // Reset the mock implementation
1616 mockRandomUUID.mockReset();
1717 // Setup a mock implementation that returns a fixed value for testing
18- mockRandomUUID.mockReturnValue('test-uuid-1234');
18+ mockRandomUUID.mockReturnValue("test-uuid-1234");
1919 });
2020
21- test('should generate a UUID on first call', () => {
21+ test("should generate a UUID on first call", () => {
2222 const result = getSecureID();
2323 expect(mockRandomUUID).toHaveBeenCalledTimes(1);
24- expect(result).toBe('<!-- SID: test-uuid-1234 -->');
24+ expect(result).toBe("<!-- SID: test-uuid-1234 -->");
2525 });
2626
27- test('should reuse the same UUID on subsequent calls', () => {
27+ test("should reuse the same UUID on subsequent calls", () => {
2828 const firstResult = getSecureID();
2929 const secondResult = getSecureID();
3030
@@ -33,17 +33,17 @@
3333
3434 // Both results should be identical
3535 expect(firstResult).toBe(secondResult);
36- expect(firstResult).toBe('<!-- SID: test-uuid-1234 -->');
36+ expect(firstResult).toBe("<!-- SID: test-uuid-1234 -->");
3737 });
3838
39- test('should maintain the same UUID across different test cases if not reset', () => {
39+ test("should maintain the same UUID across different test cases if not reset", () => {
4040 // Don't reset the UUID here to test persistence
41- (getSecureID as any).uuid = 'persistent-uuid';
41+ (getSecureID as any).uuid = "persistent-uuid";
4242
4343 const result = getSecureID();
4444
4545 // No new UUID should be generated
4646 expect(mockRandomUUID).not.toHaveBeenCalled();
47- expect(result).toBe('<!-- SID: persistent-uuid -->');
47+ expect(result).toBe("<!-- SID: persistent-uuid -->");
4848 });
49-});
No newline at the end of the file
49+});
modified core/llm/utils/extractPathsFromCodeBlocks.test.ts +2 −2
@@ -17,7 +17,7 @@
1717 });
1818
1919 it("should handle multiple code blocks with different formats", () => {
20- const content =
20+ const content =
2121 "```typescript src/main.ts\nconst x = 1;\n```\n" +
2222 "```test.js\nclass Calculator { }\n```\n" +
2323 "```js utils.js (19-25)\nfunction test() {}\n```";
@@ -32,4 +32,4 @@
3232 const content = "```typescript\nconst x = 1;\n```";
3333 expect(extractPathsFromCodeBlocks(content)).toEqual([]);
3434 });
35-});
No newline at the end of the file
35+});
modified core/tools/definitions/runTerminalCommand.ts +22 −23
@@ -1,7 +1,7 @@
11 import { Tool } from "../..";
22 import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
33
4-import os from 'os';
4+import os from "os";
55
66 /**
77 * Get the preferred shell for the current platform
@@ -10,17 +10,17 @@
1010 export function getPreferredShell(): string {
1111 const platform = os.platform();
1212
13- if (platform === 'win32') {
14- return process.env.COMSPEC || 'cmd.exe';
15- } else if (platform === 'darwin') {
16- return process.env.SHELL || '/bin/zsh';
13+ if (platform === "win32") {
14+ return process.env.COMSPEC || "cmd.exe";
15+ } else if (platform === "darwin") {
16+ return process.env.SHELL || "/bin/zsh";
1717 } else {
1818 // Linux and other Unix-like systems
19- return process.env.SHELL || '/bin/bash';
19+ return process.env.SHELL || "/bin/bash";
2020 }
2121 }
2222
23-export const PLATFORM_INFO = `Choose terminal commands and scripts optimized for ${os.platform} and ${os.arch} and shell ${getPreferredShell()}.`
23+export const PLATFORM_INFO = `Choose terminal commands and scripts optimized for ${os.platform} and ${os.arch} and shell ${getPreferredShell()}.`;
2424
2525 export const runTerminalCommandTool: Tool = {
2626 type: "function",
@@ -32,28 +32,27 @@
3232 group: BUILT_IN_GROUP_NAME,
3333 function: {
3434 name: BuiltInToolNames.RunTerminalCommand,
35- description:
36- `Run a terminal command in the current directory.\
35+ description: `Run a terminal command in the current directory.\
3736 The shell is not stateful and will not remember any previous commands.\
3837 When a command is run in the background ALWAYS suggest using shell commands to stop it; NEVER suggest using Ctrl+C.\
3938 When suggesting subsequent shell commands ALWAYS format them in shell command blocks.\
4039 Do NOT perform actions requiring special/admin privileges.\
4140 ${PLATFORM_INFO}`,
42- parameters: {
43- type: "object",
44- required: ["command"],
45- properties: {
46- command: {
47- type: "string",
48- description:
49- "The command to run. This will be passed directly into the IDE shell.",
50- },
51- waitForCompletion: {
52- type: "boolean",
53- description:
54- "Whether to wait for the command to complete before returning. Default is true. Set to false to run the command in the background. Set to true to run the command in the foreground and wait to collect the output.",
55- },
41+ parameters: {
42+ type: "object",
43+ required: ["command"],
44+ properties: {
45+ command: {
46+ type: "string",
47+ description:
48+ "The command to run. This will be passed directly into the IDE shell.",
49+ },
50+ waitForCompletion: {
51+ type: "boolean",
52+ description:
53+ "Whether to wait for the command to complete before returning. Default is true. Set to false to run the command in the background. Set to true to run the command in the foreground and wait to collect the output.",
5654 },
5755 },
56+ },
5857 },
5958 };
modified core/tools/implementations/runTerminalCommand.test.ts +84 −63
@@ -17,26 +17,31 @@
1717 const mockGetWorkspaceDirs = jest.fn();
1818 const mockOnPartialOutput = jest.fn();
1919 const mockRunCommand = jest.fn();
20-
20+
2121 // Use a simple approach to ensure background processes are terminated
2222 let testPid: number | null = null;
23-
23+
2424 // Create a temp directory for our tests
25- const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'terminal-command-test-'));
25+ const tempDir = fs.mkdtempSync(
26+ path.join(os.tmpdir(), "terminal-command-test-"),
27+ );
2628
2729 beforeEach(() => {
2830 jest.resetAllMocks();
29-
31+
3032 // Setup backgrounded processes handling - don't mock, just make sure it's empty
3133 // Get any processes that might be already tracked and clear them
32- const processMap = (processBackgroundStates as any).processTerminalBackgroundStates;
33- if (processMap && typeof processMap.clear === 'function') {
34+ const processMap = (processBackgroundStates as any)
35+ .processTerminalBackgroundStates;
36+ if (processMap && typeof processMap.clear === "function") {
3437 processMap.clear();
3538 }
36-
39+
3740 // Setup IDE mocks
3841 mockGetIdeInfo.mockReturnValue(Promise.resolve({ remoteName: "local" }));
39- mockGetWorkspaceDirs.mockReturnValue(Promise.resolve([`file://${tempDir}`]));
42+ mockGetWorkspaceDirs.mockReturnValue(
43+ Promise.resolve([`file://${tempDir}`]),
44+ );
4045 });
4146
4247 afterEach(async () => {
@@ -44,9 +49,11 @@
4449 if (testPid !== null) {
4550 try {
4651 // Platform-independent way to kill a process
47- if (process.platform === 'win32') {
48- await new Promise(resolve => {
49- childProcess.exec(`taskkill /F /PID ${testPid}`, () => resolve(null));
52+ if (process.platform === "win32") {
53+ await new Promise((resolve) => {
54+ childProcess.exec(`taskkill /F /PID ${testPid}`, () =>
55+ resolve(null),
56+ );
5057 });
5158 } else {
5259 process.kill(testPid);
@@ -57,20 +64,24 @@
5764 testPid = null;
5865 }
5966 });
60-
67+
6168 afterAll(() => {
6269 // Clean up the temp directory after tests
6370 fs.rmSync(tempDir, { recursive: true, force: true });
6471 });
6572
6673 // Helper function to create a ToolExtras object
67- const createMockExtras = (overrides: Partial<{
68- onPartialOutput?: jest.Mock;
69- remoteName?: string;
70- }> = {}): ToolExtras => {
74+ const createMockExtras = (
75+ overrides: Partial<{
76+ onPartialOutput?: jest.Mock;
77+ remoteName?: string;
78+ }> = {},
79+ ): ToolExtras => {
7180 // Update IDE info if remoteName is provided
7281 if (overrides.remoteName) {
73- mockGetIdeInfo.mockReturnValue(Promise.resolve({ remoteName: overrides.remoteName }));
82+ mockGetIdeInfo.mockReturnValue(
83+ Promise.resolve({ remoteName: overrides.remoteName }),
84+ );
7485 }
7586
7687 // Create a minimally compliant IDE mock
@@ -97,7 +108,7 @@
97108 llm: {} as any,
98109 fetch: {} as any,
99110 tool: {} as any,
100- toolCallId: "test-tool-call"
111+ toolCallId: "test-tool-call",
101112 } as ToolExtras;
102113
103114 // Apply overrides
@@ -115,7 +126,7 @@
115126 const extras = createMockExtras();
116127
117128 const result = await runTerminalCommandImpl(args, extras);
118-
129+
119130 // Verify real command output
120131 expect(result).toHaveLength(1);
121132 expect(result[0].name).toBe("Terminal");
@@ -134,27 +145,27 @@
134145 console.error('error output');
135146 }, 50);
136147 "`;
137-
148+
138149 const args = { command, waitForCompletion: true };
139150 const mockOutputFn = jest.fn();
140151 const extras = createMockExtras({ onPartialOutput: mockOutputFn });
141152
142153 // Execute the command with streaming
143154 const result = await runTerminalCommandImpl(args, extras);
144-
155+
145156 // Verify onPartialOutput was called with increasing content
146157 expect(mockOutputFn).toHaveBeenCalled();
147-
158+
148159 // Verify final result has all output
149- expect(result[0].content).toContain('first output');
150- expect(result[0].content).toContain('second output');
151- expect(result[0].content).toContain('error output');
160+ expect(result[0].content).toContain("first output");
161+ expect(result[0].content).toContain("second output");
162+ expect(result[0].content).toContain("error output");
152163 // Verify status field indicates successful completion
153164 expect(result[0].status).toBe("Command completed");
154-
165+
155166 // Verify that initial streaming updates have empty status for regular commands
156167 const firstCall = mockOutputFn.mock.calls[0][0];
157- if (firstCall && typeof firstCall === 'object') {
168+ if (firstCall && typeof firstCall === "object") {
158169 const contextItems = (firstCall as any).contextItems;
159170 if (contextItems && Array.isArray(contextItems) && contextItems[0]) {
160171 // For commands with waitForCompletion=true, status should be empty while streaming
@@ -166,8 +177,8 @@
166177 it("should run commands in background when waitForCompletion is false", async () => {
167178 // Create a self-identifying background process that writes its PID
168179 // to a file we can access to kill it later
169- const pidFile = path.join(tempDir, 'test-pid.txt');
170-
180+ const pidFile = path.join(tempDir, "test-pid.txt");
181+
171182 // This script creates a long-running process and writes its PID to our file
172183 // Using a fixed duration timeout so we can be sure to clean it up
173184 const command = `node -e "
@@ -178,59 +189,66 @@
178189 console.log('background process completed');
179190 }, 500);
180191 "`;
181-
192+
182193 const args = { command, waitForCompletion: false };
183194 const mockOutputFn = jest.fn();
184195 const extras = createMockExtras({ onPartialOutput: mockOutputFn });
185196
186197 const result = await runTerminalCommandImpl(args, extras);
187-
198+
188199 // Result should indicate background running in either content or status
189- expect(result[0].content || result[0].status).toContain("running in the background");
200+ expect(result[0].content || result[0].status).toContain(
201+ "running in the background",
202+ );
190203 // Verify status field indicates background running
191204 expect(result[0].status).toBe("Command is running in the background...");
192-
205+
193206 // Initial notification should indicate background running
194207 expect(mockOutputFn).toHaveBeenCalled();
195208 // Check the first call contains background running message
196209 const firstCallData = mockOutputFn.mock.calls[0][0];
197- if (firstCallData && typeof firstCallData === 'object') {
210+ if (firstCallData && typeof firstCallData === "object") {
198211 const contextItems = (firstCallData as any).contextItems;
199212 if (contextItems && Array.isArray(contextItems) && contextItems[0]) {
200213 expect(contextItems[0].content).toContain("");
201- expect(contextItems[0].status).toMatch(/Command is running in the background.../);
214+ expect(contextItems[0].status).toMatch(
215+ /Command is running in the background.../,
216+ );
202217 }
203218 }
204219
205220 // Wait a bit to make sure the PID file is written
206- await new Promise(resolve => setTimeout(resolve, 100));
207-
221+ await new Promise((resolve) => setTimeout(resolve, 100));
222+
208223 // Read the PID file to get the process ID so we can kill it later
209224 if (fs.existsSync(pidFile)) {
210- testPid = Number(fs.readFileSync(pidFile, 'utf-8'));
225+ testPid = Number(fs.readFileSync(pidFile, "utf-8"));
211226 }
212-
227+
213228 // Wait a bit longer for the process to complete and onPartialOutput to be called again
214- await new Promise(resolve => setTimeout(resolve, 400));
215-
229+ await new Promise((resolve) => setTimeout(resolve, 400));
230+
216231 // Check for background process completion message in mockOutputFn calls
217232 // Note: This is optional and depends on timing, so we don't want to strictly enforce it
218233 let foundCompletionMessage = false;
219-
234+
220235 for (let i = 0; i < mockOutputFn.mock.calls.length; i++) {
221236 const call = mockOutputFn.mock.calls[i][0];
222- if (call && typeof call === 'object') {
237+ if (call && typeof call === "object") {
223238 const contextItems = (call as any).contextItems;
224239 if (contextItems && Array.isArray(contextItems) && contextItems[0]) {
225- if (contextItems[0].status === "\nBackground command completed" ||
226- (contextItems[0].status && contextItems[0].status.includes("Background command"))) {
240+ if (
241+ contextItems[0].status === "\nBackground command completed" ||
242+ (contextItems[0].status &&
243+ contextItems[0].status.includes("Background command"))
244+ ) {
227245 foundCompletionMessage = true;
228246 break;
229247 }
230248 }
231249 }
232250 }
233-
251+
234252 // If we found any completion message in the output, great!
235253 // But we won't fail the test if we didn't, since it may be timing-dependent
236254 if (mockOutputFn.mock.calls.length > 1) {
@@ -244,7 +262,7 @@
244262 const extras = createMockExtras({ remoteName: "ssh" });
245263
246264 const result = await runTerminalCommandImpl(args, extras);
247-
265+
248266 // In remote environments, it should use the IDE's runCommand
249267 expect(mockRunCommand).toHaveBeenCalledWith("echo 'test'");
250268 // Match the actual output message
@@ -256,23 +274,26 @@
256274
257275 it("should handle errors when executing invalid commands", async () => {
258276 // Use a command that should fail on any platform
259- const args = { command: "non-existent-command-xyz", waitForCompletion: true };
277+ const args = {
278+ command: "non-existent-command-xyz",
279+ waitForCompletion: true,
280+ };
260281 const extras = createMockExtras();
261282
262283 const result = await runTerminalCommandImpl(args, extras);
263-
284+
264285 expect(result[0].name).toBe("Terminal");
265286 expect(result[0].description).toBe("Terminal command output");
266-
287+
267288 // The exact error message varies by platform, but should contain error information
268289 const errorContent = result[0].content;
269290 expect(
270- errorContent.includes("Command failed") ||
271- errorContent.includes("not found") ||
272- errorContent.includes("recognized") ||
273- /error/i.test(errorContent)
291+ errorContent.includes("Command failed") ||
292+ errorContent.includes("not found") ||
293+ errorContent.includes("recognized") ||
294+ /error/i.test(errorContent),
274295 ).toBe(true);
275-
296+
276297 // Verify status field indicates command failure
277298 expect(result[0].status).toContain("Command failed with:");
278299 });
@@ -284,23 +305,23 @@
284305 const extras = createMockExtras();
285306
286307 const result = await runTerminalCommandImpl(args, extras);
287-
308+
288309 // Verify we still get a result with a name and description
289310 expect(result).toHaveLength(1);
290311 expect(result[0].name).toBe("Terminal");
291312 expect(result[0].description).toBe("Terminal command output");
292-
313+
293314 // The command should have executed and returned content
294315 expect(result[0].content).toBeDefined();
295-
316+
296317 // We should see the error message we wrote to stderr
297318 expect(result[0].content).toContain("This is an error message");
298-
319+
299320 // Verify status field indicates command failure - the exact message format can vary
300321 // between different node versions and platforms
301322 expect(result[0].status).toContain("Command failed");
302323 });
303-
324+
304325 it("should set appropriate status when a command completes successfully", async () => {
305326 // Use a simple command that will succeed
306327 const command = `node -e "console.log('success test')"`;
@@ -308,14 +329,14 @@
308329 const extras = createMockExtras();
309330
310331 const result = await runTerminalCommandImpl(args, extras);
311-
332+
312333 expect(result).toHaveLength(1);
313334 expect(result[0].name).toBe("Terminal");
314335 expect(result[0].content).toContain("success test");
315336 // Verify status field for successful command
316337 expect(result[0].status).toBe("Command completed");
317338 });
318-
339+
319340 it("should include status info for background commands in non-streaming mode", async () => {
320341 // Use a simple background command
321342 const command = `node -e "setTimeout(() => console.log('done'), 300)"`;
@@ -324,7 +345,7 @@
324345 const extras = createMockExtras();
325346
326347 const result = await runTerminalCommandImpl(args, extras);
327-
348+
328349 expect(result).toHaveLength(1);
329350 expect(result[0].name).toBe("Terminal");
330351 // Verify both content and status fields for background commands
modified core/tools/implementations/runTerminalCommand.ts +17 −12
@@ -3,7 +3,10 @@
33
44 import { fileURLToPath } from "node:url";
55 import { ToolImpl } from ".";
6-import { isProcessBackgrounded, removeBackgroundedProcess } from "../../util/processTerminalBackgroundStates";
6+import {
7+ isProcessBackgrounded,
8+ removeBackgroundedProcess,
9+} from "../../util/processTerminalBackgroundStates";
710
811 const asyncExec = util.promisify(childProcess.exec);
912
@@ -56,7 +59,9 @@
5659
5760 // Send partial output to UI
5861 if (extras.onPartialOutput) {
59- const status = waitForCompletion ? "" : "Command is running in the background...";
62+ const status = waitForCompletion
63+ ? ""
64+ : "Command is running in the background...";
6065 extras.onPartialOutput({
6166 toolCallId,
6267 contextItems: [
@@ -116,9 +121,10 @@
116121 if (!waitForCompletion) {
117122 // Already resolved, just update the UI with final output
118123 if (extras.onPartialOutput) {
119- const status = (code === 0 || !code
120- ? "\nBackground command completed"
121- : `\nBackground command failed with exit code ${code}`)
124+ const status =
125+ code === 0 || !code
126+ ? "\nBackground command completed"
127+ : `\nBackground command failed with exit code ${code}`;
122128 extras.onPartialOutput({
123129 toolCallId,
124130 contextItems: [
@@ -140,7 +146,7 @@
140146 name: "Terminal",
141147 description: "Terminal command output",
142148 content: terminalOutput,
143- status: status
149+ status: status,
144150 },
145151 ]);
146152 } else {
@@ -149,9 +155,8 @@
149155 {
150156 name: "Terminal",
151157 description: "Terminal command output",
152- content:
153- terminalOutput,
154- status: status,
158+ content: terminalOutput,
159+ status: status,
155160 },
156161 ]);
157162 }
@@ -191,7 +196,7 @@
191196 // Detach the process so it's not tied to the parent
192197 detached: true,
193198 // Redirect to /dev/null equivalent (works cross-platform)
194- stdio: 'ignore',
199+ stdio: "ignore",
195200 });
196201
197202 // Even for detached processes, add event handlers to clean up the background process map
@@ -225,7 +230,7 @@
225230 name: "Terminal",
226231 description: "Terminal command output",
227232 content: status,
228- status: status
233+ status: status,
229234 },
230235 ];
231236 }
@@ -269,4 +274,4 @@
269274 status: "Command failed",
270275 },
271276 ];
272-}
277+};
modified core/util/errors.ts +5 −6
@@ -1,4 +1,3 @@
1-
21 /**
32 * Recursively retrieves the root cause of an error by traversing through its `cause` property.
43 *
@@ -6,8 +5,8 @@
65 * @returns The root cause of the error, or the original error if no further cause is found.
76 */
87 export function getRootCause(err: any): any {
9- if (err.cause) {
10- return getRootCause(err.cause);
11- }
12- return err;
13-}
No newline at the end of the file
8+ if (err.cause) {
9+ return getRootCause(err.cause);
10+ }
11+ return err;
12+}
modified core/util/fetchFavicon.ts +1 −1
@@ -14,7 +14,7 @@
1414 const document = dom.window.document;
1515
1616 // Look for favicon in <link> tags
17- const linkTags = document.querySelectorAll("link[rel*=\"icon\"]");
17+ const linkTags = document.querySelectorAll('link[rel*="icon"]');
1818
1919 for (const link of linkTags) {
2020 const href = link.getAttribute("href");
modified core/util/index.ts +4 −5
@@ -74,7 +74,7 @@
7474 tsx: "tsx",
7575 ts: "typescript",
7676 java: "java",
77- class:"java", //.class files decompile to Java
77+ class: "java", //.class files decompile to Java
7878 go: "go",
7979 rb: "ruby",
8080 rs: "rust",
@@ -101,8 +101,7 @@
101101 return ext ? (extToLangMap[ext] ?? ext) : "";
102102 }
103103
104-
105-function sanitizeExtension(ext?: string): string|undefined {
104+function sanitizeExtension(ext?: string): string | undefined {
106105 if (ext) {
107106 //ignore ranges in extension eg. "java (11-23)"
108107 const match = ext.match(/^(\S+)\s*(\(.*\))?$/);
@@ -208,6 +207,6 @@
208207 export function splitCamelCaseAndNonAlphaNumeric(value: string) {
209208 return value
210209 .split(/(?<=[a-z0-9])(?=[A-Z])|[^a-zA-Z0-9]/)
211- .filter(t => t.length > 0)
212- .map(t => t.toLowerCase());
210+ .filter((t) => t.length > 0)
211+ .map((t) => t.toLowerCase());
213212 }
modified core/util/merge.test.ts +1 −1
@@ -10,7 +10,7 @@
1010 expect(result).toEqual({ a: 1, b: 3, c: 4 });
1111 });
1212
13- it("should overwrite values when mergeBehavior is \"overwrite\"", () => {
13+ it('should overwrite values when mergeBehavior is "overwrite"', () => {
1414 const first = { a: 1, b: 2 };
1515 const second = { b: 3, c: 4 };
1616 const result = mergeJson(first, second, "overwrite");
modified core/util/messageContent.test.ts +40 −10
@@ -1,5 +1,15 @@
1-import { stripImages, renderChatMessage, renderContextItems, normalizeToMessageParts } from "./messageContent.js";
2-import { ChatMessage, ContextItem, MessageContent, MessagePart } from "../index.js";
1+import {
2+ stripImages,
3+ renderChatMessage,
4+ renderContextItems,
5+ normalizeToMessageParts,
6+} from "./messageContent.js";
7+import {
8+ ChatMessage,
9+ ContextItem,
10+ MessageContent,
11+ MessagePart,
12+} from "../index.js";
313
414 describe("messageContent utility functions", () => {
515 describe("stripImages", () => {
@@ -11,7 +21,10 @@
1121 it("should strip out image parts and join text parts of a message", () => {
1222 const content: MessageContent = [
1323 { type: "text", text: "This is" },
14- { type: "imageUrl", imageUrl: { url: "http://example.com/image1.png" } },
24+ {
25+ type: "imageUrl",
26+ imageUrl: { url: "http://example.com/image1.png" },
27+ },
1528 { type: "text", text: "a test message." },
1629 ];
1730 expect(stripImages(content)).toBe("This is\na test message.");
@@ -24,7 +37,10 @@
2437 role: "assistant",
2538 content: [
2639 { type: "text", text: "Hello," },
27- { type: "imageUrl", imageUrl: { url: "http://example.com/image.png" } },
40+ {
41+ type: "imageUrl",
42+ imageUrl: { url: "http://example.com/image.png" },
43+ },
2844 { type: "text", text: "world!" },
2945 ],
3046 };
@@ -44,10 +60,20 @@
4460 describe("renderContextItems", () => {
4561 it("should concatenate the content of context items with two newlines", () => {
4662 const items: ContextItem[] = [
47- { content: "Context Item 1", name: "Item1", description: "Description1" },
48- { content: "Context Item 2", name: "Item2", description: "Description2" },
63+ {
64+ content: "Context Item 1",
65+ name: "Item1",
66+ description: "Description1",
67+ },
68+ {
69+ content: "Context Item 2",
70+ name: "Item2",
71+ description: "Description2",
72+ },
4973 ];
50- expect(renderContextItems(items)).toBe("Context Item 1\n\nContext Item 2");
74+ expect(renderContextItems(items)).toBe(
75+ "Context Item 1\n\nContext Item 2",
76+ );
5177 });
5278 });
5379
@@ -57,7 +83,9 @@
5783 role: "user",
5884 content: "This is a test message.",
5985 };
60- const expected: MessagePart[] = [{ type: "text", text: "This is a test message." }];
86+ const expected: MessagePart[] = [
87+ { type: "text", text: "This is a test message." },
88+ ];
6189 expect(normalizeToMessageParts(message)).toEqual(expected);
6290 });
6391
@@ -67,8 +95,10 @@
6795 content: "Tool message content",
6896 toolCallId: "1",
6997 };
70- const expected: MessagePart[] = [{ type: "text", text: "Tool message content" }];
98+ const expected: MessagePart[] = [
99+ { type: "text", text: "Tool message content" },
100+ ];
71101 expect(normalizeToMessageParts(message)).toEqual(expected);
72102 });
73103 });
74-});
No newline at the end of the file
104+});
modified core/util/ollamaHelper.ts +84 −80
@@ -4,96 +4,100 @@
44 import { IDE } from "..";
55
66 export interface ModelInfo {
7- id: string;
8- size: number;
9- digest: string;
7+ id: string;
8+ size: number;
9+ digest: string;
1010 }
1111
1212 export async function isOllamaInstalled(): Promise<boolean> {
13- return new Promise((resolve, _reject) => {
14- const command = process.platform === "win32" ? "where.exe ollama" : "which ollama";
15- exec(command, (error, _stdout, _stderr) => {
16- resolve(!error);
17- });
13+ return new Promise((resolve, _reject) => {
14+ const command =
15+ process.platform === "win32" ? "where.exe ollama" : "which ollama";
16+ exec(command, (error, _stdout, _stderr) => {
17+ resolve(!error);
1818 });
19+ });
1920 }
2021
2122 export async function startLocalOllama(ide: IDE): Promise<any> {
22- let startCommand: string | undefined;
23-
24- switch (process.platform) {
25- case "darwin"://MacOS
26- startCommand = "open -a Ollama.app\n";
27- break;
28-
29- case "win32"://Windows
30- startCommand = "& \"ollama app.exe\"\n";
31- break;
32-
33- default: //Linux...
34- const start_script_path = path.resolve(__dirname, "./start_ollama.sh");
35- if (await ide.fileExists(`file:/${start_script_path}`)) {
36- startCommand = `set -e && chmod +x ${start_script_path} && ${start_script_path}\n`;
37- console.log(`Ollama Linux startup script at : ${start_script_path}`);
38- } else {
39- return ide.showToast("error", `Cannot start Ollama: could not find ${start_script_path}!`)
40- }
41- }
42- if (startCommand) {
43- return ide.runCommand(startCommand, {
44- reuseTerminal: true,
45- terminalName: "Start Ollama"
46- });
47- }
23+ let startCommand: string | undefined;
24+
25+ switch (process.platform) {
26+ case "darwin": //MacOS
27+ startCommand = "open -a Ollama.app\n";
28+ break;
29+
30+ case "win32": //Windows
31+ startCommand = '& "ollama app.exe"\n';
32+ break;
33+
34+ default: //Linux...
35+ const start_script_path = path.resolve(__dirname, "./start_ollama.sh");
36+ if (await ide.fileExists(`file:/${start_script_path}`)) {
37+ startCommand = `set -e && chmod +x ${start_script_path} && ${start_script_path}\n`;
38+ console.log(`Ollama Linux startup script at : ${start_script_path}`);
39+ } else {
40+ return ide.showToast(
41+ "error",
42+ `Cannot start Ollama: could not find ${start_script_path}!`,
43+ );
44+ }
45+ }
46+ if (startCommand) {
47+ return ide.runCommand(startCommand, {
48+ reuseTerminal: true,
49+ terminalName: "Start Ollama",
50+ });
51+ }
4852 }
4953
5054 export async function getRemoteModelInfo(
51- modelId: string,
52- signal?: AbortSignal,
53- ): Promise<ModelInfo | undefined> {
54- const start = Date.now();
55- const [modelName, tag = "latest"] = modelId.split(":");
56- const url = `https://registry.ollama.ai/v2/library/${modelName}/manifests/${tag}`;
57- try {
58- const sig = signal ? signal : AbortSignal.timeout(3000);
59- const response = await fetch(url, { signal: sig });
60-
61- if (!response.ok) {
62- throw new Error(`Failed to fetch the model page: ${response.statusText}`);
63- }
64-
65- // First, read the response body as an ArrayBuffer to compute the digest
66- const buffer = await response.arrayBuffer();
67- const digest = getDigest(buffer);
68-
69- // Then, decode the ArrayBuffer into a string and parse it as JSON
70- const text = new TextDecoder().decode(buffer);
71- const manifest = JSON.parse(text) as {
72- config: { size: number };
73- layers: { size: number }[];
74- };
75- const modelSize =
76- manifest.config.size +
77- manifest.layers.reduce((sum, layer) => sum + layer.size, 0);
78-
79- const data: ModelInfo = {
80- id: modelId,
81- size: modelSize,
82- digest,
83- };
84- // Cache the successful result
85- return data;
86- } catch (error) {
87- console.error(`Error fetching or parsing model info: ${error}`);
88- } finally {
89- const elapsed = Date.now() - start;
90- console.log(`Fetched remote information for ${modelId} in ${elapsed} ms`);
55+ modelId: string,
56+ signal?: AbortSignal,
57+): Promise<ModelInfo | undefined> {
58+ const start = Date.now();
59+ const [modelName, tag = "latest"] = modelId.split(":");
60+ const url = `https://registry.ollama.ai/v2/library/${modelName}/manifests/${tag}`;
61+ try {
62+ const sig = signal ? signal : AbortSignal.timeout(3000);
63+ const response = await fetch(url, { signal: sig });
64+
65+ if (!response.ok) {
66+ throw new Error(`Failed to fetch the model page: ${response.statusText}`);
9167 }
92- return undefined;
68+
69+ // First, read the response body as an ArrayBuffer to compute the digest
70+ const buffer = await response.arrayBuffer();
71+ const digest = getDigest(buffer);
72+
73+ // Then, decode the ArrayBuffer into a string and parse it as JSON
74+ const text = new TextDecoder().decode(buffer);
75+ const manifest = JSON.parse(text) as {
76+ config: { size: number };
77+ layers: { size: number }[];
78+ };
79+ const modelSize =
80+ manifest.config.size +
81+ manifest.layers.reduce((sum, layer) => sum + layer.size, 0);
82+
83+ const data: ModelInfo = {
84+ id: modelId,
85+ size: modelSize,
86+ digest,
87+ };
88+ // Cache the successful result
89+ return data;
90+ } catch (error) {
91+ console.error(`Error fetching or parsing model info: ${error}`);
92+ } finally {
93+ const elapsed = Date.now() - start;
94+ console.log(`Fetched remote information for ${modelId} in ${elapsed} ms`);
9395 }
96+ return undefined;
97+}
9498
95- function getDigest(buffer: ArrayBuffer): string {
96- const hash = crypto.createHash("sha256");
97- hash.update(new Uint8Array(buffer));
98- return hash.digest("hex");
99- }
No newline at the end of the file
99+function getDigest(buffer: ArrayBuffer): string {
100+ const hash = crypto.createHash("sha256");
101+ hash.update(new Uint8Array(buffer));
102+ return hash.digest("hex");
103+}
modified core/util/processTerminalBackgroundStates.test.ts +31 −29
@@ -1,71 +1,73 @@
11 import {
22 markProcessAsBackgrounded,
33 isProcessBackgrounded,
4- removeBackgroundedProcess
5-} from './processTerminalBackgroundStates';
4+ removeBackgroundedProcess,
5+} from "./processTerminalBackgroundStates";
66
7-describe('processTerminalBackgroundStates', () => {
7+describe("processTerminalBackgroundStates", () => {
88 beforeEach(() => {
99 // Clear any backgrounded processes before each test
1010 const backgroundedProcesses = Array.from(
11- Object.getOwnPropertySymbols(global)
12- ).find(symbol => String(symbol) === 'Symbol(processTerminalBackgroundStates)');
13-
11+ Object.getOwnPropertySymbols(global),
12+ ).find(
13+ (symbol) => String(symbol) === "Symbol(processTerminalBackgroundStates)",
14+ );
15+
1416 if (backgroundedProcesses) {
1517 // Reset the map by reimporting the module
1618 jest.resetModules();
1719 }
1820 });
1921
20- test('should mark a process as backgrounded', () => {
21- const toolCallId = 'test-123';
22+ test("should mark a process as backgrounded", () => {
23+ const toolCallId = "test-123";
2224 markProcessAsBackgrounded(toolCallId);
2325 expect(isProcessBackgrounded(toolCallId)).toBe(true);
2426 });
2527
26- test('should correctly identify non-backgrounded processes', () => {
27- const toolCallId = 'test-123';
28- const anotherToolCallId = 'test-456';
29-
28+ test("should correctly identify non-backgrounded processes", () => {
29+ const toolCallId = "test-123";
30+ const anotherToolCallId = "test-456";
31+
3032 markProcessAsBackgrounded(toolCallId);
31-
33+
3234 expect(isProcessBackgrounded(toolCallId)).toBe(true);
3335 expect(isProcessBackgrounded(anotherToolCallId)).toBe(false);
3436 });
3537
36- test('should remove a process from backgrounded state', () => {
37- const toolCallId = 'test-123';
38-
38+ test("should remove a process from backgrounded state", () => {
39+ const toolCallId = "test-123";
40+
3941 markProcessAsBackgrounded(toolCallId);
4042 expect(isProcessBackgrounded(toolCallId)).toBe(true);
41-
43+
4244 removeBackgroundedProcess(toolCallId);
4345 expect(isProcessBackgrounded(toolCallId)).toBe(false);
4446 });
4547
46- test('should handle removing non-existent processes', () => {
47- const toolCallId = 'test-123';
48-
48+ test("should handle removing non-existent processes", () => {
49+ const toolCallId = "test-123";
50+
4951 // Should not throw an error
5052 removeBackgroundedProcess(toolCallId);
5153 expect(isProcessBackgrounded(toolCallId)).toBe(false);
5254 });
5355
54- test('should handle multiple processes', () => {
55- const toolCallId1 = 'test-123';
56- const toolCallId2 = 'test-456';
57- const toolCallId3 = 'test-789';
58-
56+ test("should handle multiple processes", () => {
57+ const toolCallId1 = "test-123";
58+ const toolCallId2 = "test-456";
59+ const toolCallId3 = "test-789";
60+
5961 markProcessAsBackgrounded(toolCallId1);
6062 markProcessAsBackgrounded(toolCallId2);
61-
63+
6264 expect(isProcessBackgrounded(toolCallId1)).toBe(true);
6365 expect(isProcessBackgrounded(toolCallId2)).toBe(true);
6466 expect(isProcessBackgrounded(toolCallId3)).toBe(false);
65-
67+
6668 removeBackgroundedProcess(toolCallId1);
67-
69+
6870 expect(isProcessBackgrounded(toolCallId1)).toBe(false);
6971 expect(isProcessBackgrounded(toolCallId2)).toBe(true);
7072 });
71-});
No newline at the end of the file
73+});
modified core/util/processTerminalBackgroundStates.ts +1 −1
@@ -14,4 +14,4 @@
1414 // Function to remove a process from the backgrounded processes map
1515 export function removeBackgroundedProcess(toolCallId: string): void {
1616 processTerminalBackgroundStates.delete(toolCallId);
17-}
No newline at the end of the file
17+}
modified core/vendor/modules/.package-lock.json +1 −5
@@ -383,11 +383,7 @@
383383 "resolved": "https://registry.npmjs.org/onnxruntime-node/-/onnxruntime-node-1.14.0.tgz",
384384 "integrity": "sha512-5ba7TWomIV/9b6NH/1x/8QEeowsb+jBEvFzU6z0T4mNsFwdPqXeFUM7uxC6QeSRkEbWu3qEB0VMjrvzN/0S9+w==",
385385 "optional": true,
386- "os": [
387- "win32",
388- "darwin",
389- "linux"
390- ],
386+ "os": ["win32", "darwin", "linux"],
391387 "dependencies": {
392388 "onnxruntime-common": "~1.14.0"
393389 }
modified core/vendor/modules/@xenova/transformers/README.md +86 −100
@@ -1,5 +1,3 @@
1-
2-
31 <p align="center">
42 <br/>
53 <picture>
@@ -28,23 +26,21 @@
2826 </a>
2927 </p>
3028
31-
3229 State-of-the-art Machine Learning for the web. Run 🤗 Transformers directly in your browser, with no need for a server!
3330
3431 Transformers.js is designed to be functionally equivalent to Hugging Face's [transformers](https://github.com/huggingface/transformers) python library, meaning you can run the same pretrained models using a very similar API. These models support common tasks in different modalities, such as:
35- - 📝 **Natural Language Processing**: text classification, named entity recognition, question answering, language modeling, summarization, translation, multiple choice, and text generation.
36- - 🖼️ **Computer Vision**: image classification, object detection, and segmentation.
37- - 🗣️ **Audio**: automatic speech recognition and audio classification.
38- - 🐙 **Multimodal**: zero-shot image classification.
3932
40-Transformers.js uses [ONNX Runtime](https://onnxruntime.ai/) to run models in the browser. The best part about it, is that you can easily [convert](#convert-your-models-to-onnx) your pretrained PyTorch, TensorFlow, or JAX models to ONNX using [🤗 Optimum](https://github.com/huggingface/optimum#onnx--onnx-runtime).
33+- 📝 **Natural Language Processing**: text classification, named entity recognition, question answering, language modeling, summarization, translation, multiple choice, and text generation.
34+- 🖼️ **Computer Vision**: image classification, object detection, and segmentation.
35+- 🗣️ **Audio**: automatic speech recognition and audio classification.
36+- 🐙 **Multimodal**: zero-shot image classification.
4137
42-For more information, check out the full [documentation](https://huggingface.co/docs/transformers.js).
38+Transformers.js uses [ONNX Runtime](https://onnxruntime.ai/) to run models in the browser. The best part about it, is that you can easily [convert](#convert-your-models-to-onnx) your pretrained PyTorch, TensorFlow, or JAX models to ONNX using [🤗 Optimum](https://github.com/huggingface/optimum#onnx--onnx-runtime).
4339
40+For more information, check out the full [documentation](https://huggingface.co/docs/transformers.js).
4441
4542 ## Quick tour
4643
47-
4844 It's super simple to translate from existing code! Just like the python library, we support the `pipeline` API. Pipelines group together a pretrained model with preprocessing of inputs and postprocessing of outputs, making it the easiest way to run models with the library.
4945
5046 <table>
@@ -69,12 +65,12 @@
6965 <td>
7066
7167 ```javascript
72-import { pipeline } from '@xenova/transformers';
68+import { pipeline } from "@xenova/transformers";
7369
7470 // Allocate a pipeline for sentiment-analysis
75-let pipe = await pipeline('sentiment-analysis');
71+let pipe = await pipeline("sentiment-analysis");
7672
77-let out = await pipe('I love transformers!');
73+let out = await pipe("I love transformers!");
7874 // [{'label': 'POSITIVE', 'score': 0.999817686}]
7975 ```
8076
@@ -82,74 +78,72 @@
8278 </tr>
8379 </table>
8480
85-
8681 You can also use a different model by specifying the model id or path as the second argument to the `pipeline` function. For example:
82+
8783 ```javascript
8884 // Use a different model for sentiment-analysis
89-let pipe = await pipeline('sentiment-analysis', 'Xenova/bert-base-multilingual-uncased-sentiment');
85+let pipe = await pipeline(
86+ "sentiment-analysis",
87+ "Xenova/bert-base-multilingual-uncased-sentiment",
88+);
9089 ```
9190
92-
9391 ## Installation
9492
95-
9693 To install via [NPM](https://www.npmjs.com/package/@xenova/transformers), run:
94+
9795 ```bash
9896 npm i @xenova/transformers
9997 ```
10098
10199 Alternatively, you can use it in vanilla JS, without any bundler, by using a CDN or static hosting. For example, using [ES Modules](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules), you can import the library with:
100+
102101 ```html
103102 <script type="module">
104- import { pipeline } from 'https://cdn.jsdelivr.net/npm/@xenova/transformers@2.14.0';
103+ import { pipeline } from "https://cdn.jsdelivr.net/npm/@xenova/transformers@2.14.0";
105104 </script>
106105 ```
107106
108-
109107 ## Examples
110108
111109 Want to jump straight in? Get started with one of our sample applications/templates:
112110
113-| Name | Description | Links |
114-|-------------------|----------------------------------|-------------------------------|
115-| Whisper Web | Speech recognition w/ Whisper | [code](https://github.com/xenova/whisper-web), [demo](https://huggingface.co/spaces/Xenova/whisper-web) |
116-| Doodle Dash | Real-time sketch-recognition game | [blog](https://huggingface.co/blog/ml-web-games), [code](https://github.com/xenova/doodle-dash), [demo](https://huggingface.co/spaces/Xenova/doodle-dash) |
117-| Code Playground | In-browser code completion website | [code](./examples/code-completion/), [demo](https://huggingface.co/spaces/Xenova/ai-code-playground) |
118-| Semantic Image Search (client-side) | Search for images with text | [code](./examples/semantic-image-search-client/), [demo](https://huggingface.co/spaces/Xenova/semantic-image-search-client) |
119-| Semantic Image Search (server-side) | Search for images with text (Supabase) | [code](./examples/semantic-image-search/), [demo](https://huggingface.co/spaces/Xenova/semantic-image-search) |
120-| Vanilla JavaScript | In-browser object detection | [video](https://scrimba.com/scrim/cKm9bDAg), [code](./examples/vanilla-js/), [demo](https://huggingface.co/spaces/Scrimba/vanilla-js-object-detector) |
121-| React | Multilingual translation website | [code](./examples/react-translator/), [demo](https://huggingface.co/spaces/Xenova/react-translator) |
122-| Text to speech (client-side) | In-browser speech synthesis | [code](./examples/text-to-speech-client/), [demo](https://huggingface.co/spaces/Xenova/text-to-speech-client) |
123-| Browser extension | Text classification extension | [code](./examples/extension/) |
124-| Electron | Text classification application | [code](./examples/electron/) |
125-| Next.js (client-side) | Sentiment analysis (in-browser inference) | [code](./examples/next-client/), [demo](https://huggingface.co/spaces/Xenova/next-example-app) |
126-| Next.js (server-side) | Sentiment analysis (Node.js inference) | [code](./examples/next-server/), [demo](https://huggingface.co/spaces/Xenova/next-server-example-app) |
127-| Node.js | Sentiment analysis API | [code](./examples/node/) |
128-| Demo site | A collection of demos | [code](./examples/demo-site/), [demo](https://xenova.github.io/transformers.js/) |
111+| Name | Description | Links |
112+| ----------------------------------- | ----------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- |
113+| Whisper Web | Speech recognition w/ Whisper | [code](https://github.com/xenova/whisper-web), [demo](https://huggingface.co/spaces/Xenova/whisper-web) |
114+| Doodle Dash | Real-time sketch-recognition game | [blog](https://huggingface.co/blog/ml-web-games), [code](https://github.com/xenova/doodle-dash), [demo](https://huggingface.co/spaces/Xenova/doodle-dash) |
115+| Code Playground | In-browser code completion website | [code](./examples/code-completion/), [demo](https://huggingface.co/spaces/Xenova/ai-code-playground) |
116+| Semantic Image Search (client-side) | Search for images with text | [code](./examples/semantic-image-search-client/), [demo](https://huggingface.co/spaces/Xenova/semantic-image-search-client) |
117+| Semantic Image Search (server-side) | Search for images with text (Supabase) | [code](./examples/semantic-image-search/), [demo](https://huggingface.co/spaces/Xenova/semantic-image-search) |
118+| Vanilla JavaScript | In-browser object detection | [video](https://scrimba.com/scrim/cKm9bDAg), [code](./examples/vanilla-js/), [demo](https://huggingface.co/spaces/Scrimba/vanilla-js-object-detector) |
119+| React | Multilingual translation website | [code](./examples/react-translator/), [demo](https://huggingface.co/spaces/Xenova/react-translator) |
120+| Text to speech (client-side) | In-browser speech synthesis | [code](./examples/text-to-speech-client/), [demo](https://huggingface.co/spaces/Xenova/text-to-speech-client) |
121+| Browser extension | Text classification extension | [code](./examples/extension/) |
122+| Electron | Text classification application | [code](./examples/electron/) |
123+| Next.js (client-side) | Sentiment analysis (in-browser inference) | [code](./examples/next-client/), [demo](https://huggingface.co/spaces/Xenova/next-example-app) |
124+| Next.js (server-side) | Sentiment analysis (Node.js inference) | [code](./examples/next-server/), [demo](https://huggingface.co/spaces/Xenova/next-server-example-app) |
125+| Node.js | Sentiment analysis API | [code](./examples/node/) |
126+| Demo site | A collection of demos | [code](./examples/demo-site/), [demo](https://xenova.github.io/transformers.js/) |
129127
130128 Check out the Transformers.js [template](https://huggingface.co/new-space?template=static-templates%2Ftransformers.js) on Hugging Face to get started in one click!
131129
132-
133130 ## Custom usage
134131
135-
136-
137132 By default, Transformers.js uses [hosted pretrained models](https://huggingface.co/models?library=transformers.js) and [precompiled WASM binaries](https://cdn.jsdelivr.net/npm/@xenova/transformers@2.14.0/dist/), which should work out-of-the-box. You can customize this as follows:
138133
139-
140134 ### Settings
141135
142136 ```javascript
143-import { env } from '@xenova/transformers';
137+import { env } from "@xenova/transformers";
144138
145139 // Specify a custom location for models (defaults to '/models/').
146-env.localModelPath = '/path/to/models/';
140+env.localModelPath = "/path/to/models/";
147141
148142 // Disable the loading of remote models from the Hugging Face Hub:
149143 env.allowRemoteModels = false;
150144
151145 // Set location of .wasm files. Defaults to use a CDN.
152-env.backends.onnx.wasm.wasmPaths = '/path/to/files/';
146+env.backends.onnx.wasm.wasmPaths = "/path/to/files/";
153147 ```
154148
155149 For a full list of available settings, check out the [API Reference](https://huggingface.co/docs/transformers.js/api/env).
@@ -163,6 +157,7 @@
163157 ```
164158
165159 For example, convert and quantize [bert-base-uncased](https://huggingface.co/bert-base-uncased) using:
160+
166161 ```bash
167162 python -m scripts.convert --quantize --model_id bert-base-uncased
168163 ```
@@ -181,7 +176,6 @@
181176
182177 For the full list of supported architectures, see the [Optimum documentation](https://huggingface.co/docs/optimum/main/en/exporters/onnx/overview).
183178
184-
185179 ## Supported tasks/models
186180
187181 Here is the list of all tasks and architectures currently supported by Transformers.js.
@@ -191,78 +185,72 @@
191185 To find compatible models on the Hub, select the "transformers.js" library tag in the filter menu (or visit [this link](https://huggingface.co/models?library=transformers.js)).
192186 You can refine your search by selecting the task you're interested in (e.g., [text-classification](https://huggingface.co/models?pipeline_tag=text-classification&library=transformers.js)).
193187
194-
195188 ### Tasks
196189
197190 #### Natural Language Processing
198191
199-| Task | ID | Description | Supported? |
200-|--------------------------|----|-------------|------------|
201-| [Conversational](https://huggingface.co/tasks/conversational) | `conversational` | Generating conversational text that is relevant, coherent and knowledgable given a prompt. | ❌ |
202-| [Fill-Mask](https://huggingface.co/tasks/fill-mask) | `fill-mask` | Masking some of the words in a sentence and predicting which words should replace those masks. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.FillMaskPipeline)<br>[(models)](https://huggingface.co/models?pipeline_tag=fill-mask&library=transformers.js) |
203-| [Question Answering](https://huggingface.co/tasks/question-answering) | `question-answering` | Retrieve the answer to a question from a given text. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.QuestionAnsweringPipeline)<br>[(models)](https://huggingface.co/models?pipeline_tag=question-answering&library=transformers.js) |
204-| [Sentence Similarity](https://huggingface.co/tasks/sentence-similarity) | `sentence-similarity` | Determining how similar two texts are. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.FeatureExtractionPipeline)<br>[(models)](https://huggingface.co/models?pipeline_tag=feature-extraction&library=transformers.js) |
205-| [Summarization](https://huggingface.co/tasks/summarization) | `summarization` | Producing a shorter version of a document while preserving its important information. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.SummarizationPipeline)<br>[(models)](https://huggingface.co/models?pipeline_tag=summarization&library=transformers.js) |
206-| [Table Question Answering](https://huggingface.co/tasks/table-question-answering) | `table-question-answering` | Answering a question about information from a given table. | ❌ |
207-| [Text Classification](https://huggingface.co/tasks/text-classification) | `text-classification` or `sentiment-analysis` | Assigning a label or class to a given text. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.TextClassificationPipeline)<br>[(models)](https://huggingface.co/models?pipeline_tag=text-classification&library=transformers.js) |
208-| [Text Generation](https://huggingface.co/tasks/text-generation#completion-generation-models) | `text-generation` | Producing new text by predicting the next word in a sequence. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.TextGenerationPipeline)<br>[(models)](https://huggingface.co/models?pipeline_tag=text-generation&library=transformers.js) |
209-| [Text-to-text Generation](https://huggingface.co/tasks/text-generation#text-to-text-generation-models) | `text2text-generation` | Converting one text sequence into another text sequence. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.Text2TextGenerationPipeline)<br>[(models)](https://huggingface.co/models?pipeline_tag=text2text-generation&library=transformers.js) |
210-| [Token Classification](https://huggingface.co/tasks/token-classification) | `token-classification` or `ner` | Assigning a label to each token in a text. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.TokenClassificationPipeline)<br>[(models)](https://huggingface.co/models?pipeline_tag=token-classification&library=transformers.js) |
211-| [Translation](https://huggingface.co/tasks/translation) | `translation` | Converting text from one language to another. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.TranslationPipeline)<br>[(models)](https://huggingface.co/models?pipeline_tag=translation&library=transformers.js) |
212-| [Zero-Shot Classification](https://huggingface.co/tasks/zero-shot-classification) | `zero-shot-classification` | Classifying text into classes that are unseen during training. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.ZeroShotClassificationPipeline)<br>[(models)](https://huggingface.co/models?pipeline_tag=zero-shot-classification&library=transformers.js) |
192+| Task | ID | Description | Supported? |
193+| ------------------------------------------------------------------------------------------------------ | --------------------------------------------- | ---------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
194+| [Conversational](https://huggingface.co/tasks/conversational) | `conversational` | Generating conversational text that is relevant, coherent and knowledgable given a prompt. | ❌ |
195+| [Fill-Mask](https://huggingface.co/tasks/fill-mask) | `fill-mask` | Masking some of the words in a sentence and predicting which words should replace those masks. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.FillMaskPipeline)<br>[(models)](https://huggingface.co/models?pipeline_tag=fill-mask&library=transformers.js) |
196+| [Question Answering](https://huggingface.co/tasks/question-answering) | `question-answering` | Retrieve the answer to a question from a given text. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.QuestionAnsweringPipeline)<br>[(models)](https://huggingface.co/models?pipeline_tag=question-answering&library=transformers.js) |
197+| [Sentence Similarity](https://huggingface.co/tasks/sentence-similarity) | `sentence-similarity` | Determining how similar two texts are. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.FeatureExtractionPipeline)<br>[(models)](https://huggingface.co/models?pipeline_tag=feature-extraction&library=transformers.js) |
198+| [Summarization](https://huggingface.co/tasks/summarization) | `summarization` | Producing a shorter version of a document while preserving its important information. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.SummarizationPipeline)<br>[(models)](https://huggingface.co/models?pipeline_tag=summarization&library=transformers.js) |
199+| [Table Question Answering](https://huggingface.co/tasks/table-question-answering) | `table-question-answering` | Answering a question about information from a given table. | ❌ |
200+| [Text Classification](https://huggingface.co/tasks/text-classification) | `text-classification` or `sentiment-analysis` | Assigning a label or class to a given text. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.TextClassificationPipeline)<br>[(models)](https://huggingface.co/models?pipeline_tag=text-classification&library=transformers.js) |
201+| [Text Generation](https://huggingface.co/tasks/text-generation#completion-generation-models) | `text-generation` | Producing new text by predicting the next word in a sequence. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.TextGenerationPipeline)<br>[(models)](https://huggingface.co/models?pipeline_tag=text-generation&library=transformers.js) |
202+| [Text-to-text Generation](https://huggingface.co/tasks/text-generation#text-to-text-generation-models) | `text2text-generation` | Converting one text sequence into another text sequence. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.Text2TextGenerationPipeline)<br>[(models)](https://huggingface.co/models?pipeline_tag=text2text-generation&library=transformers.js) |
203+| [Token Classification](https://huggingface.co/tasks/token-classification) | `token-classification` or `ner` | Assigning a label to each token in a text. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.TokenClassificationPipeline)<br>[(models)](https://huggingface.co/models?pipeline_tag=token-classification&library=transformers.js) |
204+| [Translation](https://huggingface.co/tasks/translation) | `translation` | Converting text from one language to another. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.TranslationPipeline)<br>[(models)](https://huggingface.co/models?pipeline_tag=translation&library=transformers.js) |
205+| [Zero-Shot Classification](https://huggingface.co/tasks/zero-shot-classification) | `zero-shot-classification` | Classifying text into classes that are unseen during training. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.ZeroShotClassificationPipeline)<br>[(models)](https://huggingface.co/models?pipeline_tag=zero-shot-classification&library=transformers.js) |
213206
214207 #### Vision
215208
216-| Task | ID | Description | Supported? |
217-|--------------------------|----|-------------|------------|
218-| [Depth Estimation](https://huggingface.co/tasks/depth-estimation) | `depth-estimation` | Predicting the depth of objects present in an image. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.DepthEstimationPipeline)<br>[(models)](https://huggingface.co/models?pipeline_tag=depth-estimation&library=transformers.js) |
219-| [Image Classification](https://huggingface.co/tasks/image-classification) | `image-classification` | Assigning a label or class to an entire image. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.ImageClassificationPipeline)<br>[(models)](https://huggingface.co/models?pipeline_tag=image-classification&library=transformers.js) |
220-| [Image Segmentation](https://huggingface.co/tasks/image-segmentation) | `image-segmentation` | Divides an image into segments where each pixel is mapped to an object. This task has multiple variants such as instance segmentation, panoptic segmentation and semantic segmentation. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.ImageSegmentationPipeline)<br>[(models)](https://huggingface.co/models?pipeline_tag=image-segmentation&library=transformers.js) |
221-| [Image-to-Image](https://huggingface.co/tasks/image-to-image) | `image-to-image` | Transforming a source image to match the characteristics of a target image or a target image domain. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.ImageToImagePipeline)<br>[(models)](https://huggingface.co/models?pipeline_tag=image-to-image&library=transformers.js) |
222-| [Mask Generation](https://huggingface.co/tasks/mask-generation) | `mask-generation` | Generate masks for the objects in an image. | ❌ |
223-| [Object Detection](https://huggingface.co/tasks/object-detection) | `object-detection` | Identify objects of certain defined classes within an image. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.ObjectDetectionPipeline)<br>[(models)](https://huggingface.co/models?pipeline_tag=object-detection&library=transformers.js) |
224-| [Video Classification](https://huggingface.co/tasks/video-classification) | n/a | Assigning a label or class to an entire video. | ❌ |
225-| [Unconditional Image Generation](https://huggingface.co/tasks/unconditional-image-generation) | n/a | Generating images with no condition in any context (like a prompt text or another image). | ❌ |
209+| Task | ID | Description | Supported? |
210+| --------------------------------------------------------------------------------------------- | ---------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
211+| [Depth Estimation](https://huggingface.co/tasks/depth-estimation) | `depth-estimation` | Predicting the depth of objects present in an image. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.DepthEstimationPipeline)<br>[(models)](https://huggingface.co/models?pipeline_tag=depth-estimation&library=transformers.js) |
212+| [Image Classification](https://huggingface.co/tasks/image-classification) | `image-classification` | Assigning a label or class to an entire image. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.ImageClassificationPipeline)<br>[(models)](https://huggingface.co/models?pipeline_tag=image-classification&library=transformers.js) |
213+| [Image Segmentation](https://huggingface.co/tasks/image-segmentation) | `image-segmentation` | Divides an image into segments where each pixel is mapped to an object. This task has multiple variants such as instance segmentation, panoptic segmentation and semantic segmentation. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.ImageSegmentationPipeline)<br>[(models)](https://huggingface.co/models?pipeline_tag=image-segmentation&library=transformers.js) |
214+| [Image-to-Image](https://huggingface.co/tasks/image-to-image) | `image-to-image` | Transforming a source image to match the characteristics of a target image or a target image domain. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.ImageToImagePipeline)<br>[(models)](https://huggingface.co/models?pipeline_tag=image-to-image&library=transformers.js) |
215+| [Mask Generation](https://huggingface.co/tasks/mask-generation) | `mask-generation` | Generate masks for the objects in an image. | ❌ |
216+| [Object Detection](https://huggingface.co/tasks/object-detection) | `object-detection` | Identify objects of certain defined classes within an image. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.ObjectDetectionPipeline)<br>[(models)](https://huggingface.co/models?pipeline_tag=object-detection&library=transformers.js) |
217+| [Video Classification](https://huggingface.co/tasks/video-classification) | n/a | Assigning a label or class to an entire video. | ❌ |
218+| [Unconditional Image Generation](https://huggingface.co/tasks/unconditional-image-generation) | n/a | Generating images with no condition in any context (like a prompt text or another image). | ❌ |
226219
227220 #### Audio
228221
229-| Task | ID | Description | Supported? |
230-|--------------------------|----|-------------|------------|
231-| [Audio Classification](https://huggingface.co/tasks/audio-classification) | `audio-classification` | Assigning a label or class to a given audio. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.AudioClassificationPipeline)<br>[(models)](https://huggingface.co/models?pipeline_tag=audio-classification&library=transformers.js) |
232-| [Audio-to-Audio](https://huggingface.co/tasks/audio-to-audio) | n/a | Generating audio from an input audio source. | ❌ |
233-| [Automatic Speech Recognition](https://huggingface.co/tasks/automatic-speech-recognition) | `automatic-speech-recognition` | Transcribing a given audio into text. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.AutomaticSpeechRecognitionPipeline)<br>[(models)](https://huggingface.co/models?pipeline_tag=automatic-speech-recognition&library=transformers.js) |
234-| [Text-to-Speech](https://huggingface.co/tasks/text-to-speech) | `text-to-speech` or `text-to-audio` | Generating natural-sounding speech given text input. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.TextToAudioPipeline)<br>[(models)](https://huggingface.co/models?pipeline_tag=text-to-audio&library=transformers.js) |
235-
222+| Task | ID | Description | Supported? |
223+| ----------------------------------------------------------------------------------------- | ----------------------------------- | ---------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
224+| [Audio Classification](https://huggingface.co/tasks/audio-classification) | `audio-classification` | Assigning a label or class to a given audio. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.AudioClassificationPipeline)<br>[(models)](https://huggingface.co/models?pipeline_tag=audio-classification&library=transformers.js) |
225+| [Audio-to-Audio](https://huggingface.co/tasks/audio-to-audio) | n/a | Generating audio from an input audio source. | ❌ |
226+| [Automatic Speech Recognition](https://huggingface.co/tasks/automatic-speech-recognition) | `automatic-speech-recognition` | Transcribing a given audio into text. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.AutomaticSpeechRecognitionPipeline)<br>[(models)](https://huggingface.co/models?pipeline_tag=automatic-speech-recognition&library=transformers.js) |
227+| [Text-to-Speech](https://huggingface.co/tasks/text-to-speech) | `text-to-speech` or `text-to-audio` | Generating natural-sounding speech given text input. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.TextToAudioPipeline)<br>[(models)](https://huggingface.co/models?pipeline_tag=text-to-audio&library=transformers.js) |
236228
237229 #### Tabular
238230
239-| Task | ID | Description | Supported? |
240-|--------------------------|----|-------------|------------|
241-| [Tabular Classification](https://huggingface.co/tasks/tabular-classification) | n/a | Classifying a target category (a group) based on set of attributes. | ❌ |
242-| [Tabular Regression](https://huggingface.co/tasks/tabular-regression) | n/a | Predicting a numerical value given a set of attributes. | ❌ |
243-
231+| Task | ID | Description | Supported? |
232+| ----------------------------------------------------------------------------- | --- | ------------------------------------------------------------------- | ---------- |
233+| [Tabular Classification](https://huggingface.co/tasks/tabular-classification) | n/a | Classifying a target category (a group) based on set of attributes. | ❌ |
234+| [Tabular Regression](https://huggingface.co/tasks/tabular-regression) | n/a | Predicting a numerical value given a set of attributes. | ❌ |
244235
245236 #### Multimodal
246237
247-| Task | ID | Description | Supported? |
248-|--------------------------|----|-------------|------------|
249-| [Document Question Answering](https://huggingface.co/tasks/document-question-answering) | `document-question-answering` | Answering questions on document images. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.DocumentQuestionAnsweringPipeline)<br>[(models)](https://huggingface.co/models?pipeline_tag=document-question-answering&library=transformers.js) |
250-| [Feature Extraction](https://huggingface.co/tasks/feature-extraction) | `feature-extraction` | Transforming raw data into numerical features that can be processed while preserving the information in the original dataset. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.FeatureExtractionPipeline)<br>[(models)](https://huggingface.co/models?pipeline_tag=feature-extraction&library=transformers.js) |
251-| [Image-to-Text](https://huggingface.co/tasks/image-to-text) | `image-to-text` | Output text from a given image. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.ImageToTextPipeline)<br>[(models)](https://huggingface.co/models?pipeline_tag=image-to-text&library=transformers.js) |
252-| [Text-to-Image](https://huggingface.co/tasks/text-to-image) | `text-to-image` | Generates images from input text. | ❌ |
253-| [Visual Question Answering](https://huggingface.co/tasks/visual-question-answering) | `visual-question-answering` | Answering open-ended questions based on an image. | ❌ |
254-| [Zero-Shot Audio Classification](https://huggingface.co/learn/audio-course/chapter4/classification_models#zero-shot-audio-classification) | `zero-shot-audio-classification` | Classifying audios into classes that are unseen during training. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.ZeroShotAudioClassificationPipeline)<br>[(models)](https://huggingface.co/models?other=zero-shot-audio-classification&library=transformers.js) |
255-| [Zero-Shot Image Classification](https://huggingface.co/tasks/zero-shot-image-classification) | `zero-shot-image-classification` | Classifying images into classes that are unseen during training. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.ZeroShotImageClassificationPipeline)<br>[(models)](https://huggingface.co/models?pipeline_tag=zero-shot-image-classification&library=transformers.js) |
256-| [Zero-Shot Object Detection](https://huggingface.co/tasks/zero-shot-object-detection) | `zero-shot-object-detection` | Identify objects of classes that are unseen during training. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.ZeroShotObjectDetectionPipeline)<br>[(models)](https://huggingface.co/models?other=zero-shot-object-detection&library=transformers.js) |
257-
238+| Task | ID | Description | Supported? |
239+| ----------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------- | ----------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
240+| [Document Question Answering](https://huggingface.co/tasks/document-question-answering) | `document-question-answering` | Answering questions on document images. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.DocumentQuestionAnsweringPipeline)<br>[(models)](https://huggingface.co/models?pipeline_tag=document-question-answering&library=transformers.js) |
241+| [Feature Extraction](https://huggingface.co/tasks/feature-extraction) | `feature-extraction` | Transforming raw data into numerical features that can be processed while preserving the information in the original dataset. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.FeatureExtractionPipeline)<br>[(models)](https://huggingface.co/models?pipeline_tag=feature-extraction&library=transformers.js) |
242+| [Image-to-Text](https://huggingface.co/tasks/image-to-text) | `image-to-text` | Output text from a given image. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.ImageToTextPipeline)<br>[(models)](https://huggingface.co/models?pipeline_tag=image-to-text&library=transformers.js) |
243+| [Text-to-Image](https://huggingface.co/tasks/text-to-image) | `text-to-image` | Generates images from input text. | ❌ |
244+| [Visual Question Answering](https://huggingface.co/tasks/visual-question-answering) | `visual-question-answering` | Answering open-ended questions based on an image. | ❌ |
245+| [Zero-Shot Audio Classification](https://huggingface.co/learn/audio-course/chapter4/classification_models#zero-shot-audio-classification) | `zero-shot-audio-classification` | Classifying audios into classes that are unseen during training. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.ZeroShotAudioClassificationPipeline)<br>[(models)](https://huggingface.co/models?other=zero-shot-audio-classification&library=transformers.js) |
246+| [Zero-Shot Image Classification](https://huggingface.co/tasks/zero-shot-image-classification) | `zero-shot-image-classification` | Classifying images into classes that are unseen during training. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.ZeroShotImageClassificationPipeline)<br>[(models)](https://huggingface.co/models?pipeline_tag=zero-shot-image-classification&library=transformers.js) |
247+| [Zero-Shot Object Detection](https://huggingface.co/tasks/zero-shot-object-detection) | `zero-shot-object-detection` | Identify objects of classes that are unseen during training. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.ZeroShotObjectDetectionPipeline)<br>[(models)](https://huggingface.co/models?other=zero-shot-object-detection&library=transformers.js) |
258248
259249 #### Reinforcement Learning
260250
261-| Task | ID | Description | Supported? |
262-|--------------------------|----|-------------|------------|
263-| [Reinforcement Learning](https://huggingface.co/tasks/reinforcement-learning) | n/a | Learning from actions by interacting with an environment through trial and error and receiving rewards (negative or positive) as feedback. | ❌ |
264-
265-
251+| Task | ID | Description | Supported? |
252+| ----------------------------------------------------------------------------- | --- | ------------------------------------------------------------------------------------------------------------------------------------------ | ---------- |
253+| [Reinforcement Learning](https://huggingface.co/tasks/reinforcement-learning) | n/a | Learning from actions by interacting with an environment through trial and error and receiving rewards (negative or positive) as feedback. | ❌ |
266254
267255 ### Models
268256
@@ -274,7 +262,7 @@
274262 1. **[Blenderbot](https://huggingface.co/docs/transformers/model_doc/blenderbot)** (from Facebook) released with the paper [Recipes for building an open-domain chatbot](https://arxiv.org/abs/2004.13637) by Stephen Roller, Emily Dinan, Naman Goyal, Da Ju, Mary Williamson, Yinhan Liu, Jing Xu, Myle Ott, Kurt Shuster, Eric M. Smith, Y-Lan Boureau, Jason Weston.
275263 1. **[BlenderbotSmall](https://huggingface.co/docs/transformers/model_doc/blenderbot-small)** (from Facebook) released with the paper [Recipes for building an open-domain chatbot](https://arxiv.org/abs/2004.13637) by Stephen Roller, Emily Dinan, Naman Goyal, Da Ju, Mary Williamson, Yinhan Liu, Jing Xu, Myle Ott, Kurt Shuster, Eric M. Smith, Y-Lan Boureau, Jason Weston.
276264 1. **[BLOOM](https://huggingface.co/docs/transformers/model_doc/bloom)** (from BigScience workshop) released by the [BigScience Workshop](https://bigscience.huggingface.co/).
277-1. **[CamemBERT](https://huggingface.co/docs/transformers/model_doc/camembert)** (from Inria/Facebook/Sorbonne) released with the paper [CamemBERT: a Tasty French Language Model](https://arxiv.org/abs/1911.03894) by Louis Martin*, Benjamin Muller*, Pedro Javier Ortiz Suárez*, Yoann Dupont, Laurent Romary, Éric Villemonte de la Clergerie, Djamé Seddah and Benoît Sagot.
265+1. **[CamemBERT](https://huggingface.co/docs/transformers/model_doc/camembert)** (from Inria/Facebook/Sorbonne) released with the paper [CamemBERT: a Tasty French Language Model](https://arxiv.org/abs/1911.03894) by Louis Martin*, Benjamin Muller*, Pedro Javier Ortiz Suárez\*, Yoann Dupont, Laurent Romary, Éric Villemonte de la Clergerie, Djamé Seddah and Benoît Sagot.
278266 1. **[Chinese-CLIP](https://huggingface.co/docs/transformers/model_doc/chinese_clip)** (from OFA-Sys) released with the paper [Chinese CLIP: Contrastive Vision-Language Pretraining in Chinese](https://arxiv.org/abs/2211.01335) by An Yang, Junshu Pan, Junyang Lin, Rui Men, Yichang Zhang, Jingren Zhou, Chang Zhou.
279267 1. **[CLAP](https://huggingface.co/docs/transformers/model_doc/clap)** (from LAION-AI) released with the paper [Large-scale Contrastive Language-Audio Pretraining with Feature Fusion and Keyword-to-Caption Augmentation](https://arxiv.org/abs/2211.06687) by Yusong Wu, Ke Chen, Tianyu Zhang, Yuchen Hui, Taylor Berg-Kirkpatrick, Shlomo Dubnov.
280268 1. **[CLIP](https://huggingface.co/docs/transformers/model_doc/clip)** (from OpenAI) released with the paper [Learning Transferable Visual Models From Natural Language Supervision](https://arxiv.org/abs/2103.00020) by Alec Radford, Jong Wook Kim, Chris Hallacy, Aditya Ramesh, Gabriel Goh, Sandhini Agarwal, Girish Sastry, Amanda Askell, Pamela Mishkin, Jack Clark, Gretchen Krueger, Ilya Sutskever.
@@ -294,7 +282,7 @@
294282 1. **[Donut](https://huggingface.co/docs/transformers/model_doc/donut)** (from NAVER), released together with the paper [OCR-free Document Understanding Transformer](https://arxiv.org/abs/2111.15664) by Geewook Kim, Teakgyu Hong, Moonbin Yim, Jeongyeon Nam, Jinyoung Park, Jinyeong Yim, Wonseok Hwang, Sangdoo Yun, Dongyoon Han, Seunghyun Park.
295283 1. **[DPT](https://huggingface.co/docs/transformers/master/model_doc/dpt)** (from Intel Labs) released with the paper [Vision Transformers for Dense Prediction](https://arxiv.org/abs/2103.13413) by René Ranftl, Alexey Bochkovskiy, Vladlen Koltun.
296284 1. **[ELECTRA](https://huggingface.co/docs/transformers/model_doc/electra)** (from Google Research/Stanford University) released with the paper [ELECTRA: Pre-training text encoders as discriminators rather than generators](https://arxiv.org/abs/2003.10555) by Kevin Clark, Minh-Thang Luong, Quoc V. Le, Christopher D. Manning.
297-1. **[ESM](https://huggingface.co/docs/transformers/model_doc/esm)** (from Meta AI) are transformer protein language models. **ESM-1b** was released with the paper [Biological structure and function emerge from scaling unsupervised learning to 250 million protein sequences](https://www.pnas.org/content/118/15/e2016239118) by Alexander Rives, Joshua Meier, Tom Sercu, Siddharth Goyal, Zeming Lin, Jason Liu, Demi Guo, Myle Ott, C. Lawrence Zitnick, Jerry Ma, and Rob Fergus. **ESM-1v** was released with the paper [Language models enable zero-shot prediction of the effects of mutations on protein function](https://doi.org/10.1101/2021.07.09.450648) by Joshua Meier, Roshan Rao, Robert Verkuil, Jason Liu, Tom Sercu and Alexander Rives. **ESM-2 and ESMFold** were released with the paper [Language models of protein sequences at the scale of evolution enable accurate structure prediction](https://doi.org/10.1101/2022.07.20.500902) by Zeming Lin, Halil Akin, Roshan Rao, Brian Hie, Zhongkai Zhu, Wenting Lu, Allan dos Santos Costa, Maryam Fazel-Zarandi, Tom Sercu, Sal Candido, Alexander Rives.
285+1. **[ESM](https://huggingface.co/docs/transformers/model_doc/esm)** (from Meta AI) are transformer protein language models. **ESM-1b** was released with the paper [Biological structure and function emerge from scaling unsupervised learning to 250 million protein sequences](https://www.pnas.org/content/118/15/e2016239118) by Alexander Rives, Joshua Meier, Tom Sercu, Siddharth Goyal, Zeming Lin, Jason Liu, Demi Guo, Myle Ott, C. Lawrence Zitnick, Jerry Ma, and Rob Fergus. **ESM-1v** was released with the paper [Language models enable zero-shot prediction of the effects of mutations on protein function](https://doi.org/10.1101/2021.07.09.450648) by Joshua Meier, Roshan Rao, Robert Verkuil, Jason Liu, Tom Sercu and Alexander Rives. **ESM-2 and ESMFold** were released with the paper [Language models of protein sequences at the scale of evolution enable accurate structure prediction](https://doi.org/10.1101/2022.07.20.500902) by Zeming Lin, Halil Akin, Roshan Rao, Brian Hie, Zhongkai Zhu, Wenting Lu, Allan dos Santos Costa, Maryam Fazel-Zarandi, Tom Sercu, Sal Candido, Alexander Rives.
298286 1. **[Falcon](https://huggingface.co/docs/transformers/model_doc/falcon)** (from Technology Innovation Institute) by Almazrouei, Ebtesam and Alobeidli, Hamza and Alshamsi, Abdulaziz and Cappelli, Alessandro and Cojocaru, Ruxandra and Debbah, Merouane and Goffinet, Etienne and Heslow, Daniel and Launay, Julien and Malartic, Quentin and Noune, Badreddine and Pannier, Baptiste and Penedo, Guilherme.
299287 1. **[FLAN-T5](https://huggingface.co/docs/transformers/model_doc/flan-t5)** (from Google AI) released in the repository [google-research/t5x](https://github.com/google-research/t5x/blob/main/docs/models.md#flan-t5-checkpoints) by Hyung Won Chung, Le Hou, Shayne Longpre, Barret Zoph, Yi Tay, William Fedus, Eric Li, Xuezhi Wang, Mostafa Dehghani, Siddhartha Brahma, Albert Webson, Shixiang Shane Gu, Zhuyun Dai, Mirac Suzgun, Xinyun Chen, Aakanksha Chowdhery, Sharan Narang, Gaurav Mishra, Adams Yu, Vincent Zhao, Yanping Huang, Andrew Dai, Hongkun Yu, Slav Petrov, Ed H. Chi, Jeff Dean, Jacob Devlin, Adam Roberts, Denny Zhou, Quoc V. Le, and Jason Wei
300288 1. **[GLPN](https://huggingface.co/docs/transformers/model_doc/glpn)** (from KAIST) released with the paper [Global-Local Path Networks for Monocular Depth Estimation with Vertical CutDepth](https://arxiv.org/abs/2201.07436) by Doyeon Kim, Woonghyun Ga, Pyungwhan Ahn, Donggyu Joo, Sehwan Chun, Junmo Kim.
@@ -347,5 +335,3 @@
347335 1. **[XLM](https://huggingface.co/docs/transformers/model_doc/xlm)** (from Facebook) released together with the paper [Cross-lingual Language Model Pretraining](https://arxiv.org/abs/1901.07291) by Guillaume Lample and Alexis Conneau.
348336 1. **[XLM-RoBERTa](https://huggingface.co/docs/transformers/model_doc/xlm-roberta)** (from Facebook AI), released together with the paper [Unsupervised Cross-lingual Representation Learning at Scale](https://arxiv.org/abs/1911.02116) by Alexis Conneau*, Kartikay Khandelwal*, Naman Goyal, Vishrav Chaudhary, Guillaume Wenzek, Francisco Guzmán, Edouard Grave, Myle Ott, Luke Zettlemoyer and Veselin Stoyanov.
349337 1. **[YOLOS](https://huggingface.co/docs/transformers/model_doc/yolos)** (from Huazhong University of Science & Technology) released with the paper [You Only Look at One Sequence: Rethinking Transformer in Vision through Object Detection](https://arxiv.org/abs/2106.00666) by Yuxin Fang, Bencheng Liao, Xinggang Wang, Jiemin Fang, Jiyang Qi, Rui Wu, Jianwei Niu, Wenyu Liu.
350-
351-
modified core/vendor/modules/@xenova/transformers/src/backends/onnx.js +22 −21
@@ -6,45 +6,46 @@
66 * So, we just import both packages, and use the appropriate one based on the environment:
77 * - When running in node, we use `onnxruntime-node`.
88 * - When running in the browser, we use `onnxruntime-web` (`onnxruntime-node` is not bundled).
9- *
9+ *
1010 * This module is not directly exported, but can be accessed through the environment variables:
1111 * ```javascript
1212 * import { env } from '@xenova/transformers';
1313 * console.log(env.backends.onnx);
1414 * ```
15- *
15+ *
1616 * @module backends/onnx
1717 */
1818
1919 // NOTE: Import order matters here. We need to import `onnxruntime-node` before `onnxruntime-web`.
2020 // In either case, we select the default export if it exists, otherwise we use the named export.
21-import * as ONNX_NODE from 'onnxruntime-node';
22-import * as ONNX_WEB from 'onnxruntime-web';
21+import * as ONNX_NODE from "onnxruntime-node";
22+import * as ONNX_WEB from "onnxruntime-web";
2323
2424 /** @type {import('onnxruntime-web')} The ONNX runtime module. */
2525 export let ONNX;
2626
2727 export const executionProviders = [
28- // 'webgpu',
29- 'wasm'
28+ // 'webgpu',
29+ "wasm",
3030 ];
3131
32-if (typeof process !== 'undefined' && process?.release?.name === 'node') {
33- // Running in a node-like environment.
34- ONNX = ONNX_NODE.default ?? ONNX_NODE;
35-
36- // Add `cpu` execution provider, with higher precedence that `wasm`.
37- executionProviders.unshift('cpu');
32+if (typeof process !== "undefined" && process?.release?.name === "node") {
33+ // Running in a node-like environment.
34+ ONNX = ONNX_NODE.default ?? ONNX_NODE;
3835
36+ // Add `cpu` execution provider, with higher precedence that `wasm`.
37+ executionProviders.unshift("cpu");
3938 } else {
40- // Running in a browser-environment
41- ONNX = ONNX_WEB.default ?? ONNX_WEB;
39+ // Running in a browser-environment
40+ ONNX = ONNX_WEB.default ?? ONNX_WEB;
4241
43- // SIMD for WebAssembly does not operate correctly in some recent versions of iOS (16.4.x).
44- // As a temporary fix, we disable it for now.
45- // For more information, see: https://github.com/microsoft/onnxruntime/issues/15644
46- const isIOS = typeof navigator !== 'undefined' && /iP(hone|od|ad).+16_4.+AppleWebKit/.test(navigator.userAgent);
47- if (isIOS) {
48- ONNX.env.wasm.simd = false;
49- }
42+ // SIMD for WebAssembly does not operate correctly in some recent versions of iOS (16.4.x).
43+ // As a temporary fix, we disable it for now.
44+ // For more information, see: https://github.com/microsoft/onnxruntime/issues/15644
45+ const isIOS =
46+ typeof navigator !== "undefined" &&
47+ /iP(hone|od|ad).+16_4.+AppleWebKit/.test(navigator.userAgent);
48+ if (isIOS) {
49+ ONNX.env.wasm.simd = false;
50+ }
5051 }
modified core/vendor/modules/@xenova/transformers/src/configs.js +60 −55
@@ -1,10 +1,9 @@
1-
21 /**
32 * @file Helper module for using model configs. For more information, see the corresponding
43 * [Python documentation](https://huggingface.co/docs/transformers/main/en/model_doc/auto#transformers.AutoConfig).
5- *
4+ *
65 * **Example:** Load an `AutoConfig`.
7- *
6+ *
87 * ```javascript
98 * import { AutoConfig } from '@xenova/transformers';
109 * let config = await AutoConfig.from_pretrained('bert-base-uncased');
@@ -23,19 +22,16 @@
2322 * // ...
2423 * // }
2524 * ```
26- *
25+ *
2726 * @module configs
2827 */
2928
30-import {
31- getModelJSON,
32-} from './utils/hub.js';
29+import { getModelJSON } from "./utils/hub.js";
3330
3431 /**
3532 * @typedef {import('./utils/hub.js').PretrainedOptions} PretrainedOptions
3633 */
3734
38-
3935 /**
4036 * Loads a config from the specified path.
4137 * @param {string} pretrained_model_name_or_path The path to the config directory.
@@ -43,8 +39,13 @@
4339 * @returns {Promise<Array>} A promise that resolves with information about the loaded config.
4440 */
4541 async function loadConfig(pretrained_model_name_or_path, options) {
46- let info = await getModelJSON(pretrained_model_name_or_path, 'config.json', true, options);
47- return info;
42+ let info = await getModelJSON(
43+ pretrained_model_name_or_path,
44+ "config.json",
45+ true,
46+ options,
47+ );
48+ return info;
4849 }
4950
5051 /**
@@ -52,56 +53,60 @@
5253 * [Python documentation](https://huggingface.co/docs/transformers/main/en/main_classes/configuration#transformers.PretrainedConfig).
5354 */
5455 export class PretrainedConfig {
55- // NOTE: Typo in original
56-
57- /**
58- * Create a new PreTrainedTokenizer instance.
59- * @param {Object} configJSON The JSON of the config.
60- */
61- constructor(configJSON) {
62- this.model_type = null;
63- this.is_encoder_decoder = false;
64-
65- Object.assign(this, configJSON);
66- }
67-
68- /**
69- * Loads a pre-trained config from the given `pretrained_model_name_or_path`.
70- *
71- * @param {string} pretrained_model_name_or_path The path to the pre-trained config.
72- * @param {PretrainedOptions} options Additional options for loading the config.
73- * @throws {Error} Throws an error if the config.json is not found in the `pretrained_model_name_or_path`.
74- *
75- * @returns {Promise<PretrainedConfig>} A new instance of the `PretrainedConfig` class.
76- */
77- static async from_pretrained(pretrained_model_name_or_path, {
78- progress_callback = null,
79- config = null,
80- cache_dir = null,
81- local_files_only = false,
82- revision = 'main',
83- } = {}) {
84-
85- let data = config ?? await loadConfig(pretrained_model_name_or_path, {
86- progress_callback,
87- config,
88- cache_dir,
89- local_files_only,
90- revision,
91- })
92- return new this(data);
93- }
56+ // NOTE: Typo in original
57+
58+ /**
59+ * Create a new PreTrainedTokenizer instance.
60+ * @param {Object} configJSON The JSON of the config.
61+ */
62+ constructor(configJSON) {
63+ this.model_type = null;
64+ this.is_encoder_decoder = false;
65+
66+ Object.assign(this, configJSON);
67+ }
68+
69+ /**
70+ * Loads a pre-trained config from the given `pretrained_model_name_or_path`.
71+ *
72+ * @param {string} pretrained_model_name_or_path The path to the pre-trained config.
73+ * @param {PretrainedOptions} options Additional options for loading the config.
74+ * @throws {Error} Throws an error if the config.json is not found in the `pretrained_model_name_or_path`.
75+ *
76+ * @returns {Promise<PretrainedConfig>} A new instance of the `PretrainedConfig` class.
77+ */
78+ static async from_pretrained(
79+ pretrained_model_name_or_path,
80+ {
81+ progress_callback = null,
82+ config = null,
83+ cache_dir = null,
84+ local_files_only = false,
85+ revision = "main",
86+ } = {},
87+ ) {
88+ let data =
89+ config ??
90+ (await loadConfig(pretrained_model_name_or_path, {
91+ progress_callback,
92+ config,
93+ cache_dir,
94+ local_files_only,
95+ revision,
96+ }));
97+ return new this(data);
98+ }
9499 }
95100
96101 /**
97102 * Helper class which is used to instantiate pretrained configs with the `from_pretrained` function.
98- *
103+ *
99104 * @example
100- * let config = await AutoConfig.from_pretrained('bert-base-uncased');
105+ * let config = await AutoConfig.from_pretrained('bert-base-uncased');
101106 */
102107 export class AutoConfig {
103- /** @type {PretrainedConfig.from_pretrained} */
104- static async from_pretrained(...args) {
105- return PretrainedConfig.from_pretrained(...args);
106- }
108+ /** @type {PretrainedConfig.from_pretrained} */
109+ static async from_pretrained(...args) {
110+ return PretrainedConfig.from_pretrained(...args);
111+ }
107112 }
modified core/vendor/modules/@xenova/transformers/src/env.js +47 −50
@@ -1,37 +1,37 @@
11 /**
22 * @file Module used to configure Transformers.js.
3- *
3+ *
44 * **Example:** Disable remote models.
55 * ```javascript
66 * import { env } from '@xenova/transformers';
77 * env.allowRemoteModels = false;
88 * ```
9- *
9+ *
1010 * **Example:** Set local model path.
1111 * ```javascript
1212 * import { env } from '@xenova/transformers';
1313 * env.localModelPath = '/path/to/local/models/';
1414 * ```
15- *
15+ *
1616 * **Example:** Set cache directory.
1717 * ```javascript
1818 * import { env } from '@xenova/transformers';
1919 * env.cacheDir = '/path/to/cache/directory/';
2020 * ```
21- *
21+ *
2222 * @module env
2323 */
2424
25-import fs from 'fs';
26-import path from 'path';
25+import fs from "fs";
26+import path from "path";
2727
28-import { ONNX } from './backends/onnx.js';
28+import { ONNX } from "./backends/onnx.js";
2929 const { env: onnx_env } = ONNX;
3030
31-const VERSION = '2.14.0';
31+const VERSION = "2.14.0";
3232
3333 // Check if various APIs are available (depends on environment)
34-const WEB_CACHE_AVAILABLE = typeof self !== 'undefined' && 'caches' in self;
34+const WEB_CACHE_AVAILABLE = typeof self !== "undefined" && "caches" in self;
3535 const FS_AVAILABLE = !isEmpty(fs); // check if file system is available
3636 const PATH_AVAILABLE = !isEmpty(path); // check if path is available
3737
@@ -43,23 +43,22 @@
4343
4444 // Only used for environments with access to file system
4545 const DEFAULT_CACHE_DIR = RUNNING_LOCALLY
46- ? path.join(__dirname, '/.cache/')
47- : null;
46+ ? path.join(__dirname, "/.cache/")
47+ : null;
4848
4949 // Set local model path, based on available APIs
50-const DEFAULT_LOCAL_MODEL_PATH = '/models/';
50+const DEFAULT_LOCAL_MODEL_PATH = "/models/";
5151 const localModelPath = RUNNING_LOCALLY
52- ? path.join(__dirname, DEFAULT_LOCAL_MODEL_PATH)
53- : DEFAULT_LOCAL_MODEL_PATH;
52+ ? path.join(__dirname, DEFAULT_LOCAL_MODEL_PATH)
53+ : DEFAULT_LOCAL_MODEL_PATH;
5454
5555 // Set path to wasm files. This is needed when running in a web worker.
5656 // https://onnxruntime.ai/docs/api/js/interfaces/Env.WebAssemblyFlags.html#wasmPaths
5757 // We use remote wasm files by default to make it easier for newer users.
5858 // In practice, users should probably self-host the necessary .wasm files.
5959 onnx_env.wasm.wasmPaths = RUNNING_LOCALLY
60- ? path.join(__dirname, '/dist/')
61- : `https://cdn.jsdelivr.net/npm/@xenova/transformers@${VERSION}/dist/`;
62-
60+ ? path.join(__dirname, "/dist/")
61+ : `https://cdn.jsdelivr.net/npm/@xenova/transformers@${VERSION}/dist/`;
6362
6463 /**
6564 * Global variable used to control execution. This provides users a simple way to configure Transformers.js.
@@ -83,44 +82,42 @@
8382 * implements the `match` and `put` functions of the Web Cache API. For more information, see https://developer.mozilla.org/en-US/docs/Web/API/Cache
8483 */
8584 export const env = {
86- /////////////////// Backends settings ///////////////////
87- backends: {
88- // onnxruntime-web/onnxruntime-node
89- onnx: onnx_env,
90-
91- // TensorFlow.js
92- tfjs: {},
93- },
94-
95- __dirname,
96- version: VERSION,
97-
98- /////////////////// Model settings ///////////////////
99- allowRemoteModels: true,
100- remoteHost: 'https://huggingface.co/',
101- remotePathTemplate: '{model}/resolve/{revision}/',
102-
103- allowLocalModels: true,
104- localModelPath: localModelPath,
105- useFS: FS_AVAILABLE,
106-
107- /////////////////// Cache settings ///////////////////
108- useBrowserCache: WEB_CACHE_AVAILABLE,
109-
110- useFSCache: FS_AVAILABLE,
111- cacheDir: DEFAULT_CACHE_DIR,
112-
113- useCustomCache: false,
114- customCache: null,
115- //////////////////////////////////////////////////////
116-}
85+ /////////////////// Backends settings ///////////////////
86+ backends: {
87+ // onnxruntime-web/onnxruntime-node
88+ onnx: onnx_env,
89+
90+ // TensorFlow.js
91+ tfjs: {},
92+ },
93+
94+ __dirname,
95+ version: VERSION,
11796
97+ /////////////////// Model settings ///////////////////
98+ allowRemoteModels: true,
99+ remoteHost: "https://huggingface.co/",
100+ remotePathTemplate: "{model}/resolve/{revision}/",
101+
102+ allowLocalModels: true,
103+ localModelPath: localModelPath,
104+ useFS: FS_AVAILABLE,
105+
106+ /////////////////// Cache settings ///////////////////
107+ useBrowserCache: WEB_CACHE_AVAILABLE,
108+
109+ useFSCache: FS_AVAILABLE,
110+ cacheDir: DEFAULT_CACHE_DIR,
111+
112+ useCustomCache: false,
113+ customCache: null,
114+ //////////////////////////////////////////////////////
115+};
118116
119117 /**
120118 * @param {Object} obj
121119 * @private
122120 */
123121 function isEmpty(obj) {
124- return Object.keys(obj).length === 0;
122+ return Object.keys(obj).length === 0;
125123 }
126-
modified core/vendor/modules/@xenova/transformers/src/models.js +3873 −3478

The diff of this file is cut short. View the file.

@@ -1,9 +1,8 @@
1-
21 /**
32 * @file Definitions of all models available in Transformers.js.
4- *
3+ *
54 * **Example:** Load and run an `AutoModel`.
6- *
5+ *
76 * ```javascript
87 * import { AutoModel, AutoTokenizer } from '@xenova/transformers';
98 *
@@ -19,13 +18,13 @@
1918 * // size: 183132,
2019 * // }
2120 * ```
22- *
21+ *
2322 * We also provide other `AutoModel`s (listed below), which you can use in the same way as the Python library. For example:
24- *
23+ *
2524 * **Example:** Load and run an `AutoModelForSeq2SeqLM`.
2625 * ```javascript
2726 * import { AutoModelForSeq2SeqLM, AutoTokenizer } from '@xenova/transformers';
28- *
27+ *
2928 * let tokenizer = await AutoTokenizer.from_pretrained('Xenova/t5-small');
3029 * let model = await AutoModelForSeq2SeqLM.from_pretrained('Xenova/t5-small');
3130 *
@@ -34,53 +33,48 @@
3433 * let decoded = tokenizer.decode(outputs[0], { skip_special_tokens: true });
3534 * // 'Ich liebe Transformatoren!'
3635 * ```
37- *
36+ *
3837 * @module models
3938 */
4039
41-import {
42- AutoConfig,
43-} from './configs.js';
40+import { AutoConfig } from "./configs.js";
4441
4542 import {
46- Callable,
47- isIntegralNumber,
48- isTypedArray,
49- mergeArrays,
50-} from './utils/core.js';
43+ Callable,
44+ isIntegralNumber,
45+ isTypedArray,
46+ mergeArrays,
47+} from "./utils/core.js";
5148
52-import {
53- getModelFile,
54- getModelJSON,
55-} from './utils/hub.js';
49+import { getModelFile, getModelJSON } from "./utils/hub.js";
5650
5751 import {
58- ForcedBOSTokenLogitsProcessor,
59- ForcedEOSTokenLogitsProcessor,
60- ForceTokensLogitsProcessor,
61- GenerationConfig,
62- LogitsProcessorList,
63- MinLengthLogitsProcessor,
64- MinNewTokensLengthLogitsProcessor,
65- NoBadWordsLogitsProcessor,
66- NoRepeatNGramLogitsProcessor,
67- RepetitionPenaltyLogitsProcessor,
68- Sampler,
69- SuppressTokensAtBeginLogitsProcessor,
70- WhisperTimeStampLogitsProcessor,
71-} from './utils/generation.js';
52+ ForcedBOSTokenLogitsProcessor,
53+ ForcedEOSTokenLogitsProcessor,
54+ ForceTokensLogitsProcessor,
55+ GenerationConfig,
56+ LogitsProcessorList,
57+ MinLengthLogitsProcessor,
58+ MinNewTokensLengthLogitsProcessor,
59+ NoBadWordsLogitsProcessor,
60+ NoRepeatNGramLogitsProcessor,
61+ RepetitionPenaltyLogitsProcessor,
62+ Sampler,
63+ SuppressTokensAtBeginLogitsProcessor,
64+ WhisperTimeStampLogitsProcessor,
65+} from "./utils/generation.js";
7266
7367 import {
74- cat,
75- dynamicTimeWarping,
76- mean,
77- ones_like,
78- stack,
79- std_mean,
80- Tensor,
81-} from './utils/tensor.js';
82-
83-import { executionProviders, ONNX } from './backends/onnx.js';
68+ cat,
69+ dynamicTimeWarping,
70+ mean,
71+ ones_like,
72+ stack,
73+ std_mean,
74+ Tensor,
75+} from "./utils/tensor.js";
76+
77+import { executionProviders, ONNX } from "./backends/onnx.js";
8478 // import { medianFilter } from './transformers.js';
8579 const { InferenceSession, Tensor: ONNXTensor, env } = ONNX;
8680
@@ -89,16 +83,15 @@
8983 //////////////////////////////////////////////////
9084 // Model types: used internally
9185 const MODEL_TYPES = {
92- EncoderOnly: 0,
93- EncoderDecoder: 1,
94- Seq2Seq: 2,
95- Vision2Seq: 3,
96- DecoderOnly: 4,
97- MaskGeneration: 5,
98-}
86+ EncoderOnly: 0,
87+ EncoderDecoder: 1,
88+ Seq2Seq: 2,
89+ Vision2Seq: 3,
90+ DecoderOnly: 4,
91+ MaskGeneration: 5,
92+};
9993 //////////////////////////////////////////////////
10094
101-
10295 //////////////////////////////////////////////////
10396 // Helper functions
10497
@@ -107,7 +100,6 @@
107100 const MODEL_NAME_TO_CLASS_MAPPING = new Map();
108101 const MODEL_CLASS_TO_NAME_MAPPING = new Map();
109102
110-
111103 /**
112104 * Constructs an InferenceSession using a model file located at the specified path.
113105 * @param {string} pretrained_model_name_or_path The path to the directory containing the model file.
@@ -116,30 +108,39 @@
116108 * @returns {Promise<InferenceSession>} A Promise that resolves to an InferenceSession object.
117109 * @private
118110 */
119-async function constructSession(pretrained_model_name_or_path, fileName, options) {
120- // TODO add option for user to force specify their desired execution provider
121- let modelFileName = `onnx/${fileName}${options.quantized ? '_quantized' : ''}.onnx`;
122- let buffer = await getModelFile(pretrained_model_name_or_path, modelFileName, true, options);
123-
124- try {
125- return await InferenceSession.create(buffer, {
126- executionProviders,
127- });
128- } catch (err) {
129- // If the execution provided was only wasm, throw the error
130- if (executionProviders.length === 1 && executionProviders[0] === 'wasm') {
131- throw err;
132- }
133-
134- console.warn(err);
135- console.warn(
136- 'Something went wrong during model construction (most likely a missing operation). ' +
137- 'Using `wasm` as a fallback. '
138- )
139- return await InferenceSession.create(buffer, {
140- executionProviders: ['wasm']
141- });
142- }
111+async function constructSession(
112+ pretrained_model_name_or_path,
113+ fileName,
114+ options,
115+) {
116+ // TODO add option for user to force specify their desired execution provider
117+ let modelFileName = `onnx/${fileName}${options.quantized ? "_quantized" : ""}.onnx`;
118+ let buffer = await getModelFile(
119+ pretrained_model_name_or_path,
120+ modelFileName,
121+ true,
122+ options,
123+ );
124+
125+ try {
126+ return await InferenceSession.create(buffer, {
127+ executionProviders,
128+ });
129+ } catch (err) {
130+ // If the execution provided was only wasm, throw the error
131+ if (executionProviders.length === 1 && executionProviders[0] === "wasm") {
132+ throw err;
133+ }
134+
135+ console.warn(err);
136+ console.warn(
137+ "Something went wrong during model construction (most likely a missing operation). " +
138+ "Using `wasm` as a fallback. ",
139+ );
140+ return await InferenceSession.create(buffer, {
141+ executionProviders: ["wasm"],
142+ });
143+ }
143144 }
144145
145146 /**
@@ -151,41 +152,46 @@
151152 * @private
152153 */
153154 function validateInputs(session, inputs) {
154- /**
155- * NOTE: Create either a shallow or deep copy based on `onnx.wasm.proxy`
156- * @type {Record<string, Tensor>}
157- */
158- const checkedInputs = Object.create(null);
159- const missingInputs = [];
160- for (const inputName of session.inputNames) {
161- const tensor = inputs[inputName];
162- // Rare case where one of the model's input names corresponds to a built-in
163- // object name (e.g., toString), which would cause a simple (!tensor) check to fail,
164- // because it's not undefined but a function.
165- if (!(tensor instanceof Tensor)) {
166- missingInputs.push(inputName);
167- continue;
168- }
169- // NOTE: When `env.wasm.proxy is true` the tensor is moved across the Worker
170- // boundary, transferring ownership to the worker and invalidating the tensor.
171- // So, in this case, we simply sacrifice a clone for it.
172- checkedInputs[inputName] = env.wasm.proxy ? tensor.clone() : tensor;
173- }
174- if (missingInputs.length > 0) {
175- throw new Error(
176- `An error occurred during model execution: "Missing the following inputs: ${missingInputs.join(', ')}.`);
177- }
178-
179- const numInputsProvided = Object.keys(inputs).length;
180- const numInputsNeeded = session.inputNames.length;
181- if (numInputsProvided > numInputsNeeded) {
182- // No missing inputs, but too many inputs were provided.
183- // Warn the user and ignore the extra inputs.
184- let ignored = Object.keys(inputs).filter(inputName => !session.inputNames.includes(inputName));
185- console.warn(`WARNING: Too many inputs were provided (${numInputsProvided} > ${numInputsNeeded}). The following inputs will be ignored: "${ignored.join(', ')}".`);
186- }
187-
188- return checkedInputs;
155+ /**
156+ * NOTE: Create either a shallow or deep copy based on `onnx.wasm.proxy`
157+ * @type {Record<string, Tensor>}
158+ */
159+ const checkedInputs = Object.create(null);
160+ const missingInputs = [];
161+ for (const inputName of session.inputNames) {
162+ const tensor = inputs[inputName];
163+ // Rare case where one of the model's input names corresponds to a built-in
164+ // object name (e.g., toString), which would cause a simple (!tensor) check to fail,
165+ // because it's not undefined but a function.
166+ if (!(tensor instanceof Tensor)) {
167+ missingInputs.push(inputName);
168+ continue;
169+ }
170+ // NOTE: When `env.wasm.proxy is true` the tensor is moved across the Worker
171+ // boundary, transferring ownership to the worker and invalidating the tensor.
172+ // So, in this case, we simply sacrifice a clone for it.
173+ checkedInputs[inputName] = env.wasm.proxy ? tensor.clone() : tensor;
174+ }
175+ if (missingInputs.length > 0) {
176+ throw new Error(
177+ `An error occurred during model execution: "Missing the following inputs: ${missingInputs.join(", ")}.`,
178+ );
179+ }
180+
181+ const numInputsProvided = Object.keys(inputs).length;
182+ const numInputsNeeded = session.inputNames.length;
183+ if (numInputsProvided > numInputsNeeded) {
184+ // No missing inputs, but too many inputs were provided.
185+ // Warn the user and ignore the extra inputs.
186+ let ignored = Object.keys(inputs).filter(
187+ (inputName) => !session.inputNames.includes(inputName),
188+ );
189+ console.warn(
190+ `WARNING: Too many inputs were provided (${numInputsProvided} > ${numInputsNeeded}). The following inputs will be ignored: "${ignored.join(", ")}".`,
191+ );
192+ }
193+
194+ return checkedInputs;
189195 }
190196
191197 /**
@@ -193,25 +199,25 @@
193199 * NOTE: `inputs` must contain at least the input names of the model.
194200 * - If additional inputs are passed, they will be ignored.
195201 * - If inputs are missing, an error will be thrown.
196- *
202+ *
197203 * @param {InferenceSession} session The InferenceSession object to run.
198204 * @param {Object} inputs An object that maps input names to input tensors.
199205 * @returns {Promise<Object>} A Promise that resolves to an object that maps output names to output tensors.
200206 * @private
201207 */
202208 async function sessionRun(session, inputs) {
203- const checkedInputs = validateInputs(session, inputs);
204- try {
205- // @ts-ignore
206- let output = await session.run(checkedInputs);
207- output = replaceTensors(output);
208- return output;
209- } catch (e) {
210- // This usually occurs when the inputs are of the wrong type.
211- console.error(`An error occurred during model execution: "${e}".`);
212- console.error('Inputs given to model:', checkedInputs);
213- throw e;
214- }
209+ const checkedInputs = validateInputs(session, inputs);
210+ try {
211+ // @ts-ignore
212+ let output = await session.run(checkedInputs);
213+ output = replaceTensors(output);
214+ return output;
215+ } catch (e) {
216+ // This usually occurs when the inputs are of the wrong type.
217+ console.error(`An error occurred during model execution: "${e}".`);
218+ console.error("Inputs given to model:", checkedInputs);
219+ throw e;
220+ }
215221 }
216222
217223 /**
@@ -221,17 +227,16 @@
221227 * @private
222228 */
223229 function replaceTensors(obj) {
224- for (let prop in obj) {
225- if (obj[prop] instanceof ONNXTensor) {
226- obj[prop] = new Tensor(obj[prop]);
227- } else if (typeof obj[prop] === 'object') {
228- replaceTensors(obj[prop]);
229- }
230+ for (let prop in obj) {
231+ if (obj[prop] instanceof ONNXTensor) {
232+ obj[prop] = new Tensor(obj[prop]);
233+ } else if (typeof obj[prop] === "object") {
234+ replaceTensors(obj[prop]);
230235 }
231- return obj;
236+ }
237+ return obj;
232238 }
233239
234-
235240 /**
236241 * Converts an array or Tensor of integers to an int64 Tensor.
237242 * @param {Array|Tensor} items The input integers to be converted.
@@ -240,31 +245,35 @@
240245 * @private
241246 */
242247 function toI64Tensor(items) {
243- if (items instanceof Tensor) {
244- return items;
245- }
246- // items is an array
247- if (items.length === 0) {
248- throw Error("items must be non-empty");
249- }
250-
251- if (Array.isArray(items[0])) {
252- // batched
253- if (items.some(x => x.length !== items[0].length)) {
254- throw Error("Unable to create tensor, you should probably activate truncation and/or padding with 'padding=True' and/or 'truncation=True' to have batched tensors with the same length.")
255- }
256-
257- return new Tensor('int64',
258- BigInt64Array.from(items.flat().map(x => BigInt(x))),
259- [items.length, items[0].length]
260- );
261- } else {
262- //flat
263- return new Tensor('int64',
264- BigInt64Array.from(items.map(x => BigInt(x))),
265- [1, items.length]
266- );
267- }
248+ if (items instanceof Tensor) {
249+ return items;
250+ }
251+ // items is an array
252+ if (items.length === 0) {
253+ throw Error("items must be non-empty");
254+ }
255+
256+ if (Array.isArray(items[0])) {
257+ // batched
258+ if (items.some((x) => x.length !== items[0].length)) {
259+ throw Error(
260+ "Unable to create tensor, you should probably activate truncation and/or padding with 'padding=True' and/or 'truncation=True' to have batched tensors with the same length.",
261+ );
262+ }
263+
264+ return new Tensor(
265+ "int64",
266+ BigInt64Array.from(items.flat().map((x) => BigInt(x))),
267+ [items.length, items[0].length],
268+ );
269+ } else {
270+ //flat
271+ return new Tensor(
272+ "int64",
273+ BigInt64Array.from(items.map((x) => BigInt(x))),
274+ [1, items.length],
275+ );
276+ }
268277 }
269278
270279 /**
@@ -275,27 +284,27 @@
275284 * @private
276285 */
277286 function prepareAttentionMask(self, tokens) {
278-
279- // Prepare attention mask
280- let pad_token_id = self.config.pad_token_id ?? null;
281- let eos_token_id = self.config.eos_token_id ?? null;
282- if (isIntegralNumber(eos_token_id)) {
283- eos_token_id = [eos_token_id];
284- }
285-
286- let is_pad_token_in_inputs = tokens.indexOf(pad_token_id) !== -1;
287- let is_pad_token_not_equal_to_eos_token_id = (eos_token_id === null) || !eos_token_id.includes(pad_token_id)
288-
289- if (is_pad_token_in_inputs && is_pad_token_not_equal_to_eos_token_id) {
290- let data = BigInt64Array.from(
291- // Note: != so that int matches bigint
292- // @ts-ignore
293- tokens.data.map(x => x != pad_token_id)
294- )
295- return new Tensor('int64', data, tokens.dims)
296- } else {
297- return ones_like(tokens);
298- }
287+ // Prepare attention mask
288+ let pad_token_id = self.config.pad_token_id ?? null;
289+ let eos_token_id = self.config.eos_token_id ?? null;
290+ if (isIntegralNumber(eos_token_id)) {
291+ eos_token_id = [eos_token_id];
292+ }
293+
294+ let is_pad_token_in_inputs = tokens.indexOf(pad_token_id) !== -1;
295+ let is_pad_token_not_equal_to_eos_token_id =
296+ eos_token_id === null || !eos_token_id.includes(pad_token_id);
297+
298+ if (is_pad_token_in_inputs && is_pad_token_not_equal_to_eos_token_id) {
299+ let data = BigInt64Array.from(
300+ // Note: != so that int matches bigint
301+ // @ts-ignore
302+ tokens.data.map((x) => x != pad_token_id),
303+ );
304+ return new Tensor("int64", data, tokens.dims);
305+ } else {
306+ return ones_like(tokens);
307+ }
299308 }
300309
301310 /**
@@ -307,30 +316,31 @@
307316 * @private
308317 */
309318 function preparePositionIds(session, feeds, use_cache_branch) {
310- if (!session.inputNames.includes('position_ids')) return;
311-
312- const data = new BigInt64Array(feeds.attention_mask.data.length);
313-
314- // Compute cumulative sum of the attention mask along the sequence length dimension
315- for (let i = 0; i < feeds.attention_mask.dims[0]; ++i) {
316- let start = i * feeds.attention_mask.dims[1];
317- let sum = BigInt(0);
318- for (let j = 0; j < feeds.attention_mask.dims[1]; ++j) {
319- const index = start + j;
320- if (feeds.attention_mask.data[index] === 0n) {
321- data[index] = BigInt(1);
322- } else { // === 1n
323- data[index] = sum;
324- sum += feeds.attention_mask.data[index];
325- }
326- }
327- }
319+ if (!session.inputNames.includes("position_ids")) return;
328320
329- feeds.position_ids = new Tensor('int64', data, feeds.attention_mask.dims);
321+ const data = new BigInt64Array(feeds.attention_mask.data.length);
330322
331- if (use_cache_branch) {
332- feeds.position_ids = feeds.position_ids.slice(null, -1).unsqueeze_(-1);
323+ // Compute cumulative sum of the attention mask along the sequence length dimension
324+ for (let i = 0; i < feeds.attention_mask.dims[0]; ++i) {
325+ let start = i * feeds.attention_mask.dims[1];
326+ let sum = BigInt(0);
327+ for (let j = 0; j < feeds.attention_mask.dims[1]; ++j) {
328+ const index = start + j;
329+ if (feeds.attention_mask.data[index] === 0n) {
330+ data[index] = BigInt(1);
331+ } else {
332+ // === 1n
333+ data[index] = sum;
334+ sum += feeds.attention_mask.data[index];
335+ }
333336 }
337+ }
338+
339+ feeds.position_ids = new Tensor("int64", data, feeds.attention_mask.dims);
340+
341+ if (use_cache_branch) {
342+ feeds.position_ids = feeds.position_ids.slice(null, -1).unsqueeze_(-1);
343+ }
334344 }
335345
336346 /**
@@ -340,7 +350,7 @@
340350 * @private
341351 */
342352 function boolTensor(value) {
343- return new Tensor('bool', [value], [1]);
353+ return new Tensor("bool", [value], [1]);
344354 }
345355
346356 // JS doesn't support mixins, so we define some reused functions here, and allow "this" to be passed in
@@ -352,38 +362,52 @@
352362 * @private
353363 */
354364 async function seq2seqForward(self, model_inputs) {
355-
356- let { encoder_outputs, past_key_values } = model_inputs;
357-
358- if (!encoder_outputs) {
359- // Encoder outputs are not given, so we must compute them.
360- encoder_outputs = (await encoderForward(self, model_inputs)).last_hidden_state;
361- }
362- let decoderFeeds = {
363- input_ids: model_inputs.decoder_input_ids,
364- encoder_hidden_states: encoder_outputs,
365- };
366- const use_cache_branch = !!past_key_values;
367-
368- if (self.decoder_merged_session.inputNames.includes('use_cache_branch')) {
369- decoderFeeds.use_cache_branch = boolTensor(use_cache_branch);
370- }
371-
372- if (self.decoder_merged_session.inputNames.includes('encoder_attention_mask')) {
373- decoderFeeds.encoder_attention_mask = model_inputs.attention_mask
374- }
375-
376- preparePositionIds(self.decoder_merged_session, decoderFeeds, use_cache_branch);
377- self.addPastKeyValues(decoderFeeds, past_key_values);
378-
379- const decoderResults = await sessionRun(self.decoder_merged_session, decoderFeeds);
380- let logits = decoderResults.logits;
381- past_key_values = self.getPastKeyValues(decoderResults, past_key_values);
382-
383- // Get cross attention and/or decoder attentions if they are present
384- const attns = self.getAttentions(decoderResults);
385-
386- return new Seq2SeqLMOutput({ logits, past_key_values, encoder_outputs, ...attns });
365+ let { encoder_outputs, past_key_values } = model_inputs;
366+
367+ if (!encoder_outputs) {
368+ // Encoder outputs are not given, so we must compute them.
369+ encoder_outputs = (await encoderForward(self, model_inputs))
370+ .last_hidden_state;
371+ }
372+ let decoderFeeds = {
373+ input_ids: model_inputs.decoder_input_ids,
374+ encoder_hidden_states: encoder_outputs,
375+ };
376+ const use_cache_branch = !!past_key_values;
377+
378+ if (self.decoder_merged_session.inputNames.includes("use_cache_branch")) {
379+ decoderFeeds.use_cache_branch = boolTensor(use_cache_branch);
380+ }
381+
382+ if (
383+ self.decoder_merged_session.inputNames.includes("encoder_attention_mask")
384+ ) {
385+ decoderFeeds.encoder_attention_mask = model_inputs.attention_mask;
386+ }
387+
388+ preparePositionIds(
389+ self.decoder_merged_session,
390+ decoderFeeds,
391+ use_cache_branch,
392+ );
393+ self.addPastKeyValues(decoderFeeds, past_key_values);
394+
395+ const decoderResults = await sessionRun(
396+ self.decoder_merged_session,
397+ decoderFeeds,
398+ );
399+ let logits = decoderResults.logits;
400+ past_key_values = self.getPastKeyValues(decoderResults, past_key_values);
401+
402+ // Get cross attention and/or decoder attentions if they are present
403+ const attns = self.getAttentions(decoderResults);
404+
405+ return new Seq2SeqLMOutput({
406+ logits,
407+ past_key_values,
408+ encoder_outputs,
409+ ...attns,
410+ });
387411 }
388412
389413 /**
@@ -395,54 +419,59 @@
395419 * @returns {Object[]} Array of beam search objects.
396420 * @private
397421 */
398-function seq2seqStartBeams(self, inputTokenIds, generation_config, numOutputTokens) {
399- let beams = [];
400- let beamId = 0;
422+function seq2seqStartBeams(
423+ self,
424+ inputTokenIds,
425+ generation_config,
426+ numOutputTokens,
427+) {
428+ let beams = [];
429+ let beamId = 0;
430+
431+ // @ts-ignore
432+ const requires_attention_mask = self.requires_attention_mask ?? true;
433+
434+ // decoder_input_ids == output_token_ids
435+ let decoder_input_ids =
436+ generation_config.decoder_input_ids ??
437+ generation_config.decoder_start_token_id ??
438+ generation_config.bos_token_id ??
439+ generation_config.eos_token_id;
440+
441+ // Support input as tensor or list
442+ // TODO support batched decoder_input_ids
443+ if (decoder_input_ids instanceof Tensor) {
444+ decoder_input_ids = decoder_input_ids.tolist().flat();
445+ } else if (!Array.isArray(decoder_input_ids)) {
446+ decoder_input_ids = [decoder_input_ids];
447+ }
448+
449+ for (let tokens of inputTokenIds) {
450+ // TODO: Improve
451+ // Currently, just add back batch dimension.
452+ // In future, allow for true parallel execution
453+ tokens.dims = [1, ...tokens.dims];
454+
455+ // Create beam
456+ let start = {
457+ inputs: tokens,
458+ encoder_outputs: null,
459+ prev_model_outputs: null,
460+
461+ output_token_ids: decoder_input_ids,
462+ done: false,
463+ score: 0,
464+ id: beamId++, // assign unique id to beams
465+ };
401466
402- // @ts-ignore
403- const requires_attention_mask = self.requires_attention_mask ?? true;
404-
405- // decoder_input_ids == output_token_ids
406- let decoder_input_ids =
407- generation_config.decoder_input_ids
408- ?? generation_config.decoder_start_token_id
409- ?? generation_config.bos_token_id
410- ?? generation_config.eos_token_id;
411-
412- // Support input as tensor or list
413- // TODO support batched decoder_input_ids
414- if (decoder_input_ids instanceof Tensor) {
415- decoder_input_ids = decoder_input_ids.tolist().flat();
416- } else if (!Array.isArray(decoder_input_ids)) {
417- decoder_input_ids = [decoder_input_ids];
467+ if (requires_attention_mask) {
468+ start.attention_mask = prepareAttentionMask(self, tokens);
418469 }
419470
420- for (let tokens of inputTokenIds) {
421- // TODO: Improve
422- // Currently, just add back batch dimension.
423- // In future, allow for true parallel execution
424- tokens.dims = [1, ...tokens.dims]
425-
426- // Create beam
427- let start = {
428- inputs: tokens,
429- encoder_outputs: null,
430- prev_model_outputs: null,
431-
432- output_token_ids: decoder_input_ids,
433- done: false,
434- score: 0,
435- id: beamId++ // assign unique id to beams
436- }
437-
438- if (requires_attention_mask) {
439- start.attention_mask = prepareAttentionMask(self, tokens);
440- }
441-
442- beams.push(start);
443- }
471+ beams.push(start);
472+ }
444473
445- return beams;
474+ return beams;
446475 }
447476
448477 /**
@@ -455,34 +484,34 @@
455484 * @private
456485 */
457486 async function seq2seqRunBeam(self, beam) {
458- const input_name = self.main_input_name;
459-
460- let decoder_input_ids = beam.output_token_ids;
461- if (beam.prev_model_outputs) {
462- // After the first step, `prev_model_outputs` won't be null.
463- // So, we cut decoder_input_ids if past is used
464- decoder_input_ids = decoder_input_ids.slice(-1);
465- }
487+ const input_name = self.main_input_name;
466488
467- // 1. Prepare
468- let model_inputs = {
469- [input_name]: beam.inputs,
470- decoder_input_ids: toI64Tensor(decoder_input_ids),
471- encoder_outputs: beam.encoder_outputs,
472- past_key_values: beam.prev_model_outputs?.past_key_values,
473- }
474- if (beam.attention_mask) {
475- model_inputs.attention_mask = beam.attention_mask
476- }
489+ let decoder_input_ids = beam.output_token_ids;
490+ if (beam.prev_model_outputs) {
491+ // After the first step, `prev_model_outputs` won't be null.
492+ // So, we cut decoder_input_ids if past is used
493+ decoder_input_ids = decoder_input_ids.slice(-1);
494+ }
477495
478- // 2. Run
479- let output = await self.forward(model_inputs);
496+ // 1. Prepare
497+ let model_inputs = {
498+ [input_name]: beam.inputs,
499+ decoder_input_ids: toI64Tensor(decoder_input_ids),
500+ encoder_outputs: beam.encoder_outputs,
501+ past_key_values: beam.prev_model_outputs?.past_key_values,
502+ };
503+ if (beam.attention_mask) {
504+ model_inputs.attention_mask = beam.attention_mask;
505+ }
480506
481- // 3. Update
482- beam.prev_model_outputs = output;
483- beam.encoder_outputs = output.encoder_outputs;
507+ // 2. Run
508+ let output = await self.forward(model_inputs);
484509
485- return output;
510+ // 3. Update
511+ beam.prev_model_outputs = output;
512+ beam.encoder_outputs = output.encoder_outputs;
513+
514+ return output;
486515 }
487516
488517 /**
@@ -492,7 +521,7 @@
492521 * @private
493522 */
494523 function seq2seqUpdatebeam(beam, newTokenId) {
495- beam.output_token_ids = [...beam.output_token_ids, newTokenId];
524+ beam.output_token_ids = [...beam.output_token_ids, newTokenId];
496525 }
497526
498527 /**
@@ -503,23 +532,25 @@
503532 * @private
504533 */
505534 async function encoderForward(self, model_inputs) {
506- const encoderFeeds = Object.create(null);
507- for (const key of self.session.inputNames) {
508- encoderFeeds[key] = model_inputs[key];
509- }
510- if (self.session.inputNames.includes('token_type_ids') && !encoderFeeds.token_type_ids) {
511- // Assign default `token_type_ids` (all zeroes) to the `encoderFeeds` if the model expects it,
512- // but they weren't created by the tokenizer.
513- encoderFeeds.token_type_ids = new Tensor(
514- 'int64',
515- new BigInt64Array(encoderFeeds.input_ids.data.length),
516- encoderFeeds.input_ids.dims
517- )
518- }
519- return await sessionRun(self.session, encoderFeeds);
535+ const encoderFeeds = Object.create(null);
536+ for (const key of self.session.inputNames) {
537+ encoderFeeds[key] = model_inputs[key];
538+ }
539+ if (
540+ self.session.inputNames.includes("token_type_ids") &&
541+ !encoderFeeds.token_type_ids
542+ ) {
543+ // Assign default `token_type_ids` (all zeroes) to the `encoderFeeds` if the model expects it,
544+ // but they weren't created by the tokenizer.
545+ encoderFeeds.token_type_ids = new Tensor(
546+ "int64",
547+ new BigInt64Array(encoderFeeds.input_ids.data.length),
548+ encoderFeeds.input_ids.dims,
549+ );
550+ }
551+ return await sessionRun(self.session, encoderFeeds);
520552 }
521553
522-
523554 /**
524555 * Forward pass of a decoder model.
525556 * @param {Object} self The decoder model.
@@ -528,27 +559,27 @@
528559 * @private
529560 */
530561 async function decoderForward(self, model_inputs) {
531- let { input_ids, past_key_values, attention_mask } = model_inputs;
532- let decoderFeeds = {
533- input_ids: input_ids,
534- attention_mask: attention_mask ?? prepareAttentionMask(self, input_ids),
535- }
536- const use_cache_branch = !!past_key_values;
562+ let { input_ids, past_key_values, attention_mask } = model_inputs;
563+ let decoderFeeds = {
564+ input_ids: input_ids,
565+ attention_mask: attention_mask ?? prepareAttentionMask(self, input_ids),
566+ };
567+ const use_cache_branch = !!past_key_values;
537568
538- if (self.session.inputNames.includes('use_cache_branch')) {
539- decoderFeeds.use_cache_branch = boolTensor(use_cache_branch);
540- }
569+ if (self.session.inputNames.includes("use_cache_branch")) {
570+ decoderFeeds.use_cache_branch = boolTensor(use_cache_branch);
571+ }
541572
542- preparePositionIds(self.session, decoderFeeds, use_cache_branch);
573+ preparePositionIds(self.session, decoderFeeds, use_cache_branch);
543574
544- self.addPastKeyValues(decoderFeeds, past_key_values);
575+ self.addPastKeyValues(decoderFeeds, past_key_values);
545576
546- let decoderResults = await sessionRun(self.session, decoderFeeds);
577+ let decoderResults = await sessionRun(self.session, decoderFeeds);
547578
548- let logits = decoderResults.logits;
579+ let logits = decoderResults.logits;
549580
550- past_key_values = self.getPastKeyValues(decoderResults, past_key_values);
551- return { logits, past_key_values };
581+ past_key_values = self.getPastKeyValues(decoderResults, past_key_values);
582+ return { logits, past_key_values };
552583 }
553584
554585 /**
@@ -561,44 +592,49 @@
561592 * @returns {Object[]} An array of beams initialized with the given inputs and parameters.
562593 * @private
563594 */
564-function decoderStartBeams(self, inputTokenIds, generation_config, numOutputTokens, inputs_attention_mask) {
565- let beams = [];
566-
567- let beamId = 0;
568- for (let tokens of inputTokenIds) {
569- let output_token_ids = tokens.tolist().map(Number);
570-
571- // TODO: Improve
572- // Currently, just add back batch dimension.
573- // In future, allow for true parallel execution
574- tokens.dims = [1, ...tokens.dims]
595+function decoderStartBeams(
596+ self,
597+ inputTokenIds,
598+ generation_config,
599+ numOutputTokens,
600+ inputs_attention_mask,
601+) {
602+ let beams = [];
603+
604+ let beamId = 0;
605+ for (let tokens of inputTokenIds) {
606+ let output_token_ids = tokens.tolist().map(Number);
607+
608+ // TODO: Improve
609+ // Currently, just add back batch dimension.
610+ // In future, allow for true parallel execution
611+ tokens.dims = [1, ...tokens.dims];
612+
613+ let attn_mask;
614+ if (inputs_attention_mask) {
615+ attn_mask = inputs_attention_mask[beamId];
616+ attn_mask.dims = [1, ...attn_mask.dims];
617+ } else {
618+ attn_mask = prepareAttentionMask(self, tokens);
619+ }
575620
576- let attn_mask;
577- if (inputs_attention_mask) {
578- attn_mask = inputs_attention_mask[beamId];
579- attn_mask.dims = [1, ...attn_mask.dims]
621+ let start = {
622+ input: tokens,
623+ model_input_ids: tokens,
624+ attention_mask: attn_mask,
625+ prev_model_outputs: null,
580626
581- } else {
582- attn_mask = prepareAttentionMask(self, tokens)
583- }
627+ output_token_ids: output_token_ids,
628+ num_output_tokens: numOutputTokens,
584629
585- let start = {
586- input: tokens,
587- model_input_ids: tokens,
588- attention_mask: attn_mask,
589- prev_model_outputs: null,
590-
591- output_token_ids: output_token_ids,
592- num_output_tokens: numOutputTokens,
593-
594- done: false,
595- score: 0,
596- id: beamId++ // assign unique id to beams
597- }
630+ done: false,
631+ score: 0,
632+ id: beamId++, // assign unique id to beams
633+ };
598634
599- beams.push(start);
600- }
601- return beams;
635+ beams.push(start);
636+ }
637+ return beams;
602638 }
603639
604640 /**
@@ -615,26 +651,22 @@
615651 * @private
616652 */
617653 async function decoderRunBeam(self, beam) {
618- let attnMaskData = new BigInt64Array(beam.output_token_ids.length).fill(1n)
619-
620- // 1. Prepare
621- let model_inputs = {
622- input_ids: beam.model_input_ids,
623- attention_mask: new Tensor(
624- 'int64',
625- attnMaskData,
626- [1, attnMaskData.length]
627- ),
628- past_key_values: beam.prev_model_outputs?.past_key_values,
629- }
654+ let attnMaskData = new BigInt64Array(beam.output_token_ids.length).fill(1n);
630655
631- // 2. Run
632- let output = await self.forward(model_inputs);
656+ // 1. Prepare
657+ let model_inputs = {
658+ input_ids: beam.model_input_ids,
659+ attention_mask: new Tensor("int64", attnMaskData, [1, attnMaskData.length]),
660+ past_key_values: beam.prev_model_outputs?.past_key_values,
661+ };
633662
634- // 3. Update
635- beam.prev_model_outputs = output;
663+ // 2. Run
664+ let output = await self.forward(model_inputs);
636665
637- return output;
666+ // 3. Update
667+ beam.prev_model_outputs = output;
668+
669+ return output;
638670 }
639671
640672 /**
@@ -644,8 +676,8 @@
644676 * @private
645677 */
646678 function decoderUpdatebeam(beam, newTokenId) {
647- beam.output_token_ids = [...beam.output_token_ids, newTokenId];
648- beam.model_input_ids = new Tensor('int64', [BigInt(newTokenId)], [1, 1]);
679+ beam.output_token_ids = [...beam.output_token_ids, newTokenId];
680+ beam.model_input_ids = new Tensor("int64", [BigInt(newTokenId)], [1, 1]);
649681 }
650682
651683 //////////////////////////////////////////////////
@@ -655,858 +687,1041 @@
655687 * A base class for pre-trained models that provides the model configuration and an ONNX session.
656688 */
657689 export class PreTrainedModel extends Callable {
658- main_input_name = 'input_ids';
659-
660- /**
661- * Creates a new instance of the `PreTrainedModel` class.
662- * @param {Object} config The model configuration.
663- * @param {any} session session for the model.
664- */
665- constructor(config, session) {
666- super();
667-
668- this.config = config;
669- this.session = session;
670-
671- const modelName = MODEL_CLASS_TO_NAME_MAPPING.get(this.constructor);
672- const modelType = MODEL_TYPE_MAPPING.get(modelName);
673-
674- this.can_generate = false;
675- this._runBeam = null;
676- this._getStartBeams = null;
677- this._updateBeam = null;
678- this._forward = null;
679- if (modelType === MODEL_TYPES.DecoderOnly) {
680- this.can_generate = true;
681-
682- this._runBeam = decoderRunBeam;
683- this._getStartBeams = decoderStartBeams;
684- this._updateBeam = decoderUpdatebeam;
685- this._forward = decoderForward;
686-
687- } else if (modelType === MODEL_TYPES.Seq2Seq || modelType === MODEL_TYPES.Vision2Seq) {
688- this.can_generate = true;
689-
690- this._runBeam = seq2seqRunBeam;
691- this._getStartBeams = seq2seqStartBeams;
692- this._updateBeam = seq2seqUpdatebeam;
693- this._forward = seq2seqForward;
694-
695- } else if (modelType === MODEL_TYPES.EncoderDecoder) {
696- this._forward = encoderForward;
697-
698- } else { // should be MODEL_TYPES.EncoderOnly
699- this._forward = encoderForward;
700- }
701- }
690+ main_input_name = "input_ids";
691+
692+ /**
693+ * Creates a new instance of the `PreTrainedModel` class.
694+ * @param {Object} config The model configuration.
695+ * @param {any} session session for the model.
696+ */
697+ constructor(config, session) {
698+ super();
699+
700+ this.config = config;
701+ this.session = session;
702+
703+ const modelName = MODEL_CLASS_TO_NAME_MAPPING.get(this.constructor);
704+ const modelType = MODEL_TYPE_MAPPING.get(modelName);
705+
706+ this.can_generate = false;
707+ this._runBeam = null;
708+ this._getStartBeams = null;
709+ this._updateBeam = null;
710+ this._forward = null;
711+ if (modelType === MODEL_TYPES.DecoderOnly) {
712+ this.can_generate = true;
713+
714+ this._runBeam = decoderRunBeam;
715+ this._getStartBeams = decoderStartBeams;
716+ this._updateBeam = decoderUpdatebeam;
717+ this._forward = decoderForward;
718+ } else if (
719+ modelType === MODEL_TYPES.Seq2Seq ||
720+ modelType === MODEL_TYPES.Vision2Seq
721+ ) {
722+ this.can_generate = true;
723+
724+ this._runBeam = seq2seqRunBeam;
725+ this._getStartBeams = seq2seqStartBeams;
726+ this._updateBeam = seq2seqUpdatebeam;
727+ this._forward = seq2seqForward;
728+ } else if (modelType === MODEL_TYPES.EncoderDecoder) {
729+ this._forward = encoderForward;
730+ } else {
731+ // should be MODEL_TYPES.EncoderOnly
732+ this._forward = encoderForward;
733+ }
734+ }
735+
736+ /**
737+ * Disposes of all the ONNX sessions that were created during inference.
738+ * @returns {Promise<unknown[]>} An array of promises, one for each ONNX session that is being disposed.
739+ * @todo Use https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/FinalizationRegistry
740+ */
741+ async dispose() {
742+ const promises = [];
743+ for (let key of Object.keys(this)) {
744+ const item = this[key];
745+ // @ts-ignore
746+ if (item instanceof InferenceSession) {
747+ promises.push(item.handler.dispose());
748+ }
749+ }
750+ return await Promise.all(promises);
751+ }
752+
753+ /**
754+ * Instantiate one of the model classes of the library from a pretrained model.
755+ *
756+ * The model class to instantiate is selected based on the `model_type` property of the config object
757+ * (either passed as an argument or loaded from `pretrained_model_name_or_path` if possible)
758+ *
759+ * @param {string} pretrained_model_name_or_path The name or path of the pretrained model. Can be either:
760+ * - A string, the *model id* of a pretrained model hosted inside a model repo on huggingface.co.
761+ * Valid model ids can be located at the root-level, like `bert-base-uncased`, or namespaced under a
762+ * user or organization name, like `dbmdz/bert-base-german-cased`.
763+ * - A path to a *directory* containing model weights, e.g., `./my_model_directory/`.
764+ * @param {import('./utils/hub.js').PretrainedOptions} options Additional options for loading the model.
765+ *
766+ * @returns {Promise<PreTrainedModel>} A new instance of the `PreTrainedModel` class.
767+ */
768+ static async from_pretrained(
769+ pretrained_model_name_or_path,
770+ {
771+ quantized = true,
772+ progress_callback = null,
773+ config = null,
774+ cache_dir = null,
775+ local_files_only = false,
776+ revision = "main",
777+ model_file_name = null,
778+ } = {},
779+ ) {
780+ let options = {
781+ quantized,
782+ progress_callback,
783+ config,
784+ cache_dir,
785+ local_files_only,
786+ revision,
787+ model_file_name,
788+ };
702789
703- /**
704- * Disposes of all the ONNX sessions that were created during inference.
705- * @returns {Promise<unknown[]>} An array of promises, one for each ONNX session that is being disposed.
706- * @todo Use https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/FinalizationRegistry
707- */
708- async dispose() {
709- const promises = [];
710- for (let key of Object.keys(this)) {
711- const item = this[key];
712- // @ts-ignore
713- if (item instanceof InferenceSession) {
714- promises.push(item.handler.dispose())
715- }
716- }
717- return await Promise.all(promises);
790+ const modelName = MODEL_CLASS_TO_NAME_MAPPING.get(this);
791+ const modelType = MODEL_TYPE_MAPPING.get(modelName);
792+
793+ let info;
794+ if (modelType === MODEL_TYPES.DecoderOnly) {
795+ info = await Promise.all([
796+ AutoConfig.from_pretrained(pretrained_model_name_or_path, options),
797+ constructSession(
798+ pretrained_model_name_or_path,
799+ options.model_file_name ?? "decoder_model_merged",
800+ options,
801+ ),
802+ getModelJSON(
803+ pretrained_model_name_or_path,
804+ "generation_config.json",
805+ false,
806+ options,
807+ ),
808+ ]);
809+ } else if (
810+ modelType === MODEL_TYPES.Seq2Seq ||
811+ modelType === MODEL_TYPES.Vision2Seq
812+ ) {
813+ info = await Promise.all([
814+ AutoConfig.from_pretrained(pretrained_model_name_or_path, options),
815+ constructSession(
816+ pretrained_model_name_or_path,
817+ "encoder_model",
818+ options,
819+ ),
820+ constructSession(
821+ pretrained_model_name_or_path,
822+ "decoder_model_merged",
823+ options,
824+ ),
825+ getModelJSON(
826+ pretrained_model_name_or_path,
827+ "generation_config.json",
828+ false,
829+ options,
830+ ),
831+ ]);
832+ } else if (modelType === MODEL_TYPES.MaskGeneration) {
833+ info = await Promise.all([
834+ AutoConfig.from_pretrained(pretrained_model_name_or_path, options),
835+ constructSession(
836+ pretrained_model_name_or_path,
837+ "vision_encoder",
838+ options,
839+ ),
840+ constructSession(
841+ pretrained_model_name_or_path,
842+ "prompt_encoder_mask_decoder",
843+ options,
844+ ),
845+ ]);
846+ } else if (modelType === MODEL_TYPES.EncoderDecoder) {
847+ info = await Promise.all([
848+ AutoConfig.from_pretrained(pretrained_model_name_or_path, options),
849+ constructSession(
850+ pretrained_model_name_or_path,
851+ "encoder_model",
852+ options,
853+ ),
854+ constructSession(
855+ pretrained_model_name_or_path,
856+ "decoder_model_merged",
857+ options,
858+ ),
859+ ]);
860+ } else {
861+ // should be MODEL_TYPES.EncoderOnly
862+ if (modelType !== MODEL_TYPES.EncoderOnly) {
863+ console.warn(
864+ `Model type for '${modelName}' not found, assuming encoder-only architecture. Please report this at https://github.com/xenova/transformers.js/issues/new/choose.`,
865+ );
866+ }
867+ info = await Promise.all([
868+ AutoConfig.from_pretrained(pretrained_model_name_or_path, options),
869+ constructSession(
870+ pretrained_model_name_or_path,
871+ options.model_file_name ?? "model",
872+ options,
873+ ),
874+ ]);
718875 }
719876
720- /**
721- * Instantiate one of the model classes of the library from a pretrained model.
722- *
723- * The model class to instantiate is selected based on the `model_type` property of the config object
724- * (either passed as an argument or loaded from `pretrained_model_name_or_path` if possible)
725- *
726- * @param {string} pretrained_model_name_or_path The name or path of the pretrained model. Can be either:
727- * - A string, the *model id* of a pretrained model hosted inside a model repo on huggingface.co.
728- * Valid model ids can be located at the root-level, like `bert-base-uncased`, or namespaced under a
729- * user or organization name, like `dbmdz/bert-base-german-cased`.
730- * - A path to a *directory* containing model weights, e.g., `./my_model_directory/`.
731- * @param {import('./utils/hub.js').PretrainedOptions} options Additional options for loading the model.
732- *
733- * @returns {Promise<PreTrainedModel>} A new instance of the `PreTrainedModel` class.
734- */
735- static async from_pretrained(pretrained_model_name_or_path, {
736- quantized = true,
737- progress_callback = null,
738- config = null,
739- cache_dir = null,
740- local_files_only = false,
741- revision = 'main',
742- model_file_name = null,
743- } = {}) {
744-
745- let options = {
746- quantized,
747- progress_callback,
748- config,
749- cache_dir,
750- local_files_only,
751- revision,
752- model_file_name,
753- }
754-
755- const modelName = MODEL_CLASS_TO_NAME_MAPPING.get(this);
756- const modelType = MODEL_TYPE_MAPPING.get(modelName);
757-
758- let info;
759- if (modelType === MODEL_TYPES.DecoderOnly) {
760- info = await Promise.all([
761- AutoConfig.from_pretrained(pretrained_model_name_or_path, options),
762- constructSession(pretrained_model_name_or_path, options.model_file_name ?? 'decoder_model_merged', options),
763- getModelJSON(pretrained_model_name_or_path, 'generation_config.json', false, options),
764- ]);
765-
766- } else if (modelType === MODEL_TYPES.Seq2Seq || modelType === MODEL_TYPES.Vision2Seq) {
767- info = await Promise.all([
768- AutoConfig.from_pretrained(pretrained_model_name_or_path, options),
769- constructSession(pretrained_model_name_or_path, 'encoder_model', options),
770- constructSession(pretrained_model_name_or_path, 'decoder_model_merged', options),
771- getModelJSON(pretrained_model_name_or_path, 'generation_config.json', false, options),
772- ]);
773-
774- } else if (modelType === MODEL_TYPES.MaskGeneration) {
775- info = await Promise.all([
776- AutoConfig.from_pretrained(pretrained_model_name_or_path, options),
777- constructSession(pretrained_model_name_or_path, 'vision_encoder', options),
778- constructSession(pretrained_model_name_or_path, 'prompt_encoder_mask_decoder', options),
779- ]);
780-
781- } else if (modelType === MODEL_TYPES.EncoderDecoder) {
782- info = await Promise.all([
783- AutoConfig.from_pretrained(pretrained_model_name_or_path, options),
784- constructSession(pretrained_model_name_or_path, 'encoder_model', options),
785- constructSession(pretrained_model_name_or_path, 'decoder_model_merged', options),
786- ]);
787-
788- } else { // should be MODEL_TYPES.EncoderOnly
789- if (modelType !== MODEL_TYPES.EncoderOnly) {
790- console.warn(`Model type for '${modelName}' not found, assuming encoder-only architecture. Please report this at https://github.com/xenova/transformers.js/issues/new/choose.`)
791- }
792- info = await Promise.all([
793- AutoConfig.from_pretrained(pretrained_model_name_or_path, options),
794- constructSession(pretrained_model_name_or_path, options.model_file_name ?? 'model', options)
795- ]);
796- }
797-
798- // @ts-ignore
799- return new this(...info);
877+ // @ts-ignore
878+ return new this(...info);
879+ }
880+
881+ /**
882+ * Runs the model with the provided inputs
883+ * @param {Object} model_inputs Object containing input tensors
884+ * @returns {Promise<Object>} Object containing output tensors
885+ */
886+ async _call(model_inputs) {
887+ return await this.forward(model_inputs);
888+ }
889+
890+ /**
891+ * Forward method for a pretrained model. If not overridden by a subclass, the correct forward method
892+ * will be chosen based on the model type.
893+ * @param {Object} model_inputs The input data to the model in the format specified in the ONNX model.
894+ * @returns {Promise<Object>} The output data from the model in the format specified in the ONNX model.
895+ * @throws {Error} This method must be implemented in subclasses.
896+ */
897+ async forward(model_inputs) {
898+ return await this._forward(this, model_inputs);
899+ }
900+
901+ /**
902+ * @param {import('./utils/generation.js').GenerationConfigType} generation_config
903+ * @param {number} input_ids_seq_length The starting sequence length for the input ids.
904+ * @returns {LogitsProcessorList}
905+ * @private
906+ */
907+ _get_logits_processor(
908+ generation_config,
909+ input_ids_seq_length,
910+ // encoder_input_ids, TODO
911+ // prefix_allowed_tokens_fn, TODO
912+ logits_processor = null,
913+ ) {
914+ const processors = new LogitsProcessorList();
915+
916+ // if (generation_config.diversity_penalty !== null && generation_config.diversity_penalty > 0.0) {
917+ // processors.push(new HammingDiversityLogitsProcessor(
918+ // generation_config.diversity_penalty,
919+ // generation_config.num_beams,
920+ // generation_config.num_beam_groups
921+ // ));
922+ // }
923+
924+ // if (generation_config.encoder_repetition_penalty !== null && generation_config.encoder_repetition_penalty !== 1.0) {
925+ // processors.push(new EncoderRepetitionPenaltyLogitsProcessor(
926+ // generation_config.encoder_repetition_penalty,
927+ // encoder_input_ids
928+ // ));
929+ // }
930+
931+ if (
932+ generation_config.repetition_penalty !== null &&
933+ generation_config.repetition_penalty !== 1.0
934+ ) {
935+ processors.push(
936+ new RepetitionPenaltyLogitsProcessor(
937+ generation_config.repetition_penalty,
938+ ),
939+ );
800940 }
801941
802- /**
803- * Runs the model with the provided inputs
804- * @param {Object} model_inputs Object containing input tensors
805- * @returns {Promise<Object>} Object containing output tensors
806- */
807- async _call(model_inputs) {
808- return await this.forward(model_inputs);
942+ if (
943+ generation_config.no_repeat_ngram_size !== null &&
944+ generation_config.no_repeat_ngram_size > 0
945+ ) {
946+ processors.push(
947+ new NoRepeatNGramLogitsProcessor(
948+ generation_config.no_repeat_ngram_size,
949+ ),
950+ );
951+ }
952+
953+ // if (generation_config.encoder_no_repeat_ngram_size !== null && generation_config.encoder_no_repeat_ngram_size > 0) {
954+ // if (this.config.is_encoder_decoder) {
955+ // processors.push(new EncoderNoRepeatNGramLogitsProcessor(
956+ // generation_config.encoder_no_repeat_ngram_size,
957+ // encoder_input_ids
958+ // ));
959+ // } else {
960+ // throw new Error("It's impossible to use `encoder_no_repeat_ngram_size` with decoder-only architecture");
961+ // }
962+ // }
963+
964+ if (generation_config.bad_words_ids !== null) {
965+ processors.push(
966+ new NoBadWordsLogitsProcessor(
967+ generation_config.bad_words_ids,
968+ generation_config.eos_token_id,
969+ ),
970+ );
809971 }
810972
811- /**
812- * Forward method for a pretrained model. If not overridden by a subclass, the correct forward method
813- * will be chosen based on the model type.
814- * @param {Object} model_inputs The input data to the model in the format specified in the ONNX model.
815- * @returns {Promise<Object>} The output data from the model in the format specified in the ONNX model.
816- * @throws {Error} This method must be implemented in subclasses.
817- */
818- async forward(model_inputs) {
819- return await this._forward(this, model_inputs);
973+ if (
974+ generation_config.min_length !== null &&
975+ generation_config.eos_token_id !== null &&
976+ generation_config.min_length > 0
977+ ) {
978+ processors.push(
979+ new MinLengthLogitsProcessor(
980+ generation_config.min_length,
981+ generation_config.eos_token_id,
982+ ),
983+ );
820984 }
821985
822- /**
823- * @param {import('./utils/generation.js').GenerationConfigType} generation_config
824- * @param {number} input_ids_seq_length The starting sequence length for the input ids.
825- * @returns {LogitsProcessorList}
826- * @private
827- */
828- _get_logits_processor(
829- generation_config,
830- input_ids_seq_length,
831- // encoder_input_ids, TODO
832- // prefix_allowed_tokens_fn, TODO
833- logits_processor = null
986+ if (
987+ generation_config.min_new_tokens !== null &&
988+ generation_config.eos_token_id !== null &&
989+ generation_config.min_new_tokens > 0
834990 ) {
835- const processors = new LogitsProcessorList();
836-
837- // if (generation_config.diversity_penalty !== null && generation_config.diversity_penalty > 0.0) {
838- // processors.push(new HammingDiversityLogitsProcessor(
839- // generation_config.diversity_penalty,
840- // generation_config.num_beams,
841- // generation_config.num_beam_groups
842- // ));
843- // }
844-
845- // if (generation_config.encoder_repetition_penalty !== null && generation_config.encoder_repetition_penalty !== 1.0) {
846- // processors.push(new EncoderRepetitionPenaltyLogitsProcessor(
847- // generation_config.encoder_repetition_penalty,
848- // encoder_input_ids
849- // ));
850- // }
851-
852- if (generation_config.repetition_penalty !== null && generation_config.repetition_penalty !== 1.0) {
853- processors.push(new RepetitionPenaltyLogitsProcessor(generation_config.repetition_penalty));
854- }
855-
856- if (generation_config.no_repeat_ngram_size !== null && generation_config.no_repeat_ngram_size > 0) {
857- processors.push(new NoRepeatNGramLogitsProcessor(generation_config.no_repeat_ngram_size));
858- }
859-
860- // if (generation_config.encoder_no_repeat_ngram_size !== null && generation_config.encoder_no_repeat_ngram_size > 0) {
861- // if (this.config.is_encoder_decoder) {
862- // processors.push(new EncoderNoRepeatNGramLogitsProcessor(
863- // generation_config.encoder_no_repeat_ngram_size,
864- // encoder_input_ids
865- // ));
866- // } else {
867- // throw new Error("It's impossible to use `encoder_no_repeat_ngram_size` with decoder-only architecture");
868- // }
869- // }
870-
871- if (generation_config.bad_words_ids !== null) {
872- processors.push(new NoBadWordsLogitsProcessor(generation_config.bad_words_ids, generation_config.eos_token_id));
873- }
991+ processors.push(
992+ new MinNewTokensLengthLogitsProcessor(
993+ input_ids_seq_length,
994+ generation_config.min_new_tokens,
995+ generation_config.eos_token_id,
996+ ),
997+ );
998+ }
999+
1000+ // if (prefix_allowed_tokens_fn !== null) {
1001+ // processors.push(new PrefixConstrainedLogitsProcessor(
1002+ // prefix_allowed_tokens_fn,
1003+ // generation_config.num_beams / generation_config.num_beam_groups
1004+ // ));
1005+ // }
1006+
1007+ if (generation_config.forced_bos_token_id !== null) {
1008+ processors.push(
1009+ new ForcedBOSTokenLogitsProcessor(
1010+ generation_config.forced_bos_token_id,
1011+ ),
1012+ );
1013+ }
8741014
875- if (generation_config.min_length !== null && generation_config.eos_token_id !== null && generation_config.min_length > 0) {
876- processors.push(new MinLengthLogitsProcessor(generation_config.min_length, generation_config.eos_token_id));
877- }
1015+ if (generation_config.forced_eos_token_id !== null) {
1016+ processors.push(
1017+ new ForcedEOSTokenLogitsProcessor(
1018+ generation_config.max_length,
1019+ generation_config.forced_eos_token_id,
1020+ ),
1021+ );
1022+ }
1023+
1024+ // if (generation_config.remove_invalid_values === true) {
1025+ // processors.push(new InfNanRemoveLogitsProcessor());
1026+ // }
1027+
1028+ // if (generation_config.exponential_decay_length_penalty !== null) {
1029+ // processors.push(new ExponentialDecayLengthPenalty(
1030+ // generation_config.exponential_decay_length_penalty,
1031+ // generation_config.eos_token_id,
1032+ // input_ids_seq_length
1033+ // ));
1034+ // }
1035+
1036+ // if (generation_config.suppress_tokens !== null) {
1037+ // processors.push(new SuppressTokensLogitsProcessor(generation_config.suppress_tokens));
1038+ // }
1039+
1040+ if (generation_config.begin_suppress_tokens !== null) {
1041+ let begin_index =
1042+ input_ids_seq_length > 1 ||
1043+ generation_config.forced_bos_token_id === null
1044+ ? input_ids_seq_length
1045+ : input_ids_seq_length + 1;
1046+
1047+ if (generation_config.forced_decoder_ids !== null) {
1048+ // generation starts after the last token that is forced
1049+ begin_index +=
1050+ generation_config.forced_decoder_ids[
1051+ generation_config.forced_decoder_ids.length - 1
1052+ ][0];
1053+ }
1054+ processors.push(
1055+ new SuppressTokensAtBeginLogitsProcessor(
1056+ generation_config.begin_suppress_tokens,
1057+ begin_index,
1058+ ),
1059+ );
1060+ }
1061+
1062+ if (generation_config.forced_decoder_ids !== null) {
1063+ processors.push(
1064+ new ForceTokensLogitsProcessor(generation_config.forced_decoder_ids),
1065+ );
1066+ }
1067+
1068+ if (logits_processor !== null) {
1069+ processors.extend(logits_processor);
1070+ }
1071+
1072+ // `LogitNormalization` should always be the last logit processor, when present
1073+ // if (generation_config.renormalize_logits === true) {
1074+ // processors.push(new LogitNormalization());
1075+ // }
1076+
1077+ return processors;
1078+ }
1079+
1080+ /**
1081+ * This function merges multiple generation configs together to form a final generation config to be used by the model for text generation.
1082+ * It first creates an empty `GenerationConfig` object, then it applies the model's own `generation_config` property to it. Finally, if a `generation_config` object was passed in the arguments, it overwrites the corresponding properties in the final config with those of the passed config object.
1083+ * @param {import('./utils/generation.js').GenerationConfigType} generation_config A `GenerationConfig` object containing generation parameters.
1084+ * @returns {import('./utils/generation.js').GenerationConfigType} The final generation config object to be used by the model for text generation.
1085+ */
1086+ _get_generation_config(generation_config) {
1087+ // Create empty generation config (contains defaults)
1088+ // We pass `this.config` so that if `eos_token_id` or `bos_token_id` exist in the model's config, we will use them
1089+ let gen_config = new GenerationConfig(this.config);
1090+
1091+ // Apply model's generation config, if it exists
1092+ if ("generation_config" in this) {
1093+ Object.assign(gen_config, this.generation_config);
1094+ }
1095+
1096+ // Finally, use any generation config specified by the user
1097+ // when calling `generate`
1098+ if (generation_config !== null) {
1099+ Object.assign(gen_config, generation_config);
1100+ }
1101+ return gen_config;
1102+ }
1103+
1104+ /**
1105+ * @typedef {import('./utils/maths.js').TypedArray} TypedArray
1106+ */
1107+
1108+ /**
1109+ * @typedef {{ sequences: Tensor, decoder_attentions: Tensor, cross_attentions: Tensor }} EncoderDecoderOutput
1110+ * @typedef {Object} DecoderOutput
1111+ *
1112+ * Generates text based on the given inputs and generation configuration using the model.
1113+ * @param {Tensor|Array|TypedArray} inputs An array of input token IDs.
1114+ * @param {Object|GenerationConfig|null} generation_config The generation configuration to use. If null, default configuration will be used.
1115+ * @param {Object|null} logits_processor An optional logits processor to use. If null, a new LogitsProcessorList instance will be created.
1116+ * @param {Object} options options
1117+ * @param {Object} [options.inputs_attention_mask=null] An optional attention mask for the inputs.
1118+ * @returns {Promise<number[][]|EncoderDecoderOutput|DecoderOutput>} An array of generated output sequences, where each sequence is an array of token IDs.
1119+ * @throws {Error} Throws an error if the inputs array is empty.
1120+ */
1121+ async generate(
1122+ inputs,
1123+ generation_config = null,
1124+ logits_processor = null,
1125+ { inputs_attention_mask = null } = {},
1126+ ) {
1127+ if (!this.can_generate) {
1128+ const modelName = MODEL_CLASS_TO_NAME_MAPPING.get(this.constructor);
1129+ let errorMessage = `The current model class (${modelName}) is not compatible with \`.generate()\`, as it doesn't have a language model head.`;
1130+
1131+ const modelType = this.config.model_type;
1132+ const possibleInfo =
1133+ MODEL_WITH_LM_HEAD_MAPPING_NAMES.get(modelType) ??
1134+ MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES.get(modelType) ??
1135+ MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES.get(modelType) ??
1136+ // ?? MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING_NAMES.get(modelType) // TODO
1137+ MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES.get(modelType);
1138+
1139+ if (possibleInfo) {
1140+ // TODO: support multiple possible classes
1141+ errorMessage += ` Please use the following class instead: '${possibleInfo[0]}'`;
1142+ }
1143+ throw Error(errorMessage);
1144+ }
1145+
1146+ if (
1147+ !(inputs instanceof Tensor) &&
1148+ !isTypedArray(inputs) &&
1149+ !Array.isArray(inputs)
1150+ ) {
1151+ throw Error(
1152+ `\`inputs\` must be a Tensor, TypedArray, or Array, but is "${inputs.constructor.name}".`,
1153+ );
1154+ }
8781155
879- if (generation_config.min_new_tokens !== null && generation_config.eos_token_id !== null && generation_config.min_new_tokens > 0) {
880- processors.push(new MinNewTokensLengthLogitsProcessor(
881- input_ids_seq_length,
882- generation_config.min_new_tokens,
883- generation_config.eos_token_id
884- ));
885- }
1156+ let input_ids_seq_length;
8861157
887- // if (prefix_allowed_tokens_fn !== null) {
888- // processors.push(new PrefixConstrainedLogitsProcessor(
889- // prefix_allowed_tokens_fn,
890- // generation_config.num_beams / generation_config.num_beam_groups
891- // ));
892- // }
1158+ // Prepare `input_ids` which will be used for auto-regressive generation
1159+ // TODO: Update to align with HF transformers' implementation
1160+ if (this.config.is_encoder_decoder) {
1161+ // Generating from the encoder outputs
1162+ input_ids_seq_length = 0;
1163+ } else {
1164+ input_ids_seq_length =
1165+ inputs instanceof Tensor ? inputs.dims.at(-1) : inputs.length;
8931166
1167+ // decoder-only
1168+ if (input_ids_seq_length === 0) {
1169+ throw Error("Must supply a non-empty array of input token ids.");
1170+ }
1171+ }
8941172
895- if (generation_config.forced_bos_token_id !== null) {
896- processors.push(new ForcedBOSTokenLogitsProcessor(generation_config.forced_bos_token_id));
897- }
1173+ // Update generation config with defaults
1174+ generation_config = this._get_generation_config(generation_config);
8981175
899- if (generation_config.forced_eos_token_id !== null) {
900- processors.push(new ForcedEOSTokenLogitsProcessor(
901- generation_config.max_length,
902- generation_config.forced_eos_token_id
903- ));
904- }
1176+ logits_processor = logits_processor ?? new LogitsProcessorList();
9051177
906- // if (generation_config.remove_invalid_values === true) {
907- // processors.push(new InfNanRemoveLogitsProcessor());
908- // }
909-
910- // if (generation_config.exponential_decay_length_penalty !== null) {
911- // processors.push(new ExponentialDecayLengthPenalty(
912- // generation_config.exponential_decay_length_penalty,
913- // generation_config.eos_token_id,
914- // input_ids_seq_length
915- // ));
916- // }
917-
918- // if (generation_config.suppress_tokens !== null) {
919- // processors.push(new SuppressTokensLogitsProcessor(generation_config.suppress_tokens));
920- // }
921-
922- if (generation_config.begin_suppress_tokens !== null) {
923- let begin_index = (input_ids_seq_length > 1 || generation_config.forced_bos_token_id === null)
924- ? input_ids_seq_length
925- : input_ids_seq_length + 1;
926-
927- if (generation_config.forced_decoder_ids !== null) {
928- // generation starts after the last token that is forced
929- begin_index += generation_config.forced_decoder_ids[generation_config.forced_decoder_ids.length - 1][0];
930- }
931- processors.push(new SuppressTokensAtBeginLogitsProcessor(generation_config.begin_suppress_tokens, begin_index));
932- }
1178+ // Update logits processor
1179+ logits_processor = this._get_logits_processor(
1180+ generation_config,
1181+ input_ids_seq_length,
1182+ logits_processor,
1183+ );
9331184
934- if (generation_config.forced_decoder_ids !== null) {
935- processors.push(new ForceTokensLogitsProcessor(generation_config.forced_decoder_ids));
936- }
1185+ /** @type {number[]} */
1186+ let eos_token_ids = generation_config.eos_token_id;
1187+ if (eos_token_ids !== null && !Array.isArray(eos_token_ids)) {
1188+ eos_token_ids = [eos_token_ids];
1189+ }
9371190
938- if (logits_processor !== null) {
939- processors.extend(logits_processor)
940- }
1191+ // TODO implement early_stopping
1192+ // https://huggingface.co/blog/how-to-generate
9411193
942- // `LogitNormalization` should always be the last logit processor, when present
943- // if (generation_config.renormalize_logits === true) {
944- // processors.push(new LogitNormalization());
945- // }
1194+ let numOutputTokens = 1;
1195+ const maxOutputTokens =
1196+ numOutputTokens + (generation_config.max_new_tokens ?? Infinity);
9461197
947- return processors;
948- }
1198+ // Only use max length if max_new_tokens is not provided
1199+ const useMaxLength =
1200+ Number.isInteger(generation_config.max_length) &&
1201+ (generation_config.max_new_tokens ?? null) === null;
1202+ let sampler = Sampler.getSampler(generation_config);
9491203
950- /**
951- * This function merges multiple generation configs together to form a final generation config to be used by the model for text generation.
952- * It first creates an empty `GenerationConfig` object, then it applies the model's own `generation_config` property to it. Finally, if a `generation_config` object was passed in the arguments, it overwrites the corresponding properties in the final config with those of the passed config object.
953- * @param {import('./utils/generation.js').GenerationConfigType} generation_config A `GenerationConfig` object containing generation parameters.
954- * @returns {import('./utils/generation.js').GenerationConfigType} The final generation config object to be used by the model for text generation.
955- */
956- _get_generation_config(generation_config) {
957- // Create empty generation config (contains defaults)
958- // We pass `this.config` so that if `eos_token_id` or `bos_token_id` exist in the model's config, we will use them
959- let gen_config = new GenerationConfig(this.config);
960-
961- // Apply model's generation config, if it exists
962- if ('generation_config' in this) {
963- Object.assign(gen_config, this.generation_config);
1204+ // @ts-ignore
1205+ let beams = this.getStartBeams(
1206+ inputs,
1207+ generation_config,
1208+ numOutputTokens,
1209+ inputs_attention_mask,
1210+ );
1211+
1212+ while (beams.some((x) => !x.done) && numOutputTokens < maxOutputTokens) {
1213+ let newest_beams = [];
1214+ for (let beam of beams) {
1215+ if (beam.done) {
1216+ // Add this beam back into the pool
1217+ newest_beams.push(beam);
1218+ continue;
9641219 }
965-
966- // Finally, use any generation config specified by the user
967- // when calling `generate`
968- if (generation_config !== null) {
969- Object.assign(gen_config, generation_config);
1220+ if (
1221+ useMaxLength &&
1222+ beam.output_token_ids.length >= generation_config.max_length
1223+ ) {
1224+ // Set this beam to done and add it back into the pool
1225+ beam.done = true;
1226+ newest_beams.push(beam);
1227+ continue;
9701228 }
971- return gen_config;
972- }
9731229
974- /**
975- * @typedef {import('./utils/maths.js').TypedArray} TypedArray
976- */
977-
978- /**
979- * @typedef {{ sequences: Tensor, decoder_attentions: Tensor, cross_attentions: Tensor }} EncoderDecoderOutput
980- * @typedef {Object} DecoderOutput
981- *
982- * Generates text based on the given inputs and generation configuration using the model.
983- * @param {Tensor|Array|TypedArray} inputs An array of input token IDs.
984- * @param {Object|GenerationConfig|null} generation_config The generation configuration to use. If null, default configuration will be used.
985- * @param {Object|null} logits_processor An optional logits processor to use. If null, a new LogitsProcessorList instance will be created.
986- * @param {Object} options options
987- * @param {Object} [options.inputs_attention_mask=null] An optional attention mask for the inputs.
988- * @returns {Promise<number[][]|EncoderDecoderOutput|DecoderOutput>} An array of generated output sequences, where each sequence is an array of token IDs.
989- * @throws {Error} Throws an error if the inputs array is empty.
990- */
991- async generate(
992- inputs,
993- generation_config = null,
994- logits_processor = null,
995- {
996- inputs_attention_mask = null
997- } = {},
998- ) {
999- if (!this.can_generate) {
1000- const modelName = MODEL_CLASS_TO_NAME_MAPPING.get(this.constructor);
1001- let errorMessage = `The current model class (${modelName}) is not compatible with \`.generate()\`, as it doesn't have a language model head.`
1002-
1003- const modelType = this.config.model_type;
1004- const possibleInfo =
1005- MODEL_WITH_LM_HEAD_MAPPING_NAMES.get(modelType)
1006- ?? MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES.get(modelType)
1007- ?? MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES.get(modelType)
1008- // ?? MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING_NAMES.get(modelType) // TODO
1009- ?? MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES.get(modelType);
1010-
1011- if (possibleInfo) {
1012- // TODO: support multiple possible classes
1013- errorMessage += ` Please use the following class instead: '${possibleInfo[0]}'`;
1014- }
1015- throw Error(errorMessage);
1230+ // @ts-ignore
1231+ let output = await this.runBeam(beam);
1232+
1233+ // add attentions/scores to beam only if user requested
1234+ if (generation_config.output_attentions) {
1235+ this.addAttentionsToBeam(beam, output);
10161236 }
1017-
1018- if (!(inputs instanceof Tensor) && !isTypedArray(inputs) && !Array.isArray(inputs)) {
1019- throw Error(`\`inputs\` must be a Tensor, TypedArray, or Array, but is "${inputs.constructor.name}".`);
1237+ if (generation_config.output_scores) {
1238+ // TODO add
10201239 }
10211240
1022- let input_ids_seq_length;
1241+ // Logits are of the form [batch_size, out_seq_length, vocab_size]
1242+ // In most cases, this will be [batch_size, 1, vocab_size]
1243+ // So, we select the last token's logits:
1244+ // (equivalent to `logits = outputs.logits[:, -1, :]`)
1245+ let logits = output.logits.slice(null, -1, null);
10231246
1024- // Prepare `input_ids` which will be used for auto-regressive generation
1025- // TODO: Update to align with HF transformers' implementation
1026- if (this.config.is_encoder_decoder) {
1027- // Generating from the encoder outputs
1028- input_ids_seq_length = 0;
1029-
1030- } else {
1031- input_ids_seq_length = inputs instanceof Tensor ? inputs.dims.at(-1) : inputs.length;
1032-
1033- // decoder-only
1034- if (input_ids_seq_length === 0) {
1035- throw Error("Must supply a non-empty array of input token ids.")
1036- }
1037- }
1247+ // Apply logits processor
1248+ logits_processor(beam.output_token_ids, logits);
10381249
1039- // Update generation config with defaults
1040- generation_config = this._get_generation_config(generation_config);
1041-
1042- logits_processor = logits_processor ?? new LogitsProcessorList()
1043-
1044- // Update logits processor
1045- logits_processor = this._get_logits_processor(
1046- generation_config,
1047- input_ids_seq_length,
1048- logits_processor
1049- )
1050-
1051- /** @type {number[]} */
1052- let eos_token_ids = generation_config.eos_token_id;
1053- if (eos_token_ids !== null && !Array.isArray(eos_token_ids)) {
1054- eos_token_ids = [eos_token_ids];
1055- }
1250+ let sampledTokens = sampler(logits);
1251+ for (let [newTokenId, logProb] of sampledTokens) {
1252+ // use previous beam as a starting point
1253+ let newBeam = { ...beam };
10561254
1057- // TODO implement early_stopping
1058- // https://huggingface.co/blog/how-to-generate
1255+ // update new beam
1256+ // @ts-ignore
1257+ this.updateBeam(newBeam, newTokenId);
10591258
1060- let numOutputTokens = 1;
1061- const maxOutputTokens = numOutputTokens + (generation_config.max_new_tokens ?? Infinity);
1259+ newBeam.score += logProb;
10621260
1063- // Only use max length if max_new_tokens is not provided
1064- const useMaxLength = Number.isInteger(generation_config.max_length) && (generation_config.max_new_tokens ?? null) === null;
1065- let sampler = Sampler.getSampler(generation_config);
1261+ if (eos_token_ids && eos_token_ids.includes(newTokenId)) {
1262+ newBeam.done = true;
1263+ }
10661264
1067- // @ts-ignore
1068- let beams = this.getStartBeams(inputs, generation_config, numOutputTokens, inputs_attention_mask);
1069-
1070- while (beams.some(x => !x.done) && numOutputTokens < maxOutputTokens) {
1071- let newest_beams = [];
1072- for (let beam of beams) {
1073- if (beam.done) {
1074- // Add this beam back into the pool
1075- newest_beams.push(beam);
1076- continue
1077- }
1078- if (useMaxLength && beam.output_token_ids.length >= generation_config.max_length) {
1079- // Set this beam to done and add it back into the pool
1080- beam.done = true;
1081- newest_beams.push(beam);
1082- continue
1083- }
1084-
1085- // @ts-ignore
1086- let output = await this.runBeam(beam);
1087-
1088- // add attentions/scores to beam only if user requested
1089- if (generation_config.output_attentions) {
1090- this.addAttentionsToBeam(beam, output);
1091- }
1092- if (generation_config.output_scores) {
1093- // TODO add
1094- }
1095-
1096- // Logits are of the form [batch_size, out_seq_length, vocab_size]
1097- // In most cases, this will be [batch_size, 1, vocab_size]
1098- // So, we select the last token's logits:
1099- // (equivalent to `logits = outputs.logits[:, -1, :]`)
1100- let logits = output.logits.slice(null, -1, null);
1101-
1102- // Apply logits processor
1103- logits_processor(beam.output_token_ids, logits);
1104-
1105- let sampledTokens = sampler(logits);
1106- for (let [newTokenId, logProb] of sampledTokens) {
1107- // use previous beam as a starting point
1108- let newBeam = { ...beam };
1109-
1110- // update new beam
1111- // @ts-ignore
1112- this.updateBeam(newBeam, newTokenId);
1113-
1114- newBeam.score += logProb;
1115-
1116- if (eos_token_ids && eos_token_ids.includes(newTokenId)) {
1117- newBeam.done = true;
1118- }
1119-
1120- newest_beams.push(newBeam);
1121- }
1122- }
1123- ++numOutputTokens;
1124-
1125- // Next, we get the best beams, per ID
1126- newest_beams = this.groupBeams(newest_beams).map(
1127- group => group
1128- .sort((a, b) => b.score - a.score) // sort by score
1129- .slice(0, generation_config.num_beams) // remove outside beam width
1130- );
1131-
1132- // Flatten beams
1133- beams = newest_beams.flat();
1134-
1135- // Run callback
1136- if (generation_config.callback_function) {
1137- generation_config.callback_function(beams);
1138- }
1265+ newest_beams.push(newBeam);
11391266 }
1140-
1141- // TODO: Ensure that we can return non-batched outputs
1142-
1143- const groupedBeams = this.groupBeams(beams);
1144-
1145- const getFlattened = (key) => groupedBeams.map(
1146- batch => {
1147- if (generation_config.num_return_sequences > 1) {
1148- return batch.slice(0, generation_config.num_return_sequences).map(x => x[key]);
1149- } else {
1150- return [batch[0][key]];
1151- }
1152- }
1153- ).flat(); // Flatten across batches (depth=1)
1154-
1155- const sequences = getFlattened('output_token_ids'); // [1, seqLength]
1156-
1157- if (generation_config.return_dict_in_generate) {
1158- // NOTE: `decoder_attentions` and `cross_attentions` should be:
1159- // list (one element for each generated token)
1160- // of list (one element for each layer of the decoder)
1161- // of torch.FloatTensor of shape (batch_size, num_heads, generated_length, sequence_length)
1162- // However, since we are only generating one batch at a time, they are of the form:
1163- // list (batches)
1164- // of list (one element for each generated token)
1165- // of list (one element for each layer of the decoder)
1166- // of torch.FloatTensor of shape (1, num_heads, generated_length, sequence_length)
1167- //
1168- // TODO: In future (when true parallelism, we should be able to return the correct shape)
1169-
1170- const decoder_attentions = getFlattened('decoder_attentions');
1171- const cross_attentions = getFlattened('cross_attentions');
1172-
1173- return {
1174- sequences,
1175-
1176- decoder_attentions,
1177- cross_attentions,
1178- }
1267+ }
1268+ ++numOutputTokens;
1269+
1270+ // Next, we get the best beams, per ID
1271+ newest_beams = this.groupBeams(newest_beams).map(
1272+ (group) =>
1273+ group
1274+ .sort((a, b) => b.score - a.score) // sort by score
1275+ .slice(0, generation_config.num_beams), // remove outside beam width
1276+ );
1277+
1278+ // Flatten beams
1279+ beams = newest_beams.flat();
1280+
1281+ // Run callback
1282+ if (generation_config.callback_function) {
1283+ generation_config.callback_function(beams);
1284+ }
1285+ }
1286+
1287+ // TODO: Ensure that we can return non-batched outputs
1288+
1289+ const groupedBeams = this.groupBeams(beams);
1290+
1291+ const getFlattened = (key) =>
1292+ groupedBeams
1293+ .map((batch) => {
1294+ if (generation_config.num_return_sequences > 1) {
1295+ return batch
1296+ .slice(0, generation_config.num_return_sequences)
1297+ .map((x) => x[key]);
1298+ } else {
1299+ return [batch[0][key]];
1300+ }
1301+ })
1302+ .flat(); // Flatten across batches (depth=1)
1303+
1304+ const sequences = getFlattened("output_token_ids"); // [1, seqLength]
1305+
1306+ if (generation_config.return_dict_in_generate) {
1307+ // NOTE: `decoder_attentions` and `cross_attentions` should be:
1308+ // list (one element for each generated token)
1309+ // of list (one element for each layer of the decoder)
1310+ // of torch.FloatTensor of shape (batch_size, num_heads, generated_length, sequence_length)
1311+ // However, since we are only generating one batch at a time, they are of the form:
1312+ // list (batches)
1313+ // of list (one element for each generated token)
1314+ // of list (one element for each layer of the decoder)
1315+ // of torch.FloatTensor of shape (1, num_heads, generated_length, sequence_length)
1316+ //
1317+ // TODO: In future (when true parallelism, we should be able to return the correct shape)
1318+
1319+ const decoder_attentions = getFlattened("decoder_attentions");
1320+ const cross_attentions = getFlattened("cross_attentions");
1321+
1322+ return {
1323+ sequences,
1324+
1325+ decoder_attentions,
1326+ cross_attentions,
1327+ };
1328+ } else {
1329+ return sequences;
1330+ }
1331+ }
1332+
1333+ /**
1334+ * Helper function to add attentions to beam
1335+ * @param {Object} beam
1336+ * @param {Object} output
1337+ * @private
1338+ */
1339+ addAttentionsToBeam(beam, output) {
1340+ if (this.config.is_encoder_decoder) {
1341+ if (!output.cross_attentions || output.cross_attentions.length === 0) {
1342+ throw Error(
1343+ "`output_attentions` is true, but the model did not produce cross-attentions. " +
1344+ "This is most likely because the model was not exported with `output_attentions=True`.",
1345+ );
1346+ }
1347+ if (!beam.cross_attentions) {
1348+ beam.cross_attentions = [];
1349+ }
1350+ beam.cross_attentions.push(output.cross_attentions);
1351+ }
1352+
1353+ if (!output.decoder_attentions || output.decoder_attentions.length === 0) {
1354+ throw Error(
1355+ "`output_attentions` is true, but the model did not produce decoder-attentions. " +
1356+ "This is most likely because the model was not exported with `output_attentions=True`.",
1357+ );
1358+ }
1359+ if (!beam.decoder_attentions) {
1360+ beam.decoder_attentions = [];
1361+ }
1362+ beam.decoder_attentions.push(output.decoder_attentions);
1363+ }
1364+
1365+ /**
1366+ * Groups an array of beam objects by their ids.
1367+ *
1368+ * @param {Array} beams The array of beam objects to group.
1369+ * @returns {Array} An array of arrays, where each inner array contains beam objects with the same id.
1370+ */
1371+ groupBeams(beams) {
1372+ // Group beams by their ids
1373+ const groups = Object.create(null);
1374+ for (const obj of beams) {
1375+ if (groups[obj.id] === undefined) {
1376+ groups[obj.id] = [obj];
1377+ } else {
1378+ groups[obj.id].push(obj);
1379+ }
1380+ }
1381+
1382+ return Object.values(groups);
1383+ }
1384+
1385+ /**
1386+ * Returns an object containing past key values from the given decoder results object.
1387+ *
1388+ * @param {Object} decoderResults The decoder results object.
1389+ * @param {Object} pastKeyValues The previous past key values.
1390+ * @returns {Object} An object containing past key values.
1391+ */
1392+ getPastKeyValues(decoderResults, pastKeyValues) {
1393+ const pkvs = Object.create(null);
1394+
1395+ for (const name in decoderResults) {
1396+ if (name.startsWith("present")) {
1397+ let newName = name.replace("present", "past_key_values");
1398+
1399+ if (pastKeyValues && name.includes("encoder")) {
1400+ // Optimization introduced by optimum to reuse past key values. So, we just replace the constant
1401+ // outputs with the previous past key values.
1402+ // https://github.com/huggingface/optimum/blob/0bf2c05fb7e1182b52d21b703cfc95fd9e4ea3dc/optimum/onnxruntime/base.py#L677-L704
1403+ pkvs[newName] = pastKeyValues[newName];
11791404 } else {
1180- return sequences;
1181- }
1182- }
1183-
1184- /**
1185- * Helper function to add attentions to beam
1186- * @param {Object} beam
1187- * @param {Object} output
1188- * @private
1189- */
1190- addAttentionsToBeam(beam, output) {
1191- if (this.config.is_encoder_decoder) {
1192- if (!output.cross_attentions || output.cross_attentions.length === 0) {
1193- throw Error(
1194- "`output_attentions` is true, but the model did not produce cross-attentions. " +
1195- "This is most likely because the model was not exported with `output_attentions=True`."
1196- )
1197- }
1198- if (!beam.cross_attentions) {
1199- beam.cross_attentions = [];
1200- }
1201- beam.cross_attentions.push(output.cross_attentions);
1405+ pkvs[newName] = decoderResults[name];
12021406 }
1203-
1204- if (!output.decoder_attentions || output.decoder_attentions.length === 0) {
1205- throw Error(
1206- "`output_attentions` is true, but the model did not produce decoder-attentions. " +
1207- "This is most likely because the model was not exported with `output_attentions=True`."
1208- )
1407+ }
1408+ }
1409+ return pkvs;
1410+ }
1411+
1412+ /**
1413+ * Returns an object containing attentions from the given decoder results object.
1414+ *
1415+ * @param {Object} decoderResults The decoder results object.
1416+ * @returns {Object} An object containing attentions.
1417+ */
1418+ getAttentions(decoderResults) {
1419+ const attns = Object.create(null);
1420+
1421+ for (const attnName of ["cross_attentions", "decoder_attentions"]) {
1422+ const result = [];
1423+ for (const name in decoderResults) {
1424+ if (name.startsWith(attnName)) {
1425+ const index = name.split(".").pop();
1426+ result[index] = decoderResults[name];
12091427 }
1210- if (!beam.decoder_attentions) {
1211- beam.decoder_attentions = [];
1428+ }
1429+ attns[attnName] = result;
1430+ }
1431+ return attns;
1432+ }
1433+
1434+ /**
1435+ * Adds past key values to the decoder feeds object. If pastKeyValues is null, creates new tensors for past key values.
1436+ *
1437+ * @param {Object} decoderFeeds The decoder feeds object to add past key values to.
1438+ * @param {Object} pastKeyValues An object containing past key values.
1439+ */
1440+ addPastKeyValues(decoderFeeds, pastKeyValues) {
1441+ if (pastKeyValues) {
1442+ Object.assign(decoderFeeds, pastKeyValues);
1443+ } else {
1444+ // TODO support batches (i.e., batch_size > 1)
1445+ const batch_size = 1;
1446+
1447+ // @ts-ignore
1448+ if (this.config.is_encoder_decoder && (this.add_encoder_pkv ?? true)) {
1449+ // @ts-ignore
1450+ let encoder_dims = [
1451+ batch_size,
1452+ this.num_encoder_heads,
1453+ 0,
1454+ this.encoder_dim_kv,
1455+ ];
1456+ // @ts-ignore
1457+ let decoder_dims = [
1458+ batch_size,
1459+ this.num_decoder_heads,
1460+ 0,
1461+ this.decoder_dim_kv,
1462+ ];
1463+ // @ts-ignore
1464+ for (let i = 0; i < this.num_decoder_layers; ++i) {
1465+ decoderFeeds[`past_key_values.${i}.encoder.key`] = new Tensor(
1466+ "float32",
1467+ [],
1468+ encoder_dims,
1469+ );
1470+ decoderFeeds[`past_key_values.${i}.encoder.value`] = new Tensor(
1471+ "float32",
1472+ [],
1473+ encoder_dims,
1474+ );
1475+ decoderFeeds[`past_key_values.${i}.decoder.key`] = new Tensor(
1476+ "float32",
1477+ [],
1478+ decoder_dims,
1479+ );
1480+ decoderFeeds[`past_key_values.${i}.decoder.value`] = new Tensor(
1481+ "float32",
1482+ [],
1483+ decoder_dims,
1484+ );
12121485 }
1213- beam.decoder_attentions.push(output.decoder_attentions);
1214- }
1215-
1216- /**
1217- * Groups an array of beam objects by their ids.
1218- *
1219- * @param {Array} beams The array of beam objects to group.
1220- * @returns {Array} An array of arrays, where each inner array contains beam objects with the same id.
1221- */
1222- groupBeams(beams) {
1223- // Group beams by their ids
1224- const groups = Object.create(null);
1225- for (const obj of beams) {
1226- if (groups[obj.id] === undefined) {
1227- groups[obj.id] = [obj];
1228- } else {
1229- groups[obj.id].push(obj);
1230- }
1486+ } else if (this.config.model_type === "falcon") {
1487+ // NOTE: Custom implementation for Falcon
1488+ // @ts-ignore
1489+ let dims = [batch_size * this.num_heads, 0, this.dim_kv];
1490+ // @ts-ignore
1491+ for (let i = 0; i < this.num_layers; ++i) {
1492+ decoderFeeds[`past_key_values.${i}.key`] = new Tensor(
1493+ "float32",
1494+ [],
1495+ dims,
1496+ );
1497+ decoderFeeds[`past_key_values.${i}.value`] = new Tensor(
1498+ "float32",
1499+ [],
1500+ dims,
1501+ );
12311502 }
1232-
1233- return Object.values(groups);
1234- }
1235-
1236- /**
1237- * Returns an object containing past key values from the given decoder results object.
1238- *
1239- * @param {Object} decoderResults The decoder results object.
1240- * @param {Object} pastKeyValues The previous past key values.
1241- * @returns {Object} An object containing past key values.
1242- */
1243- getPastKeyValues(decoderResults, pastKeyValues) {
1244-
1245- const pkvs = Object.create(null);
1246-
1247- for (const name in decoderResults) {
1248- if (name.startsWith('present')) {
1249- let newName = name.replace('present', 'past_key_values');
1250-
1251- if (pastKeyValues && name.includes('encoder')) {
1252- // Optimization introduced by optimum to reuse past key values. So, we just replace the constant
1253- // outputs with the previous past key values.
1254- // https://github.com/huggingface/optimum/blob/0bf2c05fb7e1182b52d21b703cfc95fd9e4ea3dc/optimum/onnxruntime/base.py#L677-L704
1255- pkvs[newName] = pastKeyValues[newName];
1256- } else {
1257- pkvs[newName] = decoderResults[name];
1258- }
1259- }
1503+ } else if (this.config.multi_query) {
1504+ // e.g., for `gpt_bigcode`
1505+ // @ts-ignore
1506+ let dims = [batch_size * this.num_heads, 0, 2 * this.dim_kv];
1507+ // @ts-ignore
1508+ for (let i = 0; i < this.num_layers; ++i) {
1509+ decoderFeeds[`past_key_values.${i}.key_value`] = new Tensor(
1510+ "float32",
1511+ [],
1512+ dims,
1513+ );
12601514 }
1261- return pkvs;
1262- }
1515+ } else if (this.config.model_type === "bloom") {
1516+ // NOTE: Custom implementation for Bloom
12631517
1264- /**
1265- * Returns an object containing attentions from the given decoder results object.
1266- *
1267- * @param {Object} decoderResults The decoder results object.
1268- * @returns {Object} An object containing attentions.
1269- */
1270- getAttentions(decoderResults) {
1271- const attns = Object.create(null);
1272-
1273- for (const attnName of ['cross_attentions', 'decoder_attentions']) {
1274- const result = [];
1275- for (const name in decoderResults) {
1276- if (name.startsWith(attnName)) {
1277- const index = name.split('.').pop()
1278- result[index] = decoderResults[name];
1279- }
1280- }
1281- attns[attnName] = result;
1518+ // @ts-ignore
1519+ let keyDims = [batch_size * this.num_heads, this.dim_kv, 0]; // [batch_size x num_heads,64,past_sequence_length]
1520+ // @ts-ignore
1521+ let valueDims = [batch_size * this.num_heads, 0, this.dim_kv]; // [batch_size x num_heads,past_sequence_length,64]
1522+ // @ts-ignore
1523+ for (let i = 0; i < this.num_layers; ++i) {
1524+ decoderFeeds[`past_key_values.${i}.key`] = new Tensor(
1525+ "float32",
1526+ [],
1527+ keyDims,
1528+ );
1529+ decoderFeeds[`past_key_values.${i}.value`] = new Tensor(
1530+ "float32",
1531+ [],
1532+ valueDims,
1533+ );
12821534 }
1283- return attns;
1284- }
1285-
1286- /**
1287- * Adds past key values to the decoder feeds object. If pastKeyValues is null, creates new tensors for past key values.
1288- *
1289- * @param {Object} decoderFeeds The decoder feeds object to add past key values to.
1290- * @param {Object} pastKeyValues An object containing past key values.
1291- */
1292- addPastKeyValues(decoderFeeds, pastKeyValues) {
1293- if (pastKeyValues) {
1294- Object.assign(decoderFeeds, pastKeyValues)
1295- } else {
1296- // TODO support batches (i.e., batch_size > 1)
1297- const batch_size = 1;
1298-
1299- // @ts-ignore
1300- if (this.config.is_encoder_decoder && (this.add_encoder_pkv ?? true)) {
1301- // @ts-ignore
1302- let encoder_dims = [batch_size, this.num_encoder_heads, 0, this.encoder_dim_kv];
1303- // @ts-ignore
1304- let decoder_dims = [batch_size, this.num_decoder_heads, 0, this.decoder_dim_kv];
1305- // @ts-ignore
1306- for (let i = 0; i < this.num_decoder_layers; ++i) {
1307- decoderFeeds[`past_key_values.${i}.encoder.key`] = new Tensor('float32', [], encoder_dims)
1308- decoderFeeds[`past_key_values.${i}.encoder.value`] = new Tensor('float32', [], encoder_dims)
1309- decoderFeeds[`past_key_values.${i}.decoder.key`] = new Tensor('float32', [], decoder_dims)
1310- decoderFeeds[`past_key_values.${i}.decoder.value`] = new Tensor('float32', [], decoder_dims)
1311- }
1312- } else if (this.config.model_type === 'falcon') {
1313- // NOTE: Custom implementation for Falcon
1314- // @ts-ignore
1315- let dims = [batch_size * this.num_heads, 0, this.dim_kv]
1316- // @ts-ignore
1317- for (let i = 0; i < this.num_layers; ++i) {
1318- decoderFeeds[`past_key_values.${i}.key`] = new Tensor('float32', [], dims)
1319- decoderFeeds[`past_key_values.${i}.value`] = new Tensor('float32', [], dims)
1320- }
1321- } else if (this.config.multi_query) { // e.g., for `gpt_bigcode`
1322- // @ts-ignore
1323- let dims = [batch_size * this.num_heads, 0, 2 * this.dim_kv]
1324- // @ts-ignore
1325- for (let i = 0; i < this.num_layers; ++i) {
1326- decoderFeeds[`past_key_values.${i}.key_value`] = new Tensor('float32', [], dims)
1327- }
1328- } else if (this.config.model_type === 'bloom') {
1329- // NOTE: Custom implementation for Bloom
1330-
1331- // @ts-ignore
1332- let keyDims = [batch_size * this.num_heads, this.dim_kv, 0] // [batch_size x num_heads,64,past_sequence_length]
1333- // @ts-ignore
1334- let valueDims = [batch_size * this.num_heads, 0, this.dim_kv] // [batch_size x num_heads,past_sequence_length,64]
1335- // @ts-ignore
1336- for (let i = 0; i < this.num_layers; ++i) {
1337- decoderFeeds[`past_key_values.${i}.key`] = new Tensor('float32', [], keyDims)
1338- decoderFeeds[`past_key_values.${i}.value`] = new Tensor('float32', [], valueDims)
1339- }
1340- } else { // Decoder-only
1341- // @ts-ignore
1342- let dims = [batch_size, this.num_heads, 0, this.dim_kv]
1343- // @ts-ignore
1344- for (let i = 0; i < this.num_layers; ++i) {
1345- decoderFeeds[`past_key_values.${i}.key`] = new Tensor('float32', [], dims)
1346- decoderFeeds[`past_key_values.${i}.value`] = new Tensor('float32', [], dims)
1347- }
1348- }
1535+ } else {
1536+ // Decoder-only
1537+ // @ts-ignore
1538+ let dims = [batch_size, this.num_heads, 0, this.dim_kv];
1539+ // @ts-ignore
1540+ for (let i = 0; i < this.num_layers; ++i) {
1541+ decoderFeeds[`past_key_values.${i}.key`] = new Tensor(
1542+ "float32",
1543+ [],
1544+ dims,
1545+ );
1546+ decoderFeeds[`past_key_values.${i}.value`] = new Tensor(
1547+ "float32",
1548+ [],
1549+ dims,
1550+ );
13491551 }
1350- }
1351-
1352- /**
1353- * Initializes and returns the beam for text generation task
1354- * @param {Tensor} inputTokenIds The input token ids.
1355- * @param {Object} generation_config The generation config.
1356- * @param {number} numOutputTokens The number of tokens to be generated.
1357- * @param {Tensor} inputs_attention_mask Optional input attention mask.
1358- * @returns {any} A Beam object representing the initialized beam.
1359- * @private
1360- */
1361- getStartBeams(inputTokenIds, generation_config, numOutputTokens, inputs_attention_mask) {
1362- return this._getStartBeams(this, inputTokenIds, generation_config, numOutputTokens, inputs_attention_mask)
1363- }
1364-
1365- /**
1366- * Runs a single step of the beam search generation algorithm.
1367- * @param {any} beam The current beam being generated.
1368- * @returns {Promise<any>} The updated beam after a single generation step.
1369- * @private
1370- */
1371- async runBeam(beam) {
1372- return await this._runBeam(this, beam);
1373- }
1374-
1375- /**
1376- * Update a beam with a new token ID.
1377- * @param {Object} beam The beam to update.
1378- * @param {number} newTokenId The new token ID to add to the beam's output.
1379- * @private
1380- */
1381- updateBeam(beam, newTokenId) {
1382- return this._updateBeam(beam, newTokenId);
1383- }
1552+ }
1553+ }
1554+ }
1555+
1556+ /**
1557+ * Initializes and returns the beam for text generation task
1558+ * @param {Tensor} inputTokenIds The input token ids.
1559+ * @param {Object} generation_config The generation config.
1560+ * @param {number} numOutputTokens The number of tokens to be generated.
1561+ * @param {Tensor} inputs_attention_mask Optional input attention mask.
1562+ * @returns {any} A Beam object representing the initialized beam.
1563+ * @private
1564+ */
1565+ getStartBeams(
1566+ inputTokenIds,
1567+ generation_config,
1568+ numOutputTokens,
1569+ inputs_attention_mask,
1570+ ) {
1571+ return this._getStartBeams(
1572+ this,
1573+ inputTokenIds,
1574+ generation_config,
1575+ numOutputTokens,
1576+ inputs_attention_mask,
1577+ );
1578+ }
1579+
1580+ /**
1581+ * Runs a single step of the beam search generation algorithm.
1582+ * @param {any} beam The current beam being generated.
1583+ * @returns {Promise<any>} The updated beam after a single generation step.
1584+ * @private
1585+ */
1586+ async runBeam(beam) {
1587+ return await this._runBeam(this, beam);
1588+ }
1589+
1590+ /**
1591+ * Update a beam with a new token ID.
1592+ * @param {Object} beam The beam to update.
1593+ * @param {number} newTokenId The new token ID to add to the beam's output.
1594+ * @private
1595+ */
1596+ updateBeam(beam, newTokenId) {
1597+ return this._updateBeam(beam, newTokenId);
1598+ }
13841599 }
13851600
13861601 //////////////////////////////////////////////////
13871602 // Base model output class
1388-export class ModelOutput { }
1603+export class ModelOutput {}
13891604
13901605 /**
13911606 * Base class for model's outputs, with potential hidden states and attentions.
13921607 */
13931608 export class BaseModelOutput extends ModelOutput {
1394- /**
1395- * @param {Object} output The output of the model.
1396- * @param {Tensor} output.last_hidden_state Sequence of hidden-states at the output of the last layer of the model.
1397- * @param {Tensor} [output.hidden_states] Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
1398- * @param {Tensor} [output.attentions] Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads.
1399- */
1400- constructor({ last_hidden_state, hidden_states = null, attentions = null }) {
1401- super();
1402- this.last_hidden_state = last_hidden_state;
1403- this.hidden_states = hidden_states;
1404- this.attentions = attentions;
1405- }
1609+ /**
1610+ * @param {Object} output The output of the model.
1611+ * @param {Tensor} output.last_hidden_state Sequence of hidden-states at the output of the last layer of the model.
1612+ * @param {Tensor} [output.hidden_states] Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
1613+ * @param {Tensor} [output.attentions] Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads.
1614+ */
1615+ constructor({ last_hidden_state, hidden_states = null, attentions = null }) {
1616+ super();
1617+ this.last_hidden_state = last_hidden_state;
1618+ this.hidden_states = hidden_states;
1619+ this.attentions = attentions;
1620+ }
14061621 }
14071622 //////////////////////////////////////////////////
14081623 // Bert models
1409-export class BertPreTrainedModel extends PreTrainedModel { }
1410-export class BertModel extends BertPreTrainedModel { }
1624+export class BertPreTrainedModel extends PreTrainedModel {}
1625+export class BertModel extends BertPreTrainedModel {}
14111626
14121627 /**
14131628 * BertForMaskedLM is a class representing a BERT model for masked language modeling.
14141629 */
14151630 export class BertForMaskedLM extends BertPreTrainedModel {
1416- /**
1417- * Calls the model on new inputs.
1418- *
1419- * @param {Object} model_inputs The inputs to the model.
1420- * @returns {Promise<MaskedLMOutput>} An object containing the model's output logits for masked language modeling.
1421- */
1422- async _call(model_inputs) {
1423- return new MaskedLMOutput(await super._call(model_inputs));
1424- }
1631+ /**
1632+ * Calls the model on new inputs.
1633+ *
1634+ * @param {Object} model_inputs The inputs to the model.
1635+ * @returns {Promise<MaskedLMOutput>} An object containing the model's output logits for masked language modeling.
1636+ */
1637+ async _call(model_inputs) {
1638+ return new MaskedLMOutput(await super._call(model_inputs));
1639+ }
14251640 }
14261641
14271642 /**
14281643 * BertForSequenceClassification is a class representing a BERT model for sequence classification.
14291644 */
14301645 export class BertForSequenceClassification extends BertPreTrainedModel {
1431- /**
1432- * Calls the model on new inputs.
1433- *
1434- * @param {Object} model_inputs The inputs to the model.
1435- * @returns {Promise<SequenceClassifierOutput>} An object containing the model's output logits for sequence classification.
1436- */
1437- async _call(model_inputs) {
1438- return new SequenceClassifierOutput(await super._call(model_inputs));
1439- }
1646+ /**
1647+ * Calls the model on new inputs.
1648+ *
1649+ * @param {Object} model_inputs The inputs to the model.
1650+ * @returns {Promise<SequenceClassifierOutput>} An object containing the model's output logits for sequence classification.
1651+ */
1652+ async _call(model_inputs) {
1653+ return new SequenceClassifierOutput(await super._call(model_inputs));
1654+ }
14401655 }
14411656
14421657 /**
14431658 * BertForTokenClassification is a class representing a BERT model for token classification.
14441659 */
14451660 export class BertForTokenClassification extends BertPreTrainedModel {
1446- /**
1447- * Calls the model on new inputs.
1448- *
1449- * @param {Object} model_inputs The inputs to the model.
1450- * @returns {Promise<TokenClassifierOutput>} An object containing the model's output logits for token classification.
1451- */
1452- async _call(model_inputs) {
1453- return new TokenClassifierOutput(await super._call(model_inputs));
1454- }
1661+ /**
1662+ * Calls the model on new inputs.
1663+ *
1664+ * @param {Object} model_inputs The inputs to the model.
1665+ * @returns {Promise<TokenClassifierOutput>} An object containing the model's output logits for token classification.
1666+ */
1667+ async _call(model_inputs) {
1668+ return new TokenClassifierOutput(await super._call(model_inputs));
1669+ }
14551670 }
14561671
14571672 /**
14581673 * BertForQuestionAnswering is a class representing a BERT model for question answering.
14591674 */
14601675 export class BertForQuestionAnswering extends BertPreTrainedModel {
1461- /**
1462- * Calls the model on new inputs.
1463- *
1464- * @param {Object} model_inputs The inputs to the model.
1465- * @returns {Promise<QuestionAnsweringModelOutput>} An object containing the model's output logits for question answering.
1466- */
1467- async _call(model_inputs) {
1468- return new QuestionAnsweringModelOutput(await super._call(model_inputs));
1469- }
1676+ /**
1677+ * Calls the model on new inputs.
1678+ *
1679+ * @param {Object} model_inputs The inputs to the model.
1680+ * @returns {Promise<QuestionAnsweringModelOutput>} An object containing the model's output logits for question answering.
1681+ */
1682+ async _call(model_inputs) {
1683+ return new QuestionAnsweringModelOutput(await super._call(model_inputs));
1684+ }
14701685 }
14711686 //////////////////////////////////////////////////
14721687
14731688 //////////////////////////////////////////////////
14741689 // RoFormer models
1475-export class RoFormerPreTrainedModel extends PreTrainedModel { }
1690+export class RoFormerPreTrainedModel extends PreTrainedModel {}
14761691
14771692 /**
14781693 * The bare RoFormer Model transformer outputting raw hidden-states without any specific head on top.
14791694 */
1480-export class RoFormerModel extends RoFormerPreTrainedModel { }
1695+export class RoFormerModel extends RoFormerPreTrainedModel {}
14811696
14821697 /**
14831698 * RoFormer Model with a `language modeling` head on top.
14841699 */
14851700 export class RoFormerForMaskedLM extends RoFormerPreTrainedModel {
1486- /**
1487- * Calls the model on new inputs.
1488- *
1489- * @param {Object} model_inputs The inputs to the model.
1490- * @returns {Promise<MaskedLMOutput>} An object containing the model's output logits for masked language modeling.
1491- */
1492- async _call(model_inputs) {
1493- return new MaskedLMOutput(await super._call(model_inputs));
1494- }
1701+ /**
1702+ * Calls the model on new inputs.
1703+ *
1704+ * @param {Object} model_inputs The inputs to the model.
1705+ * @returns {Promise<MaskedLMOutput>} An object containing the model's output logits for masked language modeling.
1706+ */
1707+ async _call(model_inputs) {
1708+ return new MaskedLMOutput(await super._call(model_inputs));
1709+ }
14951710 }
14961711
14971712 /**
14981713 * RoFormer Model transformer with a sequence classification/regression head on top (a linear layer on top of the pooled output)
14991714 */
15001715 export class RoFormerForSequenceClassification extends RoFormerPreTrainedModel {
1501- /**
1502- * Calls the model on new inputs.
1503- *
1504- * @param {Object} model_inputs The inputs to the model.
1505- * @returns {Promise<SequenceClassifierOutput>} An object containing the model's output logits for sequence classification.
1506- */
1507- async _call(model_inputs) {
1508- return new SequenceClassifierOutput(await super._call(model_inputs));
1509- }
1716+ /**
1717+ * Calls the model on new inputs.
1718+ *
1719+ * @param {Object} model_inputs The inputs to the model.
1720+ * @returns {Promise<SequenceClassifierOutput>} An object containing the model's output logits for sequence classification.
1721+ */
1722+ async _call(model_inputs) {
1723+ return new SequenceClassifierOutput(await super._call(model_inputs));
1724+ }
15101725 }
15111726
15121727 /**
@@ -1514,15 +1729,15 @@
15141729 * e.g. for Named-Entity-Recognition (NER) tasks.
15151730 */
15161731 export class RoFormerForTokenClassification extends RoFormerPreTrainedModel {
1517- /**
1518- * Calls the model on new inputs.
1519- *
1520- * @param {Object} model_inputs The inputs to the model.
1521- * @returns {Promise<TokenClassifierOutput>} An object containing the model's output logits for token classification.
1522- */
1523- async _call(model_inputs) {
1524- return new TokenClassifierOutput(await super._call(model_inputs));
1525- }
1732+ /**
1733+ * Calls the model on new inputs.
1734+ *
1735+ * @param {Object} model_inputs The inputs to the model.
1736+ * @returns {Promise<TokenClassifierOutput>} An object containing the model's output logits for token classification.
1737+ */
1738+ async _call(model_inputs) {
1739+ return new TokenClassifierOutput(await super._call(model_inputs));
1740+ }
15261741 }
15271742
15281743 /**
@@ -1530,56 +1745,56 @@
15301745 * (a linear layers on top of the hidden-states output to compute `span start logits` and `span end logits`).
15311746 */
15321747 export class RoFormerForQuestionAnswering extends RoFormerPreTrainedModel {
1533- /**
1534- * Calls the model on new inputs.
1535- *
1536- * @param {Object} model_inputs The inputs to the model.
1537- * @returns {Promise<QuestionAnsweringModelOutput>} An object containing the model's output logits for question answering.
1538- */
1539- async _call(model_inputs) {
1540- return new QuestionAnsweringModelOutput(await super._call(model_inputs));
1541- }
1748+ /**
1749+ * Calls the model on new inputs.
1750+ *
1751+ * @param {Object} model_inputs The inputs to the model.
1752+ * @returns {Promise<QuestionAnsweringModelOutput>} An object containing the model's output logits for question answering.
1753+ */
1754+ async _call(model_inputs) {
1755+ return new QuestionAnsweringModelOutput(await super._call(model_inputs));
1756+ }
15421757 }
15431758 // TODO: Add RoFormerForCausalLM and RoFormerForMultipleChoice
15441759 //////////////////////////////////////////////////
15451760
15461761 //////////////////////////////////////////////////
15471762 // ConvBert models
1548-export class ConvBertPreTrainedModel extends PreTrainedModel { }
1763+export class ConvBertPreTrainedModel extends PreTrainedModel {}
15491764
15501765 /**
15511766 * The bare ConvBERT Model transformer outputting raw hidden-states without any specific head on top.
15521767 */
1553-export class ConvBertModel extends ConvBertPreTrainedModel { }
1768+export class ConvBertModel extends ConvBertPreTrainedModel {}
15541769
15551770 /**
15561771 * ConvBERT Model with a language modeling head on top.
15571772 */
15581773 export class ConvBertForMaskedLM extends ConvBertPreTrainedModel {
1559- /**
1560- * Calls the model on new inputs.
1561- *
1562- * @param {Object} model_inputs The inputs to the model.
1563- * @returns {Promise<MaskedLMOutput>} An object containing the model's output logits for masked language modeling.
1564- */
1565- async _call(model_inputs) {
1566- return new MaskedLMOutput(await super._call(model_inputs));
1567- }
1774+ /**
1775+ * Calls the model on new inputs.
1776+ *
1777+ * @param {Object} model_inputs The inputs to the model.
1778+ * @returns {Promise<MaskedLMOutput>} An object containing the model's output logits for masked language modeling.
1779+ */
1780+ async _call(model_inputs) {
1781+ return new MaskedLMOutput(await super._call(model_inputs));
1782+ }
15681783 }
15691784
15701785 /**
15711786 * ConvBERT Model transformer with a sequence classification/regression head on top (a linear layer on top of the pooled output)
15721787 */
15731788 export class ConvBertForSequenceClassification extends ConvBertPreTrainedModel {
1574- /**
1575- * Calls the model on new inputs.
1576- *
1577- * @param {Object} model_inputs The inputs to the model.
1578- * @returns {Promise<SequenceClassifierOutput>} An object containing the model's output logits for sequence classification.
1579- */
1580- async _call(model_inputs) {
1581- return new SequenceClassifierOutput(await super._call(model_inputs));
1582- }
1789+ /**
1790+ * Calls the model on new inputs.
1791+ *
1792+ * @param {Object} model_inputs The inputs to the model.
1793+ * @returns {Promise<SequenceClassifierOutput>} An object containing the model's output logits for sequence classification.
1794+ */
1795+ async _call(model_inputs) {
1796+ return new SequenceClassifierOutput(await super._call(model_inputs));
1797+ }
15831798 }
15841799
15851800 /**
@@ -1587,15 +1802,15 @@
15871802 * e.g. for Named-Entity-Recognition (NER) tasks.
15881803 */
15891804 export class ConvBertForTokenClassification extends ConvBertPreTrainedModel {
1590- /**
1591- * Calls the model on new inputs.
1592- *
1593- * @param {Object} model_inputs The inputs to the model.
1594- * @returns {Promise<TokenClassifierOutput>} An object containing the model's output logits for token classification.
1595- */
1596- async _call(model_inputs) {
1597- return new TokenClassifierOutput(await super._call(model_inputs));
1598- }
1805+ /**
1806+ * Calls the model on new inputs.
1807+ *
1808+ * @param {Object} model_inputs The inputs to the model.
1809+ * @returns {Promise<TokenClassifierOutput>} An object containing the model's output logits for token classification.
1810+ */
1811+ async _call(model_inputs) {
1812+ return new TokenClassifierOutput(await super._call(model_inputs));
1813+ }
15991814 }
16001815
16011816 /**
@@ -1603,73 +1818,72 @@
16031818 * (a linear layers on top of the hidden-states output to compute `span start logits` and `span end logits`)
16041819 */
16051820 export class ConvBertForQuestionAnswering extends ConvBertPreTrainedModel {
1606- /**
1607- * Calls the model on new inputs.
1608- *
1609- * @param {Object} model_inputs The inputs to the model.
1610- * @returns {Promise<QuestionAnsweringModelOutput>} An object containing the model's output logits for question answering.
1611- */
1612- async _call(model_inputs) {
1613- return new QuestionAnsweringModelOutput(await super._call(model_inputs));
1614- }
1821+ /**
1822+ * Calls the model on new inputs.
1823+ *
1824+ * @param {Object} model_inputs The inputs to the model.
1825+ * @returns {Promise<QuestionAnsweringModelOutput>} An object containing the model's output logits for question answering.
1826+ */
1827+ async _call(model_inputs) {
1828+ return new QuestionAnsweringModelOutput(await super._call(model_inputs));
1829+ }
16151830 }
16161831 //////////////////////////////////////////////////
16171832
1618-
16191833 //////////////////////////////////////////////////
16201834 // Electra models
1621-export class ElectraPreTrainedModel extends PreTrainedModel { }
1835+export class ElectraPreTrainedModel extends PreTrainedModel {}
16221836
16231837 /**
16241838 * The bare Electra Model transformer outputting raw hidden-states without any specific head on top.
16251839 * Identical to the BERT model except that it uses an additional linear layer between the embedding
16261840 * layer and the encoder if the hidden size and embedding size are different.
16271841 */
1628-export class ElectraModel extends ElectraPreTrainedModel { }
1842+export class ElectraModel extends ElectraPreTrainedModel {}
16291843 // TODO add ElectraForPreTraining
16301844 /**
16311845 * Electra model with a language modeling head on top.
16321846 */
16331847 export class ElectraForMaskedLM extends ElectraPreTrainedModel {
1634- /**
1635- * Calls the model on new inputs.
1636- *
1637- * @param {Object} model_inputs The inputs to the model.
1638- * @returns {Promise<MaskedLMOutput>} An object containing the model's output logits for masked language modeling.
1639- */
1640- async _call(model_inputs) {
1641- return new MaskedLMOutput(await super._call(model_inputs));
1642- }
1848+ /**
1849+ * Calls the model on new inputs.
1850+ *
1851+ * @param {Object} model_inputs The inputs to the model.
1852+ * @returns {Promise<MaskedLMOutput>} An object containing the model's output logits for masked language modeling.
1853+ */
1854+ async _call(model_inputs) {
1855+ return new MaskedLMOutput(await super._call(model_inputs));
1856+ }
16431857 }
16441858
16451859 /**
16461860 * ELECTRA Model transformer with a sequence classification/regression head on top (a linear layer on top of the pooled output)
16471861 */
16481862 export class ElectraForSequenceClassification extends ElectraPreTrainedModel {
1649- /**
1650- * Calls the model on new inputs.
1651- *
1652- * @param {Object} model_inputs The inputs to the model.
1653- * @returns {Promise<SequenceClassifierOutput>} An object containing the model's output logits for sequence classification.
1654- */
1655- async _call(model_inputs) {
1656- return new SequenceClassifierOutput(await super._call(model_inputs));
1657- }
1863+ /**
1864+ * Calls the model on new inputs.
1865+ *
1866+ * @param {Object} model_inputs The inputs to the model.
1867+ * @returns {Promise<SequenceClassifierOutput>} An object containing the model's output logits for sequence classification.
1868+ */
1869+ async _call(model_inputs) {
1870+ return new SequenceClassifierOutput(await super._call(model_inputs));
1871+ }
16581872 }
16591873
16601874 /**
16611875 * Electra model with a token classification head on top.
16621876 */
16631877 export class ElectraForTokenClassification extends ElectraPreTrainedModel {
1664- /**
1665- * Calls the model on new inputs.
1666- *
1667- * @param {Object} model_inputs The inputs to the model.
1668- * @returns {Promise<TokenClassifierOutput>} An object containing the model's output logits for token classification.
1669- */
1670- async _call(model_inputs) {
1671- return new TokenClassifierOutput(await super._call(model_inputs));
1672- }
1878+ /**
1879+ * Calls the model on new inputs.
1880+ *
1881+ * @param {Object} model_inputs The inputs to the model.
1882+ * @returns {Promise<TokenClassifierOutput>} An object containing the model's output logits for token classification.
1883+ */
1884+ async _call(model_inputs) {
1885+ return new TokenClassifierOutput(await super._call(model_inputs));
1886+ }
16731887 }
16741888
16751889 /**
@@ -1677,141 +1891,140 @@
16771891 * (a linear layers on top of the hidden-states output to compute `span start logits` and `span end logits`).
16781892 */
16791893 export class ElectraForQuestionAnswering extends ElectraPreTrainedModel {
1680- /**
1681- * Calls the model on new inputs.
1682- *
1683- * @param {Object} model_inputs The inputs to the model.
1684- * @returns {Promise<QuestionAnsweringModelOutput>} An object containing the model's output logits for question answering.
1685- */
1686- async _call(model_inputs) {
1687- return new QuestionAnsweringModelOutput(await super._call(model_inputs));
1688- }
1894+ /**
1895+ * Calls the model on new inputs.
1896+ *
1897+ * @param {Object} model_inputs The inputs to the model.
1898+ * @returns {Promise<QuestionAnsweringModelOutput>} An object containing the model's output logits for question answering.
1899+ */
1900+ async _call(model_inputs) {
1901+ return new QuestionAnsweringModelOutput(await super._call(model_inputs));
1902+ }
16891903 }
16901904 //////////////////////////////////////////////////
16911905
1692-
16931906 //////////////////////////////////////////////////
16941907 // CamemBERT models
1695-export class CamembertPreTrainedModel extends PreTrainedModel { }
1908+export class CamembertPreTrainedModel extends PreTrainedModel {}
16961909
16971910 /**
16981911 * The bare CamemBERT Model transformer outputting raw hidden-states without any specific head on top.
16991912 */
1700-export class CamembertModel extends CamembertPreTrainedModel { }
1913+export class CamembertModel extends CamembertPreTrainedModel {}
17011914
17021915 /**
17031916 * CamemBERT Model with a `language modeling` head on top.
17041917 */
17051918 export class CamembertForMaskedLM extends CamembertPreTrainedModel {
1706- /**
1707- * Calls the model on new inputs.
1708- *
1709- * @param {Object} model_inputs The inputs to the model.
1710- * @returns {Promise<MaskedLMOutput>} An object containing the model's output logits for masked language modeling.
1711- */
1712- async _call(model_inputs) {
1713- return new MaskedLMOutput(await super._call(model_inputs));
1714- }
1919+ /**
1920+ * Calls the model on new inputs.
1921+ *
1922+ * @param {Object} model_inputs The inputs to the model.
1923+ * @returns {Promise<MaskedLMOutput>} An object containing the model's output logits for masked language modeling.
1924+ */
1925+ async _call(model_inputs) {
1926+ return new MaskedLMOutput(await super._call(model_inputs));
1927+ }
17151928 }
17161929
17171930 /**
17181931 * CamemBERT Model transformer with a sequence classification/regression head on top (a linear layer on top of the pooled output) e.g. for GLUE tasks.
17191932 */
17201933 export class CamembertForSequenceClassification extends CamembertPreTrainedModel {
1721- /**
1722- * Calls the model on new inputs.
1723- *
1724- * @param {Object} model_inputs The inputs to the model.
1725- * @returns {Promise<SequenceClassifierOutput>} An object containing the model's output logits for sequence classification.
1726- */
1727- async _call(model_inputs) {
1728- return new SequenceClassifierOutput(await super._call(model_inputs));
1729- }
1934+ /**
1935+ * Calls the model on new inputs.
1936+ *
1937+ * @param {Object} model_inputs The inputs to the model.
1938+ * @returns {Promise<SequenceClassifierOutput>} An object containing the model's output logits for sequence classification.
1939+ */
1940+ async _call(model_inputs) {
1941+ return new SequenceClassifierOutput(await super._call(model_inputs));
1942+ }
17301943 }
17311944
17321945 /**
17331946 * CamemBERT Model with a token classification head on top (a linear layer on top of the hidden-states output) e.g. for Named-Entity-Recognition (NER) tasks.
17341947 */
17351948 export class CamembertForTokenClassification extends CamembertPreTrainedModel {
1736- /**
1737- * Calls the model on new inputs.
1738- *
1739- * @param {Object} model_inputs The inputs to the model.
1740- * @returns {Promise<TokenClassifierOutput>} An object containing the model's output logits for token classification.
1741- */
1742- async _call(model_inputs) {
1743- return new TokenClassifierOutput(await super._call(model_inputs));
1744- }
1949+ /**
1950+ * Calls the model on new inputs.
1951+ *
1952+ * @param {Object} model_inputs The inputs to the model.
1953+ * @returns {Promise<TokenClassifierOutput>} An object containing the model's output logits for token classification.
1954+ */
1955+ async _call(model_inputs) {
1956+ return new TokenClassifierOutput(await super._call(model_inputs));
1957+ }
17451958 }
17461959
17471960 /**
17481961 * CamemBERT Model with a span classification head on top for extractive question-answering tasks
17491962 */
17501963 export class CamembertForQuestionAnswering extends CamembertPreTrainedModel {
1751- /**
1752- * Calls the model on new inputs.
1753- *
1754- * @param {Object} model_inputs The inputs to the model.
1755- * @returns {Promise<QuestionAnsweringModelOutput>} An object containing the model's output logits for question answering.
1756- */
1757- async _call(model_inputs) {
1758- return new QuestionAnsweringModelOutput(await super._call(model_inputs));
1759- }
1964+ /**
1965+ * Calls the model on new inputs.
1966+ *
1967+ * @param {Object} model_inputs The inputs to the model.
1968+ * @returns {Promise<QuestionAnsweringModelOutput>} An object containing the model's output logits for question answering.
1969+ */
1970+ async _call(model_inputs) {
1971+ return new QuestionAnsweringModelOutput(await super._call(model_inputs));
1972+ }
17601973 }
17611974 //////////////////////////////////////////////////
17621975
17631976 //////////////////////////////////////////////////
17641977 // DeBERTa models
1765-export class DebertaPreTrainedModel extends PreTrainedModel { }
1978+export class DebertaPreTrainedModel extends PreTrainedModel {}
17661979
17671980 /**
17681981 * The bare DeBERTa Model transformer outputting raw hidden-states without any specific head on top.
17691982 */
1770-export class DebertaModel extends DebertaPreTrainedModel { }
1983+export class DebertaModel extends DebertaPreTrainedModel {}
17711984
17721985 /**
17731986 * DeBERTa Model with a `language modeling` head on top.
17741987 */
17751988 export class DebertaForMaskedLM extends DebertaPreTrainedModel {
1776- /**
1777- * Calls the model on new inputs.
1778- *
1779- * @param {Object} model_inputs The inputs to the model.
1780- * @returns {Promise<MaskedLMOutput>} An object containing the model's output logits for masked language modeling.
1781- */
1782- async _call(model_inputs) {
1783- return new MaskedLMOutput(await super._call(model_inputs));
1784- }
1989+ /**
1990+ * Calls the model on new inputs.
1991+ *
1992+ * @param {Object} model_inputs The inputs to the model.
1993+ * @returns {Promise<MaskedLMOutput>} An object containing the model's output logits for masked language modeling.
1994+ */
1995+ async _call(model_inputs) {
1996+ return new MaskedLMOutput(await super._call(model_inputs));
1997+ }
17851998 }
17861999
17872000 /**
17882001 * DeBERTa Model transformer with a sequence classification/regression head on top (a linear layer on top of the pooled output)
17892002 */
17902003 export class DebertaForSequenceClassification extends DebertaPreTrainedModel {
1791- /**
1792- * Calls the model on new inputs.
1793- *
1794- * @param {Object} model_inputs The inputs to the model.
1795- * @returns {Promise<SequenceClassifierOutput>} An object containing the model's output logits for sequence classification.
1796- */
1797- async _call(model_inputs) {
1798- return new SequenceClassifierOutput(await super._call(model_inputs));
1799- }
2004+ /**
2005+ * Calls the model on new inputs.
2006+ *
2007+ * @param {Object} model_inputs The inputs to the model.
2008+ * @returns {Promise<SequenceClassifierOutput>} An object containing the model's output logits for sequence classification.
2009+ */
2010+ async _call(model_inputs) {
2011+ return new SequenceClassifierOutput(await super._call(model_inputs));
2012+ }
18002013 }
18012014
18022015 /**
18032016 * DeBERTa Model with a token classification head on top (a linear layer on top of the hidden-states output) e.g. for Named-Entity-Recognition (NER) tasks.
18042017 */
18052018 export class DebertaForTokenClassification extends DebertaPreTrainedModel {
1806- /**
1807- * Calls the model on new inputs.
1808- *
1809- * @param {Object} model_inputs The inputs to the model.
1810- * @returns {Promise<TokenClassifierOutput>} An object containing the model's output logits for token classification.
1811- */
1812- async _call(model_inputs) {
1813- return new TokenClassifierOutput(await super._call(model_inputs));
1814- }
2019+ /**
2020+ * Calls the model on new inputs.
2021+ *
2022+ * @param {Object} model_inputs The inputs to the model.
2023+ * @returns {Promise<TokenClassifierOutput>} An object containing the model's output logits for token classification.
2024+ */
2025+ async _call(model_inputs) {
2026+ return new TokenClassifierOutput(await super._call(model_inputs));
2027+ }
18152028 }
18162029
18172030 /**
@@ -1819,70 +2032,70 @@
18192032 * layers on top of the hidden-states output to compute `span start logits` and `span end logits`).
18202033 */
18212034 export class DebertaForQuestionAnswering extends DebertaPreTrainedModel {
1822- /**
1823- * Calls the model on new inputs.
1824- *
1825- * @param {Object} model_inputs The inputs to the model.
1826- * @returns {Promise<QuestionAnsweringModelOutput>} An object containing the model's output logits for question answering.
1827- */
1828- async _call(model_inputs) {
1829- return new QuestionAnsweringModelOutput(await super._call(model_inputs));
1830- }
2035+ /**
2036+ * Calls the model on new inputs.
2037+ *
2038+ * @param {Object} model_inputs The inputs to the model.
2039+ * @returns {Promise<QuestionAnsweringModelOutput>} An object containing the model's output logits for question answering.
2040+ */
2041+ async _call(model_inputs) {
2042+ return new QuestionAnsweringModelOutput(await super._call(model_inputs));
2043+ }
18312044 }
18322045 //////////////////////////////////////////////////
18332046
18342047 //////////////////////////////////////////////////
18352048 // DeBERTa-v2 models
1836-export class DebertaV2PreTrainedModel extends PreTrainedModel { }
2049+export class DebertaV2PreTrainedModel extends PreTrainedModel {}
18372050
18382051 /**
18392052 * The bare DeBERTa-V2 Model transformer outputting raw hidden-states without any specific head on top.
18402053 */
1841-export class DebertaV2Model extends DebertaV2PreTrainedModel { }
2054+export class DebertaV2Model extends DebertaV2PreTrainedModel {}
18422055
18432056 /**
18442057 * DeBERTa-V2 Model with a `language modeling` head on top.
18452058 */
18462059 export class DebertaV2ForMaskedLM extends DebertaV2PreTrainedModel {
1847- /**
1848- * Calls the model on new inputs.
1849- *
1850- * @param {Object} model_inputs The inputs to the model.
1851- * @returns {Promise<MaskedLMOutput>} An object containing the model's output logits for masked language modeling.
1852- */
1853- async _call(model_inputs) {
1854- return new MaskedLMOutput(await super._call(model_inputs));
1855- }
2060+ /**
2061+ * Calls the model on new inputs.
2062+ *
2063+ * @param {Object} model_inputs The inputs to the model.
2064+ * @returns {Promise<MaskedLMOutput>} An object containing the model's output logits for masked language modeling.
2065+ */
2066+ async _call(model_inputs) {
2067+ return new MaskedLMOutput(await super._call(model_inputs));
2068+ }
18562069 }
18572070
18582071 /**
18592072 * DeBERTa-V2 Model transformer with a sequence classification/regression head on top (a linear layer on top of the pooled output)
18602073 */
18612074 export class DebertaV2ForSequenceClassification extends DebertaV2PreTrainedModel {
1862- /**
1863- * Calls the model on new inputs.
1864- *
1865- * @param {Object} model_inputs The inputs to the model.
1866- * @returns {Promise<SequenceClassifierOutput>} An object containing the model's output logits for sequence classification.
1867- */
1868- async _call(model_inputs) {
1869- return new SequenceClassifierOutput(await super._call(model_inputs));
1870- }
2075+ /**
2076+ * Calls the model on new inputs.
2077+ *
2078+ * @param {Object} model_inputs The inputs to the model.
2079+ * @returns {Promise<SequenceClassifierOutput>} An object containing the model's output logits for sequence classification.
2080+ */
2081+ async _call(model_inputs) {
2082+ return new SequenceClassifierOutput(await super._call(model_inputs));
2083+ }
18712084 }
18722085
18732086 /**
18742087 * DeBERTa-V2 Model with a token classification head on top (a linear layer on top of the hidden-states output) e.g. for Named-Entity-Recognition (NER) tasks.
18752088 */
18762089 export class DebertaV2ForTokenClassification extends DebertaV2PreTrainedModel {
1877- /**
1878- * Calls the model on new inputs.
1879- *
1880- * @param {Object} model_inputs The inputs to the model.
1881- * @returns {Promise<TokenClassifierOutput>} An object containing the model's output logits for token classification.
1882- */
1883- async _call(model_inputs) {
1884- return new TokenClassifierOutput(await super._call(model_inputs));
1885- }
2090+ /**
2091+ * Calls the model on new inputs.
2092+ *
2093+ * @param {Object} model_inputs The inputs to the model.
2094+ * @returns {Promise<TokenClassifierOutput>} An object containing the model's output logits for token classification.
2095+ */
2096+ async _call(model_inputs) {
2097+ return new TokenClassifierOutput(await super._call(model_inputs));
2098+ }
18862099 }
18872100
18882101 /**
@@ -1890,123 +2103,121 @@
18902103 * layers on top of the hidden-states output to compute `span start logits` and `span end logits`).
18912104 */
18922105 export class DebertaV2ForQuestionAnswering extends DebertaV2PreTrainedModel {
1893- /**
1894- * Calls the model on new inputs.
1895- *
1896- * @param {Object} model_inputs The inputs to the model.
1897- * @returns {Promise<QuestionAnsweringModelOutput>} An object containing the model's output logits for question answering.
1898- */
1899- async _call(model_inputs) {
1900- return new QuestionAnsweringModelOutput(await super._call(model_inputs));
1901- }
2106+ /**
2107+ * Calls the model on new inputs.
2108+ *
2109+ * @param {Object} model_inputs The inputs to the model.
2110+ * @returns {Promise<QuestionAnsweringModelOutput>} An object containing the model's output logits for question answering.
2111+ */
2112+ async _call(model_inputs) {
2113+ return new QuestionAnsweringModelOutput(await super._call(model_inputs));
2114+ }
19022115 }
19032116 //////////////////////////////////////////////////
19042117
19052118 //////////////////////////////////////////////////
19062119 // DistilBert models
1907-export class DistilBertPreTrainedModel extends PreTrainedModel { }
1908-export class DistilBertModel extends DistilBertPreTrainedModel { }
2120+export class DistilBertPreTrainedModel extends PreTrainedModel {}
2121+export class DistilBertModel extends DistilBertPreTrainedModel {}
19092122
19102123 /**
19112124 * DistilBertForSequenceClassification is a class representing a DistilBERT model for sequence classification.
19122125 */
19132126 export class DistilBertForSequenceClassification extends DistilBertPreTrainedModel {
1914- /**
1915- * Calls the model on new inputs.
1916- *
1917- * @param {Object} model_inputs The inputs to the model.
1918- * @returns {Promise<SequenceClassifierOutput>} An object containing the model's output logits for sequence classification.
1919- */
1920- async _call(model_inputs) {
1921- return new SequenceClassifierOutput(await super._call(model_inputs));
1922- }
2127+ /**
2128+ * Calls the model on new inputs.
2129+ *
2130+ * @param {Object} model_inputs The inputs to the model.
2131+ * @returns {Promise<SequenceClassifierOutput>} An object containing the model's output logits for sequence classification.
2132+ */
2133+ async _call(model_inputs) {
2134+ return new SequenceClassifierOutput(await super._call(model_inputs));
2135+ }
19232136 }
19242137
19252138 /**
19262139 * DistilBertForTokenClassification is a class representing a DistilBERT model for token classification.
19272140 */
19282141 export class DistilBertForTokenClassification extends DistilBertPreTrainedModel {
1929- /**
1930- * Calls the model on new inputs.
1931- *
1932- * @param {Object} model_inputs The inputs to the model.
1933- * @returns {Promise<TokenClassifierOutput>} An object containing the model's output logits for token classification.
1934- */
1935- async _call(model_inputs) {
1936- return new TokenClassifierOutput(await super._call(model_inputs));
1937- }
2142+ /**
2143+ * Calls the model on new inputs.
2144+ *
2145+ * @param {Object} model_inputs The inputs to the model.
2146+ * @returns {Promise<TokenClassifierOutput>} An object containing the model's output logits for token classification.
2147+ */
2148+ async _call(model_inputs) {
2149+ return new TokenClassifierOutput(await super._call(model_inputs));
2150+ }
19382151 }
19392152
1940-
19412153 /**
19422154 * DistilBertForQuestionAnswering is a class representing a DistilBERT model for question answering.
19432155 */
19442156 export class DistilBertForQuestionAnswering extends DistilBertPreTrainedModel {
1945- /**
1946- * Calls the model on new inputs.
1947- *
1948- * @param {Object} model_inputs The inputs to the model.
1949- * @returns {Promise<QuestionAnsweringModelOutput>} An object containing the model's output logits for question answering.
1950- */
1951- async _call(model_inputs) {
1952- return new QuestionAnsweringModelOutput(await super._call(model_inputs));
1953- }
2157+ /**
2158+ * Calls the model on new inputs.
2159+ *
2160+ * @param {Object} model_inputs The inputs to the model.
2161+ * @returns {Promise<QuestionAnsweringModelOutput>} An object containing the model's output logits for question answering.
2162+ */
2163+ async _call(model_inputs) {
2164+ return new QuestionAnsweringModelOutput(await super._call(model_inputs));
2165+ }
19542166 }
19552167
19562168 /**
19572169 * DistilBertForMaskedLM is a class representing a DistilBERT model for masking task.
19582170 */
19592171 export class DistilBertForMaskedLM extends DistilBertPreTrainedModel {
1960- /**
1961- * Calls the model on new inputs.
1962- *
1963- * @param {Object} model_inputs The inputs to the model.
1964- * @returns {Promise<MaskedLMOutput>} returned object
1965- */
1966- async _call(model_inputs) {
1967- return new MaskedLMOutput(await super._call(model_inputs));
1968- }
2172+ /**
2173+ * Calls the model on new inputs.
2174+ *
2175+ * @param {Object} model_inputs The inputs to the model.
2176+ * @returns {Promise<MaskedLMOutput>} returned object
2177+ */
2178+ async _call(model_inputs) {
2179+ return new MaskedLMOutput(await super._call(model_inputs));
2180+ }
19692181 }
19702182 //////////////////////////////////////////////////
19712183
1972-
19732184 //////////////////////////////////////////////////
19742185 // ESM models
1975-export class EsmPreTrainedModel extends PreTrainedModel { }
2186+export class EsmPreTrainedModel extends PreTrainedModel {}
19762187
19772188 /**
19782189 * The bare ESM Model transformer outputting raw hidden-states without any specific head on top.
19792190 */
1980-export class EsmModel extends EsmPreTrainedModel { }
2191+export class EsmModel extends EsmPreTrainedModel {}
19812192
19822193 /**
19832194 * ESM Model with a `language modeling` head on top.
19842195 */
19852196 export class EsmForMaskedLM extends EsmPreTrainedModel {
1986- /**
1987- * Calls the model on new inputs.
1988- *
1989- * @param {Object} model_inputs The inputs to the model.
1990- * @returns {Promise<MaskedLMOutput>} An object containing the model's output logits for masked language modeling.
1991- */
1992- async _call(model_inputs) {
1993- return new MaskedLMOutput(await super._call(model_inputs));
1994- }
2197+ /**
2198+ * Calls the model on new inputs.
2199+ *
2200+ * @param {Object} model_inputs The inputs to the model.
2201+ * @returns {Promise<MaskedLMOutput>} An object containing the model's output logits for masked language modeling.
2202+ */
2203+ async _call(model_inputs) {
2204+ return new MaskedLMOutput(await super._call(model_inputs));
2205+ }
19952206 }
19962207
19972208 /**
19982209 * ESM Model transformer with a sequence classification/regression head on top (a linear layer on top of the pooled output)
19992210 */
20002211 export class EsmForSequenceClassification extends EsmPreTrainedModel {
2001- /**
2002- * Calls the model on new inputs.
2003- *
2004- * @param {Object} model_inputs The inputs to the model.
2005- * @returns {Promise<SequenceClassifierOutput>} An object containing the model's output logits for sequence classification.
2006- */
2007- async _call(model_inputs) {
2008- return new SequenceClassifierOutput(await super._call(model_inputs));
2009- }
2212+ /**
2213+ * Calls the model on new inputs.
2214+ *
2215+ * @param {Object} model_inputs The inputs to the model.
2216+ * @returns {Promise<SequenceClassifierOutput>} An object containing the model's output logits for sequence classification.
2217+ */
2218+ async _call(model_inputs) {
2219+ return new SequenceClassifierOutput(await super._call(model_inputs));
2220+ }
20102221 }
20112222
20122223 /**
@@ -2014,849 +2225,932 @@
20142225 * e.g. for Named-Entity-Recognition (NER) tasks.
20152226 */
20162227 export class EsmForTokenClassification extends EsmPreTrainedModel {
2017- /**
2018- * Calls the model on new inputs.
2019- *
2020- * @param {Object} model_inputs The inputs to the model.
2021- * @returns {Promise<TokenClassifierOutput>} An object containing the model's output logits for token classification.
2022- */
2023- async _call(model_inputs) {
2024- return new TokenClassifierOutput(await super._call(model_inputs));
2025- }
2228+ /**
2229+ * Calls the model on new inputs.
2230+ *
2231+ * @param {Object} model_inputs The inputs to the model.
2232+ * @returns {Promise<TokenClassifierOutput>} An object containing the model's output logits for token classification.
2233+ */
2234+ async _call(model_inputs) {
2235+ return new TokenClassifierOutput(await super._call(model_inputs));
2236+ }
20262237 }
20272238 //////////////////////////////////////////////////
20282239
2029-
20302240 //////////////////////////////////////////////////
20312241 // MobileBert models
2032-export class MobileBertPreTrainedModel extends PreTrainedModel { }
2033-export class MobileBertModel extends MobileBertPreTrainedModel { }
2242+export class MobileBertPreTrainedModel extends PreTrainedModel {}
2243+export class MobileBertModel extends MobileBertPreTrainedModel {}
20342244
20352245 /**
20362246 * MobileBertForMaskedLM is a class representing a MobileBERT model for masking task.
20372247 */
20382248 export class MobileBertForMaskedLM extends MobileBertPreTrainedModel {
2039- /**
2040- * Calls the model on new inputs.
2041- *
2042- * @param {Object} model_inputs The inputs to the model.
2043- * @returns {Promise<MaskedLMOutput>} returned object
2044- */
2045- async _call(model_inputs) {
2046- return new MaskedLMOutput(await super._call(model_inputs));
2047- }
2249+ /**
2250+ * Calls the model on new inputs.
2251+ *
2252+ * @param {Object} model_inputs The inputs to the model.
2253+ * @returns {Promise<MaskedLMOutput>} returned object
2254+ */
2255+ async _call(model_inputs) {
2256+ return new MaskedLMOutput(await super._call(model_inputs));
2257+ }
20482258 }
20492259
20502260 /**
20512261 * MobileBert Model transformer with a sequence classification/regression head on top (a linear layer on top of the pooled output)
20522262 */
20532263 export class MobileBertForSequenceClassification extends MobileBertPreTrainedModel {
2054- /**
2055- * Calls the model on new inputs.
2056- *
2057- * @param {Object} model_inputs The inputs to the model.
2058- * @returns {Promise<SequenceClassifierOutput>} returned object
2059- */
2060- async _call(model_inputs) {
2061- return new SequenceClassifierOutput(await super._call(model_inputs));
2062- }
2264+ /**
2265+ * Calls the model on new inputs.
2266+ *
2267+ * @param {Object} model_inputs The inputs to the model.
2268+ * @returns {Promise<SequenceClassifierOutput>} returned object
2269+ */
2270+ async _call(model_inputs) {
2271+ return new SequenceClassifierOutput(await super._call(model_inputs));
2272+ }
20632273 }
20642274
20652275 /**
20662276 * MobileBert Model with a span classification head on top for extractive question-answering tasks
20672277 */
20682278 export class MobileBertForQuestionAnswering extends MobileBertPreTrainedModel {
2069- /**
2070- * Calls the model on new inputs.
2071- *
2072- * @param {Object} model_inputs The inputs to the model.
2073- * @returns {Promise<QuestionAnsweringModelOutput>} returned object
2074- */
2075- async _call(model_inputs) {
2076- return new QuestionAnsweringModelOutput(await super._call(model_inputs));
2077- }
2279+ /**
2280+ * Calls the model on new inputs.
2281+ *
2282+ * @param {Object} model_inputs The inputs to the model.
2283+ * @returns {Promise<QuestionAnsweringModelOutput>} returned object
2284+ */
2285+ async _call(model_inputs) {
2286+ return new QuestionAnsweringModelOutput(await super._call(model_inputs));
2287+ }
20782288 }
20792289 //////////////////////////////////////////////////
20802290
20812291 //////////////////////////////////////////////////
20822292 // MPNet models
2083-export class MPNetPreTrainedModel extends PreTrainedModel { }
2293+export class MPNetPreTrainedModel extends PreTrainedModel {}
20842294
20852295 /**
20862296 * The bare MPNet Model transformer outputting raw hidden-states without any specific head on top.
20872297 */
2088-export class MPNetModel extends MPNetPreTrainedModel { }
2298+export class MPNetModel extends MPNetPreTrainedModel {}
20892299
20902300 /**
20912301 * MPNetForMaskedLM is a class representing a MPNet model for masked language modeling.
20922302 */
20932303 export class MPNetForMaskedLM extends MPNetPreTrainedModel {
2094- /**
2095- * Calls the model on new inputs.
2096- *
2097- * @param {Object} model_inputs The inputs to the model.
2098- * @returns {Promise<MaskedLMOutput>} An object containing the model's output logits for masked language modeling.
2099- */
2100- async _call(model_inputs) {
2101- return new MaskedLMOutput(await super._call(model_inputs));
2102- }
2304+ /**
2305+ * Calls the model on new inputs.
2306+ *
2307+ * @param {Object} model_inputs The inputs to the model.
2308+ * @returns {Promise<MaskedLMOutput>} An object containing the model's output logits for masked language modeling.
2309+ */
2310+ async _call(model_inputs) {
2311+ return new MaskedLMOutput(await super._call(model_inputs));
2312+ }
21032313 }
21042314
21052315 /**
21062316 * MPNetForSequenceClassification is a class representing a MPNet model for sequence classification.
21072317 */
21082318 export class MPNetForSequenceClassification extends MPNetPreTrainedModel {
2109- /**
2110- * Calls the model on new inputs.
2111- *
2112- * @param {Object} model_inputs The inputs to the model.
2113- * @returns {Promise<SequenceClassifierOutput>} An object containing the model's output logits for sequence classification.
2114- */
2115- async _call(model_inputs) {
2116- return new SequenceClassifierOutput(await super._call(model_inputs));
2117- }
2319+ /**
2320+ * Calls the model on new inputs.
2321+ *
2322+ * @param {Object} model_inputs The inputs to the model.
2323+ * @returns {Promise<SequenceClassifierOutput>} An object containing the model's output logits for sequence classification.
2324+ */
2325+ async _call(model_inputs) {
2326+ return new SequenceClassifierOutput(await super._call(model_inputs));
2327+ }
21182328 }
21192329
21202330 /**
21212331 * MPNetForTokenClassification is a class representing a MPNet model for token classification.
21222332 */
21232333 export class MPNetForTokenClassification extends MPNetPreTrainedModel {
2124- /**
2125- * Calls the model on new inputs.
2126- *
2127- * @param {Object} model_inputs The inputs to the model.
2128- * @returns {Promise<TokenClassifierOutput>} An object containing the model's output logits for token classification.
2129- */
2130- async _call(model_inputs) {
2131- return new TokenClassifierOutput(await super._call(model_inputs));
2132- }
2334+ /**
2335+ * Calls the model on new inputs.
2336+ *
2337+ * @param {Object} model_inputs The inputs to the model.
2338+ * @returns {Promise<TokenClassifierOutput>} An object containing the model's output logits for token classification.
2339+ */
2340+ async _call(model_inputs) {
2341+ return new TokenClassifierOutput(await super._call(model_inputs));
2342+ }
21332343 }
21342344
21352345 /**
21362346 * MPNetForQuestionAnswering is a class representing a MPNet model for question answering.
21372347 */
21382348 export class MPNetForQuestionAnswering extends MPNetPreTrainedModel {
2139- /**
2140- * Calls the model on new inputs.
2141- *
2142- * @param {Object} model_inputs The inputs to the model.
2143- * @returns {Promise<QuestionAnsweringModelOutput>} An object containing the model's output logits for question answering.
2144- */
2145- async _call(model_inputs) {
2146- return new QuestionAnsweringModelOutput(await super._call(model_inputs));
2147- }
2349+ /**
2350+ * Calls the model on new inputs.
2351+ *
2352+ * @param {Object} model_inputs The inputs to the model.
2353+ * @returns {Promise<QuestionAnsweringModelOutput>} An object containing the model's output logits for question answering.
2354+ */
2355+ async _call(model_inputs) {
2356+ return new QuestionAnsweringModelOutput(await super._call(model_inputs));
2357+ }
21482358 }
21492359 //////////////////////////////////////////////////
21502360
2151-
21522361 //////////////////////////////////////////////////
21532362 // SqueezeBert models
2154-export class SqueezeBertPreTrainedModel extends PreTrainedModel { }
2155-export class SqueezeBertModel extends SqueezeBertPreTrainedModel { }
2363+export class SqueezeBertPreTrainedModel extends PreTrainedModel {}
2364+export class SqueezeBertModel extends SqueezeBertPreTrainedModel {}
21562365 export class SqueezeBertForMaskedLM extends SqueezeBertPreTrainedModel {
2157- /**
2158- * Calls the model on new inputs.
2159- *
2160- * @param {Object} model_inputs The inputs to the model.
2161- * @returns {Promise<MaskedLMOutput>} returned object
2162- */
2163- async _call(model_inputs) {
2164- return new MaskedLMOutput(await super._call(model_inputs));
2165- }
2366+ /**
2367+ * Calls the model on new inputs.
2368+ *
2369+ * @param {Object} model_inputs The inputs to the model.
2370+ * @returns {Promise<MaskedLMOutput>} returned object
2371+ */
2372+ async _call(model_inputs) {
2373+ return new MaskedLMOutput(await super._call(model_inputs));
2374+ }
21662375 }
21672376 export class SqueezeBertForSequenceClassification extends SqueezeBertPreTrainedModel {
2168- /**
2169- * Calls the model on new inputs.
2170- *
2171- * @param {Object} model_inputs The inputs to the model.
2172- * @returns {Promise<SequenceClassifierOutput>} returned object
2173- */
2174- async _call(model_inputs) {
2175- return new SequenceClassifierOutput(await super._call(model_inputs));
2176- }
2377+ /**
2378+ * Calls the model on new inputs.
2379+ *
2380+ * @param {Object} model_inputs The inputs to the model.
2381+ * @returns {Promise<SequenceClassifierOutput>} returned object
2382+ */
2383+ async _call(model_inputs) {
2384+ return new SequenceClassifierOutput(await super._call(model_inputs));
2385+ }
21772386 }
21782387 export class SqueezeBertForQuestionAnswering extends SqueezeBertPreTrainedModel {
2179- /**
2180- * Calls the model on new inputs.
2181- *
2182- * @param {Object} model_inputs The inputs to the model.
2183- * @returns {Promise<QuestionAnsweringModelOutput>} returned object
2184- */
2185- async _call(model_inputs) {
2186- return new QuestionAnsweringModelOutput(await super._call(model_inputs));
2187- }
2388+ /**
2389+ * Calls the model on new inputs.
2390+ *
2391+ * @param {Object} model_inputs The inputs to the model.
2392+ * @returns {Promise<QuestionAnsweringModelOutput>} returned object
2393+ */
2394+ async _call(model_inputs) {
2395+ return new QuestionAnsweringModelOutput(await super._call(model_inputs));
2396+ }
21882397 }
21892398 //////////////////////////////////////////////////
21902399
2191-
21922400 //////////////////////////////////////////////////
21932401 // Albert models
2194-export class AlbertPreTrainedModel extends PreTrainedModel { }
2195-export class AlbertModel extends AlbertPreTrainedModel { }
2402+export class AlbertPreTrainedModel extends PreTrainedModel {}
2403+export class AlbertModel extends AlbertPreTrainedModel {}
21962404 export class AlbertForSequenceClassification extends AlbertPreTrainedModel {
2197- /**
2198- * Calls the model on new inputs.
2199- *
2200- * @param {Object} model_inputs The inputs to the model.
2201- * @returns {Promise<SequenceClassifierOutput>} returned object
2202- */
2203- async _call(model_inputs) {
2204- return new SequenceClassifierOutput(await super._call(model_inputs));
2205- }
2405+ /**
2406+ * Calls the model on new inputs.
2407+ *
2408+ * @param {Object} model_inputs The inputs to the model.
2409+ * @returns {Promise<SequenceClassifierOutput>} returned object
2410+ */
2411+ async _call(model_inputs) {
2412+ return new SequenceClassifierOutput(await super._call(model_inputs));
2413+ }
22062414 }
22072415 export class AlbertForQuestionAnswering extends AlbertPreTrainedModel {
2208- /**
2209- * Calls the model on new inputs.
2210- *
2211- * @param {Object} model_inputs The inputs to the model.
2212- * @returns {Promise<QuestionAnsweringModelOutput>} returned object
2213- */
2214- async _call(model_inputs) {
2215- return new QuestionAnsweringModelOutput(await super._call(model_inputs));
2216- }
2416+ /**
2417+ * Calls the model on new inputs.
2418+ *
2419+ * @param {Object} model_inputs The inputs to the model.
2420+ * @returns {Promise<QuestionAnsweringModelOutput>} returned object
2421+ */
2422+ async _call(model_inputs) {
2423+ return new QuestionAnsweringModelOutput(await super._call(model_inputs));
2424+ }
22172425 }
22182426 export class AlbertForMaskedLM extends AlbertPreTrainedModel {
2219- /**
2220- * Calls the model on new inputs.
2221- *
2222- * @param {Object} model_inputs The inputs to the model.
2223- * @returns {Promise<MaskedLMOutput>} returned object
2224- */
2225- async _call(model_inputs) {
2226- return new MaskedLMOutput(await super._call(model_inputs));
2227- }
2427+ /**
2428+ * Calls the model on new inputs.
2429+ *
2430+ * @param {Object} model_inputs The inputs to the model.
2431+ * @returns {Promise<MaskedLMOutput>} returned object
2432+ */
2433+ async _call(model_inputs) {
2434+ return new MaskedLMOutput(await super._call(model_inputs));
2435+ }
22282436 }
22292437 //////////////////////////////////////////////////
22302438
2231-
22322439 //////////////////////////////////////////////////
22332440 // T5 models
2234-export class T5PreTrainedModel extends PreTrainedModel { };
2441+export class T5PreTrainedModel extends PreTrainedModel {}
22352442
2236-export class T5Model extends T5PreTrainedModel { }
2443+export class T5Model extends T5PreTrainedModel {}
22372444
22382445 /**
22392446 * T5Model is a class representing a T5 model for conditional generation.
22402447 */
22412448 export class T5ForConditionalGeneration extends T5PreTrainedModel {
2449+ /**
2450+ * Creates a new instance of the `T5ForConditionalGeneration` class.
2451+ * @param {Object} config The model configuration.
2452+ * @param {any} session session for the model.
2453+ * @param {any} decoder_merged_session session for the decoder.
2454+ * @param {GenerationConfig} generation_config The generation configuration.
2455+ */
2456+ constructor(config, session, decoder_merged_session, generation_config) {
2457+ super(config, session);
2458+ this.decoder_merged_session = decoder_merged_session;
2459+ this.generation_config = generation_config;
22422460
2243- /**
2244- * Creates a new instance of the `T5ForConditionalGeneration` class.
2245- * @param {Object} config The model configuration.
2246- * @param {any} session session for the model.
2247- * @param {any} decoder_merged_session session for the decoder.
2248- * @param {GenerationConfig} generation_config The generation configuration.
2249- */
2250- constructor(config, session, decoder_merged_session, generation_config) {
2251- super(config, session);
2252- this.decoder_merged_session = decoder_merged_session;
2253- this.generation_config = generation_config;
2254-
2255- this.num_decoder_layers = this.config.num_decoder_layers;
2256- this.num_decoder_heads = this.config.num_heads;
2257- this.decoder_dim_kv = this.config.d_kv;
2258-
2259- this.num_encoder_layers = this.config.num_layers;
2260- this.num_encoder_heads = this.config.num_heads;
2261- this.encoder_dim_kv = this.config.d_kv;
2262- }
2461+ this.num_decoder_layers = this.config.num_decoder_layers;
2462+ this.num_decoder_heads = this.config.num_heads;
2463+ this.decoder_dim_kv = this.config.d_kv;
2464+
2465+ this.num_encoder_layers = this.config.num_layers;
2466+ this.num_encoder_heads = this.config.num_heads;
2467+ this.encoder_dim_kv = this.config.d_kv;
2468+ }
22632469 }
22642470 //////////////////////////////////////////////////
22652471
2266-
22672472 //////////////////////////////////////////////////
22682473 // LONGT5 models
22692474 /**
22702475 * An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained models.
22712476 */
2272-export class LongT5PreTrainedModel extends PreTrainedModel { };
2477+export class LongT5PreTrainedModel extends PreTrainedModel {}
22732478
22742479 /**
22752480 * The bare LONGT5 Model transformer outputting raw hidden-states without any specific head on top.
22762481 */
2277-export class LongT5Model extends LongT5PreTrainedModel { }
2482+export class LongT5Model extends LongT5PreTrainedModel {}
22782483
22792484 /**
22802485 * LONGT5 Model with a `language modeling` head on top.
22812486 */
22822487 export class LongT5ForConditionalGeneration extends LongT5PreTrainedModel {
2283- /**
2284- * Creates a new instance of the `LongT5ForConditionalGeneration` class.
2285- * @param {Object} config The model configuration.
2286- * @param {any} session session for the model.
2287- * @param {any} decoder_merged_session session for the decoder.
2288- * @param {GenerationConfig} generation_config The generation configuration.
2289- */
2290- constructor(config, session, decoder_merged_session, generation_config) {
2291- super(config, session);
2292- this.decoder_merged_session = decoder_merged_session;
2293- this.generation_config = generation_config;
2294-
2295- this.num_decoder_layers = this.config.num_decoder_layers;
2296- this.num_decoder_heads = this.config.num_heads;
2297- this.decoder_dim_kv = this.config.d_kv;
2298-
2299- this.num_encoder_layers = this.config.num_layers;
2300- this.num_encoder_heads = this.config.num_heads;
2301- this.encoder_dim_kv = this.config.d_kv;
2302- }
2488+ /**
2489+ * Creates a new instance of the `LongT5ForConditionalGeneration` class.
2490+ * @param {Object} config The model configuration.
2491+ * @param {any} session session for the model.
2492+ * @param {any} decoder_merged_session session for the decoder.
2493+ * @param {GenerationConfig} generation_config The generation configuration.
2494+ */
2495+ constructor(config, session, decoder_merged_session, generation_config) {
2496+ super(config, session);
2497+ this.decoder_merged_session = decoder_merged_session;
2498+ this.generation_config = generation_config;
2499+
2500+ this.num_decoder_layers = this.config.num_decoder_layers;
2501+ this.num_decoder_heads = this.config.num_heads;
2502+ this.decoder_dim_kv = this.config.d_kv;
2503+
2504+ this.num_encoder_layers = this.config.num_layers;
2505+ this.num_encoder_heads = this.config.num_heads;
2506+ this.encoder_dim_kv = this.config.d_kv;
2507+ }
23032508 }
23042509 //////////////////////////////////////////////////
23052510
2306-
23072511 //////////////////////////////////////////////////
23082512 // MT5 models
2309-export class MT5PreTrainedModel extends PreTrainedModel { };
2513+export class MT5PreTrainedModel extends PreTrainedModel {}
23102514
2311-export class MT5Model extends MT5PreTrainedModel { }
2515+export class MT5Model extends MT5PreTrainedModel {}
23122516
23132517 /**
23142518 * A class representing a conditional sequence-to-sequence model based on the MT5 architecture.
23152519 */
23162520 export class MT5ForConditionalGeneration extends MT5PreTrainedModel {
2521+ /**
2522+ * Creates a new instance of the `MT5ForConditionalGeneration` class.
2523+ * @param {any} config The model configuration.
2524+ * @param {any} session The ONNX session containing the encoder weights.
2525+ * @param {any} decoder_merged_session The ONNX session containing the merged decoder weights.
2526+ * @param {GenerationConfig} generation_config The generation configuration.
2527+ */
2528+ constructor(config, session, decoder_merged_session, generation_config) {
2529+ super(config, session);
2530+ this.decoder_merged_session = decoder_merged_session;
2531+ this.generation_config = generation_config;
23172532
2318- /**
2319- * Creates a new instance of the `MT5ForConditionalGeneration` class.
2320- * @param {any} config The model configuration.
2321- * @param {any} session The ONNX session containing the encoder weights.
2322- * @param {any} decoder_merged_session The ONNX session containing the merged decoder weights.
2323- * @param {GenerationConfig} generation_config The generation configuration.
2324- */
2325- constructor(config, session, decoder_merged_session, generation_config) {
2326- super(config, session);
2327- this.decoder_merged_session = decoder_merged_session;
2328- this.generation_config = generation_config;
2329-
2330- this.num_decoder_layers = this.config.num_decoder_layers;
2331- this.num_decoder_heads = this.config.num_heads;
2332- this.decoder_dim_kv = this.config.d_kv;
2333-
2334- this.num_encoder_layers = this.config.num_layers;
2335- this.num_encoder_heads = this.config.num_heads;
2336- this.encoder_dim_kv = this.config.d_kv;
2337- }
2533+ this.num_decoder_layers = this.config.num_decoder_layers;
2534+ this.num_decoder_heads = this.config.num_heads;
2535+ this.decoder_dim_kv = this.config.d_kv;
2536+
2537+ this.num_encoder_layers = this.config.num_layers;
2538+ this.num_encoder_heads = this.config.num_heads;
2539+ this.encoder_dim_kv = this.config.d_kv;
2540+ }
23382541 }
23392542 //////////////////////////////////////////////////
23402543
23412544 //////////////////////////////////////////////////
23422545 // Bart models
2343-export class BartPretrainedModel extends PreTrainedModel { };
2546+export class BartPretrainedModel extends PreTrainedModel {}
23442547
23452548 /**
23462549 * The bare BART Model outputting raw hidden-states without any specific head on top.
23472550 */
2348-export class BartModel extends BartPretrainedModel { }
2551+export class BartModel extends BartPretrainedModel {}
23492552
23502553 /**
23512554 * The BART Model with a language modeling head. Can be used for summarization.
23522555 */
23532556 export class BartForConditionalGeneration extends BartPretrainedModel {
2354-
2355- /**
2356- * Creates a new instance of the `BartForConditionalGeneration` class.
2357- * @param {Object} config The configuration object for the Bart model.
2358- * @param {Object} session The ONNX session used to execute the model.
2359- * @param {Object} decoder_merged_session The ONNX session used to execute the decoder.
2360- * @param {Object} generation_config The generation configuration object.
2361- */
2362- constructor(config, session, decoder_merged_session, generation_config) {
2363- super(config, session);
2364- this.decoder_merged_session = decoder_merged_session;
2365- this.generation_config = generation_config;
2366-
2367- this.num_decoder_layers = this.config.decoder_layers;
2368- this.num_decoder_heads = this.config.decoder_attention_heads;
2369- this.decoder_dim_kv = this.config.d_model / this.num_decoder_heads;
2370-
2371- this.num_encoder_layers = this.config.encoder_layers;
2372- this.num_encoder_heads = this.config.encoder_attention_heads;
2373- this.encoder_dim_kv = this.config.d_model / this.num_encoder_heads;
2374- }
2375-
2557+ /**
2558+ * Creates a new instance of the `BartForConditionalGeneration` class.
2559+ * @param {Object} config The configuration object for the Bart model.
2560+ * @param {Object} session The ONNX session used to execute the model.
2561+ * @param {Object} decoder_merged_session The ONNX session used to execute the decoder.
2562+ * @param {Object} generation_config The generation configuration object.
2563+ */
2564+ constructor(config, session, decoder_merged_session, generation_config) {
2565+ super(config, session);
2566+ this.decoder_merged_session = decoder_merged_session;
2567+ this.generation_config = generation_config;
2568+
2569+ this.num_decoder_layers = this.config.decoder_layers;
2570+ this.num_decoder_heads = this.config.decoder_attention_heads;
2571+ this.decoder_dim_kv = this.config.d_model / this.num_decoder_heads;
2572+
2573+ this.num_encoder_layers = this.config.encoder_layers;
2574+ this.num_encoder_heads = this.config.encoder_attention_heads;
2575+ this.encoder_dim_kv = this.config.d_model / this.num_encoder_heads;
2576+ }
23762577 }
23772578
23782579 /**
23792580 * Bart model with a sequence classification/head on top (a linear layer on top of the pooled output)
23802581 */
23812582 export class BartForSequenceClassification extends BartPretrainedModel {
2382- /**
2383- * Calls the model on new inputs.
2384- *
2385- * @param {Object} model_inputs The inputs to the model.
2386- * @returns {Promise<SequenceClassifierOutput>} An object containing the model's output logits for sequence classification.
2387- */
2388- async _call(model_inputs) {
2389- return new SequenceClassifierOutput(await super._call(model_inputs));
2390- }
2583+ /**
2584+ * Calls the model on new inputs.
2585+ *
2586+ * @param {Object} model_inputs The inputs to the model.
2587+ * @returns {Promise<SequenceClassifierOutput>} An object containing the model's output logits for sequence classification.
2588+ */
2589+ async _call(model_inputs) {
2590+ return new SequenceClassifierOutput(await super._call(model_inputs));
2591+ }
23912592 }
23922593
23932594 //////////////////////////////////////////////////
23942595
23952596 //////////////////////////////////////////////////
23962597 // MBart models
2397-export class MBartPreTrainedModel extends PreTrainedModel { };
2598+export class MBartPreTrainedModel extends PreTrainedModel {}
23982599
23992600 /**
24002601 * The bare MBART Model outputting raw hidden-states without any specific head on top.
24012602 */
2402-export class MBartModel extends MBartPreTrainedModel { }
2603+export class MBartModel extends MBartPreTrainedModel {}
24032604
24042605 /**
24052606 * The MBART Model with a language modeling head. Can be used for summarization, after fine-tuning the pretrained models.
24062607 */
24072608 export class MBartForConditionalGeneration extends MBartPreTrainedModel {
2408-
2409- /**
2410- * Creates a new instance of the `MBartForConditionalGeneration` class.
2411- * @param {Object} config The configuration object for the Bart model.
2412- * @param {Object} session The ONNX session used to execute the model.
2413- * @param {Object} decoder_merged_session The ONNX session used to execute the decoder.
2414- * @param {Object} generation_config The generation configuration object.
2415- */
2416- constructor(config, session, decoder_merged_session, generation_config) {
2417- super(config, session);
2418- this.decoder_merged_session = decoder_merged_session;
2419- this.generation_config = generation_config;
2420-
2421- this.num_decoder_layers = this.config.decoder_layers;
2422- this.num_decoder_heads = this.config.decoder_attention_heads;
2423- this.decoder_dim_kv = this.config.d_model / this.num_decoder_heads;
2424-
2425- this.num_encoder_layers = this.config.encoder_layers;
2426- this.num_encoder_heads = this.config.encoder_attention_heads;
2427- this.encoder_dim_kv = this.config.d_model / this.num_encoder_heads;
2428- }
2429-
2609+ /**
2610+ * Creates a new instance of the `MBartForConditionalGeneration` class.
2611+ * @param {Object} config The configuration object for the Bart model.
2612+ * @param {Object} session The ONNX session used to execute the model.
2613+ * @param {Object} decoder_merged_session The ONNX session used to execute the decoder.
2614+ * @param {Object} generation_config The generation configuration object.
2615+ */
2616+ constructor(config, session, decoder_merged_session, generation_config) {
2617+ super(config, session);
2618+ this.decoder_merged_session = decoder_merged_session;
2619+ this.generation_config = generation_config;
2620+
2621+ this.num_decoder_layers = this.config.decoder_layers;
2622+ this.num_decoder_heads = this.config.decoder_attention_heads;
2623+ this.decoder_dim_kv = this.config.d_model / this.num_decoder_heads;
2624+
2625+ this.num_encoder_layers = this.config.encoder_layers;
2626+ this.num_encoder_heads = this.config.encoder_attention_heads;
2627+ this.encoder_dim_kv = this.config.d_model / this.num_encoder_heads;
2628+ }
24302629 }
24312630
24322631 /**
24332632 * MBart model with a sequence classification/head on top (a linear layer on top of the pooled output).
24342633 */
24352634 export class MBartForSequenceClassification extends MBartPreTrainedModel {
2436- /**
2437- * Calls the model on new inputs.
2438- *
2439- * @param {Object} model_inputs The inputs to the model.
2440- * @returns {Promise<SequenceClassifierOutput>} An object containing the model's output logits for sequence classification.
2441- */
2442- async _call(model_inputs) {
2443- return new SequenceClassifierOutput(await super._call(model_inputs));
2444- }
2635+ /**
2636+ * Calls the model on new inputs.
2637+ *
2638+ * @param {Object} model_inputs The inputs to the model.
2639+ * @returns {Promise<SequenceClassifierOutput>} An object containing the model's output logits for sequence classification.
2640+ */
2641+ async _call(model_inputs) {
2642+ return new SequenceClassifierOutput(await super._call(model_inputs));
2643+ }
24452644 }
24462645
2447-
24482646 export class MBartForCausalLM extends MBartPreTrainedModel {
2449- /**
2450- * Creates a new instance of the `MBartForCausalLM` class.
2451- * @param {Object} config Configuration object for the model.
2452- * @param {Object} decoder_merged_session ONNX Session object for the decoder.
2453- * @param {Object} generation_config Configuration object for the generation process.
2454- */
2455- constructor(config, decoder_merged_session, generation_config) {
2456- super(config, decoder_merged_session);
2457- this.generation_config = generation_config;
2458-
2459- this.num_decoder_layers = this.config.decoder_layers;
2460- this.num_decoder_heads = this.config.decoder_attention_heads;
2461- this.decoder_dim_kv = this.config.d_model / this.num_decoder_heads;
2462-
2463- this.num_encoder_layers = this.config.encoder_layers;
2464- this.num_encoder_heads = this.config.encoder_attention_heads;
2465- this.encoder_dim_kv = this.config.d_model / this.num_encoder_heads;
2466- }
2647+ /**
2648+ * Creates a new instance of the `MBartForCausalLM` class.
2649+ * @param {Object} config Configuration object for the model.
2650+ * @param {Object} decoder_merged_session ONNX Session object for the decoder.
2651+ * @param {Object} generation_config Configuration object for the generation process.
2652+ */
2653+ constructor(config, decoder_merged_session, generation_config) {
2654+ super(config, decoder_merged_session);
2655+ this.generation_config = generation_config;
2656+
2657+ this.num_decoder_layers = this.config.decoder_layers;
2658+ this.num_decoder_heads = this.config.decoder_attention_heads;
2659+ this.decoder_dim_kv = this.config.d_model / this.num_decoder_heads;
2660+
2661+ this.num_encoder_layers = this.config.encoder_layers;
2662+ this.num_encoder_heads = this.config.encoder_attention_heads;
2663+ this.encoder_dim_kv = this.config.d_model / this.num_encoder_heads;
2664+ }
24672665 }
24682666 //////////////////////////////////////////////////
24692667
2470-
24712668 //////////////////////////////////////////////////
24722669 // Blenderbot models
2473-export class BlenderbotPreTrainedModel extends PreTrainedModel { };
2670+export class BlenderbotPreTrainedModel extends PreTrainedModel {}
24742671
24752672 /**
24762673 * The bare Blenderbot Model outputting raw hidden-states without any specific head on top.
24772674 */
2478-export class BlenderbotModel extends BlenderbotPreTrainedModel { }
2675+export class BlenderbotModel extends BlenderbotPreTrainedModel {}
24792676
24802677 /**
24812678 * The Blenderbot Model with a language modeling head. Can be used for summarization.
24822679 */
24832680 export class BlenderbotForConditionalGeneration extends BlenderbotPreTrainedModel {
2681+ /**
2682+ * Creates a new instance of the `BlenderbotForConditionalGeneration` class.
2683+ * @param {any} config The model configuration.
2684+ * @param {any} session The ONNX session containing the encoder weights.
2685+ * @param {any} decoder_merged_session The ONNX session containing the merged decoder weights.
2686+ * @param {GenerationConfig} generation_config The generation configuration.
2687+ */
2688+ constructor(config, session, decoder_merged_session, generation_config) {
2689+ super(config, session);
2690+ this.decoder_merged_session = decoder_merged_session;
2691+ this.generation_config = generation_config;
24842692
2485- /**
2486- * Creates a new instance of the `BlenderbotForConditionalGeneration` class.
2487- * @param {any} config The model configuration.
2488- * @param {any} session The ONNX session containing the encoder weights.
2489- * @param {any} decoder_merged_session The ONNX session containing the merged decoder weights.
2490- * @param {GenerationConfig} generation_config The generation configuration.
2491- */
2492- constructor(config, session, decoder_merged_session, generation_config) {
2493- super(config, session);
2494- this.decoder_merged_session = decoder_merged_session;
2495- this.generation_config = generation_config;
2496-
2497- this.num_decoder_layers = this.config.decoder_layers;
2498- this.num_decoder_heads = this.config.decoder_attention_heads;
2499- this.decoder_dim_kv = this.config.d_model / this.num_decoder_heads;
2500-
2501- this.num_encoder_layers = this.config.encoder_layers;
2502- this.num_encoder_heads = this.config.encoder_attention_heads;
2503- this.encoder_dim_kv = this.config.d_model / this.num_encoder_heads;
2504- }
2693+ this.num_decoder_layers = this.config.decoder_layers;
2694+ this.num_decoder_heads = this.config.decoder_attention_heads;
2695+ this.decoder_dim_kv = this.config.d_model / this.num_decoder_heads;
2696+
2697+ this.num_encoder_layers = this.config.encoder_layers;
2698+ this.num_encoder_heads = this.config.encoder_attention_heads;
2699+ this.encoder_dim_kv = this.config.d_model / this.num_encoder_heads;
2700+ }
25052701 }
25062702 //////////////////////////////////////////////////
25072703
2508-
25092704 //////////////////////////////////////////////////
25102705 // Blenderbot models
2511-export class BlenderbotSmallPreTrainedModel extends PreTrainedModel { };
2706+export class BlenderbotSmallPreTrainedModel extends PreTrainedModel {}
25122707
25132708 /**
25142709 * The bare BlenderbotSmall Model outputting raw hidden-states without any specific head on top.
25152710 */
2516-export class BlenderbotSmallModel extends BlenderbotSmallPreTrainedModel { }
2711+export class BlenderbotSmallModel extends BlenderbotSmallPreTrainedModel {}
25172712
25182713 /**
25192714 * The BlenderbotSmall Model with a language modeling head. Can be used for summarization.
25202715 */
25212716 export class BlenderbotSmallForConditionalGeneration extends BlenderbotSmallPreTrainedModel {
2717+ /**
2718+ * Creates a new instance of the `BlenderbotForConditionalGeneration` class.
2719+ * @param {any} config The model configuration.
2720+ * @param {any} session The ONNX session containing the encoder weights.
2721+ * @param {any} decoder_merged_session The ONNX session containing the merged decoder weights.
2722+ * @param {GenerationConfig} generation_config The generation configuration.
2723+ */
2724+ constructor(config, session, decoder_merged_session, generation_config) {
2725+ super(config, session);
2726+ this.decoder_merged_session = decoder_merged_session;
2727+ this.generation_config = generation_config;
25222728
2523- /**
2524- * Creates a new instance of the `BlenderbotForConditionalGeneration` class.
2525- * @param {any} config The model configuration.
2526- * @param {any} session The ONNX session containing the encoder weights.
2527- * @param {any} decoder_merged_session The ONNX session containing the merged decoder weights.
2528- * @param {GenerationConfig} generation_config The generation configuration.
2529- */
2530- constructor(config, session, decoder_merged_session, generation_config) {
2531- super(config, session);
2532- this.decoder_merged_session = decoder_merged_session;
2533- this.generation_config = generation_config;
2534-
2535- this.num_decoder_layers = this.config.decoder_layers;
2536- this.num_decoder_heads = this.config.decoder_attention_heads;
2537- this.decoder_dim_kv = this.config.d_model / this.num_decoder_heads;
2538-
2539- this.num_encoder_layers = this.config.encoder_layers;
2540- this.num_encoder_heads = this.config.encoder_attention_heads;
2541- this.encoder_dim_kv = this.config.d_model / this.num_encoder_heads;
2542- }
2729+ this.num_decoder_layers = this.config.decoder_layers;
2730+ this.num_decoder_heads = this.config.decoder_attention_heads;
2731+ this.decoder_dim_kv = this.config.d_model / this.num_decoder_heads;
2732+
2733+ this.num_encoder_layers = this.config.encoder_layers;
2734+ this.num_encoder_heads = this.config.encoder_attention_heads;
2735+ this.encoder_dim_kv = this.config.d_model / this.num_encoder_heads;
2736+ }
25432737 }
25442738 //////////////////////////////////////////////////
25452739
2546-
25472740 //////////////////////////////////////////////////
25482741 // Roberta models
2549-export class RobertaPreTrainedModel extends PreTrainedModel { }
2550-export class RobertaModel extends RobertaPreTrainedModel { }
2742+export class RobertaPreTrainedModel extends PreTrainedModel {}
2743+export class RobertaModel extends RobertaPreTrainedModel {}
25512744
25522745 /**
25532746 * RobertaForMaskedLM class for performing masked language modeling on Roberta models.
25542747 */
25552748 export class RobertaForMaskedLM extends RobertaPreTrainedModel {
2556- /**
2557- * Calls the model on new inputs.
2558- *
2559- * @param {Object} model_inputs The inputs to the model.
2560- * @returns {Promise<MaskedLMOutput>} returned object
2561- */
2562- async _call(model_inputs) {
2563- return new MaskedLMOutput(await super._call(model_inputs));
2564- }
2749+ /**
2750+ * Calls the model on new inputs.
2751+ *
2752+ * @param {Object} model_inputs The inputs to the model.
2753+ * @returns {Promise<MaskedLMOutput>} returned object
2754+ */
2755+ async _call(model_inputs) {
2756+ return new MaskedLMOutput(await super._call(model_inputs));
2757+ }
25652758 }
25662759
25672760 /**
25682761 * RobertaForSequenceClassification class for performing sequence classification on Roberta models.
25692762 */
25702763 export class RobertaForSequenceClassification extends RobertaPreTrainedModel {
2571- /**
2572- * Calls the model on new inputs.
2573- *
2574- * @param {Object} model_inputs The inputs to the model.
2575- * @returns {Promise<SequenceClassifierOutput>} returned object
2576- */
2577- async _call(model_inputs) {
2578- return new SequenceClassifierOutput(await super._call(model_inputs));
2579- }
2764+ /**
2765+ * Calls the model on new inputs.
2766+ *
2767+ * @param {Object} model_inputs The inputs to the model.
2768+ * @returns {Promise<SequenceClassifierOutput>} returned object
2769+ */
2770+ async _call(model_inputs) {
2771+ return new SequenceClassifierOutput(await super._call(model_inputs));
2772+ }
25802773 }
25812774
25822775 /**
25832776 * RobertaForTokenClassification class for performing token classification on Roberta models.
25842777 */
25852778 export class RobertaForTokenClassification extends RobertaPreTrainedModel {
2586- /**
2587- * Calls the model on new inputs.
2588- *
2589- * @param {Object} model_inputs The inputs to the model.
2590- * @returns {Promise<TokenClassifierOutput>} An object containing the model's output logits for token classification.
2591- */
2592- async _call(model_inputs) {
2593- return new TokenClassifierOutput(await super._call(model_inputs));
2594- }
2779+ /**
2780+ * Calls the model on new inputs.
2781+ *
2782+ * @param {Object} model_inputs The inputs to the model.
2783+ * @returns {Promise<TokenClassifierOutput>} An object containing the model's output logits for token classification.
2784+ */
2785+ async _call(model_inputs) {
2786+ return new TokenClassifierOutput(await super._call(model_inputs));
2787+ }
25952788 }
25962789
25972790 /**
25982791 * RobertaForQuestionAnswering class for performing question answering on Roberta models.
25992792 */
26002793 export class RobertaForQuestionAnswering extends RobertaPreTrainedModel {
2601- /**
2602- * Calls the model on new inputs.
2603- *
2604- * @param {Object} model_inputs The inputs to the model.
2605- * @returns {Promise<QuestionAnsweringModelOutput>} returned object
2606- */
2607- async _call(model_inputs) {
2608- return new QuestionAnsweringModelOutput(await super._call(model_inputs));
2609- }
2794+ /**
2795+ * Calls the model on new inputs.
2796+ *
2797+ * @param {Object} model_inputs The inputs to the model.
2798+ * @returns {Promise<QuestionAnsweringModelOutput>} returned object
2799+ */
2800+ async _call(model_inputs) {
2801+ return new QuestionAnsweringModelOutput(await super._call(model_inputs));
2802+ }
26102803 }
26112804 //////////////////////////////////////////////////
26122805
2613-
26142806 //////////////////////////////////////////////////
26152807 // XLM models
26162808 /**
26172809 * An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained models.
26182810 */
2619-export class XLMPreTrainedModel extends PreTrainedModel { }
2811+export class XLMPreTrainedModel extends PreTrainedModel {}
26202812
26212813 /**
26222814 * The bare XLM Model transformer outputting raw hidden-states without any specific head on top.
26232815 */
2624-export class XLMModel extends XLMPreTrainedModel { }
2816+export class XLMModel extends XLMPreTrainedModel {}
26252817
26262818 /**
26272819 * The XLM Model transformer with a language modeling head on top (linear layer with weights tied to the input embeddings).
26282820 */
26292821 export class XLMWithLMHeadModel extends XLMPreTrainedModel {
2630- /**
2631- * Calls the model on new inputs.
2632- *
2633- * @param {Object} model_inputs The inputs to the model.
2634- * @returns {Promise<MaskedLMOutput>} returned object
2635- */
2636- async _call(model_inputs) {
2637- return new MaskedLMOutput(await super._call(model_inputs));
2638- }
2822+ /**
2823+ * Calls the model on new inputs.
2824+ *
2825+ * @param {Object} model_inputs The inputs to the model.
2826+ * @returns {Promise<MaskedLMOutput>} returned object
2827+ */
2828+ async _call(model_inputs) {
2829+ return new MaskedLMOutput(await super._call(model_inputs));
2830+ }
26392831 }
26402832
26412833 /**
26422834 * XLM Model with a sequence classification/regression head on top (a linear layer on top of the pooled output)
26432835 */
26442836 export class XLMForSequenceClassification extends XLMPreTrainedModel {
2645- /**
2646- * Calls the model on new inputs.
2647- *
2648- * @param {Object} model_inputs The inputs to the model.
2649- * @returns {Promise<SequenceClassifierOutput>} returned object
2650- */
2651- async _call(model_inputs) {
2652- return new SequenceClassifierOutput(await super._call(model_inputs));
2653- }
2837+ /**
2838+ * Calls the model on new inputs.
2839+ *
2840+ * @param {Object} model_inputs The inputs to the model.
2841+ * @returns {Promise<SequenceClassifierOutput>} returned object
2842+ */
2843+ async _call(model_inputs) {
2844+ return new SequenceClassifierOutput(await super._call(model_inputs));
2845+ }
26542846 }
26552847
26562848 /**
26572849 * XLM Model with a token classification head on top (a linear layer on top of the hidden-states output)
26582850 */
26592851 export class XLMForTokenClassification extends XLMPreTrainedModel {
2660- /**
2661- * Calls the model on new inputs.
2662- *
2663- * @param {Object} model_inputs The inputs to the model.
2664- * @returns {Promise<TokenClassifierOutput>} An object containing the model's output logits for token classification.
2665- */
2666- async _call(model_inputs) {
2667- return new TokenClassifierOutput(await super._call(model_inputs));
2668- }
2852+ /**
2853+ * Calls the model on new inputs.
2854+ *
2855+ * @param {Object} model_inputs The inputs to the model.
2856+ * @returns {Promise<TokenClassifierOutput>} An object containing the model's output logits for token classification.
2857+ */
2858+ async _call(model_inputs) {
2859+ return new TokenClassifierOutput(await super._call(model_inputs));
2860+ }
26692861 }
26702862
26712863 /**
26722864 * XLM Model with a span classification head on top for extractive question-answering tasks
26732865 */
26742866 export class XLMForQuestionAnswering extends XLMPreTrainedModel {
2675- /**
2676- * Calls the model on new inputs.
2677- *
2678- * @param {Object} model_inputs The inputs to the model.
2679- * @returns {Promise<QuestionAnsweringModelOutput>} returned object
2680- */
2681- async _call(model_inputs) {
2682- return new QuestionAnsweringModelOutput(await super._call(model_inputs));
2683- }
2867+ /**
2868+ * Calls the model on new inputs.
2869+ *
2870+ * @param {Object} model_inputs The inputs to the model.
2871+ * @returns {Promise<QuestionAnsweringModelOutput>} returned object
2872+ */
2873+ async _call(model_inputs) {
2874+ return new QuestionAnsweringModelOutput(await super._call(model_inputs));
2875+ }
26842876 }
26852877 //////////////////////////////////////////////////
26862878
26872879 //////////////////////////////////////////////////
26882880 // XLMRoberta models
2689-export class XLMRobertaPreTrainedModel extends PreTrainedModel { }
2690-export class XLMRobertaModel extends XLMRobertaPreTrainedModel { }
2881+export class XLMRobertaPreTrainedModel extends PreTrainedModel {}
2882+export class XLMRobertaModel extends XLMRobertaPreTrainedModel {}
26912883
26922884 /**
26932885 * XLMRobertaForMaskedLM class for performing masked language modeling on XLMRoberta models.
26942886 */
26952887 export class XLMRobertaForMaskedLM extends XLMRobertaPreTrainedModel {
2696- /**
2697- * Calls the model on new inputs.
2698- *
2699- * @param {Object} model_inputs The inputs to the model.
2700- * @returns {Promise<MaskedLMOutput>} returned object
2701- */
2702- async _call(model_inputs) {
2703- return new MaskedLMOutput(await super._call(model_inputs));
2704- }
2888+ /**
2889+ * Calls the model on new inputs.
2890+ *
2891+ * @param {Object} model_inputs The inputs to the model.
2892+ * @returns {Promise<MaskedLMOutput>} returned object
2893+ */
2894+ async _call(model_inputs) {
2895+ return new MaskedLMOutput(await super._call(model_inputs));
2896+ }
27052897 }
27062898
27072899 /**
27082900 * XLMRobertaForSequenceClassification class for performing sequence classification on XLMRoberta models.
27092901 */
27102902 export class XLMRobertaForSequenceClassification extends XLMRobertaPreTrainedModel {
2711- /**
2712- * Calls the model on new inputs.
2713- *
2714- * @param {Object} model_inputs The inputs to the model.
2715- * @returns {Promise<SequenceClassifierOutput>} returned object
2716- */
2717- async _call(model_inputs) {
2718- return new SequenceClassifierOutput(await super._call(model_inputs));
2719- }
2903+ /**
2904+ * Calls the model on new inputs.
2905+ *
2906+ * @param {Object} model_inputs The inputs to the model.
2907+ * @returns {Promise<SequenceClassifierOutput>} returned object
2908+ */
2909+ async _call(model_inputs) {
2910+ return new SequenceClassifierOutput(await super._call(model_inputs));
2911+ }
27202912 }
27212913
27222914 /**
27232915 * XLMRobertaForTokenClassification class for performing token classification on XLMRoberta models.
27242916 */
27252917 export class XLMRobertaForTokenClassification extends XLMRobertaPreTrainedModel {
2726- /**
2727- * Calls the model on new inputs.
2728- *
2729- * @param {Object} model_inputs The inputs to the model.
2730- * @returns {Promise<TokenClassifierOutput>} An object containing the model's output logits for token classification.
2731- */
2732- async _call(model_inputs) {
2733- return new TokenClassifierOutput(await super._call(model_inputs));
2734- }
2918+ /**
2919+ * Calls the model on new inputs.
2920+ *
2921+ * @param {Object} model_inputs The inputs to the model.
2922+ * @returns {Promise<TokenClassifierOutput>} An object containing the model's output logits for token classification.
2923+ */
2924+ async _call(model_inputs) {
2925+ return new TokenClassifierOutput(await super._call(model_inputs));
2926+ }
27352927 }
27362928
27372929 /**
27382930 * XLMRobertaForQuestionAnswering class for performing question answering on XLMRoberta models.
27392931 */
27402932 export class XLMRobertaForQuestionAnswering extends XLMRobertaPreTrainedModel {
2741- /**
2742- * Calls the model on new inputs.
2743- *
2744- * @param {Object} model_inputs The inputs to the model.
2745- * @returns {Promise<QuestionAnsweringModelOutput>} returned object
2746- */
2747- async _call(model_inputs) {
2748- return new QuestionAnsweringModelOutput(await super._call(model_inputs));
2749- }
2933+ /**
2934+ * Calls the model on new inputs.
2935+ *
2936+ * @param {Object} model_inputs The inputs to the model.
2937+ * @returns {Promise<QuestionAnsweringModelOutput>} returned object
2938+ */
2939+ async _call(model_inputs) {
2940+ return new QuestionAnsweringModelOutput(await super._call(model_inputs));
2941+ }
27502942 }
27512943 //////////////////////////////////////////////////
27522944
27532945 //////////////////////////////////////////////////
27542946 // Audio Spectrogram Transformer (AST) models
2755-export class ASTPreTrainedModel extends PreTrainedModel { };
2947+export class ASTPreTrainedModel extends PreTrainedModel {}
27562948
27572949 /**
27582950 * The bare AST Model transformer outputting raw hidden-states without any specific head on top.
27592951 */
2760-export class ASTModel extends ASTPreTrainedModel { }
2952+export class ASTModel extends ASTPreTrainedModel {}
27612953
27622954 /**
27632955 * Audio Spectrogram Transformer model with an audio classification head on top
27642956 * (a linear layer on top of the pooled output) e.g. for datasets like AudioSet, Speech Commands v2.
27652957 */
2766-export class ASTForAudioClassification extends ASTPreTrainedModel { }
2958+export class ASTForAudioClassification extends ASTPreTrainedModel {}
27672959 //////////////////////////////////////////////////
27682960
27692961 //////////////////////////////////////////////////
27702962 // Whisper models
2771-export class WhisperPreTrainedModel extends PreTrainedModel { };
2963+export class WhisperPreTrainedModel extends PreTrainedModel {}
27722964
27732965 /**
27742966 * WhisperModel class for training Whisper models without a language model head.
27752967 */
2776-export class WhisperModel extends WhisperPreTrainedModel { }
2968+export class WhisperModel extends WhisperPreTrainedModel {}
27772969
27782970 /**
27792971 * WhisperForConditionalGeneration class for generating conditional outputs from Whisper models.
27802972 */
27812973 export class WhisperForConditionalGeneration extends WhisperPreTrainedModel {
2974+ requires_attention_mask = false;
2975+ main_input_name = "input_features";
2976+
2977+ /**
2978+ * Creates a new instance of the `WhisperForConditionalGeneration` class.
2979+ * @param {Object} config Configuration object for the model.
2980+ * @param {Object} session ONNX Session object for the model.
2981+ * @param {Object} decoder_merged_session ONNX Session object for the decoder.
2982+ * @param {Object} generation_config Configuration object for the generation process.
2983+ */
2984+ constructor(config, session, decoder_merged_session, generation_config) {
2985+ super(config, session);
2986+ this.decoder_merged_session = decoder_merged_session;
2987+ this.generation_config = generation_config;
2988+
2989+ this.num_decoder_layers = this.config.decoder_layers;
2990+ this.num_decoder_heads = this.config.decoder_attention_heads;
2991+ this.decoder_dim_kv = this.config.d_model / this.num_decoder_heads;
2992+
2993+ this.num_encoder_layers = this.config.encoder_layers;
2994+ this.num_encoder_heads = this.config.encoder_attention_heads;
2995+ this.encoder_dim_kv = this.config.d_model / this.num_encoder_heads;
2996+ }
2997+
2998+ /**
2999+ * @typedef {Object} WhisperGenerationConfig
3000+ * @extends GenerationConfig
3001+ * @property {boolean} [return_timestamps=null] Whether to return the timestamps with the text. This enables the `WhisperTimestampsLogitsProcessor`.
3002+ * @property {boolean} [return_token_timestamps=null] Whether to return token-level timestamps
3003+ * with the text. This can be used with or without the `return_timestamps` option. To get word-level
3004+ * timestamps, use the tokenizer to group the tokens into words.
3005+ * @property {number} [num_frames=null] The number of audio frames available in this chunk. This is only used generating word-level timestamps.
3006+ */
3007+
3008+ /**
3009+ * Generates outputs based on input and generation configuration.
3010+ * @param {Object} inputs Input data for the model.
3011+ * @param {WhisperGenerationConfig} generation_config Configuration object for the generation process.
3012+ * @param {Object} logits_processor Optional logits processor object.
3013+ * @returns {Promise<Object>} Promise object represents the generated outputs.
3014+ */
3015+ async generate(
3016+ inputs,
3017+ generation_config = null,
3018+ logits_processor = null,
3019+ // {
3020+ // return_timestamps = null,
3021+ // return_token_timestamps = null,
3022+ // language = null,
3023+ // task = null,
3024+ // } = {},
3025+ ) {
3026+ // Create generation config object
3027+ generation_config = this._get_generation_config(generation_config);
3028+
3029+ // Whisper has additional options for returning timestamps
3030+ generation_config.return_timestamps ??= false;
3031+
3032+ // TODO add language and task
3033+
3034+ if (generation_config.return_timestamps) {
3035+ logits_processor = [
3036+ new WhisperTimeStampLogitsProcessor(generation_config),
3037+ ];
3038+ }
3039+
3040+ if (generation_config.return_token_timestamps) {
3041+ generation_config.output_attentions = true;
3042+ generation_config.return_dict_in_generate = true;
3043+
3044+ if (generation_config.task === "translate") {
3045+ console.warn(
3046+ "Token-level timestamps may not be reliable for task 'translate'.",
3047+ );
3048+ }
27823049
2783- requires_attention_mask = false;
2784- main_input_name = 'input_features';
2785-
2786- /**
2787- * Creates a new instance of the `WhisperForConditionalGeneration` class.
2788- * @param {Object} config Configuration object for the model.
2789- * @param {Object} session ONNX Session object for the model.
2790- * @param {Object} decoder_merged_session ONNX Session object for the decoder.
2791- * @param {Object} generation_config Configuration object for the generation process.
2792- */
2793- constructor(config, session, decoder_merged_session, generation_config) {
2794- super(config, session);
2795- this.decoder_merged_session = decoder_merged_session;
2796- this.generation_config = generation_config;
2797-
2798- this.num_decoder_layers = this.config.decoder_layers;
2799- this.num_decoder_heads = this.config.decoder_attention_heads;
2800- this.decoder_dim_kv = this.config.d_model / this.num_decoder_heads;
2801-
2802- this.num_encoder_layers = this.config.encoder_layers;
2803- this.num_encoder_heads = this.config.encoder_attention_heads;
2804- this.encoder_dim_kv = this.config.d_model / this.num_encoder_heads;
3050+ if (!generation_config.alignment_heads) {
3051+ throw new Error(
3052+ "Model generation config has no `alignment_heads`, token-level timestamps not available. " +
3053+ "See https://gist.github.com/hollance/42e32852f24243b748ae6bc1f985b13a on how to add this property to the generation config.",
3054+ );
3055+ }
28053056 }
28063057
2807- /**
2808- * @typedef {Object} WhisperGenerationConfig
2809- * @extends GenerationConfig
2810- * @property {boolean} [return_timestamps=null] Whether to return the timestamps with the text. This enables the `WhisperTimestampsLogitsProcessor`.
2811- * @property {boolean} [return_token_timestamps=null] Whether to return token-level timestamps
2812- * with the text. This can be used with or without the `return_timestamps` option. To get word-level
2813- * timestamps, use the tokenizer to group the tokens into words.
2814- * @property {number} [num_frames=null] The number of audio frames available in this chunk. This is only used generating word-level timestamps.
2815- */
2816-
2817- /**
2818- * Generates outputs based on input and generation configuration.
2819- * @param {Object} inputs Input data for the model.
2820- * @param {WhisperGenerationConfig} generation_config Configuration object for the generation process.
2821- * @param {Object} logits_processor Optional logits processor object.
2822- * @returns {Promise<Object>} Promise object represents the generated outputs.
2823- */
2824- async generate(
2825- inputs,
2826- generation_config = null,
2827- logits_processor = null,
2828- // {
2829- // return_timestamps = null,
2830- // return_token_timestamps = null,
2831- // language = null,
2832- // task = null,
2833- // } = {},
2834- ) {
2835- // Create generation config object
2836- generation_config = this._get_generation_config(generation_config);
2837-
2838-
2839- // Whisper has additional options for returning timestamps
2840- generation_config.return_timestamps ??= false;
2841-
2842- // TODO add language and task
2843-
2844- if (generation_config.return_timestamps) {
2845- logits_processor = [new WhisperTimeStampLogitsProcessor(generation_config)]
2846- }
2847-
2848- if (generation_config.return_token_timestamps) {
2849- generation_config.output_attentions = true;
2850- generation_config.return_dict_in_generate = true;
3058+ const outputs = await super.generate(
3059+ inputs,
3060+ generation_config,
3061+ logits_processor,
3062+ );
28513063
2852- if (generation_config.task === 'translate') {
2853- console.warn("Token-level timestamps may not be reliable for task 'translate'.")
3064+ if (
3065+ generation_config.return_token_timestamps &&
3066+ generation_config.alignment_heads
3067+ ) {
3068+ outputs["token_timestamps"] = this._extract_token_timestamps(
3069+ outputs,
3070+ generation_config.alignment_heads,
3071+ generation_config.num_frames,
3072+ );
3073+ }
3074+
3075+ return outputs;
3076+ }
3077+
3078+ /**
3079+ * Calculates token-level timestamps using the encoder-decoder cross-attentions and
3080+ * dynamic time-warping (DTW) to map each output token to a position in the input audio.
3081+ * @param {Object} generate_outputs Outputs generated by the model
3082+ * @param {Tensor[][][]} generate_outputs.cross_attentions The cross attentions output by the model
3083+ * @param {Tensor[][][]} generate_outputs.decoder_attentions The decoder attentions output by the model
3084+ * @param {number[][]} generate_outputs.sequences The sequences output by the model
3085+ * @param {number[][]} alignment_heads Alignment heads of the model
3086+ * @param {number} [num_frames=null] Number of frames in the input audio.
3087+ * @param {number} [time_precision=0.02] Precision of the timestamps in seconds
3088+ * @returns {Tensor} tensor containing the timestamps in seconds for each predicted token
3089+ */
3090+ _extract_token_timestamps(
3091+ generate_outputs,
3092+ alignment_heads,
3093+ num_frames = null,
3094+ time_precision = 0.02,
3095+ ) {
3096+ if (!generate_outputs.cross_attentions) {
3097+ throw new Error(
3098+ "Model outputs must contain cross attentions to extract timestamps. " +
3099+ "This is most likely because the model was not exported with `output_attentions=True`.",
3100+ );
3101+ }
3102+
3103+ let median_filter_width = this.config.median_filter_width;
3104+ if (median_filter_width === undefined) {
3105+ console.warn(
3106+ "Model config has no `median_filter_width`, using default value of 7.",
3107+ );
3108+ median_filter_width = 7;
3109+ }
3110+
3111+ const batchedMatrices = generate_outputs.cross_attentions.map((batch) => {
3112+ // Create a list with `decoder_layers` elements, each a tensor of shape
3113+ // (batch size, attention_heads, output length, input length).
3114+ let cross_attentions = Array.from(
3115+ { length: this.config.decoder_layers },
3116+ (_, i) =>
3117+ cat(
3118+ batch.map((x) => x[i]),
3119+ 2,
3120+ ),
3121+ );
3122+
3123+ let weights = stack(
3124+ alignment_heads.map(([l, h]) => {
3125+ return num_frames
3126+ ? cross_attentions[l].slice(null, h, null, [0, num_frames])
3127+ : cross_attentions[l].slice(null, h);
3128+ }),
3129+ );
3130+ weights = weights.transpose(1, 0, 2, 3);
3131+
3132+ let [std, calculatedMean] = std_mean(weights, -2, 0, true);
3133+
3134+ // Normalize and smoothen the weights.
3135+ let smoothedWeights = weights.clone(); // [1, 8, seqLength, 1500]
3136+
3137+ for (let a = 0; a < smoothedWeights.dims[0]; ++a) {
3138+ let aTensor = smoothedWeights[a]; // [8, seqLength, 1500]
3139+
3140+ for (let b = 0; b < aTensor.dims[0]; ++b) {
3141+ let bTensor = aTensor[b]; // [seqLength, 1500]
3142+
3143+ const stdTensor = std[a][b][0]; // [1500]
3144+ const meanTensor = calculatedMean[a][b][0]; // [1500]
3145+
3146+ for (let c = 0; c < bTensor.dims[0]; ++c) {
3147+ let cTensor = bTensor[c]; // [1500]
3148+ for (let d = 0; d < cTensor.data.length; ++d) {
3149+ cTensor.data[d] =
3150+ (cTensor.data[d] - meanTensor.data[d]) / stdTensor.data[d];
28543151 }
28553152
2856- if (!generation_config.alignment_heads) {
2857- throw new Error(
2858- "Model generation config has no `alignment_heads`, token-level timestamps not available. " +
2859- "See https://gist.github.com/hollance/42e32852f24243b748ae6bc1f985b13a on how to add this property to the generation config."
2860- )
2861- }
3153+ // Apply median filter.
3154+ // cTensor.data.set(medianFilter(cTensor.data, median_filter_width))
3155+ }
28623156 }
modified core/vendor/modules/@xenova/transformers/src/pipelines.js +1910 −1797
@@ -1,75 +1,51 @@
11 /**
22 * @file Pipelines provide a high-level, easy to use, API for running machine learning models.
3- *
3+ *
44 * **Example:** Instantiate pipeline using the `pipeline` function.
55 * ```javascript
66 * import { pipeline } from '@xenova/transformers';
7- *
7+ *
88 * const classifier = await pipeline('sentiment-analysis');
99 * const output = await classifier('I love transformers!');
1010 * // [{'label': 'POSITIVE', 'score': 0.999817686}]
1111 * ```
12- *
12+ *
1313 * @module pipelines
1414 */
1515
1616 import {
17- AutoModel,
18- AutoModelForAudioClassification,
19- AutoModelForCTC,
20- AutoModelForCausalLM,
21- AutoModelForDepthEstimation,
22- AutoModelForDocumentQuestionAnswering,
23- AutoModelForImageClassification,
24- AutoModelForImageSegmentation,
25- AutoModelForImageToImage,
26- AutoModelForMaskedLM,
27- AutoModelForObjectDetection,
28- AutoModelForQuestionAnswering,
29- AutoModelForSemanticSegmentation,
30- AutoModelForSeq2SeqLM,
31- AutoModelForSequenceClassification,
32- AutoModelForSpeechSeq2Seq,
33- AutoModelForTextToSpectrogram,
34- AutoModelForTextToWaveform,
35- AutoModelForTokenClassification,
36- AutoModelForVision2Seq,
37- AutoModelForZeroShotObjectDetection,
38- PreTrainedModel,
39-} from './models.js';
40-import {
41- AutoProcessor,
42- Processor
43-} from './processors.js';
44-import {
45- AutoTokenizer,
46- PreTrainedTokenizer,
47-} from './tokenizers.js';
48-
49-
50-import {
51- read_audio
52-} from './utils/audio.js';
53-import {
54- Callable,
55- dispatchCallback,
56- pop,
57- product,
58-} from './utils/core.js';
59-import {
60- getTopItems,
61- max,
62- round,
63- softmax,
64-} from './utils/maths.js';
65-import {
66- Tensor,
67- interpolate,
68- mean_pooling,
69-} from './utils/tensor.js';
17+ AutoModel,
18+ AutoModelForAudioClassification,
19+ AutoModelForCTC,
20+ AutoModelForCausalLM,
21+ AutoModelForDepthEstimation,
22+ AutoModelForDocumentQuestionAnswering,
23+ AutoModelForImageClassification,
24+ AutoModelForImageSegmentation,
25+ AutoModelForImageToImage,
26+ AutoModelForMaskedLM,
27+ AutoModelForObjectDetection,
28+ AutoModelForQuestionAnswering,
29+ AutoModelForSemanticSegmentation,
30+ AutoModelForSeq2SeqLM,
31+ AutoModelForSequenceClassification,
32+ AutoModelForSpeechSeq2Seq,
33+ AutoModelForTextToSpectrogram,
34+ AutoModelForTextToWaveform,
35+ AutoModelForTokenClassification,
36+ AutoModelForVision2Seq,
37+ AutoModelForZeroShotObjectDetection,
38+ PreTrainedModel,
39+} from "./models.js";
40+import { AutoProcessor, Processor } from "./processors.js";
41+import { AutoTokenizer, PreTrainedTokenizer } from "./tokenizers.js";
42+
43+import { read_audio } from "./utils/audio.js";
44+import { Callable, dispatchCallback, pop, product } from "./utils/core.js";
45+import { getTopItems, max, round, softmax } from "./utils/maths.js";
46+import { Tensor, interpolate, mean_pooling } from "./utils/tensor.js";
7047 // import { RawImage } from './utils/image.js';
7148
72-
7349 /**
7450 * @typedef {string | RawImage | URL} ImageInput
7551 * @typedef {ImageInput|ImageInput[]} ImagePipelineInputs
@@ -82,13 +58,13 @@
8258 * @private
8359 */
8460 async function prepareImages(images) {
85- if (!Array.isArray(images)) {
86- images = [images];
87- }
88-
89- // Possibly convert any non-images to images
90- // return await Promise.all(images.map(x => RawImage.read(x)));
91- return Promise.resolve([]);
61+ if (!Array.isArray(images)) {
62+ images = [images];
63+ }
64+
65+ // Possibly convert any non-images to images
66+ // return await Promise.all(images.map(x => RawImage.read(x)));
67+ return Promise.resolve([]);
9268 }
9369
9470 /**
@@ -104,18 +80,20 @@
10480 * @private
10581 */
10682 async function prepareAudios(audios, sampling_rate) {
107- if (!Array.isArray(audios)) {
108- audios = [audios];
109- }
110-
111- return await Promise.all(audios.map(x => {
112- if (typeof x === 'string' || x instanceof URL) {
113- return read_audio(x, sampling_rate);
114- } else if (x instanceof Float64Array) {
115- return new Float32Array(x);
116- }
117- return x;
118- }));
83+ if (!Array.isArray(audios)) {
84+ audios = [audios];
85+ }
86+
87+ return await Promise.all(
88+ audios.map((x) => {
89+ if (typeof x === "string" || x instanceof URL) {
90+ return read_audio(x, sampling_rate);
91+ } else if (x instanceof Float64Array) {
92+ return new Float32Array(x);
93+ }
94+ return x;
95+ }),
96+ );
11997 }
12098
12199 /**
@@ -134,19 +112,18 @@
134112 * @private
135113 */
136114 function get_bounding_box(box, asInteger) {
137- if (asInteger) {
138- box = box.map(x => x | 0);
139- }
140- const [xmin, ymin, xmax, ymax] = box;
141-
142- return { xmin, ymin, xmax, ymax };
115+ if (asInteger) {
116+ box = box.map((x) => x | 0);
117+ }
118+ const [xmin, ymin, xmax, ymax] = box;
119+
120+ return { xmin, ymin, xmax, ymax };
143121 }
144122
145-
146123 /**
147124 * @callback DisposeType Disposes the item.
148125 * @returns {Promise<void>} A promise that resolves when the item has been disposed.
149- *
126+ *
150127 * @typedef {Object} Disposable
151128 * @property {DisposeType} dispose A promise that resolves when the pipeline has been disposed.
152129 */
@@ -157,26 +134,26 @@
157134 * @extends Callable
158135 */
159136 export class Pipeline extends Callable {
160- /**
161- * Create a new Pipeline.
162- * @param {Object} options An object containing the following properties:
163- * @param {string} [options.task] The task of the pipeline. Useful for specifying subtasks.
164- * @param {PreTrainedModel} [options.model] The model used by the pipeline.
165- * @param {PreTrainedTokenizer} [options.tokenizer=null] The tokenizer used by the pipeline (if any).
166- * @param {Processor} [options.processor=null] The processor used by the pipeline (if any).
167- */
168- constructor({ task, model, tokenizer = null, processor = null }) {
169- super();
170- this.task = task;
171- this.model = model;
172- this.tokenizer = tokenizer;
173- this.processor = processor;
174- }
175-
176- /** @type {DisposeType} */
177- async dispose() {
178- await this.model.dispose();
179- }
137+ /**
138+ * Create a new Pipeline.
139+ * @param {Object} options An object containing the following properties:
140+ * @param {string} [options.task] The task of the pipeline. Useful for specifying subtasks.
141+ * @param {PreTrainedModel} [options.model] The model used by the pipeline.
142+ * @param {PreTrainedTokenizer} [options.tokenizer=null] The tokenizer used by the pipeline (if any).
143+ * @param {Processor} [options.processor=null] The processor used by the pipeline (if any).
144+ */
145+ constructor({ task, model, tokenizer = null, processor = null }) {
146+ super();
147+ this.task = task;
148+ this.model = model;
149+ this.tokenizer = tokenizer;
150+ this.processor = processor;
151+ }
152+
153+ /** @type {DisposeType} */
154+ async dispose() {
155+ await this.model.dispose();
156+ }
180157 }
181158
182159 /**
@@ -184,7 +161,7 @@
184161 * @property {string} task The task of the pipeline. Useful for specifying subtasks.
185162 * @property {PreTrainedModel} model The model used by the pipeline.
186163 * @property {PreTrainedTokenizer} tokenizer The tokenizer used by the pipeline.
187- *
164+ *
188165 * @typedef {ModelTokenizerConstructorArgs} TextPipelineConstructorArgs An object used to instantiate a text-based pipeline.
189166 */
190167
@@ -193,19 +170,18 @@
193170 * @property {string} task The task of the pipeline. Useful for specifying subtasks.
194171 * @property {PreTrainedModel} model The model used by the pipeline.
195172 * @property {Processor} processor The processor used by the pipeline.
196- *
173+ *
197174 * @typedef {ModelProcessorConstructorArgs} AudioPipelineConstructorArgs An object used to instantiate an audio-based pipeline.
198175 * @typedef {ModelProcessorConstructorArgs} ImagePipelineConstructorArgs An object used to instantiate an image-based pipeline.
199176 */
200177
201-
202178 /**
203179 * @typedef {Object} ModelTokenizerProcessorConstructorArgs
204180 * @property {string} task The task of the pipeline. Useful for specifying subtasks.
205181 * @property {PreTrainedModel} model The model used by the pipeline.
206182 * @property {PreTrainedTokenizer} tokenizer The tokenizer used by the pipeline.
207183 * @property {Processor} processor The processor used by the pipeline.
208- *
184+ *
209185 * @typedef {ModelTokenizerProcessorConstructorArgs} TextAudioPipelineConstructorArgs An object used to instantiate a text- and audio-based pipeline.
210186 * @typedef {ModelTokenizerProcessorConstructorArgs} TextImagePipelineConstructorArgs An object used to instantiate a text- and image-based pipeline.
211187 */
@@ -215,15 +191,15 @@
215191 * @property {string} label The label predicted.
216192 * @property {number} score The corresponding probability.
217193 * @typedef {TextClassificationSingle[]} TextClassificationOutput
218- *
194+ *
219195 * @typedef {Object} TextClassificationPipelineOptions Parameters specific to text classification pipelines.
220196 * @property {number} [topk=1] The number of top predictions to be returned.
221- *
197+ *
222198 * @callback TextClassificationPipelineCallback Classify the text(s) given as inputs.
223199 * @param {string|string[]} texts The input text(s) to be classified.
224200 * @param {TextClassificationPipelineOptions} [options] The options to use for text classification.
225201 * @returns {Promise<TextClassificationOutput|TextClassificationOutput[]>} An array or object containing the predicted labels and scores.
226- *
202+ *
227203 * @typedef {TextPipelineConstructorArgs & TextClassificationPipelineCallback & Disposable} TextClassificationPipelineType
228204 */
229205
@@ -236,7 +212,7 @@
236212 * const output = await classifier('I love transformers!');
237213 * // [{ label: 'POSITIVE', score: 0.999788761138916 }]
238214 * ```
239- *
215+ *
240216 * **Example:** Multilingual sentiment-analysis w/ `Xenova/bert-base-multilingual-uncased-sentiment` (and return top 5 classes).
241217 * ```javascript
242218 * const classifier = await pipeline('sentiment-analysis', 'Xenova/bert-base-multilingual-uncased-sentiment');
@@ -249,7 +225,7 @@
249225 * // { label: '2 stars', score: 0.0009423971059732139 }
250226 * // ]
251227 * ```
252- *
228+ *
253229 * **Example:** Toxic comment classification w/ `Xenova/toxic-bert` (and return all classes).
254230 * ```javascript
255231 * const classifier = await pipeline('text-classification', 'Xenova/toxic-bert');
@@ -264,56 +240,58 @@
264240 * // ]
265241 * ```
266242 */
267-export class TextClassificationPipeline extends (/** @type {new (options: TextPipelineConstructorArgs) => TextClassificationPipelineType} */ (Pipeline)) {
268-
269- /**
270- * Create a new TextClassificationPipeline.
271- * @param {TextPipelineConstructorArgs} options An object used to instantiate the pipeline.
272- */
273- constructor(options) {
274- super(options);
275- }
276-
277- /** @type {TextClassificationPipelineCallback} */
278- async _call(texts, {
279- topk = 1
280- } = {}) {
281-
282- // Run tokenization
283- const model_inputs = this.tokenizer(texts, {
284- padding: true,
285- truncation: true,
286- });
287-
288- // Run model
289- const outputs = await this.model(model_inputs)
290-
291- // TODO: Use softmax tensor function
292- const function_to_apply =
293- this.model.config.problem_type === 'multi_label_classification'
294- ? batch => batch.sigmoid().data
295- : batch => softmax(batch.data); // single_label_classification (default)
296-
297- const id2label = this.model.config.id2label;
298-
299- const toReturn = [];
300- for (const batch of outputs.logits) {
301- const output = function_to_apply(batch);
302- const scores = getTopItems(output, topk);
303-
304- const vals = scores.map(x => ({
305- label: id2label[x[0]],
306- score: x[1],
307- }));
308- if (topk === 1) {
309- toReturn.push(...vals);
310- } else {
311- toReturn.push(vals);
312- }
313- }
243+export class TextClassificationPipeline
244+ extends /** @type {new (options: TextPipelineConstructorArgs) => TextClassificationPipelineType} */ (
245+ Pipeline
246+ )
247+{
248+ /**
249+ * Create a new TextClassificationPipeline.
250+ * @param {TextPipelineConstructorArgs} options An object used to instantiate the pipeline.
251+ */
252+ constructor(options) {
253+ super(options);
254+ }
255+
256+ /** @type {TextClassificationPipelineCallback} */
257+ async _call(texts, { topk = 1 } = {}) {
258+ // Run tokenization
259+ const model_inputs = this.tokenizer(texts, {
260+ padding: true,
261+ truncation: true,
262+ });
314263
315- return Array.isArray(texts) || topk === 1 ? /** @type {TextClassificationOutput} */ (toReturn) : /** @type {TextClassificationOutput[]} */ (toReturn)[0];
264+ // Run model
265+ const outputs = await this.model(model_inputs);
266+
267+ // TODO: Use softmax tensor function
268+ const function_to_apply =
269+ this.model.config.problem_type === "multi_label_classification"
270+ ? (batch) => batch.sigmoid().data
271+ : (batch) => softmax(batch.data); // single_label_classification (default)
272+
273+ const id2label = this.model.config.id2label;
274+
275+ const toReturn = [];
276+ for (const batch of outputs.logits) {
277+ const output = function_to_apply(batch);
278+ const scores = getTopItems(output, topk);
279+
280+ const vals = scores.map((x) => ({
281+ label: id2label[x[0]],
282+ score: x[1],
283+ }));
284+ if (topk === 1) {
285+ toReturn.push(...vals);
286+ } else {
287+ toReturn.push(vals);
288+ }
316289 }
290+
291+ return Array.isArray(texts) || topk === 1
292+ ? /** @type {TextClassificationOutput} */ (toReturn)
293+ : /** @type {TextClassificationOutput[]} */ (toReturn)[0];
294+ }
317295 }
318296
319297 /**
@@ -325,21 +303,21 @@
325303 * @property {number} [start] The index of the start of the corresponding entity in the sentence.
326304 * @property {number} [end] The index of the end of the corresponding entity in the sentence.
327305 * @typedef {TokenClassificationSingle[]} TokenClassificationOutput
328- *
306+ *
329307 * @typedef {Object} TokenClassificationPipelineOptions Parameters specific to token classification pipelines.
330308 * @property {string[]} [ignore_labels] A list of labels to ignore.
331- *
309+ *
332310 * @callback TokenClassificationPipelineCallback Classify each token of the text(s) given as inputs.
333311 * @param {string|string[]} texts One or several texts (or one list of texts) for token classification.
334312 * @param {TokenClassificationPipelineOptions} [options] The options to use for token classification.
335313 * @returns {Promise<TokenClassificationOutput|TokenClassificationOutput[]>} The result.
336- *
314+ *
337315 * @typedef {TextPipelineConstructorArgs & TokenClassificationPipelineCallback & Disposable} TokenClassificationPipelineType
338316 */
339317
340318 /**
341319 * Named Entity Recognition pipeline using any `ModelForTokenClassification`.
342- *
320+ *
343321 * **Example:** Perform named entity recognition with `Xenova/bert-base-NER`.
344322 * ```javascript
345323 * const classifier = await pipeline('token-classification', 'Xenova/bert-base-NER');
@@ -349,7 +327,7 @@
349327 * // { entity: 'B-LOC', score: 0.9994474053382874, index: 9, word: 'London' }
350328 * // ]
351329 * ```
352- *
330+ *
353331 * **Example:** Perform named entity recognition with `Xenova/bert-base-NER` (and return all labels).
354332 * ```javascript
355333 * const classifier = await pipeline('token-classification', 'Xenova/bert-base-NER');
@@ -366,76 +344,80 @@
366344 * // ]
367345 * ```
368346 */
369-export class TokenClassificationPipeline extends (/** @type {new (options: TextPipelineConstructorArgs) => TokenClassificationPipelineType} */ (Pipeline)) {
370-
371- /**
372- * Create a new TokenClassificationPipeline.
373- * @param {TextPipelineConstructorArgs} options An object used to instantiate the pipeline.
374- */
375- constructor(options) {
376- super(options);
377- }
378-
379- /** @type {TokenClassificationPipelineCallback} */
380- async _call(texts, {
381- ignore_labels = ['O'],
382- } = {}) {
347+export class TokenClassificationPipeline
348+ extends /** @type {new (options: TextPipelineConstructorArgs) => TokenClassificationPipelineType} */ (
349+ Pipeline
350+ )
351+{
352+ /**
353+ * Create a new TokenClassificationPipeline.
354+ * @param {TextPipelineConstructorArgs} options An object used to instantiate the pipeline.
355+ */
356+ constructor(options) {
357+ super(options);
358+ }
359+
360+ /** @type {TokenClassificationPipelineCallback} */
361+ async _call(texts, { ignore_labels = ["O"] } = {}) {
362+ const isBatched = Array.isArray(texts);
363+
364+ // Run tokenization
365+ const model_inputs = this.tokenizer(isBatched ? texts : [texts], {
366+ padding: true,
367+ truncation: true,
368+ });
383369
384- const isBatched = Array.isArray(texts);
370+ // Run model
371+ const outputs = await this.model(model_inputs);
372+
373+ const logits = outputs.logits;
374+ const id2label = this.model.config.id2label;
375+
376+ const toReturn = [];
377+ for (let i = 0; i < logits.dims[0]; ++i) {
378+ const ids = model_inputs.input_ids[i];
379+ const batch = logits[i];
380+
381+ // List of tokens that aren't ignored
382+ const tokens = [];
383+ for (let j = 0; j < batch.dims[0]; ++j) {
384+ const tokenData = batch[j];
385+ const topScoreIndex = max(tokenData.data)[1];
386+
387+ const entity = id2label
388+ ? id2label[topScoreIndex]
389+ : `LABEL_${topScoreIndex}`;
390+ if (ignore_labels.includes(entity)) {
391+ // We predicted a token that should be ignored. So, we skip it.
392+ continue;
393+ }
385394
386- // Run tokenization
387- const model_inputs = this.tokenizer(isBatched ? texts : [texts], {
388- padding: true,
389- truncation: true,
395+ // TODO add option to keep special tokens?
396+ const word = this.tokenizer.decode([ids[j].item()], {
397+ skip_special_tokens: true,
390398 });
391-
392- // Run model
393- const outputs = await this.model(model_inputs)
394-
395- const logits = outputs.logits;
396- const id2label = this.model.config.id2label;
397-
398- const toReturn = [];
399- for (let i = 0; i < logits.dims[0]; ++i) {
400- const ids = model_inputs.input_ids[i];
401- const batch = logits[i];
402-
403- // List of tokens that aren't ignored
404- const tokens = [];
405- for (let j = 0; j < batch.dims[0]; ++j) {
406- const tokenData = batch[j];
407- const topScoreIndex = max(tokenData.data)[1];
408-
409- const entity = id2label ? id2label[topScoreIndex] : `LABEL_${topScoreIndex}`;
410- if (ignore_labels.includes(entity)) {
411- // We predicted a token that should be ignored. So, we skip it.
412- continue;
413- }
414-
415- // TODO add option to keep special tokens?
416- const word = this.tokenizer.decode([ids[j].item()], { skip_special_tokens: true });
417- if (word === '') {
418- // Was a special token. So, we skip it.
419- continue;
420- }
421-
422- const scores = softmax(tokenData.data);
423-
424- tokens.push({
425- entity: entity,
426- score: scores[topScoreIndex],
427- index: j,
428- word: word,
429-
430- // TODO: null for now, but will add
431- start: null,
432- end: null,
433- });
434- }
435- toReturn.push(tokens);
399+ if (word === "") {
400+ // Was a special token. So, we skip it.
401+ continue;
436402 }
437- return isBatched ? toReturn : toReturn[0];
403+
404+ const scores = softmax(tokenData.data);
405+
406+ tokens.push({
407+ entity: entity,
408+ score: scores[topScoreIndex],
409+ index: j,
410+ word: word,
411+
412+ // TODO: null for now, but will add
413+ start: null,
414+ end: null,
415+ });
416+ }
417+ toReturn.push(tokens);
438418 }
419+ return isBatched ? toReturn : toReturn[0];
420+ }
439421 }
440422
441423 /**
@@ -444,22 +426,22 @@
444426 * @property {number} [start] The character start index of the answer (in the tokenized version of the input).
445427 * @property {number} [end] The character end index of the answer (in the tokenized version of the input).
446428 * @property {string} answer The answer to the question.
447- *
429+ *
448430 * @typedef {Object} QuestionAnsweringPipelineOptions Parameters specific to question answering pipelines.
449431 * @property {number} [topk=1] The number of top answer predictions to be returned.
450- *
432+ *
451433 * @callback QuestionAnsweringPipelineCallback Answer the question(s) given as inputs by using the context(s).
452434 * @param {string|string[]} question One or several question(s) (must be used in conjunction with the `context` argument).
453435 * @param {string|string[]} context One or several context(s) associated with the question(s) (must be used in conjunction with the `question` argument).
454436 * @param {QuestionAnsweringPipelineOptions} [options] The options to use for question answering.
455437 * @returns {Promise<QuestionAnsweringOutput|QuestionAnsweringOutput[]>} An array or object containing the predicted answers and scores.
456- *
438+ *
457439 * @typedef {TextPipelineConstructorArgs & QuestionAnsweringPipelineCallback & Disposable} QuestionAnsweringPipelineType
458440 */
459441
460442 /**
461443 * Question Answering pipeline using any `ModelForQuestionAnswering`.
462- *
444+ *
463445 * **Example:** Run question answering with `Xenova/distilbert-base-uncased-distilled-squad`.
464446 * ```javascript
465447 * const answerer = await pipeline('question-answering', 'Xenova/distilbert-base-uncased-distilled-squad');
@@ -472,70 +454,70 @@
472454 * // }
473455 * ```
474456 */
475-export class QuestionAnsweringPipeline extends (/** @type {new (options: TextPipelineConstructorArgs) => QuestionAnsweringPipelineType} */ (Pipeline)) {
476-
477- /**
478- * Create a new QuestionAnsweringPipeline.
479- * @param {TextPipelineConstructorArgs} options An object used to instantiate the pipeline.
480- */
481- constructor(options) {
482- super(options);
483- }
457+export class QuestionAnsweringPipeline
458+ extends /** @type {new (options: TextPipelineConstructorArgs) => QuestionAnsweringPipelineType} */ (
459+ Pipeline
460+ )
461+{
462+ /**
463+ * Create a new QuestionAnsweringPipeline.
464+ * @param {TextPipelineConstructorArgs} options An object used to instantiate the pipeline.
465+ */
466+ constructor(options) {
467+ super(options);
468+ }
469+
470+ /** @type {QuestionAnsweringPipelineCallback} */
471+ async _call(question, context, { topk = 1 } = {}) {
472+ // Run tokenization
473+ const inputs = this.tokenizer(question, {
474+ text_pair: context,
475+ padding: true,
476+ truncation: true,
477+ });
484478
485- /** @type {QuestionAnsweringPipelineCallback} */
486- async _call(question, context, {
487- topk = 1
488- } = {}) {
489-
490- // Run tokenization
491- const inputs = this.tokenizer(question, {
492- text_pair: context,
493- padding: true,
494- truncation: true,
495- });
479+ const output = await this.model(inputs);
496480
497- const output = await this.model(inputs);
498-
499- /** @type {QuestionAnsweringOutput[]} */
500- const toReturn = [];
501- for (let j = 0; j < output.start_logits.dims[0]; ++j) {
502- const ids = inputs.input_ids[j];
503- const sepIndex = ids.indexOf(this.tokenizer.sep_token_id);
504-
505- const s1 = Array.from(softmax(output.start_logits[j].data))
506- .map((x, i) => [x, i])
507- .filter(x => x[1] > sepIndex);
508- const e1 = Array.from(softmax(output.end_logits[j].data))
509- .map((x, i) => [x, i])
510- .filter(x => x[1] > sepIndex);
511-
512- const options = product(s1, e1)
513- .filter(x => x[0][1] <= x[1][1])
514- .map(x => [x[0][1], x[1][1], x[0][0] * x[1][0]])
515- .sort((a, b) => b[2] - a[2]);
516-
517- for (let k = 0; k < Math.min(options.length, topk); ++k) {
518- const [start, end, score] = options[k];
519-
520- const answer_tokens = [...ids].slice(start, end + 1)
521-
522- const answer = this.tokenizer.decode(answer_tokens, {
523- skip_special_tokens: true,
524- });
525-
526- // TODO add start and end?
527- // NOTE: HF returns character index
528- toReturn.push({
529- answer, score
530- });
531- }
532- }
481+ /** @type {QuestionAnsweringOutput[]} */
482+ const toReturn = [];
483+ for (let j = 0; j < output.start_logits.dims[0]; ++j) {
484+ const ids = inputs.input_ids[j];
485+ const sepIndex = ids.indexOf(this.tokenizer.sep_token_id);
486+
487+ const s1 = Array.from(softmax(output.start_logits[j].data))
488+ .map((x, i) => [x, i])
489+ .filter((x) => x[1] > sepIndex);
490+ const e1 = Array.from(softmax(output.end_logits[j].data))
491+ .map((x, i) => [x, i])
492+ .filter((x) => x[1] > sepIndex);
533493
534- // Mimic HF's return type based on topk
535- return (topk === 1) ? toReturn[0] : toReturn;
494+ const options = product(s1, e1)
495+ .filter((x) => x[0][1] <= x[1][1])
496+ .map((x) => [x[0][1], x[1][1], x[0][0] * x[1][0]])
497+ .sort((a, b) => b[2] - a[2]);
498+
499+ for (let k = 0; k < Math.min(options.length, topk); ++k) {
500+ const [start, end, score] = options[k];
501+
502+ const answer_tokens = [...ids].slice(start, end + 1);
503+
504+ const answer = this.tokenizer.decode(answer_tokens, {
505+ skip_special_tokens: true,
506+ });
507+
508+ // TODO add start and end?
509+ // NOTE: HF returns character index
510+ toReturn.push({
511+ answer,
512+ score,
513+ });
514+ }
536515 }
537-}
538516
517+ // Mimic HF's return type based on topk
518+ return topk === 1 ? toReturn[0] : toReturn;
519+ }
520+}
539521
540522 /**
541523 * @typedef {Object} FillMaskSingle
@@ -544,10 +526,10 @@
544526 * @property {number} token The predicted token id (to replace the masked one).
545527 * @property {string} token_str The predicted token (to replace the masked one).
546528 * @typedef {FillMaskSingle[]} FillMaskOutput
547- *
529+ *
548530 * @typedef {Object} FillMaskPipelineOptions Parameters specific to fill mask pipelines.
549531 * @property {number} [topk=5] When passed, overrides the number of predictions to return.
550- *
532+ *
551533 * @callback FillMaskPipelineCallback Fill the masked token in the text(s) given as inputs.
552534 * @param {string|string[]} texts One or several texts (or one list of prompts) with masked tokens.
553535 * @param {FillMaskPipelineOptions} [options] The options to use for masked language modelling.
@@ -555,13 +537,13 @@
555537 * and the sequence with the predicted token filled in, or an array of such arrays (one for each input text).
556538 * If only one input text is given, the output will be an array of objects.
557539 * @throws {Error} When the mask token is not found in the input text.
558- *
540+ *
559541 * @typedef {TextPipelineConstructorArgs & FillMaskPipelineCallback & Disposable} FillMaskPipelineType
560542 */
561543
562544 /**
563545 * Masked language modeling prediction pipeline using any `ModelWithLMHead`.
564- *
546+ *
565547 * **Example:** Perform masked language modelling (a.k.a. "fill-mask") with `Xenova/bert-base-uncased`.
566548 * ```javascript
567549 * const unmasker = await pipeline('fill-mask', 'Xenova/bert-base-cased');
@@ -574,7 +556,7 @@
574556 * // { token_str: 'life', score: 0.01859794743359089, token: 1297, sequence: 'The goal of life is life.' }
575557 * // ]
576558 * ```
577- *
559+ *
578560 * **Example:** Perform masked language modelling (a.k.a. "fill-mask") with `Xenova/bert-base-cased` (and return top result).
579561 * ```javascript
580562 * const unmasker = await pipeline('fill-mask', 'Xenova/bert-base-cased');
@@ -582,77 +564,82 @@
582564 * // [{ token_str: 'spiral', score: 0.6299987435340881, token: 14061, sequence: 'The Milky Way is a spiral galaxy.' }]
583565 * ```
584566 */
585-export class FillMaskPipeline extends (/** @type {new (options: TextPipelineConstructorArgs) => FillMaskPipelineType} */ (Pipeline)) {
586-
587- /**
588- * Create a new FillMaskPipeline.
589- * @param {TextPipelineConstructorArgs} options An object used to instantiate the pipeline.
590- */
591- constructor(options) {
592- super(options);
593- }
567+export class FillMaskPipeline
568+ extends /** @type {new (options: TextPipelineConstructorArgs) => FillMaskPipelineType} */ (
569+ Pipeline
570+ )
571+{
572+ /**
573+ * Create a new FillMaskPipeline.
574+ * @param {TextPipelineConstructorArgs} options An object used to instantiate the pipeline.
575+ */
576+ constructor(options) {
577+ super(options);
578+ }
579+
580+ /** @type {FillMaskPipelineCallback} */
581+ async _call(texts, { topk = 5 } = {}) {
582+ // Run tokenization
583+ const model_inputs = this.tokenizer(texts, {
584+ padding: true,
585+ truncation: true,
586+ });
594587
595- /** @type {FillMaskPipelineCallback} */
596- async _call(texts, {
597- topk = 5
598- } = {}) {
599-
600- // Run tokenization
601- const model_inputs = this.tokenizer(texts, {
602- padding: true,
603- truncation: true,
604- });
588+ // Run model
589+ const outputs = await this.model(model_inputs);
605590
606- // Run model
607- const outputs = await this.model(model_inputs)
608-
609- const toReturn = [];
610-
611- for (let i = 0; i < model_inputs.input_ids.dims[0]; ++i) {
612- const ids = model_inputs.input_ids[i];
613- const mask_token_index = ids.indexOf(this.tokenizer.mask_token_id)
614-
615- if (mask_token_index === -1) {
616- throw Error(`Mask token (${this.tokenizer.mask_token}) not found in text.`)
617- }
618- const logits = outputs.logits[i];
619- const itemLogits = logits[mask_token_index];
620-
621- const scores = getTopItems(softmax(itemLogits.data), topk);
622-
623- toReturn.push(scores.map(x => {
624- const sequence = [...ids];
625- sequence[mask_token_index] = x[0];
626-
627- return {
628- score: x[1],
629- token: x[0],
630- token_str: this.tokenizer.model.vocab[x[0]],
631- sequence: this.tokenizer.decode(sequence, { skip_special_tokens: true }),
632- }
633- }));
634- }
635- return Array.isArray(texts) ? toReturn : toReturn[0];
591+ const toReturn = [];
592+
593+ for (let i = 0; i < model_inputs.input_ids.dims[0]; ++i) {
594+ const ids = model_inputs.input_ids[i];
595+ const mask_token_index = ids.indexOf(this.tokenizer.mask_token_id);
596+
597+ if (mask_token_index === -1) {
598+ throw Error(
599+ `Mask token (${this.tokenizer.mask_token}) not found in text.`,
600+ );
601+ }
602+ const logits = outputs.logits[i];
603+ const itemLogits = logits[mask_token_index];
604+
605+ const scores = getTopItems(softmax(itemLogits.data), topk);
606+
607+ toReturn.push(
608+ scores.map((x) => {
609+ const sequence = [...ids];
610+ sequence[mask_token_index] = x[0];
611+
612+ return {
613+ score: x[1],
614+ token: x[0],
615+ token_str: this.tokenizer.model.vocab[x[0]],
616+ sequence: this.tokenizer.decode(sequence, {
617+ skip_special_tokens: true,
618+ }),
619+ };
620+ }),
621+ );
636622 }
623+ return Array.isArray(texts) ? toReturn : toReturn[0];
624+ }
637625 }
638626
639-
640627 /**
641628 * @typedef {Object} Text2TextGenerationSingle
642629 * @property {string} generated_text The generated text.
643630 * @typedef {Text2TextGenerationSingle[]} Text2TextGenerationOutput
644- *
631+ *
645632 * @callback Text2TextGenerationPipelineCallback Generate the output text(s) using text(s) given as inputs.
646633 * @param {string|string[]} texts Input text for the encoder.
647634 * @param {import('./utils/generation.js').GenerationConfigType} [options] Additional keyword arguments to pass along to the generate method of the model.
648635 * @returns {Promise<Text2TextGenerationOutput|Text2TextGenerationOutput[]>}
649- *
636+ *
650637 * @typedef {TextPipelineConstructorArgs & Text2TextGenerationPipelineCallback & Disposable} Text2TextGenerationPipelineType
651638 */
652639
653640 /**
654641 * Text2TextGenerationPipeline class for generating text using a model that performs text-to-text generation tasks.
655- *
642+ *
656643 * **Example:** Text-to-text generation w/ `Xenova/LaMini-Flan-T5-783M`.
657644 * ```javascript
658645 * const generator = await pipeline('text2text-generation', 'Xenova/LaMini-Flan-T5-783M');
@@ -662,82 +649,95 @@
662649 * // [{ generated_text: "To become more healthy, you can: 1. Eat a balanced diet with plenty of fruits, vegetables, whole grains, lean proteins, and healthy fats. 2. Stay hydrated by drinking plenty of water. 3. Get enough sleep and manage stress levels. 4. Avoid smoking and excessive alcohol consumption. 5. Regularly exercise and maintain a healthy weight. 6. Practice good hygiene and sanitation. 7. Seek medical attention if you experience any health issues." }]
663650 * ```
664651 */
665-export class Text2TextGenerationPipeline extends (/** @type {new (options: TextPipelineConstructorArgs) => Text2TextGenerationPipelineType} */ (Pipeline)) {
666- /** @type {'generated_text'} */
667- _key = 'generated_text';
668-
669- /**
670- * Create a new Text2TextGenerationPipeline.
671- * @param {TextPipelineConstructorArgs} options An object used to instantiate the pipeline.
672- */
673- constructor(options) {
674- super(options);
652+export class Text2TextGenerationPipeline
653+ extends /** @type {new (options: TextPipelineConstructorArgs) => Text2TextGenerationPipelineType} */ (
654+ Pipeline
655+ )
656+{
657+ /** @type {'generated_text'} */
658+ _key = "generated_text";
659+
660+ /**
661+ * Create a new Text2TextGenerationPipeline.
662+ * @param {TextPipelineConstructorArgs} options An object used to instantiate the pipeline.
663+ */
664+ constructor(options) {
665+ super(options);
666+ }
667+
668+ /** @type {Text2TextGenerationPipelineCallback} */
669+ async _call(texts, generate_kwargs = {}) {
670+ if (!Array.isArray(texts)) {
671+ texts = [texts];
675672 }
676673
677- /** @type {Text2TextGenerationPipelineCallback} */
678- async _call(texts, generate_kwargs = {}) {
679- if (!Array.isArray(texts)) {
680- texts = [texts];
681- }
682-
683-
684- // Add global prefix, if present
685- if (this.model.config.prefix) {
686- texts = texts.map(x => this.model.config.prefix + x)
687- }
688-
689- // Handle task specific params:
690- const task_specific_params = this.model.config.task_specific_params
691- if (task_specific_params && task_specific_params[this.task]) {
692- // Add prefixes, if present
693- if (task_specific_params[this.task].prefix) {
694- texts = texts.map(x => task_specific_params[this.task].prefix + x)
695- }
696-
697- // TODO update generation config
698- }
699-
700- const tokenizer = this.tokenizer;
701- const tokenizer_options = {
702- padding: true,
703- truncation: true,
704- }
705- let input_ids;
706- if (this instanceof TranslationPipeline && '_build_translation_inputs' in tokenizer) {
707- // TODO: move to Translation pipeline?
708- // Currently put here to avoid code duplication
709- // @ts-ignore
710- input_ids = tokenizer._build_translation_inputs(texts, tokenizer_options, generate_kwargs).input_ids;
711-
712- } else {
713- input_ids = tokenizer(texts, tokenizer_options).input_ids;
714- }
674+ // Add global prefix, if present
675+ if (this.model.config.prefix) {
676+ texts = texts.map((x) => this.model.config.prefix + x);
677+ }
715678
716- const outputTokenIds = await this.model.generate(input_ids, generate_kwargs);
679+ // Handle task specific params:
680+ const task_specific_params = this.model.config.task_specific_params;
681+ if (task_specific_params && task_specific_params[this.task]) {
682+ // Add prefixes, if present
683+ if (task_specific_params[this.task].prefix) {
684+ texts = texts.map((x) => task_specific_params[this.task].prefix + x);
685+ }
686+
687+ // TODO update generation config
688+ }
717689
718- return tokenizer.batch_decode(outputTokenIds, {
719- skip_special_tokens: true,
720- }).map(text => ({ [this._key]: text }));
690+ const tokenizer = this.tokenizer;
691+ const tokenizer_options = {
692+ padding: true,
693+ truncation: true,
694+ };
695+ let input_ids;
696+ if (
697+ this instanceof TranslationPipeline &&
698+ "_build_translation_inputs" in tokenizer
699+ ) {
700+ // TODO: move to Translation pipeline?
701+ // Currently put here to avoid code duplication
702+ // @ts-ignore
703+ input_ids = tokenizer._build_translation_inputs(
704+ texts,
705+ tokenizer_options,
706+ generate_kwargs,
707+ ).input_ids;
708+ } else {
709+ input_ids = tokenizer(texts, tokenizer_options).input_ids;
721710 }
722-}
723711
712+ const outputTokenIds = await this.model.generate(
713+ input_ids,
714+ generate_kwargs,
715+ );
716+
717+ return tokenizer
718+ .batch_decode(outputTokenIds, {
719+ skip_special_tokens: true,
720+ })
721+ .map((text) => ({ [this._key]: text }));
722+ }
723+}
724724
725725 /**
726726 * @typedef {Object} SummarizationSingle
727727 * @property {string} summary_text The summary text.
728728 * @typedef {SummarizationSingle[]} SummarizationOutput
729- *
729+ *
730730 * @callback SummarizationPipelineCallback Summarize the text(s) given as inputs.
731731 * @param {string|string[]} texts One or several articles (or one list of articles) to summarize.
732732 * @param {import('./utils/generation.js').GenerationConfigType} [options] Additional keyword arguments to pass along to the generate method of the model.
733733 * @returns {Promise<SummarizationOutput|SummarizationOutput[]>}
734- *
734+ *
735735 * @typedef {TextPipelineConstructorArgs & SummarizationPipelineCallback & Disposable} SummarizationPipelineType
736736 */
737737
738738 /**
739739 * A pipeline for summarization tasks, inheriting from Text2TextGenerationPipeline.
740- *
740+ *
741741 * **Example:** Summarization w/ `Xenova/distilbart-cnn-6-6`.
742742 * ```javascript
743743 * const generator = await pipeline('summarization', 'Xenova/distilbart-cnn-6-6');
@@ -755,41 +755,44 @@
755755 * // [{ summary_text: ' The Eiffel Tower is about the same height as an 81-storey building and the tallest structure in Paris. It is the second tallest free-standing structure in France after the Millau Viaduct.' }]
756756 * ```
757757 */
758-export class SummarizationPipeline extends (/** @type {new (options: TextPipelineConstructorArgs) => SummarizationPipelineType} */ (/** @type {any} */ (Text2TextGenerationPipeline))) {
759- /** @type {'summary_text'} */
760- _key = 'summary_text';
761-
762- /**
763- * Create a new SummarizationPipeline.
764- * @param {TextPipelineConstructorArgs} options An object used to instantiate the pipeline.
765- */
766- constructor(options) {
767- super(options);
768- }
758+export class SummarizationPipeline
759+ extends /** @type {new (options: TextPipelineConstructorArgs) => SummarizationPipelineType} */ (
760+ /** @type {any} */ (Text2TextGenerationPipeline)
761+ )
762+{
763+ /** @type {'summary_text'} */
764+ _key = "summary_text";
765+
766+ /**
767+ * Create a new SummarizationPipeline.
768+ * @param {TextPipelineConstructorArgs} options An object used to instantiate the pipeline.
769+ */
770+ constructor(options) {
771+ super(options);
772+ }
769773 }
770774
771-
772775 /**
773776 * @typedef {Object} TranslationSingle
774777 * @property {string} translation_text The translated text.
775778 * @typedef {TranslationSingle[]} TranslationOutput
776- *
779+ *
777780 * @callback TranslationPipelineCallback Translate the text(s) given as inputs.
778781 * @param {string|string[]} texts Texts to be translated.
779782 * @param {import('./utils/generation.js').GenerationConfigType} [options] Additional keyword arguments to pass along to the generate method of the model.
780783 * @returns {Promise<TranslationOutput|TranslationOutput[]>}
781- *
784+ *
782785 * @typedef {TextPipelineConstructorArgs & TranslationPipelineCallback & Disposable} TranslationPipelineType
783786 */
784787
785788 /**
786789 * Translates text from one language to another.
787- *
790+ *
788791 * **Example:** Multilingual translation w/ `Xenova/nllb-200-distilled-600M`.
789- *
792+ *
790793 * See [here](https://github.com/facebookresearch/flores/blob/main/flores200/README.md#languages-in-flores-200)
791794 * for the full list of languages and their corresponding codes.
792- *
795+ *
793796 * ```javascript
794797 * const translator = await pipeline('translation', 'Xenova/nllb-200-distilled-600M');
795798 * const output = await translator('जीवन एक चॉकलेट बॉक्स की तरह है।', {
@@ -798,12 +801,12 @@
798801 * });
799802 * // [{ translation_text: 'La vie est comme une boîte à chocolat.' }]
800803 * ```
801- *
804+ *
802805 * **Example:** Multilingual translation w/ `Xenova/m2m100_418M`.
803- *
806+ *
804807 * See [here](https://huggingface.co/facebook/m2m100_418M#languages-covered)
805808 * for the full list of languages and their corresponding codes.
806- *
809+ *
807810 * ```javascript
808811 * const translator = await pipeline('translation', 'Xenova/m2m100_418M');
809812 * const output = await translator('生活就像一盒巧克力。', {
@@ -812,12 +815,12 @@
812815 * });
813816 * // [{ translation_text: 'Life is like a box of chocolate.' }]
814817 * ```
815- *
818+ *
816819 * **Example:** Multilingual translation w/ `Xenova/mbart-large-50-many-to-many-mmt`.
817- *
820+ *
818821 * See [here](https://huggingface.co/facebook/mbart-large-50-many-to-many-mmt#languages-covered)
819822 * for the full list of languages and their corresponding codes.
820- *
823+ *
821824 * ```javascript
822825 * const translator = await pipeline('translation', 'Xenova/mbart-large-50-many-to-many-mmt');
823826 * const output = await translator('संयुक्त राष्ट्र के प्रमुख का कहना है कि सीरिया में कोई सैन्य समाधान नहीं है', {
@@ -827,34 +830,37 @@
827830 * // [{ translation_text: 'Le chef des Nations affirme qu 'il n 'y a military solution in Syria.' }]
828831 * ```
829832 */
830-export class TranslationPipeline extends (/** @type {new (options: TextPipelineConstructorArgs) => TranslationPipelineType} */ (/** @type {any} */ (Text2TextGenerationPipeline))) {
831- /** @type {'translation_text'} */
832- _key = 'translation_text';
833-
834- /**
835- * Create a new TranslationPipeline.
836- * @param {TextPipelineConstructorArgs} options An object used to instantiate the pipeline.
837- */
838- constructor(options) {
839- super(options);
840- }
833+export class TranslationPipeline
834+ extends /** @type {new (options: TextPipelineConstructorArgs) => TranslationPipelineType} */ (
835+ /** @type {any} */ (Text2TextGenerationPipeline)
836+ )
837+{
838+ /** @type {'translation_text'} */
839+ _key = "translation_text";
840+
841+ /**
842+ * Create a new TranslationPipeline.
843+ * @param {TextPipelineConstructorArgs} options An object used to instantiate the pipeline.
844+ */
845+ constructor(options) {
846+ super(options);
847+ }
841848 }
842849
843-
844850 /**
845851 * @typedef {Object} TextGenerationSingle
846852 * @property {string} generated_text The generated text.
847853 * @typedef {TextGenerationSingle[]} TextGenerationOutput
848- *
854+ *
849855 * @typedef {Object} TextGenerationSpecificParams Parameters specific to text-generation pipelines.
850856 * @property {boolean} [add_special_tokens] Whether or not to add special tokens when tokenizing the sequences.
851857 * @typedef {import('./utils/generation.js').GenerationConfigType & TextGenerationSpecificParams} TextGenerationConfig
852- *
858+ *
853859 * @callback TextGenerationPipelineCallback Complete the prompt(s) given as inputs.
854860 * @param {string|string[]} texts One or several prompts (or one list of prompts) to complete.
855861 * @param {TextGenerationConfig} [options] Additional keyword arguments to pass along to the generate method of the model.
856862 * @returns {Promise<TextGenerationOutput|TextGenerationOutput[]>} An array or object containing the generated texts.
857- *
863+ *
858864 * @typedef {TextPipelineConstructorArgs & TextGenerationPipelineCallback & Disposable} TextGenerationPipelineType
859865 */
860866
@@ -862,7 +868,7 @@
862868 * Language generation pipeline using any `ModelWithLMHead` or `ModelForCausalLM`.
863869 * This pipeline predicts the words that will follow a specified text prompt.
864870 * NOTE: For the full list of generation parameters, see [`GenerationConfig`](./utils/generation#module_utils/generation.GenerationConfig).
865- *
871+ *
866872 * **Example:** Text generation with `Xenova/distilgpt2` (default settings).
867873 * ```javascript
868874 * const generator = await pipeline('text-generation', 'Xenova/distilgpt2');
@@ -870,7 +876,7 @@
870876 * const output = await generator(text);
871877 * // [{ generated_text: "I enjoy walking with my cute dog, and I love to play with the other dogs." }]
872878 * ```
873- *
879+ *
874880 * **Example:** Text generation with `Xenova/distilgpt2` (custom settings).
875881 * ```javascript
876882 * const generator = await pipeline('text-generation', 'Xenova/distilgpt2');
@@ -889,7 +895,7 @@
889895 * // "generated_text": "Once upon a time, there was an abundance of information about the most important and influential"
890896 * // }]
891897 * ```
892- *
898+ *
893899 * **Example:** Run code generation with `Xenova/codegen-350M-mono`.
894900 * ```javascript
895901 * const generator = await pipeline('text-generation', 'Xenova/codegen-350M-mono');
@@ -908,53 +914,60 @@
908914 * // }]
909915 * ```
910916 */
911-export class TextGenerationPipeline extends (/** @type {new (options: TextPipelineConstructorArgs) => TextGenerationPipelineType} */ (Pipeline)) {
912-
913- /**
914- * Create a new TextGenerationPipeline.
915- * @param {TextPipelineConstructorArgs} options An object used to instantiate the pipeline.
916- */
917- constructor(options) {
918- super(options);
917+export class TextGenerationPipeline
918+ extends /** @type {new (options: TextPipelineConstructorArgs) => TextGenerationPipelineType} */ (
919+ Pipeline
920+ )
921+{
922+ /**
923+ * Create a new TextGenerationPipeline.
924+ * @param {TextPipelineConstructorArgs} options An object used to instantiate the pipeline.
925+ */
926+ constructor(options) {
927+ super(options);
928+ }
929+
930+ /** @type {TextGenerationPipelineCallback} */
931+ async _call(texts, generate_kwargs = {}) {
932+ const isBatched = Array.isArray(texts);
933+ if (!isBatched) {
934+ texts = [/** @type {string}*/ (texts)];
919935 }
920936
921- /** @type {TextGenerationPipelineCallback} */
922- async _call(texts, generate_kwargs = {}) {
923-
924- const isBatched = Array.isArray(texts);
925- if (!isBatched) {
926- texts = [/** @type {string}*/ (texts)];
927- }
928-
929- // By default, do not add special tokens
930- const add_special_tokens = generate_kwargs.add_special_tokens ?? false;
931-
932- this.tokenizer.padding_side = 'left';
933- const { input_ids, attention_mask } = this.tokenizer(texts, {
934- add_special_tokens,
935- padding: true,
936- truncation: true,
937- });
938-
939- const outputTokenIds = await this.model.generate(input_ids, generate_kwargs, null, {
940- inputs_attention_mask: attention_mask
941- });
937+ // By default, do not add special tokens
938+ const add_special_tokens = generate_kwargs.add_special_tokens ?? false;
939+
940+ this.tokenizer.padding_side = "left";
941+ const { input_ids, attention_mask } = this.tokenizer(texts, {
942+ add_special_tokens,
943+ padding: true,
944+ truncation: true,
945+ });
942946
943- const decoded = this.tokenizer.batch_decode(outputTokenIds, {
944- skip_special_tokens: true,
945- });
947+ const outputTokenIds = await this.model.generate(
948+ input_ids,
949+ generate_kwargs,
950+ null,
951+ {
952+ inputs_attention_mask: attention_mask,
953+ },
954+ );
955+
956+ const decoded = this.tokenizer.batch_decode(outputTokenIds, {
957+ skip_special_tokens: true,
958+ });
946959
947- /** @type {TextGenerationOutput[]} */
948- const toReturn = Array.from({ length: texts.length }, _ => []);
949- for (let i = 0; i < decoded.length; ++i) {
950- const textIndex = Math.floor(i / outputTokenIds.length * texts.length);
951-
952- toReturn[textIndex].push({
953- generated_text: decoded[i]
954- });
955- }
956- return (!isBatched && toReturn.length === 1) ? toReturn[0] : toReturn;
960+ /** @type {TextGenerationOutput[]} */
961+ const toReturn = Array.from({ length: texts.length }, (_) => []);
962+ for (let i = 0; i < decoded.length; ++i) {
963+ const textIndex = Math.floor((i / outputTokenIds.length) * texts.length);
964+
965+ toReturn[textIndex].push({
966+ generated_text: decoded[i],
967+ });
957968 }
969+ return !isBatched && toReturn.length === 1 ? toReturn[0] : toReturn;
970+ }
958971 }
959972
960973 /**
@@ -962,7 +975,7 @@
962975 * @property {string} sequence The sequence for which this is the output.
963976 * @property {string[]} labels The labels sorted by order of likelihood.
964977 * @property {number[]} scores The probabilities for each of the labels.
965- *
978+ *
966979 * @typedef {Object} ZeroShotClassificationPipelineOptions Parameters specific to zero-shot classification pipelines.
967980 * @property {string} [hypothesis_template="This example is {}."] The template used to turn each
968981 * candidate label into an NLI-style hypothesis. The candidate label will replace the {} placeholder.
@@ -970,14 +983,14 @@
970983 * If `false`, the scores are normalized such that the sum of the label likelihoods for each sequence
971984 * is 1. If `true`, the labels are considered independent and probabilities are normalized for each
972985 * candidate by doing a softmax of the entailment score vs. the contradiction score.
973- *
986+ *
974987 * @callback ZeroShotClassificationPipelineCallback Classify the sequence(s) given as inputs.
975988 * @param {string|string[]} texts The sequence(s) to classify, will be truncated if the model input is too large.
976989 * @param {string|string[]} candidate_labels The set of possible class labels to classify each sequence into.
977990 * Can be a single label, a string of comma-separated labels, or a list of labels.
978991 * @param {ZeroShotClassificationPipelineOptions} [options] The options to use for zero-shot classification.
979992 * @returns {Promise<ZeroShotClassificationOutput|ZeroShotClassificationOutput[]>} An array or object containing the predicted labels and scores.
980- *
993+ *
981994 * @typedef {TextPipelineConstructorArgs & ZeroShotClassificationPipelineCallback & Disposable} ZeroShotClassificationPipelineType
982995 */
983996
@@ -986,7 +999,7 @@
986999 * trained on NLI (natural language inference) tasks. Equivalent of `text-classification`
9871000 * pipelines, but these models don't require a hardcoded number of potential classes, they
9881001 * can be chosen at runtime. It usually means it's slower but it is **much** more flexible.
989- *
1002+ *
9901003 * **Example:** Zero shot classification with `Xenova/mobilebert-uncased-mnli`.
9911004 * ```javascript
9921005 * const classifier = await pipeline('zero-shot-classification', 'Xenova/mobilebert-uncased-mnli');
@@ -999,7 +1012,7 @@
9991012 * // scores: [ 0.5562091040482018, 0.1843621307860853, 0.13942646639336376, 0.12000229877234923 ]
10001013 * // }
10011014 * ```
1002- *
1015+ *
10031016 * **Example:** Zero shot classification with `Xenova/nli-deberta-v3-xsmall` (multi-label).
10041017 * ```javascript
10051018 * const classifier = await pipeline('zero-shot-classification', 'Xenova/nli-deberta-v3-xsmall');
@@ -1013,118 +1026,127 @@
10131026 * // }
10141027 * ```
10151028 */
1016-export class ZeroShotClassificationPipeline extends (/** @type {new (options: TextPipelineConstructorArgs) => ZeroShotClassificationPipelineType} */ (Pipeline)) {
1017- /**
1018- * Create a new ZeroShotClassificationPipeline.
1019- * @param {TextPipelineConstructorArgs} options An object used to instantiate the pipeline.
1020- */
1021- constructor(options) {
1022- super(options);
1023-
1024- // Use model config to get label2id mapping
1025- this.label2id = Object.fromEntries(
1026- Object.entries((/** @type {any} */(this).model).config.label2id).map(
1027- ([k, v]) => [k.toLowerCase(), v]
1028- )
1029- );
1030-
1031- this.entailment_id = this.label2id['entailment'];
1032- if (this.entailment_id === undefined) {
1033- console.warn("Could not find 'entailment' in label2id mapping. Using 2 as entailment_id.");
1034- this.entailment_id = 2;
1035- }
1036-
1037- this.contradiction_id = this.label2id['contradiction'] ?? this.label2id['not_entailment'];
1038- if (this.contradiction_id === undefined) {
1039- console.warn("Could not find 'contradiction' in label2id mapping. Using 0 as contradiction_id.");
1040- this.contradiction_id = 0;
1041- }
1029+export class ZeroShotClassificationPipeline
1030+ extends /** @type {new (options: TextPipelineConstructorArgs) => ZeroShotClassificationPipelineType} */ (
1031+ Pipeline
1032+ )
1033+{
1034+ /**
1035+ * Create a new ZeroShotClassificationPipeline.
1036+ * @param {TextPipelineConstructorArgs} options An object used to instantiate the pipeline.
1037+ */
1038+ constructor(options) {
1039+ super(options);
1040+
1041+ // Use model config to get label2id mapping
1042+ this.label2id = Object.fromEntries(
1043+ Object.entries(/** @type {any} */ (this).model.config.label2id).map(
1044+ ([k, v]) => [k.toLowerCase(), v],
1045+ ),
1046+ );
1047+
1048+ this.entailment_id = this.label2id["entailment"];
1049+ if (this.entailment_id === undefined) {
1050+ console.warn(
1051+ "Could not find 'entailment' in label2id mapping. Using 2 as entailment_id.",
1052+ );
1053+ this.entailment_id = 2;
10421054 }
10431055
1044- /** @type {ZeroShotClassificationPipelineCallback} */
1045- async _call(texts, candidate_labels, {
1046- hypothesis_template = "This example is {}.",
1047- multi_label = false,
1048- } = {}) {
1049-
1050- const isBatched = Array.isArray(texts);
1051- if (!isBatched) {
1052- texts = [/** @type {string} */ (texts)];
1053- }
1054- if (!Array.isArray(candidate_labels)) {
1055- candidate_labels = [candidate_labels];
1056- }
1056+ this.contradiction_id =
1057+ this.label2id["contradiction"] ?? this.label2id["not_entailment"];
1058+ if (this.contradiction_id === undefined) {
1059+ console.warn(
1060+ "Could not find 'contradiction' in label2id mapping. Using 0 as contradiction_id.",
1061+ );
1062+ this.contradiction_id = 0;
1063+ }
1064+ }
1065+
1066+ /** @type {ZeroShotClassificationPipelineCallback} */
1067+ async _call(
1068+ texts,
1069+ candidate_labels,
1070+ { hypothesis_template = "This example is {}.", multi_label = false } = {},
1071+ ) {
1072+ const isBatched = Array.isArray(texts);
1073+ if (!isBatched) {
1074+ texts = [/** @type {string} */ (texts)];
1075+ }
1076+ if (!Array.isArray(candidate_labels)) {
1077+ candidate_labels = [candidate_labels];
1078+ }
10571079
1058- // Insert labels into hypothesis template
1059- const hypotheses = candidate_labels.map(
1060- x => hypothesis_template.replace('{}', x)
1061- );
1080+ // Insert labels into hypothesis template
1081+ const hypotheses = candidate_labels.map((x) =>
1082+ hypothesis_template.replace("{}", x),
1083+ );
1084+
1085+ // How to perform the softmax over the logits:
1086+ // - true: softmax over the entailment vs. contradiction dim for each label independently
1087+ // - false: softmax the "entailment" logits over all candidate labels
1088+ const softmaxEach = multi_label || candidate_labels.length === 1;
1089+
1090+ /** @type {ZeroShotClassificationOutput[]} */
1091+ const toReturn = [];
1092+ for (const premise of texts) {
1093+ const entails_logits = [];
1094+
1095+ for (const hypothesis of hypotheses) {
1096+ const inputs = this.tokenizer(premise, {
1097+ text_pair: hypothesis,
1098+ padding: true,
1099+ truncation: true,
1100+ });
1101+ const outputs = await this.model(inputs);
10621102
1063- // How to perform the softmax over the logits:
1064- // - true: softmax over the entailment vs. contradiction dim for each label independently
1065- // - false: softmax the "entailment" logits over all candidate labels
1066- const softmaxEach = multi_label || candidate_labels.length === 1;
1067-
1068- /** @type {ZeroShotClassificationOutput[]} */
1069- const toReturn = [];
1070- for (const premise of texts) {
1071- const entails_logits = [];
1072-
1073- for (const hypothesis of hypotheses) {
1074- const inputs = this.tokenizer(premise, {
1075- text_pair: hypothesis,
1076- padding: true,
1077- truncation: true,
1078- })
1079- const outputs = await this.model(inputs)
1080-
1081- if (softmaxEach) {
1082- entails_logits.push([
1083- outputs.logits.data[this.contradiction_id],
1084- outputs.logits.data[this.entailment_id]
1085- ])
1086- } else {
1087- entails_logits.push(outputs.logits.data[this.entailment_id])
1088- }
1089- }
1090-
1091- /** @type {number[]} */
1092- const scores = softmaxEach
1093- ? entails_logits.map(x => softmax(x)[1])
1094- : softmax(entails_logits);
1095-
1096- // Sort by scores (desc) and return scores with indices
1097- const scores_sorted = scores
1098- .map((x, i) => [x, i])
1099- .sort((a, b) => (b[0] - a[0]));
1100-
1101- toReturn.push({
1102- sequence: premise,
1103- labels: scores_sorted.map(x => candidate_labels[x[1]]),
1104- scores: scores_sorted.map(x => x[0]),
1105- });
1103+ if (softmaxEach) {
1104+ entails_logits.push([
1105+ outputs.logits.data[this.contradiction_id],
1106+ outputs.logits.data[this.entailment_id],
1107+ ]);
1108+ } else {
1109+ entails_logits.push(outputs.logits.data[this.entailment_id]);
11061110 }
1107- return isBatched ? toReturn : toReturn[0];
1111+ }
1112+
1113+ /** @type {number[]} */
1114+ const scores = softmaxEach
1115+ ? entails_logits.map((x) => softmax(x)[1])
1116+ : softmax(entails_logits);
1117+
1118+ // Sort by scores (desc) and return scores with indices
1119+ const scores_sorted = scores
1120+ .map((x, i) => [x, i])
1121+ .sort((a, b) => b[0] - a[0]);
1122+
1123+ toReturn.push({
1124+ sequence: premise,
1125+ labels: scores_sorted.map((x) => candidate_labels[x[1]]),
1126+ scores: scores_sorted.map((x) => x[0]),
1127+ });
11081128 }
1129+ return isBatched ? toReturn : toReturn[0];
1130+ }
11091131 }
11101132
11111133 /**
11121134 * @typedef {Object} FeatureExtractionPipelineOptions Parameters specific to feature extraction pipelines.
11131135 * @property {'none'|'mean'|'cls'} [pooling="none"] The pooling method to use.
11141136 * @property {boolean} [normalize=false] Whether or not to normalize the embeddings in the last dimension.
1115- *
1137+ *
11161138 * @callback FeatureExtractionPipelineCallback Extract the features of the input(s).
11171139 * @param {string|string[]} texts One or several texts (or one list of texts) to get the features of.
11181140 * @param {FeatureExtractionPipelineOptions} [options] The options to use for feature extraction.
11191141 * @returns {Promise<Tensor>} The features computed by the model.
1120- *
1142+ *
11211143 * @typedef {TextPipelineConstructorArgs & FeatureExtractionPipelineCallback & Disposable} FeatureExtractionPipelineType
11221144 */
11231145
11241146 /**
11251147 * Feature extraction pipeline using no model head. This pipeline extracts the hidden
11261148 * states from the base transformer, which can be used as features in downstream tasks.
1127- *
1149+ *
11281150 * **Example:** Run feature extraction with `bert-base-uncased` (without pooling/normalization).
11291151 * ```javascript
11301152 * const extractor = await pipeline('feature-extraction', 'Xenova/bert-base-uncased', { revision: 'default' });
@@ -1135,7 +1157,7 @@
11351157 * // dims: [1, 8, 768]
11361158 * // }
11371159 * ```
1138- *
1160+ *
11391161 * **Example:** Run feature extraction with `bert-base-uncased` (with pooling/normalization).
11401162 * ```javascript
11411163 * const extractor = await pipeline('feature-extraction', 'Xenova/bert-base-uncased', { revision: 'default' });
@@ -1146,7 +1168,7 @@
11461168 * // dims: [1, 768]
11471169 * // }
11481170 * ```
1149- *
1171+ *
11501172 * **Example:** Calculating embeddings with `sentence-transformers` models.
11511173 * ```javascript
11521174 * const extractor = await pipeline('feature-extraction', 'Xenova/all-MiniLM-L6-v2');
@@ -1158,53 +1180,56 @@
11581180 * // }
11591181 * ```
11601182 */
1161-export class FeatureExtractionPipeline extends (/** @type {new (options: TextPipelineConstructorArgs) => FeatureExtractionPipelineType} */ (Pipeline)) {
1162- /**
1163- * Create a new FeatureExtractionPipeline.
1164- * @param {TextPipelineConstructorArgs} options An object used to instantiate the pipeline.
1165- */
1166- constructor(options) {
1167- super(options);
1168- }
1169-
1170- /** @type {FeatureExtractionPipelineCallback} */
1171- async _call(texts, {
1172- pooling = /** @type {'none'} */('none'),
1173- normalize = false,
1174- } = {}) {
1175-
1176- // Run tokenization
1177- const model_inputs = this.tokenizer(texts, {
1178- padding: true,
1179- truncation: true,
1180- });
1181-
1182- // Run model
1183- const outputs = await this.model(model_inputs)
1184-
1185- // TODO: Provide warning to the user that they might be using model which was not exported
1186- // specifically for feature extraction
1187- // console.log(this.model.config)
1188- // console.log(outputs)
1189-
1190- /** @type {Tensor} */
1191- let result = outputs.last_hidden_state ?? outputs.logits;
1192- if (pooling === 'none') {
1193- // Skip pooling
1194- } else if (pooling === 'mean') {
1195- result = mean_pooling(result, model_inputs.attention_mask);
1196- } else if (pooling === 'cls') {
1197- result = result.slice(null, 0);
1198- } else {
1199- throw Error(`Pooling method '${pooling}' not supported.`);
1200- }
1183+export class FeatureExtractionPipeline
1184+ extends /** @type {new (options: TextPipelineConstructorArgs) => FeatureExtractionPipelineType} */ (
1185+ Pipeline
1186+ )
1187+{
1188+ /**
1189+ * Create a new FeatureExtractionPipeline.
1190+ * @param {TextPipelineConstructorArgs} options An object used to instantiate the pipeline.
1191+ */
1192+ constructor(options) {
1193+ super(options);
1194+ }
1195+
1196+ /** @type {FeatureExtractionPipelineCallback} */
1197+ async _call(
1198+ texts,
1199+ { pooling = /** @type {'none'} */ ("none"), normalize = false } = {},
1200+ ) {
1201+ // Run tokenization
1202+ const model_inputs = this.tokenizer(texts, {
1203+ padding: true,
1204+ truncation: true,
1205+ });
12011206
1202- if (normalize) {
1203- result = result.normalize(2, -1);
1204- }
1207+ // Run model
1208+ const outputs = await this.model(model_inputs);
1209+
1210+ // TODO: Provide warning to the user that they might be using model which was not exported
1211+ // specifically for feature extraction
1212+ // console.log(this.model.config)
1213+ // console.log(outputs)
1214+
1215+ /** @type {Tensor} */
1216+ let result = outputs.last_hidden_state ?? outputs.logits;
1217+ if (pooling === "none") {
1218+ // Skip pooling
1219+ } else if (pooling === "mean") {
1220+ result = mean_pooling(result, model_inputs.attention_mask);
1221+ } else if (pooling === "cls") {
1222+ result = result.slice(null, 0);
1223+ } else {
1224+ throw Error(`Pooling method '${pooling}' not supported.`);
1225+ }
12051226
1206- return result;
1227+ if (normalize) {
1228+ result = result.normalize(2, -1);
12071229 }
1230+
1231+ return result;
1232+ }
12081233 }
12091234
12101235 // TODO
@@ -1216,12 +1241,12 @@
12161241 * @property {string} label The label predicted.
12171242 * @property {number} score The corresponding probability.
12181243 * @typedef {AudioClassificationSingle[]} AudioClassificationOutput
1219- *
1244+ *
12201245 * @typedef {Object} AudioClassificationPipelineOptions Parameters specific to audio classification pipelines.
12211246 * @property {number} [topk=null] The number of top labels that will be returned by the pipeline.
12221247 * If the provided number is `null` or higher than the number of labels available in the model configuration,
12231248 * it will default to the number of labels.
1224- *
1249+ *
12251250 * @callback AudioClassificationPipelineCallback Classify the sequence(s) given as inputs.
12261251 * @param {AudioPipelineInputs} audio The input audio file(s) to be classified. The input is either:
12271252 * - `string` or `URL` that is the filename/URL of the audio file, the file will be read at the processor's sampling rate
@@ -1230,14 +1255,14 @@
12301255 * - `Float32Array` or `Float64Array` of shape `(n, )`, representing the raw audio at the correct sampling rate (no further check will be done).
12311256 * @param {AudioClassificationPipelineOptions} [options] The options to use for audio classification.
12321257 * @returns {Promise<AudioClassificationOutput|AudioClassificationOutput[]>} An array or object containing the predicted labels and scores.
1233- *
1258+ *
12341259 * @typedef {AudioPipelineConstructorArgs & AudioClassificationPipelineCallback & Disposable} AudioClassificationPipelineType
12351260 */
12361261
12371262 /**
12381263 * Audio classification pipeline using any `AutoModelForAudioClassification`.
12391264 * This pipeline predicts the class of a raw waveform or an audio file.
1240- *
1265+ *
12411266 * **Example:** Perform audio classification with `Xenova/wav2vec2-large-xlsr-53-gender-recognition-librispeech`.
12421267 * ```javascript
12431268 * const classifier = await pipeline('audio-classification', 'Xenova/wav2vec2-large-xlsr-53-gender-recognition-librispeech');
@@ -1248,7 +1273,7 @@
12481273 * // { label: 'female', score: 0.001845747814513743 }
12491274 * // ]
12501275 * ```
1251- *
1276+ *
12521277 * **Example:** Perform audio classification with `Xenova/ast-finetuned-audioset-10-10-0.4593` and return top 4 results.
12531278 * ```javascript
12541279 * const classifier = await pipeline('audio-classification', 'Xenova/ast-finetuned-audioset-10-10-0.4593');
@@ -1262,61 +1287,63 @@
12621287 * // ]
12631288 * ```
12641289 */
1265-export class AudioClassificationPipeline extends (/** @type {new (options: AudioPipelineConstructorArgs) => AudioClassificationPipelineType} */ (Pipeline)) {
1266-
1267- /**
1268- * Create a new AudioClassificationPipeline.
1269- * @param {AudioPipelineConstructorArgs} options An object used to instantiate the pipeline.
1270- */
1271- constructor(options) {
1272- super(options);
1273- }
1274-
1275- /** @type {AudioClassificationPipelineCallback} */
1276- async _call(audio, {
1277- topk = null
1278- } = {}) {
1279-
1280- const single = !Array.isArray(audio);
1281-
1282- const sampling_rate = this.processor.feature_extractor.config.sampling_rate;
1283- const preparedAudios = await prepareAudios(audio, sampling_rate);
1284-
1285- const id2label = this.model.config.id2label;
1286-
1287- const toReturn = [];
1288- for (const aud of preparedAudios) {
1289- const inputs = await this.processor(aud);
1290- const output = await this.model(inputs);
1291- const logits = output.logits[0];
1292-
1293- const scores = getTopItems(softmax(logits.data), topk);
1294-
1295- const vals = scores.map(x => ({
1296- label: /** @type {string} */ (id2label[x[0]]),
1297- score: /** @type {number} */ (x[1]),
1298- }));
1299-
1300- if (topk === 1) {
1301- toReturn.push(...vals);
1302- } else {
1303- toReturn.push(vals);
1304- }
1305- }
1306- return !single || topk === 1 ? /** @type {AudioClassificationOutput} */ (toReturn) : /** @type {AudioClassificationOutput[]} */ (toReturn)[0];
1290+export class AudioClassificationPipeline
1291+ extends /** @type {new (options: AudioPipelineConstructorArgs) => AudioClassificationPipelineType} */ (
1292+ Pipeline
1293+ )
1294+{
1295+ /**
1296+ * Create a new AudioClassificationPipeline.
1297+ * @param {AudioPipelineConstructorArgs} options An object used to instantiate the pipeline.
1298+ */
1299+ constructor(options) {
1300+ super(options);
1301+ }
1302+
1303+ /** @type {AudioClassificationPipelineCallback} */
1304+ async _call(audio, { topk = null } = {}) {
1305+ const single = !Array.isArray(audio);
1306+
1307+ const sampling_rate = this.processor.feature_extractor.config.sampling_rate;
1308+ const preparedAudios = await prepareAudios(audio, sampling_rate);
1309+
1310+ const id2label = this.model.config.id2label;
1311+
1312+ const toReturn = [];
1313+ for (const aud of preparedAudios) {
1314+ const inputs = await this.processor(aud);
1315+ const output = await this.model(inputs);
1316+ const logits = output.logits[0];
1317+
1318+ const scores = getTopItems(softmax(logits.data), topk);
1319+
1320+ const vals = scores.map((x) => ({
1321+ label: /** @type {string} */ (id2label[x[0]]),
1322+ score: /** @type {number} */ (x[1]),
1323+ }));
1324+
1325+ if (topk === 1) {
1326+ toReturn.push(...vals);
1327+ } else {
1328+ toReturn.push(vals);
1329+ }
13071330 }
1331+ return !single || topk === 1
1332+ ? /** @type {AudioClassificationOutput} */ (toReturn)
1333+ : /** @type {AudioClassificationOutput[]} */ (toReturn)[0];
1334+ }
13081335 }
13091336
13101337 /**
13111338 * @typedef {Object} ZeroShotAudioClassificationOutput
13121339 * @property {string} label The label identified by the model. It is one of the suggested `candidate_label`.
13131340 * @property {number} score The score attributed by the model for that label (between 0 and 1).
1314- *
1341+ *
13151342 * @typedef {Object} ZeroShotAudioClassificationPipelineOptions Parameters specific to zero-shot audio classification pipelines.
13161343 * @property {string} [hypothesis_template="This is a sound of {}."] The sentence used in conjunction with `candidate_labels`
13171344 * to attempt the audio classification by replacing the placeholder with the candidate_labels.
13181345 * Then likelihood is estimated by using `logits_per_audio`.
1319- *
1346+ *
13201347 * @callback ZeroShotAudioClassificationPipelineCallback Classify the sequence(s) given as inputs.
13211348 * @param {AudioPipelineInputs} audio The input audio file(s) to be classified. The input is either:
13221349 * - `string` or `URL` that is the filename/URL of the audio file, the file will be read at the processor's sampling rate
@@ -1326,14 +1353,14 @@
13261353 * @param {string[]} candidate_labels The candidate labels for this audio.
13271354 * @param {ZeroShotAudioClassificationPipelineOptions} [options] The options to use for zero-shot audio classification.
13281355 * @returns {Promise<ZeroShotAudioClassificationOutput[]|ZeroShotAudioClassificationOutput[][]>} An array of objects containing the predicted labels and scores.
1329- *
1356+ *
13301357 * @typedef {TextAudioPipelineConstructorArgs & ZeroShotAudioClassificationPipelineCallback & Disposable} ZeroShotAudioClassificationPipelineType
13311358 */
13321359
13331360 /**
13341361 * Zero shot audio classification pipeline using `ClapModel`. This pipeline predicts the class of an audio when you
13351362 * provide an audio and a set of `candidate_labels`.
1336- *
1363+ *
13371364 * **Example**: Perform zero-shot audio classification with `Xenova/clap-htsat-unfused`.
13381365 * ```javascript
13391366 * const classifier = await pipeline('zero-shot-audio-classification', 'Xenova/clap-htsat-unfused');
@@ -1346,57 +1373,63 @@
13461373 * // ]
13471374 * ```
13481375 */
1349-export class ZeroShotAudioClassificationPipeline extends (/** @type {new (options: TextAudioPipelineConstructorArgs) => ZeroShotAudioClassificationPipelineType} */ (Pipeline)) {
1350-
1351- /**
1352- * Create a new ZeroShotAudioClassificationPipeline.
1353- * @param {TextAudioPipelineConstructorArgs} options An object used to instantiate the pipeline.
1354- */
1355- constructor(options) {
1356- super(options);
1376+export class ZeroShotAudioClassificationPipeline
1377+ extends /** @type {new (options: TextAudioPipelineConstructorArgs) => ZeroShotAudioClassificationPipelineType} */ (
1378+ Pipeline
1379+ )
1380+{
1381+ /**
1382+ * Create a new ZeroShotAudioClassificationPipeline.
1383+ * @param {TextAudioPipelineConstructorArgs} options An object used to instantiate the pipeline.
1384+ */
1385+ constructor(options) {
1386+ super(options);
1387+ }
1388+
1389+ /** @type {ZeroShotAudioClassificationPipelineCallback} */
1390+ async _call(
1391+ audio,
1392+ candidate_labels,
1393+ { hypothesis_template = "This is a sound of {}." } = {},
1394+ ) {
1395+ const single = !Array.isArray(audio);
1396+ if (single) {
1397+ audio = [/** @type {AudioInput} */ (audio)];
13571398 }
13581399
1359- /** @type {ZeroShotAudioClassificationPipelineCallback} */
1360- async _call(audio, candidate_labels, {
1361- hypothesis_template = "This is a sound of {}."
1362- } = {}) {
1363-
1364- const single = !Array.isArray(audio);
1365- if (single) {
1366- audio = [/** @type {AudioInput} */ (audio)];
1367- }
1368-
1369- // Insert label into hypothesis template
1370- const texts = candidate_labels.map(
1371- x => hypothesis_template.replace('{}', x)
1372- );
1373-
1374- // Run tokenization
1375- const text_inputs = this.tokenizer(texts, {
1376- padding: true,
1377- truncation: true,
1378- });
1400+ // Insert label into hypothesis template
1401+ const texts = candidate_labels.map((x) =>
1402+ hypothesis_template.replace("{}", x),
1403+ );
1404+
1405+ // Run tokenization
1406+ const text_inputs = this.tokenizer(texts, {
1407+ padding: true,
1408+ truncation: true,
1409+ });
13791410
1380- const sampling_rate = this.processor.feature_extractor.config.sampling_rate;
1381- const preparedAudios = await prepareAudios(audio, sampling_rate);
1411+ const sampling_rate = this.processor.feature_extractor.config.sampling_rate;
1412+ const preparedAudios = await prepareAudios(audio, sampling_rate);
13821413
1383- const toReturn = [];
1384- for (const aud of preparedAudios) {
1385- const audio_inputs = await this.processor(aud);
1414+ const toReturn = [];
1415+ for (const aud of preparedAudios) {
1416+ const audio_inputs = await this.processor(aud);
13861417
1387- // Run model with both text and audio inputs
1388- const output = await this.model({ ...text_inputs, ...audio_inputs });
1418+ // Run model with both text and audio inputs
1419+ const output = await this.model({ ...text_inputs, ...audio_inputs });
13891420
1390- // Compute softmax per audio
1391- const probs = softmax(output.logits_per_audio.data);
1421+ // Compute softmax per audio
1422+ const probs = softmax(output.logits_per_audio.data);
13921423
1393- toReturn.push([...probs].map((x, i) => ({
1394- score: x,
1395- label: candidate_labels[i]
1396- })));
1397- }
1398- return single ? toReturn[0] : toReturn;
1424+ toReturn.push(
1425+ [...probs].map((x, i) => ({
1426+ score: x,
1427+ label: candidate_labels[i],
1428+ })),
1429+ );
13991430 }
1431+ return single ? toReturn[0] : toReturn;
1432+ }
14001433 }
14011434
14021435 /**
@@ -1416,7 +1449,7 @@
14161449 * @property {string} text The recognized text.
14171450 * @property {Chunk[]} [chunks] When using `return_timestamps`, the `chunks` will become a list
14181451 * containing all the various text chunks identified by the model.
1419- *
1452+ *
14201453 * @typedef {Object} AutomaticSpeechRecognitionSpecificParams Parameters specific to automatic-speech-recognition pipelines.
14211454 * @property {boolean|'word'} [kwargs.return_timestamps] Whether to return timestamps or not. Default is `false`.
14221455 * @property {number} [kwargs.chunk_length_s] The length of audio chunks to process in seconds. Default is 0 (no chunking).
@@ -1429,7 +1462,7 @@
14291462 * that will be forced before sampling. For example, [[1, 123]] means the second generated token will always be a token of index 123.
14301463 * @property {number} [num_frames] The number of frames in the input audio.
14311464 * @typedef {import('./utils/generation.js').GenerationConfigType & AutomaticSpeechRecognitionSpecificParams} AutomaticSpeechRecognitionConfig
1432- *
1465+ *
14331466 * @callback AutomaticSpeechRecognitionPipelineCallback Transcribe the audio sequence(s) given as inputs to text.
14341467 * @param {AudioPipelineInputs} audio The input audio file(s) to be transcribed. The input is either:
14351468 * - `string` or `URL` that is the filename/URL of the audio file, the file will be read at the processor's sampling rate
@@ -1438,7 +1471,7 @@
14381471 * - `Float32Array` or `Float64Array` of shape `(n, )`, representing the raw audio at the correct sampling rate (no further check will be done).
14391472 * @param {AutomaticSpeechRecognitionConfig} [options] Additional keyword arguments to pass along to the generate method of the model.
14401473 * @returns {Promise<AutomaticSpeechRecognitionOutput|AutomaticSpeechRecognitionOutput[]>} An object containing the transcription text and optionally timestamps if `return_timestamps` is `true`.
1441- *
1474+ *
14421475 * @typedef {TextAudioPipelineConstructorArgs & AutomaticSpeechRecognitionPipelineCallback & Disposable} AutomaticSpeechRecognitionPipelineType
14431476 */
14441477
@@ -1452,7 +1485,7 @@
14521485 * const output = await transcriber(url);
14531486 * // { text: " And so my fellow Americans ask not what your country can do for you, ask what you can do for your country." }
14541487 * ```
1455- *
1488+ *
14561489 * **Example:** Transcribe English w/ timestamps.
14571490 * ```javascript
14581491 * const transcriber = await pipeline('automatic-speech-recognition', 'Xenova/whisper-tiny.en');
@@ -1466,7 +1499,7 @@
14661499 * // ]
14671500 * // }
14681501 * ```
1469- *
1502+ *
14701503 * **Example:** Transcribe English w/ word-level timestamps.
14711504 * ```javascript
14721505 * const transcriber = await pipeline('automatic-speech-recognition', 'Xenova/whisper-tiny.en');
@@ -1485,7 +1518,7 @@
14851518 * // ]
14861519 * // }
14871520 * ```
1488- *
1521+ *
14891522 * **Example:** Transcribe French.
14901523 * ```javascript
14911524 * const transcriber = await pipeline('automatic-speech-recognition', 'Xenova/whisper-small');
@@ -1493,7 +1526,7 @@
14931526 * const output = await transcriber(url, { language: 'french', task: 'transcribe' });
14941527 * // { text: " J'adore, j'aime, je n'aime pas, je déteste." }
14951528 * ```
1496- *
1529+ *
14971530 * **Example:** Translate French to English.
14981531 * ```javascript
14991532 * const transcriber = await pipeline('automatic-speech-recognition', 'Xenova/whisper-small');
@@ -1501,7 +1534,7 @@
15011534 * const output = await transcriber(url, { language: 'french', task: 'translate' });
15021535 * // { text: " I love, I like, I don't like, I hate." }
15031536 * ```
1504- *
1537+ *
15051538 * **Example:** Transcribe/translate audio longer than 30 seconds.
15061539 * ```javascript
15071540 * const transcriber = await pipeline('automatic-speech-recognition', 'Xenova/whisper-tiny.en');
@@ -1510,208 +1543,224 @@
15101543 * // { text: " So in college, I was a government major, which means [...] So I'd start off light and I'd bump it up" }
15111544 * ```
15121545 */
1513-export class AutomaticSpeechRecognitionPipeline extends (/** @type {new (options: TextAudioPipelineConstructorArgs) => AutomaticSpeechRecognitionPipelineType} */ (Pipeline)) {
1514-
1515- /**
1516- * Create a new AutomaticSpeechRecognitionPipeline.
1517- * @param {TextAudioPipelineConstructorArgs} options An object used to instantiate the pipeline.
1518- */
1519- constructor(options) {
1520- super(options);
1546+export class AutomaticSpeechRecognitionPipeline
1547+ extends /** @type {new (options: TextAudioPipelineConstructorArgs) => AutomaticSpeechRecognitionPipelineType} */ (
1548+ Pipeline
1549+ )
1550+{
1551+ /**
1552+ * Create a new AutomaticSpeechRecognitionPipeline.
1553+ * @param {TextAudioPipelineConstructorArgs} options An object used to instantiate the pipeline.
1554+ */
1555+ constructor(options) {
1556+ super(options);
1557+ }
1558+
1559+ /** @type {AutomaticSpeechRecognitionPipelineCallback} */
1560+ async _call(audio, kwargs = {}) {
1561+ switch (this.model.config.model_type) {
1562+ case "whisper":
1563+ return this._call_whisper(audio, kwargs);
1564+ case "wav2vec2":
1565+ case "hubert":
1566+ return this._call_wav2vec2(audio, kwargs);
1567+ default:
1568+ throw new Error(
1569+ `AutomaticSpeechRecognitionPipeline does not support model type '${this.model.config.model_type}'.`,
1570+ );
1571+ }
1572+ }
1573+
1574+ /**
1575+ * @type {AutomaticSpeechRecognitionPipelineCallback}
1576+ * @private
1577+ */
1578+ async _call_wav2vec2(audio, kwargs = {}) {
1579+ // TODO use kwargs
1580+
1581+ if (kwargs.language) {
1582+ console.warn(
1583+ '`language` parameter is not yet supported for `wav2vec2` models, defaulting to "English".',
1584+ );
1585+ }
1586+ if (kwargs.task) {
1587+ console.warn(
1588+ '`task` parameter is not yet supported for `wav2vec2` models, defaulting to "transcribe".',
1589+ );
15211590 }
15221591
1523- /** @type {AutomaticSpeechRecognitionPipelineCallback} */
1524- async _call(audio, kwargs = {}) {
1525- switch (this.model.config.model_type) {
1526- case 'whisper':
1527- return this._call_whisper(audio, kwargs)
1528- case 'wav2vec2':
1529- case 'hubert':
1530- return this._call_wav2vec2(audio, kwargs)
1531- default:
1532- throw new Error(`AutomaticSpeechRecognitionPipeline does not support model type '${this.model.config.model_type}'.`)
1533- }
1592+ const single = !Array.isArray(audio);
1593+ if (single) {
1594+ audio = [/** @type {AudioInput} */ (audio)];
15341595 }
15351596
1536- /**
1537- * @type {AutomaticSpeechRecognitionPipelineCallback}
1538- * @private
1539- */
1540- async _call_wav2vec2(audio, kwargs = {}) {
1541- // TODO use kwargs
1542-
1543- if (kwargs.language) {
1544- console.warn('`language` parameter is not yet supported for `wav2vec2` models, defaulting to "English".');
1545- }
1546- if (kwargs.task) {
1547- console.warn('`task` parameter is not yet supported for `wav2vec2` models, defaulting to "transcribe".');
1548- }
1597+ const sampling_rate = this.processor.feature_extractor.config.sampling_rate;
1598+ const preparedAudios = await prepareAudios(audio, sampling_rate);
1599+
1600+ const toReturn = [];
1601+ for (const aud of preparedAudios) {
1602+ const inputs = await this.processor(aud);
1603+ const output = await this.model(inputs);
1604+ const logits = output.logits[0];
1605+
1606+ const predicted_ids = [];
1607+ for (const item of logits) {
1608+ predicted_ids.push(max(item.data)[1]);
1609+ }
1610+ const predicted_sentences = this.tokenizer.decode(predicted_ids);
1611+ toReturn.push({ text: predicted_sentences });
1612+ }
1613+ return single ? toReturn[0] : toReturn;
1614+ }
1615+
1616+ /**
1617+ * @type {AutomaticSpeechRecognitionPipelineCallback}
1618+ * @private
1619+ */
1620+ async _call_whisper(audio, kwargs = {}) {
1621+ const return_timestamps = kwargs.return_timestamps ?? false;
1622+ const chunk_length_s = kwargs.chunk_length_s ?? 0;
1623+ const chunk_callback = kwargs.chunk_callback ?? null;
1624+ const force_full_sequences = kwargs.force_full_sequences ?? false;
1625+ let stride_length_s = kwargs.stride_length_s ?? null;
1626+
1627+ if (return_timestamps === "word") {
1628+ kwargs["return_token_timestamps"] = true;
1629+ }
15491630
1550- const single = !Array.isArray(audio);
1551- if (single) {
1552- audio = [/** @type {AudioInput} */ (audio)];
1553- }
1631+ const language = pop(kwargs, "language", null);
1632+ const task = pop(kwargs, "task", null);
15541633
1555- const sampling_rate = this.processor.feature_extractor.config.sampling_rate;
1556- const preparedAudios = await prepareAudios(audio, sampling_rate);
1557-
1558- const toReturn = [];
1559- for (const aud of preparedAudios) {
1560- const inputs = await this.processor(aud);
1561- const output = await this.model(inputs);
1562- const logits = output.logits[0];
1563-
1564- const predicted_ids = [];
1565- for (const item of logits) {
1566- predicted_ids.push(max(item.data)[1])
1567- }
1568- const predicted_sentences = this.tokenizer.decode(predicted_ids)
1569- toReturn.push({ text: predicted_sentences })
1570- }
1571- return single ? toReturn[0] : toReturn;
1634+ if (language || task || return_timestamps) {
1635+ if (kwargs.forced_decoder_ids) {
1636+ throw new Error(
1637+ "Cannot specify `language`/`task`/`return_timestamps` and `forced_decoder_ids` at the same time.",
1638+ );
1639+ }
1640+ // @ts-ignore
1641+ const decoder_prompt_ids = this.tokenizer.get_decoder_prompt_ids({
1642+ language,
1643+ task,
1644+ no_timestamps: !return_timestamps,
1645+ });
1646+ if (decoder_prompt_ids.length > 0) {
1647+ kwargs.forced_decoder_ids = decoder_prompt_ids;
1648+ }
15721649 }
15731650
1574- /**
1575- * @type {AutomaticSpeechRecognitionPipelineCallback}
1576- * @private
1577- */
1578- async _call_whisper(audio, kwargs = {}) {
1579-
1580- const return_timestamps = kwargs.return_timestamps ?? false;
1581- const chunk_length_s = kwargs.chunk_length_s ?? 0;
1582- const chunk_callback = kwargs.chunk_callback ?? null;
1583- const force_full_sequences = kwargs.force_full_sequences ?? false;
1584- let stride_length_s = kwargs.stride_length_s ?? null;
1585-
1586- if (return_timestamps === 'word') {
1587- kwargs['return_token_timestamps'] = true;
1588- }
1651+ const single = !Array.isArray(audio);
1652+ if (single) {
1653+ audio = [/** @type {AudioInput} */ (audio)];
1654+ }
15891655
1590- const language = pop(kwargs, 'language', null);
1591- const task = pop(kwargs, 'task', null);
1592-
1593- if (language || task || return_timestamps) {
1594- if (kwargs.forced_decoder_ids) {
1595- throw new Error("Cannot specify `language`/`task`/`return_timestamps` and `forced_decoder_ids` at the same time.")
1596- }
1597- // @ts-ignore
1598- const decoder_prompt_ids = this.tokenizer.get_decoder_prompt_ids({ language, task, no_timestamps: !return_timestamps })
1599- if (decoder_prompt_ids.length > 0) {
1600- kwargs.forced_decoder_ids = decoder_prompt_ids;
1601- }
1656+ const time_precision =
1657+ this.processor.feature_extractor.config.chunk_length /
1658+ this.model.config.max_source_positions;
1659+ const hop_length = this.processor.feature_extractor.config.hop_length;
1660+
1661+ const sampling_rate = this.processor.feature_extractor.config.sampling_rate;
1662+ const preparedAudios = await prepareAudios(audio, sampling_rate);
1663+
1664+ const toReturn = [];
1665+ for (const aud of preparedAudios) {
1666+ /** @type {ChunkCallbackItem[]} */
1667+ let chunks = [];
1668+ if (chunk_length_s > 0) {
1669+ if (stride_length_s === null) {
1670+ stride_length_s = chunk_length_s / 6;
1671+ } else if (chunk_length_s <= stride_length_s) {
1672+ throw Error(
1673+ "`chunk_length_s` must be larger than `stride_length_s`.",
1674+ );
16021675 }
16031676
1604- const single = !Array.isArray(audio);
1605- if (single) {
1606- audio = [/** @type {AudioInput} */ (audio)];
1677+ // TODO support different stride_length_s (for left and right)
1678+
1679+ const window = sampling_rate * chunk_length_s;
1680+ const stride = sampling_rate * stride_length_s;
1681+ const jump = window - 2 * stride;
1682+ let offset = 0;
1683+
1684+ // Create subarrays of audio with overlaps
1685+
1686+ while (offset < aud.length) {
1687+ const subarr = aud.subarray(offset, offset + window);
1688+ const feature = await this.processor(subarr);
1689+
1690+ const isFirst = offset === 0;
1691+ const isLast = offset + jump >= aud.length;
1692+ chunks.push({
1693+ stride: [subarr.length, isFirst ? 0 : stride, isLast ? 0 : stride],
1694+ input_features: feature.input_features,
1695+ is_last: isLast,
1696+ });
1697+ offset += jump;
16071698 }
1699+ } else {
1700+ chunks = [
1701+ {
1702+ stride: [aud.length, 0, 0],
1703+ input_features: (await this.processor(aud)).input_features,
1704+ is_last: true,
1705+ },
1706+ ];
1707+ }
1708+
1709+ // Generate for each set of input features
1710+ for (const chunk of chunks) {
1711+ kwargs.num_frames = Math.floor(chunk.stride[0] / hop_length);
1712+
1713+ // NOTE: doing sequentially for now
1714+ const data = await this.model.generate(chunk.input_features, kwargs);
1715+
1716+ // TODO: Right now we only get top beam
1717+ if (return_timestamps === "word") {
1718+ chunk.tokens = data.sequences[0];
1719+ chunk.token_timestamps = data.token_timestamps
1720+ .tolist()[0]
1721+ .map((/** @type {number} */ x) => round(x, 2));
1722+ } else {
1723+ chunk.tokens = data[0];
1724+ }
1725+
1726+ // convert stride to seconds
1727+ chunk.stride = chunk.stride.map((x) => x / sampling_rate);
16081728
1609- const time_precision = this.processor.feature_extractor.config.chunk_length / this.model.config.max_source_positions;
1610- const hop_length = this.processor.feature_extractor.config.hop_length;
1611-
1612- const sampling_rate = this.processor.feature_extractor.config.sampling_rate;
1613- const preparedAudios = await prepareAudios(audio, sampling_rate);
1614-
1615- const toReturn = [];
1616- for (const aud of preparedAudios) {
1617- /** @type {ChunkCallbackItem[]} */
1618- let chunks = [];
1619- if (chunk_length_s > 0) {
1620- if (stride_length_s === null) {
1621- stride_length_s = chunk_length_s / 6;
1622- } else if (chunk_length_s <= stride_length_s) {
1623- throw Error("`chunk_length_s` must be larger than `stride_length_s`.")
1624- }
1625-
1626- // TODO support different stride_length_s (for left and right)
1627-
1628- const window = sampling_rate * chunk_length_s;
1629- const stride = sampling_rate * stride_length_s;
1630- const jump = window - 2 * stride;
1631- let offset = 0;
1632-
1633- // Create subarrays of audio with overlaps
1634-
1635- while (offset < aud.length) {
1636- const subarr = aud.subarray(offset, offset + window);
1637- const feature = await this.processor(subarr);
1638-
1639- const isFirst = offset === 0;
1640- const isLast = offset + jump >= aud.length;
1641- chunks.push({
1642- stride: [
1643- subarr.length,
1644- isFirst ? 0 : stride,
1645- isLast ? 0 : stride
1646- ],
1647- input_features: feature.input_features,
1648- is_last: isLast
1649- })
1650- offset += jump;
1651- }
1652-
1653- } else {
1654- chunks = [{
1655- stride: [aud.length, 0, 0],
1656- input_features: (await this.processor(aud)).input_features,
1657- is_last: true
1658- }]
1659- }
1660-
1661- // Generate for each set of input features
1662- for (const chunk of chunks) {
1663- kwargs.num_frames = Math.floor(chunk.stride[0] / hop_length);
1664-
1665- // NOTE: doing sequentially for now
1666- const data = await this.model.generate(chunk.input_features, kwargs);
1667-
1668- // TODO: Right now we only get top beam
1669- if (return_timestamps === 'word') {
1670- chunk.tokens = data.sequences[0];
1671- chunk.token_timestamps = data.token_timestamps.tolist()[0].map(
1672- (/** @type {number} */ x) => round(x, 2)
1673- );
1674-
1675- } else {
1676- chunk.tokens = data[0];
1677- }
1678-
1679- // convert stride to seconds
1680- chunk.stride = chunk.stride.map(x => x / sampling_rate);
1681-
1682- if (chunk_callback !== null) {
1683- chunk_callback(chunk)
1684- }
1685- }
1686-
1687- // Merge text chunks
1688- // @ts-ignore
1689- const [full_text, optional] = this.tokenizer._decode_asr(chunks, {
1690- time_precision, return_timestamps, force_full_sequences
1691- });
1692-
1693- toReturn.push({ text: full_text, ...optional })
1729+ if (chunk_callback !== null) {
1730+ chunk_callback(chunk);
16941731 }
1695- return single ? toReturn[0] : toReturn;
1732+ }
1733+
1734+ // Merge text chunks
1735+ // @ts-ignore
1736+ const [full_text, optional] = this.tokenizer._decode_asr(chunks, {
1737+ time_precision,
1738+ return_timestamps,
1739+ force_full_sequences,
1740+ });
1741+
1742+ toReturn.push({ text: full_text, ...optional });
16961743 }
1744+ return single ? toReturn[0] : toReturn;
1745+ }
16971746 }
16981747
16991748 /**
17001749 * @typedef {Object} ImageToTextSingle
17011750 * @property {string} generated_text The generated text.
17021751 * @typedef {ImageToTextSingle[]} ImageToTextOutput
1703- *
1752+ *
17041753 * @callback ImageToTextPipelineCallback Assign labels to the image(s) passed as inputs.
17051754 * @param {ImagePipelineInputs} texts The images to be captioned.
17061755 * @param {import('./utils/generation.js').GenerationConfigType} [options] Additional keyword arguments to pass along to the generate method of the model.
17071756 * @returns {Promise<ImageToTextOutput|ImageToTextOutput[]>} An object (or array of objects) containing the generated text(s).
1708- *
1757+ *
17091758 * @typedef {TextImagePipelineConstructorArgs & ImageToTextPipelineCallback & Disposable} ImageToTextPipelineType
17101759 */
17111760
17121761 /**
17131762 * Image To Text pipeline using a `AutoModelForVision2Seq`. This pipeline predicts a caption for a given image.
1714- *
1763+ *
17151764 * **Example:** Generate a caption for an image w/ `Xenova/vit-gpt2-image-captioning`.
17161765 * ```javascript
17171766 * const captioner = await pipeline('image-to-text', 'Xenova/vit-gpt2-image-captioning');
@@ -1719,7 +1768,7 @@
17191768 * const output = await captioner(url);
17201769 * // [{ generated_text: 'a cat laying on a couch with another cat' }]
17211770 * ```
1722- *
1771+ *
17231772 * **Example:** Optical Character Recognition (OCR) w/ `Xenova/trocr-small-handwritten`.
17241773 * ```javascript
17251774 * const captioner = await pipeline('image-to-text', 'Xenova/trocr-small-handwritten');
@@ -1728,36 +1777,40 @@
17281777 * // [{ generated_text: 'Mr. Brown commented icily.' }]
17291778 * ```
17301779 */
1731-export class ImageToTextPipeline extends (/** @type {new (options: TextImagePipelineConstructorArgs) => ImageToTextPipelineType} */ (Pipeline)) {
1732-
1733- /**
1734- * Create a new ImageToTextPipeline.
1735- * @param {TextImagePipelineConstructorArgs} options An object used to instantiate the pipeline.
1736- */
1737- constructor(options) {
1738- super(options);
1780+export class ImageToTextPipeline
1781+ extends /** @type {new (options: TextImagePipelineConstructorArgs) => ImageToTextPipelineType} */ (
1782+ Pipeline
1783+ )
1784+{
1785+ /**
1786+ * Create a new ImageToTextPipeline.
1787+ * @param {TextImagePipelineConstructorArgs} options An object used to instantiate the pipeline.
1788+ */
1789+ constructor(options) {
1790+ super(options);
1791+ }
1792+
1793+ /** @type {ImageToTextPipelineCallback} */
1794+ async _call(images, generate_kwargs = {}) {
1795+ const isBatched = Array.isArray(images);
1796+ const preparedImages = await prepareImages(images);
1797+
1798+ const { pixel_values } = await this.processor(preparedImages);
1799+
1800+ const toReturn = [];
1801+ for (const batch of pixel_values) {
1802+ batch.dims = [1, ...batch.dims];
1803+ const output = await this.model.generate(batch, generate_kwargs);
1804+ const decoded = this.tokenizer
1805+ .batch_decode(output, {
1806+ skip_special_tokens: true,
1807+ })
1808+ .map((x) => ({ generated_text: x.trim() }));
1809+ toReturn.push(decoded);
17391810 }
17401811
1741- /** @type {ImageToTextPipelineCallback} */
1742- async _call(images, generate_kwargs = {}) {
1743-
1744- const isBatched = Array.isArray(images);
1745- const preparedImages = await prepareImages(images);
1746-
1747- const { pixel_values } = await this.processor(preparedImages);
1748-
1749- const toReturn = [];
1750- for (const batch of pixel_values) {
1751- batch.dims = [1, ...batch.dims]
1752- const output = await this.model.generate(batch, generate_kwargs);
1753- const decoded = this.tokenizer.batch_decode(output, {
1754- skip_special_tokens: true,
1755- }).map(x => ({ generated_text: x.trim() }))
1756- toReturn.push(decoded);
1757- }
1758-
1759- return isBatched ? toReturn : toReturn[0];
1760- }
1812+ return isBatched ? toReturn : toReturn[0];
1813+ }
17611814 }
17621815
17631816 /**
@@ -1765,22 +1818,22 @@
17651818 * @property {string} label The label identified by the model.
17661819 * @property {number} score The score attributed by the model for that label.
17671820 * @typedef {ImageClassificationSingle[]} ImageClassificationOutput
1768- *
1821+ *
17691822 * @typedef {Object} ImageClassificationPipelineOptions Parameters specific to image classification pipelines.
1770- * @property {number} [topk=1] The number of top labels that will be returned by the pipeline.
1771- *
1823+ * @property {number} [topk=1] The number of top labels that will be returned by the pipeline.
1824+ *
17721825 * @callback ImageClassificationPipelineCallback Assign labels to the image(s) passed as inputs.
17731826 * @param {ImagePipelineInputs} images The input images(s) to be classified.
17741827 * @param {ImageClassificationPipelineOptions} [options] The options to use for image classification.
17751828 * @returns {Promise<ImageClassificationOutput|ImageClassificationOutput[]>} An array or object containing the predicted labels and scores.
1776- *
1829+ *
17771830 * @typedef {ImagePipelineConstructorArgs & ImageClassificationPipelineCallback & Disposable} ImageClassificationPipelineType
17781831 */
17791832
17801833 /**
17811834 * Image classification pipeline using any `AutoModelForImageClassification`.
17821835 * This pipeline predicts the class of an image.
1783- *
1836+ *
17841837 * **Example:** Classify an image.
17851838 * ```javascript
17861839 * const classifier = await pipeline('image-classification', 'Xenova/vit-base-patch16-224');
@@ -1790,7 +1843,7 @@
17901843 * // { label: 'tiger, Panthera tigris', score: 0.632695734500885 },
17911844 * // ]
17921845 * ```
1793- *
1846+ *
17941847 * **Example:** Classify an image and return top `n` classes.
17951848 * ```javascript
17961849 * const classifier = await pipeline('image-classification', 'Xenova/vit-base-patch16-224');
@@ -1802,7 +1855,7 @@
18021855 * // { label: 'lion, king of beasts, Panthera leo', score: 0.00045060308184474707 },
18031856 * // ]
18041857 * ```
1805- *
1858+ *
18061859 * **Example:** Classify an image and return all classes.
18071860 * ```javascript
18081861 * const classifier = await pipeline('image-classification', 'Xenova/vit-base-patch16-224');
@@ -1817,46 +1870,47 @@
18171870 * // ]
18181871 * ```
18191872 */
1820-export class ImageClassificationPipeline extends (/** @type {new (options: ImagePipelineConstructorArgs) => ImageClassificationPipelineType} */ (Pipeline)) {
1821-
1822- /**
1823- * Create a new ImageClassificationPipeline.
1824- * @param {ImagePipelineConstructorArgs} options An object used to instantiate the pipeline.
1825- */
1826- constructor(options) {
1827- super(options);
1828- }
1829-
1830- /** @type {ImageClassificationPipelineCallback} */
1831- async _call(images, {
1832- topk = 1
1833- } = {}) {
1834-
1835- const isBatched = Array.isArray(images);
1836- const preparedImages = await prepareImages(images);
1837-
1838- const { pixel_values } = await this.processor(preparedImages);
1839- const output = await this.model({ pixel_values });
1840-
1841- const id2label = this.model.config.id2label;
1842- const toReturn = [];
1843- for (const batch of output.logits) {
1844- const scores = getTopItems(softmax(batch.data), topk);
1845-
1846- const vals = scores.map(x => ({
1847- label: id2label[x[0]],
1848- score: x[1],
1849- }));
1850- if (topk === 1) {
1851- toReturn.push(...vals);
1852- } else {
1853- toReturn.push(vals);
1854- }
1855- }
1856-
1857- return isBatched || topk === 1 ? /** @type {ImageClassificationOutput} */ (toReturn) : /** @type {ImageClassificationOutput[]} */ (toReturn)[0];
1873+export class ImageClassificationPipeline
1874+ extends /** @type {new (options: ImagePipelineConstructorArgs) => ImageClassificationPipelineType} */ (
1875+ Pipeline
1876+ )
1877+{
1878+ /**
1879+ * Create a new ImageClassificationPipeline.
1880+ * @param {ImagePipelineConstructorArgs} options An object used to instantiate the pipeline.
1881+ */
1882+ constructor(options) {
1883+ super(options);
1884+ }
1885+
1886+ /** @type {ImageClassificationPipelineCallback} */
1887+ async _call(images, { topk = 1 } = {}) {
1888+ const isBatched = Array.isArray(images);
1889+ const preparedImages = await prepareImages(images);
1890+
1891+ const { pixel_values } = await this.processor(preparedImages);
1892+ const output = await this.model({ pixel_values });
1893+
1894+ const id2label = this.model.config.id2label;
1895+ const toReturn = [];
1896+ for (const batch of output.logits) {
1897+ const scores = getTopItems(softmax(batch.data), topk);
1898+
1899+ const vals = scores.map((x) => ({
1900+ label: id2label[x[0]],
1901+ score: x[1],
1902+ }));
1903+ if (topk === 1) {
1904+ toReturn.push(...vals);
1905+ } else {
1906+ toReturn.push(vals);
1907+ }
18581908 }
18591909
1910+ return isBatched || topk === 1
1911+ ? /** @type {ImageClassificationOutput} */ (toReturn)
1912+ : /** @type {ImageClassificationOutput[]} */ (toReturn)[0];
1913+ }
18601914 }
18611915
18621916 /**
@@ -1864,7 +1918,7 @@
18641918 * @property {string} label The label of the segment.
18651919 * @property {number|null} score The score of the segment.
18661920 * @property {RawImage} mask The mask of the segment.
1867- *
1921+ *
18681922 * @typedef {Object} ImageSegmentationPipelineOptions Parameters specific to image segmentation pipelines.
18691923 * @property {number} [threshold=0.5] Probability threshold to filter out predicted masks.
18701924 * @property {number} [mask_threshold=0.5] Threshold to use when turning the predicted masks into binary values.
@@ -1873,19 +1927,19 @@
18731927 * depending on model capabilities. If not set, the pipeline will attempt to resolve (in that order).
18741928 * @property {number[]} [label_ids_to_fuse=null] List of label ids to fuse. If not set, do not fuse any labels.
18751929 * @property {number[][]} [target_sizes=null] List of target sizes for the input images. If not set, use the original image sizes.
1876- *
1930+ *
18771931 * @callback ImageSegmentationPipelineCallback Segment the input images.
18781932 * @param {ImagePipelineInputs} images The input images.
18791933 * @param {ImageSegmentationPipelineOptions} [options] The options to use for image segmentation.
18801934 * @returns {Promise<ImageSegmentationPipelineOutput[]>} The annotated segments.
1881- *
1935+ *
18821936 * @typedef {ImagePipelineConstructorArgs & ImageSegmentationPipelineCallback & Disposable} ImageSegmentationPipelineType
18831937 */
18841938
18851939 /**
18861940 * Image segmentation pipeline using any `AutoModelForXXXSegmentation`.
18871941 * This pipeline predicts masks of objects and their classes.
1888- *
1942+ *
18891943 * **Example:** Perform image segmentation with `Xenova/detr-resnet-50-panoptic`.
18901944 * ```javascript
18911945 * const segmenter = await pipeline('image-segmentation', 'Xenova/detr-resnet-50-panoptic');
@@ -1897,139 +1951,152 @@
18971951 * // ]
18981952 * ```
18991953 */
1900-export class ImageSegmentationPipeline extends (/** @type {new (options: ImagePipelineConstructorArgs) => ImageSegmentationPipelineType} */ (Pipeline)) {
1901- /**
1902- * Create a new ImageSegmentationPipeline.
1903- * @param {ImagePipelineConstructorArgs} options An object used to instantiate the pipeline.
1904- */
1905- constructor(options) {
1906- super(options);
1907-
1908- this.subtasks_mapping = {
1909- // Mapping of subtasks to their corresponding post-processing function names.
1910- panoptic: 'post_process_panoptic_segmentation',
1911- instance: 'post_process_instance_segmentation',
1912- semantic: 'post_process_semantic_segmentation'
1913- }
1954+export class ImageSegmentationPipeline
1955+ extends /** @type {new (options: ImagePipelineConstructorArgs) => ImageSegmentationPipelineType} */ (
1956+ Pipeline
1957+ )
1958+{
1959+ /**
1960+ * Create a new ImageSegmentationPipeline.
1961+ * @param {ImagePipelineConstructorArgs} options An object used to instantiate the pipeline.
1962+ */
1963+ constructor(options) {
1964+ super(options);
1965+
1966+ this.subtasks_mapping = {
1967+ // Mapping of subtasks to their corresponding post-processing function names.
1968+ panoptic: "post_process_panoptic_segmentation",
1969+ instance: "post_process_instance_segmentation",
1970+ semantic: "post_process_semantic_segmentation",
1971+ };
1972+ }
1973+
1974+ /** @type {ImageSegmentationPipelineCallback} */
1975+ async _call(
1976+ images,
1977+ {
1978+ threshold = 0.5,
1979+ mask_threshold = 0.5,
1980+ overlap_mask_area_threshold = 0.8,
1981+ label_ids_to_fuse = null,
1982+ target_sizes = null,
1983+ subtask = null,
1984+ } = {},
1985+ ) {
1986+ const isBatched = Array.isArray(images);
1987+
1988+ if (isBatched && images.length !== 1) {
1989+ throw Error(
1990+ "Image segmentation pipeline currently only supports a batch size of 1.",
1991+ );
19141992 }
19151993
1916- /** @type {ImageSegmentationPipelineCallback} */
1917- async _call(images, {
1918- threshold = 0.5,
1919- mask_threshold = 0.5,
1920- overlap_mask_area_threshold = 0.8,
1921- label_ids_to_fuse = null,
1922- target_sizes = null,
1923- subtask = null,
1924- } = {}) {
1925- const isBatched = Array.isArray(images);
1926-
1927- if (isBatched && images.length !== 1) {
1928- throw Error("Image segmentation pipeline currently only supports a batch size of 1.");
1994+ const preparedImages = await prepareImages(images);
1995+ const imageSizes = preparedImages.map((x) => [x.height, x.width]);
1996+
1997+ const { pixel_values, pixel_mask } = await this.processor(preparedImages);
1998+ const output = await this.model({ pixel_values, pixel_mask });
1999+
2000+ let fn = null;
2001+ if (subtask !== null) {
2002+ fn = this.subtasks_mapping[subtask];
2003+ } else {
2004+ for (let [task, func] of Object.entries(this.subtasks_mapping)) {
2005+ if (func in this.processor.feature_extractor) {
2006+ fn = this.processor.feature_extractor[func].bind(
2007+ this.processor.feature_extractor,
2008+ );
2009+ subtask = task;
2010+ break;
19292011 }
2012+ }
2013+ }
19302014
1931- const preparedImages = await prepareImages(images);
1932- const imageSizes = preparedImages.map(x => [x.height, x.width]);
2015+ const id2label = this.model.config.id2label;
2016+
2017+ /** @type {ImageSegmentationPipelineOutput[]} */
2018+ const annotation = [];
2019+ if (subtask === "panoptic" || subtask === "instance") {
2020+ const processed = fn(
2021+ output,
2022+ threshold,
2023+ mask_threshold,
2024+ overlap_mask_area_threshold,
2025+ label_ids_to_fuse,
2026+ target_sizes ?? imageSizes, // TODO FIX?
2027+ )[0];
2028+
2029+ const segmentation = processed.segmentation;
2030+
2031+ for (const segment of processed.segments_info) {
2032+ const maskData = new Uint8ClampedArray(segmentation.data.length);
2033+ for (let i = 0; i < segmentation.data.length; ++i) {
2034+ if (segmentation.data[i] === segment.id) {
2035+ maskData[i] = 255;
2036+ }
2037+ }
19332038
1934- const { pixel_values, pixel_mask } = await this.processor(preparedImages);
1935- const output = await this.model({ pixel_values, pixel_mask });
2039+ // const mask = new RawImage(maskData, segmentation.dims[1], segmentation.dims[0], 1)
19362040
1937- let fn = null;
1938- if (subtask !== null) {
1939- fn = this.subtasks_mapping[subtask];
1940- } else {
1941- for (let [task, func] of Object.entries(this.subtasks_mapping)) {
1942- if (func in this.processor.feature_extractor) {
1943- fn = this.processor.feature_extractor[func].bind(this.processor.feature_extractor);
1944- subtask = task;
1945- break;
1946- }
1947- }
2041+ annotation.push({
2042+ score: segment.score,
2043+ label: id2label[segment.label_id],
2044+ // mask: mask
2045+ });
2046+ }
2047+ } else if (subtask === "semantic") {
2048+ const { segmentation, labels } = fn(
2049+ output,
2050+ target_sizes ?? imageSizes,
2051+ )[0];
2052+
2053+ for (const label of labels) {
2054+ const maskData = new Uint8ClampedArray(segmentation.data.length);
2055+ for (let i = 0; i < segmentation.data.length; ++i) {
2056+ if (segmentation.data[i] === label) {
2057+ maskData[i] = 255;
2058+ }
19482059 }
19492060
1950- const id2label = this.model.config.id2label;
1951-
1952- /** @type {ImageSegmentationPipelineOutput[]} */
1953- const annotation = [];
1954- if (subtask === 'panoptic' || subtask === 'instance') {
1955- const processed = fn(
1956- output,
1957- threshold,
1958- mask_threshold,
1959- overlap_mask_area_threshold,
1960- label_ids_to_fuse,
1961- target_sizes ?? imageSizes, // TODO FIX?
1962- )[0];
1963-
1964- const segmentation = processed.segmentation;
1965-
1966- for (const segment of processed.segments_info) {
1967- const maskData = new Uint8ClampedArray(segmentation.data.length);
1968- for (let i = 0; i < segmentation.data.length; ++i) {
1969- if (segmentation.data[i] === segment.id) {
1970- maskData[i] = 255;
1971- }
1972- }
1973-
1974- // const mask = new RawImage(maskData, segmentation.dims[1], segmentation.dims[0], 1)
1975-
1976- annotation.push({
1977- score: segment.score,
1978- label: id2label[segment.label_id],
1979- // mask: mask
1980- })
1981- }
1982-
1983- } else if (subtask === 'semantic') {
1984- const { segmentation, labels } = fn(output, target_sizes ?? imageSizes)[0];
1985-
1986- for (const label of labels) {
1987- const maskData = new Uint8ClampedArray(segmentation.data.length);
1988- for (let i = 0; i < segmentation.data.length; ++i) {
1989- if (segmentation.data[i] === label) {
1990- maskData[i] = 255;
1991- }
1992- }
1993-
1994- // const mask = new RawImage(maskData, segmentation.dims[1], segmentation.dims[0], 1);
1995-
1996- annotation.push({
1997- score: null,
1998- label: id2label[label],
1999- // mask: mask
2000- });
2001- }
2002- } else {
2003- throw Error(`Subtask ${subtask} not supported.`);
2004- }
2061+ // const mask = new RawImage(maskData, segmentation.dims[1], segmentation.dims[0], 1);
20052062
2006- return annotation;
2063+ annotation.push({
2064+ score: null,
2065+ label: id2label[label],
2066+ // mask: mask
2067+ });
2068+ }
2069+ } else {
2070+ throw Error(`Subtask ${subtask} not supported.`);
20072071 }
2072+
2073+ return annotation;
2074+ }
20082075 }
20092076
20102077 /**
20112078 * @typedef {Object} ZeroShotImageClassificationOutput
20122079 * @property {string} label The label identified by the model. It is one of the suggested `candidate_label`.
20132080 * @property {number} score The score attributed by the model for that label (between 0 and 1).
2014- *
2081+ *
20152082 * @typedef {Object} ZeroShotImageClassificationPipelineOptions Parameters specific to zero-shot image classification pipelines.
20162083 * @property {string} [hypothesis_template="This is a photo of {}"] The sentence used in conjunction with `candidate_labels`
20172084 * to attempt the image classification by replacing the placeholder with the candidate_labels.
20182085 * Then likelihood is estimated by using `logits_per_image`.
2019- *
2086+ *
20202087 * @callback ZeroShotImageClassificationPipelineCallback Assign labels to the image(s) passed as inputs.
20212088 * @param {ImagePipelineInputs} images The input images.
20222089 * @param {string[]} candidate_labels The candidate labels for this image.
20232090 * @param {ZeroShotImageClassificationPipelineOptions} [options] The options to use for zero-shot image classification.
20242091 * @returns {Promise<ZeroShotImageClassificationOutput[]|ZeroShotImageClassificationOutput[][]>} An array of objects containing the predicted labels and scores.
2025- *
2092+ *
20262093 * @typedef {TextImagePipelineConstructorArgs & ZeroShotImageClassificationPipelineCallback & Disposable} ZeroShotImageClassificationPipelineType
20272094 */
20282095
20292096 /**
20302097 * Zero shot image classification pipeline. This pipeline predicts the class of
20312098 * an image when you provide an image and a set of `candidate_labels`.
2032- *
2099+ *
20332100 * **Example:** Zero shot image classification w/ `Xenova/clip-vit-base-patch32`.
20342101 * ```javascript
20352102 * const classifier = await pipeline('zero-shot-image-classification', 'Xenova/clip-vit-base-patch32');
@@ -2042,63 +2109,67 @@
20422109 * // ]
20432110 * ```
20442111 */
2045-export class ZeroShotImageClassificationPipeline extends (/** @type {new (options: TextImagePipelineConstructorArgs) => ZeroShotImageClassificationPipelineType} */ (Pipeline)) {
2046- /**
2047- * Create a new ZeroShotImageClassificationPipeline.
2048- * @param {TextImagePipelineConstructorArgs} options An object used to instantiate the pipeline.
2049- */
2050- constructor(options) {
2051- super(options);
2052- }
2053-
2054- /** @type {ZeroShotImageClassificationPipelineCallback} */
2055- async _call(images, candidate_labels, {
2056- hypothesis_template = "This is a photo of {}"
2057- } = {}) {
2058-
2059- const isBatched = Array.isArray(images);
2060- const preparedImages = await prepareImages(images);
2061-
2062- // Insert label into hypothesis template
2063- const texts = candidate_labels.map(
2064- x => hypothesis_template.replace('{}', x)
2065- );
2066-
2067- // Run tokenization
2068- const text_inputs = this.tokenizer(texts, {
2069- padding: this.model.config.model_type === 'siglip' ? 'max_length' : true,
2070- truncation: true,
2071- });
2072-
2073- // Run processor
2074- const { pixel_values } = await this.processor(preparedImages);
2075-
2076- // Run model with both text and pixel inputs
2077- const output = await this.model({ ...text_inputs, pixel_values });
2078-
2079- const function_to_apply =
2080- this.model.config.model_type === 'siglip'
2081- ? batch => batch.sigmoid().data
2082- : batch => softmax(batch.data);
2083-
2084- // Compare each image with each candidate label
2085- const toReturn = [];
2086- for (const batch of output.logits_per_image) {
2087- // Compute softmax per image
2088- const probs = function_to_apply(batch);
2089-
2090- const result = [...probs].map((x, i) => ({
2091- score: x,
2092- label: candidate_labels[i]
2093- }));
2094- result.sort((a, b) => b.score - a.score); // sort by score in descending order
2095- toReturn.push(result);
2096- }
2112+export class ZeroShotImageClassificationPipeline
2113+ extends /** @type {new (options: TextImagePipelineConstructorArgs) => ZeroShotImageClassificationPipelineType} */ (
2114+ Pipeline
2115+ )
2116+{
2117+ /**
2118+ * Create a new ZeroShotImageClassificationPipeline.
2119+ * @param {TextImagePipelineConstructorArgs} options An object used to instantiate the pipeline.
2120+ */
2121+ constructor(options) {
2122+ super(options);
2123+ }
2124+
2125+ /** @type {ZeroShotImageClassificationPipelineCallback} */
2126+ async _call(
2127+ images,
2128+ candidate_labels,
2129+ { hypothesis_template = "This is a photo of {}" } = {},
2130+ ) {
2131+ const isBatched = Array.isArray(images);
2132+ const preparedImages = await prepareImages(images);
2133+
2134+ // Insert label into hypothesis template
2135+ const texts = candidate_labels.map((x) =>
2136+ hypothesis_template.replace("{}", x),
2137+ );
2138+
2139+ // Run tokenization
2140+ const text_inputs = this.tokenizer(texts, {
2141+ padding: this.model.config.model_type === "siglip" ? "max_length" : true,
2142+ truncation: true,
2143+ });
20972144
2098- return isBatched ? toReturn : toReturn[0];
2145+ // Run processor
2146+ const { pixel_values } = await this.processor(preparedImages);
2147+
2148+ // Run model with both text and pixel inputs
2149+ const output = await this.model({ ...text_inputs, pixel_values });
2150+
2151+ const function_to_apply =
2152+ this.model.config.model_type === "siglip"
2153+ ? (batch) => batch.sigmoid().data
2154+ : (batch) => softmax(batch.data);
2155+
2156+ // Compare each image with each candidate label
2157+ const toReturn = [];
2158+ for (const batch of output.logits_per_image) {
2159+ // Compute softmax per image
2160+ const probs = function_to_apply(batch);
2161+
2162+ const result = [...probs].map((x, i) => ({
2163+ score: x,
2164+ label: candidate_labels[i],
2165+ }));
2166+ result.sort((a, b) => b.score - a.score); // sort by score in descending order
2167+ toReturn.push(result);
20992168 }
2100-}
21012169
2170+ return isBatched ? toReturn : toReturn[0];
2171+ }
2172+}
21022173
21032174 /**
21042175 * @typedef {Object} ObjectDetectionPipelineSingle
@@ -2106,23 +2177,23 @@
21062177 * @property {number} score The score attributed by the model for that label.
21072178 * @property {BoundingBox} box The bounding box of detected object in image's original size, or as a percentage if `percentage` is set to true.
21082179 * @typedef {ObjectDetectionPipelineSingle[]} ObjectDetectionPipelineOutput
2109- *
2180+ *
21102181 * @typedef {Object} ObjectDetectionPipelineOptions Parameters specific to object detection pipelines.
21112182 * @property {number} [threshold=0.9] The threshold used to filter boxes by score.
21122183 * @property {boolean} [percentage=false] Whether to return the boxes coordinates in percentage (true) or in pixels (false).
2113- *
2184+ *
21142185 * @callback ObjectDetectionPipelineCallback Detect objects (bounding boxes & classes) in the image(s) passed as inputs.
21152186 * @param {ImagePipelineInputs} images The input images.
21162187 * @param {ObjectDetectionPipelineOptions} [options] The options to use for object detection.
2117- * @returns {Promise<ObjectDetectionPipelineOutput|ObjectDetectionPipelineOutput[]>} A list of objects or a list of list of objects.
2118- *
2188+ * @returns {Promise<ObjectDetectionPipelineOutput|ObjectDetectionPipelineOutput[]>} A list of objects or a list of list of objects.
2189+ *
21192190 * @typedef {ImagePipelineConstructorArgs & ObjectDetectionPipelineCallback & Disposable} ObjectDetectionPipelineType
21202191 */
21212192
21222193 /**
21232194 * Object detection pipeline using any `AutoModelForObjectDetection`.
21242195 * This pipeline predicts bounding boxes of objects and their classes.
2125- *
2196+ *
21262197 * **Example:** Run object-detection with `Xenova/detr-resnet-50`.
21272198 * ```javascript
21282199 * const detector = await pipeline('object-detection', 'Xenova/detr-resnet-50');
@@ -2141,81 +2212,88 @@
21412212 * // }]
21422213 * ```
21432214 */
2144-export class ObjectDetectionPipeline extends (/** @type {new (options: ImagePipelineConstructorArgs) => ObjectDetectionPipelineType} */ (Pipeline)) {
2145-
2146- /**
2147- * Create a new ObjectDetectionPipeline.
2148- * @param {ImagePipelineConstructorArgs} options An object used to instantiate the pipeline.
2149- */
2150- constructor(options) {
2151- super(options);
2215+export class ObjectDetectionPipeline
2216+ extends /** @type {new (options: ImagePipelineConstructorArgs) => ObjectDetectionPipelineType} */ (
2217+ Pipeline
2218+ )
2219+{
2220+ /**
2221+ * Create a new ObjectDetectionPipeline.
2222+ * @param {ImagePipelineConstructorArgs} options An object used to instantiate the pipeline.
2223+ */
2224+ constructor(options) {
2225+ super(options);
2226+ }
2227+
2228+ /** @type {ObjectDetectionPipelineCallback} */
2229+ async _call(images, { threshold = 0.9, percentage = false } = {}) {
2230+ const isBatched = Array.isArray(images);
2231+
2232+ if (isBatched && images.length !== 1) {
2233+ throw Error(
2234+ "Object detection pipeline currently only supports a batch size of 1.",
2235+ );
21522236 }
2237+ const preparedImages = await prepareImages(images);
21532238
2154- /** @type {ObjectDetectionPipelineCallback} */
2155- async _call(images, {
2156- threshold = 0.9,
2157- percentage = false,
2158- } = {}) {
2159-
2160- const isBatched = Array.isArray(images);
2161-
2162- if (isBatched && images.length !== 1) {
2163- throw Error("Object detection pipeline currently only supports a batch size of 1.");
2164- }
2165- const preparedImages = await prepareImages(images);
2166-
2167- const imageSizes = percentage ? null : preparedImages.map(x => [x.height, x.width]);
2168-
2169- const { pixel_values, pixel_mask } = await this.processor(preparedImages);
2170- const output = await this.model({ pixel_values, pixel_mask });
2239+ const imageSizes = percentage
2240+ ? null
2241+ : preparedImages.map((x) => [x.height, x.width]);
21712242
2172- // @ts-ignore
2173- const processed = this.processor.feature_extractor.post_process_object_detection(output, threshold, imageSizes);
2243+ const { pixel_values, pixel_mask } = await this.processor(preparedImages);
2244+ const output = await this.model({ pixel_values, pixel_mask });
21742245
2175- // Add labels
2176- const id2label = this.model.config.id2label;
2177-
2178- // Format output
2179- /** @type {ObjectDetectionPipelineOutput[]} */
2180- const result = processed.map(batch => (
2181- batch.boxes.map((box, i) => ({
2182- score: batch.scores[i],
2183- label: id2label[batch.classes[i]],
2184- box: get_bounding_box(box, !percentage),
2185- }))
2186- ))
2187-
2188- return isBatched ? result : result[0];
2189- }
2246+ // @ts-ignore
2247+ const processed =
2248+ this.processor.feature_extractor.post_process_object_detection(
2249+ output,
2250+ threshold,
2251+ imageSizes,
2252+ );
2253+
2254+ // Add labels
2255+ const id2label = this.model.config.id2label;
2256+
2257+ // Format output
2258+ /** @type {ObjectDetectionPipelineOutput[]} */
2259+ const result = processed.map((batch) =>
2260+ batch.boxes.map((box, i) => ({
2261+ score: batch.scores[i],
2262+ label: id2label[batch.classes[i]],
2263+ box: get_bounding_box(box, !percentage),
2264+ })),
2265+ );
2266+
2267+ return isBatched ? result : result[0];
2268+ }
21902269 }
21912270
2192-
21932271 /**
21942272 * @typedef {Object} ZeroShotObjectDetectionOutput
21952273 * @property {string} label Text query corresponding to the found object.
21962274 * @property {number} score Score corresponding to the object (between 0 and 1).
21972275 * @property {BoundingBox} box Bounding box of the detected object in image's original size, or as a percentage if `percentage` is set to true.
2198- *
2276+ *
21992277 * @typedef {Object} ZeroShotObjectDetectionPipelineOptions Parameters specific to zero-shot object detection pipelines.
22002278 * @property {number} [threshold=0.1] The probability necessary to make a prediction.
22012279 * @property {number} [topk=null] The number of top predictions that will be returned by the pipeline.
22022280 * If the provided number is `null` or higher than the number of predictions available, it will default
22032281 * to the number of predictions.
22042282 * @property {boolean} [percentage=false] Whether to return the boxes coordinates in percentage (true) or in pixels (false).
2205- *
2283+ *
22062284 * @callback ZeroShotObjectDetectionPipelineCallback Detect objects (bounding boxes & classes) in the image(s) passed as inputs.
22072285 * @param {ImagePipelineInputs} images The input images.
22082286 * @param {string[]} candidate_labels What the model should recognize in the image.
22092287 * @param {ZeroShotObjectDetectionPipelineOptions} [options] The options to use for zero-shot object detection.
22102288 * @returns {Promise<ZeroShotObjectDetectionOutput[]|ZeroShotObjectDetectionOutput[][]>} An array of objects containing the predicted labels, scores, and bounding boxes.
2211- *
2289+ *
22122290 * @typedef {TextImagePipelineConstructorArgs & ZeroShotObjectDetectionPipelineCallback & Disposable} ZeroShotObjectDetectionPipelineType
22132291 */
22142292
22152293 /**
22162294 * Zero-shot object detection pipeline. This pipeline predicts bounding boxes of
22172295 * objects when you provide an image and a set of `candidate_labels`.
2218- *
2296+ *
22192297 * **Example:** Zero-shot object detection w/ `Xenova/owlvit-base-patch32`.
22202298 * ```javascript
22212299 * const detector = await pipeline('zero-shot-object-detection', 'Xenova/owlvit-base-patch32');
@@ -2245,7 +2323,7 @@
22452323 * // }
22462324 * // ]
22472325 * ```
2248- *
2326+ *
22492327 * **Example:** Zero-shot object detection w/ `Xenova/owlvit-base-patch32` (returning top 4 matches and setting a threshold).
22502328 * ```javascript
22512329 * const detector = await pipeline('zero-shot-object-detection', 'Xenova/owlvit-base-patch32');
@@ -2276,75 +2354,85 @@
22762354 * // ]
22772355 * ```
22782356 */
2279-export class ZeroShotObjectDetectionPipeline extends (/** @type {new (options: TextImagePipelineConstructorArgs) => ZeroShotObjectDetectionPipelineType} */ (Pipeline)) {
2280-
2281- /**
2282- * Create a new ZeroShotObjectDetectionPipeline.
2283- * @param {TextImagePipelineConstructorArgs} options An object used to instantiate the pipeline.
2284- */
2285- constructor(options) {
2286- super(options);
2287- }
2288-
2289- /** @type {ZeroShotObjectDetectionPipelineCallback} */
2290- async _call(images, candidate_labels, {
2291- threshold = 0.1,
2292- topk = null,
2293- percentage = false,
2294- } = {}) {
2295-
2296- const isBatched = Array.isArray(images);
2297- const preparedImages = await prepareImages(images);
2298-
2299- // Run tokenization
2300- const text_inputs = this.tokenizer(candidate_labels, {
2301- padding: true,
2302- truncation: true,
2303- });
2304-
2305- // Run processor
2306- const model_inputs = await this.processor(preparedImages);
2307-
2308- // Since non-maximum suppression is performed for exporting, we need to
2309- // process each image separately. For more information, see:
2310- // https://github.com/huggingface/optimum/blob/e3b7efb1257c011db907ef40ab340e795cc5684c/optimum/exporters/onnx/model_configs.py#L1028-L1032
2311- const toReturn = [];
2312- for (let i = 0; i < preparedImages.length; ++i) {
2313- const image = preparedImages[i];
2314- const imageSize = percentage ? null : [[image.height, image.width]];
2315- const pixel_values = model_inputs.pixel_values[i].unsqueeze_(0);
2316-
2317- // Run model with both text and pixel inputs
2318- const output = await this.model({ ...text_inputs, pixel_values });
2319-
2320- // @ts-ignore
2321- const processed = this.processor.feature_extractor.post_process_object_detection(output, threshold, imageSize, true)[0];
2322- let result = processed.boxes.map((box, i) => ({
2323- score: processed.scores[i],
2324- label: candidate_labels[processed.classes[i]],
2325- box: get_bounding_box(box, !percentage),
2326- })).sort((a, b) => b.score - a.score);
2327- if (topk !== null) {
2328- result = result.slice(0, topk);
2329- }
2330- toReturn.push(result)
2331- }
2357+export class ZeroShotObjectDetectionPipeline
2358+ extends /** @type {new (options: TextImagePipelineConstructorArgs) => ZeroShotObjectDetectionPipelineType} */ (
2359+ Pipeline
2360+ )
2361+{
2362+ /**
2363+ * Create a new ZeroShotObjectDetectionPipeline.
2364+ * @param {TextImagePipelineConstructorArgs} options An object used to instantiate the pipeline.
2365+ */
2366+ constructor(options) {
2367+ super(options);
2368+ }
2369+
2370+ /** @type {ZeroShotObjectDetectionPipelineCallback} */
2371+ async _call(
2372+ images,
2373+ candidate_labels,
2374+ { threshold = 0.1, topk = null, percentage = false } = {},
2375+ ) {
2376+ const isBatched = Array.isArray(images);
2377+ const preparedImages = await prepareImages(images);
2378+
2379+ // Run tokenization
2380+ const text_inputs = this.tokenizer(candidate_labels, {
2381+ padding: true,
2382+ truncation: true,
2383+ });
23322384
2333- return isBatched ? toReturn : toReturn[0];
2385+ // Run processor
2386+ const model_inputs = await this.processor(preparedImages);
2387+
2388+ // Since non-maximum suppression is performed for exporting, we need to
2389+ // process each image separately. For more information, see:
2390+ // https://github.com/huggingface/optimum/blob/e3b7efb1257c011db907ef40ab340e795cc5684c/optimum/exporters/onnx/model_configs.py#L1028-L1032
2391+ const toReturn = [];
2392+ for (let i = 0; i < preparedImages.length; ++i) {
2393+ const image = preparedImages[i];
2394+ const imageSize = percentage ? null : [[image.height, image.width]];
2395+ const pixel_values = model_inputs.pixel_values[i].unsqueeze_(0);
2396+
2397+ // Run model with both text and pixel inputs
2398+ const output = await this.model({ ...text_inputs, pixel_values });
2399+
2400+ // @ts-ignore
2401+ const processed =
2402+ this.processor.feature_extractor.post_process_object_detection(
2403+ output,
2404+ threshold,
2405+ imageSize,
2406+ true,
2407+ )[0];
2408+ let result = processed.boxes
2409+ .map((box, i) => ({
2410+ score: processed.scores[i],
2411+ label: candidate_labels[processed.classes[i]],
2412+ box: get_bounding_box(box, !percentage),
2413+ }))
2414+ .sort((a, b) => b.score - a.score);
2415+ if (topk !== null) {
2416+ result = result.slice(0, topk);
2417+ }
2418+ toReturn.push(result);
23342419 }
2420+
2421+ return isBatched ? toReturn : toReturn[0];
2422+ }
23352423 }
23362424
23372425 /**
23382426 * @typedef {Object} DocumentQuestionAnsweringSingle
23392427 * @property {string} answer The generated text.
23402428 * @typedef {DocumentQuestionAnsweringSingle[]} DocumentQuestionAnsweringOutput
2341- *
2429+ *
23422430 * @callback DocumentQuestionAnsweringPipelineCallback Answer the question given as input by using the document.
23432431 * @param {ImageInput} image The image of the document to use.
23442432 * @param {string} question A question to ask of the document.
23452433 * @param {import('./utils/generation.js').GenerationConfigType} [options] Additional keyword arguments to pass along to the generate method of the model.
23462434 * @returns {Promise<DocumentQuestionAnsweringOutput|DocumentQuestionAnsweringOutput[]>} An object (or array of objects) containing the answer(s).
2347- *
2435+ *
23482436 * @typedef {TextImagePipelineConstructorArgs & DocumentQuestionAnsweringPipelineCallback & Disposable} DocumentQuestionAnsweringPipelineType
23492437 */
23502438
@@ -2352,7 +2440,7 @@
23522440 * Document Question Answering pipeline using any `AutoModelForDocumentQuestionAnswering`.
23532441 * The inputs/outputs are similar to the (extractive) question answering pipeline; however,
23542442 * the pipeline takes an image (and optional OCR'd words/boxes) as input instead of text context.
2355- *
2443+ *
23562444 * **Example:** Answer questions about a document with `Xenova/donut-base-finetuned-docvqa`.
23572445 * ```javascript
23582446 * const qa_pipeline = await pipeline('document-question-answering', 'Xenova/donut-base-finetuned-docvqa');
@@ -2362,57 +2450,55 @@
23622450 * // [{ answer: 'us-001' }]
23632451 * ```
23642452 */
2365-export class DocumentQuestionAnsweringPipeline extends (/** @type {new (options: TextImagePipelineConstructorArgs) => DocumentQuestionAnsweringPipelineType} */ (Pipeline)) {
2366-
2367- /**
2368- * Create a new DocumentQuestionAnsweringPipeline.
2369- * @param {TextImagePipelineConstructorArgs} options An object used to instantiate the pipeline.
2370- */
2371- constructor(options) {
2372- super(options);
2373- }
2374-
2375- /** @type {DocumentQuestionAnsweringPipelineCallback} */
2376- async _call(image, question, generate_kwargs = {}) {
2377-
2378- // NOTE: For now, we only support a batch size of 1
2379-
2380- // Preprocess image
2381- const preparedImage = (await prepareImages(image))[0];
2382- const { pixel_values } = await this.processor(preparedImage);
2383-
2384- // Run tokenization
2385- const task_prompt = `<s_docvqa><s_question>${question}</s_question><s_answer>`;
2386- const decoder_input_ids = this.tokenizer(task_prompt, {
2387- add_special_tokens: false,
2388- padding: true,
2389- truncation: true,
2390- }).input_ids;
2391-
2392- // Run model
2393- const output = await this.model.generate(
2394- pixel_values,
2395- {
2396- ...generate_kwargs,
2397- decoder_input_ids,
2398- max_length: this.model.config.decoder.max_position_embeddings,
2399- }
2400- );
2453+export class DocumentQuestionAnsweringPipeline
2454+ extends /** @type {new (options: TextImagePipelineConstructorArgs) => DocumentQuestionAnsweringPipelineType} */ (
2455+ Pipeline
2456+ )
2457+{
2458+ /**
2459+ * Create a new DocumentQuestionAnsweringPipeline.
2460+ * @param {TextImagePipelineConstructorArgs} options An object used to instantiate the pipeline.
2461+ */
2462+ constructor(options) {
2463+ super(options);
2464+ }
2465+
2466+ /** @type {DocumentQuestionAnsweringPipelineCallback} */
2467+ async _call(image, question, generate_kwargs = {}) {
2468+ // NOTE: For now, we only support a batch size of 1
2469+
2470+ // Preprocess image
2471+ const preparedImage = (await prepareImages(image))[0];
2472+ const { pixel_values } = await this.processor(preparedImage);
2473+
2474+ // Run tokenization
2475+ const task_prompt = `<s_docvqa><s_question>${question}</s_question><s_answer>`;
2476+ const decoder_input_ids = this.tokenizer(task_prompt, {
2477+ add_special_tokens: false,
2478+ padding: true,
2479+ truncation: true,
2480+ }).input_ids;
2481+
2482+ // Run model
2483+ const output = await this.model.generate(pixel_values, {
2484+ ...generate_kwargs,
2485+ decoder_input_ids,
2486+ max_length: this.model.config.decoder.max_position_embeddings,
2487+ });
24012488
2402- // Decode output
2403- const decoded = this.tokenizer.batch_decode(output)[0];
2404-
2405- // Parse answer
2406- const match = decoded.match(/<s_answer>(.*?)<\/s_answer>/);
2407- let answer = null;
2408- if (match && match.length >= 2) {
2409- answer = match[1].trim();
2410- }
2411- return [{ answer }];
2489+ // Decode output
2490+ const decoded = this.tokenizer.batch_decode(output)[0];
2491+
2492+ // Parse answer
2493+ const match = decoded.match(/<s_answer>(.*?)<\/s_answer>/);
2494+ let answer = null;
2495+ if (match && match.length >= 2) {
2496+ answer = match[1].trim();
24122497 }
2498+ return [{ answer }];
2499+ }
24132500 }
24142501
2415-
24162502 /**
24172503 * @typedef {Object} VocoderOptions
24182504 * @property {PreTrainedModel} [vocoder] The vocoder used by the pipeline (if the model uses one). If not provided, use the default HifiGan vocoder.
@@ -2423,22 +2509,22 @@
24232509 * @typedef {Object} TextToAudioOutput
24242510 * @property {Float32Array} audio The generated audio waveform.
24252511 * @property {number} sampling_rate The sampling rate of the generated audio waveform.
2426- *
2512+ *
24272513 * @typedef {Object} TextToAudioPipelineOptions Parameters specific to text-to-audio pipelines.
24282514 * @property {Tensor|Float32Array|string|URL} [speaker_embeddings=null] The speaker embeddings (if the model requires it).
2429- *
2515+ *
24302516 * @callback TextToAudioPipelineCallback Generates speech/audio from the inputs.
24312517 * @param {string|string[]} texts The text(s) to generate.
24322518 * @param {TextToAudioPipelineOptions} options Parameters passed to the model generation/forward method.
24332519 * @returns {Promise<TextToAudioOutput>} An object containing the generated audio and sampling rate.
2434- *
2520+ *
24352521 * @typedef {TextToAudioPipelineConstructorArgs & TextToAudioPipelineCallback & Disposable} TextToAudioPipelineType
24362522 */
24372523
24382524 /**
24392525 * Text-to-audio generation pipeline using any `AutoModelForTextToWaveform` or `AutoModelForTextToSpectrogram`.
24402526 * This pipeline generates an audio file from an input text and optional other conditional inputs.
2441- *
2527+ *
24422528 * **Example:** Generate audio from text with `Xenova/speecht5_tts`.
24432529 * ```javascript
24442530 * const synthesizer = await pipeline('text-to-speech', 'Xenova/speecht5_tts', { quantized: false });
@@ -2449,17 +2535,17 @@
24492535 * // sampling_rate: 16000
24502536 * // }
24512537 * ```
2452- *
2538+ *
24532539 * You can then save the audio to a .wav file with the `wavefile` package:
24542540 * ```javascript
24552541 * import wavefile from 'wavefile';
24562542 * import fs from 'fs';
2457- *
2543+ *
24582544 * const wav = new wavefile.WaveFile();
24592545 * wav.fromScratch(1, out.sampling_rate, '32f', out.audio);
24602546 * fs.writeFileSync('out.wav', wav.toBuffer());
24612547 * ```
2462- *
2548+ *
24632549 * **Example:** Multilingual speech generation with `Xenova/mms-tts-fra`. See [here](https://huggingface.co/models?pipeline_tag=text-to-speech&other=vits&sort=trending) for the full list of available languages (1107).
24642550 * ```javascript
24652551 * const synthesizer = await pipeline('text-to-speech', 'Xenova/mms-tts-fra');
@@ -2470,107 +2556,117 @@
24702556 * // }
24712557 * ```
24722558 */
2473-export class TextToAudioPipeline extends (/** @type {new (options: TextToAudioPipelineConstructorArgs) => TextToAudioPipelineType} */ (Pipeline)) {
2474- DEFAULT_VOCODER_ID = "Xenova/speecht5_hifigan"
2475-
2476- /**
2477- * Create a new TextToAudioPipeline.
2478- * @param {TextToAudioPipelineConstructorArgs} options An object used to instantiate the pipeline.
2479- */
2480- constructor(options) {
2481- super(options);
2482-
2483- // TODO: Find a better way for `pipeline` to set the default vocoder
2484- this.vocoder = options.vocoder ?? null;
2559+export class TextToAudioPipeline
2560+ extends /** @type {new (options: TextToAudioPipelineConstructorArgs) => TextToAudioPipelineType} */ (
2561+ Pipeline
2562+ )
2563+{
2564+ DEFAULT_VOCODER_ID = "Xenova/speecht5_hifigan";
2565+
2566+ /**
2567+ * Create a new TextToAudioPipeline.
2568+ * @param {TextToAudioPipelineConstructorArgs} options An object used to instantiate the pipeline.
2569+ */
2570+ constructor(options) {
2571+ super(options);
2572+
2573+ // TODO: Find a better way for `pipeline` to set the default vocoder
2574+ this.vocoder = options.vocoder ?? null;
2575+ }
2576+
2577+ /** @type {TextToAudioPipelineCallback} */
2578+ async _call(text_inputs, { speaker_embeddings = null } = {}) {
2579+ // If this.processor is not set, we are using a `AutoModelForTextToWaveform` model
2580+ if (this.processor) {
2581+ return this._call_text_to_spectrogram(text_inputs, {
2582+ speaker_embeddings,
2583+ });
2584+ } else {
2585+ return this._call_text_to_waveform(text_inputs);
24852586 }
2587+ }
2588+
2589+ async _call_text_to_waveform(text_inputs) {
2590+ // Run tokenization
2591+ const inputs = this.tokenizer(text_inputs, {
2592+ padding: true,
2593+ truncation: true,
2594+ });
24862595
2487-
2488- /** @type {TextToAudioPipelineCallback} */
2489- async _call(text_inputs, {
2490- speaker_embeddings = null,
2491- } = {}) {
2492-
2493- // If this.processor is not set, we are using a `AutoModelForTextToWaveform` model
2494- if (this.processor) {
2495- return this._call_text_to_spectrogram(text_inputs, { speaker_embeddings });
2496- } else {
2497- return this._call_text_to_waveform(text_inputs);
2498- }
2596+ // Generate waveform
2597+ const { waveform } = await this.model(inputs);
2598+
2599+ const sampling_rate = this.model.config.sampling_rate;
2600+ return {
2601+ audio: waveform.data,
2602+ sampling_rate,
2603+ };
2604+ }
2605+
2606+ async _call_text_to_spectrogram(text_inputs, { speaker_embeddings }) {
2607+ // Load vocoder, if not provided
2608+ if (!this.vocoder) {
2609+ console.log("No vocoder specified, using default HifiGan vocoder.");
2610+ this.vocoder = await AutoModel.from_pretrained(this.DEFAULT_VOCODER_ID, {
2611+ quantized: false,
2612+ });
24992613 }
25002614
2501- async _call_text_to_waveform(text_inputs) {
2502-
2503- // Run tokenization
2504- const inputs = this.tokenizer(text_inputs, {
2505- padding: true,
2506- truncation: true,
2507- });
2508-
2509- // Generate waveform
2510- const { waveform } = await this.model(inputs);
2511-
2512- const sampling_rate = this.model.config.sampling_rate;
2513- return {
2514- audio: waveform.data,
2515- sampling_rate,
2516- }
2615+ // Load speaker embeddings as Float32Array from path/URL
2616+ if (
2617+ typeof speaker_embeddings === "string" ||
2618+ speaker_embeddings instanceof URL
2619+ ) {
2620+ // Load from URL with fetch
2621+ speaker_embeddings = new Float32Array(
2622+ await (await fetch(speaker_embeddings)).arrayBuffer(),
2623+ );
25172624 }
25182625
2519- async _call_text_to_spectrogram(text_inputs, { speaker_embeddings }) {
2520-
2521- // Load vocoder, if not provided
2522- if (!this.vocoder) {
2523- console.log('No vocoder specified, using default HifiGan vocoder.');
2524- this.vocoder = await AutoModel.from_pretrained(this.DEFAULT_VOCODER_ID, { quantized: false });
2525- }
2526-
2527- // Load speaker embeddings as Float32Array from path/URL
2528- if (typeof speaker_embeddings === 'string' || speaker_embeddings instanceof URL) {
2529- // Load from URL with fetch
2530- speaker_embeddings = new Float32Array(
2531- await (await fetch(speaker_embeddings)).arrayBuffer()
2532- );
2533- }
2534-
2535- if (speaker_embeddings instanceof Float32Array) {
2536- speaker_embeddings = new Tensor(
2537- 'float32',
2538- speaker_embeddings,
2539- [1, speaker_embeddings.length]
2540- )
2541- } else if (!(speaker_embeddings instanceof Tensor)) {
2542- throw new Error("Speaker embeddings must be a `Tensor`, `Float32Array`, `string`, or `URL`.")
2543- }
2626+ if (speaker_embeddings instanceof Float32Array) {
2627+ speaker_embeddings = new Tensor("float32", speaker_embeddings, [
2628+ 1,
2629+ speaker_embeddings.length,
2630+ ]);
2631+ } else if (!(speaker_embeddings instanceof Tensor)) {
2632+ throw new Error(
2633+ "Speaker embeddings must be a `Tensor`, `Float32Array`, `string`, or `URL`.",
2634+ );
2635+ }
25442636
2545- // Run tokenization
2546- const { input_ids } = this.tokenizer(text_inputs, {
2547- padding: true,
2548- truncation: true,
2549- });
2637+ // Run tokenization
2638+ const { input_ids } = this.tokenizer(text_inputs, {
2639+ padding: true,
2640+ truncation: true,
2641+ });
25502642
2551- // NOTE: At this point, we are guaranteed that `speaker_embeddings` is a `Tensor`
2552- // @ts-ignore
2553- const { waveform } = await this.model.generate_speech(input_ids, speaker_embeddings, { vocoder: this.vocoder });
2554-
2555- const sampling_rate = this.processor.feature_extractor.config.sampling_rate;
2556- return {
2557- audio: waveform.data,
2558- sampling_rate,
2559- }
2560- }
2643+ // NOTE: At this point, we are guaranteed that `speaker_embeddings` is a `Tensor`
2644+ // @ts-ignore
2645+ const { waveform } = await this.model.generate_speech(
2646+ input_ids,
2647+ speaker_embeddings,
2648+ { vocoder: this.vocoder },
2649+ );
2650+
2651+ const sampling_rate = this.processor.feature_extractor.config.sampling_rate;
2652+ return {
2653+ audio: waveform.data,
2654+ sampling_rate,
2655+ };
2656+ }
25612657 }
25622658
25632659 /**
25642660 * @callback ImageToImagePipelineCallback Transform the image(s) passed as inputs.
25652661 * @param {ImagePipelineInputs} images The images to transform.
25662662 * @returns {Promise<RawImage|RawImage[]>} The transformed image or list of images.
2567- *
2663+ *
25682664 * @typedef {ImagePipelineConstructorArgs & ImageToImagePipelineCallback & Disposable} ImageToImagePipelineType
25692665 */
25702666
25712667 /**
25722668 * Image to Image pipeline using any `AutoModelForImageToImage`. This pipeline generates an image based on a previous image input.
2573- *
2669+ *
25742670 * **Example:** Super-resolution w/ `Xenova/swin2SR-classical-sr-x2-64`
25752671 * ```javascript
25762672 * const upscaler = await pipeline('image-to-image', 'Xenova/swin2SR-classical-sr-x2-64');
@@ -2584,48 +2680,56 @@
25842680 * // }
25852681 * ```
25862682 */
2587-export class ImageToImagePipeline extends (/** @type {new (options: ImagePipelineConstructorArgs) => ImageToImagePipelineType} */ (Pipeline)) {
2588- /**
2589- * Create a new ImageToImagePipeline.
2590- * @param {ImagePipelineConstructorArgs} options An object used to instantiate the pipeline.
2591- */
2592- constructor(options) {
2593- super(options);
2683+export class ImageToImagePipeline
2684+ extends /** @type {new (options: ImagePipelineConstructorArgs) => ImageToImagePipelineType} */ (
2685+ Pipeline
2686+ )
2687+{
2688+ /**
2689+ * Create a new ImageToImagePipeline.
2690+ * @param {ImagePipelineConstructorArgs} options An object used to instantiate the pipeline.
2691+ */
2692+ constructor(options) {
2693+ super(options);
2694+ }
2695+
2696+ /** @type {ImageToImagePipelineCallback} */
2697+ async _call(images) {
2698+ const preparedImages = await prepareImages(images);
2699+ const inputs = await this.processor(preparedImages);
2700+ const outputs = await this.model(inputs);
2701+
2702+ /** @type {RawImage[]} */
2703+ const toReturn = [];
2704+ for (const batch of outputs.reconstruction) {
2705+ const output = batch
2706+ .squeeze()
2707+ .clamp_(0, 1)
2708+ .mul_(255)
2709+ .round_()
2710+ .to("uint8");
2711+ // toReturn.push(RawImage.fromTensor(output));
25942712 }
25952713
2596- /** @type {ImageToImagePipelineCallback} */
2597- async _call(images) {
2598-
2599- const preparedImages = await prepareImages(images);
2600- const inputs = await this.processor(preparedImages);
2601- const outputs = await this.model(inputs);
2602-
2603- /** @type {RawImage[]} */
2604- const toReturn = [];
2605- for (const batch of outputs.reconstruction) {
2606- const output = batch.squeeze().clamp_(0, 1).mul_(255).round_().to('uint8');
2607- // toReturn.push(RawImage.fromTensor(output));
2608- }
2609-
2610- return toReturn.length > 1 ? toReturn : toReturn[0];
2611- }
2714+ return toReturn.length > 1 ? toReturn : toReturn[0];
2715+ }
26122716 }
26132717
26142718 /**
26152719 * @typedef {Object} DepthEstimationPipelineOutput
26162720 * @property {Tensor} predicted_depth The raw depth map predicted by the model.
26172721 * @property {RawImage} depth The processed depth map as an image (with the same size as the input image).
2618- *
2722+ *
26192723 * @callback DepthEstimationPipelineCallback Predicts the depth for the image(s) passed as inputs.
26202724 * @param {ImagePipelineInputs} images The images to compute depth for.
26212725 * @returns {Promise<DepthEstimationPipelineOutput|DepthEstimationPipelineOutput[]>} An image or a list of images containing result(s).
2622- *
2726+ *
26232727 * @typedef {ImagePipelineConstructorArgs & DepthEstimationPipelineCallback & Disposable} DepthEstimationPipelineType
26242728 */
26252729
26262730 /**
26272731 * Depth estimation pipeline using any `AutoModelForDepthEstimation`. This pipeline predicts the depth of an image.
2628- *
2732+ *
26292733 * **Example:** Depth estimation w/ `Xenova/dpt-hybrid-midas`
26302734 * ```javascript
26312735 * const depth_estimator = await pipeline('depth-estimation', 'Xenova/dpt-hybrid-midas');
@@ -2647,323 +2751,332 @@
26472751 * // }
26482752 * ```
26492753 */
2650-export class DepthEstimationPipeline extends (/** @type {new (options: ImagePipelineConstructorArgs) => DepthEstimationPipelineType} */ (Pipeline)) {
2651- /**
2652- * Create a new DepthEstimationPipeline.
2653- * @param {ImagePipelineConstructorArgs} options An object used to instantiate the pipeline.
2654- */
2655- constructor(options) {
2656- super(options);
2754+export class DepthEstimationPipeline
2755+ extends /** @type {new (options: ImagePipelineConstructorArgs) => DepthEstimationPipelineType} */ (
2756+ Pipeline
2757+ )
2758+{
2759+ /**
2760+ * Create a new DepthEstimationPipeline.
2761+ * @param {ImagePipelineConstructorArgs} options An object used to instantiate the pipeline.
2762+ */
2763+ constructor(options) {
2764+ super(options);
2765+ }
2766+
2767+ /** @type {DepthEstimationPipelineCallback} */
2768+ async _call(images) {
2769+ const preparedImages = await prepareImages(images);
2770+
2771+ const inputs = await this.processor(preparedImages);
2772+ const { predicted_depth } = await this.model(inputs);
2773+
2774+ const toReturn = [];
2775+ for (let i = 0; i < preparedImages.length; ++i) {
2776+ const prediction = interpolate(
2777+ predicted_depth[i],
2778+ preparedImages[i].size.reverse(),
2779+ "bilinear",
2780+ false,
2781+ );
2782+ const formatted = prediction
2783+ .mul_(255 / max(prediction.data)[0])
2784+ .to("uint8");
2785+ toReturn.push({
2786+ predicted_depth: predicted_depth[i],
2787+ // depth: RawImage.fromTensor(formatted),
2788+ });
26572789 }
26582790
2659- /** @type {DepthEstimationPipelineCallback} */
2660- async _call(images) {
2661-
2662- const preparedImages = await prepareImages(images);
2663-
2664- const inputs = await this.processor(preparedImages);
2665- const { predicted_depth } = await this.model(inputs);
2666-
2667- const toReturn = [];
2668- for (let i = 0; i < preparedImages.length; ++i) {
2669- const prediction = interpolate(predicted_depth[i], preparedImages[i].size.reverse(), 'bilinear', false);
2670- const formatted = prediction.mul_(255 / max(prediction.data)[0]).to('uint8');
2671- toReturn.push({
2672- predicted_depth: predicted_depth[i],
2673- // depth: RawImage.fromTensor(formatted),
2674- });
2675- }
2676-
2677- return toReturn.length > 1 ? toReturn : toReturn[0];
2678- }
2791+ return toReturn.length > 1 ? toReturn : toReturn[0];
2792+ }
26792793 }
26802794
26812795 const SUPPORTED_TASKS = Object.freeze({
2682- "text-classification": {
2683- "tokenizer": AutoTokenizer,
2684- "pipeline": TextClassificationPipeline,
2685- "model": AutoModelForSequenceClassification,
2686- "default": {
2687- // TODO: replace with original
2688- // "model": "distilbert-base-uncased-finetuned-sst-2-english",
2689- "model": "Xenova/distilbert-base-uncased-finetuned-sst-2-english",
2690- },
2691- "type": "text",
2796+ "text-classification": {
2797+ tokenizer: AutoTokenizer,
2798+ pipeline: TextClassificationPipeline,
2799+ model: AutoModelForSequenceClassification,
2800+ default: {
2801+ // TODO: replace with original
2802+ // "model": "distilbert-base-uncased-finetuned-sst-2-english",
2803+ model: "Xenova/distilbert-base-uncased-finetuned-sst-2-english",
26922804 },
2693- "token-classification": {
2694- "tokenizer": AutoTokenizer,
2695- "pipeline": TokenClassificationPipeline,
2696- "model": AutoModelForTokenClassification,
2697- "default": {
2698- // TODO: replace with original
2699- // "model": "Davlan/bert-base-multilingual-cased-ner-hrl",
2700- "model": "Xenova/bert-base-multilingual-cased-ner-hrl",
2701- },
2702- "type": "text",
2805+ type: "text",
2806+ },
2807+ "token-classification": {
2808+ tokenizer: AutoTokenizer,
2809+ pipeline: TokenClassificationPipeline,
2810+ model: AutoModelForTokenClassification,
2811+ default: {
2812+ // TODO: replace with original
2813+ // "model": "Davlan/bert-base-multilingual-cased-ner-hrl",
2814+ model: "Xenova/bert-base-multilingual-cased-ner-hrl",
27032815 },
2704- "question-answering": {
2705- "tokenizer": AutoTokenizer,
2706- "pipeline": QuestionAnsweringPipeline,
2707- "model": AutoModelForQuestionAnswering,
2708- "default": {
2709- // TODO: replace with original
2710- // "model": "distilbert-base-cased-distilled-squad",
2711- "model": "Xenova/distilbert-base-cased-distilled-squad",
2712- },
2713- "type": "text",
2816+ type: "text",
2817+ },
2818+ "question-answering": {
2819+ tokenizer: AutoTokenizer,
2820+ pipeline: QuestionAnsweringPipeline,
2821+ model: AutoModelForQuestionAnswering,
2822+ default: {
2823+ // TODO: replace with original
2824+ // "model": "distilbert-base-cased-distilled-squad",
2825+ model: "Xenova/distilbert-base-cased-distilled-squad",
27142826 },
2715-
2716- "fill-mask": {
2717- "tokenizer": AutoTokenizer,
2718- "pipeline": FillMaskPipeline,
2719- "model": AutoModelForMaskedLM,
2720- "default": {
2721- // TODO: replace with original
2722- // "model": "bert-base-uncased",
2723- "model": "Xenova/bert-base-uncased",
2724- },
2725- "type": "text",
2827+ type: "text",
2828+ },
2829+
2830+ "fill-mask": {
2831+ tokenizer: AutoTokenizer,
2832+ pipeline: FillMaskPipeline,
2833+ model: AutoModelForMaskedLM,
2834+ default: {
2835+ // TODO: replace with original
2836+ // "model": "bert-base-uncased",
2837+ model: "Xenova/bert-base-uncased",
27262838 },
2727- "summarization": {
2728- "tokenizer": AutoTokenizer,
2729- "pipeline": SummarizationPipeline,
2730- "model": AutoModelForSeq2SeqLM,
2731- "default": {
2732- // TODO: replace with original
2733- // "model": "sshleifer/distilbart-cnn-6-6",
2734- "model": "Xenova/distilbart-cnn-6-6",
2735- },
2736- "type": "text",
2839+ type: "text",
2840+ },
2841+ summarization: {
2842+ tokenizer: AutoTokenizer,
2843+ pipeline: SummarizationPipeline,
2844+ model: AutoModelForSeq2SeqLM,
2845+ default: {
2846+ // TODO: replace with original
2847+ // "model": "sshleifer/distilbart-cnn-6-6",
2848+ model: "Xenova/distilbart-cnn-6-6",
27372849 },
2738- "translation": {
2739- "tokenizer": AutoTokenizer,
2740- "pipeline": TranslationPipeline,
2741- "model": AutoModelForSeq2SeqLM,
2742- "default": {
2743- // TODO: replace with original
2744- // "model": "t5-small",
2745- "model": "Xenova/t5-small",
2746- },
2747- "type": "text",
2850+ type: "text",
2851+ },
2852+ translation: {
2853+ tokenizer: AutoTokenizer,
2854+ pipeline: TranslationPipeline,
2855+ model: AutoModelForSeq2SeqLM,
2856+ default: {
2857+ // TODO: replace with original
2858+ // "model": "t5-small",
2859+ model: "Xenova/t5-small",
27482860 },
2749- "text2text-generation": {
2750- "tokenizer": AutoTokenizer,
2751- "pipeline": Text2TextGenerationPipeline,
2752- "model": AutoModelForSeq2SeqLM,
2753- "default": {
2754- // TODO: replace with original
2755- // "model": "google/flan-t5-small",
2756- "model": "Xenova/flan-t5-small",
2757- },
2758- "type": "text",
2861+ type: "text",
2862+ },
2863+ "text2text-generation": {
2864+ tokenizer: AutoTokenizer,
2865+ pipeline: Text2TextGenerationPipeline,
2866+ model: AutoModelForSeq2SeqLM,
2867+ default: {
2868+ // TODO: replace with original
2869+ // "model": "google/flan-t5-small",
2870+ model: "Xenova/flan-t5-small",
27592871 },
2760- "text-generation": {
2761- "tokenizer": AutoTokenizer,
2762- "pipeline": TextGenerationPipeline,
2763- "model": AutoModelForCausalLM,
2764- "default": {
2765- // TODO: replace with original
2766- // "model": "gpt2",
2767- "model": "Xenova/gpt2",
2768- },
2769- "type": "text",
2872+ type: "text",
2873+ },
2874+ "text-generation": {
2875+ tokenizer: AutoTokenizer,
2876+ pipeline: TextGenerationPipeline,
2877+ model: AutoModelForCausalLM,
2878+ default: {
2879+ // TODO: replace with original
2880+ // "model": "gpt2",
2881+ model: "Xenova/gpt2",
27702882 },
2771- "zero-shot-classification": {
2772- "tokenizer": AutoTokenizer,
2773- "pipeline": ZeroShotClassificationPipeline,
2774- "model": AutoModelForSequenceClassification,
2775- "default": {
2776- // TODO: replace with original
2777- // "model": "typeform/distilbert-base-uncased-mnli",
2778- "model": "Xenova/distilbert-base-uncased-mnli",
2779- },
2780- "type": "text",
2883+ type: "text",
2884+ },
2885+ "zero-shot-classification": {
2886+ tokenizer: AutoTokenizer,
2887+ pipeline: ZeroShotClassificationPipeline,
2888+ model: AutoModelForSequenceClassification,
2889+ default: {
2890+ // TODO: replace with original
2891+ // "model": "typeform/distilbert-base-uncased-mnli",
2892+ model: "Xenova/distilbert-base-uncased-mnli",
27812893 },
2782- "audio-classification": {
2783- "pipeline": AudioClassificationPipeline,
2784- "model": AutoModelForAudioClassification,
2785- "processor": AutoProcessor,
2786- "default": {
2787- // TODO: replace with original
2788- // "model": "superb/wav2vec2-base-superb-ks",
2789- "model": "Xenova/wav2vec2-base-superb-ks",
2790- },
2791- "type": "audio",
2894+ type: "text",
2895+ },
2896+ "audio-classification": {
2897+ pipeline: AudioClassificationPipeline,
2898+ model: AutoModelForAudioClassification,
2899+ processor: AutoProcessor,
2900+ default: {
2901+ // TODO: replace with original
2902+ // "model": "superb/wav2vec2-base-superb-ks",
2903+ model: "Xenova/wav2vec2-base-superb-ks",
27922904 },
2793- "zero-shot-audio-classification": {
2794- "tokenizer": AutoTokenizer,
2795- "pipeline": ZeroShotAudioClassificationPipeline,
2796- "model": AutoModel,
2797- "processor": AutoProcessor,
2798- "default": {
2799- // TODO: replace with original
2800- // "model": "laion/clap-htsat-fused",
2801- "model": "Xenova/clap-htsat-unfused",
2802- },
2803- "type": "multimodal",
2905+ type: "audio",
2906+ },
2907+ "zero-shot-audio-classification": {
2908+ tokenizer: AutoTokenizer,
2909+ pipeline: ZeroShotAudioClassificationPipeline,
2910+ model: AutoModel,
2911+ processor: AutoProcessor,
2912+ default: {
2913+ // TODO: replace with original
2914+ // "model": "laion/clap-htsat-fused",
2915+ model: "Xenova/clap-htsat-unfused",
28042916 },
2805- "automatic-speech-recognition": {
2806- "tokenizer": AutoTokenizer,
2807- "pipeline": AutomaticSpeechRecognitionPipeline,
2808- "model": [AutoModelForSpeechSeq2Seq, AutoModelForCTC],
2809- "processor": AutoProcessor,
2810- "default": {
2811- // TODO: replace with original
2812- // "model": "openai/whisper-tiny.en",
2813- "model": "Xenova/whisper-tiny.en",
2814- },
2815- "type": "multimodal",
2917+ type: "multimodal",
2918+ },
2919+ "automatic-speech-recognition": {
2920+ tokenizer: AutoTokenizer,
2921+ pipeline: AutomaticSpeechRecognitionPipeline,
2922+ model: [AutoModelForSpeechSeq2Seq, AutoModelForCTC],
2923+ processor: AutoProcessor,
2924+ default: {
2925+ // TODO: replace with original
2926+ // "model": "openai/whisper-tiny.en",
2927+ model: "Xenova/whisper-tiny.en",
28162928 },
2817- "text-to-audio": {
2818- "tokenizer": AutoTokenizer,
2819- "pipeline": TextToAudioPipeline,
2820- "model": [AutoModelForTextToWaveform, AutoModelForTextToSpectrogram],
2821- "processor": [AutoProcessor, /* Some don't use a processor */ null],
2822- "default": {
2823- // TODO: replace with original
2824- // "model": "microsoft/speecht5_tts",
2825- "model": "Xenova/speecht5_tts",
2826- },
2827- "type": "text",
2929+ type: "multimodal",
2930+ },
2931+ "text-to-audio": {
2932+ tokenizer: AutoTokenizer,
2933+ pipeline: TextToAudioPipeline,
2934+ model: [AutoModelForTextToWaveform, AutoModelForTextToSpectrogram],
2935+ processor: [AutoProcessor, /* Some don't use a processor */ null],
2936+ default: {
2937+ // TODO: replace with original
2938+ // "model": "microsoft/speecht5_tts",
2939+ model: "Xenova/speecht5_tts",
28282940 },
2829- "image-to-text": {
2830- "tokenizer": AutoTokenizer,
2831- "pipeline": ImageToTextPipeline,
2832- "model": AutoModelForVision2Seq,
2833- "processor": AutoProcessor,
2834- "default": {
2835- // TODO: replace with original
2836- // "model": "nlpconnect/vit-gpt2-image-captioning",
2837- "model": "Xenova/vit-gpt2-image-captioning",
2838- },
2839- "type": "multimodal",
2941+ type: "text",
2942+ },
2943+ "image-to-text": {
2944+ tokenizer: AutoTokenizer,
2945+ pipeline: ImageToTextPipeline,
2946+ model: AutoModelForVision2Seq,
2947+ processor: AutoProcessor,
2948+ default: {
2949+ // TODO: replace with original
2950+ // "model": "nlpconnect/vit-gpt2-image-captioning",
2951+ model: "Xenova/vit-gpt2-image-captioning",
28402952 },
2841-
2842- "image-classification": {
2843- // no tokenizer
2844- "pipeline": ImageClassificationPipeline,
2845- "model": AutoModelForImageClassification,
2846- "processor": AutoProcessor,
2847- "default": {
2848- // TODO: replace with original
2849- // "model": "google/vit-base-patch16-224",
2850- "model": "Xenova/vit-base-patch16-224",
2851- },
2852- "type": "multimodal",
2953+ type: "multimodal",
2954+ },
2955+
2956+ "image-classification": {
2957+ // no tokenizer
2958+ pipeline: ImageClassificationPipeline,
2959+ model: AutoModelForImageClassification,
2960+ processor: AutoProcessor,
2961+ default: {
2962+ // TODO: replace with original
2963+ // "model": "google/vit-base-patch16-224",
2964+ model: "Xenova/vit-base-patch16-224",
28532965 },
2854-
2855- "image-segmentation": {
2856- // no tokenizer
2857- "pipeline": ImageSegmentationPipeline,
2858- "model": [AutoModelForImageSegmentation, AutoModelForSemanticSegmentation],
2859- "processor": AutoProcessor,
2860- "default": {
2861- // TODO: replace with original
2862- // "model": "facebook/detr-resnet-50-panoptic",
2863- "model": "Xenova/detr-resnet-50-panoptic",
2864- },
2865- "type": "multimodal",
2966+ type: "multimodal",
2967+ },
2968+
2969+ "image-segmentation": {
2970+ // no tokenizer
2971+ pipeline: ImageSegmentationPipeline,
2972+ model: [AutoModelForImageSegmentation, AutoModelForSemanticSegmentation],
2973+ processor: AutoProcessor,
2974+ default: {
2975+ // TODO: replace with original
2976+ // "model": "facebook/detr-resnet-50-panoptic",
2977+ model: "Xenova/detr-resnet-50-panoptic",
28662978 },
2867-
2868- "zero-shot-image-classification": {
2869- "tokenizer": AutoTokenizer,
2870- "pipeline": ZeroShotImageClassificationPipeline,
2871- "model": AutoModel,
2872- "processor": AutoProcessor,
2873- "default": {
2874- // TODO: replace with original
2875- // "model": "openai/clip-vit-base-patch32",
2876- "model": "Xenova/clip-vit-base-patch32",
2877- },
2878- "type": "multimodal",
2979+ type: "multimodal",
2980+ },
2981+
2982+ "zero-shot-image-classification": {
2983+ tokenizer: AutoTokenizer,
2984+ pipeline: ZeroShotImageClassificationPipeline,
2985+ model: AutoModel,
2986+ processor: AutoProcessor,
2987+ default: {
2988+ // TODO: replace with original
2989+ // "model": "openai/clip-vit-base-patch32",
2990+ model: "Xenova/clip-vit-base-patch32",
28792991 },
2880-
2881- "object-detection": {
2882- // no tokenizer
2883- "pipeline": ObjectDetectionPipeline,
2884- "model": AutoModelForObjectDetection,
2885- "processor": AutoProcessor,
2886- "default": {
2887- // TODO: replace with original
2888- // "model": "facebook/detr-resnet-50",
2889- "model": "Xenova/detr-resnet-50",
2890- },
2891- "type": "multimodal",
2992+ type: "multimodal",
2993+ },
2994+
2995+ "object-detection": {
2996+ // no tokenizer
2997+ pipeline: ObjectDetectionPipeline,
2998+ model: AutoModelForObjectDetection,
2999+ processor: AutoProcessor,
3000+ default: {
3001+ // TODO: replace with original
3002+ // "model": "facebook/detr-resnet-50",
3003+ model: "Xenova/detr-resnet-50",
28923004 },
2893- "zero-shot-object-detection": {
2894- "tokenizer": AutoTokenizer,
2895- "pipeline": ZeroShotObjectDetectionPipeline,
2896- "model": AutoModelForZeroShotObjectDetection,
2897- "processor": AutoProcessor,
2898- "default": {
2899- // TODO: replace with original
2900- // "model": "google/owlvit-base-patch32",
2901- "model": "Xenova/owlvit-base-patch32",
2902- },
2903- "type": "multimodal",
3005+ type: "multimodal",
3006+ },
3007+ "zero-shot-object-detection": {
3008+ tokenizer: AutoTokenizer,
3009+ pipeline: ZeroShotObjectDetectionPipeline,
3010+ model: AutoModelForZeroShotObjectDetection,
3011+ processor: AutoProcessor,
3012+ default: {
3013+ // TODO: replace with original
3014+ // "model": "google/owlvit-base-patch32",
3015+ model: "Xenova/owlvit-base-patch32",
29043016 },
2905- "document-question-answering": {
2906- "tokenizer": AutoTokenizer,
2907- "pipeline": DocumentQuestionAnsweringPipeline,
2908- "model": AutoModelForDocumentQuestionAnswering,
2909- "processor": AutoProcessor,
2910- "default": {
2911- // TODO: replace with original
2912- // "model": "naver-clova-ix/donut-base-finetuned-docvqa",
2913- "model": "Xenova/donut-base-finetuned-docvqa",
2914- },
2915- "type": "multimodal",
3017+ type: "multimodal",
3018+ },
3019+ "document-question-answering": {
3020+ tokenizer: AutoTokenizer,
3021+ pipeline: DocumentQuestionAnsweringPipeline,
3022+ model: AutoModelForDocumentQuestionAnswering,
3023+ processor: AutoProcessor,
3024+ default: {
3025+ // TODO: replace with original
3026+ // "model": "naver-clova-ix/donut-base-finetuned-docvqa",
3027+ model: "Xenova/donut-base-finetuned-docvqa",
29163028 },
2917- "image-to-image": {
2918- // no tokenizer
2919- "pipeline": ImageToImagePipeline,
2920- "model": AutoModelForImageToImage,
2921- "processor": AutoProcessor,
2922- "default": {
2923- // TODO: replace with original
2924- // "model": "caidas/swin2SR-classical-sr-x2-64",
2925- "model": "Xenova/swin2SR-classical-sr-x2-64",
2926- },
2927- "type": "image",
3029+ type: "multimodal",
3030+ },
3031+ "image-to-image": {
3032+ // no tokenizer
3033+ pipeline: ImageToImagePipeline,
3034+ model: AutoModelForImageToImage,
3035+ processor: AutoProcessor,
3036+ default: {
3037+ // TODO: replace with original
3038+ // "model": "caidas/swin2SR-classical-sr-x2-64",
3039+ model: "Xenova/swin2SR-classical-sr-x2-64",
29283040 },
2929- "depth-estimation": {
2930- // no tokenizer
2931- "pipeline": DepthEstimationPipeline,
2932- "model": AutoModelForDepthEstimation,
2933- "processor": AutoProcessor,
2934- "default": {
2935- // TODO: replace with original
2936- // "model": "Intel/dpt-large",
2937- "model": "Xenova/dpt-large",
2938- },
2939- "type": "image",
3041+ type: "image",
3042+ },
3043+ "depth-estimation": {
3044+ // no tokenizer
3045+ pipeline: DepthEstimationPipeline,
3046+ model: AutoModelForDepthEstimation,
3047+ processor: AutoProcessor,
3048+ default: {
3049+ // TODO: replace with original
3050+ // "model": "Intel/dpt-large",
3051+ model: "Xenova/dpt-large",
29403052 },
2941-
2942- // This task serves as a useful interface for dealing with sentence-transformers (https://huggingface.co/sentence-transformers).
2943- "feature-extraction": {
2944- "tokenizer": AutoTokenizer,
2945- "pipeline": FeatureExtractionPipeline,
2946- "model": AutoModel,
2947- "default": {
2948- // TODO: replace with original
2949- // "model": "sentence-transformers/all-MiniLM-L6-v2",
2950- "model": "Xenova/all-MiniLM-L6-v2",
2951- },
2952- "type": "text",
3053+ type: "image",
3054+ },
3055+
3056+ // This task serves as a useful interface for dealing with sentence-transformers (https://huggingface.co/sentence-transformers).
3057+ "feature-extraction": {
3058+ tokenizer: AutoTokenizer,
3059+ pipeline: FeatureExtractionPipeline,
3060+ model: AutoModel,
3061+ default: {
3062+ // TODO: replace with original
3063+ // "model": "sentence-transformers/all-MiniLM-L6-v2",
3064+ model: "Xenova/all-MiniLM-L6-v2",
29533065 },
2954-})
2955-
3066+ type: "text",
3067+ },
3068+});
29563069
29573070 // TODO: Add types for TASK_ALIASES
29583071 const TASK_ALIASES = Object.freeze({
2959- "sentiment-analysis": "text-classification",
2960- "ner": "token-classification",
2961- // "vqa": "visual-question-answering", // TODO: Add
2962- "asr": "automatic-speech-recognition",
2963- "text-to-speech": "text-to-audio",
2964-
2965- // Add for backwards compatibility
2966- "embeddings": "feature-extraction",
3072+ "sentiment-analysis": "text-classification",
3073+ ner: "token-classification",
3074+ // "vqa": "visual-question-answering", // TODO: Add
3075+ asr: "automatic-speech-recognition",
3076+ "text-to-speech": "text-to-audio",
3077+
3078+ // Add for backwards compatibility
3079+ embeddings: "feature-extraction",
29673080 });
29683081
29693082 /**
@@ -2977,7 +3090,7 @@
29773090
29783091 /**
29793092 * Utility factory method to build a `Pipeline` object.
2980- *
3093+ *
29813094 * @template {PipelineType} T The type of pipeline to return.
29823095 * @param {T} task The task defining which pipeline will be returned. Currently accepted tasks are:
29833096 * - `"audio-classification"`: will return a `AudioClassificationPipeline`.
@@ -3008,65 +3121,66 @@
30083121 * @throws {Error} If an unsupported pipeline is requested.
30093122 */
30103123 export async function pipeline(
3011- task,
3012- model = null,
3013- {
3014- quantized = true,
3015- progress_callback = null,
3016- config = null,
3017- cache_dir = null,
3018- local_files_only = false,
3019- revision = 'main',
3020- } = {}
3124+ task,
3125+ model = null,
3126+ {
3127+ quantized = true,
3128+ progress_callback = null,
3129+ config = null,
3130+ cache_dir = null,
3131+ local_files_only = false,
3132+ revision = "main",
3133+ } = {},
30213134 ) {
3022- // Helper method to construct pipeline
3023-
3024- // Apply aliases
3025- // @ts-ignore
3026- task = TASK_ALIASES[task] ?? task;
3027-
3028- // Get pipeline info
3029- const pipelineInfo = SUPPORTED_TASKS[task.split('_', 1)[0]];
3030- if (!pipelineInfo) {
3031- throw Error(`Unsupported pipeline: ${task}. Must be one of [${Object.keys(SUPPORTED_TASKS)}]`)
3032- }
3033-
3034- // Use model if specified, otherwise, use default
3035- if (!model) {
3036- model = pipelineInfo.default.model
3037- console.log(`No model specified. Using default model: "${model}".`);
3038- }
3039-
3040- const pretrainedOptions = {
3041- quantized,
3042- progress_callback,
3043- config,
3044- cache_dir,
3045- local_files_only,
3046- revision,
3047- }
3048-
3049- const classes = new Map([
3050- ['tokenizer', pipelineInfo.tokenizer],
3051- ['model', pipelineInfo.model],
3052- ['processor', pipelineInfo.processor],
3053- ]);
3054-
3055- // Load model, tokenizer, and processor (if they exist)
3056- const results = await loadItems(classes, model, pretrainedOptions);
3057- results.task = task;
3058-
3059- dispatchCallback(progress_callback, {
3060- 'status': 'ready',
3061- 'task': task,
3062- 'model': model,
3063- });
3064-
3065- const pipelineClass = pipelineInfo.pipeline;
3066- return new pipelineClass(results);
3135+ // Helper method to construct pipeline
3136+
3137+ // Apply aliases
3138+ // @ts-ignore
3139+ task = TASK_ALIASES[task] ?? task;
3140+
3141+ // Get pipeline info
3142+ const pipelineInfo = SUPPORTED_TASKS[task.split("_", 1)[0]];
3143+ if (!pipelineInfo) {
3144+ throw Error(
3145+ `Unsupported pipeline: ${task}. Must be one of [${Object.keys(SUPPORTED_TASKS)}]`,
3146+ );
3147+ }
3148+
3149+ // Use model if specified, otherwise, use default
3150+ if (!model) {
3151+ model = pipelineInfo.default.model;
3152+ console.log(`No model specified. Using default model: "${model}".`);
3153+ }
3154+
3155+ const pretrainedOptions = {
3156+ quantized,
3157+ progress_callback,
3158+ config,
3159+ cache_dir,
3160+ local_files_only,
3161+ revision,
3162+ };
3163+
3164+ const classes = new Map([
3165+ ["tokenizer", pipelineInfo.tokenizer],
3166+ ["model", pipelineInfo.model],
3167+ ["processor", pipelineInfo.processor],
3168+ ]);
3169+
3170+ // Load model, tokenizer, and processor (if they exist)
3171+ const results = await loadItems(classes, model, pretrainedOptions);
3172+ results.task = task;
3173+
3174+ dispatchCallback(progress_callback, {
3175+ status: "ready",
3176+ task: task,
3177+ model: model,
3178+ });
3179+
3180+ const pipelineClass = pipelineInfo.pipeline;
3181+ return new pipelineClass(results);
30673182 }
30683183
3069-
30703184 /**
30713185 * Helper function to get applicable model, tokenizer, or processor classes for a given model.
30723186 * @param {Map<string, any>} mapping The mapping of names to classes, arrays of classes, or null.
@@ -3075,50 +3189,49 @@
30753189 * @private
30763190 */
30773191 async function loadItems(mapping, model, pretrainedOptions) {
3078-
3079- const result = Object.create(null);
3080-
3081- /**@type {Promise[]} */
3082- const promises = [];
3083- for (let [name, cls] of mapping.entries()) {
3084- if (!cls) continue;
3085-
3086- /**@type {Promise} */
3087- let promise;
3088- if (Array.isArray(cls)) {
3089- promise = new Promise(async (resolve, reject) => {
3090- let e;
3091- for (let c of cls) {
3092- if (c === null) {
3093- // If null, we resolve it immediately, meaning the relevant
3094- // class was not found, but it is optional.
3095- resolve(null);
3096- return;
3097- }
3098- try {
3099- resolve(await c.from_pretrained(model, pretrainedOptions));
3100- return;
3101- } catch (err) {
3102- e = err;
3103- }
3104- }
3105- reject(e);
3106- })
3107- } else {
3108- promise = cls.from_pretrained(model, pretrainedOptions);
3192+ const result = Object.create(null);
3193+
3194+ /**@type {Promise[]} */
3195+ const promises = [];
3196+ for (let [name, cls] of mapping.entries()) {
3197+ if (!cls) continue;
3198+
3199+ /**@type {Promise} */
3200+ let promise;
3201+ if (Array.isArray(cls)) {
3202+ promise = new Promise(async (resolve, reject) => {
3203+ let e;
3204+ for (let c of cls) {
3205+ if (c === null) {
3206+ // If null, we resolve it immediately, meaning the relevant
3207+ // class was not found, but it is optional.
3208+ resolve(null);
3209+ return;
3210+ }
3211+ try {
3212+ resolve(await c.from_pretrained(model, pretrainedOptions));
3213+ return;
3214+ } catch (err) {
3215+ e = err;
3216+ }
31093217 }
3110-
3111- result[name] = promise;
3112- promises.push(promise);
3218+ reject(e);
3219+ });
3220+ } else {
3221+ promise = cls.from_pretrained(model, pretrainedOptions);
31133222 }
31143223
3115- // Wait for all promises to resolve (in parallel)
3116- await Promise.all(promises);
3224+ result[name] = promise;
3225+ promises.push(promise);
3226+ }
31173227
3118- // Then assign to result
3119- for (let [name, promise] of Object.entries(result)) {
3120- result[name] = await promise;
3121- }
3228+ // Wait for all promises to resolve (in parallel)
3229+ await Promise.all(promises);
31223230
3123- return result;
3124-}
No newline at the end of the file
3231+ // Then assign to result
3232+ for (let [name, promise] of Object.entries(result)) {
3233+ result[name] = await promise;
3234+ }
3235+
3236+ return result;
3237+}
modified core/vendor/modules/@xenova/transformers/src/processors.js +1762 −1663
@@ -1,7 +1,6 @@
1-
21 /**
32 * @file Processors are used to prepare non-textual inputs (e.g., image or audio) for a model.
4- *
3+ *
54 * **Example:** Using a `WhisperProcessor` to prepare an audio input for a model.
65 * ```javascript
76 * import { AutoProcessor, read_audio } from '@xenova/transformers';
@@ -16,51 +15,43 @@
1615 * // size: 240000,
1716 * // }
1817 * ```
19- *
18+ *
2019 * @module processors
2120 */
2221 import {
23- Callable,
24- calculateDimensions,
25- calculateReflectOffset,
26-} from './utils/core.js';
27-
28-import {
29- getModelJSON,
30-} from './utils/hub.js';
22+ Callable,
23+ calculateDimensions,
24+ calculateReflectOffset,
25+} from "./utils/core.js";
3126
32-import {
33- max,
34- min,
35- softmax,
36-} from './utils/maths.js';
27+import { getModelJSON } from "./utils/hub.js";
3728
29+import { max, min, softmax } from "./utils/maths.js";
3830
39-import { Tensor, cat, interpolate, stack, transpose } from './utils/tensor.js';
31+import { Tensor, cat, interpolate, stack, transpose } from "./utils/tensor.js";
4032
4133 // import { RawImage } from './utils/image.js';
4234 import {
43- mel_filter_bank,
44- spectrogram,
45- window_function,
46-} from './utils/audio.js';
47-
35+ mel_filter_bank,
36+ spectrogram,
37+ window_function,
38+} from "./utils/audio.js";
4839
4940 // Helper functions
5041
5142 /**
5243 * Converts bounding boxes from center format to corners format.
53- *
44+ *
5445 * @param {number[]} arr The coordinate for the center of the box and its width, height dimensions (center_x, center_y, width, height)
5546 * @returns {number[]} The coodinates for the top-left and bottom-right corners of the box (top_left_x, top_left_y, bottom_right_x, bottom_right_y)
5647 */
5748 function center_to_corners_format([centerX, centerY, width, height]) {
58- return [
59- centerX - width / 2,
60- centerY - height / 2,
61- centerX + width / 2,
62- centerY + height / 2
63- ];
49+ return [
50+ centerX - width / 2,
51+ centerY - height / 2,
52+ centerX + width / 2,
53+ centerY + height / 2,
54+ ];
6455 }
6556
6657 /**
@@ -74,73 +65,78 @@
7465 * @return {Object[]} An array of objects containing the post-processed outputs.
7566 * @private
7667 */
77-function post_process_object_detection(outputs, threshold = 0.5, target_sizes = null, is_zero_shot = false) {
78- const out_logits = outputs.logits;
79- const out_bbox = outputs.pred_boxes;
80- const [batch_size, num_boxes, num_classes] = out_logits.dims;
81-
82- if (target_sizes !== null && target_sizes.length !== batch_size) {
83- throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits")
84- }
85- let toReturn = [];
86- for (let i = 0; i < batch_size; ++i) {
87- let target_size = target_sizes !== null ? target_sizes[i] : null;
88- let info = {
89- boxes: [],
90- classes: [],
91- scores: []
68+function post_process_object_detection(
69+ outputs,
70+ threshold = 0.5,
71+ target_sizes = null,
72+ is_zero_shot = false,
73+) {
74+ const out_logits = outputs.logits;
75+ const out_bbox = outputs.pred_boxes;
76+ const [batch_size, num_boxes, num_classes] = out_logits.dims;
77+
78+ if (target_sizes !== null && target_sizes.length !== batch_size) {
79+ throw Error(
80+ "Make sure that you pass in as many target sizes as the batch dimension of the logits",
81+ );
82+ }
83+ let toReturn = [];
84+ for (let i = 0; i < batch_size; ++i) {
85+ let target_size = target_sizes !== null ? target_sizes[i] : null;
86+ let info = {
87+ boxes: [],
88+ classes: [],
89+ scores: [],
90+ };
91+ let logits = out_logits[i];
92+ let bbox = out_bbox[i];
93+
94+ for (let j = 0; j < num_boxes; ++j) {
95+ let logit = logits[j];
96+
97+ let indices = [];
98+ let probs;
99+ if (is_zero_shot) {
100+ // Get indices of classes with high enough probability
101+ probs = logit.sigmoid().data;
102+ for (let k = 0; k < probs.length; ++k) {
103+ if (probs[k] > threshold) {
104+ indices.push(k);
105+ }
92106 }
93- let logits = out_logits[i];
94- let bbox = out_bbox[i];
95-
96- for (let j = 0; j < num_boxes; ++j) {
97- let logit = logits[j];
98-
99- let indices = [];
100- let probs;
101- if (is_zero_shot) {
102- // Get indices of classes with high enough probability
103- probs = logit.sigmoid().data;
104- for (let k = 0; k < probs.length; ++k) {
105- if (probs[k] > threshold) {
106- indices.push(k);
107- }
108- }
109-
110- } else {
111- // Get most probable class
112- let maxIndex = max(logit.data)[1];
113-
114- if (maxIndex === num_classes - 1) {
115- // This is the background class, skip it
116- continue;
117- }
118- indices.push(maxIndex);
119-
120- // Compute softmax over classes
121- probs = softmax(logit.data);
122- }
123-
124- for (const index of indices) {
125-
126- // Some class has a high enough probability
127- /** @type {number[]} */
128- let box = bbox[j].data;
129-
130- // convert to [x0, y0, x1, y1] format
131- box = center_to_corners_format(box)
132- if (target_size !== null) {
133- box = box.map((x, i) => x * target_size[(i + 1) % 2])
134- }
135-
136- info.boxes.push(box);
137- info.classes.push(index);
138- info.scores.push(probs[index]);
139- }
107+ } else {
108+ // Get most probable class
109+ let maxIndex = max(logit.data)[1];
110+
111+ if (maxIndex === num_classes - 1) {
112+ // This is the background class, skip it
113+ continue;
114+ }
115+ indices.push(maxIndex);
116+
117+ // Compute softmax over classes
118+ probs = softmax(logit.data);
119+ }
120+
121+ for (const index of indices) {
122+ // Some class has a high enough probability
123+ /** @type {number[]} */
124+ let box = bbox[j].data;
125+
126+ // convert to [x0, y0, x1, y1] format
127+ box = center_to_corners_format(box);
128+ if (target_size !== null) {
129+ box = box.map((x, i) => x * target_size[(i + 1) % 2]);
140130 }
141- toReturn.push(info);
131+
132+ info.boxes.push(box);
133+ info.classes.push(index);
134+ info.scores.push(probs[index]);
135+ }
142136 }
143- return toReturn;
137+ toReturn.push(info);
138+ }
139+ return toReturn;
144140 }
145141
146142 /**
@@ -156,12 +152,12 @@
156152 * @private
157153 */
158154 function validate_audio_inputs(audio, feature_extractor) {
159- if (!(audio instanceof Float32Array || audio instanceof Float64Array)) {
160- throw new Error(
161- `${feature_extractor} expects input to be a Float32Array or a Float64Array, but got ${audio?.constructor?.name ?? typeof audio} instead.` +
162- `If using the feature extractor directly, remember to use \`read_audio(url, sampling_rate)\` to obtain the raw audio data of the file/url.`
163- )
164- }
155+ if (!(audio instanceof Float32Array || audio instanceof Float64Array)) {
156+ throw new Error(
157+ `${feature_extractor} expects input to be a Float32Array or a Float64Array, but got ${audio?.constructor?.name ?? typeof audio} instead.` +
158+ `If using the feature extractor directly, remember to use \`read_audio(url, sampling_rate)\` to obtain the raw audio data of the file/url.`,
159+ );
160+ }
165161 }
166162
167163 /**
@@ -170,15 +166,15 @@
170166 * @extends Callable
171167 */
172168 export class FeatureExtractor extends Callable {
173- /**
174- * Constructs a new FeatureExtractor instance.
175- *
176- * @param {Object} config The configuration for the feature extractor.
177- */
178- constructor(config) {
179- super();
180- this.config = config
181- }
169+ /**
170+ * Constructs a new FeatureExtractor instance.
171+ *
172+ * @param {Object} config The configuration for the feature extractor.
173+ */
174+ constructor(config) {
175+ super();
176+ this.config = config;
177+ }
182178 }
183179
184180 /**
@@ -194,597 +190,638 @@
194190 * @extends FeatureExtractor
195191 */
196192 export class ImageFeatureExtractor extends FeatureExtractor {
197-
198- /**
199- * Constructs a new ImageFeatureExtractor instance.
200- *
201- * @param {Object} config The configuration for the feature extractor.
202- * @param {number[]} config.image_mean The mean values for image normalization.
203- * @param {number[]} config.image_std The standard deviation values for image normalization.
204- * @param {boolean} config.do_rescale Whether to rescale the image pixel values to the [0,1] range.
205- * @param {number} config.rescale_factor The factor to use for rescaling the image pixel values.
206- * @param {boolean} config.do_normalize Whether to normalize the image pixel values.
207- * @param {boolean} config.do_resize Whether to resize the image.
208- * @param {number} config.resample What method to use for resampling.
209- * @param {number} config.size The size to resize the image to.
210- */
211- constructor(config) {
212- super(config);
213-
214- this.image_mean = this.config.image_mean ?? this.config.mean;
215- this.image_std = this.config.image_std ?? this.config.std;
216-
217- this.resample = this.config.resample ?? 2; // 2 => bilinear
218- this.do_rescale = this.config.do_rescale ?? true;
219- this.rescale_factor = this.config.rescale_factor ?? (1 / 255);
220- this.do_normalize = this.config.do_normalize;
221-
222- this.do_resize = this.config.do_resize;
223- this.do_thumbnail = this.config.do_thumbnail;
224- this.size = this.config.size;
225- this.size_divisibility = this.config.size_divisibility ?? this.config.size_divisor;
226-
227- this.do_center_crop = this.config.do_center_crop;
228- this.crop_size = this.config.crop_size;
229- this.do_convert_rgb = this.config.do_convert_rgb ?? true;
230- this.do_crop_margin = this.config.do_crop_margin;
231-
232- this.pad_size = this.config.pad_size;
233- this.do_pad = this.config.do_pad;
234-
235- if (this.do_pad && !this.pad_size && this.size && this.size.width !== undefined && this.size.height !== undefined) {
236- // Should pad, but no pad size specified
237- // We infer the pad size from the resize size
238- this.pad_size = this.size
239- }
240- }
241-
242- /**
243- * Resize the image to make a thumbnail. The image is resized so that no dimension is larger than any
244- * corresponding dimension of the specified size.
245- * @param {RawImage} image The image to be resized.
246- * @param {{height:number, width:number}} size The size `{"height": h, "width": w}` to resize the image to.
247- * @param {string | 0 | 1 | 2 | 3 | 4 | 5} [resample=2] The resampling filter to use.
248- * @returns {Promise<RawImage>} The resized image.
249- */
250- async thumbnail(image, size, resample = 2) {
251- const input_height = image.height;
252- const input_width = image.width;
253-
254- const output_height = size.height;
255- const output_width = size.width;
256-
257- // We always resize to the smallest of either the input or output size.
258- let height = Math.min(input_height, output_height)
259- let width = Math.min(input_width, output_width)
260-
261- if (height === input_height && width === input_width) {
262- return image;
263- }
264- if (input_height > input_width) {
265- width = Math.floor(input_width * height / input_height);
266- } else if (input_width > input_height) {
267- height = Math.floor(input_height * width / input_width);
268- }
269- return await image.resize(width, height, { resample });
193+ /**
194+ * Constructs a new ImageFeatureExtractor instance.
195+ *
196+ * @param {Object} config The configuration for the feature extractor.
197+ * @param {number[]} config.image_mean The mean values for image normalization.
198+ * @param {number[]} config.image_std The standard deviation values for image normalization.
199+ * @param {boolean} config.do_rescale Whether to rescale the image pixel values to the [0,1] range.
200+ * @param {number} config.rescale_factor The factor to use for rescaling the image pixel values.
201+ * @param {boolean} config.do_normalize Whether to normalize the image pixel values.
202+ * @param {boolean} config.do_resize Whether to resize the image.
203+ * @param {number} config.resample What method to use for resampling.
204+ * @param {number} config.size The size to resize the image to.
205+ */
206+ constructor(config) {
207+ super(config);
208+
209+ this.image_mean = this.config.image_mean ?? this.config.mean;
210+ this.image_std = this.config.image_std ?? this.config.std;
211+
212+ this.resample = this.config.resample ?? 2; // 2 => bilinear
213+ this.do_rescale = this.config.do_rescale ?? true;
214+ this.rescale_factor = this.config.rescale_factor ?? 1 / 255;
215+ this.do_normalize = this.config.do_normalize;
216+
217+ this.do_resize = this.config.do_resize;
218+ this.do_thumbnail = this.config.do_thumbnail;
219+ this.size = this.config.size;
220+ this.size_divisibility =
221+ this.config.size_divisibility ?? this.config.size_divisor;
222+
223+ this.do_center_crop = this.config.do_center_crop;
224+ this.crop_size = this.config.crop_size;
225+ this.do_convert_rgb = this.config.do_convert_rgb ?? true;
226+ this.do_crop_margin = this.config.do_crop_margin;
227+
228+ this.pad_size = this.config.pad_size;
229+ this.do_pad = this.config.do_pad;
230+
231+ if (
232+ this.do_pad &&
233+ !this.pad_size &&
234+ this.size &&
235+ this.size.width !== undefined &&
236+ this.size.height !== undefined
237+ ) {
238+ // Should pad, but no pad size specified
239+ // We infer the pad size from the resize size
240+ this.pad_size = this.size;
270241 }
271-
272-
273- /**
274- * Crops the margin of the image. Gray pixels are considered margin (i.e., pixels with a value below the threshold).
275- * @param {RawImage} image The image to be cropped.
276- * @param {number} gray_threshold Value below which pixels are considered to be gray.
277- * @returns {Promise<RawImage>} The cropped image.
278- */
279- async crop_margin(image, gray_threshold = 200) {
280-
281- const gray_image = image.clone().grayscale();
282-
283- const minValue = min(gray_image.data)[0];
284- const maxValue = max(gray_image.data)[0];
285- const diff = maxValue - minValue;
286-
287- if (diff === 0) {
288- return image;
289- }
290-
291- const threshold = gray_threshold / 255;
292-
293- let x_min = gray_image.width, y_min = gray_image.height, x_max = 0, y_max = 0;
294- for (let j = 0; j < gray_image.height; ++j) {
295- const row = j * gray_image.width;
296- for (let i = 0; i < gray_image.width; ++i) {
297- if ((gray_image.data[row + i] - minValue) / diff < threshold) {
298- // We have a non-zero pixel, so we update the min/max values accordingly
299- x_min = Math.min(x_min, i);
300- y_min = Math.min(y_min, j);
301- x_max = Math.max(x_max, i);
302- y_max = Math.max(y_max, j);
303- }
304- }
305- }
306-
307- image = await image.crop([x_min, y_min, x_max, y_max]);
308- return image;
242+ }
243+
244+ /**
245+ * Resize the image to make a thumbnail. The image is resized so that no dimension is larger than any
246+ * corresponding dimension of the specified size.
247+ * @param {RawImage} image The image to be resized.
248+ * @param {{height:number, width:number}} size The size `{"height": h, "width": w}` to resize the image to.
249+ * @param {string | 0 | 1 | 2 | 3 | 4 | 5} [resample=2] The resampling filter to use.
250+ * @returns {Promise<RawImage>} The resized image.
251+ */
252+ async thumbnail(image, size, resample = 2) {
253+ const input_height = image.height;
254+ const input_width = image.width;
255+
256+ const output_height = size.height;
257+ const output_width = size.width;
258+
259+ // We always resize to the smallest of either the input or output size.
260+ let height = Math.min(input_height, output_height);
261+ let width = Math.min(input_width, output_width);
262+
263+ if (height === input_height && width === input_width) {
264+ return image;
309265 }
310-
311- /**
312- * Pad the image by a certain amount.
313- * @param {Float32Array} pixelData The pixel data to pad.
314- * @param {number[]} imgDims The dimensions of the image.
315- * @param {{width:number; height:number}|number} padSize The dimensions of the padded image.
316- * @param {Object} options The options for padding.
317- * @param {'constant'|'symmetric'} [options.mode='constant'] The type of padding to add.
318- * @param {boolean} [options.center=false] Whether to center the image.
319- * @param {number} [options.constant_values=0] The constant value to use for padding.
320- * @returns {[Float32Array, number[]]} The padded pixel data and image dimensions.
321- */
322- pad_image(pixelData, imgDims, padSize, {
323- mode = 'constant',
324- center = false,
325- constant_values = 0,
326- } = {}) {
327- const [imageWidth, imageHeight, imageChannels] = imgDims;
328-
329- let paddedImageWidth, paddedImageHeight;
330- if (typeof padSize === 'number') {
331- paddedImageWidth = padSize;
332- paddedImageHeight = padSize;
333- } else {
334- paddedImageWidth = padSize.width;
335- paddedImageHeight = padSize.height;
336- }
337-
338- // Only add padding if there is a difference in size
339- if (paddedImageWidth !== imageWidth || paddedImageHeight !== imageHeight) {
340- const paddedPixelData = new Float32Array(paddedImageWidth * paddedImageHeight * imageChannels);
341- if (Array.isArray(constant_values)) {
342- // Fill with constant values, cycling through the array
343- for (let i = 0; i < paddedPixelData.length; ++i) {
344- paddedPixelData[i] = constant_values[i % imageChannels];
345- }
346- } else if (constant_values !== 0) {
347- paddedPixelData.fill(constant_values);
348- }
349-
350- const [left, top] = center
351- ? [Math.floor((paddedImageWidth - imageWidth) / 2), Math.floor((paddedImageHeight - imageHeight) / 2)]
352- : [0, 0];
353-
354- // Copy the original image into the padded image
355- for (let i = 0; i < imageHeight; ++i) {
356- const a = (i + top) * paddedImageWidth;
357- const b = i * imageWidth;
358- for (let j = 0; j < imageWidth; ++j) {
359- const c = (a + j + left) * imageChannels;
360- const d = (b + j) * imageChannels;
361- for (let k = 0; k < imageChannels; ++k) {
362- paddedPixelData[c + k] = pixelData[d + k];
363- }
364- }
365- }
366-
367- if (mode === 'symmetric') {
368- if (center) {
369- throw new Error('`center` padding is not supported when `mode` is set to `symmetric`.');
370- // TODO: Implement this
371- }
372- const h1 = imageHeight - 1;
373- const w1 = imageWidth - 1;
374- for (let i = 0; i < paddedImageHeight; ++i) {
375- const a = i * paddedImageWidth;
376- const b = calculateReflectOffset(i, h1) * imageWidth;
377-
378- for (let j = 0; j < paddedImageWidth; ++j) {
379- if (i < imageHeight && j < imageWidth) continue; // Do not overwrite original image
380- const c = (a + j) * imageChannels;
381- const d = (b + calculateReflectOffset(j, w1)) * imageChannels;
382-
383- // Copy channel-wise
384- for (let k = 0; k < imageChannels; ++k) {
385- paddedPixelData[c + k] = pixelData[d + k];
386- }
387- }
388- }
389- }
390-
391-
392- // Update pixel data and image dimensions
393- pixelData = paddedPixelData;
394- imgDims = [paddedImageHeight, paddedImageWidth, imageChannels]
395- }
396- return [pixelData, imgDims];
266+ if (input_height > input_width) {
267+ width = Math.floor((input_width * height) / input_height);
268+ } else if (input_width > input_height) {
269+ height = Math.floor((input_height * width) / input_width);
397270 }
398-
399- /**
400- * Rescale the image' pixel values by `this.rescale_factor`.
401- * @param {Float32Array} pixelData The pixel data to rescale.
402- * @returns {void}
403- */
404- rescale(pixelData) {
405- for (let i = 0; i < pixelData.length; ++i) {
406- pixelData[i] = this.rescale_factor * pixelData[i];
407- }
271+ return await image.resize(width, height, { resample });
272+ }
273+
274+ /**
275+ * Crops the margin of the image. Gray pixels are considered margin (i.e., pixels with a value below the threshold).
276+ * @param {RawImage} image The image to be cropped.
277+ * @param {number} gray_threshold Value below which pixels are considered to be gray.
278+ * @returns {Promise<RawImage>} The cropped image.
279+ */
280+ async crop_margin(image, gray_threshold = 200) {
281+ const gray_image = image.clone().grayscale();
282+
283+ const minValue = min(gray_image.data)[0];
284+ const maxValue = max(gray_image.data)[0];
285+ const diff = maxValue - minValue;
286+
287+ if (diff === 0) {
288+ return image;
408289 }
409290
410- /**
411- * Find the target (width, height) dimension of the output image after
412- * resizing given the input image and the desired size.
413- * @param {RawImage} image The image to resize.
414- * @param {any} size The size to use for resizing the image.
415- * @returns {[number, number]} The target (width, height) dimension of the output image after resizing.
416- */
417- get_resize_output_image_size(image, size) {
418- // `size` comes in many forms, so we need to handle them all here:
419- // 1. `size` is an integer, in which case we resize the image to be a square
420-
421- const [srcWidth, srcHeight] = image.size;
422-
423- let shortest_edge;
424- let longest_edge;
425-
426- if (this.do_thumbnail) {
427- // NOTE: custom logic for `Donut` models
428- const { height, width } = size;
429- shortest_edge = Math.min(height, width)
430- }
431- // Support both formats for backwards compatibility
432- else if (Number.isInteger(size)) {
433- shortest_edge = size;
434- longest_edge = this.config.max_size ?? shortest_edge;
435-
436- } else if (size !== undefined) {
437- // Extract known properties from `size`
438- shortest_edge = size.shortest_edge;
439- longest_edge = size.longest_edge;
440- }
441-
442- // If `longest_edge` and `shortest_edge` are set, maintain aspect ratio and resize to `shortest_edge`
443- // while keeping the largest dimension <= `longest_edge`
444- if (shortest_edge !== undefined || longest_edge !== undefined) {
445- // http://opensourcehacker.com/2011/12/01/calculate-aspect-ratio-conserving-resize-for-images-in-javascript/
446- // Try resize so that shortest edge is `shortest_edge` (target)
447- const shortResizeFactor = shortest_edge === undefined
448- ? 1 // If `shortest_edge` is not set, don't upscale
449- : Math.max(shortest_edge / srcWidth, shortest_edge / srcHeight);
450-
451- const newWidth = srcWidth * shortResizeFactor;
452- const newHeight = srcHeight * shortResizeFactor;
453-
454- // The new width and height might be greater than `longest_edge`, so
455- // we downscale again to ensure the largest dimension is `longest_edge`
456- const longResizeFactor = longest_edge === undefined
457- ? 1 // If `longest_edge` is not set, don't downscale
458- : Math.min(longest_edge / newWidth, longest_edge / newHeight);
459-
460- // To avoid certain floating point precision issues, we round to 2 decimal places
461- const finalWidth = Math.floor(Number((newWidth * longResizeFactor).toFixed(2)));
462- const finalHeight = Math.floor(Number((newHeight * longResizeFactor).toFixed(2)));
463-
464- return [finalWidth, finalHeight];
465-
466- } else if (size !== undefined && size.width !== undefined && size.height !== undefined) {
467- // If `width` and `height` are set, resize to those dimensions
468- return [size.width, size.height];
469-
470- } else if (this.size_divisibility !== undefined) {
471- // Rounds the height and width down to the closest multiple of size_divisibility
472- const newWidth = Math.floor(srcWidth / this.size_divisibility) * this.size_divisibility;
473- const newHeight = Math.floor(srcHeight / this.size_divisibility) * this.size_divisibility;
474- return [newWidth, newHeight];
475- } else {
476- throw new Error(`Could not resize image due to unsupported \`this.size\` option in config: ${JSON.stringify(size)}`);
291+ const threshold = gray_threshold / 255;
292+
293+ let x_min = gray_image.width,
294+ y_min = gray_image.height,
295+ x_max = 0,
296+ y_max = 0;
297+ for (let j = 0; j < gray_image.height; ++j) {
298+ const row = j * gray_image.width;
299+ for (let i = 0; i < gray_image.width; ++i) {
300+ if ((gray_image.data[row + i] - minValue) / diff < threshold) {
301+ // We have a non-zero pixel, so we update the min/max values accordingly
302+ x_min = Math.min(x_min, i);
303+ y_min = Math.min(y_min, j);
304+ x_max = Math.max(x_max, i);
305+ y_max = Math.max(y_max, j);
477306 }
307+ }
478308 }
479309
480- /**
481- * Resizes the image.
482- * @param {RawImage} image The image to resize.
483- * @returns {Promise<RawImage>} The resized image.
484- */
485- async resize(image) {
486- const [newWidth, newHeight] = this.get_resize_output_image_size(image, this.size);
487- return await image.resize(newWidth, newHeight, {
488- resample: this.resample,
489- });
310+ image = await image.crop([x_min, y_min, x_max, y_max]);
311+ return image;
312+ }
313+
314+ /**
315+ * Pad the image by a certain amount.
316+ * @param {Float32Array} pixelData The pixel data to pad.
317+ * @param {number[]} imgDims The dimensions of the image.
318+ * @param {{width:number; height:number}|number} padSize The dimensions of the padded image.
319+ * @param {Object} options The options for padding.
320+ * @param {'constant'|'symmetric'} [options.mode='constant'] The type of padding to add.
321+ * @param {boolean} [options.center=false] Whether to center the image.
322+ * @param {number} [options.constant_values=0] The constant value to use for padding.
323+ * @returns {[Float32Array, number[]]} The padded pixel data and image dimensions.
324+ */
325+ pad_image(
326+ pixelData,
327+ imgDims,
328+ padSize,
329+ { mode = "constant", center = false, constant_values = 0 } = {},
330+ ) {
331+ const [imageWidth, imageHeight, imageChannels] = imgDims;
332+
333+ let paddedImageWidth, paddedImageHeight;
334+ if (typeof padSize === "number") {
335+ paddedImageWidth = padSize;
336+ paddedImageHeight = padSize;
337+ } else {
338+ paddedImageWidth = padSize.width;
339+ paddedImageHeight = padSize.height;
490340 }
491341
492- /**
493- * @typedef {object} PreprocessedImage
494- * @property {HeightWidth} original_size The original size of the image.
495- * @property {HeightWidth} reshaped_input_size The reshaped input size of the image.
496- * @property {Tensor} pixel_values The pixel values of the preprocessed image.
497- */
498-
499- /**
500- * Preprocesses the given image.
501- *
502- * @param {RawImage} image The image to preprocess.
503- * @param {Object} overrides The overrides for the preprocessing options.
504- * @returns {Promise<PreprocessedImage>} The preprocessed image.
505- */
506- async preprocess(image, {
507- do_normalize = null,
508- do_pad = null,
509- do_convert_rgb = null,
510- do_convert_grayscale = null,
511- } = {}) {
512- if (this.do_crop_margin) {
513- // NOTE: Specific to nougat processors. This is done before resizing,
514- // and can be interpreted as a pre-preprocessing step.
515- image = await this.crop_margin(image);
516- }
517-
518- const [srcWidth, srcHeight] = image.size; // original image size
519-
520- // Convert image to RGB if specified in config.
521- if (do_convert_rgb ?? this.do_convert_rgb) {
522- image = image.rgb();
523- } else if (do_convert_grayscale) {
524- image = image.grayscale();
342+ // Only add padding if there is a difference in size
343+ if (paddedImageWidth !== imageWidth || paddedImageHeight !== imageHeight) {
344+ const paddedPixelData = new Float32Array(
345+ paddedImageWidth * paddedImageHeight * imageChannels,
346+ );
347+ if (Array.isArray(constant_values)) {
348+ // Fill with constant values, cycling through the array
349+ for (let i = 0; i < paddedPixelData.length; ++i) {
350+ paddedPixelData[i] = constant_values[i % imageChannels];
525351 }
526-
527- // TODO:
528- // For efficiency reasons, it might be best to merge the resize and center crop operations into one.
529-
530- // Resize all images
531- if (this.do_resize) {
532- image = await this.resize(image);
352+ } else if (constant_values !== 0) {
353+ paddedPixelData.fill(constant_values);
354+ }
355+
356+ const [left, top] = center
357+ ? [
358+ Math.floor((paddedImageWidth - imageWidth) / 2),
359+ Math.floor((paddedImageHeight - imageHeight) / 2),
360+ ]
361+ : [0, 0];
362+
363+ // Copy the original image into the padded image
364+ for (let i = 0; i < imageHeight; ++i) {
365+ const a = (i + top) * paddedImageWidth;
366+ const b = i * imageWidth;
367+ for (let j = 0; j < imageWidth; ++j) {
368+ const c = (a + j + left) * imageChannels;
369+ const d = (b + j) * imageChannels;
370+ for (let k = 0; k < imageChannels; ++k) {
371+ paddedPixelData[c + k] = pixelData[d + k];
372+ }
533373 }
534-
535- // Resize the image using thumbnail method.
536- if (this.do_thumbnail) {
537- image = await this.thumbnail(image, this.size, this.resample);
374+ }
375+
376+ if (mode === "symmetric") {
377+ if (center) {
378+ throw new Error(
379+ "`center` padding is not supported when `mode` is set to `symmetric`.",
380+ );
381+ // TODO: Implement this
538382 }
539-
540- if (this.do_center_crop) {
541-
542- let crop_width;
543- let crop_height;
544- if (Number.isInteger(this.crop_size)) {
545- crop_width = this.crop_size;
546- crop_height = this.crop_size;
547- } else {
548- crop_width = this.crop_size.width;
549- crop_height = this.crop_size.height;
383+ const h1 = imageHeight - 1;
384+ const w1 = imageWidth - 1;
385+ for (let i = 0; i < paddedImageHeight; ++i) {
386+ const a = i * paddedImageWidth;
387+ const b = calculateReflectOffset(i, h1) * imageWidth;
388+
389+ for (let j = 0; j < paddedImageWidth; ++j) {
390+ if (i < imageHeight && j < imageWidth) continue; // Do not overwrite original image
391+ const c = (a + j) * imageChannels;
392+ const d = (b + calculateReflectOffset(j, w1)) * imageChannels;
393+
394+ // Copy channel-wise
395+ for (let k = 0; k < imageChannels; ++k) {
396+ paddedPixelData[c + k] = pixelData[d + k];
550397 }
551-
552- image = await image.center_crop(crop_width, crop_height);
398+ }
553399 }
400+ }
401+
402+ // Update pixel data and image dimensions
403+ pixelData = paddedPixelData;
404+ imgDims = [paddedImageHeight, paddedImageWidth, imageChannels];
405+ }
406+ return [pixelData, imgDims];
407+ }
408+
409+ /**
410+ * Rescale the image' pixel values by `this.rescale_factor`.
411+ * @param {Float32Array} pixelData The pixel data to rescale.
412+ * @returns {void}
413+ */
414+ rescale(pixelData) {
415+ for (let i = 0; i < pixelData.length; ++i) {
416+ pixelData[i] = this.rescale_factor * pixelData[i];
417+ }
418+ }
419+
420+ /**
421+ * Find the target (width, height) dimension of the output image after
422+ * resizing given the input image and the desired size.
423+ * @param {RawImage} image The image to resize.
424+ * @param {any} size The size to use for resizing the image.
425+ * @returns {[number, number]} The target (width, height) dimension of the output image after resizing.
426+ */
427+ get_resize_output_image_size(image, size) {
428+ // `size` comes in many forms, so we need to handle them all here:
429+ // 1. `size` is an integer, in which case we resize the image to be a square
430+
431+ const [srcWidth, srcHeight] = image.size;
432+
433+ let shortest_edge;
434+ let longest_edge;
435+
436+ if (this.do_thumbnail) {
437+ // NOTE: custom logic for `Donut` models
438+ const { height, width } = size;
439+ shortest_edge = Math.min(height, width);
440+ }
441+ // Support both formats for backwards compatibility
442+ else if (Number.isInteger(size)) {
443+ shortest_edge = size;
444+ longest_edge = this.config.max_size ?? shortest_edge;
445+ } else if (size !== undefined) {
446+ // Extract known properties from `size`
447+ shortest_edge = size.shortest_edge;
448+ longest_edge = size.longest_edge;
449+ }
554450
555- /** @type {HeightWidth} */
556- const reshaped_input_size = [image.height, image.width];
557-
558- let pixelData = Float32Array.from(image.data);
559- let imgDims = [image.height, image.width, image.channels];
451+ // If `longest_edge` and `shortest_edge` are set, maintain aspect ratio and resize to `shortest_edge`
452+ // while keeping the largest dimension <= `longest_edge`
453+ if (shortest_edge !== undefined || longest_edge !== undefined) {
454+ // http://opensourcehacker.com/2011/12/01/calculate-aspect-ratio-conserving-resize-for-images-in-javascript/
455+ // Try resize so that shortest edge is `shortest_edge` (target)
456+ const shortResizeFactor =
457+ shortest_edge === undefined
458+ ? 1 // If `shortest_edge` is not set, don't upscale
459+ : Math.max(shortest_edge / srcWidth, shortest_edge / srcHeight);
460+
461+ const newWidth = srcWidth * shortResizeFactor;
462+ const newHeight = srcHeight * shortResizeFactor;
463+
464+ // The new width and height might be greater than `longest_edge`, so
465+ // we downscale again to ensure the largest dimension is `longest_edge`
466+ const longResizeFactor =
467+ longest_edge === undefined
468+ ? 1 // If `longest_edge` is not set, don't downscale
469+ : Math.min(longest_edge / newWidth, longest_edge / newHeight);
470+
471+ // To avoid certain floating point precision issues, we round to 2 decimal places
472+ const finalWidth = Math.floor(
473+ Number((newWidth * longResizeFactor).toFixed(2)),
474+ );
475+ const finalHeight = Math.floor(
476+ Number((newHeight * longResizeFactor).toFixed(2)),
477+ );
478+
479+ return [finalWidth, finalHeight];
480+ } else if (
481+ size !== undefined &&
482+ size.width !== undefined &&
483+ size.height !== undefined
484+ ) {
485+ // If `width` and `height` are set, resize to those dimensions
486+ return [size.width, size.height];
487+ } else if (this.size_divisibility !== undefined) {
488+ // Rounds the height and width down to the closest multiple of size_divisibility
489+ const newWidth =
490+ Math.floor(srcWidth / this.size_divisibility) * this.size_divisibility;
491+ const newHeight =
492+ Math.floor(srcHeight / this.size_divisibility) * this.size_divisibility;
493+ return [newWidth, newHeight];
494+ } else {
495+ throw new Error(
496+ `Could not resize image due to unsupported \`this.size\` option in config: ${JSON.stringify(size)}`,
497+ );
498+ }
499+ }
500+
501+ /**
502+ * Resizes the image.
503+ * @param {RawImage} image The image to resize.
504+ * @returns {Promise<RawImage>} The resized image.
505+ */
506+ async resize(image) {
507+ const [newWidth, newHeight] = this.get_resize_output_image_size(
508+ image,
509+ this.size,
510+ );
511+ return await image.resize(newWidth, newHeight, {
512+ resample: this.resample,
513+ });
514+ }
515+
516+ /**
517+ * @typedef {object} PreprocessedImage
518+ * @property {HeightWidth} original_size The original size of the image.
519+ * @property {HeightWidth} reshaped_input_size The reshaped input size of the image.
520+ * @property {Tensor} pixel_values The pixel values of the preprocessed image.
521+ */
522+
523+ /**
524+ * Preprocesses the given image.
525+ *
526+ * @param {RawImage} image The image to preprocess.
527+ * @param {Object} overrides The overrides for the preprocessing options.
528+ * @returns {Promise<PreprocessedImage>} The preprocessed image.
529+ */
530+ async preprocess(
531+ image,
532+ {
533+ do_normalize = null,
534+ do_pad = null,
535+ do_convert_rgb = null,
536+ do_convert_grayscale = null,
537+ } = {},
538+ ) {
539+ if (this.do_crop_margin) {
540+ // NOTE: Specific to nougat processors. This is done before resizing,
541+ // and can be interpreted as a pre-preprocessing step.
542+ image = await this.crop_margin(image);
543+ }
560544
561- if (this.do_rescale) {
562- this.rescale(pixelData);
563- }
545+ const [srcWidth, srcHeight] = image.size; // original image size
564546
565- if (do_normalize ?? this.do_normalize) {
566- let image_mean = this.image_mean;
567- if (!Array.isArray(this.image_mean)) {
568- image_mean = new Array(image.channels).fill(image_mean);
569- }
547+ // Convert image to RGB if specified in config.
548+ if (do_convert_rgb ?? this.do_convert_rgb) {
549+ image = image.rgb();
550+ } else if (do_convert_grayscale) {
551+ image = image.grayscale();
552+ }
570553
571- let image_std = this.image_std;
572- if (!Array.isArray(this.image_std)) {
573- image_std = new Array(image.channels).fill(image_mean);
574- }
554+ // TODO:
555+ // For efficiency reasons, it might be best to merge the resize and center crop operations into one.
575556
576- if (image_mean.length !== image.channels || image_std.length !== image.channels) {
577- throw new Error(`When set to arrays, the length of \`image_mean\` (${image_mean.length}) and \`image_std\` (${image_std.length}) must match the number of channels in the image (${image.channels}).`);
578- }
557+ // Resize all images
558+ if (this.do_resize) {
559+ image = await this.resize(image);
560+ }
579561
580- for (let i = 0; i < pixelData.length; i += image.channels) {
581- for (let j = 0; j < image.channels; ++j) {
582- pixelData[i + j] = (pixelData[i + j] - this.image_mean[j]) / this.image_std[j];
583- }
584- }
585- }
562+ // Resize the image using thumbnail method.
563+ if (this.do_thumbnail) {
564+ image = await this.thumbnail(image, this.size, this.resample);
565+ }
586566
587- // do padding after rescaling/normalizing
588- if (do_pad ?? (this.do_pad && this.pad_size)) {
589- const padded = this.pad_image(pixelData, [image.width, image.height, image.channels], this.pad_size);
590- [pixelData, imgDims] = padded; // Update pixel data and image dimensions
591- }
567+ if (this.do_center_crop) {
568+ let crop_width;
569+ let crop_height;
570+ if (Number.isInteger(this.crop_size)) {
571+ crop_width = this.crop_size;
572+ crop_height = this.crop_size;
573+ } else {
574+ crop_width = this.crop_size.width;
575+ crop_height = this.crop_size.height;
576+ }
577+
578+ image = await image.center_crop(crop_width, crop_height);
579+ }
592580
593- // Create HWC tensor
594- const img = new Tensor('float32', pixelData, imgDims);
581+ /** @type {HeightWidth} */
582+ const reshaped_input_size = [image.height, image.width];
595583
596- // convert to channel dimension format:
597- const transposed = transpose(img, [2, 0, 1]); // hwc -> chw
584+ let pixelData = Float32Array.from(image.data);
585+ let imgDims = [image.height, image.width, image.channels];
598586
599- return {
600- original_size: [srcHeight, srcWidth],
601- reshaped_input_size: reshaped_input_size,
602- pixel_values: transposed,
603- }
587+ if (this.do_rescale) {
588+ this.rescale(pixelData);
604589 }
605590
606- /**
607- * Calls the feature extraction process on an array of images,
608- * preprocesses each image, and concatenates the resulting
609- * features into a single Tensor.
610- * @param {RawImage[]} images The image(s) to extract features from.
611- * @param {...any} args Additional arguments.
612- * @returns {Promise<ImageFeatureExtractorResult>} An object containing the concatenated pixel values (and other metadata) of the preprocessed images.
613- */
614- async _call(images, ...args) {
615- if (!Array.isArray(images)) {
616- images = [images];
591+ if (do_normalize ?? this.do_normalize) {
592+ let image_mean = this.image_mean;
593+ if (!Array.isArray(this.image_mean)) {
594+ image_mean = new Array(image.channels).fill(image_mean);
595+ }
596+
597+ let image_std = this.image_std;
598+ if (!Array.isArray(this.image_std)) {
599+ image_std = new Array(image.channels).fill(image_mean);
600+ }
601+
602+ if (
603+ image_mean.length !== image.channels ||
604+ image_std.length !== image.channels
605+ ) {
606+ throw new Error(
607+ `When set to arrays, the length of \`image_mean\` (${image_mean.length}) and \`image_std\` (${image_std.length}) must match the number of channels in the image (${image.channels}).`,
608+ );
609+ }
610+
611+ for (let i = 0; i < pixelData.length; i += image.channels) {
612+ for (let j = 0; j < image.channels; ++j) {
613+ pixelData[i + j] =
614+ (pixelData[i + j] - this.image_mean[j]) / this.image_std[j];
617615 }
618- /** @type {PreprocessedImage[]} */
619- const imageData = await Promise.all(images.map(x => this.preprocess(x)));
620-
621- // Stack pixel values
622- const pixel_values = stack(imageData.map(x => x.pixel_values), 0);
623-
624- return {
625- pixel_values: pixel_values,
626-
627- // Original sizes of images
628- original_sizes: imageData.map(x => x.original_size),
616+ }
617+ }
629618
630- // Reshaped sizes of images, before padding or cropping
631- reshaped_input_sizes: imageData.map(x => x.reshaped_input_size),
632- }
619+ // do padding after rescaling/normalizing
620+ if (do_pad ?? (this.do_pad && this.pad_size)) {
621+ const padded = this.pad_image(
622+ pixelData,
623+ [image.width, image.height, image.channels],
624+ this.pad_size,
625+ );
626+ [pixelData, imgDims] = padded; // Update pixel data and image dimensions
633627 }
634628
629+ // Create HWC tensor
630+ const img = new Tensor("float32", pixelData, imgDims);
631+
632+ // convert to channel dimension format:
633+ const transposed = transpose(img, [2, 0, 1]); // hwc -> chw
634+
635+ return {
636+ original_size: [srcHeight, srcWidth],
637+ reshaped_input_size: reshaped_input_size,
638+ pixel_values: transposed,
639+ };
640+ }
641+
642+ /**
643+ * Calls the feature extraction process on an array of images,
644+ * preprocesses each image, and concatenates the resulting
645+ * features into a single Tensor.
646+ * @param {RawImage[]} images The image(s) to extract features from.
647+ * @param {...any} args Additional arguments.
648+ * @returns {Promise<ImageFeatureExtractorResult>} An object containing the concatenated pixel values (and other metadata) of the preprocessed images.
649+ */
650+ async _call(images, ...args) {
651+ if (!Array.isArray(images)) {
652+ images = [images];
653+ }
654+ /** @type {PreprocessedImage[]} */
655+ const imageData = await Promise.all(images.map((x) => this.preprocess(x)));
656+
657+ // Stack pixel values
658+ const pixel_values = stack(
659+ imageData.map((x) => x.pixel_values),
660+ 0,
661+ );
662+
663+ return {
664+ pixel_values: pixel_values,
665+
666+ // Original sizes of images
667+ original_sizes: imageData.map((x) => x.original_size),
668+
669+ // Reshaped sizes of images, before padding or cropping
670+ reshaped_input_sizes: imageData.map((x) => x.reshaped_input_size),
671+ };
672+ }
635673 }
636674
637675 export class SegformerFeatureExtractor extends ImageFeatureExtractor {
676+ /**
677+ * Converts the output of `SegformerForSemanticSegmentation` into semantic segmentation maps.
678+ * @param {*} outputs Raw outputs of the model.
679+ * @param {number[][]} [target_sizes=null] List of tuples corresponding to the requested final size
680+ * (height, width) of each prediction. If unset, predictions will not be resized.
681+ * @returns {{segmentation: Tensor; labels: number[]}[]} The semantic segmentation maps.
682+ */
683+ post_process_semantic_segmentation(outputs, target_sizes = null) {
684+ const logits = outputs.logits;
685+ const batch_size = logits.dims[0];
638686
639- /**
640- * Converts the output of `SegformerForSemanticSegmentation` into semantic segmentation maps.
641- * @param {*} outputs Raw outputs of the model.
642- * @param {number[][]} [target_sizes=null] List of tuples corresponding to the requested final size
643- * (height, width) of each prediction. If unset, predictions will not be resized.
644- * @returns {{segmentation: Tensor; labels: number[]}[]} The semantic segmentation maps.
645- */
646- post_process_semantic_segmentation(outputs, target_sizes = null) {
647-
648- const logits = outputs.logits;
649- const batch_size = logits.dims[0];
650-
651- if (target_sizes !== null && target_sizes.length !== batch_size) {
652- throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits")
653- }
654-
655- const toReturn = [];
656- for (let i = 0; i < batch_size; ++i) {
657- const target_size = target_sizes !== null ? target_sizes[i] : null;
658-
659- let data = logits[i];
660-
661- // 1. If target_size is not null, we need to resize the masks to the target size
662- if (target_size !== null) {
663- // resize the masks to the target size
664- data = interpolate(data, target_size, 'bilinear', false);
665- }
666- const [height, width] = target_size ?? data.dims.slice(-2);
667-
668- const segmentation = new Tensor(
669- 'int32',
670- new Int32Array(height * width),
671- [height, width]
672- );
673-
674- // Buffer to store current largest value
675- const buffer = data[0].data;
676- for (let j = 1; j < data.dims[0]; ++j) {
677- const row = data[j].data;
678- for (let k = 0; k < row.length; ++k) {
679- if (row[k] > buffer[k]) {
680- buffer[k] = row[k];
681- segmentation.data[k] = j;
682- }
683- }
684- }
685-
686- // Store which objects have labels
687- // This is much more efficient that creating a set of the final values
688- const hasLabel = new Array(data.dims[0]);
689- const out = segmentation.data;
690- for (let j = 0; j < out.length; ++j) {
691- const index = out[j];
692- hasLabel[index] = index;
693- }
694- /** @type {number[]} The unique list of labels that were detected */
695- const labels = hasLabel.filter(x => x !== undefined);
687+ if (target_sizes !== null && target_sizes.length !== batch_size) {
688+ throw Error(
689+ "Make sure that you pass in as many target sizes as the batch dimension of the logits",
690+ );
691+ }
696692
697- toReturn.push({ segmentation, labels });
693+ const toReturn = [];
694+ for (let i = 0; i < batch_size; ++i) {
695+ const target_size = target_sizes !== null ? target_sizes[i] : null;
696+
697+ let data = logits[i];
698+
699+ // 1. If target_size is not null, we need to resize the masks to the target size
700+ if (target_size !== null) {
701+ // resize the masks to the target size
702+ data = interpolate(data, target_size, "bilinear", false);
703+ }
704+ const [height, width] = target_size ?? data.dims.slice(-2);
705+
706+ const segmentation = new Tensor("int32", new Int32Array(height * width), [
707+ height,
708+ width,
709+ ]);
710+
711+ // Buffer to store current largest value
712+ const buffer = data[0].data;
713+ for (let j = 1; j < data.dims[0]; ++j) {
714+ const row = data[j].data;
715+ for (let k = 0; k < row.length; ++k) {
716+ if (row[k] > buffer[k]) {
717+ buffer[k] = row[k];
718+ segmentation.data[k] = j;
719+ }
698720 }
699- return toReturn;
721+ }
722+
723+ // Store which objects have labels
724+ // This is much more efficient that creating a set of the final values
725+ const hasLabel = new Array(data.dims[0]);
726+ const out = segmentation.data;
727+ for (let j = 0; j < out.length; ++j) {
728+ const index = out[j];
729+ hasLabel[index] = index;
730+ }
731+ /** @type {number[]} The unique list of labels that were detected */
732+ const labels = hasLabel.filter((x) => x !== undefined);
733+
734+ toReturn.push({ segmentation, labels });
700735 }
736+ return toReturn;
737+ }
701738 }
702-export class BitImageProcessor extends ImageFeatureExtractor { }
703-export class DPTFeatureExtractor extends ImageFeatureExtractor { }
704-export class GLPNFeatureExtractor extends ImageFeatureExtractor { }
705-export class CLIPFeatureExtractor extends ImageFeatureExtractor { }
706-export class ChineseCLIPFeatureExtractor extends ImageFeatureExtractor { }
707-export class SiglipImageProcessor extends ImageFeatureExtractor { }
739+export class BitImageProcessor extends ImageFeatureExtractor {}
740+export class DPTFeatureExtractor extends ImageFeatureExtractor {}
741+export class GLPNFeatureExtractor extends ImageFeatureExtractor {}
742+export class CLIPFeatureExtractor extends ImageFeatureExtractor {}
743+export class ChineseCLIPFeatureExtractor extends ImageFeatureExtractor {}
744+export class SiglipImageProcessor extends ImageFeatureExtractor {}
708745 export class ConvNextFeatureExtractor extends ImageFeatureExtractor {
709- constructor(config) {
710- super(config);
711-
712- /**
713- * Percentage of the image to crop. Only has an effect if this.size < 384.
714- */
715- this.crop_pct = this.config.crop_pct ?? (224 / 256);
716- }
717-
718- async resize(image) {
719- const shortest_edge = this.size?.shortest_edge;
720- if (shortest_edge === undefined) {
721- throw new Error(`Size dictionary must contain 'shortest_edge' key.`);
722- }
746+ constructor(config) {
747+ super(config);
723748
724- if (shortest_edge < 384) {
725- // maintain same ratio, resizing shortest edge to shortest_edge/crop_pct
726- const resize_shortest_edge = Math.floor(shortest_edge / this.crop_pct);
727-
728- const [newWidth, newHeight] = this.get_resize_output_image_size(image, {
729- shortest_edge: resize_shortest_edge,
730- });
731-
732- image = await image.resize(newWidth, newHeight, {
733- resample: this.resample,
734- });
735-
736- // then crop to (shortest_edge, shortest_edge)
737- image = await image.center_crop(shortest_edge, shortest_edge);
738- } else {
739- // warping (no cropping) when evaluated at 384 or larger
740- image = await image.resize(shortest_edge, shortest_edge, {
741- resample: this.resample,
742- });
743- }
749+ /**
750+ * Percentage of the image to crop. Only has an effect if this.size < 384.
751+ */
752+ this.crop_pct = this.config.crop_pct ?? 224 / 256;
753+ }
754+
755+ async resize(image) {
756+ const shortest_edge = this.size?.shortest_edge;
757+ if (shortest_edge === undefined) {
758+ throw new Error(`Size dictionary must contain 'shortest_edge' key.`);
759+ }
744760
745- return image;
761+ if (shortest_edge < 384) {
762+ // maintain same ratio, resizing shortest edge to shortest_edge/crop_pct
763+ const resize_shortest_edge = Math.floor(shortest_edge / this.crop_pct);
764+
765+ const [newWidth, newHeight] = this.get_resize_output_image_size(image, {
766+ shortest_edge: resize_shortest_edge,
767+ });
768+
769+ image = await image.resize(newWidth, newHeight, {
770+ resample: this.resample,
771+ });
772+
773+ // then crop to (shortest_edge, shortest_edge)
774+ image = await image.center_crop(shortest_edge, shortest_edge);
775+ } else {
776+ // warping (no cropping) when evaluated at 384 or larger
777+ image = await image.resize(shortest_edge, shortest_edge, {
778+ resample: this.resample,
779+ });
746780 }
781+
782+ return image;
783+ }
747784 }
748-export class ConvNextImageProcessor extends ConvNextFeatureExtractor { } // NOTE extends ConvNextFeatureExtractor
749-export class ViTFeatureExtractor extends ImageFeatureExtractor { }
750-export class ViTImageProcessor extends ImageFeatureExtractor { }
751-
752-export class MobileViTFeatureExtractor extends ImageFeatureExtractor { }
785+export class ConvNextImageProcessor extends ConvNextFeatureExtractor {} // NOTE extends ConvNextFeatureExtractor
786+export class ViTFeatureExtractor extends ImageFeatureExtractor {}
787+export class ViTImageProcessor extends ImageFeatureExtractor {}
788+
789+export class MobileViTFeatureExtractor extends ImageFeatureExtractor {}
753790 export class OwlViTFeatureExtractor extends ImageFeatureExtractor {
754- /** @type {post_process_object_detection} */
755- post_process_object_detection(...args) {
756- return post_process_object_detection(...args);
757- }
791+ /** @type {post_process_object_detection} */
792+ post_process_object_detection(...args) {
793+ return post_process_object_detection(...args);
794+ }
758795 }
759-export class DeiTFeatureExtractor extends ImageFeatureExtractor { }
760-export class BeitFeatureExtractor extends ImageFeatureExtractor { }
796+export class DeiTFeatureExtractor extends ImageFeatureExtractor {}
797+export class BeitFeatureExtractor extends ImageFeatureExtractor {}
761798 export class DonutFeatureExtractor extends ImageFeatureExtractor {
762- pad_image(pixelData, imgDims, padSize, options = {}) {
763- const [imageWidth, imageHeight, imageChannels] = imgDims;
764-
765- let image_mean = this.image_mean;
766- if (!Array.isArray(this.image_mean)) {
767- image_mean = new Array(imageChannels).fill(image_mean);
768- }
799+ pad_image(pixelData, imgDims, padSize, options = {}) {
800+ const [imageWidth, imageHeight, imageChannels] = imgDims;
801+
802+ let image_mean = this.image_mean;
803+ if (!Array.isArray(this.image_mean)) {
804+ image_mean = new Array(imageChannels).fill(image_mean);
805+ }
769806
770- let image_std = this.image_std;
771- if (!Array.isArray(image_std)) {
772- image_std = new Array(imageChannels).fill(image_mean);
773- }
807+ let image_std = this.image_std;
808+ if (!Array.isArray(image_std)) {
809+ image_std = new Array(imageChannels).fill(image_mean);
810+ }
774811
775- const constant_values = image_mean.map((x, i) => - x / this.image_std[i]);
812+ const constant_values = image_mean.map((x, i) => -x / this.image_std[i]);
776813
777- return super.pad_image(pixelData, imgDims, padSize, {
778- center: true,
814+ return super.pad_image(pixelData, imgDims, padSize, {
815+ center: true,
779816
780- // Since normalization is done after padding, we need to use certain constant values to ensure the same behaviour is observed.
781- // For more information, see https://github.com/huggingface/transformers/blob/main/src/transformers/models/donut/image_processing_donut.py#L433-L451
782- constant_values: constant_values,
783- ...options,
784- });
785- }
817+ // Since normalization is done after padding, we need to use certain constant values to ensure the same behaviour is observed.
818+ // For more information, see https://github.com/huggingface/transformers/blob/main/src/transformers/models/donut/image_processing_donut.py#L433-L451
819+ constant_values: constant_values,
820+ ...options,
821+ });
822+ }
786823 }
787-export class NougatImageProcessor extends DonutFeatureExtractor { } // NOTE extends DonutFeatureExtractor
824+export class NougatImageProcessor extends DonutFeatureExtractor {} // NOTE extends DonutFeatureExtractor
788825
789826 /**
790827 * @typedef {object} DetrFeatureExtractorResultProps
@@ -798,323 +835,336 @@
798835 * @extends ImageFeatureExtractor
799836 */
800837 export class DetrFeatureExtractor extends ImageFeatureExtractor {
801- /**
802- * Calls the feature extraction process on an array of images, preprocesses
803- * each image, and concatenates the resulting features into a single Tensor.
804- * @param {RawImage[]} images The image(s) to extract features from.
805- * @returns {Promise<DetrFeatureExtractorResult>} An object containing the concatenated pixel values of the preprocessed images.
806- */
807- async _call(images) {
808- const result = await super._call(images);
809-
810- // TODO support differently-sized images, for now assume all images are the same size.
811- // TODO support different mask sizes (not just 64x64)
812- // Currently, just fill pixel mask with 1s
813- const maskSize = [result.pixel_values.dims[0], 64, 64];
814- const pixel_mask = new Tensor(
815- 'int64',
816- new BigInt64Array(maskSize.reduce((a, b) => a * b)).fill(1n),
817- maskSize
818- );
819-
820- return { ...result, pixel_mask };
838+ /**
839+ * Calls the feature extraction process on an array of images, preprocesses
840+ * each image, and concatenates the resulting features into a single Tensor.
841+ * @param {RawImage[]} images The image(s) to extract features from.
842+ * @returns {Promise<DetrFeatureExtractorResult>} An object containing the concatenated pixel values of the preprocessed images.
843+ */
844+ async _call(images) {
845+ const result = await super._call(images);
846+
847+ // TODO support differently-sized images, for now assume all images are the same size.
848+ // TODO support different mask sizes (not just 64x64)
849+ // Currently, just fill pixel mask with 1s
850+ const maskSize = [result.pixel_values.dims[0], 64, 64];
851+ const pixel_mask = new Tensor(
852+ "int64",
853+ new BigInt64Array(maskSize.reduce((a, b) => a * b)).fill(1n),
854+ maskSize,
855+ );
856+
857+ return { ...result, pixel_mask };
858+ }
859+
860+ /**
861+ * Post-processes the outputs of the model (for object detection).
862+ * @param {Object} outputs The outputs of the model that must be post-processed
863+ * @param {Tensor} outputs.logits The logits
864+ * @param {Tensor} outputs.pred_boxes The predicted boxes.
865+ * @return {Object[]} An array of objects containing the post-processed outputs.
866+ */
867+
868+ /** @type {post_process_object_detection} */
869+ post_process_object_detection(...args) {
870+ return post_process_object_detection(...args);
871+ }
872+
873+ /**
874+ * Binarize the given masks using `object_mask_threshold`, it returns the associated values of `masks`, `scores` and `labels`.
875+ * @param {Tensor} class_logits The class logits.
876+ * @param {Tensor} mask_logits The mask logits.
877+ * @param {number} object_mask_threshold A number between 0 and 1 used to binarize the masks.
878+ * @param {number} num_labels The number of labels.
879+ * @returns {[Tensor[], number[], number[]]} The binarized masks, the scores, and the labels.
880+ */
881+ remove_low_and_no_objects(
882+ class_logits,
883+ mask_logits,
884+ object_mask_threshold,
885+ num_labels,
886+ ) {
887+ let mask_probs_item = [];
888+ let pred_scores_item = [];
889+ let pred_labels_item = [];
890+
891+ for (let j = 0; j < class_logits.dims[0]; ++j) {
892+ let cls = class_logits[j];
893+ let mask = mask_logits[j];
894+
895+ let pred_label = max(cls.data)[1];
896+ if (pred_label === num_labels) {
897+ // Is the background, so we ignore it
898+ continue;
899+ }
900+
901+ let scores = softmax(cls.data);
902+ let pred_score = scores[pred_label];
903+ if (pred_score > object_mask_threshold) {
904+ mask_probs_item.push(mask);
905+ pred_scores_item.push(pred_score);
906+ pred_labels_item.push(pred_label);
907+ }
821908 }
822909
823- /**
824- * Post-processes the outputs of the model (for object detection).
825- * @param {Object} outputs The outputs of the model that must be post-processed
826- * @param {Tensor} outputs.logits The logits
827- * @param {Tensor} outputs.pred_boxes The predicted boxes.
828- * @return {Object[]} An array of objects containing the post-processed outputs.
829- */
830-
831- /** @type {post_process_object_detection} */
832- post_process_object_detection(...args) {
833- return post_process_object_detection(...args);
910+ return [mask_probs_item, pred_scores_item, pred_labels_item];
911+ }
912+
913+ /**
914+ * Checks whether the segment is valid or not.
915+ * @param {Int32Array} mask_labels Labels for each pixel in the mask.
916+ * @param {Tensor[]} mask_probs Probabilities for each pixel in the masks.
917+ * @param {number} k The class id of the segment.
918+ * @param {number} mask_threshold The mask threshold.
919+ * @param {number} overlap_mask_area_threshold The overlap mask area threshold.
920+ * @returns {[boolean, number[]]} Whether the segment is valid or not, and the indices of the valid labels.
921+ */
922+ check_segment_validity(
923+ mask_labels,
924+ mask_probs,
925+ k,
926+ mask_threshold = 0.5,
927+ overlap_mask_area_threshold = 0.8,
928+ ) {
929+ // mask_k is a 1D array of indices, indicating where the mask is equal to k
930+ let mask_k = [];
931+ let mask_k_area = 0;
932+ let original_area = 0;
933+
934+ // Compute the area of all the stuff in query k
935+ for (let i = 0; i < mask_labels.length; ++i) {
936+ if (mask_labels[i] === k) {
937+ mask_k.push(i);
938+ ++mask_k_area;
939+ }
940+
941+ if (mask_probs[k].data[i] >= mask_threshold) {
942+ ++original_area;
943+ }
944+ }
945+ let mask_exists = mask_k_area > 0 && original_area > 0;
946+
947+ // Eliminate disconnected tiny segments
948+ if (mask_exists) {
949+ // Perform additional check
950+ let area_ratio = mask_k_area / original_area;
951+ mask_exists = area_ratio > overlap_mask_area_threshold;
834952 }
835953
836- /**
837- * Binarize the given masks using `object_mask_threshold`, it returns the associated values of `masks`, `scores` and `labels`.
838- * @param {Tensor} class_logits The class logits.
839- * @param {Tensor} mask_logits The mask logits.
840- * @param {number} object_mask_threshold A number between 0 and 1 used to binarize the masks.
841- * @param {number} num_labels The number of labels.
842- * @returns {[Tensor[], number[], number[]]} The binarized masks, the scores, and the labels.
843- */
844- remove_low_and_no_objects(class_logits, mask_logits, object_mask_threshold, num_labels) {
845-
846- let mask_probs_item = [];
847- let pred_scores_item = [];
848- let pred_labels_item = [];
849-
850- for (let j = 0; j < class_logits.dims[0]; ++j) {
851- let cls = class_logits[j];
852- let mask = mask_logits[j];
853-
854- let pred_label = max(cls.data)[1];
855- if (pred_label === num_labels) {
856- // Is the background, so we ignore it
857- continue;
858- }
954+ return [mask_exists, mask_k];
955+ }
956+
957+ /**
958+ * Computes the segments.
959+ * @param {Tensor[]} mask_probs The mask probabilities.
960+ * @param {number[]} pred_scores The predicted scores.
961+ * @param {number[]} pred_labels The predicted labels.
962+ * @param {number} mask_threshold The mask threshold.
963+ * @param {number} overlap_mask_area_threshold The overlap mask area threshold.
964+ * @param {Set<number>} label_ids_to_fuse The label ids to fuse.
965+ * @param {number[]} target_size The target size of the image.
966+ * @returns {[Tensor, Array<{id: number, label_id: number, score: number}>]} The computed segments.
967+ */
968+ compute_segments(
969+ mask_probs,
970+ pred_scores,
971+ pred_labels,
972+ mask_threshold,
973+ overlap_mask_area_threshold,
974+ label_ids_to_fuse = null,
975+ target_size = null,
976+ ) {
977+ let [height, width] = target_size ?? mask_probs[0].dims;
978+
979+ let segmentation = new Tensor("int32", new Int32Array(height * width), [
980+ height,
981+ width,
982+ ]);
983+ let segments = [];
984+
985+ // 1. If target_size is not null, we need to resize the masks to the target size
986+ if (target_size !== null) {
987+ // resize the masks to the target size
988+ for (let i = 0; i < mask_probs.length; ++i) {
989+ mask_probs[i] = interpolate(
990+ mask_probs[i],
991+ target_size,
992+ "bilinear",
993+ false,
994+ );
995+ }
996+ }
859997
860- let scores = softmax(cls.data);
861- let pred_score = scores[pred_label];
862- if (pred_score > object_mask_threshold) {
863- mask_probs_item.push(mask);
864- pred_scores_item.push(pred_score);
865- pred_labels_item.push(pred_label);
866- }
998+ // 2. Weigh each mask by its prediction score
999+ // NOTE: `mask_probs` is updated in-place
1000+ //
1001+ // Temporary storage for the best label/scores for each pixel ([height, width]):
1002+ let mask_labels = new Int32Array(mask_probs[0].data.length);
1003+ let bestScores = new Float32Array(mask_probs[0].data.length);
1004+
1005+ for (let i = 0; i < mask_probs.length; ++i) {
1006+ let score = pred_scores[i];
1007+
1008+ for (let j = 0; j < mask_probs[i].data.length; ++j) {
1009+ mask_probs[i].data[j] *= score;
1010+ if (mask_probs[i].data[j] > bestScores[j]) {
1011+ mask_labels[j] = i;
1012+ bestScores[j] = mask_probs[i].data[j];
8671013 }
868-
869- return [mask_probs_item, pred_scores_item, pred_labels_item];
870-
1014+ }
8711015 }
8721016
873- /**
874- * Checks whether the segment is valid or not.
875- * @param {Int32Array} mask_labels Labels for each pixel in the mask.
876- * @param {Tensor[]} mask_probs Probabilities for each pixel in the masks.
877- * @param {number} k The class id of the segment.
878- * @param {number} mask_threshold The mask threshold.
879- * @param {number} overlap_mask_area_threshold The overlap mask area threshold.
880- * @returns {[boolean, number[]]} Whether the segment is valid or not, and the indices of the valid labels.
881- */
882- check_segment_validity(
883- mask_labels,
884- mask_probs,
885- k,
886- mask_threshold = 0.5,
887- overlap_mask_area_threshold = 0.8
888- ) {
889- // mask_k is a 1D array of indices, indicating where the mask is equal to k
890- let mask_k = [];
891- let mask_k_area = 0;
892- let original_area = 0;
893-
894- // Compute the area of all the stuff in query k
895- for (let i = 0; i < mask_labels.length; ++i) {
896- if (mask_labels[i] === k) {
897- mask_k.push(i);
898- ++mask_k_area;
899- }
1017+ let current_segment_id = 0;
9001018
901- if (mask_probs[k].data[i] >= mask_threshold) {
902- ++original_area;
903- }
904- }
905- let mask_exists = mask_k_area > 0 && original_area > 0;
906-
907- // Eliminate disconnected tiny segments
908- if (mask_exists) {
909- // Perform additional check
910- let area_ratio = mask_k_area / original_area;
911- mask_exists = area_ratio > overlap_mask_area_threshold;
912- }
1019+ // let stuff_memory_list = {}
1020+ for (let k = 0; k < pred_labels.length; ++k) {
1021+ let pred_class = pred_labels[k];
9131022
914- return [mask_exists, mask_k]
915- }
1023+ // TODO add `should_fuse`
1024+ // let should_fuse = pred_class in label_ids_to_fuse
9161025
917- /**
918- * Computes the segments.
919- * @param {Tensor[]} mask_probs The mask probabilities.
920- * @param {number[]} pred_scores The predicted scores.
921- * @param {number[]} pred_labels The predicted labels.
922- * @param {number} mask_threshold The mask threshold.
923- * @param {number} overlap_mask_area_threshold The overlap mask area threshold.
924- * @param {Set<number>} label_ids_to_fuse The label ids to fuse.
925- * @param {number[]} target_size The target size of the image.
926- * @returns {[Tensor, Array<{id: number, label_id: number, score: number}>]} The computed segments.
927- */
928- compute_segments(
1026+ // Check if mask exists and large enough to be a segment
1027+ let [mask_exists, mask_k] = this.check_segment_validity(
1028+ mask_labels,
9291029 mask_probs,
930- pred_scores,
931- pred_labels,
1030+ k,
9321031 mask_threshold,
9331032 overlap_mask_area_threshold,
934- label_ids_to_fuse = null,
935- target_size = null,
936- ) {
937- let [height, width] = target_size ?? mask_probs[0].dims;
938-
939- let segmentation = new Tensor(
940- 'int32',
941- new Int32Array(height * width),
942- [height, width]
943- );
944- let segments = [];
945-
946- // 1. If target_size is not null, we need to resize the masks to the target size
947- if (target_size !== null) {
948- // resize the masks to the target size
949- for (let i = 0; i < mask_probs.length; ++i) {
950- mask_probs[i] = interpolate(mask_probs[i], target_size, 'bilinear', false);
951- }
952- }
953-
954- // 2. Weigh each mask by its prediction score
955- // NOTE: `mask_probs` is updated in-place
956- //
957- // Temporary storage for the best label/scores for each pixel ([height, width]):
958- let mask_labels = new Int32Array(mask_probs[0].data.length);
959- let bestScores = new Float32Array(mask_probs[0].data.length);
960-
961- for (let i = 0; i < mask_probs.length; ++i) {
962- let score = pred_scores[i];
963-
964- for (let j = 0; j < mask_probs[i].data.length; ++j) {
965- mask_probs[i].data[j] *= score
966- if (mask_probs[i].data[j] > bestScores[j]) {
967- mask_labels[j] = i;
968- bestScores[j] = mask_probs[i].data[j];
969- }
970- }
971- }
972-
973- let current_segment_id = 0;
974-
975- // let stuff_memory_list = {}
976- for (let k = 0; k < pred_labels.length; ++k) {
977- let pred_class = pred_labels[k];
978-
979- // TODO add `should_fuse`
980- // let should_fuse = pred_class in label_ids_to_fuse
981-
982- // Check if mask exists and large enough to be a segment
983- let [mask_exists, mask_k] = this.check_segment_validity(
984- mask_labels,
985- mask_probs,
986- k,
987- mask_threshold,
988- overlap_mask_area_threshold
989- )
990-
991- if (!mask_exists) {
992- // Nothing to see here
993- continue;
994- }
995-
996- // TODO
997- // if (pred_class in stuff_memory_list) {
998- // current_segment_id = stuff_memory_list[pred_class]
999- // } else {
1000- // current_segment_id += 1;
1001- // }
1002- ++current_segment_id;
1003-
1004-
1005- // Add current object segment to final segmentation map
1006- for (let index of mask_k) {
1007- segmentation.data[index] = current_segment_id;
1008- }
1009-
1010- segments.push({
1011- id: current_segment_id,
1012- label_id: pred_class,
1013- // was_fused: should_fuse, TODO
1014- score: pred_scores[k],
1015- })
1016-
1017- // TODO
1018- // if(should_fuse){
1019- // stuff_memory_list[pred_class] = current_segment_id
1020- // }
1021- }
1022-
1023- return [segmentation, segments];
1033+ );
1034+
1035+ if (!mask_exists) {
1036+ // Nothing to see here
1037+ continue;
1038+ }
1039+
1040+ // TODO
1041+ // if (pred_class in stuff_memory_list) {
1042+ // current_segment_id = stuff_memory_list[pred_class]
1043+ // } else {
1044+ // current_segment_id += 1;
1045+ // }
1046+ ++current_segment_id;
1047+
1048+ // Add current object segment to final segmentation map
1049+ for (let index of mask_k) {
1050+ segmentation.data[index] = current_segment_id;
1051+ }
1052+
1053+ segments.push({
1054+ id: current_segment_id,
1055+ label_id: pred_class,
1056+ // was_fused: should_fuse, TODO
1057+ score: pred_scores[k],
1058+ });
1059+
1060+ // TODO
1061+ // if(should_fuse){
1062+ // stuff_memory_list[pred_class] = current_segment_id
1063+ // }
10241064 }
10251065
1026- /**
1027- * Post-process the model output to generate the final panoptic segmentation.
1028- * @param {*} outputs The model output to post process
1029- * @param {number} [threshold=0.5] The probability score threshold to keep predicted instance masks.
1030- * @param {number} [mask_threshold=0.5] Threshold to use when turning the predicted masks into binary values.
1031- * @param {number} [overlap_mask_area_threshold=0.8] The overlap mask area threshold to merge or discard small disconnected parts within each binary instance mask.
1032- * @param {Set<number>} [label_ids_to_fuse=null] The labels in this state will have all their instances be fused together.
1033- * @param {number[][]} [target_sizes=null] The target sizes to resize the masks to.
1034- * @returns {Array<{ segmentation: Tensor, segments_info: Array<{id: number, label_id: number, score: number}>}>}
1035- */
1036- post_process_panoptic_segmentation(
1037- outputs,
1038- threshold = 0.5,
1039- mask_threshold = 0.5,
1040- overlap_mask_area_threshold = 0.8,
1041- label_ids_to_fuse = null,
1042- target_sizes = null,
1043- ) {
1044- if (label_ids_to_fuse === null) {
1045- console.warn("`label_ids_to_fuse` unset. No instance will be fused.")
1046- label_ids_to_fuse = new Set();
1047- }
1048-
1049- const class_queries_logits = outputs.logits; // [batch_size, num_queries, num_classes+1]
1050- const masks_queries_logits = outputs.pred_masks; // [batch_size, num_queries, height, width]
1066+ return [segmentation, segments];
1067+ }
1068+
1069+ /**
1070+ * Post-process the model output to generate the final panoptic segmentation.
1071+ * @param {*} outputs The model output to post process
1072+ * @param {number} [threshold=0.5] The probability score threshold to keep predicted instance masks.
1073+ * @param {number} [mask_threshold=0.5] Threshold to use when turning the predicted masks into binary values.
1074+ * @param {number} [overlap_mask_area_threshold=0.8] The overlap mask area threshold to merge or discard small disconnected parts within each binary instance mask.
1075+ * @param {Set<number>} [label_ids_to_fuse=null] The labels in this state will have all their instances be fused together.
1076+ * @param {number[][]} [target_sizes=null] The target sizes to resize the masks to.
1077+ * @returns {Array<{ segmentation: Tensor, segments_info: Array<{id: number, label_id: number, score: number}>}>}
1078+ */
1079+ post_process_panoptic_segmentation(
1080+ outputs,
1081+ threshold = 0.5,
1082+ mask_threshold = 0.5,
1083+ overlap_mask_area_threshold = 0.8,
1084+ label_ids_to_fuse = null,
1085+ target_sizes = null,
1086+ ) {
1087+ if (label_ids_to_fuse === null) {
1088+ console.warn("`label_ids_to_fuse` unset. No instance will be fused.");
1089+ label_ids_to_fuse = new Set();
1090+ }
10511091
1052- const mask_probs = masks_queries_logits.sigmoid() // [batch_size, num_queries, height, width]
1092+ const class_queries_logits = outputs.logits; // [batch_size, num_queries, num_classes+1]
1093+ const masks_queries_logits = outputs.pred_masks; // [batch_size, num_queries, height, width]
10531094
1054- let [batch_size, num_queries, num_labels] = class_queries_logits.dims;
1055- num_labels -= 1; // Remove last class (background)
1095+ const mask_probs = masks_queries_logits.sigmoid(); // [batch_size, num_queries, height, width]
10561096
1057- if (target_sizes !== null && target_sizes.length !== batch_size) {
1058- throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits")
1059- }
1097+ let [batch_size, num_queries, num_labels] = class_queries_logits.dims;
1098+ num_labels -= 1; // Remove last class (background)
10601099
1061- let toReturn = [];
1062- for (let i = 0; i < batch_size; ++i) {
1063- let target_size = target_sizes !== null ? target_sizes[i] : null;
1064-
1065- let class_logits = class_queries_logits[i];
1066- let mask_logits = mask_probs[i];
1067-
1068- let [mask_probs_item, pred_scores_item, pred_labels_item] = this.remove_low_and_no_objects(class_logits, mask_logits, threshold, num_labels);
1069-
1070- if (pred_labels_item.length === 0) {
1071- // No mask found
1072- let [height, width] = target_size ?? mask_logits.dims.slice(-2);
1073-
1074- let segmentation = new Tensor(
1075- 'int32',
1076- new Int32Array(height * width).fill(-1),
1077- [height, width]
1078- )
1079- toReturn.push({
1080- segmentation: segmentation,
1081- segments_info: []
1082- });
1083- continue;
1084- }
1100+ if (target_sizes !== null && target_sizes.length !== batch_size) {
1101+ throw Error(
1102+ "Make sure that you pass in as many target sizes as the batch dimension of the logits",
1103+ );
1104+ }
10851105
1106+ let toReturn = [];
1107+ for (let i = 0; i < batch_size; ++i) {
1108+ let target_size = target_sizes !== null ? target_sizes[i] : null;
1109+
1110+ let class_logits = class_queries_logits[i];
1111+ let mask_logits = mask_probs[i];
1112+
1113+ let [mask_probs_item, pred_scores_item, pred_labels_item] =
1114+ this.remove_low_and_no_objects(
1115+ class_logits,
1116+ mask_logits,
1117+ threshold,
1118+ num_labels,
1119+ );
10861120
1087- // Get segmentation map and segment information of batch item
1088- let [segmentation, segments] = this.compute_segments(
1089- mask_probs_item,
1090- pred_scores_item,
1091- pred_labels_item,
1092- mask_threshold,
1093- overlap_mask_area_threshold,
1094- label_ids_to_fuse,
1095- target_size,
1096- )
1097-
1098- toReturn.push({
1099- segmentation: segmentation,
1100- segments_info: segments
1101- })
1102- }
1121+ if (pred_labels_item.length === 0) {
1122+ // No mask found
1123+ let [height, width] = target_size ?? mask_logits.dims.slice(-2);
11031124
1104- return toReturn;
1125+ let segmentation = new Tensor(
1126+ "int32",
1127+ new Int32Array(height * width).fill(-1),
1128+ [height, width],
1129+ );
1130+ toReturn.push({
1131+ segmentation: segmentation,
1132+ segments_info: [],
1133+ });
1134+ continue;
1135+ }
1136+
1137+ // Get segmentation map and segment information of batch item
1138+ let [segmentation, segments] = this.compute_segments(
1139+ mask_probs_item,
1140+ pred_scores_item,
1141+ pred_labels_item,
1142+ mask_threshold,
1143+ overlap_mask_area_threshold,
1144+ label_ids_to_fuse,
1145+ target_size,
1146+ );
1147+
1148+ toReturn.push({
1149+ segmentation: segmentation,
1150+ segments_info: segments,
1151+ });
11051152 }
11061153
1107- post_process_instance_segmentation() {
1108- // TODO
1109- throw Error("Not implemented yet");
1110- }
1154+ return toReturn;
1155+ }
1156+
1157+ post_process_instance_segmentation() {
1158+ // TODO
1159+ throw Error("Not implemented yet");
1160+ }
11111161 }
11121162
11131163 export class YolosFeatureExtractor extends ImageFeatureExtractor {
1114- /** @type {post_process_object_detection} */
1115- post_process_object_detection(...args) {
1116- return post_process_object_detection(...args);
1117- }
1164+ /** @type {post_process_object_detection} */
1165+ post_process_object_detection(...args) {
1166+ return post_process_object_detection(...args);
1167+ }
11181168 }
11191169
11201170 /**
@@ -1127,673 +1177,710 @@
11271177 */
11281178
11291179 export class SamImageProcessor extends ImageFeatureExtractor {
1180+ /**
1181+ *
1182+ * @param {any} input_points
1183+ * @param {HeightWidth[]} original_sizes
1184+ * @param {HeightWidth[]} reshaped_input_sizes
1185+ * @returns {Tensor}
1186+ */
1187+ reshape_input_points(input_points, original_sizes, reshaped_input_sizes) {
1188+ // Make deep copy to avoid altering user's input
1189+ input_points = structuredClone(input_points);
1190+ let shape = calculateDimensions(input_points);
1191+
1192+ // TODO: add support for 2D input_points
1193+ if (shape.length === 3) {
1194+ // Correct user's input
1195+ shape = [1, ...shape];
1196+ input_points = [input_points];
1197+ } else if (shape.length !== 4) {
1198+ throw Error(
1199+ "The input_points must be a 4D tensor of shape `batch_size`, `point_batch_size`, `nb_points_per_image`, `2`.",
1200+ );
1201+ }
11301202
1131- /**
1132- *
1133- * @param {any} input_points
1134- * @param {HeightWidth[]} original_sizes
1135- * @param {HeightWidth[]} reshaped_input_sizes
1136- * @returns {Tensor}
1137- */
1138- reshape_input_points(input_points, original_sizes, reshaped_input_sizes) {
1139-
1140- // Make deep copy to avoid altering user's input
1141- input_points = structuredClone(input_points);
1142- let shape = calculateDimensions(input_points);
1143-
1144- // TODO: add support for 2D input_points
1145- if (shape.length === 3) {
1146- // Correct user's input
1147- shape = [1, ...shape];
1148- input_points = [input_points];
1149- } else if (shape.length !== 4) {
1150- throw Error("The input_points must be a 4D tensor of shape `batch_size`, `point_batch_size`, `nb_points_per_image`, `2`.")
1151- }
1152-
1153- // Reshape input points
1154- for (let i = 0; i < input_points.length; ++i) { // batch_size
1155- let originalImageSize = original_sizes[i];
1156- let reshapedImageSize = reshaped_input_sizes[i];
1157-
1158- let resizeFactors = [
1159- reshapedImageSize[0] / originalImageSize[0],
1160- reshapedImageSize[1] / originalImageSize[1]
1161- ]
1162-
1163- for (let j = 0; j < input_points[i].length; ++j) { // point_batch_size
1164- for (let k = 0; k < input_points[i][j].length; ++k) { // nb_points_per_image
1165- for (let w = 0; w < input_points[i][j][k].length; ++w) { // 2
1166- input_points[i][j][k][w] *= resizeFactors[w];
1167- }
1168- }
1169- }
1203+ // Reshape input points
1204+ for (let i = 0; i < input_points.length; ++i) {
1205+ // batch_size
1206+ let originalImageSize = original_sizes[i];
1207+ let reshapedImageSize = reshaped_input_sizes[i];
1208+
1209+ let resizeFactors = [
1210+ reshapedImageSize[0] / originalImageSize[0],
1211+ reshapedImageSize[1] / originalImageSize[1],
1212+ ];
1213+
1214+ for (let j = 0; j < input_points[i].length; ++j) {
1215+ // point_batch_size
1216+ for (let k = 0; k < input_points[i][j].length; ++k) {
1217+ // nb_points_per_image
1218+ for (let w = 0; w < input_points[i][j][k].length; ++w) {
1219+ // 2
1220+ input_points[i][j][k][w] *= resizeFactors[w];
1221+ }
11701222 }
1223+ }
1224+ }
11711225
1172- return new Tensor(
1173- 'float32',
1174- Float32Array.from(input_points.flat(Infinity)),
1175- shape
1176- )
1177-
1226+ return new Tensor(
1227+ "float32",
1228+ Float32Array.from(input_points.flat(Infinity)),
1229+ shape,
1230+ );
1231+ }
1232+
1233+ /**
1234+ *
1235+ * @param {any} input_labels
1236+ * @param {Tensor} input_points
1237+ * @returns {Tensor}
1238+ */
1239+ add_input_labels(input_labels, input_points) {
1240+ let shape = calculateDimensions(input_labels);
1241+ if (shape.length === 2) {
1242+ // Correct user's input
1243+ shape = [1, ...shape];
1244+ input_labels = [input_labels];
1245+ } else if (shape.length !== 3) {
1246+ throw Error(
1247+ "The input_points must be a 4D tensor of shape `batch_size`, `point_batch_size`, `nb_points_per_image`, `2`.",
1248+ );
11781249 }
11791250
1180- /**
1181- *
1182- * @param {any} input_labels
1183- * @param {Tensor} input_points
1184- * @returns {Tensor}
1185- */
1186- add_input_labels(input_labels, input_points) {
1187- let shape = calculateDimensions(input_labels);
1188- if (shape.length === 2) {
1189- // Correct user's input
1190- shape = [1, ...shape];
1191- input_labels = [input_labels];
1192- } else if (shape.length !== 3) {
1193- throw Error("The input_points must be a 4D tensor of shape `batch_size`, `point_batch_size`, `nb_points_per_image`, `2`.")
1194- }
1251+ if (shape.some((x, i) => x !== input_points.dims[i])) {
1252+ throw Error(
1253+ `The first ${shape.length} dimensions of 'input_points' and 'input_labels' must be the same.`,
1254+ );
1255+ }
1256+ return new Tensor("int64", input_labels.flat(Infinity).map(BigInt), shape);
1257+ }
1258+ /**
1259+ * @param {any[]} images The URL(s) of the image(s) to extract features from.
1260+ * @param {any} [input_points] A 3D or 4D array, representing the input points provided by the user.
1261+ * - 3D: `[point_batch_size, nb_points_per_image, 2]`. In this case, `batch_size` is assumed to be 1.
1262+ * - 4D: `[batch_size, point_batch_size, nb_points_per_image, 2]`.
1263+ * @param {any} [input_labels] A 2D or 3D array, representing the input labels for the points, used by the prompt encoder to encode the prompt.
1264+ * - 2D: `[point_batch_size, nb_points_per_image]`. In this case, `batch_size` is assumed to be 1.
1265+ * - 3D: `[batch_size, point_batch_size, nb_points_per_image]`.
1266+ * @returns {Promise<SamImageProcessorResult>}
1267+ */
1268+ async _call(images, input_points = null, input_labels = null) {
1269+ // TODO allow user to use preprocessed images
1270+ /** @type {SamImageProcessorResult} */
1271+ const processed = await super._call(images);
1272+
1273+ if (input_points) {
1274+ processed.input_points = this.reshape_input_points(
1275+ input_points,
1276+ processed.original_sizes,
1277+ processed.reshaped_input_sizes,
1278+ );
1279+ }
11951280
1196- if (shape.some((x, i) => x !== input_points.dims[i])) {
1197- throw Error(`The first ${shape.length} dimensions of 'input_points' and 'input_labels' must be the same.`)
1198- }
1199- return new Tensor(
1200- 'int64',
1201- input_labels.flat(Infinity).map(BigInt),
1202- shape,
1203- )
1281+ if (input_labels) {
1282+ if (!processed.input_points) {
1283+ throw Error(
1284+ "`input_points` must be provided if `input_labels` are provided.",
1285+ );
1286+ }
1287+ processed.input_labels = this.add_input_labels(
1288+ input_labels,
1289+ processed.input_points,
1290+ );
12041291 }
1205- /**
1206- * @param {any[]} images The URL(s) of the image(s) to extract features from.
1207- * @param {any} [input_points] A 3D or 4D array, representing the input points provided by the user.
1208- * - 3D: `[point_batch_size, nb_points_per_image, 2]`. In this case, `batch_size` is assumed to be 1.
1209- * - 4D: `[batch_size, point_batch_size, nb_points_per_image, 2]`.
1210- * @param {any} [input_labels] A 2D or 3D array, representing the input labels for the points, used by the prompt encoder to encode the prompt.
1211- * - 2D: `[point_batch_size, nb_points_per_image]`. In this case, `batch_size` is assumed to be 1.
1212- * - 3D: `[batch_size, point_batch_size, nb_points_per_image]`.
1213- * @returns {Promise<SamImageProcessorResult>}
1214- */
1215- async _call(images, input_points = null, input_labels = null) {
1216- // TODO allow user to use preprocessed images
1217- /** @type {SamImageProcessorResult} */
1218- const processed = await super._call(images);
1219-
1220- if (input_points) {
1221- processed.input_points = this.reshape_input_points(
1222- input_points, processed.original_sizes, processed.reshaped_input_sizes
1223- );
1224- }
12251292
1226- if (input_labels) {
1227- if (!processed.input_points) {
1228- throw Error("`input_points` must be provided if `input_labels` are provided.")
1229- }
1230- processed.input_labels = this.add_input_labels(input_labels, processed.input_points);
1231- }
1293+ return processed;
1294+ }
1295+
1296+ /**
1297+ * Remove padding and upscale masks to the original image size.
1298+ * @param {Tensor} masks Batched masks from the mask_decoder in (batch_size, num_channels, height, width) format.
1299+ * @param {number[][]} original_sizes The original sizes of each image before it was resized to the model's expected input shape, in (height, width) format.
1300+ * @param {number[][]} reshaped_input_sizes The size of each image as it is fed to the model, in (height, width) format. Used to remove padding.
1301+ * @param {Object} options Optional parameters for post-processing.
1302+ * @param {number} [options.mask_threshold] The threshold to use for binarizing the masks.
1303+ * @param {boolean} [options.binarize] Whether to binarize the masks.
1304+ * @param {Object} [options.pad_size] The target size the images were padded to before being passed to the model. If `null`, the target size is assumed to be the processor's `pad_size`.
1305+ * @param {number} [options.pad_size.height] The height the images were padded to.
1306+ * @param {number} [options.pad_size.width] The width the images were padded to.
1307+ * @returns {Tensor[]} Batched masks in batch_size, num_channels, height, width) format, where (height, width) is given by original_size.
1308+ */
1309+ post_process_masks(
1310+ masks,
1311+ original_sizes,
1312+ reshaped_input_sizes,
1313+ { mask_threshold = 0.0, binarize = true, pad_size = null } = {},
1314+ ) {
1315+ // masks: [1, 1, 3, 256, 256]
1316+
1317+ const output_masks = [];
1318+
1319+ pad_size = pad_size ?? this.pad_size;
1320+
1321+ const target_image_size = [pad_size.height, pad_size.width];
1322+
1323+ for (let i = 0; i < original_sizes.length; ++i) {
1324+ const original_size = original_sizes[i];
1325+ const reshaped_input_size = reshaped_input_sizes[i];
1326+
1327+ const mask = masks[i]; // [b, c, h, w]
1328+
1329+ // TODO: improve
1330+ const interpolated_masks = [];
1331+ for (let j = 0; j < mask.dims[0]; ++j) {
1332+ const m = mask[j]; // 3d tensor
1333+
1334+ // Upscale mask to padded size
1335+ let interpolated_mask = interpolate(
1336+ m,
1337+ target_image_size,
1338+ "bilinear",
1339+ false,
1340+ );
12321341
1233- return processed;
1234- }
1342+ // Crop mask
1343+ interpolated_mask = interpolated_mask.slice(
1344+ null,
1345+ [0, reshaped_input_size[0]],
1346+ [0, reshaped_input_size[1]],
1347+ );
12351348
1236- /**
1237- * Remove padding and upscale masks to the original image size.
1238- * @param {Tensor} masks Batched masks from the mask_decoder in (batch_size, num_channels, height, width) format.
1239- * @param {number[][]} original_sizes The original sizes of each image before it was resized to the model's expected input shape, in (height, width) format.
1240- * @param {number[][]} reshaped_input_sizes The size of each image as it is fed to the model, in (height, width) format. Used to remove padding.
1241- * @param {Object} options Optional parameters for post-processing.
1242- * @param {number} [options.mask_threshold] The threshold to use for binarizing the masks.
1243- * @param {boolean} [options.binarize] Whether to binarize the masks.
1244- * @param {Object} [options.pad_size] The target size the images were padded to before being passed to the model. If `null`, the target size is assumed to be the processor's `pad_size`.
1245- * @param {number} [options.pad_size.height] The height the images were padded to.
1246- * @param {number} [options.pad_size.width] The width the images were padded to.
1247- * @returns {Tensor[]} Batched masks in batch_size, num_channels, height, width) format, where (height, width) is given by original_size.
1248- */
1249- post_process_masks(masks, original_sizes, reshaped_input_sizes, {
1250- mask_threshold = 0.0,
1251- binarize = true,
1252- pad_size = null,
1253- } = {}) {
1254- // masks: [1, 1, 3, 256, 256]
1255-
1256- const output_masks = [];
1257-
1258- pad_size = pad_size ?? this.pad_size;
1259-
1260- const target_image_size = [pad_size.height, pad_size.width];
1261-
1262- for (let i = 0; i < original_sizes.length; ++i) {
1263- const original_size = original_sizes[i];
1264- const reshaped_input_size = reshaped_input_sizes[i];
1265-
1266- const mask = masks[i]; // [b, c, h, w]
1267-
1268- // TODO: improve
1269- const interpolated_masks = [];
1270- for (let j = 0; j < mask.dims[0]; ++j) {
1271- const m = mask[j]; // 3d tensor
1272-
1273- // Upscale mask to padded size
1274- let interpolated_mask = interpolate(m, target_image_size, 'bilinear', false);
1275-
1276- // Crop mask
1277- interpolated_mask = interpolated_mask.slice(null, [0, reshaped_input_size[0]], [0, reshaped_input_size[1]]);
1278-
1279- // Downscale mask
1280- interpolated_mask = interpolate(interpolated_mask, original_size, 'bilinear', false);
1281-
1282- if (binarize) {
1283- const binarizedMaskData = new Uint8Array(interpolated_mask.data.length);
1284- for (let i = 0; i < interpolated_mask.data.length; ++i) {
1285- if (interpolated_mask.data[i] > mask_threshold) {
1286- binarizedMaskData[i] = 1;
1287- }
1288- }
1289- interpolated_mask = new Tensor(
1290- 'bool',
1291- binarizedMaskData,
1292- interpolated_mask.dims
1293- )
1294- }
1295-
1296- interpolated_masks.push(interpolated_mask);
1297- }
1349+ // Downscale mask
1350+ interpolated_mask = interpolate(
1351+ interpolated_mask,
1352+ original_size,
1353+ "bilinear",
1354+ false,
1355+ );
12981356
1299- output_masks.push(stack(interpolated_masks));
1357+ if (binarize) {
1358+ const binarizedMaskData = new Uint8Array(
1359+ interpolated_mask.data.length,
1360+ );
1361+ for (let i = 0; i < interpolated_mask.data.length; ++i) {
1362+ if (interpolated_mask.data[i] > mask_threshold) {
1363+ binarizedMaskData[i] = 1;
1364+ }
1365+ }
1366+ interpolated_mask = new Tensor(
1367+ "bool",
1368+ binarizedMaskData,
1369+ interpolated_mask.dims,
1370+ );
13001371 }
13011372
1302- return output_masks;
1373+ interpolated_masks.push(interpolated_mask);
1374+ }
1375+
1376+ output_masks.push(stack(interpolated_masks));
13031377 }
1378+
1379+ return output_masks;
1380+ }
13041381 }
13051382
13061383 export class Swin2SRImageProcessor extends ImageFeatureExtractor {
1307- pad_image(pixelData, imgDims, padSize, options = {}) {
1308- // NOTE: In this case, `padSize` represents the size of the sliding window for the local attention.
1309- // In other words, the image is padded so that its width and height are multiples of `padSize`.
1310- const [imageWidth, imageHeight, imageChannels] = imgDims;
1311-
1312- return super.pad_image(pixelData, imgDims, {
1313- // NOTE: For Swin2SR models, the original python implementation adds padding even when the image's width/height is already
1314- // a multiple of `pad_size`. However, this is most likely a bug (PR: https://github.com/mv-lab/swin2sr/pull/19).
1315- // For this reason, we only add padding when the image's width/height is not a multiple of `pad_size`.
1316- width: imageWidth + (padSize - imageWidth % padSize) % padSize,
1317- height: imageHeight + (padSize - imageHeight % padSize) % padSize,
1318- }, {
1319- mode: 'symmetric',
1320- center: false,
1321- constant_values: -1,
1322- ...options,
1323- })
1324- }
1384+ pad_image(pixelData, imgDims, padSize, options = {}) {
1385+ // NOTE: In this case, `padSize` represents the size of the sliding window for the local attention.
1386+ // In other words, the image is padded so that its width and height are multiples of `padSize`.
1387+ const [imageWidth, imageHeight, imageChannels] = imgDims;
1388+
1389+ return super.pad_image(
1390+ pixelData,
1391+ imgDims,
1392+ {
1393+ // NOTE: For Swin2SR models, the original python implementation adds padding even when the image's width/height is already
1394+ // a multiple of `pad_size`. However, this is most likely a bug (PR: https://github.com/mv-lab/swin2sr/pull/19).
1395+ // For this reason, we only add padding when the image's width/height is not a multiple of `pad_size`.
1396+ width: imageWidth + ((padSize - (imageWidth % padSize)) % padSize),
1397+ height: imageHeight + ((padSize - (imageHeight % padSize)) % padSize),
1398+ },
1399+ {
1400+ mode: "symmetric",
1401+ center: false,
1402+ constant_values: -1,
1403+ ...options,
1404+ },
1405+ );
1406+ }
13251407 }
13261408
13271409 export class VitMatteImageProcessor extends ImageFeatureExtractor {
1328- /**
1329- * Calls the feature extraction process on an array of images, preprocesses
1330- * each image, and concatenates the resulting features into a single Tensor.
1331- * @param {RawImage[]} images The image(s) to extract features from.
1332- * @param {RawImage[]} trimaps The trimaps(s) to extract features from.
1333- * @returns {Promise<ImageFeatureExtractorResult>} An object containing the concatenated pixel values of the preprocessed images.
1334- */
1335- async _call(images, trimaps) {
1336- if (!Array.isArray(images)) {
1337- images = [images];
1338- }
1339- if (!Array.isArray(trimaps)) {
1340- trimaps = [trimaps];
1341- }
1342-
1343- const imageData = await Promise.all(images.map(x => this.preprocess(x)));
1344- const trimapData = await Promise.all(trimaps.map(x => this.preprocess(x, {
1345- do_normalize: false,
1346- do_convert_rgb: false,
1347- do_convert_grayscale: true,
1348- })));
1349-
1350-
1351- // Stack pixel values
1352- const pixel_values = stack(imageData.map(
1353- // Concatenate images and trimaps
1354- (x, i) => cat([x.pixel_values, trimapData[i].pixel_values], 0)
1355- ), 0);
1356-
1357- return {
1358- pixel_values: pixel_values,
1359-
1360- // Original sizes of images
1361- original_sizes: imageData.map(x => x.original_size),
1362-
1363- // Reshaped sizes of images, before padding or cropping
1364- reshaped_input_sizes: imageData.map(x => x.reshaped_input_size),
1365- }
1410+ /**
1411+ * Calls the feature extraction process on an array of images, preprocesses
1412+ * each image, and concatenates the resulting features into a single Tensor.
1413+ * @param {RawImage[]} images The image(s) to extract features from.
1414+ * @param {RawImage[]} trimaps The trimaps(s) to extract features from.
1415+ * @returns {Promise<ImageFeatureExtractorResult>} An object containing the concatenated pixel values of the preprocessed images.
1416+ */
1417+ async _call(images, trimaps) {
1418+ if (!Array.isArray(images)) {
1419+ images = [images];
13661420 }
1421+ if (!Array.isArray(trimaps)) {
1422+ trimaps = [trimaps];
1423+ }
1424+
1425+ const imageData = await Promise.all(images.map((x) => this.preprocess(x)));
1426+ const trimapData = await Promise.all(
1427+ trimaps.map((x) =>
1428+ this.preprocess(x, {
1429+ do_normalize: false,
1430+ do_convert_rgb: false,
1431+ do_convert_grayscale: true,
1432+ }),
1433+ ),
1434+ );
1435+
1436+ // Stack pixel values
1437+ const pixel_values = stack(
1438+ imageData.map(
1439+ // Concatenate images and trimaps
1440+ (x, i) => cat([x.pixel_values, trimapData[i].pixel_values], 0),
1441+ ),
1442+ 0,
1443+ );
1444+
1445+ return {
1446+ pixel_values: pixel_values,
1447+
1448+ // Original sizes of images
1449+ original_sizes: imageData.map((x) => x.original_size),
1450+
1451+ // Reshaped sizes of images, before padding or cropping
1452+ reshaped_input_sizes: imageData.map((x) => x.reshaped_input_size),
1453+ };
1454+ }
13671455 }
13681456
13691457 export class WhisperFeatureExtractor extends FeatureExtractor {
1370-
1371- constructor(config) {
1372- super(config);
1373-
1374- // Prefer given `mel_filters` from preprocessor_config.json, or calculate them if they don't exist.
1375- this.config.mel_filters ??= mel_filter_bank(
1376- Math.floor(1 + this.config.n_fft / 2), // num_frequency_bins
1377- this.config.feature_size, // num_mel_filters
1378- 0.0, // min_frequency
1379- 8000.0, // max_frequency
1380- this.config.sampling_rate, // sampling_rate
1381- "slaney", // norm
1382- "slaney", // mel_scale
1383- );
1384-
1385- this.window = window_function(this.config.n_fft, 'hann');
1458+ constructor(config) {
1459+ super(config);
1460+
1461+ // Prefer given `mel_filters` from preprocessor_config.json, or calculate them if they don't exist.
1462+ this.config.mel_filters ??= mel_filter_bank(
1463+ Math.floor(1 + this.config.n_fft / 2), // num_frequency_bins
1464+ this.config.feature_size, // num_mel_filters
1465+ 0.0, // min_frequency
1466+ 8000.0, // max_frequency
1467+ this.config.sampling_rate, // sampling_rate
1468+ "slaney", // norm
1469+ "slaney", // mel_scale
1470+ );
1471+
1472+ this.window = window_function(this.config.n_fft, "hann");
1473+ }
1474+
1475+ /**
1476+ * Computes the log-Mel spectrogram of the provided audio waveform.
1477+ * @param {Float32Array|Float64Array} waveform The audio waveform to process.
1478+ * @returns {{data: Float32Array, dims: number[]}} An object containing the log-Mel spectrogram data as a Float32Array and its dimensions as an array of numbers.
1479+ */
1480+ _extract_fbank_features(waveform) {
1481+ const { data, dims } = spectrogram(
1482+ waveform,
1483+ this.window, // window
1484+ this.config.n_fft, // frame_length
1485+ this.config.hop_length, // hop_length
1486+ {
1487+ power: 2.0,
1488+ mel_filters: this.config.mel_filters,
1489+ log_mel: "log10",
1490+
1491+ // Custom
1492+ max_num_frames: this.config.nb_max_frames, // 3000
1493+ },
1494+ );
1495+
1496+ const maxValue = max(data)[0];
1497+
1498+ for (let i = 0; i < data.length; ++i) {
1499+ data[i] = (Math.max(data[i], maxValue - 8.0) + 4.0) / 4.0;
13861500 }
13871501
1388- /**
1389- * Computes the log-Mel spectrogram of the provided audio waveform.
1390- * @param {Float32Array|Float64Array} waveform The audio waveform to process.
1391- * @returns {{data: Float32Array, dims: number[]}} An object containing the log-Mel spectrogram data as a Float32Array and its dimensions as an array of numbers.
1392- */
1393- _extract_fbank_features(waveform) {
1394- const { data, dims } = spectrogram(
1395- waveform,
1396- this.window, // window
1397- this.config.n_fft, // frame_length
1398- this.config.hop_length, // hop_length
1399- {
1400- power: 2.0,
1401- mel_filters: this.config.mel_filters,
1402- log_mel: 'log10',
1403-
1404- // Custom
1405- max_num_frames: this.config.nb_max_frames, // 3000
1406- }
1407- )
1408-
1409- const maxValue = max(data)[0];
1410-
1411- for (let i = 0; i < data.length; ++i) {
1412- data[i] = (Math.max(data[i], maxValue - 8.0) + 4.0) / 4.0;
1413- }
1414-
1415- return { data, dims };
1502+ return { data, dims };
1503+ }
1504+
1505+ /**
1506+ * Asynchronously extracts features from a given audio using the provided configuration.
1507+ * @param {Float32Array|Float64Array} audio The audio data as a Float32Array/Float64Array.
1508+ * @returns {Promise<{ input_features: Tensor }>} A Promise resolving to an object containing the extracted input features as a Tensor.
1509+ */
1510+ async _call(audio) {
1511+ validate_audio_inputs(audio, "WhisperFeatureExtractor");
1512+
1513+ let waveform;
1514+ if (audio.length > this.config.n_samples) {
1515+ console.warn(
1516+ "Attempting to extract features for audio longer than 30 seconds. " +
1517+ "If using a pipeline to extract transcript from a long audio clip, " +
1518+ "remember to specify `chunk_length_s` and/or `stride_length_s`.",
1519+ );
1520+ waveform = audio.slice(0, this.config.n_samples);
1521+ } else {
1522+ // pad with zeros
1523+ waveform = new Float32Array(this.config.n_samples);
1524+ waveform.set(audio);
14161525 }
14171526
1418- /**
1419- * Asynchronously extracts features from a given audio using the provided configuration.
1420- * @param {Float32Array|Float64Array} audio The audio data as a Float32Array/Float64Array.
1421- * @returns {Promise<{ input_features: Tensor }>} A Promise resolving to an object containing the extracted input features as a Tensor.
1422- */
1423- async _call(audio) {
1424- validate_audio_inputs(audio, 'WhisperFeatureExtractor');
1425-
1426- let waveform;
1427- if (audio.length > this.config.n_samples) {
1428- console.warn(
1429- "Attempting to extract features for audio longer than 30 seconds. " +
1430- "If using a pipeline to extract transcript from a long audio clip, " +
1431- "remember to specify `chunk_length_s` and/or `stride_length_s`."
1432- );
1433- waveform = audio.slice(0, this.config.n_samples);
1434- } else {
1435- // pad with zeros
1436- waveform = new Float32Array(this.config.n_samples);
1437- waveform.set(audio);
1438- }
1439-
1440- const { data, dims } = this._extract_fbank_features(waveform);
1527+ const { data, dims } = this._extract_fbank_features(waveform);
14411528
1442- return {
1443- input_features: new Tensor('float32',
1444- data,
1445- [1, ...dims]
1446- )
1447- };
1448- }
1529+ return {
1530+ input_features: new Tensor("float32", data, [1, ...dims]),
1531+ };
1532+ }
14491533 }
14501534
14511535 export class Wav2Vec2FeatureExtractor extends FeatureExtractor {
1452-
1453- /**
1454- * @param {Float32Array} input_values
1455- * @returns {Float32Array}
1456- */
1457- _zero_mean_unit_var_norm(input_values) {
1458- // TODO support batch?
1459- const sum = input_values.reduce((a, b) => a + b, 0);
1460- const mean = sum / input_values.length;
1461- const variance = input_values.reduce((a, b) => a + (b - mean) ** 2, 0) / input_values.length;
1462- return input_values.map(x => (x - mean) / Math.sqrt(variance + 1e-7));
1536+ /**
1537+ * @param {Float32Array} input_values
1538+ * @returns {Float32Array}
1539+ */
1540+ _zero_mean_unit_var_norm(input_values) {
1541+ // TODO support batch?
1542+ const sum = input_values.reduce((a, b) => a + b, 0);
1543+ const mean = sum / input_values.length;
1544+ const variance =
1545+ input_values.reduce((a, b) => a + (b - mean) ** 2, 0) /
1546+ input_values.length;
1547+ return input_values.map((x) => (x - mean) / Math.sqrt(variance + 1e-7));
1548+ }
1549+
1550+ /**
1551+ * Asynchronously extracts features from a given audio using the provided configuration.
1552+ * @param {Float32Array|Float64Array} audio The audio data as a Float32Array/Float64Array.
1553+ * @returns {Promise<{ input_values: Tensor; attention_mask: Tensor }>} A Promise resolving to an object containing the extracted input features and attention mask as Tensors.
1554+ */
1555+ async _call(audio) {
1556+ validate_audio_inputs(audio, "Wav2Vec2FeatureExtractor");
1557+
1558+ if (audio instanceof Float64Array) {
1559+ audio = new Float32Array(audio);
14631560 }
14641561
1465- /**
1466- * Asynchronously extracts features from a given audio using the provided configuration.
1467- * @param {Float32Array|Float64Array} audio The audio data as a Float32Array/Float64Array.
1468- * @returns {Promise<{ input_values: Tensor; attention_mask: Tensor }>} A Promise resolving to an object containing the extracted input features and attention mask as Tensors.
1469- */
1470- async _call(audio) {
1471- validate_audio_inputs(audio, 'Wav2Vec2FeatureExtractor');
1472-
1473- if (audio instanceof Float64Array) {
1474- audio = new Float32Array(audio);
1475- }
1476-
1477- let input_values = audio;
1478-
1479- // zero-mean and unit-variance normalization
1480- if (this.config.do_normalize) {
1481- input_values = this._zero_mean_unit_var_norm(input_values);
1482- }
1562+ let input_values = audio;
14831563
1484- // TODO: allow user to pass in attention mask
1485- const shape = [1, input_values.length];
1486- return {
1487- input_values: new Tensor('float32', input_values, shape),
1488- attention_mask: new Tensor('int64', new BigInt64Array(input_values.length).fill(1n), shape)
1489- };
1564+ // zero-mean and unit-variance normalization
1565+ if (this.config.do_normalize) {
1566+ input_values = this._zero_mean_unit_var_norm(input_values);
14901567 }
1568+
1569+ // TODO: allow user to pass in attention mask
1570+ const shape = [1, input_values.length];
1571+ return {
1572+ input_values: new Tensor("float32", input_values, shape),
1573+ attention_mask: new Tensor(
1574+ "int64",
1575+ new BigInt64Array(input_values.length).fill(1n),
1576+ shape,
1577+ ),
1578+ };
1579+ }
14911580 }
14921581
14931582 export class ASTFeatureExtractor extends FeatureExtractor {
1494-
1495-
1496- constructor(config) {
1497- super(config);
1498-
1499- const sampling_rate = this.config.sampling_rate;
1500- const mel_filters = mel_filter_bank(
1501- 256, // num_frequency_bins
1502- this.config.num_mel_bins, // num_mel_filters
1503- 20, // min_frequency
1504- Math.floor(sampling_rate / 2), // max_frequency
1505- sampling_rate, // sampling_rate
1506- null, // norm
1507- "kaldi", // mel_scale
1508- true, // triangularize_in_mel_space
1509- );
1510-
1511- // Do padding:
1512- for (let i = 0; i < mel_filters.length; ++i) {
1513- mel_filters[i].push(0);
1514- }
1515- this.mel_filters = mel_filters;
1516-
1517- this.window = window_function(400, 'hann', {
1518- periodic: false,
1519- })
1520-
1521- this.mean = this.config.mean;
1522- this.std = this.config.std;
1583+ constructor(config) {
1584+ super(config);
1585+
1586+ const sampling_rate = this.config.sampling_rate;
1587+ const mel_filters = mel_filter_bank(
1588+ 256, // num_frequency_bins
1589+ this.config.num_mel_bins, // num_mel_filters
1590+ 20, // min_frequency
1591+ Math.floor(sampling_rate / 2), // max_frequency
1592+ sampling_rate, // sampling_rate
1593+ null, // norm
1594+ "kaldi", // mel_scale
1595+ true, // triangularize_in_mel_space
1596+ );
1597+
1598+ // Do padding:
1599+ for (let i = 0; i < mel_filters.length; ++i) {
1600+ mel_filters[i].push(0);
15231601 }
1524-
1525- /**
1526- * Computes the log-Mel spectrogram of the provided audio waveform.
1527- * @param {Float32Array|Float64Array} waveform The audio waveform to process.
1528- * @param {number} max_length The maximum number of frames to return.
1529- * @returns {{data: Float32Array, dims: number[]}} An object containing the log-Mel spectrogram data as a Float32Array and its dimensions as an array of numbers.
1530- */
1531- _extract_fbank_features(waveform, max_length) {
1532- // NOTE: We don't pad/truncate since that is passed in as `max_num_frames`
1533- return spectrogram(
1534- waveform,
1535- this.window, // window
1536- 400, // frame_length
1537- 160, // hop_length
1538- {
1539- fft_length: 512,
1540- power: 2.0,
1541- center: false,
1542- preemphasis: 0.97,
1543- mel_filters: this.mel_filters,
1544- log_mel: 'log',
1545- mel_floor: 1.192092955078125e-07,
1546- remove_dc_offset: true,
1547-
1548- // Custom
1549- max_num_frames: max_length,
1550- transpose: true,
1551- }
1552- )
1602+ this.mel_filters = mel_filters;
1603+
1604+ this.window = window_function(400, "hann", {
1605+ periodic: false,
1606+ });
1607+
1608+ this.mean = this.config.mean;
1609+ this.std = this.config.std;
1610+ }
1611+
1612+ /**
1613+ * Computes the log-Mel spectrogram of the provided audio waveform.
1614+ * @param {Float32Array|Float64Array} waveform The audio waveform to process.
1615+ * @param {number} max_length The maximum number of frames to return.
1616+ * @returns {{data: Float32Array, dims: number[]}} An object containing the log-Mel spectrogram data as a Float32Array and its dimensions as an array of numbers.
1617+ */
1618+ _extract_fbank_features(waveform, max_length) {
1619+ // NOTE: We don't pad/truncate since that is passed in as `max_num_frames`
1620+ return spectrogram(
1621+ waveform,
1622+ this.window, // window
1623+ 400, // frame_length
1624+ 160, // hop_length
1625+ {
1626+ fft_length: 512,
1627+ power: 2.0,
1628+ center: false,
1629+ preemphasis: 0.97,
1630+ mel_filters: this.mel_filters,
1631+ log_mel: "log",
1632+ mel_floor: 1.192092955078125e-7,
1633+ remove_dc_offset: true,
1634+
1635+ // Custom
1636+ max_num_frames: max_length,
1637+ transpose: true,
1638+ },
1639+ );
1640+ }
1641+
1642+ /**
1643+ * Asynchronously extracts features from a given audio using the provided configuration.
1644+ * @param {Float32Array|Float64Array} audio The audio data as a Float32Array/Float64Array.
1645+ * @returns {Promise<{ input_values: Tensor }>} A Promise resolving to an object containing the extracted input features as a Tensor.
1646+ */
1647+ async _call(audio) {
1648+ validate_audio_inputs(audio, "ASTFeatureExtractor");
1649+
1650+ const features = this._extract_fbank_features(
1651+ audio,
1652+ this.config.max_length,
1653+ );
1654+ if (this.config.do_normalize) {
1655+ // Normalize the input audio spectrogram to have mean=0, std=0.5
1656+ const denom = this.std * 2;
1657+ for (let i = 0; i < features.data.length; ++i) {
1658+ features.data[i] = (features.data[i] - this.mean) / denom;
1659+ }
15531660 }
15541661
1555-
1556- /**
1557- * Asynchronously extracts features from a given audio using the provided configuration.
1558- * @param {Float32Array|Float64Array} audio The audio data as a Float32Array/Float64Array.
1559- * @returns {Promise<{ input_values: Tensor }>} A Promise resolving to an object containing the extracted input features as a Tensor.
1560- */
1561- async _call(audio) {
1562- validate_audio_inputs(audio, 'ASTFeatureExtractor');
1563-
1564- const features = this._extract_fbank_features(audio, this.config.max_length);
1565- if (this.config.do_normalize) {
1566- // Normalize the input audio spectrogram to have mean=0, std=0.5
1567- const denom = this.std * 2;
1568- for (let i = 0; i < features.data.length; ++i) {
1569- features.data[i] = (features.data[i] - this.mean) / denom;
1570- }
1571- }
1572-
1573- return {
1574- input_values: new Tensor('float32',
1575- features.data,
1576- [1, ...features.dims]
1577- )
1578- };
1579- }
1662+ return {
1663+ input_values: new Tensor("float32", features.data, [1, ...features.dims]),
1664+ };
1665+ }
15801666 }
15811667
15821668 export class ClapFeatureExtractor extends FeatureExtractor {
1583-
1584- constructor(config) {
1585- super(config);
1586-
1587- this.mel_filters = mel_filter_bank(
1588- this.config.nb_frequency_bins, // num_frequency_bins
1589- this.config.feature_size, // num_mel_filters
1590- this.config.frequency_min, // min_frequency
1591- this.config.frequency_max, // max_frequency
1592- this.config.sampling_rate, // sampling_rate
1593- null, // norm
1594- "htk", // mel_scale
1595- );
1596-
1597- this.mel_filters_slaney = mel_filter_bank(
1598- this.config.nb_frequency_bins, // num_frequency_bins
1599- this.config.feature_size, // num_mel_filters
1600- this.config.frequency_min, // min_frequency
1601- this.config.frequency_max, // max_frequency
1602- this.config.sampling_rate, // sampling_rate
1603- "slaney", // norm
1604- "slaney", // mel_scale
1669+ constructor(config) {
1670+ super(config);
1671+
1672+ this.mel_filters = mel_filter_bank(
1673+ this.config.nb_frequency_bins, // num_frequency_bins
1674+ this.config.feature_size, // num_mel_filters
1675+ this.config.frequency_min, // min_frequency
1676+ this.config.frequency_max, // max_frequency
1677+ this.config.sampling_rate, // sampling_rate
1678+ null, // norm
1679+ "htk", // mel_scale
1680+ );
1681+
1682+ this.mel_filters_slaney = mel_filter_bank(
1683+ this.config.nb_frequency_bins, // num_frequency_bins
1684+ this.config.feature_size, // num_mel_filters
1685+ this.config.frequency_min, // min_frequency
1686+ this.config.frequency_max, // max_frequency
1687+ this.config.sampling_rate, // sampling_rate
1688+ "slaney", // norm
1689+ "slaney", // mel_scale
1690+ );
1691+
1692+ this.window = window_function(this.config.fft_window_size, "hann");
1693+ }
1694+
1695+ /**
1696+ * Extracts the mel spectrogram and prepares it for the mode based on the `truncation` and `padding` arguments.
1697+ *
1698+ * Four different path are possible:
1699+ * - `truncation="fusion"` and the length of the waveform is greater than the max length: the mel spectrogram
1700+ * will be computed on the entire audio. 3 random crops and a dowsampled version of the full mel spectrogram
1701+ * are then stacked together. They will later be used for `feature_fusion`.
1702+ * - `truncation="rand_trunc"` and the length of the waveform is smaller than the max length: the audio is
1703+ * padded based on `padding`.
1704+ * - `truncation="fusion"` and the length of the waveform is smaller than the max length: the audio is padded
1705+ * based on `padding`, and is repeated `4` times.
1706+ * - `truncation="rand_trunc"` and the length of the waveform is greater than the max length: the mel
1707+ * spectrogram will be computed on a random crop of the waveform.
1708+ *
1709+ * @param {Float32Array|Float64Array} waveform The input waveform.
1710+ * @param {number} max_length The maximum length of the waveform.
1711+ * @param {string} truncation The truncation strategy to use.
1712+ * @param {string} padding The padding strategy to use.
1713+ * @returns {{ data: Float32Array; dims: number[]; longer: boolean; }} An object containing the mel spectrogram data as a Float32Array, its dimensions as an array of numbers, and a boolean indicating whether the waveform was longer than the max length.
1714+ */
1715+ _get_input_mel(waveform, max_length, truncation, padding) {
1716+ /** @type {{ data: Float32Array; dims: number[]}} */
1717+ let input_mel;
1718+ let longer = false;
1719+ const diff = waveform.length - max_length;
1720+ if (diff > 0) {
1721+ if (truncation === "rand_trunc") {
1722+ longer = true;
1723+ const idx = Math.floor(Math.random() * (diff + 1));
1724+ waveform = waveform.subarray(idx, idx + max_length);
1725+
1726+ input_mel = this._extract_fbank_features(
1727+ waveform,
1728+ this.mel_filters_slaney,
1729+ this.config.nb_max_samples,
16051730 );
1606-
1607- this.window = window_function(this.config.fft_window_size, 'hann')
1608-
1609- }
1610-
1611-
1612- /**
1613- * Extracts the mel spectrogram and prepares it for the mode based on the `truncation` and `padding` arguments.
1614- *
1615- * Four different path are possible:
1616- * - `truncation="fusion"` and the length of the waveform is greater than the max length: the mel spectrogram
1617- * will be computed on the entire audio. 3 random crops and a dowsampled version of the full mel spectrogram
1618- * are then stacked together. They will later be used for `feature_fusion`.
1619- * - `truncation="rand_trunc"` and the length of the waveform is smaller than the max length: the audio is
1620- * padded based on `padding`.
1621- * - `truncation="fusion"` and the length of the waveform is smaller than the max length: the audio is padded
1622- * based on `padding`, and is repeated `4` times.
1623- * - `truncation="rand_trunc"` and the length of the waveform is greater than the max length: the mel
1624- * spectrogram will be computed on a random crop of the waveform.
1625- *
1626- * @param {Float32Array|Float64Array} waveform The input waveform.
1627- * @param {number} max_length The maximum length of the waveform.
1628- * @param {string} truncation The truncation strategy to use.
1629- * @param {string} padding The padding strategy to use.
1630- * @returns {{ data: Float32Array; dims: number[]; longer: boolean; }} An object containing the mel spectrogram data as a Float32Array, its dimensions as an array of numbers, and a boolean indicating whether the waveform was longer than the max length.
1631- */
1632- _get_input_mel(waveform, max_length, truncation, padding) {
1633-
1634- /** @type {{ data: Float32Array; dims: number[]}} */
1635- let input_mel;
1636- let longer = false;
1637- const diff = waveform.length - max_length;
1638- if (diff > 0) {
1639- if (truncation === 'rand_trunc') {
1640- longer = true;
1641- const idx = Math.floor(Math.random() * (diff + 1));
1642- waveform = waveform.subarray(idx, idx + max_length);
1643-
1644- input_mel = this._extract_fbank_features(waveform, this.mel_filters_slaney, this.config.nb_max_samples);
1645- input_mel.dims = [1, ...input_mel.dims]; // "unsqueeze"
1646- } else {
1647- // TODO implement fusion strategy
1648- throw new Error(`Truncation strategy "${truncation}" not implemented`)
1649- }
1650- } else {
1651- if (diff < 0) {
1652- let padded = new Float64Array(max_length); // already padded with zeros
1653- padded.set(waveform);
1654-
1655- if (padding === 'repeat') {
1656- for (let i = waveform.length; i < max_length; i += waveform.length) {
1657- padded.set(waveform.subarray(0, Math.min(waveform.length, max_length - i)), i);
1658- }
1659- } else if (padding === 'repeatpad') {
1660- for (let i = waveform.length; i < -diff; i += waveform.length) {
1661- padded.set(waveform, i);
1662- }
1663- }
1664- waveform = padded;
1665- }
1666-
1667- if (truncation === 'fusion') {
1668- throw new Error(`Truncation strategy "${truncation}" not implemented`)
1669- }
1670-
1671- input_mel = this._extract_fbank_features(waveform, this.mel_filters_slaney, this.config.nb_max_samples);
1672- input_mel.dims = [1, ...input_mel.dims]; // "unsqueeze"
1673- }
1674-
1675- return {
1676- ...input_mel,
1677- longer,
1731+ input_mel.dims = [1, ...input_mel.dims]; // "unsqueeze"
1732+ } else {
1733+ // TODO implement fusion strategy
1734+ throw new Error(`Truncation strategy "${truncation}" not implemented`);
1735+ }
1736+ } else {
1737+ if (diff < 0) {
1738+ let padded = new Float64Array(max_length); // already padded with zeros
1739+ padded.set(waveform);
1740+
1741+ if (padding === "repeat") {
1742+ for (let i = waveform.length; i < max_length; i += waveform.length) {
1743+ padded.set(
1744+ waveform.subarray(0, Math.min(waveform.length, max_length - i)),
1745+ i,
1746+ );
1747+ }
1748+ } else if (padding === "repeatpad") {
1749+ for (let i = waveform.length; i < -diff; i += waveform.length) {
1750+ padded.set(waveform, i);
1751+ }
16781752 }
1753+ waveform = padded;
1754+ }
1755+
1756+ if (truncation === "fusion") {
1757+ throw new Error(`Truncation strategy "${truncation}" not implemented`);
1758+ }
1759+
1760+ input_mel = this._extract_fbank_features(
1761+ waveform,
1762+ this.mel_filters_slaney,
1763+ this.config.nb_max_samples,
1764+ );
1765+ input_mel.dims = [1, ...input_mel.dims]; // "unsqueeze"
16791766 }
16801767
1681- /**
1682- * Compute the log-mel spectrogram of the provided `waveform` using the Hann window.
1683- * In CLAP, two different filter banks are used depending on the truncation pattern:
1684- * - `self.mel_filters`: they correspond to the default parameters of `torchaudio` which can be obtained from
1685- * calling `torchaudio.transforms.MelSpectrogram().mel_scale.fb`. These filters are used when `truncation`
1686- * is set to `"fusion"`.
1687- * - `self.mel_filteres_slaney` : they correspond to the default parameters of `librosa` which used
1688- * `librosa.filters.mel` when computing the mel spectrogram. These filters were only used in the original
1689- * implementation when the truncation mode is not `"fusion"`.
1690- *
1691- * @param {Float32Array|Float64Array} waveform The audio waveform to process.
1692- * @param {number[][]} mel_filters The mel filters to use.
1693- * @param {number} [max_length=null] The maximum number of frames to return.
1694- * @returns {{data: Float32Array, dims: number[]}} An object containing the log-Mel spectrogram data as a Float32Array and its dimensions as an array of numbers.
1695- */
1696- _extract_fbank_features(waveform, mel_filters, max_length = null) {
1697- // NOTE: We don't pad/truncate since that is passed in as `max_num_frames`
1698- return spectrogram(
1699- waveform,
1700- this.window, // window
1701- this.config.fft_window_size, // frame_length
1702- this.config.hop_length, // hop_length
1703- {
1704- power: 2.0,
1705- mel_filters,
1706- log_mel: 'dB',
1707-
1708- // Custom
1709- max_num_frames: max_length,
1710- do_pad: false,
1711- transpose: true,
1712- }
1713- )
1714- }
1715-
1716-
1717- /**
1718- * Asynchronously extracts features from a given audio using the provided configuration.
1719- * @param {Float32Array|Float64Array} audio The audio data as a Float32Array/Float64Array.
1720- * @returns {Promise<{ input_features: Tensor }>} A Promise resolving to an object containing the extracted input features as a Tensor.
1721- */
1722- async _call(audio, {
1723- max_length = null,
1724- } = {}) {
1725- validate_audio_inputs(audio, 'ClapFeatureExtractor');
1726-
1727- // convert to mel spectrogram, truncate and pad if needed.
1728- const padded_inputs = this._get_input_mel(
1729- audio,
1730- max_length ?? this.config.nb_max_samples,
1731- this.config.truncation,
1732- this.config.padding,
1733- );
1734-
1735-
1736- return {
1737- input_features: new Tensor('float32',
1738- padded_inputs.data,
1739- [1, ...padded_inputs.dims]
1740- )
1741- };
1742- }
1768+ return {
1769+ ...input_mel,
1770+ longer,
1771+ };
1772+ }
1773+
1774+ /**
1775+ * Compute the log-mel spectrogram of the provided `waveform` using the Hann window.
1776+ * In CLAP, two different filter banks are used depending on the truncation pattern:
1777+ * - `self.mel_filters`: they correspond to the default parameters of `torchaudio` which can be obtained from
1778+ * calling `torchaudio.transforms.MelSpectrogram().mel_scale.fb`. These filters are used when `truncation`
1779+ * is set to `"fusion"`.
1780+ * - `self.mel_filteres_slaney` : they correspond to the default parameters of `librosa` which used
1781+ * `librosa.filters.mel` when computing the mel spectrogram. These filters were only used in the original
1782+ * implementation when the truncation mode is not `"fusion"`.
1783+ *
1784+ * @param {Float32Array|Float64Array} waveform The audio waveform to process.
1785+ * @param {number[][]} mel_filters The mel filters to use.
1786+ * @param {number} [max_length=null] The maximum number of frames to return.
1787+ * @returns {{data: Float32Array, dims: number[]}} An object containing the log-Mel spectrogram data as a Float32Array and its dimensions as an array of numbers.
1788+ */
1789+ _extract_fbank_features(waveform, mel_filters, max_length = null) {
1790+ // NOTE: We don't pad/truncate since that is passed in as `max_num_frames`
1791+ return spectrogram(
1792+ waveform,
1793+ this.window, // window
1794+ this.config.fft_window_size, // frame_length
1795+ this.config.hop_length, // hop_length
1796+ {
1797+ power: 2.0,
1798+ mel_filters,
1799+ log_mel: "dB",
1800+
1801+ // Custom
1802+ max_num_frames: max_length,
1803+ do_pad: false,
1804+ transpose: true,
1805+ },
1806+ );
1807+ }
1808+
1809+ /**
1810+ * Asynchronously extracts features from a given audio using the provided configuration.
1811+ * @param {Float32Array|Float64Array} audio The audio data as a Float32Array/Float64Array.
1812+ * @returns {Promise<{ input_features: Tensor }>} A Promise resolving to an object containing the extracted input features as a Tensor.
1813+ */
1814+ async _call(audio, { max_length = null } = {}) {
1815+ validate_audio_inputs(audio, "ClapFeatureExtractor");
1816+
1817+ // convert to mel spectrogram, truncate and pad if needed.
1818+ const padded_inputs = this._get_input_mel(
1819+ audio,
1820+ max_length ?? this.config.nb_max_samples,
1821+ this.config.truncation,
1822+ this.config.padding,
1823+ );
1824+
1825+ return {
1826+ input_features: new Tensor("float32", padded_inputs.data, [
1827+ 1,
1828+ ...padded_inputs.dims,
1829+ ]),
1830+ };
1831+ }
17431832 }
17441833
1745-
1746-
1747-export class SpeechT5FeatureExtractor extends FeatureExtractor { }
1834+export class SpeechT5FeatureExtractor extends FeatureExtractor {}
17481835
17491836 /**
17501837 * Represents a Processor that extracts features from an input.
17511838 * @extends Callable
17521839 */
17531840 export class Processor extends Callable {
1754- /**
1755- * Creates a new Processor with the given feature extractor.
1756- * @param {FeatureExtractor} feature_extractor The function used to extract features from the input.
1757- */
1758- constructor(feature_extractor) {
1759- super();
1760- this.feature_extractor = feature_extractor;
1761- // TODO use tokenizer here?
1762- }
1763-
1764- /**
1765- * Calls the feature_extractor function with the given input.
1766- * @param {any} input The input to extract features from.
1767- * @param {...any} args Additional arguments.
1768- * @returns {Promise<any>} A Promise that resolves with the extracted features.
1769- */
1770- async _call(input, ...args) {
1771- return await this.feature_extractor(input, ...args);
1772- }
1841+ /**
1842+ * Creates a new Processor with the given feature extractor.
1843+ * @param {FeatureExtractor} feature_extractor The function used to extract features from the input.
1844+ */
1845+ constructor(feature_extractor) {
1846+ super();
1847+ this.feature_extractor = feature_extractor;
1848+ // TODO use tokenizer here?
1849+ }
1850+
1851+ /**
1852+ * Calls the feature_extractor function with the given input.
1853+ * @param {any} input The input to extract features from.
1854+ * @param {...any} args Additional arguments.
1855+ * @returns {Promise<any>} A Promise that resolves with the extracted features.
1856+ */
1857+ async _call(input, ...args) {
1858+ return await this.feature_extractor(input, ...args);
1859+ }
17731860 }
17741861
17751862 export class SamProcessor extends Processor {
1776- /**
1777- * @borrows SamImageProcessor#_call as _call
1778- */
1779- async _call(...args) {
1780- return await this.feature_extractor(...args);
1781- }
1782-
1783- /**
1784- * @borrows SamImageProcessor#post_process_masks as post_process_masks
1785- */
1786- post_process_masks(...args) {
1787- // @ts-ignore
1788- return this.feature_extractor.post_process_masks(...args);
1789- }
1790- /**
1791- * @borrows SamImageProcessor#reshape_input_points as reshape_input_points
1792- */
1793- reshape_input_points(...args) {
1794- // @ts-ignore
1795- return this.feature_extractor.reshape_input_points(...args);
1796- }
1863+ /**
1864+ * @borrows SamImageProcessor#_call as _call
1865+ */
1866+ async _call(...args) {
1867+ return await this.feature_extractor(...args);
1868+ }
1869+
1870+ /**
1871+ * @borrows SamImageProcessor#post_process_masks as post_process_masks
1872+ */
1873+ post_process_masks(...args) {
1874+ // @ts-ignore
1875+ return this.feature_extractor.post_process_masks(...args);
1876+ }
1877+ /**
1878+ * @borrows SamImageProcessor#reshape_input_points as reshape_input_points
1879+ */
1880+ reshape_input_points(...args) {
1881+ // @ts-ignore
1882+ return this.feature_extractor.reshape_input_points(...args);
1883+ }
17971884 }
17981885
17991886 /**
@@ -1801,52 +1888,50 @@
18011888 * @extends Processor
18021889 */
18031890 export class WhisperProcessor extends Processor {
1804- /**
1805- * Calls the feature_extractor function with the given audio input.
1806- * @param {any} audio The audio input to extract features from.
1807- * @returns {Promise<any>} A Promise that resolves with the extracted features.
1808- */
1809- async _call(audio) {
1810- return await this.feature_extractor(audio)
1811- }
1891+ /**
1892+ * Calls the feature_extractor function with the given audio input.
1893+ * @param {any} audio The audio input to extract features from.
1894+ * @returns {Promise<any>} A Promise that resolves with the extracted features.
1895+ */
1896+ async _call(audio) {
1897+ return await this.feature_extractor(audio);
1898+ }
18121899 }
18131900
1814-
18151901 export class Wav2Vec2ProcessorWithLM extends Processor {
1816- /**
1817- * Calls the feature_extractor function with the given audio input.
1818- * @param {any} audio The audio input to extract features from.
1819- * @returns {Promise<any>} A Promise that resolves with the extracted features.
1820- */
1821- async _call(audio) {
1822- return await this.feature_extractor(audio)
1823- }
1902+ /**
1903+ * Calls the feature_extractor function with the given audio input.
1904+ * @param {any} audio The audio input to extract features from.
1905+ * @returns {Promise<any>} A Promise that resolves with the extracted features.
1906+ */
1907+ async _call(audio) {
1908+ return await this.feature_extractor(audio);
1909+ }
18241910 }
18251911
18261912 export class SpeechT5Processor extends Processor {
1827- /**
1828- * Calls the feature_extractor function with the given input.
1829- * @param {any} input The input to extract features from.
1830- * @returns {Promise<any>} A Promise that resolves with the extracted features.
1831- */
1832- async _call(input) {
1833- return await this.feature_extractor(input)
1834- }
1913+ /**
1914+ * Calls the feature_extractor function with the given input.
1915+ * @param {any} input The input to extract features from.
1916+ * @returns {Promise<any>} A Promise that resolves with the extracted features.
1917+ */
1918+ async _call(input) {
1919+ return await this.feature_extractor(input);
1920+ }
18351921 }
18361922
1837-export class OwlViTProcessor extends Processor { }
1838-
1923+export class OwlViTProcessor extends Processor {}
18391924
18401925 //////////////////////////////////////////////////
18411926 /**
18421927 * Helper class which is used to instantiate pretrained processors with the `from_pretrained` function.
18431928 * The chosen processor class is determined by the type specified in the processor config.
1844- *
1929+ *
18451930 * **Example:** Load a processor using `from_pretrained`.
18461931 * ```javascript
18471932 * let processor = await AutoProcessor.from_pretrained('openai/whisper-tiny.en');
18481933 * ```
1849- *
1934+ *
18501935 * **Example:** Run an image through a processor.
18511936 * ```javascript
18521937 * let processor = await AutoProcessor.from_pretrained('Xenova/clip-vit-base-patch16');
@@ -1869,98 +1954,112 @@
18691954 * ```
18701955 */
18711956 export class AutoProcessor {
1872- static FEATURE_EXTRACTOR_CLASS_MAPPING = {
1873- WhisperFeatureExtractor,
1874- ViTFeatureExtractor,
1875- MobileViTFeatureExtractor,
1876- OwlViTFeatureExtractor,
1877- CLIPFeatureExtractor,
1878- ChineseCLIPFeatureExtractor,
1879- SiglipImageProcessor,
1880- ConvNextFeatureExtractor,
1881- ConvNextImageProcessor,
1882- SegformerFeatureExtractor,
1883- BitImageProcessor,
1884- DPTFeatureExtractor,
1885- GLPNFeatureExtractor,
1886- BeitFeatureExtractor,
1887- DeiTFeatureExtractor,
1888- DetrFeatureExtractor,
1889- YolosFeatureExtractor,
1890- DonutFeatureExtractor,
1891- NougatImageProcessor,
1892-
1893- ViTImageProcessor,
1894- VitMatteImageProcessor,
1895- SamImageProcessor,
1896- Swin2SRImageProcessor,
1897- Wav2Vec2FeatureExtractor,
1898- SpeechT5FeatureExtractor,
1899- ASTFeatureExtractor,
1900- ClapFeatureExtractor,
1901- }
1902-
1903- static PROCESSOR_CLASS_MAPPING = {
1904- WhisperProcessor,
1905- Wav2Vec2ProcessorWithLM,
1906- SamProcessor,
1907- SpeechT5Processor,
1908- OwlViTProcessor,
1957+ static FEATURE_EXTRACTOR_CLASS_MAPPING = {
1958+ WhisperFeatureExtractor,
1959+ ViTFeatureExtractor,
1960+ MobileViTFeatureExtractor,
1961+ OwlViTFeatureExtractor,
1962+ CLIPFeatureExtractor,
1963+ ChineseCLIPFeatureExtractor,
1964+ SiglipImageProcessor,
1965+ ConvNextFeatureExtractor,
1966+ ConvNextImageProcessor,
1967+ SegformerFeatureExtractor,
1968+ BitImageProcessor,
1969+ DPTFeatureExtractor,
1970+ GLPNFeatureExtractor,
1971+ BeitFeatureExtractor,
1972+ DeiTFeatureExtractor,
1973+ DetrFeatureExtractor,
1974+ YolosFeatureExtractor,
1975+ DonutFeatureExtractor,
1976+ NougatImageProcessor,
1977+
1978+ ViTImageProcessor,
1979+ VitMatteImageProcessor,
1980+ SamImageProcessor,
1981+ Swin2SRImageProcessor,
1982+ Wav2Vec2FeatureExtractor,
1983+ SpeechT5FeatureExtractor,
1984+ ASTFeatureExtractor,
1985+ ClapFeatureExtractor,
1986+ };
1987+
1988+ static PROCESSOR_CLASS_MAPPING = {
1989+ WhisperProcessor,
1990+ Wav2Vec2ProcessorWithLM,
1991+ SamProcessor,
1992+ SpeechT5Processor,
1993+ OwlViTProcessor,
1994+ };
1995+
1996+ /**
1997+ * Instantiate one of the processor classes of the library from a pretrained model.
1998+ *
1999+ * The processor class to instantiate is selected based on the `feature_extractor_type` property of the config object
2000+ * (either passed as an argument or loaded from `pretrained_model_name_or_path` if possible)
2001+ *
2002+ * @param {string} pretrained_model_name_or_path The name or path of the pretrained model. Can be either:
2003+ * - A string, the *model id* of a pretrained processor hosted inside a model repo on huggingface.co.
2004+ * Valid model ids can be located at the root-level, like `bert-base-uncased`, or namespaced under a
2005+ * user or organization name, like `dbmdz/bert-base-german-cased`.
2006+ * - A path to a *directory* containing processor files, e.g., `./my_model_directory/`.
2007+ * @param {import('./utils/hub.js').PretrainedOptions} options Additional options for loading the processor.
2008+ *
2009+ * @returns {Promise<Processor>} A new instance of the Processor class.
2010+ */
2011+ static async from_pretrained(
2012+ pretrained_model_name_or_path,
2013+ {
2014+ progress_callback = null,
2015+ config = null,
2016+ cache_dir = null,
2017+ local_files_only = false,
2018+ revision = "main",
2019+ } = {},
2020+ ) {
2021+ let preprocessorConfig =
2022+ config ??
2023+ (await getModelJSON(
2024+ pretrained_model_name_or_path,
2025+ "preprocessor_config.json",
2026+ true,
2027+ {
2028+ progress_callback,
2029+ config,
2030+ cache_dir,
2031+ local_files_only,
2032+ revision,
2033+ },
2034+ ));
2035+
2036+ // Determine feature extractor class
2037+ // TODO: Ensure backwards compatibility with old configs
2038+ let key =
2039+ preprocessorConfig.feature_extractor_type ??
2040+ preprocessorConfig.image_processor_type;
2041+ let feature_extractor_class = this.FEATURE_EXTRACTOR_CLASS_MAPPING[key];
2042+
2043+ if (!feature_extractor_class) {
2044+ if (preprocessorConfig.size !== undefined) {
2045+ // Assume ImageFeatureExtractor
2046+ console.warn(
2047+ `Feature extractor type "${key}" not found, assuming ImageFeatureExtractor due to size parameter in config.`,
2048+ );
2049+ feature_extractor_class = ImageFeatureExtractor;
2050+ } else {
2051+ throw new Error(`Unknown Feature Extractor type: ${key}`);
2052+ }
19092053 }
19102054
1911- /**
1912- * Instantiate one of the processor classes of the library from a pretrained model.
1913- *
1914- * The processor class to instantiate is selected based on the `feature_extractor_type` property of the config object
1915- * (either passed as an argument or loaded from `pretrained_model_name_or_path` if possible)
1916- *
1917- * @param {string} pretrained_model_name_or_path The name or path of the pretrained model. Can be either:
1918- * - A string, the *model id* of a pretrained processor hosted inside a model repo on huggingface.co.
1919- * Valid model ids can be located at the root-level, like `bert-base-uncased`, or namespaced under a
1920- * user or organization name, like `dbmdz/bert-base-german-cased`.
1921- * - A path to a *directory* containing processor files, e.g., `./my_model_directory/`.
1922- * @param {import('./utils/hub.js').PretrainedOptions} options Additional options for loading the processor.
1923- *
1924- * @returns {Promise<Processor>} A new instance of the Processor class.
1925- */
1926- static async from_pretrained(pretrained_model_name_or_path, {
1927- progress_callback = null,
1928- config = null,
1929- cache_dir = null,
1930- local_files_only = false,
1931- revision = 'main',
1932- } = {}) {
1933-
1934- let preprocessorConfig = config ?? await getModelJSON(pretrained_model_name_or_path, 'preprocessor_config.json', true, {
1935- progress_callback,
1936- config,
1937- cache_dir,
1938- local_files_only,
1939- revision,
1940- })
1941-
1942- // Determine feature extractor class
1943- // TODO: Ensure backwards compatibility with old configs
1944- let key = preprocessorConfig.feature_extractor_type ?? preprocessorConfig.image_processor_type;
1945- let feature_extractor_class = this.FEATURE_EXTRACTOR_CLASS_MAPPING[key];
1946-
1947- if (!feature_extractor_class) {
1948- if (preprocessorConfig.size !== undefined) {
1949- // Assume ImageFeatureExtractor
1950- console.warn(`Feature extractor type "${key}" not found, assuming ImageFeatureExtractor due to size parameter in config.`);
1951- feature_extractor_class = ImageFeatureExtractor;
1952- } else {
1953- throw new Error(`Unknown Feature Extractor type: ${key}`);
1954- }
1955- }
1956-
1957- // If no associated processor class, use default
1958- let processor_class = this.PROCESSOR_CLASS_MAPPING[preprocessorConfig.processor_class] ?? Processor;
1959-
1960- // Instantiate processor and feature extractor
1961- let feature_extractor = new feature_extractor_class(preprocessorConfig);
1962- return new processor_class(feature_extractor);
1963- }
2055+ // If no associated processor class, use default
2056+ let processor_class =
2057+ this.PROCESSOR_CLASS_MAPPING[preprocessorConfig.processor_class] ??
2058+ Processor;
2059+
2060+ // Instantiate processor and feature extractor
2061+ let feature_extractor = new feature_extractor_class(preprocessorConfig);
2062+ return new processor_class(feature_extractor);
2063+ }
19642064 }
19652065 //////////////////////////////////////////////////
1966-
modified core/vendor/modules/@xenova/transformers/src/tokenizers.js +3747 −3564

The diff of this file is cut short. View the file.

@@ -1,12 +1,11 @@
1-
21 /**
32 * @file Tokenizers are used to prepare textual inputs for a model.
4- *
3+ *
54 * **Example:** Create an `AutoTokenizer` and use it to tokenize a sentence.
65 * This will automatically detect the tokenizer type based on the tokenizer class defined in `tokenizer.json`.
76 * ```javascript
87 * import { AutoTokenizer } from '@xenova/transformers';
9- *
8+ *
109 * const tokenizer = await AutoTokenizer.from_pretrained('Xenova/bert-base-uncased');
1110 * const { input_ids } = await tokenizer('I love transformers!');
1211 * // Tensor {
@@ -16,33 +15,30 @@
1615 * // size: 6,
1716 * // }
1817 * ```
19- *
18+ *
2019 * @module tokenizers
2120 */
2221
2322 import {
24- Callable,
25- reverseDictionary,
26- escapeRegExp,
27- isIntegralNumber,
28- mergeArrays,
29-} from './utils/core.js';
23+ Callable,
24+ reverseDictionary,
25+ escapeRegExp,
26+ isIntegralNumber,
27+ mergeArrays,
28+} from "./utils/core.js";
3029
31-import {
32- getModelJSON,
33-} from './utils/hub.js';
30+import { getModelJSON } from "./utils/hub.js";
3431
35-import { max, min, round } from './utils/maths.js';
36-import { Tensor } from './utils/tensor.js';
32+import { max, min, round } from "./utils/maths.js";
33+import { Tensor } from "./utils/tensor.js";
3734
3835 import {
39- PriorityQueue,
40- TokenLattice,
41- CharTrie,
42-} from './utils/data-structures.js';
43-
44-import { Template } from '@huggingface/jinja';
36+ PriorityQueue,
37+ TokenLattice,
38+ CharTrie,
39+} from "./utils/data-structures.js";
4540
41+import { Template } from "@huggingface/jinja";
4642
4743 /**
4844 * @typedef {Object} TokenizerProperties Additional tokenizer-specific properties.
@@ -57,20 +53,28 @@
5753 * @returns {Promise<any[]>} A promise that resolves with information about the loaded tokenizer.
5854 */
5955 async function loadTokenizer(pretrained_model_name_or_path, options) {
60-
61- const info = await Promise.all([
62- getModelJSON(pretrained_model_name_or_path, 'tokenizer.json', true, options),
63- getModelJSON(pretrained_model_name_or_path, 'tokenizer_config.json', true, options),
64- ])
65-
66- // Override legacy option if `options.legacy` is not null
67- if (options.legacy !== null) {
68- info[1].legacy = options.legacy;
69- }
70- return info;
56+ const info = await Promise.all([
57+ getModelJSON(
58+ pretrained_model_name_or_path,
59+ "tokenizer.json",
60+ true,
61+ options,
62+ ),
63+ getModelJSON(
64+ pretrained_model_name_or_path,
65+ "tokenizer_config.json",
66+ true,
67+ options,
68+ ),
69+ ]);
70+
71+ // Override legacy option if `options.legacy` is not null
72+ if (options.legacy !== null) {
73+ info[1].legacy = options.legacy;
74+ }
75+ return info;
7176 }
7277
73-
7478 /**
7579 * Helper function to split a string on a regex, but keep the delimiters.
7680 * This is required, because the JavaScript `.split()` method does not keep the delimiters,
@@ -80,25 +84,24 @@
8084 * @returns {string[]} The split string.
8185 */
8286 function regexSplit(text, regex) {
83- const result = [];
84- let prev = 0;
85- for (const match of text.matchAll(regex)) {
86- const fullMatch = match[0];
87- if (prev < match.index) {
88- result.push(text.slice(prev, match.index));
89- }
90- if (fullMatch.length > 0) {
91- result.push(fullMatch);
92- }
93- prev = match.index + fullMatch.length;
87+ const result = [];
88+ let prev = 0;
89+ for (const match of text.matchAll(regex)) {
90+ const fullMatch = match[0];
91+ if (prev < match.index) {
92+ result.push(text.slice(prev, match.index));
9493 }
95- if (prev < text.length) {
96- result.push(text.slice(prev));
94+ if (fullMatch.length > 0) {
95+ result.push(fullMatch);
9796 }
98- return result;
97+ prev = match.index + fullMatch.length;
98+ }
99+ if (prev < text.length) {
100+ result.push(text.slice(prev));
101+ }
102+ return result;
99103 }
100104
101-
102105 /**
103106 * Helper method to construct a pattern from a config object.
104107 * @param {Object} pattern The pattern object.
@@ -106,25 +109,22 @@
106109 * @returns {RegExp|null} The compiled pattern.
107110 */
108111 function createPattern(pattern, invert = true) {
109-
110- if (pattern.Regex !== undefined) {
111- // In certain cases, the pattern may contain unnecessary escape sequences (e.g., \# or \& or \~).
112- // i.e., valid in Python (where the patterns are exported from) but invalid in JavaScript (where the patterns are parsed).
113- // This isn't an issue when creating the regex w/o the 'u' flag, but it is when the 'u' flag is used.
114- // For this reason, it is necessary to remove these backslashes before creating the regex.
115- // See https://stackoverflow.com/a/63007777/13989043 for more information
116- const regex = pattern.Regex.replace(/\\([#&~])/g, '$1'); // TODO: add more characters to this list if necessary
117- return new RegExp(regex, 'gu');
118-
119- } else if (pattern.String !== undefined) {
120- const escaped = escapeRegExp(pattern.String);
121- // NOTE: if invert is true, we wrap the pattern in a group so that it is kept when performing .split()
122- return new RegExp(invert ? escaped : `(${escaped})`, 'gu');
123-
124- } else {
125- console.warn('Unknown pattern type:', pattern)
126- return null;
127- }
112+ if (pattern.Regex !== undefined) {
113+ // In certain cases, the pattern may contain unnecessary escape sequences (e.g., \# or \& or \~).
114+ // i.e., valid in Python (where the patterns are exported from) but invalid in JavaScript (where the patterns are parsed).
115+ // This isn't an issue when creating the regex w/o the 'u' flag, but it is when the 'u' flag is used.
116+ // For this reason, it is necessary to remove these backslashes before creating the regex.
117+ // See https://stackoverflow.com/a/63007777/13989043 for more information
118+ const regex = pattern.Regex.replace(/\\([#&~])/g, "$1"); // TODO: add more characters to this list if necessary
119+ return new RegExp(regex, "gu");
120+ } else if (pattern.String !== undefined) {
121+ const escaped = escapeRegExp(pattern.String);
122+ // NOTE: if invert is true, we wrap the pattern in a group so that it is kept when performing .split()
123+ return new RegExp(invert ? escaped : `(${escaped})`, "gu");
124+ } else {
125+ console.warn("Unknown pattern type:", pattern);
126+ return null;
127+ }
128128 }
129129
130130 /**
@@ -133,7 +133,7 @@
133133 * @returns {Map<string, any>} The map.
134134 */
135135 function objectToMap(obj) {
136- return new Map(Object.entries(obj));
136+ return new Map(Object.entries(obj));
137137 }
138138
139139 /**
@@ -142,18 +142,22 @@
142142 * @returns {number[]} The tensor as a list.
143143 */
144144 function prepareTensorForDecode(tensor) {
145- const dims = tensor.dims;
146- switch (dims.length) {
147- case 1:
148- return tensor.tolist();
149- case 2:
150- if (dims[0] !== 1) {
151- throw new Error('Unable to decode tensor with `batch size !== 1`. Use `tokenizer.batch_decode(...)` for batched inputs.');
152- }
153- return tensor.tolist()[0];
154- default:
155- throw new Error(`Expected tensor to have 1-2 dimensions, got ${dims.length}.`)
156- }
145+ const dims = tensor.dims;
146+ switch (dims.length) {
147+ case 1:
148+ return tensor.tolist();
149+ case 2:
150+ if (dims[0] !== 1) {
151+ throw new Error(
152+ "Unable to decode tensor with `batch size !== 1`. Use `tokenizer.batch_decode(...)` for batched inputs.",
153+ );
154+ }
155+ return tensor.tolist()[0];
156+ default:
157+ throw new Error(
158+ `Expected tensor to have 1-2 dimensions, got ${dims.length}.`,
159+ );
160+ }
157161 }
158162
159163 /**
@@ -162,18 +166,19 @@
162166 * @returns {string} The cleaned up text.
163167 */
164168 function clean_up_tokenization(text) {
165- // Clean up a list of simple English tokenization artifacts
166- // like spaces before punctuations and abbreviated forms
167- return text.replace(/ \./g, '.')
168- .replace(/ \?/g, '?')
169- .replace(/ \!/g, '!')
170- .replace(/ ,/g, ',')
171- .replace(/ \' /g, "'")
172- .replace(/ n\'t/g, "n't")
173- .replace(/ \'m/g, "'m")
174- .replace(/ \'s/g, "'s")
175- .replace(/ \'ve/g, "'ve")
176- .replace(/ \'re/g, "'re");
169+ // Clean up a list of simple English tokenization artifacts
170+ // like spaces before punctuations and abbreviated forms
171+ return text
172+ .replace(/ \./g, ".")
173+ .replace(/ \?/g, "?")
174+ .replace(/ \!/g, "!")
175+ .replace(/ ,/g, ",")
176+ .replace(/ \' /g, "'")
177+ .replace(/ n\'t/g, "n't")
178+ .replace(/ \'m/g, "'m")
179+ .replace(/ \'s/g, "'s")
180+ .replace(/ \'ve/g, "'ve")
181+ .replace(/ \'re/g, "'re");
177182 }
178183
179184 /**
@@ -182,7 +187,7 @@
182187 * @returns {string} The text with accents removed.
183188 */
184189 function remove_accents(text) {
185- return text.replace(/[\u0300-\u036f]/g, '');
190+ return text.replace(/[\u0300-\u036f]/g, "");
186191 }
187192
188193 /**
@@ -191,7 +196,7 @@
191196 * @returns {string} The lowercased text with accents removed.
192197 */
193198 function lowercase_and_remove_accent(text) {
194- return remove_accents(text.toLowerCase());
199+ return remove_accents(text.toLowerCase());
195200 }
196201
197202 /**
@@ -201,21 +206,21 @@
201206 * @param {Map<string, any>} mapping The mapping from input domain to value.
202207 */
203208 function fuse(arr, value, mapping) {
204- const fused = [];
205- let i = 0;
206- while (i < arr.length) {
207- fused.push(arr[i])
208- if ((mapping.get(arr[i]) ?? value) !== value) {
209- ++i;
210- continue;
211- }
209+ const fused = [];
210+ let i = 0;
211+ while (i < arr.length) {
212+ fused.push(arr[i]);
213+ if ((mapping.get(arr[i]) ?? value) !== value) {
214+ ++i;
215+ continue;
216+ }
212217
213- while (i < arr.length && (mapping.get(arr[i]) ?? value) === value) {
214- ++i;
215- }
218+ while (i < arr.length && (mapping.get(arr[i]) ?? value) === value) {
219+ ++i;
216220 }
221+ }
217222
218- return fused;
223+ return fused;
219224 }
220225
221226 /**
@@ -224,10 +229,11 @@
224229 * @returns {string[]} The split string.
225230 */
226231 function whitespace_split(text) {
227- return text.match(/\S+/g) || [];
232+ return text.match(/\S+/g) || [];
228233 }
229234
230-const PUNCTUATION_REGEX = '\\p{P}\\u0021-\\u002F\\u003A-\\u0040\\u005B-\\u0060\\u007B-\\u007E';
235+const PUNCTUATION_REGEX =
236+ "\\p{P}\\u0021-\\u002F\\u003A-\\u0040\\u005B-\\u0060\\u007B-\\u007E";
231237
232238 /**
233239 * Represent a token added by the user on top of the existing Model vocabulary.
@@ -236,26 +242,26 @@
236242 * - Whether to include any whitespace on its left or right
237243 */
238244 class AddedToken {
239- /**
240- * Creates a new instance of AddedToken.
241- * @param {Object} config Added token configuration object.
242- * @param {string} config.content The content of the added token.
243- * @param {number} config.id The id of the added token.
244- * @param {boolean} [config.single_word=false] Whether this token must be a single word or can break words.
245- * @param {boolean} [config.lstrip=false] Whether this token should strip whitespaces on its left.
246- * @param {boolean} [config.rstrip=false] Whether this token should strip whitespaces on its right.
247- * @param {boolean} [config.normalized=false] Whether this token should be normalized.
248- * @param {boolean} [config.special=false] Whether this token is special.
249- */
250- constructor(config) {
251- this.content = config.content;
252- this.id = config.id;
253- this.single_word = config.single_word ?? false;
254- this.lstrip = config.lstrip ?? false;
255- this.rstrip = config.rstrip ?? false;
256- this.special = config.special ?? false;
257- this.normalized = config.normalized ?? null;
258- }
245+ /**
246+ * Creates a new instance of AddedToken.
247+ * @param {Object} config Added token configuration object.
248+ * @param {string} config.content The content of the added token.
249+ * @param {number} config.id The id of the added token.
250+ * @param {boolean} [config.single_word=false] Whether this token must be a single word or can break words.
251+ * @param {boolean} [config.lstrip=false] Whether this token should strip whitespaces on its left.
252+ * @param {boolean} [config.rstrip=false] Whether this token should strip whitespaces on its right.
253+ * @param {boolean} [config.normalized=false] Whether this token should be normalized.
254+ * @param {boolean} [config.special=false] Whether this token is special.
255+ */
256+ constructor(config) {
257+ this.content = config.content;
258+ this.id = config.id;
259+ this.single_word = config.single_word ?? false;
260+ this.lstrip = config.lstrip ?? false;
261+ this.rstrip = config.rstrip ?? false;
262+ this.special = config.special ?? false;
263+ this.normalized = config.normalized ?? null;
264+ }
259265 }
260266
261267 /**
@@ -264,200 +270,199 @@
264270 * @extends Callable
265271 */
266272 export class TokenizerModel extends Callable {
273+ /**
274+ * Creates a new instance of TokenizerModel.
275+ * @param {Object} config The configuration object for the TokenizerModel.
276+ */
277+ constructor(config) {
278+ super();
279+ this.config = config;
280+
281+ /** @type {string[]} */
282+ this.vocab = [];
283+
267284 /**
268- * Creates a new instance of TokenizerModel.
269- * @param {Object} config The configuration object for the TokenizerModel.
285+ * A mapping of tokens to ids.
286+ * @type {Map<string, number>}
270287 */
271- constructor(config) {
272- super();
273- this.config = config;
288+ this.tokens_to_ids = new Map();
274289
275- /** @type {string[]} */
276- this.vocab = [];
290+ this.unk_token_id = undefined;
291+ this.unk_token = undefined;
292+ this.end_of_word_suffix = undefined;
277293
278- /**
279- * A mapping of tokens to ids.
280- * @type {Map<string, number>}
281- */
282- this.tokens_to_ids = new Map();
294+ /** @type {boolean} Whether to fuse unknown tokens when encoding. Defaults to false. */
295+ this.fuse_unk = this.config.fuse_unk ?? false;
296+ }
283297
284- this.unk_token_id = undefined;
285- this.unk_token = undefined;
286- this.end_of_word_suffix = undefined;
298+ /**
299+ * Instantiates a new TokenizerModel instance based on the configuration object provided.
300+ * @param {Object} config The configuration object for the TokenizerModel.
301+ * @param {...*} args Optional arguments to pass to the specific TokenizerModel constructor.
302+ * @returns {TokenizerModel} A new instance of a TokenizerModel.
303+ * @throws Will throw an error if the TokenizerModel type in the config is not recognized.
304+ */
305+ static fromConfig(config, ...args) {
306+ switch (config.type) {
307+ case "WordPiece":
308+ return new WordPieceTokenizer(config);
309+ case "Unigram":
310+ // @ts-ignore
311+ return new Unigram(config, ...args);
287312
288- /** @type {boolean} Whether to fuse unknown tokens when encoding. Defaults to false. */
289- this.fuse_unk = this.config.fuse_unk ?? false;
290- }
313+ case "BPE":
314+ return new BPE(config);
291315
292- /**
293- * Instantiates a new TokenizerModel instance based on the configuration object provided.
294- * @param {Object} config The configuration object for the TokenizerModel.
295- * @param {...*} args Optional arguments to pass to the specific TokenizerModel constructor.
296- * @returns {TokenizerModel} A new instance of a TokenizerModel.
297- * @throws Will throw an error if the TokenizerModel type in the config is not recognized.
298- */
299- static fromConfig(config, ...args) {
300- switch (config.type) {
301- case 'WordPiece':
302- return new WordPieceTokenizer(config);
303- case 'Unigram':
304- // @ts-ignore
305- return new Unigram(config, ...args);
306-
307- case 'BPE':
308- return new BPE(config);
309-
310- default:
311- if (config.vocab) {
312- // @ts-ignore
313- return new LegacyTokenizerModel(config, ...args);
314- }
315- throw new Error(`Unknown TokenizerModel type: ${config.type}`);
316+ default:
317+ if (config.vocab) {
318+ // @ts-ignore
319+ return new LegacyTokenizerModel(config, ...args);
316320 }
321+ throw new Error(`Unknown TokenizerModel type: ${config.type}`);
317322 }
323+ }
318324
319- /**
320- * Internal function to call the TokenizerModel instance.
321- * @param {string[]} tokens The tokens to encode.
322- * @returns {string[]} The encoded token IDs.
323- */
324- _call(tokens) {
325- let ids = this.encode(tokens);
326- if (this.fuse_unk) {
327- // Fuse unknown tokens
328- ids = fuse(ids, this.unk_token_id, this.tokens_to_ids);
329- }
330- return ids;
331- }
325+ /**
326+ * Internal function to call the TokenizerModel instance.
327+ * @param {string[]} tokens The tokens to encode.
328+ * @returns {string[]} The encoded token IDs.
329+ */
330+ _call(tokens) {
331+ let ids = this.encode(tokens);
332+ if (this.fuse_unk) {
333+ // Fuse unknown tokens
334+ ids = fuse(ids, this.unk_token_id, this.tokens_to_ids);
335+ }
336+ return ids;
337+ }
338+
339+ /**
340+ * Encodes a list of tokens into a list of token IDs.
341+ * @param {string[]} tokens The tokens to encode.
342+ * @returns {string[]} The encoded tokens.
343+ * @throws Will throw an error if not implemented in a subclass.
344+ */
345+ encode(tokens) {
346+ throw Error("encode should be implemented in subclass.");
347+ }
348+
349+ /**
350+ * Converts a list of tokens into a list of token IDs.
351+ * @param {string[]} tokens The tokens to convert.
352+ * @returns {number[]} The converted token IDs.
353+ */
354+ convert_tokens_to_ids(tokens) {
355+ return tokens.map((t) => this.tokens_to_ids.get(t) ?? this.unk_token_id);
356+ }
357+
358+ /**
359+ * Converts a list of token IDs into a list of tokens.
360+ * @param {number[]} ids The token IDs to convert.
361+ * @returns {string[]} The converted tokens.
362+ */
363+ convert_ids_to_tokens(ids) {
364+ return ids.map((i) => this.vocab[i] ?? this.unk_token);
365+ }
366+}
332367
368+/**
369+ * A subclass of TokenizerModel that uses WordPiece encoding to encode tokens.
370+ * @extends TokenizerModel
371+ */
372+class WordPieceTokenizer extends TokenizerModel {
373+ /**
374+ * @param {Object} config The configuration object.
375+ * @param {Object} config.vocab A mapping of tokens to ids.
376+ * @param {string} config.unk_token The unknown token string.
377+ * @param {string} config.continuing_subword_prefix The prefix to use for continuing subwords.
378+ * @param {number} [config.max_input_chars_per_word=100] The maximum number of characters per word.
379+ */
380+ constructor(config) {
381+ super(config);
333382 /**
334- * Encodes a list of tokens into a list of token IDs.
335- * @param {string[]} tokens The tokens to encode.
336- * @returns {string[]} The encoded tokens.
337- * @throws Will throw an error if not implemented in a subclass.
383+ * A mapping of tokens to ids.
384+ * @type {Map<string, number>}
338385 */
339- encode(tokens) {
340- throw Error("encode should be implemented in subclass.")
341- }
386+ this.tokens_to_ids = objectToMap(config.vocab);
342387
343388 /**
344- * Converts a list of tokens into a list of token IDs.
345- * @param {string[]} tokens The tokens to convert.
346- * @returns {number[]} The converted token IDs.
389+ * The id of the unknown token.
390+ * @type {number}
347391 */
348- convert_tokens_to_ids(tokens) {
349- return tokens.map(t => this.tokens_to_ids.get(t) ?? this.unk_token_id);
350- }
392+ this.unk_token_id = this.tokens_to_ids.get(config.unk_token);
351393
352394 /**
353- * Converts a list of token IDs into a list of tokens.
354- * @param {number[]} ids The token IDs to convert.
355- * @returns {string[]} The converted tokens.
395+ * The unknown token string.
396+ * @type {string}
356397 */
357- convert_ids_to_tokens(ids) {
358- return ids.map(i => this.vocab[i] ?? this.unk_token);
359- }
360-}
398+ this.unk_token = config.unk_token;
361399
362-/**
363- * A subclass of TokenizerModel that uses WordPiece encoding to encode tokens.
364- * @extends TokenizerModel
365- */
366-class WordPieceTokenizer extends TokenizerModel {
367400 /**
368- * @param {Object} config The configuration object.
369- * @param {Object} config.vocab A mapping of tokens to ids.
370- * @param {string} config.unk_token The unknown token string.
371- * @param {string} config.continuing_subword_prefix The prefix to use for continuing subwords.
372- * @param {number} [config.max_input_chars_per_word=100] The maximum number of characters per word.
401+ * The maximum number of characters allowed per word.
402+ * @type {number}
373403 */
374- constructor(config) {
375- super(config);
376- /**
377- * A mapping of tokens to ids.
378- * @type {Map<string, number>}
379- */
380- this.tokens_to_ids = objectToMap(config.vocab);
381-
382- /**
383- * The id of the unknown token.
384- * @type {number}
385- */
386- this.unk_token_id = this.tokens_to_ids.get(config.unk_token);
387-
388- /**
389- * The unknown token string.
390- * @type {string}
391- */
392- this.unk_token = config.unk_token;
393-
394- /**
395- * The maximum number of characters allowed per word.
396- * @type {number}
397- */
398- this.max_input_chars_per_word = config.max_input_chars_per_word ?? 100;
399-
400- /**
401- * An array of tokens.
402- * @type {string[]}
403- */
404- this.vocab = new Array(this.tokens_to_ids.size);
405- for (const [key, value] of this.tokens_to_ids) {
406- this.vocab[value] = key;
407- }
408- }
404+ this.max_input_chars_per_word = config.max_input_chars_per_word ?? 100;
409405
410406 /**
411- * Encodes an array of tokens using WordPiece encoding.
412- * @param {string[]} tokens The tokens to encode.
413- * @returns {string[]} An array of encoded tokens.
407+ * An array of tokens.
408+ * @type {string[]}
414409 */
415- encode(tokens) {
416- const outputTokens = [];
417- for (const token of tokens) {
418- const chars = [...token];
419- if (chars.length > this.max_input_chars_per_word) {
420- outputTokens.push(this.unk_token);
421- continue;
422- }
423-
424- let isUnknown = false;
425- let start = 0;
426- const subTokens = [];
427-
428- while (start < chars.length) {
429- let end = chars.length;
430- let currentSubstring = null;
431- while (start < end) {
432- let substr = chars.slice(start, end).join('');
433-
434- if (start > 0) {
435- substr = this.config.continuing_subword_prefix + substr;
436- }
437- if (this.tokens_to_ids.has(substr)) {
438- currentSubstring = substr;
439- break;
440- }
441-
442- --end;
443- }
444- if (currentSubstring === null) {
445- isUnknown = true;
446- break;
447- }
448- subTokens.push(currentSubstring);
449- start = end;
450- }
451- if (isUnknown) {
452- outputTokens.push(this.unk_token);
453- } else {
454- outputTokens.push(...subTokens);
455- }
456- }
457-
458- return outputTokens;
410+ this.vocab = new Array(this.tokens_to_ids.size);
411+ for (const [key, value] of this.tokens_to_ids) {
412+ this.vocab[value] = key;
459413 }
414+ }
460415
416+ /**
417+ * Encodes an array of tokens using WordPiece encoding.
418+ * @param {string[]} tokens The tokens to encode.
419+ * @returns {string[]} An array of encoded tokens.
420+ */
421+ encode(tokens) {
422+ const outputTokens = [];
423+ for (const token of tokens) {
424+ const chars = [...token];
425+ if (chars.length > this.max_input_chars_per_word) {
426+ outputTokens.push(this.unk_token);
427+ continue;
428+ }
429+
430+ let isUnknown = false;
431+ let start = 0;
432+ const subTokens = [];
433+
434+ while (start < chars.length) {
435+ let end = chars.length;
436+ let currentSubstring = null;
437+ while (start < end) {
438+ let substr = chars.slice(start, end).join("");
439+
440+ if (start > 0) {
441+ substr = this.config.continuing_subword_prefix + substr;
442+ }
443+ if (this.tokens_to_ids.has(substr)) {
444+ currentSubstring = substr;
445+ break;
446+ }
447+
448+ --end;
449+ }
450+ if (currentSubstring === null) {
451+ isUnknown = true;
452+ break;
453+ }
454+ subTokens.push(currentSubstring);
455+ start = end;
456+ }
457+ if (isUnknown) {
458+ outputTokens.push(this.unk_token);
459+ } else {
460+ outputTokens.push(...subTokens);
461+ }
462+ }
463+
464+ return outputTokens;
465+ }
461466 }
462467
463468 /**
@@ -465,106 +470,111 @@
465470 * @extends TokenizerModel
466471 */
467472 class Unigram extends TokenizerModel {
468- /**
469- * Create a new Unigram tokenizer model.
470- * @param {Object} config The configuration object for the Unigram model.
471- * @param {number} config.unk_id The ID of the unknown token
472- * @param {any[][]} config.vocab A 2D array representing a mapping of tokens to scores.
473- * @param {Object} moreConfig Additional configuration object for the Unigram model.
474- */
475- constructor(config, moreConfig) {
476- super(config);
477-
478- const vocabSize = config.vocab.length;
479- this.vocab = new Array(vocabSize);
480- this.scores = new Array(vocabSize);
481- for (let i = 0; i < vocabSize; ++i) {
482- const piece = config.vocab[i];
483- this.vocab[i] = piece[0];
484- this.scores[i] = piece[1];
485- }
486-
487- this.unk_token_id = config.unk_id;
488- this.unk_token = this.vocab[config.unk_id];
473+ /**
474+ * Create a new Unigram tokenizer model.
475+ * @param {Object} config The configuration object for the Unigram model.
476+ * @param {number} config.unk_id The ID of the unknown token
477+ * @param {any[][]} config.vocab A 2D array representing a mapping of tokens to scores.
478+ * @param {Object} moreConfig Additional configuration object for the Unigram model.
479+ */
480+ constructor(config, moreConfig) {
481+ super(config);
489482
490- this.tokens_to_ids = new Map(this.vocab.map((x, i) => [x, i]));
491- this.bosToken = ' '; // beginning of a sentence token
483+ const vocabSize = config.vocab.length;
484+ this.vocab = new Array(vocabSize);
485+ this.scores = new Array(vocabSize);
486+ for (let i = 0; i < vocabSize; ++i) {
487+ const piece = config.vocab[i];
488+ this.vocab[i] = piece[0];
489+ this.scores[i] = piece[1];
490+ }
492491
493- this.bosTokenId = this.tokens_to_ids.get(this.bosToken); // NOTE: may be undefined
494- this.eosToken = moreConfig.eos_token;
492+ this.unk_token_id = config.unk_id;
493+ this.unk_token = this.vocab[config.unk_id];
495494
496- this.eosTokenId = this.tokens_to_ids.get(this.eosToken);
497- this.unkToken = this.vocab[this.unk_token_id];
495+ this.tokens_to_ids = new Map(this.vocab.map((x, i) => [x, i]));
496+ this.bosToken = " "; // beginning of a sentence token
498497
499- this.minScore = min(this.scores)[0];
498+ this.bosTokenId = this.tokens_to_ids.get(this.bosToken); // NOTE: may be undefined
499+ this.eosToken = moreConfig.eos_token;
500500
501- this.unkScore = this.minScore - 10.0;
502- this.scores[this.unk_token_id] = this.unkScore;
501+ this.eosTokenId = this.tokens_to_ids.get(this.eosToken);
502+ this.unkToken = this.vocab[this.unk_token_id];
503503
504- this.trie = new CharTrie();
505- this.trie.extend(this.vocab);
504+ this.minScore = min(this.scores)[0];
506505
507- // NOTE: `fuse_unk` is hardcoded to true for Unigram models
508- // See: https://github.com/huggingface/tokenizers/blob/b58227c7f1ccf8b73ee2268354336da56d91e492/tokenizers/src/models/unigram/model.rs#L119
509- this.fuse_unk = true;
510- }
506+ this.unkScore = this.minScore - 10.0;
507+ this.scores[this.unk_token_id] = this.unkScore;
511508
512- /**
513- * Populates lattice nodes.
514- * @param {TokenLattice} lattice The token lattice to populate with nodes.
515- */
516- populateNodes(lattice) {
517- const sentence = lattice.sentence;
518- const len = sentence.length;
519- let beginPos = 0;
520- while (beginPos < len) {
521- const mblen = 1;
522- let hasSingleNode = false;
523- const tokens = [];
524-
525- for (let token of this.trie.commonPrefixSearch(sentence.slice(beginPos))) {
526- tokens.push(token);
527- const tokenId = this.tokens_to_ids.get(token);
528- const tokenScore = this.scores[tokenId];
529- const n = token.length;
530- lattice.insert(beginPos, n, tokenScore, tokenId);
531- if (!hasSingleNode && n === mblen) {
532- hasSingleNode = true;
533- }
534- }
535- if (!hasSingleNode) {
536- lattice.insert(beginPos, mblen, this.unkScore, this.unk_token_id);
537- }
538- beginPos += mblen;
539- }
540- }
509+ this.trie = new CharTrie();
510+ this.trie.extend(this.vocab);
541511
542- /**
543- * Encodes an array of tokens into an array of subtokens using the unigram model.
544- *
545- * @param {string} normalized The normalized string.
546- * @returns {string[]} An array of subtokens obtained by encoding the input tokens using the unigram model.
547- */
548- tokenize(normalized) {
549- const lattice = new TokenLattice(normalized, this.bosTokenId, this.eosTokenId);
550- this.populateNodes(lattice);
551- return lattice.tokens();
552- }
512+ // NOTE: `fuse_unk` is hardcoded to true for Unigram models
513+ // See: https://github.com/huggingface/tokenizers/blob/b58227c7f1ccf8b73ee2268354336da56d91e492/tokenizers/src/models/unigram/model.rs#L119
514+ this.fuse_unk = true;
515+ }
553516
554- /**
555- * Encodes an array of tokens using Unigram encoding.
556- * @param {string[]} tokens The tokens to encode.
557- * @returns {string[]} An array of encoded tokens.
558- */
559- encode(tokens) {
560- const toReturn = [];
561- for (const token of tokens) {
562- const tokenized = this.tokenize(token);
563- toReturn.push(...tokenized);
564- }
565- return toReturn;
517+ /**
518+ * Populates lattice nodes.
519+ * @param {TokenLattice} lattice The token lattice to populate with nodes.
520+ */
521+ populateNodes(lattice) {
522+ const sentence = lattice.sentence;
523+ const len = sentence.length;
524+ let beginPos = 0;
525+ while (beginPos < len) {
526+ const mblen = 1;
527+ let hasSingleNode = false;
528+ const tokens = [];
529+
530+ for (let token of this.trie.commonPrefixSearch(
531+ sentence.slice(beginPos),
532+ )) {
533+ tokens.push(token);
534+ const tokenId = this.tokens_to_ids.get(token);
535+ const tokenScore = this.scores[tokenId];
536+ const n = token.length;
537+ lattice.insert(beginPos, n, tokenScore, tokenId);
538+ if (!hasSingleNode && n === mblen) {
539+ hasSingleNode = true;
540+ }
541+ }
542+ if (!hasSingleNode) {
543+ lattice.insert(beginPos, mblen, this.unkScore, this.unk_token_id);
544+ }
545+ beginPos += mblen;
546+ }
547+ }
548+
549+ /**
550+ * Encodes an array of tokens into an array of subtokens using the unigram model.
551+ *
552+ * @param {string} normalized The normalized string.
553+ * @returns {string[]} An array of subtokens obtained by encoding the input tokens using the unigram model.
554+ */
555+ tokenize(normalized) {
556+ const lattice = new TokenLattice(
557+ normalized,
558+ this.bosTokenId,
559+ this.eosTokenId,
560+ );
561+ this.populateNodes(lattice);
562+ return lattice.tokens();
563+ }
564+
565+ /**
566+ * Encodes an array of tokens using Unigram encoding.
567+ * @param {string[]} tokens The tokens to encode.
568+ * @returns {string[]} An array of encoded tokens.
569+ */
570+ encode(tokens) {
571+ const toReturn = [];
572+ for (const token of tokens) {
573+ const tokenized = this.tokenize(token);
574+ toReturn.push(...tokenized);
566575 }
567-
576+ return toReturn;
577+ }
568578 }
569579
570580 /**
@@ -573,31 +583,39 @@
573583 * @returns {Object} Object with utf-8 byte keys and unicode string values.
574584 */
575585 const BYTES_TO_UNICODE = (() => {
576- // Returns list of utf-8 byte and a mapping to unicode strings.
577- // We specifically avoids mapping to whitespace/control characters
578- // the bpe code barfs on.
579-
580- const bs = [
581- ...Array.from({ length: "~".charCodeAt(0) - "!".charCodeAt(0) + 1 }, (_, i) => i + "!".charCodeAt(0)),
582- ...Array.from({ length: "¬".charCodeAt(0) - "¡".charCodeAt(0) + 1 }, (_, i) => i + "¡".charCodeAt(0)),
583- ...Array.from({ length: "ÿ".charCodeAt(0) - "®".charCodeAt(0) + 1 }, (_, i) => i + "®".charCodeAt(0)),
584- ];
585- const cs = bs.slice();
586- let n = 0;
587- for (let b = 0; b < 256; ++b) {
588- if (!bs.includes(b)) {
589- bs.push(b);
590- cs.push(256 + n);
591- n += 1;
592- }
593- }
594- const ccs = cs.map(n => String.fromCharCode(n));
595- return Object.fromEntries(bs.map((b, i) => [b, ccs[i]]));
586+ // Returns list of utf-8 byte and a mapping to unicode strings.
587+ // We specifically avoids mapping to whitespace/control characters
588+ // the bpe code barfs on.
589+
590+ const bs = [
591+ ...Array.from(
592+ { length: "~".charCodeAt(0) - "!".charCodeAt(0) + 1 },
593+ (_, i) => i + "!".charCodeAt(0),
594+ ),
595+ ...Array.from(
596+ { length: "¬".charCodeAt(0) - "¡".charCodeAt(0) + 1 },
597+ (_, i) => i + "¡".charCodeAt(0),
598+ ),
599+ ...Array.from(
600+ { length: "ÿ".charCodeAt(0) - "®".charCodeAt(0) + 1 },
601+ (_, i) => i + "®".charCodeAt(0),
602+ ),
603+ ];
604+ const cs = bs.slice();
605+ let n = 0;
606+ for (let b = 0; b < 256; ++b) {
607+ if (!bs.includes(b)) {
608+ bs.push(b);
609+ cs.push(256 + n);
610+ n += 1;
611+ }
612+ }
613+ const ccs = cs.map((n) => String.fromCharCode(n));
614+ return Object.fromEntries(bs.map((b, i) => [b, ccs[i]]));
596615 })();
597616
598617 const UNICODE_TO_BYTES = reverseDictionary(BYTES_TO_UNICODE);
599618
600-
601619 /**
602620 * @typedef {Object} BPENode
603621 * @property {string} token The token associated with the node
@@ -612,343 +630,345 @@
612630 * @extends TokenizerModel
613631 */
614632 class BPE extends TokenizerModel {
615- /**
616- * Create a BPE instance.
617- * @param {Object} config The configuration object for BPE.
618- * @param {Object} config.vocab A mapping of tokens to ids.
619- * @param {string} config.unk_token The unknown token used for out of vocabulary words.
620- * @param {string} config.end_of_word_suffix The suffix to place at the end of each word.
621- * @param {string} [config.continuing_subword_suffix] The suffix to insert between words.
622- * @param {Array} config.merges An array of BPE merges as strings.
623- */
624- constructor(config) {
625- super(config);
626-
627- this.BPE_SPLIT_TOKEN = ' ';
628-
629- /** @type {Map<string, number>} */
630- this.tokens_to_ids = objectToMap(config.vocab);
631-
632- this.unk_token_id = this.tokens_to_ids.get(config.unk_token);
633- this.unk_token = config.unk_token;
634-
635- this.vocab = new Array(this.tokens_to_ids.size);
636- for (const [key, value] of this.tokens_to_ids) {
637- this.vocab[value] = key;
638- }
639-
640- this.bpe_ranks = new Map(config.merges.map((x, i) => [x, i]));
641- this.merges = config.merges.map(x => x.split(this.BPE_SPLIT_TOKEN));
642-
643- this.end_of_word_suffix = config.end_of_word_suffix;
633+ /**
634+ * Create a BPE instance.
635+ * @param {Object} config The configuration object for BPE.
636+ * @param {Object} config.vocab A mapping of tokens to ids.
637+ * @param {string} config.unk_token The unknown token used for out of vocabulary words.
638+ * @param {string} config.end_of_word_suffix The suffix to place at the end of each word.
639+ * @param {string} [config.continuing_subword_suffix] The suffix to insert between words.
640+ * @param {Array} config.merges An array of BPE merges as strings.
641+ */
642+ constructor(config) {
643+ super(config);
644644
645- // NOTE: `continuing_subword_suffix` is custom (to support `BlenderbotSmallTokenizer`)
646- this.continuing_subword_suffix = config.continuing_subword_suffix ?? null;
645+ this.BPE_SPLIT_TOKEN = " ";
647646
648- this.byte_fallback = this.config.byte_fallback ?? false;
647+ /** @type {Map<string, number>} */
648+ this.tokens_to_ids = objectToMap(config.vocab);
649649
650- if (this.byte_fallback) {
651- this.text_encoder = new TextEncoder();
652- }
650+ this.unk_token_id = this.tokens_to_ids.get(config.unk_token);
651+ this.unk_token = config.unk_token;
653652
654- /** @type {Map<string, string[]>} */
655- this.cache = new Map();
653+ this.vocab = new Array(this.tokens_to_ids.size);
654+ for (const [key, value] of this.tokens_to_ids) {
655+ this.vocab[value] = key;
656656 }
657657
658- /**
659- * Apply Byte-Pair-Encoding (BPE) to a given token. Efficient heap-based priority
660- * queue implementation adapted from https://github.com/belladoreai/llama-tokenizer-js.
661- * @param {string} token The token to encode.
662- * @returns {string[]} The BPE encoded tokens.
663- */
664- bpe(token) {
665- if (token.length === 0) {
666- return [];
667- }
658+ this.bpe_ranks = new Map(config.merges.map((x, i) => [x, i]));
659+ this.merges = config.merges.map((x) => x.split(this.BPE_SPLIT_TOKEN));
668660
669- const cached = this.cache.get(token);
670- if (cached !== undefined) {
671- return cached;
672- }
661+ this.end_of_word_suffix = config.end_of_word_suffix;
673662
674- const word = Array.from(token);
675- if (this.end_of_word_suffix) {
676- word[word.length - 1] += this.end_of_word_suffix;
677- }
663+ // NOTE: `continuing_subword_suffix` is custom (to support `BlenderbotSmallTokenizer`)
664+ this.continuing_subword_suffix = config.continuing_subword_suffix ?? null;
678665
679- let result = [];
680- if (word.length > 1) {
681- // Create a priority queue to store the nodes that will be merged.
682- // The comparator function compares the scores of the nodes.
683- const queue = new PriorityQueue((a, b) => a.score < b.score);
684-
685- // Construct a doubly-linked list of nodes that will be inserted into the priority queue,
686- // starting with the individual characters. We also populate each node with a positional
687- // bias to break ties in the priority queue.
688- let startingNode = {
689- token: word[0],
690- bias: 0,
691- prev: null,
692- next: null,
693- }
666+ this.byte_fallback = this.config.byte_fallback ?? false;
694667
695- let previousNode = startingNode
696- for (let i = 1; i < word.length; ++i) {
697- const currentNode = {
698- bias: i / word.length, // Add fractional component to break ties
699- token: word[i],
700- prev: previousNode,
701- next: null,
702- }
703- previousNode.next = currentNode
704- this._add_node(queue, previousNode)
705- previousNode = currentNode
706- }
668+ if (this.byte_fallback) {
669+ this.text_encoder = new TextEncoder();
670+ }
707671
708- while (!queue.isEmpty()) {
709- // Get the next node with the highest priority
710- const node = queue.pop();
711-
712- // Check that this merge is still possible
713- if (node.deleted || !node.next || node.next.deleted) continue;
714-
715- // Here, we mark the current node (left side of the merge) and the next node (right side of the merge) as deleted.
716- // This is because they will both be replaced by a new node representing the merge result.
717- node.deleted = true;
718- node.next.deleted = true;
719-
720- // Next, we fix the node that comes before the current node (i.e., left side of the merge).
721- if (node.prev) {
722-
723- // Make a shallow copy of the previous node
724- const newPreviousNode = { ...node.prev };
725-
726- // Mark the old previous node as deleted. This avoids erroneous merges later,
727- // because there may still be references to this node in the priority queue.
728- node.prev.deleted = true;
729- node.prev = newPreviousNode;
730-
731- // Update the reference of the previous node, by pointing its previous node to this new previous node.
732- if (newPreviousNode.prev) {
733- newPreviousNode.prev.next = newPreviousNode;
734- } else {
735- // If the previous of the previous node does not exist, it means that
736- // `newPreviousNode` must be the new `startingNode`.
737- startingNode = newPreviousNode;
738- }
739- }
740-
741- // Create a new node which represents the result of the merge.
742- const merged = {
743- token: node.token + node.next.token,
744- bias: node.bias,
745- prev: node.prev,
746- next: node.next.next,
747- }
748-
749- // We now consider where we can add the new merged node to the priority queue:
750- // 1. prev <-> merged
751- if (merged.prev) {
752- merged.prev.next = merged;
753- this._add_node(queue, merged.prev);
754- } else {
755- // If `merged.prev` does not exist, then `merged` must be the new `startingNode`.
756- startingNode = merged;
757- }
758-
759- // 2. merged <-> next
760- if (merged.next) {
761- merged.next.prev = merged;
762- this._add_node(queue, merged);
763- }
764- }
672+ /** @type {Map<string, string[]>} */
673+ this.cache = new Map();
674+ }
765675
766- // Traverse the linked list, starting from the `startingNode`, and collect the tokens.
767- for (let currentNode = startingNode; currentNode !== null; currentNode = currentNode.next) {
768- result.push(currentNode.token);
769- }
676+ /**
677+ * Apply Byte-Pair-Encoding (BPE) to a given token. Efficient heap-based priority
678+ * queue implementation adapted from https://github.com/belladoreai/llama-tokenizer-js.
679+ * @param {string} token The token to encode.
680+ * @returns {string[]} The BPE encoded tokens.
681+ */
682+ bpe(token) {
683+ if (token.length === 0) {
684+ return [];
685+ }
686+
687+ const cached = this.cache.get(token);
688+ if (cached !== undefined) {
689+ return cached;
690+ }
691+
692+ const word = Array.from(token);
693+ if (this.end_of_word_suffix) {
694+ word[word.length - 1] += this.end_of_word_suffix;
695+ }
696+
697+ let result = [];
698+ if (word.length > 1) {
699+ // Create a priority queue to store the nodes that will be merged.
700+ // The comparator function compares the scores of the nodes.
701+ const queue = new PriorityQueue((a, b) => a.score < b.score);
702+
703+ // Construct a doubly-linked list of nodes that will be inserted into the priority queue,
704+ // starting with the individual characters. We also populate each node with a positional
705+ // bias to break ties in the priority queue.
706+ let startingNode = {
707+ token: word[0],
708+ bias: 0,
709+ prev: null,
710+ next: null,
711+ };
712+
713+ let previousNode = startingNode;
714+ for (let i = 1; i < word.length; ++i) {
715+ const currentNode = {
716+ bias: i / word.length, // Add fractional component to break ties
717+ token: word[i],
718+ prev: previousNode,
719+ next: null,
720+ };
721+ previousNode.next = currentNode;
722+ this._add_node(queue, previousNode);
723+ previousNode = currentNode;
724+ }
725+
726+ while (!queue.isEmpty()) {
727+ // Get the next node with the highest priority
728+ const node = queue.pop();
729+
730+ // Check that this merge is still possible
731+ if (node.deleted || !node.next || node.next.deleted) continue;
732+
733+ // Here, we mark the current node (left side of the merge) and the next node (right side of the merge) as deleted.
734+ // This is because they will both be replaced by a new node representing the merge result.
735+ node.deleted = true;
736+ node.next.deleted = true;
737+
738+ // Next, we fix the node that comes before the current node (i.e., left side of the merge).
739+ if (node.prev) {
740+ // Make a shallow copy of the previous node
741+ const newPreviousNode = { ...node.prev };
742+
743+ // Mark the old previous node as deleted. This avoids erroneous merges later,
744+ // because there may still be references to this node in the priority queue.
745+ node.prev.deleted = true;
746+ node.prev = newPreviousNode;
747+
748+ // Update the reference of the previous node, by pointing its previous node to this new previous node.
749+ if (newPreviousNode.prev) {
750+ newPreviousNode.prev.next = newPreviousNode;
751+ } else {
752+ // If the previous of the previous node does not exist, it means that
753+ // `newPreviousNode` must be the new `startingNode`.
754+ startingNode = newPreviousNode;
755+ }
756+ }
757+
758+ // Create a new node which represents the result of the merge.
759+ const merged = {
760+ token: node.token + node.next.token,
761+ bias: node.bias,
762+ prev: node.prev,
763+ next: node.next.next,
764+ };
765+
766+ // We now consider where we can add the new merged node to the priority queue:
767+ // 1. prev <-> merged
768+ if (merged.prev) {
769+ merged.prev.next = merged;
770+ this._add_node(queue, merged.prev);
770771 } else {
771- result = word;
772- }
773-
774- // Possibly append suffix
775- if (this.continuing_subword_suffix) {
776- // Do not append suffix to the last token
777- for (let i = 0; i < result.length - 1; ++i) {
778- result[i] += this.continuing_subword_suffix;
779- }
780- }
781-
782- // Save the result to the cache
783- this.cache.set(token, result);
784-
785- return result;
772+ // If `merged.prev` does not exist, then `merged` must be the new `startingNode`.
773+ startingNode = merged;
774+ }
775+
776+ // 2. merged <-> next
777+ if (merged.next) {
778+ merged.next.prev = merged;
779+ this._add_node(queue, merged);
780+ }
781+ }
782+
783+ // Traverse the linked list, starting from the `startingNode`, and collect the tokens.
784+ for (
785+ let currentNode = startingNode;
786+ currentNode !== null;
787+ currentNode = currentNode.next
788+ ) {
789+ result.push(currentNode.token);
790+ }
791+ } else {
792+ result = word;
786793 }
787794
788-
789- /**
790- * Helper function to add a node to the priority queue.
791- * @param {PriorityQueue} queue
792- * @param {BPENode} node
793- * @private
794- */
795- _add_node(queue, node) {
796- // `score` is a measure of the merge priority: lower means higher priority
797- // We use the BPE rank as a measure of priority (i.e., the local of the merge in the merges list)
798- // We also add a fractional component to the score to break ties (with the earlier character having higher priority)
799- const rank = this.bpe_ranks.get(node.token + this.BPE_SPLIT_TOKEN + node.next.token);
800- if (rank !== undefined) {
801- node.score = rank + node.bias;
802- queue.push(node);
803- }
795+ // Possibly append suffix
796+ if (this.continuing_subword_suffix) {
797+ // Do not append suffix to the last token
798+ for (let i = 0; i < result.length - 1; ++i) {
799+ result[i] += this.continuing_subword_suffix;
800+ }
804801 }
805802
806- /**
807- * Encodes the input sequence of tokens using the BPE algorithm and returns the resulting subword tokens.
808- * @param {string[]} tokens The input sequence of tokens to encode.
809- * @returns {string[]} The resulting subword tokens after applying the BPE algorithm to the input sequence of tokens.
810- */
811- encode(tokens) {
812- const outputTokens = [];
813-
814- for (const token of tokens) {
815- const bpe_token_list = this.bpe(token);
816-
817- for (const t of bpe_token_list) {
818- if (this.tokens_to_ids.has(t)) {
819- outputTokens.push(t);
820- } else {
821- if (this.byte_fallback) {
822- outputTokens.push(
823- ...Array.from(this.text_encoder.encode(t))
824- .map(x => `<0x${x.toString(16).toUpperCase().padStart(2, '0')}>`)
825- );
826- } else {
827- outputTokens.push(this.unk_token);
828- }
829- }
830- }
831- }
803+ // Save the result to the cache
804+ this.cache.set(token, result);
832805
833- return outputTokens;
806+ return result;
807+ }
808+
809+ /**
810+ * Helper function to add a node to the priority queue.
811+ * @param {PriorityQueue} queue
812+ * @param {BPENode} node
813+ * @private
814+ */
815+ _add_node(queue, node) {
816+ // `score` is a measure of the merge priority: lower means higher priority
817+ // We use the BPE rank as a measure of priority (i.e., the local of the merge in the merges list)
818+ // We also add a fractional component to the score to break ties (with the earlier character having higher priority)
819+ const rank = this.bpe_ranks.get(
820+ node.token + this.BPE_SPLIT_TOKEN + node.next.token,
821+ );
822+ if (rank !== undefined) {
823+ node.score = rank + node.bias;
824+ queue.push(node);
825+ }
826+ }
827+
828+ /**
829+ * Encodes the input sequence of tokens using the BPE algorithm and returns the resulting subword tokens.
830+ * @param {string[]} tokens The input sequence of tokens to encode.
831+ * @returns {string[]} The resulting subword tokens after applying the BPE algorithm to the input sequence of tokens.
832+ */
833+ encode(tokens) {
834+ const outputTokens = [];
835+
836+ for (const token of tokens) {
837+ const bpe_token_list = this.bpe(token);
838+
839+ for (const t of bpe_token_list) {
840+ if (this.tokens_to_ids.has(t)) {
841+ outputTokens.push(t);
842+ } else {
843+ if (this.byte_fallback) {
844+ outputTokens.push(
845+ ...Array.from(this.text_encoder.encode(t)).map(
846+ (x) => `<0x${x.toString(16).toUpperCase().padStart(2, "0")}>`,
847+ ),
848+ );
849+ } else {
850+ outputTokens.push(this.unk_token);
851+ }
852+ }
853+ }
834854 }
835855
856+ return outputTokens;
857+ }
836858 }
837859
838860 /**
839861 * Legacy tokenizer class for tokenizers with only a vocabulary.
840862 */
841863 class LegacyTokenizerModel extends TokenizerModel {
842- /**
843- * Create a LegacyTokenizerModel instance.
844- * @param {Object} config The configuration object for LegacyTokenizerModel.
845- * @param {Object} config.vocab A (possibly nested) mapping of tokens to ids.
846- * @param {Object} moreConfig Additional configuration object for the LegacyTokenizerModel model.
847- */
848- constructor(config, moreConfig) {
849- super(config);
850-
851- /**@type {Map<string, number>} */
852- this.tokens_to_ids = objectToMap(
853- moreConfig.target_lang
854- ? config.vocab[moreConfig.target_lang]
855- : config.vocab
856- );
864+ /**
865+ * Create a LegacyTokenizerModel instance.
866+ * @param {Object} config The configuration object for LegacyTokenizerModel.
867+ * @param {Object} config.vocab A (possibly nested) mapping of tokens to ids.
868+ * @param {Object} moreConfig Additional configuration object for the LegacyTokenizerModel model.
869+ */
870+ constructor(config, moreConfig) {
871+ super(config);
857872
858- this.bos_token = moreConfig.bos_token;
859- this.bos_token_id = this.tokens_to_ids.get(this.bos_token);
873+ /**@type {Map<string, number>} */
874+ this.tokens_to_ids = objectToMap(
875+ moreConfig.target_lang
876+ ? config.vocab[moreConfig.target_lang]
877+ : config.vocab,
878+ );
860879
861- this.eos_token = moreConfig.eos_token;
862- this.eos_token_id = this.tokens_to_ids.get(this.eos_token);
880+ this.bos_token = moreConfig.bos_token;
881+ this.bos_token_id = this.tokens_to_ids.get(this.bos_token);
863882
864- this.pad_token = moreConfig.pad_token;
865- this.pad_token_id = this.tokens_to_ids.get(this.pad_token);
883+ this.eos_token = moreConfig.eos_token;
884+ this.eos_token_id = this.tokens_to_ids.get(this.eos_token);
866885
867- this.unk_token = moreConfig.unk_token;
868- this.unk_token_id = this.tokens_to_ids.get(this.unk_token);
886+ this.pad_token = moreConfig.pad_token;
887+ this.pad_token_id = this.tokens_to_ids.get(this.pad_token);
869888
870- this.vocab = new Array(this.tokens_to_ids.size);
871- for (const [key, value] of this.tokens_to_ids) {
872- this.vocab[value] = key;
873- }
874- }
889+ this.unk_token = moreConfig.unk_token;
890+ this.unk_token_id = this.tokens_to_ids.get(this.unk_token);
875891
876- encode(tokens) {
877- return tokens;
892+ this.vocab = new Array(this.tokens_to_ids.size);
893+ for (const [key, value] of this.tokens_to_ids) {
894+ this.vocab[value] = key;
878895 }
879-}
896+ }
880897
898+ encode(tokens) {
899+ return tokens;
900+ }
901+}
881902
882903 /**
883904 * A base class for text normalization.
884905 * @abstract
885906 */
886907 class Normalizer extends Callable {
887- /**
888- * @param {Object} config The configuration object for the normalizer.
889- */
890- constructor(config) {
891- super();
892- this.config = config;
893- }
894-
895- /**
896- * Factory method for creating normalizers from config objects.
897- * @static
898- * @param {Object} config The configuration object for the normalizer.
899- * @returns {Normalizer} A Normalizer object.
900- * @throws {Error} If an unknown Normalizer type is specified in the config.
901- */
902- static fromConfig(config) {
903- if (config === null) return null;
904- switch (config.type) {
905- case 'BertNormalizer':
906- return new BertNormalizer(config);
907- case 'Precompiled':
908- return new Precompiled(config);
909- case 'Sequence':
910- return new NormalizerSequence(config);
911- case 'Replace':
912- return new Replace(config);
913- case 'NFC':
914- return new NFC(config);
915- case 'NFKC':
916- return new NFKC(config);
917- case 'NFKD':
918- return new NFKD(config);
919- case 'Strip':
920- return new StripNormalizer(config);
921- case 'StripAccents':
922- return new StripAccents(config);
923- case 'Lowercase':
924- return new Lowercase(config);
925- case 'Prepend':
926- return new Prepend(config);
927- default:
928- throw new Error(`Unknown Normalizer type: ${config.type}`);
929- }
930- }
931-
932- /**
933- * Normalize the input text.
934- * @abstract
935- * @param {string} text The text to normalize.
936- * @returns {string} The normalized text.
937- * @throws {Error} If this method is not implemented in a subclass.
938- */
939- normalize(text) {
940- throw Error("normalize should be implemented in subclass.")
941- }
942-
943- /**
944- * Alias for {@link Normalizer#normalize}.
945- * @param {string} text The text to normalize.
946- * @returns {string} The normalized text.
947- */
948- _call(text) {
949- return this.normalize(text);
950- }
951-
908+ /**
909+ * @param {Object} config The configuration object for the normalizer.
910+ */
911+ constructor(config) {
912+ super();
913+ this.config = config;
914+ }
915+
916+ /**
917+ * Factory method for creating normalizers from config objects.
918+ * @static
919+ * @param {Object} config The configuration object for the normalizer.
920+ * @returns {Normalizer} A Normalizer object.
921+ * @throws {Error} If an unknown Normalizer type is specified in the config.
922+ */
923+ static fromConfig(config) {
924+ if (config === null) return null;
925+ switch (config.type) {
926+ case "BertNormalizer":
927+ return new BertNormalizer(config);
928+ case "Precompiled":
929+ return new Precompiled(config);
930+ case "Sequence":
931+ return new NormalizerSequence(config);
932+ case "Replace":
933+ return new Replace(config);
934+ case "NFC":
935+ return new NFC(config);
936+ case "NFKC":
937+ return new NFKC(config);
938+ case "NFKD":
939+ return new NFKD(config);
940+ case "Strip":
941+ return new StripNormalizer(config);
942+ case "StripAccents":
943+ return new StripAccents(config);
944+ case "Lowercase":
945+ return new Lowercase(config);
946+ case "Prepend":
947+ return new Prepend(config);
948+ default:
949+ throw new Error(`Unknown Normalizer type: ${config.type}`);
950+ }
951+ }
952+
953+ /**
954+ * Normalize the input text.
955+ * @abstract
956+ * @param {string} text The text to normalize.
957+ * @returns {string} The normalized text.
958+ * @throws {Error} If this method is not implemented in a subclass.
959+ */
960+ normalize(text) {
961+ throw Error("normalize should be implemented in subclass.");
962+ }
963+
964+ /**
965+ * Alias for {@link Normalizer#normalize}.
966+ * @param {string} text The text to normalize.
967+ * @returns {string} The normalized text.
968+ */
969+ _call(text) {
970+ return this.normalize(text);
971+ }
952972 }
953973
954974 /**
@@ -956,17 +976,17 @@
956976 * @extends Normalizer
957977 */
958978 class Replace extends Normalizer {
959- /**
960- * Normalize the input text by replacing the pattern with the content.
961- * @param {string} text The input text to be normalized.
962- * @returns {string} The normalized text after replacing the pattern with the content.
963- */
964- normalize(text) {
965- const pattern = createPattern(this.config.pattern);
966- return pattern === null
967- ? text
968- : text.replaceAll(pattern, this.config.content);
969- }
979+ /**
980+ * Normalize the input text by replacing the pattern with the content.
981+ * @param {string} text The input text to be normalized.
982+ * @returns {string} The normalized text after replacing the pattern with the content.
983+ */
984+ normalize(text) {
985+ const pattern = createPattern(this.config.pattern);
986+ return pattern === null
987+ ? text
988+ : text.replaceAll(pattern, this.config.content);
989+ }
970990 }
971991
972992 /**
@@ -974,15 +994,15 @@
974994 * @extends Normalizer
975995 */
976996 class NFC extends Normalizer {
977- /**
978- * Normalize the input text by applying Unicode normalization form C (NFC).
979- * @param {string} text The input text to be normalized.
980- * @returns {string} The normalized text.
981- */
982- normalize(text) {
983- text = text.normalize('NFC')
984- return text;
985- }
997+ /**
998+ * Normalize the input text by applying Unicode normalization form C (NFC).
999+ * @param {string} text The input text to be normalized.
1000+ * @returns {string} The normalized text.
1001+ */
1002+ normalize(text) {
1003+ text = text.normalize("NFC");
1004+ return text;
1005+ }
9861006 }
9871007
9881008 /**
@@ -990,55 +1010,55 @@
9901010 * @extends Normalizer
9911011 */
9921012 class NFKC extends Normalizer {
993- /**
994- * Normalize text using NFKC normalization.
995- * @param {string} text The text to be normalized.
996- * @returns {string} The normalized text.
997- */
998- normalize(text) {
999- text = text.normalize('NFKC')
1000- return text;
1001- }
1013+ /**
1014+ * Normalize text using NFKC normalization.
1015+ * @param {string} text The text to be normalized.
1016+ * @returns {string} The normalized text.
1017+ */
1018+ normalize(text) {
1019+ text = text.normalize("NFKC");
1020+ return text;
1021+ }
10021022 }
10031023 /**
10041024 * NFKD Normalizer.
10051025 * @extends Normalizer
10061026 */
10071027 class NFKD extends Normalizer {
1008- /**
1009- * Normalize text using NFKD normalization.
1010- * @param {string} text The text to be normalized.
1011- * @returns {string} The normalized text.
1012- */
1013- normalize(text) {
1014- text = text.normalize('NFKD')
1015- return text;
1016- }
1028+ /**
1029+ * Normalize text using NFKD normalization.
1030+ * @param {string} text The text to be normalized.
1031+ * @returns {string} The normalized text.
1032+ */
1033+ normalize(text) {
1034+ text = text.normalize("NFKD");
1035+ return text;
1036+ }
10171037 }
10181038
10191039 /**
10201040 * A normalizer that strips leading and/or trailing whitespace from the input text.
10211041 */
10221042 class StripNormalizer extends Normalizer {
1023- /**
1024- * Strip leading and/or trailing whitespace from the input text.
1025- * @param {string} text The input text.
1026- * @returns {string} The normalized text.
1027- */
1028- normalize(text) {
1029- if (this.config.strip_left && this.config.strip_right) {
1030- // Fast path to avoid an extra trim call
1031- text = text.trim();
1032- } else {
1033- if (this.config.strip_left) {
1034- text = text.trimStart();
1035- }
1036- if (this.config.strip_right) {
1037- text = text.trimEnd();
1038- }
1039- }
1040- return text;
1043+ /**
1044+ * Strip leading and/or trailing whitespace from the input text.
1045+ * @param {string} text The input text.
1046+ * @returns {string} The normalized text.
1047+ */
1048+ normalize(text) {
1049+ if (this.config.strip_left && this.config.strip_right) {
1050+ // Fast path to avoid an extra trim call
1051+ text = text.trim();
1052+ } else {
1053+ if (this.config.strip_left) {
1054+ text = text.trimStart();
1055+ }
1056+ if (this.config.strip_right) {
1057+ text = text.trimEnd();
1058+ }
10411059 }
1060+ return text;
1061+ }
10421062 }
10431063
10441064 /**
@@ -1046,15 +1066,15 @@
10461066 * @extends Normalizer
10471067 */
10481068 class StripAccents extends Normalizer {
1049- /**
1050- * Remove all accents from the text.
1051- * @param {string} text The input text.
1052- * @returns {string} The normalized text without accents.
1053- */
1054- normalize(text) {
1055- text = remove_accents(text);
1056- return text;
1057- }
1069+ /**
1070+ * Remove all accents from the text.
1071+ * @param {string} text The input text.
1072+ * @returns {string} The normalized text without accents.
1073+ */
1074+ normalize(text) {
1075+ text = remove_accents(text);
1076+ return text;
1077+ }
10581078 }
10591079
10601080 /**
@@ -1062,15 +1082,15 @@
10621082 * @extends Normalizer
10631083 */
10641084 class Lowercase extends Normalizer {
1065- /**
1066- * Lowercases the input string.
1067- * @param {string} text The text to normalize.
1068- * @returns {string} The normalized text.
1069- */
1070- normalize(text) {
1071- text = text.toLowerCase();
1072- return text;
1073- }
1085+ /**
1086+ * Lowercases the input string.
1087+ * @param {string} text The text to normalize.
1088+ * @returns {string} The normalized text.
1089+ */
1090+ normalize(text) {
1091+ text = text.toLowerCase();
1092+ return text;
1093+ }
10741094 }
10751095
10761096 /**
@@ -1078,15 +1098,15 @@
10781098 * @extends Normalizer
10791099 */
10801100 class Prepend extends Normalizer {
1081- /**
1082- * Prepends the input string.
1083- * @param {string} text The text to normalize.
1084- * @returns {string} The normalized text.
1085- */
1086- normalize(text) {
1087- text = this.config.prepend + text;
1088- return text;
1089- }
1101+ /**
1102+ * Prepends the input string.
1103+ * @param {string} text The text to normalize.
1104+ * @returns {string} The normalized text.
1105+ */
1106+ normalize(text) {
1107+ text = this.config.prepend + text;
1108+ return text;
1109+ }
10901110 }
10911111
10921112 /**
@@ -1094,25 +1114,25 @@
10941114 * @extends Normalizer
10951115 */
10961116 class NormalizerSequence extends Normalizer {
1097- /**
1117+ /**
10981118 * Create a new instance of NormalizerSequence.
10991119 * @param {Object} config The configuration object.
11001120 * @param {Object[]} config.normalizers An array of Normalizer configuration objects.
11011121 */
1102- constructor(config) {
1103- super(config);
1104- this.normalizers = config.normalizers.map(x => Normalizer.fromConfig(x));
1105- }
1106- /**
1107- * Apply a sequence of Normalizers to the input text.
1108- * @param {string} text The text to normalize.
1109- * @returns {string} The normalized text.
1110- */
1111- normalize(text) {
1112- return this.normalizers.reduce((t, normalizer) => {
1113- return normalizer.normalize(t);
1114- }, text);
1115- }
1122+ constructor(config) {
1123+ super(config);
1124+ this.normalizers = config.normalizers.map((x) => Normalizer.fromConfig(x));
1125+ }
1126+ /**
1127+ * Apply a sequence of Normalizers to the input text.
1128+ * @param {string} text The text to normalize.
1129+ * @returns {string} The normalized text.
1130+ */
1131+ normalize(text) {
1132+ return this.normalizers.reduce((t, normalizer) => {
1133+ return normalizer.normalize(t);
1134+ }, text);
1135+ }
11161136 }
11171137
11181138 /**
@@ -1120,136 +1140,136 @@
11201140 * @extends Normalizer
11211141 */
11221142 class BertNormalizer extends Normalizer {
1123- /**
1124- * Adds whitespace around any CJK (Chinese, Japanese, or Korean) character in the input text.
1125- *
1126- * @param {string} text The input text to tokenize.
1127- * @returns {string} The tokenized text with whitespace added around CJK characters.
1128- */
1129- _tokenize_chinese_chars(text) {
1130- /* Adds whitespace around any CJK character. */
1131- const output = [];
1132- for (let i = 0; i < text.length; ++i) {
1133- const char = text[i];
1134- const cp = char.charCodeAt(0);
1135- if (this._is_chinese_char(cp)) {
1136- output.push(" ");
1137- output.push(char);
1138- output.push(" ");
1139- } else {
1140- output.push(char);
1141- }
1142- }
1143- return output.join("");
1143+ /**
1144+ * Adds whitespace around any CJK (Chinese, Japanese, or Korean) character in the input text.
1145+ *
1146+ * @param {string} text The input text to tokenize.
1147+ * @returns {string} The tokenized text with whitespace added around CJK characters.
1148+ */
1149+ _tokenize_chinese_chars(text) {
1150+ /* Adds whitespace around any CJK character. */
1151+ const output = [];
1152+ for (let i = 0; i < text.length; ++i) {
1153+ const char = text[i];
1154+ const cp = char.charCodeAt(0);
1155+ if (this._is_chinese_char(cp)) {
1156+ output.push(" ");
1157+ output.push(char);
1158+ output.push(" ");
1159+ } else {
1160+ output.push(char);
1161+ }
1162+ }
1163+ return output.join("");
1164+ }
1165+
1166+ /**
1167+ * Checks whether the given Unicode codepoint represents a CJK (Chinese, Japanese, or Korean) character.
1168+ *
1169+ * A "chinese character" is defined as anything in the CJK Unicode block:
1170+ * https://en.wikipedia.org/wiki/CJK_Unified_Ideographs_(Unicode_block)
1171+ *
1172+ * Note that the CJK Unicode block is NOT all Japanese and Korean characters, despite its name.
1173+ * The modern Korean Hangul alphabet is a different block, as is Japanese Hiragana and Katakana.
1174+ * Those alphabets are used to write space-separated words, so they are not treated specially
1175+ * and are handled like all other languages.
1176+ *
1177+ * @param {number} cp The Unicode codepoint to check.
1178+ * @returns {boolean} True if the codepoint represents a CJK character, false otherwise.
1179+ */
1180+ _is_chinese_char(cp) {
1181+ return (
1182+ (cp >= 0x4e00 && cp <= 0x9fff) ||
1183+ (cp >= 0x3400 && cp <= 0x4dbf) ||
1184+ (cp >= 0x20000 && cp <= 0x2a6df) ||
1185+ (cp >= 0x2a700 && cp <= 0x2b73f) ||
1186+ (cp >= 0x2b740 && cp <= 0x2b81f) ||
1187+ (cp >= 0x2b820 && cp <= 0x2ceaf) ||
1188+ (cp >= 0xf900 && cp <= 0xfaff) ||
1189+ (cp >= 0x2f800 && cp <= 0x2fa1f)
1190+ );
1191+ }
1192+ /**
1193+ * Strips accents from the given text.
1194+ * @param {string} text The text to strip accents from.
1195+ * @returns {string} The text with accents removed.
1196+ */
1197+ stripAccents(text) {
1198+ return text.normalize("NFD").replace(/[\u0300-\u036f]/g, "");
1199+ }
1200+
1201+ /**
1202+ * Checks whether `char` is a control character.
1203+ * @param {string} char The character to check.
1204+ * @returns {boolean} Whether `char` is a control character.
1205+ * @private
1206+ */
1207+ _is_control(char) {
1208+ switch (char) {
1209+ case "\t":
1210+ case "\n":
1211+ case "\r":
1212+ // These are technically control characters but we count them as whitespace characters.
1213+ return false;
1214+
1215+ default:
1216+ // Check if unicode category starts with C:
1217+ // Cc - Control
1218+ // Cf - Format
1219+ // Co - Private Use
1220+ // Cs - Surrogate
1221+ return /^\p{Cc}|\p{Cf}|\p{Co}|\p{Cs}$/u.test(char);
1222+ }
1223+ }
1224+
1225+ /**
1226+ * Performs invalid character removal and whitespace cleanup on text.
1227+ * @param {string} text The text to clean.
1228+ * @returns {string} The cleaned text.
1229+ * @private
1230+ */
1231+ _clean_text(text) {
1232+ const output = [];
1233+ for (const char of text) {
1234+ const cp = char.charCodeAt(0);
1235+ if (cp === 0 || cp === 0xfffd || this._is_control(char)) {
1236+ continue;
1237+ }
1238+ if (/^\s$/.test(char)) {
1239+ // is whitespace
1240+ output.push(" ");
1241+ } else {
1242+ output.push(char);
1243+ }
1244+ }
1245+ return output.join("");
1246+ }
1247+ /**
1248+ * Normalizes the given text based on the configuration.
1249+ * @param {string} text The text to normalize.
1250+ * @returns {string} The normalized text.
1251+ */
1252+ normalize(text) {
1253+ if (this.config.clean_text) {
1254+ text = this._clean_text(text);
11441255 }
11451256
1146- /**
1147- * Checks whether the given Unicode codepoint represents a CJK (Chinese, Japanese, or Korean) character.
1148- *
1149- * A "chinese character" is defined as anything in the CJK Unicode block:
1150- * https://en.wikipedia.org/wiki/CJK_Unified_Ideographs_(Unicode_block)
1151- *
1152- * Note that the CJK Unicode block is NOT all Japanese and Korean characters, despite its name.
1153- * The modern Korean Hangul alphabet is a different block, as is Japanese Hiragana and Katakana.
1154- * Those alphabets are used to write space-separated words, so they are not treated specially
1155- * and are handled like all other languages.
1156- *
1157- * @param {number} cp The Unicode codepoint to check.
1158- * @returns {boolean} True if the codepoint represents a CJK character, false otherwise.
1159- */
1160- _is_chinese_char(cp) {
1161- return (
1162- (cp >= 0x4E00 && cp <= 0x9FFF)
1163- || (cp >= 0x3400 && cp <= 0x4DBF)
1164- || (cp >= 0x20000 && cp <= 0x2A6DF)
1165- || (cp >= 0x2A700 && cp <= 0x2B73F)
1166- || (cp >= 0x2B740 && cp <= 0x2B81F)
1167- || (cp >= 0x2B820 && cp <= 0x2CEAF)
1168- || (cp >= 0xF900 && cp <= 0xFAFF)
1169- || (cp >= 0x2F800 && cp <= 0x2FA1F)
1170- )
1171- }
1172- /**
1173- * Strips accents from the given text.
1174- * @param {string} text The text to strip accents from.
1175- * @returns {string} The text with accents removed.
1176- */
1177- stripAccents(text) {
1178- return text.normalize('NFD').replace(/[\u0300-\u036f]/g, '');
1257+ if (this.config.handle_chinese_chars) {
1258+ text = this._tokenize_chinese_chars(text);
11791259 }
11801260
1261+ if (this.config.lowercase) {
1262+ text = text.toLowerCase();
11811263
1182- /**
1183- * Checks whether `char` is a control character.
1184- * @param {string} char The character to check.
1185- * @returns {boolean} Whether `char` is a control character.
1186- * @private
1187- */
1188- _is_control(char) {
1189- switch (char) {
1190- case '\t':
1191- case '\n':
1192- case '\r':
1193- // These are technically control characters but we count them as whitespace characters.
1194- return false;
1195-
1196- default:
1197- // Check if unicode category starts with C:
1198- // Cc - Control
1199- // Cf - Format
1200- // Co - Private Use
1201- // Cs - Surrogate
1202- return /^\p{Cc}|\p{Cf}|\p{Co}|\p{Cs}$/u.test(char);
1203- }
1204- }
1205-
1206- /**
1207- * Performs invalid character removal and whitespace cleanup on text.
1208- * @param {string} text The text to clean.
1209- * @returns {string} The cleaned text.
1210- * @private
1211- */
1212- _clean_text(text) {
1213- const output = [];
1214- for (const char of text) {
1215- const cp = char.charCodeAt(0);
1216- if (cp === 0 || cp === 0xFFFD || this._is_control(char)) {
1217- continue;
1218- }
1219- if (/^\s$/.test(char)) { // is whitespace
1220- output.push(" ");
1221- } else {
1222- output.push(char);
1223- }
1224- }
1225- return output.join("");
1264+ if (this.config.strip_accents !== false) {
1265+ text = this.stripAccents(text);
1266+ }
1267+ } else if (this.config.strip_accents) {
1268+ text = this.stripAccents(text);
12261269 }
1227- /**
1228- * Normalizes the given text based on the configuration.
1229- * @param {string} text The text to normalize.
1230- * @returns {string} The normalized text.
1231- */
1232- normalize(text) {
1233- if (this.config.clean_text) {
1234- text = this._clean_text(text);
1235- }
1236-
1237- if (this.config.handle_chinese_chars) {
1238- text = this._tokenize_chinese_chars(text);
1239- }
1240-
1241- if (this.config.lowercase) {
1242- text = text.toLowerCase();
1243-
1244- if (this.config.strip_accents !== false) {
1245- text = this.stripAccents(text);
1246- }
1247- } else if (this.config.strip_accents) {
1248- text = this.stripAccents(text);
1249- }
12501270
1251- return text;
1252- }
1271+ return text;
1272+ }
12531273 }
12541274
12551275 /**
@@ -1258,7 +1278,7 @@
12581278 * @extends Callable
12591279 */
12601280 class PreTokenizer extends Callable {
1261- /**
1281+ /**
12621282 * Factory method that returns an instance of a subclass of `PreTokenizer` based on the provided configuration.
12631283 *
12641284 * @static
@@ -1266,98 +1286,102 @@
12661286 * @returns {PreTokenizer} An instance of a subclass of `PreTokenizer`.
12671287 * @throws {Error} If the provided configuration object does not correspond to any known pre-tokenizer.
12681288 */
1269- static fromConfig(config) {
1270- if (config === null) return null;
1271-
1272- switch (config.type) {
1273- case 'BertPreTokenizer':
1274- return new BertPreTokenizer(config);
1275- case 'Sequence':
1276- return new PreTokenizerSequence(config);
1277- case 'WhitespaceSplit':
1278- return new WhitespaceSplit(config);
1279- case 'Metaspace':
1280- return new MetaspacePreTokenizer(config);
1281-
1282- case 'ByteLevel':
1283- return new ByteLevelPreTokenizer(config);
1284- case 'Split':
1285- return new SplitPreTokenizer(config);
1286- case 'Punctuation':
1287- return new PunctuationPreTokenizer(config);
1288- case 'Digits':
1289- return new DigitsPreTokenizer(config);
1290- case 'Replace':
1291- return new ReplacePreTokenizer(config);
1292- default:
1293- throw new Error(`Unknown PreTokenizer type: ${config.type}`);
1294- }
1295- }
1296-
1297- /**
1298- * Method that should be implemented by subclasses to define the specific pre-tokenization logic.
1299- *
1300- * @abstract
1301- * @param {string} text The text to pre-tokenize.
1302- * @param {Object} [options] Additional options for the pre-tokenization logic.
1303- * @returns {string[]} The pre-tokenized text.
1304- * @throws {Error} If the method is not implemented in the subclass.
1305- */
1306- pre_tokenize_text(text, options) {
1307- throw Error("pre_tokenize_text should be implemented in subclass.")
1308- }
1309-
1310- /**
1311- * Tokenizes the given text into pre-tokens.
1312- * @param {string|string[]} text The text or array of texts to pre-tokenize.
1313- * @param {Object} [options] Additional options for the pre-tokenization logic.
1314- * @returns {string[]} An array of pre-tokens.
1315- */
1316- pre_tokenize(text, options) {
1317- return (Array.isArray(text)
1318- ? text.map(x => this.pre_tokenize_text(x, options))
1319- : this.pre_tokenize_text(text, options)
1320- ).flat();
1321- }
1322-
1323- /**
1324- * Alias for {@link PreTokenizer#pre_tokenize}.
1325- * @param {string|string[]} text The text or array of texts to pre-tokenize.
1326- * @param {Object} [options] Additional options for the pre-tokenization logic.
1327- * @returns {string[]} An array of pre-tokens.
1328- */
1329- _call(text, options) {
1330- return this.pre_tokenize(text, options);
1331- }
1289+ static fromConfig(config) {
1290+ if (config === null) return null;
1291+
1292+ switch (config.type) {
1293+ case "BertPreTokenizer":
1294+ return new BertPreTokenizer(config);
1295+ case "Sequence":
1296+ return new PreTokenizerSequence(config);
1297+ case "WhitespaceSplit":
1298+ return new WhitespaceSplit(config);
1299+ case "Metaspace":
1300+ return new MetaspacePreTokenizer(config);
1301+
1302+ case "ByteLevel":
1303+ return new ByteLevelPreTokenizer(config);
1304+ case "Split":
1305+ return new SplitPreTokenizer(config);
1306+ case "Punctuation":
1307+ return new PunctuationPreTokenizer(config);
1308+ case "Digits":
1309+ return new DigitsPreTokenizer(config);
1310+ case "Replace":
1311+ return new ReplacePreTokenizer(config);
1312+ default:
1313+ throw new Error(`Unknown PreTokenizer type: ${config.type}`);
1314+ }
1315+ }
1316+
1317+ /**
1318+ * Method that should be implemented by subclasses to define the specific pre-tokenization logic.
1319+ *
1320+ * @abstract
1321+ * @param {string} text The text to pre-tokenize.
1322+ * @param {Object} [options] Additional options for the pre-tokenization logic.
1323+ * @returns {string[]} The pre-tokenized text.
1324+ * @throws {Error} If the method is not implemented in the subclass.
1325+ */
1326+ pre_tokenize_text(text, options) {
1327+ throw Error("pre_tokenize_text should be implemented in subclass.");
1328+ }
1329+
1330+ /**
1331+ * Tokenizes the given text into pre-tokens.
1332+ * @param {string|string[]} text The text or array of texts to pre-tokenize.
1333+ * @param {Object} [options] Additional options for the pre-tokenization logic.
1334+ * @returns {string[]} An array of pre-tokens.
1335+ */
1336+ pre_tokenize(text, options) {
1337+ return (
1338+ Array.isArray(text)
1339+ ? text.map((x) => this.pre_tokenize_text(x, options))
1340+ : this.pre_tokenize_text(text, options)
1341+ ).flat();
1342+ }
1343+
1344+ /**
1345+ * Alias for {@link PreTokenizer#pre_tokenize}.
1346+ * @param {string|string[]} text The text or array of texts to pre-tokenize.
1347+ * @param {Object} [options] Additional options for the pre-tokenization logic.
1348+ * @returns {string[]} An array of pre-tokens.
1349+ */
1350+ _call(text, options) {
1351+ return this.pre_tokenize(text, options);
1352+ }
13321353 }
13331354
13341355 /**
13351356 * @extends PreTokenizer
13361357 */
13371358 class BertPreTokenizer extends PreTokenizer {
1338- /**
1339- * A PreTokenizer that splits text into wordpieces using a basic tokenization scheme
1340- * similar to that used in the original implementation of BERT.
1341- *
1342- * @param {Object} config The configuration object.
1343- */
1344- constructor(config) {
1345- super();
1346- // Construct a pattern which matches the rust implementation:
1347- // https://github.com/huggingface/tokenizers/blob/b4fcc9ce6e4ad5806e82826f816acfdfdc4fcc67/tokenizers/src/pre_tokenizers/bert.rs#L11
1348- // Equivalent to removing whitespace and splitting on punctuation (both \p{P} and other ascii characters)
1349- this.pattern = new RegExp(`[^\\s${PUNCTUATION_REGEX}]+|[${PUNCTUATION_REGEX}]`, 'gu');
1350- }
1351- /**
1352- * Tokenizes a single text using the BERT pre-tokenization scheme.
1353- *
1354- * @param {string} text The text to tokenize.
1355- * @param {Object} [options] Additional options for the pre-tokenization logic.
1356- * @returns {string[]} An array of tokens.
1357- */
1358- pre_tokenize_text(text, options) {
1359- return text.trim().match(this.pattern) || [];
1360- }
1359+ /**
1360+ * A PreTokenizer that splits text into wordpieces using a basic tokenization scheme
1361+ * similar to that used in the original implementation of BERT.
1362+ *
1363+ * @param {Object} config The configuration object.
1364+ */
1365+ constructor(config) {
1366+ super();
1367+ // Construct a pattern which matches the rust implementation:
1368+ // https://github.com/huggingface/tokenizers/blob/b4fcc9ce6e4ad5806e82826f816acfdfdc4fcc67/tokenizers/src/pre_tokenizers/bert.rs#L11
1369+ // Equivalent to removing whitespace and splitting on punctuation (both \p{P} and other ascii characters)
1370+ this.pattern = new RegExp(
1371+ `[^\\s${PUNCTUATION_REGEX}]+|[${PUNCTUATION_REGEX}]`,
1372+ "gu",
1373+ );
1374+ }
1375+ /**
1376+ * Tokenizes a single text using the BERT pre-tokenization scheme.
1377+ *
1378+ * @param {string} text The text to tokenize.
1379+ * @param {Object} [options] Additional options for the pre-tokenization logic.
1380+ * @returns {string[]} An array of tokens.
1381+ */
1382+ pre_tokenize_text(text, options) {
1383+ return text.trim().match(this.pattern) || [];
1384+ }
13611385 }
13621386
13631387 /**
@@ -1365,58 +1389,62 @@
13651389 * @extends PreTokenizer
13661390 */
13671391 class ByteLevelPreTokenizer extends PreTokenizer {
1392+ /**
1393+ * Creates a new instance of the `ByteLevelPreTokenizer` class.
1394+ * @param {Object} config The configuration object.
1395+ */
1396+ constructor(config) {
1397+ super();
1398+ this.config = config;
1399+
13681400 /**
1369- * Creates a new instance of the `ByteLevelPreTokenizer` class.
1370- * @param {Object} config The configuration object.
1401+ * @type {boolean} Whether to add a leading space to the first word.
1402+ * This allows to treat the leading word just as any other word.
13711403 */
1372- constructor(config) {
1373- super();
1374- this.config = config;
1375-
1376- /**
1377- * @type {boolean} Whether to add a leading space to the first word.
1378- * This allows to treat the leading word just as any other word.
1379- */
1380- this.add_prefix_space = this.config.add_prefix_space;
1381-
1382- /**
1383- * @type {boolean} Whether the post processing step should trim offsets
1384- * to avoid including whitespaces.
1385- * @todo Use this in the pretokenization step.
1386- */
1387- this.trim_offsets = this.config.trim_offsets;
1388-
1389- /**
1390- * @type {boolean} Whether to use the standard GPT2 regex for whitespace splitting.
1391- * Set it to False if you want to use your own splitting. Defaults to true.
1392- */
1393- this.use_regex = this.config.use_regex ?? true;
1394- this.pattern = /'s|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+/gu;
1395-
1396- this.byte_encoder = BYTES_TO_UNICODE;
1397- this.text_encoder = new TextEncoder();
1398- }
1404+ this.add_prefix_space = this.config.add_prefix_space;
13991405
14001406 /**
1401- * Tokenizes a single piece of text using byte-level tokenization.
1402- * @param {string} text The text to tokenize.
1403- * @param {Object} [options] Additional options for the pre-tokenization logic.
1404- * @returns {string[]} An array of tokens.
1407+ * @type {boolean} Whether the post processing step should trim offsets
1408+ * to avoid including whitespaces.
1409+ * @todo Use this in the pretokenization step.
14051410 */
1406- pre_tokenize_text(text, options) {
1407- // Add a leading space if the option is enabled
1408- if (this.add_prefix_space && !text.startsWith(' ')) {
1409- text = ' ' + text;
1410- }
1411+ this.trim_offsets = this.config.trim_offsets;
14111412
1412- // Split on whitespace and punctuation
1413- const tokens = this.use_regex ? (text.match(this.pattern) || []) : [text];
1413+ /**
1414+ * @type {boolean} Whether to use the standard GPT2 regex for whitespace splitting.
1415+ * Set it to False if you want to use your own splitting. Defaults to true.
1416+ */
1417+ this.use_regex = this.config.use_regex ?? true;
1418+ this.pattern =
1419+ /'s|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+/gu;
14141420
1415- // Maps all our bytes to unicode strings, avoiding control tokens of the BPE (spaces in our case)
1416- return tokens.map(
1417- token => Array.from(this.text_encoder.encode(token), byte => this.byte_encoder[byte]).join('')
1418- );
1421+ this.byte_encoder = BYTES_TO_UNICODE;
1422+ this.text_encoder = new TextEncoder();
1423+ }
1424+
1425+ /**
1426+ * Tokenizes a single piece of text using byte-level tokenization.
1427+ * @param {string} text The text to tokenize.
1428+ * @param {Object} [options] Additional options for the pre-tokenization logic.
1429+ * @returns {string[]} An array of tokens.
1430+ */
1431+ pre_tokenize_text(text, options) {
1432+ // Add a leading space if the option is enabled
1433+ if (this.add_prefix_space && !text.startsWith(" ")) {
1434+ text = " " + text;
14191435 }
1436+
1437+ // Split on whitespace and punctuation
1438+ const tokens = this.use_regex ? text.match(this.pattern) || [] : [text];
1439+
1440+ // Maps all our bytes to unicode strings, avoiding control tokens of the BPE (spaces in our case)
1441+ return tokens.map((token) =>
1442+ Array.from(
1443+ this.text_encoder.encode(token),
1444+ (byte) => this.byte_encoder[byte],
1445+ ).join(""),
1446+ );
1447+ }
14201448 }
14211449
14221450 /**
@@ -1428,39 +1456,39 @@
14281456 * @extends PreTokenizer
14291457 */
14301458 class SplitPreTokenizer extends PreTokenizer {
1431- /**
1432- * @param {Object} config The configuration options for the pre-tokenizer.
1433- * @param {Object} config.pattern The pattern used to split the text. Can be a string or a regex object.
1434- * @param {string|undefined} config.pattern.String The string to use for splitting. Only defined if the pattern is a string.
1435- * @param {string|undefined} config.pattern.Regex The regex to use for splitting. Only defined if the pattern is a regex.
1436- * @param {SplitDelimiterBehavior} config.behavior The behavior to use when splitting.
1437- * @param {boolean} config.invert Whether to split (invert=false) or match (invert=true) the pattern.
1438- */
1439- constructor(config) {
1440- super();
1441- this.config = config;
1442- // TODO support all behaviours (config.behavior)
1443-
1444- this.pattern = createPattern(this.config.pattern, this.config.invert);
1459+ /**
1460+ * @param {Object} config The configuration options for the pre-tokenizer.
1461+ * @param {Object} config.pattern The pattern used to split the text. Can be a string or a regex object.
1462+ * @param {string|undefined} config.pattern.String The string to use for splitting. Only defined if the pattern is a string.
1463+ * @param {string|undefined} config.pattern.Regex The regex to use for splitting. Only defined if the pattern is a regex.
1464+ * @param {SplitDelimiterBehavior} config.behavior The behavior to use when splitting.
1465+ * @param {boolean} config.invert Whether to split (invert=false) or match (invert=true) the pattern.
1466+ */
1467+ constructor(config) {
1468+ super();
1469+ this.config = config;
1470+ // TODO support all behaviours (config.behavior)
1471+
1472+ this.pattern = createPattern(this.config.pattern, this.config.invert);
1473+ }
1474+
1475+ /**
1476+ * Tokenizes text by splitting it using the given pattern.
1477+ * @param {string} text The text to tokenize.
1478+ * @param {Object} [options] Additional options for the pre-tokenization logic.
1479+ * @returns {string[]} An array of tokens.
1480+ */
1481+ pre_tokenize_text(text, options) {
1482+ if (this.pattern === null) {
1483+ return [];
14451484 }
14461485
1447- /**
1448- * Tokenizes text by splitting it using the given pattern.
1449- * @param {string} text The text to tokenize.
1450- * @param {Object} [options] Additional options for the pre-tokenization logic.
1451- * @returns {string[]} An array of tokens.
1452- */
1453- pre_tokenize_text(text, options) {
1454- if (this.pattern === null) {
1455- return [];
1456- }
1457-
1458- if (this.config.invert) {
1459- return text.match(this.pattern) || [];
1460- } else {
1461- return regexSplit(text, this.pattern);
1462- }
1486+ if (this.config.invert) {
1487+ return text.match(this.pattern) || [];
1488+ } else {
1489+ return regexSplit(text, this.pattern);
14631490 }
1491+ }
14641492 }
14651493
14661494 /**
@@ -1468,55 +1496,57 @@
14681496 * @extends PreTokenizer
14691497 */
14701498 class PunctuationPreTokenizer extends PreTokenizer {
1471- /**
1472- * @param {Object} config The configuration options for the pre-tokenizer.
1473- * @param {SplitDelimiterBehavior} config.behavior The behavior to use when splitting.
1474- */
1475- constructor(config) {
1476- super();
1477- this.config = config;
1478- this.pattern = new RegExp(`[^${PUNCTUATION_REGEX}]+|[${PUNCTUATION_REGEX}]+`, 'gu');
1479- }
1480-
1481- /**
1482- * Tokenizes text by splitting it using the given pattern.
1483- * @param {string} text The text to tokenize.
1484- * @param {Object} [options] Additional options for the pre-tokenization logic.
1485- * @returns {string[]} An array of tokens.
1486- */
1487- pre_tokenize_text(text, options) {
1488- return text.match(this.pattern) || [];
1489- }
1499+ /**
1500+ * @param {Object} config The configuration options for the pre-tokenizer.
1501+ * @param {SplitDelimiterBehavior} config.behavior The behavior to use when splitting.
1502+ */
1503+ constructor(config) {
1504+ super();
1505+ this.config = config;
1506+ this.pattern = new RegExp(
1507+ `[^${PUNCTUATION_REGEX}]+|[${PUNCTUATION_REGEX}]+`,
1508+ "gu",
1509+ );
1510+ }
1511+
1512+ /**
1513+ * Tokenizes text by splitting it using the given pattern.
1514+ * @param {string} text The text to tokenize.
1515+ * @param {Object} [options] Additional options for the pre-tokenization logic.
1516+ * @returns {string[]} An array of tokens.
1517+ */
1518+ pre_tokenize_text(text, options) {
1519+ return text.match(this.pattern) || [];
1520+ }
14901521 }
14911522
1492-
14931523 /**
14941524 * Splits text based on digits.
14951525 * @extends PreTokenizer
14961526 */
14971527 class DigitsPreTokenizer extends PreTokenizer {
1498- /**
1499- * @param {Object} config The configuration options for the pre-tokenizer.
1500- * @param {boolean} config.individual_digits Whether to split on individual digits.
1501- */
1502- constructor(config) {
1503- super();
1504- this.config = config;
1505-
1506- // Construct a pattern which matches the rust implementation:
1507- const digit_pattern = `[^\\d]+|\\d${this.config.individual_digits ? '' : '+'}`;
1508- this.pattern = new RegExp(digit_pattern, 'gu');
1509- }
1510-
1511- /**
1512- * Tokenizes text by splitting it using the given pattern.
1513- * @param {string} text The text to tokenize.
1514- * @param {Object} [options] Additional options for the pre-tokenization logic.
1515- * @returns {string[]} An array of tokens.
1516- */
1517- pre_tokenize_text(text, options) {
1518- return text.match(this.pattern) || [];
1519- }
1528+ /**
1529+ * @param {Object} config The configuration options for the pre-tokenizer.
1530+ * @param {boolean} config.individual_digits Whether to split on individual digits.
1531+ */
1532+ constructor(config) {
1533+ super();
1534+ this.config = config;
1535+
1536+ // Construct a pattern which matches the rust implementation:
1537+ const digit_pattern = `[^\\d]+|\\d${this.config.individual_digits ? "" : "+"}`;
1538+ this.pattern = new RegExp(digit_pattern, "gu");
1539+ }
1540+
1541+ /**
1542+ * Tokenizes text by splitting it using the given pattern.
1543+ * @param {string} text The text to tokenize.
1544+ * @param {Object} [options] Additional options for the pre-tokenization logic.
1545+ * @returns {string[]} An array of tokens.
1546+ */
1547+ pre_tokenize_text(text, options) {
1548+ return text.match(this.pattern) || [];
1549+ }
15201550 }
15211551
15221552 /**
@@ -1525,7 +1555,6 @@
15251555 * @property {number[]} [token_type_ids] List of token type ids produced by the post-processor.
15261556 */
15271557
1528-
15291558 /**
15301559 * @typedef {Object} EncodingSingle
15311560 * @property {number[]} input_ids List of token ids to be fed to a model.
@@ -1533,166 +1562,169 @@
15331562 * @property {number[]} [token_type_ids] List of indices specifying which tokens should be attended to by the model
15341563 */
15351564
1536-
15371565 /**
15381566 * @extends Callable
15391567 */
15401568 class PostProcessor extends Callable {
1541-
1542- /**
1543- * @param {Object} config The configuration for the post-processor.
1544- */
1545- constructor(config) {
1546- super();
1547- this.config = config;
1548- }
1549-
1550- /**
1551- * Factory method to create a PostProcessor object from a configuration object.
1552- *
1553- * @param {Object} config Configuration object representing a PostProcessor.
1554- * @returns {PostProcessor} A PostProcessor object created from the given configuration.
1555- * @throws {Error} If an unknown PostProcessor type is encountered.
1556- */
1557- static fromConfig(config) {
1558- if (config === null) return null;
1559- switch (config.type) {
1560- case 'TemplateProcessing':
1561- return new TemplateProcessing(config);
1562-
1563- case 'ByteLevel':
1564- return new ByteLevelPostProcessor(config);
1565-
1566- case 'RobertaProcessing':
1567- return new RobertaProcessing(config);
1568- case 'BertProcessing':
1569- return new BertProcessing(config);
1570-
1571- default:
1572- throw new Error(`Unknown PostProcessor type: ${config.type}`);
1573- }
1574- }
1575-
1576- /**
1577- * Method to be implemented in subclass to apply post-processing on the given tokens.
1578- *
1579- * @param {Array} tokens The input tokens to be post-processed.
1580- * @param {...*} args Additional arguments required by the post-processing logic.
1581- * @returns {PostProcessedOutput} The post-processed tokens.
1582- * @throws {Error} If the method is not implemented in subclass.
1583- */
1584- post_process(tokens, ...args) {
1585- throw Error("post_process should be implemented in subclass.")
1586- }
1587-
1588- /**
1589- * Alias for {@link PostProcessor#post_process}.
1590- * @param {Array} tokens The text or array of texts to post-process.
1591- * @param {...*} args Additional arguments required by the post-processing logic.
1592- * @returns {PostProcessedOutput} The post-processed tokens.
1593- */
1594- _call(tokens, ...args) {
1595- return this.post_process(tokens, ...args);
1596- }
1569+ /**
1570+ * @param {Object} config The configuration for the post-processor.
1571+ */
1572+ constructor(config) {
1573+ super();
1574+ this.config = config;
1575+ }
1576+
1577+ /**
1578+ * Factory method to create a PostProcessor object from a configuration object.
1579+ *
1580+ * @param {Object} config Configuration object representing a PostProcessor.
1581+ * @returns {PostProcessor} A PostProcessor object created from the given configuration.
1582+ * @throws {Error} If an unknown PostProcessor type is encountered.
1583+ */
1584+ static fromConfig(config) {
1585+ if (config === null) return null;
1586+ switch (config.type) {
1587+ case "TemplateProcessing":
1588+ return new TemplateProcessing(config);
1589+
1590+ case "ByteLevel":
1591+ return new ByteLevelPostProcessor(config);
1592+
1593+ case "RobertaProcessing":
1594+ return new RobertaProcessing(config);
1595+ case "BertProcessing":
1596+ return new BertProcessing(config);
1597+
1598+ default:
1599+ throw new Error(`Unknown PostProcessor type: ${config.type}`);
1600+ }
1601+ }
1602+
1603+ /**
1604+ * Method to be implemented in subclass to apply post-processing on the given tokens.
1605+ *
1606+ * @param {Array} tokens The input tokens to be post-processed.
1607+ * @param {...*} args Additional arguments required by the post-processing logic.
1608+ * @returns {PostProcessedOutput} The post-processed tokens.
1609+ * @throws {Error} If the method is not implemented in subclass.
1610+ */
1611+ post_process(tokens, ...args) {
1612+ throw Error("post_process should be implemented in subclass.");
1613+ }
1614+
1615+ /**
1616+ * Alias for {@link PostProcessor#post_process}.
1617+ * @param {Array} tokens The text or array of texts to post-process.
1618+ * @param {...*} args Additional arguments required by the post-processing logic.
1619+ * @returns {PostProcessedOutput} The post-processed tokens.
1620+ */
1621+ _call(tokens, ...args) {
1622+ return this.post_process(tokens, ...args);
1623+ }
15971624 }
15981625
15991626 /**
16001627 * A post-processor that adds special tokens to the beginning and end of the input.
16011628 */
16021629 class BertProcessing extends PostProcessor {
1603- /**
1604- * @param {Object} config The configuration for the post-processor.
1605- * @param {string[]} config.cls The special tokens to add to the beginning of the input.
1606- * @param {string[]} config.sep The special tokens to add to the end of the input.
1607- */
1608- constructor(config) {
1609- super(config);
1610- // TODO use all of config: add_prefix_space, trim_offsets
1611-
1612- this.cls = config.cls[0];
1613- this.sep = config.sep[0];
1630+ /**
1631+ * @param {Object} config The configuration for the post-processor.
1632+ * @param {string[]} config.cls The special tokens to add to the beginning of the input.
1633+ * @param {string[]} config.sep The special tokens to add to the end of the input.
1634+ */
1635+ constructor(config) {
1636+ super(config);
1637+ // TODO use all of config: add_prefix_space, trim_offsets
1638+
1639+ this.cls = config.cls[0];
1640+ this.sep = config.sep[0];
1641+ }
1642+
1643+ /**
1644+ * Adds the special tokens to the beginning and end of the input.
1645+ * @param {string[]} tokens The input tokens.
1646+ * @param {string[]} [tokens_pair=null] An optional second set of input tokens.
1647+ * @returns {PostProcessedOutput} The post-processed tokens with the special tokens added to the beginning and end.
1648+ */
1649+ post_process(tokens, tokens_pair = null, { add_special_tokens = true } = {}) {
1650+ if (add_special_tokens) {
1651+ tokens = mergeArrays([this.cls], tokens, [this.sep]);
16141652 }
16151653
1616- /**
1617- * Adds the special tokens to the beginning and end of the input.
1618- * @param {string[]} tokens The input tokens.
1619- * @param {string[]} [tokens_pair=null] An optional second set of input tokens.
1620- * @returns {PostProcessedOutput} The post-processed tokens with the special tokens added to the beginning and end.
1621- */
1622- post_process(tokens, tokens_pair = null, {
1623- add_special_tokens = true,
1624- } = {}) {
1625- if (add_special_tokens) {
1626- tokens = mergeArrays([this.cls], tokens, [this.sep]);
1627- }
1654+ let token_type_ids = new Array(tokens.length).fill(0);
1655+ if (tokens_pair !== null) {
1656+ // NOTE: It is intended to add 2 EOS tokens after the first set of tokens
1657+ // https://github.com/huggingface/tokenizers/issues/983
1658+ const middle =
1659+ add_special_tokens && this instanceof RobertaProcessing
1660+ ? [this.sep]
1661+ : [];
1662+ const after = add_special_tokens ? [this.sep] : [];
16281663
1629- let token_type_ids = new Array(tokens.length).fill(0);
1630- if (tokens_pair !== null) {
1631- // NOTE: It is intended to add 2 EOS tokens after the first set of tokens
1632- // https://github.com/huggingface/tokenizers/issues/983
1633- const middle = (add_special_tokens && this instanceof RobertaProcessing)
1634- ? [this.sep]
1635- : [];
1636- const after = add_special_tokens ? [this.sep] : [];
1637-
1638- tokens = mergeArrays(tokens, middle, tokens_pair, after);
1639- token_type_ids = mergeArrays(token_type_ids, new Array(tokens_pair.length + middle.length + after.length).fill(1));
1640- }
1641- return { tokens, token_type_ids };
1664+ tokens = mergeArrays(tokens, middle, tokens_pair, after);
1665+ token_type_ids = mergeArrays(
1666+ token_type_ids,
1667+ new Array(tokens_pair.length + middle.length + after.length).fill(1),
1668+ );
16421669 }
1670+ return { tokens, token_type_ids };
1671+ }
16431672 }
1644-class RobertaProcessing extends BertProcessing { } // NOTE: extends BertProcessing
1673+class RobertaProcessing extends BertProcessing {} // NOTE: extends BertProcessing
16451674
16461675 /**
16471676 * Post processor that replaces special tokens in a template with actual tokens.
16481677 * @extends PostProcessor
16491678 */
16501679 class TemplateProcessing extends PostProcessor {
1651- /**
1652- * Creates a new instance of `TemplateProcessing`.
1653- * @param {Object} config The configuration options for the post processor.
1654- * @param {Array} config.single The template for a single sequence of tokens.
1655- * @param {Array} config.pair The template for a pair of sequences of tokens.
1656- */
1657- constructor(config) {
1658- super(config);
1659-
1660- this.single = config.single;
1661- this.pair = config.pair;
1662- }
1663-
1664- /**
1665- * Replaces special tokens in the template with actual tokens.
1666- * @param {string[]} tokens The list of tokens for the first sequence.
1667- * @param {string[]} [tokens_pair=null] The list of tokens for the second sequence (optional).
1668- * @returns {PostProcessedOutput} An object containing the list of tokens with the special tokens replaced with actual tokens.
1669- */
1670- post_process(tokens, tokens_pair = null, {
1671- add_special_tokens = true,
1672- } = {}) {
1673- const type = tokens_pair === null ? this.single : this.pair
1674-
1675- let processedTokens = [];
1676- let types = [];
1677- for (const item of type) {
1678- if ('SpecialToken' in item) {
1679- if (add_special_tokens) {
1680- processedTokens.push(item.SpecialToken.id);
1681- types.push(item.SpecialToken.type_id);
1682- }
1683- } else if ('Sequence' in item) {
1684- if (item.Sequence.id === 'A') {
1685- processedTokens = mergeArrays(processedTokens, tokens);
1686- types = mergeArrays(types, new Array(tokens.length).fill(item.Sequence.type_id));
1687-
1688- } else if (item.Sequence.id === 'B') {
1689- processedTokens = mergeArrays(processedTokens, tokens_pair);
1690- types = mergeArrays(types, new Array(tokens_pair.length).fill(item.Sequence.type_id));
1691- }
1692- }
1680+ /**
1681+ * Creates a new instance of `TemplateProcessing`.
1682+ * @param {Object} config The configuration options for the post processor.
1683+ * @param {Array} config.single The template for a single sequence of tokens.
1684+ * @param {Array} config.pair The template for a pair of sequences of tokens.
1685+ */
1686+ constructor(config) {
1687+ super(config);
1688+
1689+ this.single = config.single;
1690+ this.pair = config.pair;
1691+ }
1692+
1693+ /**
1694+ * Replaces special tokens in the template with actual tokens.
1695+ * @param {string[]} tokens The list of tokens for the first sequence.
1696+ * @param {string[]} [tokens_pair=null] The list of tokens for the second sequence (optional).
1697+ * @returns {PostProcessedOutput} An object containing the list of tokens with the special tokens replaced with actual tokens.
1698+ */
1699+ post_process(tokens, tokens_pair = null, { add_special_tokens = true } = {}) {
1700+ const type = tokens_pair === null ? this.single : this.pair;
1701+
1702+ let processedTokens = [];
1703+ let types = [];
1704+ for (const item of type) {
1705+ if ("SpecialToken" in item) {
1706+ if (add_special_tokens) {
1707+ processedTokens.push(item.SpecialToken.id);
1708+ types.push(item.SpecialToken.type_id);
1709+ }
1710+ } else if ("Sequence" in item) {
1711+ if (item.Sequence.id === "A") {
1712+ processedTokens = mergeArrays(processedTokens, tokens);
1713+ types = mergeArrays(
1714+ types,
1715+ new Array(tokens.length).fill(item.Sequence.type_id),
1716+ );
1717+ } else if (item.Sequence.id === "B") {
1718+ processedTokens = mergeArrays(processedTokens, tokens_pair);
1719+ types = mergeArrays(
1720+ types,
1721+ new Array(tokens_pair.length).fill(item.Sequence.type_id),
1722+ );
16931723 }
1694- return { tokens: processedTokens, token_type_ids: types };
1724+ }
16951725 }
1726+ return { tokens: processedTokens, token_type_ids: types };
1727+ }
16961728 }
16971729
16981730 /**
@@ -1700,18 +1732,18 @@
17001732 * @extends PostProcessor
17011733 */
17021734 class ByteLevelPostProcessor extends PostProcessor {
1703- /**
1704- * Post process the given tokens.
1705- * @param {string[]} tokens The list of tokens for the first sequence.
1706- * @param {string[]} [tokens_pair=null] The list of tokens for the second sequence (optional).
1707- * @returns {PostProcessedOutput} An object containing the post-processed tokens.
1708- */
1709- post_process(tokens, tokens_pair = null) {
1710- if (tokens_pair) {
1711- tokens = mergeArrays(tokens, tokens_pair);
1712- }
1713- return { tokens };
1735+ /**
1736+ * Post process the given tokens.
1737+ * @param {string[]} tokens The list of tokens for the first sequence.
1738+ * @param {string[]} [tokens_pair=null] The list of tokens for the second sequence (optional).
1739+ * @returns {PostProcessedOutput} An object containing the post-processed tokens.
1740+ */
1741+ post_process(tokens, tokens_pair = null) {
1742+ if (tokens_pair) {
1743+ tokens = mergeArrays(tokens, tokens_pair);
17141744 }
1745+ return { tokens };
1746+ }
17151747 }
17161748
17171749 /**
@@ -1719,144 +1751,147 @@
17191751 * @extends Callable
17201752 */
17211753 class Decoder extends Callable {
1722-
1723- /**
1724- * Creates an instance of `Decoder`.
1725- *
1726- * @param {Object} config The configuration object.
1727- */
1728- constructor(config) {
1729- super();
1730- this.config = config;
1731-
1732- /** @type {AddedToken[]} */
1733- this.added_tokens = [];
1734- this.end_of_word_suffix = null;
1735- this.trim_offsets = config.trim_offsets;
1736- }
1737-
1738- /**
1754+ /**
1755+ * Creates an instance of `Decoder`.
1756+ *
1757+ * @param {Object} config The configuration object.
1758+ */
1759+ constructor(config) {
1760+ super();
1761+ this.config = config;
1762+
1763+ /** @type {AddedToken[]} */
1764+ this.added_tokens = [];
1765+ this.end_of_word_suffix = null;
1766+ this.trim_offsets = config.trim_offsets;
1767+ }
1768+
1769+ /**
17391770 * Creates a decoder instance based on the provided configuration.
17401771 *
17411772 * @param {Object} config The configuration object.
17421773 * @returns {Decoder} A decoder instance.
17431774 * @throws {Error} If an unknown decoder type is provided.
17441775 */
1745- static fromConfig(config) {
1746- if (config === null) return null;
1747- switch (config.type) {
1748- case 'WordPiece':
1749- return new WordPieceDecoder(config);
1750- case 'Metaspace':
1751- return new MetaspaceDecoder(config);
1752- case 'ByteLevel':
1753- return new ByteLevelDecoder(config);
1754-
1755- case 'Replace':
1756- return new ReplaceDecoder(config);
1757- case 'ByteFallback':
1758- return new ByteFallback(config);
1759- case 'Fuse':
1760- return new FuseDecoder(config);
1761- case 'Strip':
1762- return new StripDecoder(config);
1763-
1764- case 'Sequence':
1765- return new DecoderSequence(config);
1766-
1767- case 'CTC':
1768- return new CTCDecoder(config);
1769- case 'BPEDecoder':
1770- return new BPEDecoder(config);
1771- default:
1772- throw new Error(`Unknown Decoder type: ${config.type}`);
1773- }
1774- }
1775-
1776- /**
1777- * Calls the `decode` method.
1778- *
1779- * @param {string[]} tokens The list of tokens.
1780- * @returns {string} The decoded string.
1781- */
1782- _call(tokens) {
1783- return this.decode(tokens);
1784- }
1785-
1786- /**
1787- * Decodes a list of tokens.
1788- * @param {string[]} tokens The list of tokens.
1789- * @returns {string} The decoded string.
1790- */
1791- decode(tokens) {
1792- return this.decode_chain(tokens).join('');
1793- }
1794-
1795- /**
1796- * Apply the decoder to a list of tokens.
1797- *
1798- * @param {string[]} tokens The list of tokens.
1799- * @returns {string[]} The decoded list of tokens.
1800- * @throws {Error} If the `decode_chain` method is not implemented in the subclass.
1801- */
1802- decode_chain(tokens) {
1803- throw Error("`decode_chain` should be implemented in subclass.")
1804- }
1805-
1776+ static fromConfig(config) {
1777+ if (config === null) return null;
1778+ switch (config.type) {
1779+ case "WordPiece":
1780+ return new WordPieceDecoder(config);
1781+ case "Metaspace":
1782+ return new MetaspaceDecoder(config);
1783+ case "ByteLevel":
1784+ return new ByteLevelDecoder(config);
1785+
1786+ case "Replace":
1787+ return new ReplaceDecoder(config);
1788+ case "ByteFallback":
1789+ return new ByteFallback(config);
1790+ case "Fuse":
1791+ return new FuseDecoder(config);
1792+ case "Strip":
1793+ return new StripDecoder(config);
1794+
1795+ case "Sequence":
1796+ return new DecoderSequence(config);
1797+
1798+ case "CTC":
1799+ return new CTCDecoder(config);
1800+ case "BPEDecoder":
1801+ return new BPEDecoder(config);
1802+ default:
1803+ throw new Error(`Unknown Decoder type: ${config.type}`);
1804+ }
1805+ }
1806+
1807+ /**
1808+ * Calls the `decode` method.
1809+ *
1810+ * @param {string[]} tokens The list of tokens.
1811+ * @returns {string} The decoded string.
1812+ */
1813+ _call(tokens) {
1814+ return this.decode(tokens);
1815+ }
1816+
1817+ /**
1818+ * Decodes a list of tokens.
1819+ * @param {string[]} tokens The list of tokens.
1820+ * @returns {string} The decoded string.
1821+ */
1822+ decode(tokens) {
1823+ return this.decode_chain(tokens).join("");
1824+ }
1825+
1826+ /**
1827+ * Apply the decoder to a list of tokens.
1828+ *
1829+ * @param {string[]} tokens The list of tokens.
1830+ * @returns {string[]} The decoded list of tokens.
1831+ * @throws {Error} If the `decode_chain` method is not implemented in the subclass.
1832+ */
1833+ decode_chain(tokens) {
1834+ throw Error("`decode_chain` should be implemented in subclass.");
1835+ }
18061836 }
18071837
18081838 class ReplaceDecoder extends Decoder {
1809-
1810- /** @type {Decoder['decode_chain']} */
1811- decode_chain(tokens) {
1812- const pattern = createPattern(this.config.pattern);
1813- return pattern === null
1814- ? tokens
1815- : tokens.map(token => token.replaceAll(pattern, this.config.content))
1816- }
1839+ /** @type {Decoder['decode_chain']} */
1840+ decode_chain(tokens) {
1841+ const pattern = createPattern(this.config.pattern);
1842+ return pattern === null
1843+ ? tokens
1844+ : tokens.map((token) => token.replaceAll(pattern, this.config.content));
1845+ }
18171846 }
18181847
1819-
18201848 class ByteFallback extends Decoder {
1821- constructor(config) {
1822- super(config);
1823-
1824- this.text_decoder = new TextDecoder();
1825- }
1826-
1827- /** @type {Decoder['decode_chain']} */
1828- decode_chain(tokens) {
1829-
1830- const new_tokens = [];
1831- let previous_byte_tokens = [];
1832-
1833- for (const token of tokens) {
1834- let bytes = null;
1835- if (token.length === 6 && token.startsWith('<0x') && token.endsWith('>')) {
1836- const byte = parseInt(token.slice(3, 5), 16);
1837- if (!isNaN(byte)) {
1838- bytes = byte;
1839- }
1840- }
1841- if (bytes !== null) {
1842- previous_byte_tokens.push(bytes);
1843- } else {
1844- if (previous_byte_tokens.length > 0) {
1845- const string = this.text_decoder.decode(Uint8Array.from(previous_byte_tokens));
1846- new_tokens.push(string);
1847- previous_byte_tokens = [];
1848- }
1849- new_tokens.push(token);
1850- }
1851- }
1849+ constructor(config) {
1850+ super(config);
1851+
1852+ this.text_decoder = new TextDecoder();
1853+ }
1854+
1855+ /** @type {Decoder['decode_chain']} */
1856+ decode_chain(tokens) {
1857+ const new_tokens = [];
1858+ let previous_byte_tokens = [];
1859+
1860+ for (const token of tokens) {
1861+ let bytes = null;
1862+ if (
1863+ token.length === 6 &&
1864+ token.startsWith("<0x") &&
1865+ token.endsWith(">")
1866+ ) {
1867+ const byte = parseInt(token.slice(3, 5), 16);
1868+ if (!isNaN(byte)) {
1869+ bytes = byte;
1870+ }
1871+ }
1872+ if (bytes !== null) {
1873+ previous_byte_tokens.push(bytes);
1874+ } else {
18521875 if (previous_byte_tokens.length > 0) {
1853- const string = this.text_decoder.decode(Uint8Array.from(previous_byte_tokens));
1854- new_tokens.push(string);
1855- previous_byte_tokens = [];
1876+ const string = this.text_decoder.decode(
1877+ Uint8Array.from(previous_byte_tokens),
1878+ );
1879+ new_tokens.push(string);
1880+ previous_byte_tokens = [];
18561881 }
1857-
1858- return new_tokens;
1882+ new_tokens.push(token);
1883+ }
1884+ }
1885+ if (previous_byte_tokens.length > 0) {
1886+ const string = this.text_decoder.decode(
1887+ Uint8Array.from(previous_byte_tokens),
1888+ );
1889+ new_tokens.push(string);
1890+ previous_byte_tokens = [];
18591891 }
1892+
1893+ return new_tokens;
1894+ }
18601895 }
18611896
18621897 /**
@@ -1865,50 +1900,48 @@
18651900 * exists incase some decoders need to happen after that step
18661901 */
18671902 class FuseDecoder extends Decoder {
1868-
1869- /** @type {Decoder['decode_chain']} */
1870- decode_chain(tokens) {
1871- return [tokens.join('')];
1872- }
1903+ /** @type {Decoder['decode_chain']} */
1904+ decode_chain(tokens) {
1905+ return [tokens.join("")];
1906+ }
18731907 }
18741908
1875-
18761909 class StripDecoder extends Decoder {
1877- constructor(config) {
1878- super(config);
1879-
1880- this.content = this.config.content;
1881- this.start = this.config.start;
1882- this.stop = this.config.stop;
1883- }
1884-
1885- /** @type {Decoder['decode_chain']} */
1886- decode_chain(tokens) {
1887- return tokens.map(token => {
1888- let start_cut = 0;
1889- for (let i = 0; i < this.start; ++i) {
1890- if (token[i] === this.content) {
1891- start_cut = i + 1;
1892- continue;
1893- } else {
1894- break;
1895- }
1896- }
1897-
1898- let stop_cut = token.length;
1899- for (let i = 0; i < this.stop; ++i) {
1900- const index = token.length - i - 1;
1901- if (token[index] === this.content) {
1902- stop_cut = index;
1903- continue;
1904- } else {
1905- break;
1906- }
1907- }
1910+ constructor(config) {
1911+ super(config);
1912+
1913+ this.content = this.config.content;
1914+ this.start = this.config.start;
1915+ this.stop = this.config.stop;
1916+ }
1917+
1918+ /** @type {Decoder['decode_chain']} */
1919+ decode_chain(tokens) {
1920+ return tokens.map((token) => {
1921+ let start_cut = 0;
1922+ for (let i = 0; i < this.start; ++i) {
1923+ if (token[i] === this.content) {
1924+ start_cut = i + 1;
1925+ continue;
1926+ } else {
1927+ break;
1928+ }
1929+ }
1930+
1931+ let stop_cut = token.length;
1932+ for (let i = 0; i < this.stop; ++i) {
1933+ const index = token.length - i - 1;
1934+ if (token[index] === this.content) {
1935+ stop_cut = index;
1936+ continue;
1937+ } else {
1938+ break;
1939+ }
1940+ }
19081941
1909- return token.slice(start_cut, stop_cut)
1910- });
1911- }
1942+ return token.slice(start_cut, stop_cut);
1943+ });
1944+ }
19121945 }
19131946
19141947 /**
@@ -1916,36 +1949,35 @@
19161949 * @extends Decoder
19171950 */
19181951 class WordPieceDecoder extends Decoder {
1952+ /**
1953+ * Creates a new instance of WordPieceDecoder.
1954+ * @param {Object} config The configuration object.
1955+ * @param {string} config.prefix The prefix used for WordPiece encoding.
1956+ * @param {boolean} config.cleanup Whether to cleanup the decoded string.
1957+ */
1958+ constructor(config) {
1959+ super(config);
1960+ this.cleanup = config.cleanup;
1961+ }
1962+
1963+ /** @type {Decoder['decode_chain']} */
1964+ decode_chain(tokens) {
1965+ return tokens.map((token, i) => {
1966+ if (i !== 0) {
1967+ if (token.startsWith(this.config.prefix)) {
1968+ // NOTE: .replace() is intended; only replace first occurrence
1969+ token = token.replace(this.config.prefix, "");
1970+ } else {
1971+ token = " " + token;
1972+ }
1973+ }
1974+ if (this.cleanup) {
1975+ token = clean_up_tokenization(token);
1976+ }
19191977
1920- /**
1921- * Creates a new instance of WordPieceDecoder.
1922- * @param {Object} config The configuration object.
1923- * @param {string} config.prefix The prefix used for WordPiece encoding.
1924- * @param {boolean} config.cleanup Whether to cleanup the decoded string.
1925- */
1926- constructor(config) {
1927- super(config);
1928- this.cleanup = config.cleanup;
1929- }
1930-
1931- /** @type {Decoder['decode_chain']} */
1932- decode_chain(tokens) {
1933- return tokens.map((token, i) => {
1934- if (i !== 0) {
1935- if (token.startsWith(this.config.prefix)) {
1936- // NOTE: .replace() is intended; only replace first occurrence
1937- token = token.replace(this.config.prefix, '');
1938- } else {
1939- token = ' ' + token;
1940- }
1941- }
1942- if (this.cleanup) {
1943- token = clean_up_tokenization(token)
1944- }
1945-
1946- return token;
1947- });
1948- }
1978+ return token;
1979+ });
1980+ }
19491981 }
19501982
19511983 /**
@@ -1953,69 +1985,70 @@
19531985 * @extends Decoder
19541986 */
19551987 class ByteLevelDecoder extends Decoder {
1956-
1957- /**
1958- * Create a `ByteLevelDecoder` object.
1959- * @param {Object} config Configuration object.
1960- */
1961- constructor(config) {
1962- super(config);
1963-
1964- this.byte_decoder = UNICODE_TO_BYTES;
1965- this.text_decoder = new TextDecoder("utf-8", {
1966- fatal: false,
1967- ignoreBOM: true,
1968- });
1969-
1970- this.end_of_word_suffix = null;
1971- }
1972-
1973- /**
1974- * Convert an array of tokens to string by decoding each byte.
1975- * @param {string[]} tokens Array of tokens to be decoded.
1976- * @returns {string} The decoded string.
1977- */
1978- convert_tokens_to_string(tokens) {
1979- const text = tokens.join('');
1980- const byteArray = new Uint8Array([...text].map(c => this.byte_decoder[c]));
1981- const decoded_text = this.text_decoder.decode(byteArray);
1982- return decoded_text;
1983- }
1984-
1985- /** @type {Decoder['decode_chain']} */
1986- decode_chain(tokens) {
1987- // TODO move to base class (like HF)
1988- // tokens === filtered_tokens
1989-
1990- // To avoid mixing byte-level and unicode for byte-level BPT
1991- // we need to build string separately for added tokens and byte-level tokens
1992- // cf. https://github.com/huggingface/transformers/issues/1133
1993- const sub_texts = [];
1994- let current_sub_text = [];
1995- for (const token of tokens) {
1996- // tokens sent here are already filtered, so we don't need to do this
1997- // if (skip_special_tokens && this.all_special_ids.includes(token)) {
1998- // continue;
1999- // }
2000-
2001- if (this.added_tokens.find(x => x.content === token) !== undefined) {
2002- if (current_sub_text.length > 0) {
2003- sub_texts.push(this.convert_tokens_to_string(current_sub_text));
2004- current_sub_text = [];
2005- }
2006- sub_texts.push(token);
2007- } else {
2008- current_sub_text.push(token);
2009- }
2010- }
1988+ /**
1989+ * Create a `ByteLevelDecoder` object.
1990+ * @param {Object} config Configuration object.
1991+ */
1992+ constructor(config) {
1993+ super(config);
1994+
1995+ this.byte_decoder = UNICODE_TO_BYTES;
1996+ this.text_decoder = new TextDecoder("utf-8", {
1997+ fatal: false,
1998+ ignoreBOM: true,
1999+ });
2000+
2001+ this.end_of_word_suffix = null;
2002+ }
2003+
2004+ /**
2005+ * Convert an array of tokens to string by decoding each byte.
2006+ * @param {string[]} tokens Array of tokens to be decoded.
2007+ * @returns {string} The decoded string.
2008+ */
2009+ convert_tokens_to_string(tokens) {
2010+ const text = tokens.join("");
2011+ const byteArray = new Uint8Array(
2012+ [...text].map((c) => this.byte_decoder[c]),
2013+ );
2014+ const decoded_text = this.text_decoder.decode(byteArray);
2015+ return decoded_text;
2016+ }
2017+
2018+ /** @type {Decoder['decode_chain']} */
2019+ decode_chain(tokens) {
2020+ // TODO move to base class (like HF)
2021+ // tokens === filtered_tokens
2022+
2023+ // To avoid mixing byte-level and unicode for byte-level BPT
2024+ // we need to build string separately for added tokens and byte-level tokens
2025+ // cf. https://github.com/huggingface/transformers/issues/1133
2026+ const sub_texts = [];
2027+ let current_sub_text = [];
2028+ for (const token of tokens) {
2029+ // tokens sent here are already filtered, so we don't need to do this
2030+ // if (skip_special_tokens && this.all_special_ids.includes(token)) {
2031+ // continue;
2032+ // }
2033+
2034+ if (this.added_tokens.find((x) => x.content === token) !== undefined) {
20112035 if (current_sub_text.length > 0) {
2012- sub_texts.push(this.convert_tokens_to_string(current_sub_text));
2036+ sub_texts.push(this.convert_tokens_to_string(current_sub_text));
2037+ current_sub_text = [];
20132038 }
2039+ sub_texts.push(token);
2040+ } else {
2041+ current_sub_text.push(token);
2042+ }
2043+ }
2044+ if (current_sub_text.length > 0) {
2045+ sub_texts.push(this.convert_tokens_to_string(current_sub_text));
2046+ }
20142047
2015- // TODO add spaces_between_special_tokens and clean_up_tokenization_spaces options
2048+ // TODO add spaces_between_special_tokens and clean_up_tokenization_spaces options
20162049
2017- return sub_texts;
2018- }
2050+ return sub_texts;
2051+ }
20192052 }
20202053
20212054 /**
@@ -2023,48 +2056,48 @@
20232056 * See https://github.com/huggingface/tokenizers/blob/bb38f390a61883fc2f29d659af696f428d1cda6b/tokenizers/src/decoders/ctc.rs
20242057 */
20252058 class CTCDecoder extends Decoder {
2059+ constructor(config) {
2060+ super(config);
2061+
2062+ this.pad_token = this.config.pad_token;
2063+ this.word_delimiter_token = this.config.word_delimiter_token;
2064+ this.cleanup = this.config.cleanup;
2065+ }
2066+ /**
2067+ * Converts a connectionist-temporal-classification (CTC) output tokens into a single string.
2068+ * @param {string[]} tokens Array of tokens to be decoded.
2069+ * @returns {string} The decoded string.
2070+ */
2071+ convert_tokens_to_string(tokens) {
2072+ if (tokens.length === 0) return "";
20262073
2027- constructor(config) {
2028- super(config);
2029-
2030- this.pad_token = this.config.pad_token;
2031- this.word_delimiter_token = this.config.word_delimiter_token;
2032- this.cleanup = this.config.cleanup;
2033- }
2034- /**
2035- * Converts a connectionist-temporal-classification (CTC) output tokens into a single string.
2036- * @param {string[]} tokens Array of tokens to be decoded.
2037- * @returns {string} The decoded string.
2038- */
2039- convert_tokens_to_string(tokens) {
2040- if (tokens.length === 0) return '';
2041-
2042- // group same tokens into non-repeating tokens in CTC style decoding
2043- const grouped_tokens = [tokens[0]];
2044- for (let i = 1; i < tokens.length; ++i) {
2045- if (tokens[i] !== grouped_tokens.at(-1)) {
2046- grouped_tokens.push(tokens[i]);
2047- }
2048- }
2049-
2050- // filter self.pad_token which is used as CTC-blank token
2051- const filtered_tokens = grouped_tokens.filter(token => token !== this.pad_token);
2052-
2053- let text = filtered_tokens.join('');
2054- if (this.cleanup) {
2055- // cleanup and replace delimiter token
2056- text = clean_up_tokenization(text)
2057- .replaceAll(this.word_delimiter_token, ' ')
2058- .trim();
2059- }
2060- return text;
2074+ // group same tokens into non-repeating tokens in CTC style decoding
2075+ const grouped_tokens = [tokens[0]];
2076+ for (let i = 1; i < tokens.length; ++i) {
2077+ if (tokens[i] !== grouped_tokens.at(-1)) {
2078+ grouped_tokens.push(tokens[i]);
2079+ }
20612080 }
20622081
2082+ // filter self.pad_token which is used as CTC-blank token
2083+ const filtered_tokens = grouped_tokens.filter(
2084+ (token) => token !== this.pad_token,
2085+ );
20632086
2064- /** @type {Decoder['decode_chain']} */
2065- decode_chain(tokens) {
2066- return [this.convert_tokens_to_string(tokens)];
2087+ let text = filtered_tokens.join("");
2088+ if (this.cleanup) {
2089+ // cleanup and replace delimiter token
2090+ text = clean_up_tokenization(text)
2091+ .replaceAll(this.word_delimiter_token, " ")
2092+ .trim();
20672093 }
2094+ return text;
2095+ }
2096+
2097+ /** @type {Decoder['decode_chain']} */
2098+ decode_chain(tokens) {
2099+ return [this.convert_tokens_to_string(tokens)];
2100+ }
20682101 }
20692102
20702103 /**
@@ -2072,108 +2105,100 @@
20722105 * @extends Decoder
20732106 */
20742107 class DecoderSequence extends Decoder {
2075-
2076- /**
2077- * Creates a new instance of DecoderSequence.
2078- * @param {Object} config The configuration object.
2079- * @param {Decoder[]} config.decoders The list of decoders to apply.
2080- */
2081- constructor(config) {
2082- super(config);
2083- this.decoders = config.decoders.map(x => Decoder.fromConfig(x));
2084- }
2085-
2086- /** @type {Decoder['decode_chain']} */
2087- decode_chain(tokens) {
2088- // Use reduce to apply each decoder to the tokens
2089- return this.decoders.reduce((toks, decoder) => {
2090- return decoder.decode_chain(toks);
2091- }, tokens);
2092- }
2093-
2108+ /**
2109+ * Creates a new instance of DecoderSequence.
2110+ * @param {Object} config The configuration object.
2111+ * @param {Decoder[]} config.decoders The list of decoders to apply.
2112+ */
2113+ constructor(config) {
2114+ super(config);
2115+ this.decoders = config.decoders.map((x) => Decoder.fromConfig(x));
2116+ }
2117+
2118+ /** @type {Decoder['decode_chain']} */
2119+ decode_chain(tokens) {
2120+ // Use reduce to apply each decoder to the tokens
2121+ return this.decoders.reduce((toks, decoder) => {
2122+ return decoder.decode_chain(toks);
2123+ }, tokens);
2124+ }
20942125 }
20952126
20962127 class BPEDecoder extends Decoder {
2097- constructor(config) {
2098- super(config);
2099-
2100- this.suffix = this.config.suffix;
2101- }
2102- /** @type {Decoder['decode_chain']} */
2103- decode_chain(tokens) {
2104- return tokens.map((token, i) => {
2105- return token.replaceAll(this.suffix, (i === tokens.length - 1) ? '' : ' ')
2106- });
2107- }
2128+ constructor(config) {
2129+ super(config);
2130+
2131+ this.suffix = this.config.suffix;
2132+ }
2133+ /** @type {Decoder['decode_chain']} */
2134+ decode_chain(tokens) {
2135+ return tokens.map((token, i) => {
2136+ return token.replaceAll(this.suffix, i === tokens.length - 1 ? "" : " ");
2137+ });
2138+ }
21082139 }
21092140
21102141 // Custom decoder for VITS
21112142 class VitsDecoder extends Decoder {
2112- /** @type {Decoder['decode_chain']} */
2113- decode_chain(tokens) {
2114- let decoded = '';
2115- for (let i = 1; i < tokens.length; i += 2) {
2116- decoded += tokens[i];
2117- }
2118- return [decoded];
2143+ /** @type {Decoder['decode_chain']} */
2144+ decode_chain(tokens) {
2145+ let decoded = "";
2146+ for (let i = 1; i < tokens.length; i += 2) {
2147+ decoded += tokens[i];
21192148 }
2149+ return [decoded];
2150+ }
21202151 }
21212152
2122-
21232153 /**
21242154 * This PreTokenizer replaces spaces with the given replacement character, adds a prefix space if requested,
21252155 * and returns a list of tokens.
21262156 * @extends PreTokenizer
21272157 */
21282158 class MetaspacePreTokenizer extends PreTokenizer {
2129- /**
2130- * @param {Object} config The configuration object for the MetaspacePreTokenizer.
2131- * @param {boolean} config.add_prefix_space Whether to add a prefix space to the first token.
2132- * @param {string} config.replacement The character to replace spaces with.
2133- * @param {string} [config.str_rep=config.replacement] An optional string representation of the replacement character.
2134- * @param {'first'|'never'|'always'} [config.prepend_scheme='always'] The metaspace prepending scheme.
2135- */
2136- constructor(config) {
2137- super();
2138-
2139- this.addPrefixSpace = config.add_prefix_space;
2140- this.replacement = config.replacement;
2141- this.strRep = config.str_rep || this.replacement;
2142- this.prepend_scheme = config.prepend_scheme ?? 'always';
2143- }
2144-
2145- /**
2146- * This method takes a string, replaces spaces with the replacement character,
2147- * adds a prefix space if requested, and returns a new list of tokens.
2148- * @param {string} text The text to pre-tokenize.
2149- * @param {Object} [options] The options for the pre-tokenization.
2150- * @param {number} [options.section_index] The index of the section to pre-tokenize.
2151- * @returns {string[]} A new list of pre-tokenized tokens.
2152- */
2153- pre_tokenize_text(text, {
2154- section_index = undefined,
2155- } = {}) {
2156-
2157- let normalized = text.replaceAll(' ', this.strRep);
2158-
2159- if (
2160- // We add a prefix space if:
2161- // (1) The addPrefixSpace option is enabled and the normalized
2162- // token does not already start with the replacement character.
2163- (this.addPrefixSpace && !normalized.startsWith(this.replacement))
2164-
2165- // and (2) either:
2166- // (a) prepend_scheme is 'always'
2167- // (b) prepend_scheme is 'first' and this is the first section
2168- && (
2169- this.prepend_scheme === 'always' ||
2170- (this.prepend_scheme === 'first' && section_index === 0)
2171- )
2172- ) {
2173- normalized = this.strRep + normalized;
2174- }
2175- return [normalized];
2159+ /**
2160+ * @param {Object} config The configuration object for the MetaspacePreTokenizer.
2161+ * @param {boolean} config.add_prefix_space Whether to add a prefix space to the first token.
2162+ * @param {string} config.replacement The character to replace spaces with.
2163+ * @param {string} [config.str_rep=config.replacement] An optional string representation of the replacement character.
2164+ * @param {'first'|'never'|'always'} [config.prepend_scheme='always'] The metaspace prepending scheme.
2165+ */
2166+ constructor(config) {
2167+ super();
2168+
2169+ this.addPrefixSpace = config.add_prefix_space;
2170+ this.replacement = config.replacement;
2171+ this.strRep = config.str_rep || this.replacement;
2172+ this.prepend_scheme = config.prepend_scheme ?? "always";
2173+ }
2174+
2175+ /**
2176+ * This method takes a string, replaces spaces with the replacement character,
2177+ * adds a prefix space if requested, and returns a new list of tokens.
2178+ * @param {string} text The text to pre-tokenize.
2179+ * @param {Object} [options] The options for the pre-tokenization.
2180+ * @param {number} [options.section_index] The index of the section to pre-tokenize.
2181+ * @returns {string[]} A new list of pre-tokenized tokens.
2182+ */
2183+ pre_tokenize_text(text, { section_index = undefined } = {}) {
2184+ let normalized = text.replaceAll(" ", this.strRep);
2185+
2186+ if (
2187+ // We add a prefix space if:
2188+ // (1) The addPrefixSpace option is enabled and the normalized
2189+ // token does not already start with the replacement character.
2190+ this.addPrefixSpace &&
2191+ !normalized.startsWith(this.replacement) &&
2192+ // and (2) either:
2193+ // (a) prepend_scheme is 'always'
2194+ // (b) prepend_scheme is 'first' and this is the first section
2195+ (this.prepend_scheme === "always" ||
2196+ (this.prepend_scheme === "first" && section_index === 0))
2197+ ) {
2198+ normalized = this.strRep + normalized;
21762199 }
2200+ return [normalized];
2201+ }
21772202 }
21782203
21792204 /**
@@ -2181,31 +2206,31 @@
21812206 * @extends Decoder
21822207 */
21832208 class MetaspaceDecoder extends Decoder {
2184- /**
2185- * Constructs a new MetaspaceDecoder object.
2186- * @param {Object} config The configuration object for the MetaspaceDecoder.
2187- * @param {boolean} config.add_prefix_space Whether to add a prefix space to the decoded string.
2188- * @param {string} config.replacement The string to replace spaces with.
2189- */
2190- constructor(config) {
2191- super(config);
2192-
2193- this.addPrefixSpace = config.add_prefix_space;
2194- this.replacement = config.replacement;
2195- }
2196-
2197- /** @type {Decoder['decode_chain']} */
2198- decode_chain(tokens) {
2199- const result = [];
2200- for (let i = 0; i < tokens.length; ++i) {
2201- let normalized = tokens[i].replaceAll(this.replacement, ' ');
2202- if (this.addPrefixSpace && i == 0 && normalized.startsWith(' ')) {
2203- normalized = normalized.substring(1);
2204- }
2205- result.push(normalized);
2206- }
2207- return result;
2209+ /**
2210+ * Constructs a new MetaspaceDecoder object.
2211+ * @param {Object} config The configuration object for the MetaspaceDecoder.
2212+ * @param {boolean} config.add_prefix_space Whether to add a prefix space to the decoded string.
2213+ * @param {string} config.replacement The string to replace spaces with.
2214+ */
2215+ constructor(config) {
2216+ super(config);
2217+
2218+ this.addPrefixSpace = config.add_prefix_space;
2219+ this.replacement = config.replacement;
2220+ }
2221+
2222+ /** @type {Decoder['decode_chain']} */
2223+ decode_chain(tokens) {
2224+ const result = [];
2225+ for (let i = 0; i < tokens.length; ++i) {
2226+ let normalized = tokens[i].replaceAll(this.replacement, " ");
2227+ if (this.addPrefixSpace && i == 0 && normalized.startsWith(" ")) {
2228+ normalized = normalized.substring(1);
2229+ }
2230+ result.push(normalized);
22082231 }
2232+ return result;
2233+ }
22092234 }
22102235
22112236 /**
@@ -2216,79 +2241,90 @@
22162241 * @param {Object} config.precompiled_charsmap The precompiled charsmap object.
22172242 */
22182243 class Precompiled extends Normalizer {
2219- /**
2220- * Create a new instance of Precompiled normalizer.
2221- * @param {Object} config The configuration object.
2222- * @param {any} config.precompiled_charsmap Precompiled chars mapping.
2223- */
2224- constructor(config) {
2225- super(config);
2226- this.charsmap = config.precompiled_charsmap;
2244+ /**
2245+ * Create a new instance of Precompiled normalizer.
2246+ * @param {Object} config The configuration object.
2247+ * @param {any} config.precompiled_charsmap Precompiled chars mapping.
2248+ */
2249+ constructor(config) {
2250+ super(config);
2251+ this.charsmap = config.precompiled_charsmap;
2252+ }
2253+
2254+ /**
2255+ * Normalizes the given text by applying the precompiled charsmap.
2256+ * @param {string} text The text to normalize.
2257+ * @returns {string} The normalized text.
2258+ */
2259+ normalize(text) {
2260+ // As stated in the sentencepiece normalization docs (https://github.com/google/sentencepiece/blob/master/doc/normalization.md#use-pre-defined-normalization-rule),
2261+ // there are 5 pre-defined normalization rules:
2262+ // 1. nmt_nfkc: NFKC normalization with some additional normalization around spaces. (default)
2263+ // 2. nfkc: original NFKC normalization.
2264+ // 3. nmt_nfkc_cf: nmt_nfkc + Unicode case folding (mostly lower casing)
2265+ // 4. nfkc_cf: nfkc + Unicode case folding.
2266+ // 5. identity: no normalization
2267+ //
2268+ // For now, we only implement the default (nmt_nfkc).
2269+ // See https://raw.githubusercontent.com/google/sentencepiece/master/data/nmt_nfkc.tsv for the full list of rules.
2270+ // TODO: detect when a different `this.charsmap` is used.
2271+
2272+ text = text.replace(
2273+ /[\u0001-\u0008\u000B\u000E-\u001F\u007F\u008F\u009F]/gm,
2274+ "",
2275+ ); // Remove control characters
2276+ text = text.replace(
2277+ /[\u0009\u000A\u000C\u000D\u1680\u200B\u200C\u200E\u200F\u2028\u2029\u2581\uFEFF\uFFFD]/gm,
2278+ "\u0020",
2279+ ); // Replace certain characters with a space
2280+
2281+ if (text.includes("\uFF5E")) {
2282+ // To match the sentencepiece implementation 100%, we must handle a very strange edge-case.
2283+ // For some reason, the "Fullwidth Tilde" character (\uFF5E) should not be converted to the standard Tilde character (\u007E).
2284+ // However, NFKC normalization does do this conversion. As a result, we split the string on the Fullwidth Tilde character,
2285+ // perform NFKC normalization on each substring, and then join them back together with the Fullwidth Tilde character.
2286+ const parts = text.split("\uFF5E");
2287+ text = parts.map((part) => part.normalize("NFKC")).join("\uFF5E");
2288+ } else {
2289+ text = text.normalize("NFKC");
22272290 }
22282291
2229- /**
2230- * Normalizes the given text by applying the precompiled charsmap.
2231- * @param {string} text The text to normalize.
2232- * @returns {string} The normalized text.
2233- */
2234- normalize(text) {
2235- // As stated in the sentencepiece normalization docs (https://github.com/google/sentencepiece/blob/master/doc/normalization.md#use-pre-defined-normalization-rule),
2236- // there are 5 pre-defined normalization rules:
2237- // 1. nmt_nfkc: NFKC normalization with some additional normalization around spaces. (default)
2238- // 2. nfkc: original NFKC normalization.
2239- // 3. nmt_nfkc_cf: nmt_nfkc + Unicode case folding (mostly lower casing)
2240- // 4. nfkc_cf: nfkc + Unicode case folding.
2241- // 5. identity: no normalization
2242- //
2243- // For now, we only implement the default (nmt_nfkc).
2244- // See https://raw.githubusercontent.com/google/sentencepiece/master/data/nmt_nfkc.tsv for the full list of rules.
2245- // TODO: detect when a different `this.charsmap` is used.
2246-
2247- text = text.replace(/[\u0001-\u0008\u000B\u000E-\u001F\u007F\u008F\u009F]/gm, ''); // Remove control characters
2248- text = text.replace(/[\u0009\u000A\u000C\u000D\u1680\u200B\u200C\u200E\u200F\u2028\u2029\u2581\uFEFF\uFFFD]/gm, '\u0020'); // Replace certain characters with a space
2249-
2250- if (text.includes('\uFF5E')) {
2251- // To match the sentencepiece implementation 100%, we must handle a very strange edge-case.
2252- // For some reason, the "Fullwidth Tilde" character (\uFF5E) should not be converted to the standard Tilde character (\u007E).
2253- // However, NFKC normalization does do this conversion. As a result, we split the string on the Fullwidth Tilde character,
2254- // perform NFKC normalization on each substring, and then join them back together with the Fullwidth Tilde character.
2255- const parts = text.split('\uFF5E');
2256- text = parts.map(part => part.normalize('NFKC')).join('\uFF5E');
2257- } else {
2258- text = text.normalize('NFKC');
2259- }
2260-
2261- return text;
2262- }
2263-}
2292+ return text;
2293+ }
2294+}
22642295
22652296 /**
22662297 * A pre-tokenizer that applies a sequence of pre-tokenizers to the input text.
22672298 * @extends PreTokenizer
22682299 */
22692300 class PreTokenizerSequence extends PreTokenizer {
2270- /**
2271- * Creates an instance of PreTokenizerSequence.
2272- * @param {Object} config The configuration object for the pre-tokenizer sequence.
2273- * @param {Object[]} config.pretokenizers An array of pre-tokenizer configurations.
2274- */
2275- constructor(config) {
2276- super();
2277- this.tokenizers = config.pretokenizers.map(x => PreTokenizer.fromConfig(x));
2278- }
2279-
2280- /**
2281- * Applies each pre-tokenizer in the sequence to the input text in turn.
2282- * @param {string} text The text to pre-tokenize.
2283- * @param {Object} [options] Additional options for the pre-tokenization logic.
2284- * @returns {string[]} The pre-tokenized text.
2285- */
2286- pre_tokenize_text(text, options) {
2287- // Use reduce to apply each tokenizer to the text
2288- return this.tokenizers.reduce((preTokenizedText, tokenizer) => {
2289- return tokenizer.pre_tokenize(preTokenizedText, options);
2290- }, [text]);
2291- }
2301+ /**
2302+ * Creates an instance of PreTokenizerSequence.
2303+ * @param {Object} config The configuration object for the pre-tokenizer sequence.
2304+ * @param {Object[]} config.pretokenizers An array of pre-tokenizer configurations.
2305+ */
2306+ constructor(config) {
2307+ super();
2308+ this.tokenizers = config.pretokenizers.map((x) =>
2309+ PreTokenizer.fromConfig(x),
2310+ );
2311+ }
2312+
2313+ /**
2314+ * Applies each pre-tokenizer in the sequence to the input text in turn.
2315+ * @param {string} text The text to pre-tokenize.
2316+ * @param {Object} [options] Additional options for the pre-tokenization logic.
2317+ * @returns {string[]} The pre-tokenized text.
2318+ */
2319+ pre_tokenize_text(text, options) {
2320+ // Use reduce to apply each tokenizer to the text
2321+ return this.tokenizers.reduce(
2322+ (preTokenizedText, tokenizer) => {
2323+ return tokenizer.pre_tokenize(preTokenizedText, options);
2324+ },
2325+ [text],
2326+ );
2327+ }
22922328 }
22932329
22942330 /**
@@ -2296,65 +2332,65 @@
22962332 * @extends PreTokenizer
22972333 */
22982334 class WhitespaceSplit extends PreTokenizer {
2299- /**
2300- * Creates an instance of WhitespaceSplit.
2301- * @param {Object} config The configuration object for the pre-tokenizer sequence.
2302- */
2303- constructor(config) {
2304- super();
2305- }
2306- /**
2307- * Pre-tokenizes the input text by splitting it on whitespace characters.
2308- * @param {string} text The text to be pre-tokenized.
2309- * @param {Object} [options] Additional options for the pre-tokenization logic.
2310- * @returns {string[]} An array of tokens produced by splitting the input text on whitespace.
2311- */
2312- pre_tokenize_text(text, options) {
2313- return whitespace_split(text);
2314- }
2335+ /**
2336+ * Creates an instance of WhitespaceSplit.
2337+ * @param {Object} config The configuration object for the pre-tokenizer sequence.
2338+ */
2339+ constructor(config) {
2340+ super();
2341+ }
2342+ /**
2343+ * Pre-tokenizes the input text by splitting it on whitespace characters.
2344+ * @param {string} text The text to be pre-tokenized.
2345+ * @param {Object} [options] Additional options for the pre-tokenization logic.
2346+ * @returns {string[]} An array of tokens produced by splitting the input text on whitespace.
2347+ */
2348+ pre_tokenize_text(text, options) {
2349+ return whitespace_split(text);
2350+ }
23152351 }
23162352
23172353 // NOTE: `ReplacePreTokenizer` is custom (to support `BlenderbotSmallTokenizer`)
23182354 class ReplacePreTokenizer extends PreTokenizer {
2319- /**
2320- * @param {Object} config The configuration options for the pre-tokenizer.
2321- * @param {Object} config.pattern The pattern used to split the text. Can be a string or a regex object.
2322- * @param {string} config.content What to replace the pattern with.
2323- */
2324- constructor(config) {
2325- super();
2326- this.config = config;
2327- this.pattern = createPattern(this.config.pattern);
2328- this.content = this.config.content;
2329- }
2330-
2331- /**
2332- * Pre-tokenizes the input text by replacing certain characters.
2333- * @param {string} text The text to be pre-tokenized.
2334- * @param {Object} [options] Additional options for the pre-tokenization logic.
2335- * @returns {string[]} An array of tokens produced by replacing certain characters.
2336- */
2337- pre_tokenize_text(text, options) {
2338- if (this.pattern === null) {
2339- return [text];
2340- }
2341- return [text.replaceAll(this.pattern, this.config.content)];
2355+ /**
2356+ * @param {Object} config The configuration options for the pre-tokenizer.
2357+ * @param {Object} config.pattern The pattern used to split the text. Can be a string or a regex object.
2358+ * @param {string} config.content What to replace the pattern with.
2359+ */
2360+ constructor(config) {
2361+ super();
2362+ this.config = config;
2363+ this.pattern = createPattern(this.config.pattern);
2364+ this.content = this.config.content;
2365+ }
2366+
2367+ /**
2368+ * Pre-tokenizes the input text by replacing certain characters.
2369+ * @param {string} text The text to be pre-tokenized.
2370+ * @param {Object} [options] Additional options for the pre-tokenization logic.
2371+ * @returns {string[]} An array of tokens produced by replacing certain characters.
2372+ */
2373+ pre_tokenize_text(text, options) {
2374+ if (this.pattern === null) {
2375+ return [text];
23422376 }
2377+ return [text.replaceAll(this.pattern, this.config.content)];
2378+ }
23432379 }
23442380
23452381 const SPECIAL_TOKEN_ATTRIBUTES = [
2346- 'bos_token',
2347- 'eos_token',
2348- 'unk_token',
2349- 'sep_token',
2350- 'pad_token',
2351- 'cls_token',
2352- 'mask_token',
2353- // additional_special_tokens (TODO)
2354-]
2355-
2356-/**
2357- *
2382+ "bos_token",
2383+ "eos_token",
2384+ "unk_token",
2385+ "sep_token",
2386+ "pad_token",
2387+ "cls_token",
2388+ "mask_token",
2389+ // additional_special_tokens (TODO)
2390+];
2391+
2392+/**
2393+ *
23582394 * Helper function for padding values of an object, which are each arrays.
23592395 * NOTE: No additional checks are made here for validity of arguments.
23602396 * @param {Record<string, any[]>} item The input object.
@@ -2364,15 +2400,16 @@
23642400 * @private
23652401 */
23662402 function padHelper(item, length, value_fn, side) {
2367- for (const key of Object.keys(item)) {
2368- const diff = length - item[key].length;
2369- const value = value_fn(key);
2403+ for (const key of Object.keys(item)) {
2404+ const diff = length - item[key].length;
2405+ const value = value_fn(key);
23702406
2371- const padData = new Array(diff).fill(value);
2372- item[key] = side === 'right'
2373- ? mergeArrays(item[key], padData)
2374- : mergeArrays(padData, item[key]);
2375- }
2407+ const padData = new Array(diff).fill(value);
2408+ item[key] =
2409+ side === "right"
2410+ ? mergeArrays(item[key], padData)
2411+ : mergeArrays(padData, item[key]);
2412+ }
23762413 }
23772414
23782415 /**
@@ -2383,465 +2420,426 @@
23832420 * @private
23842421 */
23852422 function truncateHelper(item, length) {
2386- // Setting .length to a lower value truncates the array in-place:
2387- // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/length
2388- for (const key of Object.keys(item)) {
2389- item[key].length = length;
2390- }
2423+ // Setting .length to a lower value truncates the array in-place:
2424+ // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/length
2425+ for (const key of Object.keys(item)) {
2426+ item[key].length = length;
2427+ }
23912428 }
23922429
2393-
23942430 export class PreTrainedTokenizer extends Callable {
2395- return_token_type_ids = false;
2396-
2397- _default_chat_template = `{% for message in messages %}{{'<|im_start|>' + message['role'] + '\n' + message['content'] + '<|im_end|>' + '\n'}}{% endfor %}{% if add_generation_prompt %}{{ '<|im_start|>assistant\n' }}{% endif %}`;
2398-
2399- /**
2400- * Create a new PreTrainedTokenizer instance.
2401- * @param {Object} tokenizerJSON The JSON of the tokenizer.
2402- * @param {Object} tokenizerConfig The config of the tokenizer.
2403- */
2404- constructor(tokenizerJSON, tokenizerConfig) {
2405- super();
2406-
2407- this._tokenizer_config = tokenizerConfig;
2408-
2409- // Construct parts of the tokenizer from the JSON
2410- this.normalizer = Normalizer.fromConfig(tokenizerJSON.normalizer);
2411- this.pre_tokenizer = PreTokenizer.fromConfig(tokenizerJSON.pre_tokenizer);
2412- this.model = TokenizerModel.fromConfig(tokenizerJSON.model, tokenizerConfig);
2413- this.post_processor = PostProcessor.fromConfig(tokenizerJSON.post_processor);
2414- this.decoder = Decoder.fromConfig(tokenizerJSON.decoder);
2415-
2416- // Add added_tokens to model
2417- this.special_tokens = [];
2418- this.all_special_ids = [];
2419-
2420- /** @type {AddedToken[]} */
2421- this.added_tokens = [];
2422- for (const addedToken of tokenizerJSON.added_tokens) {
2423- const token = new AddedToken(addedToken);
2424- this.added_tokens.push(token);
2425-
2426- this.model.tokens_to_ids.set(token.content, token.id);
2427- this.model.vocab[token.id] = token.content;
2428-
2429- if (token.special) {
2430- this.special_tokens.push(token.content);
2431- this.all_special_ids.push(token.id);
2432- }
2433- }
2434-
2435- // Update additional_special_tokens
2436- this.additional_special_tokens = tokenizerConfig.additional_special_tokens ?? [];
2437- this.special_tokens.push(...this.additional_special_tokens);
2438- this.special_tokens = [...new Set(this.special_tokens)]; // Remove duplicates
2439-
2440- if (this.decoder) {
2441- // Slight hack, but it prevents code duplication:
2442- this.decoder.added_tokens = this.added_tokens;
2443-
2444- // Another slight hack to add `end_of_word_suffix` (if present) to the decoder
2445- // This is needed for cases where BPE model and ByteLevel decoder are used
2446- // For more information, see https://github.com/xenova/transformers.js/issues/74
2447- // TODO: save this to the decoder when exporting?
2448- this.decoder.end_of_word_suffix = this.model.end_of_word_suffix;
2449- }
2450-
2451-
2452- this.added_tokens_regex = this.added_tokens.length > 0 ? new RegExp(
2453- this.added_tokens.map(x => `${x.lstrip ? '\\s*' : ''}(${escapeRegExp(x.content)})${x.rstrip ? '\\s*' : ''}`).join('|')
2454- ) : null;
2455-
2456- // Set mask token if present (otherwise will be undefined, which is fine)
2457- this.mask_token = this.getToken('mask_token');
2458- this.mask_token_id = this.model.tokens_to_ids.get(this.mask_token);
2459-
2460- this.pad_token = this.getToken('pad_token', 'eos_token');
2461- this.pad_token_id = this.model.tokens_to_ids.get(this.pad_token);
2462-
2463- this.sep_token = this.getToken('sep_token');
2464- this.sep_token_id = this.model.tokens_to_ids.get(this.sep_token);
2465-
2466- this.unk_token = this.getToken(tokenizerConfig, 'unk_token');
2467- this.unk_token_id = this.model.tokens_to_ids.get(this.unk_token);
2468-
2469- this.model_max_length = tokenizerConfig.model_max_length;
2470-
2471- /** @type {boolean} Whether or not to strip the text when tokenizing (removing excess spaces before and after the string). */
2472- this.remove_space = tokenizerConfig.remove_space;
2473-
2474- this.clean_up_tokenization_spaces = tokenizerConfig.clean_up_tokenization_spaces ?? true;
2475- this.do_lowercase_and_remove_accent = tokenizerConfig.do_lowercase_and_remove_accent ?? false;
2476-
2477- // TODO allow user to change this
2478- /** @type {'right'|'left'} */
2479- this.padding_side = 'right';
2480-
2481- this.legacy = false;
2482-
2483- this.chat_template = tokenizerConfig.chat_template ?? null;
2484- this._compiled_template_cache = new Map();
2485- }
2486-
2487- /**
2488- * Returns the value of the first matching key in the tokenizer config object.
2489- * @param {...string} keys One or more keys to search for in the tokenizer config object.
2490- * @returns {string|null} The value associated with the first matching key, or null if no match is found.
2491- * @throws {Error} If an object is found for a matching key and its __type property is not "AddedToken".
2492- */
2493- getToken(...keys) {
2494- for (const key of keys) {
2495- const item = this._tokenizer_config[key];
2496-
2497- if (!item) continue;
2498-
2499- if (typeof item === 'object') {
2500- if (item.__type === 'AddedToken') {
2501- return item.content;
2502- } else {
2503- throw Error(`Unknown token: ${item}`);
2504- }
2505- } else {
2506- return item;
2507- }
2508- }
2509- return null;
2510- }
2511-
2512- /**
2513- * Loads a pre-trained tokenizer from the given `pretrained_model_name_or_path`.
2514- *
2515- * @param {string} pretrained_model_name_or_path The path to the pre-trained tokenizer.
2516- * @param {PretrainedTokenizerOptions} options Additional options for loading the tokenizer.
2517- *
2518- * @throws {Error} Throws an error if the tokenizer.json or tokenizer_config.json files are not found in the `pretrained_model_name_or_path`.
2519- * @returns {Promise<PreTrainedTokenizer>} A new instance of the `PreTrainedTokenizer` class.
2520- */
2521- static async from_pretrained(pretrained_model_name_or_path, {
2522- progress_callback = null,
2523- config = null,
2524- cache_dir = null,
2525- local_files_only = false,
2526- revision = 'main',
2527- legacy = null,
2528- } = {}) {
2529-
2530- const info = await loadTokenizer(pretrained_model_name_or_path, {
2531- progress_callback,
2532- config,
2533- cache_dir,
2534- local_files_only,
2535- revision,
2536- legacy,
2537- })
2538-
2539- // @ts-ignore
2540- return new this(...info);
2541- }
2542-
2543- /**
2544- * @typedef {number[]|number[][]|Tensor} BatchEncodingItem
2545- *
2546- * @typedef {Object} BatchEncoding Holds the output of the tokenizer's call function.
2547- * @property {BatchEncodingItem} input_ids List of token ids to be fed to a model.
2548- * @property {BatchEncodingItem} attention_mask List of indices specifying which tokens should be attended to by the model.
2549- * @property {BatchEncodingItem} [token_type_ids] List of token type ids to be fed to a model.
2550- */
2551-
2552- /**
2553- * Encode/tokenize the given text(s).
2554- * @param {string|string[]} text The text to tokenize.
2555- * @param {Object} options An optional object containing the following properties:
2556- * @param {string|string[]} [options.text_pair=null] Optional second sequence to be encoded. If set, must be the same type as text.
2557- * @param {boolean|'max_length'} [options.padding=false] Whether to pad the input sequences.
2558- * @param {boolean} [options.add_special_tokens=true] Whether or not to add the special tokens associated with the corresponding model.
2559- * @param {boolean} [options.truncation=null] Whether to truncate the input sequences.
2560- * @param {number} [options.max_length=null] Maximum length of the returned list and optionally padding length.
2561- * @param {boolean} [options.return_tensor=true] Whether to return the results as Tensors or arrays.
2562- * @returns {BatchEncoding} Object to be passed to the model.
2563- */
2564- _call(
2565- // Required positional arguments
2566- text,
2567-
2568- // Optional keyword arguments
2569- {
2570- text_pair = null,
2571- add_special_tokens = true,
2572- padding = false,
2573- truncation = null,
2574- max_length = null,
2575- return_tensor = true, // Different to HF
2576- } = {},
2577- ) {
2578-
2579- const isBatched = Array.isArray(text);
2580-
2581- /** @type {EncodingSingle[]} */
2582- let encodedTokens;
2583-
2584- if (isBatched) {
2585- if (text.length === 0) {
2586- throw Error('text array must be non-empty')
2587- }
2588-
2589- if (text_pair !== null) {
2590- if (!Array.isArray(text_pair)) {
2591- throw Error('text_pair must also be an array')
2592-
2593- } else if (text.length !== text_pair.length) {
2594- throw Error('text and text_pair must have the same length')
2595- }
2596-
2597- encodedTokens = text.map(
2598- (t, i) => this._encode_plus(t, text_pair[i], { add_special_tokens })
2599- )
2431+ return_token_type_ids = false;
26002432
2601- } else {
2602- encodedTokens = text.map(x => this._encode_plus(x, null, { add_special_tokens }));
2603- }
2604-
2605- } else {
2606- if (text === null) {
2607- throw Error('text may not be null')
2608- }
2609-
2610- if (Array.isArray(text_pair)) {
2611- throw Error('When specifying `text_pair`, since `text` is a string, `text_pair` must also be a string (i.e., not an array).')
2612- }
2613-
2614- // For single input, we just wrap in an array, and then unwrap later.
2615- encodedTokens = [this._encode_plus(text, text_pair, { add_special_tokens })];
2616- }
2617- // At this point, tokens is batched: [batch_size, tokens]
2618- // However, array may be jagged. So, we pad to max_length
2619-
2620- if (max_length === null) {
2621- if (padding === 'max_length') {
2622- max_length = this.model_max_length;
2623- } else {
2624- // Calculate max length from sequences
2625- max_length = max(encodedTokens.map(x => x.input_ids.length))[0];
2626- }
2627- } else {
2628- if (!truncation) {
2629- console.warn(`Truncation was not explicitly activated but \`max_length\` is provided a specific value, please use \`truncation=true\` to explicitly truncate examples to max length.`)
2630- }
2631- }
2632-
2633- // Ensure it is less than model max length
2634- max_length = Math.min(max_length, this.model_max_length)
2635-
2636- if (padding || truncation) {
2637-
2638- // Perform padding and/or truncation
2639- for (let i = 0; i < encodedTokens.length; ++i) {
2640- if (encodedTokens[i].input_ids.length === max_length) {
2641- continue;
2642-
2643- } else if (encodedTokens[i].input_ids.length > max_length) {
2644- // possibly truncate
2645- if (truncation) {
2646- truncateHelper(encodedTokens[i], max_length);
2647- }
2648-
2649- } else { // t.length < max_length
2650- // possibly pad
2651- if (padding) {
2652- padHelper(
2653- encodedTokens[i],
2654- max_length,
2655- key => key === 'input_ids' ? this.pad_token_id : 0,
2656- this.padding_side
2657- );
2658- }
2659- }
2660- }
2661- }
2662-
2663- const result = {};
2664-
2665- if (return_tensor) {
2666- if (!(padding && truncation)) {
2667- // Not, guaranteed that all items have same length, so
2668- // we perform additional check
2669-
2670- if (
2671- encodedTokens.some(x => {
2672- for (const key of Object.keys(x)) {
2673- if (x[key].length !== encodedTokens[0][key]?.length) {
2674- return true;
2675- }
2676- }
2677- return false;
2678- })
2679- ) {
2680- throw Error(
2681- "Unable to create tensor, you should probably activate truncation and/or padding " +
2682- "with 'padding=true' and 'truncation=true' to have batched tensors with the same length."
2683- )
2684- }
2685- }
2686-
2687- // Now we actually convert to tensor
2688- // NOTE: In the same way as the python library, we return a batched tensor, regardless of
2689- // whether we have a single input or multiple inputs.
2690- const dims = [encodedTokens.length, encodedTokens[0].input_ids.length];
2691-
2692- for (const key of Object.keys(encodedTokens[0])) {
2693- result[key] = new Tensor('int64',
2694- BigInt64Array.from(encodedTokens.flatMap(x => x[key]).map(BigInt)),
2695- dims
2696- );
2697- }
2433+ _default_chat_template = `{% for message in messages %}{{'<|im_start|>' + message['role'] + '\n' + message['content'] + '<|im_end|>' + '\n'}}{% endfor %}{% if add_generation_prompt %}{{ '<|im_start|>assistant\n' }}{% endif %}`;
26982434
2435+ /**
2436+ * Create a new PreTrainedTokenizer instance.
2437+ * @param {Object} tokenizerJSON The JSON of the tokenizer.
2438+ * @param {Object} tokenizerConfig The config of the tokenizer.
2439+ */
2440+ constructor(tokenizerJSON, tokenizerConfig) {
2441+ super();
2442+
2443+ this._tokenizer_config = tokenizerConfig;
2444+
2445+ // Construct parts of the tokenizer from the JSON
2446+ this.normalizer = Normalizer.fromConfig(tokenizerJSON.normalizer);
2447+ this.pre_tokenizer = PreTokenizer.fromConfig(tokenizerJSON.pre_tokenizer);
2448+ this.model = TokenizerModel.fromConfig(
2449+ tokenizerJSON.model,
2450+ tokenizerConfig,
2451+ );
2452+ this.post_processor = PostProcessor.fromConfig(
2453+ tokenizerJSON.post_processor,
2454+ );
2455+ this.decoder = Decoder.fromConfig(tokenizerJSON.decoder);
2456+
2457+ // Add added_tokens to model
2458+ this.special_tokens = [];
2459+ this.all_special_ids = [];
2460+
2461+ /** @type {AddedToken[]} */
2462+ this.added_tokens = [];
2463+ for (const addedToken of tokenizerJSON.added_tokens) {
2464+ const token = new AddedToken(addedToken);
2465+ this.added_tokens.push(token);
2466+
2467+ this.model.tokens_to_ids.set(token.content, token.id);
2468+ this.model.vocab[token.id] = token.content;
2469+
2470+ if (token.special) {
2471+ this.special_tokens.push(token.content);
2472+ this.all_special_ids.push(token.id);
2473+ }
2474+ }
2475+
2476+ // Update additional_special_tokens
2477+ this.additional_special_tokens =
2478+ tokenizerConfig.additional_special_tokens ?? [];
2479+ this.special_tokens.push(...this.additional_special_tokens);
2480+ this.special_tokens = [...new Set(this.special_tokens)]; // Remove duplicates
2481+
2482+ if (this.decoder) {
2483+ // Slight hack, but it prevents code duplication:
2484+ this.decoder.added_tokens = this.added_tokens;
2485+
2486+ // Another slight hack to add `end_of_word_suffix` (if present) to the decoder
2487+ // This is needed for cases where BPE model and ByteLevel decoder are used
2488+ // For more information, see https://github.com/xenova/transformers.js/issues/74
2489+ // TODO: save this to the decoder when exporting?
2490+ this.decoder.end_of_word_suffix = this.model.end_of_word_suffix;
2491+ }
2492+
2493+ this.added_tokens_regex =
2494+ this.added_tokens.length > 0
2495+ ? new RegExp(
2496+ this.added_tokens
2497+ .map(
2498+ (x) =>
2499+ `${x.lstrip ? "\\s*" : ""}(${escapeRegExp(x.content)})${x.rstrip ? "\\s*" : ""}`,
2500+ )
2501+ .join("|"),
2502+ )
2503+ : null;
2504+
2505+ // Set mask token if present (otherwise will be undefined, which is fine)
2506+ this.mask_token = this.getToken("mask_token");
2507+ this.mask_token_id = this.model.tokens_to_ids.get(this.mask_token);
2508+
2509+ this.pad_token = this.getToken("pad_token", "eos_token");
2510+ this.pad_token_id = this.model.tokens_to_ids.get(this.pad_token);
2511+
2512+ this.sep_token = this.getToken("sep_token");
2513+ this.sep_token_id = this.model.tokens_to_ids.get(this.sep_token);
2514+
2515+ this.unk_token = this.getToken(tokenizerConfig, "unk_token");
2516+ this.unk_token_id = this.model.tokens_to_ids.get(this.unk_token);
2517+
2518+ this.model_max_length = tokenizerConfig.model_max_length;
2519+
2520+ /** @type {boolean} Whether or not to strip the text when tokenizing (removing excess spaces before and after the string). */
2521+ this.remove_space = tokenizerConfig.remove_space;
2522+
2523+ this.clean_up_tokenization_spaces =
2524+ tokenizerConfig.clean_up_tokenization_spaces ?? true;
2525+ this.do_lowercase_and_remove_accent =
2526+ tokenizerConfig.do_lowercase_and_remove_accent ?? false;
2527+
2528+ // TODO allow user to change this
2529+ /** @type {'right'|'left'} */
2530+ this.padding_side = "right";
2531+
2532+ this.legacy = false;
2533+
2534+ this.chat_template = tokenizerConfig.chat_template ?? null;
2535+ this._compiled_template_cache = new Map();
2536+ }
2537+
2538+ /**
2539+ * Returns the value of the first matching key in the tokenizer config object.
2540+ * @param {...string} keys One or more keys to search for in the tokenizer config object.
2541+ * @returns {string|null} The value associated with the first matching key, or null if no match is found.
2542+ * @throws {Error} If an object is found for a matching key and its __type property is not "AddedToken".
2543+ */
2544+ getToken(...keys) {
2545+ for (const key of keys) {
2546+ const item = this._tokenizer_config[key];
2547+
2548+ if (!item) continue;
2549+
2550+ if (typeof item === "object") {
2551+ if (item.__type === "AddedToken") {
2552+ return item.content;
26992553 } else {
2700- for (const key of Object.keys(encodedTokens[0])) {
2701- result[key] = encodedTokens.map(x => x[key]);
2702- }
2703-
2704- // If not returning a tensor, we match the input type
2705- if (!isBatched) {
2706- // Input was not batched, so we unwrap
2707- for (const key of Object.keys(result)) {
2708- result[key] = result[key][0];
2709- }
2710- }
2554+ throw Error(`Unknown token: ${item}`);
27112555 }
2712-
2713- return /** @type {BatchEncoding} */(result);
2556+ } else {
2557+ return item;
2558+ }
27142559 }
2560+ return null;
2561+ }
27152562
2716- /**
2717- * Encodes a single text using the preprocessor pipeline of the tokenizer.
2718- *
2719- * @param {string|null} text The text to encode.
2720- * @returns {string[]|null} The encoded tokens.
2721- */
2722- _encode_text(text) {
2723- if (text === null) return null;
2724-
2725- // Actual function which does encoding, for a single text
2726- // First, we take care of special tokens. Needed to avoid issues arising from
2727- // normalization and/or pretokenization (which may not preserve special tokens)
2728- const sections = this.added_tokens_regex ? text.split(this.added_tokens_regex).filter(x => x) : [text];
2729-
2730- const tokens = sections.map((x, section_index) => {
2731- const addedToken = this.added_tokens.find(t => t.content === x);
2732- if (addedToken !== undefined) {
2733- // Ignore added tokens
2734- return x
2735- } else {
2736- if (this.remove_space === true) {
2737- x = x.trim().split(/\s+/).join(' ');
2738- }
2739- if (this.do_lowercase_and_remove_accent) {
2740- x = lowercase_and_remove_accent(x);
2741- }
2742-
2743- if (this.normalizer !== null) {
2744- x = this.normalizer(x);
2745- }
2746-
2747- const sectionTokens = (this.pre_tokenizer !== null) ? this.pre_tokenizer(x, {
2748- section_index,
2749- }) : [x];
2750-
2751- const tokens = this.model(sectionTokens);
2752-
2753- return tokens;
2754- }
2755- }).flat();
2756-
2757- return tokens;
2758- }
2563+ /**
2564+ * Loads a pre-trained tokenizer from the given `pretrained_model_name_or_path`.
2565+ *
2566+ * @param {string} pretrained_model_name_or_path The path to the pre-trained tokenizer.
2567+ * @param {PretrainedTokenizerOptions} options Additional options for loading the tokenizer.
2568+ *
2569+ * @throws {Error} Throws an error if the tokenizer.json or tokenizer_config.json files are not found in the `pretrained_model_name_or_path`.
2570+ * @returns {Promise<PreTrainedTokenizer>} A new instance of the `PreTrainedTokenizer` class.
2571+ */
2572+ static async from_pretrained(
2573+ pretrained_model_name_or_path,
2574+ {
2575+ progress_callback = null,
2576+ config = null,
2577+ cache_dir = null,
2578+ local_files_only = false,
2579+ revision = "main",
2580+ legacy = null,
2581+ } = {},
2582+ ) {
2583+ const info = await loadTokenizer(pretrained_model_name_or_path, {
2584+ progress_callback,
2585+ config,
2586+ cache_dir,
2587+ local_files_only,
2588+ revision,
2589+ legacy,
2590+ });
2591+
2592+ // @ts-ignore
2593+ return new this(...info);
2594+ }
2595+
2596+ /**
2597+ * @typedef {number[]|number[][]|Tensor} BatchEncodingItem
2598+ *
2599+ * @typedef {Object} BatchEncoding Holds the output of the tokenizer's call function.
2600+ * @property {BatchEncodingItem} input_ids List of token ids to be fed to a model.
2601+ * @property {BatchEncodingItem} attention_mask List of indices specifying which tokens should be attended to by the model.
2602+ * @property {BatchEncodingItem} [token_type_ids] List of token type ids to be fed to a model.
2603+ */
27592604
2760- /**
2761- * Encodes a single text or a pair of texts using the model's tokenizer.
2762- *
2763- * @param {string} text The text to encode.
2764- * @param {string|null} text_pair The optional second text to encode.
2765- * @param {Object} options An optional object containing the following properties:
2766- * @param {boolean} [options.add_special_tokens=true] Whether or not to add the special tokens associated with the corresponding model.
2767- * @returns {EncodingSingle} An object containing the encoded text.
2768- * @private
2769- */
2770- _encode_plus(text, text_pair = null, {
2771- add_special_tokens = true,
2772- } = {}) {
2773- // Function called by users to encode possibly multiple texts
2774- const tokens = this._encode_text(text);
2775- const tokens2 = this._encode_text(text_pair);
2776-
2777- const combinedTokens = this.post_processor
2778- ? this.post_processor(tokens, tokens2, { add_special_tokens })
2779- : { tokens: mergeArrays(tokens ?? [], tokens2 ?? []) };
2780-
2781- const input_ids = this.model.convert_tokens_to_ids(combinedTokens.tokens);
2782-
2783- const result = {
2784- input_ids,
2785- attention_mask: new Array(input_ids.length).fill(1),
2786- }
2787- if (this.return_token_type_ids && combinedTokens.token_type_ids) {
2788- result.token_type_ids = combinedTokens.token_type_ids;
2789- }
2790- return result;
2791- }
2605+ /**
2606+ * Encode/tokenize the given text(s).
2607+ * @param {string|string[]} text The text to tokenize.
2608+ * @param {Object} options An optional object containing the following properties:
2609+ * @param {string|string[]} [options.text_pair=null] Optional second sequence to be encoded. If set, must be the same type as text.
2610+ * @param {boolean|'max_length'} [options.padding=false] Whether to pad the input sequences.
2611+ * @param {boolean} [options.add_special_tokens=true] Whether or not to add the special tokens associated with the corresponding model.
2612+ * @param {boolean} [options.truncation=null] Whether to truncate the input sequences.
2613+ * @param {number} [options.max_length=null] Maximum length of the returned list and optionally padding length.
2614+ * @param {boolean} [options.return_tensor=true] Whether to return the results as Tensors or arrays.
2615+ * @returns {BatchEncoding} Object to be passed to the model.
2616+ */
2617+ _call(
2618+ // Required positional arguments
2619+ text,
2620+
2621+ // Optional keyword arguments
2622+ {
2623+ text_pair = null,
2624+ add_special_tokens = true,
2625+ padding = false,
2626+ truncation = null,
2627+ max_length = null,
2628+ return_tensor = true, // Different to HF
2629+ } = {},
2630+ ) {
2631+ const isBatched = Array.isArray(text);
2632+
2633+ /** @type {EncodingSingle[]} */
2634+ let encodedTokens;
2635+
2636+ if (isBatched) {
2637+ if (text.length === 0) {
2638+ throw Error("text array must be non-empty");
2639+ }
2640+
2641+ if (text_pair !== null) {
2642+ if (!Array.isArray(text_pair)) {
2643+ throw Error("text_pair must also be an array");
2644+ } else if (text.length !== text_pair.length) {
2645+ throw Error("text and text_pair must have the same length");
2646+ }
2647+
2648+ encodedTokens = text.map((t, i) =>
2649+ this._encode_plus(t, text_pair[i], { add_special_tokens }),
2650+ );
2651+ } else {
2652+ encodedTokens = text.map((x) =>
2653+ this._encode_plus(x, null, { add_special_tokens }),
2654+ );
2655+ }
2656+ } else {
2657+ if (text === null) {
2658+ throw Error("text may not be null");
2659+ }
2660+
2661+ if (Array.isArray(text_pair)) {
2662+ throw Error(
2663+ "When specifying `text_pair`, since `text` is a string, `text_pair` must also be a string (i.e., not an array).",
2664+ );
2665+ }
2666+
2667+ // For single input, we just wrap in an array, and then unwrap later.
2668+ encodedTokens = [
2669+ this._encode_plus(text, text_pair, { add_special_tokens }),
2670+ ];
2671+ }
2672+ // At this point, tokens is batched: [batch_size, tokens]
2673+ // However, array may be jagged. So, we pad to max_length
2674+
2675+ if (max_length === null) {
2676+ if (padding === "max_length") {
2677+ max_length = this.model_max_length;
2678+ } else {
2679+ // Calculate max length from sequences
2680+ max_length = max(encodedTokens.map((x) => x.input_ids.length))[0];
2681+ }
2682+ } else {
2683+ if (!truncation) {
2684+ console.warn(
2685+ `Truncation was not explicitly activated but \`max_length\` is provided a specific value, please use \`truncation=true\` to explicitly truncate examples to max length.`,
2686+ );
2687+ }
2688+ }
2689+
2690+ // Ensure it is less than model max length
2691+ max_length = Math.min(max_length, this.model_max_length);
2692+
2693+ if (padding || truncation) {
2694+ // Perform padding and/or truncation
2695+ for (let i = 0; i < encodedTokens.length; ++i) {
2696+ if (encodedTokens[i].input_ids.length === max_length) {
2697+ continue;
2698+ } else if (encodedTokens[i].input_ids.length > max_length) {
2699+ // possibly truncate
2700+ if (truncation) {
2701+ truncateHelper(encodedTokens[i], max_length);
2702+ }
2703+ } else {
2704+ // t.length < max_length
2705+ // possibly pad
2706+ if (padding) {
2707+ padHelper(
2708+ encodedTokens[i],
2709+ max_length,
2710+ (key) => (key === "input_ids" ? this.pad_token_id : 0),
2711+ this.padding_side,
2712+ );
2713+ }
2714+ }
2715+ }
2716+ }
2717+
2718+ const result = {};
2719+
2720+ if (return_tensor) {
2721+ if (!(padding && truncation)) {
2722+ // Not, guaranteed that all items have same length, so
2723+ // we perform additional check
27922724
2793- /**
2794- * Encodes a single text or a pair of texts using the model's tokenizer.
2795- *
2796- * @param {string} text The text to encode.
2797- * @param {string|null} text_pair The optional second text to encode.
2798- * @param {Object} options An optional object containing the following properties:
2799- * @param {boolean} [options.add_special_tokens=true] Whether or not to add the special tokens associated with the corresponding model.
2800- * @returns {number[]} An array of token IDs representing the encoded text(s).
2801- */
2802- encode(text, text_pair = null, {
2803- add_special_tokens = true,
2804- } = {}) {
2805- const { input_ids } = this._encode_plus(text, text_pair, {
2806- add_special_tokens,
2807- });
2808- return input_ids;
2809- }
2725+ if (
2726+ encodedTokens.some((x) => {
2727+ for (const key of Object.keys(x)) {
2728+ if (x[key].length !== encodedTokens[0][key]?.length) {
2729+ return true;
2730+ }
2731+ }
2732+ return false;
2733+ })
2734+ ) {
2735+ throw Error(
2736+ "Unable to create tensor, you should probably activate truncation and/or padding " +
2737+ "with 'padding=true' and 'truncation=true' to have batched tensors with the same length.",
2738+ );
2739+ }
2740+ }
2741+
2742+ // Now we actually convert to tensor
2743+ // NOTE: In the same way as the python library, we return a batched tensor, regardless of
2744+ // whether we have a single input or multiple inputs.
2745+ const dims = [encodedTokens.length, encodedTokens[0].input_ids.length];
2746+
2747+ for (const key of Object.keys(encodedTokens[0])) {
2748+ result[key] = new Tensor(
2749+ "int64",
2750+ BigInt64Array.from(encodedTokens.flatMap((x) => x[key]).map(BigInt)),
2751+ dims,
2752+ );
2753+ }
2754+ } else {
2755+ for (const key of Object.keys(encodedTokens[0])) {
2756+ result[key] = encodedTokens.map((x) => x[key]);
2757+ }
28102758
2811- /**
2812- * Decode a batch of tokenized sequences.
2813- * @param {number[][]|Tensor} batch List/Tensor of tokenized input sequences.
2814- * @param {Object} decode_args (Optional) Object with decoding arguments.
2815- * @returns {string[]} List of decoded sequences.
2816- */
2817- batch_decode(batch, decode_args = {}) {
2818- if (batch instanceof Tensor) {
2819- batch = batch.tolist();
2759+ // If not returning a tensor, we match the input type
2760+ if (!isBatched) {
2761+ // Input was not batched, so we unwrap
2762+ for (const key of Object.keys(result)) {
2763+ result[key] = result[key][0];
28202764 }
2821- return batch.map(x => this.decode(x, decode_args));
2765+ }
28222766 }
28232767
2824- /**
2825- * Decodes a sequence of token IDs back to a string.
2826- *
2827- * @param {number[]|Tensor} token_ids List/Tensor of token IDs to decode.
2828- * @param {Object} [decode_args={}]
2829- * @param {boolean} [decode_args.skip_special_tokens=false] If true, special tokens are removed from the output string.
2830- * @param {boolean} [decode_args.clean_up_tokenization_spaces=true] If true, spaces before punctuations and abbreviated forms are removed.
2831- *
2832- * @returns {string} The decoded string.
2833- * @throws {Error} If `token_ids` is not a non-empty array of integers.
2834- */
2835- decode(
2836- token_ids,
2837- decode_args = {},
2838- ) {
2839- if (token_ids instanceof Tensor) {
2840- token_ids = prepareTensorForDecode(token_ids);
2841- }
2842-
2843- if (!Array.isArray(token_ids) || token_ids.length === 0 || !isIntegralNumber(token_ids[0])) {
2844- throw Error("token_ids must be a non-empty array of integers.");
2845- }
2768+ return /** @type {BatchEncoding} */ (result);
2769+ }
28462770
2847- return this.decode_single(token_ids, decode_args)
2771+ /**
2772+ * Encodes a single text using the preprocessor pipeline of the tokenizer.
2773+ *
2774+ * @param {string|null} text The text to encode.
2775+ * @returns {string[]|null} The encoded tokens.
2776+ */
2777+ _encode_text(text) {
2778+ if (text === null) return null;
2779+
2780+ // Actual function which does encoding, for a single text
2781+ // First, we take care of special tokens. Needed to avoid issues arising from
2782+ // normalization and/or pretokenization (which may not preserve special tokens)
2783+ const sections = this.added_tokens_regex
2784+ ? text.split(this.added_tokens_regex).filter((x) => x)
2785+ : [text];
2786+
2787+ const tokens = sections
2788+ .map((x, section_index) => {
2789+ const addedToken = this.added_tokens.find((t) => t.content === x);
2790+ if (addedToken !== undefined) {
2791+ // Ignore added tokens
2792+ return x;
2793+ } else {
2794+ if (this.remove_space === true) {
2795+ x = x.trim().split(/\s+/).join(" ");
2796+ }
2797+ if (this.do_lowercase_and_remove_accent) {
2798+ x = lowercase_and_remove_accent(x);
2799+ }
2800+
2801+ if (this.normalizer !== null) {
2802+ x = this.normalizer(x);
2803+ }
2804+
2805+ const sectionTokens =
2806+ this.pre_tokenizer !== null
2807+ ? this.pre_tokenizer(x, {
2808+ section_index,
2809+ })
2810+ : [x];
2811+
2812+ const tokens = this.model(sectionTokens);
2813+
2814+ return tokens;
2815+ }
2816+ })
2817+ .flat();
2818+
2819+ return tokens;
2820+ }
2821+
2822+ /**
2823+ * Encodes a single text or a pair of texts using the model's tokenizer.
2824+ *
2825+ * @param {string} text The text to encode.
2826+ * @param {string|null} text_pair The optional second text to encode.
2827+ * @param {Object} options An optional object containing the following properties:
2828+ * @param {boolean} [options.add_special_tokens=true] Whether or not to add the special tokens associated with the corresponding model.
2829+ * @returns {EncodingSingle} An object containing the encoded text.
2830+ * @private
2831+ */
2832+ _encode_plus(text, text_pair = null, { add_special_tokens = true } = {}) {
2833+ // Function called by users to encode possibly multiple texts
2834+ const tokens = this._encode_text(text);
2835+ const tokens2 = this._encode_text(text_pair);
2836+
2837+ const combinedTokens = this.post_processor
2838+ ? this.post_processor(tokens, tokens2, { add_special_tokens })
2839+ : { tokens: mergeArrays(tokens ?? [], tokens2 ?? []) };
2840+
2841+ const input_ids = this.model.convert_tokens_to_ids(combinedTokens.tokens);
2842+
2843+ const result = {
2844+ input_ids,
2845+ attention_mask: new Array(input_ids.length).fill(1),
modified core/vendor/modules/@xenova/transformers/src/transformers.js +4 −4
@@ -1,18 +1,18 @@
11 /**
22 * @file Entry point for the Transformers.js library. Only the exports from this file
33 * are available to the end user, and are grouped as follows:
4- *
4+ *
55 * 1. [Pipelines](./pipelines)
66 * 2. [Environment variables](./env)
77 * 3. [Models](./models)
88 * 4. [Tokenizers](./tokenizers)
99 * 5. [Processors](./processors)
10- *
10+ *
1111 * @module transformers
1212 */
1313
14-export * from './env.js';
15-export * from './pipelines.js';
14+export * from "./env.js";
15+export * from "./pipelines.js";
1616 // export * from './models.js';
1717 // export * from './tokenizers.js';
1818 // export * from './processors.js';
modified core/vendor/modules/@xenova/transformers/src/utils/audio.js +527 −459
@@ -1,20 +1,15 @@
11 /**
2- * @file Helper module for audio processing.
3- *
4- * These functions and classes are only used internally,
2+ * @file Helper module for audio processing.
3+ *
4+ * These functions and classes are only used internally,
55 * meaning an end-user shouldn't need to access anything here.
6- *
6+ *
77 * @module utils/audio
88 */
99
10-import {
11- getFile,
12-} from './hub.js';
13-import { FFT, max } from './maths.js';
14-import {
15- calculateReflectOffset,
16-} from './core.js';
17-
10+import { getFile } from "./hub.js";
11+import { FFT, max } from "./maths.js";
12+import { calculateReflectOffset } from "./core.js";
1813
1914 /**
2015 * Helper function to read audio from a path/URL.
@@ -23,58 +18,59 @@
2318 * @returns {Promise<Float32Array>} The decoded audio as a `Float32Array`.
2419 */
2520 export async function read_audio(url, sampling_rate) {
26- if (typeof AudioContext === 'undefined') {
27- // Running in node or an environment without AudioContext
28- throw Error(
29- "Unable to load audio from path/URL since `AudioContext` is not available in your environment. " +
30- "Instead, audio data should be passed directly to the pipeline/processor. " +
31- "For more information and some example code, see https://huggingface.co/docs/transformers.js/guides/node-audio-processing."
32- )
33- }
34-
35- const response = await (await getFile(url)).arrayBuffer();
36- const audioCTX = new AudioContext({ sampleRate: sampling_rate });
37- if (typeof sampling_rate === 'undefined') {
38- console.warn(`No sampling rate provided, using default of ${audioCTX.sampleRate}Hz.`)
39- }
40- const decoded = await audioCTX.decodeAudioData(response);
41-
42- /** @type {Float32Array} */
43- let audio;
44-
45- // We now replicate HuggingFace's `ffmpeg_read` method:
46- if (decoded.numberOfChannels === 2) {
47- // When downmixing a stereo audio file to mono using the -ac 1 option in FFmpeg,
48- // the audio signal is summed across both channels to create a single mono channel.
49- // However, if the audio is at full scale (i.e. the highest possible volume level),
50- // the summing of the two channels can cause the audio signal to clip or distort.
51-
52- // To prevent this clipping, FFmpeg applies a scaling factor of 1/sqrt(2) (~ 0.707)
53- // to the audio signal before summing the two channels. This scaling factor ensures
54- // that the combined audio signal will not exceed the maximum possible level, even
55- // if both channels are at full scale.
56-
57- // After applying this scaling factor, the audio signal from both channels is summed
58- // to create a single mono channel. It's worth noting that this scaling factor is
59- // only applied when downmixing stereo audio to mono using the -ac 1 option in FFmpeg.
60- // If you're using a different downmixing method, or if you're not downmixing the
61- // audio at all, this scaling factor may not be needed.
62- const SCALING_FACTOR = Math.sqrt(2);
63-
64- const left = decoded.getChannelData(0);
65- const right = decoded.getChannelData(1);
66-
67- audio = new Float32Array(left.length);
68- for (let i = 0; i < decoded.length; ++i) {
69- audio[i] = SCALING_FACTOR * (left[i] + right[i]) / 2;
70- }
71-
72- } else {
73- // If the audio is not stereo, we can just use the first channel:
74- audio = decoded.getChannelData(0);
75- }
76-
77- return audio;
21+ if (typeof AudioContext === "undefined") {
22+ // Running in node or an environment without AudioContext
23+ throw Error(
24+ "Unable to load audio from path/URL since `AudioContext` is not available in your environment. " +
25+ "Instead, audio data should be passed directly to the pipeline/processor. " +
26+ "For more information and some example code, see https://huggingface.co/docs/transformers.js/guides/node-audio-processing.",
27+ );
28+ }
29+
30+ const response = await (await getFile(url)).arrayBuffer();
31+ const audioCTX = new AudioContext({ sampleRate: sampling_rate });
32+ if (typeof sampling_rate === "undefined") {
33+ console.warn(
34+ `No sampling rate provided, using default of ${audioCTX.sampleRate}Hz.`,
35+ );
36+ }
37+ const decoded = await audioCTX.decodeAudioData(response);
38+
39+ /** @type {Float32Array} */
40+ let audio;
41+
42+ // We now replicate HuggingFace's `ffmpeg_read` method:
43+ if (decoded.numberOfChannels === 2) {
44+ // When downmixing a stereo audio file to mono using the -ac 1 option in FFmpeg,
45+ // the audio signal is summed across both channels to create a single mono channel.
46+ // However, if the audio is at full scale (i.e. the highest possible volume level),
47+ // the summing of the two channels can cause the audio signal to clip or distort.
48+
49+ // To prevent this clipping, FFmpeg applies a scaling factor of 1/sqrt(2) (~ 0.707)
50+ // to the audio signal before summing the two channels. This scaling factor ensures
51+ // that the combined audio signal will not exceed the maximum possible level, even
52+ // if both channels are at full scale.
53+
54+ // After applying this scaling factor, the audio signal from both channels is summed
55+ // to create a single mono channel. It's worth noting that this scaling factor is
56+ // only applied when downmixing stereo audio to mono using the -ac 1 option in FFmpeg.
57+ // If you're using a different downmixing method, or if you're not downmixing the
58+ // audio at all, this scaling factor may not be needed.
59+ const SCALING_FACTOR = Math.sqrt(2);
60+
61+ const left = decoded.getChannelData(0);
62+ const right = decoded.getChannelData(1);
63+
64+ audio = new Float32Array(left.length);
65+ for (let i = 0; i < decoded.length; ++i) {
66+ audio[i] = (SCALING_FACTOR * (left[i] + right[i])) / 2;
67+ }
68+ } else {
69+ // If the audio is not stereo, we can just use the first channel:
70+ audio = decoded.getChannelData(0);
71+ }
72+
73+ return audio;
7874 }
7975
8076 /**
@@ -84,107 +80,127 @@
8480 * @returns {Float64Array} The generated Hanning window.
8581 */
8682 export function hanning(M) {
87- if (M < 1) {
88- return new Float64Array();
89- }
90- if (M === 1) {
91- return new Float64Array([1]);
92- }
93- const denom = M - 1;
94- const factor = Math.PI / denom;
95- const cos_vals = new Float64Array(M);
96- for (let i = 0; i < M; ++i) {
97- const n = 2 * i - denom;
98- cos_vals[i] = 0.5 + 0.5 * Math.cos(factor * n);
99- }
100- return cos_vals;
83+ if (M < 1) {
84+ return new Float64Array();
85+ }
86+ if (M === 1) {
87+ return new Float64Array([1]);
88+ }
89+ const denom = M - 1;
90+ const factor = Math.PI / denom;
91+ const cos_vals = new Float64Array(M);
92+ for (let i = 0; i < M; ++i) {
93+ const n = 2 * i - denom;
94+ cos_vals[i] = 0.5 + 0.5 * Math.cos(factor * n);
95+ }
96+ return cos_vals;
10197 }
10298
10399 const HERTZ_TO_MEL_MAPPING = {
104- "htk": (/** @type {number} */ freq) => 2595.0 * Math.log10(1.0 + (freq / 700.0)),
105- "kaldi": (/** @type {number} */ freq) => 1127.0 * Math.log(1.0 + (freq / 700.0)),
106- "slaney": (/** @type {number} */ freq, min_log_hertz = 1000.0, min_log_mel = 15.0, logstep = 27.0 / Math.log(6.4)) =>
107- freq >= min_log_hertz
108- ? min_log_mel + Math.log(freq / min_log_hertz) * logstep
109- : 3.0 * freq / 200.0,
110-}
100+ htk: (/** @type {number} */ freq) => 2595.0 * Math.log10(1.0 + freq / 700.0),
101+ kaldi: (/** @type {number} */ freq) => 1127.0 * Math.log(1.0 + freq / 700.0),
102+ slaney: (
103+ /** @type {number} */ freq,
104+ min_log_hertz = 1000.0,
105+ min_log_mel = 15.0,
106+ logstep = 27.0 / Math.log(6.4),
107+ ) =>
108+ freq >= min_log_hertz
109+ ? min_log_mel + Math.log(freq / min_log_hertz) * logstep
110+ : (3.0 * freq) / 200.0,
111+};
111112
112113 /**
113- * @template {Float32Array|Float64Array|number} T
114- * @param {T} freq
114+ * @template {Float32Array|Float64Array|number} T
115+ * @param {T} freq
115116 * @param {string} [mel_scale]
116117 * @returns {T}
117118 */
118119 function hertz_to_mel(freq, mel_scale = "htk") {
119- const fn = HERTZ_TO_MEL_MAPPING[mel_scale];
120- if (!fn) {
121- throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');
122- }
123-
124- return typeof freq === 'number' ? fn(freq) : freq.map(x => fn(x));
120+ const fn = HERTZ_TO_MEL_MAPPING[mel_scale];
121+ if (!fn) {
122+ throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');
123+ }
124+
125+ return typeof freq === "number" ? fn(freq) : freq.map((x) => fn(x));
125126 }
126127
127128 const MEL_TO_HERTZ_MAPPING = {
128- "htk": (/** @type {number} */ mels) => 700.0 * (10.0 ** (mels / 2595.0) - 1.0),
129- "kaldi": (/** @type {number} */ mels) => 700.0 * (Math.exp(mels / 1127.0) - 1.0),
130- "slaney": (/** @type {number} */ mels, min_log_hertz = 1000.0, min_log_mel = 15.0, logstep = Math.log(6.4) / 27.0) => mels >= min_log_mel
131- ? min_log_hertz * Math.exp(logstep * (mels - min_log_mel))
132- : 200.0 * mels / 3.0,
133-}
129+ htk: (/** @type {number} */ mels) => 700.0 * (10.0 ** (mels / 2595.0) - 1.0),
130+ kaldi: (/** @type {number} */ mels) =>
131+ 700.0 * (Math.exp(mels / 1127.0) - 1.0),
132+ slaney: (
133+ /** @type {number} */ mels,
134+ min_log_hertz = 1000.0,
135+ min_log_mel = 15.0,
136+ logstep = Math.log(6.4) / 27.0,
137+ ) =>
138+ mels >= min_log_mel
139+ ? min_log_hertz * Math.exp(logstep * (mels - min_log_mel))
140+ : (200.0 * mels) / 3.0,
141+};
134142
135143 /**
136- * @template {Float32Array|Float64Array|number} T
137- * @param {T} mels
144+ * @template {Float32Array|Float64Array|number} T
145+ * @param {T} mels
138146 * @param {string} [mel_scale]
139147 * @returns {T}
140148 */
141149 function mel_to_hertz(mels, mel_scale = "htk") {
142- const fn = MEL_TO_HERTZ_MAPPING[mel_scale];
143- if (!fn) {
144- throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');
145- }
146-
147- return typeof mels === 'number' ? fn(mels) : mels.map(x => fn(x));
150+ const fn = MEL_TO_HERTZ_MAPPING[mel_scale];
151+ if (!fn) {
152+ throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');
153+ }
154+
155+ return typeof mels === "number" ? fn(mels) : mels.map((x) => fn(x));
148156 }
149157
150158 /**
151-* Creates a triangular filter bank.
152-*
153-* Adapted from torchaudio and librosa.
154-*
155-* @param {Float64Array} fft_freqs Discrete frequencies of the FFT bins in Hz, of shape `(num_frequency_bins,)`.
156-* @param {Float64Array} filter_freqs Center frequencies of the triangular filters to create, in Hz, of shape `(num_mel_filters,)`.
157-* @returns {number[][]} of shape `(num_frequency_bins, num_mel_filters)`.
158-*/
159+ * Creates a triangular filter bank.
160+ *
161+ * Adapted from torchaudio and librosa.
162+ *
163+ * @param {Float64Array} fft_freqs Discrete frequencies of the FFT bins in Hz, of shape `(num_frequency_bins,)`.
164+ * @param {Float64Array} filter_freqs Center frequencies of the triangular filters to create, in Hz, of shape `(num_mel_filters,)`.
165+ * @returns {number[][]} of shape `(num_frequency_bins, num_mel_filters)`.
166+ */
159167 function _create_triangular_filter_bank(fft_freqs, filter_freqs) {
160- const filter_diff = Float64Array.from(
161- { length: filter_freqs.length - 1 },
162- (_, i) => filter_freqs[i + 1] - filter_freqs[i]
163- );
164-
165- const slopes = Array.from({
166- length: fft_freqs.length
167- }, () => new Array(filter_freqs.length));
168-
169- for (let j = 0; j < fft_freqs.length; ++j) {
170- const slope = slopes[j];
171- for (let i = 0; i < filter_freqs.length; ++i) {
172- slope[i] = filter_freqs[i] - fft_freqs[j];
173- }
174- }
175-
176- const numFreqs = filter_freqs.length - 2;
177- const ret = Array.from({ length: numFreqs }, () => new Array(fft_freqs.length));
178-
179- for (let j = 0; j < fft_freqs.length; ++j) { // 201
180- const slope = slopes[j];
181- for (let i = 0; i < numFreqs; ++i) { // 80
182- const down = -slope[i] / filter_diff[i];
183- const up = slope[i + 2] / filter_diff[i + 1];
184- ret[i][j] = Math.max(0, Math.min(down, up));
185- }
186- }
187- return ret;
168+ const filter_diff = Float64Array.from(
169+ { length: filter_freqs.length - 1 },
170+ (_, i) => filter_freqs[i + 1] - filter_freqs[i],
171+ );
172+
173+ const slopes = Array.from(
174+ {
175+ length: fft_freqs.length,
176+ },
177+ () => new Array(filter_freqs.length),
178+ );
179+
180+ for (let j = 0; j < fft_freqs.length; ++j) {
181+ const slope = slopes[j];
182+ for (let i = 0; i < filter_freqs.length; ++i) {
183+ slope[i] = filter_freqs[i] - fft_freqs[j];
184+ }
185+ }
186+
187+ const numFreqs = filter_freqs.length - 2;
188+ const ret = Array.from(
189+ { length: numFreqs },
190+ () => new Array(fft_freqs.length),
191+ );
192+
193+ for (let j = 0; j < fft_freqs.length; ++j) {
194+ // 201
195+ const slope = slopes[j];
196+ for (let i = 0; i < numFreqs; ++i) {
197+ // 80
198+ const down = -slope[i] / filter_diff[i];
199+ const up = slope[i + 2] / filter_diff[i + 1];
200+ ret[i][j] = Math.max(0, Math.min(down, up));
201+ }
202+ }
203+ return ret;
188204 }
189205
190206 /**
@@ -195,8 +211,8 @@
195211 * @returns `num` evenly spaced samples, calculated over the interval `[start, stop]`.
196212 */
197213 function linspace(start, end, num) {
198- const step = (end - start) / (num - 1);
199- return Float64Array.from({ length: num }, (_, i) => start + step * i);
214+ const step = (end - start) / (num - 1);
215+ return Float64Array.from({ length: num }, (_, i) => start + step * i);
200216 }
201217
202218 /**
@@ -217,52 +233,57 @@
217233 * This is a projection matrix to go from a spectrogram to a mel spectrogram.
218234 */
219235 export function mel_filter_bank(
220- num_frequency_bins,
221- num_mel_filters,
222- min_frequency,
223- max_frequency,
224- sampling_rate,
225- norm = null,
226- mel_scale = "htk",
227- triangularize_in_mel_space = false,
236+ num_frequency_bins,
237+ num_mel_filters,
238+ min_frequency,
239+ max_frequency,
240+ sampling_rate,
241+ norm = null,
242+ mel_scale = "htk",
243+ triangularize_in_mel_space = false,
228244 ) {
229- if (norm !== null && norm !== "slaney") {
230- throw new Error('norm must be one of null or "slaney"');
231- }
232-
233- const mel_min = hertz_to_mel(min_frequency, mel_scale);
234- const mel_max = hertz_to_mel(max_frequency, mel_scale);
235- const mel_freqs = linspace(mel_min, mel_max, num_mel_filters + 2);
236-
237- let filter_freqs = mel_to_hertz(mel_freqs, mel_scale);
238- let fft_freqs; // frequencies of FFT bins in Hz
239-
240- if (triangularize_in_mel_space) {
241- const fft_bin_width = sampling_rate / (num_frequency_bins * 2);
242- fft_freqs = hertz_to_mel(Float64Array.from({ length: num_frequency_bins }, (_, i) => i * fft_bin_width), mel_scale);
243- filter_freqs = mel_freqs;
244- } else {
245- fft_freqs = linspace(0, Math.floor(sampling_rate / 2), num_frequency_bins);
246- }
247-
248- const mel_filters = _create_triangular_filter_bank(fft_freqs, filter_freqs);
249-
250- if (norm !== null && norm === "slaney") {
251- // Slaney-style mel is scaled to be approx constant energy per channel
252- for (let i = 0; i < num_mel_filters; ++i) {
253- const filter = mel_filters[i];
254- const enorm = 2.0 / (filter_freqs[i + 2] - filter_freqs[i]);
255- for (let j = 0; j < num_frequency_bins; ++j) {
256- // Apply this enorm to all frequency bins
257- filter[j] *= enorm;
258- }
259- }
260- }
261-
262- // TODO warn if there is a zero row
263-
264- return mel_filters;
265-
245+ if (norm !== null && norm !== "slaney") {
246+ throw new Error('norm must be one of null or "slaney"');
247+ }
248+
249+ const mel_min = hertz_to_mel(min_frequency, mel_scale);
250+ const mel_max = hertz_to_mel(max_frequency, mel_scale);
251+ const mel_freqs = linspace(mel_min, mel_max, num_mel_filters + 2);
252+
253+ let filter_freqs = mel_to_hertz(mel_freqs, mel_scale);
254+ let fft_freqs; // frequencies of FFT bins in Hz
255+
256+ if (triangularize_in_mel_space) {
257+ const fft_bin_width = sampling_rate / (num_frequency_bins * 2);
258+ fft_freqs = hertz_to_mel(
259+ Float64Array.from(
260+ { length: num_frequency_bins },
261+ (_, i) => i * fft_bin_width,
262+ ),
263+ mel_scale,
264+ );
265+ filter_freqs = mel_freqs;
266+ } else {
267+ fft_freqs = linspace(0, Math.floor(sampling_rate / 2), num_frequency_bins);
268+ }
269+
270+ const mel_filters = _create_triangular_filter_bank(fft_freqs, filter_freqs);
271+
272+ if (norm !== null && norm === "slaney") {
273+ // Slaney-style mel is scaled to be approx constant energy per channel
274+ for (let i = 0; i < num_mel_filters; ++i) {
275+ const filter = mel_filters[i];
276+ const enorm = 2.0 / (filter_freqs[i + 2] - filter_freqs[i]);
277+ for (let j = 0; j < num_frequency_bins; ++j) {
278+ // Apply this enorm to all frequency bins
279+ filter[j] *= enorm;
280+ }
281+ }
282+ }
283+
284+ // TODO warn if there is a zero row
285+
286+ return mel_filters;
266287 }
267288
268289 /**
@@ -274,73 +295,80 @@
274295 * @returns {T} The padded array.
275296 */
276297 function padReflect(array, left, right) {
277- // @ts-ignore
278- const padded = new array.constructor(array.length + left + right);
279- const w = array.length - 1;
280-
281- for (let i = 0; i < array.length; ++i) {
282- padded[left + i] = array[i];
283- }
284-
285- for (let i = 1; i <= left; ++i) {
286- padded[left - i] = array[calculateReflectOffset(i, w)];
287- }
288-
289- for (let i = 1; i <= right; ++i) {
290- padded[w + left + i] = array[calculateReflectOffset(w - i, w)];
291- }
292-
293- return padded;
298+ // @ts-ignore
299+ const padded = new array.constructor(array.length + left + right);
300+ const w = array.length - 1;
301+
302+ for (let i = 0; i < array.length; ++i) {
303+ padded[left + i] = array[i];
304+ }
305+
306+ for (let i = 1; i <= left; ++i) {
307+ padded[left - i] = array[calculateReflectOffset(i, w)];
308+ }
309+
310+ for (let i = 1; i <= right; ++i) {
311+ padded[w + left + i] = array[calculateReflectOffset(w - i, w)];
312+ }
313+
314+ return padded;
294315 }
295316
296317 /**
297318 * Helper function to compute `amplitude_to_db` and `power_to_db`.
298319 * @template {Float32Array|Float64Array} T
299- * @param {T} spectrogram
300- * @param {number} factor
301- * @param {number} reference
302- * @param {number} min_value
303- * @param {number} db_range
320+ * @param {T} spectrogram
321+ * @param {number} factor
322+ * @param {number} reference
323+ * @param {number} min_value
324+ * @param {number} db_range
304325 * @returns {T}
305326 */
306-function _db_conversion_helper(spectrogram, factor, reference, min_value, db_range) {
307- if (reference <= 0) {
308- throw new Error('reference must be greater than zero');
309- }
310-
311- if (min_value <= 0) {
312- throw new Error('min_value must be greater than zero');
313- }
314-
315- reference = Math.max(min_value, reference);
316-
317- const logReference = Math.log10(reference);
327+function _db_conversion_helper(
328+ spectrogram,
329+ factor,
330+ reference,
331+ min_value,
332+ db_range,
333+) {
334+ if (reference <= 0) {
335+ throw new Error("reference must be greater than zero");
336+ }
337+
338+ if (min_value <= 0) {
339+ throw new Error("min_value must be greater than zero");
340+ }
341+
342+ reference = Math.max(min_value, reference);
343+
344+ const logReference = Math.log10(reference);
345+ for (let i = 0; i < spectrogram.length; ++i) {
346+ spectrogram[i] =
347+ factor * Math.log10(Math.max(min_value, spectrogram[i]) - logReference);
348+ }
349+
350+ if (db_range !== null) {
351+ if (db_range <= 0) {
352+ throw new Error("db_range must be greater than zero");
353+ }
354+ const maxValue = max(spectrogram)[0] - db_range;
318355 for (let i = 0; i < spectrogram.length; ++i) {
319- spectrogram[i] = factor * Math.log10(Math.max(min_value, spectrogram[i]) - logReference)
356+ spectrogram[i] = Math.max(spectrogram[i], maxValue);
320357 }
358+ }
321359
322- if (db_range !== null) {
323- if (db_range <= 0) {
324- throw new Error('db_range must be greater than zero');
325- }
326- const maxValue = max(spectrogram)[0] - db_range;
327- for (let i = 0; i < spectrogram.length; ++i) {
328- spectrogram[i] = Math.max(spectrogram[i], maxValue);
329- }
330- }
331-
332- return spectrogram;
360+ return spectrogram;
333361 }
334362
335363 /**
336364 * Converts an amplitude spectrogram to the decibel scale. This computes `20 * log10(spectrogram / reference)`,
337365 * using basic logarithm properties for numerical stability. NOTE: Operates in-place.
338- *
366+ *
339367 * The motivation behind applying the log function on the (mel) spectrogram is that humans do not hear loudness on a
340368 * linear scale. Generally to double the perceived volume of a sound we need to put 8 times as much energy into it.
341369 * This means that large variations in energy may not sound all that different if the sound is loud to begin with.
342370 * This compression operation makes the (mel) spectrogram features match more closely what humans actually hear.
343- *
371+ *
344372 * @template {Float32Array|Float64Array} T
345373 * @param {T} spectrogram The input amplitude (mel) spectrogram.
346374 * @param {number} [reference=1.0] Sets the input spectrogram value that corresponds to 0 dB.
@@ -351,21 +379,32 @@
351379 * difference between the peak value and the smallest value will never be more than 80 dB. Must be greater than zero.
352380 * @returns {T} The modified spectrogram in decibels.
353381 */
354-function amplitude_to_db(spectrogram, reference = 1.0, min_value = 1e-5, db_range = null) {
355- return _db_conversion_helper(spectrogram, 20.0, reference, min_value, db_range);
382+function amplitude_to_db(
383+ spectrogram,
384+ reference = 1.0,
385+ min_value = 1e-5,
386+ db_range = null,
387+) {
388+ return _db_conversion_helper(
389+ spectrogram,
390+ 20.0,
391+ reference,
392+ min_value,
393+ db_range,
394+ );
356395 }
357396
358397 /**
359398 * Converts a power spectrogram to the decibel scale. This computes `10 * log10(spectrogram / reference)`,
360399 * using basic logarithm properties for numerical stability. NOTE: Operates in-place.
361- *
400+ *
362401 * The motivation behind applying the log function on the (mel) spectrogram is that humans do not hear loudness on a
363402 * linear scale. Generally to double the perceived volume of a sound we need to put 8 times as much energy into it.
364403 * This means that large variations in energy may not sound all that different if the sound is loud to begin with.
365404 * This compression operation makes the (mel) spectrogram features match more closely what humans actually hear.
366- *
405+ *
367406 * Based on the implementation of `librosa.power_to_db`.
368- *
407+ *
369408 * @template {Float32Array|Float64Array} T
370409 * @param {T} spectrogram The input power (mel) spectrogram. Note that a power spectrogram has the amplitudes squared!
371410 * @param {number} [reference=1.0] Sets the input spectrogram value that corresponds to 0 dB.
@@ -376,13 +415,24 @@
376415 * difference between the peak value and the smallest value will never be more than 80 dB. Must be greater than zero.
377416 * @returns {T} The modified spectrogram in decibels.
378417 */
379-function power_to_db(spectrogram, reference = 1.0, min_value = 1e-10, db_range = null) {
380- return _db_conversion_helper(spectrogram, 10.0, reference, min_value, db_range);
418+function power_to_db(
419+ spectrogram,
420+ reference = 1.0,
421+ min_value = 1e-10,
422+ db_range = null,
423+) {
424+ return _db_conversion_helper(
425+ spectrogram,
426+ 10.0,
427+ reference,
428+ min_value,
429+ db_range,
430+ );
381431 }
382432
383433 /**
384434 * Calculates a spectrogram over one waveform using the Short-Time Fourier Transform.
385- *
435+ *
386436 * This function can create the following kinds of spectrograms:
387437 * - amplitude spectrogram (`power = 1.0`)
388438 * - power spectrogram (`power = 2.0`)
@@ -392,9 +442,9 @@
392442 * - log-mel spectrogram (provide `mel_filters` and `log_mel`)
393443 *
394444 * In this implementation, the window is assumed to be zero-padded to have the same size as the analysis frame.
395- * A padded window can be obtained from `window_function()`. The FFT input buffer may be larger than the analysis frame,
445+ * A padded window can be obtained from `window_function()`. The FFT input buffer may be larger than the analysis frame,
396446 * typically the next power of two.
397- *
447+ *
398448 * @param {Float32Array|Float64Array} waveform The input waveform of shape `(length,)`. This must be a single real-valued, mono waveform.
399449 * @param {Float32Array|Float64Array} window The windowing function to apply of shape `(frame_length,)`, including zero-padding if necessary. The actual window length may be
400450 * shorter than `frame_length`, but we're assuming the array has already been zero-padded.
@@ -432,193 +482,209 @@
432482 * @returns {{data: Float32Array, dims: number[]}} Spectrogram of shape `(num_frequency_bins, length)` (regular spectrogram) or shape `(num_mel_filters, length)` (mel spectrogram).
433483 */
434484 export function spectrogram(
435- waveform,
436- window,
437- frame_length,
438- hop_length,
439- {
440- fft_length = null,
441- power = 1.0,
442- center = true,
443- pad_mode = "reflect",
444- onesided = true,
445- preemphasis = null,
446- mel_filters = null,
447- mel_floor = 1e-10,
448- log_mel = null,
449- reference = 1.0,
450- min_value = 1e-10,
451- db_range = null,
452- remove_dc_offset = null,
453-
454- // Custom parameters for efficiency reasons
455- max_num_frames = null,
456- do_pad = true,
457- transpose = false,
458- } = {}
485+ waveform,
486+ window,
487+ frame_length,
488+ hop_length,
489+ {
490+ fft_length = null,
491+ power = 1.0,
492+ center = true,
493+ pad_mode = "reflect",
494+ onesided = true,
495+ preemphasis = null,
496+ mel_filters = null,
497+ mel_floor = 1e-10,
498+ log_mel = null,
499+ reference = 1.0,
500+ min_value = 1e-10,
501+ db_range = null,
502+ remove_dc_offset = null,
503+
504+ // Custom parameters for efficiency reasons
505+ max_num_frames = null,
506+ do_pad = true,
507+ transpose = false,
508+ } = {},
459509 ) {
460- const window_length = window.length;
461- if (fft_length === null) {
462- fft_length = frame_length;
463- }
464- if (frame_length > fft_length) {
465- throw Error(`frame_length (${frame_length}) may not be larger than fft_length (${fft_length})`)
466- }
467-
468- if (window_length !== frame_length) {
469- throw new Error(`Length of the window (${window_length}) must equal frame_length (${frame_length})`);
470- }
471-
472- if (hop_length <= 0) {
473- throw new Error("hop_length must be greater than zero");
474- }
475-
476- if (center) {
477- if (pad_mode !== 'reflect') {
478- throw new Error(`pad_mode="${pad_mode}" not implemented yet.`)
479- }
480- const half_window = Math.floor((fft_length - 1) / 2) + 1;
481- waveform = padReflect(waveform, half_window, half_window);
482- }
483-
484- // split waveform into frames of frame_length size
485- const num_frames = Math.floor(1 + Math.floor((waveform.length - frame_length) / hop_length))
486-
487- const num_frequency_bins = onesided ? Math.floor(fft_length / 2) + 1 : fft_length
488-
489- let d1 = num_frames;
490- let d1Max = num_frames;
491-
492- // If maximum number of frames is provided, we must either pad or truncate
493- if (max_num_frames !== null) {
494- if (max_num_frames > num_frames) { // input is too short, so we pad
495- if (do_pad) {
496- d1Max = max_num_frames;
497- }
498- } else { // input is too long, so we truncate
499- d1Max = d1 = max_num_frames;
500- }
501- }
502-
503- // Preallocate arrays to store output.
504- const fft = new FFT(fft_length);
505- const inputBuffer = new Float64Array(fft_length);
506- const outputBuffer = new Float64Array(fft.outputBufferSize);
507- const magnitudes = new Array(d1);
508-
509- for (let i = 0; i < d1; ++i) {
510- // Populate buffer with waveform data
511- const offset = i * hop_length;
512- for (let j = 0; j < frame_length; ++j) {
513- inputBuffer[j] = waveform[offset + j];
514- }
515-
516- if (remove_dc_offset) {
517- let sum = 0;
518- for (let j = 0; j < frame_length; ++j) {
519- sum += inputBuffer[j];
520- }
521- const mean = sum / frame_length;
522- for (let j = 0; j < frame_length; ++j) {
523- inputBuffer[j] -= mean;
524- }
525- }
526-
527- if (preemphasis !== null) {
528- // Done in reverse to avoid copies and distructive modification
529- for (let j = frame_length - 1; j >= 1; --j) {
530- inputBuffer[j] -= preemphasis * inputBuffer[j - 1];
531- }
532- inputBuffer[0] *= 1 - preemphasis;
533- }
534-
535- for (let j = 0; j < window.length; ++j) {
536- inputBuffer[j] *= window[j];
537- }
538-
539- fft.realTransform(outputBuffer, inputBuffer);
540-
541- // compute magnitudes
542- const row = new Array(num_frequency_bins);
543- for (let j = 0; j < row.length; ++j) {
544- const j2 = j << 1;
545- row[j] = outputBuffer[j2] ** 2 + outputBuffer[j2 + 1] ** 2;
546- }
547- magnitudes[i] = row;
548- }
549-
550- // TODO what should happen if power is None?
551- // https://github.com/huggingface/transformers/issues/27772
552- if (power !== null && power !== 2) {
553- // slight optimization to not sqrt
554- const pow = 2 / power; // we use 2 since we already squared
555- for (let i = 0; i < magnitudes.length; ++i) {
556- const magnitude = magnitudes[i];
557- for (let j = 0; j < magnitude.length; ++j) {
558- magnitude[j] **= pow;
559- }
510+ const window_length = window.length;
511+ if (fft_length === null) {
512+ fft_length = frame_length;
513+ }
514+ if (frame_length > fft_length) {
515+ throw Error(
516+ `frame_length (${frame_length}) may not be larger than fft_length (${fft_length})`,
517+ );
518+ }
519+
520+ if (window_length !== frame_length) {
521+ throw new Error(
522+ `Length of the window (${window_length}) must equal frame_length (${frame_length})`,
523+ );
524+ }
525+
526+ if (hop_length <= 0) {
527+ throw new Error("hop_length must be greater than zero");
528+ }
529+
530+ if (center) {
531+ if (pad_mode !== "reflect") {
532+ throw new Error(`pad_mode="${pad_mode}" not implemented yet.`);
533+ }
534+ const half_window = Math.floor((fft_length - 1) / 2) + 1;
535+ waveform = padReflect(waveform, half_window, half_window);
536+ }
537+
538+ // split waveform into frames of frame_length size
539+ const num_frames = Math.floor(
540+ 1 + Math.floor((waveform.length - frame_length) / hop_length),
541+ );
542+
543+ const num_frequency_bins = onesided
544+ ? Math.floor(fft_length / 2) + 1
545+ : fft_length;
546+
547+ let d1 = num_frames;
548+ let d1Max = num_frames;
549+
550+ // If maximum number of frames is provided, we must either pad or truncate
551+ if (max_num_frames !== null) {
552+ if (max_num_frames > num_frames) {
553+ // input is too short, so we pad
554+ if (do_pad) {
555+ d1Max = max_num_frames;
556+ }
557+ } else {
558+ // input is too long, so we truncate
559+ d1Max = d1 = max_num_frames;
560+ }
561+ }
562+
563+ // Preallocate arrays to store output.
564+ const fft = new FFT(fft_length);
565+ const inputBuffer = new Float64Array(fft_length);
566+ const outputBuffer = new Float64Array(fft.outputBufferSize);
567+ const magnitudes = new Array(d1);
568+
569+ for (let i = 0; i < d1; ++i) {
570+ // Populate buffer with waveform data
571+ const offset = i * hop_length;
572+ for (let j = 0; j < frame_length; ++j) {
573+ inputBuffer[j] = waveform[offset + j];
574+ }
575+
576+ if (remove_dc_offset) {
577+ let sum = 0;
578+ for (let j = 0; j < frame_length; ++j) {
579+ sum += inputBuffer[j];
580+ }
581+ const mean = sum / frame_length;
582+ for (let j = 0; j < frame_length; ++j) {
583+ inputBuffer[j] -= mean;
584+ }
585+ }
586+
587+ if (preemphasis !== null) {
588+ // Done in reverse to avoid copies and distructive modification
589+ for (let j = frame_length - 1; j >= 1; --j) {
590+ inputBuffer[j] -= preemphasis * inputBuffer[j - 1];
591+ }
592+ inputBuffer[0] *= 1 - preemphasis;
593+ }
594+
595+ for (let j = 0; j < window.length; ++j) {
596+ inputBuffer[j] *= window[j];
597+ }
598+
599+ fft.realTransform(outputBuffer, inputBuffer);
600+
601+ // compute magnitudes
602+ const row = new Array(num_frequency_bins);
603+ for (let j = 0; j < row.length; ++j) {
604+ const j2 = j << 1;
605+ row[j] = outputBuffer[j2] ** 2 + outputBuffer[j2 + 1] ** 2;
606+ }
607+ magnitudes[i] = row;
608+ }
609+
610+ // TODO what should happen if power is None?
611+ // https://github.com/huggingface/transformers/issues/27772
612+ if (power !== null && power !== 2) {
613+ // slight optimization to not sqrt
614+ const pow = 2 / power; // we use 2 since we already squared
615+ for (let i = 0; i < magnitudes.length; ++i) {
616+ const magnitude = magnitudes[i];
617+ for (let j = 0; j < magnitude.length; ++j) {
618+ magnitude[j] **= pow;
619+ }
620+ }
621+ }
622+
623+ // TODO: What if `mel_filters` is null?
624+ const num_mel_filters = mel_filters.length;
625+
626+ // Only here do we create Float32Array
627+ const mel_spec = new Float32Array(num_mel_filters * d1Max);
628+
629+ // Perform matrix muliplication:
630+ // mel_spec = mel_filters @ magnitudes.T
631+ // - mel_filters.shape=(80, 201)
632+ // - magnitudes.shape=(3000, 201) => - magnitudes.T.shape=(201, 3000)
633+ // - mel_spec.shape=(80, 3000)
634+ const dims = transpose ? [d1Max, num_mel_filters] : [num_mel_filters, d1Max];
635+ for (let i = 0; i < num_mel_filters; ++i) {
636+ // num melfilters (e.g., 80)
637+ const filter = mel_filters[i];
638+ for (let j = 0; j < d1; ++j) {
639+ // num frames (e.g., 3000)
640+ const magnitude = magnitudes[j];
641+
642+ let sum = 0;
643+ for (let k = 0; k < num_frequency_bins; ++k) {
644+ // num frequency bins (e.g., 201)
645+ sum += filter[k] * magnitude[k];
646+ }
647+
648+ mel_spec[transpose ? j * num_mel_filters + i : i * d1 + j] = Math.max(
649+ mel_floor,
650+ sum,
651+ );
652+ }
653+ }
654+
655+ if (power !== null && log_mel !== null) {
656+ const o = Math.min(mel_spec.length, d1 * num_mel_filters);
657+ switch (log_mel) {
658+ case "log":
659+ for (let i = 0; i < o; ++i) {
660+ mel_spec[i] = Math.log(mel_spec[i]);
560661 }
561- }
562-
563- // TODO: What if `mel_filters` is null?
564- const num_mel_filters = mel_filters.length;
565-
566- // Only here do we create Float32Array
567- const mel_spec = new Float32Array(num_mel_filters * d1Max);
568-
569- // Perform matrix muliplication:
570- // mel_spec = mel_filters @ magnitudes.T
571- // - mel_filters.shape=(80, 201)
572- // - magnitudes.shape=(3000, 201) => - magnitudes.T.shape=(201, 3000)
573- // - mel_spec.shape=(80, 3000)
574- const dims = transpose ? [d1Max, num_mel_filters] : [num_mel_filters, d1Max];
575- for (let i = 0; i < num_mel_filters; ++i) { // num melfilters (e.g., 80)
576- const filter = mel_filters[i];
577- for (let j = 0; j < d1; ++j) { // num frames (e.g., 3000)
578- const magnitude = magnitudes[j];
579-
580- let sum = 0;
581- for (let k = 0; k < num_frequency_bins; ++k) { // num frequency bins (e.g., 201)
582- sum += filter[k] * magnitude[k];
583- }
584-
585- mel_spec[
586- transpose
587- ? j * num_mel_filters + i
588- : i * d1 + j
589- ] = Math.max(mel_floor, sum);
662+ break;
663+ case "log10":
664+ for (let i = 0; i < o; ++i) {
665+ mel_spec[i] = Math.log10(mel_spec[i]);
590666 }
591- }
592-
593- if (power !== null && log_mel !== null) {
594- const o = Math.min(mel_spec.length, d1 * num_mel_filters);
595- switch (log_mel) {
596- case 'log':
597- for (let i = 0; i < o; ++i) {
598- mel_spec[i] = Math.log(mel_spec[i]);
599- }
600- break;
601- case 'log10':
602- for (let i = 0; i < o; ++i) {
603- mel_spec[i] = Math.log10(mel_spec[i]);
604- }
605- break;
606- case 'dB':
607- if (power === 1.0) {
608- // NOTE: operates in-place
609- amplitude_to_db(mel_spec, reference, min_value, db_range);
610- } else if (power === 2.0) {
611- power_to_db(mel_spec, reference, min_value, db_range);
612- } else {
613- throw new Error(`Cannot use log_mel option '${log_mel}' with power ${power}`)
614- }
615- break;
616- default:
617- throw new Error(`log_mel must be one of null, 'log', 'log10' or 'dB'. Got '${log_mel}'`);
667+ break;
668+ case "dB":
669+ if (power === 1.0) {
670+ // NOTE: operates in-place
671+ amplitude_to_db(mel_spec, reference, min_value, db_range);
672+ } else if (power === 2.0) {
673+ power_to_db(mel_spec, reference, min_value, db_range);
674+ } else {
675+ throw new Error(
676+ `Cannot use log_mel option '${log_mel}' with power ${power}`,
677+ );
618678 }
619- }
620-
621- return { data: mel_spec, dims };
679+ break;
680+ default:
681+ throw new Error(
682+ `log_mel must be one of null, 'log', 'log10' or 'dB'. Got '${log_mel}'`,
683+ );
684+ }
685+ }
686+
687+ return { data: mel_spec, dims };
622688 }
623689
624690 /**
@@ -632,33 +698,35 @@
632698 * @param {boolean} [options.center=true] Whether to center the window inside the FFT buffer. Only used when `frame_length` is provided.
633699 * @returns {Float64Array} The window of shape `(window_length,)` or `(frame_length,)`.
634700 */
635-export function window_function(window_length, name, {
636- periodic = true,
637- frame_length = null,
638- center = true,
639-} = {}) {
640- const length = periodic ? window_length + 1 : window_length;
641- let window;
642- switch (name) {
643- case 'boxcar':
644- window = new Float64Array(length).fill(1.0);
645- break;
646- case 'hann':
647- case 'hann_window':
648- window = hanning(length);
649- break;
650- default:
651- throw new Error(`Unknown window type ${name}.`);
652- }
653- if (periodic) {
654- window = window.subarray(0, window_length);
655- }
656- if (frame_length === null) {
657- return window;
658- }
659- if (window_length > frame_length) {
660- throw new Error(`Length of the window (${window_length}) may not be larger than frame_length (${frame_length})`);
661- }
662-
701+export function window_function(
702+ window_length,
703+ name,
704+ { periodic = true, frame_length = null, center = true } = {},
705+) {
706+ const length = periodic ? window_length + 1 : window_length;
707+ let window;
708+ switch (name) {
709+ case "boxcar":
710+ window = new Float64Array(length).fill(1.0);
711+ break;
712+ case "hann":
713+ case "hann_window":
714+ window = hanning(length);
715+ break;
716+ default:
717+ throw new Error(`Unknown window type ${name}.`);
718+ }
719+ if (periodic) {
720+ window = window.subarray(0, window_length);
721+ }
722+ if (frame_length === null) {
663723 return window;
724+ }
725+ if (window_length > frame_length) {
726+ throw new Error(
727+ `Length of the window (${window_length}) may not be larger than frame_length (${frame_length})`,
728+ );
729+ }
730+
731+ return window;
664732 }
modified core/vendor/modules/@xenova/transformers/src/utils/core.js +51 −49
@@ -1,10 +1,9 @@
1-
21 /**
32 * @file Core utility functions/classes for Transformers.js.
4- *
3+ *
54 * These are only used internally, meaning an end-user shouldn't
65 * need to access anything here.
7- *
6+ *
87 * @module utils/core
98 */
109
@@ -17,7 +16,7 @@
1716 * @private
1817 */
1918 export function dispatchCallback(progress_callback, data) {
20- if (progress_callback) progress_callback(data);
19+ if (progress_callback) progress_callback(data);
2120 }
2221
2322 /**
@@ -28,8 +27,10 @@
2827 * @see https://ultimatecourses.com/blog/reverse-object-keys-and-values-in-javascript
2928 */
3029 export function reverseDictionary(data) {
31- // https://ultimatecourses.com/blog/reverse-object-keys-and-values-in-javascript
32- return Object.fromEntries(Object.entries(data).map(([key, value]) => [value, key]));
30+ // https://ultimatecourses.com/blog/reverse-object-keys-and-values-in-javascript
31+ return Object.fromEntries(
32+ Object.entries(data).map(([key, value]) => [value, key]),
33+ );
3334 }
3435
3536 /**
@@ -39,29 +40,30 @@
3940 * @returns {string} The escaped string.
4041 */
4142 export function escapeRegExp(string) {
42- return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
43+ return string.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); // $& means the whole matched string
4344 }
4445
4546 /**
4647 * A base class for creating callable objects.
47- *
48+ *
4849 * @type {new () => {(...args: any[]): any, _call(...args: any[]): any}}
4950 */
50-export const Callable = /** @type {any} */ (class {
51+export const Callable = /** @type {any} */ (
52+ class {
5153 /**
52- * Creates a new instance of the Callable class.
53- */
54+ * Creates a new instance of the Callable class.
55+ */
5456 constructor() {
55- /**
56- * Creates a closure that delegates to a private method '_call' with the given arguments.
57- * @type {any}
58- * @param {...any} args Zero or more arguments to pass to the '_call' method.
59- * @returns {*} The result of calling the '_call' method.
60- */
61- let closure = function (...args) {
62- return closure._call(...args)
63- }
64- return Object.setPrototypeOf(closure, new.target.prototype)
57+ /**
58+ * Creates a closure that delegates to a private method '_call' with the given arguments.
59+ * @type {any}
60+ * @param {...any} args Zero or more arguments to pass to the '_call' method.
61+ * @returns {*} The result of calling the '_call' method.
62+ */
63+ let closure = function (...args) {
64+ return closure._call(...args);
65+ };
66+ return Object.setPrototypeOf(closure, new.target.prototype);
6567 }
6668
6769 /**
@@ -72,29 +74,29 @@
7274 * @throws {Error} If the subclass does not implement the `_call` method.
7375 */
7476 _call(...args) {
75- throw Error('Must implement _call method in subclass')
77+ throw Error("Must implement _call method in subclass");
7678 }
77-});
79+ }
80+);
7881
7982 /**
8083 * Check if a value is a typed array.
8184 * @param {*} val The value to check.
8285 * @returns {boolean} True if the value is a `TypedArray`, false otherwise.
83- *
86+ *
8487 * Adapted from https://stackoverflow.com/a/71091338/13989043
8588 */
8689 export function isTypedArray(val) {
87- return val?.prototype?.__proto__?.constructor?.name === 'TypedArray';
90+ return val?.prototype?.__proto__?.constructor?.name === "TypedArray";
8891 }
8992
90-
9193 /**
9294 * Check if a value is an integer.
9395 * @param {*} x The value to check.
9496 * @returns {boolean} True if the value is a string, false otherwise.
9597 */
9698 export function isIntegralNumber(x) {
97- return Number.isInteger(x) || typeof x === 'bigint'
99+ return Number.isInteger(x) || typeof x === "bigint";
98100 }
99101
100102 /**
@@ -103,7 +105,7 @@
103105 * @returns {boolean} True if the value exists, false otherwise.
104106 */
105107 export function exists(x) {
106- return x !== undefined && x !== null;
108+ return x !== undefined && x !== null;
107109 }
108110
109111 /**
@@ -113,13 +115,13 @@
113115 * @returns {number[]} An array containing the dimensions of the input array.
114116 */
115117 export function calculateDimensions(arr) {
116- const dimensions = [];
117- let current = arr;
118- while (Array.isArray(current)) {
119- dimensions.push(current.length);
120- current = current[0];
121- }
122- return dimensions;
118+ const dimensions = [];
119+ let current = arr;
120+ while (Array.isArray(current)) {
121+ dimensions.push(current.length);
122+ current = current[0];
123+ }
124+ return dimensions;
123125 }
124126
125127 /**
@@ -131,15 +133,15 @@
131133 * @throws {Error} If the key does not exist and no default value is provided.
132134 */
133135 export function pop(obj, key, defaultValue = undefined) {
134- const value = obj[key];
135- if (value !== undefined) {
136- delete obj[key];
137- return value;
138- }
139- if (defaultValue === undefined) {
140- throw Error(`Key ${key} does not exist in object.`)
141- }
142- return defaultValue;
136+ const value = obj[key];
137+ if (value !== undefined) {
138+ delete obj[key];
139+ return value;
140+ }
141+ if (defaultValue === undefined) {
142+ throw Error(`Key ${key} does not exist in object.`);
143+ }
144+ return defaultValue;
143145 }
144146
145147 /**
@@ -149,7 +151,7 @@
149151 * @returns {Array} The merged array.
150152 */
151153 export function mergeArrays(...arrs) {
152- return Array.prototype.concat.apply([], arrs);
154+ return Array.prototype.concat.apply([], arrs);
153155 }
154156
155157 /**
@@ -159,9 +161,9 @@
159161 * @private
160162 */
161163 export function product(...a) {
162- // Cartesian product of items
163- // Adapted from https://stackoverflow.com/a/43053803
164- return a.reduce((a, b) => a.flatMap(d => b.map(e => [d, e])));
164+ // Cartesian product of items
165+ // Adapted from https://stackoverflow.com/a/43053803
166+ return a.reduce((a, b) => a.flatMap((d) => b.map((e) => [d, e])));
165167 }
166168
167169 /**
@@ -171,5 +173,5 @@
171173 * @returns {number} The index offset.
172174 */
173175 export function calculateReflectOffset(i, w) {
174- return Math.abs((i + w) % (2 * w) - w);
176+ return Math.abs(((i + w) % (2 * w)) - w);
175177 }
modified core/vendor/modules/@xenova/transformers/src/utils/data-structures.js +380 −375
@@ -1,415 +1,420 @@
1-
21 /**
32 * @file Custom data structures.
4- *
3+ *
54 * These are only used internally, meaning an end-user shouldn't
65 * need to access anything here.
7- *
6+ *
87 * @module utils/data-structures
98 */
109
11-
1210 /**
1311 * Efficient Heap-based Implementation of a Priority Queue.
1412 * It uses an array-based binary heap, where the root is at index `0`, and the
1513 * children of node `i` are located at indices `2i + 1` and `2i + 2`, respectively.
16- *
14+ *
1715 * Adapted from the following sources:
1816 * - https://stackoverflow.com/a/42919752/13989043 (original)
1917 * - https://github.com/belladoreai/llama-tokenizer-js (minor improvements)
2018 */
2119 export class PriorityQueue {
22-
23- /**
24- * Create a new PriorityQueue.
25- * @param {Function} comparator Comparator function to determine priority. Defaults to a MaxHeap.
26- */
27- constructor(comparator = (a, b) => a > b) {
28- this._heap = [];
29- this._comparator = comparator;
30- }
31-
32- /**
33- * The size of the queue
34- */
35- get size() {
36- return this._heap.length;
37- }
38-
39- /**
40- * Check if the queue is empty.
41- * @returns {boolean} `true` if the queue is empty, `false` otherwise.
42- */
43- isEmpty() {
44- return this.size === 0;
45- }
46-
47- /**
48- * Return the element with the highest priority in the queue.
49- * @returns {any} The highest priority element in the queue.
50- */
51- peek() {
52- return this._heap[0];
53- }
54-
55- /**
56- * Add one or more elements to the queue.
57- * @param {...any} values The values to push into the queue.
58- * @returns {number} The new size of the queue.
59- */
60- push(...values) {
61- return this.extend(values);
62- }
63-
64- /**
65- * Add multiple elements to the queue.
66- * @param {any[]} values The values to push into the queue.
67- * @returns {number} The new size of the queue.
68- */
69- extend(values) {
70- for (const value of values) {
71- this._heap.push(value);
72- this._siftUp();
73- }
74- return this.size;
75- }
76-
77- /**
78- * Remove and return the element with the highest priority in the queue.
79- * @returns {any} The element with the highest priority in the queue.
80- */
81- pop() {
82- const poppedValue = this.peek();
83- const bottom = this.size - 1;
84- if (bottom > 0) {
85- this._swap(0, bottom);
86- }
87- this._heap.pop();
88- this._siftDown();
89- return poppedValue;
90- }
91-
92- /**
93- * Replace the element with the highest priority in the queue with a new value.
94- * @param {*} value The new value.
95- * @returns {*} The replaced value.
96- */
97- replace(value) {
98- const replacedValue = this.peek();
99- this._heap[0] = value;
100- this._siftDown();
101- return replacedValue;
102- }
103-
104- /**
105- * Compute the index for the parent of the node at index `i`.
106- * @param {number} i The index of the node to get the parent of.
107- * @returns {number} The index of the parent node.
108- * @private
109- */
110- _parent(i) {
111- return ((i + 1) >>> 1) - 1;
112- }
113-
114- /**
115- * Compute the index for the left child of the node at index `i`.
116- * @param {number} i The index of the node to get the left child of.
117- * @returns {number} The index of the left child.
118- * @private
119- */
120- _left(i) {
121- return (i << 1) + 1;
122- }
123-
124- /**
125- * Compute the index for the right child of the node at index `i`.
126- * @param {number} i The index of the node to get the right child of.
127- * @returns {number} The index of the right child.
128- * @private
129- */
130- _right(i) {
131- return (i + 1) << 1;
132- }
133-
134- /**
135- * Check if the element at index `i` is greater than the element at index `j`.
136- * @param {number} i The index of the first element to compare.
137- * @param {number} j The index of the second element to compare.
138- * @returns {boolean} `true` if the element at index `i` is greater than the element at index `j`, `false` otherwise.
139- * @private
140- */
141- _greater(i, j) {
142- return this._comparator(this._heap[i], this._heap[j]);
143- }
144-
145- /**
146- * Swap the elements at indices `i` and `j`.
147- * @param {number} i The index of the first element to swap.
148- * @param {number} j The index of the second element to swap.
149- * @private
150- */
151- _swap(i, j) {
152- const temp = this._heap[i];
153- this._heap[i] = this._heap[j];
154- this._heap[j] = temp;
155- }
156-
157- /**
158- * Maintain the heap property by updating positions in the heap,
159- * starting at the last element and moving up the heap.
160- * @private
161- */
162- _siftUp() {
163- let node = this.size - 1;
164- while (node > 0 && this._greater(node, this._parent(node))) {
165- this._swap(node, this._parent(node));
166- node = this._parent(node);
167- }
168- }
169- /**
170- * Maintain the heap property by updating positions in the heap,
171- * starting at the first element and moving down the heap.
172- * @private
173- */
174- _siftDown() {
175- let node = 0;
176- while (
177- (this._left(node) < this.size && this._greater(this._left(node), node)) ||
178- (this._right(node) < this.size && this._greater(this._right(node), node))
179- ) {
180- const maxChild = (this._right(node) < this.size && this._greater(this._right(node), this._left(node)))
181- ? this._right(node)
182- : this._left(node);
183- this._swap(node, maxChild);
184- node = maxChild;
185- }
186- }
20+ /**
21+ * Create a new PriorityQueue.
22+ * @param {Function} comparator Comparator function to determine priority. Defaults to a MaxHeap.
23+ */
24+ constructor(comparator = (a, b) => a > b) {
25+ this._heap = [];
26+ this._comparator = comparator;
27+ }
28+
29+ /**
30+ * The size of the queue
31+ */
32+ get size() {
33+ return this._heap.length;
34+ }
35+
36+ /**
37+ * Check if the queue is empty.
38+ * @returns {boolean} `true` if the queue is empty, `false` otherwise.
39+ */
40+ isEmpty() {
41+ return this.size === 0;
42+ }
43+
44+ /**
45+ * Return the element with the highest priority in the queue.
46+ * @returns {any} The highest priority element in the queue.
47+ */
48+ peek() {
49+ return this._heap[0];
50+ }
51+
52+ /**
53+ * Add one or more elements to the queue.
54+ * @param {...any} values The values to push into the queue.
55+ * @returns {number} The new size of the queue.
56+ */
57+ push(...values) {
58+ return this.extend(values);
59+ }
60+
61+ /**
62+ * Add multiple elements to the queue.
63+ * @param {any[]} values The values to push into the queue.
64+ * @returns {number} The new size of the queue.
65+ */
66+ extend(values) {
67+ for (const value of values) {
68+ this._heap.push(value);
69+ this._siftUp();
70+ }
71+ return this.size;
72+ }
73+
74+ /**
75+ * Remove and return the element with the highest priority in the queue.
76+ * @returns {any} The element with the highest priority in the queue.
77+ */
78+ pop() {
79+ const poppedValue = this.peek();
80+ const bottom = this.size - 1;
81+ if (bottom > 0) {
82+ this._swap(0, bottom);
83+ }
84+ this._heap.pop();
85+ this._siftDown();
86+ return poppedValue;
87+ }
88+
89+ /**
90+ * Replace the element with the highest priority in the queue with a new value.
91+ * @param {*} value The new value.
92+ * @returns {*} The replaced value.
93+ */
94+ replace(value) {
95+ const replacedValue = this.peek();
96+ this._heap[0] = value;
97+ this._siftDown();
98+ return replacedValue;
99+ }
100+
101+ /**
102+ * Compute the index for the parent of the node at index `i`.
103+ * @param {number} i The index of the node to get the parent of.
104+ * @returns {number} The index of the parent node.
105+ * @private
106+ */
107+ _parent(i) {
108+ return ((i + 1) >>> 1) - 1;
109+ }
110+
111+ /**
112+ * Compute the index for the left child of the node at index `i`.
113+ * @param {number} i The index of the node to get the left child of.
114+ * @returns {number} The index of the left child.
115+ * @private
116+ */
117+ _left(i) {
118+ return (i << 1) + 1;
119+ }
120+
121+ /**
122+ * Compute the index for the right child of the node at index `i`.
123+ * @param {number} i The index of the node to get the right child of.
124+ * @returns {number} The index of the right child.
125+ * @private
126+ */
127+ _right(i) {
128+ return (i + 1) << 1;
129+ }
130+
131+ /**
132+ * Check if the element at index `i` is greater than the element at index `j`.
133+ * @param {number} i The index of the first element to compare.
134+ * @param {number} j The index of the second element to compare.
135+ * @returns {boolean} `true` if the element at index `i` is greater than the element at index `j`, `false` otherwise.
136+ * @private
137+ */
138+ _greater(i, j) {
139+ return this._comparator(this._heap[i], this._heap[j]);
140+ }
141+
142+ /**
143+ * Swap the elements at indices `i` and `j`.
144+ * @param {number} i The index of the first element to swap.
145+ * @param {number} j The index of the second element to swap.
146+ * @private
147+ */
148+ _swap(i, j) {
149+ const temp = this._heap[i];
150+ this._heap[i] = this._heap[j];
151+ this._heap[j] = temp;
152+ }
153+
154+ /**
155+ * Maintain the heap property by updating positions in the heap,
156+ * starting at the last element and moving up the heap.
157+ * @private
158+ */
159+ _siftUp() {
160+ let node = this.size - 1;
161+ while (node > 0 && this._greater(node, this._parent(node))) {
162+ this._swap(node, this._parent(node));
163+ node = this._parent(node);
164+ }
165+ }
166+ /**
167+ * Maintain the heap property by updating positions in the heap,
168+ * starting at the first element and moving down the heap.
169+ * @private
170+ */
171+ _siftDown() {
172+ let node = 0;
173+ while (
174+ (this._left(node) < this.size && this._greater(this._left(node), node)) ||
175+ (this._right(node) < this.size && this._greater(this._right(node), node))
176+ ) {
177+ const maxChild =
178+ this._right(node) < this.size &&
179+ this._greater(this._right(node), this._left(node))
180+ ? this._right(node)
181+ : this._left(node);
182+ this._swap(node, maxChild);
183+ node = maxChild;
184+ }
185+ }
187186 }
188187
189188 /**
190189 * A trie structure to efficiently store and search for strings.
191190 */
192191 export class CharTrie {
193- constructor() {
194- this.root = CharTrieNode.default();
195- }
196-
197- /**
198- * Adds one or more `texts` to the trie.
199- * @param {string[]} texts The strings to add to the trie.
200- */
201- extend(texts) {
202- for (let text of texts) {
203- this.push(text);
204- }
205- }
206-
207- /**
208- * Adds text to the trie.
209- * @param {string} text The string to add to the trie.
210- */
211- push(text) {
212- let node = this.root;
213- for (let ch of text) {
214- let child = node.children.get(ch);
215- if (child === undefined) {
216- child = CharTrieNode.default();
217- node.children.set(ch, child);
218- }
219- node = child;
220- }
221- node.isLeaf = true;
222- }
223-
224- /**
225- * Searches the trie for all strings with a common prefix of `text`.
226- * @param {string} text The common prefix to search for.
227- * @yields {string} Each string in the trie that has `text` as a prefix.
228- */
229- *commonPrefixSearch(text) {
230- let node = this.root;
231- let prefix = "";
232- for (let i = 0; i < text.length && node !== undefined; ++i) {
233- const ch = text[i];
234- prefix += ch;
235- node = node.children.get(ch);
236- if (node !== undefined && node.isLeaf) {
237- yield prefix;
238- }
239- }
240- }
192+ constructor() {
193+ this.root = CharTrieNode.default();
194+ }
195+
196+ /**
197+ * Adds one or more `texts` to the trie.
198+ * @param {string[]} texts The strings to add to the trie.
199+ */
200+ extend(texts) {
201+ for (let text of texts) {
202+ this.push(text);
203+ }
204+ }
205+
206+ /**
207+ * Adds text to the trie.
208+ * @param {string} text The string to add to the trie.
209+ */
210+ push(text) {
211+ let node = this.root;
212+ for (let ch of text) {
213+ let child = node.children.get(ch);
214+ if (child === undefined) {
215+ child = CharTrieNode.default();
216+ node.children.set(ch, child);
217+ }
218+ node = child;
219+ }
220+ node.isLeaf = true;
221+ }
222+
223+ /**
224+ * Searches the trie for all strings with a common prefix of `text`.
225+ * @param {string} text The common prefix to search for.
226+ * @yields {string} Each string in the trie that has `text` as a prefix.
227+ */
228+ *commonPrefixSearch(text) {
229+ let node = this.root;
230+ let prefix = "";
231+ for (let i = 0; i < text.length && node !== undefined; ++i) {
232+ const ch = text[i];
233+ prefix += ch;
234+ node = node.children.get(ch);
235+ if (node !== undefined && node.isLeaf) {
236+ yield prefix;
237+ }
238+ }
239+ }
241240 }
242241
243242 /**
244243 * Represents a node in a character trie.
245244 */
246245 class CharTrieNode {
247- /**
248- * Create a new CharTrieNode.
249- * @param {boolean} isLeaf Whether the node is a leaf node or not.
250- * @param {Map<string, CharTrieNode>} children A map containing the node's children, where the key is a character and the value is a `CharTrieNode`.
251- */
252- constructor(isLeaf, children) {
253- this.isLeaf = isLeaf;
254- this.children = children;
255- }
256-
257- /**
258- * Returns a new `CharTrieNode` instance with default values.
259- * @returns {CharTrieNode} A new `CharTrieNode` instance with `isLeaf` set to `false` and an empty `children` map.
260- */
261- static default() {
262- return new CharTrieNode(false, new Map());
263- }
246+ /**
247+ * Create a new CharTrieNode.
248+ * @param {boolean} isLeaf Whether the node is a leaf node or not.
249+ * @param {Map<string, CharTrieNode>} children A map containing the node's children, where the key is a character and the value is a `CharTrieNode`.
250+ */
251+ constructor(isLeaf, children) {
252+ this.isLeaf = isLeaf;
253+ this.children = children;
254+ }
255+
256+ /**
257+ * Returns a new `CharTrieNode` instance with default values.
258+ * @returns {CharTrieNode} A new `CharTrieNode` instance with `isLeaf` set to `false` and an empty `children` map.
259+ */
260+ static default() {
261+ return new CharTrieNode(false, new Map());
262+ }
264263 }
265264
266265 /**
267266 * A lattice data structure to be used for tokenization.
268267 */
269268 export class TokenLattice {
270- /**
271- * Creates a new TokenLattice instance.
272- *
273- * @param {string} sentence The input sentence to be tokenized.
274- * @param {number} bosTokenId The beginning-of-sequence token ID.
275- * @param {number} eosTokenId The end-of-sequence token ID.
276- */
277- constructor(sentence, bosTokenId, eosTokenId) {
278- this.sentence = sentence;
279- this.len = sentence.length;
280- this.bosTokenId = bosTokenId;
281- this.eosTokenId = eosTokenId;
282- this.nodes = [];
283- this.beginNodes = Array.from({ length: this.len + 1 }, () => []);
284- this.endNodes = Array.from({ length: this.len + 1 }, () => []);
285-
286- const bos = new TokenLatticeNode(this.bosTokenId, 0, 0, 0, 0.0);
287- const eos = new TokenLatticeNode(this.eosTokenId, 1, this.len, 0, 0.0);
288- this.nodes.push(bos.clone());
289- this.nodes.push(eos.clone());
290- this.beginNodes[this.len].push(eos);
291- this.endNodes[0].push(bos);
292- }
293-
294- /**
295- * Inserts a new token node into the token lattice.
296- *
297- * @param {number} pos The starting position of the token.
298- * @param {number} length The length of the token.
299- * @param {number} score The score of the token.
300- * @param {number} tokenId The token ID of the token.
301- */
302- insert(pos, length, score, tokenId) {
303- const nodeId = this.nodes.length;
304- const node = new TokenLatticeNode(tokenId, nodeId, pos, length, score);
305- this.beginNodes[pos].push(node);
306- this.endNodes[pos + length].push(node);
307- this.nodes.push(node);
308- }
309-
310- /**
311- * Implements the Viterbi algorithm to compute the most likely sequence of tokens.
312- *
313- * @returns {TokenLatticeNode[]} The array of nodes representing the most likely sequence of tokens.
314- */
315- viterbi() {
316- const len = this.len;
317- let pos = 0;
318- while (pos <= len) {
319- if (this.beginNodes[pos].length == 0) {
320- return [];
321- }
322- for (let rnode of this.beginNodes[pos]) {
323- rnode.prev = null;
324- let bestScore = 0.0;
325- let bestNode = null;
326- for (let lnode of this.endNodes[pos]) {
327- const score = lnode.backtraceScore + rnode.score;
328- if (bestNode === null || score > bestScore) {
329- bestNode = lnode.clone();
330- bestScore = score;
331- }
332- }
333-
334- if (bestNode !== null) {
335- rnode.prev = bestNode;
336- rnode.backtraceScore = bestScore;
337- } else {
338- return [];
339- }
340- }
341- ++pos;
269+ /**
270+ * Creates a new TokenLattice instance.
271+ *
272+ * @param {string} sentence The input sentence to be tokenized.
273+ * @param {number} bosTokenId The beginning-of-sequence token ID.
274+ * @param {number} eosTokenId The end-of-sequence token ID.
275+ */
276+ constructor(sentence, bosTokenId, eosTokenId) {
277+ this.sentence = sentence;
278+ this.len = sentence.length;
279+ this.bosTokenId = bosTokenId;
280+ this.eosTokenId = eosTokenId;
281+ this.nodes = [];
282+ this.beginNodes = Array.from({ length: this.len + 1 }, () => []);
283+ this.endNodes = Array.from({ length: this.len + 1 }, () => []);
284+
285+ const bos = new TokenLatticeNode(this.bosTokenId, 0, 0, 0, 0.0);
286+ const eos = new TokenLatticeNode(this.eosTokenId, 1, this.len, 0, 0.0);
287+ this.nodes.push(bos.clone());
288+ this.nodes.push(eos.clone());
289+ this.beginNodes[this.len].push(eos);
290+ this.endNodes[0].push(bos);
291+ }
292+
293+ /**
294+ * Inserts a new token node into the token lattice.
295+ *
296+ * @param {number} pos The starting position of the token.
297+ * @param {number} length The length of the token.
298+ * @param {number} score The score of the token.
299+ * @param {number} tokenId The token ID of the token.
300+ */
301+ insert(pos, length, score, tokenId) {
302+ const nodeId = this.nodes.length;
303+ const node = new TokenLatticeNode(tokenId, nodeId, pos, length, score);
304+ this.beginNodes[pos].push(node);
305+ this.endNodes[pos + length].push(node);
306+ this.nodes.push(node);
307+ }
308+
309+ /**
310+ * Implements the Viterbi algorithm to compute the most likely sequence of tokens.
311+ *
312+ * @returns {TokenLatticeNode[]} The array of nodes representing the most likely sequence of tokens.
313+ */
314+ viterbi() {
315+ const len = this.len;
316+ let pos = 0;
317+ while (pos <= len) {
318+ if (this.beginNodes[pos].length == 0) {
319+ return [];
320+ }
321+ for (let rnode of this.beginNodes[pos]) {
322+ rnode.prev = null;
323+ let bestScore = 0.0;
324+ let bestNode = null;
325+ for (let lnode of this.endNodes[pos]) {
326+ const score = lnode.backtraceScore + rnode.score;
327+ if (bestNode === null || score > bestScore) {
328+ bestNode = lnode.clone();
329+ bestScore = score;
330+ }
342331 }
343332
344- const results = [];
345- const root = this.beginNodes[len][0];
346- const prev = root.prev;
347- if (prev === null) {
348- return [];
333+ if (bestNode !== null) {
334+ rnode.prev = bestNode;
335+ rnode.backtraceScore = bestScore;
336+ } else {
337+ return [];
349338 }
350-
351- let node = prev.clone();
352- while (node.prev !== null) {
353- results.push(node.clone());
354- const n = node.clone();
355- node = n.prev.clone();
356- }
357-
358- results.reverse();
359- return results;
360- }
361-
362- /**
363- * @param {TokenLatticeNode} node
364- * @returns {string} The array of nodes representing the most likely sequence of tokens.
365- */
366- piece(node) {
367- return this.sentence.slice(node.pos, node.pos + node.length);
368- }
369-
370- /**
371- * @returns {Array} The array of nodes representing the most likely sequence of tokens.
372- */
373- tokens() {
374- const nodes = this.viterbi();
375- return nodes.map(x => this.piece(x));
376- }
377-
378- /**
379- * @returns {Array} The array of nodes representing the most likely sequence of tokens.
380- */
381- tokenIds() {
382- const nodes = this.viterbi();
383- return nodes.map(x => x.tokenId);
384- }
339+ }
340+ ++pos;
341+ }
342+
343+ const results = [];
344+ const root = this.beginNodes[len][0];
345+ const prev = root.prev;
346+ if (prev === null) {
347+ return [];
348+ }
349+
350+ let node = prev.clone();
351+ while (node.prev !== null) {
352+ results.push(node.clone());
353+ const n = node.clone();
354+ node = n.prev.clone();
355+ }
356+
357+ results.reverse();
358+ return results;
359+ }
360+
361+ /**
362+ * @param {TokenLatticeNode} node
363+ * @returns {string} The array of nodes representing the most likely sequence of tokens.
364+ */
365+ piece(node) {
366+ return this.sentence.slice(node.pos, node.pos + node.length);
367+ }
368+
369+ /**
370+ * @returns {Array} The array of nodes representing the most likely sequence of tokens.
371+ */
372+ tokens() {
373+ const nodes = this.viterbi();
374+ return nodes.map((x) => this.piece(x));
375+ }
376+
377+ /**
378+ * @returns {Array} The array of nodes representing the most likely sequence of tokens.
379+ */
380+ tokenIds() {
381+ const nodes = this.viterbi();
382+ return nodes.map((x) => x.tokenId);
383+ }
385384 }
386385 class TokenLatticeNode {
387- /**
388- * Represents a node in a token lattice for a given sentence.
389- * @param {number} tokenId The ID of the token associated with this node.
390- * @param {number} nodeId The ID of this node.
391- * @param {number} pos The starting position of the token in the sentence.
392- * @param {number} length The length of the token.
393- * @param {number} score The score associated with the token.
394- */
395- constructor(tokenId, nodeId, pos, length, score) {
396- this.tokenId = tokenId;
397- this.nodeId = nodeId;
398- this.pos = pos;
399- this.length = length;
400- this.score = score;
401- this.prev = null;
402- this.backtraceScore = 0.0;
403- }
404-
405- /**
406- * Returns a clone of this node.
407- * @returns {TokenLatticeNode} A clone of this node.
408- */
409- clone() {
410- const n = new TokenLatticeNode(this.tokenId, this.nodeId, this.pos, this.length, this.score);
411- n.prev = this.prev;
412- n.backtraceScore = this.backtraceScore;
413- return n;
414- }
386+ /**
387+ * Represents a node in a token lattice for a given sentence.
388+ * @param {number} tokenId The ID of the token associated with this node.
389+ * @param {number} nodeId The ID of this node.
390+ * @param {number} pos The starting position of the token in the sentence.
391+ * @param {number} length The length of the token.
392+ * @param {number} score The score associated with the token.
393+ */
394+ constructor(tokenId, nodeId, pos, length, score) {
395+ this.tokenId = tokenId;
396+ this.nodeId = nodeId;
397+ this.pos = pos;
398+ this.length = length;
399+ this.score = score;
400+ this.prev = null;
401+ this.backtraceScore = 0.0;
402+ }
403+
404+ /**
405+ * Returns a clone of this node.
406+ * @returns {TokenLatticeNode} A clone of this node.
407+ */
408+ clone() {
409+ const n = new TokenLatticeNode(
410+ this.tokenId,
411+ this.nodeId,
412+ this.pos,
413+ this.length,
414+ this.score,
415+ );
416+ n.prev = this.prev;
417+ n.backtraceScore = this.backtraceScore;
418+ return n;
419+ }
415420 }
modified core/vendor/modules/@xenova/transformers/src/utils/generation.js +712 −692
@@ -1,22 +1,13 @@
1-
21 /**
32 * @file Classes, functions, and utilities for generation.
4- *
3+ *
54 * @todo Describe how to create a custom `GenerationConfig`.
6- *
5+ *
76 * @module utils/generation
87 */
9-import { Tensor } from './tensor.js';
10-import {
11- Callable,
12- exists,
13-} from './core.js';
14-import {
15- max,
16- softmax,
17- log_softmax,
18- getTopItems,
19-} from './maths.js';
8+import { Tensor } from "./tensor.js";
9+import { Callable, exists } from "./core.js";
10+import { max, softmax, log_softmax, getTopItems } from "./maths.js";
2011
2112 /**
2213 * A class representing a list of logits processors. A logits processor is a function that modifies the logits
@@ -26,53 +17,51 @@
2617 * @extends Callable
2718 */
2819 export class LogitsProcessorList extends Callable {
29- /**
30- * Constructs a new instance of `LogitsProcessorList`.
31- */
32- constructor() {
33- super();
34- this.processors = [];
35- }
36-
37- /**
38- * Adds a new logits processor to the list.
39- *
40- * @param {LogitsProcessor} item The logits processor function to add.
41- */
42- push(item) {
43- this.processors.push(item);
44- }
45-
46- /**
47- * Adds multiple logits processors to the list.
48- *
49- * @param {LogitsProcessor[]} items The logits processor functions to add.
50- */
51- extend(items) {
52- this.processors.push(...items);
53- }
54-
55- /**
56- * Applies all logits processors in the list to a batch of logits, modifying them in-place.
57- *
58- * @param {number[]} input_ids The input IDs for the language model.
59- * @param {number[][]} batchedLogits A 2D array of logits, where each row corresponds to a single
60- * input sequence in the batch.
61- */
62- _call(input_ids, batchedLogits) {
63- // NOTE: This is different from the Python code, since vanilla JS does not support vectorized operations.
64- // As a result, we apply each processor to each item in the batch.
65- for (let logits of batchedLogits) {
66- // Modifies logits inplace
67- this.processors.forEach(
68- func => func(input_ids, logits)
69- )
70- }
71- }
72-
73- [Symbol.iterator]() {
74- return this.processors.values();
75- }
20+ /**
21+ * Constructs a new instance of `LogitsProcessorList`.
22+ */
23+ constructor() {
24+ super();
25+ this.processors = [];
26+ }
27+
28+ /**
29+ * Adds a new logits processor to the list.
30+ *
31+ * @param {LogitsProcessor} item The logits processor function to add.
32+ */
33+ push(item) {
34+ this.processors.push(item);
35+ }
36+
37+ /**
38+ * Adds multiple logits processors to the list.
39+ *
40+ * @param {LogitsProcessor[]} items The logits processor functions to add.
41+ */
42+ extend(items) {
43+ this.processors.push(...items);
44+ }
45+
46+ /**
47+ * Applies all logits processors in the list to a batch of logits, modifying them in-place.
48+ *
49+ * @param {number[]} input_ids The input IDs for the language model.
50+ * @param {number[][]} batchedLogits A 2D array of logits, where each row corresponds to a single
51+ * input sequence in the batch.
52+ */
53+ _call(input_ids, batchedLogits) {
54+ // NOTE: This is different from the Python code, since vanilla JS does not support vectorized operations.
55+ // As a result, we apply each processor to each item in the batch.
56+ for (let logits of batchedLogits) {
57+ // Modifies logits inplace
58+ this.processors.forEach((func) => func(input_ids, logits));
59+ }
60+ }
61+
62+ [Symbol.iterator]() {
63+ return this.processors.values();
64+ }
7665 }
7766
7867 /**
@@ -80,50 +69,51 @@
8069 * @extends Callable
8170 */
8271 export class LogitsProcessor extends Callable {
83- /**
84- * Apply the processor to the input logits.
85- *
86- * @abstract
87- * @param {Array} input_ids The input ids.
88- * @param {Tensor} logits The logits to process.
89- * @throws {Error} Throws an error if `_call` is not implemented in the subclass.
90- */
91- _call(input_ids, logits) {
92- throw Error("`_call` should be implemented in a subclass")
93- }
72+ /**
73+ * Apply the processor to the input logits.
74+ *
75+ * @abstract
76+ * @param {Array} input_ids The input ids.
77+ * @param {Tensor} logits The logits to process.
78+ * @throws {Error} Throws an error if `_call` is not implemented in the subclass.
79+ */
80+ _call(input_ids, logits) {
81+ throw Error("`_call` should be implemented in a subclass");
82+ }
9483 }
9584
9685 /**
9786 * A logits processor that forces a specific token to be generated by the decoder.
98- *
87+ *
9988 * @extends LogitsProcessor
10089 */
10190 export class ForceTokensLogitsProcessor extends LogitsProcessor {
102- /**
103- * Constructs a new instance of `ForceTokensLogitsProcessor`.
104- *
105- * @param {Array} forced_decoder_ids The ids of tokens that should be forced.
106- */
107- constructor(forced_decoder_ids) {
108- super();
109- this.force_token_map = Object.fromEntries(forced_decoder_ids ?? []);
110- }
111-
112- /**
113- * Apply the processor to the input logits.
114- *
115- * @param {Array} input_ids The input ids.
116- * @param {Tensor} logits The logits to process.
117- * @returns {Tensor} The processed logits.
118- */
119- _call(input_ids, logits) {
120- let map = this.force_token_map[input_ids.length];
121- if (exists(map)) { // There exists a mapping
122- logits.data.fill(-Infinity)
123- logits.data[map] = 0;
124- }
125- return logits;
126- }
91+ /**
92+ * Constructs a new instance of `ForceTokensLogitsProcessor`.
93+ *
94+ * @param {Array} forced_decoder_ids The ids of tokens that should be forced.
95+ */
96+ constructor(forced_decoder_ids) {
97+ super();
98+ this.force_token_map = Object.fromEntries(forced_decoder_ids ?? []);
99+ }
100+
101+ /**
102+ * Apply the processor to the input logits.
103+ *
104+ * @param {Array} input_ids The input ids.
105+ * @param {Tensor} logits The logits to process.
106+ * @returns {Tensor} The processed logits.
107+ */
108+ _call(input_ids, logits) {
109+ let map = this.force_token_map[input_ids.length];
110+ if (exists(map)) {
111+ // There exists a mapping
112+ logits.data.fill(-Infinity);
113+ logits.data[map] = 0;
114+ }
115+ return logits;
116+ }
127117 }
128118
129119 /**
@@ -131,57 +121,57 @@
131121 * @extends LogitsProcessor
132122 */
133123 export class ForcedBOSTokenLogitsProcessor extends LogitsProcessor {
134- /**
135- * Create a ForcedBOSTokenLogitsProcessor.
136- * @param {number} bos_token_id The ID of the beginning-of-sequence token to be forced.
137- */
138- constructor(bos_token_id) {
139- super();
140- this.bos_token_id = bos_token_id;
141- }
142-
143- /**
144- * Apply the BOS token forcing to the logits.
145- * @param {Array} input_ids The input IDs.
146- * @param {Object} logits The logits.
147- * @returns {Object} The logits with BOS token forcing.
148- */
149- _call(input_ids, logits) {
150- if (input_ids.length === 1) {
151- logits.data.fill(-Infinity)
152- logits.data[this.bos_token_id] = 0;
153- }
154- return logits;
155- }
124+ /**
125+ * Create a ForcedBOSTokenLogitsProcessor.
126+ * @param {number} bos_token_id The ID of the beginning-of-sequence token to be forced.
127+ */
128+ constructor(bos_token_id) {
129+ super();
130+ this.bos_token_id = bos_token_id;
131+ }
132+
133+ /**
134+ * Apply the BOS token forcing to the logits.
135+ * @param {Array} input_ids The input IDs.
136+ * @param {Object} logits The logits.
137+ * @returns {Object} The logits with BOS token forcing.
138+ */
139+ _call(input_ids, logits) {
140+ if (input_ids.length === 1) {
141+ logits.data.fill(-Infinity);
142+ logits.data[this.bos_token_id] = 0;
143+ }
144+ return logits;
145+ }
156146 }
157147
158148 /**
159149 * A logits processor that forces end-of-sequence token probability to 1.
160- *
150+ *
161151 * @extends LogitsProcessor
162152 */
163153 export class ForcedEOSTokenLogitsProcessor extends LogitsProcessor {
164- /**
165- * Create a ForcedEOSTokenLogitsProcessor.
166- * @param {number} max_length Max length of the sequence.
167- * @param {number|number[]} forced_eos_token_id The ID of the end-of-sequence token to be forced.
168- */
169- constructor(max_length, forced_eos_token_id) {
170- super();
171- this.max_length = max_length;
172- this.forced_eos_token_id = forced_eos_token_id;
173- }
174-
175- /**
176- * Apply the processor to input_ids and logits.
177- *
178- * @param {number[]} input_ids The input ids.
179- * @param {Tensor} logits The logits tensor.
180- */
181- _call(input_ids, logits) {
182- // console.log('call ForcedEOSTokenLogitsProcessor')
183- // TODO
184- }
154+ /**
155+ * Create a ForcedEOSTokenLogitsProcessor.
156+ * @param {number} max_length Max length of the sequence.
157+ * @param {number|number[]} forced_eos_token_id The ID of the end-of-sequence token to be forced.
158+ */
159+ constructor(max_length, forced_eos_token_id) {
160+ super();
161+ this.max_length = max_length;
162+ this.forced_eos_token_id = forced_eos_token_id;
163+ }
164+
165+ /**
166+ * Apply the processor to input_ids and logits.
167+ *
168+ * @param {number[]} input_ids The input ids.
169+ * @param {Tensor} logits The logits tensor.
170+ */
171+ _call(input_ids, logits) {
172+ // console.log('call ForcedEOSTokenLogitsProcessor')
173+ // TODO
174+ }
185175 }
186176
187177 /**
@@ -191,31 +181,31 @@
191181 * @extends LogitsProcessor
192182 */
193183 export class SuppressTokensAtBeginLogitsProcessor extends LogitsProcessor {
194- /**
195- * Create a SuppressTokensAtBeginLogitsProcessor.
196- * @param {number[]} begin_suppress_tokens The IDs of the tokens to suppress.
197- * @param {number} begin_index The number of tokens to generate before suppressing tokens.
198- */
199- constructor(begin_suppress_tokens, begin_index) {
200- super();
201- this.begin_suppress_tokens = begin_suppress_tokens;
202- this.begin_index = begin_index;
203- }
204-
205- /**
206- * Apply the BOS token forcing to the logits.
207- * @param {Array} input_ids The input IDs.
208- * @param {Object} logits The logits.
209- * @returns {Object} The logits with BOS token forcing.
210- */
211- _call(input_ids, logits) {
212- if (input_ids.length === this.begin_index) {
213- for (let token_id of this.begin_suppress_tokens) {
214- logits.data[token_id] = -Infinity;
215- }
216- }
217- return logits;
218- }
184+ /**
185+ * Create a SuppressTokensAtBeginLogitsProcessor.
186+ * @param {number[]} begin_suppress_tokens The IDs of the tokens to suppress.
187+ * @param {number} begin_index The number of tokens to generate before suppressing tokens.
188+ */
189+ constructor(begin_suppress_tokens, begin_index) {
190+ super();
191+ this.begin_suppress_tokens = begin_suppress_tokens;
192+ this.begin_index = begin_index;
193+ }
194+
195+ /**
196+ * Apply the BOS token forcing to the logits.
197+ * @param {Array} input_ids The input IDs.
198+ * @param {Object} logits The logits.
199+ * @returns {Object} The logits with BOS token forcing.
200+ */
201+ _call(input_ids, logits) {
202+ if (input_ids.length === this.begin_index) {
203+ for (let token_id of this.begin_suppress_tokens) {
204+ logits.data[token_id] = -Infinity;
205+ }
206+ }
207+ return logits;
208+ }
219209 }
220210
221211 /**
@@ -223,317 +213,348 @@
223213 * @extends LogitsProcessor
224214 */
225215 export class WhisperTimeStampLogitsProcessor extends LogitsProcessor {
226- /**
227- * Constructs a new WhisperTimeStampLogitsProcessor.
228- * @param {Object} generate_config The config object passed to the `generate()` method of a transformer model.
229- * @param {number} generate_config.eos_token_id The ID of the end-of-sequence token.
230- * @param {number} generate_config.no_timestamps_token_id The ID of the token used to indicate that a token should not have a timestamp.
231- * @param {number[][]} [generate_config.forced_decoder_ids] An array of two-element arrays representing decoder IDs that are forced to appear in the output. The second element of each array indicates whether the token is a timestamp.
232- * @param {number} [generate_config.max_initial_timestamp_index] The maximum index at which an initial timestamp can appear.
233- */
234- constructor(generate_config) {
235- super();
236- this.eos_token_id = generate_config.eos_token_id;
237- this.no_timestamps_token_id = generate_config.no_timestamps_token_id;
238- this.timestamp_begin = this.no_timestamps_token_id + 1;
239-
240- this.begin_index = (generate_config.forced_decoder_ids || []).length + 2;
241- if (generate_config.forced_decoder_ids.slice(-1)[0][1] === this.no_timestamps_token_id) {
242- this.begin_index -= 1;
243- }
244- this.max_initial_timestamp_index = generate_config.max_initial_timestamp_index;
245-
246- }
247-
248- /**
249- * Modify the logits to handle timestamp tokens.
250- * @param {Array} input_ids The input sequence of tokens.
251- * @param {Tensor} logits The logits output by the model.
252- * @returns {Tensor} The modified logits.
253- */
254- _call(input_ids, logits) {
255- const logitsData = /** @type {Float32Array} */(logits.data);
256-
257- // suppress <|notimestamps|> which is handled by without_timestamps
258- logitsData[this.no_timestamps_token_id] = -Infinity;
259-
260- if (input_ids.length === this.begin_index - 1) {
261- logitsData.fill(-Infinity);
262- logitsData[this.timestamp_begin] = 0;
263- return logits;
264- }
265-
266- // timestamps have to appear in pairs, except directly before eos_token; mask logits accordingly
267- const seq = input_ids.slice(this.begin_index);
268- const last_was_timestamp = seq.length >= 1 && seq[seq.length - 1] >= this.timestamp_begin;
269- const penultimate_was_timestamp = seq.length < 2 || seq[seq.length - 2] >= this.timestamp_begin;
270-
271- if (last_was_timestamp) {
272- if (penultimate_was_timestamp) { // has to be non-timestamp
273- logitsData.subarray(this.timestamp_begin).fill(-Infinity);
274- } else { // cannot be normal text tokens
275- logitsData.subarray(0, this.eos_token_id).fill(-Infinity);
276- }
277- }
278-
279- // apply the `max_initial_timestamp` option
280- if (input_ids.length === this.begin_index && this.max_initial_timestamp_index !== null) {
281- const last_allowed = this.timestamp_begin + this.max_initial_timestamp_index;
282- logitsData.subarray(last_allowed + 1).fill(-Infinity);
283- }
284-
285- // if sum of probability over timestamps is above any other token, sample timestamp
286- const logprobs = log_softmax(logitsData);
287- const timestamp_logprob = Math.log(logprobs.subarray(this.timestamp_begin).map(Math.exp).reduce((a, b) => a + b));
288- const max_text_token_logprob = max(logprobs.subarray(0, this.timestamp_begin))[0];
289-
290- if (timestamp_logprob > max_text_token_logprob) {
291- logitsData.subarray(0, this.timestamp_begin).fill(-Infinity);
292- }
293-
294- return logits;
295- }
216+ /**
217+ * Constructs a new WhisperTimeStampLogitsProcessor.
218+ * @param {Object} generate_config The config object passed to the `generate()` method of a transformer model.
219+ * @param {number} generate_config.eos_token_id The ID of the end-of-sequence token.
220+ * @param {number} generate_config.no_timestamps_token_id The ID of the token used to indicate that a token should not have a timestamp.
221+ * @param {number[][]} [generate_config.forced_decoder_ids] An array of two-element arrays representing decoder IDs that are forced to appear in the output. The second element of each array indicates whether the token is a timestamp.
222+ * @param {number} [generate_config.max_initial_timestamp_index] The maximum index at which an initial timestamp can appear.
223+ */
224+ constructor(generate_config) {
225+ super();
226+ this.eos_token_id = generate_config.eos_token_id;
227+ this.no_timestamps_token_id = generate_config.no_timestamps_token_id;
228+ this.timestamp_begin = this.no_timestamps_token_id + 1;
229+
230+ this.begin_index = (generate_config.forced_decoder_ids || []).length + 2;
231+ if (
232+ generate_config.forced_decoder_ids.slice(-1)[0][1] ===
233+ this.no_timestamps_token_id
234+ ) {
235+ this.begin_index -= 1;
236+ }
237+ this.max_initial_timestamp_index =
238+ generate_config.max_initial_timestamp_index;
239+ }
240+
241+ /**
242+ * Modify the logits to handle timestamp tokens.
243+ * @param {Array} input_ids The input sequence of tokens.
244+ * @param {Tensor} logits The logits output by the model.
245+ * @returns {Tensor} The modified logits.
246+ */
247+ _call(input_ids, logits) {
248+ const logitsData = /** @type {Float32Array} */ (logits.data);
249+
250+ // suppress <|notimestamps|> which is handled by without_timestamps
251+ logitsData[this.no_timestamps_token_id] = -Infinity;
252+
253+ if (input_ids.length === this.begin_index - 1) {
254+ logitsData.fill(-Infinity);
255+ logitsData[this.timestamp_begin] = 0;
256+ return logits;
257+ }
258+
259+ // timestamps have to appear in pairs, except directly before eos_token; mask logits accordingly
260+ const seq = input_ids.slice(this.begin_index);
261+ const last_was_timestamp =
262+ seq.length >= 1 && seq[seq.length - 1] >= this.timestamp_begin;
263+ const penultimate_was_timestamp =
264+ seq.length < 2 || seq[seq.length - 2] >= this.timestamp_begin;
265+
266+ if (last_was_timestamp) {
267+ if (penultimate_was_timestamp) {
268+ // has to be non-timestamp
269+ logitsData.subarray(this.timestamp_begin).fill(-Infinity);
270+ } else {
271+ // cannot be normal text tokens
272+ logitsData.subarray(0, this.eos_token_id).fill(-Infinity);
273+ }
274+ }
275+
276+ // apply the `max_initial_timestamp` option
277+ if (
278+ input_ids.length === this.begin_index &&
279+ this.max_initial_timestamp_index !== null
280+ ) {
281+ const last_allowed =
282+ this.timestamp_begin + this.max_initial_timestamp_index;
283+ logitsData.subarray(last_allowed + 1).fill(-Infinity);
284+ }
285+
286+ // if sum of probability over timestamps is above any other token, sample timestamp
287+ const logprobs = log_softmax(logitsData);
288+ const timestamp_logprob = Math.log(
289+ logprobs
290+ .subarray(this.timestamp_begin)
291+ .map(Math.exp)
292+ .reduce((a, b) => a + b),
293+ );
294+ const max_text_token_logprob = max(
295+ logprobs.subarray(0, this.timestamp_begin),
296+ )[0];
297+
298+ if (timestamp_logprob > max_text_token_logprob) {
299+ logitsData.subarray(0, this.timestamp_begin).fill(-Infinity);
300+ }
301+
302+ return logits;
303+ }
296304 }
297305
298306 /**
299307 * A logits processor that disallows ngrams of a certain size to be repeated.
300- *
308+ *
301309 * @extends LogitsProcessor
302310 */
303311 export class NoRepeatNGramLogitsProcessor extends LogitsProcessor {
304- /**
305- * Create a NoRepeatNGramLogitsProcessor.
306- * @param {number} no_repeat_ngram_size The no-repeat-ngram size. All ngrams of this size can only occur once.
307- */
308- constructor(no_repeat_ngram_size) {
309- super();
310- this.no_repeat_ngram_size = no_repeat_ngram_size;
311- }
312-
313- /**
314- * Generate n-grams from a sequence of token ids.
315- * @param {number[]} prevInputIds List of previous input ids
316- * @returns {Map<string, number[]>} Map of generated n-grams
317- */
318- getNgrams(prevInputIds) {
319- const curLen = prevInputIds.length;
320-
321- /**@type {number[][]} */
322- const ngrams = [];
323- for (let j = 0; j < curLen + 1 - this.no_repeat_ngram_size; ++j) {
324- const ngram = [];
325- for (let k = 0; k < this.no_repeat_ngram_size; ++k) {
326- ngram.push(prevInputIds[j + k]);
327- }
328- ngrams.push(ngram);
329- }
330-
331- /** @type {Map<string, number[]>} */
332- const generatedNgram = new Map();
333- for (const ngram of ngrams) {
334- const prevNgram = ngram.slice(0, ngram.length - 1);
335- const prevNgramKey = JSON.stringify(prevNgram);
336- const prevNgramValue = generatedNgram.get(prevNgramKey) ?? [];
337- prevNgramValue.push(ngram[ngram.length - 1]);
338- generatedNgram.set(prevNgramKey, prevNgramValue);
339- }
340- return generatedNgram;
341- }
342-
343- /**
344- * Generate n-grams from a sequence of token ids.
345- * @param {Map<string, number[]>} bannedNgrams Map of banned n-grams
346- * @param {number[]} prevInputIds List of previous input ids
347- * @returns {number[]} Map of generated n-grams
348- */
349- getGeneratedNgrams(bannedNgrams, prevInputIds) {
350- const ngramIdx = prevInputIds.slice(prevInputIds.length + 1 - this.no_repeat_ngram_size, prevInputIds.length);
351- const banned = bannedNgrams.get(JSON.stringify(ngramIdx)) ?? [];
352- return banned;
353- }
354-
355- /**
356- * Calculate banned n-gram tokens
357- * @param {number[]} prevInputIds List of previous input ids
358- * @returns {number[]} Map of generated n-grams
359- */
360- calcBannedNgramTokens(prevInputIds) {
361- const bannedTokens = [];
362- if (prevInputIds.length + 1 < this.no_repeat_ngram_size) {
363- // return no banned tokens if we haven't generated no_repeat_ngram_size tokens yet
364- return bannedTokens;
365-
366- } else {
367- const generatedNgrams = this.getNgrams(prevInputIds);
368- const bannedTokens = this.getGeneratedNgrams(generatedNgrams, prevInputIds);
369- return bannedTokens;
370- }
371- }
372-
373- /**
374- * Apply the no-repeat-ngram processor to the logits.
375- * @param {Array} input_ids The input IDs.
376- * @param {Object} logits The logits.
377- * @returns {Object} The logits with no-repeat-ngram processing.
378- */
379- _call(input_ids, logits) {
380- const bannedTokens = this.calcBannedNgramTokens(input_ids);
381-
382- for (const token of bannedTokens) {
383- logits.data[token] = -Infinity;
384- }
385- return logits;
386- }
312+ /**
313+ * Create a NoRepeatNGramLogitsProcessor.
314+ * @param {number} no_repeat_ngram_size The no-repeat-ngram size. All ngrams of this size can only occur once.
315+ */
316+ constructor(no_repeat_ngram_size) {
317+ super();
318+ this.no_repeat_ngram_size = no_repeat_ngram_size;
319+ }
320+
321+ /**
322+ * Generate n-grams from a sequence of token ids.
323+ * @param {number[]} prevInputIds List of previous input ids
324+ * @returns {Map<string, number[]>} Map of generated n-grams
325+ */
326+ getNgrams(prevInputIds) {
327+ const curLen = prevInputIds.length;
328+
329+ /**@type {number[][]} */
330+ const ngrams = [];
331+ for (let j = 0; j < curLen + 1 - this.no_repeat_ngram_size; ++j) {
332+ const ngram = [];
333+ for (let k = 0; k < this.no_repeat_ngram_size; ++k) {
334+ ngram.push(prevInputIds[j + k]);
335+ }
336+ ngrams.push(ngram);
337+ }
338+
339+ /** @type {Map<string, number[]>} */
340+ const generatedNgram = new Map();
341+ for (const ngram of ngrams) {
342+ const prevNgram = ngram.slice(0, ngram.length - 1);
343+ const prevNgramKey = JSON.stringify(prevNgram);
344+ const prevNgramValue = generatedNgram.get(prevNgramKey) ?? [];
345+ prevNgramValue.push(ngram[ngram.length - 1]);
346+ generatedNgram.set(prevNgramKey, prevNgramValue);
347+ }
348+ return generatedNgram;
349+ }
350+
351+ /**
352+ * Generate n-grams from a sequence of token ids.
353+ * @param {Map<string, number[]>} bannedNgrams Map of banned n-grams
354+ * @param {number[]} prevInputIds List of previous input ids
355+ * @returns {number[]} Map of generated n-grams
356+ */
357+ getGeneratedNgrams(bannedNgrams, prevInputIds) {
358+ const ngramIdx = prevInputIds.slice(
359+ prevInputIds.length + 1 - this.no_repeat_ngram_size,
360+ prevInputIds.length,
361+ );
362+ const banned = bannedNgrams.get(JSON.stringify(ngramIdx)) ?? [];
363+ return banned;
364+ }
365+
366+ /**
367+ * Calculate banned n-gram tokens
368+ * @param {number[]} prevInputIds List of previous input ids
369+ * @returns {number[]} Map of generated n-grams
370+ */
371+ calcBannedNgramTokens(prevInputIds) {
372+ const bannedTokens = [];
373+ if (prevInputIds.length + 1 < this.no_repeat_ngram_size) {
374+ // return no banned tokens if we haven't generated no_repeat_ngram_size tokens yet
375+ return bannedTokens;
376+ } else {
377+ const generatedNgrams = this.getNgrams(prevInputIds);
378+ const bannedTokens = this.getGeneratedNgrams(
379+ generatedNgrams,
380+ prevInputIds,
381+ );
382+ return bannedTokens;
383+ }
384+ }
385+
386+ /**
387+ * Apply the no-repeat-ngram processor to the logits.
388+ * @param {Array} input_ids The input IDs.
389+ * @param {Object} logits The logits.
390+ * @returns {Object} The logits with no-repeat-ngram processing.
391+ */
392+ _call(input_ids, logits) {
393+ const bannedTokens = this.calcBannedNgramTokens(input_ids);
394+
395+ for (const token of bannedTokens) {
396+ logits.data[token] = -Infinity;
397+ }
398+ return logits;
399+ }
387400 }
388401
389402 /**
390403 * A logits processor that penalises repeated output tokens.
391- *
404+ *
392405 * @extends LogitsProcessor
393406 */
394407 export class RepetitionPenaltyLogitsProcessor extends LogitsProcessor {
395- /**
396- * Create a RepetitionPenaltyLogitsProcessor.
397- * @param {number} penalty The penalty to apply for repeated tokens.
398- */
399- constructor(penalty) {
400- super();
401- this.penalty = penalty;
402- }
403-
404- /**
405- * Apply the repetition penalty to the logits.
406- * @param {Array} input_ids The input IDs.
407- * @param {Object} logits The logits.
408- * @returns {Object} The logits with repetition penalty processing.
409- */
410- _call(input_ids, logits) {
411- // Modify the logits corresponding to each element in `input_ids`.
412- // As a consequence, the logits corresponding to tokens that appear
413- // many times in the output will be penalised more.
414- for (const input_id of input_ids) {
415- if (logits.data[input_id] < 0) {
416- logits.data[input_id] *= this.penalty;
417- } else {
418- logits.data[input_id] /= this.penalty;
419- }
420- }
421- return logits
422- }
408+ /**
409+ * Create a RepetitionPenaltyLogitsProcessor.
410+ * @param {number} penalty The penalty to apply for repeated tokens.
411+ */
412+ constructor(penalty) {
413+ super();
414+ this.penalty = penalty;
415+ }
416+
417+ /**
418+ * Apply the repetition penalty to the logits.
419+ * @param {Array} input_ids The input IDs.
420+ * @param {Object} logits The logits.
421+ * @returns {Object} The logits with repetition penalty processing.
422+ */
423+ _call(input_ids, logits) {
424+ // Modify the logits corresponding to each element in `input_ids`.
425+ // As a consequence, the logits corresponding to tokens that appear
426+ // many times in the output will be penalised more.
427+ for (const input_id of input_ids) {
428+ if (logits.data[input_id] < 0) {
429+ logits.data[input_id] *= this.penalty;
430+ } else {
431+ logits.data[input_id] /= this.penalty;
432+ }
433+ }
434+ return logits;
435+ }
423436 }
424437
425438 /**
426439 * A logits processor that enforces a minimum number of tokens.
427- *
440+ *
428441 * @extends LogitsProcessor
429442 */
430443 export class MinLengthLogitsProcessor extends LogitsProcessor {
431- /**
432- * Create a MinLengthLogitsProcessor.
433- * @param {number} min_length The minimum length below which the score of `eos_token_id` is set to negative infinity.
434- * @param {number|number[]} eos_token_id The ID/IDs of the end-of-sequence token.
435- */
436- constructor(min_length, eos_token_id) {
437- super();
438- this.min_length = min_length;
439- this.eos_token_id = Array.isArray(eos_token_id) ? eos_token_id : [eos_token_id];
440- }
441-
442- /**
443- * Apply logit processor.
444- * @param {Array} input_ids The input IDs.
445- * @param {Object} logits The logits.
446- * @returns {Object} The processed logits.
447- */
448- _call(input_ids, logits) {
449- if (input_ids.length < this.min_length) {
450- for (const eos_token of this.eos_token_id) {
451- logits.data[eos_token] = -Infinity;
452- }
453- }
454-
455- return logits
456- }
444+ /**
445+ * Create a MinLengthLogitsProcessor.
446+ * @param {number} min_length The minimum length below which the score of `eos_token_id` is set to negative infinity.
447+ * @param {number|number[]} eos_token_id The ID/IDs of the end-of-sequence token.
448+ */
449+ constructor(min_length, eos_token_id) {
450+ super();
451+ this.min_length = min_length;
452+ this.eos_token_id = Array.isArray(eos_token_id)
453+ ? eos_token_id
454+ : [eos_token_id];
455+ }
456+
457+ /**
458+ * Apply logit processor.
459+ * @param {Array} input_ids The input IDs.
460+ * @param {Object} logits The logits.
461+ * @returns {Object} The processed logits.
462+ */
463+ _call(input_ids, logits) {
464+ if (input_ids.length < this.min_length) {
465+ for (const eos_token of this.eos_token_id) {
466+ logits.data[eos_token] = -Infinity;
467+ }
468+ }
469+
470+ return logits;
471+ }
457472 }
458473
459474 /**
460475 * A logits processor that enforces a minimum number of new tokens.
461- *
476+ *
462477 * @extends LogitsProcessor
463478 */
464479 export class MinNewTokensLengthLogitsProcessor extends LogitsProcessor {
465- /**
466- * Create a MinNewTokensLengthLogitsProcessor.
467- * @param {number} prompt_length_to_skip The input tokens length.
468- * @param {number} min_new_tokens The minimum *new* tokens length below which the score of `eos_token_id` is set to negative infinity.
469- * @param {number|number[]} eos_token_id The ID/IDs of the end-of-sequence token.
470- */
471- constructor(prompt_length_to_skip, min_new_tokens, eos_token_id) {
472- super();
473- this.prompt_length_to_skip = prompt_length_to_skip;
474- this.min_new_tokens = min_new_tokens;
475- this.eos_token_id = Array.isArray(eos_token_id) ? eos_token_id : [eos_token_id];
476- }
477-
478- /**
479- * Apply logit processor.
480- * @param {Array} input_ids The input IDs.
481- * @param {Object} logits The logits.
482- * @returns {Object} The processed logits.
483- */
484- _call(input_ids, logits) {
485- const new_tokens_length = input_ids.length - this.prompt_length_to_skip;
486- if (new_tokens_length < this.min_new_tokens) {
487- for (const eos_token of this.eos_token_id) {
488- logits.data[eos_token] = -Infinity;
489- }
490- }
491-
492- return logits
493- }
480+ /**
481+ * Create a MinNewTokensLengthLogitsProcessor.
482+ * @param {number} prompt_length_to_skip The input tokens length.
483+ * @param {number} min_new_tokens The minimum *new* tokens length below which the score of `eos_token_id` is set to negative infinity.
484+ * @param {number|number[]} eos_token_id The ID/IDs of the end-of-sequence token.
485+ */
486+ constructor(prompt_length_to_skip, min_new_tokens, eos_token_id) {
487+ super();
488+ this.prompt_length_to_skip = prompt_length_to_skip;
489+ this.min_new_tokens = min_new_tokens;
490+ this.eos_token_id = Array.isArray(eos_token_id)
491+ ? eos_token_id
492+ : [eos_token_id];
493+ }
494+
495+ /**
496+ * Apply logit processor.
497+ * @param {Array} input_ids The input IDs.
498+ * @param {Object} logits The logits.
499+ * @returns {Object} The processed logits.
500+ */
501+ _call(input_ids, logits) {
502+ const new_tokens_length = input_ids.length - this.prompt_length_to_skip;
503+ if (new_tokens_length < this.min_new_tokens) {
504+ for (const eos_token of this.eos_token_id) {
505+ logits.data[eos_token] = -Infinity;
506+ }
507+ }
508+
509+ return logits;
510+ }
494511 }
495512
496513 export class NoBadWordsLogitsProcessor extends LogitsProcessor {
497- /**
498- * Create a `NoBadWordsLogitsProcessor`.
499- * @param {number[][]} bad_words_ids List of list of token ids that are not allowed to be generated.
500- * @param {number|number[]} eos_token_id The id of the *end-of-sequence* token. Optionally, use a list to set multiple *end-of-sequence* tokens.
501- */
502- constructor(bad_words_ids, eos_token_id) {
503- super();
504- this.bad_words_ids = bad_words_ids;
505- this.eos_token_id = Array.isArray(eos_token_id) ? eos_token_id : [eos_token_id];
506- }
507-
508- /**
509- * Apply logit processor.
510- * @param {Array} input_ids The input IDs.
511- * @param {Object} logits The logits.
512- * @returns {Object} The processed logits.
513- */
514- _call(input_ids, logits) {
515-
516- for (const bad_word_ids of this.bad_words_ids) {
517- // Whether to modify the logits of the last token in the bad word id sequence
518- let mark = true;
519-
520- // For each bad word in the list, if the current sequence of input ids ends with this sequence (excluding the last),
521- // then we set the logits of the last bad word id to -Infinity.
522- for (let i = 1; i <= bad_word_ids.length - 1 && bad_word_ids.length < input_ids.length; ++i) {
523-
524- if (bad_word_ids.at(-i - 1) !== input_ids.at(-i)) {
525- // We have found a mismatch
526- mark = false;
527- break;
528- }
529- }
530- if (mark) {
531- logits.data[bad_word_ids.at(-1)] = -Infinity;
532- }
514+ /**
515+ * Create a `NoBadWordsLogitsProcessor`.
516+ * @param {number[][]} bad_words_ids List of list of token ids that are not allowed to be generated.
517+ * @param {number|number[]} eos_token_id The id of the *end-of-sequence* token. Optionally, use a list to set multiple *end-of-sequence* tokens.
518+ */
519+ constructor(bad_words_ids, eos_token_id) {
520+ super();
521+ this.bad_words_ids = bad_words_ids;
522+ this.eos_token_id = Array.isArray(eos_token_id)
523+ ? eos_token_id
524+ : [eos_token_id];
525+ }
526+
527+ /**
528+ * Apply logit processor.
529+ * @param {Array} input_ids The input IDs.
530+ * @param {Object} logits The logits.
531+ * @returns {Object} The processed logits.
532+ */
533+ _call(input_ids, logits) {
534+ for (const bad_word_ids of this.bad_words_ids) {
535+ // Whether to modify the logits of the last token in the bad word id sequence
536+ let mark = true;
537+
538+ // For each bad word in the list, if the current sequence of input ids ends with this sequence (excluding the last),
539+ // then we set the logits of the last bad word id to -Infinity.
540+ for (
541+ let i = 1;
542+ i <= bad_word_ids.length - 1 && bad_word_ids.length < input_ids.length;
543+ ++i
544+ ) {
545+ if (bad_word_ids.at(-i - 1) !== input_ids.at(-i)) {
546+ // We have found a mismatch
547+ mark = false;
548+ break;
533549 }
534-
535- return logits
550+ }
551+ if (mark) {
552+ logits.data[bad_word_ids.at(-1)] = -Infinity;
553+ }
536554 }
555+
556+ return logits;
557+ }
537558 }
538559
539560 /**
@@ -569,7 +590,7 @@
569590 * @property {number[][]|number[][][]} [force_words_ids=null] List of token ids that must be generated. If given a `number[][]`, this is treated as a simple list of words that must be included, the opposite to `bad_words_ids`. If given `number[][][]`, this triggers a [disjunctive constraint](https://github.com/huggingface/transformers/issues/14081), where one can allow different forms of each word.
570591 * @property {boolean} [renormalize_logits=false] Whether to renormalize the logits after applying all the logits processors or warpers (including the custom ones). It's highly recommended to set this flag to `true` as the search algorithms suppose the score logits are normalized but some logit processors or warpers break the normalization.
571592 * @property {Object[]} [constraints=null] Custom constraints that can be added to the generation to ensure that the output will contain the use of certain tokens as defined by `Constraint` objects, in the most sensible way possible.
572- *
593+ *
573594 * @property {number} [forced_bos_token_id=null] The id of the token to force as the first generated token after the `decoder_start_token_id`. Useful for multilingual models like mBART where the first generated token needs to be the target language token.
574595 * @property {number|number[]} [forced_eos_token_id=null] The id of the token to force as the last generated token when `max_length` is reached. Optionally, use a list to set multiple *end-of-sequence* tokens.
575596 * @property {boolean} [remove_invalid_values=false] Whether to remove possible *nan* and *inf* outputs of the model to prevent the generation method to crash. Note that using `remove_invalid_values` can slow down generation.
@@ -577,20 +598,20 @@
577598 * @property {number[]} [suppress_tokens=null] A list of tokens that will be suppressed at generation. The `SupressTokens` logit processor will set their log probs to `-inf` so that they are not sampled.
578599 * @property {number[]} [begin_suppress_tokens=null] A list of tokens that will be suppressed at the beginning of the generation. The `SupressBeginTokens` logit processor will set their log probs to `-inf` so that they are not sampled.
579600 * @property {number[][]} [forced_decoder_ids=null] A list of pairs of integers which indicates a mapping from generation indices to token indices that will be forced before sampling. For example, `[[1, 123]]` means the second generated token will always be a token of index 123.
580- *
601+ *
581602 * @property {number} [num_return_sequences=1] The number of independently computed returned sequences for each element in the batch.
582603 * @property {boolean} [output_attentions=false] Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned tensors for more details.
583604 * @property {boolean} [output_hidden_states=false] Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for more details.
584605 * @property {boolean} [output_scores=false] Whether or not to return the prediction scores. See `scores` under returned tensors for more details.
585606 * @property {boolean} [return_dict_in_generate=false] Whether or not to return a `ModelOutput` instead of a plain tuple.
586- *
607+ *
587608 * @property {number} [pad_token_id=null] The id of the *padding* token.
588609 * @property {number} [bos_token_id=null] The id of the *beginning-of-sequence* token.
589610 * @property {number|number[]} [eos_token_id=null] The id of the *end-of-sequence* token. Optionally, use a list to set multiple *end-of-sequence* tokens.
590- *
611+ *
591612 * @property {number} [encoder_no_repeat_ngram_size=0] If set to int > 0, all ngrams of that size that occur in the `encoder_input_ids` cannot occur in the `decoder_input_ids`.
592613 * @property {number} [decoder_start_token_id=null] If an encoder-decoder model starts decoding with a different token than *bos*, the id of that token.
593- *
614+ *
594615 * @property {Object} [generation_kwargs={}] Additional generation kwargs will be forwarded to the `generate` function of the model. Kwargs that are not present in `generate`'s signature will be used in the model forward pass.
595616 */
596617
@@ -598,180 +619,184 @@
598619 * Class that holds a configuration for a generation task.
599620 * @type {new (kwargs?: GenerationConfigType) => GenerationConfigType}
600621 */
601-export const GenerationConfig = /** @type {any} */ (class {
602-
622+export const GenerationConfig = /** @type {any} */ (
623+ class {
603624 /**
604625 * Create a new GenerationConfig object.
605- * @param {GenerationConfigType} kwargs
626+ * @param {GenerationConfigType} kwargs
606627 */
607628 constructor(kwargs = {}) {
608- // Parameters that control the length of the output
609- this.max_length = kwargs.max_length ?? 20;
610- this.max_new_tokens = kwargs.max_new_tokens ?? null;
611- this.min_length = kwargs.min_length ?? 0;
612- this.min_new_tokens = kwargs.min_new_tokens ?? null;
613- this.early_stopping = kwargs.early_stopping ?? false;
614- this.max_time = kwargs.max_time ?? null;
615-
616- // Parameters that control the generation strategy used
617- this.do_sample = kwargs.do_sample ?? false;
618- this.num_beams = kwargs.num_beams ?? 1;
619- this.num_beam_groups = kwargs.num_beam_groups ?? 1;
620- this.penalty_alpha = kwargs.penalty_alpha ?? null;
621- this.use_cache = kwargs.use_cache ?? true;
622-
623- // Parameters for manipulation of the model output logits
624- this.temperature = kwargs.temperature ?? 1.0;
625- this.top_k = kwargs.top_k ?? 50;
626- this.top_p = kwargs.top_p ?? 1.0;
627- this.typical_p = kwargs.typical_p ?? 1.0;
628- this.epsilon_cutoff = kwargs.epsilon_cutoff ?? 0.0;
629- this.eta_cutoff = kwargs.eta_cutoff ?? 0.0;
630- this.diversity_penalty = kwargs.diversity_penalty ?? 0.0;
631- this.repetition_penalty = kwargs.repetition_penalty ?? 1.0;
632- this.encoder_repetition_penalty = kwargs.encoder_repetition_penalty ?? 1.0;
633- this.length_penalty = kwargs.length_penalty ?? 1.0;
634- this.no_repeat_ngram_size = kwargs.no_repeat_ngram_size ?? 0;
635- this.bad_words_ids = kwargs.bad_words_ids ?? null;
636- this.force_words_ids = kwargs.force_words_ids ?? null;
637- this.renormalize_logits = kwargs.renormalize_logits ?? false;
638- this.constraints = kwargs.constraints ?? null;
639- this.forced_bos_token_id = kwargs.forced_bos_token_id ?? null;
640- this.forced_eos_token_id = kwargs.forced_eos_token_id ?? null;
641- this.remove_invalid_values = kwargs.remove_invalid_values ?? false;
642- this.exponential_decay_length_penalty = kwargs.exponential_decay_length_penalty ?? null;
643- this.suppress_tokens = kwargs.suppress_tokens ?? null;
644- this.begin_suppress_tokens = kwargs.begin_suppress_tokens ?? null;
645- this.forced_decoder_ids = kwargs.forced_decoder_ids ?? null;
646-
647- // Parameters that define the output variables of `generate`
648- this.num_return_sequences = kwargs.num_return_sequences ?? 1;
649- this.output_attentions = kwargs.output_attentions ?? false;
650- this.output_hidden_states = kwargs.output_hidden_states ?? false;
651- this.output_scores = kwargs.output_scores ?? false;
652- this.return_dict_in_generate = kwargs.return_dict_in_generate ?? false;
653-
654- // Special tokens that can be used at generation time
655- this.pad_token_id = kwargs.pad_token_id ?? null;
656- this.bos_token_id = kwargs.bos_token_id ?? null;
657- this.eos_token_id = kwargs.eos_token_id ?? null;
658-
659- // Generation parameters exclusive to encoder-decoder models
660- this.encoder_no_repeat_ngram_size = kwargs.encoder_no_repeat_ngram_size ?? 0;
661- this.decoder_start_token_id = kwargs.decoder_start_token_id ?? null;
662-
663- // Wild card
664- this.generation_kwargs = kwargs.generation_kwargs ?? {};
665- }
666-});
629+ // Parameters that control the length of the output
630+ this.max_length = kwargs.max_length ?? 20;
631+ this.max_new_tokens = kwargs.max_new_tokens ?? null;
632+ this.min_length = kwargs.min_length ?? 0;
633+ this.min_new_tokens = kwargs.min_new_tokens ?? null;
634+ this.early_stopping = kwargs.early_stopping ?? false;
635+ this.max_time = kwargs.max_time ?? null;
636+
637+ // Parameters that control the generation strategy used
638+ this.do_sample = kwargs.do_sample ?? false;
639+ this.num_beams = kwargs.num_beams ?? 1;
640+ this.num_beam_groups = kwargs.num_beam_groups ?? 1;
641+ this.penalty_alpha = kwargs.penalty_alpha ?? null;
642+ this.use_cache = kwargs.use_cache ?? true;
643+
644+ // Parameters for manipulation of the model output logits
645+ this.temperature = kwargs.temperature ?? 1.0;
646+ this.top_k = kwargs.top_k ?? 50;
647+ this.top_p = kwargs.top_p ?? 1.0;
648+ this.typical_p = kwargs.typical_p ?? 1.0;
649+ this.epsilon_cutoff = kwargs.epsilon_cutoff ?? 0.0;
650+ this.eta_cutoff = kwargs.eta_cutoff ?? 0.0;
651+ this.diversity_penalty = kwargs.diversity_penalty ?? 0.0;
652+ this.repetition_penalty = kwargs.repetition_penalty ?? 1.0;
653+ this.encoder_repetition_penalty =
654+ kwargs.encoder_repetition_penalty ?? 1.0;
655+ this.length_penalty = kwargs.length_penalty ?? 1.0;
656+ this.no_repeat_ngram_size = kwargs.no_repeat_ngram_size ?? 0;
657+ this.bad_words_ids = kwargs.bad_words_ids ?? null;
658+ this.force_words_ids = kwargs.force_words_ids ?? null;
659+ this.renormalize_logits = kwargs.renormalize_logits ?? false;
660+ this.constraints = kwargs.constraints ?? null;
661+ this.forced_bos_token_id = kwargs.forced_bos_token_id ?? null;
662+ this.forced_eos_token_id = kwargs.forced_eos_token_id ?? null;
663+ this.remove_invalid_values = kwargs.remove_invalid_values ?? false;
664+ this.exponential_decay_length_penalty =
665+ kwargs.exponential_decay_length_penalty ?? null;
666+ this.suppress_tokens = kwargs.suppress_tokens ?? null;
667+ this.begin_suppress_tokens = kwargs.begin_suppress_tokens ?? null;
668+ this.forced_decoder_ids = kwargs.forced_decoder_ids ?? null;
669+
670+ // Parameters that define the output variables of `generate`
671+ this.num_return_sequences = kwargs.num_return_sequences ?? 1;
672+ this.output_attentions = kwargs.output_attentions ?? false;
673+ this.output_hidden_states = kwargs.output_hidden_states ?? false;
674+ this.output_scores = kwargs.output_scores ?? false;
675+ this.return_dict_in_generate = kwargs.return_dict_in_generate ?? false;
676+
677+ // Special tokens that can be used at generation time
678+ this.pad_token_id = kwargs.pad_token_id ?? null;
679+ this.bos_token_id = kwargs.bos_token_id ?? null;
680+ this.eos_token_id = kwargs.eos_token_id ?? null;
681+
682+ // Generation parameters exclusive to encoder-decoder models
683+ this.encoder_no_repeat_ngram_size =
684+ kwargs.encoder_no_repeat_ngram_size ?? 0;
685+ this.decoder_start_token_id = kwargs.decoder_start_token_id ?? null;
686+
687+ // Wild card
688+ this.generation_kwargs = kwargs.generation_kwargs ?? {};
689+ }
690+ }
691+);
667692
668693 /**
669694 * Sampler is a base class for all sampling methods used for text generation.
670695 */
671696 export class Sampler extends Callable {
672- /**
673- * Creates a new Sampler object with the specified generation config.
674- * @param {GenerationConfigType} generation_config The generation config.
675- */
676- constructor(generation_config) {
677- super();
678- this.generation_config = generation_config;
679- }
680-
681- /**
682- * Executes the sampler, using the specified logits.
683- * @param {Tensor} logits
684- * @param {number} index
685- * @returns {void}
686- */
687- _call(logits, index = -1) {
688- // Sample from logits, of dims [batch, sequence_length, vocab_size].
689- // If index is specified, sample from [batch, index, vocab_size].
690- return this.sample(logits, index);
691- }
692-
693- /**
694- * Abstract method for sampling the logits.
695- * @param {Tensor} logits
696- * @param {number} index
697- * @throws {Error}
698- */
699- sample(logits, index) {
700- throw Error("sample should be implemented in subclasses.")
701- }
702-
703- /**
704- * Returns the specified logits as an array, with temperature applied.
705- * @param {Tensor} logits
706- * @param {number} index
707- * @returns {Float32Array}
708- */
709- getLogits(logits, index) {
710- let vocabSize = logits.dims.at(-1);
711-
712- let logs = /** @type {Float32Array} */(logits.data);
713-
714- if (index === -1) {
715- logs = logs.slice(-vocabSize);
716- } else {
717- let startIndex = index * vocabSize;
718- logs = logs.slice(startIndex, startIndex + vocabSize);
719- }
720-
721- // add temperature
722- if (this.generation_config.temperature > 0) {
723- logs = logs.map(x => x / this.generation_config.temperature)
724- }
725- return logs;
726- }
727-
728- /**
729- * Selects an item randomly based on the specified probabilities.
730- * @param {Array} probabilities An array of probabilities to use for selection.
731- * @returns {number} The index of the selected item.
732- */
733- randomSelect(probabilities) {
734- // Return index of chosen item
735- let sumProbabilities = probabilities.reduce((acc, curr) => acc + curr, 0);
736-
737- let r = Math.random() * sumProbabilities;
738- for (let i = 0; i < probabilities.length; ++i) {
739- r -= probabilities[i];
740- if (r <= 0) {
741- return i;
742- }
743- }
744- return 0; // return first (most probable) as a fallback
745- }
746-
747- /**
748- * Returns a Sampler object based on the specified options.
749- * @param {GenerationConfigType} generation_config An object containing options for the sampler.
750- * @returns {Sampler} A Sampler object.
751- */
752- static getSampler(generation_config) {
753- // - *greedy decoding*: `num_beams=1` and `do_sample=False`
754- // - *contrastive search*: `penalty_alpha>0` and `top_k>1`
755- // - *multinomial sampling*: `num_beams=1` and `do_sample=True`
756- // - *beam-search decoding*: `num_beams>1` and `do_sample=False`
757- // - *beam-search multinomial sampling*: `num_beams>1` and `do_sample=True`
758- // - *diverse beam-search decoding*: `num_beams>1` and `num_beam_groups>1`
759- // - *constrained beam-search decoding*: `constraints!=None` or `force_words_ids!=None`
760-
761- // NOTE: beam search is implemented directly into the generation function
762- if (generation_config.do_sample) {
763- return new MultinomialSampler(generation_config);
764-
765- } else if (generation_config.num_beams > 1) {
766- return new BeamSearchSampler(generation_config);
767-
768- } else {
769- if (generation_config.num_return_sequences > 1) {
770- throw Error(`num_return_sequences has to be 1 when doing greedy search, but is ${generation_config.num_return_sequences}.`)
771- }
772- return new GreedySampler(generation_config);
773- }
774- }
697+ /**
698+ * Creates a new Sampler object with the specified generation config.
699+ * @param {GenerationConfigType} generation_config The generation config.
700+ */
701+ constructor(generation_config) {
702+ super();
703+ this.generation_config = generation_config;
704+ }
705+
706+ /**
707+ * Executes the sampler, using the specified logits.
708+ * @param {Tensor} logits
709+ * @param {number} index
710+ * @returns {void}
711+ */
712+ _call(logits, index = -1) {
713+ // Sample from logits, of dims [batch, sequence_length, vocab_size].
714+ // If index is specified, sample from [batch, index, vocab_size].
715+ return this.sample(logits, index);
716+ }
717+
718+ /**
719+ * Abstract method for sampling the logits.
720+ * @param {Tensor} logits
721+ * @param {number} index
722+ * @throws {Error}
723+ */
724+ sample(logits, index) {
725+ throw Error("sample should be implemented in subclasses.");
726+ }
727+
728+ /**
729+ * Returns the specified logits as an array, with temperature applied.
730+ * @param {Tensor} logits
731+ * @param {number} index
732+ * @returns {Float32Array}
733+ */
734+ getLogits(logits, index) {
735+ let vocabSize = logits.dims.at(-1);
736+
737+ let logs = /** @type {Float32Array} */ (logits.data);
738+
739+ if (index === -1) {
740+ logs = logs.slice(-vocabSize);
741+ } else {
742+ let startIndex = index * vocabSize;
743+ logs = logs.slice(startIndex, startIndex + vocabSize);
744+ }
745+
746+ // add temperature
747+ if (this.generation_config.temperature > 0) {
748+ logs = logs.map((x) => x / this.generation_config.temperature);
749+ }
750+ return logs;
751+ }
752+
753+ /**
754+ * Selects an item randomly based on the specified probabilities.
755+ * @param {Array} probabilities An array of probabilities to use for selection.
756+ * @returns {number} The index of the selected item.
757+ */
758+ randomSelect(probabilities) {
759+ // Return index of chosen item
760+ let sumProbabilities = probabilities.reduce((acc, curr) => acc + curr, 0);
761+
762+ let r = Math.random() * sumProbabilities;
763+ for (let i = 0; i < probabilities.length; ++i) {
764+ r -= probabilities[i];
765+ if (r <= 0) {
766+ return i;
767+ }
768+ }
769+ return 0; // return first (most probable) as a fallback
770+ }
771+
772+ /**
773+ * Returns a Sampler object based on the specified options.
774+ * @param {GenerationConfigType} generation_config An object containing options for the sampler.
775+ * @returns {Sampler} A Sampler object.
776+ */
777+ static getSampler(generation_config) {
778+ // - *greedy decoding*: `num_beams=1` and `do_sample=False`
779+ // - *contrastive search*: `penalty_alpha>0` and `top_k>1`
780+ // - *multinomial sampling*: `num_beams=1` and `do_sample=True`
781+ // - *beam-search decoding*: `num_beams>1` and `do_sample=False`
782+ // - *beam-search multinomial sampling*: `num_beams>1` and `do_sample=True`
783+ // - *diverse beam-search decoding*: `num_beams>1` and `num_beam_groups>1`
784+ // - *constrained beam-search decoding*: `constraints!=None` or `force_words_ids!=None`
785+
786+ // NOTE: beam search is implemented directly into the generation function
787+ if (generation_config.do_sample) {
788+ return new MultinomialSampler(generation_config);
789+ } else if (generation_config.num_beams > 1) {
790+ return new BeamSearchSampler(generation_config);
791+ } else {
792+ if (generation_config.num_return_sequences > 1) {
793+ throw Error(
794+ `num_return_sequences has to be 1 when doing greedy search, but is ${generation_config.num_return_sequences}.`,
795+ );
796+ }
797+ return new GreedySampler(generation_config);
798+ }
799+ }
775800 }
776801
777802 /**
@@ -779,23 +804,21 @@
779804 * @extends Sampler
780805 */
781806 class GreedySampler extends Sampler {
782- /**
783- * Sample the maximum probability of a given logits tensor.
784- * @param {Tensor} logits
785- * @param {number} [index=-1]
786- * @returns {Array} An array with a single tuple, containing the index of the maximum value and a meaningless score (since this is a greedy search).
787- */
788- sample(logits, index = -1) {
789- // NOTE: no need to do log_softmax here since we only take the maximum
790- let logs = this.getLogits(logits, index);
791- let argmax = max(logs)[1];
792-
793- // Note: score is meaningless in this context, since we are performing
794- // greedy search (p = 1 => log(p) = 0)
795- return [
796- [argmax, 0]
797- ];
798- }
807+ /**
808+ * Sample the maximum probability of a given logits tensor.
809+ * @param {Tensor} logits
810+ * @param {number} [index=-1]
811+ * @returns {Array} An array with a single tuple, containing the index of the maximum value and a meaningless score (since this is a greedy search).
812+ */
813+ sample(logits, index = -1) {
814+ // NOTE: no need to do log_softmax here since we only take the maximum
815+ let logs = this.getLogits(logits, index);
816+ let argmax = max(logs)[1];
817+
818+ // Note: score is meaningless in this context, since we are performing
819+ // greedy search (p = 1 => log(p) = 0)
820+ return [[argmax, 0]];
821+ }
799822 }
800823
801824 /**
@@ -803,71 +826,68 @@
803826 * @extends Sampler
804827 */
805828 class MultinomialSampler extends Sampler {
806-
807- /**
808- * Sample from the logits.
809- * @param {Tensor} logits
810- * @param {number} index
811- * @returns {Array}
812- */
813- sample(logits, index = -1) {
814- let k = logits.dims.at(-1); // defaults to vocab size
815- if (this.generation_config.top_k > 0) {
816- k = Math.min(this.generation_config.top_k, k);
817- }
818-
819- // Get logits of nth token
820- const logs = this.getLogits(logits, index);
821-
822- // Get top k tokens
823- const topLogits = getTopItems(logs, k);
824-
825- // Compute softmax over logits
826- const probabilities = softmax(topLogits.map(x => x[1]));
827-
828- return Array.from({ length: this.generation_config.num_beams }, () => {
829- const sampledIndex = this.randomSelect(probabilities);
830- return [
831- topLogits[sampledIndex][0], // token id
832- Math.log(probabilities[sampledIndex]), // score
833- ];
834- });
835- }
829+ /**
830+ * Sample from the logits.
831+ * @param {Tensor} logits
832+ * @param {number} index
833+ * @returns {Array}
834+ */
835+ sample(logits, index = -1) {
836+ let k = logits.dims.at(-1); // defaults to vocab size
837+ if (this.generation_config.top_k > 0) {
838+ k = Math.min(this.generation_config.top_k, k);
839+ }
840+
841+ // Get logits of nth token
842+ const logs = this.getLogits(logits, index);
843+
844+ // Get top k tokens
845+ const topLogits = getTopItems(logs, k);
846+
847+ // Compute softmax over logits
848+ const probabilities = softmax(topLogits.map((x) => x[1]));
849+
850+ return Array.from({ length: this.generation_config.num_beams }, () => {
851+ const sampledIndex = this.randomSelect(probabilities);
852+ return [
853+ topLogits[sampledIndex][0], // token id
854+ Math.log(probabilities[sampledIndex]), // score
855+ ];
856+ });
857+ }
836858 }
837859
838-
839860 /**
840861 * Class representing a BeamSearchSampler.
841862 * @extends Sampler
842863 */
843864 class BeamSearchSampler extends Sampler {
844-
845- /**
846- * Sample from the logits.
847- * @param {Tensor} logits
848- * @param {number} index
849- * @returns {Array}
850- */
851- sample(logits, index = -1) {
852- let k = logits.dims.at(-1); // defaults to vocab size
853- if (this.generation_config.top_k > 0) {
854- k = Math.min(this.generation_config.top_k, k);
855- }
856-
857- // Get logits of nth token
858- const logs = this.getLogits(logits, index);
859-
860- // Get top k tokens
861- const topLogits = getTopItems(logs, k);
862-
863- // Compute softmax over logits
864- const probabilities = softmax(topLogits.map(x => x[1]));
865-
866- return Array.from({ length: this.generation_config.num_beams }, (_, i) => {
867- return [
868- topLogits[i][0], // token id
869- Math.log(probabilities[i]), // score
870- ];
871- });
872- }
865+ /**
866+ * Sample from the logits.
867+ * @param {Tensor} logits
868+ * @param {number} index
869+ * @returns {Array}
870+ */
871+ sample(logits, index = -1) {
872+ let k = logits.dims.at(-1); // defaults to vocab size
873+ if (this.generation_config.top_k > 0) {
874+ k = Math.min(this.generation_config.top_k, k);
875+ }
876+
877+ // Get logits of nth token
878+ const logs = this.getLogits(logits, index);
879+
880+ // Get top k tokens
881+ const topLogits = getTopItems(logs, k);
882+
883+ // Compute softmax over logits
884+ const probabilities = softmax(topLogits.map((x) => x[1]));
885+
886+ return Array.from({ length: this.generation_config.num_beams }, (_, i) => {
887+ return [
888+ topLogits[i][0], // token id
889+ Math.log(probabilities[i]), // score
890+ ];
891+ });
892+ }
873893 }
modified core/vendor/modules/@xenova/transformers/src/utils/hub.js +554 −524
@@ -1,24 +1,23 @@
1-
21 /**
32 * @file Utility functions to interact with the Hugging Face Hub (https://huggingface.co/models)
4- *
3+ *
54 * @module utils/hub
65 */
76
8-import fs from 'fs';
9-import path from 'path';
10-import stream from 'stream/web';
7+import fs from "fs";
8+import path from "path";
9+import stream from "stream/web";
1110
12-import { env } from '../env.js';
13-import { dispatchCallback } from './core.js';
11+import { env } from "../env.js";
12+import { dispatchCallback } from "./core.js";
1413
1514 if (!globalThis.ReadableStream) {
16- // @ts-ignore
17- globalThis.ReadableStream = stream.ReadableStream; // ReadableStream is not a global with Node 16
15+ // @ts-ignore
16+ globalThis.ReadableStream = stream.ReadableStream; // ReadableStream is not a global with Node 16
1817 }
1918
2019 /**
21- * @typedef {Object} PretrainedOptions Options for loading a pretrained model.
20+ * @typedef {Object} PretrainedOptions Options for loading a pretrained model.
2221 * @property {boolean?} [quantized=true] Whether to load the 8-bit quantized version of the model (only applicable when loading model files).
2322 * @property {function} [progress_callback=null] If specified, this function will be called during model construction, to provide the user with progress updates.
2423 * @property {Object} [config=null] Configuration for the model to use instead of an automatically loaded configuration. Configuration can be automatically loaded when:
@@ -33,121 +32,124 @@
3332 */
3433
3534 class FileResponse {
36- /**
37- * Mapping from file extensions to MIME types.
38- */
39- _CONTENT_TYPE_MAP = {
40- 'txt': 'text/plain',
41- 'html': 'text/html',
42- 'css': 'text/css',
43- 'js': 'text/javascript',
44- 'json': 'application/json',
45- 'png': 'image/png',
46- 'jpg': 'image/jpeg',
47- 'jpeg': 'image/jpeg',
48- 'gif': 'image/gif',
49- }
50- /**
51- * Creates a new `FileResponse` object.
52- * @param {string|URL} filePath
53- */
54- constructor(filePath) {
55- this.filePath = filePath;
56- this.headers = new Headers();
57-
58- this.exists = fs.existsSync(filePath);
59- if (this.exists) {
60- this.status = 200;
61- this.statusText = 'OK';
62-
63- let stats = fs.statSync(filePath);
64- this.headers.set('content-length', stats.size.toString());
65-
66- this.updateContentType();
67-
68- let self = this;
69- this.body = new ReadableStream({
70- start(controller) {
71- self.arrayBuffer().then(buffer => {
72- controller.enqueue(new Uint8Array(buffer));
73- controller.close();
74- })
75- }
76- });
77- } else {
78- this.status = 404;
79- this.statusText = 'Not Found';
80- this.body = null;
81- }
82- }
83-
84- /**
85- * Updates the 'content-type' header property of the response based on the extension of
86- * the file specified by the filePath property of the current object.
87- * @returns {void}
88- */
89- updateContentType() {
90- // Set content-type header based on file extension
91- const extension = this.filePath.toString().split('.').pop().toLowerCase();
92- this.headers.set('content-type', this._CONTENT_TYPE_MAP[extension] ?? 'application/octet-stream');
93- }
94-
95- /**
96- * Clone the current FileResponse object.
97- * @returns {FileResponse} A new FileResponse object with the same properties as the current object.
98- */
99- clone() {
100- let response = new FileResponse(this.filePath);
101- response.exists = this.exists;
102- response.status = this.status;
103- response.statusText = this.statusText;
104- response.headers = new Headers(this.headers);
105- return response;
106- }
107-
108- /**
109- * Reads the contents of the file specified by the filePath property and returns a Promise that
110- * resolves with an ArrayBuffer containing the file's contents.
111- * @returns {Promise<ArrayBuffer>} A Promise that resolves with an ArrayBuffer containing the file's contents.
112- * @throws {Error} If the file cannot be read.
113- */
114- async arrayBuffer() {
115- const data = await fs.promises.readFile(this.filePath);
116- return data.buffer;
117- }
118-
119- /**
120- * Reads the contents of the file specified by the filePath property and returns a Promise that
121- * resolves with a Blob containing the file's contents.
122- * @returns {Promise<Blob>} A Promise that resolves with a Blob containing the file's contents.
123- * @throws {Error} If the file cannot be read.
124- */
125- async blob() {
126- const data = await fs.promises.readFile(this.filePath);
127- return new Blob([data], { type: this.headers.get('content-type') });
128- }
129-
130- /**
131- * Reads the contents of the file specified by the filePath property and returns a Promise that
132- * resolves with a string containing the file's contents.
133- * @returns {Promise<string>} A Promise that resolves with a string containing the file's contents.
134- * @throws {Error} If the file cannot be read.
135- */
136- async text() {
137- const data = await fs.promises.readFile(this.filePath, 'utf8');
138- return data;
139- }
140-
141- /**
142- * Reads the contents of the file specified by the filePath property and returns a Promise that
143- * resolves with a parsed JavaScript object containing the file's contents.
144- *
145- * @returns {Promise<Object>} A Promise that resolves with a parsed JavaScript object containing the file's contents.
146- * @throws {Error} If the file cannot be read.
147- */
148- async json() {
149- return JSON.parse(await this.text());
35+ /**
36+ * Mapping from file extensions to MIME types.
37+ */
38+ _CONTENT_TYPE_MAP = {
39+ txt: "text/plain",
40+ html: "text/html",
41+ css: "text/css",
42+ js: "text/javascript",
43+ json: "application/json",
44+ png: "image/png",
45+ jpg: "image/jpeg",
46+ jpeg: "image/jpeg",
47+ gif: "image/gif",
48+ };
49+ /**
50+ * Creates a new `FileResponse` object.
51+ * @param {string|URL} filePath
52+ */
53+ constructor(filePath) {
54+ this.filePath = filePath;
55+ this.headers = new Headers();
56+
57+ this.exists = fs.existsSync(filePath);
58+ if (this.exists) {
59+ this.status = 200;
60+ this.statusText = "OK";
61+
62+ let stats = fs.statSync(filePath);
63+ this.headers.set("content-length", stats.size.toString());
64+
65+ this.updateContentType();
66+
67+ let self = this;
68+ this.body = new ReadableStream({
69+ start(controller) {
70+ self.arrayBuffer().then((buffer) => {
71+ controller.enqueue(new Uint8Array(buffer));
72+ controller.close();
73+ });
74+ },
75+ });
76+ } else {
77+ this.status = 404;
78+ this.statusText = "Not Found";
79+ this.body = null;
15080 }
81+ }
82+
83+ /**
84+ * Updates the 'content-type' header property of the response based on the extension of
85+ * the file specified by the filePath property of the current object.
86+ * @returns {void}
87+ */
88+ updateContentType() {
89+ // Set content-type header based on file extension
90+ const extension = this.filePath.toString().split(".").pop().toLowerCase();
91+ this.headers.set(
92+ "content-type",
93+ this._CONTENT_TYPE_MAP[extension] ?? "application/octet-stream",
94+ );
95+ }
96+
97+ /**
98+ * Clone the current FileResponse object.
99+ * @returns {FileResponse} A new FileResponse object with the same properties as the current object.
100+ */
101+ clone() {
102+ let response = new FileResponse(this.filePath);
103+ response.exists = this.exists;
104+ response.status = this.status;
105+ response.statusText = this.statusText;
106+ response.headers = new Headers(this.headers);
107+ return response;
108+ }
109+
110+ /**
111+ * Reads the contents of the file specified by the filePath property and returns a Promise that
112+ * resolves with an ArrayBuffer containing the file's contents.
113+ * @returns {Promise<ArrayBuffer>} A Promise that resolves with an ArrayBuffer containing the file's contents.
114+ * @throws {Error} If the file cannot be read.
115+ */
116+ async arrayBuffer() {
117+ const data = await fs.promises.readFile(this.filePath);
118+ return data.buffer;
119+ }
120+
121+ /**
122+ * Reads the contents of the file specified by the filePath property and returns a Promise that
123+ * resolves with a Blob containing the file's contents.
124+ * @returns {Promise<Blob>} A Promise that resolves with a Blob containing the file's contents.
125+ * @throws {Error} If the file cannot be read.
126+ */
127+ async blob() {
128+ const data = await fs.promises.readFile(this.filePath);
129+ return new Blob([data], { type: this.headers.get("content-type") });
130+ }
131+
132+ /**
133+ * Reads the contents of the file specified by the filePath property and returns a Promise that
134+ * resolves with a string containing the file's contents.
135+ * @returns {Promise<string>} A Promise that resolves with a string containing the file's contents.
136+ * @throws {Error} If the file cannot be read.
137+ */
138+ async text() {
139+ const data = await fs.promises.readFile(this.filePath, "utf8");
140+ return data;
141+ }
142+
143+ /**
144+ * Reads the contents of the file specified by the filePath property and returns a Promise that
145+ * resolves with a parsed JavaScript object containing the file's contents.
146+ *
147+ * @returns {Promise<Object>} A Promise that resolves with a parsed JavaScript object containing the file's contents.
148+ * @throws {Error} If the file cannot be read.
149+ */
150+ async json() {
151+ return JSON.parse(await this.text());
152+ }
151153 }
152154
153155 /**
@@ -157,17 +159,17 @@
157159 * @returns {boolean} True if the string is a valid HTTP or HTTPS URL, false otherwise.
158160 */
159161 function isValidHttpUrl(string, validHosts = null) {
160- // https://stackoverflow.com/a/43467144
161- let url;
162- try {
163- url = new URL(string);
164- } catch (_) {
165- return false;
166- }
167- if (validHosts && !validHosts.includes(url.hostname)) {
168- return false;
169- }
170- return url.protocol === "http:" || url.protocol === "https:";
162+ // https://stackoverflow.com/a/43467144
163+ let url;
164+ try {
165+ url = new URL(string);
166+ } catch (_) {
167+ return false;
168+ }
169+ if (validHosts && !validHosts.includes(url.hostname)) {
170+ return false;
171+ }
172+ return url.protocol === "http:" || url.protocol === "https:";
171173 }
172174
173175 /**
@@ -177,51 +179,52 @@
177179 * @returns {Promise<FileResponse|Response>} A promise that resolves to a FileResponse object (if the file is retrieved using the FileSystem API), or a Response object (if the file is retrieved using the Fetch API).
178180 */
179181 export async function getFile(urlOrPath) {
180-
181- if (env.useFS && !isValidHttpUrl(urlOrPath)) {
182- return new FileResponse(urlOrPath);
183-
184- } else if (typeof process !== 'undefined' && process?.release?.name === 'node') {
185- const IS_CI = !!process.env?.TESTING_REMOTELY;
186- const version = env.version;
187-
188- const headers = new Headers();
189- headers.set('User-Agent', `transformers.js/${version}; is_ci/${IS_CI};`);
190-
191- // Check whether we are making a request to the Hugging Face Hub.
192- const isHFURL = isValidHttpUrl(urlOrPath, ['huggingface.co', 'hf.co']);
193- if (isHFURL) {
194- // If an access token is present in the environment variables,
195- // we add it to the request headers.
196- // NOTE: We keep `HF_ACCESS_TOKEN` for backwards compatibility (as a fallback).
197- const token = process.env?.HF_TOKEN ?? process.env?.HF_ACCESS_TOKEN;
198- if (token) {
199- headers.set('Authorization', `Bearer ${token}`);
200- }
201- }
202- return fetch(urlOrPath, { headers });
203- } else {
204- // Running in a browser-environment, so we use default headers
205- // NOTE: We do not allow passing authorization headers in the browser,
206- // since this would require exposing the token to the client.
207- return fetch(urlOrPath);
182+ if (env.useFS && !isValidHttpUrl(urlOrPath)) {
183+ return new FileResponse(urlOrPath);
184+ } else if (
185+ typeof process !== "undefined" &&
186+ process?.release?.name === "node"
187+ ) {
188+ const IS_CI = !!process.env?.TESTING_REMOTELY;
189+ const version = env.version;
190+
191+ const headers = new Headers();
192+ headers.set("User-Agent", `transformers.js/${version}; is_ci/${IS_CI};`);
193+
194+ // Check whether we are making a request to the Hugging Face Hub.
195+ const isHFURL = isValidHttpUrl(urlOrPath, ["huggingface.co", "hf.co"]);
196+ if (isHFURL) {
197+ // If an access token is present in the environment variables,
198+ // we add it to the request headers.
199+ // NOTE: We keep `HF_ACCESS_TOKEN` for backwards compatibility (as a fallback).
200+ const token = process.env?.HF_TOKEN ?? process.env?.HF_ACCESS_TOKEN;
201+ if (token) {
202+ headers.set("Authorization", `Bearer ${token}`);
203+ }
208204 }
205+ return fetch(urlOrPath, { headers });
206+ } else {
207+ // Running in a browser-environment, so we use default headers
208+ // NOTE: We do not allow passing authorization headers in the browser,
209+ // since this would require exposing the token to the client.
210+ return fetch(urlOrPath);
211+ }
209212 }
210213
211214 const ERROR_MAPPING = {
212- // 4xx errors (https://developer.mozilla.org/en-US/docs/Web/HTTP/Status#client_error_responses)
213- 400: 'Bad request error occurred while trying to load file',
214- 401: 'Unauthorized access to file',
215- 403: 'Forbidden access to file',
216- 404: 'Could not locate file',
217- 408: 'Request timeout error occurred while trying to load file',
218-
219- // 5xx errors (https://developer.mozilla.org/en-US/docs/Web/HTTP/Status#server_error_responses)
220- 500: 'Internal server error error occurred while trying to load file',
221- 502: 'Bad gateway error occurred while trying to load file',
222- 503: 'Service unavailable error occurred while trying to load file',
223- 504: 'Gateway timeout error occurred while trying to load file',
224-}
215+ // 4xx errors (https://developer.mozilla.org/en-US/docs/Web/HTTP/Status#client_error_responses)
216+ 400: "Bad request error occurred while trying to load file",
217+ 401: "Unauthorized access to file",
218+ 403: "Forbidden access to file",
219+ 404: "Could not locate file",
220+ 408: "Request timeout error occurred while trying to load file",
221+
222+ // 5xx errors (https://developer.mozilla.org/en-US/docs/Web/HTTP/Status#server_error_responses)
223+ 500: "Internal server error error occurred while trying to load file",
224+ 502: "Bad gateway error occurred while trying to load file",
225+ 503: "Service unavailable error occurred while trying to load file",
226+ 504: "Gateway timeout error occurred while trying to load file",
227+};
225228 /**
226229 * Helper method to handle fatal errors that occur while trying to load a file from the Hugging Face Hub.
227230 * @param {number} status The HTTP status code of the error.
@@ -231,334 +234,355 @@
231234 * @throws {Error} If `fatal = false`.
232235 */
233236 function handleError(status, remoteURL, fatal) {
234- if (!fatal) {
235- // File was not loaded correctly, but it is optional.
236- // TODO in future, cache the response?
237- return null;
238- }
239-
240- const message = ERROR_MAPPING[status] ?? `Error (${status}) occurred while trying to load file`;
241- throw Error(`${message}: "${remoteURL}".`);
237+ if (!fatal) {
238+ // File was not loaded correctly, but it is optional.
239+ // TODO in future, cache the response?
240+ return null;
241+ }
242+
243+ const message =
244+ ERROR_MAPPING[status] ??
245+ `Error (${status}) occurred while trying to load file`;
246+ throw Error(`${message}: "${remoteURL}".`);
242247 }
243248
244249 class FileCache {
245- /**
246- * Instantiate a `FileCache` object.
247- * @param {string} path
248- */
249- constructor(path) {
250- this.path = path;
251- }
252-
253- /**
254- * Checks whether the given request is in the cache.
255- * @param {string} request
256- * @returns {Promise<FileResponse | undefined>}
257- */
258- async match(request) {
259-
260- let filePath = path.join(this.path, request);
261- let file = new FileResponse(filePath);
262-
263- if (file.exists) {
264- return file;
265- } else {
266- return undefined;
267- }
250+ /**
251+ * Instantiate a `FileCache` object.
252+ * @param {string} path
253+ */
254+ constructor(path) {
255+ this.path = path;
256+ }
257+
258+ /**
259+ * Checks whether the given request is in the cache.
260+ * @param {string} request
261+ * @returns {Promise<FileResponse | undefined>}
262+ */
263+ async match(request) {
264+ let filePath = path.join(this.path, request);
265+ let file = new FileResponse(filePath);
266+
267+ if (file.exists) {
268+ return file;
269+ } else {
270+ return undefined;
268271 }
272+ }
273+
274+ /**
275+ * Adds the given response to the cache.
276+ * @param {string} request
277+ * @param {Response|FileResponse} response
278+ * @returns {Promise<void>}
279+ */
280+ async put(request, response) {
281+ const buffer = Buffer.from(await response.arrayBuffer());
282+
283+ let outputPath = path.join(this.path, request);
269284
270- /**
271- * Adds the given response to the cache.
272- * @param {string} request
273- * @param {Response|FileResponse} response
274- * @returns {Promise<void>}
275- */
276- async put(request, response) {
277- const buffer = Buffer.from(await response.arrayBuffer());
278-
279- let outputPath = path.join(this.path, request);
280-
281- try {
282- await fs.promises.mkdir(path.dirname(outputPath), { recursive: true });
283- await fs.promises.writeFile(outputPath, buffer);
284-
285- } catch (err) {
286- console.warn('An error occurred while writing the file to cache:', err)
287- }
285+ try {
286+ await fs.promises.mkdir(path.dirname(outputPath), { recursive: true });
287+ await fs.promises.writeFile(outputPath, buffer);
288+ } catch (err) {
289+ console.warn("An error occurred while writing the file to cache:", err);
288290 }
289-
290- // TODO add the rest?
291- // addAll(requests: RequestInfo[]): Promise<void>;
292- // delete(request: RequestInfo | URL, options?: CacheQueryOptions): Promise<boolean>;
293- // keys(request?: RequestInfo | URL, options?: CacheQueryOptions): Promise<ReadonlyArray<Request>>;
294- // match(request: RequestInfo | URL, options?: CacheQueryOptions): Promise<Response | undefined>;
295- // matchAll(request?: RequestInfo | URL, options?: CacheQueryOptions): Promise<ReadonlyArray<Response>>;
291+ }
292+
293+ // TODO add the rest?
294+ // addAll(requests: RequestInfo[]): Promise<void>;
295+ // delete(request: RequestInfo | URL, options?: CacheQueryOptions): Promise<boolean>;
296+ // keys(request?: RequestInfo | URL, options?: CacheQueryOptions): Promise<ReadonlyArray<Request>>;
297+ // match(request: RequestInfo | URL, options?: CacheQueryOptions): Promise<Response | undefined>;
298+ // matchAll(request?: RequestInfo | URL, options?: CacheQueryOptions): Promise<ReadonlyArray<Response>>;
296299 }
297300
298301 /**
299- *
302+ *
300303 * @param {FileCache|Cache} cache The cache to search
301304 * @param {string[]} names The names of the item to search for
302305 * @returns {Promise<FileResponse|Response|undefined>} The item from the cache, or undefined if not found.
303306 */
304307 async function tryCache(cache, ...names) {
305- for (let name of names) {
306- try {
307- let result = await cache.match(name);
308- if (result) return result;
309- } catch (e) {
310- continue;
311- }
308+ for (let name of names) {
309+ try {
310+ let result = await cache.match(name);
311+ if (result) return result;
312+ } catch (e) {
313+ continue;
312314 }
313- return undefined;
315+ }
316+ return undefined;
314317 }
315318
316319 /**
317- *
320+ *
318321 * Retrieves a file from either a remote URL using the Fetch API or from the local file system using the FileSystem API.
319322 * If the filesystem is available and `env.useCache = true`, the file will be downloaded and cached.
320- *
323+ *
321324 * @param {string} path_or_repo_id This can be either:
322325 * - a string, the *model id* of a model repo on huggingface.co.
323326 * - a path to a *directory* potentially containing the file.
324327 * @param {string} filename The name of the file to locate in `path_or_repo`.
325328 * @param {boolean} [fatal=true] Whether to throw an error if the file is not found.
326329 * @param {PretrainedOptions} [options] An object containing optional parameters.
327- *
330+ *
328331 * @throws Will throw an error if the file is not found and `fatal` is true.
329332 * @returns {Promise} A Promise that resolves with the file content as a buffer.
330333 */
331-export async function getModelFile(path_or_repo_id, filename, fatal = true, options = {}) {
332-
333- if (!env.allowLocalModels) {
334- // User has disabled local models, so we just make sure other settings are correct.
335-
336- if (options.local_files_only) {
337- throw Error("Invalid configuration detected: local models are disabled (`env.allowLocalModels=false`) but you have requested to only use local models (`local_files_only=true`).")
338- } else if (!env.allowRemoteModels) {
339- throw Error("Invalid configuration detected: both local and remote models are disabled. Fix by setting `env.allowLocalModels` or `env.allowRemoteModels` to `true`.")
340- }
334+export async function getModelFile(
335+ path_or_repo_id,
336+ filename,
337+ fatal = true,
338+ options = {},
339+) {
340+ if (!env.allowLocalModels) {
341+ // User has disabled local models, so we just make sure other settings are correct.
342+
343+ if (options.local_files_only) {
344+ throw Error(
345+ "Invalid configuration detected: local models are disabled (`env.allowLocalModels=false`) but you have requested to only use local models (`local_files_only=true`).",
346+ );
347+ } else if (!env.allowRemoteModels) {
348+ throw Error(
349+ "Invalid configuration detected: both local and remote models are disabled. Fix by setting `env.allowLocalModels` or `env.allowRemoteModels` to `true`.",
350+ );
341351 }
342-
343- // Initiate file retrieval
344- dispatchCallback(options.progress_callback, {
345- status: 'initiate',
346- name: path_or_repo_id,
347- file: filename
348- })
349-
350- // First, check if the a caching backend is available
351- // If no caching mechanism available, will download the file every time
352- let cache;
353- if (!cache && env.useBrowserCache) {
354- if (typeof caches === 'undefined') {
355- throw Error('Browser cache is not available in this environment.')
356- }
357- try {
358- // In some cases, the browser cache may be visible, but not accessible due to security restrictions.
359- // For example, when running an application in an iframe, if a user attempts to load the page in
360- // incognito mode, the following error is thrown: `DOMException: Failed to execute 'open' on 'CacheStorage':
361- // An attempt was made to break through the security policy of the user agent.`
362- // So, instead of crashing, we just ignore the error and continue without using the cache.
363- cache = await caches.open('transformers-cache');
364- } catch (e) {
365- console.warn('An error occurred while opening the browser cache:', e);
366- }
352+ }
353+
354+ // Initiate file retrieval
355+ dispatchCallback(options.progress_callback, {
356+ status: "initiate",
357+ name: path_or_repo_id,
358+ file: filename,
359+ });
360+
361+ // First, check if the a caching backend is available
362+ // If no caching mechanism available, will download the file every time
363+ let cache;
364+ if (!cache && env.useBrowserCache) {
365+ if (typeof caches === "undefined") {
366+ throw Error("Browser cache is not available in this environment.");
367367 }
368-
369- if (!cache && env.useFSCache) {
370- // TODO throw error if not available
371-
372- // If `cache_dir` is not specified, use the default cache directory
373- cache = new FileCache(options.cache_dir ?? env.cacheDir);
368+ try {
369+ // In some cases, the browser cache may be visible, but not accessible due to security restrictions.
370+ // For example, when running an application in an iframe, if a user attempts to load the page in
371+ // incognito mode, the following error is thrown: `DOMException: Failed to execute 'open' on 'CacheStorage':
372+ // An attempt was made to break through the security policy of the user agent.`
373+ // So, instead of crashing, we just ignore the error and continue without using the cache.
374+ cache = await caches.open("transformers-cache");
375+ } catch (e) {
376+ console.warn("An error occurred while opening the browser cache:", e);
374377 }
375-
376- if (!cache && env.useCustomCache) {
377- // Allow the user to specify a custom cache system.
378- if (!env.customCache) {
379- throw Error('`env.useCustomCache=true`, but `env.customCache` is not defined.')
380- }
381-
382- // Check that the required methods are defined:
383- if (!env.customCache.match || !env.customCache.put) {
384- throw new Error(
385- "`env.customCache` must be an object which implements the `match` and `put` functions of the Web Cache API. " +
386- "For more information, see https://developer.mozilla.org/en-US/docs/Web/API/Cache"
387- )
388- }
389- cache = env.customCache;
378+ }
379+
380+ if (!cache && env.useFSCache) {
381+ // TODO throw error if not available
382+
383+ // If `cache_dir` is not specified, use the default cache directory
384+ cache = new FileCache(options.cache_dir ?? env.cacheDir);
385+ }
386+
387+ if (!cache && env.useCustomCache) {
388+ // Allow the user to specify a custom cache system.
389+ if (!env.customCache) {
390+ throw Error(
391+ "`env.useCustomCache=true`, but `env.customCache` is not defined.",
392+ );
390393 }
391394
392- const revision = options.revision ?? 'main';
393-
394- let requestURL = pathJoin(path_or_repo_id, filename);
395- let localPath = pathJoin(env.localModelPath, requestURL);
396-
397- let remoteURL = pathJoin(
398- env.remoteHost,
399- env.remotePathTemplate
400- .replaceAll('{model}', path_or_repo_id)
401- .replaceAll('{revision}', encodeURIComponent(revision)),
402- filename
403- );
404-
405- // Choose cache key for filesystem cache
406- // When using the main revision (default), we use the request URL as the cache key.
407- // If a specific revision is requested, we account for this in the cache key.
408- let fsCacheKey = revision === 'main' ? requestURL : pathJoin(path_or_repo_id, revision, filename);
409-
410- /** @type {string} */
411- let cacheKey;
412- let proposedCacheKey = cache instanceof FileCache ? fsCacheKey : remoteURL;
413-
414- // Whether to cache the final response in the end.
415- let toCacheResponse = false;
416-
417- /** @type {Response|FileResponse|undefined} */
418- let response;
419-
420- if (cache) {
421- // A caching system is available, so we try to get the file from it.
422- // 1. We first try to get from cache using the local path. In some environments (like deno),
423- // non-URL cache keys are not allowed. In these cases, `response` will be undefined.
424- // 2. If no response is found, we try to get from cache using the remote URL or file system cache.
425- response = await tryCache(cache, localPath, proposedCacheKey);
395+ // Check that the required methods are defined:
396+ if (!env.customCache.match || !env.customCache.put) {
397+ throw new Error(
398+ "`env.customCache` must be an object which implements the `match` and `put` functions of the Web Cache API. " +
399+ "For more information, see https://developer.mozilla.org/en-US/docs/Web/API/Cache",
400+ );
426401 }
427-
428- const cacheHit = response !== undefined;
429-
430- if (response === undefined) {
431- // Caching not available, or file is not cached, so we perform the request
432-
433- if (env.allowLocalModels) {
434- // Accessing local models is enabled, so we try to get the file locally.
435- // If request is a valid HTTP URL, we skip the local file check. Otherwise, we try to get the file locally.
436- const isURL = isValidHttpUrl(requestURL);
437- if (!isURL) {
438- try {
439- response = await getFile(localPath);
440- cacheKey = localPath; // Update the cache key to be the local path
441- } catch (e) {
442- // Something went wrong while trying to get the file locally.
443- // NOTE: error handling is done in the next step (since `response` will be undefined)
444- console.warn(`Unable to load from local path "${localPath}": "${e}"`);
445- }
446- } else if (options.local_files_only) {
447- throw new Error(`\`local_files_only=true\`, but attempted to load a remote file from: ${requestURL}.`);
448- } else if (!env.allowRemoteModels) {
449- throw new Error(`\`env.allowRemoteModels=false\`, but attempted to load a remote file from: ${requestURL}.`);
450- }
451- }
452-
453- if (response === undefined || response.status === 404) {
454- // File not found locally. This means either:
455- // - The user has disabled local file access (`env.allowLocalModels=false`)
456- // - the path is a valid HTTP url (`response === undefined`)
457- // - the path is not a valid HTTP url and the file is not present on the file system or local server (`response.status === 404`)
458-
459- if (options.local_files_only || !env.allowRemoteModels) {
460- // User requested local files only, but the file is not found locally.
461- if (fatal) {
462- throw Error(`\`local_files_only=true\` or \`env.allowRemoteModels=false\` and file was not found locally at "${localPath}".`);
463- } else {
464- // File not found, but this file is optional.
465- // TODO in future, cache the response?
466- return null;
467- }
468- }
469-
470- // File not found locally, so we try to download it from the remote server
471- response = await getFile(remoteURL);
472-
473- if (response.status !== 200) {
474- return handleError(response.status, remoteURL, fatal);
475- }
476-
477- // Success! We use the proposed cache key from earlier
478- cacheKey = proposedCacheKey;
402+ cache = env.customCache;
403+ }
404+
405+ const revision = options.revision ?? "main";
406+
407+ let requestURL = pathJoin(path_or_repo_id, filename);
408+ let localPath = pathJoin(env.localModelPath, requestURL);
409+
410+ let remoteURL = pathJoin(
411+ env.remoteHost,
412+ env.remotePathTemplate
413+ .replaceAll("{model}", path_or_repo_id)
414+ .replaceAll("{revision}", encodeURIComponent(revision)),
415+ filename,
416+ );
417+
418+ // Choose cache key for filesystem cache
419+ // When using the main revision (default), we use the request URL as the cache key.
420+ // If a specific revision is requested, we account for this in the cache key.
421+ let fsCacheKey =
422+ revision === "main"
423+ ? requestURL
424+ : pathJoin(path_or_repo_id, revision, filename);
425+
426+ /** @type {string} */
427+ let cacheKey;
428+ let proposedCacheKey = cache instanceof FileCache ? fsCacheKey : remoteURL;
429+
430+ // Whether to cache the final response in the end.
431+ let toCacheResponse = false;
432+
433+ /** @type {Response|FileResponse|undefined} */
434+ let response;
435+
436+ if (cache) {
437+ // A caching system is available, so we try to get the file from it.
438+ // 1. We first try to get from cache using the local path. In some environments (like deno),
439+ // non-URL cache keys are not allowed. In these cases, `response` will be undefined.
440+ // 2. If no response is found, we try to get from cache using the remote URL or file system cache.
441+ response = await tryCache(cache, localPath, proposedCacheKey);
442+ }
443+
444+ const cacheHit = response !== undefined;
445+
446+ if (response === undefined) {
447+ // Caching not available, or file is not cached, so we perform the request
448+
449+ if (env.allowLocalModels) {
450+ // Accessing local models is enabled, so we try to get the file locally.
451+ // If request is a valid HTTP URL, we skip the local file check. Otherwise, we try to get the file locally.
452+ const isURL = isValidHttpUrl(requestURL);
453+ if (!isURL) {
454+ try {
455+ response = await getFile(localPath);
456+ cacheKey = localPath; // Update the cache key to be the local path
457+ } catch (e) {
458+ // Something went wrong while trying to get the file locally.
459+ // NOTE: error handling is done in the next step (since `response` will be undefined)
460+ console.warn(`Unable to load from local path "${localPath}": "${e}"`);
479461 }
480-
481- // Only cache the response if:
482- toCacheResponse =
483- cache // 1. A caching system is available
484- && typeof Response !== 'undefined' // 2. `Response` is defined (i.e., we are in a browser-like environment)
485- && response instanceof Response // 3. result is a `Response` object (i.e., not a `FileResponse`)
486- && response.status === 200 // 4. request was successful (status code 200)
462+ } else if (options.local_files_only) {
463+ throw new Error(
464+ `\`local_files_only=true\`, but attempted to load a remote file from: ${requestURL}.`,
465+ );
466+ } else if (!env.allowRemoteModels) {
467+ throw new Error(
468+ `\`env.allowRemoteModels=false\`, but attempted to load a remote file from: ${requestURL}.`,
469+ );
470+ }
487471 }
488472
489- // Start downloading
490- dispatchCallback(options.progress_callback, {
491- status: 'download',
492- name: path_or_repo_id,
493- file: filename
494- })
495-
496- const progressInfo = {
497- status: 'progress',
498- name: path_or_repo_id,
499- file: filename
500- }
473+ if (response === undefined || response.status === 404) {
474+ // File not found locally. This means either:
475+ // - The user has disabled local file access (`env.allowLocalModels=false`)
476+ // - the path is a valid HTTP url (`response === undefined`)
477+ // - the path is not a valid HTTP url and the file is not present on the file system or local server (`response.status === 404`)
478+
479+ if (options.local_files_only || !env.allowRemoteModels) {
480+ // User requested local files only, but the file is not found locally.
481+ if (fatal) {
482+ throw Error(
483+ `\`local_files_only=true\` or \`env.allowRemoteModels=false\` and file was not found locally at "${localPath}".`,
484+ );
485+ } else {
486+ // File not found, but this file is optional.
487+ // TODO in future, cache the response?
488+ return null;
489+ }
490+ }
501491
502- /** @type {Uint8Array} */
503- let buffer;
504-
505- if (!options.progress_callback) {
506- // If no progress callback is specified, we can use the `.arrayBuffer()`
507- // method to read the response.
508- buffer = new Uint8Array(await response.arrayBuffer());
509-
510- } else if (
511- cacheHit // The item is being read from the cache
512- &&
513- typeof navigator !== 'undefined' && /firefox/i.test(navigator.userAgent) // We are in Firefox
514- ) {
515- // Due to bug in Firefox, we cannot display progress when loading from cache.
516- // Fortunately, since this should be instantaneous, this should not impact users too much.
517- buffer = new Uint8Array(await response.arrayBuffer());
518-
519- // For completeness, we still fire the final progress callback
520- dispatchCallback(options.progress_callback, {
521- ...progressInfo,
522- progress: 100,
523- loaded: buffer.length,
524- total: buffer.length,
525- })
526- } else {
527- buffer = await readResponse(response, data => {
528- dispatchCallback(options.progress_callback, {
529- ...progressInfo,
530- ...data,
531- })
532- })
533- }
492+ // File not found locally, so we try to download it from the remote server
493+ response = await getFile(remoteURL);
534494
535- if (
536- // Only cache web responses
537- // i.e., do not cache FileResponses (prevents duplication)
538- toCacheResponse && cacheKey
539- &&
540- // Check again whether request is in cache. If not, we add the response to the cache
541- (await cache.match(cacheKey) === undefined)
542- ) {
543- // NOTE: We use `new Response(buffer, ...)` instead of `response.clone()` to handle LFS files
544- await cache.put(cacheKey, new Response(buffer, {
545- headers: response.headers
546- }))
547- .catch(err => {
548- // Do not crash if unable to add to cache (e.g., QuotaExceededError).
549- // Rather, log a warning and proceed with execution.
550- console.warn(`Unable to add response to browser cache: ${err}.`);
551- });
495+ if (response.status !== 200) {
496+ return handleError(response.status, remoteURL, fatal);
497+ }
552498
499+ // Success! We use the proposed cache key from earlier
500+ cacheKey = proposedCacheKey;
553501 }
554502
503+ // Only cache the response if:
504+ toCacheResponse =
505+ cache && // 1. A caching system is available
506+ typeof Response !== "undefined" && // 2. `Response` is defined (i.e., we are in a browser-like environment)
507+ response instanceof Response && // 3. result is a `Response` object (i.e., not a `FileResponse`)
508+ response.status === 200; // 4. request was successful (status code 200)
509+ }
510+
511+ // Start downloading
512+ dispatchCallback(options.progress_callback, {
513+ status: "download",
514+ name: path_or_repo_id,
515+ file: filename,
516+ });
517+
518+ const progressInfo = {
519+ status: "progress",
520+ name: path_or_repo_id,
521+ file: filename,
522+ };
523+
524+ /** @type {Uint8Array} */
525+ let buffer;
526+
527+ if (!options.progress_callback) {
528+ // If no progress callback is specified, we can use the `.arrayBuffer()`
529+ // method to read the response.
530+ buffer = new Uint8Array(await response.arrayBuffer());
531+ } else if (
532+ cacheHit && // The item is being read from the cache
533+ typeof navigator !== "undefined" &&
534+ /firefox/i.test(navigator.userAgent) // We are in Firefox
535+ ) {
536+ // Due to bug in Firefox, we cannot display progress when loading from cache.
537+ // Fortunately, since this should be instantaneous, this should not impact users too much.
538+ buffer = new Uint8Array(await response.arrayBuffer());
539+
540+ // For completeness, we still fire the final progress callback
555541 dispatchCallback(options.progress_callback, {
556- status: 'done',
557- name: path_or_repo_id,
558- file: filename
542+ ...progressInfo,
543+ progress: 100,
544+ loaded: buffer.length,
545+ total: buffer.length,
559546 });
560-
561- return buffer;
547+ } else {
548+ buffer = await readResponse(response, (data) => {
549+ dispatchCallback(options.progress_callback, {
550+ ...progressInfo,
551+ ...data,
552+ });
553+ });
554+ }
555+
556+ if (
557+ // Only cache web responses
558+ // i.e., do not cache FileResponses (prevents duplication)
559+ toCacheResponse &&
560+ cacheKey &&
561+ // Check again whether request is in cache. If not, we add the response to the cache
562+ (await cache.match(cacheKey)) === undefined
563+ ) {
564+ // NOTE: We use `new Response(buffer, ...)` instead of `response.clone()` to handle LFS files
565+ await cache
566+ .put(
567+ cacheKey,
568+ new Response(buffer, {
569+ headers: response.headers,
570+ }),
571+ )
572+ .catch((err) => {
573+ // Do not crash if unable to add to cache (e.g., QuotaExceededError).
574+ // Rather, log a warning and proceed with execution.
575+ console.warn(`Unable to add response to browser cache: ${err}.`);
576+ });
577+ }
578+
579+ dispatchCallback(options.progress_callback, {
580+ status: "done",
581+ name: path_or_repo_id,
582+ file: filename,
583+ });
584+
585+ return buffer;
562586 }
563587
564588 /**
@@ -571,17 +595,22 @@
571595 * @returns {Promise<Object>} The JSON data parsed into a JavaScript object.
572596 * @throws Will throw an error if the file is not found and `fatal` is true.
573597 */
574-export async function getModelJSON(modelPath, fileName, fatal = true, options = {}) {
575- let buffer = await getModelFile(modelPath, fileName, fatal, options);
576- if (buffer === null) {
577- // Return empty object
578- return {}
579- }
580-
581- let decoder = new TextDecoder('utf-8');
582- let jsonData = decoder.decode(buffer);
583-
584- return JSON.parse(jsonData);
598+export async function getModelJSON(
599+ modelPath,
600+ fileName,
601+ fatal = true,
602+ options = {},
603+) {
604+ let buffer = await getModelFile(modelPath, fileName, fatal, options);
605+ if (buffer === null) {
606+ // Return empty object
607+ return {};
608+ }
609+
610+ let decoder = new TextDecoder("utf-8");
611+ let jsonData = decoder.decode(buffer);
612+
613+ return JSON.parse(jsonData);
585614 }
586615
587616 /**
@@ -592,52 +621,53 @@
592621 * @returns {Promise<Uint8Array>} A Promise that resolves with the Uint8Array buffer
593622 */
594623 async function readResponse(response, progress_callback) {
595-
596- const contentLength = response.headers.get('Content-Length');
597- if (contentLength === null) {
598- console.warn('Unable to determine content-length from response headers. Will expand buffer when needed.')
599- }
600- let total = parseInt(contentLength ?? '0');
601- let buffer = new Uint8Array(total);
602- let loaded = 0;
603-
604- const reader = response.body.getReader();
605- async function read() {
606- const { done, value } = await reader.read();
607- if (done) return;
608-
609- let newLoaded = loaded + value.length;
610- if (newLoaded > total) {
611- total = newLoaded;
612-
613- // Adding the new data will overflow buffer.
614- // In this case, we extend the buffer
615- let newBuffer = new Uint8Array(total);
616-
617- // copy contents
618- newBuffer.set(buffer);
619-
620- buffer = newBuffer;
621- }
622- buffer.set(value, loaded)
623- loaded = newLoaded;
624-
625- const progress = (loaded / total) * 100;
626-
627- // Call your function here
628- progress_callback({
629- progress: progress,
630- loaded: loaded,
631- total: total,
632- })
633-
634- return read();
624+ const contentLength = response.headers.get("Content-Length");
625+ if (contentLength === null) {
626+ console.warn(
627+ "Unable to determine content-length from response headers. Will expand buffer when needed.",
628+ );
629+ }
630+ let total = parseInt(contentLength ?? "0");
631+ let buffer = new Uint8Array(total);
632+ let loaded = 0;
633+
634+ const reader = response.body.getReader();
635+ async function read() {
636+ const { done, value } = await reader.read();
637+ if (done) return;
638+
639+ let newLoaded = loaded + value.length;
640+ if (newLoaded > total) {
641+ total = newLoaded;
642+
643+ // Adding the new data will overflow buffer.
644+ // In this case, we extend the buffer
645+ let newBuffer = new Uint8Array(total);
646+
647+ // copy contents
648+ newBuffer.set(buffer);
649+
650+ buffer = newBuffer;
635651 }
652+ buffer.set(value, loaded);
653+ loaded = newLoaded;
654+
655+ const progress = (loaded / total) * 100;
656+
657+ // Call your function here
658+ progress_callback({
659+ progress: progress,
660+ loaded: loaded,
661+ total: total,
662+ });
636663
637- // Actually read
638- await read();
664+ return read();
665+ }
639666
640- return buffer;
667+ // Actually read
668+ await read();
669+
670+ return buffer;
641671 }
642672
643673 /**
@@ -647,15 +677,15 @@
647677 * @returns {string} A string representing the joined path.
648678 */
649679 function pathJoin(...parts) {
650- // https://stackoverflow.com/a/55142565
651- parts = parts.map((part, index) => {
652- if (index) {
653- part = part.replace(new RegExp('^/'), '');
654- }
655- if (index !== parts.length - 1) {
656- part = part.replace(new RegExp('/$'), '');
657- }
658- return part;
659- })
660- return parts.join('/');
680+ // https://stackoverflow.com/a/55142565
681+ parts = parts.map((part, index) => {
682+ if (index) {
683+ part = part.replace(new RegExp("^/"), "");
684+ }
685+ if (index !== parts.length - 1) {
686+ part = part.replace(new RegExp("/$"), "");
687+ }
688+ return part;
689+ });
690+ return parts.join("/");
661691 }
modified core/vendor/modules/@xenova/transformers/src/utils/image.js +724 −643
@@ -1,713 +1,794 @@
1-
21 /**
3- * @file Helper module for image processing.
4- *
5- * These functions and classes are only used internally,
2+ * @file Helper module for image processing.
3+ *
4+ * These functions and classes are only used internally,
65 * meaning an end-user shouldn't need to access anything here.
7- *
6+ *
87 * @module utils/image
98 */
109
11-import { getFile } from './hub.js';
12-import { env } from '../env.js';
10+import { getFile } from "./hub.js";
11+import { env } from "../env.js";
1312
1413 // Will be empty (or not used) if running in browser or web-worker
15-import sharp from 'sharp';
14+import sharp from "sharp";
1615
17-const BROWSER_ENV = typeof self !== 'undefined';
18-const WEBWORKER_ENV = BROWSER_ENV && self.constructor.name === 'DedicatedWorkerGlobalScope';
16+const BROWSER_ENV = typeof self !== "undefined";
17+const WEBWORKER_ENV =
18+ BROWSER_ENV && self.constructor.name === "DedicatedWorkerGlobalScope";
1919
2020 let createCanvasFunction;
2121 let ImageDataClass;
2222 let loadImageFunction;
2323 if (BROWSER_ENV) {
24- // Running in browser or web-worker
25- createCanvasFunction = (/** @type {number} */ width, /** @type {number} */ height) => {
26- if (!self.OffscreenCanvas) {
27- throw new Error('OffscreenCanvas not supported by this browser.');
28- }
29- return new self.OffscreenCanvas(width, height)
30- };
31- loadImageFunction = self.createImageBitmap;
32- ImageDataClass = self.ImageData;
33-
24+ // Running in browser or web-worker
25+ createCanvasFunction = (
26+ /** @type {number} */ width,
27+ /** @type {number} */ height,
28+ ) => {
29+ if (!self.OffscreenCanvas) {
30+ throw new Error("OffscreenCanvas not supported by this browser.");
31+ }
32+ return new self.OffscreenCanvas(width, height);
33+ };
34+ loadImageFunction = self.createImageBitmap;
35+ ImageDataClass = self.ImageData;
3436 } else if (sharp) {
35- // Running in Node.js, electron, or other non-browser environment
36-
37- loadImageFunction = async (/**@type {sharp.Sharp}*/img) => {
38- const metadata = await img.metadata();
39- const rawChannels = metadata.channels;
40-
41- let { data, info } = await img.raw().toBuffer({ resolveWithObject: true });
42-
43- const newImage = new RawImage(new Uint8ClampedArray(data), info.width, info.height, info.channels);
44- if (rawChannels !== undefined && rawChannels !== info.channels) {
45- // Make sure the new image has the same number of channels as the input image.
46- // This is necessary for grayscale images.
47- newImage.convert(rawChannels);
48- }
49- return newImage;
37+ // Running in Node.js, electron, or other non-browser environment
38+
39+ loadImageFunction = async (/**@type {sharp.Sharp}*/ img) => {
40+ const metadata = await img.metadata();
41+ const rawChannels = metadata.channels;
42+
43+ let { data, info } = await img.raw().toBuffer({ resolveWithObject: true });
44+
45+ const newImage = new RawImage(
46+ new Uint8ClampedArray(data),
47+ info.width,
48+ info.height,
49+ info.channels,
50+ );
51+ if (rawChannels !== undefined && rawChannels !== info.channels) {
52+ // Make sure the new image has the same number of channels as the input image.
53+ // This is necessary for grayscale images.
54+ newImage.convert(rawChannels);
5055 }
51-
56+ return newImage;
57+ };
5258 } else {
53- throw new Error('Unable to load image processing library.');
59+ throw new Error("Unable to load image processing library.");
5460 }
5561
56-
5762 // Defined here: https://github.com/python-pillow/Pillow/blob/a405e8406b83f8bfb8916e93971edc7407b8b1ff/src/libImaging/Imaging.h#L262-L268
5863 const RESAMPLING_MAPPING = {
59- 0: 'nearest',
60- 1: 'lanczos',
61- 2: 'bilinear',
62- 3: 'bicubic',
63- 4: 'box',
64- 5: 'hamming',
65-}
64+ 0: "nearest",
65+ 1: "lanczos",
66+ 2: "bilinear",
67+ 3: "bicubic",
68+ 4: "box",
69+ 5: "hamming",
70+};
6671
6772 /**
6873 * Mapping from file extensions to MIME types.
6974 */
7075 const CONTENT_TYPE_MAP = new Map([
71- ['png', 'image/png'],
72- ['jpg', 'image/jpeg'],
73- ['jpeg', 'image/jpeg'],
74- ['gif', 'image/gif'],
76+ ["png", "image/png"],
77+ ["jpg", "image/jpeg"],
78+ ["jpeg", "image/jpeg"],
79+ ["gif", "image/gif"],
7580 ]);
7681
7782 export class RawImage {
78-
79- /**
80- * Create a new `RawImage` object.
81- * @param {Uint8ClampedArray|Uint8Array} data The pixel data.
82- * @param {number} width The width of the image.
83- * @param {number} height The height of the image.
84- * @param {1|2|3|4} channels The number of channels.
85- */
86- constructor(data, width, height, channels) {
87- this.data = data;
88- this.width = width;
89- this.height = height;
90- this.channels = channels;
83+ /**
84+ * Create a new `RawImage` object.
85+ * @param {Uint8ClampedArray|Uint8Array} data The pixel data.
86+ * @param {number} width The width of the image.
87+ * @param {number} height The height of the image.
88+ * @param {1|2|3|4} channels The number of channels.
89+ */
90+ constructor(data, width, height, channels) {
91+ this.data = data;
92+ this.width = width;
93+ this.height = height;
94+ this.channels = channels;
95+ }
96+
97+ /**
98+ * Returns the size of the image (width, height).
99+ * @returns {[number, number]} The size of the image (width, height).
100+ */
101+ get size() {
102+ return [this.width, this.height];
103+ }
104+
105+ /**
106+ * Helper method for reading an image from a variety of input types.
107+ * @param {RawImage|string|URL} input
108+ * @returns The image object.
109+ *
110+ * **Example:** Read image from a URL.
111+ * ```javascript
112+ * let image = await RawImage.read('https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/football-match.jpg');
113+ * // RawImage {
114+ * // "data": Uint8ClampedArray [ 25, 25, 25, 19, 19, 19, ... ],
115+ * // "width": 800,
116+ * // "height": 533,
117+ * // "channels": 3
118+ * // }
119+ * ```
120+ */
121+ static async read(input) {
122+ if (input instanceof RawImage) {
123+ return input;
124+ } else if (typeof input === "string" || input instanceof URL) {
125+ return await this.fromURL(input);
126+ } else {
127+ throw new Error(`Unsupported input type: ${typeof input}`);
91128 }
92-
93- /**
94- * Returns the size of the image (width, height).
95- * @returns {[number, number]} The size of the image (width, height).
96- */
97- get size() {
98- return [this.width, this.height];
129+ }
130+
131+ /**
132+ * Read an image from a URL or file path.
133+ * @param {string|URL} url The URL or file path to read the image from.
134+ * @returns {Promise<RawImage>} The image object.
135+ */
136+ static async fromURL(url) {
137+ let response = await getFile(url);
138+ if (response.status !== 200) {
139+ throw new Error(
140+ `Unable to read image from "${url}" (${response.status} ${response.statusText})`,
141+ );
99142 }
100-
101- /**
102- * Helper method for reading an image from a variety of input types.
103- * @param {RawImage|string|URL} input
104- * @returns The image object.
105- *
106- * **Example:** Read image from a URL.
107- * ```javascript
108- * let image = await RawImage.read('https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/football-match.jpg');
109- * // RawImage {
110- * // "data": Uint8ClampedArray [ 25, 25, 25, 19, 19, 19, ... ],
111- * // "width": 800,
112- * // "height": 533,
113- * // "channels": 3
114- * // }
115- * ```
116- */
117- static async read(input) {
118- if (input instanceof RawImage) {
119- return input;
120- } else if (typeof input === 'string' || input instanceof URL) {
121- return await this.fromURL(input);
122- } else {
123- throw new Error(`Unsupported input type: ${typeof input}`);
124- }
143+ let blob = await response.blob();
144+ return this.fromBlob(blob);
145+ }
146+
147+ /**
148+ * Helper method to create a new Image from a blob.
149+ * @param {Blob} blob The blob to read the image from.
150+ * @returns {Promise<RawImage>} The image object.
151+ */
152+ static async fromBlob(blob) {
153+ if (BROWSER_ENV) {
154+ // Running in environment with canvas
155+ let img = await loadImageFunction(blob);
156+
157+ const ctx = createCanvasFunction(img.width, img.height).getContext("2d");
158+
159+ // Draw image to context
160+ ctx.drawImage(img, 0, 0);
161+
162+ return new this(
163+ ctx.getImageData(0, 0, img.width, img.height).data,
164+ img.width,
165+ img.height,
166+ 4,
167+ );
168+ } else {
169+ // Use sharp.js to read (and possible resize) the image.
170+ let img = sharp(await blob.arrayBuffer());
171+
172+ return await loadImageFunction(img);
125173 }
126-
127-
128- /**
129- * Read an image from a URL or file path.
130- * @param {string|URL} url The URL or file path to read the image from.
131- * @returns {Promise<RawImage>} The image object.
132- */
133- static async fromURL(url) {
134- let response = await getFile(url);
135- if (response.status !== 200) {
136- throw new Error(`Unable to read image from "${url}" (${response.status} ${response.statusText})`);
137- }
138- let blob = await response.blob();
139- return this.fromBlob(blob);
174+ }
175+
176+ /**
177+ * Helper method to create a new Image from a tensor
178+ * @param {import('./tensor.js').Tensor} tensor
179+ */
180+ static fromTensor(tensor, channel_format = "CHW") {
181+ if (tensor.dims.length !== 3) {
182+ throw new Error(
183+ `Tensor should have 3 dimensions, but has ${tensor.dims.length} dimensions.`,
184+ );
140185 }
141186
142- /**
143- * Helper method to create a new Image from a blob.
144- * @param {Blob} blob The blob to read the image from.
145- * @returns {Promise<RawImage>} The image object.
146- */
147- static async fromBlob(blob) {
148- if (BROWSER_ENV) {
149- // Running in environment with canvas
150- let img = await loadImageFunction(blob);
151-
152- const ctx = createCanvasFunction(img.width, img.height).getContext('2d');
153-
154- // Draw image to context
155- ctx.drawImage(img, 0, 0);
156-
157- return new this(ctx.getImageData(0, 0, img.width, img.height).data, img.width, img.height, 4);
158-
159- } else {
160- // Use sharp.js to read (and possible resize) the image.
161- let img = sharp(await blob.arrayBuffer());
162-
163- return await loadImageFunction(img);
164- }
187+ if (channel_format === "CHW") {
188+ tensor = tensor.transpose(1, 2, 0);
189+ } else if (channel_format === "HWC") {
190+ // Do nothing
191+ } else {
192+ throw new Error(`Unsupported channel format: ${channel_format}`);
165193 }
166-
167- /**
168- * Helper method to create a new Image from a tensor
169- * @param {import('./tensor.js').Tensor} tensor
170- */
171- static fromTensor(tensor, channel_format = 'CHW') {
172- if (tensor.dims.length !== 3) {
173- throw new Error(`Tensor should have 3 dimensions, but has ${tensor.dims.length} dimensions.`);
174- }
175-
176- if (channel_format === 'CHW') {
177- tensor = tensor.transpose(1, 2, 0);
178- } else if (channel_format === 'HWC') {
179- // Do nothing
180- } else {
181- throw new Error(`Unsupported channel format: ${channel_format}`);
182- }
183- if (!(tensor.data instanceof Uint8ClampedArray || tensor.data instanceof Uint8Array)) {
184- throw new Error(`Unsupported tensor type: ${tensor.type}`);
185- }
186- switch (tensor.dims[2]) {
187- case 1:
188- case 2:
189- case 3:
190- case 4:
191- return new RawImage(tensor.data, tensor.dims[1], tensor.dims[0], tensor.dims[2]);
192- default:
193- throw new Error(`Unsupported number of channels: ${tensor.dims[2]}`);
194- }
194+ if (
195+ !(
196+ tensor.data instanceof Uint8ClampedArray ||
197+ tensor.data instanceof Uint8Array
198+ )
199+ ) {
200+ throw new Error(`Unsupported tensor type: ${tensor.type}`);
195201 }
196-
197- /**
198- * Convert the image to grayscale format.
199- * @returns {RawImage} `this` to support chaining.
200- */
201- grayscale() {
202- if (this.channels === 1) {
203- return this;
204- }
205-
206- let newData = new Uint8ClampedArray(this.width * this.height * 1);
207- switch (this.channels) {
208- case 3: // rgb to grayscale
209- case 4: // rgba to grayscale
210- for (let i = 0, offset = 0; i < this.data.length; i += this.channels) {
211- const red = this.data[i];
212- const green = this.data[i + 1];
213- const blue = this.data[i + 2];
214-
215- newData[offset++] = Math.round(0.2989 * red + 0.5870 * green + 0.1140 * blue);
216- }
217- break;
218- default:
219- throw new Error(`Conversion failed due to unsupported number of channels: ${this.channels}`);
220- }
221- return this._update(newData, this.width, this.height, 1);
202+ switch (tensor.dims[2]) {
203+ case 1:
204+ case 2:
205+ case 3:
206+ case 4:
207+ return new RawImage(
208+ tensor.data,
209+ tensor.dims[1],
210+ tensor.dims[0],
211+ tensor.dims[2],
212+ );
213+ default:
214+ throw new Error(`Unsupported number of channels: ${tensor.dims[2]}`);
222215 }
223-
224- /**
225- * Convert the image to RGB format.
226- * @returns {RawImage} `this` to support chaining.
227- */
228- rgb() {
229- if (this.channels === 3) {
230- return this;
231- }
232-
233- let newData = new Uint8ClampedArray(this.width * this.height * 3);
234-
235- switch (this.channels) {
236- case 1: // grayscale to rgb
237- for (let i = 0, offset = 0; i < this.data.length; ++i) {
238- newData[offset++] = this.data[i];
239- newData[offset++] = this.data[i];
240- newData[offset++] = this.data[i];
241- }
242- break;
243- case 4: // rgba to rgb
244- for (let i = 0, offset = 0; i < this.data.length; i += 4) {
245- newData[offset++] = this.data[i];
246- newData[offset++] = this.data[i + 1];
247- newData[offset++] = this.data[i + 2];
248- }
249- break;
250- default:
251- throw new Error(`Conversion failed due to unsupported number of channels: ${this.channels}`);
252- }
253- return this._update(newData, this.width, this.height, 3);
254-
216+ }
217+
218+ /**
219+ * Convert the image to grayscale format.
220+ * @returns {RawImage} `this` to support chaining.
221+ */
222+ grayscale() {
223+ if (this.channels === 1) {
224+ return this;
255225 }
256226
257- /**
258- * Convert the image to RGBA format.
259- * @returns {RawImage} `this` to support chaining.
260- */
261- rgba() {
262- if (this.channels === 4) {
263- return this;
264- }
265-
266- let newData = new Uint8ClampedArray(this.width * this.height * 4);
267-
268- switch (this.channels) {
269- case 1: // grayscale to rgba
270- for (let i = 0, offset = 0; i < this.data.length; ++i) {
271- newData[offset++] = this.data[i];
272- newData[offset++] = this.data[i];
273- newData[offset++] = this.data[i];
274- newData[offset++] = 255;
275- }
276- break;
277- case 3: // rgb to rgba
278- for (let i = 0, offset = 0; i < this.data.length; i += 3) {
279- newData[offset++] = this.data[i];
280- newData[offset++] = this.data[i + 1];
281- newData[offset++] = this.data[i + 2];
282- newData[offset++] = 255;
283- }
284- break;
285- default:
286- throw new Error(`Conversion failed due to unsupported number of channels: ${this.channels}`);
227+ let newData = new Uint8ClampedArray(this.width * this.height * 1);
228+ switch (this.channels) {
229+ case 3: // rgb to grayscale
230+ case 4: // rgba to grayscale
231+ for (let i = 0, offset = 0; i < this.data.length; i += this.channels) {
232+ const red = this.data[i];
233+ const green = this.data[i + 1];
234+ const blue = this.data[i + 2];
235+
236+ newData[offset++] = Math.round(
237+ 0.2989 * red + 0.587 * green + 0.114 * blue,
238+ );
287239 }
288-
289- return this._update(newData, this.width, this.height, 4);
240+ break;
241+ default:
242+ throw new Error(
243+ `Conversion failed due to unsupported number of channels: ${this.channels}`,
244+ );
290245 }
291-
292- /**
293- * Resize the image to the given dimensions. This method uses the canvas API to perform the resizing.
294- * @param {number} width The width of the new image.
295- * @param {number} height The height of the new image.
296- * @param {Object} options Additional options for resizing.
297- * @param {0|1|2|3|4|5|string} [options.resample] The resampling method to use.
298- * @returns {Promise<RawImage>} `this` to support chaining.
299- */
300- async resize(width, height, {
301- resample = 2,
302- } = {}) {
303-
304- // Ensure resample method is a string
305- let resampleMethod = RESAMPLING_MAPPING[resample] ?? resample;
306-
307- if (BROWSER_ENV) {
308- // TODO use `resample` in browser environment
309-
310- // Store number of channels before resizing
311- let numChannels = this.channels;
312-
313- // Create canvas object for this image
314- let canvas = this.toCanvas();
315-
316- // Actually perform resizing using the canvas API
317- const ctx = createCanvasFunction(width, height).getContext('2d');
318-
319- // Draw image to context, resizing in the process
320- ctx.drawImage(canvas, 0, 0, width, height);
321-
322- // Create image from the resized data
323- let resizedImage = new RawImage(ctx.getImageData(0, 0, width, height).data, width, height, 4);
324-
325- // Convert back so that image has the same number of channels as before
326- return resizedImage.convert(numChannels);
327-
328- } else {
329- // Create sharp image from raw data, and resize
330- let img = this.toSharp();
331-
332- switch (resampleMethod) {
333- case 'box':
334- case 'hamming':
335- if (resampleMethod === 'box' || resampleMethod === 'hamming') {
336- console.warn(`Resampling method ${resampleMethod} is not yet supported. Using bilinear instead.`);
337- resampleMethod = 'bilinear';
338- }
339-
340- case 'nearest':
341- case 'bilinear':
342- case 'bicubic':
343- // Perform resizing using affine transform.
344- // This matches how the python Pillow library does it.
345- img = img.affine([width / this.width, 0, 0, height / this.height], {
346- interpolator: resampleMethod
347- });
348- break;
349-
350- case 'lanczos':
351- // https://github.com/python-pillow/Pillow/discussions/5519
352- // https://github.com/lovell/sharp/blob/main/docs/api-resize.md
353- img = img.resize({
354- width, height,
355- fit: 'fill',
356- kernel: 'lanczos3', // PIL Lanczos uses a kernel size of 3
357- });
358- break;
359-
360- default:
361- throw new Error(`Resampling method ${resampleMethod} is not supported.`);
362- }
363-
364- return await loadImageFunction(img);
365- }
366-
246+ return this._update(newData, this.width, this.height, 1);
247+ }
248+
249+ /**
250+ * Convert the image to RGB format.
251+ * @returns {RawImage} `this` to support chaining.
252+ */
253+ rgb() {
254+ if (this.channels === 3) {
255+ return this;
367256 }
368257
369- async pad([left, right, top, bottom]) {
370- left = Math.max(left, 0);
371- right = Math.max(right, 0);
372- top = Math.max(top, 0);
373- bottom = Math.max(bottom, 0);
374-
375- if (left === 0 && right === 0 && top === 0 && bottom === 0) {
376- // No padding needed
377- return this;
258+ let newData = new Uint8ClampedArray(this.width * this.height * 3);
259+
260+ switch (this.channels) {
261+ case 1: // grayscale to rgb
262+ for (let i = 0, offset = 0; i < this.data.length; ++i) {
263+ newData[offset++] = this.data[i];
264+ newData[offset++] = this.data[i];
265+ newData[offset++] = this.data[i];
378266 }
379-
380- if (BROWSER_ENV) {
381- // Store number of channels before padding
382- let numChannels = this.channels;
383-
384- // Create canvas object for this image
385- let canvas = this.toCanvas();
386-
387- let newWidth = this.width + left + right;
388- let newHeight = this.height + top + bottom;
389-
390- // Create a new canvas of the desired size.
391- const ctx = createCanvasFunction(newWidth, newHeight).getContext('2d');
392-
393- // Draw image to context, padding in the process
394- ctx.drawImage(canvas,
395- 0, 0, this.width, this.height,
396- left, top, newWidth, newHeight
397- );
398-
399- // Create image from the padded data
400- let paddedImage = new RawImage(
401- ctx.getImageData(0, 0, newWidth, newHeight).data,
402- newWidth, newHeight, 4);
403-
404- // Convert back so that image has the same number of channels as before
405- return paddedImage.convert(numChannels);
406-
407- } else {
408- let img = this.toSharp().extend({ left, right, top, bottom });
409- return await loadImageFunction(img);
267+ break;
268+ case 4: // rgba to rgb
269+ for (let i = 0, offset = 0; i < this.data.length; i += 4) {
270+ newData[offset++] = this.data[i];
271+ newData[offset++] = this.data[i + 1];
272+ newData[offset++] = this.data[i + 2];
410273 }
274+ break;
275+ default:
276+ throw new Error(
277+ `Conversion failed due to unsupported number of channels: ${this.channels}`,
278+ );
279+ }
280+ return this._update(newData, this.width, this.height, 3);
281+ }
282+
283+ /**
284+ * Convert the image to RGBA format.
285+ * @returns {RawImage} `this` to support chaining.
286+ */
287+ rgba() {
288+ if (this.channels === 4) {
289+ return this;
411290 }
412291
413- async crop([x_min, y_min, x_max, y_max]) {
414- // Ensure crop bounds are within the image
415- x_min = Math.max(x_min, 0);
416- y_min = Math.max(y_min, 0);
417- x_max = Math.min(x_max, this.width - 1);
418- y_max = Math.min(y_max, this.height - 1);
419-
420- // Do nothing if the crop is the entire image
421- if (x_min === 0 && y_min === 0 && x_max === this.width - 1 && y_max === this.height - 1) {
422- return this;
292+ let newData = new Uint8ClampedArray(this.width * this.height * 4);
293+
294+ switch (this.channels) {
295+ case 1: // grayscale to rgba
296+ for (let i = 0, offset = 0; i < this.data.length; ++i) {
297+ newData[offset++] = this.data[i];
298+ newData[offset++] = this.data[i];
299+ newData[offset++] = this.data[i];
300+ newData[offset++] = 255;
423301 }
424-
425- const crop_width = x_max - x_min + 1;
426- const crop_height = y_max - y_min + 1;
427-
428- if (BROWSER_ENV) {
429- // Store number of channels before resizing
430- const numChannels = this.channels;
431-
432- // Create canvas object for this image
433- const canvas = this.toCanvas();
434-
435- // Create a new canvas of the desired size. This is needed since if the
436- // image is too small, we need to pad it with black pixels.
437- const ctx = createCanvasFunction(crop_width, crop_height).getContext('2d');
438-
439- // Draw image to context, cropping in the process
440- ctx.drawImage(canvas,
441- x_min, y_min, crop_width, crop_height,
442- 0, 0, crop_width, crop_height
443- );
444-
445- // Create image from the resized data
446- const resizedImage = new RawImage(ctx.getImageData(0, 0, crop_width, crop_height).data, crop_width, crop_height, 4);
447-
448- // Convert back so that image has the same number of channels as before
449- return resizedImage.convert(numChannels);
450-
451- } else {
452- // Create sharp image from raw data
453- const img = this.toSharp().extract({
454- left: x_min,
455- top: y_min,
456- width: crop_width,
457- height: crop_height,
458- });
459-
460- return await loadImageFunction(img);
302+ break;
303+ case 3: // rgb to rgba
304+ for (let i = 0, offset = 0; i < this.data.length; i += 3) {
305+ newData[offset++] = this.data[i];
306+ newData[offset++] = this.data[i + 1];
307+ newData[offset++] = this.data[i + 2];
308+ newData[offset++] = 255;
461309 }
462-
310+ break;
311+ default:
312+ throw new Error(
313+ `Conversion failed due to unsupported number of channels: ${this.channels}`,
314+ );
463315 }
464316
465- async center_crop(crop_width, crop_height) {
466- // If the image is already the desired size, return it
467- if (this.width === crop_width && this.height === crop_height) {
468- return this;
469- }
470-
471- // Determine bounds of the image in the new canvas
472- let width_offset = (this.width - crop_width) / 2;
473- let height_offset = (this.height - crop_height) / 2;
474-
475-
476- if (BROWSER_ENV) {
477- // Store number of channels before resizing
478- let numChannels = this.channels;
479-
480- // Create canvas object for this image
481- let canvas = this.toCanvas();
482-
483- // Create a new canvas of the desired size. This is needed since if the
484- // image is too small, we need to pad it with black pixels.
485- const ctx = createCanvasFunction(crop_width, crop_height).getContext('2d');
486-
487- let sourceX = 0;
488- let sourceY = 0;
489- let destX = 0;
490- let destY = 0;
491-
492- if (width_offset >= 0) {
493- sourceX = width_offset;
494- } else {
495- destX = -width_offset;
496- }
497-
498- if (height_offset >= 0) {
499- sourceY = height_offset;
500- } else {
501- destY = -height_offset;
502- }
503-
504- // Draw image to context, cropping in the process
505- ctx.drawImage(canvas,
506- sourceX, sourceY, crop_width, crop_height,
507- destX, destY, crop_width, crop_height
317+ return this._update(newData, this.width, this.height, 4);
318+ }
319+
320+ /**
321+ * Resize the image to the given dimensions. This method uses the canvas API to perform the resizing.
322+ * @param {number} width The width of the new image.
323+ * @param {number} height The height of the new image.
324+ * @param {Object} options Additional options for resizing.
325+ * @param {0|1|2|3|4|5|string} [options.resample] The resampling method to use.
326+ * @returns {Promise<RawImage>} `this` to support chaining.
327+ */
328+ async resize(width, height, { resample = 2 } = {}) {
329+ // Ensure resample method is a string
330+ let resampleMethod = RESAMPLING_MAPPING[resample] ?? resample;
331+
332+ if (BROWSER_ENV) {
333+ // TODO use `resample` in browser environment
334+
335+ // Store number of channels before resizing
336+ let numChannels = this.channels;
337+
338+ // Create canvas object for this image
339+ let canvas = this.toCanvas();
340+
341+ // Actually perform resizing using the canvas API
342+ const ctx = createCanvasFunction(width, height).getContext("2d");
343+
344+ // Draw image to context, resizing in the process
345+ ctx.drawImage(canvas, 0, 0, width, height);
346+
347+ // Create image from the resized data
348+ let resizedImage = new RawImage(
349+ ctx.getImageData(0, 0, width, height).data,
350+ width,
351+ height,
352+ 4,
353+ );
354+
355+ // Convert back so that image has the same number of channels as before
356+ return resizedImage.convert(numChannels);
357+ } else {
358+ // Create sharp image from raw data, and resize
359+ let img = this.toSharp();
360+
361+ switch (resampleMethod) {
362+ case "box":
363+ case "hamming":
364+ if (resampleMethod === "box" || resampleMethod === "hamming") {
365+ console.warn(
366+ `Resampling method ${resampleMethod} is not yet supported. Using bilinear instead.`,
508367 );
368+ resampleMethod = "bilinear";
369+ }
370+
371+ case "nearest":
372+ case "bilinear":
373+ case "bicubic":
374+ // Perform resizing using affine transform.
375+ // This matches how the python Pillow library does it.
376+ img = img.affine([width / this.width, 0, 0, height / this.height], {
377+ interpolator: resampleMethod,
378+ });
379+ break;
380+
381+ case "lanczos":
382+ // https://github.com/python-pillow/Pillow/discussions/5519
383+ // https://github.com/lovell/sharp/blob/main/docs/api-resize.md
384+ img = img.resize({
385+ width,
386+ height,
387+ fit: "fill",
388+ kernel: "lanczos3", // PIL Lanczos uses a kernel size of 3
389+ });
390+ break;
391+
392+ default:
393+ throw new Error(
394+ `Resampling method ${resampleMethod} is not supported.`,
395+ );
396+ }
397+
398+ return await loadImageFunction(img);
399+ }
400+ }
401+
402+ async pad([left, right, top, bottom]) {
403+ left = Math.max(left, 0);
404+ right = Math.max(right, 0);
405+ top = Math.max(top, 0);
406+ bottom = Math.max(bottom, 0);
407+
408+ if (left === 0 && right === 0 && top === 0 && bottom === 0) {
409+ // No padding needed
410+ return this;
411+ }
509412
510- // Create image from the resized data
511- let resizedImage = new RawImage(ctx.getImageData(0, 0, crop_width, crop_height).data, crop_width, crop_height, 4);
413+ if (BROWSER_ENV) {
414+ // Store number of channels before padding
415+ let numChannels = this.channels;
416+
417+ // Create canvas object for this image
418+ let canvas = this.toCanvas();
419+
420+ let newWidth = this.width + left + right;
421+ let newHeight = this.height + top + bottom;
422+
423+ // Create a new canvas of the desired size.
424+ const ctx = createCanvasFunction(newWidth, newHeight).getContext("2d");
425+
426+ // Draw image to context, padding in the process
427+ ctx.drawImage(
428+ canvas,
429+ 0,
430+ 0,
431+ this.width,
432+ this.height,
433+ left,
434+ top,
435+ newWidth,
436+ newHeight,
437+ );
438+
439+ // Create image from the padded data
440+ let paddedImage = new RawImage(
441+ ctx.getImageData(0, 0, newWidth, newHeight).data,
442+ newWidth,
443+ newHeight,
444+ 4,
445+ );
446+
447+ // Convert back so that image has the same number of channels as before
448+ return paddedImage.convert(numChannels);
449+ } else {
450+ let img = this.toSharp().extend({ left, right, top, bottom });
451+ return await loadImageFunction(img);
452+ }
453+ }
454+
455+ async crop([x_min, y_min, x_max, y_max]) {
456+ // Ensure crop bounds are within the image
457+ x_min = Math.max(x_min, 0);
458+ y_min = Math.max(y_min, 0);
459+ x_max = Math.min(x_max, this.width - 1);
460+ y_max = Math.min(y_max, this.height - 1);
461+
462+ // Do nothing if the crop is the entire image
463+ if (
464+ x_min === 0 &&
465+ y_min === 0 &&
466+ x_max === this.width - 1 &&
467+ y_max === this.height - 1
468+ ) {
469+ return this;
470+ }
512471
513- // Convert back so that image has the same number of channels as before
514- return resizedImage.convert(numChannels);
472+ const crop_width = x_max - x_min + 1;
473+ const crop_height = y_max - y_min + 1;
474+
475+ if (BROWSER_ENV) {
476+ // Store number of channels before resizing
477+ const numChannels = this.channels;
478+
479+ // Create canvas object for this image
480+ const canvas = this.toCanvas();
481+
482+ // Create a new canvas of the desired size. This is needed since if the
483+ // image is too small, we need to pad it with black pixels.
484+ const ctx = createCanvasFunction(crop_width, crop_height).getContext(
485+ "2d",
486+ );
487+
488+ // Draw image to context, cropping in the process
489+ ctx.drawImage(
490+ canvas,
491+ x_min,
492+ y_min,
493+ crop_width,
494+ crop_height,
495+ 0,
496+ 0,
497+ crop_width,
498+ crop_height,
499+ );
500+
501+ // Create image from the resized data
502+ const resizedImage = new RawImage(
503+ ctx.getImageData(0, 0, crop_width, crop_height).data,
504+ crop_width,
505+ crop_height,
506+ 4,
507+ );
508+
509+ // Convert back so that image has the same number of channels as before
510+ return resizedImage.convert(numChannels);
511+ } else {
512+ // Create sharp image from raw data
513+ const img = this.toSharp().extract({
514+ left: x_min,
515+ top: y_min,
516+ width: crop_width,
517+ height: crop_height,
518+ });
519+
520+ return await loadImageFunction(img);
521+ }
522+ }
523+
524+ async center_crop(crop_width, crop_height) {
525+ // If the image is already the desired size, return it
526+ if (this.width === crop_width && this.height === crop_height) {
527+ return this;
528+ }
515529
530+ // Determine bounds of the image in the new canvas
531+ let width_offset = (this.width - crop_width) / 2;
532+ let height_offset = (this.height - crop_height) / 2;
533+
534+ if (BROWSER_ENV) {
535+ // Store number of channels before resizing
536+ let numChannels = this.channels;
537+
538+ // Create canvas object for this image
539+ let canvas = this.toCanvas();
540+
541+ // Create a new canvas of the desired size. This is needed since if the
542+ // image is too small, we need to pad it with black pixels.
543+ const ctx = createCanvasFunction(crop_width, crop_height).getContext(
544+ "2d",
545+ );
546+
547+ let sourceX = 0;
548+ let sourceY = 0;
549+ let destX = 0;
550+ let destY = 0;
551+
552+ if (width_offset >= 0) {
553+ sourceX = width_offset;
554+ } else {
555+ destX = -width_offset;
556+ }
557+
558+ if (height_offset >= 0) {
559+ sourceY = height_offset;
560+ } else {
561+ destY = -height_offset;
562+ }
563+
564+ // Draw image to context, cropping in the process
565+ ctx.drawImage(
566+ canvas,
567+ sourceX,
568+ sourceY,
569+ crop_width,
570+ crop_height,
571+ destX,
572+ destY,
573+ crop_width,
574+ crop_height,
575+ );
576+
577+ // Create image from the resized data
578+ let resizedImage = new RawImage(
579+ ctx.getImageData(0, 0, crop_width, crop_height).data,
580+ crop_width,
581+ crop_height,
582+ 4,
583+ );
584+
585+ // Convert back so that image has the same number of channels as before
586+ return resizedImage.convert(numChannels);
587+ } else {
588+ // Create sharp image from raw data
589+ let img = this.toSharp();
590+
591+ if (width_offset >= 0 && height_offset >= 0) {
592+ // Cropped image lies entirely within the original image
593+ img = img.extract({
594+ left: Math.floor(width_offset),
595+ top: Math.floor(height_offset),
596+ width: crop_width,
597+ height: crop_height,
598+ });
599+ } else if (width_offset <= 0 && height_offset <= 0) {
600+ // Cropped image lies entirely outside the original image,
601+ // so we add padding
602+ let top = Math.floor(-height_offset);
603+ let left = Math.floor(-width_offset);
604+ img = img.extend({
605+ top: top,
606+ left: left,
607+
608+ // Ensures the resulting image has the desired dimensions
609+ right: crop_width - this.width - left,
610+ bottom: crop_height - this.height - top,
611+ });
612+ } else {
613+ // Cropped image lies partially outside the original image.
614+ // We first pad, then crop.
615+
616+ let y_padding = [0, 0];
617+ let y_extract = 0;
618+ if (height_offset < 0) {
619+ y_padding[0] = Math.floor(-height_offset);
620+ y_padding[1] = crop_height - this.height - y_padding[0];
516621 } else {
517- // Create sharp image from raw data
518- let img = this.toSharp();
519-
520- if (width_offset >= 0 && height_offset >= 0) {
521- // Cropped image lies entirely within the original image
522- img = img.extract({
523- left: Math.floor(width_offset),
524- top: Math.floor(height_offset),
525- width: crop_width,
526- height: crop_height,
527- })
528- } else if (width_offset <= 0 && height_offset <= 0) {
529- // Cropped image lies entirely outside the original image,
530- // so we add padding
531- let top = Math.floor(-height_offset);
532- let left = Math.floor(-width_offset);
533- img = img.extend({
534- top: top,
535- left: left,
536-
537- // Ensures the resulting image has the desired dimensions
538- right: crop_width - this.width - left,
539- bottom: crop_height - this.height - top,
540- });
541- } else {
542- // Cropped image lies partially outside the original image.
543- // We first pad, then crop.
544-
545- let y_padding = [0, 0];
546- let y_extract = 0;
547- if (height_offset < 0) {
548- y_padding[0] = Math.floor(-height_offset);
549- y_padding[1] = crop_height - this.height - y_padding[0];
550- } else {
551- y_extract = Math.floor(height_offset);
552- }
553-
554- let x_padding = [0, 0];
555- let x_extract = 0;
556- if (width_offset < 0) {
557- x_padding[0] = Math.floor(-width_offset);
558- x_padding[1] = crop_width - this.width - x_padding[0];
559- } else {
560- x_extract = Math.floor(width_offset);
561- }
562-
563- img = img.extend({
564- top: y_padding[0],
565- bottom: y_padding[1],
566- left: x_padding[0],
567- right: x_padding[1],
568- }).extract({
569- left: x_extract,
570- top: y_extract,
571- width: crop_width,
572- height: crop_height,
573- })
574- }
575-
576- return await loadImageFunction(img);
622+ y_extract = Math.floor(height_offset);
577623 }
578- }
579624
580- async toBlob(type = 'image/png', quality = 1) {
581- if (!BROWSER_ENV) {
582- throw new Error('toBlob() is only supported in browser environments.')
625+ let x_padding = [0, 0];
626+ let x_extract = 0;
627+ if (width_offset < 0) {
628+ x_padding[0] = Math.floor(-width_offset);
629+ x_padding[1] = crop_width - this.width - x_padding[0];
630+ } else {
631+ x_extract = Math.floor(width_offset);
583632 }
584633
585- const canvas = this.toCanvas();
586- return await canvas.convertToBlob({ type, quality });
634+ img = img
635+ .extend({
636+ top: y_padding[0],
637+ bottom: y_padding[1],
638+ left: x_padding[0],
639+ right: x_padding[1],
640+ })
641+ .extract({
642+ left: x_extract,
643+ top: y_extract,
644+ width: crop_width,
645+ height: crop_height,
646+ });
647+ }
648+
649+ return await loadImageFunction(img);
650+ }
651+ }
652+
653+ async toBlob(type = "image/png", quality = 1) {
654+ if (!BROWSER_ENV) {
655+ throw new Error("toBlob() is only supported in browser environments.");
587656 }
588657
589- toCanvas() {
590- if (!BROWSER_ENV) {
591- throw new Error('toCanvas() is only supported in browser environments.')
592- }
593-
594- // Clone, and convert data to RGBA before drawing to canvas.
595- // This is because the canvas API only supports RGBA
596- let cloned = this.clone().rgba();
597-
598- // Create canvas object for the cloned image
599- let clonedCanvas = createCanvasFunction(cloned.width, cloned.height);
600-
601- // Draw image to context
602- let data = new ImageDataClass(cloned.data, cloned.width, cloned.height);
603- clonedCanvas.getContext('2d').putImageData(data, 0, 0);
658+ const canvas = this.toCanvas();
659+ return await canvas.convertToBlob({ type, quality });
660+ }
604661
605- return clonedCanvas;
662+ toCanvas() {
663+ if (!BROWSER_ENV) {
664+ throw new Error("toCanvas() is only supported in browser environments.");
606665 }
607666
608- /**
609- * Helper method to update the image data.
610- * @param {Uint8ClampedArray} data The new image data.
611- * @param {number} width The new width of the image.
612- * @param {number} height The new height of the image.
613- * @param {1|2|3|4|null} [channels] The new number of channels of the image.
614- * @private
615- */
616- _update(data, width, height, channels = null) {
617- this.data = data;
618- this.width = width;
619- this.height = height;
620- if (channels !== null) {
621- this.channels = channels;
622- }
623- return this;
667+ // Clone, and convert data to RGBA before drawing to canvas.
668+ // This is because the canvas API only supports RGBA
669+ let cloned = this.clone().rgba();
670+
671+ // Create canvas object for the cloned image
672+ let clonedCanvas = createCanvasFunction(cloned.width, cloned.height);
673+
674+ // Draw image to context
675+ let data = new ImageDataClass(cloned.data, cloned.width, cloned.height);
676+ clonedCanvas.getContext("2d").putImageData(data, 0, 0);
677+
678+ return clonedCanvas;
679+ }
680+
681+ /**
682+ * Helper method to update the image data.
683+ * @param {Uint8ClampedArray} data The new image data.
684+ * @param {number} width The new width of the image.
685+ * @param {number} height The new height of the image.
686+ * @param {1|2|3|4|null} [channels] The new number of channels of the image.
687+ * @private
688+ */
689+ _update(data, width, height, channels = null) {
690+ this.data = data;
691+ this.width = width;
692+ this.height = height;
693+ if (channels !== null) {
694+ this.channels = channels;
624695 }
625-
626- /**
627- * Clone the image
628- * @returns {RawImage} The cloned image
629- */
630- clone() {
631- return new RawImage(this.data.slice(), this.width, this.height, this.channels);
696+ return this;
697+ }
698+
699+ /**
700+ * Clone the image
701+ * @returns {RawImage} The cloned image
702+ */
703+ clone() {
704+ return new RawImage(
705+ this.data.slice(),
706+ this.width,
707+ this.height,
708+ this.channels,
709+ );
710+ }
711+
712+ /**
713+ * Helper method for converting image to have a certain number of channels
714+ * @param {number} numChannels The number of channels. Must be 1, 3, or 4.
715+ * @returns {RawImage} `this` to support chaining.
716+ */
717+ convert(numChannels) {
718+ if (this.channels === numChannels) return this; // Already correct number of channels
719+
720+ switch (numChannels) {
721+ case 1:
722+ this.grayscale();
723+ break;
724+ case 3:
725+ this.rgb();
726+ break;
727+ case 4:
728+ this.rgba();
729+ break;
730+ default:
731+ throw new Error(
732+ `Conversion failed due to unsupported number of channels: ${this.channels}`,
733+ );
632734 }
633-
634- /**
635- * Helper method for converting image to have a certain number of channels
636- * @param {number} numChannels The number of channels. Must be 1, 3, or 4.
637- * @returns {RawImage} `this` to support chaining.
638- */
639- convert(numChannels) {
640- if (this.channels === numChannels) return this; // Already correct number of channels
641-
642- switch (numChannels) {
643- case 1:
644- this.grayscale();
645- break;
646- case 3:
647- this.rgb();
648- break;
649- case 4:
650- this.rgba();
651- break;
652- default:
653- throw new Error(`Conversion failed due to unsupported number of channels: ${this.channels}`);
654- }
655- return this;
735+ return this;
736+ }
737+
738+ /**
739+ * Save the image to the given path.
740+ * @param {string} path The path to save the image to.
741+ */
742+ async save(path) {
743+ if (BROWSER_ENV) {
744+ if (WEBWORKER_ENV) {
745+ throw new Error("Unable to save an image from a Web Worker.");
746+ }
747+
748+ const extension = path.split(".").pop().toLowerCase();
749+ const mime = CONTENT_TYPE_MAP.get(extension) ?? "image/png";
750+
751+ // Convert image to Blob
752+ const blob = await this.toBlob(mime);
753+
754+ // Convert the canvas content to a data URL
755+ const dataURL = URL.createObjectURL(blob);
756+
757+ // Create an anchor element with the data URL as the href attribute
758+ const downloadLink = document.createElement("a");
759+ downloadLink.href = dataURL;
760+
761+ // Set the download attribute to specify the desired filename for the downloaded image
762+ downloadLink.download = path;
763+
764+ // Trigger the download
765+ downloadLink.click();
766+
767+ // Clean up: remove the anchor element from the DOM
768+ downloadLink.remove();
769+ } else if (!env.useFS) {
770+ throw new Error(
771+ "Unable to save the image because filesystem is disabled in this environment.",
772+ );
773+ } else {
774+ const img = this.toSharp();
775+ return await img.toFile(path);
656776 }
657-
658- /**
659- * Save the image to the given path.
660- * @param {string} path The path to save the image to.
661- */
662- async save(path) {
663-
664- if (BROWSER_ENV) {
665- if (WEBWORKER_ENV) {
666- throw new Error('Unable to save an image from a Web Worker.')
667- }
668-
669- const extension = path.split('.').pop().toLowerCase();
670- const mime = CONTENT_TYPE_MAP.get(extension) ?? 'image/png';
671-
672- // Convert image to Blob
673- const blob = await this.toBlob(mime);
674-
675- // Convert the canvas content to a data URL
676- const dataURL = URL.createObjectURL(blob);
677-
678- // Create an anchor element with the data URL as the href attribute
679- const downloadLink = document.createElement('a');
680- downloadLink.href = dataURL;
681-
682- // Set the download attribute to specify the desired filename for the downloaded image
683- downloadLink.download = path;
684-
685- // Trigger the download
686- downloadLink.click();
687-
688- // Clean up: remove the anchor element from the DOM
689- downloadLink.remove();
690-
691- } else if (!env.useFS) {
692- throw new Error('Unable to save the image because filesystem is disabled in this environment.')
693-
694- } else {
695- const img = this.toSharp();
696- return await img.toFile(path);
697- }
777+ }
778+
779+ toSharp() {
780+ if (BROWSER_ENV) {
781+ throw new Error(
782+ "toSharp() is only supported in server-side environments.",
783+ );
698784 }
699785
700- toSharp() {
701- if (BROWSER_ENV) {
702- throw new Error('toSharp() is only supported in server-side environments.')
703- }
704-
705- return sharp(this.data, {
706- raw: {
707- width: this.width,
708- height: this.height,
709- channels: this.channels
710- }
711- });
712- }
786+ return sharp(this.data, {
787+ raw: {
788+ width: this.width,
789+ height: this.height,
790+ channels: this.channels,
791+ },
792+ });
793+ }
713794 }
modified core/vendor/modules/@xenova/transformers/src/utils/maths.js +774 −774
@@ -1,10 +1,9 @@
1-
21 /**
3- * @file Helper module for mathematical processing.
4- *
5- * These functions and classes are only used internally,
2+ * @file Helper module for mathematical processing.
3+ *
4+ * These functions and classes are only used internally,
65 * meaning an end-user shouldn't need to access anything here.
7- *
6+ *
87 * @module utils/maths
98 */
109
@@ -17,117 +16,120 @@
1716 /**
1817 * @param {TypedArray} input
1918 */
20-export function interpolate_data(input, [in_channels, in_height, in_width], [out_height, out_width], mode = 'bilinear', align_corners = false) {
21- // TODO use mode and align_corners
22-
23- // Output image dimensions
24- const x_scale = out_width / in_width;
25- const y_scale = out_height / in_height;
26-
27- // Output image
28- // @ts-ignore
29- const out_img = new input.constructor(out_height * out_width * in_channels);
30-
31- // Pre-calculate strides
32- const inStride = in_height * in_width;
33- const outStride = out_height * out_width;
34-
35- for (let i = 0; i < out_height; ++i) {
36- for (let j = 0; j < out_width; ++j) {
37- // Calculate output offset
38- const outOffset = i * out_width + j;
39-
40- // Calculate input pixel coordinates
41- const x = (j + 0.5) / x_scale - 0.5;
42- const y = (i + 0.5) / y_scale - 0.5;
43-
44- // Calculate the four nearest input pixels
45- // We also check if the input pixel coordinates are within the image bounds
46- let x1 = Math.floor(x);
47- let y1 = Math.floor(y);
48- const x2 = Math.min(x1 + 1, in_width - 1);
49- const y2 = Math.min(y1 + 1, in_height - 1);
50-
51- x1 = Math.max(x1, 0);
52- y1 = Math.max(y1, 0);
53-
54-
55- // Calculate the fractional distances between the input pixel and the four nearest pixels
56- const s = x - x1;
57- const t = y - y1;
58-
59- // Perform bilinear interpolation
60- const w1 = (1 - s) * (1 - t);
61- const w2 = s * (1 - t);
62- const w3 = (1 - s) * t;
63- const w4 = s * t;
64-
65- // Calculate the four nearest input pixel indices
66- const yStride = y1 * in_width;
67- const xStride = y2 * in_width;
68- const idx1 = yStride + x1;
69- const idx2 = yStride + x2;
70- const idx3 = xStride + x1;
71- const idx4 = xStride + x2;
72-
73- for (let k = 0; k < in_channels; ++k) {
74- // Calculate channel offset
75- const cOffset = k * inStride;
76-
77- out_img[k * outStride + outOffset] =
78- w1 * input[cOffset + idx1] +
79- w2 * input[cOffset + idx2] +
80- w3 * input[cOffset + idx3] +
81- w4 * input[cOffset + idx4];
82- }
83- }
19+export function interpolate_data(
20+ input,
21+ [in_channels, in_height, in_width],
22+ [out_height, out_width],
23+ mode = "bilinear",
24+ align_corners = false,
25+) {
26+ // TODO use mode and align_corners
27+
28+ // Output image dimensions
29+ const x_scale = out_width / in_width;
30+ const y_scale = out_height / in_height;
31+
32+ // Output image
33+ // @ts-ignore
34+ const out_img = new input.constructor(out_height * out_width * in_channels);
35+
36+ // Pre-calculate strides
37+ const inStride = in_height * in_width;
38+ const outStride = out_height * out_width;
39+
40+ for (let i = 0; i < out_height; ++i) {
41+ for (let j = 0; j < out_width; ++j) {
42+ // Calculate output offset
43+ const outOffset = i * out_width + j;
44+
45+ // Calculate input pixel coordinates
46+ const x = (j + 0.5) / x_scale - 0.5;
47+ const y = (i + 0.5) / y_scale - 0.5;
48+
49+ // Calculate the four nearest input pixels
50+ // We also check if the input pixel coordinates are within the image bounds
51+ let x1 = Math.floor(x);
52+ let y1 = Math.floor(y);
53+ const x2 = Math.min(x1 + 1, in_width - 1);
54+ const y2 = Math.min(y1 + 1, in_height - 1);
55+
56+ x1 = Math.max(x1, 0);
57+ y1 = Math.max(y1, 0);
58+
59+ // Calculate the fractional distances between the input pixel and the four nearest pixels
60+ const s = x - x1;
61+ const t = y - y1;
62+
63+ // Perform bilinear interpolation
64+ const w1 = (1 - s) * (1 - t);
65+ const w2 = s * (1 - t);
66+ const w3 = (1 - s) * t;
67+ const w4 = s * t;
68+
69+ // Calculate the four nearest input pixel indices
70+ const yStride = y1 * in_width;
71+ const xStride = y2 * in_width;
72+ const idx1 = yStride + x1;
73+ const idx2 = yStride + x2;
74+ const idx3 = xStride + x1;
75+ const idx4 = xStride + x2;
76+
77+ for (let k = 0; k < in_channels; ++k) {
78+ // Calculate channel offset
79+ const cOffset = k * inStride;
80+
81+ out_img[k * outStride + outOffset] =
82+ w1 * input[cOffset + idx1] +
83+ w2 * input[cOffset + idx2] +
84+ w3 * input[cOffset + idx3] +
85+ w4 * input[cOffset + idx4];
86+ }
8487 }
88+ }
8589
86- return out_img;
90+ return out_img;
8791 }
8892
89-
9093 /**
9194 * Helper method to transpose a `AnyTypedArray` directly
92- * @template {AnyTypedArray} T
93- * @param {T} array
94- * @param {number[]} dims
95- * @param {number[]} axes
95+ * @template {AnyTypedArray} T
96+ * @param {T} array
97+ * @param {number[]} dims
98+ * @param {number[]} axes
9699 * @returns {[T, number[]]} The transposed array and the new shape.
97100 */
98101 export function transpose_data(array, dims, axes) {
99- // Calculate the new shape of the transposed array
100- // and the stride of the original array
101- const shape = new Array(axes.length);
102- const stride = new Array(axes.length);
103-
104- for (let i = axes.length - 1, s = 1; i >= 0; --i) {
105- stride[i] = s;
106- shape[i] = dims[axes[i]];
107- s *= shape[i];
108- }
109-
110- // Precompute inverse mapping of stride
111- const invStride = axes.map((_, i) => stride[axes.indexOf(i)]);
112-
113- // Create the transposed array with the new shape
114- // @ts-ignore
115- const transposedData = new array.constructor(array.length);
116-
117- // Transpose the original array to the new array
118- for (let i = 0; i < array.length; ++i) {
119- let newIndex = 0;
120- for (let j = dims.length - 1, k = i; j >= 0; --j) {
121- newIndex += (k % dims[j]) * invStride[j];
122- k = Math.floor(k / dims[j]);
123- }
124- transposedData[newIndex] = array[i];
102+ // Calculate the new shape of the transposed array
103+ // and the stride of the original array
104+ const shape = new Array(axes.length);
105+ const stride = new Array(axes.length);
106+
107+ for (let i = axes.length - 1, s = 1; i >= 0; --i) {
108+ stride[i] = s;
109+ shape[i] = dims[axes[i]];
110+ s *= shape[i];
111+ }
112+
113+ // Precompute inverse mapping of stride
114+ const invStride = axes.map((_, i) => stride[axes.indexOf(i)]);
115+
116+ // Create the transposed array with the new shape
117+ // @ts-ignore
118+ const transposedData = new array.constructor(array.length);
119+
120+ // Transpose the original array to the new array
121+ for (let i = 0; i < array.length; ++i) {
122+ let newIndex = 0;
123+ for (let j = dims.length - 1, k = i; j >= 0; --j) {
124+ newIndex += (k % dims[j]) * invStride[j];
125+ k = Math.floor(k / dims[j]);
125126 }
127+ transposedData[newIndex] = array[i];
128+ }
126129
127- return [transposedData, shape];
130+ return [transposedData, shape];
128131 }
129132
130-
131133 /**
132134 * Compute the softmax of an array of numbers.
133135 * @template {TypedArray|number[]} T
@@ -135,20 +137,20 @@
135137 * @returns {T} The softmax array.
136138 */
137139 export function softmax(arr) {
138- // Compute the maximum value in the array
139- const maxVal = max(arr)[0];
140+ // Compute the maximum value in the array
141+ const maxVal = max(arr)[0];
140142
141- // Compute the exponentials of the array values
142- const exps = arr.map(x => Math.exp(x - maxVal));
143+ // Compute the exponentials of the array values
144+ const exps = arr.map((x) => Math.exp(x - maxVal));
143145
144- // Compute the sum of the exponentials
145- // @ts-ignore
146- const sumExps = exps.reduce((acc, val) => acc + val, 0);
146+ // Compute the sum of the exponentials
147+ // @ts-ignore
148+ const sumExps = exps.reduce((acc, val) => acc + val, 0);
147149
148- // Compute the softmax values
149- const softmaxArr = exps.map(x => x / sumExps);
150+ // Compute the softmax values
151+ const softmaxArr = exps.map((x) => x / sumExps);
150152
151- return /** @type {T} */(softmaxArr);
153+ return /** @type {T} */ (softmaxArr);
152154 }
153155
154156 /**
@@ -158,13 +160,13 @@
158160 * @returns {T} The resulting log_softmax array.
159161 */
160162 export function log_softmax(arr) {
161- // Compute the softmax values
162- const softmaxArr = softmax(arr);
163+ // Compute the softmax values
164+ const softmaxArr = softmax(arr);
163165
164- // Apply log formula to each element
165- const logSoftmaxArr = softmaxArr.map(x => Math.log(x));
166+ // Apply log formula to each element
167+ const logSoftmaxArr = softmaxArr.map((x) => Math.log(x));
166168
167- return /** @type {T} */(logSoftmaxArr);
169+ return /** @type {T} */ (logSoftmaxArr);
168170 }
169171
170172 /**
@@ -174,10 +176,9 @@
174176 * @returns {number} The dot product of arr1 and arr2.
175177 */
176178 export function dot(arr1, arr2) {
177- return arr1.reduce((acc, val, i) => acc + val * arr2[i], 0);
179+ return arr1.reduce((acc, val, i) => acc + val * arr2[i], 0);
178180 }
179181
180-
181182 /**
182183 * Get the top k items from an iterable, sorted by descending order
183184 * @param {any[]|TypedArray} items The items to be sorted
@@ -185,17 +186,17 @@
185186 * @returns {[number, any][]} The top k items, sorted by descending order
186187 */
187188 export function getTopItems(items, top_k = 0) {
188- // if top == 0, return all
189+ // if top == 0, return all
189190
190- items = Array.from(items)
191- .map((x, i) => [i, x]) // Get indices ([index, score])
192- .sort((a, b) => b[1] - a[1]) // Sort by log probabilities
191+ items = Array.from(items)
192+ .map((x, i) => [i, x]) // Get indices ([index, score])
193+ .sort((a, b) => b[1] - a[1]); // Sort by log probabilities
193194
194- if (top_k !== null && top_k > 0) {
195- items = items.slice(0, top_k); // Get top k items
196- }
195+ if (top_k !== null && top_k > 0) {
196+ items = items.slice(0, top_k); // Get top k items
197+ }
197198
198- return items
199+ return items;
199200 }
200201
201202 /**
@@ -206,19 +207,19 @@
206207 * @returns {number} The cosine similarity between the two arrays.
207208 */
208209 export function cos_sim(arr1, arr2) {
209- // Calculate dot product of the two arrays
210- const dotProduct = dot(arr1, arr2);
210+ // Calculate dot product of the two arrays
211+ const dotProduct = dot(arr1, arr2);
211212
212- // Calculate the magnitude of the first array
213- const magnitudeA = magnitude(arr1);
213+ // Calculate the magnitude of the first array
214+ const magnitudeA = magnitude(arr1);
214215
215- // Calculate the magnitude of the second array
216- const magnitudeB = magnitude(arr2);
216+ // Calculate the magnitude of the second array
217+ const magnitudeB = magnitude(arr2);
217218
218- // Calculate the cosine similarity
219- const cosineSimilarity = dotProduct / (magnitudeA * magnitudeB);
219+ // Calculate the cosine similarity
220+ const cosineSimilarity = dotProduct / (magnitudeA * magnitudeB);
220221
221- return cosineSimilarity;
222+ return cosineSimilarity;
222223 }
223224
224225 /**
@@ -227,10 +228,9 @@
227228 * @returns {number} The magnitude of the array.
228229 */
229230 export function magnitude(arr) {
230- return Math.sqrt(arr.reduce((acc, val) => acc + val * val, 0));
231+ return Math.sqrt(arr.reduce((acc, val) => acc + val * val, 0));
231232 }
232233
233-
234234 /**
235235 * Returns the value and index of the minimum element in an array.
236236 * @param {number[]|TypedArray} arr array of numbers.
@@ -238,19 +238,18 @@
238238 * @throws {Error} If array is empty.
239239 */
240240 export function min(arr) {
241- if (arr.length === 0) throw Error('Array must not be empty');
242- let min = arr[0];
243- let indexOfMin = 0;
244- for (let i = 1; i < arr.length; ++i) {
245- if (arr[i] < min) {
246- min = arr[i];
247- indexOfMin = i;
248- }
241+ if (arr.length === 0) throw Error("Array must not be empty");
242+ let min = arr[0];
243+ let indexOfMin = 0;
244+ for (let i = 1; i < arr.length; ++i) {
245+ if (arr[i] < min) {
246+ min = arr[i];
247+ indexOfMin = i;
249248 }
250- return [min, indexOfMin];
249+ }
250+ return [min, indexOfMin];
251251 }
252252
253-
254253 /**
255254 * Returns the value and index of the maximum element in an array.
256255 * @param {number[]|AnyTypedArray} arr array of numbers.
@@ -258,688 +257,689 @@
258257 * @throws {Error} If array is empty.
259258 */
260259 export function max(arr) {
261- if (arr.length === 0) throw Error('Array must not be empty');
262- let max = arr[0];
263- let indexOfMax = 0;
264- for (let i = 1; i < arr.length; ++i) {
265- if (arr[i] > max) {
266- max = arr[i];
267- indexOfMax = i;
268- }
260+ if (arr.length === 0) throw Error("Array must not be empty");
261+ let max = arr[0];
262+ let indexOfMax = 0;
263+ for (let i = 1; i < arr.length; ++i) {
264+ if (arr[i] > max) {
265+ max = arr[i];
266+ indexOfMax = i;
269267 }
270- return [Number(max), indexOfMax];
268+ }
269+ return [Number(max), indexOfMax];
271270 }
272271
273272 function isPowerOfTwo(number) {
274- // Check if the number is greater than 0 and has only one bit set to 1
275- return (number > 0) && ((number & (number - 1)) === 0);
273+ // Check if the number is greater than 0 and has only one bit set to 1
274+ return number > 0 && (number & (number - 1)) === 0;
276275 }
277276
278277 /**
279278 * Implementation of Radix-4 FFT.
280- *
279+ *
281280 * P2FFT class provides functionality for performing Fast Fourier Transform on arrays
282281 * which are a power of two in length.
283282 * Code adapted from https://www.npmjs.com/package/fft.js
284283 */
285284 class P2FFT {
286- /**
287- * @param {number} size The size of the input array. Must be a power of two larger than 1.
288- * @throws {Error} FFT size must be a power of two larger than 1.
289- */
290- constructor(size) {
291- this.size = size | 0; // convert to a 32-bit signed integer
292- if (this.size <= 1 || !isPowerOfTwo(this.size))
293- throw new Error('FFT size must be a power of two larger than 1');
294-
295- this._csize = size << 1;
296-
297- this.table = new Float64Array(this.size * 2);
298- for (let i = 0; i < this.table.length; i += 2) {
299- const angle = Math.PI * i / this.size;
300- this.table[i] = Math.cos(angle);
301- this.table[i + 1] = -Math.sin(angle);
302- }
303-
304- // Find size's power of two
305- let power = 0;
306- for (let t = 1; this.size > t; t <<= 1)
307- ++power;
308-
309- // Calculate initial step's width:
310- // * If we are full radix-4, it is 2x smaller to give inital len=8
311- // * Otherwise it is the same as `power` to give len=4
312- this._width = power % 2 === 0 ? power - 1 : power;
313-
314- // Pre-compute bit-reversal patterns
315- this._bitrev = new Int32Array(1 << this._width);
316- for (let j = 0; j < this._bitrev.length; ++j) {
317- this._bitrev[j] = 0;
318- for (let shift = 0; shift < this._width; shift += 2) {
319- const revShift = this._width - shift - 2;
320- this._bitrev[j] |= ((j >>> shift) & 3) << revShift;
321- }
322- }
323- }
324-
325- /**
326- * Create a complex number array with size `2 * size`
327- *
328- * @returns {Float64Array} A complex number array with size `2 * size`
329- */
330- createComplexArray() {
331- return new Float64Array(this._csize);
332- }
333-
334- /**
335- * Converts a complex number representation stored in a Float64Array to an array of real numbers.
336- *
337- * @param {Float64Array} complex The complex number representation to be converted.
338- * @param {number[]} [storage] An optional array to store the result in.
339- * @returns {number[]} An array of real numbers representing the input complex number representation.
340- */
341- fromComplexArray(complex, storage) {
342- const res = storage || new Array(complex.length >>> 1);
343- for (let i = 0; i < complex.length; i += 2)
344- res[i >>> 1] = complex[i];
345- return res;
285+ /**
286+ * @param {number} size The size of the input array. Must be a power of two larger than 1.
287+ * @throws {Error} FFT size must be a power of two larger than 1.
288+ */
289+ constructor(size) {
290+ this.size = size | 0; // convert to a 32-bit signed integer
291+ if (this.size <= 1 || !isPowerOfTwo(this.size))
292+ throw new Error("FFT size must be a power of two larger than 1");
293+
294+ this._csize = size << 1;
295+
296+ this.table = new Float64Array(this.size * 2);
297+ for (let i = 0; i < this.table.length; i += 2) {
298+ const angle = (Math.PI * i) / this.size;
299+ this.table[i] = Math.cos(angle);
300+ this.table[i + 1] = -Math.sin(angle);
346301 }
347302
348- /**
349- * Convert a real-valued input array to a complex-valued output array.
350- * @param {Float64Array} input The real-valued input array.
351- * @param {Float64Array} [storage] Optional buffer to store the output array.
352- * @returns {Float64Array} The complex-valued output array.
353- */
354- toComplexArray(input, storage) {
355- const res = storage || this.createComplexArray();
356- for (let i = 0; i < res.length; i += 2) {
357- res[i] = input[i >>> 1];
358- res[i + 1] = 0;
359- }
360- return res;
361- }
362-
363- /**
364- * Completes the spectrum by adding its mirrored negative frequency components.
365- * @param {Float64Array} spectrum The input spectrum.
366- * @returns {void}
367- */
368- completeSpectrum(spectrum) {
369- const size = this._csize;
370- const half = size >>> 1;
371- for (let i = 2; i < half; i += 2) {
372- spectrum[size - i] = spectrum[i];
373- spectrum[size - i + 1] = -spectrum[i + 1];
374- }
303+ // Find size's power of two
304+ let power = 0;
305+ for (let t = 1; this.size > t; t <<= 1) ++power;
306+
307+ // Calculate initial step's width:
308+ // * If we are full radix-4, it is 2x smaller to give inital len=8
309+ // * Otherwise it is the same as `power` to give len=4
310+ this._width = power % 2 === 0 ? power - 1 : power;
311+
312+ // Pre-compute bit-reversal patterns
313+ this._bitrev = new Int32Array(1 << this._width);
314+ for (let j = 0; j < this._bitrev.length; ++j) {
315+ this._bitrev[j] = 0;
316+ for (let shift = 0; shift < this._width; shift += 2) {
317+ const revShift = this._width - shift - 2;
318+ this._bitrev[j] |= ((j >>> shift) & 3) << revShift;
319+ }
375320 }
376-
377- /**
378- * Performs a Fast Fourier Transform (FFT) on the given input data and stores the result in the output buffer.
379- *
380- * @param {Float64Array} out The output buffer to store the result.
381- * @param {Float64Array} data The input data to transform.
382- *
383- * @throws {Error} Input and output buffers must be different.
384- *
385- * @returns {void}
386- */
387- transform(out, data) {
388- if (out === data)
389- throw new Error('Input and output buffers must be different');
390-
391- this._transform4(out, data, 1 /* DONE */);
321+ }
322+
323+ /**
324+ * Create a complex number array with size `2 * size`
325+ *
326+ * @returns {Float64Array} A complex number array with size `2 * size`
327+ */
328+ createComplexArray() {
329+ return new Float64Array(this._csize);
330+ }
331+
332+ /**
333+ * Converts a complex number representation stored in a Float64Array to an array of real numbers.
334+ *
335+ * @param {Float64Array} complex The complex number representation to be converted.
336+ * @param {number[]} [storage] An optional array to store the result in.
337+ * @returns {number[]} An array of real numbers representing the input complex number representation.
338+ */
339+ fromComplexArray(complex, storage) {
340+ const res = storage || new Array(complex.length >>> 1);
341+ for (let i = 0; i < complex.length; i += 2) res[i >>> 1] = complex[i];
342+ return res;
343+ }
344+
345+ /**
346+ * Convert a real-valued input array to a complex-valued output array.
347+ * @param {Float64Array} input The real-valued input array.
348+ * @param {Float64Array} [storage] Optional buffer to store the output array.
349+ * @returns {Float64Array} The complex-valued output array.
350+ */
351+ toComplexArray(input, storage) {
352+ const res = storage || this.createComplexArray();
353+ for (let i = 0; i < res.length; i += 2) {
354+ res[i] = input[i >>> 1];
355+ res[i + 1] = 0;
392356 }
393-
394- /**
395- * Performs a real-valued forward FFT on the given input buffer and stores the result in the given output buffer.
396- * The input buffer must contain real values only, while the output buffer will contain complex values. The input and
397- * output buffers must be different.
398- *
399- * @param {Float64Array} out The output buffer.
400- * @param {Float64Array} data The input buffer containing real values.
401- *
402- * @throws {Error} If the input and output buffers are the same.
403- */
404- realTransform(out, data) {
405- if (out === data)
406- throw new Error('Input and output buffers must be different');
407-
408- this._realTransform4(out, data, 1 /* DONE */);
357+ return res;
358+ }
359+
360+ /**
361+ * Completes the spectrum by adding its mirrored negative frequency components.
362+ * @param {Float64Array} spectrum The input spectrum.
363+ * @returns {void}
364+ */
365+ completeSpectrum(spectrum) {
366+ const size = this._csize;
367+ const half = size >>> 1;
368+ for (let i = 2; i < half; i += 2) {
369+ spectrum[size - i] = spectrum[i];
370+ spectrum[size - i + 1] = -spectrum[i + 1];
409371 }
410-
411- /**
412- * Performs an inverse FFT transformation on the given `data` array, and stores the result in `out`.
413- * The `out` array must be a different buffer than the `data` array. The `out` array will contain the
414- * result of the transformation. The `data` array will not be modified.
415- *
416- * @param {Float64Array} out The output buffer for the transformed data.
417- * @param {Float64Array} data The input data to transform.
418- * @throws {Error} If `out` and `data` refer to the same buffer.
419- * @returns {void}
420- */
421- inverseTransform(out, data) {
422- if (out === data)
423- throw new Error('Input and output buffers must be different');
424-
425- this._transform4(out, data, -1 /* DONE */);
426- for (let i = 0; i < out.length; ++i)
427- out[i] /= this.size;
372+ }
373+
374+ /**
375+ * Performs a Fast Fourier Transform (FFT) on the given input data and stores the result in the output buffer.
376+ *
377+ * @param {Float64Array} out The output buffer to store the result.
378+ * @param {Float64Array} data The input data to transform.
379+ *
380+ * @throws {Error} Input and output buffers must be different.
381+ *
382+ * @returns {void}
383+ */
384+ transform(out, data) {
385+ if (out === data)
386+ throw new Error("Input and output buffers must be different");
387+
388+ this._transform4(out, data, 1 /* DONE */);
389+ }
390+
391+ /**
392+ * Performs a real-valued forward FFT on the given input buffer and stores the result in the given output buffer.
393+ * The input buffer must contain real values only, while the output buffer will contain complex values. The input and
394+ * output buffers must be different.
395+ *
396+ * @param {Float64Array} out The output buffer.
397+ * @param {Float64Array} data The input buffer containing real values.
398+ *
399+ * @throws {Error} If the input and output buffers are the same.
400+ */
401+ realTransform(out, data) {
402+ if (out === data)
403+ throw new Error("Input and output buffers must be different");
404+
405+ this._realTransform4(out, data, 1 /* DONE */);
406+ }
407+
408+ /**
409+ * Performs an inverse FFT transformation on the given `data` array, and stores the result in `out`.
410+ * The `out` array must be a different buffer than the `data` array. The `out` array will contain the
411+ * result of the transformation. The `data` array will not be modified.
412+ *
413+ * @param {Float64Array} out The output buffer for the transformed data.
414+ * @param {Float64Array} data The input data to transform.
415+ * @throws {Error} If `out` and `data` refer to the same buffer.
416+ * @returns {void}
417+ */
418+ inverseTransform(out, data) {
419+ if (out === data)
420+ throw new Error("Input and output buffers must be different");
421+
422+ this._transform4(out, data, -1 /* DONE */);
423+ for (let i = 0; i < out.length; ++i) out[i] /= this.size;
424+ }
425+
426+ /**
427+ * Performs a radix-4 implementation of a discrete Fourier transform on a given set of data.
428+ *
429+ * @param {Float64Array} out The output buffer for the transformed data.
430+ * @param {Float64Array} data The input buffer of data to be transformed.
431+ * @param {number} inv A scaling factor to apply to the transform.
432+ * @returns {void}
433+ */
434+ _transform4(out, data, inv) {
435+ // radix-4 implementation
436+
437+ const size = this._csize;
438+
439+ // Initial step (permute and transform)
440+ const width = this._width;
441+ let step = 1 << width;
442+ let len = (size / step) << 1;
443+
444+ let outOff;
445+ let t;
446+ const bitrev = this._bitrev;
447+ if (len === 4) {
448+ for (outOff = 0, t = 0; outOff < size; outOff += len, ++t) {
449+ const off = bitrev[t];
450+ this._singleTransform2(data, out, outOff, off, step);
451+ }
452+ } else {
453+ // len === 8
454+ for (outOff = 0, t = 0; outOff < size; outOff += len, ++t) {
455+ const off = bitrev[t];
456+ this._singleTransform4(data, out, outOff, off, step, inv);
457+ }
428458 }
429459
430- /**
431- * Performs a radix-4 implementation of a discrete Fourier transform on a given set of data.
432- *
433- * @param {Float64Array} out The output buffer for the transformed data.
434- * @param {Float64Array} data The input buffer of data to be transformed.
435- * @param {number} inv A scaling factor to apply to the transform.
436- * @returns {void}
437- */
438- _transform4(out, data, inv) {
439- // radix-4 implementation
440-
441- const size = this._csize;
442-
443- // Initial step (permute and transform)
444- const width = this._width;
445- let step = 1 << width;
446- let len = (size / step) << 1;
447-
448- let outOff;
449- let t;
450- const bitrev = this._bitrev;
451- if (len === 4) {
452- for (outOff = 0, t = 0; outOff < size; outOff += len, ++t) {
453- const off = bitrev[t];
454- this._singleTransform2(data, out, outOff, off, step);
455- }
456- } else {
457- // len === 8
458- for (outOff = 0, t = 0; outOff < size; outOff += len, ++t) {
459- const off = bitrev[t];
460- this._singleTransform4(data, out, outOff, off, step, inv);
461- }
462- }
463-
464- // Loop through steps in decreasing order
465- for (step >>= 2; step >= 2; step >>= 2) {
466- len = (size / step) << 1;
467- const quarterLen = len >>> 2;
468-
469- // Loop through offsets in the data
470- for (outOff = 0; outOff < size; outOff += len) {
471- // Full case
472- const limit = outOff + quarterLen - 1;
473- for (let i = outOff, k = 0; i < limit; i += 2, k += step) {
474- const A = i;
475- const B = A + quarterLen;
476- const C = B + quarterLen;
477- const D = C + quarterLen;
478-
479- // Original values
480- const Ar = out[A];
481- const Ai = out[A + 1];
482- const Br = out[B];
483- const Bi = out[B + 1];
484- const Cr = out[C];
485- const Ci = out[C + 1];
486- const Dr = out[D];
487- const Di = out[D + 1];
488-
489- const tableBr = this.table[k];
490- const tableBi = inv * this.table[k + 1];
491- const MBr = Br * tableBr - Bi * tableBi;
492- const MBi = Br * tableBi + Bi * tableBr;
493-
494- const tableCr = this.table[2 * k];
495- const tableCi = inv * this.table[2 * k + 1];
496- const MCr = Cr * tableCr - Ci * tableCi;
497- const MCi = Cr * tableCi + Ci * tableCr;
498-
499- const tableDr = this.table[3 * k];
500- const tableDi = inv * this.table[3 * k + 1];
501- const MDr = Dr * tableDr - Di * tableDi;
502- const MDi = Dr * tableDi + Di * tableDr;
503-
504- // Pre-Final values
505- const T0r = Ar + MCr;
506- const T0i = Ai + MCi;
507- const T1r = Ar - MCr;
508- const T1i = Ai - MCi;
509- const T2r = MBr + MDr;
510- const T2i = MBi + MDi;
511- const T3r = inv * (MBr - MDr);
512- const T3i = inv * (MBi - MDi);
513-
514- // Final values
515- out[A] = T0r + T2r;
516- out[A + 1] = T0i + T2i;
517- out[B] = T1r + T3i;
518- out[B + 1] = T1i - T3r;
519- out[C] = T0r - T2r;
520- out[C + 1] = T0i - T2i;
521- out[D] = T1r - T3i;
522- out[D + 1] = T1i + T3r;
523- }
524- }
460+ // Loop through steps in decreasing order
461+ for (step >>= 2; step >= 2; step >>= 2) {
462+ len = (size / step) << 1;
463+ const quarterLen = len >>> 2;
464+
465+ // Loop through offsets in the data
466+ for (outOff = 0; outOff < size; outOff += len) {
467+ // Full case
468+ const limit = outOff + quarterLen - 1;
469+ for (let i = outOff, k = 0; i < limit; i += 2, k += step) {
470+ const A = i;
471+ const B = A + quarterLen;
472+ const C = B + quarterLen;
473+ const D = C + quarterLen;
474+
475+ // Original values
476+ const Ar = out[A];
477+ const Ai = out[A + 1];
478+ const Br = out[B];
479+ const Bi = out[B + 1];
480+ const Cr = out[C];
481+ const Ci = out[C + 1];
482+ const Dr = out[D];
483+ const Di = out[D + 1];
484+
485+ const tableBr = this.table[k];
486+ const tableBi = inv * this.table[k + 1];
487+ const MBr = Br * tableBr - Bi * tableBi;
488+ const MBi = Br * tableBi + Bi * tableBr;
489+
490+ const tableCr = this.table[2 * k];
491+ const tableCi = inv * this.table[2 * k + 1];
492+ const MCr = Cr * tableCr - Ci * tableCi;
493+ const MCi = Cr * tableCi + Ci * tableCr;
494+
495+ const tableDr = this.table[3 * k];
496+ const tableDi = inv * this.table[3 * k + 1];
497+ const MDr = Dr * tableDr - Di * tableDi;
498+ const MDi = Dr * tableDi + Di * tableDr;
499+
500+ // Pre-Final values
501+ const T0r = Ar + MCr;
502+ const T0i = Ai + MCi;
503+ const T1r = Ar - MCr;
504+ const T1i = Ai - MCi;
505+ const T2r = MBr + MDr;
506+ const T2i = MBi + MDi;
507+ const T3r = inv * (MBr - MDr);
508+ const T3i = inv * (MBi - MDi);
509+
510+ // Final values
511+ out[A] = T0r + T2r;
512+ out[A + 1] = T0i + T2i;
513+ out[B] = T1r + T3i;
514+ out[B + 1] = T1i - T3r;
515+ out[C] = T0r - T2r;
516+ out[C + 1] = T0i - T2i;
517+ out[D] = T1r - T3i;
518+ out[D + 1] = T1i + T3r;
525519 }
520+ }
526521 }
527-
528- /**
529- * Performs a radix-2 implementation of a discrete Fourier transform on a given set of data.
530- *
531- * @param {Float64Array} data The input buffer of data to be transformed.
532- * @param {Float64Array} out The output buffer for the transformed data.
533- * @param {number} outOff The offset at which to write the output data.
534- * @param {number} off The offset at which to begin reading the input data.
535- * @param {number} step The step size for indexing the input data.
536- * @returns {void}
537- */
538- _singleTransform2(data, out, outOff, off, step) {
539- // radix-2 implementation
540- // NOTE: Only called for len=4
541-
542- const evenR = data[off];
543- const evenI = data[off + 1];
544- const oddR = data[off + step];
545- const oddI = data[off + step + 1];
546-
547- out[outOff] = evenR + oddR;
548- out[outOff + 1] = evenI + oddI;
549- out[outOff + 2] = evenR - oddR;
550- out[outOff + 3] = evenI - oddI;
551- }
552-
553- /**
554- * Performs radix-4 transformation on input data of length 8
555- *
556- * @param {Float64Array} data Input data array of length 8
557- * @param {Float64Array} out Output data array of length 8
558- * @param {number} outOff Index of output array to start writing from
559- * @param {number} off Index of input array to start reading from
560- * @param {number} step Step size between elements in input array
561- * @param {number} inv Scaling factor for inverse transform
562- *
563- * @returns {void}
564- */
565- _singleTransform4(data, out, outOff, off, step, inv) {
566- // radix-4
567- // NOTE: Only called for len=8
568- const step2 = step * 2;
569- const step3 = step * 3;
570-
571- // Original values
572- const Ar = data[off];
573- const Ai = data[off + 1];
574- const Br = data[off + step];
575- const Bi = data[off + step + 1];
576- const Cr = data[off + step2];
577- const Ci = data[off + step2 + 1];
578- const Dr = data[off + step3];
579- const Di = data[off + step3 + 1];
580-
581- // Pre-Final values
582- const T0r = Ar + Cr;
583- const T0i = Ai + Ci;
584- const T1r = Ar - Cr;
585- const T1i = Ai - Ci;
586- const T2r = Br + Dr;
587- const T2i = Bi + Di;
588- const T3r = inv * (Br - Dr);
589- const T3i = inv * (Bi - Di);
590-
591- // Final values
592- out[outOff] = T0r + T2r;
593- out[outOff + 1] = T0i + T2i;
594- out[outOff + 2] = T1r + T3i;
595- out[outOff + 3] = T1i - T3r;
596- out[outOff + 4] = T0r - T2r;
597- out[outOff + 5] = T0i - T2i;
598- out[outOff + 6] = T1r - T3i;
599- out[outOff + 7] = T1i + T3r;
522+ }
523+
524+ /**
525+ * Performs a radix-2 implementation of a discrete Fourier transform on a given set of data.
526+ *
527+ * @param {Float64Array} data The input buffer of data to be transformed.
528+ * @param {Float64Array} out The output buffer for the transformed data.
529+ * @param {number} outOff The offset at which to write the output data.
530+ * @param {number} off The offset at which to begin reading the input data.
531+ * @param {number} step The step size for indexing the input data.
532+ * @returns {void}
533+ */
534+ _singleTransform2(data, out, outOff, off, step) {
535+ // radix-2 implementation
536+ // NOTE: Only called for len=4
537+
538+ const evenR = data[off];
539+ const evenI = data[off + 1];
540+ const oddR = data[off + step];
541+ const oddI = data[off + step + 1];
542+
543+ out[outOff] = evenR + oddR;
544+ out[outOff + 1] = evenI + oddI;
545+ out[outOff + 2] = evenR - oddR;
546+ out[outOff + 3] = evenI - oddI;
547+ }
548+
549+ /**
550+ * Performs radix-4 transformation on input data of length 8
551+ *
552+ * @param {Float64Array} data Input data array of length 8
553+ * @param {Float64Array} out Output data array of length 8
554+ * @param {number} outOff Index of output array to start writing from
555+ * @param {number} off Index of input array to start reading from
556+ * @param {number} step Step size between elements in input array
557+ * @param {number} inv Scaling factor for inverse transform
558+ *
559+ * @returns {void}
560+ */
561+ _singleTransform4(data, out, outOff, off, step, inv) {
562+ // radix-4
563+ // NOTE: Only called for len=8
564+ const step2 = step * 2;
565+ const step3 = step * 3;
566+
567+ // Original values
568+ const Ar = data[off];
569+ const Ai = data[off + 1];
570+ const Br = data[off + step];
571+ const Bi = data[off + step + 1];
572+ const Cr = data[off + step2];
573+ const Ci = data[off + step2 + 1];
574+ const Dr = data[off + step3];
575+ const Di = data[off + step3 + 1];
576+
577+ // Pre-Final values
578+ const T0r = Ar + Cr;
579+ const T0i = Ai + Ci;
580+ const T1r = Ar - Cr;
581+ const T1i = Ai - Ci;
582+ const T2r = Br + Dr;
583+ const T2i = Bi + Di;
584+ const T3r = inv * (Br - Dr);
585+ const T3i = inv * (Bi - Di);
586+
587+ // Final values
588+ out[outOff] = T0r + T2r;
589+ out[outOff + 1] = T0i + T2i;
590+ out[outOff + 2] = T1r + T3i;
591+ out[outOff + 3] = T1i - T3r;
592+ out[outOff + 4] = T0r - T2r;
593+ out[outOff + 5] = T0i - T2i;
594+ out[outOff + 6] = T1r - T3i;
595+ out[outOff + 7] = T1i + T3r;
596+ }
597+
598+ /**
599+ * Real input radix-4 implementation
600+ * @param {Float64Array} out Output array for the transformed data
601+ * @param {Float64Array} data Input array of real data to be transformed
602+ * @param {number} inv The scale factor used to normalize the inverse transform
603+ */
604+ _realTransform4(out, data, inv) {
605+ // Real input radix-4 implementation
606+ const size = this._csize;
607+
608+ // Initial step (permute and transform)
609+ const width = this._width;
610+ let step = 1 << width;
611+ let len = (size / step) << 1;
612+
613+ let outOff;
614+ let t;
615+ const bitrev = this._bitrev;
616+ if (len === 4) {
617+ for (outOff = 0, t = 0; outOff < size; outOff += len, ++t) {
618+ const off = bitrev[t];
619+ this._singleRealTransform2(data, out, outOff, off >>> 1, step >>> 1);
620+ }
621+ } else {
622+ // len === 8
623+ for (outOff = 0, t = 0; outOff < size; outOff += len, ++t) {
624+ const off = bitrev[t];
625+ this._singleRealTransform4(
626+ data,
627+ out,
628+ outOff,
629+ off >>> 1,
630+ step >>> 1,
631+ inv,
632+ );
633+ }
600634 }
601635
602- /**
603- * Real input radix-4 implementation
604- * @param {Float64Array} out Output array for the transformed data
605- * @param {Float64Array} data Input array of real data to be transformed
606- * @param {number} inv The scale factor used to normalize the inverse transform
607- */
608- _realTransform4(out, data, inv) {
609- // Real input radix-4 implementation
610- const size = this._csize;
611-
612- // Initial step (permute and transform)
613- const width = this._width;
614- let step = 1 << width;
615- let len = (size / step) << 1;
616-
617- let outOff;
618- let t;
619- const bitrev = this._bitrev;
620- if (len === 4) {
621- for (outOff = 0, t = 0; outOff < size; outOff += len, ++t) {
622- const off = bitrev[t];
623- this._singleRealTransform2(data, out, outOff, off >>> 1, step >>> 1);
624- }
625- } else {
626- // len === 8
627- for (outOff = 0, t = 0; outOff < size; outOff += len, ++t) {
628- const off = bitrev[t];
629- this._singleRealTransform4(data, out, outOff, off >>> 1, step >>> 1, inv);
630- }
636+ // TODO: Optimize once https://github.com/indutny/fft.js/issues/25 is fixed
637+ // Loop through steps in decreasing order
638+ for (step >>= 2; step >= 2; step >>= 2) {
639+ len = (size / step) << 1;
640+ const quarterLen = len >>> 2;
641+
642+ // Loop through offsets in the data
643+ for (outOff = 0; outOff < size; outOff += len) {
644+ // Full case
645+ const limit = outOff + quarterLen - 1;
646+ for (let i = outOff, k = 0; i < limit; i += 2, k += step) {
647+ const A = i;
648+ const B = A + quarterLen;
649+ const C = B + quarterLen;
650+ const D = C + quarterLen;
651+
652+ // Original values
653+ const Ar = out[A];
654+ const Ai = out[A + 1];
655+ const Br = out[B];
656+ const Bi = out[B + 1];
657+ const Cr = out[C];
658+ const Ci = out[C + 1];
659+ const Dr = out[D];
660+ const Di = out[D + 1];
661+
662+ const tableBr = this.table[k];
663+ const tableBi = inv * this.table[k + 1];
664+ const MBr = Br * tableBr - Bi * tableBi;
665+ const MBi = Br * tableBi + Bi * tableBr;
666+
667+ const tableCr = this.table[2 * k];
668+ const tableCi = inv * this.table[2 * k + 1];
669+ const MCr = Cr * tableCr - Ci * tableCi;
670+ const MCi = Cr * tableCi + Ci * tableCr;
671+
672+ const tableDr = this.table[3 * k];
673+ const tableDi = inv * this.table[3 * k + 1];
674+ const MDr = Dr * tableDr - Di * tableDi;
675+ const MDi = Dr * tableDi + Di * tableDr;
676+
677+ // Pre-Final values
678+ const T0r = Ar + MCr;
679+ const T0i = Ai + MCi;
680+ const T1r = Ar - MCr;
681+ const T1i = Ai - MCi;
682+ const T2r = MBr + MDr;
683+ const T2i = MBi + MDi;
684+ const T3r = inv * (MBr - MDr);
685+ const T3i = inv * (MBi - MDi);
686+
687+ // Final values
688+ out[A] = T0r + T2r;
689+ out[A + 1] = T0i + T2i;
690+ out[B] = T1r + T3i;
691+ out[B + 1] = T1i - T3r;
692+ out[C] = T0r - T2r;
693+ out[C + 1] = T0i - T2i;
694+ out[D] = T1r - T3i;
695+ out[D + 1] = T1i + T3r;
631696 }
632-
633- // TODO: Optimize once https://github.com/indutny/fft.js/issues/25 is fixed
634- // Loop through steps in decreasing order
635- for (step >>= 2; step >= 2; step >>= 2) {
636- len = (size / step) << 1;
637- const quarterLen = len >>> 2;
638-
639- // Loop through offsets in the data
640- for (outOff = 0; outOff < size; outOff += len) {
641- // Full case
642- const limit = outOff + quarterLen - 1;
643- for (let i = outOff, k = 0; i < limit; i += 2, k += step) {
644- const A = i;
645- const B = A + quarterLen;
646- const C = B + quarterLen;
647- const D = C + quarterLen;
648-
649- // Original values
650- const Ar = out[A];
651- const Ai = out[A + 1];
652- const Br = out[B];
653- const Bi = out[B + 1];
654- const Cr = out[C];
655- const Ci = out[C + 1];
656- const Dr = out[D];
657- const Di = out[D + 1];
658-
659- const tableBr = this.table[k];
660- const tableBi = inv * this.table[k + 1];
661- const MBr = Br * tableBr - Bi * tableBi;
662- const MBi = Br * tableBi + Bi * tableBr;
663-
664- const tableCr = this.table[2 * k];
665- const tableCi = inv * this.table[2 * k + 1];
666- const MCr = Cr * tableCr - Ci * tableCi;
667- const MCi = Cr * tableCi + Ci * tableCr;
668-
669- const tableDr = this.table[3 * k];
670- const tableDi = inv * this.table[3 * k + 1];
671- const MDr = Dr * tableDr - Di * tableDi;
672- const MDi = Dr * tableDi + Di * tableDr;
673-
674- // Pre-Final values
675- const T0r = Ar + MCr;
676- const T0i = Ai + MCi;
677- const T1r = Ar - MCr;
678- const T1i = Ai - MCi;
679- const T2r = MBr + MDr;
680- const T2i = MBi + MDi;
681- const T3r = inv * (MBr - MDr);
682- const T3i = inv * (MBi - MDi);
683-
684- // Final values
685- out[A] = T0r + T2r;
686- out[A + 1] = T0i + T2i;
687- out[B] = T1r + T3i;
688- out[B + 1] = T1i - T3r;
689- out[C] = T0r - T2r;
690- out[C + 1] = T0i - T2i;
691- out[D] = T1r - T3i;
692- out[D + 1] = T1i + T3r;
693- }
694- }
695- }
696- }
697-
698- /**
699- * Performs a single real input radix-2 transformation on the provided data
700- *
701- * @param {Float64Array} data The input data array
702- * @param {Float64Array} out The output data array
703- * @param {number} outOff The output offset
704- * @param {number} off The input offset
705- * @param {number} step The step
706- *
707- * @returns {void}
708- */
709- _singleRealTransform2(data, out, outOff, off, step) {
710- // radix-2 implementation
711- // NOTE: Only called for len=4
712-
713- const evenR = data[off];
714- const oddR = data[off + step];
715-
716- out[outOff] = evenR + oddR;
717- out[outOff + 1] = 0;
718- out[outOff + 2] = evenR - oddR;
719- out[outOff + 3] = 0;
720- }
721-
722- /**
723- * Computes a single real-valued transform using radix-4 algorithm.
724- * This method is only called for len=8.
725- *
726- * @param {Float64Array} data The input data array.
727- * @param {Float64Array} out The output data array.
728- * @param {number} outOff The offset into the output array.
729- * @param {number} off The offset into the input array.
730- * @param {number} step The step size for the input array.
731- * @param {number} inv The value of inverse.
732- */
733- _singleRealTransform4(data, out, outOff, off, step, inv) {
734- // radix-4
735- // NOTE: Only called for len=8
736- const step2 = step * 2;
737- const step3 = step * 3;
738-
739- // Original values
740- const Ar = data[off];
741- const Br = data[off + step];
742- const Cr = data[off + step2];
743- const Dr = data[off + step3];
744-
745- // Pre-Final values
746- const T0r = Ar + Cr;
747- const T1r = Ar - Cr;
748- const T2r = Br + Dr;
749- const T3r = inv * (Br - Dr);
750-
751- // Final values
752- out[outOff] = T0r + T2r;
753- out[outOff + 1] = 0;
754- out[outOff + 2] = T1r;
755- out[outOff + 3] = -T3r;
756- out[outOff + 4] = T0r - T2r;
757- out[outOff + 5] = 0;
758- out[outOff + 6] = T1r;
759- out[outOff + 7] = T3r;
697+ }
760698 }
699+ }
700+
701+ /**
702+ * Performs a single real input radix-2 transformation on the provided data
703+ *
704+ * @param {Float64Array} data The input data array
705+ * @param {Float64Array} out The output data array
706+ * @param {number} outOff The output offset
707+ * @param {number} off The input offset
708+ * @param {number} step The step
709+ *
710+ * @returns {void}
711+ */
712+ _singleRealTransform2(data, out, outOff, off, step) {
713+ // radix-2 implementation
714+ // NOTE: Only called for len=4
715+
716+ const evenR = data[off];
717+ const oddR = data[off + step];
718+
719+ out[outOff] = evenR + oddR;
720+ out[outOff + 1] = 0;
721+ out[outOff + 2] = evenR - oddR;
722+ out[outOff + 3] = 0;
723+ }
724+
725+ /**
726+ * Computes a single real-valued transform using radix-4 algorithm.
727+ * This method is only called for len=8.
728+ *
729+ * @param {Float64Array} data The input data array.
730+ * @param {Float64Array} out The output data array.
731+ * @param {number} outOff The offset into the output array.
732+ * @param {number} off The offset into the input array.
733+ * @param {number} step The step size for the input array.
734+ * @param {number} inv The value of inverse.
735+ */
736+ _singleRealTransform4(data, out, outOff, off, step, inv) {
737+ // radix-4
738+ // NOTE: Only called for len=8
739+ const step2 = step * 2;
740+ const step3 = step * 3;
741+
742+ // Original values
743+ const Ar = data[off];
744+ const Br = data[off + step];
745+ const Cr = data[off + step2];
746+ const Dr = data[off + step3];
747+
748+ // Pre-Final values
749+ const T0r = Ar + Cr;
750+ const T1r = Ar - Cr;
751+ const T2r = Br + Dr;
752+ const T3r = inv * (Br - Dr);
753+
754+ // Final values
755+ out[outOff] = T0r + T2r;
756+ out[outOff + 1] = 0;
757+ out[outOff + 2] = T1r;
758+ out[outOff + 3] = -T3r;
759+ out[outOff + 4] = T0r - T2r;
760+ out[outOff + 5] = 0;
761+ out[outOff + 6] = T1r;
762+ out[outOff + 7] = T3r;
763+ }
761764 }
762765
763766 /**
764767 * NP2FFT class provides functionality for performing Fast Fourier Transform on arrays
765768 * which are not a power of two in length. In such cases, the chirp-z transform is used.
766- *
769+ *
767770 * For more information, see: https://math.stackexchange.com/questions/77118/non-power-of-2-ffts/77156#77156
768771 */
769772 class NP2FFT {
770-
771- /**
772- * Constructs a new NP2FFT object.
773- * @param {number} fft_length The length of the FFT
774- */
775- constructor(fft_length) {
776- // Helper variables
777- const a = 2 * (fft_length - 1);
778- const b = 2 * (2 * fft_length - 1);
779- const nextP2 = 2 ** (Math.ceil(Math.log2(b)))
780- this.bufferSize = nextP2;
781- this._a = a;
782-
783- // Define buffers
784- // Compute chirp for transform
785- const chirp = new Float64Array(b);
786- const ichirp = new Float64Array(nextP2);
787- this._chirpBuffer = new Float64Array(nextP2);
788- this._buffer1 = new Float64Array(nextP2);
789- this._buffer2 = new Float64Array(nextP2);
790- this._outBuffer1 = new Float64Array(nextP2);
791- this._outBuffer2 = new Float64Array(nextP2);
792-
793- // Compute complex exponentiation
794- const theta = -2 * Math.PI / fft_length;
795- const baseR = Math.cos(theta);
796- const baseI = Math.sin(theta);
797-
798- // Precompute helper for chirp-z transform
799- for (let i = 0; i < b >> 1; ++i) {
800- // Compute complex power:
801- const e = (i + 1 - fft_length) ** 2 / 2.0;
802-
803- // Compute the modulus and argument of the result
804- const result_mod = Math.sqrt(baseR ** 2 + baseI ** 2) ** e;
805- const result_arg = e * Math.atan2(baseI, baseR);
806-
807- // Convert the result back to rectangular form
808- // and assign to chirp and ichirp
809- const i2 = 2 * i;
810- chirp[i2] = result_mod * Math.cos(result_arg);
811- chirp[i2 + 1] = result_mod * Math.sin(result_arg);
812-
813- // conjugate
814- ichirp[i2] = chirp[i2];
815- ichirp[i2 + 1] = - chirp[i2 + 1];
816- }
817- this._slicedChirpBuffer = chirp.subarray(a, b);
818-
819- // create object to perform Fast Fourier Transforms
820- // with `nextP2` complex numbers
821- this._f = new P2FFT(nextP2 >> 1);
822- this._f.transform(this._chirpBuffer, ichirp);
773+ /**
774+ * Constructs a new NP2FFT object.
775+ * @param {number} fft_length The length of the FFT
776+ */
777+ constructor(fft_length) {
778+ // Helper variables
779+ const a = 2 * (fft_length - 1);
780+ const b = 2 * (2 * fft_length - 1);
781+ const nextP2 = 2 ** Math.ceil(Math.log2(b));
782+ this.bufferSize = nextP2;
783+ this._a = a;
784+
785+ // Define buffers
786+ // Compute chirp for transform
787+ const chirp = new Float64Array(b);
788+ const ichirp = new Float64Array(nextP2);
789+ this._chirpBuffer = new Float64Array(nextP2);
790+ this._buffer1 = new Float64Array(nextP2);
791+ this._buffer2 = new Float64Array(nextP2);
792+ this._outBuffer1 = new Float64Array(nextP2);
793+ this._outBuffer2 = new Float64Array(nextP2);
794+
795+ // Compute complex exponentiation
796+ const theta = (-2 * Math.PI) / fft_length;
797+ const baseR = Math.cos(theta);
798+ const baseI = Math.sin(theta);
799+
800+ // Precompute helper for chirp-z transform
801+ for (let i = 0; i < b >> 1; ++i) {
802+ // Compute complex power:
803+ const e = (i + 1 - fft_length) ** 2 / 2.0;
804+
805+ // Compute the modulus and argument of the result
806+ const result_mod = Math.sqrt(baseR ** 2 + baseI ** 2) ** e;
807+ const result_arg = e * Math.atan2(baseI, baseR);
808+
809+ // Convert the result back to rectangular form
810+ // and assign to chirp and ichirp
811+ const i2 = 2 * i;
812+ chirp[i2] = result_mod * Math.cos(result_arg);
813+ chirp[i2 + 1] = result_mod * Math.sin(result_arg);
814+
815+ // conjugate
816+ ichirp[i2] = chirp[i2];
817+ ichirp[i2 + 1] = -chirp[i2 + 1];
823818 }
824-
825- _transform(output, input, real) {
826- const ib1 = this._buffer1;
827- const ib2 = this._buffer2;
828- const ob2 = this._outBuffer1;
829- const ob3 = this._outBuffer2;
830- const cb = this._chirpBuffer;
831- const sb = this._slicedChirpBuffer;
832- const a = this._a;
833-
834- if (real) {
835- // Real multiplication
836- for (let j = 0; j < sb.length; j += 2) {
837- const j2 = j + 1
838- const j3 = j >> 1;
839-
840- const a_real = input[j3];
841- ib1[j] = a_real * sb[j];
842- ib1[j2] = a_real * sb[j2];
843- }
844- } else {
845- // Complex multiplication
846- for (let j = 0; j < sb.length; j += 2) {
847- const j2 = j + 1
848- ib1[j] = input[j] * sb[j] - input[j2] * sb[j2];
849- ib1[j2] = input[j] * sb[j2] + input[j2] * sb[j];
850- }
851- }
852- this._f.transform(ob2, ib1);
853-
854- for (let j = 0; j < cb.length; j += 2) {
855- const j2 = j + 1;
856-
857- ib2[j] = ob2[j] * cb[j] - ob2[j2] * cb[j2];
858- ib2[j2] = ob2[j] * cb[j2] + ob2[j2] * cb[j];
859- }
860- this._f.inverseTransform(ob3, ib2);
861-
862- for (let j = 0; j < ob3.length; j += 2) {
863- const a_real = ob3[j + a];
864- const a_imag = ob3[j + a + 1];
865- const b_real = sb[j];
866- const b_imag = sb[j + 1];
867-
868- output[j] = a_real * b_real - a_imag * b_imag;
869- output[j + 1] = a_real * b_imag + a_imag * b_real;
870- }
819+ this._slicedChirpBuffer = chirp.subarray(a, b);
820+
821+ // create object to perform Fast Fourier Transforms
822+ // with `nextP2` complex numbers
823+ this._f = new P2FFT(nextP2 >> 1);
824+ this._f.transform(this._chirpBuffer, ichirp);
825+ }
826+
827+ _transform(output, input, real) {
828+ const ib1 = this._buffer1;
829+ const ib2 = this._buffer2;
830+ const ob2 = this._outBuffer1;
831+ const ob3 = this._outBuffer2;
832+ const cb = this._chirpBuffer;
833+ const sb = this._slicedChirpBuffer;
834+ const a = this._a;
835+
836+ if (real) {
837+ // Real multiplication
838+ for (let j = 0; j < sb.length; j += 2) {
839+ const j2 = j + 1;
840+ const j3 = j >> 1;
841+
842+ const a_real = input[j3];
843+ ib1[j] = a_real * sb[j];
844+ ib1[j2] = a_real * sb[j2];
845+ }
846+ } else {
847+ // Complex multiplication
848+ for (let j = 0; j < sb.length; j += 2) {
849+ const j2 = j + 1;
850+ ib1[j] = input[j] * sb[j] - input[j2] * sb[j2];
851+ ib1[j2] = input[j] * sb[j2] + input[j2] * sb[j];
852+ }
871853 }
854+ this._f.transform(ob2, ib1);
872855
873- transform(output, input) {
874- this._transform(output, input, false);
875- }
856+ for (let j = 0; j < cb.length; j += 2) {
857+ const j2 = j + 1;
876858
877- realTransform(output, input) {
878- this._transform(output, input, true);
859+ ib2[j] = ob2[j] * cb[j] - ob2[j2] * cb[j2];
860+ ib2[j2] = ob2[j] * cb[j2] + ob2[j2] * cb[j];
879861 }
862+ this._f.inverseTransform(ob3, ib2);
863+
864+ for (let j = 0; j < ob3.length; j += 2) {
865+ const a_real = ob3[j + a];
866+ const a_imag = ob3[j + a + 1];
867+ const b_real = sb[j];
868+ const b_imag = sb[j + 1];
869+
870+ output[j] = a_real * b_real - a_imag * b_imag;
871+ output[j + 1] = a_real * b_imag + a_imag * b_real;
872+ }
873+ }
874+
875+ transform(output, input) {
876+ this._transform(output, input, false);
877+ }
878+
879+ realTransform(output, input) {
880+ this._transform(output, input, true);
881+ }
880882 }
881883
882884 export class FFT {
883- constructor(fft_length) {
884- this.fft_length = fft_length;
885- this.isPowerOfTwo = isPowerOfTwo(fft_length);
886- if (this.isPowerOfTwo) {
887- this.fft = new P2FFT(fft_length);
888- this.outputBufferSize = 2 * fft_length;
889- } else {
890- this.fft = new NP2FFT(fft_length);
891- this.outputBufferSize = this.fft.bufferSize;
892- }
893- }
894-
895- realTransform(out, input) {
896- this.fft.realTransform(out, input);
897- }
898-
899- transform(out, input) {
900- this.fft.transform(out, input);
885+ constructor(fft_length) {
886+ this.fft_length = fft_length;
887+ this.isPowerOfTwo = isPowerOfTwo(fft_length);
888+ if (this.isPowerOfTwo) {
889+ this.fft = new P2FFT(fft_length);
890+ this.outputBufferSize = 2 * fft_length;
891+ } else {
892+ this.fft = new NP2FFT(fft_length);
893+ this.outputBufferSize = this.fft.bufferSize;
901894 }
895+ }
896+
897+ realTransform(out, input) {
898+ this.fft.realTransform(out, input);
899+ }
900+
901+ transform(out, input) {
902+ this.fft.transform(out, input);
903+ }
902904 }
903905
904-
905906 /**
906907 * Performs median filter on the provided data. Padding is done by mirroring the data.
907908 * @param {AnyTypedArray} data The input array
908909 * @param {number} windowSize The window size
909910 */
910911 export function medianFilter(data, windowSize) {
912+ if (windowSize % 2 === 0 || windowSize <= 0) {
913+ throw new Error("Window size must be a positive odd number");
914+ }
911915
912- if (windowSize % 2 === 0 || windowSize <= 0) {
913- throw new Error('Window size must be a positive odd number');
914- }
915-
916- // @ts-ignore
917- const outputArray = new data.constructor(data.length);
918-
919- // @ts-ignore
920- const buffer = new data.constructor(windowSize); // Reusable array for storing values
916+ // @ts-ignore
917+ const outputArray = new data.constructor(data.length);
921918
922- const halfWindowSize = Math.floor(windowSize / 2);
919+ // @ts-ignore
920+ const buffer = new data.constructor(windowSize); // Reusable array for storing values
923921
924- for (let i = 0; i < data.length; ++i) {
925- let valuesIndex = 0;
922+ const halfWindowSize = Math.floor(windowSize / 2);
926923
927- for (let j = -halfWindowSize; j <= halfWindowSize; ++j) {
928- let index = i + j;
929- if (index < 0) {
930- index = Math.abs(index);
931- } else if (index >= data.length) {
932- index = 2 * (data.length - 1) - index;
933- }
924+ for (let i = 0; i < data.length; ++i) {
925+ let valuesIndex = 0;
934926
935- buffer[valuesIndex++] = data[index];
936- }
927+ for (let j = -halfWindowSize; j <= halfWindowSize; ++j) {
928+ let index = i + j;
929+ if (index < 0) {
930+ index = Math.abs(index);
931+ } else if (index >= data.length) {
932+ index = 2 * (data.length - 1) - index;
933+ }
937934
938- buffer.sort();
939- outputArray[i] = buffer[halfWindowSize];
935+ buffer[valuesIndex++] = data[index];
940936 }
941937
942- return outputArray;
938+ buffer.sort();
939+ outputArray[i] = buffer[halfWindowSize];
940+ }
941+
942+ return outputArray;
943943 }
944944
945945 /**
@@ -949,6 +949,6 @@
949949 * @returns {number} The rounded number
950950 */
951951 export function round(num, decimals) {
952- const pow = Math.pow(10, decimals);
953- return Math.round(num * pow) / pow;
952+ const pow = Math.pow(10, decimals);
953+ return Math.round(num * pow) / pow;
954954 }
modified core/vendor/modules/@xenova/transformers/src/utils/tensor.js +968 −928
@@ -1,33 +1,29 @@
11 /**
22 * @file Helper module for `Tensor` processing.
3- *
4- * These functions and classes are only used internally,
3+ *
4+ * These functions and classes are only used internally,
55 * meaning an end-user shouldn't need to access anything here.
6- *
6+ *
77 * @module utils/tensor
88 */
99
10-import { ONNX } from '../backends/onnx.js';
11-
12-import {
13- interpolate_data,
14- transpose_data
15-} from './maths.js';
10+import { ONNX } from "../backends/onnx.js";
1611
12+import { interpolate_data, transpose_data } from "./maths.js";
1713
1814 const DataTypeMap = Object.freeze({
19- float32: Float32Array,
20- float64: Float64Array,
21- string: Array, // string[]
22- int8: Int8Array,
23- uint8: Uint8Array,
24- int16: Int16Array,
25- uint16: Uint16Array,
26- int32: Int32Array,
27- uint32: Uint32Array,
28- int64: BigInt64Array,
29- uint64: BigUint64Array,
30- bool: Uint8Array,
15+ float32: Float32Array,
16+ float64: Float64Array,
17+ string: Array, // string[]
18+ int8: Int8Array,
19+ uint8: Uint8Array,
20+ int16: Int16Array,
21+ uint16: Uint16Array,
22+ int32: Int32Array,
23+ uint32: Uint32Array,
24+ int64: BigInt64Array,
25+ uint64: BigUint64Array,
26+ bool: Uint8Array,
3127 });
3228
3329 /**
@@ -38,592 +34,598 @@
3834 const ONNXTensor = ONNX.Tensor;
3935
4036 export class Tensor {
41- /** @type {number[]} Dimensions of the tensor. */
42- dims;
43-
44- /** @type {DataType} Type of the tensor. */
45- type;
46-
47- /** @type {DataArray} The data stored in the tensor. */
48- data;
49-
50- /** @type {number} The number of elements in the tensor. */
51- size;
52-
53- /**
54- * Create a new Tensor or copy an existing Tensor.
55- * @param {[DataType, DataArray, number[]]|[import('onnxruntime-common').Tensor]} args
56- */
57- constructor(...args) {
58- if (args[0] instanceof ONNXTensor) {
59- // Create shallow copy
60- Object.assign(this, args[0]);
61-
62- } else {
63- // Create new tensor
64- Object.assign(this, new ONNXTensor(
65- /** @type {DataType} */(args[0]),
66- /** @type {Exclude<import('./maths.js').AnyTypedArray, Uint8ClampedArray>} */(args[1]),
67- args[2]
68- ));
69- }
70-
71- return new Proxy(this, {
72- get: (obj, key) => {
73- if (typeof key === 'string') {
74- let index = Number(key);
75- if (Number.isInteger(index)) {
76- // key is an integer (i.e., index)
77- return obj._getitem(index);
78- }
79- }
80- // @ts-ignore
81- return obj[key];
82- },
83- set: (obj, key, value) => {
84- // TODO allow setting of data
85-
86- // @ts-ignore
87- return obj[key] = value;
88- }
89- });
90- }
91-
92- /**
93- * Returns an iterator object for iterating over the tensor data in row-major order.
94- * If the tensor has more than one dimension, the iterator will yield subarrays.
95- * @returns {Iterator} An iterator object for iterating over the tensor data in row-major order.
96- */
97- *[Symbol.iterator]() {
98- const [iterLength, ...iterDims] = this.dims;
99-
100- if (iterDims.length > 0) {
101- const iterSize = iterDims.reduce((a, b) => a * b);
102- for (let i = 0; i < iterLength; ++i) {
103- yield this._subarray(i, iterSize, iterDims);
104- }
105- } else {
106- yield* this.data
107- }
108-
109- }
110-
111- /**
112- * Index into a Tensor object.
113- * @param {number} index The index to access.
114- * @returns {Tensor} The data at the specified index.
115- */
116- _getitem(index) {
117- const [iterLength, ...iterDims] = this.dims;
118-
119- index = safeIndex(index, iterLength);
120-
121- if (iterDims.length > 0) {
122- const iterSize = iterDims.reduce((a, b) => a * b);
123- return this._subarray(index, iterSize, iterDims);
124- } else {
125- return new Tensor(this.type, [this.data[index]], iterDims);
126- }
127- }
128-
129- /**
130- * @param {number|bigint} item The item to search for in the tensor
131- * @returns {number} The index of the first occurrence of item in the tensor data.
132- */
133- indexOf(item) {
134- for (let index = 0; index < this.data.length; ++index) {
135- // Note: == instead of === so we can match Ints with BigInts
136- if (this.data[index] == item) {
137- return index;
138- }
139- }
140- return -1;
141- }
142-
143- /**
144- * @param {number} index
145- * @param {number} iterSize
146- * @param {any} iterDims
147- * @returns {Tensor}
148- */
149- _subarray(index, iterSize, iterDims) {
150- const o1 = index * iterSize;
151- const o2 = (index + 1) * iterSize;
152-
153- // We use subarray if available (typed array), otherwise we use slice (normal array)
154- const data =
155- ('subarray' in this.data)
156- ? this.data.subarray(o1, o2)
157- : this.data.slice(o1, o2);
158- return new Tensor(this.type, data, iterDims);
159- }
160-
161- /**
162- * Returns the value of this tensor as a standard JavaScript Number. This only works
163- * for tensors with one element. For other cases, see `Tensor.tolist()`.
164- * @returns {number|bigint} The value of this tensor as a standard JavaScript Number.
165- * @throws {Error} If the tensor has more than one element.
166- */
167- item() {
168- if (this.data.length !== 1) {
169- throw new Error(`a Tensor with ${this.data.length} elements cannot be converted to Scalar`);
170- }
171- return this.data[0];
172- }
173-
174- /**
175- * Convert tensor data to a n-dimensional JS list
176- * @returns {Array}
177- */
178- tolist() {
179- return reshape(this.data, this.dims)
180- }
181-
182- /**
183- * Return a new Tensor with the sigmoid function applied to each element.
184- * @returns {Tensor} The tensor with the sigmoid function applied.
185- */
186- sigmoid() {
187- return this.clone().sigmoid_();
188- }
189-
190- /**
191- * Applies the sigmoid function to the tensor in place.
192- * @returns {Tensor} Returns `this`.
193- */
194- sigmoid_() {
195- for (let i = 0; i < this.data.length; ++i) {
196- this.data[i] = 1 / (1 + Math.exp(-this.data[i]));
197- }
198- return this;
199- }
200-
201- /**
202- * Return a new Tensor with every element multiplied by a constant.
203- * @param {number} val The value to multiply by.
204- * @returns {Tensor} The new tensor.
205- */
206- mul(val) {
207- return this.clone().mul_(val);
208- }
209-
210- /**
211- * Multiply the tensor by a constant in place.
212- * @param {number} val The value to multiply by.
213- * @returns {Tensor} Returns `this`.
214- */
215- mul_(val) {
216- for (let i = 0; i < this.data.length; ++i) {
217- this.data[i] *= val;
218- }
219- return this;
220- }
221-
222-
223- /**
224- * Return a new Tensor with every element added by a constant.
225- * @param {number} val The value to add by.
226- * @returns {Tensor} The new tensor.
227- */
228- add(val) {
229- return this.clone().add_(val);
230- }
231-
232- /**
233- * Add the tensor by a constant in place.
234- * @param {number} val The value to add by.
235- * @returns {Tensor} Returns `this`.
236- */
237- add_(val) {
238- for (let i = 0; i < this.data.length; ++i) {
239- this.data[i] += val;
240- }
241- return this;
242- }
243- clone() {
244- return new Tensor(this.type, this.data.slice(), this.dims.slice());
245- }
246-
247- slice(...slices) {
248- // This allows for slicing with ranges and numbers
249- let newTensorDims = [];
250- let newOffsets = [];
251-
252- // slices is an array of numbers or arrays of numbers
253- // e.g., slices = [0, [1, 3], null, [0, 3]]
254- for (let sliceIndex = 0; sliceIndex < this.dims.length; ++sliceIndex) {
255- let slice = slices[sliceIndex];
256-
257- if (slice === null || slice === undefined) {
258- // null or undefined means take the whole dimension
259- newOffsets.push([0, this.dims[sliceIndex]]);
260- newTensorDims.push(this.dims[sliceIndex]);
261-
262- } else if (typeof slice === 'number') {
263- slice = safeIndex(slice, this.dims[sliceIndex], sliceIndex);
264-
265- // A number means take a single element
266- newOffsets.push([slice, slice + 1]);
267-
268- } else if (Array.isArray(slice) && slice.length === 2) {
269- // An array of length 2 means take a range of elements
270-
271- if (slice[0] > slice[1]) {
272- throw new Error(`Invalid slice: ${slice}`);
273- }
274-
275- let offsets = [
276- Math.max(slice[0], 0),
277- Math.min(slice[1], this.dims[sliceIndex])
278- ];
279-
280- newOffsets.push(offsets);
281- newTensorDims.push(offsets[1] - offsets[0]);
282-
283- } else {
284- throw new Error(`Invalid slice: ${slice}`);
285- }
37+ /** @type {number[]} Dimensions of the tensor. */
38+ dims;
39+
40+ /** @type {DataType} Type of the tensor. */
41+ type;
42+
43+ /** @type {DataArray} The data stored in the tensor. */
44+ data;
45+
46+ /** @type {number} The number of elements in the tensor. */
47+ size;
48+
49+ /**
50+ * Create a new Tensor or copy an existing Tensor.
51+ * @param {[DataType, DataArray, number[]]|[import('onnxruntime-common').Tensor]} args
52+ */
53+ constructor(...args) {
54+ if (args[0] instanceof ONNXTensor) {
55+ // Create shallow copy
56+ Object.assign(this, args[0]);
57+ } else {
58+ // Create new tensor
59+ Object.assign(
60+ this,
61+ new ONNXTensor(
62+ /** @type {DataType} */ (args[0]),
63+ /** @type {Exclude<import('./maths.js').AnyTypedArray, Uint8ClampedArray>} */ (
64+ args[1]
65+ ),
66+ args[2],
67+ ),
68+ );
69+ }
70+
71+ return new Proxy(this, {
72+ get: (obj, key) => {
73+ if (typeof key === "string") {
74+ let index = Number(key);
75+ if (Number.isInteger(index)) {
76+ // key is an integer (i.e., index)
77+ return obj._getitem(index);
78+ }
28679 }
287-
288- let newDims = newOffsets.map(([start, end]) => end - start);
289- let newBufferSize = newDims.reduce((a, b) => a * b);
290-
291- // Allocate memory
29280 // @ts-ignore
293- let data = new this.data.constructor(newBufferSize);
294-
295- // Precompute strides
296- const stride = this.stride();
297-
298- for (let i = 0; i < newBufferSize; ++i) {
299- let originalIndex = 0;
300- for (let j = newDims.length - 1, num = i; j >= 0; --j) {
301- const size = newDims[j];
302- originalIndex += ((num % size) + newOffsets[j][0]) * stride[j];
303- num = Math.floor(num / size);
304- }
305- data[i] = this.data[originalIndex];
306- }
307- return new Tensor(this.type, data, newTensorDims);
81+ return obj[key];
82+ },
83+ set: (obj, key, value) => {
84+ // TODO allow setting of data
30885
309- }
310-
311- /**
312- * Return a transposed version of this Tensor, according to the provided dimensions.
313- * @param {...number} dims Dimensions to transpose.
314- * @returns {Tensor} The transposed tensor.
315- */
316- transpose(...dims) {
317- return transpose(this, dims);
318- }
319-
320- // TODO: rename transpose to permute
321- // TODO: implement transpose
322-
323- // TODO add .max() and .min() methods
324-
325- /**
326- * Returns the sum of each row of the input tensor in the given dimension dim.
327- *
328- * @param {number} [dim=null] The dimension or dimensions to reduce. If `null`, all dimensions are reduced.
329- * @param {boolean} keepdim Whether the output tensor has `dim` retained or not.
330- * @returns The summed tensor
331- */
332- sum(dim = null, keepdim = false) {
333- return this.norm(1, dim, keepdim);
334- }
335-
336- /**
337- * Returns the matrix norm or vector norm of a given tensor.
338- * @param {number|string} [p='fro'] The order of norm
339- * @param {number} [dim=null] Specifies which dimension of the tensor to calculate the norm across.
340- * If dim is None, the norm will be calculated across all dimensions of input.
341- * @param {boolean} [keepdim=false] Whether the output tensors have dim retained or not.
342- * @returns {Tensor} The norm of the tensor.
343- */
344- norm(p = 'fro', dim = null, keepdim = false) {
345- if (p === 'fro') {
346- // NOTE: Since we only support integer dims, Frobenius norm produces the same result as p=2.
347- p = 2;
348- } else if (typeof p === 'string') {
349- throw Error(`Unsupported norm: ${p}`);
350- }
351-
352- if (dim === null) {
353- // @ts-ignore
354- let val = this.data.reduce((a, b) => a + (b ** p), 0) ** (1 / p);
355- return new Tensor(this.type, [val], []);
356- }
357-
358- // Negative indexing
359- dim = safeIndex(dim, this.dims.length);
360-
361- // Calculate the shape of the resulting array after summation
362- const resultDims = this.dims.slice(); // Copy the original dimensions
363- resultDims[dim] = 1; // Remove the specified axis
364-
365- // Create a new array to store the accumulated values
36686 // @ts-ignore
367- const result = new this.data.constructor(this.data.length / this.dims[dim]);
368-
369- // Iterate over the data array
370- for (let i = 0; i < this.data.length; ++i) {
371-
372- // Calculate the index in the resulting array
373- let resultIndex = 0;
374-
375- for (let j = this.dims.length - 1, num = i, resultMultiplier = 1; j >= 0; --j) {
376- const size = this.dims[j];
377- if (j !== dim) {
378- const index = num % size;
379- resultIndex += index * resultMultiplier;
380- resultMultiplier *= resultDims[j];
381- }
382- num = Math.floor(num / size);
383- }
384-
385- // Accumulate the value at the current index
386- result[resultIndex] += (this.data[i]) ** p;
387- }
388-
389- if (p !== 1) {
390- for (let i = 0; i < result.length; ++i) {
391- result[i] = result[i] ** (1 / p);
392- }
393- }
394-
395- if (!keepdim) {
396- resultDims.splice(dim, 1);
397- }
398-
399- return new Tensor(this.type, result, resultDims);
400- }
401-
402- /**
403- * Performs `L_p` normalization of inputs over specified dimension. Operates in place.
404- * @param {number} [p=2] The exponent value in the norm formulation
405- * @param {number} [dim=1] The dimension to reduce
406- * @returns {Tensor} `this` for operation chaining.
407- */
408- normalize_(p = 2.0, dim = 1) {
409- dim = safeIndex(dim, this.dims.length);
410-
411- const norm = this.norm(p, dim, true);
412-
413- for (let i = 0; i < this.data.length; ++i) {
414-
415- // Calculate the index in the resulting array
416- let resultIndex = 0;
417-
418- for (let j = this.dims.length - 1, num = i, resultMultiplier = 1; j >= 0; --j) {
419- const size = this.dims[j];
420- if (j !== dim) {
421- const index = num % size;
422- resultIndex += index * resultMultiplier;
423- resultMultiplier *= this.dims[j];
424- }
425- num = Math.floor(num / size);
426- }
427-
428- // Divide by normalized value
429- this.data[i] /= norm.data[resultIndex];
87+ return (obj[key] = value);
88+ },
89+ });
90+ }
91+
92+ /**
93+ * Returns an iterator object for iterating over the tensor data in row-major order.
94+ * If the tensor has more than one dimension, the iterator will yield subarrays.
95+ * @returns {Iterator} An iterator object for iterating over the tensor data in row-major order.
96+ */
97+ *[Symbol.iterator]() {
98+ const [iterLength, ...iterDims] = this.dims;
99+
100+ if (iterDims.length > 0) {
101+ const iterSize = iterDims.reduce((a, b) => a * b);
102+ for (let i = 0; i < iterLength; ++i) {
103+ yield this._subarray(i, iterSize, iterDims);
104+ }
105+ } else {
106+ yield* this.data;
107+ }
108+ }
109+
110+ /**
111+ * Index into a Tensor object.
112+ * @param {number} index The index to access.
113+ * @returns {Tensor} The data at the specified index.
114+ */
115+ _getitem(index) {
116+ const [iterLength, ...iterDims] = this.dims;
117+
118+ index = safeIndex(index, iterLength);
119+
120+ if (iterDims.length > 0) {
121+ const iterSize = iterDims.reduce((a, b) => a * b);
122+ return this._subarray(index, iterSize, iterDims);
123+ } else {
124+ return new Tensor(this.type, [this.data[index]], iterDims);
125+ }
126+ }
127+
128+ /**
129+ * @param {number|bigint} item The item to search for in the tensor
130+ * @returns {number} The index of the first occurrence of item in the tensor data.
131+ */
132+ indexOf(item) {
133+ for (let index = 0; index < this.data.length; ++index) {
134+ // Note: == instead of === so we can match Ints with BigInts
135+ if (this.data[index] == item) {
136+ return index;
137+ }
138+ }
139+ return -1;
140+ }
141+
142+ /**
143+ * @param {number} index
144+ * @param {number} iterSize
145+ * @param {any} iterDims
146+ * @returns {Tensor}
147+ */
148+ _subarray(index, iterSize, iterDims) {
149+ const o1 = index * iterSize;
150+ const o2 = (index + 1) * iterSize;
151+
152+ // We use subarray if available (typed array), otherwise we use slice (normal array)
153+ const data =
154+ "subarray" in this.data
155+ ? this.data.subarray(o1, o2)
156+ : this.data.slice(o1, o2);
157+ return new Tensor(this.type, data, iterDims);
158+ }
159+
160+ /**
161+ * Returns the value of this tensor as a standard JavaScript Number. This only works
162+ * for tensors with one element. For other cases, see `Tensor.tolist()`.
163+ * @returns {number|bigint} The value of this tensor as a standard JavaScript Number.
164+ * @throws {Error} If the tensor has more than one element.
165+ */
166+ item() {
167+ if (this.data.length !== 1) {
168+ throw new Error(
169+ `a Tensor with ${this.data.length} elements cannot be converted to Scalar`,
170+ );
171+ }
172+ return this.data[0];
173+ }
174+
175+ /**
176+ * Convert tensor data to a n-dimensional JS list
177+ * @returns {Array}
178+ */
179+ tolist() {
180+ return reshape(this.data, this.dims);
181+ }
182+
183+ /**
184+ * Return a new Tensor with the sigmoid function applied to each element.
185+ * @returns {Tensor} The tensor with the sigmoid function applied.
186+ */
187+ sigmoid() {
188+ return this.clone().sigmoid_();
189+ }
190+
191+ /**
192+ * Applies the sigmoid function to the tensor in place.
193+ * @returns {Tensor} Returns `this`.
194+ */
195+ sigmoid_() {
196+ for (let i = 0; i < this.data.length; ++i) {
197+ this.data[i] = 1 / (1 + Math.exp(-this.data[i]));
198+ }
199+ return this;
200+ }
201+
202+ /**
203+ * Return a new Tensor with every element multiplied by a constant.
204+ * @param {number} val The value to multiply by.
205+ * @returns {Tensor} The new tensor.
206+ */
207+ mul(val) {
208+ return this.clone().mul_(val);
209+ }
210+
211+ /**
212+ * Multiply the tensor by a constant in place.
213+ * @param {number} val The value to multiply by.
214+ * @returns {Tensor} Returns `this`.
215+ */
216+ mul_(val) {
217+ for (let i = 0; i < this.data.length; ++i) {
218+ this.data[i] *= val;
219+ }
220+ return this;
221+ }
222+
223+ /**
224+ * Return a new Tensor with every element added by a constant.
225+ * @param {number} val The value to add by.
226+ * @returns {Tensor} The new tensor.
227+ */
228+ add(val) {
229+ return this.clone().add_(val);
230+ }
231+
232+ /**
233+ * Add the tensor by a constant in place.
234+ * @param {number} val The value to add by.
235+ * @returns {Tensor} Returns `this`.
236+ */
237+ add_(val) {
238+ for (let i = 0; i < this.data.length; ++i) {
239+ this.data[i] += val;
240+ }
241+ return this;
242+ }
243+ clone() {
244+ return new Tensor(this.type, this.data.slice(), this.dims.slice());
245+ }
246+
247+ slice(...slices) {
248+ // This allows for slicing with ranges and numbers
249+ let newTensorDims = [];
250+ let newOffsets = [];
251+
252+ // slices is an array of numbers or arrays of numbers
253+ // e.g., slices = [0, [1, 3], null, [0, 3]]
254+ for (let sliceIndex = 0; sliceIndex < this.dims.length; ++sliceIndex) {
255+ let slice = slices[sliceIndex];
256+
257+ if (slice === null || slice === undefined) {
258+ // null or undefined means take the whole dimension
259+ newOffsets.push([0, this.dims[sliceIndex]]);
260+ newTensorDims.push(this.dims[sliceIndex]);
261+ } else if (typeof slice === "number") {
262+ slice = safeIndex(slice, this.dims[sliceIndex], sliceIndex);
263+
264+ // A number means take a single element
265+ newOffsets.push([slice, slice + 1]);
266+ } else if (Array.isArray(slice) && slice.length === 2) {
267+ // An array of length 2 means take a range of elements
268+
269+ if (slice[0] > slice[1]) {
270+ throw new Error(`Invalid slice: ${slice}`);
430271 }
431272
432- return this;
433- }
434-
435- /**
436- * Performs `L_p` normalization of inputs over specified dimension.
437- * @param {number} [p=2] The exponent value in the norm formulation
438- * @param {number} [dim=1] The dimension to reduce
439- * @returns {Tensor} The normalized tensor.
440- */
441- normalize(p = 2.0, dim = 1) {
442- return this.clone().normalize_(p, dim);
443- }
444-
445- /**
446- * Compute and return the stride of this tensor.
447- * Stride is the jump necessary to go from one element to the next one in the specified dimension dim.
448- * @returns {number[]} The stride of this tensor.
449- */
450- stride() {
451- return dimsToStride(this.dims);
452- }
453-
454- /**
455- * Returns a tensor with all specified dimensions of input of size 1 removed.
456- *
457- * NOTE: The returned tensor shares the storage with the input tensor, so changing the contents of one will change the contents of the other.
458- * If you would like a copy, use `tensor.clone()` before squeezing.
459- *
460- * @param {number} [dim=null] If given, the input will be squeezed only in the specified dimensions.
461- * @returns The squeezed tensor
462- */
463- squeeze(dim = null) {
464- return new Tensor(
465- this.type,
466- this.data,
467- calc_squeeze_dims(this.dims, dim)
468- )
469- }
273+ let offsets = [
274+ Math.max(slice[0], 0),
275+ Math.min(slice[1], this.dims[sliceIndex]),
276+ ];
470277
471- /**
472- * In-place version of @see {@link Tensor.squeeze}
473- */
474- squeeze_(dim = null) {
475- this.dims = calc_squeeze_dims(this.dims, dim);
476- return this;
278+ newOffsets.push(offsets);
279+ newTensorDims.push(offsets[1] - offsets[0]);
280+ } else {
281+ throw new Error(`Invalid slice: ${slice}`);
282+ }
477283 }
478284
479- /**
480- * Returns a new tensor with a dimension of size one inserted at the specified position.
481- *
482- * NOTE: The returned tensor shares the same underlying data with this tensor.
483- *
484- * @param {number} dim The index at which to insert the singleton dimension
485- * @returns The unsqueezed tensor
486- */
487- unsqueeze(dim = null) {
488- return new Tensor(
489- this.type,
490- this.data,
491- calc_unsqueeze_dims(this.dims, dim)
492- );
493- }
285+ let newDims = newOffsets.map(([start, end]) => end - start);
286+ let newBufferSize = newDims.reduce((a, b) => a * b);
494287
495- /**
496- * In-place version of @see {@link Tensor.unsqueeze}
497- */
498- unsqueeze_(dim = null) {
499- this.dims = calc_unsqueeze_dims(this.dims, dim);
500- return this;
288+ // Allocate memory
289+ // @ts-ignore
290+ let data = new this.data.constructor(newBufferSize);
291+
292+ // Precompute strides
293+ const stride = this.stride();
294+
295+ for (let i = 0; i < newBufferSize; ++i) {
296+ let originalIndex = 0;
297+ for (let j = newDims.length - 1, num = i; j >= 0; --j) {
298+ const size = newDims[j];
299+ originalIndex += ((num % size) + newOffsets[j][0]) * stride[j];
300+ num = Math.floor(num / size);
301+ }
302+ data[i] = this.data[originalIndex];
303+ }
304+ return new Tensor(this.type, data, newTensorDims);
305+ }
306+
307+ /**
308+ * Return a transposed version of this Tensor, according to the provided dimensions.
309+ * @param {...number} dims Dimensions to transpose.
310+ * @returns {Tensor} The transposed tensor.
311+ */
312+ transpose(...dims) {
313+ return transpose(this, dims);
314+ }
315+
316+ // TODO: rename transpose to permute
317+ // TODO: implement transpose
318+
319+ // TODO add .max() and .min() methods
320+
321+ /**
322+ * Returns the sum of each row of the input tensor in the given dimension dim.
323+ *
324+ * @param {number} [dim=null] The dimension or dimensions to reduce. If `null`, all dimensions are reduced.
325+ * @param {boolean} keepdim Whether the output tensor has `dim` retained or not.
326+ * @returns The summed tensor
327+ */
328+ sum(dim = null, keepdim = false) {
329+ return this.norm(1, dim, keepdim);
330+ }
331+
332+ /**
333+ * Returns the matrix norm or vector norm of a given tensor.
334+ * @param {number|string} [p='fro'] The order of norm
335+ * @param {number} [dim=null] Specifies which dimension of the tensor to calculate the norm across.
336+ * If dim is None, the norm will be calculated across all dimensions of input.
337+ * @param {boolean} [keepdim=false] Whether the output tensors have dim retained or not.
338+ * @returns {Tensor} The norm of the tensor.
339+ */
340+ norm(p = "fro", dim = null, keepdim = false) {
341+ if (p === "fro") {
342+ // NOTE: Since we only support integer dims, Frobenius norm produces the same result as p=2.
343+ p = 2;
344+ } else if (typeof p === "string") {
345+ throw Error(`Unsupported norm: ${p}`);
501346 }
502347
503- /**
504- * In-place version of @see {@link Tensor.flatten}
505- */
506- flatten_(start_dim = 0, end_dim = -1) {
507- // TODO validate inputs
508- end_dim = (end_dim + this.dims.length) % this.dims.length;
509-
510- let dimsToKeepBefore = this.dims.slice(0, start_dim);
511- let dimsToFlatten = this.dims.slice(start_dim, end_dim + 1);
512- let dimsToKeepAfter = this.dims.slice(end_dim + 1);
513-
514- this.dims = [...dimsToKeepBefore, dimsToFlatten.reduce((a, b) => a * b, 1), ...dimsToKeepAfter]
515- return this;
348+ if (dim === null) {
349+ // @ts-ignore
350+ let val = this.data.reduce((a, b) => a + b ** p, 0) ** (1 / p);
351+ return new Tensor(this.type, [val], []);
516352 }
517353
518- /**
519- * Flattens input by reshaping it into a one-dimensional tensor.
520- * If `start_dim` or `end_dim` are passed, only dimensions starting with `start_dim`
521- * and ending with `end_dim` are flattened. The order of elements in input is unchanged.
522- * @param {number} start_dim the first dim to flatten
523- * @param {number} end_dim the last dim to flatten
524- * @returns The flattened tensor.
525- */
526- flatten(start_dim = 0, end_dim = -1) {
527- return this.clone().flatten_(start_dim, end_dim);
528- }
354+ // Negative indexing
355+ dim = safeIndex(dim, this.dims.length);
529356
530- /**
531- * Returns a new tensor with the same data as the `self` tensor but of a different `shape`.
532- * @param {...number} dims the desired size
533- * @returns {Tensor} The tensor with the same data but different shape
534- */
535- view(...dims) {
536- // TODO: validate dims
537- let inferredIndex = -1;
538- for (let i = 0; i < dims.length; ++i) {
539- if (dims[i] === -1) {
540- if (inferredIndex !== -1) {
541- throw new Error("Only one dimension can be inferred");
542- }
543- inferredIndex = i;
544- }
545- }
357+ // Calculate the shape of the resulting array after summation
358+ const resultDims = this.dims.slice(); // Copy the original dimensions
359+ resultDims[dim] = 1; // Remove the specified axis
546360
547- if (inferredIndex !== -1) {
548- // Some dimension must be inferred
549- const productOther = dims.reduce((product, curr, index) => {
550- return index !== inferredIndex ? product * curr : product
551- }, 1);
552-
553- dims[inferredIndex] = this.data.length / productOther;
554- }
555- return new Tensor(this.type, this.data, dims); // NOTE: uses same underlying storage
556- }
361+ // Create a new array to store the accumulated values
362+ // @ts-ignore
363+ const result = new this.data.constructor(this.data.length / this.dims[dim]);
557364
558- neg_() {
559- for (let i = 0; i < this.data.length; ++i) {
560- this.data[i] = -this.data[i];
365+ // Iterate over the data array
366+ for (let i = 0; i < this.data.length; ++i) {
367+ // Calculate the index in the resulting array
368+ let resultIndex = 0;
369+
370+ for (
371+ let j = this.dims.length - 1, num = i, resultMultiplier = 1;
372+ j >= 0;
373+ --j
374+ ) {
375+ const size = this.dims[j];
376+ if (j !== dim) {
377+ const index = num % size;
378+ resultIndex += index * resultMultiplier;
379+ resultMultiplier *= resultDims[j];
561380 }
562- return this;
563- }
564- neg() {
565- return this.clone().neg_();
566- }
381+ num = Math.floor(num / size);
382+ }
567383
568- /**
569- * In-place version of @see {@link Tensor.clamp}
570- */
571- clamp_(min, max) {
572- for (let i = 0; i < this.data.length; ++i) {
573- this.data[i] = Math.min(Math.max(this.data[i], min), max);
574- }
575- return this;
384+ // Accumulate the value at the current index
385+ result[resultIndex] += this.data[i] ** p;
576386 }
577387
578- /**
579- * Clamps all elements in input into the range [ min, max ]
580- * @param {number} min lower-bound of the range to be clamped to
581- * @param {number} max upper-bound of the range to be clamped to
582- * @returns the output tensor.
583- */
584- clamp(min, max) {
585- return this.clone().clamp_(min, max);
388+ if (p !== 1) {
389+ for (let i = 0; i < result.length; ++i) {
390+ result[i] = result[i] ** (1 / p);
391+ }
586392 }
587393
588- /**
589- * In-place version of @see {@link Tensor.round}
590- */
591- round_() {
592- for (let i = 0; i < this.data.length; ++i) {
593- this.data[i] = Math.round(this.data[i]);
394+ if (!keepdim) {
395+ resultDims.splice(dim, 1);
396+ }
397+
398+ return new Tensor(this.type, result, resultDims);
399+ }
400+
401+ /**
402+ * Performs `L_p` normalization of inputs over specified dimension. Operates in place.
403+ * @param {number} [p=2] The exponent value in the norm formulation
404+ * @param {number} [dim=1] The dimension to reduce
405+ * @returns {Tensor} `this` for operation chaining.
406+ */
407+ normalize_(p = 2.0, dim = 1) {
408+ dim = safeIndex(dim, this.dims.length);
409+
410+ const norm = this.norm(p, dim, true);
411+
412+ for (let i = 0; i < this.data.length; ++i) {
413+ // Calculate the index in the resulting array
414+ let resultIndex = 0;
415+
416+ for (
417+ let j = this.dims.length - 1, num = i, resultMultiplier = 1;
418+ j >= 0;
419+ --j
420+ ) {
421+ const size = this.dims[j];
422+ if (j !== dim) {
423+ const index = num % size;
424+ resultIndex += index * resultMultiplier;
425+ resultMultiplier *= this.dims[j];
594426 }
595- return this;
596- }
597-
598- /**
599- * Rounds elements of input to the nearest integer.
600- * @returns the output tensor.
601- */
602- round() {
603- return this.clone().round_();
604- }
605-
606- /**
607- * Performs Tensor dtype conversion.
608- * @param {DataType} type The desired data type.
609- * @returns {Tensor} The converted tensor.
610- */
611- to(type) {
612- // If the self Tensor already has the correct dtype, then self is returned.
613- if (this.type === type) return this;
614-
615- // Otherwise, the returned tensor is a copy of self with the desired dtype.
616- if (!DataTypeMap.hasOwnProperty(type)) {
617- throw new Error(`Unsupported type: ${type}`);
427+ num = Math.floor(num / size);
428+ }
429+
430+ // Divide by normalized value
431+ this.data[i] /= norm.data[resultIndex];
432+ }
433+
434+ return this;
435+ }
436+
437+ /**
438+ * Performs `L_p` normalization of inputs over specified dimension.
439+ * @param {number} [p=2] The exponent value in the norm formulation
440+ * @param {number} [dim=1] The dimension to reduce
441+ * @returns {Tensor} The normalized tensor.
442+ */
443+ normalize(p = 2.0, dim = 1) {
444+ return this.clone().normalize_(p, dim);
445+ }
446+
447+ /**
448+ * Compute and return the stride of this tensor.
449+ * Stride is the jump necessary to go from one element to the next one in the specified dimension dim.
450+ * @returns {number[]} The stride of this tensor.
451+ */
452+ stride() {
453+ return dimsToStride(this.dims);
454+ }
455+
456+ /**
457+ * Returns a tensor with all specified dimensions of input of size 1 removed.
458+ *
459+ * NOTE: The returned tensor shares the storage with the input tensor, so changing the contents of one will change the contents of the other.
460+ * If you would like a copy, use `tensor.clone()` before squeezing.
461+ *
462+ * @param {number} [dim=null] If given, the input will be squeezed only in the specified dimensions.
463+ * @returns The squeezed tensor
464+ */
465+ squeeze(dim = null) {
466+ return new Tensor(this.type, this.data, calc_squeeze_dims(this.dims, dim));
467+ }
468+
469+ /**
470+ * In-place version of @see {@link Tensor.squeeze}
471+ */
472+ squeeze_(dim = null) {
473+ this.dims = calc_squeeze_dims(this.dims, dim);
474+ return this;
475+ }
476+
477+ /**
478+ * Returns a new tensor with a dimension of size one inserted at the specified position.
479+ *
480+ * NOTE: The returned tensor shares the same underlying data with this tensor.
481+ *
482+ * @param {number} dim The index at which to insert the singleton dimension
483+ * @returns The unsqueezed tensor
484+ */
485+ unsqueeze(dim = null) {
486+ return new Tensor(
487+ this.type,
488+ this.data,
489+ calc_unsqueeze_dims(this.dims, dim),
490+ );
491+ }
492+
493+ /**
494+ * In-place version of @see {@link Tensor.unsqueeze}
495+ */
496+ unsqueeze_(dim = null) {
497+ this.dims = calc_unsqueeze_dims(this.dims, dim);
498+ return this;
499+ }
500+
501+ /**
502+ * In-place version of @see {@link Tensor.flatten}
503+ */
504+ flatten_(start_dim = 0, end_dim = -1) {
505+ // TODO validate inputs
506+ end_dim = (end_dim + this.dims.length) % this.dims.length;
507+
508+ let dimsToKeepBefore = this.dims.slice(0, start_dim);
509+ let dimsToFlatten = this.dims.slice(start_dim, end_dim + 1);
510+ let dimsToKeepAfter = this.dims.slice(end_dim + 1);
511+
512+ this.dims = [
513+ ...dimsToKeepBefore,
514+ dimsToFlatten.reduce((a, b) => a * b, 1),
515+ ...dimsToKeepAfter,
516+ ];
517+ return this;
518+ }
519+
520+ /**
521+ * Flattens input by reshaping it into a one-dimensional tensor.
522+ * If `start_dim` or `end_dim` are passed, only dimensions starting with `start_dim`
523+ * and ending with `end_dim` are flattened. The order of elements in input is unchanged.
524+ * @param {number} start_dim the first dim to flatten
525+ * @param {number} end_dim the last dim to flatten
526+ * @returns The flattened tensor.
527+ */
528+ flatten(start_dim = 0, end_dim = -1) {
529+ return this.clone().flatten_(start_dim, end_dim);
530+ }
531+
532+ /**
533+ * Returns a new tensor with the same data as the `self` tensor but of a different `shape`.
534+ * @param {...number} dims the desired size
535+ * @returns {Tensor} The tensor with the same data but different shape
536+ */
537+ view(...dims) {
538+ // TODO: validate dims
539+ let inferredIndex = -1;
540+ for (let i = 0; i < dims.length; ++i) {
541+ if (dims[i] === -1) {
542+ if (inferredIndex !== -1) {
543+ throw new Error("Only one dimension can be inferred");
618544 }
619- // @ts-ignore
620- return new Tensor(type, DataTypeMap[type].from(this.data), this.dims);
545+ inferredIndex = i;
546+ }
547+ }
548+
549+ if (inferredIndex !== -1) {
550+ // Some dimension must be inferred
551+ const productOther = dims.reduce((product, curr, index) => {
552+ return index !== inferredIndex ? product * curr : product;
553+ }, 1);
554+
555+ dims[inferredIndex] = this.data.length / productOther;
556+ }
557+ return new Tensor(this.type, this.data, dims); // NOTE: uses same underlying storage
558+ }
559+
560+ neg_() {
561+ for (let i = 0; i < this.data.length; ++i) {
562+ this.data[i] = -this.data[i];
563+ }
564+ return this;
565+ }
566+ neg() {
567+ return this.clone().neg_();
568+ }
569+
570+ /**
571+ * In-place version of @see {@link Tensor.clamp}
572+ */
573+ clamp_(min, max) {
574+ for (let i = 0; i < this.data.length; ++i) {
575+ this.data[i] = Math.min(Math.max(this.data[i], min), max);
576+ }
577+ return this;
578+ }
579+
580+ /**
581+ * Clamps all elements in input into the range [ min, max ]
582+ * @param {number} min lower-bound of the range to be clamped to
583+ * @param {number} max upper-bound of the range to be clamped to
584+ * @returns the output tensor.
585+ */
586+ clamp(min, max) {
587+ return this.clone().clamp_(min, max);
588+ }
589+
590+ /**
591+ * In-place version of @see {@link Tensor.round}
592+ */
593+ round_() {
594+ for (let i = 0; i < this.data.length; ++i) {
595+ this.data[i] = Math.round(this.data[i]);
596+ }
597+ return this;
598+ }
599+
600+ /**
601+ * Rounds elements of input to the nearest integer.
602+ * @returns the output tensor.
603+ */
604+ round() {
605+ return this.clone().round_();
606+ }
607+
608+ /**
609+ * Performs Tensor dtype conversion.
610+ * @param {DataType} type The desired data type.
611+ * @returns {Tensor} The converted tensor.
612+ */
613+ to(type) {
614+ // If the self Tensor already has the correct dtype, then self is returned.
615+ if (this.type === type) return this;
616+
617+ // Otherwise, the returned tensor is a copy of self with the desired dtype.
618+ if (!DataTypeMap.hasOwnProperty(type)) {
619+ throw new Error(`Unsupported type: ${type}`);
621620 }
621+ // @ts-ignore
622+ return new Tensor(type, DataTypeMap[type].from(this.data), this.dims);
623+ }
622624 }
623625
624626 /**
625627 * This creates a nested array of a given type and depth (see examples).
626- *
628+ *
627629 * @example
628630 * NestArray<string, 1>; // string[]
629631 * @example
@@ -651,32 +653,36 @@
651653 * @returns {NestArray<T, DIM["length"]>} The reshaped array.
652654 */
653655 function reshape(data, dimensions) {
656+ const totalElements = data.length;
657+ const dimensionSize = dimensions.reduce((a, b) => a * b);
658+
659+ if (totalElements !== dimensionSize) {
660+ throw Error(
661+ `cannot reshape array of size ${totalElements} into shape (${dimensions})`,
662+ );
663+ }
654664
655- const totalElements = data.length;
656- const dimensionSize = dimensions.reduce((a, b) => a * b);
657-
658- if (totalElements !== dimensionSize) {
659- throw Error(`cannot reshape array of size ${totalElements} into shape (${dimensions})`);
660- }
661-
662- /** @type {any} */
663- let reshapedArray = data;
665+ /** @type {any} */
666+ let reshapedArray = data;
664667
665- for (let i = dimensions.length - 1; i >= 0; i--) {
666- reshapedArray = reshapedArray.reduce((acc, val) => {
667- let lastArray = acc[acc.length - 1];
668+ for (let i = dimensions.length - 1; i >= 0; i--) {
669+ reshapedArray = reshapedArray.reduce(
670+ (acc, val) => {
671+ let lastArray = acc[acc.length - 1];
668672
669- if (lastArray.length < dimensions[i]) {
670- lastArray.push(val);
671- } else {
672- acc.push([val]);
673- }
673+ if (lastArray.length < dimensions[i]) {
674+ lastArray.push(val);
675+ } else {
676+ acc.push([val]);
677+ }
674678
675- return acc;
676- }, [[]]);
677- }
679+ return acc;
680+ },
681+ [[]],
682+ );
683+ }
678684
679- return reshapedArray[0];
685+ return reshapedArray[0];
680686 }
681687
682688 /**
@@ -686,11 +692,14 @@
686692 * @returns {Tensor} The transposed tensor.
687693 */
688694 export function transpose(tensor, axes) {
689- const [transposedData, shape] = transpose_data(tensor.data, tensor.dims, axes);
690- return new Tensor(tensor.type, transposedData, shape);
695+ const [transposedData, shape] = transpose_data(
696+ tensor.data,
697+ tensor.dims,
698+ axes,
699+ );
700+ return new Tensor(tensor.type, transposedData, shape);
691701 }
692702
693-
694703 /**
695704 * Interpolates an Tensor to the given size.
696705 * @param {Tensor} input The input tensor to interpolate. Data must be channel-first (i.e., [c, h, w])
@@ -699,21 +708,25 @@
699708 * @param {boolean} align_corners Whether to align corners.
700709 * @returns {Tensor} The interpolated tensor.
701710 */
702-export function interpolate(input, [out_height, out_width], mode = 'bilinear', align_corners = false) {
703-
704- // Input image dimensions
705- const in_channels = input.dims.at(-3) ?? 1;
706- const in_height = input.dims.at(-2);
707- const in_width = input.dims.at(-1);
708-
709- let output = interpolate_data(
710- /** @type {import('./maths.js').TypedArray}*/(input.data),
711- [in_channels, in_height, in_width],
712- [out_height, out_width],
713- mode,
714- align_corners
715- );
716- return new Tensor(input.type, output, [in_channels, out_height, out_width]);
711+export function interpolate(
712+ input,
713+ [out_height, out_width],
714+ mode = "bilinear",
715+ align_corners = false,
716+) {
717+ // Input image dimensions
718+ const in_channels = input.dims.at(-3) ?? 1;
719+ const in_height = input.dims.at(-2);
720+ const in_width = input.dims.at(-1);
721+
722+ let output = interpolate_data(
723+ /** @type {import('./maths.js').TypedArray}*/ (input.data),
724+ [in_channels, in_height, in_width],
725+ [out_height, out_width],
726+ mode,
727+ align_corners,
728+ );
729+ return new Tensor(input.type, output, [in_channels, out_height, out_width]);
717730 }
718731
719732 /**
@@ -723,43 +736,41 @@
723736 * @returns {Tensor} Returns a new Tensor of shape [batchSize, embedDim].
724737 */
725738 export function mean_pooling(last_hidden_state, attention_mask) {
726- // last_hidden_state: [batchSize, seqLength, embedDim]
727- // attention_mask: [batchSize, seqLength]
728-
729- let shape = [last_hidden_state.dims[0], last_hidden_state.dims[2]];
730- // @ts-ignore
731- let returnedData = new last_hidden_state.data.constructor(shape[0] * shape[1]);
732- let [batchSize, seqLength, embedDim] = last_hidden_state.dims;
733-
734- let outIndex = 0;
735- for (let i = 0; i < batchSize; ++i) {
736- let offset = i * embedDim * seqLength;
737-
738- for (let k = 0; k < embedDim; ++k) {
739- let sum = 0;
740- let count = 0;
741-
742- let attnMaskOffset = i * seqLength;
743- let offset2 = offset + k;
744- // Pool over all words in sequence
745- for (let j = 0; j < seqLength; ++j) {
746- // index into attention mask
747- let attn = Number(attention_mask.data[attnMaskOffset + j]);
748-
749- count += attn;
750- sum += last_hidden_state.data[offset2 + j * embedDim] * attn;
751- }
752-
753- let avg = sum / count;
754- returnedData[outIndex++] = avg;
755- }
756- }
757-
758- return new Tensor(
759- last_hidden_state.type,
760- returnedData,
761- shape
762- )
739+ // last_hidden_state: [batchSize, seqLength, embedDim]
740+ // attention_mask: [batchSize, seqLength]
741+
742+ let shape = [last_hidden_state.dims[0], last_hidden_state.dims[2]];
743+ // @ts-ignore
744+ let returnedData = new last_hidden_state.data.constructor(
745+ shape[0] * shape[1],
746+ );
747+ let [batchSize, seqLength, embedDim] = last_hidden_state.dims;
748+
749+ let outIndex = 0;
750+ for (let i = 0; i < batchSize; ++i) {
751+ let offset = i * embedDim * seqLength;
752+
753+ for (let k = 0; k < embedDim; ++k) {
754+ let sum = 0;
755+ let count = 0;
756+
757+ let attnMaskOffset = i * seqLength;
758+ let offset2 = offset + k;
759+ // Pool over all words in sequence
760+ for (let j = 0; j < seqLength; ++j) {
761+ // index into attention mask
762+ let attn = Number(attention_mask.data[attnMaskOffset + j]);
763+
764+ count += attn;
765+ sum += last_hidden_state.data[offset2 + j * embedDim] * attn;
766+ }
767+
768+ let avg = sum / count;
769+ returnedData[outIndex++] = avg;
770+ }
771+ }
772+
773+ return new Tensor(last_hidden_state.type, returnedData, shape);
763774 }
764775
765776 /**
@@ -770,19 +781,19 @@
770781 * @private
771782 */
772783 function calc_squeeze_dims(dims, dim) {
773- dims = dims.slice();
774- if (dim === null) {
775- dims = dims.filter((d) => d !== 1);
776- } else if (typeof dim === 'number') {
777- if (dims[dim] === 1) {
778- dims.splice(dim, 1);
779- }
780- } else if (Array.isArray(dim)) {
781- dims = dims.filter((x, i) => {
782- return x !== 1 || !dim.includes(i);
783- });
784- }
785- return dims;
784+ dims = dims.slice();
785+ if (dim === null) {
786+ dims = dims.filter((d) => d !== 1);
787+ } else if (typeof dim === "number") {
788+ if (dims[dim] === 1) {
789+ dims.splice(dim, 1);
790+ }
791+ } else if (Array.isArray(dim)) {
792+ dims = dims.filter((x, i) => {
793+ return x !== 1 || !dim.includes(i);
794+ });
795+ }
796+ return dims;
786797 }
787798
788799 /**
@@ -793,13 +804,13 @@
793804 * @private
794805 */
795806 function calc_unsqueeze_dims(dims, dim) {
796- // Dimension out of range (e.g., "expected to be in range of [-4, 3], but got 4")
797- // + 1 since we allow inserting at the end (i.e. dim = -1)
798- dim = safeIndex(dim, dims.length + 1);
799- dims = dims.slice();
800- // Insert 1 into specified dimension
801- dims.splice(dim, 0, 1);
802- return dims;
807+ // Dimension out of range (e.g., "expected to be in range of [-4, 3], but got 4")
808+ // + 1 since we allow inserting at the end (i.e. dim = -1)
809+ dim = safeIndex(dim, dims.length + 1);
810+ dims = dims.slice();
811+ // Insert 1 into specified dimension
812+ dims.splice(dim, 0, 1);
813+ return dims;
803814 }
804815
805816 /**
@@ -808,20 +819,22 @@
808819 * @param {number} size The size of the array.
809820 * @param {number} [dimension=null] The dimension that the index is for (optional).
810821 * @returns {number} The index, guaranteed to be non-negative and less than `arrayLength`.
811- *
822+ *
812823 * @throws {Error} If the index is out of range.
813824 * @private
814825 */
815826 function safeIndex(index, size, dimension = null) {
816- if (index < -size || index >= size) {
817- throw new Error(`IndexError: index ${index} is out of bounds for dimension${dimension === null ? '' : ' ' + dimension} with size ${size}`);
818- }
819-
820- if (index < 0) {
821- // Negative indexing, ensuring positive index
822- index = ((index % size) + size) % size;
823- }
824- return index;
827+ if (index < -size || index >= size) {
828+ throw new Error(
829+ `IndexError: index ${index} is out of bounds for dimension${dimension === null ? "" : " " + dimension} with size ${size}`,
830+ );
831+ }
832+
833+ if (index < 0) {
834+ // Negative indexing, ensuring positive index
835+ index = ((index % size) + size) % size;
836+ }
837+ return index;
825838 }
826839
827840 /**
@@ -831,60 +844,62 @@
831844 * @returns {Tensor} The concatenated tensor.
832845 */
833846 export function cat(tensors, dim = 0) {
834- dim = safeIndex(dim, tensors[0].dims.length);
847+ dim = safeIndex(dim, tensors[0].dims.length);
835848
836- // TODO do validation of shapes
849+ // TODO do validation of shapes
837850
838- const resultDims = tensors[0].dims.slice();
839- resultDims[dim] = tensors.reduce((a, b) => a + b.dims[dim], 0);
851+ const resultDims = tensors[0].dims.slice();
852+ resultDims[dim] = tensors.reduce((a, b) => a + b.dims[dim], 0);
840853
841- // Create a new array to store the accumulated values
842- const resultSize = resultDims.reduce((a, b) => a * b, 1);
843- // @ts-ignore
844- const result = new tensors[0].data.constructor(resultSize);
854+ // Create a new array to store the accumulated values
855+ const resultSize = resultDims.reduce((a, b) => a * b, 1);
856+ // @ts-ignore
857+ const result = new tensors[0].data.constructor(resultSize);
845858
846- // Create output tensor of same type as first
847- const resultType = tensors[0].type;
859+ // Create output tensor of same type as first
860+ const resultType = tensors[0].type;
848861
849- if (dim === 0) {
850- // Handle special case for performance reasons
862+ if (dim === 0) {
863+ // Handle special case for performance reasons
851864
852- let offset = 0;
853- for (let t of tensors) {
854- result.set(t.data, offset);
855- offset += t.data.length;
856- }
865+ let offset = 0;
866+ for (let t of tensors) {
867+ result.set(t.data, offset);
868+ offset += t.data.length;
869+ }
870+ } else {
871+ let currentDim = 0;
857872
858- } else {
873+ for (let t = 0; t < tensors.length; ++t) {
874+ let tensor = tensors[t];
859875
860- let currentDim = 0;
861-
862- for (let t = 0; t < tensors.length; ++t) {
863- let tensor = tensors[t];
864-
865- // Iterate over the data array
866- for (let i = 0; i < tensor.data.length; ++i) {
867- // Calculate the index in the resulting array
868- let resultIndex = 0;
869-
870- for (let j = tensor.dims.length - 1, num = i, resultMultiplier = 1; j >= 0; --j) {
871- const size = tensor.dims[j];
872- let index = num % size;
873- if (j === dim) {
874- index += currentDim;
875- }
876- resultIndex += index * resultMultiplier;
877- resultMultiplier *= resultDims[j];
878- num = Math.floor(num / size);
879- }
880- // Accumulate the value at the current index
881- result[resultIndex] = tensor.data[i];
882- }
883-
884- currentDim += tensor.dims[dim];
876+ // Iterate over the data array
877+ for (let i = 0; i < tensor.data.length; ++i) {
878+ // Calculate the index in the resulting array
879+ let resultIndex = 0;
880+
881+ for (
882+ let j = tensor.dims.length - 1, num = i, resultMultiplier = 1;
883+ j >= 0;
884+ --j
885+ ) {
886+ const size = tensor.dims[j];
887+ let index = num % size;
888+ if (j === dim) {
889+ index += currentDim;
890+ }
891+ resultIndex += index * resultMultiplier;
892+ resultMultiplier *= resultDims[j];
893+ num = Math.floor(num / size);
885894 }
895+ // Accumulate the value at the current index
896+ result[resultIndex] = tensor.data[i];
897+ }
898+
899+ currentDim += tensor.dims[dim];
886900 }
887- return new Tensor(resultType, result, resultDims);
901+ }
902+ return new Tensor(resultType, result, resultDims);
888903 }
889904
890905 /**
@@ -894,12 +909,14 @@
894909 * @returns {Tensor} The stacked tensor.
895910 */
896911 export function stack(tensors, dim = 0) {
897- // TODO do validation of shapes
898- // NOTE: stack expects each tensor to be equal size
899- return cat(tensors.map(t => t.unsqueeze(dim)), dim);
912+ // TODO do validation of shapes
913+ // NOTE: stack expects each tensor to be equal size
914+ return cat(
915+ tensors.map((t) => t.unsqueeze(dim)),
916+ dim,
917+ );
900918 }
901919
902-
903920 /**
904921 * Calculates the standard deviation and mean over the dimensions specified by dim. dim can be a single dimension or `null` to reduce over all dimensions.
905922 * @param {Tensor} input the input tenso
@@ -909,68 +926,86 @@
909926 * @returns {Tensor[]} A tuple of (std, mean) tensors.
910927 */
911928 export function std_mean(input, dim = null, correction = 1, keepdim = false) {
912-
913- if (dim === null) {
914- // None to reduce over all dimensions.
915- // @ts-ignore
916- const sum = input.data.reduce((a, b) => a + b, 0);
917- const mean = sum / input.data.length;
918- // @ts-ignore
919- const std = Math.sqrt(input.data.reduce((a, b) => a + (b - mean) ** 2, 0) / (input.data.length - correction));
920-
921- const meanTensor = new Tensor(input.type, [mean], [/* scalar */]);
922- const stdTensor = new Tensor(input.type, [std], [/* scalar */]);
923-
924- return [stdTensor, meanTensor];
925- }
926-
927- // Negative indexing
928- dim = safeIndex(dim, input.dims.length);
929-
930- const meanTensor = mean(input, dim, keepdim);
931-
932- // Calculate the shape of the resulting array after summation
933- const resultDims = input.dims.slice(); // Copy the original dimensions
934- resultDims[dim] = 1; // Remove the specified axis
935-
936- // Create a new array to store the accumulated values
929+ if (dim === null) {
930+ // None to reduce over all dimensions.
937931 // @ts-ignore
938- const result = new input.data.constructor(input.data.length / input.dims[dim]);
939-
940- // Iterate over the data array
941- for (let i = 0; i < input.data.length; ++i) {
942-
943- // Calculate the index in the resulting array
944- let resultIndex = 0;
945-
946- for (let j = input.dims.length - 1, num = i, resultMultiplier = 1; j >= 0; --j) {
947- const size = input.dims[j];
948- if (j !== dim) {
949- const index = num % size;
950- resultIndex += index * resultMultiplier;
951- resultMultiplier *= resultDims[j];
952- }
953- num = Math.floor(num / size);
954- }
955-
956- // Accumulate the value at the current index
957- result[resultIndex] += (input.data[i] - meanTensor.data[resultIndex]) ** 2;
958- }
959-
960- for (let i = 0; i < result.length; ++i) {
961- result[i] = Math.sqrt(result[i] / (input.dims[dim] - correction));
962- }
963-
964- if (!keepdim) {
965- resultDims.splice(dim, 1);
966- }
932+ const sum = input.data.reduce((a, b) => a + b, 0);
933+ const mean = sum / input.data.length;
934+ // @ts-ignore
935+ const std = Math.sqrt(
936+ input.data.reduce((a, b) => a + (b - mean) ** 2, 0) /
937+ (input.data.length - correction),
938+ );
967939
968- const stdTensor = new Tensor(input.type, result, resultDims);
940+ const meanTensor = new Tensor(
941+ input.type,
942+ [mean],
943+ [
944+ /* scalar */
945+ ],
946+ );
947+ const stdTensor = new Tensor(
948+ input.type,
949+ [std],
950+ [
951+ /* scalar */
952+ ],
953+ );
969954
970955 return [stdTensor, meanTensor];
956+ }
957+
958+ // Negative indexing
959+ dim = safeIndex(dim, input.dims.length);
960+
961+ const meanTensor = mean(input, dim, keepdim);
962+
963+ // Calculate the shape of the resulting array after summation
964+ const resultDims = input.dims.slice(); // Copy the original dimensions
965+ resultDims[dim] = 1; // Remove the specified axis
966+
967+ // Create a new array to store the accumulated values
968+ // @ts-ignore
969+ const result = new input.data.constructor(
970+ input.data.length / input.dims[dim],
971+ );
972+
973+ // Iterate over the data array
974+ for (let i = 0; i < input.data.length; ++i) {
975+ // Calculate the index in the resulting array
976+ let resultIndex = 0;
977+
978+ for (
979+ let j = input.dims.length - 1, num = i, resultMultiplier = 1;
980+ j >= 0;
981+ --j
982+ ) {
983+ const size = input.dims[j];
984+ if (j !== dim) {
985+ const index = num % size;
986+ resultIndex += index * resultMultiplier;
987+ resultMultiplier *= resultDims[j];
988+ }
989+ num = Math.floor(num / size);
990+ }
991+
992+ // Accumulate the value at the current index
993+ result[resultIndex] += (input.data[i] - meanTensor.data[resultIndex]) ** 2;
994+ }
995+
996+ for (let i = 0; i < result.length; ++i) {
997+ result[i] = Math.sqrt(result[i] / (input.dims[dim] - correction));
998+ }
999+
1000+ if (!keepdim) {
1001+ resultDims.splice(dim, 1);
1002+ }
1003+
1004+ const stdTensor = new Tensor(input.type, result, resultDims);
1005+
1006+ return [stdTensor, meanTensor];
9711007 }
9721008
973-
9741009 /**
9751010 * Returns the mean value of each row of the input tensor in the given dimension dim.
9761011 * @param {Tensor} input the input tensor.
@@ -979,159 +1014,168 @@
9791014 * @returns A new tensor with means taken along the specified dimension.
9801015 */
9811016 export function mean(input, dim = null, keepdim = false) {
982-
983- if (dim === null) {
984- // None to reduce over all dimensions.
985- // @ts-ignore
986- let val = input.data.reduce((a, b) => a + b, 0);
987- return new Tensor(input.type, [val / input.data.length], [/* scalar */]);
988- }
989-
990- // Negative indexing
991- dim = safeIndex(dim, input.dims.length);
992-
993- // Calculate the shape of the resulting array after summation
994- const resultDims = input.dims.slice(); // Copy the original dimensions
995- resultDims[dim] = 1; // Remove the specified axis
996-
997- // Create a new array to store the accumulated values
1017+ if (dim === null) {
1018+ // None to reduce over all dimensions.
9981019 // @ts-ignore
999- const result = new input.data.constructor(input.data.length / input.dims[dim]);
1000-
1001- // Iterate over the data array
1002- for (let i = 0; i < input.data.length; ++i) {
1003-
1004- // Calculate the index in the resulting array
1005- let resultIndex = 0;
1006-
1007- for (let j = input.dims.length - 1, num = i, resultMultiplier = 1; j >= 0; --j) {
1008- const size = input.dims[j];
1009- if (j !== dim) {
1010- const index = num % size;
1011- resultIndex += index * resultMultiplier;
1012- resultMultiplier *= resultDims[j];
1013- }
1014- num = Math.floor(num / size);
1015- }
1016-
1017- // Accumulate the value at the current index
1018- result[resultIndex] += input.data[i];
1019- }
1020-
1021- if (input.dims[dim] !== 1) {
1022- for (let i = 0; i < result.length; ++i) {
1023- result[i] = result[i] / input.dims[dim];
1024- }
1020+ let val = input.data.reduce((a, b) => a + b, 0);
1021+ return new Tensor(
1022+ input.type,
1023+ [val / input.data.length],
1024+ [
1025+ /* scalar */
1026+ ],
1027+ );
1028+ }
1029+
1030+ // Negative indexing
1031+ dim = safeIndex(dim, input.dims.length);
1032+
1033+ // Calculate the shape of the resulting array after summation
1034+ const resultDims = input.dims.slice(); // Copy the original dimensions
1035+ resultDims[dim] = 1; // Remove the specified axis
1036+
1037+ // Create a new array to store the accumulated values
1038+ // @ts-ignore
1039+ const result = new input.data.constructor(
1040+ input.data.length / input.dims[dim],
1041+ );
1042+
1043+ // Iterate over the data array
1044+ for (let i = 0; i < input.data.length; ++i) {
1045+ // Calculate the index in the resulting array
1046+ let resultIndex = 0;
1047+
1048+ for (
1049+ let j = input.dims.length - 1, num = i, resultMultiplier = 1;
1050+ j >= 0;
1051+ --j
1052+ ) {
1053+ const size = input.dims[j];
1054+ if (j !== dim) {
1055+ const index = num % size;
1056+ resultIndex += index * resultMultiplier;
1057+ resultMultiplier *= resultDims[j];
1058+ }
1059+ num = Math.floor(num / size);
1060+ }
1061+
1062+ // Accumulate the value at the current index
1063+ result[resultIndex] += input.data[i];
1064+ }
1065+
1066+ if (input.dims[dim] !== 1) {
1067+ for (let i = 0; i < result.length; ++i) {
1068+ result[i] = result[i] / input.dims[dim];
10251069 }
1070+ }
10261071
1027- if (!keepdim) {
1028- resultDims.splice(dim, 1);
1029- }
1072+ if (!keepdim) {
1073+ resultDims.splice(dim, 1);
1074+ }
10301075
1031- return new Tensor(input.type, result, resultDims);
1076+ return new Tensor(input.type, result, resultDims);
10321077 }
10331078
1034-
10351079 /**
10361080 *
10371081 * Measures similarity between two temporal sequences (e.g., input audio and output tokens
10381082 * to generate token-level timestamps).
1039- * @param {Tensor} matrix
1083+ * @param {Tensor} matrix
10401084 * @returns {number[][]}
10411085 */
10421086 export function dynamicTimeWarping(matrix) {
1043- const [output_length, input_length] = matrix.dims;
1044-
1045- const outputShape = [output_length + 1, input_length + 1];
1046-
1047- const cost = new Tensor(
1048- 'float32',
1049- new Float32Array(outputShape[0] * outputShape[1]).fill(Infinity),
1050- outputShape
1051- );
1052-
1053- const trace = new Tensor(
1054- 'float32',
1055- new Float32Array(outputShape[0] * outputShape[1]).fill(-1),
1056- outputShape
1057- )
1058-
1059- // same as `cost[0][0] = 0`;
1060- cost[0].data[0] = 0;
1061-
1062- for (let j = 1; j < input_length + 1; ++j) {
1063- for (let i = 1; i < output_length + 1; ++i) {
1064-
1065- const c0 = cost[i - 1][j - 1].item();
1066- const c1 = cost[i - 1][j].item();
1067- const c2 = cost[i][j - 1].item();
1068-
1069- let c, t;
1070- if (c0 < c1 && c0 < c2) {
1071- c = c0;
1072- t = 0;
1073- } else if (c1 < c0 && c1 < c2) {
1074- c = c1;
1075- t = 1;
1076- } else {
1077- c = c2;
1078- t = 2;
1079- }
1080-
1081- cost[i].data[j] = matrix[i - 1][j - 1].item() + c;
1082- trace[i].data[j] = t;
1083- }
1084- }
1085-
1086- // backtrace
1087- let i = output_length;
1088- let j = input_length;
1089-
1090- // @ts-ignore
1091- trace.data.fill(2, 0, outputShape[1]) // trace[0, :] = 2
1092- for (let i = 0; i < outputShape[0]; ++i) { // trace[:, 0] = 1
1093- trace[i].data[0] = 1;
1094- }
1095-
1096- let text_indices = [];
1097- let time_indices = [];
1098-
1099- while (i > 0 || j > 0) {
1100- text_indices.push(i - 1);
1101- time_indices.push(j - 1);
1102-
1103- const t = trace[i][j].item();
1104- switch (t) {
1105- case 0:
1106- --i; --j;
1107- break;
1108- case 1:
1109- --i;
1110- break;
1111- case 2:
1112- --j;
1113- break;
1114- default:
1115- throw new Error(
1116- `Internal error in dynamic time warping. Unexpected trace[${i}, ${j}]. Please file a bug report.`
1117- )
1118- }
1087+ const [output_length, input_length] = matrix.dims;
1088+
1089+ const outputShape = [output_length + 1, input_length + 1];
1090+
1091+ const cost = new Tensor(
1092+ "float32",
1093+ new Float32Array(outputShape[0] * outputShape[1]).fill(Infinity),
1094+ outputShape,
1095+ );
1096+
1097+ const trace = new Tensor(
1098+ "float32",
1099+ new Float32Array(outputShape[0] * outputShape[1]).fill(-1),
1100+ outputShape,
1101+ );
1102+
1103+ // same as `cost[0][0] = 0`;
1104+ cost[0].data[0] = 0;
1105+
1106+ for (let j = 1; j < input_length + 1; ++j) {
1107+ for (let i = 1; i < output_length + 1; ++i) {
1108+ const c0 = cost[i - 1][j - 1].item();
1109+ const c1 = cost[i - 1][j].item();
1110+ const c2 = cost[i][j - 1].item();
1111+
1112+ let c, t;
1113+ if (c0 < c1 && c0 < c2) {
1114+ c = c0;
1115+ t = 0;
1116+ } else if (c1 < c0 && c1 < c2) {
1117+ c = c1;
1118+ t = 1;
1119+ } else {
1120+ c = c2;
1121+ t = 2;
1122+ }
1123+
1124+ cost[i].data[j] = matrix[i - 1][j - 1].item() + c;
1125+ trace[i].data[j] = t;
1126+ }
1127+ }
1128+
1129+ // backtrace
1130+ let i = output_length;
1131+ let j = input_length;
1132+
1133+ // @ts-ignore
1134+ trace.data.fill(2, 0, outputShape[1]); // trace[0, :] = 2
1135+ for (let i = 0; i < outputShape[0]; ++i) {
1136+ // trace[:, 0] = 1
1137+ trace[i].data[0] = 1;
1138+ }
1139+
1140+ let text_indices = [];
1141+ let time_indices = [];
1142+
1143+ while (i > 0 || j > 0) {
1144+ text_indices.push(i - 1);
1145+ time_indices.push(j - 1);
1146+
1147+ const t = trace[i][j].item();
1148+ switch (t) {
1149+ case 0:
1150+ --i;
1151+ --j;
1152+ break;
1153+ case 1:
1154+ --i;
1155+ break;
1156+ case 2:
1157+ --j;
1158+ break;
1159+ default:
1160+ throw new Error(
1161+ `Internal error in dynamic time warping. Unexpected trace[${i}, ${j}]. Please file a bug report.`,
1162+ );
11191163 }
1164+ }
11201165
1121- text_indices.reverse();
1122- time_indices.reverse();
1123-
1124- return [text_indices, time_indices];
1166+ text_indices.reverse();
1167+ time_indices.reverse();
11251168
1169+ return [text_indices, time_indices];
11261170 }
11271171
11281172 function dimsToStride(dims) {
1129- const stride = new Array(dims.length);
1130- for (let i = dims.length - 1, s2 = 1; i >= 0; --i) {
1131- stride[i] = s2;
1132- s2 *= dims[i];
1133- }
1134- return stride;
1173+ const stride = new Array(dims.length);
1174+ for (let i = dims.length - 1, s2 = 1; i >= 0; --i) {
1175+ stride[i] = s2;
1176+ s2 *= dims[i];
1177+ }
1178+ return stride;
11351179 }
11361180
11371181 /**
@@ -1139,12 +1183,8 @@
11391183 * @param {number[]} size A sequence of integers defining the shape of the output tensor.
11401184 */
11411185 export function ones(size) {
1142- const numElements = size.reduce((a, b) => a * b, 1);
1143- return new Tensor(
1144- 'int64',
1145- new BigInt64Array(numElements).fill(1n),
1146- size
1147- )
1186+ const numElements = size.reduce((a, b) => a * b, 1);
1187+ return new Tensor("int64", new BigInt64Array(numElements).fill(1n), size);
11481188 }
11491189
11501190 /**
@@ -1153,5 +1193,5 @@
11531193 * @returns The ones tensor.
11541194 */
11551195 export function ones_like(tensor) {
1156- return ones(tensor.dims);
1196+ return ones(tensor.dims);
11571197 }
modified core/vendor/modules/@xenova/transformers/types/backends/onnx.d.ts +2 −2
@@ -1,5 +1,5 @@
11 /** @type {import('onnxruntime-web')} The ONNX runtime module. */
22 export let ONNX: typeof ONNX_WEB;
33 export const executionProviders: string[];
4-import * as ONNX_WEB from 'onnxruntime-web';
5-//# sourceMappingURL=onnx.d.ts.map
No newline at the end of the file
4+import * as ONNX_WEB from "onnxruntime-web";
5+//# sourceMappingURL=onnx.d.ts.map
modified core/vendor/modules/@xenova/transformers/types/configs.d.ts +47 −29
@@ -3,23 +3,32 @@
33 * [Python documentation](https://huggingface.co/docs/transformers/main/en/main_classes/configuration#transformers.PretrainedConfig).
44 */
55 export class PretrainedConfig {
6- /**
7- * Loads a pre-trained config from the given `pretrained_model_name_or_path`.
8- *
9- * @param {string} pretrained_model_name_or_path The path to the pre-trained config.
10- * @param {PretrainedOptions} options Additional options for loading the config.
11- * @throws {Error} Throws an error if the config.json is not found in the `pretrained_model_name_or_path`.
12- *
13- * @returns {Promise<PretrainedConfig>} A new instance of the `PretrainedConfig` class.
14- */
15- static from_pretrained(pretrained_model_name_or_path: string, { progress_callback, config, cache_dir, local_files_only, revision, }?: PretrainedOptions): Promise<PretrainedConfig>;
16- /**
17- * Create a new PreTrainedTokenizer instance.
18- * @param {Object} configJSON The JSON of the config.
19- */
20- constructor(configJSON: any);
21- model_type: any;
22- is_encoder_decoder: boolean;
6+ /**
7+ * Loads a pre-trained config from the given `pretrained_model_name_or_path`.
8+ *
9+ * @param {string} pretrained_model_name_or_path The path to the pre-trained config.
10+ * @param {PretrainedOptions} options Additional options for loading the config.
11+ * @throws {Error} Throws an error if the config.json is not found in the `pretrained_model_name_or_path`.
12+ *
13+ * @returns {Promise<PretrainedConfig>} A new instance of the `PretrainedConfig` class.
14+ */
15+ static from_pretrained(
16+ pretrained_model_name_or_path: string,
17+ {
18+ progress_callback,
19+ config,
20+ cache_dir,
21+ local_files_only,
22+ revision,
23+ }?: PretrainedOptions,
24+ ): Promise<PretrainedConfig>;
25+ /**
26+ * Create a new PreTrainedTokenizer instance.
27+ * @param {Object} configJSON The JSON of the config.
28+ */
29+ constructor(configJSON: any);
30+ model_type: any;
31+ is_encoder_decoder: boolean;
2332 }
2433 /**
2534 * Helper class which is used to instantiate pretrained configs with the `from_pretrained` function.
@@ -28,16 +37,25 @@
2837 * let config = await AutoConfig.from_pretrained('bert-base-uncased');
2938 */
3039 export class AutoConfig {
31- /**
32- * Loads a pre-trained config from the given `pretrained_model_name_or_path`.
33- *
34- * @param {string} pretrained_model_name_or_path The path to the pre-trained config.
35- * @param {PretrainedOptions} options Additional options for loading the config.
36- * @throws {Error} Throws an error if the config.json is not found in the `pretrained_model_name_or_path`.
37- *
38- * @returns {Promise<PretrainedConfig>} A new instance of the `PretrainedConfig` class.
39- */
40- static from_pretrained(pretrained_model_name_or_path: string, { progress_callback, config, cache_dir, local_files_only, revision, }?: import("./utils/hub.js").PretrainedOptions): Promise<PretrainedConfig>;
40+ /**
41+ * Loads a pre-trained config from the given `pretrained_model_name_or_path`.
42+ *
43+ * @param {string} pretrained_model_name_or_path The path to the pre-trained config.
44+ * @param {PretrainedOptions} options Additional options for loading the config.
45+ * @throws {Error} Throws an error if the config.json is not found in the `pretrained_model_name_or_path`.
46+ *
47+ * @returns {Promise<PretrainedConfig>} A new instance of the `PretrainedConfig` class.
48+ */
49+ static from_pretrained(
50+ pretrained_model_name_or_path: string,
51+ {
52+ progress_callback,
53+ config,
54+ cache_dir,
55+ local_files_only,
56+ revision,
57+ }?: import("./utils/hub.js").PretrainedOptions,
58+ ): Promise<PretrainedConfig>;
4159 }
42-export type PretrainedOptions = import('./utils/hub.js').PretrainedOptions;
43-//# sourceMappingURL=configs.d.ts.map
No newline at the end of the file
60+export type PretrainedOptions = import("./utils/hub.js").PretrainedOptions;
61+//# sourceMappingURL=configs.d.ts.map
modified core/vendor/modules/@xenova/transformers/types/env.d.ts +18 −18
@@ -1,21 +1,21 @@
11 export namespace env {
2- export namespace backends {
3- export { onnx_env as onnx };
4- export let tfjs: {};
5- }
6- export { __dirname };
7- export { VERSION as version };
8- export let allowRemoteModels: boolean;
9- export let remoteHost: string;
10- export let remotePathTemplate: string;
11- export let allowLocalModels: boolean;
12- export { localModelPath };
13- export { FS_AVAILABLE as useFS };
14- export { WEB_CACHE_AVAILABLE as useBrowserCache };
15- export { FS_AVAILABLE as useFSCache };
16- export { DEFAULT_CACHE_DIR as cacheDir };
17- export let useCustomCache: boolean;
18- export let customCache: any;
2+ export namespace backends {
3+ export { onnx_env as onnx };
4+ export let tfjs: {};
5+ }
6+ export { __dirname };
7+ export { VERSION as version };
8+ export let allowRemoteModels: boolean;
9+ export let remoteHost: string;
10+ export let remotePathTemplate: string;
11+ export let allowLocalModels: boolean;
12+ export { localModelPath };
13+ export { FS_AVAILABLE as useFS };
14+ export { WEB_CACHE_AVAILABLE as useBrowserCache };
15+ export { FS_AVAILABLE as useFSCache };
16+ export { DEFAULT_CACHE_DIR as cacheDir };
17+ export let useCustomCache: boolean;
18+ export let customCache: any;
1919 }
2020 declare const onnx_env: import("onnxruntime-common").Env;
2121 declare const __dirname: any;
@@ -25,4 +25,4 @@
2525 declare const WEB_CACHE_AVAILABLE: boolean;
2626 declare const DEFAULT_CACHE_DIR: any;
2727 export {};
28-//# sourceMappingURL=env.d.ts.map
No newline at the end of the file
28+//# sourceMappingURL=env.d.ts.map
modified core/vendor/modules/@xenova/transformers/types/models.d.ts +1921 −1745
@@ -1,1318 +1,1368 @@
11 declare const PreTrainedModel_base: new () => {
2- (...args: any[]): any;
3- _call(...args: any[]): any;
2+ (...args: any[]): any;
3+ _call(...args: any[]): any;
44 };
55 /**
66 * A base class for pre-trained models that provides the model configuration and an ONNX session.
77 */
88 export class PreTrainedModel extends PreTrainedModel_base {
9- /**
10- * Instantiate one of the model classes of the library from a pretrained model.
11- *
12- * The model class to instantiate is selected based on the `model_type` property of the config object
13- * (either passed as an argument or loaded from `pretrained_model_name_or_path` if possible)
14- *
15- * @param {string} pretrained_model_name_or_path The name or path of the pretrained model. Can be either:
16- * - A string, the *model id* of a pretrained model hosted inside a model repo on huggingface.co.
17- * Valid model ids can be located at the root-level, like `bert-base-uncased`, or namespaced under a
18- * user or organization name, like `dbmdz/bert-base-german-cased`.
19- * - A path to a *directory* containing model weights, e.g., `./my_model_directory/`.
20- * @param {import('./utils/hub.js').PretrainedOptions} options Additional options for loading the model.
21- *
22- * @returns {Promise<PreTrainedModel>} A new instance of the `PreTrainedModel` class.
23- */
24- static from_pretrained(pretrained_model_name_or_path: string, { quantized, progress_callback, config, cache_dir, local_files_only, revision, model_file_name, }?: import('./utils/hub.js').PretrainedOptions): Promise<PreTrainedModel>;
25- /**
26- * Creates a new instance of the `PreTrainedModel` class.
27- * @param {Object} config The model configuration.
28- * @param {any} session session for the model.
29- */
30- constructor(config: any, session: any);
31- main_input_name: string;
32- config: any;
33- session: any;
34- can_generate: boolean;
35- _runBeam: typeof decoderRunBeam;
36- _getStartBeams: typeof decoderStartBeams;
37- _updateBeam: typeof decoderUpdatebeam;
38- _forward: typeof encoderForward;
39- /**
40- * Disposes of all the ONNX sessions that were created during inference.
41- * @returns {Promise<unknown[]>} An array of promises, one for each ONNX session that is being disposed.
42- * @todo Use https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/FinalizationRegistry
43- */
44- dispose(): Promise<unknown[]>;
45- /**
46- * Runs the model with the provided inputs
47- * @param {Object} model_inputs Object containing input tensors
48- * @returns {Promise<Object>} Object containing output tensors
49- */
50- _call(model_inputs: any): Promise<any>;
51- /**
52- * Forward method for a pretrained model. If not overridden by a subclass, the correct forward method
53- * will be chosen based on the model type.
54- * @param {Object} model_inputs The input data to the model in the format specified in the ONNX model.
55- * @returns {Promise<Object>} The output data from the model in the format specified in the ONNX model.
56- * @throws {Error} This method must be implemented in subclasses.
57- */
58- forward(model_inputs: any): Promise<any>;
59- /**
60- * @param {import('./utils/generation.js').GenerationConfigType} generation_config
61- * @param {number} input_ids_seq_length The starting sequence length for the input ids.
62- * @returns {LogitsProcessorList}
63- * @private
64- */
65- private _get_logits_processor;
66- /**
67- * This function merges multiple generation configs together to form a final generation config to be used by the model for text generation.
68- * It first creates an empty `GenerationConfig` object, then it applies the model's own `generation_config` property to it. Finally, if a `generation_config` object was passed in the arguments, it overwrites the corresponding properties in the final config with those of the passed config object.
69- * @param {import('./utils/generation.js').GenerationConfigType} generation_config A `GenerationConfig` object containing generation parameters.
70- * @returns {import('./utils/generation.js').GenerationConfigType} The final generation config object to be used by the model for text generation.
71- */
72- _get_generation_config(generation_config: import('./utils/generation.js').GenerationConfigType): import('./utils/generation.js').GenerationConfigType;
73- /**
74- * @typedef {import('./utils/maths.js').TypedArray} TypedArray
75- */
76- /**
77- * @typedef {{ sequences: Tensor, decoder_attentions: Tensor, cross_attentions: Tensor }} EncoderDecoderOutput
78- * @typedef {Object} DecoderOutput
79- *
80- * Generates text based on the given inputs and generation configuration using the model.
81- * @param {Tensor|Array|TypedArray} inputs An array of input token IDs.
82- * @param {Object|GenerationConfig|null} generation_config The generation configuration to use. If null, default configuration will be used.
83- * @param {Object|null} logits_processor An optional logits processor to use. If null, a new LogitsProcessorList instance will be created.
84- * @param {Object} options options
85- * @param {Object} [options.inputs_attention_mask=null] An optional attention mask for the inputs.
86- * @returns {Promise<number[][]|EncoderDecoderOutput|DecoderOutput>} An array of generated output sequences, where each sequence is an array of token IDs.
87- * @throws {Error} Throws an error if the inputs array is empty.
88- */
89- generate(inputs: any[] | import("./transformers.js").TypedArray | Tensor, generation_config?: any | (new (kwargs?: import("./utils/generation.js").GenerationConfigType) => import("./utils/generation.js").GenerationConfigType) | null, logits_processor?: any | null, { inputs_attention_mask }?: {
90- inputs_attention_mask?: any;
91- }): Promise<any>;
92- /**
93- * Helper function to add attentions to beam
94- * @param {Object} beam
95- * @param {Object} output
96- * @private
97- */
98- private addAttentionsToBeam;
99- /**
100- * Groups an array of beam objects by their ids.
101- *
102- * @param {Array} beams The array of beam objects to group.
103- * @returns {Array} An array of arrays, where each inner array contains beam objects with the same id.
104- */
105- groupBeams(beams: any[]): any[];
106- /**
107- * Returns an object containing past key values from the given decoder results object.
108- *
109- * @param {Object} decoderResults The decoder results object.
110- * @param {Object} pastKeyValues The previous past key values.
111- * @returns {Object} An object containing past key values.
112- */
113- getPastKeyValues(decoderResults: any, pastKeyValues: any): any;
114- /**
115- * Returns an object containing attentions from the given decoder results object.
116- *
117- * @param {Object} decoderResults The decoder results object.
118- * @returns {Object} An object containing attentions.
119- */
120- getAttentions(decoderResults: any): any;
121- /**
122- * Adds past key values to the decoder feeds object. If pastKeyValues is null, creates new tensors for past key values.
123- *
124- * @param {Object} decoderFeeds The decoder feeds object to add past key values to.
125- * @param {Object} pastKeyValues An object containing past key values.
126- */
127- addPastKeyValues(decoderFeeds: any, pastKeyValues: any): void;
128- /**
129- * Initializes and returns the beam for text generation task
130- * @param {Tensor} inputTokenIds The input token ids.
131- * @param {Object} generation_config The generation config.
132- * @param {number} numOutputTokens The number of tokens to be generated.
133- * @param {Tensor} inputs_attention_mask Optional input attention mask.
134- * @returns {any} A Beam object representing the initialized beam.
135- * @private
136- */
137- private getStartBeams;
138- /**
139- * Runs a single step of the beam search generation algorithm.
140- * @param {any} beam The current beam being generated.
141- * @returns {Promise<any>} The updated beam after a single generation step.
142- * @private
143- */
144- private runBeam;
145- /**
146- * Update a beam with a new token ID.
147- * @param {Object} beam The beam to update.
148- * @param {number} newTokenId The new token ID to add to the beam's output.
149- * @private
150- */
151- private updateBeam;
152-}
153-export class ModelOutput {
154-}
9+ /**
10+ * Instantiate one of the model classes of the library from a pretrained model.
11+ *
12+ * The model class to instantiate is selected based on the `model_type` property of the config object
13+ * (either passed as an argument or loaded from `pretrained_model_name_or_path` if possible)
14+ *
15+ * @param {string} pretrained_model_name_or_path The name or path of the pretrained model. Can be either:
16+ * - A string, the *model id* of a pretrained model hosted inside a model repo on huggingface.co.
17+ * Valid model ids can be located at the root-level, like `bert-base-uncased`, or namespaced under a
18+ * user or organization name, like `dbmdz/bert-base-german-cased`.
19+ * - A path to a *directory* containing model weights, e.g., `./my_model_directory/`.
20+ * @param {import('./utils/hub.js').PretrainedOptions} options Additional options for loading the model.
21+ *
22+ * @returns {Promise<PreTrainedModel>} A new instance of the `PreTrainedModel` class.
23+ */
24+ static from_pretrained(
25+ pretrained_model_name_or_path: string,
26+ {
27+ quantized,
28+ progress_callback,
29+ config,
30+ cache_dir,
31+ local_files_only,
32+ revision,
33+ model_file_name,
34+ }?: import("./utils/hub.js").PretrainedOptions,
35+ ): Promise<PreTrainedModel>;
36+ /**
37+ * Creates a new instance of the `PreTrainedModel` class.
38+ * @param {Object} config The model configuration.
39+ * @param {any} session session for the model.
40+ */
41+ constructor(config: any, session: any);
42+ main_input_name: string;
43+ config: any;
44+ session: any;
45+ can_generate: boolean;
46+ _runBeam: typeof decoderRunBeam;
47+ _getStartBeams: typeof decoderStartBeams;
48+ _updateBeam: typeof decoderUpdatebeam;
49+ _forward: typeof encoderForward;
50+ /**
51+ * Disposes of all the ONNX sessions that were created during inference.
52+ * @returns {Promise<unknown[]>} An array of promises, one for each ONNX session that is being disposed.
53+ * @todo Use https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/FinalizationRegistry
54+ */
55+ dispose(): Promise<unknown[]>;
56+ /**
57+ * Runs the model with the provided inputs
58+ * @param {Object} model_inputs Object containing input tensors
59+ * @returns {Promise<Object>} Object containing output tensors
60+ */
61+ _call(model_inputs: any): Promise<any>;
62+ /**
63+ * Forward method for a pretrained model. If not overridden by a subclass, the correct forward method
64+ * will be chosen based on the model type.
65+ * @param {Object} model_inputs The input data to the model in the format specified in the ONNX model.
66+ * @returns {Promise<Object>} The output data from the model in the format specified in the ONNX model.
67+ * @throws {Error} This method must be implemented in subclasses.
68+ */
69+ forward(model_inputs: any): Promise<any>;
70+ /**
71+ * @param {import('./utils/generation.js').GenerationConfigType} generation_config
72+ * @param {number} input_ids_seq_length The starting sequence length for the input ids.
73+ * @returns {LogitsProcessorList}
74+ * @private
75+ */
76+ private _get_logits_processor;
77+ /**
78+ * This function merges multiple generation configs together to form a final generation config to be used by the model for text generation.
79+ * It first creates an empty `GenerationConfig` object, then it applies the model's own `generation_config` property to it. Finally, if a `generation_config` object was passed in the arguments, it overwrites the corresponding properties in the final config with those of the passed config object.
80+ * @param {import('./utils/generation.js').GenerationConfigType} generation_config A `GenerationConfig` object containing generation parameters.
81+ * @returns {import('./utils/generation.js').GenerationConfigType} The final generation config object to be used by the model for text generation.
82+ */
83+ _get_generation_config(
84+ generation_config: import("./utils/generation.js").GenerationConfigType,
85+ ): import("./utils/generation.js").GenerationConfigType;
86+ /**
87+ * @typedef {import('./utils/maths.js').TypedArray} TypedArray
88+ */
89+ /**
90+ * @typedef {{ sequences: Tensor, decoder_attentions: Tensor, cross_attentions: Tensor }} EncoderDecoderOutput
91+ * @typedef {Object} DecoderOutput
92+ *
93+ * Generates text based on the given inputs and generation configuration using the model.
94+ * @param {Tensor|Array|TypedArray} inputs An array of input token IDs.
95+ * @param {Object|GenerationConfig|null} generation_config The generation configuration to use. If null, default configuration will be used.
96+ * @param {Object|null} logits_processor An optional logits processor to use. If null, a new LogitsProcessorList instance will be created.
97+ * @param {Object} options options
98+ * @param {Object} [options.inputs_attention_mask=null] An optional attention mask for the inputs.
99+ * @returns {Promise<number[][]|EncoderDecoderOutput|DecoderOutput>} An array of generated output sequences, where each sequence is an array of token IDs.
100+ * @throws {Error} Throws an error if the inputs array is empty.
101+ */
102+ generate(
103+ inputs: any[] | import("./transformers.js").TypedArray | Tensor,
104+ generation_config?:
105+ | any
106+ | (new (
107+ kwargs?: import("./utils/generation.js").GenerationConfigType,
108+ ) => import("./utils/generation.js").GenerationConfigType)
109+ | null,
110+ logits_processor?: any | null,
111+ {
112+ inputs_attention_mask,
113+ }?: {
114+ inputs_attention_mask?: any;
115+ },
116+ ): Promise<any>;
117+ /**
118+ * Helper function to add attentions to beam
119+ * @param {Object} beam
120+ * @param {Object} output
121+ * @private
122+ */
123+ private addAttentionsToBeam;
124+ /**
125+ * Groups an array of beam objects by their ids.
126+ *
127+ * @param {Array} beams The array of beam objects to group.
128+ * @returns {Array} An array of arrays, where each inner array contains beam objects with the same id.
129+ */
130+ groupBeams(beams: any[]): any[];
131+ /**
132+ * Returns an object containing past key values from the given decoder results object.
133+ *
134+ * @param {Object} decoderResults The decoder results object.
135+ * @param {Object} pastKeyValues The previous past key values.
136+ * @returns {Object} An object containing past key values.
137+ */
138+ getPastKeyValues(decoderResults: any, pastKeyValues: any): any;
139+ /**
140+ * Returns an object containing attentions from the given decoder results object.
141+ *
142+ * @param {Object} decoderResults The decoder results object.
143+ * @returns {Object} An object containing attentions.
144+ */
145+ getAttentions(decoderResults: any): any;
146+ /**
147+ * Adds past key values to the decoder feeds object. If pastKeyValues is null, creates new tensors for past key values.
148+ *
149+ * @param {Object} decoderFeeds The decoder feeds object to add past key values to.
150+ * @param {Object} pastKeyValues An object containing past key values.
151+ */
152+ addPastKeyValues(decoderFeeds: any, pastKeyValues: any): void;
153+ /**
154+ * Initializes and returns the beam for text generation task
155+ * @param {Tensor} inputTokenIds The input token ids.
156+ * @param {Object} generation_config The generation config.
157+ * @param {number} numOutputTokens The number of tokens to be generated.
158+ * @param {Tensor} inputs_attention_mask Optional input attention mask.
159+ * @returns {any} A Beam object representing the initialized beam.
160+ * @private
161+ */
162+ private getStartBeams;
163+ /**
164+ * Runs a single step of the beam search generation algorithm.
165+ * @param {any} beam The current beam being generated.
166+ * @returns {Promise<any>} The updated beam after a single generation step.
167+ * @private
168+ */
169+ private runBeam;
170+ /**
171+ * Update a beam with a new token ID.
172+ * @param {Object} beam The beam to update.
173+ * @param {number} newTokenId The new token ID to add to the beam's output.
174+ * @private
175+ */
176+ private updateBeam;
177+}
178+export class ModelOutput {}
155179 /**
156180 * Base class for model's outputs, with potential hidden states and attentions.
157181 */
158182 export class BaseModelOutput extends ModelOutput {
159- /**
160- * @param {Object} output The output of the model.
161- * @param {Tensor} output.last_hidden_state Sequence of hidden-states at the output of the last layer of the model.
162- * @param {Tensor} [output.hidden_states] Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
163- * @param {Tensor} [output.attentions] Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads.
164- */
165- constructor({ last_hidden_state, hidden_states, attentions }: {
166- last_hidden_state: Tensor;
167- hidden_states?: Tensor;
168- attentions?: Tensor;
169- });
183+ /**
184+ * @param {Object} output The output of the model.
185+ * @param {Tensor} output.last_hidden_state Sequence of hidden-states at the output of the last layer of the model.
186+ * @param {Tensor} [output.hidden_states] Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
187+ * @param {Tensor} [output.attentions] Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads.
188+ */
189+ constructor({
190+ last_hidden_state,
191+ hidden_states,
192+ attentions,
193+ }: {
170194 last_hidden_state: Tensor;
171- hidden_states: Tensor;
172- attentions: Tensor;
173-}
174-export class BertPreTrainedModel extends PreTrainedModel {
175-}
176-export class BertModel extends BertPreTrainedModel {
177-}
195+ hidden_states?: Tensor;
196+ attentions?: Tensor;
197+ });
198+ last_hidden_state: Tensor;
199+ hidden_states: Tensor;
200+ attentions: Tensor;
201+}
202+export class BertPreTrainedModel extends PreTrainedModel {}
203+export class BertModel extends BertPreTrainedModel {}
178204 /**
179205 * BertForMaskedLM is a class representing a BERT model for masked language modeling.
180206 */
181207 export class BertForMaskedLM extends BertPreTrainedModel {
182- /**
183- * Calls the model on new inputs.
184- *
185- * @param {Object} model_inputs The inputs to the model.
186- * @returns {Promise<MaskedLMOutput>} An object containing the model's output logits for masked language modeling.
187- */
188- _call(model_inputs: any): Promise<MaskedLMOutput>;
208+ /**
209+ * Calls the model on new inputs.
210+ *
211+ * @param {Object} model_inputs The inputs to the model.
212+ * @returns {Promise<MaskedLMOutput>} An object containing the model's output logits for masked language modeling.
213+ */
214+ _call(model_inputs: any): Promise<MaskedLMOutput>;
189215 }
190216 /**
191217 * BertForSequenceClassification is a class representing a BERT model for sequence classification.
192218 */
193219 export class BertForSequenceClassification extends BertPreTrainedModel {
194- /**
195- * Calls the model on new inputs.
196- *
197- * @param {Object} model_inputs The inputs to the model.
198- * @returns {Promise<SequenceClassifierOutput>} An object containing the model's output logits for sequence classification.
199- */
200- _call(model_inputs: any): Promise<SequenceClassifierOutput>;
220+ /**
221+ * Calls the model on new inputs.
222+ *
223+ * @param {Object} model_inputs The inputs to the model.
224+ * @returns {Promise<SequenceClassifierOutput>} An object containing the model's output logits for sequence classification.
225+ */
226+ _call(model_inputs: any): Promise<SequenceClassifierOutput>;
201227 }
202228 /**
203229 * BertForTokenClassification is a class representing a BERT model for token classification.
204230 */
205231 export class BertForTokenClassification extends BertPreTrainedModel {
206- /**
207- * Calls the model on new inputs.
208- *
209- * @param {Object} model_inputs The inputs to the model.
210- * @returns {Promise<TokenClassifierOutput>} An object containing the model's output logits for token classification.
211- */
212- _call(model_inputs: any): Promise<TokenClassifierOutput>;
232+ /**
233+ * Calls the model on new inputs.
234+ *
235+ * @param {Object} model_inputs The inputs to the model.
236+ * @returns {Promise<TokenClassifierOutput>} An object containing the model's output logits for token classification.
237+ */
238+ _call(model_inputs: any): Promise<TokenClassifierOutput>;
213239 }
214240 /**
215241 * BertForQuestionAnswering is a class representing a BERT model for question answering.
216242 */
217243 export class BertForQuestionAnswering extends BertPreTrainedModel {
218- /**
219- * Calls the model on new inputs.
220- *
221- * @param {Object} model_inputs The inputs to the model.
222- * @returns {Promise<QuestionAnsweringModelOutput>} An object containing the model's output logits for question answering.
223- */
224- _call(model_inputs: any): Promise<QuestionAnsweringModelOutput>;
225-}
226-export class RoFormerPreTrainedModel extends PreTrainedModel {
227-}
244+ /**
245+ * Calls the model on new inputs.
246+ *
247+ * @param {Object} model_inputs The inputs to the model.
248+ * @returns {Promise<QuestionAnsweringModelOutput>} An object containing the model's output logits for question answering.
249+ */
250+ _call(model_inputs: any): Promise<QuestionAnsweringModelOutput>;
251+}
252+export class RoFormerPreTrainedModel extends PreTrainedModel {}
228253 /**
229254 * The bare RoFormer Model transformer outputting raw hidden-states without any specific head on top.
230255 */
231-export class RoFormerModel extends RoFormerPreTrainedModel {
232-}
256+export class RoFormerModel extends RoFormerPreTrainedModel {}
233257 /**
234258 * RoFormer Model with a `language modeling` head on top.
235259 */
236260 export class RoFormerForMaskedLM extends RoFormerPreTrainedModel {
237- /**
238- * Calls the model on new inputs.
239- *
240- * @param {Object} model_inputs The inputs to the model.
241- * @returns {Promise<MaskedLMOutput>} An object containing the model's output logits for masked language modeling.
242- */
243- _call(model_inputs: any): Promise<MaskedLMOutput>;
261+ /**
262+ * Calls the model on new inputs.
263+ *
264+ * @param {Object} model_inputs The inputs to the model.
265+ * @returns {Promise<MaskedLMOutput>} An object containing the model's output logits for masked language modeling.
266+ */
267+ _call(model_inputs: any): Promise<MaskedLMOutput>;
244268 }
245269 /**
246270 * RoFormer Model transformer with a sequence classification/regression head on top (a linear layer on top of the pooled output)
247271 */
248272 export class RoFormerForSequenceClassification extends RoFormerPreTrainedModel {
249- /**
250- * Calls the model on new inputs.
251- *
252- * @param {Object} model_inputs The inputs to the model.
253- * @returns {Promise<SequenceClassifierOutput>} An object containing the model's output logits for sequence classification.
254- */
255- _call(model_inputs: any): Promise<SequenceClassifierOutput>;
273+ /**
274+ * Calls the model on new inputs.
275+ *
276+ * @param {Object} model_inputs The inputs to the model.
277+ * @returns {Promise<SequenceClassifierOutput>} An object containing the model's output logits for sequence classification.
278+ */
279+ _call(model_inputs: any): Promise<SequenceClassifierOutput>;
256280 }
257281 /**
258282 * RoFormer Model with a token classification head on top (a linear layer on top of the hidden-states output)
259283 * e.g. for Named-Entity-Recognition (NER) tasks.
260284 */
261285 export class RoFormerForTokenClassification extends RoFormerPreTrainedModel {
262- /**
263- * Calls the model on new inputs.
264- *
265- * @param {Object} model_inputs The inputs to the model.
266- * @returns {Promise<TokenClassifierOutput>} An object containing the model's output logits for token classification.
267- */
268- _call(model_inputs: any): Promise<TokenClassifierOutput>;
286+ /**
287+ * Calls the model on new inputs.
288+ *
289+ * @param {Object} model_inputs The inputs to the model.
290+ * @returns {Promise<TokenClassifierOutput>} An object containing the model's output logits for token classification.
291+ */
292+ _call(model_inputs: any): Promise<TokenClassifierOutput>;
269293 }
270294 /**
271295 * RoFormer Model with a span classification head on top for extractive question-answering tasks like SQuAD
272296 * (a linear layers on top of the hidden-states output to compute `span start logits` and `span end logits`).
273297 */
274298 export class RoFormerForQuestionAnswering extends RoFormerPreTrainedModel {
275- /**
276- * Calls the model on new inputs.
277- *
278- * @param {Object} model_inputs The inputs to the model.
279- * @returns {Promise<QuestionAnsweringModelOutput>} An object containing the model's output logits for question answering.
280- */
281- _call(model_inputs: any): Promise<QuestionAnsweringModelOutput>;
282-}
283-export class ConvBertPreTrainedModel extends PreTrainedModel {
284-}
299+ /**
300+ * Calls the model on new inputs.
301+ *
302+ * @param {Object} model_inputs The inputs to the model.
303+ * @returns {Promise<QuestionAnsweringModelOutput>} An object containing the model's output logits for question answering.
304+ */
305+ _call(model_inputs: any): Promise<QuestionAnsweringModelOutput>;
306+}
307+export class ConvBertPreTrainedModel extends PreTrainedModel {}
285308 /**
286309 * The bare ConvBERT Model transformer outputting raw hidden-states without any specific head on top.
287310 */
288-export class ConvBertModel extends ConvBertPreTrainedModel {
289-}
311+export class ConvBertModel extends ConvBertPreTrainedModel {}
290312 /**
291313 * ConvBERT Model with a language modeling head on top.
292314 */
293315 export class ConvBertForMaskedLM extends ConvBertPreTrainedModel {
294- /**
295- * Calls the model on new inputs.
296- *
297- * @param {Object} model_inputs The inputs to the model.
298- * @returns {Promise<MaskedLMOutput>} An object containing the model's output logits for masked language modeling.
299- */
300- _call(model_inputs: any): Promise<MaskedLMOutput>;
316+ /**
317+ * Calls the model on new inputs.
318+ *
319+ * @param {Object} model_inputs The inputs to the model.
320+ * @returns {Promise<MaskedLMOutput>} An object containing the model's output logits for masked language modeling.
321+ */
322+ _call(model_inputs: any): Promise<MaskedLMOutput>;
301323 }
302324 /**
303325 * ConvBERT Model transformer with a sequence classification/regression head on top (a linear layer on top of the pooled output)
304326 */
305327 export class ConvBertForSequenceClassification extends ConvBertPreTrainedModel {
306- /**
307- * Calls the model on new inputs.
308- *
309- * @param {Object} model_inputs The inputs to the model.
310- * @returns {Promise<SequenceClassifierOutput>} An object containing the model's output logits for sequence classification.
311- */
312- _call(model_inputs: any): Promise<SequenceClassifierOutput>;
328+ /**
329+ * Calls the model on new inputs.
330+ *
331+ * @param {Object} model_inputs The inputs to the model.
332+ * @returns {Promise<SequenceClassifierOutput>} An object containing the model's output logits for sequence classification.
333+ */
334+ _call(model_inputs: any): Promise<SequenceClassifierOutput>;
313335 }
314336 /**
315337 * ConvBERT Model with a token classification head on top (a linear layer on top of the hidden-states output)
316338 * e.g. for Named-Entity-Recognition (NER) tasks.
317339 */
318340 export class ConvBertForTokenClassification extends ConvBertPreTrainedModel {
319- /**
320- * Calls the model on new inputs.
321- *
322- * @param {Object} model_inputs The inputs to the model.
323- * @returns {Promise<TokenClassifierOutput>} An object containing the model's output logits for token classification.
324- */
325- _call(model_inputs: any): Promise<TokenClassifierOutput>;
341+ /**
342+ * Calls the model on new inputs.
343+ *
344+ * @param {Object} model_inputs The inputs to the model.
345+ * @returns {Promise<TokenClassifierOutput>} An object containing the model's output logits for token classification.
346+ */
347+ _call(model_inputs: any): Promise<TokenClassifierOutput>;
326348 }
327349 /**
328350 * ConvBERT Model with a span classification head on top for extractive question-answering tasks like SQuAD
329351 * (a linear layers on top of the hidden-states output to compute `span start logits` and `span end logits`)
330352 */
331353 export class ConvBertForQuestionAnswering extends ConvBertPreTrainedModel {
332- /**
333- * Calls the model on new inputs.
334- *
335- * @param {Object} model_inputs The inputs to the model.
336- * @returns {Promise<QuestionAnsweringModelOutput>} An object containing the model's output logits for question answering.
337- */
338- _call(model_inputs: any): Promise<QuestionAnsweringModelOutput>;
339-}
340-export class ElectraPreTrainedModel extends PreTrainedModel {
341-}
354+ /**
355+ * Calls the model on new inputs.
356+ *
357+ * @param {Object} model_inputs The inputs to the model.
358+ * @returns {Promise<QuestionAnsweringModelOutput>} An object containing the model's output logits for question answering.
359+ */
360+ _call(model_inputs: any): Promise<QuestionAnsweringModelOutput>;
361+}
362+export class ElectraPreTrainedModel extends PreTrainedModel {}
342363 /**
343364 * The bare Electra Model transformer outputting raw hidden-states without any specific head on top.
344365 * Identical to the BERT model except that it uses an additional linear layer between the embedding
345366 * layer and the encoder if the hidden size and embedding size are different.
346367 */
347-export class ElectraModel extends ElectraPreTrainedModel {
348-}
368+export class ElectraModel extends ElectraPreTrainedModel {}
349369 /**
350370 * Electra model with a language modeling head on top.
351371 */
352372 export class ElectraForMaskedLM extends ElectraPreTrainedModel {
353- /**
354- * Calls the model on new inputs.
355- *
356- * @param {Object} model_inputs The inputs to the model.
357- * @returns {Promise<MaskedLMOutput>} An object containing the model's output logits for masked language modeling.
358- */
359- _call(model_inputs: any): Promise<MaskedLMOutput>;
373+ /**
374+ * Calls the model on new inputs.
375+ *
376+ * @param {Object} model_inputs The inputs to the model.
377+ * @returns {Promise<MaskedLMOutput>} An object containing the model's output logits for masked language modeling.
378+ */
379+ _call(model_inputs: any): Promise<MaskedLMOutput>;
360380 }
361381 /**
362382 * ELECTRA Model transformer with a sequence classification/regression head on top (a linear layer on top of the pooled output)
363383 */
364384 export class ElectraForSequenceClassification extends ElectraPreTrainedModel {
365- /**
366- * Calls the model on new inputs.
367- *
368- * @param {Object} model_inputs The inputs to the model.
369- * @returns {Promise<SequenceClassifierOutput>} An object containing the model's output logits for sequence classification.
370- */
371- _call(model_inputs: any): Promise<SequenceClassifierOutput>;
385+ /**
386+ * Calls the model on new inputs.
387+ *
388+ * @param {Object} model_inputs The inputs to the model.
389+ * @returns {Promise<SequenceClassifierOutput>} An object containing the model's output logits for sequence classification.
390+ */
391+ _call(model_inputs: any): Promise<SequenceClassifierOutput>;
372392 }
373393 /**
374394 * Electra model with a token classification head on top.
375395 */
376396 export class ElectraForTokenClassification extends ElectraPreTrainedModel {
377- /**
378- * Calls the model on new inputs.
379- *
380- * @param {Object} model_inputs The inputs to the model.
381- * @returns {Promise<TokenClassifierOutput>} An object containing the model's output logits for token classification.
382- */
383- _call(model_inputs: any): Promise<TokenClassifierOutput>;
397+ /**
398+ * Calls the model on new inputs.
399+ *
400+ * @param {Object} model_inputs The inputs to the model.
401+ * @returns {Promise<TokenClassifierOutput>} An object containing the model's output logits for token classification.
402+ */
403+ _call(model_inputs: any): Promise<TokenClassifierOutput>;
384404 }
385405 /**
386406 * LECTRA Model with a span classification head on top for extractive question-answering tasks like SQuAD
387407 * (a linear layers on top of the hidden-states output to compute `span start logits` and `span end logits`).
388408 */
389409 export class ElectraForQuestionAnswering extends ElectraPreTrainedModel {
390- /**
391- * Calls the model on new inputs.
392- *
393- * @param {Object} model_inputs The inputs to the model.
394- * @returns {Promise<QuestionAnsweringModelOutput>} An object containing the model's output logits for question answering.
395- */
396- _call(model_inputs: any): Promise<QuestionAnsweringModelOutput>;
397-}
398-export class CamembertPreTrainedModel extends PreTrainedModel {
399-}
410+ /**
411+ * Calls the model on new inputs.
412+ *
413+ * @param {Object} model_inputs The inputs to the model.
414+ * @returns {Promise<QuestionAnsweringModelOutput>} An object containing the model's output logits for question answering.
415+ */
416+ _call(model_inputs: any): Promise<QuestionAnsweringModelOutput>;
417+}
418+export class CamembertPreTrainedModel extends PreTrainedModel {}
400419 /**
401420 * The bare CamemBERT Model transformer outputting raw hidden-states without any specific head on top.
402421 */
403-export class CamembertModel extends CamembertPreTrainedModel {
404-}
422+export class CamembertModel extends CamembertPreTrainedModel {}
405423 /**
406424 * CamemBERT Model with a `language modeling` head on top.
407425 */
408426 export class CamembertForMaskedLM extends CamembertPreTrainedModel {
409- /**
410- * Calls the model on new inputs.
411- *
412- * @param {Object} model_inputs The inputs to the model.
413- * @returns {Promise<MaskedLMOutput>} An object containing the model's output logits for masked language modeling.
414- */
415- _call(model_inputs: any): Promise<MaskedLMOutput>;
427+ /**
428+ * Calls the model on new inputs.
429+ *
430+ * @param {Object} model_inputs The inputs to the model.
431+ * @returns {Promise<MaskedLMOutput>} An object containing the model's output logits for masked language modeling.
432+ */
433+ _call(model_inputs: any): Promise<MaskedLMOutput>;
416434 }
417435 /**
418436 * CamemBERT Model transformer with a sequence classification/regression head on top (a linear layer on top of the pooled output) e.g. for GLUE tasks.
419437 */
420438 export class CamembertForSequenceClassification extends CamembertPreTrainedModel {
421- /**
422- * Calls the model on new inputs.
423- *
424- * @param {Object} model_inputs The inputs to the model.
425- * @returns {Promise<SequenceClassifierOutput>} An object containing the model's output logits for sequence classification.
426- */
427- _call(model_inputs: any): Promise<SequenceClassifierOutput>;
439+ /**
440+ * Calls the model on new inputs.
441+ *
442+ * @param {Object} model_inputs The inputs to the model.
443+ * @returns {Promise<SequenceClassifierOutput>} An object containing the model's output logits for sequence classification.
444+ */
445+ _call(model_inputs: any): Promise<SequenceClassifierOutput>;
428446 }
429447 /**
430448 * CamemBERT Model with a token classification head on top (a linear layer on top of the hidden-states output) e.g. for Named-Entity-Recognition (NER) tasks.
431449 */
432450 export class CamembertForTokenClassification extends CamembertPreTrainedModel {
433- /**
434- * Calls the model on new inputs.
435- *
436- * @param {Object} model_inputs The inputs to the model.
437- * @returns {Promise<TokenClassifierOutput>} An object containing the model's output logits for token classification.
438- */
439- _call(model_inputs: any): Promise<TokenClassifierOutput>;
451+ /**
452+ * Calls the model on new inputs.
453+ *
454+ * @param {Object} model_inputs The inputs to the model.
455+ * @returns {Promise<TokenClassifierOutput>} An object containing the model's output logits for token classification.
456+ */
457+ _call(model_inputs: any): Promise<TokenClassifierOutput>;
440458 }
441459 /**
442460 * CamemBERT Model with a span classification head on top for extractive question-answering tasks
443461 */
444462 export class CamembertForQuestionAnswering extends CamembertPreTrainedModel {
445- /**
446- * Calls the model on new inputs.
447- *
448- * @param {Object} model_inputs The inputs to the model.
449- * @returns {Promise<QuestionAnsweringModelOutput>} An object containing the model's output logits for question answering.
450- */
451- _call(model_inputs: any): Promise<QuestionAnsweringModelOutput>;
452-}
453-export class DebertaPreTrainedModel extends PreTrainedModel {
454-}
463+ /**
464+ * Calls the model on new inputs.
465+ *
466+ * @param {Object} model_inputs The inputs to the model.
467+ * @returns {Promise<QuestionAnsweringModelOutput>} An object containing the model's output logits for question answering.
468+ */
469+ _call(model_inputs: any): Promise<QuestionAnsweringModelOutput>;
470+}
471+export class DebertaPreTrainedModel extends PreTrainedModel {}
455472 /**
456473 * The bare DeBERTa Model transformer outputting raw hidden-states without any specific head on top.
457474 */
458-export class DebertaModel extends DebertaPreTrainedModel {
459-}
475+export class DebertaModel extends DebertaPreTrainedModel {}
460476 /**
461477 * DeBERTa Model with a `language modeling` head on top.
462478 */
463479 export class DebertaForMaskedLM extends DebertaPreTrainedModel {
464- /**
465- * Calls the model on new inputs.
466- *
467- * @param {Object} model_inputs The inputs to the model.
468- * @returns {Promise<MaskedLMOutput>} An object containing the model's output logits for masked language modeling.
469- */
470- _call(model_inputs: any): Promise<MaskedLMOutput>;
480+ /**
481+ * Calls the model on new inputs.
482+ *
483+ * @param {Object} model_inputs The inputs to the model.
484+ * @returns {Promise<MaskedLMOutput>} An object containing the model's output logits for masked language modeling.
485+ */
486+ _call(model_inputs: any): Promise<MaskedLMOutput>;
471487 }
472488 /**
473489 * DeBERTa Model transformer with a sequence classification/regression head on top (a linear layer on top of the pooled output)
474490 */
475491 export class DebertaForSequenceClassification extends DebertaPreTrainedModel {
476- /**
477- * Calls the model on new inputs.
478- *
479- * @param {Object} model_inputs The inputs to the model.
480- * @returns {Promise<SequenceClassifierOutput>} An object containing the model's output logits for sequence classification.
481- */
482- _call(model_inputs: any): Promise<SequenceClassifierOutput>;
492+ /**
493+ * Calls the model on new inputs.
494+ *
495+ * @param {Object} model_inputs The inputs to the model.
496+ * @returns {Promise<SequenceClassifierOutput>} An object containing the model's output logits for sequence classification.
497+ */
498+ _call(model_inputs: any): Promise<SequenceClassifierOutput>;
483499 }
484500 /**
485501 * DeBERTa Model with a token classification head on top (a linear layer on top of the hidden-states output) e.g. for Named-Entity-Recognition (NER) tasks.
486502 */
487503 export class DebertaForTokenClassification extends DebertaPreTrainedModel {
488- /**
489- * Calls the model on new inputs.
490- *
491- * @param {Object} model_inputs The inputs to the model.
492- * @returns {Promise<TokenClassifierOutput>} An object containing the model's output logits for token classification.
493- */
494- _call(model_inputs: any): Promise<TokenClassifierOutput>;
504+ /**
505+ * Calls the model on new inputs.
506+ *
507+ * @param {Object} model_inputs The inputs to the model.
508+ * @returns {Promise<TokenClassifierOutput>} An object containing the model's output logits for token classification.
509+ */
510+ _call(model_inputs: any): Promise<TokenClassifierOutput>;
495511 }
496512 /**
497513 * DeBERTa Model with a span classification head on top for extractive question-answering tasks like SQuAD (a linear
498514 * layers on top of the hidden-states output to compute `span start logits` and `span end logits`).
499515 */
500516 export class DebertaForQuestionAnswering extends DebertaPreTrainedModel {
501- /**
502- * Calls the model on new inputs.
503- *
504- * @param {Object} model_inputs The inputs to the model.
505- * @returns {Promise<QuestionAnsweringModelOutput>} An object containing the model's output logits for question answering.
506- */
507- _call(model_inputs: any): Promise<QuestionAnsweringModelOutput>;
508-}
509-export class DebertaV2PreTrainedModel extends PreTrainedModel {
510-}
517+ /**
518+ * Calls the model on new inputs.
519+ *
520+ * @param {Object} model_inputs The inputs to the model.
521+ * @returns {Promise<QuestionAnsweringModelOutput>} An object containing the model's output logits for question answering.
522+ */
523+ _call(model_inputs: any): Promise<QuestionAnsweringModelOutput>;
524+}
525+export class DebertaV2PreTrainedModel extends PreTrainedModel {}
511526 /**
512527 * The bare DeBERTa-V2 Model transformer outputting raw hidden-states without any specific head on top.
513528 */
514-export class DebertaV2Model extends DebertaV2PreTrainedModel {
515-}
529+export class DebertaV2Model extends DebertaV2PreTrainedModel {}
516530 /**
517531 * DeBERTa-V2 Model with a `language modeling` head on top.
518532 */
519533 export class DebertaV2ForMaskedLM extends DebertaV2PreTrainedModel {
520- /**
521- * Calls the model on new inputs.
522- *
523- * @param {Object} model_inputs The inputs to the model.
524- * @returns {Promise<MaskedLMOutput>} An object containing the model's output logits for masked language modeling.
525- */
526- _call(model_inputs: any): Promise<MaskedLMOutput>;
534+ /**
535+ * Calls the model on new inputs.
536+ *
537+ * @param {Object} model_inputs The inputs to the model.
538+ * @returns {Promise<MaskedLMOutput>} An object containing the model's output logits for masked language modeling.
539+ */
540+ _call(model_inputs: any): Promise<MaskedLMOutput>;
527541 }
528542 /**
529543 * DeBERTa-V2 Model transformer with a sequence classification/regression head on top (a linear layer on top of the pooled output)
530544 */
531545 export class DebertaV2ForSequenceClassification extends DebertaV2PreTrainedModel {
532- /**
533- * Calls the model on new inputs.
534- *
535- * @param {Object} model_inputs The inputs to the model.
536- * @returns {Promise<SequenceClassifierOutput>} An object containing the model's output logits for sequence classification.
537- */
538- _call(model_inputs: any): Promise<SequenceClassifierOutput>;
546+ /**
547+ * Calls the model on new inputs.
548+ *
549+ * @param {Object} model_inputs The inputs to the model.
550+ * @returns {Promise<SequenceClassifierOutput>} An object containing the model's output logits for sequence classification.
551+ */
552+ _call(model_inputs: any): Promise<SequenceClassifierOutput>;
539553 }
540554 /**
541555 * DeBERTa-V2 Model with a token classification head on top (a linear layer on top of the hidden-states output) e.g. for Named-Entity-Recognition (NER) tasks.
542556 */
543557 export class DebertaV2ForTokenClassification extends DebertaV2PreTrainedModel {
544- /**
545- * Calls the model on new inputs.
546- *
547- * @param {Object} model_inputs The inputs to the model.
548- * @returns {Promise<TokenClassifierOutput>} An object containing the model's output logits for token classification.
549- */
550- _call(model_inputs: any): Promise<TokenClassifierOutput>;
558+ /**
559+ * Calls the model on new inputs.
560+ *
561+ * @param {Object} model_inputs The inputs to the model.
562+ * @returns {Promise<TokenClassifierOutput>} An object containing the model's output logits for token classification.
563+ */
564+ _call(model_inputs: any): Promise<TokenClassifierOutput>;
551565 }
552566 /**
553567 * DeBERTa-V2 Model with a span classification head on top for extractive question-answering tasks like SQuAD (a linear
554568 * layers on top of the hidden-states output to compute `span start logits` and `span end logits`).
555569 */
556570 export class DebertaV2ForQuestionAnswering extends DebertaV2PreTrainedModel {
557- /**
558- * Calls the model on new inputs.
559- *
560- * @param {Object} model_inputs The inputs to the model.
561- * @returns {Promise<QuestionAnsweringModelOutput>} An object containing the model's output logits for question answering.
562- */
563- _call(model_inputs: any): Promise<QuestionAnsweringModelOutput>;
564-}
565-export class DistilBertPreTrainedModel extends PreTrainedModel {
566-}
567-export class DistilBertModel extends DistilBertPreTrainedModel {
568-}
571+ /**
572+ * Calls the model on new inputs.
573+ *
574+ * @param {Object} model_inputs The inputs to the model.
575+ * @returns {Promise<QuestionAnsweringModelOutput>} An object containing the model's output logits for question answering.
576+ */
577+ _call(model_inputs: any): Promise<QuestionAnsweringModelOutput>;
578+}
579+export class DistilBertPreTrainedModel extends PreTrainedModel {}
580+export class DistilBertModel extends DistilBertPreTrainedModel {}
569581 /**
570582 * DistilBertForSequenceClassification is a class representing a DistilBERT model for sequence classification.
571583 */
572584 export class DistilBertForSequenceClassification extends DistilBertPreTrainedModel {
573- /**
574- * Calls the model on new inputs.
575- *
576- * @param {Object} model_inputs The inputs to the model.
577- * @returns {Promise<SequenceClassifierOutput>} An object containing the model's output logits for sequence classification.
578- */
579- _call(model_inputs: any): Promise<SequenceClassifierOutput>;
585+ /**
586+ * Calls the model on new inputs.
587+ *
588+ * @param {Object} model_inputs The inputs to the model.
589+ * @returns {Promise<SequenceClassifierOutput>} An object containing the model's output logits for sequence classification.
590+ */
591+ _call(model_inputs: any): Promise<SequenceClassifierOutput>;
580592 }
581593 /**
582594 * DistilBertForTokenClassification is a class representing a DistilBERT model for token classification.
583595 */
584596 export class DistilBertForTokenClassification extends DistilBertPreTrainedModel {
585- /**
586- * Calls the model on new inputs.
587- *
588- * @param {Object} model_inputs The inputs to the model.
589- * @returns {Promise<TokenClassifierOutput>} An object containing the model's output logits for token classification.
590- */
591- _call(model_inputs: any): Promise<TokenClassifierOutput>;
597+ /**
598+ * Calls the model on new inputs.
599+ *
600+ * @param {Object} model_inputs The inputs to the model.
601+ * @returns {Promise<TokenClassifierOutput>} An object containing the model's output logits for token classification.
602+ */
603+ _call(model_inputs: any): Promise<TokenClassifierOutput>;
592604 }
593605 /**
594606 * DistilBertForQuestionAnswering is a class representing a DistilBERT model for question answering.
595607 */
596608 export class DistilBertForQuestionAnswering extends DistilBertPreTrainedModel {
597- /**
598- * Calls the model on new inputs.
599- *
600- * @param {Object} model_inputs The inputs to the model.
601- * @returns {Promise<QuestionAnsweringModelOutput>} An object containing the model's output logits for question answering.
602- */
603- _call(model_inputs: any): Promise<QuestionAnsweringModelOutput>;
609+ /**
610+ * Calls the model on new inputs.
611+ *
612+ * @param {Object} model_inputs The inputs to the model.
613+ * @returns {Promise<QuestionAnsweringModelOutput>} An object containing the model's output logits for question answering.
614+ */
615+ _call(model_inputs: any): Promise<QuestionAnsweringModelOutput>;
604616 }
605617 /**
606618 * DistilBertForMaskedLM is a class representing a DistilBERT model for masking task.
607619 */
608620 export class DistilBertForMaskedLM extends DistilBertPreTrainedModel {
609- /**
610- * Calls the model on new inputs.
611- *
612- * @param {Object} model_inputs The inputs to the model.
613- * @returns {Promise<MaskedLMOutput>} returned object
614- */
615- _call(model_inputs: any): Promise<MaskedLMOutput>;
616-}
617-export class EsmPreTrainedModel extends PreTrainedModel {
618-}
621+ /**
622+ * Calls the model on new inputs.
623+ *
624+ * @param {Object} model_inputs The inputs to the model.
625+ * @returns {Promise<MaskedLMOutput>} returned object
626+ */
627+ _call(model_inputs: any): Promise<MaskedLMOutput>;
628+}
629+export class EsmPreTrainedModel extends PreTrainedModel {}
619630 /**
620631 * The bare ESM Model transformer outputting raw hidden-states without any specific head on top.
621632 */
622-export class EsmModel extends EsmPreTrainedModel {
623-}
633+export class EsmModel extends EsmPreTrainedModel {}
624634 /**
625635 * ESM Model with a `language modeling` head on top.
626636 */
627637 export class EsmForMaskedLM extends EsmPreTrainedModel {
628- /**
629- * Calls the model on new inputs.
630- *
631- * @param {Object} model_inputs The inputs to the model.
632- * @returns {Promise<MaskedLMOutput>} An object containing the model's output logits for masked language modeling.
633- */
634- _call(model_inputs: any): Promise<MaskedLMOutput>;
638+ /**
639+ * Calls the model on new inputs.
640+ *
641+ * @param {Object} model_inputs The inputs to the model.
642+ * @returns {Promise<MaskedLMOutput>} An object containing the model's output logits for masked language modeling.
643+ */
644+ _call(model_inputs: any): Promise<MaskedLMOutput>;
635645 }
636646 /**
637647 * ESM Model transformer with a sequence classification/regression head on top (a linear layer on top of the pooled output)
638648 */
639649 export class EsmForSequenceClassification extends EsmPreTrainedModel {
640- /**
641- * Calls the model on new inputs.
642- *
643- * @param {Object} model_inputs The inputs to the model.
644- * @returns {Promise<SequenceClassifierOutput>} An object containing the model's output logits for sequence classification.
645- */
646- _call(model_inputs: any): Promise<SequenceClassifierOutput>;
650+ /**
651+ * Calls the model on new inputs.
652+ *
653+ * @param {Object} model_inputs The inputs to the model.
654+ * @returns {Promise<SequenceClassifierOutput>} An object containing the model's output logits for sequence classification.
655+ */
656+ _call(model_inputs: any): Promise<SequenceClassifierOutput>;
647657 }
648658 /**
649659 * ESM Model with a token classification head on top (a linear layer on top of the hidden-states output)
650660 * e.g. for Named-Entity-Recognition (NER) tasks.
651661 */
652662 export class EsmForTokenClassification extends EsmPreTrainedModel {
653- /**
654- * Calls the model on new inputs.
655- *
656- * @param {Object} model_inputs The inputs to the model.
657- * @returns {Promise<TokenClassifierOutput>} An object containing the model's output logits for token classification.
658- */
659- _call(model_inputs: any): Promise<TokenClassifierOutput>;
660-}
661-export class MobileBertPreTrainedModel extends PreTrainedModel {
662-}
663-export class MobileBertModel extends MobileBertPreTrainedModel {
664-}
663+ /**
664+ * Calls the model on new inputs.
665+ *
666+ * @param {Object} model_inputs The inputs to the model.
667+ * @returns {Promise<TokenClassifierOutput>} An object containing the model's output logits for token classification.
668+ */
669+ _call(model_inputs: any): Promise<TokenClassifierOutput>;
670+}
671+export class MobileBertPreTrainedModel extends PreTrainedModel {}
672+export class MobileBertModel extends MobileBertPreTrainedModel {}
665673 /**
666674 * MobileBertForMaskedLM is a class representing a MobileBERT model for masking task.
667675 */
668676 export class MobileBertForMaskedLM extends MobileBertPreTrainedModel {
669- /**
670- * Calls the model on new inputs.
671- *
672- * @param {Object} model_inputs The inputs to the model.
673- * @returns {Promise<MaskedLMOutput>} returned object
674- */
675- _call(model_inputs: any): Promise<MaskedLMOutput>;
677+ /**
678+ * Calls the model on new inputs.
679+ *
680+ * @param {Object} model_inputs The inputs to the model.
681+ * @returns {Promise<MaskedLMOutput>} returned object
682+ */
683+ _call(model_inputs: any): Promise<MaskedLMOutput>;
676684 }
677685 /**
678686 * MobileBert Model transformer with a sequence classification/regression head on top (a linear layer on top of the pooled output)
679687 */
680688 export class MobileBertForSequenceClassification extends MobileBertPreTrainedModel {
681- /**
682- * Calls the model on new inputs.
683- *
684- * @param {Object} model_inputs The inputs to the model.
685- * @returns {Promise<SequenceClassifierOutput>} returned object
686- */
687- _call(model_inputs: any): Promise<SequenceClassifierOutput>;
689+ /**
690+ * Calls the model on new inputs.
691+ *
692+ * @param {Object} model_inputs The inputs to the model.
693+ * @returns {Promise<SequenceClassifierOutput>} returned object
694+ */
695+ _call(model_inputs: any): Promise<SequenceClassifierOutput>;
688696 }
689697 /**
690698 * MobileBert Model with a span classification head on top for extractive question-answering tasks
691699 */
692700 export class MobileBertForQuestionAnswering extends MobileBertPreTrainedModel {
693- /**
694- * Calls the model on new inputs.
695- *
696- * @param {Object} model_inputs The inputs to the model.
697- * @returns {Promise<QuestionAnsweringModelOutput>} returned object
698- */
699- _call(model_inputs: any): Promise<QuestionAnsweringModelOutput>;
700-}
701-export class MPNetPreTrainedModel extends PreTrainedModel {
702-}
701+ /**
702+ * Calls the model on new inputs.
703+ *
704+ * @param {Object} model_inputs The inputs to the model.
705+ * @returns {Promise<QuestionAnsweringModelOutput>} returned object
706+ */
707+ _call(model_inputs: any): Promise<QuestionAnsweringModelOutput>;
708+}
709+export class MPNetPreTrainedModel extends PreTrainedModel {}
703710 /**
704711 * The bare MPNet Model transformer outputting raw hidden-states without any specific head on top.
705712 */
706-export class MPNetModel extends MPNetPreTrainedModel {
707-}
713+export class MPNetModel extends MPNetPreTrainedModel {}
708714 /**
709715 * MPNetForMaskedLM is a class representing a MPNet model for masked language modeling.
710716 */
711717 export class MPNetForMaskedLM extends MPNetPreTrainedModel {
712- /**
713- * Calls the model on new inputs.
714- *
715- * @param {Object} model_inputs The inputs to the model.
716- * @returns {Promise<MaskedLMOutput>} An object containing the model's output logits for masked language modeling.
717- */
718- _call(model_inputs: any): Promise<MaskedLMOutput>;
718+ /**
719+ * Calls the model on new inputs.
720+ *
721+ * @param {Object} model_inputs The inputs to the model.
722+ * @returns {Promise<MaskedLMOutput>} An object containing the model's output logits for masked language modeling.
723+ */
724+ _call(model_inputs: any): Promise<MaskedLMOutput>;
719725 }
720726 /**
721727 * MPNetForSequenceClassification is a class representing a MPNet model for sequence classification.
722728 */
723729 export class MPNetForSequenceClassification extends MPNetPreTrainedModel {
724- /**
725- * Calls the model on new inputs.
726- *
727- * @param {Object} model_inputs The inputs to the model.
728- * @returns {Promise<SequenceClassifierOutput>} An object containing the model's output logits for sequence classification.
729- */
730- _call(model_inputs: any): Promise<SequenceClassifierOutput>;
730+ /**
731+ * Calls the model on new inputs.
732+ *
733+ * @param {Object} model_inputs The inputs to the model.
734+ * @returns {Promise<SequenceClassifierOutput>} An object containing the model's output logits for sequence classification.
735+ */
736+ _call(model_inputs: any): Promise<SequenceClassifierOutput>;
731737 }
732738 /**
733739 * MPNetForTokenClassification is a class representing a MPNet model for token classification.
734740 */
735741 export class MPNetForTokenClassification extends MPNetPreTrainedModel {
736- /**
737- * Calls the model on new inputs.
738- *
739- * @param {Object} model_inputs The inputs to the model.
740- * @returns {Promise<TokenClassifierOutput>} An object containing the model's output logits for token classification.
741- */
742- _call(model_inputs: any): Promise<TokenClassifierOutput>;
742+ /**
743+ * Calls the model on new inputs.
744+ *
745+ * @param {Object} model_inputs The inputs to the model.
746+ * @returns {Promise<TokenClassifierOutput>} An object containing the model's output logits for token classification.
747+ */
748+ _call(model_inputs: any): Promise<TokenClassifierOutput>;
743749 }
744750 /**
745751 * MPNetForQuestionAnswering is a class representing a MPNet model for question answering.
746752 */
747753 export class MPNetForQuestionAnswering extends MPNetPreTrainedModel {
748- /**
749- * Calls the model on new inputs.
750- *
751- * @param {Object} model_inputs The inputs to the model.
752- * @returns {Promise<QuestionAnsweringModelOutput>} An object containing the model's output logits for question answering.
753- */
754- _call(model_inputs: any): Promise<QuestionAnsweringModelOutput>;
755-}
756-export class SqueezeBertPreTrainedModel extends PreTrainedModel {
757-}
758-export class SqueezeBertModel extends SqueezeBertPreTrainedModel {
759-}
754+ /**
755+ * Calls the model on new inputs.
756+ *
757+ * @param {Object} model_inputs The inputs to the model.
758+ * @returns {Promise<QuestionAnsweringModelOutput>} An object containing the model's output logits for question answering.
759+ */
760+ _call(model_inputs: any): Promise<QuestionAnsweringModelOutput>;
761+}
762+export class SqueezeBertPreTrainedModel extends PreTrainedModel {}
763+export class SqueezeBertModel extends SqueezeBertPreTrainedModel {}
760764 export class SqueezeBertForMaskedLM extends SqueezeBertPreTrainedModel {
761- /**
762- * Calls the model on new inputs.
763- *
764- * @param {Object} model_inputs The inputs to the model.
765- * @returns {Promise<MaskedLMOutput>} returned object
766- */
767- _call(model_inputs: any): Promise<MaskedLMOutput>;
765+ /**
766+ * Calls the model on new inputs.
767+ *
768+ * @param {Object} model_inputs The inputs to the model.
769+ * @returns {Promise<MaskedLMOutput>} returned object
770+ */
771+ _call(model_inputs: any): Promise<MaskedLMOutput>;
768772 }
769773 export class SqueezeBertForSequenceClassification extends SqueezeBertPreTrainedModel {
770- /**
771- * Calls the model on new inputs.
772- *
773- * @param {Object} model_inputs The inputs to the model.
774- * @returns {Promise<SequenceClassifierOutput>} returned object
775- */
776- _call(model_inputs: any): Promise<SequenceClassifierOutput>;
774+ /**
775+ * Calls the model on new inputs.
776+ *
777+ * @param {Object} model_inputs The inputs to the model.
778+ * @returns {Promise<SequenceClassifierOutput>} returned object
779+ */
780+ _call(model_inputs: any): Promise<SequenceClassifierOutput>;
777781 }
778782 export class SqueezeBertForQuestionAnswering extends SqueezeBertPreTrainedModel {
779- /**
780- * Calls the model on new inputs.
781- *
782- * @param {Object} model_inputs The inputs to the model.
783- * @returns {Promise<QuestionAnsweringModelOutput>} returned object
784- */
785- _call(model_inputs: any): Promise<QuestionAnsweringModelOutput>;
786-}
787-export class AlbertPreTrainedModel extends PreTrainedModel {
788-}
789-export class AlbertModel extends AlbertPreTrainedModel {
790-}
783+ /**
784+ * Calls the model on new inputs.
785+ *
786+ * @param {Object} model_inputs The inputs to the model.
787+ * @returns {Promise<QuestionAnsweringModelOutput>} returned object
788+ */
789+ _call(model_inputs: any): Promise<QuestionAnsweringModelOutput>;
790+}
791+export class AlbertPreTrainedModel extends PreTrainedModel {}
792+export class AlbertModel extends AlbertPreTrainedModel {}
791793 export class AlbertForSequenceClassification extends AlbertPreTrainedModel {
792- /**
793- * Calls the model on new inputs.
794- *
795- * @param {Object} model_inputs The inputs to the model.
796- * @returns {Promise<SequenceClassifierOutput>} returned object
797- */
798- _call(model_inputs: any): Promise<SequenceClassifierOutput>;
794+ /**
795+ * Calls the model on new inputs.
796+ *
797+ * @param {Object} model_inputs The inputs to the model.
798+ * @returns {Promise<SequenceClassifierOutput>} returned object
799+ */
800+ _call(model_inputs: any): Promise<SequenceClassifierOutput>;
799801 }
800802 export class AlbertForQuestionAnswering extends AlbertPreTrainedModel {
801- /**
802- * Calls the model on new inputs.
803- *
804- * @param {Object} model_inputs The inputs to the model.
805- * @returns {Promise<QuestionAnsweringModelOutput>} returned object
806- */
807- _call(model_inputs: any): Promise<QuestionAnsweringModelOutput>;
803+ /**
804+ * Calls the model on new inputs.
805+ *
806+ * @param {Object} model_inputs The inputs to the model.
807+ * @returns {Promise<QuestionAnsweringModelOutput>} returned object
808+ */
809+ _call(model_inputs: any): Promise<QuestionAnsweringModelOutput>;
808810 }
809811 export class AlbertForMaskedLM extends AlbertPreTrainedModel {
810- /**
811- * Calls the model on new inputs.
812- *
813- * @param {Object} model_inputs The inputs to the model.
814- * @returns {Promise<MaskedLMOutput>} returned object
815- */
816- _call(model_inputs: any): Promise<MaskedLMOutput>;
817-}
818-export class T5PreTrainedModel extends PreTrainedModel {
819-}
820-export class T5Model extends T5PreTrainedModel {
821-}
812+ /**
813+ * Calls the model on new inputs.
814+ *
815+ * @param {Object} model_inputs The inputs to the model.
816+ * @returns {Promise<MaskedLMOutput>} returned object
817+ */
818+ _call(model_inputs: any): Promise<MaskedLMOutput>;
819+}
820+export class T5PreTrainedModel extends PreTrainedModel {}
821+export class T5Model extends T5PreTrainedModel {}
822822 /**
823823 * T5Model is a class representing a T5 model for conditional generation.
824824 */
825825 export class T5ForConditionalGeneration extends T5PreTrainedModel {
826- /**
827- * Creates a new instance of the `T5ForConditionalGeneration` class.
828- * @param {Object} config The model configuration.
829- * @param {any} session session for the model.
830- * @param {any} decoder_merged_session session for the decoder.
831- * @param {GenerationConfig} generation_config The generation configuration.
832- */
833- constructor(config: any, session: any, decoder_merged_session: any, generation_config: new (kwargs?: import("./utils/generation.js").GenerationConfigType) => import("./utils/generation.js").GenerationConfigType);
834- decoder_merged_session: any;
835- generation_config: new (kwargs?: import("./utils/generation.js").GenerationConfigType) => import("./utils/generation.js").GenerationConfigType;
836- num_decoder_layers: any;
837- num_decoder_heads: any;
838- decoder_dim_kv: any;
839- num_encoder_layers: any;
840- num_encoder_heads: any;
841- encoder_dim_kv: any;
826+ /**
827+ * Creates a new instance of the `T5ForConditionalGeneration` class.
828+ * @param {Object} config The model configuration.
829+ * @param {any} session session for the model.
830+ * @param {any} decoder_merged_session session for the decoder.
831+ * @param {GenerationConfig} generation_config The generation configuration.
832+ */
833+ constructor(
834+ config: any,
835+ session: any,
836+ decoder_merged_session: any,
837+ generation_config: new (
838+ kwargs?: import("./utils/generation.js").GenerationConfigType,
839+ ) => import("./utils/generation.js").GenerationConfigType,
840+ );
841+ decoder_merged_session: any;
842+ generation_config: new (
843+ kwargs?: import("./utils/generation.js").GenerationConfigType,
844+ ) => import("./utils/generation.js").GenerationConfigType;
845+ num_decoder_layers: any;
846+ num_decoder_heads: any;
847+ decoder_dim_kv: any;
848+ num_encoder_layers: any;
849+ num_encoder_heads: any;
850+ encoder_dim_kv: any;
842851 }
843852 /**
844853 * An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained models.
845854 */
846-export class LongT5PreTrainedModel extends PreTrainedModel {
847-}
855+export class LongT5PreTrainedModel extends PreTrainedModel {}
848856 /**
849857 * The bare LONGT5 Model transformer outputting raw hidden-states without any specific head on top.
850858 */
851-export class LongT5Model extends LongT5PreTrainedModel {
852-}
859+export class LongT5Model extends LongT5PreTrainedModel {}
853860 /**
854861 * LONGT5 Model with a `language modeling` head on top.
855862 */
856863 export class LongT5ForConditionalGeneration extends LongT5PreTrainedModel {
857- /**
858- * Creates a new instance of the `LongT5ForConditionalGeneration` class.
859- * @param {Object} config The model configuration.
860- * @param {any} session session for the model.
861- * @param {any} decoder_merged_session session for the decoder.
862- * @param {GenerationConfig} generation_config The generation configuration.
863- */
864- constructor(config: any, session: any, decoder_merged_session: any, generation_config: new (kwargs?: import("./utils/generation.js").GenerationConfigType) => import("./utils/generation.js").GenerationConfigType);
865- decoder_merged_session: any;
866- generation_config: new (kwargs?: import("./utils/generation.js").GenerationConfigType) => import("./utils/generation.js").GenerationConfigType;
867- num_decoder_layers: any;
868- num_decoder_heads: any;
869- decoder_dim_kv: any;
870- num_encoder_layers: any;
871- num_encoder_heads: any;
872- encoder_dim_kv: any;
873-}
874-export class MT5PreTrainedModel extends PreTrainedModel {
875-}
876-export class MT5Model extends MT5PreTrainedModel {
877-}
864+ /**
865+ * Creates a new instance of the `LongT5ForConditionalGeneration` class.
866+ * @param {Object} config The model configuration.
867+ * @param {any} session session for the model.
868+ * @param {any} decoder_merged_session session for the decoder.
869+ * @param {GenerationConfig} generation_config The generation configuration.
870+ */
871+ constructor(
872+ config: any,
873+ session: any,
874+ decoder_merged_session: any,
875+ generation_config: new (
876+ kwargs?: import("./utils/generation.js").GenerationConfigType,
877+ ) => import("./utils/generation.js").GenerationConfigType,
878+ );
879+ decoder_merged_session: any;
880+ generation_config: new (
881+ kwargs?: import("./utils/generation.js").GenerationConfigType,
882+ ) => import("./utils/generation.js").GenerationConfigType;
883+ num_decoder_layers: any;
884+ num_decoder_heads: any;
885+ decoder_dim_kv: any;
886+ num_encoder_layers: any;
887+ num_encoder_heads: any;
888+ encoder_dim_kv: any;
889+}
890+export class MT5PreTrainedModel extends PreTrainedModel {}
891+export class MT5Model extends MT5PreTrainedModel {}
878892 /**
879893 * A class representing a conditional sequence-to-sequence model based on the MT5 architecture.
880894 */
881895 export class MT5ForConditionalGeneration extends MT5PreTrainedModel {
882- /**
883- * Creates a new instance of the `MT5ForConditionalGeneration` class.
884- * @param {any} config The model configuration.
885- * @param {any} session The ONNX session containing the encoder weights.
886- * @param {any} decoder_merged_session The ONNX session containing the merged decoder weights.
887- * @param {GenerationConfig} generation_config The generation configuration.
888- */
889- constructor(config: any, session: any, decoder_merged_session: any, generation_config: new (kwargs?: import("./utils/generation.js").GenerationConfigType) => import("./utils/generation.js").GenerationConfigType);
890- decoder_merged_session: any;
891- generation_config: new (kwargs?: import("./utils/generation.js").GenerationConfigType) => import("./utils/generation.js").GenerationConfigType;
892- num_decoder_layers: any;
893- num_decoder_heads: any;
894- decoder_dim_kv: any;
895- num_encoder_layers: any;
896- num_encoder_heads: any;
897- encoder_dim_kv: any;
898-}
899-export class BartPretrainedModel extends PreTrainedModel {
900-}
896+ /**
897+ * Creates a new instance of the `MT5ForConditionalGeneration` class.
898+ * @param {any} config The model configuration.
899+ * @param {any} session The ONNX session containing the encoder weights.
900+ * @param {any} decoder_merged_session The ONNX session containing the merged decoder weights.
901+ * @param {GenerationConfig} generation_config The generation configuration.
902+ */
903+ constructor(
904+ config: any,
905+ session: any,
906+ decoder_merged_session: any,
907+ generation_config: new (
908+ kwargs?: import("./utils/generation.js").GenerationConfigType,
909+ ) => import("./utils/generation.js").GenerationConfigType,
910+ );
911+ decoder_merged_session: any;
912+ generation_config: new (
913+ kwargs?: import("./utils/generation.js").GenerationConfigType,
914+ ) => import("./utils/generation.js").GenerationConfigType;
915+ num_decoder_layers: any;
916+ num_decoder_heads: any;
917+ decoder_dim_kv: any;
918+ num_encoder_layers: any;
919+ num_encoder_heads: any;
920+ encoder_dim_kv: any;
921+}
922+export class BartPretrainedModel extends PreTrainedModel {}
901923 /**
902924 * The bare BART Model outputting raw hidden-states without any specific head on top.
903925 */
904-export class BartModel extends BartPretrainedModel {
905-}
926+export class BartModel extends BartPretrainedModel {}
906927 /**
907928 * The BART Model with a language modeling head. Can be used for summarization.
908929 */
909930 export class BartForConditionalGeneration extends BartPretrainedModel {
910- /**
911- * Creates a new instance of the `BartForConditionalGeneration` class.
912- * @param {Object} config The configuration object for the Bart model.
913- * @param {Object} session The ONNX session used to execute the model.
914- * @param {Object} decoder_merged_session The ONNX session used to execute the decoder.
915- * @param {Object} generation_config The generation configuration object.
916- */
917- constructor(config: any, session: any, decoder_merged_session: any, generation_config: any);
918- decoder_merged_session: any;
919- generation_config: any;
920- num_decoder_layers: any;
921- num_decoder_heads: any;
922- decoder_dim_kv: number;
923- num_encoder_layers: any;
924- num_encoder_heads: any;
925- encoder_dim_kv: number;
931+ /**
932+ * Creates a new instance of the `BartForConditionalGeneration` class.
933+ * @param {Object} config The configuration object for the Bart model.
934+ * @param {Object} session The ONNX session used to execute the model.
935+ * @param {Object} decoder_merged_session The ONNX session used to execute the decoder.
936+ * @param {Object} generation_config The generation configuration object.
937+ */
938+ constructor(
939+ config: any,
940+ session: any,
941+ decoder_merged_session: any,
942+ generation_config: any,
943+ );
944+ decoder_merged_session: any;
945+ generation_config: any;
946+ num_decoder_layers: any;
947+ num_decoder_heads: any;
948+ decoder_dim_kv: number;
949+ num_encoder_layers: any;
950+ num_encoder_heads: any;
951+ encoder_dim_kv: number;
926952 }
927953 /**
928954 * Bart model with a sequence classification/head on top (a linear layer on top of the pooled output)
929955 */
930956 export class BartForSequenceClassification extends BartPretrainedModel {
931- /**
932- * Calls the model on new inputs.
933- *
934- * @param {Object} model_inputs The inputs to the model.
935- * @returns {Promise<SequenceClassifierOutput>} An object containing the model's output logits for sequence classification.
936- */
937- _call(model_inputs: any): Promise<SequenceClassifierOutput>;
938-}
939-export class MBartPreTrainedModel extends PreTrainedModel {
940-}
957+ /**
958+ * Calls the model on new inputs.
959+ *
960+ * @param {Object} model_inputs The inputs to the model.
961+ * @returns {Promise<SequenceClassifierOutput>} An object containing the model's output logits for sequence classification.
962+ */
963+ _call(model_inputs: any): Promise<SequenceClassifierOutput>;
964+}
965+export class MBartPreTrainedModel extends PreTrainedModel {}
941966 /**
942967 * The bare MBART Model outputting raw hidden-states without any specific head on top.
943968 */
944-export class MBartModel extends MBartPreTrainedModel {
945-}
969+export class MBartModel extends MBartPreTrainedModel {}
946970 /**
947971 * The MBART Model with a language modeling head. Can be used for summarization, after fine-tuning the pretrained models.
948972 */
949973 export class MBartForConditionalGeneration extends MBartPreTrainedModel {
950- /**
951- * Creates a new instance of the `MBartForConditionalGeneration` class.
952- * @param {Object} config The configuration object for the Bart model.
953- * @param {Object} session The ONNX session used to execute the model.
954- * @param {Object} decoder_merged_session The ONNX session used to execute the decoder.
955- * @param {Object} generation_config The generation configuration object.
956- */
957- constructor(config: any, session: any, decoder_merged_session: any, generation_config: any);
958- decoder_merged_session: any;
959- generation_config: any;
960- num_decoder_layers: any;
961- num_decoder_heads: any;
962- decoder_dim_kv: number;
963- num_encoder_layers: any;
964- num_encoder_heads: any;
965- encoder_dim_kv: number;
974+ /**
975+ * Creates a new instance of the `MBartForConditionalGeneration` class.
976+ * @param {Object} config The configuration object for the Bart model.
977+ * @param {Object} session The ONNX session used to execute the model.
978+ * @param {Object} decoder_merged_session The ONNX session used to execute the decoder.
979+ * @param {Object} generation_config The generation configuration object.
980+ */
981+ constructor(
982+ config: any,
983+ session: any,
984+ decoder_merged_session: any,
985+ generation_config: any,
986+ );
987+ decoder_merged_session: any;
988+ generation_config: any;
989+ num_decoder_layers: any;
990+ num_decoder_heads: any;
991+ decoder_dim_kv: number;
992+ num_encoder_layers: any;
993+ num_encoder_heads: any;
994+ encoder_dim_kv: number;
966995 }
967996 /**
968997 * MBart model with a sequence classification/head on top (a linear layer on top of the pooled output).
969998 */
970999 export class MBartForSequenceClassification extends MBartPreTrainedModel {
971- /**
972- * Calls the model on new inputs.
973- *
974- * @param {Object} model_inputs The inputs to the model.
975- * @returns {Promise<SequenceClassifierOutput>} An object containing the model's output logits for sequence classification.
976- */
977- _call(model_inputs: any): Promise<SequenceClassifierOutput>;
1000+ /**
1001+ * Calls the model on new inputs.
1002+ *
1003+ * @param {Object} model_inputs The inputs to the model.
1004+ * @returns {Promise<SequenceClassifierOutput>} An object containing the model's output logits for sequence classification.
1005+ */
1006+ _call(model_inputs: any): Promise<SequenceClassifierOutput>;
9781007 }
9791008 export class MBartForCausalLM extends MBartPreTrainedModel {
980- /**
981- * Creates a new instance of the `MBartForCausalLM` class.
982- * @param {Object} config Configuration object for the model.
983- * @param {Object} decoder_merged_session ONNX Session object for the decoder.
984- * @param {Object} generation_config Configuration object for the generation process.
985- */
986- constructor(config: any, decoder_merged_session: any, generation_config: any);
987- generation_config: any;
988- num_decoder_layers: any;
989- num_decoder_heads: any;
990- decoder_dim_kv: number;
991- num_encoder_layers: any;
992- num_encoder_heads: any;
993- encoder_dim_kv: number;
994-}
995-export class BlenderbotPreTrainedModel extends PreTrainedModel {
996-}
1009+ /**
1010+ * Creates a new instance of the `MBartForCausalLM` class.
1011+ * @param {Object} config Configuration object for the model.
1012+ * @param {Object} decoder_merged_session ONNX Session object for the decoder.
1013+ * @param {Object} generation_config Configuration object for the generation process.
1014+ */
1015+ constructor(config: any, decoder_merged_session: any, generation_config: any);
1016+ generation_config: any;
1017+ num_decoder_layers: any;
1018+ num_decoder_heads: any;
1019+ decoder_dim_kv: number;
1020+ num_encoder_layers: any;
1021+ num_encoder_heads: any;
1022+ encoder_dim_kv: number;
1023+}
1024+export class BlenderbotPreTrainedModel extends PreTrainedModel {}
9971025 /**
9981026 * The bare Blenderbot Model outputting raw hidden-states without any specific head on top.
9991027 */
1000-export class BlenderbotModel extends BlenderbotPreTrainedModel {
1001-}
1028+export class BlenderbotModel extends BlenderbotPreTrainedModel {}
10021029 /**
10031030 * The Blenderbot Model with a language modeling head. Can be used for summarization.
10041031 */
10051032 export class BlenderbotForConditionalGeneration extends BlenderbotPreTrainedModel {
1006- /**
1007- * Creates a new instance of the `BlenderbotForConditionalGeneration` class.
1008- * @param {any} config The model configuration.
1009- * @param {any} session The ONNX session containing the encoder weights.
1010- * @param {any} decoder_merged_session The ONNX session containing the merged decoder weights.
1011- * @param {GenerationConfig} generation_config The generation configuration.
1012- */
1013- constructor(config: any, session: any, decoder_merged_session: any, generation_config: new (kwargs?: import("./utils/generation.js").GenerationConfigType) => import("./utils/generation.js").GenerationConfigType);
1014- decoder_merged_session: any;
1015- generation_config: new (kwargs?: import("./utils/generation.js").GenerationConfigType) => import("./utils/generation.js").GenerationConfigType;
1016- num_decoder_layers: any;
1017- num_decoder_heads: any;
1018- decoder_dim_kv: number;
1019- num_encoder_layers: any;
1020- num_encoder_heads: any;
1021- encoder_dim_kv: number;
1022-}
1023-export class BlenderbotSmallPreTrainedModel extends PreTrainedModel {
1024-}
1033+ /**
1034+ * Creates a new instance of the `BlenderbotForConditionalGeneration` class.
1035+ * @param {any} config The model configuration.
1036+ * @param {any} session The ONNX session containing the encoder weights.
1037+ * @param {any} decoder_merged_session The ONNX session containing the merged decoder weights.
1038+ * @param {GenerationConfig} generation_config The generation configuration.
1039+ */
1040+ constructor(
1041+ config: any,
1042+ session: any,
1043+ decoder_merged_session: any,
1044+ generation_config: new (
1045+ kwargs?: import("./utils/generation.js").GenerationConfigType,
1046+ ) => import("./utils/generation.js").GenerationConfigType,
1047+ );
1048+ decoder_merged_session: any;
1049+ generation_config: new (
1050+ kwargs?: import("./utils/generation.js").GenerationConfigType,
1051+ ) => import("./utils/generation.js").GenerationConfigType;
1052+ num_decoder_layers: any;
1053+ num_decoder_heads: any;
1054+ decoder_dim_kv: number;
1055+ num_encoder_layers: any;
1056+ num_encoder_heads: any;
1057+ encoder_dim_kv: number;
1058+}
1059+export class BlenderbotSmallPreTrainedModel extends PreTrainedModel {}
10251060 /**
10261061 * The bare BlenderbotSmall Model outputting raw hidden-states without any specific head on top.
10271062 */
1028-export class BlenderbotSmallModel extends BlenderbotSmallPreTrainedModel {
1029-}
1063+export class BlenderbotSmallModel extends BlenderbotSmallPreTrainedModel {}
10301064 /**
10311065 * The BlenderbotSmall Model with a language modeling head. Can be used for summarization.
10321066 */
10331067 export class BlenderbotSmallForConditionalGeneration extends BlenderbotSmallPreTrainedModel {
1034- /**
1035- * Creates a new instance of the `BlenderbotForConditionalGeneration` class.
1036- * @param {any} config The model configuration.
1037- * @param {any} session The ONNX session containing the encoder weights.
1038- * @param {any} decoder_merged_session The ONNX session containing the merged decoder weights.
1039- * @param {GenerationConfig} generation_config The generation configuration.
1040- */
1041- constructor(config: any, session: any, decoder_merged_session: any, generation_config: new (kwargs?: import("./utils/generation.js").GenerationConfigType) => import("./utils/generation.js").GenerationConfigType);
1042- decoder_merged_session: any;
1043- generation_config: new (kwargs?: import("./utils/generation.js").GenerationConfigType) => import("./utils/generation.js").GenerationConfigType;
1044- num_decoder_layers: any;
1045- num_decoder_heads: any;
1046- decoder_dim_kv: number;
1047- num_encoder_layers: any;
1048- num_encoder_heads: any;
1049- encoder_dim_kv: number;
1050-}
1051-export class RobertaPreTrainedModel extends PreTrainedModel {
1052-}
1053-export class RobertaModel extends RobertaPreTrainedModel {
1054-}
1068+ /**
1069+ * Creates a new instance of the `BlenderbotForConditionalGeneration` class.
1070+ * @param {any} config The model configuration.
1071+ * @param {any} session The ONNX session containing the encoder weights.
1072+ * @param {any} decoder_merged_session The ONNX session containing the merged decoder weights.
1073+ * @param {GenerationConfig} generation_config The generation configuration.
1074+ */
1075+ constructor(
1076+ config: any,
1077+ session: any,
1078+ decoder_merged_session: any,
1079+ generation_config: new (
1080+ kwargs?: import("./utils/generation.js").GenerationConfigType,
1081+ ) => import("./utils/generation.js").GenerationConfigType,
1082+ );
1083+ decoder_merged_session: any;
1084+ generation_config: new (
1085+ kwargs?: import("./utils/generation.js").GenerationConfigType,
1086+ ) => import("./utils/generation.js").GenerationConfigType;
1087+ num_decoder_layers: any;
1088+ num_decoder_heads: any;
1089+ decoder_dim_kv: number;
1090+ num_encoder_layers: any;
1091+ num_encoder_heads: any;
1092+ encoder_dim_kv: number;
1093+}
1094+export class RobertaPreTrainedModel extends PreTrainedModel {}
1095+export class RobertaModel extends RobertaPreTrainedModel {}
10551096 /**
10561097 * RobertaForMaskedLM class for performing masked language modeling on Roberta models.
10571098 */
10581099 export class RobertaForMaskedLM extends RobertaPreTrainedModel {
1059- /**
1060- * Calls the model on new inputs.
1061- *
1062- * @param {Object} model_inputs The inputs to the model.
1063- * @returns {Promise<MaskedLMOutput>} returned object
1064- */
1065- _call(model_inputs: any): Promise<MaskedLMOutput>;
1100+ /**
1101+ * Calls the model on new inputs.
1102+ *
1103+ * @param {Object} model_inputs The inputs to the model.
1104+ * @returns {Promise<MaskedLMOutput>} returned object
1105+ */
1106+ _call(model_inputs: any): Promise<MaskedLMOutput>;
10661107 }
10671108 /**
10681109 * RobertaForSequenceClassification class for performing sequence classification on Roberta models.
10691110 */
10701111 export class RobertaForSequenceClassification extends RobertaPreTrainedModel {
1071- /**
1072- * Calls the model on new inputs.
1073- *
1074- * @param {Object} model_inputs The inputs to the model.
1075- * @returns {Promise<SequenceClassifierOutput>} returned object
1076- */
1077- _call(model_inputs: any): Promise<SequenceClassifierOutput>;
1112+ /**
1113+ * Calls the model on new inputs.
1114+ *
1115+ * @param {Object} model_inputs The inputs to the model.
1116+ * @returns {Promise<SequenceClassifierOutput>} returned object
1117+ */
1118+ _call(model_inputs: any): Promise<SequenceClassifierOutput>;
10781119 }
10791120 /**
10801121 * RobertaForTokenClassification class for performing token classification on Roberta models.
10811122 */
10821123 export class RobertaForTokenClassification extends RobertaPreTrainedModel {
1083- /**
1084- * Calls the model on new inputs.
1085- *
1086- * @param {Object} model_inputs The inputs to the model.
1087- * @returns {Promise<TokenClassifierOutput>} An object containing the model's output logits for token classification.
1088- */
1089- _call(model_inputs: any): Promise<TokenClassifierOutput>;
1124+ /**
1125+ * Calls the model on new inputs.
1126+ *
1127+ * @param {Object} model_inputs The inputs to the model.
1128+ * @returns {Promise<TokenClassifierOutput>} An object containing the model's output logits for token classification.
1129+ */
1130+ _call(model_inputs: any): Promise<TokenClassifierOutput>;
10901131 }
10911132 /**
10921133 * RobertaForQuestionAnswering class for performing question answering on Roberta models.
10931134 */
10941135 export class RobertaForQuestionAnswering extends RobertaPreTrainedModel {
1095- /**
1096- * Calls the model on new inputs.
1097- *
1098- * @param {Object} model_inputs The inputs to the model.
1099- * @returns {Promise<QuestionAnsweringModelOutput>} returned object
1100- */
1101- _call(model_inputs: any): Promise<QuestionAnsweringModelOutput>;
1136+ /**
1137+ * Calls the model on new inputs.
1138+ *
1139+ * @param {Object} model_inputs The inputs to the model.
1140+ * @returns {Promise<QuestionAnsweringModelOutput>} returned object
1141+ */
1142+ _call(model_inputs: any): Promise<QuestionAnsweringModelOutput>;
11021143 }
11031144 /**
11041145 * An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained models.
11051146 */
1106-export class XLMPreTrainedModel extends PreTrainedModel {
1107-}
1147+export class XLMPreTrainedModel extends PreTrainedModel {}
11081148 /**
11091149 * The bare XLM Model transformer outputting raw hidden-states without any specific head on top.
11101150 */
1111-export class XLMModel extends XLMPreTrainedModel {
1112-}
1151+export class XLMModel extends XLMPreTrainedModel {}
11131152 /**
11141153 * The XLM Model transformer with a language modeling head on top (linear layer with weights tied to the input embeddings).
11151154 */
11161155 export class XLMWithLMHeadModel extends XLMPreTrainedModel {
1117- /**
1118- * Calls the model on new inputs.
1119- *
1120- * @param {Object} model_inputs The inputs to the model.
1121- * @returns {Promise<MaskedLMOutput>} returned object
1122- */
1123- _call(model_inputs: any): Promise<MaskedLMOutput>;
1156+ /**
1157+ * Calls the model on new inputs.
1158+ *
1159+ * @param {Object} model_inputs The inputs to the model.
1160+ * @returns {Promise<MaskedLMOutput>} returned object
1161+ */
1162+ _call(model_inputs: any): Promise<MaskedLMOutput>;
11241163 }
11251164 /**
11261165 * XLM Model with a sequence classification/regression head on top (a linear layer on top of the pooled output)
11271166 */
11281167 export class XLMForSequenceClassification extends XLMPreTrainedModel {
1129- /**
1130- * Calls the model on new inputs.
1131- *
1132- * @param {Object} model_inputs The inputs to the model.
1133- * @returns {Promise<SequenceClassifierOutput>} returned object
1134- */
1135- _call(model_inputs: any): Promise<SequenceClassifierOutput>;
1168+ /**
1169+ * Calls the model on new inputs.
1170+ *
1171+ * @param {Object} model_inputs The inputs to the model.
1172+ * @returns {Promise<SequenceClassifierOutput>} returned object
1173+ */
1174+ _call(model_inputs: any): Promise<SequenceClassifierOutput>;
11361175 }
11371176 /**
11381177 * XLM Model with a token classification head on top (a linear layer on top of the hidden-states output)
11391178 */
11401179 export class XLMForTokenClassification extends XLMPreTrainedModel {
1141- /**
1142- * Calls the model on new inputs.
1143- *
1144- * @param {Object} model_inputs The inputs to the model.
1145- * @returns {Promise<TokenClassifierOutput>} An object containing the model's output logits for token classification.
1146- */
1147- _call(model_inputs: any): Promise<TokenClassifierOutput>;
1180+ /**
1181+ * Calls the model on new inputs.
1182+ *
1183+ * @param {Object} model_inputs The inputs to the model.
1184+ * @returns {Promise<TokenClassifierOutput>} An object containing the model's output logits for token classification.
1185+ */
1186+ _call(model_inputs: any): Promise<TokenClassifierOutput>;
11481187 }
11491188 /**
11501189 * XLM Model with a span classification head on top for extractive question-answering tasks
11511190 */
11521191 export class XLMForQuestionAnswering extends XLMPreTrainedModel {
1153- /**
1154- * Calls the model on new inputs.
1155- *
1156- * @param {Object} model_inputs The inputs to the model.
1157- * @returns {Promise<QuestionAnsweringModelOutput>} returned object
1158- */
1159- _call(model_inputs: any): Promise<QuestionAnsweringModelOutput>;
1160-}
1161-export class XLMRobertaPreTrainedModel extends PreTrainedModel {
1162-}
1163-export class XLMRobertaModel extends XLMRobertaPreTrainedModel {
1164-}
1192+ /**
1193+ * Calls the model on new inputs.
1194+ *
1195+ * @param {Object} model_inputs The inputs to the model.
1196+ * @returns {Promise<QuestionAnsweringModelOutput>} returned object
1197+ */
1198+ _call(model_inputs: any): Promise<QuestionAnsweringModelOutput>;
1199+}
1200+export class XLMRobertaPreTrainedModel extends PreTrainedModel {}
1201+export class XLMRobertaModel extends XLMRobertaPreTrainedModel {}
11651202 /**
11661203 * XLMRobertaForMaskedLM class for performing masked language modeling on XLMRoberta models.
11671204 */
11681205 export class XLMRobertaForMaskedLM extends XLMRobertaPreTrainedModel {
1169- /**
1170- * Calls the model on new inputs.
1171- *
1172- * @param {Object} model_inputs The inputs to the model.
1173- * @returns {Promise<MaskedLMOutput>} returned object
1174- */
1175- _call(model_inputs: any): Promise<MaskedLMOutput>;
1206+ /**
1207+ * Calls the model on new inputs.
1208+ *
1209+ * @param {Object} model_inputs The inputs to the model.
1210+ * @returns {Promise<MaskedLMOutput>} returned object
1211+ */
1212+ _call(model_inputs: any): Promise<MaskedLMOutput>;
11761213 }
11771214 /**
11781215 * XLMRobertaForSequenceClassification class for performing sequence classification on XLMRoberta models.
11791216 */
11801217 export class XLMRobertaForSequenceClassification extends XLMRobertaPreTrainedModel {
1181- /**
1182- * Calls the model on new inputs.
1183- *
1184- * @param {Object} model_inputs The inputs to the model.
1185- * @returns {Promise<SequenceClassifierOutput>} returned object
1186- */
1187- _call(model_inputs: any): Promise<SequenceClassifierOutput>;
1218+ /**
1219+ * Calls the model on new inputs.
1220+ *
1221+ * @param {Object} model_inputs The inputs to the model.
1222+ * @returns {Promise<SequenceClassifierOutput>} returned object
1223+ */
1224+ _call(model_inputs: any): Promise<SequenceClassifierOutput>;
11881225 }
11891226 /**
11901227 * XLMRobertaForTokenClassification class for performing token classification on XLMRoberta models.
11911228 */
11921229 export class XLMRobertaForTokenClassification extends XLMRobertaPreTrainedModel {
1193- /**
1194- * Calls the model on new inputs.
1195- *
1196- * @param {Object} model_inputs The inputs to the model.
1197- * @returns {Promise<TokenClassifierOutput>} An object containing the model's output logits for token classification.
1198- */
1199- _call(model_inputs: any): Promise<TokenClassifierOutput>;
1230+ /**
1231+ * Calls the model on new inputs.
1232+ *
1233+ * @param {Object} model_inputs The inputs to the model.
1234+ * @returns {Promise<TokenClassifierOutput>} An object containing the model's output logits for token classification.
1235+ */
1236+ _call(model_inputs: any): Promise<TokenClassifierOutput>;
12001237 }
12011238 /**
12021239 * XLMRobertaForQuestionAnswering class for performing question answering on XLMRoberta models.
12031240 */
12041241 export class XLMRobertaForQuestionAnswering extends XLMRobertaPreTrainedModel {
1205- /**
1206- * Calls the model on new inputs.
1207- *
1208- * @param {Object} model_inputs The inputs to the model.
1209- * @returns {Promise<QuestionAnsweringModelOutput>} returned object
1210- */
1211- _call(model_inputs: any): Promise<QuestionAnsweringModelOutput>;
1212-}
1213-export class ASTPreTrainedModel extends PreTrainedModel {
1214-}
1242+ /**
1243+ * Calls the model on new inputs.
1244+ *
1245+ * @param {Object} model_inputs The inputs to the model.
1246+ * @returns {Promise<QuestionAnsweringModelOutput>} returned object
1247+ */
1248+ _call(model_inputs: any): Promise<QuestionAnsweringModelOutput>;
1249+}
1250+export class ASTPreTrainedModel extends PreTrainedModel {}
12151251 /**
12161252 * The bare AST Model transformer outputting raw hidden-states without any specific head on top.
12171253 */
1218-export class ASTModel extends ASTPreTrainedModel {
1219-}
1254+export class ASTModel extends ASTPreTrainedModel {}
12201255 /**
12211256 * Audio Spectrogram Transformer model with an audio classification head on top
12221257 * (a linear layer on top of the pooled output) e.g. for datasets like AudioSet, Speech Commands v2.
12231258 */
1224-export class ASTForAudioClassification extends ASTPreTrainedModel {
1225-}
1226-export class WhisperPreTrainedModel extends PreTrainedModel {
1227-}
1259+export class ASTForAudioClassification extends ASTPreTrainedModel {}
1260+export class WhisperPreTrainedModel extends PreTrainedModel {}
12281261 /**
12291262 * WhisperModel class for training Whisper models without a language model head.
12301263 */
1231-export class WhisperModel extends WhisperPreTrainedModel {
1232-}
1264+export class WhisperModel extends WhisperPreTrainedModel {}
12331265 /**
12341266 * WhisperForConditionalGeneration class for generating conditional outputs from Whisper models.
12351267 */
12361268 export class WhisperForConditionalGeneration extends WhisperPreTrainedModel {
1237- /**
1238- * Creates a new instance of the `WhisperForConditionalGeneration` class.
1239- * @param {Object} config Configuration object for the model.
1240- * @param {Object} session ONNX Session object for the model.
1241- * @param {Object} decoder_merged_session ONNX Session object for the decoder.
1242- * @param {Object} generation_config Configuration object for the generation process.
1243- */
1244- constructor(config: any, session: any, decoder_merged_session: any, generation_config: any);
1245- requires_attention_mask: boolean;
1246- decoder_merged_session: any;
1247- generation_config: any;
1248- num_decoder_layers: any;
1249- num_decoder_heads: any;
1250- decoder_dim_kv: number;
1251- num_encoder_layers: any;
1252- num_encoder_heads: any;
1253- encoder_dim_kv: number;
1254- /**
1255- * @typedef {Object} WhisperGenerationConfig
1256- * @extends GenerationConfig
1257- * @property {boolean} [return_timestamps=null] Whether to return the timestamps with the text. This enables the `WhisperTimestampsLogitsProcessor`.
1258- * @property {boolean} [return_token_timestamps=null] Whether to return token-level timestamps
1259- * with the text. This can be used with or without the `return_timestamps` option. To get word-level
1260- * timestamps, use the tokenizer to group the tokens into words.
1261- * @property {number} [num_frames=null] The number of audio frames available in this chunk. This is only used generating word-level timestamps.
1262- */
1263- /**
1264- * Generates outputs based on input and generation configuration.
1265- * @param {Object} inputs Input data for the model.
1266- * @param {WhisperGenerationConfig} generation_config Configuration object for the generation process.
1267- * @param {Object} logits_processor Optional logits processor object.
1268- * @returns {Promise<Object>} Promise object represents the generated outputs.
1269- */
1270- generate(inputs: any, generation_config?: any, logits_processor?: any): Promise<any>;
1271- /**
1272- * Calculates token-level timestamps using the encoder-decoder cross-attentions and
1273- * dynamic time-warping (DTW) to map each output token to a position in the input audio.
1274- * @param {Object} generate_outputs Outputs generated by the model
1275- * @param {Tensor[][][]} generate_outputs.cross_attentions The cross attentions output by the model
1276- * @param {Tensor[][][]} generate_outputs.decoder_attentions The decoder attentions output by the model
1277- * @param {number[][]} generate_outputs.sequences The sequences output by the model
1278- * @param {number[][]} alignment_heads Alignment heads of the model
1279- * @param {number} [num_frames=null] Number of frames in the input audio.
1280- * @param {number} [time_precision=0.02] Precision of the timestamps in seconds
1281- * @returns {Tensor} tensor containing the timestamps in seconds for each predicted token
1282- */
1283- _extract_token_timestamps(generate_outputs: {
1284- cross_attentions: Tensor[][][];
1285- decoder_attentions: Tensor[][][];
1286- sequences: number[][];
1287- }, alignment_heads: number[][], num_frames?: number, time_precision?: number): Tensor;
1269+ /**
1270+ * Creates a new instance of the `WhisperForConditionalGeneration` class.
1271+ * @param {Object} config Configuration object for the model.
1272+ * @param {Object} session ONNX Session object for the model.
1273+ * @param {Object} decoder_merged_session ONNX Session object for the decoder.
1274+ * @param {Object} generation_config Configuration object for the generation process.
1275+ */
1276+ constructor(
1277+ config: any,
1278+ session: any,
1279+ decoder_merged_session: any,
1280+ generation_config: any,
1281+ );
1282+ requires_attention_mask: boolean;
1283+ decoder_merged_session: any;
1284+ generation_config: any;
1285+ num_decoder_layers: any;
1286+ num_decoder_heads: any;
1287+ decoder_dim_kv: number;
1288+ num_encoder_layers: any;
1289+ num_encoder_heads: any;
1290+ encoder_dim_kv: number;
1291+ /**
1292+ * @typedef {Object} WhisperGenerationConfig
1293+ * @extends GenerationConfig
1294+ * @property {boolean} [return_timestamps=null] Whether to return the timestamps with the text. This enables the `WhisperTimestampsLogitsProcessor`.
1295+ * @property {boolean} [return_token_timestamps=null] Whether to return token-level timestamps
1296+ * with the text. This can be used with or without the `return_timestamps` option. To get word-level
1297+ * timestamps, use the tokenizer to group the tokens into words.
1298+ * @property {number} [num_frames=null] The number of audio frames available in this chunk. This is only used generating word-level timestamps.
1299+ */
1300+ /**
1301+ * Generates outputs based on input and generation configuration.
1302+ * @param {Object} inputs Input data for the model.
1303+ * @param {WhisperGenerationConfig} generation_config Configuration object for the generation process.
1304+ * @param {Object} logits_processor Optional logits processor object.
1305+ * @returns {Promise<Object>} Promise object represents the generated outputs.
1306+ */
1307+ generate(
1308+ inputs: any,
1309+ generation_config?: any,
1310+ logits_processor?: any,
1311+ ): Promise<any>;
1312+ /**
1313+ * Calculates token-level timestamps using the encoder-decoder cross-attentions and
1314+ * dynamic time-warping (DTW) to map each output token to a position in the input audio.
1315+ * @param {Object} generate_outputs Outputs generated by the model
1316+ * @param {Tensor[][][]} generate_outputs.cross_attentions The cross attentions output by the model
1317+ * @param {Tensor[][][]} generate_outputs.decoder_attentions The decoder attentions output by the model
1318+ * @param {number[][]} generate_outputs.sequences The sequences output by the model
1319+ * @param {number[][]} alignment_heads Alignment heads of the model
1320+ * @param {number} [num_frames=null] Number of frames in the input audio.
1321+ * @param {number} [time_precision=0.02] Precision of the timestamps in seconds
1322+ * @returns {Tensor} tensor containing the timestamps in seconds for each predicted token
1323+ */
1324+ _extract_token_timestamps(
1325+ generate_outputs: {
1326+ cross_attentions: Tensor[][][];
1327+ decoder_attentions: Tensor[][][];
1328+ sequences: number[][];
1329+ },
1330+ alignment_heads: number[][],
1331+ num_frames?: number,
1332+ time_precision?: number,
1333+ ): Tensor;
12881334 }
12891335 /**
12901336 * Vision Encoder-Decoder model based on OpenAI's GPT architecture for image captioning and other vision tasks
12911337 */
12921338 export class VisionEncoderDecoderModel extends PreTrainedModel {
1293- /**
1294- * Creates a new instance of the `VisionEncoderDecoderModel` class.
1295- * @param {Object} config The configuration object specifying the hyperparameters and other model settings.
1296- * @param {Object} session The ONNX session containing the encoder model.
1297- * @param {any} decoder_merged_session The ONNX session containing the merged decoder model.
1298- * @param {Object} generation_config Configuration object for the generation process.
1299- */
1300- constructor(config: any, session: any, decoder_merged_session: any, generation_config: any);
1301- decoder_merged_session: any;
1302- generation_config: any;
1303- add_encoder_pkv: boolean;
1304- num_decoder_layers: any;
1305- num_decoder_heads: any;
1306- decoder_dim_kv: any;
1307- num_encoder_layers: any;
1308- num_encoder_heads: any;
1309- encoder_dim_kv: any;
1310- num_layers: any;
1311- num_heads: any;
1312- dim_kv: any;
1313-}
1314-export class CLIPPreTrainedModel extends PreTrainedModel {
1315-}
1339+ /**
1340+ * Creates a new instance of the `VisionEncoderDecoderModel` class.
1341+ * @param {Object} config The configuration object specifying the hyperparameters and other model settings.
1342+ * @param {Object} session The ONNX session containing the encoder model.
1343+ * @param {any} decoder_merged_session The ONNX session containing the merged decoder model.
1344+ * @param {Object} generation_config Configuration object for the generation process.
1345+ */
1346+ constructor(
1347+ config: any,
1348+ session: any,
1349+ decoder_merged_session: any,
1350+ generation_config: any,
1351+ );
1352+ decoder_merged_session: any;
1353+ generation_config: any;
1354+ add_encoder_pkv: boolean;
1355+ num_decoder_layers: any;
1356+ num_decoder_heads: any;
1357+ decoder_dim_kv: any;
1358+ num_encoder_layers: any;
1359+ num_encoder_heads: any;
1360+ encoder_dim_kv: any;
1361+ num_layers: any;
1362+ num_heads: any;
1363+ dim_kv: any;
1364+}
1365+export class CLIPPreTrainedModel extends PreTrainedModel {}
13161366 /**
13171367 * CLIP Text and Vision Model with a projection layers on top
13181368 *
@@ -1356,8 +1406,7 @@
13561406 * // }
13571407 * ```
13581408 */
1359-export class CLIPModel extends CLIPPreTrainedModel {
1360-}
1409+export class CLIPModel extends CLIPPreTrainedModel {}
13611410 /**
13621411 * CLIP Text Model with a projection layer on top (a linear layer on top of the pooled output)
13631412 *
@@ -1384,8 +1433,7 @@
13841433 * // }
13851434 * ```
13861435 */
1387-export class CLIPTextModelWithProjection extends CLIPPreTrainedModel {
1388-}
1436+export class CLIPTextModelWithProjection extends CLIPPreTrainedModel {}
13891437 /**
13901438 * CLIP Vision Model with a projection layer on top (a linear layer on top of the pooled output)
13911439 *
@@ -1412,10 +1460,8 @@
14121460 * // }
14131461 * ```
14141462 */
1415-export class CLIPVisionModelWithProjection extends CLIPPreTrainedModel {
1416-}
1417-export class SiglipPreTrainedModel extends PreTrainedModel {
1418-}
1463+export class CLIPVisionModelWithProjection extends CLIPPreTrainedModel {}
1464+export class SiglipPreTrainedModel extends PreTrainedModel {}
14191465 /**
14201466 * SigLIP Text and Vision Model with a projection layers on top
14211467 *
@@ -1459,8 +1505,7 @@
14591505 * // }
14601506 * ```
14611507 */
1462-export class SiglipModel extends SiglipPreTrainedModel {
1463-}
1508+export class SiglipModel extends SiglipPreTrainedModel {}
14641509 /**
14651510 * The text model from SigLIP without any head or projection on top.
14661511 *
@@ -1487,8 +1532,7 @@
14871532 * // }
14881533 * ```
14891534 */
1490-export class SiglipTextModel extends SiglipPreTrainedModel {
1491-}
1535+export class SiglipTextModel extends SiglipPreTrainedModel {}
14921536 /**
14931537 * The vision model from SigLIP without any head or projection on top.
14941538 *
@@ -1515,16 +1559,11 @@
15151559 * // }
15161560 * ```
15171561 */
1518-export class SiglipVisionModel extends CLIPPreTrainedModel {
1519-}
1520-export class ChineseCLIPPreTrainedModel extends PreTrainedModel {
1521-}
1522-export class ChineseCLIPModel extends ChineseCLIPPreTrainedModel {
1523-}
1524-export class CLIPSegPreTrainedModel extends PreTrainedModel {
1525-}
1526-export class CLIPSegModel extends CLIPSegPreTrainedModel {
1527-}
1562+export class SiglipVisionModel extends CLIPPreTrainedModel {}
1563+export class ChineseCLIPPreTrainedModel extends PreTrainedModel {}
1564+export class ChineseCLIPModel extends ChineseCLIPPreTrainedModel {}
1565+export class CLIPSegPreTrainedModel extends PreTrainedModel {}
1566+export class CLIPSegModel extends CLIPSegPreTrainedModel {}
15281567 /**
15291568 * CLIPSeg model with a Transformer-based decoder on top for zero-shot and one-shot image segmentation.
15301569 *
@@ -1571,246 +1610,308 @@
15711610 * }
15721611 * ```
15731612 */
1574-export class CLIPSegForImageSegmentation extends CLIPSegPreTrainedModel {
1575-}
1613+export class CLIPSegForImageSegmentation extends CLIPSegPreTrainedModel {}
15761614 export class GPT2PreTrainedModel extends PreTrainedModel {
1577- /**
1578- * Creates a new instance of the `GPT2PreTrainedModel` class.
1579- * @param {Object} config The configuration of the model.
1580- * @param {any} session The ONNX session containing the model weights.
1581- * @param {GenerationConfig} generation_config The generation configuration.
1582- */
1583- constructor(config: any, session: any, generation_config: new (kwargs?: import("./utils/generation.js").GenerationConfigType) => import("./utils/generation.js").GenerationConfigType);
1584- generation_config: new (kwargs?: import("./utils/generation.js").GenerationConfigType) => import("./utils/generation.js").GenerationConfigType;
1585- num_heads: any;
1586- num_layers: any;
1587- dim_kv: number;
1588-}
1589-export class GPT2Model extends GPT2PreTrainedModel {
1590-}
1615+ /**
1616+ * Creates a new instance of the `GPT2PreTrainedModel` class.
1617+ * @param {Object} config The configuration of the model.
1618+ * @param {any} session The ONNX session containing the model weights.
1619+ * @param {GenerationConfig} generation_config The generation configuration.
1620+ */
1621+ constructor(
1622+ config: any,
1623+ session: any,
1624+ generation_config: new (
1625+ kwargs?: import("./utils/generation.js").GenerationConfigType,
1626+ ) => import("./utils/generation.js").GenerationConfigType,
1627+ );
1628+ generation_config: new (
1629+ kwargs?: import("./utils/generation.js").GenerationConfigType,
1630+ ) => import("./utils/generation.js").GenerationConfigType;
1631+ num_heads: any;
1632+ num_layers: any;
1633+ dim_kv: number;
1634+}
1635+export class GPT2Model extends GPT2PreTrainedModel {}
15911636 /**
15921637 * GPT-2 language model head on top of the GPT-2 base model. This model is suitable for text generation tasks.
15931638 */
1594-export class GPT2LMHeadModel extends GPT2PreTrainedModel {
1595-}
1639+export class GPT2LMHeadModel extends GPT2PreTrainedModel {}
15961640 export class GPTNeoPreTrainedModel extends PreTrainedModel {
1597- /**
1598- * Creates a new instance of the `GPTNeoPreTrainedModel` class.
1599- * @param {Object} config The configuration of the model.
1600- * @param {any} session The ONNX session containing the model weights.
1601- * @param {GenerationConfig} generation_config The generation configuration.
1602- */
1603- constructor(config: any, session: any, generation_config: new (kwargs?: import("./utils/generation.js").GenerationConfigType) => import("./utils/generation.js").GenerationConfigType);
1604- generation_config: new (kwargs?: import("./utils/generation.js").GenerationConfigType) => import("./utils/generation.js").GenerationConfigType;
1605- num_heads: any;
1606- num_layers: any;
1607- dim_kv: number;
1608-}
1609-export class GPTNeoModel extends GPTNeoPreTrainedModel {
1610-}
1611-export class GPTNeoForCausalLM extends GPTNeoPreTrainedModel {
1612-}
1641+ /**
1642+ * Creates a new instance of the `GPTNeoPreTrainedModel` class.
1643+ * @param {Object} config The configuration of the model.
1644+ * @param {any} session The ONNX session containing the model weights.
1645+ * @param {GenerationConfig} generation_config The generation configuration.
1646+ */
1647+ constructor(
1648+ config: any,
1649+ session: any,
1650+ generation_config: new (
1651+ kwargs?: import("./utils/generation.js").GenerationConfigType,
1652+ ) => import("./utils/generation.js").GenerationConfigType,
1653+ );
1654+ generation_config: new (
1655+ kwargs?: import("./utils/generation.js").GenerationConfigType,
1656+ ) => import("./utils/generation.js").GenerationConfigType;
1657+ num_heads: any;
1658+ num_layers: any;
1659+ dim_kv: number;
1660+}
1661+export class GPTNeoModel extends GPTNeoPreTrainedModel {}
1662+export class GPTNeoForCausalLM extends GPTNeoPreTrainedModel {}
16131663 export class GPTNeoXPreTrainedModel extends PreTrainedModel {
1614- /**
1615- * Creates a new instance of the `GPTNeoXPreTrainedModel` class.
1616- * @param {Object} config The configuration of the model.
1617- * @param {any} session The ONNX session containing the model weights.
1618- * @param {GenerationConfig} generation_config The generation configuration.
1619- */
1620- constructor(config: any, session: any, generation_config: new (kwargs?: import("./utils/generation.js").GenerationConfigType) => import("./utils/generation.js").GenerationConfigType);
1621- generation_config: new (kwargs?: import("./utils/generation.js").GenerationConfigType) => import("./utils/generation.js").GenerationConfigType;
1622- num_heads: any;
1623- num_layers: any;
1624- dim_kv: number;
1625-}
1626-export class GPTNeoXModel extends GPTNeoXPreTrainedModel {
1627-}
1628-export class GPTNeoXForCausalLM extends GPTNeoXPreTrainedModel {
1629-}
1664+ /**
1665+ * Creates a new instance of the `GPTNeoXPreTrainedModel` class.
1666+ * @param {Object} config The configuration of the model.
1667+ * @param {any} session The ONNX session containing the model weights.
1668+ * @param {GenerationConfig} generation_config The generation configuration.
1669+ */
1670+ constructor(
1671+ config: any,
1672+ session: any,
1673+ generation_config: new (
1674+ kwargs?: import("./utils/generation.js").GenerationConfigType,
1675+ ) => import("./utils/generation.js").GenerationConfigType,
1676+ );
1677+ generation_config: new (
1678+ kwargs?: import("./utils/generation.js").GenerationConfigType,
1679+ ) => import("./utils/generation.js").GenerationConfigType;
1680+ num_heads: any;
1681+ num_layers: any;
1682+ dim_kv: number;
1683+}
1684+export class GPTNeoXModel extends GPTNeoXPreTrainedModel {}
1685+export class GPTNeoXForCausalLM extends GPTNeoXPreTrainedModel {}
16301686 export class GPTJPreTrainedModel extends PreTrainedModel {
1631- /**
1632- * Creates a new instance of the `GPTJPreTrainedModel` class.
1633- * @param {Object} config The configuration of the model.
1634- * @param {any} session The ONNX session containing the model weights.
1635- * @param {GenerationConfig} generation_config The generation configuration.
1636- */
1637- constructor(config: any, session: any, generation_config: new (kwargs?: import("./utils/generation.js").GenerationConfigType) => import("./utils/generation.js").GenerationConfigType);
1638- generation_config: new (kwargs?: import("./utils/generation.js").GenerationConfigType) => import("./utils/generation.js").GenerationConfigType;
1639- num_heads: any;
1640- num_layers: any;
1641- dim_kv: number;
1642-}
1643-export class GPTJModel extends GPTJPreTrainedModel {
1644-}
1645-export class GPTJForCausalLM extends GPTJPreTrainedModel {
1646-}
1687+ /**
1688+ * Creates a new instance of the `GPTJPreTrainedModel` class.
1689+ * @param {Object} config The configuration of the model.
1690+ * @param {any} session The ONNX session containing the model weights.
1691+ * @param {GenerationConfig} generation_config The generation configuration.
1692+ */
1693+ constructor(
1694+ config: any,
1695+ session: any,
1696+ generation_config: new (
1697+ kwargs?: import("./utils/generation.js").GenerationConfigType,
1698+ ) => import("./utils/generation.js").GenerationConfigType,
1699+ );
1700+ generation_config: new (
1701+ kwargs?: import("./utils/generation.js").GenerationConfigType,
1702+ ) => import("./utils/generation.js").GenerationConfigType;
1703+ num_heads: any;
1704+ num_layers: any;
1705+ dim_kv: number;
1706+}
1707+export class GPTJModel extends GPTJPreTrainedModel {}
1708+export class GPTJForCausalLM extends GPTJPreTrainedModel {}
16471709 export class GPTBigCodePreTrainedModel extends PreTrainedModel {
1648- /**
1649- * Creates a new instance of the `GPTBigCodePreTrainedModel` class.
1650- * @param {Object} config The configuration of the model.
1651- * @param {any} session The ONNX session containing the model weights.
1652- * @param {GenerationConfig} generation_config The generation configuration.
1653- */
1654- constructor(config: any, session: any, generation_config: new (kwargs?: import("./utils/generation.js").GenerationConfigType) => import("./utils/generation.js").GenerationConfigType);
1655- generation_config: new (kwargs?: import("./utils/generation.js").GenerationConfigType) => import("./utils/generation.js").GenerationConfigType;
1656- num_heads: any;
1657- num_layers: any;
1658- dim_kv: number;
1659-}
1660-export class GPTBigCodeModel extends GPTBigCodePreTrainedModel {
1661-}
1662-export class GPTBigCodeForCausalLM extends GPTBigCodePreTrainedModel {
1663-}
1710+ /**
1711+ * Creates a new instance of the `GPTBigCodePreTrainedModel` class.
1712+ * @param {Object} config The configuration of the model.
1713+ * @param {any} session The ONNX session containing the model weights.
1714+ * @param {GenerationConfig} generation_config The generation configuration.
1715+ */
1716+ constructor(
1717+ config: any,
1718+ session: any,
1719+ generation_config: new (
1720+ kwargs?: import("./utils/generation.js").GenerationConfigType,
1721+ ) => import("./utils/generation.js").GenerationConfigType,
1722+ );
1723+ generation_config: new (
1724+ kwargs?: import("./utils/generation.js").GenerationConfigType,
1725+ ) => import("./utils/generation.js").GenerationConfigType;
1726+ num_heads: any;
1727+ num_layers: any;
1728+ dim_kv: number;
1729+}
1730+export class GPTBigCodeModel extends GPTBigCodePreTrainedModel {}
1731+export class GPTBigCodeForCausalLM extends GPTBigCodePreTrainedModel {}
16641732 export class CodeGenPreTrainedModel extends PreTrainedModel {
1665- /**
1666- * Creates a new instance of the `CodeGenPreTrainedModel` class.
1667- * @param {Object} config The model configuration object.
1668- * @param {Object} session The ONNX session object.
1669- * @param {GenerationConfig} generation_config The generation configuration.
1670- */
1671- constructor(config: any, session: any, generation_config: new (kwargs?: import("./utils/generation.js").GenerationConfigType) => import("./utils/generation.js").GenerationConfigType);
1672- generation_config: new (kwargs?: import("./utils/generation.js").GenerationConfigType) => import("./utils/generation.js").GenerationConfigType;
1673- num_heads: any;
1674- num_layers: any;
1675- dim_kv: number;
1733+ /**
1734+ * Creates a new instance of the `CodeGenPreTrainedModel` class.
1735+ * @param {Object} config The model configuration object.
1736+ * @param {Object} session The ONNX session object.
1737+ * @param {GenerationConfig} generation_config The generation configuration.
1738+ */
1739+ constructor(
1740+ config: any,
1741+ session: any,
1742+ generation_config: new (
1743+ kwargs?: import("./utils/generation.js").GenerationConfigType,
1744+ ) => import("./utils/generation.js").GenerationConfigType,
1745+ );
1746+ generation_config: new (
1747+ kwargs?: import("./utils/generation.js").GenerationConfigType,
1748+ ) => import("./utils/generation.js").GenerationConfigType;
1749+ num_heads: any;
1750+ num_layers: any;
1751+ dim_kv: number;
16761752 }
16771753 /**
16781754 * CodeGenModel is a class representing a code generation model without a language model head.
16791755 */
1680-export class CodeGenModel extends CodeGenPreTrainedModel {
1681-}
1756+export class CodeGenModel extends CodeGenPreTrainedModel {}
16821757 /**
16831758 * CodeGenForCausalLM is a class that represents a code generation model based on the GPT-2 architecture. It extends the `CodeGenPreTrainedModel` class.
16841759 */
1685-export class CodeGenForCausalLM extends CodeGenPreTrainedModel {
1686-}
1760+export class CodeGenForCausalLM extends CodeGenPreTrainedModel {}
16871761 /**
16881762 * The bare LLama Model outputting raw hidden-states without any specific head on top.
16891763 */
16901764 export class LlamaPreTrainedModel extends PreTrainedModel {
1691- /**
1692- * Creates a new instance of the `LlamaPreTrainedModel` class.
1693- * @param {Object} config The model configuration object.
1694- * @param {Object} session The ONNX session object.
1695- * @param {GenerationConfig} generation_config The generation configuration.
1696- */
1697- constructor(config: any, session: any, generation_config: new (kwargs?: import("./utils/generation.js").GenerationConfigType) => import("./utils/generation.js").GenerationConfigType);
1698- generation_config: new (kwargs?: import("./utils/generation.js").GenerationConfigType) => import("./utils/generation.js").GenerationConfigType;
1699- num_heads: any;
1700- num_layers: any;
1701- dim_kv: number;
1765+ /**
1766+ * Creates a new instance of the `LlamaPreTrainedModel` class.
1767+ * @param {Object} config The model configuration object.
1768+ * @param {Object} session The ONNX session object.
1769+ * @param {GenerationConfig} generation_config The generation configuration.
1770+ */
1771+ constructor(
1772+ config: any,
1773+ session: any,
1774+ generation_config: new (
1775+ kwargs?: import("./utils/generation.js").GenerationConfigType,
1776+ ) => import("./utils/generation.js").GenerationConfigType,
1777+ );
1778+ generation_config: new (
1779+ kwargs?: import("./utils/generation.js").GenerationConfigType,
1780+ ) => import("./utils/generation.js").GenerationConfigType;
1781+ num_heads: any;
1782+ num_layers: any;
1783+ dim_kv: number;
17021784 }
17031785 /**
17041786 * The bare LLaMA Model outputting raw hidden-states without any specific head on top.
17051787 */
1706-export class LlamaModel extends LlamaPreTrainedModel {
1707-}
1708-export class LlamaForCausalLM extends LlamaPreTrainedModel {
1709-}
1788+export class LlamaModel extends LlamaPreTrainedModel {}
1789+export class LlamaForCausalLM extends LlamaPreTrainedModel {}
17101790 export class PhiPreTrainedModel extends PreTrainedModel {
1711- /**
1712- * Creates a new instance of the `PhiPreTrainedModel` class.
1713- * @param {Object} config The model configuration object.
1714- * @param {Object} session The ONNX session object.
1715- * @param {GenerationConfig} generation_config The generation configuration.
1716- */
1717- constructor(config: any, session: any, generation_config: new (kwargs?: import("./utils/generation.js").GenerationConfigType) => import("./utils/generation.js").GenerationConfigType);
1718- generation_config: new (kwargs?: import("./utils/generation.js").GenerationConfigType) => import("./utils/generation.js").GenerationConfigType;
1719- num_heads: any;
1720- num_layers: any;
1721- dim_kv: number;
1791+ /**
1792+ * Creates a new instance of the `PhiPreTrainedModel` class.
1793+ * @param {Object} config The model configuration object.
1794+ * @param {Object} session The ONNX session object.
1795+ * @param {GenerationConfig} generation_config The generation configuration.
1796+ */
1797+ constructor(
1798+ config: any,
1799+ session: any,
1800+ generation_config: new (
1801+ kwargs?: import("./utils/generation.js").GenerationConfigType,
1802+ ) => import("./utils/generation.js").GenerationConfigType,
1803+ );
1804+ generation_config: new (
1805+ kwargs?: import("./utils/generation.js").GenerationConfigType,
1806+ ) => import("./utils/generation.js").GenerationConfigType;
1807+ num_heads: any;
1808+ num_layers: any;
1809+ dim_kv: number;
17221810 }
17231811 /**
17241812 * The bare Phi Model outputting raw hidden-states without any specific head on top.
17251813 */
1726-export class PhiModel extends PhiPreTrainedModel {
1727-}
1728-export class PhiForCausalLM extends PhiPreTrainedModel {
1729-}
1814+export class PhiModel extends PhiPreTrainedModel {}
1815+export class PhiForCausalLM extends PhiPreTrainedModel {}
17301816 /**
17311817 * The Bloom Model transformer with a language modeling head on top (linear layer with weights tied to the input embeddings).
17321818 */
17331819 export class BloomPreTrainedModel extends PreTrainedModel {
1734- /**
1735- * Creates a new instance of the `BloomPreTrainedModel` class.
1736- * @param {Object} config The configuration of the model.
1737- * @param {any} session The ONNX session containing the model weights.
1738- * @param {GenerationConfig} generation_config The generation configuration.
1739- */
1740- constructor(config: any, session: any, generation_config: new (kwargs?: import("./utils/generation.js").GenerationConfigType) => import("./utils/generation.js").GenerationConfigType);
1741- generation_config: new (kwargs?: import("./utils/generation.js").GenerationConfigType) => import("./utils/generation.js").GenerationConfigType;
1742- num_heads: any;
1743- num_layers: any;
1744- dim_kv: number;
1820+ /**
1821+ * Creates a new instance of the `BloomPreTrainedModel` class.
1822+ * @param {Object} config The configuration of the model.
1823+ * @param {any} session The ONNX session containing the model weights.
1824+ * @param {GenerationConfig} generation_config The generation configuration.
1825+ */
1826+ constructor(
1827+ config: any,
1828+ session: any,
1829+ generation_config: new (
1830+ kwargs?: import("./utils/generation.js").GenerationConfigType,
1831+ ) => import("./utils/generation.js").GenerationConfigType,
1832+ );
1833+ generation_config: new (
1834+ kwargs?: import("./utils/generation.js").GenerationConfigType,
1835+ ) => import("./utils/generation.js").GenerationConfigType;
1836+ num_heads: any;
1837+ num_layers: any;
1838+ dim_kv: number;
17451839 }
17461840 /**
17471841 * The bare Bloom Model transformer outputting raw hidden-states without any specific head on top.
17481842 */
1749-export class BloomModel extends BloomPreTrainedModel {
1750-}
1843+export class BloomModel extends BloomPreTrainedModel {}
17511844 /**
17521845 * The Bloom Model transformer with a language modeling head on top (linear layer with weights tied to the input embeddings).
17531846 */
1754-export class BloomForCausalLM extends BloomPreTrainedModel {
1755-}
1847+export class BloomForCausalLM extends BloomPreTrainedModel {}
17561848 export class MptPreTrainedModel extends PreTrainedModel {
1757- /**
1758- * Creates a new instance of the `MptPreTrainedModel` class.
1759- * @param {Object} config The model configuration object.
1760- * @param {Object} session The ONNX session object.
1761- * @param {GenerationConfig} generation_config The generation configuration.
1762- */
1763- constructor(config: any, session: any, generation_config: new (kwargs?: import("./utils/generation.js").GenerationConfigType) => import("./utils/generation.js").GenerationConfigType);
1764- generation_config: new (kwargs?: import("./utils/generation.js").GenerationConfigType) => import("./utils/generation.js").GenerationConfigType;
1765- num_heads: any;
1766- num_layers: any;
1767- dim_kv: number;
1849+ /**
1850+ * Creates a new instance of the `MptPreTrainedModel` class.
1851+ * @param {Object} config The model configuration object.
1852+ * @param {Object} session The ONNX session object.
1853+ * @param {GenerationConfig} generation_config The generation configuration.
1854+ */
1855+ constructor(
1856+ config: any,
1857+ session: any,
1858+ generation_config: new (
1859+ kwargs?: import("./utils/generation.js").GenerationConfigType,
1860+ ) => import("./utils/generation.js").GenerationConfigType,
1861+ );
1862+ generation_config: new (
1863+ kwargs?: import("./utils/generation.js").GenerationConfigType,
1864+ ) => import("./utils/generation.js").GenerationConfigType;
1865+ num_heads: any;
1866+ num_layers: any;
1867+ dim_kv: number;
17681868 }
17691869 /**
17701870 * The bare Mpt Model transformer outputting raw hidden-states without any specific head on top.
17711871 */
1772-export class MptModel extends MptPreTrainedModel {
1773-}
1872+export class MptModel extends MptPreTrainedModel {}
17741873 /**
17751874 * The MPT Model transformer with a language modeling head on top (linear layer with weights tied to the input embeddings).
17761875 */
1777-export class MptForCausalLM extends MptPreTrainedModel {
1778-}
1876+export class MptForCausalLM extends MptPreTrainedModel {}
17791877 export class OPTPreTrainedModel extends PreTrainedModel {
1780- /**
1781- * Creates a new instance of the `OPTPreTrainedModel` class.
1782- * @param {Object} config The model configuration object.
1783- * @param {Object} session The ONNX session object.
1784- * @param {GenerationConfig} generation_config The generation configuration.
1785- */
1786- constructor(config: any, session: any, generation_config: new (kwargs?: import("./utils/generation.js").GenerationConfigType) => import("./utils/generation.js").GenerationConfigType);
1787- generation_config: new (kwargs?: import("./utils/generation.js").GenerationConfigType) => import("./utils/generation.js").GenerationConfigType;
1788- num_heads: any;
1789- num_layers: any;
1790- dim_kv: number;
1878+ /**
1879+ * Creates a new instance of the `OPTPreTrainedModel` class.
1880+ * @param {Object} config The model configuration object.
1881+ * @param {Object} session The ONNX session object.
1882+ * @param {GenerationConfig} generation_config The generation configuration.
1883+ */
1884+ constructor(
1885+ config: any,
1886+ session: any,
1887+ generation_config: new (
1888+ kwargs?: import("./utils/generation.js").GenerationConfigType,
1889+ ) => import("./utils/generation.js").GenerationConfigType,
1890+ );
1891+ generation_config: new (
1892+ kwargs?: import("./utils/generation.js").GenerationConfigType,
1893+ ) => import("./utils/generation.js").GenerationConfigType;
1894+ num_heads: any;
1895+ num_layers: any;
1896+ dim_kv: number;
17911897 }
17921898 /**
17931899 * The bare OPT Model outputting raw hidden-states without any specific head on top.
17941900 */
1795-export class OPTModel extends OPTPreTrainedModel {
1796-}
1901+export class OPTModel extends OPTPreTrainedModel {}
17971902 /**
17981903 * The OPT Model transformer with a language modeling head on top (linear layer with weights tied to the input embeddings).
17991904 */
1800-export class OPTForCausalLM extends OPTPreTrainedModel {
1801-}
1802-export class ViTPreTrainedModel extends PreTrainedModel {
1803-}
1804-export class ViTModel extends ViTPreTrainedModel {
1805-}
1905+export class OPTForCausalLM extends OPTPreTrainedModel {}
1906+export class ViTPreTrainedModel extends PreTrainedModel {}
1907+export class ViTModel extends ViTPreTrainedModel {}
18061908 export class ViTForImageClassification extends ViTPreTrainedModel {
1807- /**
1808- * @param {any} model_inputs
1809- */
1810- _call(model_inputs: any): Promise<SequenceClassifierOutput>;
1811-}
1812-export class VitMattePreTrainedModel extends PreTrainedModel {
1909+ /**
1910+ * @param {any} model_inputs
1911+ */
1912+ _call(model_inputs: any): Promise<SequenceClassifierOutput>;
18131913 }
1914+export class VitMattePreTrainedModel extends PreTrainedModel {}
18141915 /**
18151916 * ViTMatte framework leveraging any vision backbone e.g. for ADE20k, CityScapes.
18161917 *
@@ -1867,151 +1968,132 @@
18671968 * ```
18681969 */
18691970 export class VitMatteForImageMatting extends VitMattePreTrainedModel {
1870- /**
1871- * @param {any} model_inputs
1872- */
1873- _call(model_inputs: any): Promise<ImageMattingOutput>;
1874-}
1875-export class MobileViTPreTrainedModel extends PreTrainedModel {
1876-}
1877-export class MobileViTModel extends MobileViTPreTrainedModel {
1878-}
1971+ /**
1972+ * @param {any} model_inputs
1973+ */
1974+ _call(model_inputs: any): Promise<ImageMattingOutput>;
1975+}
1976+export class MobileViTPreTrainedModel extends PreTrainedModel {}
1977+export class MobileViTModel extends MobileViTPreTrainedModel {}
18791978 export class MobileViTForImageClassification extends MobileViTPreTrainedModel {
1880- /**
1881- * @param {any} model_inputs
1882- */
1883- _call(model_inputs: any): Promise<SequenceClassifierOutput>;
1884-}
1885-export class OwlViTPreTrainedModel extends PreTrainedModel {
1886-}
1887-export class OwlViTModel extends OwlViTPreTrainedModel {
1888-}
1889-export class OwlViTForObjectDetection extends OwlViTPreTrainedModel {
1890-}
1891-export class BeitPreTrainedModel extends PreTrainedModel {
1892-}
1893-export class BeitModel extends BeitPreTrainedModel {
1894-}
1979+ /**
1980+ * @param {any} model_inputs
1981+ */
1982+ _call(model_inputs: any): Promise<SequenceClassifierOutput>;
1983+}
1984+export class OwlViTPreTrainedModel extends PreTrainedModel {}
1985+export class OwlViTModel extends OwlViTPreTrainedModel {}
1986+export class OwlViTForObjectDetection extends OwlViTPreTrainedModel {}
1987+export class BeitPreTrainedModel extends PreTrainedModel {}
1988+export class BeitModel extends BeitPreTrainedModel {}
18951989 export class BeitForImageClassification extends BeitPreTrainedModel {
1896- /**
1897- * @param {any} model_inputs
1898- */
1899- _call(model_inputs: any): Promise<SequenceClassifierOutput>;
1900-}
1901-export class DetrPreTrainedModel extends PreTrainedModel {
1902-}
1903-export class DetrModel extends DetrPreTrainedModel {
1904-}
1990+ /**
1991+ * @param {any} model_inputs
1992+ */
1993+ _call(model_inputs: any): Promise<SequenceClassifierOutput>;
1994+}
1995+export class DetrPreTrainedModel extends PreTrainedModel {}
1996+export class DetrModel extends DetrPreTrainedModel {}
19051997 export class DetrForObjectDetection extends DetrPreTrainedModel {
1906- /**
1907- * @param {any} model_inputs
1908- */
1909- _call(model_inputs: any): Promise<DetrObjectDetectionOutput>;
1998+ /**
1999+ * @param {any} model_inputs
2000+ */
2001+ _call(model_inputs: any): Promise<DetrObjectDetectionOutput>;
19102002 }
19112003 export class DetrForSegmentation extends DetrPreTrainedModel {
1912- /**
1913- * Runs the model with the provided inputs
1914- * @param {Object} model_inputs Model inputs
1915- * @returns {Promise<DetrSegmentationOutput>} Object containing segmentation outputs
1916- */
1917- _call(model_inputs: any): Promise<DetrSegmentationOutput>;
2004+ /**
2005+ * Runs the model with the provided inputs
2006+ * @param {Object} model_inputs Model inputs
2007+ * @returns {Promise<DetrSegmentationOutput>} Object containing segmentation outputs
2008+ */
2009+ _call(model_inputs: any): Promise<DetrSegmentationOutput>;
19182010 }
19192011 export class DetrObjectDetectionOutput extends ModelOutput {
1920- /**
1921- * @param {Object} output The output of the model.
1922- * @param {Tensor} output.logits Classification logits (including no-object) for all queries.
1923- * @param {Tensor} output.pred_boxes Normalized boxes coordinates for all queries, represented as (center_x, center_y, width, height).
1924- * These values are normalized in [0, 1], relative to the size of each individual image in the batch (disregarding possible padding).
1925- */
1926- constructor({ logits, pred_boxes }: {
1927- logits: Tensor;
1928- pred_boxes: Tensor;
1929- });
1930- logits: Tensor;
1931- pred_boxes: Tensor;
2012+ /**
2013+ * @param {Object} output The output of the model.
2014+ * @param {Tensor} output.logits Classification logits (including no-object) for all queries.
2015+ * @param {Tensor} output.pred_boxes Normalized boxes coordinates for all queries, represented as (center_x, center_y, width, height).
2016+ * These values are normalized in [0, 1], relative to the size of each individual image in the batch (disregarding possible padding).
2017+ */
2018+ constructor({ logits, pred_boxes }: { logits: Tensor; pred_boxes: Tensor });
2019+ logits: Tensor;
2020+ pred_boxes: Tensor;
19322021 }
19332022 export class DetrSegmentationOutput extends ModelOutput {
1934- /**
1935- * @param {Object} output The output of the model.
1936- * @param {Tensor} output.logits The output logits of the model.
1937- * @param {Tensor} output.pred_boxes Predicted boxes.
1938- * @param {Tensor} output.pred_masks Predicted masks.
1939- */
1940- constructor({ logits, pred_boxes, pred_masks }: {
1941- logits: Tensor;
1942- pred_boxes: Tensor;
1943- pred_masks: Tensor;
1944- });
2023+ /**
2024+ * @param {Object} output The output of the model.
2025+ * @param {Tensor} output.logits The output logits of the model.
2026+ * @param {Tensor} output.pred_boxes Predicted boxes.
2027+ * @param {Tensor} output.pred_masks Predicted masks.
2028+ */
2029+ constructor({
2030+ logits,
2031+ pred_boxes,
2032+ pred_masks,
2033+ }: {
19452034 logits: Tensor;
19462035 pred_boxes: Tensor;
19472036 pred_masks: Tensor;
2037+ });
2038+ logits: Tensor;
2039+ pred_boxes: Tensor;
2040+ pred_masks: Tensor;
19482041 }
1949-export class TableTransformerPreTrainedModel extends PreTrainedModel {
1950-}
2042+export class TableTransformerPreTrainedModel extends PreTrainedModel {}
19512043 /**
19522044 * The bare Table Transformer Model (consisting of a backbone and encoder-decoder Transformer)
19532045 * outputting raw hidden-states without any specific head on top.
19542046 */
1955-export class TableTransformerModel extends TableTransformerPreTrainedModel {
1956-}
2047+export class TableTransformerModel extends TableTransformerPreTrainedModel {}
19572048 /**
19582049 * Table Transformer Model (consisting of a backbone and encoder-decoder Transformer)
19592050 * with object detection heads on top, for tasks such as COCO detection.
19602051 */
19612052 export class TableTransformerForObjectDetection extends TableTransformerPreTrainedModel {
1962- /**
1963- * @param {any} model_inputs
1964- */
1965- _call(model_inputs: any): Promise<TableTransformerObjectDetectionOutput>;
1966-}
1967-export class TableTransformerObjectDetectionOutput extends DetrObjectDetectionOutput {
1968-}
1969-export class DeiTPreTrainedModel extends PreTrainedModel {
1970-}
1971-export class DeiTModel extends DeiTPreTrainedModel {
1972-}
2053+ /**
2054+ * @param {any} model_inputs
2055+ */
2056+ _call(model_inputs: any): Promise<TableTransformerObjectDetectionOutput>;
2057+}
2058+export class TableTransformerObjectDetectionOutput extends DetrObjectDetectionOutput {}
2059+export class DeiTPreTrainedModel extends PreTrainedModel {}
2060+export class DeiTModel extends DeiTPreTrainedModel {}
19732061 export class DeiTForImageClassification extends DeiTPreTrainedModel {
1974- /**
1975- * @param {any} model_inputs
1976- */
1977- _call(model_inputs: any): Promise<SequenceClassifierOutput>;
2062+ /**
2063+ * @param {any} model_inputs
2064+ */
2065+ _call(model_inputs: any): Promise<SequenceClassifierOutput>;
19782066 }
19792067 /**
19802068 * An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained models.
19812069 */
1982-export class ResNetPreTrainedModel extends PreTrainedModel {
1983-}
2070+export class ResNetPreTrainedModel extends PreTrainedModel {}
19842071 /**
19852072 * The bare ResNet model outputting raw features without any specific head on top.
19862073 */
1987-export class ResNetModel extends ResNetPreTrainedModel {
1988-}
2074+export class ResNetModel extends ResNetPreTrainedModel {}
19892075 /**
19902076 * ResNet Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for ImageNet.
19912077 */
19922078 export class ResNetForImageClassification extends ResNetPreTrainedModel {
1993- /**
1994- * @param {any} model_inputs
1995- */
1996- _call(model_inputs: any): Promise<SequenceClassifierOutput>;
1997-}
1998-export class SwinPreTrainedModel extends PreTrainedModel {
1999-}
2000-export class SwinModel extends SwinPreTrainedModel {
2001-}
2079+ /**
2080+ * @param {any} model_inputs
2081+ */
2082+ _call(model_inputs: any): Promise<SequenceClassifierOutput>;
2083+}
2084+export class SwinPreTrainedModel extends PreTrainedModel {}
2085+export class SwinModel extends SwinPreTrainedModel {}
20022086 export class SwinForImageClassification extends SwinPreTrainedModel {
2003- /**
2004- * @param {any} model_inputs
2005- */
2006- _call(model_inputs: any): Promise<SequenceClassifierOutput>;
2007-}
2008-export class Swin2SRPreTrainedModel extends PreTrainedModel {
2087+ /**
2088+ * @param {any} model_inputs
2089+ */
2090+ _call(model_inputs: any): Promise<SequenceClassifierOutput>;
20092091 }
2092+export class Swin2SRPreTrainedModel extends PreTrainedModel {}
20102093 /**
20112094 * The bare Swin2SR Model transformer outputting raw hidden-states without any specific head on top.
20122095 */
2013-export class Swin2SRModel extends Swin2SRPreTrainedModel {
2014-}
2096+export class Swin2SRModel extends Swin2SRPreTrainedModel {}
20152097 /**
20162098 * Swin2SR Model transformer with an upsampler head on top for image super resolution and restoration.
20172099 *
@@ -2044,15 +2126,12 @@
20442126 * // }
20452127 * ```
20462128 */
2047-export class Swin2SRForImageSuperResolution extends Swin2SRPreTrainedModel {
2048-}
2049-export class DPTPreTrainedModel extends PreTrainedModel {
2050-}
2129+export class Swin2SRForImageSuperResolution extends Swin2SRPreTrainedModel {}
2130+export class DPTPreTrainedModel extends PreTrainedModel {}
20512131 /**
20522132 * The bare DPT Model transformer outputting raw hidden-states without any specific head on top.
20532133 */
2054-export class DPTModel extends DPTPreTrainedModel {
2055-}
2134+export class DPTModel extends DPTPreTrainedModel {}
20562135 /**
20572136 * DPT Model with a depth estimation head on top (consisting of 3 convolutional layers) e.g. for KITTI, NYUv2.
20582137 *
@@ -2089,15 +2168,12 @@
20892168 * // }
20902169 * ```
20912170 */
2092-export class DPTForDepthEstimation extends DPTPreTrainedModel {
2093-}
2094-export class GLPNPreTrainedModel extends PreTrainedModel {
2095-}
2171+export class DPTForDepthEstimation extends DPTPreTrainedModel {}
2172+export class GLPNPreTrainedModel extends PreTrainedModel {}
20962173 /**
20972174 * The bare GLPN encoder (Mix-Transformer) outputting raw hidden-states without any specific head on top.
20982175 */
2099-export class GLPNModel extends GLPNPreTrainedModel {
2100-}
2176+export class GLPNModel extends GLPNPreTrainedModel {}
21012177 /**
21022178 * GLPN Model transformer with a lightweight depth estimation head on top e.g. for KITTI, NYUv2.
21032179 *
@@ -2134,10 +2210,8 @@
21342210 * // }
21352211 * ```
21362212 */
2137-export class GLPNForDepthEstimation extends GLPNPreTrainedModel {
2138-}
2139-export class DonutSwinPreTrainedModel extends PreTrainedModel {
2140-}
2213+export class GLPNForDepthEstimation extends GLPNPreTrainedModel {}
2214+export class DonutSwinPreTrainedModel extends PreTrainedModel {}
21412215 /**
21422216 * The bare Donut Swin Model transformer outputting raw hidden-states without any specific head on top.
21432217 *
@@ -2212,82 +2286,69 @@
22122286 * // <s_docvqa><s_question> What is the invoice number?</s_question><s_answer> us-001</s_answer></s>
22132287 * ```
22142288 */
2215-export class DonutSwinModel extends DonutSwinPreTrainedModel {
2216-}
2217-export class ConvNextPreTrainedModel extends PreTrainedModel {
2218-}
2289+export class DonutSwinModel extends DonutSwinPreTrainedModel {}
2290+export class ConvNextPreTrainedModel extends PreTrainedModel {}
22192291 /**
22202292 * The bare ConvNext model outputting raw features without any specific head on top.
22212293 */
2222-export class ConvNextModel extends ConvNextPreTrainedModel {
2223-}
2294+export class ConvNextModel extends ConvNextPreTrainedModel {}
22242295 /**
22252296 * ConvNext Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for ImageNet.
22262297 */
22272298 export class ConvNextForImageClassification extends ConvNextPreTrainedModel {
2228- /**
2229- * @param {any} model_inputs
2230- */
2231- _call(model_inputs: any): Promise<SequenceClassifierOutput>;
2232-}
2233-export class ConvNextV2PreTrainedModel extends PreTrainedModel {
2299+ /**
2300+ * @param {any} model_inputs
2301+ */
2302+ _call(model_inputs: any): Promise<SequenceClassifierOutput>;
22342303 }
2304+export class ConvNextV2PreTrainedModel extends PreTrainedModel {}
22352305 /**
22362306 * The bare ConvNextV2 model outputting raw features without any specific head on top.
22372307 */
2238-export class ConvNextV2Model extends ConvNextV2PreTrainedModel {
2239-}
2308+export class ConvNextV2Model extends ConvNextV2PreTrainedModel {}
22402309 /**
22412310 * ConvNextV2 Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for ImageNet.
22422311 */
22432312 export class ConvNextV2ForImageClassification extends ConvNextV2PreTrainedModel {
2244- /**
2245- * @param {any} model_inputs
2246- */
2247- _call(model_inputs: any): Promise<SequenceClassifierOutput>;
2248-}
2249-export class Dinov2PreTrainedModel extends PreTrainedModel {
2313+ /**
2314+ * @param {any} model_inputs
2315+ */
2316+ _call(model_inputs: any): Promise<SequenceClassifierOutput>;
22502317 }
2318+export class Dinov2PreTrainedModel extends PreTrainedModel {}
22512319 /**
22522320 * The bare DINOv2 Model transformer outputting raw hidden-states without any specific head on top.
22532321 */
2254-export class Dinov2Model extends Dinov2PreTrainedModel {
2255-}
2322+export class Dinov2Model extends Dinov2PreTrainedModel {}
22562323 /**
22572324 * Dinov2 Model transformer with an image classification head on top (a linear layer on top of the final hidden state of the [CLS] token) e.g. for ImageNet.
22582325 */
22592326 export class Dinov2ForImageClassification extends Dinov2PreTrainedModel {
2260- /**
2261- * @param {any} model_inputs
2262- */
2263- _call(model_inputs: any): Promise<SequenceClassifierOutput>;
2264-}
2265-export class YolosPreTrainedModel extends PreTrainedModel {
2266-}
2267-export class YolosModel extends YolosPreTrainedModel {
2268-}
2327+ /**
2328+ * @param {any} model_inputs
2329+ */
2330+ _call(model_inputs: any): Promise<SequenceClassifierOutput>;
2331+}
2332+export class YolosPreTrainedModel extends PreTrainedModel {}
2333+export class YolosModel extends YolosPreTrainedModel {}
22692334 export class YolosForObjectDetection extends YolosPreTrainedModel {
2270- /**
2271- * @param {any} model_inputs
2272- */
2273- _call(model_inputs: any): Promise<YolosObjectDetectionOutput>;
2335+ /**
2336+ * @param {any} model_inputs
2337+ */
2338+ _call(model_inputs: any): Promise<YolosObjectDetectionOutput>;
22742339 }
22752340 export class YolosObjectDetectionOutput extends ModelOutput {
2276- /**
2277- * @param {Object} output The output of the model.
2278- * @param {Tensor} output.logits Classification logits (including no-object) for all queries.
2279- * @param {Tensor} output.pred_boxes Normalized boxes coordinates for all queries, represented as (center_x, center_y, width, height).
2280- * These values are normalized in [0, 1], relative to the size of each individual image in the batch (disregarding possible padding).
2281- */
2282- constructor({ logits, pred_boxes }: {
2283- logits: Tensor;
2284- pred_boxes: Tensor;
2285- });
2286- logits: Tensor;
2287- pred_boxes: Tensor;
2288-}
2289-export class SamPreTrainedModel extends PreTrainedModel {
2290-}
2341+ /**
2342+ * @param {Object} output The output of the model.
2343+ * @param {Tensor} output.logits Classification logits (including no-object) for all queries.
2344+ * @param {Tensor} output.pred_boxes Normalized boxes coordinates for all queries, represented as (center_x, center_y, width, height).
2345+ * These values are normalized in [0, 1], relative to the size of each individual image in the batch (disregarding possible padding).
2346+ */
2347+ constructor({ logits, pred_boxes }: { logits: Tensor; pred_boxes: Tensor });
2348+ logits: Tensor;
2349+ pred_boxes: Tensor;
2350+}
2351+export class SamPreTrainedModel extends PreTrainedModel {}
22912352 /**
22922353 * Segment Anything Model (SAM) for generating segmentation masks, given an input image
22932354 * and optional 2D location and bounding boxes.
@@ -2329,143 +2390,153 @@
23292390 * ```
23302391 */
23312392 export class SamModel extends SamPreTrainedModel {
2332- /**
2333- * Creates a new instance of the `SamModel` class.
2334- * @param {Object} config The configuration object specifying the hyperparameters and other model settings.
2335- * @param {Object} vision_encoder The ONNX session containing the vision encoder model.
2336- * @param {any} prompt_encoder_mask_decoder The ONNX session containing the prompt encoder and mask decoder model.
2393+ /**
2394+ * Creates a new instance of the `SamModel` class.
2395+ * @param {Object} config The configuration object specifying the hyperparameters and other model settings.
2396+ * @param {Object} vision_encoder The ONNX session containing the vision encoder model.
2397+ * @param {any} prompt_encoder_mask_decoder The ONNX session containing the prompt encoder and mask decoder model.
2398+ */
2399+ constructor(
2400+ config: any,
2401+ vision_encoder: any,
2402+ prompt_encoder_mask_decoder: any,
2403+ );
2404+ prompt_encoder_mask_decoder: any;
2405+ /**
2406+ * Compute image embeddings and positional image embeddings, given the pixel values of an image.
2407+ * @param {Object} model_inputs Object containing the model inputs.
2408+ * @param {Tensor} model_inputs.pixel_values Pixel values obtained using a `SamProcessor`.
2409+ * @returns {Promise<{ image_embeddings: Tensor, image_positional_embeddings: Tensor }>} The image embeddings and positional image embeddings.
2410+ */
2411+ get_image_embeddings({ pixel_values }: { pixel_values: Tensor }): Promise<{
2412+ image_embeddings: Tensor;
2413+ image_positional_embeddings: Tensor;
2414+ }>;
2415+ /**
2416+ * @typedef {Object} SamModelInputs Object containing the model inputs.
2417+ * @property {Tensor} pixel_values Pixel values as a Tensor with shape `(batch_size, num_channels, height, width)`.
2418+ * These can be obtained using a `SamProcessor`.
2419+ * @property {Tensor} input_points Input 2D spatial points with shape `(batch_size, num_points, 2)`.
2420+ * This is used by the prompt encoder to encode the prompt.
2421+ * @property {Tensor} [input_labels] Input labels for the points, as a Tensor of shape `(batch_size, point_batch_size, num_points)`.
2422+ * This is used by the prompt encoder to encode the prompt. There are 4 types of labels:
2423+ * - `1`: the point is a point that contains the object of interest
2424+ * - `0`: the point is a point that does not contain the object of interest
2425+ * - `-1`: the point corresponds to the background
2426+ * - `-10`: the point is a padding point, thus should be ignored by the prompt encoder
2427+ * @property {Tensor} [image_embeddings] Image embeddings used by the mask decoder.
2428+ * @property {Tensor} [image_positional_embeddings] Image positional embeddings used by the mask decoder.
2429+ */
2430+ /**
2431+ * @param {SamModelInputs} model_inputs Object containing the model inputs.
2432+ * @returns {Promise<Object>} The output of the model.
2433+ */
2434+ forward(model_inputs: {
2435+ /**
2436+ * Pixel values as a Tensor with shape `(batch_size, num_channels, height, width)`.
2437+ * These can be obtained using a `SamProcessor`.
23372438 */
2338- constructor(config: any, vision_encoder: any, prompt_encoder_mask_decoder: any);
2339- prompt_encoder_mask_decoder: any;
2439+ pixel_values: Tensor;
23402440 /**
2341- * Compute image embeddings and positional image embeddings, given the pixel values of an image.
2342- * @param {Object} model_inputs Object containing the model inputs.
2343- * @param {Tensor} model_inputs.pixel_values Pixel values obtained using a `SamProcessor`.
2344- * @returns {Promise<{ image_embeddings: Tensor, image_positional_embeddings: Tensor }>} The image embeddings and positional image embeddings.
2441+ * Input 2D spatial points with shape `(batch_size, num_points, 2)`.
2442+ * This is used by the prompt encoder to encode the prompt.
23452443 */
2346- get_image_embeddings({ pixel_values }: {
2347- pixel_values: Tensor;
2348- }): Promise<{
2349- image_embeddings: Tensor;
2350- image_positional_embeddings: Tensor;
2351- }>;
2444+ input_points: Tensor;
23522445 /**
2353- * @typedef {Object} SamModelInputs Object containing the model inputs.
2354- * @property {Tensor} pixel_values Pixel values as a Tensor with shape `(batch_size, num_channels, height, width)`.
2355- * These can be obtained using a `SamProcessor`.
2356- * @property {Tensor} input_points Input 2D spatial points with shape `(batch_size, num_points, 2)`.
2357- * This is used by the prompt encoder to encode the prompt.
2358- * @property {Tensor} [input_labels] Input labels for the points, as a Tensor of shape `(batch_size, point_batch_size, num_points)`.
2446+ * Input labels for the points, as a Tensor of shape `(batch_size, point_batch_size, num_points)`.
23592447 * This is used by the prompt encoder to encode the prompt. There are 4 types of labels:
2360- * - `1`: the point is a point that contains the object of interest
2361- * - `0`: the point is a point that does not contain the object of interest
2362- * - `-1`: the point corresponds to the background
2363- * - `-10`: the point is a padding point, thus should be ignored by the prompt encoder
2364- * @property {Tensor} [image_embeddings] Image embeddings used by the mask decoder.
2365- * @property {Tensor} [image_positional_embeddings] Image positional embeddings used by the mask decoder.
2448+ * - `1`: the point is a point that contains the object of interest
2449+ * - `0`: the point is a point that does not contain the object of interest
2450+ * - `-1`: the point corresponds to the background
2451+ * - `-10`: the point is a padding point, thus should be ignored by the prompt encoder
23662452 */
2453+ input_labels?: Tensor;
23672454 /**
2368- * @param {SamModelInputs} model_inputs Object containing the model inputs.
2369- * @returns {Promise<Object>} The output of the model.
2455+ * Image embeddings used by the mask decoder.
23702456 */
2371- forward(model_inputs: {
2372- /**
2373- * Pixel values as a Tensor with shape `(batch_size, num_channels, height, width)`.
2374- * These can be obtained using a `SamProcessor`.
2375- */
2376- pixel_values: Tensor;
2377- /**
2378- * Input 2D spatial points with shape `(batch_size, num_points, 2)`.
2379- * This is used by the prompt encoder to encode the prompt.
2380- */
2381- input_points: Tensor;
2382- /**
2383- * Input labels for the points, as a Tensor of shape `(batch_size, point_batch_size, num_points)`.
2384- * This is used by the prompt encoder to encode the prompt. There are 4 types of labels:
2385- * - `1`: the point is a point that contains the object of interest
2386- * - `0`: the point is a point that does not contain the object of interest
2387- * - `-1`: the point corresponds to the background
2388- * - `-10`: the point is a padding point, thus should be ignored by the prompt encoder
2389- */
2390- input_labels?: Tensor;
2391- /**
2392- * Image embeddings used by the mask decoder.
2393- */
2394- image_embeddings?: Tensor;
2395- /**
2396- * Image positional embeddings used by the mask decoder.
2397- */
2398- image_positional_embeddings?: Tensor;
2399- }): Promise<any>;
2457+ image_embeddings?: Tensor;
24002458 /**
2401- * Runs the model with the provided inputs
2402- * @param {Object} model_inputs Model inputs
2403- * @returns {Promise<SamImageSegmentationOutput>} Object containing segmentation outputs
2459+ * Image positional embeddings used by the mask decoder.
24042460 */
2405- _call(model_inputs: any): Promise<SamImageSegmentationOutput>;
2461+ image_positional_embeddings?: Tensor;
2462+ }): Promise<any>;
2463+ /**
2464+ * Runs the model with the provided inputs
2465+ * @param {Object} model_inputs Model inputs
2466+ * @returns {Promise<SamImageSegmentationOutput>} Object containing segmentation outputs
2467+ */
2468+ _call(model_inputs: any): Promise<SamImageSegmentationOutput>;
24062469 }
24072470 /**
24082471 * Base class for Segment-Anything model's output.
24092472 */
24102473 export class SamImageSegmentationOutput extends ModelOutput {
2411- /**
2412- * @param {Object} output The output of the model.
2413- * @param {Tensor} output.iou_scores The output logits of the model.
2414- * @param {Tensor} output.pred_masks Predicted boxes.
2415- */
2416- constructor({ iou_scores, pred_masks }: {
2417- iou_scores: Tensor;
2418- pred_masks: Tensor;
2419- });
2474+ /**
2475+ * @param {Object} output The output of the model.
2476+ * @param {Tensor} output.iou_scores The output logits of the model.
2477+ * @param {Tensor} output.pred_masks Predicted boxes.
2478+ */
2479+ constructor({
2480+ iou_scores,
2481+ pred_masks,
2482+ }: {
24202483 iou_scores: Tensor;
24212484 pred_masks: Tensor;
2422-}
2423-export class MarianPreTrainedModel extends PreTrainedModel {
2424-}
2425-export class MarianModel extends MarianPreTrainedModel {
2426-}
2485+ });
2486+ iou_scores: Tensor;
2487+ pred_masks: Tensor;
2488+}
2489+export class MarianPreTrainedModel extends PreTrainedModel {}
2490+export class MarianModel extends MarianPreTrainedModel {}
24272491 export class MarianMTModel extends MarianPreTrainedModel {
2428- /**
2429- * Creates a new instance of the `MarianMTModel` class.
2430- * @param {Object} config The model configuration object.
2431- * @param {Object} session The ONNX session object.
2432- * @param {any} decoder_merged_session
2433- * @param {any} generation_config
2434- */
2435- constructor(config: any, session: any, decoder_merged_session: any, generation_config: any);
2436- decoder_merged_session: any;
2437- generation_config: any;
2438- num_decoder_layers: any;
2439- num_decoder_heads: any;
2440- decoder_dim_kv: number;
2441- num_encoder_layers: any;
2442- num_encoder_heads: any;
2443- encoder_dim_kv: number;
2444-}
2445-export class M2M100PreTrainedModel extends PreTrainedModel {
2446-}
2447-export class M2M100Model extends M2M100PreTrainedModel {
2448-}
2492+ /**
2493+ * Creates a new instance of the `MarianMTModel` class.
2494+ * @param {Object} config The model configuration object.
2495+ * @param {Object} session The ONNX session object.
2496+ * @param {any} decoder_merged_session
2497+ * @param {any} generation_config
2498+ */
2499+ constructor(
2500+ config: any,
2501+ session: any,
2502+ decoder_merged_session: any,
2503+ generation_config: any,
2504+ );
2505+ decoder_merged_session: any;
2506+ generation_config: any;
2507+ num_decoder_layers: any;
2508+ num_decoder_heads: any;
2509+ decoder_dim_kv: number;
2510+ num_encoder_layers: any;
2511+ num_encoder_heads: any;
2512+ encoder_dim_kv: number;
2513+}
2514+export class M2M100PreTrainedModel extends PreTrainedModel {}
2515+export class M2M100Model extends M2M100PreTrainedModel {}
24492516 export class M2M100ForConditionalGeneration extends M2M100PreTrainedModel {
2450- /**
2451- * Creates a new instance of the `M2M100ForConditionalGeneration` class.
2452- * @param {Object} config The model configuration object.
2453- * @param {Object} session The ONNX session object.
2454- * @param {any} decoder_merged_session
2455- * @param {any} generation_config
2456- */
2457- constructor(config: any, session: any, decoder_merged_session: any, generation_config: any);
2458- decoder_merged_session: any;
2459- generation_config: any;
2460- num_decoder_layers: any;
2461- num_decoder_heads: any;
2462- decoder_dim_kv: number;
2463- num_encoder_layers: any;
2464- num_encoder_heads: any;
2465- encoder_dim_kv: number;
2466-}
2467-export class Wav2Vec2PreTrainedModel extends PreTrainedModel {
2468-}
2517+ /**
2518+ * Creates a new instance of the `M2M100ForConditionalGeneration` class.
2519+ * @param {Object} config The model configuration object.
2520+ * @param {Object} session The ONNX session object.
2521+ * @param {any} decoder_merged_session
2522+ * @param {any} generation_config
2523+ */
2524+ constructor(
2525+ config: any,
2526+ session: any,
2527+ decoder_merged_session: any,
2528+ generation_config: any,
2529+ );
2530+ decoder_merged_session: any;
2531+ generation_config: any;
2532+ num_decoder_layers: any;
2533+ num_decoder_heads: any;
2534+ decoder_dim_kv: number;
2535+ num_encoder_layers: any;
2536+ num_encoder_heads: any;
2537+ encoder_dim_kv: number;
2538+}
2539+export class Wav2Vec2PreTrainedModel extends PreTrainedModel {}
24692540 /**
24702541 * The bare Wav2Vec2 Model transformer outputting raw hidden-states without any specific head on top.
24712542 *
@@ -2492,29 +2563,27 @@
24922563 * // }
24932564 * ```
24942565 */
2495-export class Wav2Vec2Model extends Wav2Vec2PreTrainedModel {
2496-}
2566+export class Wav2Vec2Model extends Wav2Vec2PreTrainedModel {}
24972567 export class Wav2Vec2ForCTC extends Wav2Vec2PreTrainedModel {
2498- /**
2499- * @param {Object} model_inputs
2500- * @param {Tensor} model_inputs.input_values Float values of input raw speech waveform.
2501- * @param {Tensor} model_inputs.attention_mask Mask to avoid performing convolution and attention on padding token indices. Mask values selected in [0, 1]
2502- */
2503- _call(model_inputs: {
2504- input_values: Tensor;
2505- attention_mask: Tensor;
2506- }): Promise<CausalLMOutput>;
2568+ /**
2569+ * @param {Object} model_inputs
2570+ * @param {Tensor} model_inputs.input_values Float values of input raw speech waveform.
2571+ * @param {Tensor} model_inputs.attention_mask Mask to avoid performing convolution and attention on padding token indices. Mask values selected in [0, 1]
2572+ */
2573+ _call(model_inputs: {
2574+ input_values: Tensor;
2575+ attention_mask: Tensor;
2576+ }): Promise<CausalLMOutput>;
25072577 }
25082578 export class Wav2Vec2ForSequenceClassification extends Wav2Vec2PreTrainedModel {
2509- /**
2510- * Calls the model on new inputs.
2511- * @param {Object} model_inputs The inputs to the model.
2512- * @returns {Promise<SequenceClassifierOutput>} An object containing the model's output logits for sequence classification.
2513- */
2514- _call(model_inputs: any): Promise<SequenceClassifierOutput>;
2515-}
2516-export class HubertPreTrainedModel extends PreTrainedModel {
2517-}
2579+ /**
2580+ * Calls the model on new inputs.
2581+ * @param {Object} model_inputs The inputs to the model.
2582+ * @returns {Promise<SequenceClassifierOutput>} An object containing the model's output logits for sequence classification.
2583+ */
2584+ _call(model_inputs: any): Promise<SequenceClassifierOutput>;
2585+}
2586+export class HubertPreTrainedModel extends PreTrainedModel {}
25182587 /**
25192588 * The bare Hubert Model transformer outputting raw hidden-states without any specific head on top.
25202589 *
@@ -2541,38 +2610,36 @@
25412610 * // }
25422611 * ```
25432612 */
2544-export class HubertModel extends Wav2Vec2PreTrainedModel {
2545-}
2613+export class HubertModel extends Wav2Vec2PreTrainedModel {}
25462614 /**
25472615 * Hubert Model with a `language modeling` head on top for Connectionist Temporal Classification (CTC).
25482616 */
25492617 export class HubertForCTC extends Wav2Vec2PreTrainedModel {
2550- /**
2551- * @param {Object} model_inputs
2552- * @param {Tensor} model_inputs.input_values Float values of input raw speech waveform.
2553- * @param {Tensor} model_inputs.attention_mask Mask to avoid performing convolution and attention on padding token indices. Mask values selected in [0, 1]
2554- */
2555- _call(model_inputs: {
2556- input_values: Tensor;
2557- attention_mask: Tensor;
2558- }): Promise<CausalLMOutput>;
2618+ /**
2619+ * @param {Object} model_inputs
2620+ * @param {Tensor} model_inputs.input_values Float values of input raw speech waveform.
2621+ * @param {Tensor} model_inputs.attention_mask Mask to avoid performing convolution and attention on padding token indices. Mask values selected in [0, 1]
2622+ */
2623+ _call(model_inputs: {
2624+ input_values: Tensor;
2625+ attention_mask: Tensor;
2626+ }): Promise<CausalLMOutput>;
25592627 }
25602628 /**
25612629 * Hubert Model with a sequence classification head on top (a linear layer over the pooled output) for tasks like SUPERB Keyword Spotting.
25622630 */
25632631 export class HubertForSequenceClassification extends Wav2Vec2PreTrainedModel {
2564- /**
2565- * Calls the model on new inputs.
2566- * @param {Object} model_inputs The inputs to the model.
2567- * @returns {Promise<SequenceClassifierOutput>} An object containing the model's output logits for sequence classification.
2568- */
2569- _call(model_inputs: any): Promise<SequenceClassifierOutput>;
2632+ /**
2633+ * Calls the model on new inputs.
2634+ * @param {Object} model_inputs The inputs to the model.
2635+ * @returns {Promise<SequenceClassifierOutput>} An object containing the model's output logits for sequence classification.
2636+ */
2637+ _call(model_inputs: any): Promise<SequenceClassifierOutput>;
25702638 }
25712639 /**
25722640 * An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained models.
25732641 */
2574-export class WavLMPreTrainedModel extends PreTrainedModel {
2575-}
2642+export class WavLMPreTrainedModel extends PreTrainedModel {}
25762643 /**
25772644 * The bare WavLM Model transformer outputting raw hidden-states without any specific head on top.
25782645 *
@@ -2599,43 +2666,40 @@
25992666 * // }
26002667 * ```
26012668 */
2602-export class WavLMModel extends WavLMPreTrainedModel {
2603-}
2669+export class WavLMModel extends WavLMPreTrainedModel {}
26042670 /**
26052671 * WavLM Model with a `language modeling` head on top for Connectionist Temporal Classification (CTC).
26062672 */
26072673 export class WavLMForCTC extends WavLMPreTrainedModel {
2608- /**
2609- * @param {Object} model_inputs
2610- * @param {Tensor} model_inputs.input_values Float values of input raw speech waveform.
2611- * @param {Tensor} model_inputs.attention_mask Mask to avoid performing convolution and attention on padding token indices. Mask values selected in [0, 1]
2612- */
2613- _call(model_inputs: {
2614- input_values: Tensor;
2615- attention_mask: Tensor;
2616- }): Promise<CausalLMOutput>;
2674+ /**
2675+ * @param {Object} model_inputs
2676+ * @param {Tensor} model_inputs.input_values Float values of input raw speech waveform.
2677+ * @param {Tensor} model_inputs.attention_mask Mask to avoid performing convolution and attention on padding token indices. Mask values selected in [0, 1]
2678+ */
2679+ _call(model_inputs: {
2680+ input_values: Tensor;
2681+ attention_mask: Tensor;
2682+ }): Promise<CausalLMOutput>;
26172683 }
26182684 /**
26192685 * WavLM Model with a sequence classification head on top (a linear layer over the pooled output).
26202686 */
26212687 export class WavLMForSequenceClassification extends WavLMPreTrainedModel {
2622- /**
2623- * Calls the model on new inputs.
2624- * @param {Object} model_inputs The inputs to the model.
2625- * @returns {Promise<SequenceClassifierOutput>} An object containing the model's output logits for sequence classification.
2626- */
2627- _call(model_inputs: any): Promise<SequenceClassifierOutput>;
2688+ /**
2689+ * Calls the model on new inputs.
2690+ * @param {Object} model_inputs The inputs to the model.
2691+ * @returns {Promise<SequenceClassifierOutput>} An object containing the model's output logits for sequence classification.
2692+ */
2693+ _call(model_inputs: any): Promise<SequenceClassifierOutput>;
26282694 }
26292695 /**
26302696 * An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained models.
26312697 */
2632-export class SpeechT5PreTrainedModel extends PreTrainedModel {
2633-}
2698+export class SpeechT5PreTrainedModel extends PreTrainedModel {}
26342699 /**
26352700 * The bare SpeechT5 Encoder-Decoder Model outputting raw hidden-states without any specific pre- or post-nets.
26362701 */
2637-export class SpeechT5Model extends SpeechT5PreTrainedModel {
2638-}
2702+export class SpeechT5Model extends SpeechT5PreTrainedModel {}
26392703 /**
26402704 * SpeechT5 Model with a speech encoder and a text decoder.
26412705 *
@@ -2676,143 +2740,176 @@
26762740 * // }
26772741 * ```
26782742 */
2679-export class SpeechT5ForSpeechToText extends SpeechT5PreTrainedModel {
2680-}
2743+export class SpeechT5ForSpeechToText extends SpeechT5PreTrainedModel {}
26812744 /**
26822745 * SpeechT5 Model with a text encoder and a speech decoder.
26832746 */
26842747 export class SpeechT5ForTextToSpeech extends SpeechT5PreTrainedModel {
2685- /**
2686- * Creates a new instance of the `SpeechT5ForTextToSpeech` class.
2687- * @param {Object} config The model configuration.
2688- * @param {any} session session for the model.
2689- * @param {any} decoder_merged_session session for the decoder.
2690- * @param {GenerationConfig} generation_config The generation configuration.
2748+ /**
2749+ * Creates a new instance of the `SpeechT5ForTextToSpeech` class.
2750+ * @param {Object} config The model configuration.
2751+ * @param {any} session session for the model.
2752+ * @param {any} decoder_merged_session session for the decoder.
2753+ * @param {GenerationConfig} generation_config The generation configuration.
2754+ */
2755+ constructor(
2756+ config: any,
2757+ session: any,
2758+ decoder_merged_session: any,
2759+ generation_config: new (
2760+ kwargs?: import("./utils/generation.js").GenerationConfigType,
2761+ ) => import("./utils/generation.js").GenerationConfigType,
2762+ );
2763+ decoder_merged_session: any;
2764+ generation_config: new (
2765+ kwargs?: import("./utils/generation.js").GenerationConfigType,
2766+ ) => import("./utils/generation.js").GenerationConfigType;
2767+ num_decoder_layers: any;
2768+ num_decoder_heads: any;
2769+ decoder_dim_kv: number;
2770+ num_encoder_layers: any;
2771+ num_encoder_heads: any;
2772+ encoder_dim_kv: number;
2773+ /**
2774+ * @typedef {Object} SpeechOutput
2775+ * @property {Tensor} [spectrogram] The predicted log-mel spectrogram of shape
2776+ * `(output_sequence_length, config.num_mel_bins)`. Returned when no `vocoder` is provided
2777+ * @property {Tensor} [waveform] The predicted waveform of shape `(num_frames,)`. Returned when a `vocoder` is provided.
2778+ * @property {Tensor} [cross_attentions] The outputs of the decoder's cross-attention layers of shape
2779+ * `(config.decoder_layers, config.decoder_attention_heads, output_sequence_length, input_sequence_length)`. returned when `output_cross_attentions` is `true`.
2780+ */
2781+ /**
2782+ * Converts a sequence of input tokens into a sequence of mel spectrograms, which are subsequently turned into a speech waveform using a vocoder.
2783+ * @param {Tensor} input_values Indices of input sequence tokens in the vocabulary.
2784+ * @param {Tensor} speaker_embeddings Tensor containing the speaker embeddings.
2785+ * @param {Object} options Optional parameters for generating speech.
2786+ * @param {number} [options.threshold=0.5] The generated sequence ends when the predicted stop token probability exceeds this value.
2787+ * @param {number} [options.minlenratio=0.0] Used to calculate the minimum required length for the output sequence.
2788+ * @param {number} [options.maxlenratio=20.0] Used to calculate the maximum allowed length for the output sequence.
2789+ * @param {Object} [options.vocoder=null] The vocoder that converts the mel spectrogram into a speech waveform. If `null`, the output is the mel spectrogram.
2790+ * @param {boolean} [options.output_cross_attentions=false] Whether or not to return the attentions tensors of the decoder's cross-attention layers.
2791+ * @returns {Promise<SpeechOutput>} A promise which resolves to an object containing the spectrogram, waveform, and cross-attention tensors.
2792+ */
2793+ generate_speech(
2794+ input_values: Tensor,
2795+ speaker_embeddings: Tensor,
2796+ {
2797+ threshold,
2798+ minlenratio,
2799+ maxlenratio,
2800+ vocoder,
2801+ }?: {
2802+ threshold?: number;
2803+ minlenratio?: number;
2804+ maxlenratio?: number;
2805+ vocoder?: any;
2806+ output_cross_attentions?: boolean;
2807+ },
2808+ ): Promise<{
2809+ /**
2810+ * The predicted log-mel spectrogram of shape
2811+ * `(output_sequence_length, config.num_mel_bins)`. Returned when no `vocoder` is provided
26912812 */
2692- constructor(config: any, session: any, decoder_merged_session: any, generation_config: new (kwargs?: import("./utils/generation.js").GenerationConfigType) => import("./utils/generation.js").GenerationConfigType);
2693- decoder_merged_session: any;
2694- generation_config: new (kwargs?: import("./utils/generation.js").GenerationConfigType) => import("./utils/generation.js").GenerationConfigType;
2695- num_decoder_layers: any;
2696- num_decoder_heads: any;
2697- decoder_dim_kv: number;
2698- num_encoder_layers: any;
2699- num_encoder_heads: any;
2700- encoder_dim_kv: number;
2813+ spectrogram?: Tensor;
27012814 /**
2702- * @typedef {Object} SpeechOutput
2703- * @property {Tensor} [spectrogram] The predicted log-mel spectrogram of shape
2704- * `(output_sequence_length, config.num_mel_bins)`. Returned when no `vocoder` is provided
2705- * @property {Tensor} [waveform] The predicted waveform of shape `(num_frames,)`. Returned when a `vocoder` is provided.
2706- * @property {Tensor} [cross_attentions] The outputs of the decoder's cross-attention layers of shape
2707- * `(config.decoder_layers, config.decoder_attention_heads, output_sequence_length, input_sequence_length)`. returned when `output_cross_attentions` is `true`.
2815+ * The predicted waveform of shape `(num_frames,)`. Returned when a `vocoder` is provided.
27082816 */
2817+ waveform?: Tensor;
27092818 /**
2710- * Converts a sequence of input tokens into a sequence of mel spectrograms, which are subsequently turned into a speech waveform using a vocoder.
2711- * @param {Tensor} input_values Indices of input sequence tokens in the vocabulary.
2712- * @param {Tensor} speaker_embeddings Tensor containing the speaker embeddings.
2713- * @param {Object} options Optional parameters for generating speech.
2714- * @param {number} [options.threshold=0.5] The generated sequence ends when the predicted stop token probability exceeds this value.
2715- * @param {number} [options.minlenratio=0.0] Used to calculate the minimum required length for the output sequence.
2716- * @param {number} [options.maxlenratio=20.0] Used to calculate the maximum allowed length for the output sequence.
2717- * @param {Object} [options.vocoder=null] The vocoder that converts the mel spectrogram into a speech waveform. If `null`, the output is the mel spectrogram.
2718- * @param {boolean} [options.output_cross_attentions=false] Whether or not to return the attentions tensors of the decoder's cross-attention layers.
2719- * @returns {Promise<SpeechOutput>} A promise which resolves to an object containing the spectrogram, waveform, and cross-attention tensors.
2819+ * The outputs of the decoder's cross-attention layers of shape
2820+ * `(config.decoder_layers, config.decoder_attention_heads, output_sequence_length, input_sequence_length)`. returned when `output_cross_attentions` is `true`.
27202821 */
2721- generate_speech(input_values: Tensor, speaker_embeddings: Tensor, { threshold, minlenratio, maxlenratio, vocoder, }?: {
2722- threshold?: number;
2723- minlenratio?: number;
2724- maxlenratio?: number;
2725- vocoder?: any;
2726- output_cross_attentions?: boolean;
2727- }): Promise<{
2728- /**
2729- * The predicted log-mel spectrogram of shape
2730- * `(output_sequence_length, config.num_mel_bins)`. Returned when no `vocoder` is provided
2731- */
2732- spectrogram?: Tensor;
2733- /**
2734- * The predicted waveform of shape `(num_frames,)`. Returned when a `vocoder` is provided.
2735- */
2736- waveform?: Tensor;
2737- /**
2738- * The outputs of the decoder's cross-attention layers of shape
2739- * `(config.decoder_layers, config.decoder_attention_heads, output_sequence_length, input_sequence_length)`. returned when `output_cross_attentions` is `true`.
2740- */
2741- cross_attentions?: Tensor;
2742- }>;
2822+ cross_attentions?: Tensor;
2823+ }>;
27432824 }
27442825 /**
27452826 * HiFi-GAN vocoder.
27462827 *
27472828 * See [SpeechT5ForSpeechToText](./models#module_models.SpeechT5ForSpeechToText) for example usage.
27482829 */
2749-export class SpeechT5HifiGan extends PreTrainedModel {
2750-}
2830+export class SpeechT5HifiGan extends PreTrainedModel {}
27512831 export class TrOCRPreTrainedModel extends PreTrainedModel {
2752- /**
2753- * Creates a new instance of the `TrOCRPreTrainedModel` class.
2754- * @param {Object} config The configuration of the model.
2755- * @param {any} session The ONNX session containing the model weights.
2756- * @param {GenerationConfig} generation_config The generation configuration.
2757- */
2758- constructor(config: any, session: any, generation_config: new (kwargs?: import("./utils/generation.js").GenerationConfigType) => import("./utils/generation.js").GenerationConfigType);
2759- generation_config: new (kwargs?: import("./utils/generation.js").GenerationConfigType) => import("./utils/generation.js").GenerationConfigType;
2760- num_encoder_layers: any;
2761- num_decoder_layers: any;
2762- num_encoder_heads: any;
2763- num_decoder_heads: any;
2764- encoder_dim_kv: number;
2765- decoder_dim_kv: number;
2832+ /**
2833+ * Creates a new instance of the `TrOCRPreTrainedModel` class.
2834+ * @param {Object} config The configuration of the model.
2835+ * @param {any} session The ONNX session containing the model weights.
2836+ * @param {GenerationConfig} generation_config The generation configuration.
2837+ */
2838+ constructor(
2839+ config: any,
2840+ session: any,
2841+ generation_config: new (
2842+ kwargs?: import("./utils/generation.js").GenerationConfigType,
2843+ ) => import("./utils/generation.js").GenerationConfigType,
2844+ );
2845+ generation_config: new (
2846+ kwargs?: import("./utils/generation.js").GenerationConfigType,
2847+ ) => import("./utils/generation.js").GenerationConfigType;
2848+ num_encoder_layers: any;
2849+ num_decoder_layers: any;
2850+ num_encoder_heads: any;
2851+ num_decoder_heads: any;
2852+ encoder_dim_kv: number;
2853+ decoder_dim_kv: number;
27662854 }
27672855 /**
27682856 * The TrOCR Decoder with a language modeling head.
27692857 */
2770-export class TrOCRForCausalLM extends TrOCRPreTrainedModel {
2771-}
2858+export class TrOCRForCausalLM extends TrOCRPreTrainedModel {}
27722859 /**
27732860 * The bare Mistral Model outputting raw hidden-states without any specific head on top.
27742861 */
27752862 export class MistralPreTrainedModel extends PreTrainedModel {
2776- /**
2777- * Creates a new instance of the `MistralPreTrainedModel` class.
2778- * @param {Object} config The configuration of the model.
2779- * @param {any} session The ONNX session containing the model weights.
2780- * @param {GenerationConfig} generation_config The generation configuration.
2781- */
2782- constructor(config: any, session: any, generation_config: new (kwargs?: import("./utils/generation.js").GenerationConfigType) => import("./utils/generation.js").GenerationConfigType);
2783- generation_config: new (kwargs?: import("./utils/generation.js").GenerationConfigType) => import("./utils/generation.js").GenerationConfigType;
2784- num_heads: any;
2785- num_layers: any;
2786- dim_kv: number;
2787-}
2788-export class MistralModel extends MistralPreTrainedModel {
2789-}
2790-export class MistralForCausalLM extends MistralPreTrainedModel {
2791-}
2863+ /**
2864+ * Creates a new instance of the `MistralPreTrainedModel` class.
2865+ * @param {Object} config The configuration of the model.
2866+ * @param {any} session The ONNX session containing the model weights.
2867+ * @param {GenerationConfig} generation_config The generation configuration.
2868+ */
2869+ constructor(
2870+ config: any,
2871+ session: any,
2872+ generation_config: new (
2873+ kwargs?: import("./utils/generation.js").GenerationConfigType,
2874+ ) => import("./utils/generation.js").GenerationConfigType,
2875+ );
2876+ generation_config: new (
2877+ kwargs?: import("./utils/generation.js").GenerationConfigType,
2878+ ) => import("./utils/generation.js").GenerationConfigType;
2879+ num_heads: any;
2880+ num_layers: any;
2881+ dim_kv: number;
2882+}
2883+export class MistralModel extends MistralPreTrainedModel {}
2884+export class MistralForCausalLM extends MistralPreTrainedModel {}
27922885 /**
27932886 * The bare Falcon Model outputting raw hidden-states without any specific head on top.
27942887 */
27952888 export class FalconPreTrainedModel extends PreTrainedModel {
2796- /**
2797- * Creates a new instance of the `FalconPreTrainedModel` class.
2798- * @param {Object} config The configuration of the model.
2799- * @param {any} session The ONNX session containing the model weights.
2800- * @param {GenerationConfig} generation_config The generation configuration.
2801- */
2802- constructor(config: any, session: any, generation_config: new (kwargs?: import("./utils/generation.js").GenerationConfigType) => import("./utils/generation.js").GenerationConfigType);
2803- generation_config: new (kwargs?: import("./utils/generation.js").GenerationConfigType) => import("./utils/generation.js").GenerationConfigType;
2804- num_heads: any;
2805- num_layers: any;
2806- dim_kv: number;
2807-}
2808-export class FalconModel extends FalconPreTrainedModel {
2809-}
2810-export class FalconForCausalLM extends FalconPreTrainedModel {
2811-}
2812-export class ClapPreTrainedModel extends PreTrainedModel {
2813-}
2814-export class ClapModel extends ClapPreTrainedModel {
2815-}
2889+ /**
2890+ * Creates a new instance of the `FalconPreTrainedModel` class.
2891+ * @param {Object} config The configuration of the model.
2892+ * @param {any} session The ONNX session containing the model weights.
2893+ * @param {GenerationConfig} generation_config The generation configuration.
2894+ */
2895+ constructor(
2896+ config: any,
2897+ session: any,
2898+ generation_config: new (
2899+ kwargs?: import("./utils/generation.js").GenerationConfigType,
2900+ ) => import("./utils/generation.js").GenerationConfigType,
2901+ );
2902+ generation_config: new (
2903+ kwargs?: import("./utils/generation.js").GenerationConfigType,
2904+ ) => import("./utils/generation.js").GenerationConfigType;
2905+ num_heads: any;
2906+ num_layers: any;
2907+ dim_kv: number;
2908+}
2909+export class FalconModel extends FalconPreTrainedModel {}
2910+export class FalconForCausalLM extends FalconPreTrainedModel {}
2911+export class ClapPreTrainedModel extends PreTrainedModel {}
2912+export class ClapModel extends ClapPreTrainedModel {}
28162913 /**
28172914 * CLAP Text Model with a projection layer on top (a linear layer on top of the pooled output).
28182915 *
@@ -2839,8 +2936,7 @@
28392936 * // }
28402937 * ```
28412938 */
2842-export class ClapTextModelWithProjection extends ClapPreTrainedModel {
2843-}
2939+export class ClapTextModelWithProjection extends ClapPreTrainedModel {}
28442940 /**
28452941 * CLAP Audio Model with a projection layer on top (a linear layer on top of the pooled output).
28462942 *
@@ -2867,10 +2963,8 @@
28672963 * // }
28682964 * ```
28692965 */
2870-export class ClapAudioModelWithProjection extends ClapPreTrainedModel {
2871-}
2872-export class VitsPreTrainedModel extends PreTrainedModel {
2873-}
2966+export class ClapAudioModelWithProjection extends ClapPreTrainedModel {}
2967+export class VitsPreTrainedModel extends PreTrainedModel {}
28742968 /**
28752969 * The complete VITS model, for text-to-speech synthesis.
28762970 *
@@ -2896,61 +2990,68 @@
28962990 * ```
28972991 */
28982992 export class VitsModel extends VitsPreTrainedModel {
2899- /**
2900- * Calls the model on new inputs.
2901- * @param {Object} model_inputs The inputs to the model.
2902- * @returns {Promise<VitsModelOutput>} The outputs for the VITS model.
2903- */
2904- _call(model_inputs: any): Promise<VitsModelOutput>;
2905-}
2906-export class SegformerPreTrainedModel extends PreTrainedModel {
2907-}
2993+ /**
2994+ * Calls the model on new inputs.
2995+ * @param {Object} model_inputs The inputs to the model.
2996+ * @returns {Promise<VitsModelOutput>} The outputs for the VITS model.
2997+ */
2998+ _call(model_inputs: any): Promise<VitsModelOutput>;
2999+}
3000+export class SegformerPreTrainedModel extends PreTrainedModel {}
29083001 /**
29093002 * The bare SegFormer encoder (Mix-Transformer) outputting raw hidden-states without any specific head on top.
29103003 */
2911-export class SegformerModel extends SegformerPreTrainedModel {
2912-}
3004+export class SegformerModel extends SegformerPreTrainedModel {}
29133005 /**
29143006 * SegFormer Model transformer with an image classification head on top (a linear layer on top of the final hidden states) e.g. for ImageNet.
29153007 */
2916-export class SegformerForImageClassification extends SegformerPreTrainedModel {
2917-}
3008+export class SegformerForImageClassification extends SegformerPreTrainedModel {}
29183009 /**
29193010 * SegFormer Model transformer with an all-MLP decode head on top e.g. for ADE20k, CityScapes.
29203011 */
2921-export class SegformerForSemanticSegmentation extends SegformerPreTrainedModel {
2922-}
3012+export class SegformerForSemanticSegmentation extends SegformerPreTrainedModel {}
29233013 /**
29243014 * Base class of all AutoModels. Contains the `from_pretrained` function
29253015 * which is used to instantiate pretrained models.
29263016 */
29273017 export class PretrainedMixin {
2928- /**
2929- * Mapping from model type to model class.
2930- * @type {Map<string, Object>[]}
2931- */
2932- static MODEL_CLASS_MAPPINGS: Map<string, any>[];
2933- /**
2934- * Whether to attempt to instantiate the base class (`PretrainedModel`) if
2935- * the model type is not found in the mapping.
2936- */
2937- static BASE_IF_FAIL: boolean;
2938- /**
2939- * Instantiate one of the model classes of the library from a pretrained model.
2940- *
2941- * The model class to instantiate is selected based on the `model_type` property of the config object
2942- * (either passed as an argument or loaded from `pretrained_model_name_or_path` if possible)
2943- *
2944- * @param {string} pretrained_model_name_or_path The name or path of the pretrained model. Can be either:
2945- * - A string, the *model id* of a pretrained model hosted inside a model repo on huggingface.co.
2946- * Valid model ids can be located at the root-level, like `bert-base-uncased`, or namespaced under a
2947- * user or organization name, like `dbmdz/bert-base-german-cased`.
2948- * - A path to a *directory* containing model weights, e.g., `./my_model_directory/`.
2949- * @param {import('./utils/hub.js').PretrainedOptions} options Additional options for loading the model.
2950- *
2951- * @returns {Promise<PreTrainedModel>} A new instance of the `PreTrainedModel` class.
2952- */
2953- static from_pretrained(pretrained_model_name_or_path: string, { quantized, progress_callback, config, cache_dir, local_files_only, revision, model_file_name, }?: import("./utils/hub.js").PretrainedOptions): Promise<PreTrainedModel>;
3018+ /**
3019+ * Mapping from model type to model class.
3020+ * @type {Map<string, Object>[]}
3021+ */
3022+ static MODEL_CLASS_MAPPINGS: Map<string, any>[];
3023+ /**
3024+ * Whether to attempt to instantiate the base class (`PretrainedModel`) if
3025+ * the model type is not found in the mapping.
3026+ */
3027+ static BASE_IF_FAIL: boolean;
3028+ /**
3029+ * Instantiate one of the model classes of the library from a pretrained model.
3030+ *
3031+ * The model class to instantiate is selected based on the `model_type` property of the config object
3032+ * (either passed as an argument or loaded from `pretrained_model_name_or_path` if possible)
3033+ *
3034+ * @param {string} pretrained_model_name_or_path The name or path of the pretrained model. Can be either:
3035+ * - A string, the *model id* of a pretrained model hosted inside a model repo on huggingface.co.
3036+ * Valid model ids can be located at the root-level, like `bert-base-uncased`, or namespaced under a
3037+ * user or organization name, like `dbmdz/bert-base-german-cased`.
3038+ * - A path to a *directory* containing model weights, e.g., `./my_model_directory/`.
3039+ * @param {import('./utils/hub.js').PretrainedOptions} options Additional options for loading the model.
3040+ *
3041+ * @returns {Promise<PreTrainedModel>} A new instance of the `PreTrainedModel` class.
3042+ */
3043+ static from_pretrained(
3044+ pretrained_model_name_or_path: string,
3045+ {
3046+ quantized,
3047+ progress_callback,
3048+ config,
3049+ cache_dir,
3050+ local_files_only,
3051+ revision,
3052+ model_file_name,
3053+ }?: import("./utils/hub.js").PretrainedOptions,
3054+ ): Promise<PreTrainedModel>;
29543055 }
29553056 /**
29563057 * Helper class which is used to instantiate pretrained models with the `from_pretrained` function.
@@ -2959,8 +3060,7 @@
29593060 * @example
29603061 * let model = await AutoModel.from_pretrained('bert-base-uncased');
29613062 */
2962-export class AutoModel extends PretrainedMixin {
2963-}
3063+export class AutoModel extends PretrainedMixin {}
29643064 /**
29653065 * Helper class which is used to instantiate pretrained sequence classification models with the `from_pretrained` function.
29663066 * The chosen model class is determined by the type specified in the model config.
@@ -2969,7 +3069,10 @@
29693069 * let model = await AutoModelForSequenceClassification.from_pretrained('distilbert-base-uncased-finetuned-sst-2-english');
29703070 */
29713071 export class AutoModelForSequenceClassification extends PretrainedMixin {
2972- static MODEL_CLASS_MAPPINGS: Map<string, (string | typeof BertForSequenceClassification)[]>[];
3072+ static MODEL_CLASS_MAPPINGS: Map<
3073+ string,
3074+ (string | typeof BertForSequenceClassification)[]
3075+ >[];
29733076 }
29743077 /**
29753078 * Helper class which is used to instantiate pretrained token classification models with the `from_pretrained` function.
@@ -2979,7 +3082,10 @@
29793082 * let model = await AutoModelForTokenClassification.from_pretrained('Davlan/distilbert-base-multilingual-cased-ner-hrl');
29803083 */
29813084 export class AutoModelForTokenClassification extends PretrainedMixin {
2982- static MODEL_CLASS_MAPPINGS: Map<string, (string | typeof BertForTokenClassification)[]>[];
3085+ static MODEL_CLASS_MAPPINGS: Map<
3086+ string,
3087+ (string | typeof BertForTokenClassification)[]
3088+ >[];
29833089 }
29843090 /**
29853091 * Helper class which is used to instantiate pretrained sequence-to-sequence models with the `from_pretrained` function.
@@ -2989,7 +3095,11 @@
29893095 * let model = await AutoModelForSeq2SeqLM.from_pretrained('t5-small');
29903096 */
29913097 export class AutoModelForSeq2SeqLM extends PretrainedMixin {
2992- static MODEL_CLASS_MAPPINGS: Map<string, (string | typeof T5ForConditionalGeneration)[] | (string | typeof BartForConditionalGeneration)[]>[];
3098+ static MODEL_CLASS_MAPPINGS: Map<
3099+ string,
3100+ | (string | typeof T5ForConditionalGeneration)[]
3101+ | (string | typeof BartForConditionalGeneration)[]
3102+ >[];
29933103 }
29943104 /**
29953105 * Helper class which is used to instantiate pretrained sequence-to-sequence speech-to-text models with the `from_pretrained` function.
@@ -2999,7 +3109,11 @@
29993109 * let model = await AutoModelForSpeechSeq2Seq.from_pretrained('openai/whisper-tiny.en');
30003110 */
30013111 export class AutoModelForSpeechSeq2Seq extends PretrainedMixin {
3002- static MODEL_CLASS_MAPPINGS: Map<string, (string | typeof SpeechT5ForSpeechToText)[] | (string | typeof WhisperForConditionalGeneration)[]>[];
3112+ static MODEL_CLASS_MAPPINGS: Map<
3113+ string,
3114+ | (string | typeof SpeechT5ForSpeechToText)[]
3115+ | (string | typeof WhisperForConditionalGeneration)[]
3116+ >[];
30033117 }
30043118 /**
30053119 * Helper class which is used to instantiate pretrained sequence-to-sequence text-to-spectrogram models with the `from_pretrained` function.
@@ -3009,7 +3123,10 @@
30093123 * let model = await AutoModelForTextToSpectrogram.from_pretrained('microsoft/speecht5_tts');
30103124 */
30113125 export class AutoModelForTextToSpectrogram extends PretrainedMixin {
3012- static MODEL_CLASS_MAPPINGS: Map<string, (string | typeof SpeechT5ForTextToSpeech)[]>[];
3126+ static MODEL_CLASS_MAPPINGS: Map<
3127+ string,
3128+ (string | typeof SpeechT5ForTextToSpeech)[]
3129+ >[];
30133130 }
30143131 /**
30153132 * Helper class which is used to instantiate pretrained text-to-waveform models with the `from_pretrained` function.
@@ -3019,7 +3136,7 @@
30193136 * let model = await AutoModelForTextToSpectrogram.from_pretrained('facebook/mms-tts-eng');
30203137 */
30213138 export class AutoModelForTextToWaveform extends PretrainedMixin {
3022- static MODEL_CLASS_MAPPINGS: Map<string, (string | typeof VitsModel)[]>[];
3139+ static MODEL_CLASS_MAPPINGS: Map<string, (string | typeof VitsModel)[]>[];
30233140 }
30243141 /**
30253142 * Helper class which is used to instantiate pretrained causal language models with the `from_pretrained` function.
@@ -3029,7 +3146,10 @@
30293146 * let model = await AutoModelForCausalLM.from_pretrained('gpt2');
30303147 */
30313148 export class AutoModelForCausalLM extends PretrainedMixin {
3032- static MODEL_CLASS_MAPPINGS: Map<string, (string | typeof BloomForCausalLM)[] | (string | typeof MBartForCausalLM)[]>[];
3149+ static MODEL_CLASS_MAPPINGS: Map<
3150+ string,
3151+ (string | typeof BloomForCausalLM)[] | (string | typeof MBartForCausalLM)[]
3152+ >[];
30333153 }
30343154 /**
30353155 * Helper class which is used to instantiate pretrained masked language models with the `from_pretrained` function.
@@ -3039,7 +3159,10 @@
30393159 * let model = await AutoModelForMaskedLM.from_pretrained('bert-base-uncased');
30403160 */
30413161 export class AutoModelForMaskedLM extends PretrainedMixin {
3042- static MODEL_CLASS_MAPPINGS: Map<string, (string | typeof BertForMaskedLM)[]>[];
3162+ static MODEL_CLASS_MAPPINGS: Map<
3163+ string,
3164+ (string | typeof BertForMaskedLM)[]
3165+ >[];
30433166 }
30443167 /**
30453168 * Helper class which is used to instantiate pretrained question answering models with the `from_pretrained` function.
@@ -3049,7 +3172,10 @@
30493172 * let model = await AutoModelForQuestionAnswering.from_pretrained('distilbert-base-cased-distilled-squad');
30503173 */
30513174 export class AutoModelForQuestionAnswering extends PretrainedMixin {
3052- static MODEL_CLASS_MAPPINGS: Map<string, (string | typeof BertForQuestionAnswering)[]>[];
3175+ static MODEL_CLASS_MAPPINGS: Map<
3176+ string,
3177+ (string | typeof BertForQuestionAnswering)[]
3178+ >[];
30533179 }
30543180 /**
30553181 * Helper class which is used to instantiate pretrained vision-to-sequence models with the `from_pretrained` function.
@@ -3059,7 +3185,10 @@
30593185 * let model = await AutoModelForVision2Seq.from_pretrained('nlpconnect/vit-gpt2-image-captioning');
30603186 */
30613187 export class AutoModelForVision2Seq extends PretrainedMixin {
3062- static MODEL_CLASS_MAPPINGS: Map<string, (string | typeof VisionEncoderDecoderModel)[]>[];
3188+ static MODEL_CLASS_MAPPINGS: Map<
3189+ string,
3190+ (string | typeof VisionEncoderDecoderModel)[]
3191+ >[];
30633192 }
30643193 /**
30653194 * Helper class which is used to instantiate pretrained image classification models with the `from_pretrained` function.
@@ -3069,7 +3198,10 @@
30693198 * let model = await AutoModelForImageClassification.from_pretrained('google/vit-base-patch16-224');
30703199 */
30713200 export class AutoModelForImageClassification extends PretrainedMixin {
3072- static MODEL_CLASS_MAPPINGS: Map<string, (string | typeof SegformerForImageClassification)[]>[];
3201+ static MODEL_CLASS_MAPPINGS: Map<
3202+ string,
3203+ (string | typeof SegformerForImageClassification)[]
3204+ >[];
30733205 }
30743206 /**
30753207 * Helper class which is used to instantiate pretrained image segmentation models with the `from_pretrained` function.
@@ -3079,7 +3211,10 @@
30793211 * let model = await AutoModelForImageSegmentation.from_pretrained('facebook/detr-resnet-50-panoptic');
30803212 */
30813213 export class AutoModelForImageSegmentation extends PretrainedMixin {
3082- static MODEL_CLASS_MAPPINGS: Map<string, (string | typeof CLIPSegForImageSegmentation)[]>[];
3214+ static MODEL_CLASS_MAPPINGS: Map<
3215+ string,
3216+ (string | typeof CLIPSegForImageSegmentation)[]
3217+ >[];
30833218 }
30843219 /**
30853220 * Helper class which is used to instantiate pretrained image segmentation models with the `from_pretrained` function.
@@ -3089,7 +3224,10 @@
30893224 * let model = await AutoModelForSemanticSegmentation.from_pretrained('nvidia/segformer-b3-finetuned-cityscapes-1024-1024');
30903225 */
30913226 export class AutoModelForSemanticSegmentation extends PretrainedMixin {
3092- static MODEL_CLASS_MAPPINGS: Map<string, (string | typeof SegformerForSemanticSegmentation)[]>[];
3227+ static MODEL_CLASS_MAPPINGS: Map<
3228+ string,
3229+ (string | typeof SegformerForSemanticSegmentation)[]
3230+ >[];
30933231 }
30943232 /**
30953233 * Helper class which is used to instantiate pretrained object detection models with the `from_pretrained` function.
@@ -3099,10 +3237,16 @@
30993237 * let model = await AutoModelForObjectDetection.from_pretrained('facebook/detr-resnet-50');
31003238 */
31013239 export class AutoModelForObjectDetection extends PretrainedMixin {
3102- static MODEL_CLASS_MAPPINGS: Map<string, (string | typeof DetrForObjectDetection)[]>[];
3240+ static MODEL_CLASS_MAPPINGS: Map<
3241+ string,
3242+ (string | typeof DetrForObjectDetection)[]
3243+ >[];
31033244 }
31043245 export class AutoModelForZeroShotObjectDetection extends PretrainedMixin {
3105- static MODEL_CLASS_MAPPINGS: Map<string, (string | typeof OwlViTForObjectDetection)[]>[];
3246+ static MODEL_CLASS_MAPPINGS: Map<
3247+ string,
3248+ (string | typeof OwlViTForObjectDetection)[]
3249+ >[];
31063250 }
31073251 /**
31083252 * Helper class which is used to instantiate pretrained mask generation models with the `from_pretrained` function.
@@ -3112,161 +3256,184 @@
31123256 * let model = await AutoModelForMaskGeneration.from_pretrained('Xenova/sam-vit-base');
31133257 */
31143258 export class AutoModelForMaskGeneration extends PretrainedMixin {
3115- static MODEL_CLASS_MAPPINGS: Map<string, (string | typeof SamModel)[]>[];
3259+ static MODEL_CLASS_MAPPINGS: Map<string, (string | typeof SamModel)[]>[];
31163260 }
31173261 export class AutoModelForCTC extends PretrainedMixin {
3118- static MODEL_CLASS_MAPPINGS: Map<string, (string | typeof Wav2Vec2ForCTC)[]>[];
3262+ static MODEL_CLASS_MAPPINGS: Map<
3263+ string,
3264+ (string | typeof Wav2Vec2ForCTC)[]
3265+ >[];
31193266 }
31203267 export class AutoModelForAudioClassification extends PretrainedMixin {
3121- static MODEL_CLASS_MAPPINGS: Map<string, (string | typeof ASTForAudioClassification)[]>[];
3268+ static MODEL_CLASS_MAPPINGS: Map<
3269+ string,
3270+ (string | typeof ASTForAudioClassification)[]
3271+ >[];
31223272 }
31233273 export class AutoModelForDocumentQuestionAnswering extends PretrainedMixin {
3124- static MODEL_CLASS_MAPPINGS: Map<string, (string | typeof VisionEncoderDecoderModel)[]>[];
3274+ static MODEL_CLASS_MAPPINGS: Map<
3275+ string,
3276+ (string | typeof VisionEncoderDecoderModel)[]
3277+ >[];
31253278 }
31263279 export class AutoModelForImageMatting extends PretrainedMixin {
3127- static MODEL_CLASS_MAPPINGS: Map<string, (string | typeof VitMatteForImageMatting)[]>[];
3280+ static MODEL_CLASS_MAPPINGS: Map<
3281+ string,
3282+ (string | typeof VitMatteForImageMatting)[]
3283+ >[];
31283284 }
31293285 export class AutoModelForImageToImage extends PretrainedMixin {
3130- static MODEL_CLASS_MAPPINGS: Map<string, (string | typeof Swin2SRForImageSuperResolution)[]>[];
3286+ static MODEL_CLASS_MAPPINGS: Map<
3287+ string,
3288+ (string | typeof Swin2SRForImageSuperResolution)[]
3289+ >[];
31313290 }
31323291 export class AutoModelForDepthEstimation extends PretrainedMixin {
3133- static MODEL_CLASS_MAPPINGS: Map<string, (string | typeof DPTForDepthEstimation)[]>[];
3292+ static MODEL_CLASS_MAPPINGS: Map<
3293+ string,
3294+ (string | typeof DPTForDepthEstimation)[]
3295+ >[];
31343296 }
31353297 export class Seq2SeqLMOutput extends ModelOutput {
3136- /**
3137- * @param {Object} output The output of the model.
3138- * @param {Tensor} output.logits The output logits of the model.
3139- * @param {Tensor} output.past_key_values An tensor of key/value pairs that represent the previous state of the model.
3140- * @param {Tensor} output.encoder_outputs The output of the encoder in a sequence-to-sequence model.
3141- * @param {Tensor} [output.decoder_attentions] Attentions weights of the decoder, after the attention softmax, used to compute the weighted average in the self-attention heads.
3142- * @param {Tensor} [output.cross_attentions] Attentions weights of the decoder's cross-attention layer, after the attention softmax, used to compute the weighted average in the cross-attention heads.
3143- */
3144- constructor({ logits, past_key_values, encoder_outputs, decoder_attentions, cross_attentions }: {
3145- logits: Tensor;
3146- past_key_values: Tensor;
3147- encoder_outputs: Tensor;
3148- decoder_attentions?: Tensor;
3149- cross_attentions?: Tensor;
3150- });
3298+ /**
3299+ * @param {Object} output The output of the model.
3300+ * @param {Tensor} output.logits The output logits of the model.
3301+ * @param {Tensor} output.past_key_values An tensor of key/value pairs that represent the previous state of the model.
3302+ * @param {Tensor} output.encoder_outputs The output of the encoder in a sequence-to-sequence model.
3303+ * @param {Tensor} [output.decoder_attentions] Attentions weights of the decoder, after the attention softmax, used to compute the weighted average in the self-attention heads.
3304+ * @param {Tensor} [output.cross_attentions] Attentions weights of the decoder's cross-attention layer, after the attention softmax, used to compute the weighted average in the cross-attention heads.
3305+ */
3306+ constructor({
3307+ logits,
3308+ past_key_values,
3309+ encoder_outputs,
3310+ decoder_attentions,
3311+ cross_attentions,
3312+ }: {
31513313 logits: Tensor;
31523314 past_key_values: Tensor;
31533315 encoder_outputs: Tensor;
3154- decoder_attentions: Tensor;
3155- cross_attentions: Tensor;
3316+ decoder_attentions?: Tensor;
3317+ cross_attentions?: Tensor;
3318+ });
3319+ logits: Tensor;
3320+ past_key_values: Tensor;
3321+ encoder_outputs: Tensor;
3322+ decoder_attentions: Tensor;
3323+ cross_attentions: Tensor;
31563324 }
31573325 /**
31583326 * Base class for outputs of sentence classification models.
31593327 */
31603328 export class SequenceClassifierOutput extends ModelOutput {
3161- /**
3162- * @param {Object} output The output of the model.
3163- * @param {Tensor} output.logits classification (or regression if config.num_labels==1) scores (before SoftMax).
3164- */
3165- constructor({ logits }: {
3166- logits: Tensor;
3167- });
3168- logits: Tensor;
3329+ /**
3330+ * @param {Object} output The output of the model.
3331+ * @param {Tensor} output.logits classification (or regression if config.num_labels==1) scores (before SoftMax).
3332+ */
3333+ constructor({ logits }: { logits: Tensor });
3334+ logits: Tensor;
31693335 }
31703336 /**
31713337 * Base class for outputs of token classification models.
31723338 */
31733339 export class TokenClassifierOutput extends ModelOutput {
3174- /**
3175- * @param {Object} output The output of the model.
3176- * @param {Tensor} output.logits Classification scores (before SoftMax).
3177- */
3178- constructor({ logits }: {
3179- logits: Tensor;
3180- });
3181- logits: Tensor;
3340+ /**
3341+ * @param {Object} output The output of the model.
3342+ * @param {Tensor} output.logits Classification scores (before SoftMax).
3343+ */
3344+ constructor({ logits }: { logits: Tensor });
3345+ logits: Tensor;
31823346 }
31833347 /**
31843348 * Base class for masked language models outputs.
31853349 */
31863350 export class MaskedLMOutput extends ModelOutput {
3187- /**
3188- * @param {Object} output The output of the model.
3189- * @param {Tensor} output.logits Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
3190- */
3191- constructor({ logits }: {
3192- logits: Tensor;
3193- });
3194- logits: Tensor;
3351+ /**
3352+ * @param {Object} output The output of the model.
3353+ * @param {Tensor} output.logits Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
3354+ */
3355+ constructor({ logits }: { logits: Tensor });
3356+ logits: Tensor;
31953357 }
31963358 /**
31973359 * Base class for outputs of question answering models.
31983360 */
31993361 export class QuestionAnsweringModelOutput extends ModelOutput {
3200- /**
3201- * @param {Object} output The output of the model.
3202- * @param {Tensor} output.start_logits Span-start scores (before SoftMax).
3203- * @param {Tensor} output.end_logits Span-end scores (before SoftMax).
3204- */
3205- constructor({ start_logits, end_logits }: {
3206- start_logits: Tensor;
3207- end_logits: Tensor;
3208- });
3362+ /**
3363+ * @param {Object} output The output of the model.
3364+ * @param {Tensor} output.start_logits Span-start scores (before SoftMax).
3365+ * @param {Tensor} output.end_logits Span-end scores (before SoftMax).
3366+ */
3367+ constructor({
3368+ start_logits,
3369+ end_logits,
3370+ }: {
32093371 start_logits: Tensor;
32103372 end_logits: Tensor;
3373+ });
3374+ start_logits: Tensor;
3375+ end_logits: Tensor;
32113376 }
32123377 /**
32133378 * Base class for causal language model (or autoregressive) outputs.
32143379 */
32153380 export class CausalLMOutput extends ModelOutput {
3216- /**
3217- * @param {Object} output The output of the model.
3218- * @param {Tensor} output.logits Prediction scores of the language modeling head (scores for each vocabulary token before softmax).
3219- */
3220- constructor({ logits }: {
3221- logits: Tensor;
3222- });
3223- logits: Tensor;
3381+ /**
3382+ * @param {Object} output The output of the model.
3383+ * @param {Tensor} output.logits Prediction scores of the language modeling head (scores for each vocabulary token before softmax).
3384+ */
3385+ constructor({ logits }: { logits: Tensor });
3386+ logits: Tensor;
32243387 }
32253388 /**
32263389 * Base class for causal language model (or autoregressive) outputs.
32273390 */
32283391 export class CausalLMOutputWithPast extends ModelOutput {
3229- /**
3230- * @param {Object} output The output of the model.
3231- * @param {Tensor} output.logits Prediction scores of the language modeling head (scores for each vocabulary token before softmax).
3232- * @param {Tensor} output.past_key_values Contains pre-computed hidden-states (key and values in the self-attention blocks)
3233- * that can be used (see `past_key_values` input) to speed up sequential decoding.
3234- */
3235- constructor({ logits, past_key_values }: {
3236- logits: Tensor;
3237- past_key_values: Tensor;
3238- });
3392+ /**
3393+ * @param {Object} output The output of the model.
3394+ * @param {Tensor} output.logits Prediction scores of the language modeling head (scores for each vocabulary token before softmax).
3395+ * @param {Tensor} output.past_key_values Contains pre-computed hidden-states (key and values in the self-attention blocks)
3396+ * that can be used (see `past_key_values` input) to speed up sequential decoding.
3397+ */
3398+ constructor({
3399+ logits,
3400+ past_key_values,
3401+ }: {
32393402 logits: Tensor;
32403403 past_key_values: Tensor;
3404+ });
3405+ logits: Tensor;
3406+ past_key_values: Tensor;
32413407 }
32423408 export class ImageMattingOutput extends ModelOutput {
3243- /**
3244- * @param {Object} output The output of the model.
3245- * @param {Tensor} output.alphas Estimated alpha values, of shape `(batch_size, num_channels, height, width)`.
3246- */
3247- constructor({ alphas }: {
3248- alphas: Tensor;
3249- });
3250- alphas: Tensor;
3409+ /**
3410+ * @param {Object} output The output of the model.
3411+ * @param {Tensor} output.alphas Estimated alpha values, of shape `(batch_size, num_channels, height, width)`.
3412+ */
3413+ constructor({ alphas }: { alphas: Tensor });
3414+ alphas: Tensor;
32513415 }
32523416 /**
32533417 * Describes the outputs for the VITS model.
32543418 */
32553419 export class VitsModelOutput extends ModelOutput {
3256- /**
3257- * @param {Object} output The output of the model.
3258- * @param {Tensor} output.waveform The final audio waveform predicted by the model, of shape `(batch_size, sequence_length)`.
3259- * @param {Tensor} output.spectrogram The log-mel spectrogram predicted at the output of the flow model.
3260- * This spectrogram is passed to the Hi-Fi GAN decoder model to obtain the final audio waveform.
3261- */
3262- constructor({ waveform, spectrogram }: {
3263- waveform: Tensor;
3264- spectrogram: Tensor;
3265- });
3420+ /**
3421+ * @param {Object} output The output of the model.
3422+ * @param {Tensor} output.waveform The final audio waveform predicted by the model, of shape `(batch_size, sequence_length)`.
3423+ * @param {Tensor} output.spectrogram The log-mel spectrogram predicted at the output of the flow model.
3424+ * This spectrogram is passed to the Hi-Fi GAN decoder model to obtain the final audio waveform.
3425+ */
3426+ constructor({
3427+ waveform,
3428+ spectrogram,
3429+ }: {
32663430 waveform: Tensor;
32673431 spectrogram: Tensor;
3432+ });
3433+ waveform: Tensor;
3434+ spectrogram: Tensor;
32683435 }
3269-export type InferenceSession = import('onnxruntime-web').InferenceSession;
3436+export type InferenceSession = import("onnxruntime-web").InferenceSession;
32703437 /**
32713438 * Runs a single step of the text generation process for a given beam.
32723439 *
@@ -3280,13 +3447,16 @@
32803447 * @returns {Promise<Object>} The output of the generation step.
32813448 * @private
32823449 */
3283-declare function decoderRunBeam(self: any, beam: {
3450+declare function decoderRunBeam(
3451+ self: any,
3452+ beam: {
32843453 input: Tensor;
32853454 model_input_ids: Tensor;
32863455 attention_mask: Tensor;
32873456 prev_model_outputs: any;
32883457 output_token_ids: number[];
3289-}): Promise<any>;
3458+ },
3459+): Promise<any>;
32903460 /**
32913461 * Starts the generation of text by initializing the beams for the given input token IDs.
32923462 * @param {Object} self The text generation model object.
@@ -3297,7 +3467,13 @@
32973467 * @returns {Object[]} An array of beams initialized with the given inputs and parameters.
32983468 * @private
32993469 */
3300-declare function decoderStartBeams(self: any, inputTokenIds: Tensor, generation_config: any, numOutputTokens: number, inputs_attention_mask?: Tensor): any[];
3470+declare function decoderStartBeams(
3471+ self: any,
3472+ inputTokenIds: Tensor,
3473+ generation_config: any,
3474+ numOutputTokens: number,
3475+ inputs_attention_mask?: Tensor,
3476+): any[];
33013477 /**
33023478 * Update a beam with a new token ID.
33033479 * @param {Object} beam The beam to update.
@@ -3313,6 +3489,6 @@
33133489 * @private
33143490 */
33153491 declare function encoderForward(self: any, model_inputs: any): Promise<any>;
3316-import { Tensor } from './utils/tensor.js';
3492+import { Tensor } from "./utils/tensor.js";
33173493 export {};
3318-//# sourceMappingURL=models.d.ts.map
No newline at the end of the file
3494+//# sourceMappingURL=models.d.ts.map
modified core/vendor/modules/@xenova/transformers/types/pipelines.d.ts +1112 −826
@@ -38,10 +38,21 @@
3838 * @returns {Promise<AllTasks[T]>} A Pipeline object for the specified task.
3939 * @throws {Error} If an unsupported pipeline is requested.
4040 */
41-export function pipeline<T extends PipelineType>(task: T, model?: string, { quantized, progress_callback, config, cache_dir, local_files_only, revision, }?: import('./utils/hub.js').PretrainedOptions): Promise<AllTasks[T]>;
41+export function pipeline<T extends PipelineType>(
42+ task: T,
43+ model?: string,
44+ {
45+ quantized,
46+ progress_callback,
47+ config,
48+ cache_dir,
49+ local_files_only,
50+ revision,
51+ }?: import("./utils/hub.js").PretrainedOptions,
52+): Promise<AllTasks[T]>;
4253 declare const Pipeline_base: new () => {
43- (...args: any[]): any;
44- _call(...args: any[]): any;
54+ (...args: any[]): any;
55+ _call(...args: any[]): any;
4556 };
4657 /**
4758 * @callback DisposeType Disposes the item.
@@ -56,27 +67,34 @@
5667 * @extends Callable
5768 */
5869 export class Pipeline extends Pipeline_base {
59- /**
60- * Create a new Pipeline.
61- * @param {Object} options An object containing the following properties:
62- * @param {string} [options.task] The task of the pipeline. Useful for specifying subtasks.
63- * @param {PreTrainedModel} [options.model] The model used by the pipeline.
64- * @param {PreTrainedTokenizer} [options.tokenizer=null] The tokenizer used by the pipeline (if any).
65- * @param {Processor} [options.processor=null] The processor used by the pipeline (if any).
66- */
67- constructor({ task, model, tokenizer, processor }: {
68- task?: string;
69- model?: PreTrainedModel;
70- tokenizer?: PreTrainedTokenizer;
71- processor?: Processor;
72- });
73- task: string;
74- model: PreTrainedModel;
75- tokenizer: PreTrainedTokenizer;
76- processor: Processor;
77- dispose(): Promise<void>;
70+ /**
71+ * Create a new Pipeline.
72+ * @param {Object} options An object containing the following properties:
73+ * @param {string} [options.task] The task of the pipeline. Useful for specifying subtasks.
74+ * @param {PreTrainedModel} [options.model] The model used by the pipeline.
75+ * @param {PreTrainedTokenizer} [options.tokenizer=null] The tokenizer used by the pipeline (if any).
76+ * @param {Processor} [options.processor=null] The processor used by the pipeline (if any).
77+ */
78+ constructor({
79+ task,
80+ model,
81+ tokenizer,
82+ processor,
83+ }: {
84+ task?: string;
85+ model?: PreTrainedModel;
86+ tokenizer?: PreTrainedTokenizer;
87+ processor?: Processor;
88+ });
89+ task: string;
90+ model: PreTrainedModel;
91+ tokenizer: PreTrainedTokenizer;
92+ processor: Processor;
93+ dispose(): Promise<void>;
7894 }
79-declare const TextClassificationPipeline_base: new (options: TextPipelineConstructorArgs) => TextClassificationPipelineType;
95+declare const TextClassificationPipeline_base: new (
96+ options: TextPipelineConstructorArgs,
97+) => TextClassificationPipelineType;
8098 /**
8199 * @typedef {Object} ModelTokenizerConstructorArgs
82100 * @property {string} task The task of the pipeline. Useful for specifying subtasks.
@@ -158,9 +176,14 @@
158176 * ```
159177 */
160178 export class TextClassificationPipeline extends TextClassificationPipeline_base {
161- _call(texts: string | string[], options?: TextClassificationPipelineOptions): Promise<TextClassificationOutput | TextClassificationOutput[]>;
179+ _call(
180+ texts: string | string[],
181+ options?: TextClassificationPipelineOptions,
182+ ): Promise<TextClassificationOutput | TextClassificationOutput[]>;
162183 }
163-declare const TokenClassificationPipeline_base: new (options: TextPipelineConstructorArgs) => TokenClassificationPipelineType;
184+declare const TokenClassificationPipeline_base: new (
185+ options: TextPipelineConstructorArgs,
186+) => TokenClassificationPipelineType;
164187 /**
165188 * @typedef {Object} TokenClassificationSingle
166189 * @property {string} word The token/word classified. This is obtained by decoding the selected tokens.
@@ -211,9 +234,14 @@
211234 * ```
212235 */
213236 export class TokenClassificationPipeline extends TokenClassificationPipeline_base {
214- _call(texts: string | string[], options?: TokenClassificationPipelineOptions): Promise<TokenClassificationOutput | TokenClassificationOutput[]>;
237+ _call(
238+ texts: string | string[],
239+ options?: TokenClassificationPipelineOptions,
240+ ): Promise<TokenClassificationOutput | TokenClassificationOutput[]>;
215241 }
216-declare const QuestionAnsweringPipeline_base: new (options: TextPipelineConstructorArgs) => QuestionAnsweringPipelineType;
242+declare const QuestionAnsweringPipeline_base: new (
243+ options: TextPipelineConstructorArgs,
244+) => QuestionAnsweringPipelineType;
217245 /**
218246 * @typedef {Object} QuestionAnsweringOutput
219247 * @property {number} score The probability associated to the answer.
@@ -248,9 +276,15 @@
248276 * ```
249277 */
250278 export class QuestionAnsweringPipeline extends QuestionAnsweringPipeline_base {
251- _call(question: string | string[], context: string | string[], options?: QuestionAnsweringPipelineOptions): Promise<QuestionAnsweringOutput | QuestionAnsweringOutput[]>;
279+ _call(
280+ question: string | string[],
281+ context: string | string[],
282+ options?: QuestionAnsweringPipelineOptions,
283+ ): Promise<QuestionAnsweringOutput | QuestionAnsweringOutput[]>;
252284 }
253-declare const FillMaskPipeline_base: new (options: TextPipelineConstructorArgs) => FillMaskPipelineType;
285+declare const FillMaskPipeline_base: new (
286+ options: TextPipelineConstructorArgs,
287+) => FillMaskPipelineType;
254288 /**
255289 * @typedef {Object} FillMaskSingle
256290 * @property {string} sequence The corresponding input with the mask token prediction.
@@ -296,9 +330,14 @@
296330 * ```
297331 */
298332 export class FillMaskPipeline extends FillMaskPipeline_base {
299- _call(texts: string | string[], options?: FillMaskPipelineOptions): Promise<FillMaskOutput | FillMaskOutput[]>;
333+ _call(
334+ texts: string | string[],
335+ options?: FillMaskPipelineOptions,
336+ ): Promise<FillMaskOutput | FillMaskOutput[]>;
300337 }
301-declare const Text2TextGenerationPipeline_base: new (options: TextPipelineConstructorArgs) => Text2TextGenerationPipelineType;
338+declare const Text2TextGenerationPipeline_base: new (
339+ options: TextPipelineConstructorArgs,
340+) => Text2TextGenerationPipelineType;
302341 /**
303342 * @typedef {Object} Text2TextGenerationSingle
304343 * @property {string} generated_text The generated text.
@@ -324,11 +363,16 @@
324363 * ```
325364 */
326365 export class Text2TextGenerationPipeline extends Text2TextGenerationPipeline_base {
327- /** @type {'generated_text'} */
328- _key: 'generated_text';
329- _call(texts: string | string[], options?: import('./utils/generation.js').GenerationConfigType): Promise<Text2TextGenerationOutput | Text2TextGenerationOutput[]>;
366+ /** @type {'generated_text'} */
367+ _key: "generated_text";
368+ _call(
369+ texts: string | string[],
370+ options?: import("./utils/generation.js").GenerationConfigType,
371+ ): Promise<Text2TextGenerationOutput | Text2TextGenerationOutput[]>;
330372 }
331-declare const SummarizationPipeline_base: new (options: TextPipelineConstructorArgs) => SummarizationPipelineType;
373+declare const SummarizationPipeline_base: new (
374+ options: TextPipelineConstructorArgs,
375+) => SummarizationPipelineType;
332376 /**
333377 * @typedef {Object} SummarizationSingle
334378 * @property {string} summary_text The summary text.
@@ -362,10 +406,12 @@
362406 * ```
363407 */
364408 export class SummarizationPipeline extends SummarizationPipeline_base {
365- /** @type {'summary_text'} */
366- _key: 'summary_text';
409+ /** @type {'summary_text'} */
410+ _key: "summary_text";
367411 }
368-declare const TranslationPipeline_base: new (options: TextPipelineConstructorArgs) => TranslationPipelineType;
412+declare const TranslationPipeline_base: new (
413+ options: TextPipelineConstructorArgs,
414+) => TranslationPipelineType;
369415 /**
370416 * @typedef {Object} TranslationSingle
371417 * @property {string} translation_text The translated text.
@@ -424,10 +470,12 @@
424470 * ```
425471 */
426472 export class TranslationPipeline extends TranslationPipeline_base {
427- /** @type {'translation_text'} */
428- _key: 'translation_text';
473+ /** @type {'translation_text'} */
474+ _key: "translation_text";
429475 }
430-declare const TextGenerationPipeline_base: new (options: TextPipelineConstructorArgs) => TextGenerationPipelineType;
476+declare const TextGenerationPipeline_base: new (
477+ options: TextPipelineConstructorArgs,
478+) => TextGenerationPipelineType;
431479 /**
432480 * @typedef {Object} TextGenerationSingle
433481 * @property {string} generated_text The generated text.
@@ -495,9 +543,14 @@
495543 * ```
496544 */
497545 export class TextGenerationPipeline extends TextGenerationPipeline_base {
498- _call(texts: string | string[], options?: TextGenerationConfig): Promise<TextGenerationOutput | TextGenerationOutput[]>;
546+ _call(
547+ texts: string | string[],
548+ options?: TextGenerationConfig,
549+ ): Promise<TextGenerationOutput | TextGenerationOutput[]>;
499550 }
500-declare const ZeroShotClassificationPipeline_base: new (options: TextPipelineConstructorArgs) => ZeroShotClassificationPipelineType;
551+declare const ZeroShotClassificationPipeline_base: new (
552+ options: TextPipelineConstructorArgs,
553+) => ZeroShotClassificationPipelineType;
501554 /**
502555 * @typedef {Object} ZeroShotClassificationOutput
503556 * @property {string} sequence The sequence for which this is the output.
@@ -554,14 +607,20 @@
554607 * ```
555608 */
556609 export class ZeroShotClassificationPipeline extends ZeroShotClassificationPipeline_base {
557- label2id: {
558- [k: string]: any;
559- };
560- entailment_id: any;
561- contradiction_id: any;
562- _call(texts: string | string[], candidate_labels: string | string[], options?: ZeroShotClassificationPipelineOptions): Promise<ZeroShotClassificationOutput | ZeroShotClassificationOutput[]>;
610+ label2id: {
611+ [k: string]: any;
612+ };
613+ entailment_id: any;
614+ contradiction_id: any;
615+ _call(
616+ texts: string | string[],
617+ candidate_labels: string | string[],
618+ options?: ZeroShotClassificationPipelineOptions,
619+ ): Promise<ZeroShotClassificationOutput | ZeroShotClassificationOutput[]>;
563620 }
564-declare const FeatureExtractionPipeline_base: new (options: TextPipelineConstructorArgs) => FeatureExtractionPipelineType;
621+declare const FeatureExtractionPipeline_base: new (
622+ options: TextPipelineConstructorArgs,
623+) => FeatureExtractionPipelineType;
565624 /**
566625 * @typedef {Object} FeatureExtractionPipelineOptions Parameters specific to feature extraction pipelines.
567626 * @property {'none'|'mean'|'cls'} [pooling="none"] The pooling method to use.
@@ -612,9 +671,14 @@
612671 * ```
613672 */
614673 export class FeatureExtractionPipeline extends FeatureExtractionPipeline_base {
615- _call(texts: string | string[], options?: FeatureExtractionPipelineOptions): Promise<Tensor>;
674+ _call(
675+ texts: string | string[],
676+ options?: FeatureExtractionPipelineOptions,
677+ ): Promise<Tensor>;
616678 }
617-declare const AudioClassificationPipeline_base: new (options: AudioPipelineConstructorArgs) => AudioClassificationPipelineType;
679+declare const AudioClassificationPipeline_base: new (
680+ options: AudioPipelineConstructorArgs,
681+) => AudioClassificationPipelineType;
618682 /**
619683 * @typedef {Object} AudioClassificationSingle
620684 * @property {string} label The label predicted.
@@ -666,9 +730,14 @@
666730 * ```
667731 */
668732 export class AudioClassificationPipeline extends AudioClassificationPipeline_base {
669- _call(audio: AudioPipelineInputs, options?: AudioClassificationPipelineOptions): Promise<AudioClassificationOutput | AudioClassificationOutput[]>;
733+ _call(
734+ audio: AudioPipelineInputs,
735+ options?: AudioClassificationPipelineOptions,
736+ ): Promise<AudioClassificationOutput | AudioClassificationOutput[]>;
670737 }
671-declare const ZeroShotAudioClassificationPipeline_base: new (options: TextAudioPipelineConstructorArgs) => ZeroShotAudioClassificationPipelineType;
738+declare const ZeroShotAudioClassificationPipeline_base: new (
739+ options: TextAudioPipelineConstructorArgs,
740+) => ZeroShotAudioClassificationPipelineType;
672741 /**
673742 * @typedef {Object} ZeroShotAudioClassificationOutput
674743 * @property {string} label The label identified by the model. It is one of the suggested `candidate_label`.
@@ -708,9 +777,17 @@
708777 * ```
709778 */
710779 export class ZeroShotAudioClassificationPipeline extends ZeroShotAudioClassificationPipeline_base {
711- _call(audio: AudioPipelineInputs, candidate_labels: string[], options?: ZeroShotAudioClassificationPipelineOptions): Promise<ZeroShotAudioClassificationOutput[] | ZeroShotAudioClassificationOutput[][]>;
780+ _call(
781+ audio: AudioPipelineInputs,
782+ candidate_labels: string[],
783+ options?: ZeroShotAudioClassificationPipelineOptions,
784+ ): Promise<
785+ ZeroShotAudioClassificationOutput[] | ZeroShotAudioClassificationOutput[][]
786+ >;
712787 }
713-declare const AutomaticSpeechRecognitionPipeline_base: new (options: TextAudioPipelineConstructorArgs) => AutomaticSpeechRecognitionPipelineType;
788+declare const AutomaticSpeechRecognitionPipeline_base: new (
789+ options: TextAudioPipelineConstructorArgs,
790+) => AutomaticSpeechRecognitionPipelineType;
714791 /**
715792 * @typedef {{stride: number[], input_features: Tensor, is_last: boolean, tokens?: number[], token_timestamps?: number[]}} ChunkCallbackItem
716793 * @callback ChunkCallback
@@ -820,19 +897,26 @@
820897 * ```
821898 */
822899 export class AutomaticSpeechRecognitionPipeline extends AutomaticSpeechRecognitionPipeline_base {
823- _call(audio: AudioPipelineInputs, options?: AutomaticSpeechRecognitionConfig): Promise<AutomaticSpeechRecognitionOutput | AutomaticSpeechRecognitionOutput[]>;
824- /**
825- * @type {AutomaticSpeechRecognitionPipelineCallback}
826- * @private
827- */
828- private _call_wav2vec2;
829- /**
830- * @type {AutomaticSpeechRecognitionPipelineCallback}
831- * @private
832- */
833- private _call_whisper;
900+ _call(
901+ audio: AudioPipelineInputs,
902+ options?: AutomaticSpeechRecognitionConfig,
903+ ): Promise<
904+ AutomaticSpeechRecognitionOutput | AutomaticSpeechRecognitionOutput[]
905+ >;
906+ /**
907+ * @type {AutomaticSpeechRecognitionPipelineCallback}
908+ * @private
909+ */
910+ private _call_wav2vec2;
911+ /**
912+ * @type {AutomaticSpeechRecognitionPipelineCallback}
913+ * @private
914+ */
915+ private _call_whisper;
834916 }
835-declare const ImageToTextPipeline_base: new (options: TextImagePipelineConstructorArgs) => ImageToTextPipelineType;
917+declare const ImageToTextPipeline_base: new (
918+ options: TextImagePipelineConstructorArgs,
919+) => ImageToTextPipelineType;
836920 /**
837921 * @typedef {Object} ImageToTextSingle
838922 * @property {string} generated_text The generated text.
@@ -865,9 +949,14 @@
865949 * ```
866950 */
867951 export class ImageToTextPipeline extends ImageToTextPipeline_base {
868- _call(texts: ImagePipelineInputs, options?: import('./utils/generation.js').GenerationConfigType): Promise<ImageToTextOutput | ImageToTextOutput[]>;
952+ _call(
953+ texts: ImagePipelineInputs,
954+ options?: import("./utils/generation.js").GenerationConfigType,
955+ ): Promise<ImageToTextOutput | ImageToTextOutput[]>;
869956 }
870-declare const ImageClassificationPipeline_base: new (options: ImagePipelineConstructorArgs) => ImageClassificationPipelineType;
957+declare const ImageClassificationPipeline_base: new (
958+ options: ImagePipelineConstructorArgs,
959+) => ImageClassificationPipelineType;
871960 /**
872961 * @typedef {Object} ImageClassificationSingle
873962 * @property {string} label The label identified by the model.
@@ -925,9 +1014,14 @@
9251014 * ```
9261015 */
9271016 export class ImageClassificationPipeline extends ImageClassificationPipeline_base {
928- _call(images: ImagePipelineInputs, options?: ImageClassificationPipelineOptions): Promise<ImageClassificationOutput | ImageClassificationOutput[]>;
1017+ _call(
1018+ images: ImagePipelineInputs,
1019+ options?: ImageClassificationPipelineOptions,
1020+ ): Promise<ImageClassificationOutput | ImageClassificationOutput[]>;
9291021 }
930-declare const ImageSegmentationPipeline_base: new (options: ImagePipelineConstructorArgs) => ImageSegmentationPipelineType;
1022+declare const ImageSegmentationPipeline_base: new (
1023+ options: ImagePipelineConstructorArgs,
1024+) => ImageSegmentationPipelineType;
9311025 /**
9321026 * @typedef {Object} ImageSegmentationPipelineOutput
9331027 * @property {string} label The label of the segment.
@@ -966,14 +1060,19 @@
9661060 * ```
9671061 */
9681062 export class ImageSegmentationPipeline extends ImageSegmentationPipeline_base {
969- subtasks_mapping: {
970- panoptic: string;
971- instance: string;
972- semantic: string;
973- };
974- _call(images: ImagePipelineInputs, options?: ImageSegmentationPipelineOptions): Promise<ImageSegmentationPipelineOutput[]>;
1063+ subtasks_mapping: {
1064+ panoptic: string;
1065+ instance: string;
1066+ semantic: string;
1067+ };
1068+ _call(
1069+ images: ImagePipelineInputs,
1070+ options?: ImageSegmentationPipelineOptions,
1071+ ): Promise<ImageSegmentationPipelineOutput[]>;
9751072 }
976-declare const ZeroShotImageClassificationPipeline_base: new (options: TextImagePipelineConstructorArgs) => ZeroShotImageClassificationPipelineType;
1073+declare const ZeroShotImageClassificationPipeline_base: new (
1074+ options: TextImagePipelineConstructorArgs,
1075+) => ZeroShotImageClassificationPipelineType;
9771076 /**
9781077 * @typedef {Object} ZeroShotImageClassificationOutput
9791078 * @property {string} label The label identified by the model. It is one of the suggested `candidate_label`.
@@ -1009,9 +1108,17 @@
10091108 * ```
10101109 */
10111110 export class ZeroShotImageClassificationPipeline extends ZeroShotImageClassificationPipeline_base {
1012- _call(images: ImagePipelineInputs, candidate_labels: string[], options?: ZeroShotImageClassificationPipelineOptions): Promise<ZeroShotImageClassificationOutput[] | ZeroShotImageClassificationOutput[][]>;
1111+ _call(
1112+ images: ImagePipelineInputs,
1113+ candidate_labels: string[],
1114+ options?: ZeroShotImageClassificationPipelineOptions,
1115+ ): Promise<
1116+ ZeroShotImageClassificationOutput[] | ZeroShotImageClassificationOutput[][]
1117+ >;
10131118 }
1014-declare const ObjectDetectionPipeline_base: new (options: ImagePipelineConstructorArgs) => ObjectDetectionPipelineType;
1119+declare const ObjectDetectionPipeline_base: new (
1120+ options: ImagePipelineConstructorArgs,
1121+) => ObjectDetectionPipelineType;
10151122 /**
10161123 * @typedef {Object} ObjectDetectionPipelineSingle
10171124 * @property {string} label The class label identified by the model.
@@ -1053,9 +1160,14 @@
10531160 * ```
10541161 */
10551162 export class ObjectDetectionPipeline extends ObjectDetectionPipeline_base {
1056- _call(images: ImagePipelineInputs, options?: ObjectDetectionPipelineOptions): Promise<ObjectDetectionPipelineOutput | ObjectDetectionPipelineOutput[]>;
1163+ _call(
1164+ images: ImagePipelineInputs,
1165+ options?: ObjectDetectionPipelineOptions,
1166+ ): Promise<ObjectDetectionPipelineOutput | ObjectDetectionPipelineOutput[]>;
10571167 }
1058-declare const ZeroShotObjectDetectionPipeline_base: new (options: TextImagePipelineConstructorArgs) => ZeroShotObjectDetectionPipelineType;
1168+declare const ZeroShotObjectDetectionPipeline_base: new (
1169+ options: TextImagePipelineConstructorArgs,
1170+) => ZeroShotObjectDetectionPipelineType;
10591171 /**
10601172 * @typedef {Object} ZeroShotObjectDetectionOutput
10611173 * @property {string} label Text query corresponding to the found object.
@@ -1142,9 +1254,17 @@
11421254 * ```
11431255 */
11441256 export class ZeroShotObjectDetectionPipeline extends ZeroShotObjectDetectionPipeline_base {
1145- _call(images: ImagePipelineInputs, candidate_labels: string[], options?: ZeroShotObjectDetectionPipelineOptions): Promise<ZeroShotObjectDetectionOutput[] | ZeroShotObjectDetectionOutput[][]>;
1257+ _call(
1258+ images: ImagePipelineInputs,
1259+ candidate_labels: string[],
1260+ options?: ZeroShotObjectDetectionPipelineOptions,
1261+ ): Promise<
1262+ ZeroShotObjectDetectionOutput[] | ZeroShotObjectDetectionOutput[][]
1263+ >;
11461264 }
1147-declare const DocumentQuestionAnsweringPipeline_base: new (options: TextImagePipelineConstructorArgs) => DocumentQuestionAnsweringPipelineType;
1265+declare const DocumentQuestionAnsweringPipeline_base: new (
1266+ options: TextImagePipelineConstructorArgs,
1267+) => DocumentQuestionAnsweringPipelineType;
11481268 /**
11491269 * @typedef {Object} DocumentQuestionAnsweringSingle
11501270 * @property {string} answer The generated text.
@@ -1173,9 +1293,17 @@
11731293 * ```
11741294 */
11751295 export class DocumentQuestionAnsweringPipeline extends DocumentQuestionAnsweringPipeline_base {
1176- _call(image: ImageInput, question: string, options?: import('./utils/generation.js').GenerationConfigType): Promise<DocumentQuestionAnsweringOutput | DocumentQuestionAnsweringOutput[]>;
1296+ _call(
1297+ image: ImageInput,
1298+ question: string,
1299+ options?: import("./utils/generation.js").GenerationConfigType,
1300+ ): Promise<
1301+ DocumentQuestionAnsweringOutput | DocumentQuestionAnsweringOutput[]
1302+ >;
11771303 }
1178-declare const TextToAudioPipeline_base: new (options: TextToAudioPipelineConstructorArgs) => TextToAudioPipelineType;
1304+declare const TextToAudioPipeline_base: new (
1305+ options: TextToAudioPipelineConstructorArgs,
1306+) => TextToAudioPipelineType;
11791307 /**
11801308 * @typedef {Object} VocoderOptions
11811309 * @property {PreTrainedModel} [vocoder] The vocoder used by the pipeline (if the model uses one). If not provided, use the default HifiGan vocoder.
@@ -1232,21 +1360,31 @@
12321360 * ```
12331361 */
12341362 export class TextToAudioPipeline extends TextToAudioPipeline_base {
1235- DEFAULT_VOCODER_ID: string;
1236- vocoder: PreTrainedModel;
1237- _call(texts: string | string[], options: TextToAudioPipelineOptions): Promise<TextToAudioOutput>;
1238- _call_text_to_waveform(text_inputs: any): Promise<{
1239- audio: any;
1240- sampling_rate: any;
1241- }>;
1242- _call_text_to_spectrogram(text_inputs: any, { speaker_embeddings }: {
1243- speaker_embeddings: any;
1244- }): Promise<{
1245- audio: any;
1246- sampling_rate: any;
1247- }>;
1363+ DEFAULT_VOCODER_ID: string;
1364+ vocoder: PreTrainedModel;
1365+ _call(
1366+ texts: string | string[],
1367+ options: TextToAudioPipelineOptions,
1368+ ): Promise<TextToAudioOutput>;
1369+ _call_text_to_waveform(text_inputs: any): Promise<{
1370+ audio: any;
1371+ sampling_rate: any;
1372+ }>;
1373+ _call_text_to_spectrogram(
1374+ text_inputs: any,
1375+ {
1376+ speaker_embeddings,
1377+ }: {
1378+ speaker_embeddings: any;
1379+ },
1380+ ): Promise<{
1381+ audio: any;
1382+ sampling_rate: any;
1383+ }>;
12481384 }
1249-declare const ImageToImagePipeline_base: new (options: ImagePipelineConstructorArgs) => ImageToImagePipelineType;
1385+declare const ImageToImagePipeline_base: new (
1386+ options: ImagePipelineConstructorArgs,
1387+) => ImageToImagePipelineType;
12501388 /**
12511389 * @callback ImageToImagePipelineCallback Transform the image(s) passed as inputs.
12521390 * @param {ImagePipelineInputs} images The images to transform.
@@ -1271,9 +1409,11 @@
12711409 * ```
12721410 */
12731411 export class ImageToImagePipeline extends ImageToImagePipeline_base {
1274- _call(images: ImagePipelineInputs): Promise<RawImage | RawImage[]>;
1412+ _call(images: ImagePipelineInputs): Promise<RawImage | RawImage[]>;
12751413 }
1276-declare const DepthEstimationPipeline_base: new (options: ImagePipelineConstructorArgs) => DepthEstimationPipelineType;
1414+declare const DepthEstimationPipeline_base: new (
1415+ options: ImagePipelineConstructorArgs,
1416+) => DepthEstimationPipelineType;
12771417 /**
12781418 * @typedef {Object} DepthEstimationPipelineOutput
12791419 * @property {Tensor} predicted_depth The raw depth map predicted by the model.
@@ -1310,29 +1450,31 @@
13101450 * ```
13111451 */
13121452 export class DepthEstimationPipeline extends DepthEstimationPipeline_base {
1313- _call(images: ImagePipelineInputs): Promise<DepthEstimationPipelineOutput | DepthEstimationPipelineOutput[]>;
1453+ _call(
1454+ images: ImagePipelineInputs,
1455+ ): Promise<DepthEstimationPipelineOutput | DepthEstimationPipelineOutput[]>;
13141456 }
13151457 export type ImageInput = string | RawImage | URL;
13161458 export type ImagePipelineInputs = ImageInput | ImageInput[];
13171459 export type AudioInput = string | URL | Float32Array | Float64Array;
13181460 export type AudioPipelineInputs = AudioInput | AudioInput[];
13191461 export type BoundingBox = {
1320- /**
1321- * The minimum x coordinate of the bounding box.
1322- */
1323- xmin: number;
1324- /**
1325- * The minimum y coordinate of the bounding box.
1326- */
1327- ymin: number;
1328- /**
1329- * The maximum x coordinate of the bounding box.
1330- */
1331- xmax: number;
1332- /**
1333- * The maximum y coordinate of the bounding box.
1334- */
1335- ymax: number;
1462+ /**
1463+ * The minimum x coordinate of the bounding box.
1464+ */
1465+ xmin: number;
1466+ /**
1467+ * The minimum y coordinate of the bounding box.
1468+ */
1469+ ymin: number;
1470+ /**
1471+ * The maximum x coordinate of the bounding box.
1472+ */
1473+ xmax: number;
1474+ /**
1475+ * The maximum y coordinate of the bounding box.
1476+ */
1477+ ymax: number;
13361478 };
13371479 export type TaskType = keyof typeof SUPPORTED_TASKS;
13381480 export type AliasType = keyof typeof TASK_ALIASES;
@@ -1344,39 +1486,39 @@
13441486 * A mapping of pipeline names to their corresponding pipeline classes.
13451487 */
13461488 export type SupportedTasks = {
1347- "text-classification": TextClassificationPipeline;
1348- "token-classification": TokenClassificationPipeline;
1349- "question-answering": QuestionAnsweringPipeline;
1350- "fill-mask": FillMaskPipeline;
1351- summarization: SummarizationPipeline;
1352- translation: TranslationPipeline;
1353- "text2text-generation": Text2TextGenerationPipeline;
1354- "text-generation": TextGenerationPipeline;
1355- "zero-shot-classification": ZeroShotClassificationPipeline;
1356- "audio-classification": AudioClassificationPipeline;
1357- "zero-shot-audio-classification": ZeroShotAudioClassificationPipeline;
1358- "automatic-speech-recognition": AutomaticSpeechRecognitionPipeline;
1359- "text-to-audio": TextToAudioPipeline;
1360- "image-to-text": ImageToTextPipeline;
1361- "image-classification": ImageClassificationPipeline;
1362- "image-segmentation": ImageSegmentationPipeline;
1363- "zero-shot-image-classification": ZeroShotImageClassificationPipeline;
1364- "object-detection": ObjectDetectionPipeline;
1365- "zero-shot-object-detection": ZeroShotObjectDetectionPipeline;
1366- "document-question-answering": DocumentQuestionAnsweringPipeline;
1367- "image-to-image": ImageToImagePipeline;
1368- "depth-estimation": DepthEstimationPipeline;
1369- "feature-extraction": FeatureExtractionPipeline;
1489+ "text-classification": TextClassificationPipeline;
1490+ "token-classification": TokenClassificationPipeline;
1491+ "question-answering": QuestionAnsweringPipeline;
1492+ "fill-mask": FillMaskPipeline;
1493+ summarization: SummarizationPipeline;
1494+ translation: TranslationPipeline;
1495+ "text2text-generation": Text2TextGenerationPipeline;
1496+ "text-generation": TextGenerationPipeline;
1497+ "zero-shot-classification": ZeroShotClassificationPipeline;
1498+ "audio-classification": AudioClassificationPipeline;
1499+ "zero-shot-audio-classification": ZeroShotAudioClassificationPipeline;
1500+ "automatic-speech-recognition": AutomaticSpeechRecognitionPipeline;
1501+ "text-to-audio": TextToAudioPipeline;
1502+ "image-to-text": ImageToTextPipeline;
1503+ "image-classification": ImageClassificationPipeline;
1504+ "image-segmentation": ImageSegmentationPipeline;
1505+ "zero-shot-image-classification": ZeroShotImageClassificationPipeline;
1506+ "object-detection": ObjectDetectionPipeline;
1507+ "zero-shot-object-detection": ZeroShotObjectDetectionPipeline;
1508+ "document-question-answering": DocumentQuestionAnsweringPipeline;
1509+ "image-to-image": ImageToImagePipeline;
1510+ "depth-estimation": DepthEstimationPipeline;
1511+ "feature-extraction": FeatureExtractionPipeline;
13701512 };
13711513 /**
13721514 * A mapping from pipeline aliases to their corresponding pipeline classes.
13731515 */
13741516 export type AliasTasks = {
1375- "sentiment-analysis": TextClassificationPipeline;
1376- ner: TokenClassificationPipeline;
1377- asr: AutomaticSpeechRecognitionPipeline;
1378- "text-to-speech": TextToAudioPipeline;
1379- embeddings: FeatureExtractionPipeline;
1517+ "sentiment-analysis": TextClassificationPipeline;
1518+ ner: TokenClassificationPipeline;
1519+ asr: AutomaticSpeechRecognitionPipeline;
1520+ "text-to-speech": TextToAudioPipeline;
1521+ embeddings: FeatureExtractionPipeline;
13801522 };
13811523 /**
13821524 * A mapping from all pipeline names and aliases to their corresponding pipeline classes.
@@ -1387,42 +1529,42 @@
13871529 */
13881530 export type DisposeType = () => Promise<void>;
13891531 export type Disposable = {
1390- /**
1391- * A promise that resolves when the pipeline has been disposed.
1392- */
1393- dispose: DisposeType;
1532+ /**
1533+ * A promise that resolves when the pipeline has been disposed.
1534+ */
1535+ dispose: DisposeType;
13941536 };
13951537 export type ModelTokenizerConstructorArgs = {
1396- /**
1397- * The task of the pipeline. Useful for specifying subtasks.
1398- */
1399- task: string;
1400- /**
1401- * The model used by the pipeline.
1402- */
1403- model: PreTrainedModel;
1404- /**
1405- * The tokenizer used by the pipeline.
1406- */
1407- tokenizer: PreTrainedTokenizer;
1538+ /**
1539+ * The task of the pipeline. Useful for specifying subtasks.
1540+ */
1541+ task: string;
1542+ /**
1543+ * The model used by the pipeline.
1544+ */
1545+ model: PreTrainedModel;
1546+ /**
1547+ * The tokenizer used by the pipeline.
1548+ */
1549+ tokenizer: PreTrainedTokenizer;
14081550 };
14091551 /**
14101552 * An object used to instantiate a text-based pipeline.
14111553 */
14121554 export type TextPipelineConstructorArgs = ModelTokenizerConstructorArgs;
14131555 export type ModelProcessorConstructorArgs = {
1414- /**
1415- * The task of the pipeline. Useful for specifying subtasks.
1416- */
1417- task: string;
1418- /**
1419- * The model used by the pipeline.
1420- */
1421- model: PreTrainedModel;
1422- /**
1423- * The processor used by the pipeline.
1424- */
1425- processor: Processor;
1556+ /**
1557+ * The task of the pipeline. Useful for specifying subtasks.
1558+ */
1559+ task: string;
1560+ /**
1561+ * The model used by the pipeline.
1562+ */
1563+ model: PreTrainedModel;
1564+ /**
1565+ * The processor used by the pipeline.
1566+ */
1567+ processor: Processor;
14261568 };
14271569 /**
14281570 * An object used to instantiate an audio-based pipeline.
@@ -1433,898 +1575,1042 @@
14331575 */
14341576 export type ImagePipelineConstructorArgs = ModelProcessorConstructorArgs;
14351577 export type ModelTokenizerProcessorConstructorArgs = {
1436- /**
1437- * The task of the pipeline. Useful for specifying subtasks.
1438- */
1439- task: string;
1440- /**
1441- * The model used by the pipeline.
1442- */
1443- model: PreTrainedModel;
1444- /**
1445- * The tokenizer used by the pipeline.
1446- */
1447- tokenizer: PreTrainedTokenizer;
1448- /**
1449- * The processor used by the pipeline.
1450- */
1451- processor: Processor;
1578+ /**
1579+ * The task of the pipeline. Useful for specifying subtasks.
1580+ */
1581+ task: string;
1582+ /**
1583+ * The model used by the pipeline.
1584+ */
1585+ model: PreTrainedModel;
1586+ /**
1587+ * The tokenizer used by the pipeline.
1588+ */
1589+ tokenizer: PreTrainedTokenizer;
1590+ /**
1591+ * The processor used by the pipeline.
1592+ */
1593+ processor: Processor;
14521594 };
14531595 /**
14541596 * An object used to instantiate a text- and audio-based pipeline.
14551597 */
1456-export type TextAudioPipelineConstructorArgs = ModelTokenizerProcessorConstructorArgs;
1598+export type TextAudioPipelineConstructorArgs =
1599+ ModelTokenizerProcessorConstructorArgs;
14571600 /**
14581601 * An object used to instantiate a text- and image-based pipeline.
14591602 */
1460-export type TextImagePipelineConstructorArgs = ModelTokenizerProcessorConstructorArgs;
1603+export type TextImagePipelineConstructorArgs =
1604+ ModelTokenizerProcessorConstructorArgs;
14611605 export type TextClassificationSingle = {
1462- /**
1463- * The label predicted.
1464- */
1465- label: string;
1466- /**
1467- * The corresponding probability.
1468- */
1469- score: number;
1606+ /**
1607+ * The label predicted.
1608+ */
1609+ label: string;
1610+ /**
1611+ * The corresponding probability.
1612+ */
1613+ score: number;
14701614 };
14711615 export type TextClassificationOutput = TextClassificationSingle[];
14721616 /**
14731617 * Parameters specific to text classification pipelines.
14741618 */
14751619 export type TextClassificationPipelineOptions = {
1476- /**
1477- * The number of top predictions to be returned.
1478- */
1479- topk?: number;
1620+ /**
1621+ * The number of top predictions to be returned.
1622+ */
1623+ topk?: number;
14801624 };
14811625 /**
14821626 * Classify the text(s) given as inputs.
14831627 */
1484-export type TextClassificationPipelineCallback = (texts: string | string[], options?: TextClassificationPipelineOptions) => Promise<TextClassificationOutput | TextClassificationOutput[]>;
1485-export type TextClassificationPipelineType = TextPipelineConstructorArgs & TextClassificationPipelineCallback & Disposable;
1628+export type TextClassificationPipelineCallback = (
1629+ texts: string | string[],
1630+ options?: TextClassificationPipelineOptions,
1631+) => Promise<TextClassificationOutput | TextClassificationOutput[]>;
1632+export type TextClassificationPipelineType = TextPipelineConstructorArgs &
1633+ TextClassificationPipelineCallback &
1634+ Disposable;
14861635 export type TokenClassificationSingle = {
1487- /**
1488- * The token/word classified. This is obtained by decoding the selected tokens.
1489- */
1490- word: string;
1491- /**
1492- * The corresponding probability for `entity`.
1493- */
1494- score: number;
1495- /**
1496- * The entity predicted for that token/word.
1497- */
1498- entity: string;
1499- /**
1500- * The index of the corresponding token in the sentence.
1501- */
1502- index: number;
1503- /**
1504- * The index of the start of the corresponding entity in the sentence.
1505- */
1506- start?: number;
1507- /**
1508- * The index of the end of the corresponding entity in the sentence.
1509- */
1510- end?: number;
1636+ /**
1637+ * The token/word classified. This is obtained by decoding the selected tokens.
1638+ */
1639+ word: string;
1640+ /**
1641+ * The corresponding probability for `entity`.
1642+ */
1643+ score: number;
1644+ /**
1645+ * The entity predicted for that token/word.
1646+ */
1647+ entity: string;
1648+ /**
1649+ * The index of the corresponding token in the sentence.
1650+ */
1651+ index: number;
1652+ /**
1653+ * The index of the start of the corresponding entity in the sentence.
1654+ */
1655+ start?: number;
1656+ /**
1657+ * The index of the end of the corresponding entity in the sentence.
1658+ */
1659+ end?: number;
15111660 };
15121661 export type TokenClassificationOutput = TokenClassificationSingle[];
15131662 /**
15141663 * Parameters specific to token classification pipelines.
15151664 */
15161665 export type TokenClassificationPipelineOptions = {
1517- /**
1518- * A list of labels to ignore.
1519- */
1520- ignore_labels?: string[];
1666+ /**
1667+ * A list of labels to ignore.
1668+ */
1669+ ignore_labels?: string[];
15211670 };
15221671 /**
15231672 * Classify each token of the text(s) given as inputs.
15241673 */
1525-export type TokenClassificationPipelineCallback = (texts: string | string[], options?: TokenClassificationPipelineOptions) => Promise<TokenClassificationOutput | TokenClassificationOutput[]>;
1526-export type TokenClassificationPipelineType = TextPipelineConstructorArgs & TokenClassificationPipelineCallback & Disposable;
1674+export type TokenClassificationPipelineCallback = (
1675+ texts: string | string[],
1676+ options?: TokenClassificationPipelineOptions,
1677+) => Promise<TokenClassificationOutput | TokenClassificationOutput[]>;
1678+export type TokenClassificationPipelineType = TextPipelineConstructorArgs &
1679+ TokenClassificationPipelineCallback &
1680+ Disposable;
15271681 export type QuestionAnsweringOutput = {
1528- /**
1529- * The probability associated to the answer.
1530- */
1531- score: number;
1532- /**
1533- * The character start index of the answer (in the tokenized version of the input).
1534- */
1535- start?: number;
1536- /**
1537- * The character end index of the answer (in the tokenized version of the input).
1538- */
1539- end?: number;
1540- /**
1541- * The answer to the question.
1542- */
1543- answer: string;
1682+ /**
1683+ * The probability associated to the answer.
1684+ */
1685+ score: number;
1686+ /**
1687+ * The character start index of the answer (in the tokenized version of the input).
1688+ */
1689+ start?: number;
1690+ /**
1691+ * The character end index of the answer (in the tokenized version of the input).
1692+ */
1693+ end?: number;
1694+ /**
1695+ * The answer to the question.
1696+ */
1697+ answer: string;
15441698 };
15451699 /**
15461700 * Parameters specific to question answering pipelines.
15471701 */
15481702 export type QuestionAnsweringPipelineOptions = {
1549- /**
1550- * The number of top answer predictions to be returned.
1551- */
1552- topk?: number;
1703+ /**
1704+ * The number of top answer predictions to be returned.
1705+ */
1706+ topk?: number;
15531707 };
15541708 /**
15551709 * Answer the question(s) given as inputs by using the context(s).
15561710 */
1557-export type QuestionAnsweringPipelineCallback = (question: string | string[], context: string | string[], options?: QuestionAnsweringPipelineOptions) => Promise<QuestionAnsweringOutput | QuestionAnsweringOutput[]>;
1558-export type QuestionAnsweringPipelineType = TextPipelineConstructorArgs & QuestionAnsweringPipelineCallback & Disposable;
1711+export type QuestionAnsweringPipelineCallback = (
1712+ question: string | string[],
1713+ context: string | string[],
1714+ options?: QuestionAnsweringPipelineOptions,
1715+) => Promise<QuestionAnsweringOutput | QuestionAnsweringOutput[]>;
1716+export type QuestionAnsweringPipelineType = TextPipelineConstructorArgs &
1717+ QuestionAnsweringPipelineCallback &
1718+ Disposable;
15591719 export type FillMaskSingle = {
1560- /**
1561- * The corresponding input with the mask token prediction.
1562- */
1563- sequence: string;
1564- /**
1565- * The corresponding probability.
1566- */
1567- score: number;
1568- /**
1569- * The predicted token id (to replace the masked one).
1570- */
1571- token: number;
1572- /**
1573- * The predicted token (to replace the masked one).
1574- */
1575- token_str: string;
1720+ /**
1721+ * The corresponding input with the mask token prediction.
1722+ */
1723+ sequence: string;
1724+ /**
1725+ * The corresponding probability.
1726+ */
1727+ score: number;
1728+ /**
1729+ * The predicted token id (to replace the masked one).
1730+ */
1731+ token: number;
1732+ /**
1733+ * The predicted token (to replace the masked one).
1734+ */
1735+ token_str: string;
15761736 };
15771737 export type FillMaskOutput = FillMaskSingle[];
15781738 /**
15791739 * Parameters specific to fill mask pipelines.
15801740 */
15811741 export type FillMaskPipelineOptions = {
1582- /**
1583- * When passed, overrides the number of predictions to return.
1584- */
1585- topk?: number;
1742+ /**
1743+ * When passed, overrides the number of predictions to return.
1744+ */
1745+ topk?: number;
15861746 };
15871747 /**
15881748 * Fill the masked token in the text(s) given as inputs.
15891749 */
1590-export type FillMaskPipelineCallback = (texts: string | string[], options?: FillMaskPipelineOptions) => Promise<FillMaskOutput | FillMaskOutput[]>;
1591-export type FillMaskPipelineType = TextPipelineConstructorArgs & FillMaskPipelineCallback & Disposable;
1750+export type FillMaskPipelineCallback = (
1751+ texts: string | string[],
1752+ options?: FillMaskPipelineOptions,
1753+) => Promise<FillMaskOutput | FillMaskOutput[]>;
1754+export type FillMaskPipelineType = TextPipelineConstructorArgs &
1755+ FillMaskPipelineCallback &
1756+ Disposable;
15921757 export type Text2TextGenerationSingle = {
1593- /**
1594- * The generated text.
1595- */
1596- generated_text: string;
1758+ /**
1759+ * The generated text.
1760+ */
1761+ generated_text: string;
15971762 };
15981763 export type Text2TextGenerationOutput = Text2TextGenerationSingle[];
15991764 /**
16001765 * Generate the output text(s) using text(s) given as inputs.
16011766 */
1602-export type Text2TextGenerationPipelineCallback = (texts: string | string[], options?: import('./utils/generation.js').GenerationConfigType) => Promise<Text2TextGenerationOutput | Text2TextGenerationOutput[]>;
1603-export type Text2TextGenerationPipelineType = TextPipelineConstructorArgs & Text2TextGenerationPipelineCallback & Disposable;
1767+export type Text2TextGenerationPipelineCallback = (
1768+ texts: string | string[],
1769+ options?: import("./utils/generation.js").GenerationConfigType,
1770+) => Promise<Text2TextGenerationOutput | Text2TextGenerationOutput[]>;
1771+export type Text2TextGenerationPipelineType = TextPipelineConstructorArgs &
1772+ Text2TextGenerationPipelineCallback &
1773+ Disposable;
16041774 export type SummarizationSingle = {
1605- /**
1606- * The summary text.
1607- */
1608- summary_text: string;
1775+ /**
1776+ * The summary text.
1777+ */
1778+ summary_text: string;
16091779 };
16101780 export type SummarizationOutput = SummarizationSingle[];
16111781 /**
16121782 * Summarize the text(s) given as inputs.
16131783 */
1614-export type SummarizationPipelineCallback = (texts: string | string[], options?: import('./utils/generation.js').GenerationConfigType) => Promise<SummarizationOutput | SummarizationOutput[]>;
1615-export type SummarizationPipelineType = TextPipelineConstructorArgs & SummarizationPipelineCallback & Disposable;
1784+export type SummarizationPipelineCallback = (
1785+ texts: string | string[],
1786+ options?: import("./utils/generation.js").GenerationConfigType,
1787+) => Promise<SummarizationOutput | SummarizationOutput[]>;
1788+export type SummarizationPipelineType = TextPipelineConstructorArgs &
1789+ SummarizationPipelineCallback &
1790+ Disposable;
16161791 export type TranslationSingle = {
1617- /**
1618- * The translated text.
1619- */
1620- translation_text: string;
1792+ /**
1793+ * The translated text.
1794+ */
1795+ translation_text: string;
16211796 };
16221797 export type TranslationOutput = TranslationSingle[];
16231798 /**
16241799 * Translate the text(s) given as inputs.
16251800 */
1626-export type TranslationPipelineCallback = (texts: string | string[], options?: import('./utils/generation.js').GenerationConfigType) => Promise<TranslationOutput | TranslationOutput[]>;
1627-export type TranslationPipelineType = TextPipelineConstructorArgs & TranslationPipelineCallback & Disposable;
1801+export type TranslationPipelineCallback = (
1802+ texts: string | string[],
1803+ options?: import("./utils/generation.js").GenerationConfigType,
1804+) => Promise<TranslationOutput | TranslationOutput[]>;
1805+export type TranslationPipelineType = TextPipelineConstructorArgs &
1806+ TranslationPipelineCallback &
1807+ Disposable;
16281808 export type TextGenerationSingle = {
1629- /**
1630- * The generated text.
1631- */
1632- generated_text: string;
1809+ /**
1810+ * The generated text.
1811+ */
1812+ generated_text: string;
16331813 };
16341814 export type TextGenerationOutput = TextGenerationSingle[];
16351815 /**
16361816 * Parameters specific to text-generation pipelines.
16371817 */
16381818 export type TextGenerationSpecificParams = {
1639- /**
1640- * Whether or not to add special tokens when tokenizing the sequences.
1641- */
1642- add_special_tokens?: boolean;
1819+ /**
1820+ * Whether or not to add special tokens when tokenizing the sequences.
1821+ */
1822+ add_special_tokens?: boolean;
16431823 };
1644-export type TextGenerationConfig = import('./utils/generation.js').GenerationConfigType & TextGenerationSpecificParams;
1824+export type TextGenerationConfig =
1825+ import("./utils/generation.js").GenerationConfigType &
1826+ TextGenerationSpecificParams;
16451827 /**
16461828 * Complete the prompt(s) given as inputs.
16471829 */
1648-export type TextGenerationPipelineCallback = (texts: string | string[], options?: TextGenerationConfig) => Promise<TextGenerationOutput | TextGenerationOutput[]>;
1649-export type TextGenerationPipelineType = TextPipelineConstructorArgs & TextGenerationPipelineCallback & Disposable;
1830+export type TextGenerationPipelineCallback = (
1831+ texts: string | string[],
1832+ options?: TextGenerationConfig,
1833+) => Promise<TextGenerationOutput | TextGenerationOutput[]>;
1834+export type TextGenerationPipelineType = TextPipelineConstructorArgs &
1835+ TextGenerationPipelineCallback &
1836+ Disposable;
16501837 export type ZeroShotClassificationOutput = {
1651- /**
1652- * The sequence for which this is the output.
1653- */
1654- sequence: string;
1655- /**
1656- * The labels sorted by order of likelihood.
1657- */
1658- labels: string[];
1659- /**
1660- * The probabilities for each of the labels.
1661- */
1662- scores: number[];
1838+ /**
1839+ * The sequence for which this is the output.
1840+ */
1841+ sequence: string;
1842+ /**
1843+ * The labels sorted by order of likelihood.
1844+ */
1845+ labels: string[];
1846+ /**
1847+ * The probabilities for each of the labels.
1848+ */
1849+ scores: number[];
16631850 };
16641851 /**
16651852 * Parameters specific to zero-shot classification pipelines.
16661853 */
16671854 export type ZeroShotClassificationPipelineOptions = {
1668- /**
1669- * The template used to turn each
1670- * candidate label into an NLI-style hypothesis. The candidate label will replace the {} placeholder.
1671- */
1672- hypothesis_template?: string;
1673- /**
1674- * Whether or not multiple candidate labels can be true.
1675- * If `false`, the scores are normalized such that the sum of the label likelihoods for each sequence
1676- * is 1. If `true`, the labels are considered independent and probabilities are normalized for each
1677- * candidate by doing a softmax of the entailment score vs. the contradiction score.
1678- */
1679- multi_label?: boolean;
1855+ /**
1856+ * The template used to turn each
1857+ * candidate label into an NLI-style hypothesis. The candidate label will replace the {} placeholder.
1858+ */
1859+ hypothesis_template?: string;
1860+ /**
1861+ * Whether or not multiple candidate labels can be true.
1862+ * If `false`, the scores are normalized such that the sum of the label likelihoods for each sequence
1863+ * is 1. If `true`, the labels are considered independent and probabilities are normalized for each
1864+ * candidate by doing a softmax of the entailment score vs. the contradiction score.
1865+ */
1866+ multi_label?: boolean;
16801867 };
16811868 /**
16821869 * Classify the sequence(s) given as inputs.
16831870 */
1684-export type ZeroShotClassificationPipelineCallback = (texts: string | string[], candidate_labels: string | string[], options?: ZeroShotClassificationPipelineOptions) => Promise<ZeroShotClassificationOutput | ZeroShotClassificationOutput[]>;
1685-export type ZeroShotClassificationPipelineType = TextPipelineConstructorArgs & ZeroShotClassificationPipelineCallback & Disposable;
1871+export type ZeroShotClassificationPipelineCallback = (
1872+ texts: string | string[],
1873+ candidate_labels: string | string[],
1874+ options?: ZeroShotClassificationPipelineOptions,
1875+) => Promise<ZeroShotClassificationOutput | ZeroShotClassificationOutput[]>;
1876+export type ZeroShotClassificationPipelineType = TextPipelineConstructorArgs &
1877+ ZeroShotClassificationPipelineCallback &
1878+ Disposable;
16861879 /**
16871880 * Parameters specific to feature extraction pipelines.
16881881 */
16891882 export type FeatureExtractionPipelineOptions = {
1690- /**
1691- * The pooling method to use.
1692- */
1693- pooling?: 'none' | 'mean' | 'cls';
1694- /**
1695- * Whether or not to normalize the embeddings in the last dimension.
1696- */
1697- normalize?: boolean;
1883+ /**
1884+ * The pooling method to use.
1885+ */
1886+ pooling?: "none" | "mean" | "cls";
1887+ /**
1888+ * Whether or not to normalize the embeddings in the last dimension.
1889+ */
1890+ normalize?: boolean;
16981891 };
16991892 /**
17001893 * Extract the features of the input(s).
17011894 */
1702-export type FeatureExtractionPipelineCallback = (texts: string | string[], options?: FeatureExtractionPipelineOptions) => Promise<Tensor>;
1703-export type FeatureExtractionPipelineType = TextPipelineConstructorArgs & FeatureExtractionPipelineCallback & Disposable;
1895+export type FeatureExtractionPipelineCallback = (
1896+ texts: string | string[],
1897+ options?: FeatureExtractionPipelineOptions,
1898+) => Promise<Tensor>;
1899+export type FeatureExtractionPipelineType = TextPipelineConstructorArgs &
1900+ FeatureExtractionPipelineCallback &
1901+ Disposable;
17041902 export type AudioClassificationSingle = {
1705- /**
1706- * The label predicted.
1707- */
1708- label: string;
1709- /**
1710- * The corresponding probability.
1711- */
1712- score: number;
1903+ /**
1904+ * The label predicted.
1905+ */
1906+ label: string;
1907+ /**
1908+ * The corresponding probability.
1909+ */
1910+ score: number;
17131911 };
17141912 export type AudioClassificationOutput = AudioClassificationSingle[];
17151913 /**
17161914 * Parameters specific to audio classification pipelines.
17171915 */
17181916 export type AudioClassificationPipelineOptions = {
1719- /**
1720- * The number of top labels that will be returned by the pipeline.
1721- * If the provided number is `null` or higher than the number of labels available in the model configuration,
1722- * it will default to the number of labels.
1723- */
1724- topk?: number;
1917+ /**
1918+ * The number of top labels that will be returned by the pipeline.
1919+ * If the provided number is `null` or higher than the number of labels available in the model configuration,
1920+ * it will default to the number of labels.
1921+ */
1922+ topk?: number;
17251923 };
17261924 /**
17271925 * Classify the sequence(s) given as inputs.
17281926 */
1729-export type AudioClassificationPipelineCallback = (audio: AudioPipelineInputs, options?: AudioClassificationPipelineOptions) => Promise<AudioClassificationOutput | AudioClassificationOutput[]>;
1730-export type AudioClassificationPipelineType = AudioPipelineConstructorArgs & AudioClassificationPipelineCallback & Disposable;
1927+export type AudioClassificationPipelineCallback = (
1928+ audio: AudioPipelineInputs,
1929+ options?: AudioClassificationPipelineOptions,
1930+) => Promise<AudioClassificationOutput | AudioClassificationOutput[]>;
1931+export type AudioClassificationPipelineType = AudioPipelineConstructorArgs &
1932+ AudioClassificationPipelineCallback &
1933+ Disposable;
17311934 export type ZeroShotAudioClassificationOutput = {
1732- /**
1733- * The label identified by the model. It is one of the suggested `candidate_label`.
1734- */
1735- label: string;
1736- /**
1737- * The score attributed by the model for that label (between 0 and 1).
1738- */
1739- score: number;
1935+ /**
1936+ * The label identified by the model. It is one of the suggested `candidate_label`.
1937+ */
1938+ label: string;
1939+ /**
1940+ * The score attributed by the model for that label (between 0 and 1).
1941+ */
1942+ score: number;
17401943 };
17411944 /**
17421945 * Parameters specific to zero-shot audio classification pipelines.
17431946 */
17441947 export type ZeroShotAudioClassificationPipelineOptions = {
1745- /**
1746- * The sentence used in conjunction with `candidate_labels`
1747- * to attempt the audio classification by replacing the placeholder with the candidate_labels.
1748- * Then likelihood is estimated by using `logits_per_audio`.
1749- */
1750- hypothesis_template?: string;
1948+ /**
1949+ * The sentence used in conjunction with `candidate_labels`
1950+ * to attempt the audio classification by replacing the placeholder with the candidate_labels.
1951+ * Then likelihood is estimated by using `logits_per_audio`.
1952+ */
1953+ hypothesis_template?: string;
17511954 };
17521955 /**
17531956 * Classify the sequence(s) given as inputs.
17541957 */
1755-export type ZeroShotAudioClassificationPipelineCallback = (audio: AudioPipelineInputs, candidate_labels: string[], options?: ZeroShotAudioClassificationPipelineOptions) => Promise<ZeroShotAudioClassificationOutput[] | ZeroShotAudioClassificationOutput[][]>;
1756-export type ZeroShotAudioClassificationPipelineType = TextAudioPipelineConstructorArgs & ZeroShotAudioClassificationPipelineCallback & Disposable;
1958+export type ZeroShotAudioClassificationPipelineCallback = (
1959+ audio: AudioPipelineInputs,
1960+ candidate_labels: string[],
1961+ options?: ZeroShotAudioClassificationPipelineOptions,
1962+) => Promise<
1963+ ZeroShotAudioClassificationOutput[] | ZeroShotAudioClassificationOutput[][]
1964+>;
1965+export type ZeroShotAudioClassificationPipelineType =
1966+ TextAudioPipelineConstructorArgs &
1967+ ZeroShotAudioClassificationPipelineCallback &
1968+ Disposable;
17571969 export type ChunkCallbackItem = {
1758- stride: number[];
1759- input_features: Tensor;
1760- is_last: boolean;
1761- tokens?: number[];
1762- token_timestamps?: number[];
1970+ stride: number[];
1971+ input_features: Tensor;
1972+ is_last: boolean;
1973+ tokens?: number[];
1974+ token_timestamps?: number[];
17631975 };
17641976 export type ChunkCallback = (chunk: ChunkCallbackItem) => any;
17651977 export type Chunk = {
1766- /**
1767- * The start and end timestamp of the chunk in seconds.
1768- */
1769- timestamp: [number, number];
1770- /**
1771- * The recognized text.
1772- */
1773- text: string;
1978+ /**
1979+ * The start and end timestamp of the chunk in seconds.
1980+ */
1981+ timestamp: [number, number];
1982+ /**
1983+ * The recognized text.
1984+ */
1985+ text: string;
17741986 };
17751987 export type AutomaticSpeechRecognitionOutput = {
1776- /**
1777- * The recognized text.
1778- */
1779- text: string;
1780- /**
1781- * When using `return_timestamps`, the `chunks` will become a list
1782- * containing all the various text chunks identified by the model.
1783- */
1784- chunks?: Chunk[];
1988+ /**
1989+ * The recognized text.
1990+ */
1991+ text: string;
1992+ /**
1993+ * When using `return_timestamps`, the `chunks` will become a list
1994+ * containing all the various text chunks identified by the model.
1995+ */
1996+ chunks?: Chunk[];
17851997 };
17861998 /**
17871999 * Parameters specific to automatic-speech-recognition pipelines.
17882000 */
17892001 export type AutomaticSpeechRecognitionSpecificParams = {
1790- /**
1791- * Whether to return timestamps or not. Default is `false`.
1792- */
1793- return_timestamps?: boolean | 'word';
1794- /**
1795- * The length of audio chunks to process in seconds. Default is 0 (no chunking).
1796- */
1797- chunk_length_s?: number;
1798- /**
1799- * The length of overlap between consecutive audio chunks in seconds. If not provided, defaults to `chunk_length_s / 6`.
1800- */
1801- stride_length_s?: number;
1802- /**
1803- * Callback function to be called with each chunk processed.
1804- */
1805- chunk_callback?: ChunkCallback;
1806- /**
1807- * Whether to force outputting full sequences or not. Default is `false`.
1808- */
1809- force_full_sequences?: boolean;
1810- /**
1811- * The source language. Default is `null`, meaning it should be auto-detected. Use this to potentially improve performance if the source language is known.
1812- */
1813- language?: string;
1814- /**
1815- * The task to perform. Default is `null`, meaning it should be auto-detected.
1816- */
1817- task?: string;
1818- /**
1819- * A list of pairs of integers which indicates a mapping from generation indices to token indices
1820- * that will be forced before sampling. For example, [[1, 123]] means the second generated token will always be a token of index 123.
1821- */
1822- forced_decoder_ids?: number[][];
1823- /**
1824- * The number of frames in the input audio.
1825- */
1826- num_frames?: number;
2002+ /**
2003+ * Whether to return timestamps or not. Default is `false`.
2004+ */
2005+ return_timestamps?: boolean | "word";
2006+ /**
2007+ * The length of audio chunks to process in seconds. Default is 0 (no chunking).
2008+ */
2009+ chunk_length_s?: number;
2010+ /**
2011+ * The length of overlap between consecutive audio chunks in seconds. If not provided, defaults to `chunk_length_s / 6`.
2012+ */
2013+ stride_length_s?: number;
2014+ /**
2015+ * Callback function to be called with each chunk processed.
2016+ */
2017+ chunk_callback?: ChunkCallback;
2018+ /**
2019+ * Whether to force outputting full sequences or not. Default is `false`.
2020+ */
2021+ force_full_sequences?: boolean;
2022+ /**
2023+ * The source language. Default is `null`, meaning it should be auto-detected. Use this to potentially improve performance if the source language is known.
2024+ */
2025+ language?: string;
2026+ /**
2027+ * The task to perform. Default is `null`, meaning it should be auto-detected.
2028+ */
2029+ task?: string;
2030+ /**
2031+ * A list of pairs of integers which indicates a mapping from generation indices to token indices
2032+ * that will be forced before sampling. For example, [[1, 123]] means the second generated token will always be a token of index 123.
2033+ */
2034+ forced_decoder_ids?: number[][];
2035+ /**
2036+ * The number of frames in the input audio.
2037+ */
2038+ num_frames?: number;
18272039 };
1828-export type AutomaticSpeechRecognitionConfig = import('./utils/generation.js').GenerationConfigType & AutomaticSpeechRecognitionSpecificParams;
2040+export type AutomaticSpeechRecognitionConfig =
2041+ import("./utils/generation.js").GenerationConfigType &
2042+ AutomaticSpeechRecognitionSpecificParams;
18292043 /**
18302044 * Transcribe the audio sequence(s) given as inputs to text.
18312045 */
1832-export type AutomaticSpeechRecognitionPipelineCallback = (audio: AudioPipelineInputs, options?: AutomaticSpeechRecognitionConfig) => Promise<AutomaticSpeechRecognitionOutput | AutomaticSpeechRecognitionOutput[]>;
1833-export type AutomaticSpeechRecognitionPipelineType = TextAudioPipelineConstructorArgs & AutomaticSpeechRecognitionPipelineCallback & Disposable;
2046+export type AutomaticSpeechRecognitionPipelineCallback = (
2047+ audio: AudioPipelineInputs,
2048+ options?: AutomaticSpeechRecognitionConfig,
2049+) => Promise<
2050+ AutomaticSpeechRecognitionOutput | AutomaticSpeechRecognitionOutput[]
2051+>;
2052+export type AutomaticSpeechRecognitionPipelineType =
2053+ TextAudioPipelineConstructorArgs &
2054+ AutomaticSpeechRecognitionPipelineCallback &
2055+ Disposable;
18342056 export type ImageToTextSingle = {
1835- /**
1836- * The generated text.
1837- */
1838- generated_text: string;
2057+ /**
2058+ * The generated text.
2059+ */
2060+ generated_text: string;
18392061 };
18402062 export type ImageToTextOutput = ImageToTextSingle[];
18412063 /**
18422064 * Assign labels to the image(s) passed as inputs.
18432065 */
1844-export type ImageToTextPipelineCallback = (texts: ImagePipelineInputs, options?: import('./utils/generation.js').GenerationConfigType) => Promise<ImageToTextOutput | ImageToTextOutput[]>;
1845-export type ImageToTextPipelineType = TextImagePipelineConstructorArgs & ImageToTextPipelineCallback & Disposable;
2066+export type ImageToTextPipelineCallback = (
2067+ texts: ImagePipelineInputs,
2068+ options?: import("./utils/generation.js").GenerationConfigType,
2069+) => Promise<ImageToTextOutput | ImageToTextOutput[]>;
2070+export type ImageToTextPipelineType = TextImagePipelineConstructorArgs &
2071+ ImageToTextPipelineCallback &
2072+ Disposable;
18462073 export type ImageClassificationSingle = {
1847- /**
1848- * The label identified by the model.
1849- */
1850- label: string;
1851- /**
1852- * The score attributed by the model for that label.
1853- */
1854- score: number;
2074+ /**
2075+ * The label identified by the model.
2076+ */
2077+ label: string;
2078+ /**
2079+ * The score attributed by the model for that label.
2080+ */
2081+ score: number;
18552082 };
18562083 export type ImageClassificationOutput = ImageClassificationSingle[];
18572084 /**
18582085 * Parameters specific to image classification pipelines.
18592086 */
18602087 export type ImageClassificationPipelineOptions = {
1861- /**
1862- * The number of top labels that will be returned by the pipeline.
1863- */
1864- topk?: number;
2088+ /**
2089+ * The number of top labels that will be returned by the pipeline.
2090+ */
2091+ topk?: number;
18652092 };
18662093 /**
18672094 * Assign labels to the image(s) passed as inputs.
18682095 */
1869-export type ImageClassificationPipelineCallback = (images: ImagePipelineInputs, options?: ImageClassificationPipelineOptions) => Promise<ImageClassificationOutput | ImageClassificationOutput[]>;
1870-export type ImageClassificationPipelineType = ImagePipelineConstructorArgs & ImageClassificationPipelineCallback & Disposable;
2096+export type ImageClassificationPipelineCallback = (
2097+ images: ImagePipelineInputs,
2098+ options?: ImageClassificationPipelineOptions,
2099+) => Promise<ImageClassificationOutput | ImageClassificationOutput[]>;
2100+export type ImageClassificationPipelineType = ImagePipelineConstructorArgs &
2101+ ImageClassificationPipelineCallback &
2102+ Disposable;
18712103 export type ImageSegmentationPipelineOutput = {
1872- /**
1873- * The label of the segment.
1874- */
1875- label: string;
1876- /**
1877- * The score of the segment.
1878- */
1879- score: number | null;
1880- /**
1881- * The mask of the segment.
1882- */
1883- mask: RawImage;
2104+ /**
2105+ * The label of the segment.
2106+ */
2107+ label: string;
2108+ /**
2109+ * The score of the segment.
2110+ */
2111+ score: number | null;
2112+ /**
2113+ * The mask of the segment.
2114+ */
2115+ mask: RawImage;
18842116 };
18852117 /**
18862118 * Parameters specific to image segmentation pipelines.
18872119 */
18882120 export type ImageSegmentationPipelineOptions = {
1889- /**
1890- * Probability threshold to filter out predicted masks.
1891- */
1892- threshold?: number;
1893- /**
1894- * Threshold to use when turning the predicted masks into binary values.
1895- */
1896- mask_threshold?: number;
1897- /**
1898- * Mask overlap threshold to eliminate small, disconnected segments.
1899- */
1900- overlap_mask_area_threshold?: number;
1901- /**
1902- * Segmentation task to be performed. One of [`panoptic`, `instance`, and `semantic`],
1903- * depending on model capabilities. If not set, the pipeline will attempt to resolve (in that order).
1904- */
1905- subtask?: null | string;
1906- /**
1907- * List of label ids to fuse. If not set, do not fuse any labels.
1908- */
1909- label_ids_to_fuse?: number[];
1910- /**
1911- * List of target sizes for the input images. If not set, use the original image sizes.
1912- */
1913- target_sizes?: number[][];
2121+ /**
2122+ * Probability threshold to filter out predicted masks.
2123+ */
2124+ threshold?: number;
2125+ /**
2126+ * Threshold to use when turning the predicted masks into binary values.
2127+ */
2128+ mask_threshold?: number;
2129+ /**
2130+ * Mask overlap threshold to eliminate small, disconnected segments.
2131+ */
2132+ overlap_mask_area_threshold?: number;
2133+ /**
2134+ * Segmentation task to be performed. One of [`panoptic`, `instance`, and `semantic`],
2135+ * depending on model capabilities. If not set, the pipeline will attempt to resolve (in that order).
2136+ */
2137+ subtask?: null | string;
2138+ /**
2139+ * List of label ids to fuse. If not set, do not fuse any labels.
2140+ */
2141+ label_ids_to_fuse?: number[];
2142+ /**
2143+ * List of target sizes for the input images. If not set, use the original image sizes.
2144+ */
2145+ target_sizes?: number[][];
19142146 };
19152147 /**
19162148 * Segment the input images.
19172149 */
1918-export type ImageSegmentationPipelineCallback = (images: ImagePipelineInputs, options?: ImageSegmentationPipelineOptions) => Promise<ImageSegmentationPipelineOutput[]>;
1919-export type ImageSegmentationPipelineType = ImagePipelineConstructorArgs & ImageSegmentationPipelineCallback & Disposable;
2150+export type ImageSegmentationPipelineCallback = (
2151+ images: ImagePipelineInputs,
2152+ options?: ImageSegmentationPipelineOptions,
2153+) => Promise<ImageSegmentationPipelineOutput[]>;
2154+export type ImageSegmentationPipelineType = ImagePipelineConstructorArgs &
2155+ ImageSegmentationPipelineCallback &
2156+ Disposable;
19202157 export type ZeroShotImageClassificationOutput = {
1921- /**
1922- * The label identified by the model. It is one of the suggested `candidate_label`.
1923- */
1924- label: string;
1925- /**
1926- * The score attributed by the model for that label (between 0 and 1).
1927- */
1928- score: number;
2158+ /**
2159+ * The label identified by the model. It is one of the suggested `candidate_label`.
2160+ */
2161+ label: string;
2162+ /**
2163+ * The score attributed by the model for that label (between 0 and 1).
2164+ */
2165+ score: number;
19292166 };
19302167 /**
19312168 * Parameters specific to zero-shot image classification pipelines.
19322169 */
19332170 export type ZeroShotImageClassificationPipelineOptions = {
1934- /**
1935- * The sentence used in conjunction with `candidate_labels`
1936- * to attempt the image classification by replacing the placeholder with the candidate_labels.
1937- * Then likelihood is estimated by using `logits_per_image`.
1938- */
1939- hypothesis_template?: string;
2171+ /**
2172+ * The sentence used in conjunction with `candidate_labels`
2173+ * to attempt the image classification by replacing the placeholder with the candidate_labels.
2174+ * Then likelihood is estimated by using `logits_per_image`.
2175+ */
2176+ hypothesis_template?: string;
19402177 };
19412178 /**
19422179 * Assign labels to the image(s) passed as inputs.
19432180 */
1944-export type ZeroShotImageClassificationPipelineCallback = (images: ImagePipelineInputs, candidate_labels: string[], options?: ZeroShotImageClassificationPipelineOptions) => Promise<ZeroShotImageClassificationOutput[] | ZeroShotImageClassificationOutput[][]>;
1945-export type ZeroShotImageClassificationPipelineType = TextImagePipelineConstructorArgs & ZeroShotImageClassificationPipelineCallback & Disposable;
2181+export type ZeroShotImageClassificationPipelineCallback = (
2182+ images: ImagePipelineInputs,
2183+ candidate_labels: string[],
2184+ options?: ZeroShotImageClassificationPipelineOptions,
2185+) => Promise<
2186+ ZeroShotImageClassificationOutput[] | ZeroShotImageClassificationOutput[][]
2187+>;
2188+export type ZeroShotImageClassificationPipelineType =
2189+ TextImagePipelineConstructorArgs &
2190+ ZeroShotImageClassificationPipelineCallback &
2191+ Disposable;
19462192 export type ObjectDetectionPipelineSingle = {
1947- /**
1948- * The class label identified by the model.
1949- */
1950- label: string;
1951- /**
1952- * The score attributed by the model for that label.
1953- */
1954- score: number;
1955- /**
1956- * The bounding box of detected object in image's original size, or as a percentage if `percentage` is set to true.
1957- */
1958- box: BoundingBox;
2193+ /**
2194+ * The class label identified by the model.
2195+ */
2196+ label: string;
2197+ /**
2198+ * The score attributed by the model for that label.
2199+ */
2200+ score: number;
2201+ /**
2202+ * The bounding box of detected object in image's original size, or as a percentage if `percentage` is set to true.
2203+ */
2204+ box: BoundingBox;
19592205 };
19602206 export type ObjectDetectionPipelineOutput = ObjectDetectionPipelineSingle[];
19612207 /**
19622208 * Parameters specific to object detection pipelines.
19632209 */
19642210 export type ObjectDetectionPipelineOptions = {
1965- /**
1966- * The threshold used to filter boxes by score.
1967- */
1968- threshold?: number;
1969- /**
1970- * Whether to return the boxes coordinates in percentage (true) or in pixels (false).
1971- */
1972- percentage?: boolean;
2211+ /**
2212+ * The threshold used to filter boxes by score.
2213+ */
2214+ threshold?: number;
2215+ /**
2216+ * Whether to return the boxes coordinates in percentage (true) or in pixels (false).
2217+ */
2218+ percentage?: boolean;
19732219 };
19742220 /**
19752221 * Detect objects (bounding boxes & classes) in the image(s) passed as inputs.
19762222 */
1977-export type ObjectDetectionPipelineCallback = (images: ImagePipelineInputs, options?: ObjectDetectionPipelineOptions) => Promise<ObjectDetectionPipelineOutput | ObjectDetectionPipelineOutput[]>;
1978-export type ObjectDetectionPipelineType = ImagePipelineConstructorArgs & ObjectDetectionPipelineCallback & Disposable;
2223+export type ObjectDetectionPipelineCallback = (
2224+ images: ImagePipelineInputs,
2225+ options?: ObjectDetectionPipelineOptions,
2226+) => Promise<ObjectDetectionPipelineOutput | ObjectDetectionPipelineOutput[]>;
2227+export type ObjectDetectionPipelineType = ImagePipelineConstructorArgs &
2228+ ObjectDetectionPipelineCallback &
2229+ Disposable;
19792230 export type ZeroShotObjectDetectionOutput = {
1980- /**
1981- * Text query corresponding to the found object.
1982- */
1983- label: string;
1984- /**
1985- * Score corresponding to the object (between 0 and 1).
1986- */
1987- score: number;
1988- /**
1989- * Bounding box of the detected object in image's original size, or as a percentage if `percentage` is set to true.
1990- */
1991- box: BoundingBox;
2231+ /**
2232+ * Text query corresponding to the found object.
2233+ */
2234+ label: string;
2235+ /**
2236+ * Score corresponding to the object (between 0 and 1).
2237+ */
2238+ score: number;
2239+ /**
2240+ * Bounding box of the detected object in image's original size, or as a percentage if `percentage` is set to true.
2241+ */
2242+ box: BoundingBox;
19922243 };
19932244 /**
19942245 * Parameters specific to zero-shot object detection pipelines.
19952246 */
19962247 export type ZeroShotObjectDetectionPipelineOptions = {
1997- /**
1998- * The probability necessary to make a prediction.
1999- */
2000- threshold?: number;
2001- /**
2002- * The number of top predictions that will be returned by the pipeline.
2003- * If the provided number is `null` or higher than the number of predictions available, it will default
2004- * to the number of predictions.
2005- */
2006- topk?: number;
2007- /**
2008- * Whether to return the boxes coordinates in percentage (true) or in pixels (false).
2009- */
2010- percentage?: boolean;
2248+ /**
2249+ * The probability necessary to make a prediction.
2250+ */
2251+ threshold?: number;
2252+ /**
2253+ * The number of top predictions that will be returned by the pipeline.
2254+ * If the provided number is `null` or higher than the number of predictions available, it will default
2255+ * to the number of predictions.
2256+ */
2257+ topk?: number;
2258+ /**
2259+ * Whether to return the boxes coordinates in percentage (true) or in pixels (false).
2260+ */
2261+ percentage?: boolean;
20112262 };
20122263 /**
20132264 * Detect objects (bounding boxes & classes) in the image(s) passed as inputs.
20142265 */
2015-export type ZeroShotObjectDetectionPipelineCallback = (images: ImagePipelineInputs, candidate_labels: string[], options?: ZeroShotObjectDetectionPipelineOptions) => Promise<ZeroShotObjectDetectionOutput[] | ZeroShotObjectDetectionOutput[][]>;
2016-export type ZeroShotObjectDetectionPipelineType = TextImagePipelineConstructorArgs & ZeroShotObjectDetectionPipelineCallback & Disposable;
2266+export type ZeroShotObjectDetectionPipelineCallback = (
2267+ images: ImagePipelineInputs,
2268+ candidate_labels: string[],
2269+ options?: ZeroShotObjectDetectionPipelineOptions,
2270+) => Promise<
2271+ ZeroShotObjectDetectionOutput[] | ZeroShotObjectDetectionOutput[][]
2272+>;
2273+export type ZeroShotObjectDetectionPipelineType =
2274+ TextImagePipelineConstructorArgs &
2275+ ZeroShotObjectDetectionPipelineCallback &
2276+ Disposable;
20172277 export type DocumentQuestionAnsweringSingle = {
2018- /**
2019- * The generated text.
2020- */
2021- answer: string;
2278+ /**
2279+ * The generated text.
2280+ */
2281+ answer: string;
20222282 };
20232283 export type DocumentQuestionAnsweringOutput = DocumentQuestionAnsweringSingle[];
20242284 /**
20252285 * Answer the question given as input by using the document.
20262286 */
2027-export type DocumentQuestionAnsweringPipelineCallback = (image: ImageInput, question: string, options?: import('./utils/generation.js').GenerationConfigType) => Promise<DocumentQuestionAnsweringOutput | DocumentQuestionAnsweringOutput[]>;
2028-export type DocumentQuestionAnsweringPipelineType = TextImagePipelineConstructorArgs & DocumentQuestionAnsweringPipelineCallback & Disposable;
2287+export type DocumentQuestionAnsweringPipelineCallback = (
2288+ image: ImageInput,
2289+ question: string,
2290+ options?: import("./utils/generation.js").GenerationConfigType,
2291+) => Promise<
2292+ DocumentQuestionAnsweringOutput | DocumentQuestionAnsweringOutput[]
2293+>;
2294+export type DocumentQuestionAnsweringPipelineType =
2295+ TextImagePipelineConstructorArgs &
2296+ DocumentQuestionAnsweringPipelineCallback &
2297+ Disposable;
20292298 export type VocoderOptions = {
2030- /**
2031- * The vocoder used by the pipeline (if the model uses one). If not provided, use the default HifiGan vocoder.
2032- */
2033- vocoder?: PreTrainedModel;
2299+ /**
2300+ * The vocoder used by the pipeline (if the model uses one). If not provided, use the default HifiGan vocoder.
2301+ */
2302+ vocoder?: PreTrainedModel;
20342303 };
2035-export type TextToAudioPipelineConstructorArgs = TextAudioPipelineConstructorArgs & VocoderOptions;
2304+export type TextToAudioPipelineConstructorArgs =
2305+ TextAudioPipelineConstructorArgs & VocoderOptions;
20362306 export type TextToAudioOutput = {
2037- /**
2038- * The generated audio waveform.
2039- */
2040- audio: Float32Array;
2041- /**
2042- * The sampling rate of the generated audio waveform.
2043- */
2044- sampling_rate: number;
2307+ /**
2308+ * The generated audio waveform.
2309+ */
2310+ audio: Float32Array;
2311+ /**
2312+ * The sampling rate of the generated audio waveform.
2313+ */
2314+ sampling_rate: number;
20452315 };
20462316 /**
20472317 * Parameters specific to text-to-audio pipelines.
20482318 */
20492319 export type TextToAudioPipelineOptions = {
2050- /**
2051- * The speaker embeddings (if the model requires it).
2052- */
2053- speaker_embeddings?: Tensor | Float32Array | string | URL;
2320+ /**
2321+ * The speaker embeddings (if the model requires it).
2322+ */
2323+ speaker_embeddings?: Tensor | Float32Array | string | URL;
20542324 };
20552325 /**
20562326 * Generates speech/audio from the inputs.
20572327 */
2058-export type TextToAudioPipelineCallback = (texts: string | string[], options: TextToAudioPipelineOptions) => Promise<TextToAudioOutput>;
2059-export type TextToAudioPipelineType = TextToAudioPipelineConstructorArgs & TextToAudioPipelineCallback & Disposable;
2328+export type TextToAudioPipelineCallback = (
2329+ texts: string | string[],
2330+ options: TextToAudioPipelineOptions,
2331+) => Promise<TextToAudioOutput>;
2332+export type TextToAudioPipelineType = TextToAudioPipelineConstructorArgs &
2333+ TextToAudioPipelineCallback &
2334+ Disposable;
20602335 /**
20612336 * Transform the image(s) passed as inputs.
20622337 */
2063-export type ImageToImagePipelineCallback = (images: ImagePipelineInputs) => Promise<RawImage | RawImage[]>;
2064-export type ImageToImagePipelineType = ImagePipelineConstructorArgs & ImageToImagePipelineCallback & Disposable;
2338+export type ImageToImagePipelineCallback = (
2339+ images: ImagePipelineInputs,
2340+) => Promise<RawImage | RawImage[]>;
2341+export type ImageToImagePipelineType = ImagePipelineConstructorArgs &
2342+ ImageToImagePipelineCallback &
2343+ Disposable;
20652344 export type DepthEstimationPipelineOutput = {
2066- /**
2067- * The raw depth map predicted by the model.
2068- */
2069- predicted_depth: Tensor;
2070- /**
2071- * The processed depth map as an image (with the same size as the input image).
2072- */
2073- depth: RawImage;
2345+ /**
2346+ * The raw depth map predicted by the model.
2347+ */
2348+ predicted_depth: Tensor;
2349+ /**
2350+ * The processed depth map as an image (with the same size as the input image).
2351+ */
2352+ depth: RawImage;
20742353 };
20752354 /**
20762355 * Predicts the depth for the image(s) passed as inputs.
20772356 */
2078-export type DepthEstimationPipelineCallback = (images: ImagePipelineInputs) => Promise<DepthEstimationPipelineOutput | DepthEstimationPipelineOutput[]>;
2079-export type DepthEstimationPipelineType = ImagePipelineConstructorArgs & DepthEstimationPipelineCallback & Disposable;
2080-import { PreTrainedModel } from './models.js';
2081-import { PreTrainedTokenizer } from './tokenizers.js';
2082-import { Processor } from './processors.js';
2083-import { Tensor } from './utils/tensor.js';
2084-import { RawImage } from './utils/image.js';
2357+export type DepthEstimationPipelineCallback = (
2358+ images: ImagePipelineInputs,
2359+) => Promise<DepthEstimationPipelineOutput | DepthEstimationPipelineOutput[]>;
2360+export type DepthEstimationPipelineType = ImagePipelineConstructorArgs &
2361+ DepthEstimationPipelineCallback &
2362+ Disposable;
2363+import { PreTrainedModel } from "./models.js";
2364+import { PreTrainedTokenizer } from "./tokenizers.js";
2365+import { Processor } from "./processors.js";
2366+import { Tensor } from "./utils/tensor.js";
2367+import { RawImage } from "./utils/image.js";
20852368 declare const SUPPORTED_TASKS: Readonly<{
2086- "text-classification": {
2087- tokenizer: typeof AutoTokenizer;
2088- pipeline: typeof TextClassificationPipeline;
2089- model: typeof AutoModelForSequenceClassification;
2090- default: {
2091- model: string;
2092- };
2093- type: string;
2369+ "text-classification": {
2370+ tokenizer: typeof AutoTokenizer;
2371+ pipeline: typeof TextClassificationPipeline;
2372+ model: typeof AutoModelForSequenceClassification;
2373+ default: {
2374+ model: string;
20942375 };
2095- "token-classification": {
2096- tokenizer: typeof AutoTokenizer;
2097- pipeline: typeof TokenClassificationPipeline;
2098- model: typeof AutoModelForTokenClassification;
2099- default: {
2100- model: string;
2101- };
2102- type: string;
2376+ type: string;
2377+ };
2378+ "token-classification": {
2379+ tokenizer: typeof AutoTokenizer;
2380+ pipeline: typeof TokenClassificationPipeline;
2381+ model: typeof AutoModelForTokenClassification;
2382+ default: {
2383+ model: string;
21032384 };
2104- "question-answering": {
2105- tokenizer: typeof AutoTokenizer;
2106- pipeline: typeof QuestionAnsweringPipeline;
2107- model: typeof AutoModelForQuestionAnswering;
2108- default: {
2109- model: string;
2110- };
2111- type: string;
2385+ type: string;
2386+ };
2387+ "question-answering": {
2388+ tokenizer: typeof AutoTokenizer;
2389+ pipeline: typeof QuestionAnsweringPipeline;
2390+ model: typeof AutoModelForQuestionAnswering;
2391+ default: {
2392+ model: string;
21122393 };
2113- "fill-mask": {
2114- tokenizer: typeof AutoTokenizer;
2115- pipeline: typeof FillMaskPipeline;
2116- model: typeof AutoModelForMaskedLM;
2117- default: {
2118- model: string;
2119- };
2120- type: string;
2394+ type: string;
2395+ };
2396+ "fill-mask": {
2397+ tokenizer: typeof AutoTokenizer;
2398+ pipeline: typeof FillMaskPipeline;
2399+ model: typeof AutoModelForMaskedLM;
2400+ default: {
2401+ model: string;
21212402 };
2122- summarization: {
2123- tokenizer: typeof AutoTokenizer;
2124- pipeline: typeof SummarizationPipeline;
2125- model: typeof AutoModelForSeq2SeqLM;
2126- default: {
2127- model: string;
2128- };
2129- type: string;
2403+ type: string;
2404+ };
2405+ summarization: {
2406+ tokenizer: typeof AutoTokenizer;
2407+ pipeline: typeof SummarizationPipeline;
2408+ model: typeof AutoModelForSeq2SeqLM;
2409+ default: {
2410+ model: string;
21302411 };
2131- translation: {
2132- tokenizer: typeof AutoTokenizer;
2133- pipeline: typeof TranslationPipeline;
2134- model: typeof AutoModelForSeq2SeqLM;
2135- default: {
2136- model: string;
2137- };
2138- type: string;
2412+ type: string;
2413+ };
2414+ translation: {
2415+ tokenizer: typeof AutoTokenizer;
2416+ pipeline: typeof TranslationPipeline;
2417+ model: typeof AutoModelForSeq2SeqLM;
2418+ default: {
2419+ model: string;
21392420 };
2140- "text2text-generation": {
2141- tokenizer: typeof AutoTokenizer;
2142- pipeline: typeof Text2TextGenerationPipeline;
2143- model: typeof AutoModelForSeq2SeqLM;
2144- default: {
2145- model: string;
2146- };
2147- type: string;
2421+ type: string;
2422+ };
2423+ "text2text-generation": {
2424+ tokenizer: typeof AutoTokenizer;
2425+ pipeline: typeof Text2TextGenerationPipeline;
2426+ model: typeof AutoModelForSeq2SeqLM;
2427+ default: {
2428+ model: string;
21482429 };
2149- "text-generation": {
2150- tokenizer: typeof AutoTokenizer;
2151- pipeline: typeof TextGenerationPipeline;
2152- model: typeof AutoModelForCausalLM;
2153- default: {
2154- model: string;
2155- };
2156- type: string;
2430+ type: string;
2431+ };
2432+ "text-generation": {
2433+ tokenizer: typeof AutoTokenizer;
2434+ pipeline: typeof TextGenerationPipeline;
2435+ model: typeof AutoModelForCausalLM;
2436+ default: {
2437+ model: string;
21572438 };
2158- "zero-shot-classification": {
2159- tokenizer: typeof AutoTokenizer;
2160- pipeline: typeof ZeroShotClassificationPipeline;
2161- model: typeof AutoModelForSequenceClassification;
2162- default: {
2163- model: string;
2164- };
2165- type: string;
2439+ type: string;
2440+ };
2441+ "zero-shot-classification": {
2442+ tokenizer: typeof AutoTokenizer;
2443+ pipeline: typeof ZeroShotClassificationPipeline;
2444+ model: typeof AutoModelForSequenceClassification;
2445+ default: {
2446+ model: string;
21662447 };
2167- "audio-classification": {
2168- pipeline: typeof AudioClassificationPipeline;
2169- model: typeof AutoModelForAudioClassification;
2170- processor: typeof AutoProcessor;
2171- default: {
2172- model: string;
2173- };
2174- type: string;
2448+ type: string;
2449+ };
2450+ "audio-classification": {
2451+ pipeline: typeof AudioClassificationPipeline;
2452+ model: typeof AutoModelForAudioClassification;
2453+ processor: typeof AutoProcessor;
2454+ default: {
2455+ model: string;
21752456 };
2176- "zero-shot-audio-classification": {
2177- tokenizer: typeof AutoTokenizer;
2178- pipeline: typeof ZeroShotAudioClassificationPipeline;
2179- model: typeof AutoModel;
2180- processor: typeof AutoProcessor;
2181- default: {
2182- model: string;
2183- };
2184- type: string;
2457+ type: string;
2458+ };
2459+ "zero-shot-audio-classification": {
2460+ tokenizer: typeof AutoTokenizer;
2461+ pipeline: typeof ZeroShotAudioClassificationPipeline;
2462+ model: typeof AutoModel;
2463+ processor: typeof AutoProcessor;
2464+ default: {
2465+ model: string;
21852466 };
2186- "automatic-speech-recognition": {
2187- tokenizer: typeof AutoTokenizer;
2188- pipeline: typeof AutomaticSpeechRecognitionPipeline;
2189- model: (typeof AutoModelForSpeechSeq2Seq)[];
2190- processor: typeof AutoProcessor;
2191- default: {
2192- model: string;
2193- };
2194- type: string;
2467+ type: string;
2468+ };
2469+ "automatic-speech-recognition": {
2470+ tokenizer: typeof AutoTokenizer;
2471+ pipeline: typeof AutomaticSpeechRecognitionPipeline;
2472+ model: (typeof AutoModelForSpeechSeq2Seq)[];
2473+ processor: typeof AutoProcessor;
2474+ default: {
2475+ model: string;
21952476 };
2196- "text-to-audio": {
2197- tokenizer: typeof AutoTokenizer;
2198- pipeline: typeof TextToAudioPipeline;
2199- model: (typeof AutoModelForTextToSpectrogram | typeof AutoModelForTextToWaveform)[];
2200- processor: (typeof AutoProcessor)[];
2201- default: {
2202- model: string;
2203- };
2204- type: string;
2477+ type: string;
2478+ };
2479+ "text-to-audio": {
2480+ tokenizer: typeof AutoTokenizer;
2481+ pipeline: typeof TextToAudioPipeline;
2482+ model: (
2483+ | typeof AutoModelForTextToSpectrogram
2484+ | typeof AutoModelForTextToWaveform
2485+ )[];
2486+ processor: (typeof AutoProcessor)[];
2487+ default: {
2488+ model: string;
22052489 };
2206- "image-to-text": {
2207- tokenizer: typeof AutoTokenizer;
2208- pipeline: typeof ImageToTextPipeline;
2209- model: typeof AutoModelForVision2Seq;
2210- processor: typeof AutoProcessor;
2211- default: {
2212- model: string;
2213- };
2214- type: string;
2490+ type: string;
2491+ };
2492+ "image-to-text": {
2493+ tokenizer: typeof AutoTokenizer;
2494+ pipeline: typeof ImageToTextPipeline;
2495+ model: typeof AutoModelForVision2Seq;
2496+ processor: typeof AutoProcessor;
2497+ default: {
2498+ model: string;
22152499 };
2216- "image-classification": {
2217- pipeline: typeof ImageClassificationPipeline;
2218- model: typeof AutoModelForImageClassification;
2219- processor: typeof AutoProcessor;
2220- default: {
2221- model: string;
2222- };
2223- type: string;
2500+ type: string;
2501+ };
2502+ "image-classification": {
2503+ pipeline: typeof ImageClassificationPipeline;
2504+ model: typeof AutoModelForImageClassification;
2505+ processor: typeof AutoProcessor;
2506+ default: {
2507+ model: string;
22242508 };
2225- "image-segmentation": {
2226- pipeline: typeof ImageSegmentationPipeline;
2227- model: (typeof AutoModelForImageSegmentation)[];
2228- processor: typeof AutoProcessor;
2229- default: {
2230- model: string;
2231- };
2232- type: string;
2509+ type: string;
2510+ };
2511+ "image-segmentation": {
2512+ pipeline: typeof ImageSegmentationPipeline;
2513+ model: (typeof AutoModelForImageSegmentation)[];
2514+ processor: typeof AutoProcessor;
2515+ default: {
2516+ model: string;
22332517 };
2234- "zero-shot-image-classification": {
2235- tokenizer: typeof AutoTokenizer;
2236- pipeline: typeof ZeroShotImageClassificationPipeline;
2237- model: typeof AutoModel;
2238- processor: typeof AutoProcessor;
2239- default: {
2240- model: string;
2241- };
2242- type: string;
2518+ type: string;
2519+ };
2520+ "zero-shot-image-classification": {
2521+ tokenizer: typeof AutoTokenizer;
2522+ pipeline: typeof ZeroShotImageClassificationPipeline;
2523+ model: typeof AutoModel;
2524+ processor: typeof AutoProcessor;
2525+ default: {
2526+ model: string;
22432527 };
2244- "object-detection": {
2245- pipeline: typeof ObjectDetectionPipeline;
2246- model: typeof AutoModelForObjectDetection;
2247- processor: typeof AutoProcessor;
2248- default: {
2249- model: string;
2250- };
2251- type: string;
2528+ type: string;
2529+ };
2530+ "object-detection": {
2531+ pipeline: typeof ObjectDetectionPipeline;
2532+ model: typeof AutoModelForObjectDetection;
2533+ processor: typeof AutoProcessor;
2534+ default: {
2535+ model: string;
22522536 };
2253- "zero-shot-object-detection": {
2254- tokenizer: typeof AutoTokenizer;
2255- pipeline: typeof ZeroShotObjectDetectionPipeline;
2256- model: typeof AutoModelForZeroShotObjectDetection;
2257- processor: typeof AutoProcessor;
2258- default: {
2259- model: string;
2260- };
2261- type: string;
2537+ type: string;
2538+ };
2539+ "zero-shot-object-detection": {
2540+ tokenizer: typeof AutoTokenizer;
2541+ pipeline: typeof ZeroShotObjectDetectionPipeline;
2542+ model: typeof AutoModelForZeroShotObjectDetection;
2543+ processor: typeof AutoProcessor;
2544+ default: {
2545+ model: string;
22622546 };
2263- "document-question-answering": {
2264- tokenizer: typeof AutoTokenizer;
2265- pipeline: typeof DocumentQuestionAnsweringPipeline;
2266- model: typeof AutoModelForDocumentQuestionAnswering;
2267- processor: typeof AutoProcessor;
2268- default: {
2269- model: string;
2270- };
2271- type: string;
2547+ type: string;
2548+ };
2549+ "document-question-answering": {
2550+ tokenizer: typeof AutoTokenizer;
2551+ pipeline: typeof DocumentQuestionAnsweringPipeline;
2552+ model: typeof AutoModelForDocumentQuestionAnswering;
2553+ processor: typeof AutoProcessor;
2554+ default: {
2555+ model: string;
22722556 };
2273- "image-to-image": {
2274- pipeline: typeof ImageToImagePipeline;
2275- model: typeof AutoModelForImageToImage;
2276- processor: typeof AutoProcessor;
2277- default: {
2278- model: string;
2279- };
2280- type: string;
2557+ type: string;
2558+ };
2559+ "image-to-image": {
2560+ pipeline: typeof ImageToImagePipeline;
2561+ model: typeof AutoModelForImageToImage;
2562+ processor: typeof AutoProcessor;
2563+ default: {
2564+ model: string;
22812565 };
2282- "depth-estimation": {
2283- pipeline: typeof DepthEstimationPipeline;
2284- model: typeof AutoModelForDepthEstimation;
2285- processor: typeof AutoProcessor;
2286- default: {
2287- model: string;
2288- };
2289- type: string;
2566+ type: string;
2567+ };
2568+ "depth-estimation": {
2569+ pipeline: typeof DepthEstimationPipeline;
2570+ model: typeof AutoModelForDepthEstimation;
2571+ processor: typeof AutoProcessor;
2572+ default: {
2573+ model: string;
22902574 };
2291- "feature-extraction": {
2292- tokenizer: typeof AutoTokenizer;
2293- pipeline: typeof FeatureExtractionPipeline;
2294- model: typeof AutoModel;
2295- default: {
2296- model: string;
2297- };
2298- type: string;
2575+ type: string;
2576+ };
2577+ "feature-extraction": {
2578+ tokenizer: typeof AutoTokenizer;
2579+ pipeline: typeof FeatureExtractionPipeline;
2580+ model: typeof AutoModel;
2581+ default: {
2582+ model: string;
22992583 };
2584+ type: string;
2585+ };
23002586 }>;
23012587 declare const TASK_ALIASES: Readonly<{
2302- "sentiment-analysis": "text-classification";
2303- ner: "token-classification";
2304- asr: "automatic-speech-recognition";
2305- "text-to-speech": "text-to-audio";
2306- embeddings: "feature-extraction";
2588+ "sentiment-analysis": "text-classification";
2589+ ner: "token-classification";
2590+ asr: "automatic-speech-recognition";
2591+ "text-to-speech": "text-to-audio";
2592+ embeddings: "feature-extraction";
23072593 }>;
2308-import { AutoTokenizer } from './tokenizers.js';
2309-import { AutoModelForSequenceClassification } from './models.js';
2310-import { AutoModelForTokenClassification } from './models.js';
2311-import { AutoModelForQuestionAnswering } from './models.js';
2312-import { AutoModelForMaskedLM } from './models.js';
2313-import { AutoModelForSeq2SeqLM } from './models.js';
2314-import { AutoModelForCausalLM } from './models.js';
2315-import { AutoModelForAudioClassification } from './models.js';
2316-import { AutoProcessor } from './processors.js';
2317-import { AutoModel } from './models.js';
2318-import { AutoModelForSpeechSeq2Seq } from './models.js';
2319-import { AutoModelForTextToSpectrogram } from './models.js';
2320-import { AutoModelForTextToWaveform } from './models.js';
2321-import { AutoModelForVision2Seq } from './models.js';
2322-import { AutoModelForImageClassification } from './models.js';
2323-import { AutoModelForImageSegmentation } from './models.js';
2324-import { AutoModelForObjectDetection } from './models.js';
2325-import { AutoModelForZeroShotObjectDetection } from './models.js';
2326-import { AutoModelForDocumentQuestionAnswering } from './models.js';
2327-import { AutoModelForImageToImage } from './models.js';
2328-import { AutoModelForDepthEstimation } from './models.js';
2594+import { AutoTokenizer } from "./tokenizers.js";
2595+import { AutoModelForSequenceClassification } from "./models.js";
2596+import { AutoModelForTokenClassification } from "./models.js";
2597+import { AutoModelForQuestionAnswering } from "./models.js";
2598+import { AutoModelForMaskedLM } from "./models.js";
2599+import { AutoModelForSeq2SeqLM } from "./models.js";
2600+import { AutoModelForCausalLM } from "./models.js";
2601+import { AutoModelForAudioClassification } from "./models.js";
2602+import { AutoProcessor } from "./processors.js";
2603+import { AutoModel } from "./models.js";
2604+import { AutoModelForSpeechSeq2Seq } from "./models.js";
2605+import { AutoModelForTextToSpectrogram } from "./models.js";
2606+import { AutoModelForTextToWaveform } from "./models.js";
2607+import { AutoModelForVision2Seq } from "./models.js";
2608+import { AutoModelForImageClassification } from "./models.js";
2609+import { AutoModelForImageSegmentation } from "./models.js";
2610+import { AutoModelForObjectDetection } from "./models.js";
2611+import { AutoModelForZeroShotObjectDetection } from "./models.js";
2612+import { AutoModelForDocumentQuestionAnswering } from "./models.js";
2613+import { AutoModelForImageToImage } from "./models.js";
2614+import { AutoModelForDepthEstimation } from "./models.js";
23292615 export {};
2330-//# sourceMappingURL=pipelines.d.ts.map
No newline at the end of the file
2616+//# sourceMappingURL=pipelines.d.ts.map
modified core/vendor/modules/@xenova/transformers/types/processors.d.ts +699 −589
@@ -1,6 +1,6 @@
11 declare const FeatureExtractor_base: new () => {
2- (...args: any[]): any;
3- _call(...args: any[]): any;
2+ (...args: any[]): any;
3+ _call(...args: any[]): any;
44 };
55 /**
66 * Base class for feature extractors.
@@ -8,13 +8,13 @@
88 * @extends Callable
99 */
1010 export class FeatureExtractor extends FeatureExtractor_base {
11- /**
12- * Constructs a new FeatureExtractor instance.
13- *
14- * @param {Object} config The configuration for the feature extractor.
15- */
16- constructor(config: any);
17- config: any;
11+ /**
12+ * Constructs a new FeatureExtractor instance.
13+ *
14+ * @param {Object} config The configuration for the feature extractor.
15+ */
16+ constructor(config: any);
17+ config: any;
1818 }
1919 /**
2020 * @typedef {object} ImageFeatureExtractorResult
@@ -28,207 +28,228 @@
2828 * @extends FeatureExtractor
2929 */
3030 export class ImageFeatureExtractor extends FeatureExtractor {
31- /**
32- * Constructs a new ImageFeatureExtractor instance.
33- *
34- * @param {Object} config The configuration for the feature extractor.
35- * @param {number[]} config.image_mean The mean values for image normalization.
36- * @param {number[]} config.image_std The standard deviation values for image normalization.
37- * @param {boolean} config.do_rescale Whether to rescale the image pixel values to the [0,1] range.
38- * @param {number} config.rescale_factor The factor to use for rescaling the image pixel values.
39- * @param {boolean} config.do_normalize Whether to normalize the image pixel values.
40- * @param {boolean} config.do_resize Whether to resize the image.
41- * @param {number} config.resample What method to use for resampling.
42- * @param {number} config.size The size to resize the image to.
43- */
44- constructor(config: {
45- image_mean: number[];
46- image_std: number[];
47- do_rescale: boolean;
48- rescale_factor: number;
49- do_normalize: boolean;
50- do_resize: boolean;
51- resample: number;
52- size: number;
53- });
54- image_mean: any;
55- image_std: any;
56- resample: any;
57- do_rescale: any;
58- rescale_factor: any;
59- do_normalize: any;
60- do_resize: any;
61- do_thumbnail: any;
62- size: any;
63- size_divisibility: any;
64- do_center_crop: any;
65- crop_size: any;
66- do_convert_rgb: any;
67- do_crop_margin: any;
68- pad_size: any;
69- do_pad: any;
70- /**
71- * Resize the image to make a thumbnail. The image is resized so that no dimension is larger than any
72- * corresponding dimension of the specified size.
73- * @param {RawImage} image The image to be resized.
74- * @param {{height:number, width:number}} size The size `{"height": h, "width": w}` to resize the image to.
75- * @param {string | 0 | 1 | 2 | 3 | 4 | 5} [resample=2] The resampling filter to use.
76- * @returns {Promise<RawImage>} The resized image.
77- */
78- thumbnail(image: RawImage, size: {
79- height: number;
80- width: number;
81- }, resample?: string | 0 | 1 | 2 | 3 | 4 | 5): Promise<RawImage>;
82- /**
83- * Crops the margin of the image. Gray pixels are considered margin (i.e., pixels with a value below the threshold).
84- * @param {RawImage} image The image to be cropped.
85- * @param {number} gray_threshold Value below which pixels are considered to be gray.
86- * @returns {Promise<RawImage>} The cropped image.
87- */
88- crop_margin(image: RawImage, gray_threshold?: number): Promise<RawImage>;
89- /**
90- * Pad the image by a certain amount.
91- * @param {Float32Array} pixelData The pixel data to pad.
92- * @param {number[]} imgDims The dimensions of the image.
93- * @param {{width:number; height:number}|number} padSize The dimensions of the padded image.
94- * @param {Object} options The options for padding.
95- * @param {'constant'|'symmetric'} [options.mode='constant'] The type of padding to add.
96- * @param {boolean} [options.center=false] Whether to center the image.
97- * @param {number} [options.constant_values=0] The constant value to use for padding.
98- * @returns {[Float32Array, number[]]} The padded pixel data and image dimensions.
99- */
100- pad_image(pixelData: Float32Array, imgDims: number[], padSize: {
101- width: number;
102- height: number;
103- } | number, { mode, center, constant_values, }?: {
104- mode?: 'constant' | 'symmetric';
105- center?: boolean;
106- constant_values?: number;
107- }): [Float32Array, number[]];
108- /**
109- * Rescale the image' pixel values by `this.rescale_factor`.
110- * @param {Float32Array} pixelData The pixel data to rescale.
111- * @returns {void}
112- */
113- rescale(pixelData: Float32Array): void;
114- /**
115- * Find the target (width, height) dimension of the output image after
116- * resizing given the input image and the desired size.
117- * @param {RawImage} image The image to resize.
118- * @param {any} size The size to use for resizing the image.
119- * @returns {[number, number]} The target (width, height) dimension of the output image after resizing.
120- */
121- get_resize_output_image_size(image: RawImage, size: any): [number, number];
122- /**
123- * Resizes the image.
124- * @param {RawImage} image The image to resize.
125- * @returns {Promise<RawImage>} The resized image.
31+ /**
32+ * Constructs a new ImageFeatureExtractor instance.
33+ *
34+ * @param {Object} config The configuration for the feature extractor.
35+ * @param {number[]} config.image_mean The mean values for image normalization.
36+ * @param {number[]} config.image_std The standard deviation values for image normalization.
37+ * @param {boolean} config.do_rescale Whether to rescale the image pixel values to the [0,1] range.
38+ * @param {number} config.rescale_factor The factor to use for rescaling the image pixel values.
39+ * @param {boolean} config.do_normalize Whether to normalize the image pixel values.
40+ * @param {boolean} config.do_resize Whether to resize the image.
41+ * @param {number} config.resample What method to use for resampling.
42+ * @param {number} config.size The size to resize the image to.
43+ */
44+ constructor(config: {
45+ image_mean: number[];
46+ image_std: number[];
47+ do_rescale: boolean;
48+ rescale_factor: number;
49+ do_normalize: boolean;
50+ do_resize: boolean;
51+ resample: number;
52+ size: number;
53+ });
54+ image_mean: any;
55+ image_std: any;
56+ resample: any;
57+ do_rescale: any;
58+ rescale_factor: any;
59+ do_normalize: any;
60+ do_resize: any;
61+ do_thumbnail: any;
62+ size: any;
63+ size_divisibility: any;
64+ do_center_crop: any;
65+ crop_size: any;
66+ do_convert_rgb: any;
67+ do_crop_margin: any;
68+ pad_size: any;
69+ do_pad: any;
70+ /**
71+ * Resize the image to make a thumbnail. The image is resized so that no dimension is larger than any
72+ * corresponding dimension of the specified size.
73+ * @param {RawImage} image The image to be resized.
74+ * @param {{height:number, width:number}} size The size `{"height": h, "width": w}` to resize the image to.
75+ * @param {string | 0 | 1 | 2 | 3 | 4 | 5} [resample=2] The resampling filter to use.
76+ * @returns {Promise<RawImage>} The resized image.
77+ */
78+ thumbnail(
79+ image: RawImage,
80+ size: {
81+ height: number;
82+ width: number;
83+ },
84+ resample?: string | 0 | 1 | 2 | 3 | 4 | 5,
85+ ): Promise<RawImage>;
86+ /**
87+ * Crops the margin of the image. Gray pixels are considered margin (i.e., pixels with a value below the threshold).
88+ * @param {RawImage} image The image to be cropped.
89+ * @param {number} gray_threshold Value below which pixels are considered to be gray.
90+ * @returns {Promise<RawImage>} The cropped image.
91+ */
92+ crop_margin(image: RawImage, gray_threshold?: number): Promise<RawImage>;
93+ /**
94+ * Pad the image by a certain amount.
95+ * @param {Float32Array} pixelData The pixel data to pad.
96+ * @param {number[]} imgDims The dimensions of the image.
97+ * @param {{width:number; height:number}|number} padSize The dimensions of the padded image.
98+ * @param {Object} options The options for padding.
99+ * @param {'constant'|'symmetric'} [options.mode='constant'] The type of padding to add.
100+ * @param {boolean} [options.center=false] Whether to center the image.
101+ * @param {number} [options.constant_values=0] The constant value to use for padding.
102+ * @returns {[Float32Array, number[]]} The padded pixel data and image dimensions.
103+ */
104+ pad_image(
105+ pixelData: Float32Array,
106+ imgDims: number[],
107+ padSize:
108+ | {
109+ width: number;
110+ height: number;
111+ }
112+ | number,
113+ {
114+ mode,
115+ center,
116+ constant_values,
117+ }?: {
118+ mode?: "constant" | "symmetric";
119+ center?: boolean;
120+ constant_values?: number;
121+ },
122+ ): [Float32Array, number[]];
123+ /**
124+ * Rescale the image' pixel values by `this.rescale_factor`.
125+ * @param {Float32Array} pixelData The pixel data to rescale.
126+ * @returns {void}
127+ */
128+ rescale(pixelData: Float32Array): void;
129+ /**
130+ * Find the target (width, height) dimension of the output image after
131+ * resizing given the input image and the desired size.
132+ * @param {RawImage} image The image to resize.
133+ * @param {any} size The size to use for resizing the image.
134+ * @returns {[number, number]} The target (width, height) dimension of the output image after resizing.
135+ */
136+ get_resize_output_image_size(image: RawImage, size: any): [number, number];
137+ /**
138+ * Resizes the image.
139+ * @param {RawImage} image The image to resize.
140+ * @returns {Promise<RawImage>} The resized image.
141+ */
142+ resize(image: RawImage): Promise<RawImage>;
143+ /**
144+ * @typedef {object} PreprocessedImage
145+ * @property {HeightWidth} original_size The original size of the image.
146+ * @property {HeightWidth} reshaped_input_size The reshaped input size of the image.
147+ * @property {Tensor} pixel_values The pixel values of the preprocessed image.
148+ */
149+ /**
150+ * Preprocesses the given image.
151+ *
152+ * @param {RawImage} image The image to preprocess.
153+ * @param {Object} overrides The overrides for the preprocessing options.
154+ * @returns {Promise<PreprocessedImage>} The preprocessed image.
155+ */
156+ preprocess(
157+ image: RawImage,
158+ { do_normalize, do_pad, do_convert_rgb, do_convert_grayscale }?: any,
159+ ): Promise<{
160+ /**
161+ * The original size of the image.
162+ */
163+ original_size: HeightWidth;
164+ /**
165+ * The reshaped input size of the image.
166+ */
167+ reshaped_input_size: HeightWidth;
168+ /**
169+ * The pixel values of the preprocessed image.
126170 */
127- resize(image: RawImage): Promise<RawImage>;
128- /**
129- * @typedef {object} PreprocessedImage
130- * @property {HeightWidth} original_size The original size of the image.
131- * @property {HeightWidth} reshaped_input_size The reshaped input size of the image.
132- * @property {Tensor} pixel_values The pixel values of the preprocessed image.
133- */
134- /**
135- * Preprocesses the given image.
136- *
137- * @param {RawImage} image The image to preprocess.
138- * @param {Object} overrides The overrides for the preprocessing options.
139- * @returns {Promise<PreprocessedImage>} The preprocessed image.
140- */
141- preprocess(image: RawImage, { do_normalize, do_pad, do_convert_rgb, do_convert_grayscale, }?: any): Promise<{
142- /**
143- * The original size of the image.
144- */
145- original_size: HeightWidth;
146- /**
147- * The reshaped input size of the image.
148- */
149- reshaped_input_size: HeightWidth;
150- /**
151- * The pixel values of the preprocessed image.
152- */
153- pixel_values: Tensor;
154- }>;
155- /**
156- * Calls the feature extraction process on an array of images,
157- * preprocesses each image, and concatenates the resulting
158- * features into a single Tensor.
159- * @param {RawImage[]} images The image(s) to extract features from.
160- * @param {...any} args Additional arguments.
161- * @returns {Promise<ImageFeatureExtractorResult>} An object containing the concatenated pixel values (and other metadata) of the preprocessed images.
162- */
163- _call(images: RawImage[], ...args: any[]): Promise<ImageFeatureExtractorResult>;
171+ pixel_values: Tensor;
172+ }>;
173+ /**
174+ * Calls the feature extraction process on an array of images,
175+ * preprocesses each image, and concatenates the resulting
176+ * features into a single Tensor.
177+ * @param {RawImage[]} images The image(s) to extract features from.
178+ * @param {...any} args Additional arguments.
179+ * @returns {Promise<ImageFeatureExtractorResult>} An object containing the concatenated pixel values (and other metadata) of the preprocessed images.
180+ */
181+ _call(
182+ images: RawImage[],
183+ ...args: any[]
184+ ): Promise<ImageFeatureExtractorResult>;
164185 }
165186 export class SegformerFeatureExtractor extends ImageFeatureExtractor {
166- /**
167- * Converts the output of `SegformerForSemanticSegmentation` into semantic segmentation maps.
168- * @param {*} outputs Raw outputs of the model.
169- * @param {number[][]} [target_sizes=null] List of tuples corresponding to the requested final size
170- * (height, width) of each prediction. If unset, predictions will not be resized.
171- * @returns {{segmentation: Tensor; labels: number[]}[]} The semantic segmentation maps.
172- */
173- post_process_semantic_segmentation(outputs: any, target_sizes?: number[][]): {
174- segmentation: Tensor;
175- labels: number[];
176- }[];
177-}
178-export class BitImageProcessor extends ImageFeatureExtractor {
179-}
180-export class DPTFeatureExtractor extends ImageFeatureExtractor {
181-}
182-export class GLPNFeatureExtractor extends ImageFeatureExtractor {
183-}
184-export class CLIPFeatureExtractor extends ImageFeatureExtractor {
185-}
186-export class ChineseCLIPFeatureExtractor extends ImageFeatureExtractor {
187-}
188-export class SiglipImageProcessor extends ImageFeatureExtractor {
189-}
187+ /**
188+ * Converts the output of `SegformerForSemanticSegmentation` into semantic segmentation maps.
189+ * @param {*} outputs Raw outputs of the model.
190+ * @param {number[][]} [target_sizes=null] List of tuples corresponding to the requested final size
191+ * (height, width) of each prediction. If unset, predictions will not be resized.
192+ * @returns {{segmentation: Tensor; labels: number[]}[]} The semantic segmentation maps.
193+ */
194+ post_process_semantic_segmentation(
195+ outputs: any,
196+ target_sizes?: number[][],
197+ ): {
198+ segmentation: Tensor;
199+ labels: number[];
200+ }[];
201+}
202+export class BitImageProcessor extends ImageFeatureExtractor {}
203+export class DPTFeatureExtractor extends ImageFeatureExtractor {}
204+export class GLPNFeatureExtractor extends ImageFeatureExtractor {}
205+export class CLIPFeatureExtractor extends ImageFeatureExtractor {}
206+export class ChineseCLIPFeatureExtractor extends ImageFeatureExtractor {}
207+export class SiglipImageProcessor extends ImageFeatureExtractor {}
190208 export class ConvNextFeatureExtractor extends ImageFeatureExtractor {
191- constructor(config: any);
192- /**
193- * Percentage of the image to crop. Only has an effect if this.size < 384.
194- */
195- crop_pct: any;
196- resize(image: any): Promise<any>;
197-}
198-export class ConvNextImageProcessor extends ConvNextFeatureExtractor {
199-}
200-export class ViTFeatureExtractor extends ImageFeatureExtractor {
201-}
202-export class ViTImageProcessor extends ImageFeatureExtractor {
203-}
204-export class MobileViTFeatureExtractor extends ImageFeatureExtractor {
205-}
209+ constructor(config: any);
210+ /**
211+ * Percentage of the image to crop. Only has an effect if this.size < 384.
212+ */
213+ crop_pct: any;
214+ resize(image: any): Promise<any>;
215+}
216+export class ConvNextImageProcessor extends ConvNextFeatureExtractor {}
217+export class ViTFeatureExtractor extends ImageFeatureExtractor {}
218+export class ViTImageProcessor extends ImageFeatureExtractor {}
219+export class MobileViTFeatureExtractor extends ImageFeatureExtractor {}
206220 export class OwlViTFeatureExtractor extends ImageFeatureExtractor {
207- /**
208- * Post-processes the outputs of the model (for object detection).
209- * @param {Object} outputs The outputs of the model that must be post-processed
210- * @param {Tensor} outputs.logits The logits
211- * @param {Tensor} outputs.pred_boxes The predicted boxes.
212- * @param {number} [threshold=0.5] The threshold to use for the scores.
213- * @param {number[][]} [target_sizes=null] The sizes of the original images.
214- * @param {boolean} [is_zero_shot=false] Whether zero-shot object detection was performed.
215- * @return {Object[]} An array of objects containing the post-processed outputs.
216- * @private
217- */
218- post_process_object_detection(outputs: {
219- logits: Tensor;
220- pred_boxes: Tensor;
221- }, threshold?: number, target_sizes?: number[][], is_zero_shot?: boolean): any[];
222-}
223-export class DeiTFeatureExtractor extends ImageFeatureExtractor {
224-}
225-export class BeitFeatureExtractor extends ImageFeatureExtractor {
226-}
221+ /**
222+ * Post-processes the outputs of the model (for object detection).
223+ * @param {Object} outputs The outputs of the model that must be post-processed
224+ * @param {Tensor} outputs.logits The logits
225+ * @param {Tensor} outputs.pred_boxes The predicted boxes.
226+ * @param {number} [threshold=0.5] The threshold to use for the scores.
227+ * @param {number[][]} [target_sizes=null] The sizes of the original images.
228+ * @param {boolean} [is_zero_shot=false] Whether zero-shot object detection was performed.
229+ * @return {Object[]} An array of objects containing the post-processed outputs.
230+ * @private
231+ */
232+ post_process_object_detection(
233+ outputs: {
234+ logits: Tensor;
235+ pred_boxes: Tensor;
236+ },
237+ threshold?: number,
238+ target_sizes?: number[][],
239+ is_zero_shot?: boolean,
240+ ): any[];
241+}
242+export class DeiTFeatureExtractor extends ImageFeatureExtractor {}
243+export class BeitFeatureExtractor extends ImageFeatureExtractor {}
227244 export class DonutFeatureExtractor extends ImageFeatureExtractor {
228- pad_image(pixelData: any, imgDims: any, padSize: any, options?: {}): [Float32Array, number[]];
229-}
230-export class NougatImageProcessor extends DonutFeatureExtractor {
231-}
245+ pad_image(
246+ pixelData: any,
247+ imgDims: any,
248+ padSize: any,
249+ options?: {},
250+ ): [Float32Array, number[]];
251+}
252+export class NougatImageProcessor extends DonutFeatureExtractor {}
232253 /**
233254 * @typedef {object} DetrFeatureExtractorResultProps
234255 * @property {Tensor} pixel_mask
@@ -240,99 +261,138 @@
240261 * @extends ImageFeatureExtractor
241262 */
242263 export class DetrFeatureExtractor extends ImageFeatureExtractor {
243- /**
244- * Calls the feature extraction process on an array of images, preprocesses
245- * each image, and concatenates the resulting features into a single Tensor.
246- * @param {RawImage[]} images The image(s) to extract features from.
247- * @returns {Promise<DetrFeatureExtractorResult>} An object containing the concatenated pixel values of the preprocessed images.
248- */
249- _call(images: RawImage[]): Promise<DetrFeatureExtractorResult>;
250- /**
251- * Post-processes the outputs of the model (for object detection).
252- * @param {Object} outputs The outputs of the model that must be post-processed
253- * @param {Tensor} outputs.logits The logits
254- * @param {Tensor} outputs.pred_boxes The predicted boxes.
255- * @param {number} [threshold=0.5] The threshold to use for the scores.
256- * @param {number[][]} [target_sizes=null] The sizes of the original images.
257- * @param {boolean} [is_zero_shot=false] Whether zero-shot object detection was performed.
258- * @return {Object[]} An array of objects containing the post-processed outputs.
259- * @private
260- */
261- post_process_object_detection(outputs: {
262- logits: Tensor;
263- pred_boxes: Tensor;
264- }, threshold?: number, target_sizes?: number[][], is_zero_shot?: boolean): any[];
265- /**
266- * Binarize the given masks using `object_mask_threshold`, it returns the associated values of `masks`, `scores` and `labels`.
267- * @param {Tensor} class_logits The class logits.
268- * @param {Tensor} mask_logits The mask logits.
269- * @param {number} object_mask_threshold A number between 0 and 1 used to binarize the masks.
270- * @param {number} num_labels The number of labels.
271- * @returns {[Tensor[], number[], number[]]} The binarized masks, the scores, and the labels.
272- */
273- remove_low_and_no_objects(class_logits: Tensor, mask_logits: Tensor, object_mask_threshold: number, num_labels: number): [Tensor[], number[], number[]];
274- /**
275- * Checks whether the segment is valid or not.
276- * @param {Int32Array} mask_labels Labels for each pixel in the mask.
277- * @param {Tensor[]} mask_probs Probabilities for each pixel in the masks.
278- * @param {number} k The class id of the segment.
279- * @param {number} mask_threshold The mask threshold.
280- * @param {number} overlap_mask_area_threshold The overlap mask area threshold.
281- * @returns {[boolean, number[]]} Whether the segment is valid or not, and the indices of the valid labels.
282- */
283- check_segment_validity(mask_labels: Int32Array, mask_probs: Tensor[], k: number, mask_threshold?: number, overlap_mask_area_threshold?: number): [boolean, number[]];
284- /**
285- * Computes the segments.
286- * @param {Tensor[]} mask_probs The mask probabilities.
287- * @param {number[]} pred_scores The predicted scores.
288- * @param {number[]} pred_labels The predicted labels.
289- * @param {number} mask_threshold The mask threshold.
290- * @param {number} overlap_mask_area_threshold The overlap mask area threshold.
291- * @param {Set<number>} label_ids_to_fuse The label ids to fuse.
292- * @param {number[]} target_size The target size of the image.
293- * @returns {[Tensor, Array<{id: number, label_id: number, score: number}>]} The computed segments.
294- */
295- compute_segments(mask_probs: Tensor[], pred_scores: number[], pred_labels: number[], mask_threshold: number, overlap_mask_area_threshold: number, label_ids_to_fuse?: Set<number>, target_size?: number[]): [Tensor, Array<{
296- id: number;
297- label_id: number;
298- score: number;
299- }>];
300- /**
301- * Post-process the model output to generate the final panoptic segmentation.
302- * @param {*} outputs The model output to post process
303- * @param {number} [threshold=0.5] The probability score threshold to keep predicted instance masks.
304- * @param {number} [mask_threshold=0.5] Threshold to use when turning the predicted masks into binary values.
305- * @param {number} [overlap_mask_area_threshold=0.8] The overlap mask area threshold to merge or discard small disconnected parts within each binary instance mask.
306- * @param {Set<number>} [label_ids_to_fuse=null] The labels in this state will have all their instances be fused together.
307- * @param {number[][]} [target_sizes=null] The target sizes to resize the masks to.
308- * @returns {Array<{ segmentation: Tensor, segments_info: Array<{id: number, label_id: number, score: number}>}>}
309- */
310- post_process_panoptic_segmentation(outputs: any, threshold?: number, mask_threshold?: number, overlap_mask_area_threshold?: number, label_ids_to_fuse?: Set<number>, target_sizes?: number[][]): Array<{
311- segmentation: Tensor;
312- segments_info: Array<{
313- id: number;
314- label_id: number;
315- score: number;
316- }>;
264+ /**
265+ * Calls the feature extraction process on an array of images, preprocesses
266+ * each image, and concatenates the resulting features into a single Tensor.
267+ * @param {RawImage[]} images The image(s) to extract features from.
268+ * @returns {Promise<DetrFeatureExtractorResult>} An object containing the concatenated pixel values of the preprocessed images.
269+ */
270+ _call(images: RawImage[]): Promise<DetrFeatureExtractorResult>;
271+ /**
272+ * Post-processes the outputs of the model (for object detection).
273+ * @param {Object} outputs The outputs of the model that must be post-processed
274+ * @param {Tensor} outputs.logits The logits
275+ * @param {Tensor} outputs.pred_boxes The predicted boxes.
276+ * @param {number} [threshold=0.5] The threshold to use for the scores.
277+ * @param {number[][]} [target_sizes=null] The sizes of the original images.
278+ * @param {boolean} [is_zero_shot=false] Whether zero-shot object detection was performed.
279+ * @return {Object[]} An array of objects containing the post-processed outputs.
280+ * @private
281+ */
282+ post_process_object_detection(
283+ outputs: {
284+ logits: Tensor;
285+ pred_boxes: Tensor;
286+ },
287+ threshold?: number,
288+ target_sizes?: number[][],
289+ is_zero_shot?: boolean,
290+ ): any[];
291+ /**
292+ * Binarize the given masks using `object_mask_threshold`, it returns the associated values of `masks`, `scores` and `labels`.
293+ * @param {Tensor} class_logits The class logits.
294+ * @param {Tensor} mask_logits The mask logits.
295+ * @param {number} object_mask_threshold A number between 0 and 1 used to binarize the masks.
296+ * @param {number} num_labels The number of labels.
297+ * @returns {[Tensor[], number[], number[]]} The binarized masks, the scores, and the labels.
298+ */
299+ remove_low_and_no_objects(
300+ class_logits: Tensor,
301+ mask_logits: Tensor,
302+ object_mask_threshold: number,
303+ num_labels: number,
304+ ): [Tensor[], number[], number[]];
305+ /**
306+ * Checks whether the segment is valid or not.
307+ * @param {Int32Array} mask_labels Labels for each pixel in the mask.
308+ * @param {Tensor[]} mask_probs Probabilities for each pixel in the masks.
309+ * @param {number} k The class id of the segment.
310+ * @param {number} mask_threshold The mask threshold.
311+ * @param {number} overlap_mask_area_threshold The overlap mask area threshold.
312+ * @returns {[boolean, number[]]} Whether the segment is valid or not, and the indices of the valid labels.
313+ */
314+ check_segment_validity(
315+ mask_labels: Int32Array,
316+ mask_probs: Tensor[],
317+ k: number,
318+ mask_threshold?: number,
319+ overlap_mask_area_threshold?: number,
320+ ): [boolean, number[]];
321+ /**
322+ * Computes the segments.
323+ * @param {Tensor[]} mask_probs The mask probabilities.
324+ * @param {number[]} pred_scores The predicted scores.
325+ * @param {number[]} pred_labels The predicted labels.
326+ * @param {number} mask_threshold The mask threshold.
327+ * @param {number} overlap_mask_area_threshold The overlap mask area threshold.
328+ * @param {Set<number>} label_ids_to_fuse The label ids to fuse.
329+ * @param {number[]} target_size The target size of the image.
330+ * @returns {[Tensor, Array<{id: number, label_id: number, score: number}>]} The computed segments.
331+ */
332+ compute_segments(
333+ mask_probs: Tensor[],
334+ pred_scores: number[],
335+ pred_labels: number[],
336+ mask_threshold: number,
337+ overlap_mask_area_threshold: number,
338+ label_ids_to_fuse?: Set<number>,
339+ target_size?: number[],
340+ ): [
341+ Tensor,
342+ Array<{
343+ id: number;
344+ label_id: number;
345+ score: number;
346+ }>,
347+ ];
348+ /**
349+ * Post-process the model output to generate the final panoptic segmentation.
350+ * @param {*} outputs The model output to post process
351+ * @param {number} [threshold=0.5] The probability score threshold to keep predicted instance masks.
352+ * @param {number} [mask_threshold=0.5] Threshold to use when turning the predicted masks into binary values.
353+ * @param {number} [overlap_mask_area_threshold=0.8] The overlap mask area threshold to merge or discard small disconnected parts within each binary instance mask.
354+ * @param {Set<number>} [label_ids_to_fuse=null] The labels in this state will have all their instances be fused together.
355+ * @param {number[][]} [target_sizes=null] The target sizes to resize the masks to.
356+ * @returns {Array<{ segmentation: Tensor, segments_info: Array<{id: number, label_id: number, score: number}>}>}
357+ */
358+ post_process_panoptic_segmentation(
359+ outputs: any,
360+ threshold?: number,
361+ mask_threshold?: number,
362+ overlap_mask_area_threshold?: number,
363+ label_ids_to_fuse?: Set<number>,
364+ target_sizes?: number[][],
365+ ): Array<{
366+ segmentation: Tensor;
367+ segments_info: Array<{
368+ id: number;
369+ label_id: number;
370+ score: number;
317371 }>;
318- post_process_instance_segmentation(): void;
372+ }>;
373+ post_process_instance_segmentation(): void;
319374 }
320375 export class YolosFeatureExtractor extends ImageFeatureExtractor {
321- /**
322- * Post-processes the outputs of the model (for object detection).
323- * @param {Object} outputs The outputs of the model that must be post-processed
324- * @param {Tensor} outputs.logits The logits
325- * @param {Tensor} outputs.pred_boxes The predicted boxes.
326- * @param {number} [threshold=0.5] The threshold to use for the scores.
327- * @param {number[][]} [target_sizes=null] The sizes of the original images.
328- * @param {boolean} [is_zero_shot=false] Whether zero-shot object detection was performed.
329- * @return {Object[]} An array of objects containing the post-processed outputs.
330- * @private
331- */
332- post_process_object_detection(outputs: {
333- logits: Tensor;
334- pred_boxes: Tensor;
335- }, threshold?: number, target_sizes?: number[][], is_zero_shot?: boolean): any[];
376+ /**
377+ * Post-processes the outputs of the model (for object detection).
378+ * @param {Object} outputs The outputs of the model that must be post-processed
379+ * @param {Tensor} outputs.logits The logits
380+ * @param {Tensor} outputs.pred_boxes The predicted boxes.
381+ * @param {number} [threshold=0.5] The threshold to use for the scores.
382+ * @param {number[][]} [target_sizes=null] The sizes of the original images.
383+ * @param {boolean} [is_zero_shot=false] Whether zero-shot object detection was performed.
384+ * @return {Object[]} An array of objects containing the post-processed outputs.
385+ * @private
386+ */
387+ post_process_object_detection(
388+ outputs: {
389+ logits: Tensor;
390+ pred_boxes: Tensor;
391+ },
392+ threshold?: number,
393+ target_sizes?: number[][],
394+ is_zero_shot?: boolean,
395+ ): any[];
336396 }
337397 /**
338398 * @typedef {object} SamImageProcessorResult
@@ -343,258 +403,298 @@
343403 * @property {Tensor} [input_labels]
344404 */
345405 export class SamImageProcessor extends ImageFeatureExtractor {
346- /**
347- *
348- * @param {any} input_points
349- * @param {HeightWidth[]} original_sizes
350- * @param {HeightWidth[]} reshaped_input_sizes
351- * @returns {Tensor}
352- */
353- reshape_input_points(input_points: any, original_sizes: HeightWidth[], reshaped_input_sizes: HeightWidth[]): Tensor;
354- /**
355- *
356- * @param {any} input_labels
357- * @param {Tensor} input_points
358- * @returns {Tensor}
359- */
360- add_input_labels(input_labels: any, input_points: Tensor): Tensor;
361- /**
362- * @param {any[]} images The URL(s) of the image(s) to extract features from.
363- * @param {any} [input_points] A 3D or 4D array, representing the input points provided by the user.
364- * - 3D: `[point_batch_size, nb_points_per_image, 2]`. In this case, `batch_size` is assumed to be 1.
365- * - 4D: `[batch_size, point_batch_size, nb_points_per_image, 2]`.
366- * @param {any} [input_labels] A 2D or 3D array, representing the input labels for the points, used by the prompt encoder to encode the prompt.
367- * - 2D: `[point_batch_size, nb_points_per_image]`. In this case, `batch_size` is assumed to be 1.
368- * - 3D: `[batch_size, point_batch_size, nb_points_per_image]`.
369- * @returns {Promise<SamImageProcessorResult>}
370- */
371- _call(images: any[], input_points?: any, input_labels?: any): Promise<SamImageProcessorResult>;
372- /**
373- * Remove padding and upscale masks to the original image size.
374- * @param {Tensor} masks Batched masks from the mask_decoder in (batch_size, num_channels, height, width) format.
375- * @param {number[][]} original_sizes The original sizes of each image before it was resized to the model's expected input shape, in (height, width) format.
376- * @param {number[][]} reshaped_input_sizes The size of each image as it is fed to the model, in (height, width) format. Used to remove padding.
377- * @param {Object} options Optional parameters for post-processing.
378- * @param {number} [options.mask_threshold] The threshold to use for binarizing the masks.
379- * @param {boolean} [options.binarize] Whether to binarize the masks.
380- * @param {Object} [options.pad_size] The target size the images were padded to before being passed to the model. If `null`, the target size is assumed to be the processor's `pad_size`.
381- * @param {number} [options.pad_size.height] The height the images were padded to.
382- * @param {number} [options.pad_size.width] The width the images were padded to.
383- * @returns {Tensor[]} Batched masks in batch_size, num_channels, height, width) format, where (height, width) is given by original_size.
384- */
385- post_process_masks(masks: Tensor, original_sizes: number[][], reshaped_input_sizes: number[][], { mask_threshold, binarize, pad_size, }?: {
386- mask_threshold?: number;
387- binarize?: boolean;
388- pad_size?: {
389- height?: number;
390- width?: number;
391- };
392- }): Tensor[];
406+ /**
407+ *
408+ * @param {any} input_points
409+ * @param {HeightWidth[]} original_sizes
410+ * @param {HeightWidth[]} reshaped_input_sizes
411+ * @returns {Tensor}
412+ */
413+ reshape_input_points(
414+ input_points: any,
415+ original_sizes: HeightWidth[],
416+ reshaped_input_sizes: HeightWidth[],
417+ ): Tensor;
418+ /**
419+ *
420+ * @param {any} input_labels
421+ * @param {Tensor} input_points
422+ * @returns {Tensor}
423+ */
424+ add_input_labels(input_labels: any, input_points: Tensor): Tensor;
425+ /**
426+ * @param {any[]} images The URL(s) of the image(s) to extract features from.
427+ * @param {any} [input_points] A 3D or 4D array, representing the input points provided by the user.
428+ * - 3D: `[point_batch_size, nb_points_per_image, 2]`. In this case, `batch_size` is assumed to be 1.
429+ * - 4D: `[batch_size, point_batch_size, nb_points_per_image, 2]`.
430+ * @param {any} [input_labels] A 2D or 3D array, representing the input labels for the points, used by the prompt encoder to encode the prompt.
431+ * - 2D: `[point_batch_size, nb_points_per_image]`. In this case, `batch_size` is assumed to be 1.
432+ * - 3D: `[batch_size, point_batch_size, nb_points_per_image]`.
433+ * @returns {Promise<SamImageProcessorResult>}
434+ */
435+ _call(
436+ images: any[],
437+ input_points?: any,
438+ input_labels?: any,
439+ ): Promise<SamImageProcessorResult>;
440+ /**
441+ * Remove padding and upscale masks to the original image size.
442+ * @param {Tensor} masks Batched masks from the mask_decoder in (batch_size, num_channels, height, width) format.
443+ * @param {number[][]} original_sizes The original sizes of each image before it was resized to the model's expected input shape, in (height, width) format.
444+ * @param {number[][]} reshaped_input_sizes The size of each image as it is fed to the model, in (height, width) format. Used to remove padding.
445+ * @param {Object} options Optional parameters for post-processing.
446+ * @param {number} [options.mask_threshold] The threshold to use for binarizing the masks.
447+ * @param {boolean} [options.binarize] Whether to binarize the masks.
448+ * @param {Object} [options.pad_size] The target size the images were padded to before being passed to the model. If `null`, the target size is assumed to be the processor's `pad_size`.
449+ * @param {number} [options.pad_size.height] The height the images were padded to.
450+ * @param {number} [options.pad_size.width] The width the images were padded to.
451+ * @returns {Tensor[]} Batched masks in batch_size, num_channels, height, width) format, where (height, width) is given by original_size.
452+ */
453+ post_process_masks(
454+ masks: Tensor,
455+ original_sizes: number[][],
456+ reshaped_input_sizes: number[][],
457+ {
458+ mask_threshold,
459+ binarize,
460+ pad_size,
461+ }?: {
462+ mask_threshold?: number;
463+ binarize?: boolean;
464+ pad_size?: {
465+ height?: number;
466+ width?: number;
467+ };
468+ },
469+ ): Tensor[];
393470 }
394471 export class Swin2SRImageProcessor extends ImageFeatureExtractor {
395- pad_image(pixelData: any, imgDims: any, padSize: any, options?: {}): [Float32Array, number[]];
472+ pad_image(
473+ pixelData: any,
474+ imgDims: any,
475+ padSize: any,
476+ options?: {},
477+ ): [Float32Array, number[]];
396478 }
397479 export class VitMatteImageProcessor extends ImageFeatureExtractor {
398- /**
399- * Calls the feature extraction process on an array of images, preprocesses
400- * each image, and concatenates the resulting features into a single Tensor.
401- * @param {RawImage[]} images The image(s) to extract features from.
402- * @param {RawImage[]} trimaps The trimaps(s) to extract features from.
403- * @returns {Promise<ImageFeatureExtractorResult>} An object containing the concatenated pixel values of the preprocessed images.
404- */
405- _call(images: RawImage[], trimaps: RawImage[]): Promise<ImageFeatureExtractorResult>;
480+ /**
481+ * Calls the feature extraction process on an array of images, preprocesses
482+ * each image, and concatenates the resulting features into a single Tensor.
483+ * @param {RawImage[]} images The image(s) to extract features from.
484+ * @param {RawImage[]} trimaps The trimaps(s) to extract features from.
485+ * @returns {Promise<ImageFeatureExtractorResult>} An object containing the concatenated pixel values of the preprocessed images.
486+ */
487+ _call(
488+ images: RawImage[],
489+ trimaps: RawImage[],
490+ ): Promise<ImageFeatureExtractorResult>;
406491 }
407492 export class WhisperFeatureExtractor extends FeatureExtractor {
408- constructor(config: any);
409- window: Float64Array;
410- /**
411- * Computes the log-Mel spectrogram of the provided audio waveform.
412- * @param {Float32Array|Float64Array} waveform The audio waveform to process.
413- * @returns {{data: Float32Array, dims: number[]}} An object containing the log-Mel spectrogram data as a Float32Array and its dimensions as an array of numbers.
414- */
415- _extract_fbank_features(waveform: Float32Array | Float64Array): {
416- data: Float32Array;
417- dims: number[];
418- };
419- /**
420- * Asynchronously extracts features from a given audio using the provided configuration.
421- * @param {Float32Array|Float64Array} audio The audio data as a Float32Array/Float64Array.
422- * @returns {Promise<{ input_features: Tensor }>} A Promise resolving to an object containing the extracted input features as a Tensor.
423- */
424- _call(audio: Float32Array | Float64Array): Promise<{
425- input_features: Tensor;
426- }>;
493+ constructor(config: any);
494+ window: Float64Array;
495+ /**
496+ * Computes the log-Mel spectrogram of the provided audio waveform.
497+ * @param {Float32Array|Float64Array} waveform The audio waveform to process.
498+ * @returns {{data: Float32Array, dims: number[]}} An object containing the log-Mel spectrogram data as a Float32Array and its dimensions as an array of numbers.
499+ */
500+ _extract_fbank_features(waveform: Float32Array | Float64Array): {
501+ data: Float32Array;
502+ dims: number[];
503+ };
504+ /**
505+ * Asynchronously extracts features from a given audio using the provided configuration.
506+ * @param {Float32Array|Float64Array} audio The audio data as a Float32Array/Float64Array.
507+ * @returns {Promise<{ input_features: Tensor }>} A Promise resolving to an object containing the extracted input features as a Tensor.
508+ */
509+ _call(audio: Float32Array | Float64Array): Promise<{
510+ input_features: Tensor;
511+ }>;
427512 }
428513 export class Wav2Vec2FeatureExtractor extends FeatureExtractor {
429- /**
430- * @param {Float32Array} input_values
431- * @returns {Float32Array}
432- */
433- _zero_mean_unit_var_norm(input_values: Float32Array): Float32Array;
434- /**
435- * Asynchronously extracts features from a given audio using the provided configuration.
436- * @param {Float32Array|Float64Array} audio The audio data as a Float32Array/Float64Array.
437- * @returns {Promise<{ input_values: Tensor; attention_mask: Tensor }>} A Promise resolving to an object containing the extracted input features and attention mask as Tensors.
438- */
439- _call(audio: Float32Array | Float64Array): Promise<{
440- input_values: Tensor;
441- attention_mask: Tensor;
442- }>;
514+ /**
515+ * @param {Float32Array} input_values
516+ * @returns {Float32Array}
517+ */
518+ _zero_mean_unit_var_norm(input_values: Float32Array): Float32Array;
519+ /**
520+ * Asynchronously extracts features from a given audio using the provided configuration.
521+ * @param {Float32Array|Float64Array} audio The audio data as a Float32Array/Float64Array.
522+ * @returns {Promise<{ input_values: Tensor; attention_mask: Tensor }>} A Promise resolving to an object containing the extracted input features and attention mask as Tensors.
523+ */
524+ _call(audio: Float32Array | Float64Array): Promise<{
525+ input_values: Tensor;
526+ attention_mask: Tensor;
527+ }>;
443528 }
444529 export class ASTFeatureExtractor extends FeatureExtractor {
445- constructor(config: any);
446- mel_filters: number[][];
447- window: Float64Array;
448- mean: any;
449- std: any;
450- /**
451- * Computes the log-Mel spectrogram of the provided audio waveform.
452- * @param {Float32Array|Float64Array} waveform The audio waveform to process.
453- * @param {number} max_length The maximum number of frames to return.
454- * @returns {{data: Float32Array, dims: number[]}} An object containing the log-Mel spectrogram data as a Float32Array and its dimensions as an array of numbers.
455- */
456- _extract_fbank_features(waveform: Float32Array | Float64Array, max_length: number): {
457- data: Float32Array;
458- dims: number[];
459- };
460- /**
461- * Asynchronously extracts features from a given audio using the provided configuration.
462- * @param {Float32Array|Float64Array} audio The audio data as a Float32Array/Float64Array.
463- * @returns {Promise<{ input_values: Tensor }>} A Promise resolving to an object containing the extracted input features as a Tensor.
464- */
465- _call(audio: Float32Array | Float64Array): Promise<{
466- input_values: Tensor;
467- }>;
530+ constructor(config: any);
531+ mel_filters: number[][];
532+ window: Float64Array;
533+ mean: any;
534+ std: any;
535+ /**
536+ * Computes the log-Mel spectrogram of the provided audio waveform.
537+ * @param {Float32Array|Float64Array} waveform The audio waveform to process.
538+ * @param {number} max_length The maximum number of frames to return.
539+ * @returns {{data: Float32Array, dims: number[]}} An object containing the log-Mel spectrogram data as a Float32Array and its dimensions as an array of numbers.
540+ */
541+ _extract_fbank_features(
542+ waveform: Float32Array | Float64Array,
543+ max_length: number,
544+ ): {
545+ data: Float32Array;
546+ dims: number[];
547+ };
548+ /**
549+ * Asynchronously extracts features from a given audio using the provided configuration.
550+ * @param {Float32Array|Float64Array} audio The audio data as a Float32Array/Float64Array.
551+ * @returns {Promise<{ input_values: Tensor }>} A Promise resolving to an object containing the extracted input features as a Tensor.
552+ */
553+ _call(audio: Float32Array | Float64Array): Promise<{
554+ input_values: Tensor;
555+ }>;
468556 }
469557 export class ClapFeatureExtractor extends FeatureExtractor {
470- constructor(config: any);
471- mel_filters: number[][];
472- mel_filters_slaney: number[][];
473- window: Float64Array;
474- /**
475- * Extracts the mel spectrogram and prepares it for the mode based on the `truncation` and `padding` arguments.
476- *
477- * Four different path are possible:
478- * - `truncation="fusion"` and the length of the waveform is greater than the max length: the mel spectrogram
479- * will be computed on the entire audio. 3 random crops and a dowsampled version of the full mel spectrogram
480- * are then stacked together. They will later be used for `feature_fusion`.
481- * - `truncation="rand_trunc"` and the length of the waveform is smaller than the max length: the audio is
482- * padded based on `padding`.
483- * - `truncation="fusion"` and the length of the waveform is smaller than the max length: the audio is padded
484- * based on `padding`, and is repeated `4` times.
485- * - `truncation="rand_trunc"` and the length of the waveform is greater than the max length: the mel
486- * spectrogram will be computed on a random crop of the waveform.
487- *
488- * @param {Float32Array|Float64Array} waveform The input waveform.
489- * @param {number} max_length The maximum length of the waveform.
490- * @param {string} truncation The truncation strategy to use.
491- * @param {string} padding The padding strategy to use.
492- * @returns {{ data: Float32Array; dims: number[]; longer: boolean; }} An object containing the mel spectrogram data as a Float32Array, its dimensions as an array of numbers, and a boolean indicating whether the waveform was longer than the max length.
493- */
494- _get_input_mel(waveform: Float32Array | Float64Array, max_length: number, truncation: string, padding: string): {
495- data: Float32Array;
496- dims: number[];
497- longer: boolean;
498- };
499- /**
500- * Compute the log-mel spectrogram of the provided `waveform` using the Hann window.
501- * In CLAP, two different filter banks are used depending on the truncation pattern:
502- * - `self.mel_filters`: they correspond to the default parameters of `torchaudio` which can be obtained from
503- * calling `torchaudio.transforms.MelSpectrogram().mel_scale.fb`. These filters are used when `truncation`
504- * is set to `"fusion"`.
505- * - `self.mel_filteres_slaney` : they correspond to the default parameters of `librosa` which used
506- * `librosa.filters.mel` when computing the mel spectrogram. These filters were only used in the original
507- * implementation when the truncation mode is not `"fusion"`.
508- *
509- * @param {Float32Array|Float64Array} waveform The audio waveform to process.
510- * @param {number[][]} mel_filters The mel filters to use.
511- * @param {number} [max_length=null] The maximum number of frames to return.
512- * @returns {{data: Float32Array, dims: number[]}} An object containing the log-Mel spectrogram data as a Float32Array and its dimensions as an array of numbers.
513- */
514- _extract_fbank_features(waveform: Float32Array | Float64Array, mel_filters: number[][], max_length?: number): {
515- data: Float32Array;
516- dims: number[];
517- };
518- /**
519- * Asynchronously extracts features from a given audio using the provided configuration.
520- * @param {Float32Array|Float64Array} audio The audio data as a Float32Array/Float64Array.
521- * @returns {Promise<{ input_features: Tensor }>} A Promise resolving to an object containing the extracted input features as a Tensor.
522- */
523- _call(audio: Float32Array | Float64Array, { max_length, }?: {
524- max_length?: any;
525- }): Promise<{
526- input_features: Tensor;
527- }>;
528-}
529-export class SpeechT5FeatureExtractor extends FeatureExtractor {
530-}
558+ constructor(config: any);
559+ mel_filters: number[][];
560+ mel_filters_slaney: number[][];
561+ window: Float64Array;
562+ /**
563+ * Extracts the mel spectrogram and prepares it for the mode based on the `truncation` and `padding` arguments.
564+ *
565+ * Four different path are possible:
566+ * - `truncation="fusion"` and the length of the waveform is greater than the max length: the mel spectrogram
567+ * will be computed on the entire audio. 3 random crops and a dowsampled version of the full mel spectrogram
568+ * are then stacked together. They will later be used for `feature_fusion`.
569+ * - `truncation="rand_trunc"` and the length of the waveform is smaller than the max length: the audio is
570+ * padded based on `padding`.
571+ * - `truncation="fusion"` and the length of the waveform is smaller than the max length: the audio is padded
572+ * based on `padding`, and is repeated `4` times.
573+ * - `truncation="rand_trunc"` and the length of the waveform is greater than the max length: the mel
574+ * spectrogram will be computed on a random crop of the waveform.
575+ *
576+ * @param {Float32Array|Float64Array} waveform The input waveform.
577+ * @param {number} max_length The maximum length of the waveform.
578+ * @param {string} truncation The truncation strategy to use.
579+ * @param {string} padding The padding strategy to use.
580+ * @returns {{ data: Float32Array; dims: number[]; longer: boolean; }} An object containing the mel spectrogram data as a Float32Array, its dimensions as an array of numbers, and a boolean indicating whether the waveform was longer than the max length.
581+ */
582+ _get_input_mel(
583+ waveform: Float32Array | Float64Array,
584+ max_length: number,
585+ truncation: string,
586+ padding: string,
587+ ): {
588+ data: Float32Array;
589+ dims: number[];
590+ longer: boolean;
591+ };
592+ /**
593+ * Compute the log-mel spectrogram of the provided `waveform` using the Hann window.
594+ * In CLAP, two different filter banks are used depending on the truncation pattern:
595+ * - `self.mel_filters`: they correspond to the default parameters of `torchaudio` which can be obtained from
596+ * calling `torchaudio.transforms.MelSpectrogram().mel_scale.fb`. These filters are used when `truncation`
597+ * is set to `"fusion"`.
598+ * - `self.mel_filteres_slaney` : they correspond to the default parameters of `librosa` which used
599+ * `librosa.filters.mel` when computing the mel spectrogram. These filters were only used in the original
600+ * implementation when the truncation mode is not `"fusion"`.
601+ *
602+ * @param {Float32Array|Float64Array} waveform The audio waveform to process.
603+ * @param {number[][]} mel_filters The mel filters to use.
604+ * @param {number} [max_length=null] The maximum number of frames to return.
605+ * @returns {{data: Float32Array, dims: number[]}} An object containing the log-Mel spectrogram data as a Float32Array and its dimensions as an array of numbers.
606+ */
607+ _extract_fbank_features(
608+ waveform: Float32Array | Float64Array,
609+ mel_filters: number[][],
610+ max_length?: number,
611+ ): {
612+ data: Float32Array;
613+ dims: number[];
614+ };
615+ /**
616+ * Asynchronously extracts features from a given audio using the provided configuration.
617+ * @param {Float32Array|Float64Array} audio The audio data as a Float32Array/Float64Array.
618+ * @returns {Promise<{ input_features: Tensor }>} A Promise resolving to an object containing the extracted input features as a Tensor.
619+ */
620+ _call(
621+ audio: Float32Array | Float64Array,
622+ {
623+ max_length,
624+ }?: {
625+ max_length?: any;
626+ },
627+ ): Promise<{
628+ input_features: Tensor;
629+ }>;
630+}
631+export class SpeechT5FeatureExtractor extends FeatureExtractor {}
531632 declare const Processor_base: new () => {
532- (...args: any[]): any;
533- _call(...args: any[]): any;
633+ (...args: any[]): any;
634+ _call(...args: any[]): any;
534635 };
535636 /**
536637 * Represents a Processor that extracts features from an input.
537638 * @extends Callable
538639 */
539640 export class Processor extends Processor_base {
540- /**
541- * Creates a new Processor with the given feature extractor.
542- * @param {FeatureExtractor} feature_extractor The function used to extract features from the input.
543- */
544- constructor(feature_extractor: FeatureExtractor);
545- feature_extractor: FeatureExtractor;
546- /**
547- * Calls the feature_extractor function with the given input.
548- * @param {any} input The input to extract features from.
549- * @param {...any} args Additional arguments.
550- * @returns {Promise<any>} A Promise that resolves with the extracted features.
551- */
552- _call(input: any, ...args: any[]): Promise<any>;
641+ /**
642+ * Creates a new Processor with the given feature extractor.
643+ * @param {FeatureExtractor} feature_extractor The function used to extract features from the input.
644+ */
645+ constructor(feature_extractor: FeatureExtractor);
646+ feature_extractor: FeatureExtractor;
647+ /**
648+ * Calls the feature_extractor function with the given input.
649+ * @param {any} input The input to extract features from.
650+ * @param {...any} args Additional arguments.
651+ * @returns {Promise<any>} A Promise that resolves with the extracted features.
652+ */
653+ _call(input: any, ...args: any[]): Promise<any>;
553654 }
554655 export class SamProcessor extends Processor {
555- /**
556- * @borrows SamImageProcessor#_call as _call
557- */
558- _call(...args: any[]): Promise<any>;
559- /**
560- * @borrows SamImageProcessor#post_process_masks as post_process_masks
561- */
562- post_process_masks(...args: any[]): any;
563- /**
564- * @borrows SamImageProcessor#reshape_input_points as reshape_input_points
565- */
566- reshape_input_points(...args: any[]): any;
656+ /**
657+ * @borrows SamImageProcessor#_call as _call
658+ */
659+ _call(...args: any[]): Promise<any>;
660+ /**
661+ * @borrows SamImageProcessor#post_process_masks as post_process_masks
662+ */
663+ post_process_masks(...args: any[]): any;
664+ /**
665+ * @borrows SamImageProcessor#reshape_input_points as reshape_input_points
666+ */
667+ reshape_input_points(...args: any[]): any;
567668 }
568669 /**
569670 * Represents a WhisperProcessor that extracts features from an audio input.
570671 * @extends Processor
571672 */
572673 export class WhisperProcessor extends Processor {
573- /**
574- * Calls the feature_extractor function with the given audio input.
575- * @param {any} audio The audio input to extract features from.
576- * @returns {Promise<any>} A Promise that resolves with the extracted features.
577- */
578- _call(audio: any): Promise<any>;
674+ /**
675+ * Calls the feature_extractor function with the given audio input.
676+ * @param {any} audio The audio input to extract features from.
677+ * @returns {Promise<any>} A Promise that resolves with the extracted features.
678+ */
679+ _call(audio: any): Promise<any>;
579680 }
580681 export class Wav2Vec2ProcessorWithLM extends Processor {
581- /**
582- * Calls the feature_extractor function with the given audio input.
583- * @param {any} audio The audio input to extract features from.
584- * @returns {Promise<any>} A Promise that resolves with the extracted features.
585- */
586- _call(audio: any): Promise<any>;
682+ /**
683+ * Calls the feature_extractor function with the given audio input.
684+ * @param {any} audio The audio input to extract features from.
685+ * @returns {Promise<any>} A Promise that resolves with the extracted features.
686+ */
687+ _call(audio: any): Promise<any>;
587688 }
588689 export class SpeechT5Processor extends Processor {
589- /**
590- * Calls the feature_extractor function with the given input.
591- * @param {any} input The input to extract features from.
592- * @returns {Promise<any>} A Promise that resolves with the extracted features.
593- */
594- _call(input: any): Promise<any>;
595-}
596-export class OwlViTProcessor extends Processor {
597-}
690+ /**
691+ * Calls the feature_extractor function with the given input.
692+ * @param {any} input The input to extract features from.
693+ * @returns {Promise<any>} A Promise that resolves with the extracted features.
694+ */
695+ _call(input: any): Promise<any>;
696+}
697+export class OwlViTProcessor extends Processor {}
598698 /**
599699 * Helper class which is used to instantiate pretrained processors with the `from_pretrained` function.
600700 * The chosen processor class is determined by the type specified in the processor config.
@@ -626,58 +726,67 @@
626726 * ```
627727 */
628728 export class AutoProcessor {
629- static FEATURE_EXTRACTOR_CLASS_MAPPING: {
630- WhisperFeatureExtractor: typeof WhisperFeatureExtractor;
631- ViTFeatureExtractor: typeof ViTFeatureExtractor;
632- MobileViTFeatureExtractor: typeof MobileViTFeatureExtractor;
633- OwlViTFeatureExtractor: typeof OwlViTFeatureExtractor;
634- CLIPFeatureExtractor: typeof CLIPFeatureExtractor;
635- ChineseCLIPFeatureExtractor: typeof ChineseCLIPFeatureExtractor;
636- SiglipImageProcessor: typeof SiglipImageProcessor;
637- ConvNextFeatureExtractor: typeof ConvNextFeatureExtractor;
638- ConvNextImageProcessor: typeof ConvNextImageProcessor;
639- SegformerFeatureExtractor: typeof SegformerFeatureExtractor;
640- BitImageProcessor: typeof BitImageProcessor;
641- DPTFeatureExtractor: typeof DPTFeatureExtractor;
642- GLPNFeatureExtractor: typeof GLPNFeatureExtractor;
643- BeitFeatureExtractor: typeof BeitFeatureExtractor;
644- DeiTFeatureExtractor: typeof DeiTFeatureExtractor;
645- DetrFeatureExtractor: typeof DetrFeatureExtractor;
646- YolosFeatureExtractor: typeof YolosFeatureExtractor;
647- DonutFeatureExtractor: typeof DonutFeatureExtractor;
648- NougatImageProcessor: typeof NougatImageProcessor;
649- ViTImageProcessor: typeof ViTImageProcessor;
650- VitMatteImageProcessor: typeof VitMatteImageProcessor;
651- SamImageProcessor: typeof SamImageProcessor;
652- Swin2SRImageProcessor: typeof Swin2SRImageProcessor;
653- Wav2Vec2FeatureExtractor: typeof Wav2Vec2FeatureExtractor;
654- SpeechT5FeatureExtractor: typeof SpeechT5FeatureExtractor;
655- ASTFeatureExtractor: typeof ASTFeatureExtractor;
656- ClapFeatureExtractor: typeof ClapFeatureExtractor;
657- };
658- static PROCESSOR_CLASS_MAPPING: {
659- WhisperProcessor: typeof WhisperProcessor;
660- Wav2Vec2ProcessorWithLM: typeof Wav2Vec2ProcessorWithLM;
661- SamProcessor: typeof SamProcessor;
662- SpeechT5Processor: typeof SpeechT5Processor;
663- OwlViTProcessor: typeof OwlViTProcessor;
664- };
665- /**
666- * Instantiate one of the processor classes of the library from a pretrained model.
667- *
668- * The processor class to instantiate is selected based on the `feature_extractor_type` property of the config object
669- * (either passed as an argument or loaded from `pretrained_model_name_or_path` if possible)
670- *
671- * @param {string} pretrained_model_name_or_path The name or path of the pretrained model. Can be either:
672- * - A string, the *model id* of a pretrained processor hosted inside a model repo on huggingface.co.
673- * Valid model ids can be located at the root-level, like `bert-base-uncased`, or namespaced under a
674- * user or organization name, like `dbmdz/bert-base-german-cased`.
675- * - A path to a *directory* containing processor files, e.g., `./my_model_directory/`.
676- * @param {import('./utils/hub.js').PretrainedOptions} options Additional options for loading the processor.
677- *
678- * @returns {Promise<Processor>} A new instance of the Processor class.
679- */
680- static from_pretrained(pretrained_model_name_or_path: string, { progress_callback, config, cache_dir, local_files_only, revision, }?: import('./utils/hub.js').PretrainedOptions): Promise<Processor>;
729+ static FEATURE_EXTRACTOR_CLASS_MAPPING: {
730+ WhisperFeatureExtractor: typeof WhisperFeatureExtractor;
731+ ViTFeatureExtractor: typeof ViTFeatureExtractor;
732+ MobileViTFeatureExtractor: typeof MobileViTFeatureExtractor;
733+ OwlViTFeatureExtractor: typeof OwlViTFeatureExtractor;
734+ CLIPFeatureExtractor: typeof CLIPFeatureExtractor;
735+ ChineseCLIPFeatureExtractor: typeof ChineseCLIPFeatureExtractor;
736+ SiglipImageProcessor: typeof SiglipImageProcessor;
737+ ConvNextFeatureExtractor: typeof ConvNextFeatureExtractor;
738+ ConvNextImageProcessor: typeof ConvNextImageProcessor;
739+ SegformerFeatureExtractor: typeof SegformerFeatureExtractor;
740+ BitImageProcessor: typeof BitImageProcessor;
741+ DPTFeatureExtractor: typeof DPTFeatureExtractor;
742+ GLPNFeatureExtractor: typeof GLPNFeatureExtractor;
743+ BeitFeatureExtractor: typeof BeitFeatureExtractor;
744+ DeiTFeatureExtractor: typeof DeiTFeatureExtractor;
745+ DetrFeatureExtractor: typeof DetrFeatureExtractor;
746+ YolosFeatureExtractor: typeof YolosFeatureExtractor;
747+ DonutFeatureExtractor: typeof DonutFeatureExtractor;
748+ NougatImageProcessor: typeof NougatImageProcessor;
749+ ViTImageProcessor: typeof ViTImageProcessor;
750+ VitMatteImageProcessor: typeof VitMatteImageProcessor;
751+ SamImageProcessor: typeof SamImageProcessor;
752+ Swin2SRImageProcessor: typeof Swin2SRImageProcessor;
753+ Wav2Vec2FeatureExtractor: typeof Wav2Vec2FeatureExtractor;
754+ SpeechT5FeatureExtractor: typeof SpeechT5FeatureExtractor;
755+ ASTFeatureExtractor: typeof ASTFeatureExtractor;
756+ ClapFeatureExtractor: typeof ClapFeatureExtractor;
757+ };
758+ static PROCESSOR_CLASS_MAPPING: {
759+ WhisperProcessor: typeof WhisperProcessor;
760+ Wav2Vec2ProcessorWithLM: typeof Wav2Vec2ProcessorWithLM;
761+ SamProcessor: typeof SamProcessor;
762+ SpeechT5Processor: typeof SpeechT5Processor;
763+ OwlViTProcessor: typeof OwlViTProcessor;
764+ };
765+ /**
766+ * Instantiate one of the processor classes of the library from a pretrained model.
767+ *
768+ * The processor class to instantiate is selected based on the `feature_extractor_type` property of the config object
769+ * (either passed as an argument or loaded from `pretrained_model_name_or_path` if possible)
770+ *
771+ * @param {string} pretrained_model_name_or_path The name or path of the pretrained model. Can be either:
772+ * - A string, the *model id* of a pretrained processor hosted inside a model repo on huggingface.co.
773+ * Valid model ids can be located at the root-level, like `bert-base-uncased`, or namespaced under a
774+ * user or organization name, like `dbmdz/bert-base-german-cased`.
775+ * - A path to a *directory* containing processor files, e.g., `./my_model_directory/`.
776+ * @param {import('./utils/hub.js').PretrainedOptions} options Additional options for loading the processor.
777+ *
778+ * @returns {Promise<Processor>} A new instance of the Processor class.
779+ */
780+ static from_pretrained(
781+ pretrained_model_name_or_path: string,
782+ {
783+ progress_callback,
784+ config,
785+ cache_dir,
786+ local_files_only,
787+ revision,
788+ }?: import("./utils/hub.js").PretrainedOptions,
789+ ): Promise<Processor>;
681790 }
682791 /**
683792 * Named tuple to indicate the order we are using is (height x width), even though
@@ -685,31 +794,32 @@
685794 */
686795 export type HeightWidth = [height: number, width: number];
687796 export type ImageFeatureExtractorResult = {
688- /**
689- * The pixel values of the batched preprocessed images.
690- */
691- pixel_values: Tensor;
692- /**
693- * Array of two-dimensional tuples like [[480, 640]].
694- */
695- original_sizes: HeightWidth[];
696- /**
697- * Array of two-dimensional tuples like [[1000, 1330]].
698- */
699- reshaped_input_sizes: HeightWidth[];
797+ /**
798+ * The pixel values of the batched preprocessed images.
799+ */
800+ pixel_values: Tensor;
801+ /**
802+ * Array of two-dimensional tuples like [[480, 640]].
803+ */
804+ original_sizes: HeightWidth[];
805+ /**
806+ * Array of two-dimensional tuples like [[1000, 1330]].
807+ */
808+ reshaped_input_sizes: HeightWidth[];
700809 };
701810 export type DetrFeatureExtractorResultProps = {
702- pixel_mask: Tensor;
811+ pixel_mask: Tensor;
703812 };
704-export type DetrFeatureExtractorResult = ImageFeatureExtractorResult & DetrFeatureExtractorResultProps;
813+export type DetrFeatureExtractorResult = ImageFeatureExtractorResult &
814+ DetrFeatureExtractorResultProps;
705815 export type SamImageProcessorResult = {
706- pixel_values: Tensor;
707- original_sizes: HeightWidth[];
708- reshaped_input_sizes: HeightWidth[];
709- input_points?: Tensor;
710- input_labels?: Tensor;
816+ pixel_values: Tensor;
817+ original_sizes: HeightWidth[];
818+ reshaped_input_sizes: HeightWidth[];
819+ input_points?: Tensor;
820+ input_labels?: Tensor;
711821 };
712-import { RawImage } from './utils/image.js';
713-import { Tensor } from './utils/tensor.js';
822+import { RawImage } from "./utils/image.js";
823+import { Tensor } from "./utils/tensor.js";
714824 export {};
715-//# sourceMappingURL=processors.d.ts.map
No newline at the end of the file
825+//# sourceMappingURL=processors.d.ts.map
modified core/vendor/modules/@xenova/transformers/types/tokenizers.d.ts +816 −755
@@ -1,6 +1,6 @@
11 declare const TokenizerModel_base: new () => {
2- (...args: any[]): any;
3- _call(...args: any[]): any;
2+ (...args: any[]): any;
3+ _call(...args: any[]): any;
44 };
55 /**
66 * Abstract base class for tokenizer models.
@@ -8,375 +8,402 @@
88 * @extends Callable
99 */
1010 export class TokenizerModel extends TokenizerModel_base {
11- /**
12- * Instantiates a new TokenizerModel instance based on the configuration object provided.
13- * @param {Object} config The configuration object for the TokenizerModel.
14- * @param {...*} args Optional arguments to pass to the specific TokenizerModel constructor.
15- * @returns {TokenizerModel} A new instance of a TokenizerModel.
16- * @throws Will throw an error if the TokenizerModel type in the config is not recognized.
17- */
18- static fromConfig(config: any, ...args: any[]): TokenizerModel;
19- /**
20- * Creates a new instance of TokenizerModel.
21- * @param {Object} config The configuration object for the TokenizerModel.
22- */
23- constructor(config: any);
24- config: any;
25- /** @type {string[]} */
26- vocab: string[];
27- /**
28- * A mapping of tokens to ids.
29- * @type {Map<string, number>}
30- */
31- tokens_to_ids: Map<string, number>;
32- unk_token_id: any;
33- unk_token: any;
34- end_of_word_suffix: any;
35- /** @type {boolean} Whether to fuse unknown tokens when encoding. Defaults to false. */
36- fuse_unk: boolean;
37- /**
38- * Internal function to call the TokenizerModel instance.
39- * @param {string[]} tokens The tokens to encode.
40- * @returns {string[]} The encoded token IDs.
41- */
42- _call(tokens: string[]): string[];
43- /**
44- * Encodes a list of tokens into a list of token IDs.
45- * @param {string[]} tokens The tokens to encode.
46- * @returns {string[]} The encoded tokens.
47- * @throws Will throw an error if not implemented in a subclass.
48- */
49- encode(tokens: string[]): string[];
50- /**
51- * Converts a list of tokens into a list of token IDs.
52- * @param {string[]} tokens The tokens to convert.
53- * @returns {number[]} The converted token IDs.
54- */
55- convert_tokens_to_ids(tokens: string[]): number[];
56- /**
57- * Converts a list of token IDs into a list of tokens.
58- * @param {number[]} ids The token IDs to convert.
59- * @returns {string[]} The converted tokens.
60- */
61- convert_ids_to_tokens(ids: number[]): string[];
11+ /**
12+ * Instantiates a new TokenizerModel instance based on the configuration object provided.
13+ * @param {Object} config The configuration object for the TokenizerModel.
14+ * @param {...*} args Optional arguments to pass to the specific TokenizerModel constructor.
15+ * @returns {TokenizerModel} A new instance of a TokenizerModel.
16+ * @throws Will throw an error if the TokenizerModel type in the config is not recognized.
17+ */
18+ static fromConfig(config: any, ...args: any[]): TokenizerModel;
19+ /**
20+ * Creates a new instance of TokenizerModel.
21+ * @param {Object} config The configuration object for the TokenizerModel.
22+ */
23+ constructor(config: any);
24+ config: any;
25+ /** @type {string[]} */
26+ vocab: string[];
27+ /**
28+ * A mapping of tokens to ids.
29+ * @type {Map<string, number>}
30+ */
31+ tokens_to_ids: Map<string, number>;
32+ unk_token_id: any;
33+ unk_token: any;
34+ end_of_word_suffix: any;
35+ /** @type {boolean} Whether to fuse unknown tokens when encoding. Defaults to false. */
36+ fuse_unk: boolean;
37+ /**
38+ * Internal function to call the TokenizerModel instance.
39+ * @param {string[]} tokens The tokens to encode.
40+ * @returns {string[]} The encoded token IDs.
41+ */
42+ _call(tokens: string[]): string[];
43+ /**
44+ * Encodes a list of tokens into a list of token IDs.
45+ * @param {string[]} tokens The tokens to encode.
46+ * @returns {string[]} The encoded tokens.
47+ * @throws Will throw an error if not implemented in a subclass.
48+ */
49+ encode(tokens: string[]): string[];
50+ /**
51+ * Converts a list of tokens into a list of token IDs.
52+ * @param {string[]} tokens The tokens to convert.
53+ * @returns {number[]} The converted token IDs.
54+ */
55+ convert_tokens_to_ids(tokens: string[]): number[];
56+ /**
57+ * Converts a list of token IDs into a list of tokens.
58+ * @param {number[]} ids The token IDs to convert.
59+ * @returns {string[]} The converted tokens.
60+ */
61+ convert_ids_to_tokens(ids: number[]): string[];
6262 }
6363 declare const PreTrainedTokenizer_base: new () => {
64- (...args: any[]): any;
65- _call(...args: any[]): any;
64+ (...args: any[]): any;
65+ _call(...args: any[]): any;
6666 };
6767 export class PreTrainedTokenizer extends PreTrainedTokenizer_base {
68+ /**
69+ * Loads a pre-trained tokenizer from the given `pretrained_model_name_or_path`.
70+ *
71+ * @param {string} pretrained_model_name_or_path The path to the pre-trained tokenizer.
72+ * @param {PretrainedTokenizerOptions} options Additional options for loading the tokenizer.
73+ *
74+ * @throws {Error} Throws an error if the tokenizer.json or tokenizer_config.json files are not found in the `pretrained_model_name_or_path`.
75+ * @returns {Promise<PreTrainedTokenizer>} A new instance of the `PreTrainedTokenizer` class.
76+ */
77+ static from_pretrained(
78+ pretrained_model_name_or_path: string,
79+ {
80+ progress_callback,
81+ config,
82+ cache_dir,
83+ local_files_only,
84+ revision,
85+ legacy,
86+ }?: PretrainedTokenizerOptions,
87+ ): Promise<PreTrainedTokenizer>;
88+ /**
89+ * Create a new PreTrainedTokenizer instance.
90+ * @param {Object} tokenizerJSON The JSON of the tokenizer.
91+ * @param {Object} tokenizerConfig The config of the tokenizer.
92+ */
93+ constructor(tokenizerJSON: any, tokenizerConfig: any);
94+ return_token_type_ids: boolean;
95+ _default_chat_template: string;
96+ _tokenizer_config: any;
97+ normalizer: Normalizer;
98+ pre_tokenizer: PreTokenizer;
99+ model: TokenizerModel;
100+ post_processor: PostProcessor;
101+ decoder: Decoder;
102+ special_tokens: any[];
103+ all_special_ids: number[];
104+ /** @type {AddedToken[]} */
105+ added_tokens: AddedToken[];
106+ additional_special_tokens: any;
107+ added_tokens_regex: RegExp;
108+ mask_token: string;
109+ mask_token_id: number;
110+ pad_token: string;
111+ pad_token_id: number;
112+ sep_token: string;
113+ sep_token_id: number;
114+ unk_token: string;
115+ unk_token_id: number;
116+ model_max_length: any;
117+ /** @type {boolean} Whether or not to strip the text when tokenizing (removing excess spaces before and after the string). */
118+ remove_space: boolean;
119+ clean_up_tokenization_spaces: any;
120+ do_lowercase_and_remove_accent: any;
121+ /** @type {'right'|'left'} */
122+ padding_side: "right" | "left";
123+ legacy: boolean;
124+ chat_template: any;
125+ _compiled_template_cache: Map<any, any>;
126+ /**
127+ * Returns the value of the first matching key in the tokenizer config object.
128+ * @param {...string} keys One or more keys to search for in the tokenizer config object.
129+ * @returns {string|null} The value associated with the first matching key, or null if no match is found.
130+ * @throws {Error} If an object is found for a matching key and its __type property is not "AddedToken".
131+ */
132+ getToken(...keys: string[]): string | null;
133+ /**
134+ * @typedef {number[]|number[][]|Tensor} BatchEncodingItem
135+ *
136+ * @typedef {Object} BatchEncoding Holds the output of the tokenizer's call function.
137+ * @property {BatchEncodingItem} input_ids List of token ids to be fed to a model.
138+ * @property {BatchEncodingItem} attention_mask List of indices specifying which tokens should be attended to by the model.
139+ * @property {BatchEncodingItem} [token_type_ids] List of token type ids to be fed to a model.
140+ */
141+ /**
142+ * Encode/tokenize the given text(s).
143+ * @param {string|string[]} text The text to tokenize.
144+ * @param {Object} options An optional object containing the following properties:
145+ * @param {string|string[]} [options.text_pair=null] Optional second sequence to be encoded. If set, must be the same type as text.
146+ * @param {boolean|'max_length'} [options.padding=false] Whether to pad the input sequences.
147+ * @param {boolean} [options.add_special_tokens=true] Whether or not to add the special tokens associated with the corresponding model.
148+ * @param {boolean} [options.truncation=null] Whether to truncate the input sequences.
149+ * @param {number} [options.max_length=null] Maximum length of the returned list and optionally padding length.
150+ * @param {boolean} [options.return_tensor=true] Whether to return the results as Tensors or arrays.
151+ * @returns {BatchEncoding} Object to be passed to the model.
152+ */
153+ _call(
154+ text: string | string[],
155+ {
156+ text_pair,
157+ add_special_tokens,
158+ padding,
159+ truncation,
160+ max_length,
161+ return_tensor,
162+ }?: {
163+ text_pair?: string | string[];
164+ padding?: boolean | "max_length";
165+ add_special_tokens?: boolean;
166+ truncation?: boolean;
167+ max_length?: number;
168+ return_tensor?: boolean;
169+ },
170+ ): {
68171 /**
69- * Loads a pre-trained tokenizer from the given `pretrained_model_name_or_path`.
70- *
71- * @param {string} pretrained_model_name_or_path The path to the pre-trained tokenizer.
72- * @param {PretrainedTokenizerOptions} options Additional options for loading the tokenizer.
73- *
74- * @throws {Error} Throws an error if the tokenizer.json or tokenizer_config.json files are not found in the `pretrained_model_name_or_path`.
75- * @returns {Promise<PreTrainedTokenizer>} A new instance of the `PreTrainedTokenizer` class.
76- */
77- static from_pretrained(pretrained_model_name_or_path: string, { progress_callback, config, cache_dir, local_files_only, revision, legacy, }?: PretrainedTokenizerOptions): Promise<PreTrainedTokenizer>;
78- /**
79- * Create a new PreTrainedTokenizer instance.
80- * @param {Object} tokenizerJSON The JSON of the tokenizer.
81- * @param {Object} tokenizerConfig The config of the tokenizer.
82- */
83- constructor(tokenizerJSON: any, tokenizerConfig: any);
84- return_token_type_ids: boolean;
85- _default_chat_template: string;
86- _tokenizer_config: any;
87- normalizer: Normalizer;
88- pre_tokenizer: PreTokenizer;
89- model: TokenizerModel;
90- post_processor: PostProcessor;
91- decoder: Decoder;
92- special_tokens: any[];
93- all_special_ids: number[];
94- /** @type {AddedToken[]} */
95- added_tokens: AddedToken[];
96- additional_special_tokens: any;
97- added_tokens_regex: RegExp;
98- mask_token: string;
99- mask_token_id: number;
100- pad_token: string;
101- pad_token_id: number;
102- sep_token: string;
103- sep_token_id: number;
104- unk_token: string;
105- unk_token_id: number;
106- model_max_length: any;
107- /** @type {boolean} Whether or not to strip the text when tokenizing (removing excess spaces before and after the string). */
108- remove_space: boolean;
109- clean_up_tokenization_spaces: any;
110- do_lowercase_and_remove_accent: any;
111- /** @type {'right'|'left'} */
112- padding_side: 'right' | 'left';
113- legacy: boolean;
114- chat_template: any;
115- _compiled_template_cache: Map<any, any>;
116- /**
117- * Returns the value of the first matching key in the tokenizer config object.
118- * @param {...string} keys One or more keys to search for in the tokenizer config object.
119- * @returns {string|null} The value associated with the first matching key, or null if no match is found.
120- * @throws {Error} If an object is found for a matching key and its __type property is not "AddedToken".
121- */
122- getToken(...keys: string[]): string | null;
123- /**
124- * @typedef {number[]|number[][]|Tensor} BatchEncodingItem
125- *
126- * @typedef {Object} BatchEncoding Holds the output of the tokenizer's call function.
127- * @property {BatchEncodingItem} input_ids List of token ids to be fed to a model.
128- * @property {BatchEncodingItem} attention_mask List of indices specifying which tokens should be attended to by the model.
129- * @property {BatchEncodingItem} [token_type_ids] List of token type ids to be fed to a model.
130- */
131- /**
132- * Encode/tokenize the given text(s).
133- * @param {string|string[]} text The text to tokenize.
134- * @param {Object} options An optional object containing the following properties:
135- * @param {string|string[]} [options.text_pair=null] Optional second sequence to be encoded. If set, must be the same type as text.
136- * @param {boolean|'max_length'} [options.padding=false] Whether to pad the input sequences.
137- * @param {boolean} [options.add_special_tokens=true] Whether or not to add the special tokens associated with the corresponding model.
138- * @param {boolean} [options.truncation=null] Whether to truncate the input sequences.
139- * @param {number} [options.max_length=null] Maximum length of the returned list and optionally padding length.
140- * @param {boolean} [options.return_tensor=true] Whether to return the results as Tensors or arrays.
141- * @returns {BatchEncoding} Object to be passed to the model.
142- */
143- _call(text: string | string[], { text_pair, add_special_tokens, padding, truncation, max_length, return_tensor, }?: {
144- text_pair?: string | string[];
145- padding?: boolean | 'max_length';
146- add_special_tokens?: boolean;
147- truncation?: boolean;
148- max_length?: number;
149- return_tensor?: boolean;
150- }): {
151- /**
152- * List of token ids to be fed to a model.
153- */
154- input_ids: number[] | Tensor | number[][];
155- /**
156- * List of indices specifying which tokens should be attended to by the model.
157- */
158- attention_mask: number[] | Tensor | number[][];
159- /**
160- * List of token type ids to be fed to a model.
161- */
162- token_type_ids?: number[] | Tensor | number[][];
163- };
164- /**
165- * Encodes a single text using the preprocessor pipeline of the tokenizer.
166- *
167- * @param {string|null} text The text to encode.
168- * @returns {string[]|null} The encoded tokens.
169- */
170- _encode_text(text: string | null): string[] | null;
171- /**
172- * Encodes a single text or a pair of texts using the model's tokenizer.
173- *
174- * @param {string} text The text to encode.
175- * @param {string|null} text_pair The optional second text to encode.
176- * @param {Object} options An optional object containing the following properties:
177- * @param {boolean} [options.add_special_tokens=true] Whether or not to add the special tokens associated with the corresponding model.
178- * @returns {EncodingSingle} An object containing the encoded text.
179- * @private
180- */
181- private _encode_plus;
182- /**
183- * Encodes a single text or a pair of texts using the model's tokenizer.
184- *
185- * @param {string} text The text to encode.
186- * @param {string|null} text_pair The optional second text to encode.
187- * @param {Object} options An optional object containing the following properties:
188- * @param {boolean} [options.add_special_tokens=true] Whether or not to add the special tokens associated with the corresponding model.
189- * @returns {number[]} An array of token IDs representing the encoded text(s).
190- */
191- encode(text: string, text_pair?: string | null, { add_special_tokens, }?: {
192- add_special_tokens?: boolean;
193- }): number[];
194- /**
195- * Decode a batch of tokenized sequences.
196- * @param {number[][]|Tensor} batch List/Tensor of tokenized input sequences.
197- * @param {Object} decode_args (Optional) Object with decoding arguments.
198- * @returns {string[]} List of decoded sequences.
199- */
200- batch_decode(batch: number[][] | Tensor, decode_args?: any): string[];
201- /**
202- * Decodes a sequence of token IDs back to a string.
203- *
204- * @param {number[]|Tensor} token_ids List/Tensor of token IDs to decode.
205- * @param {Object} [decode_args={}]
206- * @param {boolean} [decode_args.skip_special_tokens=false] If true, special tokens are removed from the output string.
207- * @param {boolean} [decode_args.clean_up_tokenization_spaces=true] If true, spaces before punctuations and abbreviated forms are removed.
208- *
209- * @returns {string} The decoded string.
210- * @throws {Error} If `token_ids` is not a non-empty array of integers.
211- */
212- decode(token_ids: number[] | Tensor, decode_args?: {
213- skip_special_tokens?: boolean;
214- clean_up_tokenization_spaces?: boolean;
215- }): string;
216- /**
217- * Decode a single list of token ids to a string.
218- * @param {number[]} token_ids List of token ids to decode
219- * @param {Object} decode_args Optional arguments for decoding
220- * @param {boolean} [decode_args.skip_special_tokens=false] Whether to skip special tokens during decoding
221- * @param {boolean} [decode_args.clean_up_tokenization_spaces=null] Whether to clean up tokenization spaces during decoding.
222- * If null, the value is set to `this.decoder.cleanup` if it exists, falling back to `this.clean_up_tokenization_spaces` if it exists, falling back to `true`.
223- * @returns {string} The decoded string
172+ * List of token ids to be fed to a model.
224173 */
225- decode_single(token_ids: number[], { skip_special_tokens, clean_up_tokenization_spaces, }: {
226- skip_special_tokens?: boolean;
227- clean_up_tokenization_spaces?: boolean;
228- }): string;
229- get default_chat_template(): string;
230- _warned_about_chat_template: boolean;
174+ input_ids: number[] | Tensor | number[][];
231175 /**
232- * @typedef {Object} Message
233- * @property {string} role The role of the message (e.g., "user" or "assistant" or "system").
234- * @property {string} content The content of the message.
176+ * List of indices specifying which tokens should be attended to by the model.
235177 */
178+ attention_mask: number[] | Tensor | number[][];
236179 /**
237- * Converts a list of message objects with `"role"` and `"content"` keys to a list of token
238- * ids. This method is intended for use with chat models, and will read the tokenizer's chat_template attribute to
239- * determine the format and control tokens to use when converting. When chat_template is None, it will fall back
240- * to the default_chat_template specified at the class level.
241- *
242- * See [here](https://huggingface.co/docs/transformers/chat_templating) for more information.
243- *
244- * **Example:** Applying a chat template to a conversation.
245- *
246- * ```javascript
247- * import { AutoTokenizer } from "@xenova/transformers";
248- *
249- * const tokenizer = await AutoTokenizer.from_pretrained("mistralai/Mistral-7B-Instruct-v0.1");
250- *
251- * const chat = [
252- * { "role": "user", "content": "Hello, how are you?" },
253- * { "role": "assistant", "content": "I'm doing great. How can I help you today?" },
254- * { "role": "user", "content": "I'd like to show off how chat templating works!" },
255- * ]
256- *
257- * const text = tokenizer.apply_chat_template(chat, { tokenize: false });
258- * // "<s>[INST] Hello, how are you? [/INST]I'm doing great. How can I help you today?</s> [INST] I'd like to show off how chat templating works! [/INST]"
259- *
260- * const input_ids = tokenizer.apply_chat_template(chat, { tokenize: true, return_tensor: false });
261- * // [1, 733, 16289, 28793, 22557, 28725, 910, 460, 368, 28804, 733, 28748, 16289, 28793, 28737, 28742, 28719, 2548, 1598, 28723, 1602, 541, 315, 1316, 368, 3154, 28804, 2, 28705, 733, 16289, 28793, 315, 28742, 28715, 737, 298, 1347, 805, 910, 10706, 5752, 1077, 3791, 28808, 733, 28748, 16289, 28793]
262- * ```
263- *
264- * @param {Message[]} conversation A list of message objects with `"role"` and `"content"` keys.
265- * @param {Object} options An optional object containing the following properties:
266- * @param {string} [options.chat_template=null] A Jinja template to use for this conversion. If
267- * this is not passed, the model's default chat template will be used instead.
268- * @param {boolean} [options.add_generation_prompt=false] Whether to end the prompt with the token(s) that indicate
269- * the start of an assistant message. This is useful when you want to generate a response from the model.
270- * Note that this argument will be passed to the chat template, and so it must be supported in the
271- * template for this argument to have any effect.
272- * @param {boolean} [options.tokenize=true] Whether to tokenize the output. If false, the output will be a string.
273- * @param {boolean} [options.padding=false] Whether to pad sequences to the maximum length. Has no effect if tokenize is false.
274- * @param {boolean} [options.truncation=false] Whether to truncate sequences to the maximum length. Has no effect if tokenize is false.
275- * @param {number} [options.max_length=null] Maximum length (in tokens) to use for padding or truncation. Has no effect if tokenize is false.
276- * If not specified, the tokenizer's `max_length` attribute will be used as a default.
277- * @param {boolean} [options.return_tensor=true] Whether to return the output as a Tensor or an Array. Has no effect if tokenize is false.
278- * @returns {string | Tensor | number[]| number[][]} The tokenized output.
180+ * List of token type ids to be fed to a model.
279181 */
280- apply_chat_template(conversation: {
281- /**
282- * The role of the message (e.g., "user" or "assistant" or "system").
283- */
284- role: string;
285- /**
286- * The content of the message.
287- */
288- content: string;
289- }[], { chat_template, add_generation_prompt, tokenize, padding, truncation, max_length, return_tensor, }?: {
290- chat_template?: string;
291- add_generation_prompt?: boolean;
292- tokenize?: boolean;
293- padding?: boolean;
294- truncation?: boolean;
295- max_length?: number;
296- return_tensor?: boolean;
297- }): string | Tensor | number[] | number[][];
182+ token_type_ids?: number[] | Tensor | number[][];
183+ };
184+ /**
185+ * Encodes a single text using the preprocessor pipeline of the tokenizer.
186+ *
187+ * @param {string|null} text The text to encode.
188+ * @returns {string[]|null} The encoded tokens.
189+ */
190+ _encode_text(text: string | null): string[] | null;
191+ /**
192+ * Encodes a single text or a pair of texts using the model's tokenizer.
193+ *
194+ * @param {string} text The text to encode.
195+ * @param {string|null} text_pair The optional second text to encode.
196+ * @param {Object} options An optional object containing the following properties:
197+ * @param {boolean} [options.add_special_tokens=true] Whether or not to add the special tokens associated with the corresponding model.
198+ * @returns {EncodingSingle} An object containing the encoded text.
199+ * @private
200+ */
201+ private _encode_plus;
202+ /**
203+ * Encodes a single text or a pair of texts using the model's tokenizer.
204+ *
205+ * @param {string} text The text to encode.
206+ * @param {string|null} text_pair The optional second text to encode.
207+ * @param {Object} options An optional object containing the following properties:
208+ * @param {boolean} [options.add_special_tokens=true] Whether or not to add the special tokens associated with the corresponding model.
209+ * @returns {number[]} An array of token IDs representing the encoded text(s).
210+ */
211+ encode(
212+ text: string,
213+ text_pair?: string | null,
214+ {
215+ add_special_tokens,
216+ }?: {
217+ add_special_tokens?: boolean;
218+ },
219+ ): number[];
220+ /**
221+ * Decode a batch of tokenized sequences.
222+ * @param {number[][]|Tensor} batch List/Tensor of tokenized input sequences.
223+ * @param {Object} decode_args (Optional) Object with decoding arguments.
224+ * @returns {string[]} List of decoded sequences.
225+ */
226+ batch_decode(batch: number[][] | Tensor, decode_args?: any): string[];
227+ /**
228+ * Decodes a sequence of token IDs back to a string.
229+ *
230+ * @param {number[]|Tensor} token_ids List/Tensor of token IDs to decode.
231+ * @param {Object} [decode_args={}]
232+ * @param {boolean} [decode_args.skip_special_tokens=false] If true, special tokens are removed from the output string.
233+ * @param {boolean} [decode_args.clean_up_tokenization_spaces=true] If true, spaces before punctuations and abbreviated forms are removed.
234+ *
235+ * @returns {string} The decoded string.
236+ * @throws {Error} If `token_ids` is not a non-empty array of integers.
237+ */
238+ decode(
239+ token_ids: number[] | Tensor,
240+ decode_args?: {
241+ skip_special_tokens?: boolean;
242+ clean_up_tokenization_spaces?: boolean;
243+ },
244+ ): string;
245+ /**
246+ * Decode a single list of token ids to a string.
247+ * @param {number[]} token_ids List of token ids to decode
248+ * @param {Object} decode_args Optional arguments for decoding
249+ * @param {boolean} [decode_args.skip_special_tokens=false] Whether to skip special tokens during decoding
250+ * @param {boolean} [decode_args.clean_up_tokenization_spaces=null] Whether to clean up tokenization spaces during decoding.
251+ * If null, the value is set to `this.decoder.cleanup` if it exists, falling back to `this.clean_up_tokenization_spaces` if it exists, falling back to `true`.
252+ * @returns {string} The decoded string
253+ */
254+ decode_single(
255+ token_ids: number[],
256+ {
257+ skip_special_tokens,
258+ clean_up_tokenization_spaces,
259+ }: {
260+ skip_special_tokens?: boolean;
261+ clean_up_tokenization_spaces?: boolean;
262+ },
263+ ): string;
264+ get default_chat_template(): string;
265+ _warned_about_chat_template: boolean;
266+ /**
267+ * @typedef {Object} Message
268+ * @property {string} role The role of the message (e.g., "user" or "assistant" or "system").
269+ * @property {string} content The content of the message.
270+ */
271+ /**
272+ * Converts a list of message objects with `"role"` and `"content"` keys to a list of token
273+ * ids. This method is intended for use with chat models, and will read the tokenizer's chat_template attribute to
274+ * determine the format and control tokens to use when converting. When chat_template is None, it will fall back
275+ * to the default_chat_template specified at the class level.
276+ *
277+ * See [here](https://huggingface.co/docs/transformers/chat_templating) for more information.
278+ *
279+ * **Example:** Applying a chat template to a conversation.
280+ *
281+ * ```javascript
282+ * import { AutoTokenizer } from "@xenova/transformers";
283+ *
284+ * const tokenizer = await AutoTokenizer.from_pretrained("mistralai/Mistral-7B-Instruct-v0.1");
285+ *
286+ * const chat = [
287+ * { "role": "user", "content": "Hello, how are you?" },
288+ * { "role": "assistant", "content": "I'm doing great. How can I help you today?" },
289+ * { "role": "user", "content": "I'd like to show off how chat templating works!" },
290+ * ]
291+ *
292+ * const text = tokenizer.apply_chat_template(chat, { tokenize: false });
293+ * // "<s>[INST] Hello, how are you? [/INST]I'm doing great. How can I help you today?</s> [INST] I'd like to show off how chat templating works! [/INST]"
294+ *
295+ * const input_ids = tokenizer.apply_chat_template(chat, { tokenize: true, return_tensor: false });
296+ * // [1, 733, 16289, 28793, 22557, 28725, 910, 460, 368, 28804, 733, 28748, 16289, 28793, 28737, 28742, 28719, 2548, 1598, 28723, 1602, 541, 315, 1316, 368, 3154, 28804, 2, 28705, 733, 16289, 28793, 315, 28742, 28715, 737, 298, 1347, 805, 910, 10706, 5752, 1077, 3791, 28808, 733, 28748, 16289, 28793]
297+ * ```
298+ *
299+ * @param {Message[]} conversation A list of message objects with `"role"` and `"content"` keys.
300+ * @param {Object} options An optional object containing the following properties:
301+ * @param {string} [options.chat_template=null] A Jinja template to use for this conversion. If
302+ * this is not passed, the model's default chat template will be used instead.
303+ * @param {boolean} [options.add_generation_prompt=false] Whether to end the prompt with the token(s) that indicate
304+ * the start of an assistant message. This is useful when you want to generate a response from the model.
305+ * Note that this argument will be passed to the chat template, and so it must be supported in the
306+ * template for this argument to have any effect.
307+ * @param {boolean} [options.tokenize=true] Whether to tokenize the output. If false, the output will be a string.
308+ * @param {boolean} [options.padding=false] Whether to pad sequences to the maximum length. Has no effect if tokenize is false.
309+ * @param {boolean} [options.truncation=false] Whether to truncate sequences to the maximum length. Has no effect if tokenize is false.
310+ * @param {number} [options.max_length=null] Maximum length (in tokens) to use for padding or truncation. Has no effect if tokenize is false.
311+ * If not specified, the tokenizer's `max_length` attribute will be used as a default.
312+ * @param {boolean} [options.return_tensor=true] Whether to return the output as a Tensor or an Array. Has no effect if tokenize is false.
313+ * @returns {string | Tensor | number[]| number[][]} The tokenized output.
314+ */
315+ apply_chat_template(
316+ conversation: {
317+ /**
318+ * The role of the message (e.g., "user" or "assistant" or "system").
319+ */
320+ role: string;
321+ /**
322+ * The content of the message.
323+ */
324+ content: string;
325+ }[],
326+ {
327+ chat_template,
328+ add_generation_prompt,
329+ tokenize,
330+ padding,
331+ truncation,
332+ max_length,
333+ return_tensor,
334+ }?: {
335+ chat_template?: string;
336+ add_generation_prompt?: boolean;
337+ tokenize?: boolean;
338+ padding?: boolean;
339+ truncation?: boolean;
340+ max_length?: number;
341+ return_tensor?: boolean;
342+ },
343+ ): string | Tensor | number[] | number[][];
298344 }
299345 /**
300346 * BertTokenizer is a class used to tokenize text for BERT models.
301347 * @extends PreTrainedTokenizer
302348 */
303-export class BertTokenizer extends PreTrainedTokenizer {
304-}
349+export class BertTokenizer extends PreTrainedTokenizer {}
305350 /**
306351 * Albert tokenizer
307352 * @extends PreTrainedTokenizer
308353 */
309-export class AlbertTokenizer extends PreTrainedTokenizer {
310-}
311-export class MobileBertTokenizer extends PreTrainedTokenizer {
312-}
313-export class SqueezeBertTokenizer extends PreTrainedTokenizer {
314-}
315-export class DebertaTokenizer extends PreTrainedTokenizer {
316-}
317-export class DebertaV2Tokenizer extends PreTrainedTokenizer {
318-}
319-export class HerbertTokenizer extends PreTrainedTokenizer {
320-}
321-export class ConvBertTokenizer extends PreTrainedTokenizer {
322-}
323-export class RoFormerTokenizer extends PreTrainedTokenizer {
324-}
325-export class DistilBertTokenizer extends PreTrainedTokenizer {
326-}
327-export class CamembertTokenizer extends PreTrainedTokenizer {
328-}
354+export class AlbertTokenizer extends PreTrainedTokenizer {}
355+export class MobileBertTokenizer extends PreTrainedTokenizer {}
356+export class SqueezeBertTokenizer extends PreTrainedTokenizer {}
357+export class DebertaTokenizer extends PreTrainedTokenizer {}
358+export class DebertaV2Tokenizer extends PreTrainedTokenizer {}
359+export class HerbertTokenizer extends PreTrainedTokenizer {}
360+export class ConvBertTokenizer extends PreTrainedTokenizer {}
361+export class RoFormerTokenizer extends PreTrainedTokenizer {}
362+export class DistilBertTokenizer extends PreTrainedTokenizer {}
363+export class CamembertTokenizer extends PreTrainedTokenizer {}
329364 export class XLMTokenizer extends PreTrainedTokenizer {
330- constructor(tokenizerJSON: any, tokenizerConfig: any);
331-}
332-export class ElectraTokenizer extends PreTrainedTokenizer {
333-}
334-export class T5Tokenizer extends PreTrainedTokenizer {
335-}
336-export class GPT2Tokenizer extends PreTrainedTokenizer {
337-}
338-export class BartTokenizer extends PreTrainedTokenizer {
339-}
365+ constructor(tokenizerJSON: any, tokenizerConfig: any);
366+}
367+export class ElectraTokenizer extends PreTrainedTokenizer {}
368+export class T5Tokenizer extends PreTrainedTokenizer {}
369+export class GPT2Tokenizer extends PreTrainedTokenizer {}
370+export class BartTokenizer extends PreTrainedTokenizer {}
340371 export class MBartTokenizer extends PreTrainedTokenizer {
341- constructor(tokenizerJSON: any, tokenizerConfig: any);
342- languageRegex: RegExp;
343- language_codes: any[];
344- lang_to_token: (x: any) => any;
345- /**
346- * Helper function to build translation inputs for an `MBartTokenizer`.
347- * @param {string|string[]} raw_inputs The text to tokenize.
348- * @param {Object} tokenizer_options Options to be sent to the tokenizer
349- * @param {Object} generate_kwargs Generation options.
350- * @returns {Object} Object to be passed to the model.
351- */
352- _build_translation_inputs(raw_inputs: string | string[], tokenizer_options: any, generate_kwargs: any): any;
353-}
354-export class MBart50Tokenizer extends MBartTokenizer {
355-}
356-export class RobertaTokenizer extends PreTrainedTokenizer {
357-}
372+ constructor(tokenizerJSON: any, tokenizerConfig: any);
373+ languageRegex: RegExp;
374+ language_codes: any[];
375+ lang_to_token: (x: any) => any;
376+ /**
377+ * Helper function to build translation inputs for an `MBartTokenizer`.
378+ * @param {string|string[]} raw_inputs The text to tokenize.
379+ * @param {Object} tokenizer_options Options to be sent to the tokenizer
380+ * @param {Object} generate_kwargs Generation options.
381+ * @returns {Object} Object to be passed to the model.
382+ */
383+ _build_translation_inputs(
384+ raw_inputs: string | string[],
385+ tokenizer_options: any,
386+ generate_kwargs: any,
387+ ): any;
388+}
389+export class MBart50Tokenizer extends MBartTokenizer {}
390+export class RobertaTokenizer extends PreTrainedTokenizer {}
358391 export class BloomTokenizer extends GPT2Tokenizer {
359- constructor(tokenizerJSON: any, tokenizerConfig: any);
392+ constructor(tokenizerJSON: any, tokenizerConfig: any);
360393 }
361394 export class LlamaTokenizer extends PreTrainedTokenizer {
362- constructor(tokenizerJSON: any, tokenizerConfig: any);
363- DEFAULT_SYSTEM_PROMPT: string;
364- use_default_system_prompt: any;
365- legacy: any;
366- get default_chat_template(): any;
367-}
368-export class CodeLlamaTokenizer extends LlamaTokenizer {
369-}
370-export class XLMRobertaTokenizer extends PreTrainedTokenizer {
371-}
372-export class MPNetTokenizer extends PreTrainedTokenizer {
373-}
374-export class FalconTokenizer extends PreTrainedTokenizer {
375-}
376-export class GPTNeoXTokenizer extends PreTrainedTokenizer {
377-}
378-export class EsmTokenizer extends PreTrainedTokenizer {
379-}
395+ constructor(tokenizerJSON: any, tokenizerConfig: any);
396+ DEFAULT_SYSTEM_PROMPT: string;
397+ use_default_system_prompt: any;
398+ legacy: any;
399+ get default_chat_template(): any;
400+}
401+export class CodeLlamaTokenizer extends LlamaTokenizer {}
402+export class XLMRobertaTokenizer extends PreTrainedTokenizer {}
403+export class MPNetTokenizer extends PreTrainedTokenizer {}
404+export class FalconTokenizer extends PreTrainedTokenizer {}
405+export class GPTNeoXTokenizer extends PreTrainedTokenizer {}
406+export class EsmTokenizer extends PreTrainedTokenizer {}
380407 /**
381408 * The NllbTokenizer class is used to tokenize text for NLLB ("No Language Left Behind") models.
382409 *
@@ -391,18 +418,22 @@
391418 * @see {@link https://github.com/facebookresearch/flores/blob/main/flores200/README.md#languages-in-flores-200}
392419 */
393420 export class NllbTokenizer extends PreTrainedTokenizer {
394- constructor(tokenizerJSON: any, tokenizerConfig: any);
395- languageRegex: RegExp;
396- language_codes: any[];
397- lang_to_token: (x: any) => any;
398- /**
399- * Helper function to build translation inputs for an `NllbTokenizer`.
400- * @param {string|string[]} raw_inputs The text to tokenize.
401- * @param {Object} tokenizer_options Options to be sent to the tokenizer
402- * @param {Object} generate_kwargs Generation options.
403- * @returns {Object} Object to be passed to the model.
404- */
405- _build_translation_inputs(raw_inputs: string | string[], tokenizer_options: any, generate_kwargs: any): any;
421+ constructor(tokenizerJSON: any, tokenizerConfig: any);
422+ languageRegex: RegExp;
423+ language_codes: any[];
424+ lang_to_token: (x: any) => any;
425+ /**
426+ * Helper function to build translation inputs for an `NllbTokenizer`.
427+ * @param {string|string[]} raw_inputs The text to tokenize.
428+ * @param {Object} tokenizer_options Options to be sent to the tokenizer
429+ * @param {Object} generate_kwargs Generation options.
430+ * @returns {Object} Object to be passed to the model.
431+ */
432+ _build_translation_inputs(
433+ raw_inputs: string | string[],
434+ tokenizer_options: any,
435+ generate_kwargs: any,
436+ ): any;
406437 }
407438 /**
408439 * The M2M100Tokenizer class is used to tokenize text for M2M100 ("Many-to-Many") models.
@@ -415,157 +446,170 @@
415446 * @see {@link https://huggingface.co/facebook/m2m100_418M#languages-covered}
416447 */
417448 export class M2M100Tokenizer extends PreTrainedTokenizer {
418- constructor(tokenizerJSON: any, tokenizerConfig: any);
419- languageRegex: RegExp;
420- language_codes: any[];
421- lang_to_token: (x: any) => string;
422- /**
423- * Helper function to build translation inputs for an `M2M100Tokenizer`.
424- * @param {string|string[]} raw_inputs The text to tokenize.
425- * @param {Object} tokenizer_options Options to be sent to the tokenizer
426- * @param {Object} generate_kwargs Generation options.
427- * @returns {Object} Object to be passed to the model.
428- */
429- _build_translation_inputs(raw_inputs: string | string[], tokenizer_options: any, generate_kwargs: any): any;
449+ constructor(tokenizerJSON: any, tokenizerConfig: any);
450+ languageRegex: RegExp;
451+ language_codes: any[];
452+ lang_to_token: (x: any) => string;
453+ /**
454+ * Helper function to build translation inputs for an `M2M100Tokenizer`.
455+ * @param {string|string[]} raw_inputs The text to tokenize.
456+ * @param {Object} tokenizer_options Options to be sent to the tokenizer
457+ * @param {Object} generate_kwargs Generation options.
458+ * @returns {Object} Object to be passed to the model.
459+ */
460+ _build_translation_inputs(
461+ raw_inputs: string | string[],
462+ tokenizer_options: any,
463+ generate_kwargs: any,
464+ ): any;
430465 }
431466 /**
432467 * WhisperTokenizer tokenizer
433468 * @extends PreTrainedTokenizer
434469 */
435470 export class WhisperTokenizer extends PreTrainedTokenizer {
436- /**
437- * Decodes automatic speech recognition (ASR) sequences.
438- * @param {Array<{tokens: number[], token_timestamps?: number[], stride: number[]}>} sequences The sequences to decode.
439- * @param {Object} options The options to use for decoding.
440- * @returns {Array<string|{chunks?: undefined|Array<{language: string|null, timestamp: Array<number|null>, text: string}>}>} The decoded sequences.
441- */
442- _decode_asr(sequences: Array<{
443- tokens: number[];
444- token_timestamps?: number[];
445- stride: number[];
446- }>, { return_timestamps, return_language, time_precision, force_full_sequences }?: any): (string | {
447- chunks?: undefined | Array<{
448- language: string | null;
449- timestamp: Array<number | null>;
450- text: string;
451- }>;
452- })[];
453- /**
454- * Finds the longest common sequence among the provided sequences.
455- * @param {number[][]} sequences An array of sequences of token ids to compare.
456- * @returns {number[][]} The longest common sequence found.
457- * @throws {Error} If there is a bug within the function.
458- * @private
459- */
460- private findLongestCommonSequence;
461- /** @private */
462- private collateWordTimestamps;
463- /**
464- * Groups tokens by word. Returns a tuple containing a list of strings with the words,
465- * and a list of `token_id` sequences with the tokens making up each word.
466- * @param {number[]} tokens
467- * @param {string} [language]
468- * @param {string} prepend_punctionations
469- * @param {string} append_punctuations
470- *
471- * @private
472- */
473- private combineTokensIntoWords;
474- /**
475- * @param {number[]} token_ids List of token IDs to decode.
476- * @param {Object} decode_args Optional arguments for decoding
477- * @private
478- */
479- private decodeWithTimestamps;
480- /**
481- * Combine tokens into words by splitting at any position where the tokens are decoded as valid unicode points.
482- * @param {number[]} tokens
483- * @returns {*}
484- * @private
485- */
486- private splitTokensOnUnicode;
487- /**
488- * Combine tokens into words by splitting at whitespace and punctuation tokens.
489- * @param {number[]} tokens
490- * @private
491- */
492- private splitTokensOnSpaces;
493- /**
494- * Merges punctuation tokens with neighboring words.
495- * @param {string[]} words
496- * @param {number[][]} tokens
497- * @param {number[][]} indices
498- * @param {string} prepended
499- * @param {string} appended
500- * @private
501- */
502- private mergePunctuations;
503- /**
504- * Helper function to build translation inputs for a `WhisperTokenizer`,
505- * depending on the language, task, and whether to predict timestamp tokens.
506- *
507- * Used to override the prefix tokens appended to the start of the label sequence.
508- *
509- * **Example: Get ids for a language**
510- * ```javascript
511- * // instantiate the tokenizer and set the prefix token to Spanish
512- * const tokenizer = await WhisperTokenizer.from_pretrained('Xenova/whisper-tiny');
513- * const forced_decoder_ids = tokenizer.get_decoder_prompt_ids({ language: 'spanish' });
514- * // [(1, 50262), (2, 50363)]
515- * ```
516- *
517- * @param {Object} options Options to generate the decoder prompt.
518- * @param {string} [options.language] The language of the transcription text.
519- * The corresponding language id token is appended to the start of the sequence for multilingual
520- * speech recognition and speech translation tasks, e.g. for "Spanish" the token "<|es|>" is appended
521- * to the start of sequence.
522- * @param {string} [options.task] Task identifier to append at the start of sequence (if any).
523- * This should be used for mulitlingual fine-tuning, with "transcribe" for speech recognition and
524- * "translate" for speech translation.
525- * @param {boolean} [options.no_timestamps] Whether to add the <|notimestamps|> token at the start of the sequence.
526- * @returns {number[][]} The decoder prompt ids.
527- */
528- get_decoder_prompt_ids({ language, task, no_timestamps, }?: {
529- language?: string;
530- task?: string;
531- no_timestamps?: boolean;
532- }): number[][];
533-}
534-export class CodeGenTokenizer extends PreTrainedTokenizer {
535-}
536-export class CLIPTokenizer extends PreTrainedTokenizer {
537-}
538-export class SiglipTokenizer extends PreTrainedTokenizer {
539-}
471+ /**
472+ * Decodes automatic speech recognition (ASR) sequences.
473+ * @param {Array<{tokens: number[], token_timestamps?: number[], stride: number[]}>} sequences The sequences to decode.
474+ * @param {Object} options The options to use for decoding.
475+ * @returns {Array<string|{chunks?: undefined|Array<{language: string|null, timestamp: Array<number|null>, text: string}>}>} The decoded sequences.
476+ */
477+ _decode_asr(
478+ sequences: Array<{
479+ tokens: number[];
480+ token_timestamps?: number[];
481+ stride: number[];
482+ }>,
483+ {
484+ return_timestamps,
485+ return_language,
486+ time_precision,
487+ force_full_sequences,
488+ }?: any,
489+ ): (
490+ | string
491+ | {
492+ chunks?:
493+ | undefined
494+ | Array<{
495+ language: string | null;
496+ timestamp: Array<number | null>;
497+ text: string;
498+ }>;
499+ }
500+ )[];
501+ /**
502+ * Finds the longest common sequence among the provided sequences.
503+ * @param {number[][]} sequences An array of sequences of token ids to compare.
504+ * @returns {number[][]} The longest common sequence found.
505+ * @throws {Error} If there is a bug within the function.
506+ * @private
507+ */
508+ private findLongestCommonSequence;
509+ /** @private */
510+ private collateWordTimestamps;
511+ /**
512+ * Groups tokens by word. Returns a tuple containing a list of strings with the words,
513+ * and a list of `token_id` sequences with the tokens making up each word.
514+ * @param {number[]} tokens
515+ * @param {string} [language]
516+ * @param {string} prepend_punctionations
517+ * @param {string} append_punctuations
518+ *
519+ * @private
520+ */
521+ private combineTokensIntoWords;
522+ /**
523+ * @param {number[]} token_ids List of token IDs to decode.
524+ * @param {Object} decode_args Optional arguments for decoding
525+ * @private
526+ */
527+ private decodeWithTimestamps;
528+ /**
529+ * Combine tokens into words by splitting at any position where the tokens are decoded as valid unicode points.
530+ * @param {number[]} tokens
531+ * @returns {*}
532+ * @private
533+ */
534+ private splitTokensOnUnicode;
535+ /**
536+ * Combine tokens into words by splitting at whitespace and punctuation tokens.
537+ * @param {number[]} tokens
538+ * @private
539+ */
540+ private splitTokensOnSpaces;
541+ /**
542+ * Merges punctuation tokens with neighboring words.
543+ * @param {string[]} words
544+ * @param {number[][]} tokens
545+ * @param {number[][]} indices
546+ * @param {string} prepended
547+ * @param {string} appended
548+ * @private
549+ */
550+ private mergePunctuations;
551+ /**
552+ * Helper function to build translation inputs for a `WhisperTokenizer`,
553+ * depending on the language, task, and whether to predict timestamp tokens.
554+ *
555+ * Used to override the prefix tokens appended to the start of the label sequence.
556+ *
557+ * **Example: Get ids for a language**
558+ * ```javascript
559+ * // instantiate the tokenizer and set the prefix token to Spanish
560+ * const tokenizer = await WhisperTokenizer.from_pretrained('Xenova/whisper-tiny');
561+ * const forced_decoder_ids = tokenizer.get_decoder_prompt_ids({ language: 'spanish' });
562+ * // [(1, 50262), (2, 50363)]
563+ * ```
564+ *
565+ * @param {Object} options Options to generate the decoder prompt.
566+ * @param {string} [options.language] The language of the transcription text.
567+ * The corresponding language id token is appended to the start of the sequence for multilingual
568+ * speech recognition and speech translation tasks, e.g. for "Spanish" the token "<|es|>" is appended
569+ * to the start of sequence.
570+ * @param {string} [options.task] Task identifier to append at the start of sequence (if any).
571+ * This should be used for mulitlingual fine-tuning, with "transcribe" for speech recognition and
572+ * "translate" for speech translation.
573+ * @param {boolean} [options.no_timestamps] Whether to add the <|notimestamps|> token at the start of the sequence.
574+ * @returns {number[][]} The decoder prompt ids.
575+ */
576+ get_decoder_prompt_ids({
577+ language,
578+ task,
579+ no_timestamps,
580+ }?: {
581+ language?: string;
582+ task?: string;
583+ no_timestamps?: boolean;
584+ }): number[][];
585+}
586+export class CodeGenTokenizer extends PreTrainedTokenizer {}
587+export class CLIPTokenizer extends PreTrainedTokenizer {}
588+export class SiglipTokenizer extends PreTrainedTokenizer {}
540589 /**
541590 * @todo This model is not yet supported by Hugging Face's "fast" tokenizers library (https://github.com/huggingface/tokenizers).
542591 * Therefore, this implementation (which is based on fast tokenizers) may produce slightly inaccurate results.
543592 */
544593 export class MarianTokenizer extends PreTrainedTokenizer {
545- languageRegex: RegExp;
546- supported_language_codes: string[];
547- /**
548- * Encodes a single text. Overriding this method is necessary since the language codes
549- * must be removed before encoding with sentencepiece model.
550- * @see https://github.com/huggingface/transformers/blob/12d51db243a00726a548a43cc333390ebae731e3/src/transformers/models/marian/tokenization_marian.py#L204-L213
551- *
552- * @param {string|null} text The text to encode.
553- * @returns {Array} The encoded tokens.
554- */
555- _encode_text(text: string | null): any[];
556-}
557-export class Wav2Vec2CTCTokenizer extends PreTrainedTokenizer {
558-}
559-export class BlenderbotTokenizer extends PreTrainedTokenizer {
560-}
561-export class BlenderbotSmallTokenizer extends BlenderbotTokenizer {
562-}
563-export class SpeechT5Tokenizer extends PreTrainedTokenizer {
564-}
565-export class NougatTokenizer extends PreTrainedTokenizer {
566-}
594+ languageRegex: RegExp;
595+ supported_language_codes: string[];
596+ /**
597+ * Encodes a single text. Overriding this method is necessary since the language codes
598+ * must be removed before encoding with sentencepiece model.
599+ * @see https://github.com/huggingface/transformers/blob/12d51db243a00726a548a43cc333390ebae731e3/src/transformers/models/marian/tokenization_marian.py#L204-L213
600+ *
601+ * @param {string|null} text The text to encode.
602+ * @returns {Array} The encoded tokens.
603+ */
604+ _encode_text(text: string | null): any[];
605+}
606+export class Wav2Vec2CTCTokenizer extends PreTrainedTokenizer {}
607+export class BlenderbotTokenizer extends PreTrainedTokenizer {}
608+export class BlenderbotSmallTokenizer extends BlenderbotTokenizer {}
609+export class SpeechT5Tokenizer extends PreTrainedTokenizer {}
610+export class NougatTokenizer extends PreTrainedTokenizer {}
567611 export class VitsTokenizer extends PreTrainedTokenizer {
568- constructor(tokenizerJSON: any, tokenizerConfig: any);
612+ constructor(tokenizerJSON: any, tokenizerConfig: any);
569613 }
570614 /**
571615 * Helper class which is used to instantiate pretrained tokenizers with the `from_pretrained` function.
@@ -575,163 +619,180 @@
575619 * const tokenizer = await AutoTokenizer.from_pretrained('Xenova/bert-base-uncased');
576620 */
577621 export class AutoTokenizer {
578- static TOKENIZER_CLASS_MAPPING: {
579- T5Tokenizer: typeof T5Tokenizer;
580- DistilBertTokenizer: typeof DistilBertTokenizer;
581- CamembertTokenizer: typeof CamembertTokenizer;
582- DebertaTokenizer: typeof DebertaTokenizer;
583- DebertaV2Tokenizer: typeof DebertaV2Tokenizer;
584- BertTokenizer: typeof BertTokenizer;
585- HerbertTokenizer: typeof HerbertTokenizer;
586- ConvBertTokenizer: typeof ConvBertTokenizer;
587- RoFormerTokenizer: typeof RoFormerTokenizer;
588- XLMTokenizer: typeof XLMTokenizer;
589- ElectraTokenizer: typeof ElectraTokenizer;
590- MobileBertTokenizer: typeof MobileBertTokenizer;
591- SqueezeBertTokenizer: typeof SqueezeBertTokenizer;
592- AlbertTokenizer: typeof AlbertTokenizer;
593- GPT2Tokenizer: typeof GPT2Tokenizer;
594- BartTokenizer: typeof BartTokenizer;
595- MBartTokenizer: typeof MBartTokenizer;
596- MBart50Tokenizer: typeof MBart50Tokenizer;
597- RobertaTokenizer: typeof RobertaTokenizer;
598- WhisperTokenizer: typeof WhisperTokenizer;
599- CodeGenTokenizer: typeof CodeGenTokenizer;
600- CLIPTokenizer: typeof CLIPTokenizer;
601- SiglipTokenizer: typeof SiglipTokenizer;
602- MarianTokenizer: typeof MarianTokenizer;
603- BloomTokenizer: typeof BloomTokenizer;
604- NllbTokenizer: typeof NllbTokenizer;
605- M2M100Tokenizer: typeof M2M100Tokenizer;
606- LlamaTokenizer: typeof LlamaTokenizer;
607- CodeLlamaTokenizer: typeof CodeLlamaTokenizer;
608- XLMRobertaTokenizer: typeof XLMRobertaTokenizer;
609- MPNetTokenizer: typeof MPNetTokenizer;
610- FalconTokenizer: typeof FalconTokenizer;
611- GPTNeoXTokenizer: typeof GPTNeoXTokenizer;
612- EsmTokenizer: typeof EsmTokenizer;
613- Wav2Vec2CTCTokenizer: typeof Wav2Vec2CTCTokenizer;
614- BlenderbotTokenizer: typeof BlenderbotTokenizer;
615- BlenderbotSmallTokenizer: typeof BlenderbotSmallTokenizer;
616- SpeechT5Tokenizer: typeof SpeechT5Tokenizer;
617- NougatTokenizer: typeof NougatTokenizer;
618- VitsTokenizer: typeof VitsTokenizer;
619- PreTrainedTokenizer: typeof PreTrainedTokenizer;
620- };
621- /**
622- * Instantiate one of the tokenizer classes of the library from a pretrained model.
623- *
624- * The tokenizer class to instantiate is selected based on the `tokenizer_class` property of the config object
625- * (either passed as an argument or loaded from `pretrained_model_name_or_path` if possible)
626- *
627- * @param {string} pretrained_model_name_or_path The name or path of the pretrained model. Can be either:
628- * - A string, the *model id* of a pretrained tokenizer hosted inside a model repo on huggingface.co.
629- * Valid model ids can be located at the root-level, like `bert-base-uncased`, or namespaced under a
630- * user or organization name, like `dbmdz/bert-base-german-cased`.
631- * - A path to a *directory* containing tokenizer files, e.g., `./my_model_directory/`.
632- * @param {PretrainedTokenizerOptions} options Additional options for loading the tokenizer.
633- *
634- * @returns {Promise<PreTrainedTokenizer>} A new instance of the PreTrainedTokenizer class.
635- */
636- static from_pretrained(pretrained_model_name_or_path: string, { quantized, progress_callback, config, cache_dir, local_files_only, revision, legacy, }?: PretrainedTokenizerOptions): Promise<PreTrainedTokenizer>;
622+ static TOKENIZER_CLASS_MAPPING: {
623+ T5Tokenizer: typeof T5Tokenizer;
624+ DistilBertTokenizer: typeof DistilBertTokenizer;
625+ CamembertTokenizer: typeof CamembertTokenizer;
626+ DebertaTokenizer: typeof DebertaTokenizer;
627+ DebertaV2Tokenizer: typeof DebertaV2Tokenizer;
628+ BertTokenizer: typeof BertTokenizer;
629+ HerbertTokenizer: typeof HerbertTokenizer;
630+ ConvBertTokenizer: typeof ConvBertTokenizer;
631+ RoFormerTokenizer: typeof RoFormerTokenizer;
632+ XLMTokenizer: typeof XLMTokenizer;
633+ ElectraTokenizer: typeof ElectraTokenizer;
634+ MobileBertTokenizer: typeof MobileBertTokenizer;
635+ SqueezeBertTokenizer: typeof SqueezeBertTokenizer;
636+ AlbertTokenizer: typeof AlbertTokenizer;
637+ GPT2Tokenizer: typeof GPT2Tokenizer;
638+ BartTokenizer: typeof BartTokenizer;
639+ MBartTokenizer: typeof MBartTokenizer;
640+ MBart50Tokenizer: typeof MBart50Tokenizer;
641+ RobertaTokenizer: typeof RobertaTokenizer;
642+ WhisperTokenizer: typeof WhisperTokenizer;
643+ CodeGenTokenizer: typeof CodeGenTokenizer;
644+ CLIPTokenizer: typeof CLIPTokenizer;
645+ SiglipTokenizer: typeof SiglipTokenizer;
646+ MarianTokenizer: typeof MarianTokenizer;
647+ BloomTokenizer: typeof BloomTokenizer;
648+ NllbTokenizer: typeof NllbTokenizer;
649+ M2M100Tokenizer: typeof M2M100Tokenizer;
650+ LlamaTokenizer: typeof LlamaTokenizer;
651+ CodeLlamaTokenizer: typeof CodeLlamaTokenizer;
652+ XLMRobertaTokenizer: typeof XLMRobertaTokenizer;
653+ MPNetTokenizer: typeof MPNetTokenizer;
654+ FalconTokenizer: typeof FalconTokenizer;
655+ GPTNeoXTokenizer: typeof GPTNeoXTokenizer;
656+ EsmTokenizer: typeof EsmTokenizer;
657+ Wav2Vec2CTCTokenizer: typeof Wav2Vec2CTCTokenizer;
658+ BlenderbotTokenizer: typeof BlenderbotTokenizer;
659+ BlenderbotSmallTokenizer: typeof BlenderbotSmallTokenizer;
660+ SpeechT5Tokenizer: typeof SpeechT5Tokenizer;
661+ NougatTokenizer: typeof NougatTokenizer;
662+ VitsTokenizer: typeof VitsTokenizer;
663+ PreTrainedTokenizer: typeof PreTrainedTokenizer;
664+ };
665+ /**
666+ * Instantiate one of the tokenizer classes of the library from a pretrained model.
667+ *
668+ * The tokenizer class to instantiate is selected based on the `tokenizer_class` property of the config object
669+ * (either passed as an argument or loaded from `pretrained_model_name_or_path` if possible)
670+ *
671+ * @param {string} pretrained_model_name_or_path The name or path of the pretrained model. Can be either:
672+ * - A string, the *model id* of a pretrained tokenizer hosted inside a model repo on huggingface.co.
673+ * Valid model ids can be located at the root-level, like `bert-base-uncased`, or namespaced under a
674+ * user or organization name, like `dbmdz/bert-base-german-cased`.
675+ * - A path to a *directory* containing tokenizer files, e.g., `./my_model_directory/`.
676+ * @param {PretrainedTokenizerOptions} options Additional options for loading the tokenizer.
677+ *
678+ * @returns {Promise<PreTrainedTokenizer>} A new instance of the PreTrainedTokenizer class.
679+ */
680+ static from_pretrained(
681+ pretrained_model_name_or_path: string,
682+ {
683+ quantized,
684+ progress_callback,
685+ config,
686+ cache_dir,
687+ local_files_only,
688+ revision,
689+ legacy,
690+ }?: PretrainedTokenizerOptions,
691+ ): Promise<PreTrainedTokenizer>;
637692 }
638693 /**
639694 * Additional tokenizer-specific properties.
640695 */
641696 export type TokenizerProperties = {
642- /**
643- * Whether or not the `legacy` behavior of the tokenizer should be used.
644- */
645- legacy?: boolean;
697+ /**
698+ * Whether or not the `legacy` behavior of the tokenizer should be used.
699+ */
700+ legacy?: boolean;
646701 };
647-export type PretrainedTokenizerOptions = import('./utils/hub.js').PretrainedOptions & TokenizerProperties;
702+export type PretrainedTokenizerOptions =
703+ import("./utils/hub.js").PretrainedOptions & TokenizerProperties;
648704 export type BPENode = {
649- /**
650- * The token associated with the node
651- */
652- token: string;
653- /**
654- * A positional bias for the node.
655- */
656- bias: number;
657- /**
658- * The score of the node.
659- */
660- score?: number;
661- /**
662- * The previous node in the linked list.
663- */
664- prev?: BPENode;
665- /**
666- * The next node in the linked list.
667- */
668- next?: BPENode;
705+ /**
706+ * The token associated with the node
707+ */
708+ token: string;
709+ /**
710+ * A positional bias for the node.
711+ */
712+ bias: number;
713+ /**
714+ * The score of the node.
715+ */
716+ score?: number;
717+ /**
718+ * The previous node in the linked list.
719+ */
720+ prev?: BPENode;
721+ /**
722+ * The next node in the linked list.
723+ */
724+ next?: BPENode;
669725 };
670-export type SplitDelimiterBehavior = 'removed' | 'isolated' | 'mergedWithPrevious' | 'mergedWithNext' | 'contiguous';
726+export type SplitDelimiterBehavior =
727+ | "removed"
728+ | "isolated"
729+ | "mergedWithPrevious"
730+ | "mergedWithNext"
731+ | "contiguous";
671732 export type PostProcessedOutput = {
672- /**
673- * List of token produced by the post-processor.
674- */
675- tokens: string[];
676- /**
677- * List of token type ids produced by the post-processor.
678- */
679- token_type_ids?: number[];
733+ /**
734+ * List of token produced by the post-processor.
735+ */
736+ tokens: string[];
737+ /**
738+ * List of token type ids produced by the post-processor.
739+ */
740+ token_type_ids?: number[];
680741 };
681742 export type EncodingSingle = {
682- /**
683- * List of token ids to be fed to a model.
684- */
685- input_ids: number[];
686- /**
687- * List of token type ids to be fed to a model
688- */
689- attention_mask: number[];
690- /**
691- * List of indices specifying which tokens should be attended to by the model
692- */
693- token_type_ids?: number[];
743+ /**
744+ * List of token ids to be fed to a model.
745+ */
746+ input_ids: number[];
747+ /**
748+ * List of token type ids to be fed to a model
749+ */
750+ attention_mask: number[];
751+ /**
752+ * List of indices specifying which tokens should be attended to by the model
753+ */
754+ token_type_ids?: number[];
694755 };
695756 declare const Normalizer_base: new () => {
696- (...args: any[]): any;
697- _call(...args: any[]): any;
757+ (...args: any[]): any;
758+ _call(...args: any[]): any;
698759 };
699760 /**
700761 * A base class for text normalization.
701762 * @abstract
702763 */
703764 declare class Normalizer extends Normalizer_base {
704- /**
705- * Factory method for creating normalizers from config objects.
706- * @static
707- * @param {Object} config The configuration object for the normalizer.
708- * @returns {Normalizer} A Normalizer object.
709- * @throws {Error} If an unknown Normalizer type is specified in the config.
710- */
711- static fromConfig(config: any): Normalizer;
712- /**
713- * @param {Object} config The configuration object for the normalizer.
714- */
715- constructor(config: any);
716- config: any;
717- /**
718- * Normalize the input text.
719- * @abstract
720- * @param {string} text The text to normalize.
721- * @returns {string} The normalized text.
722- * @throws {Error} If this method is not implemented in a subclass.
723- */
724- normalize(text: string): string;
725- /**
726- * Alias for {@link Normalizer#normalize}.
727- * @param {string} text The text to normalize.
728- * @returns {string} The normalized text.
729- */
730- _call(text: string): string;
765+ /**
766+ * Factory method for creating normalizers from config objects.
767+ * @static
768+ * @param {Object} config The configuration object for the normalizer.
769+ * @returns {Normalizer} A Normalizer object.
770+ * @throws {Error} If an unknown Normalizer type is specified in the config.
771+ */
772+ static fromConfig(config: any): Normalizer;
773+ /**
774+ * @param {Object} config The configuration object for the normalizer.
775+ */
776+ constructor(config: any);
777+ config: any;
778+ /**
779+ * Normalize the input text.
780+ * @abstract
781+ * @param {string} text The text to normalize.
782+ * @returns {string} The normalized text.
783+ * @throws {Error} If this method is not implemented in a subclass.
784+ */
785+ normalize(text: string): string;
786+ /**
787+ * Alias for {@link Normalizer#normalize}.
788+ * @param {string} text The text to normalize.
789+ * @returns {string} The normalized text.
790+ */
791+ _call(text: string): string;
731792 }
732793 declare const PreTokenizer_base: new () => {
733- (...args: any[]): any;
734- _call(...args: any[]): any;
794+ (...args: any[]): any;
795+ _call(...args: any[]): any;
735796 };
736797 /**
737798 * A callable class representing a pre-tokenizer used in tokenization. Subclasses
@@ -739,7 +800,7 @@
739800 * @extends Callable
740801 */
741802 declare class PreTokenizer extends PreTokenizer_base {
742- /**
803+ /**
743804 * Factory method that returns an instance of a subclass of `PreTokenizer` based on the provided configuration.
744805 *
745806 * @static
@@ -747,35 +808,35 @@
747808 * @returns {PreTokenizer} An instance of a subclass of `PreTokenizer`.
748809 * @throws {Error} If the provided configuration object does not correspond to any known pre-tokenizer.
749810 */
750- static fromConfig(config: any): PreTokenizer;
751- /**
752- * Method that should be implemented by subclasses to define the specific pre-tokenization logic.
753- *
754- * @abstract
755- * @param {string} text The text to pre-tokenize.
756- * @param {Object} [options] Additional options for the pre-tokenization logic.
757- * @returns {string[]} The pre-tokenized text.
758- * @throws {Error} If the method is not implemented in the subclass.
759- */
760- pre_tokenize_text(text: string, options?: any): string[];
761- /**
762- * Tokenizes the given text into pre-tokens.
763- * @param {string|string[]} text The text or array of texts to pre-tokenize.
764- * @param {Object} [options] Additional options for the pre-tokenization logic.
765- * @returns {string[]} An array of pre-tokens.
766- */
767- pre_tokenize(text: string | string[], options?: any): string[];
768- /**
769- * Alias for {@link PreTokenizer#pre_tokenize}.
770- * @param {string|string[]} text The text or array of texts to pre-tokenize.
771- * @param {Object} [options] Additional options for the pre-tokenization logic.
772- * @returns {string[]} An array of pre-tokens.
773- */
774- _call(text: string | string[], options?: any): string[];
811+ static fromConfig(config: any): PreTokenizer;
812+ /**
813+ * Method that should be implemented by subclasses to define the specific pre-tokenization logic.
814+ *
815+ * @abstract
816+ * @param {string} text The text to pre-tokenize.
817+ * @param {Object} [options] Additional options for the pre-tokenization logic.
818+ * @returns {string[]} The pre-tokenized text.
819+ * @throws {Error} If the method is not implemented in the subclass.
820+ */
821+ pre_tokenize_text(text: string, options?: any): string[];
822+ /**
823+ * Tokenizes the given text into pre-tokens.
824+ * @param {string|string[]} text The text or array of texts to pre-tokenize.
825+ * @param {Object} [options] Additional options for the pre-tokenization logic.
826+ * @returns {string[]} An array of pre-tokens.
827+ */
828+ pre_tokenize(text: string | string[], options?: any): string[];
829+ /**
830+ * Alias for {@link PreTokenizer#pre_tokenize}.
831+ * @param {string|string[]} text The text or array of texts to pre-tokenize.
832+ * @param {Object} [options] Additional options for the pre-tokenization logic.
833+ * @returns {string[]} An array of pre-tokens.
834+ */
835+ _call(text: string | string[], options?: any): string[];
775836 }
776837 declare const PostProcessor_base: new () => {
777- (...args: any[]): any;
778- _call(...args: any[]): any;
838+ (...args: any[]): any;
839+ _call(...args: any[]): any;
779840 };
780841 /**
781842 * @typedef {Object} PostProcessedOutput
@@ -792,85 +853,85 @@
792853 * @extends Callable
793854 */
794855 declare class PostProcessor extends PostProcessor_base {
795- /**
796- * Factory method to create a PostProcessor object from a configuration object.
797- *
798- * @param {Object} config Configuration object representing a PostProcessor.
799- * @returns {PostProcessor} A PostProcessor object created from the given configuration.
800- * @throws {Error} If an unknown PostProcessor type is encountered.
801- */
802- static fromConfig(config: any): PostProcessor;
803- /**
804- * @param {Object} config The configuration for the post-processor.
805- */
806- constructor(config: any);
807- config: any;
808- /**
809- * Method to be implemented in subclass to apply post-processing on the given tokens.
810- *
811- * @param {Array} tokens The input tokens to be post-processed.
812- * @param {...*} args Additional arguments required by the post-processing logic.
813- * @returns {PostProcessedOutput} The post-processed tokens.
814- * @throws {Error} If the method is not implemented in subclass.
815- */
816- post_process(tokens: any[], ...args: any[]): PostProcessedOutput;
817- /**
818- * Alias for {@link PostProcessor#post_process}.
819- * @param {Array} tokens The text or array of texts to post-process.
820- * @param {...*} args Additional arguments required by the post-processing logic.
821- * @returns {PostProcessedOutput} The post-processed tokens.
822- */
823- _call(tokens: any[], ...args: any[]): PostProcessedOutput;
856+ /**
857+ * Factory method to create a PostProcessor object from a configuration object.
858+ *
859+ * @param {Object} config Configuration object representing a PostProcessor.
860+ * @returns {PostProcessor} A PostProcessor object created from the given configuration.
861+ * @throws {Error} If an unknown PostProcessor type is encountered.
862+ */
863+ static fromConfig(config: any): PostProcessor;
864+ /**
865+ * @param {Object} config The configuration for the post-processor.
866+ */
867+ constructor(config: any);
868+ config: any;
869+ /**
870+ * Method to be implemented in subclass to apply post-processing on the given tokens.
871+ *
872+ * @param {Array} tokens The input tokens to be post-processed.
873+ * @param {...*} args Additional arguments required by the post-processing logic.
874+ * @returns {PostProcessedOutput} The post-processed tokens.
875+ * @throws {Error} If the method is not implemented in subclass.
876+ */
877+ post_process(tokens: any[], ...args: any[]): PostProcessedOutput;
878+ /**
879+ * Alias for {@link PostProcessor#post_process}.
880+ * @param {Array} tokens The text or array of texts to post-process.
881+ * @param {...*} args Additional arguments required by the post-processing logic.
882+ * @returns {PostProcessedOutput} The post-processed tokens.
883+ */
884+ _call(tokens: any[], ...args: any[]): PostProcessedOutput;
824885 }
825886 declare const Decoder_base: new () => {
826- (...args: any[]): any;
827- _call(...args: any[]): any;
887+ (...args: any[]): any;
888+ _call(...args: any[]): any;
828889 };
829890 /**
830891 * The base class for token decoders.
831892 * @extends Callable
832893 */
833894 declare class Decoder extends Decoder_base {
834- /**
895+ /**
835896 * Creates a decoder instance based on the provided configuration.
836897 *
837898 * @param {Object} config The configuration object.
838899 * @returns {Decoder} A decoder instance.
839900 * @throws {Error} If an unknown decoder type is provided.
840901 */
841- static fromConfig(config: any): Decoder;
842- /**
843- * Creates an instance of `Decoder`.
844- *
845- * @param {Object} config The configuration object.
846- */
847- constructor(config: any);
848- config: any;
849- /** @type {AddedToken[]} */
850- added_tokens: AddedToken[];
851- end_of_word_suffix: any;
852- trim_offsets: any;
853- /**
854- * Calls the `decode` method.
855- *
856- * @param {string[]} tokens The list of tokens.
857- * @returns {string} The decoded string.
858- */
859- _call(tokens: string[]): string;
860- /**
861- * Decodes a list of tokens.
862- * @param {string[]} tokens The list of tokens.
863- * @returns {string} The decoded string.
864- */
865- decode(tokens: string[]): string;
866- /**
867- * Apply the decoder to a list of tokens.
868- *
869- * @param {string[]} tokens The list of tokens.
870- * @returns {string[]} The decoded list of tokens.
871- * @throws {Error} If the `decode_chain` method is not implemented in the subclass.
872- */
873- decode_chain(tokens: string[]): string[];
902+ static fromConfig(config: any): Decoder;
903+ /**
904+ * Creates an instance of `Decoder`.
905+ *
906+ * @param {Object} config The configuration object.
907+ */
908+ constructor(config: any);
909+ config: any;
910+ /** @type {AddedToken[]} */
911+ added_tokens: AddedToken[];
912+ end_of_word_suffix: any;
913+ trim_offsets: any;
914+ /**
915+ * Calls the `decode` method.
916+ *
917+ * @param {string[]} tokens The list of tokens.
918+ * @returns {string} The decoded string.
919+ */
920+ _call(tokens: string[]): string;
921+ /**
922+ * Decodes a list of tokens.
923+ * @param {string[]} tokens The list of tokens.
924+ * @returns {string} The decoded string.
925+ */
926+ decode(tokens: string[]): string;
927+ /**
928+ * Apply the decoder to a list of tokens.
929+ *
930+ * @param {string[]} tokens The list of tokens.
931+ * @returns {string[]} The decoded list of tokens.
932+ * @throws {Error} If the `decode_chain` method is not implemented in the subclass.
933+ */
934+ decode_chain(tokens: string[]): string[];
874935 }
875936 /**
876937 * Represent a token added by the user on top of the existing Model vocabulary.
@@ -879,34 +940,34 @@
879940 * - Whether to include any whitespace on its left or right
880941 */
881942 declare class AddedToken {
882- /**
883- * Creates a new instance of AddedToken.
884- * @param {Object} config Added token configuration object.
885- * @param {string} config.content The content of the added token.
886- * @param {number} config.id The id of the added token.
887- * @param {boolean} [config.single_word=false] Whether this token must be a single word or can break words.
888- * @param {boolean} [config.lstrip=false] Whether this token should strip whitespaces on its left.
889- * @param {boolean} [config.rstrip=false] Whether this token should strip whitespaces on its right.
890- * @param {boolean} [config.normalized=false] Whether this token should be normalized.
891- * @param {boolean} [config.special=false] Whether this token is special.
892- */
893- constructor(config: {
894- content: string;
895- id: number;
896- single_word?: boolean;
897- lstrip?: boolean;
898- rstrip?: boolean;
899- normalized?: boolean;
900- special?: boolean;
901- });
943+ /**
944+ * Creates a new instance of AddedToken.
945+ * @param {Object} config Added token configuration object.
946+ * @param {string} config.content The content of the added token.
947+ * @param {number} config.id The id of the added token.
948+ * @param {boolean} [config.single_word=false] Whether this token must be a single word or can break words.
949+ * @param {boolean} [config.lstrip=false] Whether this token should strip whitespaces on its left.
950+ * @param {boolean} [config.rstrip=false] Whether this token should strip whitespaces on its right.
951+ * @param {boolean} [config.normalized=false] Whether this token should be normalized.
952+ * @param {boolean} [config.special=false] Whether this token is special.
953+ */
954+ constructor(config: {
902955 content: string;
903956 id: number;
904- single_word: boolean;
905- lstrip: boolean;
906- rstrip: boolean;
907- special: boolean;
908- normalized: boolean;
909-}
910-import { Tensor } from './utils/tensor.js';
957+ single_word?: boolean;
958+ lstrip?: boolean;
959+ rstrip?: boolean;
960+ normalized?: boolean;
961+ special?: boolean;
962+ });
963+ content: string;
964+ id: number;
965+ single_word: boolean;
966+ lstrip: boolean;
967+ rstrip: boolean;
968+ special: boolean;
969+ normalized: boolean;
970+}
971+import { Tensor } from "./utils/tensor.js";
911972 export {};
912-//# sourceMappingURL=tokenizers.d.ts.map
No newline at the end of the file
973+//# sourceMappingURL=tokenizers.d.ts.map
modified core/vendor/modules/@xenova/transformers/types/transformers.d.ts +1 −1
@@ -8,4 +8,4 @@
88 export * from "./utils/image.js";
99 export * from "./utils/tensor.js";
1010 export * from "./utils/maths.js";
11-//# sourceMappingURL=transformers.d.ts.map
No newline at the end of the file
11+//# sourceMappingURL=transformers.d.ts.map
modified core/vendor/modules/@xenova/transformers/types/utils/audio.d.ts +52 −9
@@ -4,7 +4,10 @@
44 * @param {number} sampling_rate The sampling rate to use when decoding the audio.
55 * @returns {Promise<Float32Array>} The decoded audio as a `Float32Array`.
66 */
7-export function read_audio(url: string | URL, sampling_rate: number): Promise<Float32Array>;
7+export function read_audio(
8+ url: string | URL,
9+ sampling_rate: number,
10+): Promise<Float32Array>;
811 /**
912 * Generates a Hanning window of length M.
1013 *
@@ -29,7 +32,16 @@
2932 * @returns {number[][]} Triangular filter bank matrix, which is a 2D array of shape (`num_frequency_bins`, `num_mel_filters`).
3033 * This is a projection matrix to go from a spectrogram to a mel spectrogram.
3134 */
32-export function mel_filter_bank(num_frequency_bins: number, num_mel_filters: number, min_frequency: number, max_frequency: number, sampling_rate: number, norm?: string, mel_scale?: string, triangularize_in_mel_space?: boolean): number[][];
35+export function mel_filter_bank(
36+ num_frequency_bins: number,
37+ num_mel_filters: number,
38+ min_frequency: number,
39+ max_frequency: number,
40+ sampling_rate: number,
41+ norm?: string,
42+ mel_scale?: string,
43+ triangularize_in_mel_space?: boolean,
44+): number[][];
3345 /**
3446 * Calculates a spectrogram over one waveform using the Short-Time Fourier Transform.
3547 *
@@ -81,7 +93,29 @@
8193 * @param {boolean} [options.transpose=false] If `true`, the returned spectrogram will have shape `(num_frames, num_frequency_bins/num_mel_filters)`. If `false`, the returned spectrogram will have shape `(num_frequency_bins/num_mel_filters, num_frames)`.
8294 * @returns {{data: Float32Array, dims: number[]}} Spectrogram of shape `(num_frequency_bins, length)` (regular spectrogram) or shape `(num_mel_filters, length)` (mel spectrogram).
8395 */
84-export function spectrogram(waveform: Float32Array | Float64Array, window: Float32Array | Float64Array, frame_length: number, hop_length: number, { fft_length, power, center, pad_mode, onesided, preemphasis, mel_filters, mel_floor, log_mel, reference, min_value, db_range, remove_dc_offset, max_num_frames, do_pad, transpose, }?: {
96+export function spectrogram(
97+ waveform: Float32Array | Float64Array,
98+ window: Float32Array | Float64Array,
99+ frame_length: number,
100+ hop_length: number,
101+ {
102+ fft_length,
103+ power,
104+ center,
105+ pad_mode,
106+ onesided,
107+ preemphasis,
108+ mel_filters,
109+ mel_floor,
110+ log_mel,
111+ reference,
112+ min_value,
113+ db_range,
114+ remove_dc_offset,
115+ max_num_frames,
116+ do_pad,
117+ transpose,
118+ }?: {
85119 fft_length?: number;
86120 power?: number;
87121 center?: boolean;
@@ -98,9 +132,10 @@
98132 max_num_frames?: number;
99133 do_pad?: boolean;
100134 transpose?: boolean;
101-}): {
102- data: Float32Array;
103- dims: number[];
135+ },
136+): {
137+ data: Float32Array;
138+ dims: number[];
104139 };
105140 /**
106141 * Returns an array containing the specified window.
@@ -113,9 +148,17 @@
113148 * @param {boolean} [options.center=true] Whether to center the window inside the FFT buffer. Only used when `frame_length` is provided.
114149 * @returns {Float64Array} The window of shape `(window_length,)` or `(frame_length,)`.
115150 */
116-export function window_function(window_length: number, name: string, { periodic, frame_length, center, }?: {
151+export function window_function(
152+ window_length: number,
153+ name: string,
154+ {
155+ periodic,
156+ frame_length,
157+ center,
158+ }?: {
117159 periodic?: boolean;
118160 frame_length?: number;
119161 center?: boolean;
120-}): Float64Array;
121-//# sourceMappingURL=audio.d.ts.map
No newline at the end of the file
162+ },
163+): Float64Array;
164+//# sourceMappingURL=audio.d.ts.map
modified core/vendor/modules/@xenova/transformers/types/utils/core.d.ts +3 −3
@@ -93,7 +93,7 @@
9393 * @type {new () => {(...args: any[]): any, _call(...args: any[]): any}}
9494 */
9595 export const Callable: new () => {
96- (...args: any[]): any;
97- _call(...args: any[]): any;
96+ (...args: any[]): any;
97+ _call(...args: any[]): any;
9898 };
99-//# sourceMappingURL=core.d.ts.map
No newline at the end of the file
99+//# sourceMappingURL=core.d.ts.map
modified core/vendor/modules/@xenova/transformers/types/utils/data-structures.d.ts +193 −187
@@ -16,209 +16,215 @@
1616 * - https://github.com/belladoreai/llama-tokenizer-js (minor improvements)
1717 */
1818 export class PriorityQueue {
19- /**
20- * Create a new PriorityQueue.
21- * @param {Function} comparator Comparator function to determine priority. Defaults to a MaxHeap.
22- */
23- constructor(comparator?: Function);
24- _heap: any[];
25- _comparator: Function;
26- /**
27- * The size of the queue
28- */
29- get size(): number;
30- /**
31- * Check if the queue is empty.
32- * @returns {boolean} `true` if the queue is empty, `false` otherwise.
33- */
34- isEmpty(): boolean;
35- /**
36- * Return the element with the highest priority in the queue.
37- * @returns {any} The highest priority element in the queue.
38- */
39- peek(): any;
40- /**
41- * Add one or more elements to the queue.
42- * @param {...any} values The values to push into the queue.
43- * @returns {number} The new size of the queue.
44- */
45- push(...values: any[]): number;
46- /**
47- * Add multiple elements to the queue.
48- * @param {any[]} values The values to push into the queue.
49- * @returns {number} The new size of the queue.
50- */
51- extend(values: any[]): number;
52- /**
53- * Remove and return the element with the highest priority in the queue.
54- * @returns {any} The element with the highest priority in the queue.
55- */
56- pop(): any;
57- /**
58- * Replace the element with the highest priority in the queue with a new value.
59- * @param {*} value The new value.
60- * @returns {*} The replaced value.
61- */
62- replace(value: any): any;
63- /**
64- * Compute the index for the parent of the node at index `i`.
65- * @param {number} i The index of the node to get the parent of.
66- * @returns {number} The index of the parent node.
67- * @private
68- */
69- private _parent;
70- /**
71- * Compute the index for the left child of the node at index `i`.
72- * @param {number} i The index of the node to get the left child of.
73- * @returns {number} The index of the left child.
74- * @private
75- */
76- private _left;
77- /**
78- * Compute the index for the right child of the node at index `i`.
79- * @param {number} i The index of the node to get the right child of.
80- * @returns {number} The index of the right child.
81- * @private
82- */
83- private _right;
84- /**
85- * Check if the element at index `i` is greater than the element at index `j`.
86- * @param {number} i The index of the first element to compare.
87- * @param {number} j The index of the second element to compare.
88- * @returns {boolean} `true` if the element at index `i` is greater than the element at index `j`, `false` otherwise.
89- * @private
90- */
91- private _greater;
92- /**
93- * Swap the elements at indices `i` and `j`.
94- * @param {number} i The index of the first element to swap.
95- * @param {number} j The index of the second element to swap.
96- * @private
97- */
98- private _swap;
99- /**
100- * Maintain the heap property by updating positions in the heap,
101- * starting at the last element and moving up the heap.
102- * @private
103- */
104- private _siftUp;
105- /**
106- * Maintain the heap property by updating positions in the heap,
107- * starting at the first element and moving down the heap.
108- * @private
109- */
110- private _siftDown;
19+ /**
20+ * Create a new PriorityQueue.
21+ * @param {Function} comparator Comparator function to determine priority. Defaults to a MaxHeap.
22+ */
23+ constructor(comparator?: Function);
24+ _heap: any[];
25+ _comparator: Function;
26+ /**
27+ * The size of the queue
28+ */
29+ get size(): number;
30+ /**
31+ * Check if the queue is empty.
32+ * @returns {boolean} `true` if the queue is empty, `false` otherwise.
33+ */
34+ isEmpty(): boolean;
35+ /**
36+ * Return the element with the highest priority in the queue.
37+ * @returns {any} The highest priority element in the queue.
38+ */
39+ peek(): any;
40+ /**
41+ * Add one or more elements to the queue.
42+ * @param {...any} values The values to push into the queue.
43+ * @returns {number} The new size of the queue.
44+ */
45+ push(...values: any[]): number;
46+ /**
47+ * Add multiple elements to the queue.
48+ * @param {any[]} values The values to push into the queue.
49+ * @returns {number} The new size of the queue.
50+ */
51+ extend(values: any[]): number;
52+ /**
53+ * Remove and return the element with the highest priority in the queue.
54+ * @returns {any} The element with the highest priority in the queue.
55+ */
56+ pop(): any;
57+ /**
58+ * Replace the element with the highest priority in the queue with a new value.
59+ * @param {*} value The new value.
60+ * @returns {*} The replaced value.
61+ */
62+ replace(value: any): any;
63+ /**
64+ * Compute the index for the parent of the node at index `i`.
65+ * @param {number} i The index of the node to get the parent of.
66+ * @returns {number} The index of the parent node.
67+ * @private
68+ */
69+ private _parent;
70+ /**
71+ * Compute the index for the left child of the node at index `i`.
72+ * @param {number} i The index of the node to get the left child of.
73+ * @returns {number} The index of the left child.
74+ * @private
75+ */
76+ private _left;
77+ /**
78+ * Compute the index for the right child of the node at index `i`.
79+ * @param {number} i The index of the node to get the right child of.
80+ * @returns {number} The index of the right child.
81+ * @private
82+ */
83+ private _right;
84+ /**
85+ * Check if the element at index `i` is greater than the element at index `j`.
86+ * @param {number} i The index of the first element to compare.
87+ * @param {number} j The index of the second element to compare.
88+ * @returns {boolean} `true` if the element at index `i` is greater than the element at index `j`, `false` otherwise.
89+ * @private
90+ */
91+ private _greater;
92+ /**
93+ * Swap the elements at indices `i` and `j`.
94+ * @param {number} i The index of the first element to swap.
95+ * @param {number} j The index of the second element to swap.
96+ * @private
97+ */
98+ private _swap;
99+ /**
100+ * Maintain the heap property by updating positions in the heap,
101+ * starting at the last element and moving up the heap.
102+ * @private
103+ */
104+ private _siftUp;
105+ /**
106+ * Maintain the heap property by updating positions in the heap,
107+ * starting at the first element and moving down the heap.
108+ * @private
109+ */
110+ private _siftDown;
111111 }
112112 /**
113113 * A trie structure to efficiently store and search for strings.
114114 */
115115 export class CharTrie {
116- root: CharTrieNode;
117- /**
118- * Adds one or more `texts` to the trie.
119- * @param {string[]} texts The strings to add to the trie.
120- */
121- extend(texts: string[]): void;
122- /**
123- * Adds text to the trie.
124- * @param {string} text The string to add to the trie.
125- */
126- push(text: string): void;
127- /**
128- * Searches the trie for all strings with a common prefix of `text`.
129- * @param {string} text The common prefix to search for.
130- * @yields {string} Each string in the trie that has `text` as a prefix.
131- */
132- commonPrefixSearch(text: string): Generator<string, void, unknown>;
116+ root: CharTrieNode;
117+ /**
118+ * Adds one or more `texts` to the trie.
119+ * @param {string[]} texts The strings to add to the trie.
120+ */
121+ extend(texts: string[]): void;
122+ /**
123+ * Adds text to the trie.
124+ * @param {string} text The string to add to the trie.
125+ */
126+ push(text: string): void;
127+ /**
128+ * Searches the trie for all strings with a common prefix of `text`.
129+ * @param {string} text The common prefix to search for.
130+ * @yields {string} Each string in the trie that has `text` as a prefix.
131+ */
132+ commonPrefixSearch(text: string): Generator<string, void, unknown>;
133133 }
134134 /**
135135 * A lattice data structure to be used for tokenization.
136136 */
137137 export class TokenLattice {
138- /**
139- * Creates a new TokenLattice instance.
140- *
141- * @param {string} sentence The input sentence to be tokenized.
142- * @param {number} bosTokenId The beginning-of-sequence token ID.
143- * @param {number} eosTokenId The end-of-sequence token ID.
144- */
145- constructor(sentence: string, bosTokenId: number, eosTokenId: number);
146- sentence: string;
147- len: number;
148- bosTokenId: number;
149- eosTokenId: number;
150- nodes: TokenLatticeNode[];
151- beginNodes: any[][];
152- endNodes: any[][];
153- /**
154- * Inserts a new token node into the token lattice.
155- *
156- * @param {number} pos The starting position of the token.
157- * @param {number} length The length of the token.
158- * @param {number} score The score of the token.
159- * @param {number} tokenId The token ID of the token.
160- */
161- insert(pos: number, length: number, score: number, tokenId: number): void;
162- /**
163- * Implements the Viterbi algorithm to compute the most likely sequence of tokens.
164- *
165- * @returns {TokenLatticeNode[]} The array of nodes representing the most likely sequence of tokens.
166- */
167- viterbi(): TokenLatticeNode[];
168- /**
169- * @param {TokenLatticeNode} node
170- * @returns {string} The array of nodes representing the most likely sequence of tokens.
171- */
172- piece(node: TokenLatticeNode): string;
173- /**
174- * @returns {Array} The array of nodes representing the most likely sequence of tokens.
175- */
176- tokens(): any[];
177- /**
178- * @returns {Array} The array of nodes representing the most likely sequence of tokens.
179- */
180- tokenIds(): any[];
138+ /**
139+ * Creates a new TokenLattice instance.
140+ *
141+ * @param {string} sentence The input sentence to be tokenized.
142+ * @param {number} bosTokenId The beginning-of-sequence token ID.
143+ * @param {number} eosTokenId The end-of-sequence token ID.
144+ */
145+ constructor(sentence: string, bosTokenId: number, eosTokenId: number);
146+ sentence: string;
147+ len: number;
148+ bosTokenId: number;
149+ eosTokenId: number;
150+ nodes: TokenLatticeNode[];
151+ beginNodes: any[][];
152+ endNodes: any[][];
153+ /**
154+ * Inserts a new token node into the token lattice.
155+ *
156+ * @param {number} pos The starting position of the token.
157+ * @param {number} length The length of the token.
158+ * @param {number} score The score of the token.
159+ * @param {number} tokenId The token ID of the token.
160+ */
161+ insert(pos: number, length: number, score: number, tokenId: number): void;
162+ /**
163+ * Implements the Viterbi algorithm to compute the most likely sequence of tokens.
164+ *
165+ * @returns {TokenLatticeNode[]} The array of nodes representing the most likely sequence of tokens.
166+ */
167+ viterbi(): TokenLatticeNode[];
168+ /**
169+ * @param {TokenLatticeNode} node
170+ * @returns {string} The array of nodes representing the most likely sequence of tokens.
171+ */
172+ piece(node: TokenLatticeNode): string;
173+ /**
174+ * @returns {Array} The array of nodes representing the most likely sequence of tokens.
175+ */
176+ tokens(): any[];
177+ /**
178+ * @returns {Array} The array of nodes representing the most likely sequence of tokens.
179+ */
180+ tokenIds(): any[];
181181 }
182182 /**
183183 * Represents a node in a character trie.
184184 */
185185 declare class CharTrieNode {
186- /**
187- * Returns a new `CharTrieNode` instance with default values.
188- * @returns {CharTrieNode} A new `CharTrieNode` instance with `isLeaf` set to `false` and an empty `children` map.
189- */
190- static default(): CharTrieNode;
191- /**
192- * Create a new CharTrieNode.
193- * @param {boolean} isLeaf Whether the node is a leaf node or not.
194- * @param {Map<string, CharTrieNode>} children A map containing the node's children, where the key is a character and the value is a `CharTrieNode`.
195- */
196- constructor(isLeaf: boolean, children: Map<string, CharTrieNode>);
197- isLeaf: boolean;
198- children: Map<string, CharTrieNode>;
186+ /**
187+ * Returns a new `CharTrieNode` instance with default values.
188+ * @returns {CharTrieNode} A new `CharTrieNode` instance with `isLeaf` set to `false` and an empty `children` map.
189+ */
190+ static default(): CharTrieNode;
191+ /**
192+ * Create a new CharTrieNode.
193+ * @param {boolean} isLeaf Whether the node is a leaf node or not.
194+ * @param {Map<string, CharTrieNode>} children A map containing the node's children, where the key is a character and the value is a `CharTrieNode`.
195+ */
196+ constructor(isLeaf: boolean, children: Map<string, CharTrieNode>);
197+ isLeaf: boolean;
198+ children: Map<string, CharTrieNode>;
199199 }
200200 declare class TokenLatticeNode {
201- /**
202- * Represents a node in a token lattice for a given sentence.
203- * @param {number} tokenId The ID of the token associated with this node.
204- * @param {number} nodeId The ID of this node.
205- * @param {number} pos The starting position of the token in the sentence.
206- * @param {number} length The length of the token.
207- * @param {number} score The score associated with the token.
208- */
209- constructor(tokenId: number, nodeId: number, pos: number, length: number, score: number);
210- tokenId: number;
211- nodeId: number;
212- pos: number;
213- length: number;
214- score: number;
215- prev: any;
216- backtraceScore: number;
217- /**
218- * Returns a clone of this node.
219- * @returns {TokenLatticeNode} A clone of this node.
220- */
221- clone(): TokenLatticeNode;
201+ /**
202+ * Represents a node in a token lattice for a given sentence.
203+ * @param {number} tokenId The ID of the token associated with this node.
204+ * @param {number} nodeId The ID of this node.
205+ * @param {number} pos The starting position of the token in the sentence.
206+ * @param {number} length The length of the token.
207+ * @param {number} score The score associated with the token.
208+ */
209+ constructor(
210+ tokenId: number,
211+ nodeId: number,
212+ pos: number,
213+ length: number,
214+ score: number,
215+ );
216+ tokenId: number;
217+ nodeId: number;
218+ pos: number;
219+ length: number;
220+ score: number;
221+ prev: any;
222+ backtraceScore: number;
223+ /**
224+ * Returns a clone of this node.
225+ * @returns {TokenLatticeNode} A clone of this node.
226+ */
227+ clone(): TokenLatticeNode;
222228 }
223229 export {};
224-//# sourceMappingURL=data-structures.d.ts.map
No newline at the end of the file
230+//# sourceMappingURL=data-structures.d.ts.map
modified core/vendor/modules/@xenova/transformers/types/utils/generation.d.ts +442 −433
@@ -1,6 +1,6 @@
11 declare const LogitsProcessorList_base: new () => {
2- (...args: any[]): any;
3- _call(...args: any[]): any;
2+ (...args: any[]): any;
3+ _call(...args: any[]): any;
44 };
55 /**
66 * A class representing a list of logits processors. A logits processor is a function that modifies the logits
@@ -10,47 +10,47 @@
1010 * @extends Callable
1111 */
1212 export class LogitsProcessorList extends LogitsProcessorList_base {
13- processors: any[];
14- /**
15- * Adds a new logits processor to the list.
16- *
17- * @param {LogitsProcessor} item The logits processor function to add.
18- */
19- push(item: LogitsProcessor): void;
20- /**
21- * Adds multiple logits processors to the list.
22- *
23- * @param {LogitsProcessor[]} items The logits processor functions to add.
24- */
25- extend(items: LogitsProcessor[]): void;
26- /**
27- * Applies all logits processors in the list to a batch of logits, modifying them in-place.
28- *
29- * @param {number[]} input_ids The input IDs for the language model.
30- * @param {number[][]} batchedLogits A 2D array of logits, where each row corresponds to a single
31- * input sequence in the batch.
32- */
33- _call(input_ids: number[], batchedLogits: number[][]): void;
34- [Symbol.iterator](): IterableIterator<any>;
13+ processors: any[];
14+ /**
15+ * Adds a new logits processor to the list.
16+ *
17+ * @param {LogitsProcessor} item The logits processor function to add.
18+ */
19+ push(item: LogitsProcessor): void;
20+ /**
21+ * Adds multiple logits processors to the list.
22+ *
23+ * @param {LogitsProcessor[]} items The logits processor functions to add.
24+ */
25+ extend(items: LogitsProcessor[]): void;
26+ /**
27+ * Applies all logits processors in the list to a batch of logits, modifying them in-place.
28+ *
29+ * @param {number[]} input_ids The input IDs for the language model.
30+ * @param {number[][]} batchedLogits A 2D array of logits, where each row corresponds to a single
31+ * input sequence in the batch.
32+ */
33+ _call(input_ids: number[], batchedLogits: number[][]): void;
34+ [Symbol.iterator](): IterableIterator<any>;
3535 }
3636 declare const LogitsProcessor_base: new () => {
37- (...args: any[]): any;
38- _call(...args: any[]): any;
37+ (...args: any[]): any;
38+ _call(...args: any[]): any;
3939 };
4040 /**
4141 * Base class for processing logits.
4242 * @extends Callable
4343 */
4444 export class LogitsProcessor extends LogitsProcessor_base {
45- /**
46- * Apply the processor to the input logits.
47- *
48- * @abstract
49- * @param {Array} input_ids The input ids.
50- * @param {Tensor} logits The logits to process.
51- * @throws {Error} Throws an error if `_call` is not implemented in the subclass.
52- */
53- _call(input_ids: any[], logits: Tensor): void;
45+ /**
46+ * Apply the processor to the input logits.
47+ *
48+ * @abstract
49+ * @param {Array} input_ids The input ids.
50+ * @param {Tensor} logits The logits to process.
51+ * @throws {Error} Throws an error if `_call` is not implemented in the subclass.
52+ */
53+ _call(input_ids: any[], logits: Tensor): void;
5454 }
5555 /**
5656 * A logits processor that forces a specific token to be generated by the decoder.
@@ -58,42 +58,42 @@
5858 * @extends LogitsProcessor
5959 */
6060 export class ForceTokensLogitsProcessor extends LogitsProcessor {
61- /**
62- * Constructs a new instance of `ForceTokensLogitsProcessor`.
63- *
64- * @param {Array} forced_decoder_ids The ids of tokens that should be forced.
65- */
66- constructor(forced_decoder_ids: any[]);
67- force_token_map: {
68- [k: string]: any;
69- };
70- /**
71- * Apply the processor to the input logits.
72- *
73- * @param {Array} input_ids The input ids.
74- * @param {Tensor} logits The logits to process.
75- * @returns {Tensor} The processed logits.
76- */
77- _call(input_ids: any[], logits: Tensor): Tensor;
61+ /**
62+ * Constructs a new instance of `ForceTokensLogitsProcessor`.
63+ *
64+ * @param {Array} forced_decoder_ids The ids of tokens that should be forced.
65+ */
66+ constructor(forced_decoder_ids: any[]);
67+ force_token_map: {
68+ [k: string]: any;
69+ };
70+ /**
71+ * Apply the processor to the input logits.
72+ *
73+ * @param {Array} input_ids The input ids.
74+ * @param {Tensor} logits The logits to process.
75+ * @returns {Tensor} The processed logits.
76+ */
77+ _call(input_ids: any[], logits: Tensor): Tensor;
7878 }
7979 /**
8080 * A LogitsProcessor that forces a BOS token at the beginning of the generated sequence.
8181 * @extends LogitsProcessor
8282 */
8383 export class ForcedBOSTokenLogitsProcessor extends LogitsProcessor {
84- /**
85- * Create a ForcedBOSTokenLogitsProcessor.
86- * @param {number} bos_token_id The ID of the beginning-of-sequence token to be forced.
87- */
88- constructor(bos_token_id: number);
89- bos_token_id: number;
90- /**
91- * Apply the BOS token forcing to the logits.
92- * @param {Array} input_ids The input IDs.
93- * @param {Object} logits The logits.
94- * @returns {Object} The logits with BOS token forcing.
95- */
96- _call(input_ids: any[], logits: any): any;
84+ /**
85+ * Create a ForcedBOSTokenLogitsProcessor.
86+ * @param {number} bos_token_id The ID of the beginning-of-sequence token to be forced.
87+ */
88+ constructor(bos_token_id: number);
89+ bos_token_id: number;
90+ /**
91+ * Apply the BOS token forcing to the logits.
92+ * @param {Array} input_ids The input IDs.
93+ * @param {Object} logits The logits.
94+ * @returns {Object} The logits with BOS token forcing.
95+ */
96+ _call(input_ids: any[], logits: any): any;
9797 }
9898 /**
9999 * A logits processor that forces end-of-sequence token probability to 1.
@@ -101,21 +101,21 @@
101101 * @extends LogitsProcessor
102102 */
103103 export class ForcedEOSTokenLogitsProcessor extends LogitsProcessor {
104- /**
105- * Create a ForcedEOSTokenLogitsProcessor.
106- * @param {number} max_length Max length of the sequence.
107- * @param {number|number[]} forced_eos_token_id The ID of the end-of-sequence token to be forced.
108- */
109- constructor(max_length: number, forced_eos_token_id: number | number[]);
110- max_length: number;
111- forced_eos_token_id: number | number[];
112- /**
113- * Apply the processor to input_ids and logits.
114- *
115- * @param {number[]} input_ids The input ids.
116- * @param {Tensor} logits The logits tensor.
117- */
118- _call(input_ids: number[], logits: Tensor): void;
104+ /**
105+ * Create a ForcedEOSTokenLogitsProcessor.
106+ * @param {number} max_length Max length of the sequence.
107+ * @param {number|number[]} forced_eos_token_id The ID of the end-of-sequence token to be forced.
108+ */
109+ constructor(max_length: number, forced_eos_token_id: number | number[]);
110+ max_length: number;
111+ forced_eos_token_id: number | number[];
112+ /**
113+ * Apply the processor to input_ids and logits.
114+ *
115+ * @param {number[]} input_ids The input ids.
116+ * @param {Tensor} logits The logits tensor.
117+ */
118+ _call(input_ids: number[], logits: Tensor): void;
119119 }
120120 /**
121121 * A LogitsProcessor that suppresses a list of tokens as soon as the `generate` function starts
@@ -124,53 +124,53 @@
124124 * @extends LogitsProcessor
125125 */
126126 export class SuppressTokensAtBeginLogitsProcessor extends LogitsProcessor {
127- /**
128- * Create a SuppressTokensAtBeginLogitsProcessor.
129- * @param {number[]} begin_suppress_tokens The IDs of the tokens to suppress.
130- * @param {number} begin_index The number of tokens to generate before suppressing tokens.
131- */
132- constructor(begin_suppress_tokens: number[], begin_index: number);
133- begin_suppress_tokens: number[];
134- begin_index: number;
135- /**
136- * Apply the BOS token forcing to the logits.
137- * @param {Array} input_ids The input IDs.
138- * @param {Object} logits The logits.
139- * @returns {Object} The logits with BOS token forcing.
140- */
141- _call(input_ids: any[], logits: any): any;
127+ /**
128+ * Create a SuppressTokensAtBeginLogitsProcessor.
129+ * @param {number[]} begin_suppress_tokens The IDs of the tokens to suppress.
130+ * @param {number} begin_index The number of tokens to generate before suppressing tokens.
131+ */
132+ constructor(begin_suppress_tokens: number[], begin_index: number);
133+ begin_suppress_tokens: number[];
134+ begin_index: number;
135+ /**
136+ * Apply the BOS token forcing to the logits.
137+ * @param {Array} input_ids The input IDs.
138+ * @param {Object} logits The logits.
139+ * @returns {Object} The logits with BOS token forcing.
140+ */
141+ _call(input_ids: any[], logits: any): any;
142142 }
143143 /**
144144 * A LogitsProcessor that handles adding timestamps to generated text.
145145 * @extends LogitsProcessor
146146 */
147147 export class WhisperTimeStampLogitsProcessor extends LogitsProcessor {
148- /**
149- * Constructs a new WhisperTimeStampLogitsProcessor.
150- * @param {Object} generate_config The config object passed to the `generate()` method of a transformer model.
151- * @param {number} generate_config.eos_token_id The ID of the end-of-sequence token.
152- * @param {number} generate_config.no_timestamps_token_id The ID of the token used to indicate that a token should not have a timestamp.
153- * @param {number[][]} [generate_config.forced_decoder_ids] An array of two-element arrays representing decoder IDs that are forced to appear in the output. The second element of each array indicates whether the token is a timestamp.
154- * @param {number} [generate_config.max_initial_timestamp_index] The maximum index at which an initial timestamp can appear.
155- */
156- constructor(generate_config: {
157- eos_token_id: number;
158- no_timestamps_token_id: number;
159- forced_decoder_ids?: number[][];
160- max_initial_timestamp_index?: number;
161- });
148+ /**
149+ * Constructs a new WhisperTimeStampLogitsProcessor.
150+ * @param {Object} generate_config The config object passed to the `generate()` method of a transformer model.
151+ * @param {number} generate_config.eos_token_id The ID of the end-of-sequence token.
152+ * @param {number} generate_config.no_timestamps_token_id The ID of the token used to indicate that a token should not have a timestamp.
153+ * @param {number[][]} [generate_config.forced_decoder_ids] An array of two-element arrays representing decoder IDs that are forced to appear in the output. The second element of each array indicates whether the token is a timestamp.
154+ * @param {number} [generate_config.max_initial_timestamp_index] The maximum index at which an initial timestamp can appear.
155+ */
156+ constructor(generate_config: {
162157 eos_token_id: number;
163158 no_timestamps_token_id: number;
164- timestamp_begin: number;
165- begin_index: number;
166- max_initial_timestamp_index: number;
167- /**
168- * Modify the logits to handle timestamp tokens.
169- * @param {Array} input_ids The input sequence of tokens.
170- * @param {Tensor} logits The logits output by the model.
171- * @returns {Tensor} The modified logits.
172- */
173- _call(input_ids: any[], logits: Tensor): Tensor;
159+ forced_decoder_ids?: number[][];
160+ max_initial_timestamp_index?: number;
161+ });
162+ eos_token_id: number;
163+ no_timestamps_token_id: number;
164+ timestamp_begin: number;
165+ begin_index: number;
166+ max_initial_timestamp_index: number;
167+ /**
168+ * Modify the logits to handle timestamp tokens.
169+ * @param {Array} input_ids The input sequence of tokens.
170+ * @param {Tensor} logits The logits output by the model.
171+ * @returns {Tensor} The modified logits.
172+ */
173+ _call(input_ids: any[], logits: Tensor): Tensor;
174174 }
175175 /**
176176 * A logits processor that disallows ngrams of a certain size to be repeated.
@@ -178,38 +178,41 @@
178178 * @extends LogitsProcessor
179179 */
180180 export class NoRepeatNGramLogitsProcessor extends LogitsProcessor {
181- /**
182- * Create a NoRepeatNGramLogitsProcessor.
183- * @param {number} no_repeat_ngram_size The no-repeat-ngram size. All ngrams of this size can only occur once.
184- */
185- constructor(no_repeat_ngram_size: number);
186- no_repeat_ngram_size: number;
187- /**
188- * Generate n-grams from a sequence of token ids.
189- * @param {number[]} prevInputIds List of previous input ids
190- * @returns {Map<string, number[]>} Map of generated n-grams
191- */
192- getNgrams(prevInputIds: number[]): Map<string, number[]>;
193- /**
194- * Generate n-grams from a sequence of token ids.
195- * @param {Map<string, number[]>} bannedNgrams Map of banned n-grams
196- * @param {number[]} prevInputIds List of previous input ids
197- * @returns {number[]} Map of generated n-grams
198- */
199- getGeneratedNgrams(bannedNgrams: Map<string, number[]>, prevInputIds: number[]): number[];
200- /**
201- * Calculate banned n-gram tokens
202- * @param {number[]} prevInputIds List of previous input ids
203- * @returns {number[]} Map of generated n-grams
204- */
205- calcBannedNgramTokens(prevInputIds: number[]): number[];
206- /**
207- * Apply the no-repeat-ngram processor to the logits.
208- * @param {Array} input_ids The input IDs.
209- * @param {Object} logits The logits.
210- * @returns {Object} The logits with no-repeat-ngram processing.
211- */
212- _call(input_ids: any[], logits: any): any;
181+ /**
182+ * Create a NoRepeatNGramLogitsProcessor.
183+ * @param {number} no_repeat_ngram_size The no-repeat-ngram size. All ngrams of this size can only occur once.
184+ */
185+ constructor(no_repeat_ngram_size: number);
186+ no_repeat_ngram_size: number;
187+ /**
188+ * Generate n-grams from a sequence of token ids.
189+ * @param {number[]} prevInputIds List of previous input ids
190+ * @returns {Map<string, number[]>} Map of generated n-grams
191+ */
192+ getNgrams(prevInputIds: number[]): Map<string, number[]>;
193+ /**
194+ * Generate n-grams from a sequence of token ids.
195+ * @param {Map<string, number[]>} bannedNgrams Map of banned n-grams
196+ * @param {number[]} prevInputIds List of previous input ids
197+ * @returns {number[]} Map of generated n-grams
198+ */
199+ getGeneratedNgrams(
200+ bannedNgrams: Map<string, number[]>,
201+ prevInputIds: number[],
202+ ): number[];
203+ /**
204+ * Calculate banned n-gram tokens
205+ * @param {number[]} prevInputIds List of previous input ids
206+ * @returns {number[]} Map of generated n-grams
207+ */
208+ calcBannedNgramTokens(prevInputIds: number[]): number[];
209+ /**
210+ * Apply the no-repeat-ngram processor to the logits.
211+ * @param {Array} input_ids The input IDs.
212+ * @param {Object} logits The logits.
213+ * @returns {Object} The logits with no-repeat-ngram processing.
214+ */
215+ _call(input_ids: any[], logits: any): any;
213216 }
214217 /**
215218 * A logits processor that penalises repeated output tokens.
@@ -217,19 +220,19 @@
217220 * @extends LogitsProcessor
218221 */
219222 export class RepetitionPenaltyLogitsProcessor extends LogitsProcessor {
220- /**
221- * Create a RepetitionPenaltyLogitsProcessor.
222- * @param {number} penalty The penalty to apply for repeated tokens.
223- */
224- constructor(penalty: number);
225- penalty: number;
226- /**
227- * Apply the repetition penalty to the logits.
228- * @param {Array} input_ids The input IDs.
229- * @param {Object} logits The logits.
230- * @returns {Object} The logits with repetition penalty processing.
231- */
232- _call(input_ids: any[], logits: any): any;
223+ /**
224+ * Create a RepetitionPenaltyLogitsProcessor.
225+ * @param {number} penalty The penalty to apply for repeated tokens.
226+ */
227+ constructor(penalty: number);
228+ penalty: number;
229+ /**
230+ * Apply the repetition penalty to the logits.
231+ * @param {Array} input_ids The input IDs.
232+ * @param {Object} logits The logits.
233+ * @returns {Object} The logits with repetition penalty processing.
234+ */
235+ _call(input_ids: any[], logits: any): any;
233236 }
234237 /**
235238 * A logits processor that enforces a minimum number of tokens.
@@ -237,21 +240,21 @@
237240 * @extends LogitsProcessor
238241 */
239242 export class MinLengthLogitsProcessor extends LogitsProcessor {
240- /**
241- * Create a MinLengthLogitsProcessor.
242- * @param {number} min_length The minimum length below which the score of `eos_token_id` is set to negative infinity.
243- * @param {number|number[]} eos_token_id The ID/IDs of the end-of-sequence token.
244- */
245- constructor(min_length: number, eos_token_id: number | number[]);
246- min_length: number;
247- eos_token_id: number[];
248- /**
249- * Apply logit processor.
250- * @param {Array} input_ids The input IDs.
251- * @param {Object} logits The logits.
252- * @returns {Object} The processed logits.
253- */
254- _call(input_ids: any[], logits: any): any;
243+ /**
244+ * Create a MinLengthLogitsProcessor.
245+ * @param {number} min_length The minimum length below which the score of `eos_token_id` is set to negative infinity.
246+ * @param {number|number[]} eos_token_id The ID/IDs of the end-of-sequence token.
247+ */
248+ constructor(min_length: number, eos_token_id: number | number[]);
249+ min_length: number;
250+ eos_token_id: number[];
251+ /**
252+ * Apply logit processor.
253+ * @param {Array} input_ids The input IDs.
254+ * @param {Object} logits The logits.
255+ * @returns {Object} The processed logits.
256+ */
257+ _call(input_ids: any[], logits: any): any;
255258 }
256259 /**
257260 * A logits processor that enforces a minimum number of new tokens.
@@ -259,40 +262,44 @@
259262 * @extends LogitsProcessor
260263 */
261264 export class MinNewTokensLengthLogitsProcessor extends LogitsProcessor {
262- /**
263- * Create a MinNewTokensLengthLogitsProcessor.
264- * @param {number} prompt_length_to_skip The input tokens length.
265- * @param {number} min_new_tokens The minimum *new* tokens length below which the score of `eos_token_id` is set to negative infinity.
266- * @param {number|number[]} eos_token_id The ID/IDs of the end-of-sequence token.
267- */
268- constructor(prompt_length_to_skip: number, min_new_tokens: number, eos_token_id: number | number[]);
269- prompt_length_to_skip: number;
270- min_new_tokens: number;
271- eos_token_id: number[];
272- /**
273- * Apply logit processor.
274- * @param {Array} input_ids The input IDs.
275- * @param {Object} logits The logits.
276- * @returns {Object} The processed logits.
277- */
278- _call(input_ids: any[], logits: any): any;
265+ /**
266+ * Create a MinNewTokensLengthLogitsProcessor.
267+ * @param {number} prompt_length_to_skip The input tokens length.
268+ * @param {number} min_new_tokens The minimum *new* tokens length below which the score of `eos_token_id` is set to negative infinity.
269+ * @param {number|number[]} eos_token_id The ID/IDs of the end-of-sequence token.
270+ */
271+ constructor(
272+ prompt_length_to_skip: number,
273+ min_new_tokens: number,
274+ eos_token_id: number | number[],
275+ );
276+ prompt_length_to_skip: number;
277+ min_new_tokens: number;
278+ eos_token_id: number[];
279+ /**
280+ * Apply logit processor.
281+ * @param {Array} input_ids The input IDs.
282+ * @param {Object} logits The logits.
283+ * @returns {Object} The processed logits.
284+ */
285+ _call(input_ids: any[], logits: any): any;
279286 }
280287 export class NoBadWordsLogitsProcessor extends LogitsProcessor {
281- /**
282- * Create a `NoBadWordsLogitsProcessor`.
283- * @param {number[][]} bad_words_ids List of list of token ids that are not allowed to be generated.
284- * @param {number|number[]} eos_token_id The id of the *end-of-sequence* token. Optionally, use a list to set multiple *end-of-sequence* tokens.
285- */
286- constructor(bad_words_ids: number[][], eos_token_id: number | number[]);
287- bad_words_ids: number[][];
288- eos_token_id: number[];
289- /**
290- * Apply logit processor.
291- * @param {Array} input_ids The input IDs.
292- * @param {Object} logits The logits.
293- * @returns {Object} The processed logits.
294- */
295- _call(input_ids: any[], logits: any): any;
288+ /**
289+ * Create a `NoBadWordsLogitsProcessor`.
290+ * @param {number[][]} bad_words_ids List of list of token ids that are not allowed to be generated.
291+ * @param {number|number[]} eos_token_id The id of the *end-of-sequence* token. Optionally, use a list to set multiple *end-of-sequence* tokens.
292+ */
293+ constructor(bad_words_ids: number[][], eos_token_id: number | number[]);
294+ bad_words_ids: number[][];
295+ eos_token_id: number[];
296+ /**
297+ * Apply logit processor.
298+ * @param {Array} input_ids The input IDs.
299+ * @param {Object} logits The logits.
300+ * @returns {Object} The processed logits.
301+ */
302+ _call(input_ids: any[], logits: any): any;
296303 }
297304 /**
298305 * @typedef {Object} GenerationConfigType The default configuration parameters.
@@ -355,239 +362,241 @@
355362 * Class that holds a configuration for a generation task.
356363 * @type {new (kwargs?: GenerationConfigType) => GenerationConfigType}
357364 */
358-export const GenerationConfig: new (kwargs?: GenerationConfigType) => GenerationConfigType;
365+export const GenerationConfig: new (
366+ kwargs?: GenerationConfigType,
367+) => GenerationConfigType;
359368 declare const Sampler_base: new () => {
360- (...args: any[]): any;
361- _call(...args: any[]): any;
369+ (...args: any[]): any;
370+ _call(...args: any[]): any;
362371 };
363372 /**
364373 * Sampler is a base class for all sampling methods used for text generation.
365374 */
366375 export class Sampler extends Sampler_base {
367- /**
368- * Returns a Sampler object based on the specified options.
369- * @param {GenerationConfigType} generation_config An object containing options for the sampler.
370- * @returns {Sampler} A Sampler object.
371- */
372- static getSampler(generation_config: GenerationConfigType): Sampler;
373- /**
374- * Creates a new Sampler object with the specified generation config.
375- * @param {GenerationConfigType} generation_config The generation config.
376- */
377- constructor(generation_config: GenerationConfigType);
378- generation_config: GenerationConfigType;
379- /**
380- * Executes the sampler, using the specified logits.
381- * @param {Tensor} logits
382- * @param {number} index
383- * @returns {void}
384- */
385- _call(logits: Tensor, index?: number): void;
386- /**
387- * Abstract method for sampling the logits.
388- * @param {Tensor} logits
389- * @param {number} index
390- * @throws {Error}
391- */
392- sample(logits: Tensor, index: number): void;
393- /**
394- * Returns the specified logits as an array, with temperature applied.
395- * @param {Tensor} logits
396- * @param {number} index
397- * @returns {Float32Array}
398- */
399- getLogits(logits: Tensor, index: number): Float32Array;
400- /**
401- * Selects an item randomly based on the specified probabilities.
402- * @param {Array} probabilities An array of probabilities to use for selection.
403- * @returns {number} The index of the selected item.
404- */
405- randomSelect(probabilities: any[]): number;
376+ /**
377+ * Returns a Sampler object based on the specified options.
378+ * @param {GenerationConfigType} generation_config An object containing options for the sampler.
379+ * @returns {Sampler} A Sampler object.
380+ */
381+ static getSampler(generation_config: GenerationConfigType): Sampler;
382+ /**
383+ * Creates a new Sampler object with the specified generation config.
384+ * @param {GenerationConfigType} generation_config The generation config.
385+ */
386+ constructor(generation_config: GenerationConfigType);
387+ generation_config: GenerationConfigType;
388+ /**
389+ * Executes the sampler, using the specified logits.
390+ * @param {Tensor} logits
391+ * @param {number} index
392+ * @returns {void}
393+ */
394+ _call(logits: Tensor, index?: number): void;
395+ /**
396+ * Abstract method for sampling the logits.
397+ * @param {Tensor} logits
398+ * @param {number} index
399+ * @throws {Error}
400+ */
401+ sample(logits: Tensor, index: number): void;
402+ /**
403+ * Returns the specified logits as an array, with temperature applied.
404+ * @param {Tensor} logits
405+ * @param {number} index
406+ * @returns {Float32Array}
407+ */
408+ getLogits(logits: Tensor, index: number): Float32Array;
409+ /**
410+ * Selects an item randomly based on the specified probabilities.
411+ * @param {Array} probabilities An array of probabilities to use for selection.
412+ * @returns {number} The index of the selected item.
413+ */
414+ randomSelect(probabilities: any[]): number;
406415 }
407416 /**
408417 * The default configuration parameters.
409418 */
410419 export type GenerationConfigType = {
411- /**
412- * The maximum length the generated tokens can have. Corresponds to the length of the input prompt + `max_new_tokens`. Its effect is overridden by `max_new_tokens`, if also set.
413- */
414- max_length?: number;
415- /**
416- * The maximum numbers of tokens to generate, ignoring the number of tokens in the prompt.
417- */
418- max_new_tokens?: number;
419- /**
420- * The minimum length of the sequence to be generated. Corresponds to the length of the input prompt + `min_new_tokens`. Its effect is overridden by `min_new_tokens`, if also set.
421- */
422- min_length?: number;
423- /**
424- * The minimum numbers of tokens to generate, ignoring the number of tokens in the prompt.
425- */
426- min_new_tokens?: number;
427- /**
428- * Controls the stopping condition for beam-based methods, like beam-search. It accepts the following values:
429- * - `true`, where the generation stops as soon as there are `num_beams` complete candidates;
430- * - `false`, where an heuristic is applied and the generation stops when is it very unlikely to find better candidates;
431- * - `"never"`, where the beam search procedure only stops when there cannot be better candidates (canonical beam search algorithm).
432- */
433- early_stopping?: boolean | "never";
434- /**
435- * The maximum amount of time you allow the computation to run for in seconds. Generation will still finish the current pass after allocated time has been passed.
436- */
437- max_time?: number;
438- /**
439- * Whether or not to use sampling; use greedy decoding otherwise.
440- */
441- do_sample?: boolean;
442- /**
443- * Number of beams for beam search. 1 means no beam search.
444- */
445- num_beams?: number;
446- /**
447- * Number of groups to divide `num_beams` into in order to ensure diversity among different groups of beams. See [this paper](https://arxiv.org/pdf/1610.02424.pdf) for more details.
448- */
449- num_beam_groups?: number;
450- /**
451- * The values balance the model confidence and the degeneration penalty in contrastive search decoding.
452- */
453- penalty_alpha?: number;
454- /**
455- * Whether or not the model should use the past last key/values attentions (if applicable to the model) to speed up decoding.
456- */
457- use_cache?: boolean;
458- /**
459- * The value used to modulate the next token probabilities.
460- */
461- temperature?: number;
462- /**
463- * The number of highest probability vocabulary tokens to keep for top-k-filtering.
464- */
465- top_k?: number;
466- /**
467- * If set to float < 1, only the smallest set of most probable tokens with probabilities that add up to `top_p` or higher are kept for generation.
468- */
469- top_p?: number;
470- /**
471- * Local typicality measures how similar the conditional probability of predicting a target token next is to the expected conditional probability of predicting a random token next, given the partial text already generated. If set to float < 1, the smallest set of the most locally typical tokens with probabilities that add up to `typical_p` or higher are kept for generation. See [this paper](https://arxiv.org/pdf/2202.00666.pdf) for more details.
472- */
473- typical_p?: number;
474- /**
475- * If set to float strictly between 0 and 1, only tokens with a conditional probability greater than `epsilon_cutoff` will be sampled. In the paper, suggested values range from 3e-4 to 9e-4, depending on the size of the model. See [Truncation Sampling as Language Model Desmoothing](https://arxiv.org/abs/2210.15191) for more details.
476- */
477- epsilon_cutoff?: number;
478- /**
479- * Eta sampling is a hybrid of locally typical sampling and epsilon sampling. If set to float strictly between 0 and 1, a token is only considered if it is greater than either `eta_cutoff` or `sqrt(eta_cutoff) * exp(-entropy(softmax(next_token_logits)))`. The latter term is intuitively the expected next token probability, scaled by `sqrt(eta_cutoff)`. In the paper, suggested values range from 3e-4 to 2e-3, depending on the size of the model. See [Truncation Sampling as Language Model Desmoothing](https://arxiv.org/abs/2210.15191) for more details.
480- */
481- eta_cutoff?: number;
482- /**
483- * This value is subtracted from a beam's score if it generates a token same as any beam from other group at a particular time. Note that `diversity_penalty` is only effective if `group beam search` is enabled.
484- */
485- diversity_penalty?: number;
486- /**
487- * The parameter for repetition penalty. 1.0 means no penalty. See [this paper](https://arxiv.org/pdf/1909.05858.pdf) for more details.
488- */
489- repetition_penalty?: number;
490- /**
491- * The parameter for encoder_repetition_penalty. An exponential penalty on sequences that are not in the original input. 1.0 means no penalty.
492- */
493- encoder_repetition_penalty?: number;
494- /**
495- * Exponential penalty to the length that is used with beam-based generation. It is applied as an exponent to the sequence length, which in turn is used to divide the score of the sequence. Since the score is the log likelihood of the sequence (i.e. negative), `length_penalty` > 0.0 promotes longer sequences, while `length_penalty` < 0.0 encourages shorter sequences.
496- */
497- length_penalty?: number;
498- /**
499- * If set to int > 0, all ngrams of that size can only occur once.
500- */
501- no_repeat_ngram_size?: number;
502- /**
503- * List of token ids that are not allowed to be generated. In order to get the token ids of the words that should not appear in the generated text, use `(await tokenizer(bad_words, {add_prefix_space: true, add_special_tokens: false})).input_ids`.
504- */
505- bad_words_ids?: number[][];
506- /**
507- * List of token ids that must be generated. If given a `number[][]`, this is treated as a simple list of words that must be included, the opposite to `bad_words_ids`. If given `number[][][]`, this triggers a [disjunctive constraint](https://github.com/huggingface/transformers/issues/14081), where one can allow different forms of each word.
508- */
509- force_words_ids?: number[][] | number[][][];
510- /**
511- * Whether to renormalize the logits after applying all the logits processors or warpers (including the custom ones). It's highly recommended to set this flag to `true` as the search algorithms suppose the score logits are normalized but some logit processors or warpers break the normalization.
512- */
513- renormalize_logits?: boolean;
514- /**
515- * Custom constraints that can be added to the generation to ensure that the output will contain the use of certain tokens as defined by `Constraint` objects, in the most sensible way possible.
516- */
517- constraints?: any[];
518- /**
519- * The id of the token to force as the first generated token after the `decoder_start_token_id`. Useful for multilingual models like mBART where the first generated token needs to be the target language token.
520- */
521- forced_bos_token_id?: number;
522- /**
523- * The id of the token to force as the last generated token when `max_length` is reached. Optionally, use a list to set multiple *end-of-sequence* tokens.
524- */
525- forced_eos_token_id?: number | number[];
526- /**
527- * Whether to remove possible *nan* and *inf* outputs of the model to prevent the generation method to crash. Note that using `remove_invalid_values` can slow down generation.
528- */
529- remove_invalid_values?: boolean;
530- /**
531- * This Tuple adds an exponentially increasing length penalty, after a certain amount of tokens have been generated. The tuple shall consist of: `(start_index, decay_factor)` where `start_index` indicates where penalty starts and `decay_factor` represents the factor of exponential decay.
532- */
533- exponential_decay_length_penalty?: number[];
534- /**
535- * A list of tokens that will be suppressed at generation. The `SupressTokens` logit processor will set their log probs to `-inf` so that they are not sampled.
536- */
537- suppress_tokens?: number[];
538- /**
539- * A list of tokens that will be suppressed at the beginning of the generation. The `SupressBeginTokens` logit processor will set their log probs to `-inf` so that they are not sampled.
540- */
541- begin_suppress_tokens?: number[];
542- /**
543- * A list of pairs of integers which indicates a mapping from generation indices to token indices that will be forced before sampling. For example, `[[1, 123]]` means the second generated token will always be a token of index 123.
544- */
545- forced_decoder_ids?: number[][];
546- /**
547- * The number of independently computed returned sequences for each element in the batch.
548- */
549- num_return_sequences?: number;
550- /**
551- * Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned tensors for more details.
552- */
553- output_attentions?: boolean;
554- /**
555- * Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for more details.
556- */
557- output_hidden_states?: boolean;
558- /**
559- * Whether or not to return the prediction scores. See `scores` under returned tensors for more details.
560- */
561- output_scores?: boolean;
562- /**
563- * Whether or not to return a `ModelOutput` instead of a plain tuple.
564- */
565- return_dict_in_generate?: boolean;
566- /**
567- * The id of the *padding* token.
568- */
569- pad_token_id?: number;
570- /**
571- * The id of the *beginning-of-sequence* token.
572- */
573- bos_token_id?: number;
574- /**
575- * The id of the *end-of-sequence* token. Optionally, use a list to set multiple *end-of-sequence* tokens.
576- */
577- eos_token_id?: number | number[];
578- /**
579- * If set to int > 0, all ngrams of that size that occur in the `encoder_input_ids` cannot occur in the `decoder_input_ids`.
580- */
581- encoder_no_repeat_ngram_size?: number;
582- /**
583- * If an encoder-decoder model starts decoding with a different token than *bos*, the id of that token.
584- */
585- decoder_start_token_id?: number;
586- /**
587- * Additional generation kwargs will be forwarded to the `generate` function of the model. Kwargs that are not present in `generate`'s signature will be used in the model forward pass.
588- */
589- generation_kwargs?: any;
420+ /**
421+ * The maximum length the generated tokens can have. Corresponds to the length of the input prompt + `max_new_tokens`. Its effect is overridden by `max_new_tokens`, if also set.
422+ */
423+ max_length?: number;
424+ /**
425+ * The maximum numbers of tokens to generate, ignoring the number of tokens in the prompt.
426+ */
427+ max_new_tokens?: number;
428+ /**
429+ * The minimum length of the sequence to be generated. Corresponds to the length of the input prompt + `min_new_tokens`. Its effect is overridden by `min_new_tokens`, if also set.
430+ */
431+ min_length?: number;
432+ /**
433+ * The minimum numbers of tokens to generate, ignoring the number of tokens in the prompt.
434+ */
435+ min_new_tokens?: number;
436+ /**
437+ * Controls the stopping condition for beam-based methods, like beam-search. It accepts the following values:
438+ * - `true`, where the generation stops as soon as there are `num_beams` complete candidates;
439+ * - `false`, where an heuristic is applied and the generation stops when is it very unlikely to find better candidates;
440+ * - `"never"`, where the beam search procedure only stops when there cannot be better candidates (canonical beam search algorithm).
441+ */
442+ early_stopping?: boolean | "never";
443+ /**
444+ * The maximum amount of time you allow the computation to run for in seconds. Generation will still finish the current pass after allocated time has been passed.
445+ */
446+ max_time?: number;
447+ /**
448+ * Whether or not to use sampling; use greedy decoding otherwise.
449+ */
450+ do_sample?: boolean;
451+ /**
452+ * Number of beams for beam search. 1 means no beam search.
453+ */
454+ num_beams?: number;
455+ /**
456+ * Number of groups to divide `num_beams` into in order to ensure diversity among different groups of beams. See [this paper](https://arxiv.org/pdf/1610.02424.pdf) for more details.
457+ */
458+ num_beam_groups?: number;
459+ /**
460+ * The values balance the model confidence and the degeneration penalty in contrastive search decoding.
461+ */
462+ penalty_alpha?: number;
463+ /**
464+ * Whether or not the model should use the past last key/values attentions (if applicable to the model) to speed up decoding.
465+ */
466+ use_cache?: boolean;
467+ /**
468+ * The value used to modulate the next token probabilities.
469+ */
470+ temperature?: number;
471+ /**
472+ * The number of highest probability vocabulary tokens to keep for top-k-filtering.
473+ */
474+ top_k?: number;
475+ /**
476+ * If set to float < 1, only the smallest set of most probable tokens with probabilities that add up to `top_p` or higher are kept for generation.
477+ */
478+ top_p?: number;
479+ /**
480+ * Local typicality measures how similar the conditional probability of predicting a target token next is to the expected conditional probability of predicting a random token next, given the partial text already generated. If set to float < 1, the smallest set of the most locally typical tokens with probabilities that add up to `typical_p` or higher are kept for generation. See [this paper](https://arxiv.org/pdf/2202.00666.pdf) for more details.
481+ */
482+ typical_p?: number;
483+ /**
484+ * If set to float strictly between 0 and 1, only tokens with a conditional probability greater than `epsilon_cutoff` will be sampled. In the paper, suggested values range from 3e-4 to 9e-4, depending on the size of the model. See [Truncation Sampling as Language Model Desmoothing](https://arxiv.org/abs/2210.15191) for more details.
485+ */
486+ epsilon_cutoff?: number;
487+ /**
488+ * Eta sampling is a hybrid of locally typical sampling and epsilon sampling. If set to float strictly between 0 and 1, a token is only considered if it is greater than either `eta_cutoff` or `sqrt(eta_cutoff) * exp(-entropy(softmax(next_token_logits)))`. The latter term is intuitively the expected next token probability, scaled by `sqrt(eta_cutoff)`. In the paper, suggested values range from 3e-4 to 2e-3, depending on the size of the model. See [Truncation Sampling as Language Model Desmoothing](https://arxiv.org/abs/2210.15191) for more details.
489+ */
490+ eta_cutoff?: number;
491+ /**
492+ * This value is subtracted from a beam's score if it generates a token same as any beam from other group at a particular time. Note that `diversity_penalty` is only effective if `group beam search` is enabled.
493+ */
494+ diversity_penalty?: number;
495+ /**
496+ * The parameter for repetition penalty. 1.0 means no penalty. See [this paper](https://arxiv.org/pdf/1909.05858.pdf) for more details.
497+ */
498+ repetition_penalty?: number;
499+ /**
500+ * The parameter for encoder_repetition_penalty. An exponential penalty on sequences that are not in the original input. 1.0 means no penalty.
501+ */
502+ encoder_repetition_penalty?: number;
503+ /**
504+ * Exponential penalty to the length that is used with beam-based generation. It is applied as an exponent to the sequence length, which in turn is used to divide the score of the sequence. Since the score is the log likelihood of the sequence (i.e. negative), `length_penalty` > 0.0 promotes longer sequences, while `length_penalty` < 0.0 encourages shorter sequences.
505+ */
506+ length_penalty?: number;
507+ /**
508+ * If set to int > 0, all ngrams of that size can only occur once.
509+ */
510+ no_repeat_ngram_size?: number;
511+ /**
512+ * List of token ids that are not allowed to be generated. In order to get the token ids of the words that should not appear in the generated text, use `(await tokenizer(bad_words, {add_prefix_space: true, add_special_tokens: false})).input_ids`.
513+ */
514+ bad_words_ids?: number[][];
515+ /**
516+ * List of token ids that must be generated. If given a `number[][]`, this is treated as a simple list of words that must be included, the opposite to `bad_words_ids`. If given `number[][][]`, this triggers a [disjunctive constraint](https://github.com/huggingface/transformers/issues/14081), where one can allow different forms of each word.
517+ */
518+ force_words_ids?: number[][] | number[][][];
519+ /**
520+ * Whether to renormalize the logits after applying all the logits processors or warpers (including the custom ones). It's highly recommended to set this flag to `true` as the search algorithms suppose the score logits are normalized but some logit processors or warpers break the normalization.
521+ */
522+ renormalize_logits?: boolean;
523+ /**
524+ * Custom constraints that can be added to the generation to ensure that the output will contain the use of certain tokens as defined by `Constraint` objects, in the most sensible way possible.
525+ */
526+ constraints?: any[];
527+ /**
528+ * The id of the token to force as the first generated token after the `decoder_start_token_id`. Useful for multilingual models like mBART where the first generated token needs to be the target language token.
529+ */
530+ forced_bos_token_id?: number;
531+ /**
532+ * The id of the token to force as the last generated token when `max_length` is reached. Optionally, use a list to set multiple *end-of-sequence* tokens.
533+ */
534+ forced_eos_token_id?: number | number[];
535+ /**
536+ * Whether to remove possible *nan* and *inf* outputs of the model to prevent the generation method to crash. Note that using `remove_invalid_values` can slow down generation.
537+ */
538+ remove_invalid_values?: boolean;
539+ /**
540+ * This Tuple adds an exponentially increasing length penalty, after a certain amount of tokens have been generated. The tuple shall consist of: `(start_index, decay_factor)` where `start_index` indicates where penalty starts and `decay_factor` represents the factor of exponential decay.
541+ */
542+ exponential_decay_length_penalty?: number[];
543+ /**
544+ * A list of tokens that will be suppressed at generation. The `SupressTokens` logit processor will set their log probs to `-inf` so that they are not sampled.
545+ */
546+ suppress_tokens?: number[];
547+ /**
548+ * A list of tokens that will be suppressed at the beginning of the generation. The `SupressBeginTokens` logit processor will set their log probs to `-inf` so that they are not sampled.
549+ */
550+ begin_suppress_tokens?: number[];
551+ /**
552+ * A list of pairs of integers which indicates a mapping from generation indices to token indices that will be forced before sampling. For example, `[[1, 123]]` means the second generated token will always be a token of index 123.
553+ */
554+ forced_decoder_ids?: number[][];
555+ /**
556+ * The number of independently computed returned sequences for each element in the batch.
557+ */
558+ num_return_sequences?: number;
559+ /**
560+ * Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned tensors for more details.
561+ */
562+ output_attentions?: boolean;
563+ /**
564+ * Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for more details.
565+ */
566+ output_hidden_states?: boolean;
567+ /**
568+ * Whether or not to return the prediction scores. See `scores` under returned tensors for more details.
569+ */
570+ output_scores?: boolean;
571+ /**
572+ * Whether or not to return a `ModelOutput` instead of a plain tuple.
573+ */
574+ return_dict_in_generate?: boolean;
575+ /**
576+ * The id of the *padding* token.
577+ */
578+ pad_token_id?: number;
579+ /**
580+ * The id of the *beginning-of-sequence* token.
581+ */
582+ bos_token_id?: number;
583+ /**
584+ * The id of the *end-of-sequence* token. Optionally, use a list to set multiple *end-of-sequence* tokens.
585+ */
586+ eos_token_id?: number | number[];
587+ /**
588+ * If set to int > 0, all ngrams of that size that occur in the `encoder_input_ids` cannot occur in the `decoder_input_ids`.
589+ */
590+ encoder_no_repeat_ngram_size?: number;
591+ /**
592+ * If an encoder-decoder model starts decoding with a different token than *bos*, the id of that token.
593+ */
594+ decoder_start_token_id?: number;
595+ /**
596+ * Additional generation kwargs will be forwarded to the `generate` function of the model. Kwargs that are not present in `generate`'s signature will be used in the model forward pass.
597+ */
598+ generation_kwargs?: any;
590599 };
591-import { Tensor } from './tensor.js';
600+import { Tensor } from "./tensor.js";
592601 export {};
593602 //# sourceMappingURL=generation.d.ts.map
modified core/vendor/modules/@xenova/transformers/types/utils/hub.d.ts +113 −101
@@ -4,7 +4,9 @@
44 * @param {URL|string} urlOrPath The URL/path of the file to get.
55 * @returns {Promise<FileResponse|Response>} A promise that resolves to a FileResponse object (if the file is retrieved using the FileSystem API), or a Response object (if the file is retrieved using the Fetch API).
66 */
7-export function getFile(urlOrPath: URL | string): Promise<FileResponse | Response>;
7+export function getFile(
8+ urlOrPath: URL | string,
9+): Promise<FileResponse | Response>;
810 /**
911 *
1012 * Retrieves a file from either a remote URL using the Fetch API or from the local file system using the FileSystem API.
@@ -20,7 +22,12 @@
2022 * @throws Will throw an error if the file is not found and `fatal` is true.
2123 * @returns {Promise} A Promise that resolves with the file content as a buffer.
2224 */
23-export function getModelFile(path_or_repo_id: string, filename: string, fatal?: boolean, options?: PretrainedOptions): Promise<any>;
25+export function getModelFile(
26+ path_or_repo_id: string,
27+ filename: string,
28+ fatal?: boolean,
29+ options?: PretrainedOptions,
30+): Promise<any>;
2431 /**
2532 * Fetches a JSON file from a given path and file name.
2633 *
@@ -31,43 +38,48 @@
3138 * @returns {Promise<Object>} The JSON data parsed into a JavaScript object.
3239 * @throws Will throw an error if the file is not found and `fatal` is true.
3340 */
34-export function getModelJSON(modelPath: string, fileName: string, fatal?: boolean, options?: PretrainedOptions): Promise<any>;
41+export function getModelJSON(
42+ modelPath: string,
43+ fileName: string,
44+ fatal?: boolean,
45+ options?: PretrainedOptions,
46+): Promise<any>;
3547 /**
3648 * Options for loading a pretrained model.
3749 */
3850 export type PretrainedOptions = {
39- /**
40- * Whether to load the 8-bit quantized version of the model (only applicable when loading model files).
41- */
42- quantized?: boolean | null;
43- /**
44- * If specified, this function will be called during model construction, to provide the user with progress updates.
45- */
46- progress_callback?: Function;
47- /**
48- * Configuration for the model to use instead of an automatically loaded configuration. Configuration can be automatically loaded when:
49- * - The model is a model provided by the library (loaded with the *model id* string of a pretrained model).
50- * - The model is loaded by supplying a local directory as `pretrained_model_name_or_path` and a configuration JSON file named *config.json* is found in the directory.
51- */
52- config?: any;
53- /**
54- * Path to a directory in which a downloaded pretrained model configuration should be cached if the standard cache should not be used.
55- */
56- cache_dir?: string;
57- /**
58- * Whether or not to only look at local files (e.g., not try downloading the model).
59- */
60- local_files_only?: boolean;
61- /**
62- * The specific model version to use. It can be a branch name, a tag name, or a commit id,
63- * since we use a git-based system for storing models and other artifacts on huggingface.co, so `revision` can be any identifier allowed by git.
64- * NOTE: This setting is ignored for local requests.
65- */
66- revision?: string;
67- /**
68- * If specified, load the model with this name (excluding the .onnx suffix). Currently only valid for encoder- or decoder-only models.
69- */
70- model_file_name?: string;
51+ /**
52+ * Whether to load the 8-bit quantized version of the model (only applicable when loading model files).
53+ */
54+ quantized?: boolean | null;
55+ /**
56+ * If specified, this function will be called during model construction, to provide the user with progress updates.
57+ */
58+ progress_callback?: Function;
59+ /**
60+ * Configuration for the model to use instead of an automatically loaded configuration. Configuration can be automatically loaded when:
61+ * - The model is a model provided by the library (loaded with the *model id* string of a pretrained model).
62+ * - The model is loaded by supplying a local directory as `pretrained_model_name_or_path` and a configuration JSON file named *config.json* is found in the directory.
63+ */
64+ config?: any;
65+ /**
66+ * Path to a directory in which a downloaded pretrained model configuration should be cached if the standard cache should not be used.
67+ */
68+ cache_dir?: string;
69+ /**
70+ * Whether or not to only look at local files (e.g., not try downloading the model).
71+ */
72+ local_files_only?: boolean;
73+ /**
74+ * The specific model version to use. It can be a branch name, a tag name, or a commit id,
75+ * since we use a git-based system for storing models and other artifacts on huggingface.co, so `revision` can be any identifier allowed by git.
76+ * NOTE: This setting is ignored for local requests.
77+ */
78+ revision?: string;
79+ /**
80+ * If specified, load the model with this name (excluding the .onnx suffix). Currently only valid for encoder- or decoder-only models.
81+ */
82+ model_file_name?: string;
7183 };
7284 /**
7385 * @typedef {Object} PretrainedOptions Options for loading a pretrained model.
@@ -84,71 +96,71 @@
8496 * @property {string} [model_file_name=null] If specified, load the model with this name (excluding the .onnx suffix). Currently only valid for encoder- or decoder-only models.
8597 */
8698 declare class FileResponse {
87- /**
88- * Creates a new `FileResponse` object.
89- * @param {string|URL} filePath
90- */
91- constructor(filePath: string | URL);
92- /**
93- * Mapping from file extensions to MIME types.
94- */
95- _CONTENT_TYPE_MAP: {
96- txt: string;
97- html: string;
98- css: string;
99- js: string;
100- json: string;
101- png: string;
102- jpg: string;
103- jpeg: string;
104- gif: string;
105- };
106- filePath: string | URL;
107- headers: Headers;
108- exists: any;
109- status: number;
110- statusText: string;
111- body: ReadableStream<any>;
112- /**
113- * Updates the 'content-type' header property of the response based on the extension of
114- * the file specified by the filePath property of the current object.
115- * @returns {void}
116- */
117- updateContentType(): void;
118- /**
119- * Clone the current FileResponse object.
120- * @returns {FileResponse} A new FileResponse object with the same properties as the current object.
121- */
122- clone(): FileResponse;
123- /**
124- * Reads the contents of the file specified by the filePath property and returns a Promise that
125- * resolves with an ArrayBuffer containing the file's contents.
126- * @returns {Promise<ArrayBuffer>} A Promise that resolves with an ArrayBuffer containing the file's contents.
127- * @throws {Error} If the file cannot be read.
128- */
129- arrayBuffer(): Promise<ArrayBuffer>;
130- /**
131- * Reads the contents of the file specified by the filePath property and returns a Promise that
132- * resolves with a Blob containing the file's contents.
133- * @returns {Promise<Blob>} A Promise that resolves with a Blob containing the file's contents.
134- * @throws {Error} If the file cannot be read.
135- */
136- blob(): Promise<Blob>;
137- /**
138- * Reads the contents of the file specified by the filePath property and returns a Promise that
139- * resolves with a string containing the file's contents.
140- * @returns {Promise<string>} A Promise that resolves with a string containing the file's contents.
141- * @throws {Error} If the file cannot be read.
142- */
143- text(): Promise<string>;
144- /**
145- * Reads the contents of the file specified by the filePath property and returns a Promise that
146- * resolves with a parsed JavaScript object containing the file's contents.
147- *
148- * @returns {Promise<Object>} A Promise that resolves with a parsed JavaScript object containing the file's contents.
149- * @throws {Error} If the file cannot be read.
150- */
151- json(): Promise<any>;
99+ /**
100+ * Creates a new `FileResponse` object.
101+ * @param {string|URL} filePath
102+ */
103+ constructor(filePath: string | URL);
104+ /**
105+ * Mapping from file extensions to MIME types.
106+ */
107+ _CONTENT_TYPE_MAP: {
108+ txt: string;
109+ html: string;
110+ css: string;
111+ js: string;
112+ json: string;
113+ png: string;
114+ jpg: string;
115+ jpeg: string;
116+ gif: string;
117+ };
118+ filePath: string | URL;
119+ headers: Headers;
120+ exists: any;
121+ status: number;
122+ statusText: string;
123+ body: ReadableStream<any>;
124+ /**
125+ * Updates the 'content-type' header property of the response based on the extension of
126+ * the file specified by the filePath property of the current object.
127+ * @returns {void}
128+ */
129+ updateContentType(): void;
130+ /**
131+ * Clone the current FileResponse object.
132+ * @returns {FileResponse} A new FileResponse object with the same properties as the current object.
133+ */
134+ clone(): FileResponse;
135+ /**
136+ * Reads the contents of the file specified by the filePath property and returns a Promise that
137+ * resolves with an ArrayBuffer containing the file's contents.
138+ * @returns {Promise<ArrayBuffer>} A Promise that resolves with an ArrayBuffer containing the file's contents.
139+ * @throws {Error} If the file cannot be read.
140+ */
141+ arrayBuffer(): Promise<ArrayBuffer>;
142+ /**
143+ * Reads the contents of the file specified by the filePath property and returns a Promise that
144+ * resolves with a Blob containing the file's contents.
145+ * @returns {Promise<Blob>} A Promise that resolves with a Blob containing the file's contents.
146+ * @throws {Error} If the file cannot be read.
147+ */
148+ blob(): Promise<Blob>;
149+ /**
150+ * Reads the contents of the file specified by the filePath property and returns a Promise that
151+ * resolves with a string containing the file's contents.
152+ * @returns {Promise<string>} A Promise that resolves with a string containing the file's contents.
153+ * @throws {Error} If the file cannot be read.
154+ */
155+ text(): Promise<string>;
156+ /**
157+ * Reads the contents of the file specified by the filePath property and returns a Promise that
158+ * resolves with a parsed JavaScript object containing the file's contents.
159+ *
160+ * @returns {Promise<Object>} A Promise that resolves with a parsed JavaScript object containing the file's contents.
161+ * @throws {Error} If the file cannot be read.
162+ */
163+ json(): Promise<any>;
152164 }
153165 export {};
154-//# sourceMappingURL=hub.d.ts.map
No newline at the end of the file
166+//# sourceMappingURL=hub.d.ts.map
modified core/vendor/modules/@xenova/transformers/types/utils/image.d.ts +123 −109
@@ -1,111 +1,125 @@
11 export class RawImage {
2- /**
3- * Helper method for reading an image from a variety of input types.
4- * @param {RawImage|string|URL} input
5- * @returns The image object.
6- *
7- * **Example:** Read image from a URL.
8- * ```javascript
9- * let image = await RawImage.read('https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/football-match.jpg');
10- * // RawImage {
11- * // "data": Uint8ClampedArray [ 25, 25, 25, 19, 19, 19, ... ],
12- * // "width": 800,
13- * // "height": 533,
14- * // "channels": 3
15- * // }
16- * ```
17- */
18- static read(input: RawImage | string | URL): Promise<RawImage>;
19- /**
20- * Read an image from a URL or file path.
21- * @param {string|URL} url The URL or file path to read the image from.
22- * @returns {Promise<RawImage>} The image object.
23- */
24- static fromURL(url: string | URL): Promise<RawImage>;
25- /**
26- * Helper method to create a new Image from a blob.
27- * @param {Blob} blob The blob to read the image from.
28- * @returns {Promise<RawImage>} The image object.
29- */
30- static fromBlob(blob: Blob): Promise<RawImage>;
31- /**
32- * Helper method to create a new Image from a tensor
33- * @param {import('./tensor.js').Tensor} tensor
34- */
35- static fromTensor(tensor: import('./tensor.js').Tensor, channel_format?: string): RawImage;
36- /**
37- * Create a new `RawImage` object.
38- * @param {Uint8ClampedArray|Uint8Array} data The pixel data.
39- * @param {number} width The width of the image.
40- * @param {number} height The height of the image.
41- * @param {1|2|3|4} channels The number of channels.
42- */
43- constructor(data: Uint8ClampedArray | Uint8Array, width: number, height: number, channels: 1 | 2 | 3 | 4);
44- data: Uint8Array | Uint8ClampedArray;
45- width: number;
46- height: number;
47- channels: 2 | 1 | 3 | 4;
48- /**
49- * Returns the size of the image (width, height).
50- * @returns {[number, number]} The size of the image (width, height).
51- */
52- get size(): [number, number];
53- /**
54- * Convert the image to grayscale format.
55- * @returns {RawImage} `this` to support chaining.
56- */
57- grayscale(): RawImage;
58- /**
59- * Convert the image to RGB format.
60- * @returns {RawImage} `this` to support chaining.
61- */
62- rgb(): RawImage;
63- /**
64- * Convert the image to RGBA format.
65- * @returns {RawImage} `this` to support chaining.
66- */
67- rgba(): RawImage;
68- /**
69- * Resize the image to the given dimensions. This method uses the canvas API to perform the resizing.
70- * @param {number} width The width of the new image.
71- * @param {number} height The height of the new image.
72- * @param {Object} options Additional options for resizing.
73- * @param {0|1|2|3|4|5|string} [options.resample] The resampling method to use.
74- * @returns {Promise<RawImage>} `this` to support chaining.
75- */
76- resize(width: number, height: number, { resample, }?: {
77- resample?: 0 | 1 | 2 | 3 | 4 | 5 | string;
78- }): Promise<RawImage>;
79- pad([left, right, top, bottom]: [any, any, any, any]): Promise<any>;
80- crop([x_min, y_min, x_max, y_max]: [any, any, any, any]): Promise<any>;
81- center_crop(crop_width: any, crop_height: any): Promise<any>;
82- toBlob(type?: string, quality?: number): Promise<any>;
83- toCanvas(): any;
84- /**
85- * Helper method to update the image data.
86- * @param {Uint8ClampedArray} data The new image data.
87- * @param {number} width The new width of the image.
88- * @param {number} height The new height of the image.
89- * @param {1|2|3|4|null} [channels] The new number of channels of the image.
90- * @private
91- */
92- private _update;
93- /**
94- * Clone the image
95- * @returns {RawImage} The cloned image
96- */
97- clone(): RawImage;
98- /**
99- * Helper method for converting image to have a certain number of channels
100- * @param {number} numChannels The number of channels. Must be 1, 3, or 4.
101- * @returns {RawImage} `this` to support chaining.
102- */
103- convert(numChannels: number): RawImage;
104- /**
105- * Save the image to the given path.
106- * @param {string} path The path to save the image to.
107- */
108- save(path: string): Promise<any>;
109- toSharp(): any;
2+ /**
3+ * Helper method for reading an image from a variety of input types.
4+ * @param {RawImage|string|URL} input
5+ * @returns The image object.
6+ *
7+ * **Example:** Read image from a URL.
8+ * ```javascript
9+ * let image = await RawImage.read('https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/football-match.jpg');
10+ * // RawImage {
11+ * // "data": Uint8ClampedArray [ 25, 25, 25, 19, 19, 19, ... ],
12+ * // "width": 800,
13+ * // "height": 533,
14+ * // "channels": 3
15+ * // }
16+ * ```
17+ */
18+ static read(input: RawImage | string | URL): Promise<RawImage>;
19+ /**
20+ * Read an image from a URL or file path.
21+ * @param {string|URL} url The URL or file path to read the image from.
22+ * @returns {Promise<RawImage>} The image object.
23+ */
24+ static fromURL(url: string | URL): Promise<RawImage>;
25+ /**
26+ * Helper method to create a new Image from a blob.
27+ * @param {Blob} blob The blob to read the image from.
28+ * @returns {Promise<RawImage>} The image object.
29+ */
30+ static fromBlob(blob: Blob): Promise<RawImage>;
31+ /**
32+ * Helper method to create a new Image from a tensor
33+ * @param {import('./tensor.js').Tensor} tensor
34+ */
35+ static fromTensor(
36+ tensor: import("./tensor.js").Tensor,
37+ channel_format?: string,
38+ ): RawImage;
39+ /**
40+ * Create a new `RawImage` object.
41+ * @param {Uint8ClampedArray|Uint8Array} data The pixel data.
42+ * @param {number} width The width of the image.
43+ * @param {number} height The height of the image.
44+ * @param {1|2|3|4} channels The number of channels.
45+ */
46+ constructor(
47+ data: Uint8ClampedArray | Uint8Array,
48+ width: number,
49+ height: number,
50+ channels: 1 | 2 | 3 | 4,
51+ );
52+ data: Uint8Array | Uint8ClampedArray;
53+ width: number;
54+ height: number;
55+ channels: 2 | 1 | 3 | 4;
56+ /**
57+ * Returns the size of the image (width, height).
58+ * @returns {[number, number]} The size of the image (width, height).
59+ */
60+ get size(): [number, number];
61+ /**
62+ * Convert the image to grayscale format.
63+ * @returns {RawImage} `this` to support chaining.
64+ */
65+ grayscale(): RawImage;
66+ /**
67+ * Convert the image to RGB format.
68+ * @returns {RawImage} `this` to support chaining.
69+ */
70+ rgb(): RawImage;
71+ /**
72+ * Convert the image to RGBA format.
73+ * @returns {RawImage} `this` to support chaining.
74+ */
75+ rgba(): RawImage;
76+ /**
77+ * Resize the image to the given dimensions. This method uses the canvas API to perform the resizing.
78+ * @param {number} width The width of the new image.
79+ * @param {number} height The height of the new image.
80+ * @param {Object} options Additional options for resizing.
81+ * @param {0|1|2|3|4|5|string} [options.resample] The resampling method to use.
82+ * @returns {Promise<RawImage>} `this` to support chaining.
83+ */
84+ resize(
85+ width: number,
86+ height: number,
87+ {
88+ resample,
89+ }?: {
90+ resample?: 0 | 1 | 2 | 3 | 4 | 5 | string;
91+ },
92+ ): Promise<RawImage>;
93+ pad([left, right, top, bottom]: [any, any, any, any]): Promise<any>;
94+ crop([x_min, y_min, x_max, y_max]: [any, any, any, any]): Promise<any>;
95+ center_crop(crop_width: any, crop_height: any): Promise<any>;
96+ toBlob(type?: string, quality?: number): Promise<any>;
97+ toCanvas(): any;
98+ /**
99+ * Helper method to update the image data.
100+ * @param {Uint8ClampedArray} data The new image data.
101+ * @param {number} width The new width of the image.
102+ * @param {number} height The new height of the image.
103+ * @param {1|2|3|4|null} [channels] The new number of channels of the image.
104+ * @private
105+ */
106+ private _update;
107+ /**
108+ * Clone the image
109+ * @returns {RawImage} The cloned image
110+ */
111+ clone(): RawImage;
112+ /**
113+ * Helper method for converting image to have a certain number of channels
114+ * @param {number} numChannels The number of channels. Must be 1, 3, or 4.
115+ * @returns {RawImage} `this` to support chaining.
116+ */
117+ convert(numChannels: number): RawImage;
118+ /**
119+ * Save the image to the given path.
120+ * @param {string} path The path to save the image to.
121+ */
122+ save(path: string): Promise<any>;
123+ toSharp(): any;
110124 }
111-//# sourceMappingURL=image.d.ts.map
No newline at the end of the file
125+//# sourceMappingURL=image.d.ts.map
modified core/vendor/modules/@xenova/transformers/types/utils/maths.d.ts +211 −163
@@ -14,7 +14,13 @@
1414 /**
1515 * @param {TypedArray} input
1616 */
17-export function interpolate_data(input: TypedArray, [in_channels, in_height, in_width]: [any, any, any], [out_height, out_width]: [any, any], mode?: string, align_corners?: boolean): any;
17+export function interpolate_data(
18+ input: TypedArray,
19+ [in_channels, in_height, in_width]: [any, any, any],
20+ [out_height, out_width]: [any, any],
21+ mode?: string,
22+ align_corners?: boolean,
23+): any;
1824 /**
1925 * Helper method to transpose a `AnyTypedArray` directly
2026 * @template {AnyTypedArray} T
@@ -23,7 +29,11 @@
2329 * @param {number[]} axes
2430 * @returns {[T, number[]]} The transposed array and the new shape.
2531 */
26-export function transpose_data<T extends AnyTypedArray>(array: T, dims: number[], axes: number[]): [T, number[]];
32+export function transpose_data<T extends AnyTypedArray>(
33+ array: T,
34+ dims: number[],
35+ axes: number[],
36+): [T, number[]];
2737 /**
2838 * Compute the softmax of an array of numbers.
2939 * @template {TypedArray|number[]} T
@@ -51,7 +61,10 @@
5161 * @param {number|null} [top_k=0] The number of top items to return (default: 0 = return all)
5262 * @returns {[number, any][]} The top k items, sorted by descending order
5363 */
54-export function getTopItems(items: any[] | TypedArray, top_k?: number | null): [number, any][];
64+export function getTopItems(
65+ items: any[] | TypedArray,
66+ top_k?: number | null,
67+): [number, any][];
5568 /**
5669 * Computes the cosine similarity between two arrays.
5770 *
@@ -94,15 +107,24 @@
94107 */
95108 export function round(num: number, decimals: number): number;
96109 export class FFT {
97- constructor(fft_length: any);
98- fft_length: any;
99- isPowerOfTwo: boolean;
100- fft: P2FFT | NP2FFT;
101- outputBufferSize: number;
102- realTransform(out: any, input: any): void;
103- transform(out: any, input: any): void;
110+ constructor(fft_length: any);
111+ fft_length: any;
112+ isPowerOfTwo: boolean;
113+ fft: P2FFT | NP2FFT;
114+ outputBufferSize: number;
115+ realTransform(out: any, input: any): void;
116+ transform(out: any, input: any): void;
104117 }
105-export type TypedArray = Int8Array | Uint8Array | Uint8ClampedArray | Int16Array | Uint16Array | Int32Array | Uint32Array | Float32Array | Float64Array;
118+export type TypedArray =
119+ | Int8Array
120+ | Uint8Array
121+ | Uint8ClampedArray
122+ | Int16Array
123+ | Uint16Array
124+ | Int32Array
125+ | Uint32Array
126+ | Float32Array
127+ | Float64Array;
106128 export type BigTypedArray = BigInt64Array | BigUint64Array;
107129 export type AnyTypedArray = TypedArray | BigTypedArray;
108130 /**
@@ -113,140 +135,166 @@
113135 * Code adapted from https://www.npmjs.com/package/fft.js
114136 */
115137 declare class P2FFT {
116- /**
117- * @param {number} size The size of the input array. Must be a power of two larger than 1.
118- * @throws {Error} FFT size must be a power of two larger than 1.
119- */
120- constructor(size: number);
121- size: number;
122- _csize: number;
123- table: Float64Array;
124- _width: number;
125- _bitrev: Int32Array;
126- /**
127- * Create a complex number array with size `2 * size`
128- *
129- * @returns {Float64Array} A complex number array with size `2 * size`
130- */
131- createComplexArray(): Float64Array;
132- /**
133- * Converts a complex number representation stored in a Float64Array to an array of real numbers.
134- *
135- * @param {Float64Array} complex The complex number representation to be converted.
136- * @param {number[]} [storage] An optional array to store the result in.
137- * @returns {number[]} An array of real numbers representing the input complex number representation.
138- */
139- fromComplexArray(complex: Float64Array, storage?: number[]): number[];
140- /**
141- * Convert a real-valued input array to a complex-valued output array.
142- * @param {Float64Array} input The real-valued input array.
143- * @param {Float64Array} [storage] Optional buffer to store the output array.
144- * @returns {Float64Array} The complex-valued output array.
145- */
146- toComplexArray(input: Float64Array, storage?: Float64Array): Float64Array;
147- /**
148- * Completes the spectrum by adding its mirrored negative frequency components.
149- * @param {Float64Array} spectrum The input spectrum.
150- * @returns {void}
151- */
152- completeSpectrum(spectrum: Float64Array): void;
153- /**
154- * Performs a Fast Fourier Transform (FFT) on the given input data and stores the result in the output buffer.
155- *
156- * @param {Float64Array} out The output buffer to store the result.
157- * @param {Float64Array} data The input data to transform.
158- *
159- * @throws {Error} Input and output buffers must be different.
160- *
161- * @returns {void}
162- */
163- transform(out: Float64Array, data: Float64Array): void;
164- /**
165- * Performs a real-valued forward FFT on the given input buffer and stores the result in the given output buffer.
166- * The input buffer must contain real values only, while the output buffer will contain complex values. The input and
167- * output buffers must be different.
168- *
169- * @param {Float64Array} out The output buffer.
170- * @param {Float64Array} data The input buffer containing real values.
171- *
172- * @throws {Error} If the input and output buffers are the same.
173- */
174- realTransform(out: Float64Array, data: Float64Array): void;
175- /**
176- * Performs an inverse FFT transformation on the given `data` array, and stores the result in `out`.
177- * The `out` array must be a different buffer than the `data` array. The `out` array will contain the
178- * result of the transformation. The `data` array will not be modified.
179- *
180- * @param {Float64Array} out The output buffer for the transformed data.
181- * @param {Float64Array} data The input data to transform.
182- * @throws {Error} If `out` and `data` refer to the same buffer.
183- * @returns {void}
184- */
185- inverseTransform(out: Float64Array, data: Float64Array): void;
186- /**
187- * Performs a radix-4 implementation of a discrete Fourier transform on a given set of data.
188- *
189- * @param {Float64Array} out The output buffer for the transformed data.
190- * @param {Float64Array} data The input buffer of data to be transformed.
191- * @param {number} inv A scaling factor to apply to the transform.
192- * @returns {void}
193- */
194- _transform4(out: Float64Array, data: Float64Array, inv: number): void;
195- /**
196- * Performs a radix-2 implementation of a discrete Fourier transform on a given set of data.
197- *
198- * @param {Float64Array} data The input buffer of data to be transformed.
199- * @param {Float64Array} out The output buffer for the transformed data.
200- * @param {number} outOff The offset at which to write the output data.
201- * @param {number} off The offset at which to begin reading the input data.
202- * @param {number} step The step size for indexing the input data.
203- * @returns {void}
204- */
205- _singleTransform2(data: Float64Array, out: Float64Array, outOff: number, off: number, step: number): void;
206- /**
207- * Performs radix-4 transformation on input data of length 8
208- *
209- * @param {Float64Array} data Input data array of length 8
210- * @param {Float64Array} out Output data array of length 8
211- * @param {number} outOff Index of output array to start writing from
212- * @param {number} off Index of input array to start reading from
213- * @param {number} step Step size between elements in input array
214- * @param {number} inv Scaling factor for inverse transform
215- *
216- * @returns {void}
217- */
218- _singleTransform4(data: Float64Array, out: Float64Array, outOff: number, off: number, step: number, inv: number): void;
219- /**
220- * Real input radix-4 implementation
221- * @param {Float64Array} out Output array for the transformed data
222- * @param {Float64Array} data Input array of real data to be transformed
223- * @param {number} inv The scale factor used to normalize the inverse transform
224- */
225- _realTransform4(out: Float64Array, data: Float64Array, inv: number): void;
226- /**
227- * Performs a single real input radix-2 transformation on the provided data
228- *
229- * @param {Float64Array} data The input data array
230- * @param {Float64Array} out The output data array
231- * @param {number} outOff The output offset
232- * @param {number} off The input offset
233- * @param {number} step The step
234- *
235- * @returns {void}
236- */
237- _singleRealTransform2(data: Float64Array, out: Float64Array, outOff: number, off: number, step: number): void;
238- /**
239- * Computes a single real-valued transform using radix-4 algorithm.
240- * This method is only called for len=8.
241- *
242- * @param {Float64Array} data The input data array.
243- * @param {Float64Array} out The output data array.
244- * @param {number} outOff The offset into the output array.
245- * @param {number} off The offset into the input array.
246- * @param {number} step The step size for the input array.
247- * @param {number} inv The value of inverse.
248- */
249- _singleRealTransform4(data: Float64Array, out: Float64Array, outOff: number, off: number, step: number, inv: number): void;
138+ /**
139+ * @param {number} size The size of the input array. Must be a power of two larger than 1.
140+ * @throws {Error} FFT size must be a power of two larger than 1.
141+ */
142+ constructor(size: number);
143+ size: number;
144+ _csize: number;
145+ table: Float64Array;
146+ _width: number;
147+ _bitrev: Int32Array;
148+ /**
149+ * Create a complex number array with size `2 * size`
150+ *
151+ * @returns {Float64Array} A complex number array with size `2 * size`
152+ */
153+ createComplexArray(): Float64Array;
154+ /**
155+ * Converts a complex number representation stored in a Float64Array to an array of real numbers.
156+ *
157+ * @param {Float64Array} complex The complex number representation to be converted.
158+ * @param {number[]} [storage] An optional array to store the result in.
159+ * @returns {number[]} An array of real numbers representing the input complex number representation.
160+ */
161+ fromComplexArray(complex: Float64Array, storage?: number[]): number[];
162+ /**
163+ * Convert a real-valued input array to a complex-valued output array.
164+ * @param {Float64Array} input The real-valued input array.
165+ * @param {Float64Array} [storage] Optional buffer to store the output array.
166+ * @returns {Float64Array} The complex-valued output array.
167+ */
168+ toComplexArray(input: Float64Array, storage?: Float64Array): Float64Array;
169+ /**
170+ * Completes the spectrum by adding its mirrored negative frequency components.
171+ * @param {Float64Array} spectrum The input spectrum.
172+ * @returns {void}
173+ */
174+ completeSpectrum(spectrum: Float64Array): void;
175+ /**
176+ * Performs a Fast Fourier Transform (FFT) on the given input data and stores the result in the output buffer.
177+ *
178+ * @param {Float64Array} out The output buffer to store the result.
179+ * @param {Float64Array} data The input data to transform.
180+ *
181+ * @throws {Error} Input and output buffers must be different.
182+ *
183+ * @returns {void}
184+ */
185+ transform(out: Float64Array, data: Float64Array): void;
186+ /**
187+ * Performs a real-valued forward FFT on the given input buffer and stores the result in the given output buffer.
188+ * The input buffer must contain real values only, while the output buffer will contain complex values. The input and
189+ * output buffers must be different.
190+ *
191+ * @param {Float64Array} out The output buffer.
192+ * @param {Float64Array} data The input buffer containing real values.
193+ *
194+ * @throws {Error} If the input and output buffers are the same.
195+ */
196+ realTransform(out: Float64Array, data: Float64Array): void;
197+ /**
198+ * Performs an inverse FFT transformation on the given `data` array, and stores the result in `out`.
199+ * The `out` array must be a different buffer than the `data` array. The `out` array will contain the
200+ * result of the transformation. The `data` array will not be modified.
201+ *
202+ * @param {Float64Array} out The output buffer for the transformed data.
203+ * @param {Float64Array} data The input data to transform.
204+ * @throws {Error} If `out` and `data` refer to the same buffer.
205+ * @returns {void}
206+ */
207+ inverseTransform(out: Float64Array, data: Float64Array): void;
208+ /**
209+ * Performs a radix-4 implementation of a discrete Fourier transform on a given set of data.
210+ *
211+ * @param {Float64Array} out The output buffer for the transformed data.
212+ * @param {Float64Array} data The input buffer of data to be transformed.
213+ * @param {number} inv A scaling factor to apply to the transform.
214+ * @returns {void}
215+ */
216+ _transform4(out: Float64Array, data: Float64Array, inv: number): void;
217+ /**
218+ * Performs a radix-2 implementation of a discrete Fourier transform on a given set of data.
219+ *
220+ * @param {Float64Array} data The input buffer of data to be transformed.
221+ * @param {Float64Array} out The output buffer for the transformed data.
222+ * @param {number} outOff The offset at which to write the output data.
223+ * @param {number} off The offset at which to begin reading the input data.
224+ * @param {number} step The step size for indexing the input data.
225+ * @returns {void}
226+ */
227+ _singleTransform2(
228+ data: Float64Array,
229+ out: Float64Array,
230+ outOff: number,
231+ off: number,
232+ step: number,
233+ ): void;
234+ /**
235+ * Performs radix-4 transformation on input data of length 8
236+ *
237+ * @param {Float64Array} data Input data array of length 8
238+ * @param {Float64Array} out Output data array of length 8
239+ * @param {number} outOff Index of output array to start writing from
240+ * @param {number} off Index of input array to start reading from
241+ * @param {number} step Step size between elements in input array
242+ * @param {number} inv Scaling factor for inverse transform
243+ *
244+ * @returns {void}
245+ */
246+ _singleTransform4(
247+ data: Float64Array,
248+ out: Float64Array,
249+ outOff: number,
250+ off: number,
251+ step: number,
252+ inv: number,
253+ ): void;
254+ /**
255+ * Real input radix-4 implementation
256+ * @param {Float64Array} out Output array for the transformed data
257+ * @param {Float64Array} data Input array of real data to be transformed
258+ * @param {number} inv The scale factor used to normalize the inverse transform
259+ */
260+ _realTransform4(out: Float64Array, data: Float64Array, inv: number): void;
261+ /**
262+ * Performs a single real input radix-2 transformation on the provided data
263+ *
264+ * @param {Float64Array} data The input data array
265+ * @param {Float64Array} out The output data array
266+ * @param {number} outOff The output offset
267+ * @param {number} off The input offset
268+ * @param {number} step The step
269+ *
270+ * @returns {void}
271+ */
272+ _singleRealTransform2(
273+ data: Float64Array,
274+ out: Float64Array,
275+ outOff: number,
276+ off: number,
277+ step: number,
278+ ): void;
279+ /**
280+ * Computes a single real-valued transform using radix-4 algorithm.
281+ * This method is only called for len=8.
282+ *
283+ * @param {Float64Array} data The input data array.
284+ * @param {Float64Array} out The output data array.
285+ * @param {number} outOff The offset into the output array.
286+ * @param {number} off The offset into the input array.
287+ * @param {number} step The step size for the input array.
288+ * @param {number} inv The value of inverse.
289+ */
290+ _singleRealTransform4(
291+ data: Float64Array,
292+ out: Float64Array,
293+ outOff: number,
294+ off: number,
295+ step: number,
296+ inv: number,
297+ ): void;
250298 }
251299 /**
252300 * NP2FFT class provides functionality for performing Fast Fourier Transform on arrays
@@ -255,23 +303,23 @@
255303 * For more information, see: https://math.stackexchange.com/questions/77118/non-power-of-2-ffts/77156#77156
256304 */
257305 declare class NP2FFT {
258- /**
259- * Constructs a new NP2FFT object.
260- * @param {number} fft_length The length of the FFT
261- */
262- constructor(fft_length: number);
263- bufferSize: number;
264- _a: number;
265- _chirpBuffer: Float64Array;
266- _buffer1: Float64Array;
267- _buffer2: Float64Array;
268- _outBuffer1: Float64Array;
269- _outBuffer2: Float64Array;
270- _slicedChirpBuffer: Float64Array;
271- _f: P2FFT;
272- _transform(output: any, input: any, real: any): void;
273- transform(output: any, input: any): void;
274- realTransform(output: any, input: any): void;
306+ /**
307+ * Constructs a new NP2FFT object.
308+ * @param {number} fft_length The length of the FFT
309+ */
310+ constructor(fft_length: number);
311+ bufferSize: number;
312+ _a: number;
313+ _chirpBuffer: Float64Array;
314+ _buffer1: Float64Array;
315+ _buffer2: Float64Array;
316+ _outBuffer1: Float64Array;
317+ _outBuffer2: Float64Array;
318+ _slicedChirpBuffer: Float64Array;
319+ _f: P2FFT;
320+ _transform(output: any, input: any, real: any): void;
321+ transform(output: any, input: any): void;
322+ realTransform(output: any, input: any): void;
275323 }
276324 export {};
277-//# sourceMappingURL=maths.d.ts.map
No newline at the end of the file
325+//# sourceMappingURL=maths.d.ts.map
modified core/vendor/modules/@xenova/transformers/types/utils/tensor.d.ts +246 −221
@@ -13,14 +13,22 @@
1313 * @param {boolean} align_corners Whether to align corners.
1414 * @returns {Tensor} The interpolated tensor.
1515 */
16-export function interpolate(input: Tensor, [out_height, out_width]: number[], mode?: string, align_corners?: boolean): Tensor;
16+export function interpolate(
17+ input: Tensor,
18+ [out_height, out_width]: number[],
19+ mode?: string,
20+ align_corners?: boolean,
21+): Tensor;
1722 /**
1823 * Perform mean pooling of the last hidden state followed by a normalization step.
1924 * @param {Tensor} last_hidden_state Tensor of shape [batchSize, seqLength, embedDim]
2025 * @param {Tensor} attention_mask Tensor of shape [batchSize, seqLength]
2126 * @returns {Tensor} Returns a new Tensor of shape [batchSize, embedDim].
2227 */
23-export function mean_pooling(last_hidden_state: Tensor, attention_mask: Tensor): Tensor;
28+export function mean_pooling(
29+ last_hidden_state: Tensor,
30+ attention_mask: Tensor,
31+): Tensor;
2432 /**
2533 * Concatenates an array of tensors along a specified dimension.
2634 * @param {Tensor[]} tensors The array of tensors to concatenate.
@@ -43,7 +51,12 @@
4351 * @param {boolean} keepdim whether the output tensor has dim retained or not.
4452 * @returns {Tensor[]} A tuple of (std, mean) tensors.
4553 */
46-export function std_mean(input: Tensor, dim?: number | null, correction?: number, keepdim?: boolean): Tensor[];
54+export function std_mean(
55+ input: Tensor,
56+ dim?: number | null,
57+ correction?: number,
58+ keepdim?: boolean,
59+): Tensor[];
4760 /**
4861 * Returns the mean value of each row of the input tensor in the given dimension dim.
4962 * @param {Tensor} input the input tensor.
@@ -51,7 +64,11 @@
5164 * @param {boolean} keepdim whether the output tensor has dim retained or not.
5265 * @returns A new tensor with means taken along the specified dimension.
5366 */
54-export function mean(input: Tensor, dim?: number | null, keepdim?: boolean): Tensor;
67+export function mean(
68+ input: Tensor,
69+ dim?: number | null,
70+ keepdim?: boolean,
71+): Tensor;
5572 /**
5673 *
5774 * Measures similarity between two temporal sequences (e.g., input audio and output tokens
@@ -72,228 +89,236 @@
7289 */
7390 export function ones_like(tensor: Tensor): Tensor;
7491 export class Tensor {
75- /**
76- * Create a new Tensor or copy an existing Tensor.
77- * @param {[DataType, DataArray, number[]]|[import('onnxruntime-common').Tensor]} args
78- */
79- constructor(...args: [DataType, DataArray, number[]] | [import('onnxruntime-common').Tensor]);
80- /** @type {number[]} Dimensions of the tensor. */
81- dims: number[];
82- /** @type {DataType} Type of the tensor. */
83- type: DataType;
84- /** @type {DataArray} The data stored in the tensor. */
85- data: DataArray;
86- /** @type {number} The number of elements in the tensor. */
87- size: number;
88- /**
89- * Index into a Tensor object.
90- * @param {number} index The index to access.
91- * @returns {Tensor} The data at the specified index.
92- */
93- _getitem(index: number): Tensor;
94- /**
95- * @param {number|bigint} item The item to search for in the tensor
96- * @returns {number} The index of the first occurrence of item in the tensor data.
97- */
98- indexOf(item: number | bigint): number;
99- /**
100- * @param {number} index
101- * @param {number} iterSize
102- * @param {any} iterDims
103- * @returns {Tensor}
104- */
105- _subarray(index: number, iterSize: number, iterDims: any): Tensor;
106- /**
107- * Returns the value of this tensor as a standard JavaScript Number. This only works
108- * for tensors with one element. For other cases, see `Tensor.tolist()`.
109- * @returns {number|bigint} The value of this tensor as a standard JavaScript Number.
110- * @throws {Error} If the tensor has more than one element.
111- */
112- item(): number | bigint;
113- /**
114- * Convert tensor data to a n-dimensional JS list
115- * @returns {Array}
116- */
117- tolist(): any[];
118- /**
119- * Return a new Tensor with the sigmoid function applied to each element.
120- * @returns {Tensor} The tensor with the sigmoid function applied.
121- */
122- sigmoid(): Tensor;
123- /**
124- * Applies the sigmoid function to the tensor in place.
125- * @returns {Tensor} Returns `this`.
126- */
127- sigmoid_(): Tensor;
128- /**
129- * Return a new Tensor with every element multiplied by a constant.
130- * @param {number} val The value to multiply by.
131- * @returns {Tensor} The new tensor.
132- */
133- mul(val: number): Tensor;
134- /**
135- * Multiply the tensor by a constant in place.
136- * @param {number} val The value to multiply by.
137- * @returns {Tensor} Returns `this`.
138- */
139- mul_(val: number): Tensor;
140- /**
141- * Return a new Tensor with every element added by a constant.
142- * @param {number} val The value to add by.
143- * @returns {Tensor} The new tensor.
144- */
145- add(val: number): Tensor;
146- /**
147- * Add the tensor by a constant in place.
148- * @param {number} val The value to add by.
149- * @returns {Tensor} Returns `this`.
150- */
151- add_(val: number): Tensor;
152- clone(): Tensor;
153- slice(...slices: any[]): Tensor;
154- /**
155- * Return a transposed version of this Tensor, according to the provided dimensions.
156- * @param {...number} dims Dimensions to transpose.
157- * @returns {Tensor} The transposed tensor.
158- */
159- transpose(...dims: number[]): Tensor;
160- /**
161- * Returns the sum of each row of the input tensor in the given dimension dim.
162- *
163- * @param {number} [dim=null] The dimension or dimensions to reduce. If `null`, all dimensions are reduced.
164- * @param {boolean} keepdim Whether the output tensor has `dim` retained or not.
165- * @returns The summed tensor
166- */
167- sum(dim?: number, keepdim?: boolean): Tensor;
168- /**
169- * Returns the matrix norm or vector norm of a given tensor.
170- * @param {number|string} [p='fro'] The order of norm
171- * @param {number} [dim=null] Specifies which dimension of the tensor to calculate the norm across.
172- * If dim is None, the norm will be calculated across all dimensions of input.
173- * @param {boolean} [keepdim=false] Whether the output tensors have dim retained or not.
174- * @returns {Tensor} The norm of the tensor.
175- */
176- norm(p?: number | string, dim?: number, keepdim?: boolean): Tensor;
177- /**
178- * Performs `L_p` normalization of inputs over specified dimension. Operates in place.
179- * @param {number} [p=2] The exponent value in the norm formulation
180- * @param {number} [dim=1] The dimension to reduce
181- * @returns {Tensor} `this` for operation chaining.
182- */
183- normalize_(p?: number, dim?: number): Tensor;
184- /**
185- * Performs `L_p` normalization of inputs over specified dimension.
186- * @param {number} [p=2] The exponent value in the norm formulation
187- * @param {number} [dim=1] The dimension to reduce
188- * @returns {Tensor} The normalized tensor.
189- */
190- normalize(p?: number, dim?: number): Tensor;
191- /**
192- * Compute and return the stride of this tensor.
193- * Stride is the jump necessary to go from one element to the next one in the specified dimension dim.
194- * @returns {number[]} The stride of this tensor.
195- */
196- stride(): number[];
197- /**
198- * Returns a tensor with all specified dimensions of input of size 1 removed.
199- *
200- * NOTE: The returned tensor shares the storage with the input tensor, so changing the contents of one will change the contents of the other.
201- * If you would like a copy, use `tensor.clone()` before squeezing.
202- *
203- * @param {number} [dim=null] If given, the input will be squeezed only in the specified dimensions.
204- * @returns The squeezed tensor
205- */
206- squeeze(dim?: number): Tensor;
207- /**
208- * In-place version of @see {@link Tensor.squeeze}
209- */
210- squeeze_(dim?: any): this;
211- /**
212- * Returns a new tensor with a dimension of size one inserted at the specified position.
213- *
214- * NOTE: The returned tensor shares the same underlying data with this tensor.
215- *
216- * @param {number} dim The index at which to insert the singleton dimension
217- * @returns The unsqueezed tensor
218- */
219- unsqueeze(dim?: number): Tensor;
220- /**
221- * In-place version of @see {@link Tensor.unsqueeze}
222- */
223- unsqueeze_(dim?: any): this;
224- /**
225- * In-place version of @see {@link Tensor.flatten}
226- */
227- flatten_(start_dim?: number, end_dim?: number): this;
228- /**
229- * Flattens input by reshaping it into a one-dimensional tensor.
230- * If `start_dim` or `end_dim` are passed, only dimensions starting with `start_dim`
231- * and ending with `end_dim` are flattened. The order of elements in input is unchanged.
232- * @param {number} start_dim the first dim to flatten
233- * @param {number} end_dim the last dim to flatten
234- * @returns The flattened tensor.
235- */
236- flatten(start_dim?: number, end_dim?: number): Tensor;
237- /**
238- * Returns a new tensor with the same data as the `self` tensor but of a different `shape`.
239- * @param {...number} dims the desired size
240- * @returns {Tensor} The tensor with the same data but different shape
241- */
242- view(...dims: number[]): Tensor;
243- neg_(): this;
244- neg(): Tensor;
245- /**
246- * In-place version of @see {@link Tensor.clamp}
247- */
248- clamp_(min: any, max: any): this;
249- /**
250- * Clamps all elements in input into the range [ min, max ]
251- * @param {number} min lower-bound of the range to be clamped to
252- * @param {number} max upper-bound of the range to be clamped to
253- * @returns the output tensor.
254- */
255- clamp(min: number, max: number): Tensor;
256- /**
257- * In-place version of @see {@link Tensor.round}
258- */
259- round_(): this;
260- /**
261- * Rounds elements of input to the nearest integer.
262- * @returns the output tensor.
263- */
264- round(): Tensor;
265- /**
266- * Performs Tensor dtype conversion.
267- * @param {DataType} type The desired data type.
268- * @returns {Tensor} The converted tensor.
269- */
270- to(type: DataType): Tensor;
271- /**
272- * Returns an iterator object for iterating over the tensor data in row-major order.
273- * If the tensor has more than one dimension, the iterator will yield subarrays.
274- * @returns {Iterator} An iterator object for iterating over the tensor data in row-major order.
275- */
276- [Symbol.iterator](): Iterator<any, any, undefined>;
92+ /**
93+ * Create a new Tensor or copy an existing Tensor.
94+ * @param {[DataType, DataArray, number[]]|[import('onnxruntime-common').Tensor]} args
95+ */
96+ constructor(
97+ ...args:
98+ | [DataType, DataArray, number[]]
99+ | [import("onnxruntime-common").Tensor]
100+ );
101+ /** @type {number[]} Dimensions of the tensor. */
102+ dims: number[];
103+ /** @type {DataType} Type of the tensor. */
104+ type: DataType;
105+ /** @type {DataArray} The data stored in the tensor. */
106+ data: DataArray;
107+ /** @type {number} The number of elements in the tensor. */
108+ size: number;
109+ /**
110+ * Index into a Tensor object.
111+ * @param {number} index The index to access.
112+ * @returns {Tensor} The data at the specified index.
113+ */
114+ _getitem(index: number): Tensor;
115+ /**
116+ * @param {number|bigint} item The item to search for in the tensor
117+ * @returns {number} The index of the first occurrence of item in the tensor data.
118+ */
119+ indexOf(item: number | bigint): number;
120+ /**
121+ * @param {number} index
122+ * @param {number} iterSize
123+ * @param {any} iterDims
124+ * @returns {Tensor}
125+ */
126+ _subarray(index: number, iterSize: number, iterDims: any): Tensor;
127+ /**
128+ * Returns the value of this tensor as a standard JavaScript Number. This only works
129+ * for tensors with one element. For other cases, see `Tensor.tolist()`.
130+ * @returns {number|bigint} The value of this tensor as a standard JavaScript Number.
131+ * @throws {Error} If the tensor has more than one element.
132+ */
133+ item(): number | bigint;
134+ /**
135+ * Convert tensor data to a n-dimensional JS list
136+ * @returns {Array}
137+ */
138+ tolist(): any[];
139+ /**
140+ * Return a new Tensor with the sigmoid function applied to each element.
141+ * @returns {Tensor} The tensor with the sigmoid function applied.
142+ */
143+ sigmoid(): Tensor;
144+ /**
145+ * Applies the sigmoid function to the tensor in place.
146+ * @returns {Tensor} Returns `this`.
147+ */
148+ sigmoid_(): Tensor;
149+ /**
150+ * Return a new Tensor with every element multiplied by a constant.
151+ * @param {number} val The value to multiply by.
152+ * @returns {Tensor} The new tensor.
153+ */
154+ mul(val: number): Tensor;
155+ /**
156+ * Multiply the tensor by a constant in place.
157+ * @param {number} val The value to multiply by.
158+ * @returns {Tensor} Returns `this`.
159+ */
160+ mul_(val: number): Tensor;
161+ /**
162+ * Return a new Tensor with every element added by a constant.
163+ * @param {number} val The value to add by.
164+ * @returns {Tensor} The new tensor.
165+ */
166+ add(val: number): Tensor;
167+ /**
168+ * Add the tensor by a constant in place.
169+ * @param {number} val The value to add by.
170+ * @returns {Tensor} Returns `this`.
171+ */
172+ add_(val: number): Tensor;
173+ clone(): Tensor;
174+ slice(...slices: any[]): Tensor;
175+ /**
176+ * Return a transposed version of this Tensor, according to the provided dimensions.
177+ * @param {...number} dims Dimensions to transpose.
178+ * @returns {Tensor} The transposed tensor.
179+ */
180+ transpose(...dims: number[]): Tensor;
181+ /**
182+ * Returns the sum of each row of the input tensor in the given dimension dim.
183+ *
184+ * @param {number} [dim=null] The dimension or dimensions to reduce. If `null`, all dimensions are reduced.
185+ * @param {boolean} keepdim Whether the output tensor has `dim` retained or not.
186+ * @returns The summed tensor
187+ */
188+ sum(dim?: number, keepdim?: boolean): Tensor;
189+ /**
190+ * Returns the matrix norm or vector norm of a given tensor.
191+ * @param {number|string} [p='fro'] The order of norm
192+ * @param {number} [dim=null] Specifies which dimension of the tensor to calculate the norm across.
193+ * If dim is None, the norm will be calculated across all dimensions of input.
194+ * @param {boolean} [keepdim=false] Whether the output tensors have dim retained or not.
195+ * @returns {Tensor} The norm of the tensor.
196+ */
197+ norm(p?: number | string, dim?: number, keepdim?: boolean): Tensor;
198+ /**
199+ * Performs `L_p` normalization of inputs over specified dimension. Operates in place.
200+ * @param {number} [p=2] The exponent value in the norm formulation
201+ * @param {number} [dim=1] The dimension to reduce
202+ * @returns {Tensor} `this` for operation chaining.
203+ */
204+ normalize_(p?: number, dim?: number): Tensor;
205+ /**
206+ * Performs `L_p` normalization of inputs over specified dimension.
207+ * @param {number} [p=2] The exponent value in the norm formulation
208+ * @param {number} [dim=1] The dimension to reduce
209+ * @returns {Tensor} The normalized tensor.
210+ */
211+ normalize(p?: number, dim?: number): Tensor;
212+ /**
213+ * Compute and return the stride of this tensor.
214+ * Stride is the jump necessary to go from one element to the next one in the specified dimension dim.
215+ * @returns {number[]} The stride of this tensor.
216+ */
217+ stride(): number[];
218+ /**
219+ * Returns a tensor with all specified dimensions of input of size 1 removed.
220+ *
221+ * NOTE: The returned tensor shares the storage with the input tensor, so changing the contents of one will change the contents of the other.
222+ * If you would like a copy, use `tensor.clone()` before squeezing.
223+ *
224+ * @param {number} [dim=null] If given, the input will be squeezed only in the specified dimensions.
225+ * @returns The squeezed tensor
226+ */
227+ squeeze(dim?: number): Tensor;
228+ /**
229+ * In-place version of @see {@link Tensor.squeeze}
230+ */
231+ squeeze_(dim?: any): this;
232+ /**
233+ * Returns a new tensor with a dimension of size one inserted at the specified position.
234+ *
235+ * NOTE: The returned tensor shares the same underlying data with this tensor.
236+ *
237+ * @param {number} dim The index at which to insert the singleton dimension
238+ * @returns The unsqueezed tensor
239+ */
240+ unsqueeze(dim?: number): Tensor;
241+ /**
242+ * In-place version of @see {@link Tensor.unsqueeze}
243+ */
244+ unsqueeze_(dim?: any): this;
245+ /**
246+ * In-place version of @see {@link Tensor.flatten}
247+ */
248+ flatten_(start_dim?: number, end_dim?: number): this;
249+ /**
250+ * Flattens input by reshaping it into a one-dimensional tensor.
251+ * If `start_dim` or `end_dim` are passed, only dimensions starting with `start_dim`
252+ * and ending with `end_dim` are flattened. The order of elements in input is unchanged.
253+ * @param {number} start_dim the first dim to flatten
254+ * @param {number} end_dim the last dim to flatten
255+ * @returns The flattened tensor.
256+ */
257+ flatten(start_dim?: number, end_dim?: number): Tensor;
258+ /**
259+ * Returns a new tensor with the same data as the `self` tensor but of a different `shape`.
260+ * @param {...number} dims the desired size
261+ * @returns {Tensor} The tensor with the same data but different shape
262+ */
263+ view(...dims: number[]): Tensor;
264+ neg_(): this;
265+ neg(): Tensor;
266+ /**
267+ * In-place version of @see {@link Tensor.clamp}
268+ */
269+ clamp_(min: any, max: any): this;
270+ /**
271+ * Clamps all elements in input into the range [ min, max ]
272+ * @param {number} min lower-bound of the range to be clamped to
273+ * @param {number} max upper-bound of the range to be clamped to
274+ * @returns the output tensor.
275+ */
276+ clamp(min: number, max: number): Tensor;
277+ /**
278+ * In-place version of @see {@link Tensor.round}
279+ */
280+ round_(): this;
281+ /**
282+ * Rounds elements of input to the nearest integer.
283+ * @returns the output tensor.
284+ */
285+ round(): Tensor;
286+ /**
287+ * Performs Tensor dtype conversion.
288+ * @param {DataType} type The desired data type.
289+ * @returns {Tensor} The converted tensor.
290+ */
291+ to(type: DataType): Tensor;
292+ /**
293+ * Returns an iterator object for iterating over the tensor data in row-major order.
294+ * If the tensor has more than one dimension, the iterator will yield subarrays.
295+ * @returns {Iterator} An iterator object for iterating over the tensor data in row-major order.
296+ */
297+ [Symbol.iterator](): Iterator<any, any, undefined>;
277298 }
278299 /**
279300 * This creates a nested array of a given type and depth (see examples).
280301 */
281-export type NestArray<T, Depth extends number, Acc extends never[] = []> = Acc['length'] extends Depth ? T : NestArray<T[], Depth, [...Acc, never]>;
302+export type NestArray<
303+ T,
304+ Depth extends number,
305+ Acc extends never[] = [],
306+> = Acc["length"] extends Depth ? T : NestArray<T[], Depth, [...Acc, never]>;
282307 export type DataType = keyof typeof DataTypeMap;
283-export type DataArray = import('./maths.js').AnyTypedArray | any[];
308+export type DataArray = import("./maths.js").AnyTypedArray | any[];
284309 declare const DataTypeMap: Readonly<{
285- float32: Float32ArrayConstructor;
286- float64: Float64ArrayConstructor;
287- string: ArrayConstructor;
288- int8: Int8ArrayConstructor;
289- uint8: Uint8ArrayConstructor;
290- int16: Int16ArrayConstructor;
291- uint16: Uint16ArrayConstructor;
292- int32: Int32ArrayConstructor;
293- uint32: Uint32ArrayConstructor;
294- int64: BigInt64ArrayConstructor;
295- uint64: BigUint64ArrayConstructor;
296- bool: Uint8ArrayConstructor;
310+ float32: Float32ArrayConstructor;
311+ float64: Float64ArrayConstructor;
312+ string: ArrayConstructor;
313+ int8: Int8ArrayConstructor;
314+ uint8: Uint8ArrayConstructor;
315+ int16: Int16ArrayConstructor;
316+ uint16: Uint16ArrayConstructor;
317+ int32: Int32ArrayConstructor;
318+ uint32: Uint32ArrayConstructor;
319+ int64: BigInt64ArrayConstructor;
320+ uint64: BigUint64ArrayConstructor;
321+ bool: Uint8ArrayConstructor;
297322 }>;
298323 export {};
299-//# sourceMappingURL=tensor.d.ts.map
No newline at the end of the file
324+//# sourceMappingURL=tensor.d.ts.map
modified docs/babel.config.js +1 −1
@@ -1,3 +1,3 @@
11 module.exports = {
2- presets: [require.resolve('@docusaurus/core/lib/babel/preset')],
2+ presets: [require.resolve("@docusaurus/core/lib/babel/preset")],
33 };
modified docs/docs/CLA.md +1 −1
@@ -22,7 +22,7 @@
2222 license to reproduce, prepare derivative works of, publicly display, publicly
2323 perform, sublicense, and distribute Your Contributions and derivative works.
2424
25-## 3. Patent License
25+## 3. Patent License
2626
2727 You grant **Continue Dev, Inc.** and all recipients of the Project a perpetual,
2828 worldwide, non‑exclusive, royalty‑free, irrevocable (except as below) patent
modified docs/docs/agent/context-selection.md +2 −2
@@ -7,6 +7,6 @@
77
88 You can use the same [methods to manually add context as Chat](../chat/context-selection.md).
99
10-In addition, tool call responses are automatically included as context items.
10+In addition, tool call responses are automatically included as context items.
1111
12-This enables Agent mode to see the result of the previous action and decide what to do next.
No newline at the end of the file
12+This enables Agent mode to see the result of the previous action and decide what to do next.
modified docs/docs/agent/how-to-customize.md +1 −1
@@ -29,4 +29,4 @@
2929
3030 ![Tool Policies](/img/tool-policies.png)
3131
32-Tool policies are stored locally per user.
No newline at the end of the file
32+Tool policies are stored locally per user.
modified docs/docs/agent/how-to-use-it.md +2 −2
@@ -28,7 +28,7 @@
2828
2929 #### Use natural language
3030
31-With Agent, you can provide natural language instruction and let the model do the work. As an example, you might say
31+With Agent, you can provide natural language instruction and let the model do the work. As an example, you might say
3232
3333 > Set the @typescript-eslint/naming-convention rule to "off" for all eslint configurations in this project
3434
@@ -46,4 +46,4 @@
4646
4747 Any data returned from a tool call is automatically fed back into the model as a context item. Most errors are also caught and returned, so that Agent mode can decide how to proceed.
4848
49-![agent response](/img/agent-response.png)
No newline at the end of the file
49+![agent response](/img/agent-response.png)
modified docs/docs/customize/changelog.md +1 −1
@@ -10,4 +10,4 @@
1010
1111 <head>
1212 <meta http-equiv="refresh" content="0;url=https://changelog.continue.dev" />
13-</head>
No newline at the end of the file
13+</head>
modified docs/docs/customize/model-providers/more/venice.md +3 −3
@@ -1,6 +1,6 @@
11 # Venice
22
3-Venice.AI is a privacy focused generative AI platform, allowing users to interact with open-source LLMs without storing any private user data. To get started with Venice's API, either purchase a pro account, stake $VVV to obtain daily inference allotments or fund your account with USD and head over to https://venice.ai/settings/api. Venice hosts state of the art open-source AI models and supports the OpenAI API standard, allowing users to easily interact with the platform. Learn more about the Venice API at https://venice.ai/api.
3+Venice.AI is a privacy focused generative AI platform, allowing users to interact with open-source LLMs without storing any private user data. To get started with Venice's API, either purchase a pro account, stake $VVV to obtain daily inference allotments or fund your account with USD and head over to https://venice.ai/settings/api. Venice hosts state of the art open-source AI models and supports the OpenAI API standard, allowing users to easily interact with the platform. Learn more about the Venice API at https://venice.ai/api.
44
55 Change `~/.continue/config.json` to look like the following.
66
@@ -28,8 +28,8 @@
2828 "include_venice_system_prompt" : false
2929 },
3030 ...
31- }
31+ }
3232 }
3333 ```
3434
35-Learn more about available settings [here](https://docs.venice.ai/api-reference/api-spec).
No newline at the end of the file
35+Learn more about available settings [here](https://docs.venice.ai/api-reference/api-spec).
modified docs/docs/customize/model-roles/autocomplete.md +1 −1
@@ -38,4 +38,4 @@
3838 globalThis.importantFunc = importantFunc
3939 <|fim_prefix|>{{{prefix}}}<|fim_suffix|>{{{suffix}}}<|fim_middle|>
4040 `
41-```
No newline at the end of the file
41+```
modified docs/docs/hub/assistants/edit-an-assistant.md +1 −1
@@ -23,4 +23,4 @@
2323
2424 When you are done editing, click "Publish" to publish a new version of the assistant.
2525
26-Click "Open VS Code" or "Open JetBrains" to open your IDE for using the assistant.
No newline at the end of the file
26+Click "Open VS Code" or "Open JetBrains" to open your IDE for using the assistant.
modified docs/docs/hub/assistants/use-an-assistant.md +1 −1
@@ -17,4 +17,4 @@
1717
1818 After this, you can then go to your IDE extension and begin using the assistant by selecting it from the assistant dropdown.
1919
20-[Extension Assistant Selector](/img/hub/assistant-extension-select.png)
No newline at the end of the file
20+[Extension Assistant Selector](/img/hub/assistant-extension-select.png)
modified docs/docs/hub/blocks/bundles.md +1 −1
@@ -36,4 +36,4 @@
3636
3737 ## Remix a bundle
3838
39-It is not currently possible to remix a bundle.
No newline at the end of the file
39+It is not currently possible to remix a bundle.
modified docs/docs/hub/blocks/use-a-block.md +2 −1
@@ -7,9 +7,10 @@
77 # Use a block
88
99 Blocks can be used by adding them to assistants:
10+
1011 - [Create an assistant](../assistants/create-an-assistant.md)
1112 - [Edit an assistant](../assistants/edit-an-assistant.md)
1213
1314 Some blocks require inputs. If you are missing an input for a block, a notification icon will show up in the sidebar next to the block. Click the notification to select which secret to use for the block input:
1415
15-![Block inputs](/img/hub/block-inputs.png)
No newline at the end of the file
16+![Block inputs](/img/hub/block-inputs.png)
modified docs/docs/hub/governance/org-permissions.md +1 −1
@@ -15,4 +15,4 @@
1515
1616 - [Solo](./pricing.md#solo)
1717 - [Teams](./pricing.md#teams)
18-- [Enterprise](./pricing.md#enterprise)
No newline at the end of the file
18+- [Enterprise](./pricing.md#enterprise)
modified docs/docs/hub/governance/pricing.md +5 −5
@@ -8,28 +8,28 @@
88
99 ## Solo
1010
11-**Solo** is best suited for individuals and small teams with "single-player" problems.
11+**Solo** is best suited for individuals and small teams with "single-player" problems.
1212
1313 You can read more about what **Solo** includes [here](https://hub.continue.dev/pricing).
1414
1515 ## Teams
1616
17-**Teams** is best suited for growing teams with "multiplayer" problems.
17+**Teams** is best suited for growing teams with "multiplayer" problems.
1818
1919 You can read more about what **Teams** includes [here](https://hub.continue.dev/pricing).
2020
2121 ## Enterprise
2222
23-**Enterprise** is best suited for large teams with enterprise-grade requirements.
23+**Enterprise** is best suited for large teams with enterprise-grade requirements.
2424
2525 You can read more about what **Enterprise** includes [here](https://hub.continue.dev/pricing).
2626
2727 ## Models Add-On
2828
29-The **Models Add-On** allows you to use a variety of frontier models for a flat monthly fee. It’s designed to cover the usage of most developers.
29+The **Models Add-On** allows you to use a variety of frontier models for a flat monthly fee. It’s designed to cover the usage of most developers.
3030
3131 You can read more about usage limits and what models are included [here](https://hub.continue.dev/pricing).
3232
3333 ### Free Trial
3434
35-To try out Continue, we offer a free trial of the **Models Add-On** that allows you to use 50 Chat requests and 2,000 autocomplete requests.
No newline at the end of the file
35+To try out Continue, we offer a free trial of the **Models Add-On** that allows you to use 50 Chat requests and 2,000 autocomplete requests.
modified docs/docs/hub/secrets/secret-resolution.md +1 −1
@@ -19,4 +19,4 @@
1919
2020 1. Org [models add-on](../governance/pricing.md#models-add-on) (if subscribed)
2121 2. [Org secrets](../secrets/secret-types.md#org-secrets) (if set)
22-3. [User secrets](../secrets/secret-types.md#user-secrets) (if set)
No newline at the end of the file
22+3. [User secrets](../secrets/secret-types.md#user-secrets) (if set)
modified docs/docs/hub/secrets/secret-types.md +3 −3
@@ -11,12 +11,12 @@
1111
1212 ## User secrets
1313
14-User secrets are defined by the user for themselves. This means that user secrets are available only to the user that created them. User secrets are assumed to be safe for the user to know, so they will be sent to the IDE extensions alongside the assistant `config.yaml`.
14+User secrets are defined by the user for themselves. This means that user secrets are available only to the user that created them. User secrets are assumed to be safe for the user to know, so they will be sent to the IDE extensions alongside the assistant `config.yaml`.
1515
1616 This allows API requests to be made directly from the IDE extensions. You can use user secrets with [Solo](../governance/pricing.md#solo), [Teams](../governance/pricing.md#teams), and [Enterprise](../governance/pricing.md#enterprise). User secrets can be managed [here](https://hub.continue.dev/settings/secrets) in the hub.
1717
1818 ## Org secrets
1919
20-Org secrets are defined by admins for their organization. Org secrets are available to anyone in the organization to use with assistants in that organization. Org secrets are assumed to not be shareable with the user (e.g. you are a team lead who wants to give team members access to models without passing out API keys).
20+Org secrets are defined by admins for their organization. Org secrets are available to anyone in the organization to use with assistants in that organization. Org secrets are assumed to not be shareable with the user (e.g. you are a team lead who wants to give team members access to models without passing out API keys).
2121
22-This is why LLM requests are proxied through api.continue.dev / on-premise proxy and secrets are never sent to the IDE extensions. You can only use org secrets on [Teams](../governance/pricing.md#teams) and [Enterprise](../governance/pricing.md#enterprise). If you are an admin, you can manage secrets for your organization from the org settings page.
No newline at the end of the file
22+This is why LLM requests are proxied through api.continue.dev / on-premise proxy and secrets are never sent to the IDE extensions. You can only use org secrets on [Teams](../governance/pricing.md#teams) and [Enterprise](../governance/pricing.md#enterprise). If you are an admin, you can manage secrets for your organization from the org settings page.
modified docs/docs/reference.md +2 −1
@@ -83,9 +83,10 @@
8383
8484 :::info
8585 Local blocks utilizing mustache notation for secrets (`${{ secrets.SECRET_NAME }}`) can read secret values:
86+
8687 - globally, from a `.env` located in the global `.continue` folder (`~/.continue/.env`)
8788 - per-workspace, from a `.env` file located at the root of the current workspace.
88-:::
89+ :::
8990
9091 ### Inputs
9192
modified docs/docs/telemetry.md +31 −31
@@ -1,31 +1,31 @@
1----
2-title: Telemetry
3-description: Learn how Continue collects anonymous usage information and how you can opt out.
4-keywords: [telemetry, anonymous, usage info, opt out]
5----
6-
7-## Overview
8-
9-The open-source Continue Extensions collect and report **anonymous** usage information to help us improve our product. This data enables us to understand user interactions and optimize the user experience effectively. You can opt out of telemetry collection at any time if you prefer not to share your usage information.
10-
11-We utilize [Posthog](https://posthog.com/), an open-source platform for product analytics, to gather and store this data. For transparency, you can review the implementation code [here](https://github.com/continuedev/continue/blob/main/gui/src/hooks/CustomPostHogProvider.tsx) or read our [official privacy policy](https://continue.dev/privacy).
12-
13-## Tracking Policy
14-
15-All data collected by the open-source Continue extensions is anonymized and stripped of personally identifiable information (PII) before being sent to PostHog. We are committed to maintaining the privacy and security of your data.
16-
17-## What We Track
18-
19-The following usage information is collected and reported:
20-
21-- **Suggestion Interactions:** Whether you accept or reject suggestions (excluding the actual code or prompts involved).
22-- **Model and Command Information:** The name of the model and command used.
23-- **Token Metrics:** The number of tokens generated.
24-- **System Information:** The name of your operating system (OS) and integrated development environment (IDE).
25-- **Pageviews:** General pageview statistics.
26-
27-## How to Opt Out
28-
29-You can disable anonymous telemetry by visiting the [User Settings Page](./customize/deep-dives/settings.md) and toggling "Allow Anonymous Telemetry" off.
30-
31-Alternatively in VS Code, you can disable telemetry through your VS Code settings by unchecking the "Continue: Telemetry Enabled" box (this will override the Settings Page settings). VS Code settings can be accessed with `File` > `Preferences` > `Settings` (or use the keyboard shortcut <kbd>ctrl</kbd> + <kbd>,</kbd> on Windows/Linux or <kbd>cmd</kbd> + <kbd>,</kbd> on macOS).
1+---
2+title: Telemetry
3+description: Learn how Continue collects anonymous usage information and how you can opt out.
4+keywords: [telemetry, anonymous, usage info, opt out]
5+---
6+
7+## Overview
8+
9+The open-source Continue Extensions collect and report **anonymous** usage information to help us improve our product. This data enables us to understand user interactions and optimize the user experience effectively. You can opt out of telemetry collection at any time if you prefer not to share your usage information.
10+
11+We utilize [Posthog](https://posthog.com/), an open-source platform for product analytics, to gather and store this data. For transparency, you can review the implementation code [here](https://github.com/continuedev/continue/blob/main/gui/src/hooks/CustomPostHogProvider.tsx) or read our [official privacy policy](https://continue.dev/privacy).
12+
13+## Tracking Policy
14+
15+All data collected by the open-source Continue extensions is anonymized and stripped of personally identifiable information (PII) before being sent to PostHog. We are committed to maintaining the privacy and security of your data.
16+
17+## What We Track
18+
19+The following usage information is collected and reported:
20+
21+- **Suggestion Interactions:** Whether you accept or reject suggestions (excluding the actual code or prompts involved).
22+- **Model and Command Information:** The name of the model and command used.
23+- **Token Metrics:** The number of tokens generated.
24+- **System Information:** The name of your operating system (OS) and integrated development environment (IDE).
25+- **Pageviews:** General pageview statistics.
26+
27+## How to Opt Out
28+
29+You can disable anonymous telemetry by visiting the [User Settings Page](./customize/deep-dives/settings.md) and toggling "Allow Anonymous Telemetry" off.
30+
31+Alternatively in VS Code, you can disable telemetry through your VS Code settings by unchecking the "Continue: Telemetry Enabled" box (this will override the Settings Page settings). VS Code settings can be accessed with `File` > `Preferences` > `Settings` (or use the keyboard shortcut <kbd>ctrl</kbd> + <kbd>,</kbd> on Windows/Linux or <kbd>cmd</kbd> + <kbd>,</kbd> on macOS).
modified docs/docusaurus.config.js +1 −1
@@ -67,7 +67,7 @@
6767
6868 scripts: [
6969 {
70- src: "/scripts/custom-reo.js", // it references from static folder
70+ src: "/scripts/custom-reo.js", // it references from static folder
7171 },
7272 ],
7373
modified docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/context-providers.md +3 −1
@@ -449,7 +449,7 @@
449449 {
450450 "name": "http",
451451 "params": {
452- "url": "https://api.example.com/v1/users",
452+ "url": "https://api.example.com/v1/users"
453453 }
454454 }
455455 ]
@@ -457,6 +457,7 @@
457457 ```
458458
459459 接收的 URL 应该接收下面的参数:
460+
460461 ```json title="POST parameters"
461462 {
462463 query: string,
@@ -465,6 +466,7 @@
465466 ```
466467
467468 响应 200 OK 应该是一个有以下结构的 JSON 对象:
469+
468470 ```json title="Response"
469471 [
470472 {
modified docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/more/SambaNova.md +2 −1
@@ -1,6 +1,7 @@
11 # SambaNova Cloud
22
3-SambaNova 云是一个运行大型 AI 模型的云平台,有 Llama 3.1 70B/405B 性能的世界记录。你可以在 [这里](http://cloud.sambanova.ai?utm_source=continue&utm_medium=external&utm_campaign=cloud_signup ) 登录,在最初的欢迎屏幕复制你的 API key ,然后在 [模型列表](https://community.sambanova.ai/t/quick-start-guide/104) 任何模型上点击 play 按钮。
3+SambaNova 云是一个运行大型 AI 模型的云平台,有 Llama 3.1 70B/405B 性能的世界记录。你可以在 [这里](http://cloud.sambanova.ai?utm_source=continue&utm_medium=external&utm_campaign=cloud_signup) 登录,在最初的欢迎屏幕复制你的 API key ,然后在 [模型列表](https://community.sambanova.ai/t/quick-start-guide/104) 任何模型上点击 play 按钮。
4+
45 ```json title="config.json"
56 {
67 "models": [
modified docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/tutorials/build-your-own-slash-command.md +1 −1
@@ -36,7 +36,7 @@
3636
3737 如果你想要比使用自然语言编写自定义命令更进一步,你可以编写一个自定义函数返回响应。这需要使用 `config.ts` 代替 `config.json` 。
3838
39-为了做这个,放一个新的 `SlashCommand` 对象到 `slashCommands` 列表中。这个对象包含 "name" ,你用来触发斜杠命令的名称, "description" ,在下拉菜单中看到的描述,以及 "run" 。 `run` 函数是任何异步生成器,应该生成你想要流式输出到 UI 的字符串。作为函数的参数,你可以访问一个有实用工具的 `ContinueSDK` 对象,例如访问 IDE 中的当前信息/action ,当前语言模型,以及一些其他实用工具。例如,这是一个生成 commit 信息的斜杠命令:
39+为了做这个,放一个新的 `SlashCommand` 对象到 `slashCommands` 列表中。这个对象包含 "name" ,你用来触发斜杠命令的名称, "description" ,在下拉菜单中看到的描述,以及 "run" 。 `run` 函数是任何异步生成器,应该生成你想要流式输出到 UI 的字符串。作为函数的参数,你可以访问一个有实用工具的 `ContinueSDK` 对象,例如访问 IDE 中的当前信息/action ,当前语言模型,以及一些其他实用工具。例如,这是一个生成 commit 信息的斜杠命令:
4040
4141 ```typescript title="~/.continue/config.ts"
4242 export function modifyConfig(config: Config): Config {
modified docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/introduction.md +1 −11
@@ -2,17 +2,7 @@
22 title: 简介
33 description: 开发者的开源 AI 代码助手
44 slug: /
5-keywords:
6- [
7- continue,
8- AI,
9- 代码助手,
10- 自动补全,
11- 聊天,
12- VS Code,
13- JetBrains,
14- 简介,
15- ]
5+keywords: [continue, AI, 代码助手, 自动补全, 聊天, VS Code, JetBrains, 简介]
166 ---
177
188 ![Continue Logo](/img/intro.png)
modified docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/telemetry.md +51 −50
@@ -1,50 +1,51 @@
1----
2-title: 遥测
3-description: 了解 Continue 如何收集匿名使用信息,以及你如何选择退出
4-keywords: [遥测, 匿名, 使用信息, 选择退出]
5----
6-
7-## 概述
8-Continue 收集并报告 **匿名** 使用信息,来帮助我们提高产品。这个数据允许我们有效地理解用户交互,并优化用户体验。你可以在任何时候选择退出遥测收集,如果你倾向与不分享你的使用信息。
9-
10-我们使用 [Posthog](https://posthog.com/) ,一个产品分析的开源平台,来收集并存储这个数据。为了透明,你可以 [在这里](https://github.com/continuedev/continue/blob/main/gui/src/hooks/CustomPostHogProvider.tsx) 检查实现代码,或者查看我们的 [官方隐私策略](https://continue.dev/privacy) 。
11-
12-## 跟踪策略
13-
14-所有 Continue 收集的数据是匿名的,在发送到 PostHog 之前,除去个人可识别信息 (PII) 。我们承诺维护你的数据的隐私和安全。
15-
16-## 我们跟踪什么
17-
18-以下使用信息被收集和报告:
19-
20-- **建议交互:** 你是否接受或拒绝建议(不包括涉及的实际代码或提示词)。
21-- **模型和命令信息:** 使用的模型和命令的名称。
22-- **token 指标:** 生成的 token 的数量。
23-- **系统信息:** 你的操作系统 (OS) 和集成开发环境 (IDE) 的名称。
24-- **页面浏览量:** 一般页面浏览量统计。
25-
26-## 如何退出
27-
28-你可以通过修改位于 `~/.continue` 目录中 `config.json` 文件禁用匿名遥测。这个文件通常包含以下条目:
29-
30-```json title="config.json"
31-{
32- "allowAnonymousTelemetry": true
33-}
34-```
35-
36-为了退出,修改 `allowAnonymousTelemetry` 的值为 `false` 。另外,你可以通过 VS Code 设置禁用遥测,通过取消勾选 "Continue: Telemetry Enabled" 选择框。
37-
38-### 通过配置文件禁用遥测的步骤
39-
40-1. 用你的文件编辑器打开 `~/.continue/config.json` 文件。
41-2. 定位到 `"allowAnonymousTelemetry"` 设置。
42-3. 将值从 `true` 修改为 `false` 。
43-4. 保存文件。
44-
45-### 通过 VS Code 设置禁用遥测
46-
47-1. 打开 VS Code 。
48-2. 导航到 `File` > `Preferences` > `Settings` (或在 Windows/Linux 上使用快捷键 `Ctrl + ,` 或在 macOS 上使用 `Cmd + ,` )。
49-3. 在搜索栏中,输入 "Continue: Telemetry Enabled" 。
50-4. 取消勾选 "Continue: Telemetry Enabled" 选择框。
1+---
2+title: 遥测
3+description: 了解 Continue 如何收集匿名使用信息,以及你如何选择退出
4+keywords: [遥测, 匿名, 使用信息, 选择退出]
5+---
6+
7+## 概述
8+
9+Continue 收集并报告 **匿名** 使用信息,来帮助我们提高产品。这个数据允许我们有效地理解用户交互,并优化用户体验。你可以在任何时候选择退出遥测收集,如果你倾向与不分享你的使用信息。
10+
11+我们使用 [Posthog](https://posthog.com/) ,一个产品分析的开源平台,来收集并存储这个数据。为了透明,你可以 [在这里](https://github.com/continuedev/continue/blob/main/gui/src/hooks/CustomPostHogProvider.tsx) 检查实现代码,或者查看我们的 [官方隐私策略](https://continue.dev/privacy) 。
12+
13+## 跟踪策略
14+
15+所有 Continue 收集的数据是匿名的,在发送到 PostHog 之前,除去个人可识别信息 (PII) 。我们承诺维护你的数据的隐私和安全。
16+
17+## 我们跟踪什么
18+
19+以下使用信息被收集和报告:
20+
21+- **建议交互:** 你是否接受或拒绝建议(不包括涉及的实际代码或提示词)。
22+- **模型和命令信息:** 使用的模型和命令的名称。
23+- **token 指标:** 生成的 token 的数量。
24+- **系统信息:** 你的操作系统 (OS) 和集成开发环境 (IDE) 的名称。
25+- **页面浏览量:** 一般页面浏览量统计。
26+
27+## 如何退出
28+
29+你可以通过修改位于 `~/.continue` 目录中 `config.json` 文件禁用匿名遥测。这个文件通常包含以下条目:
30+
31+```json title="config.json"
32+{
33+ "allowAnonymousTelemetry": true
34+}
35+```
36+
37+为了退出,修改 `allowAnonymousTelemetry` 的值为 `false` 。另外,你可以通过 VS Code 设置禁用遥测,通过取消勾选 "Continue: Telemetry Enabled" 选择框。
38+
39+### 通过配置文件禁用遥测的步骤
40+
41+1. 用你的文件编辑器打开 `~/.continue/config.json` 文件。
42+2. 定位到 `"allowAnonymousTelemetry"` 设置。
43+3. 将值从 `true` 修改为 `false` 。
44+4. 保存文件。
45+
46+### 通过 VS Code 设置禁用遥测
47+
48+1. 打开 VS Code 。
49+2. 导航到 `File` > `Preferences` > `Settings` (或在 Windows/Linux 上使用快捷键 `Ctrl + ,` 或在 macOS 上使用 `Cmd + ,` )。
50+3. 在搜索栏中,输入 "Continue: Telemetry Enabled" 。
51+4. 取消勾选 "Continue: Telemetry Enabled" 选择框。
modified docs/src/css/custom.css +6 −6
@@ -15,14 +15,14 @@
1515 --ifm-color-primary-lightest: rgb(67, 31, 242);
1616 --ifm-code-font-size: 95%;
1717 --docusaurus-highlighted-code-line-bg: rgba(0, 0, 0, 0.1);
18- --ifm-list-item-margin: 0.70rem;
18+ --ifm-list-item-margin: 0.7rem;
1919 /* These vars control the colors of the kbd tag 3d keycap */
2020 --kbd-keycap-bg-color: #ffffffce;
2121 --kbd-keycap-border-color: #ccc;
2222 --kbd-text-color: #ca3a18;
2323 --kbd-shadow-color: #b4b4b4;
2424 --kbd-shadow-color-outer: #9c9c9c;
25- --kbd-shadow-tint: rgba(0, 0, 0, .4);
25+ --kbd-shadow-tint: rgba(0, 0, 0, 0.4);
2626 }
2727
2828 /* For readability concerns, you should choose a lighter palette in dark mode. */
@@ -47,18 +47,18 @@
4747 kbd {
4848 display: inline-block;
4949 padding: 0.3em 0.4em;
50- margin: 0.1em .4em;
50+ margin: 0.1em 0.4em;
5151 font-family: var(--ifm-font-family-monospace);
52- font-size: .8rem;
52+ font-size: 0.8rem;
5353 font-weight: 500;
54- line-height: .8;
54+ line-height: 0.8;
5555 color: var(--kbd-text-color);
5656 text-align: center;
5757 white-space: nowrap;
5858 background-color: var(--kbd-keycap-bg-color);
5959 border: 1px solid var(--kbd-keycap-border-color);
6060 border-radius: 0.3em;
61- box-shadow:
61+ box-shadow:
6262 0 2px 0 1px var(--kbd-shadow-color),
6363 0 3px 0 2px var(--kbd-shadow-color-outer),
6464 0 4px 6px var(--kbd-shadow-tint);
modified docs/static/scripts/custom-reo.js +12 −1
@@ -1,1 +1,12 @@
1-!function(){var e,t,n;e="7aa28ed11570734",t=function(){Reo.init({clientID:"7aa28ed11570734"})},(n=document.createElement("script")).src="https://static.reo.dev/"+e+"/reo.js",n.async=!0,n.onload=t,document.head.appendChild(n)}();
No newline at the end of the file
1+!(function () {
2+ var e, t, n;
3+ (e = "7aa28ed11570734"),
4+ (t = function () {
5+ Reo.init({ clientID: "7aa28ed11570734" });
6+ }),
7+ ((n = document.createElement("script")).src =
8+ "https://static.reo.dev/" + e + "/reo.js"),
9+ (n.async = !0),
10+ (n.onload = t),
11+ document.head.appendChild(n);
12+})();
modified extensions/intellij/CONTRIBUTING.md +21 −21
@@ -7,26 +7,26 @@
77
88 - [Architecture Overview](#architecture-overview)
99 - [Environment Setup](#environment-setup)
10- - [IDE Installation](#ide-installation)
11- - [IDE configuration](#ide-configuration)
12- - [Node.js Requirements](#nodejs-requirements)
13- - [Install all dependencies](#install-all-dependencies)
14- - [Misc](#misc)
10+ - [IDE Installation](#ide-installation)
11+ - [IDE configuration](#ide-configuration)
12+ - [Node.js Requirements](#nodejs-requirements)
13+ - [Install all dependencies](#install-all-dependencies)
14+ - [Misc](#misc)
1515 - [Development Workflow](#development-workflow)
16- - [Running the extension in debug mode](#running-the-extension-in-debug-mode)
17- - [Accessing files in the `.continue` directory](#accessing-files-in-the-continue-directory)
18- - [Viewing logs](#viewing-logs)
19- - [Reloading changes](#reloading-changes)
20- - [Setting breakpoints](#setting-breakpoints)
21- - [Available Gradle tasks](#available-gradle-tasks)
22- - [Packaging](#packaging)
23- - [Installing the packaged extension](#installing-the-packaged-extension)
16+ - [Running the extension in debug mode](#running-the-extension-in-debug-mode)
17+ - [Accessing files in the `.continue` directory](#accessing-files-in-the-continue-directory)
18+ - [Viewing logs](#viewing-logs)
19+ - [Reloading changes](#reloading-changes)
20+ - [Setting breakpoints](#setting-breakpoints)
21+ - [Available Gradle tasks](#available-gradle-tasks)
22+ - [Packaging](#packaging)
23+ - [Installing the packaged extension](#installing-the-packaged-extension)
2424 - [Testing](#testing)
25- - [e2e testing](#e2e-testing)
26- - [Overview](#overview)
27- - [Setup](#setup)
28- - [Running the tests](#running-the-tests)
29- - [Identifying selectors](#identifying-selectors)
25+ - [e2e testing](#e2e-testing)
26+ - [Overview](#overview)
27+ - [Setup](#setup)
28+ - [Running the tests](#running-the-tests)
29+ - [Identifying selectors](#identifying-selectors)
3030
3131 ## Architecture Overview
3232
@@ -96,7 +96,7 @@
9696
9797 - `extensions/intellij`: Attempt to reload changed classes by selecting
9898 _Run | Debugging Actions | Reload Changed Classes`_
99- - This will often fail on new imports, schema changes etc. In that case, you need to stop and restart the extension
99+ - This will often fail on new imports, schema changes etc. In that case, you need to stop and restart the extension
100100 - `gui`: Changes will be reloaded automatically
101101 - `core`: Run `npm run build -- --os [darwin | linux | win32]` from the `binary` directory (requires
102102 restarting the
@@ -107,8 +107,8 @@
107107 - `extensions/intellij`: Breakpoints can be set in Intellij
108108 - `gui`: You'll need to set explicit `debugger` statements in the source code, or through the browser dev tools
109109 - `core`: Breakpoints can be set in Intellij (requires restarting the `Start Core Dev Server` task)
110- - If you have Community Edition installed, you won't be able to use breakpoints in IntelliJ. Instead, you can start
111- the `Core Binary` task in VS Code and set breakpoints in that IDE.
110+ - If you have Community Edition installed, you won't be able to use breakpoints in IntelliJ. Instead, you can start
111+ the `Core Binary` task in VS Code and set breakpoints in that IDE.
112112
113113 ### Available Gradle tasks
114114
modified extensions/vscode/e2e/tests/TODO.md +1 −1
@@ -1,3 +1,3 @@
11 TODO testing scenarios
22
3-- Highlighting code and pressing CMD+L _before_ the GUI was first opened. The highlighted code should be included as chat input.
No newline at the end of the file
3+- Highlighting code and pressing CMD+L _before_ the GUI was first opened. The highlighted code should be included as chat input.
modified extensions/vscode/models/all-MiniLM-L6-v2/README.md +10 −6
@@ -7,6 +7,7 @@
77 ## Usage (Transformers.js)
88
99 If you haven't already, you can install the [Transformers.js](https://huggingface.co/docs/transformers.js) JavaScript library from [NPM](https://www.npmjs.com/package/@xenova/transformers) using:
10+
1011 ```bash
1112 npm i @xenova/transformers
1213 ```
@@ -14,14 +15,17 @@
1415 You can then use the model to compute embeddings like this:
1516
1617 ```js
17-import { pipeline } from '@xenova/transformers';
18+import { pipeline } from "@xenova/transformers";
1819
1920 // Create a feature-extraction pipeline
20-const extractor = await pipeline('feature-extraction', 'Xenova/all-MiniLM-L6-v2');
21+const extractor = await pipeline(
22+ "feature-extraction",
23+ "Xenova/all-MiniLM-L6-v2",
24+);
2125
2226 // Compute sentence embeddings
23-const sentences = ['This is an example sentence', 'Each sentence is converted'];
24-const output = await extractor(sentences, { pooling: 'mean', normalize: true });
27+const sentences = ["This is an example sentence", "Each sentence is converted"];
28+const output = await extractor(sentences, { pooling: "mean", normalize: true });
2529 console.log(output);
2630 // Tensor {
2731 // dims: [ 2, 384 ],
@@ -32,6 +36,7 @@
3236 ```
3337
3438 You can convert this Tensor to a nested JavaScript array using `.tolist()`:
39+
3540 ```js
3641 console.log(output.tolist());
3742 // [
@@ -40,5 +45,4 @@
4045 // ]
4146 ```
4247
43-
44-Note: Having a separate repo for ONNX weights is intended to be a temporary solution until WebML gains more traction. If you would like to make your models web-ready, we recommend converting to ONNX using [🤗 Optimum](https://huggingface.co/docs/optimum/index) and structuring your repo like this one (with ONNX weights located in a subfolder named `onnx`).
No newline at the end of the file
48+Note: Having a separate repo for ONNX weights is intended to be a temporary solution until WebML gains more traction. If you would like to make your models web-ready, we recommend converting to ONNX using [🤗 Optimum](https://huggingface.co/docs/optimum/index) and structuring your repo like this one (with ONNX weights located in a subfolder named `onnx`).
modified extensions/vscode/models/all-MiniLM-L6-v2/tokenizer.json +0 −0

Not shown: the file is larger than the hub shows, or this page holds as much as it shows. View the file.

modified extensions/vscode/scripts/package-all.js +6 −13
@@ -2,12 +2,12 @@
22
33 const PLATFORMS = [
44 "win32-x64",
5-// "win32-arm64", can't be built due to no sqlite3 binaries
5+ // "win32-arm64", can't be built due to no sqlite3 binaries
66 "linux-x64",
77 "linux-arm64",
88 "darwin-x64",
99 "darwin-arm64",
10-]
10+];
1111 const args = process.argv.slice(2);
1212 const isPreRelease = args.includes("--pre-release");
1313
@@ -18,16 +18,9 @@
1818 ? "node scripts/package.js --pre-release --target " + platform // --yarn"
1919 : "node scripts/package.js --target " + platform; // --yarn";
2020
21- execSync(
22- "node scripts/prepackage-cross-platform.js --target "+ platform,
23- {stdio: 'inherit'}
24-
25- );
26- execSync(
27- pkgCommand,
28- {stdio: 'inherit'}
29- );
21+ execSync("node scripts/prepackage-cross-platform.js --target " + platform, {
22+ stdio: "inherit",
23+ });
24+ execSync(pkgCommand, { stdio: "inherit" });
3025 }
3126 })();
32-
33-
No newline at the end of the file
modified extensions/vscode/scripts/utils.js +1 −1
@@ -302,7 +302,7 @@
302302 );
303303
304304 // delete esbuild/bin because platform-specific @esbuild is downloaded
305- fs.rmdirSync(`out/node_modules/esbuild/bin`, {recursive: true});
305+ fs.rmdirSync(`out/node_modules/esbuild/bin`, { recursive: true });
306306
307307 console.log(`[info] Copied ${NODE_MODULES_TO_COPY.join(", ")}`);
308308 }
modified extensions/vscode/scripts/versionCheck.js +1 −1
@@ -7,6 +7,6 @@
77 const minor = parseInt(version.split(".")[1]);
88 if (minor % 2 !== 0) {
99 throw new Error(
10- "Do not publish odd-numbered version to main VS Code release!"
10+ "Do not publish odd-numbered version to main VS Code release!",
1111 );
1212 }
modified extensions/vscode/src/activation/InlineTipManager.ts +6 −2
@@ -49,7 +49,7 @@
4949 return this.fontSize;
5050 },
5151 get textY() {
52- return (this.tipHeight + this.fontSize)/2;
52+ return (this.tipHeight + this.fontSize) / 2;
5353 },
5454 get chatLabelX() {
5555 return this.paddingX;
@@ -58,7 +58,11 @@
5858 return this.chatLabelX + this.getEstimatedTextWidth(this.chatLabel + " ");
5959 },
6060 get editLabelX() {
61- return this.chatShortcutX + this.getEstimatedTextWidth(this.chatShortcut) + this.gap;
61+ return (
62+ this.chatShortcutX +
63+ this.getEstimatedTextWidth(this.chatShortcut) +
64+ this.gap
65+ );
6266 },
6367 get editShortcutX() {
6468 return this.editLabelX + this.getEstimatedTextWidth(this.editLabel + " ");
modified extensions/vscode/src/activation/activate.ts +2 −1
@@ -1,8 +1,9 @@
1+import * as path from "path";
2+
13 import { getContinueRcPath, getTsConfigPath } from "core/util/paths";
24 import { Telemetry } from "core/util/posthog";
35 import * as vscode from "vscode";
46
5-import * as path from "path";
67 import { VsCodeExtension } from "../extension/VsCodeExtension";
78 import registerQuickFixProvider from "../lang-server/codeActions";
89 import { getExtensionVersion } from "../util/util";
modified extensions/vscode/src/apply/utils.ts +1 −1
@@ -10,6 +10,6 @@
1010 */
1111 export function isFastApplyModel(llm: ILLM): boolean {
1212 return FAST_APPLY_MODELS?.some((fastApplyModel) =>
13- llm.model.toLowerCase().includes(fastApplyModel.toLowerCase())
13+ llm.model.toLowerCase().includes(fastApplyModel.toLowerCase()),
1414 );
1515 }
modified extensions/vscode/src/autocomplete/RecentlyVisitedRangesService.ts +10 −4
@@ -113,10 +113,16 @@
113113 }
114114
115115 return allSnippets
116- .filter((s) => !currentFilepath || (s.filepath !== currentFilepath &&
117- // Exclude Continue's own output as it makes it super-hard for users to test the autocomplete feature
118- // while looking at the prompts in the Continue's output
119- !s.filepath.startsWith("output:extension-output-Continue.continue")))
116+ .filter(
117+ (s) =>
118+ !currentFilepath ||
119+ (s.filepath !== currentFilepath &&
120+ // Exclude Continue's own output as it makes it super-hard for users to test the autocomplete feature
121+ // while looking at the prompts in the Continue's output
122+ !s.filepath.startsWith(
123+ "output:extension-output-Continue.continue",
124+ )),
125+ )
120126 .sort((a, b) => b.timestamp - a.timestamp)
121127 .map(({ timestamp, ...snippet }) => snippet);
122128 }
modified extensions/vscode/src/autocomplete/completionProvider.ts +4 −1
@@ -218,7 +218,10 @@
218218 // In the future we will have to figure out how to call this more gracefully.
219219 if (this.nextEditProvider) {
220220 const nextEditOutcome =
221- await this.nextEditProvider?.provideInlineCompletionItems(input, signal);
221+ await this.nextEditProvider?.provideInlineCompletionItems(
222+ input,
223+ signal,
224+ );
222225
223226 if (nextEditOutcome && nextEditOutcome.completion) {
224227 outcome.completion = nextEditOutcome.completion;
modified extensions/vscode/src/autocomplete/lsp.ts +6 −6
@@ -1,20 +1,20 @@
11 import { AutocompleteLanguageInfo } from "core/autocomplete/constants/AutocompleteLanguageInfo";
2+import {
3+ AutocompleteCodeSnippet,
4+ AutocompleteSnippetType,
5+} from "core/autocomplete/snippets/types";
6+import { GetLspDefinitionsFunction } from "core/autocomplete/types";
27 import { getAst, getTreePathAtCursor } from "core/autocomplete/util/ast";
38 import {
49 FUNCTION_BLOCK_NODE_TYPES,
510 FUNCTION_DECLARATION_NODE_TYPEs,
611 } from "core/indexing/chunk/code";
712 import { intersection } from "core/util/ranges";
13+import * as URI from "uri-js";
814 import * as vscode from "vscode";
915
1016 import type { IDE, Range, RangeInFile, RangeInFileWithContents } from "core";
1117 import type Parser from "web-tree-sitter";
12-import { GetLspDefinitionsFunction } from "core/autocomplete/types";
13-import {
14- AutocompleteCodeSnippet,
15- AutocompleteSnippetType,
16-} from "core/autocomplete/snippets/types";
17-import * as URI from "uri-js";
1818
1919 type GotoProviderName =
2020 | "vscode.executeDefinitionProvider"
modified extensions/vscode/src/autocomplete/recentlyEdited.ts +4 −5
@@ -48,7 +48,6 @@
4848 private async insertRange(
4949 editedRange: Omit<VsCodeRecentlyEditedRange, "lines" | "symbols">,
5050 ): Promise<void> {
51-
5251 if (editedRange.uri.scheme !== "file") {
5352 return;
5453 }
@@ -119,10 +118,10 @@
119118 return "";
120119 }
121120 return content
122- .toString()
123- .split("\n")
124- .slice(entry.range.start.line, entry.range.end.line + 1)
125- .join("\n");
121+ .toString()
122+ .split("\n")
123+ .slice(entry.range.start.line, entry.range.end.line + 1)
124+ .join("\n");
126125 }
127126
128127 public async getRecentlyEditedRanges(): Promise<RecentlyEditedRange[]> {
modified extensions/vscode/src/diff/vertical/handler.ts +8 −9
@@ -9,8 +9,8 @@
99 indexDecorationType,
1010 } from "./decorations";
1111
12-import type { ApplyState, DiffLine } from "core";
1312 import type { VerticalDiffCodeLens } from "./manager";
13+import type { ApplyState, DiffLine } from "core";
1414
1515 export interface VerticalDiffHandlerOptions {
1616 input?: string;
@@ -174,10 +174,7 @@
174174 await this.reapplyWithMyersDiff(diffLines);
175175
176176 const range = new vscode.Range(this.startLine, 0, this.startLine, 0);
177- this.editor.revealRange(
178- range,
179- vscode.TextEditorRevealType.Default,
180- );
177+ this.editor.revealRange(range, vscode.TextEditorRevealType.Default);
181178
182179 this.options.onStatusUpdate(
183180 "done",
@@ -423,11 +420,13 @@
423420 private incrementCurrentLineIndex() {
424421 this.currentLineIndex++;
425422 this.updateIndexLineDecorations();
426- const range = new vscode.Range(this.currentLineIndex, 0, this.currentLineIndex, 0);
427- this.editor.revealRange(
428- range,
429- vscode.TextEditorRevealType.Default,
423+ const range = new vscode.Range(
424+ this.currentLineIndex,
425+ 0,
426+ this.currentLineIndex,
427+ 0,
430428 );
429+ this.editor.revealRange(range, vscode.TextEditorRevealType.Default);
431430 }
432431
433432 private async insertTextAboveLine(index: number, text: string) {
modified extensions/vscode/src/extension/VsCodeMessenger.ts +2 −2
@@ -1,4 +1,6 @@
11 import { ConfigHandler } from "core/config/ConfigHandler";
2+import { DataLogger } from "core/data/log";
3+import { EDIT_MODE_STREAM_ID } from "core/edit/constants";
24 import {
35 FromCoreProtocol,
46 FromWebviewProtocol,
@@ -15,8 +17,6 @@
1517 import { stripImages } from "core/util/messageContent";
1618 import * as vscode from "vscode";
1719
18-import { DataLogger } from "core/data/log";
19-import { EDIT_MODE_STREAM_ID } from "core/edit/constants";
2020 import { ApplyManager } from "../apply";
2121 import { VerticalDiffManager } from "../diff/vertical/manager";
2222 import { addCurrentSelectionToEdit } from "../quickEdit/AddCurrentSelection";
modified extensions/vscode/src/lang-server/codeLens/providers/ConfigJsonConverterCodeLensProvider.ts +2 −1
@@ -1,5 +1,6 @@
1-import { getConfigYamlPath } from "core/util/paths";
21 import * as fs from "fs";
2+
3+import { getConfigYamlPath } from "core/util/paths";
34 import * as vscode from "vscode";
45
56 export class ConfigJsonConverterCodeLensProvider
modified extensions/vscode/src/lang-server/codeLens/providers/QuickActionsCodeLensProvider.ts +1 −1
@@ -3,11 +3,11 @@
33 import * as vscode from "vscode";
44
55 import { QuickEditShowParams } from "../../../quickEdit/QuickEditQuickPick";
6+import { isTutorialFile } from "../../../util/tutorial";
67 import {
78 CONTINUE_WORKSPACE_KEY,
89 getContinueWorkspaceConfig,
910 } from "../../../util/workspaceConfig";
10-import { isTutorialFile } from "../../../util/tutorial";
1111
1212 export const ENABLE_QUICK_ACTIONS_KEY = "enableQuickActions";
1313
modified extensions/vscode/src/lang-server/promptFileCompletions.ts +1 −1
@@ -1,8 +1,8 @@
11 import { IDE } from "core";
2+import { getUriPathBasename, getLastNPathParts } from "core/util/uri";
23 import vscode from "vscode";
34
45 import { FileSearch } from "../util/FileSearch";
5-import { getUriPathBasename, getLastNPathParts } from "core/util/uri";
66
77 class PromptFilesCompletionItemProvider
88 implements vscode.CompletionItemProvider
modified extensions/vscode/src/quickEdit/AddCurrentSelection.ts +2 −0
@@ -1,7 +1,9 @@
11 import * as vscode from "vscode";
2+
23 import { VerticalDiffManager } from "../diff/vertical/manager";
34 import { getRangeInFileWithContents } from "../util/addCode";
45 import { VsCodeWebviewProtocol } from "../webviewProtocol";
6+
57 import EditDecorationManager from "./EditDecorationManager";
68 import { QuickEditShowParams } from "./QuickEditQuickPick";
79
modified extensions/vscode/src/quickEdit/EditDecorationManager.ts +18 −8
@@ -31,10 +31,12 @@
3131
3232 // Checks if two ranges are adjacent or overlapping
3333 private rangesCoincide(range1: vscode.Range, range2: vscode.Range): boolean {
34- return range1.start.isEqual(range2.start)
35- || range1.end.isEqual(range2.start)
36- || range2.end.isEqual(range1.start)
37- || !!range1.intersection(range2);
34+ return (
35+ range1.start.isEqual(range2.start) ||
36+ range1.end.isEqual(range2.start) ||
37+ range2.end.isEqual(range1.start) ||
38+ !!range1.intersection(range2)
39+ );
3840 }
3941
4042 // Merges new range with existing ranges in the map
@@ -43,12 +45,16 @@
4345 const rangesToPrune: string[] = [];
4446
4547 for (const [key, existingRange] of this.activeRangesMap.entries()) {
46- if (!this.rangesCoincide(mergedRange, existingRange)) continue;
48+ if (!this.rangesCoincide(mergedRange, existingRange)) {
49+ continue;
50+ }
4751 mergedRange = mergedRange.union(existingRange);
4852 rangesToPrune.push(key);
4953 }
5054
51- for (const key of rangesToPrune) this.activeRangesMap.delete(key);
55+ for (const key of rangesToPrune) {
56+ this.activeRangesMap.delete(key);
57+ }
5258 this.activeRangesMap.set(this.rangeToString(mergedRange), mergedRange);
5359 }
5460
@@ -59,10 +65,14 @@
5965 }
6066 this._lastEditor = editor;
6167
62- for (const range of ranges) this.mergeNewRange(range);
68+ for (const range of ranges) {
69+ this.mergeNewRange(range);
70+ }
6371
6472 const activeRanges = Array.from(this.activeRangesMap.values());
65- if (activeRanges.length === 0) return; // No ranges to highlight
73+ if (activeRanges.length === 0) {
74+ return;
75+ } // No ranges to highlight
6676
6777 // Update active ranges and apply decorations
6878 editor.setDecorations(this.decorationType, activeRanges);
modified extensions/vscode/src/stubs/WorkOsAuthProvider.ts +6 −6
@@ -1,5 +1,11 @@
11 import crypto from "crypto";
22
3+import {
4+ AuthType,
5+ ControlPlaneSessionInfo,
6+ HubEnv,
7+ isHubEnv,
8+} from "core/control-plane/AuthTypes";
39 import { getControlPlaneEnvSync } from "core/control-plane/env";
410 import fetch from "node-fetch";
511 import { v4 as uuidv4 } from "uuid";
@@ -17,12 +23,6 @@
1723 window,
1824 } from "vscode";
1925
20-import {
21- AuthType,
22- ControlPlaneSessionInfo,
23- HubEnv,
24- isHubEnv,
25-} from "core/control-plane/AuthTypes";
2626 import { PromiseAdapter, promiseFromEvent } from "./promiseUtils";
2727 import { SecretStorage } from "./SecretStorage";
2828 import { UriEventHandler } from "./uriHandler";
modified extensions/vscode/src/stubs/remoteConfig.ts +1 −1
@@ -3,9 +3,9 @@
33 import { ContinueServerClient } from "core/continueServer/stubs/client";
44 import { EXTENSION_NAME } from "core/control-plane/env";
55 import { getConfigJsonPathForRemote } from "core/util/paths";
6+import { canParseUrl } from "core/util/url";
67 import * as vscode from "vscode";
78
8-import { canParseUrl } from "core/util/url";
99 import { CONTINUE_WORKSPACE_KEY } from "../util/workspaceConfig";
1010
1111 export class RemoteConfigSync {
modified extensions/vscode/src/suggestions.ts +1 −1
@@ -1,7 +1,7 @@
1+import * as URI from "uri-js";
12 import * as vscode from "vscode";
23
34 import { openEditorAndRevealRange, translate } from "./util/vscode";
4-import * as URI from "uri-js";
55
66 export interface SuggestionRanges {
77 oldRange: vscode.Range;
modified extensions/vscode/src/util/FileSearch.ts +7 −1
@@ -18,7 +18,13 @@
1818 private miniSearch = new MiniSearch<FileMiniSearchResult>({
1919 fields: ["relativePath", "id"],
2020 storeFields: ["relativePath", "id"],
21- tokenize: text => deduplicateArray(MiniSearch.getDefault('tokenize')(text).concat(splitCamelCaseAndNonAlphaNumeric(text)), (a, b) => a === b),
21+ tokenize: (text) =>
22+ deduplicateArray(
23+ MiniSearch.getDefault("tokenize")(text).concat(
24+ splitCamelCaseAndNonAlphaNumeric(text),
25+ ),
26+ (a, b) => a === b,
27+ ),
2228 searchOptions: {
2329 prefix: true,
2430 fuzzy: 2,
modified extensions/vscode/src/util/addCode.ts +3 −3
@@ -89,18 +89,18 @@
8989 export async function addEntireFileToContext(
9090 uri: vscode.Uri,
9191 webviewProtocol: VsCodeWebviewProtocol | undefined,
92- ideUtils: VsCodeIdeUtils
92+ ideUtils: VsCodeIdeUtils,
9393 ) {
9494 // If a directory, add all files in the directory
9595 const stat = await ideUtils.stat(uri);
9696 if (stat?.type === vscode.FileType.Directory) {
97- const files = (await ideUtils.readDirectory(uri))!;//files can't be null if we reached this point
97+ const files = (await ideUtils.readDirectory(uri))!; //files can't be null if we reached this point
9898 for (const [filename, type] of files) {
9999 if (type === vscode.FileType.File) {
100100 addEntireFileToContext(
101101 vscode.Uri.joinPath(uri, filename),
102102 webviewProtocol,
103- ideUtils
103+ ideUtils,
104104 );
105105 }
106106 }
modified extensions/vscode/src/util/expandSnippet.ts +1 −0
@@ -4,6 +4,7 @@
44 import { deduplicateArray } from "core/util";
55 import { getParserForFile } from "core/util/treeSitter";
66 import * as vscode from "vscode";
7+
78 import { getDefinitionsForNode } from "../autocomplete/lsp";
89
910 import type { SyntaxNode } from "web-tree-sitter";
modified extensions/vscode/src/util/getTheme.ts +4 −4
@@ -11,20 +11,20 @@
1111
1212 function stripInLineComment(line: string): string {
1313 let inString = false;
14- let pCh = '';
14+ let pCh = "";
1515
16- for (let i = 0; i < line.length-1; i++) {
16+ for (let i = 0; i < line.length - 1; i++) {
1717 const ch = line[i];
1818 const nCh = line[i + 1];
1919
2020 // If we're not in a string and we see '//' this is a comment.
21- if (!inString && ch === '/' && nCh === '/') {
21+ if (!inString && ch === "/" && nCh === "/") {
2222 // Stop processing this line from here.
2323 return line.substring(0, i);
2424 }
2525
2626 // Toggle inString state if we see a double quote not escaped by a backslash.
27- if (ch === '"' && pCh !== '\\') {
27+ if (ch === '"' && pCh !== "\\") {
2828 inString = !inString;
2929 }
3030
modified extensions/vscode/src/util/ideUtils.ts +1 −4
@@ -292,7 +292,7 @@
292292 async readRangeInFile(uri: vscode.Uri, range: vscode.Range): Promise<string> {
293293 const buffer = await this.readFile(uri);
294294 if (buffer === null) {
295- return '';
295+ return "";
296296 }
297297 const contents = new TextDecoder().decode(buffer);
298298 const lines = contents.split("\n");
@@ -608,7 +608,6 @@
608608 try {
609609 if (repos) {
610610 for (const repo of repos) {
611-
612611 const staged = await repo.diff(true);
613612
614613 diffs.push(staged);
@@ -620,11 +619,9 @@
620619 }
621620
622621 return diffs.flatMap((diff) => this.splitDiff(diff));
623-
624622 } catch (e) {
625623 console.error(e);
626624 return [];
627625 }
628-
629626 }
630627 }
modified extensions/vscode/src/util/tutorial.ts +2 −1
@@ -1,7 +1,8 @@
11 import { IDE } from "core";
2-import { getExtensionUri } from "./vscode";
32 import * as vscode from "vscode";
43
4+import { getExtensionUri } from "./vscode";
5+
56 const TUTORIAL_FILE_NAME = "continue_tutorial.py";
67 export function getTutorialUri(): vscode.Uri {
78 return vscode.Uri.joinPath(getExtensionUri(), TUTORIAL_FILE_NAME);
modified extensions/vscode/src/util/vscode.ts +1 −1
@@ -1,6 +1,6 @@
11 import { machineIdSync } from "node-machine-id";
2-import * as vscode from "vscode";
32 import * as URI from "uri-js";
3+import * as vscode from "vscode";
44
55 export function translate(range: vscode.Range, lines: number): vscode.Range {
66 return new vscode.Range(
modified extensions/vscode/textmate-syntaxes/Handlebars.json +853 −853
@@ -1,854 +1,854 @@
11 {
2- "name": "Handlebars",
3- "repository": {
4- "html_tags": {
5- "patterns": [
6- {
7- "begin": "(<)([a-zA-Z0-9:-]+)(?=[^>]*></\\2>)",
8- "beginCaptures": {
9- "1": {
10- "name": "punctuation.definition.tag.html"
11- },
12- "2": {
13- "name": "entity.name.tag.html"
14- }
15- },
16- "end": "(>(<)/)(\\2)(>)",
17- "endCaptures": {
18- "1": {
19- "name": "punctuation.definition.tag.html"
20- },
21- "2": {
22- "name": "meta.scope.between-tag-pair.html"
23- },
24- "3": {
25- "name": "entity.name.tag.html"
26- },
27- "4": {
28- "name": "punctuation.definition.tag.html"
29- }
30- },
31- "name": "meta.tag.any.html",
32- "patterns": [
33- {
34- "include": "#tag-stuff"
35- }
36- ]
37- },
38- {
39- "begin": "(<\\?)(xml)",
40- "captures": {
41- "1": {
42- "name": "punctuation.definition.tag.html"
43- },
44- "2": {
45- "name": "entity.name.tag.xml.html"
46- }
47- },
48- "end": "(\\?>)",
49- "name": "meta.tag.preprocessor.xml.html",
50- "patterns": [
51- {
52- "include": "#tag_generic_attribute"
53- },
54- {
55- "include": "#string"
56- }
57- ]
58- },
59- {
60- "begin": "<!--",
61- "captures": {
62- "0": {
63- "name": "punctuation.definition.comment.html"
64- }
65- },
66- "end": "--\\s*>",
67- "name": "comment.block.html",
68- "patterns": [
69- {
70- "match": "--",
71- "name": "invalid.illegal.bad-comments-or-CDATA.html"
72- }
73- ]
74- },
75- {
76- "begin": "<!",
77- "captures": {
78- "0": {
79- "name": "punctuation.definition.tag.html"
80- }
81- },
82- "end": ">",
83- "name": "meta.tag.sgml.html",
84- "patterns": [
85- {
86- "begin": "(DOCTYPE|doctype)",
87- "captures": {
88- "1": {
89- "name": "entity.name.tag.doctype.html"
90- }
91- },
92- "end": "(?=>)",
93- "name": "meta.tag.sgml.doctype.html",
94- "patterns": [
95- {
96- "match": "\"[^\">]*\"",
97- "name": "string.quoted.double.doctype.identifiers-and-DTDs.html"
98- }
99- ]
100- },
101- {
102- "begin": "\\[CDATA\\[",
103- "end": "]](?=>)",
104- "name": "constant.other.inline-data.html"
105- },
106- {
107- "match": "(\\s*)(?!--|>)\\S(\\s*)",
108- "name": "invalid.illegal.bad-comments-or-CDATA.html"
109- }
110- ]
111- },
112- {
113- "begin": "(?:^\\s+)?(<)((?i:style))\\b(?![^>]*/>)",
114- "captures": {
115- "1": {
116- "name": "punctuation.definition.tag.html"
117- },
118- "2": {
119- "name": "entity.name.tag.style.html"
120- },
121- "3": {
122- "name": "punctuation.definition.tag.html"
123- }
124- },
125- "end": "(</)((?i:style))(>)(?:\\s*\\n)?",
126- "name": "source.css.embedded.html",
127- "patterns": [
128- {
129- "include": "#tag-stuff"
130- },
131- {
132- "begin": "(>)",
133- "beginCaptures": {
134- "1": {
135- "name": "punctuation.definition.tag.html"
136- }
137- },
138- "end": "(?=</(?i:style))",
139- "patterns": [
140- {
141- "include": "source.css"
142- }
143- ]
144- }
145- ]
146- },
147- {
148- "begin": "(?:^\\s+)?(<)((?i:script))\\b(?![^>]*/>)",
149- "beginCaptures": {
150- "1": {
151- "name": "punctuation.definition.tag.html"
152- },
153- "2": {
154- "name": "entity.name.tag.script.html"
155- }
156- },
157- "end": "(?<=</(script|SCRIPT))(>)(?:\\s*\\n)?",
158- "endCaptures": {
159- "2": {
160- "name": "punctuation.definition.tag.html"
161- }
162- },
163- "name": "source.js.embedded.html",
164- "patterns": [
165- {
166- "include": "#tag-stuff"
167- },
168- {
169- "begin": "(?<!</(?:script|SCRIPT))(>)",
170- "captures": {
171- "1": {
172- "name": "punctuation.definition.tag.html"
173- },
174- "2": {
175- "name": "entity.name.tag.script.html"
176- }
177- },
178- "end": "(</)((?i:script))",
179- "patterns": [
180- {
181- "captures": {
182- "1": {
183- "name": "punctuation.definition.comment.js"
184- }
185- },
186- "match": "(//).*?((?=</script)|$\\n?)",
187- "name": "comment.line.double-slash.js"
188- },
189- {
190- "begin": "/\\*",
191- "captures": {
192- "0": {
193- "name": "punctuation.definition.comment.js"
194- }
195- },
196- "end": "\\*/|(?=</script)",
197- "name": "comment.block.js"
198- },
199- {
200- "include": "source.js"
201- }
202- ]
203- }
204- ]
205- },
206- {
207- "begin": "(</?)((?i:body|head|html)\\b)",
208- "captures": {
209- "1": {
210- "name": "punctuation.definition.tag.html"
211- },
212- "2": {
213- "name": "entity.name.tag.structure.any.html"
214- }
215- },
216- "end": "(>)",
217- "name": "meta.tag.structure.any.html",
218- "patterns": [
219- {
220- "include": "#tag-stuff"
221- }
222- ]
223- },
224- {
225- "begin": "(</?)((?i:address|blockquote|dd|div|header|section|footer|aside|nav|dl|dt|fieldset|form|frame|frameset|h1|h2|h3|h4|h5|h6|iframe|noframes|object|ol|p|ul|applet|center|dir|hr|menu|pre)\\b)",
226- "captures": {
227- "1": {
228- "name": "punctuation.definition.tag.html"
229- },
230- "2": {
231- "name": "entity.name.tag.block.any.html"
232- }
233- },
234- "end": "(>)",
235- "name": "meta.tag.block.any.html",
236- "patterns": [
237- {
238- "include": "#tag-stuff"
239- }
240- ]
241- },
242- {
243- "begin": "(</?)((?i:a|abbr|acronym|area|b|base|basefont|bdo|big|br|button|caption|cite|code|col|colgroup|del|dfn|em|font|head|html|i|img|input|ins|isindex|kbd|label|legend|li|link|map|meta|noscript|optgroup|option|param|q|s|samp|script|select|small|span|strike|strong|style|sub|sup|table|tbody|td|textarea|tfoot|th|thead|title|tr|tt|u|var)\\b)",
244- "captures": {
245- "1": {
246- "name": "punctuation.definition.tag.html"
247- },
248- "2": {
249- "name": "entity.name.tag.inline.any.html"
250- }
251- },
252- "end": "((?: ?/)?>)",
253- "name": "meta.tag.inline.any.html",
254- "patterns": [
255- {
256- "include": "#tag-stuff"
257- }
258- ]
259- },
260- {
261- "begin": "(</?)([a-zA-Z0-9:-]+)",
262- "captures": {
263- "1": {
264- "name": "punctuation.definition.tag.html"
265- },
266- "2": {
267- "name": "entity.name.tag.other.html"
268- }
269- },
270- "end": "(>)",
271- "name": "meta.tag.other.html",
272- "patterns": [
273- {
274- "include": "#tag-stuff"
275- }
276- ]
277- },
278- {
279- "begin": "(</?)([a-zA-Z0-9{}:-]+)",
280- "captures": {
281- "1": {
282- "name": "punctuation.definition.tag.html"
283- },
284- "2": {
285- "name": "entity.name.tag.tokenised.html"
286- }
287- },
288- "end": "(>)",
289- "name": "meta.tag.tokenised.html",
290- "patterns": [
291- {
292- "include": "#tag-stuff"
293- }
294- ]
295- },
296- {
297- "include": "#entities"
298- },
299- {
300- "match": "<>",
301- "name": "invalid.illegal.incomplete.html"
302- },
303- {
304- "match": "<",
305- "name": "invalid.illegal.bad-angle-bracket.html"
306- }
307- ]
308- },
309- "entities": {
310- "patterns": [
311- {
312- "captures": {
313- "1": {
314- "name": "punctuation.definition.entity.html"
315- },
316- "3": {
317- "name": "punctuation.definition.entity.html"
318- }
319- },
320- "name": "constant.character.entity.html",
321- "match": "(&)([a-zA-Z0-9]+|#[0-9]+|#x[0-9a-fA-F]+)(;)"
322- },
323- {
324- "name": "invalid.illegal.bad-ampersand.html",
325- "match": "&"
326- }
327- ]
328- },
329- "end_block": {
330- "begin": "(\\{\\{~?/)([a-zA-Z0-9_\\.-]+)\\s*",
331- "end": "(~?\\}\\})",
332- "name": "meta.function.block.end.handlebars",
333- "endCaptures": {
334- "1": {
335- "name": "support.constant.handlebars"
336- }
337- },
338- "beginCaptures": {
339- "1": {
340- "name": "support.constant.handlebars"
341- },
342- "2": {
343- "name": "support.constant.handlebars"
344- }
345- },
346- "patterns": []
347- },
348- "yfm": {
349- "patterns": [
350- {
351- "patterns": [
352- {
353- "include": "source.yaml"
354- }
355- ],
356- "begin": "(?<!\\s)---\\n$",
357- "end": "^---\\s",
358- "name": "markup.raw.yaml.front-matter"
359- }
360- ]
361- },
362- "comments": {
363- "patterns": [
364- {
365- "patterns": [
366- {
367- "name": "keyword.annotation.handlebars",
368- "match": "@\\w*"
369- },
370- {
371- "include": "#comments"
372- }
373- ],
374- "begin": "\\{\\{!",
375- "end": "\\}\\}",
376- "name": "comment.block.handlebars"
377- },
378- {
379- "captures": {
380- "0": {
381- "name": "punctuation.definition.comment.html"
382- }
383- },
384- "begin": "<!--",
385- "end": "-{2,3}\\s*>",
386- "name": "comment.block.html",
387- "patterns": [
388- {
389- "name": "invalid.illegal.bad-comments-or-CDATA.html",
390- "match": "--"
391- }
392- ]
393- }
394- ]
395- },
396- "block_comments": {
397- "patterns": [
398- {
399- "patterns": [
400- {
401- "name": "keyword.annotation.handlebars",
402- "match": "@\\w*"
403- },
404- {
405- "include": "#comments"
406- }
407- ],
408- "begin": "\\{\\{!--",
409- "end": "--\\}\\}",
410- "name": "comment.block.handlebars"
411- },
412- {
413- "captures": {
414- "0": {
415- "name": "punctuation.definition.comment.html"
416- }
417- },
418- "begin": "<!--",
419- "end": "-{2,3}\\s*>",
420- "name": "comment.block.html",
421- "patterns": [
422- {
423- "name": "invalid.illegal.bad-comments-or-CDATA.html",
424- "match": "--"
425- }
426- ]
427- }
428- ]
429- },
430- "block_helper": {
431- "begin": "(\\{\\{~?\\#)([-a-zA-Z0-9_\\./]+)\\s?(@?[-a-zA-Z0-9_\\./]+)*\\s?(@?[-a-zA-Z0-9_\\./]+)*\\s?(@?[-a-zA-Z0-9_\\./]+)*",
432- "end": "(~?\\}\\})",
433- "name": "meta.function.block.start.handlebars",
434- "endCaptures": {
435- "1": {
436- "name": "support.constant.handlebars"
437- }
438- },
439- "beginCaptures": {
440- "1": {
441- "name": "support.constant.handlebars"
442- },
443- "2": {
444- "name": "support.constant.handlebars"
445- },
446- "3": {
447- "name": "variable.parameter.handlebars"
448- },
449- "4": {
450- "name": "support.constant.handlebars"
451- },
452- "5": {
453- "name": "variable.parameter.handlebars"
454- },
455- "6": {
456- "name": "support.constant.handlebars"
457- }
458- },
459- "patterns": [
460- {
461- "include": "#string"
462- },
463- {
464- "include": "#handlebars_attribute"
465- }
466- ]
467- },
468- "string-single-quoted": {
469- "begin": "'",
470- "end": "'",
471- "name": "string.quoted.single.handlebars",
472- "endCaptures": {
473- "0": {
474- "name": "punctuation.definition.string.end.html"
475- }
476- },
477- "beginCaptures": {
478- "0": {
479- "name": "punctuation.definition.string.begin.html"
480- }
481- },
482- "patterns": [
483- {
484- "include": "#escaped-single-quote"
485- },
486- {
487- "include": "#block_comments"
488- },
489- {
490- "include": "#comments"
491- },
492- {
493- "include": "#block_helper"
494- },
495- {
496- "include": "#else_token"
497- },
498- {
499- "include": "#end_block"
500- },
501- {
502- "include": "#partial_and_var"
503- }
504- ]
505- },
506- "string": {
507- "patterns": [
508- {
509- "include": "#string-single-quoted"
510- },
511- {
512- "include": "#string-double-quoted"
513- }
514- ]
515- },
516- "escaped-single-quote": {
517- "name": "constant.character.escape.js",
518- "match": "\\\\'"
519- },
520- "escaped-double-quote": {
521- "name": "constant.character.escape.js",
522- "match": "\\\\\""
523- },
524- "partial_and_var": {
525- "begin": "(\\{\\{~?\\{*(>|!<)*)\\s*(@?[-a-zA-Z0-9_\\./]+)*",
526- "end": "(~?\\}\\}\\}*)",
527- "name": "meta.function.inline.other.handlebars",
528- "beginCaptures": {
529- "1": {
530- "name": "support.constant.handlebars"
531- },
532- "3": {
533- "name": "variable.parameter.handlebars"
534- }
535- },
536- "endCaptures": {
537- "1": {
538- "name": "support.constant.handlebars"
539- }
540- },
541- "patterns": [
542- {
543- "include": "#string"
544- },
545- {
546- "include": "#handlebars_attribute"
547- }
548- ]
549- },
550- "handlebars_attribute_name": {
551- "begin": "\\b([-a-zA-Z0-9_\\.]+)\\b=",
552- "captures": {
553- "1": {
554- "name": "variable.parameter.handlebars"
555- }
556- },
557- "end": "(?='|\"|)",
558- "name": "entity.other.attribute-name.handlebars"
559- },
560- "handlebars_attribute_value": {
561- "begin": "([-a-zA-Z0-9_\\./]+)\\b\\s*",
562- "captures": {
563- "1": {
564- "name": "variable.parameter.handlebars"
565- }
566- },
567- "end": "('|\"|)",
568- "name": "entity.other.attribute-value.handlebars",
569- "patterns": [
570- {
571- "include": "#string"
572- }
573- ]
574- },
575- "handlebars_attribute": {
576- "patterns": [
577- {
578- "include": "#handlebars_attribute_name"
579- },
580- {
581- "include": "#handlebars_attribute_value"
582- }
583- ]
584- },
585- "extends": {
586- "patterns": [
587- {
588- "end": "(\\}\\})",
589- "begin": "(\\{\\{!<)\\s([-a-zA-Z0-9_\\./]+)",
590- "beginCaptures": {
591- "1": {
592- "name": "support.function.handlebars"
593- },
594- "2": {
595- "name": "support.class.handlebars"
596- }
597- },
598- "endCaptures": {
599- "1": {
600- "name": "support.function.handlebars"
601- }
602- },
603- "name": "meta.preprocessor.handlebars"
604- }
605- ]
606- },
607- "else_token": {
608- "begin": "(\\{\\{~?else)(@?\\s(if)\\s([-a-zA-Z0-9_\\./]+))?",
609- "end": "(~?\\}\\}\\}*)",
610- "name": "meta.function.inline.else.handlebars",
611- "beginCaptures": {
612- "1": {
613- "name": "support.constant.handlebars"
614- },
615- "3": {
616- "name": "support.constant.handlebars"
617- },
618- "4": {
619- "name": "variable.parameter.handlebars"
620- }
621- },
622- "endCaptures": {
623- "1": {
624- "name": "support.constant.handlebars"
625- }
626- }
627- },
628- "string-double-quoted": {
629- "begin": "\"",
630- "end": "\"",
631- "name": "string.quoted.double.handlebars",
632- "beginCaptures": {
633- "0": {
634- "name": "punctuation.definition.string.begin.html"
635- }
636- },
637- "endCaptures": {
638- "0": {
639- "name": "punctuation.definition.string.end.html"
640- }
641- },
642- "patterns": [
643- {
644- "include": "#escaped-double-quote"
645- },
646- {
647- "include": "#block_comments"
648- },
649- {
650- "include": "#comments"
651- },
652- {
653- "include": "#block_helper"
654- },
655- {
656- "include": "#else_token"
657- },
658- {
659- "include": "#end_block"
660- },
661- {
662- "include": "#partial_and_var"
663- }
664- ]
665- },
666- "inline_script": {
667- "begin": "(?:^\\s+)?(<)((?i:script))\\b(?:.*(type)=([\"'](?:text/x-handlebars-template|text/x-handlebars|text/template|x-tmpl-handlebars)[\"']))(?![^>]*/>)",
668- "beginCaptures": {
669- "1": {
670- "name": "punctuation.definition.tag.html"
671- },
672- "2": {
673- "name": "entity.name.tag.script.html"
674- },
675- "3": {
676- "name": "entity.other.attribute-name.html"
677- },
678- "4": {
679- "name": "string.quoted.double.html"
680- }
681- },
682- "end": "(?<=</(script|SCRIPT))(>)(?:\\s*\\n)?",
683- "endCaptures": {
684- "2": {
685- "name": "punctuation.definition.tag.html"
686- }
687- },
688- "name": "source.handlebars.embedded.html",
689- "patterns": [
690- {
691- "include": "#tag-stuff"
692- },
693- {
694- "begin": "(?<!</(?:script|SCRIPT))(>)",
695- "captures": {
696- "1": {
697- "name": "punctuation.definition.tag.html"
698- },
699- "2": {
700- "name": "entity.name.tag.script.html"
701- }
702- },
703- "end": "(</)((?i:script))",
704- "patterns": [
705- {
706- "include": "#block_comments"
707- },
708- {
709- "include": "#comments"
710- },
711- {
712- "include": "#block_helper"
713- },
714- {
715- "include": "#end_block"
716- },
717- {
718- "include": "#else_token"
719- },
720- {
721- "include": "#partial_and_var"
722- },
723- {
724- "include": "#html_tags"
725- },
726- {
727- "include": "text.html.basic"
728- }
729- ]
730- }
731- ]
732- },
733- "tag_generic_attribute": {
734- "begin": "\\b([a-zA-Z0-9_-]+)\\b\\s*(=)",
735- "captures": {
736- "1": {
737- "name": "entity.other.attribute-name.generic.html"
738- },
739- "2": {
740- "name": "punctuation.separator.key-value.html"
741- }
742- },
743- "patterns": [
744- {
745- "include": "#string"
746- }
747- ],
748- "name": "entity.other.attribute-name.html",
749- "end": "(?<='|\"|)"
750- },
751- "tag_id_attribute": {
752- "begin": "\\b(id)\\b\\s*(=)",
753- "captures": {
754- "1": {
755- "name": "entity.other.attribute-name.id.html"
756- },
757- "2": {
758- "name": "punctuation.separator.key-value.html"
759- }
760- },
761- "end": "(?<='|\"|)",
762- "name": "meta.attribute-with-value.id.html",
763- "patterns": [
764- {
765- "include": "#string"
766- }
767- ]
768- },
769- "tag-stuff": {
770- "patterns": [
771- {
772- "include": "#tag_id_attribute"
773- },
774- {
775- "include": "#tag_generic_attribute"
776- },
777- {
778- "include": "#string"
779- },
780- {
781- "include": "#block_comments"
782- },
783- {
784- "include": "#comments"
785- },
786- {
787- "include": "#block_helper"
788- },
789- {
790- "include": "#end_block"
791- },
792- {
793- "include": "#else_token"
794- },
795- {
796- "include": "#partial_and_var"
797- }
798- ]
799- }
800- },
801- "scopeName": "text.html.handlebars",
802- "patterns": [
803- {
804- "include": "#yfm"
805- },
806- {
807- "include": "#extends"
808- },
809- {
810- "include": "#block_comments"
811- },
812- {
813- "include": "#comments"
814- },
815- {
816- "include": "#block_helper"
817- },
818- {
819- "include": "#end_block"
820- },
821- {
822- "include": "#else_token"
823- },
824- {
825- "include": "#partial_and_var"
826- },
827- {
828- "include": "#inline_script"
829- },
830- {
831- "include": "#html_tags"
832- },
833- {
834- "include": "text.html.basic"
835- }
836- ],
837- "fileTypes": [
838- "handlebars",
839- "handlebars.html",
840- "hbr",
841- "hbrs",
842- "hbs",
843- "hdbs",
844- "hjs",
845- "mu",
846- "mustache",
847- "rac",
848- "stache",
849- "template",
850- "tmpl"
851- ],
852- "uuid": "70E91676-DE0A-4266-A2B9-3AD2E535E484",
853- "version": "https://github.com/daaain/Handlebars/commit/bdaec7aaf5eaac45d1878096110d1db7975fb100"
854-}
No newline at the end of the file
2+ "name": "Handlebars",
3+ "repository": {
4+ "html_tags": {
5+ "patterns": [
6+ {
7+ "begin": "(<)([a-zA-Z0-9:-]+)(?=[^>]*></\\2>)",
8+ "beginCaptures": {
9+ "1": {
10+ "name": "punctuation.definition.tag.html"
11+ },
12+ "2": {
13+ "name": "entity.name.tag.html"
14+ }
15+ },
16+ "end": "(>(<)/)(\\2)(>)",
17+ "endCaptures": {
18+ "1": {
19+ "name": "punctuation.definition.tag.html"
20+ },
21+ "2": {
22+ "name": "meta.scope.between-tag-pair.html"
23+ },
24+ "3": {
25+ "name": "entity.name.tag.html"
26+ },
27+ "4": {
28+ "name": "punctuation.definition.tag.html"
29+ }
30+ },
31+ "name": "meta.tag.any.html",
32+ "patterns": [
33+ {
34+ "include": "#tag-stuff"
35+ }
36+ ]
37+ },
38+ {
39+ "begin": "(<\\?)(xml)",
40+ "captures": {
41+ "1": {
42+ "name": "punctuation.definition.tag.html"
43+ },
44+ "2": {
45+ "name": "entity.name.tag.xml.html"
46+ }
47+ },
48+ "end": "(\\?>)",
49+ "name": "meta.tag.preprocessor.xml.html",
50+ "patterns": [
51+ {
52+ "include": "#tag_generic_attribute"
53+ },
54+ {
55+ "include": "#string"
56+ }
57+ ]
58+ },
59+ {
60+ "begin": "<!--",
61+ "captures": {
62+ "0": {
63+ "name": "punctuation.definition.comment.html"
64+ }
65+ },
66+ "end": "--\\s*>",
67+ "name": "comment.block.html",
68+ "patterns": [
69+ {
70+ "match": "--",
71+ "name": "invalid.illegal.bad-comments-or-CDATA.html"
72+ }
73+ ]
74+ },
75+ {
76+ "begin": "<!",
77+ "captures": {
78+ "0": {
79+ "name": "punctuation.definition.tag.html"
80+ }
81+ },
82+ "end": ">",
83+ "name": "meta.tag.sgml.html",
84+ "patterns": [
85+ {
86+ "begin": "(DOCTYPE|doctype)",
87+ "captures": {
88+ "1": {
89+ "name": "entity.name.tag.doctype.html"
90+ }
91+ },
92+ "end": "(?=>)",
93+ "name": "meta.tag.sgml.doctype.html",
94+ "patterns": [
95+ {
96+ "match": "\"[^\">]*\"",
97+ "name": "string.quoted.double.doctype.identifiers-and-DTDs.html"
98+ }
99+ ]
100+ },
101+ {
102+ "begin": "\\[CDATA\\[",
103+ "end": "]](?=>)",
104+ "name": "constant.other.inline-data.html"
105+ },
106+ {
107+ "match": "(\\s*)(?!--|>)\\S(\\s*)",
108+ "name": "invalid.illegal.bad-comments-or-CDATA.html"
109+ }
110+ ]
111+ },
112+ {
113+ "begin": "(?:^\\s+)?(<)((?i:style))\\b(?![^>]*/>)",
114+ "captures": {
115+ "1": {
116+ "name": "punctuation.definition.tag.html"
117+ },
118+ "2": {
119+ "name": "entity.name.tag.style.html"
120+ },
121+ "3": {
122+ "name": "punctuation.definition.tag.html"
123+ }
124+ },
125+ "end": "(</)((?i:style))(>)(?:\\s*\\n)?",
126+ "name": "source.css.embedded.html",
127+ "patterns": [
128+ {
129+ "include": "#tag-stuff"
130+ },
131+ {
132+ "begin": "(>)",
133+ "beginCaptures": {
134+ "1": {
135+ "name": "punctuation.definition.tag.html"
136+ }
137+ },
138+ "end": "(?=</(?i:style))",
139+ "patterns": [
140+ {
141+ "include": "source.css"
142+ }
143+ ]
144+ }
145+ ]
146+ },
147+ {
148+ "begin": "(?:^\\s+)?(<)((?i:script))\\b(?![^>]*/>)",
149+ "beginCaptures": {
150+ "1": {
151+ "name": "punctuation.definition.tag.html"
152+ },
153+ "2": {
154+ "name": "entity.name.tag.script.html"
155+ }
156+ },
157+ "end": "(?<=</(script|SCRIPT))(>)(?:\\s*\\n)?",
158+ "endCaptures": {
159+ "2": {
160+ "name": "punctuation.definition.tag.html"
161+ }
162+ },
163+ "name": "source.js.embedded.html",
164+ "patterns": [
165+ {
166+ "include": "#tag-stuff"
167+ },
168+ {
169+ "begin": "(?<!</(?:script|SCRIPT))(>)",
170+ "captures": {
171+ "1": {
172+ "name": "punctuation.definition.tag.html"
173+ },
174+ "2": {
175+ "name": "entity.name.tag.script.html"
176+ }
177+ },
178+ "end": "(</)((?i:script))",
179+ "patterns": [
180+ {
181+ "captures": {
182+ "1": {
183+ "name": "punctuation.definition.comment.js"
184+ }
185+ },
186+ "match": "(//).*?((?=</script)|$\\n?)",
187+ "name": "comment.line.double-slash.js"
188+ },
189+ {
190+ "begin": "/\\*",
191+ "captures": {
192+ "0": {
193+ "name": "punctuation.definition.comment.js"
194+ }
195+ },
196+ "end": "\\*/|(?=</script)",
197+ "name": "comment.block.js"
198+ },
199+ {
200+ "include": "source.js"
201+ }
202+ ]
203+ }
204+ ]
205+ },
206+ {
207+ "begin": "(</?)((?i:body|head|html)\\b)",
208+ "captures": {
209+ "1": {
210+ "name": "punctuation.definition.tag.html"
211+ },
212+ "2": {
213+ "name": "entity.name.tag.structure.any.html"
214+ }
215+ },
216+ "end": "(>)",
217+ "name": "meta.tag.structure.any.html",
218+ "patterns": [
219+ {
220+ "include": "#tag-stuff"
221+ }
222+ ]
223+ },
224+ {
225+ "begin": "(</?)((?i:address|blockquote|dd|div|header|section|footer|aside|nav|dl|dt|fieldset|form|frame|frameset|h1|h2|h3|h4|h5|h6|iframe|noframes|object|ol|p|ul|applet|center|dir|hr|menu|pre)\\b)",
226+ "captures": {
227+ "1": {
228+ "name": "punctuation.definition.tag.html"
229+ },
230+ "2": {
231+ "name": "entity.name.tag.block.any.html"
232+ }
233+ },
234+ "end": "(>)",
235+ "name": "meta.tag.block.any.html",
236+ "patterns": [
237+ {
238+ "include": "#tag-stuff"
239+ }
240+ ]
241+ },
242+ {
243+ "begin": "(</?)((?i:a|abbr|acronym|area|b|base|basefont|bdo|big|br|button|caption|cite|code|col|colgroup|del|dfn|em|font|head|html|i|img|input|ins|isindex|kbd|label|legend|li|link|map|meta|noscript|optgroup|option|param|q|s|samp|script|select|small|span|strike|strong|style|sub|sup|table|tbody|td|textarea|tfoot|th|thead|title|tr|tt|u|var)\\b)",
244+ "captures": {
245+ "1": {
246+ "name": "punctuation.definition.tag.html"
247+ },
248+ "2": {
249+ "name": "entity.name.tag.inline.any.html"
250+ }
251+ },
252+ "end": "((?: ?/)?>)",
253+ "name": "meta.tag.inline.any.html",
254+ "patterns": [
255+ {
256+ "include": "#tag-stuff"
257+ }
258+ ]
259+ },
260+ {
261+ "begin": "(</?)([a-zA-Z0-9:-]+)",
262+ "captures": {
263+ "1": {
264+ "name": "punctuation.definition.tag.html"
265+ },
266+ "2": {
267+ "name": "entity.name.tag.other.html"
268+ }
269+ },
270+ "end": "(>)",
271+ "name": "meta.tag.other.html",
272+ "patterns": [
273+ {
274+ "include": "#tag-stuff"
275+ }
276+ ]
277+ },
278+ {
279+ "begin": "(</?)([a-zA-Z0-9{}:-]+)",
280+ "captures": {
281+ "1": {
282+ "name": "punctuation.definition.tag.html"
283+ },
284+ "2": {
285+ "name": "entity.name.tag.tokenised.html"
286+ }
287+ },
288+ "end": "(>)",
289+ "name": "meta.tag.tokenised.html",
290+ "patterns": [
291+ {
292+ "include": "#tag-stuff"
293+ }
294+ ]
295+ },
296+ {
297+ "include": "#entities"
298+ },
299+ {
300+ "match": "<>",
301+ "name": "invalid.illegal.incomplete.html"
302+ },
303+ {
304+ "match": "<",
305+ "name": "invalid.illegal.bad-angle-bracket.html"
306+ }
307+ ]
308+ },
309+ "entities": {
310+ "patterns": [
311+ {
312+ "captures": {
313+ "1": {
314+ "name": "punctuation.definition.entity.html"
315+ },
316+ "3": {
317+ "name": "punctuation.definition.entity.html"
318+ }
319+ },
320+ "name": "constant.character.entity.html",
321+ "match": "(&)([a-zA-Z0-9]+|#[0-9]+|#x[0-9a-fA-F]+)(;)"
322+ },
323+ {
324+ "name": "invalid.illegal.bad-ampersand.html",
325+ "match": "&"
326+ }
327+ ]
328+ },
329+ "end_block": {
330+ "begin": "(\\{\\{~?/)([a-zA-Z0-9_\\.-]+)\\s*",
331+ "end": "(~?\\}\\})",
332+ "name": "meta.function.block.end.handlebars",
333+ "endCaptures": {
334+ "1": {
335+ "name": "support.constant.handlebars"
336+ }
337+ },
338+ "beginCaptures": {
339+ "1": {
340+ "name": "support.constant.handlebars"
341+ },
342+ "2": {
343+ "name": "support.constant.handlebars"
344+ }
345+ },
346+ "patterns": []
347+ },
348+ "yfm": {
349+ "patterns": [
350+ {
351+ "patterns": [
352+ {
353+ "include": "source.yaml"
354+ }
355+ ],
356+ "begin": "(?<!\\s)---\\n$",
357+ "end": "^---\\s",
358+ "name": "markup.raw.yaml.front-matter"
359+ }
360+ ]
361+ },
362+ "comments": {
363+ "patterns": [
364+ {
365+ "patterns": [
366+ {
367+ "name": "keyword.annotation.handlebars",
368+ "match": "@\\w*"
369+ },
370+ {
371+ "include": "#comments"
372+ }
373+ ],
374+ "begin": "\\{\\{!",
375+ "end": "\\}\\}",
376+ "name": "comment.block.handlebars"
377+ },
378+ {
379+ "captures": {
380+ "0": {
381+ "name": "punctuation.definition.comment.html"
382+ }
383+ },
384+ "begin": "<!--",
385+ "end": "-{2,3}\\s*>",
386+ "name": "comment.block.html",
387+ "patterns": [
388+ {
389+ "name": "invalid.illegal.bad-comments-or-CDATA.html",
390+ "match": "--"
391+ }
392+ ]
393+ }
394+ ]
395+ },
396+ "block_comments": {
397+ "patterns": [
398+ {
399+ "patterns": [
400+ {
401+ "name": "keyword.annotation.handlebars",
402+ "match": "@\\w*"
403+ },
404+ {
405+ "include": "#comments"
406+ }
407+ ],
408+ "begin": "\\{\\{!--",
409+ "end": "--\\}\\}",
410+ "name": "comment.block.handlebars"
411+ },
412+ {
413+ "captures": {
414+ "0": {
415+ "name": "punctuation.definition.comment.html"
416+ }
417+ },
418+ "begin": "<!--",
419+ "end": "-{2,3}\\s*>",
420+ "name": "comment.block.html",
421+ "patterns": [
422+ {
423+ "name": "invalid.illegal.bad-comments-or-CDATA.html",
424+ "match": "--"
425+ }
426+ ]
427+ }
428+ ]
429+ },
430+ "block_helper": {
431+ "begin": "(\\{\\{~?\\#)([-a-zA-Z0-9_\\./]+)\\s?(@?[-a-zA-Z0-9_\\./]+)*\\s?(@?[-a-zA-Z0-9_\\./]+)*\\s?(@?[-a-zA-Z0-9_\\./]+)*",
432+ "end": "(~?\\}\\})",
433+ "name": "meta.function.block.start.handlebars",
434+ "endCaptures": {
435+ "1": {
436+ "name": "support.constant.handlebars"
437+ }
438+ },
439+ "beginCaptures": {
440+ "1": {
441+ "name": "support.constant.handlebars"
442+ },
443+ "2": {
444+ "name": "support.constant.handlebars"
445+ },
446+ "3": {
447+ "name": "variable.parameter.handlebars"
448+ },
449+ "4": {
450+ "name": "support.constant.handlebars"
451+ },
452+ "5": {
453+ "name": "variable.parameter.handlebars"
454+ },
455+ "6": {
456+ "name": "support.constant.handlebars"
457+ }
458+ },
459+ "patterns": [
460+ {
461+ "include": "#string"
462+ },
463+ {
464+ "include": "#handlebars_attribute"
465+ }
466+ ]
467+ },
468+ "string-single-quoted": {
469+ "begin": "'",
470+ "end": "'",
471+ "name": "string.quoted.single.handlebars",
472+ "endCaptures": {
473+ "0": {
474+ "name": "punctuation.definition.string.end.html"
475+ }
476+ },
477+ "beginCaptures": {
478+ "0": {
479+ "name": "punctuation.definition.string.begin.html"
480+ }
481+ },
482+ "patterns": [
483+ {
484+ "include": "#escaped-single-quote"
485+ },
486+ {
487+ "include": "#block_comments"
488+ },
489+ {
490+ "include": "#comments"
491+ },
492+ {
493+ "include": "#block_helper"
494+ },
495+ {
496+ "include": "#else_token"
497+ },
498+ {
499+ "include": "#end_block"
500+ },
501+ {
502+ "include": "#partial_and_var"
503+ }
504+ ]
505+ },
506+ "string": {
507+ "patterns": [
508+ {
509+ "include": "#string-single-quoted"
510+ },
511+ {
512+ "include": "#string-double-quoted"
513+ }
514+ ]
515+ },
516+ "escaped-single-quote": {
517+ "name": "constant.character.escape.js",
518+ "match": "\\\\'"
519+ },
520+ "escaped-double-quote": {
521+ "name": "constant.character.escape.js",
522+ "match": "\\\\\""
523+ },
524+ "partial_and_var": {
525+ "begin": "(\\{\\{~?\\{*(>|!<)*)\\s*(@?[-a-zA-Z0-9_\\./]+)*",
526+ "end": "(~?\\}\\}\\}*)",
527+ "name": "meta.function.inline.other.handlebars",
528+ "beginCaptures": {
529+ "1": {
530+ "name": "support.constant.handlebars"
531+ },
532+ "3": {
533+ "name": "variable.parameter.handlebars"
534+ }
535+ },
536+ "endCaptures": {
537+ "1": {
538+ "name": "support.constant.handlebars"
539+ }
540+ },
541+ "patterns": [
542+ {
543+ "include": "#string"
544+ },
545+ {
546+ "include": "#handlebars_attribute"
547+ }
548+ ]
549+ },
550+ "handlebars_attribute_name": {
551+ "begin": "\\b([-a-zA-Z0-9_\\.]+)\\b=",
552+ "captures": {
553+ "1": {
554+ "name": "variable.parameter.handlebars"
555+ }
556+ },
557+ "end": "(?='|\"|)",
558+ "name": "entity.other.attribute-name.handlebars"
559+ },
560+ "handlebars_attribute_value": {
561+ "begin": "([-a-zA-Z0-9_\\./]+)\\b\\s*",
562+ "captures": {
563+ "1": {
564+ "name": "variable.parameter.handlebars"
565+ }
566+ },
567+ "end": "('|\"|)",
568+ "name": "entity.other.attribute-value.handlebars",
569+ "patterns": [
570+ {
571+ "include": "#string"
572+ }
573+ ]
574+ },
575+ "handlebars_attribute": {
576+ "patterns": [
577+ {
578+ "include": "#handlebars_attribute_name"
579+ },
580+ {
581+ "include": "#handlebars_attribute_value"
582+ }
583+ ]
584+ },
585+ "extends": {
586+ "patterns": [
587+ {
588+ "end": "(\\}\\})",
589+ "begin": "(\\{\\{!<)\\s([-a-zA-Z0-9_\\./]+)",
590+ "beginCaptures": {
591+ "1": {
592+ "name": "support.function.handlebars"
593+ },
594+ "2": {
595+ "name": "support.class.handlebars"
596+ }
597+ },
598+ "endCaptures": {
599+ "1": {
600+ "name": "support.function.handlebars"
601+ }
602+ },
603+ "name": "meta.preprocessor.handlebars"
604+ }
605+ ]
606+ },
607+ "else_token": {
608+ "begin": "(\\{\\{~?else)(@?\\s(if)\\s([-a-zA-Z0-9_\\./]+))?",
609+ "end": "(~?\\}\\}\\}*)",
610+ "name": "meta.function.inline.else.handlebars",
611+ "beginCaptures": {
612+ "1": {
613+ "name": "support.constant.handlebars"
614+ },
615+ "3": {
616+ "name": "support.constant.handlebars"
617+ },
618+ "4": {
619+ "name": "variable.parameter.handlebars"
620+ }
621+ },
622+ "endCaptures": {
623+ "1": {
624+ "name": "support.constant.handlebars"
625+ }
626+ }
627+ },
628+ "string-double-quoted": {
629+ "begin": "\"",
630+ "end": "\"",
631+ "name": "string.quoted.double.handlebars",
632+ "beginCaptures": {
633+ "0": {
634+ "name": "punctuation.definition.string.begin.html"
635+ }
636+ },
637+ "endCaptures": {
638+ "0": {
639+ "name": "punctuation.definition.string.end.html"
640+ }
641+ },
642+ "patterns": [
643+ {
644+ "include": "#escaped-double-quote"
645+ },
646+ {
647+ "include": "#block_comments"
648+ },
649+ {
650+ "include": "#comments"
651+ },
652+ {
653+ "include": "#block_helper"
654+ },
655+ {
656+ "include": "#else_token"
657+ },
658+ {
659+ "include": "#end_block"
660+ },
661+ {
662+ "include": "#partial_and_var"
663+ }
664+ ]
665+ },
666+ "inline_script": {
667+ "begin": "(?:^\\s+)?(<)((?i:script))\\b(?:.*(type)=([\"'](?:text/x-handlebars-template|text/x-handlebars|text/template|x-tmpl-handlebars)[\"']))(?![^>]*/>)",
668+ "beginCaptures": {
669+ "1": {
670+ "name": "punctuation.definition.tag.html"
671+ },
672+ "2": {
673+ "name": "entity.name.tag.script.html"
674+ },
675+ "3": {
676+ "name": "entity.other.attribute-name.html"
677+ },
678+ "4": {
679+ "name": "string.quoted.double.html"
680+ }
681+ },
682+ "end": "(?<=</(script|SCRIPT))(>)(?:\\s*\\n)?",
683+ "endCaptures": {
684+ "2": {
685+ "name": "punctuation.definition.tag.html"
686+ }
687+ },
688+ "name": "source.handlebars.embedded.html",
689+ "patterns": [
690+ {
691+ "include": "#tag-stuff"
692+ },
693+ {
694+ "begin": "(?<!</(?:script|SCRIPT))(>)",
695+ "captures": {
696+ "1": {
697+ "name": "punctuation.definition.tag.html"
698+ },
699+ "2": {
700+ "name": "entity.name.tag.script.html"
701+ }
702+ },
703+ "end": "(</)((?i:script))",
704+ "patterns": [
705+ {
706+ "include": "#block_comments"
707+ },
708+ {
709+ "include": "#comments"
710+ },
711+ {
712+ "include": "#block_helper"
713+ },
714+ {
715+ "include": "#end_block"
716+ },
717+ {
718+ "include": "#else_token"
719+ },
720+ {
721+ "include": "#partial_and_var"
722+ },
723+ {
724+ "include": "#html_tags"
725+ },
726+ {
727+ "include": "text.html.basic"
728+ }
729+ ]
730+ }
731+ ]
732+ },
733+ "tag_generic_attribute": {
734+ "begin": "\\b([a-zA-Z0-9_-]+)\\b\\s*(=)",
735+ "captures": {
736+ "1": {
737+ "name": "entity.other.attribute-name.generic.html"
738+ },
739+ "2": {
740+ "name": "punctuation.separator.key-value.html"
741+ }
742+ },
743+ "patterns": [
744+ {
745+ "include": "#string"
746+ }
747+ ],
748+ "name": "entity.other.attribute-name.html",
749+ "end": "(?<='|\"|)"
750+ },
751+ "tag_id_attribute": {
752+ "begin": "\\b(id)\\b\\s*(=)",
753+ "captures": {
754+ "1": {
755+ "name": "entity.other.attribute-name.id.html"
756+ },
757+ "2": {
758+ "name": "punctuation.separator.key-value.html"
759+ }
760+ },
761+ "end": "(?<='|\"|)",
762+ "name": "meta.attribute-with-value.id.html",
763+ "patterns": [
764+ {
765+ "include": "#string"
766+ }
767+ ]
768+ },
769+ "tag-stuff": {
770+ "patterns": [
771+ {
772+ "include": "#tag_id_attribute"
773+ },
774+ {
775+ "include": "#tag_generic_attribute"
776+ },
777+ {
778+ "include": "#string"
779+ },
780+ {
781+ "include": "#block_comments"
782+ },
783+ {
784+ "include": "#comments"
785+ },
786+ {
787+ "include": "#block_helper"
788+ },
789+ {
790+ "include": "#end_block"
791+ },
792+ {
793+ "include": "#else_token"
794+ },
795+ {
796+ "include": "#partial_and_var"
797+ }
798+ ]
799+ }
800+ },
801+ "scopeName": "text.html.handlebars",
802+ "patterns": [
803+ {
804+ "include": "#yfm"
805+ },
806+ {
807+ "include": "#extends"
808+ },
809+ {
810+ "include": "#block_comments"
811+ },
812+ {
813+ "include": "#comments"
814+ },
815+ {
816+ "include": "#block_helper"
817+ },
818+ {
819+ "include": "#end_block"
820+ },
821+ {
822+ "include": "#else_token"
823+ },
824+ {
825+ "include": "#partial_and_var"
826+ },
827+ {
828+ "include": "#inline_script"
829+ },
830+ {
831+ "include": "#html_tags"
832+ },
833+ {
834+ "include": "text.html.basic"
835+ }
836+ ],
837+ "fileTypes": [
838+ "handlebars",
839+ "handlebars.html",
840+ "hbr",
841+ "hbrs",
842+ "hbs",
843+ "hdbs",
844+ "hjs",
845+ "mu",
846+ "mustache",
847+ "rac",
848+ "stache",
849+ "template",
850+ "tmpl"
851+ ],
852+ "uuid": "70E91676-DE0A-4266-A2B9-3AD2E535E484",
853+ "version": "https://github.com/daaain/Handlebars/commit/bdaec7aaf5eaac45d1878096110d1db7975fb100"
854+}
modified extensions/vscode/textmate-syntaxes/Jade.json +961 −963
@@ -1,964 +1,962 @@
11 {
2- "fileTypes": [
3- "jade"
4- ],
5- "name": "Jade",
6- "patterns": [
7- {
8- "comment": "Doctype declaration.",
9- "match": "^(!!!|doctype)(\\s*[a-zA-Z0-9-_]+)?",
10- "name": "meta.tag.sgml.doctype.html"
11- },
12- {
13- "begin": "^(\\s*)//-",
14- "comment": "Unbuffered (jade-only) comments.",
15- "end": "^(?!(\\1\\s)|\\s*$)",
16- "name": "comment.unbuffered.block.jade"
17- },
18- {
19- "begin": "^(\\s*)//",
20- "comment": "Buffered (html) comments.",
21- "end": "^(?!(\\1\\s)|\\s*$)",
22- "name": "string.comment.buffered.block.jade",
23- "patterns": [
24- {
25- "captures": {
26- "1": {
27- "name": "invalid.illegal.comment.comment.block.jade"
28- }
29- },
30- "comment": "Buffered comments inside buffered comments will generate invalid html.",
31- "match": "^\\s*(//)(?!-)",
32- "name": "string.comment.buffered.block.jade"
33- }
34- ]
35- },
36- {
37- "begin": "^(\\s*)-$",
38- "comment": "Unbuffered code block.",
39- "end": "^(?!(\\1\\s)|\\s*$)",
40- "name": "source.js",
41- "patterns": [
42- {
43- "include": "source.js"
44- }
45- ]
46- },
47- {
48- "begin": "^(\\s*)(script)(?=[.#(\\s])((?![^\\n]*type=)|(?=[^\\n]*(text|application)/javascript))",
49- "beginCaptures": {
50- "2": {
51- "name": "entity.name.tag.script.jade"
52- }
53- },
54- "comment": "Script tag with JavaScript code.",
55- "end": "^(?!(\\1\\s)|\\s*$)",
56- "name": "meta.tag.other",
57- "patterns": [
58- {
59- "begin": "\\G(?=\\()",
60- "end": "$",
61- "name": "stuff.tag.script.jade",
62- "patterns": [
63- {
64- "include": "#tag_attributes"
65- }
66- ]
67- },
68- {
69- "begin": "\\G(?=[.#])",
70- "end": "$",
71- "name": "stuff.tag.script.jade",
72- "patterns": [
73- {
74- "include": "#complete_tag"
75- }
76- ]
77- },
78- {
79- "include": "source.js"
80- }
81- ]
82- },
83- {
84- "begin": "^(\\s*)(style)((\\.$)|(?=[.#(].*\\.$))",
85- "beginCaptures": {
86- "2": {
87- "name": "entity.name.tag.script.jade"
88- }
89- },
90- "comment": "Style tag with CSS code.",
91- "end": "^(?!(\\1\\s)|\\s*$)",
92- "name": "meta.tag.other",
93- "patterns": [
94- {
95- "begin": "\\G(?=\\()",
96- "end": "$",
97- "name": "stuff.tag.style.jade",
98- "patterns": [
99- {
100- "include": "#tag_attributes"
101- }
102- ]
103- },
104- {
105- "begin": "\\G(?=[.#])",
106- "end": "$",
107- "name": "stuff.tag.style.jade",
108- "patterns": [
109- {
110- "include": "#complete_tag"
111- }
112- ]
113- },
114- {
115- "include": "source.css"
116- }
117- ]
118- },
119- {
120- "begin": "^(\\s*):(sass)(?=\\(|$)",
121- "beginCaptures": {
122- "2": {
123- "name": "constant.language.name.sass.filter.jade"
124- }
125- },
126- "end": "^(?!(\\1\\s)|\\s*$)",
127- "name": "source.sass.filter.jade",
128- "patterns": [
129- {
130- "include": "#tag_attributes"
131- },
132- {
133- "include": "source.sass"
134- }
135- ]
136- },
137- {
138- "begin": "^(\\s*):(less)(?=\\(|$)",
139- "beginCaptures": {
140- "2": {
141- "name": "constant.language.name.less.filter.jade"
142- }
143- },
144- "end": "^(?!(\\1\\s)|\\s*$)",
145- "name": "source.less.filter.jade",
146- "patterns": [
147- {
148- "include": "#tag_attributes"
149- },
150- {
151- "include": "source.less"
152- }
153- ]
154- },
155- {
156- "begin": "^(\\s*):(stylus)(?=\\(|$)",
157- "beginCaptures": {
158- "2": {
159- "name": "constant.language.name.stylus.filter.jade"
160- }
161- },
162- "end": "^(?!(\\1\\s)|\\s*$)",
163- "patterns": [
164- {
165- "include": "#tag_attributes"
166- },
167- {
168- "include": "source.stylus"
169- }
170- ]
171- },
172- {
173- "begin": "^(\\s*):(coffee(-?script)?)(?=\\(|$)",
174- "beginCaptures": {
175- "2": {
176- "name": "constant.language.name.coffeescript.filter.jade"
177- }
178- },
179- "end": "^(?!(\\1\\s)|\\s*$)",
180- "name": "source.coffeescript.filter.jade",
181- "patterns": [
182- {
183- "include": "#tag_attributes"
184- },
185- {
186- "include": "source.coffee"
187- }
188- ]
189- },
190- {
191- "begin": "^(\\s*)((:(?=.))|(:$))",
192- "beginCaptures": {
193- "4": {
194- "name": "invalid.illegal.empty.generic.filter.jade"
195- }
196- },
197- "comment": "Generic Jade filter.",
198- "end": "^(?!(\\1\\s)|\\s*$)",
199- "patterns": [
200- {
201- "begin": "\\G(?<=:)(?=.)",
202- "end": "$",
203- "name": "name.generic.filter.jade",
204- "patterns": [
205- {
206- "match": "\\G\\(",
207- "name": "invalid.illegal.name.generic.filter.jade"
208- },
209- {
210- "match": "[\\w-]",
211- "name": "constant.language.name.generic.filter.jade"
212- },
213- {
214- "include": "#tag_attributes"
215- },
216- {
217- "match": "\\W",
218- "name": "invalid.illegal.name.generic.filter.jade"
219- }
220- ]
221- }
222- ]
223- },
224- {
225- "begin": "^(\\s*)(?=[\\w.#].*?\\.$)(?=(?:(?:(?:(?:(?:#[\\w-]+)|(?:\\.[\\w-]+))|(?:(?:[#!]\\{[^}]*\\})|(?:\\w(?:(?:[\\w:-]+[\\w-])|(?:[\\w-]*)))))(?:(?:#[\\w-]+)|(?:\\.[\\w-]+)|(?:\\((?:[^()\\'\\\"]*(?:(?:\\'(?:[^\\']|(?:(?<!\\\\)\\\\\\'))*\\')|(?:\\\"(?:[^\\\"]|(?:(?<!\\\\)\\\\\\\"))*\\\")))*[^()]*\\))*)*)(?:(?:(?::\\s+)|(?<=\\)))(?:(?:(?:(?:#[\\w-]+)|(?:\\.[\\w-]+))|(?:(?:[#!]\\{[^}]*\\})|(?:\\w(?:(?:[\\w:-]+[\\w-])|(?:[\\w-]*)))))(?:(?:#[\\w-]+)|(?:\\.[\\w-]+)|(?:\\((?:[^()\\'\\\"]*(?:(?:\\'(?:[^\\']|(?:(?<!\\\\)\\\\\\'))*\\')|(?:\\\"(?:[^\\\"]|(?:(?<!\\\\)\\\\\\\"))*\\\")))*[^()]*\\))*)*))*)\\.$)(?:(?:(#[\\w-]+)|(\\.[\\w-]+))|((?:[#!]\\{[^}]*\\})|(?:\\w(?:(?:[\\w:-]+[\\w-])|(?:[\\w-]*)))))",
226- "beginCaptures": {
227- "2": {
228- "name": "constant.id.tag.jade"
229- },
230- "3": {
231- "name": "constant.language.js"
232- },
233- "4": {
234- "name": "meta.tag.other entity.name.tag.jade"
235- }
236- },
237- "comment": "Generated from dot_block_tag.py",
238- "end": "^(?!(\\1\\s)|\\s*$)",
239- "patterns": [
240- {
241- "include": "#tag_attributes"
242- },
243- {
244- "include": "#complete_tag"
245- },
246- {
247- "begin": "^(?=.)",
248- "end": "$",
249- "name": "text.block.jade",
250- "patterns": [
251- {
252- "include": "#inline_jade"
253- },
254- {
255- "include": "#embedded_html"
256- },
257- {
258- "include": "#html_entity"
259- },
260- {
261- "include": "#interpolated_value"
262- },
263- {
264- "include": "#interpolated_error"
265- }
266- ]
267- }
268- ]
269- },
270- {
271- "begin": "^\\s*",
272- "comment": "All constructs that generally span a single line starting with any number of white-spaces.",
273- "end": "$",
274- "patterns": [
275- {
276- "include": "#inline_jade"
277- },
278- {
279- "include": "#blocks_and_includes"
280- },
281- {
282- "include": "#unbuffered_code"
283- },
284- {
285- "include": "#mixin_definition"
286- },
287- {
288- "include": "#mixin_call"
289- },
290- {
291- "include": "#flow_control"
292- },
293- {
294- "include": "#case_conds"
295- },
296- {
297- "begin": "\\|",
298- "comment": "Tag pipe text line.",
299- "end": "$",
300- "name": "text.block.pipe.jade",
301- "patterns": [
302- {
303- "include": "#inline_jade"
304- },
305- {
306- "include": "#embedded_html"
307- },
308- {
309- "include": "#html_entity"
310- },
311- {
312- "include": "#interpolated_value"
313- },
314- {
315- "include": "#interpolated_error"
316- }
317- ]
318- },
319- {
320- "include": "#printed_expression"
321- },
322- {
323- "begin": "\\G(?=(#[^\\{\\w-])|[^\\w.#])",
324- "comment": "Line starting with characters incompatible with tag name/id/class is standalone text.",
325- "end": "$",
326- "patterns": [
327- {
328- "begin": "</?(?=[!#])",
329- "end": ">|$",
330- "patterns": [
331- {
332- "include": "#inline_jade"
333- },
334- {
335- "include": "#interpolated_value"
336- },
337- {
338- "include": "#interpolated_error"
339- }
340- ]
341- },
342- {
343- "include": "#inline_jade"
344- },
345- {
346- "include": "#embedded_html"
347- },
348- {
349- "include": "#html_entity"
350- },
351- {
352- "include": "#interpolated_value"
353- },
354- {
355- "include": "#interpolated_error"
356- }
357- ]
358- },
359- {
360- "include": "#complete_tag"
361- }
362- ]
363- }
364- ],
365- "repository": {
366- "blocks_and_includes": {
367- "captures": {
368- "1": {
369- "name": "storage.type.import.include.jade"
370- },
371- "4": {
372- "name": "variable.control.import.include.jade"
373- }
374- },
375- "comment": "Template blocks and includes.",
376- "match": "(extends|include|yield|append|prepend|block( (append|prepend))?)\\s+(.*)$",
377- "name": "meta.first-class.jade"
378- },
379- "case_conds": {
380- "begin": "(default|when)((\\s+|(?=:))|$)",
381- "captures": {
382- "1": {
383- "name": "storage.type.function.jade"
384- }
385- },
386- "comment": "Jade case conditionals.",
387- "end": "$",
388- "name": "meta.control.flow.jade",
389- "patterns": [
390- {
391- "begin": "\\G(?!:)",
392- "end": "(?=:\\s+)|$",
393- "name": "js.embedded.control.flow.jade",
394- "patterns": [
395- {
396- "include": "#case_when_paren"
397- },
398- {
399- "include": "source.js"
400- }
401- ]
402- },
403- {
404- "begin": ":\\s+",
405- "end": "$",
406- "name": "tag.case.control.flow.jade",
407- "patterns": [
408- {
409- "include": "#complete_tag"
410- }
411- ]
412- }
413- ]
414- },
415- "case_when_paren": {
416- "begin": "\\(",
417- "end": "\\)",
418- "name": "js.when.control.flow.jade",
419- "patterns": [
420- {
421- "include": "#case_when_paren"
422- },
423- {
424- "match": ":",
425- "name": "invalid.illegal.name.tag.jade"
426- },
427- {
428- "include": "source.js"
429- }
430- ]
431- },
432- "complete_tag": {
433- "begin": "(?=[\\w.#])|(:\\s*)",
434- "end": "(\\.?$)|(?=:.)",
435- "patterns": [
436- {
437- "include": "#blocks_and_includes"
438- },
439- {
440- "include": "#unbuffered_code"
441- },
442- {
443- "include": "#mixin_call"
444- },
445- {
446- "include": "#flow_control"
447- },
448- {
449- "match": "(?<=:)\\w.*$",
450- "name": "invalid.illegal.name.tag.jade"
451- },
452- {
453- "include": "#tag_name"
454- },
455- {
456- "include": "#tag_id"
457- },
458- {
459- "include": "#tag_classes"
460- },
461- {
462- "include": "#tag_attributes"
463- },
464- {
465- "include": "#tag_mixin_attributes"
466- },
467- {
468- "captures": {
469- "2": {
470- "name": "invalid.illegal.end.tag.jade"
471- },
472- "4": {
473- "name": "invalid.illegal.end.tag.jade"
474- }
475- },
476- "match": "((\\.)\\s+$)|((:)\\s*$)"
477- },
478- {
479- "include": "#printed_expression"
480- },
481- {
482- "include": "#tag_text"
483- }
484- ]
485- },
486- "embedded_html": {
487- "begin": "(?=<[^>]*>)",
488- "end": "$|(?=>)",
489- "name": "html",
490- "patterns": [
491- {
492- "include": "text.html.basic"
493- },
494- {
495- "include": "#interpolated_value"
496- },
497- {
498- "include": "#interpolated_error"
499- }
500- ]
501- },
502- "flow_control": {
503- "begin": "(for|if|else if|else|each|until|while|unless|case)(\\s+|$)",
504- "captures": {
505- "1": {
506- "name": "storage.type.function.jade"
507- }
508- },
509- "comment": "Jade control flow.",
510- "end": "$",
511- "name": "meta.control.flow.jade",
512- "patterns": [
513- {
514- "begin": "",
515- "end": "$",
516- "name": "js.embedded.control.flow.jade",
517- "patterns": [
518- {
519- "include": "source.js"
520- }
521- ]
522- }
523- ]
524- },
525- "html_entity": {
526- "patterns": [
527- {
528- "match": "(&)([a-zA-Z0-9]+|#[0-9]+|#x[0-9a-fA-F]+)(;)",
529- "name": "constant.character.entity.html.text.jade"
530- },
531- {
532- "match": "[<>&]",
533- "name": "invalid.illegal.html_entity.text.jade"
534- }
535- ]
536- },
537- "inline_jade": {
538- "begin": "(?<!\\\\)(#\\[)",
539- "captures": {
540- "1": {
541- "name": "entity.name.function.jade"
542- },
543- "2": {
544- "name": "entity.name.function.jade"
545- }
546- },
547- "end": "(\\])",
548- "name": "inline.jade",
549- "patterns": [
550- {
551- "include": "#inline_jade"
552- },
553- {
554- "include": "#mixin_call"
555- },
556- {
557- "begin": "(?<!\\])(?=[\\w.#])|(:\\s*)",
558- "end": "(?=\\]|(:.)|=|\\s)",
559- "name": "tag.inline.jade",
560- "patterns": [
561- {
562- "include": "#tag_name"
563- },
564- {
565- "include": "#tag_id"
566- },
567- {
568- "include": "#tag_classes"
569- },
570- {
571- "include": "#tag_attributes"
572- },
573- {
574- "include": "#tag_mixin_attributes"
575- },
576- {
577- "include": "#inline_jade"
578- },
579- {
580- "match": "\\[",
581- "name": "invalid.illegal.tag.jade"
582- }
583- ]
584- },
585- {
586- "include": "#unbuffered_code"
587- },
588- {
589- "include": "#printed_expression"
590- },
591- {
592- "match": "\\[",
593- "name": "invalid.illegal.tag.jade"
594- },
595- {
596- "include": "#inline_jade_text"
597- }
598- ]
599- },
600- "inline_jade_text": {
601- "begin": "",
602- "end": "(?=\\])",
603- "patterns": [
604- {
605- "begin": "\\[",
606- "end": "\\]",
607- "patterns": [
608- {
609- "include": "#inline_jade_text"
610- }
611- ]
612- },
613- {
614- "include": "#inline_jade"
615- },
616- {
617- "include": "#embedded_html"
618- },
619- {
620- "include": "#html_entity"
621- },
622- {
623- "include": "#interpolated_value"
624- },
625- {
626- "include": "#interpolated_error"
627- }
628- ]
629- },
630- "interpolated_error": {
631- "match": "(?<!\\\\)[#!]\\{(?=[^}]*$)",
632- "name": "invalid.illegal.tag.jade"
633- },
634- "interpolated_value": {
635- "begin": "(?<!\\\\)[#!]\\{(?=.*?\\})",
636- "end": "\\}",
637- "name": "string.interpolated.jade",
638- "patterns": [
639- {
640- "match": "{",
641- "name": "invalid.illegal.tag.jade"
642- },
643- {
644- "include": "source.js"
645- }
646- ]
647- },
648- "js_braces": {
649- "begin": "\\{",
650- "end": "\\}",
651- "patterns": [
652- {
653- "include": "#js_braces"
654- },
655- {
656- "include": "source.js"
657- }
658- ]
659- },
660- "js_brackets": {
661- "begin": "\\[",
662- "end": "\\]",
663- "patterns": [
664- {
665- "include": "#js_brackets"
666- },
667- {
668- "include": "source.js"
669- }
670- ]
671- },
672- "js_parens": {
673- "begin": "\\(",
674- "end": "\\)",
675- "patterns": [
676- {
677- "include": "#js_parens"
678- },
679- {
680- "include": "source.js"
681- }
682- ]
683- },
684- "mixin_call": {
685- "begin": "((?:mixin\\s+)|\\+)([\\w-]+)",
686- "beginCaptures": {
687- "1": {
688- "name": "storage.type.function.jade"
689- },
690- "2": {
691- "name": "meta.tag.other entity.name.function.jade"
692- }
693- },
694- "end": "(?!\\()|$",
695- "patterns": [
696- {
697- "begin": "(?<!\\))\\(",
698- "end": "\\)",
699- "name": "args.mixin.jade",
700- "patterns": [
701- {
702- "include": "#js_parens"
703- },
704- {
705- "include": "#string"
706- },
707- {
708- "captures": {
709- "1": {
710- "name": "meta.tag.other entity.other.attribute-name.tag.jade"
711- }
712- },
713- "match": "([^\\s(),=/]+)\\s*=\\s*"
714- },
715- {
716- "include": "source.js"
717- }
718- ]
719- },
720- {
721- "include": "#tag_attributes"
722- }
723- ]
724- },
725- "mixin_definition": {
726- "captures": {
727- "1": {
728- "name": "storage.type.function.jade"
729- },
730- "2": {
731- "name": "meta.tag.other entity.name.function.jade"
732- },
733- "3": {
734- "name": "punctuation.definition.parameters.begin.js"
735- },
736- "4": {
737- "name": "variable.parameter.function.js"
738- },
739- "5": {
740- "name": "punctuation.definition.parameters.begin.js"
741- }
742- },
743- "match": "(mixin\\s+)([\\w-]+)(?:(\\()\\s*((?:[a-zA-Z_]\\w*\\s*)(?:,\\s*[a-zA-Z_]\\w*\\s*)*)(\\)))?$"
744- },
745- "printed_expression": {
746- "begin": "(!?\\=)\\s*",
747- "captures": {
748- "1": {
749- "name": "constant"
750- }
751- },
752- "end": "(?=\\])|$",
753- "name": "source.js",
754- "patterns": [
755- {
756- "include": "#js_brackets"
757- },
758- {
759- "include": "source.js"
760- }
761- ]
762- },
763- "string": {
764- "begin": "(['\"])",
765- "end": "(?<!\\\\)\\1",
766- "name": "string.quoted.jade",
767- "patterns": [
768- {
769- "match": "\\\\((x[0-9a-fA-F]{2})|(u[0-9]{4})|.)",
770- "name": "constant.character.quoted.jade"
771- },
772- {
773- "include": "#interpolated_value"
774- },
775- {
776- "include": "#interpolated_error"
777- }
778- ]
779- },
780- "tag_attribute_name": {
781- "captures": {
782- "1": {
783- "name": "entity.other.attribute-name.tag.jade"
784- }
785- },
786- "match": "([^\\s(),=/!]+)\\s*"
787- },
788- "tag_attribute_name_paren": {
789- "begin": "\\(\\s*",
790- "end": "\\)",
791- "name": "entity.other.attribute-name.tag.jade",
792- "patterns": [
793- {
794- "include": "#tag_attribute_name_paren"
795- },
796- {
797- "include": "#tag_attribute_name"
798- }
799- ]
800- },
801- "tag_attributes": {
802- "begin": "(\\(\\s*)",
803- "captures": {
804- "1": {
805- "name": "constant.name.attribute.tag.jade"
806- }
807- },
808- "end": "(\\))",
809- "name": "meta.tag.other",
810- "patterns": [
811- {
812- "include": "#tag_attribute_name_paren"
813- },
814- {
815- "include": "#tag_attribute_name"
816- },
817- {
818- "match": "!(?!=)",
819- "name": "invalid.illegal.tag.jade"
820- },
821- {
822- "begin": "=\\s*",
823- "end": "$|(?=,|(?:\\s+[^!%&*-+~|<>:?/])|\\))",
824- "name": "attribute_value",
825- "patterns": [
826- {
827- "include": "#string"
828- },
829- {
830- "include": "#js_parens"
831- },
832- {
833- "include": "#js_brackets"
834- },
835- {
836- "include": "#js_braces"
837- },
838- {
839- "include": "source.js"
840- }
841- ]
842- },
843- {
844- "begin": "(?<=[%&*-+~|<>:?/])\\s+",
845- "end": "$|(?=,|(?:\\s+[^!%&*-+~|<>:?/])|\\))",
846- "name": "attribute_value2",
847- "patterns": [
848- {
849- "include": "#string"
850- },
851- {
852- "include": "#js_parens"
853- },
854- {
855- "include": "#js_brackets"
856- },
857- {
858- "include": "#js_braces"
859- },
860- {
861- "include": "source.js"
862- }
863- ]
864- }
865- ]
866- },
867- "tag_classes": {
868- "captures": {
869- "1": {
870- "name": "invalid.illegal.tag.jade"
871- }
872- },
873- "match": "\\.([^\\w-])?[\\w-]*",
874- "name": "constant.language.js"
875- },
876- "tag_id": {
877- "match": "#[\\w-]+",
878- "name": "constant.id.tag.jade"
879- },
880- "tag_mixin_attributes": {
881- "begin": "(&attributes\\()",
882- "captures": {
883- "1": {
884- "name": "entity.name.function.jade"
885- }
886- },
887- "end": "(\\))",
888- "name": "meta.tag.other",
889- "patterns": [
890- {
891- "match": "attributes(?=\\))",
892- "name": "storage.type.keyword.jade"
893- },
894- {
895- "include": "source.js"
896- }
897- ]
898- },
899- "tag_name": {
900- "begin": "([#!]\\{(?=.*?\\}))|(\\w(([\\w:-]+[\\w-])|([\\w-]*)))",
901- "end": "(\\G(?<!\\5[^\\w-]))|\\}|$",
902- "name": "meta.tag.other entity.name.tag.jade",
903- "patterns": [
904- {
905- "begin": "\\G(?<=\\{)",
906- "end": "(?=\\})",
907- "name": "meta.tag.other entity.name.tag.jade",
908- "patterns": [
909- {
910- "match": "{",
911- "name": "invalid.illegal.tag.jade"
912- },
913- {
914- "include": "source.js"
915- }
916- ]
917- }
918- ]
919- },
920- "tag_text": {
921- "begin": "(?=.)",
922- "end": "$",
923- "patterns": [
924- {
925- "include": "#inline_jade"
926- },
927- {
928- "include": "#embedded_html"
929- },
930- {
931- "include": "#html_entity"
932- },
933- {
934- "include": "#interpolated_value"
935- },
936- {
937- "include": "#interpolated_error"
938- }
939- ]
940- },
941- "unbuffered_code": {
942- "begin": "(-|(([a-zA-Z0-9_]+)\\s+=))",
943- "beginCaptures": {
944- "3": {
945- "name": "variable.parameter.javascript.embedded.jade"
946- }
947- },
948- "comment": "name = function() {}",
949- "end": "(?=\\])|$",
950- "name": "source.js",
951- "patterns": [
952- {
953- "include": "#js_brackets"
954- },
955- {
956- "include": "source.js"
957- }
958- ]
959- }
960- },
961- "scopeName": "text.jade",
962- "uuid": "eee6ba25-6ac2-4f7e-9c70-cddf2bd3448b",
963- "version": "https://github.com/davidrios/jade-tmbundle/commit/7c1304aa5a0d916a93fd296d3dd994219ecdc90f"
964-}
No newline at the end of the file
2+ "fileTypes": ["jade"],
3+ "name": "Jade",
4+ "patterns": [
5+ {
6+ "comment": "Doctype declaration.",
7+ "match": "^(!!!|doctype)(\\s*[a-zA-Z0-9-_]+)?",
8+ "name": "meta.tag.sgml.doctype.html"
9+ },
10+ {
11+ "begin": "^(\\s*)//-",
12+ "comment": "Unbuffered (jade-only) comments.",
13+ "end": "^(?!(\\1\\s)|\\s*$)",
14+ "name": "comment.unbuffered.block.jade"
15+ },
16+ {
17+ "begin": "^(\\s*)//",
18+ "comment": "Buffered (html) comments.",
19+ "end": "^(?!(\\1\\s)|\\s*$)",
20+ "name": "string.comment.buffered.block.jade",
21+ "patterns": [
22+ {
23+ "captures": {
24+ "1": {
25+ "name": "invalid.illegal.comment.comment.block.jade"
26+ }
27+ },
28+ "comment": "Buffered comments inside buffered comments will generate invalid html.",
29+ "match": "^\\s*(//)(?!-)",
30+ "name": "string.comment.buffered.block.jade"
31+ }
32+ ]
33+ },
34+ {
35+ "begin": "^(\\s*)-$",
36+ "comment": "Unbuffered code block.",
37+ "end": "^(?!(\\1\\s)|\\s*$)",
38+ "name": "source.js",
39+ "patterns": [
40+ {
41+ "include": "source.js"
42+ }
43+ ]
44+ },
45+ {
46+ "begin": "^(\\s*)(script)(?=[.#(\\s])((?![^\\n]*type=)|(?=[^\\n]*(text|application)/javascript))",
47+ "beginCaptures": {
48+ "2": {
49+ "name": "entity.name.tag.script.jade"
50+ }
51+ },
52+ "comment": "Script tag with JavaScript code.",
53+ "end": "^(?!(\\1\\s)|\\s*$)",
54+ "name": "meta.tag.other",
55+ "patterns": [
56+ {
57+ "begin": "\\G(?=\\()",
58+ "end": "$",
59+ "name": "stuff.tag.script.jade",
60+ "patterns": [
61+ {
62+ "include": "#tag_attributes"
63+ }
64+ ]
65+ },
66+ {
67+ "begin": "\\G(?=[.#])",
68+ "end": "$",
69+ "name": "stuff.tag.script.jade",
70+ "patterns": [
71+ {
72+ "include": "#complete_tag"
73+ }
74+ ]
75+ },
76+ {
77+ "include": "source.js"
78+ }
79+ ]
80+ },
81+ {
82+ "begin": "^(\\s*)(style)((\\.$)|(?=[.#(].*\\.$))",
83+ "beginCaptures": {
84+ "2": {
85+ "name": "entity.name.tag.script.jade"
86+ }
87+ },
88+ "comment": "Style tag with CSS code.",
89+ "end": "^(?!(\\1\\s)|\\s*$)",
90+ "name": "meta.tag.other",
91+ "patterns": [
92+ {
93+ "begin": "\\G(?=\\()",
94+ "end": "$",
95+ "name": "stuff.tag.style.jade",
96+ "patterns": [
97+ {
98+ "include": "#tag_attributes"
99+ }
100+ ]
101+ },
102+ {
103+ "begin": "\\G(?=[.#])",
104+ "end": "$",
105+ "name": "stuff.tag.style.jade",
106+ "patterns": [
107+ {
108+ "include": "#complete_tag"
109+ }
110+ ]
111+ },
112+ {
113+ "include": "source.css"
114+ }
115+ ]
116+ },
117+ {
118+ "begin": "^(\\s*):(sass)(?=\\(|$)",
119+ "beginCaptures": {
120+ "2": {
121+ "name": "constant.language.name.sass.filter.jade"
122+ }
123+ },
124+ "end": "^(?!(\\1\\s)|\\s*$)",
125+ "name": "source.sass.filter.jade",
126+ "patterns": [
127+ {
128+ "include": "#tag_attributes"
129+ },
130+ {
131+ "include": "source.sass"
132+ }
133+ ]
134+ },
135+ {
136+ "begin": "^(\\s*):(less)(?=\\(|$)",
137+ "beginCaptures": {
138+ "2": {
139+ "name": "constant.language.name.less.filter.jade"
140+ }
141+ },
142+ "end": "^(?!(\\1\\s)|\\s*$)",
143+ "name": "source.less.filter.jade",
144+ "patterns": [
145+ {
146+ "include": "#tag_attributes"
147+ },
148+ {
149+ "include": "source.less"
150+ }
151+ ]
152+ },
153+ {
154+ "begin": "^(\\s*):(stylus)(?=\\(|$)",
155+ "beginCaptures": {
156+ "2": {
157+ "name": "constant.language.name.stylus.filter.jade"
158+ }
159+ },
160+ "end": "^(?!(\\1\\s)|\\s*$)",
161+ "patterns": [
162+ {
163+ "include": "#tag_attributes"
164+ },
165+ {
166+ "include": "source.stylus"
167+ }
168+ ]
169+ },
170+ {
171+ "begin": "^(\\s*):(coffee(-?script)?)(?=\\(|$)",
172+ "beginCaptures": {
173+ "2": {
174+ "name": "constant.language.name.coffeescript.filter.jade"
175+ }
176+ },
177+ "end": "^(?!(\\1\\s)|\\s*$)",
178+ "name": "source.coffeescript.filter.jade",
179+ "patterns": [
180+ {
181+ "include": "#tag_attributes"
182+ },
183+ {
184+ "include": "source.coffee"
185+ }
186+ ]
187+ },
188+ {
189+ "begin": "^(\\s*)((:(?=.))|(:$))",
190+ "beginCaptures": {
191+ "4": {
192+ "name": "invalid.illegal.empty.generic.filter.jade"
193+ }
194+ },
195+ "comment": "Generic Jade filter.",
196+ "end": "^(?!(\\1\\s)|\\s*$)",
197+ "patterns": [
198+ {
199+ "begin": "\\G(?<=:)(?=.)",
200+ "end": "$",
201+ "name": "name.generic.filter.jade",
202+ "patterns": [
203+ {
204+ "match": "\\G\\(",
205+ "name": "invalid.illegal.name.generic.filter.jade"
206+ },
207+ {
208+ "match": "[\\w-]",
209+ "name": "constant.language.name.generic.filter.jade"
210+ },
211+ {
212+ "include": "#tag_attributes"
213+ },
214+ {
215+ "match": "\\W",
216+ "name": "invalid.illegal.name.generic.filter.jade"
217+ }
218+ ]
219+ }
220+ ]
221+ },
222+ {
223+ "begin": "^(\\s*)(?=[\\w.#].*?\\.$)(?=(?:(?:(?:(?:(?:#[\\w-]+)|(?:\\.[\\w-]+))|(?:(?:[#!]\\{[^}]*\\})|(?:\\w(?:(?:[\\w:-]+[\\w-])|(?:[\\w-]*)))))(?:(?:#[\\w-]+)|(?:\\.[\\w-]+)|(?:\\((?:[^()\\'\\\"]*(?:(?:\\'(?:[^\\']|(?:(?<!\\\\)\\\\\\'))*\\')|(?:\\\"(?:[^\\\"]|(?:(?<!\\\\)\\\\\\\"))*\\\")))*[^()]*\\))*)*)(?:(?:(?::\\s+)|(?<=\\)))(?:(?:(?:(?:#[\\w-]+)|(?:\\.[\\w-]+))|(?:(?:[#!]\\{[^}]*\\})|(?:\\w(?:(?:[\\w:-]+[\\w-])|(?:[\\w-]*)))))(?:(?:#[\\w-]+)|(?:\\.[\\w-]+)|(?:\\((?:[^()\\'\\\"]*(?:(?:\\'(?:[^\\']|(?:(?<!\\\\)\\\\\\'))*\\')|(?:\\\"(?:[^\\\"]|(?:(?<!\\\\)\\\\\\\"))*\\\")))*[^()]*\\))*)*))*)\\.$)(?:(?:(#[\\w-]+)|(\\.[\\w-]+))|((?:[#!]\\{[^}]*\\})|(?:\\w(?:(?:[\\w:-]+[\\w-])|(?:[\\w-]*)))))",
224+ "beginCaptures": {
225+ "2": {
226+ "name": "constant.id.tag.jade"
227+ },
228+ "3": {
229+ "name": "constant.language.js"
230+ },
231+ "4": {
232+ "name": "meta.tag.other entity.name.tag.jade"
233+ }
234+ },
235+ "comment": "Generated from dot_block_tag.py",
236+ "end": "^(?!(\\1\\s)|\\s*$)",
237+ "patterns": [
238+ {
239+ "include": "#tag_attributes"
240+ },
241+ {
242+ "include": "#complete_tag"
243+ },
244+ {
245+ "begin": "^(?=.)",
246+ "end": "$",
247+ "name": "text.block.jade",
248+ "patterns": [
249+ {
250+ "include": "#inline_jade"
251+ },
252+ {
253+ "include": "#embedded_html"
254+ },
255+ {
256+ "include": "#html_entity"
257+ },
258+ {
259+ "include": "#interpolated_value"
260+ },
261+ {
262+ "include": "#interpolated_error"
263+ }
264+ ]
265+ }
266+ ]
267+ },
268+ {
269+ "begin": "^\\s*",
270+ "comment": "All constructs that generally span a single line starting with any number of white-spaces.",
271+ "end": "$",
272+ "patterns": [
273+ {
274+ "include": "#inline_jade"
275+ },
276+ {
277+ "include": "#blocks_and_includes"
278+ },
279+ {
280+ "include": "#unbuffered_code"
281+ },
282+ {
283+ "include": "#mixin_definition"
284+ },
285+ {
286+ "include": "#mixin_call"
287+ },
288+ {
289+ "include": "#flow_control"
290+ },
291+ {
292+ "include": "#case_conds"
293+ },
294+ {
295+ "begin": "\\|",
296+ "comment": "Tag pipe text line.",
297+ "end": "$",
298+ "name": "text.block.pipe.jade",
299+ "patterns": [
300+ {
301+ "include": "#inline_jade"
302+ },
303+ {
304+ "include": "#embedded_html"
305+ },
306+ {
307+ "include": "#html_entity"
308+ },
309+ {
310+ "include": "#interpolated_value"
311+ },
312+ {
313+ "include": "#interpolated_error"
314+ }
315+ ]
316+ },
317+ {
318+ "include": "#printed_expression"
319+ },
320+ {
321+ "begin": "\\G(?=(#[^\\{\\w-])|[^\\w.#])",
322+ "comment": "Line starting with characters incompatible with tag name/id/class is standalone text.",
323+ "end": "$",
324+ "patterns": [
325+ {
326+ "begin": "</?(?=[!#])",
327+ "end": ">|$",
328+ "patterns": [
329+ {
330+ "include": "#inline_jade"
331+ },
332+ {
333+ "include": "#interpolated_value"
334+ },
335+ {
336+ "include": "#interpolated_error"
337+ }
338+ ]
339+ },
340+ {
341+ "include": "#inline_jade"
342+ },
343+ {
344+ "include": "#embedded_html"
345+ },
346+ {
347+ "include": "#html_entity"
348+ },
349+ {
350+ "include": "#interpolated_value"
351+ },
352+ {
353+ "include": "#interpolated_error"
354+ }
355+ ]
356+ },
357+ {
358+ "include": "#complete_tag"
359+ }
360+ ]
361+ }
362+ ],
363+ "repository": {
364+ "blocks_and_includes": {
365+ "captures": {
366+ "1": {
367+ "name": "storage.type.import.include.jade"
368+ },
369+ "4": {
370+ "name": "variable.control.import.include.jade"
371+ }
372+ },
373+ "comment": "Template blocks and includes.",
374+ "match": "(extends|include|yield|append|prepend|block( (append|prepend))?)\\s+(.*)$",
375+ "name": "meta.first-class.jade"
376+ },
377+ "case_conds": {
378+ "begin": "(default|when)((\\s+|(?=:))|$)",
379+ "captures": {
380+ "1": {
381+ "name": "storage.type.function.jade"
382+ }
383+ },
384+ "comment": "Jade case conditionals.",
385+ "end": "$",
386+ "name": "meta.control.flow.jade",
387+ "patterns": [
388+ {
389+ "begin": "\\G(?!:)",
390+ "end": "(?=:\\s+)|$",
391+ "name": "js.embedded.control.flow.jade",
392+ "patterns": [
393+ {
394+ "include": "#case_when_paren"
395+ },
396+ {
397+ "include": "source.js"
398+ }
399+ ]
400+ },
401+ {
402+ "begin": ":\\s+",
403+ "end": "$",
404+ "name": "tag.case.control.flow.jade",
405+ "patterns": [
406+ {
407+ "include": "#complete_tag"
408+ }
409+ ]
410+ }
411+ ]
412+ },
413+ "case_when_paren": {
414+ "begin": "\\(",
415+ "end": "\\)",
416+ "name": "js.when.control.flow.jade",
417+ "patterns": [
418+ {
419+ "include": "#case_when_paren"
420+ },
421+ {
422+ "match": ":",
423+ "name": "invalid.illegal.name.tag.jade"
424+ },
425+ {
426+ "include": "source.js"
427+ }
428+ ]
429+ },
430+ "complete_tag": {
431+ "begin": "(?=[\\w.#])|(:\\s*)",
432+ "end": "(\\.?$)|(?=:.)",
433+ "patterns": [
434+ {
435+ "include": "#blocks_and_includes"
436+ },
437+ {
438+ "include": "#unbuffered_code"
439+ },
440+ {
441+ "include": "#mixin_call"
442+ },
443+ {
444+ "include": "#flow_control"
445+ },
446+ {
447+ "match": "(?<=:)\\w.*$",
448+ "name": "invalid.illegal.name.tag.jade"
449+ },
450+ {
451+ "include": "#tag_name"
452+ },
453+ {
454+ "include": "#tag_id"
455+ },
456+ {
457+ "include": "#tag_classes"
458+ },
459+ {
460+ "include": "#tag_attributes"
461+ },
462+ {
463+ "include": "#tag_mixin_attributes"
464+ },
465+ {
466+ "captures": {
467+ "2": {
468+ "name": "invalid.illegal.end.tag.jade"
469+ },
470+ "4": {
471+ "name": "invalid.illegal.end.tag.jade"
472+ }
473+ },
474+ "match": "((\\.)\\s+$)|((:)\\s*$)"
475+ },
476+ {
477+ "include": "#printed_expression"
478+ },
479+ {
480+ "include": "#tag_text"
481+ }
482+ ]
483+ },
484+ "embedded_html": {
485+ "begin": "(?=<[^>]*>)",
486+ "end": "$|(?=>)",
487+ "name": "html",
488+ "patterns": [
489+ {
490+ "include": "text.html.basic"
491+ },
492+ {
493+ "include": "#interpolated_value"
494+ },
495+ {
496+ "include": "#interpolated_error"
497+ }
498+ ]
499+ },
500+ "flow_control": {
501+ "begin": "(for|if|else if|else|each|until|while|unless|case)(\\s+|$)",
502+ "captures": {
503+ "1": {
504+ "name": "storage.type.function.jade"
505+ }
506+ },
507+ "comment": "Jade control flow.",
508+ "end": "$",
509+ "name": "meta.control.flow.jade",
510+ "patterns": [
511+ {
512+ "begin": "",
513+ "end": "$",
514+ "name": "js.embedded.control.flow.jade",
515+ "patterns": [
516+ {
517+ "include": "source.js"
518+ }
519+ ]
520+ }
521+ ]
522+ },
523+ "html_entity": {
524+ "patterns": [
525+ {
526+ "match": "(&)([a-zA-Z0-9]+|#[0-9]+|#x[0-9a-fA-F]+)(;)",
527+ "name": "constant.character.entity.html.text.jade"
528+ },
529+ {
530+ "match": "[<>&]",
531+ "name": "invalid.illegal.html_entity.text.jade"
532+ }
533+ ]
534+ },
535+ "inline_jade": {
536+ "begin": "(?<!\\\\)(#\\[)",
537+ "captures": {
538+ "1": {
539+ "name": "entity.name.function.jade"
540+ },
541+ "2": {
542+ "name": "entity.name.function.jade"
543+ }
544+ },
545+ "end": "(\\])",
546+ "name": "inline.jade",
547+ "patterns": [
548+ {
549+ "include": "#inline_jade"
550+ },
551+ {
552+ "include": "#mixin_call"
553+ },
554+ {
555+ "begin": "(?<!\\])(?=[\\w.#])|(:\\s*)",
556+ "end": "(?=\\]|(:.)|=|\\s)",
557+ "name": "tag.inline.jade",
558+ "patterns": [
559+ {
560+ "include": "#tag_name"
561+ },
562+ {
563+ "include": "#tag_id"
564+ },
565+ {
566+ "include": "#tag_classes"
567+ },
568+ {
569+ "include": "#tag_attributes"
570+ },
571+ {
572+ "include": "#tag_mixin_attributes"
573+ },
574+ {
575+ "include": "#inline_jade"
576+ },
577+ {
578+ "match": "\\[",
579+ "name": "invalid.illegal.tag.jade"
580+ }
581+ ]
582+ },
583+ {
584+ "include": "#unbuffered_code"
585+ },
586+ {
587+ "include": "#printed_expression"
588+ },
589+ {
590+ "match": "\\[",
591+ "name": "invalid.illegal.tag.jade"
592+ },
593+ {
594+ "include": "#inline_jade_text"
595+ }
596+ ]
597+ },
598+ "inline_jade_text": {
599+ "begin": "",
600+ "end": "(?=\\])",
601+ "patterns": [
602+ {
603+ "begin": "\\[",
604+ "end": "\\]",
605+ "patterns": [
606+ {
607+ "include": "#inline_jade_text"
608+ }
609+ ]
610+ },
611+ {
612+ "include": "#inline_jade"
613+ },
614+ {
615+ "include": "#embedded_html"
616+ },
617+ {
618+ "include": "#html_entity"
619+ },
620+ {
621+ "include": "#interpolated_value"
622+ },
623+ {
624+ "include": "#interpolated_error"
625+ }
626+ ]
627+ },
628+ "interpolated_error": {
629+ "match": "(?<!\\\\)[#!]\\{(?=[^}]*$)",
630+ "name": "invalid.illegal.tag.jade"
631+ },
632+ "interpolated_value": {
633+ "begin": "(?<!\\\\)[#!]\\{(?=.*?\\})",
634+ "end": "\\}",
635+ "name": "string.interpolated.jade",
636+ "patterns": [
637+ {
638+ "match": "{",
639+ "name": "invalid.illegal.tag.jade"
640+ },
641+ {
642+ "include": "source.js"
643+ }
644+ ]
645+ },
646+ "js_braces": {
647+ "begin": "\\{",
648+ "end": "\\}",
649+ "patterns": [
650+ {
651+ "include": "#js_braces"
652+ },
653+ {
654+ "include": "source.js"
655+ }
656+ ]
657+ },
658+ "js_brackets": {
659+ "begin": "\\[",
660+ "end": "\\]",
661+ "patterns": [
662+ {
663+ "include": "#js_brackets"
664+ },
665+ {
666+ "include": "source.js"
667+ }
668+ ]
669+ },
670+ "js_parens": {
671+ "begin": "\\(",
672+ "end": "\\)",
673+ "patterns": [
674+ {
675+ "include": "#js_parens"
676+ },
677+ {
678+ "include": "source.js"
679+ }
680+ ]
681+ },
682+ "mixin_call": {
683+ "begin": "((?:mixin\\s+)|\\+)([\\w-]+)",
684+ "beginCaptures": {
685+ "1": {
686+ "name": "storage.type.function.jade"
687+ },
688+ "2": {
689+ "name": "meta.tag.other entity.name.function.jade"
690+ }
691+ },
692+ "end": "(?!\\()|$",
693+ "patterns": [
694+ {
695+ "begin": "(?<!\\))\\(",
696+ "end": "\\)",
697+ "name": "args.mixin.jade",
698+ "patterns": [
699+ {
700+ "include": "#js_parens"
701+ },
702+ {
703+ "include": "#string"
704+ },
705+ {
706+ "captures": {
707+ "1": {
708+ "name": "meta.tag.other entity.other.attribute-name.tag.jade"
709+ }
710+ },
711+ "match": "([^\\s(),=/]+)\\s*=\\s*"
712+ },
713+ {
714+ "include": "source.js"
715+ }
716+ ]
717+ },
718+ {
719+ "include": "#tag_attributes"
720+ }
721+ ]
722+ },
723+ "mixin_definition": {
724+ "captures": {
725+ "1": {
726+ "name": "storage.type.function.jade"
727+ },
728+ "2": {
729+ "name": "meta.tag.other entity.name.function.jade"
730+ },
731+ "3": {
732+ "name": "punctuation.definition.parameters.begin.js"
733+ },
734+ "4": {
735+ "name": "variable.parameter.function.js"
736+ },
737+ "5": {
738+ "name": "punctuation.definition.parameters.begin.js"
739+ }
740+ },
741+ "match": "(mixin\\s+)([\\w-]+)(?:(\\()\\s*((?:[a-zA-Z_]\\w*\\s*)(?:,\\s*[a-zA-Z_]\\w*\\s*)*)(\\)))?$"
742+ },
743+ "printed_expression": {
744+ "begin": "(!?\\=)\\s*",
745+ "captures": {
746+ "1": {
747+ "name": "constant"
748+ }
749+ },
750+ "end": "(?=\\])|$",
751+ "name": "source.js",
752+ "patterns": [
753+ {
754+ "include": "#js_brackets"
755+ },
756+ {
757+ "include": "source.js"
758+ }
759+ ]
760+ },
761+ "string": {
762+ "begin": "(['\"])",
763+ "end": "(?<!\\\\)\\1",
764+ "name": "string.quoted.jade",
765+ "patterns": [
766+ {
767+ "match": "\\\\((x[0-9a-fA-F]{2})|(u[0-9]{4})|.)",
768+ "name": "constant.character.quoted.jade"
769+ },
770+ {
771+ "include": "#interpolated_value"
772+ },
773+ {
774+ "include": "#interpolated_error"
775+ }
776+ ]
777+ },
778+ "tag_attribute_name": {
779+ "captures": {
780+ "1": {
781+ "name": "entity.other.attribute-name.tag.jade"
782+ }
783+ },
784+ "match": "([^\\s(),=/!]+)\\s*"
785+ },
786+ "tag_attribute_name_paren": {
787+ "begin": "\\(\\s*",
788+ "end": "\\)",
789+ "name": "entity.other.attribute-name.tag.jade",
790+ "patterns": [
791+ {
792+ "include": "#tag_attribute_name_paren"
793+ },
794+ {
795+ "include": "#tag_attribute_name"
796+ }
797+ ]
798+ },
799+ "tag_attributes": {
800+ "begin": "(\\(\\s*)",
801+ "captures": {
802+ "1": {
803+ "name": "constant.name.attribute.tag.jade"
804+ }
805+ },
806+ "end": "(\\))",
807+ "name": "meta.tag.other",
808+ "patterns": [
809+ {
810+ "include": "#tag_attribute_name_paren"
811+ },
812+ {
813+ "include": "#tag_attribute_name"
814+ },
815+ {
816+ "match": "!(?!=)",
817+ "name": "invalid.illegal.tag.jade"
818+ },
819+ {
820+ "begin": "=\\s*",
821+ "end": "$|(?=,|(?:\\s+[^!%&*-+~|<>:?/])|\\))",
822+ "name": "attribute_value",
823+ "patterns": [
824+ {
825+ "include": "#string"
826+ },
827+ {
828+ "include": "#js_parens"
829+ },
830+ {
831+ "include": "#js_brackets"
832+ },
833+ {
834+ "include": "#js_braces"
835+ },
836+ {
837+ "include": "source.js"
838+ }
839+ ]
840+ },
841+ {
842+ "begin": "(?<=[%&*-+~|<>:?/])\\s+",
843+ "end": "$|(?=,|(?:\\s+[^!%&*-+~|<>:?/])|\\))",
844+ "name": "attribute_value2",
845+ "patterns": [
846+ {
847+ "include": "#string"
848+ },
849+ {
850+ "include": "#js_parens"
851+ },
852+ {
853+ "include": "#js_brackets"
854+ },
855+ {
856+ "include": "#js_braces"
857+ },
858+ {
859+ "include": "source.js"
860+ }
861+ ]
862+ }
863+ ]
864+ },
865+ "tag_classes": {
866+ "captures": {
867+ "1": {
868+ "name": "invalid.illegal.tag.jade"
869+ }
870+ },
871+ "match": "\\.([^\\w-])?[\\w-]*",
872+ "name": "constant.language.js"
873+ },
874+ "tag_id": {
875+ "match": "#[\\w-]+",
876+ "name": "constant.id.tag.jade"
877+ },
878+ "tag_mixin_attributes": {
879+ "begin": "(&attributes\\()",
880+ "captures": {
881+ "1": {
882+ "name": "entity.name.function.jade"
883+ }
884+ },
885+ "end": "(\\))",
886+ "name": "meta.tag.other",
887+ "patterns": [
888+ {
889+ "match": "attributes(?=\\))",
890+ "name": "storage.type.keyword.jade"
891+ },
892+ {
893+ "include": "source.js"
894+ }
895+ ]
896+ },
897+ "tag_name": {
898+ "begin": "([#!]\\{(?=.*?\\}))|(\\w(([\\w:-]+[\\w-])|([\\w-]*)))",
899+ "end": "(\\G(?<!\\5[^\\w-]))|\\}|$",
900+ "name": "meta.tag.other entity.name.tag.jade",
901+ "patterns": [
902+ {
903+ "begin": "\\G(?<=\\{)",
904+ "end": "(?=\\})",
905+ "name": "meta.tag.other entity.name.tag.jade",
906+ "patterns": [
907+ {
908+ "match": "{",
909+ "name": "invalid.illegal.tag.jade"
910+ },
911+ {
912+ "include": "source.js"
913+ }
914+ ]
915+ }
916+ ]
917+ },
918+ "tag_text": {
919+ "begin": "(?=.)",
920+ "end": "$",
921+ "patterns": [
922+ {
923+ "include": "#inline_jade"
924+ },
925+ {
926+ "include": "#embedded_html"
927+ },
928+ {
929+ "include": "#html_entity"
930+ },
931+ {
932+ "include": "#interpolated_value"
933+ },
934+ {
935+ "include": "#interpolated_error"
936+ }
937+ ]
938+ },
939+ "unbuffered_code": {
940+ "begin": "(-|(([a-zA-Z0-9_]+)\\s+=))",
941+ "beginCaptures": {
942+ "3": {
943+ "name": "variable.parameter.javascript.embedded.jade"
944+ }
945+ },
946+ "comment": "name = function() {}",
947+ "end": "(?=\\])|$",
948+ "name": "source.js",
949+ "patterns": [
950+ {
951+ "include": "#js_brackets"
952+ },
953+ {
954+ "include": "source.js"
955+ }
956+ ]
957+ }
958+ },
959+ "scopeName": "text.jade",
960+ "uuid": "eee6ba25-6ac2-4f7e-9c70-cddf2bd3448b",
961+ "version": "https://github.com/davidrios/jade-tmbundle/commit/7c1304aa5a0d916a93fd296d3dd994219ecdc90f"
962+}
modified extensions/vscode/textmate-syntaxes/JavaScript.tmLanguage.json +3571 −3574

The diff of this file is cut short. View the file.

@@ -1,3575 +1,1426 @@
11 {
2- "name": "JavaScript (with React support)",
3- "scopeName": "source.js",
4- "fileTypes": [
5- ".js",
6- ".jsx"
7- ],
8- "uuid": "805375ec-d614-41f5-8993-5843fe63ea82",
9- "patterns": [
10- {
11- "include": "#directives"
12- },
13- {
14- "include": "#statements"
15- },
16- {
17- "name": "comment.line.shebang.ts",
18- "match": "\\A(#!).*(?=$)",
19- "captures": {
20- "1": {
21- "name": "punctuation.definition.comment.ts"
22- }
23- }
24- }
25- ],
26- "repository": {
27- "statements": {
28- "patterns": [
29- {
30- "include": "#string"
31- },
32- {
33- "include": "#template"
34- },
35- {
36- "include": "#comment"
37- },
38- {
39- "include": "#literal"
40- },
41- {
42- "include": "#declaration"
43- },
44- {
45- "include": "#switch-statement"
46- },
47- {
48- "include": "#for-loop"
49- },
50- {
51- "include": "#after-operator-block"
52- },
53- {
54- "include": "#decl-block"
55- },
56- {
57- "include": "#control-statement"
58- },
59- {
60- "include": "#expression"
61- },
62- {
63- "include": "#punctuation-semicolon"
64- }
65- ]
66- },
67- "var-expr": {
68- "name": "meta.var.expr.js",
69- "begin": "(?<!\\.|\\$)(?:(\\bexport)\\s+)?\\b(var|let|const(?!\\s+enum\\b))\\b(?!\\$)",
70- "beginCaptures": {
71- "1": {
72- "name": "keyword.control.export.js"
73- },
74- "2": {
75- "name": "storage.type.js"
76- }
77- },
78- "end": "(?=$|;|}|(\\s+(of|in)\\s+))",
79- "patterns": [
80- {
81- "include": "#destructuring-variable"
82- },
83- {
84- "include": "#var-single-variable"
85- },
86- {
87- "include": "#variable-initializer"
88- },
89- {
90- "include": "#comment"
91- },
92- {
93- "include": "#punctuation-comma"
94- }
95- ]
96- },
97- "var-single-variable": {
98- "patterns": [
99- {
100- "name": "meta.var-single-variable.expr.js",
101- "begin": "(?x)([_$[:alpha:]][_$[:alnum:]]*)(?=\\s* (=\\s*( (async\\s+) | (function\\s*[(<]) | (function\\s+) | ([_$[:alpha:]][_$[:alnum:]]*\\s*=>) | ((<([^<>]|\\<[^<>]+\\>)+>\\s*)?\\(([^()]|\\([^()]*\\))*\\)(\\s*:\\s*(.)*)?\\s*=>)) ) | (:\\s*( (<) | ([(]\\s*( ([)]) | (\\.\\.\\.) | ([_$[:alnum:]]+\\s*( ([:,?=])| ([)]\\s*=>) )) ))) ))",
102- "beginCaptures": {
103- "1": {
104- "name": "entity.name.function.js"
105- }
106- },
107- "end": "(?=$|[;,=}]|(\\s+(of|in)\\s+))",
108- "patterns": [
109- {
110- "include": "#type-annotation"
111- },
112- {
113- "include": "#string"
114- },
115- {
116- "include": "#comment"
117- }
118- ]
119- },
120- {
121- "name": "meta.var-single-variable.expr.js",
122- "begin": "([_$[:alpha:]][_$[:alnum:]]*)",
123- "beginCaptures": {
124- "1": {
125- "name": "variable.other.readwrite.js"
126- }
127- },
128- "end": "(?=$|[;,=}]|(\\s+(of|in)\\s+))",
129- "patterns": [
130- {
131- "include": "#type-annotation"
132- },
133- {
134- "include": "#string"
135- },
136- {
137- "include": "#comment"
138- }
139- ]
140- }
141- ]
142- },
143- "destructuring-variable": {
144- "patterns": [
145- {
146- "name": "meta.object-binding-pattern-variable.js",
147- "begin": "(?<!=|:|of|in)\\s*(?=\\{)",
148- "end": "(?=$|[;,=}]|(\\s+(of|in)\\s+))",
149- "patterns": [
150- {
151- "include": "#object-binding-pattern"
152- },
153- {
154- "include": "#type-annotation"
155- },
156- {
157- "include": "#comment"
158- }
159- ]
160- },
161- {
162- "name": "meta.array-binding-pattern-variable.js",
163- "begin": "(?<!=|:|of|in)\\s*(?=\\[)",
164- "end": "(?=$|[;,=}]|(\\s+(of|in)\\s+))",
165- "patterns": [
166- {
167- "include": "#array-binding-pattern"
168- },
169- {
170- "include": "#type-annotation"
171- },
172- {
173- "include": "#comment"
174- }
175- ]
176- }
177- ]
178- },
179- "object-binding-element": {
180- "patterns": [
181- {
182- "include": "#comment"
183- },
184- {
185- "begin": "(?=(([_$[:alpha:]][_$[:alnum:]]*)|(\\'[^']*\\')|(\\\"[^\"]*\\\")|(\\[([^\\[\\]]|\\[[^\\[\\]]+\\])+\\]))\\s*(:))",
186- "end": "(?=,|\\})",
187- "patterns": [
188- {
189- "include": "#object-binding-element-propertyName"
190- },
191- {
192- "include": "#binding-element"
193- }
194- ]
195- },
196- {
197- "include": "#object-binding-pattern"
198- },
199- {
200- "include": "#destructuring-variable-rest"
201- },
202- {
203- "include": "#variable-initializer"
204- },
205- {
206- "include": "#punctuation-comma"
207- }
208- ]
209- },
210- "object-binding-element-propertyName": {
211- "begin": "(?=(([_$[:alpha:]][_$[:alnum:]]*)|(\\'[^']*\\')|(\\\"[^\"]*\\\")|(\\[([^\\[\\]]|\\[[^\\[\\]]+\\])+\\]))\\s*(:))",
212- "end": "(:)",
213- "endCaptures": {
214- "0": {
215- "name": "punctuation.destructuring.js"
216- }
217- },
218- "patterns": [
219- {
220- "include": "#string"
221- },
222- {
223- "include": "#array-literal"
224- },
225- {
226- "name": "variable.object.property.js",
227- "match": "([_$[:alpha:]][_$[:alnum:]]*)"
228- }
229- ]
230- },
231- "binding-element": {
232- "patterns": [
233- {
234- "include": "#comment"
235- },
236- {
237- "include": "#object-binding-pattern"
238- },
239- {
240- "include": "#array-binding-pattern"
241- },
242- {
243- "include": "#destructuring-variable-rest"
244- },
245- {
246- "include": "#variable-initializer"
247- }
248- ]
249- },
250- "destructuring-variable-rest": {
251- "match": "(?:(\\.\\.\\.)\\s*)?([_$[:alpha:]][_$[:alnum:]]*)",
252- "captures": {
253- "1": {
254- "name": "keyword.operator.rest.js"
255- },
256- "2": {
257- "name": "variable.other.readwrite.js"
258- }
259- }
260- },
261- "object-binding-pattern": {
262- "begin": "(?:(\\.\\.\\.)\\s*)?(\\{)",
263- "beginCaptures": {
264- "1": {
265- "name": "keyword.operator.rest.js"
266- },
267- "2": {
268- "name": "punctuation.definition.binding-pattern.object.js"
269- }
270- },
271- "end": "\\}",
272- "endCaptures": {
273- "0": {
274- "name": "punctuation.definition.binding-pattern.object.js"
275- }
276- },
277- "patterns": [
278- {
279- "include": "#object-binding-element"
280- }
281- ]
282- },
283- "array-binding-pattern": {
284- "begin": "(?:(\\.\\.\\.)\\s*)?(\\[)",
285- "beginCaptures": {
286- "1": {
287- "name": "keyword.operator.rest.js"
288- },
289- "2": {
290- "name": "punctuation.definition.binding-pattern.array.js"
291- }
292- },
293- "end": "\\]",
294- "endCaptures": {
295- "0": {
296- "name": "punctuation.definition.binding-pattern.array.js"
297- }
298- },
299- "patterns": [
300- {
301- "include": "#binding-element"
302- },
303- {
304- "include": "#punctuation-comma"
305- }
306- ]
307- },
308- "ternary-expression": {
309- "begin": "(?=\\?)",
310- "end": "(?=$|[;,})\\]])",
311- "patterns": [
312- {
313- "include": "#ternary-operator"
314- },
315- {
316- "include": "#expression"
317- }
318- ]
319- },
320- "ternary-operator": {
321- "begin": "(\\?)",
322- "beginCaptures": {
323- "0": {
324- "name": "keyword.operator.ternary.js"
325- }
326- },
327- "end": "(:)",
328- "endCaptures": {
329- "0": {
330- "name": "keyword.operator.ternary.js"
331- }
332- },
333- "patterns": [
334- {
335- "include": "#expression"
336- }
337- ]
338- },
339- "expression": {
340- "name": "meta.expression.js",
341- "patterns": [
342- {
343- "include": "#jsx"
344- },
345- {
346- "include": "#string"
347- },
348- {
349- "include": "#regex"
350- },
351- {
352- "include": "#template"
353- },
354- {
355- "include": "#comment"
356- },
357- {
358- "include": "#literal"
359- },
360- {
361- "include": "#function-declaration"
362- },
363- {
364- "include": "#class-or-interface-declaration"
365- },
366- {
367- "include": "#arrow-function"
368- },
369- {
370- "include": "#cast"
371- },
372- {
373- "include": "#ternary-expression"
374- },
375- {
376- "include": "#new-expr"
377- },
378- {
379- "include": "#object-literal"
380- },
381- {
382- "include": "#expression-operators"
383- },
384- {
385- "include": "#function-call"
386- },
387- {
388- "include": "#support-objects"
389- },
390- {
391- "include": "#identifiers"
392- },
393- {
394- "include": "#paren-expression"
395- },
396- {
397- "include": "#punctuation-comma"
398- },
399- {
400- "include": "#punctuation-accessor"
401- }
402- ]
403- },
404- "control-statement": {
405- "patterns": [
406- {
407- "name": "keyword.control.trycatch.js",
408- "match": "(?<!\\.|\\$)\\b(catch|finally|throw|try)\\b(?!\\$)"
409- },
410- {
411- "name": "keyword.control.loop.js",
412- "match": "(?<!\\.|\\$)\\b(break|continue|do|goto|while)\\b(?!\\$)"
413- },
414- {
415- "name": "keyword.control.flow.js",
416- "match": "(?<!\\.|\\$)\\b(return)\\b(?!\\$)"
417- },
418- {
419- "match": "(?<!\\.|\\$)\\b(yield)\\b(?!\\$)(?:\\s*(\\*))?",
420- "captures": {
421- "1": {
422- "name": "keyword.control.flow.js"
423- },
424- "2": {
425- "name": "keyword.generator.asterisk.js"
426- }
427- }
428- },
429- {
430- "name": "keyword.control.switch.js",
431- "match": "(?<!\\.|\\$)\\b(case|default|switch)\\b(?!\\$)"
432- },
433- {
434- "name": "keyword.control.conditional.js",
435- "match": "(?<!\\.|\\$)\\b(else|if)\\b(?!\\$)"
436- },
437- {
438- "name": "keyword.control.with.js",
439- "match": "(?<!\\.|\\$)\\b(with)\\b(?!\\$)"
440- },
441- {
442- "name": "keyword.other.debugger.js",
443- "match": "(?<!\\.|\\$)\\b(debugger)\\b(?!\\$)"
444- },
445- {
446- "name": "storage.modifier.js",
447- "match": "(?<!\\.|\\$)\\b(declare)\\b(?!\\$)"
448- }
449- ]
450- },
451- "declaration": {
452- "name": "meta.declaration.js",
453- "patterns": [
454- {
455- "include": "#decorator"
456- },
457- {
458- "include": "#var-expr"
459- },
460- {
461- "include": "#function-declaration"
462- },
463- {
464- "include": "#class-or-interface-declaration"
465- },
466- {
467- "include": "#type-declaration"
468- },
469- {
470- "include": "#enum-declaration"
471- },
472- {
473- "include": "#namespace-declaration"
474- },
475- {
476- "include": "#import-equals-declaration"
477- },
478- {
479- "include": "#import-declaration"
480- },
481- {
482- "include": "#export-declaration"
483- }
484- ]
485- },
486- "decorator": {
487- "name": "meta.decorator.js",
488- "begin": "(?<!\\.|\\$)\\@",
489- "beginCaptures": {
490- "0": {
491- "name": "punctuation.decorator.js"
492- }
493- },
494- "end": "(?=\\s)",
495- "patterns": [
496- {
497- "include": "#expression"
498- }
499- ]
500- },
501- "type-declaration": {
502- "name": "meta.type.declaration.js",
503- "begin": "(?<!\\.|\\$)(?:(\\bexport)\\s+)?\\b(type)\\b\\s+([_$[:alpha:]][_$[:alnum:]]*)\\s*",
504- "beginCaptures": {
505- "1": {
506- "name": "keyword.control.export.js"
507- },
508- "2": {
509- "name": "storage.type.type.js"
510- },
511- "3": {
512- "name": "entity.name.type.js"
513- }
514- },
515- "end": "(?=[};]|\\bvar\\b|\\blet\\b|\\bconst\\b|\\btype\\b|\\bfunction\\b|\\bclass\\b|\\binterface\\b|\\bnamespace\\b|\\bmodule\\b|\\bimport\\b|\\benum\\b|\\bdeclare\\b|\\bexport\\b|\\babstract\\b|\\basync\\b)",
516- "patterns": [
517- {
518- "include": "#comment"
519- },
520- {
521- "include": "#type-parameters"
522- },
523- {
524- "include": "#type"
525- },
526- {
527- "match": "(=)\\s*",
528- "captures": {
529- "1": {
530- "name": "keyword.operator.assignment.js"
531- }
532- }
533- }
534- ]
535- },
536- "enum-declaration": {
537- "name": "meta.enum.declaration.js",
538- "begin": "(?<!\\.|\\$)(?:(\\bexport)\\s+)?(?:\\b(const)\\s+)?\\b(enum)\\s+([_$[:alpha:]][_$[:alnum:]]*)",
539- "beginCaptures": {
540- "1": {
541- "name": "keyword.control.export.js"
542- },
543- "2": {
544- "name": "storage.modifier.js"
545- },
546- "3": {
547- "name": "storage.type.enum.js"
548- },
549- "4": {
550- "name": "entity.name.type.enum.js"
551- }
552- },
553- "end": "(?<=\\})",
554- "patterns": [
555- {
556- "include": "#comment"
557- },
558- {
559- "begin": "\\{",
560- "beginCaptures": {
561- "0": {
562- "name": "punctuation.definition.block.js"
563- }
564- },
565- "end": "\\}",
566- "endCaptures": {
567- "0": {
568- "name": "punctuation.definition.block.js"
569- }
570- },
571- "patterns": [
572- {
573- "include": "#comment"
574- },
575- {
576- "begin": "([_$[:alpha:]][_$[:alnum:]]*)",
577- "beginCaptures": {
578- "0": {
579- "name": "variable.other.enummember.js"
580- }
581- },
582- "end": "(?=,|\\}|$)",
583- "patterns": [
584- {
585- "include": "#comment"
586- },
587- {
588- "include": "#variable-initializer"
589- }
590- ]
591- },
592- {
593- "begin": "(?=((\\'[^']*\\')|(\\\"[^\"]*\\\")|(\\[([^\\[\\]]|\\[[^\\[\\]]+\\])+\\])))",
594- "end": "(?=,|\\}|$)",
595- "patterns": [
596- {
597- "include": "#string"
598- },
599- {
600- "include": "#array-literal"
601- },
602- {
603- "include": "#comment"
604- },
605- {
606- "include": "#variable-initializer"
607- }
608- ]
609- },
610- {
611- "include": "#punctuation-comma"
612- }
613- ]
614- }
615- ]
616- },
617- "namespace-declaration": {
618- "name": "meta.namespace.declaration.js",
619- "begin": "(?<!\\.|\\$)(?:(\\bexport)\\s+)?\\b(namespace|module)\\s+",
620- "beginCaptures": {
621- "1": {
622- "name": "keyword.control.export.js"
623- },
624- "2": {
625- "name": "storage.type.namespace.js"
626- }
627- },
628- "end": "(?=$|\\{)",
629- "patterns": [
630- {
631- "include": "#comment"
632- },
633- {
634- "include": "#string"
635- },
636- {
637- "name": "entity.name.type.module.js",
638- "match": "([_$[:alpha:]][_$[:alnum:]]*)"
639- },
640- {
641- "name": "punctuation.accessor.js",
642- "match": "\\."
643- }
644- ]
645- },
646- "import-equals-declaration": {
647- "patterns": [
648- {
649- "name": "meta.import-equals.external.js",
650- "begin": "(?<!\\.|\\$)(?:(\\bexport)\\s+)?\\b(import)\\s+([_$[:alpha:]][_$[:alnum:]]*)\\s*(=)\\s*(require)\\s*(\\()",
651- "beginCaptures": {
652- "1": {
653- "name": "keyword.control.export.js"
654- },
655- "2": {
656- "name": "keyword.control.import.js"
657- },
658- "3": {
659- "name": "variable.other.readwrite.alias.js"
660- },
661- "4": {
662- "name": "keyword.operator.assignment.js"
663- },
664- "5": {
665- "name": "keyword.control.require.js"
666- },
667- "6": {
668- "name": "meta.brace.round.js"
669- }
670- },
671- "end": "\\)",
672- "endCaptures": {
673- "0": {
674- "name": "meta.brace.round.js"
675- }
676- },
677- "patterns": [
678- {
679- "include": "#comment"
680- },
681- {
682- "include": "#string"
683- }
684- ]
685- },
686- {
687- "name": "meta.import-equals.internal.js",
688- "begin": "(?<!\\.|\\$)(?:(\\bexport)\\s+)?\\b(import)\\s+([_$[:alpha:]][_$[:alnum:]]*)\\s*(=)\\s*(?!require\\b)",
689- "beginCaptures": {
690- "1": {
691- "name": "keyword.control.export.js"
692- },
693- "2": {
694- "name": "keyword.control.import.js"
695- },
696- "3": {
697- "name": "variable.other.readwrite.alias.js"
698- },
699- "4": {
700- "name": "keyword.operator.assignment.js"
701- }
702- },
703- "end": "(?=;|$)",
704- "patterns": [
705- {
706- "include": "#comment"
707- },
708- {
709- "match": "([_$[:alpha:]][_$[:alnum:]]*)\\s*(\\.)",
710- "captures": {
711- "1": {
712- "name": "entity.name.type.module.js"
713- },
714- "2": {
715- "name": "punctuation.accessor.js"
716- }
717- }
718- },
719- {
720- "name": "variable.other.readwrite.js",
721- "match": "([_$[:alpha:]][_$[:alnum:]]*)"
722- }
723- ]
724- }
725- ]
726- },
727- "import-declaration": {
728- "name": "meta.import.js",
729- "begin": "(?<!\\.|\\$)(?:(\\bexport)\\s+)?\\b(import)(?!(\\s*:)|(\\$))\\b",
730- "beginCaptures": {
731- "1": {
732- "name": "keyword.control.export.js"
733- },
734- "2": {
735- "name": "keyword.control.import.js"
736- }
737- },
738- "end": "(?=;|$)",
739- "patterns": [
740- {
741- "include": "#import-export-declaration"
742- }
743- ]
744- },
745- "export-declaration": {
746- "patterns": [
747- {
748- "match": "(?<!\\.|\\$)\\b(export)\\s+(as)\\s+(namespace)\\s+([_$[:alpha:]][_$[:alnum:]]*)",
749- "captures": {
750- "1": {
751- "name": "keyword.control.export.js"
752- },
753- "2": {
754- "name": "keyword.control.as.js"
755- },
756- "3": {
757- "name": "storage.type.namespace.js"
758- },
759- "4": {
760- "name": "entity.name.type.module.js"
761- }
762- }
763- },
764- {
765- "name": "meta.export.default.js",
766- "begin": "(?<!\\.|\\$)\\b(export)(?:(?:\\s*(=))|(?:\\s+(default)(?=\\s+)))",
767- "beginCaptures": {
768- "1": {
769- "name": "keyword.control.export.js"
770- },
771- "2": {
772- "name": "keyword.operator.assignment.js"
773- },
774- "3": {
775- "name": "keyword.control.default.js"
776- }
777- },
778- "end": "(?=;|\\bexport\\b|\\bfunction\\b|\\bclass\\b|\\binterface\\b|\\blet\\b|\\bvar\\b|\\bconst\\b|\\bimport\\b|\\benum\\b|\\bnamespace\\b|\\bmodule\\b|\\btype\\b|\\babstract\\b|\\bdeclare\\b|\\basync\\b|$)",
779- "patterns": [
780- {
781- "include": "#expression"
782- }
783- ]
784- },
785- {
786- "name": "meta.export.js",
787- "begin": "(?<!\\.|\\$)\\b(export)(?!(\\s*:)|(\\$))\\b",
788- "beginCaptures": {
789- "0": {
790- "name": "keyword.control.export.js"
791- }
792- },
793- "end": "(?=;|\\bexport\\b|\\bfunction\\b|\\bclass\\b|\\binterface\\b|\\blet\\b|\\bvar\\b|\\bconst\\b|\\bimport\\b|\\benum\\b|\\bnamespace\\b|\\bmodule\\b|\\btype\\b|\\babstract\\b|\\bdeclare\\b|\\basync\\b|$)",
794- "patterns": [
795- {
796- "include": "#import-export-declaration"
797- }
798- ]
799- }
800- ]
801- },
802- "import-export-declaration": {
803- "patterns": [
804- {
805- "include": "#comment"
806- },
807- {
808- "include": "#string"
809- },
810- {
811- "include": "#import-export-block"
812- },
813- {
814- "name": "keyword.control.from.js",
815- "match": "\\bfrom\\b"
816- },
817- {
818- "include": "#import-export-clause"
819- }
820- ]
821- },
822- "import-export-block": {
823- "name": "meta.block.js",
824- "begin": "\\{",
825- "beginCaptures": {
826- "0": {
827- "name": "punctuation.definition.block.js"
828- }
829- },
830- "end": "\\}",
831- "endCaptures": {
832- "0": {
833- "name": "punctuation.definition.block.js"
834- }
835- },
836- "patterns": [
837- {
838- "include": "#import-export-clause"
839- }
840- ]
841- },
842- "import-export-clause": {
843- "patterns": [
844- {
845- "include": "#comment"
846- },
847- {
848- "comment": "(default|*|name) as alias",
849- "match": "(?x) (?: \\b(default)\\b | (\\*) | ([_$[:alpha:]][_$[:alnum:]]*)) \\s+ (as) \\s+ (?: (\\b default \\b | \\*) | ([_$[:alpha:]][_$[:alnum:]]*))",
850- "captures": {
851- "1": {
852- "name": "keyword.control.default.js"
853- },
854- "2": {
855- "name": "constant.language.import-export-all.js"
856- },
857- "3": {
858- "name": "variable.other.readwrite.js"
859- },
860- "4": {
861- "name": "keyword.control.as.js"
862- },
863- "5": {
864- "name": "invalid.illegal.js"
865- },
866- "6": {
867- "name": "variable.other.readwrite.alias.js"
868- }
869- }
870- },
871- {
872- "include": "#punctuation-comma"
873- },
874- {
875- "name": "constant.language.import-export-all.js",
876- "match": "\\*"
877- },
878- {
879- "name": "keyword.control.default.js",
880- "match": "\\b(default)\\b"
881- },
882- {
883- "name": "variable.other.readwrite.alias.js",
884- "match": "([_$[:alpha:]][_$[:alnum:]]*)"
885- }
886- ]
887- },
888- "class-or-interface-declaration": {
889- "name": "meta.class.js",
890- "begin": "(?<!\\.|\\$)\\b(?:(export)\\s+)?\\b(?:(abstract)\\s+)?\\b(?:(class)|(interface))\\b",
891- "beginCaptures": {
892- "1": {
893- "name": "keyword.control.export.js"
894- },
895- "2": {
896- "name": "storage.modifier.js"
897- },
898- "3": {
899- "name": "storage.type.class.js"
900- },
901- "4": {
902- "name": "storage.type.interface.js"
903- }
904- },
905- "end": "(?<=\\})",
906- "endCaptures": {
907- "1": {
908- "name": "punctuation.definition.block.js"
909- }
910- },
911- "patterns": [
912- {
913- "include": "#comment"
914- },
915- {
916- "include": "#class-or-interface-heritage"
917- },
918- {
919- "match": "[_$[:alpha:]][_$[:alnum:]]*",
920- "captures": {
921- "0": {
922- "name": "entity.name.type.class.js"
923- }
924- }
925- },
926- {
927- "include": "#type-parameters"
928- },
929- {
930- "include": "#class-or-interface-body"
931- }
932- ]
933- },
934- "class-or-interface-heritage": {
935- "begin": "(?<!\\.|\\$)(?:\\b(extends|implements)\\b)(?!\\$)",
936- "beginCaptures": {
937- "1": {
938- "name": "storage.modifier.js"
939- }
940- },
941- "end": "(?=\\{)",
942- "endCaptures": {
943- "1": {
944- "name": "punctuation.definition.block.js"
945- }
946- },
947- "patterns": [
948- {
949- "include": "#comment"
950- },
951- {
952- "include": "#class-or-interface-heritage"
953- },
954- {
955- "include": "#type-parameters"
956- },
957- {
958- "match": "([_$[:alpha:]][_$[:alnum:]]*)\\s*(\\.)(?=\\s*[_$[:alpha:]][_$[:alnum:]]*(\\s*\\.\\s*[_$[:alpha:]][_$[:alnum:]]*)*\\s*([,<{]|extends|implements|//|/\\*))",
959- "captures": {
960- "1": {
961- "name": "entity.name.type.module.js"
962- },
963- "2": {
964- "name": "punctuation.accessor.js"
965- }
966- }
967- },
968- {
969- "match": "([_$[:alpha:]][_$[:alnum:]]*)(?=\\s*([,<{]|extends|implements|//|/\\*))",
970- "captures": {
971- "1": {
972- "name": "entity.other.inherited-class.js"
973- }
974- }
975- },
976- {
977- "include": "#expression"
978- }
979- ]
980- },
981- "class-or-interface-body": {
982- "begin": "\\{",
983- "beginCaptures": {
984- "0": {
985- "name": "punctuation.definition.block.js"
986- }
987- },
988- "end": "\\}",
989- "endCaptures": {
990- "0": {
991- "name": "punctuation.definition.block.js"
992- }
993- },
994- "patterns": [
995- {
996- "include": "#string"
997- },
998- {
999- "include": "#comment"
1000- },
1001- {
1002- "include": "#decorator"
1003- },
1004- {
1005- "include": "#method-declaration"
1006- },
1007- {
1008- "include": "#indexer-declaration"
1009- },
1010- {
1011- "include": "#field-declaration"
1012- },
1013- {
1014- "include": "#type-annotation"
1015- },
1016- {
1017- "include": "#variable-initializer"
1018- },
1019- {
1020- "include": "#access-modifier"
1021- },
1022- {
1023- "include": "#property-accessor"
1024- },
1025- {
1026- "include": "#expression"
1027- },
1028- {
1029- "include": "#punctuation-comma"
1030- },
1031- {
1032- "include": "#punctuation-semicolon"
1033- }
1034- ]
1035- },
1036- "type-object": {
1037- "name": "meta.object.type.js",
1038- "begin": "\\{",
1039- "beginCaptures": {
1040- "0": {
1041- "name": "punctuation.definition.block.js"
1042- }
1043- },
1044- "end": "\\}",
1045- "endCaptures": {
1046- "0": {
1047- "name": "punctuation.definition.block.js"
1048- }
1049- },
1050- "patterns": [
1051- {
1052- "include": "#type-object-members"
1053- }
1054- ]
1055- },
1056- "type-object-members": {
1057- "patterns": [
1058- {
1059- "include": "#comment"
1060- },
1061- {
1062- "include": "#method-declaration"
1063- },
1064- {
1065- "include": "#indexer-declaration"
1066- },
1067- {
1068- "include": "#field-declaration"
1069- },
1070- {
1071- "include": "#type-annotation"
1072- },
1073- {
1074- "begin": "\\.\\.\\.",
1075- "beginCaptures": {
1076- "0": {
1077- "name": "keyword.operator.spread.js"
1078- }
1079- },
1080- "end": "(?=\\}|;|,|$)|(?<=\\})",
1081- "patterns": [
1082- {
1083- "include": "#type"
1084- }
1085- ]
1086- },
1087- {
1088- "include": "#punctuation-comma"
1089- },
1090- {
1091- "include": "#punctuation-semicolon"
1092- }
1093- ]
1094- },
1095- "field-declaration": {
1096- "name": "meta.field.declaration.js",
1097- "begin": "(?<!\\()(?:(?<!\\.|\\$)\\b(readonly)\\s+)?(?=(([_$[:alpha:]][_$[:alnum:]]*)|(\\'[^']*\\')|(\\\"[^\"]*\\\")|(\\[([^\\[\\]]|\\[[^\\[\\]]+\\])+\\]))\\s*(\\?\\s*)?(=|:))",
1098- "beginCaptures": {
1099- "1": {
1100- "name": "storage.modifier.js"
1101- }
1102- },
1103- "end": "(?=\\}|;|,|$)|(?<=\\})",
1104- "patterns": [
1105- {
1106- "include": "#variable-initializer"
1107- },
1108- {
1109- "begin": "(?=((?:[_$[:alpha:]][_$[:alnum:]]*)|(?:\\'[^']*\\')|(?:\\\"[^\"]*\\\")|(\\[([^\\[\\]]|\\[[^\\[\\]]+\\])+\\]))\\s*(\\?\\s*)?(=|:))",
1110- "end": "(?=[};,=]|$)|(?<=\\})",
1111- "patterns": [
1112- {
1113- "include": "#type-annotation"
1114- },
1115- {
1116- "include": "#string"
1117- },
1118- {
1119- "include": "#array-literal"
1120- },
1121- {
1122- "include": "#comment"
1123- },
1124- {
1125- "name": "entity.name.function.js",
1126- "match": "(?x)([_$[:alpha:]][_$[:alnum:]]*)(?=(\\?\\s*)?\\s* (=\\s*( (async\\s+) | (function\\s*[(<]) | (function\\s+) | ([_$[:alpha:]][_$[:alnum:]]*\\s*=>) | ((<([^<>]|\\<[^<>]+\\>)+>\\s*)?\\(([^()]|\\([^()]*\\))*\\)(\\s*:\\s*(.)*)?\\s*=>)) ) | (:\\s*( (<) | ([(]\\s*( ([)]) | (\\.\\.\\.) | ([_$[:alnum:]]+\\s*( ([:,?=])| ([)]\\s*=>) )) ))) ))"
1127- },
1128- {
1129- "name": "variable.object.property.js",
1130- "match": "[_$[:alpha:]][_$[:alnum:]]*"
1131- },
1132- {
1133- "name": "keyword.operator.optional.js",
1134- "match": "\\?"
1135- }
1136- ]
1137- }
1138- ]
1139- },
1140- "method-declaration": {
1141- "name": "meta.method.declaration.js",
1142- "begin": "(?<!\\.|\\$)(?:\\b(public|private|protected)\\s+)?(?:\\b(abstract)\\s+)?(?:\\b(async)\\s+)?(?:\\b(get|set)\\s+)?(?:(?:\\b(?:(new)|(constructor))\\b(?!\\$|:))|(?:(\\*)\\s*)?(?=((([_$[:alpha:]][_$[:alnum:]]*)|(\\'[^']*\\')|(\\\"[^\"]*\\\")|(\\[([^\\[\\]]|\\[[^\\[\\]]+\\])+\\]))\\s*(\\??))?\\s*[\\(\\<]))",
1143- "beginCaptures": {
1144- "1": {
1145- "name": "storage.modifier.js"
1146- },
1147- "2": {
1148- "name": "storage.modifier.js"
1149- },
1150- "3": {
1151- "name": "storage.modifier.async.js"
1152- },
1153- "4": {
1154- "name": "storage.type.property.js"
1155- },
1156- "5": {
1157- "name": "keyword.operator.new.js"
1158- },
1159- "6": {
1160- "name": "storage.type.js"
1161- },
1162- "7": {
1163- "name": "keyword.generator.asterisk.js"
1164- }
1165- },
1166- "end": "(?=\\}|;|,)|(?<=\\})",
1167- "patterns": [
1168- {
1169- "include": "#method-declaration-name"
1170- },
1171- {
1172- "include": "#comment"
1173- },
1174- {
1175- "include": "#type-parameters"
1176- },
1177- {
1178- "include": "#function-parameters"
1179- },
1180- {
1181- "include": "#return-type"
1182- },
1183- {
1184- "include": "#method-overload-declaration"
1185- },
1186- {
1187- "include": "#decl-block"
1188- }
1189- ]
1190- },
1191- "method-overload-declaration": {
1192- "begin": "(?<!\\.|\\$)(?:\\b(public|private|protected)\\s+)?(?:\\b(abstract)\\s+)?(?:\\b(async)\\s+)?(?:\\b(get|set)\\s+)?(?:(?:\\b(?:(new)|(constructor))\\b(?!\\$|:))|(?:(\\*)\\s*)?(?=((([_$[:alpha:]][_$[:alnum:]]*)|(\\'[^']*\\')|(\\\"[^\"]*\\\")|(\\[([^\\[\\]]|\\[[^\\[\\]]+\\])+\\]))\\s*(\\??))?\\s*[\\(\\<]))",
1193- "beginCaptures": {
1194- "1": {
1195- "name": "storage.modifier.js"
1196- },
1197- "2": {
1198- "name": "storage.modifier.js"
1199- },
1200- "3": {
1201- "name": "storage.modifier.async.js"
1202- },
1203- "4": {
1204- "name": "storage.type.property.js"
1205- },
1206- "5": {
1207- "name": "keyword.operator.new.js"
1208- },
1209- "6": {
1210- "name": "storage.type.js"
1211- },
1212- "7": {
1213- "name": "keyword.generator.asterisk.js"
1214- }
1215- },
1216- "end": "(?=\\(|\\<)",
1217- "patterns": [
1218- {
1219- "include": "#method-declaration-name"
1220- }
1221- ]
1222- },
1223- "method-declaration-name": {
1224- "begin": "(?=(([_$[:alpha:]][_$[:alnum:]]*)|(\\'[^']*\\')|(\\\"[^\"]*\\\")|(\\[([^\\[\\]]|\\[[^\\[\\]]+\\])+\\]))\\s*(\\??)\\s*[\\(\\<])",
1225- "end": "(?=\\(|\\<)",
1226- "patterns": [
1227- {
1228- "include": "#string"
1229- },
1230- {
1231- "include": "#array-literal"
1232- },
1233- {
1234- "name": "entity.name.function.js",
1235- "match": "[_$[:alpha:]][_$[:alnum:]]*"
1236- },
1237- {
1238- "name": "keyword.operator.optional.js",
1239- "match": "\\?"
1240- }
1241- ]
1242- },
1243- "indexer-declaration": {
1244- "name": "meta.indexer.declaration.js",
1245- "begin": "(?:(?<!\\.|\\$)\\b(readonly)\\s*)?(\\[)\\s*([_$[:alpha:]][_$[:alnum:]]*)\\s*(?=:)",
1246- "beginCaptures": {
1247- "1": {
1248- "name": "storage.modifier.js"
1249- },
1250- "2": {
1251- "name": "meta.brace.square.js"
1252- },
1253- "3": {
1254- "name": "variable.parameter.js"
1255- }
1256- },
1257- "end": "(\\])\\s*(\\?\\s*)?|$",
1258- "endCaptures": {
1259- "1": {
1260- "name": "meta.brace.square.js"
1261- },
1262- "2": {
1263- "name": "keyword.operator.optional.js"
1264- }
1265- },
1266- "patterns": [
1267- {
1268- "include": "#type-annotation"
1269- }
1270- ]
1271- },
1272- "function-declaration": {
1273- "name": "meta.function.js",
1274- "begin": "(?<!\\.|\\$)\\b(?:(export)\\s+)?(?:(async)\\s+)?(function\\b)(?:\\s*(\\*))?(?:(?:\\s+|(?<=\\*))([_$[:alpha:]][_$[:alnum:]]*))?\\s*",
1275- "beginCaptures": {
1276- "1": {
1277- "name": "keyword.control.export.js"
1278- },
1279- "2": {
1280- "name": "storage.modifier.async.js"
1281- },
1282- "3": {
1283- "name": "storage.type.function.js"
1284- },
1285- "4": {
1286- "name": "keyword.generator.asterisk.js"
1287- },
1288- "5": {
1289- "name": "entity.name.function.js"
1290- }
1291- },
1292- "end": "(?=;|\\})|(?<=\\})",
1293- "patterns": [
1294- {
1295- "include": "#comment"
1296- },
1297- {
1298- "include": "#type-parameters"
1299- },
1300- {
1301- "include": "#function-parameters"
1302- },
1303- {
1304- "include": "#return-type"
1305- },
1306- {
1307- "include": "#function-overload-declaration"
1308- },
1309- {
1310- "include": "#decl-block"
1311- }
1312- ]
1313- },
1314- "function-overload-declaration": {
1315- "name": "meta.function.overload.js",
1316- "match": "(?<!\\.|\\$)\\b(?:(export)\\s+)?(?:(async)\\s+)?(function\\b)(?:\\s*(\\*))?(?:(?:\\s+|(?<=\\*))([_$[:alpha:]][_$[:alnum:]]*))?\\s*",
1317- "captures": {
1318- "1": {
1319- "name": "keyword.control.export.js"
1320- },
1321- "2": {
1322- "name": "storage.modifier.async.js"
1323- },
1324- "3": {
1325- "name": "storage.type.function.js"
1326- },
1327- "4": {
1328- "name": "keyword.generator.asterisk.js"
1329- },
1330- "5": {
1331- "name": "entity.name.function.js"
1332- }
1333- }
1334- },
1335- "object-literal": {
1336- "name": "meta.objectliteral.js",
1337- "begin": "\\{",
1338- "beginCaptures": {
1339- "0": {
1340- "name": "punctuation.definition.block.js"
1341- }
1342- },
1343- "end": "\\}",
1344- "endCaptures": {
1345- "0": {
1346- "name": "punctuation.definition.block.js"
1347- }
1348- },
1349- "patterns": [
1350- {
1351- "include": "#object-member"
1352- }
1353- ]
1354- },
1355- "decl-block": {
1356- "name": "meta.block.js",
1357- "begin": "\\{",
1358- "beginCaptures": {
1359- "0": {
1360- "name": "punctuation.definition.block.js"
1361- }
1362- },
1363- "end": "\\}",
1364- "endCaptures": {
1365- "0": {
1366- "name": "punctuation.definition.block.js"
1367- }
1368- },
1369- "patterns": [
1370- {
1371- "include": "#statements"
1372- }
1373- ]
1374- },
1375- "after-operator-block": {
1376- "name": "meta.objectliteral.js",
1377- "begin": "(?<=[=(,\\[?+!]|await|return|yield|throw|in|of|typeof|&&|\\|\\||\\*)\\s*(\\{)",
1378- "beginCaptures": {
1379- "1": {
1380- "name": "punctuation.definition.block.js"
1381- }
1382- },
1383- "end": "\\}",
1384- "endCaptures": {
1385- "0": {
1386- "name": "punctuation.definition.block.js"
1387- }
1388- },
1389- "patterns": [
1390- {
1391- "include": "#object-member"
1392- }
1393- ]
1394- },
1395- "parameter-name": {
1396- "patterns": [
1397- {
1398- "match": "(?x)(?:\\s*\\b(readonly)\\s+)?(?:\\s*\\b(public|private|protected)\\s+)?(\\.\\.\\.)?\\s*(?<!=|:)([_$[:alpha:]][_$[:alnum:]]*)\\s*(\\??)(?=\\s* (=\\s*( (async\\s+) | (function\\s*[(<]) | (function\\s+) | ([_$[:alpha:]][_$[:alnum:]]*\\s*=>) | ((<([^<>]|\\<[^<>]+\\>)+>\\s*)?\\(([^()]|\\([^()]*\\))*\\)(\\s*:\\s*(.)*)?\\s*=>)) ) | (:\\s*( (<) | ([(]\\s*( ([)]) | (\\.\\.\\.) | ([_$[:alnum:]]+\\s*( ([:,?=])| ([)]\\s*=>) )) ))) ))",
1399- "captures": {
1400- "1": {
1401- "name": "storage.modifier.js"
1402- },
1403- "2": {
1404- "name": "storage.modifier.js"
1405- },
1406- "3": {
1407- "name": "keyword.operator.rest.js"
1408- },
1409- "4": {
1410- "name": "entity.name.function.js"
1411- },
1412- "5": {
1413- "name": "keyword.operator.optional.js"
1414- }
1415- }
1416- },
1417- {
1418- "match": "(?:\\s*\\b(readonly)\\s+)?(?:\\s*\\b(public|private|protected)\\s+)?(\\.\\.\\.)?\\s*(?<!=|:)([_$[:alpha:]][_$[:alnum:]]*)\\s*(\\??)",
1419- "captures": {
1420- "1": {
1421- "name": "storage.modifier.js"
1422- },
1423- "2": {
1424- "name": "storage.modifier.js"
1425- },
1426- "3": {
1427- "name": "keyword.operator.rest.js"
1428- },
1429- "4": {
1430- "name": "variable.parameter.js"
1431- },
1432- "5": {
1433- "name": "keyword.operator.optional.js"
1434- }
1435- }
1436- }
1437- ]
1438- },
1439- "destructuring-parameter": {
1440- "patterns": [
1441- {
1442- "name": "meta.parameter.object-binding-pattern.js",
1443- "begin": "(?<!=|:)\\s*(\\{)",
1444- "beginCaptures": {
1445- "1": {
1446- "name": "punctuation.definition.binding-pattern.object.js"
1447- }
1448- },
1449- "end": "\\}",
1450- "endCaptures": {
1451- "0": {
1452- "name": "punctuation.definition.binding-pattern.object.js"
1453- }
1454- },
1455- "patterns": [
1456- {
1457- "include": "#parameter-object-binding-element"
1458- }
1459- ]
1460- },
1461- {
1462- "name": "meta.paramter.array-binding-pattern.js",
1463- "begin": "(?<!=|:)\\s*(\\[)",
1464- "beginCaptures": {
1465- "1": {
1466- "name": "punctuation.definition.binding-pattern.array.js"
1467- }
1468- },
1469- "end": "\\]",
1470- "endCaptures": {
1471- "0": {
1472- "name": "punctuation.definition.binding-pattern.array.js"
1473- }
1474- },
1475- "patterns": [
1476- {
1477- "include": "#parameter-binding-element"
1478- },
1479- {
1480- "include": "#punctuation-comma"
1481- }
1482- ]
1483- }
1484- ]
1485- },
1486- "parameter-object-binding-element": {
1487- "patterns": [
1488- {
1489- "include": "#comment"
1490- },
1491- {
1492- "begin": "(?=(([_$[:alpha:]][_$[:alnum:]]*)|(\\'[^']*\\')|(\\\"[^\"]*\\\")|(\\[([^\\[\\]]|\\[[^\\[\\]]+\\])+\\]))\\s*(:))",
1493- "end": "(?=,|\\})",
1494- "patterns": [
1495- {
1496- "include": "#object-binding-element-propertyName"
1497- },
1498- {
1499- "include": "#parameter-binding-element"
1500- }
1501- ]
1502- },
1503- {
1504- "include": "#parameter-object-binding-pattern"
1505- },
1506- {
1507- "include": "#destructuring-parameter-rest"
1508- },
1509- {
1510- "include": "#variable-initializer"
1511- },
1512- {
1513- "include": "#punctuation-comma"
1514- }
1515- ]
1516- },
1517- "parameter-binding-element": {
1518- "patterns": [
1519- {
1520- "include": "#comment"
1521- },
1522- {
1523- "include": "#parameter-object-binding-pattern"
1524- },
1525- {
1526- "include": "#parameter-array-binding-pattern"
1527- },
1528- {
1529- "include": "#destructuring-parameter-rest"
1530- },
1531- {
1532- "include": "#variable-initializer"
1533- }
1534- ]
1535- },
1536- "destructuring-parameter-rest": {
1537- "match": "(?:(\\.\\.\\.)\\s*)?([_$[:alpha:]][_$[:alnum:]]*)",
1538- "captures": {
1539- "1": {
1540- "name": "keyword.operator.rest.js"
1541- },
1542- "2": {
1543- "name": "variable.parameter.js"
1544- }
1545- }
1546- },
1547- "parameter-object-binding-pattern": {
1548- "begin": "(?:(\\.\\.\\.)\\s*)?(\\{)",
1549- "beginCaptures": {
1550- "1": {
1551- "name": "keyword.operator.rest.js"
1552- },
1553- "2": {
1554- "name": "punctuation.definition.binding-pattern.object.js"
1555- }
1556- },
1557- "end": "\\}",
1558- "endCaptures": {
1559- "0": {
1560- "name": "punctuation.definition.binding-pattern.object.js"
1561- }
1562- },
1563- "patterns": [
1564- {
1565- "include": "#parameter-object-binding-element"
1566- }
1567- ]
1568- },
1569- "parameter-array-binding-pattern": {
1570- "begin": "(?:(\\.\\.\\.)\\s*)?(\\[)",
1571- "beginCaptures": {
1572- "1": {
1573- "name": "keyword.operator.rest.js"
1574- },
1575- "2": {
1576- "name": "punctuation.definition.binding-pattern.array.js"
1577- }
1578- },
1579- "end": "\\]",
1580- "endCaptures": {
1581- "0": {
1582- "name": "punctuation.definition.binding-pattern.array.js"
1583- }
1584- },
1585- "patterns": [
1586- {
1587- "include": "#parameter-binding-element"
1588- },
1589- {
1590- "include": "#punctuation-comma"
1591- }
1592- ]
1593- },
1594- "return-type": {
1595- "name": "meta.return.type.js",
1596- "begin": "(?<=\\))\\s*(:)",
1597- "beginCaptures": {
1598- "1": {
1599- "name": "keyword.operator.type.annotation.js"
1600- }
1601- },
1602- "end": "(?<!:)((?=$)|(?=\\{|;|//|\\}))",
1603- "patterns": [
1604- {
1605- "include": "#comment"
1606- },
1607- {
1608- "name": "meta.object.type.js",
1609- "begin": "(?<=:)\\s*(\\{)",
1610- "beginCaptures": {
1611- "1": {
1612- "name": "punctuation.definition.block.js"
1613- }
1614- },
1615- "end": "\\}",
1616- "endCaptures": {
1617- "0": {
1618- "name": "punctuation.definition.block.js"
1619- }
1620- },
1621- "patterns": [
1622- {
1623- "include": "#type-object-members"
1624- }
1625- ]
1626- },
1627- {
1628- "include": "#type-predicate-operator"
1629- },
1630- {
1631- "include": "#type"
1632- }
1633- ]
1634- },
1635- "type-predicate-operator": {
1636- "name": "keyword.operator.expression.is.js",
1637- "match": "(?<!\\.|\\$)\\bis\\b(?!\\$)"
1638- },
1639- "type-annotation": {
1640- "name": "meta.type.annotation.js",
1641- "begin": ":",
1642- "beginCaptures": {
1643- "0": {
1644- "name": "keyword.operator.type.annotation.js"
1645- }
1646- },
1647- "end": "(?=$|[,);\\}\\]]|//)|(?==[^>])|(?<=[\\}>\\]\\)]|[_$[:alpha:]])\\s*(?=\\{)",
1648- "patterns": [
1649- {
1650- "include": "#comment"
1651- },
1652- {
1653- "include": "#type"
1654- }
1655- ]
1656- },
1657- "type": {
1658- "name": "meta.type.js",
1659- "patterns": [
1660- {
1661- "include": "#comment"
1662- },
1663- {
1664- "include": "#string"
1665- },
1666- {
1667- "include": "#numeric-literal"
1668- },
1669- {
1670- "include": "#type-primitive"
1671- },
1672- {
1673- "include": "#type-builtin-literals"
1674- },
1675- {
1676- "include": "#type-parameters"
1677- },
1678- {
1679- "include": "#type-tuple"
1680- },
1681- {
1682- "include": "#type-object"
1683- },
1684- {
1685- "include": "#type-operators"
1686- },
1687- {
1688- "include": "#type-fn-type-parameters"
1689- },
1690- {
1691- "include": "#type-paren-or-function-parameters"
1692- },
1693- {
1694- "include": "#type-function-return-type"
1695- },
1696- {
1697- "include": "#type-name"
1698- }
1699- ]
1700- },
1701- "function-parameters": {
1702- "name": "meta.parameters.js",
1703- "begin": "\\(",
1704- "beginCaptures": {
1705- "0": {
1706- "name": "punctuation.definition.parameters.begin.js"
1707- }
1708- },
1709- "end": "\\)",
1710- "endCaptures": {
1711- "0": {
1712- "name": "punctuation.definition.parameters.end.js"
1713- }
1714- },
1715- "patterns": [
1716- {
1717- "include": "#comment"
1718- },
1719- {
1720- "include": "#decorator"
1721- },
1722- {
1723- "include": "#destructuring-parameter"
1724- },
1725- {
1726- "include": "#parameter-name"
1727- },
1728- {
1729- "include": "#type-annotation"
1730- },
1731- {
1732- "include": "#variable-initializer"
1733- },
1734- {
1735- "name": "punctuation.separator.parameter.js",
1736- "match": ","
1737- }
1738- ]
1739- },
1740- "type-primitive": {
1741- "name": "support.type.primitive.js",
1742- "match": "(?<!\\.|\\$)\\b(string|number|boolean|symbol|any|void|never)\\b(?!\\$)"
1743- },
1744- "type-builtin-literals": {
1745- "name": "support.type.builtin.js",
1746- "match": "(?<!\\.|\\$)\\b(this|true|false|undefined|null)\\b(?!\\$)"
1747- },
1748- "type-paren-or-function-parameters": {
1749- "name": "meta.type.paren.cover.js",
1750- "begin": "\\(",
1751- "beginCaptures": {
1752- "0": {
1753- "name": "meta.brace.round.js"
1754- }
1755- },
1756- "end": "\\)",
1757- "endCaptures": {
1758- "0": {
1759- "name": "meta.brace.round.js"
1760- }
1761- },
1762- "patterns": [
1763- {
1764- "include": "#type"
1765- },
1766- {
1767- "include": "#function-parameters"
1768- }
1769- ]
1770- },
1771- "type-fn-type-parameters": {
1772- "patterns": [
1773- {
1774- "name": "meta.type.constructor.js",
1775- "match": "(?<!\\.|\\$)\\b(new)\\b(?=\\s*\\<)",
1776- "captures": {
1777- "1": {
1778- "name": "keyword.control.new.js"
1779- }
1780- }
1781- },
1782- {
1783- "name": "meta.type.constructor.js",
1784- "begin": "(?<!\\.|\\$)\\b(new)\\b\\s*(?=\\()",
1785- "beginCaptures": {
1786- "1": {
1787- "name": "keyword.control.new.js"
1788- }
1789- },
1790- "end": "(?<=\\))",
1791- "patterns": [
1792- {
1793- "include": "#function-parameters"
1794- }
1795- ]
1796- },
1797- {
1798- "name": "meta.type.function.js",
1799- "begin": "(?<=\\>)\\s*(?=\\()",
1800- "end": "(?<=\\))",
1801- "patterns": [
1802- {
1803- "include": "#function-parameters"
1804- }
1805- ]
1806- },
1807- {
1808- "name": "meta.type.function.js",
1809- "begin": "(?x)( (?= [(]\\s*( ([)]) | (\\.\\.\\.) | ([_$[:alnum:]]+\\s*( ([:,?=])| ([)]\\s*=>) )) ) ) )",
1810- "end": "(?<=\\))",
1811- "patterns": [
1812- {
1813- "include": "#function-parameters"
1814- }
1815- ]
1816- }
1817- ]
1818- },
1819- "type-operators": {
1820- "patterns": [
1821- {
1822- "include": "#typeof-operator"
1823- },
1824- {
1825- "name": "keyword.operator.type.js",
1826- "match": "[&|]"
1827- },
1828- {
1829- "name": "keyword.operator.expression.keyof.js",
1830- "match": "(?<!\\.|\\$)\\bkeyof\\b(?!\\$)"
1831- }
1832- ]
1833- },
1834- "type-function-return-type": {
1835- "name": "meta.type.function.return.js",
1836- "begin": "=>",
1837- "beginCaptures": {
1838- "0": {
1839- "name": "storage.type.function.arrow.js"
1840- }
1841- },
1842- "end": "(?<!=>)(?=[,\\]\\)\\{\\}=;>]|//|$)",
1843- "patterns": [
1844- {
1845- "include": "#comment"
1846- },
1847- {
1848- "name": "meta.object.type.js",
1849- "begin": "(?<==>)\\s*(\\{)",
1850- "beginCaptures": {
1851- "1": {
1852- "name": "punctuation.definition.block.js"
1853- }
1854- },
1855- "end": "\\}",
1856- "endCaptures": {
1857- "0": {
1858- "name": "punctuation.definition.block.js"
1859- }
1860- },
1861- "patterns": [
1862- {
1863- "include": "#type-object-members"
1864- }
1865- ]
1866- },
1867- {
1868- "include": "#type-predicate-operator"
1869- },
1870- {
1871- "include": "#type"
1872- }
1873- ]
1874- },
1875- "type-tuple": {
1876- "name": "meta.type.tuple.js",
1877- "begin": "\\[",
1878- "beginCaptures": {
1879- "0": {
1880- "name": "meta.brace.square.js"
1881- }
1882- },
1883- "end": "\\]",
1884- "endCaptures": {
1885- "0": {
1886- "name": "meta.brace.square.js"
1887- }
1888- },
1889- "patterns": [
1890- {
1891- "include": "#type"
1892- },
1893- {
1894- "include": "#punctuation-comma"
1895- }
1896- ]
1897- },
1898- "type-name": {
1899- "patterns": [
1900- {
1901- "match": "([_$[:alpha:]][_$[:alnum:]]*)\\s*(\\.)",
1902- "captures": {
1903- "1": {
1904- "name": "entity.name.type.module.js"
1905- },
1906- "2": {
1907- "name": "punctuation.accessor.js"
1908- }
1909- }
1910- },
1911- {
1912- "name": "entity.name.type.js",
1913- "match": "[_$[:alpha:]][_$[:alnum:]]*"
1914- }
1915- ]
1916- },
1917- "type-parameters": {
1918- "name": "meta.type.parameters.js",
1919- "begin": "(<)",
1920- "beginCaptures": {
1921- "1": {
1922- "name": "punctuation.definition.typeparameters.begin.js"
1923- }
1924- },
1925- "end": "(?=$)|(>)",
1926- "endCaptures": {
1927- "1": {
1928- "name": "punctuation.definition.typeparameters.end.js"
1929- }
1930- },
1931- "patterns": [
1932- {
1933- "include": "#comment"
1934- },
1935- {
1936- "name": "storage.modifier.js",
1937- "match": "(?<!\\.|\\$)\\b(extends)\\b(?!\\$)"
1938- },
1939- {
1940- "include": "#type"
1941- },
1942- {
1943- "include": "#punctuation-comma"
1944- }
1945- ]
1946- },
1947- "variable-initializer": {
1948- "begin": "(?<!=|!)(=)(?!=)",
1949- "beginCaptures": {
1950- "1": {
1951- "name": "keyword.operator.assignment.js"
1952- }
1953- },
1954- "end": "(?=$|[,);}\\]])",
1955- "patterns": [
1956- {
1957- "include": "#expression"
1958- }
1959- ]
1960- },
1961- "for-loop": {
1962- "begin": "(?<!\\.|\\$)\\b(for)\\s*(\\()",
1963- "beginCaptures": {
1964- "1": {
1965- "name": "keyword.control.loop.js"
1966- },
1967- "2": {
1968- "name": "meta.brace.round.js"
1969- }
1970- },
1971- "end": "\\)",
1972- "endCaptures": {
1973- "0": {
1974- "name": "meta.brace.round.js"
1975- }
1976- },
1977- "patterns": [
1978- {
1979- "include": "#var-expr"
1980- },
1981- {
1982- "include": "#expression"
1983- },
1984- {
1985- "include": "#punctuation-semicolon"
1986- }
1987- ]
1988- },
1989- "switch-expression": {
1990- "name": "switch-expression.expr.js",
1991- "begin": "(?<!\\.|\\$)\\b(switch)\\s*(\\()",
1992- "beginCaptures": {
1993- "1": {
1994- "name": "keyword.control.switch.js"
1995- },
1996- "2": {
1997- "name": "meta.brace.round.js"
1998- }
1999- },
2000- "end": "\\)",
2001- "endCaptures": {
2002- "0": {
2003- "name": "meta.brace.round.js"
2004- }
2005- },
2006- "patterns": [
2007- {
2008- "include": "#expression"
2009- }
2010- ]
2011- },
2012- "switch-block": {
2013- "name": "switch-block.expr.js",
2014- "begin": "{",
2015- "beginCaptures": {
2016- "0": {
2017- "name": "punctuation.definition.block.js"
2018- }
2019- },
2020- "end": "(?=\\})",
2021- "patterns": [
2022- {
2023- "include": "#case-clause"
2024- },
2025- {
2026- "include": "#statements"
2027- }
2028- ]
2029- },
2030- "case-clause": {
2031- "name": "case-clause.expr.js",
2032- "begin": "(?<!\\.|\\$)\\b(case|default(?=:))\\b(?!\\$)",
2033- "beginCaptures": {
2034- "1": {
2035- "name": "keyword.control.switch.js"
2036- }
2037- },
2038- "end": ":",
2039- "endCaptures": {
2040- "0": {
2041- "name": "punctuation.definition.section.case-statement.js"
2042- }
2043- },
2044- "patterns": [
2045- {
2046- "include": "#expression"
2047- }
2048- ]
2049- },
2050- "switch-statement": {
2051- "name": "switch-statement.expr.js",
2052- "begin": "(?<!\\.|\\$)(?=\\bswitch\\s*\\()",
2053- "end": "}",
2054- "endCaptures": {
2055- "0": {
2056- "name": "punctuation.definition.block.js"
2057- }
2058- },
2059- "patterns": [
2060- {
2061- "include": "#switch-expression"
2062- },
2063- {
2064- "include": "#switch-block"
2065- }
2066- ]
2067- },
2068- "support-objects": {
2069- "patterns": [
2070- {
2071- "name": "variable.language.arguments.js",
2072- "match": "(?<!\\.|\\$)\\b(arguments)\\b(?!\\$)"
2073- },
2074- {
2075- "name": "support.class.builtin.js",
2076- "match": "(?x)(?<!\\.|\\$)\\b(Array|ArrayBuffer|Atomics|Boolean|DataView|Date|Float32Array|Float64Array|Function|Generator |GeneratorFunction|Int8Array|Int16Array|Int32Array|Intl|Map|Number|Object|Promise|Proxy |Reflect|RegExp|Set|SharedArrayBuffer|SIMD|String|Symbol|TypedArray |Uint8Array|Uint16Array|Uint32Array|Uint8ClampedArray|WeakMap|WeakSet)\\b(?!\\$)"
2077- },
2078- {
2079- "name": "support.class.error.js",
2080- "match": "(?<!\\.|\\$)\\b((Eval|Internal|Range|Reference|Syntax|Type|URI)?Error)\\b(?!\\$)"
2081- },
2082- {
2083- "name": "support.function.js",
2084- "match": "(?x)(?<!\\.|\\$)\\b(clear(Interval|Timeout)|decodeURI|decodeURIComponent|encodeURI|encodeURIComponent|escape|eval| isFinite|isNaN|parseFloat|parseInt|require|set(Interval|Timeout)|super|unescape|uneval)(?=\\s*\\()"
2085- },
2086- {
2087- "match": "(?x)(?<!\\.|\\$)\\b(Math)(?:\\s*(\\.)\\s*(?:\n (abs|acos|acosh|asin|asinh|atan|atan2|atanh|cbrt|ceil|clz32|cos|cosh|exp|\n expm1|floor|fround|hypot|imul|log|log10|log1p|log2|max|min|pow|random|\n round|sign|sin|sinh|sqrt|tan|tanh|trunc)\n |\n (E|LN10|LN2|LOG10E|LOG2E|PI|SQRT1_2|SQRT2)))?\\b(?!\\$)",
2088- "captures": {
2089- "1": {
2090- "name": "support.constant.math.js"
2091- },
2092- "2": {
2093- "name": "punctuation.accessor.js"
2094- },
2095- "3": {
2096- "name": "support.function.math.js"
2097- },
2098- "4": {
2099- "name": "support.constant.property.math.js"
2100- }
2101- }
2102- },
2103- {
2104- "match": "(?x)(?<!\\.|\\$)\\b(console)(?:\\s*(\\.)\\s*(\n assert|clear|count|debug|dir|error|group|groupCollapsed|groupEnd|info|log\n |profile|profileEnd|table|time|timeEnd|timeStamp|trace|warn))?\\b(?!\\$)",
2105- "captures": {
2106- "1": {
2107- "name": "support.class.console.js"
2108- },
2109- "2": {
2110- "name": "punctuation.accessor.js"
2111- },
2112- "3": {
2113- "name": "support.function.console.js"
2114- }
2115- }
2116- },
2117- {
2118- "match": "(?<!\\.|\\$)\\b(JSON)(?:\\s*(\\.)\\s*(parse|stringify))?\\b(?!\\$)",
2119- "captures": {
2120- "1": {
2121- "name": "support.constant.json.js"
2122- },
2123- "2": {
2124- "name": "punctuation.accessor.js"
2125- },
2126- "3": {
2127- "name": "support.function.json.js"
2128- }
2129- }
2130- },
2131- {
2132- "match": "(?x) (\\.) \\s* (?:\n (constructor|length|prototype|__proto__) \n |\n (EPSILON|MAX_SAFE_INTEGER|MAX_VALUE|MIN_SAFE_INTEGER|MIN_VALUE|NEGATIVE_INFINITY|POSITIVE_INFINITY))\\b(?!\\$)",
2133- "captures": {
2134- "1": {
2135- "name": "punctuation.accessor.js"
2136- },
2137- "2": {
2138- "name": "support.variable.property.js"
2139- },
2140- "3": {
2141- "name": "support.constant.js"
2142- }
2143- }
2144- },
2145- {
2146- "match": "(?x) (?<!\\.|\\$) \\b (?:\n (document|event|navigator|performance|screen|window) \n |\n (AnalyserNode|ArrayBufferView|Attr|AudioBuffer|AudioBufferSourceNode|AudioContext|AudioDestinationNode|AudioListener\n |AudioNode|AudioParam|BatteryManager|BeforeUnloadEvent|BiquadFilterNode|Blob|BufferSource|ByteString|CSS|CSSConditionRule\n |CSSCounterStyleRule|CSSGroupingRule|CSSMatrix|CSSMediaRule|CSSPageRule|CSSPrimitiveValue|CSSRule|CSSRuleList|CSSStyleDeclaration\n |CSSStyleRule|CSSStyleSheet|CSSSupportsRule|CSSValue|CSSValueList|CanvasGradient|CanvasImageSource|CanvasPattern\n |CanvasRenderingContext2D|ChannelMergerNode|ChannelSplitterNode|CharacterData|ChromeWorker|CloseEvent|Comment|CompositionEvent\n |Console|ConvolverNode|Coordinates|Credential|CredentialsContainer|Crypto|CryptoKey|CustomEvent|DOMError|DOMException\n |DOMHighResTimeStamp|DOMImplementation|DOMString|DOMStringList|DOMStringMap|DOMTimeStamp|DOMTokenList|DataTransfer\n |DataTransferItem|DataTransferItemList|DedicatedWorkerGlobalScope|DelayNode|DeviceProximityEvent|DirectoryEntry\n |DirectoryEntrySync|DirectoryReader|DirectoryReaderSync|Document|DocumentFragment|DocumentTouch|DocumentType|DragEvent\n |DynamicsCompressorNode|Element|Entry|EntrySync|ErrorEvent|Event|EventListener|EventSource|EventTarget|FederatedCredential\n |FetchEvent|File|FileEntry|FileEntrySync|FileException|FileList|FileReader|FileReaderSync|FileSystem|FileSystemSync\n |FontFace|FormData|GainNode|Gamepad|GamepadButton|GamepadEvent|Geolocation|GlobalEventHandlers|HTMLAnchorElement\n |HTMLAreaElement|HTMLAudioElement|HTMLBRElement|HTMLBaseElement|HTMLBodyElement|HTMLButtonElement|HTMLCanvasElement\n |HTMLCollection|HTMLContentElement|HTMLDListElement|HTMLDataElement|HTMLDataListElement|HTMLDialogElement|HTMLDivElement\n |HTMLDocument|HTMLElement|HTMLEmbedElement|HTMLFieldSetElement|HTMLFontElement|HTMLFormControlsCollection|HTMLFormElement\n |HTMLHRElement|HTMLHeadElement|HTMLHeadingElement|HTMLHtmlElement|HTMLIFrameElement|HTMLImageElement|HTMLInputElement\n |HTMLKeygenElement|HTMLLIElement|HTMLLabelElement|HTMLLegendElement|HTMLLinkElement|HTMLMapElement|HTMLMediaElement\n |HTMLMetaElement|HTMLMeterElement|HTMLModElement|HTMLOListElement|HTMLObjectElement|HTMLOptGroupElement|HTMLOptionElement\n |HTMLOptionsCollection|HTMLOutputElement|HTMLParagraphElement|HTMLParamElement|HTMLPreElement|HTMLProgressElement\n |HTMLQuoteElement|HTMLScriptElement|HTMLSelectElement|HTMLShadowElement|HTMLSourceElement|HTMLSpanElement|HTMLStyleElement\n |HTMLTableCaptionElement|HTMLTableCellElement|HTMLTableColElement|HTMLTableDataCellElement|HTMLTableElement|HTMLTableHeaderCellElement\n |HTMLTableRowElement|HTMLTableSectionElement|HTMLTextAreaElement|HTMLTimeElement|HTMLTitleElement|HTMLTrackElement\n |HTMLUListElement|HTMLUnknownElement|HTMLVideoElement|HashChangeEvent|History|IDBCursor|IDBCursorWithValue|IDBDatabase\n |IDBEnvironment|IDBFactory|IDBIndex|IDBKeyRange|IDBMutableFile|IDBObjectStore|IDBOpenDBRequest|IDBRequest|IDBTransaction\n |IDBVersionChangeEvent|IIRFilterNode|IdentityManager|ImageBitmap|ImageBitmapFactories|ImageData|Index|InputDeviceCapabilities\n |InputEvent|InstallEvent|InstallTrigger|KeyboardEvent|LinkStyle|LocalFileSystem|LocalFileSystemSync|Location|MIDIAccess\n |MIDIConnectionEvent|MIDIInput|MIDIInputMap|MIDIOutputMap|MediaElementAudioSourceNode|MediaError|MediaKeyMessageEvent\n |MediaKeySession|MediaKeyStatusMap|MediaKeySystemAccess|MediaKeySystemConfiguration|MediaKeys|MediaRecorder|MediaStream\n |MediaStreamAudioDestinationNode|MediaStreamAudioSourceNode|MessageChannel|MessageEvent|MessagePort|MouseEvent\n |MutationObserver|MutationRecord|NamedNodeMap|Navigator|NavigatorConcurrentHardware|NavigatorGeolocation|NavigatorID\n |NavigatorLanguage|NavigatorOnLine|Node|NodeFilter|NodeIterator|NodeList|NonDocumentTypeChildNode|Notification\n |OfflineAudioCompletionEvent|OfflineAudioContext|OscillatorNode|PageTransitionEvent|PannerNode|ParentNode|PasswordCredential\n |Path2D|PaymentAddress|PaymentRequest|PaymentResponse|Performance|PerformanceEntry|PerformanceFrameTiming|PerformanceMark\n |PerformanceMeasure|PerformanceNavigation|PerformanceNavigationTiming|PerformanceObserver|PerformanceObserverEntryList\n |PerformanceResourceTiming|PerformanceTiming|PeriodicSyncEvent|PeriodicWave|Plugin|Point|PointerEvent|PopStateEvent\n |PortCollection|Position|PositionError|PositionOptions|PresentationConnectionClosedEvent|PresentationConnectionList\n |PresentationReceiver|ProcessingInstruction|ProgressEvent|PromiseRejectionEvent|PushEvent|PushRegistrationManager\n |RTCCertificate|RTCConfiguration|RTCPeerConnection|RTCSessionDescriptionCallback|RTCStatsReport|RadioNodeList|RandomSource\n |Range|ReadableByteStream|RenderingContext|SVGAElement|SVGAngle|SVGAnimateColorElement|SVGAnimateElement|SVGAnimateMotionElement\n |SVGAnimateTransformElement|SVGAnimatedAngle|SVGAnimatedBoolean|SVGAnimatedEnumeration|SVGAnimatedInteger|SVGAnimatedLength\n |SVGAnimatedLengthList|SVGAnimatedNumber|SVGAnimatedNumberList|SVGAnimatedPoints|SVGAnimatedPreserveAspectRatio\n |SVGAnimatedRect|SVGAnimatedString|SVGAnimatedTransformList|SVGAnimationElement|SVGCircleElement|SVGClipPathElement\n |SVGCursorElement|SVGDefsElement|SVGDescElement|SVGElement|SVGEllipseElement|SVGEvent|SVGFilterElement|SVGFontElement\n |SVGFontFaceElement|SVGFontFaceFormatElement|SVGFontFaceNameElement|SVGFontFaceSrcElement|SVGFontFaceUriElement\n |SVGForeignObjectElement|SVGGElement|SVGGlyphElement|SVGGradientElement|SVGHKernElement|SVGImageElement|SVGLength\n |SVGLengthList|SVGLineElement|SVGLinearGradientElement|SVGMPathElement|SVGMaskElement|SVGMatrix|SVGMissingGlyphElement\n |SVGNumber|SVGNumberList|SVGPathElement|SVGPatternElement|SVGPoint|SVGPolygonElement|SVGPolylineElement|SVGPreserveAspectRatio\n |SVGRadialGradientElement|SVGRect|SVGRectElement|SVGSVGElement|SVGScriptElement|SVGSetElement|SVGStopElement|SVGStringList\n |SVGStylable|SVGStyleElement|SVGSwitchElement|SVGSymbolElement|SVGTRefElement|SVGTSpanElement|SVGTests|SVGTextElement\n |SVGTextPositioningElement|SVGTitleElement|SVGTransform|SVGTransformList|SVGTransformable|SVGUseElement|SVGVKernElement\n |SVGViewElement|ServiceWorker|ServiceWorkerContainer|ServiceWorkerGlobalScope|ServiceWorkerRegistration|ServiceWorkerState\n |ShadowRoot|SharedWorker|SharedWorkerGlobalScope|SourceBufferList|StereoPannerNode|Storage|StorageEvent|StyleSheet\n |StyleSheetList|SubtleCrypto|SyncEvent|Text|TextMetrics|TimeEvent|TimeRanges|Touch|TouchEvent|TouchList|Transferable\n |TreeWalker|UIEvent|USVString|VRDisplayCapabilities|ValidityState|WaveShaperNode|WebGL|WebGLActiveInfo|WebGLBuffer\n |WebGLContextEvent|WebGLFramebuffer|WebGLProgram|WebGLRenderbuffer|WebGLRenderingContext|WebGLShader|WebGLShaderPrecisionFormat\n |WebGLTexture|WebGLTimerQueryEXT|WebGLTransformFeedback|WebGLUniformLocation|WebGLVertexArrayObject|WebGLVertexArrayObjectOES\n |WebSocket|WebSockets|WebVTT|WheelEvent|Window|WindowBase64|WindowEventHandlers|WindowTimers|Worker|WorkerGlobalScope\n |WorkerLocation|WorkerNavigator|XMLHttpRequest|XMLHttpRequestEventTarget|XMLSerializer|XPathExpression|XPathResult\n |XSLTProcessor))\\b(?!\\$)",
2147- "captures": {
2148- "1": {
2149- "name": "support.variable.dom.js"
2150- },
2151- "2": {
2152- "name": "support.class.dom.js"
2153- }
2154- }
2155- },
2156- {
2157- "match": "(?x) (\\.) \\s* (?:\n (ATTRIBUTE_NODE|CDATA_SECTION_NODE|COMMENT_NODE|DOCUMENT_FRAGMENT_NODE|DOCUMENT_NODE|DOCUMENT_TYPE_NODE\n |DOMSTRING_SIZE_ERR|ELEMENT_NODE|ENTITY_NODE|ENTITY_REFERENCE_NODE|HIERARCHY_REQUEST_ERR|INDEX_SIZE_ERR\n |INUSE_ATTRIBUTE_ERR|INVALID_CHARACTER_ERR|NO_DATA_ALLOWED_ERR|NO_MODIFICATION_ALLOWED_ERR|NOT_FOUND_ERR\n |NOT_SUPPORTED_ERR|NOTATION_NODE|PROCESSING_INSTRUCTION_NODE|TEXT_NODE|WRONG_DOCUMENT_ERR)\n |\n (_content|[xyz]|abbr|above|accept|acceptCharset|accessKey|action|align|[av]Link(?:color)?|all|alt|anchors|appCodeName\n |appCore|applets|appMinorVersion|appName|appVersion|archive|areas|arguments|attributes|availHeight|availLeft|availTop\n |availWidth|axis|background|backgroundColor|backgroundImage|below|bgColor|body|border|borderBottomWidth|borderColor\n |borderLeftWidth|borderRightWidth|borderStyle|borderTopWidth|borderWidth|bottom|bufferDepth|callee|caller|caption\n |cellPadding|cells|cellSpacing|ch|characterSet|charset|checked|childNodes|chOff|cite|classes|className|clear\n |clientInformation|clip|clipBoardData|closed|code|codeBase|codeType|color|colorDepth|cols|colSpan|compact|complete\n |components|content|controllers|cookie|cookieEnabled|cords|cpuClass|crypto|current|data|dateTime|declare|defaultCharset\n |defaultChecked|defaultSelected|defaultStatus|defaultValue|defaultView|defer|description|dialogArguments|dialogHeight\n |dialogLeft|dialogTop|dialogWidth|dir|directories|disabled|display|docmain|doctype|documentElement|elements|embeds\n |enabledPlugin|encoding|enctype|entities|event|expando|external|face|fgColor|filename|firstChild|fontFamily|fontSize\n |fontWeight|form|formName|forms|frame|frameBorder|frameElement|frames|hasFocus|hash|headers|height|history|host\n |hostname|href|hreflang|hspace|htmlFor|httpEquiv|id|ids|ignoreCase|images|implementation|index|innerHeight|innerWidth\n |input|isMap|label|lang|language|lastChild|lastIndex|lastMatch|lastModified|lastParen|layer[sXY]|left|leftContext\n |lineHeight|link|linkColor|links|listStyleType|localName|location|locationbar|longDesc|lowsrc|lowSrc|marginBottom\n |marginHeight|marginLeft|marginRight|marginTop|marginWidth|maxLength|media|menubar|method|mimeTypes|multiline|multiple\n |name|nameProp|namespaces|namespaceURI|next|nextSibling|nodeName|nodeType|nodeValue|noHref|noResize|noShade|notationName\n |notations|noWrap|object|offscreenBuffering|onLine|onreadystatechange|opener|opsProfile|options|oscpu|outerHeight\n |outerWidth|ownerDocument|paddingBottom|paddingLeft|paddingRight|paddingTop|page[XY]|page[XY]Offset|parent|parentLayer\n |parentNode|parentWindow|pathname|personalbar|pixelDepth|pkcs11|platform|plugins|port|prefix|previous|previousDibling\n |product|productSub|profile|profileend|prompt|prompter|protocol|publicId|readOnly|readyState|referrer|rel|responseText\n |responseXML|rev|right|rightContext|rowIndex|rows|rowSpan|rules|scheme|scope|screen[XY]|screenLeft|screenTop|scripts\n |scrollbars|scrolling|sectionRowIndex|security|securityPolicy|selected|selectedIndex|selection|self|shape|siblingAbove\n |siblingBelow|size|source|specified|standby|start|status|statusbar|statusText|style|styleSheets|suffixes|summary\n |systemId|systemLanguage|tagName|tags|target|tBodies|text|textAlign|textDecoration|textIndent|textTransform|tFoot|tHead\n |title|toolbar|top|type|undefined|uniqueID|updateInterval|URL|URLUnencoded|useMap|userAgent|userLanguage|userProfile\n |vAlign|value|valueType|vendor|vendorSub|version|visibility|vspace|whiteSpace|width|X[MS]LDocument|zIndex))\\b(?!\\$|\\s*(<([^<>]|\\<[^<>]+\\>)+>\\s*)?\\()",
2158- "captures": {
2159- "1": {
2160- "name": "punctuation.accessor.js"
2161- },
2162- "2": {
2163- "name": "support.constant.dom.js"
2164- },
2165- "3": {
2166- "name": "support.variable.property.dom.js"
2167- }
2168- }
2169- },
2170- {
2171- "name": "support.class.node.js",
2172- "match": "(?x)(?<!\\.|\\$)\\b(Buffer|EventEmitter|Server|Pipe|Socket|REPLServer|ReadStream|WriteStream|Stream\n |Inflate|Deflate|InflateRaw|DeflateRaw|GZip|GUnzip|Unzip|Zip)\\b(?!\\$)"
2173- },
2174- {
2175- "name": "support.module.node.js",
2176- "match": "(?x)(?<!\\.|\\$)\\b(assert|buffer|child_process|cluster|constants|crypto|dgram|dns|domain|events|fs|http|https|net\n |os|path|punycode|querystring|readline|repl|stream|string_decoder|timers|tls|tty|url|util|vm|zlib)\\b(?!\\$)"
2177- },
2178- {
2179- "match": "(?x)(?<!\\.|\\$)\\b(process)(?:(\\.)(?:\n (arch|argv|config|connected|env|execArgv|execPath|exitCode|mainModule|pid|platform|release|stderr|stdin|stdout|title|version|versions)\n |\n (abort|chdir|cwd|disconnect|exit|[sg]ete?[gu]id|send|[sg]etgroups|initgroups|kill|memoryUsage|nextTick|umask|uptime|hrtime)\n))?\\b(?!\\$)",
2180- "captures": {
2181- "1": {
2182- "name": "support.variable.object.process.js"
2183- },
2184- "2": {
2185- "name": "punctuation.accessor.js"
2186- },
2187- "3": {
2188- "name": "support.variable.property.process.js"
2189- },
2190- "4": {
2191- "name": "support.function.process.js"
2192- }
2193- }
2194- },
2195- {
2196- "match": "(?<!\\.|\\$)\\b(?:(exports)|(module)(?:(\\.)(exports|id|filename|loaded|parent|children))?)\\b(?!\\$)",
2197- "captures": {
2198- "1": {
2199- "name": "support.type.object.module.js"
2200- },
2201- "2": {
2202- "name": "support.type.object.module.js"
2203- },
2204- "3": {
2205- "name": "punctuation.accessor.js"
2206- },
2207- "4": {
2208- "name": "support.type.object.module.js"
2209- }
2210- }
2211- },
2212- {
2213- "name": "support.variable.object.node.js",
2214- "match": "(?<!\\.|\\$)\\b(global|GLOBAL|root|__dirname|__filename)\\b(?!\\$)"
2215- },
2216- {
2217- "match": "(?x) (\\.) \\s* \n(?:\n (on(?:Rowsinserted|Rowsdelete|Rowenter|Rowexit|Resize|Resizestart|Resizeend|Reset|\n Readystatechange|Mouseout|Mouseover|Mousedown|Mouseup|Mousemove|\n Before(?:cut|deactivate|unload|update|paste|print|editfocus|activate)|\n Blur|Scrolltop|Submit|Select|Selectstart|Selectionchange|Hover|Help|\n Change|Contextmenu|Controlselect|Cut|Cellchange|Clock|Close|Deactivate|\n Datasetchanged|Datasetcomplete|Dataavailable|Drop|Drag|Dragstart|Dragover|\n Dragdrop|Dragenter|Dragend|Dragleave|Dblclick|Unload|Paste|Propertychange|Error|\n Errorupdate|Keydown|Keyup|Keypress|Focus|Load|Activate|Afterupdate|Afterprint|Abort)\n ) |\n (shift|showModelessDialog|showModalDialog|showHelp|scroll|scrollX|scrollByPages|\n scrollByLines|scrollY|scrollTo|stop|strike|sizeToContent|sidebar|signText|sort|\n sup|sub|substr|substring|splice|split|send|set(?:Milliseconds|Seconds|Minutes|Hours|\n Month|Year|FullYear|Date|UTC(?:Milliseconds|Seconds|Minutes|Hours|Month|FullYear|Date)|\n Time|Hotkeys|Cursor|ZOptions|Active|Resizable|RequestHeader)|search|slice|\n savePreferences|small|home|handleEvent|navigate|char|charCodeAt|charAt|concat|\n contextual|confirm|compile|clear|captureEvents|call|createStyleSheet|createPopup|\n createEventObject|to(?:GMTString|UTCString|String|Source|UpperCase|LowerCase|LocaleString)|\n test|taint|taintEnabled|indexOf|italics|disableExternalCapture|dump|detachEvent|unshift|\n untaint|unwatch|updateCommands|join|javaEnabled|pop|push|plugins.refresh|paddings|parse|\n print|prompt|preference|enableExternalCapture|exec|execScript|valueOf|UTC|find|file|\n fileModifiedDate|fileSize|fileCreatedDate|fileUpdatedDate|fixed|fontsize|fontcolor|\n forward|fromCharCode|watch|link|load|lastIndexOf|anchor|attachEvent|atob|apply|alert|\n abort|routeEvents|resize|resizeBy|resizeTo|recalc|returnValue|replace|reverse|reload|\n releaseCapture|releaseEvents|go|get(?:Milliseconds|Seconds|Minutes|Hours|Month|Day|Year|FullYear|\n Time|Date|TimezoneOffset|UTC(?:Milliseconds|Seconds|Minutes|Hours|Day|Month|FullYear|Date)|\n Attention|Selection|ResponseHeader|AllResponseHeaders)|moveBy|moveBelow|moveTo|\n moveToAbsolute|moveAbove|mergeAttributes|match|margins|btoa|big|bold|borderWidths|blink|back\n ) |\n (acceptNode|add|addEventListener|addTextTrack|adoptNode|after|animate|append|\n appendChild|appendData|before|blur|canPlayType|captureStream|\n caretPositionFromPoint|caretRangeFromPoint|checkValidity|clear|click|\n cloneContents|cloneNode|cloneRange|close|closest|collapse|\n compareBoundaryPoints|compareDocumentPosition|comparePoint|contains|\n convertPointFromNode|convertQuadFromNode|convertRectFromNode|createAttribute|\n createAttributeNS|createCaption|createCDATASection|createComment|\n createContextualFragment|createDocument|createDocumentFragment|\n createDocumentType|createElement|createElementNS|createEntityReference|\n createEvent|createExpression|createHTMLDocument|createNodeIterator|\n createNSResolver|createProcessingInstruction|createRange|createShadowRoot|\n createTBody|createTextNode|createTFoot|createTHead|createTreeWalker|delete|\n deleteCaption|deleteCell|deleteContents|deleteData|deleteRow|deleteTFoot|\n deleteTHead|detach|disconnect|dispatchEvent|elementFromPoint|elementsFromPoint|\n enableStyleSheetsForSet|entries|evaluate|execCommand|exitFullscreen|\n exitPointerLock|expand|extractContents|fastSeek|firstChild|focus|forEach|get|\n getAll|getAnimations|getAttribute|getAttributeNames|getAttributeNode|\n getAttributeNodeNS|getAttributeNS|getBoundingClientRect|getBoxQuads|\n getClientRects|getContext|getDestinationInsertionPoints|getElementById|\n getElementsByClassName|getElementsByName|getElementsByTagName|\n getElementsByTagNameNS|getItem|getNamedItem|getSelection|getStartDate|\n getVideoPlaybackQuality|has|hasAttribute|hasAttributeNS|hasAttributes|\n hasChildNodes|hasFeature|hasFocus|importNode|initEvent|insertAdjacentElement|\n insertAdjacentHTML|insertAdjacentText|insertBefore|insertCell|insertData|\n insertNode|insertRow|intersectsNode|isDefaultNamespace|isEqualNode|\n isPointInRange|isSameNode|item|key|keys|lastChild|load|lookupNamespaceURI|\n lookupPrefix|matches|move|moveAttribute|moveAttributeNode|moveChild|\n moveNamedItem|namedItem|nextNode|nextSibling|normalize|observe|open|\n parentNode|pause|play|postMessage|prepend|preventDefault|previousNode|\n previousSibling|probablySupportsContext|queryCommandEnabled|\n queryCommandIndeterm|queryCommandState|queryCommandSupported|queryCommandValue|\n querySelector|querySelectorAll|registerContentHandler|registerElement|\n registerProtocolHandler|releaseCapture|releaseEvents|remove|removeAttribute|\n removeAttributeNode|removeAttributeNS|removeChild|removeEventListener|\n removeItem|replace|replaceChild|replaceData|replaceWith|reportValidity|\n requestFullscreen|requestPointerLock|reset|scroll|scrollBy|scrollIntoView|\n scrollTo|seekToNextFrame|select|selectNode|selectNodeContents|set|setAttribute|\n setAttributeNode|setAttributeNodeNS|setAttributeNS|setCapture|\n setCustomValidity|setEnd|setEndAfter|setEndBefore|setItem|setNamedItem|\n setRangeText|setSelectionRange|setSinkId|setStart|setStartAfter|setStartBefore|\n slice|splitText|stepDown|stepUp|stopImmediatePropagation|stopPropagation|\n submit|substringData|supports|surroundContents|takeRecords|terminate|toBlob|\n toDataURL|toggle|toString|values|write|writeln\n )\n)(?=\\s*\\()",
2218- "captures": {
2219- "1": {
2220- "name": "punctuation.accessor.js"
2221- },
2222- "2": {
2223- "name": "support.function.event-handler.js"
2224- },
2225- "3": {
2226- "name": "support.function.js"
2227- },
2228- "4": {
2229- "name": "support.function.dom.js"
2230- }
2231- }
2232- }
2233- ]
2234- },
2235- "function-call": {
2236- "begin": "(?=(\\.\\s*)?([_$[:alpha:]][_$[:alnum:]]*)\\s*(<([^<>]|\\<[^<>]+\\>)+>\\s*)?\\()",
2237- "end": "(?<=\\))(?!(\\.\\s*)?([_$[:alpha:]][_$[:alnum:]]*)\\s*(<([^<>]|\\<[^<>]+\\>)+>\\s*)?\\()",
2238- "patterns": [
2239- {
2240- "include": "#support-objects"
2241- },
2242- {
2243- "name": "punctuation.accessor.js",
2244- "match": "\\."
2245- },
2246- {
2247- "name": "entity.name.function.js",
2248- "match": "([_$[:alpha:]][_$[:alnum:]]*)"
2249- },
2250- {
2251- "include": "#comment"
2252- },
2253- {
2254- "name": "meta.type.parameters.js",
2255- "begin": "\\<",
2256- "beginCaptures": {
2257- "0": {
2258- "name": "punctuation.definition.typeparameters.begin.js"
2259- }
2260- },
2261- "end": "\\>",
2262- "endCaptures": {
2263- "0": {
2264- "name": "punctuation.definition.typeparameters.end.js"
2265- }
2266- },
2267- "patterns": [
2268- {
2269- "include": "#type"
2270- },
2271- {
2272- "include": "#punctuation-comma"
2273- }
2274- ]
2275- },
2276- {
2277- "include": "#paren-expression"
2278- }
2279- ]
2280- },
2281- "identifiers": {
2282- "patterns": [
2283- {
2284- "name": "support.class.js",
2285- "match": "([_$[:alpha:]][_$[:alnum:]]*)(?=\\s*\\.\\s*prototype\\b(?!\\$))"
2286- },
2287- {
2288- "match": "(?x)(\\.)\\s*(?:\n ([[:upper:]][_$[:digit:][:upper:]]*) |\n ([_$[:alpha:]][_$[:alnum:]]*)\n)(?=\\s*\\.\\s*[_$[:alpha:]][_$[:alnum:]]*)",
2289- "captures": {
2290- "1": {
2291- "name": "punctuation.accessor.js"
2292- },
2293- "2": {
2294- "name": "constant.other.object.property.js"
2295- },
2296- "3": {
2297- "name": "variable.other.object.property.js"
2298- }
2299- }
2300- },
2301- {
2302- "match": "(?x)(?:(\\.)\\s*)?([_$[:alpha:]][_$[:alnum:]]*)(?=\\s*=\\s*( (async\\s+)|(function\\s*[(<])|(function\\s+)| ([_$[:alpha:]][_$[:alnum:]]*\\s*=>)| ((<([^<>]|\\<[^<>]+\\>)+>\\s*)?\\(([^()]|\\([^()]*\\))*\\)(\\s*:\\s*(.)*)?\\s*=>)))",
2303- "captures": {
2304- "1": {
2305- "name": "punctuation.accessor.js"
2306- },
2307- "2": {
2308- "name": "entity.name.function.js"
2309- }
2310- }
2311- },
2312- {
2313- "match": "(\\.)\\s*([[:upper:]][_$[:digit:][:upper:]]*)(?![_$[:alnum:]])",
2314- "captures": {
2315- "1": {
2316- "name": "punctuation.accessor.js"
2317- },
2318- "2": {
2319- "name": "constant.other.property.js"
2320- }
2321- }
2322- },
2323- {
2324- "match": "(\\.)\\s*([_$[:alpha:]][_$[:alnum:]]*)",
2325- "captures": {
2326- "1": {
2327- "name": "punctuation.accessor.js"
2328- },
2329- "2": {
2330- "name": "variable.other.property.js"
2331- }
2332- }
2333- },
2334- {
2335- "match": "(?x)(?:\n ([[:upper:]][_$[:digit:][:upper:]]*) |\n ([_$[:alpha:]][_$[:alnum:]]*)\n)(?=\\s*\\.\\s*[_$[:alpha:]][_$[:alnum:]]*)",
2336- "captures": {
2337- "1": {
2338- "name": "constant.other.object.js"
2339- },
2340- "2": {
2341- "name": "variable.other.object.js"
2342- }
2343- }
2344- },
2345- {
2346- "name": "constant.other.js",
2347- "match": "([[:upper:]][_$[:digit:][:upper:]]*)(?![_$[:alnum:]])"
2348- },
2349- {
2350- "name": "variable.other.readwrite.js",
2351- "match": "[_$[:alpha:]][_$[:alnum:]]*"
2352- }
2353- ]
2354- },
2355- "cast": {
2356- "patterns": [
2357- {
2358- "include": "#jsx"
2359- }
2360- ]
2361- },
2362- "new-expr": {
2363- "name": "new.expr.js",
2364- "begin": "(?<!\\.|\\$)\\b(new)\\b(?!\\$)",
2365- "beginCaptures": {
2366- "1": {
2367- "name": "keyword.operator.new.js"
2368- }
2369- },
2370- "end": "(?<=\\))|(?=[;),]|$|((?<!\\.|\\$)\\bnew\\b(?!\\$)))",
2371- "patterns": [
2372- {
2373- "include": "#paren-expression"
2374- },
2375- {
2376- "include": "#class-or-interface-declaration"
2377- },
2378- {
2379- "include": "#type"
2380- }
2381- ]
2382- },
2383- "object-member": {
2384- "patterns": [
2385- {
2386- "include": "#comment"
2387- },
2388- {
2389- "include": "#method-declaration"
2390- },
2391- {
2392- "name": "meta.object.member.js",
2393- "begin": "(?=(?:(?:\\'[^']*\\')|(?:\\\"[^\"]*\\\")|(?:\\[([^\\[\\]]|\\[[^\\[\\]]+\\])+\\]))\\s*:)",
2394- "end": "(?=,|\\})",
2395- "patterns": [
2396- {
2397- "name": "meta.object-literal.key.js",
2398- "begin": "(?=(?:(?:\\'[^']*\\')|(?:\\\"[^\"]*\\\")|(?:\\[([^\\[\\]]|\\[[^\\[\\]]+\\])+\\]))\\s*:)",
2399- "end": ":",
2400- "endCaptures": {
2401- "0": {
2402- "name": "punctuation.separator.key-value.js"
2403- }
2404- },
2405- "patterns": [
2406- {
2407- "include": "#string"
2408- },
2409- {
2410- "include": "#array-literal"
2411- }
2412- ]
2413- },
2414- {
2415- "include": "#expression"
2416- }
2417- ]
2418- },
2419- {
2420- "name": "meta.object.member.js",
2421- "begin": "(?x)(?:([_$[:alpha:]][_$[:alnum:]]*)\\s*(:)(?=\\s*( (async\\s+)|(function\\s*[(<])|(function\\s+)| ([_$[:alpha:]][_$[:alnum:]]*\\s*=>)| ((<([^<>]|\\<[^<>]+\\>)+>\\s*)?\\(([^()]|\\([^()]*\\))*\\)(\\s*:\\s*(.)*)?\\s*=>))))",
2422- "beginCaptures": {
2423- "0": {
2424- "name": "meta.object-literal.key.js"
2425- },
2426- "1": {
2427- "name": "entity.name.function.js"
2428- },
2429- "2": {
2430- "name": "punctuation.separator.key-value.js"
2431- }
2432- },
2433- "end": "(?=,|\\})",
2434- "patterns": [
2435- {
2436- "include": "#expression"
2437- }
2438- ]
2439- },
2440- {
2441- "name": "meta.object.member.js",
2442- "begin": "(?:[_$[:alpha:]][_$[:alnum:]]*)\\s*(:)",
2443- "beginCaptures": {
2444- "0": {
2445- "name": "meta.object-literal.key.js"
2446- },
2447- "1": {
2448- "name": "punctuation.separator.key-value.js"
2449- }
2450- },
2451- "end": "(?=,|\\})",
2452- "patterns": [
2453- {
2454- "include": "#expression"
2455- }
2456- ]
2457- },
2458- {
2459- "name": "meta.object.member.js",
2460- "begin": "\\.\\.\\.",
2461- "beginCaptures": {
2462- "0": {
2463- "name": "keyword.operator.spread.js"
2464- }
2465- },
2466- "end": "(?=,|\\})",
2467- "patterns": [
2468- {
2469- "include": "#expression"
2470- }
2471- ]
2472- },
2473- {
2474- "name": "meta.object.member.js",
2475- "match": "([_$[:alpha:]][_$[:alnum:]]*)\\s*(?=,|\\}|$)",
2476- "captures": {
2477- "1": {
2478- "name": "variable.other.readwrite.js"
2479- }
2480- }
2481- },
2482- {
2483- "include": "#punctuation-comma"
2484- }
2485- ]
2486- },
2487- "expression-operators": {
2488- "patterns": [
2489- {
2490- "name": "keyword.control.flow.js",
2491- "match": "(?<!\\.|\\$)\\b(await)\\b(?!\\$)"
2492- },
2493- {
2494- "name": "keyword.operator.expression.delete.js",
2495- "match": "(?<!\\.|\\$)\\bdelete\\b(?!\\$)"
2496- },
2497- {
2498- "name": "keyword.operator.expression.in.js",
2499- "match": "(?<!\\.|\\$)\\bin\\b(?!\\$)"
2500- },
2501- {
2502- "name": "keyword.operator.expression.of.js",
2503- "match": "(?<!\\.|\\$)\\bof\\b(?!\\$)"
2504- },
2505- {
2506- "name": "keyword.operator.expression.instanceof.js",
2507- "match": "(?<!\\.|\\$)\\binstanceof\\b(?!\\$)"
2508- },
2509- {
2510- "name": "keyword.operator.new.js",
2511- "match": "(?<!\\.|\\$)\\bnew\\b(?!\\$)"
2512- },
2513- {
2514- "include": "#typeof-operator"
2515- },
2516- {
2517- "name": "keyword.operator.expression.void.js",
2518- "match": "(?<!\\.|\\$)\\bvoid\\b(?!\\$)"
2519- },
2520- {
2521- "begin": "(?<!\\.|\\$)\\bas\\b(?!\\$)",
2522- "beginCaptures": {
2523- "0": {
2524- "name": "keyword.control.as.js"
2525- }
2526- },
2527- "end": "(?=$|[;,:})\\]])",
2528- "patterns": [
2529- {
2530- "include": "#type"
2531- }
2532- ]
2533- },
2534- {
2535- "name": "keyword.operator.spread.js",
2536- "match": "\\.\\.\\."
2537- },
2538- {
2539- "name": "keyword.operator.assignment.compound.js",
2540- "match": "\\*=|(?<!\\()/=|%=|\\+=|\\-="
2541- },
2542- {
2543- "name": "keyword.operator.assignment.compound.bitwise.js",
2544- "match": "\\&=|\\^=|<<=|>>=|>>>=|\\|="
2545- },
2546- {
2547- "name": "keyword.operator.bitwise.shift.js",
2548- "match": "<<|>>>|>>"
2549- },
2550- {
2551- "name": "keyword.operator.comparison.js",
2552- "match": "===|!==|==|!="
2553- },
2554- {
2555- "name": "keyword.operator.relational.js",
2556- "match": "<=|>=|<>|<|>"
2557- },
2558- {
2559- "name": "keyword.operator.logical.js",
2560- "match": "\\!|&&|\\|\\|"
2561- },
2562- {
2563- "name": "keyword.operator.bitwise.js",
2564- "match": "\\&|~|\\^|\\|"
2565- },
2566- {
2567- "name": "keyword.operator.assignment.js",
2568- "match": "\\="
2569- },
2570- {
2571- "name": "keyword.operator.decrement.js",
2572- "match": "--"
2573- },
2574- {
2575- "name": "keyword.operator.increment.js",
2576- "match": "\\+\\+"
2577- },
2578- {
2579- "name": "keyword.operator.arithmetic.js",
2580- "match": "%|\\*|/|-|\\+"
2581- },
2582- {
2583- "match": "(?<=[_$[:alnum:]])\\s*(/)(?![/*])",
2584- "captures": {
2585- "1": {
2586- "name": "keyword.operator.arithmetic.js"
2587- }
2588- }
2589- }
2590- ]
2591- },
2592- "typeof-operator": {
2593- "name": "keyword.operator.expression.typeof.js",
2594- "match": "(?<!\\.|\\$)\\btypeof\\b(?!\\$)"
2595- },
2596- "arrow-function": {
2597- "patterns": [
2598- {
2599- "name": "meta.arrow.js",
2600- "match": "(?<!\\.|\\$)(\\basync)(?=\\s*[<(])",
2601- "captures": {
2602- "1": {
2603- "name": "storage.modifier.async.js"
2604- }
2605- }
2606- },
2607- {
2608- "name": "meta.arrow.js",
2609- "match": "(?:(?<!\\.|\\$)(\\basync)\\s*)?([_$[:alpha:]][_$[:alnum:]]*)\\s*(?==>)",
2610- "captures": {
2611- "1": {
2612- "name": "storage.modifier.async.js"
2613- },
2614- "2": {
2615- "name": "variable.parameter.js"
2616- }
2617- }
2618- },
2619- {
2620- "name": "meta.arrow.js",
2621- "begin": "(?x)\\s*(?=(<([^<>]|\\<[^<>]+\\>)+>\\s*)?\\(([^()]|\\([^()]*\\))*\\)(\\s*:\\s*(.)*)?\\s*=>)",
2622- "end": "(?==>)",
2623- "patterns": [
2624- {
2625- "include": "#comment"
2626- },
2627- {
2628- "include": "#type-parameters"
2629- },
2630- {
2631- "include": "#function-parameters"
2632- },
2633- {
2634- "include": "#arrow-return-type"
2635- }
2636- ]
2637- },
2638- {
2639- "name": "meta.arrow.js",
2640- "begin": "=>",
2641- "beginCaptures": {
2642- "0": {
2643- "name": "storage.type.function.arrow.js"
2644- }
2645- },
2646- "end": "(?<=\\})|((?!\\{)(?=\\S))",
2647- "patterns": [
2648- {
2649- "include": "#decl-block"
2650- },
2651- {
2652- "include": "#expression"
2653- }
2654- ]
2655- }
2656- ]
2657- },
2658- "arrow-return-type": {
2659- "name": "meta.return.type.arrow.js",
2660- "begin": "(?<=\\))\\s*(:)",
2661- "beginCaptures": {
2662- "1": {
2663- "name": "keyword.operator.type.annotation.js"
2664- }
2665- },
2666- "end": "(?<!:)((?=$)|(?==>|;|//))",
2667- "patterns": [
2668- {
2669- "include": "#type-predicate-operator"
2670- },
2671- {
2672- "include": "#type"
2673- }
2674- ]
2675- },
2676- "punctuation-comma": {
2677- "name": "punctuation.separator.comma.js",
2678- "match": ","
2679- },
2680- "punctuation-semicolon": {
2681- "name": "punctuation.terminator.statement.js",
2682- "match": ";"
2683- },
2684- "punctuation-accessor": {
2685- "name": "punctuation.accessor.js",
2686- "match": "\\."
2687- },
2688- "paren-expression": {
2689- "begin": "\\(",
2690- "beginCaptures": {
2691- "0": {
2692- "name": "meta.brace.round.js"
2693- }
2694- },
2695- "end": "\\)",
2696- "endCaptures": {
2697- "0": {
2698- "name": "meta.brace.round.js"
2699- }
2700- },
2701- "patterns": [
2702- {
2703- "include": "#expression"
2704- },
2705- {
2706- "include": "#punctuation-comma"
2707- }
2708- ]
2709- },
2710- "qstring-double": {
2711- "name": "string.quoted.double.js",
2712- "begin": "\"",
2713- "beginCaptures": {
2714- "0": {
2715- "name": "punctuation.definition.string.begin.js"
2716- }
2717- },
2718- "end": "(\")|((?:[^\\\\\\n])$)",
2719- "endCaptures": {
2720- "1": {
2721- "name": "punctuation.definition.string.end.js"
2722- },
2723- "2": {
2724- "name": "invalid.illegal.newline.js"
2725- }
2726- },
2727- "patterns": [
2728- {
2729- "include": "#string-character-escape"
2730- }
2731- ]
2732- },
2733- "qstring-single": {
2734- "name": "string.quoted.single.js",
2735- "begin": "'",
2736- "beginCaptures": {
2737- "0": {
2738- "name": "punctuation.definition.string.begin.js"
2739- }
2740- },
2741- "end": "(\\')|((?:[^\\\\\\n])$)",
2742- "endCaptures": {
2743- "1": {
2744- "name": "punctuation.definition.string.end.js"
2745- },
2746- "2": {
2747- "name": "invalid.illegal.newline.js"
2748- }
2749- },
2750- "patterns": [
2751- {
2752- "include": "#string-character-escape"
2753- }
2754- ]
2755- },
2756- "regex": {
2757- "patterns": [
2758- {
2759- "name": "string.regex.js",
2760- "begin": "(?<=[=(:,\\[?+!]|return|case|=>|&&|\\|\\||\\*\\/)\\s*(/)(?![/*])(?=(?:[^/\\\\\\[]|\\\\.|\\[([^\\]\\\\]|\\\\.)+\\])+/(?![/*])[gimy]*(?!\\s*[a-zA-Z0-9_$]))",
2761- "beginCaptures": {
2762- "1": {
2763- "name": "punctuation.definition.string.begin.js"
2764- }
2765- },
2766- "end": "(/)([gimuy]*)",
2767- "endCaptures": {
2768- "1": {
2769- "name": "punctuation.definition.string.end.js"
2770- },
2771- "2": {
2772- "name": "keyword.other.js"
2773- }
2774- },
2775- "patterns": [
2776- {
2777- "include": "#regexp"
2778- }
2779- ]
2780- },
2781- {
2782- "name": "string.regex.js",
2783- "begin": "/(?![/*])(?=(?:[^/\\\\\\[]|\\\\.|\\[([^\\]\\\\]|\\\\.)+\\])+/(?![/*])[gimy]*(?!\\s*[a-zA-Z0-9_$]))",
2784- "beginCaptures": {
2785- "0": {
2786- "name": "punctuation.definition.string.begin.js"
2787- }
2788- },
2789- "end": "(/)([gimuy]*)",
2790- "endCaptures": {
2791- "1": {
2792- "name": "punctuation.definition.string.end.js"
2793- },
2794- "2": {
2795- "name": "keyword.other.js"
2796- }
2797- },
2798- "patterns": [
2799- {
2800- "include": "#regexp"
2801- }
2802- ]
2803- }
2804- ]
2805- },
2806- "regexp": {
2807- "patterns": [
2808- {
2809- "name": "keyword.control.anchor.regexp",
2810- "match": "\\\\[bB]|\\^|\\$"
2811- },
2812- {
2813- "name": "keyword.other.back-reference.regexp",
2814- "match": "\\\\[1-9]\\d*"
2815- },
2816- {
2817- "name": "keyword.operator.quantifier.regexp",
2818- "match": "[?+*]|\\{(\\d+,\\d+|\\d+,|,\\d+|\\d+)\\}\\??"
2819- },
2820- {
2821- "name": "keyword.operator.or.regexp",
2822- "match": "\\|"
2823- },
2824- {
2825- "name": "meta.group.assertion.regexp",
2826- "begin": "(\\()((\\?=)|(\\?!))",
2827- "beginCaptures": {
2828- "1": {
2829- "name": "punctuation.definition.group.regexp"
2830- },
2831- "2": {
2832- "name": "punctuation.definition.group.assertion.regexp"
2833- },
2834- "3": {
2835- "name": "meta.assertion.look-ahead.regexp"
2836- },
2837- "4": {
2838- "name": "meta.assertion.negative-look-ahead.regexp"
2839- }
2840- },
2841- "end": "(\\))",
2842- "endCaptures": {
2843- "1": {
2844- "name": "punctuation.definition.group.regexp"
2845- }
2846- },
2847- "patterns": [
2848- {
2849- "include": "#regexp"
2850- }
2851- ]
2852- },
2853- {
2854- "name": "meta.group.regexp",
2855- "begin": "\\((\\?:)?",
2856- "beginCaptures": {
2857- "0": {
2858- "name": "punctuation.definition.group.regexp"
2859- },
2860- "1": {
2861- "name": "punctuation.definition.group.capture.regexp"
2862- }
2863- },
2864- "end": "\\)",
2865- "endCaptures": {
2866- "0": {
2867- "name": "punctuation.definition.group.regexp"
2868- }
2869- },
2870- "patterns": [
2871- {
2872- "include": "#regexp"
2873- }
2874- ]
2875- },
2876- {
2877- "name": "constant.other.character-class.set.regexp",
2878- "begin": "(\\[)(\\^)?",
2879- "beginCaptures": {
2880- "1": {
2881- "name": "punctuation.definition.character-class.regexp"
2882- },
2883- "2": {
2884- "name": "keyword.operator.negation.regexp"
2885- }
2886- },
2887- "end": "(\\])",
2888- "endCaptures": {
2889- "1": {
2890- "name": "punctuation.definition.character-class.regexp"
2891- }
2892- },
2893- "patterns": [
2894- {
2895- "name": "constant.other.character-class.range.regexp",
2896- "match": "(?:.|(\\\\(?:[0-7]{3}|x\\h\\h|u\\h\\h\\h\\h))|(\\\\c[A-Z])|(\\\\.))\\-(?:[^\\]\\\\]|(\\\\(?:[0-7]{3}|x\\h\\h|u\\h\\h\\h\\h))|(\\\\c[A-Z])|(\\\\.))",
2897- "captures": {
2898- "1": {
2899- "name": "constant.character.numeric.regexp"
2900- },
2901- "2": {
2902- "name": "constant.character.control.regexp"
2903- },
2904- "3": {
2905- "name": "constant.character.escape.backslash.regexp"
2906- },
2907- "4": {
2908- "name": "constant.character.numeric.regexp"
2909- },
2910- "5": {
2911- "name": "constant.character.control.regexp"
2912- },
2913- "6": {
2914- "name": "constant.character.escape.backslash.regexp"
2915- }
2916- }
2917- },
2918- {
2919- "include": "#regex-character-class"
2920- }
2921- ]
2922- },
2923- {
2924- "include": "#regex-character-class"
2925- }
2926- ]
2927- },
2928- "regex-character-class": {
2929- "patterns": [
2930- {
2931- "name": "constant.other.character-class.regexp",
2932- "match": "\\\\[wWsSdDtrnvf]|\\."
2933- },
2934- {
2935- "name": "constant.character.numeric.regexp",
2936- "match": "\\\\([0-7]{3}|x\\h\\h|u\\h\\h\\h\\h)"
2937- },
2938- {
2939- "name": "constant.character.control.regexp",
2940- "match": "\\\\c[A-Z]"
2941- },
2942- {
2943- "name": "constant.character.escape.backslash.regexp",
2944- "match": "\\\\."
2945- }
2946- ]
2947- },
2948- "string": {
2949- "patterns": [
2950- {
2951- "include": "#qstring-single"
2952- },
2953- {
2954- "include": "#qstring-double"
2955- }
2956- ]
2957- },
2958- "template": {
2959- "name": "string.template.js",
2960- "begin": "([_$[:alpha:]][_$[:alnum:]]*)?(`)",
2961- "beginCaptures": {
2962- "1": {
2963- "name": "entity.name.function.tagged-template.js"
2964- },
2965- "2": {
2966- "name": "punctuation.definition.string.template.begin.js"
2967- }
2968- },
2969- "end": "`",
2970- "endCaptures": {
2971- "0": {
2972- "name": "punctuation.definition.string.template.end.js"
2973- }
2974- },
2975- "patterns": [
2976- {
2977- "include": "#template-substitution-element"
2978- },
2979- {
2980- "include": "#string-character-escape"
2981- }
2982- ]
2983- },
2984- "string-character-escape": {
2985- "name": "constant.character.escape.js",
2986- "match": "\\\\(x\\h{2}|[0-2][0-7]{0,2}|3[0-6][0-7]?|37[0-7]?|[4-7][0-7]?|.|$)"
2987- },
2988- "template-substitution-element": {
2989- "name": "meta.template.expression.js",
2990- "begin": "\\$\\{",
2991- "beginCaptures": {
2992- "0": {
2993- "name": "punctuation.definition.template-expression.begin.js"
2994- }
2995- },
2996- "end": "\\}",
2997- "endCaptures": {
2998- "0": {
2999- "name": "punctuation.definition.template-expression.end.js"
3000- }
3001- },
3002- "patterns": [
3003- {
3004- "include": "#expression"
3005- }
3006- ]
3007- },
3008- "literal": {
3009- "name": "literal.js",
3010- "patterns": [
3011- {
3012- "include": "#numeric-literal"
3013- },
3014- {
3015- "include": "#boolean-literal"
3016- },
3017- {
3018- "include": "#null-literal"
3019- },
3020- {
3021- "include": "#undefined-literal"
3022- },
3023- {
3024- "include": "#numericConstant-literal"
3025- },
3026- {
3027- "include": "#array-literal"
3028- },
3029- {
3030- "include": "#this-literal"
3031- },
3032- {
3033- "include": "#super-literal"
3034- }
3035- ]
3036- },
3037- "array-literal": {
3038- "name": "meta.array.literal.js",
3039- "begin": "\\[",
3040- "beginCaptures": {
3041- "0": {
3042- "name": "meta.brace.square.js"
3043- }
3044- },
3045- "end": "\\]",
3046- "endCaptures": {
3047- "0": {
3048- "name": "meta.brace.square.js"
3049- }
3050- },
3051- "patterns": [
3052- {
3053- "include": "#expression"
3054- },
3055- {
3056- "include": "#punctuation-comma"
3057- }
3058- ]
3059- },
3060- "numeric-literal": {
3061- "patterns": [
3062- {
3063- "name": "constant.numeric.hex.js",
3064- "match": "\\b(?<!\\$)0(x|X)[0-9a-fA-F]+\\b(?!\\$)"
3065- },
3066- {
3067- "name": "constant.numeric.binary.js",
3068- "match": "\\b(?<!\\$)0(b|B)[01]+\\b(?!\\$)"
3069- },
3070- {
3071- "name": "constant.numeric.octal.js",
3072- "match": "\\b(?<!\\$)0(o|O)?[0-7]+\\b(?!\\$)"
3073- },
3074- {
3075- "match": "(?x)\n(?<!\\$)(?:\n (?:\\b[0-9]+(\\.)[0-9]+[eE][+-]?[0-9]+\\b)| # 1.1E+3\n (?:\\b[0-9]+(\\.)[eE][+-]?[0-9]+\\b)| # 1.E+3\n (?:\\B(\\.)[0-9]+[eE][+-]?[0-9]+\\b)| # .1E+3\n (?:\\b[0-9]+[eE][+-]?[0-9]+\\b)| # 1E+3\n (?:\\b[0-9]+(\\.)[0-9]+\\b)| # 1.1\n (?:\\b[0-9]+(\\.)\\B)| # 1.\n (?:\\B(\\.)[0-9]+\\b)| # .1\n (?:\\b[0-9]+\\b(?!\\.)) # 1\n)(?!\\$)",
3076- "captures": {
3077- "0": {
3078- "name": "constant.numeric.decimal.js"
3079- },
3080- "1": {
3081- "name": "meta.delimiter.decimal.period.js"
3082- },
3083- "2": {
3084- "name": "meta.delimiter.decimal.period.js"
3085- },
3086- "3": {
3087- "name": "meta.delimiter.decimal.period.js"
3088- },
3089- "4": {
3090- "name": "meta.delimiter.decimal.period.js"
3091- },
3092- "5": {
3093- "name": "meta.delimiter.decimal.period.js"
3094- },
3095- "6": {
3096- "name": "meta.delimiter.decimal.period.js"
3097- }
3098- }
3099- }
3100- ]
3101- },
3102- "boolean-literal": {
3103- "patterns": [
3104- {
3105- "name": "constant.language.boolean.true.js",
3106- "match": "(?<!\\.|\\$)\\btrue\\b(?!\\$)"
3107- },
3108- {
3109- "name": "constant.language.boolean.false.js",
3110- "match": "(?<!\\.|\\$)\\bfalse\\b(?!\\$)"
3111- }
3112- ]
3113- },
3114- "null-literal": {
3115- "name": "constant.language.null.js",
3116- "match": "(?<!\\.|\\$)\\bnull\\b(?!\\$)"
3117- },
3118- "this-literal": {
3119- "name": "variable.language.this.js",
3120- "match": "(?<!\\.|\\$)\\bthis\\b(?!\\$)"
3121- },
3122- "super-literal": {
3123- "name": "variable.language.super.js",
3124- "match": "(?<!\\.|\\$)\\bsuper\\b(?!\\$)"
3125- },
3126- "undefined-literal": {
3127- "name": "constant.language.undefined.js",
3128- "match": "(?<!\\.|\\$)\\bundefined\\b(?!\\$)"
3129- },
3130- "numericConstant-literal": {
3131- "patterns": [
3132- {
3133- "name": "constant.language.nan.js",
3134- "match": "(?<!\\.|\\$)\\bNaN\\b(?!\\$)"
3135- },
3136- {
3137- "name": "constant.language.infinity.js",
3138- "match": "(?<!\\.|\\$)\\bInfinity\\b(?!\\$)"
3139- }
3140- ]
3141- },
3142- "access-modifier": {
3143- "name": "storage.modifier.js",
3144- "match": "(?<!\\.|\\$)\\b(abstract|public|protected|private|readonly|static)\\b(?!\\$)"
3145- },
3146- "property-accessor": {
3147- "name": "storage.type.property.js",
3148- "match": "(?<!\\.|\\$)\\b(get|set)\\b(?!\\$)"
3149- },
3150- "comment": {
3151- "patterns": [
3152- {
3153- "name": "comment.block.documentation.js",
3154- "begin": "/\\*\\*(?!/)",
3155- "beginCaptures": {
3156- "0": {
3157- "name": "punctuation.definition.comment.js"
3158- }
3159- },
3160- "end": "\\*/",
3161- "endCaptures": {
3162- "0": {
3163- "name": "punctuation.definition.comment.js"
3164- }
3165- },
3166- "patterns": [
3167- {
3168- "include": "#docblock"
3169- }
3170- ]
3171- },
3172- {
3173- "name": "comment.block.js",
3174- "begin": "/\\*",
3175- "beginCaptures": {
3176- "0": {
3177- "name": "punctuation.definition.comment.js"
3178- }
3179- },
3180- "end": "\\*/",
3181- "endCaptures": {
3182- "0": {
3183- "name": "punctuation.definition.comment.js"
3184- }
3185- }
3186- },
3187- {
3188- "begin": "(^[ \\t]+)?(?=//)",
3189- "beginCaptures": {
3190- "1": {
3191- "name": "punctuation.whitespace.comment.leading.js"
3192- }
3193- },
3194- "end": "(?=$)",
3195- "patterns": [
3196- {
3197- "name": "comment.line.double-slash.js",
3198- "begin": "//",
3199- "beginCaptures": {
3200- "0": {
3201- "name": "punctuation.definition.comment.js"
3202- }
3203- },
3204- "end": "(?=$)"
3205- }
3206- ]
3207- }
3208- ]
3209- },
3210- "directives": {
3211- "name": "comment.line.triple-slash.directive.js",
3212- "begin": "^(///)\\s*(?=<(reference|amd-dependency|amd-module)(\\s+(path|types|no-default-lib|name)\\s*=\\s*((\\'[^']*\\')|(\\\"[^\"]*\\\")))+\\s*/>\\s*$)",
3213- "beginCaptures": {
3214- "1": {
3215- "name": "punctuation.definition.comment.js"
3216- }
3217- },
3218- "end": "(?=$)",
3219- "patterns": [
3220- {
3221- "name": "meta.tag.js",
3222- "begin": "(<)(reference|amd-dependency|amd-module)",
3223- "beginCaptures": {
3224- "1": {
3225- "name": "punctuation.definition.tag.directive.js"
3226- },
3227- "2": {
3228- "name": "entity.name.tag.directive.js"
3229- }
3230- },
3231- "end": "/>",
3232- "endCaptures": {
3233- "0": {
3234- "name": "punctuation.definition.tag.directive.js"
3235- }
3236- },
3237- "patterns": [
3238- {
3239- "name": "entity.other.attribute-name.directive.js",
3240- "match": "path|types|no-default-lib|name"
3241- },
3242- {
3243- "name": "keyword.operator.assignment.js",
3244- "match": "="
3245- },
3246- {
3247- "include": "#string"
3248- }
3249- ]
3250- }
3251- ]
3252- },
3253- "docblock": {
3254- "patterns": [
3255- {
3256- "name": "storage.type.class.jsdoc",
3257- "match": "(?<!\\w)@(abstract|access|alias|arg|argument|async|attribute|augments|author|beta|borrows|bubbes|callback|chainable|class|classdesc|code|config|const|constant|constructor|constructs|copyright|default|defaultvalue|define|deprecated|desc|description|dict|emits|enum|event|example|exports?|extends|extension|extension_for|extensionfor|external|file|fileoverview|final|fires|for|function|global|host|ignore|implements|inherit[Dd]oc|inner|instance|interface|kind|lends|license|listens|main|member|memberof|method|mixex|mixins?|module|name|namespace|nocollapse|nosideeffects|override|overview|package|param|preserve|private|prop|property|protected|public|read[Oo]nly|record|require[ds]|returns?|see|since|static|struct|submodule|summary|template|this|throws|todo|tutorial|type|typedef|unrestricted|uses|var|variation|version|virtual|writeOnce)\\b"
3258- },
3259- {
3260- "match": "(?x)\n(?:(?<=@param)|(?<=@arg)|(?<=@argument)|(?<=@type))\n\\s+\n({(?:\n \\* | # {*} any type\n \\? | # {?} unknown type\n (?: # Check for a prefix\n \\? | # {?string} nullable type\n ! | # {!string} non-nullable type\n \\.{3} # {...string} variable number of parameters\n )?\n (?:\n \\( # Opening bracket of multiple types with parenthesis {(string|number)}\n [a-zA-Z_$]+\n (?:\n (?:\n [\\w$]*\n (?:\\[\\])? # {(string[]|number)} type application, an array of strings or a number\n ) |\n \\.?<[\\w$]+(?:,\\s+[\\w$]+)*> # {Array<string>} or {Object<string, number>} type application (optional .)\n )\n (?:\n [\\.|~] # {Foo.bar} namespaced, {string|number} multiple, {Foo~bar} class-specific callback\n [a-zA-Z_$]+\n (?:\n (?:\n [\\w$]*\n (?:\\[\\])? # {(string|number[])} type application, a string or an array of numbers\n ) |\n \\.?<[\\w$]+(?:,\\s+[\\w$]+)*> # {Array<string>} or {Object<string, number>} type application (optional .)\n )\n )*\n \\) |\n [a-zA-Z_$]+\n (?:\n (?:\n [\\w$]*\n (?:\\[\\])? # {string[]|number} type application, an array of strings or a number\n ) |\n \\.?<[\\w$]+(?:,\\s+[\\w$]+)*> # {Array<string>} or {Object<string, number>} type application (optional .)\n )\n (?:\n [\\.|~] # {Foo.bar} namespaced, {string|number} multiple, {Foo~bar} class-specific callback\n [a-zA-Z_$]+\n (?:\n [\\w$]* |\n \\.?<[\\w$]+(?:,\\s+[\\w$]+)*> # {Array<string>} or {Object<string, number>} type application (optional .)\n )\n )*\n )\n # Check for suffix\n (?:\\[\\])? # {string[]} type application, an array of strings\n =? # {string=} optional parameter\n)})\n\\s+\n(\n \\[ # [foo] optional parameter\n \\s*\n (?:\n [a-zA-Z_$][\\w$]*\n (?:\n (?:\\[\\])? # Foo[].bar properties within an array\n \\. # Foo.Bar namespaced parameter\n [a-zA-Z_$][\\w$]*\n )*\n (?:\n \\s*\n = # [foo=bar] Default parameter value\n \\s*\n [\\w$\\s]*\n )?\n )\n \\s*\n \\] |\n (?:\n [a-zA-Z_$][\\w$]*\n (?:\n (?:\\[\\])? # Foo[].bar properties within an array\n \\. # Foo.Bar namespaced parameter\n [a-zA-Z_$][\\w$]*\n )*\n )?\n)\n\\s+\n(?:-\\s+)? # optional hyphen before the description\n((?:(?!\\*\\/).)*) # The type description",
3261- "captures": {
3262- "0": {
3263- "name": "other.meta.jsdoc"
3264- },
3265- "1": {
3266- "name": "entity.name.type.instance.jsdoc"
3267- },
3268- "2": {
3269- "name": "variable.other.jsdoc"
3270- },
3271- "3": {
3272- "name": "other.description.jsdoc"
3273- }
3274- }
3275- },
3276- {
3277- "match": "(?x)\n({(?:\n \\* | # {*} any type\n \\? | # {?} unknown type\n\n (?: # Check for a prefix\n \\? | # {?string} nullable type\n ! | # {!string} non-nullable type\n \\.{3} # {...string} variable number of parameters\n )?\n\n (?:\n \\( # Opening bracket of multiple types with parenthesis {(string|number)}\n [a-zA-Z_$]+\n (?:\n [\\w$]* |\n \\.?<[\\w$]+(?:,\\s+[\\w$]+)*> # {Array<string>} or {Object<string, number>} type application (optional .)\n )\n (?:\n [\\.|~] # {Foo.bar} namespaced, {string|number} multiple, {Foo~bar} class-specific callback\n [a-zA-Z_$]+\n (?:\n [\\w$]* |\n \\.?<[\\w$]+(?:,\\s+[\\w$]+)*> # {Array<string>} or {Object<string, number>} type application (optional .)\n )\n )*\n \\) |\n [a-zA-Z_$]+\n (?:\n [\\w$]* |\n \\.?<[\\w$]+(?:,\\s+[\\w$]+)*> # {Array<string>} or {Object<string, number>} type application (optional .)\n )\n (?:\n [\\.|~] # {Foo.bar} namespaced, {string|number} multiple, {Foo~bar} class-specific callback\n [a-zA-Z_$]+\n (?:\n [\\w$]* |\n \\.?<[\\w$]+(?:,\\s+[\\w$]+)*> # {Array<string>} or {Object<string, number>} type application (optional .)\n )\n )*\n )\n # Check for suffix\n (?:\\[\\])? # {string[]} type application, an array of strings\n =? # {string=} optional parameter\n)})\n\\s+\n(?:-\\s+)? # optional hyphen before the description\n((?:(?!\\*\\/).)*) # The type description",
3278- "captures": {
3279- "0": {
3280- "name": "other.meta.jsdoc"
3281- },
3282- "1": {
3283- "name": "entity.name.type.instance.jsdoc"
3284- },
3285- "2": {
3286- "name": "other.description.jsdoc"
3287- }
3288- }
3289- }
3290- ]
3291- },
3292- "jsx-tag-attributes": {
3293- "patterns": [
3294- {
3295- "include": "#jsx-tag-attribute-name"
3296- },
3297- {
3298- "include": "#jsx-tag-attribute-assignment"
3299- },
3300- {
3301- "include": "#jsx-string-double-quoted"
3302- },
3303- {
3304- "include": "#jsx-string-single-quoted"
3305- },
3306- {
3307- "include": "#jsx-evaluated-code"
3308- }
3309- ]
3310- },
3311- "jsx-tag-attribute-name": {
3312- "match": "(?x)\n \\s*\n ([_$a-zA-Z][-$\\w]*)\n (?=\\s|=|/?>|/\\*|//)",
3313- "captures": {
3314- "1": {
3315- "name": "entity.other.attribute-name.js"
3316- }
3317- }
3318- },
3319- "jsx-tag-attribute-assignment": {
3320- "name": "keyword.operator.assignment.js",
3321- "match": "=(?=\\s*(?:'|\"|{|/\\*|//|\\n))"
3322- },
3323- "jsx-string-double-quoted": {
3324- "name": "string.quoted.double.js",
3325- "begin": "\"",
3326- "end": "\"",
3327- "beginCaptures": {
3328- "0": {
3329- "name": "punctuation.definition.string.begin.js"
3330- }
3331- },
3332- "endCaptures": {
3333- "0": {
3334- "name": "punctuation.definition.string.end.js"
3335- }
3336- },
3337- "patterns": [
3338- {
3339- "include": "#jsx-entities"
3340- }
3341- ]
3342- },
3343- "jsx-string-single-quoted": {
3344- "name": "string.quoted.single.js",
3345- "begin": "'",
3346- "end": "'",
3347- "beginCaptures": {
3348- "0": {
3349- "name": "punctuation.definition.string.begin.js"
3350- }
3351- },
3352- "endCaptures": {
3353- "0": {
3354- "name": "punctuation.definition.string.end.js"
3355- }
3356- },
3357- "patterns": [
3358- {
3359- "include": "#jsx-entities"
3360- }
3361- ]
3362- },
3363- "jsx-entities": {
3364- "patterns": [
3365- {
3366- "name": "constant.character.entity.js",
3367- "match": "(&)([a-zA-Z0-9]+|#[0-9]+|#x[0-9a-fA-F]+)(;)",
3368- "captures": {
3369- "1": {
3370- "name": "punctuation.definition.entity.js"
3371- },
3372- "3": {
3373- "name": "punctuation.definition.entity.js"
3374- }
3375- }
3376- },
3377- {
3378- "name": "invalid.illegal.bad-ampersand.js",
3379- "match": "&"
3380- }
3381- ]
3382- },
3383- "jsx-evaluated-code": {
3384- "name": "meta.embedded.expression.js",
3385- "begin": "{",
3386- "end": "}",
3387- "beginCaptures": {
3388- "0": {
3389- "name": "punctuation.section.embedded.begin.js"
3390- }
3391- },
3392- "endCaptures": {
3393- "0": {
3394- "name": "punctuation.section.embedded.end.js"
3395- }
3396- },
3397- "patterns": [
3398- {
3399- "include": "#expression"
3400- }
3401- ]
3402- },
3403- "jsx-tag-attributes-illegal": {
3404- "name": "invalid.illegal.attribute.js",
3405- "match": "\\S+"
3406- },
3407- "jsx-tag-without-attributes": {
3408- "name": "meta.tag.without-attributes.js",
3409- "begin": "(<)\\s*([_$a-zA-Z][-$\\w.]*(?<!\\.|-))\\s*(>)",
3410- "end": "(</)\\s*([_$a-zA-Z][-$\\w.]*(?<!\\.|-))\\s*(>)",
3411- "beginCaptures": {
3412- "1": {
3413- "name": "punctuation.definition.tag.begin.js"
3414- },
3415- "2": {
3416- "name": "entity.name.tag.js"
3417- },
3418- "3": {
3419- "name": "punctuation.definition.tag.end.js"
3420- }
3421- },
3422- "endCaptures": {
3423- "1": {
3424- "name": "punctuation.definition.tag.begin.js"
3425- },
3426- "2": {
3427- "name": "entity.name.tag.js"
3428- },
3429- "3": {
3430- "name": "punctuation.definition.tag.end.js"
3431- }
3432- },
3433- "contentName": "meta.jsx.children.tsx",
3434- "patterns": [
3435- {
3436- "include": "#jsx-children"
3437- }
3438- ]
3439- },
3440- "jsx-tag-in-expression": {
3441- "begin": "(?x)\n (?<=[({\\[,?=>]|&&|\\|\\||\\?|\\Wreturn|^return|\\Wdefault|^)\\s*\n (?!(<)\\s*([_$a-zA-Z][-$\\w.]*(?<!\\.|-))\\s*(>)) #look ahead is not start of tag without attributes\n (?!<\\s*[_$[:alpha:]][_$[:alnum:]]*((\\s+extends\\s+[^=>])|,)) # look ahead is not type parameter of arrow\n (?=(<)\\s*\n ([_$a-zA-Z][-$\\w.]*(?<!\\.|-))\n (?=\\s+(?!\\?)|/?>))",
3442- "end": "(/>)|(?:(</)\\s*([_$a-zA-Z][-$\\w.]*(?<!\\.|-))\\s*(>))",
3443- "endCaptures": {
3444- "0": {
3445- "name": "meta.tag.js"
3446- },
3447- "1": {
3448- "name": "punctuation.definition.tag.end.js"
3449- },
3450- "2": {
3451- "name": "punctuation.definition.tag.begin.js"
3452- },
3453- "3": {
3454- "name": "entity.name.tag.js"
3455- },
3456- "4": {
3457- "name": "punctuation.definition.tag.end.js"
3458- }
3459- },
3460- "patterns": [
3461- {
3462- "include": "#jsx-tag"
3463- }
3464- ]
3465- },
3466- "jsx-child-tag": {
3467- "begin": "(?x)\n (?=(<)\\s*\n ([_$a-zA-Z][-$\\w.]*(?<!\\.|-))\n (?=\\s+(?!\\?)|/?>))",
3468- "end": "(/>)|(?:(</)\\s*([_$a-zA-Z][-$\\w.]*(?<!\\.|-))\\s*(>))",
3469- "endCaptures": {
3470- "0": {
3471- "name": "meta.tag.js"
3472- },
3473- "1": {
3474- "name": "punctuation.definition.tag.end.js"
3475- },
3476- "2": {
3477- "name": "punctuation.definition.tag.begin.js"
3478- },
3479- "3": {
3480- "name": "entity.name.tag.js"
3481- },
3482- "4": {
3483- "name": "punctuation.definition.tag.end.js"
3484- }
3485- },
3486- "patterns": [
3487- {
3488- "include": "#jsx-tag"
3489- }
3490- ]
3491- },
3492- "jsx-tag": {
3493- "name": "meta.tag.js",
3494- "begin": "(?x)\n (?=(<)\\s*\n ([_$a-zA-Z][-$\\w.]*(?<!\\.|-))\n (?=\\s+(?!\\?)|/?>))",
3495- "end": "(?=(/>)|(?:(</)\\s*([_$a-zA-Z][-$\\w.]*(?<!\\.|-))\\s*(>)))",
3496- "patterns": [
3497- {
3498- "begin": "(?x)\n (<)\\s*\n ([_$a-zA-Z][-$\\w.]*(?<!\\.|-))\n (?=\\s+(?!\\?)|/?>)",
3499- "beginCaptures": {
3500- "1": {
3501- "name": "punctuation.definition.tag.begin.js"
3502- },
3503- "2": {
3504- "name": "entity.name.tag.js"
3505- }
3506- },
3507- "end": "(?=[/]?>)",
3508- "patterns": [
3509- {
3510- "include": "#comment"
3511- },
3512- {
3513- "include": "#jsx-tag-attributes"
3514- },
3515- {
3516- "include": "#jsx-tag-attributes-illegal"
3517- }
3518- ]
3519- },
3520- {
3521- "begin": "(>)",
3522- "beginCaptures": {
3523- "1": {
3524- "name": "punctuation.definition.tag.end.js"
3525- }
3526- },
3527- "end": "(?=</)",
3528- "contentName": "meta.jsx.children.tsx",
3529- "patterns": [
3530- {
3531- "include": "#jsx-children"
3532- }
3533- ]
3534- }
3535- ]
3536- },
3537- "jsx-tag-invalid": {
3538- "name": "invalid.illegal.tag.incomplete.js",
3539- "match": "<\\s*>"
3540- },
3541- "jsx-children": {
3542- "patterns": [
3543- {
3544- "include": "#jsx-tag-without-attributes"
3545- },
3546- {
3547- "include": "#jsx-child-tag"
3548- },
3549- {
3550- "include": "#jsx-tag-invalid"
3551- },
3552- {
3553- "include": "#jsx-evaluated-code"
3554- },
3555- {
3556- "include": "#jsx-entities"
3557- }
3558- ]
3559- },
3560- "jsx": {
3561- "patterns": [
3562- {
3563- "include": "#jsx-tag-without-attributes"
3564- },
3565- {
3566- "include": "#jsx-tag-in-expression"
3567- },
3568- {
3569- "include": "#jsx-tag-invalid"
3570- }
3571- ]
3572- }
3573- },
3574- "version": "https://github.com/Microsoft/TypeScript-TmLanguage/commit/4d0bdebb93aadc25ecbb903ebc897e9cd5fab69c"
3575-}
No newline at the end of the file
2+ "name": "JavaScript (with React support)",
3+ "scopeName": "source.js",
4+ "fileTypes": [".js", ".jsx"],
5+ "uuid": "805375ec-d614-41f5-8993-5843fe63ea82",
6+ "patterns": [
7+ {
8+ "include": "#directives"
9+ },
10+ {
11+ "include": "#statements"
12+ },
13+ {
14+ "name": "comment.line.shebang.ts",
15+ "match": "\\A(#!).*(?=$)",
16+ "captures": {
17+ "1": {
18+ "name": "punctuation.definition.comment.ts"
19+ }
20+ }
21+ }
22+ ],
23+ "repository": {
24+ "statements": {
25+ "patterns": [
26+ {
27+ "include": "#string"
28+ },
29+ {
30+ "include": "#template"
31+ },
32+ {
33+ "include": "#comment"
34+ },
35+ {
36+ "include": "#literal"
37+ },
38+ {
39+ "include": "#declaration"
40+ },
41+ {
42+ "include": "#switch-statement"
43+ },
44+ {
45+ "include": "#for-loop"
46+ },
47+ {
48+ "include": "#after-operator-block"
49+ },
50+ {
51+ "include": "#decl-block"
52+ },
53+ {
54+ "include": "#control-statement"
55+ },
56+ {
57+ "include": "#expression"
58+ },
59+ {
60+ "include": "#punctuation-semicolon"
61+ }
62+ ]
63+ },
64+ "var-expr": {
65+ "name": "meta.var.expr.js",
66+ "begin": "(?<!\\.|\\$)(?:(\\bexport)\\s+)?\\b(var|let|const(?!\\s+enum\\b))\\b(?!\\$)",
67+ "beginCaptures": {
68+ "1": {
69+ "name": "keyword.control.export.js"
70+ },
71+ "2": {
72+ "name": "storage.type.js"
73+ }
74+ },
75+ "end": "(?=$|;|}|(\\s+(of|in)\\s+))",
76+ "patterns": [
77+ {
78+ "include": "#destructuring-variable"
79+ },
80+ {
81+ "include": "#var-single-variable"
82+ },
83+ {
84+ "include": "#variable-initializer"
85+ },
86+ {
87+ "include": "#comment"
88+ },
89+ {
90+ "include": "#punctuation-comma"
91+ }
92+ ]
93+ },
94+ "var-single-variable": {
95+ "patterns": [
96+ {
97+ "name": "meta.var-single-variable.expr.js",
98+ "begin": "(?x)([_$[:alpha:]][_$[:alnum:]]*)(?=\\s* (=\\s*( (async\\s+) | (function\\s*[(<]) | (function\\s+) | ([_$[:alpha:]][_$[:alnum:]]*\\s*=>) | ((<([^<>]|\\<[^<>]+\\>)+>\\s*)?\\(([^()]|\\([^()]*\\))*\\)(\\s*:\\s*(.)*)?\\s*=>)) ) | (:\\s*( (<) | ([(]\\s*( ([)]) | (\\.\\.\\.) | ([_$[:alnum:]]+\\s*( ([:,?=])| ([)]\\s*=>) )) ))) ))",
99+ "beginCaptures": {
100+ "1": {
101+ "name": "entity.name.function.js"
102+ }
103+ },
104+ "end": "(?=$|[;,=}]|(\\s+(of|in)\\s+))",
105+ "patterns": [
106+ {
107+ "include": "#type-annotation"
108+ },
109+ {
110+ "include": "#string"
111+ },
112+ {
113+ "include": "#comment"
114+ }
115+ ]
116+ },
117+ {
118+ "name": "meta.var-single-variable.expr.js",
119+ "begin": "([_$[:alpha:]][_$[:alnum:]]*)",
120+ "beginCaptures": {
121+ "1": {
122+ "name": "variable.other.readwrite.js"
123+ }
124+ },
125+ "end": "(?=$|[;,=}]|(\\s+(of|in)\\s+))",
126+ "patterns": [
127+ {
128+ "include": "#type-annotation"
129+ },
130+ {
131+ "include": "#string"
132+ },
133+ {
134+ "include": "#comment"
135+ }
136+ ]
137+ }
138+ ]
139+ },
140+ "destructuring-variable": {
141+ "patterns": [
142+ {
143+ "name": "meta.object-binding-pattern-variable.js",
144+ "begin": "(?<!=|:|of|in)\\s*(?=\\{)",
145+ "end": "(?=$|[;,=}]|(\\s+(of|in)\\s+))",
146+ "patterns": [
147+ {
148+ "include": "#object-binding-pattern"
149+ },
150+ {
151+ "include": "#type-annotation"
152+ },
153+ {
154+ "include": "#comment"
155+ }
156+ ]
157+ },
158+ {
159+ "name": "meta.array-binding-pattern-variable.js",
160+ "begin": "(?<!=|:|of|in)\\s*(?=\\[)",
161+ "end": "(?=$|[;,=}]|(\\s+(of|in)\\s+))",
162+ "patterns": [
163+ {
164+ "include": "#array-binding-pattern"
165+ },
166+ {
167+ "include": "#type-annotation"
168+ },
169+ {
170+ "include": "#comment"
171+ }
172+ ]
173+ }
174+ ]
175+ },
176+ "object-binding-element": {
177+ "patterns": [
178+ {
179+ "include": "#comment"
180+ },
181+ {
182+ "begin": "(?=(([_$[:alpha:]][_$[:alnum:]]*)|(\\'[^']*\\')|(\\\"[^\"]*\\\")|(\\[([^\\[\\]]|\\[[^\\[\\]]+\\])+\\]))\\s*(:))",
183+ "end": "(?=,|\\})",
184+ "patterns": [
185+ {
186+ "include": "#object-binding-element-propertyName"
187+ },
188+ {
189+ "include": "#binding-element"
190+ }
191+ ]
192+ },
193+ {
194+ "include": "#object-binding-pattern"
195+ },
196+ {
197+ "include": "#destructuring-variable-rest"
198+ },
199+ {
200+ "include": "#variable-initializer"
201+ },
202+ {
203+ "include": "#punctuation-comma"
204+ }
205+ ]
206+ },
207+ "object-binding-element-propertyName": {
208+ "begin": "(?=(([_$[:alpha:]][_$[:alnum:]]*)|(\\'[^']*\\')|(\\\"[^\"]*\\\")|(\\[([^\\[\\]]|\\[[^\\[\\]]+\\])+\\]))\\s*(:))",
209+ "end": "(:)",
210+ "endCaptures": {
211+ "0": {
212+ "name": "punctuation.destructuring.js"
213+ }
214+ },
215+ "patterns": [
216+ {
217+ "include": "#string"
218+ },
219+ {
220+ "include": "#array-literal"
221+ },
222+ {
223+ "name": "variable.object.property.js",
224+ "match": "([_$[:alpha:]][_$[:alnum:]]*)"
225+ }
226+ ]
227+ },
228+ "binding-element": {
229+ "patterns": [
230+ {
231+ "include": "#comment"
232+ },
233+ {
234+ "include": "#object-binding-pattern"
235+ },
236+ {
237+ "include": "#array-binding-pattern"
238+ },
239+ {
240+ "include": "#destructuring-variable-rest"
241+ },
242+ {
243+ "include": "#variable-initializer"
244+ }
245+ ]
246+ },
247+ "destructuring-variable-rest": {
248+ "match": "(?:(\\.\\.\\.)\\s*)?([_$[:alpha:]][_$[:alnum:]]*)",
249+ "captures": {
250+ "1": {
251+ "name": "keyword.operator.rest.js"
252+ },
253+ "2": {
254+ "name": "variable.other.readwrite.js"
255+ }
256+ }
257+ },
258+ "object-binding-pattern": {
259+ "begin": "(?:(\\.\\.\\.)\\s*)?(\\{)",
260+ "beginCaptures": {
261+ "1": {
262+ "name": "keyword.operator.rest.js"
263+ },
264+ "2": {
265+ "name": "punctuation.definition.binding-pattern.object.js"
266+ }
267+ },
268+ "end": "\\}",
269+ "endCaptures": {
270+ "0": {
271+ "name": "punctuation.definition.binding-pattern.object.js"
272+ }
273+ },
274+ "patterns": [
275+ {
276+ "include": "#object-binding-element"
277+ }
278+ ]
279+ },
280+ "array-binding-pattern": {
281+ "begin": "(?:(\\.\\.\\.)\\s*)?(\\[)",
282+ "beginCaptures": {
283+ "1": {
284+ "name": "keyword.operator.rest.js"
285+ },
286+ "2": {
287+ "name": "punctuation.definition.binding-pattern.array.js"
288+ }
289+ },
290+ "end": "\\]",
291+ "endCaptures": {
292+ "0": {
293+ "name": "punctuation.definition.binding-pattern.array.js"
294+ }
295+ },
296+ "patterns": [
297+ {
298+ "include": "#binding-element"
299+ },
300+ {
301+ "include": "#punctuation-comma"
302+ }
303+ ]
304+ },
305+ "ternary-expression": {
306+ "begin": "(?=\\?)",
307+ "end": "(?=$|[;,})\\]])",
308+ "patterns": [
309+ {
310+ "include": "#ternary-operator"
311+ },
312+ {
313+ "include": "#expression"
314+ }
315+ ]
316+ },
317+ "ternary-operator": {
318+ "begin": "(\\?)",
319+ "beginCaptures": {
320+ "0": {
321+ "name": "keyword.operator.ternary.js"
322+ }
323+ },
324+ "end": "(:)",
325+ "endCaptures": {
326+ "0": {
327+ "name": "keyword.operator.ternary.js"
328+ }
329+ },
330+ "patterns": [
331+ {
332+ "include": "#expression"
333+ }
334+ ]
335+ },
336+ "expression": {
337+ "name": "meta.expression.js",
338+ "patterns": [
339+ {
340+ "include": "#jsx"
341+ },
342+ {
343+ "include": "#string"
344+ },
345+ {
346+ "include": "#regex"
347+ },
348+ {
349+ "include": "#template"
350+ },
351+ {
352+ "include": "#comment"
353+ },
354+ {
355+ "include": "#literal"
356+ },
357+ {
358+ "include": "#function-declaration"
359+ },
360+ {
361+ "include": "#class-or-interface-declaration"
362+ },
363+ {
364+ "include": "#arrow-function"
365+ },
366+ {
367+ "include": "#cast"
368+ },
369+ {
370+ "include": "#ternary-expression"
371+ },
372+ {
373+ "include": "#new-expr"
374+ },
375+ {
376+ "include": "#object-literal"
377+ },
378+ {
379+ "include": "#expression-operators"
380+ },
381+ {
382+ "include": "#function-call"
383+ },
384+ {
385+ "include": "#support-objects"
386+ },
387+ {
388+ "include": "#identifiers"
389+ },
390+ {
391+ "include": "#paren-expression"
392+ },
393+ {
394+ "include": "#punctuation-comma"
395+ },
396+ {
397+ "include": "#punctuation-accessor"
398+ }
399+ ]
400+ },
401+ "control-statement": {
402+ "patterns": [
403+ {
404+ "name": "keyword.control.trycatch.js",
405+ "match": "(?<!\\.|\\$)\\b(catch|finally|throw|try)\\b(?!\\$)"
406+ },
407+ {
408+ "name": "keyword.control.loop.js",
409+ "match": "(?<!\\.|\\$)\\b(break|continue|do|goto|while)\\b(?!\\$)"
410+ },
411+ {
412+ "name": "keyword.control.flow.js",
413+ "match": "(?<!\\.|\\$)\\b(return)\\b(?!\\$)"
414+ },
415+ {
416+ "match": "(?<!\\.|\\$)\\b(yield)\\b(?!\\$)(?:\\s*(\\*))?",
417+ "captures": {
418+ "1": {
419+ "name": "keyword.control.flow.js"
420+ },
421+ "2": {
422+ "name": "keyword.generator.asterisk.js"
423+ }
424+ }
425+ },
426+ {
427+ "name": "keyword.control.switch.js",
428+ "match": "(?<!\\.|\\$)\\b(case|default|switch)\\b(?!\\$)"
429+ },
430+ {
431+ "name": "keyword.control.conditional.js",
432+ "match": "(?<!\\.|\\$)\\b(else|if)\\b(?!\\$)"
433+ },
434+ {
435+ "name": "keyword.control.with.js",
436+ "match": "(?<!\\.|\\$)\\b(with)\\b(?!\\$)"
437+ },
438+ {
439+ "name": "keyword.other.debugger.js",
440+ "match": "(?<!\\.|\\$)\\b(debugger)\\b(?!\\$)"
441+ },
442+ {
443+ "name": "storage.modifier.js",
444+ "match": "(?<!\\.|\\$)\\b(declare)\\b(?!\\$)"
445+ }
446+ ]
447+ },
448+ "declaration": {
449+ "name": "meta.declaration.js",
450+ "patterns": [
451+ {
452+ "include": "#decorator"
453+ },
454+ {
455+ "include": "#var-expr"
456+ },
457+ {
458+ "include": "#function-declaration"
459+ },
460+ {
461+ "include": "#class-or-interface-declaration"
462+ },
463+ {
464+ "include": "#type-declaration"
465+ },
466+ {
467+ "include": "#enum-declaration"
468+ },
469+ {
470+ "include": "#namespace-declaration"
471+ },
472+ {
473+ "include": "#import-equals-declaration"
474+ },
475+ {
476+ "include": "#import-declaration"
477+ },
478+ {
479+ "include": "#export-declaration"
480+ }
481+ ]
482+ },
483+ "decorator": {
484+ "name": "meta.decorator.js",
485+ "begin": "(?<!\\.|\\$)\\@",
486+ "beginCaptures": {
487+ "0": {
488+ "name": "punctuation.decorator.js"
489+ }
490+ },
491+ "end": "(?=\\s)",
492+ "patterns": [
493+ {
494+ "include": "#expression"
495+ }
496+ ]
497+ },
498+ "type-declaration": {
499+ "name": "meta.type.declaration.js",
500+ "begin": "(?<!\\.|\\$)(?:(\\bexport)\\s+)?\\b(type)\\b\\s+([_$[:alpha:]][_$[:alnum:]]*)\\s*",
501+ "beginCaptures": {
502+ "1": {
503+ "name": "keyword.control.export.js"
504+ },
505+ "2": {
506+ "name": "storage.type.type.js"
507+ },
508+ "3": {
509+ "name": "entity.name.type.js"
510+ }
511+ },
512+ "end": "(?=[};]|\\bvar\\b|\\blet\\b|\\bconst\\b|\\btype\\b|\\bfunction\\b|\\bclass\\b|\\binterface\\b|\\bnamespace\\b|\\bmodule\\b|\\bimport\\b|\\benum\\b|\\bdeclare\\b|\\bexport\\b|\\babstract\\b|\\basync\\b)",
513+ "patterns": [
514+ {
515+ "include": "#comment"
516+ },
517+ {
518+ "include": "#type-parameters"
519+ },
520+ {
521+ "include": "#type"
522+ },
523+ {
524+ "match": "(=)\\s*",
525+ "captures": {
526+ "1": {
527+ "name": "keyword.operator.assignment.js"
528+ }
529+ }
530+ }
531+ ]
532+ },
533+ "enum-declaration": {
534+ "name": "meta.enum.declaration.js",
535+ "begin": "(?<!\\.|\\$)(?:(\\bexport)\\s+)?(?:\\b(const)\\s+)?\\b(enum)\\s+([_$[:alpha:]][_$[:alnum:]]*)",
536+ "beginCaptures": {
537+ "1": {
538+ "name": "keyword.control.export.js"
539+ },
540+ "2": {
541+ "name": "storage.modifier.js"
542+ },
543+ "3": {
544+ "name": "storage.type.enum.js"
545+ },
546+ "4": {
547+ "name": "entity.name.type.enum.js"
548+ }
549+ },
550+ "end": "(?<=\\})",
551+ "patterns": [
552+ {
553+ "include": "#comment"
554+ },
555+ {
556+ "begin": "\\{",
557+ "beginCaptures": {
558+ "0": {
559+ "name": "punctuation.definition.block.js"
560+ }
561+ },
562+ "end": "\\}",
563+ "endCaptures": {
564+ "0": {
565+ "name": "punctuation.definition.block.js"
566+ }
567+ },
568+ "patterns": [
569+ {
570+ "include": "#comment"
571+ },
572+ {
573+ "begin": "([_$[:alpha:]][_$[:alnum:]]*)",
574+ "beginCaptures": {
575+ "0": {
576+ "name": "variable.other.enummember.js"
577+ }
578+ },
579+ "end": "(?=,|\\}|$)",
580+ "patterns": [
581+ {
582+ "include": "#comment"
583+ },
584+ {
585+ "include": "#variable-initializer"
586+ }
587+ ]
588+ },
589+ {
590+ "begin": "(?=((\\'[^']*\\')|(\\\"[^\"]*\\\")|(\\[([^\\[\\]]|\\[[^\\[\\]]+\\])+\\])))",
591+ "end": "(?=,|\\}|$)",
592+ "patterns": [
593+ {
594+ "include": "#string"
595+ },
596+ {
597+ "include": "#array-literal"
598+ },
599+ {
600+ "include": "#comment"
601+ },
602+ {
603+ "include": "#variable-initializer"
604+ }
605+ ]
606+ },
607+ {
608+ "include": "#punctuation-comma"
609+ }
610+ ]
611+ }
612+ ]
613+ },
614+ "namespace-declaration": {
615+ "name": "meta.namespace.declaration.js",
616+ "begin": "(?<!\\.|\\$)(?:(\\bexport)\\s+)?\\b(namespace|module)\\s+",
617+ "beginCaptures": {
618+ "1": {
619+ "name": "keyword.control.export.js"
620+ },
621+ "2": {
622+ "name": "storage.type.namespace.js"
623+ }
624+ },
625+ "end": "(?=$|\\{)",
626+ "patterns": [
627+ {
628+ "include": "#comment"
629+ },
630+ {
631+ "include": "#string"
632+ },
633+ {
634+ "name": "entity.name.type.module.js",
635+ "match": "([_$[:alpha:]][_$[:alnum:]]*)"
636+ },
637+ {
638+ "name": "punctuation.accessor.js",
639+ "match": "\\."
640+ }
641+ ]
642+ },
643+ "import-equals-declaration": {
644+ "patterns": [
645+ {
646+ "name": "meta.import-equals.external.js",
647+ "begin": "(?<!\\.|\\$)(?:(\\bexport)\\s+)?\\b(import)\\s+([_$[:alpha:]][_$[:alnum:]]*)\\s*(=)\\s*(require)\\s*(\\()",
648+ "beginCaptures": {
649+ "1": {
650+ "name": "keyword.control.export.js"
651+ },
652+ "2": {
653+ "name": "keyword.control.import.js"
654+ },
655+ "3": {
656+ "name": "variable.other.readwrite.alias.js"
657+ },
658+ "4": {
659+ "name": "keyword.operator.assignment.js"
660+ },
661+ "5": {
662+ "name": "keyword.control.require.js"
663+ },
664+ "6": {
665+ "name": "meta.brace.round.js"
666+ }
667+ },
668+ "end": "\\)",
669+ "endCaptures": {
670+ "0": {
671+ "name": "meta.brace.round.js"
672+ }
673+ },
674+ "patterns": [
675+ {
676+ "include": "#comment"
677+ },
678+ {
679+ "include": "#string"
680+ }
681+ ]
682+ },
683+ {
684+ "name": "meta.import-equals.internal.js",
685+ "begin": "(?<!\\.|\\$)(?:(\\bexport)\\s+)?\\b(import)\\s+([_$[:alpha:]][_$[:alnum:]]*)\\s*(=)\\s*(?!require\\b)",
686+ "beginCaptures": {
687+ "1": {
688+ "name": "keyword.control.export.js"
689+ },
690+ "2": {
691+ "name": "keyword.control.import.js"
692+ },
693+ "3": {
694+ "name": "variable.other.readwrite.alias.js"
695+ },
696+ "4": {
697+ "name": "keyword.operator.assignment.js"
698+ }
699+ },
700+ "end": "(?=;|$)",
701+ "patterns": [
702+ {
703+ "include": "#comment"
704+ },
705+ {
706+ "match": "([_$[:alpha:]][_$[:alnum:]]*)\\s*(\\.)",
707+ "captures": {
708+ "1": {
709+ "name": "entity.name.type.module.js"
710+ },
711+ "2": {
712+ "name": "punctuation.accessor.js"
713+ }
714+ }
715+ },
716+ {
717+ "name": "variable.other.readwrite.js",
718+ "match": "([_$[:alpha:]][_$[:alnum:]]*)"
719+ }
720+ ]
721+ }
722+ ]
723+ },
724+ "import-declaration": {
725+ "name": "meta.import.js",
726+ "begin": "(?<!\\.|\\$)(?:(\\bexport)\\s+)?\\b(import)(?!(\\s*:)|(\\$))\\b",
727+ "beginCaptures": {
728+ "1": {
729+ "name": "keyword.control.export.js"
730+ },
731+ "2": {
732+ "name": "keyword.control.import.js"
733+ }
734+ },
735+ "end": "(?=;|$)",
736+ "patterns": [
737+ {
738+ "include": "#import-export-declaration"
739+ }
740+ ]
741+ },
742+ "export-declaration": {
743+ "patterns": [
744+ {
745+ "match": "(?<!\\.|\\$)\\b(export)\\s+(as)\\s+(namespace)\\s+([_$[:alpha:]][_$[:alnum:]]*)",
746+ "captures": {
747+ "1": {
748+ "name": "keyword.control.export.js"
749+ },
750+ "2": {
751+ "name": "keyword.control.as.js"
752+ },
753+ "3": {
754+ "name": "storage.type.namespace.js"
755+ },
756+ "4": {
757+ "name": "entity.name.type.module.js"
758+ }
759+ }
760+ },
761+ {
762+ "name": "meta.export.default.js",
763+ "begin": "(?<!\\.|\\$)\\b(export)(?:(?:\\s*(=))|(?:\\s+(default)(?=\\s+)))",
764+ "beginCaptures": {
765+ "1": {
766+ "name": "keyword.control.export.js"
767+ },
768+ "2": {
769+ "name": "keyword.operator.assignment.js"
770+ },
771+ "3": {
772+ "name": "keyword.control.default.js"
773+ }
774+ },
775+ "end": "(?=;|\\bexport\\b|\\bfunction\\b|\\bclass\\b|\\binterface\\b|\\blet\\b|\\bvar\\b|\\bconst\\b|\\bimport\\b|\\benum\\b|\\bnamespace\\b|\\bmodule\\b|\\btype\\b|\\babstract\\b|\\bdeclare\\b|\\basync\\b|$)",
776+ "patterns": [
777+ {
778+ "include": "#expression"
779+ }
780+ ]
781+ },
782+ {
783+ "name": "meta.export.js",
784+ "begin": "(?<!\\.|\\$)\\b(export)(?!(\\s*:)|(\\$))\\b",
785+ "beginCaptures": {
786+ "0": {
787+ "name": "keyword.control.export.js"
788+ }
789+ },
790+ "end": "(?=;|\\bexport\\b|\\bfunction\\b|\\bclass\\b|\\binterface\\b|\\blet\\b|\\bvar\\b|\\bconst\\b|\\bimport\\b|\\benum\\b|\\bnamespace\\b|\\bmodule\\b|\\btype\\b|\\babstract\\b|\\bdeclare\\b|\\basync\\b|$)",
791+ "patterns": [
792+ {
793+ "include": "#import-export-declaration"
794+ }
795+ ]
796+ }
797+ ]
798+ },
799+ "import-export-declaration": {
800+ "patterns": [
801+ {
802+ "include": "#comment"
803+ },
804+ {
805+ "include": "#string"
806+ },
807+ {
808+ "include": "#import-export-block"
809+ },
810+ {
811+ "name": "keyword.control.from.js",
812+ "match": "\\bfrom\\b"
813+ },
814+ {
815+ "include": "#import-export-clause"
816+ }
817+ ]
818+ },
819+ "import-export-block": {
820+ "name": "meta.block.js",
821+ "begin": "\\{",
822+ "beginCaptures": {
823+ "0": {
824+ "name": "punctuation.definition.block.js"
825+ }
826+ },
827+ "end": "\\}",
828+ "endCaptures": {
829+ "0": {
830+ "name": "punctuation.definition.block.js"
831+ }
832+ },
833+ "patterns": [
834+ {
835+ "include": "#import-export-clause"
836+ }
837+ ]
838+ },
839+ "import-export-clause": {
840+ "patterns": [
841+ {
842+ "include": "#comment"
843+ },
844+ {
845+ "comment": "(default|*|name) as alias",
846+ "match": "(?x) (?: \\b(default)\\b | (\\*) | ([_$[:alpha:]][_$[:alnum:]]*)) \\s+ (as) \\s+ (?: (\\b default \\b | \\*) | ([_$[:alpha:]][_$[:alnum:]]*))",
847+ "captures": {
848+ "1": {
849+ "name": "keyword.control.default.js"
850+ },
851+ "2": {
852+ "name": "constant.language.import-export-all.js"
853+ },
854+ "3": {
855+ "name": "variable.other.readwrite.js"
856+ },
857+ "4": {
858+ "name": "keyword.control.as.js"
859+ },
860+ "5": {
861+ "name": "invalid.illegal.js"
862+ },
863+ "6": {
864+ "name": "variable.other.readwrite.alias.js"
865+ }
866+ }
867+ },
868+ {
869+ "include": "#punctuation-comma"
870+ },
871+ {
872+ "name": "constant.language.import-export-all.js",
873+ "match": "\\*"
874+ },
875+ {
876+ "name": "keyword.control.default.js",
877+ "match": "\\b(default)\\b"
878+ },
879+ {
880+ "name": "variable.other.readwrite.alias.js",
881+ "match": "([_$[:alpha:]][_$[:alnum:]]*)"
882+ }
883+ ]
884+ },
885+ "class-or-interface-declaration": {
886+ "name": "meta.class.js",
887+ "begin": "(?<!\\.|\\$)\\b(?:(export)\\s+)?\\b(?:(abstract)\\s+)?\\b(?:(class)|(interface))\\b",
888+ "beginCaptures": {
889+ "1": {
890+ "name": "keyword.control.export.js"
891+ },
892+ "2": {
893+ "name": "storage.modifier.js"
894+ },
895+ "3": {
896+ "name": "storage.type.class.js"
897+ },
898+ "4": {
899+ "name": "storage.type.interface.js"
900+ }
901+ },
902+ "end": "(?<=\\})",
903+ "endCaptures": {
904+ "1": {
905+ "name": "punctuation.definition.block.js"
906+ }
907+ },
908+ "patterns": [
909+ {
910+ "include": "#comment"
911+ },
912+ {
913+ "include": "#class-or-interface-heritage"
914+ },
915+ {
916+ "match": "[_$[:alpha:]][_$[:alnum:]]*",
917+ "captures": {
918+ "0": {
919+ "name": "entity.name.type.class.js"
920+ }
921+ }
922+ },
923+ {
924+ "include": "#type-parameters"
925+ },
926+ {
927+ "include": "#class-or-interface-body"
928+ }
929+ ]
930+ },
931+ "class-or-interface-heritage": {
932+ "begin": "(?<!\\.|\\$)(?:\\b(extends|implements)\\b)(?!\\$)",
933+ "beginCaptures": {
934+ "1": {
935+ "name": "storage.modifier.js"
936+ }
937+ },
938+ "end": "(?=\\{)",
939+ "endCaptures": {
940+ "1": {
941+ "name": "punctuation.definition.block.js"
942+ }
943+ },
944+ "patterns": [
945+ {
946+ "include": "#comment"
947+ },
948+ {
949+ "include": "#class-or-interface-heritage"
950+ },
951+ {
952+ "include": "#type-parameters"
953+ },
954+ {
955+ "match": "([_$[:alpha:]][_$[:alnum:]]*)\\s*(\\.)(?=\\s*[_$[:alpha:]][_$[:alnum:]]*(\\s*\\.\\s*[_$[:alpha:]][_$[:alnum:]]*)*\\s*([,<{]|extends|implements|//|/\\*))",
956+ "captures": {
957+ "1": {
958+ "name": "entity.name.type.module.js"
959+ },
960+ "2": {
961+ "name": "punctuation.accessor.js"
962+ }
963+ }
964+ },
965+ {
966+ "match": "([_$[:alpha:]][_$[:alnum:]]*)(?=\\s*([,<{]|extends|implements|//|/\\*))",
967+ "captures": {
968+ "1": {
969+ "name": "entity.other.inherited-class.js"
970+ }
971+ }
972+ },
973+ {
974+ "include": "#expression"
975+ }
976+ ]
977+ },
978+ "class-or-interface-body": {
979+ "begin": "\\{",
980+ "beginCaptures": {
981+ "0": {
982+ "name": "punctuation.definition.block.js"
983+ }
984+ },
985+ "end": "\\}",
986+ "endCaptures": {
987+ "0": {
988+ "name": "punctuation.definition.block.js"
989+ }
990+ },
991+ "patterns": [
992+ {
993+ "include": "#string"
994+ },
995+ {
996+ "include": "#comment"
997+ },
998+ {
999+ "include": "#decorator"
1000+ },
1001+ {
1002+ "include": "#method-declaration"
1003+ },
1004+ {
1005+ "include": "#indexer-declaration"
1006+ },
1007+ {
1008+ "include": "#field-declaration"
1009+ },
1010+ {
1011+ "include": "#type-annotation"
1012+ },
1013+ {
1014+ "include": "#variable-initializer"
1015+ },
1016+ {
1017+ "include": "#access-modifier"
1018+ },
1019+ {
1020+ "include": "#property-accessor"
1021+ },
1022+ {
1023+ "include": "#expression"
1024+ },
1025+ {
1026+ "include": "#punctuation-comma"
1027+ },
1028+ {
1029+ "include": "#punctuation-semicolon"
1030+ }
1031+ ]
1032+ },
1033+ "type-object": {
1034+ "name": "meta.object.type.js",
1035+ "begin": "\\{",
1036+ "beginCaptures": {
1037+ "0": {
1038+ "name": "punctuation.definition.block.js"
1039+ }
1040+ },
1041+ "end": "\\}",
1042+ "endCaptures": {
1043+ "0": {
1044+ "name": "punctuation.definition.block.js"
1045+ }
1046+ },
1047+ "patterns": [
1048+ {
1049+ "include": "#type-object-members"
1050+ }
1051+ ]
1052+ },
1053+ "type-object-members": {
1054+ "patterns": [
1055+ {
1056+ "include": "#comment"
1057+ },
1058+ {
1059+ "include": "#method-declaration"
1060+ },
1061+ {
1062+ "include": "#indexer-declaration"
1063+ },
1064+ {
1065+ "include": "#field-declaration"
1066+ },
1067+ {
1068+ "include": "#type-annotation"
1069+ },
1070+ {
1071+ "begin": "\\.\\.\\.",
1072+ "beginCaptures": {
1073+ "0": {
1074+ "name": "keyword.operator.spread.js"
1075+ }
1076+ },
1077+ "end": "(?=\\}|;|,|$)|(?<=\\})",
1078+ "patterns": [
1079+ {
1080+ "include": "#type"
1081+ }
1082+ ]
1083+ },
1084+ {
1085+ "include": "#punctuation-comma"
1086+ },
1087+ {
1088+ "include": "#punctuation-semicolon"
1089+ }
1090+ ]
1091+ },
1092+ "field-declaration": {
1093+ "name": "meta.field.declaration.js",
1094+ "begin": "(?<!\\()(?:(?<!\\.|\\$)\\b(readonly)\\s+)?(?=(([_$[:alpha:]][_$[:alnum:]]*)|(\\'[^']*\\')|(\\\"[^\"]*\\\")|(\\[([^\\[\\]]|\\[[^\\[\\]]+\\])+\\]))\\s*(\\?\\s*)?(=|:))",
1095+ "beginCaptures": {
1096+ "1": {
1097+ "name": "storage.modifier.js"
1098+ }
1099+ },
1100+ "end": "(?=\\}|;|,|$)|(?<=\\})",
1101+ "patterns": [
1102+ {
1103+ "include": "#variable-initializer"
1104+ },
1105+ {
1106+ "begin": "(?=((?:[_$[:alpha:]][_$[:alnum:]]*)|(?:\\'[^']*\\')|(?:\\\"[^\"]*\\\")|(\\[([^\\[\\]]|\\[[^\\[\\]]+\\])+\\]))\\s*(\\?\\s*)?(=|:))",
1107+ "end": "(?=[};,=]|$)|(?<=\\})",
1108+ "patterns": [
1109+ {
1110+ "include": "#type-annotation"
1111+ },
1112+ {
1113+ "include": "#string"
1114+ },
1115+ {
1116+ "include": "#array-literal"
1117+ },
1118+ {
1119+ "include": "#comment"
1120+ },
1121+ {
1122+ "name": "entity.name.function.js",
1123+ "match": "(?x)([_$[:alpha:]][_$[:alnum:]]*)(?=(\\?\\s*)?\\s* (=\\s*( (async\\s+) | (function\\s*[(<]) | (function\\s+) | ([_$[:alpha:]][_$[:alnum:]]*\\s*=>) | ((<([^<>]|\\<[^<>]+\\>)+>\\s*)?\\(([^()]|\\([^()]*\\))*\\)(\\s*:\\s*(.)*)?\\s*=>)) ) | (:\\s*( (<) | ([(]\\s*( ([)]) | (\\.\\.\\.) | ([_$[:alnum:]]+\\s*( ([:,?=])| ([)]\\s*=>) )) ))) ))"
1124+ },
1125+ {
1126+ "name": "variable.object.property.js",
1127+ "match": "[_$[:alpha:]][_$[:alnum:]]*"
1128+ },
1129+ {
1130+ "name": "keyword.operator.optional.js",
1131+ "match": "\\?"
1132+ }
1133+ ]
1134+ }
1135+ ]
1136+ },
1137+ "method-declaration": {
1138+ "name": "meta.method.declaration.js",
1139+ "begin": "(?<!\\.|\\$)(?:\\b(public|private|protected)\\s+)?(?:\\b(abstract)\\s+)?(?:\\b(async)\\s+)?(?:\\b(get|set)\\s+)?(?:(?:\\b(?:(new)|(constructor))\\b(?!\\$|:))|(?:(\\*)\\s*)?(?=((([_$[:alpha:]][_$[:alnum:]]*)|(\\'[^']*\\')|(\\\"[^\"]*\\\")|(\\[([^\\[\\]]|\\[[^\\[\\]]+\\])+\\]))\\s*(\\??))?\\s*[\\(\\<]))",
1140+ "beginCaptures": {
1141+ "1": {
1142+ "name": "storage.modifier.js"
1143+ },
1144+ "2": {
1145+ "name": "storage.modifier.js"
1146+ },
1147+ "3": {
1148+ "name": "storage.modifier.async.js"
1149+ },
1150+ "4": {
1151+ "name": "storage.type.property.js"
1152+ },
1153+ "5": {
1154+ "name": "keyword.operator.new.js"
1155+ },
1156+ "6": {
1157+ "name": "storage.type.js"
1158+ },
1159+ "7": {
1160+ "name": "keyword.generator.asterisk.js"
1161+ }
1162+ },
1163+ "end": "(?=\\}|;|,)|(?<=\\})",
1164+ "patterns": [
1165+ {
1166+ "include": "#method-declaration-name"
1167+ },
1168+ {
1169+ "include": "#comment"
1170+ },
1171+ {
1172+ "include": "#type-parameters"
1173+ },
1174+ {
1175+ "include": "#function-parameters"
1176+ },
1177+ {
1178+ "include": "#return-type"
1179+ },
1180+ {
1181+ "include": "#method-overload-declaration"
1182+ },
1183+ {
1184+ "include": "#decl-block"
1185+ }
1186+ ]
1187+ },
1188+ "method-overload-declaration": {
1189+ "begin": "(?<!\\.|\\$)(?:\\b(public|private|protected)\\s+)?(?:\\b(abstract)\\s+)?(?:\\b(async)\\s+)?(?:\\b(get|set)\\s+)?(?:(?:\\b(?:(new)|(constructor))\\b(?!\\$|:))|(?:(\\*)\\s*)?(?=((([_$[:alpha:]][_$[:alnum:]]*)|(\\'[^']*\\')|(\\\"[^\"]*\\\")|(\\[([^\\[\\]]|\\[[^\\[\\]]+\\])+\\]))\\s*(\\??))?\\s*[\\(\\<]))",
1190+ "beginCaptures": {
1191+ "1": {
1192+ "name": "storage.modifier.js"
1193+ },
1194+ "2": {
1195+ "name": "storage.modifier.js"
1196+ },
1197+ "3": {
1198+ "name": "storage.modifier.async.js"
1199+ },
1200+ "4": {
1201+ "name": "storage.type.property.js"
1202+ },
1203+ "5": {
1204+ "name": "keyword.operator.new.js"
1205+ },
1206+ "6": {
1207+ "name": "storage.type.js"
1208+ },
1209+ "7": {
1210+ "name": "keyword.generator.asterisk.js"
1211+ }
1212+ },
1213+ "end": "(?=\\(|\\<)",
1214+ "patterns": [
1215+ {
1216+ "include": "#method-declaration-name"
1217+ }
1218+ ]
1219+ },
1220+ "method-declaration-name": {
1221+ "begin": "(?=(([_$[:alpha:]][_$[:alnum:]]*)|(\\'[^']*\\')|(\\\"[^\"]*\\\")|(\\[([^\\[\\]]|\\[[^\\[\\]]+\\])+\\]))\\s*(\\??)\\s*[\\(\\<])",
1222+ "end": "(?=\\(|\\<)",
1223+ "patterns": [
1224+ {
1225+ "include": "#string"
1226+ },
1227+ {
1228+ "include": "#array-literal"
1229+ },
1230+ {
1231+ "name": "entity.name.function.js",
1232+ "match": "[_$[:alpha:]][_$[:alnum:]]*"
1233+ },
1234+ {
1235+ "name": "keyword.operator.optional.js",
1236+ "match": "\\?"
1237+ }
1238+ ]
1239+ },
1240+ "indexer-declaration": {
1241+ "name": "meta.indexer.declaration.js",
1242+ "begin": "(?:(?<!\\.|\\$)\\b(readonly)\\s*)?(\\[)\\s*([_$[:alpha:]][_$[:alnum:]]*)\\s*(?=:)",
1243+ "beginCaptures": {
1244+ "1": {
1245+ "name": "storage.modifier.js"
1246+ },
1247+ "2": {
1248+ "name": "meta.brace.square.js"
1249+ },
1250+ "3": {
1251+ "name": "variable.parameter.js"
1252+ }
1253+ },
1254+ "end": "(\\])\\s*(\\?\\s*)?|$",
1255+ "endCaptures": {
1256+ "1": {
1257+ "name": "meta.brace.square.js"
1258+ },
1259+ "2": {
1260+ "name": "keyword.operator.optional.js"
1261+ }
1262+ },
1263+ "patterns": [
1264+ {
1265+ "include": "#type-annotation"
1266+ }
1267+ ]
1268+ },
1269+ "function-declaration": {
1270+ "name": "meta.function.js",
1271+ "begin": "(?<!\\.|\\$)\\b(?:(export)\\s+)?(?:(async)\\s+)?(function\\b)(?:\\s*(\\*))?(?:(?:\\s+|(?<=\\*))([_$[:alpha:]][_$[:alnum:]]*))?\\s*",
1272+ "beginCaptures": {
1273+ "1": {
1274+ "name": "keyword.control.export.js"
1275+ },
1276+ "2": {
1277+ "name": "storage.modifier.async.js"
1278+ },
1279+ "3": {
1280+ "name": "storage.type.function.js"
1281+ },
1282+ "4": {
1283+ "name": "keyword.generator.asterisk.js"
1284+ },
1285+ "5": {
1286+ "name": "entity.name.function.js"
1287+ }
1288+ },
1289+ "end": "(?=;|\\})|(?<=\\})",
1290+ "patterns": [
1291+ {
1292+ "include": "#comment"
1293+ },
1294+ {
1295+ "include": "#type-parameters"
1296+ },
1297+ {
1298+ "include": "#function-parameters"
1299+ },
1300+ {
1301+ "include": "#return-type"
1302+ },
1303+ {
1304+ "include": "#function-overload-declaration"
1305+ },
1306+ {
1307+ "include": "#decl-block"
1308+ }
1309+ ]
1310+ },
1311+ "function-overload-declaration": {
1312+ "name": "meta.function.overload.js",
1313+ "match": "(?<!\\.|\\$)\\b(?:(export)\\s+)?(?:(async)\\s+)?(function\\b)(?:\\s*(\\*))?(?:(?:\\s+|(?<=\\*))([_$[:alpha:]][_$[:alnum:]]*))?\\s*",
1314+ "captures": {
1315+ "1": {
1316+ "name": "keyword.control.export.js"
1317+ },
1318+ "2": {
1319+ "name": "storage.modifier.async.js"
1320+ },
1321+ "3": {
1322+ "name": "storage.type.function.js"
1323+ },
1324+ "4": {
1325+ "name": "keyword.generator.asterisk.js"
1326+ },
1327+ "5": {
1328+ "name": "entity.name.function.js"
1329+ }
1330+ }
1331+ },
1332+ "object-literal": {
1333+ "name": "meta.objectliteral.js",
1334+ "begin": "\\{",
1335+ "beginCaptures": {
1336+ "0": {
1337+ "name": "punctuation.definition.block.js"
1338+ }
1339+ },
1340+ "end": "\\}",
1341+ "endCaptures": {
1342+ "0": {
1343+ "name": "punctuation.definition.block.js"
1344+ }
1345+ },
1346+ "patterns": [
1347+ {
1348+ "include": "#object-member"
1349+ }
1350+ ]
1351+ },
1352+ "decl-block": {
1353+ "name": "meta.block.js",
1354+ "begin": "\\{",
1355+ "beginCaptures": {
1356+ "0": {
1357+ "name": "punctuation.definition.block.js"
1358+ }
1359+ },
1360+ "end": "\\}",
1361+ "endCaptures": {
1362+ "0": {
1363+ "name": "punctuation.definition.block.js"
1364+ }
1365+ },
1366+ "patterns": [
1367+ {
1368+ "include": "#statements"
1369+ }
1370+ ]
1371+ },
1372+ "after-operator-block": {
1373+ "name": "meta.objectliteral.js",
1374+ "begin": "(?<=[=(,\\[?+!]|await|return|yield|throw|in|of|typeof|&&|\\|\\||\\*)\\s*(\\{)",
1375+ "beginCaptures": {
1376+ "1": {
1377+ "name": "punctuation.definition.block.js"
1378+ }
1379+ },
1380+ "end": "\\}",
1381+ "endCaptures": {
1382+ "0": {
1383+ "name": "punctuation.definition.block.js"
1384+ }
1385+ },
1386+ "patterns": [
1387+ {
1388+ "include": "#object-member"
1389+ }
1390+ ]
1391+ },
1392+ "parameter-name": {
1393+ "patterns": [
1394+ {
1395+ "match": "(?x)(?:\\s*\\b(readonly)\\s+)?(?:\\s*\\b(public|private|protected)\\s+)?(\\.\\.\\.)?\\s*(?<!=|:)([_$[:alpha:]][_$[:alnum:]]*)\\s*(\\??)(?=\\s* (=\\s*( (async\\s+) | (function\\s*[(<]) | (function\\s+) | ([_$[:alpha:]][_$[:alnum:]]*\\s*=>) | ((<([^<>]|\\<[^<>]+\\>)+>\\s*)?\\(([^()]|\\([^()]*\\))*\\)(\\s*:\\s*(.)*)?\\s*=>)) ) | (:\\s*( (<) | ([(]\\s*( ([)]) | (\\.\\.\\.) | ([_$[:alnum:]]+\\s*( ([:,?=])| ([)]\\s*=>) )) ))) ))",
1396+ "captures": {
1397+ "1": {
1398+ "name": "storage.modifier.js"
1399+ },
1400+ "2": {
1401+ "name": "storage.modifier.js"
1402+ },
1403+ "3": {
1404+ "name": "keyword.operator.rest.js"
1405+ },
1406+ "4": {
1407+ "name": "entity.name.function.js"
1408+ },
1409+ "5": {
1410+ "name": "keyword.operator.optional.js"
1411+ }
1412+ }
1413+ },
1414+ {
1415+ "match": "(?:\\s*\\b(readonly)\\s+)?(?:\\s*\\b(public|private|protected)\\s+)?(\\.\\.\\.)?\\s*(?<!=|:)([_$[:alpha:]][_$[:alnum:]]*)\\s*(\\??)",
1416+ "captures": {
1417+ "1": {
1418+ "name": "storage.modifier.js"
1419+ },
1420+ "2": {
1421+ "name": "storage.modifier.js"
1422+ },
1423+ "3": {
1424+ "name": "keyword.operator.rest.js"
1425+ },
1426+ "4": {
modified extensions/vscode/textmate-syntaxes/MagicPython.tmLanguage.json +3437 −3437

The diff of this file is cut short. View the file.

@@ -1,3438 +1,1563 @@
11 {
2- "name": "MagicPython",
3- "scopeName": "source.python",
4- "fileTypes": [
5- "py",
6- "py3",
7- "rpy",
8- "pyw",
9- "cpy",
10- "SConstruct",
11- "Sconstruct",
12- "sconstruct",
13- "SConscript",
14- "gyp",
15- "gypi"
16- ],
17- "first_line_match": "^#!/.*\\bpython[\\d\\.]*\\b",
18- "firstLineMatch": "^#!/.*\\bpython[\\d\\.]*\\b",
19- "uuid": "742deb57-6e38-4192-bed6-410746efd85d",
20- "patterns": [
21- {
22- "include": "#statement"
23- },
24- {
25- "include": "#expression"
26- }
27- ],
28- "repository": {
29- "statement": {
30- "patterns": [
31- {
32- "include": "#import"
33- },
34- {
35- "include": "#class-declaration"
36- },
37- {
38- "include": "#function-declaration"
39- },
40- {
41- "include": "#statement-keyword"
42- },
43- {
44- "include": "#assignment-operator"
45- },
46- {
47- "include": "#decorator"
48- },
49- {
50- "include": "#docstring-statement"
51- },
52- {
53- "include": "#semicolon"
54- }
55- ]
56- },
57- "semicolon": {
58- "patterns": [
59- {
60- "name": "invalid.deprecated.semicolon.python",
61- "match": "\\;$"
62- }
63- ]
64- },
65- "comments": {
66- "patterns": [
67- {
68- "name": "comment.line.number-sign.python",
69- "contentName": "meta.typehint.comment.python",
70- "begin": "(?x)\n (?:\n \\# \\s* (type:)\n \\s*+ (?# we want `\\s*+` which is possessive quantifier since\n we do not actually want to backtrack when matching\n whitespace here)\n (?! $ | \\#)\n )\n",
71- "end": "(?:$|(?=\\#))",
72- "beginCaptures": {
73- "0": {
74- "name": "meta.typehint.comment.python"
75- },
76- "1": {
77- "name": "comment.typehint.directive.notation.python"
78- }
79- },
80- "patterns": [
81- {
82- "name": "comment.typehint.ignore.notation.python",
83- "match": "(?x)\n \\G ignore\n (?= \\s* (?: $ | \\#))\n"
84- },
85- {
86- "name": "comment.typehint.type.notation.python",
87- "match": "(?x)\n (?<!\\.)\\b(\n bool | bytes | float | int | object | str\n | List | Dict | Iterable | Sequence | Set\n | FrozenSet | Callable | Union | Tuple\n | Any | None\n )\\b\n"
88- },
89- {
90- "name": "comment.typehint.punctuation.notation.python",
91- "match": "([\\[\\]\\(\\),\\.\\=\\*]|(->))"
92- },
93- {
94- "name": "comment.typehint.variable.notation.python",
95- "match": "([[:alpha:]_]\\w*)"
96- }
97- ]
98- },
99- {
100- "include": "#comments-base"
101- }
102- ]
103- },
104- "docstring-statement": {
105- "begin": "^(?=\\s*[rR]?(\\'\\'\\'|\\\"\\\"\\\"|\\'|\\\"))",
106- "end": "(?<=\\'\\'\\'|\\\"\\\"\\\"|\\'|\\\")",
107- "patterns": [
108- {
109- "include": "#docstring"
110- }
111- ]
112- },
113- "docstring": {
114- "patterns": [
115- {
116- "name": "string.quoted.docstring.multi.python",
117- "begin": "(\\'\\'\\'|\\\"\\\"\\\")",
118- "end": "(\\1)",
119- "beginCaptures": {
120- "1": {
121- "name": "punctuation.definition.string.begin.python"
122- }
123- },
124- "endCaptures": {
125- "1": {
126- "name": "punctuation.definition.string.end.python"
127- }
128- },
129- "patterns": [
130- {
131- "include": "#docstring-prompt"
132- },
133- {
134- "include": "#codetags"
135- },
136- {
137- "include": "#docstring-guts-unicode"
138- }
139- ]
140- },
141- {
142- "name": "string.quoted.docstring.raw.multi.python",
143- "begin": "([rR])(\\'\\'\\'|\\\"\\\"\\\")",
144- "end": "(\\2)",
145- "beginCaptures": {
146- "1": {
147- "name": "storage.type.string.python"
148- },
149- "2": {
150- "name": "punctuation.definition.string.begin.python"
151- }
152- },
153- "endCaptures": {
154- "1": {
155- "name": "punctuation.definition.string.end.python"
156- }
157- },
158- "patterns": [
159- {
160- "include": "#string-consume-escape"
161- },
162- {
163- "include": "#docstring-prompt"
164- },
165- {
166- "include": "#codetags"
167- }
168- ]
169- },
170- {
171- "name": "string.quoted.docstring.single.python",
172- "begin": "(\\'|\\\")",
173- "end": "(\\1)|((?<!\\\\)\\n)",
174- "beginCaptures": {
175- "1": {
176- "name": "punctuation.definition.string.begin.python"
177- }
178- },
179- "endCaptures": {
180- "1": {
181- "name": "punctuation.definition.string.end.python"
182- },
183- "2": {
184- "name": "invalid.illegal.newline.python"
185- }
186- },
187- "patterns": [
188- {
189- "include": "#codetags"
190- },
191- {
192- "include": "#docstring-guts-unicode"
193- }
194- ]
195- },
196- {
197- "name": "string.quoted.docstring.raw.single.python",
198- "begin": "([rR])(\\'|\\\")",
199- "end": "(\\2)|((?<!\\\\)\\n)",
200- "beginCaptures": {
201- "1": {
202- "name": "storage.type.string.python"
203- },
204- "2": {
205- "name": "punctuation.definition.string.begin.python"
206- }
207- },
208- "endCaptures": {
209- "1": {
210- "name": "punctuation.definition.string.end.python"
211- },
212- "2": {
213- "name": "invalid.illegal.newline.python"
214- }
215- },
216- "patterns": [
217- {
218- "include": "#string-consume-escape"
219- },
220- {
221- "include": "#codetags"
222- }
223- ]
224- }
225- ]
226- },
227- "docstring-guts-unicode": {
228- "patterns": [
229- {
230- "include": "#escape-sequence-unicode"
231- },
232- {
233- "include": "#escape-sequence"
234- },
235- {
236- "include": "#string-line-continuation"
237- }
238- ]
239- },
240- "docstring-prompt": {
241- "match": "(?x)\n (?:\n (?:^|\\G) \\s* (?# '\\G' is necessary for ST)\n ((?:>>>|\\.\\.\\.) \\s) (?=\\s*\\S)\n )\n",
242- "captures": {
243- "1": {
244- "name": "keyword.control.flow.python"
245- }
246- }
247- },
248- "codetags": {
249- "match": "(?:\\b(NOTE|XXX|HACK|FIXME|BUG|TODO)\\b)",
250- "captures": {
251- "1": {
252- "name": "keyword.codetag.notation.python"
253- }
254- }
255- },
256- "statement-keyword": {
257- "patterns": [
258- {
259- "name": "storage.type.function.python",
260- "match": "\\b((async\\s+)?\\s*def)\\b"
261- },
262- {
263- "name": "keyword.control.flow.python",
264- "match": "(?x)\n \\b(?<!\\.)(\n as | async | continue | del | assert | break | finally | for\n | from | elif | else | if | except | pass | raise\n | return | try | while | with\n )\\b\n"
265- },
266- {
267- "name": "storage.modifier.declaration.python",
268- "match": "(?x)\n \\b(?<!\\.)(\n global | nonlocal\n )\\b\n"
269- },
270- {
271- "name": "storage.type.class.python",
272- "match": "\\b(?<!\\.)(class)\\b"
273- }
274- ]
275- },
276- "expression-base": {
277- "comment": "All valid Python expressions",
278- "patterns": [
279- {
280- "include": "#backticks"
281- },
282- {
283- "include": "#illegal-anno"
284- },
285- {
286- "include": "#comments"
287- },
288- {
289- "include": "#literal"
290- },
291- {
292- "include": "#regexp"
293- },
294- {
295- "include": "#string"
296- },
297- {
298- "include": "#lambda"
299- },
300- {
301- "include": "#illegal-operator"
302- },
303- {
304- "include": "#operator"
305- },
306- {
307- "include": "#curly-braces"
308- },
309- {
310- "include": "#item-access"
311- },
312- {
313- "include": "#list"
314- },
315- {
316- "include": "#round-braces"
317- },
318- {
319- "include": "#function-call"
320- },
321- {
322- "include": "#builtin-functions"
323- },
324- {
325- "include": "#builtin-types"
326- },
327- {
328- "include": "#builtin-exceptions"
329- },
330- {
331- "include": "#magic-names"
332- },
333- {
334- "include": "#special-names"
335- },
336- {
337- "include": "#illegal-names"
338- },
339- {
340- "include": "#special-variables"
341- },
342- {
343- "include": "#line-continuation"
344- },
345- {
346- "include": "#ellipsis"
347- }
348- ]
349- },
350- "expression": {
351- "comment": "All valid Python expressions",
352- "patterns": [
353- {
354- "include": "#expression-base"
355- },
356- {
357- "include": "#member-access"
358- },
359- {
360- "comment": "Tokenize identifiers to help linters",
361- "match": "(?x) \\b ([[:alpha:]_]\\w*) \\b"
362- }
363- ]
364- },
365- "member-access": {
366- "begin": "\\.\\s*(?!\\.)",
367- "end": "(?x)\n # stop when you've just read non-whitespace followed by non-word\n # i.e. when finished reading an identifier or function call\n (?<=\\S)(?=\\W) |\n # stop when seeing the start of something that's not a word,\n # i.e. when seeing a non-identifier\n (^|(?<=\\s))(?=[^\\\\\\w\\s]) |\n $\n",
368- "patterns": [
369- {
370- "include": "#function-call"
371- },
372- {
373- "include": "#member-access-base"
374- }
375- ]
376- },
377- "member-access-base": {
378- "patterns": [
379- {
380- "include": "#magic-names"
381- },
382- {
383- "include": "#illegal-names"
384- },
385- {
386- "include": "#illegal-object-name"
387- },
388- {
389- "include": "#special-names"
390- },
391- {
392- "include": "#line-continuation"
393- },
394- {
395- "include": "#item-access"
396- }
397- ]
398- },
399- "special-names": {
400- "name": "constant.other.caps.python",
401- "match": "(?x)\n \\b\n (\n _* [[:upper:]]\n )\n [[:upper:]\\d]* (_\\w*)?\n \\b\n"
402- },
403- "curly-braces": {
404- "begin": "\\{",
405- "end": "\\}",
406- "beginCaptures": {
407- "0": {
408- "name": "punctuation.definition.dict.begin.python"
409- }
410- },
411- "endCaptures": {
412- "0": {
413- "name": "punctuation.definition.dict.end.python"
414- }
415- },
416- "patterns": [
417- {
418- "include": "#expression"
419- }
420- ]
421- },
422- "list": {
423- "begin": "\\[",
424- "end": "\\]",
425- "beginCaptures": {
426- "0": {
427- "name": "punctuation.definition.list.begin.python"
428- }
429- },
430- "endCaptures": {
431- "0": {
432- "name": "punctuation.definition.list.end.python"
433- }
434- },
435- "patterns": [
436- {
437- "include": "#expression"
438- }
439- ]
440- },
441- "round-braces": {
442- "begin": "\\(",
443- "end": "\\)",
444- "beginCaptures": {
445- "0": {
446- "name": "punctuation.parenthesis.begin.python"
447- }
448- },
449- "endCaptures": {
450- "0": {
451- "name": "punctuation.parenthesis.end.python"
452- }
453- },
454- "patterns": [
455- {
456- "include": "#expression"
457- }
458- ]
459- },
460- "line-continuation": {
461- "patterns": [
462- {
463- "match": "(\\\\)\\s*(\\S.*$\\n?)",
464- "captures": {
465- "1": {
466- "name": "separator.continuation.line.python"
467- },
468- "2": {
469- "name": "invalid.illegal.line.continuation.python"
470- }
471- }
472- },
473- {
474- "begin": "(\\\\)\\s*$\\n?",
475- "end": "(?x)\n (?=^\\s*$)\n |\n (?! (\\s* [rR]? (\\'\\'\\'|\\\"\\\"\\\"|\\'|\\\"))\n |\n (\\G $) (?# '\\G' is necessary for ST)\n )\n",
476- "beginCaptures": {
477- "1": {
478- "name": "separator.continuation.line.python"
479- }
480- },
481- "patterns": [
482- {
483- "include": "#regexp"
484- },
485- {
486- "include": "#string"
487- }
488- ]
489- }
490- ]
491- },
492- "assignment-operator": {
493- "name": "keyword.operator.assignment.python",
494- "match": "(?x)\n <<= | >>= | //= | \\*\\*=\n | \\+= | -= | /= | @=\n | \\*= | %= | ~= | \\^= | &= | \\|=\n | =(?!=)\n"
495- },
496- "operator": {
497- "match": "(?x)\n \\b(?<!\\.)\n (?:\n (and | or | not | in | is) (?# 1)\n |\n (for | if | else | await | (?:yield(?:\\s+from)?)) (?# 2)\n )\n (?!\\s*:)\\b\n\n | (<< | >> | & | \\| | \\^ | ~) (?# 3)\n\n | (\\*\\* | \\* | \\+ | - | % | // | / | @) (?# 4)\n\n | (!= | == | >= | <= | < | >) (?# 5)\n",
498- "captures": {
499- "1": {
500- "name": "keyword.operator.logical.python"
501- },
502- "2": {
503- "name": "keyword.control.flow.python"
504- },
505- "3": {
506- "name": "keyword.operator.bitwise.python"
507- },
508- "4": {
509- "name": "keyword.operator.arithmetic.python"
510- },
511- "5": {
512- "name": "keyword.operator.comparison.python"
513- }
514- }
515- },
516- "literal": {
517- "patterns": [
518- {
519- "name": "constant.language.python",
520- "match": "\\b(True|False|None|NotImplemented|Ellipsis)\\b"
521- },
522- {
523- "include": "#number"
524- }
525- ]
526- },
527- "number": {
528- "name": "constant.numeric.python",
529- "patterns": [
530- {
531- "include": "#number-float"
532- },
533- {
534- "include": "#number-dec"
535- },
536- {
537- "include": "#number-hex"
538- },
539- {
540- "include": "#number-oct"
541- },
542- {
543- "include": "#number-bin"
544- },
545- {
546- "include": "#number-long"
547- },
548- {
549- "name": "invalid.illegal.name.python",
550- "match": "\\b[0-9]+\\w+"
551- }
552- ]
553- },
554- "number-float": {
555- "name": "constant.numeric.float.python",
556- "match": "(?x)\n (?<! \\w)(?:\n [0-9]*\\.[0-9]+ ([eE][+-]?[0-9]+)?\n | [0-9]+\\. ([eE][+-]?[0-9]+)?\n | [0-9]+ ([eE][+-]?[0-9]+)\n )([jJ])?\\b\n",
557- "captures": {
558- "4": {
559- "name": "storage.type.imaginary.number.python"
560- }
561- }
562- },
563- "number-dec": {
564- "name": "constant.numeric.dec.python",
565- "match": "(?x)\n (?<![\\w\\.])(?:\n [1-9][0-9]*\n |\n 0+\n |\n [0-9]+ ([jJ])\n |\n 0 ([0-9]+)(?![eE\\.])\n )\\b\n",
566- "captures": {
567- "1": {
568- "name": "storage.type.imaginary.number.python"
569- },
570- "2": {
571- "name": "invalid.illegal.dec.python"
572- },
573- "3": {
574- "name": "invalid.illegal.dec.python"
575- }
576- }
577- },
578- "number-hex": {
579- "name": "constant.numeric.hex.python",
580- "match": "(?x)\n (?<![\\w\\.])\n (0[xX]) [0-9a-fA-F]+\n \\b\n",
581- "captures": {
582- "1": {
583- "name": "storage.type.number.python"
584- }
585- }
586- },
587- "number-oct": {
588- "name": "constant.numeric.oct.python",
589- "match": "(?x)\n (?<![\\w\\.])\n (0[oO]) [0-7]+\n \\b\n",
590- "captures": {
591- "1": {
592- "name": "storage.type.number.python"
593- }
594- }
595- },
596- "number-bin": {
597- "name": "constant.numeric.bin.python",
598- "match": "(?x)\n (?<![\\w\\.])\n (0[bB]) [01]+\n \\b\n",
599- "captures": {
600- "1": {
601- "name": "storage.type.number.python"
602- }
603- }
604- },
605- "number-long": {
606- "name": "constant.numeric.bin.python",
607- "comment": "this is to support python2 syntax for long ints",
608- "match": "(?x)\n (?<![\\w\\.])\n ([1-9][0-9]* | 0) ([lL])\n \\b\n",
609- "captures": {
610- "2": {
611- "name": "storage.type.number.python"
612- }
613- }
614- },
615- "regexp": {
616- "patterns": [
617- {
618- "include": "#regexp-single-quoted-multi-line"
619- },
620- {
621- "include": "#regexp-double-quoted-multi-line"
622- },
623- {
624- "include": "#regexp-single-quoted-single-line"
625- },
626- {
627- "include": "#regexp-double-quoted-single-line"
628- }
629- ]
630- },
631- "regexp-single-quoted-single-line": {
632- "name": "string.regexp.quoted.single.python",
633- "begin": "\\b(([uU]r)|([bB]r)|(r[bB]?))(\\')",
634- "end": "(\\')|(?<!\\\\)(\\n)",
635- "beginCaptures": {
636- "2": {
637- "name": "invalid.deprecated.prefix.python"
638- },
639- "3": {
640- "name": "storage.type.string.python"
641- },
642- "4": {
643- "name": "storage.type.string.python"
644- },
645- "5": {
646- "name": "punctuation.definition.string.begin.python"
647- }
648- },
649- "endCaptures": {
650- "1": {
651- "name": "punctuation.definition.string.end.python"
652- },
653- "2": {
654- "name": "invalid.illegal.newline.python"
655- }
656- },
657- "patterns": [
658- {
659- "include": "#single-one-regexp-expression"
660- }
661- ]
662- },
663- "regexp-double-quoted-single-line": {
664- "name": "string.regexp.quoted.single.python",
665- "begin": "\\b(([uU]r)|([bB]r)|(r[bB]?))(\\\")",
666- "end": "(\\\")|(?<!\\\\)(\\n)",
667- "beginCaptures": {
668- "2": {
669- "name": "invalid.deprecated.prefix.python"
670- },
671- "3": {
672- "name": "storage.type.string.python"
673- },
674- "4": {
675- "name": "storage.type.string.python"
676- },
677- "5": {
678- "name": "punctuation.definition.string.begin.python"
679- }
680- },
681- "endCaptures": {
682- "1": {
683- "name": "punctuation.definition.string.end.python"
684- },
685- "2": {
686- "name": "invalid.illegal.newline.python"
687- }
688- },
689- "patterns": [
690- {
691- "include": "#double-one-regexp-expression"
692- }
693- ]
694- },
695- "regexp-single-quoted-multi-line": {
696- "name": "string.regexp.quoted.multi.python",
697- "begin": "\\b(([uU]r)|([bB]r)|(r[bB]?))(\\'\\'\\')",
698- "end": "\\'\\'\\'",
699- "beginCaptures": {
700- "2": {
701- "name": "invalid.deprecated.prefix.python"
702- },
703- "3": {
704- "name": "storage.type.string.python"
705- },
706- "4": {
707- "name": "storage.type.string.python"
708- },
709- "5": {
710- "name": "punctuation.definition.string.begin.python"
711- }
712- },
713- "endCaptures": {
714- "0": {
715- "name": "punctuation.definition.string.end.python"
716- }
717- },
718- "patterns": [
719- {
720- "include": "#single-three-regexp-expression"
721- }
722- ]
723- },
724- "regexp-double-quoted-multi-line": {
725- "name": "string.regexp.quoted.multi.python",
726- "begin": "\\b(([uU]r)|([bB]r)|(r[bB]?))(\\\"\\\"\\\")",
727- "end": "\\\"\\\"\\\"",
728- "beginCaptures": {
729- "2": {
730- "name": "invalid.deprecated.prefix.python"
731- },
732- "3": {
733- "name": "storage.type.string.python"
734- },
735- "4": {
736- "name": "storage.type.string.python"
737- },
738- "5": {
739- "name": "punctuation.definition.string.begin.python"
740- }
741- },
742- "endCaptures": {
743- "0": {
744- "name": "punctuation.definition.string.end.python"
745- }
746- },
747- "patterns": [
748- {
749- "include": "#double-three-regexp-expression"
750- }
751- ]
752- },
753- "string": {
754- "patterns": [
755- {
756- "include": "#string-quoted-multi-line"
757- },
758- {
759- "include": "#string-quoted-single-line"
760- },
761- {
762- "include": "#string-bin-quoted-multi-line"
763- },
764- {
765- "include": "#string-bin-quoted-single-line"
766- },
767- {
768- "include": "#string-raw-quoted-multi-line"
769- },
770- {
771- "include": "#string-raw-quoted-single-line"
772- },
773- {
774- "include": "#string-raw-bin-quoted-multi-line"
775- },
776- {
777- "include": "#string-raw-bin-quoted-single-line"
778- }
779- ]
780- },
781- "string-unicode-guts": {
782- "patterns": [
783- {
784- "include": "#escape-sequence-unicode"
785- },
786- {
787- "include": "#string-entity"
788- },
789- {
790- "include": "#string-brace-formatting"
791- }
792- ]
793- },
794- "string-consume-escape": {
795- "match": "\\\\['\"\\n\\\\]"
796- },
797- "string-raw-guts": {
798- "patterns": [
799- {
800- "include": "#string-consume-escape"
801- },
802- {
803- "include": "#string-formatting"
804- },
805- {
806- "include": "#string-brace-formatting"
807- }
808- ]
809- },
810- "string-raw-bin-guts": {
811- "patterns": [
812- {
813- "include": "#string-consume-escape"
814- },
815- {
816- "include": "#string-formatting"
817- }
818- ]
819- },
820- "string-entity": {
821- "patterns": [
822- {
823- "include": "#escape-sequence"
824- },
825- {
826- "include": "#string-line-continuation"
827- },
828- {
829- "include": "#string-formatting"
830- }
831- ]
832- },
833- "escape-sequence-unicode": {
834- "patterns": [
835- {
836- "name": "constant.character.escape.python",
837- "match": "(?x)\n \\\\ (\n u[0-9A-Fa-f]{4}\n | U[0-9A-Fa-f]{8}\n | N\\{[\\w\\s]+?\\}\n )\n"
838- }
839- ]
840- },
841- "escape-sequence": {
842- "name": "constant.character.escape.python",
843- "match": "(?x)\n \\\\ (\n x[0-9A-Fa-f]{2}\n | [0-7]{1,3}\n | [\\\\\"'abfnrtv]\n )\n"
844- },
845- "string-line-continuation": {
846- "name": "constant.language.python",
847- "match": "\\\\$"
848- },
849- "string-formatting": {
850- "name": "constant.character.format.placeholder.other.python",
851- "match": "(?x)\n % (\\([\\w\\s]*\\))?\n [-+#0 ]*\n (\\d+|\\*)? (\\.(\\d+|\\*))?\n ([hlL])?\n [diouxXeEfFgGcrsa%]\n"
852- },
853- "string-brace-formatting": {
854- "patterns": [
855- {
856- "name": "constant.character.format.placeholder.other.python",
857- "match": "(?x)\n (?:\n {{ | }}\n | (?:\n {\n \\w*? (\\.[[:alpha:]_]\\w*? | \\[[^\\]'\"]+\\])*?\n (![rsa])?\n ( : \\w? [<>=^]? [-+ ]? \\#?\n \\d* ,? (\\.\\d+)? [bcdeEfFgGnosxX%]? )?\n })\n )\n",
858- "captures": {
859- "2": {
860- "name": "storage.type.format.python"
861- },
862- "3": {
863- "name": "support.other.format.python"
864- }
865- }
866- },
867- {
868- "name": "constant.character.format.placeholder.other.python",
869- "begin": "(?x)\n \\{\n \\w*? (\\.[[:alpha:]_]\\w*? | \\[[^\\]'\"]+\\])*?\n (![rsa])?\n (:)\n (?=[^'\"}\\n]*\\})\n",
870- "end": "\\}",
871- "beginCaptures": {
872- "2": {
873- "name": "storage.type.format.python"
874- },
875- "3": {
876- "name": "support.other.format.python"
877- }
878- },
879- "patterns": [
880- {
881- "match": "(?x) \\{ [^'\"}\\n]*? \\} (?=.*?\\})\n"
882- }
883- ]
884- }
885- ]
886- },
887- "import": {
888- "comment": "Import statements\n",
889- "patterns": [
890- {
891- "match": "(?x)\n \\s* \\b(from)\\b (\\s*\\.+\\s*) (import)?\n",
892- "captures": {
893- "1": {
894- "name": "keyword.control.import.python"
895- },
896- "3": {
897- "name": "keyword.control.import.python"
898- }
899- }
900- },
901- {
902- "name": "keyword.control.import.python",
903- "match": "\\b(?<!\\.)import\\b"
904- }
905- ]
906- },
907- "class-declaration": {
908- "patterns": [
909- {
910- "name": "meta.class.python",
911- "begin": "(?x)\n \\s*(class)\\s+\n (?=\n [[:alpha:]_]\\w* \\s* (:|\\()\n )\n",
912- "end": "(:)",
913- "beginCaptures": {
914- "1": {
915- "name": "storage.type.class.python"
916- }
917- },
918- "endCaptures": {
919- "1": {
920- "name": "punctuation.section.class.begin.python"
921- }
922- },
923- "patterns": [
924- {
925- "include": "#class-name"
926- },
927- {
928- "include": "#class-inheritance"
929- }
930- ]
931- }
932- ]
933- },
934- "class-name": {
935- "patterns": [
936- {
937- "include": "#illegal-object-name"
938- },
939- {
940- "include": "#builtin-possible-callables"
941- },
942- {
943- "name": "entity.name.type.class.python",
944- "match": "(?x)\n \\b ([[:alpha:]_]\\w*) \\b\n"
945- }
946- ]
947- },
948- "class-inheritance": {
949- "name": "meta.class.inheritance.python",
950- "begin": "(\\()",
951- "end": "(\\))",
952- "beginCaptures": {
953- "1": {
954- "name": "punctuation.definition.inheritance.begin.python"
955- }
956- },
957- "endCaptures": {
958- "1": {
959- "name": "punctuation.definition.inheritance.end.python"
960- }
961- },
962- "patterns": [
963- {
964- "name": "keyword.operator.unpacking.arguments.python",
965- "match": "(\\*\\*|\\*)"
966- },
967- {
968- "name": "punctuation.separator.inheritance.python",
969- "match": ","
970- },
971- {
972- "name": "keyword.operator.assignment.python",
973- "match": "=(?!=)"
974- },
975- {
976- "include": "#expression-class"
977- },
978- {
979- "name": "support.type.metaclass.python",
980- "match": "\\bmetaclass\\b"
981- },
982- {
983- "include": "#inheritance-identifier"
984- }
985- ]
986- },
987- "inheritance-identifier": {
988- "match": "(?x)\n \\b ([[:alpha:]_]\\w*) \\b\n",
989- "captures": {
990- "1": {
991- "name": "entity.other.inherited-class.python"
992- }
993- }
994- },
995- "expression-class": {
996- "patterns": [
997- {
998- "include": "#call-wrapper-inheritance"
999- },
1000- {
1001- "include": "#expression-base"
1002- },
1003- {
1004- "include": "#member-access-class"
1005- }
1006- ]
1007- },
1008- "member-access-class": {
1009- "begin": "\\.\\s*(?!\\.)",
1010- "end": "(?<=\\S)(?=\\W)|$",
1011- "patterns": [
1012- {
1013- "include": "#call-wrapper-inheritance"
1014- },
1015- {
1016- "include": "#member-access-base"
1017- },
1018- {
1019- "include": "#inheritance-identifier"
1020- }
1021- ]
1022- },
1023- "lambda": {
1024- "patterns": [
1025- {
1026- "match": "((?<=\\.)lambda|lambda(?=\\s*[\\.=]))",
1027- "captures": {
1028- "1": {
1029- "name": "keyword.control.flow.python"
1030- }
1031- }
1032- },
1033- {
1034- "match": "\\b(lambda)\\s*?([,\\n]|$)",
1035- "captures": {
1036- "1": {
1037- "name": "storage.type.function.lambda.python"
1038- }
1039- }
1040- },
1041- {
1042- "name": "meta.lambda-function.python",
1043- "begin": "(?x)\n \\b (lambda) \\b\n",
1044- "end": "(:)|(\\n)",
1045- "beginCaptures": {
1046- "1": {
1047- "name": "storage.type.function.lambda.python"
1048- }
1049- },
1050- "endCaptures": {
1051- "1": {
1052- "name": "punctuation.section.function.lambda.begin.python"
1053- }
1054- },
1055- "contentName": "meta.function.lambda.parameters.python",
1056- "patterns": [
1057- {
1058- "name": "keyword.operator.unpacking.parameter.python",
1059- "match": "(\\*\\*|\\*)"
1060- },
1061- {
1062- "include": "#lambda-incomplete"
1063- },
1064- {
1065- "include": "#illegal-names"
1066- },
1067- {
1068- "match": "([[:alpha:]_]\\w*)\\s*(?:(,)|(?=:|$))",
1069- "captures": {
1070- "1": {
1071- "name": "variable.parameter.function.language.python"
1072- },
1073- "2": {
1074- "name": "punctuation.separator.parameters.python"
1075- }
1076- }
1077- },
1078- {
1079- "include": "#comments"
1080- },
1081- {
1082- "include": "#backticks"
1083- },
1084- {
1085- "include": "#illegal-anno"
1086- },
1087- {
1088- "include": "#lambda-parameter-with-default"
1089- },
1090- {
1091- "include": "#line-continuation"
1092- },
1093- {
1094- "include": "#illegal-operator"
1095- }
1096- ]
1097- }
1098- ]
1099- },
1100- "lambda-incomplete": {
1101- "name": "storage.type.function.lambda.python",
1102- "match": "\\blambda(?=\\s*[:,)])"
1103- },
1104- "lambda-parameter-with-default": {
1105- "begin": "(?x)\n \\b\n ([[:alpha:]_]\\w*) \\s* (=)\n",
1106- "end": "(,)|(?=:|$)",
1107- "beginCaptures": {
1108- "1": {
1109- "name": "variable.parameter.function.language.python"
1110- },
1111- "2": {
1112- "name": "keyword.operator.python"
1113- }
1114- },
1115- "endCaptures": {
1116- "1": {
1117- "name": "punctuation.separator.parameters.python"
1118- }
1119- },
1120- "patterns": [
1121- {
1122- "include": "#expression"
1123- }
1124- ]
1125- },
1126- "function-declaration": {
1127- "name": "meta.function.python",
1128- "begin": "(?x)\n \\s*\n (?:\\b(async) \\s+)? \\b(def)\\s+\n (?=\n [[:alpha:]_][[:word:]]* \\s* \\(\n )\n",
1129- "end": "(:|(?=[#'\"\\n]))",
1130- "beginCaptures": {
1131- "1": {
1132- "name": "storage.type.function.async.python"
1133- },
1134- "2": {
1135- "name": "storage.type.function.python"
1136- }
1137- },
1138- "endCaptures": {
1139- "1": {
1140- "name": "punctuation.section.function.begin.python"
1141- }
1142- },
1143- "patterns": [
1144- {
1145- "include": "#function-def-name"
1146- },
1147- {
1148- "include": "#parameters"
1149- },
1150- {
1151- "include": "#line-continuation"
1152- },
1153- {
1154- "include": "#return-annotation"
1155- }
1156- ]
1157- },
1158- "function-def-name": {
1159- "patterns": [
1160- {
1161- "include": "#illegal-object-name"
1162- },
1163- {
1164- "include": "#builtin-possible-callables"
1165- },
1166- {
1167- "name": "entity.name.function.python",
1168- "match": "(?x)\n \\b ([[:alpha:]_]\\w*) \\b\n"
1169- }
1170- ]
1171- },
1172- "parameters": {
1173- "name": "meta.function.parameters.python",
1174- "begin": "(\\()",
1175- "end": "(\\))",
1176- "beginCaptures": {
1177- "1": {
1178- "name": "punctuation.definition.parameters.begin.python"
1179- }
1180- },
1181- "endCaptures": {
1182- "1": {
1183- "name": "punctuation.definition.parameters.end.python"
1184- }
1185- },
1186- "patterns": [
1187- {
1188- "name": "keyword.operator.unpacking.parameter.python",
1189- "match": "(\\*\\*|\\*)"
1190- },
1191- {
1192- "include": "#lambda-incomplete"
1193- },
1194- {
1195- "include": "#illegal-names"
1196- },
1197- {
1198- "include": "#illegal-object-name"
1199- },
1200- {
1201- "include": "#parameter-special"
1202- },
1203- {
1204- "match": "(?x)\n ([[:alpha:]_]\\w*)\n \\s* (?: (,) | (?=[)#\\n=]))\n",
1205- "captures": {
1206- "1": {
1207- "name": "variable.parameter.function.language.python"
1208- },
1209- "2": {
1210- "name": "punctuation.separator.parameters.python"
1211- }
1212- }
1213- },
1214- {
1215- "include": "#comments"
1216- },
1217- {
1218- "include": "#loose-default"
1219- },
1220- {
1221- "include": "#annotated-parameter"
1222- }
1223- ]
1224- },
1225- "parameter-special": {
1226- "match": "(?x)\n \\b ((self)|(cls)) \\b \\s*(?:(,)|(?=\\)))\n",
1227- "captures": {
1228- "1": {
1229- "name": "variable.parameter.function.language.python"
1230- },
1231- "2": {
1232- "name": "variable.parameter.function.language.special.self.python"
1233- },
1234- "3": {
1235- "name": "variable.parameter.function.language.special.cls.python"
1236- },
1237- "4": {
1238- "name": "punctuation.separator.parameters.python"
1239- }
1240- }
1241- },
1242- "loose-default": {
1243- "begin": "(=)",
1244- "end": "(,)|(?=\\))",
1245- "beginCaptures": {
1246- "1": {
1247- "name": "keyword.operator.python"
1248- }
1249- },
1250- "endCaptures": {
1251- "1": {
1252- "name": "punctuation.separator.parameters.python"
1253- }
1254- },
1255- "patterns": [
1256- {
1257- "include": "#expression"
1258- }
1259- ]
1260- },
1261- "annotated-parameter": {
1262- "begin": "(?x)\n \\b\n ([[:alpha:]_]\\w*) \\s* (:)\n",
1263- "end": "(,)|(?=\\))",
1264- "beginCaptures": {
1265- "1": {
1266- "name": "variable.parameter.function.language.python"
1267- },
1268- "2": {
1269- "name": "punctuation.separator.annotation.python"
1270- }
1271- },
1272- "endCaptures": {
1273- "1": {
1274- "name": "punctuation.separator.parameters.python"
1275- }
1276- },
1277- "patterns": [
1278- {
1279- "include": "#expression"
1280- },
1281- {
1282- "name": "keyword.operator.assignment.python",
1283- "match": "=(?!=)"
1284- }
1285- ]
1286- },
1287- "return-annotation": {
1288- "begin": "(->)",
1289- "end": "(?=:)",
1290- "beginCaptures": {
1291- "1": {
1292- "name": "punctuation.separator.annotation.result.python"
1293- }
1294- },
1295- "patterns": [
1296- {
1297- "include": "#expression"
1298- }
1299- ]
1300- },
1301- "item-access": {
1302- "patterns": [
1303- {
1304- "name": "meta.item-access.python",
1305- "begin": "(?x)\n \\b(?=\n [[:alpha:]_]\\w* \\s* \\[\n )\n",
1306- "end": "(\\])",
1307- "endCaptures": {
1308- "1": {
1309- "name": "punctuation.definition.arguments.end.python"
1310- }
1311- },
1312- "patterns": [
1313- {
1314- "include": "#item-name"
1315- },
1316- {
1317- "include": "#item-index"
1318- },
1319- {
1320- "include": "#expression"
1321- }
1322- ]
1323- }
1324- ]
1325- },
1326- "item-name": {
1327- "patterns": [
1328- {
1329- "include": "#special-variables"
1330- },
1331- {
1332- "include": "#builtin-functions"
1333- },
1334- {
1335- "include": "#special-names"
1336- },
1337- {
1338- "match": "(?x)\n \\b ([[:alpha:]_]\\w*) \\b\n"
1339- }
1340- ]
1341- },
1342- "item-index": {
1343- "begin": "(\\[)",
1344- "end": "(?=\\])",
1345- "beginCaptures": {
1346- "1": {
1347- "name": "punctuation.definition.arguments.begin.python"
1348- }
1349- },
1350- "contentName": "meta.item-access.arguments.python",
1351- "patterns": [
1352- {
1353- "include": "#expression"
1354- }
1355- ]
1356- },
1357- "decorator": {
1358- "name": "meta.function.decorator.python",
1359- "begin": "(?x)\n ^\\s*\n (@) \\s* (?=[[:alpha:]_]\\w*)\n",
1360- "end": "(?x)\n ( \\) ) (?: (?=\\s*\\#|$) | (.*$) )\n | (?=\\n|\\#)\n",
1361- "beginCaptures": {
1362- "1": {
1363- "name": "entity.name.function.decorator.python"
1364- }
1365- },
1366- "endCaptures": {
1367- "1": {
1368- "name": "punctuation.definition.arguments.end.python"
1369- },
1370- "2": {
1371- "name": "invalid.illegal.decorator.python"
1372- }
1373- },
1374- "patterns": [
1375- {
1376- "include": "#decorator-name"
1377- },
1378- {
1379- "include": "#function-arguments"
1380- }
1381- ]
1382- },
1383- "decorator-name": {
1384- "patterns": [
1385- {
1386- "include": "#builtin-callables"
1387- },
1388- {
1389- "include": "#illegal-object-name"
1390- },
1391- {
1392- "name": "entity.name.function.decorator.python",
1393- "match": "(?x)\n ([[:alpha:]_]\\w*) | \\.\n"
1394- },
1395- {
1396- "include": "#line-continuation"
1397- },
1398- {
1399- "name": "invalid.illegal.decorator.python",
1400- "match": "(?x)\n \\s* ([^([:alpha:]\\s_\\.#\\\\] .*?) (?=\\#|$)\n",
1401- "captures": {
1402- "1": {
1403- "name": "invalid.illegal.decorator.python"
1404- }
1405- }
1406- }
1407- ]
1408- },
1409- "call-wrapper-inheritance": {
1410- "comment": "same as a funciton call, but in inheritance context",
1411- "name": "meta.function-call.python",
1412- "begin": "(?x)\n \\b(?=\n ([[:alpha:]_]\\w*) \\s* (\\()\n )\n",
1413- "end": "(\\))",
1414- "endCaptures": {
1415- "1": {
1416- "name": "punctuation.definition.arguments.end.python"
1417- }
1418- },
1419- "patterns": [
1420- {
1421- "include": "#inheritance-name"
1422- },
1423- {
1424- "include": "#function-arguments"
1425- }
1426- ]
1427- },
1428- "inheritance-name": {
1429- "patterns": [
1430- {
1431- "include": "#lambda-incomplete"
1432- },
1433- {
1434- "include": "#builtin-possible-callables"
1435- },
1436- {
1437- "include": "#inheritance-identifier"
1438- }
1439- ]
1440- },
1441- "function-call": {
1442- "name": "meta.function-call.python",
1443- "begin": "(?x)\n \\b(?=\n ([[:alpha:]_]\\w*) \\s* (\\()\n )\n",
1444- "end": "(\\))",
1445- "endCaptures": {
1446- "1": {
1447- "name": "punctuation.definition.arguments.end.python"
1448- }
1449- },
1450- "patterns": [
1451- {
1452- "include": "#special-variables"
1453- },
1454- {
1455- "include": "#function-name"
1456- },
1457- {
1458- "include": "#function-arguments"
1459- }
1460- ]
1461- },
1462- "function-name": {
1463- "patterns": [
1464- {
1465- "include": "#builtin-possible-callables"
1466- },
1467- {
1468- "comment": "Some color schemas support meta.function-call.generic scope",
1469- "name": "meta.function-call.generic.python",
1470- "match": "(?x)\n \\b ([[:alpha:]_]\\w*) \\b\n"
1471- }
1472- ]
1473- },
1474- "function-arguments": {
1475- "begin": "(?x)\n (?:\n (\\()\n (?:\\s*(\\*\\*|\\*))?\n )\n",
1476- "end": "(?=\\))(?!\\)\\s*\\()",
1477- "beginCaptures": {
1478- "1": {
1479- "name": "punctuation.definition.arguments.begin.python"
1480- },
1481- "2": {
1482- "name": "keyword.operator.unpacking.arguments.python"
1483- }
1484- },
1485- "contentName": "meta.function-call.arguments.python",
1486- "patterns": [
1487- {
1488- "match": "(?x)\n (?:\n (,)\n (?:\\s*(\\*\\*|\\*))?\n )\n",
1489- "captures": {
1490- "1": {
1491- "name": "punctuation.separator.arguments.python"
1492- },
1493- "2": {
1494- "name": "keyword.operator.unpacking.arguments.python"
1495- }
1496- }
1497- },
1498- {
1499- "include": "#lambda-incomplete"
1500- },
1501- {
1502- "include": "#illegal-names"
1503- },
1504- {
1505- "match": "\\b([[:alpha:]_]\\w*)\\s*(=)(?!=)",
1506- "captures": {
1507- "1": {
1508- "name": "variable.parameter.function-call.python"
1509- },
1510- "2": {
1511- "name": "keyword.operator.assignment.python"
1512- }
1513- }
1514- },
1515- {
1516- "name": "keyword.operator.assignment.python",
1517- "match": "=(?!=)"
1518- },
1519- {
1520- "include": "#expression"
1521- },
1522- {
1523- "match": "\\s*(\\))\\s*(\\()",
1524- "captures": {
1525- "1": {
1526- "name": "punctuation.definition.arguments.end.python"
1527- },
1528- "2": {
1529- "name": "punctuation.definition.arguments.begin.python"
1530- }
1531- }
1532- }
1533- ]
1534- },
1535- "builtin-callables": {
1536- "patterns": [
1537- {
1538- "include": "#illegal-names"
1539- },
1540- {
1541- "include": "#illegal-object-name"
1542- },
1543- {
1544- "include": "#builtin-exceptions"
1545- },
1546- {
1547- "include": "#builtin-functions"
1548- },
1549- {
1550- "include": "#builtin-types"
1551- }
1552- ]
1553- },
1554- "builtin-possible-callables": {
1555- "patterns": [
1556- {
1557- "include": "#builtin-callables"
1558- },
1559- {
1560- "include": "#magic-names"
1561- }
1562- ]
1563- },
1564- "builtin-exceptions": {
1565- "name": "support.type.exception.python",
1566- "match": "(?x) (?<!\\.) \\b(\n (\n Arithmetic | Assertion | Attribute | Buffer | BlockingIO\n | BrokenPipe | ChildProcess\n | (Connection (Aborted | Refused | Reset)?)\n | EOF | Environment | FileExists | FileNotFound\n | FloatingPoint | IO | Import | Indentation | Index | Interrupted\n | IsADirectory | NotADirectory | Permission | ProcessLookup\n | Timeout\n | Key | Lookup | Memory | Name | NotImplemented | OS | Overflow\n | Reference | Runtime | Recursion | Syntax | System\n | Tab | Type | UnboundLocal | Unicode(Encode|Decode|Translate)?\n | Value | Windows | ZeroDivision\n ) Error\n|\n ((Pending)?Deprecation | Runtime | Syntax | User | Future | Import\n | Unicode | Bytes | Resource\n )? Warning\n|\n SystemExit | Stop(Async)?Iteration\n | KeyboardInterrupt\n | GeneratorExit | (Base)?Exception\n)\\b\n"
1567- },
1568- "builtin-functions": {
1569- "patterns": [
1570- {
1571- "name": "support.function.builtin.python",
1572- "match": "(?x)\n (?<!\\.) \\b(\n __import__ | abs | all | any | ascii | bin | callable\n | chr | compile | copyright | credits | delattr | dir | divmod\n | enumerate | eval | exec | exit | filter | format | getattr\n | globals | hasattr | hash | help | hex | id | input\n | isinstance | issubclass | iter | len | license | locals | map\n | max | memoryview | min | next | oct | open | ord | pow | print\n | quit | range | reload | repr | reversed | round\n | setattr | sorted | sum | vars | zip\n )\\b\n"
1573- },
1574- {
1575- "name": "variable.legacy.builtin.python",
1576- "match": "(?x)\n (?<!\\.) \\b(\n file | reduce | intern | raw_input | unicode | cmp | basestring\n | execfile | long | xrange\n )\\b\n"
1577- }
1578- ]
1579- },
1580- "builtin-types": {
1581- "name": "support.type.python",
1582- "match": "(?x)\n (?<!\\.) \\b(\n bool | bytearray | bytes | classmethod | complex | dict\n | float | frozenset | int | list | object | property\n | set | slice | staticmethod | str | tuple | type\n\n (?# Although 'super' is not a type, it's related to types,\n and is special enough to be highlighted differently from\n other built-ins)\n | super\n )\\b\n"
1583- },
1584- "magic-function-names": {
1585- "comment": "these methods have magic interpretation by python and are generally called\nindirectly through syntactic constructs\n",
1586- "match": "(?x)\n \\b(\n __(?:\n abs | add | aenter | aexit | aiter | and | anext | await\n | bool | call | ceil | cmp | coerce | complex | contains\n | copy | deepcopy | del | delattr | delete | delitem\n | delslice | dir | div | divmod | enter | eq | exit | float\n | floor | floordiv | format | ge | get | getattr\n | getattribute | getinitargs | getitem | getnewargs\n | getslice | getstate | gt | hash | hex | iadd | iand | idiv\n | ifloordiv | ilshift | imod | imul | index | init\n | instancecheck | int | invert | ior | ipow | irshift | isub\n | iter | itruediv | ixor | le | len | long | lshift | lt\n | missing | mod | mul | ne | neg | new | next | nonzero | oct | or\n | pos | pow | radd | rand | rdiv | rdivmod | reduce\n | reduce_ex | repr | reversed | rfloordiv | rlshift | rmod\n | rmul | ror | round | rpow | rrshift | rshift | rsub\n | rtruediv | rxor | set | setattr | setitem | setslice\n | setstate | sizeof | str | sub | subclasscheck | truediv\n | trunc | unicode | xor\n )__\n )\\b\n",
1587- "captures": {
1588- "1": {
1589- "name": "support.function.magic.python"
1590- }
1591- }
1592- },
1593- "magic-variable-names": {
1594- "comment": "magic variables which a class/module may have.",
1595- "match": "(?x)\n \\b(\n __(?:\n all | bases | builtins | class | code | debug | defaults | dict\n | doc | file | func | kwdefaults | members\n | metaclass | methods | module | mro | name\n | qualname | self | signature | slots | subclasses\n | version | weakref | wrapped\n )__\n )\\b\n",
1596- "captures": {
1597- "1": {
1598- "name": "support.variable.magic.python"
1599- }
1600- }
1601- },
1602- "magic-names": {
1603- "patterns": [
1604- {
1605- "include": "#magic-function-names"
1606- },
1607- {
1608- "include": "#magic-variable-names"
1609- }
1610- ]
1611- },
1612- "illegal-names": {
1613- "name": "keyword.control.flow.python",
1614- "match": "(?x)\n \\b(\n and | as | assert | async | await | break | class | continue | def\n | del | elif | else | except | exec | finally | for | from | global\n | if | import | in | is | (?<=\\.)lambda | lambda(?=\\s*[\\.=])\n | nonlocal | not | or | pass | raise | return | try | while | with\n | yield\n )\\b\n"
1615- },
1616- "special-variables": {
1617- "match": "(?x)\n \\b (?<!\\.) (?:\n (self) | (cls)\n )\\b\n",
1618- "captures": {
1619- "1": {
1620- "name": "variable.language.special.self.python"
1621- },
1622- "2": {
1623- "name": "variable.language.special.cls.python"
1624- }
1625- }
1626- },
1627- "ellipsis": {
1628- "name": "constant.other.ellipsis.python",
1629- "match": "\\.\\.\\."
1630- },
1631- "backticks": {
1632- "name": "invalid.deprecated.backtick.python",
1633- "begin": "\\`",
1634- "end": "(?:\\`|(?<!\\\\)(\\n))",
1635- "patterns": [
1636- {
1637- "include": "#expression"
1638- }
1639- ]
1640- },
1641- "illegal-operator": {
1642- "patterns": [
1643- {
1644- "name": "invalid.illegal.operator.python",
1645- "match": "&&|\\|\\||--|\\+\\+"
1646- },
1647- {
1648- "name": "invalid.illegal.operator.python",
1649- "match": "[?$]"
1650- },
1651- {
1652- "name": "invalid.illegal.operator.python",
1653- "comment": "We don't want `!` to flash when we're typing `!=`",
1654- "match": "!\\b"
1655- }
1656- ]
1657- },
1658- "illegal-object-name": {
1659- "comment": "It's illegal to name class or function \"True\"",
1660- "name": "keyword.illegal.name.python",
1661- "match": "\\b(True|False|None)\\b"
1662- },
1663- "illegal-anno": {
1664- "name": "invalid.illegal.annotation.python",
1665- "match": "->"
1666- },
1667- "regexp-base-expression": {
1668- "patterns": [
1669- {
1670- "name": "support.other.match.any.regexp",
1671- "match": "\\."
1672- },
1673- {
1674- "name": "support.other.match.begin.regexp",
1675- "match": "\\^"
1676- },
1677- {
1678- "name": "support.other.match.end.regexp",
1679- "match": "\\$"
1680- },
1681- {
1682- "name": "keyword.operator.quantifier.regexp",
1683- "match": "[+*?]\\??"
1684- },
1685- {
1686- "name": "keyword.operator.disjunction.regexp",
1687- "match": "\\|"
1688- },
1689- {
1690- "name": "keyword.operator.quantifier.regexp",
1691- "match": "(?x)\n \\{(\n \\d+ | \\d+,(\\d+)? | ,\\d+\n )\\}\n"
1692- },
1693- {
1694- "include": "#regexp-escape-sequence"
1695- }
1696- ]
1697- },
1698- "regexp-backreference-number": {
1699- "name": "meta.backreference.regexp",
1700- "match": "(\\\\[1-9]\\d?)",
1701- "captures": {
1702- "1": {
1703- "name": "entity.name.tag.backreference.regexp"
1704- }
1705- }
1706- },
1707- "regexp-backreference": {
1708- "name": "meta.backreference.named.regexp",
1709- "match": "(?x)\n (\\() (\\?P= \\w+(?:\\s+[[:alnum:]]+)?) (\\))\n",
1710- "captures": {
1711- "1": {
1712- "name": "punctuation.parenthesis.backreference.named.begin.regexp support.other.parenthesis.regexp"
1713- },
1714- "2": {
1715- "name": "entity.name.tag.named.backreference.regexp"
1716- },
1717- "3": {
1718- "name": "punctuation.parenthesis.backreference.named.end.regexp support.other.parenthesis.regexp"
1719- }
1720- }
1721- },
1722- "regexp-flags": {
1723- "name": "storage.modifier.flag.regexp",
1724- "match": "\\(\\?[aiLmsux]+\\)"
1725- },
1726- "regexp-escape-special": {
1727- "name": "support.other.escape.special.regexp",
1728- "match": "\\\\([AbBdDsSwWZ])"
1729- },
1730- "regexp-escape-character": {
1731- "name": "constant.character.escape.regexp",
1732- "match": "(?x)\n \\\\ (\n x[0-9A-Fa-f]{2}\n | 0[0-7]{1,2}\n | [0-7]{3}\n )\n"
1733- },
1734- "regexp-escape-unicode": {
1735- "name": "constant.character.unicode.regexp",
1736- "match": "(?x)\n \\\\ (\n u[0-9A-Fa-f]{4}\n | U[0-9A-Fa-f]{8}\n )\n"
1737- },
1738- "regexp-escape-catchall": {
1739- "name": "constant.character.escape.regexp",
1740- "match": "\\\\(.|\\n)"
1741- },
1742- "regexp-escape-sequence": {
1743- "patterns": [
1744- {
1745- "include": "#regexp-escape-special"
1746- },
1747- {
1748- "include": "#regexp-escape-character"
1749- },
1750- {
1751- "include": "#regexp-escape-unicode"
1752- },
1753- {
1754- "include": "#regexp-backreference-number"
1755- },
1756- {
1757- "include": "#regexp-escape-catchall"
1758- }
1759- ]
1760- },
1761- "regexp-charecter-set-escapes": {
1762- "patterns": [
1763- {
1764- "name": "constant.character.escape.regexp",
1765- "match": "\\\\[abfnrtv\\\\]"
1766- },
1767- {
1768- "include": "#regexp-escape-special"
1769- },
1770- {
1771- "name": "constant.character.escape.regexp",
1772- "match": "\\\\([0-7]{1,3})"
1773- },
1774- {
1775- "include": "#regexp-escape-character"
1776- },
1777- {
1778- "include": "#regexp-escape-unicode"
1779- },
1780- {
1781- "include": "#regexp-escape-catchall"
1782- }
1783- ]
1784- },
1785- "comments-base": {
1786- "name": "comment.line.number-sign.python",
1787- "begin": "(\\#)",
1788- "beginCaptures": {
1789- "1": {
1790- "name": "punctuation.definition.comment.python"
1791- }
1792- },
1793- "end": "($)",
1794- "patterns": [
1795- {
1796- "include": "#codetags"
1797- }
1798- ]
1799- },
1800- "comments-string-single-three": {
1801- "name": "comment.line.number-sign.python",
1802- "begin": "(\\#)",
1803- "beginCaptures": {
1804- "1": {
1805- "name": "punctuation.definition.comment.python"
1806- }
1807- },
1808- "end": "($|(?='''))",
1809- "patterns": [
1810- {
1811- "include": "#codetags"
1812- }
1813- ]
1814- },
1815- "comments-string-double-three": {
1816- "name": "comment.line.number-sign.python",
1817- "begin": "(\\#)",
1818- "beginCaptures": {
1819- "1": {
1820- "name": "punctuation.definition.comment.python"
1821- }
1822- },
1823- "end": "($|(?=\"\"\"))",
1824- "patterns": [
1825- {
1826- "include": "#codetags"
1827- }
1828- ]
1829- },
1830- "single-one-regexp-expression": {
1831- "patterns": [
1832- {
1833- "include": "#regexp-base-expression"
1834- },
1835- {
1836- "include": "#single-one-regexp-character-set"
1837- },
1838- {
1839- "include": "#single-one-regexp-comments"
1840- },
1841- {
1842- "include": "#regexp-flags"
1843- },
1844- {
1845- "include": "#single-one-regexp-named-group"
1846- },
1847- {
1848- "include": "#regexp-backreference"
1849- },
1850- {
1851- "include": "#single-one-regexp-lookahead"
1852- },
1853- {
1854- "include": "#single-one-regexp-lookahead-negative"
1855- },
1856- {
1857- "include": "#single-one-regexp-lookbehind"
1858- },
1859- {
1860- "include": "#single-one-regexp-lookbehind-negative"
1861- },
1862- {
1863- "include": "#single-one-regexp-conditional"
1864- },
1865- {
1866- "include": "#single-one-regexp-parentheses-non-capturing"
1867- },
1868- {
1869- "include": "#single-one-regexp-parentheses"
1870- }
1871- ]
1872- },
1873- "single-one-regexp-character-set": {
1874- "patterns": [
1875- {
1876- "match": "(?x)\n \\[ \\^? \\] (?! .*?\\])\n"
1877- },
1878- {
1879- "name": "meta.character.set.regexp",
1880- "begin": "(\\[)(\\^)?(\\])?",
1881- "end": "(\\]|(?=\\'))|((?=(?<!\\\\)\\n))",
1882- "beginCaptures": {
1883- "1": {
1884- "name": "constant.other.set.regexp punctuation.character.set.begin.regexp"
1885- },
1886- "2": {
1887- "name": "keyword.operator.negation.regexp"
1888- },
1889- "3": {
1890- "name": "constant.character.set.regexp"
1891- }
1892- },
1893- "endCaptures": {
1894- "1": {
1895- "name": "constant.other.set.regexp punctuation.character.set.end.regexp"
1896- },
1897- "2": {
1898- "name": "invalid.illegal.newline.python"
1899- }
1900- },
1901- "patterns": [
1902- {
1903- "include": "#regexp-charecter-set-escapes"
1904- },
1905- {
1906- "name": "constant.character.set.regexp",
1907- "match": "[^\\n]"
1908- }
1909- ]
1910- }
1911- ]
1912- },
1913- "single-one-regexp-named-group": {
1914- "name": "meta.named.regexp",
1915- "begin": "(?x)\n (\\() (\\?P <\\w+(?:\\s+[[:alnum:]]+)?>)\n",
1916- "end": "(\\)|(?=\\'))|((?=(?<!\\\\)\\n))",
1917- "beginCaptures": {
1918- "1": {
1919- "name": "punctuation.parenthesis.named.begin.regexp support.other.parenthesis.regexp"
1920- },
1921- "2": {
1922- "name": "entity.name.tag.named.group.regexp"
1923- }
1924- },
1925- "endCaptures": {
1926- "1": {
1927- "name": "punctuation.parenthesis.named.end.regexp support.other.parenthesis.regexp"
1928- },
1929- "2": {
1930- "name": "invalid.illegal.newline.python"
1931- }
1932- },
1933- "patterns": [
1934- {
1935- "include": "#single-one-regexp-expression"
1936- }
1937- ]
1938- },
1939- "single-one-regexp-comments": {
1940- "name": "comment.regexp",
1941- "begin": "\\(\\?#",
1942- "end": "(\\)|(?=\\'))|((?=(?<!\\\\)\\n))",
1943- "beginCaptures": {
1944- "0": {
1945- "name": "punctuation.comment.begin.regexp"
1946- }
1947- },
1948- "endCaptures": {
1949- "1": {
1950- "name": "punctuation.comment.end.regexp"
1951- },
1952- "2": {
1953- "name": "invalid.illegal.newline.python"
1954- }
1955- },
1956- "patterns": [
1957- {
1958- "include": "#codetags"
1959- }
1960- ]
1961- },
1962- "single-one-regexp-lookahead": {
1963- "begin": "(\\()\\?=",
1964- "end": "(\\)|(?=\\'))|((?=(?<!\\\\)\\n))",
1965- "beginCaptures": {
1966- "0": {
1967- "name": "keyword.operator.lookahead.regexp"
1968- },
1969- "1": {
1970- "name": "punctuation.parenthesis.lookahead.begin.regexp"
1971- }
1972- },
1973- "endCaptures": {
1974- "1": {
1975- "name": "punctuation.parenthesis.lookahead.end.regexp keyword.operator.lookahead.regexp"
1976- },
1977- "2": {
1978- "name": "invalid.illegal.newline.python"
1979- }
1980- },
1981- "patterns": [
1982- {
1983- "include": "#single-one-regexp-expression"
1984- }
1985- ]
1986- },
1987- "single-one-regexp-lookahead-negative": {
1988- "begin": "(\\()\\?!",
1989- "end": "(\\)|(?=\\'))|((?=(?<!\\\\)\\n))",
1990- "beginCaptures": {
1991- "0": {
1992- "name": "keyword.operator.lookahead.negative.regexp"
1993- },
1994- "1": {
1995- "name": "punctuation.parenthesis.lookahead.begin.regexp"
1996- }
1997- },
1998- "endCaptures": {
1999- "1": {
2000- "name": "punctuation.parenthesis.lookahead.end.regexp keyword.operator.lookahead.negative.regexp"
2001- },
2002- "2": {
2003- "name": "invalid.illegal.newline.python"
2004- }
2005- },
2006- "patterns": [
2007- {
2008- "include": "#single-one-regexp-expression"
2009- }
2010- ]
2011- },
2012- "single-one-regexp-lookbehind": {
2013- "begin": "(\\()\\?<=",
2014- "end": "(\\)|(?=\\'))|((?=(?<!\\\\)\\n))",
2015- "beginCaptures": {
2016- "0": {
2017- "name": "keyword.operator.lookbehind.regexp"
2018- },
2019- "1": {
2020- "name": "punctuation.parenthesis.lookbehind.begin.regexp"
2021- }
2022- },
2023- "endCaptures": {
2024- "1": {
2025- "name": "punctuation.parenthesis.lookbehind.end.regexp keyword.operator.lookbehind.regexp"
2026- },
2027- "2": {
2028- "name": "invalid.illegal.newline.python"
2029- }
2030- },
2031- "patterns": [
2032- {
2033- "include": "#single-one-regexp-expression"
2034- }
2035- ]
2036- },
2037- "single-one-regexp-lookbehind-negative": {
2038- "begin": "(\\()\\?<!",
2039- "end": "(\\)|(?=\\'))|((?=(?<!\\\\)\\n))",
2040- "beginCaptures": {
2041- "0": {
2042- "name": "keyword.operator.lookbehind.negative.regexp"
2043- },
2044- "1": {
2045- "name": "punctuation.parenthesis.lookbehind.begin.regexp"
2046- }
2047- },
2048- "endCaptures": {
2049- "1": {
2050- "name": "punctuation.parenthesis.lookbehind.end.regexp keyword.operator.lookbehind.negative.regexp"
2051- },
2052- "2": {
2053- "name": "invalid.illegal.newline.python"
2054- }
2055- },
2056- "patterns": [
2057- {
2058- "include": "#single-one-regexp-expression"
2059- }
2060- ]
2061- },
2062- "single-one-regexp-conditional": {
2063- "begin": "(\\()\\?\\((\\w+(?:\\s+[[:alnum:]]+)?|\\d+)\\)",
2064- "end": "(\\)|(?=\\'))|((?=(?<!\\\\)\\n))",
2065- "beginCaptures": {
2066- "0": {
2067- "name": "keyword.operator.conditional.regexp"
2068- },
2069- "1": {
2070- "name": "punctuation.parenthesis.conditional.begin.regexp"
2071- }
2072- },
2073- "endCaptures": {
2074- "1": {
2075- "name": "punctuation.parenthesis.conditional.end.regexp keyword.operator.conditional.negative.regexp"
2076- },
2077- "2": {
2078- "name": "invalid.illegal.newline.python"
2079- }
2080- },
2081- "patterns": [
2082- {
2083- "include": "#single-one-regexp-expression"
2084- }
2085- ]
2086- },
2087- "single-one-regexp-parentheses-non-capturing": {
2088- "begin": "\\(\\?:",
2089- "end": "(\\)|(?=\\'))|((?=(?<!\\\\)\\n))",
2090- "beginCaptures": {
2091- "0": {
2092- "name": "punctuation.parenthesis.non-capturing.begin.regexp support.other.parenthesis.regexp"
2093- }
2094- },
2095- "endCaptures": {
2096- "1": {
2097- "name": "punctuation.parenthesis.non-capturing.end.regexp support.other.parenthesis.regexp"
2098- },
2099- "2": {
2100- "name": "invalid.illegal.newline.python"
2101- }
2102- },
2103- "patterns": [
2104- {
2105- "include": "#single-one-regexp-expression"
2106- }
2107- ]
2108- },
2109- "single-one-regexp-parentheses": {
2110- "begin": "\\(",
2111- "end": "(\\)|(?=\\'))|((?=(?<!\\\\)\\n))",
2112- "beginCaptures": {
2113- "0": {
2114- "name": "punctuation.parenthesis.begin.regexp support.other.parenthesis.regexp"
2115- }
2116- },
2117- "endCaptures": {
2118- "1": {
2119- "name": "punctuation.parenthesis.end.regexp support.other.parenthesis.regexp"
2120- },
2121- "2": {
2122- "name": "invalid.illegal.newline.python"
2123- }
2124- },
2125- "patterns": [
2126- {
2127- "include": "#single-one-regexp-expression"
2128- }
2129- ]
2130- },
2131- "single-three-regexp-expression": {
2132- "patterns": [
2133- {
2134- "include": "#regexp-base-expression"
2135- },
2136- {
2137- "include": "#single-three-regexp-character-set"
2138- },
2139- {
2140- "include": "#single-three-regexp-comments"
2141- },
2142- {
2143- "include": "#regexp-flags"
2144- },
2145- {
2146- "include": "#single-three-regexp-named-group"
2147- },
2148- {
2149- "include": "#regexp-backreference"
2150- },
2151- {
2152- "include": "#single-three-regexp-lookahead"
2153- },
2154- {
2155- "include": "#single-three-regexp-lookahead-negative"
2156- },
2157- {
2158- "include": "#single-three-regexp-lookbehind"
2159- },
2160- {
2161- "include": "#single-three-regexp-lookbehind-negative"
2162- },
2163- {
2164- "include": "#single-three-regexp-conditional"
2165- },
2166- {
2167- "include": "#single-three-regexp-parentheses-non-capturing"
2168- },
2169- {
2170- "include": "#single-three-regexp-parentheses"
2171- },
2172- {
2173- "include": "#comments-string-single-three"
2174- }
2175- ]
2176- },
2177- "single-three-regexp-character-set": {
2178- "patterns": [
2179- {
2180- "match": "(?x)\n \\[ \\^? \\] (?! .*?\\])\n"
2181- },
2182- {
2183- "name": "meta.character.set.regexp",
2184- "begin": "(\\[)(\\^)?(\\])?",
2185- "end": "(\\]|(?=\\'\\'\\'))",
2186- "beginCaptures": {
2187- "1": {
2188- "name": "constant.other.set.regexp punctuation.character.set.begin.regexp"
2189- },
2190- "2": {
2191- "name": "keyword.operator.negation.regexp"
2192- },
2193- "3": {
2194- "name": "constant.character.set.regexp"
2195- }
2196- },
2197- "endCaptures": {
2198- "1": {
2199- "name": "constant.other.set.regexp punctuation.character.set.end.regexp"
2200- },
2201- "2": {
2202- "name": "invalid.illegal.newline.python"
2203- }
2204- },
2205- "patterns": [
2206- {
2207- "include": "#regexp-charecter-set-escapes"
2208- },
2209- {
2210- "name": "constant.character.set.regexp",
2211- "match": "[^\\n]"
2212- }
2213- ]
2214- }
2215- ]
2216- },
2217- "single-three-regexp-named-group": {
2218- "name": "meta.named.regexp",
2219- "begin": "(?x)\n (\\() (\\?P <\\w+(?:\\s+[[:alnum:]]+)?>)\n",
2220- "end": "(\\)|(?=\\'\\'\\'))",
2221- "beginCaptures": {
2222- "1": {
2223- "name": "punctuation.parenthesis.named.begin.regexp support.other.parenthesis.regexp"
2224- },
2225- "2": {
2226- "name": "entity.name.tag.named.group.regexp"
2227- }
2228- },
2229- "endCaptures": {
2230- "1": {
2231- "name": "punctuation.parenthesis.named.end.regexp support.other.parenthesis.regexp"
2232- },
2233- "2": {
2234- "name": "invalid.illegal.newline.python"
2235- }
2236- },
2237- "patterns": [
2238- {
2239- "include": "#single-three-regexp-expression"
2240- },
2241- {
2242- "include": "#comments-string-single-three"
2243- }
2244- ]
2245- },
2246- "single-three-regexp-comments": {
2247- "name": "comment.regexp",
2248- "begin": "\\(\\?#",
2249- "end": "(\\)|(?=\\'\\'\\'))",
2250- "beginCaptures": {
2251- "0": {
2252- "name": "punctuation.comment.begin.regexp"
2253- }
2254- },
2255- "endCaptures": {
2256- "1": {
2257- "name": "punctuation.comment.end.regexp"
2258- },
2259- "2": {
2260- "name": "invalid.illegal.newline.python"
2261- }
2262- },
2263- "patterns": [
2264- {
2265- "include": "#codetags"
2266- }
2267- ]
2268- },
2269- "single-three-regexp-lookahead": {
2270- "begin": "(\\()\\?=",
2271- "end": "(\\)|(?=\\'\\'\\'))",
2272- "beginCaptures": {
2273- "0": {
2274- "name": "keyword.operator.lookahead.regexp"
2275- },
2276- "1": {
2277- "name": "punctuation.parenthesis.lookahead.begin.regexp"
2278- }
2279- },
2280- "endCaptures": {
2281- "1": {
2282- "name": "punctuation.parenthesis.lookahead.end.regexp keyword.operator.lookahead.regexp"
2283- },
2284- "2": {
2285- "name": "invalid.illegal.newline.python"
2286- }
2287- },
2288- "patterns": [
2289- {
2290- "include": "#single-three-regexp-expression"
2291- },
2292- {
2293- "include": "#comments-string-single-three"
2294- }
2295- ]
2296- },
2297- "single-three-regexp-lookahead-negative": {
2298- "begin": "(\\()\\?!",
2299- "end": "(\\)|(?=\\'\\'\\'))",
2300- "beginCaptures": {
2301- "0": {
2302- "name": "keyword.operator.lookahead.negative.regexp"
2303- },
2304- "1": {
2305- "name": "punctuation.parenthesis.lookahead.begin.regexp"
2306- }
2307- },
2308- "endCaptures": {
2309- "1": {
2310- "name": "punctuation.parenthesis.lookahead.end.regexp keyword.operator.lookahead.negative.regexp"
2311- },
2312- "2": {
2313- "name": "invalid.illegal.newline.python"
2314- }
2315- },
2316- "patterns": [
2317- {
2318- "include": "#single-three-regexp-expression"
2319- },
2320- {
2321- "include": "#comments-string-single-three"
2322- }
2323- ]
2324- },
2325- "single-three-regexp-lookbehind": {
2326- "begin": "(\\()\\?<=",
2327- "end": "(\\)|(?=\\'\\'\\'))",
2328- "beginCaptures": {
2329- "0": {
2330- "name": "keyword.operator.lookbehind.regexp"
2331- },
2332- "1": {
2333- "name": "punctuation.parenthesis.lookbehind.begin.regexp"
2334- }
2335- },
2336- "endCaptures": {
2337- "1": {
2338- "name": "punctuation.parenthesis.lookbehind.end.regexp keyword.operator.lookbehind.regexp"
2339- },
2340- "2": {
2341- "name": "invalid.illegal.newline.python"
2342- }
2343- },
2344- "patterns": [
2345- {
2346- "include": "#single-three-regexp-expression"
2347- },
2348- {
2349- "include": "#comments-string-single-three"
2350- }
2351- ]
2352- },
2353- "single-three-regexp-lookbehind-negative": {
2354- "begin": "(\\()\\?<!",
2355- "end": "(\\)|(?=\\'\\'\\'))",
2356- "beginCaptures": {
2357- "0": {
2358- "name": "keyword.operator.lookbehind.negative.regexp"
2359- },
2360- "1": {
2361- "name": "punctuation.parenthesis.lookbehind.begin.regexp"
2362- }
2363- },
2364- "endCaptures": {
2365- "1": {
2366- "name": "punctuation.parenthesis.lookbehind.end.regexp keyword.operator.lookbehind.negative.regexp"
2367- },
2368- "2": {
2369- "name": "invalid.illegal.newline.python"
2370- }
2371- },
2372- "patterns": [
2373- {
2374- "include": "#single-three-regexp-expression"
2375- },
2376- {
2377- "include": "#comments-string-single-three"
2378- }
2379- ]
2380- },
2381- "single-three-regexp-conditional": {
2382- "begin": "(\\()\\?\\((\\w+(?:\\s+[[:alnum:]]+)?|\\d+)\\)",
2383- "end": "(\\)|(?=\\'\\'\\'))",
2384- "beginCaptures": {
2385- "0": {
2386- "name": "keyword.operator.conditional.regexp"
2387- },
2388- "1": {
2389- "name": "punctuation.parenthesis.conditional.begin.regexp"
2390- }
2391- },
2392- "endCaptures": {
2393- "1": {
2394- "name": "punctuation.parenthesis.conditional.end.regexp keyword.operator.conditional.negative.regexp"
2395- },
2396- "2": {
2397- "name": "invalid.illegal.newline.python"
2398- }
2399- },
2400- "patterns": [
2401- {
2402- "include": "#single-three-regexp-expression"
2403- },
2404- {
2405- "include": "#comments-string-single-three"
2406- }
2407- ]
2408- },
2409- "single-three-regexp-parentheses-non-capturing": {
2410- "begin": "\\(\\?:",
2411- "end": "(\\)|(?=\\'\\'\\'))",
2412- "beginCaptures": {
2413- "0": {
2414- "name": "punctuation.parenthesis.non-capturing.begin.regexp support.other.parenthesis.regexp"
2415- }
2416- },
2417- "endCaptures": {
2418- "1": {
2419- "name": "punctuation.parenthesis.non-capturing.end.regexp support.other.parenthesis.regexp"
2420- },
2421- "2": {
2422- "name": "invalid.illegal.newline.python"
2423- }
2424- },
2425- "patterns": [
2426- {
2427- "include": "#single-three-regexp-expression"
2428- },
2429- {
2430- "include": "#comments-string-single-three"
2431- }
2432- ]
2433- },
2434- "single-three-regexp-parentheses": {
2435- "begin": "\\(",
2436- "end": "(\\)|(?=\\'\\'\\'))",
2437- "beginCaptures": {
2438- "0": {
2439- "name": "punctuation.parenthesis.begin.regexp support.other.parenthesis.regexp"
2440- }
2441- },
2442- "endCaptures": {
2443- "1": {
2444- "name": "punctuation.parenthesis.end.regexp support.other.parenthesis.regexp"
2445- },
2446- "2": {
2447- "name": "invalid.illegal.newline.python"
2448- }
2449- },
2450- "patterns": [
2451- {
2452- "include": "#single-three-regexp-expression"
2453- },
2454- {
2455- "include": "#comments-string-single-three"
2456- }
2457- ]
2458- },
2459- "double-one-regexp-expression": {
2460- "patterns": [
2461- {
2462- "include": "#regexp-base-expression"
2463- },
2464- {
2465- "include": "#double-one-regexp-character-set"
2466- },
2467- {
2468- "include": "#double-one-regexp-comments"
2469- },
2470- {
2471- "include": "#regexp-flags"
2472- },
2473- {
2474- "include": "#double-one-regexp-named-group"
2475- },
2476- {
2477- "include": "#regexp-backreference"
2478- },
2479- {
2480- "include": "#double-one-regexp-lookahead"
2481- },
2482- {
2483- "include": "#double-one-regexp-lookahead-negative"
2484- },
2485- {
2486- "include": "#double-one-regexp-lookbehind"
2487- },
2488- {
2489- "include": "#double-one-regexp-lookbehind-negative"
2490- },
2491- {
2492- "include": "#double-one-regexp-conditional"
2493- },
2494- {
2495- "include": "#double-one-regexp-parentheses-non-capturing"
2496- },
2497- {
2498- "include": "#double-one-regexp-parentheses"
2499- }
2500- ]
2501- },
2502- "double-one-regexp-character-set": {
2503- "patterns": [
2504- {
2505- "match": "(?x)\n \\[ \\^? \\] (?! .*?\\])\n"
2506- },
2507- {
2508- "name": "meta.character.set.regexp",
2509- "begin": "(\\[)(\\^)?(\\])?",
2510- "end": "(\\]|(?=\"))|((?=(?<!\\\\)\\n))",
2511- "beginCaptures": {
2512- "1": {
2513- "name": "constant.other.set.regexp punctuation.character.set.begin.regexp"
2514- },
2515- "2": {
2516- "name": "keyword.operator.negation.regexp"
2517- },
2518- "3": {
2519- "name": "constant.character.set.regexp"
2520- }
2521- },
2522- "endCaptures": {
2523- "1": {
2524- "name": "constant.other.set.regexp punctuation.character.set.end.regexp"
2525- },
2526- "2": {
2527- "name": "invalid.illegal.newline.python"
2528- }
2529- },
2530- "patterns": [
2531- {
2532- "include": "#regexp-charecter-set-escapes"
2533- },
2534- {
2535- "name": "constant.character.set.regexp",
2536- "match": "[^\\n]"
2537- }
2538- ]
2539- }
2540- ]
2541- },
2542- "double-one-regexp-named-group": {
2543- "name": "meta.named.regexp",
2544- "begin": "(?x)\n (\\() (\\?P <\\w+(?:\\s+[[:alnum:]]+)?>)\n",
2545- "end": "(\\)|(?=\"))|((?=(?<!\\\\)\\n))",
2546- "beginCaptures": {
2547- "1": {
2548- "name": "punctuation.parenthesis.named.begin.regexp support.other.parenthesis.regexp"
2549- },
2550- "2": {
2551- "name": "entity.name.tag.named.group.regexp"
2552- }
2553- },
2554- "endCaptures": {
2555- "1": {
2556- "name": "punctuation.parenthesis.named.end.regexp support.other.parenthesis.regexp"
2557- },
2558- "2": {
2559- "name": "invalid.illegal.newline.python"
2560- }
2561- },
2562- "patterns": [
2563- {
2564- "include": "#double-one-regexp-expression"
2565- }
2566- ]
2567- },
2568- "double-one-regexp-comments": {
2569- "name": "comment.regexp",
2570- "begin": "\\(\\?#",
2571- "end": "(\\)|(?=\"))|((?=(?<!\\\\)\\n))",
2572- "beginCaptures": {
2573- "0": {
2574- "name": "punctuation.comment.begin.regexp"
2575- }
2576- },
2577- "endCaptures": {
2578- "1": {
2579- "name": "punctuation.comment.end.regexp"
2580- },
2581- "2": {
2582- "name": "invalid.illegal.newline.python"
2583- }
2584- },
2585- "patterns": [
2586- {
2587- "include": "#codetags"
2588- }
2589- ]
2590- },
2591- "double-one-regexp-lookahead": {
2592- "begin": "(\\()\\?=",
2593- "end": "(\\)|(?=\"))|((?=(?<!\\\\)\\n))",
2594- "beginCaptures": {
2595- "0": {
2596- "name": "keyword.operator.lookahead.regexp"
2597- },
2598- "1": {
2599- "name": "punctuation.parenthesis.lookahead.begin.regexp"
2600- }
2601- },
2602- "endCaptures": {
2603- "1": {
2604- "name": "punctuation.parenthesis.lookahead.end.regexp keyword.operator.lookahead.regexp"
2605- },
2606- "2": {
2607- "name": "invalid.illegal.newline.python"
2608- }
2609- },
2610- "patterns": [
2611- {
2612- "include": "#double-one-regexp-expression"
2613- }
2614- ]
2615- },
2616- "double-one-regexp-lookahead-negative": {
2617- "begin": "(\\()\\?!",
2618- "end": "(\\)|(?=\"))|((?=(?<!\\\\)\\n))",
2619- "beginCaptures": {
2620- "0": {
2621- "name": "keyword.operator.lookahead.negative.regexp"
2622- },
2623- "1": {
2624- "name": "punctuation.parenthesis.lookahead.begin.regexp"
2625- }
2626- },
2627- "endCaptures": {
2628- "1": {
2629- "name": "punctuation.parenthesis.lookahead.end.regexp keyword.operator.lookahead.negative.regexp"
2630- },
2631- "2": {
2632- "name": "invalid.illegal.newline.python"
2633- }
2634- },
2635- "patterns": [
2636- {
2637- "include": "#double-one-regexp-expression"
2638- }
2639- ]
2640- },
2641- "double-one-regexp-lookbehind": {
2642- "begin": "(\\()\\?<=",
2643- "end": "(\\)|(?=\"))|((?=(?<!\\\\)\\n))",
2644- "beginCaptures": {
2645- "0": {
2646- "name": "keyword.operator.lookbehind.regexp"
2647- },
2648- "1": {
2649- "name": "punctuation.parenthesis.lookbehind.begin.regexp"
2650- }
2651- },
2652- "endCaptures": {
2653- "1": {
2654- "name": "punctuation.parenthesis.lookbehind.end.regexp keyword.operator.lookbehind.regexp"
2655- },
2656- "2": {
2657- "name": "invalid.illegal.newline.python"
2658- }
2659- },
2660- "patterns": [
2661- {
2662- "include": "#double-one-regexp-expression"
2663- }
2664- ]
2665- },
2666- "double-one-regexp-lookbehind-negative": {
2667- "begin": "(\\()\\?<!",
2668- "end": "(\\)|(?=\"))|((?=(?<!\\\\)\\n))",
2669- "beginCaptures": {
2670- "0": {
2671- "name": "keyword.operator.lookbehind.negative.regexp"
2672- },
2673- "1": {
2674- "name": "punctuation.parenthesis.lookbehind.begin.regexp"
2675- }
2676- },
2677- "endCaptures": {
2678- "1": {
2679- "name": "punctuation.parenthesis.lookbehind.end.regexp keyword.operator.lookbehind.negative.regexp"
2680- },
2681- "2": {
2682- "name": "invalid.illegal.newline.python"
2683- }
2684- },
2685- "patterns": [
2686- {
2687- "include": "#double-one-regexp-expression"
2688- }
2689- ]
2690- },
2691- "double-one-regexp-conditional": {
2692- "begin": "(\\()\\?\\((\\w+(?:\\s+[[:alnum:]]+)?|\\d+)\\)",
2693- "end": "(\\)|(?=\"))|((?=(?<!\\\\)\\n))",
2694- "beginCaptures": {
2695- "0": {
2696- "name": "keyword.operator.conditional.regexp"
2697- },
2698- "1": {
2699- "name": "punctuation.parenthesis.conditional.begin.regexp"
2700- }
2701- },
2702- "endCaptures": {
2703- "1": {
2704- "name": "punctuation.parenthesis.conditional.end.regexp keyword.operator.conditional.negative.regexp"
2705- },
2706- "2": {
2707- "name": "invalid.illegal.newline.python"
2708- }
2709- },
2710- "patterns": [
2711- {
2712- "include": "#double-one-regexp-expression"
2713- }
2714- ]
2715- },
2716- "double-one-regexp-parentheses-non-capturing": {
2717- "begin": "\\(\\?:",
2718- "end": "(\\)|(?=\"))|((?=(?<!\\\\)\\n))",
2719- "beginCaptures": {
2720- "0": {
2721- "name": "punctuation.parenthesis.non-capturing.begin.regexp support.other.parenthesis.regexp"
2722- }
2723- },
2724- "endCaptures": {
2725- "1": {
2726- "name": "punctuation.parenthesis.non-capturing.end.regexp support.other.parenthesis.regexp"
2727- },
2728- "2": {
2729- "name": "invalid.illegal.newline.python"
2730- }
2731- },
2732- "patterns": [
2733- {
2734- "include": "#double-one-regexp-expression"
2735- }
2736- ]
2737- },
2738- "double-one-regexp-parentheses": {
2739- "begin": "\\(",
2740- "end": "(\\)|(?=\"))|((?=(?<!\\\\)\\n))",
2741- "beginCaptures": {
2742- "0": {
2743- "name": "punctuation.parenthesis.begin.regexp support.other.parenthesis.regexp"
2744- }
2745- },
2746- "endCaptures": {
2747- "1": {
2748- "name": "punctuation.parenthesis.end.regexp support.other.parenthesis.regexp"
2749- },
2750- "2": {
2751- "name": "invalid.illegal.newline.python"
2752- }
2753- },
2754- "patterns": [
2755- {
2756- "include": "#double-one-regexp-expression"
2757- }
2758- ]
2759- },
2760- "double-three-regexp-expression": {
2761- "patterns": [
2762- {
2763- "include": "#regexp-base-expression"
2764- },
2765- {
2766- "include": "#double-three-regexp-character-set"
2767- },
2768- {
2769- "include": "#double-three-regexp-comments"
2770- },
2771- {
2772- "include": "#regexp-flags"
2773- },
2774- {
2775- "include": "#double-three-regexp-named-group"
2776- },
2777- {
2778- "include": "#regexp-backreference"
2779- },
2780- {
2781- "include": "#double-three-regexp-lookahead"
2782- },
2783- {
2784- "include": "#double-three-regexp-lookahead-negative"
2785- },
2786- {
2787- "include": "#double-three-regexp-lookbehind"
2788- },
2789- {
2790- "include": "#double-three-regexp-lookbehind-negative"
2791- },
2792- {
2793- "include": "#double-three-regexp-conditional"
2794- },
2795- {
2796- "include": "#double-three-regexp-parentheses-non-capturing"
2797- },
2798- {
2799- "include": "#double-three-regexp-parentheses"
2800- },
2801- {
2802- "include": "#comments-string-double-three"
2803- }
2804- ]
2805- },
2806- "double-three-regexp-character-set": {
2807- "patterns": [
2808- {
2809- "match": "(?x)\n \\[ \\^? \\] (?! .*?\\])\n"
2810- },
2811- {
2812- "name": "meta.character.set.regexp",
2813- "begin": "(\\[)(\\^)?(\\])?",
2814- "end": "(\\]|(?=\"\"\"))",
2815- "beginCaptures": {
2816- "1": {
2817- "name": "constant.other.set.regexp punctuation.character.set.begin.regexp"
2818- },
2819- "2": {
2820- "name": "keyword.operator.negation.regexp"
2821- },
2822- "3": {
2823- "name": "constant.character.set.regexp"
2824- }
2825- },
2826- "endCaptures": {
2827- "1": {
2828- "name": "constant.other.set.regexp punctuation.character.set.end.regexp"
2829- },
2830- "2": {
2831- "name": "invalid.illegal.newline.python"
2832- }
2833- },
2834- "patterns": [
2835- {
2836- "include": "#regexp-charecter-set-escapes"
2837- },
2838- {
2839- "name": "constant.character.set.regexp",
2840- "match": "[^\\n]"
2841- }
2842- ]
2843- }
2844- ]
2845- },
2846- "double-three-regexp-named-group": {
2847- "name": "meta.named.regexp",
2848- "begin": "(?x)\n (\\() (\\?P <\\w+(?:\\s+[[:alnum:]]+)?>)\n",
2849- "end": "(\\)|(?=\"\"\"))",
2850- "beginCaptures": {
2851- "1": {
2852- "name": "punctuation.parenthesis.named.begin.regexp support.other.parenthesis.regexp"
2853- },
2854- "2": {
2855- "name": "entity.name.tag.named.group.regexp"
2856- }
2857- },
2858- "endCaptures": {
2859- "1": {
2860- "name": "punctuation.parenthesis.named.end.regexp support.other.parenthesis.regexp"
2861- },
2862- "2": {
2863- "name": "invalid.illegal.newline.python"
2864- }
2865- },
2866- "patterns": [
2867- {
2868- "include": "#double-three-regexp-expression"
2869- },
2870- {
2871- "include": "#comments-string-double-three"
2872- }
2873- ]
2874- },
2875- "double-three-regexp-comments": {
2876- "name": "comment.regexp",
2877- "begin": "\\(\\?#",
2878- "end": "(\\)|(?=\"\"\"))",
2879- "beginCaptures": {
2880- "0": {
2881- "name": "punctuation.comment.begin.regexp"
2882- }
2883- },
2884- "endCaptures": {
2885- "1": {
2886- "name": "punctuation.comment.end.regexp"
2887- },
2888- "2": {
2889- "name": "invalid.illegal.newline.python"
2890- }
2891- },
2892- "patterns": [
2893- {
2894- "include": "#codetags"
2895- }
2896- ]
2897- },
2898- "double-three-regexp-lookahead": {
2899- "begin": "(\\()\\?=",
2900- "end": "(\\)|(?=\"\"\"))",
2901- "beginCaptures": {
2902- "0": {
2903- "name": "keyword.operator.lookahead.regexp"
2904- },
2905- "1": {
2906- "name": "punctuation.parenthesis.lookahead.begin.regexp"
2907- }
2908- },
2909- "endCaptures": {
2910- "1": {
2911- "name": "punctuation.parenthesis.lookahead.end.regexp keyword.operator.lookahead.regexp"
2912- },
2913- "2": {
2914- "name": "invalid.illegal.newline.python"
2915- }
2916- },
2917- "patterns": [
2918- {
2919- "include": "#double-three-regexp-expression"
2920- },
2921- {
2922- "include": "#comments-string-double-three"
2923- }
2924- ]
2925- },
2926- "double-three-regexp-lookahead-negative": {
2927- "begin": "(\\()\\?!",
2928- "end": "(\\)|(?=\"\"\"))",
2929- "beginCaptures": {
2930- "0": {
2931- "name": "keyword.operator.lookahead.negative.regexp"
2932- },
2933- "1": {
2934- "name": "punctuation.parenthesis.lookahead.begin.regexp"
2935- }
2936- },
2937- "endCaptures": {
2938- "1": {
2939- "name": "punctuation.parenthesis.lookahead.end.regexp keyword.operator.lookahead.negative.regexp"
2940- },
2941- "2": {
2942- "name": "invalid.illegal.newline.python"
2943- }
2944- },
2945- "patterns": [
2946- {
2947- "include": "#double-three-regexp-expression"
2948- },
2949- {
2950- "include": "#comments-string-double-three"
2951- }
2952- ]
2953- },
2954- "double-three-regexp-lookbehind": {
2955- "begin": "(\\()\\?<=",
2956- "end": "(\\)|(?=\"\"\"))",
2957- "beginCaptures": {
2958- "0": {
2959- "name": "keyword.operator.lookbehind.regexp"
2960- },
2961- "1": {
2962- "name": "punctuation.parenthesis.lookbehind.begin.regexp"
2963- }
2964- },
2965- "endCaptures": {
2966- "1": {
2967- "name": "punctuation.parenthesis.lookbehind.end.regexp keyword.operator.lookbehind.regexp"
2968- },
2969- "2": {
2970- "name": "invalid.illegal.newline.python"
2971- }
2972- },
2973- "patterns": [
2974- {
2975- "include": "#double-three-regexp-expression"
2976- },
2977- {
2978- "include": "#comments-string-double-three"
2979- }
2980- ]
2981- },
2982- "double-three-regexp-lookbehind-negative": {
2983- "begin": "(\\()\\?<!",
2984- "end": "(\\)|(?=\"\"\"))",
2985- "beginCaptures": {
2986- "0": {
2987- "name": "keyword.operator.lookbehind.negative.regexp"
2988- },
2989- "1": {
2990- "name": "punctuation.parenthesis.lookbehind.begin.regexp"
2991- }
2992- },
2993- "endCaptures": {
2994- "1": {
2995- "name": "punctuation.parenthesis.lookbehind.end.regexp keyword.operator.lookbehind.negative.regexp"
2996- },
2997- "2": {
2998- "name": "invalid.illegal.newline.python"
2999- }
3000- },
3001- "patterns": [
3002- {
3003- "include": "#double-three-regexp-expression"
3004- },
3005- {
3006- "include": "#comments-string-double-three"
3007- }
3008- ]
3009- },
3010- "double-three-regexp-conditional": {
3011- "begin": "(\\()\\?\\((\\w+(?:\\s+[[:alnum:]]+)?|\\d+)\\)",
3012- "end": "(\\)|(?=\"\"\"))",
3013- "beginCaptures": {
3014- "0": {
3015- "name": "keyword.operator.conditional.regexp"
3016- },
3017- "1": {
3018- "name": "punctuation.parenthesis.conditional.begin.regexp"
3019- }
3020- },
3021- "endCaptures": {
3022- "1": {
3023- "name": "punctuation.parenthesis.conditional.end.regexp keyword.operator.conditional.negative.regexp"
3024- },
3025- "2": {
3026- "name": "invalid.illegal.newline.python"
3027- }
3028- },
3029- "patterns": [
3030- {
3031- "include": "#double-three-regexp-expression"
3032- },
3033- {
3034- "include": "#comments-string-double-three"
3035- }
3036- ]
3037- },
3038- "double-three-regexp-parentheses-non-capturing": {
3039- "begin": "\\(\\?:",
3040- "end": "(\\)|(?=\"\"\"))",
3041- "beginCaptures": {
3042- "0": {
3043- "name": "punctuation.parenthesis.non-capturing.begin.regexp support.other.parenthesis.regexp"
3044- }
3045- },
3046- "endCaptures": {
3047- "1": {
3048- "name": "punctuation.parenthesis.non-capturing.end.regexp support.other.parenthesis.regexp"
3049- },
3050- "2": {
3051- "name": "invalid.illegal.newline.python"
3052- }
3053- },
3054- "patterns": [
3055- {
3056- "include": "#double-three-regexp-expression"
3057- },
3058- {
3059- "include": "#comments-string-double-three"
3060- }
3061- ]
3062- },
3063- "double-three-regexp-parentheses": {
3064- "begin": "\\(",
3065- "end": "(\\)|(?=\"\"\"))",
3066- "beginCaptures": {
3067- "0": {
3068- "name": "punctuation.parenthesis.begin.regexp support.other.parenthesis.regexp"
3069- }
3070- },
3071- "endCaptures": {
3072- "1": {
3073- "name": "punctuation.parenthesis.end.regexp support.other.parenthesis.regexp"
3074- },
3075- "2": {
3076- "name": "invalid.illegal.newline.python"
3077- }
3078- },
3079- "patterns": [
3080- {
3081- "include": "#double-three-regexp-expression"
3082- },
3083- {
3084- "include": "#comments-string-double-three"
3085- }
3086- ]
3087- },
3088- "string-raw-quoted-single-line": {
3089- "name": "string.quoted.raw.single.python",
3090- "begin": "\\b(([uU]R)|(R))((['\"]))",
3091- "end": "(\\4)|((?<!\\\\)\\n)",
3092- "beginCaptures": {
3093- "2": {
3094- "name": "invalid.deprecated.prefix.python"
3095- },
3096- "3": {
3097- "name": "storage.type.string.python"
3098- },
3099- "4": {
3100- "name": "punctuation.definition.string.begin.python"
3101- }
3102- },
3103- "endCaptures": {
3104- "1": {
3105- "name": "punctuation.definition.string.end.python"
3106- },
3107- "2": {
3108- "name": "invalid.illegal.newline.python"
3109- }
3110- },
3111- "patterns": [
3112- {
3113- "include": "#string-single-bad-brace1-formatting-raw"
3114- },
3115- {
3116- "include": "#string-single-bad-brace2-formatting-raw"
3117- },
3118- {
3119- "include": "#string-raw-guts"
3120- }
3121- ]
3122- },
3123- "string-bin-quoted-single-line": {
3124- "name": "string.quoted.binary.single.python",
3125- "begin": "(\\b[bB])((['\"]))",
3126- "end": "(\\2)|((?<!\\\\)\\n)",
3127- "beginCaptures": {
3128- "1": {
3129- "name": "storage.type.string.python"
3130- },
3131- "2": {
3132- "name": "punctuation.definition.string.begin.python"
3133- }
3134- },
3135- "endCaptures": {
3136- "1": {
3137- "name": "punctuation.definition.string.end.python"
3138- },
3139- "2": {
3140- "name": "invalid.illegal.newline.python"
3141- }
3142- },
3143- "patterns": [
3144- {
3145- "include": "#string-entity"
3146- }
3147- ]
3148- },
3149- "string-raw-bin-quoted-single-line": {
3150- "name": "string.quoted.raw.binary.single.python",
3151- "begin": "(\\b(?:R[bB]|[bB]R))((['\"]))",
3152- "end": "(\\2)|((?<!\\\\)\\n)",
3153- "beginCaptures": {
3154- "1": {
3155- "name": "storage.type.string.python"
3156- },
3157- "2": {
3158- "name": "punctuation.definition.string.begin.python"
3159- }
3160- },
3161- "endCaptures": {
3162- "1": {
3163- "name": "punctuation.definition.string.end.python"
3164- },
3165- "2": {
3166- "name": "invalid.illegal.newline.python"
3167- }
3168- },
3169- "patterns": [
3170- {
3171- "include": "#string-raw-bin-guts"
3172- }
3173- ]
3174- },
3175- "string-quoted-single-line": {
3176- "name": "string.quoted.single.python",
3177- "begin": "(\\b[rR](?=[uU]))?([uU])?((['\"]))",
3178- "end": "(\\3)|((?<!\\\\)\\n)",
3179- "beginCaptures": {
3180- "1": {
3181- "name": "invalid.illegal.prefix.python"
3182- },
3183- "2": {
3184- "name": "storage.type.string.python"
3185- },
3186- "3": {
3187- "name": "punctuation.definition.string.begin.python"
3188- }
3189- },
3190- "endCaptures": {
3191- "1": {
3192- "name": "punctuation.definition.string.end.python"
3193- },
3194- "2": {
3195- "name": "invalid.illegal.newline.python"
3196- }
3197- },
3198- "patterns": [
3199- {
3200- "include": "#string-single-bad-brace1-formatting-unicode"
3201- },
3202- {
3203- "include": "#string-single-bad-brace2-formatting-unicode"
3204- },
3205- {
3206- "include": "#string-unicode-guts"
3207- }
3208- ]
3209- },
3210- "string-single-bad-brace1-formatting-unicode": {
3211- "comment": "template using {% ... %}",
3212- "begin": "(?x)\n (?= \\{%\n ( .*? (?!(['\"])|((?<!\\\\)\\n)) )\n %\\}\n )\n",
3213- "end": "(?=(['\"])|((?<!\\\\)\\n))",
3214- "patterns": [
3215- {
3216- "include": "#escape-sequence-unicode"
3217- },
3218- {
3219- "include": "#escape-sequence"
3220- },
3221- {
3222- "include": "#string-line-continuation"
3223- }
3224- ]
3225- },
3226- "string-single-bad-brace1-formatting-raw": {
3227- "comment": "template using {% ... %}",
3228- "begin": "(?x)\n (?= \\{%\n ( .*? (?!(['\"])|((?<!\\\\)\\n)) )\n %\\}\n )\n",
3229- "end": "(?=(['\"])|((?<!\\\\)\\n))",
3230- "patterns": [
3231- {
3232- "include": "#string-consume-escape"
3233- }
3234- ]
3235- },
3236- "string-single-bad-brace2-formatting-unicode": {
3237- "comment": "odd format or format-like syntax",
3238- "begin": "(?x)\n (?!\\{\\{)\n (?= \\{ (\n \\w*? (?!(['\"])|((?<!\\\\)\\n)) [^!:\\.\\[}\\w]\n )\n .*?(?!(['\"])|((?<!\\\\)\\n))\n \\}\n )\n",
3239- "end": "(?=(['\"])|((?<!\\\\)\\n))",
3240- "patterns": [
3241- {
3242- "include": "#escape-sequence-unicode"
3243- },
3244- {
3245- "include": "#string-entity"
3246- }
3247- ]
3248- },
3249- "string-single-bad-brace2-formatting-raw": {
3250- "comment": "odd format or format-like syntax",
3251- "begin": "(?x)\n (?!\\{\\{)\n (?= \\{ (\n \\w*? (?!(['\"])|((?<!\\\\)\\n)) [^!:\\.\\[}\\w]\n )\n .*?(?!(['\"])|((?<!\\\\)\\n))\n \\}\n )\n",
3252- "end": "(?=(['\"])|((?<!\\\\)\\n))",
3253- "patterns": [
3254- {
3255- "include": "#string-consume-escape"
3256- },
3257- {
3258- "include": "#string-formatting"
3259- }
3260- ]
3261- },
3262- "string-raw-quoted-multi-line": {
3263- "name": "string.quoted.raw.multi.python",
3264- "begin": "\\b(([uU]R)|(R))('''|\"\"\")",
3265- "end": "(\\4)",
3266- "beginCaptures": {
3267- "2": {
3268- "name": "invalid.deprecated.prefix.python"
3269- },
3270- "3": {
3271- "name": "storage.type.string.python"
3272- },
3273- "4": {
3274- "name": "punctuation.definition.string.begin.python"
3275- }
3276- },
3277- "endCaptures": {
3278- "1": {
3279- "name": "punctuation.definition.string.end.python"
3280- },
3281- "2": {
3282- "name": "invalid.illegal.newline.python"
3283- }
3284- },
3285- "patterns": [
3286- {
3287- "include": "#string-multi-bad-brace1-formatting-raw"
3288- },
3289- {
3290- "include": "#string-multi-bad-brace2-formatting-raw"
3291- },
3292- {
3293- "include": "#string-raw-guts"
3294- }
3295- ]
3296- },
3297- "string-bin-quoted-multi-line": {
3298- "name": "string.quoted.binary.multi.python",
3299- "begin": "(\\b[bB])('''|\"\"\")",
3300- "end": "(\\2)",
3301- "beginCaptures": {
3302- "1": {
3303- "name": "storage.type.string.python"
3304- },
3305- "2": {
3306- "name": "punctuation.definition.string.begin.python"
3307- }
3308- },
3309- "endCaptures": {
3310- "1": {
3311- "name": "punctuation.definition.string.end.python"
3312- },
3313- "2": {
3314- "name": "invalid.illegal.newline.python"
3315- }
3316- },
3317- "patterns": [
3318- {
3319- "include": "#string-entity"
3320- }
3321- ]
3322- },
3323- "string-raw-bin-quoted-multi-line": {
3324- "name": "string.quoted.raw.binary.multi.python",
3325- "begin": "(\\b(?:R[bB]|[bB]R))('''|\"\"\")",
3326- "end": "(\\2)",
3327- "beginCaptures": {
3328- "1": {
3329- "name": "storage.type.string.python"
3330- },
3331- "2": {
3332- "name": "punctuation.definition.string.begin.python"
3333- }
3334- },
3335- "endCaptures": {
3336- "1": {
3337- "name": "punctuation.definition.string.end.python"
3338- },
3339- "2": {
3340- "name": "invalid.illegal.newline.python"
3341- }
3342- },
3343- "patterns": [
3344- {
3345- "include": "#string-raw-bin-guts"
3346- }
3347- ]
3348- },
3349- "string-quoted-multi-line": {
3350- "name": "string.quoted.multi.python",
3351- "begin": "(\\b[rR](?=[uU]))?([uU])?('''|\"\"\")",
3352- "end": "(\\3)",
3353- "beginCaptures": {
3354- "1": {
3355- "name": "invalid.illegal.prefix.python"
3356- },
3357- "2": {
3358- "name": "storage.type.string.python"
3359- },
3360- "3": {
3361- "name": "punctuation.definition.string.begin.python"
3362- }
3363- },
3364- "endCaptures": {
3365- "1": {
3366- "name": "punctuation.definition.string.end.python"
3367- },
3368- "2": {
3369- "name": "invalid.illegal.newline.python"
3370- }
3371- },
3372- "patterns": [
3373- {
3374- "include": "#string-multi-bad-brace1-formatting-unicode"
3375- },
3376- {
3377- "include": "#string-multi-bad-brace2-formatting-unicode"
3378- },
3379- {
3380- "include": "#string-unicode-guts"
3381- }
3382- ]
3383- },
3384- "string-multi-bad-brace1-formatting-unicode": {
3385- "comment": "template using {% ... %}",
3386- "begin": "(?x)\n (?= \\{%\n ( .*? (?!'''|\"\"\") )\n %\\}\n )\n",
3387- "end": "(?='''|\"\"\")",
3388- "patterns": [
3389- {
3390- "include": "#escape-sequence-unicode"
3391- },
3392- {
3393- "include": "#escape-sequence"
3394- },
3395- {
3396- "include": "#string-line-continuation"
3397- }
3398- ]
3399- },
3400- "string-multi-bad-brace1-formatting-raw": {
3401- "comment": "template using {% ... %}",
3402- "begin": "(?x)\n (?= \\{%\n ( .*? (?!'''|\"\"\") )\n %\\}\n )\n",
3403- "end": "(?='''|\"\"\")",
3404- "patterns": [
3405- {
3406- "include": "#string-consume-escape"
3407- }
3408- ]
3409- },
3410- "string-multi-bad-brace2-formatting-unicode": {
3411- "comment": "odd format or format-like syntax",
3412- "begin": "(?x)\n (?!\\{\\{)\n (?= \\{ (\n \\w*? (?!'''|\"\"\") [^!:\\.\\[}\\w]\n )\n .*?(?!'''|\"\"\")\n \\}\n )\n",
3413- "end": "(?='''|\"\"\")",
3414- "patterns": [
3415- {
3416- "include": "#escape-sequence-unicode"
3417- },
3418- {
3419- "include": "#string-entity"
3420- }
3421- ]
3422- },
3423- "string-multi-bad-brace2-formatting-raw": {
3424- "comment": "odd format or format-like syntax",
3425- "begin": "(?x)\n (?!\\{\\{)\n (?= \\{ (\n \\w*? (?!'''|\"\"\") [^!:\\.\\[}\\w]\n )\n .*?(?!'''|\"\"\")\n \\}\n )\n",
3426- "end": "(?='''|\"\"\")",
3427- "patterns": [
3428- {
3429- "include": "#string-consume-escape"
3430- },
3431- {
3432- "include": "#string-formatting"
3433- }
3434- ]
3435- }
3436- },
3437- "version": "https://github.com/MagicStack/MagicPython/commit/37b660d0490d69ffd8cb4eabc0dd768e6cdaae7a"
3438-}
No newline at the end of the file
2+ "name": "MagicPython",
3+ "scopeName": "source.python",
4+ "fileTypes": [
5+ "py",
6+ "py3",
7+ "rpy",
8+ "pyw",
9+ "cpy",
10+ "SConstruct",
11+ "Sconstruct",
12+ "sconstruct",
13+ "SConscript",
14+ "gyp",
15+ "gypi"
16+ ],
17+ "first_line_match": "^#!/.*\\bpython[\\d\\.]*\\b",
18+ "firstLineMatch": "^#!/.*\\bpython[\\d\\.]*\\b",
19+ "uuid": "742deb57-6e38-4192-bed6-410746efd85d",
20+ "patterns": [
21+ {
22+ "include": "#statement"
23+ },
24+ {
25+ "include": "#expression"
26+ }
27+ ],
28+ "repository": {
29+ "statement": {
30+ "patterns": [
31+ {
32+ "include": "#import"
33+ },
34+ {
35+ "include": "#class-declaration"
36+ },
37+ {
38+ "include": "#function-declaration"
39+ },
40+ {
41+ "include": "#statement-keyword"
42+ },
43+ {
44+ "include": "#assignment-operator"
45+ },
46+ {
47+ "include": "#decorator"
48+ },
49+ {
50+ "include": "#docstring-statement"
51+ },
52+ {
53+ "include": "#semicolon"
54+ }
55+ ]
56+ },
57+ "semicolon": {
58+ "patterns": [
59+ {
60+ "name": "invalid.deprecated.semicolon.python",
61+ "match": "\\;$"
62+ }
63+ ]
64+ },
65+ "comments": {
66+ "patterns": [
67+ {
68+ "name": "comment.line.number-sign.python",
69+ "contentName": "meta.typehint.comment.python",
70+ "begin": "(?x)\n (?:\n \\# \\s* (type:)\n \\s*+ (?# we want `\\s*+` which is possessive quantifier since\n we do not actually want to backtrack when matching\n whitespace here)\n (?! $ | \\#)\n )\n",
71+ "end": "(?:$|(?=\\#))",
72+ "beginCaptures": {
73+ "0": {
74+ "name": "meta.typehint.comment.python"
75+ },
76+ "1": {
77+ "name": "comment.typehint.directive.notation.python"
78+ }
79+ },
80+ "patterns": [
81+ {
82+ "name": "comment.typehint.ignore.notation.python",
83+ "match": "(?x)\n \\G ignore\n (?= \\s* (?: $ | \\#))\n"
84+ },
85+ {
86+ "name": "comment.typehint.type.notation.python",
87+ "match": "(?x)\n (?<!\\.)\\b(\n bool | bytes | float | int | object | str\n | List | Dict | Iterable | Sequence | Set\n | FrozenSet | Callable | Union | Tuple\n | Any | None\n )\\b\n"
88+ },
89+ {
90+ "name": "comment.typehint.punctuation.notation.python",
91+ "match": "([\\[\\]\\(\\),\\.\\=\\*]|(->))"
92+ },
93+ {
94+ "name": "comment.typehint.variable.notation.python",
95+ "match": "([[:alpha:]_]\\w*)"
96+ }
97+ ]
98+ },
99+ {
100+ "include": "#comments-base"
101+ }
102+ ]
103+ },
104+ "docstring-statement": {
105+ "begin": "^(?=\\s*[rR]?(\\'\\'\\'|\\\"\\\"\\\"|\\'|\\\"))",
106+ "end": "(?<=\\'\\'\\'|\\\"\\\"\\\"|\\'|\\\")",
107+ "patterns": [
108+ {
109+ "include": "#docstring"
110+ }
111+ ]
112+ },
113+ "docstring": {
114+ "patterns": [
115+ {
116+ "name": "string.quoted.docstring.multi.python",
117+ "begin": "(\\'\\'\\'|\\\"\\\"\\\")",
118+ "end": "(\\1)",
119+ "beginCaptures": {
120+ "1": {
121+ "name": "punctuation.definition.string.begin.python"
122+ }
123+ },
124+ "endCaptures": {
125+ "1": {
126+ "name": "punctuation.definition.string.end.python"
127+ }
128+ },
129+ "patterns": [
130+ {
131+ "include": "#docstring-prompt"
132+ },
133+ {
134+ "include": "#codetags"
135+ },
136+ {
137+ "include": "#docstring-guts-unicode"
138+ }
139+ ]
140+ },
141+ {
142+ "name": "string.quoted.docstring.raw.multi.python",
143+ "begin": "([rR])(\\'\\'\\'|\\\"\\\"\\\")",
144+ "end": "(\\2)",
145+ "beginCaptures": {
146+ "1": {
147+ "name": "storage.type.string.python"
148+ },
149+ "2": {
150+ "name": "punctuation.definition.string.begin.python"
151+ }
152+ },
153+ "endCaptures": {
154+ "1": {
155+ "name": "punctuation.definition.string.end.python"
156+ }
157+ },
158+ "patterns": [
159+ {
160+ "include": "#string-consume-escape"
161+ },
162+ {
163+ "include": "#docstring-prompt"
164+ },
165+ {
166+ "include": "#codetags"
167+ }
168+ ]
169+ },
170+ {
171+ "name": "string.quoted.docstring.single.python",
172+ "begin": "(\\'|\\\")",
173+ "end": "(\\1)|((?<!\\\\)\\n)",
174+ "beginCaptures": {
175+ "1": {
176+ "name": "punctuation.definition.string.begin.python"
177+ }
178+ },
179+ "endCaptures": {
180+ "1": {
181+ "name": "punctuation.definition.string.end.python"
182+ },
183+ "2": {
184+ "name": "invalid.illegal.newline.python"
185+ }
186+ },
187+ "patterns": [
188+ {
189+ "include": "#codetags"
190+ },
191+ {
192+ "include": "#docstring-guts-unicode"
193+ }
194+ ]
195+ },
196+ {
197+ "name": "string.quoted.docstring.raw.single.python",
198+ "begin": "([rR])(\\'|\\\")",
199+ "end": "(\\2)|((?<!\\\\)\\n)",
200+ "beginCaptures": {
201+ "1": {
202+ "name": "storage.type.string.python"
203+ },
204+ "2": {
205+ "name": "punctuation.definition.string.begin.python"
206+ }
207+ },
208+ "endCaptures": {
209+ "1": {
210+ "name": "punctuation.definition.string.end.python"
211+ },
212+ "2": {
213+ "name": "invalid.illegal.newline.python"
214+ }
215+ },
216+ "patterns": [
217+ {
218+ "include": "#string-consume-escape"
219+ },
220+ {
221+ "include": "#codetags"
222+ }
223+ ]
224+ }
225+ ]
226+ },
227+ "docstring-guts-unicode": {
228+ "patterns": [
229+ {
230+ "include": "#escape-sequence-unicode"
231+ },
232+ {
233+ "include": "#escape-sequence"
234+ },
235+ {
236+ "include": "#string-line-continuation"
237+ }
238+ ]
239+ },
240+ "docstring-prompt": {
241+ "match": "(?x)\n (?:\n (?:^|\\G) \\s* (?# '\\G' is necessary for ST)\n ((?:>>>|\\.\\.\\.) \\s) (?=\\s*\\S)\n )\n",
242+ "captures": {
243+ "1": {
244+ "name": "keyword.control.flow.python"
245+ }
246+ }
247+ },
248+ "codetags": {
249+ "match": "(?:\\b(NOTE|XXX|HACK|FIXME|BUG|TODO)\\b)",
250+ "captures": {
251+ "1": {
252+ "name": "keyword.codetag.notation.python"
253+ }
254+ }
255+ },
256+ "statement-keyword": {
257+ "patterns": [
258+ {
259+ "name": "storage.type.function.python",
260+ "match": "\\b((async\\s+)?\\s*def)\\b"
261+ },
262+ {
263+ "name": "keyword.control.flow.python",
264+ "match": "(?x)\n \\b(?<!\\.)(\n as | async | continue | del | assert | break | finally | for\n | from | elif | else | if | except | pass | raise\n | return | try | while | with\n )\\b\n"
265+ },
266+ {
267+ "name": "storage.modifier.declaration.python",
268+ "match": "(?x)\n \\b(?<!\\.)(\n global | nonlocal\n )\\b\n"
269+ },
270+ {
271+ "name": "storage.type.class.python",
272+ "match": "\\b(?<!\\.)(class)\\b"
273+ }
274+ ]
275+ },
276+ "expression-base": {
277+ "comment": "All valid Python expressions",
278+ "patterns": [
279+ {
280+ "include": "#backticks"
281+ },
282+ {
283+ "include": "#illegal-anno"
284+ },
285+ {
286+ "include": "#comments"
287+ },
288+ {
289+ "include": "#literal"
290+ },
291+ {
292+ "include": "#regexp"
293+ },
294+ {
295+ "include": "#string"
296+ },
297+ {
298+ "include": "#lambda"
299+ },
300+ {
301+ "include": "#illegal-operator"
302+ },
303+ {
304+ "include": "#operator"
305+ },
306+ {
307+ "include": "#curly-braces"
308+ },
309+ {
310+ "include": "#item-access"
311+ },
312+ {
313+ "include": "#list"
314+ },
315+ {
316+ "include": "#round-braces"
317+ },
318+ {
319+ "include": "#function-call"
320+ },
321+ {
322+ "include": "#builtin-functions"
323+ },
324+ {
325+ "include": "#builtin-types"
326+ },
327+ {
328+ "include": "#builtin-exceptions"
329+ },
330+ {
331+ "include": "#magic-names"
332+ },
333+ {
334+ "include": "#special-names"
335+ },
336+ {
337+ "include": "#illegal-names"
338+ },
339+ {
340+ "include": "#special-variables"
341+ },
342+ {
343+ "include": "#line-continuation"
344+ },
345+ {
346+ "include": "#ellipsis"
347+ }
348+ ]
349+ },
350+ "expression": {
351+ "comment": "All valid Python expressions",
352+ "patterns": [
353+ {
354+ "include": "#expression-base"
355+ },
356+ {
357+ "include": "#member-access"
358+ },
359+ {
360+ "comment": "Tokenize identifiers to help linters",
361+ "match": "(?x) \\b ([[:alpha:]_]\\w*) \\b"
362+ }
363+ ]
364+ },
365+ "member-access": {
366+ "begin": "\\.\\s*(?!\\.)",
367+ "end": "(?x)\n # stop when you've just read non-whitespace followed by non-word\n # i.e. when finished reading an identifier or function call\n (?<=\\S)(?=\\W) |\n # stop when seeing the start of something that's not a word,\n # i.e. when seeing a non-identifier\n (^|(?<=\\s))(?=[^\\\\\\w\\s]) |\n $\n",
368+ "patterns": [
369+ {
370+ "include": "#function-call"
371+ },
372+ {
373+ "include": "#member-access-base"
374+ }
375+ ]
376+ },
377+ "member-access-base": {
378+ "patterns": [
379+ {
380+ "include": "#magic-names"
381+ },
382+ {
383+ "include": "#illegal-names"
384+ },
385+ {
386+ "include": "#illegal-object-name"
387+ },
388+ {
389+ "include": "#special-names"
390+ },
391+ {
392+ "include": "#line-continuation"
393+ },
394+ {
395+ "include": "#item-access"
396+ }
397+ ]
398+ },
399+ "special-names": {
400+ "name": "constant.other.caps.python",
401+ "match": "(?x)\n \\b\n (\n _* [[:upper:]]\n )\n [[:upper:]\\d]* (_\\w*)?\n \\b\n"
402+ },
403+ "curly-braces": {
404+ "begin": "\\{",
405+ "end": "\\}",
406+ "beginCaptures": {
407+ "0": {
408+ "name": "punctuation.definition.dict.begin.python"
409+ }
410+ },
411+ "endCaptures": {
412+ "0": {
413+ "name": "punctuation.definition.dict.end.python"
414+ }
415+ },
416+ "patterns": [
417+ {
418+ "include": "#expression"
419+ }
420+ ]
421+ },
422+ "list": {
423+ "begin": "\\[",
424+ "end": "\\]",
425+ "beginCaptures": {
426+ "0": {
427+ "name": "punctuation.definition.list.begin.python"
428+ }
429+ },
430+ "endCaptures": {
431+ "0": {
432+ "name": "punctuation.definition.list.end.python"
433+ }
434+ },
435+ "patterns": [
436+ {
437+ "include": "#expression"
438+ }
439+ ]
440+ },
441+ "round-braces": {
442+ "begin": "\\(",
443+ "end": "\\)",
444+ "beginCaptures": {
445+ "0": {
446+ "name": "punctuation.parenthesis.begin.python"
447+ }
448+ },
449+ "endCaptures": {
450+ "0": {
451+ "name": "punctuation.parenthesis.end.python"
452+ }
453+ },
454+ "patterns": [
455+ {
456+ "include": "#expression"
457+ }
458+ ]
459+ },
460+ "line-continuation": {
461+ "patterns": [
462+ {
463+ "match": "(\\\\)\\s*(\\S.*$\\n?)",
464+ "captures": {
465+ "1": {
466+ "name": "separator.continuation.line.python"
467+ },
468+ "2": {
469+ "name": "invalid.illegal.line.continuation.python"
470+ }
471+ }
472+ },
473+ {
474+ "begin": "(\\\\)\\s*$\\n?",
475+ "end": "(?x)\n (?=^\\s*$)\n |\n (?! (\\s* [rR]? (\\'\\'\\'|\\\"\\\"\\\"|\\'|\\\"))\n |\n (\\G $) (?# '\\G' is necessary for ST)\n )\n",
476+ "beginCaptures": {
477+ "1": {
478+ "name": "separator.continuation.line.python"
479+ }
480+ },
481+ "patterns": [
482+ {
483+ "include": "#regexp"
484+ },
485+ {
486+ "include": "#string"
487+ }
488+ ]
489+ }
490+ ]
491+ },
492+ "assignment-operator": {
493+ "name": "keyword.operator.assignment.python",
494+ "match": "(?x)\n <<= | >>= | //= | \\*\\*=\n | \\+= | -= | /= | @=\n | \\*= | %= | ~= | \\^= | &= | \\|=\n | =(?!=)\n"
495+ },
496+ "operator": {
497+ "match": "(?x)\n \\b(?<!\\.)\n (?:\n (and | or | not | in | is) (?# 1)\n |\n (for | if | else | await | (?:yield(?:\\s+from)?)) (?# 2)\n )\n (?!\\s*:)\\b\n\n | (<< | >> | & | \\| | \\^ | ~) (?# 3)\n\n | (\\*\\* | \\* | \\+ | - | % | // | / | @) (?# 4)\n\n | (!= | == | >= | <= | < | >) (?# 5)\n",
498+ "captures": {
499+ "1": {
500+ "name": "keyword.operator.logical.python"
501+ },
502+ "2": {
503+ "name": "keyword.control.flow.python"
504+ },
505+ "3": {
506+ "name": "keyword.operator.bitwise.python"
507+ },
508+ "4": {
509+ "name": "keyword.operator.arithmetic.python"
510+ },
511+ "5": {
512+ "name": "keyword.operator.comparison.python"
513+ }
514+ }
515+ },
516+ "literal": {
517+ "patterns": [
518+ {
519+ "name": "constant.language.python",
520+ "match": "\\b(True|False|None|NotImplemented|Ellipsis)\\b"
521+ },
522+ {
523+ "include": "#number"
524+ }
525+ ]
526+ },
527+ "number": {
528+ "name": "constant.numeric.python",
529+ "patterns": [
530+ {
531+ "include": "#number-float"
532+ },
533+ {
534+ "include": "#number-dec"
535+ },
536+ {
537+ "include": "#number-hex"
538+ },
539+ {
540+ "include": "#number-oct"
541+ },
542+ {
543+ "include": "#number-bin"
544+ },
545+ {
546+ "include": "#number-long"
547+ },
548+ {
549+ "name": "invalid.illegal.name.python",
550+ "match": "\\b[0-9]+\\w+"
551+ }
552+ ]
553+ },
554+ "number-float": {
555+ "name": "constant.numeric.float.python",
556+ "match": "(?x)\n (?<! \\w)(?:\n [0-9]*\\.[0-9]+ ([eE][+-]?[0-9]+)?\n | [0-9]+\\. ([eE][+-]?[0-9]+)?\n | [0-9]+ ([eE][+-]?[0-9]+)\n )([jJ])?\\b\n",
557+ "captures": {
558+ "4": {
559+ "name": "storage.type.imaginary.number.python"
560+ }
561+ }
562+ },
563+ "number-dec": {
564+ "name": "constant.numeric.dec.python",
565+ "match": "(?x)\n (?<![\\w\\.])(?:\n [1-9][0-9]*\n |\n 0+\n |\n [0-9]+ ([jJ])\n |\n 0 ([0-9]+)(?![eE\\.])\n )\\b\n",
566+ "captures": {
567+ "1": {
568+ "name": "storage.type.imaginary.number.python"
569+ },
570+ "2": {
571+ "name": "invalid.illegal.dec.python"
572+ },
573+ "3": {
574+ "name": "invalid.illegal.dec.python"
575+ }
576+ }
577+ },
578+ "number-hex": {
579+ "name": "constant.numeric.hex.python",
580+ "match": "(?x)\n (?<![\\w\\.])\n (0[xX]) [0-9a-fA-F]+\n \\b\n",
581+ "captures": {
582+ "1": {
583+ "name": "storage.type.number.python"
584+ }
585+ }
586+ },
587+ "number-oct": {
588+ "name": "constant.numeric.oct.python",
589+ "match": "(?x)\n (?<![\\w\\.])\n (0[oO]) [0-7]+\n \\b\n",
590+ "captures": {
591+ "1": {
592+ "name": "storage.type.number.python"
593+ }
594+ }
595+ },
596+ "number-bin": {
597+ "name": "constant.numeric.bin.python",
598+ "match": "(?x)\n (?<![\\w\\.])\n (0[bB]) [01]+\n \\b\n",
599+ "captures": {
600+ "1": {
601+ "name": "storage.type.number.python"
602+ }
603+ }
604+ },
605+ "number-long": {
606+ "name": "constant.numeric.bin.python",
607+ "comment": "this is to support python2 syntax for long ints",
608+ "match": "(?x)\n (?<![\\w\\.])\n ([1-9][0-9]* | 0) ([lL])\n \\b\n",
609+ "captures": {
610+ "2": {
611+ "name": "storage.type.number.python"
612+ }
613+ }
614+ },
615+ "regexp": {
616+ "patterns": [
617+ {
618+ "include": "#regexp-single-quoted-multi-line"
619+ },
620+ {
621+ "include": "#regexp-double-quoted-multi-line"
622+ },
623+ {
624+ "include": "#regexp-single-quoted-single-line"
625+ },
626+ {
627+ "include": "#regexp-double-quoted-single-line"
628+ }
629+ ]
630+ },
631+ "regexp-single-quoted-single-line": {
632+ "name": "string.regexp.quoted.single.python",
633+ "begin": "\\b(([uU]r)|([bB]r)|(r[bB]?))(\\')",
634+ "end": "(\\')|(?<!\\\\)(\\n)",
635+ "beginCaptures": {
636+ "2": {
637+ "name": "invalid.deprecated.prefix.python"
638+ },
639+ "3": {
640+ "name": "storage.type.string.python"
641+ },
642+ "4": {
643+ "name": "storage.type.string.python"
644+ },
645+ "5": {
646+ "name": "punctuation.definition.string.begin.python"
647+ }
648+ },
649+ "endCaptures": {
650+ "1": {
651+ "name": "punctuation.definition.string.end.python"
652+ },
653+ "2": {
654+ "name": "invalid.illegal.newline.python"
655+ }
656+ },
657+ "patterns": [
658+ {
659+ "include": "#single-one-regexp-expression"
660+ }
661+ ]
662+ },
663+ "regexp-double-quoted-single-line": {
664+ "name": "string.regexp.quoted.single.python",
665+ "begin": "\\b(([uU]r)|([bB]r)|(r[bB]?))(\\\")",
666+ "end": "(\\\")|(?<!\\\\)(\\n)",
667+ "beginCaptures": {
668+ "2": {
669+ "name": "invalid.deprecated.prefix.python"
670+ },
671+ "3": {
672+ "name": "storage.type.string.python"
673+ },
674+ "4": {
675+ "name": "storage.type.string.python"
676+ },
677+ "5": {
678+ "name": "punctuation.definition.string.begin.python"
679+ }
680+ },
681+ "endCaptures": {
682+ "1": {
683+ "name": "punctuation.definition.string.end.python"
684+ },
685+ "2": {
686+ "name": "invalid.illegal.newline.python"
687+ }
688+ },
689+ "patterns": [
690+ {
691+ "include": "#double-one-regexp-expression"
692+ }
693+ ]
694+ },
695+ "regexp-single-quoted-multi-line": {
696+ "name": "string.regexp.quoted.multi.python",
697+ "begin": "\\b(([uU]r)|([bB]r)|(r[bB]?))(\\'\\'\\')",
698+ "end": "\\'\\'\\'",
699+ "beginCaptures": {
700+ "2": {
701+ "name": "invalid.deprecated.prefix.python"
702+ },
703+ "3": {
704+ "name": "storage.type.string.python"
705+ },
706+ "4": {
707+ "name": "storage.type.string.python"
708+ },
709+ "5": {
710+ "name": "punctuation.definition.string.begin.python"
711+ }
712+ },
713+ "endCaptures": {
714+ "0": {
715+ "name": "punctuation.definition.string.end.python"
716+ }
717+ },
718+ "patterns": [
719+ {
720+ "include": "#single-three-regexp-expression"
721+ }
722+ ]
723+ },
724+ "regexp-double-quoted-multi-line": {
725+ "name": "string.regexp.quoted.multi.python",
726+ "begin": "\\b(([uU]r)|([bB]r)|(r[bB]?))(\\\"\\\"\\\")",
727+ "end": "\\\"\\\"\\\"",
728+ "beginCaptures": {
729+ "2": {
730+ "name": "invalid.deprecated.prefix.python"
731+ },
732+ "3": {
733+ "name": "storage.type.string.python"
734+ },
735+ "4": {
736+ "name": "storage.type.string.python"
737+ },
738+ "5": {
739+ "name": "punctuation.definition.string.begin.python"
740+ }
741+ },
742+ "endCaptures": {
743+ "0": {
744+ "name": "punctuation.definition.string.end.python"
745+ }
746+ },
747+ "patterns": [
748+ {
749+ "include": "#double-three-regexp-expression"
750+ }
751+ ]
752+ },
753+ "string": {
754+ "patterns": [
755+ {
756+ "include": "#string-quoted-multi-line"
757+ },
758+ {
759+ "include": "#string-quoted-single-line"
760+ },
761+ {
762+ "include": "#string-bin-quoted-multi-line"
763+ },
764+ {
765+ "include": "#string-bin-quoted-single-line"
766+ },
767+ {
768+ "include": "#string-raw-quoted-multi-line"
769+ },
770+ {
771+ "include": "#string-raw-quoted-single-line"
772+ },
773+ {
774+ "include": "#string-raw-bin-quoted-multi-line"
775+ },
776+ {
777+ "include": "#string-raw-bin-quoted-single-line"
778+ }
779+ ]
780+ },
781+ "string-unicode-guts": {
782+ "patterns": [
783+ {
784+ "include": "#escape-sequence-unicode"
785+ },
786+ {
787+ "include": "#string-entity"
788+ },
789+ {
790+ "include": "#string-brace-formatting"
791+ }
792+ ]
793+ },
794+ "string-consume-escape": {
795+ "match": "\\\\['\"\\n\\\\]"
796+ },
797+ "string-raw-guts": {
798+ "patterns": [
799+ {
800+ "include": "#string-consume-escape"
801+ },
802+ {
803+ "include": "#string-formatting"
804+ },
805+ {
806+ "include": "#string-brace-formatting"
807+ }
808+ ]
809+ },
810+ "string-raw-bin-guts": {
811+ "patterns": [
812+ {
813+ "include": "#string-consume-escape"
814+ },
815+ {
816+ "include": "#string-formatting"
817+ }
818+ ]
819+ },
820+ "string-entity": {
821+ "patterns": [
822+ {
823+ "include": "#escape-sequence"
824+ },
825+ {
826+ "include": "#string-line-continuation"
827+ },
828+ {
829+ "include": "#string-formatting"
830+ }
831+ ]
832+ },
833+ "escape-sequence-unicode": {
834+ "patterns": [
835+ {
836+ "name": "constant.character.escape.python",
837+ "match": "(?x)\n \\\\ (\n u[0-9A-Fa-f]{4}\n | U[0-9A-Fa-f]{8}\n | N\\{[\\w\\s]+?\\}\n )\n"
838+ }
839+ ]
840+ },
841+ "escape-sequence": {
842+ "name": "constant.character.escape.python",
843+ "match": "(?x)\n \\\\ (\n x[0-9A-Fa-f]{2}\n | [0-7]{1,3}\n | [\\\\\"'abfnrtv]\n )\n"
844+ },
845+ "string-line-continuation": {
846+ "name": "constant.language.python",
847+ "match": "\\\\$"
848+ },
849+ "string-formatting": {
850+ "name": "constant.character.format.placeholder.other.python",
851+ "match": "(?x)\n % (\\([\\w\\s]*\\))?\n [-+#0 ]*\n (\\d+|\\*)? (\\.(\\d+|\\*))?\n ([hlL])?\n [diouxXeEfFgGcrsa%]\n"
852+ },
853+ "string-brace-formatting": {
854+ "patterns": [
855+ {
856+ "name": "constant.character.format.placeholder.other.python",
857+ "match": "(?x)\n (?:\n {{ | }}\n | (?:\n {\n \\w*? (\\.[[:alpha:]_]\\w*? | \\[[^\\]'\"]+\\])*?\n (![rsa])?\n ( : \\w? [<>=^]? [-+ ]? \\#?\n \\d* ,? (\\.\\d+)? [bcdeEfFgGnosxX%]? )?\n })\n )\n",
858+ "captures": {
859+ "2": {
860+ "name": "storage.type.format.python"
861+ },
862+ "3": {
863+ "name": "support.other.format.python"
864+ }
865+ }
866+ },
867+ {
868+ "name": "constant.character.format.placeholder.other.python",
869+ "begin": "(?x)\n \\{\n \\w*? (\\.[[:alpha:]_]\\w*? | \\[[^\\]'\"]+\\])*?\n (![rsa])?\n (:)\n (?=[^'\"}\\n]*\\})\n",
870+ "end": "\\}",
871+ "beginCaptures": {
872+ "2": {
873+ "name": "storage.type.format.python"
874+ },
875+ "3": {
876+ "name": "support.other.format.python"
877+ }
878+ },
879+ "patterns": [
880+ {
881+ "match": "(?x) \\{ [^'\"}\\n]*? \\} (?=.*?\\})\n"
882+ }
883+ ]
884+ }
885+ ]
886+ },
887+ "import": {
888+ "comment": "Import statements\n",
889+ "patterns": [
890+ {
891+ "match": "(?x)\n \\s* \\b(from)\\b (\\s*\\.+\\s*) (import)?\n",
892+ "captures": {
893+ "1": {
894+ "name": "keyword.control.import.python"
895+ },
896+ "3": {
897+ "name": "keyword.control.import.python"
898+ }
899+ }
900+ },
901+ {
902+ "name": "keyword.control.import.python",
903+ "match": "\\b(?<!\\.)import\\b"
904+ }
905+ ]
906+ },
907+ "class-declaration": {
908+ "patterns": [
909+ {
910+ "name": "meta.class.python",
911+ "begin": "(?x)\n \\s*(class)\\s+\n (?=\n [[:alpha:]_]\\w* \\s* (:|\\()\n )\n",
912+ "end": "(:)",
913+ "beginCaptures": {
914+ "1": {
915+ "name": "storage.type.class.python"
916+ }
917+ },
918+ "endCaptures": {
919+ "1": {
920+ "name": "punctuation.section.class.begin.python"
921+ }
922+ },
923+ "patterns": [
924+ {
925+ "include": "#class-name"
926+ },
927+ {
928+ "include": "#class-inheritance"
929+ }
930+ ]
931+ }
932+ ]
933+ },
934+ "class-name": {
935+ "patterns": [
936+ {
937+ "include": "#illegal-object-name"
938+ },
939+ {
940+ "include": "#builtin-possible-callables"
941+ },
942+ {
943+ "name": "entity.name.type.class.python",
944+ "match": "(?x)\n \\b ([[:alpha:]_]\\w*) \\b\n"
945+ }
946+ ]
947+ },
948+ "class-inheritance": {
949+ "name": "meta.class.inheritance.python",
950+ "begin": "(\\()",
951+ "end": "(\\))",
952+ "beginCaptures": {
953+ "1": {
954+ "name": "punctuation.definition.inheritance.begin.python"
955+ }
956+ },
957+ "endCaptures": {
958+ "1": {
959+ "name": "punctuation.definition.inheritance.end.python"
960+ }
961+ },
962+ "patterns": [
963+ {
964+ "name": "keyword.operator.unpacking.arguments.python",
965+ "match": "(\\*\\*|\\*)"
966+ },
967+ {
968+ "name": "punctuation.separator.inheritance.python",
969+ "match": ","
970+ },
971+ {
972+ "name": "keyword.operator.assignment.python",
973+ "match": "=(?!=)"
974+ },
975+ {
976+ "include": "#expression-class"
977+ },
978+ {
979+ "name": "support.type.metaclass.python",
980+ "match": "\\bmetaclass\\b"
981+ },
982+ {
983+ "include": "#inheritance-identifier"
984+ }
985+ ]
986+ },
987+ "inheritance-identifier": {
988+ "match": "(?x)\n \\b ([[:alpha:]_]\\w*) \\b\n",
989+ "captures": {
990+ "1": {
991+ "name": "entity.other.inherited-class.python"
992+ }
993+ }
994+ },
995+ "expression-class": {
996+ "patterns": [
997+ {
998+ "include": "#call-wrapper-inheritance"
999+ },
1000+ {
1001+ "include": "#expression-base"
1002+ },
1003+ {
1004+ "include": "#member-access-class"
1005+ }
1006+ ]
1007+ },
1008+ "member-access-class": {
1009+ "begin": "\\.\\s*(?!\\.)",
1010+ "end": "(?<=\\S)(?=\\W)|$",
1011+ "patterns": [
1012+ {
1013+ "include": "#call-wrapper-inheritance"
1014+ },
1015+ {
1016+ "include": "#member-access-base"
1017+ },
1018+ {
1019+ "include": "#inheritance-identifier"
1020+ }
1021+ ]
1022+ },
1023+ "lambda": {
1024+ "patterns": [
1025+ {
1026+ "match": "((?<=\\.)lambda|lambda(?=\\s*[\\.=]))",
1027+ "captures": {
1028+ "1": {
1029+ "name": "keyword.control.flow.python"
1030+ }
1031+ }
1032+ },
1033+ {
1034+ "match": "\\b(lambda)\\s*?([,\\n]|$)",
1035+ "captures": {
1036+ "1": {
1037+ "name": "storage.type.function.lambda.python"
1038+ }
1039+ }
1040+ },
1041+ {
1042+ "name": "meta.lambda-function.python",
1043+ "begin": "(?x)\n \\b (lambda) \\b\n",
1044+ "end": "(:)|(\\n)",
1045+ "beginCaptures": {
1046+ "1": {
1047+ "name": "storage.type.function.lambda.python"
1048+ }
1049+ },
1050+ "endCaptures": {
1051+ "1": {
1052+ "name": "punctuation.section.function.lambda.begin.python"
1053+ }
1054+ },
1055+ "contentName": "meta.function.lambda.parameters.python",
1056+ "patterns": [
1057+ {
1058+ "name": "keyword.operator.unpacking.parameter.python",
1059+ "match": "(\\*\\*|\\*)"
1060+ },
1061+ {
1062+ "include": "#lambda-incomplete"
1063+ },
1064+ {
1065+ "include": "#illegal-names"
1066+ },
1067+ {
1068+ "match": "([[:alpha:]_]\\w*)\\s*(?:(,)|(?=:|$))",
1069+ "captures": {
1070+ "1": {
1071+ "name": "variable.parameter.function.language.python"
1072+ },
1073+ "2": {
1074+ "name": "punctuation.separator.parameters.python"
1075+ }
1076+ }
1077+ },
1078+ {
1079+ "include": "#comments"
1080+ },
1081+ {
1082+ "include": "#backticks"
1083+ },
1084+ {
1085+ "include": "#illegal-anno"
1086+ },
1087+ {
1088+ "include": "#lambda-parameter-with-default"
1089+ },
1090+ {
1091+ "include": "#line-continuation"
1092+ },
1093+ {
1094+ "include": "#illegal-operator"
1095+ }
1096+ ]
1097+ }
1098+ ]
1099+ },
1100+ "lambda-incomplete": {
1101+ "name": "storage.type.function.lambda.python",
1102+ "match": "\\blambda(?=\\s*[:,)])"
1103+ },
1104+ "lambda-parameter-with-default": {
1105+ "begin": "(?x)\n \\b\n ([[:alpha:]_]\\w*) \\s* (=)\n",
1106+ "end": "(,)|(?=:|$)",
1107+ "beginCaptures": {
1108+ "1": {
1109+ "name": "variable.parameter.function.language.python"
1110+ },
1111+ "2": {
1112+ "name": "keyword.operator.python"
1113+ }
1114+ },
1115+ "endCaptures": {
1116+ "1": {
1117+ "name": "punctuation.separator.parameters.python"
1118+ }
1119+ },
1120+ "patterns": [
1121+ {
1122+ "include": "#expression"
1123+ }
1124+ ]
1125+ },
1126+ "function-declaration": {
1127+ "name": "meta.function.python",
1128+ "begin": "(?x)\n \\s*\n (?:\\b(async) \\s+)? \\b(def)\\s+\n (?=\n [[:alpha:]_][[:word:]]* \\s* \\(\n )\n",
1129+ "end": "(:|(?=[#'\"\\n]))",
1130+ "beginCaptures": {
1131+ "1": {
1132+ "name": "storage.type.function.async.python"
1133+ },
1134+ "2": {
1135+ "name": "storage.type.function.python"
1136+ }
1137+ },
1138+ "endCaptures": {
1139+ "1": {
1140+ "name": "punctuation.section.function.begin.python"
1141+ }
1142+ },
1143+ "patterns": [
1144+ {
1145+ "include": "#function-def-name"
1146+ },
1147+ {
1148+ "include": "#parameters"
1149+ },
1150+ {
1151+ "include": "#line-continuation"
1152+ },
1153+ {
1154+ "include": "#return-annotation"
1155+ }
1156+ ]
1157+ },
1158+ "function-def-name": {
1159+ "patterns": [
1160+ {
1161+ "include": "#illegal-object-name"
1162+ },
1163+ {
1164+ "include": "#builtin-possible-callables"
1165+ },
1166+ {
1167+ "name": "entity.name.function.python",
1168+ "match": "(?x)\n \\b ([[:alpha:]_]\\w*) \\b\n"
1169+ }
1170+ ]
1171+ },
1172+ "parameters": {
1173+ "name": "meta.function.parameters.python",
1174+ "begin": "(\\()",
1175+ "end": "(\\))",
1176+ "beginCaptures": {
1177+ "1": {
1178+ "name": "punctuation.definition.parameters.begin.python"
1179+ }
1180+ },
1181+ "endCaptures": {
1182+ "1": {
1183+ "name": "punctuation.definition.parameters.end.python"
1184+ }
1185+ },
1186+ "patterns": [
1187+ {
1188+ "name": "keyword.operator.unpacking.parameter.python",
1189+ "match": "(\\*\\*|\\*)"
1190+ },
1191+ {
1192+ "include": "#lambda-incomplete"
1193+ },
1194+ {
1195+ "include": "#illegal-names"
1196+ },
1197+ {
1198+ "include": "#illegal-object-name"
1199+ },
1200+ {
1201+ "include": "#parameter-special"
1202+ },
1203+ {
1204+ "match": "(?x)\n ([[:alpha:]_]\\w*)\n \\s* (?: (,) | (?=[)#\\n=]))\n",
1205+ "captures": {
1206+ "1": {
1207+ "name": "variable.parameter.function.language.python"
1208+ },
1209+ "2": {
1210+ "name": "punctuation.separator.parameters.python"
1211+ }
1212+ }
1213+ },
1214+ {
1215+ "include": "#comments"
1216+ },
1217+ {
1218+ "include": "#loose-default"
1219+ },
1220+ {
1221+ "include": "#annotated-parameter"
1222+ }
1223+ ]
1224+ },
1225+ "parameter-special": {
1226+ "match": "(?x)\n \\b ((self)|(cls)) \\b \\s*(?:(,)|(?=\\)))\n",
1227+ "captures": {
1228+ "1": {
1229+ "name": "variable.parameter.function.language.python"
1230+ },
1231+ "2": {
1232+ "name": "variable.parameter.function.language.special.self.python"
1233+ },
1234+ "3": {
1235+ "name": "variable.parameter.function.language.special.cls.python"
1236+ },
1237+ "4": {
1238+ "name": "punctuation.separator.parameters.python"
1239+ }
1240+ }
1241+ },
1242+ "loose-default": {
1243+ "begin": "(=)",
1244+ "end": "(,)|(?=\\))",
1245+ "beginCaptures": {
1246+ "1": {
1247+ "name": "keyword.operator.python"
1248+ }
1249+ },
1250+ "endCaptures": {
1251+ "1": {
1252+ "name": "punctuation.separator.parameters.python"
1253+ }
1254+ },
1255+ "patterns": [
1256+ {
1257+ "include": "#expression"
1258+ }
1259+ ]
1260+ },
1261+ "annotated-parameter": {
1262+ "begin": "(?x)\n \\b\n ([[:alpha:]_]\\w*) \\s* (:)\n",
1263+ "end": "(,)|(?=\\))",
1264+ "beginCaptures": {
1265+ "1": {
1266+ "name": "variable.parameter.function.language.python"
1267+ },
1268+ "2": {
1269+ "name": "punctuation.separator.annotation.python"
1270+ }
1271+ },
1272+ "endCaptures": {
1273+ "1": {
1274+ "name": "punctuation.separator.parameters.python"
1275+ }
1276+ },
1277+ "patterns": [
1278+ {
1279+ "include": "#expression"
1280+ },
1281+ {
1282+ "name": "keyword.operator.assignment.python",
1283+ "match": "=(?!=)"
1284+ }
1285+ ]
1286+ },
1287+ "return-annotation": {
1288+ "begin": "(->)",
1289+ "end": "(?=:)",
1290+ "beginCaptures": {
1291+ "1": {
1292+ "name": "punctuation.separator.annotation.result.python"
1293+ }
1294+ },
1295+ "patterns": [
1296+ {
1297+ "include": "#expression"
1298+ }
1299+ ]
1300+ },
1301+ "item-access": {
1302+ "patterns": [
1303+ {
1304+ "name": "meta.item-access.python",
1305+ "begin": "(?x)\n \\b(?=\n [[:alpha:]_]\\w* \\s* \\[\n )\n",
1306+ "end": "(\\])",
1307+ "endCaptures": {
1308+ "1": {
1309+ "name": "punctuation.definition.arguments.end.python"
1310+ }
1311+ },
1312+ "patterns": [
1313+ {
1314+ "include": "#item-name"
1315+ },
1316+ {
1317+ "include": "#item-index"
1318+ },
1319+ {
1320+ "include": "#expression"
1321+ }
1322+ ]
1323+ }
1324+ ]
1325+ },
1326+ "item-name": {
1327+ "patterns": [
1328+ {
1329+ "include": "#special-variables"
1330+ },
1331+ {
1332+ "include": "#builtin-functions"
1333+ },
1334+ {
1335+ "include": "#special-names"
1336+ },
1337+ {
1338+ "match": "(?x)\n \\b ([[:alpha:]_]\\w*) \\b\n"
1339+ }
1340+ ]
1341+ },
1342+ "item-index": {
1343+ "begin": "(\\[)",
1344+ "end": "(?=\\])",
1345+ "beginCaptures": {
1346+ "1": {
1347+ "name": "punctuation.definition.arguments.begin.python"
1348+ }
1349+ },
1350+ "contentName": "meta.item-access.arguments.python",
1351+ "patterns": [
1352+ {
1353+ "include": "#expression"
1354+ }
1355+ ]
1356+ },
1357+ "decorator": {
1358+ "name": "meta.function.decorator.python",
1359+ "begin": "(?x)\n ^\\s*\n (@) \\s* (?=[[:alpha:]_]\\w*)\n",
1360+ "end": "(?x)\n ( \\) ) (?: (?=\\s*\\#|$) | (.*$) )\n | (?=\\n|\\#)\n",
1361+ "beginCaptures": {
1362+ "1": {
1363+ "name": "entity.name.function.decorator.python"
1364+ }
1365+ },
1366+ "endCaptures": {
1367+ "1": {
1368+ "name": "punctuation.definition.arguments.end.python"
1369+ },
1370+ "2": {
1371+ "name": "invalid.illegal.decorator.python"
1372+ }
1373+ },
1374+ "patterns": [
1375+ {
1376+ "include": "#decorator-name"
1377+ },
1378+ {
1379+ "include": "#function-arguments"
1380+ }
1381+ ]
1382+ },
1383+ "decorator-name": {
1384+ "patterns": [
1385+ {
1386+ "include": "#builtin-callables"
1387+ },
1388+ {
1389+ "include": "#illegal-object-name"
1390+ },
1391+ {
1392+ "name": "entity.name.function.decorator.python",
1393+ "match": "(?x)\n ([[:alpha:]_]\\w*) | \\.\n"
1394+ },
1395+ {
1396+ "include": "#line-continuation"
1397+ },
1398+ {
1399+ "name": "invalid.illegal.decorator.python",
1400+ "match": "(?x)\n \\s* ([^([:alpha:]\\s_\\.#\\\\] .*?) (?=\\#|$)\n",
1401+ "captures": {
1402+ "1": {
1403+ "name": "invalid.illegal.decorator.python"
1404+ }
1405+ }
1406+ }
1407+ ]
1408+ },
1409+ "call-wrapper-inheritance": {
1410+ "comment": "same as a funciton call, but in inheritance context",
1411+ "name": "meta.function-call.python",
1412+ "begin": "(?x)\n \\b(?=\n ([[:alpha:]_]\\w*) \\s* (\\()\n )\n",
1413+ "end": "(\\))",
1414+ "endCaptures": {
1415+ "1": {
1416+ "name": "punctuation.definition.arguments.end.python"
1417+ }
1418+ },
1419+ "patterns": [
1420+ {
1421+ "include": "#inheritance-name"
1422+ },
1423+ {
1424+ "include": "#function-arguments"
1425+ }
1426+ ]
1427+ },
1428+ "inheritance-name": {
1429+ "patterns": [
1430+ {
1431+ "include": "#lambda-incomplete"
1432+ },
1433+ {
1434+ "include": "#builtin-possible-callables"
1435+ },
1436+ {
1437+ "include": "#inheritance-identifier"
1438+ }
1439+ ]
1440+ },
1441+ "function-call": {
1442+ "name": "meta.function-call.python",
1443+ "begin": "(?x)\n \\b(?=\n ([[:alpha:]_]\\w*) \\s* (\\()\n )\n",
1444+ "end": "(\\))",
1445+ "endCaptures": {
1446+ "1": {
1447+ "name": "punctuation.definition.arguments.end.python"
1448+ }
1449+ },
1450+ "patterns": [
1451+ {
1452+ "include": "#special-variables"
1453+ },
1454+ {
1455+ "include": "#function-name"
1456+ },
1457+ {
1458+ "include": "#function-arguments"
1459+ }
1460+ ]
1461+ },
1462+ "function-name": {
1463+ "patterns": [
1464+ {
1465+ "include": "#builtin-possible-callables"
1466+ },
1467+ {
1468+ "comment": "Some color schemas support meta.function-call.generic scope",
1469+ "name": "meta.function-call.generic.python",
1470+ "match": "(?x)\n \\b ([[:alpha:]_]\\w*) \\b\n"
1471+ }
1472+ ]
1473+ },
1474+ "function-arguments": {
1475+ "begin": "(?x)\n (?:\n (\\()\n (?:\\s*(\\*\\*|\\*))?\n )\n",
1476+ "end": "(?=\\))(?!\\)\\s*\\()",
1477+ "beginCaptures": {
1478+ "1": {
1479+ "name": "punctuation.definition.arguments.begin.python"
1480+ },
1481+ "2": {
1482+ "name": "keyword.operator.unpacking.arguments.python"
1483+ }
1484+ },
1485+ "contentName": "meta.function-call.arguments.python",
1486+ "patterns": [
1487+ {
1488+ "match": "(?x)\n (?:\n (,)\n (?:\\s*(\\*\\*|\\*))?\n )\n",
1489+ "captures": {
1490+ "1": {
1491+ "name": "punctuation.separator.arguments.python"
1492+ },
1493+ "2": {
1494+ "name": "keyword.operator.unpacking.arguments.python"
1495+ }
1496+ }
1497+ },
1498+ {
1499+ "include": "#lambda-incomplete"
1500+ },
1501+ {
1502+ "include": "#illegal-names"
1503+ },
1504+ {
1505+ "match": "\\b([[:alpha:]_]\\w*)\\s*(=)(?!=)",
1506+ "captures": {
1507+ "1": {
1508+ "name": "variable.parameter.function-call.python"
1509+ },
1510+ "2": {
1511+ "name": "keyword.operator.assignment.python"
1512+ }
1513+ }
1514+ },
1515+ {
1516+ "name": "keyword.operator.assignment.python",
1517+ "match": "=(?!=)"
1518+ },
1519+ {
1520+ "include": "#expression"
1521+ },
1522+ {
1523+ "match": "\\s*(\\))\\s*(\\()",
1524+ "captures": {
1525+ "1": {
1526+ "name": "punctuation.definition.arguments.end.python"
1527+ },
1528+ "2": {
1529+ "name": "punctuation.definition.arguments.begin.python"
1530+ }
1531+ }
1532+ }
1533+ ]
1534+ },
1535+ "builtin-callables": {
1536+ "patterns": [
1537+ {
1538+ "include": "#illegal-names"
1539+ },
1540+ {
1541+ "include": "#illegal-object-name"
1542+ },
1543+ {
1544+ "include": "#builtin-exceptions"
1545+ },
1546+ {
1547+ "include": "#builtin-functions"
1548+ },
1549+ {
1550+ "include": "#builtin-types"
1551+ }
1552+ ]
1553+ },
1554+ "builtin-possible-callables": {
1555+ "patterns": [
1556+ {
1557+ "include": "#builtin-callables"
1558+ },
1559+ {
1560+ "include": "#magic-names"
1561+ }
1562+ ]
1563+ },
modified extensions/vscode/textmate-syntaxes/MagicRegExp.tmLanguage.json +432 −434
@@ -1,435 +1,433 @@
11 {
2- "name": "MagicRegExp",
3- "scopeName": "source.regexp.python",
4- "fileTypes": [
5- "re"
6- ],
7- "uuid": "39e15186-71e6-11e5-b82c-7c6d62900c7c",
8- "patterns": [
9- {
10- "include": "#regexp-expression"
11- }
12- ],
13- "repository": {
14- "regexp-base-expression": {
15- "patterns": [
16- {
17- "name": "support.other.match.any.regexp",
18- "match": "\\."
19- },
20- {
21- "name": "support.other.match.begin.regexp",
22- "match": "\\^"
23- },
24- {
25- "name": "support.other.match.end.regexp",
26- "match": "\\$"
27- },
28- {
29- "name": "keyword.operator.quantifier.regexp",
30- "match": "[+*?]\\??"
31- },
32- {
33- "name": "keyword.operator.disjunction.regexp",
34- "match": "\\|"
35- },
36- {
37- "name": "keyword.operator.quantifier.regexp",
38- "match": "(?x)\n \\{(\n \\d+ | \\d+,(\\d+)? | ,\\d+\n )\\}\n"
39- },
40- {
41- "include": "#regexp-escape-sequence"
42- }
43- ]
44- },
45- "regexp-backreference-number": {
46- "name": "meta.backreference.regexp",
47- "match": "(\\\\[1-9]\\d?)",
48- "captures": {
49- "1": {
50- "name": "entity.name.tag.backreference.regexp"
51- }
52- }
53- },
54- "regexp-backreference": {
55- "name": "meta.backreference.named.regexp",
56- "match": "(?x)\n (\\() (\\?P= \\w+(?:\\s+[[:alnum:]]+)?) (\\))\n",
57- "captures": {
58- "1": {
59- "name": "punctuation.parenthesis.backreference.named.begin.regexp support.other.parenthesis.regexp"
60- },
61- "2": {
62- "name": "entity.name.tag.named.backreference.regexp"
63- },
64- "3": {
65- "name": "punctuation.parenthesis.backreference.named.end.regexp support.other.parenthesis.regexp"
66- }
67- }
68- },
69- "regexp-flags": {
70- "name": "storage.modifier.flag.regexp",
71- "match": "\\(\\?[aiLmsux]+\\)"
72- },
73- "regexp-escape-special": {
74- "name": "support.other.escape.special.regexp",
75- "match": "\\\\([AbBdDsSwWZ])"
76- },
77- "regexp-escape-character": {
78- "name": "constant.character.escape.regexp",
79- "match": "(?x)\n \\\\ (\n x[0-9A-Fa-f]{2}\n | 0[0-7]{1,2}\n | [0-7]{3}\n )\n"
80- },
81- "regexp-escape-unicode": {
82- "name": "constant.character.unicode.regexp",
83- "match": "(?x)\n \\\\ (\n u[0-9A-Fa-f]{4}\n | U[0-9A-Fa-f]{8}\n )\n"
84- },
85- "regexp-escape-catchall": {
86- "name": "constant.character.escape.regexp",
87- "match": "\\\\(.|\\n)"
88- },
89- "regexp-escape-sequence": {
90- "patterns": [
91- {
92- "include": "#regexp-escape-special"
93- },
94- {
95- "include": "#regexp-escape-character"
96- },
97- {
98- "include": "#regexp-escape-unicode"
99- },
100- {
101- "include": "#regexp-backreference-number"
102- },
103- {
104- "include": "#regexp-escape-catchall"
105- }
106- ]
107- },
108- "regexp-charecter-set-escapes": {
109- "patterns": [
110- {
111- "name": "constant.character.escape.regexp",
112- "match": "\\\\[abfnrtv\\\\]"
113- },
114- {
115- "include": "#regexp-escape-special"
116- },
117- {
118- "name": "constant.character.escape.regexp",
119- "match": "\\\\([0-7]{1,3})"
120- },
121- {
122- "include": "#regexp-escape-character"
123- },
124- {
125- "include": "#regexp-escape-unicode"
126- },
127- {
128- "include": "#regexp-escape-catchall"
129- }
130- ]
131- },
132- "regexp-expression": {
133- "patterns": [
134- {
135- "include": "#regexp-base-expression"
136- },
137- {
138- "include": "#regexp-character-set"
139- },
140- {
141- "include": "#regexp-comments"
142- },
143- {
144- "include": "#regexp-flags"
145- },
146- {
147- "include": "#regexp-named-group"
148- },
149- {
150- "include": "#regexp-backreference"
151- },
152- {
153- "include": "#regexp-lookahead"
154- },
155- {
156- "include": "#regexp-lookahead-negative"
157- },
158- {
159- "include": "#regexp-lookbehind"
160- },
161- {
162- "include": "#regexp-lookbehind-negative"
163- },
164- {
165- "include": "#regexp-conditional"
166- },
167- {
168- "include": "#regexp-parentheses-non-capturing"
169- },
170- {
171- "include": "#regexp-parentheses"
172- }
173- ]
174- },
175- "regexp-character-set": {
176- "patterns": [
177- {
178- "match": "(?x)\n \\[ \\^? \\] (?! .*?\\])\n"
179- },
180- {
181- "name": "meta.character.set.regexp",
182- "begin": "(\\[)(\\^)?(\\])?",
183- "end": "(\\])",
184- "beginCaptures": {
185- "1": {
186- "name": "constant.other.set.regexp punctuation.character.set.begin.regexp"
187- },
188- "2": {
189- "name": "keyword.operator.negation.regexp"
190- },
191- "3": {
192- "name": "constant.character.set.regexp"
193- }
194- },
195- "endCaptures": {
196- "1": {
197- "name": "constant.other.set.regexp punctuation.character.set.end.regexp"
198- },
199- "2": {
200- "name": "invalid.illegal.newline.python"
201- }
202- },
203- "patterns": [
204- {
205- "include": "#regexp-charecter-set-escapes"
206- },
207- {
208- "name": "constant.character.set.regexp",
209- "match": "[^\\n]"
210- }
211- ]
212- }
213- ]
214- },
215- "regexp-named-group": {
216- "name": "meta.named.regexp",
217- "begin": "(?x)\n (\\() (\\?P <\\w+(?:\\s+[[:alnum:]]+)?>)\n",
218- "end": "(\\))",
219- "beginCaptures": {
220- "1": {
221- "name": "punctuation.parenthesis.named.begin.regexp support.other.parenthesis.regexp"
222- },
223- "2": {
224- "name": "entity.name.tag.named.group.regexp"
225- }
226- },
227- "endCaptures": {
228- "1": {
229- "name": "punctuation.parenthesis.named.end.regexp support.other.parenthesis.regexp"
230- },
231- "2": {
232- "name": "invalid.illegal.newline.python"
233- }
234- },
235- "patterns": [
236- {
237- "include": "#regexp-expression"
238- }
239- ]
240- },
241- "regexp-comments": {
242- "name": "comment.regexp",
243- "begin": "\\(\\?#",
244- "end": "(\\))",
245- "beginCaptures": {
246- "0": {
247- "name": "punctuation.comment.begin.regexp"
248- }
249- },
250- "endCaptures": {
251- "1": {
252- "name": "punctuation.comment.end.regexp"
253- },
254- "2": {
255- "name": "invalid.illegal.newline.python"
256- }
257- },
258- "patterns": [
259- {
260- "include": "#codetags"
261- }
262- ]
263- },
264- "regexp-lookahead": {
265- "begin": "(\\()\\?=",
266- "end": "(\\))",
267- "beginCaptures": {
268- "0": {
269- "name": "keyword.operator.lookahead.regexp"
270- },
271- "1": {
272- "name": "punctuation.parenthesis.lookahead.begin.regexp"
273- }
274- },
275- "endCaptures": {
276- "1": {
277- "name": "punctuation.parenthesis.lookahead.end.regexp keyword.operator.lookahead.regexp"
278- },
279- "2": {
280- "name": "invalid.illegal.newline.python"
281- }
282- },
283- "patterns": [
284- {
285- "include": "#regexp-expression"
286- }
287- ]
288- },
289- "regexp-lookahead-negative": {
290- "begin": "(\\()\\?!",
291- "end": "(\\))",
292- "beginCaptures": {
293- "0": {
294- "name": "keyword.operator.lookahead.negative.regexp"
295- },
296- "1": {
297- "name": "punctuation.parenthesis.lookahead.begin.regexp"
298- }
299- },
300- "endCaptures": {
301- "1": {
302- "name": "punctuation.parenthesis.lookahead.end.regexp keyword.operator.lookahead.negative.regexp"
303- },
304- "2": {
305- "name": "invalid.illegal.newline.python"
306- }
307- },
308- "patterns": [
309- {
310- "include": "#regexp-expression"
311- }
312- ]
313- },
314- "regexp-lookbehind": {
315- "begin": "(\\()\\?<=",
316- "end": "(\\))",
317- "beginCaptures": {
318- "0": {
319- "name": "keyword.operator.lookbehind.regexp"
320- },
321- "1": {
322- "name": "punctuation.parenthesis.lookbehind.begin.regexp"
323- }
324- },
325- "endCaptures": {
326- "1": {
327- "name": "punctuation.parenthesis.lookbehind.end.regexp keyword.operator.lookbehind.regexp"
328- },
329- "2": {
330- "name": "invalid.illegal.newline.python"
331- }
332- },
333- "patterns": [
334- {
335- "include": "#regexp-expression"
336- }
337- ]
338- },
339- "regexp-lookbehind-negative": {
340- "begin": "(\\()\\?<!",
341- "end": "(\\))",
342- "beginCaptures": {
343- "0": {
344- "name": "keyword.operator.lookbehind.negative.regexp"
345- },
346- "1": {
347- "name": "punctuation.parenthesis.lookbehind.begin.regexp"
348- }
349- },
350- "endCaptures": {
351- "1": {
352- "name": "punctuation.parenthesis.lookbehind.end.regexp keyword.operator.lookbehind.negative.regexp"
353- },
354- "2": {
355- "name": "invalid.illegal.newline.python"
356- }
357- },
358- "patterns": [
359- {
360- "include": "#regexp-expression"
361- }
362- ]
363- },
364- "regexp-conditional": {
365- "begin": "(\\()\\?\\((\\w+(?:\\s+[[:alnum:]]+)?|\\d+)\\)",
366- "end": "(\\))",
367- "beginCaptures": {
368- "0": {
369- "name": "keyword.operator.conditional.regexp"
370- },
371- "1": {
372- "name": "punctuation.parenthesis.conditional.begin.regexp"
373- }
374- },
375- "endCaptures": {
376- "1": {
377- "name": "punctuation.parenthesis.conditional.end.regexp keyword.operator.conditional.negative.regexp"
378- },
379- "2": {
380- "name": "invalid.illegal.newline.python"
381- }
382- },
383- "patterns": [
384- {
385- "include": "#regexp-expression"
386- }
387- ]
388- },
389- "regexp-parentheses-non-capturing": {
390- "begin": "\\(\\?:",
391- "end": "(\\))",
392- "beginCaptures": {
393- "0": {
394- "name": "punctuation.parenthesis.non-capturing.begin.regexp support.other.parenthesis.regexp"
395- }
396- },
397- "endCaptures": {
398- "1": {
399- "name": "punctuation.parenthesis.non-capturing.end.regexp support.other.parenthesis.regexp"
400- },
401- "2": {
402- "name": "invalid.illegal.newline.python"
403- }
404- },
405- "patterns": [
406- {
407- "include": "#regexp-expression"
408- }
409- ]
410- },
411- "regexp-parentheses": {
412- "begin": "\\(",
413- "end": "(\\))",
414- "beginCaptures": {
415- "0": {
416- "name": "punctuation.parenthesis.begin.regexp support.other.parenthesis.regexp"
417- }
418- },
419- "endCaptures": {
420- "1": {
421- "name": "punctuation.parenthesis.end.regexp support.other.parenthesis.regexp"
422- },
423- "2": {
424- "name": "invalid.illegal.newline.python"
425- }
426- },
427- "patterns": [
428- {
429- "include": "#regexp-expression"
430- }
431- ]
432- }
433- },
434- "version": "https://github.com/MagicStack/MagicPython/commit/a45287d159f82256c768ad2e1114ca9751d28670"
435-}
No newline at the end of the file
2+ "name": "MagicRegExp",
3+ "scopeName": "source.regexp.python",
4+ "fileTypes": ["re"],
5+ "uuid": "39e15186-71e6-11e5-b82c-7c6d62900c7c",
6+ "patterns": [
7+ {
8+ "include": "#regexp-expression"
9+ }
10+ ],
11+ "repository": {
12+ "regexp-base-expression": {
13+ "patterns": [
14+ {
15+ "name": "support.other.match.any.regexp",
16+ "match": "\\."
17+ },
18+ {
19+ "name": "support.other.match.begin.regexp",
20+ "match": "\\^"
21+ },
22+ {
23+ "name": "support.other.match.end.regexp",
24+ "match": "\\$"
25+ },
26+ {
27+ "name": "keyword.operator.quantifier.regexp",
28+ "match": "[+*?]\\??"
29+ },
30+ {
31+ "name": "keyword.operator.disjunction.regexp",
32+ "match": "\\|"
33+ },
34+ {
35+ "name": "keyword.operator.quantifier.regexp",
36+ "match": "(?x)\n \\{(\n \\d+ | \\d+,(\\d+)? | ,\\d+\n )\\}\n"
37+ },
38+ {
39+ "include": "#regexp-escape-sequence"
40+ }
41+ ]
42+ },
43+ "regexp-backreference-number": {
44+ "name": "meta.backreference.regexp",
45+ "match": "(\\\\[1-9]\\d?)",
46+ "captures": {
47+ "1": {
48+ "name": "entity.name.tag.backreference.regexp"
49+ }
50+ }
51+ },
52+ "regexp-backreference": {
53+ "name": "meta.backreference.named.regexp",
54+ "match": "(?x)\n (\\() (\\?P= \\w+(?:\\s+[[:alnum:]]+)?) (\\))\n",
55+ "captures": {
56+ "1": {
57+ "name": "punctuation.parenthesis.backreference.named.begin.regexp support.other.parenthesis.regexp"
58+ },
59+ "2": {
60+ "name": "entity.name.tag.named.backreference.regexp"
61+ },
62+ "3": {
63+ "name": "punctuation.parenthesis.backreference.named.end.regexp support.other.parenthesis.regexp"
64+ }
65+ }
66+ },
67+ "regexp-flags": {
68+ "name": "storage.modifier.flag.regexp",
69+ "match": "\\(\\?[aiLmsux]+\\)"
70+ },
71+ "regexp-escape-special": {
72+ "name": "support.other.escape.special.regexp",
73+ "match": "\\\\([AbBdDsSwWZ])"
74+ },
75+ "regexp-escape-character": {
76+ "name": "constant.character.escape.regexp",
77+ "match": "(?x)\n \\\\ (\n x[0-9A-Fa-f]{2}\n | 0[0-7]{1,2}\n | [0-7]{3}\n )\n"
78+ },
79+ "regexp-escape-unicode": {
80+ "name": "constant.character.unicode.regexp",
81+ "match": "(?x)\n \\\\ (\n u[0-9A-Fa-f]{4}\n | U[0-9A-Fa-f]{8}\n )\n"
82+ },
83+ "regexp-escape-catchall": {
84+ "name": "constant.character.escape.regexp",
85+ "match": "\\\\(.|\\n)"
86+ },
87+ "regexp-escape-sequence": {
88+ "patterns": [
89+ {
90+ "include": "#regexp-escape-special"
91+ },
92+ {
93+ "include": "#regexp-escape-character"
94+ },
95+ {
96+ "include": "#regexp-escape-unicode"
97+ },
98+ {
99+ "include": "#regexp-backreference-number"
100+ },
101+ {
102+ "include": "#regexp-escape-catchall"
103+ }
104+ ]
105+ },
106+ "regexp-charecter-set-escapes": {
107+ "patterns": [
108+ {
109+ "name": "constant.character.escape.regexp",
110+ "match": "\\\\[abfnrtv\\\\]"
111+ },
112+ {
113+ "include": "#regexp-escape-special"
114+ },
115+ {
116+ "name": "constant.character.escape.regexp",
117+ "match": "\\\\([0-7]{1,3})"
118+ },
119+ {
120+ "include": "#regexp-escape-character"
121+ },
122+ {
123+ "include": "#regexp-escape-unicode"
124+ },
125+ {
126+ "include": "#regexp-escape-catchall"
127+ }
128+ ]
129+ },
130+ "regexp-expression": {
131+ "patterns": [
132+ {
133+ "include": "#regexp-base-expression"
134+ },
135+ {
136+ "include": "#regexp-character-set"
137+ },
138+ {
139+ "include": "#regexp-comments"
140+ },
141+ {
142+ "include": "#regexp-flags"
143+ },
144+ {
145+ "include": "#regexp-named-group"
146+ },
147+ {
148+ "include": "#regexp-backreference"
149+ },
150+ {
151+ "include": "#regexp-lookahead"
152+ },
153+ {
154+ "include": "#regexp-lookahead-negative"
155+ },
156+ {
157+ "include": "#regexp-lookbehind"
158+ },
159+ {
160+ "include": "#regexp-lookbehind-negative"
161+ },
162+ {
163+ "include": "#regexp-conditional"
164+ },
165+ {
166+ "include": "#regexp-parentheses-non-capturing"
167+ },
168+ {
169+ "include": "#regexp-parentheses"
170+ }
171+ ]
172+ },
173+ "regexp-character-set": {
174+ "patterns": [
175+ {
176+ "match": "(?x)\n \\[ \\^? \\] (?! .*?\\])\n"
177+ },
178+ {
179+ "name": "meta.character.set.regexp",
180+ "begin": "(\\[)(\\^)?(\\])?",
181+ "end": "(\\])",
182+ "beginCaptures": {
183+ "1": {
184+ "name": "constant.other.set.regexp punctuation.character.set.begin.regexp"
185+ },
186+ "2": {
187+ "name": "keyword.operator.negation.regexp"
188+ },
189+ "3": {
190+ "name": "constant.character.set.regexp"
191+ }
192+ },
193+ "endCaptures": {
194+ "1": {
195+ "name": "constant.other.set.regexp punctuation.character.set.end.regexp"
196+ },
197+ "2": {
198+ "name": "invalid.illegal.newline.python"
199+ }
200+ },
201+ "patterns": [
202+ {
203+ "include": "#regexp-charecter-set-escapes"
204+ },
205+ {
206+ "name": "constant.character.set.regexp",
207+ "match": "[^\\n]"
208+ }
209+ ]
210+ }
211+ ]
212+ },
213+ "regexp-named-group": {
214+ "name": "meta.named.regexp",
215+ "begin": "(?x)\n (\\() (\\?P <\\w+(?:\\s+[[:alnum:]]+)?>)\n",
216+ "end": "(\\))",
217+ "beginCaptures": {
218+ "1": {
219+ "name": "punctuation.parenthesis.named.begin.regexp support.other.parenthesis.regexp"
220+ },
221+ "2": {
222+ "name": "entity.name.tag.named.group.regexp"
223+ }
224+ },
225+ "endCaptures": {
226+ "1": {
227+ "name": "punctuation.parenthesis.named.end.regexp support.other.parenthesis.regexp"
228+ },
229+ "2": {
230+ "name": "invalid.illegal.newline.python"
231+ }
232+ },
233+ "patterns": [
234+ {
235+ "include": "#regexp-expression"
236+ }
237+ ]
238+ },
239+ "regexp-comments": {
240+ "name": "comment.regexp",
241+ "begin": "\\(\\?#",
242+ "end": "(\\))",
243+ "beginCaptures": {
244+ "0": {
245+ "name": "punctuation.comment.begin.regexp"
246+ }
247+ },
248+ "endCaptures": {
249+ "1": {
250+ "name": "punctuation.comment.end.regexp"
251+ },
252+ "2": {
253+ "name": "invalid.illegal.newline.python"
254+ }
255+ },
256+ "patterns": [
257+ {
258+ "include": "#codetags"
259+ }
260+ ]
261+ },
262+ "regexp-lookahead": {
263+ "begin": "(\\()\\?=",
264+ "end": "(\\))",
265+ "beginCaptures": {
266+ "0": {
267+ "name": "keyword.operator.lookahead.regexp"
268+ },
269+ "1": {
270+ "name": "punctuation.parenthesis.lookahead.begin.regexp"
271+ }
272+ },
273+ "endCaptures": {
274+ "1": {
275+ "name": "punctuation.parenthesis.lookahead.end.regexp keyword.operator.lookahead.regexp"
276+ },
277+ "2": {
278+ "name": "invalid.illegal.newline.python"
279+ }
280+ },
281+ "patterns": [
282+ {
283+ "include": "#regexp-expression"
284+ }
285+ ]
286+ },
287+ "regexp-lookahead-negative": {
288+ "begin": "(\\()\\?!",
289+ "end": "(\\))",
290+ "beginCaptures": {
291+ "0": {
292+ "name": "keyword.operator.lookahead.negative.regexp"
293+ },
294+ "1": {
295+ "name": "punctuation.parenthesis.lookahead.begin.regexp"
296+ }
297+ },
298+ "endCaptures": {
299+ "1": {
300+ "name": "punctuation.parenthesis.lookahead.end.regexp keyword.operator.lookahead.negative.regexp"
301+ },
302+ "2": {
303+ "name": "invalid.illegal.newline.python"
304+ }
305+ },
306+ "patterns": [
307+ {
308+ "include": "#regexp-expression"
309+ }
310+ ]
311+ },
312+ "regexp-lookbehind": {
313+ "begin": "(\\()\\?<=",
314+ "end": "(\\))",
315+ "beginCaptures": {
316+ "0": {
317+ "name": "keyword.operator.lookbehind.regexp"
318+ },
319+ "1": {
320+ "name": "punctuation.parenthesis.lookbehind.begin.regexp"
321+ }
322+ },
323+ "endCaptures": {
324+ "1": {
325+ "name": "punctuation.parenthesis.lookbehind.end.regexp keyword.operator.lookbehind.regexp"
326+ },
327+ "2": {
328+ "name": "invalid.illegal.newline.python"
329+ }
330+ },
331+ "patterns": [
332+ {
333+ "include": "#regexp-expression"
334+ }
335+ ]
336+ },
337+ "regexp-lookbehind-negative": {
338+ "begin": "(\\()\\?<!",
339+ "end": "(\\))",
340+ "beginCaptures": {
341+ "0": {
342+ "name": "keyword.operator.lookbehind.negative.regexp"
343+ },
344+ "1": {
345+ "name": "punctuation.parenthesis.lookbehind.begin.regexp"
346+ }
347+ },
348+ "endCaptures": {
349+ "1": {
350+ "name": "punctuation.parenthesis.lookbehind.end.regexp keyword.operator.lookbehind.negative.regexp"
351+ },
352+ "2": {
353+ "name": "invalid.illegal.newline.python"
354+ }
355+ },
356+ "patterns": [
357+ {
358+ "include": "#regexp-expression"
359+ }
360+ ]
361+ },
362+ "regexp-conditional": {
363+ "begin": "(\\()\\?\\((\\w+(?:\\s+[[:alnum:]]+)?|\\d+)\\)",
364+ "end": "(\\))",
365+ "beginCaptures": {
366+ "0": {
367+ "name": "keyword.operator.conditional.regexp"
368+ },
369+ "1": {
370+ "name": "punctuation.parenthesis.conditional.begin.regexp"
371+ }
372+ },
373+ "endCaptures": {
374+ "1": {
375+ "name": "punctuation.parenthesis.conditional.end.regexp keyword.operator.conditional.negative.regexp"
376+ },
377+ "2": {
378+ "name": "invalid.illegal.newline.python"
379+ }
380+ },
381+ "patterns": [
382+ {
383+ "include": "#regexp-expression"
384+ }
385+ ]
386+ },
387+ "regexp-parentheses-non-capturing": {
388+ "begin": "\\(\\?:",
389+ "end": "(\\))",
390+ "beginCaptures": {
391+ "0": {
392+ "name": "punctuation.parenthesis.non-capturing.begin.regexp support.other.parenthesis.regexp"
393+ }
394+ },
395+ "endCaptures": {
396+ "1": {
397+ "name": "punctuation.parenthesis.non-capturing.end.regexp support.other.parenthesis.regexp"
398+ },
399+ "2": {
400+ "name": "invalid.illegal.newline.python"
401+ }
402+ },
403+ "patterns": [
404+ {
405+ "include": "#regexp-expression"
406+ }
407+ ]
408+ },
409+ "regexp-parentheses": {
410+ "begin": "\\(",
411+ "end": "(\\))",
412+ "beginCaptures": {
413+ "0": {
414+ "name": "punctuation.parenthesis.begin.regexp support.other.parenthesis.regexp"
415+ }
416+ },
417+ "endCaptures": {
418+ "1": {
419+ "name": "punctuation.parenthesis.end.regexp support.other.parenthesis.regexp"
420+ },
421+ "2": {
422+ "name": "invalid.illegal.newline.python"
423+ }
424+ },
425+ "patterns": [
426+ {
427+ "include": "#regexp-expression"
428+ }
429+ ]
430+ }
431+ },
432+ "version": "https://github.com/MagicStack/MagicPython/commit/a45287d159f82256c768ad2e1114ca9751d28670"
433+}
modified extensions/vscode/textmate-syntaxes/Makefile.json +469 −474
@@ -1,475 +1,470 @@
11 {
2- "fileTypes": [
3- "Makefile",
4- "makefile",
5- "GNUmakefile",
6- "OCamlMakefile"
7- ],
8- "name": "Makefile",
9- "patterns": [
10- {
11- "include": "#comment"
12- },
13- {
14- "include": "#variable-assignment"
15- },
16- {
17- "include": "#recipe"
18- },
19- {
20- "include": "#directives"
21- }
22- ],
23- "repository": {
24- "comment": {
25- "begin": "(^[ \\t]+)?(?=#)",
26- "beginCaptures": {
27- "1": {
28- "name": "punctuation.whitespace.comment.leading.makefile"
29- }
30- },
31- "end": "(?!\\G)",
32- "patterns": [
33- {
34- "begin": "#",
35- "beginCaptures": {
36- "0": {
37- "name": "punctuation.definition.comment.makefile"
38- }
39- },
40- "end": "\\n",
41- "name": "comment.line.number-sign.makefile",
42- "patterns": [
43- {
44- "match": "\\\\\\n",
45- "name": "constant.character.escape.continuation.makefile"
46- }
47- ]
48- }
49- ]
50- },
51- "directives": {
52- "patterns": [
53- {
54- "begin": "^[ ]*([s\\-]?include)\\b",
55- "beginCaptures": {
56- "1": {
57- "name": "keyword.control.include.makefile"
58- }
59- },
60- "end": "^",
61- "patterns": [
62- {
63- "include": "#comment"
64- },
65- {
66- "include": "#variables"
67- },
68- {
69- "match": "%",
70- "name": "constant.other.placeholder.makefile"
71- }
72- ]
73- },
74- {
75- "begin": "^[ ]*(vpath)\\b",
76- "beginCaptures": {
77- "1": {
78- "name": "keyword.control.vpath.makefile"
79- }
80- },
81- "end": "^",
82- "patterns": [
83- {
84- "include": "#comment"
85- },
86- {
87- "include": "#variables"
88- },
89- {
90- "match": "%",
91- "name": "constant.other.placeholder.makefile"
92- }
93- ]
94- },
95- {
96- "begin": "^(?:(override)\\s*)?(define)\\s*([^\\s]+)\\s*(=|\\?=|:=|\\+=)?(?=\\s)",
97- "captures": {
98- "1": {
99- "name": "keyword.control.override.makefile"
100- },
101- "2": {
102- "name": "keyword.control.define.makefile"
103- },
104- "3": {
105- "name": "variable.other.makefile"
106- },
107- "4": {
108- "name": "punctuation.separator.key-value.makefile"
109- }
110- },
111- "end": "^(endef)\\b",
112- "name": "meta.scope.conditional.makefile",
113- "patterns": [
114- {
115- "begin": "\\G(?!\\n)",
116- "end": "^",
117- "patterns": [
118- {
119- "include": "#comment"
120- }
121- ]
122- },
123- {
124- "include": "#variables"
125- },
126- {
127- "include": "#comment"
128- }
129- ]
130- },
131- {
132- "begin": "^[ ]*(export)\\b",
133- "beginCaptures": {
134- "1": {
135- "name": "keyword.control.$1.makefile"
136- }
137- },
138- "end": "^",
139- "patterns": [
140- {
141- "include": "#comment"
142- },
143- {
144- "include": "#variable-assignment"
145- },
146- {
147- "match": "[^\\s]+",
148- "name": "variable.other.makefile"
149- }
150- ]
151- },
152- {
153- "begin": "^[ ]*(override|private)\\b",
154- "beginCaptures": {
155- "1": {
156- "name": "keyword.control.$1.makefile"
157- }
158- },
159- "end": "^",
160- "patterns": [
161- {
162- "include": "#comment"
163- },
164- {
165- "include": "#variable-assignment"
166- }
167- ]
168- },
169- {
170- "begin": "^[ ]*(unexport|undefine)\\b",
171- "beginCaptures": {
172- "1": {
173- "name": "keyword.control.$1.makefile"
174- }
175- },
176- "end": "^",
177- "patterns": [
178- {
179- "include": "#comment"
180- },
181- {
182- "match": "[^\\s]+",
183- "name": "variable.other.makefile"
184- }
185- ]
186- },
187- {
188- "begin": "^(ifdef|ifndef)\\s*([^\\s]+)(?=\\s)",
189- "captures": {
190- "1": {
191- "name": "keyword.control.$1.makefile"
192- },
193- "2": {
194- "name": "variable.other.makefile"
195- },
196- "3": {
197- "name": "punctuation.separator.key-value.makefile"
198- }
199- },
200- "end": "^(endif)\\b",
201- "name": "meta.scope.conditional.makefile",
202- "patterns": [
203- {
204- "begin": "\\G(?!\\n)",
205- "end": "^",
206- "patterns": [
207- {
208- "include": "#comment"
209- }
210- ]
211- },
212- {
213- "include": "$self"
214- }
215- ]
216- },
217- {
218- "begin": "^(ifeq|ifneq)(?=\\s)",
219- "captures": {
220- "1": {
221- "name": "keyword.control.$1.makefile"
222- }
223- },
224- "end": "^(endif)\\b",
225- "name": "meta.scope.conditional.makefile",
226- "patterns": [
227- {
228- "begin": "\\G",
229- "end": "^",
230- "name": "meta.scope.condition.makefile",
231- "patterns": [
232- {
233- "include": "#variables"
234- },
235- {
236- "include": "#comment"
237- }
238- ]
239- },
240- {
241- "begin": "^else(?=\\s)",
242- "beginCaptures": {
243- "0": {
244- "name": "keyword.control.else.makefile"
245- }
246- },
247- "end": "^"
248- },
249- {
250- "include": "$self"
251- }
252- ]
253- }
254- ]
255- },
256- "interpolation": {
257- "begin": "(?=`)",
258- "end": "(?!\\G)",
259- "name": "meta.embedded.line.shell",
260- "patterns": [
261- {
262- "begin": "`",
263- "beginCaptures": {
264- "0": {
265- "name": "punctuation.definition.string.makefile"
266- }
267- },
268- "contentName": "source.shell",
269- "end": "(`)",
270- "endCaptures": {
271- "0": {
272- "name": "punctuation.definition.string.makefile"
273- },
274- "1": {
275- "name": "source.shell"
276- }
277- },
278- "name": "string.interpolated.backtick.makefile",
279- "patterns": [
280- {
281- "include": "source.shell"
282- }
283- ]
284- }
285- ]
286- },
287- "recipe": {
288- "begin": "^(?!\\t)([^:]*)(:)(?!\\=)",
289- "beginCaptures": {
290- "1": {
291- "patterns": [
292- {
293- "captures": {
294- "1": {
295- "name": "support.function.target.$1.makefile"
296- }
297- },
298- "match": "^\\s*(\\.(PHONY|SUFFIXES|DEFAULT|PRECIOUS|INTERMEDIATE|SECONDARY|SECONDEXPANSION|DELETE_ON_ERROR|IGNORE|LOW_RESOLUTION_TIME|SILENT|EXPORT_ALL_VARIABLES|NOTPARALLEL|ONESHELL|POSIX))\\s*$"
299- },
300- {
301- "begin": "(?=\\S)",
302- "end": "(?=\\s|$)",
303- "name": "entity.name.function.target.makefile",
304- "patterns": [
305- {
306- "include": "#variables"
307- },
308- {
309- "match": "%",
310- "name": "constant.other.placeholder.makefile"
311- }
312- ]
313- }
314- ]
315- },
316- "2": {
317- "name": "punctuation.separator.key-value.makefile"
318- }
319- },
320- "end": "^(?!\\t)",
321- "name": "meta.scope.target.makefile",
322- "patterns": [
323- {
324- "begin": "\\G",
325- "end": "^",
326- "name": "meta.scope.prerequisites.makefile",
327- "patterns": [
328- {
329- "match": "\\\\\\n",
330- "name": "constant.character.escape.continuation.makefile"
331- },
332- {
333- "match": "%|\\*",
334- "name": "constant.other.placeholder.makefile"
335- },
336- {
337- "include": "#comment"
338- },
339- {
340- "include": "#variables"
341- }
342- ]
343- },
344- {
345- "begin": "^\\t",
346- "name": "meta.scope.recipe.makefile",
347- "patterns": [
348- {
349- "captures": {
350- "0": {
351- "patterns": [
352- {
353- "match": "\\\\\\n",
354- "name": "constant.character.escape.continuation.makefile"
355- },
356- {
357- "include": "#variables"
358- },
359- {
360- "include": "source.shell"
361- }
362- ]
363- }
364- },
365- "match": ".+\\n?"
366- }
367- ],
368- "while": "^\\t"
369- }
370- ]
371- },
372- "variable-assignment": {
373- "begin": "(^[ ]*|\\G\\s*)([^\\s]+)\\s*(=|\\?=|:=|\\+=)",
374- "beginCaptures": {
375- "2": {
376- "name": "variable.other.makefile"
377- },
378- "3": {
379- "name": "punctuation.separator.key-value.makefile"
380- }
381- },
382- "end": "\\n",
383- "patterns": [
384- {
385- "match": "\\\\\\n",
386- "name": "constant.character.escape.continuation.makefile"
387- },
388- {
389- "include": "#comment"
390- },
391- {
392- "include": "#variables"
393- },
394- {
395- "include": "#interpolation"
396- }
397- ]
398- },
399- "variables": {
400- "patterns": [
401- {
402- "captures": {
403- "1": {
404- "name": "punctuation.definition.variable.makefile"
405- }
406- },
407- "match": "(\\$?\\$)[@%<?^+*]",
408- "name": "variable.language.makefile"
409- },
410- {
411- "begin": "\\$?\\$\\(",
412- "captures": {
413- "0": {
414- "name": "punctuation.definition.variable.makefile"
415- }
416- },
417- "end": "\\)",
418- "name": "string.interpolated.makefile",
419- "patterns": [
420- {
421- "include": "#variables"
422- },
423- {
424- "match": "\\G(MAKEFILES|VPATH|SHELL|MAKESHELL|MAKE|MAKELEVEL|MAKEFLAGS|MAKECMDGOALS|CURDIR|SUFFIXES|\\.LIBPATTERNS)(?=\\s*\\))",
425- "name": "variable.language.makefile"
426- },
427- {
428- "begin": "\\G(subst|patsubst|strip|findstring|filter(-out)?|sort|word(list)?|firstword|lastword|dir|notdir|suffix|basename|addsuffix|addprefix|join|wildcard|realpath|abspath|info|error|warning|shell|foreach|if|or|and|call|eval|value|file|guile)\\s",
429- "beginCaptures": {
430- "1": {
431- "name": "support.function.$1.makefile"
432- }
433- },
434- "end": "(?=\\))",
435- "name": "meta.scope.function-call.makefile",
436- "patterns": [
437- {
438- "include": "#variables"
439- },
440- {
441- "match": "%|\\*",
442- "name": "constant.other.placeholder.makefile"
443- }
444- ]
445- },
446- {
447- "begin": "\\G(origin|flavor)\\s(?=[^\\s)]+\\s*\\))",
448- "contentName": "variable.other.makefile",
449- "end": "(?=\\))",
450- "name": "meta.scope.function-call.makefile",
451- "patterns": [
452- {
453- "include": "#variables"
454- }
455- ]
456- },
457- {
458- "begin": "\\G(?!\\))",
459- "end": "(?=\\))",
460- "name": "variable.other.makefile",
461- "patterns": [
462- {
463- "include": "#variables"
464- }
465- ]
466- }
467- ]
468- }
469- ]
470- }
471- },
472- "scopeName": "source.makefile",
473- "uuid": "FF1825E8-6B1C-11D9-B883-000D93589AF6",
474- "version": "https://github.com/textmate/make.tmbundle/commit/1a1827da81e20fdce56e2658451340c070ca44b7"
475-}
No newline at the end of the file
2+ "fileTypes": ["Makefile", "makefile", "GNUmakefile", "OCamlMakefile"],
3+ "name": "Makefile",
4+ "patterns": [
5+ {
6+ "include": "#comment"
7+ },
8+ {
9+ "include": "#variable-assignment"
10+ },
11+ {
12+ "include": "#recipe"
13+ },
14+ {
15+ "include": "#directives"
16+ }
17+ ],
18+ "repository": {
19+ "comment": {
20+ "begin": "(^[ \\t]+)?(?=#)",
21+ "beginCaptures": {
22+ "1": {
23+ "name": "punctuation.whitespace.comment.leading.makefile"
24+ }
25+ },
26+ "end": "(?!\\G)",
27+ "patterns": [
28+ {
29+ "begin": "#",
30+ "beginCaptures": {
31+ "0": {
32+ "name": "punctuation.definition.comment.makefile"
33+ }
34+ },
35+ "end": "\\n",
36+ "name": "comment.line.number-sign.makefile",
37+ "patterns": [
38+ {
39+ "match": "\\\\\\n",
40+ "name": "constant.character.escape.continuation.makefile"
41+ }
42+ ]
43+ }
44+ ]
45+ },
46+ "directives": {
47+ "patterns": [
48+ {
49+ "begin": "^[ ]*([s\\-]?include)\\b",
50+ "beginCaptures": {
51+ "1": {
52+ "name": "keyword.control.include.makefile"
53+ }
54+ },
55+ "end": "^",
56+ "patterns": [
57+ {
58+ "include": "#comment"
59+ },
60+ {
61+ "include": "#variables"
62+ },
63+ {
64+ "match": "%",
65+ "name": "constant.other.placeholder.makefile"
66+ }
67+ ]
68+ },
69+ {
70+ "begin": "^[ ]*(vpath)\\b",
71+ "beginCaptures": {
72+ "1": {
73+ "name": "keyword.control.vpath.makefile"
74+ }
75+ },
76+ "end": "^",
77+ "patterns": [
78+ {
79+ "include": "#comment"
80+ },
81+ {
82+ "include": "#variables"
83+ },
84+ {
85+ "match": "%",
86+ "name": "constant.other.placeholder.makefile"
87+ }
88+ ]
89+ },
90+ {
91+ "begin": "^(?:(override)\\s*)?(define)\\s*([^\\s]+)\\s*(=|\\?=|:=|\\+=)?(?=\\s)",
92+ "captures": {
93+ "1": {
94+ "name": "keyword.control.override.makefile"
95+ },
96+ "2": {
97+ "name": "keyword.control.define.makefile"
98+ },
99+ "3": {
100+ "name": "variable.other.makefile"
101+ },
102+ "4": {
103+ "name": "punctuation.separator.key-value.makefile"
104+ }
105+ },
106+ "end": "^(endef)\\b",
107+ "name": "meta.scope.conditional.makefile",
108+ "patterns": [
109+ {
110+ "begin": "\\G(?!\\n)",
111+ "end": "^",
112+ "patterns": [
113+ {
114+ "include": "#comment"
115+ }
116+ ]
117+ },
118+ {
119+ "include": "#variables"
120+ },
121+ {
122+ "include": "#comment"
123+ }
124+ ]
125+ },
126+ {
127+ "begin": "^[ ]*(export)\\b",
128+ "beginCaptures": {
129+ "1": {
130+ "name": "keyword.control.$1.makefile"
131+ }
132+ },
133+ "end": "^",
134+ "patterns": [
135+ {
136+ "include": "#comment"
137+ },
138+ {
139+ "include": "#variable-assignment"
140+ },
141+ {
142+ "match": "[^\\s]+",
143+ "name": "variable.other.makefile"
144+ }
145+ ]
146+ },
147+ {
148+ "begin": "^[ ]*(override|private)\\b",
149+ "beginCaptures": {
150+ "1": {
151+ "name": "keyword.control.$1.makefile"
152+ }
153+ },
154+ "end": "^",
155+ "patterns": [
156+ {
157+ "include": "#comment"
158+ },
159+ {
160+ "include": "#variable-assignment"
161+ }
162+ ]
163+ },
164+ {
165+ "begin": "^[ ]*(unexport|undefine)\\b",
166+ "beginCaptures": {
167+ "1": {
168+ "name": "keyword.control.$1.makefile"
169+ }
170+ },
171+ "end": "^",
172+ "patterns": [
173+ {
174+ "include": "#comment"
175+ },
176+ {
177+ "match": "[^\\s]+",
178+ "name": "variable.other.makefile"
179+ }
180+ ]
181+ },
182+ {
183+ "begin": "^(ifdef|ifndef)\\s*([^\\s]+)(?=\\s)",
184+ "captures": {
185+ "1": {
186+ "name": "keyword.control.$1.makefile"
187+ },
188+ "2": {
189+ "name": "variable.other.makefile"
190+ },
191+ "3": {
192+ "name": "punctuation.separator.key-value.makefile"
193+ }
194+ },
195+ "end": "^(endif)\\b",
196+ "name": "meta.scope.conditional.makefile",
197+ "patterns": [
198+ {
199+ "begin": "\\G(?!\\n)",
200+ "end": "^",
201+ "patterns": [
202+ {
203+ "include": "#comment"
204+ }
205+ ]
206+ },
207+ {
208+ "include": "$self"
209+ }
210+ ]
211+ },
212+ {
213+ "begin": "^(ifeq|ifneq)(?=\\s)",
214+ "captures": {
215+ "1": {
216+ "name": "keyword.control.$1.makefile"
217+ }
218+ },
219+ "end": "^(endif)\\b",
220+ "name": "meta.scope.conditional.makefile",
221+ "patterns": [
222+ {
223+ "begin": "\\G",
224+ "end": "^",
225+ "name": "meta.scope.condition.makefile",
226+ "patterns": [
227+ {
228+ "include": "#variables"
229+ },
230+ {
231+ "include": "#comment"
232+ }
233+ ]
234+ },
235+ {
236+ "begin": "^else(?=\\s)",
237+ "beginCaptures": {
238+ "0": {
239+ "name": "keyword.control.else.makefile"
240+ }
241+ },
242+ "end": "^"
243+ },
244+ {
245+ "include": "$self"
246+ }
247+ ]
248+ }
249+ ]
250+ },
251+ "interpolation": {
252+ "begin": "(?=`)",
253+ "end": "(?!\\G)",
254+ "name": "meta.embedded.line.shell",
255+ "patterns": [
256+ {
257+ "begin": "`",
258+ "beginCaptures": {
259+ "0": {
260+ "name": "punctuation.definition.string.makefile"
261+ }
262+ },
263+ "contentName": "source.shell",
264+ "end": "(`)",
265+ "endCaptures": {
266+ "0": {
267+ "name": "punctuation.definition.string.makefile"
268+ },
269+ "1": {
270+ "name": "source.shell"
271+ }
272+ },
273+ "name": "string.interpolated.backtick.makefile",
274+ "patterns": [
275+ {
276+ "include": "source.shell"
277+ }
278+ ]
279+ }
280+ ]
281+ },
282+ "recipe": {
283+ "begin": "^(?!\\t)([^:]*)(:)(?!\\=)",
284+ "beginCaptures": {
285+ "1": {
286+ "patterns": [
287+ {
288+ "captures": {
289+ "1": {
290+ "name": "support.function.target.$1.makefile"
291+ }
292+ },
293+ "match": "^\\s*(\\.(PHONY|SUFFIXES|DEFAULT|PRECIOUS|INTERMEDIATE|SECONDARY|SECONDEXPANSION|DELETE_ON_ERROR|IGNORE|LOW_RESOLUTION_TIME|SILENT|EXPORT_ALL_VARIABLES|NOTPARALLEL|ONESHELL|POSIX))\\s*$"
294+ },
295+ {
296+ "begin": "(?=\\S)",
297+ "end": "(?=\\s|$)",
298+ "name": "entity.name.function.target.makefile",
299+ "patterns": [
300+ {
301+ "include": "#variables"
302+ },
303+ {
304+ "match": "%",
305+ "name": "constant.other.placeholder.makefile"
306+ }
307+ ]
308+ }
309+ ]
310+ },
311+ "2": {
312+ "name": "punctuation.separator.key-value.makefile"
313+ }
314+ },
315+ "end": "^(?!\\t)",
316+ "name": "meta.scope.target.makefile",
317+ "patterns": [
318+ {
319+ "begin": "\\G",
320+ "end": "^",
321+ "name": "meta.scope.prerequisites.makefile",
322+ "patterns": [
323+ {
324+ "match": "\\\\\\n",
325+ "name": "constant.character.escape.continuation.makefile"
326+ },
327+ {
328+ "match": "%|\\*",
329+ "name": "constant.other.placeholder.makefile"
330+ },
331+ {
332+ "include": "#comment"
333+ },
334+ {
335+ "include": "#variables"
336+ }
337+ ]
338+ },
339+ {
340+ "begin": "^\\t",
341+ "name": "meta.scope.recipe.makefile",
342+ "patterns": [
343+ {
344+ "captures": {
345+ "0": {
346+ "patterns": [
347+ {
348+ "match": "\\\\\\n",
349+ "name": "constant.character.escape.continuation.makefile"
350+ },
351+ {
352+ "include": "#variables"
353+ },
354+ {
355+ "include": "source.shell"
356+ }
357+ ]
358+ }
359+ },
360+ "match": ".+\\n?"
361+ }
362+ ],
363+ "while": "^\\t"
364+ }
365+ ]
366+ },
367+ "variable-assignment": {
368+ "begin": "(^[ ]*|\\G\\s*)([^\\s]+)\\s*(=|\\?=|:=|\\+=)",
369+ "beginCaptures": {
370+ "2": {
371+ "name": "variable.other.makefile"
372+ },
373+ "3": {
374+ "name": "punctuation.separator.key-value.makefile"
375+ }
376+ },
377+ "end": "\\n",
378+ "patterns": [
379+ {
380+ "match": "\\\\\\n",
381+ "name": "constant.character.escape.continuation.makefile"
382+ },
383+ {
384+ "include": "#comment"
385+ },
386+ {
387+ "include": "#variables"
388+ },
389+ {
390+ "include": "#interpolation"
391+ }
392+ ]
393+ },
394+ "variables": {
395+ "patterns": [
396+ {
397+ "captures": {
398+ "1": {
399+ "name": "punctuation.definition.variable.makefile"
400+ }
401+ },
402+ "match": "(\\$?\\$)[@%<?^+*]",
403+ "name": "variable.language.makefile"
404+ },
405+ {
406+ "begin": "\\$?\\$\\(",
407+ "captures": {
408+ "0": {
409+ "name": "punctuation.definition.variable.makefile"
410+ }
411+ },
412+ "end": "\\)",
413+ "name": "string.interpolated.makefile",
414+ "patterns": [
415+ {
416+ "include": "#variables"
417+ },
418+ {
419+ "match": "\\G(MAKEFILES|VPATH|SHELL|MAKESHELL|MAKE|MAKELEVEL|MAKEFLAGS|MAKECMDGOALS|CURDIR|SUFFIXES|\\.LIBPATTERNS)(?=\\s*\\))",
420+ "name": "variable.language.makefile"
421+ },
422+ {
423+ "begin": "\\G(subst|patsubst|strip|findstring|filter(-out)?|sort|word(list)?|firstword|lastword|dir|notdir|suffix|basename|addsuffix|addprefix|join|wildcard|realpath|abspath|info|error|warning|shell|foreach|if|or|and|call|eval|value|file|guile)\\s",
424+ "beginCaptures": {
425+ "1": {
426+ "name": "support.function.$1.makefile"
427+ }
428+ },
429+ "end": "(?=\\))",
430+ "name": "meta.scope.function-call.makefile",
431+ "patterns": [
432+ {
433+ "include": "#variables"
434+ },
435+ {
436+ "match": "%|\\*",
437+ "name": "constant.other.placeholder.makefile"
438+ }
439+ ]
440+ },
441+ {
442+ "begin": "\\G(origin|flavor)\\s(?=[^\\s)]+\\s*\\))",
443+ "contentName": "variable.other.makefile",
444+ "end": "(?=\\))",
445+ "name": "meta.scope.function-call.makefile",
446+ "patterns": [
447+ {
448+ "include": "#variables"
449+ }
450+ ]
451+ },
452+ {
453+ "begin": "\\G(?!\\))",
454+ "end": "(?=\\))",
455+ "name": "variable.other.makefile",
456+ "patterns": [
457+ {
458+ "include": "#variables"
459+ }
460+ ]
461+ }
462+ ]
463+ }
464+ ]
465+ }
466+ },
467+ "scopeName": "source.makefile",
468+ "uuid": "FF1825E8-6B1C-11D9-B883-000D93589AF6",
469+ "version": "https://github.com/textmate/make.tmbundle/commit/1a1827da81e20fdce56e2658451340c070ca44b7"
470+}
modified extensions/vscode/textmate-syntaxes/Shell-Unix-Bash.tmLanguage.json +1230 −1230
@@ -1,1231 +1,1231 @@
11 {
2- "fileTypes": [
3- "sh",
4- "bash",
5- "zsh",
6- "bashrc",
7- "bash_profile",
8- "bash_login",
9- "profile",
10- "bash_logout",
11- ".textmate_init"
12- ],
13- "firstLineMatch": "^#!.*\\b(bash|zsh|sh|tcsh)|^#.*-\\*-.*\\bshell-script\\b.*-\\*-",
14- "keyEquivalent": "^~S",
15- "name": "Shell Script (Bash)",
16- "patterns": [
17- {
18- "include": "#comment"
19- },
20- {
21- "include": "#pipeline"
22- },
23- {
24- "include": "#list"
25- },
26- {
27- "include": "#compound-command"
28- },
29- {
30- "include": "#loop"
31- },
32- {
33- "include": "#string"
34- },
35- {
36- "include": "#function-definition"
37- },
38- {
39- "include": "#variable"
40- },
41- {
42- "include": "#interpolation"
43- },
44- {
45- "include": "#heredoc"
46- },
47- {
48- "include": "#herestring"
49- },
50- {
51- "include": "#redirection"
52- },
53- {
54- "include": "#pathname"
55- },
56- {
57- "include": "#keyword"
58- },
59- {
60- "include": "#support"
61- }
62- ],
63- "repository": {
64- "case-clause": {
65- "patterns": [
66- {
67- "begin": "(?=\\S)",
68- "end": ";;",
69- "endCaptures": {
70- "0": {
71- "name": "punctuation.terminator.case-clause.shell"
72- }
73- },
74- "name": "meta.scope.case-clause.shell",
75- "patterns": [
76- {
77- "begin": "(\\(|(?=\\S))",
78- "captures": {
79- "0": {
80- "name": "punctuation.definition.case-pattern.shell"
81- }
82- },
83- "end": "\\)",
84- "name": "meta.scope.case-pattern.shell",
85- "patterns": [
86- {
87- "match": "\\|",
88- "name": "punctuation.separator.pipe-sign.shell"
89- },
90- {
91- "include": "#string"
92- },
93- {
94- "include": "#variable"
95- },
96- {
97- "include": "#interpolation"
98- },
99- {
100- "include": "#pathname"
101- }
102- ]
103- },
104- {
105- "begin": "(?<=\\))",
106- "end": "(?=;;)",
107- "name": "meta.scope.case-clause-body.shell",
108- "patterns": [
109- {
110- "include": "$self"
111- }
112- ]
113- }
114- ]
115- }
116- ]
117- },
118- "comment": {
119- "begin": "(^[ \\t]+)?(?<!\\S)(?=#)(?!#\\{)",
120- "beginCaptures": {
121- "1": {
122- "name": "punctuation.whitespace.comment.leading.shell"
123- }
124- },
125- "end": "(?!\\G)",
126- "patterns": [
127- {
128- "begin": "^(#!)",
129- "beginCaptures": {
130- "1": {
131- "name": "punctuation.definition.comment.line.shebang.shell"
132- }
133- },
134- "end": "\\n",
135- "name": "comment.line.shebang.shell"
136- },
137- {
138- "begin": "#",
139- "beginCaptures": {
140- "0": {
141- "name": "punctuation.definition.comment.shell"
142- }
143- },
144- "end": "\\n",
145- "name": "comment.line.number-sign.shell"
146- }
147- ]
148- },
149- "compound-command": {
150- "patterns": [
151- {
152- "begin": "(\\[{2})",
153- "captures": {
154- "1": {
155- "name": "punctuation.definition.logical-expression.shell"
156- }
157- },
158- "end": "(\\]{2})",
159- "name": "meta.scope.logical-expression.shell",
160- "patterns": [
161- {
162- "include": "#logical-expression"
163- },
164- {
165- "include": "$self"
166- }
167- ]
168- },
169- {
170- "begin": "(\\({2})",
171- "beginCaptures": {
172- "0": {
173- "name": "punctuation.definition.string.begin.shell"
174- }
175- },
176- "end": "(\\){2})",
177- "endCaptures": {
178- "0": {
179- "name": "punctuation.definition.string.end.shell"
180- }
181- },
182- "name": "string.other.math.shell",
183- "patterns": [
184- {
185- "include": "#math"
186- }
187- ]
188- },
189- {
190- "begin": "(\\()",
191- "captures": {
192- "1": {
193- "name": "punctuation.definition.subshell.shell"
194- }
195- },
196- "end": "(\\))",
197- "name": "meta.scope.subshell.shell",
198- "patterns": [
199- {
200- "include": "$self"
201- }
202- ]
203- },
204- {
205- "begin": "(?<=\\s|^)(\\{)(?=\\s|$)",
206- "captures": {
207- "1": {
208- "name": "punctuation.definition.group.shell"
209- }
210- },
211- "end": "(?<=^|;)\\s*(\\})",
212- "name": "meta.scope.group.shell",
213- "patterns": [
214- {
215- "include": "$self"
216- }
217- ]
218- }
219- ]
220- },
221- "function-definition": {
222- "patterns": [
223- {
224- "begin": "(?<=^|;|&|\\s)(function)\\s+([^\\s<>;'\"\\\\|$&()]+)(?:\\s*(\\(\\)))?",
225- "beginCaptures": {
226- "1": {
227- "name": "storage.type.function.shell"
228- },
229- "2": {
230- "name": "entity.name.function.shell"
231- },
232- "3": {
233- "name": "punctuation.definition.arguments.shell"
234- }
235- },
236- "end": ";|&|$",
237- "endCaptures": {
238- "0": {
239- "name": "punctuation.definition.function.shell"
240- }
241- },
242- "name": "meta.function.shell",
243- "patterns": [
244- {
245- "include": "$self"
246- }
247- ]
248- },
249- {
250- "begin": "(?<=^|;|&|\\s)([^\\s<>;'\"\\\\|$&()]+)\\s*(\\(\\))",
251- "beginCaptures": {
252- "1": {
253- "name": "entity.name.function.shell"
254- },
255- "2": {
256- "name": "punctuation.definition.arguments.shell"
257- }
258- },
259- "end": ";|&|$",
260- "endCaptures": {
261- "0": {
262- "name": "punctuation.definition.function.shell"
263- }
264- },
265- "name": "meta.function.shell",
266- "patterns": [
267- {
268- "include": "$self"
269- }
270- ]
271- }
272- ]
273- },
274- "heredoc": {
275- "patterns": [
276- {
277- "begin": "(<<)-\\s*(\"|'|)(RUBY)\\2",
278- "beginCaptures": {
279- "1": {
280- "name": "keyword.operator.heredoc.shell"
281- },
282- "3": {
283- "name": "keyword.control.heredoc-token.shell"
284- }
285- },
286- "captures": {
287- "0": {
288- "name": "punctuation.definition.string.shell"
289- }
290- },
291- "contentName": "source.ruby.embedded.shell",
292- "end": "^\\t*(RUBY)(?=\\s|;|&|$)",
293- "endCaptures": {
294- "1": {
295- "name": "keyword.control.heredoc-token.shell"
296- }
297- },
298- "name": "string.unquoted.heredoc.no-indent.ruby.shell",
299- "patterns": [
300- {
301- "include": "source.ruby"
302- }
303- ]
304- },
305- {
306- "begin": "(<<)\\s*(\"|'|)(RUBY)\\2",
307- "beginCaptures": {
308- "1": {
309- "name": "keyword.operator.heredoc.shell"
310- },
311- "3": {
312- "name": "keyword.control.heredoc-token.shell"
313- }
314- },
315- "captures": {
316- "0": {
317- "name": "punctuation.definition.string.shell"
318- }
319- },
320- "contentName": "source.ruby.embedded.shell",
321- "end": "^(RUBY)(?=\\s|;|&|$)",
322- "endCaptures": {
323- "1": {
324- "name": "keyword.control.heredoc-token.shell"
325- }
326- },
327- "name": "string.unquoted.heredoc.ruby.shell",
328- "patterns": [
329- {
330- "include": "source.ruby"
331- }
332- ]
333- },
334- {
335- "begin": "(<<)-\\s*(\"|'|)(PYTHON)\\2",
336- "beginCaptures": {
337- "1": {
338- "name": "keyword.operator.heredoc.shell"
339- },
340- "3": {
341- "name": "keyword.control.heredoc-token.shell"
342- }
343- },
344- "captures": {
345- "0": {
346- "name": "punctuation.definition.string.shell"
347- }
348- },
349- "contentName": "source.python.embedded.shell",
350- "end": "^\\t*(PYTHON)(?=\\s|;|&|$)",
351- "endCaptures": {
352- "1": {
353- "name": "keyword.control.heredoc-token.shell"
354- }
355- },
356- "name": "string.unquoted.heredoc.no-indent.python.shell",
357- "patterns": [
358- {
359- "include": "source.python"
360- }
361- ]
362- },
363- {
364- "begin": "(<<)\\s*(\"|'|)(PYTHON)\\2",
365- "beginCaptures": {
366- "1": {
367- "name": "keyword.operator.heredoc.shell"
368- },
369- "3": {
370- "name": "keyword.control.heredoc-token.shell"
371- }
372- },
373- "captures": {
374- "0": {
375- "name": "punctuation.definition.string.shell"
376- }
377- },
378- "contentName": "source.python.embedded.shell",
379- "end": "^(PYTHON)(?=\\s|;|&|$)",
380- "endCaptures": {
381- "1": {
382- "name": "keyword.control.heredoc-token.shell"
383- }
384- },
385- "name": "string.unquoted.heredoc.python.shell",
386- "patterns": [
387- {
388- "include": "source.python"
389- }
390- ]
391- },
392- {
393- "begin": "(<<)-\\s*(\"|'|)(APPLESCRIPT)\\2",
394- "beginCaptures": {
395- "1": {
396- "name": "keyword.operator.heredoc.shell"
397- },
398- "3": {
399- "name": "keyword.control.heredoc-token.shell"
400- }
401- },
402- "captures": {
403- "0": {
404- "name": "punctuation.definition.string.shell"
405- }
406- },
407- "contentName": "source.applescript.embedded.shell",
408- "end": "^\\t*(APPLESCRIPT)(?=\\s|;|&|$)",
409- "endCaptures": {
410- "1": {
411- "name": "keyword.control.heredoc-token.shell"
412- }
413- },
414- "name": "string.unquoted.heredoc.no-indent.applescript.shell",
415- "patterns": [
416- {
417- "include": "source.applescript"
418- }
419- ]
420- },
421- {
422- "begin": "(<<)\\s*(\"|'|)(APPLESCRIPT)\\2",
423- "beginCaptures": {
424- "1": {
425- "name": "keyword.operator.heredoc.shell"
426- },
427- "3": {
428- "name": "keyword.control.heredoc-token.shell"
429- }
430- },
431- "captures": {
432- "0": {
433- "name": "punctuation.definition.string.shell"
434- }
435- },
436- "contentName": "source.applescript.embedded.shell",
437- "end": "^(APPLESCRIPT)(?=\\s|;|&|$)",
438- "endCaptures": {
439- "1": {
440- "name": "keyword.control.heredoc-token.shell"
441- }
442- },
443- "name": "string.unquoted.heredoc.applescript.shell",
444- "patterns": [
445- {
446- "include": "source.applescript"
447- }
448- ]
449- },
450- {
451- "begin": "(<<)-\\s*(\"|'|)(HTML)\\2",
452- "beginCaptures": {
453- "1": {
454- "name": "keyword.operator.heredoc.shell"
455- },
456- "3": {
457- "name": "keyword.control.heredoc-token.shell"
458- }
459- },
460- "captures": {
461- "0": {
462- "name": "punctuation.definition.string.shell"
463- }
464- },
465- "contentName": "text.html.embedded.shell",
466- "end": "^\\t*(HTML)(?=\\s|;|&|$)",
467- "endCaptures": {
468- "1": {
469- "name": "keyword.control.heredoc-token.shell"
470- }
471- },
472- "name": "string.unquoted.heredoc.no-indent.html.shell",
473- "patterns": [
474- {
475- "include": "text.html.basic"
476- }
477- ]
478- },
479- {
480- "begin": "(<<)\\s*(\"|'|)(HTML)\\2",
481- "beginCaptures": {
482- "1": {
483- "name": "keyword.operator.heredoc.shell"
484- },
485- "3": {
486- "name": "keyword.control.heredoc-token.shell"
487- }
488- },
489- "captures": {
490- "0": {
491- "name": "punctuation.definition.string.shell"
492- }
493- },
494- "contentName": "text.html.embedded.shell",
495- "end": "^(HTML)(?=\\s|;|&|$)",
496- "endCaptures": {
497- "1": {
498- "name": "keyword.control.heredoc-token.shell"
499- }
500- },
501- "name": "string.unquoted.heredoc.html.shell",
502- "patterns": [
503- {
504- "include": "text.html.basic"
505- }
506- ]
507- },
508- {
509- "begin": "(<<)-\\s*(\"|'|)(MARKDOWN)\\2",
510- "beginCaptures": {
511- "1": {
512- "name": "keyword.operator.heredoc.shell"
513- },
514- "3": {
515- "name": "keyword.control.heredoc-token.shell"
516- }
517- },
518- "captures": {
519- "0": {
520- "name": "punctuation.definition.string.shell"
521- }
522- },
523- "contentName": "text.html.markdown.embedded.shell",
524- "end": "^\\t*(MARKDOWN)(?=\\s|;|&|$)",
525- "endCaptures": {
526- "1": {
527- "name": "keyword.control.heredoc-token.shell"
528- }
529- },
530- "name": "string.unquoted.heredoc.no-indent.markdown.shell",
531- "patterns": [
532- {
533- "include": "text.html.markdown"
534- }
535- ]
536- },
537- {
538- "begin": "(<<)\\s*(\"|'|)(MARKDOWN)\\2",
539- "beginCaptures": {
540- "1": {
541- "name": "keyword.operator.heredoc.shell"
542- },
543- "3": {
544- "name": "keyword.control.heredoc-token.shell"
545- }
546- },
547- "captures": {
548- "0": {
549- "name": "punctuation.definition.string.shell"
550- }
551- },
552- "contentName": "text.html.markdown.embedded.shell",
553- "end": "^(MARKDOWN)(?=\\s|;|&|$)",
554- "endCaptures": {
555- "1": {
556- "name": "keyword.control.heredoc-token.shell"
557- }
558- },
559- "name": "string.unquoted.heredoc.markdown.shell",
560- "patterns": [
561- {
562- "include": "text.html.markdown"
563- }
564- ]
565- },
566- {
567- "begin": "(<<)-\\s*(\"|'|)(TEXTILE)\\2",
568- "beginCaptures": {
569- "1": {
570- "name": "keyword.operator.heredoc.shell"
571- },
572- "3": {
573- "name": "keyword.control.heredoc-token.shell"
574- }
575- },
576- "captures": {
577- "0": {
578- "name": "punctuation.definition.string.shell"
579- }
580- },
581- "contentName": "text.html.textile.embedded.shell",
582- "end": "^\\t*(TEXTILE)(?=\\s|;|&|$)",
583- "endCaptures": {
584- "1": {
585- "name": "keyword.control.heredoc-token.shell"
586- }
587- },
588- "name": "string.unquoted.heredoc.no-indent.textile.shell",
589- "patterns": [
590- {
591- "include": "text.html.textile"
592- }
593- ]
594- },
595- {
596- "begin": "(<<)\\s*(\"|'|)(TEXTILE)\\2",
597- "beginCaptures": {
598- "1": {
599- "name": "keyword.operator.heredoc.shell"
600- },
601- "3": {
602- "name": "keyword.control.heredoc-token.shell"
603- }
604- },
605- "captures": {
606- "0": {
607- "name": "punctuation.definition.string.shell"
608- }
609- },
610- "contentName": "text.html.textile.embedded.shell",
611- "end": "^(TEXTILE)(?=\\s|;|&|$)",
612- "endCaptures": {
613- "1": {
614- "name": "keyword.control.heredoc-token.shell"
615- }
616- },
617- "name": "string.unquoted.heredoc.textile.shell",
618- "patterns": [
619- {
620- "include": "text.html.textile"
621- }
622- ]
623- },
624- {
625- "begin": "(<<)-\\s*(\"|'|)\\\\?(\\w+)\\2",
626- "beginCaptures": {
627- "1": {
628- "name": "keyword.operator.heredoc.shell"
629- },
630- "3": {
631- "name": "keyword.control.heredoc-token.shell"
632- }
633- },
634- "captures": {
635- "0": {
636- "name": "punctuation.definition.string.shell"
637- }
638- },
639- "end": "^\\t*(\\3)(?=\\s|;|&|$)",
640- "endCaptures": {
641- "1": {
642- "name": "keyword.control.heredoc-token.shell"
643- }
644- },
645- "name": "string.unquoted.heredoc.no-indent.shell"
646- },
647- {
648- "begin": "(<<)\\s*(\"|'|)\\\\?(\\w+)\\2",
649- "beginCaptures": {
650- "1": {
651- "name": "keyword.operator.heredoc.shell"
652- },
653- "3": {
654- "name": "keyword.control.heredoc-token.shell"
655- }
656- },
657- "captures": {
658- "0": {
659- "name": "punctuation.definition.string.shell"
660- }
661- },
662- "end": "^(\\3)(?=\\s|;|&|$)",
663- "endCaptures": {
664- "1": {
665- "name": "keyword.control.heredoc-token.shell"
666- }
667- },
668- "name": "string.unquoted.heredoc.shell"
669- }
670- ]
671- },
672- "herestring": {
673- "patterns": [
674- {
675- "captures": {
676- "1": {
677- "name": "keyword.operator.herestring.shell"
678- },
679- "2": {
680- "name": "string.quoted.single.herestring.shell"
681- },
682- "3": {
683- "name": "punctuation.definition.string.begin.shell"
684- },
685- "4": {
686- "name": "punctuation.definition.string.end.shell"
687- }
688- },
689- "match": "(<<<)\\s*((')[^']*('))",
690- "name": "meta.herestring.shell"
691- },
692- {
693- "captures": {
694- "1": {
695- "name": "keyword.operator.herestring.shell"
696- },
697- "2": {
698- "name": "string.quoted.double.herestring.shell"
699- },
700- "3": {
701- "name": "punctuation.definition.string.begin.shell"
702- },
703- "6": {
704- "name": "punctuation.definition.string.end.shell"
705- }
706- },
707- "match": "(<<<)\\s*((\")(\\\\(\"|\\\\)|[^\"])*(\"))",
708- "name": "meta.herestring.shell"
709- },
710- {
711- "captures": {
712- "1": {
713- "name": "keyword.operator.herestring.shell"
714- },
715- "2": {
716- "name": "string.unquoted.herestring.shell"
717- }
718- },
719- "match": "(<<<)\\s*(([^\\s\\\\]|\\\\.)+)",
720- "name": "meta.herestring.shell"
721- }
722- ]
723- },
724- "interpolation": {
725- "patterns": [
726- {
727- "begin": "\\$\\({2}",
728- "beginCaptures": {
729- "0": {
730- "name": "punctuation.definition.string.begin.shell"
731- }
732- },
733- "end": "\\){2}",
734- "endCaptures": {
735- "0": {
736- "name": "punctuation.definition.string.end.shell"
737- }
738- },
739- "name": "string.other.math.shell",
740- "patterns": [
741- {
742- "include": "#math"
743- }
744- ]
745- },
746- {
747- "begin": "`",
748- "beginCaptures": {
749- "0": {
750- "name": "punctuation.definition.string.begin.shell"
751- }
752- },
753- "end": "`",
754- "endCaptures": {
755- "0": {
756- "name": "punctuation.definition.string.end.shell"
757- }
758- },
759- "name": "string.interpolated.backtick.shell",
760- "patterns": [
761- {
762- "match": "\\\\[`\\\\$]",
763- "name": "constant.character.escape.shell"
764- },
765- {
766- "include": "$self"
767- }
768- ]
769- },
770- {
771- "begin": "\\$\\(",
772- "beginCaptures": {
773- "0": {
774- "name": "punctuation.definition.string.begin.shell"
775- }
776- },
777- "end": "\\)",
778- "endCaptures": {
779- "0": {
780- "name": "punctuation.definition.string.end.shell"
781- }
782- },
783- "name": "string.interpolated.dollar.shell",
784- "patterns": [
785- {
786- "include": "$self"
787- }
788- ]
789- }
790- ]
791- },
792- "keyword": {
793- "patterns": [
794- {
795- "match": "(?<=^|;|&|\\s)(?:if|then|else|elif|fi|for|in|do|done|select|case|continue|esac|while|until|return|coproc)(?=\\s|;|&|$)",
796- "name": "keyword.control.shell"
797- },
798- {
799- "match": "(?<=^|;|&|\\s)(?:export|declare|typeset|local|readonly)(?=\\s|;|&|$)",
800- "name": "storage.modifier.shell"
801- }
802- ]
803- },
804- "list": {
805- "patterns": [
806- {
807- "match": ";|&&|&|\\|\\|",
808- "name": "keyword.operator.list.shell"
809- }
810- ]
811- },
812- "logical-expression": {
813- "patterns": [
814- {
815- "comment": "do we want a special rule for ( expr )?",
816- "match": "=[=~]?|!=?|<|>|&&|\\|\\|",
817- "name": "keyword.operator.logical.shell"
818- },
819- {
820- "match": "(?<!\\S)-(nt|ot|ef|eq|ne|l[te]|g[te]|[a-hknoprstuwxzOGLSN])",
821- "name": "keyword.operator.logical.shell"
822- }
823- ]
824- },
825- "loop": {
826- "patterns": [
827- {
828- "begin": "(?<=^|;|&|\\s)(for)\\s+(?=\\({2})",
829- "captures": {
830- "1": {
831- "name": "keyword.control.shell"
832- }
833- },
834- "end": "(?<=^|;|&|\\s)(done)(?=\\s|;|&|$)",
835- "name": "meta.scope.for-loop.shell",
836- "patterns": [
837- {
838- "include": "$self"
839- }
840- ]
841- },
842- {
843- "begin": "(?<=^|;|&|\\s)(for)\\s+([^\\s\\\\]+)(?=\\s|;|&|$)",
844- "beginCaptures": {
845- "1": {
846- "name": "keyword.control.shell"
847- },
848- "2": {
849- "name": "variable.other.loop.shell"
850- }
851- },
852- "end": "(?<=^|;|&|\\s)(done)(?=\\s|;|&|$)",
853- "endCaptures": {
854- "1": {
855- "name": "keyword.control.shell"
856- }
857- },
858- "name": "meta.scope.for-in-loop.shell",
859- "patterns": [
860- {
861- "include": "$self"
862- }
863- ]
864- },
865- {
866- "begin": "(?<=^|;|&|\\s)(while|until)(?=\\s|;|&|$)",
867- "captures": {
868- "1": {
869- "name": "keyword.control.shell"
870- }
871- },
872- "end": "(?<=^|;|&|\\s)(done)(?=\\s|;|&|$)",
873- "name": "meta.scope.while-loop.shell",
874- "patterns": [
875- {
876- "include": "$self"
877- }
878- ]
879- },
880- {
881- "begin": "(?<=^|;|&|\\s)(select)\\s+([^\\s\\\\]+)(?=\\s|;|&|$)",
882- "beginCaptures": {
883- "1": {
884- "name": "keyword.control.shell"
885- },
886- "2": {
887- "name": "variable.other.loop.shell"
888- }
889- },
890- "end": "(?<=^|;|&|\\s)(done)(?=\\s|;|&|$)",
891- "endCaptures": {
892- "1": {
893- "name": "keyword.control.shell"
894- }
895- },
896- "name": "meta.scope.select-block.shell",
897- "patterns": [
898- {
899- "include": "$self"
900- }
901- ]
902- },
903- {
904- "begin": "(?<=^|;|&|\\s)(case)(?=\\s|;|&|$)",
905- "captures": {
906- "1": {
907- "name": "keyword.control.shell"
908- }
909- },
910- "end": "(?<=^|;|&|\\s)(esac)(?=\\s|;|&|$)",
911- "name": "meta.scope.case-block.shell",
912- "patterns": [
913- {
914- "begin": "(?<=^|;|&|\\s)(?:in)(?=\\s|;|&|$)",
915- "beginCaptures": {
916- "1": {
917- "name": "keyword.control.shell"
918- }
919- },
920- "end": "(?<=^|;|&|\\s)(?=(?:esac)(?:\\s|;|&|$))",
921- "name": "meta.scope.case-body.shell",
922- "patterns": [
923- {
924- "include": "#comment"
925- },
926- {
927- "include": "#case-clause"
928- },
929- {
930- "include": "$self"
931- }
932- ]
933- },
934- {
935- "include": "$self"
936- }
937- ]
938- },
939- {
940- "begin": "(^|(?<=[&;|]))\\s*(if)(?=\\s|;|&|$)",
941- "beginCaptures": {
942- "2": {
943- "name": "keyword.control.shell"
944- }
945- },
946- "comment": "Restrict match to avoid matching in lines like `dd if=/dev/sda1 …`",
947- "end": "(?<=^|;|&|\\s)(fi)(?=\\s|;|&|$)",
948- "endCaptures": {
949- "1": {
950- "name": "keyword.control.shell"
951- }
952- },
953- "name": "meta.scope.if-block.shell",
954- "patterns": [
955- {
956- "include": "$self"
957- }
958- ]
959- }
960- ]
961- },
962- "math": {
963- "patterns": [
964- {
965- "include": "#variable"
966- },
967- {
968- "match": "\\+{1,2}|-{1,2}|!|~|\\*{1,2}|/|%|<[<=]?|>[>=]?|==|!=|\\^|\\|{1,2}|&{1,2}|\\?|\\:|,|=|[*/%+\\-&^|]=|<<=|>>=",
969- "name": "keyword.operator.arithmetic.shell"
970- },
971- {
972- "match": "0[xX]\\h+",
973- "name": "constant.numeric.hex.shell"
974- },
975- {
976- "match": "0\\d+",
977- "name": "constant.numeric.octal.shell"
978- },
979- {
980- "match": "\\d{1,2}#[0-9a-zA-Z@_]+",
981- "name": "constant.numeric.other.shell"
982- },
983- {
984- "match": "\\d+",
985- "name": "constant.numeric.integer.shell"
986- }
987- ]
988- },
989- "pathname": {
990- "patterns": [
991- {
992- "match": "(?<=\\s|:|=|^)~",
993- "name": "keyword.operator.tilde.shell"
994- },
995- {
996- "match": "\\*|\\?",
997- "name": "keyword.operator.glob.shell"
998- },
999- {
1000- "begin": "([?*+@!])(\\()",
1001- "beginCaptures": {
1002- "1": {
1003- "name": "keyword.operator.extglob.shell"
1004- },
1005- "2": {
1006- "name": "punctuation.definition.extglob.shell"
1007- }
1008- },
1009- "end": "(\\))",
1010- "endCaptures": {
1011- "1": {
1012- "name": "punctuation.definition.extglob.shell"
1013- }
1014- },
1015- "name": "meta.structure.extglob.shell",
1016- "patterns": [
1017- {
1018- "include": "$self"
1019- }
1020- ]
1021- }
1022- ]
1023- },
1024- "pipeline": {
1025- "patterns": [
1026- {
1027- "match": "(?<=^|;|&|\\s)(time)(?=\\s|;|&|$)",
1028- "name": "keyword.other.shell"
1029- },
1030- {
1031- "match": "[|!]",
1032- "name": "keyword.operator.pipe.shell"
1033- }
1034- ]
1035- },
1036- "redirection": {
1037- "patterns": [
1038- {
1039- "begin": "[><]\\(",
1040- "beginCaptures": {
1041- "0": {
1042- "name": "punctuation.definition.string.begin.shell"
1043- }
1044- },
1045- "end": "\\)",
1046- "endCaptures": {
1047- "0": {
1048- "name": "punctuation.definition.string.end.shell"
1049- }
1050- },
1051- "name": "string.interpolated.process-substitution.shell",
1052- "patterns": [
1053- {
1054- "include": "$self"
1055- }
1056- ]
1057- },
1058- {
1059- "comment": "valid: &>word >&word >word [n]>&[n] [n]<word [n]>word [n]>>word [n]<&word (last one is duplicate)",
1060- "match": "&>|\\d*>&\\d*|\\d*(>>|>|<)|\\d*<&|\\d*<>",
1061- "name": "keyword.operator.redirect.shell"
1062- }
1063- ]
1064- },
1065- "string": {
1066- "patterns": [
1067- {
1068- "match": "\\\\.",
1069- "name": "constant.character.escape.shell"
1070- },
1071- {
1072- "begin": "'",
1073- "beginCaptures": {
1074- "0": {
1075- "name": "punctuation.definition.string.begin.shell"
1076- }
1077- },
1078- "end": "'",
1079- "endCaptures": {
1080- "0": {
1081- "name": "punctuation.definition.string.end.shell"
1082- }
1083- },
1084- "name": "string.quoted.single.shell"
1085- },
1086- {
1087- "begin": "\\$?\"",
1088- "beginCaptures": {
1089- "0": {
1090- "name": "punctuation.definition.string.begin.shell"
1091- }
1092- },
1093- "end": "\"",
1094- "endCaptures": {
1095- "0": {
1096- "name": "punctuation.definition.string.end.shell"
1097- }
1098- },
1099- "name": "string.quoted.double.shell",
1100- "patterns": [
1101- {
1102- "match": "\\\\[\\$`\"\\\\\\n]",
1103- "name": "constant.character.escape.shell"
1104- },
1105- {
1106- "include": "#variable"
1107- },
1108- {
1109- "include": "#interpolation"
1110- }
1111- ]
1112- },
1113- {
1114- "begin": "\\$'",
1115- "beginCaptures": {
1116- "0": {
1117- "name": "punctuation.definition.string.begin.shell"
1118- }
1119- },
1120- "end": "'",
1121- "endCaptures": {
1122- "0": {
1123- "name": "punctuation.definition.string.end.shell"
1124- }
1125- },
1126- "name": "string.quoted.single.dollar.shell",
1127- "patterns": [
1128- {
1129- "match": "\\\\(a|b|e|f|n|r|t|v|\\\\|')",
1130- "name": "constant.character.escape.ansi-c.shell"
1131- },
1132- {
1133- "match": "\\\\[0-9]{3}",
1134- "name": "constant.character.escape.octal.shell"
1135- },
1136- {
1137- "match": "\\\\x[0-9a-fA-F]{2}",
1138- "name": "constant.character.escape.hex.shell"
1139- },
1140- {
1141- "match": "\\\\c.",
1142- "name": "constant.character.escape.control-char.shell"
1143- }
1144- ]
1145- }
1146- ]
1147- },
1148- "support": {
1149- "patterns": [
1150- {
1151- "match": "(?<=^|;|&|\\s)(?::|\\.)(?=\\s|;|&|$)",
1152- "name": "support.function.builtin.shell"
1153- },
1154- {
1155- "match": "(?<=^|;|&|\\s)(?:alias|bg|bind|break|builtin|caller|cd|command|compgen|complete|dirs|disown|echo|enable|eval|exec|exit|false|fc|fg|getopts|hash|help|history|jobs|kill|let|logout|mapfile|popd|printf|pushd|pwd|read(array)?|readonly|set|shift|shopt|source|suspend|test|times|trap|true|type|ulimit|umask|unalias|unset|wait)(?=\\s|;|&|$)",
1156- "name": "support.function.builtin.shell"
1157- }
1158- ]
1159- },
1160- "variable": {
1161- "patterns": [
1162- {
1163- "captures": {
1164- "1": {
1165- "name": "punctuation.definition.variable.shell"
1166- }
1167- },
1168- "match": "(\\$)[a-zA-Z_][a-zA-Z0-9_]*",
1169- "name": "variable.other.normal.shell"
1170- },
1171- {
1172- "captures": {
1173- "1": {
1174- "name": "punctuation.definition.variable.shell"
1175- }
1176- },
1177- "match": "(\\$)[-*@#?$!0_]",
1178- "name": "variable.other.special.shell"
1179- },
1180- {
1181- "captures": {
1182- "1": {
1183- "name": "punctuation.definition.variable.shell"
1184- }
1185- },
1186- "match": "(\\$)[1-9]",
1187- "name": "variable.other.positional.shell"
1188- },
1189- {
1190- "begin": "\\$\\{",
1191- "captures": {
1192- "0": {
1193- "name": "punctuation.definition.variable.shell"
1194- }
1195- },
1196- "end": "\\}",
1197- "name": "variable.other.bracket.shell",
1198- "patterns": [
1199- {
1200- "match": "!|:[-=?+]?|\\*|@|#{1,2}|%{1,2}|/",
1201- "name": "keyword.operator.expansion.shell"
1202- },
1203- {
1204- "captures": {
1205- "1": {
1206- "name": "punctuation.section.array.shell"
1207- },
1208- "3": {
1209- "name": "punctuation.section.array.shell"
1210- }
1211- },
1212- "match": "(\\[)([^\\]]+)(\\])"
1213- },
1214- {
1215- "include": "#string"
1216- },
1217- {
1218- "include": "#variable"
1219- },
1220- {
1221- "include": "#interpolation"
1222- }
1223- ]
1224- }
1225- ]
1226- }
1227- },
1228- "scopeName": "source.shell",
1229- "uuid": "DDEEA3ED-6B1C-11D9-8B10-000D93589AF6",
1230- "version": "https://github.com/textmate/shellscript.tmbundle/commit/2677fdc83ed9d6a517d5d204e003f49141fc72e4"
1231-}
No newline at the end of the file
2+ "fileTypes": [
3+ "sh",
4+ "bash",
5+ "zsh",
6+ "bashrc",
7+ "bash_profile",
8+ "bash_login",
9+ "profile",
10+ "bash_logout",
11+ ".textmate_init"
12+ ],
13+ "firstLineMatch": "^#!.*\\b(bash|zsh|sh|tcsh)|^#.*-\\*-.*\\bshell-script\\b.*-\\*-",
14+ "keyEquivalent": "^~S",
15+ "name": "Shell Script (Bash)",
16+ "patterns": [
17+ {
18+ "include": "#comment"
19+ },
20+ {
21+ "include": "#pipeline"
22+ },
23+ {
24+ "include": "#list"
25+ },
26+ {
27+ "include": "#compound-command"
28+ },
29+ {
30+ "include": "#loop"
31+ },
32+ {
33+ "include": "#string"
34+ },
35+ {
36+ "include": "#function-definition"
37+ },
38+ {
39+ "include": "#variable"
40+ },
41+ {
42+ "include": "#interpolation"
43+ },
44+ {
45+ "include": "#heredoc"
46+ },
47+ {
48+ "include": "#herestring"
49+ },
50+ {
51+ "include": "#redirection"
52+ },
53+ {
54+ "include": "#pathname"
55+ },
56+ {
57+ "include": "#keyword"
58+ },
59+ {
60+ "include": "#support"
61+ }
62+ ],
63+ "repository": {
64+ "case-clause": {
65+ "patterns": [
66+ {
67+ "begin": "(?=\\S)",
68+ "end": ";;",
69+ "endCaptures": {
70+ "0": {
71+ "name": "punctuation.terminator.case-clause.shell"
72+ }
73+ },
74+ "name": "meta.scope.case-clause.shell",
75+ "patterns": [
76+ {
77+ "begin": "(\\(|(?=\\S))",
78+ "captures": {
79+ "0": {
80+ "name": "punctuation.definition.case-pattern.shell"
81+ }
82+ },
83+ "end": "\\)",
84+ "name": "meta.scope.case-pattern.shell",
85+ "patterns": [
86+ {
87+ "match": "\\|",
88+ "name": "punctuation.separator.pipe-sign.shell"
89+ },
90+ {
91+ "include": "#string"
92+ },
93+ {
94+ "include": "#variable"
95+ },
96+ {
97+ "include": "#interpolation"
98+ },
99+ {
100+ "include": "#pathname"
101+ }
102+ ]
103+ },
104+ {
105+ "begin": "(?<=\\))",
106+ "end": "(?=;;)",
107+ "name": "meta.scope.case-clause-body.shell",
108+ "patterns": [
109+ {
110+ "include": "$self"
111+ }
112+ ]
113+ }
114+ ]
115+ }
116+ ]
117+ },
118+ "comment": {
119+ "begin": "(^[ \\t]+)?(?<!\\S)(?=#)(?!#\\{)",
120+ "beginCaptures": {
121+ "1": {
122+ "name": "punctuation.whitespace.comment.leading.shell"
123+ }
124+ },
125+ "end": "(?!\\G)",
126+ "patterns": [
127+ {
128+ "begin": "^(#!)",
129+ "beginCaptures": {
130+ "1": {
131+ "name": "punctuation.definition.comment.line.shebang.shell"
132+ }
133+ },
134+ "end": "\\n",
135+ "name": "comment.line.shebang.shell"
136+ },
137+ {
138+ "begin": "#",
139+ "beginCaptures": {
140+ "0": {
141+ "name": "punctuation.definition.comment.shell"
142+ }
143+ },
144+ "end": "\\n",
145+ "name": "comment.line.number-sign.shell"
146+ }
147+ ]
148+ },
149+ "compound-command": {
150+ "patterns": [
151+ {
152+ "begin": "(\\[{2})",
153+ "captures": {
154+ "1": {
155+ "name": "punctuation.definition.logical-expression.shell"
156+ }
157+ },
158+ "end": "(\\]{2})",
159+ "name": "meta.scope.logical-expression.shell",
160+ "patterns": [
161+ {
162+ "include": "#logical-expression"
163+ },
164+ {
165+ "include": "$self"
166+ }
167+ ]
168+ },
169+ {
170+ "begin": "(\\({2})",
171+ "beginCaptures": {
172+ "0": {
173+ "name": "punctuation.definition.string.begin.shell"
174+ }
175+ },
176+ "end": "(\\){2})",
177+ "endCaptures": {
178+ "0": {
179+ "name": "punctuation.definition.string.end.shell"
180+ }
181+ },
182+ "name": "string.other.math.shell",
183+ "patterns": [
184+ {
185+ "include": "#math"
186+ }
187+ ]
188+ },
189+ {
190+ "begin": "(\\()",
191+ "captures": {
192+ "1": {
193+ "name": "punctuation.definition.subshell.shell"
194+ }
195+ },
196+ "end": "(\\))",
197+ "name": "meta.scope.subshell.shell",
198+ "patterns": [
199+ {
200+ "include": "$self"
201+ }
202+ ]
203+ },
204+ {
205+ "begin": "(?<=\\s|^)(\\{)(?=\\s|$)",
206+ "captures": {
207+ "1": {
208+ "name": "punctuation.definition.group.shell"
209+ }
210+ },
211+ "end": "(?<=^|;)\\s*(\\})",
212+ "name": "meta.scope.group.shell",
213+ "patterns": [
214+ {
215+ "include": "$self"
216+ }
217+ ]
218+ }
219+ ]
220+ },
221+ "function-definition": {
222+ "patterns": [
223+ {
224+ "begin": "(?<=^|;|&|\\s)(function)\\s+([^\\s<>;'\"\\\\|$&()]+)(?:\\s*(\\(\\)))?",
225+ "beginCaptures": {
226+ "1": {
227+ "name": "storage.type.function.shell"
228+ },
229+ "2": {
230+ "name": "entity.name.function.shell"
231+ },
232+ "3": {
233+ "name": "punctuation.definition.arguments.shell"
234+ }
235+ },
236+ "end": ";|&|$",
237+ "endCaptures": {
238+ "0": {
239+ "name": "punctuation.definition.function.shell"
240+ }
241+ },
242+ "name": "meta.function.shell",
243+ "patterns": [
244+ {
245+ "include": "$self"
246+ }
247+ ]
248+ },
249+ {
250+ "begin": "(?<=^|;|&|\\s)([^\\s<>;'\"\\\\|$&()]+)\\s*(\\(\\))",
251+ "beginCaptures": {
252+ "1": {
253+ "name": "entity.name.function.shell"
254+ },
255+ "2": {
256+ "name": "punctuation.definition.arguments.shell"
257+ }
258+ },
259+ "end": ";|&|$",
260+ "endCaptures": {
261+ "0": {
262+ "name": "punctuation.definition.function.shell"
263+ }
264+ },
265+ "name": "meta.function.shell",
266+ "patterns": [
267+ {
268+ "include": "$self"
269+ }
270+ ]
271+ }
272+ ]
273+ },
274+ "heredoc": {
275+ "patterns": [
276+ {
277+ "begin": "(<<)-\\s*(\"|'|)(RUBY)\\2",
278+ "beginCaptures": {
279+ "1": {
280+ "name": "keyword.operator.heredoc.shell"
281+ },
282+ "3": {
283+ "name": "keyword.control.heredoc-token.shell"
284+ }
285+ },
286+ "captures": {
287+ "0": {
288+ "name": "punctuation.definition.string.shell"
289+ }
290+ },
291+ "contentName": "source.ruby.embedded.shell",
292+ "end": "^\\t*(RUBY)(?=\\s|;|&|$)",
293+ "endCaptures": {
294+ "1": {
295+ "name": "keyword.control.heredoc-token.shell"
296+ }
297+ },
298+ "name": "string.unquoted.heredoc.no-indent.ruby.shell",
299+ "patterns": [
300+ {
301+ "include": "source.ruby"
302+ }
303+ ]
304+ },
305+ {
306+ "begin": "(<<)\\s*(\"|'|)(RUBY)\\2",
307+ "beginCaptures": {
308+ "1": {
309+ "name": "keyword.operator.heredoc.shell"
310+ },
311+ "3": {
312+ "name": "keyword.control.heredoc-token.shell"
313+ }
314+ },
315+ "captures": {
316+ "0": {
317+ "name": "punctuation.definition.string.shell"
318+ }
319+ },
320+ "contentName": "source.ruby.embedded.shell",
321+ "end": "^(RUBY)(?=\\s|;|&|$)",
322+ "endCaptures": {
323+ "1": {
324+ "name": "keyword.control.heredoc-token.shell"
325+ }
326+ },
327+ "name": "string.unquoted.heredoc.ruby.shell",
328+ "patterns": [
329+ {
330+ "include": "source.ruby"
331+ }
332+ ]
333+ },
334+ {
335+ "begin": "(<<)-\\s*(\"|'|)(PYTHON)\\2",
336+ "beginCaptures": {
337+ "1": {
338+ "name": "keyword.operator.heredoc.shell"
339+ },
340+ "3": {
341+ "name": "keyword.control.heredoc-token.shell"
342+ }
343+ },
344+ "captures": {
345+ "0": {
346+ "name": "punctuation.definition.string.shell"
347+ }
348+ },
349+ "contentName": "source.python.embedded.shell",
350+ "end": "^\\t*(PYTHON)(?=\\s|;|&|$)",
351+ "endCaptures": {
352+ "1": {
353+ "name": "keyword.control.heredoc-token.shell"
354+ }
355+ },
356+ "name": "string.unquoted.heredoc.no-indent.python.shell",
357+ "patterns": [
358+ {
359+ "include": "source.python"
360+ }
361+ ]
362+ },
363+ {
364+ "begin": "(<<)\\s*(\"|'|)(PYTHON)\\2",
365+ "beginCaptures": {
366+ "1": {
367+ "name": "keyword.operator.heredoc.shell"
368+ },
369+ "3": {
370+ "name": "keyword.control.heredoc-token.shell"
371+ }
372+ },
373+ "captures": {
374+ "0": {
375+ "name": "punctuation.definition.string.shell"
376+ }
377+ },
378+ "contentName": "source.python.embedded.shell",
379+ "end": "^(PYTHON)(?=\\s|;|&|$)",
380+ "endCaptures": {
381+ "1": {
382+ "name": "keyword.control.heredoc-token.shell"
383+ }
384+ },
385+ "name": "string.unquoted.heredoc.python.shell",
386+ "patterns": [
387+ {
388+ "include": "source.python"
389+ }
390+ ]
391+ },
392+ {
393+ "begin": "(<<)-\\s*(\"|'|)(APPLESCRIPT)\\2",
394+ "beginCaptures": {
395+ "1": {
396+ "name": "keyword.operator.heredoc.shell"
397+ },
398+ "3": {
399+ "name": "keyword.control.heredoc-token.shell"
400+ }
401+ },
402+ "captures": {
403+ "0": {
404+ "name": "punctuation.definition.string.shell"
405+ }
406+ },
407+ "contentName": "source.applescript.embedded.shell",
408+ "end": "^\\t*(APPLESCRIPT)(?=\\s|;|&|$)",
409+ "endCaptures": {
410+ "1": {
411+ "name": "keyword.control.heredoc-token.shell"
412+ }
413+ },
414+ "name": "string.unquoted.heredoc.no-indent.applescript.shell",
415+ "patterns": [
416+ {
417+ "include": "source.applescript"
418+ }
419+ ]
420+ },
421+ {
422+ "begin": "(<<)\\s*(\"|'|)(APPLESCRIPT)\\2",
423+ "beginCaptures": {
424+ "1": {
425+ "name": "keyword.operator.heredoc.shell"
426+ },
427+ "3": {
428+ "name": "keyword.control.heredoc-token.shell"
429+ }
430+ },
431+ "captures": {
432+ "0": {
433+ "name": "punctuation.definition.string.shell"
434+ }
435+ },
436+ "contentName": "source.applescript.embedded.shell",
437+ "end": "^(APPLESCRIPT)(?=\\s|;|&|$)",
438+ "endCaptures": {
439+ "1": {
440+ "name": "keyword.control.heredoc-token.shell"
441+ }
442+ },
443+ "name": "string.unquoted.heredoc.applescript.shell",
444+ "patterns": [
445+ {
446+ "include": "source.applescript"
447+ }
448+ ]
449+ },
450+ {
451+ "begin": "(<<)-\\s*(\"|'|)(HTML)\\2",
452+ "beginCaptures": {
453+ "1": {
454+ "name": "keyword.operator.heredoc.shell"
455+ },
456+ "3": {
457+ "name": "keyword.control.heredoc-token.shell"
458+ }
459+ },
460+ "captures": {
461+ "0": {
462+ "name": "punctuation.definition.string.shell"
463+ }
464+ },
465+ "contentName": "text.html.embedded.shell",
466+ "end": "^\\t*(HTML)(?=\\s|;|&|$)",
467+ "endCaptures": {
468+ "1": {
469+ "name": "keyword.control.heredoc-token.shell"
470+ }
471+ },
472+ "name": "string.unquoted.heredoc.no-indent.html.shell",
473+ "patterns": [
474+ {
475+ "include": "text.html.basic"
476+ }
477+ ]
478+ },
479+ {
480+ "begin": "(<<)\\s*(\"|'|)(HTML)\\2",
481+ "beginCaptures": {
482+ "1": {
483+ "name": "keyword.operator.heredoc.shell"
484+ },
485+ "3": {
486+ "name": "keyword.control.heredoc-token.shell"
487+ }
488+ },
489+ "captures": {
490+ "0": {
491+ "name": "punctuation.definition.string.shell"
492+ }
493+ },
494+ "contentName": "text.html.embedded.shell",
495+ "end": "^(HTML)(?=\\s|;|&|$)",
496+ "endCaptures": {
497+ "1": {
498+ "name": "keyword.control.heredoc-token.shell"
499+ }
500+ },
501+ "name": "string.unquoted.heredoc.html.shell",
502+ "patterns": [
503+ {
504+ "include": "text.html.basic"
505+ }
506+ ]
507+ },
508+ {
509+ "begin": "(<<)-\\s*(\"|'|)(MARKDOWN)\\2",
510+ "beginCaptures": {
511+ "1": {
512+ "name": "keyword.operator.heredoc.shell"
513+ },
514+ "3": {
515+ "name": "keyword.control.heredoc-token.shell"
516+ }
517+ },
518+ "captures": {
519+ "0": {
520+ "name": "punctuation.definition.string.shell"
521+ }
522+ },
523+ "contentName": "text.html.markdown.embedded.shell",
524+ "end": "^\\t*(MARKDOWN)(?=\\s|;|&|$)",
525+ "endCaptures": {
526+ "1": {
527+ "name": "keyword.control.heredoc-token.shell"
528+ }
529+ },
530+ "name": "string.unquoted.heredoc.no-indent.markdown.shell",
531+ "patterns": [
532+ {
533+ "include": "text.html.markdown"
534+ }
535+ ]
536+ },
537+ {
538+ "begin": "(<<)\\s*(\"|'|)(MARKDOWN)\\2",
539+ "beginCaptures": {
540+ "1": {
541+ "name": "keyword.operator.heredoc.shell"
542+ },
543+ "3": {
544+ "name": "keyword.control.heredoc-token.shell"
545+ }
546+ },
547+ "captures": {
548+ "0": {
549+ "name": "punctuation.definition.string.shell"
550+ }
551+ },
552+ "contentName": "text.html.markdown.embedded.shell",
553+ "end": "^(MARKDOWN)(?=\\s|;|&|$)",
554+ "endCaptures": {
555+ "1": {
556+ "name": "keyword.control.heredoc-token.shell"
557+ }
558+ },
559+ "name": "string.unquoted.heredoc.markdown.shell",
560+ "patterns": [
561+ {
562+ "include": "text.html.markdown"
563+ }
564+ ]
565+ },
566+ {
567+ "begin": "(<<)-\\s*(\"|'|)(TEXTILE)\\2",
568+ "beginCaptures": {
569+ "1": {
570+ "name": "keyword.operator.heredoc.shell"
571+ },
572+ "3": {
573+ "name": "keyword.control.heredoc-token.shell"
574+ }
575+ },
576+ "captures": {
577+ "0": {
578+ "name": "punctuation.definition.string.shell"
579+ }
580+ },
581+ "contentName": "text.html.textile.embedded.shell",
582+ "end": "^\\t*(TEXTILE)(?=\\s|;|&|$)",
583+ "endCaptures": {
584+ "1": {
585+ "name": "keyword.control.heredoc-token.shell"
586+ }
587+ },
588+ "name": "string.unquoted.heredoc.no-indent.textile.shell",
589+ "patterns": [
590+ {
591+ "include": "text.html.textile"
592+ }
593+ ]
594+ },
595+ {
596+ "begin": "(<<)\\s*(\"|'|)(TEXTILE)\\2",
597+ "beginCaptures": {
598+ "1": {
599+ "name": "keyword.operator.heredoc.shell"
600+ },
601+ "3": {
602+ "name": "keyword.control.heredoc-token.shell"
603+ }
604+ },
605+ "captures": {
606+ "0": {
607+ "name": "punctuation.definition.string.shell"
608+ }
609+ },
610+ "contentName": "text.html.textile.embedded.shell",
611+ "end": "^(TEXTILE)(?=\\s|;|&|$)",
612+ "endCaptures": {
613+ "1": {
614+ "name": "keyword.control.heredoc-token.shell"
615+ }
616+ },
617+ "name": "string.unquoted.heredoc.textile.shell",
618+ "patterns": [
619+ {
620+ "include": "text.html.textile"
621+ }
622+ ]
623+ },
624+ {
625+ "begin": "(<<)-\\s*(\"|'|)\\\\?(\\w+)\\2",
626+ "beginCaptures": {
627+ "1": {
628+ "name": "keyword.operator.heredoc.shell"
629+ },
630+ "3": {
631+ "name": "keyword.control.heredoc-token.shell"
632+ }
633+ },
634+ "captures": {
635+ "0": {
636+ "name": "punctuation.definition.string.shell"
637+ }
638+ },
639+ "end": "^\\t*(\\3)(?=\\s|;|&|$)",
640+ "endCaptures": {
641+ "1": {
642+ "name": "keyword.control.heredoc-token.shell"
643+ }
644+ },
645+ "name": "string.unquoted.heredoc.no-indent.shell"
646+ },
647+ {
648+ "begin": "(<<)\\s*(\"|'|)\\\\?(\\w+)\\2",
649+ "beginCaptures": {
650+ "1": {
651+ "name": "keyword.operator.heredoc.shell"
652+ },
653+ "3": {
654+ "name": "keyword.control.heredoc-token.shell"
655+ }
656+ },
657+ "captures": {
658+ "0": {
659+ "name": "punctuation.definition.string.shell"
660+ }
661+ },
662+ "end": "^(\\3)(?=\\s|;|&|$)",
663+ "endCaptures": {
664+ "1": {
665+ "name": "keyword.control.heredoc-token.shell"
666+ }
667+ },
668+ "name": "string.unquoted.heredoc.shell"
669+ }
670+ ]
671+ },
672+ "herestring": {
673+ "patterns": [
674+ {
675+ "captures": {
676+ "1": {
677+ "name": "keyword.operator.herestring.shell"
678+ },
679+ "2": {
680+ "name": "string.quoted.single.herestring.shell"
681+ },
682+ "3": {
683+ "name": "punctuation.definition.string.begin.shell"
684+ },
685+ "4": {
686+ "name": "punctuation.definition.string.end.shell"
687+ }
688+ },
689+ "match": "(<<<)\\s*((')[^']*('))",
690+ "name": "meta.herestring.shell"
691+ },
692+ {
693+ "captures": {
694+ "1": {
695+ "name": "keyword.operator.herestring.shell"
696+ },
697+ "2": {
698+ "name": "string.quoted.double.herestring.shell"
699+ },
700+ "3": {
701+ "name": "punctuation.definition.string.begin.shell"
702+ },
703+ "6": {
704+ "name": "punctuation.definition.string.end.shell"
705+ }
706+ },
707+ "match": "(<<<)\\s*((\")(\\\\(\"|\\\\)|[^\"])*(\"))",
708+ "name": "meta.herestring.shell"
709+ },
710+ {
711+ "captures": {
712+ "1": {
713+ "name": "keyword.operator.herestring.shell"
714+ },
715+ "2": {
716+ "name": "string.unquoted.herestring.shell"
717+ }
718+ },
719+ "match": "(<<<)\\s*(([^\\s\\\\]|\\\\.)+)",
720+ "name": "meta.herestring.shell"
721+ }
722+ ]
723+ },
724+ "interpolation": {
725+ "patterns": [
726+ {
727+ "begin": "\\$\\({2}",
728+ "beginCaptures": {
729+ "0": {
730+ "name": "punctuation.definition.string.begin.shell"
731+ }
732+ },
733+ "end": "\\){2}",
734+ "endCaptures": {
735+ "0": {
736+ "name": "punctuation.definition.string.end.shell"
737+ }
738+ },
739+ "name": "string.other.math.shell",
740+ "patterns": [
741+ {
742+ "include": "#math"
743+ }
744+ ]
745+ },
746+ {
747+ "begin": "`",
748+ "beginCaptures": {
749+ "0": {
750+ "name": "punctuation.definition.string.begin.shell"
751+ }
752+ },
753+ "end": "`",
754+ "endCaptures": {
755+ "0": {
756+ "name": "punctuation.definition.string.end.shell"
757+ }
758+ },
759+ "name": "string.interpolated.backtick.shell",
760+ "patterns": [
761+ {
762+ "match": "\\\\[`\\\\$]",
763+ "name": "constant.character.escape.shell"
764+ },
765+ {
766+ "include": "$self"
767+ }
768+ ]
769+ },
770+ {
771+ "begin": "\\$\\(",
772+ "beginCaptures": {
773+ "0": {
774+ "name": "punctuation.definition.string.begin.shell"
775+ }
776+ },
777+ "end": "\\)",
778+ "endCaptures": {
779+ "0": {
780+ "name": "punctuation.definition.string.end.shell"
781+ }
782+ },
783+ "name": "string.interpolated.dollar.shell",
784+ "patterns": [
785+ {
786+ "include": "$self"
787+ }
788+ ]
789+ }
790+ ]
791+ },
792+ "keyword": {
793+ "patterns": [
794+ {
795+ "match": "(?<=^|;|&|\\s)(?:if|then|else|elif|fi|for|in|do|done|select|case|continue|esac|while|until|return|coproc)(?=\\s|;|&|$)",
796+ "name": "keyword.control.shell"
797+ },
798+ {
799+ "match": "(?<=^|;|&|\\s)(?:export|declare|typeset|local|readonly)(?=\\s|;|&|$)",
800+ "name": "storage.modifier.shell"
801+ }
802+ ]
803+ },
804+ "list": {
805+ "patterns": [
806+ {
807+ "match": ";|&&|&|\\|\\|",
808+ "name": "keyword.operator.list.shell"
809+ }
810+ ]
811+ },
812+ "logical-expression": {
813+ "patterns": [
814+ {
815+ "comment": "do we want a special rule for ( expr )?",
816+ "match": "=[=~]?|!=?|<|>|&&|\\|\\|",
817+ "name": "keyword.operator.logical.shell"
818+ },
819+ {
820+ "match": "(?<!\\S)-(nt|ot|ef|eq|ne|l[te]|g[te]|[a-hknoprstuwxzOGLSN])",
821+ "name": "keyword.operator.logical.shell"
822+ }
823+ ]
824+ },
825+ "loop": {
826+ "patterns": [
827+ {
828+ "begin": "(?<=^|;|&|\\s)(for)\\s+(?=\\({2})",
829+ "captures": {
830+ "1": {
831+ "name": "keyword.control.shell"
832+ }
833+ },
834+ "end": "(?<=^|;|&|\\s)(done)(?=\\s|;|&|$)",
835+ "name": "meta.scope.for-loop.shell",
836+ "patterns": [
837+ {
838+ "include": "$self"
839+ }
840+ ]
841+ },
842+ {
843+ "begin": "(?<=^|;|&|\\s)(for)\\s+([^\\s\\\\]+)(?=\\s|;|&|$)",
844+ "beginCaptures": {
845+ "1": {
846+ "name": "keyword.control.shell"
847+ },
848+ "2": {
849+ "name": "variable.other.loop.shell"
850+ }
851+ },
852+ "end": "(?<=^|;|&|\\s)(done)(?=\\s|;|&|$)",
853+ "endCaptures": {
854+ "1": {
855+ "name": "keyword.control.shell"
856+ }
857+ },
858+ "name": "meta.scope.for-in-loop.shell",
859+ "patterns": [
860+ {
861+ "include": "$self"
862+ }
863+ ]
864+ },
865+ {
866+ "begin": "(?<=^|;|&|\\s)(while|until)(?=\\s|;|&|$)",
867+ "captures": {
868+ "1": {
869+ "name": "keyword.control.shell"
870+ }
871+ },
872+ "end": "(?<=^|;|&|\\s)(done)(?=\\s|;|&|$)",
873+ "name": "meta.scope.while-loop.shell",
874+ "patterns": [
875+ {
876+ "include": "$self"
877+ }
878+ ]
879+ },
880+ {
881+ "begin": "(?<=^|;|&|\\s)(select)\\s+([^\\s\\\\]+)(?=\\s|;|&|$)",
882+ "beginCaptures": {
883+ "1": {
884+ "name": "keyword.control.shell"
885+ },
886+ "2": {
887+ "name": "variable.other.loop.shell"
888+ }
889+ },
890+ "end": "(?<=^|;|&|\\s)(done)(?=\\s|;|&|$)",
891+ "endCaptures": {
892+ "1": {
893+ "name": "keyword.control.shell"
894+ }
895+ },
896+ "name": "meta.scope.select-block.shell",
897+ "patterns": [
898+ {
899+ "include": "$self"
900+ }
901+ ]
902+ },
903+ {
904+ "begin": "(?<=^|;|&|\\s)(case)(?=\\s|;|&|$)",
905+ "captures": {
906+ "1": {
907+ "name": "keyword.control.shell"
908+ }
909+ },
910+ "end": "(?<=^|;|&|\\s)(esac)(?=\\s|;|&|$)",
911+ "name": "meta.scope.case-block.shell",
912+ "patterns": [
913+ {
914+ "begin": "(?<=^|;|&|\\s)(?:in)(?=\\s|;|&|$)",
915+ "beginCaptures": {
916+ "1": {
917+ "name": "keyword.control.shell"
918+ }
919+ },
920+ "end": "(?<=^|;|&|\\s)(?=(?:esac)(?:\\s|;|&|$))",
921+ "name": "meta.scope.case-body.shell",
922+ "patterns": [
923+ {
924+ "include": "#comment"
925+ },
926+ {
927+ "include": "#case-clause"
928+ },
929+ {
930+ "include": "$self"
931+ }
932+ ]
933+ },
934+ {
935+ "include": "$self"
936+ }
937+ ]
938+ },
939+ {
940+ "begin": "(^|(?<=[&;|]))\\s*(if)(?=\\s|;|&|$)",
941+ "beginCaptures": {
942+ "2": {
943+ "name": "keyword.control.shell"
944+ }
945+ },
946+ "comment": "Restrict match to avoid matching in lines like `dd if=/dev/sda1 …`",
947+ "end": "(?<=^|;|&|\\s)(fi)(?=\\s|;|&|$)",
948+ "endCaptures": {
949+ "1": {
950+ "name": "keyword.control.shell"
951+ }
952+ },
953+ "name": "meta.scope.if-block.shell",
954+ "patterns": [
955+ {
956+ "include": "$self"
957+ }
958+ ]
959+ }
960+ ]
961+ },
962+ "math": {
963+ "patterns": [
964+ {
965+ "include": "#variable"
966+ },
967+ {
968+ "match": "\\+{1,2}|-{1,2}|!|~|\\*{1,2}|/|%|<[<=]?|>[>=]?|==|!=|\\^|\\|{1,2}|&{1,2}|\\?|\\:|,|=|[*/%+\\-&^|]=|<<=|>>=",
969+ "name": "keyword.operator.arithmetic.shell"
970+ },
971+ {
972+ "match": "0[xX]\\h+",
973+ "name": "constant.numeric.hex.shell"
974+ },
975+ {
976+ "match": "0\\d+",
977+ "name": "constant.numeric.octal.shell"
978+ },
979+ {
980+ "match": "\\d{1,2}#[0-9a-zA-Z@_]+",
981+ "name": "constant.numeric.other.shell"
982+ },
983+ {
984+ "match": "\\d+",
985+ "name": "constant.numeric.integer.shell"
986+ }
987+ ]
988+ },
989+ "pathname": {
990+ "patterns": [
991+ {
992+ "match": "(?<=\\s|:|=|^)~",
993+ "name": "keyword.operator.tilde.shell"
994+ },
995+ {
996+ "match": "\\*|\\?",
997+ "name": "keyword.operator.glob.shell"
998+ },
999+ {
1000+ "begin": "([?*+@!])(\\()",
1001+ "beginCaptures": {
1002+ "1": {
1003+ "name": "keyword.operator.extglob.shell"
1004+ },
1005+ "2": {
1006+ "name": "punctuation.definition.extglob.shell"
1007+ }
1008+ },
1009+ "end": "(\\))",
1010+ "endCaptures": {
1011+ "1": {
1012+ "name": "punctuation.definition.extglob.shell"
1013+ }
1014+ },
1015+ "name": "meta.structure.extglob.shell",
1016+ "patterns": [
1017+ {
1018+ "include": "$self"
1019+ }
1020+ ]
1021+ }
1022+ ]
1023+ },
1024+ "pipeline": {
1025+ "patterns": [
1026+ {
1027+ "match": "(?<=^|;|&|\\s)(time)(?=\\s|;|&|$)",
1028+ "name": "keyword.other.shell"
1029+ },
1030+ {
1031+ "match": "[|!]",
1032+ "name": "keyword.operator.pipe.shell"
1033+ }
1034+ ]
1035+ },
1036+ "redirection": {
1037+ "patterns": [
1038+ {
1039+ "begin": "[><]\\(",
1040+ "beginCaptures": {
1041+ "0": {
1042+ "name": "punctuation.definition.string.begin.shell"
1043+ }
1044+ },
1045+ "end": "\\)",
1046+ "endCaptures": {
1047+ "0": {
1048+ "name": "punctuation.definition.string.end.shell"
1049+ }
1050+ },
1051+ "name": "string.interpolated.process-substitution.shell",
1052+ "patterns": [
1053+ {
1054+ "include": "$self"
1055+ }
1056+ ]
1057+ },
1058+ {
1059+ "comment": "valid: &>word >&word >word [n]>&[n] [n]<word [n]>word [n]>>word [n]<&word (last one is duplicate)",
1060+ "match": "&>|\\d*>&\\d*|\\d*(>>|>|<)|\\d*<&|\\d*<>",
1061+ "name": "keyword.operator.redirect.shell"
1062+ }
1063+ ]
1064+ },
1065+ "string": {
1066+ "patterns": [
1067+ {
1068+ "match": "\\\\.",
1069+ "name": "constant.character.escape.shell"
1070+ },
1071+ {
1072+ "begin": "'",
1073+ "beginCaptures": {
1074+ "0": {
1075+ "name": "punctuation.definition.string.begin.shell"
1076+ }
1077+ },
1078+ "end": "'",
1079+ "endCaptures": {
1080+ "0": {
1081+ "name": "punctuation.definition.string.end.shell"
1082+ }
1083+ },
1084+ "name": "string.quoted.single.shell"
1085+ },
1086+ {
1087+ "begin": "\\$?\"",
1088+ "beginCaptures": {
1089+ "0": {
1090+ "name": "punctuation.definition.string.begin.shell"
1091+ }
1092+ },
1093+ "end": "\"",
1094+ "endCaptures": {
1095+ "0": {
1096+ "name": "punctuation.definition.string.end.shell"
1097+ }
1098+ },
1099+ "name": "string.quoted.double.shell",
1100+ "patterns": [
1101+ {
1102+ "match": "\\\\[\\$`\"\\\\\\n]",
1103+ "name": "constant.character.escape.shell"
1104+ },
1105+ {
1106+ "include": "#variable"
1107+ },
1108+ {
1109+ "include": "#interpolation"
1110+ }
1111+ ]
1112+ },
1113+ {
1114+ "begin": "\\$'",
1115+ "beginCaptures": {
1116+ "0": {
1117+ "name": "punctuation.definition.string.begin.shell"
1118+ }
1119+ },
1120+ "end": "'",
1121+ "endCaptures": {
1122+ "0": {
1123+ "name": "punctuation.definition.string.end.shell"
1124+ }
1125+ },
1126+ "name": "string.quoted.single.dollar.shell",
1127+ "patterns": [
1128+ {
1129+ "match": "\\\\(a|b|e|f|n|r|t|v|\\\\|')",
1130+ "name": "constant.character.escape.ansi-c.shell"
1131+ },
1132+ {
1133+ "match": "\\\\[0-9]{3}",
1134+ "name": "constant.character.escape.octal.shell"
1135+ },
1136+ {
1137+ "match": "\\\\x[0-9a-fA-F]{2}",
1138+ "name": "constant.character.escape.hex.shell"
1139+ },
1140+ {
1141+ "match": "\\\\c.",
1142+ "name": "constant.character.escape.control-char.shell"
1143+ }
1144+ ]
1145+ }
1146+ ]
1147+ },
1148+ "support": {
1149+ "patterns": [
1150+ {
1151+ "match": "(?<=^|;|&|\\s)(?::|\\.)(?=\\s|;|&|$)",
1152+ "name": "support.function.builtin.shell"
1153+ },
1154+ {
1155+ "match": "(?<=^|;|&|\\s)(?:alias|bg|bind|break|builtin|caller|cd|command|compgen|complete|dirs|disown|echo|enable|eval|exec|exit|false|fc|fg|getopts|hash|help|history|jobs|kill|let|logout|mapfile|popd|printf|pushd|pwd|read(array)?|readonly|set|shift|shopt|source|suspend|test|times|trap|true|type|ulimit|umask|unalias|unset|wait)(?=\\s|;|&|$)",
1156+ "name": "support.function.builtin.shell"
1157+ }
1158+ ]
1159+ },
1160+ "variable": {
1161+ "patterns": [
1162+ {
1163+ "captures": {
1164+ "1": {
1165+ "name": "punctuation.definition.variable.shell"
1166+ }
1167+ },
1168+ "match": "(\\$)[a-zA-Z_][a-zA-Z0-9_]*",
1169+ "name": "variable.other.normal.shell"
1170+ },
1171+ {
1172+ "captures": {
1173+ "1": {
1174+ "name": "punctuation.definition.variable.shell"
1175+ }
1176+ },
1177+ "match": "(\\$)[-*@#?$!0_]",
1178+ "name": "variable.other.special.shell"
1179+ },
1180+ {
1181+ "captures": {
1182+ "1": {
1183+ "name": "punctuation.definition.variable.shell"
1184+ }
1185+ },
1186+ "match": "(\\$)[1-9]",
1187+ "name": "variable.other.positional.shell"
1188+ },
1189+ {
1190+ "begin": "\\$\\{",
1191+ "captures": {
1192+ "0": {
1193+ "name": "punctuation.definition.variable.shell"
1194+ }
1195+ },
1196+ "end": "\\}",
1197+ "name": "variable.other.bracket.shell",
1198+ "patterns": [
1199+ {
1200+ "match": "!|:[-=?+]?|\\*|@|#{1,2}|%{1,2}|/",
1201+ "name": "keyword.operator.expansion.shell"
1202+ },
1203+ {
1204+ "captures": {
1205+ "1": {
1206+ "name": "punctuation.section.array.shell"
1207+ },
1208+ "3": {
1209+ "name": "punctuation.section.array.shell"
1210+ }
1211+ },
1212+ "match": "(\\[)([^\\]]+)(\\])"
1213+ },
1214+ {
1215+ "include": "#string"
1216+ },
1217+ {
1218+ "include": "#variable"
1219+ },
1220+ {
1221+ "include": "#interpolation"
1222+ }
1223+ ]
1224+ }
1225+ ]
1226+ }
1227+ },
1228+ "scopeName": "source.shell",
1229+ "uuid": "DDEEA3ED-6B1C-11D9-8B10-000D93589AF6",
1230+ "version": "https://github.com/textmate/shellscript.tmbundle/commit/2677fdc83ed9d6a517d5d204e003f49141fc72e4"
1231+}
modified extensions/vscode/textmate-syntaxes/TypeScript.tmLanguage.json +3300 −3302

The diff of this file is cut short. View the file.

@@ -1,3303 +1,1698 @@
11 {
2- "name": "TypeScript",
3- "scopeName": "source.ts",
4- "fileTypes": [
5- "ts"
6- ],
7- "uuid": "ef98eb90-bf9b-11e4-bb52-0800200c9a66",
8- "patterns": [
9- {
10- "include": "#directives"
11- },
12- {
13- "include": "#statements"
14- },
15- {
16- "name": "comment.line.shebang.ts",
17- "match": "\\A(#!).*(?=$)",
18- "captures": {
19- "1": {
20- "name": "punctuation.definition.comment.ts"
21- }
22- }
23- }
24- ],
25- "repository": {
26- "statements": {
27- "patterns": [
28- {
29- "include": "#string"
30- },
31- {
32- "include": "#template"
33- },
34- {
35- "include": "#comment"
36- },
37- {
38- "include": "#literal"
39- },
40- {
41- "include": "#declaration"
42- },
43- {
44- "include": "#switch-statement"
45- },
46- {
47- "include": "#for-loop"
48- },
49- {
50- "include": "#after-operator-block"
51- },
52- {
53- "include": "#decl-block"
54- },
55- {
56- "include": "#control-statement"
57- },
58- {
59- "include": "#expression"
60- },
61- {
62- "include": "#punctuation-semicolon"
63- }
64- ]
65- },
66- "var-expr": {
67- "name": "meta.var.expr.ts",
68- "begin": "(?<!\\.|\\$)(?:(\\bexport)\\s+)?\\b(var|let|const(?!\\s+enum\\b))\\b(?!\\$)",
69- "beginCaptures": {
70- "1": {
71- "name": "keyword.control.export.ts"
72- },
73- "2": {
74- "name": "storage.type.ts"
75- }
76- },
77- "end": "(?=$|;|}|(\\s+(of|in)\\s+))",
78- "patterns": [
79- {
80- "include": "#destructuring-variable"
81- },
82- {
83- "include": "#var-single-variable"
84- },
85- {
86- "include": "#variable-initializer"
87- },
88- {
89- "include": "#comment"
90- },
91- {
92- "include": "#punctuation-comma"
93- }
94- ]
95- },
96- "var-single-variable": {
97- "patterns": [
98- {
99- "name": "meta.var-single-variable.expr.ts",
100- "begin": "(?x)([_$[:alpha:]][_$[:alnum:]]*)(?=\\s* (=\\s*( (async\\s+) | (function\\s*[(<]) | (function\\s+) | ([_$[:alpha:]][_$[:alnum:]]*\\s*=>) | ((<([^<>]|\\<[^<>]+\\>)+>\\s*)?\\(([^()]|\\([^()]*\\))*\\)(\\s*:\\s*(.)*)?\\s*=>)) ) | (:\\s*( (<) | ([(]\\s*( ([)]) | (\\.\\.\\.) | ([_$[:alnum:]]+\\s*( ([:,?=])| ([)]\\s*=>) )) ))) ))",
101- "beginCaptures": {
102- "1": {
103- "name": "entity.name.function.ts"
104- }
105- },
106- "end": "(?=$|[;,=}]|(\\s+(of|in)\\s+))",
107- "patterns": [
108- {
109- "include": "#type-annotation"
110- },
111- {
112- "include": "#string"
113- },
114- {
115- "include": "#comment"
116- }
117- ]
118- },
119- {
120- "name": "meta.var-single-variable.expr.ts",
121- "begin": "([_$[:alpha:]][_$[:alnum:]]*)",
122- "beginCaptures": {
123- "1": {
124- "name": "variable.other.readwrite.ts"
125- }
126- },
127- "end": "(?=$|[;,=}]|(\\s+(of|in)\\s+))",
128- "patterns": [
129- {
130- "include": "#type-annotation"
131- },
132- {
133- "include": "#string"
134- },
135- {
136- "include": "#comment"
137- }
138- ]
139- }
140- ]
141- },
142- "destructuring-variable": {
143- "patterns": [
144- {
145- "name": "meta.object-binding-pattern-variable.ts",
146- "begin": "(?<!=|:|of|in)\\s*(?=\\{)",
147- "end": "(?=$|[;,=}]|(\\s+(of|in)\\s+))",
148- "patterns": [
149- {
150- "include": "#object-binding-pattern"
151- },
152- {
153- "include": "#type-annotation"
154- },
155- {
156- "include": "#comment"
157- }
158- ]
159- },
160- {
161- "name": "meta.array-binding-pattern-variable.ts",
162- "begin": "(?<!=|:|of|in)\\s*(?=\\[)",
163- "end": "(?=$|[;,=}]|(\\s+(of|in)\\s+))",
164- "patterns": [
165- {
166- "include": "#array-binding-pattern"
167- },
168- {
169- "include": "#type-annotation"
170- },
171- {
172- "include": "#comment"
173- }
174- ]
175- }
176- ]
177- },
178- "object-binding-element": {
179- "patterns": [
180- {
181- "include": "#comment"
182- },
183- {
184- "begin": "(?=(([_$[:alpha:]][_$[:alnum:]]*)|(\\'[^']*\\')|(\\\"[^\"]*\\\")|(\\[([^\\[\\]]|\\[[^\\[\\]]+\\])+\\]))\\s*(:))",
185- "end": "(?=,|\\})",
186- "patterns": [
187- {
188- "include": "#object-binding-element-propertyName"
189- },
190- {
191- "include": "#binding-element"
192- }
193- ]
194- },
195- {
196- "include": "#object-binding-pattern"
197- },
198- {
199- "include": "#destructuring-variable-rest"
200- },
201- {
202- "include": "#variable-initializer"
203- },
204- {
205- "include": "#punctuation-comma"
206- }
207- ]
208- },
209- "object-binding-element-propertyName": {
210- "begin": "(?=(([_$[:alpha:]][_$[:alnum:]]*)|(\\'[^']*\\')|(\\\"[^\"]*\\\")|(\\[([^\\[\\]]|\\[[^\\[\\]]+\\])+\\]))\\s*(:))",
211- "end": "(:)",
212- "endCaptures": {
213- "0": {
214- "name": "punctuation.destructuring.ts"
215- }
216- },
217- "patterns": [
218- {
219- "include": "#string"
220- },
221- {
222- "include": "#array-literal"
223- },
224- {
225- "name": "variable.object.property.ts",
226- "match": "([_$[:alpha:]][_$[:alnum:]]*)"
227- }
228- ]
229- },
230- "binding-element": {
231- "patterns": [
232- {
233- "include": "#comment"
234- },
235- {
236- "include": "#object-binding-pattern"
237- },
238- {
239- "include": "#array-binding-pattern"
240- },
241- {
242- "include": "#destructuring-variable-rest"
243- },
244- {
245- "include": "#variable-initializer"
246- }
247- ]
248- },
249- "destructuring-variable-rest": {
250- "match": "(?:(\\.\\.\\.)\\s*)?([_$[:alpha:]][_$[:alnum:]]*)",
251- "captures": {
252- "1": {
253- "name": "keyword.operator.rest.ts"
254- },
255- "2": {
256- "name": "variable.other.readwrite.ts"
257- }
258- }
259- },
260- "object-binding-pattern": {
261- "begin": "(?:(\\.\\.\\.)\\s*)?(\\{)",
262- "beginCaptures": {
263- "1": {
264- "name": "keyword.operator.rest.ts"
265- },
266- "2": {
267- "name": "punctuation.definition.binding-pattern.object.ts"
268- }
269- },
270- "end": "\\}",
271- "endCaptures": {
272- "0": {
273- "name": "punctuation.definition.binding-pattern.object.ts"
274- }
275- },
276- "patterns": [
277- {
278- "include": "#object-binding-element"
279- }
280- ]
281- },
282- "array-binding-pattern": {
283- "begin": "(?:(\\.\\.\\.)\\s*)?(\\[)",
284- "beginCaptures": {
285- "1": {
286- "name": "keyword.operator.rest.ts"
287- },
288- "2": {
289- "name": "punctuation.definition.binding-pattern.array.ts"
290- }
291- },
292- "end": "\\]",
293- "endCaptures": {
294- "0": {
295- "name": "punctuation.definition.binding-pattern.array.ts"
296- }
297- },
298- "patterns": [
299- {
300- "include": "#binding-element"
301- },
302- {
303- "include": "#punctuation-comma"
304- }
305- ]
306- },
307- "ternary-expression": {
308- "begin": "(?=\\?)",
309- "end": "(?=$|[;,})\\]])",
310- "patterns": [
311- {
312- "include": "#ternary-operator"
313- },
314- {
315- "include": "#expression"
316- }
317- ]
318- },
319- "ternary-operator": {
320- "begin": "(\\?)",
321- "beginCaptures": {
322- "0": {
323- "name": "keyword.operator.ternary.ts"
324- }
325- },
326- "end": "(:)",
327- "endCaptures": {
328- "0": {
329- "name": "keyword.operator.ternary.ts"
330- }
331- },
332- "patterns": [
333- {
334- "include": "#expression"
335- }
336- ]
337- },
338- "expression": {
339- "name": "meta.expression.ts",
340- "patterns": [
341- {
342- "include": "#string"
343- },
344- {
345- "include": "#regex"
346- },
347- {
348- "include": "#template"
349- },
350- {
351- "include": "#comment"
352- },
353- {
354- "include": "#literal"
355- },
356- {
357- "include": "#function-declaration"
358- },
359- {
360- "include": "#class-or-interface-declaration"
361- },
362- {
363- "include": "#arrow-function"
364- },
365- {
366- "include": "#cast"
367- },
368- {
369- "include": "#ternary-expression"
370- },
371- {
372- "include": "#new-expr"
373- },
374- {
375- "include": "#object-literal"
376- },
377- {
378- "include": "#expression-operators"
379- },
380- {
381- "include": "#function-call"
382- },
383- {
384- "include": "#support-objects"
385- },
386- {
387- "include": "#identifiers"
388- },
389- {
390- "include": "#paren-expression"
391- },
392- {
393- "include": "#punctuation-comma"
394- },
395- {
396- "include": "#punctuation-accessor"
397- }
398- ]
399- },
400- "control-statement": {
401- "patterns": [
402- {
403- "name": "keyword.control.trycatch.ts",
404- "match": "(?<!\\.|\\$)\\b(catch|finally|throw|try)\\b(?!\\$)"
405- },
406- {
407- "name": "keyword.control.loop.ts",
408- "match": "(?<!\\.|\\$)\\b(break|continue|do|goto|while)\\b(?!\\$)"
409- },
410- {
411- "name": "keyword.control.flow.ts",
412- "match": "(?<!\\.|\\$)\\b(return)\\b(?!\\$)"
413- },
414- {
415- "match": "(?<!\\.|\\$)\\b(yield)\\b(?!\\$)(?:\\s*(\\*))?",
416- "captures": {
417- "1": {
418- "name": "keyword.control.flow.ts"
419- },
420- "2": {
421- "name": "keyword.generator.asterisk.ts"
422- }
423- }
424- },
425- {
426- "name": "keyword.control.switch.ts",
427- "match": "(?<!\\.|\\$)\\b(case|default|switch)\\b(?!\\$)"
428- },
429- {
430- "name": "keyword.control.conditional.ts",
431- "match": "(?<!\\.|\\$)\\b(else|if)\\b(?!\\$)"
432- },
433- {
434- "name": "keyword.control.with.ts",
435- "match": "(?<!\\.|\\$)\\b(with)\\b(?!\\$)"
436- },
437- {
438- "name": "keyword.other.debugger.ts",
439- "match": "(?<!\\.|\\$)\\b(debugger)\\b(?!\\$)"
440- },
441- {
442- "name": "storage.modifier.ts",
443- "match": "(?<!\\.|\\$)\\b(declare)\\b(?!\\$)"
444- }
445- ]
446- },
447- "declaration": {
448- "name": "meta.declaration.ts",
449- "patterns": [
450- {
451- "include": "#decorator"
452- },
453- {
454- "include": "#var-expr"
455- },
456- {
457- "include": "#function-declaration"
458- },
459- {
460- "include": "#class-or-interface-declaration"
461- },
462- {
463- "include": "#type-declaration"
464- },
465- {
466- "include": "#enum-declaration"
467- },
468- {
469- "include": "#namespace-declaration"
470- },
471- {
472- "include": "#import-equals-declaration"
473- },
474- {
475- "include": "#import-declaration"
476- },
477- {
478- "include": "#export-declaration"
479- }
480- ]
481- },
482- "decorator": {
483- "name": "meta.decorator.ts",
484- "begin": "(?<!\\.|\\$)\\@",
485- "beginCaptures": {
486- "0": {
487- "name": "punctuation.decorator.ts"
488- }
489- },
490- "end": "(?=\\s)",
491- "patterns": [
492- {
493- "include": "#expression"
494- }
495- ]
496- },
497- "type-declaration": {
498- "name": "meta.type.declaration.ts",
499- "begin": "(?<!\\.|\\$)(?:(\\bexport)\\s+)?\\b(type)\\b\\s+([_$[:alpha:]][_$[:alnum:]]*)\\s*",
500- "beginCaptures": {
501- "1": {
502- "name": "keyword.control.export.ts"
503- },
504- "2": {
505- "name": "storage.type.type.ts"
506- },
507- "3": {
508- "name": "entity.name.type.ts"
509- }
510- },
511- "end": "(?=[};]|\\bvar\\b|\\blet\\b|\\bconst\\b|\\btype\\b|\\bfunction\\b|\\bclass\\b|\\binterface\\b|\\bnamespace\\b|\\bmodule\\b|\\bimport\\b|\\benum\\b|\\bdeclare\\b|\\bexport\\b|\\babstract\\b|\\basync\\b)",
512- "patterns": [
513- {
514- "include": "#comment"
515- },
516- {
517- "include": "#type-parameters"
518- },
519- {
520- "include": "#type"
521- },
522- {
523- "match": "(=)\\s*",
524- "captures": {
525- "1": {
526- "name": "keyword.operator.assignment.ts"
527- }
528- }
529- }
530- ]
531- },
532- "enum-declaration": {
533- "name": "meta.enum.declaration.ts",
534- "begin": "(?<!\\.|\\$)(?:(\\bexport)\\s+)?(?:\\b(const)\\s+)?\\b(enum)\\s+([_$[:alpha:]][_$[:alnum:]]*)",
535- "beginCaptures": {
536- "1": {
537- "name": "keyword.control.export.ts"
538- },
539- "2": {
540- "name": "storage.modifier.ts"
541- },
542- "3": {
543- "name": "storage.type.enum.ts"
544- },
545- "4": {
546- "name": "entity.name.type.enum.ts"
547- }
548- },
549- "end": "(?<=\\})",
550- "patterns": [
551- {
552- "include": "#comment"
553- },
554- {
555- "begin": "\\{",
556- "beginCaptures": {
557- "0": {
558- "name": "punctuation.definition.block.ts"
559- }
560- },
561- "end": "\\}",
562- "endCaptures": {
563- "0": {
564- "name": "punctuation.definition.block.ts"
565- }
566- },
567- "patterns": [
568- {
569- "include": "#comment"
570- },
571- {
572- "begin": "([_$[:alpha:]][_$[:alnum:]]*)",
573- "beginCaptures": {
574- "0": {
575- "name": "variable.other.enummember.ts"
576- }
577- },
578- "end": "(?=,|\\}|$)",
579- "patterns": [
580- {
581- "include": "#comment"
582- },
583- {
584- "include": "#variable-initializer"
585- }
586- ]
587- },
588- {
589- "begin": "(?=((\\'[^']*\\')|(\\\"[^\"]*\\\")|(\\[([^\\[\\]]|\\[[^\\[\\]]+\\])+\\])))",
590- "end": "(?=,|\\}|$)",
591- "patterns": [
592- {
593- "include": "#string"
594- },
595- {
596- "include": "#array-literal"
597- },
598- {
599- "include": "#comment"
600- },
601- {
602- "include": "#variable-initializer"
603- }
604- ]
605- },
606- {
607- "include": "#punctuation-comma"
608- }
609- ]
610- }
611- ]
612- },
613- "namespace-declaration": {
614- "name": "meta.namespace.declaration.ts",
615- "begin": "(?<!\\.|\\$)(?:(\\bexport)\\s+)?\\b(namespace|module)\\s+",
616- "beginCaptures": {
617- "1": {
618- "name": "keyword.control.export.ts"
619- },
620- "2": {
621- "name": "storage.type.namespace.ts"
622- }
623- },
624- "end": "(?=$|\\{)",
625- "patterns": [
626- {
627- "include": "#comment"
628- },
629- {
630- "include": "#string"
631- },
632- {
633- "name": "entity.name.type.module.ts",
634- "match": "([_$[:alpha:]][_$[:alnum:]]*)"
635- },
636- {
637- "name": "punctuation.accessor.ts",
638- "match": "\\."
639- }
640- ]
641- },
642- "import-equals-declaration": {
643- "patterns": [
644- {
645- "name": "meta.import-equals.external.ts",
646- "begin": "(?<!\\.|\\$)(?:(\\bexport)\\s+)?\\b(import)\\s+([_$[:alpha:]][_$[:alnum:]]*)\\s*(=)\\s*(require)\\s*(\\()",
647- "beginCaptures": {
648- "1": {
649- "name": "keyword.control.export.ts"
650- },
651- "2": {
652- "name": "keyword.control.import.ts"
653- },
654- "3": {
655- "name": "variable.other.readwrite.alias.ts"
656- },
657- "4": {
658- "name": "keyword.operator.assignment.ts"
659- },
660- "5": {
661- "name": "keyword.control.require.ts"
662- },
663- "6": {
664- "name": "meta.brace.round.ts"
665- }
666- },
667- "end": "\\)",
668- "endCaptures": {
669- "0": {
670- "name": "meta.brace.round.ts"
671- }
672- },
673- "patterns": [
674- {
675- "include": "#comment"
676- },
677- {
678- "include": "#string"
679- }
680- ]
681- },
682- {
683- "name": "meta.import-equals.internal.ts",
684- "begin": "(?<!\\.|\\$)(?:(\\bexport)\\s+)?\\b(import)\\s+([_$[:alpha:]][_$[:alnum:]]*)\\s*(=)\\s*(?!require\\b)",
685- "beginCaptures": {
686- "1": {
687- "name": "keyword.control.export.ts"
688- },
689- "2": {
690- "name": "keyword.control.import.ts"
691- },
692- "3": {
693- "name": "variable.other.readwrite.alias.ts"
694- },
695- "4": {
696- "name": "keyword.operator.assignment.ts"
697- }
698- },
699- "end": "(?=;|$)",
700- "patterns": [
701- {
702- "include": "#comment"
703- },
704- {
705- "match": "([_$[:alpha:]][_$[:alnum:]]*)\\s*(\\.)",
706- "captures": {
707- "1": {
708- "name": "entity.name.type.module.ts"
709- },
710- "2": {
711- "name": "punctuation.accessor.ts"
712- }
713- }
714- },
715- {
716- "name": "variable.other.readwrite.ts",
717- "match": "([_$[:alpha:]][_$[:alnum:]]*)"
718- }
719- ]
720- }
721- ]
722- },
723- "import-declaration": {
724- "name": "meta.import.ts",
725- "begin": "(?<!\\.|\\$)(?:(\\bexport)\\s+)?\\b(import)(?!(\\s*:)|(\\$))\\b",
726- "beginCaptures": {
727- "1": {
728- "name": "keyword.control.export.ts"
729- },
730- "2": {
731- "name": "keyword.control.import.ts"
732- }
733- },
734- "end": "(?=;|$)",
735- "patterns": [
736- {
737- "include": "#import-export-declaration"
738- }
739- ]
740- },
741- "export-declaration": {
742- "patterns": [
743- {
744- "match": "(?<!\\.|\\$)\\b(export)\\s+(as)\\s+(namespace)\\s+([_$[:alpha:]][_$[:alnum:]]*)",
745- "captures": {
746- "1": {
747- "name": "keyword.control.export.ts"
748- },
749- "2": {
750- "name": "keyword.control.as.ts"
751- },
752- "3": {
753- "name": "storage.type.namespace.ts"
754- },
755- "4": {
756- "name": "entity.name.type.module.ts"
757- }
758- }
759- },
760- {
761- "name": "meta.export.default.ts",
762- "begin": "(?<!\\.|\\$)\\b(export)(?:(?:\\s*(=))|(?:\\s+(default)(?=\\s+)))",
763- "beginCaptures": {
764- "1": {
765- "name": "keyword.control.export.ts"
766- },
767- "2": {
768- "name": "keyword.operator.assignment.ts"
769- },
770- "3": {
771- "name": "keyword.control.default.ts"
772- }
773- },
774- "end": "(?=;|\\bexport\\b|\\bfunction\\b|\\bclass\\b|\\binterface\\b|\\blet\\b|\\bvar\\b|\\bconst\\b|\\bimport\\b|\\benum\\b|\\bnamespace\\b|\\bmodule\\b|\\btype\\b|\\babstract\\b|\\bdeclare\\b|\\basync\\b|$)",
775- "patterns": [
776- {
777- "include": "#expression"
778- }
779- ]
780- },
781- {
782- "name": "meta.export.ts",
783- "begin": "(?<!\\.|\\$)\\b(export)(?!(\\s*:)|(\\$))\\b",
784- "beginCaptures": {
785- "0": {
786- "name": "keyword.control.export.ts"
787- }
788- },
789- "end": "(?=;|\\bexport\\b|\\bfunction\\b|\\bclass\\b|\\binterface\\b|\\blet\\b|\\bvar\\b|\\bconst\\b|\\bimport\\b|\\benum\\b|\\bnamespace\\b|\\bmodule\\b|\\btype\\b|\\babstract\\b|\\bdeclare\\b|\\basync\\b|$)",
790- "patterns": [
791- {
792- "include": "#import-export-declaration"
793- }
794- ]
795- }
796- ]
797- },
798- "import-export-declaration": {
799- "patterns": [
800- {
801- "include": "#comment"
802- },
803- {
804- "include": "#string"
805- },
806- {
807- "include": "#import-export-block"
808- },
809- {
810- "name": "keyword.control.from.ts",
811- "match": "\\bfrom\\b"
812- },
813- {
814- "include": "#import-export-clause"
815- }
816- ]
817- },
818- "import-export-block": {
819- "name": "meta.block.ts",
820- "begin": "\\{",
821- "beginCaptures": {
822- "0": {
823- "name": "punctuation.definition.block.ts"
824- }
825- },
826- "end": "\\}",
827- "endCaptures": {
828- "0": {
829- "name": "punctuation.definition.block.ts"
830- }
831- },
832- "patterns": [
833- {
834- "include": "#import-export-clause"
835- }
836- ]
837- },
838- "import-export-clause": {
839- "patterns": [
840- {
841- "include": "#comment"
842- },
843- {
844- "comment": "(default|*|name) as alias",
845- "match": "(?x) (?: \\b(default)\\b | (\\*) | ([_$[:alpha:]][_$[:alnum:]]*)) \\s+ (as) \\s+ (?: (\\b default \\b | \\*) | ([_$[:alpha:]][_$[:alnum:]]*))",
846- "captures": {
847- "1": {
848- "name": "keyword.control.default.ts"
849- },
850- "2": {
851- "name": "constant.language.import-export-all.ts"
852- },
853- "3": {
854- "name": "variable.other.readwrite.ts"
855- },
856- "4": {
857- "name": "keyword.control.as.ts"
858- },
859- "5": {
860- "name": "invalid.illegal.ts"
861- },
862- "6": {
863- "name": "variable.other.readwrite.alias.ts"
864- }
865- }
866- },
867- {
868- "include": "#punctuation-comma"
869- },
870- {
871- "name": "constant.language.import-export-all.ts",
872- "match": "\\*"
873- },
874- {
875- "name": "keyword.control.default.ts",
876- "match": "\\b(default)\\b"
877- },
878- {
879- "name": "variable.other.readwrite.alias.ts",
880- "match": "([_$[:alpha:]][_$[:alnum:]]*)"
881- }
882- ]
883- },
884- "class-or-interface-declaration": {
885- "name": "meta.class.ts",
886- "begin": "(?<!\\.|\\$)\\b(?:(export)\\s+)?\\b(?:(abstract)\\s+)?\\b(?:(class)|(interface))\\b",
887- "beginCaptures": {
888- "1": {
889- "name": "keyword.control.export.ts"
890- },
891- "2": {
892- "name": "storage.modifier.ts"
893- },
894- "3": {
895- "name": "storage.type.class.ts"
896- },
897- "4": {
898- "name": "storage.type.interface.ts"
899- }
900- },
901- "end": "(?<=\\})",
902- "endCaptures": {
903- "1": {
904- "name": "punctuation.definition.block.ts"
905- }
906- },
907- "patterns": [
908- {
909- "include": "#comment"
910- },
911- {
912- "include": "#class-or-interface-heritage"
913- },
914- {
915- "match": "[_$[:alpha:]][_$[:alnum:]]*",
916- "captures": {
917- "0": {
918- "name": "entity.name.type.class.ts"
919- }
920- }
921- },
922- {
923- "include": "#type-parameters"
924- },
925- {
926- "include": "#class-or-interface-body"
927- }
928- ]
929- },
930- "class-or-interface-heritage": {
931- "begin": "(?<!\\.|\\$)(?:\\b(extends|implements)\\b)(?!\\$)",
932- "beginCaptures": {
933- "1": {
934- "name": "storage.modifier.ts"
935- }
936- },
937- "end": "(?=\\{)",
938- "endCaptures": {
939- "1": {
940- "name": "punctuation.definition.block.ts"
941- }
942- },
943- "patterns": [
944- {
945- "include": "#comment"
946- },
947- {
948- "include": "#class-or-interface-heritage"
949- },
950- {
951- "include": "#type-parameters"
952- },
953- {
954- "match": "([_$[:alpha:]][_$[:alnum:]]*)\\s*(\\.)(?=\\s*[_$[:alpha:]][_$[:alnum:]]*(\\s*\\.\\s*[_$[:alpha:]][_$[:alnum:]]*)*\\s*([,<{]|extends|implements|//|/\\*))",
955- "captures": {
956- "1": {
957- "name": "entity.name.type.module.ts"
958- },
959- "2": {
960- "name": "punctuation.accessor.ts"
961- }
962- }
963- },
964- {
965- "match": "([_$[:alpha:]][_$[:alnum:]]*)(?=\\s*([,<{]|extends|implements|//|/\\*))",
966- "captures": {
967- "1": {
968- "name": "entity.other.inherited-class.ts"
969- }
970- }
971- },
972- {
973- "include": "#expression"
974- }
975- ]
976- },
977- "class-or-interface-body": {
978- "begin": "\\{",
979- "beginCaptures": {
980- "0": {
981- "name": "punctuation.definition.block.ts"
982- }
983- },
984- "end": "\\}",
985- "endCaptures": {
986- "0": {
987- "name": "punctuation.definition.block.ts"
988- }
989- },
990- "patterns": [
991- {
992- "include": "#string"
993- },
994- {
995- "include": "#comment"
996- },
997- {
998- "include": "#decorator"
999- },
1000- {
1001- "include": "#method-declaration"
1002- },
1003- {
1004- "include": "#indexer-declaration"
1005- },
1006- {
1007- "include": "#field-declaration"
1008- },
1009- {
1010- "include": "#type-annotation"
1011- },
1012- {
1013- "include": "#variable-initializer"
1014- },
1015- {
1016- "include": "#access-modifier"
1017- },
1018- {
1019- "include": "#property-accessor"
1020- },
1021- {
1022- "include": "#expression"
1023- },
1024- {
1025- "include": "#punctuation-comma"
1026- },
1027- {
1028- "include": "#punctuation-semicolon"
1029- }
1030- ]
1031- },
1032- "type-object": {
1033- "name": "meta.object.type.ts",
1034- "begin": "\\{",
1035- "beginCaptures": {
1036- "0": {
1037- "name": "punctuation.definition.block.ts"
1038- }
1039- },
1040- "end": "\\}",
1041- "endCaptures": {
1042- "0": {
1043- "name": "punctuation.definition.block.ts"
1044- }
1045- },
1046- "patterns": [
1047- {
1048- "include": "#type-object-members"
1049- }
1050- ]
1051- },
1052- "type-object-members": {
1053- "patterns": [
1054- {
1055- "include": "#comment"
1056- },
1057- {
1058- "include": "#method-declaration"
1059- },
1060- {
1061- "include": "#indexer-declaration"
1062- },
1063- {
1064- "include": "#field-declaration"
1065- },
1066- {
1067- "include": "#type-annotation"
1068- },
1069- {
1070- "begin": "\\.\\.\\.",
1071- "beginCaptures": {
1072- "0": {
1073- "name": "keyword.operator.spread.ts"
1074- }
1075- },
1076- "end": "(?=\\}|;|,|$)|(?<=\\})",
1077- "patterns": [
1078- {
1079- "include": "#type"
1080- }
1081- ]
1082- },
1083- {
1084- "include": "#punctuation-comma"
1085- },
1086- {
1087- "include": "#punctuation-semicolon"
1088- }
1089- ]
1090- },
1091- "field-declaration": {
1092- "name": "meta.field.declaration.ts",
1093- "begin": "(?<!\\()(?:(?<!\\.|\\$)\\b(readonly)\\s+)?(?=(([_$[:alpha:]][_$[:alnum:]]*)|(\\'[^']*\\')|(\\\"[^\"]*\\\")|(\\[([^\\[\\]]|\\[[^\\[\\]]+\\])+\\]))\\s*(\\?\\s*)?(=|:))",
1094- "beginCaptures": {
1095- "1": {
1096- "name": "storage.modifier.ts"
1097- }
1098- },
1099- "end": "(?=\\}|;|,|$)|(?<=\\})",
1100- "patterns": [
1101- {
1102- "include": "#variable-initializer"
1103- },
1104- {
1105- "begin": "(?=((?:[_$[:alpha:]][_$[:alnum:]]*)|(?:\\'[^']*\\')|(?:\\\"[^\"]*\\\")|(\\[([^\\[\\]]|\\[[^\\[\\]]+\\])+\\]))\\s*(\\?\\s*)?(=|:))",
1106- "end": "(?=[};,=]|$)|(?<=\\})",
1107- "patterns": [
1108- {
1109- "include": "#type-annotation"
1110- },
1111- {
1112- "include": "#string"
1113- },
1114- {
1115- "include": "#array-literal"
1116- },
1117- {
1118- "include": "#comment"
1119- },
1120- {
1121- "name": "entity.name.function.ts",
1122- "match": "(?x)([_$[:alpha:]][_$[:alnum:]]*)(?=(\\?\\s*)?\\s* (=\\s*( (async\\s+) | (function\\s*[(<]) | (function\\s+) | ([_$[:alpha:]][_$[:alnum:]]*\\s*=>) | ((<([^<>]|\\<[^<>]+\\>)+>\\s*)?\\(([^()]|\\([^()]*\\))*\\)(\\s*:\\s*(.)*)?\\s*=>)) ) | (:\\s*( (<) | ([(]\\s*( ([)]) | (\\.\\.\\.) | ([_$[:alnum:]]+\\s*( ([:,?=])| ([)]\\s*=>) )) ))) ))"
1123- },
1124- {
1125- "name": "variable.object.property.ts",
1126- "match": "[_$[:alpha:]][_$[:alnum:]]*"
1127- },
1128- {
1129- "name": "keyword.operator.optional.ts",
1130- "match": "\\?"
1131- }
1132- ]
1133- }
1134- ]
1135- },
1136- "method-declaration": {
1137- "name": "meta.method.declaration.ts",
1138- "begin": "(?<!\\.|\\$)(?:\\b(public|private|protected)\\s+)?(?:\\b(abstract)\\s+)?(?:\\b(async)\\s+)?(?:\\b(get|set)\\s+)?(?:(?:\\b(?:(new)|(constructor))\\b(?!\\$|:))|(?:(\\*)\\s*)?(?=((([_$[:alpha:]][_$[:alnum:]]*)|(\\'[^']*\\')|(\\\"[^\"]*\\\")|(\\[([^\\[\\]]|\\[[^\\[\\]]+\\])+\\]))\\s*(\\??))?\\s*[\\(\\<]))",
1139- "beginCaptures": {
1140- "1": {
1141- "name": "storage.modifier.ts"
1142- },
1143- "2": {
1144- "name": "storage.modifier.ts"
1145- },
1146- "3": {
1147- "name": "storage.modifier.async.ts"
1148- },
1149- "4": {
1150- "name": "storage.type.property.ts"
1151- },
1152- "5": {
1153- "name": "keyword.operator.new.ts"
1154- },
1155- "6": {
1156- "name": "storage.type.ts"
1157- },
1158- "7": {
1159- "name": "keyword.generator.asterisk.ts"
1160- }
1161- },
1162- "end": "(?=\\}|;|,)|(?<=\\})",
1163- "patterns": [
1164- {
1165- "include": "#method-declaration-name"
1166- },
1167- {
1168- "include": "#comment"
1169- },
1170- {
1171- "include": "#type-parameters"
1172- },
1173- {
1174- "include": "#function-parameters"
1175- },
1176- {
1177- "include": "#return-type"
1178- },
1179- {
1180- "include": "#method-overload-declaration"
1181- },
1182- {
1183- "include": "#decl-block"
1184- }
1185- ]
1186- },
1187- "method-overload-declaration": {
1188- "begin": "(?<!\\.|\\$)(?:\\b(public|private|protected)\\s+)?(?:\\b(abstract)\\s+)?(?:\\b(async)\\s+)?(?:\\b(get|set)\\s+)?(?:(?:\\b(?:(new)|(constructor))\\b(?!\\$|:))|(?:(\\*)\\s*)?(?=((([_$[:alpha:]][_$[:alnum:]]*)|(\\'[^']*\\')|(\\\"[^\"]*\\\")|(\\[([^\\[\\]]|\\[[^\\[\\]]+\\])+\\]))\\s*(\\??))?\\s*[\\(\\<]))",
1189- "beginCaptures": {
1190- "1": {
1191- "name": "storage.modifier.ts"
1192- },
1193- "2": {
1194- "name": "storage.modifier.ts"
1195- },
1196- "3": {
1197- "name": "storage.modifier.async.ts"
1198- },
1199- "4": {
1200- "name": "storage.type.property.ts"
1201- },
1202- "5": {
1203- "name": "keyword.operator.new.ts"
1204- },
1205- "6": {
1206- "name": "storage.type.ts"
1207- },
1208- "7": {
1209- "name": "keyword.generator.asterisk.ts"
1210- }
1211- },
1212- "end": "(?=\\(|\\<)",
1213- "patterns": [
1214- {
1215- "include": "#method-declaration-name"
1216- }
1217- ]
1218- },
1219- "method-declaration-name": {
1220- "begin": "(?=(([_$[:alpha:]][_$[:alnum:]]*)|(\\'[^']*\\')|(\\\"[^\"]*\\\")|(\\[([^\\[\\]]|\\[[^\\[\\]]+\\])+\\]))\\s*(\\??)\\s*[\\(\\<])",
1221- "end": "(?=\\(|\\<)",
1222- "patterns": [
1223- {
1224- "include": "#string"
1225- },
1226- {
1227- "include": "#array-literal"
1228- },
1229- {
1230- "name": "entity.name.function.ts",
1231- "match": "[_$[:alpha:]][_$[:alnum:]]*"
1232- },
1233- {
1234- "name": "keyword.operator.optional.ts",
1235- "match": "\\?"
1236- }
1237- ]
1238- },
1239- "indexer-declaration": {
1240- "name": "meta.indexer.declaration.ts",
1241- "begin": "(?:(?<!\\.|\\$)\\b(readonly)\\s*)?(\\[)\\s*([_$[:alpha:]][_$[:alnum:]]*)\\s*(?=:)",
1242- "beginCaptures": {
1243- "1": {
1244- "name": "storage.modifier.ts"
1245- },
1246- "2": {
1247- "name": "meta.brace.square.ts"
1248- },
1249- "3": {
1250- "name": "variable.parameter.ts"
1251- }
1252- },
1253- "end": "(\\])\\s*(\\?\\s*)?|$",
1254- "endCaptures": {
1255- "1": {
1256- "name": "meta.brace.square.ts"
1257- },
1258- "2": {
1259- "name": "keyword.operator.optional.ts"
1260- }
1261- },
1262- "patterns": [
1263- {
1264- "include": "#type-annotation"
1265- }
1266- ]
1267- },
1268- "function-declaration": {
1269- "name": "meta.function.ts",
1270- "begin": "(?<!\\.|\\$)\\b(?:(export)\\s+)?(?:(async)\\s+)?(function\\b)(?:\\s*(\\*))?(?:(?:\\s+|(?<=\\*))([_$[:alpha:]][_$[:alnum:]]*))?\\s*",
1271- "beginCaptures": {
1272- "1": {
1273- "name": "keyword.control.export.ts"
1274- },
1275- "2": {
1276- "name": "storage.modifier.async.ts"
1277- },
1278- "3": {
1279- "name": "storage.type.function.ts"
1280- },
1281- "4": {
1282- "name": "keyword.generator.asterisk.ts"
1283- },
1284- "5": {
1285- "name": "entity.name.function.ts"
1286- }
1287- },
1288- "end": "(?=;|\\})|(?<=\\})",
1289- "patterns": [
1290- {
1291- "include": "#comment"
1292- },
1293- {
1294- "include": "#type-parameters"
1295- },
1296- {
1297- "include": "#function-parameters"
1298- },
1299- {
1300- "include": "#return-type"
1301- },
1302- {
1303- "include": "#function-overload-declaration"
1304- },
1305- {
1306- "include": "#decl-block"
1307- }
1308- ]
1309- },
1310- "function-overload-declaration": {
1311- "name": "meta.function.overload.ts",
1312- "match": "(?<!\\.|\\$)\\b(?:(export)\\s+)?(?:(async)\\s+)?(function\\b)(?:\\s*(\\*))?(?:(?:\\s+|(?<=\\*))([_$[:alpha:]][_$[:alnum:]]*))?\\s*",
1313- "captures": {
1314- "1": {
1315- "name": "keyword.control.export.ts"
1316- },
1317- "2": {
1318- "name": "storage.modifier.async.ts"
1319- },
1320- "3": {
1321- "name": "storage.type.function.ts"
1322- },
1323- "4": {
1324- "name": "keyword.generator.asterisk.ts"
1325- },
1326- "5": {
1327- "name": "entity.name.function.ts"
1328- }
1329- }
1330- },
1331- "object-literal": {
1332- "name": "meta.objectliteral.ts",
1333- "begin": "\\{",
1334- "beginCaptures": {
1335- "0": {
1336- "name": "punctuation.definition.block.ts"
1337- }
1338- },
1339- "end": "\\}",
1340- "endCaptures": {
1341- "0": {
1342- "name": "punctuation.definition.block.ts"
1343- }
1344- },
1345- "patterns": [
1346- {
1347- "include": "#object-member"
1348- }
1349- ]
1350- },
1351- "decl-block": {
1352- "name": "meta.block.ts",
1353- "begin": "\\{",
1354- "beginCaptures": {
1355- "0": {
1356- "name": "punctuation.definition.block.ts"
1357- }
1358- },
1359- "end": "\\}",
1360- "endCaptures": {
1361- "0": {
1362- "name": "punctuation.definition.block.ts"
1363- }
1364- },
1365- "patterns": [
1366- {
1367- "include": "#statements"
1368- }
1369- ]
1370- },
1371- "after-operator-block": {
1372- "name": "meta.objectliteral.ts",
1373- "begin": "(?<=[=(,\\[?+!]|await|return|yield|throw|in|of|typeof|&&|\\|\\||\\*)\\s*(\\{)",
1374- "beginCaptures": {
1375- "1": {
1376- "name": "punctuation.definition.block.ts"
1377- }
1378- },
1379- "end": "\\}",
1380- "endCaptures": {
1381- "0": {
1382- "name": "punctuation.definition.block.ts"
1383- }
1384- },
1385- "patterns": [
1386- {
1387- "include": "#object-member"
1388- }
1389- ]
1390- },
1391- "parameter-name": {
1392- "patterns": [
1393- {
1394- "match": "(?x)(?:\\s*\\b(readonly)\\s+)?(?:\\s*\\b(public|private|protected)\\s+)?(\\.\\.\\.)?\\s*(?<!=|:)([_$[:alpha:]][_$[:alnum:]]*)\\s*(\\??)(?=\\s* (=\\s*( (async\\s+) | (function\\s*[(<]) | (function\\s+) | ([_$[:alpha:]][_$[:alnum:]]*\\s*=>) | ((<([^<>]|\\<[^<>]+\\>)+>\\s*)?\\(([^()]|\\([^()]*\\))*\\)(\\s*:\\s*(.)*)?\\s*=>)) ) | (:\\s*( (<) | ([(]\\s*( ([)]) | (\\.\\.\\.) | ([_$[:alnum:]]+\\s*( ([:,?=])| ([)]\\s*=>) )) ))) ))",
1395- "captures": {
1396- "1": {
1397- "name": "storage.modifier.ts"
1398- },
1399- "2": {
1400- "name": "storage.modifier.ts"
1401- },
1402- "3": {
1403- "name": "keyword.operator.rest.ts"
1404- },
1405- "4": {
1406- "name": "entity.name.function.ts"
1407- },
1408- "5": {
1409- "name": "keyword.operator.optional.ts"
1410- }
1411- }
1412- },
1413- {
1414- "match": "(?:\\s*\\b(readonly)\\s+)?(?:\\s*\\b(public|private|protected)\\s+)?(\\.\\.\\.)?\\s*(?<!=|:)([_$[:alpha:]][_$[:alnum:]]*)\\s*(\\??)",
1415- "captures": {
1416- "1": {
1417- "name": "storage.modifier.ts"
1418- },
1419- "2": {
1420- "name": "storage.modifier.ts"
1421- },
1422- "3": {
1423- "name": "keyword.operator.rest.ts"
1424- },
1425- "4": {
1426- "name": "variable.parameter.ts"
1427- },
1428- "5": {
1429- "name": "keyword.operator.optional.ts"
1430- }
1431- }
1432- }
1433- ]
1434- },
1435- "destructuring-parameter": {
1436- "patterns": [
1437- {
1438- "name": "meta.parameter.object-binding-pattern.ts",
1439- "begin": "(?<!=|:)\\s*(\\{)",
1440- "beginCaptures": {
1441- "1": {
1442- "name": "punctuation.definition.binding-pattern.object.ts"
1443- }
1444- },
1445- "end": "\\}",
1446- "endCaptures": {
1447- "0": {
1448- "name": "punctuation.definition.binding-pattern.object.ts"
1449- }
1450- },
1451- "patterns": [
1452- {
1453- "include": "#parameter-object-binding-element"
1454- }
1455- ]
1456- },
1457- {
1458- "name": "meta.paramter.array-binding-pattern.ts",
1459- "begin": "(?<!=|:)\\s*(\\[)",
1460- "beginCaptures": {
1461- "1": {
1462- "name": "punctuation.definition.binding-pattern.array.ts"
1463- }
1464- },
1465- "end": "\\]",
1466- "endCaptures": {
1467- "0": {
1468- "name": "punctuation.definition.binding-pattern.array.ts"
1469- }
1470- },
1471- "patterns": [
1472- {
1473- "include": "#parameter-binding-element"
1474- },
1475- {
1476- "include": "#punctuation-comma"
1477- }
1478- ]
1479- }
1480- ]
1481- },
1482- "parameter-object-binding-element": {
1483- "patterns": [
1484- {
1485- "include": "#comment"
1486- },
1487- {
1488- "begin": "(?=(([_$[:alpha:]][_$[:alnum:]]*)|(\\'[^']*\\')|(\\\"[^\"]*\\\")|(\\[([^\\[\\]]|\\[[^\\[\\]]+\\])+\\]))\\s*(:))",
1489- "end": "(?=,|\\})",
1490- "patterns": [
1491- {
1492- "include": "#object-binding-element-propertyName"
1493- },
1494- {
1495- "include": "#parameter-binding-element"
1496- }
1497- ]
1498- },
1499- {
1500- "include": "#parameter-object-binding-pattern"
1501- },
1502- {
1503- "include": "#destructuring-parameter-rest"
1504- },
1505- {
1506- "include": "#variable-initializer"
1507- },
1508- {
1509- "include": "#punctuation-comma"
1510- }
1511- ]
1512- },
1513- "parameter-binding-element": {
1514- "patterns": [
1515- {
1516- "include": "#comment"
1517- },
1518- {
1519- "include": "#parameter-object-binding-pattern"
1520- },
1521- {
1522- "include": "#parameter-array-binding-pattern"
1523- },
1524- {
1525- "include": "#destructuring-parameter-rest"
1526- },
1527- {
1528- "include": "#variable-initializer"
1529- }
1530- ]
1531- },
1532- "destructuring-parameter-rest": {
1533- "match": "(?:(\\.\\.\\.)\\s*)?([_$[:alpha:]][_$[:alnum:]]*)",
1534- "captures": {
1535- "1": {
1536- "name": "keyword.operator.rest.ts"
1537- },
1538- "2": {
1539- "name": "variable.parameter.ts"
1540- }
1541- }
1542- },
1543- "parameter-object-binding-pattern": {
1544- "begin": "(?:(\\.\\.\\.)\\s*)?(\\{)",
1545- "beginCaptures": {
1546- "1": {
1547- "name": "keyword.operator.rest.ts"
1548- },
1549- "2": {
1550- "name": "punctuation.definition.binding-pattern.object.ts"
1551- }
1552- },
1553- "end": "\\}",
1554- "endCaptures": {
1555- "0": {
1556- "name": "punctuation.definition.binding-pattern.object.ts"
1557- }
1558- },
1559- "patterns": [
1560- {
1561- "include": "#parameter-object-binding-element"
1562- }
1563- ]
1564- },
1565- "parameter-array-binding-pattern": {
1566- "begin": "(?:(\\.\\.\\.)\\s*)?(\\[)",
1567- "beginCaptures": {
1568- "1": {
1569- "name": "keyword.operator.rest.ts"
1570- },
1571- "2": {
1572- "name": "punctuation.definition.binding-pattern.array.ts"
1573- }
1574- },
1575- "end": "\\]",
1576- "endCaptures": {
1577- "0": {
1578- "name": "punctuation.definition.binding-pattern.array.ts"
1579- }
1580- },
1581- "patterns": [
1582- {
1583- "include": "#parameter-binding-element"
1584- },
1585- {
1586- "include": "#punctuation-comma"
1587- }
1588- ]
1589- },
1590- "return-type": {
1591- "name": "meta.return.type.ts",
1592- "begin": "(?<=\\))\\s*(:)",
1593- "beginCaptures": {
1594- "1": {
1595- "name": "keyword.operator.type.annotation.ts"
1596- }
1597- },
1598- "end": "(?<!:)((?=$)|(?=\\{|;|//|\\}))",
1599- "patterns": [
1600- {
1601- "include": "#comment"
1602- },
1603- {
1604- "name": "meta.object.type.ts",
1605- "begin": "(?<=:)\\s*(\\{)",
1606- "beginCaptures": {
1607- "1": {
1608- "name": "punctuation.definition.block.ts"
1609- }
1610- },
1611- "end": "\\}",
1612- "endCaptures": {
1613- "0": {
1614- "name": "punctuation.definition.block.ts"
1615- }
1616- },
1617- "patterns": [
1618- {
1619- "include": "#type-object-members"
1620- }
1621- ]
1622- },
1623- {
1624- "include": "#type-predicate-operator"
1625- },
1626- {
1627- "include": "#type"
1628- }
1629- ]
1630- },
1631- "type-predicate-operator": {
1632- "name": "keyword.operator.expression.is.ts",
1633- "match": "(?<!\\.|\\$)\\bis\\b(?!\\$)"
1634- },
1635- "type-annotation": {
1636- "name": "meta.type.annotation.ts",
1637- "begin": ":",
1638- "beginCaptures": {
1639- "0": {
1640- "name": "keyword.operator.type.annotation.ts"
1641- }
1642- },
1643- "end": "(?=$|[,);\\}\\]]|//)|(?==[^>])|(?<=[\\}>\\]\\)]|[_$[:alpha:]])\\s*(?=\\{)",
1644- "patterns": [
1645- {
1646- "include": "#comment"
1647- },
1648- {
1649- "include": "#type"
1650- }
1651- ]
1652- },
1653- "type": {
1654- "name": "meta.type.ts",
1655- "patterns": [
1656- {
1657- "include": "#comment"
1658- },
1659- {
1660- "include": "#string"
1661- },
1662- {
1663- "include": "#numeric-literal"
1664- },
1665- {
1666- "include": "#type-primitive"
1667- },
1668- {
1669- "include": "#type-builtin-literals"
1670- },
1671- {
1672- "include": "#type-parameters"
1673- },
1674- {
1675- "include": "#type-tuple"
1676- },
1677- {
1678- "include": "#type-object"
1679- },
1680- {
1681- "include": "#type-operators"
1682- },
1683- {
1684- "include": "#type-fn-type-parameters"
1685- },
1686- {
1687- "include": "#type-paren-or-function-parameters"
1688- },
1689- {
1690- "include": "#type-function-return-type"
1691- },
1692- {
1693- "include": "#type-name"
1694- }
1695- ]
1696- },
1697- "function-parameters": {
1698- "name": "meta.parameters.ts",
1699- "begin": "\\(",
1700- "beginCaptures": {
1701- "0": {
1702- "name": "punctuation.definition.parameters.begin.ts"
1703- }
1704- },
1705- "end": "\\)",
1706- "endCaptures": {
1707- "0": {
1708- "name": "punctuation.definition.parameters.end.ts"
1709- }
1710- },
1711- "patterns": [
1712- {
1713- "include": "#comment"
1714- },
1715- {
1716- "include": "#decorator"
1717- },
1718- {
1719- "include": "#destructuring-parameter"
1720- },
1721- {
1722- "include": "#parameter-name"
1723- },
1724- {
1725- "include": "#type-annotation"
1726- },
1727- {
1728- "include": "#variable-initializer"
1729- },
1730- {
1731- "name": "punctuation.separator.parameter.ts",
1732- "match": ","
1733- }
1734- ]
1735- },
1736- "type-primitive": {
1737- "name": "support.type.primitive.ts",
1738- "match": "(?<!\\.|\\$)\\b(string|number|boolean|symbol|any|void|never)\\b(?!\\$)"
1739- },
1740- "type-builtin-literals": {
1741- "name": "support.type.builtin.ts",
1742- "match": "(?<!\\.|\\$)\\b(this|true|false|undefined|null)\\b(?!\\$)"
1743- },
1744- "type-paren-or-function-parameters": {
1745- "name": "meta.type.paren.cover.ts",
1746- "begin": "\\(",
1747- "beginCaptures": {
1748- "0": {
1749- "name": "meta.brace.round.ts"
1750- }
1751- },
1752- "end": "\\)",
1753- "endCaptures": {
1754- "0": {
1755- "name": "meta.brace.round.ts"
1756- }
1757- },
1758- "patterns": [
1759- {
1760- "include": "#type"
1761- },
1762- {
1763- "include": "#function-parameters"
1764- }
1765- ]
1766- },
1767- "type-fn-type-parameters": {
1768- "patterns": [
1769- {
1770- "name": "meta.type.constructor.ts",
1771- "match": "(?<!\\.|\\$)\\b(new)\\b(?=\\s*\\<)",
1772- "captures": {
1773- "1": {
1774- "name": "keyword.control.new.ts"
1775- }
1776- }
1777- },
1778- {
1779- "name": "meta.type.constructor.ts",
1780- "begin": "(?<!\\.|\\$)\\b(new)\\b\\s*(?=\\()",
1781- "beginCaptures": {
1782- "1": {
1783- "name": "keyword.control.new.ts"
1784- }
1785- },
1786- "end": "(?<=\\))",
1787- "patterns": [
1788- {
1789- "include": "#function-parameters"
1790- }
1791- ]
1792- },
1793- {
1794- "name": "meta.type.function.ts",
1795- "begin": "(?<=\\>)\\s*(?=\\()",
1796- "end": "(?<=\\))",
1797- "patterns": [
1798- {
1799- "include": "#function-parameters"
1800- }
1801- ]
1802- },
1803- {
1804- "name": "meta.type.function.ts",
1805- "begin": "(?x)( (?= [(]\\s*( ([)]) | (\\.\\.\\.) | ([_$[:alnum:]]+\\s*( ([:,?=])| ([)]\\s*=>) )) ) ) )",
1806- "end": "(?<=\\))",
1807- "patterns": [
1808- {
1809- "include": "#function-parameters"
1810- }
1811- ]
1812- }
1813- ]
1814- },
1815- "type-operators": {
1816- "patterns": [
1817- {
1818- "include": "#typeof-operator"
1819- },
1820- {
1821- "name": "keyword.operator.type.ts",
1822- "match": "[&|]"
1823- },
1824- {
1825- "name": "keyword.operator.expression.keyof.ts",
1826- "match": "(?<!\\.|\\$)\\bkeyof\\b(?!\\$)"
1827- }
1828- ]
1829- },
1830- "type-function-return-type": {
1831- "name": "meta.type.function.return.ts",
1832- "begin": "=>",
1833- "beginCaptures": {
1834- "0": {
1835- "name": "storage.type.function.arrow.ts"
1836- }
1837- },
1838- "end": "(?<!=>)(?=[,\\]\\)\\{\\}=;>]|//|$)",
1839- "patterns": [
1840- {
1841- "include": "#comment"
1842- },
1843- {
1844- "name": "meta.object.type.ts",
1845- "begin": "(?<==>)\\s*(\\{)",
1846- "beginCaptures": {
1847- "1": {
1848- "name": "punctuation.definition.block.ts"
1849- }
1850- },
1851- "end": "\\}",
1852- "endCaptures": {
1853- "0": {
1854- "name": "punctuation.definition.block.ts"
1855- }
1856- },
1857- "patterns": [
1858- {
1859- "include": "#type-object-members"
1860- }
1861- ]
1862- },
1863- {
1864- "include": "#type-predicate-operator"
1865- },
1866- {
1867- "include": "#type"
1868- }
1869- ]
1870- },
1871- "type-tuple": {
1872- "name": "meta.type.tuple.ts",
1873- "begin": "\\[",
1874- "beginCaptures": {
1875- "0": {
1876- "name": "meta.brace.square.ts"
1877- }
1878- },
1879- "end": "\\]",
1880- "endCaptures": {
1881- "0": {
1882- "name": "meta.brace.square.ts"
1883- }
1884- },
1885- "patterns": [
1886- {
1887- "include": "#type"
1888- },
1889- {
1890- "include": "#punctuation-comma"
1891- }
1892- ]
1893- },
1894- "type-name": {
1895- "patterns": [
1896- {
1897- "match": "([_$[:alpha:]][_$[:alnum:]]*)\\s*(\\.)",
1898- "captures": {
1899- "1": {
1900- "name": "entity.name.type.module.ts"
1901- },
1902- "2": {
1903- "name": "punctuation.accessor.ts"
1904- }
1905- }
1906- },
1907- {
1908- "name": "entity.name.type.ts",
1909- "match": "[_$[:alpha:]][_$[:alnum:]]*"
1910- }
1911- ]
1912- },
1913- "type-parameters": {
1914- "name": "meta.type.parameters.ts",
1915- "begin": "(<)",
1916- "beginCaptures": {
1917- "1": {
1918- "name": "punctuation.definition.typeparameters.begin.ts"
1919- }
1920- },
1921- "end": "(?=$)|(>)",
1922- "endCaptures": {
1923- "1": {
1924- "name": "punctuation.definition.typeparameters.end.ts"
1925- }
1926- },
1927- "patterns": [
1928- {
1929- "include": "#comment"
1930- },
1931- {
1932- "name": "storage.modifier.ts",
1933- "match": "(?<!\\.|\\$)\\b(extends)\\b(?!\\$)"
1934- },
1935- {
1936- "include": "#type"
1937- },
1938- {
1939- "include": "#punctuation-comma"
1940- }
1941- ]
1942- },
1943- "variable-initializer": {
1944- "begin": "(?<!=|!)(=)(?!=)",
1945- "beginCaptures": {
1946- "1": {
1947- "name": "keyword.operator.assignment.ts"
1948- }
1949- },
1950- "end": "(?=$|[,);}\\]])",
1951- "patterns": [
1952- {
1953- "include": "#expression"
1954- }
1955- ]
1956- },
1957- "for-loop": {
1958- "begin": "(?<!\\.|\\$)\\b(for)\\s*(\\()",
1959- "beginCaptures": {
1960- "1": {
1961- "name": "keyword.control.loop.ts"
1962- },
1963- "2": {
1964- "name": "meta.brace.round.ts"
1965- }
1966- },
1967- "end": "\\)",
1968- "endCaptures": {
1969- "0": {
1970- "name": "meta.brace.round.ts"
1971- }
1972- },
1973- "patterns": [
1974- {
1975- "include": "#var-expr"
1976- },
1977- {
1978- "include": "#expression"
1979- },
1980- {
1981- "include": "#punctuation-semicolon"
1982- }
1983- ]
1984- },
1985- "switch-expression": {
1986- "name": "switch-expression.expr.ts",
1987- "begin": "(?<!\\.|\\$)\\b(switch)\\s*(\\()",
1988- "beginCaptures": {
1989- "1": {
1990- "name": "keyword.control.switch.ts"
1991- },
1992- "2": {
1993- "name": "meta.brace.round.ts"
1994- }
1995- },
1996- "end": "\\)",
1997- "endCaptures": {
1998- "0": {
1999- "name": "meta.brace.round.ts"
2000- }
2001- },
2002- "patterns": [
2003- {
2004- "include": "#expression"
2005- }
2006- ]
2007- },
2008- "switch-block": {
2009- "name": "switch-block.expr.ts",
2010- "begin": "{",
2011- "beginCaptures": {
2012- "0": {
2013- "name": "punctuation.definition.block.ts"
2014- }
2015- },
2016- "end": "(?=\\})",
2017- "patterns": [
2018- {
2019- "include": "#case-clause"
2020- },
2021- {
2022- "include": "#statements"
2023- }
2024- ]
2025- },
2026- "case-clause": {
2027- "name": "case-clause.expr.ts",
2028- "begin": "(?<!\\.|\\$)\\b(case|default(?=:))\\b(?!\\$)",
2029- "beginCaptures": {
2030- "1": {
2031- "name": "keyword.control.switch.ts"
2032- }
2033- },
2034- "end": ":",
2035- "endCaptures": {
2036- "0": {
2037- "name": "punctuation.definition.section.case-statement.ts"
2038- }
2039- },
2040- "patterns": [
2041- {
2042- "include": "#expression"
2043- }
2044- ]
2045- },
2046- "switch-statement": {
2047- "name": "switch-statement.expr.ts",
2048- "begin": "(?<!\\.|\\$)(?=\\bswitch\\s*\\()",
2049- "end": "}",
2050- "endCaptures": {
2051- "0": {
2052- "name": "punctuation.definition.block.ts"
2053- }
2054- },
2055- "patterns": [
2056- {
2057- "include": "#switch-expression"
2058- },
2059- {
2060- "include": "#switch-block"
2061- }
2062- ]
2063- },
2064- "support-objects": {
2065- "patterns": [
2066- {
2067- "name": "variable.language.arguments.ts",
2068- "match": "(?<!\\.|\\$)\\b(arguments)\\b(?!\\$)"
2069- },
2070- {
2071- "name": "support.class.builtin.ts",
2072- "match": "(?x)(?<!\\.|\\$)\\b(Array|ArrayBuffer|Atomics|Boolean|DataView|Date|Float32Array|Float64Array|Function|Generator |GeneratorFunction|Int8Array|Int16Array|Int32Array|Intl|Map|Number|Object|Promise|Proxy |Reflect|RegExp|Set|SharedArrayBuffer|SIMD|String|Symbol|TypedArray |Uint8Array|Uint16Array|Uint32Array|Uint8ClampedArray|WeakMap|WeakSet)\\b(?!\\$)"
2073- },
2074- {
2075- "name": "support.class.error.ts",
2076- "match": "(?<!\\.|\\$)\\b((Eval|Internal|Range|Reference|Syntax|Type|URI)?Error)\\b(?!\\$)"
2077- },
2078- {
2079- "name": "support.function.ts",
2080- "match": "(?x)(?<!\\.|\\$)\\b(clear(Interval|Timeout)|decodeURI|decodeURIComponent|encodeURI|encodeURIComponent|escape|eval| isFinite|isNaN|parseFloat|parseInt|require|set(Interval|Timeout)|super|unescape|uneval)(?=\\s*\\()"
2081- },
2082- {
2083- "match": "(?x)(?<!\\.|\\$)\\b(Math)(?:\\s*(\\.)\\s*(?:\n (abs|acos|acosh|asin|asinh|atan|atan2|atanh|cbrt|ceil|clz32|cos|cosh|exp|\n expm1|floor|fround|hypot|imul|log|log10|log1p|log2|max|min|pow|random|\n round|sign|sin|sinh|sqrt|tan|tanh|trunc)\n |\n (E|LN10|LN2|LOG10E|LOG2E|PI|SQRT1_2|SQRT2)))?\\b(?!\\$)",
2084- "captures": {
2085- "1": {
2086- "name": "support.constant.math.ts"
2087- },
2088- "2": {
2089- "name": "punctuation.accessor.ts"
2090- },
2091- "3": {
2092- "name": "support.function.math.ts"
2093- },
2094- "4": {
2095- "name": "support.constant.property.math.ts"
2096- }
2097- }
2098- },
2099- {
2100- "match": "(?x)(?<!\\.|\\$)\\b(console)(?:\\s*(\\.)\\s*(\n assert|clear|count|debug|dir|error|group|groupCollapsed|groupEnd|info|log\n |profile|profileEnd|table|time|timeEnd|timeStamp|trace|warn))?\\b(?!\\$)",
2101- "captures": {
2102- "1": {
2103- "name": "support.class.console.ts"
2104- },
2105- "2": {
2106- "name": "punctuation.accessor.ts"
2107- },
2108- "3": {
2109- "name": "support.function.console.ts"
2110- }
2111- }
2112- },
2113- {
2114- "match": "(?<!\\.|\\$)\\b(JSON)(?:\\s*(\\.)\\s*(parse|stringify))?\\b(?!\\$)",
2115- "captures": {
2116- "1": {
2117- "name": "support.constant.json.ts"
2118- },
2119- "2": {
2120- "name": "punctuation.accessor.ts"
2121- },
2122- "3": {
2123- "name": "support.function.json.ts"
2124- }
2125- }
2126- },
2127- {
2128- "match": "(?x) (\\.) \\s* (?:\n (constructor|length|prototype|__proto__) \n |\n (EPSILON|MAX_SAFE_INTEGER|MAX_VALUE|MIN_SAFE_INTEGER|MIN_VALUE|NEGATIVE_INFINITY|POSITIVE_INFINITY))\\b(?!\\$)",
2129- "captures": {
2130- "1": {
2131- "name": "punctuation.accessor.ts"
2132- },
2133- "2": {
2134- "name": "support.variable.property.ts"
2135- },
2136- "3": {
2137- "name": "support.constant.ts"
2138- }
2139- }
2140- },
2141- {
2142- "match": "(?x) (?<!\\.|\\$) \\b (?:\n (document|event|navigator|performance|screen|window) \n |\n (AnalyserNode|ArrayBufferView|Attr|AudioBuffer|AudioBufferSourceNode|AudioContext|AudioDestinationNode|AudioListener\n |AudioNode|AudioParam|BatteryManager|BeforeUnloadEvent|BiquadFilterNode|Blob|BufferSource|ByteString|CSS|CSSConditionRule\n |CSSCounterStyleRule|CSSGroupingRule|CSSMatrix|CSSMediaRule|CSSPageRule|CSSPrimitiveValue|CSSRule|CSSRuleList|CSSStyleDeclaration\n |CSSStyleRule|CSSStyleSheet|CSSSupportsRule|CSSValue|CSSValueList|CanvasGradient|CanvasImageSource|CanvasPattern\n |CanvasRenderingContext2D|ChannelMergerNode|ChannelSplitterNode|CharacterData|ChromeWorker|CloseEvent|Comment|CompositionEvent\n |Console|ConvolverNode|Coordinates|Credential|CredentialsContainer|Crypto|CryptoKey|CustomEvent|DOMError|DOMException\n |DOMHighResTimeStamp|DOMImplementation|DOMString|DOMStringList|DOMStringMap|DOMTimeStamp|DOMTokenList|DataTransfer\n |DataTransferItem|DataTransferItemList|DedicatedWorkerGlobalScope|DelayNode|DeviceProximityEvent|DirectoryEntry\n |DirectoryEntrySync|DirectoryReader|DirectoryReaderSync|Document|DocumentFragment|DocumentTouch|DocumentType|DragEvent\n |DynamicsCompressorNode|Element|Entry|EntrySync|ErrorEvent|Event|EventListener|EventSource|EventTarget|FederatedCredential\n |FetchEvent|File|FileEntry|FileEntrySync|FileException|FileList|FileReader|FileReaderSync|FileSystem|FileSystemSync\n |FontFace|FormData|GainNode|Gamepad|GamepadButton|GamepadEvent|Geolocation|GlobalEventHandlers|HTMLAnchorElement\n |HTMLAreaElement|HTMLAudioElement|HTMLBRElement|HTMLBaseElement|HTMLBodyElement|HTMLButtonElement|HTMLCanvasElement\n |HTMLCollection|HTMLContentElement|HTMLDListElement|HTMLDataElement|HTMLDataListElement|HTMLDialogElement|HTMLDivElement\n |HTMLDocument|HTMLElement|HTMLEmbedElement|HTMLFieldSetElement|HTMLFontElement|HTMLFormControlsCollection|HTMLFormElement\n |HTMLHRElement|HTMLHeadElement|HTMLHeadingElement|HTMLHtmlElement|HTMLIFrameElement|HTMLImageElement|HTMLInputElement\n |HTMLKeygenElement|HTMLLIElement|HTMLLabelElement|HTMLLegendElement|HTMLLinkElement|HTMLMapElement|HTMLMediaElement\n |HTMLMetaElement|HTMLMeterElement|HTMLModElement|HTMLOListElement|HTMLObjectElement|HTMLOptGroupElement|HTMLOptionElement\n |HTMLOptionsCollection|HTMLOutputElement|HTMLParagraphElement|HTMLParamElement|HTMLPreElement|HTMLProgressElement\n |HTMLQuoteElement|HTMLScriptElement|HTMLSelectElement|HTMLShadowElement|HTMLSourceElement|HTMLSpanElement|HTMLStyleElement\n |HTMLTableCaptionElement|HTMLTableCellElement|HTMLTableColElement|HTMLTableDataCellElement|HTMLTableElement|HTMLTableHeaderCellElement\n |HTMLTableRowElement|HTMLTableSectionElement|HTMLTextAreaElement|HTMLTimeElement|HTMLTitleElement|HTMLTrackElement\n |HTMLUListElement|HTMLUnknownElement|HTMLVideoElement|HashChangeEvent|History|IDBCursor|IDBCursorWithValue|IDBDatabase\n |IDBEnvironment|IDBFactory|IDBIndex|IDBKeyRange|IDBMutableFile|IDBObjectStore|IDBOpenDBRequest|IDBRequest|IDBTransaction\n |IDBVersionChangeEvent|IIRFilterNode|IdentityManager|ImageBitmap|ImageBitmapFactories|ImageData|Index|InputDeviceCapabilities\n |InputEvent|InstallEvent|InstallTrigger|KeyboardEvent|LinkStyle|LocalFileSystem|LocalFileSystemSync|Location|MIDIAccess\n |MIDIConnectionEvent|MIDIInput|MIDIInputMap|MIDIOutputMap|MediaElementAudioSourceNode|MediaError|MediaKeyMessageEvent\n |MediaKeySession|MediaKeyStatusMap|MediaKeySystemAccess|MediaKeySystemConfiguration|MediaKeys|MediaRecorder|MediaStream\n |MediaStreamAudioDestinationNode|MediaStreamAudioSourceNode|MessageChannel|MessageEvent|MessagePort|MouseEvent\n |MutationObserver|MutationRecord|NamedNodeMap|Navigator|NavigatorConcurrentHardware|NavigatorGeolocation|NavigatorID\n |NavigatorLanguage|NavigatorOnLine|Node|NodeFilter|NodeIterator|NodeList|NonDocumentTypeChildNode|Notification\n |OfflineAudioCompletionEvent|OfflineAudioContext|OscillatorNode|PageTransitionEvent|PannerNode|ParentNode|PasswordCredential\n |Path2D|PaymentAddress|PaymentRequest|PaymentResponse|Performance|PerformanceEntry|PerformanceFrameTiming|PerformanceMark\n |PerformanceMeasure|PerformanceNavigation|PerformanceNavigationTiming|PerformanceObserver|PerformanceObserverEntryList\n |PerformanceResourceTiming|PerformanceTiming|PeriodicSyncEvent|PeriodicWave|Plugin|Point|PointerEvent|PopStateEvent\n |PortCollection|Position|PositionError|PositionOptions|PresentationConnectionClosedEvent|PresentationConnectionList\n |PresentationReceiver|ProcessingInstruction|ProgressEvent|PromiseRejectionEvent|PushEvent|PushRegistrationManager\n |RTCCertificate|RTCConfiguration|RTCPeerConnection|RTCSessionDescriptionCallback|RTCStatsReport|RadioNodeList|RandomSource\n |Range|ReadableByteStream|RenderingContext|SVGAElement|SVGAngle|SVGAnimateColorElement|SVGAnimateElement|SVGAnimateMotionElement\n |SVGAnimateTransformElement|SVGAnimatedAngle|SVGAnimatedBoolean|SVGAnimatedEnumeration|SVGAnimatedInteger|SVGAnimatedLength\n |SVGAnimatedLengthList|SVGAnimatedNumber|SVGAnimatedNumberList|SVGAnimatedPoints|SVGAnimatedPreserveAspectRatio\n |SVGAnimatedRect|SVGAnimatedString|SVGAnimatedTransformList|SVGAnimationElement|SVGCircleElement|SVGClipPathElement\n |SVGCursorElement|SVGDefsElement|SVGDescElement|SVGElement|SVGEllipseElement|SVGEvent|SVGFilterElement|SVGFontElement\n |SVGFontFaceElement|SVGFontFaceFormatElement|SVGFontFaceNameElement|SVGFontFaceSrcElement|SVGFontFaceUriElement\n |SVGForeignObjectElement|SVGGElement|SVGGlyphElement|SVGGradientElement|SVGHKernElement|SVGImageElement|SVGLength\n |SVGLengthList|SVGLineElement|SVGLinearGradientElement|SVGMPathElement|SVGMaskElement|SVGMatrix|SVGMissingGlyphElement\n |SVGNumber|SVGNumberList|SVGPathElement|SVGPatternElement|SVGPoint|SVGPolygonElement|SVGPolylineElement|SVGPreserveAspectRatio\n |SVGRadialGradientElement|SVGRect|SVGRectElement|SVGSVGElement|SVGScriptElement|SVGSetElement|SVGStopElement|SVGStringList\n |SVGStylable|SVGStyleElement|SVGSwitchElement|SVGSymbolElement|SVGTRefElement|SVGTSpanElement|SVGTests|SVGTextElement\n |SVGTextPositioningElement|SVGTitleElement|SVGTransform|SVGTransformList|SVGTransformable|SVGUseElement|SVGVKernElement\n |SVGViewElement|ServiceWorker|ServiceWorkerContainer|ServiceWorkerGlobalScope|ServiceWorkerRegistration|ServiceWorkerState\n |ShadowRoot|SharedWorker|SharedWorkerGlobalScope|SourceBufferList|StereoPannerNode|Storage|StorageEvent|StyleSheet\n |StyleSheetList|SubtleCrypto|SyncEvent|Text|TextMetrics|TimeEvent|TimeRanges|Touch|TouchEvent|TouchList|Transferable\n |TreeWalker|UIEvent|USVString|VRDisplayCapabilities|ValidityState|WaveShaperNode|WebGL|WebGLActiveInfo|WebGLBuffer\n |WebGLContextEvent|WebGLFramebuffer|WebGLProgram|WebGLRenderbuffer|WebGLRenderingContext|WebGLShader|WebGLShaderPrecisionFormat\n |WebGLTexture|WebGLTimerQueryEXT|WebGLTransformFeedback|WebGLUniformLocation|WebGLVertexArrayObject|WebGLVertexArrayObjectOES\n |WebSocket|WebSockets|WebVTT|WheelEvent|Window|WindowBase64|WindowEventHandlers|WindowTimers|Worker|WorkerGlobalScope\n |WorkerLocation|WorkerNavigator|XMLHttpRequest|XMLHttpRequestEventTarget|XMLSerializer|XPathExpression|XPathResult\n |XSLTProcessor))\\b(?!\\$)",
2143- "captures": {
2144- "1": {
2145- "name": "support.variable.dom.ts"
2146- },
2147- "2": {
2148- "name": "support.class.dom.ts"
2149- }
2150- }
2151- },
2152- {
2153- "match": "(?x) (\\.) \\s* (?:\n (ATTRIBUTE_NODE|CDATA_SECTION_NODE|COMMENT_NODE|DOCUMENT_FRAGMENT_NODE|DOCUMENT_NODE|DOCUMENT_TYPE_NODE\n |DOMSTRING_SIZE_ERR|ELEMENT_NODE|ENTITY_NODE|ENTITY_REFERENCE_NODE|HIERARCHY_REQUEST_ERR|INDEX_SIZE_ERR\n |INUSE_ATTRIBUTE_ERR|INVALID_CHARACTER_ERR|NO_DATA_ALLOWED_ERR|NO_MODIFICATION_ALLOWED_ERR|NOT_FOUND_ERR\n |NOT_SUPPORTED_ERR|NOTATION_NODE|PROCESSING_INSTRUCTION_NODE|TEXT_NODE|WRONG_DOCUMENT_ERR)\n |\n (_content|[xyz]|abbr|above|accept|acceptCharset|accessKey|action|align|[av]Link(?:color)?|all|alt|anchors|appCodeName\n |appCore|applets|appMinorVersion|appName|appVersion|archive|areas|arguments|attributes|availHeight|availLeft|availTop\n |availWidth|axis|background|backgroundColor|backgroundImage|below|bgColor|body|border|borderBottomWidth|borderColor\n |borderLeftWidth|borderRightWidth|borderStyle|borderTopWidth|borderWidth|bottom|bufferDepth|callee|caller|caption\n |cellPadding|cells|cellSpacing|ch|characterSet|charset|checked|childNodes|chOff|cite|classes|className|clear\n |clientInformation|clip|clipBoardData|closed|code|codeBase|codeType|color|colorDepth|cols|colSpan|compact|complete\n |components|content|controllers|cookie|cookieEnabled|cords|cpuClass|crypto|current|data|dateTime|declare|defaultCharset\n |defaultChecked|defaultSelected|defaultStatus|defaultValue|defaultView|defer|description|dialogArguments|dialogHeight\n |dialogLeft|dialogTop|dialogWidth|dir|directories|disabled|display|docmain|doctype|documentElement|elements|embeds\n |enabledPlugin|encoding|enctype|entities|event|expando|external|face|fgColor|filename|firstChild|fontFamily|fontSize\n |fontWeight|form|formName|forms|frame|frameBorder|frameElement|frames|hasFocus|hash|headers|height|history|host\n |hostname|href|hreflang|hspace|htmlFor|httpEquiv|id|ids|ignoreCase|images|implementation|index|innerHeight|innerWidth\n |input|isMap|label|lang|language|lastChild|lastIndex|lastMatch|lastModified|lastParen|layer[sXY]|left|leftContext\n |lineHeight|link|linkColor|links|listStyleType|localName|location|locationbar|longDesc|lowsrc|lowSrc|marginBottom\n |marginHeight|marginLeft|marginRight|marginTop|marginWidth|maxLength|media|menubar|method|mimeTypes|multiline|multiple\n |name|nameProp|namespaces|namespaceURI|next|nextSibling|nodeName|nodeType|nodeValue|noHref|noResize|noShade|notationName\n |notations|noWrap|object|offscreenBuffering|onLine|onreadystatechange|opener|opsProfile|options|oscpu|outerHeight\n |outerWidth|ownerDocument|paddingBottom|paddingLeft|paddingRight|paddingTop|page[XY]|page[XY]Offset|parent|parentLayer\n |parentNode|parentWindow|pathname|personalbar|pixelDepth|pkcs11|platform|plugins|port|prefix|previous|previousDibling\n |product|productSub|profile|profileend|prompt|prompter|protocol|publicId|readOnly|readyState|referrer|rel|responseText\n |responseXML|rev|right|rightContext|rowIndex|rows|rowSpan|rules|scheme|scope|screen[XY]|screenLeft|screenTop|scripts\n |scrollbars|scrolling|sectionRowIndex|security|securityPolicy|selected|selectedIndex|selection|self|shape|siblingAbove\n |siblingBelow|size|source|specified|standby|start|status|statusbar|statusText|style|styleSheets|suffixes|summary\n |systemId|systemLanguage|tagName|tags|target|tBodies|text|textAlign|textDecoration|textIndent|textTransform|tFoot|tHead\n |title|toolbar|top|type|undefined|uniqueID|updateInterval|URL|URLUnencoded|useMap|userAgent|userLanguage|userProfile\n |vAlign|value|valueType|vendor|vendorSub|version|visibility|vspace|whiteSpace|width|X[MS]LDocument|zIndex))\\b(?!\\$|\\s*(<([^<>]|\\<[^<>]+\\>)+>\\s*)?\\()",
2154- "captures": {
2155- "1": {
2156- "name": "punctuation.accessor.ts"
2157- },
2158- "2": {
2159- "name": "support.constant.dom.ts"
2160- },
2161- "3": {
2162- "name": "support.variable.property.dom.ts"
2163- }
2164- }
2165- },
2166- {
2167- "name": "support.class.node.ts",
2168- "match": "(?x)(?<!\\.|\\$)\\b(Buffer|EventEmitter|Server|Pipe|Socket|REPLServer|ReadStream|WriteStream|Stream\n |Inflate|Deflate|InflateRaw|DeflateRaw|GZip|GUnzip|Unzip|Zip)\\b(?!\\$)"
2169- },
2170- {
2171- "name": "support.module.node.ts",
2172- "match": "(?x)(?<!\\.|\\$)\\b(assert|buffer|child_process|cluster|constants|crypto|dgram|dns|domain|events|fs|http|https|net\n |os|path|punycode|querystring|readline|repl|stream|string_decoder|timers|tls|tty|url|util|vm|zlib)\\b(?!\\$)"
2173- },
2174- {
2175- "match": "(?x)(?<!\\.|\\$)\\b(process)(?:(\\.)(?:\n (arch|argv|config|connected|env|execArgv|execPath|exitCode|mainModule|pid|platform|release|stderr|stdin|stdout|title|version|versions)\n |\n (abort|chdir|cwd|disconnect|exit|[sg]ete?[gu]id|send|[sg]etgroups|initgroups|kill|memoryUsage|nextTick|umask|uptime|hrtime)\n))?\\b(?!\\$)",
2176- "captures": {
2177- "1": {
2178- "name": "support.variable.object.process.ts"
2179- },
2180- "2": {
2181- "name": "punctuation.accessor.ts"
2182- },
2183- "3": {
2184- "name": "support.variable.property.process.ts"
2185- },
2186- "4": {
2187- "name": "support.function.process.ts"
2188- }
2189- }
2190- },
2191- {
2192- "match": "(?<!\\.|\\$)\\b(?:(exports)|(module)(?:(\\.)(exports|id|filename|loaded|parent|children))?)\\b(?!\\$)",
2193- "captures": {
2194- "1": {
2195- "name": "support.type.object.module.ts"
2196- },
2197- "2": {
2198- "name": "support.type.object.module.ts"
2199- },
2200- "3": {
2201- "name": "punctuation.accessor.ts"
2202- },
2203- "4": {
2204- "name": "support.type.object.module.ts"
2205- }
2206- }
2207- },
2208- {
2209- "name": "support.variable.object.node.ts",
2210- "match": "(?<!\\.|\\$)\\b(global|GLOBAL|root|__dirname|__filename)\\b(?!\\$)"
2211- },
2212- {
2213- "match": "(?x) (\\.) \\s* \n(?:\n (on(?:Rowsinserted|Rowsdelete|Rowenter|Rowexit|Resize|Resizestart|Resizeend|Reset|\n Readystatechange|Mouseout|Mouseover|Mousedown|Mouseup|Mousemove|\n Before(?:cut|deactivate|unload|update|paste|print|editfocus|activate)|\n Blur|Scrolltop|Submit|Select|Selectstart|Selectionchange|Hover|Help|\n Change|Contextmenu|Controlselect|Cut|Cellchange|Clock|Close|Deactivate|\n Datasetchanged|Datasetcomplete|Dataavailable|Drop|Drag|Dragstart|Dragover|\n Dragdrop|Dragenter|Dragend|Dragleave|Dblclick|Unload|Paste|Propertychange|Error|\n Errorupdate|Keydown|Keyup|Keypress|Focus|Load|Activate|Afterupdate|Afterprint|Abort)\n ) |\n (shift|showModelessDialog|showModalDialog|showHelp|scroll|scrollX|scrollByPages|\n scrollByLines|scrollY|scrollTo|stop|strike|sizeToContent|sidebar|signText|sort|\n sup|sub|substr|substring|splice|split|send|set(?:Milliseconds|Seconds|Minutes|Hours|\n Month|Year|FullYear|Date|UTC(?:Milliseconds|Seconds|Minutes|Hours|Month|FullYear|Date)|\n Time|Hotkeys|Cursor|ZOptions|Active|Resizable|RequestHeader)|search|slice|\n savePreferences|small|home|handleEvent|navigate|char|charCodeAt|charAt|concat|\n contextual|confirm|compile|clear|captureEvents|call|createStyleSheet|createPopup|\n createEventObject|to(?:GMTString|UTCString|String|Source|UpperCase|LowerCase|LocaleString)|\n test|taint|taintEnabled|indexOf|italics|disableExternalCapture|dump|detachEvent|unshift|\n untaint|unwatch|updateCommands|join|javaEnabled|pop|push|plugins.refresh|paddings|parse|\n print|prompt|preference|enableExternalCapture|exec|execScript|valueOf|UTC|find|file|\n fileModifiedDate|fileSize|fileCreatedDate|fileUpdatedDate|fixed|fontsize|fontcolor|\n forward|fromCharCode|watch|link|load|lastIndexOf|anchor|attachEvent|atob|apply|alert|\n abort|routeEvents|resize|resizeBy|resizeTo|recalc|returnValue|replace|reverse|reload|\n releaseCapture|releaseEvents|go|get(?:Milliseconds|Seconds|Minutes|Hours|Month|Day|Year|FullYear|\n Time|Date|TimezoneOffset|UTC(?:Milliseconds|Seconds|Minutes|Hours|Day|Month|FullYear|Date)|\n Attention|Selection|ResponseHeader|AllResponseHeaders)|moveBy|moveBelow|moveTo|\n moveToAbsolute|moveAbove|mergeAttributes|match|margins|btoa|big|bold|borderWidths|blink|back\n ) |\n (acceptNode|add|addEventListener|addTextTrack|adoptNode|after|animate|append|\n appendChild|appendData|before|blur|canPlayType|captureStream|\n caretPositionFromPoint|caretRangeFromPoint|checkValidity|clear|click|\n cloneContents|cloneNode|cloneRange|close|closest|collapse|\n compareBoundaryPoints|compareDocumentPosition|comparePoint|contains|\n convertPointFromNode|convertQuadFromNode|convertRectFromNode|createAttribute|\n createAttributeNS|createCaption|createCDATASection|createComment|\n createContextualFragment|createDocument|createDocumentFragment|\n createDocumentType|createElement|createElementNS|createEntityReference|\n createEvent|createExpression|createHTMLDocument|createNodeIterator|\n createNSResolver|createProcessingInstruction|createRange|createShadowRoot|\n createTBody|createTextNode|createTFoot|createTHead|createTreeWalker|delete|\n deleteCaption|deleteCell|deleteContents|deleteData|deleteRow|deleteTFoot|\n deleteTHead|detach|disconnect|dispatchEvent|elementFromPoint|elementsFromPoint|\n enableStyleSheetsForSet|entries|evaluate|execCommand|exitFullscreen|\n exitPointerLock|expand|extractContents|fastSeek|firstChild|focus|forEach|get|\n getAll|getAnimations|getAttribute|getAttributeNames|getAttributeNode|\n getAttributeNodeNS|getAttributeNS|getBoundingClientRect|getBoxQuads|\n getClientRects|getContext|getDestinationInsertionPoints|getElementById|\n getElementsByClassName|getElementsByName|getElementsByTagName|\n getElementsByTagNameNS|getItem|getNamedItem|getSelection|getStartDate|\n getVideoPlaybackQuality|has|hasAttribute|hasAttributeNS|hasAttributes|\n hasChildNodes|hasFeature|hasFocus|importNode|initEvent|insertAdjacentElement|\n insertAdjacentHTML|insertAdjacentText|insertBefore|insertCell|insertData|\n insertNode|insertRow|intersectsNode|isDefaultNamespace|isEqualNode|\n isPointInRange|isSameNode|item|key|keys|lastChild|load|lookupNamespaceURI|\n lookupPrefix|matches|move|moveAttribute|moveAttributeNode|moveChild|\n moveNamedItem|namedItem|nextNode|nextSibling|normalize|observe|open|\n parentNode|pause|play|postMessage|prepend|preventDefault|previousNode|\n previousSibling|probablySupportsContext|queryCommandEnabled|\n queryCommandIndeterm|queryCommandState|queryCommandSupported|queryCommandValue|\n querySelector|querySelectorAll|registerContentHandler|registerElement|\n registerProtocolHandler|releaseCapture|releaseEvents|remove|removeAttribute|\n removeAttributeNode|removeAttributeNS|removeChild|removeEventListener|\n removeItem|replace|replaceChild|replaceData|replaceWith|reportValidity|\n requestFullscreen|requestPointerLock|reset|scroll|scrollBy|scrollIntoView|\n scrollTo|seekToNextFrame|select|selectNode|selectNodeContents|set|setAttribute|\n setAttributeNode|setAttributeNodeNS|setAttributeNS|setCapture|\n setCustomValidity|setEnd|setEndAfter|setEndBefore|setItem|setNamedItem|\n setRangeText|setSelectionRange|setSinkId|setStart|setStartAfter|setStartBefore|\n slice|splitText|stepDown|stepUp|stopImmediatePropagation|stopPropagation|\n submit|substringData|supports|surroundContents|takeRecords|terminate|toBlob|\n toDataURL|toggle|toString|values|write|writeln\n )\n)(?=\\s*\\()",
2214- "captures": {
2215- "1": {
2216- "name": "punctuation.accessor.ts"
2217- },
2218- "2": {
2219- "name": "support.function.event-handler.ts"
2220- },
2221- "3": {
2222- "name": "support.function.ts"
2223- },
2224- "4": {
2225- "name": "support.function.dom.ts"
2226- }
2227- }
2228- }
2229- ]
2230- },
2231- "function-call": {
2232- "begin": "(?=(\\.\\s*)?([_$[:alpha:]][_$[:alnum:]]*)\\s*(<([^<>]|\\<[^<>]+\\>)+>\\s*)?\\()",
2233- "end": "(?<=\\))(?!(\\.\\s*)?([_$[:alpha:]][_$[:alnum:]]*)\\s*(<([^<>]|\\<[^<>]+\\>)+>\\s*)?\\()",
2234- "patterns": [
2235- {
2236- "include": "#support-objects"
2237- },
2238- {
2239- "name": "punctuation.accessor.ts",
2240- "match": "\\."
2241- },
2242- {
2243- "name": "entity.name.function.ts",
2244- "match": "([_$[:alpha:]][_$[:alnum:]]*)"
2245- },
2246- {
2247- "include": "#comment"
2248- },
2249- {
2250- "name": "meta.type.parameters.ts",
2251- "begin": "\\<",
2252- "beginCaptures": {
2253- "0": {
2254- "name": "punctuation.definition.typeparameters.begin.ts"
2255- }
2256- },
2257- "end": "\\>",
2258- "endCaptures": {
2259- "0": {
2260- "name": "punctuation.definition.typeparameters.end.ts"
2261- }
2262- },
2263- "patterns": [
2264- {
2265- "include": "#type"
2266- },
2267- {
2268- "include": "#punctuation-comma"
2269- }
2270- ]
2271- },
2272- {
2273- "include": "#paren-expression"
2274- }
2275- ]
2276- },
2277- "identifiers": {
2278- "patterns": [
2279- {
2280- "name": "support.class.ts",
2281- "match": "([_$[:alpha:]][_$[:alnum:]]*)(?=\\s*\\.\\s*prototype\\b(?!\\$))"
2282- },
2283- {
2284- "match": "(?x)(\\.)\\s*(?:\n ([[:upper:]][_$[:digit:][:upper:]]*) |\n ([_$[:alpha:]][_$[:alnum:]]*)\n)(?=\\s*\\.\\s*[_$[:alpha:]][_$[:alnum:]]*)",
2285- "captures": {
2286- "1": {
2287- "name": "punctuation.accessor.ts"
2288- },
2289- "2": {
2290- "name": "constant.other.object.property.ts"
2291- },
2292- "3": {
2293- "name": "variable.other.object.property.ts"
2294- }
2295- }
2296- },
2297- {
2298- "match": "(?x)(?:(\\.)\\s*)?([_$[:alpha:]][_$[:alnum:]]*)(?=\\s*=\\s*( (async\\s+)|(function\\s*[(<])|(function\\s+)| ([_$[:alpha:]][_$[:alnum:]]*\\s*=>)| ((<([^<>]|\\<[^<>]+\\>)+>\\s*)?\\(([^()]|\\([^()]*\\))*\\)(\\s*:\\s*(.)*)?\\s*=>)))",
2299- "captures": {
2300- "1": {
2301- "name": "punctuation.accessor.ts"
2302- },
2303- "2": {
2304- "name": "entity.name.function.ts"
2305- }
2306- }
2307- },
2308- {
2309- "match": "(\\.)\\s*([[:upper:]][_$[:digit:][:upper:]]*)(?![_$[:alnum:]])",
2310- "captures": {
2311- "1": {
2312- "name": "punctuation.accessor.ts"
2313- },
2314- "2": {
2315- "name": "constant.other.property.ts"
2316- }
2317- }
2318- },
2319- {
2320- "match": "(\\.)\\s*([_$[:alpha:]][_$[:alnum:]]*)",
2321- "captures": {
2322- "1": {
2323- "name": "punctuation.accessor.ts"
2324- },
2325- "2": {
2326- "name": "variable.other.property.ts"
2327- }
2328- }
2329- },
2330- {
2331- "match": "(?x)(?:\n ([[:upper:]][_$[:digit:][:upper:]]*) |\n ([_$[:alpha:]][_$[:alnum:]]*)\n)(?=\\s*\\.\\s*[_$[:alpha:]][_$[:alnum:]]*)",
2332- "captures": {
2333- "1": {
2334- "name": "constant.other.object.ts"
2335- },
2336- "2": {
2337- "name": "variable.other.object.ts"
2338- }
2339- }
2340- },
2341- {
2342- "name": "constant.other.ts",
2343- "match": "([[:upper:]][_$[:digit:][:upper:]]*)(?![_$[:alnum:]])"
2344- },
2345- {
2346- "name": "variable.other.readwrite.ts",
2347- "match": "[_$[:alpha:]][_$[:alnum:]]*"
2348- }
2349- ]
2350- },
2351- "cast": {
2352- "name": "cast.expr.ts",
2353- "begin": "(?:(?<=return|throw|yield|await|default|[=(,:>*]))\\s*(<)(?!<?\\=)",
2354- "beginCaptures": {
2355- "1": {
2356- "name": "meta.brace.angle.ts"
2357- }
2358- },
2359- "end": ">",
2360- "endCaptures": {
2361- "0": {
2362- "name": "meta.brace.angle.ts"
2363- }
2364- },
2365- "patterns": [
2366- {
2367- "include": "#type"
2368- }
2369- ]
2370- },
2371- "new-expr": {
2372- "name": "new.expr.ts",
2373- "begin": "(?<!\\.|\\$)\\b(new)\\b(?!\\$)",
2374- "beginCaptures": {
2375- "1": {
2376- "name": "keyword.operator.new.ts"
2377- }
2378- },
2379- "end": "(?<=\\))|(?=[;),]|$|((?<!\\.|\\$)\\bnew\\b(?!\\$)))",
2380- "patterns": [
2381- {
2382- "include": "#paren-expression"
2383- },
2384- {
2385- "include": "#class-or-interface-declaration"
2386- },
2387- {
2388- "include": "#type"
2389- }
2390- ]
2391- },
2392- "object-member": {
2393- "patterns": [
2394- {
2395- "include": "#comment"
2396- },
2397- {
2398- "include": "#method-declaration"
2399- },
2400- {
2401- "name": "meta.object.member.ts",
2402- "begin": "(?=(?:(?:\\'[^']*\\')|(?:\\\"[^\"]*\\\")|(?:\\[([^\\[\\]]|\\[[^\\[\\]]+\\])+\\]))\\s*:)",
2403- "end": "(?=,|\\})",
2404- "patterns": [
2405- {
2406- "name": "meta.object-literal.key.ts",
2407- "begin": "(?=(?:(?:\\'[^']*\\')|(?:\\\"[^\"]*\\\")|(?:\\[([^\\[\\]]|\\[[^\\[\\]]+\\])+\\]))\\s*:)",
2408- "end": ":",
2409- "endCaptures": {
2410- "0": {
2411- "name": "punctuation.separator.key-value.ts"
2412- }
2413- },
2414- "patterns": [
2415- {
2416- "include": "#string"
2417- },
2418- {
2419- "include": "#array-literal"
2420- }
2421- ]
2422- },
2423- {
2424- "include": "#expression"
2425- }
2426- ]
2427- },
2428- {
2429- "name": "meta.object.member.ts",
2430- "begin": "(?x)(?:([_$[:alpha:]][_$[:alnum:]]*)\\s*(:)(?=\\s*( (async\\s+)|(function\\s*[(<])|(function\\s+)| ([_$[:alpha:]][_$[:alnum:]]*\\s*=>)| ((<([^<>]|\\<[^<>]+\\>)+>\\s*)?\\(([^()]|\\([^()]*\\))*\\)(\\s*:\\s*(.)*)?\\s*=>))))",
2431- "beginCaptures": {
2432- "0": {
2433- "name": "meta.object-literal.key.ts"
2434- },
2435- "1": {
2436- "name": "entity.name.function.ts"
2437- },
2438- "2": {
2439- "name": "punctuation.separator.key-value.ts"
2440- }
2441- },
2442- "end": "(?=,|\\})",
2443- "patterns": [
2444- {
2445- "include": "#expression"
2446- }
2447- ]
2448- },
2449- {
2450- "name": "meta.object.member.ts",
2451- "begin": "(?:[_$[:alpha:]][_$[:alnum:]]*)\\s*(:)",
2452- "beginCaptures": {
2453- "0": {
2454- "name": "meta.object-literal.key.ts"
2455- },
2456- "1": {
2457- "name": "punctuation.separator.key-value.ts"
2458- }
2459- },
2460- "end": "(?=,|\\})",
2461- "patterns": [
2462- {
2463- "include": "#expression"
2464- }
2465- ]
2466- },
2467- {
2468- "name": "meta.object.member.ts",
2469- "begin": "\\.\\.\\.",
2470- "beginCaptures": {
2471- "0": {
2472- "name": "keyword.operator.spread.ts"
2473- }
2474- },
2475- "end": "(?=,|\\})",
2476- "patterns": [
2477- {
2478- "include": "#expression"
2479- }
2480- ]
2481- },
2482- {
2483- "name": "meta.object.member.ts",
2484- "match": "([_$[:alpha:]][_$[:alnum:]]*)\\s*(?=,|\\}|$)",
2485- "captures": {
2486- "1": {
2487- "name": "variable.other.readwrite.ts"
2488- }
2489- }
2490- },
2491- {
2492- "include": "#punctuation-comma"
2493- }
2494- ]
2495- },
2496- "expression-operators": {
2497- "patterns": [
2498- {
2499- "name": "keyword.control.flow.ts",
2500- "match": "(?<!\\.|\\$)\\b(await)\\b(?!\\$)"
2501- },
2502- {
2503- "name": "keyword.operator.expression.delete.ts",
2504- "match": "(?<!\\.|\\$)\\bdelete\\b(?!\\$)"
2505- },
2506- {
2507- "name": "keyword.operator.expression.in.ts",
2508- "match": "(?<!\\.|\\$)\\bin\\b(?!\\$)"
2509- },
2510- {
2511- "name": "keyword.operator.expression.of.ts",
2512- "match": "(?<!\\.|\\$)\\bof\\b(?!\\$)"
2513- },
2514- {
2515- "name": "keyword.operator.expression.instanceof.ts",
2516- "match": "(?<!\\.|\\$)\\binstanceof\\b(?!\\$)"
2517- },
2518- {
2519- "name": "keyword.operator.new.ts",
2520- "match": "(?<!\\.|\\$)\\bnew\\b(?!\\$)"
2521- },
2522- {
2523- "include": "#typeof-operator"
2524- },
2525- {
2526- "name": "keyword.operator.expression.void.ts",
2527- "match": "(?<!\\.|\\$)\\bvoid\\b(?!\\$)"
2528- },
2529- {
2530- "begin": "(?<!\\.|\\$)\\bas\\b(?!\\$)",
2531- "beginCaptures": {
2532- "0": {
2533- "name": "keyword.control.as.ts"
2534- }
2535- },
2536- "end": "(?=$|[;,:})\\]])",
2537- "patterns": [
2538- {
2539- "include": "#type"
2540- }
2541- ]
2542- },
2543- {
2544- "name": "keyword.operator.spread.ts",
2545- "match": "\\.\\.\\."
2546- },
2547- {
2548- "name": "keyword.operator.assignment.compound.ts",
2549- "match": "\\*=|(?<!\\()/=|%=|\\+=|\\-="
2550- },
2551- {
2552- "name": "keyword.operator.assignment.compound.bitwise.ts",
2553- "match": "\\&=|\\^=|<<=|>>=|>>>=|\\|="
2554- },
2555- {
2556- "name": "keyword.operator.bitwise.shift.ts",
2557- "match": "<<|>>>|>>"
2558- },
2559- {
2560- "name": "keyword.operator.comparison.ts",
2561- "match": "===|!==|==|!="
2562- },
2563- {
2564- "name": "keyword.operator.relational.ts",
2565- "match": "<=|>=|<>|<|>"
2566- },
2567- {
2568- "name": "keyword.operator.logical.ts",
2569- "match": "\\!|&&|\\|\\|"
2570- },
2571- {
2572- "name": "keyword.operator.bitwise.ts",
2573- "match": "\\&|~|\\^|\\|"
2574- },
2575- {
2576- "name": "keyword.operator.assignment.ts",
2577- "match": "\\="
2578- },
2579- {
2580- "name": "keyword.operator.decrement.ts",
2581- "match": "--"
2582- },
2583- {
2584- "name": "keyword.operator.increment.ts",
2585- "match": "\\+\\+"
2586- },
2587- {
2588- "name": "keyword.operator.arithmetic.ts",
2589- "match": "%|\\*|/|-|\\+"
2590- },
2591- {
2592- "match": "(?<=[_$[:alnum:]])\\s*(/)(?![/*])",
2593- "captures": {
2594- "1": {
2595- "name": "keyword.operator.arithmetic.ts"
2596- }
2597- }
2598- }
2599- ]
2600- },
2601- "typeof-operator": {
2602- "name": "keyword.operator.expression.typeof.ts",
2603- "match": "(?<!\\.|\\$)\\btypeof\\b(?!\\$)"
2604- },
2605- "arrow-function": {
2606- "patterns": [
2607- {
2608- "name": "meta.arrow.ts",
2609- "match": "(?<!\\.|\\$)(\\basync)(?=\\s*[<(])",
2610- "captures": {
2611- "1": {
2612- "name": "storage.modifier.async.ts"
2613- }
2614- }
2615- },
2616- {
2617- "name": "meta.arrow.ts",
2618- "match": "(?:(?<!\\.|\\$)(\\basync)\\s*)?([_$[:alpha:]][_$[:alnum:]]*)\\s*(?==>)",
2619- "captures": {
2620- "1": {
2621- "name": "storage.modifier.async.ts"
2622- },
2623- "2": {
2624- "name": "variable.parameter.ts"
2625- }
2626- }
2627- },
2628- {
2629- "name": "meta.arrow.ts",
2630- "begin": "(?x)\\s*(?=(<([^<>]|\\<[^<>]+\\>)+>\\s*)?\\(([^()]|\\([^()]*\\))*\\)(\\s*:\\s*(.)*)?\\s*=>)",
2631- "end": "(?==>)",
2632- "patterns": [
2633- {
2634- "include": "#comment"
2635- },
2636- {
2637- "include": "#type-parameters"
2638- },
2639- {
2640- "include": "#function-parameters"
2641- },
2642- {
2643- "include": "#arrow-return-type"
2644- }
2645- ]
2646- },
2647- {
2648- "name": "meta.arrow.ts",
2649- "begin": "=>",
2650- "beginCaptures": {
2651- "0": {
2652- "name": "storage.type.function.arrow.ts"
2653- }
2654- },
2655- "end": "(?<=\\})|((?!\\{)(?=\\S))",
2656- "patterns": [
2657- {
2658- "include": "#decl-block"
2659- },
2660- {
2661- "include": "#expression"
2662- }
2663- ]
2664- }
2665- ]
2666- },
2667- "arrow-return-type": {
2668- "name": "meta.return.type.arrow.ts",
2669- "begin": "(?<=\\))\\s*(:)",
2670- "beginCaptures": {
2671- "1": {
2672- "name": "keyword.operator.type.annotation.ts"
2673- }
2674- },
2675- "end": "(?<!:)((?=$)|(?==>|;|//))",
2676- "patterns": [
2677- {
2678- "include": "#type-predicate-operator"
2679- },
2680- {
2681- "include": "#type"
2682- }
2683- ]
2684- },
2685- "punctuation-comma": {
2686- "name": "punctuation.separator.comma.ts",
2687- "match": ","
2688- },
2689- "punctuation-semicolon": {
2690- "name": "punctuation.terminator.statement.ts",
2691- "match": ";"
2692- },
2693- "punctuation-accessor": {
2694- "name": "punctuation.accessor.ts",
2695- "match": "\\."
2696- },
2697- "paren-expression": {
2698- "begin": "\\(",
2699- "beginCaptures": {
2700- "0": {
2701- "name": "meta.brace.round.ts"
2702- }
2703- },
2704- "end": "\\)",
2705- "endCaptures": {
2706- "0": {
2707- "name": "meta.brace.round.ts"
2708- }
2709- },
2710- "patterns": [
2711- {
2712- "include": "#expression"
2713- },
2714- {
2715- "include": "#punctuation-comma"
2716- }
2717- ]
2718- },
2719- "qstring-double": {
2720- "name": "string.quoted.double.ts",
2721- "begin": "\"",
2722- "beginCaptures": {
2723- "0": {
2724- "name": "punctuation.definition.string.begin.ts"
2725- }
2726- },
2727- "end": "(\")|((?:[^\\\\\\n])$)",
2728- "endCaptures": {
2729- "1": {
2730- "name": "punctuation.definition.string.end.ts"
2731- },
2732- "2": {
2733- "name": "invalid.illegal.newline.ts"
2734- }
2735- },
2736- "patterns": [
2737- {
2738- "include": "#string-character-escape"
2739- }
2740- ]
2741- },
2742- "qstring-single": {
2743- "name": "string.quoted.single.ts",
2744- "begin": "'",
2745- "beginCaptures": {
2746- "0": {
2747- "name": "punctuation.definition.string.begin.ts"
2748- }
2749- },
2750- "end": "(\\')|((?:[^\\\\\\n])$)",
2751- "endCaptures": {
2752- "1": {
2753- "name": "punctuation.definition.string.end.ts"
2754- },
2755- "2": {
2756- "name": "invalid.illegal.newline.ts"
2757- }
2758- },
2759- "patterns": [
2760- {
2761- "include": "#string-character-escape"
2762- }
2763- ]
2764- },
2765- "regex": {
2766- "patterns": [
2767- {
2768- "name": "string.regex.ts",
2769- "begin": "(?<=[=(:,\\[?+!]|return|case|=>|&&|\\|\\||\\*\\/)\\s*(/)(?![/*])(?=(?:[^/\\\\\\[]|\\\\.|\\[([^\\]\\\\]|\\\\.)+\\])+/(?![/*])[gimy]*(?!\\s*[a-zA-Z0-9_$]))",
2770- "beginCaptures": {
2771- "1": {
2772- "name": "punctuation.definition.string.begin.ts"
2773- }
2774- },
2775- "end": "(/)([gimuy]*)",
2776- "endCaptures": {
2777- "1": {
2778- "name": "punctuation.definition.string.end.ts"
2779- },
2780- "2": {
2781- "name": "keyword.other.ts"
2782- }
2783- },
2784- "patterns": [
2785- {
2786- "include": "#regexp"
2787- }
2788- ]
2789- },
2790- {
2791- "name": "string.regex.ts",
2792- "begin": "/(?![/*])(?=(?:[^/\\\\\\[]|\\\\.|\\[([^\\]\\\\]|\\\\.)+\\])+/(?![/*])[gimy]*(?!\\s*[a-zA-Z0-9_$]))",
2793- "beginCaptures": {
2794- "0": {
2795- "name": "punctuation.definition.string.begin.ts"
2796- }
2797- },
2798- "end": "(/)([gimuy]*)",
2799- "endCaptures": {
2800- "1": {
2801- "name": "punctuation.definition.string.end.ts"
2802- },
2803- "2": {
2804- "name": "keyword.other.ts"
2805- }
2806- },
2807- "patterns": [
2808- {
2809- "include": "#regexp"
2810- }
2811- ]
2812- }
2813- ]
2814- },
2815- "regexp": {
2816- "patterns": [
2817- {
2818- "name": "keyword.control.anchor.regexp",
2819- "match": "\\\\[bB]|\\^|\\$"
2820- },
2821- {
2822- "name": "keyword.other.back-reference.regexp",
2823- "match": "\\\\[1-9]\\d*"
2824- },
2825- {
2826- "name": "keyword.operator.quantifier.regexp",
2827- "match": "[?+*]|\\{(\\d+,\\d+|\\d+,|,\\d+|\\d+)\\}\\??"
2828- },
2829- {
2830- "name": "keyword.operator.or.regexp",
2831- "match": "\\|"
2832- },
2833- {
2834- "name": "meta.group.assertion.regexp",
2835- "begin": "(\\()((\\?=)|(\\?!))",
2836- "beginCaptures": {
2837- "1": {
2838- "name": "punctuation.definition.group.regexp"
2839- },
2840- "2": {
2841- "name": "punctuation.definition.group.assertion.regexp"
2842- },
2843- "3": {
2844- "name": "meta.assertion.look-ahead.regexp"
2845- },
2846- "4": {
2847- "name": "meta.assertion.negative-look-ahead.regexp"
2848- }
2849- },
2850- "end": "(\\))",
2851- "endCaptures": {
2852- "1": {
2853- "name": "punctuation.definition.group.regexp"
2854- }
2855- },
2856- "patterns": [
2857- {
2858- "include": "#regexp"
2859- }
2860- ]
2861- },
2862- {
2863- "name": "meta.group.regexp",
2864- "begin": "\\((\\?:)?",
2865- "beginCaptures": {
2866- "0": {
2867- "name": "punctuation.definition.group.regexp"
2868- },
2869- "1": {
2870- "name": "punctuation.definition.group.capture.regexp"
2871- }
2872- },
2873- "end": "\\)",
2874- "endCaptures": {
2875- "0": {
2876- "name": "punctuation.definition.group.regexp"
2877- }
2878- },
2879- "patterns": [
2880- {
2881- "include": "#regexp"
2882- }
2883- ]
2884- },
2885- {
2886- "name": "constant.other.character-class.set.regexp",
2887- "begin": "(\\[)(\\^)?",
2888- "beginCaptures": {
2889- "1": {
2890- "name": "punctuation.definition.character-class.regexp"
2891- },
2892- "2": {
2893- "name": "keyword.operator.negation.regexp"
2894- }
2895- },
2896- "end": "(\\])",
2897- "endCaptures": {
2898- "1": {
2899- "name": "punctuation.definition.character-class.regexp"
2900- }
2901- },
2902- "patterns": [
2903- {
2904- "name": "constant.other.character-class.range.regexp",
2905- "match": "(?:.|(\\\\(?:[0-7]{3}|x\\h\\h|u\\h\\h\\h\\h))|(\\\\c[A-Z])|(\\\\.))\\-(?:[^\\]\\\\]|(\\\\(?:[0-7]{3}|x\\h\\h|u\\h\\h\\h\\h))|(\\\\c[A-Z])|(\\\\.))",
2906- "captures": {
2907- "1": {
2908- "name": "constant.character.numeric.regexp"
2909- },
2910- "2": {
2911- "name": "constant.character.control.regexp"
2912- },
2913- "3": {
2914- "name": "constant.character.escape.backslash.regexp"
2915- },
2916- "4": {
2917- "name": "constant.character.numeric.regexp"
2918- },
2919- "5": {
2920- "name": "constant.character.control.regexp"
2921- },
2922- "6": {
2923- "name": "constant.character.escape.backslash.regexp"
2924- }
2925- }
2926- },
2927- {
2928- "include": "#regex-character-class"
2929- }
2930- ]
2931- },
2932- {
2933- "include": "#regex-character-class"
2934- }
2935- ]
2936- },
2937- "regex-character-class": {
2938- "patterns": [
2939- {
2940- "name": "constant.other.character-class.regexp",
2941- "match": "\\\\[wWsSdDtrnvf]|\\."
2942- },
2943- {
2944- "name": "constant.character.numeric.regexp",
2945- "match": "\\\\([0-7]{3}|x\\h\\h|u\\h\\h\\h\\h)"
2946- },
2947- {
2948- "name": "constant.character.control.regexp",
2949- "match": "\\\\c[A-Z]"
2950- },
2951- {
2952- "name": "constant.character.escape.backslash.regexp",
2953- "match": "\\\\."
2954- }
2955- ]
2956- },
2957- "string": {
2958- "patterns": [
2959- {
2960- "include": "#qstring-single"
2961- },
2962- {
2963- "include": "#qstring-double"
2964- }
2965- ]
2966- },
2967- "template": {
2968- "name": "string.template.ts",
2969- "begin": "([_$[:alpha:]][_$[:alnum:]]*)?(`)",
2970- "beginCaptures": {
2971- "1": {
2972- "name": "entity.name.function.tagged-template.ts"
2973- },
2974- "2": {
2975- "name": "punctuation.definition.string.template.begin.ts"
2976- }
2977- },
2978- "end": "`",
2979- "endCaptures": {
2980- "0": {
2981- "name": "punctuation.definition.string.template.end.ts"
2982- }
2983- },
2984- "patterns": [
2985- {
2986- "include": "#template-substitution-element"
2987- },
2988- {
2989- "include": "#string-character-escape"
2990- }
2991- ]
2992- },
2993- "string-character-escape": {
2994- "name": "constant.character.escape.ts",
2995- "match": "\\\\(x\\h{2}|[0-2][0-7]{0,2}|3[0-6][0-7]?|37[0-7]?|[4-7][0-7]?|.|$)"
2996- },
2997- "template-substitution-element": {
2998- "name": "meta.template.expression.ts",
2999- "begin": "\\$\\{",
3000- "beginCaptures": {
3001- "0": {
3002- "name": "punctuation.definition.template-expression.begin.ts"
3003- }
3004- },
3005- "end": "\\}",
3006- "endCaptures": {
3007- "0": {
3008- "name": "punctuation.definition.template-expression.end.ts"
3009- }
3010- },
3011- "patterns": [
3012- {
3013- "include": "#expression"
3014- }
3015- ]
3016- },
3017- "literal": {
3018- "name": "literal.ts",
3019- "patterns": [
3020- {
3021- "include": "#numeric-literal"
3022- },
3023- {
3024- "include": "#boolean-literal"
3025- },
3026- {
3027- "include": "#null-literal"
3028- },
3029- {
3030- "include": "#undefined-literal"
3031- },
3032- {
3033- "include": "#numericConstant-literal"
3034- },
3035- {
3036- "include": "#array-literal"
3037- },
3038- {
3039- "include": "#this-literal"
3040- },
3041- {
3042- "include": "#super-literal"
3043- }
3044- ]
3045- },
3046- "array-literal": {
3047- "name": "meta.array.literal.ts",
3048- "begin": "\\[",
3049- "beginCaptures": {
3050- "0": {
3051- "name": "meta.brace.square.ts"
3052- }
3053- },
3054- "end": "\\]",
3055- "endCaptures": {
3056- "0": {
3057- "name": "meta.brace.square.ts"
3058- }
3059- },
3060- "patterns": [
3061- {
3062- "include": "#expression"
3063- },
3064- {
3065- "include": "#punctuation-comma"
3066- }
3067- ]
3068- },
3069- "numeric-literal": {
3070- "patterns": [
3071- {
3072- "name": "constant.numeric.hex.ts",
3073- "match": "\\b(?<!\\$)0(x|X)[0-9a-fA-F]+\\b(?!\\$)"
3074- },
3075- {
3076- "name": "constant.numeric.binary.ts",
3077- "match": "\\b(?<!\\$)0(b|B)[01]+\\b(?!\\$)"
3078- },
3079- {
3080- "name": "constant.numeric.octal.ts",
3081- "match": "\\b(?<!\\$)0(o|O)?[0-7]+\\b(?!\\$)"
3082- },
3083- {
3084- "match": "(?x)\n(?<!\\$)(?:\n (?:\\b[0-9]+(\\.)[0-9]+[eE][+-]?[0-9]+\\b)| # 1.1E+3\n (?:\\b[0-9]+(\\.)[eE][+-]?[0-9]+\\b)| # 1.E+3\n (?:\\B(\\.)[0-9]+[eE][+-]?[0-9]+\\b)| # .1E+3\n (?:\\b[0-9]+[eE][+-]?[0-9]+\\b)| # 1E+3\n (?:\\b[0-9]+(\\.)[0-9]+\\b)| # 1.1\n (?:\\b[0-9]+(\\.)\\B)| # 1.\n (?:\\B(\\.)[0-9]+\\b)| # .1\n (?:\\b[0-9]+\\b(?!\\.)) # 1\n)(?!\\$)",
3085- "captures": {
3086- "0": {
3087- "name": "constant.numeric.decimal.ts"
3088- },
3089- "1": {
3090- "name": "meta.delimiter.decimal.period.ts"
3091- },
3092- "2": {
3093- "name": "meta.delimiter.decimal.period.ts"
3094- },
3095- "3": {
3096- "name": "meta.delimiter.decimal.period.ts"
3097- },
3098- "4": {
3099- "name": "meta.delimiter.decimal.period.ts"
3100- },
3101- "5": {
3102- "name": "meta.delimiter.decimal.period.ts"
3103- },
3104- "6": {
3105- "name": "meta.delimiter.decimal.period.ts"
3106- }
3107- }
3108- }
3109- ]
3110- },
3111- "boolean-literal": {
3112- "patterns": [
3113- {
3114- "name": "constant.language.boolean.true.ts",
3115- "match": "(?<!\\.|\\$)\\btrue\\b(?!\\$)"
3116- },
3117- {
3118- "name": "constant.language.boolean.false.ts",
3119- "match": "(?<!\\.|\\$)\\bfalse\\b(?!\\$)"
3120- }
3121- ]
3122- },
3123- "null-literal": {
3124- "name": "constant.language.null.ts",
3125- "match": "(?<!\\.|\\$)\\bnull\\b(?!\\$)"
3126- },
3127- "this-literal": {
3128- "name": "variable.language.this.ts",
3129- "match": "(?<!\\.|\\$)\\bthis\\b(?!\\$)"
3130- },
3131- "super-literal": {
3132- "name": "variable.language.super.ts",
3133- "match": "(?<!\\.|\\$)\\bsuper\\b(?!\\$)"
3134- },
3135- "undefined-literal": {
3136- "name": "constant.language.undefined.ts",
3137- "match": "(?<!\\.|\\$)\\bundefined\\b(?!\\$)"
3138- },
3139- "numericConstant-literal": {
3140- "patterns": [
3141- {
3142- "name": "constant.language.nan.ts",
3143- "match": "(?<!\\.|\\$)\\bNaN\\b(?!\\$)"
3144- },
3145- {
3146- "name": "constant.language.infinity.ts",
3147- "match": "(?<!\\.|\\$)\\bInfinity\\b(?!\\$)"
3148- }
3149- ]
3150- },
3151- "access-modifier": {
3152- "name": "storage.modifier.ts",
3153- "match": "(?<!\\.|\\$)\\b(abstract|public|protected|private|readonly|static)\\b(?!\\$)"
3154- },
3155- "property-accessor": {
3156- "name": "storage.type.property.ts",
3157- "match": "(?<!\\.|\\$)\\b(get|set)\\b(?!\\$)"
3158- },
3159- "comment": {
3160- "patterns": [
3161- {
3162- "name": "comment.block.documentation.ts",
3163- "begin": "/\\*\\*(?!/)",
3164- "beginCaptures": {
3165- "0": {
3166- "name": "punctuation.definition.comment.ts"
3167- }
3168- },
3169- "end": "\\*/",
3170- "endCaptures": {
3171- "0": {
3172- "name": "punctuation.definition.comment.ts"
3173- }
3174- },
3175- "patterns": [
3176- {
3177- "include": "#docblock"
3178- }
3179- ]
3180- },
3181- {
3182- "name": "comment.block.ts",
3183- "begin": "/\\*",
3184- "beginCaptures": {
3185- "0": {
3186- "name": "punctuation.definition.comment.ts"
3187- }
3188- },
3189- "end": "\\*/",
3190- "endCaptures": {
3191- "0": {
3192- "name": "punctuation.definition.comment.ts"
3193- }
3194- }
3195- },
3196- {
3197- "begin": "(^[ \\t]+)?(?=//)",
3198- "beginCaptures": {
3199- "1": {
3200- "name": "punctuation.whitespace.comment.leading.ts"
3201- }
3202- },
3203- "end": "(?=$)",
3204- "patterns": [
3205- {
3206- "name": "comment.line.double-slash.ts",
3207- "begin": "//",
3208- "beginCaptures": {
3209- "0": {
3210- "name": "punctuation.definition.comment.ts"
3211- }
3212- },
3213- "end": "(?=$)"
3214- }
3215- ]
3216- }
3217- ]
3218- },
3219- "directives": {
3220- "name": "comment.line.triple-slash.directive.ts",
3221- "begin": "^(///)\\s*(?=<(reference|amd-dependency|amd-module)(\\s+(path|types|no-default-lib|name)\\s*=\\s*((\\'[^']*\\')|(\\\"[^\"]*\\\")))+\\s*/>\\s*$)",
3222- "beginCaptures": {
3223- "1": {
3224- "name": "punctuation.definition.comment.ts"
3225- }
3226- },
3227- "end": "(?=$)",
3228- "patterns": [
3229- {
3230- "name": "meta.tag.ts",
3231- "begin": "(<)(reference|amd-dependency|amd-module)",
3232- "beginCaptures": {
3233- "1": {
3234- "name": "punctuation.definition.tag.directive.ts"
3235- },
3236- "2": {
3237- "name": "entity.name.tag.directive.ts"
3238- }
3239- },
3240- "end": "/>",
3241- "endCaptures": {
3242- "0": {
3243- "name": "punctuation.definition.tag.directive.ts"
3244- }
3245- },
3246- "patterns": [
3247- {
3248- "name": "entity.other.attribute-name.directive.ts",
3249- "match": "path|types|no-default-lib|name"
3250- },
3251- {
3252- "name": "keyword.operator.assignment.ts",
3253- "match": "="
3254- },
3255- {
3256- "include": "#string"
3257- }
3258- ]
3259- }
3260- ]
3261- },
3262- "docblock": {
3263- "patterns": [
3264- {
3265- "name": "storage.type.class.jsdoc",
3266- "match": "(?<!\\w)@(abstract|access|alias|arg|argument|async|attribute|augments|author|beta|borrows|bubbes|callback|chainable|class|classdesc|code|config|const|constant|constructor|constructs|copyright|default|defaultvalue|define|deprecated|desc|description|dict|emits|enum|event|example|exports?|extends|extension|extension_for|extensionfor|external|file|fileoverview|final|fires|for|function|global|host|ignore|implements|inherit[Dd]oc|inner|instance|interface|kind|lends|license|listens|main|member|memberof|method|mixex|mixins?|module|name|namespace|nocollapse|nosideeffects|override|overview|package|param|preserve|private|prop|property|protected|public|read[Oo]nly|record|require[ds]|returns?|see|since|static|struct|submodule|summary|template|this|throws|todo|tutorial|type|typedef|unrestricted|uses|var|variation|version|virtual|writeOnce)\\b"
3267- },
3268- {
3269- "match": "(?x)\n(?:(?<=@param)|(?<=@arg)|(?<=@argument)|(?<=@type))\n\\s+\n({(?:\n \\* | # {*} any type\n \\? | # {?} unknown type\n (?: # Check for a prefix\n \\? | # {?string} nullable type\n ! | # {!string} non-nullable type\n \\.{3} # {...string} variable number of parameters\n )?\n (?:\n \\( # Opening bracket of multiple types with parenthesis {(string|number)}\n [a-zA-Z_$]+\n (?:\n (?:\n [\\w$]*\n (?:\\[\\])? # {(string[]|number)} type application, an array of strings or a number\n ) |\n \\.?<[\\w$]+(?:,\\s+[\\w$]+)*> # {Array<string>} or {Object<string, number>} type application (optional .)\n )\n (?:\n [\\.|~] # {Foo.bar} namespaced, {string|number} multiple, {Foo~bar} class-specific callback\n [a-zA-Z_$]+\n (?:\n (?:\n [\\w$]*\n (?:\\[\\])? # {(string|number[])} type application, a string or an array of numbers\n ) |\n \\.?<[\\w$]+(?:,\\s+[\\w$]+)*> # {Array<string>} or {Object<string, number>} type application (optional .)\n )\n )*\n \\) |\n [a-zA-Z_$]+\n (?:\n (?:\n [\\w$]*\n (?:\\[\\])? # {string[]|number} type application, an array of strings or a number\n ) |\n \\.?<[\\w$]+(?:,\\s+[\\w$]+)*> # {Array<string>} or {Object<string, number>} type application (optional .)\n )\n (?:\n [\\.|~] # {Foo.bar} namespaced, {string|number} multiple, {Foo~bar} class-specific callback\n [a-zA-Z_$]+\n (?:\n [\\w$]* |\n \\.?<[\\w$]+(?:,\\s+[\\w$]+)*> # {Array<string>} or {Object<string, number>} type application (optional .)\n )\n )*\n )\n # Check for suffix\n (?:\\[\\])? # {string[]} type application, an array of strings\n =? # {string=} optional parameter\n)})\n\\s+\n(\n \\[ # [foo] optional parameter\n \\s*\n (?:\n [a-zA-Z_$][\\w$]*\n (?:\n (?:\\[\\])? # Foo[].bar properties within an array\n \\. # Foo.Bar namespaced parameter\n [a-zA-Z_$][\\w$]*\n )*\n (?:\n \\s*\n = # [foo=bar] Default parameter value\n \\s*\n [\\w$\\s]*\n )?\n )\n \\s*\n \\] |\n (?:\n [a-zA-Z_$][\\w$]*\n (?:\n (?:\\[\\])? # Foo[].bar properties within an array\n \\. # Foo.Bar namespaced parameter\n [a-zA-Z_$][\\w$]*\n )*\n )?\n)\n\\s+\n(?:-\\s+)? # optional hyphen before the description\n((?:(?!\\*\\/).)*) # The type description",
3270- "captures": {
3271- "0": {
3272- "name": "other.meta.jsdoc"
3273- },
3274- "1": {
3275- "name": "entity.name.type.instance.jsdoc"
3276- },
3277- "2": {
3278- "name": "variable.other.jsdoc"
3279- },
3280- "3": {
3281- "name": "other.description.jsdoc"
3282- }
3283- }
3284- },
3285- {
3286- "match": "(?x)\n({(?:\n \\* | # {*} any type\n \\? | # {?} unknown type\n\n (?: # Check for a prefix\n \\? | # {?string} nullable type\n ! | # {!string} non-nullable type\n \\.{3} # {...string} variable number of parameters\n )?\n\n (?:\n \\( # Opening bracket of multiple types with parenthesis {(string|number)}\n [a-zA-Z_$]+\n (?:\n [\\w$]* |\n \\.?<[\\w$]+(?:,\\s+[\\w$]+)*> # {Array<string>} or {Object<string, number>} type application (optional .)\n )\n (?:\n [\\.|~] # {Foo.bar} namespaced, {string|number} multiple, {Foo~bar} class-specific callback\n [a-zA-Z_$]+\n (?:\n [\\w$]* |\n \\.?<[\\w$]+(?:,\\s+[\\w$]+)*> # {Array<string>} or {Object<string, number>} type application (optional .)\n )\n )*\n \\) |\n [a-zA-Z_$]+\n (?:\n [\\w$]* |\n \\.?<[\\w$]+(?:,\\s+[\\w$]+)*> # {Array<string>} or {Object<string, number>} type application (optional .)\n )\n (?:\n [\\.|~] # {Foo.bar} namespaced, {string|number} multiple, {Foo~bar} class-specific callback\n [a-zA-Z_$]+\n (?:\n [\\w$]* |\n \\.?<[\\w$]+(?:,\\s+[\\w$]+)*> # {Array<string>} or {Object<string, number>} type application (optional .)\n )\n )*\n )\n # Check for suffix\n (?:\\[\\])? # {string[]} type application, an array of strings\n =? # {string=} optional parameter\n)})\n\\s+\n(?:-\\s+)? # optional hyphen before the description\n((?:(?!\\*\\/).)*) # The type description",
3287- "captures": {
3288- "0": {
3289- "name": "other.meta.jsdoc"
3290- },
3291- "1": {
3292- "name": "entity.name.type.instance.jsdoc"
3293- },
3294- "2": {
3295- "name": "other.description.jsdoc"
3296- }
3297- }
3298- }
3299- ]
3300- }
3301- },
3302- "version": "https://github.com/Microsoft/TypeScript-TmLanguage/commit/4d0bdebb93aadc25ecbb903ebc897e9cd5fab69c"
3303-}
No newline at the end of the file
2+ "name": "TypeScript",
3+ "scopeName": "source.ts",
4+ "fileTypes": ["ts"],
5+ "uuid": "ef98eb90-bf9b-11e4-bb52-0800200c9a66",
6+ "patterns": [
7+ {
8+ "include": "#directives"
9+ },
10+ {
11+ "include": "#statements"
12+ },
13+ {
14+ "name": "comment.line.shebang.ts",
15+ "match": "\\A(#!).*(?=$)",
16+ "captures": {
17+ "1": {
18+ "name": "punctuation.definition.comment.ts"
19+ }
20+ }
21+ }
22+ ],
23+ "repository": {
24+ "statements": {
25+ "patterns": [
26+ {
27+ "include": "#string"
28+ },
29+ {
30+ "include": "#template"
31+ },
32+ {
33+ "include": "#comment"
34+ },
35+ {
36+ "include": "#literal"
37+ },
38+ {
39+ "include": "#declaration"
40+ },
41+ {
42+ "include": "#switch-statement"
43+ },
44+ {
45+ "include": "#for-loop"
46+ },
47+ {
48+ "include": "#after-operator-block"
49+ },
50+ {
51+ "include": "#decl-block"
52+ },
53+ {
54+ "include": "#control-statement"
55+ },
56+ {
57+ "include": "#expression"
58+ },
59+ {
60+ "include": "#punctuation-semicolon"
61+ }
62+ ]
63+ },
64+ "var-expr": {
65+ "name": "meta.var.expr.ts",
66+ "begin": "(?<!\\.|\\$)(?:(\\bexport)\\s+)?\\b(var|let|const(?!\\s+enum\\b))\\b(?!\\$)",
67+ "beginCaptures": {
68+ "1": {
69+ "name": "keyword.control.export.ts"
70+ },
71+ "2": {
72+ "name": "storage.type.ts"
73+ }
74+ },
75+ "end": "(?=$|;|}|(\\s+(of|in)\\s+))",
76+ "patterns": [
77+ {
78+ "include": "#destructuring-variable"
79+ },
80+ {
81+ "include": "#var-single-variable"
82+ },
83+ {
84+ "include": "#variable-initializer"
85+ },
86+ {
87+ "include": "#comment"
88+ },
89+ {
90+ "include": "#punctuation-comma"
91+ }
92+ ]
93+ },
94+ "var-single-variable": {
95+ "patterns": [
96+ {
97+ "name": "meta.var-single-variable.expr.ts",
98+ "begin": "(?x)([_$[:alpha:]][_$[:alnum:]]*)(?=\\s* (=\\s*( (async\\s+) | (function\\s*[(<]) | (function\\s+) | ([_$[:alpha:]][_$[:alnum:]]*\\s*=>) | ((<([^<>]|\\<[^<>]+\\>)+>\\s*)?\\(([^()]|\\([^()]*\\))*\\)(\\s*:\\s*(.)*)?\\s*=>)) ) | (:\\s*( (<) | ([(]\\s*( ([)]) | (\\.\\.\\.) | ([_$[:alnum:]]+\\s*( ([:,?=])| ([)]\\s*=>) )) ))) ))",
99+ "beginCaptures": {
100+ "1": {
101+ "name": "entity.name.function.ts"
102+ }
103+ },
104+ "end": "(?=$|[;,=}]|(\\s+(of|in)\\s+))",
105+ "patterns": [
106+ {
107+ "include": "#type-annotation"
108+ },
109+ {
110+ "include": "#string"
111+ },
112+ {
113+ "include": "#comment"
114+ }
115+ ]
116+ },
117+ {
118+ "name": "meta.var-single-variable.expr.ts",
119+ "begin": "([_$[:alpha:]][_$[:alnum:]]*)",
120+ "beginCaptures": {
121+ "1": {
122+ "name": "variable.other.readwrite.ts"
123+ }
124+ },
125+ "end": "(?=$|[;,=}]|(\\s+(of|in)\\s+))",
126+ "patterns": [
127+ {
128+ "include": "#type-annotation"
129+ },
130+ {
131+ "include": "#string"
132+ },
133+ {
134+ "include": "#comment"
135+ }
136+ ]
137+ }
138+ ]
139+ },
140+ "destructuring-variable": {
141+ "patterns": [
142+ {
143+ "name": "meta.object-binding-pattern-variable.ts",
144+ "begin": "(?<!=|:|of|in)\\s*(?=\\{)",
145+ "end": "(?=$|[;,=}]|(\\s+(of|in)\\s+))",
146+ "patterns": [
147+ {
148+ "include": "#object-binding-pattern"
149+ },
150+ {
151+ "include": "#type-annotation"
152+ },
153+ {
154+ "include": "#comment"
155+ }
156+ ]
157+ },
158+ {
159+ "name": "meta.array-binding-pattern-variable.ts",
160+ "begin": "(?<!=|:|of|in)\\s*(?=\\[)",
161+ "end": "(?=$|[;,=}]|(\\s+(of|in)\\s+))",
162+ "patterns": [
163+ {
164+ "include": "#array-binding-pattern"
165+ },
166+ {
167+ "include": "#type-annotation"
168+ },
169+ {
170+ "include": "#comment"
171+ }
172+ ]
173+ }
174+ ]
175+ },
176+ "object-binding-element": {
177+ "patterns": [
178+ {
179+ "include": "#comment"
180+ },
181+ {
182+ "begin": "(?=(([_$[:alpha:]][_$[:alnum:]]*)|(\\'[^']*\\')|(\\\"[^\"]*\\\")|(\\[([^\\[\\]]|\\[[^\\[\\]]+\\])+\\]))\\s*(:))",
183+ "end": "(?=,|\\})",
184+ "patterns": [
185+ {
186+ "include": "#object-binding-element-propertyName"
187+ },
188+ {
189+ "include": "#binding-element"
190+ }
191+ ]
192+ },
193+ {
194+ "include": "#object-binding-pattern"
195+ },
196+ {
197+ "include": "#destructuring-variable-rest"
198+ },
199+ {
200+ "include": "#variable-initializer"
201+ },
202+ {
203+ "include": "#punctuation-comma"
204+ }
205+ ]
206+ },
207+ "object-binding-element-propertyName": {
208+ "begin": "(?=(([_$[:alpha:]][_$[:alnum:]]*)|(\\'[^']*\\')|(\\\"[^\"]*\\\")|(\\[([^\\[\\]]|\\[[^\\[\\]]+\\])+\\]))\\s*(:))",
209+ "end": "(:)",
210+ "endCaptures": {
211+ "0": {
212+ "name": "punctuation.destructuring.ts"
213+ }
214+ },
215+ "patterns": [
216+ {
217+ "include": "#string"
218+ },
219+ {
220+ "include": "#array-literal"
221+ },
222+ {
223+ "name": "variable.object.property.ts",
224+ "match": "([_$[:alpha:]][_$[:alnum:]]*)"
225+ }
226+ ]
227+ },
228+ "binding-element": {
229+ "patterns": [
230+ {
231+ "include": "#comment"
232+ },
233+ {
234+ "include": "#object-binding-pattern"
235+ },
236+ {
237+ "include": "#array-binding-pattern"
238+ },
239+ {
240+ "include": "#destructuring-variable-rest"
241+ },
242+ {
243+ "include": "#variable-initializer"
244+ }
245+ ]
246+ },
247+ "destructuring-variable-rest": {
248+ "match": "(?:(\\.\\.\\.)\\s*)?([_$[:alpha:]][_$[:alnum:]]*)",
249+ "captures": {
250+ "1": {
251+ "name": "keyword.operator.rest.ts"
252+ },
253+ "2": {
254+ "name": "variable.other.readwrite.ts"
255+ }
256+ }
257+ },
258+ "object-binding-pattern": {
259+ "begin": "(?:(\\.\\.\\.)\\s*)?(\\{)",
260+ "beginCaptures": {
261+ "1": {
262+ "name": "keyword.operator.rest.ts"
263+ },
264+ "2": {
265+ "name": "punctuation.definition.binding-pattern.object.ts"
266+ }
267+ },
268+ "end": "\\}",
269+ "endCaptures": {
270+ "0": {
271+ "name": "punctuation.definition.binding-pattern.object.ts"
272+ }
273+ },
274+ "patterns": [
275+ {
276+ "include": "#object-binding-element"
277+ }
278+ ]
279+ },
280+ "array-binding-pattern": {
281+ "begin": "(?:(\\.\\.\\.)\\s*)?(\\[)",
282+ "beginCaptures": {
283+ "1": {
284+ "name": "keyword.operator.rest.ts"
285+ },
286+ "2": {
287+ "name": "punctuation.definition.binding-pattern.array.ts"
288+ }
289+ },
290+ "end": "\\]",
291+ "endCaptures": {
292+ "0": {
293+ "name": "punctuation.definition.binding-pattern.array.ts"
294+ }
295+ },
296+ "patterns": [
297+ {
298+ "include": "#binding-element"
299+ },
300+ {
301+ "include": "#punctuation-comma"
302+ }
303+ ]
304+ },
305+ "ternary-expression": {
306+ "begin": "(?=\\?)",
307+ "end": "(?=$|[;,})\\]])",
308+ "patterns": [
309+ {
310+ "include": "#ternary-operator"
311+ },
312+ {
313+ "include": "#expression"
314+ }
315+ ]
316+ },
317+ "ternary-operator": {
318+ "begin": "(\\?)",
319+ "beginCaptures": {
320+ "0": {
321+ "name": "keyword.operator.ternary.ts"
322+ }
323+ },
324+ "end": "(:)",
325+ "endCaptures": {
326+ "0": {
327+ "name": "keyword.operator.ternary.ts"
328+ }
329+ },
330+ "patterns": [
331+ {
332+ "include": "#expression"
333+ }
334+ ]
335+ },
336+ "expression": {
337+ "name": "meta.expression.ts",
338+ "patterns": [
339+ {
340+ "include": "#string"
341+ },
342+ {
343+ "include": "#regex"
344+ },
345+ {
346+ "include": "#template"
347+ },
348+ {
349+ "include": "#comment"
350+ },
351+ {
352+ "include": "#literal"
353+ },
354+ {
355+ "include": "#function-declaration"
356+ },
357+ {
358+ "include": "#class-or-interface-declaration"
359+ },
360+ {
361+ "include": "#arrow-function"
362+ },
363+ {
364+ "include": "#cast"
365+ },
366+ {
367+ "include": "#ternary-expression"
368+ },
369+ {
370+ "include": "#new-expr"
371+ },
372+ {
373+ "include": "#object-literal"
374+ },
375+ {
376+ "include": "#expression-operators"
377+ },
378+ {
379+ "include": "#function-call"
380+ },
381+ {
382+ "include": "#support-objects"
383+ },
384+ {
385+ "include": "#identifiers"
386+ },
387+ {
388+ "include": "#paren-expression"
389+ },
390+ {
391+ "include": "#punctuation-comma"
392+ },
393+ {
394+ "include": "#punctuation-accessor"
395+ }
396+ ]
397+ },
398+ "control-statement": {
399+ "patterns": [
400+ {
401+ "name": "keyword.control.trycatch.ts",
402+ "match": "(?<!\\.|\\$)\\b(catch|finally|throw|try)\\b(?!\\$)"
403+ },
404+ {
405+ "name": "keyword.control.loop.ts",
406+ "match": "(?<!\\.|\\$)\\b(break|continue|do|goto|while)\\b(?!\\$)"
407+ },
408+ {
409+ "name": "keyword.control.flow.ts",
410+ "match": "(?<!\\.|\\$)\\b(return)\\b(?!\\$)"
411+ },
412+ {
413+ "match": "(?<!\\.|\\$)\\b(yield)\\b(?!\\$)(?:\\s*(\\*))?",
414+ "captures": {
415+ "1": {
416+ "name": "keyword.control.flow.ts"
417+ },
418+ "2": {
419+ "name": "keyword.generator.asterisk.ts"
420+ }
421+ }
422+ },
423+ {
424+ "name": "keyword.control.switch.ts",
425+ "match": "(?<!\\.|\\$)\\b(case|default|switch)\\b(?!\\$)"
426+ },
427+ {
428+ "name": "keyword.control.conditional.ts",
429+ "match": "(?<!\\.|\\$)\\b(else|if)\\b(?!\\$)"
430+ },
431+ {
432+ "name": "keyword.control.with.ts",
433+ "match": "(?<!\\.|\\$)\\b(with)\\b(?!\\$)"
434+ },
435+ {
436+ "name": "keyword.other.debugger.ts",
437+ "match": "(?<!\\.|\\$)\\b(debugger)\\b(?!\\$)"
438+ },
439+ {
440+ "name": "storage.modifier.ts",
441+ "match": "(?<!\\.|\\$)\\b(declare)\\b(?!\\$)"
442+ }
443+ ]
444+ },
445+ "declaration": {
446+ "name": "meta.declaration.ts",
447+ "patterns": [
448+ {
449+ "include": "#decorator"
450+ },
451+ {
452+ "include": "#var-expr"
453+ },
454+ {
455+ "include": "#function-declaration"
456+ },
457+ {
458+ "include": "#class-or-interface-declaration"
459+ },
460+ {
461+ "include": "#type-declaration"
462+ },
463+ {
464+ "include": "#enum-declaration"
465+ },
466+ {
467+ "include": "#namespace-declaration"
468+ },
469+ {
470+ "include": "#import-equals-declaration"
471+ },
472+ {
473+ "include": "#import-declaration"
474+ },
475+ {
476+ "include": "#export-declaration"
477+ }
478+ ]
479+ },
480+ "decorator": {
481+ "name": "meta.decorator.ts",
482+ "begin": "(?<!\\.|\\$)\\@",
483+ "beginCaptures": {
484+ "0": {
485+ "name": "punctuation.decorator.ts"
486+ }
487+ },
488+ "end": "(?=\\s)",
489+ "patterns": [
490+ {
491+ "include": "#expression"
492+ }
493+ ]
494+ },
495+ "type-declaration": {
496+ "name": "meta.type.declaration.ts",
497+ "begin": "(?<!\\.|\\$)(?:(\\bexport)\\s+)?\\b(type)\\b\\s+([_$[:alpha:]][_$[:alnum:]]*)\\s*",
498+ "beginCaptures": {
499+ "1": {
500+ "name": "keyword.control.export.ts"
501+ },
502+ "2": {
503+ "name": "storage.type.type.ts"
504+ },
505+ "3": {
506+ "name": "entity.name.type.ts"
507+ }
508+ },
509+ "end": "(?=[};]|\\bvar\\b|\\blet\\b|\\bconst\\b|\\btype\\b|\\bfunction\\b|\\bclass\\b|\\binterface\\b|\\bnamespace\\b|\\bmodule\\b|\\bimport\\b|\\benum\\b|\\bdeclare\\b|\\bexport\\b|\\babstract\\b|\\basync\\b)",
510+ "patterns": [
511+ {
512+ "include": "#comment"
513+ },
514+ {
515+ "include": "#type-parameters"
516+ },
517+ {
518+ "include": "#type"
519+ },
520+ {
521+ "match": "(=)\\s*",
522+ "captures": {
523+ "1": {
524+ "name": "keyword.operator.assignment.ts"
525+ }
526+ }
527+ }
528+ ]
529+ },
530+ "enum-declaration": {
531+ "name": "meta.enum.declaration.ts",
532+ "begin": "(?<!\\.|\\$)(?:(\\bexport)\\s+)?(?:\\b(const)\\s+)?\\b(enum)\\s+([_$[:alpha:]][_$[:alnum:]]*)",
533+ "beginCaptures": {
534+ "1": {
535+ "name": "keyword.control.export.ts"
536+ },
537+ "2": {
538+ "name": "storage.modifier.ts"
539+ },
540+ "3": {
541+ "name": "storage.type.enum.ts"
542+ },
543+ "4": {
544+ "name": "entity.name.type.enum.ts"
545+ }
546+ },
547+ "end": "(?<=\\})",
548+ "patterns": [
549+ {
550+ "include": "#comment"
551+ },
552+ {
553+ "begin": "\\{",
554+ "beginCaptures": {
555+ "0": {
556+ "name": "punctuation.definition.block.ts"
557+ }
558+ },
559+ "end": "\\}",
560+ "endCaptures": {
561+ "0": {
562+ "name": "punctuation.definition.block.ts"
563+ }
564+ },
565+ "patterns": [
566+ {
567+ "include": "#comment"
568+ },
569+ {
570+ "begin": "([_$[:alpha:]][_$[:alnum:]]*)",
571+ "beginCaptures": {
572+ "0": {
573+ "name": "variable.other.enummember.ts"
574+ }
575+ },
576+ "end": "(?=,|\\}|$)",
577+ "patterns": [
578+ {
579+ "include": "#comment"
580+ },
581+ {
582+ "include": "#variable-initializer"
583+ }
584+ ]
585+ },
586+ {
587+ "begin": "(?=((\\'[^']*\\')|(\\\"[^\"]*\\\")|(\\[([^\\[\\]]|\\[[^\\[\\]]+\\])+\\])))",
588+ "end": "(?=,|\\}|$)",
589+ "patterns": [
590+ {
591+ "include": "#string"
592+ },
593+ {
594+ "include": "#array-literal"
595+ },
596+ {
597+ "include": "#comment"
598+ },
599+ {
600+ "include": "#variable-initializer"
601+ }
602+ ]
603+ },
604+ {
605+ "include": "#punctuation-comma"
606+ }
607+ ]
608+ }
609+ ]
610+ },
611+ "namespace-declaration": {
612+ "name": "meta.namespace.declaration.ts",
613+ "begin": "(?<!\\.|\\$)(?:(\\bexport)\\s+)?\\b(namespace|module)\\s+",
614+ "beginCaptures": {
615+ "1": {
616+ "name": "keyword.control.export.ts"
617+ },
618+ "2": {
619+ "name": "storage.type.namespace.ts"
620+ }
621+ },
622+ "end": "(?=$|\\{)",
623+ "patterns": [
624+ {
625+ "include": "#comment"
626+ },
627+ {
628+ "include": "#string"
629+ },
630+ {
631+ "name": "entity.name.type.module.ts",
632+ "match": "([_$[:alpha:]][_$[:alnum:]]*)"
633+ },
634+ {
635+ "name": "punctuation.accessor.ts",
636+ "match": "\\."
637+ }
638+ ]
639+ },
640+ "import-equals-declaration": {
641+ "patterns": [
642+ {
643+ "name": "meta.import-equals.external.ts",
644+ "begin": "(?<!\\.|\\$)(?:(\\bexport)\\s+)?\\b(import)\\s+([_$[:alpha:]][_$[:alnum:]]*)\\s*(=)\\s*(require)\\s*(\\()",
645+ "beginCaptures": {
646+ "1": {
647+ "name": "keyword.control.export.ts"
648+ },
649+ "2": {
650+ "name": "keyword.control.import.ts"
651+ },
652+ "3": {
653+ "name": "variable.other.readwrite.alias.ts"
654+ },
655+ "4": {
656+ "name": "keyword.operator.assignment.ts"
657+ },
658+ "5": {
659+ "name": "keyword.control.require.ts"
660+ },
661+ "6": {
662+ "name": "meta.brace.round.ts"
663+ }
664+ },
665+ "end": "\\)",
666+ "endCaptures": {
667+ "0": {
668+ "name": "meta.brace.round.ts"
669+ }
670+ },
671+ "patterns": [
672+ {
673+ "include": "#comment"
674+ },
675+ {
676+ "include": "#string"
677+ }
678+ ]
679+ },
680+ {
681+ "name": "meta.import-equals.internal.ts",
682+ "begin": "(?<!\\.|\\$)(?:(\\bexport)\\s+)?\\b(import)\\s+([_$[:alpha:]][_$[:alnum:]]*)\\s*(=)\\s*(?!require\\b)",
683+ "beginCaptures": {
684+ "1": {
685+ "name": "keyword.control.export.ts"
686+ },
687+ "2": {
688+ "name": "keyword.control.import.ts"
689+ },
690+ "3": {
691+ "name": "variable.other.readwrite.alias.ts"
692+ },
693+ "4": {
694+ "name": "keyword.operator.assignment.ts"
695+ }
696+ },
697+ "end": "(?=;|$)",
698+ "patterns": [
699+ {
700+ "include": "#comment"
701+ },
702+ {
703+ "match": "([_$[:alpha:]][_$[:alnum:]]*)\\s*(\\.)",
704+ "captures": {
705+ "1": {
706+ "name": "entity.name.type.module.ts"
707+ },
708+ "2": {
709+ "name": "punctuation.accessor.ts"
710+ }
711+ }
712+ },
713+ {
714+ "name": "variable.other.readwrite.ts",
715+ "match": "([_$[:alpha:]][_$[:alnum:]]*)"
716+ }
717+ ]
718+ }
719+ ]
720+ },
721+ "import-declaration": {
722+ "name": "meta.import.ts",
723+ "begin": "(?<!\\.|\\$)(?:(\\bexport)\\s+)?\\b(import)(?!(\\s*:)|(\\$))\\b",
724+ "beginCaptures": {
725+ "1": {
726+ "name": "keyword.control.export.ts"
727+ },
728+ "2": {
729+ "name": "keyword.control.import.ts"
730+ }
731+ },
732+ "end": "(?=;|$)",
733+ "patterns": [
734+ {
735+ "include": "#import-export-declaration"
736+ }
737+ ]
738+ },
739+ "export-declaration": {
740+ "patterns": [
741+ {
742+ "match": "(?<!\\.|\\$)\\b(export)\\s+(as)\\s+(namespace)\\s+([_$[:alpha:]][_$[:alnum:]]*)",
743+ "captures": {
744+ "1": {
745+ "name": "keyword.control.export.ts"
746+ },
747+ "2": {
748+ "name": "keyword.control.as.ts"
749+ },
750+ "3": {
751+ "name": "storage.type.namespace.ts"
752+ },
753+ "4": {
754+ "name": "entity.name.type.module.ts"
755+ }
756+ }
757+ },
758+ {
759+ "name": "meta.export.default.ts",
760+ "begin": "(?<!\\.|\\$)\\b(export)(?:(?:\\s*(=))|(?:\\s+(default)(?=\\s+)))",
761+ "beginCaptures": {
762+ "1": {
763+ "name": "keyword.control.export.ts"
764+ },
765+ "2": {
766+ "name": "keyword.operator.assignment.ts"
767+ },
768+ "3": {
769+ "name": "keyword.control.default.ts"
770+ }
771+ },
772+ "end": "(?=;|\\bexport\\b|\\bfunction\\b|\\bclass\\b|\\binterface\\b|\\blet\\b|\\bvar\\b|\\bconst\\b|\\bimport\\b|\\benum\\b|\\bnamespace\\b|\\bmodule\\b|\\btype\\b|\\babstract\\b|\\bdeclare\\b|\\basync\\b|$)",
773+ "patterns": [
774+ {
775+ "include": "#expression"
776+ }
777+ ]
778+ },
779+ {
780+ "name": "meta.export.ts",
781+ "begin": "(?<!\\.|\\$)\\b(export)(?!(\\s*:)|(\\$))\\b",
782+ "beginCaptures": {
783+ "0": {
784+ "name": "keyword.control.export.ts"
785+ }
786+ },
787+ "end": "(?=;|\\bexport\\b|\\bfunction\\b|\\bclass\\b|\\binterface\\b|\\blet\\b|\\bvar\\b|\\bconst\\b|\\bimport\\b|\\benum\\b|\\bnamespace\\b|\\bmodule\\b|\\btype\\b|\\babstract\\b|\\bdeclare\\b|\\basync\\b|$)",
788+ "patterns": [
789+ {
790+ "include": "#import-export-declaration"
791+ }
792+ ]
793+ }
794+ ]
795+ },
796+ "import-export-declaration": {
797+ "patterns": [
798+ {
799+ "include": "#comment"
800+ },
801+ {
802+ "include": "#string"
803+ },
804+ {
805+ "include": "#import-export-block"
806+ },
807+ {
808+ "name": "keyword.control.from.ts",
809+ "match": "\\bfrom\\b"
810+ },
811+ {
812+ "include": "#import-export-clause"
813+ }
814+ ]
815+ },
816+ "import-export-block": {
817+ "name": "meta.block.ts",
818+ "begin": "\\{",
819+ "beginCaptures": {
820+ "0": {
821+ "name": "punctuation.definition.block.ts"
822+ }
823+ },
824+ "end": "\\}",
825+ "endCaptures": {
826+ "0": {
827+ "name": "punctuation.definition.block.ts"
828+ }
829+ },
830+ "patterns": [
831+ {
832+ "include": "#import-export-clause"
833+ }
834+ ]
835+ },
836+ "import-export-clause": {
837+ "patterns": [
838+ {
839+ "include": "#comment"
840+ },
841+ {
842+ "comment": "(default|*|name) as alias",
843+ "match": "(?x) (?: \\b(default)\\b | (\\*) | ([_$[:alpha:]][_$[:alnum:]]*)) \\s+ (as) \\s+ (?: (\\b default \\b | \\*) | ([_$[:alpha:]][_$[:alnum:]]*))",
844+ "captures": {
845+ "1": {
846+ "name": "keyword.control.default.ts"
847+ },
848+ "2": {
849+ "name": "constant.language.import-export-all.ts"
850+ },
851+ "3": {
852+ "name": "variable.other.readwrite.ts"
853+ },
854+ "4": {
855+ "name": "keyword.control.as.ts"
856+ },
857+ "5": {
858+ "name": "invalid.illegal.ts"
859+ },
860+ "6": {
861+ "name": "variable.other.readwrite.alias.ts"
862+ }
863+ }
864+ },
865+ {
866+ "include": "#punctuation-comma"
867+ },
868+ {
869+ "name": "constant.language.import-export-all.ts",
870+ "match": "\\*"
871+ },
872+ {
873+ "name": "keyword.control.default.ts",
874+ "match": "\\b(default)\\b"
875+ },
876+ {
877+ "name": "variable.other.readwrite.alias.ts",
878+ "match": "([_$[:alpha:]][_$[:alnum:]]*)"
879+ }
880+ ]
881+ },
882+ "class-or-interface-declaration": {
883+ "name": "meta.class.ts",
884+ "begin": "(?<!\\.|\\$)\\b(?:(export)\\s+)?\\b(?:(abstract)\\s+)?\\b(?:(class)|(interface))\\b",
885+ "beginCaptures": {
886+ "1": {
887+ "name": "keyword.control.export.ts"
888+ },
889+ "2": {
890+ "name": "storage.modifier.ts"
891+ },
892+ "3": {
893+ "name": "storage.type.class.ts"
894+ },
895+ "4": {
896+ "name": "storage.type.interface.ts"
897+ }
898+ },
899+ "end": "(?<=\\})",
900+ "endCaptures": {
901+ "1": {
902+ "name": "punctuation.definition.block.ts"
903+ }
904+ },
905+ "patterns": [
906+ {
907+ "include": "#comment"
908+ },
909+ {
910+ "include": "#class-or-interface-heritage"
911+ },
912+ {
913+ "match": "[_$[:alpha:]][_$[:alnum:]]*",
914+ "captures": {
915+ "0": {
916+ "name": "entity.name.type.class.ts"
917+ }
918+ }
919+ },
920+ {
921+ "include": "#type-parameters"
922+ },
923+ {
924+ "include": "#class-or-interface-body"
925+ }
926+ ]
927+ },
928+ "class-or-interface-heritage": {
929+ "begin": "(?<!\\.|\\$)(?:\\b(extends|implements)\\b)(?!\\$)",
930+ "beginCaptures": {
931+ "1": {
932+ "name": "storage.modifier.ts"
933+ }
934+ },
935+ "end": "(?=\\{)",
936+ "endCaptures": {
937+ "1": {
938+ "name": "punctuation.definition.block.ts"
939+ }
940+ },
941+ "patterns": [
942+ {
943+ "include": "#comment"
944+ },
945+ {
946+ "include": "#class-or-interface-heritage"
947+ },
948+ {
949+ "include": "#type-parameters"
950+ },
951+ {
952+ "match": "([_$[:alpha:]][_$[:alnum:]]*)\\s*(\\.)(?=\\s*[_$[:alpha:]][_$[:alnum:]]*(\\s*\\.\\s*[_$[:alpha:]][_$[:alnum:]]*)*\\s*([,<{]|extends|implements|//|/\\*))",
953+ "captures": {
954+ "1": {
955+ "name": "entity.name.type.module.ts"
956+ },
957+ "2": {
958+ "name": "punctuation.accessor.ts"
959+ }
960+ }
961+ },
962+ {
963+ "match": "([_$[:alpha:]][_$[:alnum:]]*)(?=\\s*([,<{]|extends|implements|//|/\\*))",
964+ "captures": {
965+ "1": {
966+ "name": "entity.other.inherited-class.ts"
967+ }
968+ }
969+ },
970+ {
971+ "include": "#expression"
972+ }
973+ ]
974+ },
975+ "class-or-interface-body": {
976+ "begin": "\\{",
977+ "beginCaptures": {
978+ "0": {
979+ "name": "punctuation.definition.block.ts"
980+ }
981+ },
982+ "end": "\\}",
983+ "endCaptures": {
984+ "0": {
985+ "name": "punctuation.definition.block.ts"
986+ }
987+ },
988+ "patterns": [
989+ {
990+ "include": "#string"
991+ },
992+ {
993+ "include": "#comment"
994+ },
995+ {
996+ "include": "#decorator"
997+ },
998+ {
999+ "include": "#method-declaration"
1000+ },
1001+ {
1002+ "include": "#indexer-declaration"
1003+ },
1004+ {
1005+ "include": "#field-declaration"
1006+ },
1007+ {
1008+ "include": "#type-annotation"
1009+ },
1010+ {
1011+ "include": "#variable-initializer"
1012+ },
1013+ {
1014+ "include": "#access-modifier"
1015+ },
1016+ {
1017+ "include": "#property-accessor"
1018+ },
1019+ {
1020+ "include": "#expression"
1021+ },
1022+ {
1023+ "include": "#punctuation-comma"
1024+ },
1025+ {
1026+ "include": "#punctuation-semicolon"
1027+ }
1028+ ]
1029+ },
1030+ "type-object": {
1031+ "name": "meta.object.type.ts",
1032+ "begin": "\\{",
1033+ "beginCaptures": {
1034+ "0": {
1035+ "name": "punctuation.definition.block.ts"
1036+ }
1037+ },
1038+ "end": "\\}",
1039+ "endCaptures": {
1040+ "0": {
1041+ "name": "punctuation.definition.block.ts"
1042+ }
1043+ },
1044+ "patterns": [
1045+ {
1046+ "include": "#type-object-members"
1047+ }
1048+ ]
1049+ },
1050+ "type-object-members": {
1051+ "patterns": [
1052+ {
1053+ "include": "#comment"
1054+ },
1055+ {
1056+ "include": "#method-declaration"
1057+ },
1058+ {
1059+ "include": "#indexer-declaration"
1060+ },
1061+ {
1062+ "include": "#field-declaration"
1063+ },
1064+ {
1065+ "include": "#type-annotation"
1066+ },
1067+ {
1068+ "begin": "\\.\\.\\.",
1069+ "beginCaptures": {
1070+ "0": {
1071+ "name": "keyword.operator.spread.ts"
1072+ }
1073+ },
1074+ "end": "(?=\\}|;|,|$)|(?<=\\})",
1075+ "patterns": [
1076+ {
1077+ "include": "#type"
1078+ }
1079+ ]
1080+ },
1081+ {
1082+ "include": "#punctuation-comma"
1083+ },
1084+ {
1085+ "include": "#punctuation-semicolon"
1086+ }
1087+ ]
1088+ },
1089+ "field-declaration": {
1090+ "name": "meta.field.declaration.ts",
1091+ "begin": "(?<!\\()(?:(?<!\\.|\\$)\\b(readonly)\\s+)?(?=(([_$[:alpha:]][_$[:alnum:]]*)|(\\'[^']*\\')|(\\\"[^\"]*\\\")|(\\[([^\\[\\]]|\\[[^\\[\\]]+\\])+\\]))\\s*(\\?\\s*)?(=|:))",
1092+ "beginCaptures": {
1093+ "1": {
1094+ "name": "storage.modifier.ts"
1095+ }
1096+ },
1097+ "end": "(?=\\}|;|,|$)|(?<=\\})",
1098+ "patterns": [
1099+ {
1100+ "include": "#variable-initializer"
1101+ },
1102+ {
1103+ "begin": "(?=((?:[_$[:alpha:]][_$[:alnum:]]*)|(?:\\'[^']*\\')|(?:\\\"[^\"]*\\\")|(\\[([^\\[\\]]|\\[[^\\[\\]]+\\])+\\]))\\s*(\\?\\s*)?(=|:))",
1104+ "end": "(?=[};,=]|$)|(?<=\\})",
1105+ "patterns": [
1106+ {
1107+ "include": "#type-annotation"
1108+ },
1109+ {
1110+ "include": "#string"
1111+ },
1112+ {
1113+ "include": "#array-literal"
1114+ },
1115+ {
1116+ "include": "#comment"
1117+ },
1118+ {
1119+ "name": "entity.name.function.ts",
1120+ "match": "(?x)([_$[:alpha:]][_$[:alnum:]]*)(?=(\\?\\s*)?\\s* (=\\s*( (async\\s+) | (function\\s*[(<]) | (function\\s+) | ([_$[:alpha:]][_$[:alnum:]]*\\s*=>) | ((<([^<>]|\\<[^<>]+\\>)+>\\s*)?\\(([^()]|\\([^()]*\\))*\\)(\\s*:\\s*(.)*)?\\s*=>)) ) | (:\\s*( (<) | ([(]\\s*( ([)]) | (\\.\\.\\.) | ([_$[:alnum:]]+\\s*( ([:,?=])| ([)]\\s*=>) )) ))) ))"
1121+ },
1122+ {
1123+ "name": "variable.object.property.ts",
1124+ "match": "[_$[:alpha:]][_$[:alnum:]]*"
1125+ },
1126+ {
1127+ "name": "keyword.operator.optional.ts",
1128+ "match": "\\?"
1129+ }
1130+ ]
1131+ }
1132+ ]
1133+ },
1134+ "method-declaration": {
1135+ "name": "meta.method.declaration.ts",
1136+ "begin": "(?<!\\.|\\$)(?:\\b(public|private|protected)\\s+)?(?:\\b(abstract)\\s+)?(?:\\b(async)\\s+)?(?:\\b(get|set)\\s+)?(?:(?:\\b(?:(new)|(constructor))\\b(?!\\$|:))|(?:(\\*)\\s*)?(?=((([_$[:alpha:]][_$[:alnum:]]*)|(\\'[^']*\\')|(\\\"[^\"]*\\\")|(\\[([^\\[\\]]|\\[[^\\[\\]]+\\])+\\]))\\s*(\\??))?\\s*[\\(\\<]))",
1137+ "beginCaptures": {
1138+ "1": {
1139+ "name": "storage.modifier.ts"
1140+ },
1141+ "2": {
1142+ "name": "storage.modifier.ts"
1143+ },
1144+ "3": {
1145+ "name": "storage.modifier.async.ts"
1146+ },
1147+ "4": {
1148+ "name": "storage.type.property.ts"
1149+ },
1150+ "5": {
1151+ "name": "keyword.operator.new.ts"
1152+ },
1153+ "6": {
1154+ "name": "storage.type.ts"
1155+ },
1156+ "7": {
1157+ "name": "keyword.generator.asterisk.ts"
1158+ }
1159+ },
1160+ "end": "(?=\\}|;|,)|(?<=\\})",
1161+ "patterns": [
1162+ {
1163+ "include": "#method-declaration-name"
1164+ },
1165+ {
1166+ "include": "#comment"
1167+ },
1168+ {
1169+ "include": "#type-parameters"
1170+ },
1171+ {
1172+ "include": "#function-parameters"
1173+ },
1174+ {
1175+ "include": "#return-type"
1176+ },
1177+ {
1178+ "include": "#method-overload-declaration"
1179+ },
1180+ {
1181+ "include": "#decl-block"
1182+ }
1183+ ]
1184+ },
1185+ "method-overload-declaration": {
1186+ "begin": "(?<!\\.|\\$)(?:\\b(public|private|protected)\\s+)?(?:\\b(abstract)\\s+)?(?:\\b(async)\\s+)?(?:\\b(get|set)\\s+)?(?:(?:\\b(?:(new)|(constructor))\\b(?!\\$|:))|(?:(\\*)\\s*)?(?=((([_$[:alpha:]][_$[:alnum:]]*)|(\\'[^']*\\')|(\\\"[^\"]*\\\")|(\\[([^\\[\\]]|\\[[^\\[\\]]+\\])+\\]))\\s*(\\??))?\\s*[\\(\\<]))",
1187+ "beginCaptures": {
1188+ "1": {
1189+ "name": "storage.modifier.ts"
1190+ },
1191+ "2": {
1192+ "name": "storage.modifier.ts"
1193+ },
1194+ "3": {
1195+ "name": "storage.modifier.async.ts"
1196+ },
1197+ "4": {
1198+ "name": "storage.type.property.ts"
1199+ },
1200+ "5": {
1201+ "name": "keyword.operator.new.ts"
1202+ },
1203+ "6": {
1204+ "name": "storage.type.ts"
1205+ },
1206+ "7": {
1207+ "name": "keyword.generator.asterisk.ts"
1208+ }
1209+ },
1210+ "end": "(?=\\(|\\<)",
1211+ "patterns": [
1212+ {
1213+ "include": "#method-declaration-name"
1214+ }
1215+ ]
1216+ },
1217+ "method-declaration-name": {
1218+ "begin": "(?=(([_$[:alpha:]][_$[:alnum:]]*)|(\\'[^']*\\')|(\\\"[^\"]*\\\")|(\\[([^\\[\\]]|\\[[^\\[\\]]+\\])+\\]))\\s*(\\??)\\s*[\\(\\<])",
1219+ "end": "(?=\\(|\\<)",
1220+ "patterns": [
1221+ {
1222+ "include": "#string"
1223+ },
1224+ {
1225+ "include": "#array-literal"
1226+ },
1227+ {
1228+ "name": "entity.name.function.ts",
1229+ "match": "[_$[:alpha:]][_$[:alnum:]]*"
1230+ },
1231+ {
1232+ "name": "keyword.operator.optional.ts",
1233+ "match": "\\?"
1234+ }
1235+ ]
1236+ },
1237+ "indexer-declaration": {
1238+ "name": "meta.indexer.declaration.ts",
1239+ "begin": "(?:(?<!\\.|\\$)\\b(readonly)\\s*)?(\\[)\\s*([_$[:alpha:]][_$[:alnum:]]*)\\s*(?=:)",
1240+ "beginCaptures": {
1241+ "1": {
1242+ "name": "storage.modifier.ts"
1243+ },
1244+ "2": {
1245+ "name": "meta.brace.square.ts"
1246+ },
1247+ "3": {
1248+ "name": "variable.parameter.ts"
1249+ }
1250+ },
1251+ "end": "(\\])\\s*(\\?\\s*)?|$",
1252+ "endCaptures": {
1253+ "1": {
1254+ "name": "meta.brace.square.ts"
1255+ },
1256+ "2": {
1257+ "name": "keyword.operator.optional.ts"
1258+ }
1259+ },
1260+ "patterns": [
1261+ {
1262+ "include": "#type-annotation"
1263+ }
1264+ ]
1265+ },
1266+ "function-declaration": {
1267+ "name": "meta.function.ts",
1268+ "begin": "(?<!\\.|\\$)\\b(?:(export)\\s+)?(?:(async)\\s+)?(function\\b)(?:\\s*(\\*))?(?:(?:\\s+|(?<=\\*))([_$[:alpha:]][_$[:alnum:]]*))?\\s*",
1269+ "beginCaptures": {
1270+ "1": {
1271+ "name": "keyword.control.export.ts"
1272+ },
1273+ "2": {
1274+ "name": "storage.modifier.async.ts"
1275+ },
1276+ "3": {
1277+ "name": "storage.type.function.ts"
1278+ },
1279+ "4": {
1280+ "name": "keyword.generator.asterisk.ts"
1281+ },
1282+ "5": {
1283+ "name": "entity.name.function.ts"
1284+ }
1285+ },
1286+ "end": "(?=;|\\})|(?<=\\})",
1287+ "patterns": [
1288+ {
1289+ "include": "#comment"
1290+ },
1291+ {
1292+ "include": "#type-parameters"
1293+ },
1294+ {
1295+ "include": "#function-parameters"
1296+ },
1297+ {
1298+ "include": "#return-type"
1299+ },
1300+ {
1301+ "include": "#function-overload-declaration"
1302+ },
1303+ {
1304+ "include": "#decl-block"
1305+ }
1306+ ]
1307+ },
1308+ "function-overload-declaration": {
1309+ "name": "meta.function.overload.ts",
1310+ "match": "(?<!\\.|\\$)\\b(?:(export)\\s+)?(?:(async)\\s+)?(function\\b)(?:\\s*(\\*))?(?:(?:\\s+|(?<=\\*))([_$[:alpha:]][_$[:alnum:]]*))?\\s*",
1311+ "captures": {
1312+ "1": {
1313+ "name": "keyword.control.export.ts"
1314+ },
1315+ "2": {
1316+ "name": "storage.modifier.async.ts"
1317+ },
1318+ "3": {
1319+ "name": "storage.type.function.ts"
1320+ },
1321+ "4": {
1322+ "name": "keyword.generator.asterisk.ts"
1323+ },
1324+ "5": {
1325+ "name": "entity.name.function.ts"
1326+ }
1327+ }
1328+ },
1329+ "object-literal": {
1330+ "name": "meta.objectliteral.ts",
1331+ "begin": "\\{",
1332+ "beginCaptures": {
1333+ "0": {
1334+ "name": "punctuation.definition.block.ts"
1335+ }
1336+ },
1337+ "end": "\\}",
1338+ "endCaptures": {
1339+ "0": {
1340+ "name": "punctuation.definition.block.ts"
1341+ }
1342+ },
1343+ "patterns": [
1344+ {
1345+ "include": "#object-member"
1346+ }
1347+ ]
1348+ },
1349+ "decl-block": {
1350+ "name": "meta.block.ts",
1351+ "begin": "\\{",
1352+ "beginCaptures": {
1353+ "0": {
1354+ "name": "punctuation.definition.block.ts"
1355+ }
1356+ },
1357+ "end": "\\}",
1358+ "endCaptures": {
1359+ "0": {
1360+ "name": "punctuation.definition.block.ts"
1361+ }
1362+ },
1363+ "patterns": [
1364+ {
1365+ "include": "#statements"
1366+ }
1367+ ]
1368+ },
1369+ "after-operator-block": {
1370+ "name": "meta.objectliteral.ts",
1371+ "begin": "(?<=[=(,\\[?+!]|await|return|yield|throw|in|of|typeof|&&|\\|\\||\\*)\\s*(\\{)",
1372+ "beginCaptures": {
1373+ "1": {
1374+ "name": "punctuation.definition.block.ts"
1375+ }
1376+ },
1377+ "end": "\\}",
1378+ "endCaptures": {
1379+ "0": {
1380+ "name": "punctuation.definition.block.ts"
1381+ }
1382+ },
1383+ "patterns": [
1384+ {
1385+ "include": "#object-member"
1386+ }
1387+ ]
1388+ },
1389+ "parameter-name": {
1390+ "patterns": [
1391+ {
1392+ "match": "(?x)(?:\\s*\\b(readonly)\\s+)?(?:\\s*\\b(public|private|protected)\\s+)?(\\.\\.\\.)?\\s*(?<!=|:)([_$[:alpha:]][_$[:alnum:]]*)\\s*(\\??)(?=\\s* (=\\s*( (async\\s+) | (function\\s*[(<]) | (function\\s+) | ([_$[:alpha:]][_$[:alnum:]]*\\s*=>) | ((<([^<>]|\\<[^<>]+\\>)+>\\s*)?\\(([^()]|\\([^()]*\\))*\\)(\\s*:\\s*(.)*)?\\s*=>)) ) | (:\\s*( (<) | ([(]\\s*( ([)]) | (\\.\\.\\.) | ([_$[:alnum:]]+\\s*( ([:,?=])| ([)]\\s*=>) )) ))) ))",
1393+ "captures": {
1394+ "1": {
1395+ "name": "storage.modifier.ts"
1396+ },
1397+ "2": {
1398+ "name": "storage.modifier.ts"
1399+ },
1400+ "3": {
1401+ "name": "keyword.operator.rest.ts"
1402+ },
1403+ "4": {
1404+ "name": "entity.name.function.ts"
1405+ },
1406+ "5": {
1407+ "name": "keyword.operator.optional.ts"
1408+ }
1409+ }
1410+ },
1411+ {
1412+ "match": "(?:\\s*\\b(readonly)\\s+)?(?:\\s*\\b(public|private|protected)\\s+)?(\\.\\.\\.)?\\s*(?<!=|:)([_$[:alpha:]][_$[:alnum:]]*)\\s*(\\??)",
1413+ "captures": {
1414+ "1": {
1415+ "name": "storage.modifier.ts"
1416+ },
1417+ "2": {
1418+ "name": "storage.modifier.ts"
1419+ },
1420+ "3": {
1421+ "name": "keyword.operator.rest.ts"
1422+ },
1423+ "4": {
1424+ "name": "variable.parameter.ts"
1425+ },
1426+ "5": {
1427+ "name": "keyword.operator.optional.ts"
1428+ }
1429+ }
1430+ }
1431+ ]
1432+ },
1433+ "destructuring-parameter": {
1434+ "patterns": [
1435+ {
1436+ "name": "meta.parameter.object-binding-pattern.ts",
1437+ "begin": "(?<!=|:)\\s*(\\{)",
1438+ "beginCaptures": {
1439+ "1": {
1440+ "name": "punctuation.definition.binding-pattern.object.ts"
1441+ }
1442+ },
1443+ "end": "\\}",
1444+ "endCaptures": {
1445+ "0": {
1446+ "name": "punctuation.definition.binding-pattern.object.ts"
1447+ }
1448+ },
1449+ "patterns": [
1450+ {
1451+ "include": "#parameter-object-binding-element"
1452+ }
1453+ ]
1454+ },
1455+ {
1456+ "name": "meta.paramter.array-binding-pattern.ts",
1457+ "begin": "(?<!=|:)\\s*(\\[)",
1458+ "beginCaptures": {
1459+ "1": {
1460+ "name": "punctuation.definition.binding-pattern.array.ts"
1461+ }
1462+ },
1463+ "end": "\\]",
1464+ "endCaptures": {
1465+ "0": {
1466+ "name": "punctuation.definition.binding-pattern.array.ts"
1467+ }
1468+ },
1469+ "patterns": [
1470+ {
1471+ "include": "#parameter-binding-element"
1472+ },
1473+ {
1474+ "include": "#punctuation-comma"
1475+ }
1476+ ]
1477+ }
1478+ ]
1479+ },
1480+ "parameter-object-binding-element": {
1481+ "patterns": [
1482+ {
1483+ "include": "#comment"
1484+ },
1485+ {
1486+ "begin": "(?=(([_$[:alpha:]][_$[:alnum:]]*)|(\\'[^']*\\')|(\\\"[^\"]*\\\")|(\\[([^\\[\\]]|\\[[^\\[\\]]+\\])+\\]))\\s*(:))",
1487+ "end": "(?=,|\\})",
1488+ "patterns": [
1489+ {
1490+ "include": "#object-binding-element-propertyName"
1491+ },
1492+ {
1493+ "include": "#parameter-binding-element"
1494+ }
1495+ ]
1496+ },
1497+ {
1498+ "include": "#parameter-object-binding-pattern"
1499+ },
1500+ {
1501+ "include": "#destructuring-parameter-rest"
1502+ },
1503+ {
1504+ "include": "#variable-initializer"
1505+ },
1506+ {
1507+ "include": "#punctuation-comma"
1508+ }
1509+ ]
1510+ },
1511+ "parameter-binding-element": {
1512+ "patterns": [
1513+ {
1514+ "include": "#comment"
1515+ },
1516+ {
1517+ "include": "#parameter-object-binding-pattern"
1518+ },
1519+ {
1520+ "include": "#parameter-array-binding-pattern"
1521+ },
1522+ {
1523+ "include": "#destructuring-parameter-rest"
1524+ },
1525+ {
1526+ "include": "#variable-initializer"
1527+ }
1528+ ]
1529+ },
1530+ "destructuring-parameter-rest": {
1531+ "match": "(?:(\\.\\.\\.)\\s*)?([_$[:alpha:]][_$[:alnum:]]*)",
1532+ "captures": {
1533+ "1": {
1534+ "name": "keyword.operator.rest.ts"
1535+ },
1536+ "2": {
1537+ "name": "variable.parameter.ts"
1538+ }
1539+ }
1540+ },
1541+ "parameter-object-binding-pattern": {
1542+ "begin": "(?:(\\.\\.\\.)\\s*)?(\\{)",
1543+ "beginCaptures": {
1544+ "1": {
1545+ "name": "keyword.operator.rest.ts"
1546+ },
1547+ "2": {
1548+ "name": "punctuation.definition.binding-pattern.object.ts"
1549+ }
1550+ },
1551+ "end": "\\}",
1552+ "endCaptures": {
1553+ "0": {
1554+ "name": "punctuation.definition.binding-pattern.object.ts"
1555+ }
1556+ },
1557+ "patterns": [
1558+ {
1559+ "include": "#parameter-object-binding-element"
1560+ }
1561+ ]
1562+ },
1563+ "parameter-array-binding-pattern": {
1564+ "begin": "(?:(\\.\\.\\.)\\s*)?(\\[)",
1565+ "beginCaptures": {
1566+ "1": {
1567+ "name": "keyword.operator.rest.ts"
1568+ },
1569+ "2": {
1570+ "name": "punctuation.definition.binding-pattern.array.ts"
1571+ }
1572+ },
1573+ "end": "\\]",
1574+ "endCaptures": {
1575+ "0": {
1576+ "name": "punctuation.definition.binding-pattern.array.ts"
1577+ }
1578+ },
1579+ "patterns": [
1580+ {
1581+ "include": "#parameter-binding-element"
1582+ },
1583+ {
1584+ "include": "#punctuation-comma"
1585+ }
1586+ ]
1587+ },
1588+ "return-type": {
1589+ "name": "meta.return.type.ts",
1590+ "begin": "(?<=\\))\\s*(:)",
1591+ "beginCaptures": {
1592+ "1": {
1593+ "name": "keyword.operator.type.annotation.ts"
1594+ }
1595+ },
1596+ "end": "(?<!:)((?=$)|(?=\\{|;|//|\\}))",
1597+ "patterns": [
1598+ {
1599+ "include": "#comment"
1600+ },
1601+ {
1602+ "name": "meta.object.type.ts",
1603+ "begin": "(?<=:)\\s*(\\{)",
1604+ "beginCaptures": {
1605+ "1": {
1606+ "name": "punctuation.definition.block.ts"
1607+ }
1608+ },
1609+ "end": "\\}",
1610+ "endCaptures": {
1611+ "0": {
1612+ "name": "punctuation.definition.block.ts"
1613+ }
1614+ },
1615+ "patterns": [
1616+ {
1617+ "include": "#type-object-members"
1618+ }
1619+ ]
1620+ },
1621+ {
1622+ "include": "#type-predicate-operator"
1623+ },
1624+ {
1625+ "include": "#type"
1626+ }
1627+ ]
1628+ },
1629+ "type-predicate-operator": {
1630+ "name": "keyword.operator.expression.is.ts",
1631+ "match": "(?<!\\.|\\$)\\bis\\b(?!\\$)"
1632+ },
1633+ "type-annotation": {
1634+ "name": "meta.type.annotation.ts",
1635+ "begin": ":",
1636+ "beginCaptures": {
1637+ "0": {
1638+ "name": "keyword.operator.type.annotation.ts"
1639+ }
1640+ },
1641+ "end": "(?=$|[,);\\}\\]]|//)|(?==[^>])|(?<=[\\}>\\]\\)]|[_$[:alpha:]])\\s*(?=\\{)",
1642+ "patterns": [
1643+ {
1644+ "include": "#comment"
1645+ },
1646+ {
1647+ "include": "#type"
1648+ }
1649+ ]
1650+ },
1651+ "type": {
1652+ "name": "meta.type.ts",
1653+ "patterns": [
1654+ {
1655+ "include": "#comment"
1656+ },
1657+ {
1658+ "include": "#string"
1659+ },
1660+ {
1661+ "include": "#numeric-literal"
1662+ },
1663+ {
1664+ "include": "#type-primitive"
1665+ },
1666+ {
1667+ "include": "#type-builtin-literals"
1668+ },
1669+ {
1670+ "include": "#type-parameters"
1671+ },
1672+ {
1673+ "include": "#type-tuple"
1674+ },
1675+ {
1676+ "include": "#type-object"
1677+ },
1678+ {
1679+ "include": "#type-operators"
1680+ },
1681+ {
1682+ "include": "#type-fn-type-parameters"
1683+ },
1684+ {
1685+ "include": "#type-paren-or-function-parameters"
1686+ },
1687+ {
1688+ "include": "#type-function-return-type"
1689+ },
1690+ {
1691+ "include": "#type-name"
1692+ }
1693+ ]
1694+ },
1695+ "function-parameters": {
1696+ "name": "meta.parameters.ts",
1697+ "begin": "\\(",
1698+ "beginCaptures": {
modified extensions/vscode/textmate-syntaxes/TypeScriptReact.tmLanguage.json +3571 −3573

The diff of this file is cut short. View the file.

@@ -1,3574 +1,1427 @@
11 {
2- "name": "TypeScriptReact",
3- "scopeName": "source.tsx",
4- "fileTypes": [
5- "tsx"
6- ],
7- "uuid": "805375ec-d614-41f5-8993-5843fe63ea82",
8- "patterns": [
9- {
10- "include": "#directives"
11- },
12- {
13- "include": "#statements"
14- },
15- {
16- "name": "comment.line.shebang.ts",
17- "match": "\\A(#!).*(?=$)",
18- "captures": {
19- "1": {
20- "name": "punctuation.definition.comment.ts"
21- }
22- }
23- }
24- ],
25- "repository": {
26- "statements": {
27- "patterns": [
28- {
29- "include": "#string"
30- },
31- {
32- "include": "#template"
33- },
34- {
35- "include": "#comment"
36- },
37- {
38- "include": "#literal"
39- },
40- {
41- "include": "#declaration"
42- },
43- {
44- "include": "#switch-statement"
45- },
46- {
47- "include": "#for-loop"
48- },
49- {
50- "include": "#after-operator-block"
51- },
52- {
53- "include": "#decl-block"
54- },
55- {
56- "include": "#control-statement"
57- },
58- {
59- "include": "#expression"
60- },
61- {
62- "include": "#punctuation-semicolon"
63- }
64- ]
65- },
66- "var-expr": {
67- "name": "meta.var.expr.tsx",
68- "begin": "(?<!\\.|\\$)(?:(\\bexport)\\s+)?\\b(var|let|const(?!\\s+enum\\b))\\b(?!\\$)",
69- "beginCaptures": {
70- "1": {
71- "name": "keyword.control.export.tsx"
72- },
73- "2": {
74- "name": "storage.type.tsx"
75- }
76- },
77- "end": "(?=$|;|}|(\\s+(of|in)\\s+))",
78- "patterns": [
79- {
80- "include": "#destructuring-variable"
81- },
82- {
83- "include": "#var-single-variable"
84- },
85- {
86- "include": "#variable-initializer"
87- },
88- {
89- "include": "#comment"
90- },
91- {
92- "include": "#punctuation-comma"
93- }
94- ]
95- },
96- "var-single-variable": {
97- "patterns": [
98- {
99- "name": "meta.var-single-variable.expr.tsx",
100- "begin": "(?x)([_$[:alpha:]][_$[:alnum:]]*)(?=\\s* (=\\s*( (async\\s+) | (function\\s*[(<]) | (function\\s+) | ([_$[:alpha:]][_$[:alnum:]]*\\s*=>) | ((<([^<>]|\\<[^<>]+\\>)+>\\s*)?\\(([^()]|\\([^()]*\\))*\\)(\\s*:\\s*(.)*)?\\s*=>)) ) | (:\\s*( (<) | ([(]\\s*( ([)]) | (\\.\\.\\.) | ([_$[:alnum:]]+\\s*( ([:,?=])| ([)]\\s*=>) )) ))) ))",
101- "beginCaptures": {
102- "1": {
103- "name": "entity.name.function.tsx"
104- }
105- },
106- "end": "(?=$|[;,=}]|(\\s+(of|in)\\s+))",
107- "patterns": [
108- {
109- "include": "#type-annotation"
110- },
111- {
112- "include": "#string"
113- },
114- {
115- "include": "#comment"
116- }
117- ]
118- },
119- {
120- "name": "meta.var-single-variable.expr.tsx",
121- "begin": "([_$[:alpha:]][_$[:alnum:]]*)",
122- "beginCaptures": {
123- "1": {
124- "name": "variable.other.readwrite.tsx"
125- }
126- },
127- "end": "(?=$|[;,=}]|(\\s+(of|in)\\s+))",
128- "patterns": [
129- {
130- "include": "#type-annotation"
131- },
132- {
133- "include": "#string"
134- },
135- {
136- "include": "#comment"
137- }
138- ]
139- }
140- ]
141- },
142- "destructuring-variable": {
143- "patterns": [
144- {
145- "name": "meta.object-binding-pattern-variable.tsx",
146- "begin": "(?<!=|:|of|in)\\s*(?=\\{)",
147- "end": "(?=$|[;,=}]|(\\s+(of|in)\\s+))",
148- "patterns": [
149- {
150- "include": "#object-binding-pattern"
151- },
152- {
153- "include": "#type-annotation"
154- },
155- {
156- "include": "#comment"
157- }
158- ]
159- },
160- {
161- "name": "meta.array-binding-pattern-variable.tsx",
162- "begin": "(?<!=|:|of|in)\\s*(?=\\[)",
163- "end": "(?=$|[;,=}]|(\\s+(of|in)\\s+))",
164- "patterns": [
165- {
166- "include": "#array-binding-pattern"
167- },
168- {
169- "include": "#type-annotation"
170- },
171- {
172- "include": "#comment"
173- }
174- ]
175- }
176- ]
177- },
178- "object-binding-element": {
179- "patterns": [
180- {
181- "include": "#comment"
182- },
183- {
184- "begin": "(?=(([_$[:alpha:]][_$[:alnum:]]*)|(\\'[^']*\\')|(\\\"[^\"]*\\\")|(\\[([^\\[\\]]|\\[[^\\[\\]]+\\])+\\]))\\s*(:))",
185- "end": "(?=,|\\})",
186- "patterns": [
187- {
188- "include": "#object-binding-element-propertyName"
189- },
190- {
191- "include": "#binding-element"
192- }
193- ]
194- },
195- {
196- "include": "#object-binding-pattern"
197- },
198- {
199- "include": "#destructuring-variable-rest"
200- },
201- {
202- "include": "#variable-initializer"
203- },
204- {
205- "include": "#punctuation-comma"
206- }
207- ]
208- },
209- "object-binding-element-propertyName": {
210- "begin": "(?=(([_$[:alpha:]][_$[:alnum:]]*)|(\\'[^']*\\')|(\\\"[^\"]*\\\")|(\\[([^\\[\\]]|\\[[^\\[\\]]+\\])+\\]))\\s*(:))",
211- "end": "(:)",
212- "endCaptures": {
213- "0": {
214- "name": "punctuation.destructuring.tsx"
215- }
216- },
217- "patterns": [
218- {
219- "include": "#string"
220- },
221- {
222- "include": "#array-literal"
223- },
224- {
225- "name": "variable.object.property.tsx",
226- "match": "([_$[:alpha:]][_$[:alnum:]]*)"
227- }
228- ]
229- },
230- "binding-element": {
231- "patterns": [
232- {
233- "include": "#comment"
234- },
235- {
236- "include": "#object-binding-pattern"
237- },
238- {
239- "include": "#array-binding-pattern"
240- },
241- {
242- "include": "#destructuring-variable-rest"
243- },
244- {
245- "include": "#variable-initializer"
246- }
247- ]
248- },
249- "destructuring-variable-rest": {
250- "match": "(?:(\\.\\.\\.)\\s*)?([_$[:alpha:]][_$[:alnum:]]*)",
251- "captures": {
252- "1": {
253- "name": "keyword.operator.rest.tsx"
254- },
255- "2": {
256- "name": "variable.other.readwrite.tsx"
257- }
258- }
259- },
260- "object-binding-pattern": {
261- "begin": "(?:(\\.\\.\\.)\\s*)?(\\{)",
262- "beginCaptures": {
263- "1": {
264- "name": "keyword.operator.rest.tsx"
265- },
266- "2": {
267- "name": "punctuation.definition.binding-pattern.object.tsx"
268- }
269- },
270- "end": "\\}",
271- "endCaptures": {
272- "0": {
273- "name": "punctuation.definition.binding-pattern.object.tsx"
274- }
275- },
276- "patterns": [
277- {
278- "include": "#object-binding-element"
279- }
280- ]
281- },
282- "array-binding-pattern": {
283- "begin": "(?:(\\.\\.\\.)\\s*)?(\\[)",
284- "beginCaptures": {
285- "1": {
286- "name": "keyword.operator.rest.tsx"
287- },
288- "2": {
289- "name": "punctuation.definition.binding-pattern.array.tsx"
290- }
291- },
292- "end": "\\]",
293- "endCaptures": {
294- "0": {
295- "name": "punctuation.definition.binding-pattern.array.tsx"
296- }
297- },
298- "patterns": [
299- {
300- "include": "#binding-element"
301- },
302- {
303- "include": "#punctuation-comma"
304- }
305- ]
306- },
307- "ternary-expression": {
308- "begin": "(?=\\?)",
309- "end": "(?=$|[;,})\\]])",
310- "patterns": [
311- {
312- "include": "#ternary-operator"
313- },
314- {
315- "include": "#expression"
316- }
317- ]
318- },
319- "ternary-operator": {
320- "begin": "(\\?)",
321- "beginCaptures": {
322- "0": {
323- "name": "keyword.operator.ternary.tsx"
324- }
325- },
326- "end": "(:)",
327- "endCaptures": {
328- "0": {
329- "name": "keyword.operator.ternary.tsx"
330- }
331- },
332- "patterns": [
333- {
334- "include": "#expression"
335- }
336- ]
337- },
338- "expression": {
339- "name": "meta.expression.tsx",
340- "patterns": [
341- {
342- "include": "#jsx"
343- },
344- {
345- "include": "#string"
346- },
347- {
348- "include": "#regex"
349- },
350- {
351- "include": "#template"
352- },
353- {
354- "include": "#comment"
355- },
356- {
357- "include": "#literal"
358- },
359- {
360- "include": "#function-declaration"
361- },
362- {
363- "include": "#class-or-interface-declaration"
364- },
365- {
366- "include": "#arrow-function"
367- },
368- {
369- "include": "#cast"
370- },
371- {
372- "include": "#ternary-expression"
373- },
374- {
375- "include": "#new-expr"
376- },
377- {
378- "include": "#object-literal"
379- },
380- {
381- "include": "#expression-operators"
382- },
383- {
384- "include": "#function-call"
385- },
386- {
387- "include": "#support-objects"
388- },
389- {
390- "include": "#identifiers"
391- },
392- {
393- "include": "#paren-expression"
394- },
395- {
396- "include": "#punctuation-comma"
397- },
398- {
399- "include": "#punctuation-accessor"
400- }
401- ]
402- },
403- "control-statement": {
404- "patterns": [
405- {
406- "name": "keyword.control.trycatch.tsx",
407- "match": "(?<!\\.|\\$)\\b(catch|finally|throw|try)\\b(?!\\$)"
408- },
409- {
410- "name": "keyword.control.loop.tsx",
411- "match": "(?<!\\.|\\$)\\b(break|continue|do|goto|while)\\b(?!\\$)"
412- },
413- {
414- "name": "keyword.control.flow.tsx",
415- "match": "(?<!\\.|\\$)\\b(return)\\b(?!\\$)"
416- },
417- {
418- "match": "(?<!\\.|\\$)\\b(yield)\\b(?!\\$)(?:\\s*(\\*))?",
419- "captures": {
420- "1": {
421- "name": "keyword.control.flow.tsx"
422- },
423- "2": {
424- "name": "keyword.generator.asterisk.tsx"
425- }
426- }
427- },
428- {
429- "name": "keyword.control.switch.tsx",
430- "match": "(?<!\\.|\\$)\\b(case|default|switch)\\b(?!\\$)"
431- },
432- {
433- "name": "keyword.control.conditional.tsx",
434- "match": "(?<!\\.|\\$)\\b(else|if)\\b(?!\\$)"
435- },
436- {
437- "name": "keyword.control.with.tsx",
438- "match": "(?<!\\.|\\$)\\b(with)\\b(?!\\$)"
439- },
440- {
441- "name": "keyword.other.debugger.tsx",
442- "match": "(?<!\\.|\\$)\\b(debugger)\\b(?!\\$)"
443- },
444- {
445- "name": "storage.modifier.tsx",
446- "match": "(?<!\\.|\\$)\\b(declare)\\b(?!\\$)"
447- }
448- ]
449- },
450- "declaration": {
451- "name": "meta.declaration.tsx",
452- "patterns": [
453- {
454- "include": "#decorator"
455- },
456- {
457- "include": "#var-expr"
458- },
459- {
460- "include": "#function-declaration"
461- },
462- {
463- "include": "#class-or-interface-declaration"
464- },
465- {
466- "include": "#type-declaration"
467- },
468- {
469- "include": "#enum-declaration"
470- },
471- {
472- "include": "#namespace-declaration"
473- },
474- {
475- "include": "#import-equals-declaration"
476- },
477- {
478- "include": "#import-declaration"
479- },
480- {
481- "include": "#export-declaration"
482- }
483- ]
484- },
485- "decorator": {
486- "name": "meta.decorator.tsx",
487- "begin": "(?<!\\.|\\$)\\@",
488- "beginCaptures": {
489- "0": {
490- "name": "punctuation.decorator.tsx"
491- }
492- },
493- "end": "(?=\\s)",
494- "patterns": [
495- {
496- "include": "#expression"
497- }
498- ]
499- },
500- "type-declaration": {
501- "name": "meta.type.declaration.tsx",
502- "begin": "(?<!\\.|\\$)(?:(\\bexport)\\s+)?\\b(type)\\b\\s+([_$[:alpha:]][_$[:alnum:]]*)\\s*",
503- "beginCaptures": {
504- "1": {
505- "name": "keyword.control.export.tsx"
506- },
507- "2": {
508- "name": "storage.type.type.tsx"
509- },
510- "3": {
511- "name": "entity.name.type.tsx"
512- }
513- },
514- "end": "(?=[};]|\\bvar\\b|\\blet\\b|\\bconst\\b|\\btype\\b|\\bfunction\\b|\\bclass\\b|\\binterface\\b|\\bnamespace\\b|\\bmodule\\b|\\bimport\\b|\\benum\\b|\\bdeclare\\b|\\bexport\\b|\\babstract\\b|\\basync\\b)",
515- "patterns": [
516- {
517- "include": "#comment"
518- },
519- {
520- "include": "#type-parameters"
521- },
522- {
523- "include": "#type"
524- },
525- {
526- "match": "(=)\\s*",
527- "captures": {
528- "1": {
529- "name": "keyword.operator.assignment.tsx"
530- }
531- }
532- }
533- ]
534- },
535- "enum-declaration": {
536- "name": "meta.enum.declaration.tsx",
537- "begin": "(?<!\\.|\\$)(?:(\\bexport)\\s+)?(?:\\b(const)\\s+)?\\b(enum)\\s+([_$[:alpha:]][_$[:alnum:]]*)",
538- "beginCaptures": {
539- "1": {
540- "name": "keyword.control.export.tsx"
541- },
542- "2": {
543- "name": "storage.modifier.tsx"
544- },
545- "3": {
546- "name": "storage.type.enum.tsx"
547- },
548- "4": {
549- "name": "entity.name.type.enum.tsx"
550- }
551- },
552- "end": "(?<=\\})",
553- "patterns": [
554- {
555- "include": "#comment"
556- },
557- {
558- "begin": "\\{",
559- "beginCaptures": {
560- "0": {
561- "name": "punctuation.definition.block.tsx"
562- }
563- },
564- "end": "\\}",
565- "endCaptures": {
566- "0": {
567- "name": "punctuation.definition.block.tsx"
568- }
569- },
570- "patterns": [
571- {
572- "include": "#comment"
573- },
574- {
575- "begin": "([_$[:alpha:]][_$[:alnum:]]*)",
576- "beginCaptures": {
577- "0": {
578- "name": "variable.other.enummember.tsx"
579- }
580- },
581- "end": "(?=,|\\}|$)",
582- "patterns": [
583- {
584- "include": "#comment"
585- },
586- {
587- "include": "#variable-initializer"
588- }
589- ]
590- },
591- {
592- "begin": "(?=((\\'[^']*\\')|(\\\"[^\"]*\\\")|(\\[([^\\[\\]]|\\[[^\\[\\]]+\\])+\\])))",
593- "end": "(?=,|\\}|$)",
594- "patterns": [
595- {
596- "include": "#string"
597- },
598- {
599- "include": "#array-literal"
600- },
601- {
602- "include": "#comment"
603- },
604- {
605- "include": "#variable-initializer"
606- }
607- ]
608- },
609- {
610- "include": "#punctuation-comma"
611- }
612- ]
613- }
614- ]
615- },
616- "namespace-declaration": {
617- "name": "meta.namespace.declaration.tsx",
618- "begin": "(?<!\\.|\\$)(?:(\\bexport)\\s+)?\\b(namespace|module)\\s+",
619- "beginCaptures": {
620- "1": {
621- "name": "keyword.control.export.tsx"
622- },
623- "2": {
624- "name": "storage.type.namespace.tsx"
625- }
626- },
627- "end": "(?=$|\\{)",
628- "patterns": [
629- {
630- "include": "#comment"
631- },
632- {
633- "include": "#string"
634- },
635- {
636- "name": "entity.name.type.module.tsx",
637- "match": "([_$[:alpha:]][_$[:alnum:]]*)"
638- },
639- {
640- "name": "punctuation.accessor.tsx",
641- "match": "\\."
642- }
643- ]
644- },
645- "import-equals-declaration": {
646- "patterns": [
647- {
648- "name": "meta.import-equals.external.tsx",
649- "begin": "(?<!\\.|\\$)(?:(\\bexport)\\s+)?\\b(import)\\s+([_$[:alpha:]][_$[:alnum:]]*)\\s*(=)\\s*(require)\\s*(\\()",
650- "beginCaptures": {
651- "1": {
652- "name": "keyword.control.export.tsx"
653- },
654- "2": {
655- "name": "keyword.control.import.tsx"
656- },
657- "3": {
658- "name": "variable.other.readwrite.alias.tsx"
659- },
660- "4": {
661- "name": "keyword.operator.assignment.tsx"
662- },
663- "5": {
664- "name": "keyword.control.require.tsx"
665- },
666- "6": {
667- "name": "meta.brace.round.tsx"
668- }
669- },
670- "end": "\\)",
671- "endCaptures": {
672- "0": {
673- "name": "meta.brace.round.tsx"
674- }
675- },
676- "patterns": [
677- {
678- "include": "#comment"
679- },
680- {
681- "include": "#string"
682- }
683- ]
684- },
685- {
686- "name": "meta.import-equals.internal.tsx",
687- "begin": "(?<!\\.|\\$)(?:(\\bexport)\\s+)?\\b(import)\\s+([_$[:alpha:]][_$[:alnum:]]*)\\s*(=)\\s*(?!require\\b)",
688- "beginCaptures": {
689- "1": {
690- "name": "keyword.control.export.tsx"
691- },
692- "2": {
693- "name": "keyword.control.import.tsx"
694- },
695- "3": {
696- "name": "variable.other.readwrite.alias.tsx"
697- },
698- "4": {
699- "name": "keyword.operator.assignment.tsx"
700- }
701- },
702- "end": "(?=;|$)",
703- "patterns": [
704- {
705- "include": "#comment"
706- },
707- {
708- "match": "([_$[:alpha:]][_$[:alnum:]]*)\\s*(\\.)",
709- "captures": {
710- "1": {
711- "name": "entity.name.type.module.tsx"
712- },
713- "2": {
714- "name": "punctuation.accessor.tsx"
715- }
716- }
717- },
718- {
719- "name": "variable.other.readwrite.tsx",
720- "match": "([_$[:alpha:]][_$[:alnum:]]*)"
721- }
722- ]
723- }
724- ]
725- },
726- "import-declaration": {
727- "name": "meta.import.tsx",
728- "begin": "(?<!\\.|\\$)(?:(\\bexport)\\s+)?\\b(import)(?!(\\s*:)|(\\$))\\b",
729- "beginCaptures": {
730- "1": {
731- "name": "keyword.control.export.tsx"
732- },
733- "2": {
734- "name": "keyword.control.import.tsx"
735- }
736- },
737- "end": "(?=;|$)",
738- "patterns": [
739- {
740- "include": "#import-export-declaration"
741- }
742- ]
743- },
744- "export-declaration": {
745- "patterns": [
746- {
747- "match": "(?<!\\.|\\$)\\b(export)\\s+(as)\\s+(namespace)\\s+([_$[:alpha:]][_$[:alnum:]]*)",
748- "captures": {
749- "1": {
750- "name": "keyword.control.export.tsx"
751- },
752- "2": {
753- "name": "keyword.control.as.tsx"
754- },
755- "3": {
756- "name": "storage.type.namespace.tsx"
757- },
758- "4": {
759- "name": "entity.name.type.module.tsx"
760- }
761- }
762- },
763- {
764- "name": "meta.export.default.tsx",
765- "begin": "(?<!\\.|\\$)\\b(export)(?:(?:\\s*(=))|(?:\\s+(default)(?=\\s+)))",
766- "beginCaptures": {
767- "1": {
768- "name": "keyword.control.export.tsx"
769- },
770- "2": {
771- "name": "keyword.operator.assignment.tsx"
772- },
773- "3": {
774- "name": "keyword.control.default.tsx"
775- }
776- },
777- "end": "(?=;|\\bexport\\b|\\bfunction\\b|\\bclass\\b|\\binterface\\b|\\blet\\b|\\bvar\\b|\\bconst\\b|\\bimport\\b|\\benum\\b|\\bnamespace\\b|\\bmodule\\b|\\btype\\b|\\babstract\\b|\\bdeclare\\b|\\basync\\b|$)",
778- "patterns": [
779- {
780- "include": "#expression"
781- }
782- ]
783- },
784- {
785- "name": "meta.export.tsx",
786- "begin": "(?<!\\.|\\$)\\b(export)(?!(\\s*:)|(\\$))\\b",
787- "beginCaptures": {
788- "0": {
789- "name": "keyword.control.export.tsx"
790- }
791- },
792- "end": "(?=;|\\bexport\\b|\\bfunction\\b|\\bclass\\b|\\binterface\\b|\\blet\\b|\\bvar\\b|\\bconst\\b|\\bimport\\b|\\benum\\b|\\bnamespace\\b|\\bmodule\\b|\\btype\\b|\\babstract\\b|\\bdeclare\\b|\\basync\\b|$)",
793- "patterns": [
794- {
795- "include": "#import-export-declaration"
796- }
797- ]
798- }
799- ]
800- },
801- "import-export-declaration": {
802- "patterns": [
803- {
804- "include": "#comment"
805- },
806- {
807- "include": "#string"
808- },
809- {
810- "include": "#import-export-block"
811- },
812- {
813- "name": "keyword.control.from.tsx",
814- "match": "\\bfrom\\b"
815- },
816- {
817- "include": "#import-export-clause"
818- }
819- ]
820- },
821- "import-export-block": {
822- "name": "meta.block.tsx",
823- "begin": "\\{",
824- "beginCaptures": {
825- "0": {
826- "name": "punctuation.definition.block.tsx"
827- }
828- },
829- "end": "\\}",
830- "endCaptures": {
831- "0": {
832- "name": "punctuation.definition.block.tsx"
833- }
834- },
835- "patterns": [
836- {
837- "include": "#import-export-clause"
838- }
839- ]
840- },
841- "import-export-clause": {
842- "patterns": [
843- {
844- "include": "#comment"
845- },
846- {
847- "comment": "(default|*|name) as alias",
848- "match": "(?x) (?: \\b(default)\\b | (\\*) | ([_$[:alpha:]][_$[:alnum:]]*)) \\s+ (as) \\s+ (?: (\\b default \\b | \\*) | ([_$[:alpha:]][_$[:alnum:]]*))",
849- "captures": {
850- "1": {
851- "name": "keyword.control.default.tsx"
852- },
853- "2": {
854- "name": "constant.language.import-export-all.tsx"
855- },
856- "3": {
857- "name": "variable.other.readwrite.tsx"
858- },
859- "4": {
860- "name": "keyword.control.as.tsx"
861- },
862- "5": {
863- "name": "invalid.illegal.tsx"
864- },
865- "6": {
866- "name": "variable.other.readwrite.alias.tsx"
867- }
868- }
869- },
870- {
871- "include": "#punctuation-comma"
872- },
873- {
874- "name": "constant.language.import-export-all.tsx",
875- "match": "\\*"
876- },
877- {
878- "name": "keyword.control.default.tsx",
879- "match": "\\b(default)\\b"
880- },
881- {
882- "name": "variable.other.readwrite.alias.tsx",
883- "match": "([_$[:alpha:]][_$[:alnum:]]*)"
884- }
885- ]
886- },
887- "class-or-interface-declaration": {
888- "name": "meta.class.tsx",
889- "begin": "(?<!\\.|\\$)\\b(?:(export)\\s+)?\\b(?:(abstract)\\s+)?\\b(?:(class)|(interface))\\b",
890- "beginCaptures": {
891- "1": {
892- "name": "keyword.control.export.tsx"
893- },
894- "2": {
895- "name": "storage.modifier.tsx"
896- },
897- "3": {
898- "name": "storage.type.class.tsx"
899- },
900- "4": {
901- "name": "storage.type.interface.tsx"
902- }
903- },
904- "end": "(?<=\\})",
905- "endCaptures": {
906- "1": {
907- "name": "punctuation.definition.block.tsx"
908- }
909- },
910- "patterns": [
911- {
912- "include": "#comment"
913- },
914- {
915- "include": "#class-or-interface-heritage"
916- },
917- {
918- "match": "[_$[:alpha:]][_$[:alnum:]]*",
919- "captures": {
920- "0": {
921- "name": "entity.name.type.class.tsx"
922- }
923- }
924- },
925- {
926- "include": "#type-parameters"
927- },
928- {
929- "include": "#class-or-interface-body"
930- }
931- ]
932- },
933- "class-or-interface-heritage": {
934- "begin": "(?<!\\.|\\$)(?:\\b(extends|implements)\\b)(?!\\$)",
935- "beginCaptures": {
936- "1": {
937- "name": "storage.modifier.tsx"
938- }
939- },
940- "end": "(?=\\{)",
941- "endCaptures": {
942- "1": {
943- "name": "punctuation.definition.block.tsx"
944- }
945- },
946- "patterns": [
947- {
948- "include": "#comment"
949- },
950- {
951- "include": "#class-or-interface-heritage"
952- },
953- {
954- "include": "#type-parameters"
955- },
956- {
957- "match": "([_$[:alpha:]][_$[:alnum:]]*)\\s*(\\.)(?=\\s*[_$[:alpha:]][_$[:alnum:]]*(\\s*\\.\\s*[_$[:alpha:]][_$[:alnum:]]*)*\\s*([,<{]|extends|implements|//|/\\*))",
958- "captures": {
959- "1": {
960- "name": "entity.name.type.module.tsx"
961- },
962- "2": {
963- "name": "punctuation.accessor.tsx"
964- }
965- }
966- },
967- {
968- "match": "([_$[:alpha:]][_$[:alnum:]]*)(?=\\s*([,<{]|extends|implements|//|/\\*))",
969- "captures": {
970- "1": {
971- "name": "entity.other.inherited-class.tsx"
972- }
973- }
974- },
975- {
976- "include": "#expression"
977- }
978- ]
979- },
980- "class-or-interface-body": {
981- "begin": "\\{",
982- "beginCaptures": {
983- "0": {
984- "name": "punctuation.definition.block.tsx"
985- }
986- },
987- "end": "\\}",
988- "endCaptures": {
989- "0": {
990- "name": "punctuation.definition.block.tsx"
991- }
992- },
993- "patterns": [
994- {
995- "include": "#string"
996- },
997- {
998- "include": "#comment"
999- },
1000- {
1001- "include": "#decorator"
1002- },
1003- {
1004- "include": "#method-declaration"
1005- },
1006- {
1007- "include": "#indexer-declaration"
1008- },
1009- {
1010- "include": "#field-declaration"
1011- },
1012- {
1013- "include": "#type-annotation"
1014- },
1015- {
1016- "include": "#variable-initializer"
1017- },
1018- {
1019- "include": "#access-modifier"
1020- },
1021- {
1022- "include": "#property-accessor"
1023- },
1024- {
1025- "include": "#expression"
1026- },
1027- {
1028- "include": "#punctuation-comma"
1029- },
1030- {
1031- "include": "#punctuation-semicolon"
1032- }
1033- ]
1034- },
1035- "type-object": {
1036- "name": "meta.object.type.tsx",
1037- "begin": "\\{",
1038- "beginCaptures": {
1039- "0": {
1040- "name": "punctuation.definition.block.tsx"
1041- }
1042- },
1043- "end": "\\}",
1044- "endCaptures": {
1045- "0": {
1046- "name": "punctuation.definition.block.tsx"
1047- }
1048- },
1049- "patterns": [
1050- {
1051- "include": "#type-object-members"
1052- }
1053- ]
1054- },
1055- "type-object-members": {
1056- "patterns": [
1057- {
1058- "include": "#comment"
1059- },
1060- {
1061- "include": "#method-declaration"
1062- },
1063- {
1064- "include": "#indexer-declaration"
1065- },
1066- {
1067- "include": "#field-declaration"
1068- },
1069- {
1070- "include": "#type-annotation"
1071- },
1072- {
1073- "begin": "\\.\\.\\.",
1074- "beginCaptures": {
1075- "0": {
1076- "name": "keyword.operator.spread.tsx"
1077- }
1078- },
1079- "end": "(?=\\}|;|,|$)|(?<=\\})",
1080- "patterns": [
1081- {
1082- "include": "#type"
1083- }
1084- ]
1085- },
1086- {
1087- "include": "#punctuation-comma"
1088- },
1089- {
1090- "include": "#punctuation-semicolon"
1091- }
1092- ]
1093- },
1094- "field-declaration": {
1095- "name": "meta.field.declaration.tsx",
1096- "begin": "(?<!\\()(?:(?<!\\.|\\$)\\b(readonly)\\s+)?(?=(([_$[:alpha:]][_$[:alnum:]]*)|(\\'[^']*\\')|(\\\"[^\"]*\\\")|(\\[([^\\[\\]]|\\[[^\\[\\]]+\\])+\\]))\\s*(\\?\\s*)?(=|:))",
1097- "beginCaptures": {
1098- "1": {
1099- "name": "storage.modifier.tsx"
1100- }
1101- },
1102- "end": "(?=\\}|;|,|$)|(?<=\\})",
1103- "patterns": [
1104- {
1105- "include": "#variable-initializer"
1106- },
1107- {
1108- "begin": "(?=((?:[_$[:alpha:]][_$[:alnum:]]*)|(?:\\'[^']*\\')|(?:\\\"[^\"]*\\\")|(\\[([^\\[\\]]|\\[[^\\[\\]]+\\])+\\]))\\s*(\\?\\s*)?(=|:))",
1109- "end": "(?=[};,=]|$)|(?<=\\})",
1110- "patterns": [
1111- {
1112- "include": "#type-annotation"
1113- },
1114- {
1115- "include": "#string"
1116- },
1117- {
1118- "include": "#array-literal"
1119- },
1120- {
1121- "include": "#comment"
1122- },
1123- {
1124- "name": "entity.name.function.tsx",
1125- "match": "(?x)([_$[:alpha:]][_$[:alnum:]]*)(?=(\\?\\s*)?\\s* (=\\s*( (async\\s+) | (function\\s*[(<]) | (function\\s+) | ([_$[:alpha:]][_$[:alnum:]]*\\s*=>) | ((<([^<>]|\\<[^<>]+\\>)+>\\s*)?\\(([^()]|\\([^()]*\\))*\\)(\\s*:\\s*(.)*)?\\s*=>)) ) | (:\\s*( (<) | ([(]\\s*( ([)]) | (\\.\\.\\.) | ([_$[:alnum:]]+\\s*( ([:,?=])| ([)]\\s*=>) )) ))) ))"
1126- },
1127- {
1128- "name": "variable.object.property.tsx",
1129- "match": "[_$[:alpha:]][_$[:alnum:]]*"
1130- },
1131- {
1132- "name": "keyword.operator.optional.tsx",
1133- "match": "\\?"
1134- }
1135- ]
1136- }
1137- ]
1138- },
1139- "method-declaration": {
1140- "name": "meta.method.declaration.tsx",
1141- "begin": "(?<!\\.|\\$)(?:\\b(public|private|protected)\\s+)?(?:\\b(abstract)\\s+)?(?:\\b(async)\\s+)?(?:\\b(get|set)\\s+)?(?:(?:\\b(?:(new)|(constructor))\\b(?!\\$|:))|(?:(\\*)\\s*)?(?=((([_$[:alpha:]][_$[:alnum:]]*)|(\\'[^']*\\')|(\\\"[^\"]*\\\")|(\\[([^\\[\\]]|\\[[^\\[\\]]+\\])+\\]))\\s*(\\??))?\\s*[\\(\\<]))",
1142- "beginCaptures": {
1143- "1": {
1144- "name": "storage.modifier.tsx"
1145- },
1146- "2": {
1147- "name": "storage.modifier.tsx"
1148- },
1149- "3": {
1150- "name": "storage.modifier.async.tsx"
1151- },
1152- "4": {
1153- "name": "storage.type.property.tsx"
1154- },
1155- "5": {
1156- "name": "keyword.operator.new.tsx"
1157- },
1158- "6": {
1159- "name": "storage.type.tsx"
1160- },
1161- "7": {
1162- "name": "keyword.generator.asterisk.tsx"
1163- }
1164- },
1165- "end": "(?=\\}|;|,)|(?<=\\})",
1166- "patterns": [
1167- {
1168- "include": "#method-declaration-name"
1169- },
1170- {
1171- "include": "#comment"
1172- },
1173- {
1174- "include": "#type-parameters"
1175- },
1176- {
1177- "include": "#function-parameters"
1178- },
1179- {
1180- "include": "#return-type"
1181- },
1182- {
1183- "include": "#method-overload-declaration"
1184- },
1185- {
1186- "include": "#decl-block"
1187- }
1188- ]
1189- },
1190- "method-overload-declaration": {
1191- "begin": "(?<!\\.|\\$)(?:\\b(public|private|protected)\\s+)?(?:\\b(abstract)\\s+)?(?:\\b(async)\\s+)?(?:\\b(get|set)\\s+)?(?:(?:\\b(?:(new)|(constructor))\\b(?!\\$|:))|(?:(\\*)\\s*)?(?=((([_$[:alpha:]][_$[:alnum:]]*)|(\\'[^']*\\')|(\\\"[^\"]*\\\")|(\\[([^\\[\\]]|\\[[^\\[\\]]+\\])+\\]))\\s*(\\??))?\\s*[\\(\\<]))",
1192- "beginCaptures": {
1193- "1": {
1194- "name": "storage.modifier.tsx"
1195- },
1196- "2": {
1197- "name": "storage.modifier.tsx"
1198- },
1199- "3": {
1200- "name": "storage.modifier.async.tsx"
1201- },
1202- "4": {
1203- "name": "storage.type.property.tsx"
1204- },
1205- "5": {
1206- "name": "keyword.operator.new.tsx"
1207- },
1208- "6": {
1209- "name": "storage.type.tsx"
1210- },
1211- "7": {
1212- "name": "keyword.generator.asterisk.tsx"
1213- }
1214- },
1215- "end": "(?=\\(|\\<)",
1216- "patterns": [
1217- {
1218- "include": "#method-declaration-name"
1219- }
1220- ]
1221- },
1222- "method-declaration-name": {
1223- "begin": "(?=(([_$[:alpha:]][_$[:alnum:]]*)|(\\'[^']*\\')|(\\\"[^\"]*\\\")|(\\[([^\\[\\]]|\\[[^\\[\\]]+\\])+\\]))\\s*(\\??)\\s*[\\(\\<])",
1224- "end": "(?=\\(|\\<)",
1225- "patterns": [
1226- {
1227- "include": "#string"
1228- },
1229- {
1230- "include": "#array-literal"
1231- },
1232- {
1233- "name": "entity.name.function.tsx",
1234- "match": "[_$[:alpha:]][_$[:alnum:]]*"
1235- },
1236- {
1237- "name": "keyword.operator.optional.tsx",
1238- "match": "\\?"
1239- }
1240- ]
1241- },
1242- "indexer-declaration": {
1243- "name": "meta.indexer.declaration.tsx",
1244- "begin": "(?:(?<!\\.|\\$)\\b(readonly)\\s*)?(\\[)\\s*([_$[:alpha:]][_$[:alnum:]]*)\\s*(?=:)",
1245- "beginCaptures": {
1246- "1": {
1247- "name": "storage.modifier.tsx"
1248- },
1249- "2": {
1250- "name": "meta.brace.square.tsx"
1251- },
1252- "3": {
1253- "name": "variable.parameter.tsx"
1254- }
1255- },
1256- "end": "(\\])\\s*(\\?\\s*)?|$",
1257- "endCaptures": {
1258- "1": {
1259- "name": "meta.brace.square.tsx"
1260- },
1261- "2": {
1262- "name": "keyword.operator.optional.tsx"
1263- }
1264- },
1265- "patterns": [
1266- {
1267- "include": "#type-annotation"
1268- }
1269- ]
1270- },
1271- "function-declaration": {
1272- "name": "meta.function.tsx",
1273- "begin": "(?<!\\.|\\$)\\b(?:(export)\\s+)?(?:(async)\\s+)?(function\\b)(?:\\s*(\\*))?(?:(?:\\s+|(?<=\\*))([_$[:alpha:]][_$[:alnum:]]*))?\\s*",
1274- "beginCaptures": {
1275- "1": {
1276- "name": "keyword.control.export.tsx"
1277- },
1278- "2": {
1279- "name": "storage.modifier.async.tsx"
1280- },
1281- "3": {
1282- "name": "storage.type.function.tsx"
1283- },
1284- "4": {
1285- "name": "keyword.generator.asterisk.tsx"
1286- },
1287- "5": {
1288- "name": "entity.name.function.tsx"
1289- }
1290- },
1291- "end": "(?=;|\\})|(?<=\\})",
1292- "patterns": [
1293- {
1294- "include": "#comment"
1295- },
1296- {
1297- "include": "#type-parameters"
1298- },
1299- {
1300- "include": "#function-parameters"
1301- },
1302- {
1303- "include": "#return-type"
1304- },
1305- {
1306- "include": "#function-overload-declaration"
1307- },
1308- {
1309- "include": "#decl-block"
1310- }
1311- ]
1312- },
1313- "function-overload-declaration": {
1314- "name": "meta.function.overload.tsx",
1315- "match": "(?<!\\.|\\$)\\b(?:(export)\\s+)?(?:(async)\\s+)?(function\\b)(?:\\s*(\\*))?(?:(?:\\s+|(?<=\\*))([_$[:alpha:]][_$[:alnum:]]*))?\\s*",
1316- "captures": {
1317- "1": {
1318- "name": "keyword.control.export.tsx"
1319- },
1320- "2": {
1321- "name": "storage.modifier.async.tsx"
1322- },
1323- "3": {
1324- "name": "storage.type.function.tsx"
1325- },
1326- "4": {
1327- "name": "keyword.generator.asterisk.tsx"
1328- },
1329- "5": {
1330- "name": "entity.name.function.tsx"
1331- }
1332- }
1333- },
1334- "object-literal": {
1335- "name": "meta.objectliteral.tsx",
1336- "begin": "\\{",
1337- "beginCaptures": {
1338- "0": {
1339- "name": "punctuation.definition.block.tsx"
1340- }
1341- },
1342- "end": "\\}",
1343- "endCaptures": {
1344- "0": {
1345- "name": "punctuation.definition.block.tsx"
1346- }
1347- },
1348- "patterns": [
1349- {
1350- "include": "#object-member"
1351- }
1352- ]
1353- },
1354- "decl-block": {
1355- "name": "meta.block.tsx",
1356- "begin": "\\{",
1357- "beginCaptures": {
1358- "0": {
1359- "name": "punctuation.definition.block.tsx"
1360- }
1361- },
1362- "end": "\\}",
1363- "endCaptures": {
1364- "0": {
1365- "name": "punctuation.definition.block.tsx"
1366- }
1367- },
1368- "patterns": [
1369- {
1370- "include": "#statements"
1371- }
1372- ]
1373- },
1374- "after-operator-block": {
1375- "name": "meta.objectliteral.tsx",
1376- "begin": "(?<=[=(,\\[?+!]|await|return|yield|throw|in|of|typeof|&&|\\|\\||\\*)\\s*(\\{)",
1377- "beginCaptures": {
1378- "1": {
1379- "name": "punctuation.definition.block.tsx"
1380- }
1381- },
1382- "end": "\\}",
1383- "endCaptures": {
1384- "0": {
1385- "name": "punctuation.definition.block.tsx"
1386- }
1387- },
1388- "patterns": [
1389- {
1390- "include": "#object-member"
1391- }
1392- ]
1393- },
1394- "parameter-name": {
1395- "patterns": [
1396- {
1397- "match": "(?x)(?:\\s*\\b(readonly)\\s+)?(?:\\s*\\b(public|private|protected)\\s+)?(\\.\\.\\.)?\\s*(?<!=|:)([_$[:alpha:]][_$[:alnum:]]*)\\s*(\\??)(?=\\s* (=\\s*( (async\\s+) | (function\\s*[(<]) | (function\\s+) | ([_$[:alpha:]][_$[:alnum:]]*\\s*=>) | ((<([^<>]|\\<[^<>]+\\>)+>\\s*)?\\(([^()]|\\([^()]*\\))*\\)(\\s*:\\s*(.)*)?\\s*=>)) ) | (:\\s*( (<) | ([(]\\s*( ([)]) | (\\.\\.\\.) | ([_$[:alnum:]]+\\s*( ([:,?=])| ([)]\\s*=>) )) ))) ))",
1398- "captures": {
1399- "1": {
1400- "name": "storage.modifier.tsx"
1401- },
1402- "2": {
1403- "name": "storage.modifier.tsx"
1404- },
1405- "3": {
1406- "name": "keyword.operator.rest.tsx"
1407- },
1408- "4": {
1409- "name": "entity.name.function.tsx"
1410- },
1411- "5": {
1412- "name": "keyword.operator.optional.tsx"
1413- }
1414- }
1415- },
1416- {
1417- "match": "(?:\\s*\\b(readonly)\\s+)?(?:\\s*\\b(public|private|protected)\\s+)?(\\.\\.\\.)?\\s*(?<!=|:)([_$[:alpha:]][_$[:alnum:]]*)\\s*(\\??)",
1418- "captures": {
1419- "1": {
1420- "name": "storage.modifier.tsx"
1421- },
1422- "2": {
1423- "name": "storage.modifier.tsx"
1424- },
1425- "3": {
1426- "name": "keyword.operator.rest.tsx"
1427- },
1428- "4": {
1429- "name": "variable.parameter.tsx"
1430- },
1431- "5": {
1432- "name": "keyword.operator.optional.tsx"
1433- }
1434- }
1435- }
1436- ]
1437- },
1438- "destructuring-parameter": {
1439- "patterns": [
1440- {
1441- "name": "meta.parameter.object-binding-pattern.tsx",
1442- "begin": "(?<!=|:)\\s*(\\{)",
1443- "beginCaptures": {
1444- "1": {
1445- "name": "punctuation.definition.binding-pattern.object.tsx"
1446- }
1447- },
1448- "end": "\\}",
1449- "endCaptures": {
1450- "0": {
1451- "name": "punctuation.definition.binding-pattern.object.tsx"
1452- }
1453- },
1454- "patterns": [
1455- {
1456- "include": "#parameter-object-binding-element"
1457- }
1458- ]
1459- },
1460- {
1461- "name": "meta.paramter.array-binding-pattern.tsx",
1462- "begin": "(?<!=|:)\\s*(\\[)",
1463- "beginCaptures": {
1464- "1": {
1465- "name": "punctuation.definition.binding-pattern.array.tsx"
1466- }
1467- },
1468- "end": "\\]",
1469- "endCaptures": {
1470- "0": {
1471- "name": "punctuation.definition.binding-pattern.array.tsx"
1472- }
1473- },
1474- "patterns": [
1475- {
1476- "include": "#parameter-binding-element"
1477- },
1478- {
1479- "include": "#punctuation-comma"
1480- }
1481- ]
1482- }
1483- ]
1484- },
1485- "parameter-object-binding-element": {
1486- "patterns": [
1487- {
1488- "include": "#comment"
1489- },
1490- {
1491- "begin": "(?=(([_$[:alpha:]][_$[:alnum:]]*)|(\\'[^']*\\')|(\\\"[^\"]*\\\")|(\\[([^\\[\\]]|\\[[^\\[\\]]+\\])+\\]))\\s*(:))",
1492- "end": "(?=,|\\})",
1493- "patterns": [
1494- {
1495- "include": "#object-binding-element-propertyName"
1496- },
1497- {
1498- "include": "#parameter-binding-element"
1499- }
1500- ]
1501- },
1502- {
1503- "include": "#parameter-object-binding-pattern"
1504- },
1505- {
1506- "include": "#destructuring-parameter-rest"
1507- },
1508- {
1509- "include": "#variable-initializer"
1510- },
1511- {
1512- "include": "#punctuation-comma"
1513- }
1514- ]
1515- },
1516- "parameter-binding-element": {
1517- "patterns": [
1518- {
1519- "include": "#comment"
1520- },
1521- {
1522- "include": "#parameter-object-binding-pattern"
1523- },
1524- {
1525- "include": "#parameter-array-binding-pattern"
1526- },
1527- {
1528- "include": "#destructuring-parameter-rest"
1529- },
1530- {
1531- "include": "#variable-initializer"
1532- }
1533- ]
1534- },
1535- "destructuring-parameter-rest": {
1536- "match": "(?:(\\.\\.\\.)\\s*)?([_$[:alpha:]][_$[:alnum:]]*)",
1537- "captures": {
1538- "1": {
1539- "name": "keyword.operator.rest.tsx"
1540- },
1541- "2": {
1542- "name": "variable.parameter.tsx"
1543- }
1544- }
1545- },
1546- "parameter-object-binding-pattern": {
1547- "begin": "(?:(\\.\\.\\.)\\s*)?(\\{)",
1548- "beginCaptures": {
1549- "1": {
1550- "name": "keyword.operator.rest.tsx"
1551- },
1552- "2": {
1553- "name": "punctuation.definition.binding-pattern.object.tsx"
1554- }
1555- },
1556- "end": "\\}",
1557- "endCaptures": {
1558- "0": {
1559- "name": "punctuation.definition.binding-pattern.object.tsx"
1560- }
1561- },
1562- "patterns": [
1563- {
1564- "include": "#parameter-object-binding-element"
1565- }
1566- ]
1567- },
1568- "parameter-array-binding-pattern": {
1569- "begin": "(?:(\\.\\.\\.)\\s*)?(\\[)",
1570- "beginCaptures": {
1571- "1": {
1572- "name": "keyword.operator.rest.tsx"
1573- },
1574- "2": {
1575- "name": "punctuation.definition.binding-pattern.array.tsx"
1576- }
1577- },
1578- "end": "\\]",
1579- "endCaptures": {
1580- "0": {
1581- "name": "punctuation.definition.binding-pattern.array.tsx"
1582- }
1583- },
1584- "patterns": [
1585- {
1586- "include": "#parameter-binding-element"
1587- },
1588- {
1589- "include": "#punctuation-comma"
1590- }
1591- ]
1592- },
1593- "return-type": {
1594- "name": "meta.return.type.tsx",
1595- "begin": "(?<=\\))\\s*(:)",
1596- "beginCaptures": {
1597- "1": {
1598- "name": "keyword.operator.type.annotation.tsx"
1599- }
1600- },
1601- "end": "(?<!:)((?=$)|(?=\\{|;|//|\\}))",
1602- "patterns": [
1603- {
1604- "include": "#comment"
1605- },
1606- {
1607- "name": "meta.object.type.tsx",
1608- "begin": "(?<=:)\\s*(\\{)",
1609- "beginCaptures": {
1610- "1": {
1611- "name": "punctuation.definition.block.tsx"
1612- }
1613- },
1614- "end": "\\}",
1615- "endCaptures": {
1616- "0": {
1617- "name": "punctuation.definition.block.tsx"
1618- }
1619- },
1620- "patterns": [
1621- {
1622- "include": "#type-object-members"
1623- }
1624- ]
1625- },
1626- {
1627- "include": "#type-predicate-operator"
1628- },
1629- {
1630- "include": "#type"
1631- }
1632- ]
1633- },
1634- "type-predicate-operator": {
1635- "name": "keyword.operator.expression.is.tsx",
1636- "match": "(?<!\\.|\\$)\\bis\\b(?!\\$)"
1637- },
1638- "type-annotation": {
1639- "name": "meta.type.annotation.tsx",
1640- "begin": ":",
1641- "beginCaptures": {
1642- "0": {
1643- "name": "keyword.operator.type.annotation.tsx"
1644- }
1645- },
1646- "end": "(?=$|[,);\\}\\]]|//)|(?==[^>])|(?<=[\\}>\\]\\)]|[_$[:alpha:]])\\s*(?=\\{)",
1647- "patterns": [
1648- {
1649- "include": "#comment"
1650- },
1651- {
1652- "include": "#type"
1653- }
1654- ]
1655- },
1656- "type": {
1657- "name": "meta.type.tsx",
1658- "patterns": [
1659- {
1660- "include": "#comment"
1661- },
1662- {
1663- "include": "#string"
1664- },
1665- {
1666- "include": "#numeric-literal"
1667- },
1668- {
1669- "include": "#type-primitive"
1670- },
1671- {
1672- "include": "#type-builtin-literals"
1673- },
1674- {
1675- "include": "#type-parameters"
1676- },
1677- {
1678- "include": "#type-tuple"
1679- },
1680- {
1681- "include": "#type-object"
1682- },
1683- {
1684- "include": "#type-operators"
1685- },
1686- {
1687- "include": "#type-fn-type-parameters"
1688- },
1689- {
1690- "include": "#type-paren-or-function-parameters"
1691- },
1692- {
1693- "include": "#type-function-return-type"
1694- },
1695- {
1696- "include": "#type-name"
1697- }
1698- ]
1699- },
1700- "function-parameters": {
1701- "name": "meta.parameters.tsx",
1702- "begin": "\\(",
1703- "beginCaptures": {
1704- "0": {
1705- "name": "punctuation.definition.parameters.begin.tsx"
1706- }
1707- },
1708- "end": "\\)",
1709- "endCaptures": {
1710- "0": {
1711- "name": "punctuation.definition.parameters.end.tsx"
1712- }
1713- },
1714- "patterns": [
1715- {
1716- "include": "#comment"
1717- },
1718- {
1719- "include": "#decorator"
1720- },
1721- {
1722- "include": "#destructuring-parameter"
1723- },
1724- {
1725- "include": "#parameter-name"
1726- },
1727- {
1728- "include": "#type-annotation"
1729- },
1730- {
1731- "include": "#variable-initializer"
1732- },
1733- {
1734- "name": "punctuation.separator.parameter.tsx",
1735- "match": ","
1736- }
1737- ]
1738- },
1739- "type-primitive": {
1740- "name": "support.type.primitive.tsx",
1741- "match": "(?<!\\.|\\$)\\b(string|number|boolean|symbol|any|void|never)\\b(?!\\$)"
1742- },
1743- "type-builtin-literals": {
1744- "name": "support.type.builtin.tsx",
1745- "match": "(?<!\\.|\\$)\\b(this|true|false|undefined|null)\\b(?!\\$)"
1746- },
1747- "type-paren-or-function-parameters": {
1748- "name": "meta.type.paren.cover.tsx",
1749- "begin": "\\(",
1750- "beginCaptures": {
1751- "0": {
1752- "name": "meta.brace.round.tsx"
1753- }
1754- },
1755- "end": "\\)",
1756- "endCaptures": {
1757- "0": {
1758- "name": "meta.brace.round.tsx"
1759- }
1760- },
1761- "patterns": [
1762- {
1763- "include": "#type"
1764- },
1765- {
1766- "include": "#function-parameters"
1767- }
1768- ]
1769- },
1770- "type-fn-type-parameters": {
1771- "patterns": [
1772- {
1773- "name": "meta.type.constructor.tsx",
1774- "match": "(?<!\\.|\\$)\\b(new)\\b(?=\\s*\\<)",
1775- "captures": {
1776- "1": {
1777- "name": "keyword.control.new.tsx"
1778- }
1779- }
1780- },
1781- {
1782- "name": "meta.type.constructor.tsx",
1783- "begin": "(?<!\\.|\\$)\\b(new)\\b\\s*(?=\\()",
1784- "beginCaptures": {
1785- "1": {
1786- "name": "keyword.control.new.tsx"
1787- }
1788- },
1789- "end": "(?<=\\))",
1790- "patterns": [
1791- {
1792- "include": "#function-parameters"
1793- }
1794- ]
1795- },
1796- {
1797- "name": "meta.type.function.tsx",
1798- "begin": "(?<=\\>)\\s*(?=\\()",
1799- "end": "(?<=\\))",
1800- "patterns": [
1801- {
1802- "include": "#function-parameters"
1803- }
1804- ]
1805- },
1806- {
1807- "name": "meta.type.function.tsx",
1808- "begin": "(?x)( (?= [(]\\s*( ([)]) | (\\.\\.\\.) | ([_$[:alnum:]]+\\s*( ([:,?=])| ([)]\\s*=>) )) ) ) )",
1809- "end": "(?<=\\))",
1810- "patterns": [
1811- {
1812- "include": "#function-parameters"
1813- }
1814- ]
1815- }
1816- ]
1817- },
1818- "type-operators": {
1819- "patterns": [
1820- {
1821- "include": "#typeof-operator"
1822- },
1823- {
1824- "name": "keyword.operator.type.tsx",
1825- "match": "[&|]"
1826- },
1827- {
1828- "name": "keyword.operator.expression.keyof.tsx",
1829- "match": "(?<!\\.|\\$)\\bkeyof\\b(?!\\$)"
1830- }
1831- ]
1832- },
1833- "type-function-return-type": {
1834- "name": "meta.type.function.return.tsx",
1835- "begin": "=>",
1836- "beginCaptures": {
1837- "0": {
1838- "name": "storage.type.function.arrow.tsx"
1839- }
1840- },
1841- "end": "(?<!=>)(?=[,\\]\\)\\{\\}=;>]|//|$)",
1842- "patterns": [
1843- {
1844- "include": "#comment"
1845- },
1846- {
1847- "name": "meta.object.type.tsx",
1848- "begin": "(?<==>)\\s*(\\{)",
1849- "beginCaptures": {
1850- "1": {
1851- "name": "punctuation.definition.block.tsx"
1852- }
1853- },
1854- "end": "\\}",
1855- "endCaptures": {
1856- "0": {
1857- "name": "punctuation.definition.block.tsx"
1858- }
1859- },
1860- "patterns": [
1861- {
1862- "include": "#type-object-members"
1863- }
1864- ]
1865- },
1866- {
1867- "include": "#type-predicate-operator"
1868- },
1869- {
1870- "include": "#type"
1871- }
1872- ]
1873- },
1874- "type-tuple": {
1875- "name": "meta.type.tuple.tsx",
1876- "begin": "\\[",
1877- "beginCaptures": {
1878- "0": {
1879- "name": "meta.brace.square.tsx"
1880- }
1881- },
1882- "end": "\\]",
1883- "endCaptures": {
1884- "0": {
1885- "name": "meta.brace.square.tsx"
1886- }
1887- },
1888- "patterns": [
1889- {
1890- "include": "#type"
1891- },
1892- {
1893- "include": "#punctuation-comma"
1894- }
1895- ]
1896- },
1897- "type-name": {
1898- "patterns": [
1899- {
1900- "match": "([_$[:alpha:]][_$[:alnum:]]*)\\s*(\\.)",
1901- "captures": {
1902- "1": {
1903- "name": "entity.name.type.module.tsx"
1904- },
1905- "2": {
1906- "name": "punctuation.accessor.tsx"
1907- }
1908- }
1909- },
1910- {
1911- "name": "entity.name.type.tsx",
1912- "match": "[_$[:alpha:]][_$[:alnum:]]*"
1913- }
1914- ]
1915- },
1916- "type-parameters": {
1917- "name": "meta.type.parameters.tsx",
1918- "begin": "(<)",
1919- "beginCaptures": {
1920- "1": {
1921- "name": "punctuation.definition.typeparameters.begin.tsx"
1922- }
1923- },
1924- "end": "(?=$)|(>)",
1925- "endCaptures": {
1926- "1": {
1927- "name": "punctuation.definition.typeparameters.end.tsx"
1928- }
1929- },
1930- "patterns": [
1931- {
1932- "include": "#comment"
1933- },
1934- {
1935- "name": "storage.modifier.tsx",
1936- "match": "(?<!\\.|\\$)\\b(extends)\\b(?!\\$)"
1937- },
1938- {
1939- "include": "#type"
1940- },
1941- {
1942- "include": "#punctuation-comma"
1943- }
1944- ]
1945- },
1946- "variable-initializer": {
1947- "begin": "(?<!=|!)(=)(?!=)",
1948- "beginCaptures": {
1949- "1": {
1950- "name": "keyword.operator.assignment.tsx"
1951- }
1952- },
1953- "end": "(?=$|[,);}\\]])",
1954- "patterns": [
1955- {
1956- "include": "#expression"
1957- }
1958- ]
1959- },
1960- "for-loop": {
1961- "begin": "(?<!\\.|\\$)\\b(for)\\s*(\\()",
1962- "beginCaptures": {
1963- "1": {
1964- "name": "keyword.control.loop.tsx"
1965- },
1966- "2": {
1967- "name": "meta.brace.round.tsx"
1968- }
1969- },
1970- "end": "\\)",
1971- "endCaptures": {
1972- "0": {
1973- "name": "meta.brace.round.tsx"
1974- }
1975- },
1976- "patterns": [
1977- {
1978- "include": "#var-expr"
1979- },
1980- {
1981- "include": "#expression"
1982- },
1983- {
1984- "include": "#punctuation-semicolon"
1985- }
1986- ]
1987- },
1988- "switch-expression": {
1989- "name": "switch-expression.expr.tsx",
1990- "begin": "(?<!\\.|\\$)\\b(switch)\\s*(\\()",
1991- "beginCaptures": {
1992- "1": {
1993- "name": "keyword.control.switch.tsx"
1994- },
1995- "2": {
1996- "name": "meta.brace.round.tsx"
1997- }
1998- },
1999- "end": "\\)",
2000- "endCaptures": {
2001- "0": {
2002- "name": "meta.brace.round.tsx"
2003- }
2004- },
2005- "patterns": [
2006- {
2007- "include": "#expression"
2008- }
2009- ]
2010- },
2011- "switch-block": {
2012- "name": "switch-block.expr.tsx",
2013- "begin": "{",
2014- "beginCaptures": {
2015- "0": {
2016- "name": "punctuation.definition.block.tsx"
2017- }
2018- },
2019- "end": "(?=\\})",
2020- "patterns": [
2021- {
2022- "include": "#case-clause"
2023- },
2024- {
2025- "include": "#statements"
2026- }
2027- ]
2028- },
2029- "case-clause": {
2030- "name": "case-clause.expr.tsx",
2031- "begin": "(?<!\\.|\\$)\\b(case|default(?=:))\\b(?!\\$)",
2032- "beginCaptures": {
2033- "1": {
2034- "name": "keyword.control.switch.tsx"
2035- }
2036- },
2037- "end": ":",
2038- "endCaptures": {
2039- "0": {
2040- "name": "punctuation.definition.section.case-statement.tsx"
2041- }
2042- },
2043- "patterns": [
2044- {
2045- "include": "#expression"
2046- }
2047- ]
2048- },
2049- "switch-statement": {
2050- "name": "switch-statement.expr.tsx",
2051- "begin": "(?<!\\.|\\$)(?=\\bswitch\\s*\\()",
2052- "end": "}",
2053- "endCaptures": {
2054- "0": {
2055- "name": "punctuation.definition.block.tsx"
2056- }
2057- },
2058- "patterns": [
2059- {
2060- "include": "#switch-expression"
2061- },
2062- {
2063- "include": "#switch-block"
2064- }
2065- ]
2066- },
2067- "support-objects": {
2068- "patterns": [
2069- {
2070- "name": "variable.language.arguments.tsx",
2071- "match": "(?<!\\.|\\$)\\b(arguments)\\b(?!\\$)"
2072- },
2073- {
2074- "name": "support.class.builtin.tsx",
2075- "match": "(?x)(?<!\\.|\\$)\\b(Array|ArrayBuffer|Atomics|Boolean|DataView|Date|Float32Array|Float64Array|Function|Generator |GeneratorFunction|Int8Array|Int16Array|Int32Array|Intl|Map|Number|Object|Promise|Proxy |Reflect|RegExp|Set|SharedArrayBuffer|SIMD|String|Symbol|TypedArray |Uint8Array|Uint16Array|Uint32Array|Uint8ClampedArray|WeakMap|WeakSet)\\b(?!\\$)"
2076- },
2077- {
2078- "name": "support.class.error.tsx",
2079- "match": "(?<!\\.|\\$)\\b((Eval|Internal|Range|Reference|Syntax|Type|URI)?Error)\\b(?!\\$)"
2080- },
2081- {
2082- "name": "support.function.tsx",
2083- "match": "(?x)(?<!\\.|\\$)\\b(clear(Interval|Timeout)|decodeURI|decodeURIComponent|encodeURI|encodeURIComponent|escape|eval| isFinite|isNaN|parseFloat|parseInt|require|set(Interval|Timeout)|super|unescape|uneval)(?=\\s*\\()"
2084- },
2085- {
2086- "match": "(?x)(?<!\\.|\\$)\\b(Math)(?:\\s*(\\.)\\s*(?:\n (abs|acos|acosh|asin|asinh|atan|atan2|atanh|cbrt|ceil|clz32|cos|cosh|exp|\n expm1|floor|fround|hypot|imul|log|log10|log1p|log2|max|min|pow|random|\n round|sign|sin|sinh|sqrt|tan|tanh|trunc)\n |\n (E|LN10|LN2|LOG10E|LOG2E|PI|SQRT1_2|SQRT2)))?\\b(?!\\$)",
2087- "captures": {
2088- "1": {
2089- "name": "support.constant.math.tsx"
2090- },
2091- "2": {
2092- "name": "punctuation.accessor.tsx"
2093- },
2094- "3": {
2095- "name": "support.function.math.tsx"
2096- },
2097- "4": {
2098- "name": "support.constant.property.math.tsx"
2099- }
2100- }
2101- },
2102- {
2103- "match": "(?x)(?<!\\.|\\$)\\b(console)(?:\\s*(\\.)\\s*(\n assert|clear|count|debug|dir|error|group|groupCollapsed|groupEnd|info|log\n |profile|profileEnd|table|time|timeEnd|timeStamp|trace|warn))?\\b(?!\\$)",
2104- "captures": {
2105- "1": {
2106- "name": "support.class.console.tsx"
2107- },
2108- "2": {
2109- "name": "punctuation.accessor.tsx"
2110- },
2111- "3": {
2112- "name": "support.function.console.tsx"
2113- }
2114- }
2115- },
2116- {
2117- "match": "(?<!\\.|\\$)\\b(JSON)(?:\\s*(\\.)\\s*(parse|stringify))?\\b(?!\\$)",
2118- "captures": {
2119- "1": {
2120- "name": "support.constant.json.tsx"
2121- },
2122- "2": {
2123- "name": "punctuation.accessor.tsx"
2124- },
2125- "3": {
2126- "name": "support.function.json.tsx"
2127- }
2128- }
2129- },
2130- {
2131- "match": "(?x) (\\.) \\s* (?:\n (constructor|length|prototype|__proto__) \n |\n (EPSILON|MAX_SAFE_INTEGER|MAX_VALUE|MIN_SAFE_INTEGER|MIN_VALUE|NEGATIVE_INFINITY|POSITIVE_INFINITY))\\b(?!\\$)",
2132- "captures": {
2133- "1": {
2134- "name": "punctuation.accessor.tsx"
2135- },
2136- "2": {
2137- "name": "support.variable.property.tsx"
2138- },
2139- "3": {
2140- "name": "support.constant.tsx"
2141- }
2142- }
2143- },
2144- {
2145- "match": "(?x) (?<!\\.|\\$) \\b (?:\n (document|event|navigator|performance|screen|window) \n |\n (AnalyserNode|ArrayBufferView|Attr|AudioBuffer|AudioBufferSourceNode|AudioContext|AudioDestinationNode|AudioListener\n |AudioNode|AudioParam|BatteryManager|BeforeUnloadEvent|BiquadFilterNode|Blob|BufferSource|ByteString|CSS|CSSConditionRule\n |CSSCounterStyleRule|CSSGroupingRule|CSSMatrix|CSSMediaRule|CSSPageRule|CSSPrimitiveValue|CSSRule|CSSRuleList|CSSStyleDeclaration\n |CSSStyleRule|CSSStyleSheet|CSSSupportsRule|CSSValue|CSSValueList|CanvasGradient|CanvasImageSource|CanvasPattern\n |CanvasRenderingContext2D|ChannelMergerNode|ChannelSplitterNode|CharacterData|ChromeWorker|CloseEvent|Comment|CompositionEvent\n |Console|ConvolverNode|Coordinates|Credential|CredentialsContainer|Crypto|CryptoKey|CustomEvent|DOMError|DOMException\n |DOMHighResTimeStamp|DOMImplementation|DOMString|DOMStringList|DOMStringMap|DOMTimeStamp|DOMTokenList|DataTransfer\n |DataTransferItem|DataTransferItemList|DedicatedWorkerGlobalScope|DelayNode|DeviceProximityEvent|DirectoryEntry\n |DirectoryEntrySync|DirectoryReader|DirectoryReaderSync|Document|DocumentFragment|DocumentTouch|DocumentType|DragEvent\n |DynamicsCompressorNode|Element|Entry|EntrySync|ErrorEvent|Event|EventListener|EventSource|EventTarget|FederatedCredential\n |FetchEvent|File|FileEntry|FileEntrySync|FileException|FileList|FileReader|FileReaderSync|FileSystem|FileSystemSync\n |FontFace|FormData|GainNode|Gamepad|GamepadButton|GamepadEvent|Geolocation|GlobalEventHandlers|HTMLAnchorElement\n |HTMLAreaElement|HTMLAudioElement|HTMLBRElement|HTMLBaseElement|HTMLBodyElement|HTMLButtonElement|HTMLCanvasElement\n |HTMLCollection|HTMLContentElement|HTMLDListElement|HTMLDataElement|HTMLDataListElement|HTMLDialogElement|HTMLDivElement\n |HTMLDocument|HTMLElement|HTMLEmbedElement|HTMLFieldSetElement|HTMLFontElement|HTMLFormControlsCollection|HTMLFormElement\n |HTMLHRElement|HTMLHeadElement|HTMLHeadingElement|HTMLHtmlElement|HTMLIFrameElement|HTMLImageElement|HTMLInputElement\n |HTMLKeygenElement|HTMLLIElement|HTMLLabelElement|HTMLLegendElement|HTMLLinkElement|HTMLMapElement|HTMLMediaElement\n |HTMLMetaElement|HTMLMeterElement|HTMLModElement|HTMLOListElement|HTMLObjectElement|HTMLOptGroupElement|HTMLOptionElement\n |HTMLOptionsCollection|HTMLOutputElement|HTMLParagraphElement|HTMLParamElement|HTMLPreElement|HTMLProgressElement\n |HTMLQuoteElement|HTMLScriptElement|HTMLSelectElement|HTMLShadowElement|HTMLSourceElement|HTMLSpanElement|HTMLStyleElement\n |HTMLTableCaptionElement|HTMLTableCellElement|HTMLTableColElement|HTMLTableDataCellElement|HTMLTableElement|HTMLTableHeaderCellElement\n |HTMLTableRowElement|HTMLTableSectionElement|HTMLTextAreaElement|HTMLTimeElement|HTMLTitleElement|HTMLTrackElement\n |HTMLUListElement|HTMLUnknownElement|HTMLVideoElement|HashChangeEvent|History|IDBCursor|IDBCursorWithValue|IDBDatabase\n |IDBEnvironment|IDBFactory|IDBIndex|IDBKeyRange|IDBMutableFile|IDBObjectStore|IDBOpenDBRequest|IDBRequest|IDBTransaction\n |IDBVersionChangeEvent|IIRFilterNode|IdentityManager|ImageBitmap|ImageBitmapFactories|ImageData|Index|InputDeviceCapabilities\n |InputEvent|InstallEvent|InstallTrigger|KeyboardEvent|LinkStyle|LocalFileSystem|LocalFileSystemSync|Location|MIDIAccess\n |MIDIConnectionEvent|MIDIInput|MIDIInputMap|MIDIOutputMap|MediaElementAudioSourceNode|MediaError|MediaKeyMessageEvent\n |MediaKeySession|MediaKeyStatusMap|MediaKeySystemAccess|MediaKeySystemConfiguration|MediaKeys|MediaRecorder|MediaStream\n |MediaStreamAudioDestinationNode|MediaStreamAudioSourceNode|MessageChannel|MessageEvent|MessagePort|MouseEvent\n |MutationObserver|MutationRecord|NamedNodeMap|Navigator|NavigatorConcurrentHardware|NavigatorGeolocation|NavigatorID\n |NavigatorLanguage|NavigatorOnLine|Node|NodeFilter|NodeIterator|NodeList|NonDocumentTypeChildNode|Notification\n |OfflineAudioCompletionEvent|OfflineAudioContext|OscillatorNode|PageTransitionEvent|PannerNode|ParentNode|PasswordCredential\n |Path2D|PaymentAddress|PaymentRequest|PaymentResponse|Performance|PerformanceEntry|PerformanceFrameTiming|PerformanceMark\n |PerformanceMeasure|PerformanceNavigation|PerformanceNavigationTiming|PerformanceObserver|PerformanceObserverEntryList\n |PerformanceResourceTiming|PerformanceTiming|PeriodicSyncEvent|PeriodicWave|Plugin|Point|PointerEvent|PopStateEvent\n |PortCollection|Position|PositionError|PositionOptions|PresentationConnectionClosedEvent|PresentationConnectionList\n |PresentationReceiver|ProcessingInstruction|ProgressEvent|PromiseRejectionEvent|PushEvent|PushRegistrationManager\n |RTCCertificate|RTCConfiguration|RTCPeerConnection|RTCSessionDescriptionCallback|RTCStatsReport|RadioNodeList|RandomSource\n |Range|ReadableByteStream|RenderingContext|SVGAElement|SVGAngle|SVGAnimateColorElement|SVGAnimateElement|SVGAnimateMotionElement\n |SVGAnimateTransformElement|SVGAnimatedAngle|SVGAnimatedBoolean|SVGAnimatedEnumeration|SVGAnimatedInteger|SVGAnimatedLength\n |SVGAnimatedLengthList|SVGAnimatedNumber|SVGAnimatedNumberList|SVGAnimatedPoints|SVGAnimatedPreserveAspectRatio\n |SVGAnimatedRect|SVGAnimatedString|SVGAnimatedTransformList|SVGAnimationElement|SVGCircleElement|SVGClipPathElement\n |SVGCursorElement|SVGDefsElement|SVGDescElement|SVGElement|SVGEllipseElement|SVGEvent|SVGFilterElement|SVGFontElement\n |SVGFontFaceElement|SVGFontFaceFormatElement|SVGFontFaceNameElement|SVGFontFaceSrcElement|SVGFontFaceUriElement\n |SVGForeignObjectElement|SVGGElement|SVGGlyphElement|SVGGradientElement|SVGHKernElement|SVGImageElement|SVGLength\n |SVGLengthList|SVGLineElement|SVGLinearGradientElement|SVGMPathElement|SVGMaskElement|SVGMatrix|SVGMissingGlyphElement\n |SVGNumber|SVGNumberList|SVGPathElement|SVGPatternElement|SVGPoint|SVGPolygonElement|SVGPolylineElement|SVGPreserveAspectRatio\n |SVGRadialGradientElement|SVGRect|SVGRectElement|SVGSVGElement|SVGScriptElement|SVGSetElement|SVGStopElement|SVGStringList\n |SVGStylable|SVGStyleElement|SVGSwitchElement|SVGSymbolElement|SVGTRefElement|SVGTSpanElement|SVGTests|SVGTextElement\n |SVGTextPositioningElement|SVGTitleElement|SVGTransform|SVGTransformList|SVGTransformable|SVGUseElement|SVGVKernElement\n |SVGViewElement|ServiceWorker|ServiceWorkerContainer|ServiceWorkerGlobalScope|ServiceWorkerRegistration|ServiceWorkerState\n |ShadowRoot|SharedWorker|SharedWorkerGlobalScope|SourceBufferList|StereoPannerNode|Storage|StorageEvent|StyleSheet\n |StyleSheetList|SubtleCrypto|SyncEvent|Text|TextMetrics|TimeEvent|TimeRanges|Touch|TouchEvent|TouchList|Transferable\n |TreeWalker|UIEvent|USVString|VRDisplayCapabilities|ValidityState|WaveShaperNode|WebGL|WebGLActiveInfo|WebGLBuffer\n |WebGLContextEvent|WebGLFramebuffer|WebGLProgram|WebGLRenderbuffer|WebGLRenderingContext|WebGLShader|WebGLShaderPrecisionFormat\n |WebGLTexture|WebGLTimerQueryEXT|WebGLTransformFeedback|WebGLUniformLocation|WebGLVertexArrayObject|WebGLVertexArrayObjectOES\n |WebSocket|WebSockets|WebVTT|WheelEvent|Window|WindowBase64|WindowEventHandlers|WindowTimers|Worker|WorkerGlobalScope\n |WorkerLocation|WorkerNavigator|XMLHttpRequest|XMLHttpRequestEventTarget|XMLSerializer|XPathExpression|XPathResult\n |XSLTProcessor))\\b(?!\\$)",
2146- "captures": {
2147- "1": {
2148- "name": "support.variable.dom.tsx"
2149- },
2150- "2": {
2151- "name": "support.class.dom.tsx"
2152- }
2153- }
2154- },
2155- {
2156- "match": "(?x) (\\.) \\s* (?:\n (ATTRIBUTE_NODE|CDATA_SECTION_NODE|COMMENT_NODE|DOCUMENT_FRAGMENT_NODE|DOCUMENT_NODE|DOCUMENT_TYPE_NODE\n |DOMSTRING_SIZE_ERR|ELEMENT_NODE|ENTITY_NODE|ENTITY_REFERENCE_NODE|HIERARCHY_REQUEST_ERR|INDEX_SIZE_ERR\n |INUSE_ATTRIBUTE_ERR|INVALID_CHARACTER_ERR|NO_DATA_ALLOWED_ERR|NO_MODIFICATION_ALLOWED_ERR|NOT_FOUND_ERR\n |NOT_SUPPORTED_ERR|NOTATION_NODE|PROCESSING_INSTRUCTION_NODE|TEXT_NODE|WRONG_DOCUMENT_ERR)\n |\n (_content|[xyz]|abbr|above|accept|acceptCharset|accessKey|action|align|[av]Link(?:color)?|all|alt|anchors|appCodeName\n |appCore|applets|appMinorVersion|appName|appVersion|archive|areas|arguments|attributes|availHeight|availLeft|availTop\n |availWidth|axis|background|backgroundColor|backgroundImage|below|bgColor|body|border|borderBottomWidth|borderColor\n |borderLeftWidth|borderRightWidth|borderStyle|borderTopWidth|borderWidth|bottom|bufferDepth|callee|caller|caption\n |cellPadding|cells|cellSpacing|ch|characterSet|charset|checked|childNodes|chOff|cite|classes|className|clear\n |clientInformation|clip|clipBoardData|closed|code|codeBase|codeType|color|colorDepth|cols|colSpan|compact|complete\n |components|content|controllers|cookie|cookieEnabled|cords|cpuClass|crypto|current|data|dateTime|declare|defaultCharset\n |defaultChecked|defaultSelected|defaultStatus|defaultValue|defaultView|defer|description|dialogArguments|dialogHeight\n |dialogLeft|dialogTop|dialogWidth|dir|directories|disabled|display|docmain|doctype|documentElement|elements|embeds\n |enabledPlugin|encoding|enctype|entities|event|expando|external|face|fgColor|filename|firstChild|fontFamily|fontSize\n |fontWeight|form|formName|forms|frame|frameBorder|frameElement|frames|hasFocus|hash|headers|height|history|host\n |hostname|href|hreflang|hspace|htmlFor|httpEquiv|id|ids|ignoreCase|images|implementation|index|innerHeight|innerWidth\n |input|isMap|label|lang|language|lastChild|lastIndex|lastMatch|lastModified|lastParen|layer[sXY]|left|leftContext\n |lineHeight|link|linkColor|links|listStyleType|localName|location|locationbar|longDesc|lowsrc|lowSrc|marginBottom\n |marginHeight|marginLeft|marginRight|marginTop|marginWidth|maxLength|media|menubar|method|mimeTypes|multiline|multiple\n |name|nameProp|namespaces|namespaceURI|next|nextSibling|nodeName|nodeType|nodeValue|noHref|noResize|noShade|notationName\n |notations|noWrap|object|offscreenBuffering|onLine|onreadystatechange|opener|opsProfile|options|oscpu|outerHeight\n |outerWidth|ownerDocument|paddingBottom|paddingLeft|paddingRight|paddingTop|page[XY]|page[XY]Offset|parent|parentLayer\n |parentNode|parentWindow|pathname|personalbar|pixelDepth|pkcs11|platform|plugins|port|prefix|previous|previousDibling\n |product|productSub|profile|profileend|prompt|prompter|protocol|publicId|readOnly|readyState|referrer|rel|responseText\n |responseXML|rev|right|rightContext|rowIndex|rows|rowSpan|rules|scheme|scope|screen[XY]|screenLeft|screenTop|scripts\n |scrollbars|scrolling|sectionRowIndex|security|securityPolicy|selected|selectedIndex|selection|self|shape|siblingAbove\n |siblingBelow|size|source|specified|standby|start|status|statusbar|statusText|style|styleSheets|suffixes|summary\n |systemId|systemLanguage|tagName|tags|target|tBodies|text|textAlign|textDecoration|textIndent|textTransform|tFoot|tHead\n |title|toolbar|top|type|undefined|uniqueID|updateInterval|URL|URLUnencoded|useMap|userAgent|userLanguage|userProfile\n |vAlign|value|valueType|vendor|vendorSub|version|visibility|vspace|whiteSpace|width|X[MS]LDocument|zIndex))\\b(?!\\$|\\s*(<([^<>]|\\<[^<>]+\\>)+>\\s*)?\\()",
2157- "captures": {
2158- "1": {
2159- "name": "punctuation.accessor.tsx"
2160- },
2161- "2": {
2162- "name": "support.constant.dom.tsx"
2163- },
2164- "3": {
2165- "name": "support.variable.property.dom.tsx"
2166- }
2167- }
2168- },
2169- {
2170- "name": "support.class.node.tsx",
2171- "match": "(?x)(?<!\\.|\\$)\\b(Buffer|EventEmitter|Server|Pipe|Socket|REPLServer|ReadStream|WriteStream|Stream\n |Inflate|Deflate|InflateRaw|DeflateRaw|GZip|GUnzip|Unzip|Zip)\\b(?!\\$)"
2172- },
2173- {
2174- "name": "support.module.node.tsx",
2175- "match": "(?x)(?<!\\.|\\$)\\b(assert|buffer|child_process|cluster|constants|crypto|dgram|dns|domain|events|fs|http|https|net\n |os|path|punycode|querystring|readline|repl|stream|string_decoder|timers|tls|tty|url|util|vm|zlib)\\b(?!\\$)"
2176- },
2177- {
2178- "match": "(?x)(?<!\\.|\\$)\\b(process)(?:(\\.)(?:\n (arch|argv|config|connected|env|execArgv|execPath|exitCode|mainModule|pid|platform|release|stderr|stdin|stdout|title|version|versions)\n |\n (abort|chdir|cwd|disconnect|exit|[sg]ete?[gu]id|send|[sg]etgroups|initgroups|kill|memoryUsage|nextTick|umask|uptime|hrtime)\n))?\\b(?!\\$)",
2179- "captures": {
2180- "1": {
2181- "name": "support.variable.object.process.tsx"
2182- },
2183- "2": {
2184- "name": "punctuation.accessor.tsx"
2185- },
2186- "3": {
2187- "name": "support.variable.property.process.tsx"
2188- },
2189- "4": {
2190- "name": "support.function.process.tsx"
2191- }
2192- }
2193- },
2194- {
2195- "match": "(?<!\\.|\\$)\\b(?:(exports)|(module)(?:(\\.)(exports|id|filename|loaded|parent|children))?)\\b(?!\\$)",
2196- "captures": {
2197- "1": {
2198- "name": "support.type.object.module.tsx"
2199- },
2200- "2": {
2201- "name": "support.type.object.module.tsx"
2202- },
2203- "3": {
2204- "name": "punctuation.accessor.tsx"
2205- },
2206- "4": {
2207- "name": "support.type.object.module.tsx"
2208- }
2209- }
2210- },
2211- {
2212- "name": "support.variable.object.node.tsx",
2213- "match": "(?<!\\.|\\$)\\b(global|GLOBAL|root|__dirname|__filename)\\b(?!\\$)"
2214- },
2215- {
2216- "match": "(?x) (\\.) \\s* \n(?:\n (on(?:Rowsinserted|Rowsdelete|Rowenter|Rowexit|Resize|Resizestart|Resizeend|Reset|\n Readystatechange|Mouseout|Mouseover|Mousedown|Mouseup|Mousemove|\n Before(?:cut|deactivate|unload|update|paste|print|editfocus|activate)|\n Blur|Scrolltop|Submit|Select|Selectstart|Selectionchange|Hover|Help|\n Change|Contextmenu|Controlselect|Cut|Cellchange|Clock|Close|Deactivate|\n Datasetchanged|Datasetcomplete|Dataavailable|Drop|Drag|Dragstart|Dragover|\n Dragdrop|Dragenter|Dragend|Dragleave|Dblclick|Unload|Paste|Propertychange|Error|\n Errorupdate|Keydown|Keyup|Keypress|Focus|Load|Activate|Afterupdate|Afterprint|Abort)\n ) |\n (shift|showModelessDialog|showModalDialog|showHelp|scroll|scrollX|scrollByPages|\n scrollByLines|scrollY|scrollTo|stop|strike|sizeToContent|sidebar|signText|sort|\n sup|sub|substr|substring|splice|split|send|set(?:Milliseconds|Seconds|Minutes|Hours|\n Month|Year|FullYear|Date|UTC(?:Milliseconds|Seconds|Minutes|Hours|Month|FullYear|Date)|\n Time|Hotkeys|Cursor|ZOptions|Active|Resizable|RequestHeader)|search|slice|\n savePreferences|small|home|handleEvent|navigate|char|charCodeAt|charAt|concat|\n contextual|confirm|compile|clear|captureEvents|call|createStyleSheet|createPopup|\n createEventObject|to(?:GMTString|UTCString|String|Source|UpperCase|LowerCase|LocaleString)|\n test|taint|taintEnabled|indexOf|italics|disableExternalCapture|dump|detachEvent|unshift|\n untaint|unwatch|updateCommands|join|javaEnabled|pop|push|plugins.refresh|paddings|parse|\n print|prompt|preference|enableExternalCapture|exec|execScript|valueOf|UTC|find|file|\n fileModifiedDate|fileSize|fileCreatedDate|fileUpdatedDate|fixed|fontsize|fontcolor|\n forward|fromCharCode|watch|link|load|lastIndexOf|anchor|attachEvent|atob|apply|alert|\n abort|routeEvents|resize|resizeBy|resizeTo|recalc|returnValue|replace|reverse|reload|\n releaseCapture|releaseEvents|go|get(?:Milliseconds|Seconds|Minutes|Hours|Month|Day|Year|FullYear|\n Time|Date|TimezoneOffset|UTC(?:Milliseconds|Seconds|Minutes|Hours|Day|Month|FullYear|Date)|\n Attention|Selection|ResponseHeader|AllResponseHeaders)|moveBy|moveBelow|moveTo|\n moveToAbsolute|moveAbove|mergeAttributes|match|margins|btoa|big|bold|borderWidths|blink|back\n ) |\n (acceptNode|add|addEventListener|addTextTrack|adoptNode|after|animate|append|\n appendChild|appendData|before|blur|canPlayType|captureStream|\n caretPositionFromPoint|caretRangeFromPoint|checkValidity|clear|click|\n cloneContents|cloneNode|cloneRange|close|closest|collapse|\n compareBoundaryPoints|compareDocumentPosition|comparePoint|contains|\n convertPointFromNode|convertQuadFromNode|convertRectFromNode|createAttribute|\n createAttributeNS|createCaption|createCDATASection|createComment|\n createContextualFragment|createDocument|createDocumentFragment|\n createDocumentType|createElement|createElementNS|createEntityReference|\n createEvent|createExpression|createHTMLDocument|createNodeIterator|\n createNSResolver|createProcessingInstruction|createRange|createShadowRoot|\n createTBody|createTextNode|createTFoot|createTHead|createTreeWalker|delete|\n deleteCaption|deleteCell|deleteContents|deleteData|deleteRow|deleteTFoot|\n deleteTHead|detach|disconnect|dispatchEvent|elementFromPoint|elementsFromPoint|\n enableStyleSheetsForSet|entries|evaluate|execCommand|exitFullscreen|\n exitPointerLock|expand|extractContents|fastSeek|firstChild|focus|forEach|get|\n getAll|getAnimations|getAttribute|getAttributeNames|getAttributeNode|\n getAttributeNodeNS|getAttributeNS|getBoundingClientRect|getBoxQuads|\n getClientRects|getContext|getDestinationInsertionPoints|getElementById|\n getElementsByClassName|getElementsByName|getElementsByTagName|\n getElementsByTagNameNS|getItem|getNamedItem|getSelection|getStartDate|\n getVideoPlaybackQuality|has|hasAttribute|hasAttributeNS|hasAttributes|\n hasChildNodes|hasFeature|hasFocus|importNode|initEvent|insertAdjacentElement|\n insertAdjacentHTML|insertAdjacentText|insertBefore|insertCell|insertData|\n insertNode|insertRow|intersectsNode|isDefaultNamespace|isEqualNode|\n isPointInRange|isSameNode|item|key|keys|lastChild|load|lookupNamespaceURI|\n lookupPrefix|matches|move|moveAttribute|moveAttributeNode|moveChild|\n moveNamedItem|namedItem|nextNode|nextSibling|normalize|observe|open|\n parentNode|pause|play|postMessage|prepend|preventDefault|previousNode|\n previousSibling|probablySupportsContext|queryCommandEnabled|\n queryCommandIndeterm|queryCommandState|queryCommandSupported|queryCommandValue|\n querySelector|querySelectorAll|registerContentHandler|registerElement|\n registerProtocolHandler|releaseCapture|releaseEvents|remove|removeAttribute|\n removeAttributeNode|removeAttributeNS|removeChild|removeEventListener|\n removeItem|replace|replaceChild|replaceData|replaceWith|reportValidity|\n requestFullscreen|requestPointerLock|reset|scroll|scrollBy|scrollIntoView|\n scrollTo|seekToNextFrame|select|selectNode|selectNodeContents|set|setAttribute|\n setAttributeNode|setAttributeNodeNS|setAttributeNS|setCapture|\n setCustomValidity|setEnd|setEndAfter|setEndBefore|setItem|setNamedItem|\n setRangeText|setSelectionRange|setSinkId|setStart|setStartAfter|setStartBefore|\n slice|splitText|stepDown|stepUp|stopImmediatePropagation|stopPropagation|\n submit|substringData|supports|surroundContents|takeRecords|terminate|toBlob|\n toDataURL|toggle|toString|values|write|writeln\n )\n)(?=\\s*\\()",
2217- "captures": {
2218- "1": {
2219- "name": "punctuation.accessor.tsx"
2220- },
2221- "2": {
2222- "name": "support.function.event-handler.tsx"
2223- },
2224- "3": {
2225- "name": "support.function.tsx"
2226- },
2227- "4": {
2228- "name": "support.function.dom.tsx"
2229- }
2230- }
2231- }
2232- ]
2233- },
2234- "function-call": {
2235- "begin": "(?=(\\.\\s*)?([_$[:alpha:]][_$[:alnum:]]*)\\s*(<([^<>]|\\<[^<>]+\\>)+>\\s*)?\\()",
2236- "end": "(?<=\\))(?!(\\.\\s*)?([_$[:alpha:]][_$[:alnum:]]*)\\s*(<([^<>]|\\<[^<>]+\\>)+>\\s*)?\\()",
2237- "patterns": [
2238- {
2239- "include": "#support-objects"
2240- },
2241- {
2242- "name": "punctuation.accessor.tsx",
2243- "match": "\\."
2244- },
2245- {
2246- "name": "entity.name.function.tsx",
2247- "match": "([_$[:alpha:]][_$[:alnum:]]*)"
2248- },
2249- {
2250- "include": "#comment"
2251- },
2252- {
2253- "name": "meta.type.parameters.tsx",
2254- "begin": "\\<",
2255- "beginCaptures": {
2256- "0": {
2257- "name": "punctuation.definition.typeparameters.begin.tsx"
2258- }
2259- },
2260- "end": "\\>",
2261- "endCaptures": {
2262- "0": {
2263- "name": "punctuation.definition.typeparameters.end.tsx"
2264- }
2265- },
2266- "patterns": [
2267- {
2268- "include": "#type"
2269- },
2270- {
2271- "include": "#punctuation-comma"
2272- }
2273- ]
2274- },
2275- {
2276- "include": "#paren-expression"
2277- }
2278- ]
2279- },
2280- "identifiers": {
2281- "patterns": [
2282- {
2283- "name": "support.class.tsx",
2284- "match": "([_$[:alpha:]][_$[:alnum:]]*)(?=\\s*\\.\\s*prototype\\b(?!\\$))"
2285- },
2286- {
2287- "match": "(?x)(\\.)\\s*(?:\n ([[:upper:]][_$[:digit:][:upper:]]*) |\n ([_$[:alpha:]][_$[:alnum:]]*)\n)(?=\\s*\\.\\s*[_$[:alpha:]][_$[:alnum:]]*)",
2288- "captures": {
2289- "1": {
2290- "name": "punctuation.accessor.tsx"
2291- },
2292- "2": {
2293- "name": "constant.other.object.property.tsx"
2294- },
2295- "3": {
2296- "name": "variable.other.object.property.tsx"
2297- }
2298- }
2299- },
2300- {
2301- "match": "(?x)(?:(\\.)\\s*)?([_$[:alpha:]][_$[:alnum:]]*)(?=\\s*=\\s*( (async\\s+)|(function\\s*[(<])|(function\\s+)| ([_$[:alpha:]][_$[:alnum:]]*\\s*=>)| ((<([^<>]|\\<[^<>]+\\>)+>\\s*)?\\(([^()]|\\([^()]*\\))*\\)(\\s*:\\s*(.)*)?\\s*=>)))",
2302- "captures": {
2303- "1": {
2304- "name": "punctuation.accessor.tsx"
2305- },
2306- "2": {
2307- "name": "entity.name.function.tsx"
2308- }
2309- }
2310- },
2311- {
2312- "match": "(\\.)\\s*([[:upper:]][_$[:digit:][:upper:]]*)(?![_$[:alnum:]])",
2313- "captures": {
2314- "1": {
2315- "name": "punctuation.accessor.tsx"
2316- },
2317- "2": {
2318- "name": "constant.other.property.tsx"
2319- }
2320- }
2321- },
2322- {
2323- "match": "(\\.)\\s*([_$[:alpha:]][_$[:alnum:]]*)",
2324- "captures": {
2325- "1": {
2326- "name": "punctuation.accessor.tsx"
2327- },
2328- "2": {
2329- "name": "variable.other.property.tsx"
2330- }
2331- }
2332- },
2333- {
2334- "match": "(?x)(?:\n ([[:upper:]][_$[:digit:][:upper:]]*) |\n ([_$[:alpha:]][_$[:alnum:]]*)\n)(?=\\s*\\.\\s*[_$[:alpha:]][_$[:alnum:]]*)",
2335- "captures": {
2336- "1": {
2337- "name": "constant.other.object.tsx"
2338- },
2339- "2": {
2340- "name": "variable.other.object.tsx"
2341- }
2342- }
2343- },
2344- {
2345- "name": "constant.other.tsx",
2346- "match": "([[:upper:]][_$[:digit:][:upper:]]*)(?![_$[:alnum:]])"
2347- },
2348- {
2349- "name": "variable.other.readwrite.tsx",
2350- "match": "[_$[:alpha:]][_$[:alnum:]]*"
2351- }
2352- ]
2353- },
2354- "cast": {
2355- "patterns": [
2356- {
2357- "include": "#jsx"
2358- }
2359- ]
2360- },
2361- "new-expr": {
2362- "name": "new.expr.tsx",
2363- "begin": "(?<!\\.|\\$)\\b(new)\\b(?!\\$)",
2364- "beginCaptures": {
2365- "1": {
2366- "name": "keyword.operator.new.tsx"
2367- }
2368- },
2369- "end": "(?<=\\))|(?=[;),]|$|((?<!\\.|\\$)\\bnew\\b(?!\\$)))",
2370- "patterns": [
2371- {
2372- "include": "#paren-expression"
2373- },
2374- {
2375- "include": "#class-or-interface-declaration"
2376- },
2377- {
2378- "include": "#type"
2379- }
2380- ]
2381- },
2382- "object-member": {
2383- "patterns": [
2384- {
2385- "include": "#comment"
2386- },
2387- {
2388- "include": "#method-declaration"
2389- },
2390- {
2391- "name": "meta.object.member.tsx",
2392- "begin": "(?=(?:(?:\\'[^']*\\')|(?:\\\"[^\"]*\\\")|(?:\\[([^\\[\\]]|\\[[^\\[\\]]+\\])+\\]))\\s*:)",
2393- "end": "(?=,|\\})",
2394- "patterns": [
2395- {
2396- "name": "meta.object-literal.key.tsx",
2397- "begin": "(?=(?:(?:\\'[^']*\\')|(?:\\\"[^\"]*\\\")|(?:\\[([^\\[\\]]|\\[[^\\[\\]]+\\])+\\]))\\s*:)",
2398- "end": ":",
2399- "endCaptures": {
2400- "0": {
2401- "name": "punctuation.separator.key-value.tsx"
2402- }
2403- },
2404- "patterns": [
2405- {
2406- "include": "#string"
2407- },
2408- {
2409- "include": "#array-literal"
2410- }
2411- ]
2412- },
2413- {
2414- "include": "#expression"
2415- }
2416- ]
2417- },
2418- {
2419- "name": "meta.object.member.tsx",
2420- "begin": "(?x)(?:([_$[:alpha:]][_$[:alnum:]]*)\\s*(:)(?=\\s*( (async\\s+)|(function\\s*[(<])|(function\\s+)| ([_$[:alpha:]][_$[:alnum:]]*\\s*=>)| ((<([^<>]|\\<[^<>]+\\>)+>\\s*)?\\(([^()]|\\([^()]*\\))*\\)(\\s*:\\s*(.)*)?\\s*=>))))",
2421- "beginCaptures": {
2422- "0": {
2423- "name": "meta.object-literal.key.tsx"
2424- },
2425- "1": {
2426- "name": "entity.name.function.tsx"
2427- },
2428- "2": {
2429- "name": "punctuation.separator.key-value.tsx"
2430- }
2431- },
2432- "end": "(?=,|\\})",
2433- "patterns": [
2434- {
2435- "include": "#expression"
2436- }
2437- ]
2438- },
2439- {
2440- "name": "meta.object.member.tsx",
2441- "begin": "(?:[_$[:alpha:]][_$[:alnum:]]*)\\s*(:)",
2442- "beginCaptures": {
2443- "0": {
2444- "name": "meta.object-literal.key.tsx"
2445- },
2446- "1": {
2447- "name": "punctuation.separator.key-value.tsx"
2448- }
2449- },
2450- "end": "(?=,|\\})",
2451- "patterns": [
2452- {
2453- "include": "#expression"
2454- }
2455- ]
2456- },
2457- {
2458- "name": "meta.object.member.tsx",
2459- "begin": "\\.\\.\\.",
2460- "beginCaptures": {
2461- "0": {
2462- "name": "keyword.operator.spread.tsx"
2463- }
2464- },
2465- "end": "(?=,|\\})",
2466- "patterns": [
2467- {
2468- "include": "#expression"
2469- }
2470- ]
2471- },
2472- {
2473- "name": "meta.object.member.tsx",
2474- "match": "([_$[:alpha:]][_$[:alnum:]]*)\\s*(?=,|\\}|$)",
2475- "captures": {
2476- "1": {
2477- "name": "variable.other.readwrite.tsx"
2478- }
2479- }
2480- },
2481- {
2482- "include": "#punctuation-comma"
2483- }
2484- ]
2485- },
2486- "expression-operators": {
2487- "patterns": [
2488- {
2489- "name": "keyword.control.flow.tsx",
2490- "match": "(?<!\\.|\\$)\\b(await)\\b(?!\\$)"
2491- },
2492- {
2493- "name": "keyword.operator.expression.delete.tsx",
2494- "match": "(?<!\\.|\\$)\\bdelete\\b(?!\\$)"
2495- },
2496- {
2497- "name": "keyword.operator.expression.in.tsx",
2498- "match": "(?<!\\.|\\$)\\bin\\b(?!\\$)"
2499- },
2500- {
2501- "name": "keyword.operator.expression.of.tsx",
2502- "match": "(?<!\\.|\\$)\\bof\\b(?!\\$)"
2503- },
2504- {
2505- "name": "keyword.operator.expression.instanceof.tsx",
2506- "match": "(?<!\\.|\\$)\\binstanceof\\b(?!\\$)"
2507- },
2508- {
2509- "name": "keyword.operator.new.tsx",
2510- "match": "(?<!\\.|\\$)\\bnew\\b(?!\\$)"
2511- },
2512- {
2513- "include": "#typeof-operator"
2514- },
2515- {
2516- "name": "keyword.operator.expression.void.tsx",
2517- "match": "(?<!\\.|\\$)\\bvoid\\b(?!\\$)"
2518- },
2519- {
2520- "begin": "(?<!\\.|\\$)\\bas\\b(?!\\$)",
2521- "beginCaptures": {
2522- "0": {
2523- "name": "keyword.control.as.tsx"
2524- }
2525- },
2526- "end": "(?=$|[;,:})\\]])",
2527- "patterns": [
2528- {
2529- "include": "#type"
2530- }
2531- ]
2532- },
2533- {
2534- "name": "keyword.operator.spread.tsx",
2535- "match": "\\.\\.\\."
2536- },
2537- {
2538- "name": "keyword.operator.assignment.compound.tsx",
2539- "match": "\\*=|(?<!\\()/=|%=|\\+=|\\-="
2540- },
2541- {
2542- "name": "keyword.operator.assignment.compound.bitwise.tsx",
2543- "match": "\\&=|\\^=|<<=|>>=|>>>=|\\|="
2544- },
2545- {
2546- "name": "keyword.operator.bitwise.shift.tsx",
2547- "match": "<<|>>>|>>"
2548- },
2549- {
2550- "name": "keyword.operator.comparison.tsx",
2551- "match": "===|!==|==|!="
2552- },
2553- {
2554- "name": "keyword.operator.relational.tsx",
2555- "match": "<=|>=|<>|<|>"
2556- },
2557- {
2558- "name": "keyword.operator.logical.tsx",
2559- "match": "\\!|&&|\\|\\|"
2560- },
2561- {
2562- "name": "keyword.operator.bitwise.tsx",
2563- "match": "\\&|~|\\^|\\|"
2564- },
2565- {
2566- "name": "keyword.operator.assignment.tsx",
2567- "match": "\\="
2568- },
2569- {
2570- "name": "keyword.operator.decrement.tsx",
2571- "match": "--"
2572- },
2573- {
2574- "name": "keyword.operator.increment.tsx",
2575- "match": "\\+\\+"
2576- },
2577- {
2578- "name": "keyword.operator.arithmetic.tsx",
2579- "match": "%|\\*|/|-|\\+"
2580- },
2581- {
2582- "match": "(?<=[_$[:alnum:]])\\s*(/)(?![/*])",
2583- "captures": {
2584- "1": {
2585- "name": "keyword.operator.arithmetic.tsx"
2586- }
2587- }
2588- }
2589- ]
2590- },
2591- "typeof-operator": {
2592- "name": "keyword.operator.expression.typeof.tsx",
2593- "match": "(?<!\\.|\\$)\\btypeof\\b(?!\\$)"
2594- },
2595- "arrow-function": {
2596- "patterns": [
2597- {
2598- "name": "meta.arrow.tsx",
2599- "match": "(?<!\\.|\\$)(\\basync)(?=\\s*[<(])",
2600- "captures": {
2601- "1": {
2602- "name": "storage.modifier.async.tsx"
2603- }
2604- }
2605- },
2606- {
2607- "name": "meta.arrow.tsx",
2608- "match": "(?:(?<!\\.|\\$)(\\basync)\\s*)?([_$[:alpha:]][_$[:alnum:]]*)\\s*(?==>)",
2609- "captures": {
2610- "1": {
2611- "name": "storage.modifier.async.tsx"
2612- },
2613- "2": {
2614- "name": "variable.parameter.tsx"
2615- }
2616- }
2617- },
2618- {
2619- "name": "meta.arrow.tsx",
2620- "begin": "(?x)\\s*(?=(<([^<>]|\\<[^<>]+\\>)+>\\s*)?\\(([^()]|\\([^()]*\\))*\\)(\\s*:\\s*(.)*)?\\s*=>)",
2621- "end": "(?==>)",
2622- "patterns": [
2623- {
2624- "include": "#comment"
2625- },
2626- {
2627- "include": "#type-parameters"
2628- },
2629- {
2630- "include": "#function-parameters"
2631- },
2632- {
2633- "include": "#arrow-return-type"
2634- }
2635- ]
2636- },
2637- {
2638- "name": "meta.arrow.tsx",
2639- "begin": "=>",
2640- "beginCaptures": {
2641- "0": {
2642- "name": "storage.type.function.arrow.tsx"
2643- }
2644- },
2645- "end": "(?<=\\})|((?!\\{)(?=\\S))",
2646- "patterns": [
2647- {
2648- "include": "#decl-block"
2649- },
2650- {
2651- "include": "#expression"
2652- }
2653- ]
2654- }
2655- ]
2656- },
2657- "arrow-return-type": {
2658- "name": "meta.return.type.arrow.tsx",
2659- "begin": "(?<=\\))\\s*(:)",
2660- "beginCaptures": {
2661- "1": {
2662- "name": "keyword.operator.type.annotation.tsx"
2663- }
2664- },
2665- "end": "(?<!:)((?=$)|(?==>|;|//))",
2666- "patterns": [
2667- {
2668- "include": "#type-predicate-operator"
2669- },
2670- {
2671- "include": "#type"
2672- }
2673- ]
2674- },
2675- "punctuation-comma": {
2676- "name": "punctuation.separator.comma.tsx",
2677- "match": ","
2678- },
2679- "punctuation-semicolon": {
2680- "name": "punctuation.terminator.statement.tsx",
2681- "match": ";"
2682- },
2683- "punctuation-accessor": {
2684- "name": "punctuation.accessor.tsx",
2685- "match": "\\."
2686- },
2687- "paren-expression": {
2688- "begin": "\\(",
2689- "beginCaptures": {
2690- "0": {
2691- "name": "meta.brace.round.tsx"
2692- }
2693- },
2694- "end": "\\)",
2695- "endCaptures": {
2696- "0": {
2697- "name": "meta.brace.round.tsx"
2698- }
2699- },
2700- "patterns": [
2701- {
2702- "include": "#expression"
2703- },
2704- {
2705- "include": "#punctuation-comma"
2706- }
2707- ]
2708- },
2709- "qstring-double": {
2710- "name": "string.quoted.double.tsx",
2711- "begin": "\"",
2712- "beginCaptures": {
2713- "0": {
2714- "name": "punctuation.definition.string.begin.tsx"
2715- }
2716- },
2717- "end": "(\")|((?:[^\\\\\\n])$)",
2718- "endCaptures": {
2719- "1": {
2720- "name": "punctuation.definition.string.end.tsx"
2721- },
2722- "2": {
2723- "name": "invalid.illegal.newline.tsx"
2724- }
2725- },
2726- "patterns": [
2727- {
2728- "include": "#string-character-escape"
2729- }
2730- ]
2731- },
2732- "qstring-single": {
2733- "name": "string.quoted.single.tsx",
2734- "begin": "'",
2735- "beginCaptures": {
2736- "0": {
2737- "name": "punctuation.definition.string.begin.tsx"
2738- }
2739- },
2740- "end": "(\\')|((?:[^\\\\\\n])$)",
2741- "endCaptures": {
2742- "1": {
2743- "name": "punctuation.definition.string.end.tsx"
2744- },
2745- "2": {
2746- "name": "invalid.illegal.newline.tsx"
2747- }
2748- },
2749- "patterns": [
2750- {
2751- "include": "#string-character-escape"
2752- }
2753- ]
2754- },
2755- "regex": {
2756- "patterns": [
2757- {
2758- "name": "string.regex.tsx",
2759- "begin": "(?<=[=(:,\\[?+!]|return|case|=>|&&|\\|\\||\\*\\/)\\s*(/)(?![/*])(?=(?:[^/\\\\\\[]|\\\\.|\\[([^\\]\\\\]|\\\\.)+\\])+/(?![/*])[gimy]*(?!\\s*[a-zA-Z0-9_$]))",
2760- "beginCaptures": {
2761- "1": {
2762- "name": "punctuation.definition.string.begin.tsx"
2763- }
2764- },
2765- "end": "(/)([gimuy]*)",
2766- "endCaptures": {
2767- "1": {
2768- "name": "punctuation.definition.string.end.tsx"
2769- },
2770- "2": {
2771- "name": "keyword.other.tsx"
2772- }
2773- },
2774- "patterns": [
2775- {
2776- "include": "#regexp"
2777- }
2778- ]
2779- },
2780- {
2781- "name": "string.regex.tsx",
2782- "begin": "/(?![/*])(?=(?:[^/\\\\\\[]|\\\\.|\\[([^\\]\\\\]|\\\\.)+\\])+/(?![/*])[gimy]*(?!\\s*[a-zA-Z0-9_$]))",
2783- "beginCaptures": {
2784- "0": {
2785- "name": "punctuation.definition.string.begin.tsx"
2786- }
2787- },
2788- "end": "(/)([gimuy]*)",
2789- "endCaptures": {
2790- "1": {
2791- "name": "punctuation.definition.string.end.tsx"
2792- },
2793- "2": {
2794- "name": "keyword.other.tsx"
2795- }
2796- },
2797- "patterns": [
2798- {
2799- "include": "#regexp"
2800- }
2801- ]
2802- }
2803- ]
2804- },
2805- "regexp": {
2806- "patterns": [
2807- {
2808- "name": "keyword.control.anchor.regexp",
2809- "match": "\\\\[bB]|\\^|\\$"
2810- },
2811- {
2812- "name": "keyword.other.back-reference.regexp",
2813- "match": "\\\\[1-9]\\d*"
2814- },
2815- {
2816- "name": "keyword.operator.quantifier.regexp",
2817- "match": "[?+*]|\\{(\\d+,\\d+|\\d+,|,\\d+|\\d+)\\}\\??"
2818- },
2819- {
2820- "name": "keyword.operator.or.regexp",
2821- "match": "\\|"
2822- },
2823- {
2824- "name": "meta.group.assertion.regexp",
2825- "begin": "(\\()((\\?=)|(\\?!))",
2826- "beginCaptures": {
2827- "1": {
2828- "name": "punctuation.definition.group.regexp"
2829- },
2830- "2": {
2831- "name": "punctuation.definition.group.assertion.regexp"
2832- },
2833- "3": {
2834- "name": "meta.assertion.look-ahead.regexp"
2835- },
2836- "4": {
2837- "name": "meta.assertion.negative-look-ahead.regexp"
2838- }
2839- },
2840- "end": "(\\))",
2841- "endCaptures": {
2842- "1": {
2843- "name": "punctuation.definition.group.regexp"
2844- }
2845- },
2846- "patterns": [
2847- {
2848- "include": "#regexp"
2849- }
2850- ]
2851- },
2852- {
2853- "name": "meta.group.regexp",
2854- "begin": "\\((\\?:)?",
2855- "beginCaptures": {
2856- "0": {
2857- "name": "punctuation.definition.group.regexp"
2858- },
2859- "1": {
2860- "name": "punctuation.definition.group.capture.regexp"
2861- }
2862- },
2863- "end": "\\)",
2864- "endCaptures": {
2865- "0": {
2866- "name": "punctuation.definition.group.regexp"
2867- }
2868- },
2869- "patterns": [
2870- {
2871- "include": "#regexp"
2872- }
2873- ]
2874- },
2875- {
2876- "name": "constant.other.character-class.set.regexp",
2877- "begin": "(\\[)(\\^)?",
2878- "beginCaptures": {
2879- "1": {
2880- "name": "punctuation.definition.character-class.regexp"
2881- },
2882- "2": {
2883- "name": "keyword.operator.negation.regexp"
2884- }
2885- },
2886- "end": "(\\])",
2887- "endCaptures": {
2888- "1": {
2889- "name": "punctuation.definition.character-class.regexp"
2890- }
2891- },
2892- "patterns": [
2893- {
2894- "name": "constant.other.character-class.range.regexp",
2895- "match": "(?:.|(\\\\(?:[0-7]{3}|x\\h\\h|u\\h\\h\\h\\h))|(\\\\c[A-Z])|(\\\\.))\\-(?:[^\\]\\\\]|(\\\\(?:[0-7]{3}|x\\h\\h|u\\h\\h\\h\\h))|(\\\\c[A-Z])|(\\\\.))",
2896- "captures": {
2897- "1": {
2898- "name": "constant.character.numeric.regexp"
2899- },
2900- "2": {
2901- "name": "constant.character.control.regexp"
2902- },
2903- "3": {
2904- "name": "constant.character.escape.backslash.regexp"
2905- },
2906- "4": {
2907- "name": "constant.character.numeric.regexp"
2908- },
2909- "5": {
2910- "name": "constant.character.control.regexp"
2911- },
2912- "6": {
2913- "name": "constant.character.escape.backslash.regexp"
2914- }
2915- }
2916- },
2917- {
2918- "include": "#regex-character-class"
2919- }
2920- ]
2921- },
2922- {
2923- "include": "#regex-character-class"
2924- }
2925- ]
2926- },
2927- "regex-character-class": {
2928- "patterns": [
2929- {
2930- "name": "constant.other.character-class.regexp",
2931- "match": "\\\\[wWsSdDtrnvf]|\\."
2932- },
2933- {
2934- "name": "constant.character.numeric.regexp",
2935- "match": "\\\\([0-7]{3}|x\\h\\h|u\\h\\h\\h\\h)"
2936- },
2937- {
2938- "name": "constant.character.control.regexp",
2939- "match": "\\\\c[A-Z]"
2940- },
2941- {
2942- "name": "constant.character.escape.backslash.regexp",
2943- "match": "\\\\."
2944- }
2945- ]
2946- },
2947- "string": {
2948- "patterns": [
2949- {
2950- "include": "#qstring-single"
2951- },
2952- {
2953- "include": "#qstring-double"
2954- }
2955- ]
2956- },
2957- "template": {
2958- "name": "string.template.tsx",
2959- "begin": "([_$[:alpha:]][_$[:alnum:]]*)?(`)",
2960- "beginCaptures": {
2961- "1": {
2962- "name": "entity.name.function.tagged-template.tsx"
2963- },
2964- "2": {
2965- "name": "punctuation.definition.string.template.begin.tsx"
2966- }
2967- },
2968- "end": "`",
2969- "endCaptures": {
2970- "0": {
2971- "name": "punctuation.definition.string.template.end.tsx"
2972- }
2973- },
2974- "patterns": [
2975- {
2976- "include": "#template-substitution-element"
2977- },
2978- {
2979- "include": "#string-character-escape"
2980- }
2981- ]
2982- },
2983- "string-character-escape": {
2984- "name": "constant.character.escape.tsx",
2985- "match": "\\\\(x\\h{2}|[0-2][0-7]{0,2}|3[0-6][0-7]?|37[0-7]?|[4-7][0-7]?|.|$)"
2986- },
2987- "template-substitution-element": {
2988- "name": "meta.template.expression.tsx",
2989- "begin": "\\$\\{",
2990- "beginCaptures": {
2991- "0": {
2992- "name": "punctuation.definition.template-expression.begin.tsx"
2993- }
2994- },
2995- "end": "\\}",
2996- "endCaptures": {
2997- "0": {
2998- "name": "punctuation.definition.template-expression.end.tsx"
2999- }
3000- },
3001- "patterns": [
3002- {
3003- "include": "#expression"
3004- }
3005- ]
3006- },
3007- "literal": {
3008- "name": "literal.tsx",
3009- "patterns": [
3010- {
3011- "include": "#numeric-literal"
3012- },
3013- {
3014- "include": "#boolean-literal"
3015- },
3016- {
3017- "include": "#null-literal"
3018- },
3019- {
3020- "include": "#undefined-literal"
3021- },
3022- {
3023- "include": "#numericConstant-literal"
3024- },
3025- {
3026- "include": "#array-literal"
3027- },
3028- {
3029- "include": "#this-literal"
3030- },
3031- {
3032- "include": "#super-literal"
3033- }
3034- ]
3035- },
3036- "array-literal": {
3037- "name": "meta.array.literal.tsx",
3038- "begin": "\\[",
3039- "beginCaptures": {
3040- "0": {
3041- "name": "meta.brace.square.tsx"
3042- }
3043- },
3044- "end": "\\]",
3045- "endCaptures": {
3046- "0": {
3047- "name": "meta.brace.square.tsx"
3048- }
3049- },
3050- "patterns": [
3051- {
3052- "include": "#expression"
3053- },
3054- {
3055- "include": "#punctuation-comma"
3056- }
3057- ]
3058- },
3059- "numeric-literal": {
3060- "patterns": [
3061- {
3062- "name": "constant.numeric.hex.tsx",
3063- "match": "\\b(?<!\\$)0(x|X)[0-9a-fA-F]+\\b(?!\\$)"
3064- },
3065- {
3066- "name": "constant.numeric.binary.tsx",
3067- "match": "\\b(?<!\\$)0(b|B)[01]+\\b(?!\\$)"
3068- },
3069- {
3070- "name": "constant.numeric.octal.tsx",
3071- "match": "\\b(?<!\\$)0(o|O)?[0-7]+\\b(?!\\$)"
3072- },
3073- {
3074- "match": "(?x)\n(?<!\\$)(?:\n (?:\\b[0-9]+(\\.)[0-9]+[eE][+-]?[0-9]+\\b)| # 1.1E+3\n (?:\\b[0-9]+(\\.)[eE][+-]?[0-9]+\\b)| # 1.E+3\n (?:\\B(\\.)[0-9]+[eE][+-]?[0-9]+\\b)| # .1E+3\n (?:\\b[0-9]+[eE][+-]?[0-9]+\\b)| # 1E+3\n (?:\\b[0-9]+(\\.)[0-9]+\\b)| # 1.1\n (?:\\b[0-9]+(\\.)\\B)| # 1.\n (?:\\B(\\.)[0-9]+\\b)| # .1\n (?:\\b[0-9]+\\b(?!\\.)) # 1\n)(?!\\$)",
3075- "captures": {
3076- "0": {
3077- "name": "constant.numeric.decimal.tsx"
3078- },
3079- "1": {
3080- "name": "meta.delimiter.decimal.period.tsx"
3081- },
3082- "2": {
3083- "name": "meta.delimiter.decimal.period.tsx"
3084- },
3085- "3": {
3086- "name": "meta.delimiter.decimal.period.tsx"
3087- },
3088- "4": {
3089- "name": "meta.delimiter.decimal.period.tsx"
3090- },
3091- "5": {
3092- "name": "meta.delimiter.decimal.period.tsx"
3093- },
3094- "6": {
3095- "name": "meta.delimiter.decimal.period.tsx"
3096- }
3097- }
3098- }
3099- ]
3100- },
3101- "boolean-literal": {
3102- "patterns": [
3103- {
3104- "name": "constant.language.boolean.true.tsx",
3105- "match": "(?<!\\.|\\$)\\btrue\\b(?!\\$)"
3106- },
3107- {
3108- "name": "constant.language.boolean.false.tsx",
3109- "match": "(?<!\\.|\\$)\\bfalse\\b(?!\\$)"
3110- }
3111- ]
3112- },
3113- "null-literal": {
3114- "name": "constant.language.null.tsx",
3115- "match": "(?<!\\.|\\$)\\bnull\\b(?!\\$)"
3116- },
3117- "this-literal": {
3118- "name": "variable.language.this.tsx",
3119- "match": "(?<!\\.|\\$)\\bthis\\b(?!\\$)"
3120- },
3121- "super-literal": {
3122- "name": "variable.language.super.tsx",
3123- "match": "(?<!\\.|\\$)\\bsuper\\b(?!\\$)"
3124- },
3125- "undefined-literal": {
3126- "name": "constant.language.undefined.tsx",
3127- "match": "(?<!\\.|\\$)\\bundefined\\b(?!\\$)"
3128- },
3129- "numericConstant-literal": {
3130- "patterns": [
3131- {
3132- "name": "constant.language.nan.tsx",
3133- "match": "(?<!\\.|\\$)\\bNaN\\b(?!\\$)"
3134- },
3135- {
3136- "name": "constant.language.infinity.tsx",
3137- "match": "(?<!\\.|\\$)\\bInfinity\\b(?!\\$)"
3138- }
3139- ]
3140- },
3141- "access-modifier": {
3142- "name": "storage.modifier.tsx",
3143- "match": "(?<!\\.|\\$)\\b(abstract|public|protected|private|readonly|static)\\b(?!\\$)"
3144- },
3145- "property-accessor": {
3146- "name": "storage.type.property.tsx",
3147- "match": "(?<!\\.|\\$)\\b(get|set)\\b(?!\\$)"
3148- },
3149- "comment": {
3150- "patterns": [
3151- {
3152- "name": "comment.block.documentation.tsx",
3153- "begin": "/\\*\\*(?!/)",
3154- "beginCaptures": {
3155- "0": {
3156- "name": "punctuation.definition.comment.tsx"
3157- }
3158- },
3159- "end": "\\*/",
3160- "endCaptures": {
3161- "0": {
3162- "name": "punctuation.definition.comment.tsx"
3163- }
3164- },
3165- "patterns": [
3166- {
3167- "include": "#docblock"
3168- }
3169- ]
3170- },
3171- {
3172- "name": "comment.block.tsx",
3173- "begin": "/\\*",
3174- "beginCaptures": {
3175- "0": {
3176- "name": "punctuation.definition.comment.tsx"
3177- }
3178- },
3179- "end": "\\*/",
3180- "endCaptures": {
3181- "0": {
3182- "name": "punctuation.definition.comment.tsx"
3183- }
3184- }
3185- },
3186- {
3187- "begin": "(^[ \\t]+)?(?=//)",
3188- "beginCaptures": {
3189- "1": {
3190- "name": "punctuation.whitespace.comment.leading.tsx"
3191- }
3192- },
3193- "end": "(?=$)",
3194- "patterns": [
3195- {
3196- "name": "comment.line.double-slash.tsx",
3197- "begin": "//",
3198- "beginCaptures": {
3199- "0": {
3200- "name": "punctuation.definition.comment.tsx"
3201- }
3202- },
3203- "end": "(?=$)"
3204- }
3205- ]
3206- }
3207- ]
3208- },
3209- "directives": {
3210- "name": "comment.line.triple-slash.directive.tsx",
3211- "begin": "^(///)\\s*(?=<(reference|amd-dependency|amd-module)(\\s+(path|types|no-default-lib|name)\\s*=\\s*((\\'[^']*\\')|(\\\"[^\"]*\\\")))+\\s*/>\\s*$)",
3212- "beginCaptures": {
3213- "1": {
3214- "name": "punctuation.definition.comment.tsx"
3215- }
3216- },
3217- "end": "(?=$)",
3218- "patterns": [
3219- {
3220- "name": "meta.tag.tsx",
3221- "begin": "(<)(reference|amd-dependency|amd-module)",
3222- "beginCaptures": {
3223- "1": {
3224- "name": "punctuation.definition.tag.directive.tsx"
3225- },
3226- "2": {
3227- "name": "entity.name.tag.directive.tsx"
3228- }
3229- },
3230- "end": "/>",
3231- "endCaptures": {
3232- "0": {
3233- "name": "punctuation.definition.tag.directive.tsx"
3234- }
3235- },
3236- "patterns": [
3237- {
3238- "name": "entity.other.attribute-name.directive.tsx",
3239- "match": "path|types|no-default-lib|name"
3240- },
3241- {
3242- "name": "keyword.operator.assignment.tsx",
3243- "match": "="
3244- },
3245- {
3246- "include": "#string"
3247- }
3248- ]
3249- }
3250- ]
3251- },
3252- "docblock": {
3253- "patterns": [
3254- {
3255- "name": "storage.type.class.jsdoc",
3256- "match": "(?<!\\w)@(abstract|access|alias|arg|argument|async|attribute|augments|author|beta|borrows|bubbes|callback|chainable|class|classdesc|code|config|const|constant|constructor|constructs|copyright|default|defaultvalue|define|deprecated|desc|description|dict|emits|enum|event|example|exports?|extends|extension|extension_for|extensionfor|external|file|fileoverview|final|fires|for|function|global|host|ignore|implements|inherit[Dd]oc|inner|instance|interface|kind|lends|license|listens|main|member|memberof|method|mixex|mixins?|module|name|namespace|nocollapse|nosideeffects|override|overview|package|param|preserve|private|prop|property|protected|public|read[Oo]nly|record|require[ds]|returns?|see|since|static|struct|submodule|summary|template|this|throws|todo|tutorial|type|typedef|unrestricted|uses|var|variation|version|virtual|writeOnce)\\b"
3257- },
3258- {
3259- "match": "(?x)\n(?:(?<=@param)|(?<=@arg)|(?<=@argument)|(?<=@type))\n\\s+\n({(?:\n \\* | # {*} any type\n \\? | # {?} unknown type\n (?: # Check for a prefix\n \\? | # {?string} nullable type\n ! | # {!string} non-nullable type\n \\.{3} # {...string} variable number of parameters\n )?\n (?:\n \\( # Opening bracket of multiple types with parenthesis {(string|number)}\n [a-zA-Z_$]+\n (?:\n (?:\n [\\w$]*\n (?:\\[\\])? # {(string[]|number)} type application, an array of strings or a number\n ) |\n \\.?<[\\w$]+(?:,\\s+[\\w$]+)*> # {Array<string>} or {Object<string, number>} type application (optional .)\n )\n (?:\n [\\.|~] # {Foo.bar} namespaced, {string|number} multiple, {Foo~bar} class-specific callback\n [a-zA-Z_$]+\n (?:\n (?:\n [\\w$]*\n (?:\\[\\])? # {(string|number[])} type application, a string or an array of numbers\n ) |\n \\.?<[\\w$]+(?:,\\s+[\\w$]+)*> # {Array<string>} or {Object<string, number>} type application (optional .)\n )\n )*\n \\) |\n [a-zA-Z_$]+\n (?:\n (?:\n [\\w$]*\n (?:\\[\\])? # {string[]|number} type application, an array of strings or a number\n ) |\n \\.?<[\\w$]+(?:,\\s+[\\w$]+)*> # {Array<string>} or {Object<string, number>} type application (optional .)\n )\n (?:\n [\\.|~] # {Foo.bar} namespaced, {string|number} multiple, {Foo~bar} class-specific callback\n [a-zA-Z_$]+\n (?:\n [\\w$]* |\n \\.?<[\\w$]+(?:,\\s+[\\w$]+)*> # {Array<string>} or {Object<string, number>} type application (optional .)\n )\n )*\n )\n # Check for suffix\n (?:\\[\\])? # {string[]} type application, an array of strings\n =? # {string=} optional parameter\n)})\n\\s+\n(\n \\[ # [foo] optional parameter\n \\s*\n (?:\n [a-zA-Z_$][\\w$]*\n (?:\n (?:\\[\\])? # Foo[].bar properties within an array\n \\. # Foo.Bar namespaced parameter\n [a-zA-Z_$][\\w$]*\n )*\n (?:\n \\s*\n = # [foo=bar] Default parameter value\n \\s*\n [\\w$\\s]*\n )?\n )\n \\s*\n \\] |\n (?:\n [a-zA-Z_$][\\w$]*\n (?:\n (?:\\[\\])? # Foo[].bar properties within an array\n \\. # Foo.Bar namespaced parameter\n [a-zA-Z_$][\\w$]*\n )*\n )?\n)\n\\s+\n(?:-\\s+)? # optional hyphen before the description\n((?:(?!\\*\\/).)*) # The type description",
3260- "captures": {
3261- "0": {
3262- "name": "other.meta.jsdoc"
3263- },
3264- "1": {
3265- "name": "entity.name.type.instance.jsdoc"
3266- },
3267- "2": {
3268- "name": "variable.other.jsdoc"
3269- },
3270- "3": {
3271- "name": "other.description.jsdoc"
3272- }
3273- }
3274- },
3275- {
3276- "match": "(?x)\n({(?:\n \\* | # {*} any type\n \\? | # {?} unknown type\n\n (?: # Check for a prefix\n \\? | # {?string} nullable type\n ! | # {!string} non-nullable type\n \\.{3} # {...string} variable number of parameters\n )?\n\n (?:\n \\( # Opening bracket of multiple types with parenthesis {(string|number)}\n [a-zA-Z_$]+\n (?:\n [\\w$]* |\n \\.?<[\\w$]+(?:,\\s+[\\w$]+)*> # {Array<string>} or {Object<string, number>} type application (optional .)\n )\n (?:\n [\\.|~] # {Foo.bar} namespaced, {string|number} multiple, {Foo~bar} class-specific callback\n [a-zA-Z_$]+\n (?:\n [\\w$]* |\n \\.?<[\\w$]+(?:,\\s+[\\w$]+)*> # {Array<string>} or {Object<string, number>} type application (optional .)\n )\n )*\n \\) |\n [a-zA-Z_$]+\n (?:\n [\\w$]* |\n \\.?<[\\w$]+(?:,\\s+[\\w$]+)*> # {Array<string>} or {Object<string, number>} type application (optional .)\n )\n (?:\n [\\.|~] # {Foo.bar} namespaced, {string|number} multiple, {Foo~bar} class-specific callback\n [a-zA-Z_$]+\n (?:\n [\\w$]* |\n \\.?<[\\w$]+(?:,\\s+[\\w$]+)*> # {Array<string>} or {Object<string, number>} type application (optional .)\n )\n )*\n )\n # Check for suffix\n (?:\\[\\])? # {string[]} type application, an array of strings\n =? # {string=} optional parameter\n)})\n\\s+\n(?:-\\s+)? # optional hyphen before the description\n((?:(?!\\*\\/).)*) # The type description",
3277- "captures": {
3278- "0": {
3279- "name": "other.meta.jsdoc"
3280- },
3281- "1": {
3282- "name": "entity.name.type.instance.jsdoc"
3283- },
3284- "2": {
3285- "name": "other.description.jsdoc"
3286- }
3287- }
3288- }
3289- ]
3290- },
3291- "jsx-tag-attributes": {
3292- "patterns": [
3293- {
3294- "include": "#jsx-tag-attribute-name"
3295- },
3296- {
3297- "include": "#jsx-tag-attribute-assignment"
3298- },
3299- {
3300- "include": "#jsx-string-double-quoted"
3301- },
3302- {
3303- "include": "#jsx-string-single-quoted"
3304- },
3305- {
3306- "include": "#jsx-evaluated-code"
3307- }
3308- ]
3309- },
3310- "jsx-tag-attribute-name": {
3311- "match": "(?x)\n \\s*\n ([_$a-zA-Z][-$\\w]*)\n (?=\\s|=|/?>|/\\*|//)",
3312- "captures": {
3313- "1": {
3314- "name": "entity.other.attribute-name.tsx"
3315- }
3316- }
3317- },
3318- "jsx-tag-attribute-assignment": {
3319- "name": "keyword.operator.assignment.tsx",
3320- "match": "=(?=\\s*(?:'|\"|{|/\\*|//|\\n))"
3321- },
3322- "jsx-string-double-quoted": {
3323- "name": "string.quoted.double.tsx",
3324- "begin": "\"",
3325- "end": "\"",
3326- "beginCaptures": {
3327- "0": {
3328- "name": "punctuation.definition.string.begin.tsx"
3329- }
3330- },
3331- "endCaptures": {
3332- "0": {
3333- "name": "punctuation.definition.string.end.tsx"
3334- }
3335- },
3336- "patterns": [
3337- {
3338- "include": "#jsx-entities"
3339- }
3340- ]
3341- },
3342- "jsx-string-single-quoted": {
3343- "name": "string.quoted.single.tsx",
3344- "begin": "'",
3345- "end": "'",
3346- "beginCaptures": {
3347- "0": {
3348- "name": "punctuation.definition.string.begin.tsx"
3349- }
3350- },
3351- "endCaptures": {
3352- "0": {
3353- "name": "punctuation.definition.string.end.tsx"
3354- }
3355- },
3356- "patterns": [
3357- {
3358- "include": "#jsx-entities"
3359- }
3360- ]
3361- },
3362- "jsx-entities": {
3363- "patterns": [
3364- {
3365- "name": "constant.character.entity.tsx",
3366- "match": "(&)([a-zA-Z0-9]+|#[0-9]+|#x[0-9a-fA-F]+)(;)",
3367- "captures": {
3368- "1": {
3369- "name": "punctuation.definition.entity.tsx"
3370- },
3371- "3": {
3372- "name": "punctuation.definition.entity.tsx"
3373- }
3374- }
3375- },
3376- {
3377- "name": "invalid.illegal.bad-ampersand.tsx",
3378- "match": "&"
3379- }
3380- ]
3381- },
3382- "jsx-evaluated-code": {
3383- "name": "meta.embedded.expression.tsx",
3384- "begin": "{",
3385- "end": "}",
3386- "beginCaptures": {
3387- "0": {
3388- "name": "punctuation.section.embedded.begin.tsx"
3389- }
3390- },
3391- "endCaptures": {
3392- "0": {
3393- "name": "punctuation.section.embedded.end.tsx"
3394- }
3395- },
3396- "patterns": [
3397- {
3398- "include": "#expression"
3399- }
3400- ]
3401- },
3402- "jsx-tag-attributes-illegal": {
3403- "name": "invalid.illegal.attribute.tsx",
3404- "match": "\\S+"
3405- },
3406- "jsx-tag-without-attributes": {
3407- "name": "meta.tag.without-attributes.tsx",
3408- "begin": "(<)\\s*([_$a-zA-Z][-$\\w.]*(?<!\\.|-))\\s*(>)",
3409- "end": "(</)\\s*([_$a-zA-Z][-$\\w.]*(?<!\\.|-))\\s*(>)",
3410- "beginCaptures": {
3411- "1": {
3412- "name": "punctuation.definition.tag.begin.tsx"
3413- },
3414- "2": {
3415- "name": "entity.name.tag.tsx"
3416- },
3417- "3": {
3418- "name": "punctuation.definition.tag.end.tsx"
3419- }
3420- },
3421- "endCaptures": {
3422- "1": {
3423- "name": "punctuation.definition.tag.begin.tsx"
3424- },
3425- "2": {
3426- "name": "entity.name.tag.tsx"
3427- },
3428- "3": {
3429- "name": "punctuation.definition.tag.end.tsx"
3430- }
3431- },
3432- "contentName": "meta.jsx.children.tsx",
3433- "patterns": [
3434- {
3435- "include": "#jsx-children"
3436- }
3437- ]
3438- },
3439- "jsx-tag-in-expression": {
3440- "begin": "(?x)\n (?<=[({\\[,?=>]|&&|\\|\\||\\?|\\Wreturn|^return|\\Wdefault|^)\\s*\n (?!(<)\\s*([_$a-zA-Z][-$\\w.]*(?<!\\.|-))\\s*(>)) #look ahead is not start of tag without attributes\n (?!<\\s*[_$[:alpha:]][_$[:alnum:]]*((\\s+extends\\s+[^=>])|,)) # look ahead is not type parameter of arrow\n (?=(<)\\s*\n ([_$a-zA-Z][-$\\w.]*(?<!\\.|-))\n (?=\\s+(?!\\?)|/?>))",
3441- "end": "(/>)|(?:(</)\\s*([_$a-zA-Z][-$\\w.]*(?<!\\.|-))\\s*(>))",
3442- "endCaptures": {
3443- "0": {
3444- "name": "meta.tag.tsx"
3445- },
3446- "1": {
3447- "name": "punctuation.definition.tag.end.tsx"
3448- },
3449- "2": {
3450- "name": "punctuation.definition.tag.begin.tsx"
3451- },
3452- "3": {
3453- "name": "entity.name.tag.tsx"
3454- },
3455- "4": {
3456- "name": "punctuation.definition.tag.end.tsx"
3457- }
3458- },
3459- "patterns": [
3460- {
3461- "include": "#jsx-tag"
3462- }
3463- ]
3464- },
3465- "jsx-child-tag": {
3466- "begin": "(?x)\n (?=(<)\\s*\n ([_$a-zA-Z][-$\\w.]*(?<!\\.|-))\n (?=\\s+(?!\\?)|/?>))",
3467- "end": "(/>)|(?:(</)\\s*([_$a-zA-Z][-$\\w.]*(?<!\\.|-))\\s*(>))",
3468- "endCaptures": {
3469- "0": {
3470- "name": "meta.tag.tsx"
3471- },
3472- "1": {
3473- "name": "punctuation.definition.tag.end.tsx"
3474- },
3475- "2": {
3476- "name": "punctuation.definition.tag.begin.tsx"
3477- },
3478- "3": {
3479- "name": "entity.name.tag.tsx"
3480- },
3481- "4": {
3482- "name": "punctuation.definition.tag.end.tsx"
3483- }
3484- },
3485- "patterns": [
3486- {
3487- "include": "#jsx-tag"
3488- }
3489- ]
3490- },
3491- "jsx-tag": {
3492- "name": "meta.tag.tsx",
3493- "begin": "(?x)\n (?=(<)\\s*\n ([_$a-zA-Z][-$\\w.]*(?<!\\.|-))\n (?=\\s+(?!\\?)|/?>))",
3494- "end": "(?=(/>)|(?:(</)\\s*([_$a-zA-Z][-$\\w.]*(?<!\\.|-))\\s*(>)))",
3495- "patterns": [
3496- {
3497- "begin": "(?x)\n (<)\\s*\n ([_$a-zA-Z][-$\\w.]*(?<!\\.|-))\n (?=\\s+(?!\\?)|/?>)",
3498- "beginCaptures": {
3499- "1": {
3500- "name": "punctuation.definition.tag.begin.tsx"
3501- },
3502- "2": {
3503- "name": "entity.name.tag.tsx"
3504- }
3505- },
3506- "end": "(?=[/]?>)",
3507- "patterns": [
3508- {
3509- "include": "#comment"
3510- },
3511- {
3512- "include": "#jsx-tag-attributes"
3513- },
3514- {
3515- "include": "#jsx-tag-attributes-illegal"
3516- }
3517- ]
3518- },
3519- {
3520- "begin": "(>)",
3521- "beginCaptures": {
3522- "1": {
3523- "name": "punctuation.definition.tag.end.tsx"
3524- }
3525- },
3526- "end": "(?=</)",
3527- "contentName": "meta.jsx.children.tsx",
3528- "patterns": [
3529- {
3530- "include": "#jsx-children"
3531- }
3532- ]
3533- }
3534- ]
3535- },
3536- "jsx-tag-invalid": {
3537- "name": "invalid.illegal.tag.incomplete.tsx",
3538- "match": "<\\s*>"
3539- },
3540- "jsx-children": {
3541- "patterns": [
3542- {
3543- "include": "#jsx-tag-without-attributes"
3544- },
3545- {
3546- "include": "#jsx-child-tag"
3547- },
3548- {
3549- "include": "#jsx-tag-invalid"
3550- },
3551- {
3552- "include": "#jsx-evaluated-code"
3553- },
3554- {
3555- "include": "#jsx-entities"
3556- }
3557- ]
3558- },
3559- "jsx": {
3560- "patterns": [
3561- {
3562- "include": "#jsx-tag-without-attributes"
3563- },
3564- {
3565- "include": "#jsx-tag-in-expression"
3566- },
3567- {
3568- "include": "#jsx-tag-invalid"
3569- }
3570- ]
3571- }
3572- },
3573- "version": "https://github.com/Microsoft/TypeScript-TmLanguage/commit/4d0bdebb93aadc25ecbb903ebc897e9cd5fab69c"
3574-}
No newline at the end of the file
2+ "name": "TypeScriptReact",
3+ "scopeName": "source.tsx",
4+ "fileTypes": ["tsx"],
5+ "uuid": "805375ec-d614-41f5-8993-5843fe63ea82",
6+ "patterns": [
7+ {
8+ "include": "#directives"
9+ },
10+ {
11+ "include": "#statements"
12+ },
13+ {
14+ "name": "comment.line.shebang.ts",
15+ "match": "\\A(#!).*(?=$)",
16+ "captures": {
17+ "1": {
18+ "name": "punctuation.definition.comment.ts"
19+ }
20+ }
21+ }
22+ ],
23+ "repository": {
24+ "statements": {
25+ "patterns": [
26+ {
27+ "include": "#string"
28+ },
29+ {
30+ "include": "#template"
31+ },
32+ {
33+ "include": "#comment"
34+ },
35+ {
36+ "include": "#literal"
37+ },
38+ {
39+ "include": "#declaration"
40+ },
41+ {
42+ "include": "#switch-statement"
43+ },
44+ {
45+ "include": "#for-loop"
46+ },
47+ {
48+ "include": "#after-operator-block"
49+ },
50+ {
51+ "include": "#decl-block"
52+ },
53+ {
54+ "include": "#control-statement"
55+ },
56+ {
57+ "include": "#expression"
58+ },
59+ {
60+ "include": "#punctuation-semicolon"
61+ }
62+ ]
63+ },
64+ "var-expr": {
65+ "name": "meta.var.expr.tsx",
66+ "begin": "(?<!\\.|\\$)(?:(\\bexport)\\s+)?\\b(var|let|const(?!\\s+enum\\b))\\b(?!\\$)",
67+ "beginCaptures": {
68+ "1": {
69+ "name": "keyword.control.export.tsx"
70+ },
71+ "2": {
72+ "name": "storage.type.tsx"
73+ }
74+ },
75+ "end": "(?=$|;|}|(\\s+(of|in)\\s+))",
76+ "patterns": [
77+ {
78+ "include": "#destructuring-variable"
79+ },
80+ {
81+ "include": "#var-single-variable"
82+ },
83+ {
84+ "include": "#variable-initializer"
85+ },
86+ {
87+ "include": "#comment"
88+ },
89+ {
90+ "include": "#punctuation-comma"
91+ }
92+ ]
93+ },
94+ "var-single-variable": {
95+ "patterns": [
96+ {
97+ "name": "meta.var-single-variable.expr.tsx",
98+ "begin": "(?x)([_$[:alpha:]][_$[:alnum:]]*)(?=\\s* (=\\s*( (async\\s+) | (function\\s*[(<]) | (function\\s+) | ([_$[:alpha:]][_$[:alnum:]]*\\s*=>) | ((<([^<>]|\\<[^<>]+\\>)+>\\s*)?\\(([^()]|\\([^()]*\\))*\\)(\\s*:\\s*(.)*)?\\s*=>)) ) | (:\\s*( (<) | ([(]\\s*( ([)]) | (\\.\\.\\.) | ([_$[:alnum:]]+\\s*( ([:,?=])| ([)]\\s*=>) )) ))) ))",
99+ "beginCaptures": {
100+ "1": {
101+ "name": "entity.name.function.tsx"
102+ }
103+ },
104+ "end": "(?=$|[;,=}]|(\\s+(of|in)\\s+))",
105+ "patterns": [
106+ {
107+ "include": "#type-annotation"
108+ },
109+ {
110+ "include": "#string"
111+ },
112+ {
113+ "include": "#comment"
114+ }
115+ ]
116+ },
117+ {
118+ "name": "meta.var-single-variable.expr.tsx",
119+ "begin": "([_$[:alpha:]][_$[:alnum:]]*)",
120+ "beginCaptures": {
121+ "1": {
122+ "name": "variable.other.readwrite.tsx"
123+ }
124+ },
125+ "end": "(?=$|[;,=}]|(\\s+(of|in)\\s+))",
126+ "patterns": [
127+ {
128+ "include": "#type-annotation"
129+ },
130+ {
131+ "include": "#string"
132+ },
133+ {
134+ "include": "#comment"
135+ }
136+ ]
137+ }
138+ ]
139+ },
140+ "destructuring-variable": {
141+ "patterns": [
142+ {
143+ "name": "meta.object-binding-pattern-variable.tsx",
144+ "begin": "(?<!=|:|of|in)\\s*(?=\\{)",
145+ "end": "(?=$|[;,=}]|(\\s+(of|in)\\s+))",
146+ "patterns": [
147+ {
148+ "include": "#object-binding-pattern"
149+ },
150+ {
151+ "include": "#type-annotation"
152+ },
153+ {
154+ "include": "#comment"
155+ }
156+ ]
157+ },
158+ {
159+ "name": "meta.array-binding-pattern-variable.tsx",
160+ "begin": "(?<!=|:|of|in)\\s*(?=\\[)",
161+ "end": "(?=$|[;,=}]|(\\s+(of|in)\\s+))",
162+ "patterns": [
163+ {
164+ "include": "#array-binding-pattern"
165+ },
166+ {
167+ "include": "#type-annotation"
168+ },
169+ {
170+ "include": "#comment"
171+ }
172+ ]
173+ }
174+ ]
175+ },
176+ "object-binding-element": {
177+ "patterns": [
178+ {
179+ "include": "#comment"
180+ },
181+ {
182+ "begin": "(?=(([_$[:alpha:]][_$[:alnum:]]*)|(\\'[^']*\\')|(\\\"[^\"]*\\\")|(\\[([^\\[\\]]|\\[[^\\[\\]]+\\])+\\]))\\s*(:))",
183+ "end": "(?=,|\\})",
184+ "patterns": [
185+ {
186+ "include": "#object-binding-element-propertyName"
187+ },
188+ {
189+ "include": "#binding-element"
190+ }
191+ ]
192+ },
193+ {
194+ "include": "#object-binding-pattern"
195+ },
196+ {
197+ "include": "#destructuring-variable-rest"
198+ },
199+ {
200+ "include": "#variable-initializer"
201+ },
202+ {
203+ "include": "#punctuation-comma"
204+ }
205+ ]
206+ },
207+ "object-binding-element-propertyName": {
208+ "begin": "(?=(([_$[:alpha:]][_$[:alnum:]]*)|(\\'[^']*\\')|(\\\"[^\"]*\\\")|(\\[([^\\[\\]]|\\[[^\\[\\]]+\\])+\\]))\\s*(:))",
209+ "end": "(:)",
210+ "endCaptures": {
211+ "0": {
212+ "name": "punctuation.destructuring.tsx"
213+ }
214+ },
215+ "patterns": [
216+ {
217+ "include": "#string"
218+ },
219+ {
220+ "include": "#array-literal"
221+ },
222+ {
223+ "name": "variable.object.property.tsx",
224+ "match": "([_$[:alpha:]][_$[:alnum:]]*)"
225+ }
226+ ]
227+ },
228+ "binding-element": {
229+ "patterns": [
230+ {
231+ "include": "#comment"
232+ },
233+ {
234+ "include": "#object-binding-pattern"
235+ },
236+ {
237+ "include": "#array-binding-pattern"
238+ },
239+ {
240+ "include": "#destructuring-variable-rest"
241+ },
242+ {
243+ "include": "#variable-initializer"
244+ }
245+ ]
246+ },
247+ "destructuring-variable-rest": {
248+ "match": "(?:(\\.\\.\\.)\\s*)?([_$[:alpha:]][_$[:alnum:]]*)",
249+ "captures": {
250+ "1": {
251+ "name": "keyword.operator.rest.tsx"
252+ },
253+ "2": {
254+ "name": "variable.other.readwrite.tsx"
255+ }
256+ }
257+ },
258+ "object-binding-pattern": {
259+ "begin": "(?:(\\.\\.\\.)\\s*)?(\\{)",
260+ "beginCaptures": {
261+ "1": {
262+ "name": "keyword.operator.rest.tsx"
263+ },
264+ "2": {
265+ "name": "punctuation.definition.binding-pattern.object.tsx"
266+ }
267+ },
268+ "end": "\\}",
269+ "endCaptures": {
270+ "0": {
271+ "name": "punctuation.definition.binding-pattern.object.tsx"
272+ }
273+ },
274+ "patterns": [
275+ {
276+ "include": "#object-binding-element"
277+ }
278+ ]
279+ },
280+ "array-binding-pattern": {
281+ "begin": "(?:(\\.\\.\\.)\\s*)?(\\[)",
282+ "beginCaptures": {
283+ "1": {
284+ "name": "keyword.operator.rest.tsx"
285+ },
286+ "2": {
287+ "name": "punctuation.definition.binding-pattern.array.tsx"
288+ }
289+ },
290+ "end": "\\]",
291+ "endCaptures": {
292+ "0": {
293+ "name": "punctuation.definition.binding-pattern.array.tsx"
294+ }
295+ },
296+ "patterns": [
297+ {
298+ "include": "#binding-element"
299+ },
300+ {
301+ "include": "#punctuation-comma"
302+ }
303+ ]
304+ },
305+ "ternary-expression": {
306+ "begin": "(?=\\?)",
307+ "end": "(?=$|[;,})\\]])",
308+ "patterns": [
309+ {
310+ "include": "#ternary-operator"
311+ },
312+ {
313+ "include": "#expression"
314+ }
315+ ]
316+ },
317+ "ternary-operator": {
318+ "begin": "(\\?)",
319+ "beginCaptures": {
320+ "0": {
321+ "name": "keyword.operator.ternary.tsx"
322+ }
323+ },
324+ "end": "(:)",
325+ "endCaptures": {
326+ "0": {
327+ "name": "keyword.operator.ternary.tsx"
328+ }
329+ },
330+ "patterns": [
331+ {
332+ "include": "#expression"
333+ }
334+ ]
335+ },
336+ "expression": {
337+ "name": "meta.expression.tsx",
338+ "patterns": [
339+ {
340+ "include": "#jsx"
341+ },
342+ {
343+ "include": "#string"
344+ },
345+ {
346+ "include": "#regex"
347+ },
348+ {
349+ "include": "#template"
350+ },
351+ {
352+ "include": "#comment"
353+ },
354+ {
355+ "include": "#literal"
356+ },
357+ {
358+ "include": "#function-declaration"
359+ },
360+ {
361+ "include": "#class-or-interface-declaration"
362+ },
363+ {
364+ "include": "#arrow-function"
365+ },
366+ {
367+ "include": "#cast"
368+ },
369+ {
370+ "include": "#ternary-expression"
371+ },
372+ {
373+ "include": "#new-expr"
374+ },
375+ {
376+ "include": "#object-literal"
377+ },
378+ {
379+ "include": "#expression-operators"
380+ },
381+ {
382+ "include": "#function-call"
383+ },
384+ {
385+ "include": "#support-objects"
386+ },
387+ {
388+ "include": "#identifiers"
389+ },
390+ {
391+ "include": "#paren-expression"
392+ },
393+ {
394+ "include": "#punctuation-comma"
395+ },
396+ {
397+ "include": "#punctuation-accessor"
398+ }
399+ ]
400+ },
401+ "control-statement": {
402+ "patterns": [
403+ {
404+ "name": "keyword.control.trycatch.tsx",
405+ "match": "(?<!\\.|\\$)\\b(catch|finally|throw|try)\\b(?!\\$)"
406+ },
407+ {
408+ "name": "keyword.control.loop.tsx",
409+ "match": "(?<!\\.|\\$)\\b(break|continue|do|goto|while)\\b(?!\\$)"
410+ },
411+ {
412+ "name": "keyword.control.flow.tsx",
413+ "match": "(?<!\\.|\\$)\\b(return)\\b(?!\\$)"
414+ },
415+ {
416+ "match": "(?<!\\.|\\$)\\b(yield)\\b(?!\\$)(?:\\s*(\\*))?",
417+ "captures": {
418+ "1": {
419+ "name": "keyword.control.flow.tsx"
420+ },
421+ "2": {
422+ "name": "keyword.generator.asterisk.tsx"
423+ }
424+ }
425+ },
426+ {
427+ "name": "keyword.control.switch.tsx",
428+ "match": "(?<!\\.|\\$)\\b(case|default|switch)\\b(?!\\$)"
429+ },
430+ {
431+ "name": "keyword.control.conditional.tsx",
432+ "match": "(?<!\\.|\\$)\\b(else|if)\\b(?!\\$)"
433+ },
434+ {
435+ "name": "keyword.control.with.tsx",
436+ "match": "(?<!\\.|\\$)\\b(with)\\b(?!\\$)"
437+ },
438+ {
439+ "name": "keyword.other.debugger.tsx",
440+ "match": "(?<!\\.|\\$)\\b(debugger)\\b(?!\\$)"
441+ },
442+ {
443+ "name": "storage.modifier.tsx",
444+ "match": "(?<!\\.|\\$)\\b(declare)\\b(?!\\$)"
445+ }
446+ ]
447+ },
448+ "declaration": {
449+ "name": "meta.declaration.tsx",
450+ "patterns": [
451+ {
452+ "include": "#decorator"
453+ },
454+ {
455+ "include": "#var-expr"
456+ },
457+ {
458+ "include": "#function-declaration"
459+ },
460+ {
461+ "include": "#class-or-interface-declaration"
462+ },
463+ {
464+ "include": "#type-declaration"
465+ },
466+ {
467+ "include": "#enum-declaration"
468+ },
469+ {
470+ "include": "#namespace-declaration"
471+ },
472+ {
473+ "include": "#import-equals-declaration"
474+ },
475+ {
476+ "include": "#import-declaration"
477+ },
478+ {
479+ "include": "#export-declaration"
480+ }
481+ ]
482+ },
483+ "decorator": {
484+ "name": "meta.decorator.tsx",
485+ "begin": "(?<!\\.|\\$)\\@",
486+ "beginCaptures": {
487+ "0": {
488+ "name": "punctuation.decorator.tsx"
489+ }
490+ },
491+ "end": "(?=\\s)",
492+ "patterns": [
493+ {
494+ "include": "#expression"
495+ }
496+ ]
497+ },
498+ "type-declaration": {
499+ "name": "meta.type.declaration.tsx",
500+ "begin": "(?<!\\.|\\$)(?:(\\bexport)\\s+)?\\b(type)\\b\\s+([_$[:alpha:]][_$[:alnum:]]*)\\s*",
501+ "beginCaptures": {
502+ "1": {
503+ "name": "keyword.control.export.tsx"
504+ },
505+ "2": {
506+ "name": "storage.type.type.tsx"
507+ },
508+ "3": {
509+ "name": "entity.name.type.tsx"
510+ }
511+ },
512+ "end": "(?=[};]|\\bvar\\b|\\blet\\b|\\bconst\\b|\\btype\\b|\\bfunction\\b|\\bclass\\b|\\binterface\\b|\\bnamespace\\b|\\bmodule\\b|\\bimport\\b|\\benum\\b|\\bdeclare\\b|\\bexport\\b|\\babstract\\b|\\basync\\b)",
513+ "patterns": [
514+ {
515+ "include": "#comment"
516+ },
517+ {
518+ "include": "#type-parameters"
519+ },
520+ {
521+ "include": "#type"
522+ },
523+ {
524+ "match": "(=)\\s*",
525+ "captures": {
526+ "1": {
527+ "name": "keyword.operator.assignment.tsx"
528+ }
529+ }
530+ }
531+ ]
532+ },
533+ "enum-declaration": {
534+ "name": "meta.enum.declaration.tsx",
535+ "begin": "(?<!\\.|\\$)(?:(\\bexport)\\s+)?(?:\\b(const)\\s+)?\\b(enum)\\s+([_$[:alpha:]][_$[:alnum:]]*)",
536+ "beginCaptures": {
537+ "1": {
538+ "name": "keyword.control.export.tsx"
539+ },
540+ "2": {
541+ "name": "storage.modifier.tsx"
542+ },
543+ "3": {
544+ "name": "storage.type.enum.tsx"
545+ },
546+ "4": {
547+ "name": "entity.name.type.enum.tsx"
548+ }
549+ },
550+ "end": "(?<=\\})",
551+ "patterns": [
552+ {
553+ "include": "#comment"
554+ },
555+ {
556+ "begin": "\\{",
557+ "beginCaptures": {
558+ "0": {
559+ "name": "punctuation.definition.block.tsx"
560+ }
561+ },
562+ "end": "\\}",
563+ "endCaptures": {
564+ "0": {
565+ "name": "punctuation.definition.block.tsx"
566+ }
567+ },
568+ "patterns": [
569+ {
570+ "include": "#comment"
571+ },
572+ {
573+ "begin": "([_$[:alpha:]][_$[:alnum:]]*)",
574+ "beginCaptures": {
575+ "0": {
576+ "name": "variable.other.enummember.tsx"
577+ }
578+ },
579+ "end": "(?=,|\\}|$)",
580+ "patterns": [
581+ {
582+ "include": "#comment"
583+ },
584+ {
585+ "include": "#variable-initializer"
586+ }
587+ ]
588+ },
589+ {
590+ "begin": "(?=((\\'[^']*\\')|(\\\"[^\"]*\\\")|(\\[([^\\[\\]]|\\[[^\\[\\]]+\\])+\\])))",
591+ "end": "(?=,|\\}|$)",
592+ "patterns": [
593+ {
594+ "include": "#string"
595+ },
596+ {
597+ "include": "#array-literal"
598+ },
599+ {
600+ "include": "#comment"
601+ },
602+ {
603+ "include": "#variable-initializer"
604+ }
605+ ]
606+ },
607+ {
608+ "include": "#punctuation-comma"
609+ }
610+ ]
611+ }
612+ ]
613+ },
614+ "namespace-declaration": {
615+ "name": "meta.namespace.declaration.tsx",
616+ "begin": "(?<!\\.|\\$)(?:(\\bexport)\\s+)?\\b(namespace|module)\\s+",
617+ "beginCaptures": {
618+ "1": {
619+ "name": "keyword.control.export.tsx"
620+ },
621+ "2": {
622+ "name": "storage.type.namespace.tsx"
623+ }
624+ },
625+ "end": "(?=$|\\{)",
626+ "patterns": [
627+ {
628+ "include": "#comment"
629+ },
630+ {
631+ "include": "#string"
632+ },
633+ {
634+ "name": "entity.name.type.module.tsx",
635+ "match": "([_$[:alpha:]][_$[:alnum:]]*)"
636+ },
637+ {
638+ "name": "punctuation.accessor.tsx",
639+ "match": "\\."
640+ }
641+ ]
642+ },
643+ "import-equals-declaration": {
644+ "patterns": [
645+ {
646+ "name": "meta.import-equals.external.tsx",
647+ "begin": "(?<!\\.|\\$)(?:(\\bexport)\\s+)?\\b(import)\\s+([_$[:alpha:]][_$[:alnum:]]*)\\s*(=)\\s*(require)\\s*(\\()",
648+ "beginCaptures": {
649+ "1": {
650+ "name": "keyword.control.export.tsx"
651+ },
652+ "2": {
653+ "name": "keyword.control.import.tsx"
654+ },
655+ "3": {
656+ "name": "variable.other.readwrite.alias.tsx"
657+ },
658+ "4": {
659+ "name": "keyword.operator.assignment.tsx"
660+ },
661+ "5": {
662+ "name": "keyword.control.require.tsx"
663+ },
664+ "6": {
665+ "name": "meta.brace.round.tsx"
666+ }
667+ },
668+ "end": "\\)",
669+ "endCaptures": {
670+ "0": {
671+ "name": "meta.brace.round.tsx"
672+ }
673+ },
674+ "patterns": [
675+ {
676+ "include": "#comment"
677+ },
678+ {
679+ "include": "#string"
680+ }
681+ ]
682+ },
683+ {
684+ "name": "meta.import-equals.internal.tsx",
685+ "begin": "(?<!\\.|\\$)(?:(\\bexport)\\s+)?\\b(import)\\s+([_$[:alpha:]][_$[:alnum:]]*)\\s*(=)\\s*(?!require\\b)",
686+ "beginCaptures": {
687+ "1": {
688+ "name": "keyword.control.export.tsx"
689+ },
690+ "2": {
691+ "name": "keyword.control.import.tsx"
692+ },
693+ "3": {
694+ "name": "variable.other.readwrite.alias.tsx"
695+ },
696+ "4": {
697+ "name": "keyword.operator.assignment.tsx"
698+ }
699+ },
700+ "end": "(?=;|$)",
701+ "patterns": [
702+ {
703+ "include": "#comment"
704+ },
705+ {
706+ "match": "([_$[:alpha:]][_$[:alnum:]]*)\\s*(\\.)",
707+ "captures": {
708+ "1": {
709+ "name": "entity.name.type.module.tsx"
710+ },
711+ "2": {
712+ "name": "punctuation.accessor.tsx"
713+ }
714+ }
715+ },
716+ {
717+ "name": "variable.other.readwrite.tsx",
718+ "match": "([_$[:alpha:]][_$[:alnum:]]*)"
719+ }
720+ ]
721+ }
722+ ]
723+ },
724+ "import-declaration": {
725+ "name": "meta.import.tsx",
726+ "begin": "(?<!\\.|\\$)(?:(\\bexport)\\s+)?\\b(import)(?!(\\s*:)|(\\$))\\b",
727+ "beginCaptures": {
728+ "1": {
729+ "name": "keyword.control.export.tsx"
730+ },
731+ "2": {
732+ "name": "keyword.control.import.tsx"
733+ }
734+ },
735+ "end": "(?=;|$)",
736+ "patterns": [
737+ {
738+ "include": "#import-export-declaration"
739+ }
740+ ]
741+ },
742+ "export-declaration": {
743+ "patterns": [
744+ {
745+ "match": "(?<!\\.|\\$)\\b(export)\\s+(as)\\s+(namespace)\\s+([_$[:alpha:]][_$[:alnum:]]*)",
746+ "captures": {
747+ "1": {
748+ "name": "keyword.control.export.tsx"
749+ },
750+ "2": {
751+ "name": "keyword.control.as.tsx"
752+ },
753+ "3": {
754+ "name": "storage.type.namespace.tsx"
755+ },
756+ "4": {
757+ "name": "entity.name.type.module.tsx"
758+ }
759+ }
760+ },
761+ {
762+ "name": "meta.export.default.tsx",
763+ "begin": "(?<!\\.|\\$)\\b(export)(?:(?:\\s*(=))|(?:\\s+(default)(?=\\s+)))",
764+ "beginCaptures": {
765+ "1": {
766+ "name": "keyword.control.export.tsx"
767+ },
768+ "2": {
769+ "name": "keyword.operator.assignment.tsx"
770+ },
771+ "3": {
772+ "name": "keyword.control.default.tsx"
773+ }
774+ },
775+ "end": "(?=;|\\bexport\\b|\\bfunction\\b|\\bclass\\b|\\binterface\\b|\\blet\\b|\\bvar\\b|\\bconst\\b|\\bimport\\b|\\benum\\b|\\bnamespace\\b|\\bmodule\\b|\\btype\\b|\\babstract\\b|\\bdeclare\\b|\\basync\\b|$)",
776+ "patterns": [
777+ {
778+ "include": "#expression"
779+ }
780+ ]
781+ },
782+ {
783+ "name": "meta.export.tsx",
784+ "begin": "(?<!\\.|\\$)\\b(export)(?!(\\s*:)|(\\$))\\b",
785+ "beginCaptures": {
786+ "0": {
787+ "name": "keyword.control.export.tsx"
788+ }
789+ },
790+ "end": "(?=;|\\bexport\\b|\\bfunction\\b|\\bclass\\b|\\binterface\\b|\\blet\\b|\\bvar\\b|\\bconst\\b|\\bimport\\b|\\benum\\b|\\bnamespace\\b|\\bmodule\\b|\\btype\\b|\\babstract\\b|\\bdeclare\\b|\\basync\\b|$)",
791+ "patterns": [
792+ {
793+ "include": "#import-export-declaration"
794+ }
795+ ]
796+ }
797+ ]
798+ },
799+ "import-export-declaration": {
800+ "patterns": [
801+ {
802+ "include": "#comment"
803+ },
804+ {
805+ "include": "#string"
806+ },
807+ {
808+ "include": "#import-export-block"
809+ },
810+ {
811+ "name": "keyword.control.from.tsx",
812+ "match": "\\bfrom\\b"
813+ },
814+ {
815+ "include": "#import-export-clause"
816+ }
817+ ]
818+ },
819+ "import-export-block": {
820+ "name": "meta.block.tsx",
821+ "begin": "\\{",
822+ "beginCaptures": {
823+ "0": {
824+ "name": "punctuation.definition.block.tsx"
825+ }
826+ },
827+ "end": "\\}",
828+ "endCaptures": {
829+ "0": {
830+ "name": "punctuation.definition.block.tsx"
831+ }
832+ },
833+ "patterns": [
834+ {
835+ "include": "#import-export-clause"
836+ }
837+ ]
838+ },
839+ "import-export-clause": {
840+ "patterns": [
841+ {
842+ "include": "#comment"
843+ },
844+ {
845+ "comment": "(default|*|name) as alias",
846+ "match": "(?x) (?: \\b(default)\\b | (\\*) | ([_$[:alpha:]][_$[:alnum:]]*)) \\s+ (as) \\s+ (?: (\\b default \\b | \\*) | ([_$[:alpha:]][_$[:alnum:]]*))",
847+ "captures": {
848+ "1": {
849+ "name": "keyword.control.default.tsx"
850+ },
851+ "2": {
852+ "name": "constant.language.import-export-all.tsx"
853+ },
854+ "3": {
855+ "name": "variable.other.readwrite.tsx"
856+ },
857+ "4": {
858+ "name": "keyword.control.as.tsx"
859+ },
860+ "5": {
861+ "name": "invalid.illegal.tsx"
862+ },
863+ "6": {
864+ "name": "variable.other.readwrite.alias.tsx"
865+ }
866+ }
867+ },
868+ {
869+ "include": "#punctuation-comma"
870+ },
871+ {
872+ "name": "constant.language.import-export-all.tsx",
873+ "match": "\\*"
874+ },
875+ {
876+ "name": "keyword.control.default.tsx",
877+ "match": "\\b(default)\\b"
878+ },
879+ {
880+ "name": "variable.other.readwrite.alias.tsx",
881+ "match": "([_$[:alpha:]][_$[:alnum:]]*)"
882+ }
883+ ]
884+ },
885+ "class-or-interface-declaration": {
886+ "name": "meta.class.tsx",
887+ "begin": "(?<!\\.|\\$)\\b(?:(export)\\s+)?\\b(?:(abstract)\\s+)?\\b(?:(class)|(interface))\\b",
888+ "beginCaptures": {
889+ "1": {
890+ "name": "keyword.control.export.tsx"
891+ },
892+ "2": {
893+ "name": "storage.modifier.tsx"
894+ },
895+ "3": {
896+ "name": "storage.type.class.tsx"
897+ },
898+ "4": {
899+ "name": "storage.type.interface.tsx"
900+ }
901+ },
902+ "end": "(?<=\\})",
903+ "endCaptures": {
904+ "1": {
905+ "name": "punctuation.definition.block.tsx"
906+ }
907+ },
908+ "patterns": [
909+ {
910+ "include": "#comment"
911+ },
912+ {
913+ "include": "#class-or-interface-heritage"
914+ },
915+ {
916+ "match": "[_$[:alpha:]][_$[:alnum:]]*",
917+ "captures": {
918+ "0": {
919+ "name": "entity.name.type.class.tsx"
920+ }
921+ }
922+ },
923+ {
924+ "include": "#type-parameters"
925+ },
926+ {
927+ "include": "#class-or-interface-body"
928+ }
929+ ]
930+ },
931+ "class-or-interface-heritage": {
932+ "begin": "(?<!\\.|\\$)(?:\\b(extends|implements)\\b)(?!\\$)",
933+ "beginCaptures": {
934+ "1": {
935+ "name": "storage.modifier.tsx"
936+ }
937+ },
938+ "end": "(?=\\{)",
939+ "endCaptures": {
940+ "1": {
941+ "name": "punctuation.definition.block.tsx"
942+ }
943+ },
944+ "patterns": [
945+ {
946+ "include": "#comment"
947+ },
948+ {
949+ "include": "#class-or-interface-heritage"
950+ },
951+ {
952+ "include": "#type-parameters"
953+ },
954+ {
955+ "match": "([_$[:alpha:]][_$[:alnum:]]*)\\s*(\\.)(?=\\s*[_$[:alpha:]][_$[:alnum:]]*(\\s*\\.\\s*[_$[:alpha:]][_$[:alnum:]]*)*\\s*([,<{]|extends|implements|//|/\\*))",
956+ "captures": {
957+ "1": {
958+ "name": "entity.name.type.module.tsx"
959+ },
960+ "2": {
961+ "name": "punctuation.accessor.tsx"
962+ }
963+ }
964+ },
965+ {
966+ "match": "([_$[:alpha:]][_$[:alnum:]]*)(?=\\s*([,<{]|extends|implements|//|/\\*))",
967+ "captures": {
968+ "1": {
969+ "name": "entity.other.inherited-class.tsx"
970+ }
971+ }
972+ },
973+ {
974+ "include": "#expression"
975+ }
976+ ]
977+ },
978+ "class-or-interface-body": {
979+ "begin": "\\{",
980+ "beginCaptures": {
981+ "0": {
982+ "name": "punctuation.definition.block.tsx"
983+ }
984+ },
985+ "end": "\\}",
986+ "endCaptures": {
987+ "0": {
988+ "name": "punctuation.definition.block.tsx"
989+ }
990+ },
991+ "patterns": [
992+ {
993+ "include": "#string"
994+ },
995+ {
996+ "include": "#comment"
997+ },
998+ {
999+ "include": "#decorator"
1000+ },
1001+ {
1002+ "include": "#method-declaration"
1003+ },
1004+ {
1005+ "include": "#indexer-declaration"
1006+ },
1007+ {
1008+ "include": "#field-declaration"
1009+ },
1010+ {
1011+ "include": "#type-annotation"
1012+ },
1013+ {
1014+ "include": "#variable-initializer"
1015+ },
1016+ {
1017+ "include": "#access-modifier"
1018+ },
1019+ {
1020+ "include": "#property-accessor"
1021+ },
1022+ {
1023+ "include": "#expression"
1024+ },
1025+ {
1026+ "include": "#punctuation-comma"
1027+ },
1028+ {
1029+ "include": "#punctuation-semicolon"
1030+ }
1031+ ]
1032+ },
1033+ "type-object": {
1034+ "name": "meta.object.type.tsx",
1035+ "begin": "\\{",
1036+ "beginCaptures": {
1037+ "0": {
1038+ "name": "punctuation.definition.block.tsx"
1039+ }
1040+ },
1041+ "end": "\\}",
1042+ "endCaptures": {
1043+ "0": {
1044+ "name": "punctuation.definition.block.tsx"
1045+ }
1046+ },
1047+ "patterns": [
1048+ {
1049+ "include": "#type-object-members"
1050+ }
1051+ ]
1052+ },
1053+ "type-object-members": {
1054+ "patterns": [
1055+ {
1056+ "include": "#comment"
1057+ },
1058+ {
1059+ "include": "#method-declaration"
1060+ },
1061+ {
1062+ "include": "#indexer-declaration"
1063+ },
1064+ {
1065+ "include": "#field-declaration"
1066+ },
1067+ {
1068+ "include": "#type-annotation"
1069+ },
1070+ {
1071+ "begin": "\\.\\.\\.",
1072+ "beginCaptures": {
1073+ "0": {
1074+ "name": "keyword.operator.spread.tsx"
1075+ }
1076+ },
1077+ "end": "(?=\\}|;|,|$)|(?<=\\})",
1078+ "patterns": [
1079+ {
1080+ "include": "#type"
1081+ }
1082+ ]
1083+ },
1084+ {
1085+ "include": "#punctuation-comma"
1086+ },
1087+ {
1088+ "include": "#punctuation-semicolon"
1089+ }
1090+ ]
1091+ },
1092+ "field-declaration": {
1093+ "name": "meta.field.declaration.tsx",
1094+ "begin": "(?<!\\()(?:(?<!\\.|\\$)\\b(readonly)\\s+)?(?=(([_$[:alpha:]][_$[:alnum:]]*)|(\\'[^']*\\')|(\\\"[^\"]*\\\")|(\\[([^\\[\\]]|\\[[^\\[\\]]+\\])+\\]))\\s*(\\?\\s*)?(=|:))",
1095+ "beginCaptures": {
1096+ "1": {
1097+ "name": "storage.modifier.tsx"
1098+ }
1099+ },
1100+ "end": "(?=\\}|;|,|$)|(?<=\\})",
1101+ "patterns": [
1102+ {
1103+ "include": "#variable-initializer"
1104+ },
1105+ {
1106+ "begin": "(?=((?:[_$[:alpha:]][_$[:alnum:]]*)|(?:\\'[^']*\\')|(?:\\\"[^\"]*\\\")|(\\[([^\\[\\]]|\\[[^\\[\\]]+\\])+\\]))\\s*(\\?\\s*)?(=|:))",
1107+ "end": "(?=[};,=]|$)|(?<=\\})",
1108+ "patterns": [
1109+ {
1110+ "include": "#type-annotation"
1111+ },
1112+ {
1113+ "include": "#string"
1114+ },
1115+ {
1116+ "include": "#array-literal"
1117+ },
1118+ {
1119+ "include": "#comment"
1120+ },
1121+ {
1122+ "name": "entity.name.function.tsx",
1123+ "match": "(?x)([_$[:alpha:]][_$[:alnum:]]*)(?=(\\?\\s*)?\\s* (=\\s*( (async\\s+) | (function\\s*[(<]) | (function\\s+) | ([_$[:alpha:]][_$[:alnum:]]*\\s*=>) | ((<([^<>]|\\<[^<>]+\\>)+>\\s*)?\\(([^()]|\\([^()]*\\))*\\)(\\s*:\\s*(.)*)?\\s*=>)) ) | (:\\s*( (<) | ([(]\\s*( ([)]) | (\\.\\.\\.) | ([_$[:alnum:]]+\\s*( ([:,?=])| ([)]\\s*=>) )) ))) ))"
1124+ },
1125+ {
1126+ "name": "variable.object.property.tsx",
1127+ "match": "[_$[:alpha:]][_$[:alnum:]]*"
1128+ },
1129+ {
1130+ "name": "keyword.operator.optional.tsx",
1131+ "match": "\\?"
1132+ }
1133+ ]
1134+ }
1135+ ]
1136+ },
1137+ "method-declaration": {
1138+ "name": "meta.method.declaration.tsx",
1139+ "begin": "(?<!\\.|\\$)(?:\\b(public|private|protected)\\s+)?(?:\\b(abstract)\\s+)?(?:\\b(async)\\s+)?(?:\\b(get|set)\\s+)?(?:(?:\\b(?:(new)|(constructor))\\b(?!\\$|:))|(?:(\\*)\\s*)?(?=((([_$[:alpha:]][_$[:alnum:]]*)|(\\'[^']*\\')|(\\\"[^\"]*\\\")|(\\[([^\\[\\]]|\\[[^\\[\\]]+\\])+\\]))\\s*(\\??))?\\s*[\\(\\<]))",
1140+ "beginCaptures": {
1141+ "1": {
1142+ "name": "storage.modifier.tsx"
1143+ },
1144+ "2": {
1145+ "name": "storage.modifier.tsx"
1146+ },
1147+ "3": {
1148+ "name": "storage.modifier.async.tsx"
1149+ },
1150+ "4": {
1151+ "name": "storage.type.property.tsx"
1152+ },
1153+ "5": {
1154+ "name": "keyword.operator.new.tsx"
1155+ },
1156+ "6": {
1157+ "name": "storage.type.tsx"
1158+ },
1159+ "7": {
1160+ "name": "keyword.generator.asterisk.tsx"
1161+ }
1162+ },
1163+ "end": "(?=\\}|;|,)|(?<=\\})",
1164+ "patterns": [
1165+ {
1166+ "include": "#method-declaration-name"
1167+ },
1168+ {
1169+ "include": "#comment"
1170+ },
1171+ {
1172+ "include": "#type-parameters"
1173+ },
1174+ {
1175+ "include": "#function-parameters"
1176+ },
1177+ {
1178+ "include": "#return-type"
1179+ },
1180+ {
1181+ "include": "#method-overload-declaration"
1182+ },
1183+ {
1184+ "include": "#decl-block"
1185+ }
1186+ ]
1187+ },
1188+ "method-overload-declaration": {
1189+ "begin": "(?<!\\.|\\$)(?:\\b(public|private|protected)\\s+)?(?:\\b(abstract)\\s+)?(?:\\b(async)\\s+)?(?:\\b(get|set)\\s+)?(?:(?:\\b(?:(new)|(constructor))\\b(?!\\$|:))|(?:(\\*)\\s*)?(?=((([_$[:alpha:]][_$[:alnum:]]*)|(\\'[^']*\\')|(\\\"[^\"]*\\\")|(\\[([^\\[\\]]|\\[[^\\[\\]]+\\])+\\]))\\s*(\\??))?\\s*[\\(\\<]))",
1190+ "beginCaptures": {
1191+ "1": {
1192+ "name": "storage.modifier.tsx"
1193+ },
1194+ "2": {
1195+ "name": "storage.modifier.tsx"
1196+ },
1197+ "3": {
1198+ "name": "storage.modifier.async.tsx"
1199+ },
1200+ "4": {
1201+ "name": "storage.type.property.tsx"
1202+ },
1203+ "5": {
1204+ "name": "keyword.operator.new.tsx"
1205+ },
1206+ "6": {
1207+ "name": "storage.type.tsx"
1208+ },
1209+ "7": {
1210+ "name": "keyword.generator.asterisk.tsx"
1211+ }
1212+ },
1213+ "end": "(?=\\(|\\<)",
1214+ "patterns": [
1215+ {
1216+ "include": "#method-declaration-name"
1217+ }
1218+ ]
1219+ },
1220+ "method-declaration-name": {
1221+ "begin": "(?=(([_$[:alpha:]][_$[:alnum:]]*)|(\\'[^']*\\')|(\\\"[^\"]*\\\")|(\\[([^\\[\\]]|\\[[^\\[\\]]+\\])+\\]))\\s*(\\??)\\s*[\\(\\<])",
1222+ "end": "(?=\\(|\\<)",
1223+ "patterns": [
1224+ {
1225+ "include": "#string"
1226+ },
1227+ {
1228+ "include": "#array-literal"
1229+ },
1230+ {
1231+ "name": "entity.name.function.tsx",
1232+ "match": "[_$[:alpha:]][_$[:alnum:]]*"
1233+ },
1234+ {
1235+ "name": "keyword.operator.optional.tsx",
1236+ "match": "\\?"
1237+ }
1238+ ]
1239+ },
1240+ "indexer-declaration": {
1241+ "name": "meta.indexer.declaration.tsx",
1242+ "begin": "(?:(?<!\\.|\\$)\\b(readonly)\\s*)?(\\[)\\s*([_$[:alpha:]][_$[:alnum:]]*)\\s*(?=:)",
1243+ "beginCaptures": {
1244+ "1": {
1245+ "name": "storage.modifier.tsx"
1246+ },
1247+ "2": {
1248+ "name": "meta.brace.square.tsx"
1249+ },
1250+ "3": {
1251+ "name": "variable.parameter.tsx"
1252+ }
1253+ },
1254+ "end": "(\\])\\s*(\\?\\s*)?|$",
1255+ "endCaptures": {
1256+ "1": {
1257+ "name": "meta.brace.square.tsx"
1258+ },
1259+ "2": {
1260+ "name": "keyword.operator.optional.tsx"
1261+ }
1262+ },
1263+ "patterns": [
1264+ {
1265+ "include": "#type-annotation"
1266+ }
1267+ ]
1268+ },
1269+ "function-declaration": {
1270+ "name": "meta.function.tsx",
1271+ "begin": "(?<!\\.|\\$)\\b(?:(export)\\s+)?(?:(async)\\s+)?(function\\b)(?:\\s*(\\*))?(?:(?:\\s+|(?<=\\*))([_$[:alpha:]][_$[:alnum:]]*))?\\s*",
1272+ "beginCaptures": {
1273+ "1": {
1274+ "name": "keyword.control.export.tsx"
1275+ },
1276+ "2": {
1277+ "name": "storage.modifier.async.tsx"
1278+ },
1279+ "3": {
1280+ "name": "storage.type.function.tsx"
1281+ },
1282+ "4": {
1283+ "name": "keyword.generator.asterisk.tsx"
1284+ },
1285+ "5": {
1286+ "name": "entity.name.function.tsx"
1287+ }
1288+ },
1289+ "end": "(?=;|\\})|(?<=\\})",
1290+ "patterns": [
1291+ {
1292+ "include": "#comment"
1293+ },
1294+ {
1295+ "include": "#type-parameters"
1296+ },
1297+ {
1298+ "include": "#function-parameters"
1299+ },
1300+ {
1301+ "include": "#return-type"
1302+ },
1303+ {
1304+ "include": "#function-overload-declaration"
1305+ },
1306+ {
1307+ "include": "#decl-block"
1308+ }
1309+ ]
1310+ },
1311+ "function-overload-declaration": {
1312+ "name": "meta.function.overload.tsx",
1313+ "match": "(?<!\\.|\\$)\\b(?:(export)\\s+)?(?:(async)\\s+)?(function\\b)(?:\\s*(\\*))?(?:(?:\\s+|(?<=\\*))([_$[:alpha:]][_$[:alnum:]]*))?\\s*",
1314+ "captures": {
1315+ "1": {
1316+ "name": "keyword.control.export.tsx"
1317+ },
1318+ "2": {
1319+ "name": "storage.modifier.async.tsx"
1320+ },
1321+ "3": {
1322+ "name": "storage.type.function.tsx"
1323+ },
1324+ "4": {
1325+ "name": "keyword.generator.asterisk.tsx"
1326+ },
1327+ "5": {
1328+ "name": "entity.name.function.tsx"
1329+ }
1330+ }
1331+ },
1332+ "object-literal": {
1333+ "name": "meta.objectliteral.tsx",
1334+ "begin": "\\{",
1335+ "beginCaptures": {
1336+ "0": {
1337+ "name": "punctuation.definition.block.tsx"
1338+ }
1339+ },
1340+ "end": "\\}",
1341+ "endCaptures": {
1342+ "0": {
1343+ "name": "punctuation.definition.block.tsx"
1344+ }
1345+ },
1346+ "patterns": [
1347+ {
1348+ "include": "#object-member"
1349+ }
1350+ ]
1351+ },
1352+ "decl-block": {
1353+ "name": "meta.block.tsx",
1354+ "begin": "\\{",
1355+ "beginCaptures": {
1356+ "0": {
1357+ "name": "punctuation.definition.block.tsx"
1358+ }
1359+ },
1360+ "end": "\\}",
1361+ "endCaptures": {
1362+ "0": {
1363+ "name": "punctuation.definition.block.tsx"
1364+ }
1365+ },
1366+ "patterns": [
1367+ {
1368+ "include": "#statements"
1369+ }
1370+ ]
1371+ },
1372+ "after-operator-block": {
1373+ "name": "meta.objectliteral.tsx",
1374+ "begin": "(?<=[=(,\\[?+!]|await|return|yield|throw|in|of|typeof|&&|\\|\\||\\*)\\s*(\\{)",
1375+ "beginCaptures": {
1376+ "1": {
1377+ "name": "punctuation.definition.block.tsx"
1378+ }
1379+ },
1380+ "end": "\\}",
1381+ "endCaptures": {
1382+ "0": {
1383+ "name": "punctuation.definition.block.tsx"
1384+ }
1385+ },
1386+ "patterns": [
1387+ {
1388+ "include": "#object-member"
1389+ }
1390+ ]
1391+ },
1392+ "parameter-name": {
1393+ "patterns": [
1394+ {
1395+ "match": "(?x)(?:\\s*\\b(readonly)\\s+)?(?:\\s*\\b(public|private|protected)\\s+)?(\\.\\.\\.)?\\s*(?<!=|:)([_$[:alpha:]][_$[:alnum:]]*)\\s*(\\??)(?=\\s* (=\\s*( (async\\s+) | (function\\s*[(<]) | (function\\s+) | ([_$[:alpha:]][_$[:alnum:]]*\\s*=>) | ((<([^<>]|\\<[^<>]+\\>)+>\\s*)?\\(([^()]|\\([^()]*\\))*\\)(\\s*:\\s*(.)*)?\\s*=>)) ) | (:\\s*( (<) | ([(]\\s*( ([)]) | (\\.\\.\\.) | ([_$[:alnum:]]+\\s*( ([:,?=])| ([)]\\s*=>) )) ))) ))",
1396+ "captures": {
1397+ "1": {
1398+ "name": "storage.modifier.tsx"
1399+ },
1400+ "2": {
1401+ "name": "storage.modifier.tsx"
1402+ },
1403+ "3": {
1404+ "name": "keyword.operator.rest.tsx"
1405+ },
1406+ "4": {
1407+ "name": "entity.name.function.tsx"
1408+ },
1409+ "5": {
1410+ "name": "keyword.operator.optional.tsx"
1411+ }
1412+ }
1413+ },
1414+ {
1415+ "match": "(?:\\s*\\b(readonly)\\s+)?(?:\\s*\\b(public|private|protected)\\s+)?(\\.\\.\\.)?\\s*(?<!=|:)([_$[:alpha:]][_$[:alnum:]]*)\\s*(\\??)",
1416+ "captures": {
1417+ "1": {
1418+ "name": "storage.modifier.tsx"
1419+ },
1420+ "2": {
1421+ "name": "storage.modifier.tsx"
1422+ },
1423+ "3": {
1424+ "name": "keyword.operator.rest.tsx"
1425+ },
1426+ "4": {
1427+ "name": "variable.parameter.tsx"
modified extensions/vscode/textmate-syntaxes/c++.json +454 −454
@@ -1,455 +1,455 @@
11 {
2- "scopeName": "source.cpp",
3- "fileTypes": [
4- "cc",
5- "cpp",
6- "cp",
7- "cxx",
8- "c++",
9- "cu",
10- "cuh",
11- "h",
12- "hh",
13- "hpp",
14- "hxx",
15- "h++",
16- "inl",
17- "ino",
18- "ipp",
19- "tcc",
20- "tpp"
21- ],
22- "firstLineMatch": "(?i)-\\*-[^*]*(Mode:\\s*)?C\\+\\+(\\s*;.*?)?\\s*-\\*-",
23- "name": "C++",
24- "patterns": [
25- {
26- "include": "#special_block"
27- },
28- {
29- "include": "#strings"
30- },
31- {
32- "match": "\\b(friend|explicit|virtual|override|final|noexcept)\\b",
33- "name": "storage.modifier.cpp"
34- },
35- {
36- "match": "\\b(private:|protected:|public:)",
37- "name": "storage.modifier.cpp"
38- },
39- {
40- "match": "\\b(catch|operator|try|throw|using)\\b",
41- "name": "keyword.control.cpp"
42- },
43- {
44- "match": "\\bdelete\\b(\\s*\\[\\])?|\\bnew\\b(?!])",
45- "name": "keyword.control.cpp"
46- },
47- {
48- "match": "\\b(f|m)[A-Z]\\w*\\b",
49- "name": "variable.other.readwrite.member.cpp"
50- },
51- {
52- "match": "\\bthis\\b",
53- "name": "variable.language.this.cpp"
54- },
55- {
56- "match": "\\bnullptr\\b",
57- "name": "variable.language.cpp"
58- },
59- {
60- "match": "\\btemplate\\b\\s*",
61- "name": "storage.type.template.cpp"
62- },
63- {
64- "match": "\\b(const_cast|dynamic_cast|reinterpret_cast|static_cast)\\b\\s*",
65- "name": "keyword.operator.cast.cpp"
66- },
67- {
68- "match": "\\b(and|and_eq|bitand|bitor|compl|not|not_eq|or|or_eq|typeid|xor|xor_eq|alignof|alignas)\\b",
69- "name": "keyword.operator.cpp"
70- },
71- {
72- "match": "\\b(class|decltype|wchar_t|char16_t|char32_t)\\b",
73- "name": "storage.type.cpp"
74- },
75- {
76- "match": "\\b(constexpr|export|mutable|typename|thread_local)\\b",
77- "name": "storage.modifier.cpp"
78- },
79- {
80- "begin": "(?x)\n(?:\n ^ | # beginning of line\n (?:(?<!else|new|=)) # or word + space before name\n)\n((?:[A-Za-z_][A-Za-z0-9_]*::)*+~[A-Za-z_][A-Za-z0-9_]*) # actual name\n\\s*(\\() # opening bracket",
81- "beginCaptures": {
82- "1": {
83- "name": "entity.name.function.cpp"
84- },
85- "2": {
86- "name": "punctuation.definition.parameters.begin.c"
87- }
88- },
89- "end": "\\)",
90- "endCaptures": {
91- "0": {
92- "name": "punctuation.definition.parameters.end.c"
93- }
94- },
95- "name": "meta.function.destructor.cpp",
96- "patterns": [
97- {
98- "include": "$base"
99- }
100- ]
101- },
102- {
103- "begin": "(?x)\n(?:\n ^ | # beginning of line\n (?:(?<!else|new|=)) # or word + space before name\n)\n((?:[A-Za-z_][A-Za-z0-9_]*::)*+~[A-Za-z_][A-Za-z0-9_]*) # actual name\n\\s*(\\() # opening bracket",
104- "beginCaptures": {
105- "1": {
106- "name": "entity.name.function.cpp"
107- },
108- "2": {
109- "name": "punctuation.definition.parameters.begin.c"
110- }
111- },
112- "end": "\\)",
113- "endCaptures": {
114- "0": {
115- "name": "punctuation.definition.parameters.end.c"
116- }
117- },
118- "name": "meta.function.destructor.prototype.cpp",
119- "patterns": [
120- {
121- "include": "$base"
122- }
123- ]
124- },
125- {
126- "include": "source.c"
127- }
128- ],
129- "repository": {
130- "angle_brackets": {
131- "begin": "<",
132- "end": ">",
133- "name": "meta.angle-brackets.cpp",
134- "patterns": [
135- {
136- "include": "#angle_brackets"
137- },
138- {
139- "include": "$base"
140- }
141- ]
142- },
143- "block": {
144- "begin": "\\{",
145- "beginCaptures": {
146- "0": {
147- "name": "punctuation.section.block.begin.c"
148- }
149- },
150- "end": "\\}",
151- "endCaptures": {
152- "0": {
153- "name": "punctuation.section.block.end.c"
154- }
155- },
156- "name": "meta.block.cpp",
157- "patterns": [
158- {
159- "captures": {
160- "1": {
161- "name": "support.function.any-method.c"
162- },
163- "2": {
164- "name": "punctuation.definition.parameters.c"
165- }
166- },
167- "match": "(?x)\n(\n (?!while|for|do|if|else|switch|catch|enumerate|return|r?iterate)\n (?:\\b[A-Za-z_][A-Za-z0-9_]*+\\b|::)*+ # actual name\n)\n\\s*(\\() # opening bracket",
168- "name": "meta.function-call.c"
169- },
170- {
171- "include": "$base"
172- }
173- ]
174- },
175- "constructor": {
176- "patterns": [
177- {
178- "begin": "(?x)\n(?:^\\s*) # beginning of line\n((?!while|for|do|if|else|switch|catch|enumerate|r?iterate)[A-Za-z_][A-Za-z0-9_:]*) # actual name\n\\s*(\\() # opening bracket",
179- "beginCaptures": {
180- "1": {
181- "name": "entity.name.function.cpp"
182- },
183- "2": {
184- "name": "punctuation.definition.parameters.begin.c"
185- }
186- },
187- "end": "\\)",
188- "endCaptures": {
189- "0": {
190- "name": "punctuation.definition.parameters.end.c"
191- }
192- },
193- "name": "meta.function.constructor.cpp",
194- "patterns": [
195- {
196- "include": "$base"
197- }
198- ]
199- },
200- {
201- "begin": "(?x)\n(:)\n(\n (?=\n \\s*[A-Za-z_][A-Za-z0-9_:]* # actual name\n \\s* (\\() # opening bracket\n )\n)",
202- "beginCaptures": {
203- "1": {
204- "name": "punctuation.definition.parameters.c"
205- }
206- },
207- "end": "(?=\\{)",
208- "name": "meta.function.constructor.initializer-list.cpp",
209- "patterns": [
210- {
211- "include": "$base"
212- }
213- ]
214- }
215- ]
216- },
217- "special_block": {
218- "patterns": [
219- {
220- "begin": "\\b(using)\\b\\s*(namespace)\\b\\s*((?:[_A-Za-z][_A-Za-z0-9]*\\b(::)?)*)",
221- "beginCaptures": {
222- "1": {
223- "name": "keyword.control.cpp"
224- },
225- "2": {
226- "name": "storage.type.cpp"
227- },
228- "3": {
229- "name": "entity.name.type.cpp"
230- }
231- },
232- "end": "(;)",
233- "name": "meta.using-namespace-declaration.cpp"
234- },
235- {
236- "begin": "\\b(namespace)\\b\\s*([_A-Za-z][_A-Za-z0-9]*\\b)?+",
237- "beginCaptures": {
238- "1": {
239- "name": "storage.type.cpp"
240- },
241- "2": {
242- "name": "entity.name.type.cpp"
243- }
244- },
245- "captures": {
246- "1": {
247- "name": "keyword.control.namespace.$2"
248- }
249- },
250- "end": "(?<=\\})|(?=(;|,|\\(|\\)|>|\\[|\\]|=))",
251- "name": "meta.namespace-block.cpp",
252- "patterns": [
253- {
254- "begin": "\\{",
255- "beginCaptures": {
256- "0": {
257- "name": "punctuation.definition.scope.cpp"
258- }
259- },
260- "end": "\\}",
261- "endCaptures": {
262- "0": {
263- "name": "punctuation.definition.scope.cpp"
264- }
265- },
266- "patterns": [
267- {
268- "include": "#special_block"
269- },
270- {
271- "include": "#constructor"
272- },
273- {
274- "include": "$base"
275- }
276- ]
277- },
278- {
279- "include": "$base"
280- }
281- ]
282- },
283- {
284- "begin": "\\b(class|struct)\\b\\s*([_A-Za-z][_A-Za-z0-9]*\\b)?+(\\s*:\\s*(public|protected|private)\\s*([_A-Za-z][_A-Za-z0-9]*\\b)((\\s*,\\s*(public|protected|private)\\s*[_A-Za-z][_A-Za-z0-9]*\\b)*))?",
285- "beginCaptures": {
286- "1": {
287- "name": "storage.type.cpp"
288- },
289- "2": {
290- "name": "entity.name.type.cpp"
291- },
292- "4": {
293- "name": "storage.type.modifier.cpp"
294- },
295- "5": {
296- "name": "entity.name.type.inherited.cpp"
297- },
298- "6": {
299- "patterns": [
300- {
301- "match": "(public|protected|private)",
302- "name": "storage.type.modifier.cpp"
303- },
304- {
305- "match": "[_A-Za-z][_A-Za-z0-9]*",
306- "name": "entity.name.type.inherited.cpp"
307- }
308- ]
309- }
310- },
311- "end": "(?<=\\})|(?=(;|\\(|\\)|>|\\[|\\]|=))",
312- "name": "meta.class-struct-block.cpp",
313- "patterns": [
314- {
315- "include": "#angle_brackets"
316- },
317- {
318- "begin": "\\{",
319- "beginCaptures": {
320- "0": {
321- "name": "punctuation.section.block.begin.cpp"
322- }
323- },
324- "end": "(\\})(\\s*\\n)?",
325- "endCaptures": {
326- "1": {
327- "name": "punctuation.section.block.end.cpp"
328- },
329- "2": {
330- "name": "invalid.illegal.you-forgot-semicolon.cpp"
331- }
332- },
333- "patterns": [
334- {
335- "include": "#special_block"
336- },
337- {
338- "include": "#constructor"
339- },
340- {
341- "include": "$base"
342- }
343- ]
344- },
345- {
346- "include": "$base"
347- }
348- ]
349- },
350- {
351- "begin": "\\b(extern)(?=\\s*\")",
352- "beginCaptures": {
353- "1": {
354- "name": "storage.modifier.cpp"
355- }
356- },
357- "end": "(?<=\\})|(?=\\w)|(?=\\s*#\\s*endif\\b)",
358- "name": "meta.extern-block.cpp",
359- "patterns": [
360- {
361- "begin": "\\{",
362- "beginCaptures": {
363- "0": {
364- "name": "punctuation.section.block.begin.c"
365- }
366- },
367- "end": "\\}|(?=\\s*#\\s*endif\\b)",
368- "endCaptures": {
369- "0": {
370- "name": "punctuation.section.block.end.c"
371- }
372- },
373- "patterns": [
374- {
375- "include": "#special_block"
376- },
377- {
378- "include": "$base"
379- }
380- ]
381- },
382- {
383- "include": "$base"
384- }
385- ]
386- }
387- ]
388- },
389- "strings": {
390- "patterns": [
391- {
392- "begin": "(u|u8|U|L)?\"",
393- "beginCaptures": {
394- "0": {
395- "name": "punctuation.definition.string.begin.cpp"
396- },
397- "1": {
398- "name": "meta.encoding.cpp"
399- }
400- },
401- "end": "\"",
402- "endCaptures": {
403- "0": {
404- "name": "punctuation.definition.string.end.cpp"
405- }
406- },
407- "name": "string.quoted.double.cpp",
408- "patterns": [
409- {
410- "match": "\\\\u\\h{4}|\\\\U\\h{8}",
411- "name": "constant.character.escape.cpp"
412- },
413- {
414- "match": "\\\\['\"?\\\\abfnrtv]",
415- "name": "constant.character.escape.cpp"
416- },
417- {
418- "match": "\\\\[0-7]{1,3}",
419- "name": "constant.character.escape.cpp"
420- },
421- {
422- "match": "\\\\x\\h+",
423- "name": "constant.character.escape.cpp"
424- }
425- ]
426- },
427- {
428- "begin": "(u|u8|U|L)?R\"(?:([^ ()\\\\\\t]{0,16})|([^ ()\\\\\\t]*))\\(",
429- "beginCaptures": {
430- "0": {
431- "name": "punctuation.definition.string.begin.cpp"
432- },
433- "1": {
434- "name": "meta.encoding.cpp"
435- },
436- "3": {
437- "name": "invalid.illegal.delimiter-too-long.cpp"
438- }
439- },
440- "end": "\\)\\2(\\3)\"",
441- "endCaptures": {
442- "0": {
443- "name": "punctuation.definition.string.end.cpp"
444- },
445- "1": {
446- "name": "invalid.illegal.delimiter-too-long.cpp"
447- }
448- },
449- "name": "string.quoted.double.raw.cpp"
450- }
451- ]
452- }
453- },
454- "version": "https://github.com/atom/language-c/commit/80db38512efabb3030d600a8d8f8b6d91abbc96b"
455-}
No newline at the end of the file
2+ "scopeName": "source.cpp",
3+ "fileTypes": [
4+ "cc",
5+ "cpp",
6+ "cp",
7+ "cxx",
8+ "c++",
9+ "cu",
10+ "cuh",
11+ "h",
12+ "hh",
13+ "hpp",
14+ "hxx",
15+ "h++",
16+ "inl",
17+ "ino",
18+ "ipp",
19+ "tcc",
20+ "tpp"
21+ ],
22+ "firstLineMatch": "(?i)-\\*-[^*]*(Mode:\\s*)?C\\+\\+(\\s*;.*?)?\\s*-\\*-",
23+ "name": "C++",
24+ "patterns": [
25+ {
26+ "include": "#special_block"
27+ },
28+ {
29+ "include": "#strings"
30+ },
31+ {
32+ "match": "\\b(friend|explicit|virtual|override|final|noexcept)\\b",
33+ "name": "storage.modifier.cpp"
34+ },
35+ {
36+ "match": "\\b(private:|protected:|public:)",
37+ "name": "storage.modifier.cpp"
38+ },
39+ {
40+ "match": "\\b(catch|operator|try|throw|using)\\b",
41+ "name": "keyword.control.cpp"
42+ },
43+ {
44+ "match": "\\bdelete\\b(\\s*\\[\\])?|\\bnew\\b(?!])",
45+ "name": "keyword.control.cpp"
46+ },
47+ {
48+ "match": "\\b(f|m)[A-Z]\\w*\\b",
49+ "name": "variable.other.readwrite.member.cpp"
50+ },
51+ {
52+ "match": "\\bthis\\b",
53+ "name": "variable.language.this.cpp"
54+ },
55+ {
56+ "match": "\\bnullptr\\b",
57+ "name": "variable.language.cpp"
58+ },
59+ {
60+ "match": "\\btemplate\\b\\s*",
61+ "name": "storage.type.template.cpp"
62+ },
63+ {
64+ "match": "\\b(const_cast|dynamic_cast|reinterpret_cast|static_cast)\\b\\s*",
65+ "name": "keyword.operator.cast.cpp"
66+ },
67+ {
68+ "match": "\\b(and|and_eq|bitand|bitor|compl|not|not_eq|or|or_eq|typeid|xor|xor_eq|alignof|alignas)\\b",
69+ "name": "keyword.operator.cpp"
70+ },
71+ {
72+ "match": "\\b(class|decltype|wchar_t|char16_t|char32_t)\\b",
73+ "name": "storage.type.cpp"
74+ },
75+ {
76+ "match": "\\b(constexpr|export|mutable|typename|thread_local)\\b",
77+ "name": "storage.modifier.cpp"
78+ },
79+ {
80+ "begin": "(?x)\n(?:\n ^ | # beginning of line\n (?:(?<!else|new|=)) # or word + space before name\n)\n((?:[A-Za-z_][A-Za-z0-9_]*::)*+~[A-Za-z_][A-Za-z0-9_]*) # actual name\n\\s*(\\() # opening bracket",
81+ "beginCaptures": {
82+ "1": {
83+ "name": "entity.name.function.cpp"
84+ },
85+ "2": {
86+ "name": "punctuation.definition.parameters.begin.c"
87+ }
88+ },
89+ "end": "\\)",
90+ "endCaptures": {
91+ "0": {
92+ "name": "punctuation.definition.parameters.end.c"
93+ }
94+ },
95+ "name": "meta.function.destructor.cpp",
96+ "patterns": [
97+ {
98+ "include": "$base"
99+ }
100+ ]
101+ },
102+ {
103+ "begin": "(?x)\n(?:\n ^ | # beginning of line\n (?:(?<!else|new|=)) # or word + space before name\n)\n((?:[A-Za-z_][A-Za-z0-9_]*::)*+~[A-Za-z_][A-Za-z0-9_]*) # actual name\n\\s*(\\() # opening bracket",
104+ "beginCaptures": {
105+ "1": {
106+ "name": "entity.name.function.cpp"
107+ },
108+ "2": {
109+ "name": "punctuation.definition.parameters.begin.c"
110+ }
111+ },
112+ "end": "\\)",
113+ "endCaptures": {
114+ "0": {
115+ "name": "punctuation.definition.parameters.end.c"
116+ }
117+ },
118+ "name": "meta.function.destructor.prototype.cpp",
119+ "patterns": [
120+ {
121+ "include": "$base"
122+ }
123+ ]
124+ },
125+ {
126+ "include": "source.c"
127+ }
128+ ],
129+ "repository": {
130+ "angle_brackets": {
131+ "begin": "<",
132+ "end": ">",
133+ "name": "meta.angle-brackets.cpp",
134+ "patterns": [
135+ {
136+ "include": "#angle_brackets"
137+ },
138+ {
139+ "include": "$base"
140+ }
141+ ]
142+ },
143+ "block": {
144+ "begin": "\\{",
145+ "beginCaptures": {
146+ "0": {
147+ "name": "punctuation.section.block.begin.c"
148+ }
149+ },
150+ "end": "\\}",
151+ "endCaptures": {
152+ "0": {
153+ "name": "punctuation.section.block.end.c"
154+ }
155+ },
156+ "name": "meta.block.cpp",
157+ "patterns": [
158+ {
159+ "captures": {
160+ "1": {
161+ "name": "support.function.any-method.c"
162+ },
163+ "2": {
164+ "name": "punctuation.definition.parameters.c"
165+ }
166+ },
167+ "match": "(?x)\n(\n (?!while|for|do|if|else|switch|catch|enumerate|return|r?iterate)\n (?:\\b[A-Za-z_][A-Za-z0-9_]*+\\b|::)*+ # actual name\n)\n\\s*(\\() # opening bracket",
168+ "name": "meta.function-call.c"
169+ },
170+ {
171+ "include": "$base"
172+ }
173+ ]
174+ },
175+ "constructor": {
176+ "patterns": [
177+ {
178+ "begin": "(?x)\n(?:^\\s*) # beginning of line\n((?!while|for|do|if|else|switch|catch|enumerate|r?iterate)[A-Za-z_][A-Za-z0-9_:]*) # actual name\n\\s*(\\() # opening bracket",
179+ "beginCaptures": {
180+ "1": {
181+ "name": "entity.name.function.cpp"
182+ },
183+ "2": {
184+ "name": "punctuation.definition.parameters.begin.c"
185+ }
186+ },
187+ "end": "\\)",
188+ "endCaptures": {
189+ "0": {
190+ "name": "punctuation.definition.parameters.end.c"
191+ }
192+ },
193+ "name": "meta.function.constructor.cpp",
194+ "patterns": [
195+ {
196+ "include": "$base"
197+ }
198+ ]
199+ },
200+ {
201+ "begin": "(?x)\n(:)\n(\n (?=\n \\s*[A-Za-z_][A-Za-z0-9_:]* # actual name\n \\s* (\\() # opening bracket\n )\n)",
202+ "beginCaptures": {
203+ "1": {
204+ "name": "punctuation.definition.parameters.c"
205+ }
206+ },
207+ "end": "(?=\\{)",
208+ "name": "meta.function.constructor.initializer-list.cpp",
209+ "patterns": [
210+ {
211+ "include": "$base"
212+ }
213+ ]
214+ }
215+ ]
216+ },
217+ "special_block": {
218+ "patterns": [
219+ {
220+ "begin": "\\b(using)\\b\\s*(namespace)\\b\\s*((?:[_A-Za-z][_A-Za-z0-9]*\\b(::)?)*)",
221+ "beginCaptures": {
222+ "1": {
223+ "name": "keyword.control.cpp"
224+ },
225+ "2": {
226+ "name": "storage.type.cpp"
227+ },
228+ "3": {
229+ "name": "entity.name.type.cpp"
230+ }
231+ },
232+ "end": "(;)",
233+ "name": "meta.using-namespace-declaration.cpp"
234+ },
235+ {
236+ "begin": "\\b(namespace)\\b\\s*([_A-Za-z][_A-Za-z0-9]*\\b)?+",
237+ "beginCaptures": {
238+ "1": {
239+ "name": "storage.type.cpp"
240+ },
241+ "2": {
242+ "name": "entity.name.type.cpp"
243+ }
244+ },
245+ "captures": {
246+ "1": {
247+ "name": "keyword.control.namespace.$2"
248+ }
249+ },
250+ "end": "(?<=\\})|(?=(;|,|\\(|\\)|>|\\[|\\]|=))",
251+ "name": "meta.namespace-block.cpp",
252+ "patterns": [
253+ {
254+ "begin": "\\{",
255+ "beginCaptures": {
256+ "0": {
257+ "name": "punctuation.definition.scope.cpp"
258+ }
259+ },
260+ "end": "\\}",
261+ "endCaptures": {
262+ "0": {
263+ "name": "punctuation.definition.scope.cpp"
264+ }
265+ },
266+ "patterns": [
267+ {
268+ "include": "#special_block"
269+ },
270+ {
271+ "include": "#constructor"
272+ },
273+ {
274+ "include": "$base"
275+ }
276+ ]
277+ },
278+ {
279+ "include": "$base"
280+ }
281+ ]
282+ },
283+ {
284+ "begin": "\\b(class|struct)\\b\\s*([_A-Za-z][_A-Za-z0-9]*\\b)?+(\\s*:\\s*(public|protected|private)\\s*([_A-Za-z][_A-Za-z0-9]*\\b)((\\s*,\\s*(public|protected|private)\\s*[_A-Za-z][_A-Za-z0-9]*\\b)*))?",
285+ "beginCaptures": {
286+ "1": {
287+ "name": "storage.type.cpp"
288+ },
289+ "2": {
290+ "name": "entity.name.type.cpp"
291+ },
292+ "4": {
293+ "name": "storage.type.modifier.cpp"
294+ },
295+ "5": {
296+ "name": "entity.name.type.inherited.cpp"
297+ },
298+ "6": {
299+ "patterns": [
300+ {
301+ "match": "(public|protected|private)",
302+ "name": "storage.type.modifier.cpp"
303+ },
304+ {
305+ "match": "[_A-Za-z][_A-Za-z0-9]*",
306+ "name": "entity.name.type.inherited.cpp"
307+ }
308+ ]
309+ }
310+ },
311+ "end": "(?<=\\})|(?=(;|\\(|\\)|>|\\[|\\]|=))",
312+ "name": "meta.class-struct-block.cpp",
313+ "patterns": [
314+ {
315+ "include": "#angle_brackets"
316+ },
317+ {
318+ "begin": "\\{",
319+ "beginCaptures": {
320+ "0": {
321+ "name": "punctuation.section.block.begin.cpp"
322+ }
323+ },
324+ "end": "(\\})(\\s*\\n)?",
325+ "endCaptures": {
326+ "1": {
327+ "name": "punctuation.section.block.end.cpp"
328+ },
329+ "2": {
330+ "name": "invalid.illegal.you-forgot-semicolon.cpp"
331+ }
332+ },
333+ "patterns": [
334+ {
335+ "include": "#special_block"
336+ },
337+ {
338+ "include": "#constructor"
339+ },
340+ {
341+ "include": "$base"
342+ }
343+ ]
344+ },
345+ {
346+ "include": "$base"
347+ }
348+ ]
349+ },
350+ {
351+ "begin": "\\b(extern)(?=\\s*\")",
352+ "beginCaptures": {
353+ "1": {
354+ "name": "storage.modifier.cpp"
355+ }
356+ },
357+ "end": "(?<=\\})|(?=\\w)|(?=\\s*#\\s*endif\\b)",
358+ "name": "meta.extern-block.cpp",
359+ "patterns": [
360+ {
361+ "begin": "\\{",
362+ "beginCaptures": {
363+ "0": {
364+ "name": "punctuation.section.block.begin.c"
365+ }
366+ },
367+ "end": "\\}|(?=\\s*#\\s*endif\\b)",
368+ "endCaptures": {
369+ "0": {
370+ "name": "punctuation.section.block.end.c"
371+ }
372+ },
373+ "patterns": [
374+ {
375+ "include": "#special_block"
376+ },
377+ {
378+ "include": "$base"
379+ }
380+ ]
381+ },
382+ {
383+ "include": "$base"
384+ }
385+ ]
386+ }
387+ ]
388+ },
389+ "strings": {
390+ "patterns": [
391+ {
392+ "begin": "(u|u8|U|L)?\"",
393+ "beginCaptures": {
394+ "0": {
395+ "name": "punctuation.definition.string.begin.cpp"
396+ },
397+ "1": {
398+ "name": "meta.encoding.cpp"
399+ }
400+ },
401+ "end": "\"",
402+ "endCaptures": {
403+ "0": {
404+ "name": "punctuation.definition.string.end.cpp"
405+ }
406+ },
407+ "name": "string.quoted.double.cpp",
408+ "patterns": [
409+ {
410+ "match": "\\\\u\\h{4}|\\\\U\\h{8}",
411+ "name": "constant.character.escape.cpp"
412+ },
413+ {
414+ "match": "\\\\['\"?\\\\abfnrtv]",
415+ "name": "constant.character.escape.cpp"
416+ },
417+ {
418+ "match": "\\\\[0-7]{1,3}",
419+ "name": "constant.character.escape.cpp"
420+ },
421+ {
422+ "match": "\\\\x\\h+",
423+ "name": "constant.character.escape.cpp"
424+ }
425+ ]
426+ },
427+ {
428+ "begin": "(u|u8|U|L)?R\"(?:([^ ()\\\\\\t]{0,16})|([^ ()\\\\\\t]*))\\(",
429+ "beginCaptures": {
430+ "0": {
431+ "name": "punctuation.definition.string.begin.cpp"
432+ },
433+ "1": {
434+ "name": "meta.encoding.cpp"
435+ },
436+ "3": {
437+ "name": "invalid.illegal.delimiter-too-long.cpp"
438+ }
439+ },
440+ "end": "\\)\\2(\\3)\"",
441+ "endCaptures": {
442+ "0": {
443+ "name": "punctuation.definition.string.end.cpp"
444+ },
445+ "1": {
446+ "name": "invalid.illegal.delimiter-too-long.cpp"
447+ }
448+ },
449+ "name": "string.quoted.double.raw.cpp"
450+ }
451+ ]
452+ }
453+ },
454+ "version": "https://github.com/atom/language-c/commit/80db38512efabb3030d600a8d8f8b6d91abbc96b"
455+}
modified extensions/vscode/textmate-syntaxes/c.json +976 −979
@@ -1,980 +1,977 @@
11 {
2- "scopeName": "source.c",
3- "fileTypes": [
4- "c",
5- "h.in"
6- ],
7- "firstLineMatch": "(?i)-\\*-[^*]*(Mode:\\s*)?C(\\s*;.*?)?\\s*-\\*-",
8- "name": "C",
9- "patterns": [
10- {
11- "include": "#preprocessor-rule-enabled"
12- },
13- {
14- "include": "#preprocessor-rule-disabled"
15- },
16- {
17- "include": "#preprocessor-rule-other"
18- },
19- {
20- "include": "#comments"
21- },
22- {
23- "match": "\\b(break|case|continue|default|do|else|for|goto|if|_Pragma|return|switch|while)\\b",
24- "name": "keyword.control.c"
25- },
26- {
27- "match": "\\b(asm|__asm__|auto|bool|_Bool|char|_Complex|double|enum|float|_Imaginary|int|long|short|signed|struct|typedef|union|unsigned|void)\\b",
28- "name": "storage.type.c"
29- },
30- {
31- "match": "\\b(const|extern|register|restrict|static|volatile|inline)\\b",
32- "name": "storage.modifier.c"
33- },
34- {
35- "match": "\\bk[A-Z]\\w*\\b",
36- "name": "constant.other.variable.mac-classic.c"
37- },
38- {
39- "match": "\\bg[A-Z]\\w*\\b",
40- "name": "variable.other.readwrite.global.mac-classic.c"
41- },
42- {
43- "match": "\\bs[A-Z]\\w*\\b",
44- "name": "variable.other.readwrite.static.mac-classic.c"
45- },
46- {
47- "match": "\\b(NULL|true|false|TRUE|FALSE)\\b",
48- "name": "constant.language.c"
49- },
50- {
51- "include": "#operators"
52- },
53- {
54- "include": "#numbers"
55- },
56- {
57- "include": "#strings"
58- },
59- {
60- "begin": "(?x)\n^\\s* ((\\#)\\s*define) \\s+ # define\n((?<id>[a-zA-Z_$][\\w$]*)) # macro name\n(?:\n (\\()\n (\n \\s* \\g<id> \\s* # first argument\n ((,) \\s* \\g<id> \\s*)* # additional arguments\n (?:\\.\\.\\.)? # varargs ellipsis?\n )\n (\\))\n)?",
61- "beginCaptures": {
62- "1": {
63- "name": "keyword.control.directive.define.c"
64- },
65- "2": {
66- "name": "punctuation.definition.directive.c"
67- },
68- "3": {
69- "name": "entity.name.function.preprocessor.c"
70- },
71- "5": {
72- "name": "punctuation.definition.parameters.begin.c"
73- },
74- "6": {
75- "name": "variable.parameter.preprocessor.c"
76- },
77- "8": {
78- "name": "punctuation.separator.parameters.c"
79- },
80- "9": {
81- "name": "punctuation.definition.parameters.end.c"
82- }
83- },
84- "end": "(?=(?://|/\\*))|(?<!\\\\)(?=\\n)",
85- "name": "meta.preprocessor.macro.c",
86- "patterns": [
87- {
88- "include": "$base"
89- }
90- ]
91- },
92- {
93- "begin": "^\\s*((#)\\s*(error|warning))\\b",
94- "captures": {
95- "1": {
96- "name": "keyword.control.directive.diagnostic.$3.c"
97- },
98- "2": {
99- "name": "punctuation.definition.directive.c"
100- }
101- },
102- "end": "(?<!\\\\)(?=\\n)",
103- "name": "meta.preprocessor.diagnostic.c",
104- "patterns": [
105- {
106- "include": "#line_continuation_character"
107- }
108- ]
109- },
110- {
111- "begin": "^\\s*((#)\\s*(include|import))\\b\\s*",
112- "beginCaptures": {
113- "1": {
114- "name": "keyword.control.directive.$3.c"
115- },
116- "2": {
117- "name": "punctuation.definition.directive.c"
118- }
119- },
120- "end": "(?=(?://|/\\*))|(?<!\\\\)(?=\\n)",
121- "name": "meta.preprocessor.include.c",
122- "patterns": [
123- {
124- "include": "#line_continuation_character"
125- },
126- {
127- "begin": "\"",
128- "beginCaptures": {
129- "0": {
130- "name": "punctuation.definition.string.begin.c"
131- }
132- },
133- "end": "\"",
134- "endCaptures": {
135- "0": {
136- "name": "punctuation.definition.string.end.c"
137- }
138- },
139- "name": "string.quoted.double.include.c"
140- },
141- {
142- "begin": "<",
143- "beginCaptures": {
144- "0": {
145- "name": "punctuation.definition.string.begin.c"
146- }
147- },
148- "end": ">",
149- "endCaptures": {
150- "0": {
151- "name": "punctuation.definition.string.end.c"
152- }
153- },
154- "name": "string.quoted.other.lt-gt.include.c"
155- }
156- ]
157- },
158- {
159- "include": "#pragma-mark"
160- },
161- {
162- "begin": "^\\s*((#)\\s*line)\\b",
163- "beginCaptures": {
164- "1": {
165- "name": "keyword.control.directive.line.c"
166- },
167- "2": {
168- "name": "punctuation.definition.directive.c"
169- }
170- },
171- "end": "(?=(?://|/\\*))|(?<!\\\\)(?=\\n)",
172- "name": "meta.preprocessor.c",
173- "patterns": [
174- {
175- "include": "#strings"
176- },
177- {
178- "include": "#numbers"
179- },
180- {
181- "include": "#line_continuation_character"
182- }
183- ]
184- },
185- {
186- "begin": "^\\s*(?:((#)\\s*(?:elif|else|if|ifdef|ifndef))|((#)\\s*(pragma|undef)))\\b",
187- "beginCaptures": {
188- "1": {
189- "name": "keyword.control.directive.conditional.c"
190- },
191- "2": {
192- "name": "punctuation.definition.directive.c"
193- },
194- "3": {
195- "name": "keyword.control.directive.$5.c"
196- },
197- "4": {
198- "name": "punctuation.definition.directive.c"
199- }
200- },
201- "end": "(?=(?://|/\\*))|(?<!\\\\)(?=\\n)",
202- "name": "meta.preprocessor.c",
203- "patterns": [
204- {
205- "include": "#line_continuation_character"
206- }
207- ]
208- },
209- {
210- "match": "\\b(u_char|u_short|u_int|u_long|ushort|uint|u_quad_t|quad_t|qaddr_t|caddr_t|daddr_t|dev_t|fixpt_t|blkcnt_t|blksize_t|gid_t|in_addr_t|in_port_t|ino_t|key_t|mode_t|nlink_t|id_t|pid_t|off_t|segsz_t|swblk_t|uid_t|id_t|clock_t|size_t|ssize_t|time_t|useconds_t|suseconds_t)\\b",
211- "name": "support.type.sys-types.c"
212- },
213- {
214- "match": "\\b(pthread_attr_t|pthread_cond_t|pthread_condattr_t|pthread_mutex_t|pthread_mutexattr_t|pthread_once_t|pthread_rwlock_t|pthread_rwlockattr_t|pthread_t|pthread_key_t)\\b",
215- "name": "support.type.pthread.c"
216- },
217- {
218- "match": "(?x) \\b\n(int8_t|int16_t|int32_t|int64_t|uint8_t|uint16_t|uint32_t|uint64_t|int_least8_t\n|int_least16_t|int_least32_t|int_least64_t|uint_least8_t|uint_least16_t|uint_least32_t\n|uint_least64_t|int_fast8_t|int_fast16_t|int_fast32_t|int_fast64_t|uint_fast8_t\n|uint_fast16_t|uint_fast32_t|uint_fast64_t|intptr_t|uintptr_t|intmax_t|intmax_t\n|uintmax_t|uintmax_t)\n\\b",
219- "name": "support.type.stdint.c"
220- },
221- {
222- "match": "\\b(noErr|kNilOptions|kInvalidID|kVariableLengthArray)\\b",
223- "name": "support.constant.mac-classic.c"
224- },
225- {
226- "match": "(?x) \\b\n(AbsoluteTime|Boolean|Byte|ByteCount|ByteOffset|BytePtr|CompTimeValue|ConstLogicalAddress|ConstStrFileNameParam\n|ConstStringPtr|Duration|Fixed|FixedPtr|Float32|Float32Point|Float64|Float80|Float96|FourCharCode|Fract|FractPtr\n|Handle|ItemCount|LogicalAddress|OptionBits|OSErr|OSStatus|OSType|OSTypePtr|PhysicalAddress|ProcessSerialNumber\n|ProcessSerialNumberPtr|ProcHandle|Ptr|ResType|ResTypePtr|ShortFixed|ShortFixedPtr|SignedByte|SInt16|SInt32|SInt64\n|SInt8|Size|StrFileName|StringHandle|StringPtr|TimeBase|TimeRecord|TimeScale|TimeValue|TimeValue64|UInt16|UInt32\n|UInt64|UInt8|UniChar|UniCharCount|UniCharCountPtr|UniCharPtr|UnicodeScalarValue|UniversalProcHandle|UniversalProcPtr\n|UnsignedFixed|UnsignedFixedPtr|UnsignedWide|UTF16Char|UTF32Char|UTF8Char)\n\\b",
227- "name": "support.type.mac-classic.c"
228- },
229- {
230- "match": "\\b([A-Za-z0-9_]+_t)\\b",
231- "name": "support.type.posix-reserved.c"
232- },
233- {
234- "include": "#block"
235- },
236- {
237- "begin": "(?x)\n(?:\n ^ |\n (?:\n (?=\\s)(?<!else|new|return)(?<=\\w) # word + space before name\n |\n (?=\\s*[A-Za-z_])(?<!&&)(?<=[*&>]) # type modifier before name\n )\n)\n(\\s*)(?!(while|for|do|if|else|switch|catch|enumerate|return|sizeof|[cr]?iterate)\\s*\\()\n(\n (?:[A-Za-z_][A-Za-z0-9_]*+|::)++ # actual name\n |\n (?:(?<=operator)(?:[-*&<>=+!]+|\\(\\)|\\[\\]))\n)\n\\s*(?=\\()",
238- "beginCaptures": {
239- "1": {
240- "name": "punctuation.whitespace.function.leading.c"
241- },
242- "3": {
243- "name": "entity.name.function.c"
244- },
245- "4": {
246- "name": "punctuation.definition.parameters.c"
247- }
248- },
249- "end": "(?<=\\})|(?=#)|(;)",
250- "name": "meta.function.c",
251- "patterns": [
252- {
253- "include": "#comments"
254- },
255- {
256- "include": "#parens"
257- },
258- {
259- "match": "\\b(const)\\b",
260- "name": "storage.modifier.c"
261- },
262- {
263- "include": "#block"
264- }
265- ]
266- },
267- {
268- "include": "#line_continuation_character"
269- }
270- ],
271- "repository": {
272- "access": {
273- "captures": {
274- "2": {
275- "name": "punctuation.separator.dot-access.c"
276- },
277- "3": {
278- "name": "punctuation.separator.pointer-access.c"
279- },
280- "4": {
281- "name": "variable.other.member.c"
282- }
283- },
284- "match": "((\\.)|(->))([a-zA-Z_][a-zA-Z_0-9]*)\\b(?!\\s*\\()"
285- },
286- "block": {
287- "patterns": [
288- {
289- "begin": "\\{",
290- "beginCaptures": {
291- "0": {
292- "name": "punctuation.section.block.begin.c"
293- }
294- },
295- "end": "\\}|(?=\\s*#\\s*endif\\b)",
296- "endCaptures": {
297- "0": {
298- "name": "punctuation.section.block.end.c"
299- }
300- },
301- "name": "meta.block.c",
302- "patterns": [
303- {
304- "include": "#block_innards"
305- }
306- ]
307- }
308- ]
309- },
310- "block_innards": {
311- "patterns": [
312- {
313- "include": "#preprocessor-rule-enabled-block"
314- },
315- {
316- "include": "#preprocessor-rule-disabled-block"
317- },
318- {
319- "include": "#preprocessor-rule-other-block"
320- },
321- {
322- "include": "#sizeof"
323- },
324- {
325- "include": "#access"
326- },
327- {
328- "include": "#libc"
329- },
330- {
331- "include": "#c_function_call"
332- },
333- {
334- "captures": {
335- "1": {
336- "name": "variable.other.c"
337- },
338- "2": {
339- "name": "punctuation.definition.parameters.c"
340- }
341- },
342- "match": "(?x)\n(?:\n (?:\n (?=\\s)(?<!else|new|return)\n (?<=\\w) \\s+ # or word + space before name\n )\n)\n(\n (?:[A-Za-z_][A-Za-z0-9_]*+ | :: )++ # actual name\n |\n (?:(?<=operator) (?:[-*&<>=+!]+ | \\(\\) | \\[\\]))\n)\n\\s*(\\() # opening bracket",
343- "name": "meta.initialization.c"
344- },
345- {
346- "include": "#block"
347- },
348- {
349- "include": "$base"
350- }
351- ]
352- },
353- "c_function_call": {
354- "captures": {
355- "1": {
356- "name": "punctuation.whitespace.function-call.leading.c"
357- },
358- "2": {
359- "name": "support.function.any-method.c"
360- },
361- "4": {
362- "name": "punctuation.definition.parameters.c"
363- }
364- },
365- "match": "(?x)\n(?:\n (?=\\s)\n (?:(?<=else|new|return) | (?<!\\w)) (\\s+)\n)?\n\n# Actual name\n(\n \\b\n (?!\n (while|for|do|if|else|switch|catch|enumerate|return|sizeof|r?iterate)\n \\s* \\(\n )\n (?:(?!NS)[A-Za-z_][A-Za-z0-9_]*+\\b | ::)++\n)\n\\s*(\\() # Opening bracket",
366- "name": "meta.function-call.c"
367- },
368- "comments": {
369- "patterns": [
370- {
371- "captures": {
372- "1": {
373- "name": "meta.toc-list.banner.block.c"
374- }
375- },
376- "match": "^/\\* =(\\s*.*?)\\s*= \\*/$\\n?",
377- "name": "comment.block.c"
378- },
379- {
380- "begin": "/\\*",
381- "beginCaptures": {
382- "0": {
383- "name": "punctuation.definition.comment.begin.c"
384- }
385- },
386- "end": "\\*/",
387- "endCaptures": {
388- "0": {
389- "name": "punctuation.definition.comment.end.c"
390- }
391- },
392- "name": "comment.block.c"
393- },
394- {
395- "match": "\\*/.*\\n",
396- "name": "invalid.illegal.stray-comment-end.c"
397- },
398- {
399- "captures": {
400- "1": {
401- "name": "meta.toc-list.banner.line.c"
402- }
403- },
404- "match": "^// =(\\s*.*?)\\s*=\\s*$\\n?",
405- "name": "comment.line.banner.cpp"
406- },
407- {
408- "begin": "(^[ \\t]+)?(?=//)",
409- "beginCaptures": {
410- "1": {
411- "name": "punctuation.whitespace.comment.leading.cpp"
412- }
413- },
414- "end": "(?!\\G)",
415- "patterns": [
416- {
417- "begin": "//",
418- "beginCaptures": {
419- "0": {
420- "name": "punctuation.definition.comment.cpp"
421- }
422- },
423- "end": "\\n",
424- "name": "comment.line.double-slash.cpp",
425- "patterns": [
426- {
427- "include": "#line_continuation_character"
428- }
429- ]
430- }
431- ]
432- }
433- ]
434- },
435- "disabled": {
436- "begin": "^\\s*#\\s*if(n?def)?\\b.*$",
437- "end": "^\\s*#\\s*endif\\b",
438- "patterns": [
439- {
440- "include": "#disabled"
441- },
442- {
443- "include": "#pragma-mark"
444- }
445- ]
446- },
447- "libc": {
448- "captures": {
449- "1": {
450- "name": "punctuation.whitespace.support.function.leading.c"
451- },
452- "2": {
453- "name": "support.function.C99.c"
454- }
455- },
456- "match": "(?x) (\\s*) \\b\n(_Exit|(?:nearbyint|nextafter|nexttoward|netoward|nan)[fl]?|a(?:cos|sin)h?[fl]?|abort|abs|asctime|assert\n|atan(?:[h2]?[fl]?)?|atexit|ato[ifl]|atoll|bsearch|btowc|cabs[fl]?|cacos|cacos[fl]|cacosh[fl]?\n|calloc|carg[fl]?|casinh?[fl]?|catanh?[fl]?|cbrt[fl]?|ccosh?[fl]?|ceil[fl]?|cexp[fl]?|cimag[fl]?\n|clearerr|clock|clog[fl]?|conj[fl]?|copysign[fl]?|cosh?[fl]?|cpow[fl]?|cproj[fl]?|creal[fl]?\n|csinh?[fl]?|csqrt[fl]?|ctanh?[fl]?|ctime|difftime|div|erfc?[fl]?|exit|fabs[fl]?\n|exp(?:2[fl]?|[fl]|m1[fl]?)?|fclose|fdim[fl]?|fe[gs]et(?:env|exceptflag|round)|feclearexcept\n|feholdexcept|feof|feraiseexcept|ferror|fetestexcept|feupdateenv|fflush|fgetpos|fgetw?[sc]\n|floor[fl]?|fmax?[fl]?|fmin[fl]?|fmod[fl]?|fopen|fpclassify|fprintf|fputw?[sc]|fread|free|freopen\n|frexp[fl]?|fscanf|fseek|fsetpos|ftell|fwide|fwprintf|fwrite|fwscanf|genv|get[sc]|getchar|gmtime\n|gwc|gwchar|hypot[fl]?|ilogb[fl]?|imaxabs|imaxdiv|isalnum|isalpha|isblank|iscntrl|isdigit|isfinite\n|isgraph|isgreater|isgreaterequal|isinf|isless(?:equal|greater)?|isw?lower|isnan|isnormal|isw?print\n|isw?punct|isw?space|isunordered|isw?upper|iswalnum|iswalpha|iswblank|iswcntrl|iswctype|iswdigit|iswgraph\n|isw?xdigit|labs|ldexp[fl]?|ldiv|lgamma[fl]?|llabs|lldiv|llrint[fl]?|llround[fl]?|localeconv|localtime\n|log[2b]?[fl]?|log1[p0][fl]?|longjmp|lrint[fl]?|lround[fl]?|malloc|mbr?len|mbr?towc|mbsinit|mbsrtowcs\n|mbstowcs|memchr|memcmp|memcpy|memmove|memset|mktime|modf[fl]?|perror|pow[fl]?|printf|puts|putw?c(?:har)?\n|qsort|raise|rand|remainder[fl]?|realloc|remove|remquo[fl]?|rename|rewind|rint[fl]?|round[fl]?|scalbl?n[fl]?\n|scanf|setbuf|setjmp|setlocale|setvbuf|signal|signbit|sinh?[fl]?|snprintf|sprintf|sqrt[fl]?|srand|sscanf\n|strcat|strchr|strcmp|strcoll|strcpy|strcspn|strerror|strftime|strlen|strncat|strncmp|strncpy|strpbrk\n|strrchr|strspn|strstr|strto[kdf]|strtoimax|strtol[dl]?|strtoull?|strtoumax|strxfrm|swprintf|swscanf\n|system|tan|tan[fl]|tanh[fl]?|tgamma[fl]?|time|tmpfile|tmpnam|tolower|toupper|trunc[fl]?|ungetw?c|va_arg\n|va_copy|va_end|va_start|vfw?printf|vfw?scanf|vprintf|vscanf|vsnprintf|vsprintf|vsscanf|vswprintf|vswscanf\n|vwprintf|vwscanf|wcrtomb|wcscat|wcschr|wcscmp|wcscoll|wcscpy|wcscspn|wcsftime|wcslen|wcsncat|wcsncmp|wcsncpy\n|wcspbrk|wcsrchr|wcsrtombs|wcsspn|wcsstr|wcsto[dkf]|wcstoimax|wcstol[dl]?|wcstombs|wcstoull?|wcstoumax|wcsxfrm\n|wctom?b|wmem(?:set|chr|cpy|cmp|move)|wprintf|wscanf)\\b"
457- },
458- "line_continuation_character": {
459- "patterns": [
460- {
461- "match": "(\\\\)\\s*\\n",
462- "captures": {
463- "1": {
464- "name": "constant.character.escape.line-continuation.c"
465- }
466- }
467- }
468- ]
469- },
470- "numbers": {
471- "patterns": [
472- {
473- "match": "\\b((0(x|X)[0-9a-fA-F]*)|(0(b|B)[01]*)|(([0-9]+\\.?[0-9]*)|(\\.[0-9]+))((e|E)(\\+|-)?[0-9]+)?)(L|l|UL|ul|u|U|F|f|ll|LL|ull|ULL)?\\b",
474- "name": "constant.numeric.c"
475- }
476- ]
477- },
478- "parens": {
479- "begin": "\\(",
480- "beginCaptures": {
481- "0": {
482- "name": "punctuation.section.parens.begin.c"
483- }
484- },
485- "end": "\\)",
486- "endCaptures": {
487- "0": {
488- "name": "punctuation.section.parens.end.c"
489- }
490- },
491- "name": "meta.parens.c",
492- "patterns": [
493- {
494- "include": "$base"
495- }
496- ]
497- },
498- "pragma-mark": {
499- "captures": {
500- "1": {
501- "name": "meta.preprocessor.c"
502- },
503- "2": {
504- "name": "keyword.control.directive.pragma.pragma-mark.c"
505- },
506- "3": {
507- "name": "punctuation.definition.directive.c"
508- },
509- "4": {
510- "name": "meta.toc-list.pragma-mark.c"
511- }
512- },
513- "match": "^\\s*(((#)\\s*pragma\\s+mark)\\s+(.*))",
514- "name": "meta.section"
515- },
516- "preprocessor-rule-disabled": {
517- "begin": "^\\s*(((#)if)\\s+(0)\\b).*",
518- "beginCaptures": {
519- "1": {
520- "name": "meta.preprocessor.c"
521- },
522- "2": {
523- "name": "keyword.control.directive.conditional.c"
524- },
525- "3": {
526- "name": "punctuation.definition.directive.c"
527- },
528- "4": {
529- "name": "constant.numeric.preprocessor.c"
530- }
531- },
532- "end": "^\\s*(((#)\\s*endif)\\b)",
533- "endCaptures": {
534- "1": {
535- "name": "meta.preprocessor.c"
536- },
537- "2": {
538- "name": "keyword.control.directive.conditional.c"
539- },
540- "3": {
541- "name": "punctuation.definition.directive.c"
542- }
543- },
544- "patterns": [
545- {
546- "begin": "^\\s*(((#)\\s*else)\\b)",
547- "beginCaptures": {
548- "1": {
549- "name": "meta.preprocessor.c"
550- },
551- "2": {
552- "name": "keyword.control.directive.conditional.c"
553- },
554- "3": {
555- "name": "punctuation.definition.directive.c"
556- }
557- },
558- "end": "(?=^\\s*#\\s*endif\\b)",
559- "patterns": [
560- {
561- "include": "$base"
562- }
563- ]
564- },
565- {
566- "begin": "\\G",
567- "end": "(?=^\\s*#\\s*(else|endif)\\b)",
568- "contentName": "comment.block.preprocessor.if-branch",
569- "patterns": [
570- {
571- "include": "#disabled"
572- },
573- {
574- "include": "#pragma-mark"
575- }
576- ]
577- }
578- ]
579- },
580- "preprocessor-rule-disabled-block": {
581- "begin": "^\\s*(((#)if)\\s+(0)\\b).*",
582- "beginCaptures": {
583- "1": {
584- "name": "meta.preprocessor.c"
585- },
586- "2": {
587- "name": "keyword.control.directive.conditional.c"
588- },
589- "3": {
590- "name": "punctuation.definition.directive.c"
591- },
592- "4": {
593- "name": "constant.numeric.preprocessor.c"
594- }
595- },
596- "end": "^\\s*(((#)\\s*endif)\\b)",
597- "endCaptures": {
598- "1": {
599- "name": "meta.preprocessor.c"
600- },
601- "2": {
602- "name": "keyword.control.directive.conditional.c"
603- },
604- "3": {
605- "name": "punctuation.definition.directive.c"
606- }
607- },
608- "patterns": [
609- {
610- "begin": "^\\s*(((#)\\s*else\\b))",
611- "beginCaptures": {
612- "1": {
613- "name": "meta.preprocessor.c"
614- },
615- "2": {
616- "name": "keyword.control.directive.conditional.c"
617- },
618- "3": {
619- "name": "punctuation.definition.directive.c"
620- }
621- },
622- "end": "(?=^\\s*#\\s*endif\\b)",
623- "patterns": [
624- {
625- "include": "#block_innards"
626- }
627- ]
628- },
629- {
630- "begin": "\\G",
631- "end": "(?=^\\s*#\\s*(else|endif)\\b)",
632- "contentName": "comment.block.preprocessor.if-branch.in-block",
633- "patterns": [
634- {
635- "include": "#disabled"
636- },
637- {
638- "include": "#pragma-mark"
639- }
640- ]
641- }
642- ]
643- },
644- "preprocessor-rule-enabled": {
645- "begin": "^\\s*(((#)if)\\s+(0*1)\\b)",
646- "beginCaptures": {
647- "1": {
648- "name": "meta.preprocessor.c"
649- },
650- "2": {
651- "name": "keyword.control.directive.conditional.c"
652- },
653- "3": {
654- "name": "punctuation.definition.directive.c"
655- },
656- "4": {
657- "name": "constant.numeric.preprocessor.c"
658- }
659- },
660- "end": "^\\s*(((#)\\s*endif)\\b)",
661- "endCaptures": {
662- "1": {
663- "name": "meta.preprocessor.c"
664- },
665- "2": {
666- "name": "keyword.control.directive.conditional.c"
667- },
668- "3": {
669- "name": "punctuation.definition.directive.c"
670- }
671- },
672- "patterns": [
673- {
674- "begin": "^\\s*(((#)\\s*else)\\b).*",
675- "beginCaptures": {
676- "1": {
677- "name": "meta.preprocessor.c"
678- },
679- "2": {
680- "name": "keyword.control.directive.conditional.c"
681- },
682- "3": {
683- "name": "punctuation.definition.directive.c"
684- }
685- },
686- "contentName": "comment.block.preprocessor.else-branch",
687- "end": "(?=^\\s*#\\s*endif\\b)",
688- "patterns": [
689- {
690- "include": "#disabled"
691- },
692- {
693- "include": "#pragma-mark"
694- }
695- ]
696- },
697- {
698- "begin": "\\G",
699- "end": "(?=^\\s*#\\s*(else|endif)\\b)",
700- "patterns": [
701- {
702- "include": "$base"
703- }
704- ]
705- }
706- ]
707- },
708- "preprocessor-rule-enabled-block": {
709- "begin": "^\\s*(((#)if)\\s+(0*1)\\b)",
710- "beginCaptures": {
711- "1": {
712- "name": "meta.preprocessor.c"
713- },
714- "2": {
715- "name": "keyword.control.directive.conditional.c"
716- },
717- "3": {
718- "name": "punctuation.definition.directive.c"
719- },
720- "4": {
721- "name": "constant.numeric.preprocessor.c"
722- }
723- },
724- "end": "^\\s*(((#)\\s*endif)\\b)",
725- "endCaptures": {
726- "1": {
727- "name": "meta.preprocessor.c"
728- },
729- "2": {
730- "name": "keyword.control.directive.conditional.c"
731- },
732- "3": {
733- "name": "punctuation.definition.directive.c"
734- }
735- },
736- "patterns": [
737- {
738- "begin": "^\\s*(((#)\\s*else)\\b).*",
739- "beginCaptures": {
740- "1": {
741- "name": "meta.preprocessor.c"
742- },
743- "2": {
744- "name": "keyword.control.directive.conditional.c"
745- },
746- "3": {
747- "name": "punctuation.definition.directive.c"
748- }
749- },
750- "contentName": "comment.block.preprocessor.else-branch.in-block",
751- "end": "(?=^\\s*#\\s*endif\\b)",
752- "patterns": [
753- {
754- "include": "#disabled"
755- },
756- {
757- "include": "#pragma-mark"
758- }
759- ]
760- },
761- {
762- "begin": "\\G",
763- "end": "(?=^\\s*#\\s*(else|endif)\\b)",
764- "patterns": [
765- {
766- "include": "#block_innards"
767- }
768- ]
769- }
770- ]
771- },
772- "preprocessor-rule-other": {
773- "begin": "^\\s*(((#)\\s*if(n?def)?)\\b.*?(?:(?=(?://|/\\*))|$))",
774- "beginCaptures": {
775- "1": {
776- "name": "meta.preprocessor.c"
777- },
778- "2": {
779- "name": "keyword.control.directive.conditional.c"
780- },
781- "3": {
782- "name": "punctuation.definition.directive.c"
783- }
784- },
785- "end": "^\\s*(((#)\\s*(endif))\\b)",
786- "endCaptures": {
787- "1": {
788- "name": "meta.preprocessor.c"
789- },
790- "2": {
791- "name": "keyword.control.directive.conditional.c"
792- },
793- "3": {
794- "name": "punctuation.definition.directive.c"
795- }
796- },
797- "patterns": [
798- {
799- "include": "$base"
800- }
801- ]
802- },
803- "preprocessor-rule-other-block": {
804- "begin": "^\\s*(((#)\\s*if(n?def)?)\\b.*?(?:(?=(?://|/\\*))|$))",
805- "beginCaptures": {
806- "1": {
807- "name": "meta.preprocessor.c"
808- },
809- "2": {
810- "name": "keyword.control.directive.conditional.c"
811- },
812- "3": {
813- "name": "punctuation.definition.directive.c"
814- }
815- },
816- "end": "^\\s*(((#)\\s*endif)\\b)",
817- "endCaptures": {
818- "1": {
819- "name": "meta.preprocessor.c"
820- },
821- "2": {
822- "name": "keyword.control.directive.conditional.c"
823- },
824- "3": {
825- "name": "punctuation.definition.directive.c"
826- }
827- },
828- "patterns": [
829- {
830- "include": "#block_innards"
831- }
832- ]
833- },
834- "operators": {
835- "patterns": [
836- {
837- "match": "(?<![\\w$])(sizeof)(?![\\w$])",
838- "name": "keyword.operator.sizeof.c"
839- },
840- {
841- "match": "--",
842- "name": "keyword.operator.decrement.c"
843- },
844- {
845- "match": "\\+\\+",
846- "name": "keyword.operator.increment.c"
847- },
848- {
849- "match": "%=|\\+=|-=|\\*=|(?<!\\()/=",
850- "name": "keyword.operator.assignment.compound.c"
851- },
852- {
853- "match": "&=|\\^=|<<=|>>=|\\|=",
854- "name": "keyword.operator.assignment.compound.bitwise.c"
855- },
856- {
857- "match": "<<|>>",
858- "name": "keyword.operator.bitwise.shift.c"
859- },
860- {
861- "match": "!=|<=|>=|==|<|>",
862- "name": "keyword.operator.comparison.c"
863- },
864- {
865- "match": "&&|!|\\|\\|",
866- "name": "keyword.operator.logical.c"
867- },
868- {
869- "match": "&|\\||\\^|~",
870- "name": "keyword.operator.c"
871- },
872- {
873- "match": "=",
874- "name": "keyword.operator.assignment.c"
875- },
876- {
877- "match": "%|\\*|/|-|\\+",
878- "name": "keyword.operator.c"
879- },
880- {
881- "begin": "\\?",
882- "beginCaptures": {
883- "0": {
884- "name": "keyword.operator.ternary.c"
885- }
886- },
887- "end": ":",
888- "endCaptures": {
889- "0": {
890- "name": "keyword.operator.ternary.c"
891- }
892- },
893- "patterns": [
894- {
895- "include": "$self"
896- }
897- ]
898- }
899- ]
900- },
901- "strings": {
902- "patterns": [
903- {
904- "begin": "\"",
905- "beginCaptures": {
906- "0": {
907- "name": "punctuation.definition.string.begin.c"
908- }
909- },
910- "end": "\"",
911- "endCaptures": {
912- "0": {
913- "name": "punctuation.definition.string.end.c"
914- }
915- },
916- "name": "string.quoted.double.c",
917- "patterns": [
918- {
919- "include": "#string_escaped_char"
920- },
921- {
922- "include": "#string_placeholder"
923- },
924- {
925- "include": "#line_continuation_character"
926- }
927- ]
928- },
929- {
930- "begin": "'",
931- "beginCaptures": {
932- "0": {
933- "name": "punctuation.definition.string.begin.c"
934- }
935- },
936- "end": "'",
937- "endCaptures": {
938- "0": {
939- "name": "punctuation.definition.string.end.c"
940- }
941- },
942- "name": "string.quoted.single.c",
943- "patterns": [
944- {
945- "include": "#string_escaped_char"
946- },
947- {
948- "include": "#line_continuation_character"
949- }
950- ]
951- }
952- ]
953- },
954- "string_escaped_char": {
955- "patterns": [
956- {
957- "match": "(?x)\\\\ (\n\\\\ |\n[abefnprtv'\"?] |\n[0-3]\\d{,2} |\n[4-7]\\d? |\nx[a-fA-F0-9]{,2} |\nu[a-fA-F0-9]{,4} |\nU[a-fA-F0-9]{,8} )",
958- "name": "constant.character.escape.c"
959- },
960- {
961- "match": "\\\\.",
962- "name": "invalid.illegal.unknown-escape.c"
963- }
964- ]
965- },
966- "string_placeholder": {
967- "patterns": [
968- {
969- "match": "(?x) %\n(\\d+\\$)? # field (argument #)\n[#0\\- +']* # flags\n[,;:_]? # separator character (AltiVec)\n((-?\\d+)|\\*(-?\\d+\\$)?)? # minimum field width\n(\\.((-?\\d+)|\\*(-?\\d+\\$)?)?)? # precision\n(hh|h|ll|l|j|t|z|q|L|vh|vl|v|hv|hl)? # length modifier\n[diouxXDOUeEfFgGaACcSspn%] # conversion type",
970- "name": "constant.other.placeholder.c"
971- },
972- {
973- "match": "%",
974- "name": "invalid.illegal.placeholder.c"
975- }
976- ]
977- }
978- },
979- "version": "https://github.com/atom/language-c/commit/2a5fafe1d86f690b5ab2c877cea2fc6a598e001a"
980-}
No newline at the end of the file
2+ "scopeName": "source.c",
3+ "fileTypes": ["c", "h.in"],
4+ "firstLineMatch": "(?i)-\\*-[^*]*(Mode:\\s*)?C(\\s*;.*?)?\\s*-\\*-",
5+ "name": "C",
6+ "patterns": [
7+ {
8+ "include": "#preprocessor-rule-enabled"
9+ },
10+ {
11+ "include": "#preprocessor-rule-disabled"
12+ },
13+ {
14+ "include": "#preprocessor-rule-other"
15+ },
16+ {
17+ "include": "#comments"
18+ },
19+ {
20+ "match": "\\b(break|case|continue|default|do|else|for|goto|if|_Pragma|return|switch|while)\\b",
21+ "name": "keyword.control.c"
22+ },
23+ {
24+ "match": "\\b(asm|__asm__|auto|bool|_Bool|char|_Complex|double|enum|float|_Imaginary|int|long|short|signed|struct|typedef|union|unsigned|void)\\b",
25+ "name": "storage.type.c"
26+ },
27+ {
28+ "match": "\\b(const|extern|register|restrict|static|volatile|inline)\\b",
29+ "name": "storage.modifier.c"
30+ },
31+ {
32+ "match": "\\bk[A-Z]\\w*\\b",
33+ "name": "constant.other.variable.mac-classic.c"
34+ },
35+ {
36+ "match": "\\bg[A-Z]\\w*\\b",
37+ "name": "variable.other.readwrite.global.mac-classic.c"
38+ },
39+ {
40+ "match": "\\bs[A-Z]\\w*\\b",
41+ "name": "variable.other.readwrite.static.mac-classic.c"
42+ },
43+ {
44+ "match": "\\b(NULL|true|false|TRUE|FALSE)\\b",
45+ "name": "constant.language.c"
46+ },
47+ {
48+ "include": "#operators"
49+ },
50+ {
51+ "include": "#numbers"
52+ },
53+ {
54+ "include": "#strings"
55+ },
56+ {
57+ "begin": "(?x)\n^\\s* ((\\#)\\s*define) \\s+ # define\n((?<id>[a-zA-Z_$][\\w$]*)) # macro name\n(?:\n (\\()\n (\n \\s* \\g<id> \\s* # first argument\n ((,) \\s* \\g<id> \\s*)* # additional arguments\n (?:\\.\\.\\.)? # varargs ellipsis?\n )\n (\\))\n)?",
58+ "beginCaptures": {
59+ "1": {
60+ "name": "keyword.control.directive.define.c"
61+ },
62+ "2": {
63+ "name": "punctuation.definition.directive.c"
64+ },
65+ "3": {
66+ "name": "entity.name.function.preprocessor.c"
67+ },
68+ "5": {
69+ "name": "punctuation.definition.parameters.begin.c"
70+ },
71+ "6": {
72+ "name": "variable.parameter.preprocessor.c"
73+ },
74+ "8": {
75+ "name": "punctuation.separator.parameters.c"
76+ },
77+ "9": {
78+ "name": "punctuation.definition.parameters.end.c"
79+ }
80+ },
81+ "end": "(?=(?://|/\\*))|(?<!\\\\)(?=\\n)",
82+ "name": "meta.preprocessor.macro.c",
83+ "patterns": [
84+ {
85+ "include": "$base"
86+ }
87+ ]
88+ },
89+ {
90+ "begin": "^\\s*((#)\\s*(error|warning))\\b",
91+ "captures": {
92+ "1": {
93+ "name": "keyword.control.directive.diagnostic.$3.c"
94+ },
95+ "2": {
96+ "name": "punctuation.definition.directive.c"
97+ }
98+ },
99+ "end": "(?<!\\\\)(?=\\n)",
100+ "name": "meta.preprocessor.diagnostic.c",
101+ "patterns": [
102+ {
103+ "include": "#line_continuation_character"
104+ }
105+ ]
106+ },
107+ {
108+ "begin": "^\\s*((#)\\s*(include|import))\\b\\s*",
109+ "beginCaptures": {
110+ "1": {
111+ "name": "keyword.control.directive.$3.c"
112+ },
113+ "2": {
114+ "name": "punctuation.definition.directive.c"
115+ }
116+ },
117+ "end": "(?=(?://|/\\*))|(?<!\\\\)(?=\\n)",
118+ "name": "meta.preprocessor.include.c",
119+ "patterns": [
120+ {
121+ "include": "#line_continuation_character"
122+ },
123+ {
124+ "begin": "\"",
125+ "beginCaptures": {
126+ "0": {
127+ "name": "punctuation.definition.string.begin.c"
128+ }
129+ },
130+ "end": "\"",
131+ "endCaptures": {
132+ "0": {
133+ "name": "punctuation.definition.string.end.c"
134+ }
135+ },
136+ "name": "string.quoted.double.include.c"
137+ },
138+ {
139+ "begin": "<",
140+ "beginCaptures": {
141+ "0": {
142+ "name": "punctuation.definition.string.begin.c"
143+ }
144+ },
145+ "end": ">",
146+ "endCaptures": {
147+ "0": {
148+ "name": "punctuation.definition.string.end.c"
149+ }
150+ },
151+ "name": "string.quoted.other.lt-gt.include.c"
152+ }
153+ ]
154+ },
155+ {
156+ "include": "#pragma-mark"
157+ },
158+ {
159+ "begin": "^\\s*((#)\\s*line)\\b",
160+ "beginCaptures": {
161+ "1": {
162+ "name": "keyword.control.directive.line.c"
163+ },
164+ "2": {
165+ "name": "punctuation.definition.directive.c"
166+ }
167+ },
168+ "end": "(?=(?://|/\\*))|(?<!\\\\)(?=\\n)",
169+ "name": "meta.preprocessor.c",
170+ "patterns": [
171+ {
172+ "include": "#strings"
173+ },
174+ {
175+ "include": "#numbers"
176+ },
177+ {
178+ "include": "#line_continuation_character"
179+ }
180+ ]
181+ },
182+ {
183+ "begin": "^\\s*(?:((#)\\s*(?:elif|else|if|ifdef|ifndef))|((#)\\s*(pragma|undef)))\\b",
184+ "beginCaptures": {
185+ "1": {
186+ "name": "keyword.control.directive.conditional.c"
187+ },
188+ "2": {
189+ "name": "punctuation.definition.directive.c"
190+ },
191+ "3": {
192+ "name": "keyword.control.directive.$5.c"
193+ },
194+ "4": {
195+ "name": "punctuation.definition.directive.c"
196+ }
197+ },
198+ "end": "(?=(?://|/\\*))|(?<!\\\\)(?=\\n)",
199+ "name": "meta.preprocessor.c",
200+ "patterns": [
201+ {
202+ "include": "#line_continuation_character"
203+ }
204+ ]
205+ },
206+ {
207+ "match": "\\b(u_char|u_short|u_int|u_long|ushort|uint|u_quad_t|quad_t|qaddr_t|caddr_t|daddr_t|dev_t|fixpt_t|blkcnt_t|blksize_t|gid_t|in_addr_t|in_port_t|ino_t|key_t|mode_t|nlink_t|id_t|pid_t|off_t|segsz_t|swblk_t|uid_t|id_t|clock_t|size_t|ssize_t|time_t|useconds_t|suseconds_t)\\b",
208+ "name": "support.type.sys-types.c"
209+ },
210+ {
211+ "match": "\\b(pthread_attr_t|pthread_cond_t|pthread_condattr_t|pthread_mutex_t|pthread_mutexattr_t|pthread_once_t|pthread_rwlock_t|pthread_rwlockattr_t|pthread_t|pthread_key_t)\\b",
212+ "name": "support.type.pthread.c"
213+ },
214+ {
215+ "match": "(?x) \\b\n(int8_t|int16_t|int32_t|int64_t|uint8_t|uint16_t|uint32_t|uint64_t|int_least8_t\n|int_least16_t|int_least32_t|int_least64_t|uint_least8_t|uint_least16_t|uint_least32_t\n|uint_least64_t|int_fast8_t|int_fast16_t|int_fast32_t|int_fast64_t|uint_fast8_t\n|uint_fast16_t|uint_fast32_t|uint_fast64_t|intptr_t|uintptr_t|intmax_t|intmax_t\n|uintmax_t|uintmax_t)\n\\b",
216+ "name": "support.type.stdint.c"
217+ },
218+ {
219+ "match": "\\b(noErr|kNilOptions|kInvalidID|kVariableLengthArray)\\b",
220+ "name": "support.constant.mac-classic.c"
221+ },
222+ {
223+ "match": "(?x) \\b\n(AbsoluteTime|Boolean|Byte|ByteCount|ByteOffset|BytePtr|CompTimeValue|ConstLogicalAddress|ConstStrFileNameParam\n|ConstStringPtr|Duration|Fixed|FixedPtr|Float32|Float32Point|Float64|Float80|Float96|FourCharCode|Fract|FractPtr\n|Handle|ItemCount|LogicalAddress|OptionBits|OSErr|OSStatus|OSType|OSTypePtr|PhysicalAddress|ProcessSerialNumber\n|ProcessSerialNumberPtr|ProcHandle|Ptr|ResType|ResTypePtr|ShortFixed|ShortFixedPtr|SignedByte|SInt16|SInt32|SInt64\n|SInt8|Size|StrFileName|StringHandle|StringPtr|TimeBase|TimeRecord|TimeScale|TimeValue|TimeValue64|UInt16|UInt32\n|UInt64|UInt8|UniChar|UniCharCount|UniCharCountPtr|UniCharPtr|UnicodeScalarValue|UniversalProcHandle|UniversalProcPtr\n|UnsignedFixed|UnsignedFixedPtr|UnsignedWide|UTF16Char|UTF32Char|UTF8Char)\n\\b",
224+ "name": "support.type.mac-classic.c"
225+ },
226+ {
227+ "match": "\\b([A-Za-z0-9_]+_t)\\b",
228+ "name": "support.type.posix-reserved.c"
229+ },
230+ {
231+ "include": "#block"
232+ },
233+ {
234+ "begin": "(?x)\n(?:\n ^ |\n (?:\n (?=\\s)(?<!else|new|return)(?<=\\w) # word + space before name\n |\n (?=\\s*[A-Za-z_])(?<!&&)(?<=[*&>]) # type modifier before name\n )\n)\n(\\s*)(?!(while|for|do|if|else|switch|catch|enumerate|return|sizeof|[cr]?iterate)\\s*\\()\n(\n (?:[A-Za-z_][A-Za-z0-9_]*+|::)++ # actual name\n |\n (?:(?<=operator)(?:[-*&<>=+!]+|\\(\\)|\\[\\]))\n)\n\\s*(?=\\()",
235+ "beginCaptures": {
236+ "1": {
237+ "name": "punctuation.whitespace.function.leading.c"
238+ },
239+ "3": {
240+ "name": "entity.name.function.c"
241+ },
242+ "4": {
243+ "name": "punctuation.definition.parameters.c"
244+ }
245+ },
246+ "end": "(?<=\\})|(?=#)|(;)",
247+ "name": "meta.function.c",
248+ "patterns": [
249+ {
250+ "include": "#comments"
251+ },
252+ {
253+ "include": "#parens"
254+ },
255+ {
256+ "match": "\\b(const)\\b",
257+ "name": "storage.modifier.c"
258+ },
259+ {
260+ "include": "#block"
261+ }
262+ ]
263+ },
264+ {
265+ "include": "#line_continuation_character"
266+ }
267+ ],
268+ "repository": {
269+ "access": {
270+ "captures": {
271+ "2": {
272+ "name": "punctuation.separator.dot-access.c"
273+ },
274+ "3": {
275+ "name": "punctuation.separator.pointer-access.c"
276+ },
277+ "4": {
278+ "name": "variable.other.member.c"
279+ }
280+ },
281+ "match": "((\\.)|(->))([a-zA-Z_][a-zA-Z_0-9]*)\\b(?!\\s*\\()"
282+ },
283+ "block": {
284+ "patterns": [
285+ {
286+ "begin": "\\{",
287+ "beginCaptures": {
288+ "0": {
289+ "name": "punctuation.section.block.begin.c"
290+ }
291+ },
292+ "end": "\\}|(?=\\s*#\\s*endif\\b)",
293+ "endCaptures": {
294+ "0": {
295+ "name": "punctuation.section.block.end.c"
296+ }
297+ },
298+ "name": "meta.block.c",
299+ "patterns": [
300+ {
301+ "include": "#block_innards"
302+ }
303+ ]
304+ }
305+ ]
306+ },
307+ "block_innards": {
308+ "patterns": [
309+ {
310+ "include": "#preprocessor-rule-enabled-block"
311+ },
312+ {
313+ "include": "#preprocessor-rule-disabled-block"
314+ },
315+ {
316+ "include": "#preprocessor-rule-other-block"
317+ },
318+ {
319+ "include": "#sizeof"
320+ },
321+ {
322+ "include": "#access"
323+ },
324+ {
325+ "include": "#libc"
326+ },
327+ {
328+ "include": "#c_function_call"
329+ },
330+ {
331+ "captures": {
332+ "1": {
333+ "name": "variable.other.c"
334+ },
335+ "2": {
336+ "name": "punctuation.definition.parameters.c"
337+ }
338+ },
339+ "match": "(?x)\n(?:\n (?:\n (?=\\s)(?<!else|new|return)\n (?<=\\w) \\s+ # or word + space before name\n )\n)\n(\n (?:[A-Za-z_][A-Za-z0-9_]*+ | :: )++ # actual name\n |\n (?:(?<=operator) (?:[-*&<>=+!]+ | \\(\\) | \\[\\]))\n)\n\\s*(\\() # opening bracket",
340+ "name": "meta.initialization.c"
341+ },
342+ {
343+ "include": "#block"
344+ },
345+ {
346+ "include": "$base"
347+ }
348+ ]
349+ },
350+ "c_function_call": {
351+ "captures": {
352+ "1": {
353+ "name": "punctuation.whitespace.function-call.leading.c"
354+ },
355+ "2": {
356+ "name": "support.function.any-method.c"
357+ },
358+ "4": {
359+ "name": "punctuation.definition.parameters.c"
360+ }
361+ },
362+ "match": "(?x)\n(?:\n (?=\\s)\n (?:(?<=else|new|return) | (?<!\\w)) (\\s+)\n)?\n\n# Actual name\n(\n \\b\n (?!\n (while|for|do|if|else|switch|catch|enumerate|return|sizeof|r?iterate)\n \\s* \\(\n )\n (?:(?!NS)[A-Za-z_][A-Za-z0-9_]*+\\b | ::)++\n)\n\\s*(\\() # Opening bracket",
363+ "name": "meta.function-call.c"
364+ },
365+ "comments": {
366+ "patterns": [
367+ {
368+ "captures": {
369+ "1": {
370+ "name": "meta.toc-list.banner.block.c"
371+ }
372+ },
373+ "match": "^/\\* =(\\s*.*?)\\s*= \\*/$\\n?",
374+ "name": "comment.block.c"
375+ },
376+ {
377+ "begin": "/\\*",
378+ "beginCaptures": {
379+ "0": {
380+ "name": "punctuation.definition.comment.begin.c"
381+ }
382+ },
383+ "end": "\\*/",
384+ "endCaptures": {
385+ "0": {
386+ "name": "punctuation.definition.comment.end.c"
387+ }
388+ },
389+ "name": "comment.block.c"
390+ },
391+ {
392+ "match": "\\*/.*\\n",
393+ "name": "invalid.illegal.stray-comment-end.c"
394+ },
395+ {
396+ "captures": {
397+ "1": {
398+ "name": "meta.toc-list.banner.line.c"
399+ }
400+ },
401+ "match": "^// =(\\s*.*?)\\s*=\\s*$\\n?",
402+ "name": "comment.line.banner.cpp"
403+ },
404+ {
405+ "begin": "(^[ \\t]+)?(?=//)",
406+ "beginCaptures": {
407+ "1": {
408+ "name": "punctuation.whitespace.comment.leading.cpp"
409+ }
410+ },
411+ "end": "(?!\\G)",
412+ "patterns": [
413+ {
414+ "begin": "//",
415+ "beginCaptures": {
416+ "0": {
417+ "name": "punctuation.definition.comment.cpp"
418+ }
419+ },
420+ "end": "\\n",
421+ "name": "comment.line.double-slash.cpp",
422+ "patterns": [
423+ {
424+ "include": "#line_continuation_character"
425+ }
426+ ]
427+ }
428+ ]
429+ }
430+ ]
431+ },
432+ "disabled": {
433+ "begin": "^\\s*#\\s*if(n?def)?\\b.*$",
434+ "end": "^\\s*#\\s*endif\\b",
435+ "patterns": [
436+ {
437+ "include": "#disabled"
438+ },
439+ {
440+ "include": "#pragma-mark"
441+ }
442+ ]
443+ },
444+ "libc": {
445+ "captures": {
446+ "1": {
447+ "name": "punctuation.whitespace.support.function.leading.c"
448+ },
449+ "2": {
450+ "name": "support.function.C99.c"
451+ }
452+ },
453+ "match": "(?x) (\\s*) \\b\n(_Exit|(?:nearbyint|nextafter|nexttoward|netoward|nan)[fl]?|a(?:cos|sin)h?[fl]?|abort|abs|asctime|assert\n|atan(?:[h2]?[fl]?)?|atexit|ato[ifl]|atoll|bsearch|btowc|cabs[fl]?|cacos|cacos[fl]|cacosh[fl]?\n|calloc|carg[fl]?|casinh?[fl]?|catanh?[fl]?|cbrt[fl]?|ccosh?[fl]?|ceil[fl]?|cexp[fl]?|cimag[fl]?\n|clearerr|clock|clog[fl]?|conj[fl]?|copysign[fl]?|cosh?[fl]?|cpow[fl]?|cproj[fl]?|creal[fl]?\n|csinh?[fl]?|csqrt[fl]?|ctanh?[fl]?|ctime|difftime|div|erfc?[fl]?|exit|fabs[fl]?\n|exp(?:2[fl]?|[fl]|m1[fl]?)?|fclose|fdim[fl]?|fe[gs]et(?:env|exceptflag|round)|feclearexcept\n|feholdexcept|feof|feraiseexcept|ferror|fetestexcept|feupdateenv|fflush|fgetpos|fgetw?[sc]\n|floor[fl]?|fmax?[fl]?|fmin[fl]?|fmod[fl]?|fopen|fpclassify|fprintf|fputw?[sc]|fread|free|freopen\n|frexp[fl]?|fscanf|fseek|fsetpos|ftell|fwide|fwprintf|fwrite|fwscanf|genv|get[sc]|getchar|gmtime\n|gwc|gwchar|hypot[fl]?|ilogb[fl]?|imaxabs|imaxdiv|isalnum|isalpha|isblank|iscntrl|isdigit|isfinite\n|isgraph|isgreater|isgreaterequal|isinf|isless(?:equal|greater)?|isw?lower|isnan|isnormal|isw?print\n|isw?punct|isw?space|isunordered|isw?upper|iswalnum|iswalpha|iswblank|iswcntrl|iswctype|iswdigit|iswgraph\n|isw?xdigit|labs|ldexp[fl]?|ldiv|lgamma[fl]?|llabs|lldiv|llrint[fl]?|llround[fl]?|localeconv|localtime\n|log[2b]?[fl]?|log1[p0][fl]?|longjmp|lrint[fl]?|lround[fl]?|malloc|mbr?len|mbr?towc|mbsinit|mbsrtowcs\n|mbstowcs|memchr|memcmp|memcpy|memmove|memset|mktime|modf[fl]?|perror|pow[fl]?|printf|puts|putw?c(?:har)?\n|qsort|raise|rand|remainder[fl]?|realloc|remove|remquo[fl]?|rename|rewind|rint[fl]?|round[fl]?|scalbl?n[fl]?\n|scanf|setbuf|setjmp|setlocale|setvbuf|signal|signbit|sinh?[fl]?|snprintf|sprintf|sqrt[fl]?|srand|sscanf\n|strcat|strchr|strcmp|strcoll|strcpy|strcspn|strerror|strftime|strlen|strncat|strncmp|strncpy|strpbrk\n|strrchr|strspn|strstr|strto[kdf]|strtoimax|strtol[dl]?|strtoull?|strtoumax|strxfrm|swprintf|swscanf\n|system|tan|tan[fl]|tanh[fl]?|tgamma[fl]?|time|tmpfile|tmpnam|tolower|toupper|trunc[fl]?|ungetw?c|va_arg\n|va_copy|va_end|va_start|vfw?printf|vfw?scanf|vprintf|vscanf|vsnprintf|vsprintf|vsscanf|vswprintf|vswscanf\n|vwprintf|vwscanf|wcrtomb|wcscat|wcschr|wcscmp|wcscoll|wcscpy|wcscspn|wcsftime|wcslen|wcsncat|wcsncmp|wcsncpy\n|wcspbrk|wcsrchr|wcsrtombs|wcsspn|wcsstr|wcsto[dkf]|wcstoimax|wcstol[dl]?|wcstombs|wcstoull?|wcstoumax|wcsxfrm\n|wctom?b|wmem(?:set|chr|cpy|cmp|move)|wprintf|wscanf)\\b"
454+ },
455+ "line_continuation_character": {
456+ "patterns": [
457+ {
458+ "match": "(\\\\)\\s*\\n",
459+ "captures": {
460+ "1": {
461+ "name": "constant.character.escape.line-continuation.c"
462+ }
463+ }
464+ }
465+ ]
466+ },
467+ "numbers": {
468+ "patterns": [
469+ {
470+ "match": "\\b((0(x|X)[0-9a-fA-F]*)|(0(b|B)[01]*)|(([0-9]+\\.?[0-9]*)|(\\.[0-9]+))((e|E)(\\+|-)?[0-9]+)?)(L|l|UL|ul|u|U|F|f|ll|LL|ull|ULL)?\\b",
471+ "name": "constant.numeric.c"
472+ }
473+ ]
474+ },
475+ "parens": {
476+ "begin": "\\(",
477+ "beginCaptures": {
478+ "0": {
479+ "name": "punctuation.section.parens.begin.c"
480+ }
481+ },
482+ "end": "\\)",
483+ "endCaptures": {
484+ "0": {
485+ "name": "punctuation.section.parens.end.c"
486+ }
487+ },
488+ "name": "meta.parens.c",
489+ "patterns": [
490+ {
491+ "include": "$base"
492+ }
493+ ]
494+ },
495+ "pragma-mark": {
496+ "captures": {
497+ "1": {
498+ "name": "meta.preprocessor.c"
499+ },
500+ "2": {
501+ "name": "keyword.control.directive.pragma.pragma-mark.c"
502+ },
503+ "3": {
504+ "name": "punctuation.definition.directive.c"
505+ },
506+ "4": {
507+ "name": "meta.toc-list.pragma-mark.c"
508+ }
509+ },
510+ "match": "^\\s*(((#)\\s*pragma\\s+mark)\\s+(.*))",
511+ "name": "meta.section"
512+ },
513+ "preprocessor-rule-disabled": {
514+ "begin": "^\\s*(((#)if)\\s+(0)\\b).*",
515+ "beginCaptures": {
516+ "1": {
517+ "name": "meta.preprocessor.c"
518+ },
519+ "2": {
520+ "name": "keyword.control.directive.conditional.c"
521+ },
522+ "3": {
523+ "name": "punctuation.definition.directive.c"
524+ },
525+ "4": {
526+ "name": "constant.numeric.preprocessor.c"
527+ }
528+ },
529+ "end": "^\\s*(((#)\\s*endif)\\b)",
530+ "endCaptures": {
531+ "1": {
532+ "name": "meta.preprocessor.c"
533+ },
534+ "2": {
535+ "name": "keyword.control.directive.conditional.c"
536+ },
537+ "3": {
538+ "name": "punctuation.definition.directive.c"
539+ }
540+ },
541+ "patterns": [
542+ {
543+ "begin": "^\\s*(((#)\\s*else)\\b)",
544+ "beginCaptures": {
545+ "1": {
546+ "name": "meta.preprocessor.c"
547+ },
548+ "2": {
549+ "name": "keyword.control.directive.conditional.c"
550+ },
551+ "3": {
552+ "name": "punctuation.definition.directive.c"
553+ }
554+ },
555+ "end": "(?=^\\s*#\\s*endif\\b)",
556+ "patterns": [
557+ {
558+ "include": "$base"
559+ }
560+ ]
561+ },
562+ {
563+ "begin": "\\G",
564+ "end": "(?=^\\s*#\\s*(else|endif)\\b)",
565+ "contentName": "comment.block.preprocessor.if-branch",
566+ "patterns": [
567+ {
568+ "include": "#disabled"
569+ },
570+ {
571+ "include": "#pragma-mark"
572+ }
573+ ]
574+ }
575+ ]
576+ },
577+ "preprocessor-rule-disabled-block": {
578+ "begin": "^\\s*(((#)if)\\s+(0)\\b).*",
579+ "beginCaptures": {
580+ "1": {
581+ "name": "meta.preprocessor.c"
582+ },
583+ "2": {
584+ "name": "keyword.control.directive.conditional.c"
585+ },
586+ "3": {
587+ "name": "punctuation.definition.directive.c"
588+ },
589+ "4": {
590+ "name": "constant.numeric.preprocessor.c"
591+ }
592+ },
593+ "end": "^\\s*(((#)\\s*endif)\\b)",
594+ "endCaptures": {
595+ "1": {
596+ "name": "meta.preprocessor.c"
597+ },
598+ "2": {
599+ "name": "keyword.control.directive.conditional.c"
600+ },
601+ "3": {
602+ "name": "punctuation.definition.directive.c"
603+ }
604+ },
605+ "patterns": [
606+ {
607+ "begin": "^\\s*(((#)\\s*else\\b))",
608+ "beginCaptures": {
609+ "1": {
610+ "name": "meta.preprocessor.c"
611+ },
612+ "2": {
613+ "name": "keyword.control.directive.conditional.c"
614+ },
615+ "3": {
616+ "name": "punctuation.definition.directive.c"
617+ }
618+ },
619+ "end": "(?=^\\s*#\\s*endif\\b)",
620+ "patterns": [
621+ {
622+ "include": "#block_innards"
623+ }
624+ ]
625+ },
626+ {
627+ "begin": "\\G",
628+ "end": "(?=^\\s*#\\s*(else|endif)\\b)",
629+ "contentName": "comment.block.preprocessor.if-branch.in-block",
630+ "patterns": [
631+ {
632+ "include": "#disabled"
633+ },
634+ {
635+ "include": "#pragma-mark"
636+ }
637+ ]
638+ }
639+ ]
640+ },
641+ "preprocessor-rule-enabled": {
642+ "begin": "^\\s*(((#)if)\\s+(0*1)\\b)",
643+ "beginCaptures": {
644+ "1": {
645+ "name": "meta.preprocessor.c"
646+ },
647+ "2": {
648+ "name": "keyword.control.directive.conditional.c"
649+ },
650+ "3": {
651+ "name": "punctuation.definition.directive.c"
652+ },
653+ "4": {
654+ "name": "constant.numeric.preprocessor.c"
655+ }
656+ },
657+ "end": "^\\s*(((#)\\s*endif)\\b)",
658+ "endCaptures": {
659+ "1": {
660+ "name": "meta.preprocessor.c"
661+ },
662+ "2": {
663+ "name": "keyword.control.directive.conditional.c"
664+ },
665+ "3": {
666+ "name": "punctuation.definition.directive.c"
667+ }
668+ },
669+ "patterns": [
670+ {
671+ "begin": "^\\s*(((#)\\s*else)\\b).*",
672+ "beginCaptures": {
673+ "1": {
674+ "name": "meta.preprocessor.c"
675+ },
676+ "2": {
677+ "name": "keyword.control.directive.conditional.c"
678+ },
679+ "3": {
680+ "name": "punctuation.definition.directive.c"
681+ }
682+ },
683+ "contentName": "comment.block.preprocessor.else-branch",
684+ "end": "(?=^\\s*#\\s*endif\\b)",
685+ "patterns": [
686+ {
687+ "include": "#disabled"
688+ },
689+ {
690+ "include": "#pragma-mark"
691+ }
692+ ]
693+ },
694+ {
695+ "begin": "\\G",
696+ "end": "(?=^\\s*#\\s*(else|endif)\\b)",
697+ "patterns": [
698+ {
699+ "include": "$base"
700+ }
701+ ]
702+ }
703+ ]
704+ },
705+ "preprocessor-rule-enabled-block": {
706+ "begin": "^\\s*(((#)if)\\s+(0*1)\\b)",
707+ "beginCaptures": {
708+ "1": {
709+ "name": "meta.preprocessor.c"
710+ },
711+ "2": {
712+ "name": "keyword.control.directive.conditional.c"
713+ },
714+ "3": {
715+ "name": "punctuation.definition.directive.c"
716+ },
717+ "4": {
718+ "name": "constant.numeric.preprocessor.c"
719+ }
720+ },
721+ "end": "^\\s*(((#)\\s*endif)\\b)",
722+ "endCaptures": {
723+ "1": {
724+ "name": "meta.preprocessor.c"
725+ },
726+ "2": {
727+ "name": "keyword.control.directive.conditional.c"
728+ },
729+ "3": {
730+ "name": "punctuation.definition.directive.c"
731+ }
732+ },
733+ "patterns": [
734+ {
735+ "begin": "^\\s*(((#)\\s*else)\\b).*",
736+ "beginCaptures": {
737+ "1": {
738+ "name": "meta.preprocessor.c"
739+ },
740+ "2": {
741+ "name": "keyword.control.directive.conditional.c"
742+ },
743+ "3": {
744+ "name": "punctuation.definition.directive.c"
745+ }
746+ },
747+ "contentName": "comment.block.preprocessor.else-branch.in-block",
748+ "end": "(?=^\\s*#\\s*endif\\b)",
749+ "patterns": [
750+ {
751+ "include": "#disabled"
752+ },
753+ {
754+ "include": "#pragma-mark"
755+ }
756+ ]
757+ },
758+ {
759+ "begin": "\\G",
760+ "end": "(?=^\\s*#\\s*(else|endif)\\b)",
761+ "patterns": [
762+ {
763+ "include": "#block_innards"
764+ }
765+ ]
766+ }
767+ ]
768+ },
769+ "preprocessor-rule-other": {
770+ "begin": "^\\s*(((#)\\s*if(n?def)?)\\b.*?(?:(?=(?://|/\\*))|$))",
771+ "beginCaptures": {
772+ "1": {
773+ "name": "meta.preprocessor.c"
774+ },
775+ "2": {
776+ "name": "keyword.control.directive.conditional.c"
777+ },
778+ "3": {
779+ "name": "punctuation.definition.directive.c"
780+ }
781+ },
782+ "end": "^\\s*(((#)\\s*(endif))\\b)",
783+ "endCaptures": {
784+ "1": {
785+ "name": "meta.preprocessor.c"
786+ },
787+ "2": {
788+ "name": "keyword.control.directive.conditional.c"
789+ },
790+ "3": {
791+ "name": "punctuation.definition.directive.c"
792+ }
793+ },
794+ "patterns": [
795+ {
796+ "include": "$base"
797+ }
798+ ]
799+ },
800+ "preprocessor-rule-other-block": {
801+ "begin": "^\\s*(((#)\\s*if(n?def)?)\\b.*?(?:(?=(?://|/\\*))|$))",
802+ "beginCaptures": {
803+ "1": {
804+ "name": "meta.preprocessor.c"
805+ },
806+ "2": {
807+ "name": "keyword.control.directive.conditional.c"
808+ },
809+ "3": {
810+ "name": "punctuation.definition.directive.c"
811+ }
812+ },
813+ "end": "^\\s*(((#)\\s*endif)\\b)",
814+ "endCaptures": {
815+ "1": {
816+ "name": "meta.preprocessor.c"
817+ },
818+ "2": {
819+ "name": "keyword.control.directive.conditional.c"
820+ },
821+ "3": {
822+ "name": "punctuation.definition.directive.c"
823+ }
824+ },
825+ "patterns": [
826+ {
827+ "include": "#block_innards"
828+ }
829+ ]
830+ },
831+ "operators": {
832+ "patterns": [
833+ {
834+ "match": "(?<![\\w$])(sizeof)(?![\\w$])",
835+ "name": "keyword.operator.sizeof.c"
836+ },
837+ {
838+ "match": "--",
839+ "name": "keyword.operator.decrement.c"
840+ },
841+ {
842+ "match": "\\+\\+",
843+ "name": "keyword.operator.increment.c"
844+ },
845+ {
846+ "match": "%=|\\+=|-=|\\*=|(?<!\\()/=",
847+ "name": "keyword.operator.assignment.compound.c"
848+ },
849+ {
850+ "match": "&=|\\^=|<<=|>>=|\\|=",
851+ "name": "keyword.operator.assignment.compound.bitwise.c"
852+ },
853+ {
854+ "match": "<<|>>",
855+ "name": "keyword.operator.bitwise.shift.c"
856+ },
857+ {
858+ "match": "!=|<=|>=|==|<|>",
859+ "name": "keyword.operator.comparison.c"
860+ },
861+ {
862+ "match": "&&|!|\\|\\|",
863+ "name": "keyword.operator.logical.c"
864+ },
865+ {
866+ "match": "&|\\||\\^|~",
867+ "name": "keyword.operator.c"
868+ },
869+ {
870+ "match": "=",
871+ "name": "keyword.operator.assignment.c"
872+ },
873+ {
874+ "match": "%|\\*|/|-|\\+",
875+ "name": "keyword.operator.c"
876+ },
877+ {
878+ "begin": "\\?",
879+ "beginCaptures": {
880+ "0": {
881+ "name": "keyword.operator.ternary.c"
882+ }
883+ },
884+ "end": ":",
885+ "endCaptures": {
886+ "0": {
887+ "name": "keyword.operator.ternary.c"
888+ }
889+ },
890+ "patterns": [
891+ {
892+ "include": "$self"
893+ }
894+ ]
895+ }
896+ ]
897+ },
898+ "strings": {
899+ "patterns": [
900+ {
901+ "begin": "\"",
902+ "beginCaptures": {
903+ "0": {
904+ "name": "punctuation.definition.string.begin.c"
905+ }
906+ },
907+ "end": "\"",
908+ "endCaptures": {
909+ "0": {
910+ "name": "punctuation.definition.string.end.c"
911+ }
912+ },
913+ "name": "string.quoted.double.c",
914+ "patterns": [
915+ {
916+ "include": "#string_escaped_char"
917+ },
918+ {
919+ "include": "#string_placeholder"
920+ },
921+ {
922+ "include": "#line_continuation_character"
923+ }
924+ ]
925+ },
926+ {
927+ "begin": "'",
928+ "beginCaptures": {
929+ "0": {
930+ "name": "punctuation.definition.string.begin.c"
931+ }
932+ },
933+ "end": "'",
934+ "endCaptures": {
935+ "0": {
936+ "name": "punctuation.definition.string.end.c"
937+ }
938+ },
939+ "name": "string.quoted.single.c",
940+ "patterns": [
941+ {
942+ "include": "#string_escaped_char"
943+ },
944+ {
945+ "include": "#line_continuation_character"
946+ }
947+ ]
948+ }
949+ ]
950+ },
951+ "string_escaped_char": {
952+ "patterns": [
953+ {
954+ "match": "(?x)\\\\ (\n\\\\ |\n[abefnprtv'\"?] |\n[0-3]\\d{,2} |\n[4-7]\\d? |\nx[a-fA-F0-9]{,2} |\nu[a-fA-F0-9]{,4} |\nU[a-fA-F0-9]{,8} )",
955+ "name": "constant.character.escape.c"
956+ },
957+ {
958+ "match": "\\\\.",
959+ "name": "invalid.illegal.unknown-escape.c"
960+ }
961+ ]
962+ },
963+ "string_placeholder": {
964+ "patterns": [
965+ {
966+ "match": "(?x) %\n(\\d+\\$)? # field (argument #)\n[#0\\- +']* # flags\n[,;:_]? # separator character (AltiVec)\n((-?\\d+)|\\*(-?\\d+\\$)?)? # minimum field width\n(\\.((-?\\d+)|\\*(-?\\d+\\$)?)?)? # precision\n(hh|h|ll|l|j|t|z|q|L|vh|vl|v|hv|hl)? # length modifier\n[diouxXDOUeEfFgGaACcSspn%] # conversion type",
967+ "name": "constant.other.placeholder.c"
968+ },
969+ {
970+ "match": "%",
971+ "name": "invalid.illegal.placeholder.c"
972+ }
973+ ]
974+ }
975+ },
976+ "version": "https://github.com/atom/language-c/commit/2a5fafe1d86f690b5ab2c877cea2fc6a598e001a"
977+}
modified extensions/vscode/textmate-syntaxes/coffeescript.json +667 −667
@@ -1,668 +1,668 @@
11 {
2- "comment": "CoffeeScript",
3- "fileTypes": [
4- "coffee",
5- "Cakefile",
6- "coffee.erb",
7- "cake",
8- "cjsx",
9- "cson",
10- "iced"
11- ],
12- "injections": {
13- "string.regexp.block.coffee": {
14- "patterns": [
15- {
16- "include": "#interpolated_coffee"
17- },
18- {
19- "include": "#embedded_comment"
20- }
21- ]
22- }
23- },
24- "keyEquivalent": "^~C",
25- "name": "CoffeeScript",
26- "patterns": [
27- {
28- "captures": {
29- "1": {
30- "name": "punctuation.definition.parameters.begin.coffee"
31- },
32- "2": {
33- "patterns": [
34- {
35- "captures": {
36- "1": {
37- "name": "variable.parameter.function.coffee"
38- },
39- "2": {
40- "name": "punctuation.separator.key-value.coffee"
41- },
42- "3": {
43- "name": "string.quoted.double.coffee"
44- },
45- "4": {
46- "name": "punctuation.definition.string.begin.coffee"
47- },
48- "5": {
49- "name": "punctuation.definition.string.end.coffee"
50- },
51- "6": {
52- "name": "string.quoted.single.coffee"
53- },
54- "7": {
55- "name": "punctuation.definition.string.begin.coffee"
56- },
57- "8": {
58- "name": "punctuation.definition.string.end.coffee"
59- }
60- },
61- "match": "(?x)\n\t\t\t\t\t\t\t\t([^()\\s,]+)\n\t\t\t\t\t\t\t\t\\s+(=)\\s+\n\t\t\t\t\t\t\t\t(?:\n\t\t\t\t\t\t\t\t\t((\")[^\"]*(\"))\n\t\t\t\t\t\t\t\t | ((')[^']*('))\n\t\t\t\t\t\t\t\t)"
62- },
63- {
64- "match": "[^()\\s,]+",
65- "name": "variable.parameter.function.coffee"
66- },
67- {
68- "match": ",",
69- "name": "punctuation.separator.arguments.coffee"
70- }
71- ]
72- },
73- "3": {
74- "name": "punctuation.definition.parameters.begin.coffee"
75- },
76- "4": {
77- "name": "storage.type.function.coffee"
78- }
79- },
80- "comment": "match stuff like: a -> … ",
81- "match": "(\\()([^()]*?)(\\))\\s*([=-]>)",
82- "name": "meta.inline.function.coffee"
83- },
84- {
85- "captures": {
86- "1": {
87- "name": "keyword.operator.new.coffee"
88- },
89- "4": {
90- "name": "storage.type.class.coffee"
91- },
92- "6": {
93- "name": "entity.name.type.instance.coffee"
94- },
95- "7": {
96- "name": "entity.name.type.instance.coffee"
97- }
98- },
99- "match": "(new)\\s+(((class)(\\s+(\\w+(?:\\.\\w*)*))?)|(\\w+(?:\\.\\w*)*))",
100- "name": "meta.class.instance.constructor"
101- },
102- {
103- "begin": "'''",
104- "beginCaptures": {
105- "0": {
106- "name": "punctuation.definition.string.begin.coffee"
107- }
108- },
109- "end": "'''",
110- "endCaptures": {
111- "0": {
112- "name": "punctuation.definition.string.end.coffee"
113- }
114- },
115- "name": "string.unquoted.heredoc.coffee"
116- },
117- {
118- "begin": "\"\"\"",
119- "beginCaptures": {
120- "0": {
121- "name": "punctuation.definition.string.begin.coffee"
122- }
123- },
124- "end": "\"\"\"",
125- "endCaptures": {
126- "0": {
127- "name": "punctuation.definition.string.end.coffee"
128- }
129- },
130- "name": "string.quoted.double.heredoc.coffee",
131- "patterns": [
132- {
133- "match": "\\\\.",
134- "name": "constant.character.escape.coffee"
135- },
136- {
137- "include": "#interpolated_coffee"
138- }
139- ]
140- },
141- {
142- "begin": "(?=`)",
143- "end": "(?<=`)",
144- "name": "meta.embedded.line.coffee",
145- "patterns": [
146- {
147- "begin": "`",
148- "beginCaptures": {
149- "0": {
150- "name": "punctuation.definition.string.begin.coffee"
151- }
152- },
153- "contentName": "source.js",
154- "end": "(`)",
155- "endCaptures": {
156- "0": {
157- "name": "punctuation.definition.string.end.coffee"
158- },
159- "1": {
160- "name": "source.js"
161- }
162- },
163- "name": "string.other.embedded.javascript.coffee",
164- "patterns": [
165- {
166- "include": "source.js"
167- }
168- ]
169- }
170- ]
171- },
172- {
173- "begin": "(?<!#)###(?!#)",
174- "captures": {
175- "0": {
176- "name": "punctuation.definition.comment.coffee"
177- }
178- },
179- "end": "###(?:[ \\t]*\\n)",
180- "name": "comment.block.coffee",
181- "patterns": [
182- {
183- "match": "(?<=^|\\s)@\\w*(?=\\s)",
184- "name": "storage.type.annotation.coffeescript"
185- }
186- ]
187- },
188- {
189- "begin": "(^[ \\t]+)?(?=#)",
190- "beginCaptures": {
191- "1": {
192- "name": "punctuation.whitespace.comment.leading.coffee"
193- }
194- },
195- "end": "(?!\\G)",
196- "patterns": [
197- {
198- "begin": "#",
199- "beginCaptures": {
200- "0": {
201- "name": "punctuation.definition.comment.coffee"
202- }
203- },
204- "end": "\\n",
205- "name": "comment.line.number-sign.coffee"
206- }
207- ]
208- },
209- {
210- "begin": "/{3}",
211- "beginCaptures": {
212- "0": {
213- "name": "punctuation.definition.string.begin.coffee"
214- }
215- },
216- "end": "(/{3})[imgy]{0,4}",
217- "endCaptures": {
218- "1": {
219- "name": "punctuation.definition.string.end.coffee"
220- }
221- },
222- "name": "string.regexp.block.coffee",
223- "patterns": [
224- {
225- "include": "source.js.regexp"
226- }
227- ]
228- },
229- {
230- "begin": "/(?![\\s=/*+{}?])",
231- "beginCaptures": {
232- "0": {
233- "name": "punctuation.definition.string.begin.coffee"
234- }
235- },
236- "end": "(/)[igmy]{0,4}(?![a-zA-Z0-9])",
237- "endCaptures": {
238- "1": {
239- "name": "punctuation.definition.string.end.coffee"
240- }
241- },
242- "name": "string.regexp.coffee",
243- "patterns": [
244- {
245- "include": "source.js.regexp"
246- }
247- ]
248- },
249- {
250- "match": "(?x)\n\t\t\t\t\\b\n\t\t\t\t(?<![\\.\\$])\n\t\t\t\t(\n\t\t\t\t\tbreak\n\t\t\t\t | by\n\t\t\t\t | catch\n\t\t\t\t | continue\n\t\t\t\t | else\n\t\t\t\t | finally\n\t\t\t\t | for\n\t\t\t\t | in\n\t\t\t\t | of\n\t\t\t\t | if\n\t\t\t\t | return\n\t\t\t\t | switch\n\t\t\t\t | then\n\t\t\t\t | throw\n\t\t\t\t | try\n\t\t\t\t | unless\n\t\t\t\t | when\n\t\t\t\t | while\n\t\t\t\t | until\n\t\t\t\t | loop\n\t\t\t\t | do\n\t\t\t\t | (?<=for)\\s+own\n\t\t\t\t)\n\t\t\t\t(?!\\s*:)\n\t\t\t\t\\b\n\t\t\t",
251- "name": "keyword.control.coffee"
252- },
253- {
254- "match": "(?x)\n (and|or|<<|>>>?|(?<!\\()\\/|[=!<>*%+\\-&^])?=(?!>)\n | [!%^*\\/~?:]\n | \\-?\\-(?!>)\n | \\+\\+?\n | <>\n | <\n | >\n | &&?\n | \\.\\.\\.?\n | \\|\\|?\n | \\b(?<![\\.\\$])(instanceof|new|delete|typeof|and|or|is|isnt|not|super)(?!\\s*:)\\b\n\t\t\t",
255- "name": "keyword.operator.coffee"
256- },
257- {
258- "match": "(?x)\n\t\t\t\t\\b\n\t\t\t\t(?<![\\.\\$])\n\t\t\t\t(\n\t\t\t\t\t case\n | default\n | function\n | var\n | void\n | with\n | const\n | let\n | enum\n | export\n | import\n | native\n | __hasProp\n | __extends\n | __slice\n | __bind\n | __indexOf\n | implements\n | interface\n | package\n | private\n | protected\n | public\n | static\n | yield\n )\n\t\t\t\t(?!\\s*:)\n\t\t\t\t\\b\n\t\t\t",
259- "name": "keyword.other.reserved.coffee"
260- },
261- {
262- "captures": {
263- "1": {
264- "name": "variable.other.assignment.coffee"
265- },
266- "4": {
267- "name": "punctuation.separator.key-value"
268- },
269- "5": {
270- "name": "keyword.operator.coffee"
271- }
272- },
273- "match": "(?x)\n\t\t\t\t(?:\n\t\t\t\t\t([a-zA-Z\\$_](\\w|\\$|\\.)*)\n\t\t\t\t\t\\s*\n\t\t\t\t\t(?!\\::)\n\t\t\t\t\t((:)|((?:or|and|[-+/&%*?])?=)(?![>=]))\n\t\t\t\t\t(?!\n\t\t\t\t\t\t(\n\t\t\t\t\t\t\t\\s*\\(.*\\)\n\t\t\t\t\t\t)?\n\t\t\t\t\t\t\\s*\n\t\t\t\t\t\t([=-]>)\n\t\t\t\t\t)\n\t\t\t\t)"
274- },
275- {
276- "begin": "(?<=\\s|^)(\\{)(?=.+?\\}\\s+[:=])",
277- "beginCaptures": {
278- "0": {
279- "name": "keyword.operator.coffee"
280- }
281- },
282- "end": "(\\}\\s*[:=])",
283- "endCaptures": {
284- "0": {
285- "name": "keyword.operator.coffee"
286- }
287- },
288- "name": "meta.variable.assignment.destructured.object.coffee",
289- "patterns": [
290- {
291- "include": "#variable_name"
292- },
293- {
294- "include": "#instance_variable"
295- },
296- {
297- "include": "#single_quoted_string"
298- },
299- {
300- "include": "#double_quoted_string"
301- },
302- {
303- "include": "#numeric"
304- }
305- ]
306- },
307- {
308- "begin": "(?<=\\s|^)(\\[)(?=.+?\\]\\s+[:=])",
309- "beginCaptures": {
310- "0": {
311- "name": "keyword.operator.coffee"
312- }
313- },
314- "end": "(\\]\\s*[:=])",
315- "endCaptures": {
316- "0": {
317- "name": "keyword.operator.coffee"
318- }
319- },
320- "name": "meta.variable.assignment.destructured.array.coffee",
321- "patterns": [
322- {
323- "include": "#variable_name"
324- },
325- {
326- "include": "#instance_variable"
327- },
328- {
329- "include": "#single_quoted_string"
330- },
331- {
332- "include": "#double_quoted_string"
333- },
334- {
335- "include": "#numeric"
336- }
337- ]
338- },
339- {
340- "captures": {
341- "1": {
342- "name": "entity.name.function.coffee"
343- },
344- "4": {
345- "name": "punctuation.definition.parameters.begin.coffee"
346- },
347- "5": {
348- "patterns": [
349- {
350- "captures": {
351- "1": {
352- "name": "variable.parameter.function.coffee"
353- },
354- "2": {
355- "name": "punctuation.separator.key-value.coffee"
356- },
357- "3": {
358- "name": "string.quoted.double.coffee"
359- },
360- "4": {
361- "name": "punctuation.definition.string.begin.coffee"
362- },
363- "5": {
364- "name": "punctuation.definition.string.end.coffee"
365- },
366- "6": {
367- "name": "string.quoted.single.coffee"
368- },
369- "7": {
370- "name": "punctuation.definition.string.begin.coffee"
371- },
372- "8": {
373- "name": "punctuation.definition.string.end.coffee"
374- }
375- },
376- "match": "(?x)\n\t\t\t\t\t\t\t\t([^()\\s,]+)\n\t\t\t\t\t\t\t\t\\s+(=)\\s+\n\t\t\t\t\t\t\t\t(?:\n\t\t\t\t\t\t\t\t\t((\")[^\"]*(\"))\n\t\t\t\t\t\t\t\t | ((')[^']*('))\n\t\t\t\t\t\t\t\t)"
377- },
378- {
379- "match": "[^()\\s,]+",
380- "name": "variable.parameter.function.coffee"
381- },
382- {
383- "match": ",",
384- "name": "punctuation.separator.arguments.coffee"
385- }
386- ]
387- },
388- "6": {
389- "name": "punctuation.definition.parameters.begin.coffee"
390- },
391- "7": {
392- "name": "storage.type.function.coffee"
393- }
394- },
395- "match": "(?x)\n\t\t\t\t(?<=^|\\s)\n\t\t\t\t(?=@?[a-zA-Z\\$_])\n\t\t\t\t(\n\t\t\t\t\t@?[a-zA-Z\\$_](\\w|\\$|:|\\.)*\n\t\t\t\t\t\\s*\n\t\t\t\t\t(?=\n\t\t\t\t\t\t[:=]\n\t\t\t\t\t\t(\\s*(\\()(.*)(\\)))?\n\t\t\t\t\t\t\\s*\n\t\t\t\t\t\t([=-]>)\n\t\t\t\t\t)\n\t\t\t\t)\n\t\t\t",
396- "name": "meta.function.coffee"
397- },
398- {
399- "match": "(?x)\n\t\t\t\t\\b\n\t\t\t\t(?<!\\.|::)\n\t\t\t\t(true|on|yes)\n\t\t\t\t(?!\\s*[:=][^=])\n\t\t\t\t\\b",
400- "name": "constant.language.boolean.true.coffee"
401- },
402- {
403- "match": "(?x)\n\t\t\t\t\\b\n\t\t\t\t(?<!\\.|::)\n\t\t\t\t(false|off|no)\n\t\t\t\t(?!\\s*[:=][^=])\n\t\t\t\t\\b",
404- "name": "constant.language.boolean.false.coffee"
405- },
406- {
407- "match": "@?\\b(?!class|subclass|extends|decodeURI(Component)?|encodeURI(Component)?|eval|parse(Float|Int)|require)\\w+(?=\\s+(?!(of|in|then|is|isnt|and|or|for|else|when|not|if)\\s)(?=(@?\\w+|\\->|\\-\\d|\\[|\\{|\"|'))|(?=\\())",
408- "name": "entity.name.function.coffee"
409- },
410- {
411- "match": "[=-]>",
412- "name": "storage.type.function.coffee"
413- },
414- {
415- "match": "(?x)\n\t\t\t\t\\b\n\t\t\t\t(?<!\\.|::)\n\t\t\t\tnull\n\t\t\t\t(?!\\s*[:=][^=])\n\t\t\t\t\\b",
416- "name": "constant.language.null.coffee"
417- },
418- {
419- "match": "(?x)\n\t\t\t\t\\b\n\t\t\t\t(?<!\\.|::)\n\t\t\t\t(extends)\n\t\t\t\t(?!\\s*[:=][^=])\n\t\t\t\t\\b",
420- "name": "variable.language.coffee"
421- },
422- {
423- "match": "\\b(?<!\\.)this(?!\\s*[:=])\\b",
424- "name": "variable.language.this.coffee"
425- },
426- {
427- "captures": {
428- "1": {
429- "name": "storage.type.class.coffee"
430- },
431- "2": {
432- "name": "keyword.control.inheritance.coffee"
433- },
434- "3": {
435- "name": "entity.other.inherited-class.coffee"
436- }
437- },
438- "match": "(?x)\n\t\t\t\t\t(?<=\\s|^|\\[|\\()\n (class\\b)\n\t\t\t\t\t(?:\n\t\t\t\t\t\t\\s+(extends)\\s+\n\t\t\t\t\t\t(@?[a-zA-Z\\$\\._][\\w\\.]*)\n\t\t\t\t\t)",
439- "name": "meta.class.coffee"
440- },
441- {
442- "captures": {
443- "1": {
444- "name": "storage.type.class.coffee"
445- },
446- "2": {
447- "name": "entity.name.type.class.coffee"
448- },
449- "3": {
450- "name": "keyword.control.inheritance.coffee"
451- },
452- "4": {
453- "name": "entity.other.inherited-class.coffee"
454- }
455- },
456- "match": "(?x)\n\t\t\t (?<=\\s|^|\\[|\\()\n\t\t\t\t\t(class\\b)\n\t\t\t\t\t\\s+\n\t\t\t\t\t(@?[a-zA-Z\\$_][\\w\\.]*)?\n\t\t\t\t\t(?:\n\t\t\t\t\t\t\\s+(extends)\\s+\n\t\t\t\t\t\t(@?[a-zA-Z\\$\\._][\\w\\.]*)\n\t\t\t\t\t)?",
457- "name": "meta.class.coffee"
458- },
459- {
460- "match": "\\b(debugger|\\\\)\\b",
461- "name": "keyword.other.coffee"
462- },
463- {
464- "match": "(?x)\n\t\t\t\t\\b(\n\t\t\t\t\tArray\n\t\t\t\t | ArrayBuffer\n\t\t\t\t | Blob\n\t\t\t\t | Boolean\n\t\t\t\t | Date\n\t\t\t\t | document\n\t\t\t\t | Function\n\t\t\t\t | Int(8|16|32|64)Array\n\t\t\t\t | Math\n\t\t\t\t | Map\n\t\t\t\t | Number\n\t\t\t\t | Object\n\t\t\t\t | Proxy\n\t\t\t\t | RegExp\n\t\t\t\t | Set\n\t\t\t\t | String\n\t\t\t\t | WeakMap\n\t\t\t\t | window\n\t\t\t\t | Uint(8|16|32|64)Array\n\t\t\t\t | XMLHttpRequest\n\t\t\t\t)\\b",
465- "name": "support.class.coffee"
466- },
467- {
468- "match": "\\b(console)\\b",
469- "name": "entity.name.type.object.coffee"
470- },
471- {
472- "match": "((?<=console\\.)(debug|warn|info|log|error|time|timeEnd|assert))\\b",
473- "name": "support.function.console.coffee"
474- },
475- {
476- "match": "(?x)\n\t\t\t\t\\b(\n\t\t\t\t\tdecodeURI(Component)?\n\t\t\t\t | encodeURI(Component)?\n\t\t\t\t | eval\n\t\t\t\t | parse(Float|Int)\n\t\t\t\t | require\n\t\t\t\t)\\b",
477- "name": "support.function.coffee"
478- },
479- {
480- "match": "(?x)\n\t\t\t\t(\n\t\t\t\t\t(?<=\\.)\n\t\t\t\t\t(\n\t\t\t\t\t\tapply\n\t\t\t\t\t | call\n\t\t\t\t\t | concat\n\t\t\t\t\t | every\n\t\t\t\t\t | filter\n\t\t\t\t\t | forEach\n\t\t\t\t\t | from\n\t\t\t\t\t | hasOwnProperty\n\t\t\t\t\t | indexOf\n\t\t\t\t\t | isPrototypeOf\n\t\t\t\t\t | join\n\t\t\t\t\t | lastIndexOf\n\t\t\t\t\t | map\n\t\t\t\t\t | of\n\t\t\t\t\t | pop\n\t\t\t\t\t | propertyIsEnumerable\n\t\t\t\t\t | push\n\t\t\t\t\t | reduce(Right)?\n\t\t\t\t\t | reverse\n\t\t\t\t\t | shift\n\t\t\t\t\t | slice\n\t\t\t\t\t | some\n\t\t\t\t\t | sort\n\t\t\t\t\t | splice\n\t\t\t\t\t | to(Locale)?String\n\t\t\t\t\t | unshift\n\t\t\t\t\t | valueOf\n\t\t\t\t\t)\n\t\t\t\t)\\b",
481- "name": "support.function.method.array.coffee"
482- },
483- {
484- "match": "((?<=Array\\.)(isArray))\\b",
485- "name": "support.function.static.array.coffee"
486- },
487- {
488- "match": "(?x)\n\t\t\t\t(\n\t\t\t\t\t(?<=Object\\.)\n\t\t\t\t\t(\n\t\t\t\t\t\tcreate\n\t\t\t\t\t | definePropert(ies|y)\n\t\t\t\t\t | freeze\n\t\t\t\t\t | getOwnProperty(Descriptors?|Names)\n\t\t\t\t\t | getProperty(Descriptor|Names)\n\t\t\t\t\t | getPrototypeOf\n\t\t\t\t\t | is(Extensible|Frozen|Sealed)?\n\t\t\t\t\t | isnt\n\t\t\t\t\t | keys\n\t\t\t\t\t | preventExtensions\n\t\t\t\t\t | seal\n\t\t\t\t\t)\n\t\t\t\t)\\b",
489- "name": "support.function.static.object.coffee"
490- },
491- {
492- "match": "(?x)\n\t\t\t\t(\n\t\t\t\t\t(?<=Math\\.)\n\t\t\t\t\t(\n\t\t\t\t\t\tabs\n\t\t\t\t\t | acos\n\t\t\t\t\t | acosh\n\t\t\t\t\t | asin\n\t\t\t\t\t | asinh\n\t\t\t\t\t | atan\n\t\t\t\t\t | atan2\n\t\t\t\t\t | atanh\n\t\t\t\t\t | ceil\n\t\t\t\t\t | cos\n\t\t\t\t\t | cosh\n\t\t\t\t\t | exp\n\t\t\t\t\t | expm1\n\t\t\t\t\t | floor\n\t\t\t\t\t | hypot\n\t\t\t\t\t | log\n\t\t\t\t\t | log10\n\t\t\t\t\t | log1p\n\t\t\t\t\t | log2\n\t\t\t\t\t | max\n\t\t\t\t\t | min\n\t\t\t\t\t | pow\n\t\t\t\t\t | random\n\t\t\t\t\t | round\n\t\t\t\t\t | sign\n\t\t\t\t\t | sin\n\t\t\t\t\t | sinh\n\t\t\t\t\t | sqrt\n\t\t\t\t\t | tan\n\t\t\t\t\t | tanh\n\t\t\t\t\t | trunc\n\t\t\t\t\t)\n\t\t\t\t)\\b",
493- "name": "support.function.static.math.coffee"
494- },
495- {
496- "match": "(?x)\n\t\t\t\t(\n\t\t\t\t\t(?<=Number\\.)\n\t\t\t\t\t(\n\t\t\t\t\t\tis(Finite|Integer|NaN)\n\t\t\t\t\t | toInteger\n\t\t\t\t\t)\n\t\t\t\t)\\b",
497- "name": "support.function.static.number.coffee"
498- },
499- {
500- "match": "\\b(Infinity|NaN|undefined)\\b",
501- "name": "constant.language.coffee"
502- },
503- {
504- "match": "\\;",
505- "name": "punctuation.terminator.statement.coffee"
506- },
507- {
508- "match": ",",
509- "name": "meta.delimiter.object.comma.coffee"
510- },
511- {
512- "match": "\\.",
513- "name": "meta.delimiter.method.period.coffee"
514- },
515- {
516- "match": "\\{|\\}",
517- "name": "meta.brace.curly.coffee"
518- },
519- {
520- "match": "\\(|\\)",
521- "name": "meta.brace.round.coffee"
522- },
523- {
524- "match": "\\[|\\]\\s*",
525- "name": "meta.brace.square.coffee"
526- },
527- {
528- "include": "#instance_variable"
529- },
530- {
531- "include": "#single_quoted_string"
532- },
533- {
534- "include": "#double_quoted_string"
535- },
536- {
537- "include": "#numeric"
538- }
539- ],
540- "repository": {
541- "double_quoted_string": {
542- "patterns": [
543- {
544- "begin": "\"",
545- "beginCaptures": {
546- "0": {
547- "name": "punctuation.definition.string.begin.coffee"
548- }
549- },
550- "end": "\"",
551- "endCaptures": {
552- "0": {
553- "name": "punctuation.definition.string.end.coffee"
554- }
555- },
556- "name": "string.quoted.double.coffee",
557- "patterns": [
558- {
559- "match": "(?x)\n\t\t\t\t\t\t\t\t\\\\(\n\t\t\t\t\t\t\t\t\tx\\h{2}\n\t\t\t\t\t\t\t\t | [0-2][0-7]{0,2}\n\t\t\t\t\t\t\t\t | 3[0-6][0-7]\n\t\t\t\t\t\t\t\t | 37[0-7]?\n\t\t\t\t\t\t\t\t | [4-7][0-7]?\n\t\t\t\t\t\t\t\t | .\n\t\t\t\t\t\t\t\t)",
560- "name": "constant.character.escape.coffee"
561- },
562- {
563- "include": "#interpolated_coffee"
564- }
565- ]
566- }
567- ]
568- },
569- "embedded_comment": {
570- "patterns": [
571- {
572- "captures": {
573- "1": {
574- "name": "punctuation.definition.comment.coffee"
575- }
576- },
577- "match": "(?<!\\\\)(#).*$\\n?",
578- "name": "comment.line.number-sign.coffee"
579- }
580- ]
581- },
582- "instance_variable": {
583- "patterns": [
584- {
585- "captures": {
586- "1": {
587- "name": "punctuation.definition.variable.coffee"
588- }
589- },
590- "match": "(@)([a-zA-Z_\\$]\\w*)?",
591- "name": "variable.other.readwrite.instance.coffee"
592- }
593- ]
594- },
595- "interpolated_coffee": {
596- "patterns": [
597- {
598- "begin": "#\\{",
599- "beginCaptures": {
600- "0": {
601- "name": "punctuation.section.embedded.begin.coffee"
602- }
603- },
604- "contentName": "source.coffee",
605- "end": "(\\})",
606- "endCaptures": {
607- "0": {
608- "name": "punctuation.section.embedded.end.coffee"
609- },
610- "1": {
611- "name": "source.coffee"
612- }
613- },
614- "name": "meta.embedded.line.coffee",
615- "patterns": [
616- {
617- "include": "$self"
618- }
619- ]
620- }
621- ]
622- },
623- "numeric": {
624- "patterns": [
625- {
626- "match": "(?x)\n\t\t\t\t\t\t(?<!\\$)\\b\n\t\t\t\t\t\t(\n\t\t\t\t\t\t\t(0([box])[0-9a-fA-F]+)\n\t\t\t\t\t\t | ([0-9]+(\\.[0-9]+)?(e[+\\-]?[0-9]+)?)\n\t\t\t\t\t\t)\\b",
627- "name": "constant.numeric.coffee"
628- }
629- ]
630- },
631- "single_quoted_string": {
632- "patterns": [
633- {
634- "begin": "'",
635- "beginCaptures": {
636- "0": {
637- "name": "punctuation.definition.string.begin.coffee"
638- }
639- },
640- "end": "'",
641- "endCaptures": {
642- "0": {
643- "name": "punctuation.definition.string.end.coffee"
644- }
645- },
646- "name": "string.quoted.single.coffee",
647- "patterns": [
648- {
649- "match": "(?x)\n\t\t\t\t\t\t\t\t\\\\(\n\t\t\t\t\t\t\t\t\tx\\h{2}\n\t\t\t\t\t\t\t\t | [0-2][0-7]{0,2}\n\t\t\t\t\t\t\t\t | 3[0-6][0-7]?\n\t\t\t\t\t\t\t\t | 37[0-7]?\n\t\t\t\t\t\t\t\t | [4-7][0-7]?\n\t\t\t\t\t\t\t\t | .\n\t\t\t\t\t\t\t\t)",
650- "name": "constant.character.escape.coffee"
651- }
652- ]
653- }
654- ]
655- },
656- "variable_name": {
657- "patterns": [
658- {
659- "match": "([a-zA-Z\\$_]\\w*(\\.\\w+)*)",
660- "name": "variable.other.assignment.coffee"
661- }
662- ]
663- }
664- },
665- "scopeName": "source.coffee",
666- "uuid": "5B520980-A7D5-4E10-8582-1A4C889A8DE5",
667- "version": "https://github.com/textmate/coffee-script.tmbundle/commit/da28450cf18a73595e298535c93c8370ae06994c"
668-}
No newline at the end of the file
2+ "comment": "CoffeeScript",
3+ "fileTypes": [
4+ "coffee",
5+ "Cakefile",
6+ "coffee.erb",
7+ "cake",
8+ "cjsx",
9+ "cson",
10+ "iced"
11+ ],
12+ "injections": {
13+ "string.regexp.block.coffee": {
14+ "patterns": [
15+ {
16+ "include": "#interpolated_coffee"
17+ },
18+ {
19+ "include": "#embedded_comment"
20+ }
21+ ]
22+ }
23+ },
24+ "keyEquivalent": "^~C",
25+ "name": "CoffeeScript",
26+ "patterns": [
27+ {
28+ "captures": {
29+ "1": {
30+ "name": "punctuation.definition.parameters.begin.coffee"
31+ },
32+ "2": {
33+ "patterns": [
34+ {
35+ "captures": {
36+ "1": {
37+ "name": "variable.parameter.function.coffee"
38+ },
39+ "2": {
40+ "name": "punctuation.separator.key-value.coffee"
41+ },
42+ "3": {
43+ "name": "string.quoted.double.coffee"
44+ },
45+ "4": {
46+ "name": "punctuation.definition.string.begin.coffee"
47+ },
48+ "5": {
49+ "name": "punctuation.definition.string.end.coffee"
50+ },
51+ "6": {
52+ "name": "string.quoted.single.coffee"
53+ },
54+ "7": {
55+ "name": "punctuation.definition.string.begin.coffee"
56+ },
57+ "8": {
58+ "name": "punctuation.definition.string.end.coffee"
59+ }
60+ },
61+ "match": "(?x)\n\t\t\t\t\t\t\t\t([^()\\s,]+)\n\t\t\t\t\t\t\t\t\\s+(=)\\s+\n\t\t\t\t\t\t\t\t(?:\n\t\t\t\t\t\t\t\t\t((\")[^\"]*(\"))\n\t\t\t\t\t\t\t\t | ((')[^']*('))\n\t\t\t\t\t\t\t\t)"
62+ },
63+ {
64+ "match": "[^()\\s,]+",
65+ "name": "variable.parameter.function.coffee"
66+ },
67+ {
68+ "match": ",",
69+ "name": "punctuation.separator.arguments.coffee"
70+ }
71+ ]
72+ },
73+ "3": {
74+ "name": "punctuation.definition.parameters.begin.coffee"
75+ },
76+ "4": {
77+ "name": "storage.type.function.coffee"
78+ }
79+ },
80+ "comment": "match stuff like: a -> … ",
81+ "match": "(\\()([^()]*?)(\\))\\s*([=-]>)",
82+ "name": "meta.inline.function.coffee"
83+ },
84+ {
85+ "captures": {
86+ "1": {
87+ "name": "keyword.operator.new.coffee"
88+ },
89+ "4": {
90+ "name": "storage.type.class.coffee"
91+ },
92+ "6": {
93+ "name": "entity.name.type.instance.coffee"
94+ },
95+ "7": {
96+ "name": "entity.name.type.instance.coffee"
97+ }
98+ },
99+ "match": "(new)\\s+(((class)(\\s+(\\w+(?:\\.\\w*)*))?)|(\\w+(?:\\.\\w*)*))",
100+ "name": "meta.class.instance.constructor"
101+ },
102+ {
103+ "begin": "'''",
104+ "beginCaptures": {
105+ "0": {
106+ "name": "punctuation.definition.string.begin.coffee"
107+ }
108+ },
109+ "end": "'''",
110+ "endCaptures": {
111+ "0": {
112+ "name": "punctuation.definition.string.end.coffee"
113+ }
114+ },
115+ "name": "string.unquoted.heredoc.coffee"
116+ },
117+ {
118+ "begin": "\"\"\"",
119+ "beginCaptures": {
120+ "0": {
121+ "name": "punctuation.definition.string.begin.coffee"
122+ }
123+ },
124+ "end": "\"\"\"",
125+ "endCaptures": {
126+ "0": {
127+ "name": "punctuation.definition.string.end.coffee"
128+ }
129+ },
130+ "name": "string.quoted.double.heredoc.coffee",
131+ "patterns": [
132+ {
133+ "match": "\\\\.",
134+ "name": "constant.character.escape.coffee"
135+ },
136+ {
137+ "include": "#interpolated_coffee"
138+ }
139+ ]
140+ },
141+ {
142+ "begin": "(?=`)",
143+ "end": "(?<=`)",
144+ "name": "meta.embedded.line.coffee",
145+ "patterns": [
146+ {
147+ "begin": "`",
148+ "beginCaptures": {
149+ "0": {
150+ "name": "punctuation.definition.string.begin.coffee"
151+ }
152+ },
153+ "contentName": "source.js",
154+ "end": "(`)",
155+ "endCaptures": {
156+ "0": {
157+ "name": "punctuation.definition.string.end.coffee"
158+ },
159+ "1": {
160+ "name": "source.js"
161+ }
162+ },
163+ "name": "string.other.embedded.javascript.coffee",
164+ "patterns": [
165+ {
166+ "include": "source.js"
167+ }
168+ ]
169+ }
170+ ]
171+ },
172+ {
173+ "begin": "(?<!#)###(?!#)",
174+ "captures": {
175+ "0": {
176+ "name": "punctuation.definition.comment.coffee"
177+ }
178+ },
179+ "end": "###(?:[ \\t]*\\n)",
180+ "name": "comment.block.coffee",
181+ "patterns": [
182+ {
183+ "match": "(?<=^|\\s)@\\w*(?=\\s)",
184+ "name": "storage.type.annotation.coffeescript"
185+ }
186+ ]
187+ },
188+ {
189+ "begin": "(^[ \\t]+)?(?=#)",
190+ "beginCaptures": {
191+ "1": {
192+ "name": "punctuation.whitespace.comment.leading.coffee"
193+ }
194+ },
195+ "end": "(?!\\G)",
196+ "patterns": [
197+ {
198+ "begin": "#",
199+ "beginCaptures": {
200+ "0": {
201+ "name": "punctuation.definition.comment.coffee"
202+ }
203+ },
204+ "end": "\\n",
205+ "name": "comment.line.number-sign.coffee"
206+ }
207+ ]
208+ },
209+ {
210+ "begin": "/{3}",
211+ "beginCaptures": {
212+ "0": {
213+ "name": "punctuation.definition.string.begin.coffee"
214+ }
215+ },
216+ "end": "(/{3})[imgy]{0,4}",
217+ "endCaptures": {
218+ "1": {
219+ "name": "punctuation.definition.string.end.coffee"
220+ }
221+ },
222+ "name": "string.regexp.block.coffee",
223+ "patterns": [
224+ {
225+ "include": "source.js.regexp"
226+ }
227+ ]
228+ },
229+ {
230+ "begin": "/(?![\\s=/*+{}?])",
231+ "beginCaptures": {
232+ "0": {
233+ "name": "punctuation.definition.string.begin.coffee"
234+ }
235+ },
236+ "end": "(/)[igmy]{0,4}(?![a-zA-Z0-9])",
237+ "endCaptures": {
238+ "1": {
239+ "name": "punctuation.definition.string.end.coffee"
240+ }
241+ },
242+ "name": "string.regexp.coffee",
243+ "patterns": [
244+ {
245+ "include": "source.js.regexp"
246+ }
247+ ]
248+ },
249+ {
250+ "match": "(?x)\n\t\t\t\t\\b\n\t\t\t\t(?<![\\.\\$])\n\t\t\t\t(\n\t\t\t\t\tbreak\n\t\t\t\t | by\n\t\t\t\t | catch\n\t\t\t\t | continue\n\t\t\t\t | else\n\t\t\t\t | finally\n\t\t\t\t | for\n\t\t\t\t | in\n\t\t\t\t | of\n\t\t\t\t | if\n\t\t\t\t | return\n\t\t\t\t | switch\n\t\t\t\t | then\n\t\t\t\t | throw\n\t\t\t\t | try\n\t\t\t\t | unless\n\t\t\t\t | when\n\t\t\t\t | while\n\t\t\t\t | until\n\t\t\t\t | loop\n\t\t\t\t | do\n\t\t\t\t | (?<=for)\\s+own\n\t\t\t\t)\n\t\t\t\t(?!\\s*:)\n\t\t\t\t\\b\n\t\t\t",
251+ "name": "keyword.control.coffee"
252+ },
253+ {
254+ "match": "(?x)\n (and|or|<<|>>>?|(?<!\\()\\/|[=!<>*%+\\-&^])?=(?!>)\n | [!%^*\\/~?:]\n | \\-?\\-(?!>)\n | \\+\\+?\n | <>\n | <\n | >\n | &&?\n | \\.\\.\\.?\n | \\|\\|?\n | \\b(?<![\\.\\$])(instanceof|new|delete|typeof|and|or|is|isnt|not|super)(?!\\s*:)\\b\n\t\t\t",
255+ "name": "keyword.operator.coffee"
256+ },
257+ {
258+ "match": "(?x)\n\t\t\t\t\\b\n\t\t\t\t(?<![\\.\\$])\n\t\t\t\t(\n\t\t\t\t\t case\n | default\n | function\n | var\n | void\n | with\n | const\n | let\n | enum\n | export\n | import\n | native\n | __hasProp\n | __extends\n | __slice\n | __bind\n | __indexOf\n | implements\n | interface\n | package\n | private\n | protected\n | public\n | static\n | yield\n )\n\t\t\t\t(?!\\s*:)\n\t\t\t\t\\b\n\t\t\t",
259+ "name": "keyword.other.reserved.coffee"
260+ },
261+ {
262+ "captures": {
263+ "1": {
264+ "name": "variable.other.assignment.coffee"
265+ },
266+ "4": {
267+ "name": "punctuation.separator.key-value"
268+ },
269+ "5": {
270+ "name": "keyword.operator.coffee"
271+ }
272+ },
273+ "match": "(?x)\n\t\t\t\t(?:\n\t\t\t\t\t([a-zA-Z\\$_](\\w|\\$|\\.)*)\n\t\t\t\t\t\\s*\n\t\t\t\t\t(?!\\::)\n\t\t\t\t\t((:)|((?:or|and|[-+/&%*?])?=)(?![>=]))\n\t\t\t\t\t(?!\n\t\t\t\t\t\t(\n\t\t\t\t\t\t\t\\s*\\(.*\\)\n\t\t\t\t\t\t)?\n\t\t\t\t\t\t\\s*\n\t\t\t\t\t\t([=-]>)\n\t\t\t\t\t)\n\t\t\t\t)"
274+ },
275+ {
276+ "begin": "(?<=\\s|^)(\\{)(?=.+?\\}\\s+[:=])",
277+ "beginCaptures": {
278+ "0": {
279+ "name": "keyword.operator.coffee"
280+ }
281+ },
282+ "end": "(\\}\\s*[:=])",
283+ "endCaptures": {
284+ "0": {
285+ "name": "keyword.operator.coffee"
286+ }
287+ },
288+ "name": "meta.variable.assignment.destructured.object.coffee",
289+ "patterns": [
290+ {
291+ "include": "#variable_name"
292+ },
293+ {
294+ "include": "#instance_variable"
295+ },
296+ {
297+ "include": "#single_quoted_string"
298+ },
299+ {
300+ "include": "#double_quoted_string"
301+ },
302+ {
303+ "include": "#numeric"
304+ }
305+ ]
306+ },
307+ {
308+ "begin": "(?<=\\s|^)(\\[)(?=.+?\\]\\s+[:=])",
309+ "beginCaptures": {
310+ "0": {
311+ "name": "keyword.operator.coffee"
312+ }
313+ },
314+ "end": "(\\]\\s*[:=])",
315+ "endCaptures": {
316+ "0": {
317+ "name": "keyword.operator.coffee"
318+ }
319+ },
320+ "name": "meta.variable.assignment.destructured.array.coffee",
321+ "patterns": [
322+ {
323+ "include": "#variable_name"
324+ },
325+ {
326+ "include": "#instance_variable"
327+ },
328+ {
329+ "include": "#single_quoted_string"
330+ },
331+ {
332+ "include": "#double_quoted_string"
333+ },
334+ {
335+ "include": "#numeric"
336+ }
337+ ]
338+ },
339+ {
340+ "captures": {
341+ "1": {
342+ "name": "entity.name.function.coffee"
343+ },
344+ "4": {
345+ "name": "punctuation.definition.parameters.begin.coffee"
346+ },
347+ "5": {
348+ "patterns": [
349+ {
350+ "captures": {
351+ "1": {
352+ "name": "variable.parameter.function.coffee"
353+ },
354+ "2": {
355+ "name": "punctuation.separator.key-value.coffee"
356+ },
357+ "3": {
358+ "name": "string.quoted.double.coffee"
359+ },
360+ "4": {
361+ "name": "punctuation.definition.string.begin.coffee"
362+ },
363+ "5": {
364+ "name": "punctuation.definition.string.end.coffee"
365+ },
366+ "6": {
367+ "name": "string.quoted.single.coffee"
368+ },
369+ "7": {
370+ "name": "punctuation.definition.string.begin.coffee"
371+ },
372+ "8": {
373+ "name": "punctuation.definition.string.end.coffee"
374+ }
375+ },
376+ "match": "(?x)\n\t\t\t\t\t\t\t\t([^()\\s,]+)\n\t\t\t\t\t\t\t\t\\s+(=)\\s+\n\t\t\t\t\t\t\t\t(?:\n\t\t\t\t\t\t\t\t\t((\")[^\"]*(\"))\n\t\t\t\t\t\t\t\t | ((')[^']*('))\n\t\t\t\t\t\t\t\t)"
377+ },
378+ {
379+ "match": "[^()\\s,]+",
380+ "name": "variable.parameter.function.coffee"
381+ },
382+ {
383+ "match": ",",
384+ "name": "punctuation.separator.arguments.coffee"
385+ }
386+ ]
387+ },
388+ "6": {
389+ "name": "punctuation.definition.parameters.begin.coffee"
390+ },
391+ "7": {
392+ "name": "storage.type.function.coffee"
393+ }
394+ },
395+ "match": "(?x)\n\t\t\t\t(?<=^|\\s)\n\t\t\t\t(?=@?[a-zA-Z\\$_])\n\t\t\t\t(\n\t\t\t\t\t@?[a-zA-Z\\$_](\\w|\\$|:|\\.)*\n\t\t\t\t\t\\s*\n\t\t\t\t\t(?=\n\t\t\t\t\t\t[:=]\n\t\t\t\t\t\t(\\s*(\\()(.*)(\\)))?\n\t\t\t\t\t\t\\s*\n\t\t\t\t\t\t([=-]>)\n\t\t\t\t\t)\n\t\t\t\t)\n\t\t\t",
396+ "name": "meta.function.coffee"
397+ },
398+ {
399+ "match": "(?x)\n\t\t\t\t\\b\n\t\t\t\t(?<!\\.|::)\n\t\t\t\t(true|on|yes)\n\t\t\t\t(?!\\s*[:=][^=])\n\t\t\t\t\\b",
400+ "name": "constant.language.boolean.true.coffee"
401+ },
402+ {
403+ "match": "(?x)\n\t\t\t\t\\b\n\t\t\t\t(?<!\\.|::)\n\t\t\t\t(false|off|no)\n\t\t\t\t(?!\\s*[:=][^=])\n\t\t\t\t\\b",
404+ "name": "constant.language.boolean.false.coffee"
405+ },
406+ {
407+ "match": "@?\\b(?!class|subclass|extends|decodeURI(Component)?|encodeURI(Component)?|eval|parse(Float|Int)|require)\\w+(?=\\s+(?!(of|in|then|is|isnt|and|or|for|else|when|not|if)\\s)(?=(@?\\w+|\\->|\\-\\d|\\[|\\{|\"|'))|(?=\\())",
408+ "name": "entity.name.function.coffee"
409+ },
410+ {
411+ "match": "[=-]>",
412+ "name": "storage.type.function.coffee"
413+ },
414+ {
415+ "match": "(?x)\n\t\t\t\t\\b\n\t\t\t\t(?<!\\.|::)\n\t\t\t\tnull\n\t\t\t\t(?!\\s*[:=][^=])\n\t\t\t\t\\b",
416+ "name": "constant.language.null.coffee"
417+ },
418+ {
419+ "match": "(?x)\n\t\t\t\t\\b\n\t\t\t\t(?<!\\.|::)\n\t\t\t\t(extends)\n\t\t\t\t(?!\\s*[:=][^=])\n\t\t\t\t\\b",
420+ "name": "variable.language.coffee"
421+ },
422+ {
423+ "match": "\\b(?<!\\.)this(?!\\s*[:=])\\b",
424+ "name": "variable.language.this.coffee"
425+ },
426+ {
427+ "captures": {
428+ "1": {
429+ "name": "storage.type.class.coffee"
430+ },
431+ "2": {
432+ "name": "keyword.control.inheritance.coffee"
433+ },
434+ "3": {
435+ "name": "entity.other.inherited-class.coffee"
436+ }
437+ },
438+ "match": "(?x)\n\t\t\t\t\t(?<=\\s|^|\\[|\\()\n (class\\b)\n\t\t\t\t\t(?:\n\t\t\t\t\t\t\\s+(extends)\\s+\n\t\t\t\t\t\t(@?[a-zA-Z\\$\\._][\\w\\.]*)\n\t\t\t\t\t)",
439+ "name": "meta.class.coffee"
440+ },
441+ {
442+ "captures": {
443+ "1": {
444+ "name": "storage.type.class.coffee"
445+ },
446+ "2": {
447+ "name": "entity.name.type.class.coffee"
448+ },
449+ "3": {
450+ "name": "keyword.control.inheritance.coffee"
451+ },
452+ "4": {
453+ "name": "entity.other.inherited-class.coffee"
454+ }
455+ },
456+ "match": "(?x)\n\t\t\t (?<=\\s|^|\\[|\\()\n\t\t\t\t\t(class\\b)\n\t\t\t\t\t\\s+\n\t\t\t\t\t(@?[a-zA-Z\\$_][\\w\\.]*)?\n\t\t\t\t\t(?:\n\t\t\t\t\t\t\\s+(extends)\\s+\n\t\t\t\t\t\t(@?[a-zA-Z\\$\\._][\\w\\.]*)\n\t\t\t\t\t)?",
457+ "name": "meta.class.coffee"
458+ },
459+ {
460+ "match": "\\b(debugger|\\\\)\\b",
461+ "name": "keyword.other.coffee"
462+ },
463+ {
464+ "match": "(?x)\n\t\t\t\t\\b(\n\t\t\t\t\tArray\n\t\t\t\t | ArrayBuffer\n\t\t\t\t | Blob\n\t\t\t\t | Boolean\n\t\t\t\t | Date\n\t\t\t\t | document\n\t\t\t\t | Function\n\t\t\t\t | Int(8|16|32|64)Array\n\t\t\t\t | Math\n\t\t\t\t | Map\n\t\t\t\t | Number\n\t\t\t\t | Object\n\t\t\t\t | Proxy\n\t\t\t\t | RegExp\n\t\t\t\t | Set\n\t\t\t\t | String\n\t\t\t\t | WeakMap\n\t\t\t\t | window\n\t\t\t\t | Uint(8|16|32|64)Array\n\t\t\t\t | XMLHttpRequest\n\t\t\t\t)\\b",
465+ "name": "support.class.coffee"
466+ },
467+ {
468+ "match": "\\b(console)\\b",
469+ "name": "entity.name.type.object.coffee"
470+ },
471+ {
472+ "match": "((?<=console\\.)(debug|warn|info|log|error|time|timeEnd|assert))\\b",
473+ "name": "support.function.console.coffee"
474+ },
475+ {
476+ "match": "(?x)\n\t\t\t\t\\b(\n\t\t\t\t\tdecodeURI(Component)?\n\t\t\t\t | encodeURI(Component)?\n\t\t\t\t | eval\n\t\t\t\t | parse(Float|Int)\n\t\t\t\t | require\n\t\t\t\t)\\b",
477+ "name": "support.function.coffee"
478+ },
479+ {
480+ "match": "(?x)\n\t\t\t\t(\n\t\t\t\t\t(?<=\\.)\n\t\t\t\t\t(\n\t\t\t\t\t\tapply\n\t\t\t\t\t | call\n\t\t\t\t\t | concat\n\t\t\t\t\t | every\n\t\t\t\t\t | filter\n\t\t\t\t\t | forEach\n\t\t\t\t\t | from\n\t\t\t\t\t | hasOwnProperty\n\t\t\t\t\t | indexOf\n\t\t\t\t\t | isPrototypeOf\n\t\t\t\t\t | join\n\t\t\t\t\t | lastIndexOf\n\t\t\t\t\t | map\n\t\t\t\t\t | of\n\t\t\t\t\t | pop\n\t\t\t\t\t | propertyIsEnumerable\n\t\t\t\t\t | push\n\t\t\t\t\t | reduce(Right)?\n\t\t\t\t\t | reverse\n\t\t\t\t\t | shift\n\t\t\t\t\t | slice\n\t\t\t\t\t | some\n\t\t\t\t\t | sort\n\t\t\t\t\t | splice\n\t\t\t\t\t | to(Locale)?String\n\t\t\t\t\t | unshift\n\t\t\t\t\t | valueOf\n\t\t\t\t\t)\n\t\t\t\t)\\b",
481+ "name": "support.function.method.array.coffee"
482+ },
483+ {
484+ "match": "((?<=Array\\.)(isArray))\\b",
485+ "name": "support.function.static.array.coffee"
486+ },
487+ {
488+ "match": "(?x)\n\t\t\t\t(\n\t\t\t\t\t(?<=Object\\.)\n\t\t\t\t\t(\n\t\t\t\t\t\tcreate\n\t\t\t\t\t | definePropert(ies|y)\n\t\t\t\t\t | freeze\n\t\t\t\t\t | getOwnProperty(Descriptors?|Names)\n\t\t\t\t\t | getProperty(Descriptor|Names)\n\t\t\t\t\t | getPrototypeOf\n\t\t\t\t\t | is(Extensible|Frozen|Sealed)?\n\t\t\t\t\t | isnt\n\t\t\t\t\t | keys\n\t\t\t\t\t | preventExtensions\n\t\t\t\t\t | seal\n\t\t\t\t\t)\n\t\t\t\t)\\b",
489+ "name": "support.function.static.object.coffee"
490+ },
491+ {
492+ "match": "(?x)\n\t\t\t\t(\n\t\t\t\t\t(?<=Math\\.)\n\t\t\t\t\t(\n\t\t\t\t\t\tabs\n\t\t\t\t\t | acos\n\t\t\t\t\t | acosh\n\t\t\t\t\t | asin\n\t\t\t\t\t | asinh\n\t\t\t\t\t | atan\n\t\t\t\t\t | atan2\n\t\t\t\t\t | atanh\n\t\t\t\t\t | ceil\n\t\t\t\t\t | cos\n\t\t\t\t\t | cosh\n\t\t\t\t\t | exp\n\t\t\t\t\t | expm1\n\t\t\t\t\t | floor\n\t\t\t\t\t | hypot\n\t\t\t\t\t | log\n\t\t\t\t\t | log10\n\t\t\t\t\t | log1p\n\t\t\t\t\t | log2\n\t\t\t\t\t | max\n\t\t\t\t\t | min\n\t\t\t\t\t | pow\n\t\t\t\t\t | random\n\t\t\t\t\t | round\n\t\t\t\t\t | sign\n\t\t\t\t\t | sin\n\t\t\t\t\t | sinh\n\t\t\t\t\t | sqrt\n\t\t\t\t\t | tan\n\t\t\t\t\t | tanh\n\t\t\t\t\t | trunc\n\t\t\t\t\t)\n\t\t\t\t)\\b",
493+ "name": "support.function.static.math.coffee"
494+ },
495+ {
496+ "match": "(?x)\n\t\t\t\t(\n\t\t\t\t\t(?<=Number\\.)\n\t\t\t\t\t(\n\t\t\t\t\t\tis(Finite|Integer|NaN)\n\t\t\t\t\t | toInteger\n\t\t\t\t\t)\n\t\t\t\t)\\b",
497+ "name": "support.function.static.number.coffee"
498+ },
499+ {
500+ "match": "\\b(Infinity|NaN|undefined)\\b",
501+ "name": "constant.language.coffee"
502+ },
503+ {
504+ "match": "\\;",
505+ "name": "punctuation.terminator.statement.coffee"
506+ },
507+ {
508+ "match": ",",
509+ "name": "meta.delimiter.object.comma.coffee"
510+ },
511+ {
512+ "match": "\\.",
513+ "name": "meta.delimiter.method.period.coffee"
514+ },
515+ {
516+ "match": "\\{|\\}",
517+ "name": "meta.brace.curly.coffee"
518+ },
519+ {
520+ "match": "\\(|\\)",
521+ "name": "meta.brace.round.coffee"
522+ },
523+ {
524+ "match": "\\[|\\]\\s*",
525+ "name": "meta.brace.square.coffee"
526+ },
527+ {
528+ "include": "#instance_variable"
529+ },
530+ {
531+ "include": "#single_quoted_string"
532+ },
533+ {
534+ "include": "#double_quoted_string"
535+ },
536+ {
537+ "include": "#numeric"
538+ }
539+ ],
540+ "repository": {
541+ "double_quoted_string": {
542+ "patterns": [
543+ {
544+ "begin": "\"",
545+ "beginCaptures": {
546+ "0": {
547+ "name": "punctuation.definition.string.begin.coffee"
548+ }
549+ },
550+ "end": "\"",
551+ "endCaptures": {
552+ "0": {
553+ "name": "punctuation.definition.string.end.coffee"
554+ }
555+ },
556+ "name": "string.quoted.double.coffee",
557+ "patterns": [
558+ {
559+ "match": "(?x)\n\t\t\t\t\t\t\t\t\\\\(\n\t\t\t\t\t\t\t\t\tx\\h{2}\n\t\t\t\t\t\t\t\t | [0-2][0-7]{0,2}\n\t\t\t\t\t\t\t\t | 3[0-6][0-7]\n\t\t\t\t\t\t\t\t | 37[0-7]?\n\t\t\t\t\t\t\t\t | [4-7][0-7]?\n\t\t\t\t\t\t\t\t | .\n\t\t\t\t\t\t\t\t)",
560+ "name": "constant.character.escape.coffee"
561+ },
562+ {
563+ "include": "#interpolated_coffee"
564+ }
565+ ]
566+ }
567+ ]
568+ },
569+ "embedded_comment": {
570+ "patterns": [
571+ {
572+ "captures": {
573+ "1": {
574+ "name": "punctuation.definition.comment.coffee"
575+ }
576+ },
577+ "match": "(?<!\\\\)(#).*$\\n?",
578+ "name": "comment.line.number-sign.coffee"
579+ }
580+ ]
581+ },
582+ "instance_variable": {
583+ "patterns": [
584+ {
585+ "captures": {
586+ "1": {
587+ "name": "punctuation.definition.variable.coffee"
588+ }
589+ },
590+ "match": "(@)([a-zA-Z_\\$]\\w*)?",
591+ "name": "variable.other.readwrite.instance.coffee"
592+ }
593+ ]
594+ },
595+ "interpolated_coffee": {
596+ "patterns": [
597+ {
598+ "begin": "#\\{",
599+ "beginCaptures": {
600+ "0": {
601+ "name": "punctuation.section.embedded.begin.coffee"
602+ }
603+ },
604+ "contentName": "source.coffee",
605+ "end": "(\\})",
606+ "endCaptures": {
607+ "0": {
608+ "name": "punctuation.section.embedded.end.coffee"
609+ },
610+ "1": {
611+ "name": "source.coffee"
612+ }
613+ },
614+ "name": "meta.embedded.line.coffee",
615+ "patterns": [
616+ {
617+ "include": "$self"
618+ }
619+ ]
620+ }
621+ ]
622+ },
623+ "numeric": {
624+ "patterns": [
625+ {
626+ "match": "(?x)\n\t\t\t\t\t\t(?<!\\$)\\b\n\t\t\t\t\t\t(\n\t\t\t\t\t\t\t(0([box])[0-9a-fA-F]+)\n\t\t\t\t\t\t | ([0-9]+(\\.[0-9]+)?(e[+\\-]?[0-9]+)?)\n\t\t\t\t\t\t)\\b",
627+ "name": "constant.numeric.coffee"
628+ }
629+ ]
630+ },
631+ "single_quoted_string": {
632+ "patterns": [
633+ {
634+ "begin": "'",
635+ "beginCaptures": {
636+ "0": {
637+ "name": "punctuation.definition.string.begin.coffee"
638+ }
639+ },
640+ "end": "'",
641+ "endCaptures": {
642+ "0": {
643+ "name": "punctuation.definition.string.end.coffee"
644+ }
645+ },
646+ "name": "string.quoted.single.coffee",
647+ "patterns": [
648+ {
649+ "match": "(?x)\n\t\t\t\t\t\t\t\t\\\\(\n\t\t\t\t\t\t\t\t\tx\\h{2}\n\t\t\t\t\t\t\t\t | [0-2][0-7]{0,2}\n\t\t\t\t\t\t\t\t | 3[0-6][0-7]?\n\t\t\t\t\t\t\t\t | 37[0-7]?\n\t\t\t\t\t\t\t\t | [4-7][0-7]?\n\t\t\t\t\t\t\t\t | .\n\t\t\t\t\t\t\t\t)",
650+ "name": "constant.character.escape.coffee"
651+ }
652+ ]
653+ }
654+ ]
655+ },
656+ "variable_name": {
657+ "patterns": [
658+ {
659+ "match": "([a-zA-Z\\$_]\\w*(\\.\\w+)*)",
660+ "name": "variable.other.assignment.coffee"
661+ }
662+ ]
663+ }
664+ },
665+ "scopeName": "source.coffee",
666+ "uuid": "5B520980-A7D5-4E10-8582-1A4C889A8DE5",
667+ "version": "https://github.com/textmate/coffee-script.tmbundle/commit/da28450cf18a73595e298535c93c8370ae06994c"
668+}
modified extensions/vscode/textmate-syntaxes/cshtml.json +149 −152
@@ -1,153 +1,150 @@
11 {
2- "name": "ASP.NET Razor",
3- "scopeName": "text.html.cshtml",
4- "fileTypes": [
5- "cshtml",
6- "gohtml"
7- ],
8- "patterns": [
9- {
10- "name": "section.embedded.source.cshtml",
11- "begin": "(@?([a-zA-Z0-9]+)?)(\\s[a-zA-Z0-9]+)?(\n|\r)?(\\{)",
12- "beginCaptures": {
13- "0": {
14- "name": "punctuation.section.embedded.begin.cshtml"
15- },
16- "1": {
17- "name": "keyword.control.cshtml"
18- }
19- },
20- "patterns": [
21- {
22- "name": "section.embedded.source.cshtml",
23- "begin": "(@?([a-zA-Z0-9]+)?)(\\s[a-zA-Z0-9]+)?(\n|\r)?(\\{)",
24- "beginCaptures": {
25- "0": {
26- "name": "punctuation.section.embedded.begin.cshtml"
27- },
28- "1": {
29- "name": "keyword.control.cshtml"
30- }
31- },
32- "patterns": [
33- {
34- "name": "string.quoted.single.cshtml",
35- "match": "'"
36- },
37- {
38- "include": "#embedded-code"
39- },
40- {
41- "include": "#comments"
42- },
43- {
44- "include": "source.cs"
45- },
46- {
47- "include": "text.html.basic"
48- }
49- ],
50- "end": "\\}",
51- "endCaptures": {
52- "0": {
53- "name": "punctuation.section.embedded.begin.cshtml"
54- }
55- }
56- },
57- {
58- "name": "string.quoted.single.cshtml",
59- "match": "'"
60- },
61- {
62- "include": "#embedded-code"
63- },
64- {
65- "include": "#comments"
66- },
67- {
68- "include": "text.html.basic"
69- }
70- ],
71- "end": "\\}",
72- "endCaptures": {
73- "0": {
74- "name": "punctuation.section.embedded.begin.cshtml"
75- }
76- },
77- "comments": "Simple multi-line code section"
78- },
79- {
80- "begin": "(@[a-zA-Z0-9]+)(\\s?)",
81- "captures": {
82- "0": {
83- "name": "section.embedded.begin.cshtml"
84- },
85- "1": {
86- "name": "keyword.control.cshtml"
87- }
88- },
89- "patterns": [
90- {
91- "match": "(([a-zA-Z0-9]+)(\\.)?)+?",
92- "captures": {
93- "2": {
94- "name": "entity.name.tag.source.cshtml"
95- },
96- "3": {
97- "name": "punctuation.separator.namespace.source.cshtml"
98- }
99- }
100- },
101- {
102- "include": "#embedded-code"
103- },
104- {
105- "include": "#comments"
106- },
107- {
108- "include": "source.cs"
109- },
110- {
111- "include": "text.html.basic"
112- }
113- ],
114- "end": "(\\n|\\s)",
115- "comments": "Covers single line Razor tags"
116- },
117- {
118- "include": "#comments"
119- },
120- {
121- "include": "text.html.basic"
122- }
123- ],
124- "repository": {
125- "embedded-code": {
126- "match": "(@?[a-zA-Z0-9]+)(\\.([a-zA-Z0-9]+))?",
127- "captures": {
128- "1": {
129- "name": "keyword.control.cshtml"
130- },
131- "3": {
132- "name": "entity.name.tag.source.cshtml"
133- }
134- },
135- "patterns": [
136- {
137- "include": "#comments"
138- }
139- ]
140- },
141- "comments": {
142- "begin": "@\\*",
143- "captures": {
144- "0": {
145- "name": "punctuation.definition.comment.source.cshtml"
146- }
147- },
148- "end": "\\*@",
149- "name": "comment.block.cshtml"
150- }
151- },
152- "version": "https://github.com/demyte/language-cshtml/commit/a49735dc7aef56ae772a3bcfd8e42c89895dcff4"
153-}
No newline at the end of the file
2+ "name": "ASP.NET Razor",
3+ "scopeName": "text.html.cshtml",
4+ "fileTypes": ["cshtml", "gohtml"],
5+ "patterns": [
6+ {
7+ "name": "section.embedded.source.cshtml",
8+ "begin": "(@?([a-zA-Z0-9]+)?)(\\s[a-zA-Z0-9]+)?(\n|\r)?(\\{)",
9+ "beginCaptures": {
10+ "0": {
11+ "name": "punctuation.section.embedded.begin.cshtml"
12+ },
13+ "1": {
14+ "name": "keyword.control.cshtml"
15+ }
16+ },
17+ "patterns": [
18+ {
19+ "name": "section.embedded.source.cshtml",
20+ "begin": "(@?([a-zA-Z0-9]+)?)(\\s[a-zA-Z0-9]+)?(\n|\r)?(\\{)",
21+ "beginCaptures": {
22+ "0": {
23+ "name": "punctuation.section.embedded.begin.cshtml"
24+ },
25+ "1": {
26+ "name": "keyword.control.cshtml"
27+ }
28+ },
29+ "patterns": [
30+ {
31+ "name": "string.quoted.single.cshtml",
32+ "match": "'"
33+ },
34+ {
35+ "include": "#embedded-code"
36+ },
37+ {
38+ "include": "#comments"
39+ },
40+ {
41+ "include": "source.cs"
42+ },
43+ {
44+ "include": "text.html.basic"
45+ }
46+ ],
47+ "end": "\\}",
48+ "endCaptures": {
49+ "0": {
50+ "name": "punctuation.section.embedded.begin.cshtml"
51+ }
52+ }
53+ },
54+ {
55+ "name": "string.quoted.single.cshtml",
56+ "match": "'"
57+ },
58+ {
59+ "include": "#embedded-code"
60+ },
61+ {
62+ "include": "#comments"
63+ },
64+ {
65+ "include": "text.html.basic"
66+ }
67+ ],
68+ "end": "\\}",
69+ "endCaptures": {
70+ "0": {
71+ "name": "punctuation.section.embedded.begin.cshtml"
72+ }
73+ },
74+ "comments": "Simple multi-line code section"
75+ },
76+ {
77+ "begin": "(@[a-zA-Z0-9]+)(\\s?)",
78+ "captures": {
79+ "0": {
80+ "name": "section.embedded.begin.cshtml"
81+ },
82+ "1": {
83+ "name": "keyword.control.cshtml"
84+ }
85+ },
86+ "patterns": [
87+ {
88+ "match": "(([a-zA-Z0-9]+)(\\.)?)+?",
89+ "captures": {
90+ "2": {
91+ "name": "entity.name.tag.source.cshtml"
92+ },
93+ "3": {
94+ "name": "punctuation.separator.namespace.source.cshtml"
95+ }
96+ }
97+ },
98+ {
99+ "include": "#embedded-code"
100+ },
101+ {
102+ "include": "#comments"
103+ },
104+ {
105+ "include": "source.cs"
106+ },
107+ {
108+ "include": "text.html.basic"
109+ }
110+ ],
111+ "end": "(\\n|\\s)",
112+ "comments": "Covers single line Razor tags"
113+ },
114+ {
115+ "include": "#comments"
116+ },
117+ {
118+ "include": "text.html.basic"
119+ }
120+ ],
121+ "repository": {
122+ "embedded-code": {
123+ "match": "(@?[a-zA-Z0-9]+)(\\.([a-zA-Z0-9]+))?",
124+ "captures": {
125+ "1": {
126+ "name": "keyword.control.cshtml"
127+ },
128+ "3": {
129+ "name": "entity.name.tag.source.cshtml"
130+ }
131+ },
132+ "patterns": [
133+ {
134+ "include": "#comments"
135+ }
136+ ]
137+ },
138+ "comments": {
139+ "begin": "@\\*",
140+ "captures": {
141+ "0": {
142+ "name": "punctuation.definition.comment.source.cshtml"
143+ }
144+ },
145+ "end": "\\*@",
146+ "name": "comment.block.cshtml"
147+ }
148+ },
149+ "version": "https://github.com/demyte/language-cshtml/commit/a49735dc7aef56ae772a3bcfd8e42c89895dcff4"
150+}
modified extensions/vscode/textmate-syntaxes/fsharp.json +493 −496
@@ -1,533 +1,530 @@
11 {
2- "name": "F#",
3- "scopeName": "source.fsharp",
4- "fileTypes": [
5- "fs"
6- ],
7- "foldingStartMarker": "",
8- "foldingStopMarker": "",
9- "patterns": [
10- {
11- "include": "#comments"
12- },
13- {
14- "include": "#constants"
15- },
16- {
17- "include": "#structure"
18- },
2+ "name": "F#",
3+ "scopeName": "source.fsharp",
4+ "fileTypes": ["fs"],
5+ "foldingStartMarker": "",
6+ "foldingStopMarker": "",
7+ "patterns": [
8+ {
9+ "include": "#comments"
10+ },
11+ {
12+ "include": "#constants"
13+ },
14+ {
15+ "include": "#structure"
16+ },
17+ {
18+ "include": "#attributes"
19+ },
20+ {
21+ "include": "#strings"
22+ },
23+ {
24+ "include": "#chars"
25+ },
26+ {
27+ "include": "#double_tick"
28+ },
29+ {
30+ "include": "#definition"
31+ },
32+ {
33+ "include": "#method_calls"
34+ },
35+ {
36+ "include": "#modules"
37+ },
38+ {
39+ "include": "#anonymous_functions"
40+ },
41+ {
42+ "include": "#keywords"
43+ },
44+ {
45+ "include": "#records"
46+ },
47+ {
48+ "include": "#cexprs"
49+ },
50+ {
51+ "include": "#text"
52+ }
53+ ],
54+ "repository": {
55+ "anonymous_functions": {
56+ "patterns": [
1957 {
20- "include": "#attributes"
21- },
58+ "name": "meta.function.anonymous",
59+ "begin": "\\b(fun)\\b",
60+ "end": "(->)",
61+ "beginCaptures": {
62+ "1": {
63+ "name": "keyword.other.function-definition.fsharp"
64+ }
65+ },
66+ "endCaptures": {
67+ "1": {
68+ "name": "keyword.other.fsharp"
69+ }
70+ },
71+ "patterns": [
72+ {
73+ "include": "#variables"
74+ }
75+ ]
76+ }
77+ ]
78+ },
79+ "attributes": {
80+ "patterns": [
2281 {
23- "include": "#strings"
24- },
82+ "name": "support.function.attribute.fsharp",
83+ "begin": "\\[\\<",
84+ "end": "\\>\\]",
85+ "patterns": [
86+ {
87+ "include": "$self"
88+ }
89+ ]
90+ }
91+ ]
92+ },
93+ "comments": {
94+ "patterns": [
2595 {
26- "include": "#chars"
96+ "name": "comment.block.fsharp",
97+ "begin": "(\\(\\*(?!\\)))",
98+ "end": "(\\*\\))",
99+ "beginCaptures": {
100+ "1": {
101+ "name": "comment.block.fsharp"
102+ }
103+ },
104+ "endCaptures": {
105+ "1": {
106+ "name": "comment.block.fsharp"
107+ }
108+ }
27109 },
28110 {
29- "include": "#double_tick"
30- },
111+ "name": "comment.line.double-slash.fsharp",
112+ "match": "//.*$"
113+ }
114+ ]
115+ },
116+ "constants": {
117+ "patterns": [
31118 {
32- "include": "#definition"
119+ "name": "constant.language.unit.fsharp",
120+ "match": "\\(\\)"
33121 },
34122 {
35- "include": "#method_calls"
123+ "name": "constant.numeric.floating-point.fsharp",
124+ "match": "\\b-?[0-9][0-9_]*((\\.([0-9][0-9_]*([eE][+-]??[0-9][0-9_]*)?)?)|([eE][+-]??[0-9][0-9_]*))"
36125 },
37126 {
38- "include": "#modules"
127+ "name": "constant.numeric.integer.nativeint.fsharp",
128+ "match": "\\b(-?((0(x|X)[0-9a-fA-F][0-9a-fA-F_]*)|(0(o|O)[0-7][0-7_]*)|(0(b|B)[01][01_]*)|([0-9][0-9_]*)))"
39129 },
40130 {
41- "include": "#anonymous_functions"
42- },
131+ "name": "constant.others.fsharp",
132+ "match": "\\b(true|false|null|unit)\\b"
133+ }
134+ ]
135+ },
136+ "definition": {
137+ "patterns": [
43138 {
44- "include": "#keywords"
45- },
139+ "name": "meta.binding.fsharp",
140+ "begin": "(val mutable|val|let mutable|let|member|static member|override|let!)(\\s+rec|mutable)?(\\s+private|internal|public)?\\s+(\\([^\\s-]*\\)|[_a-zA-Z]([_a-zA-Z0-9,\\.]|(?<=,)\\s)*)",
141+ "end": "((``.*``)|(with)|=|$)",
142+ "beginCaptures": {
143+ "1": {
144+ "name": "keyword.other.binding.fsharp"
145+ },
146+ "2": {
147+ "name": "keyword.other.function-recursive.fsharp"
148+ },
149+ "3": {
150+ "name": "keyword.other.access.fsharp"
151+ },
152+ "4": {
153+ "name": "variable.other.binding.fsharp"
154+ }
155+ },
156+ "endCaptures": {
157+ "1": {
158+ "name": "keyword.other.fsharp"
159+ },
160+ "2": {
161+ "name": "variable.other.binding.fsharp"
162+ },
163+ "3": {
164+ "name": "keyword.other.fsharp"
165+ }
166+ },
167+ "patterns": [
168+ {
169+ "include": "#variables"
170+ }
171+ ]
172+ }
173+ ]
174+ },
175+ "keywords": {
176+ "patterns": [
46177 {
47- "include": "#records"
178+ "name": "keyword.other.fsharp",
179+ "match": "\\b(function|yield!|yield|class|match|delegate|of|new|in|as|if|then|else|elif|for|begin|end|inherit|do|let\\!|return\\!|return|interface|with|member|try|finally|and|when|use|use\\!)\\b"
48180 },
49181 {
50- "include": "#cexprs"
182+ "name": "meta.preprocessor.fsharp",
183+ "begin": "^\\s*#\\s*(light)\\b",
184+ "end": "(\\s|$)"
51185 },
52186 {
53- "include": "#text"
187+ "name": "keyword.other.fsharp",
188+ "match": "(\\|>|\\->|\\<\\-|:>|:\\?>|:|\\[|\\]|\\;|<>|=|@|\\|\\||&&|{|}|\\||_|\\.\\.|\\+|\\-|\\*|\\/|\\^|\\!|\\>|\\>\\=|\\>\\>|\\<|\\<\\=|\\<\\<)"
54189 }
55- ],
56- "repository": {
57- "anonymous_functions": {
58- "patterns": [
59- {
60- "name": "meta.function.anonymous",
61- "begin": "\\b(fun)\\b",
62- "end": "(->)",
63- "beginCaptures": {
64- "1": {
65- "name": "keyword.other.function-definition.fsharp"
66- }
67- },
68- "endCaptures": {
69- "1": {
70- "name": "keyword.other.fsharp"
71- }
72- },
73- "patterns": [
74- {
75- "include": "#variables"
76- }
77- ]
78- }
79- ]
80- },
81- "attributes": {
82- "patterns": [
83- {
84- "name": "support.function.attribute.fsharp",
85- "begin": "\\[\\<",
86- "end": "\\>\\]",
87- "patterns": [
88- {
89- "include": "$self"
90- }
91- ]
92- }
93- ]
94- },
95- "comments": {
96- "patterns": [
97- {
98- "name": "comment.block.fsharp",
99- "begin": "(\\(\\*(?!\\)))",
100- "end": "(\\*\\))",
101- "beginCaptures": {
102- "1": {
103- "name": "comment.block.fsharp"
104- }
105- },
106- "endCaptures": {
107- "1": {
108- "name": "comment.block.fsharp"
109- }
110- }
111-
190+ ]
191+ },
192+ "modules": {
193+ "patterns": [
194+ {
195+ "name": "entity.name.section.fsharp",
196+ "begin": "\\b(namespace|module)(\\s+public|internal|private)?\\s+([a-zA-Z][a-zA-Z0-9'_. ]*)",
197+ "end": "(\\s|$)",
198+ "beginCaptures": {
199+ "1": {
200+ "name": "keyword.other.fsharp"
201+ },
202+ "2": {
203+ "name": "keyword.other.fsharp"
204+ },
205+ "3": {
206+ "name": "entity.name.section.fsharp"
207+ }
208+ },
209+ "patterns": [
210+ {
211+ "name": "entity.name.section.fsharp",
212+ "match": "(\\.)([A-Z][a-zA-Z0-9'_]*)",
213+ "captures": {
214+ "1": {
215+ "name": "punctuation.separator.namespace-reference.fsharp"
112216 },
113- {
114- "name": "comment.line.double-slash.fsharp",
115- "match": "//.*$"
217+ "2": {
218+ "name": "entity.name.section.fsharp"
116219 }
117- ]
220+ }
221+ }
222+ ]
118223 },
119- "constants": {
120- "patterns": [
121- {
122- "name": "constant.language.unit.fsharp",
123- "match": "\\(\\)"
124- },
125- {
126- "name": "constant.numeric.floating-point.fsharp",
127- "match": "\\b-?[0-9][0-9_]*((\\.([0-9][0-9_]*([eE][+-]??[0-9][0-9_]*)?)?)|([eE][+-]??[0-9][0-9_]*))"
128- },
129- {
130- "name": "constant.numeric.integer.nativeint.fsharp",
131- "match": "\\b(-?((0(x|X)[0-9a-fA-F][0-9a-fA-F_]*)|(0(o|O)[0-7][0-7_]*)|(0(b|B)[01][01_]*)|([0-9][0-9_]*)))"
224+ {
225+ "name": "meta.namespace.open.fsharp",
226+ "begin": "\\b(open)\\s+([A-Z][a-zA-Z0-9'_]*)(?=(\\.[A-Z][a-zA-Z0-9_]*)*)",
227+ "end": "(\\s|$)",
228+ "beginCaptures": {
229+ "1": {
230+ "name": "keyword.other.fsharp"
231+ },
232+ "2": {
233+ "name": "entity.name.section.fsharp"
234+ }
235+ },
236+ "patterns": [
237+ {
238+ "name": "entity.name.section.fsharp",
239+ "match": "(\\.)([a-zA-Z][a-zA-Z0-9'_]*)",
240+ "captures": {
241+ "1": {
242+ "name": "punctuation.separator.namespace-reference.fsharp"
132243 },
133- {
134- "name": "constant.others.fsharp",
135- "match": "\\b(true|false|null|unit)\\b"
136- }
137- ]
138- },
139- "definition": {
140- "patterns": [
141- {
142- "name": "meta.binding.fsharp",
143- "begin": "(val mutable|val|let mutable|let|member|static member|override|let!)(\\s+rec|mutable)?(\\s+private|internal|public)?\\s+(\\([^\\s-]*\\)|[_a-zA-Z]([_a-zA-Z0-9,\\.]|(?<=,)\\s)*)",
144- "end": "((``.*``)|(with)|=|$)",
145- "beginCaptures": {
146- "1": {
147- "name": "keyword.other.binding.fsharp"
148- },
149- "2": {
150- "name": "keyword.other.function-recursive.fsharp"
151- },
152- "3": {
153- "name": "keyword.other.access.fsharp"
154- },
155- "4": {
156- "name": "variable.other.binding.fsharp"
157- }
158- },
159- "endCaptures": {
160- "1": {
161- "name": "keyword.other.fsharp"
162- },
163- "2": {
164- "name": "variable.other.binding.fsharp"
165- },
166- "3": {
167- "name": "keyword.other.fsharp"
168- }
169- },
170- "patterns": [
171- {
172- "include": "#variables"
173- }
174- ]
244+ "2": {
245+ "name": "entity.name.section.fsharp"
175246 }
176- ]
247+ }
248+ }
249+ ]
177250 },
178- "keywords": {
179- "patterns": [
180- {
181- "name": "keyword.other.fsharp",
182- "match": "\\b(function|yield!|yield|class|match|delegate|of|new|in|as|if|then|else|elif|for|begin|end|inherit|do|let\\!|return\\!|return|interface|with|member|try|finally|and|when|use|use\\!)\\b"
183- },
184- {
185- "name": "meta.preprocessor.fsharp",
186- "begin": "^\\s*#\\s*(light)\\b",
187- "end": "(\\s|$)"
251+ {
252+ "name": "meta.namespace.alias.fsharp",
253+ "begin": "^\\s*(module)\\s+([A-Z][a-zA-Z0-9'_]*)\\s*(=)\\s*([A-Z][a-zA-Z0-9'_]*)",
254+ "end": "(\\s|$)",
255+ "beginCaptures": {
256+ "1": {
257+ "name": "keyword.other.namespace-definition.fsharp"
258+ },
259+ "2": {
260+ "name": "entity.name.type.namespace.fsharp"
261+ },
262+ "3": {
263+ "name": "punctuation.separator.namespace-definition.fsharp"
264+ },
265+ "4": {
266+ "name": "entity.name.section.fsharp"
267+ }
268+ },
269+ "patterns": [
270+ {
271+ "name": "entity.name.section.fsharp",
272+ "match": "(\\.)([A-Z][a-zA-Z0-9'_]*)",
273+ "captures": {
274+ "1": {
275+ "name": "punctuation.separator.namespace-reference.fsharp"
188276 },
189- {
190- "name": "keyword.other.fsharp",
191- "match": "(\\|>|\\->|\\<\\-|:>|:\\?>|:|\\[|\\]|\\;|<>|=|@|\\|\\||&&|{|}|\\||_|\\.\\.|\\+|\\-|\\*|\\/|\\^|\\!|\\>|\\>\\=|\\>\\>|\\<|\\<\\=|\\<\\<)"
277+ "2": {
278+ "name": "entity.name.section.fsharp"
192279 }
193- ]
280+ }
281+ }
282+ ]
283+ }
284+ ]
285+ },
286+ "strings": {
287+ "patterns": [
288+ {
289+ "contentName": "string.quoted.literalprintf.fsharp",
290+ "begin": "(sprintf|printf[n]|failwithf)\\s+((?=[^\\\\])(@\"))",
291+ "end": "(\")",
292+ "beginCaptures": {
293+ "2": {
294+ "name": "punctuation.definition.string.begin.fsharp"
295+ }
296+ },
297+ "endCaptures": {
298+ "1": {
299+ "name": "punctuation.definition.string.end.fsharp"
300+ }
301+ },
302+ "patterns": [
303+ {
304+ "name": "constant.character.string.escape.fsharp",
305+ "match": "\"(\")"
306+ },
307+ {
308+ "name": "constant.character.string.escape.format.fsharp",
309+ "match": "%[0\\-\\+# ]{0,3}(\\*|[0-9]{0,2})(\\.[0-9]{1,2})?([bcsdiuxXoeEfFgGMOAt]|\\+A)"
310+ }
311+ ]
194312 },
195- "modules": {
196- "patterns": [
197- {
198- "name": "entity.name.section.fsharp",
199- "begin": "\\b(namespace|module)(\\s+public|internal|private)?\\s+([a-zA-Z][a-zA-Z0-9'_. ]*)",
200- "end": "(\\s|$)",
201- "beginCaptures": {
202- "1": {
203- "name": "keyword.other.fsharp"
204- },
205- "2": {
206- "name": "keyword.other.fsharp"
207- },
208- "3": {
209- "name": "entity.name.section.fsharp"
210- }
211- },
212- "patterns": [
213- {
214- "name": "entity.name.section.fsharp",
215- "match": "(\\.)([A-Z][a-zA-Z0-9'_]*)",
216- "captures": {
217- "1": {
218- "name": "punctuation.separator.namespace-reference.fsharp"
219- },
220- "2": {
221- "name": "entity.name.section.fsharp"
222- }
223- }
224- }
225- ]
226- },
227- {
228- "name": "meta.namespace.open.fsharp",
229- "begin": "\\b(open)\\s+([A-Z][a-zA-Z0-9'_]*)(?=(\\.[A-Z][a-zA-Z0-9_]*)*)",
230- "end": "(\\s|$)",
231- "beginCaptures": {
232- "1": {
233- "name": "keyword.other.fsharp"
234- },
235- "2": {
236- "name": "entity.name.section.fsharp"
237- }
238- },
239- "patterns": [
240- {
241- "name": "entity.name.section.fsharp",
242- "match": "(\\.)([a-zA-Z][a-zA-Z0-9'_]*)",
243- "captures": {
244- "1": {
245- "name": "punctuation.separator.namespace-reference.fsharp"
246- },
247- "2": {
248- "name": "entity.name.section.fsharp"
249- }
250- }
251- }
252- ]
253- },
254- {
255- "name": "meta.namespace.alias.fsharp",
256- "begin": "^\\s*(module)\\s+([A-Z][a-zA-Z0-9'_]*)\\s*(=)\\s*([A-Z][a-zA-Z0-9'_]*)",
257- "end": "(\\s|$)",
258- "beginCaptures": {
259- "1": {
260- "name": "keyword.other.namespace-definition.fsharp"
261- },
262- "2": {
263- "name": "entity.name.type.namespace.fsharp"
264- },
265- "3": {
266- "name": "punctuation.separator.namespace-definition.fsharp"
267- },
268- "4": {
269- "name": "entity.name.section.fsharp"
270- }
271- },
272- "patterns": [
273- {
274- "name": "entity.name.section.fsharp",
275- "match": "(\\.)([A-Z][a-zA-Z0-9'_]*)",
276- "captures": {
277- "1": {
278- "name": "punctuation.separator.namespace-reference.fsharp"
279- },
280- "2": {
281- "name": "entity.name.section.fsharp"
282- }
283- }
284- }
285- ]
286- }
287- ]
313+ {
314+ "name": "string.quoted.literal.fsharp",
315+ "begin": "(?=[^\\\\])(@\")",
316+ "end": "(\")",
317+ "beginCaptures": {
318+ "1": {
319+ "name": "punctuation.definition.string.begin.fsharp"
320+ }
321+ },
322+ "endCaptures": {
323+ "1": {
324+ "name": "punctuation.definition.string.end.fsharp"
325+ }
326+ },
327+ "patterns": [
328+ {
329+ "name": "constant.character.string.escape.fsharp",
330+ "match": "\"(\")"
331+ }
332+ ]
288333 },
289- "strings": {
290- "patterns": [
291- {
292- "contentName": "string.quoted.literalprintf.fsharp",
293- "begin": "(sprintf|printf[n]|failwithf)\\s+((?=[^\\\\])(@\"))",
294- "end": "(\")",
295- "beginCaptures": {
296- "2": {
297- "name": "punctuation.definition.string.begin.fsharp"
298- }
299- },
300- "endCaptures": {
301- "1": {
302- "name": "punctuation.definition.string.end.fsharp"
303- }
304- },
305- "patterns": [
306- {
307- "name": "constant.character.string.escape.fsharp",
308- "match": "\"(\")"
309- },
310- {
311- "name": "constant.character.string.escape.format.fsharp",
312- "match": "%[0\\-\\+# ]{0,3}(\\*|[0-9]{0,2})(\\.[0-9]{1,2})?([bcsdiuxXoeEfFgGMOAt]|\\+A)"
313- }
314- ]
315- },
316- {
317- "name": "string.quoted.literal.fsharp",
318- "begin": "(?=[^\\\\])(@\")",
319- "end": "(\")",
320- "beginCaptures": {
321- "1": {
322- "name": "punctuation.definition.string.begin.fsharp"
323- }
324- },
325- "endCaptures": {
326- "1": {
327- "name": "punctuation.definition.string.end.fsharp"
328- }
329- },
330- "patterns": [
331- {
332- "name": "constant.character.string.escape.fsharp",
333- "match": "\"(\")"
334- }
335- ]
336- },
337- {
338- "contentName": "string.quoted.tripleprintf.fsharp",
339- "begin": "(sprintf|printf[n]|failwithf)\\s+((?=[^\\\\])(\"\"\"))",
340- "end": "(\"\"\")",
341- "beginCaptures": {
342- "2": {
343- "name": "punctuation.definition.string.begin.fsharp"
344- }
345- },
346- "endCaptures": {
347- "1": {
348- "name": "punctuation.definition.string.end.fsharp"
349- }
350- },
351- "patterns": [
352- {
353- "name": "constant.character.string.escape.format.fsharp",
354- "match": "%[0\\-\\+# ]{0,3}(\\*|[0-9]{0,2})(\\.[0-9]{1,2})?([bcsdiuxXoeEfFgGMOAt]|\\+A)"
355- }
356- ]
357- },
358- {
359- "name": "string.quoted.triple.fsharp",
360- "begin": "(?=[^\\\\])(\"\"\")",
361- "end": "(\"\"\")",
362- "beginCaptures": {
363- "1": {
364- "name": "punctuation.definition.string.begin.fsharp"
365- }
366- },
367- "endCaptures": {
368- "1": {
369- "name": "punctuation.definition.string.end.fsharp"
370- }
371- }
372- },
373- {
374- "contentName": "string.quoted.doubleprintf.fsharp",
375- "begin": "(sprintf|printf[n]|failwithf)\\s+((?=[^\\\\])(\"))",
376- "end": "(\")",
377- "beginCaptures": {
378- "2": {
379- "name": "punctuation.definition.string.begin.fsharp"
380- }
381- },
382- "endCaptures": {
383- "1": {
384- "name": "punctuation.definition.string.end.fsharp"
385- }
386- },
387- "patterns": [
388- {
389- "name": "punctuation.separator.string.ignore-eol.fsharp",
390- "match": "\\\\$[ \\t]*"
391- },
392- {
393- "name": "constant.character.string.escape.format.fsharp",
394- "match": "%[0\\-\\+# ]{0,3}(\\*|[0-9]{0,2})(\\.[0-9]{1,2})?([bcsdiuxXoeEfFgGMOAt]|\\+A)"
395- },
396- {
397- "name": "constant.character.string.escape.fsharp",
398- "match": "\\\\([\\\\''ntbr]|u[a-fA-F0-9]{4}|u[a-fA-F0-9]{8})"
399- },
400- {
401- "name": "invalid.illeagal.character.string.fsharp",
402- "match": "\\\\(?![\\\\''ntbr]|u[a-fA-F0-9]{4}|u[a-fA-F0-9]{8})."
403- }
404- ]
405- },
406-
407- {
408- "name": "string.quoted.double.fsharp",
409- "begin": "(?=[^\\\\])(\")",
410- "end": "(\")",
411- "beginCaptures": {
412- "1": {
413- "name": "punctuation.definition.string.begin.fsharp"
414- }
415- },
416- "endCaptures": {
417- "1": {
418- "name": "punctuation.definition.string.end.fsharp"
419- }
420- },
421- "patterns": [
422- {
423- "name": "punctuation.separator.string.ignore-eol.fsharp",
424- "match": "\\\\$[ \\t]*"
425- },
426- {
427- "name": "constant.character.string.escape.fsharp",
428- "match": "\\\\([\\\\''ntbr]|u[a-fA-F0-9]{4}|u[a-fA-F0-9]{8})"
429- },
430- {
431- "name": "invalid.illeagal.character.string.fsharp",
432- "match": "\\\\(?![\\\\''ntbr]|u[a-fA-F0-9]{4}|u[a-fA-F0-9]{8})."
433- }
434- ]
435- }
436- ]
334+ {
335+ "contentName": "string.quoted.tripleprintf.fsharp",
336+ "begin": "(sprintf|printf[n]|failwithf)\\s+((?=[^\\\\])(\"\"\"))",
337+ "end": "(\"\"\")",
338+ "beginCaptures": {
339+ "2": {
340+ "name": "punctuation.definition.string.begin.fsharp"
341+ }
342+ },
343+ "endCaptures": {
344+ "1": {
345+ "name": "punctuation.definition.string.end.fsharp"
346+ }
347+ },
348+ "patterns": [
349+ {
350+ "name": "constant.character.string.escape.format.fsharp",
351+ "match": "%[0\\-\\+# ]{0,3}(\\*|[0-9]{0,2})(\\.[0-9]{1,2})?([bcsdiuxXoeEfFgGMOAt]|\\+A)"
352+ }
353+ ]
437354 },
438- "variables": {
439- "patterns": [
440- {
441- "name": "constant.language.unit.fsharp",
442- "match": "\\(\\)"
443- },
444- {
445- "name": "variable.parameter.fsharp",
446- "match": "[a-zA-Z']\\w*"
447- }
448- ]
355+ {
356+ "name": "string.quoted.triple.fsharp",
357+ "begin": "(?=[^\\\\])(\"\"\")",
358+ "end": "(\"\"\")",
359+ "beginCaptures": {
360+ "1": {
361+ "name": "punctuation.definition.string.begin.fsharp"
362+ }
363+ },
364+ "endCaptures": {
365+ "1": {
366+ "name": "punctuation.definition.string.end.fsharp"
367+ }
368+ }
449369 },
450- "double_tick": {
451- "patterns": [
452- {
453- "name": "variable.other.binding.fsharp",
454- "match": "(``)(.*)(``)",
455- "captures": {
456- "1": {
457- "name": "string.quoted.single.fsharp"
458- },
459- "1": {
460- "name": "variable.other.binding.fsharp"
461- },
462- "3": {
463- "name": "string.quoted.single.fsharp"
464- }
465- }
466- }
467- ]
370+ {
371+ "contentName": "string.quoted.doubleprintf.fsharp",
372+ "begin": "(sprintf|printf[n]|failwithf)\\s+((?=[^\\\\])(\"))",
373+ "end": "(\")",
374+ "beginCaptures": {
375+ "2": {
376+ "name": "punctuation.definition.string.begin.fsharp"
377+ }
378+ },
379+ "endCaptures": {
380+ "1": {
381+ "name": "punctuation.definition.string.end.fsharp"
382+ }
383+ },
384+ "patterns": [
385+ {
386+ "name": "punctuation.separator.string.ignore-eol.fsharp",
387+ "match": "\\\\$[ \\t]*"
388+ },
389+ {
390+ "name": "constant.character.string.escape.format.fsharp",
391+ "match": "%[0\\-\\+# ]{0,3}(\\*|[0-9]{0,2})(\\.[0-9]{1,2})?([bcsdiuxXoeEfFgGMOAt]|\\+A)"
392+ },
393+ {
394+ "name": "constant.character.string.escape.fsharp",
395+ "match": "\\\\([\\\\''ntbr]|u[a-fA-F0-9]{4}|u[a-fA-F0-9]{8})"
396+ },
397+ {
398+ "name": "invalid.illeagal.character.string.fsharp",
399+ "match": "\\\\(?![\\\\''ntbr]|u[a-fA-F0-9]{4}|u[a-fA-F0-9]{8})."
400+ }
401+ ]
468402 },
469- "records": {
470- "patterns": [
471- {
472- "name": "record.fsharp",
473- "match": "(type)[\\s]+(private|internal|public)?[\\s]*([a-zA-Z0-9'<>^:,. ]+)((with)|(=)|(\\(\\)))",
474403
475- "captures": {
476- "1": {
477- "name": "keyword.other.fsharp"
478- },
479- "2": {
480- "name": "keyword.other.fsharp"
481- },
482- "3": {
483- "name": "entity.name.type.fsharp"
484- },
485- "5": {
486- "name": "keyword.other.fsharp"
487- },
488- "6": {
489- "name": "keyword.other.fsharp"
490- },
491- "7": {
492- "name": "constant.language.unit.fsharp"
493- }
494- }
495- }
496- ]
497- },
498- "cexprs": {
499- "patterns": [
500- {
501- "name": "cexpr.fsharp",
502- "match": "\\b([a-zA-Z]*\\s+\\{)",
503- "captures": {
504- "1": {
505- "name": "keyword.other.fsharp"
506- }
507- }
508- }
509- ]
510- },
511- "chars": {
512- "patterns": [
513- {
514- "name": "char.fsharp",
515- "match": "('\\\\?.')",
516- "captures": {
517- "1": {
518- "name": "string.quoted.single.fsharp"
519- }
520- }
521- }
522- ]
404+ {
405+ "name": "string.quoted.double.fsharp",
406+ "begin": "(?=[^\\\\])(\")",
407+ "end": "(\")",
408+ "beginCaptures": {
409+ "1": {
410+ "name": "punctuation.definition.string.begin.fsharp"
411+ }
412+ },
413+ "endCaptures": {
414+ "1": {
415+ "name": "punctuation.definition.string.end.fsharp"
416+ }
417+ },
418+ "patterns": [
419+ {
420+ "name": "punctuation.separator.string.ignore-eol.fsharp",
421+ "match": "\\\\$[ \\t]*"
422+ },
423+ {
424+ "name": "constant.character.string.escape.fsharp",
425+ "match": "\\\\([\\\\''ntbr]|u[a-fA-F0-9]{4}|u[a-fA-F0-9]{8})"
426+ },
427+ {
428+ "name": "invalid.illeagal.character.string.fsharp",
429+ "match": "\\\\(?![\\\\''ntbr]|u[a-fA-F0-9]{4}|u[a-fA-F0-9]{8})."
430+ }
431+ ]
432+ }
433+ ]
434+ },
435+ "variables": {
436+ "patterns": [
437+ {
438+ "name": "constant.language.unit.fsharp",
439+ "match": "\\(\\)"
523440 },
524- "text": {
525- "patterns": [
526- {
527- "name": "text.fsharp",
528- "match": "\\\\"
529- }
530- ]
441+ {
442+ "name": "variable.parameter.fsharp",
443+ "match": "[a-zA-Z']\\w*"
444+ }
445+ ]
446+ },
447+ "double_tick": {
448+ "patterns": [
449+ {
450+ "name": "variable.other.binding.fsharp",
451+ "match": "(``)(.*)(``)",
452+ "captures": {
453+ "1": {
454+ "name": "string.quoted.single.fsharp"
455+ },
456+ "1": {
457+ "name": "variable.other.binding.fsharp"
458+ },
459+ "3": {
460+ "name": "string.quoted.single.fsharp"
461+ }
462+ }
463+ }
464+ ]
465+ },
466+ "records": {
467+ "patterns": [
468+ {
469+ "name": "record.fsharp",
470+ "match": "(type)[\\s]+(private|internal|public)?[\\s]*([a-zA-Z0-9'<>^:,. ]+)((with)|(=)|(\\(\\)))",
471+
472+ "captures": {
473+ "1": {
474+ "name": "keyword.other.fsharp"
475+ },
476+ "2": {
477+ "name": "keyword.other.fsharp"
478+ },
479+ "3": {
480+ "name": "entity.name.type.fsharp"
481+ },
482+ "5": {
483+ "name": "keyword.other.fsharp"
484+ },
485+ "6": {
486+ "name": "keyword.other.fsharp"
487+ },
488+ "7": {
489+ "name": "constant.language.unit.fsharp"
490+ }
491+ }
492+ }
493+ ]
494+ },
495+ "cexprs": {
496+ "patterns": [
497+ {
498+ "name": "cexpr.fsharp",
499+ "match": "\\b([a-zA-Z]*\\s+\\{)",
500+ "captures": {
501+ "1": {
502+ "name": "keyword.other.fsharp"
503+ }
504+ }
505+ }
506+ ]
507+ },
508+ "chars": {
509+ "patterns": [
510+ {
511+ "name": "char.fsharp",
512+ "match": "('\\\\?.')",
513+ "captures": {
514+ "1": {
515+ "name": "string.quoted.single.fsharp"
516+ }
517+ }
518+ }
519+ ]
520+ },
521+ "text": {
522+ "patterns": [
523+ {
524+ "name": "text.fsharp",
525+ "match": "\\\\"
531526 }
527+ ]
532528 }
533-}
No newline at the end of the file
529+ }
530+}
modified extensions/vscode/textmate-syntaxes/go.json +608 −610
@@ -1,611 +1,609 @@
11 {
2- "scopeName": "source.go",
3- "name": "Go",
4- "comment": "Go language",
5- "fileTypes": [
6- "go"
7- ],
8- "foldingStartMarker": "({|\\()\\s*$",
9- "foldingStopMarker": "(}|\\))\\s*$",
10- "patterns": [
11- {
12- "comment": "Block comments",
13- "begin": "/\\*",
14- "end": "\\*/",
15- "captures": {
16- "0": {
17- "name": "punctuation.definition.comment.go"
18- }
19- },
20- "name": "comment.block.go"
21- },
22- {
23- "comment": "Line comments",
24- "begin": "//",
25- "beginCaptures": {
26- "0": {
27- "name": "punctuation.definition.comment.go"
28- }
29- },
30- "end": "$",
31- "name": "comment.line.double-slash.go"
32- },
33- {
34- "comment": "Interpreted string literals",
35- "begin": "\"",
36- "beginCaptures": {
37- "0": {
38- "name": "punctuation.definition.string.begin.go"
39- }
40- },
41- "end": "\"",
42- "endCaptures": {
43- "0": {
44- "name": "punctuation.definition.string.end.go"
45- }
46- },
47- "name": "string.quoted.double.go",
48- "patterns": [
49- {
50- "include": "#string_escaped_char"
51- },
52- {
53- "include": "#string_placeholder"
54- }
55- ]
56- },
57- {
58- "comment": "Raw string literals",
59- "begin": "`",
60- "beginCaptures": {
61- "0": {
62- "name": "punctuation.definition.string.begin.go"
63- }
64- },
65- "end": "`",
66- "endCaptures": {
67- "0": {
68- "name": "punctuation.definition.string.end.go"
69- }
70- },
71- "name": "string.quoted.raw.go",
72- "patterns": [
73- {
74- "include": "#string_placeholder"
75- }
76- ]
77- },
78- {
79- "comment": "Syntax error receiving channels",
80- "match": "<\\-([\\t ]+)chan\\b",
81- "captures": {
82- "1": {
83- "name": "invalid.illegal.receive-channel.go"
84- }
85- }
86- },
87- {
88- "comment": "Syntax error sending channels",
89- "match": "\\bchan([\\t ]+)<-",
90- "captures": {
91- "1": {
92- "name": "invalid.illegal.send-channel.go"
93- }
94- }
95- },
96- {
97- "comment": "Syntax error using slices",
98- "match": "\\[\\](\\s+)",
99- "captures": {
100- "1": {
101- "name": "invalid.illegal.slice.go"
102- }
103- }
104- },
105- {
106- "comment": "Syntax error numeric literals",
107- "match": "\\b0[0-7]*[89]\\d*\\b",
108- "name": "invalid.illegal.numeric.go"
109- },
110- {
111- "comment": "Built-in functions",
112- "match": "\\b(append|cap|close|complex|copy|delete|imag|len|make|new|panic|print|println|real|recover)\\b(?=\\()",
113- "name": "support.function.builtin.go"
114- },
115- {
116- "comment": "Function declarations",
117- "match": "^(\\bfunc\\b)(?:\\s+(\\([^\\)]+\\)\\s+)?([a-zA-Z_]\\w*)(?=\\())?",
118- "captures": {
119- "1": {
120- "name": "keyword.function.go"
121- },
122- "2": {
123- "patterns": [
124- {
125- "include": "#brackets"
126- },
127- {
128- "include": "#operators"
129- }
130- ]
131- },
132- "3": {
133- "name": "entity.name.function"
134- }
135- }
136- },
137- {
138- "comment": "Functions",
139- "match": "(\\bfunc\\b)|([a-zA-Z_]\\w*)(?=\\()",
140- "captures": {
141- "1": {
142- "name": "keyword.function.go"
143- },
144- "2": {
145- "name": "support.function.go"
146- }
147- }
148- },
149- {
150- "comment": "Floating-point literals",
151- "match": "(\\.\\d+([Ee][-+]\\d+)?i?)\\b|\\b\\d+\\.\\d*(([Ee][-+]\\d+)?i?\\b)?",
152- "name": "constant.numeric.floating-point.go"
153- },
154- {
155- "comment": "Integers",
156- "match": "\\b((0x[0-9a-fA-F]+)|(0[0-7]+i?)|(\\d+([Ee]\\d+)?i?)|(\\d+[Ee][-+]\\d+i?))\\b",
157- "name": "constant.numeric.integer.go"
158- },
159- {
160- "comment": "Language constants",
161- "match": "\\b(true|false|nil|iota)\\b",
162- "name": "constant.language.go"
163- },
164- {
165- "comment": "Package declarations",
166- "match": "(?<=package)\\s+([a-zA-Z_]\\w*)",
167- "captures": {
168- "1": {
169- "name": "entity.name.package.go"
170- }
171- }
172- },
173- {
174- "comment": "Single line import declarations",
175- "match": "(?<=import)(\\s+((?!\\s+\")[^\\s]*)?\\s*)((\")([^\"]*)(\"))",
176- "captures": {
177- "2": {
178- "name": "entity.alias.import.go"
179- },
180- "3": {
181- "name": "string.quoted.double.go"
182- },
183- "4": {
184- "name": "punctuation.definition.string.begin.go"
185- },
186- "5": {
187- "name": "entity.name.import.go"
188- },
189- "6": {
190- "name": "punctuation.definition.string.end.go"
191- }
192- }
193- },
194- {
195- "comment": "Multiline import declarations",
196- "begin": "(?<=import)\\s+(\\()",
197- "beginCaptures": {
198- "1": {
199- "name": "punctuation.other.bracket.round.go"
200- }
201- },
202- "patterns": [
203- {
204- "match": "((?!\\s+\")[^\\s]*)?\\s+((\")([^\"]*)(\"))",
205- "captures": {
206- "1": {
207- "name": "entity.alias.import.go"
208- },
209- "2": {
210- "name": "string.quoted.double.go"
211- },
212- "3": {
213- "name": "punctuation.definition.string.begin.go"
214- },
215- "4": {
216- "name": "entity.name.import.go"
217- },
218- "5": {
219- "name": "punctuation.definition.string.end.go"
220- }
221- }
222- }
223- ],
224- "end": "\\)",
225- "endCaptures": {
226- "0": {
227- "name": "punctuation.other.bracket.round.go"
228- }
229- }
230- },
231- {
232- "comment": "Type declarations",
233- "match": "(?<=type)\\s+([a-zA-Z_]\\w*)",
234- "captures": {
235- "1": {
236- "name": "entity.name.type.go"
237- }
238- }
239- },
240- {
241- "comment": "Shorthand variable declaration and assignments",
242- "match": "[a-zA-Z_]\\w*(?:,\\s*[a-zA-Z_]\\w*)*(?=\\s*:=)",
243- "captures": {
244- "0": {
245- "patterns": [
246- {
247- "match": "[a-zA-Z_]\\w*",
248- "name": "variable.other.assignment.go"
249- },
250- {
251- "include": "#delimiters"
252- }
253- ]
254- }
255- }
256- },
257- {
258- "comment": "Assignments to existing variables",
259- "match": "(?<!var )\\s*([a-zA-Z_]\\w*(?:,\\s*[a-zA-Z_]\\w*)*)(?=\\s*=[^=])",
260- "captures": {
261- "1": {
262- "patterns": [
263- {
264- "match": "[a-zA-Z_]\\w*",
265- "name": "variable.other.assignment.go"
266- },
267- {
268- "include": "#delimiters"
269- }
270- ]
271- }
272- }
273- },
274- {
275- "comment": "Single line variable declarations/assignments",
276- "match": "(?<=var)\\s+(.*)$",
277- "captures": {
278- "1": {
279- "patterns": [
280- {
281- "include": "#variables"
282- }
283- ]
284- }
285- }
286- },
287- {
288- "comment": "Multiline variable declarations/assignments",
289- "begin": "(\\bvar\\b)\\s+(\\()",
290- "beginCaptures": {
291- "1": {
292- "name": "keyword.var.go"
293- },
294- "2": {
295- "name": "punctuation.other.bracket.round.go"
296- }
297- },
298- "end": "\\)",
299- "endCaptures": {
300- "0": {
301- "name": "punctuation.other.bracket.round.go"
302- }
303- },
304- "patterns": [
305- {
306- "include": "#variables"
307- },
308- {
309- "include": "$self"
310- }
311- ]
312- },
313- {
314- "comment": "Terminators",
315- "match": ";",
316- "name": "punctuation.terminator.go"
317- },
318- {
319- "include": "#brackets"
320- },
321- {
322- "include": "#delimiters"
323- },
324- {
325- "include": "#keywords"
326- },
327- {
328- "include": "#operators"
329- },
330- {
331- "include": "#runes"
332- },
333- {
334- "include": "#storage_types"
335- }
336- ],
337- "repository": {
338- "brackets": {
339- "patterns": [
340- {
341- "match": "\\{|\\}",
342- "name": "punctuation.other.bracket.curly.go"
343- },
344- {
345- "match": "\\(|\\)",
346- "name": "punctuation.other.bracket.round.go"
347- },
348- {
349- "match": "\\[|\\]",
350- "name": "punctuation.other.bracket.square.go"
351- }
352- ]
353- },
354- "delimiters": {
355- "patterns": [
356- {
357- "match": ",",
358- "name": "punctuation.other.comma.go"
359- },
360- {
361- "match": "\\.(?!\\.\\.)",
362- "name": "punctuation.other.period.go"
363- },
364- {
365- "match": ":(?!=)",
366- "name": "punctuation.other.colon.go"
367- }
368- ]
369- },
370- "keywords": {
371- "patterns": [
372- {
373- "comment": "Flow control keywords",
374- "match": "\\b(break|case|continue|default|defer|else|fallthrough|for|go|goto|if|range|return|select|switch)\\b",
375- "name": "keyword.control.go"
376- },
377- {
378- "match": "\\bchan\\b",
379- "name": "keyword.channel.go"
380- },
381- {
382- "match": "\\bconst\\b",
383- "name": "keyword.const.go"
384- },
385- {
386- "match": "\\bfunc\\b",
387- "name": "keyword.function.go"
388- },
389- {
390- "match": "\\binterface\\b",
391- "name": "keyword.interface.go"
392- },
393- {
394- "match": "\\bimport\\b",
395- "name": "keyword.import.go"
396- },
397- {
398- "match": "\\bmap\\b",
399- "name": "keyword.map.go"
400- },
401- {
402- "match": "\\bpackage\\b",
403- "name": "keyword.package.go"
404- },
405- {
406- "match": "\\bstruct\\b",
407- "name": "keyword.struct.go"
408- },
409- {
410- "match": "\\btype\\b",
411- "name": "keyword.type.go"
412- },
413- {
414- "match": "\\bvar\\b",
415- "name": "keyword.var.go"
416- }
417- ]
418- },
419- "operators": {
420- "comment": "Note that the order here is very important!",
421- "patterns": [
422- {
423- "match": "(\\*|&)(?=\\w)",
424- "name": "keyword.operator.address.go"
425- },
426- {
427- "match": "<\\-",
428- "name": "keyword.operator.channel.go"
429- },
430- {
431- "match": "\\-\\-",
432- "name": "keyword.operator.decrement.go"
433- },
434- {
435- "match": "\\+\\+",
436- "name": "keyword.operator.increment.go"
437- },
438- {
439- "match": "(==|!=|<=|>=|<[^<]|>[^>])",
440- "name": "keyword.operator.comparison.go"
441- },
442- {
443- "match": "(&&|\\|\\||!)",
444- "name": "keyword.operator.logical.go"
445- },
446- {
447- "match": "(=|\\+=|\\-=|\\|=|\\^=|\\*=|/=|:=|%=|<<=|>>=|&\\^=|&=)",
448- "name": "keyword.operator.assignment.go"
449- },
450- {
451- "match": "(\\+|\\-|\\*|/|%)",
452- "name": "keyword.operator.arithmetic.go"
453- },
454- {
455- "match": "(&(?!\\^)|\\||\\^|&\\^|<<|>>)",
456- "name": "keyword.operator.arithmetic.bitwise.go"
457- },
458- {
459- "match": "\\.\\.\\.",
460- "name": "keyword.operator.ellipsis.go"
461- }
462- ]
463- },
464- "runes": {
465- "patterns": [
466- {
467- "match": "\\'(\\\\([0-7]{3}|[abfnrtv\\\\'\"]|x[0-9a-fA-F]{2}|u[0-9a-fA-F]{4}|U[0-9a-fA-F]{8})|\\p{Any})\\'",
468- "name": "constant.other.rune.go"
469- },
470- {
471- "match": "\\'.*\\'",
472- "name": "invalid.illegal.unknown-rune.go"
473- }
474- ]
475- },
476- "storage_types": {
477- "patterns": [
478- {
479- "match": "\\bbool\\b",
480- "name": "storage.type.boolean.go"
481- },
482- {
483- "match": "\\bbyte\\b",
484- "name": "storage.type.byte.go"
485- },
486- {
487- "match": "\\berror\\b",
488- "name": "storage.type.error.go"
489- },
490- {
491- "match": "\\b(complex(64|128)|float(32|64)|u?int(8|16|32|64)?)\\b",
492- "name": "storage.type.numeric.go"
493- },
494- {
495- "match": "\\brune\\b",
496- "name": "storage.type.rune.go"
497- },
498- {
499- "match": "\\bstring\\b",
500- "name": "storage.type.string.go"
501- },
502- {
503- "match": "\\buintptr\\b",
504- "name": "storage.type.uintptr.go"
505- }
506- ]
507- },
508- "string_escaped_char": {
509- "patterns": [
510- {
511- "match": "\\\\([0-7]{3}|[abfnrtv\\\\'\"]|x[0-9a-fA-F]{2}|u[0-9a-fA-F]{4}|U[0-9a-fA-F]{8})",
512- "name": "constant.character.escape.go"
513- },
514- {
515- "match": "\\\\[^0-7xuUabfnrtv\\'\"]",
516- "name": "invalid.illegal.unknown-escape.go"
517- }
518- ]
519- },
520- "string_placeholder": {
521- "patterns": [
522- {
523- "match": "%(\\[\\d+\\])?([\\+#\\-0\\x20]{,2}((\\d+|\\*)?(\\.?(\\d+|\\*|(\\[\\d+\\])\\*?)?(\\[\\d+\\])?)?))?[vT%tbcdoqxXUbeEfFgGsp]",
524- "name": "constant.other.placeholder.go"
525- }
526- ]
527- },
528- "variables": {
529- "comment": "First add tests and make sure existing tests still pass when changing anything here!",
530- "patterns": [
531- {
532- "match": "([a-zA-Z_]\\w*(?:,\\s*[a-zA-Z_]\\w*)*)\\s*(=.*)",
533- "captures": {
534- "1": {
535- "patterns": [
536- {
537- "match": "[a-zA-Z_]\\w*",
538- "name": "variable.other.assignment.go"
539- },
540- {
541- "include": "#delimiters"
542- }
543- ]
544- },
545- "2": {
546- "patterns": [
547- {
548- "include": "$self"
549- }
550- ]
551- }
552- }
553- },
554- {
555- "match": "([a-zA-Z_]\\w*(?:,\\s*[a-zA-Z_]\\w*)*)(\\s+[\\*]?[a-zA-Z_]\\w*\\s*)(=.*)",
556- "captures": {
557- "1": {
558- "patterns": [
559- {
560- "match": "[a-zA-Z_]\\w*",
561- "name": "variable.other.assignment.go"
562- },
563- {
564- "include": "#delimiters"
565- }
566- ]
567- },
568- "2": {
569- "patterns": [
570- {
571- "include": "$self"
572- }
573- ]
574- },
575- "3": {
576- "patterns": [
577- {
578- "include": "$self"
579- }
580- ]
581- }
582- }
583- },
584- {
585- "match": "([a-zA-Z_]\\w*(?:,\\s*[a-zA-Z_]\\w*)*)(\\s+[\\[\\]\\*]{0,3}[a-zA-Z_]\\w*\\s*[^=].*)",
586- "captures": {
587- "1": {
588- "patterns": [
589- {
590- "match": "[a-zA-Z_]\\w*",
591- "name": "variable.other.declaration.go"
592- },
593- {
594- "include": "#delimiters"
595- }
596- ]
597- },
598- "2": {
599- "patterns": [
600- {
601- "include": "$self"
602- }
603- ]
604- }
605- }
606- }
607- ]
608- }
609- },
610- "version": "https://github.com/atom/language-go/commit/d941ce3155b500e65b4d7fbc53ea51b9c92ec1cb"
611-}
No newline at the end of the file
2+ "scopeName": "source.go",
3+ "name": "Go",
4+ "comment": "Go language",
5+ "fileTypes": ["go"],
6+ "foldingStartMarker": "({|\\()\\s*$",
7+ "foldingStopMarker": "(}|\\))\\s*$",
8+ "patterns": [
9+ {
10+ "comment": "Block comments",
11+ "begin": "/\\*",
12+ "end": "\\*/",
13+ "captures": {
14+ "0": {
15+ "name": "punctuation.definition.comment.go"
16+ }
17+ },
18+ "name": "comment.block.go"
19+ },
20+ {
21+ "comment": "Line comments",
22+ "begin": "//",
23+ "beginCaptures": {
24+ "0": {
25+ "name": "punctuation.definition.comment.go"
26+ }
27+ },
28+ "end": "$",
29+ "name": "comment.line.double-slash.go"
30+ },
31+ {
32+ "comment": "Interpreted string literals",
33+ "begin": "\"",
34+ "beginCaptures": {
35+ "0": {
36+ "name": "punctuation.definition.string.begin.go"
37+ }
38+ },
39+ "end": "\"",
40+ "endCaptures": {
41+ "0": {
42+ "name": "punctuation.definition.string.end.go"
43+ }
44+ },
45+ "name": "string.quoted.double.go",
46+ "patterns": [
47+ {
48+ "include": "#string_escaped_char"
49+ },
50+ {
51+ "include": "#string_placeholder"
52+ }
53+ ]
54+ },
55+ {
56+ "comment": "Raw string literals",
57+ "begin": "`",
58+ "beginCaptures": {
59+ "0": {
60+ "name": "punctuation.definition.string.begin.go"
61+ }
62+ },
63+ "end": "`",
64+ "endCaptures": {
65+ "0": {
66+ "name": "punctuation.definition.string.end.go"
67+ }
68+ },
69+ "name": "string.quoted.raw.go",
70+ "patterns": [
71+ {
72+ "include": "#string_placeholder"
73+ }
74+ ]
75+ },
76+ {
77+ "comment": "Syntax error receiving channels",
78+ "match": "<\\-([\\t ]+)chan\\b",
79+ "captures": {
80+ "1": {
81+ "name": "invalid.illegal.receive-channel.go"
82+ }
83+ }
84+ },
85+ {
86+ "comment": "Syntax error sending channels",
87+ "match": "\\bchan([\\t ]+)<-",
88+ "captures": {
89+ "1": {
90+ "name": "invalid.illegal.send-channel.go"
91+ }
92+ }
93+ },
94+ {
95+ "comment": "Syntax error using slices",
96+ "match": "\\[\\](\\s+)",
97+ "captures": {
98+ "1": {
99+ "name": "invalid.illegal.slice.go"
100+ }
101+ }
102+ },
103+ {
104+ "comment": "Syntax error numeric literals",
105+ "match": "\\b0[0-7]*[89]\\d*\\b",
106+ "name": "invalid.illegal.numeric.go"
107+ },
108+ {
109+ "comment": "Built-in functions",
110+ "match": "\\b(append|cap|close|complex|copy|delete|imag|len|make|new|panic|print|println|real|recover)\\b(?=\\()",
111+ "name": "support.function.builtin.go"
112+ },
113+ {
114+ "comment": "Function declarations",
115+ "match": "^(\\bfunc\\b)(?:\\s+(\\([^\\)]+\\)\\s+)?([a-zA-Z_]\\w*)(?=\\())?",
116+ "captures": {
117+ "1": {
118+ "name": "keyword.function.go"
119+ },
120+ "2": {
121+ "patterns": [
122+ {
123+ "include": "#brackets"
124+ },
125+ {
126+ "include": "#operators"
127+ }
128+ ]
129+ },
130+ "3": {
131+ "name": "entity.name.function"
132+ }
133+ }
134+ },
135+ {
136+ "comment": "Functions",
137+ "match": "(\\bfunc\\b)|([a-zA-Z_]\\w*)(?=\\()",
138+ "captures": {
139+ "1": {
140+ "name": "keyword.function.go"
141+ },
142+ "2": {
143+ "name": "support.function.go"
144+ }
145+ }
146+ },
147+ {
148+ "comment": "Floating-point literals",
149+ "match": "(\\.\\d+([Ee][-+]\\d+)?i?)\\b|\\b\\d+\\.\\d*(([Ee][-+]\\d+)?i?\\b)?",
150+ "name": "constant.numeric.floating-point.go"
151+ },
152+ {
153+ "comment": "Integers",
154+ "match": "\\b((0x[0-9a-fA-F]+)|(0[0-7]+i?)|(\\d+([Ee]\\d+)?i?)|(\\d+[Ee][-+]\\d+i?))\\b",
155+ "name": "constant.numeric.integer.go"
156+ },
157+ {
158+ "comment": "Language constants",
159+ "match": "\\b(true|false|nil|iota)\\b",
160+ "name": "constant.language.go"
161+ },
162+ {
163+ "comment": "Package declarations",
164+ "match": "(?<=package)\\s+([a-zA-Z_]\\w*)",
165+ "captures": {
166+ "1": {
167+ "name": "entity.name.package.go"
168+ }
169+ }
170+ },
171+ {
172+ "comment": "Single line import declarations",
173+ "match": "(?<=import)(\\s+((?!\\s+\")[^\\s]*)?\\s*)((\")([^\"]*)(\"))",
174+ "captures": {
175+ "2": {
176+ "name": "entity.alias.import.go"
177+ },
178+ "3": {
179+ "name": "string.quoted.double.go"
180+ },
181+ "4": {
182+ "name": "punctuation.definition.string.begin.go"
183+ },
184+ "5": {
185+ "name": "entity.name.import.go"
186+ },
187+ "6": {
188+ "name": "punctuation.definition.string.end.go"
189+ }
190+ }
191+ },
192+ {
193+ "comment": "Multiline import declarations",
194+ "begin": "(?<=import)\\s+(\\()",
195+ "beginCaptures": {
196+ "1": {
197+ "name": "punctuation.other.bracket.round.go"
198+ }
199+ },
200+ "patterns": [
201+ {
202+ "match": "((?!\\s+\")[^\\s]*)?\\s+((\")([^\"]*)(\"))",
203+ "captures": {
204+ "1": {
205+ "name": "entity.alias.import.go"
206+ },
207+ "2": {
208+ "name": "string.quoted.double.go"
209+ },
210+ "3": {
211+ "name": "punctuation.definition.string.begin.go"
212+ },
213+ "4": {
214+ "name": "entity.name.import.go"
215+ },
216+ "5": {
217+ "name": "punctuation.definition.string.end.go"
218+ }
219+ }
220+ }
221+ ],
222+ "end": "\\)",
223+ "endCaptures": {
224+ "0": {
225+ "name": "punctuation.other.bracket.round.go"
226+ }
227+ }
228+ },
229+ {
230+ "comment": "Type declarations",
231+ "match": "(?<=type)\\s+([a-zA-Z_]\\w*)",
232+ "captures": {
233+ "1": {
234+ "name": "entity.name.type.go"
235+ }
236+ }
237+ },
238+ {
239+ "comment": "Shorthand variable declaration and assignments",
240+ "match": "[a-zA-Z_]\\w*(?:,\\s*[a-zA-Z_]\\w*)*(?=\\s*:=)",
241+ "captures": {
242+ "0": {
243+ "patterns": [
244+ {
245+ "match": "[a-zA-Z_]\\w*",
246+ "name": "variable.other.assignment.go"
247+ },
248+ {
249+ "include": "#delimiters"
250+ }
251+ ]
252+ }
253+ }
254+ },
255+ {
256+ "comment": "Assignments to existing variables",
257+ "match": "(?<!var )\\s*([a-zA-Z_]\\w*(?:,\\s*[a-zA-Z_]\\w*)*)(?=\\s*=[^=])",
258+ "captures": {
259+ "1": {
260+ "patterns": [
261+ {
262+ "match": "[a-zA-Z_]\\w*",
263+ "name": "variable.other.assignment.go"
264+ },
265+ {
266+ "include": "#delimiters"
267+ }
268+ ]
269+ }
270+ }
271+ },
272+ {
273+ "comment": "Single line variable declarations/assignments",
274+ "match": "(?<=var)\\s+(.*)$",
275+ "captures": {
276+ "1": {
277+ "patterns": [
278+ {
279+ "include": "#variables"
280+ }
281+ ]
282+ }
283+ }
284+ },
285+ {
286+ "comment": "Multiline variable declarations/assignments",
287+ "begin": "(\\bvar\\b)\\s+(\\()",
288+ "beginCaptures": {
289+ "1": {
290+ "name": "keyword.var.go"
291+ },
292+ "2": {
293+ "name": "punctuation.other.bracket.round.go"
294+ }
295+ },
296+ "end": "\\)",
297+ "endCaptures": {
298+ "0": {
299+ "name": "punctuation.other.bracket.round.go"
300+ }
301+ },
302+ "patterns": [
303+ {
304+ "include": "#variables"
305+ },
306+ {
307+ "include": "$self"
308+ }
309+ ]
310+ },
311+ {
312+ "comment": "Terminators",
313+ "match": ";",
314+ "name": "punctuation.terminator.go"
315+ },
316+ {
317+ "include": "#brackets"
318+ },
319+ {
320+ "include": "#delimiters"
321+ },
322+ {
323+ "include": "#keywords"
324+ },
325+ {
326+ "include": "#operators"
327+ },
328+ {
329+ "include": "#runes"
330+ },
331+ {
332+ "include": "#storage_types"
333+ }
334+ ],
335+ "repository": {
336+ "brackets": {
337+ "patterns": [
338+ {
339+ "match": "\\{|\\}",
340+ "name": "punctuation.other.bracket.curly.go"
341+ },
342+ {
343+ "match": "\\(|\\)",
344+ "name": "punctuation.other.bracket.round.go"
345+ },
346+ {
347+ "match": "\\[|\\]",
348+ "name": "punctuation.other.bracket.square.go"
349+ }
350+ ]
351+ },
352+ "delimiters": {
353+ "patterns": [
354+ {
355+ "match": ",",
356+ "name": "punctuation.other.comma.go"
357+ },
358+ {
359+ "match": "\\.(?!\\.\\.)",
360+ "name": "punctuation.other.period.go"
361+ },
362+ {
363+ "match": ":(?!=)",
364+ "name": "punctuation.other.colon.go"
365+ }
366+ ]
367+ },
368+ "keywords": {
369+ "patterns": [
370+ {
371+ "comment": "Flow control keywords",
372+ "match": "\\b(break|case|continue|default|defer|else|fallthrough|for|go|goto|if|range|return|select|switch)\\b",
373+ "name": "keyword.control.go"
374+ },
375+ {
376+ "match": "\\bchan\\b",
377+ "name": "keyword.channel.go"
378+ },
379+ {
380+ "match": "\\bconst\\b",
381+ "name": "keyword.const.go"
382+ },
383+ {
384+ "match": "\\bfunc\\b",
385+ "name": "keyword.function.go"
386+ },
387+ {
388+ "match": "\\binterface\\b",
389+ "name": "keyword.interface.go"
390+ },
391+ {
392+ "match": "\\bimport\\b",
393+ "name": "keyword.import.go"
394+ },
395+ {
396+ "match": "\\bmap\\b",
397+ "name": "keyword.map.go"
398+ },
399+ {
400+ "match": "\\bpackage\\b",
401+ "name": "keyword.package.go"
402+ },
403+ {
404+ "match": "\\bstruct\\b",
405+ "name": "keyword.struct.go"
406+ },
407+ {
408+ "match": "\\btype\\b",
409+ "name": "keyword.type.go"
410+ },
411+ {
412+ "match": "\\bvar\\b",
413+ "name": "keyword.var.go"
414+ }
415+ ]
416+ },
417+ "operators": {
418+ "comment": "Note that the order here is very important!",
419+ "patterns": [
420+ {
421+ "match": "(\\*|&)(?=\\w)",
422+ "name": "keyword.operator.address.go"
423+ },
424+ {
425+ "match": "<\\-",
426+ "name": "keyword.operator.channel.go"
427+ },
428+ {
429+ "match": "\\-\\-",
430+ "name": "keyword.operator.decrement.go"
431+ },
432+ {
433+ "match": "\\+\\+",
434+ "name": "keyword.operator.increment.go"
435+ },
436+ {
437+ "match": "(==|!=|<=|>=|<[^<]|>[^>])",
438+ "name": "keyword.operator.comparison.go"
439+ },
440+ {
441+ "match": "(&&|\\|\\||!)",
442+ "name": "keyword.operator.logical.go"
443+ },
444+ {
445+ "match": "(=|\\+=|\\-=|\\|=|\\^=|\\*=|/=|:=|%=|<<=|>>=|&\\^=|&=)",
446+ "name": "keyword.operator.assignment.go"
447+ },
448+ {
449+ "match": "(\\+|\\-|\\*|/|%)",
450+ "name": "keyword.operator.arithmetic.go"
451+ },
452+ {
453+ "match": "(&(?!\\^)|\\||\\^|&\\^|<<|>>)",
454+ "name": "keyword.operator.arithmetic.bitwise.go"
455+ },
456+ {
457+ "match": "\\.\\.\\.",
458+ "name": "keyword.operator.ellipsis.go"
459+ }
460+ ]
461+ },
462+ "runes": {
463+ "patterns": [
464+ {
465+ "match": "\\'(\\\\([0-7]{3}|[abfnrtv\\\\'\"]|x[0-9a-fA-F]{2}|u[0-9a-fA-F]{4}|U[0-9a-fA-F]{8})|\\p{Any})\\'",
466+ "name": "constant.other.rune.go"
467+ },
468+ {
469+ "match": "\\'.*\\'",
470+ "name": "invalid.illegal.unknown-rune.go"
471+ }
472+ ]
473+ },
474+ "storage_types": {
475+ "patterns": [
476+ {
477+ "match": "\\bbool\\b",
478+ "name": "storage.type.boolean.go"
479+ },
480+ {
481+ "match": "\\bbyte\\b",
482+ "name": "storage.type.byte.go"
483+ },
484+ {
485+ "match": "\\berror\\b",
486+ "name": "storage.type.error.go"
487+ },
488+ {
489+ "match": "\\b(complex(64|128)|float(32|64)|u?int(8|16|32|64)?)\\b",
490+ "name": "storage.type.numeric.go"
491+ },
492+ {
493+ "match": "\\brune\\b",
494+ "name": "storage.type.rune.go"
495+ },
496+ {
497+ "match": "\\bstring\\b",
498+ "name": "storage.type.string.go"
499+ },
500+ {
501+ "match": "\\buintptr\\b",
502+ "name": "storage.type.uintptr.go"
503+ }
504+ ]
505+ },
506+ "string_escaped_char": {
507+ "patterns": [
508+ {
509+ "match": "\\\\([0-7]{3}|[abfnrtv\\\\'\"]|x[0-9a-fA-F]{2}|u[0-9a-fA-F]{4}|U[0-9a-fA-F]{8})",
510+ "name": "constant.character.escape.go"
511+ },
512+ {
513+ "match": "\\\\[^0-7xuUabfnrtv\\'\"]",
514+ "name": "invalid.illegal.unknown-escape.go"
515+ }
516+ ]
517+ },
518+ "string_placeholder": {
519+ "patterns": [
520+ {
521+ "match": "%(\\[\\d+\\])?([\\+#\\-0\\x20]{,2}((\\d+|\\*)?(\\.?(\\d+|\\*|(\\[\\d+\\])\\*?)?(\\[\\d+\\])?)?))?[vT%tbcdoqxXUbeEfFgGsp]",
522+ "name": "constant.other.placeholder.go"
523+ }
524+ ]
525+ },
526+ "variables": {
527+ "comment": "First add tests and make sure existing tests still pass when changing anything here!",
528+ "patterns": [
529+ {
530+ "match": "([a-zA-Z_]\\w*(?:,\\s*[a-zA-Z_]\\w*)*)\\s*(=.*)",
531+ "captures": {
532+ "1": {
533+ "patterns": [
534+ {
535+ "match": "[a-zA-Z_]\\w*",
536+ "name": "variable.other.assignment.go"
537+ },
538+ {
539+ "include": "#delimiters"
540+ }
541+ ]
542+ },
543+ "2": {
544+ "patterns": [
545+ {
546+ "include": "$self"
547+ }
548+ ]
549+ }
550+ }
551+ },
552+ {
553+ "match": "([a-zA-Z_]\\w*(?:,\\s*[a-zA-Z_]\\w*)*)(\\s+[\\*]?[a-zA-Z_]\\w*\\s*)(=.*)",
554+ "captures": {
555+ "1": {
556+ "patterns": [
557+ {
558+ "match": "[a-zA-Z_]\\w*",
559+ "name": "variable.other.assignment.go"
560+ },
561+ {
562+ "include": "#delimiters"
563+ }
564+ ]
565+ },
566+ "2": {
567+ "patterns": [
568+ {
569+ "include": "$self"
570+ }
571+ ]
572+ },
573+ "3": {
574+ "patterns": [
575+ {
576+ "include": "$self"
577+ }
578+ ]
579+ }
580+ }
581+ },
582+ {
583+ "match": "([a-zA-Z_]\\w*(?:,\\s*[a-zA-Z_]\\w*)*)(\\s+[\\[\\]\\*]{0,3}[a-zA-Z_]\\w*\\s*[^=].*)",
584+ "captures": {
585+ "1": {
586+ "patterns": [
587+ {
588+ "match": "[a-zA-Z_]\\w*",
589+ "name": "variable.other.declaration.go"
590+ },
591+ {
592+ "include": "#delimiters"
593+ }
594+ ]
595+ },
596+ "2": {
597+ "patterns": [
598+ {
599+ "include": "$self"
600+ }
601+ ]
602+ }
603+ }
604+ }
605+ ]
606+ }
607+ },
608+ "version": "https://github.com/atom/language-go/commit/d941ce3155b500e65b4d7fbc53ea51b9c92ec1cb"
609+}
modified extensions/vscode/textmate-syntaxes/html.json +544 −552
@@ -1,553 +1,545 @@
11 {
2- "fileTypes": [
3- "html",
4- "htm",
5- "shtml",
6- "xhtml",
7- "inc",
8- "tmpl",
9- "tpl"
10- ],
11- "firstLineMatch": "<(?i:(!DOCTYPE\\s*)?html)",
12- "injections": {
13- "R:text.html - comment.block": {
14- "comment": "Use R: to ensure this matches after any other injections.",
15- "patterns": [
16- {
17- "match": "<",
18- "name": "invalid.illegal.bad-angle-bracket.html"
19- }
20- ]
21- }
22- },
23- "keyEquivalent": "^~H",
24- "name": "HTML",
25- "patterns": [
26- {
27- "begin": "(<)([a-zA-Z0-9:\\-]++)(?=[^>]*></\\2>)",
28- "beginCaptures": {
29- "1": {
30- "name": "punctuation.definition.tag.html"
31- },
32- "2": {
33- "name": "entity.name.tag.html"
34- }
35- },
36- "end": "(>(<)/)(\\2)(>)",
37- "endCaptures": {
38- "1": {
39- "name": "punctuation.definition.tag.html"
40- },
41- "2": {
42- "name": "meta.scope.between-tag-pair.html"
43- },
44- "3": {
45- "name": "entity.name.tag.html"
46- },
47- "4": {
48- "name": "punctuation.definition.tag.html"
49- }
50- },
51- "name": "meta.tag.any.html",
52- "patterns": [
53- {
54- "include": "#tag-stuff"
55- }
56- ]
57- },
58- {
59- "begin": "(<\\?)(xml)",
60- "captures": {
61- "1": {
62- "name": "punctuation.definition.tag.html"
63- },
64- "2": {
65- "name": "entity.name.tag.xml.html"
66- }
67- },
68- "end": "(\\?>)",
69- "name": "meta.tag.preprocessor.xml.html",
70- "patterns": [
71- {
72- "include": "#tag-generic-attribute"
73- },
74- {
75- "include": "#string-double-quoted"
76- },
77- {
78- "include": "#string-single-quoted"
79- }
80- ]
81- },
82- {
83- "begin": "<!--",
84- "captures": {
85- "0": {
86- "name": "punctuation.definition.comment.html"
87- }
88- },
89- "end": "--\\s*>",
90- "name": "comment.block.html",
91- "patterns": [
92- {
93- "match": "--",
94- "name": "invalid.illegal.bad-comments-or-CDATA.html"
95- },
96- {
97- "include": "#embedded-code"
98- }
99- ]
100- },
101- {
102- "begin": "<!",
103- "captures": {
104- "0": {
105- "name": "punctuation.definition.tag.html"
106- }
107- },
108- "end": ">",
109- "name": "meta.tag.sgml.html",
110- "patterns": [
111- {
112- "begin": "(?i:DOCTYPE)",
113- "captures": {
114- "1": {
115- "name": "entity.name.tag.doctype.html"
116- }
117- },
118- "end": "(?=>)",
119- "name": "meta.tag.sgml.doctype.html",
120- "patterns": [
121- {
122- "match": "\"[^\">]*\"",
123- "name": "string.quoted.double.doctype.identifiers-and-DTDs.html"
124- }
125- ]
126- },
127- {
128- "begin": "\\[CDATA\\[",
129- "end": "]](?=>)",
130- "name": "constant.other.inline-data.html"
131- },
132- {
133- "match": "(\\s*)(?!--|>)\\S(\\s*)",
134- "name": "invalid.illegal.bad-comments-or-CDATA.html"
135- }
136- ]
137- },
138- {
139- "include": "#embedded-code"
140- },
141- {
142- "begin": "(?:^\\s+)?(<)((?i:style))\\b(?![^>]*/>)",
143- "captures": {
144- "1": {
145- "name": "punctuation.definition.tag.html"
146- },
147- "2": {
148- "name": "entity.name.tag.style.html"
149- },
150- "3": {
151- "name": "punctuation.definition.tag.html"
152- }
153- },
154- "end": "(</)((?i:style))(>)(?:\\s*\\n)?",
155- "contentName": "source.css.embedded.html",
156- "patterns": [
157- {
158- "include": "#tag-stuff"
159- },
160- {
161- "begin": "(>)",
162- "beginCaptures": {
163- "1": {
164- "name": "punctuation.definition.tag.html"
165- }
166- },
167- "end": "(?=</(?i:style))",
168- "patterns": [
169- {
170- "include": "#embedded-code"
171- },
172- {
173- "include": "source.css"
174- }
175- ]
176- }
177- ]
178- },
179- {
180- "begin": "(?:^\\s+)?(<)((?i:script))\\b(?![^>]*/>)(?![^>]*(?i:type.?=.?text/((?!javascript).*)))",
181- "beginCaptures": {
182- "1": {
183- "name": "punctuation.definition.tag.html"
184- },
185- "2": {
186- "name": "entity.name.tag.script.html"
187- }
188- },
189- "end": "(?<=</(script|SCRIPT))(>)(?:\\s*\\n)?",
190- "endCaptures": {
191- "2": {
192- "name": "punctuation.definition.tag.html"
193- }
194- },
195- "contentName": "source.js.embedded.html",
196- "patterns": [
197- {
198- "include": "#tag-stuff"
199- },
200- {
201- "begin": "(?<!</(?:script|SCRIPT))(>)",
202- "captures": {
203- "1": {
204- "name": "punctuation.definition.tag.html"
205- },
206- "2": {
207- "name": "entity.name.tag.script.html"
208- }
209- },
210- "end": "(</)((?i:script))",
211- "patterns": [
212- {
213- "captures": {
214- "1": {
215- "name": "punctuation.definition.comment.js"
216- }
217- },
218- "match": "(//).*?((?=</script)|$\\n?)",
219- "name": "comment.line.double-slash.js"
220- },
221- {
222- "begin": "/\\*",
223- "captures": {
224- "0": {
225- "name": "punctuation.definition.comment.js"
226- }
227- },
228- "end": "\\*/|(?=</script)",
229- "name": "comment.block.js"
230- },
231- {
232- "include": "source.js"
233- }
234- ]
235- }
236- ]
237- },
238- {
239- "begin": "(</?)((?i:body|head|html)(?=\\s|\\\\|>))",
240- "captures": {
241- "1": {
242- "name": "punctuation.definition.tag.html"
243- },
244- "2": {
245- "name": "entity.name.tag.structure.any.html"
246- }
247- },
248- "end": "(>)",
249- "name": "meta.tag.structure.any.html",
250- "patterns": [
251- {
252- "include": "#tag-stuff"
253- }
254- ]
255- },
256- {
257- "begin": "(</?)((?i:address|blockquote|dd|div|section|article|aside|header|footer|nav|menu|dl|dt|fieldset|form|frame|frameset|h1|h2|h3|h4|h5|h6|iframe|noframes|object|ol|p|ul|applet|center|dir|hr|pre)(?=\\s|\\\\|>))",
258- "beginCaptures": {
259- "1": {
260- "name": "punctuation.definition.tag.begin.html"
261- },
262- "2": {
263- "name": "entity.name.tag.block.any.html"
264- }
265- },
266- "end": "(>)",
267- "endCaptures": {
268- "1": {
269- "name": "punctuation.definition.tag.end.html"
270- }
271- },
272- "name": "meta.tag.block.any.html",
273- "patterns": [
274- {
275- "include": "#tag-stuff"
276- }
277- ]
278- },
279- {
280- "begin": "(</?)((?i:a|abbr|acronym|area|b|base|basefont|bdo|big|br|button|caption|cite|code|col|colgroup|del|dfn|em|font|head|html|i|img|input|ins|isindex|kbd|label|legend|li|link|map|meta|noscript|optgroup|option|param|q|s|samp|script|select|small|span|strike|strong|style|sub|sup|table|tbody|td|textarea|tfoot|th|thead|title|tr|tt|u|var)(?=\\s|\\\\|>))",
281- "beginCaptures": {
282- "1": {
283- "name": "punctuation.definition.tag.begin.html"
284- },
285- "2": {
286- "name": "entity.name.tag.inline.any.html"
287- }
288- },
289- "end": "((?: ?/)?>)",
290- "endCaptures": {
291- "1": {
292- "name": "punctuation.definition.tag.end.html"
293- }
294- },
295- "name": "meta.tag.inline.any.html",
296- "patterns": [
297- {
298- "include": "#tag-stuff"
299- }
300- ]
301- },
302- {
303- "begin": "(</?)([a-zA-Z0-9:\\-]+)",
304- "beginCaptures": {
305- "1": {
306- "name": "punctuation.definition.tag.begin.html"
307- },
308- "2": {
309- "name": "entity.name.tag.other.html"
310- }
311- },
312- "end": "(>)",
313- "endCaptures": {
314- "1": {
315- "name": "punctuation.definition.tag.end.html"
316- }
317- },
318- "name": "meta.tag.other.html",
319- "patterns": [
320- {
321- "include": "#tag-stuff"
322- }
323- ]
324- },
325- {
326- "include": "#entities"
327- },
328- {
329- "match": "<>",
330- "name": "invalid.illegal.incomplete.html"
331- }
332- ],
333- "repository": {
334- "embedded-code": {
335- "patterns": [
336- {
337- "include": "#smarty"
338- },
339- {
340- "include": "#python"
341- }
342- ]
343- },
344- "entities": {
345- "patterns": [
346- {
347- "captures": {
348- "1": {
349- "name": "punctuation.definition.entity.html"
350- },
351- "3": {
352- "name": "punctuation.definition.entity.html"
353- }
354- },
355- "match": "(&)([a-zA-Z0-9]+|#[0-9]+|#[xX][0-9a-fA-F]+)(;)",
356- "name": "constant.character.entity.html"
357- },
358- {
359- "match": "&",
360- "name": "invalid.illegal.bad-ampersand.html"
361- }
362- ]
363- },
364- "python": {
365- "begin": "(?:^\\s*)<\\?python(?!.*\\?>)",
366- "end": "\\?>(?:\\s*$\\n)?",
367- "contentName": "source.python.embedded.html",
368- "patterns": [
369- {
370- "include": "source.python"
371- }
372- ]
373- },
374- "smarty": {
375- "patterns": [
376- {
377- "begin": "(\\{(literal)\\})",
378- "captures": {
379- "1": {
380- "name": "source.smarty.embedded.html"
381- },
382- "2": {
383- "name": "support.function.built-in.smarty"
384- }
385- },
386- "end": "(\\{/(literal)\\})"
387- },
388- {
389- "begin": "{{|{",
390- "disabled": 1,
391- "end": "}}|}",
392- "contentName": "source.smarty.embedded.html",
393- "patterns": [
394- {
395- "include": "source.smarty"
396- }
397- ]
398- }
399- ]
400- },
401- "string-double-quoted": {
402- "begin": "\"",
403- "beginCaptures": {
404- "0": {
405- "name": "punctuation.definition.string.begin.html"
406- }
407- },
408- "end": "\"",
409- "endCaptures": {
410- "0": {
411- "name": "punctuation.definition.string.end.html"
412- }
413- },
414- "name": "string.quoted.double.html",
415- "patterns": [
416- {
417- "include": "#embedded-code"
418- },
419- {
420- "include": "#entities"
421- }
422- ]
423- },
424- "string-single-quoted": {
425- "begin": "'",
426- "beginCaptures": {
427- "0": {
428- "name": "punctuation.definition.string.begin.html"
429- }
430- },
431- "end": "'",
432- "endCaptures": {
433- "0": {
434- "name": "punctuation.definition.string.end.html"
435- }
436- },
437- "name": "string.quoted.single.html",
438- "patterns": [
439- {
440- "include": "#embedded-code"
441- },
442- {
443- "include": "#entities"
444- }
445- ]
446- },
447- "tag-generic-attribute": {
448- "match": "(?<=[^=])\\b([a-zA-Z0-9:-]+)",
449- "name": "entity.other.attribute-name.html"
450- },
451- "tag-id-attribute": {
452- "begin": "\\b(id)\\b\\s*(=)",
453- "captures": {
454- "1": {
455- "name": "entity.other.attribute-name.id.html"
456- },
457- "2": {
458- "name": "punctuation.separator.key-value.html"
459- }
460- },
461- "end": "(?!\\G)(?<='|\"|[^\\s<>/])",
462- "name": "meta.attribute-with-value.id.html",
463- "patterns": [
464- {
465- "begin": "\"",
466- "beginCaptures": {
467- "0": {
468- "name": "punctuation.definition.string.begin.html"
469- }
470- },
471- "contentName": "meta.toc-list.id.html",
472- "end": "\"",
473- "endCaptures": {
474- "0": {
475- "name": "punctuation.definition.string.end.html"
476- }
477- },
478- "name": "string.quoted.double.html",
479- "patterns": [
480- {
481- "include": "#embedded-code"
482- },
483- {
484- "include": "#entities"
485- }
486- ]
487- },
488- {
489- "begin": "'",
490- "beginCaptures": {
491- "0": {
492- "name": "punctuation.definition.string.begin.html"
493- }
494- },
495- "contentName": "meta.toc-list.id.html",
496- "end": "'",
497- "endCaptures": {
498- "0": {
499- "name": "punctuation.definition.string.end.html"
500- }
501- },
502- "name": "string.quoted.single.html",
503- "patterns": [
504- {
505- "include": "#embedded-code"
506- },
507- {
508- "include": "#entities"
509- }
510- ]
511- },
512- {
513- "captures": {
514- "0": {
515- "name": "meta.toc-list.id.html"
516- }
517- },
518- "match": "(?<==)(?:[^\\s<>/'\"]|/(?!>))+",
519- "name": "string.unquoted.html"
520- }
521- ]
522- },
523- "tag-stuff": {
524- "patterns": [
525- {
526- "include": "#tag-id-attribute"
527- },
528- {
529- "include": "#tag-generic-attribute"
530- },
531- {
532- "include": "#string-double-quoted"
533- },
534- {
535- "include": "#string-single-quoted"
536- },
537- {
538- "include": "#embedded-code"
539- },
540- {
541- "include": "#unquoted-attribute"
542- }
543- ]
544- },
545- "unquoted-attribute": {
546- "match": "(?<==)(?:[^\\s<>/'\"]|/(?!>))+",
547- "name": "string.unquoted.html"
548- }
549- },
550- "scopeName": "text.html.basic",
551- "uuid": "17994EC8-6B1D-11D9-AC3A-000D93589AF6",
552- "version": "https://github.com/textmate/html.tmbundle/commit/9f812c89f4990a98391701caa77824c94860538f"
553-}
No newline at the end of the file
2+ "fileTypes": ["html", "htm", "shtml", "xhtml", "inc", "tmpl", "tpl"],
3+ "firstLineMatch": "<(?i:(!DOCTYPE\\s*)?html)",
4+ "injections": {
5+ "R:text.html - comment.block": {
6+ "comment": "Use R: to ensure this matches after any other injections.",
7+ "patterns": [
8+ {
9+ "match": "<",
10+ "name": "invalid.illegal.bad-angle-bracket.html"
11+ }
12+ ]
13+ }
14+ },
15+ "keyEquivalent": "^~H",
16+ "name": "HTML",
17+ "patterns": [
18+ {
19+ "begin": "(<)([a-zA-Z0-9:\\-]++)(?=[^>]*></\\2>)",
20+ "beginCaptures": {
21+ "1": {
22+ "name": "punctuation.definition.tag.html"
23+ },
24+ "2": {
25+ "name": "entity.name.tag.html"
26+ }
27+ },
28+ "end": "(>(<)/)(\\2)(>)",
29+ "endCaptures": {
30+ "1": {
31+ "name": "punctuation.definition.tag.html"
32+ },
33+ "2": {
34+ "name": "meta.scope.between-tag-pair.html"
35+ },
36+ "3": {
37+ "name": "entity.name.tag.html"
38+ },
39+ "4": {
40+ "name": "punctuation.definition.tag.html"
41+ }
42+ },
43+ "name": "meta.tag.any.html",
44+ "patterns": [
45+ {
46+ "include": "#tag-stuff"
47+ }
48+ ]
49+ },
50+ {
51+ "begin": "(<\\?)(xml)",
52+ "captures": {
53+ "1": {
54+ "name": "punctuation.definition.tag.html"
55+ },
56+ "2": {
57+ "name": "entity.name.tag.xml.html"
58+ }
59+ },
60+ "end": "(\\?>)",
61+ "name": "meta.tag.preprocessor.xml.html",
62+ "patterns": [
63+ {
64+ "include": "#tag-generic-attribute"
65+ },
66+ {
67+ "include": "#string-double-quoted"
68+ },
69+ {
70+ "include": "#string-single-quoted"
71+ }
72+ ]
73+ },
74+ {
75+ "begin": "<!--",
76+ "captures": {
77+ "0": {
78+ "name": "punctuation.definition.comment.html"
79+ }
80+ },
81+ "end": "--\\s*>",
82+ "name": "comment.block.html",
83+ "patterns": [
84+ {
85+ "match": "--",
86+ "name": "invalid.illegal.bad-comments-or-CDATA.html"
87+ },
88+ {
89+ "include": "#embedded-code"
90+ }
91+ ]
92+ },
93+ {
94+ "begin": "<!",
95+ "captures": {
96+ "0": {
97+ "name": "punctuation.definition.tag.html"
98+ }
99+ },
100+ "end": ">",
101+ "name": "meta.tag.sgml.html",
102+ "patterns": [
103+ {
104+ "begin": "(?i:DOCTYPE)",
105+ "captures": {
106+ "1": {
107+ "name": "entity.name.tag.doctype.html"
108+ }
109+ },
110+ "end": "(?=>)",
111+ "name": "meta.tag.sgml.doctype.html",
112+ "patterns": [
113+ {
114+ "match": "\"[^\">]*\"",
115+ "name": "string.quoted.double.doctype.identifiers-and-DTDs.html"
116+ }
117+ ]
118+ },
119+ {
120+ "begin": "\\[CDATA\\[",
121+ "end": "]](?=>)",
122+ "name": "constant.other.inline-data.html"
123+ },
124+ {
125+ "match": "(\\s*)(?!--|>)\\S(\\s*)",
126+ "name": "invalid.illegal.bad-comments-or-CDATA.html"
127+ }
128+ ]
129+ },
130+ {
131+ "include": "#embedded-code"
132+ },
133+ {
134+ "begin": "(?:^\\s+)?(<)((?i:style))\\b(?![^>]*/>)",
135+ "captures": {
136+ "1": {
137+ "name": "punctuation.definition.tag.html"
138+ },
139+ "2": {
140+ "name": "entity.name.tag.style.html"
141+ },
142+ "3": {
143+ "name": "punctuation.definition.tag.html"
144+ }
145+ },
146+ "end": "(</)((?i:style))(>)(?:\\s*\\n)?",
147+ "contentName": "source.css.embedded.html",
148+ "patterns": [
149+ {
150+ "include": "#tag-stuff"
151+ },
152+ {
153+ "begin": "(>)",
154+ "beginCaptures": {
155+ "1": {
156+ "name": "punctuation.definition.tag.html"
157+ }
158+ },
159+ "end": "(?=</(?i:style))",
160+ "patterns": [
161+ {
162+ "include": "#embedded-code"
163+ },
164+ {
165+ "include": "source.css"
166+ }
167+ ]
168+ }
169+ ]
170+ },
171+ {
172+ "begin": "(?:^\\s+)?(<)((?i:script))\\b(?![^>]*/>)(?![^>]*(?i:type.?=.?text/((?!javascript).*)))",
173+ "beginCaptures": {
174+ "1": {
175+ "name": "punctuation.definition.tag.html"
176+ },
177+ "2": {
178+ "name": "entity.name.tag.script.html"
179+ }
180+ },
181+ "end": "(?<=</(script|SCRIPT))(>)(?:\\s*\\n)?",
182+ "endCaptures": {
183+ "2": {
184+ "name": "punctuation.definition.tag.html"
185+ }
186+ },
187+ "contentName": "source.js.embedded.html",
188+ "patterns": [
189+ {
190+ "include": "#tag-stuff"
191+ },
192+ {
193+ "begin": "(?<!</(?:script|SCRIPT))(>)",
194+ "captures": {
195+ "1": {
196+ "name": "punctuation.definition.tag.html"
197+ },
198+ "2": {
199+ "name": "entity.name.tag.script.html"
200+ }
201+ },
202+ "end": "(</)((?i:script))",
203+ "patterns": [
204+ {
205+ "captures": {
206+ "1": {
207+ "name": "punctuation.definition.comment.js"
208+ }
209+ },
210+ "match": "(//).*?((?=</script)|$\\n?)",
211+ "name": "comment.line.double-slash.js"
212+ },
213+ {
214+ "begin": "/\\*",
215+ "captures": {
216+ "0": {
217+ "name": "punctuation.definition.comment.js"
218+ }
219+ },
220+ "end": "\\*/|(?=</script)",
221+ "name": "comment.block.js"
222+ },
223+ {
224+ "include": "source.js"
225+ }
226+ ]
227+ }
228+ ]
229+ },
230+ {
231+ "begin": "(</?)((?i:body|head|html)(?=\\s|\\\\|>))",
232+ "captures": {
233+ "1": {
234+ "name": "punctuation.definition.tag.html"
235+ },
236+ "2": {
237+ "name": "entity.name.tag.structure.any.html"
238+ }
239+ },
240+ "end": "(>)",
241+ "name": "meta.tag.structure.any.html",
242+ "patterns": [
243+ {
244+ "include": "#tag-stuff"
245+ }
246+ ]
247+ },
248+ {
249+ "begin": "(</?)((?i:address|blockquote|dd|div|section|article|aside|header|footer|nav|menu|dl|dt|fieldset|form|frame|frameset|h1|h2|h3|h4|h5|h6|iframe|noframes|object|ol|p|ul|applet|center|dir|hr|pre)(?=\\s|\\\\|>))",
250+ "beginCaptures": {
251+ "1": {
252+ "name": "punctuation.definition.tag.begin.html"
253+ },
254+ "2": {
255+ "name": "entity.name.tag.block.any.html"
256+ }
257+ },
258+ "end": "(>)",
259+ "endCaptures": {
260+ "1": {
261+ "name": "punctuation.definition.tag.end.html"
262+ }
263+ },
264+ "name": "meta.tag.block.any.html",
265+ "patterns": [
266+ {
267+ "include": "#tag-stuff"
268+ }
269+ ]
270+ },
271+ {
272+ "begin": "(</?)((?i:a|abbr|acronym|area|b|base|basefont|bdo|big|br|button|caption|cite|code|col|colgroup|del|dfn|em|font|head|html|i|img|input|ins|isindex|kbd|label|legend|li|link|map|meta|noscript|optgroup|option|param|q|s|samp|script|select|small|span|strike|strong|style|sub|sup|table|tbody|td|textarea|tfoot|th|thead|title|tr|tt|u|var)(?=\\s|\\\\|>))",
273+ "beginCaptures": {
274+ "1": {
275+ "name": "punctuation.definition.tag.begin.html"
276+ },
277+ "2": {
278+ "name": "entity.name.tag.inline.any.html"
279+ }
280+ },
281+ "end": "((?: ?/)?>)",
282+ "endCaptures": {
283+ "1": {
284+ "name": "punctuation.definition.tag.end.html"
285+ }
286+ },
287+ "name": "meta.tag.inline.any.html",
288+ "patterns": [
289+ {
290+ "include": "#tag-stuff"
291+ }
292+ ]
293+ },
294+ {
295+ "begin": "(</?)([a-zA-Z0-9:\\-]+)",
296+ "beginCaptures": {
297+ "1": {
298+ "name": "punctuation.definition.tag.begin.html"
299+ },
300+ "2": {
301+ "name": "entity.name.tag.other.html"
302+ }
303+ },
304+ "end": "(>)",
305+ "endCaptures": {
306+ "1": {
307+ "name": "punctuation.definition.tag.end.html"
308+ }
309+ },
310+ "name": "meta.tag.other.html",
311+ "patterns": [
312+ {
313+ "include": "#tag-stuff"
314+ }
315+ ]
316+ },
317+ {
318+ "include": "#entities"
319+ },
320+ {
321+ "match": "<>",
322+ "name": "invalid.illegal.incomplete.html"
323+ }
324+ ],
325+ "repository": {
326+ "embedded-code": {
327+ "patterns": [
328+ {
329+ "include": "#smarty"
330+ },
331+ {
332+ "include": "#python"
333+ }
334+ ]
335+ },
336+ "entities": {
337+ "patterns": [
338+ {
339+ "captures": {
340+ "1": {
341+ "name": "punctuation.definition.entity.html"
342+ },
343+ "3": {
344+ "name": "punctuation.definition.entity.html"
345+ }
346+ },
347+ "match": "(&)([a-zA-Z0-9]+|#[0-9]+|#[xX][0-9a-fA-F]+)(;)",
348+ "name": "constant.character.entity.html"
349+ },
350+ {
351+ "match": "&",
352+ "name": "invalid.illegal.bad-ampersand.html"
353+ }
354+ ]
355+ },
356+ "python": {
357+ "begin": "(?:^\\s*)<\\?python(?!.*\\?>)",
358+ "end": "\\?>(?:\\s*$\\n)?",
359+ "contentName": "source.python.embedded.html",
360+ "patterns": [
361+ {
362+ "include": "source.python"
363+ }
364+ ]
365+ },
366+ "smarty": {
367+ "patterns": [
368+ {
369+ "begin": "(\\{(literal)\\})",
370+ "captures": {
371+ "1": {
372+ "name": "source.smarty.embedded.html"
373+ },
374+ "2": {
375+ "name": "support.function.built-in.smarty"
376+ }
377+ },
378+ "end": "(\\{/(literal)\\})"
379+ },
380+ {
381+ "begin": "{{|{",
382+ "disabled": 1,
383+ "end": "}}|}",
384+ "contentName": "source.smarty.embedded.html",
385+ "patterns": [
386+ {
387+ "include": "source.smarty"
388+ }
389+ ]
390+ }
391+ ]
392+ },
393+ "string-double-quoted": {
394+ "begin": "\"",
395+ "beginCaptures": {
396+ "0": {
397+ "name": "punctuation.definition.string.begin.html"
398+ }
399+ },
400+ "end": "\"",
401+ "endCaptures": {
402+ "0": {
403+ "name": "punctuation.definition.string.end.html"
404+ }
405+ },
406+ "name": "string.quoted.double.html",
407+ "patterns": [
408+ {
409+ "include": "#embedded-code"
410+ },
411+ {
412+ "include": "#entities"
413+ }
414+ ]
415+ },
416+ "string-single-quoted": {
417+ "begin": "'",
418+ "beginCaptures": {
419+ "0": {
420+ "name": "punctuation.definition.string.begin.html"
421+ }
422+ },
423+ "end": "'",
424+ "endCaptures": {
425+ "0": {
426+ "name": "punctuation.definition.string.end.html"
427+ }
428+ },
429+ "name": "string.quoted.single.html",
430+ "patterns": [
431+ {
432+ "include": "#embedded-code"
433+ },
434+ {
435+ "include": "#entities"
436+ }
437+ ]
438+ },
439+ "tag-generic-attribute": {
440+ "match": "(?<=[^=])\\b([a-zA-Z0-9:-]+)",
441+ "name": "entity.other.attribute-name.html"
442+ },
443+ "tag-id-attribute": {
444+ "begin": "\\b(id)\\b\\s*(=)",
445+ "captures": {
446+ "1": {
447+ "name": "entity.other.attribute-name.id.html"
448+ },
449+ "2": {
450+ "name": "punctuation.separator.key-value.html"
451+ }
452+ },
453+ "end": "(?!\\G)(?<='|\"|[^\\s<>/])",
454+ "name": "meta.attribute-with-value.id.html",
455+ "patterns": [
456+ {
457+ "begin": "\"",
458+ "beginCaptures": {
459+ "0": {
460+ "name": "punctuation.definition.string.begin.html"
461+ }
462+ },
463+ "contentName": "meta.toc-list.id.html",
464+ "end": "\"",
465+ "endCaptures": {
466+ "0": {
467+ "name": "punctuation.definition.string.end.html"
468+ }
469+ },
470+ "name": "string.quoted.double.html",
471+ "patterns": [
472+ {
473+ "include": "#embedded-code"
474+ },
475+ {
476+ "include": "#entities"
477+ }
478+ ]
479+ },
480+ {
481+ "begin": "'",
482+ "beginCaptures": {
483+ "0": {
484+ "name": "punctuation.definition.string.begin.html"
485+ }
486+ },
487+ "contentName": "meta.toc-list.id.html",
488+ "end": "'",
489+ "endCaptures": {
490+ "0": {
491+ "name": "punctuation.definition.string.end.html"
492+ }
493+ },
494+ "name": "string.quoted.single.html",
495+ "patterns": [
496+ {
497+ "include": "#embedded-code"
498+ },
499+ {
500+ "include": "#entities"
501+ }
502+ ]
503+ },
504+ {
505+ "captures": {
506+ "0": {
507+ "name": "meta.toc-list.id.html"
508+ }
509+ },
510+ "match": "(?<==)(?:[^\\s<>/'\"]|/(?!>))+",
511+ "name": "string.unquoted.html"
512+ }
513+ ]
514+ },
515+ "tag-stuff": {
516+ "patterns": [
517+ {
518+ "include": "#tag-id-attribute"
519+ },
520+ {
521+ "include": "#tag-generic-attribute"
522+ },
523+ {
524+ "include": "#string-double-quoted"
525+ },
526+ {
527+ "include": "#string-single-quoted"
528+ },
529+ {
530+ "include": "#embedded-code"
531+ },
532+ {
533+ "include": "#unquoted-attribute"
534+ }
535+ ]
536+ },
537+ "unquoted-attribute": {
538+ "match": "(?<==)(?:[^\\s<>/'\"]|/(?!>))+",
539+ "name": "string.unquoted.html"
540+ }
541+ },
542+ "scopeName": "text.html.basic",
543+ "uuid": "17994EC8-6B1D-11D9-AC3A-000D93589AF6",
544+ "version": "https://github.com/textmate/html.tmbundle/commit/9f812c89f4990a98391701caa77824c94860538f"
545+}
modified extensions/vscode/textmate-syntaxes/java.json +1026 −1029
@@ -1,1030 +1,1027 @@
11 {
2- "fileTypes": [
3- "java",
4- "bsh"
5- ],
6- "keyEquivalent": "^~J",
7- "name": "Java",
8- "patterns": [
9- {
10- "captures": {
11- "1": {
12- "name": "keyword.other.package.java"
13- },
14- "2": {
15- "name": "storage.modifier.package.java"
16- },
17- "3": {
18- "name": "punctuation.terminator.java"
19- }
20- },
21- "match": "^\\s*(package)\\b(?:\\s*([^ ;$]+)\\s*(;)?)?",
22- "name": "meta.package.java"
23- },
24- {
25- "begin": "(import static)\\b\\s*",
26- "beginCaptures": {
27- "1": {
28- "name": "keyword.other.import.static.java"
29- }
30- },
31- "captures": {
32- "1": {
33- "name": "keyword.other.import.java"
34- },
35- "2": {
36- "name": "storage.modifier.import.java"
37- },
38- "3": {
39- "name": "punctuation.terminator.java"
40- }
41- },
42- "contentName": "storage.modifier.import.java",
43- "end": "\\s*(?:$|(;))",
44- "endCaptures": {
45- "1": {
46- "name": "punctuation.terminator.java"
47- }
48- },
49- "name": "meta.import.java",
50- "patterns": [
51- {
52- "match": "\\.",
53- "name": "punctuation.separator.java"
54- },
55- {
56- "match": "\\s",
57- "name": "invalid.illegal.character_not_allowed_here.java"
58- }
59- ]
60- },
61- {
62- "begin": "(import)\\b\\s*",
63- "beginCaptures": {
64- "1": {
65- "name": "keyword.other.import.java"
66- }
67- },
68- "captures": {
69- "1": {
70- "name": "keyword.other.import.java"
71- },
72- "2": {
73- "name": "storage.modifier.import.java"
74- },
75- "3": {
76- "name": "punctuation.terminator.java"
77- }
78- },
79- "contentName": "storage.modifier.import.java",
80- "end": "\\s*(?:$|(;))",
81- "endCaptures": {
82- "1": {
83- "name": "punctuation.terminator.java"
84- }
85- },
86- "name": "meta.import.java",
87- "patterns": [
88- {
89- "match": "\\.",
90- "name": "punctuation.separator.java"
91- },
92- {
93- "match": "\\s",
94- "name": "invalid.illegal.character_not_allowed_here.java"
95- }
96- ]
97- },
98- {
99- "include": "#code"
100- }
101- ],
102- "repository": {
103- "all-types": {
104- "patterns": [
105- {
106- "include": "#primitive-arrays"
107- },
108- {
109- "include": "#primitive-types"
110- },
111- {
112- "include": "#object-types"
113- }
114- ]
115- },
116- "annotations": {
117- "patterns": [
118- {
119- "begin": "(@[^ (]+)(\\()",
120- "beginCaptures": {
121- "1": {
122- "name": "storage.type.annotation.java"
123- },
124- "2": {
125- "name": "punctuation.definition.annotation-arguments.begin.java"
126- }
127- },
128- "end": "(\\))",
129- "endCaptures": {
130- "1": {
131- "name": "punctuation.definition.annotation-arguments.end.java"
132- }
133- },
134- "name": "meta.declaration.annotation.java",
135- "patterns": [
136- {
137- "captures": {
138- "1": {
139- "name": "constant.other.key.java"
140- },
141- "2": {
142- "name": "keyword.operator.assignment.java"
143- }
144- },
145- "match": "(\\w*)\\s*(=)"
146- },
147- {
148- "include": "#code"
149- },
150- {
151- "match": ",",
152- "name": "punctuation.separator.property.java"
153- }
154- ]
155- },
156- {
157- "match": "@\\w*",
158- "name": "storage.type.annotation.java"
159- }
160- ]
161- },
162- "anonymous-classes-and-new": {
163- "begin": "\\bnew\\b",
164- "beginCaptures": {
165- "0": {
166- "name": "keyword.control.new.java"
167- }
168- },
169- "end": "(?<=\\)|\\])(?!\\s*{)|(?<=})|(?=;)",
170- "patterns": [
171- {
172- "begin": "(\\w+)\\s*(?=\\[)",
173- "beginCaptures": {
174- "1": {
175- "name": "storage.type.java"
176- }
177- },
178- "end": "(})|(?=\\s*(?:,|;|\\)))",
179- "endCaptures": {
180- "1": {
181- "name": "punctuation.section.block.end.java"
182- }
183- },
184- "patterns": [
185- {
186- "begin": "\\[",
187- "end": "\\]",
188- "patterns": [
189- {
190- "include": "#code"
191- }
192- ]
193- },
194- {
195- "begin": "{",
196- "beginCaptures": {
197- "0": {
198- "name": "punctuation.section.block.begin.java"
199- }
200- },
201- "end": "(?=})",
202- "patterns": [
203- {
204- "include": "#code"
205- }
206- ]
207- }
208- ]
209- },
210- {
211- "begin": "(?=\\w.*\\()",
212- "end": "(?<=\\))",
213- "patterns": [
214- {
215- "include": "#object-types"
216- },
217- {
218- "begin": "\\(",
219- "beginCaptures": {
220- "1": {
221- "name": "storage.type.java"
222- }
223- },
224- "end": "\\)",
225- "patterns": [
226- {
227- "include": "#code"
228- }
229- ]
230- }
231- ]
232- },
233- {
234- "begin": "{",
235- "beginCaptures": {
236- "0": {
237- "name": "punctuation.section.inner-class.begin.java"
238- }
239- },
240- "end": "}",
241- "endCaptures": {
242- "0": {
243- "name": "punctuation.section.inner-class.end.java"
244- }
245- },
246- "name": "meta.inner-class.java",
247- "patterns": [
248- {
249- "include": "#class-body"
250- }
251- ]
252- }
253- ]
254- },
255- "assertions": {
256- "patterns": [
257- {
258- "begin": "\\b(assert)\\s",
259- "beginCaptures": {
260- "1": {
261- "name": "keyword.control.assert.java"
262- }
263- },
264- "end": "$",
265- "name": "meta.declaration.assertion.java",
266- "patterns": [
267- {
268- "match": ":",
269- "name": "keyword.operator.assert.expression-seperator.java"
270- },
271- {
272- "include": "#code"
273- }
274- ]
275- }
276- ]
277- },
278- "class": {
279- "begin": "(?=\\w?[\\w\\s]*(?:class|(?:@)?interface|enum)\\s+\\w+)",
280- "end": "}",
281- "endCaptures": {
282- "0": {
283- "name": "punctuation.section.class.end.java"
284- }
285- },
286- "name": "meta.class.java",
287- "patterns": [
288- {
289- "include": "#storage-modifiers"
290- },
291- {
292- "include": "#comments"
293- },
294- {
295- "captures": {
296- "1": {
297- "name": "storage.modifier.java"
298- },
299- "2": {
300- "name": "entity.name.type.class.java"
301- }
302- },
303- "match": "(class|(?:@)?interface|enum)\\s+(\\w+)",
304- "name": "meta.class.identifier.java"
305- },
306- {
307- "begin": "extends",
308- "beginCaptures": {
309- "0": {
310- "name": "storage.modifier.extends.java"
311- }
312- },
313- "end": "(?={|implements)",
314- "name": "meta.definition.class.inherited.classes.java",
315- "patterns": [
316- {
317- "include": "#object-types-inherited"
318- },
319- {
320- "include": "#comments"
321- }
322- ]
323- },
324- {
325- "begin": "(implements)\\s",
326- "beginCaptures": {
327- "1": {
328- "name": "storage.modifier.implements.java"
329- }
330- },
331- "end": "(?=\\s*extends|\\{)",
332- "name": "meta.definition.class.implemented.interfaces.java",
333- "patterns": [
334- {
335- "include": "#object-types-inherited"
336- },
337- {
338- "include": "#comments"
339- }
340- ]
341- },
342- {
343- "begin": "{",
344- "beginCaptures": {
345- "0": {
346- "name": "punctuation.section.class.begin.java"
347- }
348- },
349- "end": "(?=})",
350- "name": "meta.class.body.java",
351- "patterns": [
352- {
353- "include": "#class-body"
354- }
355- ]
356- }
357- ]
358- },
359- "class-body": {
360- "patterns": [
361- {
362- "include": "#comments"
363- },
364- {
365- "include": "#class"
366- },
367- {
368- "include": "#enums"
369- },
370- {
371- "include": "#variables"
372- },
373- {
374- "include": "#methods"
375- },
376- {
377- "include": "#annotations"
378- },
379- {
380- "include": "#storage-modifiers"
381- },
382- {
383- "include": "#code"
384- }
385- ]
386- },
387- "code": {
388- "patterns": [
389- {
390- "include": "#comments"
391- },
392- {
393- "include": "#class"
394- },
395- {
396- "begin": "{",
397- "beginCaptures": {
398- "0": {
399- "name": "punctuation.section.block.begin.java"
400- }
401- },
402- "end": "}",
403- "endCaptures": {
404- "0": {
405- "name": "punctuation.section.block.end.java"
406- }
407- },
408- "patterns": [
409- {
410- "include": "#code"
411- }
412- ]
413- },
414- {
415- "include": "#assertions"
416- },
417- {
418- "include": "#parens"
419- },
420- {
421- "include": "#constants-and-special-vars"
422- },
423- {
424- "include": "#anonymous-classes-and-new"
425- },
426- {
427- "include": "#annotations"
428- },
429- {
430- "include": "#keywords"
431- },
432- {
433- "include": "#storage-modifiers"
434- },
435- {
436- "include": "#method-call"
437- },
438- {
439- "include": "#strings"
440- },
441- {
442- "include": "#all-types"
443- }
444- ]
445- },
446- "comments": {
447- "patterns": [
448- {
449- "captures": {
450- "0": {
451- "name": "punctuation.definition.comment.java"
452- }
453- },
454- "match": "/\\*\\*/",
455- "name": "comment.block.empty.java"
456- },
457- {
458- "include": "text.html.javadoc"
459- },
460- {
461- "include": "#comments-inline"
462- }
463- ]
464- },
465- "comments-inline": {
466- "patterns": [
467- {
468- "begin": "/\\*",
469- "captures": {
470- "0": {
471- "name": "punctuation.definition.comment.java"
472- }
473- },
474- "end": "\\*/",
475- "name": "comment.block.java"
476- },
477- {
478- "begin": "(^[ \\t]+)?(?=//)",
479- "beginCaptures": {
480- "1": {
481- "name": "punctuation.whitespace.comment.leading.java"
482- }
483- },
484- "end": "(?!\\G)",
485- "patterns": [
486- {
487- "begin": "//",
488- "beginCaptures": {
489- "0": {
490- "name": "punctuation.definition.comment.java"
491- }
492- },
493- "end": "\\n",
494- "name": "comment.line.double-slash.java"
495- }
496- ]
497- }
498- ]
499- },
500- "constants-and-special-vars": {
501- "patterns": [
502- {
503- "match": "\\b(true|false|null)\\b",
504- "name": "constant.language.java"
505- },
506- {
507- "match": "\\b(this|super)\\b",
508- "name": "variable.language.java"
509- },
510- {
511- "match": "\\b0[xX]\\h([\\h_]*\\h)?[lL]?(?!\\w|\\.)",
512- "name": "constant.numeric.hex.java"
513- },
514- {
515- "match": "\\b0[0-7_]*[0-7][lL]?\\b",
516- "name": "constant.numeric.octal.java"
517- },
518- {
519- "match": "\\b0[bB][01]([01_]*[01])?[lL]?\\b",
520- "name": "constant.numeric.binary.java"
521- },
522- {
523- "match": "\\b(0|[1-9]([0-9_]*[0-9])?)[lL]?(?!\\w|\\.)",
524- "name": "constant.numeric.integer.java"
525- },
526- {
527- "match": "(?x)\n\t\t\t\t\t\t(?<!\\w)\t\t\t\t\t\t\t\t\t\t# Ensure word boundry\n\t\t\t\t\t\t(?>\n\t\t\t\t\t\t\t0[xX]\t\t\t\t\t\t\t\t\t# Start literal\n\t\t\t\t\t\t\t(\\h([\\h_]*\\h)?)?\t\t\t\t\t\t# Optional Number\n\t\t\t\t\t\t\t(\n\t\t\t\t\t\t\t\t(?<=\\h)\\.\t\t\t\t\t\t\t# A number must exist on\n\t\t\t\t\t\t | \\.(?=\\h)\t\t\t\t\t\t\t# one side of the decimal\n\t\t\t\t\t\t | (?<=\\h)\t\t\t\t\t\t\t\t# Decimal not required\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t(\\h([\\h_]*\\h)?)?\t\t\t\t\t\t# Optional Number\n\t\t\t\t\t\t\t[pP]\t\t\t\t\t\t\t\t\t# Exponent Indicator\n\t\t\t\t\t\t\t[+-]?(0|[1-9]([0-9_]*[0-9])?)\t\t\t# Signed Integer\n\t\t\t\t\t\t\t[fFdD]?\t\t\t\t\t\t\t\t\t# Float Type Suffix\n\t\t\t\t\t\t)\n\t\t\t\t\t\t(?!\\w)\t\t\t\t\t\t\t\t\t\t# Ensure word boundry\n\t\t\t\t\t",
528- "name": "constant.numeric.hex-float.java"
529- },
530- {
531- "match": "(?x)\n\t\t\t\t\t\t(?<!\\w)\t\t\t\t\t\t\t\t\t\t\t# Ensure word boundry\n\t\t\t\t\t\t(?>\n\t\t\t\t\t\t\t(\n\t\t\t\t\t\t\t\t(0|[1-9]([0-9_]*[0-9])?)\t\t\t\t# Leading digits\n\t\t\t\t\t\t\t\t(?=[eEfFdD.])\t\t\t\t\t\t\t# Allow for numbers without .\n\t\t\t\t\t\t\t)?\n\t\t\t\t\t\t\t(\n\t\t\t\t\t\t\t\t(?<=[0-9])(?=[eEfFdD])\t\t\t\t\t# Allow for numbers without .\n\t\t\t\t\t\t\t | \\.\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t(\n\t\t\t\t\t\t\t\t[0-9]([0-9_]*[0-9])?\t\t\t\t\t# Numbers after .\n\t\t\t\t\t\t\t)?\n\t\t\t\t\t\t\t(\n\t\t\t\t\t\t\t\t[eE][+-]?(0|[1-9]([0-9_]*[0-9])?)\t\t# Exponent\n\t\t\t\t\t\t\t)?\n\t\t\t\t\t\t\t[fFdD]?\t\t\t\t\t\t\t\t\t\t# Float Type Suffix\n\t\t\t\t\t\t)\n\t\t\t\t\t\t(?!\\w)\t\t\t\t\t\t\t\t\t\t\t# Ensure word boundry\n\t\t\t\t\t",
532- "name": "constant.numeric.float.java"
533- },
534- {
535- "captures": {
536- "1": {
537- "name": "keyword.operator.dereference.java"
538- }
539- },
540- "match": "(\\.)?\\b([A-Z][A-Z0-9_]+)(?!<|\\.class|\\s*\\w+\\s*=)\\b",
541- "name": "constant.other.java"
542- }
543- ]
544- },
545- "enums": {
546- "begin": "^(?=\\s*[A-Z0-9_]+\\s*({|\\(|,))",
547- "end": "(?=;|})",
548- "patterns": [
549- {
550- "begin": "\\w+",
551- "beginCaptures": {
552- "0": {
553- "name": "constant.other.enum.java"
554- }
555- },
556- "end": "(?=,|;|})",
557- "name": "meta.enum.java",
558- "patterns": [
559- {
560- "include": "#parens"
561- },
562- {
563- "begin": "{",
564- "beginCaptures": {
565- "0": {
566- "name": "punctuation.section.enum.begin.java"
567- }
568- },
569- "end": "}",
570- "endCaptures": {
571- "0": {
572- "name": "punctuation.section.enum.end.java"
573- }
574- },
575- "patterns": [
576- {
577- "include": "#class-body"
578- }
579- ]
580- }
581- ]
582- },
583- {
584- "include": "#comments"
585- },
586- {
587- "include": "#annotations"
588- }
589- ]
590- },
591- "keywords": {
592- "patterns": [
593- {
594- "match": "\\b(try|catch|finally|throw)\\b",
595- "name": "keyword.control.catch-exception.java"
596- },
597- {
598- "match": "\\?|:",
599- "name": "keyword.control.ternary.java"
600- },
601- {
602- "match": "\\b(return|break|case|continue|default|do|while|for|switch|if|else)\\b",
603- "name": "keyword.control.java"
604- },
605- {
606- "match": "\\b(instanceof)\\b",
607- "name": "keyword.operator.java"
608- },
609- {
610- "match": "(<<|>>>?|~|\\^)",
611- "name": "keyword.operator.bitwise.java"
612- },
613- {
614- "match": "((&|\\^|\\||<<|>>>?)=)",
615- "name": "keyword.operator.assignment.bitwise.java"
616- },
617- {
618- "match": "(===?|!=|<=|>=|<>|<|>)",
619- "name": "keyword.operator.comparison.java"
620- },
621- {
622- "match": "([+*/%-]=)",
623- "name": "keyword.operator.assignment.arithmetic.java"
624- },
625- {
626- "match": "(=)",
627- "name": "keyword.operator.assignment.java"
628- },
629- {
630- "match": "(\\-\\-|\\+\\+)",
631- "name": "keyword.operator.increment-decrement.java"
632- },
633- {
634- "match": "(\\-|\\+|\\*|\\/|%)",
635- "name": "keyword.operator.arithmetic.java"
636- },
637- {
638- "match": "(!|&&|\\|\\|)",
639- "name": "keyword.operator.logical.java"
640- },
641- {
642- "match": "(\\||&)",
643- "name": "keyword.operator.bitwise.java"
644- },
645- {
646- "match": "(?<=\\S)\\.(?=\\S)",
647- "name": "keyword.operator.dereference.java"
648- },
649- {
650- "match": ";",
651- "name": "punctuation.terminator.java"
652- }
653- ]
654- },
655- "method-call": {
656- "begin": "([\\w$]+)(\\()",
657- "beginCaptures": {
658- "1": {
659- "name": "meta.method.java"
660- },
661- "2": {
662- "name": "punctuation.definition.method-parameters.begin.java"
663- }
664- },
665- "end": "\\)",
666- "endCaptures": {
667- "0": {
668- "name": "punctuation.definition.method-parameters.end.java"
669- }
670- },
671- "name": "meta.method-call.java",
672- "patterns": [
673- {
674- "match": ",",
675- "name": "punctuation.definition.seperator.parameter.java"
676- },
677- {
678- "include": "#code"
679- }
680- ]
681- },
682- "methods": {
683- "begin": "(?!new)(?=[\\w<].*\\s+)(?=([^=/]|/(?!/))+\\()",
684- "end": "(})|(?=;)",
685- "endCaptures": {
686- "1": {
687- "name": "punctuation.section.method.end.java"
688- }
689- },
690- "name": "meta.method.java",
691- "patterns": [
692- {
693- "include": "#storage-modifiers"
694- },
695- {
696- "begin": "(\\w+)\\s*\\(",
697- "beginCaptures": {
698- "1": {
699- "name": "entity.name.function.java"
700- }
701- },
702- "end": "\\)",
703- "name": "meta.method.identifier.java",
704- "patterns": [
705- {
706- "include": "#parameters"
707- },
708- {
709- "include": "#comments"
710- }
711- ]
712- },
713- {
714- "begin": "<",
715- "end": ">",
716- "name": "storage.type.token.java",
717- "patterns": [
718- {
719- "include": "#object-types"
720- },
721- {
722- "begin": "<",
723- "comment": "This is just to support <>'s with no actual type prefix",
724- "end": ">|[^\\w\\s,\\[\\]<]",
725- "name": "storage.type.generic.java"
726- }
727- ]
728- },
729- {
730- "begin": "(?=\\w.*\\s+\\w+\\s*\\()",
731- "end": "(?=\\w+\\s*\\()",
732- "name": "meta.method.return-type.java",
733- "patterns": [
734- {
735- "include": "#all-types"
736- },
737- {
738- "include": "#comments"
739- }
740- ]
741- },
742- {
743- "include": "#throws"
744- },
745- {
746- "begin": "{",
747- "beginCaptures": {
748- "0": {
749- "name": "punctuation.section.method.begin.java"
750- }
751- },
752- "end": "(?=})",
753- "name": "meta.method.body.java",
754- "patterns": [
755- {
756- "include": "#code"
757- }
758- ]
759- },
760- {
761- "include": "#comments"
762- }
763- ]
764- },
765- "object-types": {
766- "patterns": [
767- {
768- "begin": "\\b((?:[a-z]\\w*\\.)*[A-Z]+\\w*)<",
769- "end": ">|[^\\w\\s,\\?<\\[\\]]",
770- "name": "storage.type.generic.java",
771- "patterns": [
772- {
773- "include": "#object-types"
774- },
775- {
776- "begin": "<",
777- "comment": "This is just to support <>'s with no actual type prefix",
778- "end": ">|[^\\w\\s,\\[\\]<]",
779- "name": "storage.type.generic.java"
780- }
781- ]
782- },
783- {
784- "begin": "\\b((?:[a-z]\\w*\\.)*[A-Z]+\\w*)(?=\\[)",
785- "end": "(?=[^\\]\\s])",
786- "name": "storage.type.object.array.java",
787- "patterns": [
788- {
789- "begin": "\\[",
790- "end": "\\]",
791- "patterns": [
792- {
793- "include": "#code"
794- }
795- ]
796- }
797- ]
798- },
799- {
800- "captures": {
801- "1": {
802- "name": "keyword.operator.dereference.java"
803- }
804- },
805- "match": "\\b(?:[a-z]\\w*(\\.))*[A-Z]+\\w*\\b",
806- "name": "storage.type.java"
807- }
808- ]
809- },
810- "object-types-inherited": {
811- "patterns": [
812- {
813- "begin": "\\b((?:[a-z]\\w*\\.)*[A-Z]+\\w*)<",
814- "end": ">|[^\\w\\s,<]",
815- "name": "entity.other.inherited-class.java",
816- "patterns": [
817- {
818- "include": "#object-types"
819- },
820- {
821- "begin": "<",
822- "comment": "This is just to support <>'s with no actual type prefix",
823- "end": ">|[^\\w\\s,<]",
824- "name": "storage.type.generic.java"
825- }
826- ]
827- },
828- {
829- "captures": {
830- "1": {
831- "name": "keyword.operator.dereference.java"
832- }
833- },
834- "match": "\\b(?:[a-z]\\w*(\\.))*[A-Z]+\\w*",
835- "name": "entity.other.inherited-class.java"
836- }
837- ]
838- },
839- "parameters": {
840- "patterns": [
841- {
842- "match": "final",
843- "name": "storage.modifier.java"
844- },
845- {
846- "include": "#annotations"
847- },
848- {
849- "include": "#primitive-arrays"
850- },
851- {
852- "include": "#primitive-types"
853- },
854- {
855- "include": "#object-types"
856- },
857- {
858- "match": "\\w+",
859- "name": "variable.parameter.java"
860- }
861- ]
862- },
863- "parens": {
864- "begin": "\\(",
865- "end": "\\)",
866- "patterns": [
867- {
868- "include": "#code"
869- }
870- ]
871- },
872- "primitive-arrays": {
873- "patterns": [
874- {
875- "match": "\\b(?:void|boolean|byte|char|short|int|float|long|double)(\\[\\])*\\b",
876- "name": "storage.type.primitive.array.java"
877- }
878- ]
879- },
880- "primitive-types": {
881- "patterns": [
882- {
883- "match": "\\b(?:void|boolean|byte|char|short|int|float|long|double)\\b",
884- "name": "storage.type.primitive.java"
885- }
886- ]
887- },
888- "storage-modifiers": {
889- "captures": {
890- "1": {
891- "name": "storage.modifier.java"
892- }
893- },
894- "match": "\\b(public|private|protected|static|final|native|synchronized|volatile|abstract|threadsafe|transient)\\b"
895- },
896- "strings": {
897- "patterns": [
898- {
899- "begin": "\"",
900- "beginCaptures": {
901- "0": {
902- "name": "punctuation.definition.string.begin.java"
903- }
904- },
905- "end": "\"",
906- "endCaptures": {
907- "0": {
908- "name": "punctuation.definition.string.end.java"
909- }
910- },
911- "name": "string.quoted.double.java",
912- "patterns": [
913- {
914- "match": "\\\\.",
915- "name": "constant.character.escape.java"
916- }
917- ]
918- },
919- {
920- "begin": "'",
921- "beginCaptures": {
922- "0": {
923- "name": "punctuation.definition.string.begin.java"
924- }
925- },
926- "end": "'",
927- "endCaptures": {
928- "0": {
929- "name": "punctuation.definition.string.end.java"
930- }
931- },
932- "name": "string.quoted.single.java",
933- "patterns": [
934- {
935- "match": "\\\\.",
936- "name": "constant.character.escape.java"
937- }
938- ]
939- }
940- ]
941- },
942- "throws": {
943- "begin": "throws",
944- "beginCaptures": {
945- "0": {
946- "name": "storage.modifier.java"
947- }
948- },
949- "end": "(?={|;)",
950- "name": "meta.throwables.java",
951- "patterns": [
952- {
953- "include": "#object-types"
954- }
955- ]
956- },
957- "values": {
958- "patterns": [
959- {
960- "include": "#strings"
961- },
962- {
963- "include": "#object-types"
964- },
965- {
966- "include": "#constants-and-special-vars"
967- }
968- ]
969- },
970- "variables": {
971- "applyEndPatternLast": 1,
972- "patterns": [
973- {
974- "begin": "(?x:(?=\n (?:\n (?:private|protected|public|native|synchronized|volatile|abstract|threadsafe|transient|static|final) # visibility/modifier\n |\n (?:def)\n |\n (?:void|boolean|byte|char|short|int|float|long|double)\n |\n (?:(?:[a-z]\\w*\\.)*[A-Z]+\\w*) # object type\n )\n \\s+\n (?!private|protected|public|native|synchronized|volatile|abstract|threadsafe|transient|static|final|def|void|boolean|byte|char|short|int|float|long|double)\n [\\w\\d_<>\\[\\],\\?][\\w\\d_<>\\[\\],\\? \\t]*\n (?:=|$)\n \n\t\t\t\t\t))",
975- "end": "(?=;)",
976- "name": "meta.definition.variable.java",
977- "patterns": [
978- {
979- "match": "\\s"
980- },
981- {
982- "captures": {
983- "1": {
984- "name": "constant.other.variable.java"
985- }
986- },
987- "match": "([A-Z_0-9]+)\\s+(?=\\=)"
988- },
989- {
990- "captures": {
991- "1": {
992- "name": "meta.definition.variable.name.java"
993- }
994- },
995- "match": "(\\w[^\\s,]*)\\s+(?=\\=)"
996- },
997- {
998- "begin": "=",
999- "beginCaptures": {
1000- "0": {
1001- "name": "keyword.operator.assignment.java"
1002- }
1003- },
1004- "end": "(?=;)",
1005- "patterns": [
1006- {
1007- "include": "#code"
1008- }
1009- ]
1010- },
1011- {
1012- "captures": {
1013- "1": {
1014- "name": "meta.definition.variable.name.java"
1015- }
1016- },
1017- "match": "(\\w[^\\s=]*)(?=\\s*;)"
1018- },
1019- {
1020- "include": "#code"
1021- }
1022- ]
1023- }
1024- ]
1025- }
1026- },
1027- "scopeName": "source.java",
1028- "uuid": "2B449DF6-6B1D-11D9-94EC-000D93589AF6",
1029- "version": "https://github.com/textmate/java.tmbundle/commit/faffa518d0b22b68b4e5e6b4c939722522b97d40"
1030-}
No newline at the end of the file
2+ "fileTypes": ["java", "bsh"],
3+ "keyEquivalent": "^~J",
4+ "name": "Java",
5+ "patterns": [
6+ {
7+ "captures": {
8+ "1": {
9+ "name": "keyword.other.package.java"
10+ },
11+ "2": {
12+ "name": "storage.modifier.package.java"
13+ },
14+ "3": {
15+ "name": "punctuation.terminator.java"
16+ }
17+ },
18+ "match": "^\\s*(package)\\b(?:\\s*([^ ;$]+)\\s*(;)?)?",
19+ "name": "meta.package.java"
20+ },
21+ {
22+ "begin": "(import static)\\b\\s*",
23+ "beginCaptures": {
24+ "1": {
25+ "name": "keyword.other.import.static.java"
26+ }
27+ },
28+ "captures": {
29+ "1": {
30+ "name": "keyword.other.import.java"
31+ },
32+ "2": {
33+ "name": "storage.modifier.import.java"
34+ },
35+ "3": {
36+ "name": "punctuation.terminator.java"
37+ }
38+ },
39+ "contentName": "storage.modifier.import.java",
40+ "end": "\\s*(?:$|(;))",
41+ "endCaptures": {
42+ "1": {
43+ "name": "punctuation.terminator.java"
44+ }
45+ },
46+ "name": "meta.import.java",
47+ "patterns": [
48+ {
49+ "match": "\\.",
50+ "name": "punctuation.separator.java"
51+ },
52+ {
53+ "match": "\\s",
54+ "name": "invalid.illegal.character_not_allowed_here.java"
55+ }
56+ ]
57+ },
58+ {
59+ "begin": "(import)\\b\\s*",
60+ "beginCaptures": {
61+ "1": {
62+ "name": "keyword.other.import.java"
63+ }
64+ },
65+ "captures": {
66+ "1": {
67+ "name": "keyword.other.import.java"
68+ },
69+ "2": {
70+ "name": "storage.modifier.import.java"
71+ },
72+ "3": {
73+ "name": "punctuation.terminator.java"
74+ }
75+ },
76+ "contentName": "storage.modifier.import.java",
77+ "end": "\\s*(?:$|(;))",
78+ "endCaptures": {
79+ "1": {
80+ "name": "punctuation.terminator.java"
81+ }
82+ },
83+ "name": "meta.import.java",
84+ "patterns": [
85+ {
86+ "match": "\\.",
87+ "name": "punctuation.separator.java"
88+ },
89+ {
90+ "match": "\\s",
91+ "name": "invalid.illegal.character_not_allowed_here.java"
92+ }
93+ ]
94+ },
95+ {
96+ "include": "#code"
97+ }
98+ ],
99+ "repository": {
100+ "all-types": {
101+ "patterns": [
102+ {
103+ "include": "#primitive-arrays"
104+ },
105+ {
106+ "include": "#primitive-types"
107+ },
108+ {
109+ "include": "#object-types"
110+ }
111+ ]
112+ },
113+ "annotations": {
114+ "patterns": [
115+ {
116+ "begin": "(@[^ (]+)(\\()",
117+ "beginCaptures": {
118+ "1": {
119+ "name": "storage.type.annotation.java"
120+ },
121+ "2": {
122+ "name": "punctuation.definition.annotation-arguments.begin.java"
123+ }
124+ },
125+ "end": "(\\))",
126+ "endCaptures": {
127+ "1": {
128+ "name": "punctuation.definition.annotation-arguments.end.java"
129+ }
130+ },
131+ "name": "meta.declaration.annotation.java",
132+ "patterns": [
133+ {
134+ "captures": {
135+ "1": {
136+ "name": "constant.other.key.java"
137+ },
138+ "2": {
139+ "name": "keyword.operator.assignment.java"
140+ }
141+ },
142+ "match": "(\\w*)\\s*(=)"
143+ },
144+ {
145+ "include": "#code"
146+ },
147+ {
148+ "match": ",",
149+ "name": "punctuation.separator.property.java"
150+ }
151+ ]
152+ },
153+ {
154+ "match": "@\\w*",
155+ "name": "storage.type.annotation.java"
156+ }
157+ ]
158+ },
159+ "anonymous-classes-and-new": {
160+ "begin": "\\bnew\\b",
161+ "beginCaptures": {
162+ "0": {
163+ "name": "keyword.control.new.java"
164+ }
165+ },
166+ "end": "(?<=\\)|\\])(?!\\s*{)|(?<=})|(?=;)",
167+ "patterns": [
168+ {
169+ "begin": "(\\w+)\\s*(?=\\[)",
170+ "beginCaptures": {
171+ "1": {
172+ "name": "storage.type.java"
173+ }
174+ },
175+ "end": "(})|(?=\\s*(?:,|;|\\)))",
176+ "endCaptures": {
177+ "1": {
178+ "name": "punctuation.section.block.end.java"
179+ }
180+ },
181+ "patterns": [
182+ {
183+ "begin": "\\[",
184+ "end": "\\]",
185+ "patterns": [
186+ {
187+ "include": "#code"
188+ }
189+ ]
190+ },
191+ {
192+ "begin": "{",
193+ "beginCaptures": {
194+ "0": {
195+ "name": "punctuation.section.block.begin.java"
196+ }
197+ },
198+ "end": "(?=})",
199+ "patterns": [
200+ {
201+ "include": "#code"
202+ }
203+ ]
204+ }
205+ ]
206+ },
207+ {
208+ "begin": "(?=\\w.*\\()",
209+ "end": "(?<=\\))",
210+ "patterns": [
211+ {
212+ "include": "#object-types"
213+ },
214+ {
215+ "begin": "\\(",
216+ "beginCaptures": {
217+ "1": {
218+ "name": "storage.type.java"
219+ }
220+ },
221+ "end": "\\)",
222+ "patterns": [
223+ {
224+ "include": "#code"
225+ }
226+ ]
227+ }
228+ ]
229+ },
230+ {
231+ "begin": "{",
232+ "beginCaptures": {
233+ "0": {
234+ "name": "punctuation.section.inner-class.begin.java"
235+ }
236+ },
237+ "end": "}",
238+ "endCaptures": {
239+ "0": {
240+ "name": "punctuation.section.inner-class.end.java"
241+ }
242+ },
243+ "name": "meta.inner-class.java",
244+ "patterns": [
245+ {
246+ "include": "#class-body"
247+ }
248+ ]
249+ }
250+ ]
251+ },
252+ "assertions": {
253+ "patterns": [
254+ {
255+ "begin": "\\b(assert)\\s",
256+ "beginCaptures": {
257+ "1": {
258+ "name": "keyword.control.assert.java"
259+ }
260+ },
261+ "end": "$",
262+ "name": "meta.declaration.assertion.java",
263+ "patterns": [
264+ {
265+ "match": ":",
266+ "name": "keyword.operator.assert.expression-seperator.java"
267+ },
268+ {
269+ "include": "#code"
270+ }
271+ ]
272+ }
273+ ]
274+ },
275+ "class": {
276+ "begin": "(?=\\w?[\\w\\s]*(?:class|(?:@)?interface|enum)\\s+\\w+)",
277+ "end": "}",
278+ "endCaptures": {
279+ "0": {
280+ "name": "punctuation.section.class.end.java"
281+ }
282+ },
283+ "name": "meta.class.java",
284+ "patterns": [
285+ {
286+ "include": "#storage-modifiers"
287+ },
288+ {
289+ "include": "#comments"
290+ },
291+ {
292+ "captures": {
293+ "1": {
294+ "name": "storage.modifier.java"
295+ },
296+ "2": {
297+ "name": "entity.name.type.class.java"
298+ }
299+ },
300+ "match": "(class|(?:@)?interface|enum)\\s+(\\w+)",
301+ "name": "meta.class.identifier.java"
302+ },
303+ {
304+ "begin": "extends",
305+ "beginCaptures": {
306+ "0": {
307+ "name": "storage.modifier.extends.java"
308+ }
309+ },
310+ "end": "(?={|implements)",
311+ "name": "meta.definition.class.inherited.classes.java",
312+ "patterns": [
313+ {
314+ "include": "#object-types-inherited"
315+ },
316+ {
317+ "include": "#comments"
318+ }
319+ ]
320+ },
321+ {
322+ "begin": "(implements)\\s",
323+ "beginCaptures": {
324+ "1": {
325+ "name": "storage.modifier.implements.java"
326+ }
327+ },
328+ "end": "(?=\\s*extends|\\{)",
329+ "name": "meta.definition.class.implemented.interfaces.java",
330+ "patterns": [
331+ {
332+ "include": "#object-types-inherited"
333+ },
334+ {
335+ "include": "#comments"
336+ }
337+ ]
338+ },
339+ {
340+ "begin": "{",
341+ "beginCaptures": {
342+ "0": {
343+ "name": "punctuation.section.class.begin.java"
344+ }
345+ },
346+ "end": "(?=})",
347+ "name": "meta.class.body.java",
348+ "patterns": [
349+ {
350+ "include": "#class-body"
351+ }
352+ ]
353+ }
354+ ]
355+ },
356+ "class-body": {
357+ "patterns": [
358+ {
359+ "include": "#comments"
360+ },
361+ {
362+ "include": "#class"
363+ },
364+ {
365+ "include": "#enums"
366+ },
367+ {
368+ "include": "#variables"
369+ },
370+ {
371+ "include": "#methods"
372+ },
373+ {
374+ "include": "#annotations"
375+ },
376+ {
377+ "include": "#storage-modifiers"
378+ },
379+ {
380+ "include": "#code"
381+ }
382+ ]
383+ },
384+ "code": {
385+ "patterns": [
386+ {
387+ "include": "#comments"
388+ },
389+ {
390+ "include": "#class"
391+ },
392+ {
393+ "begin": "{",
394+ "beginCaptures": {
395+ "0": {
396+ "name": "punctuation.section.block.begin.java"
397+ }
398+ },
399+ "end": "}",
400+ "endCaptures": {
401+ "0": {
402+ "name": "punctuation.section.block.end.java"
403+ }
404+ },
405+ "patterns": [
406+ {
407+ "include": "#code"
408+ }
409+ ]
410+ },
411+ {
412+ "include": "#assertions"
413+ },
414+ {
415+ "include": "#parens"
416+ },
417+ {
418+ "include": "#constants-and-special-vars"
419+ },
420+ {
421+ "include": "#anonymous-classes-and-new"
422+ },
423+ {
424+ "include": "#annotations"
425+ },
426+ {
427+ "include": "#keywords"
428+ },
429+ {
430+ "include": "#storage-modifiers"
431+ },
432+ {
433+ "include": "#method-call"
434+ },
435+ {
436+ "include": "#strings"
437+ },
438+ {
439+ "include": "#all-types"
440+ }
441+ ]
442+ },
443+ "comments": {
444+ "patterns": [
445+ {
446+ "captures": {
447+ "0": {
448+ "name": "punctuation.definition.comment.java"
449+ }
450+ },
451+ "match": "/\\*\\*/",
452+ "name": "comment.block.empty.java"
453+ },
454+ {
455+ "include": "text.html.javadoc"
456+ },
457+ {
458+ "include": "#comments-inline"
459+ }
460+ ]
461+ },
462+ "comments-inline": {
463+ "patterns": [
464+ {
465+ "begin": "/\\*",
466+ "captures": {
467+ "0": {
468+ "name": "punctuation.definition.comment.java"
469+ }
470+ },
471+ "end": "\\*/",
472+ "name": "comment.block.java"
473+ },
474+ {
475+ "begin": "(^[ \\t]+)?(?=//)",
476+ "beginCaptures": {
477+ "1": {
478+ "name": "punctuation.whitespace.comment.leading.java"
479+ }
480+ },
481+ "end": "(?!\\G)",
482+ "patterns": [
483+ {
484+ "begin": "//",
485+ "beginCaptures": {
486+ "0": {
487+ "name": "punctuation.definition.comment.java"
488+ }
489+ },
490+ "end": "\\n",
491+ "name": "comment.line.double-slash.java"
492+ }
493+ ]
494+ }
495+ ]
496+ },
497+ "constants-and-special-vars": {
498+ "patterns": [
499+ {
500+ "match": "\\b(true|false|null)\\b",
501+ "name": "constant.language.java"
502+ },
503+ {
504+ "match": "\\b(this|super)\\b",
505+ "name": "variable.language.java"
506+ },
507+ {
508+ "match": "\\b0[xX]\\h([\\h_]*\\h)?[lL]?(?!\\w|\\.)",
509+ "name": "constant.numeric.hex.java"
510+ },
511+ {
512+ "match": "\\b0[0-7_]*[0-7][lL]?\\b",
513+ "name": "constant.numeric.octal.java"
514+ },
515+ {
516+ "match": "\\b0[bB][01]([01_]*[01])?[lL]?\\b",
517+ "name": "constant.numeric.binary.java"
518+ },
519+ {
520+ "match": "\\b(0|[1-9]([0-9_]*[0-9])?)[lL]?(?!\\w|\\.)",
521+ "name": "constant.numeric.integer.java"
522+ },
523+ {
524+ "match": "(?x)\n\t\t\t\t\t\t(?<!\\w)\t\t\t\t\t\t\t\t\t\t# Ensure word boundry\n\t\t\t\t\t\t(?>\n\t\t\t\t\t\t\t0[xX]\t\t\t\t\t\t\t\t\t# Start literal\n\t\t\t\t\t\t\t(\\h([\\h_]*\\h)?)?\t\t\t\t\t\t# Optional Number\n\t\t\t\t\t\t\t(\n\t\t\t\t\t\t\t\t(?<=\\h)\\.\t\t\t\t\t\t\t# A number must exist on\n\t\t\t\t\t\t | \\.(?=\\h)\t\t\t\t\t\t\t# one side of the decimal\n\t\t\t\t\t\t | (?<=\\h)\t\t\t\t\t\t\t\t# Decimal not required\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t(\\h([\\h_]*\\h)?)?\t\t\t\t\t\t# Optional Number\n\t\t\t\t\t\t\t[pP]\t\t\t\t\t\t\t\t\t# Exponent Indicator\n\t\t\t\t\t\t\t[+-]?(0|[1-9]([0-9_]*[0-9])?)\t\t\t# Signed Integer\n\t\t\t\t\t\t\t[fFdD]?\t\t\t\t\t\t\t\t\t# Float Type Suffix\n\t\t\t\t\t\t)\n\t\t\t\t\t\t(?!\\w)\t\t\t\t\t\t\t\t\t\t# Ensure word boundry\n\t\t\t\t\t",
525+ "name": "constant.numeric.hex-float.java"
526+ },
527+ {
528+ "match": "(?x)\n\t\t\t\t\t\t(?<!\\w)\t\t\t\t\t\t\t\t\t\t\t# Ensure word boundry\n\t\t\t\t\t\t(?>\n\t\t\t\t\t\t\t(\n\t\t\t\t\t\t\t\t(0|[1-9]([0-9_]*[0-9])?)\t\t\t\t# Leading digits\n\t\t\t\t\t\t\t\t(?=[eEfFdD.])\t\t\t\t\t\t\t# Allow for numbers without .\n\t\t\t\t\t\t\t)?\n\t\t\t\t\t\t\t(\n\t\t\t\t\t\t\t\t(?<=[0-9])(?=[eEfFdD])\t\t\t\t\t# Allow for numbers without .\n\t\t\t\t\t\t\t | \\.\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t(\n\t\t\t\t\t\t\t\t[0-9]([0-9_]*[0-9])?\t\t\t\t\t# Numbers after .\n\t\t\t\t\t\t\t)?\n\t\t\t\t\t\t\t(\n\t\t\t\t\t\t\t\t[eE][+-]?(0|[1-9]([0-9_]*[0-9])?)\t\t# Exponent\n\t\t\t\t\t\t\t)?\n\t\t\t\t\t\t\t[fFdD]?\t\t\t\t\t\t\t\t\t\t# Float Type Suffix\n\t\t\t\t\t\t)\n\t\t\t\t\t\t(?!\\w)\t\t\t\t\t\t\t\t\t\t\t# Ensure word boundry\n\t\t\t\t\t",
529+ "name": "constant.numeric.float.java"
530+ },
531+ {
532+ "captures": {
533+ "1": {
534+ "name": "keyword.operator.dereference.java"
535+ }
536+ },
537+ "match": "(\\.)?\\b([A-Z][A-Z0-9_]+)(?!<|\\.class|\\s*\\w+\\s*=)\\b",
538+ "name": "constant.other.java"
539+ }
540+ ]
541+ },
542+ "enums": {
543+ "begin": "^(?=\\s*[A-Z0-9_]+\\s*({|\\(|,))",
544+ "end": "(?=;|})",
545+ "patterns": [
546+ {
547+ "begin": "\\w+",
548+ "beginCaptures": {
549+ "0": {
550+ "name": "constant.other.enum.java"
551+ }
552+ },
553+ "end": "(?=,|;|})",
554+ "name": "meta.enum.java",
555+ "patterns": [
556+ {
557+ "include": "#parens"
558+ },
559+ {
560+ "begin": "{",
561+ "beginCaptures": {
562+ "0": {
563+ "name": "punctuation.section.enum.begin.java"
564+ }
565+ },
566+ "end": "}",
567+ "endCaptures": {
568+ "0": {
569+ "name": "punctuation.section.enum.end.java"
570+ }
571+ },
572+ "patterns": [
573+ {
574+ "include": "#class-body"
575+ }
576+ ]
577+ }
578+ ]
579+ },
580+ {
581+ "include": "#comments"
582+ },
583+ {
584+ "include": "#annotations"
585+ }
586+ ]
587+ },
588+ "keywords": {
589+ "patterns": [
590+ {
591+ "match": "\\b(try|catch|finally|throw)\\b",
592+ "name": "keyword.control.catch-exception.java"
593+ },
594+ {
595+ "match": "\\?|:",
596+ "name": "keyword.control.ternary.java"
597+ },
598+ {
599+ "match": "\\b(return|break|case|continue|default|do|while|for|switch|if|else)\\b",
600+ "name": "keyword.control.java"
601+ },
602+ {
603+ "match": "\\b(instanceof)\\b",
604+ "name": "keyword.operator.java"
605+ },
606+ {
607+ "match": "(<<|>>>?|~|\\^)",
608+ "name": "keyword.operator.bitwise.java"
609+ },
610+ {
611+ "match": "((&|\\^|\\||<<|>>>?)=)",
612+ "name": "keyword.operator.assignment.bitwise.java"
613+ },
614+ {
615+ "match": "(===?|!=|<=|>=|<>|<|>)",
616+ "name": "keyword.operator.comparison.java"
617+ },
618+ {
619+ "match": "([+*/%-]=)",
620+ "name": "keyword.operator.assignment.arithmetic.java"
621+ },
622+ {
623+ "match": "(=)",
624+ "name": "keyword.operator.assignment.java"
625+ },
626+ {
627+ "match": "(\\-\\-|\\+\\+)",
628+ "name": "keyword.operator.increment-decrement.java"
629+ },
630+ {
631+ "match": "(\\-|\\+|\\*|\\/|%)",
632+ "name": "keyword.operator.arithmetic.java"
633+ },
634+ {
635+ "match": "(!|&&|\\|\\|)",
636+ "name": "keyword.operator.logical.java"
637+ },
638+ {
639+ "match": "(\\||&)",
640+ "name": "keyword.operator.bitwise.java"
641+ },
642+ {
643+ "match": "(?<=\\S)\\.(?=\\S)",
644+ "name": "keyword.operator.dereference.java"
645+ },
646+ {
647+ "match": ";",
648+ "name": "punctuation.terminator.java"
649+ }
650+ ]
651+ },
652+ "method-call": {
653+ "begin": "([\\w$]+)(\\()",
654+ "beginCaptures": {
655+ "1": {
656+ "name": "meta.method.java"
657+ },
658+ "2": {
659+ "name": "punctuation.definition.method-parameters.begin.java"
660+ }
661+ },
662+ "end": "\\)",
663+ "endCaptures": {
664+ "0": {
665+ "name": "punctuation.definition.method-parameters.end.java"
666+ }
667+ },
668+ "name": "meta.method-call.java",
669+ "patterns": [
670+ {
671+ "match": ",",
672+ "name": "punctuation.definition.seperator.parameter.java"
673+ },
674+ {
675+ "include": "#code"
676+ }
677+ ]
678+ },
679+ "methods": {
680+ "begin": "(?!new)(?=[\\w<].*\\s+)(?=([^=/]|/(?!/))+\\()",
681+ "end": "(})|(?=;)",
682+ "endCaptures": {
683+ "1": {
684+ "name": "punctuation.section.method.end.java"
685+ }
686+ },
687+ "name": "meta.method.java",
688+ "patterns": [
689+ {
690+ "include": "#storage-modifiers"
691+ },
692+ {
693+ "begin": "(\\w+)\\s*\\(",
694+ "beginCaptures": {
695+ "1": {
696+ "name": "entity.name.function.java"
697+ }
698+ },
699+ "end": "\\)",
700+ "name": "meta.method.identifier.java",
701+ "patterns": [
702+ {
703+ "include": "#parameters"
704+ },
705+ {
706+ "include": "#comments"
707+ }
708+ ]
709+ },
710+ {
711+ "begin": "<",
712+ "end": ">",
713+ "name": "storage.type.token.java",
714+ "patterns": [
715+ {
716+ "include": "#object-types"
717+ },
718+ {
719+ "begin": "<",
720+ "comment": "This is just to support <>'s with no actual type prefix",
721+ "end": ">|[^\\w\\s,\\[\\]<]",
722+ "name": "storage.type.generic.java"
723+ }
724+ ]
725+ },
726+ {
727+ "begin": "(?=\\w.*\\s+\\w+\\s*\\()",
728+ "end": "(?=\\w+\\s*\\()",
729+ "name": "meta.method.return-type.java",
730+ "patterns": [
731+ {
732+ "include": "#all-types"
733+ },
734+ {
735+ "include": "#comments"
736+ }
737+ ]
738+ },
739+ {
740+ "include": "#throws"
741+ },
742+ {
743+ "begin": "{",
744+ "beginCaptures": {
745+ "0": {
746+ "name": "punctuation.section.method.begin.java"
747+ }
748+ },
749+ "end": "(?=})",
750+ "name": "meta.method.body.java",
751+ "patterns": [
752+ {
753+ "include": "#code"
754+ }
755+ ]
756+ },
757+ {
758+ "include": "#comments"
759+ }
760+ ]
761+ },
762+ "object-types": {
763+ "patterns": [
764+ {
765+ "begin": "\\b((?:[a-z]\\w*\\.)*[A-Z]+\\w*)<",
766+ "end": ">|[^\\w\\s,\\?<\\[\\]]",
767+ "name": "storage.type.generic.java",
768+ "patterns": [
769+ {
770+ "include": "#object-types"
771+ },
772+ {
773+ "begin": "<",
774+ "comment": "This is just to support <>'s with no actual type prefix",
775+ "end": ">|[^\\w\\s,\\[\\]<]",
776+ "name": "storage.type.generic.java"
777+ }
778+ ]
779+ },
780+ {
781+ "begin": "\\b((?:[a-z]\\w*\\.)*[A-Z]+\\w*)(?=\\[)",
782+ "end": "(?=[^\\]\\s])",
783+ "name": "storage.type.object.array.java",
784+ "patterns": [
785+ {
786+ "begin": "\\[",
787+ "end": "\\]",
788+ "patterns": [
789+ {
790+ "include": "#code"
791+ }
792+ ]
793+ }
794+ ]
795+ },
796+ {
797+ "captures": {
798+ "1": {
799+ "name": "keyword.operator.dereference.java"
800+ }
801+ },
802+ "match": "\\b(?:[a-z]\\w*(\\.))*[A-Z]+\\w*\\b",
803+ "name": "storage.type.java"
804+ }
805+ ]
806+ },
807+ "object-types-inherited": {
808+ "patterns": [
809+ {
810+ "begin": "\\b((?:[a-z]\\w*\\.)*[A-Z]+\\w*)<",
811+ "end": ">|[^\\w\\s,<]",
812+ "name": "entity.other.inherited-class.java",
813+ "patterns": [
814+ {
815+ "include": "#object-types"
816+ },
817+ {
818+ "begin": "<",
819+ "comment": "This is just to support <>'s with no actual type prefix",
820+ "end": ">|[^\\w\\s,<]",
821+ "name": "storage.type.generic.java"
822+ }
823+ ]
824+ },
825+ {
826+ "captures": {
827+ "1": {
828+ "name": "keyword.operator.dereference.java"
829+ }
830+ },
831+ "match": "\\b(?:[a-z]\\w*(\\.))*[A-Z]+\\w*",
832+ "name": "entity.other.inherited-class.java"
833+ }
834+ ]
835+ },
836+ "parameters": {
837+ "patterns": [
838+ {
839+ "match": "final",
840+ "name": "storage.modifier.java"
841+ },
842+ {
843+ "include": "#annotations"
844+ },
845+ {
846+ "include": "#primitive-arrays"
847+ },
848+ {
849+ "include": "#primitive-types"
850+ },
851+ {
852+ "include": "#object-types"
853+ },
854+ {
855+ "match": "\\w+",
856+ "name": "variable.parameter.java"
857+ }
858+ ]
859+ },
860+ "parens": {
861+ "begin": "\\(",
862+ "end": "\\)",
863+ "patterns": [
864+ {
865+ "include": "#code"
866+ }
867+ ]
868+ },
869+ "primitive-arrays": {
870+ "patterns": [
871+ {
872+ "match": "\\b(?:void|boolean|byte|char|short|int|float|long|double)(\\[\\])*\\b",
873+ "name": "storage.type.primitive.array.java"
874+ }
875+ ]
876+ },
877+ "primitive-types": {
878+ "patterns": [
879+ {
880+ "match": "\\b(?:void|boolean|byte|char|short|int|float|long|double)\\b",
881+ "name": "storage.type.primitive.java"
882+ }
883+ ]
884+ },
885+ "storage-modifiers": {
886+ "captures": {
887+ "1": {
888+ "name": "storage.modifier.java"
889+ }
890+ },
891+ "match": "\\b(public|private|protected|static|final|native|synchronized|volatile|abstract|threadsafe|transient)\\b"
892+ },
893+ "strings": {
894+ "patterns": [
895+ {
896+ "begin": "\"",
897+ "beginCaptures": {
898+ "0": {
899+ "name": "punctuation.definition.string.begin.java"
900+ }
901+ },
902+ "end": "\"",
903+ "endCaptures": {
904+ "0": {
905+ "name": "punctuation.definition.string.end.java"
906+ }
907+ },
908+ "name": "string.quoted.double.java",
909+ "patterns": [
910+ {
911+ "match": "\\\\.",
912+ "name": "constant.character.escape.java"
913+ }
914+ ]
915+ },
916+ {
917+ "begin": "'",
918+ "beginCaptures": {
919+ "0": {
920+ "name": "punctuation.definition.string.begin.java"
921+ }
922+ },
923+ "end": "'",
924+ "endCaptures": {
925+ "0": {
926+ "name": "punctuation.definition.string.end.java"
927+ }
928+ },
929+ "name": "string.quoted.single.java",
930+ "patterns": [
931+ {
932+ "match": "\\\\.",
933+ "name": "constant.character.escape.java"
934+ }
935+ ]
936+ }
937+ ]
938+ },
939+ "throws": {
940+ "begin": "throws",
941+ "beginCaptures": {
942+ "0": {
943+ "name": "storage.modifier.java"
944+ }
945+ },
946+ "end": "(?={|;)",
947+ "name": "meta.throwables.java",
948+ "patterns": [
949+ {
950+ "include": "#object-types"
951+ }
952+ ]
953+ },
954+ "values": {
955+ "patterns": [
956+ {
957+ "include": "#strings"
958+ },
959+ {
960+ "include": "#object-types"
961+ },
962+ {
963+ "include": "#constants-and-special-vars"
964+ }
965+ ]
966+ },
967+ "variables": {
968+ "applyEndPatternLast": 1,
969+ "patterns": [
970+ {
971+ "begin": "(?x:(?=\n (?:\n (?:private|protected|public|native|synchronized|volatile|abstract|threadsafe|transient|static|final) # visibility/modifier\n |\n (?:def)\n |\n (?:void|boolean|byte|char|short|int|float|long|double)\n |\n (?:(?:[a-z]\\w*\\.)*[A-Z]+\\w*) # object type\n )\n \\s+\n (?!private|protected|public|native|synchronized|volatile|abstract|threadsafe|transient|static|final|def|void|boolean|byte|char|short|int|float|long|double)\n [\\w\\d_<>\\[\\],\\?][\\w\\d_<>\\[\\],\\? \\t]*\n (?:=|$)\n \n\t\t\t\t\t))",
972+ "end": "(?=;)",
973+ "name": "meta.definition.variable.java",
974+ "patterns": [
975+ {
976+ "match": "\\s"
977+ },
978+ {
979+ "captures": {
980+ "1": {
981+ "name": "constant.other.variable.java"
982+ }
983+ },
984+ "match": "([A-Z_0-9]+)\\s+(?=\\=)"
985+ },
986+ {
987+ "captures": {
988+ "1": {
989+ "name": "meta.definition.variable.name.java"
990+ }
991+ },
992+ "match": "(\\w[^\\s,]*)\\s+(?=\\=)"
993+ },
994+ {
995+ "begin": "=",
996+ "beginCaptures": {
997+ "0": {
998+ "name": "keyword.operator.assignment.java"
999+ }
1000+ },
1001+ "end": "(?=;)",
1002+ "patterns": [
1003+ {
1004+ "include": "#code"
1005+ }
1006+ ]
1007+ },
1008+ {
1009+ "captures": {
1010+ "1": {
1011+ "name": "meta.definition.variable.name.java"
1012+ }
1013+ },
1014+ "match": "(\\w[^\\s=]*)(?=\\s*;)"
1015+ },
1016+ {
1017+ "include": "#code"
1018+ }
1019+ ]
1020+ }
1021+ ]
1022+ }
1023+ },
1024+ "scopeName": "source.java",
1025+ "uuid": "2B449DF6-6B1D-11D9-94EC-000D93589AF6",
1026+ "version": "https://github.com/textmate/java.tmbundle/commit/faffa518d0b22b68b4e5e6b4c939722522b97d40"
1027+}
modified extensions/vscode/textmate-syntaxes/less.tmLanguage.json +611 −618
@@ -1,619 +1,612 @@
11 {
2- "name": "Less",
3- "scopeName": "source.css.less",
4- "fileTypes": [
5- "less",
6- "less.erb",
7- "rc",
8- "gtkrc",
9- "gtkrc-2.0",
10- "themerc"
11- ],
12- "patterns": [
13- {
14- "include": "#strings"
15- },
16- {
17- "captures": {
18- "1": {
19- "name": "entity.other.attribute-name.class.mixin.css"
20- }
21- },
22- "match": "(\\.[_a-zA-Z][a-zA-Z0-9_-]*(?=\\())"
23- },
24- {
25- "captures": {
26- "1": {
27- "name": "entity.other.attribute-name.class.css"
28- },
29- "2": {
30- "name": "punctuation.definition.entity.css"
31- },
32- "4": {
33- "name": "variable.other.interpolation.less"
34- }
35- },
36- "match": "((\\.)([_a-zA-Z]|(@{[a-zA-Z0-9_-]+}))[a-zA-Z0-9_-]*)"
37- },
38- {
39- "captures": {
40- "0": {
41- "name": "entity.other.attribute-name.parent-selector.css"
42- },
43- "1": {
44- "name": "punctuation.definition.entity.css"
45- }
46- },
47- "match": "(&)[a-zA-Z0-9_-]*"
48- },
49- {
50- "begin": "(format|local|url|attr|counter|counters)\\s*(\\()",
51- "beginCaptures": {
52- "1": {
53- "name": "support.function.misc.css"
54- },
55- "2": {
56- "name": "punctuation.section.function.css"
57- }
58- },
59- "end": "\\)",
60- "endCaptures": {
61- "0": {
62- "name": "punctuation.section.function.css"
63- }
64- },
65- "patterns": [
66- {
67- "begin": "'",
68- "beginCaptures": {
69- "0": {
70- "name": "punctuation.definition.string.begin.css"
71- }
72- },
73- "end": "'",
74- "endCaptures": {
75- "0": {
76- "name": "punctuation.definition.string.end.css"
77- }
78- },
79- "name": "string.quoted.single.css",
80- "patterns": [
81- {
82- "match": "\\\\.",
83- "name": "constant.character.escape.css"
84- }
85- ]
86- },
87- {
88- "begin": "\"",
89- "beginCaptures": {
90- "0": {
91- "name": "punctuation.definition.string.begin.css"
92- }
93- },
94- "end": "\"",
95- "endCaptures": {
96- "0": {
97- "name": "punctuation.definition.string.end.css"
98- }
99- },
100- "name": "string.quoted.double.css",
101- "patterns": [
102- {
103- "match": "\\\\(\\d{1,6}|.)",
104- "name": "constant.character.escape.css"
105- }
106- ]
107- },
108- {
109- "match": "[^'\") \\t]+",
110- "name": "variable.parameter.misc.css"
111- }
112- ]
113- },
114- {
115- "match": "(#)([0-9a-fA-F]{3}|[0-9a-fA-F]{6})\\b(?!.*?(?<!@){)",
116- "name": "constant.other.rgb-value.css"
117- },
118- {
119- "captures": {
120- "1": {
121- "name": "entity.other.attribute-name.id"
122- },
123- "2": {
124- "name": "punctuation.definition.entity.css"
125- },
126- "4": {
127- "name": "variable.other.interpolation.less"
128- }
129- },
130- "match": "((#)([_a-zA-Z]|(@{[a-zA-Z0-9_-]+}))[a-zA-Z0-9_-]*)",
131- "name": "meta.selector.css"
132- },
133- {
134- "begin": "/\\*",
135- "beginCaptures": {
136- "0": {
137- "name": "punctuation.definition.comment.begin.css"
138- }
139- },
140- "end": "\\*/",
141- "endCaptures": {
142- "0": {
143- "name": "punctuation.definition.comment.end.css"
144- }
145- },
146- "name": "comment.block.css"
147- },
148- {
149- "match": "[+-]?\\d*\\.?\\d+",
150- "name": "constant.numeric.css"
151- },
152- {
153- "match": "(?<=[\\d])(ch|cm|deg|dpi|dpcm|dppx|em|ex|grad|in|mm|ms|pc|pt|px|rad|rem|turn|s|vh|vmin|vw)\\b|%",
154- "name": "keyword.other.unit.css"
155- },
156- {
157- "captures": {
158- "1": {
159- "name": "punctuation.definition.begin.entity.css"
160- },
161- "2": {
162- "name": "entity.other.attribute-name.attribute.css"
163- },
164- "3": {
165- "name": "punctuation.separator.operator.css"
166- },
167- "4": {
168- "name": "string.unquoted.attribute-value.css"
169- },
170- "5": {
171- "name": "string.quoted.double.attribute-value.css"
172- },
173- "6": {
174- "name": "punctuation.definition.string.begin.css"
175- },
176- "7": {
177- "name": "punctuation.definition.string.end.css"
178- },
179- "8": {
180- "name": "punctuation.definition.end.entity.css"
181- }
182- },
183- "match": "(?i)(\\[)\\s*(-?[_a-z\\\\[[:^ascii:]]][_a-z0-9\\-\\\\[[:^ascii:]]]*)(?:\\s*([~|^$*]?=)\\s*(?:(-?[_a-z\\\\[[:^ascii:]]][_a-z0-9\\-\\\\[[:^ascii:]]]*)|((?>(['\"])(?:[^\\\\]|\\\\.)*?(\\6)))))?\\s*(\\])",
184- "name": "meta.attribute-selector.css"
185- },
186- {
187- "begin": "((@)import\\b)",
188- "beginCaptures": {
189- "1": {
190- "name": "keyword.control.at-rule.import.less"
191- },
192- "2": {
193- "name": "punctuation.definition.keyword.less"
194- }
195- },
196- "end": ";",
197- "endCaptures": {
198- "0": {
199- "name": "punctuation.terminator.rule.css"
200- }
201- },
202- "name": "meta.at-rule.import.css",
203- "patterns": [
204- {
205- "match": "(?<=\\(|,|\\s)\\b(reference|optional|once|multiple|less|inline)\\b(?=\\)|,)",
206- "name": "keyword.control.import.option.less"
207- },
208- {
209- "include": "#brace_round"
210- },
211- {
212- "include": "#commas"
213- },
214- {
215- "include": "#strings"
216- }
217- ]
218- },
219- {
220- "captures": {
221- "1": {
222- "name": "keyword.control.at-rule.fontface.css"
223- },
224- "2": {
225- "name": "punctuation.definition.keyword.css"
226- }
227- },
228- "match": "^\\s*((@)font-face\\b)",
229- "name": "meta.at-rule.fontface.css"
230- },
231- {
232- "captures": {
233- "1": {
234- "name": "keyword.control.at-rule.media.css"
235- },
236- "2": {
237- "name": "punctuation.definition.keyword.css"
238- }
239- },
240- "match": "^\\s*((@)media\\b)",
241- "name": "meta.at-rule.media.css"
242- },
243- {
244- "match": "\\b(width|scan|resolution|orientation|monochrome|min-width|min-resolution|min-monochrome|min-height|min-device-width|min-device-height|min-device-aspect-ratio|min-color-index|min-color|min-aspect-ratio|max-width|max-resolution|max-monochrome|max-height|max-device-width|max-device-height|max-device-aspect-ratio|max-color-index|max-color|max-aspect-ratio|height|grid|device-width|device-height|device-aspect-ratio|color-index|color|aspect-ratio)\\b",
245- "name": "support.type.property-name.media-feature.media.css"
246- },
247- {
248- "match": "\\b(tv|tty|screen|projection|print|handheld|embossed|braille|aural|all)\\b",
249- "name": "support.constant.media-type.media.css"
250- },
251- {
252- "match": "\\b(portrait|landscape)\\b",
253- "name": "support.constant.property-value.media-property.media.css"
254- },
255- {
256- "captures": {
257- "1": {
258- "name": "support.function.less"
259- }
260- },
261- "match": "(\\.[a-zA-Z0-9_-]+)\\s*(;|\\()"
262- },
263- {
264- "begin": "(^[ \\t]+)?(?=//)",
265- "beginCaptures": {
266- "1": {
267- "name": "punctuation.whitespace.comment.leading.less"
268- }
269- },
270- "end": "(?!\\G)",
271- "patterns": [
272- {
273- "begin": "//",
274- "beginCaptures": {
275- "0": {
276- "name": "punctuation.definition.comment.less"
277- }
278- },
279- "end": "\\n",
280- "name": "comment.line.double-slash.less"
281- }
282- ]
283- },
284- {
285- "captures": {
286- "1": {
287- "name": "punctuation.definition.variable.less"
288- }
289- },
290- "match": "(?:@|\\-\\-)[a-zA-Z0-9_-][\\w-]*(?=\\s*)",
291- "name": "variable.other.less"
292- },
293- {
294- "include": "#variable_interpolation"
295- },
296- {
297- "begin": "{",
298- "beginCaptures": {
299- "0": {
300- "name": "punctuation.section.property-list.begin.css"
301- }
302- },
303- "end": "}",
304- "endCaptures": {
305- "0": {
306- "name": "punctuation.section.property-list.end.css"
307- }
308- },
309- "name": "meta.property-list.css",
310- "patterns": [
311- {
312- "include": "#pseudo_elements"
313- },
314- {
315- "include": "#pseudo_classes"
316- },
317- {
318- "include": "#variable_interpolation"
319- },
320- {
321- "include": "#property_names"
322- },
323- {
324- "include": "#property_names_svg"
325- },
326- {
327- "include": "#property_values"
328- },
329- {
330- "include": "$self"
331- }
332- ]
333- },
334- {
335- "match": "\\!\\s*important",
336- "name": "keyword.other.important.css"
337- },
338- {
339- "match": "\\*|\\/|\\-|\\+|~|=|<=|>=|<|>",
340- "name": "keyword.operator.less"
341- },
342- {
343- "match": "\\b(not|and|when)\\b",
344- "name": "keyword.control.logical.operator.less"
345- },
346- {
347- "match": "(?x)\n(?<![\\w-])\n(a|abbr|address|area|article|aside|audio\n|b|base|bdi|bdo|blockquote|body|br|button\n|canvas|caption|cite|code|col|colgroup\n|data|datalist|dd|del|details|dfn|dialog|div|dl|dt\n|em|embed|fieldset|figure|figcaption|footer|form\n|h[1-6]|head|header|hgroup|hr|html|i|iframe|img|input|ins\n|kbd|keygen|label|legend|li|link|main|map|mark|math|menu|menuitem|meta|meter\n|nav|noscript|object|ol|optgroup|option|output\n|p|param|picture|pre|progress|q|rb|rp|rt|rtc|ruby\n|s|samp|script|section|select|small|source|span|strong|style|sub|summary|sup|svg\n|table|tbody|td|template|textarea|tfoot|th|thead|time|title|tr|track\n|u|ul|var|video|wbr)\n(?![\\w-])",
348- "name": "entity.name.tag.css"
349- },
350- {
351- "match": "(?x)\n(?<![\\w-])\n(vkern|view|use|tspan|tref|textPath|text|symbol|switch|stop|set\n|rect|radialGradient|polyline|polygon|pattern|path\n|mpath|missing-glyph|metadata|mask|marker|linearGradient|line\n|image|hkern|glyphRef|glyph|g\n|foreignObject|font(-face(-uri|-src|-name|-format)?)?|filter\n|fe(Turbulence|Tile|SpotLight|SpecularLighting|PointLight|Offset\n |Morphology|MergeNode|Merge|Image|GaussianBlur|Func[RGBA]\n |Flood|DistantLight|DisplacementMap|DiffuseLighting\n |ConvolveMatrix|Composite|ComponentTransfer|ColorMatrix|Blend)\n|ellipse|desc|defs|cursor|color-profile|clipPath|circle\n|animate(Transform|Motion|Color)?|altGlyph(Item|Def)?)\n(?![\\w-])",
352- "name": "entity.name.tag.svg.css"
353- },
354- {
355- "match": "(?<![\\w-])[a-z][\\w&&[^A-Z]]*+-[\\w-&&[^A-Z]]+",
356- "name": "entity.name.tag.custom.css"
357- },
358- {
359- "include": "#pseudo_elements"
360- },
361- {
362- "include": "#pseudo_classes"
363- },
364- {
365- "captures": {
366- "1": {
367- "name": "punctuation.section.property-list.begin.css"
368- },
369- "2": {
370- "name": "punctuation.section.property-list.end.css"
371- }
372- },
373- "comment": "Match empty braces to give proper ↩ action",
374- "match": "(\\{)(\\})",
375- "name": "meta.brace.curly.css"
376- },
377- {
378- "match": "\\{|\\}",
379- "name": "meta.brace.curly.css"
380- },
381- {
382- "include": "#brace_round"
383- },
384- {
385- "match": "\\[|\\]",
386- "name": "meta.brace.square.less"
387- },
388- {
389- "match": ";",
390- "name": "punctuation.terminator.rule.css"
391- },
392- {
393- "match": ":",
394- "name": "punctuation.separator.key-value.css"
395- },
396- {
397- "match": "\\btrue\\b",
398- "name": "constant.language.boolean.less"
399- },
400- {
401- "match": "\\bdefault\\b",
402- "name": "support.function.default.less"
403- },
404- {
405- "match": "\\b(isurl|isstring|isnumber|iskeyword|iscolor)\\b",
406- "name": "support.function.type-checking.less"
407- },
408- {
409- "match": "\\b(isunit|ispixel|ispercentage|isem)\\b",
410- "name": "support.function.unit-checking.less"
411- },
412- {
413- "include": "#font_names"
414- },
415- {
416- "include": "#commas"
417- },
418- {
419- "include": "#color_names"
420- },
421- {
422- "include": "#less_builtin_functions"
423- },
424- {
425- "include": "#css_builtin_functions"
426- },
427- {
428- "include": "#gradient_builtin_functions"
429- }
430- ],
431- "repository": {
432- "variable_interpolation": {
433- "match": "@{[a-zA-Z0-9_-]+}",
434- "name": "variable.other.interpolation.less"
435- },
436- "strings": {
437- "patterns": [
438- {
439- "begin": "\"",
440- "beginCaptures": {
441- "0": {
442- "name": "punctuation.definition.string.begin.css"
443- }
444- },
445- "end": "\"",
446- "endCaptures": {
447- "0": {
448- "name": "punctuation.definition.string.end.css"
449- }
450- },
451- "name": "string.quoted.double.css",
452- "patterns": [
453- {
454- "match": "\\\\(\\h{1,6}|.)",
455- "name": "constant.character.escape.css"
456- },
457- {
458- "include": "#variable_interpolation"
459- }
460- ]
461- },
462- {
463- "begin": "'",
464- "beginCaptures": {
465- "0": {
466- "name": "punctuation.definition.string.begin.css"
467- }
468- },
469- "end": "'",
470- "endCaptures": {
471- "0": {
472- "name": "punctuation.definition.string.end.css"
473- }
474- },
475- "name": "string.quoted.single.css",
476- "patterns": [
477- {
478- "match": "\\\\(\\h{1,6}|.)",
479- "name": "constant.character.escape.css"
480- },
481- {
482- "include": "#variable_interpolation"
483- }
484- ]
485- }
486- ]
487- },
488- "commas": {
489- "match": ",",
490- "name": "punctuation.separator.list.css"
491- },
492- "brace_round": {
493- "match": "\\(|\\)",
494- "name": "meta.brace.round.css"
495- },
496- "property_names": {
497- "captures": {
498- "1": {
499- "name": "support.type.property-name.css"
500- }
501- },
502- "match": "(?<![-a-z])(-webkit-[-A-Za-z]+|-moz-[-A-Za-z]+|-o-[-A-Za-z]+|-ms-[-A-Za-z]+|-khtml-[-A-Za-z]+|zoom|z-index|y|x|wrap|word-wrap|word-spacing|word-break|word|width|widows|white-space-collapse|white-space|white|weight|volume|voice-volume|voice-stress|voice-rate|voice-pitch-range|voice-pitch|voice-family|voice-duration|voice-balance|voice|visibility|vertical-align|variant|user-select|up|unicode-bidi|unicode-range|unicode|trim|transition-timing-function|transition-property|transition-duration|transition-delay|transition|transform|touch-action|top-width|top-style|top-right-radius|top-left-radius|top-color|top|timing-function|text-wrap|text-transform|text-shadow|text-replace|text-rendering|text-overflow|text-outline|text-justify|text-indent|text-height|text-emphasis|text-decoration|text-align-last|text-align|text|target-position|target-new|target-name|target|table-layout|tab-size|style-type|style-position|style-image|style|string-set|stretch|stress|stacking-strategy|stacking-shift|stacking-ruby|stacking|src|speed|speech-rate|speech|speak-punctuation|speak-numeral|speak-header|speak|span|spacing|space-collapse|space|sizing|size-adjust|size|shadow|respond-to|rule-width|rule-style|rule-color|rule|ruby-span|ruby-position|ruby-overhang|ruby-align|ruby|rows|rotation-point|rotation|role|right-width|right-style|right-color|right|richness|rest-before|rest-after|rest|resource|resize|reset|replace|repeat|rendering-intent|rate|radius|quotes|punctuation-trim|punctuation|property|profile|presentation-level|presentation|position|pointer-events|point|play-state|play-during|play-count|pitch-range|pitch|phonemes|pause-before|pause-after|pause|page-policy|page-break-inside|page-break-before|page-break-after|page|padding-top|padding-right|padding-left|padding-bottom|padding|pack|overhang|overflow-y|overflow-x|overflow-style|overflow|outline-width|outline-style|outline-offset|outline-color|outline|orphans|origin|orientation|orient|ordinal-group|order|opacity|offset|numeral|new|nav-up|nav-right|nav-left|nav-index|nav-down|nav|name|move-to|model|mix-blend-mode|min-width|min-height|min|max-width|max-height|max|marquee-style|marquee-speed|marquee-play-count|marquee-direction|marquee|marks|mark-before|mark-after|mark|margin-top|margin-right|margin-left|margin-bottom|margin|mask-image|list-style-type|list-style-position|list-style-image|list-style|list|lines|line-stacking-strategy|line-stacking-shift|line-stacking-ruby|line-stacking|line-height|line-break|level|letter-spacing|length|left-width|left-style|left-color|left|label|justify-content|justify|iteration-count|inline-box-align|initial-value|initial-size|initial-before-align|initial-before-adjust|initial-after-align|initial-after-adjust|index|indent|increment|image-resolution|image-orientation|image|icon|hyphens|hyphenate-resource|hyphenate-lines|hyphenate-character|hyphenate-before|hyphenate-after|hyphenate|height|header|hanging-punctuation|grid-rows|grid-columns|grid|gap|font-kerning|font-language-override|font-weight|font-variant-caps|font-variant|font-style|font-synthesis|font-stretch|font-size-adjust|font-size|font-family|font|float-offset|float|flex-wrap|flex-shrink|flex-grow|flex-group|flex-flow|flex-direction|flex-basis|flex|fit-position|fit|fill|filter|family|empty-cells|emphasis|elevation|duration|drop-initial-value|drop-initial-size|drop-initial-before-align|drop-initial-before-adjust|drop-initial-after-align|drop-initial-after-adjust|drop|down|dominant-baseline|display-role|display-model|display|direction|delay|decoration-break|decoration|cursor|cue-before|cue-after|cue|crop|counter-reset|counter-increment|counter|count|content|columns|column-width|column-span|column-rule-width|column-rule-style|column-rule-color|column-rule|column-gap|column-fill|column-count|column-break-before|column-break-after|column|color-profile|color|collapse|clip|clear|character|caption-side|break-inside|break-before|break-after|break|box-sizing|box-shadow|box-pack|box-orient|box-ordinal-group|box-lines|box-flex-group|box-flex|box-direction|box-decoration-break|box-align|box|bottom-width|bottom-style|bottom-right-radius|bottom-left-radius|bottom-color|bottom|border-width|border-top-width|border-top-style|border-top-right-radius|border-top-left-radius|border-top-color|border-top|border-style|border-spacing|border-right-width|border-right-style|border-right-color|border-right|border-radius|border-length|border-left-width|border-left-style|border-left-color|border-left|border-image|border-color|border-collapse|border-bottom-width|border-bottom-style|border-bottom-right-radius|border-bottom-left-radius|border-bottom-color|border-bottom|border|bookmark-target|bookmark-level|bookmark-label|bookmark|binding|bidi|before|baseline-shift|baseline|balance|background-blend-mode|background-size|background-repeat|background-position|background-origin|background-image|background-color|background-clip|background-break|background-attachment|background|azimuth|attachment|appearance|animation-timing-function|animation-play-state|animation-name|animation-iteration-count|animation-duration|animation-direction|animation-delay|animation-fill-mode|animation|alignment-baseline|alignment-adjust|alignment|align-self|align-last|align-items|align-content|align|after|adjust|will-change)(?=\\s*:?(.*\\()|(?!.*(?<!@){))\\b"
503- },
504- "property_names_svg": {
505- "captures": {
506- "1": {
507- "name": "support.type.property-name.svg.css"
508- }
509- },
510- "match": "(?<![-a-z])(writing-mode|text-anchor|stroke-width|stroke-opacity|stroke-miterlimit|stroke-linejoin|stroke-linecap|stroke-dashoffset|stroke-dasharray|stroke|stop-opacity|stop-color|shape-rendering|marker-start|marker-mid|marker-end|lighting-color|kerning|image-rendering|glyph-orientation-vertical|glyph-orientation-horizontal|flood-opacity|flood-color|fill-rule|fill-opacity|fill|enable-background|color-rendering|color-interpolation-filters|color-interpolation|clip-rule|clip-path)(?=\\s*:)"
511- },
512- "property_values": {
513- "begin": "(?<!&)(:)\\s*(?!(\\s*{))(?!.*(?<!@){)",
514- "beginCaptures": {
515- "1": {
516- "name": "punctuation.separator.key-value.css"
517- }
518- },
519- "end": "\\s*(;)|\\s*(?=})",
520- "endCaptures": {
521- "1": {
522- "name": "punctuation.terminator.rule.css"
523- }
524- },
525- "contentName": "meta.property-value.css",
526- "patterns": [
527- {
528- "match": "\\b(wrap-reverse|wrap|whitespace|wait|w-resize|visible|vertical-text|vertical-ideographic|uppercase|upper-roman|upper-alpha|unicase|underline|ultra-expanded|ultra-condensed|transparent|transform|top|titling-caps|thin|thick|text-top|text-bottom|text|tb-rl|table-row-group|table-row|table-header-group|table-footer-group|table-column-group|table-column|table-cell|table|sw-resize|super|strict|stretch|step-start|step-end|static|square|space-between|space-around|space|solid|soft-light|small-caps|separate|semi-expanded|semi-condensed|se-resize|scroll|screen|saturation|s-resize|running|rtl|row-reverse|row-resize|row|round|right|ridge|reverse|repeat-y|repeat-x|repeat|relative|progressive|progress|pre-wrap|pre-line|pre|pointer|petite-caps|paused|pan-x|pan-left|pan-right|pan-y|pan-up|pan-down|padding-box|overline|overlay|outside|outset|optimizeSpeed|optimizeLegibility|opacity|oblique|nw-resize|nowrap|not-allowed|normal|none|no-repeat|no-drop|newspaper|ne-resize|n-resize|multiply|move|middle|medium|max-height|manipulation|main-size|luminosity|ltr|lr-tb|lowercase|lower-roman|lower-alpha|loose|local|list-item|linear(?!-)|line-through|line-edge|line|lighter|lighten|left|keep-all|justify|italic|inter-word|inter-ideograph|inside|inset|inline-block|inline|inherit|infinite|inactive|ideograph-space|ideograph-parenthesis|ideograph-numeric|ideograph-alpha|hue|horizontal|hidden|help|hard-light|hand|groove|geometricPrecision|forwards|flex-start|flex-end|flex|fixed|extra-expanded|extra-condensed|expanded|exclusion|ellipsis|ease-out|ease-in-out|ease-in|ease|e-resize|double|dotted|distribute-space|distribute-letter|distribute-all-lines|distribute|disc|disabled|difference|default|decimal|dashed|darken|currentColor|crosshair|cover|content-box|contain|condensed|column-reverse|column|color-dodge|color-burn|color|collapse|col-resize|circle|char|center|capitalize|break-word|break-all|bottom|both|border-box|bolder|bold|block|bidi-override|below|baseline|balance|backwards|auto|antialiased|always|alternate-reverse|alternate|all-small-caps|all-scroll|all-petite-caps|all|absolute)\\b",
529- "name": "support.constant.property-value.css"
530- },
531- {
532- "match": "\\b(start|sRGB|square|round|optimizeSpeed|optimizeQuality|nonzero|miter|middle|linearRGB|geometricPrecision |evenodd |end |crispEdges|butt|bevel)\\b",
533- "name": "support.constant.property-value.svg.css"
534- },
535- {
536- "begin": "url(\\()",
537- "beginCaptures": {
538- "1": {
539- "name": "meta.brace.round.css"
540- }
541- },
542- "end": "\\)",
543- "endCaptures": {
544- "0": {
545- "name": "meta.brace.round.css"
546- }
547- },
548- "name": "support.function.any-method.builtin.url.css",
549- "patterns": [
550- {
551- "include": "#strings"
552- },
553- {
554- "match": "(\\b|\\.{0,2}/).*\\b",
555- "name": "string.url.css"
556- }
557- ]
558- },
559- {
560- "include": "#font_names"
561- },
562- {
563- "include": "#color_names"
564- },
565- {
566- "include": "#less_builtin_functions"
567- },
568- {
569- "include": "#css_builtin_functions"
570- },
571- {
572- "include": "#gradient_builtin_functions"
573- },
574- {
575- "include": "$self"
576- }
577- ]
578- },
579- "pseudo_elements": {
580- "captures": {
581- "1": {
582- "name": "punctuation.definition.entity.css"
583- }
584- },
585- "match": "(:|::)(after|before|first-letter|first-line|selection|shadow)",
586- "name": "entity.other.attribute-name.pseudo-element.css"
587- },
588- "pseudo_classes": {
589- "captures": {
590- "1": {
591- "name": "punctuation.definition.entity.css"
592- }
593- },
594- "match": "(:)(active|checked|default|dir|disabled|empty|enabled|extend|first-child|first-of-type|first|fullscreen|focus|hover|indeterminate|in-range|invalid|lang|last-child|last-of-type|left|link|not|nth-child|nth-last-child|nth-last-of-type|nth-of-type|only-child|only-of-type|optional|out-of-range|read-only|read-write|required|right|root|scope|shadow|target|valid|visited)(?!\\s*;)",
595- "name": "entity.other.attribute-name.pseudo-class.css"
596- },
597- "font_names": {
598- "match": "(\\b(?i:arial|century|comic|courier|cursive|fantasy|futura|garamond|georgia|helvetica|impact|lucida|monospace|symbol|system|tahoma|times|trebuchet|utopia|verdana|webdings|sans-serif|serif)\\b)",
599- "name": "support.constant.font-name.css"
600- },
601- "color_names": {
602- "match": "\\b(yellowgreen|yellow|whitesmoke|white|wheat|violet|turquoise|tomato|thistle|teal|tan|steelblue|springgreen|snow|slategrey|slategray|slateblue|skyblue|silver|sienna|seashell|seagreen|sandybrown|salmon|saddlebrown|royalblue|rosybrown|red|rebeccapurple|purple|powderblue|plum|pink|peru|peachpuff|papayawhip|palevioletred|paleturquoise|palegreen|palegoldenrod|orchid|orangered|orange|olivedrab|olive|oldlace|navy|navajowhite|moccasin|mistyrose|mintcream|midnightblue|mediumvioletred|mediumturquoise|mediumspringgreen|mediumslateblue|mediumseagreen|mediumpurple|mediumorchid|mediumblue|mediumaquamarine|maroon|linen|limegreen|lime|lightyellow|lightsteelblue|lightslategrey|lightslategray|lightskyblue|lightseagreen|lightsalmon|lightpink|lightgrey|lightgreen|lightgray|lightgoldenrodyellow|lightcyan|lightcoral|lightblue|lemonchiffon|lawngreen|lavenderblush|lavender|khaki|ivory|indigo|indianred|hotpink|honeydew|grey|greenyellow|green|gray|goldenrod|gold|ghostwhite|gainsboro|fuchsia|forestgreen|floralwhite|firebrick|dodgerblue|dimgrey|dimgray|deepskyblue|deeppink|darkviolet|darkturquoise|darkslategrey|darkslategray|darkslateblue|darkseagreen|darksalmon|darkred|darkorchid|darkorange|darkolivegreen|darkmagenta|darkkhaki|darkgrey|darkgreen|darkgray|darkgoldenrod|darkcyan|darkblue|crimson|cornsilk|cornflowerblue|coral|chocolate|chartreuse|cadetblue|burlywood|brown|blueviolet|blue|blanchedalmond|black|bisque|beige|azure|aquamarine|aqua|antiquewhite|aliceblue)\\b",
603- "name": "support.constant.color.w3c-standard-color-name.css"
604- },
605- "less_builtin_functions": {
606- "match": "\\b(abs|acos|alpha|argb|asin|atan|average|blue|calc|ceil|color|contrast|convert|convert|cos|darken|data-uri|desaturate|difference|e|escape|exclusion|extract|fade|fadein|fadeout|floor|format|green|greyscale|hardlight|hsl|hsla|hsv|hsva|hsvhue|hsvsaturation|hsvvalue|hue|length|lighten|lightness|luma|max|min|mix|mod|multiply|negation|overlay|percentage|pi|pow|red|replace|round|saturate|saturation|screen|sin|softlight|spin|sqrt|tan|unit)\\b",
607- "name": "support.function.any-method.builtin.less"
608- },
609- "css_builtin_functions": {
610- "match": "\\b(url|translate3d|translate[XYZ]|translate|skew[XY]|skew|scale[XYZ]|scale|rotate3d|rotate[XYZ]|rotate|rgba|rgb|repeating-radial-gradient|repeating-linear-gradient|rect|radial-gradient|matrix3d|matrix|linear-gradient|hsla|hsl|drop-shadow|cubic-bezier|blur)\\b",
611- "name": "support.function.any-method.builtin.css"
612- },
613- "gradient_builtin_functions": {
614- "match": "\\b(color-stop|from|to)\\b",
615- "name": "support.function.any-method.gradient.css"
616- }
617- },
618- "version": "https://github.com/atom/language-less/commit/c5876823ed8ae556c82f76c05de815a72a9df6a4"
619-}
No newline at the end of the file
2+ "name": "Less",
3+ "scopeName": "source.css.less",
4+ "fileTypes": ["less", "less.erb", "rc", "gtkrc", "gtkrc-2.0", "themerc"],
5+ "patterns": [
6+ {
7+ "include": "#strings"
8+ },
9+ {
10+ "captures": {
11+ "1": {
12+ "name": "entity.other.attribute-name.class.mixin.css"
13+ }
14+ },
15+ "match": "(\\.[_a-zA-Z][a-zA-Z0-9_-]*(?=\\())"
16+ },
17+ {
18+ "captures": {
19+ "1": {
20+ "name": "entity.other.attribute-name.class.css"
21+ },
22+ "2": {
23+ "name": "punctuation.definition.entity.css"
24+ },
25+ "4": {
26+ "name": "variable.other.interpolation.less"
27+ }
28+ },
29+ "match": "((\\.)([_a-zA-Z]|(@{[a-zA-Z0-9_-]+}))[a-zA-Z0-9_-]*)"
30+ },
31+ {
32+ "captures": {
33+ "0": {
34+ "name": "entity.other.attribute-name.parent-selector.css"
35+ },
36+ "1": {
37+ "name": "punctuation.definition.entity.css"
38+ }
39+ },
40+ "match": "(&)[a-zA-Z0-9_-]*"
41+ },
42+ {
43+ "begin": "(format|local|url|attr|counter|counters)\\s*(\\()",
44+ "beginCaptures": {
45+ "1": {
46+ "name": "support.function.misc.css"
47+ },
48+ "2": {
49+ "name": "punctuation.section.function.css"
50+ }
51+ },
52+ "end": "\\)",
53+ "endCaptures": {
54+ "0": {
55+ "name": "punctuation.section.function.css"
56+ }
57+ },
58+ "patterns": [
59+ {
60+ "begin": "'",
61+ "beginCaptures": {
62+ "0": {
63+ "name": "punctuation.definition.string.begin.css"
64+ }
65+ },
66+ "end": "'",
67+ "endCaptures": {
68+ "0": {
69+ "name": "punctuation.definition.string.end.css"
70+ }
71+ },
72+ "name": "string.quoted.single.css",
73+ "patterns": [
74+ {
75+ "match": "\\\\.",
76+ "name": "constant.character.escape.css"
77+ }
78+ ]
79+ },
80+ {
81+ "begin": "\"",
82+ "beginCaptures": {
83+ "0": {
84+ "name": "punctuation.definition.string.begin.css"
85+ }
86+ },
87+ "end": "\"",
88+ "endCaptures": {
89+ "0": {
90+ "name": "punctuation.definition.string.end.css"
91+ }
92+ },
93+ "name": "string.quoted.double.css",
94+ "patterns": [
95+ {
96+ "match": "\\\\(\\d{1,6}|.)",
97+ "name": "constant.character.escape.css"
98+ }
99+ ]
100+ },
101+ {
102+ "match": "[^'\") \\t]+",
103+ "name": "variable.parameter.misc.css"
104+ }
105+ ]
106+ },
107+ {
108+ "match": "(#)([0-9a-fA-F]{3}|[0-9a-fA-F]{6})\\b(?!.*?(?<!@){)",
109+ "name": "constant.other.rgb-value.css"
110+ },
111+ {
112+ "captures": {
113+ "1": {
114+ "name": "entity.other.attribute-name.id"
115+ },
116+ "2": {
117+ "name": "punctuation.definition.entity.css"
118+ },
119+ "4": {
120+ "name": "variable.other.interpolation.less"
121+ }
122+ },
123+ "match": "((#)([_a-zA-Z]|(@{[a-zA-Z0-9_-]+}))[a-zA-Z0-9_-]*)",
124+ "name": "meta.selector.css"
125+ },
126+ {
127+ "begin": "/\\*",
128+ "beginCaptures": {
129+ "0": {
130+ "name": "punctuation.definition.comment.begin.css"
131+ }
132+ },
133+ "end": "\\*/",
134+ "endCaptures": {
135+ "0": {
136+ "name": "punctuation.definition.comment.end.css"
137+ }
138+ },
139+ "name": "comment.block.css"
140+ },
141+ {
142+ "match": "[+-]?\\d*\\.?\\d+",
143+ "name": "constant.numeric.css"
144+ },
145+ {
146+ "match": "(?<=[\\d])(ch|cm|deg|dpi|dpcm|dppx|em|ex|grad|in|mm|ms|pc|pt|px|rad|rem|turn|s|vh|vmin|vw)\\b|%",
147+ "name": "keyword.other.unit.css"
148+ },
149+ {
150+ "captures": {
151+ "1": {
152+ "name": "punctuation.definition.begin.entity.css"
153+ },
154+ "2": {
155+ "name": "entity.other.attribute-name.attribute.css"
156+ },
157+ "3": {
158+ "name": "punctuation.separator.operator.css"
159+ },
160+ "4": {
161+ "name": "string.unquoted.attribute-value.css"
162+ },
163+ "5": {
164+ "name": "string.quoted.double.attribute-value.css"
165+ },
166+ "6": {
167+ "name": "punctuation.definition.string.begin.css"
168+ },
169+ "7": {
170+ "name": "punctuation.definition.string.end.css"
171+ },
172+ "8": {
173+ "name": "punctuation.definition.end.entity.css"
174+ }
175+ },
176+ "match": "(?i)(\\[)\\s*(-?[_a-z\\\\[[:^ascii:]]][_a-z0-9\\-\\\\[[:^ascii:]]]*)(?:\\s*([~|^$*]?=)\\s*(?:(-?[_a-z\\\\[[:^ascii:]]][_a-z0-9\\-\\\\[[:^ascii:]]]*)|((?>(['\"])(?:[^\\\\]|\\\\.)*?(\\6)))))?\\s*(\\])",
177+ "name": "meta.attribute-selector.css"
178+ },
179+ {
180+ "begin": "((@)import\\b)",
181+ "beginCaptures": {
182+ "1": {
183+ "name": "keyword.control.at-rule.import.less"
184+ },
185+ "2": {
186+ "name": "punctuation.definition.keyword.less"
187+ }
188+ },
189+ "end": ";",
190+ "endCaptures": {
191+ "0": {
192+ "name": "punctuation.terminator.rule.css"
193+ }
194+ },
195+ "name": "meta.at-rule.import.css",
196+ "patterns": [
197+ {
198+ "match": "(?<=\\(|,|\\s)\\b(reference|optional|once|multiple|less|inline)\\b(?=\\)|,)",
199+ "name": "keyword.control.import.option.less"
200+ },
201+ {
202+ "include": "#brace_round"
203+ },
204+ {
205+ "include": "#commas"
206+ },
207+ {
208+ "include": "#strings"
209+ }
210+ ]
211+ },
212+ {
213+ "captures": {
214+ "1": {
215+ "name": "keyword.control.at-rule.fontface.css"
216+ },
217+ "2": {
218+ "name": "punctuation.definition.keyword.css"
219+ }
220+ },
221+ "match": "^\\s*((@)font-face\\b)",
222+ "name": "meta.at-rule.fontface.css"
223+ },
224+ {
225+ "captures": {
226+ "1": {
227+ "name": "keyword.control.at-rule.media.css"
228+ },
229+ "2": {
230+ "name": "punctuation.definition.keyword.css"
231+ }
232+ },
233+ "match": "^\\s*((@)media\\b)",
234+ "name": "meta.at-rule.media.css"
235+ },
236+ {
237+ "match": "\\b(width|scan|resolution|orientation|monochrome|min-width|min-resolution|min-monochrome|min-height|min-device-width|min-device-height|min-device-aspect-ratio|min-color-index|min-color|min-aspect-ratio|max-width|max-resolution|max-monochrome|max-height|max-device-width|max-device-height|max-device-aspect-ratio|max-color-index|max-color|max-aspect-ratio|height|grid|device-width|device-height|device-aspect-ratio|color-index|color|aspect-ratio)\\b",
238+ "name": "support.type.property-name.media-feature.media.css"
239+ },
240+ {
241+ "match": "\\b(tv|tty|screen|projection|print|handheld|embossed|braille|aural|all)\\b",
242+ "name": "support.constant.media-type.media.css"
243+ },
244+ {
245+ "match": "\\b(portrait|landscape)\\b",
246+ "name": "support.constant.property-value.media-property.media.css"
247+ },
248+ {
249+ "captures": {
250+ "1": {
251+ "name": "support.function.less"
252+ }
253+ },
254+ "match": "(\\.[a-zA-Z0-9_-]+)\\s*(;|\\()"
255+ },
256+ {
257+ "begin": "(^[ \\t]+)?(?=//)",
258+ "beginCaptures": {
259+ "1": {
260+ "name": "punctuation.whitespace.comment.leading.less"
261+ }
262+ },
263+ "end": "(?!\\G)",
264+ "patterns": [
265+ {
266+ "begin": "//",
267+ "beginCaptures": {
268+ "0": {
269+ "name": "punctuation.definition.comment.less"
270+ }
271+ },
272+ "end": "\\n",
273+ "name": "comment.line.double-slash.less"
274+ }
275+ ]
276+ },
277+ {
278+ "captures": {
279+ "1": {
280+ "name": "punctuation.definition.variable.less"
281+ }
282+ },
283+ "match": "(?:@|\\-\\-)[a-zA-Z0-9_-][\\w-]*(?=\\s*)",
284+ "name": "variable.other.less"
285+ },
286+ {
287+ "include": "#variable_interpolation"
288+ },
289+ {
290+ "begin": "{",
291+ "beginCaptures": {
292+ "0": {
293+ "name": "punctuation.section.property-list.begin.css"
294+ }
295+ },
296+ "end": "}",
297+ "endCaptures": {
298+ "0": {
299+ "name": "punctuation.section.property-list.end.css"
300+ }
301+ },
302+ "name": "meta.property-list.css",
303+ "patterns": [
304+ {
305+ "include": "#pseudo_elements"
306+ },
307+ {
308+ "include": "#pseudo_classes"
309+ },
310+ {
311+ "include": "#variable_interpolation"
312+ },
313+ {
314+ "include": "#property_names"
315+ },
316+ {
317+ "include": "#property_names_svg"
318+ },
319+ {
320+ "include": "#property_values"
321+ },
322+ {
323+ "include": "$self"
324+ }
325+ ]
326+ },
327+ {
328+ "match": "\\!\\s*important",
329+ "name": "keyword.other.important.css"
330+ },
331+ {
332+ "match": "\\*|\\/|\\-|\\+|~|=|<=|>=|<|>",
333+ "name": "keyword.operator.less"
334+ },
335+ {
336+ "match": "\\b(not|and|when)\\b",
337+ "name": "keyword.control.logical.operator.less"
338+ },
339+ {
340+ "match": "(?x)\n(?<![\\w-])\n(a|abbr|address|area|article|aside|audio\n|b|base|bdi|bdo|blockquote|body|br|button\n|canvas|caption|cite|code|col|colgroup\n|data|datalist|dd|del|details|dfn|dialog|div|dl|dt\n|em|embed|fieldset|figure|figcaption|footer|form\n|h[1-6]|head|header|hgroup|hr|html|i|iframe|img|input|ins\n|kbd|keygen|label|legend|li|link|main|map|mark|math|menu|menuitem|meta|meter\n|nav|noscript|object|ol|optgroup|option|output\n|p|param|picture|pre|progress|q|rb|rp|rt|rtc|ruby\n|s|samp|script|section|select|small|source|span|strong|style|sub|summary|sup|svg\n|table|tbody|td|template|textarea|tfoot|th|thead|time|title|tr|track\n|u|ul|var|video|wbr)\n(?![\\w-])",
341+ "name": "entity.name.tag.css"
342+ },
343+ {
344+ "match": "(?x)\n(?<![\\w-])\n(vkern|view|use|tspan|tref|textPath|text|symbol|switch|stop|set\n|rect|radialGradient|polyline|polygon|pattern|path\n|mpath|missing-glyph|metadata|mask|marker|linearGradient|line\n|image|hkern|glyphRef|glyph|g\n|foreignObject|font(-face(-uri|-src|-name|-format)?)?|filter\n|fe(Turbulence|Tile|SpotLight|SpecularLighting|PointLight|Offset\n |Morphology|MergeNode|Merge|Image|GaussianBlur|Func[RGBA]\n |Flood|DistantLight|DisplacementMap|DiffuseLighting\n |ConvolveMatrix|Composite|ComponentTransfer|ColorMatrix|Blend)\n|ellipse|desc|defs|cursor|color-profile|clipPath|circle\n|animate(Transform|Motion|Color)?|altGlyph(Item|Def)?)\n(?![\\w-])",
345+ "name": "entity.name.tag.svg.css"
346+ },
347+ {
348+ "match": "(?<![\\w-])[a-z][\\w&&[^A-Z]]*+-[\\w-&&[^A-Z]]+",
349+ "name": "entity.name.tag.custom.css"
350+ },
351+ {
352+ "include": "#pseudo_elements"
353+ },
354+ {
355+ "include": "#pseudo_classes"
356+ },
357+ {
358+ "captures": {
359+ "1": {
360+ "name": "punctuation.section.property-list.begin.css"
361+ },
362+ "2": {
363+ "name": "punctuation.section.property-list.end.css"
364+ }
365+ },
366+ "comment": "Match empty braces to give proper ↩ action",
367+ "match": "(\\{)(\\})",
368+ "name": "meta.brace.curly.css"
369+ },
370+ {
371+ "match": "\\{|\\}",
372+ "name": "meta.brace.curly.css"
373+ },
374+ {
375+ "include": "#brace_round"
376+ },
377+ {
378+ "match": "\\[|\\]",
379+ "name": "meta.brace.square.less"
380+ },
381+ {
382+ "match": ";",
383+ "name": "punctuation.terminator.rule.css"
384+ },
385+ {
386+ "match": ":",
387+ "name": "punctuation.separator.key-value.css"
388+ },
389+ {
390+ "match": "\\btrue\\b",
391+ "name": "constant.language.boolean.less"
392+ },
393+ {
394+ "match": "\\bdefault\\b",
395+ "name": "support.function.default.less"
396+ },
397+ {
398+ "match": "\\b(isurl|isstring|isnumber|iskeyword|iscolor)\\b",
399+ "name": "support.function.type-checking.less"
400+ },
401+ {
402+ "match": "\\b(isunit|ispixel|ispercentage|isem)\\b",
403+ "name": "support.function.unit-checking.less"
404+ },
405+ {
406+ "include": "#font_names"
407+ },
408+ {
409+ "include": "#commas"
410+ },
411+ {
412+ "include": "#color_names"
413+ },
414+ {
415+ "include": "#less_builtin_functions"
416+ },
417+ {
418+ "include": "#css_builtin_functions"
419+ },
420+ {
421+ "include": "#gradient_builtin_functions"
422+ }
423+ ],
424+ "repository": {
425+ "variable_interpolation": {
426+ "match": "@{[a-zA-Z0-9_-]+}",
427+ "name": "variable.other.interpolation.less"
428+ },
429+ "strings": {
430+ "patterns": [
431+ {
432+ "begin": "\"",
433+ "beginCaptures": {
434+ "0": {
435+ "name": "punctuation.definition.string.begin.css"
436+ }
437+ },
438+ "end": "\"",
439+ "endCaptures": {
440+ "0": {
441+ "name": "punctuation.definition.string.end.css"
442+ }
443+ },
444+ "name": "string.quoted.double.css",
445+ "patterns": [
446+ {
447+ "match": "\\\\(\\h{1,6}|.)",
448+ "name": "constant.character.escape.css"
449+ },
450+ {
451+ "include": "#variable_interpolation"
452+ }
453+ ]
454+ },
455+ {
456+ "begin": "'",
457+ "beginCaptures": {
458+ "0": {
459+ "name": "punctuation.definition.string.begin.css"
460+ }
461+ },
462+ "end": "'",
463+ "endCaptures": {
464+ "0": {
465+ "name": "punctuation.definition.string.end.css"
466+ }
467+ },
468+ "name": "string.quoted.single.css",
469+ "patterns": [
470+ {
471+ "match": "\\\\(\\h{1,6}|.)",
472+ "name": "constant.character.escape.css"
473+ },
474+ {
475+ "include": "#variable_interpolation"
476+ }
477+ ]
478+ }
479+ ]
480+ },
481+ "commas": {
482+ "match": ",",
483+ "name": "punctuation.separator.list.css"
484+ },
485+ "brace_round": {
486+ "match": "\\(|\\)",
487+ "name": "meta.brace.round.css"
488+ },
489+ "property_names": {
490+ "captures": {
491+ "1": {
492+ "name": "support.type.property-name.css"
493+ }
494+ },
495+ "match": "(?<![-a-z])(-webkit-[-A-Za-z]+|-moz-[-A-Za-z]+|-o-[-A-Za-z]+|-ms-[-A-Za-z]+|-khtml-[-A-Za-z]+|zoom|z-index|y|x|wrap|word-wrap|word-spacing|word-break|word|width|widows|white-space-collapse|white-space|white|weight|volume|voice-volume|voice-stress|voice-rate|voice-pitch-range|voice-pitch|voice-family|voice-duration|voice-balance|voice|visibility|vertical-align|variant|user-select|up|unicode-bidi|unicode-range|unicode|trim|transition-timing-function|transition-property|transition-duration|transition-delay|transition|transform|touch-action|top-width|top-style|top-right-radius|top-left-radius|top-color|top|timing-function|text-wrap|text-transform|text-shadow|text-replace|text-rendering|text-overflow|text-outline|text-justify|text-indent|text-height|text-emphasis|text-decoration|text-align-last|text-align|text|target-position|target-new|target-name|target|table-layout|tab-size|style-type|style-position|style-image|style|string-set|stretch|stress|stacking-strategy|stacking-shift|stacking-ruby|stacking|src|speed|speech-rate|speech|speak-punctuation|speak-numeral|speak-header|speak|span|spacing|space-collapse|space|sizing|size-adjust|size|shadow|respond-to|rule-width|rule-style|rule-color|rule|ruby-span|ruby-position|ruby-overhang|ruby-align|ruby|rows|rotation-point|rotation|role|right-width|right-style|right-color|right|richness|rest-before|rest-after|rest|resource|resize|reset|replace|repeat|rendering-intent|rate|radius|quotes|punctuation-trim|punctuation|property|profile|presentation-level|presentation|position|pointer-events|point|play-state|play-during|play-count|pitch-range|pitch|phonemes|pause-before|pause-after|pause|page-policy|page-break-inside|page-break-before|page-break-after|page|padding-top|padding-right|padding-left|padding-bottom|padding|pack|overhang|overflow-y|overflow-x|overflow-style|overflow|outline-width|outline-style|outline-offset|outline-color|outline|orphans|origin|orientation|orient|ordinal-group|order|opacity|offset|numeral|new|nav-up|nav-right|nav-left|nav-index|nav-down|nav|name|move-to|model|mix-blend-mode|min-width|min-height|min|max-width|max-height|max|marquee-style|marquee-speed|marquee-play-count|marquee-direction|marquee|marks|mark-before|mark-after|mark|margin-top|margin-right|margin-left|margin-bottom|margin|mask-image|list-style-type|list-style-position|list-style-image|list-style|list|lines|line-stacking-strategy|line-stacking-shift|line-stacking-ruby|line-stacking|line-height|line-break|level|letter-spacing|length|left-width|left-style|left-color|left|label|justify-content|justify|iteration-count|inline-box-align|initial-value|initial-size|initial-before-align|initial-before-adjust|initial-after-align|initial-after-adjust|index|indent|increment|image-resolution|image-orientation|image|icon|hyphens|hyphenate-resource|hyphenate-lines|hyphenate-character|hyphenate-before|hyphenate-after|hyphenate|height|header|hanging-punctuation|grid-rows|grid-columns|grid|gap|font-kerning|font-language-override|font-weight|font-variant-caps|font-variant|font-style|font-synthesis|font-stretch|font-size-adjust|font-size|font-family|font|float-offset|float|flex-wrap|flex-shrink|flex-grow|flex-group|flex-flow|flex-direction|flex-basis|flex|fit-position|fit|fill|filter|family|empty-cells|emphasis|elevation|duration|drop-initial-value|drop-initial-size|drop-initial-before-align|drop-initial-before-adjust|drop-initial-after-align|drop-initial-after-adjust|drop|down|dominant-baseline|display-role|display-model|display|direction|delay|decoration-break|decoration|cursor|cue-before|cue-after|cue|crop|counter-reset|counter-increment|counter|count|content|columns|column-width|column-span|column-rule-width|column-rule-style|column-rule-color|column-rule|column-gap|column-fill|column-count|column-break-before|column-break-after|column|color-profile|color|collapse|clip|clear|character|caption-side|break-inside|break-before|break-after|break|box-sizing|box-shadow|box-pack|box-orient|box-ordinal-group|box-lines|box-flex-group|box-flex|box-direction|box-decoration-break|box-align|box|bottom-width|bottom-style|bottom-right-radius|bottom-left-radius|bottom-color|bottom|border-width|border-top-width|border-top-style|border-top-right-radius|border-top-left-radius|border-top-color|border-top|border-style|border-spacing|border-right-width|border-right-style|border-right-color|border-right|border-radius|border-length|border-left-width|border-left-style|border-left-color|border-left|border-image|border-color|border-collapse|border-bottom-width|border-bottom-style|border-bottom-right-radius|border-bottom-left-radius|border-bottom-color|border-bottom|border|bookmark-target|bookmark-level|bookmark-label|bookmark|binding|bidi|before|baseline-shift|baseline|balance|background-blend-mode|background-size|background-repeat|background-position|background-origin|background-image|background-color|background-clip|background-break|background-attachment|background|azimuth|attachment|appearance|animation-timing-function|animation-play-state|animation-name|animation-iteration-count|animation-duration|animation-direction|animation-delay|animation-fill-mode|animation|alignment-baseline|alignment-adjust|alignment|align-self|align-last|align-items|align-content|align|after|adjust|will-change)(?=\\s*:?(.*\\()|(?!.*(?<!@){))\\b"
496+ },
497+ "property_names_svg": {
498+ "captures": {
499+ "1": {
500+ "name": "support.type.property-name.svg.css"
501+ }
502+ },
503+ "match": "(?<![-a-z])(writing-mode|text-anchor|stroke-width|stroke-opacity|stroke-miterlimit|stroke-linejoin|stroke-linecap|stroke-dashoffset|stroke-dasharray|stroke|stop-opacity|stop-color|shape-rendering|marker-start|marker-mid|marker-end|lighting-color|kerning|image-rendering|glyph-orientation-vertical|glyph-orientation-horizontal|flood-opacity|flood-color|fill-rule|fill-opacity|fill|enable-background|color-rendering|color-interpolation-filters|color-interpolation|clip-rule|clip-path)(?=\\s*:)"
504+ },
505+ "property_values": {
506+ "begin": "(?<!&)(:)\\s*(?!(\\s*{))(?!.*(?<!@){)",
507+ "beginCaptures": {
508+ "1": {
509+ "name": "punctuation.separator.key-value.css"
510+ }
511+ },
512+ "end": "\\s*(;)|\\s*(?=})",
513+ "endCaptures": {
514+ "1": {
515+ "name": "punctuation.terminator.rule.css"
516+ }
517+ },
518+ "contentName": "meta.property-value.css",
519+ "patterns": [
520+ {
521+ "match": "\\b(wrap-reverse|wrap|whitespace|wait|w-resize|visible|vertical-text|vertical-ideographic|uppercase|upper-roman|upper-alpha|unicase|underline|ultra-expanded|ultra-condensed|transparent|transform|top|titling-caps|thin|thick|text-top|text-bottom|text|tb-rl|table-row-group|table-row|table-header-group|table-footer-group|table-column-group|table-column|table-cell|table|sw-resize|super|strict|stretch|step-start|step-end|static|square|space-between|space-around|space|solid|soft-light|small-caps|separate|semi-expanded|semi-condensed|se-resize|scroll|screen|saturation|s-resize|running|rtl|row-reverse|row-resize|row|round|right|ridge|reverse|repeat-y|repeat-x|repeat|relative|progressive|progress|pre-wrap|pre-line|pre|pointer|petite-caps|paused|pan-x|pan-left|pan-right|pan-y|pan-up|pan-down|padding-box|overline|overlay|outside|outset|optimizeSpeed|optimizeLegibility|opacity|oblique|nw-resize|nowrap|not-allowed|normal|none|no-repeat|no-drop|newspaper|ne-resize|n-resize|multiply|move|middle|medium|max-height|manipulation|main-size|luminosity|ltr|lr-tb|lowercase|lower-roman|lower-alpha|loose|local|list-item|linear(?!-)|line-through|line-edge|line|lighter|lighten|left|keep-all|justify|italic|inter-word|inter-ideograph|inside|inset|inline-block|inline|inherit|infinite|inactive|ideograph-space|ideograph-parenthesis|ideograph-numeric|ideograph-alpha|hue|horizontal|hidden|help|hard-light|hand|groove|geometricPrecision|forwards|flex-start|flex-end|flex|fixed|extra-expanded|extra-condensed|expanded|exclusion|ellipsis|ease-out|ease-in-out|ease-in|ease|e-resize|double|dotted|distribute-space|distribute-letter|distribute-all-lines|distribute|disc|disabled|difference|default|decimal|dashed|darken|currentColor|crosshair|cover|content-box|contain|condensed|column-reverse|column|color-dodge|color-burn|color|collapse|col-resize|circle|char|center|capitalize|break-word|break-all|bottom|both|border-box|bolder|bold|block|bidi-override|below|baseline|balance|backwards|auto|antialiased|always|alternate-reverse|alternate|all-small-caps|all-scroll|all-petite-caps|all|absolute)\\b",
522+ "name": "support.constant.property-value.css"
523+ },
524+ {
525+ "match": "\\b(start|sRGB|square|round|optimizeSpeed|optimizeQuality|nonzero|miter|middle|linearRGB|geometricPrecision |evenodd |end |crispEdges|butt|bevel)\\b",
526+ "name": "support.constant.property-value.svg.css"
527+ },
528+ {
529+ "begin": "url(\\()",
530+ "beginCaptures": {
531+ "1": {
532+ "name": "meta.brace.round.css"
533+ }
534+ },
535+ "end": "\\)",
536+ "endCaptures": {
537+ "0": {
538+ "name": "meta.brace.round.css"
539+ }
540+ },
541+ "name": "support.function.any-method.builtin.url.css",
542+ "patterns": [
543+ {
544+ "include": "#strings"
545+ },
546+ {
547+ "match": "(\\b|\\.{0,2}/).*\\b",
548+ "name": "string.url.css"
549+ }
550+ ]
551+ },
552+ {
553+ "include": "#font_names"
554+ },
555+ {
556+ "include": "#color_names"
557+ },
558+ {
559+ "include": "#less_builtin_functions"
560+ },
561+ {
562+ "include": "#css_builtin_functions"
563+ },
564+ {
565+ "include": "#gradient_builtin_functions"
566+ },
567+ {
568+ "include": "$self"
569+ }
570+ ]
571+ },
572+ "pseudo_elements": {
573+ "captures": {
574+ "1": {
575+ "name": "punctuation.definition.entity.css"
576+ }
577+ },
578+ "match": "(:|::)(after|before|first-letter|first-line|selection|shadow)",
579+ "name": "entity.other.attribute-name.pseudo-element.css"
580+ },
581+ "pseudo_classes": {
582+ "captures": {
583+ "1": {
584+ "name": "punctuation.definition.entity.css"
585+ }
586+ },
587+ "match": "(:)(active|checked|default|dir|disabled|empty|enabled|extend|first-child|first-of-type|first|fullscreen|focus|hover|indeterminate|in-range|invalid|lang|last-child|last-of-type|left|link|not|nth-child|nth-last-child|nth-last-of-type|nth-of-type|only-child|only-of-type|optional|out-of-range|read-only|read-write|required|right|root|scope|shadow|target|valid|visited)(?!\\s*;)",
588+ "name": "entity.other.attribute-name.pseudo-class.css"
589+ },
590+ "font_names": {
591+ "match": "(\\b(?i:arial|century|comic|courier|cursive|fantasy|futura|garamond|georgia|helvetica|impact|lucida|monospace|symbol|system|tahoma|times|trebuchet|utopia|verdana|webdings|sans-serif|serif)\\b)",
592+ "name": "support.constant.font-name.css"
593+ },
594+ "color_names": {
595+ "match": "\\b(yellowgreen|yellow|whitesmoke|white|wheat|violet|turquoise|tomato|thistle|teal|tan|steelblue|springgreen|snow|slategrey|slategray|slateblue|skyblue|silver|sienna|seashell|seagreen|sandybrown|salmon|saddlebrown|royalblue|rosybrown|red|rebeccapurple|purple|powderblue|plum|pink|peru|peachpuff|papayawhip|palevioletred|paleturquoise|palegreen|palegoldenrod|orchid|orangered|orange|olivedrab|olive|oldlace|navy|navajowhite|moccasin|mistyrose|mintcream|midnightblue|mediumvioletred|mediumturquoise|mediumspringgreen|mediumslateblue|mediumseagreen|mediumpurple|mediumorchid|mediumblue|mediumaquamarine|maroon|linen|limegreen|lime|lightyellow|lightsteelblue|lightslategrey|lightslategray|lightskyblue|lightseagreen|lightsalmon|lightpink|lightgrey|lightgreen|lightgray|lightgoldenrodyellow|lightcyan|lightcoral|lightblue|lemonchiffon|lawngreen|lavenderblush|lavender|khaki|ivory|indigo|indianred|hotpink|honeydew|grey|greenyellow|green|gray|goldenrod|gold|ghostwhite|gainsboro|fuchsia|forestgreen|floralwhite|firebrick|dodgerblue|dimgrey|dimgray|deepskyblue|deeppink|darkviolet|darkturquoise|darkslategrey|darkslategray|darkslateblue|darkseagreen|darksalmon|darkred|darkorchid|darkorange|darkolivegreen|darkmagenta|darkkhaki|darkgrey|darkgreen|darkgray|darkgoldenrod|darkcyan|darkblue|crimson|cornsilk|cornflowerblue|coral|chocolate|chartreuse|cadetblue|burlywood|brown|blueviolet|blue|blanchedalmond|black|bisque|beige|azure|aquamarine|aqua|antiquewhite|aliceblue)\\b",
596+ "name": "support.constant.color.w3c-standard-color-name.css"
597+ },
598+ "less_builtin_functions": {
599+ "match": "\\b(abs|acos|alpha|argb|asin|atan|average|blue|calc|ceil|color|contrast|convert|convert|cos|darken|data-uri|desaturate|difference|e|escape|exclusion|extract|fade|fadein|fadeout|floor|format|green|greyscale|hardlight|hsl|hsla|hsv|hsva|hsvhue|hsvsaturation|hsvvalue|hue|length|lighten|lightness|luma|max|min|mix|mod|multiply|negation|overlay|percentage|pi|pow|red|replace|round|saturate|saturation|screen|sin|softlight|spin|sqrt|tan|unit)\\b",
600+ "name": "support.function.any-method.builtin.less"
601+ },
602+ "css_builtin_functions": {
603+ "match": "\\b(url|translate3d|translate[XYZ]|translate|skew[XY]|skew|scale[XYZ]|scale|rotate3d|rotate[XYZ]|rotate|rgba|rgb|repeating-radial-gradient|repeating-linear-gradient|rect|radial-gradient|matrix3d|matrix|linear-gradient|hsla|hsl|drop-shadow|cubic-bezier|blur)\\b",
604+ "name": "support.function.any-method.builtin.css"
605+ },
606+ "gradient_builtin_functions": {
607+ "match": "\\b(color-stop|from|to)\\b",
608+ "name": "support.function.any-method.gradient.css"
609+ }
610+ },
611+ "version": "https://github.com/atom/language-less/commit/c5876823ed8ae556c82f76c05de815a72a9df6a4"
612+}
modified extensions/vscode/textmate-syntaxes/lua.json +189 −191
@@ -1,192 +1,190 @@
11 {
2- "comment": "Lua Syntax: version 0.8",
3- "fileTypes": [
4- "lua"
5- ],
6- "firstLineMatch": "\\A#!.*?\\blua\\b",
7- "keyEquivalent": "^~L",
8- "name": "Lua",
9- "patterns": [
10- {
11- "captures": {
12- "1": {
13- "name": "keyword.control.lua"
14- },
15- "2": {
16- "name": "entity.name.function.scope.lua"
17- },
18- "3": {
19- "name": "entity.name.function.lua"
20- },
21- "4": {
22- "name": "punctuation.definition.parameters.begin.lua"
23- },
24- "5": {
25- "name": "variable.parameter.function.lua"
26- },
27- "6": {
28- "name": "punctuation.definition.parameters.end.lua"
29- }
30- },
31- "match": "\\b(function)(?:\\s+([a-zA-Z_.:]+[.:])?([a-zA-Z_]\\w*)\\s*)?(\\()([^)]*)(\\))",
32- "name": "meta.function.lua"
33- },
34- {
35- "match": "(?<![\\d.])\\s0x[a-fA-F\\d]+|\\b\\d+(\\.\\d+)?([eE]-?\\d+)?|\\.\\d+([eE]-?\\d+)?",
36- "name": "constant.numeric.lua"
37- },
38- {
39- "begin": "'",
40- "beginCaptures": {
41- "0": {
42- "name": "punctuation.definition.string.begin.lua"
43- }
44- },
45- "end": "'",
46- "endCaptures": {
47- "0": {
48- "name": "punctuation.definition.string.end.lua"
49- }
50- },
51- "name": "string.quoted.single.lua",
52- "patterns": [
53- {
54- "match": "\\\\.",
55- "name": "constant.character.escape.lua"
56- }
57- ]
58- },
59- {
60- "begin": "\"",
61- "beginCaptures": {
62- "0": {
63- "name": "punctuation.definition.string.begin.lua"
64- }
65- },
66- "end": "\"",
67- "endCaptures": {
68- "0": {
69- "name": "punctuation.definition.string.end.lua"
70- }
71- },
72- "name": "string.quoted.double.lua",
73- "patterns": [
74- {
75- "match": "\\\\.",
76- "name": "constant.character.escape.lua"
77- }
78- ]
79- },
80- {
81- "begin": "(?<=\\.cdef)\\s*(\\[(=*)\\[)",
82- "beginCaptures": {
83- "0": {
84- "name": "string.quoted.other.multiline.lua"
85- },
86- "1": {
87- "name": "punctuation.definition.string.begin.lua"
88- }
89- },
90- "contentName": "meta.embedded.lua",
91- "end": "(\\]\\2\\])",
92- "endCaptures": {
93- "0": {
94- "name": "string.quoted.other.multiline.lua"
95- },
96- "1": {
97- "name": "punctuation.definition.string.end.lua"
98- }
99- },
100- "patterns": [
101- {
102- "include": "source.c"
103- }
104- ]
105- },
106- {
107- "begin": "(?<!--)\\[(=*)\\[",
108- "beginCaptures": {
109- "0": {
110- "name": "punctuation.definition.string.begin.lua"
111- }
112- },
113- "end": "\\]\\1\\]",
114- "endCaptures": {
115- "0": {
116- "name": "punctuation.definition.string.end.lua"
117- }
118- },
119- "name": "string.quoted.other.multiline.lua"
120- },
121- {
122- "begin": "--\\[(=*)\\[",
123- "captures": {
124- "0": {
125- "name": "punctuation.definition.comment.lua"
126- }
127- },
128- "end": "\\]\\1\\]",
129- "name": "comment.block.lua"
130- },
131- {
132- "begin": "(^[ \\t]+)?(?=--(?!\\[\\[))",
133- "beginCaptures": {
134- "1": {
135- "name": "punctuation.whitespace.comment.leading.lua"
136- }
137- },
138- "end": "(?!\\G)",
139- "patterns": [
140- {
141- "begin": "--",
142- "beginCaptures": {
143- "0": {
144- "name": "punctuation.definition.comment.lua"
145- }
146- },
147- "end": "\\n",
148- "name": "comment.line.double-dash.lua"
149- }
150- ]
151- },
152- {
153- "match": "\\b(break|do|else|for|if|elseif|return|then|repeat|while|until|end|function|local|in)\\b",
154- "name": "keyword.control.lua"
155- },
156- {
157- "match": "(?<![^.]\\.|:)\\b(false|nil|true|_G|_VERSION|math\\.(pi|huge))\\b|(?<![.])\\.{3}(?!\\.)",
158- "name": "constant.language.lua"
159- },
160- {
161- "match": "(?<![^.]\\.|:)\\b(self)\\b",
162- "name": "variable.language.self.lua"
163- },
164- {
165- "match": "(?<![^.]\\.|:)\\b(assert|collectgarbage|dofile|error|getfenv|getmetatable|ipairs|loadfile|loadstring|module|next|pairs|pcall|print|rawequal|rawget|rawset|require|select|setfenv|setmetatable|tonumber|tostring|type|unpack|xpcall)\\b(?=\\s*(?:[({\"']|\\[\\[))",
166- "name": "support.function.lua"
167- },
168- {
169- "match": "(?<![^.]\\.|:)\\b(coroutine\\.(create|resume|running|status|wrap|yield)|string\\.(byte|char|dump|find|format|gmatch|gsub|len|lower|match|rep|reverse|sub|upper)|table\\.(concat|insert|maxn|remove|sort)|math\\.(abs|acos|asin|atan2?|ceil|cosh?|deg|exp|floor|fmod|frexp|ldexp|log|log10|max|min|modf|pow|rad|random|randomseed|sinh?|sqrt|tanh?)|io\\.(close|flush|input|lines|open|output|popen|read|tmpfile|type|write)|os\\.(clock|date|difftime|execute|exit|getenv|remove|rename|setlocale|time|tmpname)|package\\.(cpath|loaded|loadlib|path|preload|seeall)|debug\\.(debug|[gs]etfenv|[gs]ethook|getinfo|[gs]etlocal|[gs]etmetatable|getregistry|[gs]etupvalue|traceback))\\b(?=\\s*(?:[({\"']|\\[\\[))",
170- "name": "support.function.library.lua"
171- },
172- {
173- "match": "\\b(and|or|not)\\b",
174- "name": "keyword.operator.lua"
175- },
176- {
177- "match": "\\b([A-Za-z_]\\w*)\\b(?=\\s*(?:[({\"']|\\[\\[))",
178- "name": "support.function.any-method.lua"
179- },
180- {
181- "match": "(?<=[^.]\\.|:)\\b([A-Za-z_]\\w*)",
182- "name": "variable.other.lua"
183- },
184- {
185- "match": "\\+|-|%|#|\\*|\\/|\\^|==?|~=|<=?|>=?|(?<!\\.)\\.{2}(?!\\.)",
186- "name": "keyword.operator.lua"
187- }
188- ],
189- "scopeName": "source.lua",
190- "uuid": "93E017CC-6F27-11D9-90EB-000D93589AF7",
191- "version": "https://github.com/textmate/lua.tmbundle/commit/609fe340f40b31f4189dabbb38f885b58cf0dd26"
192-}
No newline at the end of the file
2+ "comment": "Lua Syntax: version 0.8",
3+ "fileTypes": ["lua"],
4+ "firstLineMatch": "\\A#!.*?\\blua\\b",
5+ "keyEquivalent": "^~L",
6+ "name": "Lua",
7+ "patterns": [
8+ {
9+ "captures": {
10+ "1": {
11+ "name": "keyword.control.lua"
12+ },
13+ "2": {
14+ "name": "entity.name.function.scope.lua"
15+ },
16+ "3": {
17+ "name": "entity.name.function.lua"
18+ },
19+ "4": {
20+ "name": "punctuation.definition.parameters.begin.lua"
21+ },
22+ "5": {
23+ "name": "variable.parameter.function.lua"
24+ },
25+ "6": {
26+ "name": "punctuation.definition.parameters.end.lua"
27+ }
28+ },
29+ "match": "\\b(function)(?:\\s+([a-zA-Z_.:]+[.:])?([a-zA-Z_]\\w*)\\s*)?(\\()([^)]*)(\\))",
30+ "name": "meta.function.lua"
31+ },
32+ {
33+ "match": "(?<![\\d.])\\s0x[a-fA-F\\d]+|\\b\\d+(\\.\\d+)?([eE]-?\\d+)?|\\.\\d+([eE]-?\\d+)?",
34+ "name": "constant.numeric.lua"
35+ },
36+ {
37+ "begin": "'",
38+ "beginCaptures": {
39+ "0": {
40+ "name": "punctuation.definition.string.begin.lua"
41+ }
42+ },
43+ "end": "'",
44+ "endCaptures": {
45+ "0": {
46+ "name": "punctuation.definition.string.end.lua"
47+ }
48+ },
49+ "name": "string.quoted.single.lua",
50+ "patterns": [
51+ {
52+ "match": "\\\\.",
53+ "name": "constant.character.escape.lua"
54+ }
55+ ]
56+ },
57+ {
58+ "begin": "\"",
59+ "beginCaptures": {
60+ "0": {
61+ "name": "punctuation.definition.string.begin.lua"
62+ }
63+ },
64+ "end": "\"",
65+ "endCaptures": {
66+ "0": {
67+ "name": "punctuation.definition.string.end.lua"
68+ }
69+ },
70+ "name": "string.quoted.double.lua",
71+ "patterns": [
72+ {
73+ "match": "\\\\.",
74+ "name": "constant.character.escape.lua"
75+ }
76+ ]
77+ },
78+ {
79+ "begin": "(?<=\\.cdef)\\s*(\\[(=*)\\[)",
80+ "beginCaptures": {
81+ "0": {
82+ "name": "string.quoted.other.multiline.lua"
83+ },
84+ "1": {
85+ "name": "punctuation.definition.string.begin.lua"
86+ }
87+ },
88+ "contentName": "meta.embedded.lua",
89+ "end": "(\\]\\2\\])",
90+ "endCaptures": {
91+ "0": {
92+ "name": "string.quoted.other.multiline.lua"
93+ },
94+ "1": {
95+ "name": "punctuation.definition.string.end.lua"
96+ }
97+ },
98+ "patterns": [
99+ {
100+ "include": "source.c"
101+ }
102+ ]
103+ },
104+ {
105+ "begin": "(?<!--)\\[(=*)\\[",
106+ "beginCaptures": {
107+ "0": {
108+ "name": "punctuation.definition.string.begin.lua"
109+ }
110+ },
111+ "end": "\\]\\1\\]",
112+ "endCaptures": {
113+ "0": {
114+ "name": "punctuation.definition.string.end.lua"
115+ }
116+ },
117+ "name": "string.quoted.other.multiline.lua"
118+ },
119+ {
120+ "begin": "--\\[(=*)\\[",
121+ "captures": {
122+ "0": {
123+ "name": "punctuation.definition.comment.lua"
124+ }
125+ },
126+ "end": "\\]\\1\\]",
127+ "name": "comment.block.lua"
128+ },
129+ {
130+ "begin": "(^[ \\t]+)?(?=--(?!\\[\\[))",
131+ "beginCaptures": {
132+ "1": {
133+ "name": "punctuation.whitespace.comment.leading.lua"
134+ }
135+ },
136+ "end": "(?!\\G)",
137+ "patterns": [
138+ {
139+ "begin": "--",
140+ "beginCaptures": {
141+ "0": {
142+ "name": "punctuation.definition.comment.lua"
143+ }
144+ },
145+ "end": "\\n",
146+ "name": "comment.line.double-dash.lua"
147+ }
148+ ]
149+ },
150+ {
151+ "match": "\\b(break|do|else|for|if|elseif|return|then|repeat|while|until|end|function|local|in)\\b",
152+ "name": "keyword.control.lua"
153+ },
154+ {
155+ "match": "(?<![^.]\\.|:)\\b(false|nil|true|_G|_VERSION|math\\.(pi|huge))\\b|(?<![.])\\.{3}(?!\\.)",
156+ "name": "constant.language.lua"
157+ },
158+ {
159+ "match": "(?<![^.]\\.|:)\\b(self)\\b",
160+ "name": "variable.language.self.lua"
161+ },
162+ {
163+ "match": "(?<![^.]\\.|:)\\b(assert|collectgarbage|dofile|error|getfenv|getmetatable|ipairs|loadfile|loadstring|module|next|pairs|pcall|print|rawequal|rawget|rawset|require|select|setfenv|setmetatable|tonumber|tostring|type|unpack|xpcall)\\b(?=\\s*(?:[({\"']|\\[\\[))",
164+ "name": "support.function.lua"
165+ },
166+ {
167+ "match": "(?<![^.]\\.|:)\\b(coroutine\\.(create|resume|running|status|wrap|yield)|string\\.(byte|char|dump|find|format|gmatch|gsub|len|lower|match|rep|reverse|sub|upper)|table\\.(concat|insert|maxn|remove|sort)|math\\.(abs|acos|asin|atan2?|ceil|cosh?|deg|exp|floor|fmod|frexp|ldexp|log|log10|max|min|modf|pow|rad|random|randomseed|sinh?|sqrt|tanh?)|io\\.(close|flush|input|lines|open|output|popen|read|tmpfile|type|write)|os\\.(clock|date|difftime|execute|exit|getenv|remove|rename|setlocale|time|tmpname)|package\\.(cpath|loaded|loadlib|path|preload|seeall)|debug\\.(debug|[gs]etfenv|[gs]ethook|getinfo|[gs]etlocal|[gs]etmetatable|getregistry|[gs]etupvalue|traceback))\\b(?=\\s*(?:[({\"']|\\[\\[))",
168+ "name": "support.function.library.lua"
169+ },
170+ {
171+ "match": "\\b(and|or|not)\\b",
172+ "name": "keyword.operator.lua"
173+ },
174+ {
175+ "match": "\\b([A-Za-z_]\\w*)\\b(?=\\s*(?:[({\"']|\\[\\[))",
176+ "name": "support.function.any-method.lua"
177+ },
178+ {
179+ "match": "(?<=[^.]\\.|:)\\b([A-Za-z_]\\w*)",
180+ "name": "variable.other.lua"
181+ },
182+ {
183+ "match": "\\+|-|%|#|\\*|\\/|\\^|==?|~=|<=?|>=?|(?<!\\.)\\.{2}(?!\\.)",
184+ "name": "keyword.operator.lua"
185+ }
186+ ],
187+ "scopeName": "source.lua",
188+ "uuid": "93E017CC-6F27-11D9-90EB-000D93589AF7",
189+ "version": "https://github.com/textmate/lua.tmbundle/commit/609fe340f40b31f4189dabbb38f885b58cf0dd26"
190+}
modified extensions/vscode/textmate-syntaxes/php.json +1 −1
@@ -2635,4 +2635,4 @@
26352635 ]
26362636 }
26372637 }
2638-}
No newline at the end of the file
2638+}
modified extensions/vscode/textmate-syntaxes/rust.json +2 −4
@@ -1,9 +1,7 @@
11 {
22 "name": "Rust",
33 "scopeName": "source.rust",
4- "fileTypes": [
5- "rs"
6- ],
4+ "fileTypes": ["rs"],
75 "repository": {
86 "block_doc_comment": {
97 "comment": "Block documentation comment",
@@ -592,4 +590,4 @@
592590 ]
593591 }
594592 ]
595-}
No newline at the end of the file
593+}
modified extensions/vscode/textmate-syntaxes/scss.json +1666 −1671
@@ -1,1672 +1,1667 @@
11 {
2- "scopeName": "source.css.scss",
3- "name": "SCSS",
4- "fileTypes": [
5- "scss",
6- "css.scss",
7- "css.scss.erb",
8- "scss.erb"
9- ],
10- "patterns": [
11- {
12- "include": "#variable_setting"
13- },
14- {
15- "include": "#at_rule_include"
16- },
17- {
18- "include": "#at_rule_import"
19- },
20- {
21- "include": "#general"
22- },
23- {
24- "include": "#flow_control"
25- },
26- {
27- "include": "#rules"
28- },
29- {
30- "include": "#property_list"
31- },
32- {
33- "include": "#at_rule_mixin"
34- },
35- {
36- "include": "#at_rule_media"
37- },
38- {
39- "include": "#at_rule_function"
40- },
41- {
42- "include": "#at_rule_charset"
43- },
44- {
45- "include": "#at_rule_option"
46- },
47- {
48- "include": "#at_rule_namespace"
49- },
50- {
51- "include": "#at_rule_fontface"
52- },
53- {
54- "include": "#at_rule_page"
55- },
56- {
57- "include": "#at_rule_keyframes"
58- },
59- {
60- "include": "#at_rule_at_root"
61- },
62- {
63- "include": "#at_rule_supports"
64- }
65- ],
66- "repository": {
67- "at_rule__": {
68- "comment": "Note how all @rules are prefixed."
69- },
70- "at_rule_charset": {
71- "begin": "\\s*((@)charset\\b)\\s*",
72- "captures": {
73- "1": {
74- "name": "keyword.control.at-rule.charset.scss"
75- },
76- "2": {
77- "name": "punctuation.definition.keyword.scss"
78- }
79- },
80- "comment": "Charset",
81- "end": "\\s*((?=;|$))",
82- "name": "meta.at-rule.charset.scss",
83- "patterns": [
84- {
85- "include": "#variable"
86- },
87- {
88- "include": "#string_single"
89- },
90- {
91- "include": "#string_double"
92- }
93- ]
94- },
95- "at_rule_content": {
96- "begin": "\\s*((@)content\\b)\\s*",
97- "captures": {
98- "1": {
99- "name": "keyword.control.content.scss"
100- }
101- },
102- "end": "\\s*((?=;))",
103- "name": "meta.content.scss",
104- "patterns": [
105- {
106- "include": "#variable"
107- },
108- {
109- "include": "#selectors"
110- },
111- {
112- "include": "#property_values"
113- }
114- ]
115- },
116- "at_rule_each": {
117- "begin": "\\s*((@)each\\b)\\s*",
118- "captures": {
119- "1": {
120- "name": "keyword.control.each.scss"
121- },
122- "2": {
123- "name": "punctuation.definition.keyword.scss"
124- }
125- },
126- "end": "\\s*((?=}))",
127- "name": "meta.at-rule.each.scss",
128- "patterns": [
129- {
130- "match": "\\b(in|,)\\b",
131- "name": "keyword.control.operator"
132- },
133- {
134- "include": "#variable"
135- },
136- {
137- "include": "#property_values"
138- },
139- {
140- "include": "$self"
141- }
142- ]
143- },
144- "at_rule_else": {
145- "begin": "\\s*((@)else(\\s*(if)?))\\s*",
146- "captures": {
147- "1": {
148- "name": "keyword.control.else.scss"
149- },
150- "2": {
151- "name": "punctuation.definition.keyword.scss"
152- }
153- },
154- "end": "\\s*(?={)",
155- "name": "meta.at-rule.else.scss",
156- "patterns": [
157- {
158- "include": "#conditional_operators"
159- },
160- {
161- "include": "#variable"
162- },
163- {
164- "include": "#property_values"
165- }
166- ]
167- },
168- "at_rule_extend": {
169- "begin": "\\s*((@)extend\\b)\\s*",
170- "captures": {
171- "1": {
172- "name": "keyword.control.at-rule.import.scss"
173- },
174- "2": {
175- "name": "punctuation.definition.keyword.scss"
176- }
177- },
178- "end": "\\s*(?=;)",
179- "name": "meta.at-rule.import.scss",
180- "patterns": [
181- {
182- "include": "#variable"
183- },
184- {
185- "include": "#selectors"
186- },
187- {
188- "include": "#property_values"
189- }
190- ]
191- },
192- "at_rule_fontface": {
193- "patterns": [
194- {
195- "begin": "^\\s*((@)font-face\\b)",
196- "beginCaptures": {
197- "1": {
198- "name": "keyword.control.at-rule.fontface.scss"
199- },
200- "2": {
201- "name": "punctuation.definition.keyword.scss"
202- }
203- },
204- "end": "\\s*(?={)",
205- "name": "meta.at-rule.fontface.scss",
206- "patterns": [
207- {
208- "include": "#function_attributes"
209- }
210- ]
211- }
212- ]
213- },
214- "at_rule_for": {
215- "begin": "\\s*((@)for\\b)\\s*",
216- "captures": {
217- "1": {
218- "name": "keyword.control.for.scss"
219- },
220- "2": {
221- "name": "punctuation.definition.keyword.scss"
222- }
223- },
224- "end": "\\s*(?={)",
225- "name": "meta.at-rule.for.scss",
226- "patterns": [
227- {
228- "match": "(==|!=|<=|>=|<|>|from|to|through)",
229- "name": "keyword.control.operator"
230- },
231- {
232- "include": "#variable"
233- },
234- {
235- "include": "#property_values"
236- },
237- {
238- "include": "$self"
239- }
240- ]
241- },
242- "at_rule_function": {
243- "patterns": [
244- {
245- "begin": "\\s*((@)function\\b)\\s*",
246- "captures": {
247- "1": {
248- "name": "keyword.control.at-rule.function.scss"
249- },
250- "2": {
251- "name": "punctuation.definition.keyword.scss"
252- },
253- "3": {
254- "name": "entity.name.function.scss"
255- }
256- },
257- "comment": "Function with Attributes",
258- "end": "\\s*(?={)",
259- "name": "meta.at-rule.function.scss",
260- "patterns": [
261- {
262- "include": "#function_attributes"
263- }
264- ]
265- },
266- {
267- "captures": {
268- "1": {
269- "name": "keyword.control.at-rule.function.scss"
270- },
271- "2": {
272- "name": "punctuation.definition.keyword.scss"
273- },
274- "3": {
275- "name": "entity.name.function.scss"
276- }
277- },
278- "comment": "Simple Function",
279- "match": "\\s*((@)function\\b)\\s*",
280- "name": "meta.at-rule.function.scss"
281- }
282- ]
283- },
284- "at_rule_if": {
285- "begin": "\\s*((@)if\\b)\\s*",
286- "captures": {
287- "1": {
288- "name": "keyword.control.if.scss"
289- },
290- "2": {
291- "name": "punctuation.definition.keyword.scss"
292- }
293- },
294- "end": "\\s*(?={)",
295- "name": "meta.at-rule.if.scss",
296- "patterns": [
297- {
298- "include": "#conditional_operators"
299- },
300- {
301- "include": "#variable"
302- },
303- {
304- "include": "#property_values"
305- }
306- ]
307- },
308- "at_rule_import": {
309- "begin": "\\s*((@)import\\b)\\s*",
310- "captures": {
311- "1": {
312- "name": "keyword.control.at-rule.import.scss"
313- },
314- "2": {
315- "name": "punctuation.definition.keyword.scss"
316- }
317- },
318- "end": "\\s*((?=;)|(?=}))",
319- "name": "meta.at-rule.import.scss",
320- "patterns": [
321- {
322- "include": "#variable"
323- },
324- {
325- "include": "#string_single"
326- },
327- {
328- "include": "#string_double"
329- },
330- {
331- "include": "#functions"
332- },
333- {
334- "include": "#comment_line"
335- }
336- ]
337- },
338- "at_rule_include": {
339- "patterns": [
340- {
341- "begin": "(?<=@include)\\s+([\\w-]+)\\s*(\\()",
342- "beginCaptures": {
343- "1": {
344- "name": "entity.name.function.scss"
345- },
346- "2": {
347- "name": "punctuation.definition.parameters.begin.bracket.round.scss"
348- }
349- },
350- "end": "\\)",
351- "endCaptures": {
352- "0": {
353- "name": "punctuation.definition.parameters.end.bracket.round.scss"
354- }
355- },
356- "name": "meta.at-rule.include.scss",
357- "patterns": [
358- {
359- "include": "#function_attributes"
360- }
361- ]
362- },
363- {
364- "match": "(?<=@include)\\s+([\\w-]+)",
365- "captures": {
366- "0": {
367- "name": "meta.at-rule.include.scss"
368- },
369- "1": {
370- "name": "entity.name.function.scss"
371- }
372- }
373- },
374- {
375- "match": "((@)include)\\b",
376- "captures": {
377- "0": {
378- "name": "meta.at-rule.include.scss"
379- },
380- "1": {
381- "name": "keyword.control.at-rule.include.scss"
382- },
383- "2": {
384- "name": "punctuation.definition.keyword.scss"
385- }
386- }
387- }
388- ]
389- },
390- "at_rule_keyframes": {
391- "begin": "(?<=^|\\s)(@)(?:-(?:webkit|moz)-)?keyframes\\b",
392- "beginCaptures": {
393- "0": {
394- "name": "keyword.control.at-rule.keyframes.scss"
395- },
396- "1": {
397- "name": "punctuation.definition.keyword.scss"
398- }
399- },
400- "end": "(?<=})",
401- "name": "meta.at-rule.keyframes.scss",
402- "patterns": [
403- {
404- "match": "(?<=@keyframes)\\s+((?:[_A-Za-z][-\\w]|-[_A-Za-z])[-\\w]*)",
405- "captures": {
406- "1": {
407- "name": "entity.name.function.scss"
408- }
409- }
410- },
411- {
412- "begin": "(?<=@keyframes)\\s+(\")",
413- "beginCaptures": {
414- "1": {
415- "name": "punctuation.definition.string.begin.scss"
416- }
417- },
418- "end": "\"",
419- "endCaptures": {
420- "0": {
421- "name": "punctuation.definition.string.end.scss"
422- }
423- },
424- "name": "string.quoted.double.scss",
425- "contentName": "entity.name.function.scss",
426- "patterns": [
427- {
428- "match": "\\\\(\\h{1,6}|.)",
429- "name": "constant.character.escape.scss"
430- },
431- {
432- "include": "#interpolation"
433- }
434- ]
435- },
436- {
437- "begin": "(?<=@keyframes)\\s+(')",
438- "beginCaptures": {
439- "1": {
440- "name": "punctuation.definition.string.begin.scss"
441- }
442- },
443- "end": "'",
444- "endCaptures": {
445- "0": {
446- "name": "punctuation.definition.string.end.scss"
447- }
448- },
449- "name": "string.quoted.single.scss",
450- "contentName": "entity.name.function.scss",
451- "patterns": [
452- {
453- "match": "\\\\(\\h{1,6}|.)",
454- "name": "constant.character.escape.scss"
455- },
456- {
457- "include": "#interpolation"
458- }
459- ]
460- },
461- {
462- "begin": "{",
463- "beginCaptures": {
464- "0": {
465- "name": "punctuation.section.keyframes.begin.scss"
466- }
467- },
468- "end": "}",
469- "endCaptures": {
470- "0": {
471- "name": "punctuation.section.keyframes.end.scss"
472- }
473- },
474- "patterns": [
475- {
476- "match": "\\b(?:(?:100|[1-9]\\d|\\d)%|from|to)(?=\\s*{)",
477- "name": "entity.other.attribute-name.scss"
478- },
479- {
480- "include": "#flow_control"
481- },
482- {
483- "include": "#interpolation"
484- },
485- {
486- "include": "#property_list"
487- },
488- {
489- "include": "#rules"
490- }
491- ]
492- }
493- ]
494- },
495- "at_rule_media": {
496- "patterns": [
497- {
498- "begin": "^\\s*((@)media\\b)\\s*",
499- "end": "\\s*(?={)",
500- "captures": {
501- "1": {
502- "name": "keyword.control.at-rule.media.scss"
503- },
504- "2": {
505- "name": "punctuation.definition.keyword.scss"
506- }
507- },
508- "name": "meta.at-rule.media.scss",
509- "patterns": [
510- {
511- "match": "\\b(only)\\b",
512- "name": "keyword.control.operator"
513- },
514- {
515- "include": "#media_features"
516- },
517- {
518- "include": "#property_values"
519- },
520- {
521- "include": "#variable"
522- },
523- {
524- "include": "#conditional_operators"
525- },
526- {
527- "include": "#media_types"
528- },
529- {
530- "include": "#property_names"
531- }
532- ]
533- }
534- ]
535- },
536- "at_rule_mixin": {
537- "patterns": [
538- {
539- "begin": "(?<=@mixin)\\s+([\\w-]+)\\s*(\\()",
540- "beginCaptures": {
541- "1": {
542- "name": "entity.name.function.scss"
543- },
544- "2": {
545- "name": "punctuation.definition.parameters.begin.bracket.round.scss"
546- }
547- },
548- "end": "\\)",
549- "endCaptures": {
550- "0": {
551- "name": "punctuation.definition.parameters.end.bracket.round.scss"
552- }
553- },
554- "name": "meta.at-rule.mixin.scss",
555- "patterns": [
556- {
557- "include": "#function_attributes"
558- }
559- ]
560- },
561- {
562- "match": "(?<=@mixin)\\s+([\\w-]+)",
563- "captures": {
564- "1": {
565- "name": "entity.name.function.scss"
566- }
567- },
568- "name": "meta.at-rule.mixin.scss"
569- },
570- {
571- "match": "((@)mixin)\\b",
572- "captures": {
573- "1": {
574- "name": "keyword.control.at-rule.mixin.scss"
575- },
576- "2": {
577- "name": "punctuation.definition.keyword.scss"
578- }
579- },
580- "name": "meta.at-rule.mixin.scss"
581- }
582- ]
583- },
584- "at_rule_namespace": {
585- "patterns": [
586- {
587- "begin": "(?<=@namespace)\\s+(?=url)",
588- "end": "(?=;|$)",
589- "name": "meta.at-rule.namespace.scss",
590- "patterns": [
591- {
592- "include": "#property_values"
593- },
594- {
595- "include": "#string_single"
596- },
597- {
598- "include": "#string_double"
599- }
600- ]
601- },
602- {
603- "begin": "(?<=@namespace)\\s+([\\w-]*)",
604- "captures": {
605- "1": {
606- "name": "entity.name.namespace-prefix.scss"
607- }
608- },
609- "end": "(?=;|$)",
610- "name": "meta.at-rule.namespace.scss",
611- "patterns": [
612- {
613- "include": "#variables"
614- },
615- {
616- "include": "#property_values"
617- },
618- {
619- "include": "#string_single"
620- },
621- {
622- "include": "#string_double"
623- }
624- ]
625- },
626- {
627- "match": "((@)namespace)\\b",
628- "captures": {
629- "1": {
630- "name": "keyword.control.at-rule.namespace.scss"
631- },
632- "2": {
633- "name": "punctuation.definition.keyword.scss"
634- }
635- },
636- "name": "meta.at-rule.namespace.scss"
637- }
638- ]
639- },
640- "at_rule_option": {
641- "captures": {
642- "1": {
643- "name": "keyword.control.at-rule.charset.scss"
644- },
645- "2": {
646- "name": "punctuation.definition.keyword.scss"
647- }
648- },
649- "comment": "Option",
650- "match": "^\\s*((@)option\\b)\\s*",
651- "name": "meta.at-rule.option.scss"
652- },
653- "at_rule_page": {
654- "patterns": [
655- {
656- "begin": "^\\s*((@)page)(?=:|\\s)\\s*([-:\\w]*)",
657- "captures": {
658- "1": {
659- "name": "keyword.control.at-rule.page.scss"
660- },
661- "2": {
662- "name": "punctuation.definition.keyword.scss"
663- },
664- "3": {
665- "name": "entity.name.function.scss"
666- }
667- },
668- "comment": "Page with Attributes",
669- "end": "\\s*(?={)",
670- "name": "meta.at-rule.page.scss"
671- }
672- ]
673- },
674- "at_rule_return": {
675- "begin": "\\s*((@)(return)\\b)",
676- "captures": {
677- "1": {
678- "name": "keyword.control.return.scss"
679- },
680- "2": {
681- "name": "punctuation.definition.keyword.scss"
682- }
683- },
684- "end": "\\s*((?=;))",
685- "name": "meta.at-rule.return.scss",
686- "patterns": [
687- {
688- "include": "#variable"
689- },
690- {
691- "include": "#property_values"
692- }
693- ]
694- },
695- "at_rule_at_root": {
696- "begin": "\\s*((@)(at-root))(\\s+|$)",
697- "end": "\\s*(?={)",
698- "beginCaptures": {
699- "1": {
700- "name": "keyword.control.at-rule.at-root.scss"
701- },
702- "2": {
703- "name": "punctuation.definition.keyword.scss"
704- }
705- },
706- "name": "meta.at-rule.at-root.scss",
707- "patterns": [
708- {
709- "include": "#function_attributes"
710- },
711- {
712- "include": "#functions"
713- },
714- {
715- "include": "#selectors"
716- }
717- ]
718- },
719- "at_rule_supports": {
720- "begin": "(?<=^|\\s)(@)supports\\b",
721- "captures": {
722- "0": {
723- "name": "keyword.control.at-rule.supports.scss"
724- },
725- "1": {
726- "name": "punctuation.definition.keyword.scss"
727- }
728- },
729- "end": "(?={)|$",
730- "name": "meta.at-rule.supports.scss",
731- "patterns": [
732- {
733- "include": "#logical_operators"
734- },
735- {
736- "include": "#properties"
737- },
738- {
739- "match": "\\(",
740- "name": "punctuation.definition.condition.begin.bracket.round.scss"
741- },
742- {
743- "match": "\\)",
744- "name": "punctuation.definition.condition.end.bracket.round.scss"
745- }
746- ]
747- },
748- "at_rule_warn": {
749- "begin": "\\s*((@)(warn|debug|error)\\b)\\s*",
750- "captures": {
751- "1": {
752- "name": "keyword.control.warn.scss"
753- },
754- "2": {
755- "name": "punctuation.definition.keyword.scss"
756- }
757- },
758- "end": "\\s*(?=;)",
759- "name": "meta.at-rule.warn.scss",
760- "patterns": [
761- {
762- "include": "#variable"
763- },
764- {
765- "include": "#string_double"
766- },
767- {
768- "include": "#string_single"
769- }
770- ]
771- },
772- "at_rule_while": {
773- "begin": "\\s*((@)while\\b)\\s*",
774- "captures": {
775- "1": {
776- "name": "keyword.control.while.scss"
777- },
778- "2": {
779- "name": "punctuation.definition.keyword.scss"
780- }
781- },
782- "end": "\\s*(?=})",
783- "name": "meta.at-rule.while.scss",
784- "patterns": [
785- {
786- "include": "#conditional_operators"
787- },
788- {
789- "include": "#variable"
790- },
791- {
792- "include": "#property_values"
793- },
794- {
795- "include": "$self"
796- }
797- ]
798- },
799- "comment_block": {
800- "begin": "/\\*",
801- "beginCaptures": {
802- "0": {
803- "name": "punctuation.definition.comment.scss"
804- }
805- },
806- "end": "\\*/",
807- "endCaptures": {
808- "0": {
809- "name": "punctuation.definition.comment.scss"
810- }
811- },
812- "name": "comment.block.scss"
813- },
814- "comment_line": {
815- "begin": "//",
816- "beginCaptures": {
817- "0": {
818- "name": "punctuation.definition.comment.scss"
819- }
820- },
821- "end": "\\n",
822- "name": "comment.line.scss"
823- },
824- "constant_color": {
825- "comment": "http://www.w3.org/TR/css3-color/#svg-color",
826- "match": "\\b(aliceblue|antiquewhite|aqua|aquamarine|azure|beige|bisque|black|blanchedalmond|blue|blueviolet|brown|burlywood|cadetblue|chartreuse|chocolate|coral|cornflowerblue|cornsilk|crimson|cyan|darkblue|darkcyan|darkgoldenrod|darkgray|darkgreen|darkgrey|darkkhaki|darkmagenta|darkolivegreen|darkorange|darkorchid|darkred|darksalmon|darkseagreen|darkslateblue|darkslategray|darkslategrey|darkturquoise|darkviolet|deeppink|deepskyblue|dimgray|dimgrey|dodgerblue|firebrick|floralwhite|forestgreen|fuchsia|gainsboro|ghostwhite|gold|goldenrod|gray|green|greenyellow|grey|honeydew|hotpink|indianred|indigo|ivory|khaki|lavender|lavenderblush|lawngreen|lemonchiffon|lightblue|lightcoral|lightcyan|lightgoldenrodyellow|lightgray|lightgreen|lightgrey|lightpink|lightsalmon|lightseagreen|lightskyblue|lightslategray|lightslategrey|lightsteelblue|lightyellow|lime|limegreen|linen|magenta|maroon|mediumaquamarine|mediumblue|mediumorchid|mediumpurple|mediumseagreen|mediumslateblue|mediumspringgreen|mediumturquoise|mediumvioletred|midnightblue|mintcream|mistyrose|moccasin|navajowhite|navy|oldlace|olive|olivedrab|orange|orangered|orchid|palegoldenrod|palegreen|paleturquoise|palevioletred|papayawhip|peachpuff|peru|pink|plum|powderblue|purple|red|rosybrown|royalblue|saddlebrown|salmon|sandybrown|seagreen|seashell|sienna|silver|skyblue|slateblue|slategray|slategrey|snow|springgreen|steelblue|tan|teal|thistle|tomato|turquoise|violet|wheat|white|whitesmoke|yellow|yellowgreen)\\b",
827- "name": "support.constant.color.w3c-standard-color-name.scss"
828- },
829- "constant_default": {
830- "match": "!default",
831- "name": "keyword.other.default.scss"
832- },
833- "constant_deprecated_color": {
834- "comment": "These colours are deprecated from CSS color module level 3 http://www.w3.org/TR/css3-color/#css2-system",
835- "match": "\\b(ActiveBorder|ActiveCaption|AppWorkspace|Background|ButtonFace|ButtonHighlight|ButtonShadow|ButtonText|CaptionText|GrayText|Highlight|HighlightText|InactiveBorder|InactiveCaption|InactiveCaptionText|InfoBackground|InfoText|Menu|MenuText|Scrollbar|ThreeDDarkShadow|ThreeDFace|ThreeDHighlight|ThreeDLightShadow|ThreeDShadow|Window|WindowFrame|WindowText)\\b",
836- "name": "invalid.deprecated.color.system.css.scss"
837- },
838- "constant_font": {
839- "match": "(\\b(?i:arial|century|comic|courier|garamond|georgia|helvetica|impact|lucida|symbol|system|tahoma|times|trebuchet|utopia|verdana|webdings|sans-serif|serif|monospace)\\b)",
840- "name": "support.constant.font-name.scss"
841- },
842- "constant_functions": {
843- "begin": "([\\w-]+)(\\()",
844- "beginCaptures": {
845- "1": {
846- "name": "support.function.misc.scss"
847- },
848- "2": {
849- "name": "punctuation.section.function.scss"
850- }
851- },
852- "end": "(\\))",
853- "endCaptures": {
854- "1": {
855- "name": "punctuation.section.function.scss"
856- }
857- },
858- "patterns": [
859- {
860- "include": "#parameters"
861- }
862- ]
863- },
864- "constant_hex": {
865- "captures": {
866- "1": {
867- "name": "punctuation.definition.constant.scss"
868- }
869- },
870- "match": "(#)([0-9a-fA-F]{3}|[0-9a-fA-F]{6})\\b",
871- "name": "constant.numeric.color.hex-value.scss"
872- },
873- "constant_important": {
874- "match": "!important",
875- "name": "keyword.other.important.scss"
876- },
877- "constant_mathematical_symbols": {
878- "match": "\\b(\\+|-|\\*|/)\\b",
879- "name": "support.constant.mathematical-symbols.scss"
880- },
881- "constant_number": {
882- "match": "(\\b([0-9]+(\\.[0-9]+)?)|\\B\\.[0-9]+)(?=\\s*(ch|cm|deg|dpi|dpcm|dppx|em|ex|grad|in|mm|mozmm|ms|pc|pt|px|rad|rem|turn|s|vh|vmin|vmax|vw|\\b))",
883- "name": "constant.numeric.scss"
884- },
885- "constant_optional": {
886- "match": "!optional",
887- "name": "keyword.other.optional.scss"
888- },
889- "constant_property_value": {
890- "match": "\\b(absolute|all-scroll|always|armenian|auto|baseline|below|bidi-override|block|bold|bolder|both|bottom|border-box|break-all|break-word|butt|capitalize|center|char|circle|cjk-ideographic|col-resize|collapse|column-reverse|column|contain|content-box|cover|crosshair|currentColor|dashed|decimal-leading-zero|decimal|default|disabled|disc|distribute-all-lines|distribute-letter|distribute-space|distribute|dotted|double|e-resize|ease-in-out|ease-in|ease-out|ease|ellipsis|fill|fixed|flex-end|flex-start|flex|georgian|grid|groove|hand|hebrew|help|hidden|hiragana-iroha|hiragana|horizontal|ideograph-alpha|ideograph-numeric|ideograph-parenthesis|ideograph-space|inactive|inherit|inline-block|inline-flex|inline-grid|inline-table|inline|inset|inside|inter-ideograph|inter-word|italic|justify|katakana-iroha|katakana|keep-all|landscape|left|lighter|line-edge|line-through|line|linear|list-item|loose|lower-alpha|lower-greek|lower-latin|lower-roman|lowercase|lr-tb|ltr|manipulation|medium|middle|move|n-resize|ne-resize|newspaper|no-drop|no-repeat|nw-resize|none|normal|not-allowed|nowrap|null|oblique|outset|outside|overline|pan-(x|y|left|right|up|down)|pointer|portrait|preserve-3d|progress|relative|repeat-x|repeat-y|repeat|right|ridge|round|row-resize|row-reverse|row|rtl|ruby-base-container|ruby-base|ruby-text-container|ruby-text|ruby|s-resize|scale-down|scroll|se-resize|separate|small-caps|solid|space-around|space-between|square|static|step-end|step-start|stretch|strict|super|sw-resize|table-caption|table-cell|table-column-group|table-column|table-footer-group|table-header-group|table-row-group|table-row|table|tb-rl|text-bottom|text-top|text|thick|thin|top|transparent|underline|upper-alpha|upper-latin|upper-roman|uppercase|vertical-ideographic|vertical-text|visible|w-resize|wait|whitespace|wrap|wrap-reverse|zero|true|false|vertical|horizontal)\\b",
891- "name": "support.constant.property-value.scss"
892- },
893- "constant_rgb": {
894- "match": "(?x)\n(?<!scale3d\\(|translate3d\\(|rotate3d\\() # scale3d, translate3d, and rotate3d don't use RGB values\n\\b\n(0*(?:1?[0-9]{1,2})|(?:2(?:[0-4][0-9]|5[0-5])))\n\\s*(,)\\s*\n(0*(?:1?[0-9]{1,2})|(?:2(?:[0-4][0-9]|5[0-5])))\n\\s*(,)\\s*\n(0*(?:1?[0-9]{1,2})|(?:2(?:[0-4][0-9]|5[0-5])))\n\\b",
895- "captures": {
896- "1": {
897- "name": "constant.numeric.color.rgb-value.scss"
898- },
899- "2": {
900- "name": "punctuation.separator.delimiter.scss"
901- },
902- "3": {
903- "name": "constant.numeric.color.rgb-value.scss"
904- },
905- "4": {
906- "name": "punctuation.separator.delimiter.scss"
907- },
908- "5": {
909- "name": "constant.numeric.color.rgb-value.scss"
910- }
911- }
912- },
913- "constant_rgb_percentage": {
914- "match": "(?x)\n(?<!scale3d\\(|translate3d\\(|rotate3d\\() # scale3d, translate3d, and rotate3d don't use RGB percentages\n\\b\n([0-9]{1,2}|100)\\s*(%)\n\\s*(,)\\s*\n([0-9]{1,2}|100)\\s*(%)\n\\s*(,)\\s*\n([0-9]{1,2}|100)\\s*(%)",
915- "captures": {
916- "1": {
917- "name": "constant.numeric.color.rgb-percentage.scss"
918- },
919- "2": {
920- "name": "keyword.other.unit.scss"
921- },
922- "3": {
923- "name": "punctuation.separator.delimiter.scss"
924- },
925- "4": {
926- "name": "constant.numeric.color.rgb-percentage.scss"
927- },
928- "5": {
929- "name": "keyword.other.unit.scss"
930- },
931- "6": {
932- "name": "punctuation.separator.delimiter.scss"
933- },
934- "7": {
935- "name": "constant.numeric.color.rgb-percentage.scss"
936- },
937- "8": {
938- "name": "keyword.other.unit.scss"
939- }
940- }
941- },
942- "constant_sass_functions": {
943- "begin": "(headings|stylesheet-url|rgba?|hsla?|ie-hex-str|red|green|blue|alpha|opacity|hue|saturation|lightness|prefixed|prefix|-moz|-svg|-css2|-pie|-webkit|-ms|font-(?:files|url)|grid-image|image-(?:width|height|url|color)|sprites?|sprite-(?:map|map-name|file|url|position)|inline-(?:font-files|image)|opposite-position|grad-point|grad-end-position|color-stops|color-stops-in-percentages|grad-color-stops|(?:radial|linear)-(?:gradient|svg-gradient)|opacify|fade-?in|transparentize|fade-?out|lighten|darken|saturate|desaturate|grayscale|adjust-(?:hue|lightness|saturation|color)|scale-(?:lightness|saturation|color)|change-color|spin|complement|invert|mix|-compass-(?:list|space-list|slice|nth|list-size)|blank|compact|nth|first-value-of|join|length|append|nest|append-selector|headers|enumerate|range|percentage|unitless|unit|if|type-of|comparable|elements-of-type|quote|unquote|escape|e|sin|cos|tan|abs|round|ceil|floor|pi|translate(?:X|Y))(\\()",
944- "beginCaptures": {
945- "1": {
946- "name": "support.function.misc.scss"
947- },
948- "2": {
949- "name": "punctuation.section.function.scss"
950- }
951- },
952- "end": "(\\))",
953- "endCaptures": {
954- "1": {
955- "name": "punctuation.section.function.scss"
956- }
957- },
958- "patterns": [
959- {
960- "include": "#parameters"
961- }
962- ]
963- },
964- "constant_unit": {
965- "match": "(?<=[\\d])(ch|cm|deg|dpi|dpcm|dppx|em|ex|grad|in|mm|mozmm|ms|pc|pt|px|rad|rem|turn|s|vh|vmin|vmax|vw)\\b|%",
966- "name": "keyword.other.unit.scss"
967- },
968- "flow_control": {
969- "patterns": [
970- {
971- "include": "#at_rule_if"
972- },
973- {
974- "include": "#at_rule_else"
975- },
976- {
977- "include": "#at_rule_warn"
978- },
979- {
980- "include": "#at_rule_for"
981- },
982- {
983- "include": "#at_rule_while"
984- },
985- {
986- "include": "#at_rule_each"
987- },
988- {
989- "include": "#at_rule_return"
990- }
991- ]
992- },
993- "function_attributes": {
994- "patterns": [
995- {
996- "match": ":",
997- "name": "punctuation.separator.key-value.scss"
998- },
999- {
1000- "include": "#general"
1001- },
1002- {
1003- "include": "#property_values"
1004- },
1005- {
1006- "comment": "We even have error highlighting <3",
1007- "match": "[={}\\?;@]",
1008- "name": "invalid.illegal.scss"
1009- }
1010- ]
1011- },
1012- "functions": {
1013- "patterns": [
1014- {
1015- "begin": "([\\w-]{1,})(\\()\\s*",
1016- "beginCaptures": {
1017- "1": {
1018- "name": "support.function.misc.scss"
1019- },
1020- "2": {
1021- "name": "punctuation.section.function.scss"
1022- }
1023- },
1024- "end": "(\\))",
1025- "endCaptures": {
1026- "1": {
1027- "name": "punctuation.section.function.scss"
1028- }
1029- },
1030- "patterns": [
1031- {
1032- "include": "#parameters"
1033- }
1034- ]
1035- },
1036- {
1037- "match": "([\\w-]{1,})",
1038- "name": "support.function.misc.scss"
1039- }
1040- ]
1041- },
1042- "general": {
1043- "comment": "Stuff that should be everywhere",
1044- "patterns": [
1045- {
1046- "include": "#variable"
1047- },
1048- {
1049- "include": "#comment_block"
1050- },
1051- {
1052- "include": "#comment_line"
1053- }
1054- ]
1055- },
1056- "interpolation": {
1057- "begin": "#{",
1058- "beginCaptures": {
1059- "0": {
1060- "name": "punctuation.definition.interpolation.begin.bracket.curly.scss"
1061- }
1062- },
1063- "end": "}",
1064- "endCaptures": {
1065- "0": {
1066- "name": "punctuation.definition.interpolation.end.bracket.curly.scss"
1067- }
1068- },
1069- "name": "variable.interpolation.scss",
1070- "patterns": [
1071- {
1072- "include": "#property_values"
1073- },
1074- {
1075- "include": "#variable"
1076- }
1077- ]
1078- },
1079- "conditional_operators": {
1080- "patterns": [
1081- {
1082- "include": "#comparison_operators"
1083- },
1084- {
1085- "include": "#logical_operators"
1086- }
1087- ]
1088- },
1089- "comparison_operators": {
1090- "match": "==|!=|<=|>=|<|>",
1091- "name": "keyword.operator.comparison.scss"
1092- },
1093- "logical_operators": {
1094- "match": "\\b(not\\b|or\\b|and\\b)",
1095- "name": "keyword.operator.logical.scss"
1096- },
1097- "map": {
1098- "begin": "\\(",
1099- "beginCaptures": {
1100- "0": {
1101- "name": "punctuation.definition.map.begin.bracket.round.scss"
1102- }
1103- },
1104- "end": "\\)",
1105- "endCaptures": {
1106- "0": {
1107- "name": "punctuation.definition.map.end.bracket.round.scss"
1108- }
1109- },
1110- "name": "meta.set.variable.map.scss",
1111- "patterns": [
1112- {
1113- "include": "#comment_block"
1114- },
1115- {
1116- "include": "#comment_line"
1117- },
1118- {
1119- "match": "\\b([\\w-]+)\\s*(:)",
1120- "captures": {
1121- "1": {
1122- "name": "support.type.map.key.scss"
1123- },
1124- "2": {
1125- "name": "punctuation.separator.key-value.scss"
1126- }
1127- }
1128- },
1129- {
1130- "match": ",",
1131- "name": "punctuation.separator.delimiter.scss"
1132- },
1133- {
1134- "include": "#property_values"
1135- },
1136- {
1137- "include": "#variable"
1138- },
1139- {
1140- "include": "#map"
1141- }
1142- ]
1143- },
1144- "media_attributes": {
1145- "patterns": [
1146- {
1147- "match": ":",
1148- "name": "punctuation.separator.key-value.scss"
1149- },
1150- {
1151- "include": "#general"
1152- },
1153- {
1154- "include": "#property_name"
1155- },
1156- {
1157- "include": "#property_values"
1158- },
1159- {
1160- "comment": "We even have error highlighting <3",
1161- "match": "[={}\\?@]",
1162- "name": "invalid.illegal.scss"
1163- }
1164- ]
1165- },
1166- "media_features": {
1167- "patterns": [
1168- {
1169- "match": "\\b(min-device-aspect-ratio|max-device-aspect-ratio|device-aspect-ratio|min-aspect-ratio|max-aspect-ratio|aspect-ratio|min-device-height|max-device-height|device-height|min-device-width|max-device-width|device-width|min-monochrome|max-monochrome|monochrome|min-color-index|max-color-index|color-index|min-color|max-color|color|orientation|scan|min-resolution|max-resolution|resolution|grid|min-width|max-width|width)\\b",
1170- "name": "support.type.property-name.media.css"
1171- }
1172- ]
1173- },
1174- "media_types": {
1175- "patterns": [
1176- {
1177- "match": "\\b(all|aural|braille|embossed|handheld|print|projection|screen|tty|tv)\\b",
1178- "name": "support.constant.media.css"
1179- }
1180- ]
1181- },
1182- "operators": {
1183- "match": "[-+*/](?!\\s*[-+*/])",
1184- "name": "keyword.operator.css"
1185- },
1186- "parameters": {
1187- "patterns": [
1188- {
1189- "include": "#variable"
1190- },
1191- {
1192- "include": "#property_values"
1193- },
1194- {
1195- "include": "#comment_block"
1196- },
1197- {
1198- "begin": "\\(",
1199- "beginCaptures": {
1200- "0": {
1201- "name": "punctuation.definition.begin.bracket.round.scss"
1202- }
1203- },
1204- "end": "\\)",
1205- "endCaptures": {
1206- "0": {
1207- "name": "punctuation.definition.end.bracket.round.scss"
1208- }
1209- },
1210- "patterns": [
1211- {
1212- "include": "#function_attributes"
1213- }
1214- ]
1215- },
1216- {
1217- "match": "[^'\",) \\t]+",
1218- "name": "variable.parameter.url.scss"
1219- },
1220- {
1221- "match": ",",
1222- "name": "punctuation.separator.delimiter.scss"
1223- }
1224- ]
1225- },
1226- "properties": {
1227- "patterns": [
1228- {
1229- "begin": "(?<![-a-z])(?=[-a-z])",
1230- "end": "$|(?![-a-z])",
1231- "name": "meta.property-name.scss",
1232- "patterns": [
1233- {
1234- "include": "#property_names"
1235- },
1236- {
1237- "include": "#at_rule_include"
1238- }
1239- ]
1240- },
1241- {
1242- "begin": "(:)\\s*(?!(\\s*{))",
1243- "beginCaptures": {
1244- "1": {
1245- "name": "punctuation.separator.key-value.scss"
1246- }
1247- },
1248- "comment": "Kuroir: fixed nested elements for sass.",
1249- "end": "\\s*(;|(?=}|\\)))",
1250- "endCaptures": {
1251- "1": {
1252- "name": "punctuation.terminator.rule.scss"
1253- }
1254- },
1255- "contentName": "meta.property-value.scss",
1256- "patterns": [
1257- {
1258- "include": "#general"
1259- },
1260- {
1261- "include": "#property_values"
1262- }
1263- ]
1264- }
1265- ]
1266- },
1267- "property_list": {
1268- "begin": "{",
1269- "beginCaptures": {
1270- "0": {
1271- "name": "punctuation.section.property-list.begin.bracket.curly.scss"
1272- }
1273- },
1274- "end": "}",
1275- "endCaptures": {
1276- "0": {
1277- "name": "punctuation.section.property-list.end.bracket.curly.scss"
1278- }
1279- },
1280- "name": "meta.property-list.scss",
1281- "patterns": [
1282- {
1283- "include": "#flow_control"
1284- },
1285- {
1286- "include": "#rules"
1287- },
1288- {
1289- "include": "#properties"
1290- },
1291- {
1292- "include": "$self"
1293- }
1294- ]
1295- },
1296- "property_name": {
1297- "comment": "Reversal order is important; KEEP IT. Also when adding new properties add them to the error checker below!",
1298- "match": "((?<=\\s|^)(-webkit-[A-Za-z-]+|-moz-[A-Za-z-]+|-ms-[A-Za-z-]+))|\\b([0-9]{1,3}%|zoom|z-index|y|x|wrap|word-wrap|word-spacing|word-break|word|width|widows|will-change|white-space-collapse|white-space|white|weight|volume|voice-volume|voice-stress|voice-rate|voice-pitch-range|voice-pitch|voice-family|voice-duration|voice-balance|voice|visibility|vertical-align|variant|user-select|up|unicode-bidi|unicode|trim|transition-timing-function|transition-property|transition-duration|transition-delay|transition|transform|touch-action|top-width|top-style|top-right-radius|top-left-radius|top-color|top|timing-function|text-wrap|text-transform|text-shadow|text-replace|text-outline|text-justify|text-indent|text-height|text-emphasis|text-decoration|text-align-last|text-align|text|target-position|target-new|target-name|target|table-layout|tab-size|style-type|style-position|style-image|style|stroke|string-set|stretch|stress|stacking-strategy|stacking-shift|stacking-ruby|stacking|src|speed|speech-rate|speech|speak-punctuation|speak-numeral|speak-header|speak|span|spacing|space-collapse|space|sizing|size-adjust|size|shadow|respond-to|rule-width|rule-style|rule-color|rule|ruby-span|ruby-position|ruby-overhang|ruby-align|ruby|rows|rotation-point|rotation|role|right-width|right-style|right-color|right|richness|rest-before|rest-after|rest|resource|resolution|resize|reset|replace|repeat|rendering-intent|rate|radius|quotes|punctuation-trim|punctuation|property|profile|presentation-level|presentation|position|pointer-events|point|play-state|play-during|play-count|pitch-range|pitch|phonemes|perspective|pause-before|pause-after|pause|page-policy|page-break-inside|page-break-before|page-break-after|page|padding-top|padding-right|padding-left|padding-bottom|padding|pack|overhang|overflow-y|overflow-x|overflow-wrap|overflow-style|overflow|outline-width|outline-style|outline-offset|outline-color|outline|orphans|origin|orientation|orient|ordinal-group|order|opacity|offset|object-position|object-fit|numeral|new|nav-up|nav-right|nav-left|nav-index|nav-down|nav|name|move-to|model|min-width|min-height|min|max-width|max-height|max|marquee-style|marquee-speed|marquee-play-count|marquee-direction|marquee|marks|mark-before|mark-after|marker|mark|margin-top|margin-right|margin-left|margin-bottom|margin|mask-image|list-style-type|list-style-position|list-style-image|list-style|list|lines|line-stacking-strategy|line-stacking-shift|line-stacking-ruby|line-stacking|line-height|line|level|letter-spacing|length|left-width|left-style|left-color|left|label|justify-content|justify|iteration-count|inline-box-align|initial-value|initial-size|initial-before-align|initial-before-adjust|initial-after-align|initial-after-adjust|index|indent|increment|image-resolution|image-orientation|image|icon|hyphens|hyphenate-resource|hyphenate-lines|hyphenate-character|hyphenate-before|hyphenate-after|hyphenate|height|header|hanging-punctuation|grid-rows|grid-columns|grid|gap|font-weight|font-variant|font-variant-ligatures|font-style|font-stretch|font-size-adjust|font-size|font-family|font|float-offset|float|flex-wrap|flex-shrink|flex-grow|flex-group|flex-flow|flex-direction|flex-basis|flex|fit-position|fit|fill|filter|family|empty-cells|emphasis|elevation|duration|drop-initial-value|drop-initial-size|drop-initial-before-align|drop-initial-before-adjust|drop-initial-after-align|drop-initial-after-adjust|drop|down|dominant-baseline|display-role|display-model|display|direction|delay|decoration-break|decoration|cursor|cue-before|cue-after|cue|crop|counter-reset|counter-increment|counter|count|content|columns|column-width|column-span|column-rule-width|column-rule-style|column-rule-color|column-rule|column-gap|column-fill|column-count|column-break-before|column-break-after|column|color-profile|color|collapse|clip|clear|character|caption-side|break-inside|break-before|break-after|break|box-sizing|box-shadow|box-pack|box-orient|box-ordinal-group|box-lines|box-flex-group|box-flex|box-direction|box-decoration-break|box-align|box|bottom-width|bottom-style|bottom-right-radius|bottom-left-radius|bottom-color|bottom|border-width|border-top-width|border-top-style|border-top-right-radius|border-top-left-radius|border-top-color|border-top|border-style|border-spacing|border-right-width|border-right-style|border-right-color|border-right|border-radius|border-length|border-left-width|border-left-style|border-left-color|border-left|border-image|border-color|border-collapse|border-bottom-width|border-bottom-style|border-bottom-right-radius|border-bottom-left-radius|border-bottom-color|border-bottom|border|bookmark-target|bookmark-level|bookmark-label|bookmark|binding|bidi|before|baseline-shift|baseline|balance|background-size|background-repeat|background-position-y|background-position-x|background-position|background-origin|background-image|background-color|background-clip|background-break|background-attachment|background|backface-visibility|azimuth|attachment|appearance|animation-timing-function|animation-play-state|animation-name|animation-iteration-count|animation-fill-mode|animation-duration|animation-direction|animation-delay|animation|alignment-baseline|alignment-adjust|alignment|align-self|align-last|align-items|align-content|align|after|adjust)\\b",
1299- "name": "support.type.property-name.scss"
1300- },
1301- "property_name_error": {
1302- "match": "(?<![a-z-])(?!-(top|right|left|bottom|color|radius|last|inside|width|before|after|value|size|type|position|style|image|strategy|shift|align|adjust)\\b|-webkit-[A-Za-z]+\\b|-moz-[A-Za-z]+\\b|-ms-[A-Za-z]+\\b|z-index\\b|[0-9]{1,3}%\\b|zoom\\b|y\\b|x\\b|wrap\\b|word-wrap\\b|word-spacing\\b|word-break\\b|word\\b|will-change\\b|width\\b|widows\\b|white-space-collapse\\b|white-space\\b|white\\b|weight\\b|volume\\b|voice-volume\\b|voice-stress\\b|voice-rate\\b|voice-pitch-range\\b|voice-pitch\\b|voice-family\\b|voice-duration\\b|voice-balance\\b|voice\\b|visibility\\b|vertical-align\\b|variant\\b|user-select\\b|up\\b|unicode-bidi\\b|unicode\\b|u\\b|tt\\b|trim\\b|transition-timing-function\\b|transition-property\\b|transition-duration\\b|transition-delay\\b|transition\\b|transform\\b|touch-action\\b|top-width\\b|top-style\\b|top-right-radius\\b|top-left-radius\\b|top-color\\b|top\\b|timing-function\\b|text-wrap\\b|text-transform\\b|text-shadow\\b|text-replace\\b|text-outline\\b|text-justify\\b|text-indent\\b|text-height\\b|text-emphasis\\b|text-decoration\\b|text-align-last\\b|text-align\\b|text\\b|target-position\\b|target-new\\b|target-name\\b|target\\b|table-layout\\b|tab-size\\b|style-type\\b|style-position\\b|style-image\\b|style\\b|string-set\\b|stroke\\b|strike\\b|stretch\\b|stress\\b|stacking-strategy\\b|stacking-shift\\b|stacking-ruby\\b|stacking\\b|src\\b|speed\\b|speech-rate\\b|speech\\b|speak-punctuation\\b|speak-numeral\\b|speak-header\\b|speak\\b|span\\b|spacing\\b|space-collapse\\b|space\\b|sizing\\b|size-adjust\\b|size\\b|shadow\\b|s\\b|respond-to\\b|rule-width\\b|rule-style\\b|rule-color\\b|rule\\b|ruby-span\\b|ruby-position\\b|ruby-overhang\\b|ruby-align\\b|ruby\\b|rows\\b|rotation-point\\b|rotation\\b|role\\b|right-width\\b|right-style\\b|right-color\\b|right\\b|richness\\b|rest-before\\b|rest-after\\b|rest\\b|resource\\b|resolution\\b|resize\\b|reset\\b|replace\\b|repeat\\b|rendering-intent\\b|rate\\b|radius\\b|quotes\\b|punctuation-trim\\b|punctuation\\b|property\\b|profile\\b|presentation-level\\b|presentation\\b|position\\b|pointer-events\\b|point\\b|play-state\\b|play-during\\b|play-count\\b|pitch-range\\b|pitch\\b|phonemes\\b|pause-before\\b|pause-after\\b|pause\\b|page-policy\\b|page-break-inside\\b|page-break-before\\b|page-break-after\\b|page\\b|padding-top\\b|padding-right\\b|padding-left\\b|padding-bottom\\b|padding\\b|pack\\b|overhang\\b|overflow-y\\b|overflow-x\\b|overflow-wrap\\b|overflow-style\\b|overflow\\b|outline-width\\b|outline-style\\b|outline-offset\\b|outline-color\\b|outline\\b|orphans\\b|origin\\b|orientation\\b|orient\\b|ordinal-group\\b|order\\b|opacity\\b|offset\\b|object-position\\b|object-fit\\b|numeral\\b|new\\b|nav-up\\b|nav-right\\b|nav-left\\b|nav-index\\b|nav-down\\b|nav\\b|name\\b|move-to\\b|model\\b|min-width\\b|min-height\\b|min\\b|max-width\\b|max-height\\b|max\\b|marquee-style\\b|marquee-speed\\b|marquee-play-count\\b|marquee-direction\\b|marquee\\b|marks\\b|mark-before\\b|mark-after\\b|marker\\b|mark\\b|margin-top\\b|margin-right\\b|margin-left\\b|margin-bottom\\b|margin\\b|mask-image\\b|list-style-type\\b|list-style-position\\b|list-style-image\\b|list-style\\b|list\\b|lines\\b|line-stacking-strategy\\b|line-stacking-shift\\b|line-stacking-ruby\\b|line-stacking\\b|line-height\\b|line\\b|level\\b|letter-spacing\\b|length\\b|left-width\\b|left-style\\b|left-color\\b|left\\b|label\\b|justify-content\\b|justify\\b|iteration-count\\b|inline-box-align\\b|initial-value\\b|initial-size\\b|initial-before-align\\b|initial-before-adjust\\b|initial-after-align\\b|initial-after-adjust\\b|index\\b|indent\\b|increment\\b|image-resolution\\b|image-orientation\\b|image\\b|icon\\b|hyphens\\b|hyphenate-resource\\b|hyphenate-lines\\b|hyphenate-character\\b|hyphenate-before\\b|hyphenate-after\\b|hyphenate\\b|height\\b|header\\b|hanging-punctuation\\b|grid-rows\\b|grid-columns\\b|grid\\b|gap\\b|font-weight\\b|font-variant\\b|font-variant-ligatures\\b|font-style\\b|font-stretch\\b|font-size-adjust\\b|font-size\\b|font-family\\b|font\\b|float-offset\\b|float\\b|flex-wrap\\b|flex-shrink\\b|flex-grow\\b|flex-group\\b|flex-flow\\b|flex-direction\\b|flex-basis\\b|flex\\b|fit-position\\b|fit\\b|fill\\b|filter\\b|family\\b|empty-cells\\b|emphasis\\b|elevation\\b|duration\\b|drop-initial-value\\b|drop-initial-size\\b|drop-initial-before-align\\b|drop-initial-before-adjust\\b|drop-initial-after-align\\b|drop-initial-after-adjust\\b|drop\\b|down\\b|dominant-baseline\\b|display-role\\b|display-model\\b|display\\b|direction\\b|delay\\b|decoration-break\\b|decoration\\b|cursor\\b|cue-before\\b|cue-after\\b|cue\\b|crop\\b|counter-reset\\b|counter-increment\\b|counter\\b|count\\b|content\\b|columns\\b|column-width\\b|column-span\\b|column-rule-width\\b|column-rule-style\\b|column-rule-color\\b|column-rule\\b|column-gap\\b|column-fill\\b|column-count\\b|column-break-before\\b|column-break-after\\b|column\\b|color-profile\\b|color\\b|collapse\\b|clip\\b|clear\\b|character\\b|center\\b|caption-side\\b|break-inside\\b|break-before\\b|break-after\\b|break\\b|box-sizing\\b|box-shadow\\b|box-pack\\b|box-orient\\b|box-ordinal-group\\b|box-lines\\b|box-flex-group\\b|box-flex\\b|box-direction\\b|box-decoration-break\\b|box-align\\b|box\\b|bottom-width\\b|bottom-style\\b|bottom-right-radius\\b|bottom-left-radius\\b|bottom-color\\b|bottom\\b|border-width\\b|border-top-width\\b|border-top-style\\b|border-top-right-radius\\b|border-top-left-radius\\b|border-top-color\\b|border-top\\b|border-style\\b|border-spacing\\b|border-right-width\\b|border-right-style\\b|border-right-color\\b|border-right\\b|border-radius\\b|border-length\\b|border-left-width\\b|border-left-style\\b|border-left-color\\b|border-left\\b|border-image\\b|border-color\\b|border-collapse\\b|border-bottom-width\\b|border-bottom-style\\b|border-bottom-right-radius\\b|border-bottom-left-radius\\b|border-bottom-color\\b|border-bottom\\b|border\\b|bookmark-target\\b|bookmark-level\\b|bookmark-label\\b|bookmark\\b|binding\\b|bidi\\b|big\\b|before\\b|baseline-shift\\b|baseline\\b|balance\\b|background-size\\b|background-repeat\\b|background-position-y\\b|background-position-x\\b|background-position\\b|background-origin\\b|background-image\\b|background-color\\b|background-clip\\b|background-break\\b|background-attachment\\b|background\\b|backface-visibility\\b|azimuth\\b|attachment\\b|applet\\b|appearance\\b|animation-timing-function\\b|animation-play-state\\b|animation-name\\b|animation-iteration-count\\b|animation-fill-mode\\b|animation-duration\\b|animation-direction\\b|animation-delay\\b|animation\\b|alignment-baseline\\b|alignment-adjust\\b|alignment\\b|align-last\\b|align-self\\b|align-items\\b|align-content\\b|align\\b|after\\b|adjust\\b|acronym\\b)[-_a-z]+",
1303- "name": "invalid.illegal.scss"
1304- },
1305- "property_names": {
1306- "patterns": [
1307- {
1308- "include": "#property_name"
1309- },
1310- {
1311- "include": "#property_name_error"
1312- }
1313- ]
1314- },
1315- "property_values": {
1316- "comment": "Stuff that should only be available on values.",
1317- "patterns": [
1318- {
1319- "include": "#string_single"
1320- },
1321- {
1322- "include": "#string_double"
1323- },
1324- {
1325- "include": "#constant_functions"
1326- },
1327- {
1328- "include": "#constant_sass_functions"
1329- },
1330- {
1331- "include": "#constant_hex"
1332- },
1333- {
1334- "include": "#constant_rgb"
1335- },
1336- {
1337- "include": "#constant_rgb_percentage"
1338- },
1339- {
1340- "include": "#constant_important"
1341- },
1342- {
1343- "include": "#constant_default"
1344- },
1345- {
1346- "include": "#constant_optional"
1347- },
1348- {
1349- "include": "#constant_unit"
1350- },
1351- {
1352- "include": "#constant_property_value"
1353- },
1354- {
1355- "include": "#constant_number"
1356- },
1357- {
1358- "include": "#constant_font"
1359- },
1360- {
1361- "include": "#constant_color"
1362- },
1363- {
1364- "include": "#constant_deprecated_color"
1365- },
1366- {
1367- "include": "#property_name"
1368- },
1369- {
1370- "include": "#constant_mathematical_symbols"
1371- },
1372- {
1373- "include": "#operators"
1374- }
1375- ]
1376- },
1377- "rules": {
1378- "patterns": [
1379- {
1380- "include": "#general"
1381- },
1382- {
1383- "include": "#at_rule_extend"
1384- },
1385- {
1386- "include": "#at_rule_content"
1387- },
1388- {
1389- "include": "#at_rule_include"
1390- },
1391- {
1392- "include": "#at_rule_media"
1393- },
1394- {
1395- "include": "#selectors"
1396- }
1397- ]
1398- },
1399- "selector_attribute": {
1400- "captures": {
1401- "1": {
1402- "name": "punctuation.definition.attribute-selector.begin.bracket.square.scss"
1403- },
1404- "2": {
1405- "name": "entity.other.attribute-name.attribute.scss"
1406- },
1407- "3": {
1408- "name": "punctuation.separator.operator.scss"
1409- },
1410- "4": {
1411- "name": "string.unquoted.attribute-value.scss"
1412- },
1413- "5": {
1414- "name": "string.quoted.double.attribute-value.scss"
1415- },
1416- "6": {
1417- "name": "punctuation.definition.string.begin.scss"
1418- },
1419- "7": {
1420- "name": "punctuation.definition.string.end.scss"
1421- },
1422- "8": {
1423- "name": "punctuation.definition.attribute-selector.end.bracket.square.scss"
1424- }
1425- },
1426- "match": "(?i)(\\[)\\s*(-?[_a-z\\\\[[:^ascii:]]][-_a-z0-9\\\\[[:^ascii:]]]*)(?:\\s*([~|^$*]?=)\\s*(?:(-?[_a-z\\\\[[:^ascii:]]][-_a-z0-9\\\\[[:^ascii:]]]*)|((?>(['\"])(?:[^\\\\]|\\\\.)*?(\\6)))))?\\s*(])",
1427- "name": "meta.attribute-selector.scss"
1428- },
1429- "selector_class": {
1430- "begin": "(\\.)(?=[\\w-]|#{)",
1431- "beginCaptures": {
1432- "1": {
1433- "name": "punctuation.definition.entity.css"
1434- }
1435- },
1436- "end": "(?![\\w-]|(#{))",
1437- "name": "entity.other.attribute-name.class.css",
1438- "patterns": [
1439- {
1440- "include": "#interpolation"
1441- }
1442- ]
1443- },
1444- "selector_entities": {
1445- "match": "\\b(a|abbr|acronym|address|area|article|aside|audio|b|base|bdi|bdo|big|blockquote|body|br|button|canvas|caption|circle|cite|code|col|colgroup|data|datalist|dd|del|details|dfn|dialog|div|dl|dt|ellipse|em|embed|eventsource|fieldset|figure|figcaption|footer|form|frame|frameset|g|(h[1-6])|head|header|hgroup|hr|html|i|iframe|img|image|input|ins|kbd|keygen|label|legend|li|line(?!-)|link|main|map|mark|menu|menuitem|meta|meter|nav|noframes|noscript|object(?!-)|ol|optgroup|option|output|p|param|path|picture|polygon|polyline|pre|progress|q|rb|rect|rp|rt|rtc|ruby|s|samp|script|section|select|small|source|span|strike|strong|style|sub|summary|sup|svg|table(?!-)|tbody|td|template|text(?!-)|textarea|textpath|tfoot|th|thead|time|title|tr|track|tspan|tt|u|ul|var|video|wbr)\\b",
1446- "name": "entity.name.tag.scss"
1447- },
1448- "selector_custom": {
1449- "match": "\\b([a-zA-Z0-9]+(-[a-zA-Z0-9]+)+)(?=\\.|\\s++[^:]|\\s*[,{]|:(link|visited|hover|active|focus|target|lang|disabled|enabled|checked|indeterminate|root|nth-(child|last-child|of-type|last-of-type)|first-child|last-child|first-of-type|last-of-type|only-child|only-of-type|empty|not|valid|invalid)(\\([0-9A-Za-z]*\\))?)",
1450- "name": "entity.name.tag.custom.scss"
1451- },
1452- "selector_id": {
1453- "captures": {
1454- "1": {
1455- "name": "punctuation.definition.entity.css"
1456- }
1457- },
1458- "match": "(#)[a-zA-Z][a-zA-Z0-9_-]*",
1459- "name": "entity.other.attribute-name.id.css"
1460- },
1461- "selector_placeholder": {
1462- "captures": {
1463- "1": {
1464- "name": "punctuation.definition.entity.scss"
1465- }
1466- },
1467- "match": "(%)[a-zA-Z0-9_-]+",
1468- "name": "entity.other.attribute-name.placeholder.scss"
1469- },
1470- "parent_selector_suffix": {
1471- "match": "(?<=&)[a-zA-Z0-9_-]+",
1472- "name": "entity.other.attribute-name.parent-selector-suffix.scss"
1473- },
1474- "selector_pseudo_class": {
1475- "patterns": [
1476- {
1477- "begin": "((:)\\bnth-(?:child|last-child|of-type|last-of-type))(\\()",
1478- "beginCaptures": {
1479- "1": {
1480- "name": "entity.other.attribute-name.pseudo-class.css"
1481- },
1482- "2": {
1483- "name": "punctuation.definition.entity.css"
1484- },
1485- "3": {
1486- "name": "punctuation.definition.pseudo-class.begin.bracket.round.css"
1487- }
1488- },
1489- "end": "\\)",
1490- "endCaptures": {
1491- "0": {
1492- "name": "punctuation.definition.pseudo-class.end.bracket.round.css"
1493- }
1494- },
1495- "patterns": [
1496- {
1497- "match": "\\d+",
1498- "name": "constant.numeric.scss"
1499- },
1500- {
1501- "match": "(?<=\\d)n\\b|\\b(n|even|odd)\\b",
1502- "name": "constant.other.scss"
1503- },
1504- {
1505- "match": "\\w+",
1506- "name": "invalid.illegal.scss"
1507- }
1508- ]
1509- },
1510- {
1511- "match": "(?x)\n(:)\\b\n(link|visited|hover|active|focus|target|lang|disabled|enabled|checked|\nindeterminate|root|first-child|last-child|first-of-type|last-of-type|\nonly-child|only-of-type|empty|not|valid|invalid)\\b",
1512- "captures": {
1513- "0": {
1514- "name": "entity.other.attribute-name.pseudo-class.css"
1515- },
1516- "1": {
1517- "name": "punctuation.definition.entity.css"
1518- }
1519- }
1520- }
1521- ]
1522- },
1523- "selector_pseudo_element": {
1524- "captures": {
1525- "1": {
1526- "name": "punctuation.definition.entity.css"
1527- }
1528- },
1529- "match": "(:+)((-(moz|webkit|ms)-)?(after|before|first-letter|first-line|selection))\\b",
1530- "name": "entity.other.attribute-name.pseudo-element.css"
1531- },
1532- "selectors": {
1533- "comment": "Stuff for Selectors.",
1534- "patterns": [
1535- {
1536- "include": "#selector_entities"
1537- },
1538- {
1539- "include": "#selector_custom"
1540- },
1541- {
1542- "include": "#selector_class"
1543- },
1544- {
1545- "include": "#selector_id"
1546- },
1547- {
1548- "include": "#selector_pseudo_class"
1549- },
1550- {
1551- "include": "#tag_wildcard"
1552- },
1553- {
1554- "include": "#tag_parent_reference"
1555- },
1556- {
1557- "include": "#selector_pseudo_element"
1558- },
1559- {
1560- "include": "#selector_attribute"
1561- },
1562- {
1563- "include": "#selector_placeholder"
1564- },
1565- {
1566- "include": "#parent_selector_suffix"
1567- }
1568- ]
1569- },
1570- "string_double": {
1571- "begin": "\"",
1572- "beginCaptures": {
1573- "0": {
1574- "name": "punctuation.definition.string.begin.scss"
1575- }
1576- },
1577- "end": "\"",
1578- "endCaptures": {
1579- "0": {
1580- "name": "punctuation.definition.string.end.scss"
1581- }
1582- },
1583- "name": "string.quoted.double.scss",
1584- "patterns": [
1585- {
1586- "match": "\\\\(\\h{1,6}|.)",
1587- "name": "constant.character.escape.scss"
1588- },
1589- {
1590- "include": "#interpolation"
1591- }
1592- ]
1593- },
1594- "string_single": {
1595- "begin": "'",
1596- "beginCaptures": {
1597- "0": {
1598- "name": "punctuation.definition.string.begin.scss"
1599- }
1600- },
1601- "end": "'",
1602- "endCaptures": {
1603- "0": {
1604- "name": "punctuation.definition.string.end.scss"
1605- }
1606- },
1607- "name": "string.quoted.single.scss",
1608- "patterns": [
1609- {
1610- "match": "\\\\(\\h{1,6}|.)",
1611- "name": "constant.character.escape.scss"
1612- },
1613- {
1614- "include": "#interpolation"
1615- }
1616- ]
1617- },
1618- "tag_parent_reference": {
1619- "match": "&",
1620- "name": "entity.name.tag.reference.scss"
1621- },
1622- "tag_wildcard": {
1623- "match": "\\*",
1624- "name": "entity.name.tag.wildcard.scss"
1625- },
1626- "variable": {
1627- "patterns": [
1628- {
1629- "include": "#variables"
1630- },
1631- {
1632- "include": "#interpolation"
1633- }
1634- ]
1635- },
1636- "variable_setting": {
1637- "begin": "\\s*(\\$[A-Za-z0-9_-]+\\b)\\s*(:)\\s*",
1638- "captures": {
1639- "1": {
1640- "name": "variable.scss"
1641- },
1642- "2": {
1643- "name": "punctuation.separator.key-value.scss"
1644- }
1645- },
1646- "end": "\\s*(?=;)",
1647- "name": "meta.set.variable.scss",
1648- "patterns": [
1649- {
1650- "include": "#comment_block"
1651- },
1652- {
1653- "include": "#comment_line"
1654- },
1655- {
1656- "include": "#map"
1657- },
1658- {
1659- "include": "#property_values"
1660- },
1661- {
1662- "include": "#variable"
1663- }
1664- ]
1665- },
1666- "variables": {
1667- "match": "\\$[A-Za-z0-9_-]+\\b",
1668- "name": "variable.scss"
1669- }
1670- },
1671- "version": "https://github.com/atom/language-sass/commit/b0417d1412a9169562f637133099fe2bb841a735"
1672-}
No newline at the end of the file
2+ "scopeName": "source.css.scss",
3+ "name": "SCSS",
4+ "fileTypes": ["scss", "css.scss", "css.scss.erb", "scss.erb"],
5+ "patterns": [
6+ {
7+ "include": "#variable_setting"
8+ },
9+ {
10+ "include": "#at_rule_include"
11+ },
12+ {
13+ "include": "#at_rule_import"
14+ },
15+ {
16+ "include": "#general"
17+ },
18+ {
19+ "include": "#flow_control"
20+ },
21+ {
22+ "include": "#rules"
23+ },
24+ {
25+ "include": "#property_list"
26+ },
27+ {
28+ "include": "#at_rule_mixin"
29+ },
30+ {
31+ "include": "#at_rule_media"
32+ },
33+ {
34+ "include": "#at_rule_function"
35+ },
36+ {
37+ "include": "#at_rule_charset"
38+ },
39+ {
40+ "include": "#at_rule_option"
41+ },
42+ {
43+ "include": "#at_rule_namespace"
44+ },
45+ {
46+ "include": "#at_rule_fontface"
47+ },
48+ {
49+ "include": "#at_rule_page"
50+ },
51+ {
52+ "include": "#at_rule_keyframes"
53+ },
54+ {
55+ "include": "#at_rule_at_root"
56+ },
57+ {
58+ "include": "#at_rule_supports"
59+ }
60+ ],
61+ "repository": {
62+ "at_rule__": {
63+ "comment": "Note how all @rules are prefixed."
64+ },
65+ "at_rule_charset": {
66+ "begin": "\\s*((@)charset\\b)\\s*",
67+ "captures": {
68+ "1": {
69+ "name": "keyword.control.at-rule.charset.scss"
70+ },
71+ "2": {
72+ "name": "punctuation.definition.keyword.scss"
73+ }
74+ },
75+ "comment": "Charset",
76+ "end": "\\s*((?=;|$))",
77+ "name": "meta.at-rule.charset.scss",
78+ "patterns": [
79+ {
80+ "include": "#variable"
81+ },
82+ {
83+ "include": "#string_single"
84+ },
85+ {
86+ "include": "#string_double"
87+ }
88+ ]
89+ },
90+ "at_rule_content": {
91+ "begin": "\\s*((@)content\\b)\\s*",
92+ "captures": {
93+ "1": {
94+ "name": "keyword.control.content.scss"
95+ }
96+ },
97+ "end": "\\s*((?=;))",
98+ "name": "meta.content.scss",
99+ "patterns": [
100+ {
101+ "include": "#variable"
102+ },
103+ {
104+ "include": "#selectors"
105+ },
106+ {
107+ "include": "#property_values"
108+ }
109+ ]
110+ },
111+ "at_rule_each": {
112+ "begin": "\\s*((@)each\\b)\\s*",
113+ "captures": {
114+ "1": {
115+ "name": "keyword.control.each.scss"
116+ },
117+ "2": {
118+ "name": "punctuation.definition.keyword.scss"
119+ }
120+ },
121+ "end": "\\s*((?=}))",
122+ "name": "meta.at-rule.each.scss",
123+ "patterns": [
124+ {
125+ "match": "\\b(in|,)\\b",
126+ "name": "keyword.control.operator"
127+ },
128+ {
129+ "include": "#variable"
130+ },
131+ {
132+ "include": "#property_values"
133+ },
134+ {
135+ "include": "$self"
136+ }
137+ ]
138+ },
139+ "at_rule_else": {
140+ "begin": "\\s*((@)else(\\s*(if)?))\\s*",
141+ "captures": {
142+ "1": {
143+ "name": "keyword.control.else.scss"
144+ },
145+ "2": {
146+ "name": "punctuation.definition.keyword.scss"
147+ }
148+ },
149+ "end": "\\s*(?={)",
150+ "name": "meta.at-rule.else.scss",
151+ "patterns": [
152+ {
153+ "include": "#conditional_operators"
154+ },
155+ {
156+ "include": "#variable"
157+ },
158+ {
159+ "include": "#property_values"
160+ }
161+ ]
162+ },
163+ "at_rule_extend": {
164+ "begin": "\\s*((@)extend\\b)\\s*",
165+ "captures": {
166+ "1": {
167+ "name": "keyword.control.at-rule.import.scss"
168+ },
169+ "2": {
170+ "name": "punctuation.definition.keyword.scss"
171+ }
172+ },
173+ "end": "\\s*(?=;)",
174+ "name": "meta.at-rule.import.scss",
175+ "patterns": [
176+ {
177+ "include": "#variable"
178+ },
179+ {
180+ "include": "#selectors"
181+ },
182+ {
183+ "include": "#property_values"
184+ }
185+ ]
186+ },
187+ "at_rule_fontface": {
188+ "patterns": [
189+ {
190+ "begin": "^\\s*((@)font-face\\b)",
191+ "beginCaptures": {
192+ "1": {
193+ "name": "keyword.control.at-rule.fontface.scss"
194+ },
195+ "2": {
196+ "name": "punctuation.definition.keyword.scss"
197+ }
198+ },
199+ "end": "\\s*(?={)",
200+ "name": "meta.at-rule.fontface.scss",
201+ "patterns": [
202+ {
203+ "include": "#function_attributes"
204+ }
205+ ]
206+ }
207+ ]
208+ },
209+ "at_rule_for": {
210+ "begin": "\\s*((@)for\\b)\\s*",
211+ "captures": {
212+ "1": {
213+ "name": "keyword.control.for.scss"
214+ },
215+ "2": {
216+ "name": "punctuation.definition.keyword.scss"
217+ }
218+ },
219+ "end": "\\s*(?={)",
220+ "name": "meta.at-rule.for.scss",
221+ "patterns": [
222+ {
223+ "match": "(==|!=|<=|>=|<|>|from|to|through)",
224+ "name": "keyword.control.operator"
225+ },
226+ {
227+ "include": "#variable"
228+ },
229+ {
230+ "include": "#property_values"
231+ },
232+ {
233+ "include": "$self"
234+ }
235+ ]
236+ },
237+ "at_rule_function": {
238+ "patterns": [
239+ {
240+ "begin": "\\s*((@)function\\b)\\s*",
241+ "captures": {
242+ "1": {
243+ "name": "keyword.control.at-rule.function.scss"
244+ },
245+ "2": {
246+ "name": "punctuation.definition.keyword.scss"
247+ },
248+ "3": {
249+ "name": "entity.name.function.scss"
250+ }
251+ },
252+ "comment": "Function with Attributes",
253+ "end": "\\s*(?={)",
254+ "name": "meta.at-rule.function.scss",
255+ "patterns": [
256+ {
257+ "include": "#function_attributes"
258+ }
259+ ]
260+ },
261+ {
262+ "captures": {
263+ "1": {
264+ "name": "keyword.control.at-rule.function.scss"
265+ },
266+ "2": {
267+ "name": "punctuation.definition.keyword.scss"
268+ },
269+ "3": {
270+ "name": "entity.name.function.scss"
271+ }
272+ },
273+ "comment": "Simple Function",
274+ "match": "\\s*((@)function\\b)\\s*",
275+ "name": "meta.at-rule.function.scss"
276+ }
277+ ]
278+ },
279+ "at_rule_if": {
280+ "begin": "\\s*((@)if\\b)\\s*",
281+ "captures": {
282+ "1": {
283+ "name": "keyword.control.if.scss"
284+ },
285+ "2": {
286+ "name": "punctuation.definition.keyword.scss"
287+ }
288+ },
289+ "end": "\\s*(?={)",
290+ "name": "meta.at-rule.if.scss",
291+ "patterns": [
292+ {
293+ "include": "#conditional_operators"
294+ },
295+ {
296+ "include": "#variable"
297+ },
298+ {
299+ "include": "#property_values"
300+ }
301+ ]
302+ },
303+ "at_rule_import": {
304+ "begin": "\\s*((@)import\\b)\\s*",
305+ "captures": {
306+ "1": {
307+ "name": "keyword.control.at-rule.import.scss"
308+ },
309+ "2": {
310+ "name": "punctuation.definition.keyword.scss"
311+ }
312+ },
313+ "end": "\\s*((?=;)|(?=}))",
314+ "name": "meta.at-rule.import.scss",
315+ "patterns": [
316+ {
317+ "include": "#variable"
318+ },
319+ {
320+ "include": "#string_single"
321+ },
322+ {
323+ "include": "#string_double"
324+ },
325+ {
326+ "include": "#functions"
327+ },
328+ {
329+ "include": "#comment_line"
330+ }
331+ ]
332+ },
333+ "at_rule_include": {
334+ "patterns": [
335+ {
336+ "begin": "(?<=@include)\\s+([\\w-]+)\\s*(\\()",
337+ "beginCaptures": {
338+ "1": {
339+ "name": "entity.name.function.scss"
340+ },
341+ "2": {
342+ "name": "punctuation.definition.parameters.begin.bracket.round.scss"
343+ }
344+ },
345+ "end": "\\)",
346+ "endCaptures": {
347+ "0": {
348+ "name": "punctuation.definition.parameters.end.bracket.round.scss"
349+ }
350+ },
351+ "name": "meta.at-rule.include.scss",
352+ "patterns": [
353+ {
354+ "include": "#function_attributes"
355+ }
356+ ]
357+ },
358+ {
359+ "match": "(?<=@include)\\s+([\\w-]+)",
360+ "captures": {
361+ "0": {
362+ "name": "meta.at-rule.include.scss"
363+ },
364+ "1": {
365+ "name": "entity.name.function.scss"
366+ }
367+ }
368+ },
369+ {
370+ "match": "((@)include)\\b",
371+ "captures": {
372+ "0": {
373+ "name": "meta.at-rule.include.scss"
374+ },
375+ "1": {
376+ "name": "keyword.control.at-rule.include.scss"
377+ },
378+ "2": {
379+ "name": "punctuation.definition.keyword.scss"
380+ }
381+ }
382+ }
383+ ]
384+ },
385+ "at_rule_keyframes": {
386+ "begin": "(?<=^|\\s)(@)(?:-(?:webkit|moz)-)?keyframes\\b",
387+ "beginCaptures": {
388+ "0": {
389+ "name": "keyword.control.at-rule.keyframes.scss"
390+ },
391+ "1": {
392+ "name": "punctuation.definition.keyword.scss"
393+ }
394+ },
395+ "end": "(?<=})",
396+ "name": "meta.at-rule.keyframes.scss",
397+ "patterns": [
398+ {
399+ "match": "(?<=@keyframes)\\s+((?:[_A-Za-z][-\\w]|-[_A-Za-z])[-\\w]*)",
400+ "captures": {
401+ "1": {
402+ "name": "entity.name.function.scss"
403+ }
404+ }
405+ },
406+ {
407+ "begin": "(?<=@keyframes)\\s+(\")",
408+ "beginCaptures": {
409+ "1": {
410+ "name": "punctuation.definition.string.begin.scss"
411+ }
412+ },
413+ "end": "\"",
414+ "endCaptures": {
415+ "0": {
416+ "name": "punctuation.definition.string.end.scss"
417+ }
418+ },
419+ "name": "string.quoted.double.scss",
420+ "contentName": "entity.name.function.scss",
421+ "patterns": [
422+ {
423+ "match": "\\\\(\\h{1,6}|.)",
424+ "name": "constant.character.escape.scss"
425+ },
426+ {
427+ "include": "#interpolation"
428+ }
429+ ]
430+ },
431+ {
432+ "begin": "(?<=@keyframes)\\s+(')",
433+ "beginCaptures": {
434+ "1": {
435+ "name": "punctuation.definition.string.begin.scss"
436+ }
437+ },
438+ "end": "'",
439+ "endCaptures": {
440+ "0": {
441+ "name": "punctuation.definition.string.end.scss"
442+ }
443+ },
444+ "name": "string.quoted.single.scss",
445+ "contentName": "entity.name.function.scss",
446+ "patterns": [
447+ {
448+ "match": "\\\\(\\h{1,6}|.)",
449+ "name": "constant.character.escape.scss"
450+ },
451+ {
452+ "include": "#interpolation"
453+ }
454+ ]
455+ },
456+ {
457+ "begin": "{",
458+ "beginCaptures": {
459+ "0": {
460+ "name": "punctuation.section.keyframes.begin.scss"
461+ }
462+ },
463+ "end": "}",
464+ "endCaptures": {
465+ "0": {
466+ "name": "punctuation.section.keyframes.end.scss"
467+ }
468+ },
469+ "patterns": [
470+ {
471+ "match": "\\b(?:(?:100|[1-9]\\d|\\d)%|from|to)(?=\\s*{)",
472+ "name": "entity.other.attribute-name.scss"
473+ },
474+ {
475+ "include": "#flow_control"
476+ },
477+ {
478+ "include": "#interpolation"
479+ },
480+ {
481+ "include": "#property_list"
482+ },
483+ {
484+ "include": "#rules"
485+ }
486+ ]
487+ }
488+ ]
489+ },
490+ "at_rule_media": {
491+ "patterns": [
492+ {
493+ "begin": "^\\s*((@)media\\b)\\s*",
494+ "end": "\\s*(?={)",
495+ "captures": {
496+ "1": {
497+ "name": "keyword.control.at-rule.media.scss"
498+ },
499+ "2": {
500+ "name": "punctuation.definition.keyword.scss"
501+ }
502+ },
503+ "name": "meta.at-rule.media.scss",
504+ "patterns": [
505+ {
506+ "match": "\\b(only)\\b",
507+ "name": "keyword.control.operator"
508+ },
509+ {
510+ "include": "#media_features"
511+ },
512+ {
513+ "include": "#property_values"
514+ },
515+ {
516+ "include": "#variable"
517+ },
518+ {
519+ "include": "#conditional_operators"
520+ },
521+ {
522+ "include": "#media_types"
523+ },
524+ {
525+ "include": "#property_names"
526+ }
527+ ]
528+ }
529+ ]
530+ },
531+ "at_rule_mixin": {
532+ "patterns": [
533+ {
534+ "begin": "(?<=@mixin)\\s+([\\w-]+)\\s*(\\()",
535+ "beginCaptures": {
536+ "1": {
537+ "name": "entity.name.function.scss"
538+ },
539+ "2": {
540+ "name": "punctuation.definition.parameters.begin.bracket.round.scss"
541+ }
542+ },
543+ "end": "\\)",
544+ "endCaptures": {
545+ "0": {
546+ "name": "punctuation.definition.parameters.end.bracket.round.scss"
547+ }
548+ },
549+ "name": "meta.at-rule.mixin.scss",
550+ "patterns": [
551+ {
552+ "include": "#function_attributes"
553+ }
554+ ]
555+ },
556+ {
557+ "match": "(?<=@mixin)\\s+([\\w-]+)",
558+ "captures": {
559+ "1": {
560+ "name": "entity.name.function.scss"
561+ }
562+ },
563+ "name": "meta.at-rule.mixin.scss"
564+ },
565+ {
566+ "match": "((@)mixin)\\b",
567+ "captures": {
568+ "1": {
569+ "name": "keyword.control.at-rule.mixin.scss"
570+ },
571+ "2": {
572+ "name": "punctuation.definition.keyword.scss"
573+ }
574+ },
575+ "name": "meta.at-rule.mixin.scss"
576+ }
577+ ]
578+ },
579+ "at_rule_namespace": {
580+ "patterns": [
581+ {
582+ "begin": "(?<=@namespace)\\s+(?=url)",
583+ "end": "(?=;|$)",
584+ "name": "meta.at-rule.namespace.scss",
585+ "patterns": [
586+ {
587+ "include": "#property_values"
588+ },
589+ {
590+ "include": "#string_single"
591+ },
592+ {
593+ "include": "#string_double"
594+ }
595+ ]
596+ },
597+ {
598+ "begin": "(?<=@namespace)\\s+([\\w-]*)",
599+ "captures": {
600+ "1": {
601+ "name": "entity.name.namespace-prefix.scss"
602+ }
603+ },
604+ "end": "(?=;|$)",
605+ "name": "meta.at-rule.namespace.scss",
606+ "patterns": [
607+ {
608+ "include": "#variables"
609+ },
610+ {
611+ "include": "#property_values"
612+ },
613+ {
614+ "include": "#string_single"
615+ },
616+ {
617+ "include": "#string_double"
618+ }
619+ ]
620+ },
621+ {
622+ "match": "((@)namespace)\\b",
623+ "captures": {
624+ "1": {
625+ "name": "keyword.control.at-rule.namespace.scss"
626+ },
627+ "2": {
628+ "name": "punctuation.definition.keyword.scss"
629+ }
630+ },
631+ "name": "meta.at-rule.namespace.scss"
632+ }
633+ ]
634+ },
635+ "at_rule_option": {
636+ "captures": {
637+ "1": {
638+ "name": "keyword.control.at-rule.charset.scss"
639+ },
640+ "2": {
641+ "name": "punctuation.definition.keyword.scss"
642+ }
643+ },
644+ "comment": "Option",
645+ "match": "^\\s*((@)option\\b)\\s*",
646+ "name": "meta.at-rule.option.scss"
647+ },
648+ "at_rule_page": {
649+ "patterns": [
650+ {
651+ "begin": "^\\s*((@)page)(?=:|\\s)\\s*([-:\\w]*)",
652+ "captures": {
653+ "1": {
654+ "name": "keyword.control.at-rule.page.scss"
655+ },
656+ "2": {
657+ "name": "punctuation.definition.keyword.scss"
658+ },
659+ "3": {
660+ "name": "entity.name.function.scss"
661+ }
662+ },
663+ "comment": "Page with Attributes",
664+ "end": "\\s*(?={)",
665+ "name": "meta.at-rule.page.scss"
666+ }
667+ ]
668+ },
669+ "at_rule_return": {
670+ "begin": "\\s*((@)(return)\\b)",
671+ "captures": {
672+ "1": {
673+ "name": "keyword.control.return.scss"
674+ },
675+ "2": {
676+ "name": "punctuation.definition.keyword.scss"
677+ }
678+ },
679+ "end": "\\s*((?=;))",
680+ "name": "meta.at-rule.return.scss",
681+ "patterns": [
682+ {
683+ "include": "#variable"
684+ },
685+ {
686+ "include": "#property_values"
687+ }
688+ ]
689+ },
690+ "at_rule_at_root": {
691+ "begin": "\\s*((@)(at-root))(\\s+|$)",
692+ "end": "\\s*(?={)",
693+ "beginCaptures": {
694+ "1": {
695+ "name": "keyword.control.at-rule.at-root.scss"
696+ },
697+ "2": {
698+ "name": "punctuation.definition.keyword.scss"
699+ }
700+ },
701+ "name": "meta.at-rule.at-root.scss",
702+ "patterns": [
703+ {
704+ "include": "#function_attributes"
705+ },
706+ {
707+ "include": "#functions"
708+ },
709+ {
710+ "include": "#selectors"
711+ }
712+ ]
713+ },
714+ "at_rule_supports": {
715+ "begin": "(?<=^|\\s)(@)supports\\b",
716+ "captures": {
717+ "0": {
718+ "name": "keyword.control.at-rule.supports.scss"
719+ },
720+ "1": {
721+ "name": "punctuation.definition.keyword.scss"
722+ }
723+ },
724+ "end": "(?={)|$",
725+ "name": "meta.at-rule.supports.scss",
726+ "patterns": [
727+ {
728+ "include": "#logical_operators"
729+ },
730+ {
731+ "include": "#properties"
732+ },
733+ {
734+ "match": "\\(",
735+ "name": "punctuation.definition.condition.begin.bracket.round.scss"
736+ },
737+ {
738+ "match": "\\)",
739+ "name": "punctuation.definition.condition.end.bracket.round.scss"
740+ }
741+ ]
742+ },
743+ "at_rule_warn": {
744+ "begin": "\\s*((@)(warn|debug|error)\\b)\\s*",
745+ "captures": {
746+ "1": {
747+ "name": "keyword.control.warn.scss"
748+ },
749+ "2": {
750+ "name": "punctuation.definition.keyword.scss"
751+ }
752+ },
753+ "end": "\\s*(?=;)",
754+ "name": "meta.at-rule.warn.scss",
755+ "patterns": [
756+ {
757+ "include": "#variable"
758+ },
759+ {
760+ "include": "#string_double"
761+ },
762+ {
763+ "include": "#string_single"
764+ }
765+ ]
766+ },
767+ "at_rule_while": {
768+ "begin": "\\s*((@)while\\b)\\s*",
769+ "captures": {
770+ "1": {
771+ "name": "keyword.control.while.scss"
772+ },
773+ "2": {
774+ "name": "punctuation.definition.keyword.scss"
775+ }
776+ },
777+ "end": "\\s*(?=})",
778+ "name": "meta.at-rule.while.scss",
779+ "patterns": [
780+ {
781+ "include": "#conditional_operators"
782+ },
783+ {
784+ "include": "#variable"
785+ },
786+ {
787+ "include": "#property_values"
788+ },
789+ {
790+ "include": "$self"
791+ }
792+ ]
793+ },
794+ "comment_block": {
795+ "begin": "/\\*",
796+ "beginCaptures": {
797+ "0": {
798+ "name": "punctuation.definition.comment.scss"
799+ }
800+ },
801+ "end": "\\*/",
802+ "endCaptures": {
803+ "0": {
804+ "name": "punctuation.definition.comment.scss"
805+ }
806+ },
807+ "name": "comment.block.scss"
808+ },
809+ "comment_line": {
810+ "begin": "//",
811+ "beginCaptures": {
812+ "0": {
813+ "name": "punctuation.definition.comment.scss"
814+ }
815+ },
816+ "end": "\\n",
817+ "name": "comment.line.scss"
818+ },
819+ "constant_color": {
820+ "comment": "http://www.w3.org/TR/css3-color/#svg-color",
821+ "match": "\\b(aliceblue|antiquewhite|aqua|aquamarine|azure|beige|bisque|black|blanchedalmond|blue|blueviolet|brown|burlywood|cadetblue|chartreuse|chocolate|coral|cornflowerblue|cornsilk|crimson|cyan|darkblue|darkcyan|darkgoldenrod|darkgray|darkgreen|darkgrey|darkkhaki|darkmagenta|darkolivegreen|darkorange|darkorchid|darkred|darksalmon|darkseagreen|darkslateblue|darkslategray|darkslategrey|darkturquoise|darkviolet|deeppink|deepskyblue|dimgray|dimgrey|dodgerblue|firebrick|floralwhite|forestgreen|fuchsia|gainsboro|ghostwhite|gold|goldenrod|gray|green|greenyellow|grey|honeydew|hotpink|indianred|indigo|ivory|khaki|lavender|lavenderblush|lawngreen|lemonchiffon|lightblue|lightcoral|lightcyan|lightgoldenrodyellow|lightgray|lightgreen|lightgrey|lightpink|lightsalmon|lightseagreen|lightskyblue|lightslategray|lightslategrey|lightsteelblue|lightyellow|lime|limegreen|linen|magenta|maroon|mediumaquamarine|mediumblue|mediumorchid|mediumpurple|mediumseagreen|mediumslateblue|mediumspringgreen|mediumturquoise|mediumvioletred|midnightblue|mintcream|mistyrose|moccasin|navajowhite|navy|oldlace|olive|olivedrab|orange|orangered|orchid|palegoldenrod|palegreen|paleturquoise|palevioletred|papayawhip|peachpuff|peru|pink|plum|powderblue|purple|red|rosybrown|royalblue|saddlebrown|salmon|sandybrown|seagreen|seashell|sienna|silver|skyblue|slateblue|slategray|slategrey|snow|springgreen|steelblue|tan|teal|thistle|tomato|turquoise|violet|wheat|white|whitesmoke|yellow|yellowgreen)\\b",
822+ "name": "support.constant.color.w3c-standard-color-name.scss"
823+ },
824+ "constant_default": {
825+ "match": "!default",
826+ "name": "keyword.other.default.scss"
827+ },
828+ "constant_deprecated_color": {
829+ "comment": "These colours are deprecated from CSS color module level 3 http://www.w3.org/TR/css3-color/#css2-system",
830+ "match": "\\b(ActiveBorder|ActiveCaption|AppWorkspace|Background|ButtonFace|ButtonHighlight|ButtonShadow|ButtonText|CaptionText|GrayText|Highlight|HighlightText|InactiveBorder|InactiveCaption|InactiveCaptionText|InfoBackground|InfoText|Menu|MenuText|Scrollbar|ThreeDDarkShadow|ThreeDFace|ThreeDHighlight|ThreeDLightShadow|ThreeDShadow|Window|WindowFrame|WindowText)\\b",
831+ "name": "invalid.deprecated.color.system.css.scss"
832+ },
833+ "constant_font": {
834+ "match": "(\\b(?i:arial|century|comic|courier|garamond|georgia|helvetica|impact|lucida|symbol|system|tahoma|times|trebuchet|utopia|verdana|webdings|sans-serif|serif|monospace)\\b)",
835+ "name": "support.constant.font-name.scss"
836+ },
837+ "constant_functions": {
838+ "begin": "([\\w-]+)(\\()",
839+ "beginCaptures": {
840+ "1": {
841+ "name": "support.function.misc.scss"
842+ },
843+ "2": {
844+ "name": "punctuation.section.function.scss"
845+ }
846+ },
847+ "end": "(\\))",
848+ "endCaptures": {
849+ "1": {
850+ "name": "punctuation.section.function.scss"
851+ }
852+ },
853+ "patterns": [
854+ {
855+ "include": "#parameters"
856+ }
857+ ]
858+ },
859+ "constant_hex": {
860+ "captures": {
861+ "1": {
862+ "name": "punctuation.definition.constant.scss"
863+ }
864+ },
865+ "match": "(#)([0-9a-fA-F]{3}|[0-9a-fA-F]{6})\\b",
866+ "name": "constant.numeric.color.hex-value.scss"
867+ },
868+ "constant_important": {
869+ "match": "!important",
870+ "name": "keyword.other.important.scss"
871+ },
872+ "constant_mathematical_symbols": {
873+ "match": "\\b(\\+|-|\\*|/)\\b",
874+ "name": "support.constant.mathematical-symbols.scss"
875+ },
876+ "constant_number": {
877+ "match": "(\\b([0-9]+(\\.[0-9]+)?)|\\B\\.[0-9]+)(?=\\s*(ch|cm|deg|dpi|dpcm|dppx|em|ex|grad|in|mm|mozmm|ms|pc|pt|px|rad|rem|turn|s|vh|vmin|vmax|vw|\\b))",
878+ "name": "constant.numeric.scss"
879+ },
880+ "constant_optional": {
881+ "match": "!optional",
882+ "name": "keyword.other.optional.scss"
883+ },
884+ "constant_property_value": {
885+ "match": "\\b(absolute|all-scroll|always|armenian|auto|baseline|below|bidi-override|block|bold|bolder|both|bottom|border-box|break-all|break-word|butt|capitalize|center|char|circle|cjk-ideographic|col-resize|collapse|column-reverse|column|contain|content-box|cover|crosshair|currentColor|dashed|decimal-leading-zero|decimal|default|disabled|disc|distribute-all-lines|distribute-letter|distribute-space|distribute|dotted|double|e-resize|ease-in-out|ease-in|ease-out|ease|ellipsis|fill|fixed|flex-end|flex-start|flex|georgian|grid|groove|hand|hebrew|help|hidden|hiragana-iroha|hiragana|horizontal|ideograph-alpha|ideograph-numeric|ideograph-parenthesis|ideograph-space|inactive|inherit|inline-block|inline-flex|inline-grid|inline-table|inline|inset|inside|inter-ideograph|inter-word|italic|justify|katakana-iroha|katakana|keep-all|landscape|left|lighter|line-edge|line-through|line|linear|list-item|loose|lower-alpha|lower-greek|lower-latin|lower-roman|lowercase|lr-tb|ltr|manipulation|medium|middle|move|n-resize|ne-resize|newspaper|no-drop|no-repeat|nw-resize|none|normal|not-allowed|nowrap|null|oblique|outset|outside|overline|pan-(x|y|left|right|up|down)|pointer|portrait|preserve-3d|progress|relative|repeat-x|repeat-y|repeat|right|ridge|round|row-resize|row-reverse|row|rtl|ruby-base-container|ruby-base|ruby-text-container|ruby-text|ruby|s-resize|scale-down|scroll|se-resize|separate|small-caps|solid|space-around|space-between|square|static|step-end|step-start|stretch|strict|super|sw-resize|table-caption|table-cell|table-column-group|table-column|table-footer-group|table-header-group|table-row-group|table-row|table|tb-rl|text-bottom|text-top|text|thick|thin|top|transparent|underline|upper-alpha|upper-latin|upper-roman|uppercase|vertical-ideographic|vertical-text|visible|w-resize|wait|whitespace|wrap|wrap-reverse|zero|true|false|vertical|horizontal)\\b",
886+ "name": "support.constant.property-value.scss"
887+ },
888+ "constant_rgb": {
889+ "match": "(?x)\n(?<!scale3d\\(|translate3d\\(|rotate3d\\() # scale3d, translate3d, and rotate3d don't use RGB values\n\\b\n(0*(?:1?[0-9]{1,2})|(?:2(?:[0-4][0-9]|5[0-5])))\n\\s*(,)\\s*\n(0*(?:1?[0-9]{1,2})|(?:2(?:[0-4][0-9]|5[0-5])))\n\\s*(,)\\s*\n(0*(?:1?[0-9]{1,2})|(?:2(?:[0-4][0-9]|5[0-5])))\n\\b",
890+ "captures": {
891+ "1": {
892+ "name": "constant.numeric.color.rgb-value.scss"
893+ },
894+ "2": {
895+ "name": "punctuation.separator.delimiter.scss"
896+ },
897+ "3": {
898+ "name": "constant.numeric.color.rgb-value.scss"
899+ },
900+ "4": {
901+ "name": "punctuation.separator.delimiter.scss"
902+ },
903+ "5": {
904+ "name": "constant.numeric.color.rgb-value.scss"
905+ }
906+ }
907+ },
908+ "constant_rgb_percentage": {
909+ "match": "(?x)\n(?<!scale3d\\(|translate3d\\(|rotate3d\\() # scale3d, translate3d, and rotate3d don't use RGB percentages\n\\b\n([0-9]{1,2}|100)\\s*(%)\n\\s*(,)\\s*\n([0-9]{1,2}|100)\\s*(%)\n\\s*(,)\\s*\n([0-9]{1,2}|100)\\s*(%)",
910+ "captures": {
911+ "1": {
912+ "name": "constant.numeric.color.rgb-percentage.scss"
913+ },
914+ "2": {
915+ "name": "keyword.other.unit.scss"
916+ },
917+ "3": {
918+ "name": "punctuation.separator.delimiter.scss"
919+ },
920+ "4": {
921+ "name": "constant.numeric.color.rgb-percentage.scss"
922+ },
923+ "5": {
924+ "name": "keyword.other.unit.scss"
925+ },
926+ "6": {
927+ "name": "punctuation.separator.delimiter.scss"
928+ },
929+ "7": {
930+ "name": "constant.numeric.color.rgb-percentage.scss"
931+ },
932+ "8": {
933+ "name": "keyword.other.unit.scss"
934+ }
935+ }
936+ },
937+ "constant_sass_functions": {
938+ "begin": "(headings|stylesheet-url|rgba?|hsla?|ie-hex-str|red|green|blue|alpha|opacity|hue|saturation|lightness|prefixed|prefix|-moz|-svg|-css2|-pie|-webkit|-ms|font-(?:files|url)|grid-image|image-(?:width|height|url|color)|sprites?|sprite-(?:map|map-name|file|url|position)|inline-(?:font-files|image)|opposite-position|grad-point|grad-end-position|color-stops|color-stops-in-percentages|grad-color-stops|(?:radial|linear)-(?:gradient|svg-gradient)|opacify|fade-?in|transparentize|fade-?out|lighten|darken|saturate|desaturate|grayscale|adjust-(?:hue|lightness|saturation|color)|scale-(?:lightness|saturation|color)|change-color|spin|complement|invert|mix|-compass-(?:list|space-list|slice|nth|list-size)|blank|compact|nth|first-value-of|join|length|append|nest|append-selector|headers|enumerate|range|percentage|unitless|unit|if|type-of|comparable|elements-of-type|quote|unquote|escape|e|sin|cos|tan|abs|round|ceil|floor|pi|translate(?:X|Y))(\\()",
939+ "beginCaptures": {
940+ "1": {
941+ "name": "support.function.misc.scss"
942+ },
943+ "2": {
944+ "name": "punctuation.section.function.scss"
945+ }
946+ },
947+ "end": "(\\))",
948+ "endCaptures": {
949+ "1": {
950+ "name": "punctuation.section.function.scss"
951+ }
952+ },
953+ "patterns": [
954+ {
955+ "include": "#parameters"
956+ }
957+ ]
958+ },
959+ "constant_unit": {
960+ "match": "(?<=[\\d])(ch|cm|deg|dpi|dpcm|dppx|em|ex|grad|in|mm|mozmm|ms|pc|pt|px|rad|rem|turn|s|vh|vmin|vmax|vw)\\b|%",
961+ "name": "keyword.other.unit.scss"
962+ },
963+ "flow_control": {
964+ "patterns": [
965+ {
966+ "include": "#at_rule_if"
967+ },
968+ {
969+ "include": "#at_rule_else"
970+ },
971+ {
972+ "include": "#at_rule_warn"
973+ },
974+ {
975+ "include": "#at_rule_for"
976+ },
977+ {
978+ "include": "#at_rule_while"
979+ },
980+ {
981+ "include": "#at_rule_each"
982+ },
983+ {
984+ "include": "#at_rule_return"
985+ }
986+ ]
987+ },
988+ "function_attributes": {
989+ "patterns": [
990+ {
991+ "match": ":",
992+ "name": "punctuation.separator.key-value.scss"
993+ },
994+ {
995+ "include": "#general"
996+ },
997+ {
998+ "include": "#property_values"
999+ },
1000+ {
1001+ "comment": "We even have error highlighting <3",
1002+ "match": "[={}\\?;@]",
1003+ "name": "invalid.illegal.scss"
1004+ }
1005+ ]
1006+ },
1007+ "functions": {
1008+ "patterns": [
1009+ {
1010+ "begin": "([\\w-]{1,})(\\()\\s*",
1011+ "beginCaptures": {
1012+ "1": {
1013+ "name": "support.function.misc.scss"
1014+ },
1015+ "2": {
1016+ "name": "punctuation.section.function.scss"
1017+ }
1018+ },
1019+ "end": "(\\))",
1020+ "endCaptures": {
1021+ "1": {
1022+ "name": "punctuation.section.function.scss"
1023+ }
1024+ },
1025+ "patterns": [
1026+ {
1027+ "include": "#parameters"
1028+ }
1029+ ]
1030+ },
1031+ {
1032+ "match": "([\\w-]{1,})",
1033+ "name": "support.function.misc.scss"
1034+ }
1035+ ]
1036+ },
1037+ "general": {
1038+ "comment": "Stuff that should be everywhere",
1039+ "patterns": [
1040+ {
1041+ "include": "#variable"
1042+ },
1043+ {
1044+ "include": "#comment_block"
1045+ },
1046+ {
1047+ "include": "#comment_line"
1048+ }
1049+ ]
1050+ },
1051+ "interpolation": {
1052+ "begin": "#{",
1053+ "beginCaptures": {
1054+ "0": {
1055+ "name": "punctuation.definition.interpolation.begin.bracket.curly.scss"
1056+ }
1057+ },
1058+ "end": "}",
1059+ "endCaptures": {
1060+ "0": {
1061+ "name": "punctuation.definition.interpolation.end.bracket.curly.scss"
1062+ }
1063+ },
1064+ "name": "variable.interpolation.scss",
1065+ "patterns": [
1066+ {
1067+ "include": "#property_values"
1068+ },
1069+ {
1070+ "include": "#variable"
1071+ }
1072+ ]
1073+ },
1074+ "conditional_operators": {
1075+ "patterns": [
1076+ {
1077+ "include": "#comparison_operators"
1078+ },
1079+ {
1080+ "include": "#logical_operators"
1081+ }
1082+ ]
1083+ },
1084+ "comparison_operators": {
1085+ "match": "==|!=|<=|>=|<|>",
1086+ "name": "keyword.operator.comparison.scss"
1087+ },
1088+ "logical_operators": {
1089+ "match": "\\b(not\\b|or\\b|and\\b)",
1090+ "name": "keyword.operator.logical.scss"
1091+ },
1092+ "map": {
1093+ "begin": "\\(",
1094+ "beginCaptures": {
1095+ "0": {
1096+ "name": "punctuation.definition.map.begin.bracket.round.scss"
1097+ }
1098+ },
1099+ "end": "\\)",
1100+ "endCaptures": {
1101+ "0": {
1102+ "name": "punctuation.definition.map.end.bracket.round.scss"
1103+ }
1104+ },
1105+ "name": "meta.set.variable.map.scss",
1106+ "patterns": [
1107+ {
1108+ "include": "#comment_block"
1109+ },
1110+ {
1111+ "include": "#comment_line"
1112+ },
1113+ {
1114+ "match": "\\b([\\w-]+)\\s*(:)",
1115+ "captures": {
1116+ "1": {
1117+ "name": "support.type.map.key.scss"
1118+ },
1119+ "2": {
1120+ "name": "punctuation.separator.key-value.scss"
1121+ }
1122+ }
1123+ },
1124+ {
1125+ "match": ",",
1126+ "name": "punctuation.separator.delimiter.scss"
1127+ },
1128+ {
1129+ "include": "#property_values"
1130+ },
1131+ {
1132+ "include": "#variable"
1133+ },
1134+ {
1135+ "include": "#map"
1136+ }
1137+ ]
1138+ },
1139+ "media_attributes": {
1140+ "patterns": [
1141+ {
1142+ "match": ":",
1143+ "name": "punctuation.separator.key-value.scss"
1144+ },
1145+ {
1146+ "include": "#general"
1147+ },
1148+ {
1149+ "include": "#property_name"
1150+ },
1151+ {
1152+ "include": "#property_values"
1153+ },
1154+ {
1155+ "comment": "We even have error highlighting <3",
1156+ "match": "[={}\\?@]",
1157+ "name": "invalid.illegal.scss"
1158+ }
1159+ ]
1160+ },
1161+ "media_features": {
1162+ "patterns": [
1163+ {
1164+ "match": "\\b(min-device-aspect-ratio|max-device-aspect-ratio|device-aspect-ratio|min-aspect-ratio|max-aspect-ratio|aspect-ratio|min-device-height|max-device-height|device-height|min-device-width|max-device-width|device-width|min-monochrome|max-monochrome|monochrome|min-color-index|max-color-index|color-index|min-color|max-color|color|orientation|scan|min-resolution|max-resolution|resolution|grid|min-width|max-width|width)\\b",
1165+ "name": "support.type.property-name.media.css"
1166+ }
1167+ ]
1168+ },
1169+ "media_types": {
1170+ "patterns": [
1171+ {
1172+ "match": "\\b(all|aural|braille|embossed|handheld|print|projection|screen|tty|tv)\\b",
1173+ "name": "support.constant.media.css"
1174+ }
1175+ ]
1176+ },
1177+ "operators": {
1178+ "match": "[-+*/](?!\\s*[-+*/])",
1179+ "name": "keyword.operator.css"
1180+ },
1181+ "parameters": {
1182+ "patterns": [
1183+ {
1184+ "include": "#variable"
1185+ },
1186+ {
1187+ "include": "#property_values"
1188+ },
1189+ {
1190+ "include": "#comment_block"
1191+ },
1192+ {
1193+ "begin": "\\(",
1194+ "beginCaptures": {
1195+ "0": {
1196+ "name": "punctuation.definition.begin.bracket.round.scss"
1197+ }
1198+ },
1199+ "end": "\\)",
1200+ "endCaptures": {
1201+ "0": {
1202+ "name": "punctuation.definition.end.bracket.round.scss"
1203+ }
1204+ },
1205+ "patterns": [
1206+ {
1207+ "include": "#function_attributes"
1208+ }
1209+ ]
1210+ },
1211+ {
1212+ "match": "[^'\",) \\t]+",
1213+ "name": "variable.parameter.url.scss"
1214+ },
1215+ {
1216+ "match": ",",
1217+ "name": "punctuation.separator.delimiter.scss"
1218+ }
1219+ ]
1220+ },
1221+ "properties": {
1222+ "patterns": [
1223+ {
1224+ "begin": "(?<![-a-z])(?=[-a-z])",
1225+ "end": "$|(?![-a-z])",
1226+ "name": "meta.property-name.scss",
1227+ "patterns": [
1228+ {
1229+ "include": "#property_names"
1230+ },
1231+ {
1232+ "include": "#at_rule_include"
1233+ }
1234+ ]
1235+ },
1236+ {
1237+ "begin": "(:)\\s*(?!(\\s*{))",
1238+ "beginCaptures": {
1239+ "1": {
1240+ "name": "punctuation.separator.key-value.scss"
1241+ }
1242+ },
1243+ "comment": "Kuroir: fixed nested elements for sass.",
1244+ "end": "\\s*(;|(?=}|\\)))",
1245+ "endCaptures": {
1246+ "1": {
1247+ "name": "punctuation.terminator.rule.scss"
1248+ }
1249+ },
1250+ "contentName": "meta.property-value.scss",
1251+ "patterns": [
1252+ {
1253+ "include": "#general"
1254+ },
1255+ {
1256+ "include": "#property_values"
1257+ }
1258+ ]
1259+ }
1260+ ]
1261+ },
1262+ "property_list": {
1263+ "begin": "{",
1264+ "beginCaptures": {
1265+ "0": {
1266+ "name": "punctuation.section.property-list.begin.bracket.curly.scss"
1267+ }
1268+ },
1269+ "end": "}",
1270+ "endCaptures": {
1271+ "0": {
1272+ "name": "punctuation.section.property-list.end.bracket.curly.scss"
1273+ }
1274+ },
1275+ "name": "meta.property-list.scss",
1276+ "patterns": [
1277+ {
1278+ "include": "#flow_control"
1279+ },
1280+ {
1281+ "include": "#rules"
1282+ },
1283+ {
1284+ "include": "#properties"
1285+ },
1286+ {
1287+ "include": "$self"
1288+ }
1289+ ]
1290+ },
1291+ "property_name": {
1292+ "comment": "Reversal order is important; KEEP IT. Also when adding new properties add them to the error checker below!",
1293+ "match": "((?<=\\s|^)(-webkit-[A-Za-z-]+|-moz-[A-Za-z-]+|-ms-[A-Za-z-]+))|\\b([0-9]{1,3}%|zoom|z-index|y|x|wrap|word-wrap|word-spacing|word-break|word|width|widows|will-change|white-space-collapse|white-space|white|weight|volume|voice-volume|voice-stress|voice-rate|voice-pitch-range|voice-pitch|voice-family|voice-duration|voice-balance|voice|visibility|vertical-align|variant|user-select|up|unicode-bidi|unicode|trim|transition-timing-function|transition-property|transition-duration|transition-delay|transition|transform|touch-action|top-width|top-style|top-right-radius|top-left-radius|top-color|top|timing-function|text-wrap|text-transform|text-shadow|text-replace|text-outline|text-justify|text-indent|text-height|text-emphasis|text-decoration|text-align-last|text-align|text|target-position|target-new|target-name|target|table-layout|tab-size|style-type|style-position|style-image|style|stroke|string-set|stretch|stress|stacking-strategy|stacking-shift|stacking-ruby|stacking|src|speed|speech-rate|speech|speak-punctuation|speak-numeral|speak-header|speak|span|spacing|space-collapse|space|sizing|size-adjust|size|shadow|respond-to|rule-width|rule-style|rule-color|rule|ruby-span|ruby-position|ruby-overhang|ruby-align|ruby|rows|rotation-point|rotation|role|right-width|right-style|right-color|right|richness|rest-before|rest-after|rest|resource|resolution|resize|reset|replace|repeat|rendering-intent|rate|radius|quotes|punctuation-trim|punctuation|property|profile|presentation-level|presentation|position|pointer-events|point|play-state|play-during|play-count|pitch-range|pitch|phonemes|perspective|pause-before|pause-after|pause|page-policy|page-break-inside|page-break-before|page-break-after|page|padding-top|padding-right|padding-left|padding-bottom|padding|pack|overhang|overflow-y|overflow-x|overflow-wrap|overflow-style|overflow|outline-width|outline-style|outline-offset|outline-color|outline|orphans|origin|orientation|orient|ordinal-group|order|opacity|offset|object-position|object-fit|numeral|new|nav-up|nav-right|nav-left|nav-index|nav-down|nav|name|move-to|model|min-width|min-height|min|max-width|max-height|max|marquee-style|marquee-speed|marquee-play-count|marquee-direction|marquee|marks|mark-before|mark-after|marker|mark|margin-top|margin-right|margin-left|margin-bottom|margin|mask-image|list-style-type|list-style-position|list-style-image|list-style|list|lines|line-stacking-strategy|line-stacking-shift|line-stacking-ruby|line-stacking|line-height|line|level|letter-spacing|length|left-width|left-style|left-color|left|label|justify-content|justify|iteration-count|inline-box-align|initial-value|initial-size|initial-before-align|initial-before-adjust|initial-after-align|initial-after-adjust|index|indent|increment|image-resolution|image-orientation|image|icon|hyphens|hyphenate-resource|hyphenate-lines|hyphenate-character|hyphenate-before|hyphenate-after|hyphenate|height|header|hanging-punctuation|grid-rows|grid-columns|grid|gap|font-weight|font-variant|font-variant-ligatures|font-style|font-stretch|font-size-adjust|font-size|font-family|font|float-offset|float|flex-wrap|flex-shrink|flex-grow|flex-group|flex-flow|flex-direction|flex-basis|flex|fit-position|fit|fill|filter|family|empty-cells|emphasis|elevation|duration|drop-initial-value|drop-initial-size|drop-initial-before-align|drop-initial-before-adjust|drop-initial-after-align|drop-initial-after-adjust|drop|down|dominant-baseline|display-role|display-model|display|direction|delay|decoration-break|decoration|cursor|cue-before|cue-after|cue|crop|counter-reset|counter-increment|counter|count|content|columns|column-width|column-span|column-rule-width|column-rule-style|column-rule-color|column-rule|column-gap|column-fill|column-count|column-break-before|column-break-after|column|color-profile|color|collapse|clip|clear|character|caption-side|break-inside|break-before|break-after|break|box-sizing|box-shadow|box-pack|box-orient|box-ordinal-group|box-lines|box-flex-group|box-flex|box-direction|box-decoration-break|box-align|box|bottom-width|bottom-style|bottom-right-radius|bottom-left-radius|bottom-color|bottom|border-width|border-top-width|border-top-style|border-top-right-radius|border-top-left-radius|border-top-color|border-top|border-style|border-spacing|border-right-width|border-right-style|border-right-color|border-right|border-radius|border-length|border-left-width|border-left-style|border-left-color|border-left|border-image|border-color|border-collapse|border-bottom-width|border-bottom-style|border-bottom-right-radius|border-bottom-left-radius|border-bottom-color|border-bottom|border|bookmark-target|bookmark-level|bookmark-label|bookmark|binding|bidi|before|baseline-shift|baseline|balance|background-size|background-repeat|background-position-y|background-position-x|background-position|background-origin|background-image|background-color|background-clip|background-break|background-attachment|background|backface-visibility|azimuth|attachment|appearance|animation-timing-function|animation-play-state|animation-name|animation-iteration-count|animation-fill-mode|animation-duration|animation-direction|animation-delay|animation|alignment-baseline|alignment-adjust|alignment|align-self|align-last|align-items|align-content|align|after|adjust)\\b",
1294+ "name": "support.type.property-name.scss"
1295+ },
1296+ "property_name_error": {
1297+ "match": "(?<![a-z-])(?!-(top|right|left|bottom|color|radius|last|inside|width|before|after|value|size|type|position|style|image|strategy|shift|align|adjust)\\b|-webkit-[A-Za-z]+\\b|-moz-[A-Za-z]+\\b|-ms-[A-Za-z]+\\b|z-index\\b|[0-9]{1,3}%\\b|zoom\\b|y\\b|x\\b|wrap\\b|word-wrap\\b|word-spacing\\b|word-break\\b|word\\b|will-change\\b|width\\b|widows\\b|white-space-collapse\\b|white-space\\b|white\\b|weight\\b|volume\\b|voice-volume\\b|voice-stress\\b|voice-rate\\b|voice-pitch-range\\b|voice-pitch\\b|voice-family\\b|voice-duration\\b|voice-balance\\b|voice\\b|visibility\\b|vertical-align\\b|variant\\b|user-select\\b|up\\b|unicode-bidi\\b|unicode\\b|u\\b|tt\\b|trim\\b|transition-timing-function\\b|transition-property\\b|transition-duration\\b|transition-delay\\b|transition\\b|transform\\b|touch-action\\b|top-width\\b|top-style\\b|top-right-radius\\b|top-left-radius\\b|top-color\\b|top\\b|timing-function\\b|text-wrap\\b|text-transform\\b|text-shadow\\b|text-replace\\b|text-outline\\b|text-justify\\b|text-indent\\b|text-height\\b|text-emphasis\\b|text-decoration\\b|text-align-last\\b|text-align\\b|text\\b|target-position\\b|target-new\\b|target-name\\b|target\\b|table-layout\\b|tab-size\\b|style-type\\b|style-position\\b|style-image\\b|style\\b|string-set\\b|stroke\\b|strike\\b|stretch\\b|stress\\b|stacking-strategy\\b|stacking-shift\\b|stacking-ruby\\b|stacking\\b|src\\b|speed\\b|speech-rate\\b|speech\\b|speak-punctuation\\b|speak-numeral\\b|speak-header\\b|speak\\b|span\\b|spacing\\b|space-collapse\\b|space\\b|sizing\\b|size-adjust\\b|size\\b|shadow\\b|s\\b|respond-to\\b|rule-width\\b|rule-style\\b|rule-color\\b|rule\\b|ruby-span\\b|ruby-position\\b|ruby-overhang\\b|ruby-align\\b|ruby\\b|rows\\b|rotation-point\\b|rotation\\b|role\\b|right-width\\b|right-style\\b|right-color\\b|right\\b|richness\\b|rest-before\\b|rest-after\\b|rest\\b|resource\\b|resolution\\b|resize\\b|reset\\b|replace\\b|repeat\\b|rendering-intent\\b|rate\\b|radius\\b|quotes\\b|punctuation-trim\\b|punctuation\\b|property\\b|profile\\b|presentation-level\\b|presentation\\b|position\\b|pointer-events\\b|point\\b|play-state\\b|play-during\\b|play-count\\b|pitch-range\\b|pitch\\b|phonemes\\b|pause-before\\b|pause-after\\b|pause\\b|page-policy\\b|page-break-inside\\b|page-break-before\\b|page-break-after\\b|page\\b|padding-top\\b|padding-right\\b|padding-left\\b|padding-bottom\\b|padding\\b|pack\\b|overhang\\b|overflow-y\\b|overflow-x\\b|overflow-wrap\\b|overflow-style\\b|overflow\\b|outline-width\\b|outline-style\\b|outline-offset\\b|outline-color\\b|outline\\b|orphans\\b|origin\\b|orientation\\b|orient\\b|ordinal-group\\b|order\\b|opacity\\b|offset\\b|object-position\\b|object-fit\\b|numeral\\b|new\\b|nav-up\\b|nav-right\\b|nav-left\\b|nav-index\\b|nav-down\\b|nav\\b|name\\b|move-to\\b|model\\b|min-width\\b|min-height\\b|min\\b|max-width\\b|max-height\\b|max\\b|marquee-style\\b|marquee-speed\\b|marquee-play-count\\b|marquee-direction\\b|marquee\\b|marks\\b|mark-before\\b|mark-after\\b|marker\\b|mark\\b|margin-top\\b|margin-right\\b|margin-left\\b|margin-bottom\\b|margin\\b|mask-image\\b|list-style-type\\b|list-style-position\\b|list-style-image\\b|list-style\\b|list\\b|lines\\b|line-stacking-strategy\\b|line-stacking-shift\\b|line-stacking-ruby\\b|line-stacking\\b|line-height\\b|line\\b|level\\b|letter-spacing\\b|length\\b|left-width\\b|left-style\\b|left-color\\b|left\\b|label\\b|justify-content\\b|justify\\b|iteration-count\\b|inline-box-align\\b|initial-value\\b|initial-size\\b|initial-before-align\\b|initial-before-adjust\\b|initial-after-align\\b|initial-after-adjust\\b|index\\b|indent\\b|increment\\b|image-resolution\\b|image-orientation\\b|image\\b|icon\\b|hyphens\\b|hyphenate-resource\\b|hyphenate-lines\\b|hyphenate-character\\b|hyphenate-before\\b|hyphenate-after\\b|hyphenate\\b|height\\b|header\\b|hanging-punctuation\\b|grid-rows\\b|grid-columns\\b|grid\\b|gap\\b|font-weight\\b|font-variant\\b|font-variant-ligatures\\b|font-style\\b|font-stretch\\b|font-size-adjust\\b|font-size\\b|font-family\\b|font\\b|float-offset\\b|float\\b|flex-wrap\\b|flex-shrink\\b|flex-grow\\b|flex-group\\b|flex-flow\\b|flex-direction\\b|flex-basis\\b|flex\\b|fit-position\\b|fit\\b|fill\\b|filter\\b|family\\b|empty-cells\\b|emphasis\\b|elevation\\b|duration\\b|drop-initial-value\\b|drop-initial-size\\b|drop-initial-before-align\\b|drop-initial-before-adjust\\b|drop-initial-after-align\\b|drop-initial-after-adjust\\b|drop\\b|down\\b|dominant-baseline\\b|display-role\\b|display-model\\b|display\\b|direction\\b|delay\\b|decoration-break\\b|decoration\\b|cursor\\b|cue-before\\b|cue-after\\b|cue\\b|crop\\b|counter-reset\\b|counter-increment\\b|counter\\b|count\\b|content\\b|columns\\b|column-width\\b|column-span\\b|column-rule-width\\b|column-rule-style\\b|column-rule-color\\b|column-rule\\b|column-gap\\b|column-fill\\b|column-count\\b|column-break-before\\b|column-break-after\\b|column\\b|color-profile\\b|color\\b|collapse\\b|clip\\b|clear\\b|character\\b|center\\b|caption-side\\b|break-inside\\b|break-before\\b|break-after\\b|break\\b|box-sizing\\b|box-shadow\\b|box-pack\\b|box-orient\\b|box-ordinal-group\\b|box-lines\\b|box-flex-group\\b|box-flex\\b|box-direction\\b|box-decoration-break\\b|box-align\\b|box\\b|bottom-width\\b|bottom-style\\b|bottom-right-radius\\b|bottom-left-radius\\b|bottom-color\\b|bottom\\b|border-width\\b|border-top-width\\b|border-top-style\\b|border-top-right-radius\\b|border-top-left-radius\\b|border-top-color\\b|border-top\\b|border-style\\b|border-spacing\\b|border-right-width\\b|border-right-style\\b|border-right-color\\b|border-right\\b|border-radius\\b|border-length\\b|border-left-width\\b|border-left-style\\b|border-left-color\\b|border-left\\b|border-image\\b|border-color\\b|border-collapse\\b|border-bottom-width\\b|border-bottom-style\\b|border-bottom-right-radius\\b|border-bottom-left-radius\\b|border-bottom-color\\b|border-bottom\\b|border\\b|bookmark-target\\b|bookmark-level\\b|bookmark-label\\b|bookmark\\b|binding\\b|bidi\\b|big\\b|before\\b|baseline-shift\\b|baseline\\b|balance\\b|background-size\\b|background-repeat\\b|background-position-y\\b|background-position-x\\b|background-position\\b|background-origin\\b|background-image\\b|background-color\\b|background-clip\\b|background-break\\b|background-attachment\\b|background\\b|backface-visibility\\b|azimuth\\b|attachment\\b|applet\\b|appearance\\b|animation-timing-function\\b|animation-play-state\\b|animation-name\\b|animation-iteration-count\\b|animation-fill-mode\\b|animation-duration\\b|animation-direction\\b|animation-delay\\b|animation\\b|alignment-baseline\\b|alignment-adjust\\b|alignment\\b|align-last\\b|align-self\\b|align-items\\b|align-content\\b|align\\b|after\\b|adjust\\b|acronym\\b)[-_a-z]+",
1298+ "name": "invalid.illegal.scss"
1299+ },
1300+ "property_names": {
1301+ "patterns": [
1302+ {
1303+ "include": "#property_name"
1304+ },
1305+ {
1306+ "include": "#property_name_error"
1307+ }
1308+ ]
1309+ },
1310+ "property_values": {
1311+ "comment": "Stuff that should only be available on values.",
1312+ "patterns": [
1313+ {
1314+ "include": "#string_single"
1315+ },
1316+ {
1317+ "include": "#string_double"
1318+ },
1319+ {
1320+ "include": "#constant_functions"
1321+ },
1322+ {
1323+ "include": "#constant_sass_functions"
1324+ },
1325+ {
1326+ "include": "#constant_hex"
1327+ },
1328+ {
1329+ "include": "#constant_rgb"
1330+ },
1331+ {
1332+ "include": "#constant_rgb_percentage"
1333+ },
1334+ {
1335+ "include": "#constant_important"
1336+ },
1337+ {
1338+ "include": "#constant_default"
1339+ },
1340+ {
1341+ "include": "#constant_optional"
1342+ },
1343+ {
1344+ "include": "#constant_unit"
1345+ },
1346+ {
1347+ "include": "#constant_property_value"
1348+ },
1349+ {
1350+ "include": "#constant_number"
1351+ },
1352+ {
1353+ "include": "#constant_font"
1354+ },
1355+ {
1356+ "include": "#constant_color"
1357+ },
1358+ {
1359+ "include": "#constant_deprecated_color"
1360+ },
1361+ {
1362+ "include": "#property_name"
1363+ },
1364+ {
1365+ "include": "#constant_mathematical_symbols"
1366+ },
1367+ {
1368+ "include": "#operators"
1369+ }
1370+ ]
1371+ },
1372+ "rules": {
1373+ "patterns": [
1374+ {
1375+ "include": "#general"
1376+ },
1377+ {
1378+ "include": "#at_rule_extend"
1379+ },
1380+ {
1381+ "include": "#at_rule_content"
1382+ },
1383+ {
1384+ "include": "#at_rule_include"
1385+ },
1386+ {
1387+ "include": "#at_rule_media"
1388+ },
1389+ {
1390+ "include": "#selectors"
1391+ }
1392+ ]
1393+ },
1394+ "selector_attribute": {
1395+ "captures": {
1396+ "1": {
1397+ "name": "punctuation.definition.attribute-selector.begin.bracket.square.scss"
1398+ },
1399+ "2": {
1400+ "name": "entity.other.attribute-name.attribute.scss"
1401+ },
1402+ "3": {
1403+ "name": "punctuation.separator.operator.scss"
1404+ },
1405+ "4": {
1406+ "name": "string.unquoted.attribute-value.scss"
1407+ },
1408+ "5": {
1409+ "name": "string.quoted.double.attribute-value.scss"
1410+ },
1411+ "6": {
1412+ "name": "punctuation.definition.string.begin.scss"
1413+ },
1414+ "7": {
1415+ "name": "punctuation.definition.string.end.scss"
1416+ },
1417+ "8": {
1418+ "name": "punctuation.definition.attribute-selector.end.bracket.square.scss"
1419+ }
1420+ },
1421+ "match": "(?i)(\\[)\\s*(-?[_a-z\\\\[[:^ascii:]]][-_a-z0-9\\\\[[:^ascii:]]]*)(?:\\s*([~|^$*]?=)\\s*(?:(-?[_a-z\\\\[[:^ascii:]]][-_a-z0-9\\\\[[:^ascii:]]]*)|((?>(['\"])(?:[^\\\\]|\\\\.)*?(\\6)))))?\\s*(])",
1422+ "name": "meta.attribute-selector.scss"
1423+ },
1424+ "selector_class": {
1425+ "begin": "(\\.)(?=[\\w-]|#{)",
1426+ "beginCaptures": {
1427+ "1": {
1428+ "name": "punctuation.definition.entity.css"
1429+ }
1430+ },
1431+ "end": "(?![\\w-]|(#{))",
1432+ "name": "entity.other.attribute-name.class.css",
1433+ "patterns": [
1434+ {
1435+ "include": "#interpolation"
1436+ }
1437+ ]
1438+ },
1439+ "selector_entities": {
1440+ "match": "\\b(a|abbr|acronym|address|area|article|aside|audio|b|base|bdi|bdo|big|blockquote|body|br|button|canvas|caption|circle|cite|code|col|colgroup|data|datalist|dd|del|details|dfn|dialog|div|dl|dt|ellipse|em|embed|eventsource|fieldset|figure|figcaption|footer|form|frame|frameset|g|(h[1-6])|head|header|hgroup|hr|html|i|iframe|img|image|input|ins|kbd|keygen|label|legend|li|line(?!-)|link|main|map|mark|menu|menuitem|meta|meter|nav|noframes|noscript|object(?!-)|ol|optgroup|option|output|p|param|path|picture|polygon|polyline|pre|progress|q|rb|rect|rp|rt|rtc|ruby|s|samp|script|section|select|small|source|span|strike|strong|style|sub|summary|sup|svg|table(?!-)|tbody|td|template|text(?!-)|textarea|textpath|tfoot|th|thead|time|title|tr|track|tspan|tt|u|ul|var|video|wbr)\\b",
1441+ "name": "entity.name.tag.scss"
1442+ },
1443+ "selector_custom": {
1444+ "match": "\\b([a-zA-Z0-9]+(-[a-zA-Z0-9]+)+)(?=\\.|\\s++[^:]|\\s*[,{]|:(link|visited|hover|active|focus|target|lang|disabled|enabled|checked|indeterminate|root|nth-(child|last-child|of-type|last-of-type)|first-child|last-child|first-of-type|last-of-type|only-child|only-of-type|empty|not|valid|invalid)(\\([0-9A-Za-z]*\\))?)",
1445+ "name": "entity.name.tag.custom.scss"
1446+ },
1447+ "selector_id": {
1448+ "captures": {
1449+ "1": {
1450+ "name": "punctuation.definition.entity.css"
1451+ }
1452+ },
1453+ "match": "(#)[a-zA-Z][a-zA-Z0-9_-]*",
1454+ "name": "entity.other.attribute-name.id.css"
1455+ },
1456+ "selector_placeholder": {
1457+ "captures": {
1458+ "1": {
1459+ "name": "punctuation.definition.entity.scss"
1460+ }
1461+ },
1462+ "match": "(%)[a-zA-Z0-9_-]+",
1463+ "name": "entity.other.attribute-name.placeholder.scss"
1464+ },
1465+ "parent_selector_suffix": {
1466+ "match": "(?<=&)[a-zA-Z0-9_-]+",
1467+ "name": "entity.other.attribute-name.parent-selector-suffix.scss"
1468+ },
1469+ "selector_pseudo_class": {
1470+ "patterns": [
1471+ {
1472+ "begin": "((:)\\bnth-(?:child|last-child|of-type|last-of-type))(\\()",
1473+ "beginCaptures": {
1474+ "1": {
1475+ "name": "entity.other.attribute-name.pseudo-class.css"
1476+ },
1477+ "2": {
1478+ "name": "punctuation.definition.entity.css"
1479+ },
1480+ "3": {
1481+ "name": "punctuation.definition.pseudo-class.begin.bracket.round.css"
1482+ }
1483+ },
1484+ "end": "\\)",
1485+ "endCaptures": {
1486+ "0": {
1487+ "name": "punctuation.definition.pseudo-class.end.bracket.round.css"
1488+ }
1489+ },
1490+ "patterns": [
1491+ {
1492+ "match": "\\d+",
1493+ "name": "constant.numeric.scss"
1494+ },
1495+ {
1496+ "match": "(?<=\\d)n\\b|\\b(n|even|odd)\\b",
1497+ "name": "constant.other.scss"
1498+ },
1499+ {
1500+ "match": "\\w+",
1501+ "name": "invalid.illegal.scss"
1502+ }
1503+ ]
1504+ },
1505+ {
1506+ "match": "(?x)\n(:)\\b\n(link|visited|hover|active|focus|target|lang|disabled|enabled|checked|\nindeterminate|root|first-child|last-child|first-of-type|last-of-type|\nonly-child|only-of-type|empty|not|valid|invalid)\\b",
1507+ "captures": {
1508+ "0": {
1509+ "name": "entity.other.attribute-name.pseudo-class.css"
1510+ },
1511+ "1": {
1512+ "name": "punctuation.definition.entity.css"
1513+ }
1514+ }
1515+ }
1516+ ]
1517+ },
1518+ "selector_pseudo_element": {
1519+ "captures": {
1520+ "1": {
1521+ "name": "punctuation.definition.entity.css"
1522+ }
1523+ },
1524+ "match": "(:+)((-(moz|webkit|ms)-)?(after|before|first-letter|first-line|selection))\\b",
1525+ "name": "entity.other.attribute-name.pseudo-element.css"
1526+ },
1527+ "selectors": {
1528+ "comment": "Stuff for Selectors.",
1529+ "patterns": [
1530+ {
1531+ "include": "#selector_entities"
1532+ },
1533+ {
1534+ "include": "#selector_custom"
1535+ },
1536+ {
1537+ "include": "#selector_class"
1538+ },
1539+ {
1540+ "include": "#selector_id"
1541+ },
1542+ {
1543+ "include": "#selector_pseudo_class"
1544+ },
1545+ {
1546+ "include": "#tag_wildcard"
1547+ },
1548+ {
1549+ "include": "#tag_parent_reference"
1550+ },
1551+ {
1552+ "include": "#selector_pseudo_element"
1553+ },
1554+ {
1555+ "include": "#selector_attribute"
1556+ },
1557+ {
1558+ "include": "#selector_placeholder"
1559+ },
1560+ {
1561+ "include": "#parent_selector_suffix"
1562+ }
1563+ ]
1564+ },
1565+ "string_double": {
1566+ "begin": "\"",
1567+ "beginCaptures": {
1568+ "0": {
1569+ "name": "punctuation.definition.string.begin.scss"
1570+ }
1571+ },
1572+ "end": "\"",
1573+ "endCaptures": {
1574+ "0": {
1575+ "name": "punctuation.definition.string.end.scss"
1576+ }
1577+ },
1578+ "name": "string.quoted.double.scss",
1579+ "patterns": [
1580+ {
1581+ "match": "\\\\(\\h{1,6}|.)",
1582+ "name": "constant.character.escape.scss"
1583+ },
1584+ {
1585+ "include": "#interpolation"
1586+ }
1587+ ]
1588+ },
1589+ "string_single": {
1590+ "begin": "'",
1591+ "beginCaptures": {
1592+ "0": {
1593+ "name": "punctuation.definition.string.begin.scss"
1594+ }
1595+ },
1596+ "end": "'",
1597+ "endCaptures": {
1598+ "0": {
1599+ "name": "punctuation.definition.string.end.scss"
1600+ }
1601+ },
1602+ "name": "string.quoted.single.scss",
1603+ "patterns": [
1604+ {
1605+ "match": "\\\\(\\h{1,6}|.)",
1606+ "name": "constant.character.escape.scss"
1607+ },
1608+ {
1609+ "include": "#interpolation"
1610+ }
1611+ ]
1612+ },
1613+ "tag_parent_reference": {
1614+ "match": "&",
1615+ "name": "entity.name.tag.reference.scss"
1616+ },
1617+ "tag_wildcard": {
1618+ "match": "\\*",
1619+ "name": "entity.name.tag.wildcard.scss"
1620+ },
1621+ "variable": {
1622+ "patterns": [
1623+ {
1624+ "include": "#variables"
1625+ },
1626+ {
1627+ "include": "#interpolation"
1628+ }
1629+ ]
1630+ },
1631+ "variable_setting": {
1632+ "begin": "\\s*(\\$[A-Za-z0-9_-]+\\b)\\s*(:)\\s*",
1633+ "captures": {
1634+ "1": {
1635+ "name": "variable.scss"
1636+ },
1637+ "2": {
1638+ "name": "punctuation.separator.key-value.scss"
1639+ }
1640+ },
1641+ "end": "\\s*(?=;)",
1642+ "name": "meta.set.variable.scss",
1643+ "patterns": [
1644+ {
1645+ "include": "#comment_block"
1646+ },
1647+ {
1648+ "include": "#comment_line"
1649+ },
1650+ {
1651+ "include": "#map"
1652+ },
1653+ {
1654+ "include": "#property_values"
1655+ },
1656+ {
1657+ "include": "#variable"
1658+ }
1659+ ]
1660+ },
1661+ "variables": {
1662+ "match": "\\$[A-Za-z0-9_-]+\\b",
1663+ "name": "variable.scss"
1664+ }
1665+ },
1666+ "version": "https://github.com/atom/language-sass/commit/b0417d1412a9169562f637133099fe2bb841a735"
1667+}
modified extensions/vscode/textmate-syntaxes/shaderlab.json +0 −0

Not shown: the file is larger than the hub shows, or this page holds as much as it shows. View the file.

modified extensions/vscode/textmate-syntaxes/swift.json +0 −0

Not shown: the file is larger than the hub shows, or this page holds as much as it shows. View the file.

modified extensions/vscode/textmate-syntaxes/xml.json +0 −0

Not shown: the file is larger than the hub shows, or this page holds as much as it shows. View the file.

modified extensions/vscode/textmate-syntaxes/xsl.json +0 −0

Not shown: the file is larger than the hub shows, or this page holds as much as it shows. View the file.

modified extensions/vscode/textmate-syntaxes/yaml.json +0 −0

Not shown: the file is larger than the hub shows, or this page holds as much as it shows. View the file.

modified gui/src/components/StyledMarkdownPreview/utils/commandExtractor.test.ts +0 −0

Not shown: the file is larger than the hub shows, or this page holds as much as it shows. View the file.

modified gui/src/components/StyledMarkdownPreview/utils/commandExtractor.ts +0 −0

Not shown: the file is larger than the hub shows, or this page holds as much as it shows. View the file.

modified gui/src/components/StyledMarkdownPreview/utils/headerIsMarkdown.test.ts +0 −0

Not shown: the file is larger than the hub shows, or this page holds as much as it shows. View the file.

modified gui/src/components/StyledMarkdownPreview/utils/headerIsMarkdown.ts +0 −0

Not shown: the file is larger than the hub shows, or this page holds as much as it shows. View the file.

modified gui/src/components/StyledMarkdownPreview/utils/patchNestedMarkdown.test.ts +0 −0

Not shown: the file is larger than the hub shows, or this page holds as much as it shows. View the file.

modified gui/src/components/StyledMarkdownPreview/utils/patchNestedMarkdown.ts +0 −0

Not shown: the file is larger than the hub shows, or this page holds as much as it shows. View the file.

modified gui/src/components/StyledMarkdownPreview/utils/remarkTables.tsx +0 −0

Not shown: the file is larger than the hub shows, or this page holds as much as it shows. View the file.

modified gui/src/components/console/Details.tsx +0 −0

Not shown: the file is larger than the hub shows, or this page holds as much as it shows. View the file.

modified gui/src/components/gui/Shortcut.css +0 −0

Not shown: the file is larger than the hub shows, or this page holds as much as it shows. View the file.

modified gui/src/components/mainInput/Lump/sections/PromptsSection.tsx +0 −0

Not shown: the file is larger than the hub shows, or this page holds as much as it shows. View the file.

modified gui/src/components/mainInput/Lump/sections/RulesSection.tsx +0 −0

Not shown: the file is larger than the hub shows, or this page holds as much as it shows. View the file.

modified gui/src/components/mainInput/Lump/sections/errors/ErrorSection.tsx +0 −0

Not shown: the file is larger than the hub shows, or this page holds as much as it shows. View the file.

modified gui/src/components/mainInput/belowMainInput/RulesPeek.tsx +0 −0

Not shown: the file is larger than the hub shows, or this page holds as much as it shows. View the file.

modified gui/src/hooks/useWebviewListener.ts +0 −0

Not shown: the file is larger than the hub shows, or this page holds as much as it shows. View the file.

modified gui/src/pages/config/IndexingProgress/IndexingProgressBar.tsx +0 −0

Not shown: the file is larger than the hub shows, or this page holds as much as it shows. View the file.

modified gui/src/pages/config/ModelRoleSelector.tsx +0 −0

Not shown: the file is larger than the hub shows, or this page holds as much as it shows. View the file.

modified gui/src/pages/gui/ToolCallDiv/RunTerminalCommand.tsx +0 −0

Not shown: the file is larger than the hub shows, or this page holds as much as it shows. View the file.

modified gui/src/redux/selectors/selectActiveTools.ts +0 −0

Not shown: the file is larger than the hub shows, or this page holds as much as it shows. View the file.

modified gui/src/redux/slices/tabsSlice.ts +0 −0

Not shown: the file is larger than the hub shows, or this page holds as much as it shows. View the file.

modified gui/src/redux/thunks/streamResponseAfterToolCall.ts +0 −0

Not shown: the file is larger than the hub shows, or this page holds as much as it shows. View the file.

modified gui/src/util/index.ts +0 −0

Not shown: the file is larger than the hub shows, or this page holds as much as it shows. View the file.

modified manual-testing-sandbox/test.ts +0 −0

Not shown: the file is larger than the hub shows, or this page holds as much as it shows. View the file.

modified package.json +0 −0

Not shown: the file is larger than the hub shows, or this page holds as much as it shows. View the file.

modified packages/config-types/package.json +0 −0

Not shown: the file is larger than the hub shows, or this page holds as much as it shows. View the file.

modified packages/config-yaml/release.config.js +0 −0

Not shown: the file is larger than the hub shows, or this page holds as much as it shows. View the file.

modified packages/config-yaml/src/__tests__/index.test.ts +0 −0

Not shown: the file is larger than the hub shows, or this page holds as much as it shows. View the file.

modified packages/config-yaml/src/schemas/models.ts +0 −0

Not shown: the file is larger than the hub shows, or this page holds as much as it shows. View the file.

modified packages/config-yaml/src/scripts/generateJsonSchema.ts +0 −0

Not shown: the file is larger than the hub shows, or this page holds as much as it shows. View the file.

modified packages/continue-sdk/python/api/README.md +0 −0

Not shown: the file is larger than the hub shows, or this page holds as much as it shows. View the file.

modified packages/continue-sdk/python/api/docs/DefaultApi.md +0 −0

Not shown: the file is larger than the hub shows, or this page holds as much as it shows. View the file.

modified packages/continue-sdk/python/api/docs/ListAssistants200ResponseInner.md +0 −0

Not shown: the file is larger than the hub shows, or this page holds as much as it shows. View the file.

modified packages/continue-sdk/python/api/docs/ListAssistants200ResponseInnerConfigResult.md +0 −0

Not shown: the file is larger than the hub shows, or this page holds as much as it shows. View the file.

modified packages/continue-sdk/python/api/docs/ListAssistants401Response.md +0 −0

Not shown: the file is larger than the hub shows, or this page holds as much as it shows. View the file.

modified packages/continue-sdk/python/api/docs/ListAssistants404Response.md +0 −0

Not shown: the file is larger than the hub shows, or this page holds as much as it shows. View the file.

modified packages/continue-sdk/typescript/api/README.md +0 −0

Not shown: the file is larger than the hub shows, or this page holds as much as it shows. View the file.

modified packages/continue-sdk/typescript/api/src/apis/DefaultApi.ts +0 −0

Not shown: the file is larger than the hub shows, or this page holds as much as it shows. View the file.

modified packages/continue-sdk/typescript/api/src/apis/index.ts +0 −0

Not shown: the file is larger than the hub shows, or this page holds as much as it shows. View the file.

modified packages/continue-sdk/typescript/api/src/index.ts +0 −0

Not shown: the file is larger than the hub shows, or this page holds as much as it shows. View the file.

modified packages/continue-sdk/typescript/api/src/models/ListAssistants200ResponseInner.ts +0 −0

Not shown: the file is larger than the hub shows, or this page holds as much as it shows. View the file.

modified packages/continue-sdk/typescript/api/src/models/ListAssistants200ResponseInnerConfigResult.ts +0 −0

Not shown: the file is larger than the hub shows, or this page holds as much as it shows. View the file.

modified packages/continue-sdk/typescript/api/src/models/ListAssistants401Response.ts +0 −0

Not shown: the file is larger than the hub shows, or this page holds as much as it shows. View the file.

modified packages/continue-sdk/typescript/api/src/models/ListAssistants404Response.ts +0 −0

Not shown: the file is larger than the hub shows, or this page holds as much as it shows. View the file.

modified packages/continue-sdk/typescript/api/src/models/index.ts +0 −0

Not shown: the file is larger than the hub shows, or this page holds as much as it shows. View the file.

modified packages/continue-sdk/typescript/api/src/runtime.ts +0 −0

Not shown: the file is larger than the hub shows, or this page holds as much as it shows. View the file.

modified packages/continue-sdk/typescript/api/tsconfig.json +0 −0

Not shown: the file is larger than the hub shows, or this page holds as much as it shows. View the file.

modified packages/fetch/jest.globals.d.ts +0 −0

Not shown: the file is larger than the hub shows, or this page holds as much as it shows. View the file.

modified packages/llm-info/src/providers/gemini.ts +0 −0

Not shown: the file is larger than the hub shows, or this page holds as much as it shows. View the file.

modified packages/llm-info/src/providers/vertexai.ts +0 −0

Not shown: the file is larger than the hub shows, or this page holds as much as it shows. View the file.

modified packages/llm-info/src/providers/xAI.ts +0 −0

Not shown: the file is larger than the hub shows, or this page holds as much as it shows. View the file.