Skip to content
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

Using node:url imports for core modules. #1028

Merged
merged 6 commits into from
Jun 28, 2023
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
9 changes: 6 additions & 3 deletions .eslintrc.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,19 +18,22 @@
"plugins": [
"@typescript-eslint",
"prettier",
"import"
"import",
"eslint-plugin-local-rules"
],
"rules": {
"@typescript-eslint/lines-between-class-members": "off",
"sort-imports": ["warn", {
"ignoreDeclarationSort": true
}]
}],
"local-rules/core-node-prefix": "error"
},
"overrides": [
{
"files": [
"./tools/*.ts",
"./tests/**/*.ts"
"./tests/**/*.ts",
"./eslint-local-rules/*.*s"
],
"rules": {
"import/no-extraneous-dependencies": "off"
Expand Down
1 change: 1 addition & 0 deletions .npmignore
Original file line number Diff line number Diff line change
Expand Up @@ -18,3 +18,4 @@ coverage
.prettierignore
tsup.config.ts
dist-esm
eslint-local-rules
8 changes: 4 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -708,11 +708,11 @@ The documentation on these arguments you may find [here](http://expressjs.com/en

```typescript
import { Routing, ServeStatic } from "express-zod-api";
import path from "path";
import { join } from "node:path";

const routing: Routing = {
// path /public serves static files from ./assets
public: new ServeStatic(path.join(__dirname, "assets"), {
public: new ServeStatic(join(__dirname, "assets"), {
dotfiles: "deny",
index: false,
redirect: false,
Expand Down Expand Up @@ -808,10 +808,10 @@ Consuming the generated client requires Typescript version 4.1 or higher.

```typescript
// example client-generator.ts
import fs from "fs";
import { writeFileSync } from "node:fs";
import { Integration } from "express-zod-api";

fs.writeFileSync(
writeFileSync(
"./frontend/client.ts",
new Integration({
routing,
Expand Down
2 changes: 2 additions & 0 deletions eslint-local-rules/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
require("ts-node").register({ transpileOnly: true, swc: true });
module.exports = require("./rules").default;
45 changes: 45 additions & 0 deletions eslint-local-rules/rules.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import { builtinModules } from "node:module";
import { Rule } from "eslint";

/**
* @link https://gist.github.com/alex-kinokon/f8f373e1a6bb01aa654d9085f2cff834
* @todo remove when the issue fixed:
* @link https://github.com/import-js/eslint-plugin-import/issues/2717
* @licence https://unlicense.org/
*/

export default {
"core-node-prefix": {
meta: {
type: "problem",
docs: {
description:
"Disallow imports of built-in Node.js modules without the `node:` prefix",
category: "Best Practices",
recommended: true,
},
fixable: "code",
schema: [],
},
create: (context) => ({
ImportDeclaration(node) {
const { source } = node;

if (source?.type === "Literal" && typeof source.value === "string") {
const moduleName = source.value;

if (
builtinModules.includes(moduleName) &&
!moduleName.startsWith("node:")
) {
context.report({
node: source,
message: `Import of built-in Node.js module "${moduleName}" must use the "node:" prefix.`,
fix: (fixer) => fixer.replaceText(source, `"node:${moduleName}"`),
});
}
}
},
}),
},
} satisfies Record<"core-node-prefix", Rule.RuleModule>;
4 changes: 2 additions & 2 deletions example/endpoints/send-avatar.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { z } from "zod";
import { fileSendingEndpointsFactory } from "../factories";
import fs from "fs";
import { readFile } from "node:fs/promises";

export const sendAvatarEndpoint = fileSendingEndpointsFactory.build({
method: "get",
Expand All @@ -16,7 +16,7 @@ export const sendAvatarEndpoint = fileSendingEndpointsFactory.build({
data: z.string(),
}),
handler: async () => {
const data = fs.readFileSync("logo.svg", "utf-8");
const data = await readFile("logo.svg", "utf-8");
return { data };
},
});
4 changes: 2 additions & 2 deletions example/endpoints/upload-avatar.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { z } from "zod";
import { ez } from "../../src";
import crypto from "crypto";
import { createHash } from "node:crypto";
import { taggedEndpointsFactory } from "../factories";

export const uploadAvatarEndpoint = taggedEndpointsFactory.build({
Expand Down Expand Up @@ -29,7 +29,7 @@ export const uploadAvatarEndpoint = taggedEndpointsFactory.build({
name: avatar.name,
size: avatar.size,
mime: avatar.mimetype,
hash: crypto.createHash("sha1").update(avatar.data).digest("hex"),
hash: createHash("sha1").update(avatar.data).digest("hex"),
otherInputs: rest,
};
},
Expand Down
6 changes: 2 additions & 4 deletions example/factories.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import {
} from "../src";
import { config } from "./config";
import { authMiddleware } from "./middlewares";
import fs from "fs";
import { createReadStream } from "node:fs";
import { z } from "zod";

export const taggedEndpointsFactory = new EndpointsFactory({
Expand Down Expand Up @@ -60,9 +60,7 @@ export const fileStreamingEndpointsFactory = new EndpointsFactory({
return;
}
if ("filename" in output) {
fs.createReadStream(output.filename).pipe(
response.type(output.filename)
);
createReadStream(output.filename).pipe(response.type(output.filename));
} else {
response.status(400).send("Filename is missing");
}
Expand Down
4 changes: 2 additions & 2 deletions example/routing.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { retrieveUserEndpoint } from "./endpoints/retrieve-user";
import { sendAvatarEndpoint } from "./endpoints/send-avatar";
import { updateUserEndpoint } from "./endpoints/update-user";
import { streamAvatarEndpoint } from "./endpoints/stream-avatar";
import path from "path";
import { join } from "node:path";

export const routing: Routing = {
v1: {
Expand All @@ -25,7 +25,7 @@ export const routing: Routing = {
},
},
// path /public serves static files from /example/assets
public: new ServeStatic(path.join(__dirname, "assets"), {
public: new ServeStatic(join(__dirname, "assets"), {
dotfiles: "deny",
index: false,
redirect: false,
Expand Down
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
"test:types": "tsc --noEmit",
"test:jest": "jest --detectOpenHandles ./tests/unit ./tests/system",
"test:badge": "make-coverage-badge --output-path ./coverage.svg",
"lint": "eslint ./src ./example ./tests && yarn prettier *.md --check",
"lint": "eslint src example tests tools && yarn prettier *.md --check",
"mdfix": "prettier *.md --write",
"precommit": "yarn lint && yarn test && yarn build && git add example/example.swagger.yaml example/example.client.ts ./LICENSE ./coverage.svg",
"prepublishOnly": "yarn lint && yarn test && yarn build",
Expand Down Expand Up @@ -99,6 +99,7 @@
"eslint-config-airbnb-typescript": "^17.0.0",
"eslint-config-prettier": "^8.5.0",
"eslint-plugin-import": "^2.26.0",
"eslint-plugin-local-rules": "^1.3.2",
"eslint-plugin-prettier": "^4.2.1",
"express": "^4.18.2",
"form-data": "^4.0.0",
Expand Down
2 changes: 1 addition & 1 deletion src/common-helpers.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { createHash } from "crypto";
import { createHash } from "node:crypto";
import { Request } from "express";
import { HttpError } from "http-errors";
import { z } from "zod";
Expand Down
2 changes: 1 addition & 1 deletion src/config-type.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import compression from "compression";
import { NextHandleFunction } from "connect";
import { Express, Request } from "express";
import fileUpload from "express-fileupload";
import { ServerOptions } from "https";
import { ServerOptions } from "node:https";
import { Logger } from "winston";
import { AbstractEndpoint } from "./endpoint";
import { Method } from "./method";
Expand Down
2 changes: 1 addition & 1 deletion src/logger.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { inspect } from "util";
import { inspect } from "node:util";
import type { Format } from "logform";
import { LEVEL, MESSAGE, SPLAT } from "triple-beam";
import winston from "winston";
Expand Down
2 changes: 1 addition & 1 deletion src/mock.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Request, Response } from "express";
import http from "http";
import http from "node:http";
import { Logger } from "winston";
import { CommonConfig } from "./config-type";
import { AbstractEndpoint } from "./endpoint";
Expand Down
2 changes: 1 addition & 1 deletion src/server.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import express, { ErrorRequestHandler, RequestHandler, json } from "express";
import compression from "compression";
import fileUpload from "express-fileupload";
import https from "https";
import https from "node:https";
import { Logger } from "winston";
import { AppConfig, CommonConfig, ServerConfig } from "./config-type";
import { ResultHandlerError } from "./errors";
Expand Down
2 changes: 1 addition & 1 deletion tests/esm/quick-start.spec.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { ChildProcessWithoutNullStreams, spawn } from "child_process";
import { ChildProcessWithoutNullStreams, spawn } from "node:child_process";
import fetch from "node-fetch";
import { esmTestPort, waitFor } from "../helpers";

Expand Down
2 changes: 1 addition & 1 deletion tests/express-mock.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
// @see https://github.com/swc-project/jest/issues/14#issuecomment-970189585
import http from "http";
import http from "node:http";

const expressJsonMock = jest.fn();
const compressionMock = jest.fn();
Expand Down
2 changes: 1 addition & 1 deletion tests/integration/quick-start.spec.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { ChildProcessWithoutNullStreams, spawn } from "child_process";
import { ChildProcessWithoutNullStreams, spawn } from "node:child_process";
import fetch from "node-fetch";
import { waitFor } from "../helpers";

Expand Down
2 changes: 1 addition & 1 deletion tests/system/client.spec.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { ChildProcessWithoutNullStreams, spawn } from "child_process";
import { ChildProcessWithoutNullStreams, spawn } from "node:child_process";
import { expectType } from "tsd";
import { config } from "../../example/config";
import { waitFor } from "../helpers";
Expand Down
17 changes: 7 additions & 10 deletions tests/system/example.spec.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import fetch from "node-fetch";
import { ChildProcessWithoutNullStreams, spawn } from "child_process";
import { ChildProcessWithoutNullStreams, spawn } from "node:child_process";
import { mimeMultipart } from "../../src/mime";
import { waitFor } from "../helpers";
import crypto from "crypto";
import { createHash } from "node:crypto";
import FormData from "form-data";
import { readFileSync } from "fs";
import { readFile } from "node:fs/promises";

describe("Example", () => {
let example: ChildProcessWithoutNullStreams;
Expand Down Expand Up @@ -128,8 +128,7 @@ describe("Example", () => {
expect(response.headers.get("Content-encoding")).toBe("gzip");
expect(response.headers.has("Transfer-encoding")).toBeTruthy();
expect(response.headers.get("Transfer-encoding")).toBe("chunked");
const hash = crypto
.createHash("sha1")
const hash = createHash("sha1")
.update(await response.text())
.digest("hex");
expect(hash).toMatchSnapshot();
Expand All @@ -144,8 +143,7 @@ describe("Example", () => {
expect(response.headers.get("Content-type")).toBe("image/svg+xml");
expect(response.headers.has("Transfer-encoding")).toBeTruthy();
expect(response.headers.get("Transfer-encoding")).toBe("chunked");
const hash = crypto
.createHash("sha1")
const hash = createHash("sha1")
.update(await response.text())
.digest("hex");
expect(hash).toMatchSnapshot();
Expand All @@ -155,16 +153,15 @@ describe("Example", () => {
const response = await fetch("http://localhost:8090/public/logo.svg");
expect(response.status).toBe(200);
expect(response.headers.get("Content-type")).toBe("image/svg+xml");
const hash = crypto
.createHash("sha1")
const hash = createHash("sha1")
.update(await response.text())
.digest("hex");
expect(hash).toMatchSnapshot();
});

test("Should upload the file", async () => {
const filename = "logo.svg";
const logo = readFileSync(filename, "utf-8");
const logo = await readFile(filename, "utf-8");
const data = new FormData();
data.append("avatar", logo, { filename });
data.append("str", "test string value");
Expand Down
2 changes: 1 addition & 1 deletion tests/system/system.spec.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import cors from "cors";
import http from "http";
import http from "node:http";
import fetch from "node-fetch";
import { z } from "zod";
import {
Expand Down
10 changes: 5 additions & 5 deletions tests/unit/file-schema.spec.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { ZodFile } from "../../src/file-schema";
import fs from "fs";
import { readFile } from "node:fs/promises";

describe("ZodFile", () => {
describe("static::create()", () => {
Expand Down Expand Up @@ -83,19 +83,19 @@ describe("ZodFile", () => {
});
});

test("should accept binary read string", () => {
test("should accept binary read string", async () => {
const schema = ZodFile.create().binary();
const data = fs.readFileSync("logo.svg", "binary");
const data = await readFile("logo.svg", "binary");
const result = schema.safeParse(data);
expect(result).toEqual({
success: true,
data,
});
});

test("should accept base64 read string", () => {
test("should accept base64 read string", async () => {
const schema = ZodFile.create().base64();
const data = fs.readFileSync("logo.svg", "base64");
const data = await readFile("logo.svg", "base64");
const result = schema.safeParse(data);
expect(result).toEqual({
success: true,
Expand Down
4 changes: 2 additions & 2 deletions tests/unit/server.spec.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import http from "http";
import https from "https";
import http from "node:http";
import https from "node:https";
import {
appMock,
compressionMock,
Expand Down
4 changes: 2 additions & 2 deletions tools/esm-test-package.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import fs from "fs";
import { writeFileSync } from "node:fs";

const manifest = {
type: "module",
types: "../../../../dist/index.d.ts",
};

fs.writeFileSync(
writeFileSync(
"./tests/esm/node_modules/express-zod-api/package.json",
`${JSON.stringify(manifest)}\n`
);
10 changes: 5 additions & 5 deletions tools/esm-test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import fs from "fs";
import { readFileSync, writeFileSync } from "node:fs";
import { esmTestPort } from "../tests/helpers";
import { extractReadmeQuickStart } from "./extract-quick-start";
import { getTSConfigBase } from "./tsconfig-base";
Expand Down Expand Up @@ -35,7 +35,7 @@ const tsConfigJson = `
}
`;

const readme = fs.readFileSync("README.md", "utf-8");
const readme = readFileSync("README.md", "utf-8");
const quickStartSection = readme.match(/# Quick start(.+?)\n#\s[A-Z]+/s);

if (!quickStartSection) {
Expand All @@ -51,6 +51,6 @@ if (!tsParts) {
const quickStart = extractReadmeQuickStart().replace(/8090/g, `${esmTestPort}`);

const dir = "./tests/esm";
fs.writeFileSync(`${dir}/package.json`, packageJson.trim());
fs.writeFileSync(`${dir}/tsconfig.json`, tsConfigJson.trim());
fs.writeFileSync(`${dir}/quick-start.ts`, quickStart.trim());
writeFileSync(`${dir}/package.json`, packageJson.trim());
writeFileSync(`${dir}/tsconfig.json`, tsConfigJson.trim());
writeFileSync(`${dir}/quick-start.ts`, quickStart.trim());
Loading