Git Product home page Git Product logo

elysia-autoload's Introduction

Привет, я Kravets 👋

  • Спикер Я 💛 Фронтенд 2024, с докладом про Elysia + Bun и о остальных фреймворках для серверных приложений.

✨ Навыки

🖌️ Фронтенд

Tech stack

⚙️ Бекенд

Tech stack

🛠 Инструменты

Tools I use

👉 Мои проекты

1. [GramIO] - WIP Telegram Bot API фреймворк для создания ботов с удобством!

  • [types] - Авто-обновляемая и кодогенерируемая библиотека с типами Telegram Bot API с помощью Github Actions

  • [keyboards] - Фреймворк-агностик библиотека для создания клавиатур телеграм ботам с многими классными возможностями!

  • [documentation] - Документация на VitePress с авто-деплоем на Netlify

  • [media-cache] - Плагин, который предотвращает лишние загрузки файлов сохраняя их file_id в GramIO

  • [create-gramio] - Скаффолдер, который позволяет развернуть проект с GramIO и окружением очень легко

  • [auto-retry] - Плагин, который повторяет запросы получившие retry_after параметр в GramIO

  • [format] - Библиотека для форматирования текста

  • [files] - Библиотека для удобной работой с загрузкой файлов для Telegram Bot API (работает под капотом GramIO)

  • [autoload] - Плагин для автозагрузки команд и т.д. из файлов в GramIO

  • [session] - Плагин для сессий в GramIO

  • [prompt] - Плагин реализующий "Вопрос-Ответ" в GramIO

  • [i18n] - Плагин, который позволяет удобно работать с локализацией

  • [media-group] - Плагин, который позволяет собрать медиа группу благодаря debounce

2. [t-kassa-api] - Библиотека для взаимодействия с API Т-Кассы. Генерируется из OpenAPI спецификации и имеет удобную работу с webhook и умными фильтрами.

3. [vscode-publint] - Расширение для VS Code, которое позволяет линтить package.json, добавляя интеграцию с publint.dev (о расширении даже рассказали в Twitter)

сообщение из твиттера

4. [elysia-autoload] - Плагин для Elysia, который загружает все endpoints в папке и генерирует типы для Eden

5. [create-elysiajs] - Модуль, который позволяет развернуть проект с ElysiaJS фреймворком и настроить его окружение простой командой bun create elysiajs. Biome, ESLint, Prisma, Drizzle, Husky и выбор плагинов. Авто-обновление зависимостей (включая те которые используются в генерации шаблона) с помощью Renovate

6. [elysia-oauth2] - Плагин для Elysia, который реализует удобную работу с авторизацией по протоколу OAuth 2.0, предоставляя 45+ адаптера под различные сервисы

7. [enkaNetwork] - TypeScript модуль, который позволяет удобно работать с enka.network добавляя локализацию и работу с асетами (например, авто-обновление)

8. [fluent2ts] - CLI утилита, которая позволяет генерировать типы для Fluent (.ftl) файлов локализации

9. [slidev-addon-qrcode] - Аддон для slidev, который предоставляет QRCode компонент (обёртка над qr-code-styling)

10. [aigram-monorepo] - MVP мессенджера в монорепе с e2e type-safety. (Svelte + Effector и ElysiaJS + Drizzle)

11. [Code Syntax Highlighter] - Плагин/Виджет для Figma который отрендерит текст с подсветкой синтаксиса. Поддерживаются многие языки и множество тем благодаря Shiki.

12. [PAYOK] - TypeScript модуль, который позволяет принимать платежи агрегатора payok.io

13. [rustore_notify] - Телеграм бот написанный на Rust с использованием Teloxide (магазин приложений RuStore в виде бота)

Проекты с хакатонов

1. [Мемология] - VK MINI APPS, который не одержал победы в VK FRESH CODE 2023

2. [webauthn-store] - приложение, которое эмулирует флешку с ключом безопасности и сохраняет его на сервере для кросс-девайс авторизации по протоколу webauthn

3. [driveIT-backend] - Бекенд для веб-платформы ЦОДД, который публикует телеметрию судов и отдаёт различную информацию (REST, WEBSOCKET, PROTOBUF)

4. [rosatom-backend] - Бекенд для управления сущностями (CRUD с импортом и экспортом) и формированием телеметрии судов

