fix types

fix-build-duplicate-code
Nikhil Saraf 2 years ago
parent d5d6f9e5f0
commit fb0eebe8c4

@ -1,5 +1,6 @@
{
"editor.codeActionsOnSave": {
"source.organizeImports": true
}
},
"typescript.tsdk": "node_modules/typescript/lib"
}

@ -1,90 +0,0 @@
import fs from "fs";
import path from "path";
import { $, cd } from "zx";
let tailwindConfig = `module.exports = {
content: ["./src/**/*.{html,js,jsx,ts,tsx}"],
theme: {
extend: {}
},
plugins: []
};
`;
let postcssConfig = `module.exports = {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
}
`;
let tailwindCSS = `@tailwind base;
@tailwind components;
@tailwind utilities;`;
export default async function main(vite) {
cd(vite.root);
if (fs.existsSync(path.join(vite.root, ".git"))) {
await $`git add -A`;
}
let pkgJSON = JSON.parse(fs.readFileSync(path.join(vite.root, "package.json")).toString());
pkgJSON.devDependencies = {
...pkgJSON.devDependencies,
"solid-mdx": "*",
"@mdx-js/rollup": "*"
};
fs.writeFileSync(path.join(vite.root, "package.json"), JSON.stringify(pkgJSON, null, 2));
// fs.writeFileSync(path.join(vite.root, "vite.config"), tailwindConfig);
let config, vitep;
for (var vitePath of ["vite.config.js", "vite.config.ts"]) {
console.log(path.resolve(vite.root, vitePath));
if (fs.existsSync(path.resolve(vite.root, vitePath))) {
console.log("here", vitePath);
vitep = vitePath;
config = fs.readFileSync(path.resolve(vite.root, vitePath)).toString();
}
}
if (!config) {
console.error("Could not find vite.config");
return;
}
// replace solid() with solid({ extensions: [".mdx", ".md"] })
config = config
.replace(`solid({`, `solid({ extensions: [".mdx", ".md"], `)
.replace(`solid()`, `solid({ extensions: [".mdx", ".md"] })`)
.replace(
`plugins: [`,
`plugins: [
{
...(await import("@mdx-js/rollup")).default({
jsx: true,
jsxImportSource: "solid-js",
providerImportSource: "solid-mdx"
}),
enforce: "pre"
},`
);
console.log(config);
fs.writeFileSync(path.resolve(vite.root, vitep), config);
await $`npx prettier -w ${vitep}`;
// let newConfig = config.replace(
// fs.writeFileSync(path.join(vite.root, "postcss.config.cjs"), postcssConfig);
// fs.writeFileSync(path.join(vite.root, "src", "tailwind.css"), tailwindCSS);
// let root = path.join(vite.root, "src", "root.tsx");
// fs.writeFileSync(
// root,
// fs.readFileSync(root).toString().replace("import", 'import "./tailwind.css";\nimport')
// );
await $`npx @antfu/ni`;
}

