Skip to content

Chore: upgrade vite to v3 #183

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Jul 13, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ module.exports = {
},
},
{
files: ["*.ts"],
files: ["*.ts", "*.mts"],
parser: "@typescript-eslint/parser",
parserOptions: {
sourceType: "module",
Expand Down
2 changes: 1 addition & 1 deletion docs-svelte-kit/.eslintrc.cjs
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
// eslint-disable-next-line no-undef -- ignore
module.exports = {
extends: ["plugin:svelte/recommended"],
env: {
Expand All @@ -15,5 +14,6 @@ module.exports = {
"svelte/prefer-class-directive": "error",
"svelte/prefer-style-directive": "error",
"svelte/spaced-html-comment": "error",
"node/file-extension-in-import": "off",
},
}
Original file line number Diff line number Diff line change
@@ -1,21 +1,28 @@
const esbuild = require("esbuild")
const path = require("path")
const fs = require("fs")
import esbuild from "esbuild"
import path from "path"
import fs from "fs"
// const babelCore = require("@babel/core")
// const t = require("@babel/types")

const dirname = path.dirname(
new URL(
// @ts-expect-error -- Cannot change `module` option
import.meta.url,
).pathname,
)

build(
require.resolve("./src/eslint.mjs"),
path.join(__dirname, "../shim/eslint.mjs"),
path.join(dirname, "./src/eslint.mjs"),
path.join(dirname, "../shim/eslint.mjs"),
["assert", "util"],
)
build(
require.resolve("../../node_modules/assert"),
path.join(__dirname, "../shim/assert.mjs"),
path.join(dirname, "../../node_modules/assert"),
path.join(dirname, "../shim/assert.mjs"),
)

/** build */
function build(input, out, injects = []) {
function build(input: string, out: string, injects: string[] = []) {
// eslint-disable-next-line no-console -- ignore
console.log(`build@ ${input}`)
let code = bundle(input, ["path", ...injects])
Expand All @@ -24,21 +31,21 @@ function build(input, out, injects = []) {
}

/** bundle */
function bundle(entryPoint, externals) {
function bundle(entryPoint: string, externals: string[]) {
const result = esbuild.buildSync({
entryPoints: [entryPoint],
format: "esm",
bundle: true,
external: externals,
write: false,
inject: [require.resolve("./src/process-shim.mjs")],
inject: [path.join(dirname, "./src/process-shim.mjs")],
})

return `${result.outputFiles[0].text}`
}

/** transform code */
function transform(code, injects) {
function transform(code: string, injects: string[]) {
const newCode = code.replace(/"[a-z]+" = "[a-z]+";/, "")
// const newCode = babelCore.transformSync(code, {
// babelrc: false,
Expand Down
6 changes: 3 additions & 3 deletions docs-svelte-kit/shim/module.mjs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
/* eslint require-jsdoc:0 -- shim */
function createRequire() {
function _createRequire() {
return () => null
}

export { createRequire }
export default { createRequire }
export { _createRequire as createRequire }
export default { createRequire: _createRequire }
3 changes: 1 addition & 2 deletions docs-svelte-kit/src/lib/eslint/scripts/linter.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
// eslint-disable-next-line node/file-extension-in-import -- ignore
import { rules as pluginRules } from "../../../../../src/utils/rules.ts"
import { Linter } from "eslint"
import * as svelteEslintParser from "svelte-eslint-parser"
// eslint-disable-next-line node/file-extension-in-import -- ignore

export { preprocess, postprocess } from "../../../../../src/processor/index.ts"

const linter = new Linter()
Expand Down
1 change: 0 additions & 1 deletion docs-svelte-kit/src/lib/utils.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
// eslint-disable-next-line node/file-extension-in-import -- ignore
import { rules } from "../../../src/utils/rules.ts"
import { readable, writable } from "svelte/store"
// eslint-disable-next-line node/no-missing-import -- ignore
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,12 @@ import "prism-svelte"
loadLanguages(["markup", "css", "javascript"])

/** Wrap pre tag */
function wrapPre(code, lang) {
function wrapPre(code: string, lang: string) {
const htmlCode = lang === "text" ? escapeHtml(code) : code
return `<pre class="language-${lang}"><code>${htmlCode}</code></pre>`
}

const EXTENSION_MAPPINGS = {
const EXTENSION_MAPPINGS: Record<string, string | undefined> = {
vue: "markup",
html: "markup",
svelte: "svelte",
Expand All @@ -28,7 +28,7 @@ const EXTENSION_MAPPINGS = {
rs: "rust",
}

export default (str, lang) => {
export default (str: string, lang: string): string => {
if (!lang) {
return wrapPre(str, "text")
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,21 +1,23 @@
import type Md from "markdown-it"
import type Token from "markdown-it/lib/token"
/**
* @param {import('markdown-it')} md
*/
export default (md) => {
export default (md: Md): void => {
md.core.ruler.push("auto_inject_components", (state) => {
const injected = new Set(extractInjectedComponents(state.tokens))
for (const component of new Set(
extractComponents(state.tokens, injected),
)) {
const newToken = new state.Token("auto_inject_component")
const newToken = new state.Token("auto_inject_component", "", 0)
newToken.content = `<script>
import ${component} from '$lib/components/${component}.svelte'
</script>`
state.tokens.unshift(newToken)
}

/** Extract imported components */
function* extractInjectedComponents(tokens) {
function* extractInjectedComponents(tokens: Token[]): Iterable<string> {
for (const token of tokens) {
if (
(token.type === "html_inline" || token.type === "html_block") &&
Expand All @@ -33,7 +35,10 @@ import ${component} from '$lib/components/${component}.svelte'
}

/** Extract inject components */
function* extractComponents(tokens, injected) {
function* extractComponents(
tokens: Token[],
injected: Set<string>,
): Iterable<string> {
for (const token of tokens) {
if (token.type === "html_inline" || token.type === "html_block") {
const match = /<([A-Z][\w$]*)/u.exec(token.content)
Expand All @@ -47,7 +52,7 @@ import ${component} from '$lib/components/${component}.svelte'
}
}
})
// eslint-disable-next-line camelcase -- ignore

md.renderer.rules.auto_inject_component = (tokens, idx, _options) => {
return tokens[idx].content
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,13 @@
import type containerPlugin from "markdown-it-container"
type ContainerPluginOption = Parameters<typeof containerPlugin>[2]
/**
* Generate markdown-it-container option
* @see https://github.com/markdown-it/markdown-it-container
*/
export default (type, defaultTitle = type.toUpperCase()) => {
export default (
type: string,
defaultTitle = type.toUpperCase(),
): ContainerPluginOption => {
return {
render(tokens, index) {
const token = tokens[index]
Expand Down
Original file line number Diff line number Diff line change
@@ -1,15 +1,24 @@
import path from "path"
import spawn from "cross-spawn"
import type Md from "markdown-it"

type TreeItem = {
children: TreeItem[]
}
type TreeStack = { item: TreeItem; level: number; upper: TreeStack | null }

class TOCRenderer {
constructor(name) {
const item = { children: [] }
private readonly tree: TreeItem

private stack: TreeStack

public constructor() {
const item: TreeItem = { children: [] }
this.tree = item
this.stack = { item, level: 1, upper: null }
this.name = name
}

addMenu(level, id, title) {
public addMenu(level: number, id: string, title: string) {
if (this.stack.level < level) {
const parent = this.stack.item
const item = parent.children[parent.children.length - 1]
Expand All @@ -24,53 +33,52 @@ class TOCRenderer {
this.stack.item.children.push(item)
}

toc() {
public toc() {
return this.tree
}
}
/**
* @param {import('markdown-it')} md
*/
export default (md) => {
export default (md: Md): void => {
md.core.ruler.push("custom_markdown", (state) => {
const tokens = state.tokens
tokens.unshift(new state.Token("custom_markdown_data"))
tokens.unshift(new state.Token("custom_markdown_data", "", 0))
})
// eslint-disable-next-line camelcase -- ignore

md.renderer.rules.custom_markdown_data = (
tokens,
_idx,
_options,
env,
_self,
) => {
const name = path.basename(env.id).replace(/\.md$/, "")
const renderer = new TOCRenderer(name)
const renderer = new TOCRenderer()
for (let idx = 0; idx < tokens.length; idx++) {
const token = tokens[idx]

if (token.type !== "heading_open") {
continue
}
let level = Number(token.tag.substr(1))
const level = Number(token.tag.slice(1))
if (level > 3) {
continue
}
// Aggregate the next token children text.
const title = tokens[idx + 1].children
.filter(
const title = tokens[idx + 1]
.children!.filter(
(token) =>
token.type === "text" ||
token.type === "emoji" ||
token.type === "code_inline",
)
.reduce((acc, t) => acc + t.content, "")

let slug = token.attrGet("id")
const slug = token.attrGet("id")!
renderer.addMenu(level, slug, title)
}

const fileInfo = {}
const fileInfo: { timestamp?: number; lastUpdated?: string } = {}
const timestamp = getGitLastUpdatedTimestamp(env.id)
if (timestamp) {
fileInfo.timestamp = timestamp
Expand All @@ -85,7 +93,7 @@ export default (md) => {
}

/** Get last updated timestamp */
function getGitLastUpdatedTimestamp(filePath) {
function getGitLastUpdatedTimestamp(filePath: string) {
let lastUpdated
try {
lastUpdated =
Expand Down
Original file line number Diff line number Diff line change
@@ -1,17 +1,17 @@
// eslint-disable-next-line eslint-comments/disable-enable-pair -- ignore
/* eslint-disable camelcase -- ignore */
import path from "path"
import type Md from "markdown-it"
import type Token from "markdown-it/lib/token"

export default (md, options = {}) => {
export default (md: Md, options: { baseUrl: string; root: string }): void => {
const base = options.baseUrl
const root = path.resolve(options.root)

/** Normalize href */
function normalizeHref(curr, href) {
function normalizeHref(curr: string, href: string) {
let absolutePath
let hash = ""
if (/\.md(?:#.*)?$/.test(href)) {
hash = /\.md(#.*)?$/.exec(href)[1] || ""
hash = /\.md(#.*)?$/.exec(href)![1] || ""
absolutePath = path.join(
path.dirname(curr),
hash ? href.slice(0, -hash.length) : href,
Expand All @@ -31,23 +31,23 @@ export default (md, options = {}) => {
const token = tokens[idx]
const hrefIndex = token.attrIndex("href")
if (hrefIndex >= 0) {
const link = token.attrs[hrefIndex]
const link = token.attrs![hrefIndex]
const href = link[1]
if (/^https?:/.test(href)) {
const proxyToken = {
...token,
attrs: [...token.attrs, ["target", "_blank"]],
}
attrs: [...token.attrs!, ["target", "_blank"]],
} as Token
return self.renderToken([proxyToken], 0, options)
} else if (/\.md(?:#.*)?$/.test(href) || /^#.*$/.test(href)) {
const proxyToken = {
...token,
attrs: [
...token.attrs.slice(0, hrefIndex - 1),
...token.attrs!.slice(0, hrefIndex - 1),
[link[0], normalizeHref(env.id, href)],
...token.attrs.slice(hrefIndex + 1),
...token.attrs!.slice(hrefIndex + 1),
],
}
} as Token
return self.renderToken([proxyToken], 0, options)
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,20 +1,21 @@
import type Md from "markdown-it"
/**
* @param {import('markdown-it')} md
*/
export default (md) => {
export default (md: Md): void => {
const headingOpen = md.renderer.rules.heading_open
// eslint-disable-next-line camelcase -- ignore

md.renderer.rules.heading_open = (tokens, idx, options, env, self) => {
const head = headingOpen
? headingOpen(tokens, idx, options, env, self)
: self.renderToken(tokens, idx, options)
const token = tokens[idx]
let level = Number(token.tag.substr(1))
const level = Number(token.tag.substr(1))
if (level > 1) {
return head
}
const title = tokens[idx + 1].children
.filter(
const title = tokens[idx + 1]
.children!.filter(
(token) =>
token.type === "text" ||
token.type === "emoji" ||
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,9 @@ import titlePlugin from "./markdown-it-title.mjs"
import markdownPlugin from "./markdown-it-markdown.mjs"
import containerPluginOption from "./markdown-it-container-option.mjs"
import slugify from "@sindresorhus/slugify"
import type { Options } from "vite-plugin-svelte-md"

export default (options = {}) => ({
export default (options: { baseUrl: string; root: string }): Options => ({
wrapperClasses: [],
markdownItOptions: {
highlight,
Expand Down
Loading