5. [pro.fipro] - Репозиторий с бекендом, который разрабатывался в качестве подготовки к чемпионату. Стек - Express & TypeORM и фронтендом для этого бекенда на React

📖 Моя статистика в GitHub ()

⌛ Моя статистика в WakaTime (wakatime)

❓ Как со мной связаться?

Telegram

🧑‍💻 Хакатоны и другие мероприятия

Участвую в разных активностях вместе со своей командой «Безымянные» фотокарточка безымянных

Наш телеграм канал - @team_noname (пост с победами)

Наш GitHub - @noname-to

🎧 Моя недавно прослушанная музыка

elysia-autoload's People

Contributors

bewinxed avatar kravetsone avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar

elysia-autoload's Issues

Crash with Elysia v1

I installed the latest bun and latest Elysia in my/tests/routes , followed the standard install per your doc

I get this error in a loop:

5288 |             return plugin2.default(this);
5289 |           }
5290 |           if (plugin2.default instanceof _Elysia) {
5291 |             return this._use(plugin2.default);
5292 |           }
5293 |           throw new Error(
                       ^
error: Invalid plugin type. Expected Elysia instance, function, or module with "default" as Elysia instance or function that returns Elysia instance.

package.json

{
  "name": "routes",
  "version": "1.0.50",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "dev": "bun run --watch src/index.ts"
  },
  "dependencies": {
    "elysia": "latest",
    "elysia-autoload": "^0.1.7"
  },
  "devDependencies": {
    "bun-types": "latest"
  },
  "module": "src/index.js"
}

src/index.ts

import { Elysia } from "elysia";
import { autoload } from "elysia-autoload";

// const app = new Elysia().get("/", () => "Hello Elysia").listen(3000);
const app = new Elysia().use(autoload()).listen(3000);

export type ElysiaApp = typeof app;

console.log(
  `Elysia is running with autoload at ${app.server?.hostname}:${app.server?.port}`
);

and

// routes/index.ts
import type { ElysiaApp } from "app";

export default (app: ElysiaApp) => app.get("/", { hello: "world" });

Hope you can fix this soon...

Thanks

Websockets don't work at all

Try adding a websocket to a route. Doesn't work, it is ignored. Tested on 0.2.3 with various Elysia versions.

error: Cannot find package "elysia-autoload"

Bun version: v1.0.33
Elysia version: 1.0.10
Autoload version: 0.2.1

Everything is installed. I tried to downgrade but issues still persist.

When I run bun run src/index.ts with the code example in the README, I get this error:

error: Cannot find package "elysia-autoload"

It is in the node_modules folder. It's an odd error so I'm not sure what other information to provide.

Build fails as of Bun 1.1.3 / 1.1.4

% bun run build       
$ bun build src/index.ts
3 | import { join as join2 } from "node:path";
             ^
error: No matching export in "node:path" for import "join"
    at /home/kainoa/redacted/node_modules/elysia-autoload/dist/index.js:3:10

7 | import { isAbsolute, join } from "node:path";
             ^
error: No matching export in "node:path" for import "isAbsolute"
    at /home/kainoa/redacted/node_modules/elysia-autoload/dist/index.js:7:10

7 | import { isAbsolute, join } from "node:path";
                         ^
error: No matching export in "node:path" for import "join"
    at /home/kainoa/redacted/node_modules/elysia-autoload/dist/index.js:7:22
error: script "build" exited with code 1

Code:
src/index.ts:

const app = new Elysia();
// ...
app.use(
	autoload({
		types: true,
	}),
);

Bun version: 1.1.4
Elysia version: 1.0.13
elysia-autoload version: 0.2.3

bun run dev still works fine.

autoload crashes with elysia > 0.8.10

My experiments with elysia, including autoload, ran well and smoothly last week until i bun updated my project... then the project started segfaulting when running my code, as well as your basic example.

I installed isolated, clean projects, with just your code, and came to conclude that your basic example:

  • runs well with this package.json:
{
  "name": "8.10",
  "module": "index.ts",
  "type": "module",
  "devDependencies": {
    "@types/bun": "latest"
  },
  "peerDependencies": {
    "typescript": "^5.0.0"
  },
  "dependencies": {
    "elysia": "0.8.10",
    "elysia-autoload": "^0.1.5"
  }
}
  • but crashes with that one:
{
  "name": "8.11",
  "module": "index.ts",
  "type": "module",
  "devDependencies": {
    "@types/bun": "latest"
  },
  "peerDependencies": {
    "typescript": "^5.0.0"
  },
  "dependencies": {
    "elysia": "0.8.11",
    "elysia-autoload": "^0.1.5"
  }
}

