This commit is contained in:
Drew Powers 2021-05-03 12:26:10 -06:00 committed by GitHub
parent c93201a909
commit 94038d3297
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
96 changed files with 2777 additions and 3003 deletions

View file

@ -6,8 +6,5 @@
"access": "public", "access": "public",
"baseBranch": "main", "baseBranch": "main",
"updateInternalDependencies": "patch", "updateInternalDependencies": "patch",
"ignore": [ "ignore": ["@example/*", "www"]
"@example/*",
"www"
]
} }

1
.prettierignore Normal file
View file

@ -0,0 +1 @@
**/dist/*

10
.vscode/launch.json vendored
View file

@ -7,12 +7,8 @@
"request": "launch", "request": "launch",
"name": "Launch Client", "name": "Launch Client",
"runtimeExecutable": "${execPath}", "runtimeExecutable": "${execPath}",
"args": [ "args": ["--extensionDevelopmentPath=${workspaceRoot}/vscode"],
"--extensionDevelopmentPath=${workspaceRoot}/vscode" "outFiles": ["${workspaceRoot}/vscode/dist/**/*.js"],
],
"outFiles": [
"${workspaceRoot}/vscode/dist/**/*.js"
],
"preLaunchTask": { "preLaunchTask": {
"type": "npm", "type": "npm",
"script": "build:extension" "script": "build:extension"
@ -25,7 +21,7 @@
"port": 6040, "port": 6040,
"restart": true, "restart": true,
"outFiles": ["${workspaceRoot}/vscode/dist/**/*.js"] "outFiles": ["${workspaceRoot}/vscode/dist/**/*.js"]
}, }
], ],
"compounds": [ "compounds": [
{ {

5
.vscode/tasks.json vendored
View file

@ -1,4 +1,3 @@
{ {
"version": "2.0.0", "version": "2.0.0",
"tasks": [ "tasks": [
@ -10,9 +9,7 @@
"panel": "dedicated", "panel": "dedicated",
"reveal": "never" "reveal": "never"
}, },
"problemMatcher": [ "problemMatcher": ["$tsc"]
"$tsc"
]
} }
] ]
} }

View file

@ -43,7 +43,6 @@ npm run build
To deploy your Astro site to production, upload the contents of `/dist` to your favorite static site host. To deploy your Astro site to production, upload the contents of `/dist` to your favorite static site host.
## 🥾 Guides ## 🥾 Guides
### 🚀 Basic Usage ### 🚀 Basic Usage
@ -67,7 +66,7 @@ Even though nearly-everything [is configurable][docs-config], we recommend start
Routing happens in `src/pages/*`. Every `.astro` or `.md.astro` file in this folder corresponds with a public URL. For example: Routing happens in `src/pages/*`. Every `.astro` or `.md.astro` file in this folder corresponds with a public URL. For example:
| Local file | Public URL | | Local file | Public URL |
| :--------------------------------------- | :------------------------------ | | :------------------------------------- | :------------------------------ |
| `src/pages/index.astro` | `/index.html` | | `src/pages/index.astro` | `/index.html` |
| `src/pages/post/my-blog-post.md.astro` | `/post/my-blog-post/index.html` | | `src/pages/post/my-blog-post.md.astro` | `/post/my-blog-post/index.html` |
@ -164,10 +163,10 @@ Astro will automatically create a `/sitemap.xml` for you for SEO! Be sure to set
👉 [**Collections API**][docs-collections] 👉 [**Collections API**][docs-collections]
## ⚙️ Config ## ⚙️ Config
👉 [**`astro.config.mjs` Reference**][docs-config] 👉 [**`astro.config.mjs` Reference**][docs-config]
## 📚 API ## 📚 API
👉 [**Full API Reference**][docs-api] 👉 [**Full API Reference**][docs-api]

View file

@ -36,7 +36,7 @@ Runs the Astro development server. This starts an HTTP server that responds to r
See the [dev server](./dev.md) docs for more information on how the dev server works. See the [dev server](./dev.md) docs for more information on how the dev server works.
__Flags__ **Flags**
##### `--port` ##### `--port`

View file

@ -14,7 +14,7 @@ The dev server will serve the following special routes:
### /400 ### /400
This is a custom __400__ status code page. You can add this route by adding a page component to your `src/pages` folder: This is a custom **400** status code page. You can add this route by adding a page component to your `src/pages` folder:
``` ```
├── src/ ├── src/
@ -27,13 +27,10 @@ For any URL you visit that doesn't have a corresponding page, the `400.astro` fi
### /500 ### /500
This is a custom __500__ status code page. You can add this route by adding a page component to your `src/pages` folder: This is a custom **500** status code page. You can add this route by adding a page component to your `src/pages` folder:
```astro ```astro
├── src/ ├── src/ │ ├── components/ │ └── pages/ │ └── 500.astro
│ ├── components/
│ └── pages/
│ └── 500.astro
``` ```
This page is used any time an error occurs in the dev server. This page is used any time an error occurs in the dev server.

View file

@ -117,7 +117,7 @@ export let name;
`.astro` files can end up looking very similar to `.jsx` files, but there are a few key differences. Here's a comparison between the two formats. `.astro` files can end up looking very similar to `.jsx` files, but there are a few key differences. Here's a comparison between the two formats.
| Feature | Astro | JSX | | Feature | Astro | JSX |
|------------------------- |------------------------------------------ |---------------------------------------------------- | | ---------------------------- | ---------------------------------------- | -------------------------------------------------- |
| File extension | `.astro` | `.jsx` or `.tsx` | | File extension | `.astro` | `.jsx` or `.tsx` |
| User-Defined Components | `<Capitalized>` | `<Capitalized>` | | User-Defined Components | `<Capitalized>` | `<Capitalized>` |
| Expression Syntax | `{}` | `{}` | | Expression Syntax | `{}` | `{}` |
@ -137,5 +137,4 @@ export let name;
### TODO: Composition (Slots) ### TODO: Composition (Slots)
[code-ext]: https://marketplace.visualstudio.com/items?itemName=astro-build.astro [code-ext]: https://marketplace.visualstudio.com/items?itemName=astro-build.astro

View file

@ -3,18 +3,18 @@ import { useState } from 'preact/hooks';
/** a counter written in Preact */ /** a counter written in Preact */
export default function PreactCounter({ children }) { export default function PreactCounter({ children }) {
const [count, setCount] = useState(0) const [count, setCount] = useState(0);
const add = () => setCount(i => i + 1); const add = () => setCount((i) => i + 1);
const subtract = () => setCount(i => i - 1); const subtract = () => setCount((i) => i - 1);
return <> return (
<>
<div className="counter"> <div className="counter">
<button onClick={subtract}>-</button> <button onClick={subtract}>-</button>
<pre>{count}</pre> <pre>{count}</pre>
<button onClick={add}>+</button> <button onClick={add}>+</button>
</div> </div>
<div className="children"> <div className="children">{children}</div>
{children}
</div>
</> </>
);
} }

View file

@ -2,18 +2,18 @@ import React, { useState } from 'react';
/** a counter written in React */ /** a counter written in React */
export default function ReactCounter({ children }) { export default function ReactCounter({ children }) {
const [count, setCount] = useState(0) const [count, setCount] = useState(0);
const add = () => setCount(i => i + 1); const add = () => setCount((i) => i + 1);
const subtract = () => setCount(i => i - 1); const subtract = () => setCount((i) => i - 1);
return <> return (
<>
<div className="counter"> <div className="counter">
<button onClick={subtract}>-</button> <button onClick={subtract}>-</button>
<pre>{count}</pre> <pre>{count}</pre>
<button onClick={add}>+</button> <button onClick={add}>+</button>
</div> </div>
<div className="children"> <div className="children">{children}</div>
{children}
</div>
</> </>
);
} }

View file

@ -117,5 +117,9 @@ function PluginSearchPageLive() {
} }
export default function PluginSearchPage(props) { export default function PluginSearchPage(props) {
return import.meta.env.astro ? <div>Loading...</div> : <PluginSearchPageLive {...props} /> return import.meta.env.astro ? (
<div>Loading...</div>
) : (
<PluginSearchPageLive {...props} />
);
} }

View file

@ -1,6 +1,8 @@
import docsearch from 'docsearch.js/dist/cdn/docsearch.min.js'; import docsearch from 'docsearch.js/dist/cdn/docsearch.min.js';
customElements.define('doc-search', class extends HTMLElement { customElements.define(
'doc-search',
class extends HTMLElement {
connectedCallback() { connectedCallback() {
if (!this._setup) { if (!this._setup) {
const apiKey = this.getAttribute('api-key'); const apiKey = this.getAttribute('api-key');
@ -9,9 +11,10 @@ customElements.define('doc-search', class extends HTMLElement {
apiKey: apiKey, apiKey: apiKey,
indexName: 'snowpack', indexName: 'snowpack',
inputSelector: selector, inputSelector: selector,
debug: true // Set debug to true if you want to inspect the dropdown debug: true, // Set debug to true if you want to inspect the dropdown
}); });
this._setup = true; this._setup = true;
} }
} }
}); },
);

View file

@ -1,2 +1,4 @@
const snowpackManifest = JSON.parse(fs.readFileSync(path.join(__dirname, '../../snowpack/package.json'), 'utf8')); const snowpackManifest = JSON.parse(
fs.readFileSync(path.join(__dirname, '../../snowpack/package.json'), 'utf8'),
);
export default snowpackManifest.version; export default snowpackManifest.version;

View file

@ -1,8 +1,5 @@
{ {
"ignoreChanges": [ "ignoreChanges": ["**/test/**", "**/*.md"],
"**/test/**",
"**/*.md"
],
"useWorkspaces": true, "useWorkspaces": true,
"version": "4.0.0" "version": "4.0.0"
} }

View file

@ -5,11 +5,11 @@
"release": "yarn build && yarn changeset publish", "release": "yarn build && yarn changeset publish",
"build": "yarn build:core", "build": "yarn build:core",
"build:core": "lerna run build --scope astro --scope astro-parser --scope create-astro", "build:core": "lerna run build --scope astro --scope astro-parser --scope create-astro",
"format": "prettier -w '**/*.{js,jsx,ts,tsx,md,json}'",
"lint": "eslint 'packages/**/*.ts'", "lint": "eslint 'packages/**/*.ts'",
"test": "yarn test:core && yarn test:prettier", "test": "yarn test:core && yarn test:prettier",
"test:core": "cd packages/astro && npm test", "test:core": "cd packages/astro && npm test",
"test:prettier": "cd tools/prettier-plugin-astro && npm test", "test:prettier": "cd tools/prettier-plugin-astro && npm test"
"format": "prettier -w '**/*.{js,jsx,ts,tsx,md,json}'"
}, },
"workspaces": [ "workspaces": [
"packages/*", "packages/*",

View file

@ -16,7 +16,6 @@ import { generateRSS } from './build/rss.js';
import { generateSitemap } from './build/sitemap.js'; import { generateSitemap } from './build/sitemap.js';
import { collectStatics } from './build/static.js'; import { collectStatics } from './build/static.js';
import { canonicalURL } from './build/util.js'; import { canonicalURL } from './build/util.js';
import { pathToFileURL } from 'node:url';
const { mkdir, readFile, writeFile } = fsPromises; const { mkdir, readFile, writeFile } = fsPromises;
@ -69,8 +68,8 @@ async function writeFilep(outPath: URL, bytes: string | Buffer, encoding: 'utf8'
interface WriteResultOptions { interface WriteResultOptions {
srcPath: string; srcPath: string;
result: LoadResult; result: LoadResult;
outPath: URL, outPath: URL;
encoding: null|'utf8' encoding: null | 'utf8';
} }
/** Utility for writing a build result to disk */ /** Utility for writing a build result to disk */

View file

@ -34,7 +34,7 @@ function resolveArgs(flags: Arguments): CLIState {
projectRoot: typeof flags.projectRoot === 'string' ? flags.projectRoot : undefined, projectRoot: typeof flags.projectRoot === 'string' ? flags.projectRoot : undefined,
sitemap: typeof flags.sitemap === 'boolean' ? flags.sitemap : undefined, sitemap: typeof flags.sitemap === 'boolean' ? flags.sitemap : undefined,
port: typeof flags.port === 'number' ? flags.port : undefined, port: typeof flags.port === 'number' ? flags.port : undefined,
config: typeof flags.config === 'string' ? flags.config : undefined config: typeof flags.config === 'string' ? flags.config : undefined,
}; };
if (flags.version) { if (flags.version) {

View file

@ -15,7 +15,7 @@ import { encodeAstroMdx } from './markdown/micromark-mdx-astro.js';
import { transform } from './transform/index.js'; import { transform } from './transform/index.js';
import { codegen } from './codegen/index.js'; import { codegen } from './codegen/index.js';
export { scopeRule } from './transform/postcss-scoped-styles/index.js' export { scopeRule } from './transform/postcss-scoped-styles/index.js';
/** Return Astro internal import URL */ /** Return Astro internal import URL */
function internalImport(internalPath: string) { function internalImport(internalPath: string) {

View file

@ -27,7 +27,7 @@ function validateConfig(config: any): void {
} }
if (typeof config.devOptions?.port !== 'number') { if (typeof config.devOptions?.port !== 'number') {
throw new Error(`[astro config] devOptions.port: Expected number, received ${type(config.devOptions?.port)}`) throw new Error(`[astro config] devOptions.port: Expected number, received ${type(config.devOptions?.port)}`);
} }
} }

View file

@ -49,6 +49,6 @@ export const childrenToH = moize.deep(function childrenToH(renderer: ComponentRe
}; };
return tree.map((subtree) => { return tree.map((subtree) => {
if (subtree.type === 'text') return JSON.stringify(subtree.value); if (subtree.type === 'text') return JSON.stringify(subtree.value);
return toH(innerH, subtree).__SERIALIZED return toH(innerH, subtree).__SERIALIZED;
}); });
}); });

View file

@ -140,5 +140,5 @@ export function trapWarn(cb: (...args: any[]) => void = () =>{}) {
console.warn = function (...args: any[]) { console.warn = function (...args: any[]) {
cb(...args); cb(...args);
}; };
return () => console.warn = warn; return () => (console.warn = warn);
} }

View file

@ -207,7 +207,7 @@ async function load(config: RuntimeConfig, rawPathname: string | undefined): Pro
let html = (await mod.exports.__renderPage({ let html = (await mod.exports.__renderPage({
request: { request: {
// params should go here when implemented // params should go here when implemented
url: requestURL url: requestURL,
}, },
children: [], children: [],
props: { collection }, props: { collection },

View file

@ -97,9 +97,9 @@ export function searchForPage(url: URL, astroRoot: URL): SearchResult {
statusCode: 200, statusCode: 200,
location: { location: {
fileURL: new URL('./frontend/500.astro', import.meta.url), fileURL: new URL('./frontend/500.astro', import.meta.url),
snowpackURL: `/_astro_internal/500.astro.js` snowpackURL: `/_astro_internal/500.astro.js`,
}, },
pathname: reqPath pathname: reqPath,
}; };
} }

View file

@ -4,7 +4,6 @@ import * as assert from 'uvu/assert';
import { loadConfig } from '#astro/config'; import { loadConfig } from '#astro/config';
import { createRuntime } from '#astro/runtime'; import { createRuntime } from '#astro/runtime';
const DType = suite('doctype'); const DType = suite('doctype');
let runtime, setupError; let runtime, setupError;

View file

@ -1,5 +1,5 @@
import { h } from 'preact'; import { h } from 'preact';
export default function PreactComponent({ children }) { export default function PreactComponent({ children }) {
return <div id="preact">{children}</div> return <div id="preact">{children}</div>;
} }

View file

@ -5,5 +5,5 @@ export default function() {
<div> <div>
<button type="button">Increment -</button> <button type="button">Increment -</button>
</div> </div>
) );
} }

View file

@ -1,5 +1,5 @@
import { h } from 'preact'; import { h } from 'preact';
export default function ({ name }) { export default function ({ name }) {
return <div id={name}>{name}</div> return <div id={name}>{name}</div>;
} }

View file

@ -1,7 +1,5 @@
import { h } from 'preact'; import { h } from 'preact';
export default function (props) { export default function (props) {
return ( return <div id="fallback">{import.meta.env.astro ? 'static' : 'dynamic'}</div>;
<div id="fallback">{import.meta.env.astro ? 'static' : 'dynamic'}</div> }
);
};

View file

@ -1,5 +1,5 @@
import { h } from 'preact'; import { h } from 'preact';
export default function () { export default function () {
return <div id="test">Testing</div> return <div id="test">Testing</div>;
} }

View file

@ -1,5 +1,5 @@
import { h } from 'preact'; import { h } from 'preact';
export default function ({ name }) { export default function ({ name }) {
return <div id="test">Hello {name}</div> return <div id="test">Hello {name}</div>;
} }