@ -1,68 +0,0 @@
import fs from "fs";
import path from "path";
import { $, cd } from "zx";
export default async function main(vite) {
cd(vite.root);
if (fs.existsSync(path.join(vite.root, ".git"))) {
await $`git add -A`;
}
let pkgJSON = JSON.parse(fs.readFileSync(path.join(vite.root, "package.json")).toString());
pkgJSON.devDependencies = {
...pkgJSON.devDependencies,
playwright: "1.19.2",
"@playwright/test": "^1.18.1",
"npm-run-all": "latest",
"start-server-and-test": "latest",
"cross-env": "latest"
};
pkgJSON.scripts = {
...pkgJSON.scripts,
"start-server-and-test": "start-server-and-test build-and-start http://localhost:3000 test:e2e",
"build-and-start": "npm run build && npm run start",
"test:e2e": "npm-run-all -p test:e2e:*",
"test:e2e:js": "playwright test e2e/*.mjs",
"test:e2e:no-js": "cross-env DISABLE_JAVASCRIPT=true playwright test e2e/*.mjs"
};
fs.writeFileSync(path.join(vite.root, "package.json"), JSON.stringify(pkgJSON, null, 2));
fs.mkdirSync(path.join(vite.root, "e2e"), { recursive: true });
let specPath = path.join(vite.root, "e2e", "index.spec.mjs");
fs.writeFileSync(
specPath,
`
import { test, expect } from "@playwright/test";
test("basic login test", async ({ browser }) => {
let appURL = new URL(process.env.TEST_HOST ?? "http://localhost:3000/").href;
const context = await browser.newContext({
javaScriptEnabled: !process.env.DISABLE_JAVASCRIPT
});
const page = await context.newPage();
// go to home
await page.goto(appURL);
expect(page.url()).toBe(appURL);
});
`
);
// fs.writeFileSync(path.resolve(vite.root, vitep), config);
await $`npx prettier -w ${specPath}`;
// let newConfig = config.replace(
// fs.writeFileSync(path.join(vite.root, "postcss.config.cjs"), postcssConfig);
// fs.writeFileSync(path.join(vite.root, "src", "tailwind.css"), tailwindCSS);
// let root = path.join(vite.root, "src", "root.tsx");
// fs.writeFileSync(
// root,
// fs.readFileSync(root).toString().replace("import", 'import "./tailwind.css";\nimport')
// );
await $`npx @antfu/ni`;
await $`npx playwright install`;
}

@ -1,52 +0,0 @@
import fs from "fs";
import path from "path";
import { $, cd } from "zx";
let tailwindConfig = `module.exports = {
content: ["./src/**/*.{html,js,jsx,ts,tsx}"],
theme: {
extend: {}
},
plugins: []
};
`;
let postcssConfig = `module.exports = {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
}
`;
let tailwindCSS = `@tailwind base;
@tailwind components;
@tailwind utilities;`;
export default async function main(vite) {
cd(vite.root);
if (fs.existsSync(path.join(vite.root, ".git"))) {
await $`git add -A`;
}
let pkgJSON = JSON.parse(fs.readFileSync(path.join(vite.root, "package.json")).toString());
pkgJSON.devDependencies = {
...pkgJSON.devDependencies,
tailwindcss: "*",
autoprefixer: "*",
postcss: "*"
};
fs.writeFileSync(path.join(vite.root, "package.json"), JSON.stringify(pkgJSON, null, 2));
fs.writeFileSync(path.join(vite.root, "tailwind.config.cjs"), tailwindConfig);
fs.writeFileSync(path.join(vite.root, "postcss.config.cjs"), postcssConfig);
fs.writeFileSync(path.join(vite.root, "src", "tailwind.css"), tailwindCSS);
let root = path.join(vite.root, "src", "root.tsx");
fs.writeFileSync(
root,
fs.readFileSync(root).toString().replace("import", 'import "./tailwind.css";\nimport')
);
await $`npx @antfu/ni`;
}