Latest elysia versions crash as well (up to latest 0.8.15)

I hope you can fix this...

Build fails

Tested on 0.1.0 and 0.1.1

Dev works fine, but build errors.

build.ts:

import { autoload } from "esbuild-plugin-autoload";

await Bun.build({
	entrypoints: ["src/index.ts"],
	outdir: "dist",
	target: "bun",
	sourcemap: "inline",
	minify: true,
	plugins: [
		autoload({
			pattern: "**/*.{ts,tsx,js,jsx,mjs,cjs}",
			directory: "src/routes",
		}),
	],
}).then(console.log);

index.ts

const app = new Elysia({
	serve: { reusePort: true },
})
	.use(
		await autoload({
			types: {
				output: "./routes.ts",
				typeName: "Routes",
			},
		}),
	)

File structure:

.
├── build.ts
├── env.d.ts
├── package.json
├── spawn.ts
├── src
│   ├── index.ts
│   ├── routes
│   │   ├── market
│   │   │   └── create.ts
│   │   ├── signedIn.ts
│   │   ├── signer
│   │   │   ├── approve.ts
│   │   │   └── sessionKey.ts
│   │   ├── timeline
│   │   │   └── [...].ts
│   │   └── user
│   │       ├── follow.ts
│   │       └── [name]
│   │           ├── followers.ts
│   │           ├── following.ts
│   │           └── index.ts
│   └── routes.ts

bun run build.ts:

{
  path: "/home/REDACTED/node_modules/elysia-autoload/dist/index.js",
  namespace: "file",
  loader: "jsx",
}
[ "signedIn.ts", "market/create.ts", "user/follow.ts", "user/[name]/index.ts", "user/[name]/followers.ts",
  "user/[name]/following.ts", "signer/sessionKey.ts", "signer/approve.ts", "timeline/[...].ts"
]
{
  outputs: [],
  success: false,
  logs: [
    74 |                                 ,
                                     ^
error: Expected identifier but found ","
    at /home/REDACTED/node_modules/elysia-autoload/dist/index.js:74:33, 76 |                                 ,
                                     ^
error: Expected identifier but found ","
    at /home/REDACTED/node_modules/elysia-autoload/dist/index.js:76:33, 78 |                                 ,
                                     ^
error: Expected identifier but found ","
    at /home/REDACTED/node_modules/elysia-autoload/dist/index.js:78:33, 80 |                                 ,
                                     ^
error: Expected identifier but found ","
    at /home/REDACTED/node_modules/elysia-autoload/dist/index.js:80:33, 82 |                                 ,
                                     ^
error: Expected identifier but found ","
    at /home/REDACTED/node_modules/elysia-autoload/dist/index.js:82:33, 84 |                                 ,
                                     ^
error: Expected identifier but found ","
    at /home/REDACTED/node_modules/elysia-autoload/dist/index.js:84:33, 86 |                                 ,
                                     ^
error: Expected identifier but found ","
    at /home/REDACTED/node_modules/elysia-autoload/dist/index.js:86:33, 88 |                                 ,
                                     ^
error: Expected identifier but found ","
    at /home/REDACTED/node_modules/elysia-autoload/dist/index.js:88:33
  ],
}

Plugin tries to look for dir in node_modules/.bin/ when relative path is specified

I am using Elysia in a sveltekit project, with the svelte-adapter-bun adapter.

Here's the Repo
https://github.com/Bewinxed/elysiakit

I am initiating it like so:

export const app = new Elysia({})
	.use(
		autoload({
			prefix,
			dir: "./routes",
			types: {
				output: "/src/lib/elysia/route-types.ts",
			},
		}),
	)
	.use(
		swagger({
			path: `${prefix}/docs`,
		}),
	)
	.onRequest(({ request, set }) => {
		// FIX: For elysia-autoload, using swagger and elysia-autoload together causes double prefix, so we remove it
		if (request.url.includes(`${prefix}${prefix}`)) {
			set.redirect = request.url.replace(`${prefix}${prefix}`, prefix);
			return request;
		}
	});