View file

@ -4,4 +4,3 @@ import cheerio from 'cheerio';
export function doc(html) { export function doc(html) {
return cheerio.load(html); return cheerio.load(html);
} }

View file

@ -1,6 +1,7 @@
# create-astro # create-astro
## 0.1.0 ## 0.1.0
### Minor Changes ### Minor Changes
- ed63132: Added **interactive mode** with a fesh new UI. - ed63132: Added **interactive mode** with a fesh new UI.

View file

@ -1,12 +1,15 @@
# create-astro # create-astro
## Scaffolding for Astro projects ## Scaffolding for Astro projects
**With NPM:** **With NPM:**
```bash ```bash
npm init astro npm init astro
``` ```
**With Yarn:** **With Yarn:**
```bash ```bash
yarn create astro yarn create astro
``` ```

View file

@ -20,28 +20,33 @@ interface Context {
const getStep = ({ projectName, projectExists: exists, template, force, ready }: Context) => { const getStep = ({ projectName, projectExists: exists, template, force, ready }: Context) => {
switch (true) { switch (true) {
case !projectName: return { case !projectName:
return {
key: 'projectName', key: 'projectName',
Component: ProjectName Component: ProjectName,
}; };
case projectName && exists === true && typeof force === 'undefined': return { case projectName && exists === true && typeof force === 'undefined':
return {
key: 'force', key: 'force',
Component: Confirm Component: Confirm,
} };
case (exists === false || force) && !template: return { case (exists === false || force) && !template:
return {
key: 'template', key: 'template',
Component: Template Component: Template,
}; };
case !ready: return { case !ready:
return {
key: 'install', key: 'install',
Component: Install Component: Install,
}; };
default: return { default:
return {
key: 'final', key: 'final',
Component: Finalize Component: Finalize,
} };
}
} }
};
const App: FC<{ context: Context }> = ({ context }) => { const App: FC<{ context: Context }> = ({ context }) => {
const [state, setState] = React.useState(context); const [state, setState] = React.useState(context);
@ -49,15 +54,15 @@ const App: FC<{ context: Context }> = ({ context }) => {
const onSubmit = (value: string | boolean) => { const onSubmit = (value: string | boolean) => {
const { key } = step.current; const { key } = step.current;
const newState = { ...state, [key]: value }; const newState = { ...state, [key]: value };
step.current = getStep(newState) step.current = getStep(newState);
setState(newState) setState(newState);
} };
useEffect(() => { useEffect(() => {
let isSubscribed = true let isSubscribed = true;
if (state.projectName && typeof state.projectExists === 'undefined') { if (state.projectName && typeof state.projectExists === 'undefined') {
const newState = { ...state, projectExists: !isEmpty(state.projectName) }; const newState = { ...state, projectExists: !isEmpty(state.projectName) };
step.current = getStep(newState) step.current = getStep(newState);
if (isSubscribed) { if (isSubscribed) {
setState(newState); setState(newState);
} }
@ -67,7 +72,7 @@ const App: FC<{ context: Context }> = ({ context }) => {
if (state.force) emptyDir(state.projectName); if (state.force) emptyDir(state.projectName);
prepareTemplate(context.use, state.template, state.projectName).then(() => { prepareTemplate(context.use, state.template, state.projectName).then(() => {
if (isSubscribed) { if (isSubscribed) {
setState(v => { setState((v) => {
const newState = { ...v, ready: true }; const newState = { ...v, ready: true };
step.current = getStep(newState); step.current = getStep(newState);
return newState; return newState;
@ -78,7 +83,7 @@ const App: FC<{ context: Context }> = ({ context }) => {
return () => { return () => {
isSubscribed = false; isSubscribed = false;
} };
}, [state]); }, [state]);
const { Component } = step.current; const { Component } = step.current;
@ -87,7 +92,7 @@ const App: FC<{ context: Context }> = ({ context }) => {
<Header context={state} /> <Header context={state} />
<Component context={state} onSubmit={onSubmit} /> <Component context={state} onSubmit={onSubmit} />
</> </>
) );
}; };
export default App; export default App;

View file

@ -31,7 +31,7 @@ const Confirm: FC<{ message?: any; context: any; onSubmit: (value: boolean) => v
items={[ items={[
{ {
value: false, value: false,
label: 'no' label: 'no',
}, },
{ {
value: true, value: true,

View file

@ -2,4 +2,4 @@ import React from 'react';
import { Text } from 'ink'; import { Text } from 'ink';
import { isWin } from '../utils'; import { isWin } from '../utils';
export default ({ children }) => isWin() ? null : <Text>{children}</Text> export default ({ children }) => (isWin() ? null : <Text>{children}</Text>);

View file

@ -2,8 +2,11 @@ import React, { FC } from 'react';
import { Box, Text } from 'ink'; import { Box, Text } from 'ink';
import { isDone } from '../utils'; import { isDone } from '../utils';
const Exit: FC<{ didError?: boolean }> = ({ didError }) => isDone ? null : <Box marginTop={1} display="flex"> const Exit: FC<{ didError?: boolean }> = ({ didError }) =>
<Text color={didError ? "#FF1639" : "#FFBE2D"}>[abort]</Text> isDone ? null : (
<Box marginTop={1} display="flex">
<Text color={didError ? '#FF1639' : '#FFBE2D'}>[abort]</Text>
<Text> astro cancelled</Text> <Text> astro cancelled</Text>
</Box> </Box>
);
export default Exit; export default Exit;

View file

@ -8,10 +8,14 @@ const Finalize: FC<{ context: any }> = ({ context: { use, projectName } }) => {
process.exit(0); process.exit(0);
}, []); }, []);
return <> return (
<>
<Box display="flex"> <Box display="flex">
<Text color="#17C083">{'[ yes ]'}</Text> <Text color="#17C083">{'[ yes ]'}</Text>
<Text> Project initialized at <Text color="#3894FF">./{projectName}</Text></Text> <Text>
{' '}
Project initialized at <Text color="#3894FF">./{projectName}</Text>
</Text>
</Box> </Box>
<Box display="flex" marginY={1}> <Box display="flex" marginY={1}>
<Text dimColor>{'[ tip ]'}</Text> <Text dimColor>{'[ tip ]'}</Text>
@ -21,7 +25,8 @@ const Finalize: FC<{ context: any }> = ({ context: { use, projectName } }) => {
<Text color="#3894FF">{use} start</Text> <Text color="#3894FF">{use} start</Text>
</Box> </Box>
</Box> </Box>
</>; </>
);
}; };
export default Finalize; export default Finalize;

View file

@ -3,18 +3,26 @@ import { Box, Text } from 'ink';
const getMessage = ({ projectName, template }) => { const getMessage = ({ projectName, template }) => {
switch (true) { switch (true) {
case !projectName: return <Text dimColor>Gathering mission details</Text>; case !projectName:
case !template: return <Text dimColor>Optimizing navigational system</Text>; return <Text dimColor>Gathering mission details</Text>;
default: return <Text color="black" backgroundColor="white"> {projectName} </Text> case !template:
} return <Text dimColor>Optimizing navigational system</Text>;
default:
return (
<Text color="black" backgroundColor="white">
{' '}
{projectName}{' '}
</Text>
);
} }
};
const Header: React.FC<{ context: any }> = ({ context }) => ( const Header: React.FC<{ context: any }> = ({ context }) => (
<Box width={48} display="flex" marginY={1}> <Box width={48} display="flex" marginY={1}>
<Text backgroundColor="#882DE7" color="white">{' astro '}</Text> <Text backgroundColor="#882DE7" color="white">
<Box marginLeft={1}> {' astro '}
{getMessage(context)} </Text>
<Box marginLeft={1}>{getMessage(context)}</Box>
</Box> </Box>
</Box> );
)
export default Header; export default Header;

View file

@ -2,37 +2,48 @@ import React, { FC } from 'react';
import { Box, Text } from 'ink'; import { Box, Text } from 'ink';
import { ARGS, ARG } from '../config'; import { ARGS, ARG } from '../config';
const Type: FC<{ type: any, enum?: string[] }> = ({ type, enum: e }) => { const Type: FC<{ type: any; enum?: string[] }> = ({ type, enum: e }) => {
if (type === Boolean) { if (type === Boolean) {
return <> return (
<>
<Text color="#3894FF">true</Text> <Text color="#3894FF">true</Text>
<Text dimColor>|</Text> <Text dimColor>|</Text>
<Text color="#3894FF">false</Text> <Text color="#3894FF">false</Text>
</> </>
);
} }
if (e?.length > 0) { if (e?.length > 0) {
return <> return (
<>
{e.map((item, i, { length: len }) => { {e.map((item, i, { length: len }) => {
if (i !== len - 1) { if (i !== len - 1) {
return <Box key={item}> return (
<Box key={item}>
<Text color="#17C083">{item}</Text> <Text color="#17C083">{item}</Text>
<Text dimColor>|</Text> <Text dimColor>|</Text>
</Box> </Box>
);
} }
return <Text color="#17C083" key={item}>{item}</Text> return (
<Text color="#17C083" key={item}>
{item}
</Text>
);
})} })}
</> </>
);
} }
return <Text color="#3894FF">string</Text>; return <Text color="#3894FF">string</Text>;
} };
const Command: FC<{ name: string, info: ARG }> = ({ name, info: { alias, description, type, enum: e } }) => { const Command: FC<{ name: string; info: ARG }> = ({ name, info: { alias, description, type, enum: e } }) => {
return ( return (
<Box display="flex" alignItems="flex-start"> <Box display="flex" alignItems="flex-start">
<Box width={24} display="flex" flexGrow={0}> <Box width={24} display="flex" flexGrow={0}>
<Text color="whiteBright">--{name}</Text>{alias && <Text dimColor> -{alias}</Text>} <Text color="whiteBright">--{name}</Text>
{alias && <Text dimColor> -{alias}</Text>}
</Box> </Box>
<Box width={24}> <Box width={24}>
<Type type={type} enum={e} /> <Type type={type} enum={e} />
@ -42,21 +53,28 @@ const Command: FC<{ name: string, info: ARG }> = ({ name, info: { alias, descrip
</Box> </Box>
</Box> </Box>
); );
} };
const Help: FC<{ context: any }> = ({ context: { templates } }) => { const Help: FC<{ context: any }> = ({ context: { templates } }) => {
return ( return (
<> <>
<Box width={48} display="flex" marginY={1}> <Box width={48} display="flex" marginY={1}>
<Text backgroundColor="#882DE7" color="white">{' astro '}</Text> <Text backgroundColor="#882DE7" color="white">
{' astro '}
</Text>
<Box marginLeft={1}> <Box marginLeft={1}>
<Text color="black" backgroundColor="white"> help </Text> <Text color="black" backgroundColor="white">
{' '}
help{' '}
</Text>
</Box> </Box>
</Box> </Box>
<Box marginBottom={1} marginLeft={2} display="flex" flexDirection="column"> <Box marginBottom={1} marginLeft={2} display="flex" flexDirection="column">
{Object.entries(ARGS).map(([name, info]) => <Command key={name} name={name} info={name === 'template' ? { ...info, enum: templates.map(({ value }) => value) } : info} /> )} {Object.entries(ARGS).map(([name, info]) => (
<Command key={name} name={name} info={name === 'template' ? { ...info, enum: templates.map(({ value }) => value) } : info} />
))}
</Box> </Box>
</> </>
) );
}; };
export default Help; export default Help;

View file

@ -4,16 +4,20 @@ import Spacer from './Spacer';
import Spinner from './Spinner'; import Spinner from './Spinner';
const Install: FC<{ context: any }> = ({ context: { use } }) => { const Install: FC<{ context: any }> = ({ context: { use } }) => {
return <> return (
<>
<Box display="flex"> <Box display="flex">
<Spinner /> <Spinner />
<Text> Initiating launch sequence...</Text> <Text> Initiating launch sequence...</Text>
</Box> </Box>
<Box> <Box>
<Spacer /> <Spacer />
<Text color="white" dimColor>(aka running <Text color="#17C083">{use === 'npm' ? 'npm install' : 'yarn'}</Text>)</Text> <Text color="white" dimColor>
(aka running <Text color="#17C083">{use === 'npm' ? 'npm install' : 'yarn'}</Text>)
</Text>
</Box> </Box>
</>; </>
);
}; };
export default Install; export default Install;

View file

@ -9,7 +9,8 @@ const ProjectName: FC<{ onSubmit: (value: string) => void }> = ({ onSubmit }) =>
const [value, setValue] = React.useState(''); const [value, setValue] = React.useState('');
const handleSubmit = (v: string) => onSubmit(v); const handleSubmit = (v: string) => onSubmit(v);
return <> return (
<>
<Box display="flex"> <Box display="flex">
<Text color="#17C083">{'[query]'}</Text> <Text color="#17C083">{'[query]'}</Text>
<Text> What is your project name?</Text> <Text> What is your project name?</Text>
@ -18,7 +19,8 @@ const ProjectName: FC<{ onSubmit: (value: string) => void }> = ({ onSubmit }) =>
<Spacer /> <Spacer />
<Input value={value} onChange={setValue} onSubmit={handleSubmit} placeholder="my-project" /> <Input value={value} onChange={setValue} onSubmit={handleSubmit} placeholder="my-project" />
</Box> </Box>
</>; </>
);
}; };
export default ProjectName; export default ProjectName;

View file

@ -9,24 +9,24 @@ interface Props {
label: string; label: string;
description?: string; description?: string;
} }
const Indicator: FC<Props> = ({ isSelected }) => isSelected ? <Text color="#3894FF">[ </Text> : <Text> </Text> const Indicator: FC<Props> = ({ isSelected }) => (isSelected ? <Text color="#3894FF">[ </Text> : <Text> </Text>);
const Item: FC<Props> = ({ isSelected = false, label, description }) => ( const Item: FC<Props> = ({ isSelected = false, label, description }) => (
<Box display="flex"> <Box display="flex">
<Text color={isSelected ? '#3894FF' : 'white'} dimColor={!isSelected}>{label}</Text> <Text color={isSelected ? '#3894FF' : 'white'} dimColor={!isSelected}>
{label}
</Text>
{isSelected && description && typeof description === 'string' && <Text> {description}</Text>} {isSelected && description && typeof description === 'string' && <Text> {description}</Text>}
{isSelected && description && typeof description !== 'string' && <Box marginLeft={1}>{description}</Box>} {isSelected && description && typeof description !== 'string' && <Box marginLeft={1}>{description}</Box>}
</Box> </Box>
); );
interface SelectProps { interface SelectProps {
items: { value: string|number|boolean, label: string, description?: any }[] items: { value: string | number | boolean; label: string; description?: any }[];
onSelect(value: string | number | boolean): void; onSelect(value: string | number | boolean): void;
} }
const CustomSelect: FC<SelectProps> = ({ items, onSelect }) => { const CustomSelect: FC<SelectProps> = ({ items, onSelect }) => {
const handleSelect = ({ value }) => onSelect(value); const handleSelect = ({ value }) => onSelect(value);
return ( return <Select indicatorComponent={Indicator} itemComponent={Item} items={items} onSelect={handleSelect} />;
<Select indicatorComponent={Indicator} itemComponent={Item} items={items} onSelect={handleSelect} /> };
)
}
export default CustomSelect; export default CustomSelect;

View file

@ -1,5 +1,5 @@
import React, { FC } from 'react'; import React, { FC } from 'react';
import { Box } from 'ink'; import { Box } from 'ink';
const Spacer: FC<{ width?: number }> = ({ width = 8 }) => <Box width={width} /> const Spacer: FC<{ width?: number }> = ({ width = 8 }) => <Box width={width} />;
export default Spacer; export default Spacer;

View file

@ -6,14 +6,14 @@ const Spinner: FC<{ type?: keyof typeof spinners }> = ({ type = 'countdown' }) =
const [i, setI] = useState(0); const [i, setI] = useState(0);
useEffect(() => { useEffect(() => {
const _ = setInterval(() => { const _ = setInterval(() => {
setI(v => (v < frames.length - 1) ? v + 1 : 0) setI((v) => (v < frames.length - 1 ? v + 1 : 0));
}, interval) }, interval);
return () => clearInterval(_); return () => clearInterval(_);
}, []) }, []);
return frames[i] return frames[i];
} };
const spinners = { const spinners = {
countdown: { countdown: {
@ -35,73 +35,73 @@ const spinners = {
<Text backgroundColor="#882DE7">{' '}</Text> <Text backgroundColor="#882DE7">{' '}</Text>
</Box>, </Box>,
<Box display="flex"> <Box display="flex">
<Text backgroundColor="#6858F1">{' '}</Text> <Text backgroundColor="#6858F1"> </Text>
<Text backgroundColor="#882DE7">{' '}</Text> <Text backgroundColor="#882DE7">{' '}</Text>
</Box>, </Box>,
<Box display="flex"> <Box display="flex">
<Text backgroundColor="#5076F9">{' '}</Text> <Text backgroundColor="#5076F9"> </Text>
<Text backgroundColor="#6858F1">{' '}</Text> <Text backgroundColor="#6858F1"> </Text>
<Text backgroundColor="#882DE7">{' '}</Text> <Text backgroundColor="#882DE7">{' '}</Text>
</Box>, </Box>,
<Box display="flex"> <Box display="flex">
<Text backgroundColor="#3894FF">{' '}</Text> <Text backgroundColor="#3894FF"> </Text>
<Text backgroundColor="#5076F9">{' '}</Text> <Text backgroundColor="#5076F9"> </Text>
<Text backgroundColor="#6858F1">{' '}</Text> <Text backgroundColor="#6858F1"> </Text>
<Text backgroundColor="#882DE7">{' '}</Text> <Text backgroundColor="#882DE7">{' '}</Text>
</Box>, </Box>,
<Box display="flex"> <Box display="flex">
<Text backgroundColor="#2CA5D2">{' '}</Text> <Text backgroundColor="#2CA5D2"> </Text>
<Text backgroundColor="#3894FF">{' '}</Text> <Text backgroundColor="#3894FF"> </Text>
<Text backgroundColor="#5076F9">{' '}</Text> <Text backgroundColor="#5076F9"> </Text>
<Text backgroundColor="#6858F1">{' '}</Text> <Text backgroundColor="#6858F1"> </Text>
<Text backgroundColor="#882DE7">{' '}</Text> <Text backgroundColor="#882DE7">{' '}</Text>
</Box>, </Box>,
<Box display="flex"> <Box display="flex">
<Text backgroundColor="#23B1AF">{' '}</Text> <Text backgroundColor="#23B1AF"> </Text>
<Text backgroundColor="#2CA5D2">{' '}</Text> <Text backgroundColor="#2CA5D2"> </Text>
<Text backgroundColor="#3894FF">{' '}</Text> <Text backgroundColor="#3894FF"> </Text>
<Text backgroundColor="#5076F9">{' '}</Text> <Text backgroundColor="#5076F9"> </Text>
<Text backgroundColor="#6858F1">{' '}</Text> <Text backgroundColor="#6858F1"> </Text>
<Text backgroundColor="#882DE7">{' '}</Text> <Text backgroundColor="#882DE7">{' '}</Text>
</Box>, </Box>,
<Box display="flex"> <Box display="flex">
<Text backgroundColor="#17C083">{' '}</Text> <Text backgroundColor="#17C083"> </Text>
<Text backgroundColor="#23B1AF">{' '}</Text> <Text backgroundColor="#23B1AF"> </Text>
<Text backgroundColor="#2CA5D2">{' '}</Text> <Text backgroundColor="#2CA5D2"> </Text>
<Text backgroundColor="#3894FF">{' '}</Text> <Text backgroundColor="#3894FF"> </Text>
<Text backgroundColor="#5076F9">{' '}</Text> <Text backgroundColor="#5076F9"> </Text>
<Text backgroundColor="#6858F1">{' '}</Text> <Text backgroundColor="#6858F1"> </Text>
<Text backgroundColor="#882DE7">{' '}</Text> <Text backgroundColor="#882DE7"> </Text>
</Box>, </Box>,
<Box display="flex"> <Box display="flex">
<Text backgroundColor="#17C083">{' '}</Text> <Text backgroundColor="#17C083">{' '}</Text>
<Text backgroundColor="#23B1AF">{' '}</Text> <Text backgroundColor="#23B1AF"> </Text>
<Text backgroundColor="#2CA5D2">{' '}</Text> <Text backgroundColor="#2CA5D2"> </Text>
<Text backgroundColor="#3894FF">{' '}</Text> <Text backgroundColor="#3894FF"> </Text>
<Text backgroundColor="#5076F9">{' '}</Text> <Text backgroundColor="#5076F9"> </Text>
<Text backgroundColor="#6858F1">{' '}</Text> <Text backgroundColor="#6858F1"> </Text>
</Box>, </Box>,
<Box display="flex"> <Box display="flex">
<Text backgroundColor="#17C083">{' '}</Text> <Text backgroundColor="#17C083">{' '}</Text>
<Text backgroundColor="#23B1AF">{' '}</Text> <Text backgroundColor="#23B1AF"> </Text>
<Text backgroundColor="#2CA5D2">{' '}</Text> <Text backgroundColor="#2CA5D2"> </Text>
<Text backgroundColor="#3894FF">{' '}</Text> <Text backgroundColor="#3894FF"> </Text>
<Text backgroundColor="#5076F9">{' '}</Text> <Text backgroundColor="#5076F9"> </Text>
</Box>, </Box>,
<Box display="flex"> <Box display="flex">
<Text backgroundColor="#17C083">{' '}</Text> <Text backgroundColor="#17C083">{' '}</Text>
<Text backgroundColor="#23B1AF">{' '}</Text> <Text backgroundColor="#23B1AF"> </Text>
<Text backgroundColor="#2CA5D2">{' '}</Text> <Text backgroundColor="#2CA5D2"> </Text>
<Text backgroundColor="#3894FF">{' '}</Text> <Text backgroundColor="#3894FF"> </Text>
</Box>, </Box>,
<Box display="flex"> <Box display="flex">
<Text backgroundColor="#17C083">{' '}</Text> <Text backgroundColor="#17C083">{' '}</Text>
<Text backgroundColor="#23B1AF">{' '}</Text> <Text backgroundColor="#23B1AF"> </Text>
<Text backgroundColor="#2CA5D2">{' '}</Text> <Text backgroundColor="#2CA5D2"> </Text>
</Box>, </Box>,
<Box display="flex"> <Box display="flex">
<Text backgroundColor="#17C083">{' '}</Text> <Text backgroundColor="#17C083">{' '}</Text>
<Text backgroundColor="#23B1AF">{' '}</Text> <Text backgroundColor="#23B1AF"> </Text>
</Box>, </Box>,
<Box display="flex"> <Box display="flex">
<Text backgroundColor="#17C083">{' '}</Text> <Text backgroundColor="#17C083">{' '}</Text>
@ -122,79 +122,79 @@ const spinners = {
<Text backgroundColor="#17C083">{' '}</Text> <Text backgroundColor="#17C083">{' '}</Text>
</Box>, </Box>,
<Box display="flex"> <Box display="flex">
<Text backgroundColor="#23B1AF">{' '}</Text> <Text backgroundColor="#23B1AF"> </Text>
<Text backgroundColor="#17C083">{' '}</Text> <Text backgroundColor="#17C083">{' '}</Text>
</Box>, </Box>,
<Box display="flex"> <Box display="flex">
<Text backgroundColor="#2CA5D2">{' '}</Text> <Text backgroundColor="#2CA5D2"> </Text>
<Text backgroundColor="#23B1AF">{' '}</Text> <Text backgroundColor="#23B1AF"> </Text>
<Text backgroundColor="#17C083">{' '}</Text> <Text backgroundColor="#17C083">{' '}</Text>
</Box>, </Box>,
<Box display="flex"> <Box display="flex">
<Text backgroundColor="#3894FF">{' '}</Text> <Text backgroundColor="#3894FF"> </Text>
<Text backgroundColor="#2CA5D2">{' '}</Text> <Text backgroundColor="#2CA5D2"> </Text>
<Text backgroundColor="#23B1AF">{' '}</Text> <Text backgroundColor="#23B1AF"> </Text>
<Text backgroundColor="#17C083">{' '}</Text> <Text backgroundColor="#17C083">{' '}</Text>
</Box>, </Box>,
<Box display="flex"> <Box display="flex">
<Text backgroundColor="#5076F9">{' '}</Text> <Text backgroundColor="#5076F9"> </Text>
<Text backgroundColor="#3894FF">{' '}</Text> <Text backgroundColor="#3894FF"> </Text>
<Text backgroundColor="#2CA5D2">{' '}</Text> <Text backgroundColor="#2CA5D2"> </Text>
<Text backgroundColor="#23B1AF">{' '}</Text> <Text backgroundColor="#23B1AF"> </Text>
<Text backgroundColor="#17C083">{' '}</Text> <Text backgroundColor="#17C083">{' '}</Text>
</Box>, </Box>,
<Box display="flex"> <Box display="flex">
<Text backgroundColor="#6858F1">{' '}</Text> <Text backgroundColor="#6858F1"> </Text>
<Text backgroundColor="#5076F9">{' '}</Text> <Text backgroundColor="#5076F9"> </Text>
<Text backgroundColor="#3894FF">{' '}</Text> <Text backgroundColor="#3894FF"> </Text>
<Text backgroundColor="#2CA5D2">{' '}</Text> <Text backgroundColor="#2CA5D2"> </Text>
<Text backgroundColor="#23B1AF">{' '}</Text> <Text backgroundColor="#23B1AF"> </Text>
<Text backgroundColor="#17C083">{' '}</Text> <Text backgroundColor="#17C083">{' '}</Text>
</Box>, </Box>,
<Box display="flex">
<Text backgroundColor="#882DE7"> </Text>
<Text backgroundColor="#6858F1"> </Text>
<Text backgroundColor="#5076F9"> </Text>
<Text backgroundColor="#3894FF"> </Text>
<Text backgroundColor="#2CA5D2"> </Text>
<Text backgroundColor="#23B1AF"> </Text>
<Text backgroundColor="#17C083"> </Text>
</Box>,
<Box display="flex"> <Box display="flex">
<Text backgroundColor="#882DE7">{' '}</Text> <Text backgroundColor="#882DE7">{' '}</Text>
<Text backgroundColor="#6858F1">{' '}</Text> <Text backgroundColor="#6858F1"> </Text>
<Text backgroundColor="#5076F9">{' '}</Text> <Text backgroundColor="#5076F9"> </Text>
<Text backgroundColor="#3894FF">{' '}</Text> <Text backgroundColor="#3894FF"> </Text>
<Text backgroundColor="#2CA5D2">{' '}</Text> <Text backgroundColor="#2CA5D2"> </Text>
<Text backgroundColor="#23B1AF">{' '}</Text> <Text backgroundColor="#23B1AF"> </Text>
<Text backgroundColor="#17C083">{' '}</Text>
</Box>, </Box>,
<Box display="flex"> <Box display="flex">
<Text backgroundColor="#882DE7">{' '}</Text> <Text backgroundColor="#882DE7">{' '}</Text>
<Text backgroundColor="#6858F1">{' '}</Text> <Text backgroundColor="#6858F1"> </Text>
<Text backgroundColor="#5076F9">{' '}</Text> <Text backgroundColor="#5076F9"> </Text>
<Text backgroundColor="#3894FF">{' '}</Text> <Text backgroundColor="#3894FF"> </Text>
<Text backgroundColor="#2CA5D2">{' '}</Text> <Text backgroundColor="#2CA5D2"> </Text>
<Text backgroundColor="#23B1AF">{' '}</Text>
</Box>, </Box>,
<Box display="flex"> <Box display="flex">
<Text backgroundColor="#882DE7">{' '}</Text> <Text backgroundColor="#882DE7">{' '}</Text>
<Text backgroundColor="#6858F1">{' '}</Text> <Text backgroundColor="#6858F1"> </Text>
<Text backgroundColor="#5076F9">{' '}</Text> <Text backgroundColor="#5076F9"> </Text>
<Text backgroundColor="#3894FF">{' '}</Text> <Text backgroundColor="#3894FF"> </Text>
<Text backgroundColor="#2CA5D2">{' '}</Text>
</Box>, </Box>,
<Box display="flex"> <Box display="flex">
<Text backgroundColor="#882DE7">{' '}</Text> <Text backgroundColor="#882DE7">{' '}</Text>
<Text backgroundColor="#6858F1">{' '}</Text> <Text backgroundColor="#6858F1"> </Text>
<Text backgroundColor="#5076F9">{' '}</Text> <Text backgroundColor="#5076F9"> </Text>
<Text backgroundColor="#3894FF">{' '}</Text>
</Box>, </Box>,
<Box display="flex"> <Box display="flex">
<Text backgroundColor="#882DE7">{' '}</Text> <Text backgroundColor="#882DE7">{' '}</Text>
<Text backgroundColor="#6858F1">{' '}</Text> <Text backgroundColor="#6858F1"> </Text>
<Text backgroundColor="#5076F9">{' '}</Text>
</Box>,
<Box display="flex">
<Text backgroundColor="#882DE7">{' '}</Text>
<Text backgroundColor="#6858F1">{' '}</Text>
</Box>, </Box>,
<Box display="flex"> <Box display="flex">
<Text backgroundColor="#882DE7">{' '}</Text> <Text backgroundColor="#882DE7">{' '}</Text>
</Box>, </Box>,
] ],
} },
} };
export default Spinner; export default Spinner;

View file

@ -3,7 +3,7 @@ import { Box, Text } from 'ink';
import Spacer from './Spacer'; import Spacer from './Spacer';
import Select from './Select'; import Select from './Select';
const Template: FC<{ context: any, onSubmit: (value: string) => void }> = ({ context: { templates }, onSubmit }) => { const Template: FC<{ context: any; onSubmit: (value: string) => void }> = ({ context: { templates }, onSubmit }) => {
const items = templates.map(({ title: label, ...rest }) => ({ ...rest, label })); const items = templates.map(({ title: label, ...rest }) => ({ ...rest, label }));
return ( return (

View file

@ -8,35 +8,35 @@ export interface ARG {
} }
export const ARGS: Record<string, ARG> = { export const ARGS: Record<string, ARG> = {
'template': { template: {
type: String, type: String,
description: 'specifies template to use' description: 'specifies template to use',
}, },
'use': { use: {
type: String, type: String,
enum: ['npm', 'yarn'], enum: ['npm', 'yarn'],
description: 'specifies package manager to use' description: 'specifies package manager to use',
}, },
'run': { run: {
type: Boolean, type: Boolean,
description: 'should dependencies be installed automatically?' description: 'should dependencies be installed automatically?',
}, },
'force': { force: {
type: Boolean, type: Boolean,
alias: 'f', alias: 'f',
description: 'should existing files be overwritten?' description: 'should existing files be overwritten?',
}, },
'version': { version: {
type: Boolean, type: Boolean,
alias: 'v', alias: 'v',
description: 'prints current version' description: 'prints current version',
}, },
'help': { help: {
type: Boolean, type: Boolean,
alias: 'h', alias: 'h',
description: 'prints this message' description: 'prints this message',
} },
} };
export const args = Object.entries(ARGS).reduce((acc, [name, info]) => { export const args = Object.entries(ARGS).reduce((acc, [name, info]) => {
const key = `--${name}`; const key = `--${name}`;
@ -45,5 +45,5 @@ export const args = Object.entries(ARGS).reduce((acc, [name, info]) => {
if (info.alias) { if (info.alias) {
spec[`-${info.alias}`] = key; spec[`-${info.alias}`] = key;
} }
return spec return spec;
}, {} as arg.Spec); }, {} as arg.Spec);

View file

@ -18,7 +18,7 @@ export default async function createAstro() {
} }
const templates = await getTemplates(); const templates = await getTemplates();
if (args['--help']) { if (args['--help']) {
return render(<Help context={{ templates }} />) return render(<Help context={{ templates }} />);
} }
const pkgManager = /yarn/.test(process.env.npm_execpath) ? 'yarn' : 'npm'; const pkgManager = /yarn/.test(process.env.npm_execpath) ? 'yarn' : 'npm';
@ -32,15 +32,15 @@ export default async function createAstro() {
const onError = () => { const onError = () => {
if (app) app.clear(); if (app) app.clear();
render(<Exit didError />); render(<Exit didError />);
} };
const onExit = () => { const onExit = () => {
if (app) app.clear(); if (app) app.clear();
render(<Exit />); render(<Exit />);
} };
addProcessListeners([ addProcessListeners([
['uncaughtException', onError], ['uncaughtException', onError],
['exit', onExit], ['exit', onExit],
['SIGINT', onExit], ['SIGINT', onExit],
['SIGTERM', onExit], ['SIGTERM', onExit],
]) ]);
} }

View file

@ -21,10 +21,8 @@ Inside of your Astro project, you'll see the following folders and files:
Astro looks for `.astro` or `.md.astro` files in the `src/pages/` directory. Each page is exposed as a route based on its file name. Astro looks for `.astro` or `.md.astro` files in the `src/pages/` directory. Each page is exposed as a route based on its file name.
There's nothing special about `src/components/`, but that's where we like to put any Astro/React/Vue/Svelte/Preact components. There's nothing special about `src/components/`, but that's where we like to put any Astro/React/Vue/Svelte/Preact components.
Any static assets, like images, can be placed in the `public/` directory. Any static assets, like images, can be placed in the `public/` directory.
## 👀 Want to learn more? ## 👀 Want to learn more?

View file

@ -23,16 +23,18 @@ export async function cancelProcessListeners() {
export async function getTemplates() { export async function getTemplates() {
const templatesRoot = fileURLToPath(new URL('./templates', import.meta.url)); const templatesRoot = fileURLToPath(new URL('./templates', import.meta.url));
const templateFiles = await fs.readdir(templatesRoot, 'utf8'); const templateFiles = await fs.readdir(templatesRoot, 'utf8');
const templates = templateFiles.filter(t => t.endsWith('.tgz')); const templates = templateFiles.filter((t) => t.endsWith('.tgz'));
const metafile = templateFiles.find(t => t.endsWith('meta.json')); const metafile = templateFiles.find((t) => t.endsWith('meta.json'));
const meta = await fs.readFile(resolve(templatesRoot, metafile)).then(r => JSON.parse(r.toString())); const meta = await fs.readFile(resolve(templatesRoot, metafile)).then((r) => JSON.parse(r.toString()));
return templates.map(template => { return templates
.map((template) => {
const value = basename(template, '.tgz'); const value = basename(template, '.tgz');
if (meta[value]) return { ...meta[value], value }; if (meta[value]) return { ...meta[value], value };
return { value }; return { value };
}).sort((a, b) => { })
.sort((a, b) => {
const aRank = a.rank ?? 0; const aRank = a.rank ?? 0;
const bRank = b.rank ?? 0; const bRank = b.rank ?? 0;
if (aRank > bRank) return -1; if (aRank > bRank) return -1;
@ -49,10 +51,11 @@ export async function rewriteFiles(projectName: string) {
const tasks = []; const tasks = [];
tasks.push(fs.rename(resolve(dest, '_gitignore'), resolve(dest, '.gitignore'))); tasks.push(fs.rename(resolve(dest, '_gitignore'), resolve(dest, '.gitignore')));
tasks.push( tasks.push(
fs.readFile(resolve(dest, 'package.json')) fs
.then(res => JSON.parse(res.toString())) .readFile(resolve(dest, 'package.json'))
.then(json => JSON.stringify({ ...json, name: getValidPackageName(projectName) }, null, 2)) .then((res) => JSON.parse(res.toString()))
.then(res => fs.writeFile(resolve(dest, 'package.json'), res)) .then((json) => JSON.stringify({ ...json, name: getValidPackageName(projectName) }, null, 2))
.then((res) => fs.writeFile(resolve(dest, 'package.json'), res))
); );
return Promise.all(tasks); return Promise.all(tasks);
@ -81,7 +84,7 @@ export function cleanup(didError = false) {
} }
export function killChildren() { export function killChildren() {
childrenProcesses.forEach(p => p.kill('SIGINT')); childrenProcesses.forEach((p) => p.kill('SIGINT'));
} }
export function run(pkgManager: 'npm' | 'yarn', command: string, projectPath: string, stdio: any = 'ignore'): Promise<void> { export function run(pkgManager: 'npm' | 'yarn', command: string, projectPath: string, stdio: any = 'ignore'): Promise<void> {
@ -118,24 +121,24 @@ export function isEmpty(path) {
export function emptyDir(dir) { export function emptyDir(dir) {
dir = resolve(dir); dir = resolve(dir);
if (!existsSync(dir)) { if (!existsSync(dir)) {
return return;
} }
for (const file of readdirSync(dir)) { for (const file of readdirSync(dir)) {
const abs = resolve(dir, file) const abs = resolve(dir, file);
if (lstatSync(abs).isDirectory()) { if (lstatSync(abs).isDirectory()) {
emptyDir(abs) emptyDir(abs);
rmdirSync(abs) rmdirSync(abs);
} else { } else {
unlinkSync(abs) unlinkSync(abs);
} }
} }
} }
export function getValidPackageName(projectName: string) { export function getValidPackageName(projectName: string) {
const packageNameRegExp = /^(?:@[a-z0-9-*~][a-z0-9-*._~]*\/)?[a-z0-9-~][a-z0-9-._~]*$/ const packageNameRegExp = /^(?:@[a-z0-9-*~][a-z0-9-*._~]*\/)?[a-z0-9-~][a-z0-9-._~]*$/;
if (packageNameRegExp.test(projectName)) { if (packageNameRegExp.test(projectName)) {
return projectName return projectName;
} }
return projectName return projectName

View file

@ -5,56 +5,57 @@ import { promises as fs } from 'fs';
const convertMessage = ({ message, start, end, filename, frame }) => ({ const convertMessage = ({ message, start, end, filename, frame }) => ({
text: message, text: message,
location: start && end && { location: start &&
end && {
file: filename, file: filename,
line: start.line, line: start.line,
column: start.column, column: start.column,
length: start.line === end.line ? end.column - start.column : 0, length: start.line === end.line ? end.column - start.column : 0,
lineText: frame, lineText: frame,
}, },
}) });
const handleLoad = async (args, generate) => { const handleLoad = async (args, generate) => {
const { path } = args; const { path } = args;
const source = await fs.readFile(path, 'utf8'); const source = await fs.readFile(path, 'utf8');
const filename = relative(process.cwd(), path) const filename = relative(process.cwd(), path);
try { try {
let compileOptions = { css: false, generate, hydratable: true }; let compileOptions = { css: false, generate, hydratable: true };
let { js, warnings } = compile(source, { ...compileOptions, filename }) let { js, warnings } = compile(source, { ...compileOptions, filename });
let contents = js.code + `\n//# sourceMappingURL=` + js.map.toUrl() let contents = js.code + `\n//# sourceMappingURL=` + js.map.toUrl();
return { loader: 'js', contents, resolveDir: dirname(path), warnings: warnings.map(w => convertMessage(w)) }; return { loader: 'js', contents, resolveDir: dirname(path), warnings: warnings.map((w) => convertMessage(w)) };
} catch (e) { } catch (e) {
return { errors: [convertMessage(e)] } return { errors: [convertMessage(e)] };
}
} }
};
export default function sveltePlugin() { export default function sveltePlugin() {
return { return {
name: 'svelte-esbuild', name: 'svelte-esbuild',
setup(build) { setup(build) {
build.onResolve({ filter: /\.svelte$/ }, args => { build.onResolve({ filter: /\.svelte$/ }, (args) => {
let path = args.path.replace(/\.(?:client|server)/, ''); let path = args.path.replace(/\.(?:client|server)/, '');
path = isAbsolute(path) ? path : join(args.resolveDir, path) path = isAbsolute(path) ? path : join(args.resolveDir, path);
if (/\.client\.svelte$/.test(args.path)) { if (/\.client\.svelte$/.test(args.path)) {
return { return {
path, path,
namespace: 'svelte:client', namespace: 'svelte:client',
} };
} }
if (/\.server\.svelte$/.test(args.path)) { if (/\.server\.svelte$/.test(args.path)) {
return { return {
path, path,
namespace: 'svelte:server', namespace: 'svelte:server',
} };
} }
}); });
build.onLoad({ filter: /.*/, namespace: 'svelte:client' }, (args) => handleLoad(args, 'dom')) build.onLoad({ filter: /.*/, namespace: 'svelte:client' }, (args) => handleLoad(args, 'dom'));
build.onLoad({ filter: /.*/, namespace: 'svelte:server' }, (args) => handleLoad(args, 'ssr')) build.onLoad({ filter: /.*/, namespace: 'svelte:server' }, (args) => handleLoad(args, 'ssr'));
}, },
} };
} }

View file

@ -42,7 +42,7 @@ module.exports.parsers = {
return node.end; return node.end;
}, },
astFormat: 'astro-expression', astFormat: 'astro-expression',
} },
}; };
const findExpressionsInAST = (node, collect = []) => { const findExpressionsInAST = (node, collect = []) => {
@ -50,24 +50,24 @@ const findExpressionsInAST = (node, collect = []) => {
return collect.concat(node); return collect.concat(node);
} }
if (node.children) { if (node.children) {
collect.push(...[].concat(...node.children.map(child => findExpressionsInAST(child)))); collect.push(...[].concat(...node.children.map((child) => findExpressionsInAST(child))));
} }
return collect; return collect;
} };
const formatExpression = ({ expression: { codeChunks, children } }, text, options) => { const formatExpression = ({ expression: { codeChunks, children } }, text, options) => {
if (children.length === 0) { if (children.length === 0) {
const codeStart = codeChunks[0]; // If no children, there should only exist a single chunk. const codeStart = codeChunks[0]; // If no children, there should only exist a single chunk.
if (codeStart && [`'`, `"`].includes(codeStart[0])) { if (codeStart && [`'`, `"`].includes(codeStart[0])) {
return `<script $ lang="ts">${codeChunks.join('')}</script>` return `<script $ lang="ts">${codeChunks.join('')}</script>`;
} }
return `{${codeChunks.join('')}}`; return `{${codeChunks.join('')}}`;
} }
return `<script $ lang="ts">${text}</script>`; return `<script $ lang="ts">${text}</script>`;
} };
const isAstroScript = (node) => node.type === 'concat' && node.parts[0] === '<script' && node.parts[1].type === 'indent' && node.parts[1].contents.parts.find(v => v === '$'); const isAstroScript = (node) => node.type === 'concat' && node.parts[0] === '<script' && node.parts[1].type === 'indent' && node.parts[1].contents.parts.find((v) => v === '$');
const walkDoc = (doc) => { const walkDoc = (doc) => {
let inAstroScript = false; let inAstroScript = false;
@ -77,38 +77,38 @@ const walkDoc = (doc) => {
inAstroScript = true; inAstroScript = true;
parent.contents = { type: 'concat', parts: ['{'] }; parent.contents = { type: 'concat', parts: ['{'] };
} }
return node.parts.map(part => recurse(part, { parent: node })); return node.parts.map((part) => recurse(part, { parent: node }));
} }
if (inAstroScript) { if (inAstroScript) {
if (node.type === 'break-parent') { if (node.type === 'break-parent') {
parent.parts = parent.parts.filter(part => !['break-parent', 'line'].includes(part.type)); parent.parts = parent.parts.filter((part) => !['break-parent', 'line'].includes(part.type));
} }
if (node.type === 'indent') { if (node.type === 'indent') {
parent.parts = parent.parts.map(part => { parent.parts = parent.parts.map((part) => {
if (part.type !== 'indent') return part; if (part.type !== 'indent') return part;
return { return {
type: 'concat', type: 'concat',
parts: [part.contents] parts: [part.contents],
} };
}) });
} }
if (typeof node === 'string' && node.endsWith(';')) { if (typeof node === 'string' && node.endsWith(';')) {
parent.parts = parent.parts.map(part => { parent.parts = parent.parts.map((part) => {
if (typeof part === 'string' && part.endsWith(';')) return part.slice(0, -1); if (typeof part === 'string' && part.endsWith(';')) return part.slice(0, -1);
return part; return part;
}); });
} }
if (node === '</script>') { if (node === '</script>') {
parent.parts = parent.parts.map(part => part === '</script>' ? '}' : part); parent.parts = parent.parts.map((part) => (part === '</script>' ? '}' : part));
inAstroScript = false; inAstroScript = false;
} }
} }
if (['group', 'indent'].includes(node.type)) { if (['group', 'indent'].includes(node.type)) {
return recurse(node.contents, { parent: node }); return recurse(node.contents, { parent: node });
} }
} };
recurse(doc, { parent: null }); recurse(doc, { parent: null });
} };
/** @type {Record<string, import('prettier').Printer>} */ /** @type {Record<string, import('prettier').Printer>} */
module.exports.printers = { module.exports.printers = {
@ -129,18 +129,20 @@ module.exports.printers = {
if (node.type === 'Fragment' && node.isRoot) { if (node.type === 'Fragment' && node.isRoot) {
const expressions = findExpressionsInAST(node); const expressions = findExpressionsInAST(node);
if (expressions.length > 0) { if (expressions.length > 0) {
const parts = [].concat(...expressions.map((expr, i, all) => { const parts = [].concat(
...expressions.map((expr, i, all) => {
const prev = all[i - 1]; const prev = all[i - 1];
const start = node.text.slice((prev?.end ?? node.start) - node.start, expr.start - node.start); const start = node.text.slice((prev?.end ?? node.start) - node.start, expr.start - node.start);
const exprText = formatExpression(expr, node.text.slice(expr.start - node.start + 1, expr.end - node.start - 1), options); const exprText = formatExpression(expr, node.text.slice(expr.start - node.start + 1, expr.end - node.start - 1), options);
if (i === all.length - 1) { if (i === all.length - 1) {
const end = node.text.slice(expr.end - node.start); const end = node.text.slice(expr.end - node.start);
return [start, exprText, end] return [start, exprText, end];
} }
return [start, exprText] return [start, exprText];
})); })
);
const html = parts.join('\n'); const html = parts.join('\n');
const doc = textToDoc(html, { parser: 'html' }); const doc = textToDoc(html, { parser: 'html' });
walkDoc(doc); walkDoc(doc);

View file

@ -2,10 +2,10 @@ import { suite } from 'uvu';
import * as assert from 'uvu/assert'; import * as assert from 'uvu/assert';
import { format } from './test-utils.js'; import { format } from './test-utils.js';
import { promises as fs } from 'fs'; import { promises as fs } from 'fs';
import { fileURLToPath } from 'url' import { fileURLToPath } from 'url';
const Prettier = suite('Prettier formatting'); const Prettier = suite('Prettier formatting');
const readFile = (path) => fs.readFile(fileURLToPath(new URL(`./fixtures${path}`, import.meta.url))).then(res => res.toString()) const readFile = (path) => fs.readFile(fileURLToPath(new URL(`./fixtures${path}`, import.meta.url))).then((res) => res.toString());
/** /**
* Utility to get `[src, out]` files * Utility to get `[src, out]` files

View file

@ -17,11 +17,7 @@ export function activateTagClosing(
configName: string configName: string
): Disposable { ): Disposable {
const disposables: Disposable[] = []; const disposables: Disposable[] = [];
workspace.onDidChangeTextDocument( workspace.onDidChangeTextDocument((event) => onDidChangeTextDocument(event.document, event.contentChanges), null, disposables);
(event) => onDidChangeTextDocument(event.document, event.contentChanges),
null,
disposables
);
let isEnabled = false; let isEnabled = false;
updateEnabledState(); updateEnabledState();
@ -47,10 +43,7 @@ export function activateTagClosing(
} }
/** Handle text document changes */ /** Handle text document changes */
function onDidChangeTextDocument( function onDidChangeTextDocument(document: TextDocument, changes: readonly TextDocumentContentChangeEvent[]) {
document: TextDocument,
changes: readonly TextDocumentContentChangeEvent[]
) {
if (!isEnabled) { if (!isEnabled) {
return; return;
} }
@ -63,22 +56,13 @@ export function activateTagClosing(
} }
const lastChange = changes[changes.length - 1]; const lastChange = changes[changes.length - 1];
const lastCharacter = lastChange.text[lastChange.text.length - 1]; const lastCharacter = lastChange.text[lastChange.text.length - 1];
if ( if (('range' in lastChange && (lastChange.rangeLength ?? 0) > 0) || (lastCharacter !== '>' && lastCharacter !== '/')) {
('range' in lastChange && (lastChange.rangeLength ?? 0) > 0) ||
(lastCharacter !== '>' && lastCharacter !== '/')
) {
return; return;
} }
const rangeStart = const rangeStart = 'range' in lastChange ? lastChange.range.start : new Position(0, document.getText().length);
'range' in lastChange
? lastChange.range.start
: new Position(0, document.getText().length);
const version = document.version; const version = document.version;
timeout = setTimeout(() => { timeout = setTimeout(() => {
const position = new Position( const position = new Position(rangeStart.line, rangeStart.character + lastChange.text.length);
rangeStart.line,
rangeStart.character + lastChange.text.length
);
tagProvider(document, position).then((text) => { tagProvider(document, position).then((text) => {
if (text && isEnabled) { if (text && isEnabled) {
const activeEditor = window.activeTextEditor; const activeEditor = window.activeTextEditor;
@ -86,10 +70,7 @@ export function activateTagClosing(
const activeDocument = activeEditor.document; const activeDocument = activeEditor.document;
if (document === activeDocument && activeDocument.version === version) { if (document === activeDocument && activeDocument.version === version) {
const selections = activeEditor.selections; const selections = activeEditor.selections;
if ( if (selections.length && selections.some((s) => s.active.isEqual(position))) {
selections.length &&
selections.some((s) => s.active.isEqual(position))
) {
activeEditor.insertSnippet( activeEditor.insertSnippet(
new SnippetString(text), new SnippetString(text),
selections.map((s) => s.active) selections.map((s) => s.active)

View file

@ -2,11 +2,9 @@
"extends": "../../tsconfig.base.json", "extends": "../../tsconfig.base.json",
"compilerOptions": { "compilerOptions": {
"outDir": "dist", "outDir": "dist",
"rootDir": "src", "rootDir": "src"
}, },
"include": ["src"], "include": ["src"],
"exclude": ["node_modules"], "exclude": ["node_modules"],
"references": [ "references": [{ "path": "../server" }]
{ "path": "../server" }
]
} }

View file

@ -7,7 +7,6 @@ import { parseHtml } from './parseHtml';
import { parseAstro, AstroDocument } from './parseAstro'; import { parseAstro, AstroDocument } from './parseAstro';
export class Document implements TextDocument { export class Document implements TextDocument {
private content: string; private content: string;
languageId = 'astro'; languageId = 'astro';
@ -43,7 +42,7 @@ export class Document implements TextDocument {
} }
getText(): string { getText(): string {
return this.content return this.content;
} }
/** /**
@ -89,10 +88,7 @@ export class Document implements TextDocument {
} }
const lineOffset = lineOffsets[position.line]; const lineOffset = lineOffsets[position.line];
const nextLineOffset = const nextLineOffset = position.line + 1 < lineOffsets.length ? lineOffsets[position.line + 1] : this.getTextLength();
position.line + 1 < lineOffsets.length
? lineOffsets[position.line + 1]
: this.getTextLength();
return clamp(nextLineOffset, lineOffset, lineOffset + position.character); return clamp(nextLineOffset, lineOffset, lineOffset + position.character);
} }
@ -147,7 +143,6 @@ export class Document implements TextDocument {
return this.uri; return this.uri;
} }
get lines(): string[] { get lines(): string[] {
return this.getText().split(/\r?\n/); return this.getText().split(/\r?\n/);
} }
@ -155,5 +150,4 @@ export class Document implements TextDocument {
get lineCount(): number { get lineCount(): number {
return this.lines.length; return this.lines.length;
} }
} }

View file

@ -1,8 +1,5 @@
import { EventEmitter } from 'events'; import { EventEmitter } from 'events';
import { import { TextDocumentContentChangeEvent, TextDocumentItem } from 'vscode-languageserver';
TextDocumentContentChangeEvent,
TextDocumentItem
} from 'vscode-languageserver';
import { Document } from './Document'; import { Document } from './Document';
import { normalizeUri } from '../../utils'; import { normalizeUri } from '../../utils';
@ -15,9 +12,7 @@ export class DocumentManager {
private locked = new Set<string>(); private locked = new Set<string>();
private deleteCandidates = new Set<string>(); private deleteCandidates = new Set<string>();
constructor( constructor(private createDocument: (textDocument: { uri: string; text: string }) => Document) {}
private createDocument: (textDocument: { uri: string, text: string }) => Document
) {}
get(uri: string) { get(uri: string) {
return this.documents.get(normalizeUri(uri)); return this.documents.get(normalizeUri(uri));
@ -59,10 +54,7 @@ export class DocumentManager {
this.openedInClient.delete(uri); this.openedInClient.delete(uri);
} }
updateDocument( updateDocument(uri: string, changes: TextDocumentContentChangeEvent[]) {
uri: string,
changes: TextDocumentContentChangeEvent[]
) {
const document = this.documents.get(normalizeUri(uri)); const document = this.documents.get(normalizeUri(uri));
if (!document) { if (!document) {
throw new Error('Cannot call methods on an unopened document'); throw new Error('Cannot call methods on an unopened document');
@ -89,9 +81,7 @@ export class DocumentManager {
} }
getAllOpenedByClient() { getAllOpenedByClient() {
return Array.from(this.documents.entries()).filter((doc) => return Array.from(this.documents.entries()).filter((doc) => this.openedInClient.has(doc[0]));
this.openedInClient.has(doc[0])
);
} }
on(name: DocumentEvent, listener: (document: Document) => void) { on(name: DocumentEvent, listener: (document: Document) => void) {

View file

@ -11,17 +11,17 @@ interface Content {
} }
export interface AstroDocument { export interface AstroDocument {
frontmatter: Frontmatter frontmatter: Frontmatter;
content: Content; content: Content;
} }
/** Parses a document to collect metadata about Astro features */ /** Parses a document to collect metadata about Astro features */
export function parseAstro(content: string): AstroDocument { export function parseAstro(content: string): AstroDocument {
const frontmatter = getFrontmatter(content) const frontmatter = getFrontmatter(content);
return { return {
frontmatter, frontmatter,
content: getContent(content, frontmatter) content: getContent(content, frontmatter),
} };
} }
/** Get frontmatter metadata */ /** Get frontmatter metadata */
@ -30,9 +30,12 @@ function getFrontmatter(content: string): Frontmatter {
function getFrontmatterState(): Frontmatter['state'] { function getFrontmatterState(): Frontmatter['state'] {
const parts = content.trim().split('---').length; const parts = content.trim().split('---').length;
switch (parts) { switch (parts) {
case 1: return null; case 1:
case 2: return 'open'; return null;
default: return 'closed'; case 2:
return 'open';
default:
return 'closed';
} }
} }
const state = getFrontmatterState(); const state = getFrontmatterState();
@ -50,7 +53,7 @@ function getFrontmatter(content: string): Frontmatter {
return { return {
state, state,
startOffset, startOffset,
endOffset endOffset,
}; };
} }
@ -59,16 +62,16 @@ function getContent(content: string, frontmatter: Frontmatter): Content {
switch (frontmatter.state) { switch (frontmatter.state) {
case null: { case null: {
const offset = getFirstNonWhitespaceIndex(content); const offset = getFirstNonWhitespaceIndex(content);
return { firstNonWhitespaceOffset: offset === -1 ? null : offset } return { firstNonWhitespaceOffset: offset === -1 ? null : offset };
} }
case 'open': { case 'open': {
return { firstNonWhitespaceOffset: null } return { firstNonWhitespaceOffset: null };
} }
case 'closed': { case 'closed': {
const { endOffset } = frontmatter; const { endOffset } = frontmatter;
const end = (endOffset ?? 0) + 3; const end = (endOffset ?? 0) + 3;
const offset = getFirstNonWhitespaceIndex(content.slice(end)) const offset = getFirstNonWhitespaceIndex(content.slice(end));
return { firstNonWhitespaceOffset: end + offset } return { firstNonWhitespaceOffset: end + offset };
} }
} }
} }

View file

@ -1,12 +1,4 @@
import { import { getLanguageService, HTMLDocument, TokenType, ScannerState, Scanner, Node, Position } from 'vscode-html-languageservice';
getLanguageService,
HTMLDocument,
TokenType,
ScannerState,
Scanner,
Node,
Position
} from 'vscode-html-languageservice';
import { Document } from './Document'; import { Document } from './Document';
import { isInsideExpression } from './utils'; import { isInsideExpression } from './utils';
@ -24,11 +16,7 @@ export function parseHtml(text: string): HTMLDocument {
return parsedDoc; return parsedDoc;
} }
const createScanner = parser.createScanner as ( const createScanner = parser.createScanner as (input: string, initialOffset?: number, initialState?: ScannerState) => Scanner;
input: string,
initialOffset?: number,
initialState?: ScannerState
) => Scanner;
/** /**
* scan the text and remove any `>` or `<` that cause the tag to end short, * scan the text and remove any `>` or `<` that cause the tag to end short,
@ -59,12 +47,7 @@ function preprocess(text: string) {
// <Foo checked={a < 1}> // <Foo checked={a < 1}>
// https://github.com/microsoft/vscode-html-languageservice/blob/71806ef57be07e1068ee40900ef8b0899c80e68a/src/parser/htmlScanner.ts#L327 // https://github.com/microsoft/vscode-html-languageservice/blob/71806ef57be07e1068ee40900ef8b0899c80e68a/src/parser/htmlScanner.ts#L327
if ( if (token === TokenType.Unknown && scanner.getScannerState() === ScannerState.WithinTag && scanner.getTokenText() === '<' && shouldBlankStartOrEndTagLike(offset)) {
token === TokenType.Unknown &&
scanner.getScannerState() === ScannerState.WithinTag &&
scanner.getTokenText() === '<' &&
shouldBlankStartOrEndTagLike(offset)
) {
blankStartOrEndTagLike(offset); blankStartOrEndTagLike(offset);
} }
@ -75,10 +58,7 @@ function preprocess(text: string) {
function shouldBlankStartOrEndTagLike(offset: number) { function shouldBlankStartOrEndTagLike(offset: number) {
// not null rather than falsy, otherwise it won't work on first tag(0) // not null rather than falsy, otherwise it won't work on first tag(0)
return ( return currentStartTagStart !== null && isInsideExpression(text, currentStartTagStart, offset);
currentStartTagStart !== null &&
isInsideExpression(text, currentStartTagStart, offset)
);
} }
function blankStartOrEndTagLike(offset: number) { function blankStartOrEndTagLike(offset: number) {
@ -93,10 +73,7 @@ export interface AttributeContext {
valueRange?: [number, number]; valueRange?: [number, number];
} }
export function getAttributeContextAtPosition( export function getAttributeContextAtPosition(document: Document, position: Position): AttributeContext | null {
document: Document,
position: Position
): AttributeContext | null {
const offset = document.offsetAt(position); const offset = document.offsetAt(position);
const { html } = document; const { html } = document;
const tag = html.findNodeAt(offset); const tag = html.findNodeAt(offset);
@ -106,15 +83,13 @@ export function getAttributeContextAtPosition(
} }
const text = document.getText(); const text = document.getText();
const beforeStartTagEnd = const beforeStartTagEnd = text.substring(0, tag.start) + preprocess(text.substring(tag.start, tag.startTagEnd));
text.substring(0, tag.start) + preprocess(text.substring(tag.start, tag.startTagEnd));
const scanner = createScanner(beforeStartTagEnd, tag.start); const scanner = createScanner(beforeStartTagEnd, tag.start);
let token = scanner.scan(); let token = scanner.scan();
let currentAttributeName: string | undefined; let currentAttributeName: string | undefined;
const inTokenRange = () => const inTokenRange = () => scanner.getTokenOffset() <= offset && offset <= scanner.getTokenEnd();
scanner.getTokenOffset() <= offset && offset <= scanner.getTokenEnd();
while (token != TokenType.EOS) { while (token != TokenType.EOS) {
// adopted from https://github.com/microsoft/vscode-html-languageservice/blob/2f7ae4df298ac2c299a40e9024d118f4a9dc0c68/src/services/htmlCompletion.ts#L402 // adopted from https://github.com/microsoft/vscode-html-languageservice/blob/2f7ae4df298ac2c299a40e9024d118f4a9dc0c68/src/services/htmlCompletion.ts#L402
if (token === TokenType.AttributeName) { if (token === TokenType.AttributeName) {
@ -123,7 +98,7 @@ export function getAttributeContextAtPosition(
if (inTokenRange()) { if (inTokenRange()) {
return { return {
name: currentAttributeName, name: currentAttributeName,
inValue: false inValue: false,
}; };
} }
} else if (token === TokenType.DelimiterAssign) { } else if (token === TokenType.DelimiterAssign) {
@ -133,10 +108,7 @@ export function getAttributeContextAtPosition(
return { return {
name: currentAttributeName, name: currentAttributeName,
inValue: true, inValue: true,
valueRange: [ valueRange: [offset, nextToken === TokenType.AttributeValue ? scanner.getTokenEnd() : offset],
offset,
nextToken === TokenType.AttributeValue ? scanner.getTokenEnd() : offset
]
}; };
} }
} else if (token === TokenType.AttributeValue) { } else if (token === TokenType.AttributeValue) {
@ -153,7 +125,7 @@ export function getAttributeContextAtPosition(
return { return {
name: currentAttributeName, name: currentAttributeName,
inValue: true, inValue: true,
valueRange: [start, end] valueRange: [start, end],
}; };
} }
currentAttributeName = undefined; currentAttributeName = undefined;

View file

@ -5,11 +5,7 @@ import { clamp } from '../../utils';
* Gets word range at position. * Gets word range at position.
* Delimiter is by default a whitespace, but can be adjusted. * Delimiter is by default a whitespace, but can be adjusted.
*/ */
export function getWordRangeAt( export function getWordRangeAt(str: string, pos: number, delimiterRegex = { left: /\S+$/, right: /\s/ }): { start: number; end: number } {
str: string,
pos: number,
delimiterRegex = { left: /\S+$/, right: /\s/ }
): { start: number; end: number } {
let start = str.slice(0, pos).search(delimiterRegex.left); let start = str.slice(0, pos).search(delimiterRegex.left);
if (start < 0) { if (start < 0) {
start = pos; start = pos;
@ -29,11 +25,7 @@ export function getWordRangeAt(
* Gets word at position. * Gets word at position.
* Delimiter is by default a whitespace, but can be adjusted. * Delimiter is by default a whitespace, but can be adjusted.
*/ */
export function getWordAt( export function getWordAt(str: string, pos: number, delimiterRegex = { left: /\S+$/, right: /\s/ }): string {
str: string,
pos: number,
delimiterRegex = { left: /\S+$/, right: /\s/ }
): string {
const { start, end } = getWordRangeAt(str, pos, delimiterRegex); const { start, end } = getWordRangeAt(str, pos, delimiterRegex);
return str.slice(start, end); return str.slice(start, end);
} }
@ -54,10 +46,7 @@ export function isInsideExpression(html: string, tagStart: number, position: num
/** /**
* Returns if a given offset is inside of the document frontmatter * Returns if a given offset is inside of the document frontmatter
*/ */
export function isInsideFrontmatter( export function isInsideFrontmatter(text: string, offset: number): boolean {
text: string,
offset: number
): boolean {
let start = text.slice(0, offset).trim().split('---').length; let start = text.slice(0, offset).trim().split('---').length;
let end = text.slice(offset).trim().split('---').length; let end = text.slice(offset).trim().split('---').length;
@ -109,8 +98,7 @@ export function offsetAt(position: Position, text: string): number {
} }
const lineOffset = lineOffsets[position.line]; const lineOffset = lineOffsets[position.line];
const nextLineOffset = const nextLineOffset = position.line + 1 < lineOffsets.length ? lineOffsets[position.line + 1] : text.length;
position.line + 1 < lineOffsets.length ? lineOffsets[position.line + 1] : text.length;
return clamp(nextLineOffset, lineOffset, lineOffset + position.character); return clamp(nextLineOffset, lineOffset, lineOffset + position.character);
} }

View file

@ -71,10 +71,12 @@ export function startServer() {
connection.onDidChangeTextDocument((evt) => docManager.updateDocument(evt.textDocument.uri, evt.contentChanges)); connection.onDidChangeTextDocument((evt) => docManager.updateDocument(evt.textDocument.uri, evt.contentChanges));
connection.onDidChangeWatchedFiles((evt) => { connection.onDidChangeWatchedFiles((evt) => {
const params = evt.changes.map(change => ({ const params = evt.changes
.map((change) => ({
fileName: urlToPath(change.uri), fileName: urlToPath(change.uri),
changeType: change.type changeType: change.type,
})).filter(change => !!change.fileName) }))
.filter((change) => !!change.fileName);
pluginHost.onWatchFileChanges(params); pluginHost.onWatchFileChanges(params);
}); });

View file

@ -1,11 +1,4 @@
import { CompletionContext, CompletionItem, CompletionList, Position, TextDocumentIdentifier } from 'vscode-languageserver';
import {
CompletionContext,
CompletionItem,
CompletionList,
Position,
TextDocumentIdentifier,
} from 'vscode-languageserver';
import type { DocumentManager } from '../core/documents'; import type { DocumentManager } from '../core/documents';
import type * as d from './interfaces'; import type * as d from './interfaces';
import { flatten } from '../utils'; import { flatten } from '../utils';
@ -15,7 +8,7 @@ import { FoldingRange } from 'vscode-languageserver-types';
enum ExecuteMode { enum ExecuteMode {
None, None,
FirstNonNull, FirstNonNull,
Collect Collect,
} }
export class PluginHost { export class PluginHost {
@ -27,81 +20,50 @@ export class PluginHost {
this.plugins.push(plugin); this.plugins.push(plugin);
} }
async getCompletions( async getCompletions(textDocument: TextDocumentIdentifier, position: Position, completionContext?: CompletionContext): Promise<CompletionList> {
textDocument: TextDocumentIdentifier,
position: Position,
completionContext?: CompletionContext
): Promise<CompletionList> {
const document = this.getDocument(textDocument.uri); const document = this.getDocument(textDocument.uri);
if (!document) { if (!document) {
throw new Error('Cannot call methods on an unopened document'); throw new Error('Cannot call methods on an unopened document');
} }
const completions = ( const completions = (await this.execute<CompletionList>('getCompletions', [document, position, completionContext], ExecuteMode.Collect)).filter(
await this.execute<CompletionList>( (completion) => completion != null
'getCompletions', );
[document, position, completionContext],
ExecuteMode.Collect
)
).filter((completion) => completion != null);
let flattenedCompletions = flatten(completions.map((completion) => completion.items)); let flattenedCompletions = flatten(completions.map((completion) => completion.items));
const isIncomplete = completions.reduce( const isIncomplete = completions.reduce((incomplete, completion) => incomplete || completion.isIncomplete, false as boolean);
(incomplete, completion) => incomplete || completion.isIncomplete,
false as boolean
);
return CompletionList.create(flattenedCompletions, isIncomplete); return CompletionList.create(flattenedCompletions, isIncomplete);
} }
async resolveCompletion( async resolveCompletion(textDocument: TextDocumentIdentifier, completionItem: d.AppCompletionItem): Promise<CompletionItem> {
textDocument: TextDocumentIdentifier,
completionItem: d.AppCompletionItem
): Promise<CompletionItem> {
const document = this.getDocument(textDocument.uri); const document = this.getDocument(textDocument.uri);
if (!document) { if (!document) {
throw new Error('Cannot call methods on an unopened document'); throw new Error('Cannot call methods on an unopened document');
} }
const result = await this.execute<CompletionItem>( const result = await this.execute<CompletionItem>('resolveCompletion', [document, completionItem], ExecuteMode.FirstNonNull);
'resolveCompletion',
[document, completionItem],
ExecuteMode.FirstNonNull
);
return result ?? completionItem; return result ?? completionItem;
} }
async doTagComplete( async doTagComplete(textDocument: TextDocumentIdentifier, position: Position): Promise<string | null> {
textDocument: TextDocumentIdentifier,
position: Position
): Promise<string | null> {
const document = this.getDocument(textDocument.uri); const document = this.getDocument(textDocument.uri);
if (!document) { if (!document) {
throw new Error('Cannot call methods on an unopened document'); throw new Error('Cannot call methods on an unopened document');
} }
return this.execute<string | null>( return this.execute<string | null>('doTagComplete', [document, position], ExecuteMode.FirstNonNull);
'doTagComplete',
[document, position],
ExecuteMode.FirstNonNull
);
} }
async getFoldingRanges( async getFoldingRanges(textDocument: TextDocumentIdentifier): Promise<FoldingRange[] | null> {
textDocument: TextDocumentIdentifier
): Promise<FoldingRange[]|null> {
const document = this.getDocument(textDocument.uri); const document = this.getDocument(textDocument.uri);
if (!document) { if (!document) {
throw new Error('Cannot call methods on an unopened document'); throw new Error('Cannot call methods on an unopened document');
} }
const foldingRanges = flatten(await this.execute<FoldingRange[]>( const foldingRanges = flatten(await this.execute<FoldingRange[]>('getFoldingRanges', [document], ExecuteMode.Collect)).filter((completion) => completion != null);
'getFoldingRanges',
[document],
ExecuteMode.Collect
)).filter((completion) => completion != null)
return foldingRanges; return foldingRanges;
} }
@ -116,22 +78,10 @@ export class PluginHost {
return this.documentsManager.get(uri); return this.documentsManager.get(uri);
} }
private execute<T>( private execute<T>(name: keyof d.LSProvider, args: any[], mode: ExecuteMode.FirstNonNull): Promise<T | null>;
name: keyof d.LSProvider, private execute<T>(name: keyof d.LSProvider, args: any[], mode: ExecuteMode.Collect): Promise<T[]>;
args: any[],
mode: ExecuteMode.FirstNonNull
): Promise<T | null>;
private execute<T>(
name: keyof d.LSProvider,
args: any[],
mode: ExecuteMode.Collect
): Promise<T[]>;
private execute(name: keyof d.LSProvider, args: any[], mode: ExecuteMode.None): Promise<void>; private execute(name: keyof d.LSProvider, args: any[], mode: ExecuteMode.None): Promise<void>;
private async execute<T>( private async execute<T>(name: keyof d.LSProvider, args: any[], mode: ExecuteMode): Promise<(T | null) | T[] | void> {
name: keyof d.LSProvider,
args: any[],
mode: ExecuteMode
): Promise<(T | null) | T[] | void> {
const plugins = this.plugins.filter((plugin) => typeof plugin[name] === 'function'); const plugins = this.plugins.filter((plugin) => typeof plugin[name] === 'function');
switch (mode) { switch (mode) {
@ -144,13 +94,9 @@ export class PluginHost {
} }
return null; return null;
case ExecuteMode.Collect: case ExecuteMode.Collect:
return Promise.all( return Promise.all(plugins.map((plugin) => this.tryExecutePlugin(plugin, name, args, [])));
plugins.map((plugin) => this.tryExecutePlugin(plugin, name, args, []))
);
case ExecuteMode.None: case ExecuteMode.None:
await Promise.all( await Promise.all(plugins.map((plugin) => this.tryExecutePlugin(plugin, name, args, null)));
plugins.map((plugin) => this.tryExecutePlugin(plugin, name, args, null))
);
return; return;
} }
} }

View file

@ -49,7 +49,7 @@ export class AstroPlugin implements CompletionsProvider, FoldingRangeProvider {
endLine: end.line, endLine: end.line,
endCharacter: end.character, endCharacter: end.character,
kind: FoldingRangeKind.Imports, kind: FoldingRangeKind.Imports,
} },
]; ];
} }

View file

@ -34,15 +34,7 @@ export class HTMLPlugin implements CompletionsProvider, FoldingRangeProvider {
isIncomplete: true, isIncomplete: true,
items: [], items: [],
}; };
this.lang.setCompletionParticipants([ this.lang.setCompletionParticipants([getEmmetCompletionParticipants(document, position, 'html', this.configManager.getEmmetConfig(), emmetResults)]);
getEmmetCompletionParticipants(
document,
position,
'html',
this.configManager.getEmmetConfig(),
emmetResults
)
]);
const results = this.lang.doComplete(document, position, html); const results = this.lang.doComplete(document, position, html);
const items = this.toCompletionItems(results.items); const items = this.toCompletionItems(results.items);
@ -61,7 +53,6 @@ export class HTMLPlugin implements CompletionsProvider, FoldingRangeProvider {
} }
return this.lang.getFoldingRanges(document); return this.lang.getFoldingRanges(document);
} }
doTagComplete(document: Document, position: Position): string | null { doTagComplete(document: Document, position: Position): string | null {

View file

@ -1,11 +1,4 @@
import { import { CompletionContext, FileChangeType, LinkedEditingRanges, SemanticTokens, SignatureHelpContext, TextDocumentContentChangeEvent } from 'vscode-languageserver';
CompletionContext,
FileChangeType,
LinkedEditingRanges,
SemanticTokens,
SignatureHelpContext,
TextDocumentContentChangeEvent
} from 'vscode-languageserver';
import { import {
CodeAction, CodeAction,
CodeActionContext, CodeActionContext,
@ -28,7 +21,7 @@ import {
WorkspaceEdit, WorkspaceEdit,
SelectionRange, SelectionRange,
SignatureHelp, SignatureHelp,
FoldingRange FoldingRange,
} from 'vscode-languageserver-types'; } from 'vscode-languageserver-types';
import { Document } from '../core/documents'; import { Document } from '../core/documents';
@ -55,16 +48,9 @@ export interface FoldingRangeProvider {
} }
export interface CompletionsProvider<T extends TextDocumentIdentifier = any> { export interface CompletionsProvider<T extends TextDocumentIdentifier = any> {
getCompletions( getCompletions(document: Document, position: Position, completionContext?: CompletionContext): Resolvable<AppCompletionList<T> | null>;
document: Document,
position: Position,
completionContext?: CompletionContext
): Resolvable<AppCompletionList<T> | null>;
resolveCompletion?( resolveCompletion?(document: Document, completionItem: AppCompletionItem<T>): Resolvable<AppCompletionItem<T>>;
document: Document,
completionItem: AppCompletionItem<T>
): Resolvable<AppCompletionItem<T>>;
} }
export interface FormattingProvider { export interface FormattingProvider {
@ -80,11 +66,7 @@ export interface DocumentColorsProvider {
} }
export interface ColorPresentationsProvider { export interface ColorPresentationsProvider {
getColorPresentations( getColorPresentations(document: Document, range: Range, color: Color): Resolvable<ColorPresentation[]>;
document: Document,
range: Range,
color: Color
): Resolvable<ColorPresentation[]>;
} }
export interface DocumentSymbolsProvider { export interface DocumentSymbolsProvider {
@ -96,23 +78,12 @@ export interface DefinitionsProvider {
} }
export interface BackwardsCompatibleDefinitionsProvider { export interface BackwardsCompatibleDefinitionsProvider {
getDefinitions( getDefinitions(document: Document, position: Position): Resolvable<DefinitionLink[] | Location[]>;
document: Document,
position: Position
): Resolvable<DefinitionLink[] | Location[]>;
} }
export interface CodeActionsProvider { export interface CodeActionsProvider {
getCodeActions( getCodeActions(document: Document, range: Range, context: CodeActionContext): Resolvable<CodeAction[]>;
document: Document, executeCommand?(document: Document, command: string, args?: any[]): Resolvable<WorkspaceEdit | string | null>;
range: Range,
context: CodeActionContext
): Resolvable<CodeAction[]>;
executeCommand?(
document: Document,
command: string,
args?: any[]
): Resolvable<WorkspaceEdit | string | null>;
} }
export interface FileRename { export interface FileRename {
@ -125,28 +96,16 @@ export interface UpdateImportsProvider {
} }
export interface RenameProvider { export interface RenameProvider {
rename( rename(document: Document, position: Position, newName: string): Resolvable<WorkspaceEdit | null>;
document: Document,
position: Position,
newName: string
): Resolvable<WorkspaceEdit | null>;
prepareRename(document: Document, position: Position): Resolvable<Range | null>; prepareRename(document: Document, position: Position): Resolvable<Range | null>;
} }
export interface FindReferencesProvider { export interface FindReferencesProvider {
findReferences( findReferences(document: Document, position: Position, context: ReferenceContext): Promise<Location[] | null>;
document: Document,
position: Position,
context: ReferenceContext
): Promise<Location[] | null>;
} }
export interface SignatureHelpProvider { export interface SignatureHelpProvider {
getSignatureHelp( getSignatureHelp(document: Document, position: Position, context: SignatureHelpContext | undefined): Resolvable<SignatureHelp | null>;
document: Document,
position: Position,
context: SignatureHelpContext | undefined
): Resolvable<SignatureHelp | null>;
} }
export interface SelectionRangeProvider { export interface SelectionRangeProvider {
@ -158,10 +117,7 @@ export interface SemanticTokensProvider {
} }
export interface LinkedEditingRangesProvider { export interface LinkedEditingRangesProvider {
getLinkedEditingRanges( getLinkedEditingRanges(document: Document, position: Position): Resolvable<LinkedEditingRanges | null>;
document: Document,
position: Position
): Resolvable<LinkedEditingRanges | null>;
} }
export interface OnWatchFileChangesPara { export interface OnWatchFileChangesPara {
@ -208,10 +164,4 @@ export interface LSPProviderConfig {
definitionLinkSupport: boolean; definitionLinkSupport: boolean;
} }
export type Plugin = Partial< export type Plugin = Partial<ProviderBase & DefinitionsProvider & OnWatchFileChanges & SelectionRangeProvider & UpdateTsOrJsFile>;
ProviderBase &
DefinitionsProvider &
OnWatchFileChanges &
SelectionRangeProvider &
UpdateTsOrJsFile
>;

View file

@ -38,7 +38,7 @@ export class LanguageServiceManager {
const url = urlToPath(curr) as string; const url = urlToPath(curr) as string;
if (fileName.startsWith(url) && curr.length < url.length) return url; if (fileName.startsWith(url) && curr.length < url.length) return url;
return found; return found;
}, '') }, '');
} }
private createDocument = (fileName: string, content: string) => { private createDocument = (fileName: string, content: string) => {

View file

@ -14,34 +14,16 @@ export class SnapshotManager {
private documents: Map<string, DocumentSnapshot> = new Map(); private documents: Map<string, DocumentSnapshot> = new Map();
private lastLogged = new Date(new Date().getTime() - 60_001); private lastLogged = new Date(new Date().getTime() - 60_001);
private readonly watchExtensions = [ private readonly watchExtensions = [ts.Extension.Dts, ts.Extension.Js, ts.Extension.Jsx, ts.Extension.Ts, ts.Extension.Tsx, ts.Extension.Json];
ts.Extension.Dts,
ts.Extension.Js,
ts.Extension.Jsx,
ts.Extension.Ts,
ts.Extension.Tsx,
ts.Extension.Json
];
constructor( constructor(private projectFiles: string[], private fileSpec: TsFilesSpec, private workspaceRoot: string) {}
private projectFiles: string[],
private fileSpec: TsFilesSpec,
private workspaceRoot: string
) {
}
updateProjectFiles() { updateProjectFiles() {
const { include, exclude } = this.fileSpec; const { include, exclude } = this.fileSpec;
if (include?.length === 0) return; if (include?.length === 0) return;
const projectFiles = ts.sys.readDirectory( const projectFiles = ts.sys.readDirectory(this.workspaceRoot, this.watchExtensions, exclude, include);
this.workspaceRoot,
this.watchExtensions,
exclude,
include
);
this.projectFiles = Array.from(new Set([...this.projectFiles, ...projectFiles])); this.projectFiles = Array.from(new Set([...this.projectFiles, ...projectFiles]));
} }
@ -88,7 +70,7 @@ export class SnapshotManager {
} }
getFileNames() { getFileNames() {
return Array.from(this.documents.keys()).map(fileName => toVirtualAstroFilePath(fileName)); return Array.from(this.documents.keys()).map((fileName) => toVirtualAstroFilePath(fileName));
} }
getProjectFileNames() { getProjectFileNames() {
@ -106,12 +88,8 @@ export class SnapshotManager {
console.log( console.log(
'SnapshotManager File Statistics:\n' + 'SnapshotManager File Statistics:\n' +
`Project files: ${projectFiles.length}\n` + `Project files: ${projectFiles.length}\n` +
`Astro files: ${ `Astro files: ${allFiles.filter((name) => name.endsWith('.astro')).length}\n` +
allFiles.filter((name) => name.endsWith('.astro')).length `From node_modules: ${allFiles.filter((name) => name.includes('node_modules')).length}\n` +
}\n` +
`From node_modules: ${
allFiles.filter((name) => name.includes('node_modules')).length
}\n` +
`Total: ${allFiles.length}` `Total: ${allFiles.length}`
); );
} }
@ -152,11 +130,9 @@ export const createDocumentSnapshot = (filePath: string, createDocument?: (_file
} }
return new TypeScriptDocumentSnapshot(0, filePath, text); return new TypeScriptDocumentSnapshot(0, filePath, text);
};
}
class AstroDocumentSnapshot implements DocumentSnapshot { class AstroDocumentSnapshot implements DocumentSnapshot {
version = this.doc.version; version = this.doc.version;
scriptKind = ts.ScriptKind.Unknown; scriptKind = ts.ScriptKind.Unknown;
@ -206,11 +182,9 @@ class AstroDocumentSnapshot implements DocumentSnapshot {
offsetAt(position: Position) { offsetAt(position: Position) {
return offsetAt(position, this.text); return offsetAt(position, this.text);
} }
} }
class DocumentFragmentSnapshot implements Omit<DocumentSnapshot, 'getFragment' | 'destroyFragment'> { class DocumentFragmentSnapshot implements Omit<DocumentSnapshot, 'getFragment' | 'destroyFragment'> {
version: number; version: number;
filePath: string; filePath: string;
url: string; url: string;
@ -219,9 +193,7 @@ class DocumentFragmentSnapshot implements Omit<DocumentSnapshot, 'getFragment'|'
scriptKind = ts.ScriptKind.TSX; scriptKind = ts.ScriptKind.TSX;
scriptInfo = null; scriptInfo = null;
constructor( constructor(private doc: Document) {
private doc: Document
) {
const filePath = doc.getFilePath(); const filePath = doc.getFilePath();
if (!filePath) throw new Error('Cannot create a document fragment from a non-local document'); if (!filePath) throw new Error('Cannot create a document fragment from a non-local document');
const text = doc.getText(); const text = doc.getText();
@ -267,14 +239,12 @@ class DocumentFragmentSnapshot implements Omit<DocumentSnapshot, 'getFragment'|'
} }
class TypeScriptDocumentSnapshot implements DocumentSnapshot { class TypeScriptDocumentSnapshot implements DocumentSnapshot {
scriptKind = getScriptKindFromFileName(this.filePath); scriptKind = getScriptKindFromFileName(this.filePath);
scriptInfo = null; scriptInfo = null;
url: string; url: string;
constructor(public version: number, public readonly filePath: string, private text: string) { constructor(public version: number, public readonly filePath: string, private text: string) {
this.url = pathToUrl(filePath) this.url = pathToUrl(filePath);
} }
getText(start: number, end: number) { getText(start: number, end: number) {
@ -302,7 +272,7 @@ class TypeScriptDocumentSnapshot implements DocumentSnapshot {
} }
async getFragment(): Promise<DocumentFragmentSnapshot> { async getFragment(): Promise<DocumentFragmentSnapshot> {
return this as unknown as any; return (this as unknown) as any;
} }
destroyFragment() { destroyFragment() {

View file

@ -1,11 +1,7 @@
import type { Document, DocumentManager } from '../../core/documents'; import type { Document, DocumentManager } from '../../core/documents';
import type { ConfigManager } from '../../core/config'; import type { ConfigManager } from '../../core/config';
import type { CompletionsProvider, AppCompletionItem, AppCompletionList } from '../interfaces'; import type { CompletionsProvider, AppCompletionItem, AppCompletionList } from '../interfaces';
import { import { CompletionContext, Position, FileChangeType } from 'vscode-languageserver';
CompletionContext,
Position,
FileChangeType
} from 'vscode-languageserver';
import * as ts from 'typescript'; import * as ts from 'typescript';
import { CompletionsProviderImpl, CompletionEntryWithIdentifer } from './features/CompletionsProvider'; import { CompletionsProviderImpl, CompletionEntryWithIdentifer } from './features/CompletionsProvider';
import { LanguageServiceManager } from './LanguageServiceManager'; import { LanguageServiceManager } from './LanguageServiceManager';
@ -19,11 +15,7 @@ export class TypeScriptPlugin implements CompletionsProvider {
private readonly completionProvider: CompletionsProviderImpl; private readonly completionProvider: CompletionsProviderImpl;
constructor( constructor(docManager: DocumentManager, configManager: ConfigManager, workspaceUris: string[]) {
docManager: DocumentManager,
configManager: ConfigManager,
workspaceUris: string[]
) {
this.docManager = docManager; this.docManager = docManager;
this.configManager = configManager; this.configManager = configManager;
this.languageServiceManager = new LanguageServiceManager(docManager, configManager, workspaceUris); this.languageServiceManager = new LanguageServiceManager(docManager, configManager, workspaceUris);
@ -31,24 +23,13 @@ export class TypeScriptPlugin implements CompletionsProvider {
this.completionProvider = new CompletionsProviderImpl(this.languageServiceManager); this.completionProvider = new CompletionsProviderImpl(this.languageServiceManager);
} }
async getCompletions( async getCompletions(document: Document, position: Position, completionContext?: CompletionContext): Promise<AppCompletionList<CompletionEntryWithIdentifer> | null> {
document: Document, const completions = await this.completionProvider.getCompletions(document, position, completionContext);
position: Position,
completionContext?: CompletionContext
): Promise<AppCompletionList<CompletionEntryWithIdentifer> | null> {
const completions = await this.completionProvider.getCompletions(
document,
position,
completionContext
);
return completions; return completions;
} }
async resolveCompletion( async resolveCompletion(document: Document, completionItem: AppCompletionItem<CompletionEntryWithIdentifer>): Promise<AppCompletionItem<CompletionEntryWithIdentifer>> {
document: Document,
completionItem: AppCompletionItem<CompletionEntryWithIdentifer>
): Promise<AppCompletionItem<CompletionEntryWithIdentifer>> {
return this.completionProvider.resolveCompletion(document, completionItem); return this.completionProvider.resolveCompletion(document, completionItem);
} }
@ -86,4 +67,3 @@ export class TypeScriptPlugin implements CompletionsProvider {
return this.languageServiceManager.getSnapshotManager(fileName); return this.languageServiceManager.getSnapshotManager(fileName);
} }
} }

View file

@ -23,9 +23,9 @@ export function createAstroSys(getSnapshot: (fileName: string) => DocumentSnapsh
}, },
readDirectory(path, extensions, exclude, include, depth) { readDirectory(path, extensions, exclude, include, depth) {
const extensionsWithAstro = (extensions ?? []).concat(...['.astro']); const extensionsWithAstro = (extensions ?? []).concat(...['.astro']);
const result = ts.sys.readDirectory(path, extensionsWithAstro, exclude, include, depth);; const result = ts.sys.readDirectory(path, extensionsWithAstro, exclude, include, depth);
return result; return result;
} },
}; };
if (ts.sys.realpath) { if (ts.sys.realpath) {

View file

@ -99,7 +99,7 @@ export class CompletionsProviderImpl implements CompletionsProvider<CompletionEn
data: { data: {
...comp, ...comp,
uri, uri,
position position,
}, },
}; };
} }

View file

@ -58,25 +58,17 @@ async function createLanguageService(tsconfigPath: string, workspaceRoot: string
if (!configJson.extends) { if (!configJson.extends) {
configJson = Object.assign( configJson = Object.assign(
{ {
exclude: getDefaultExclude() exclude: getDefaultExclude(),
}, },
configJson configJson
); );
} }
const project = ts.parseJsonConfigFileContent( const project = ts.parseJsonConfigFileContent(configJson, parseConfigHost, workspaceRoot, {}, basename(tsconfigPath), undefined, [
configJson,
parseConfigHost,
workspaceRoot,
{},
basename(tsconfigPath),
undefined,
[
{ extension: '.vue', isMixedContent: true, scriptKind: ts.ScriptKind.Deferred }, { extension: '.vue', isMixedContent: true, scriptKind: ts.ScriptKind.Deferred },
{ extension: '.svelte', isMixedContent: true, scriptKind: ts.ScriptKind.Deferred }, { extension: '.svelte', isMixedContent: true, scriptKind: ts.ScriptKind.Deferred },
{ extension: '.astro', isMixedContent: true, scriptKind: ts.ScriptKind.Deferred } { extension: '.astro', isMixedContent: true, scriptKind: ts.ScriptKind.Deferred },
] ]);
);
let projectVersion = 0; let projectVersion = 0;
const snapshotManager = new SnapshotManager(project.fileNames, { exclude: ['node_modules', 'dist'], include: ['astro'] }, workspaceRoot || process.cwd()); const snapshotManager = new SnapshotManager(project.fileNames, { exclude: ['node_modules', 'dist'], include: ['astro'] }, workspaceRoot || process.cwd());
@ -100,15 +92,15 @@ async function createLanguageService(tsconfigPath: string, workspaceRoot: string
getProjectVersion: () => `${projectVersion}`, getProjectVersion: () => `${projectVersion}`,
getScriptFileNames: () => Array.from(new Set([...snapshotManager.getFileNames(), ...snapshotManager.getProjectFileNames()])), getScriptFileNames: () => Array.from(new Set([...snapshotManager.getFileNames(), ...snapshotManager.getProjectFileNames()])),
getScriptSnapshot, getScriptSnapshot,
getScriptVersion: (fileName: string) => getScriptSnapshot(fileName).version.toString() getScriptVersion: (fileName: string) => getScriptSnapshot(fileName).version.toString(),
}; };
const languageService = ts.createLanguageService(host); const languageService = ts.createLanguageService(host);
const languageServiceProxy = new Proxy(languageService, { const languageServiceProxy = new Proxy(languageService, {
get(target, prop) { get(target, prop) {
return Reflect.get(target, prop); return Reflect.get(target, prop);
} },
}) });
return { return {
tsconfigPath, tsconfigPath,
@ -148,10 +140,7 @@ async function createLanguageService(tsconfigPath: string, workspaceRoot: string
return doc; return doc;
} }
doc = createDocumentSnapshot( doc = createDocumentSnapshot(fileName, docContext.createDocument);
fileName,
docContext.createDocument,
);
snapshotManager.set(fileName, doc); snapshotManager.set(fileName, doc);
return doc; return doc;
} }
@ -168,7 +157,7 @@ function getDefaultJsConfig(): {
compilerOptions: { compilerOptions: {
maxNodeModuleJsDepth: 2, maxNodeModuleJsDepth: 2,
allowSyntheticDefaultImports: true, allowSyntheticDefaultImports: true,
allowJs: true allowJs: true,
}, },
include: ['astro'], include: ['astro'],
}; };

View file

@ -3,9 +3,7 @@ import { CompletionItemKind, DiagnosticSeverity } from 'vscode-languageserver';
import { dirname } from 'path'; import { dirname } from 'path';
import { pathToUrl } from '../../utils'; import { pathToUrl } from '../../utils';
export function scriptElementKindToCompletionItemKind( export function scriptElementKindToCompletionItemKind(kind: ts.ScriptElementKind): CompletionItemKind {
kind: ts.ScriptElementKind
): CompletionItemKind {
switch (kind) { switch (kind) {
case ts.ScriptElementKind.primitiveType: case ts.ScriptElementKind.primitiveType:
case ts.ScriptElementKind.keyword: case ts.ScriptElementKind.keyword:
@ -49,9 +47,7 @@ export function scriptElementKindToCompletionItemKind(
return CompletionItemKind.Property; return CompletionItemKind.Property;
} }
export function getCommitCharactersForScriptElement( export function getCommitCharactersForScriptElement(kind: ts.ScriptElementKind): string[] | undefined {
kind: ts.ScriptElementKind
): string[] | undefined {
const commitCharacters: string[] = []; const commitCharacters: string[] = [];
switch (kind) { switch (kind) {
case ts.ScriptElementKind.memberGetAccessorElement: case ts.ScriptElementKind.memberGetAccessorElement:
@ -137,10 +133,7 @@ export function ensureRealAstroFilePath(filePath: string) {
export function findTsConfigPath(fileName: string, rootUris: string[]) { export function findTsConfigPath(fileName: string, rootUris: string[]) {
const searchDir = dirname(fileName); const searchDir = dirname(fileName);
const path = const path = ts.findConfigFile(searchDir, ts.sys.fileExists, 'tsconfig.json') || ts.findConfigFile(searchDir, ts.sys.fileExists, 'jsconfig.json') || '';
ts.findConfigFile(searchDir, ts.sys.fileExists, 'tsconfig.json') ||
ts.findConfigFile(searchDir, ts.sys.fileExists, 'jsconfig.json') ||
'';
// Don't return config files that exceed the current workspace context. // Don't return config files that exceed the current workspace context.
return !!path && rootUris.some((rootUri) => isSubPath(rootUri, path)) ? path : ''; return !!path && rootUris.some((rootUri) => isSubPath(rootUri, path)) ? path : '';
} }
@ -150,7 +143,6 @@ export function isSubPath(uri: string, possibleSubPath: string): boolean {
return pathToUrl(possibleSubPath).startsWith(uri); return pathToUrl(possibleSubPath).startsWith(uri);
} }
/** Substitutes */ /** Substitutes */
export function substituteWithWhitespace(result: string, start: number, end: number, oldContent: string, before: string, after: string) { export function substituteWithWhitespace(result: string, start: number, end: number, oldContent: string, before: string, after: string) {
let accumulatedWS = 0; let accumulatedWS = 0;

View file

@ -21,7 +21,6 @@ export function pathToUrl(path: string) {
return URI.file(path).toString(); return URI.file(path).toString();
} }
/** /**
* *
* The language service is case insensitive, and would provide * The language service is case insensitive, and would provide
@ -54,18 +53,12 @@ export function clamp(num: number, min: number, max: number): number {
/** Checks if a position is inside range */ /** Checks if a position is inside range */
export function isInRange(positionToTest: Position, range: Range): boolean { export function isInRange(positionToTest: Position, range: Range): boolean {
return ( return isBeforeOrEqualToPosition(range.end, positionToTest) && isBeforeOrEqualToPosition(positionToTest, range.start);
isBeforeOrEqualToPosition(range.end, positionToTest) &&
isBeforeOrEqualToPosition(positionToTest, range.start)
);
} }
/** */ /** */
export function isBeforeOrEqualToPosition(position: Position, positionToTest: Position): boolean { export function isBeforeOrEqualToPosition(position: Position, positionToTest: Position): boolean {
return ( return positionToTest.line < position.line || (positionToTest.line === position.line && positionToTest.character <= position.character);
positionToTest.line < position.line ||
(positionToTest.line === position.line && positionToTest.character <= position.character)
);
} }
/** /**
@ -76,11 +69,7 @@ export function isBeforeOrEqualToPosition(position: Position, positionToTest: Po
* @param determineIfSame The function which determines if the previous invocation should be canceld or not * @param determineIfSame The function which determines if the previous invocation should be canceld or not
* @param miliseconds Number of miliseconds to debounce * @param miliseconds Number of miliseconds to debounce
*/ */
export function debounceSameArg<T>( export function debounceSameArg<T>(fn: (arg: T) => void, shouldCancelPrevious: (newArg: T, prevArg?: T) => boolean, miliseconds: number): (arg: T) => void {
fn: (arg: T) => void,
shouldCancelPrevious: (newArg: T, prevArg?: T) => boolean,
miliseconds: number
): (arg: T) => void {
let timeout: any; let timeout: any;
let prevArg: T | undefined; let prevArg: T | undefined;

View file

@ -2,8 +2,8 @@
"extends": "../../tsconfig.base.json", "extends": "../../tsconfig.base.json",
"compilerOptions": { "compilerOptions": {
"outDir": "dist", "outDir": "dist",
"rootDir": "src", "rootDir": "src"
}, },
"include": ["src"], "include": ["src"],
"exclude": ["node_modules"], "exclude": ["node_modules"]
} }

View file

@ -1,9 +1,7 @@
{ {
"fileTypes": [ "fileTypes": ["astro"],
"astro" "foldingStartMarker": "(?x)\n(<(?i:head|body|table|thead|tbody|tfoot|tr|div|select|fieldset|style|script|ul|ol|li|form|dl)\\b.*?>\n|<!--(?!.*--\\s*>)\n|^<!--\\ \\#tminclude\\ (?>.*?-->)$\n|<\\?(?:php)?.*\\b(if|for(each)?|while)\\b.+:\n|\\{\\{?(if|foreach|capture|literal|foreach|php|section|strip)\n|\\{\\s*($|\\?>\\s*$|//|/\\*(.*\\*/\\s*$|(?!.*?\\*/)))\n)",
], "foldingStopMarker": "(?x)\n(</(?i:head|body|table|thead|tbody|tfoot|tr|div|select|fieldset|style|script|ul|ol|li|form|dl)>\n|^(?!.*?<!--).*?--\\s*>\n|^<!--\\ end\\ tminclude\\ -->$\n|<\\?(?:php)?.*\\bend(if|for(each)?|while)\\b\n|\\{\\{?/(if|foreach|capture|literal|foreach|php|section|strip)\n|^[^{]*\\}\n)",
"foldingStartMarker": "(?x)\n(<(?i:head|body|table|thead|tbody|tfoot|tr|div|select|fieldset|style|script|ul|ol|li|form|dl)\\b.*?>\n|<!--(?!.*--\\s*>)\n|^<!--\\ \\#tminclude\\ (?>.*?-->)$\n|<\\?(?:php)?.*\\b(if|for(each)?|while)\\b.+:\n|\\{\\{?(if|foreach|capture|literal|foreach|php|section|strip)\n|\\{\\s*($|\\?>\\s*$|\/\/|\/\\*(.*\\*\/\\s*$|(?!.*?\\*\/)))\n)",
"foldingStopMarker": "(?x)\n(<\/(?i:head|body|table|thead|tbody|tfoot|tr|div|select|fieldset|style|script|ul|ol|li|form|dl)>\n|^(?!.*?<!--).*?--\\s*>\n|^<!--\\ end\\ tminclude\\ -->$\n|<\\?(?:php)?.*\\bend(if|for(each)?|while)\\b\n|\\{\\{?\/(if|foreach|capture|literal|foreach|php|section|strip)\n|^[^{]*\\}\n)",
"keyEquivalent": "^~H", "keyEquivalent": "^~H",
"name": "Astro", "name": "Astro",
"patterns": [ "patterns": [
@ -11,7 +9,7 @@
"include": "#astro-expressions" "include": "#astro-expressions"
}, },
{ {
"begin": "(<)([a-zA-Z0-9:-]++)(?=[^>]*><\/\\2>)", "begin": "(<)([a-zA-Z0-9:-]++)(?=[^>]*></\\2>)",
"beginCaptures": { "beginCaptures": {
"1": { "1": {
"name": "punctuation.definition.tag.begin.html" "name": "punctuation.definition.tag.begin.html"
@ -20,7 +18,7 @@
"name": "entity.name.tag.html" "name": "entity.name.tag.html"
} }
}, },
"end": "(>)(<)(\/)(\\2)(>)", "end": "(>)(<)(/)(\\2)(>)",
"endCaptures": { "endCaptures": {
"1": { "1": {
"name": "punctuation.definition.tag.end.html" "name": "punctuation.definition.tag.end.html"
@ -135,7 +133,7 @@
"name": "punctuation.definition.tag.html" "name": "punctuation.definition.tag.html"
} }
}, },
"end": "(<\/)((?i:style))(>)(?:\\s*\\n)?", "end": "(</)((?i:style))(>)(?:\\s*\\n)?",
"name": "source.css.embedded.html", "name": "source.css.embedded.html",
"patterns": [ "patterns": [
{ {
@ -148,7 +146,7 @@
"name": "punctuation.definition.tag.end.html" "name": "punctuation.definition.tag.end.html"
} }
}, },
"end": "(?=<\/(?i:style))", "end": "(?=</(?i:style))",
"patterns": [ "patterns": [
{ {
"include": "source.css" "include": "source.css"
@ -170,7 +168,7 @@
"name": "punctuation.definition.tag.html" "name": "punctuation.definition.tag.html"
} }
}, },
"end": "(<\/)((?i:style))(>)(?:\\s*\\n)?", "end": "(</)((?i:style))(>)(?:\\s*\\n)?",
"name": "source.sass.embedded.html", "name": "source.sass.embedded.html",
"patterns": [ "patterns": [
{ {
@ -183,7 +181,7 @@
"name": "punctuation.definition.tag.end.html" "name": "punctuation.definition.tag.end.html"
} }
}, },
"end": "(?=<\/(?i:style))", "end": "(?=</(?i:style))",
"patterns": [ "patterns": [
{ {
"include": "source.sass" "include": "source.sass"
@ -205,7 +203,7 @@
"name": "punctuation.definition.tag.html" "name": "punctuation.definition.tag.html"
} }
}, },
"end": "(<\/)((?i:style))(>)(?:\\s*\\n)?", "end": "(</)((?i:style))(>)(?:\\s*\\n)?",
"name": "source.scss.embedded.html", "name": "source.scss.embedded.html",
"patterns": [ "patterns": [
{ {
@ -218,7 +216,7 @@
"name": "punctuation.definition.tag.end.html" "name": "punctuation.definition.tag.end.html"
} }
}, },
"end": "(?=<\/(?i:style))", "end": "(?=</(?i:style))",
"patterns": [ "patterns": [
{ {
"include": "source.css.scss" "include": "source.css.scss"
@ -228,7 +226,7 @@
] ]
}, },
{ {
"begin": "(?:^\\s+)?(<)((?i:style))\\b(?![^>]*\/>)", "begin": "(?:^\\s+)?(<)((?i:style))\\b(?![^>]*/>)",
"captures": { "captures": {
"1": { "1": {
"name": "punctuation.definition.tag.begin.html" "name": "punctuation.definition.tag.begin.html"
@ -240,8 +238,10 @@
"name": "punctuation.definition.tag.html" "name": "punctuation.definition.tag.html"
} }
}, },
"end": "(<\/)((?i:style))(>)(?:\\s*\\n)?", "end": "(</)((?i:style))(>)(?:\\s*\\n)?",
"__DEFAULT_STYLE_NAME_START__": null,"name": "source.css.embedded.html","__DEFAULT_STYLE_NAME_END__": null, "__DEFAULT_STYLE_NAME_START__": null,
"name": "source.css.embedded.html",
"__DEFAULT_STYLE_NAME_END__": null,
"patterns": [ "patterns": [
{ {
"include": "#tag-stuff" "include": "#tag-stuff"
@ -253,10 +253,12 @@
"name": "punctuation.definition.tag.end.html" "name": "punctuation.definition.tag.end.html"
} }
}, },
"end": "(?=<\/(?i:style))", "end": "(?=</(?i:style))",
"patterns": [ "patterns": [
{ {
"__DEFAULT_STYLE_INCLUDE_START__": null,"include": "source.css","__DEFAULT_STYLE_INCLUDE_END__": null "__DEFAULT_STYLE_INCLUDE_START__": null,
"include": "source.css",
"__DEFAULT_STYLE_INCLUDE_END__": null
} }
] ]
} }
@ -272,7 +274,7 @@
"name": "entity.name.tag.script.html" "name": "entity.name.tag.script.html"
} }
}, },
"end": "(?<=<\/(script|SCRIPT))(>)(?:\\s*\\n)?", "end": "(?<=</(script|SCRIPT))(>)(?:\\s*\\n)?",
"endCaptures": { "endCaptures": {
"2": { "2": {
"name": "punctuation.definition.tag.html" "name": "punctuation.definition.tag.html"
@ -284,7 +286,7 @@
"include": "#tag-stuff" "include": "#tag-stuff"
}, },
{ {
"begin": "(?<!<\/(?:script|SCRIPT))(>)", "begin": "(?<!</(?:script|SCRIPT))(>)",
"captures": { "captures": {
"1": { "1": {
"name": "punctuation.definition.tag.begin.html" "name": "punctuation.definition.tag.begin.html"
@ -293,7 +295,7 @@
"name": "entity.name.tag.script.html" "name": "entity.name.tag.script.html"
} }
}, },
"end": "(<\/)((?i:script))", "end": "(</)((?i:script))",
"patterns": [ "patterns": [
{ {
"include": "source.tsx" "include": "source.tsx"
@ -312,7 +314,7 @@
"name": "entity.name.tag.script.html" "name": "entity.name.tag.script.html"
} }
}, },
"end": "(?<=<\/(script|SCRIPT))(>)(?:\\s*\\n)?", "end": "(?<=</(script|SCRIPT))(>)(?:\\s*\\n)?",
"endCaptures": { "endCaptures": {
"2": { "2": {
"name": "punctuation.definition.tag.html" "name": "punctuation.definition.tag.html"
@ -324,7 +326,7 @@
"include": "#tag-stuff" "include": "#tag-stuff"
}, },
{ {
"begin": "(?<!<\/(?:script|SCRIPT))(>)", "begin": "(?<!</(?:script|SCRIPT))(>)",
"captures": { "captures": {
"1": { "1": {
"name": "punctuation.definition.tag.begin.html" "name": "punctuation.definition.tag.begin.html"
@ -333,7 +335,7 @@
"name": "entity.name.tag.script.html" "name": "entity.name.tag.script.html"
} }
}, },
"end": "(<\/)((?i:script))", "end": "(</)((?i:script))",
"patterns": [ "patterns": [
{ {
"include": "source.tsx" "include": "source.tsx"
@ -343,7 +345,7 @@
] ]
}, },
{ {
"begin": "(<)((?i:script))\\b(?![^>]*\/>)(?![^>]*(?i:type.?=.?text\/((?!javascript|babel|ecmascript).*)))", "begin": "(<)((?i:script))\\b(?![^>]*/>)(?![^>]*(?i:type.?=.?text/((?!javascript|babel|ecmascript).*)))",
"beginCaptures": { "beginCaptures": {
"1": { "1": {
"name": "punctuation.definition.tag.begin.html" "name": "punctuation.definition.tag.begin.html"
@ -352,7 +354,7 @@
"name": "entity.name.tag.script.html" "name": "entity.name.tag.script.html"
} }
}, },
"end": "(?<=<\/(script|SCRIPT))(>)(?:\\s*\\n)?", "end": "(?<=</(script|SCRIPT))(>)(?:\\s*\\n)?",
"endCaptures": { "endCaptures": {
"2": { "2": {
"name": "punctuation.definition.tag.html" "name": "punctuation.definition.tag.html"
@ -364,7 +366,7 @@
"include": "#tag-stuff" "include": "#tag-stuff"
}, },
{ {
"begin": "(?<!<\/(?:script|SCRIPT))(>)", "begin": "(?<!</(?:script|SCRIPT))(>)",
"captures": { "captures": {
"1": { "1": {
"name": "punctuation.definition.tag.begin.html" "name": "punctuation.definition.tag.begin.html"
@ -373,7 +375,7 @@
"name": "entity.name.tag.script.html" "name": "entity.name.tag.script.html"
} }
}, },
"end": "(<\/)((?i:script))", "end": "(</)((?i:script))",
"patterns": [ "patterns": [
{ {
"captures": { "captures": {
@ -381,17 +383,17 @@
"name": "punctuation.definition.comment.js" "name": "punctuation.definition.comment.js"
} }
}, },
"match": "(\/\/).*?((?=<\/script)|$\\n?)", "match": "(//).*?((?=</script)|$\\n?)",
"name": "comment.line.double-slash.js" "name": "comment.line.double-slash.js"
}, },
{ {
"begin": "\/\\*", "begin": "/\\*",
"captures": [ "captures": [
{ {
"name": "punctuation.definition.comment.js" "name": "punctuation.definition.comment.js"
} }
], ],
"end": "\\*\/|(?=<\/script)", "end": "\\*/|(?=</script)",
"name": "comment.block.js" "name": "comment.block.js"
}, },
{ {
@ -402,7 +404,7 @@
] ]
}, },
{ {
"begin": "(<\/?)((?i:body|head|html)\\b)", "begin": "(</?)((?i:body|head|html)\\b)",
"captures": { "captures": {
"1": { "1": {
"name": "punctuation.definition.tag.begin.html" "name": "punctuation.definition.tag.begin.html"
@ -425,7 +427,7 @@
] ]
}, },
{ {
"begin": "(<\/?)((?i:address|blockquote|dd|div|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)", "begin": "(</?)((?i:address|blockquote|dd|div|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)",
"beginCaptures": { "beginCaptures": {
"1": { "1": {
"name": "punctuation.definition.tag.begin.html" "name": "punctuation.definition.tag.begin.html"
@ -448,7 +450,7 @@
] ]
}, },
{ {
"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)", "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)",
"beginCaptures": { "beginCaptures": {
"1": { "1": {
"name": "punctuation.definition.tag.begin.html" "name": "punctuation.definition.tag.begin.html"
@ -457,7 +459,7 @@
"name": "entity.name.tag.inline.any.html" "name": "entity.name.tag.inline.any.html"
} }
}, },
"end": "((?: ?\/)?>)", "end": "((?: ?/)?>)",
"endCaptures": { "endCaptures": {
"1": { "1": {
"name": "punctuation.definition.tag.end.html" "name": "punctuation.definition.tag.end.html"
@ -471,7 +473,7 @@
] ]
}, },
{ {
"begin": "(<\/?)([a-zA-Z0-9:-]+)", "begin": "(</?)([a-zA-Z0-9:-]+)",
"beginCaptures": { "beginCaptures": {
"1": { "1": {
"name": "punctuation.definition.tag.begin.html" "name": "punctuation.definition.tag.begin.html"

View file

@ -1,4 +1,3 @@
{ {
"compilerOptions": { "compilerOptions": {
"target": "es2019", "target": "es2019",
@ -13,6 +12,6 @@
"baseUrl": "./", "baseUrl": "./",
"paths": { "paths": {
"@astro-vscode/*": ["packages/*/src"] "@astro-vscode/*": ["packages/*/src"]
}, }
}, }
} }

View file

@ -1,4 +1,3 @@
{ {
"extends": "./tsconfig.base.json", "extends": "./tsconfig.base.json",
"files": [], "files": [],

View file

@ -1,4 +1,3 @@
module.exports = { module.exports = {
workspaceRoot: '../' workspaceRoot: '../',
}; };

View file

@ -1656,7 +1656,7 @@
resolved "https://registry.npmjs.org/@types/yoga-layout/-/yoga-layout-1.9.2.tgz" resolved "https://registry.npmjs.org/@types/yoga-layout/-/yoga-layout-1.9.2.tgz"
integrity sha512-S9q47ByT2pPvD65IvrWp7qppVMpk9WGMbVq9wbWZOHg6tnXSD4vyhao6nOSBwwfDdV2p3Kx9evA9vI+XWTfDvw== integrity sha512-S9q47ByT2pPvD65IvrWp7qppVMpk9WGMbVq9wbWZOHg6tnXSD4vyhao6nOSBwwfDdV2p3Kx9evA9vI+XWTfDvw==
"@typescript-eslint/eslint-plugin@^4.18.0": "@typescript-eslint/eslint-plugin@^4.22.0":
version "4.22.0" version "4.22.0"
resolved "https://registry.yarnpkg.com/@typescript-eslint/eslint-plugin/-/eslint-plugin-4.22.0.tgz#3d5f29bb59e61a9dba1513d491b059e536e16dbc" resolved "https://registry.yarnpkg.com/@typescript-eslint/eslint-plugin/-/eslint-plugin-4.22.0.tgz#3d5f29bb59e61a9dba1513d491b059e536e16dbc"
integrity sha512-U8SP9VOs275iDXaL08Ln1Fa/wLXfj5aTr/1c0t0j6CdbOnxh+TruXu1p4I0NAvdPBQgoPjHsgKn28mOi0FzfoA== integrity sha512-U8SP9VOs275iDXaL08Ln1Fa/wLXfj5aTr/1c0t0j6CdbOnxh+TruXu1p4I0NAvdPBQgoPjHsgKn28mOi0FzfoA==
@ -4278,12 +4278,12 @@ escape-string-regexp@^2.0.0:
resolved "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-2.0.0.tgz" resolved "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-2.0.0.tgz"
integrity sha512-UpzcLCXolUWcNu5HtVMHYdXJjArjsF9C0aNnquZYY4uW/Vu0miy5YoWvbV345HauVvcAUnpRuhMMcqTcGOY2+w== integrity sha512-UpzcLCXolUWcNu5HtVMHYdXJjArjsF9C0aNnquZYY4uW/Vu0miy5YoWvbV345HauVvcAUnpRuhMMcqTcGOY2+w==
eslint-config-prettier@^8.1.0: eslint-config-prettier@^8.3.0:
version "8.3.0" version "8.3.0"
resolved "https://registry.yarnpkg.com/eslint-config-prettier/-/eslint-config-prettier-8.3.0.tgz#f7471b20b6fe8a9a9254cc684454202886a2dd7a" resolved "https://registry.yarnpkg.com/eslint-config-prettier/-/eslint-config-prettier-8.3.0.tgz#f7471b20b6fe8a9a9254cc684454202886a2dd7a"
integrity sha512-BgZuLUSeKzvlL/VUjx/Yb787VQ26RU3gGjA3iiFvdsp/2bMfVIWUVP7tjxtjS0e+HP409cPlPvNkQloz8C91ew== integrity sha512-BgZuLUSeKzvlL/VUjx/Yb787VQ26RU3gGjA3iiFvdsp/2bMfVIWUVP7tjxtjS0e+HP409cPlPvNkQloz8C91ew==
eslint-plugin-prettier@^3.3.1: eslint-plugin-prettier@^3.4.0:
version "3.4.0" version "3.4.0"
resolved "https://registry.yarnpkg.com/eslint-plugin-prettier/-/eslint-plugin-prettier-3.4.0.tgz#cdbad3bf1dbd2b177e9825737fe63b476a08f0c7" resolved "https://registry.yarnpkg.com/eslint-plugin-prettier/-/eslint-plugin-prettier-3.4.0.tgz#cdbad3bf1dbd2b177e9825737fe63b476a08f0c7"
integrity sha512-UDK6rJT6INSfcOo545jiaOwB701uAIt2/dR7WnFQoGCVl1/EMqdANBmwUaqqQ45aXprsTGzSa39LI1PyuRBxxw== integrity sha512-UDK6rJT6INSfcOo545jiaOwB701uAIt2/dR7WnFQoGCVl1/EMqdANBmwUaqqQ45aXprsTGzSa39LI1PyuRBxxw==
@ -4315,7 +4315,7 @@ eslint-visitor-keys@^2.0.0:
resolved "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-2.0.0.tgz" resolved "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-2.0.0.tgz"
integrity sha512-QudtT6av5WXels9WjIM7qz1XD1cWGvX4gGXvp/zBn9nXG02D0utdU3Em2m/QjTnrsk6bBjmCygl3rmj118msQQ== integrity sha512-QudtT6av5WXels9WjIM7qz1XD1cWGvX4gGXvp/zBn9nXG02D0utdU3Em2m/QjTnrsk6bBjmCygl3rmj118msQQ==
eslint@^7.22.0: eslint@^7.25.0:
version "7.25.0" version "7.25.0"
resolved "https://registry.yarnpkg.com/eslint/-/eslint-7.25.0.tgz#1309e4404d94e676e3e831b3a3ad2b050031eb67" resolved "https://registry.yarnpkg.com/eslint/-/eslint-7.25.0.tgz#1309e4404d94e676e3e831b3a3ad2b050031eb67"
integrity sha512-TVpSovpvCNpLURIScDRB6g5CYu/ZFq9GfX2hLNIV4dSBKxIWojeDODvYl3t0k0VtMxYeR8OXPCFE5+oHMlGfhw== integrity sha512-TVpSovpvCNpLURIScDRB6g5CYu/ZFq9GfX2hLNIV4dSBKxIWojeDODvYl3t0k0VtMxYeR8OXPCFE5+oHMlGfhw==