@ -1,112 +0,0 @@
import fs from "fs";
import path from "path";
import { $, cd } from "zx";
let fixJestDom = `import fs from 'fs';
import path from 'path';
const typesPath = path.resolve('node_modules', '@types', 'testing-library__jest-dom', 'index.d.ts');
const refMatcher = /[\\r\\n]+\\/\\/\\/ <reference types="jest" \\/>/;
fs.readFile(typesPath, 'utf8', (err, data) => {
if (err) throw err;
fs.writeFile(
typesPath,
data.replace(refMatcher, ''),
'utf8',
function(err) {
if (err) throw err;
}
);
});
`;
export default async function main(vite) {
cd(vite.root);
if (fs.existsSync(path.join(vite.root, ".git"))) {
await $`git add -A`;
}
let pkgJSON = JSON.parse(fs.readFileSync(path.join(vite.root, "package.json")).toString());
pkgJSON.devDependencies = {
...pkgJSON.devDependencies,
"@testing-library/jest-dom": "^5.16.2",
"@types/testing-library__jest-dom": "^5.14.3",
"solid-testing-library": "^0.3.0",
jsdom: "^19.0.0",
vitest: "^0.6.1"
};
pkgJSON.scripts = {
...pkgJSON.scripts,
postinstall: "node ./fix-jest-dom.mjs",
"test:unit": "vitest"
};
fs.writeFileSync(path.join(vite.root, "package.json"), JSON.stringify(pkgJSON, null, 2));
fs.writeFileSync(
path.join(vite.root, "setupVitest.ts"),
`import '@testing-library/jest-dom';
`
);
fs.writeFileSync(path.join(vite.root, "fix-jest-dom.mjs"), fixJestDom);
let config, vitep;
for (var vitePath of ["vite.config.js", "vite.config.ts"]) {
console.log(path.resolve(vite.root, vitePath));
if (fs.existsSync(path.resolve(vite.root, vitePath))) {
console.log("here", vitePath);
vitep = vitePath;
config = fs.readFileSync(path.resolve(vite.root, vitePath)).toString();
}
}
if (!config) {
console.error("Could not find vite.config");
return;
}
config = config.replace(
`plugins: [`,
`test: {
exclude: ["node_modules", "e2e"],
globals: true,
setupFiles: process.env.TEST_ENV === 'server' ? undefined : './setupVitest.ts',
environment: "jsdom",
transformMode:
process.env.TEST_ENV === "server"
? {
ssr: [/.[tj]sx?$/]
}
: {
web: [/.[tj]sx?$/]
},
// solid needs to be inline to work around
// a resolution issue in vitest:
deps: {
inline: [/solid-js/]
}
// if you have few tests, try commenting one
// or both out to improve performance:
// threads: false,
// isolate: false,
},
build: {
target: "esnext",
polyfillDynamicImport: false
},
resolve: {
conditions: process.env.TEST_ENV === "server" ? [] : ["development", "browser"]
},
plugins: [`
);
console.log(config);
fs.writeFileSync(path.resolve(vite.root, vitep), config);
await $`npx prettier -w ${vitep}`;
await $`npx @antfu/ni`;
}