here's my tsconfig

{
	"extends": "./.svelte-kit/tsconfig.json",
	"compilerOptions": {
		"lib": [
			"ESNext"
		  ],
		  "module": "ESNext",
		  "target": "ESNext",
		"allowJs": true,
		"checkJs": true,
		"esModuleInterop": true,
		"forceConsistentCasingInFileNames": true,
		"resolveJsonModule": true,
		"skipLibCheck": true,
		"sourceMap": true,
		"strict": true,
		"moduleResolution": "Bundler",
		"allowSyntheticDefaultImports": true,
		"noEmit": true,
		"paths": { "/*": ["./*"] }
	},
	"include": [
		"src"
	]
	// Path aliases are handled by https://kit.svelte.dev/docs/configuration#alias
	//
	// If you want to overwrite includes/excludes, make sure to copy over the relevant includes/excludes
	// from the referenced tsconfig.json - TypeScript does not merge them in
}

I run my project like bunx --bun vite

but when the plugin is loaded, the process.argv[1] resolves to /root/dev/elysiakit/node_modules/.bin/routes

/root/dev/elysiakit
22 | const TYPES_OUTPUT_DEFAULT = "./routes-types.ts";
23 | const TYPES_TYPENAME_DEFAULT = "Routes";
24 | async function autoload({ pattern, dir, prefix, schema, types, } = {}) {
25 |     const directoryPath = (0, utils_1.getPath)(dir || "./routes");
26 |     if (!(0, node_fs_1.existsSync)(directoryPath))
27 |         throw new Error(`Directory ${directoryPath} doesn't exists`);
                   ^
error: Directory /root/dev/elysiakit/node_modules/.bin/routes doesn't exists
      at /root/dev/elysiakit/node_modules/elysia-autoload/dist/index.js:27:15
      at autoload (/root/dev/elysiakit/node_modules/elysia-autoload/dist/index.js:24:27)
error: script "dev" exited with code 1

Any idea why this is happening?

Using Elysia prefix adds the prefix at the END of all auto loaded paths

const prefix = "/api" as const;
export const app = new Elysia({})
	.use(
		autoload({
			prefix,
			dir: "./routes",
			types: {
				output: "../lib/elysia/route-types.ts",
			},
		}),
	)
	.use(
		swagger({
			path: `${prefix}/docs`,
		}),
	)
	.onRequest(({ request, set }) => {
		// FIX: For elysia-autoload, using swagger and elysia-autoload together causes double prefix, so we remove it
		if (request.url.includes(`${prefix}${prefix}`)) {
			set.redirect = request.url.replace(`${prefix}${prefix}`, prefix);
			return request;
		}
	});

If you add the prefix to Elysia,

then the routes will have the prefix added at the END.

This causes issues with subsequent plugins like Swagger, I'd have to add the prefix to the swagger path parameter and then i have to add some middleware to remove the double prefix.

Am i using it incorrectly? shouldn't it play nice with the Elysia native prefix?

Thanks!

Cannot run built version

$ bun build.ts
{
  outputs: [
    BuildArtifact (entry-point) {
      path: "/home/REDACTED/packages/backend/dist/index.js",
      loader: "ts",
      kind: "entry-point",
      hash: "bad6cd93cd11db91",
      FileRef ("/home/REDACTED/packages/backend/dist/index.js") {
        type: "text/javascript;charset=utf-8"
      },
      sourcemap: null
    }
  ],
  success: true,
  logs: [],
}

$ bun run dist/index.js
5371 |           staticRouter.map[loosePath].all = shouldPrecompile ? `default: return st${index}(ctx)
5372 | ` : `default: ${jitRoute(index)}
5373 | `;
5374 |         else
5375 |           staticRouter.map[loosePath].code = shouldPrecompile ? `case '${method}': return st${index}(ctx)
5376 | ${staticRouter.map[loosePath].code}` : `case '${method}': ${jitRoute(index)}
       ^
SyntaxError: Unexpected identifier 'cY'. Expected ';' after variable declaration.
      at <parse> (/home/REDACTED/node_modules/elysia/dist/index.mjs:5376:1)

Bun v1.1.13 (Linux x64)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.