@ -469,17 +469,6 @@ prog
}
});
prog
.command("use <feature>")
.describe("Use a solid-start feature")
.action(async feature => {
const { default: fn } = await import(`./addons/${feature}.js`);
const vite = require("vite");
const config = await vite.resolveConfig({}, "serve");
console.log(await fn(config));
});
prog.parse(process.argv);
/**

@ -51,7 +51,7 @@ export function createRouteAction<T, U = void>(
fn: (args: T, event: ActionEvent) => Promise<U>,
options: { invalidate?: ((r: Response) => string | any[] | void) | string | any[] } = {}
): RouteAction<T, U> {
let init: { result?: { data?: U; error?: any }; input?: T } = checkFlash(fn);
let init: { result?: { data?: U; error?: any }; input?: T } = checkFlash<T>(fn);
const [input, setInput] = createSignal<T>(init.input);
const [result, setResult] = createSignal<{ data?: U; error?: any }>(init.result);
const navigate = useNavigate();
@ -145,7 +145,7 @@ export function createRouteMultiAction<T, U = void>(
fn: (args: T, event: ActionEvent) => Promise<U>,
options: { invalidate?: ((r: Response) => string | any[] | void) | string | any[] } = {}
): RouteMultiAction<T, U> {
let init: { result?: { data?: U; error?: any }; input?: T } = checkFlash(fn);
let init: { result?: { data?: U; error?: any }; input?: T } = checkFlash<T>(fn);
const [submissions, setSubmissions] = createSignal<Submission<T, U>[]>(
init.input ? [createSubmission(init.input)[0]] : []
);
@ -246,7 +246,7 @@ function handleResponse(response: Response, navigate, options) {
if (isRedirectResponse(response)) return handleRefetch(response, options);
}
function checkFlash(fn: any) {
function checkFlash<T>(fn: any) {
const [params] = useSearchParams();
let param = params.form ? JSON.parse(params.form) : null;
@ -266,6 +266,6 @@ function checkFlash(fn: any) {
})
: undefined
},
input
input: input as unknown as T
};
}

@ -5,22 +5,27 @@ import { Readable } from "stream";
import { createRequest } from "../node/fetch.js";
import "../node/globals.js";
// @ts-ignore
globalThis.DEBUG = debug("start:server");
// Vite doesn't expose this so we just copy the list for now
// https://github.com/vitejs/vite/blob/3edd1af56e980aef56641a5a51cf2932bb580d41/packages/vite/src/node/plugins/css.ts#L96
const style_pattern = /\.(css|less|sass|scss|styl|stylus|pcss|postcss)$/;
process.on("unhandledRejection", function (e) {
if (
!(
(typeof e === "string" && e.includes("renderToString timed out")) ||
(e.message && e.message.includes("renderToString timed out"))
)
) {
console.error(e);
process.on(
"unhandledRejection",
/** @param {Error | string} err */ err => {
if (
!(typeof err === "string"
? err.includes("renderToString timed out")
: err.message
? err.message.includes("renderToString timed out")
: false)
) {
console.error(`An unhandler error occured: ${err}`);
}
}
});
);
/**
*
@ -111,6 +116,7 @@ export function createDevHandler(viteServer, config, options) {
}
if (webRes.body) {
// @ts-ignore
const readable = Readable.from(webRes.body);
readable.pipe(res);
await once(readable, "end");

@ -80,7 +80,7 @@ export default function mount(code?: () => JSX.Element, element?: Document) {
window._$HY.hydrateIslands = () => {
const islands = document.querySelectorAll("solid-island[data-hk]");
const assets = new Set<string>();
islands.forEach(el => assets.add(el.dataset.component));
islands.forEach((el: HTMLElement) => assets.add(el.dataset.component));
Promise.all([...assets].map(asset => import(/* @vite-ignore */ asset))).then(() => {
islands.forEach((el: HTMLElement) => {
if (el.dataset.when === "idle" && "requestIdleCallback" in window) {

@ -72,6 +72,8 @@ const docType = ssr("<!DOCTYPE html>");
export default function StartServer({ event }: { event: PageEvent }) {
const parsed = new URL(event.request.url);
const path = parsed.pathname + parsed.search;
// @ts-ignore
sharedConfig.context.requestContext = event;
return (
<ServerContext.Provider value={event}>

@ -120,6 +120,7 @@ export class Router {
log("processing", path);
let id = path.slice(this.baseDir.length).replace(pageRegex, "");
/** @type {{ dataPath?: string; componentPath?: string; apiPath?: { [key: string]: string }}} */
let routeConfig = {};
if (path.match(new RegExp(`\\.(${["ts", "tsx", "jsx", "js"].join("|")})$`))) {

@ -17,7 +17,7 @@ export interface MatchedRoute {
id: string;
originalPath: string;
pattern: string;
component: () => JSX.Element;
component: (props: any) => JSX.Element;
match: PathMatch;
shared: boolean;
}

@ -96,6 +96,7 @@ class NodeRequest extends BaseNodeRequest {
// return (await this.buffer()).toString();
// }
// @ts-ignore
async formData() {
if (this.headers.get("content-type") === "application/x-www-form-urlencoded") {
return await super.formData();
@ -123,7 +124,9 @@ class NodeRequest extends BaseNodeRequest {
}
}
// @ts-ignore
clone() {
/** @type {BaseNodeRequest & { buffer?: () => Promise<Buffer>; formData?: () => Promise<FormData> }} */
let el = super.clone();
el.buffer = this.buffer.bind(el);
el.formData = this.formData.bind(el);

@ -6,9 +6,10 @@ Object.assign(globalThis, Streams, {
Request,
Response,
fetch,
Headers,
Headers
});
if (globalThis.crypto != crypto.webcrypto) {
// @ts-ignore
globalThis.crypto = crypto.webcrypto;
}

@ -103,10 +103,12 @@
"wait-on": "^6.0.1"
},
"devDependencies": {
"@cloudflare/workers-types": "^3.18.0",
"@solidjs/meta": "^0.28.0",
"@solidjs/router": "^0.5.0",
"@testing-library/jest-dom": "^5.16.5",
"@types/debug": "^4.1.7",
"@types/node": "^18.11.3",
"@types/wait-on": "^5.3.1",
"jsdom": "^20.0.1",
"solid-js": "^1.6.0",

@ -63,4 +63,5 @@ export default function Links() {
!isDev &&
import.meta.env.START_SSR &&
useAssets(() => getAssetsFromManifest(context.env.manifest, context.routerContext));
return null;
}

@ -6,5 +6,6 @@ import { ServerContext } from "../server/ServerContext";
export default function Meta() {
const context = useContext(ServerContext);
// @ts-expect-error The ssr() types do not match the Assets child types
useAssets(() => ssr(renderTags(context.tags)))
useAssets(() => ssr(renderTags(context.tags)));
return null;
}

@ -107,7 +107,7 @@ export function isResponse(value: any): value is Response {
const redirectStatusCodes = new Set([204, 301, 302, 303, 307, 308]);
export function isRedirectResponse(response: Response): boolean {
export function isRedirectResponse(response: Response | any): response is Response {
return response && response instanceof Response && redirectStatusCodes.has(response.status);
}

@ -11,6 +11,12 @@
"jsxImportSource": "solid-js",
"jsx": "preserve",
"types": ["vite/client"],
"lib": ["DOM", "DOM.Iterable", "ESNext"],
"paths": {
"vite": ["./node_modules/vite"]
},
"baseUrl": "./"
}
},
"include": ["./**/*.ts", "./**/*.tsx", "./**/*.js", "./**/*.jsx"],
"exclude": ["node_modules", "**/node_modules/*"]
}

@ -12,7 +12,9 @@ declare global {
};
}
export const DEBUG: Debugger;
interface RequestInit {
duplex?: "half";
}
}
type Adapter = {
@ -38,5 +40,4 @@ export type StartOptions = {
appRootFile: string;
};
export { };
export {};

@ -17,6 +17,7 @@ import type { Debugger } from "debug";
import type { Component } from "solid-js";
declare global {
export const DEBUG: Debugger;
interface Window {
DEBUG: Debugger;
_$HY: {
@ -26,13 +27,6 @@ declare global {
fe(id: string): void;
};
}
export const DEBUG: Debugger;
}
};
}
export const DEBUG: Debugger;
}
export const start: (options?: Partial<Options>) => Plugin[];

@ -1,3 +1,5 @@
/// <reference path="./plugin.d.ts" />
import inspect from "@vinxi/vite-plugin-inspect";
import debug from "debug";
import { solidPlugin } from "esbuild-plugin-solid";
@ -14,6 +16,8 @@ import routeData from "../server/routeData.js";
import routeDataHmr from "../server/routeDataHmr.js";
import babelServerModule from "../server/server-functions/babel.js";
import routeResource from "../server/serverResource.js";
// @ts-ignore
globalThis.DEBUG = debug("start:vite");
let _dirname = dirname(fileURLToPath(import.meta.url));
@ -71,7 +75,7 @@ function toArray(arr) {
/**
* @returns {import('node_modules/vite').Plugin}
* @param {{ lazy?: any; restart?: any; reload?: any; ssr?: any; appRoot?: any; routesDir?: any; delay?: any; glob?: any; router?: any; }} options
* @param {{ lazy?: any; restart?: any; reload?: any; ssr?: any; appRoot?: any; routesDir?: any; delay?: any; glob?: any; router?: any; babel?: any }} options
*/
function solidStartFileSystemRouter(options) {
let lazy;
@ -129,6 +133,7 @@ function solidStartFileSystemRouter(options) {
if (!c.server.watch) c.server.watch = {};
c.server.watch.disableGlobbing = false;
// @ts-expect-error
router = c.solidOptions.router;
},
async configResolved(_config) {
@ -179,11 +184,14 @@ function solidStartFileSystemRouter(options) {
};
let babelSolidCompiler = (/** @type {string} */ code, /** @type {string} */ id, fn) => {
// @ts-ignore
return solid({
let plugin = solid({
...(options ?? {}),
ssr: process.env.START_SPA_CLIENT === "true" ? false : true,
babel: babelOptions(fn)
}).transform(code, id, transformOptions);
});
// @ts-ignore
plugin.transform(code, id, transformOptions);
};
let ssr = process.env.TEST_ENV === "client" ? false : isSsr;
@ -539,7 +547,7 @@ function find(locate, cwd) {
return find(locate, path.join(cwd, ".."));
}
const nodeModulesPath = find("node_modules");
const nodeModulesPath = find("node_modules", process.cwd());
function detectAdapter() {
let adapters = [];

@ -1,4 +1,26 @@
import { webSocketHandlers } from "./webSocketHandlers";
interface DurableObjectId {
toString(): string;
equals(other: DurableObjectId): boolean;
readonly name?: string;
}
interface DurableObjectStorage {}
interface DurableObjectState {
waitUntil(promise: Promise<any>): void;
id: DurableObjectId;
readonly storage: DurableObjectStorage;
blockConcurrencyWhile<T>(callback: () => Promise<T>): Promise<T>;
}
declare const WebSocketPair: { new (): { 0: WebSocket; 1: WebSocket } };
declare global {
interface ResponseInit {
webSocket?: WebSocket;
}
}
export class WebSocketDurableObject {
storage: DurableObjectStorage;
@ -8,11 +30,7 @@ export class WebSocketDurableObject {
constructor(state: DurableObjectState) {
// We will put the WebSocket objects for each client into `websockets`
this.storage = state.storage;
this.dolocation = "";
this.state = state;
// this.scheduleNextAlarm(this.storage);
this.getDurableObjectLocation();
}
async fetch(request: Request) {
@ -43,10 +61,4 @@ export class WebSocketDurableObject {
.find(h => h.url === new URL(request.url).pathname)
?.handler.call(websocketEvent, webSocket, websocketEvent);
}
async getDurableObjectLocation() {
const res = await fetch("https://workers.cloudflare.com/cf.json");
const json = (await res.json()) as IncomingRequestCfProperties;
this.dolocation = `${json.city} (${json.country})`;
}
}

@ -375,11 +375,13 @@ importers:
'@babel/preset-env': ^7.19.4
'@babel/preset-typescript': ^7.18.6
'@babel/template': ^7.18.10
'@cloudflare/workers-types': ^3.18.0
'@solidjs/meta': ^0.28.0
'@solidjs/router': ^0.5.0
'@testing-library/jest-dom': ^5.16.5
'@types/cookie': ^0.5.1
'@types/debug': ^4.1.7
'@types/node': ^18.11.3
'@types/wait-on': ^5.3.1
'@vinxi/vite-plugin-inspect': ^0.6.27
chokidar: ^3.5.3
@ -449,10 +451,12 @@ importers:
vite-plugin-solid: 2.3.10_solid-js@1.6.0+vite@3.2.1
wait-on: 6.0.1_debug@4.3.4
devDependencies:
'@cloudflare/workers-types': 3.18.0
'@solidjs/meta': 0.28.2_solid-js@1.6.0
'@solidjs/router': 0.5.0_solid-js@1.6.0
'@testing-library/jest-dom': 5.16.5
'@types/debug': 4.1.7
'@types/node': 18.11.7
'@types/wait-on': 5.3.1
jsdom: 20.0.1
solid-js: 1.6.0
@ -1932,7 +1936,6 @@ packages:
/@cloudflare/workers-types/3.18.0:
resolution: {integrity: sha512-ehKOJVLMeR+tZkYhWEaLYQxl0TaIZu/kE86HF3/RidR8Xv5LuQxpbh+XXAoKVqsaphWLhIgBhgnlN5HGdheXSQ==}
dev: false
/@esbuild-plugins/node-globals-polyfill/0.1.1_esbuild@0.14.51:
resolution: {integrity: sha512-MR0oAA+mlnJWrt1RQVQ+4VYuRJW/P2YmRTv1AsplObyvuBMnPHiizUF95HHYiSsMGLhyGtWufaq2XQg6+iurBg==}

Loading…
Cancel
Save