prefix
stringlengths
82
32.6k
middle
stringlengths
5
470
suffix
stringlengths
0
81.2k
file_path
stringlengths
6
168
repo_name
stringlengths
16
77
context
listlengths
5
5
lang
stringclasses
4 values
ground_truth
stringlengths
5
470
import { sign } from 'jsonwebtoken'; import { IUser } from '../types'; import { Request, Response } from 'express'; import User from '../model'; import { AppError } from '../../../utils/appError'; import { catchAsync } from '../../../utils/catchAsync'; import redisService from '../../../utils/redis'; const accessToken = (user: { _id: string; name: string; email: string; role: string }) => { return sign( { id: user._id, name: user.name, email: user.email, type: process.env.JWT_ACCESS, role: user.role }, process.env.JWT_KEY_SECRET as string, { subject: user.email, expiresIn: process.env.JWT_EXPIRES_IN, audience: process.env.JWT_AUDIENCE, issuer: process.env.JWT_ISSUER, }, ); }; const refreshToken = (user: { _id: string; name: string; email: string; role: string }) => { return sign( { id: user._id, name: user.name, email: user.email, type: process.env.JWT_REFRESH, role: user.role }, process.env.JWT_KEY_REFRESH as string, { subject: user.email, expiresIn: process.env.JWT_EXPIRES_IN, audience: process.env.JWT_AUDIENCE, issuer: process.env.JWT_ISSUER, }, ); }; const createSendToken = (user: IUser, statusCode: number, req: Request, res: Response) => { const acess = accessToken(user); const refresh = refreshToken(user); // Remove password from output // eslint-disable-next-line @typescript-eslint/no-unused-vars const { name, email, role, ...otherUserData } = user; res.status(statusCode).json({ status: 'success', acess, refresh, data: { name, email, role, }, }); }; export const signup
= catchAsync(async (req, res) => {
const newUser = await User.create({ name: req.body.name, email: req.body.email, password: req.body.password, }); createSendToken(newUser, 201, req, res); }); export const login = catchAsync(async (req, res, next) => { const { email, password } = req.body; // 1) Check if email and password exist if (!email || !password) { return next(new AppError('Please provide email and password!', 400)); } // 2) Check if user exists && password is correct const user: any = await User.findOne({ email }).select('+password'); if (!user || !(await user.correctPassword(password, user.password))) { return next(new AppError('Incorrect email or password', 401)); } // 3) If everything ok, send token to client createSendToken(user, 200, req, res); }); export const getMe = catchAsync(async (req, res) => { const user = req.user; // 3) If everything ok, send token to client res.status(200).json({ message: 'user sucessfully fetched!', user }); }); export function logout(req: Request, res: Response) { res.cookie('jwt', 'loggedout', { expires: new Date(Date.now() + 10 * 1000), httpOnly: true, }); res.status(200).json({ status: 'success' }); } export async function refresh(req: Request, res: Response) { const user: any = req.user; await redisService.set({ key: user?.token, value: '1', timeType: 'EX', time: parseInt(process.env.JWT_REFRESH_TIME || '', 10), }); const refresh = refreshToken(user); return res.status(200).json({ status: 'sucess', refresh }); } export async function fetchUsers(req: Request, res: Response) { const body = req.body; console.log({ body }); try { const users = await User.find(); return res.status(200).json({ message: 'sucessfully fetch users', data: users }); } catch (error: any) { new AppError(error.message, 201); } } export async function deleteUser(req: Request, res: Response) { const id = req.params.id; try { await User.deleteOne({ _id: id }); return res.status(200).json({ message: 'sucessfully deleted users' }); } catch (error: any) { new AppError(error.message, 201); } }
src/modules/auth/service/index.ts
walosha-BACKEND_DEV_TESTS-db2fcb4
[ { "filename": "src/middleware/protect.ts", "retrieved_chunk": "import { NextFunction, Request, Response } from 'express';\nimport { JwtPayload, verify } from 'jsonwebtoken';\nimport { AppError } from '../utils/appError';\nimport { catchAsync } from '../utils/catchAsync';\nimport User from '../modules/auth/model';\nexport const protect = catchAsync(async (req: Request, res: Response, next: NextFunction) => {\n // 1) Getting token and check of it's there\n let token;\n if (req.headers.authorization && req.headers.authorization.startsWith('Bearer')) {\n token = req.headers.authorization.split(' ')[1];", "score": 10.27481144660087 }, { "filename": "src/utils/catchAsync.ts", "retrieved_chunk": "import { NextFunction, Request, Response } from 'express';\ntype AsyncFunction = (req: Request, res: Response, next: NextFunction) => Promise<any>;\nexport const catchAsync = (fn: AsyncFunction) => {\n return (req: Request, res: Response, next: NextFunction) => {\n fn(req, res, next).catch(next);\n };\n};", "score": 9.88492815162634 }, { "filename": "src/middleware/refresh.ts", "retrieved_chunk": " req.user = {\n email: decoded.email,\n name: decoded.name,\n role: decoded.role,\n token,\n };\n next();\n return;\n } catch (err) {\n console.log({ err });", "score": 9.797796687975092 }, { "filename": "src/middleware/refresh.ts", "retrieved_chunk": "import jwt, { JwtPayload } from 'jsonwebtoken';\nimport redisService from '../utils/redis';\nimport { AppError } from '../utils/appError';\nimport { NextFunction, Request, Response } from 'express';\nexport const refreshMiddleware: any = async (req: Request, res: Response, next: NextFunction) => {\n if (req.body?.refresh) {\n const token = req.body.refresh;\n try {\n const decoded: any = jwt.verify(token, process.env.JWT_KEY_REFRESH as string) as JwtPayload;\n if (", "score": 9.192050672156531 }, { "filename": "src/modules/auth/controller/index.ts", "retrieved_chunk": "import express from 'express';\nimport { getMe, login, refresh, signup } from '../service';\nimport { refreshMiddleware } from '../../../middleware/refresh';\nimport { protect } from '../../../middleware';\nconst router = express.Router();\n/**\n * @swagger\n * /api/v1/auth/signup:\n * post:\n * summary: Creates an account", "score": 8.987614342960367 } ]
typescript
= catchAsync(async (req, res) => {
import { sign } from 'jsonwebtoken'; import { IUser } from '../types'; import { Request, Response } from 'express'; import User from '../model'; import { AppError } from '../../../utils/appError'; import { catchAsync } from '../../../utils/catchAsync'; import redisService from '../../../utils/redis'; const accessToken = (user: { _id: string; name: string; email: string; role: string }) => { return sign( { id: user._id, name: user.name, email: user.email, type: process.env.JWT_ACCESS, role: user.role }, process.env.JWT_KEY_SECRET as string, { subject: user.email, expiresIn: process.env.JWT_EXPIRES_IN, audience: process.env.JWT_AUDIENCE, issuer: process.env.JWT_ISSUER, }, ); }; const refreshToken = (user: { _id: string; name: string; email: string; role: string }) => { return sign( { id: user._id, name: user.name, email: user.email, type: process.env.JWT_REFRESH, role: user.role }, process.env.JWT_KEY_REFRESH as string, { subject: user.email, expiresIn: process.env.JWT_EXPIRES_IN, audience: process.env.JWT_AUDIENCE, issuer: process.env.JWT_ISSUER, }, ); }; const createSendToken = (user: IUser, statusCode: number, req: Request, res: Response) => { const acess = accessToken(user); const refresh = refreshToken(user); // Remove password from output // eslint-disable-next-line @typescript-eslint/no-unused-vars const { name, email, role, ...otherUserData } = user; res.status(statusCode).json({ status: 'success', acess, refresh, data: { name, email, role, }, }); }; export const signup = catchAsync(async (req, res) => {
const newUser = await User.create({
name: req.body.name, email: req.body.email, password: req.body.password, }); createSendToken(newUser, 201, req, res); }); export const login = catchAsync(async (req, res, next) => { const { email, password } = req.body; // 1) Check if email and password exist if (!email || !password) { return next(new AppError('Please provide email and password!', 400)); } // 2) Check if user exists && password is correct const user: any = await User.findOne({ email }).select('+password'); if (!user || !(await user.correctPassword(password, user.password))) { return next(new AppError('Incorrect email or password', 401)); } // 3) If everything ok, send token to client createSendToken(user, 200, req, res); }); export const getMe = catchAsync(async (req, res) => { const user = req.user; // 3) If everything ok, send token to client res.status(200).json({ message: 'user sucessfully fetched!', user }); }); export function logout(req: Request, res: Response) { res.cookie('jwt', 'loggedout', { expires: new Date(Date.now() + 10 * 1000), httpOnly: true, }); res.status(200).json({ status: 'success' }); } export async function refresh(req: Request, res: Response) { const user: any = req.user; await redisService.set({ key: user?.token, value: '1', timeType: 'EX', time: parseInt(process.env.JWT_REFRESH_TIME || '', 10), }); const refresh = refreshToken(user); return res.status(200).json({ status: 'sucess', refresh }); } export async function fetchUsers(req: Request, res: Response) { const body = req.body; console.log({ body }); try { const users = await User.find(); return res.status(200).json({ message: 'sucessfully fetch users', data: users }); } catch (error: any) { new AppError(error.message, 201); } } export async function deleteUser(req: Request, res: Response) { const id = req.params.id; try { await User.deleteOne({ _id: id }); return res.status(200).json({ message: 'sucessfully deleted users' }); } catch (error: any) { new AppError(error.message, 201); } }
src/modules/auth/service/index.ts
walosha-BACKEND_DEV_TESTS-db2fcb4
[ { "filename": "src/middleware/protect.ts", "retrieved_chunk": "import { NextFunction, Request, Response } from 'express';\nimport { JwtPayload, verify } from 'jsonwebtoken';\nimport { AppError } from '../utils/appError';\nimport { catchAsync } from '../utils/catchAsync';\nimport User from '../modules/auth/model';\nexport const protect = catchAsync(async (req: Request, res: Response, next: NextFunction) => {\n // 1) Getting token and check of it's there\n let token;\n if (req.headers.authorization && req.headers.authorization.startsWith('Bearer')) {\n token = req.headers.authorization.split(' ')[1];", "score": 11.779101971400317 }, { "filename": "src/utils/catchAsync.ts", "retrieved_chunk": "import { NextFunction, Request, Response } from 'express';\ntype AsyncFunction = (req: Request, res: Response, next: NextFunction) => Promise<any>;\nexport const catchAsync = (fn: AsyncFunction) => {\n return (req: Request, res: Response, next: NextFunction) => {\n fn(req, res, next).catch(next);\n };\n};", "score": 10.556787427819858 }, { "filename": "src/middleware/refresh.ts", "retrieved_chunk": "import jwt, { JwtPayload } from 'jsonwebtoken';\nimport redisService from '../utils/redis';\nimport { AppError } from '../utils/appError';\nimport { NextFunction, Request, Response } from 'express';\nexport const refreshMiddleware: any = async (req: Request, res: Response, next: NextFunction) => {\n if (req.body?.refresh) {\n const token = req.body.refresh;\n try {\n const decoded: any = jwt.verify(token, process.env.JWT_KEY_REFRESH as string) as JwtPayload;\n if (", "score": 10.176994760848254 }, { "filename": "src/middleware/refresh.ts", "retrieved_chunk": " req.user = {\n email: decoded.email,\n name: decoded.name,\n role: decoded.role,\n token,\n };\n next();\n return;\n } catch (err) {\n console.log({ err });", "score": 9.797796687975092 }, { "filename": "src/modules/auth/controller/index.ts", "retrieved_chunk": "import express from 'express';\nimport { getMe, login, refresh, signup } from '../service';\nimport { refreshMiddleware } from '../../../middleware/refresh';\nimport { protect } from '../../../middleware';\nconst router = express.Router();\n/**\n * @swagger\n * /api/v1/auth/signup:\n * post:\n * summary: Creates an account", "score": 9.659473619153884 } ]
typescript
const newUser = await User.create({
/** * @swagger * components: * schemas: * User: * type: object * required: * - name * - email * properties: * name: * type: string * description: The user name * email: * type: string * format: email * description: The user email address * password: * type: string * description: The user password (hashed) * role: * type: string * enum: [user, admin] * description: The user role * default: user * example: * name: John Doe * email: [email protected] * password: $2a$10$gR06R4K1NM4p4b4ELq.LlOTzq3Dcxj2iPwE5U/O2MDE70o9noemhO * role: user */ import express from 'express'; import { deleteUser, fetchUsers } from '../service'; import { protect, restrictTo } from '../../../middleware'; const router = express.Router(); /** * @swagger * /api/v1/users: * get: * summary: Retrieve all users * tags: [User] * security: * - bearerAuth: [] * responses: * "200": * description: A list of users * content: * application/json: * schema: * type: array * items: * $ref: '#/components/schemas/User' * "401": * description: Unauthorized */ router
.get('/', protect, restrictTo('admin'), fetchUsers);
/** * @swagger * /api/v1/users/{id}: * delete: * summary: Delete a user by ID * tags: [User] * security: * - bearerAuth: [] * parameters: * - in: path * name: id * schema: * type: string * required: true * description: The ID of the user to delete * responses: * "204": * description: User deleted successfully * "401": * description: Unauthorized * "404": * description: User not found */ // A simple case where users can only delete themselves not the admin router.delete('/:id', restrictTo('user'), deleteUser); export default router;
src/modules/auth/controller/users.ts
walosha-BACKEND_DEV_TESTS-db2fcb4
[ { "filename": "src/modules/auth/controller/index.ts", "retrieved_chunk": " * description: The authenticated user.\n * content:\n * application/json:\n * schema:\n * $ref: '#/components/schemas/User'\n */\nrouter.post('/login', login);\n/**\n * @swagger\n * /api/v1/auth/refresh:", "score": 23.36940559308816 }, { "filename": "src/modules/auth/controller/index.ts", "retrieved_chunk": " * content:\n * application/json:\n * schema:\n * $ref: '#/components/schemas/User'\n */\nrouter.post('/signup', signup);\n/**\n * @swagger\n * /api/v1/auth/login:\n * post:", "score": 22.615784206928453 }, { "filename": "src/modules/auth/controller/index.ts", "retrieved_chunk": " * summary: Login User\n * tags: [Auth]\n * requestBody:\n * required: true\n * content:\n * application/json:\n * schema:\n * $ref: '#/components/schemas/LoginRequest'\n * responses:\n * \"200\":", "score": 19.57300590680708 }, { "filename": "src/modules/auth/controller/index.ts", "retrieved_chunk": " * tags: [Auth]\n * requestBody:\n * required: true\n * content:\n * application/json:\n * schema:\n * $ref: '#/components/schemas/SignupRequest'\n * responses:\n * \"200\":\n * description: The created user.", "score": 19.21657302046459 }, { "filename": "src/modules/account/controller/index.ts", "retrieved_chunk": " * description: Invalid request parameters\n * '401':\n * description: Unauthorized request\n */\nrouter.post('/transfer', protect, transferFund);\nexport default router;", "score": 17.839611483388857 } ]
typescript
.get('/', protect, restrictTo('admin'), fetchUsers);
/** * @swagger * components: * schemas: * SignupRequest: * type: object * required: * - email * - password * - name * properties: * name: * type: string * description: The user name * email: * type: string * description: The user email address * password: * type: string * description: The user password * example: * name: John Doe * email: [email protected] * password: password123 * LoginRequest: * type: object * required: * - email * - password * properties: * email: * type: string * description: The user email address * password: * type: string * description: The user password * example: * email: [email protected] * password: password123 */ import express from 'express'; import { getMe, login, refresh, signup } from '../service'; import { refreshMiddleware } from '../../../middleware/refresh'; import { protect } from '../../../middleware'; const router = express.Router(); /** * @swagger * /api/v1/auth/signup: * post: * summary: Creates an account * tags: [Auth] * requestBody: * required: true * content: * application/json: * schema: * $ref: '#/components/schemas/SignupRequest' * responses: * "200": * description: The created user. * content: * application/json: * schema: * $ref: '#/components/schemas/User' */ router.post
('/signup', signup);
/** * @swagger * /api/v1/auth/login: * post: * summary: Login User * tags: [Auth] * requestBody: * required: true * content: * application/json: * schema: * $ref: '#/components/schemas/LoginRequest' * responses: * "200": * description: The authenticated user. * content: * application/json: * schema: * $ref: '#/components/schemas/User' */ router.post('/login', login); /** * @swagger * /api/v1/auth/refresh: * post: * summary: Refreshes the access token * tags: [Auth] * requestBody: * required: true * content: * application/json: * schema: * type: object * required: * - refresh * properties: * refresh: * type: string * description: Refresh token * example: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjY0NGYwMjg0MWRmNGJlYzliOWI3ZjlhYSIsImlhdCI6MTY4Mjg5OTU4OCwiZXhwIjoxNjgzMDcyMzg4fQ.Bt2kzyxyUEtUy9pLvr0zSzpI8_xTaM6KulO2mwYztbQ * responses: * "200": * description: The new access token * content: * application/json: * schema: * type: object * properties: * accessToken: * type: string * description: Access token * example: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJKb2huIERvZSIsImlhdCI6MTUxNjIzOTAyMn0.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c * "400": * description: Invalid request or refresh token is not present * "401": * description: Invalid or expired token or refresh token was already used */ router.post('/refresh', refreshMiddleware, refresh); /** * @swagger * /api/v1/auth/me: * post: * summary: Get user profile * tags: [Auth] * security: * - bearerAuth: [] * responses: * "200": * description: The user profile * "401": * description: Unauthorized */ router.post('/me', protect, getMe); export default router;
src/modules/auth/controller/index.ts
walosha-BACKEND_DEV_TESTS-db2fcb4
[ { "filename": "src/modules/auth/controller/users.ts", "retrieved_chunk": " * tags: [User]\n * security:\n * - bearerAuth: []\n * responses:\n * \"200\":\n * description: A list of users\n * content:\n * application/json:\n * schema:\n * type: array", "score": 26.408654712126708 }, { "filename": "src/modules/auth/controller/users.ts", "retrieved_chunk": " * items:\n * $ref: '#/components/schemas/User'\n * \"401\":\n * description: Unauthorized\n */\nrouter.get('/', protect, restrictTo('admin'), fetchUsers);\n/**\n * @swagger\n * /api/v1/users/{id}:\n * delete:", "score": 18.83551318474517 }, { "filename": "src/modules/account/controller/index.ts", "retrieved_chunk": " * summary: Transfer funds between accounts\n * security:\n * - BearerAuth: []\n * requestBody:\n * required: true\n * content:\n * application/json:\n * schema:\n * type: object\n * properties:", "score": 15.129055693889292 }, { "filename": "src/modules/account/controller/index.ts", "retrieved_chunk": " * description: Invalid request parameters\n * '401':\n * description: Unauthorized request\n */\nrouter.post('/transfer', protect, transferFund);\nexport default router;", "score": 12.414665924452233 }, { "filename": "src/modules/auth/service/index.ts", "retrieved_chunk": " refresh,\n data: {\n name,\n email,\n role,\n },\n });\n};\nexport const signup = catchAsync(async (req, res) => {\n const newUser = await User.create({", "score": 12.095125910916646 } ]
typescript
('/signup', signup);
/** * @swagger * components: * schemas: * SignupRequest: * type: object * required: * - email * - password * - name * properties: * name: * type: string * description: The user name * email: * type: string * description: The user email address * password: * type: string * description: The user password * example: * name: John Doe * email: [email protected] * password: password123 * LoginRequest: * type: object * required: * - email * - password * properties: * email: * type: string * description: The user email address * password: * type: string * description: The user password * example: * email: [email protected] * password: password123 */ import express from 'express'; import { getMe, login, refresh, signup } from '../service'; import { refreshMiddleware } from '../../../middleware/refresh'; import { protect } from '../../../middleware'; const router = express.Router(); /** * @swagger * /api/v1/auth/signup: * post: * summary: Creates an account * tags: [Auth] * requestBody: * required: true * content: * application/json: * schema: * $ref: '#/components/schemas/SignupRequest' * responses: * "200": * description: The created user. * content: * application/json: * schema: * $ref: '#/components/schemas/User' */ router.post('/signup', signup); /** * @swagger * /api/v1/auth/login: * post: * summary: Login User * tags: [Auth] * requestBody: * required: true * content: * application/json: * schema: * $ref: '#/components/schemas/LoginRequest' * responses: * "200": * description: The authenticated user. * content: * application/json: * schema: * $ref: '#/components/schemas/User' */ router.post('/login', login); /** * @swagger * /api/v1/auth/refresh: * post: * summary: Refreshes the access token * tags: [Auth] * requestBody: * required: true * content: * application/json: * schema: * type: object * required: * - refresh * properties: * refresh: * type: string * description: Refresh token * example: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjY0NGYwMjg0MWRmNGJlYzliOWI3ZjlhYSIsImlhdCI6MTY4Mjg5OTU4OCwiZXhwIjoxNjgzMDcyMzg4fQ.Bt2kzyxyUEtUy9pLvr0zSzpI8_xTaM6KulO2mwYztbQ * responses: * "200": * description: The new access token * content: * application/json: * schema: * type: object * properties: * accessToken: * type: string * description: Access token * example: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJKb2huIERvZSIsImlhdCI6MTUxNjIzOTAyMn0.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c * "400": * description: Invalid request or refresh token is not present * "401": * description: Invalid or expired token or refresh token was already used */ router.post('/refresh', refreshMiddleware, refresh); /** * @swagger * /api/v1/auth/me: * post: * summary: Get user profile * tags: [Auth] * security: * - bearerAuth: [] * responses: * "200": * description: The user profile * "401": * description: Unauthorized */ router.post(
'/me', protect, getMe);
export default router;
src/modules/auth/controller/index.ts
walosha-BACKEND_DEV_TESTS-db2fcb4
[ { "filename": "src/modules/account/controller/index.ts", "retrieved_chunk": " * description: Invalid request parameters\n * '401':\n * description: Unauthorized request\n */\nrouter.post('/transfer', protect, transferFund);\nexport default router;", "score": 25.78394479631677 }, { "filename": "src/modules/auth/controller/users.ts", "retrieved_chunk": " * tags: [User]\n * security:\n * - bearerAuth: []\n * responses:\n * \"200\":\n * description: A list of users\n * content:\n * application/json:\n * schema:\n * type: array", "score": 18.95573333462072 }, { "filename": "src/modules/auth/controller/users.ts", "retrieved_chunk": " * description: The ID of the user to delete\n * responses:\n * \"204\":\n * description: User deleted successfully\n * \"401\":\n * description: Unauthorized\n * \"404\":\n * description: User not found\n */\n// A simple case where users can only delete themselves not the admin", "score": 17.81497743905644 }, { "filename": "src/modules/auth/controller/users.ts", "retrieved_chunk": " * items:\n * $ref: '#/components/schemas/User'\n * \"401\":\n * description: Unauthorized\n */\nrouter.get('/', protect, restrictTo('admin'), fetchUsers);\n/**\n * @swagger\n * /api/v1/users/{id}:\n * delete:", "score": 17.185952635685464 }, { "filename": "src/modules/account/controller/index.ts", "retrieved_chunk": " * description: The amount of funds to transfer.\n * example: 1000.00\n * tag:\n * type: string\n * description: The tag associated with the transfer.\n * example: \"Rent payment\"\n * responses:\n * '200':\n * description: Successful transfer of funds\n * '400':", "score": 15.12522358086859 } ]
typescript
'/me', protect, getMe);
/** * @swagger * components: * schemas: * User: * type: object * required: * - name * - email * properties: * name: * type: string * description: The user name * email: * type: string * format: email * description: The user email address * password: * type: string * description: The user password (hashed) * role: * type: string * enum: [user, admin] * description: The user role * default: user * example: * name: John Doe * email: [email protected] * password: $2a$10$gR06R4K1NM4p4b4ELq.LlOTzq3Dcxj2iPwE5U/O2MDE70o9noemhO * role: user */ import express from 'express'; import { deleteUser, fetchUsers } from '../service'; import { protect, restrictTo } from '../../../middleware'; const router = express.Router(); /** * @swagger * /api/v1/users: * get: * summary: Retrieve all users * tags: [User] * security: * - bearerAuth: [] * responses: * "200": * description: A list of users * content: * application/json: * schema: * type: array * items: * $ref: '#/components/schemas/User' * "401": * description: Unauthorized */
router.get('/', protect, restrictTo('admin'), fetchUsers);
/** * @swagger * /api/v1/users/{id}: * delete: * summary: Delete a user by ID * tags: [User] * security: * - bearerAuth: [] * parameters: * - in: path * name: id * schema: * type: string * required: true * description: The ID of the user to delete * responses: * "204": * description: User deleted successfully * "401": * description: Unauthorized * "404": * description: User not found */ // A simple case where users can only delete themselves not the admin router.delete('/:id', restrictTo('user'), deleteUser); export default router;
src/modules/auth/controller/users.ts
walosha-BACKEND_DEV_TESTS-db2fcb4
[ { "filename": "src/modules/auth/controller/index.ts", "retrieved_chunk": " * description: The authenticated user.\n * content:\n * application/json:\n * schema:\n * $ref: '#/components/schemas/User'\n */\nrouter.post('/login', login);\n/**\n * @swagger\n * /api/v1/auth/refresh:", "score": 26.251794494743265 }, { "filename": "src/modules/auth/controller/index.ts", "retrieved_chunk": " * content:\n * application/json:\n * schema:\n * $ref: '#/components/schemas/User'\n */\nrouter.post('/signup', signup);\n/**\n * @swagger\n * /api/v1/auth/login:\n * post:", "score": 25.658562507049826 }, { "filename": "src/modules/auth/controller/index.ts", "retrieved_chunk": " * summary: Login User\n * tags: [Auth]\n * requestBody:\n * required: true\n * content:\n * application/json:\n * schema:\n * $ref: '#/components/schemas/LoginRequest'\n * responses:\n * \"200\":", "score": 22.615784206928453 }, { "filename": "src/modules/auth/controller/index.ts", "retrieved_chunk": " * tags: [Auth]\n * requestBody:\n * required: true\n * content:\n * application/json:\n * schema:\n * $ref: '#/components/schemas/SignupRequest'\n * responses:\n * \"200\":\n * description: The created user.", "score": 22.203941014311273 }, { "filename": "src/modules/account/controller/index.ts", "retrieved_chunk": " * description: Invalid request parameters\n * '401':\n * description: Unauthorized request\n */\nrouter.post('/transfer', protect, transferFund);\nexport default router;", "score": 17.839611483388857 } ]
typescript
router.get('/', protect, restrictTo('admin'), fetchUsers);
import { sign } from 'jsonwebtoken'; import { IUser } from '../types'; import { Request, Response } from 'express'; import User from '../model'; import { AppError } from '../../../utils/appError'; import { catchAsync } from '../../../utils/catchAsync'; import redisService from '../../../utils/redis'; const accessToken = (user: { _id: string; name: string; email: string; role: string }) => { return sign( { id: user._id, name: user.name, email: user.email, type: process.env.JWT_ACCESS, role: user.role }, process.env.JWT_KEY_SECRET as string, { subject: user.email, expiresIn: process.env.JWT_EXPIRES_IN, audience: process.env.JWT_AUDIENCE, issuer: process.env.JWT_ISSUER, }, ); }; const refreshToken = (user: { _id: string; name: string; email: string; role: string }) => { return sign( { id: user._id, name: user.name, email: user.email, type: process.env.JWT_REFRESH, role: user.role }, process.env.JWT_KEY_REFRESH as string, { subject: user.email, expiresIn: process.env.JWT_EXPIRES_IN, audience: process.env.JWT_AUDIENCE, issuer: process.env.JWT_ISSUER, }, ); }; const createSendToken = (user: IUser, statusCode: number, req: Request, res: Response) => { const acess = accessToken(user); const refresh = refreshToken(user); // Remove password from output // eslint-disable-next-line @typescript-eslint/no-unused-vars const
{ name, email, role, ...otherUserData } = user;
res.status(statusCode).json({ status: 'success', acess, refresh, data: { name, email, role, }, }); }; export const signup = catchAsync(async (req, res) => { const newUser = await User.create({ name: req.body.name, email: req.body.email, password: req.body.password, }); createSendToken(newUser, 201, req, res); }); export const login = catchAsync(async (req, res, next) => { const { email, password } = req.body; // 1) Check if email and password exist if (!email || !password) { return next(new AppError('Please provide email and password!', 400)); } // 2) Check if user exists && password is correct const user: any = await User.findOne({ email }).select('+password'); if (!user || !(await user.correctPassword(password, user.password))) { return next(new AppError('Incorrect email or password', 401)); } // 3) If everything ok, send token to client createSendToken(user, 200, req, res); }); export const getMe = catchAsync(async (req, res) => { const user = req.user; // 3) If everything ok, send token to client res.status(200).json({ message: 'user sucessfully fetched!', user }); }); export function logout(req: Request, res: Response) { res.cookie('jwt', 'loggedout', { expires: new Date(Date.now() + 10 * 1000), httpOnly: true, }); res.status(200).json({ status: 'success' }); } export async function refresh(req: Request, res: Response) { const user: any = req.user; await redisService.set({ key: user?.token, value: '1', timeType: 'EX', time: parseInt(process.env.JWT_REFRESH_TIME || '', 10), }); const refresh = refreshToken(user); return res.status(200).json({ status: 'sucess', refresh }); } export async function fetchUsers(req: Request, res: Response) { const body = req.body; console.log({ body }); try { const users = await User.find(); return res.status(200).json({ message: 'sucessfully fetch users', data: users }); } catch (error: any) { new AppError(error.message, 201); } } export async function deleteUser(req: Request, res: Response) { const id = req.params.id; try { await User.deleteOne({ _id: id }); return res.status(200).json({ message: 'sucessfully deleted users' }); } catch (error: any) { new AppError(error.message, 201); } }
src/modules/auth/service/index.ts
walosha-BACKEND_DEV_TESTS-db2fcb4
[ { "filename": "src/middleware/isLoggedIn.ts", "retrieved_chunk": "/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { NextFunction, Request, Response } from 'express';\nimport jwt from 'jsonwebtoken';\nimport User from '../modules/auth/model';\n// Only for rendered pages, no errors!\nexport async function isLoggedIn(req: Request, res: Response, next: NextFunction) {\n if (req.cookies.jwt) {\n try {\n // 1) verify token\n const decoded: any = await jwt.verify(req.cookies.jwt, process.env.JWT_KEY_SECRET as string);", "score": 29.12194906691274 }, { "filename": "src/middleware/roles.ts", "retrieved_chunk": "import { NextFunction, Request, Response } from 'express';\nimport { AppError } from '../utils/appError';\nimport { UserPayload } from '../../@types/express';\nexport function restrictTo(...roles: string[]) {\n return (req: Request & { user?: UserPayload }, res: Response, next: NextFunction) => {\n // roles ['admin', 'user']. role='user'\n if (req?.user) {\n if (!roles.includes(req.user.role)) {\n return next(new AppError('You do not have permission to perform this action', 403));\n }", "score": 18.96848163013994 }, { "filename": "src/utils/catchAsync.ts", "retrieved_chunk": "import { NextFunction, Request, Response } from 'express';\ntype AsyncFunction = (req: Request, res: Response, next: NextFunction) => Promise<any>;\nexport const catchAsync = (fn: AsyncFunction) => {\n return (req: Request, res: Response, next: NextFunction) => {\n fn(req, res, next).catch(next);\n };\n};", "score": 17.582608054061357 }, { "filename": "src/middleware/refresh.ts", "retrieved_chunk": "import jwt, { JwtPayload } from 'jsonwebtoken';\nimport redisService from '../utils/redis';\nimport { AppError } from '../utils/appError';\nimport { NextFunction, Request, Response } from 'express';\nexport const refreshMiddleware: any = async (req: Request, res: Response, next: NextFunction) => {\n if (req.body?.refresh) {\n const token = req.body.refresh;\n try {\n const decoded: any = jwt.verify(token, process.env.JWT_KEY_REFRESH as string) as JwtPayload;\n if (", "score": 17.04072172381099 }, { "filename": "src/modules/auth/types/index.ts", "retrieved_chunk": "export interface IUser {\n _id: string;\n name: string;\n email: string;\n role: 'user' | 'admin';\n password: string;\n}", "score": 16.54572232942889 } ]
typescript
{ name, email, role, ...otherUserData } = user;
import { sign } from 'jsonwebtoken'; import { IUser } from '../types'; import { Request, Response } from 'express'; import User from '../model'; import { AppError } from '../../../utils/appError'; import { catchAsync } from '../../../utils/catchAsync'; import redisService from '../../../utils/redis'; const accessToken = (user: { _id: string; name: string; email: string; role: string }) => { return sign( { id: user._id, name: user.name, email: user.email, type: process.env.JWT_ACCESS, role: user.role }, process.env.JWT_KEY_SECRET as string, { subject: user.email, expiresIn: process.env.JWT_EXPIRES_IN, audience: process.env.JWT_AUDIENCE, issuer: process.env.JWT_ISSUER, }, ); }; const refreshToken = (user: { _id: string; name: string; email: string; role: string }) => { return sign( { id: user._id, name: user.name, email: user.email, type: process.env.JWT_REFRESH, role: user.role }, process.env.JWT_KEY_REFRESH as string, { subject: user.email, expiresIn: process.env.JWT_EXPIRES_IN, audience: process.env.JWT_AUDIENCE, issuer: process.env.JWT_ISSUER, }, ); }; const createSendToken = (user: IUser, statusCode: number, req: Request, res: Response) => { const acess = accessToken(user); const refresh = refreshToken(user); // Remove password from output // eslint-disable-next-line @typescript-eslint/no-unused-vars const { name, email, role, ...otherUserData } = user; res.status(statusCode).json({ status: 'success', acess, refresh, data: { name, email, role, }, }); }; export const signup = catchAsync
(async (req, res) => {
const newUser = await User.create({ name: req.body.name, email: req.body.email, password: req.body.password, }); createSendToken(newUser, 201, req, res); }); export const login = catchAsync(async (req, res, next) => { const { email, password } = req.body; // 1) Check if email and password exist if (!email || !password) { return next(new AppError('Please provide email and password!', 400)); } // 2) Check if user exists && password is correct const user: any = await User.findOne({ email }).select('+password'); if (!user || !(await user.correctPassword(password, user.password))) { return next(new AppError('Incorrect email or password', 401)); } // 3) If everything ok, send token to client createSendToken(user, 200, req, res); }); export const getMe = catchAsync(async (req, res) => { const user = req.user; // 3) If everything ok, send token to client res.status(200).json({ message: 'user sucessfully fetched!', user }); }); export function logout(req: Request, res: Response) { res.cookie('jwt', 'loggedout', { expires: new Date(Date.now() + 10 * 1000), httpOnly: true, }); res.status(200).json({ status: 'success' }); } export async function refresh(req: Request, res: Response) { const user: any = req.user; await redisService.set({ key: user?.token, value: '1', timeType: 'EX', time: parseInt(process.env.JWT_REFRESH_TIME || '', 10), }); const refresh = refreshToken(user); return res.status(200).json({ status: 'sucess', refresh }); } export async function fetchUsers(req: Request, res: Response) { const body = req.body; console.log({ body }); try { const users = await User.find(); return res.status(200).json({ message: 'sucessfully fetch users', data: users }); } catch (error: any) { new AppError(error.message, 201); } } export async function deleteUser(req: Request, res: Response) { const id = req.params.id; try { await User.deleteOne({ _id: id }); return res.status(200).json({ message: 'sucessfully deleted users' }); } catch (error: any) { new AppError(error.message, 201); } }
src/modules/auth/service/index.ts
walosha-BACKEND_DEV_TESTS-db2fcb4
[ { "filename": "src/middleware/protect.ts", "retrieved_chunk": "import { NextFunction, Request, Response } from 'express';\nimport { JwtPayload, verify } from 'jsonwebtoken';\nimport { AppError } from '../utils/appError';\nimport { catchAsync } from '../utils/catchAsync';\nimport User from '../modules/auth/model';\nexport const protect = catchAsync(async (req: Request, res: Response, next: NextFunction) => {\n // 1) Getting token and check of it's there\n let token;\n if (req.headers.authorization && req.headers.authorization.startsWith('Bearer')) {\n token = req.headers.authorization.split(' ')[1];", "score": 10.27481144660087 }, { "filename": "src/utils/catchAsync.ts", "retrieved_chunk": "import { NextFunction, Request, Response } from 'express';\ntype AsyncFunction = (req: Request, res: Response, next: NextFunction) => Promise<any>;\nexport const catchAsync = (fn: AsyncFunction) => {\n return (req: Request, res: Response, next: NextFunction) => {\n fn(req, res, next).catch(next);\n };\n};", "score": 9.88492815162634 }, { "filename": "src/middleware/refresh.ts", "retrieved_chunk": " req.user = {\n email: decoded.email,\n name: decoded.name,\n role: decoded.role,\n token,\n };\n next();\n return;\n } catch (err) {\n console.log({ err });", "score": 9.797796687975092 }, { "filename": "src/middleware/refresh.ts", "retrieved_chunk": "import jwt, { JwtPayload } from 'jsonwebtoken';\nimport redisService from '../utils/redis';\nimport { AppError } from '../utils/appError';\nimport { NextFunction, Request, Response } from 'express';\nexport const refreshMiddleware: any = async (req: Request, res: Response, next: NextFunction) => {\n if (req.body?.refresh) {\n const token = req.body.refresh;\n try {\n const decoded: any = jwt.verify(token, process.env.JWT_KEY_REFRESH as string) as JwtPayload;\n if (", "score": 9.192050672156531 }, { "filename": "src/modules/auth/controller/index.ts", "retrieved_chunk": "import express from 'express';\nimport { getMe, login, refresh, signup } from '../service';\nimport { refreshMiddleware } from '../../../middleware/refresh';\nimport { protect } from '../../../middleware';\nconst router = express.Router();\n/**\n * @swagger\n * /api/v1/auth/signup:\n * post:\n * summary: Creates an account", "score": 8.987614342960367 } ]
typescript
(async (req, res) => {
import { sign } from 'jsonwebtoken'; import { IUser } from '../types'; import { Request, Response } from 'express'; import User from '../model'; import { AppError } from '../../../utils/appError'; import { catchAsync } from '../../../utils/catchAsync'; import redisService from '../../../utils/redis'; const accessToken = (user: { _id: string; name: string; email: string; role: string }) => { return sign( { id: user._id, name: user.name, email: user.email, type: process.env.JWT_ACCESS, role: user.role }, process.env.JWT_KEY_SECRET as string, { subject: user.email, expiresIn: process.env.JWT_EXPIRES_IN, audience: process.env.JWT_AUDIENCE, issuer: process.env.JWT_ISSUER, }, ); }; const refreshToken = (user: { _id: string; name: string; email: string; role: string }) => { return sign( { id: user._id, name: user.name, email: user.email, type: process.env.JWT_REFRESH, role: user.role }, process.env.JWT_KEY_REFRESH as string, { subject: user.email, expiresIn: process.env.JWT_EXPIRES_IN, audience: process.env.JWT_AUDIENCE, issuer: process.env.JWT_ISSUER, }, ); }; const createSendToken = (user: IUser, statusCode: number, req: Request, res: Response) => { const acess = accessToken(user); const refresh = refreshToken(user); // Remove password from output // eslint-disable-next-line @typescript-eslint/no-unused-vars const {
name, email, role, ...otherUserData } = user;
res.status(statusCode).json({ status: 'success', acess, refresh, data: { name, email, role, }, }); }; export const signup = catchAsync(async (req, res) => { const newUser = await User.create({ name: req.body.name, email: req.body.email, password: req.body.password, }); createSendToken(newUser, 201, req, res); }); export const login = catchAsync(async (req, res, next) => { const { email, password } = req.body; // 1) Check if email and password exist if (!email || !password) { return next(new AppError('Please provide email and password!', 400)); } // 2) Check if user exists && password is correct const user: any = await User.findOne({ email }).select('+password'); if (!user || !(await user.correctPassword(password, user.password))) { return next(new AppError('Incorrect email or password', 401)); } // 3) If everything ok, send token to client createSendToken(user, 200, req, res); }); export const getMe = catchAsync(async (req, res) => { const user = req.user; // 3) If everything ok, send token to client res.status(200).json({ message: 'user sucessfully fetched!', user }); }); export function logout(req: Request, res: Response) { res.cookie('jwt', 'loggedout', { expires: new Date(Date.now() + 10 * 1000), httpOnly: true, }); res.status(200).json({ status: 'success' }); } export async function refresh(req: Request, res: Response) { const user: any = req.user; await redisService.set({ key: user?.token, value: '1', timeType: 'EX', time: parseInt(process.env.JWT_REFRESH_TIME || '', 10), }); const refresh = refreshToken(user); return res.status(200).json({ status: 'sucess', refresh }); } export async function fetchUsers(req: Request, res: Response) { const body = req.body; console.log({ body }); try { const users = await User.find(); return res.status(200).json({ message: 'sucessfully fetch users', data: users }); } catch (error: any) { new AppError(error.message, 201); } } export async function deleteUser(req: Request, res: Response) { const id = req.params.id; try { await User.deleteOne({ _id: id }); return res.status(200).json({ message: 'sucessfully deleted users' }); } catch (error: any) { new AppError(error.message, 201); } }
src/modules/auth/service/index.ts
walosha-BACKEND_DEV_TESTS-db2fcb4
[ { "filename": "src/middleware/isLoggedIn.ts", "retrieved_chunk": "/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { NextFunction, Request, Response } from 'express';\nimport jwt from 'jsonwebtoken';\nimport User from '../modules/auth/model';\n// Only for rendered pages, no errors!\nexport async function isLoggedIn(req: Request, res: Response, next: NextFunction) {\n if (req.cookies.jwt) {\n try {\n // 1) verify token\n const decoded: any = await jwt.verify(req.cookies.jwt, process.env.JWT_KEY_SECRET as string);", "score": 29.12194906691274 }, { "filename": "src/middleware/roles.ts", "retrieved_chunk": "import { NextFunction, Request, Response } from 'express';\nimport { AppError } from '../utils/appError';\nimport { UserPayload } from '../../@types/express';\nexport function restrictTo(...roles: string[]) {\n return (req: Request & { user?: UserPayload }, res: Response, next: NextFunction) => {\n // roles ['admin', 'user']. role='user'\n if (req?.user) {\n if (!roles.includes(req.user.role)) {\n return next(new AppError('You do not have permission to perform this action', 403));\n }", "score": 18.96848163013994 }, { "filename": "src/utils/catchAsync.ts", "retrieved_chunk": "import { NextFunction, Request, Response } from 'express';\ntype AsyncFunction = (req: Request, res: Response, next: NextFunction) => Promise<any>;\nexport const catchAsync = (fn: AsyncFunction) => {\n return (req: Request, res: Response, next: NextFunction) => {\n fn(req, res, next).catch(next);\n };\n};", "score": 17.582608054061357 }, { "filename": "src/middleware/refresh.ts", "retrieved_chunk": "import jwt, { JwtPayload } from 'jsonwebtoken';\nimport redisService from '../utils/redis';\nimport { AppError } from '../utils/appError';\nimport { NextFunction, Request, Response } from 'express';\nexport const refreshMiddleware: any = async (req: Request, res: Response, next: NextFunction) => {\n if (req.body?.refresh) {\n const token = req.body.refresh;\n try {\n const decoded: any = jwt.verify(token, process.env.JWT_KEY_REFRESH as string) as JwtPayload;\n if (", "score": 17.04072172381099 }, { "filename": "src/modules/auth/types/index.ts", "retrieved_chunk": "export interface IUser {\n _id: string;\n name: string;\n email: string;\n role: 'user' | 'admin';\n password: string;\n}", "score": 16.54572232942889 } ]
typescript
name, email, role, ...otherUserData } = user;
import { sign } from 'jsonwebtoken'; import { IUser } from '../types'; import { Request, Response } from 'express'; import User from '../model'; import { AppError } from '../../../utils/appError'; import { catchAsync } from '../../../utils/catchAsync'; import redisService from '../../../utils/redis'; const accessToken = (user: { _id: string; name: string; email: string; role: string }) => { return sign( { id: user._id, name: user.name, email: user.email, type: process.env.JWT_ACCESS, role: user.role }, process.env.JWT_KEY_SECRET as string, { subject: user.email, expiresIn: process.env.JWT_EXPIRES_IN, audience: process.env.JWT_AUDIENCE, issuer: process.env.JWT_ISSUER, }, ); }; const refreshToken = (user: { _id: string; name: string; email: string; role: string }) => { return sign( { id: user._id, name: user.name, email: user.email, type: process.env.JWT_REFRESH, role: user.role }, process.env.JWT_KEY_REFRESH as string, { subject: user.email, expiresIn: process.env.JWT_EXPIRES_IN, audience: process.env.JWT_AUDIENCE, issuer: process.env.JWT_ISSUER, }, ); }; const createSendToken = (user: IUser, statusCode: number, req: Request, res: Response) => { const acess = accessToken(user); const refresh = refreshToken(user); // Remove password from output // eslint-disable-next-line @typescript-eslint/no-unused-vars const { name, email, role, ...otherUserData } = user; res.status(statusCode).json({ status: 'success', acess, refresh, data: { name, email, role, }, }); }; export const signup = catchAsync(async (req, res) => { const newUser = await User.create({ name: req.body.name, email: req.body.email, password: req.body.password, }); createSendToken(newUser, 201, req, res); }); export const login = catchAsync(async (req, res
, next) => {
const { email, password } = req.body; // 1) Check if email and password exist if (!email || !password) { return next(new AppError('Please provide email and password!', 400)); } // 2) Check if user exists && password is correct const user: any = await User.findOne({ email }).select('+password'); if (!user || !(await user.correctPassword(password, user.password))) { return next(new AppError('Incorrect email or password', 401)); } // 3) If everything ok, send token to client createSendToken(user, 200, req, res); }); export const getMe = catchAsync(async (req, res) => { const user = req.user; // 3) If everything ok, send token to client res.status(200).json({ message: 'user sucessfully fetched!', user }); }); export function logout(req: Request, res: Response) { res.cookie('jwt', 'loggedout', { expires: new Date(Date.now() + 10 * 1000), httpOnly: true, }); res.status(200).json({ status: 'success' }); } export async function refresh(req: Request, res: Response) { const user: any = req.user; await redisService.set({ key: user?.token, value: '1', timeType: 'EX', time: parseInt(process.env.JWT_REFRESH_TIME || '', 10), }); const refresh = refreshToken(user); return res.status(200).json({ status: 'sucess', refresh }); } export async function fetchUsers(req: Request, res: Response) { const body = req.body; console.log({ body }); try { const users = await User.find(); return res.status(200).json({ message: 'sucessfully fetch users', data: users }); } catch (error: any) { new AppError(error.message, 201); } } export async function deleteUser(req: Request, res: Response) { const id = req.params.id; try { await User.deleteOne({ _id: id }); return res.status(200).json({ message: 'sucessfully deleted users' }); } catch (error: any) { new AppError(error.message, 201); } }
src/modules/auth/service/index.ts
walosha-BACKEND_DEV_TESTS-db2fcb4
[ { "filename": "src/utils/catchAsync.ts", "retrieved_chunk": "import { NextFunction, Request, Response } from 'express';\ntype AsyncFunction = (req: Request, res: Response, next: NextFunction) => Promise<any>;\nexport const catchAsync = (fn: AsyncFunction) => {\n return (req: Request, res: Response, next: NextFunction) => {\n fn(req, res, next).catch(next);\n };\n};", "score": 35.04689734701321 }, { "filename": "src/middleware/refresh.ts", "retrieved_chunk": "import jwt, { JwtPayload } from 'jsonwebtoken';\nimport redisService from '../utils/redis';\nimport { AppError } from '../utils/appError';\nimport { NextFunction, Request, Response } from 'express';\nexport const refreshMiddleware: any = async (req: Request, res: Response, next: NextFunction) => {\n if (req.body?.refresh) {\n const token = req.body.refresh;\n try {\n const decoded: any = jwt.verify(token, process.env.JWT_KEY_REFRESH as string) as JwtPayload;\n if (", "score": 34.38804612060772 }, { "filename": "src/middleware/protect.ts", "retrieved_chunk": "import { NextFunction, Request, Response } from 'express';\nimport { JwtPayload, verify } from 'jsonwebtoken';\nimport { AppError } from '../utils/appError';\nimport { catchAsync } from '../utils/catchAsync';\nimport User from '../modules/auth/model';\nexport const protect = catchAsync(async (req: Request, res: Response, next: NextFunction) => {\n // 1) Getting token and check of it's there\n let token;\n if (req.headers.authorization && req.headers.authorization.startsWith('Bearer')) {\n token = req.headers.authorization.split(' ')[1];", "score": 32.648631112473666 }, { "filename": "src/modules/account/service/index.ts", "retrieved_chunk": "import { Request, Response } from 'express';\nimport Account from '../model';\nexport const transferFund = async (req: Request, res: Response) => {\n const { fromAccountId, toAccountId, amount } = req.body;\n try {\n let srcAccount: any = await Account.findById(fromAccountId);\n let destAccount: any = await Account.findById(toAccountId);\n if (String(srcAccount.user) == String(destAccount.user)) {\n return res.status(400).json({\n error: 'Cannot transfer to own acccount',", "score": 29.95978992658713 }, { "filename": "src/middleware/isLoggedIn.ts", "retrieved_chunk": "/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { NextFunction, Request, Response } from 'express';\nimport jwt from 'jsonwebtoken';\nimport User from '../modules/auth/model';\n// Only for rendered pages, no errors!\nexport async function isLoggedIn(req: Request, res: Response, next: NextFunction) {\n if (req.cookies.jwt) {\n try {\n // 1) verify token\n const decoded: any = await jwt.verify(req.cookies.jwt, process.env.JWT_KEY_SECRET as string);", "score": 23.53646495015619 } ]
typescript
, next) => {
import { sign } from 'jsonwebtoken'; import { IUser } from '../types'; import { Request, Response } from 'express'; import User from '../model'; import { AppError } from '../../../utils/appError'; import { catchAsync } from '../../../utils/catchAsync'; import redisService from '../../../utils/redis'; const accessToken = (user: { _id: string; name: string; email: string; role: string }) => { return sign( { id: user._id, name: user.name, email: user.email, type: process.env.JWT_ACCESS, role: user.role }, process.env.JWT_KEY_SECRET as string, { subject: user.email, expiresIn: process.env.JWT_EXPIRES_IN, audience: process.env.JWT_AUDIENCE, issuer: process.env.JWT_ISSUER, }, ); }; const refreshToken = (user: { _id: string; name: string; email: string; role: string }) => { return sign( { id: user._id, name: user.name, email: user.email, type: process.env.JWT_REFRESH, role: user.role }, process.env.JWT_KEY_REFRESH as string, { subject: user.email, expiresIn: process.env.JWT_EXPIRES_IN, audience: process.env.JWT_AUDIENCE, issuer: process.env.JWT_ISSUER, }, ); }; const createSendToken = (user: IUser, statusCode: number, req: Request, res: Response) => { const acess = accessToken(user); const refresh = refreshToken(user); // Remove password from output // eslint-disable-next-line @typescript-eslint/no-unused-vars const { name, email, role, ...otherUserData } = user; res.status(statusCode).json({ status: 'success', acess, refresh, data: { name, email, role, }, }); }; export const signup = catchAsync(async (req, res) => { const newUser = await User.create({ name: req.body.name, email: req.body.email, password: req.body.password, }); createSendToken(newUser, 201, req, res); }); export const login = catchAsync(async (req, res, next) => { const { email, password } = req.body; // 1) Check if email and password exist if (!email || !password) { return next(new AppError('Please provide email and password!', 400)); } // 2) Check if user exists && password is correct
const user: any = await User.findOne({ email }).select('+password');
if (!user || !(await user.correctPassword(password, user.password))) { return next(new AppError('Incorrect email or password', 401)); } // 3) If everything ok, send token to client createSendToken(user, 200, req, res); }); export const getMe = catchAsync(async (req, res) => { const user = req.user; // 3) If everything ok, send token to client res.status(200).json({ message: 'user sucessfully fetched!', user }); }); export function logout(req: Request, res: Response) { res.cookie('jwt', 'loggedout', { expires: new Date(Date.now() + 10 * 1000), httpOnly: true, }); res.status(200).json({ status: 'success' }); } export async function refresh(req: Request, res: Response) { const user: any = req.user; await redisService.set({ key: user?.token, value: '1', timeType: 'EX', time: parseInt(process.env.JWT_REFRESH_TIME || '', 10), }); const refresh = refreshToken(user); return res.status(200).json({ status: 'sucess', refresh }); } export async function fetchUsers(req: Request, res: Response) { const body = req.body; console.log({ body }); try { const users = await User.find(); return res.status(200).json({ message: 'sucessfully fetch users', data: users }); } catch (error: any) { new AppError(error.message, 201); } } export async function deleteUser(req: Request, res: Response) { const id = req.params.id; try { await User.deleteOne({ _id: id }); return res.status(200).json({ message: 'sucessfully deleted users' }); } catch (error: any) { new AppError(error.message, 201); } }
src/modules/auth/service/index.ts
walosha-BACKEND_DEV_TESTS-db2fcb4
[ { "filename": "src/middleware/protect.ts", "retrieved_chunk": " // 3) Check if user still exists\n const currentUser = await User.findById(decoded.id);\n if (!currentUser) {\n return next(new AppError('The user belonging to this token does no longer exist.', 401));\n }\n // GRANT ACCESS TO PROTECTED ROUTE\n req.user = currentUser;\n next();\n});", "score": 35.586507750652245 }, { "filename": "src/middleware/isLoggedIn.ts", "retrieved_chunk": " // 2) Check if user still exists\n const currentUser = await User.findById(decoded?.id);\n if (!currentUser) {\n return next();\n }\n return next();\n } catch (err) {\n return next();\n }\n }", "score": 35.36443024486808 }, { "filename": "src/modules/auth/controller/index.ts", "retrieved_chunk": " * email:\n * type: string\n * description: The user email address\n * password:\n * type: string\n * description: The user password\n * example:\n * email: [email protected]\n * password: password123\n */", "score": 31.832466080869487 }, { "filename": "src/modules/account/controller/index.ts", "retrieved_chunk": " * email:\n * type: string\n * description: The user email address\n * password:\n * type: string\n * description: The user password\n * example:\n * email: [email protected]\n * password: password123\n */", "score": 31.832466080869487 }, { "filename": "src/modules/auth/model/index.ts", "retrieved_chunk": " password: string;\n}\nconst userSchema = new Schema<IUser>({\n name: {\n type: String,\n required: [true, 'Please tell us your name!'],\n },\n email: {\n type: String,\n required: [true, 'Please provide your email'],", "score": 31.417437753623517 } ]
typescript
const user: any = await User.findOne({ email }).select('+password');
import { AuthenticationFields, AuthenticationResponse, RequestRefreshTokenOptions, NonceHashOptions, API, Endpoints, AccessToken, PreBuiltAuthenticationToken } from '../types'; import axios, { AxiosProxyConfig, AxiosResponse } from 'axios'; import { createHmac } from 'node:crypto'; import KretaError from './errors/KretaError'; import requireParam from '../decorators/requireParam'; import tryRequest from '../utils/tryRequest'; import requireCredentials from '../decorators/requireCredentials'; export class Authentication { private readonly username: string; private readonly password: string; private readonly institute_code: string; private readonly client_id: string = 'kreta-ellenorzo-mobile-android'; private readonly grant_type: string = 'password'; private readonly auth_policy_version: string = 'v2'; constructor(options: AuthenticationFields) { this.username = options.username; this.password = options.password; this.institute_code = options.institute_code; } public get _username() { return this.username; } public get _password() { return this.password; } public get _institute_code() { return this.institute_code; } @requireParam('proxy.host') @requireParam('proxy.port') public setProxy(proxy: AxiosProxyConfig): this { axios.defaults.proxy = proxy; return this; } @requireParam('ua') public setUserAgent(ua: string): this { axios.defaults.headers.common['User-Agent'] = ua; return this; };
@requireCredentials private authenticate(options: AuthenticationFields): Promise<AuthenticationResponse> {
return new Promise(async (resolve): Promise<void> => { const nonce_key: string = await this.getNonce(); const hash: string = await this.getNonceHash({ nonce: nonce_key, institute_code: options.institute_code, username: options.username }); await tryRequest(axios.post(API.IDP + Endpoints.Token, { institute_code: options.institute_code, username: options.username, password: options.password, grant_type: this.grant_type, client_id: this.client_id }, { headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'X-Authorizationpolicy-Nonce': nonce_key, 'X-Authorizationpolicy-Key': hash, 'X-Authorizationpolicy-Version': this.auth_policy_version, } }).then((r: AxiosResponse<AuthenticationResponse>) => resolve(r.data))); }); } private getNonce(): Promise<string> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(API.IDP + Endpoints.Nonce).then((r: AxiosResponse<string>) => resolve(r.data.toString()))); }); } private getNonceHash(options: NonceHashOptions): Promise<string> { return new Promise((resolve): void => { const buffer_bytes: Buffer = Buffer.from(options.institute_code.toUpperCase() + options.nonce + options.username.toUpperCase(), 'utf8'); const hash: Buffer = createHmac('sha512', Buffer.from([98, 97, 83, 115, 120, 79, 119, 108, 85, 49, 106, 77])).update(buffer_bytes).digest(); return resolve(hash.toString('base64')); }); } private async returnTokens(): Promise<AccessToken> { return await this.authenticate({ username: this.username, password: this.password, institute_code: this.institute_code }).then((r: AuthenticationResponse): AccessToken => { return { access_token: r.access_token, refresh_token: r.refresh_token, token_type: r.token_type }; }).catch((): { access_token: null; refresh_token: null; token_type: null } => { return { access_token: null, refresh_token: null, token_type: null }; }); } public getAccessToken(): Promise<PreBuiltAuthenticationToken> { return new Promise(async (resolve, reject): Promise<void> => { const { access_token, refresh_token }: AccessToken = await this.returnTokens(); if (access_token === null || refresh_token === null) return reject(new KretaError('Failed to get access token: Invalid credentials')); else return resolve({ token: 'Bearer' + ' ' + access_token, access_token, refresh_token }); }); } @requireParam('options.refreshToken') @requireParam('options.refreshUserData') public getRefreshToken(options: RequestRefreshTokenOptions): Promise<AuthenticationResponse> { return new Promise(async (resolve): Promise<void> => { const nonce_key: string = await this.getNonce(); const hash: string = await this.getNonceHash({ nonce: nonce_key, institute_code: this.institute_code, username: this.username }); await tryRequest(axios.post(API.IDP + Endpoints.Token, { refresh_token: options.refreshToken, institute_code: this.institute_code, grant_type: 'refresh_token', client_id: this.client_id, refresh_user_data: options.refreshUserData }, { headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'X-Authorizationpolicy-Key': hash, 'X-Authorizationpolicy-Version': this.auth_policy_version, } }).then((r: AxiosResponse<AuthenticationResponse>) => resolve(r.data) )); }); } }
src/lib/Authentication.ts
blazsmaster-kreta.js-9274c52
[ { "filename": "src/lib/Kreta.ts", "retrieved_chunk": "\t\taxios.defaults.proxy = proxy;\n\t\treturn this;\n\t}\n\t@requireParam('ua')\n\tpublic setUserAgent(ua: string): this {\n\t\taxios.defaults.headers.common['User-Agent'] = ua;\n\t\treturn this;\n\t}\n\tprivate buildEllenorzoApiURL(endpointWithSlash: Endpoints, params?: { [key: string]: any }): string {\n\t\tconst urlParams: string = params ? '?' + new URLSearchParams(params).toString() : '';", "score": 64.80499377621977 }, { "filename": "src/lib/Kreta.ts", "retrieved_chunk": "\t}\n\tpublic get _password() {\n\t\treturn this.password;\n\t}\n\tpublic get _institute_code() {\n\t\treturn this.institute_code;\n\t}\n\t@requireParam('proxy.host')\n\t@requireParam('proxy.port')\n\tpublic setProxy(proxy: AxiosProxyConfig): this {", "score": 20.69961228251497 }, { "filename": "src/lib/Administration.ts", "retrieved_chunk": "\tprivate token?: Promise<string>;\n\tconstructor(options: AuthenticationFields) {\n\t\tthis.username = options.username;\n\t\tthis.password = options.password;\n\t\tthis.institute_code = options.institute_code;\n\t\tthis.authenticate = new Authentication({ username: this.username, password: this.password, institute_code: this.institute_code });\n\t\tif (this.username && this.password && this.institute_code)\n\t\t\tthis.token = this.authenticate.getAccessToken().then((r: PreBuiltAuthenticationToken) => r.token);\n\t\taxios.defaults.headers['X-Uzenet-Lokalizacio'] = 'hu-HU';\n\t}", "score": 20.406231422277394 }, { "filename": "src/lib/Kreta.ts", "retrieved_chunk": "\t\tthis.institute_code = options?.institute_code || '';\n\t\taxios.defaults.headers.common['User-Agent'] = 'hu.ekreta.student/1.0.5/Android/0/0';\n\t\tthis.Global = new Global();\n\t\tthis.authenticate = new Authentication({ username: this.username!, password: this.password!, institute_code: this.institute_code! });\n\t\tif (this.username && this.password && this.institute_code)\n\t\t\tthis.token = this.authenticate.getAccessToken().then((r: PreBuiltAuthenticationToken) => r.token);\n\t\tthis.Administration = new Administration({ username: this.username!, password: this.password!, institute_code: this.institute_code! });\n\t}\n\tpublic get _username() {\n\t\treturn this.username;", "score": 19.764500642924734 }, { "filename": "src/lib/Kreta.ts", "retrieved_chunk": "\tprivate readonly username?: string;\n\tprivate readonly password?: string;\n\tprivate readonly institute_code?: string;\n\tprivate authenticate?: Authentication;\n\tpublic Administration?: Administration;\n\tpublic Global: Global;\n\tprivate token?: Promise<string>;\n\tconstructor(options?: KretaOptions) {\n\t\tthis.username = options?.username || '';\n\t\tthis.password = options?.password || '';", "score": 16.01077298355666 } ]
typescript
@requireCredentials private authenticate(options: AuthenticationFields): Promise<AuthenticationResponse> {
import axios, { AxiosProxyConfig, AxiosResponse } from 'axios'; import moment from 'moment'; import { AnnouncedTest, ClassAverage, ClassMaster, ConfigurationDescriptor, Evaluation, Group, Homework, Institute, Institution, KretaOptions, LepEvent, Lesson, Note, NoticeBoardItem, Omission, PreBuiltAuthenticationToken, RequestAnnouncedTestsOptions, RequestClassAveragesOptions, RequestDateRangeOptions, RequestDateRangeRequiredOptions, RequestHomeWorkOptions, SchoolYearCalendarEntry, Student, SubjectAverage, TimeTableWeek, API, Endpoints } from '../types'; import { Authentication } from './Authentication'; import dynamicValue from '../utils/dynamicValue'; import Administration from './Administration'; import Global from './Global'; import requireCredentials from '../decorators/requireCredentials'; import tryRequest from '../utils/tryRequest'; import validateDate from '../utils/validateDate'; import requireParam from '../decorators/requireParam'; export default class Kreta { private readonly username?: string; private readonly password?: string; private readonly institute_code?: string; private authenticate?: Authentication; public Administration?: Administration; public Global: Global; private token?: Promise<string>; constructor(options?: KretaOptions) { this.username = options?.username || ''; this.password = options?.password || ''; this.institute_code = options?.institute_code || ''; axios.defaults.headers.common['User-Agent'] = 'hu.ekreta.student/1.0.5/Android/0/0';
this.Global = new Global();
this.authenticate = new Authentication({ username: this.username!, password: this.password!, institute_code: this.institute_code! }); if (this.username && this.password && this.institute_code) this.token = this.authenticate.getAccessToken().then((r: PreBuiltAuthenticationToken) => r.token); this.Administration = new Administration({ username: this.username!, password: this.password!, institute_code: this.institute_code! }); } public get _username() { return this.username; } public get _password() { return this.password; } public get _institute_code() { return this.institute_code; } @requireParam('proxy.host') @requireParam('proxy.port') public setProxy(proxy: AxiosProxyConfig): this { axios.defaults.proxy = proxy; return this; } @requireParam('ua') public setUserAgent(ua: string): this { axios.defaults.headers.common['User-Agent'] = ua; return this; } private buildEllenorzoApiURL(endpointWithSlash: Endpoints, params?: { [key: string]: any }): string { const urlParams: string = params ? '?' + new URLSearchParams(params).toString() : ''; return dynamicValue(API.INSTITUTE, { institute_code: this.institute_code }).toString() + '/ellenorzo/V3' + endpointWithSlash + urlParams; } @requireParam('api_key') public getInstituteList(api_key: string): Promise<Institute[]> { return new Promise(async (resolve): Promise<void> => { const config_descriptor: AxiosResponse<ConfigurationDescriptor> = await axios.get('https://kretamobile.blob.core.windows.net/configuration/ConfigurationDescriptor.json'); await tryRequest(axios.get(config_descriptor.data.GlobalMobileApiUrlPROD + '/api/v3/Institute', { headers: { apiKey: api_key } }).then((r: AxiosResponse<Institute[]>) => resolve(r.data))); }); } @requireCredentials public getStudent(): Promise<Student> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.Tanulo), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Student>) => resolve(r.data))); }); } @requireCredentials public getEvaluations(options?: RequestDateRangeOptions): Promise<Evaluation[]> { return new Promise(async (resolve): Promise<void> => { const ops: { datumTol?: string; datumIg?: string } = {}; if (options?.dateFrom) ops.datumTol = validateDate(moment(options.dateFrom).format('YYYY-MM-DD')); if (options?.dateTo) ops.datumIg = validateDate(moment(options.dateTo).format('YYYY-MM-DD')); await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.Ertekelesek, ops), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Evaluation[]>) => resolve(r.data))); }); } @requireCredentials public getNotes(options?: RequestDateRangeOptions): Promise<Note[]> { return new Promise(async (resolve): Promise<void> => { const ops: { datumTol?: string; datumIg?: string } = {}; if (options?.dateFrom) ops.datumTol = validateDate(moment(options.dateFrom).format('YYYY-MM-DD')); if (options?.dateTo) ops.datumIg = validateDate(moment(options.dateTo).format('YYYY-MM-DD')); await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.Feljegyzesek, ops), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Note[]>) => resolve(r.data))); }); } @requireCredentials public getAnnouncedTests(options?: RequestAnnouncedTestsOptions): Promise<AnnouncedTest[]> { return new Promise(async (resolve): Promise<void> => { const ops: { datumTol?: string; datumIg?: string, Uids?: string } = {}; if (options?.dateFrom) ops.datumTol = validateDate(moment(options.dateFrom).format('YYYY-MM-DD')); if (options?.dateTo) ops.datumIg = validateDate(moment(options.dateTo).format('YYYY-MM-DD')); if (options?.uids) ops.Uids = options.uids.map((uid: string | number) => uid.toString()).join(';'); await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.Szamonkeresek, ops), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<AnnouncedTest[]>) => resolve(r.data))); }); } @requireCredentials @requireParam('options.dateFrom') public getHomeworks(options: RequestHomeWorkOptions): Promise<Homework[]> { return new Promise(async (resolve): Promise<void> => { const ops: { datumTol: string; datumIg?: string } = { datumTol: validateDate(moment(options.dateFrom).format('YYYY-MM-DD')) }; if (options?.dateTo) ops.datumIg = validateDate(moment(options.dateTo).format('YYYY-MM-DD')); await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.HaziFeladatok, ops), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Homework[]>) => resolve(r.data))); }); } @requireCredentials @requireParam('uid') public getHomework(uid: string | number): Promise<Homework> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.HaziFeladatok) + '/' + uid.toString(), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Homework>) => resolve(r.data))); }); } @requireCredentials public getOmissions(options?: RequestDateRangeOptions): Promise<Omission[]> { return new Promise(async (resolve): Promise<void> => { const ops: { datumTol?: string; datumIg?: string } = {}; if (options?.dateFrom) ops.datumTol = validateDate(moment(options.dateFrom).format('YYYY-MM-DD')); if (options?.dateTo) ops.datumIg = validateDate(moment(options.dateTo).format('YYYY-MM-DD')); await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.Mulasztasok, ops), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Omission[]>) => resolve(r.data))); }); } @requireCredentials public getGroups(): Promise<Group[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.OsztalyCsoportok), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Group[]>) => resolve(r.data))); }); } @requireCredentials public getSubjectAverages(onfUid?: string): Promise<SubjectAverage[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.TantargyiAtlagok, { oktatasiNevelesiFeladatUid: onfUid || await this.getGroups().then((groups: Group[]) => groups[0].OktatasNevelesiFeladat.Uid) }), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<SubjectAverage[]>) => resolve(r.data))); }); } @requireCredentials @requireParam('options.dateFrom') @requireParam('options.dateTo') public getLessons(options: RequestDateRangeRequiredOptions): Promise<Lesson[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.OrarendElemek, { datumTol: validateDate(moment(options.dateFrom).format('YYYY-MM-DD')), datumIg: validateDate(moment(options.dateTo).format('YYYY-MM-DD')) }), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Lesson[]>) => resolve(r.data))); }); } @requireCredentials @requireParam('uid') public getLesson(uid: string | number): Promise<Lesson> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.OrarendElem, { orarendElemUid: uid.toString() }), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Lesson>) => resolve(r.data))); }); } @requireCredentials public getNoticeBoardItems(): Promise<NoticeBoardItem[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.FaliujsagElemek), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<NoticeBoardItem[]>) => resolve(r.data))); }); } @requireCredentials public getClassAverage(options?: RequestClassAveragesOptions): Promise<ClassAverage[]> { return new Promise(async (resolve): Promise<void> => { const ops: { oktatasiNevelesiFeladatUid: string; tantargyUid?: string; } = { oktatasiNevelesiFeladatUid: options?.oktatasiNevelesiFeladatUid || await this.getGroups().then((groups: Group[]) => groups[0].OktatasNevelesiFeladat.Uid) }; if (options?.subjectUid) ops.tantargyUid = options.subjectUid; await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.OsztalyCsoportAtlag, ops), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<ClassAverage[]>) => resolve(r.data))); }); } @requireCredentials public getInstitute(): Promise<Institution> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.Intezmenyek), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Institution>) => resolve(r.data))); }); } @requireCredentials @requireParam('uids') public getClassMasters(uids: string[] | number[]): Promise<ClassMaster[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.Osztalyfonokok, { Uids: uids.map((u: string | number) => u.toString()).join(';') }), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<ClassMaster[]>) => resolve(r.data))); }); } @requireCredentials @requireParam('options.dateFrom') @requireParam('options.dateTo') public getTimeTableWeeks(options: RequestDateRangeRequiredOptions): Promise<TimeTableWeek[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.OrarendHetek, { orarendElemKezdoNapDatuma: validateDate(moment(options.dateFrom).format('YYYY-MM-DD')), orarendElemVegNapDatuma: validateDate(moment(options.dateTo).format('YYYY-MM-DD')) }), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<TimeTableWeek[]>) => resolve(r.data))); }); } @requireCredentials public getLepEvents(): Promise<LepEvent[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.Eloadasok), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<LepEvent[]>) => resolve(r.data))); }); } @requireCredentials public getSchoolYearCalendar(): Promise<SchoolYearCalendarEntry[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.TanevNaptar), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<SchoolYearCalendarEntry[]>) => resolve(r.data))); }); } @requireCredentials public getDeviceGivenState(): Promise<boolean> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.EszkozAllapot), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<boolean>) => resolve(r.data))); }); } }
src/lib/Kreta.ts
blazsmaster-kreta.js-9274c52
[ { "filename": "src/lib/Administration.ts", "retrieved_chunk": "\tprivate token?: Promise<string>;\n\tconstructor(options: AuthenticationFields) {\n\t\tthis.username = options.username;\n\t\tthis.password = options.password;\n\t\tthis.institute_code = options.institute_code;\n\t\tthis.authenticate = new Authentication({ username: this.username, password: this.password, institute_code: this.institute_code });\n\t\tif (this.username && this.password && this.institute_code)\n\t\t\tthis.token = this.authenticate.getAccessToken().then((r: PreBuiltAuthenticationToken) => r.token);\n\t\taxios.defaults.headers['X-Uzenet-Lokalizacio'] = 'hu-HU';\n\t}", "score": 62.836019527377644 }, { "filename": "src/lib/Authentication.ts", "retrieved_chunk": "\tprivate readonly auth_policy_version: string = 'v2';\n\tconstructor(options: AuthenticationFields) {\n\t\tthis.username = options.username;\n\t\tthis.password = options.password;\n\t\tthis.institute_code = options.institute_code;\n\t}\n\tpublic get _username() {\n\t\treturn this.username;\n\t}\n\tpublic get _password() {", "score": 54.63193070827865 }, { "filename": "src/lib/Authentication.ts", "retrieved_chunk": "\t\t\tconst hash: string = await this.getNonceHash({\n\t\t\t\tnonce: nonce_key,\n\t\t\t\tinstitute_code: options.institute_code,\n\t\t\t\tusername: options.username\n\t\t\t});\n\t\t\tawait tryRequest(axios.post(API.IDP + Endpoints.Token, {\n\t\t\t\tinstitute_code: options.institute_code,\n\t\t\t\tusername: options.username,\n\t\t\t\tpassword: options.password,\n\t\t\t\tgrant_type: this.grant_type,", "score": 44.958843254996346 }, { "filename": "src/lib/Authentication.ts", "retrieved_chunk": "\t}\n\t@requireParam('ua')\n\tpublic setUserAgent(ua: string): this {\n\t\taxios.defaults.headers.common['User-Agent'] = ua;\n\t\treturn this;\n\t};\n\t@requireCredentials\n\tprivate authenticate(options: AuthenticationFields): Promise<AuthenticationResponse> {\n\t\treturn new Promise(async (resolve): Promise<void> => {\n\t\t\tconst nonce_key: string = await this.getNonce();", "score": 42.42581814268546 }, { "filename": "src/lib/Authentication.ts", "retrieved_chunk": "\t\t\t\tinstitute_code: this.institute_code,\n\t\t\t\tusername: this.username\n\t\t\t});\n\t\t\tawait tryRequest(axios.post(API.IDP + Endpoints.Token, {\n\t\t\t\trefresh_token: options.refreshToken,\n\t\t\t\tinstitute_code: this.institute_code,\n\t\t\t\tgrant_type: 'refresh_token',\n\t\t\t\tclient_id: this.client_id,\n\t\t\t\trefresh_user_data: options.refreshUserData\n\t\t\t}, {", "score": 34.02745189104392 } ]
typescript
this.Global = new Global();
import { Cog6ToothIcon } from "@heroicons/react/24/solid"; import Image from "next/image"; import useStore from "~/store/store"; import type { Message } from "~/types/appstate"; import { TextWithCode } from "../TextWithCode"; function classNames(...classes: string[]) { return classes.filter(Boolean).join(' ') } const AIResponse = ({ content }: { content: string }) => { return ( <div className="prose prose-sm max-w-full dark:prose-invert"> <TextWithCode text={content} /> </div> ); }; const MessageContainer = ({ content, role }: Message) => { return ( <div className="px-4 rounded-lg mb-2"> <div className="pl-14 relative response-block scroll-mt-32 rounded-md hover:bg-gray-50 dark:hover:bg-zinc-900 pb-2 pt-2 pr-2 group min-h-[52px]"> <div className="absolute top-2 left-2"> <div className='w-9 h-9 bg-gray-200 rounded-md flex-none flex items-center justify-center text-gray-500 hover:bg-gray-300 transition-all active:bg-gray-200'> {role === 'user' ? (<Image src='/favicon.ico' alt="Avatar" width={20} height={20} />) : (<Cog6ToothIcon className="w-5 h-5" />) } </div> </div> <div className="w-full"> {role === 'assistant' ? <AIResponse content={content} /> : ( <div> <div className="text-sm whitespace-pre-wrap space-y-2 w-fit text-white px-4 py-2 rounded-lg max-w-full overflow-auto highlight-darkblue focus:outline bg-blue-500"> {content} </div> </div> )} </div> </div> </div> ); }; const MessageWindow = () => {
const thread = useStore((state) => state.thread) if (!thread.messages) {
return null; } return ( <> {thread.messages.map((message, index) => { return ( <MessageContainer key={index} {...message} /> ); }) } </> ); }; export default MessageWindow;
src/components/ChatWindow/MessageWindow.tsx
cloudnothings-better-gpt-f1ad4fa
[ { "filename": "src/pages/index.tsx", "retrieved_chunk": " </div>\n </div>\n </div>\n </div>\n </div >\n )\n}\nconst ThreadList = () => {\n const threads = useStore((state) => state.threads)\n const selectedThread = useStore((state) => state.thread)", "score": 26.355309196123482 }, { "filename": "src/components/modals/ChangeModelModal.tsx", "retrieved_chunk": " const setThread = useStore((state) => state.setThread)\n const modelModal = useStore((state) => state.modelModal)\n const setModelModal = useStore((state) => state.setModelModal)\n const models = useStore((state) => state.models)\n const [selectedModel, setSelectedModel] = useState<Model>(thread.model)\n useEffect(() => {\n setSelectedModel(thread.model)\n }, [thread.model])\n const [systemInstruction, setSystemInstruction] = useState<string>(thread.initialSystemInstruction)\n const confirmationHandler = () => {", "score": 25.76420977462586 }, { "filename": "src/pages/index.tsx", "retrieved_chunk": "const StarredChat = (props: Thread & { selected: boolean }) => {\n const profile = useStore((state) => state.profile)\n const setProfile = useStore((state) => state.setProfile)\n const setThread = useStore((state) => state.setThread)\n const threads = useStore((state) => state.threads)\n const setThreads = useStore((state) => state.setThreads)\n const starThreadHandler: MouseEventHandler<HTMLButtonElement> = (e) => {\n e.stopPropagation()\n setThread({ ...props, starred: !props.starred })\n setThreads(threads.map(thread => thread.id === props.id ? { ...thread, starred: !thread.starred } : thread))", "score": 25.733842776669132 }, { "filename": "src/pages/index.tsx", "retrieved_chunk": " const selectedThread = useStore((state) => state.thread)\n return (\n <>\n <div className=\"max-h-[200px] overflow-auto\">\n {threads.map((thread) => (\n <StarredChat {...thread} key={thread.id} selected={selectedThread.id === thread.id} />\n ))}\n </div>\n {threads.length > 0 && (<hr className=\"border-gray-700\"></hr>)}\n </ >", "score": 25.613804677704863 }, { "filename": "src/components/ChatWindow/ChatWindow.tsx", "retrieved_chunk": " setStyle('mx-auto w-full hide-when-print transition-all max-w-full px-12')\n break\n }\n }, [width])\n const [showMenu, setShowMenu] = useState<boolean>(false)\n const thread = useStore((state) => state.thread)\n const setThread = useStore((state) => state.setThread)\n const setProfile = useStore((state) => state.setProfile)\n const profile = useStore((state) => state.profile)\n const { mutate, isLoading } = api.gpt.post.useMutation()", "score": 22.209515608366154 } ]
typescript
const thread = useStore((state) => state.thread) if (!thread.messages) {
import { Cog6ToothIcon } from "@heroicons/react/24/solid"; import Image from "next/image"; import useStore from "~/store/store"; import type { Message } from "~/types/appstate"; import { TextWithCode } from "../TextWithCode"; function classNames(...classes: string[]) { return classes.filter(Boolean).join(' ') } const AIResponse = ({ content }: { content: string }) => { return ( <div className="prose prose-sm max-w-full dark:prose-invert"> <TextWithCode text={content} /> </div> ); }; const MessageContainer = ({ content, role }: Message) => { return ( <div className="px-4 rounded-lg mb-2"> <div className="pl-14 relative response-block scroll-mt-32 rounded-md hover:bg-gray-50 dark:hover:bg-zinc-900 pb-2 pt-2 pr-2 group min-h-[52px]"> <div className="absolute top-2 left-2"> <div className='w-9 h-9 bg-gray-200 rounded-md flex-none flex items-center justify-center text-gray-500 hover:bg-gray-300 transition-all active:bg-gray-200'> {role === 'user' ? (<Image src='/favicon.ico' alt="Avatar" width={20} height={20} />) : (<Cog6ToothIcon className="w-5 h-5" />) } </div> </div> <div className="w-full"> {role === 'assistant' ? <AIResponse content={content} /> : ( <div> <div className="text-sm whitespace-pre-wrap space-y-2 w-fit text-white px-4 py-2 rounded-lg max-w-full overflow-auto highlight-darkblue focus:outline bg-blue-500"> {content} </div> </div> )} </div> </div> </div> ); }; const MessageWindow = () => { const thread = useStore((state) => state.thread) if (!thread.messages) { return null; } return ( <>
{thread.messages.map((message, index) => {
return ( <MessageContainer key={index} {...message} /> ); }) } </> ); }; export default MessageWindow;
src/components/ChatWindow/MessageWindow.tsx
cloudnothings-better-gpt-f1ad4fa
[ { "filename": "src/components/ChatWindow/ChatWindow.tsx", "retrieved_chunk": " const [message, setMessage] = useState<string>(\"\")\n const sendMessage = () => {\n if (message.length > 0) {\n if (thread.messages.length === 0) {\n const id = uuid()\n const messages = [\n { role: 'system', content: thread.initialSystemInstruction },\n { role: 'user', content: message }\n ] as Message[]\n mutate({", "score": 33.093618642902854 }, { "filename": "src/pages/index.tsx", "retrieved_chunk": "const StarredChat = (props: Thread & { selected: boolean }) => {\n const profile = useStore((state) => state.profile)\n const setProfile = useStore((state) => state.setProfile)\n const setThread = useStore((state) => state.setThread)\n const threads = useStore((state) => state.threads)\n const setThreads = useStore((state) => state.setThreads)\n const starThreadHandler: MouseEventHandler<HTMLButtonElement> = (e) => {\n e.stopPropagation()\n setThread({ ...props, starred: !props.starred })\n setThreads(threads.map(thread => thread.id === props.id ? { ...thread, starred: !thread.starred } : thread))", "score": 32.805120723557486 }, { "filename": "src/pages/index.tsx", "retrieved_chunk": " const selectedThread = useStore((state) => state.thread)\n return (\n <>\n <div className=\"max-h-[200px] overflow-auto\">\n {threads.map((thread) => (\n <StarredChat {...thread} key={thread.id} selected={selectedThread.id === thread.id} />\n ))}\n </div>\n {threads.length > 0 && (<hr className=\"border-gray-700\"></hr>)}\n </ >", "score": 32.62312148065703 }, { "filename": "src/components/ChatWindow/ChatWindow.tsx", "retrieved_chunk": " const cost = calculateCost(data.usage, thread.model)\n setThread({ ...thread, cost: thread.cost + cost, messages: [...thread.messages, { content: message, role: \"user\" }, data.choices[0].message] as Message[] })\n setProfile({ ...profile, cost: profile.cost + cost, usage: increaseUsage(profile.usage, data.usage) })\n setMessage(\"\")\n },\n onError: (e) => {\n alert(e.message)\n }\n })\n }", "score": 31.026500705896247 }, { "filename": "src/components/ChatWindow/ChatWindow.tsx", "retrieved_chunk": " })\n setMessage(\"\")\n },\n onError: (e) => {\n alert(e.message)\n }\n })\n } else\n mutate({ model: thread.model.id, apiKey: profile.key, messages: [...thread.messages, { content: message, role: \"user\" }] }, {\n onSuccess: (data) => {", "score": 30.22545681515991 } ]
typescript
{thread.messages.map((message, index) => {
import axios, { AxiosResponse } from 'axios'; import { AddresseType, AuthenticationFields, CardEvent, CurrentInstitutionDetails, DefaultType, EmployeeDetails, GuardianEAdmin, KretaClass, MailboxItem, MessageLimitations, PreBuiltAuthenticationToken, API, AdministrationEndpoints } from '../types'; import { Authentication } from './Authentication'; import requireCredentials from '../decorators/requireCredentials'; import tryRequest from '../utils/tryRequest'; import requireParam from '../decorators/requireParam'; export default class Administration { private readonly username: string; private readonly password: string; private readonly institute_code: string; private authenticate: Authentication; private token?: Promise<string>; constructor(options: AuthenticationFields) { this.username = options.username; this.password = options.password; this.institute_code = options.institute_code; this.authenticate = new Authentication({ username: this.username, password: this.password, institute_code: this.institute_code }); if (this.username && this.password && this.institute_code) this.token = this.authenticate.getAccessToken().then((r: PreBuiltAuthenticationToken) => r.token); axios.defaults.headers['X-Uzenet-Lokalizacio'] = 'hu-HU'; } public get _username() { return this.username; } public get _password() { return this.password; } public get _institute_code() { return this.institute_code; } private buildUgyintezesApiURL(endpointWithSlash: AdministrationEndpoints, params?: { [key: string]: any }): string { const urlParams: string = params ? '?' + new URLSearchParams(params).toString() : ''; return API.ADMINISTRATION + '/api/v1' + endpointWithSlash + urlParams; } @requireCredentials public getAddresseeType(): Promise<AddresseType[]> { return new Promise(async (resolve): Promise<void> => {
await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.CimzettTipusok), {
headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<AddresseType[]>) => resolve(r.data))); }); } @requireCredentials public getCaseTypes(): Promise<DefaultType[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.KerelemTipusok), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<DefaultType[]>) => resolve(r.data))); }); } @requireCredentials public getTmgiCaseTypes(): Promise<DefaultType[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.TmgiIgazolasTipusok), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<DefaultType[]>) => resolve(r.data))); }); } @requireCredentials public getAccessControlSystemEvents(): Promise<CardEvent[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.Esemenyek), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<CardEvent[]>) => resolve(r.data))); }); } @requireCredentials public getCurrentInstitutionModules(): Promise<string[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.JelenlegiIntezmenyModulok), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<string[]>) => resolve(r.data))); }); } @requireCredentials public getAddressableType(): Promise<AddresseType[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.CimezhetoTipusok), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<AddresseType[]>) => resolve(r.data))); }); } @requireCredentials @requireParam('addressId') public getAddressableClasses(addressId: string | number): Promise<KretaClass[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.CimezhetoOsztalyok, { cimzettKod: addressId.toString() }), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<KretaClass[]>) => resolve(r.data))); }); } @requireCredentials public getUnreadMessagesCount(): Promise<number> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.OlvasatlanokSzama), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<number>) => resolve(r.data))); }); } @requireCredentials public getMessages(): Promise<MailboxItem[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.Uzenetek), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<MailboxItem[]>) => resolve(r.data))); }); } @requireCredentials @requireParam('id') public getMessage(id: string | number): Promise<MailboxItem> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.Uzenet) + '/' + id.toString(), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<MailboxItem>) => resolve(r.data))); }); } @requireCredentials public getAddressableSzmkRepesentative(): Promise<GuardianEAdmin[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.CimezhetoSzmkKepviselok), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<GuardianEAdmin[]>) => resolve(r.data))); }); } @requireCredentials public getMessageLimitations(): Promise<MessageLimitations> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.UzenetLimitacio), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<MessageLimitations>) => resolve(r.data))); }); } @requireCredentials public getAdministrators(): Promise<EmployeeDetails[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.Adminisztratorok), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<EmployeeDetails[]>) => resolve(r.data))); }); } @requireCredentials public getDirectors(): Promise<EmployeeDetails[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.Igazgatok), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<EmployeeDetails[]>) => resolve(r.data))); }); } @requireCredentials public getClassMasters(): Promise<EmployeeDetails[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.Osztalyfonokok), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<EmployeeDetails[]>) => resolve(r.data))); }); } @requireCredentials public getTeachers(): Promise<EmployeeDetails[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.Oktatok), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<EmployeeDetails[]>) => resolve(r.data))); }); } @requireCredentials @requireParam('classId') public getAddressableGuardiansForClass(classId: string | number): Promise<GuardianEAdmin[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.CimezhetoTanuloSzulok) + '/' + classId.toString(), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<GuardianEAdmin[]>) => resolve(r.data))); }); } @requireCredentials public getCurrentInstitutionDetails(): Promise<CurrentInstitutionDetails> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.JelenlegiIntezmeny), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<CurrentInstitutionDetails>) => resolve(r.data))); }); } }
src/lib/Administration.ts
blazsmaster-kreta.js-9274c52
[ { "filename": "src/lib/Kreta.ts", "retrieved_chunk": "\t\taxios.defaults.proxy = proxy;\n\t\treturn this;\n\t}\n\t@requireParam('ua')\n\tpublic setUserAgent(ua: string): this {\n\t\taxios.defaults.headers.common['User-Agent'] = ua;\n\t\treturn this;\n\t}\n\tprivate buildEllenorzoApiURL(endpointWithSlash: Endpoints, params?: { [key: string]: any }): string {\n\t\tconst urlParams: string = params ? '?' + new URLSearchParams(params).toString() : '';", "score": 62.41693870505462 }, { "filename": "src/lib/Kreta.ts", "retrieved_chunk": "\t\treturn dynamicValue(API.INSTITUTE, { institute_code: this.institute_code }).toString() + '/ellenorzo/V3' + endpointWithSlash + urlParams;\n\t}\n\t@requireParam('api_key')\n\tpublic getInstituteList(api_key: string): Promise<Institute[]> {\n\t\treturn new Promise(async (resolve): Promise<void> => {\n\t\t\tconst config_descriptor: AxiosResponse<ConfigurationDescriptor> = await axios.get('https://kretamobile.blob.core.windows.net/configuration/ConfigurationDescriptor.json');\n\t\t\tawait tryRequest(axios.get(config_descriptor.data.GlobalMobileApiUrlPROD + '/api/v3/Institute', {\n\t\t\t\theaders: {\n\t\t\t\t\tapiKey: api_key\n\t\t\t\t}", "score": 38.39132024878659 }, { "filename": "src/lib/Authentication.ts", "retrieved_chunk": "\t}\n\t@requireParam('ua')\n\tpublic setUserAgent(ua: string): this {\n\t\taxios.defaults.headers.common['User-Agent'] = ua;\n\t\treturn this;\n\t};\n\t@requireCredentials\n\tprivate authenticate(options: AuthenticationFields): Promise<AuthenticationResponse> {\n\t\treturn new Promise(async (resolve): Promise<void> => {\n\t\t\tconst nonce_key: string = await this.getNonce();", "score": 25.563895551959554 }, { "filename": "src/lib/Authentication.ts", "retrieved_chunk": "\t}\n\tprivate getNonce(): Promise<string> {\n\t\treturn new Promise(async (resolve): Promise<void> => {\n\t\t\tawait tryRequest(axios.get(API.IDP + Endpoints.Nonce).then((r: AxiosResponse<string>) => resolve(r.data.toString())));\n\t\t});\n\t}\n\tprivate getNonceHash(options: NonceHashOptions): Promise<string> {\n\t\treturn new Promise((resolve): void => {\n\t\t\tconst buffer_bytes: Buffer = Buffer.from(options.institute_code.toUpperCase() + options.nonce + options.username.toUpperCase(), 'utf8');\n\t\t\tconst hash: Buffer = createHmac('sha512', Buffer.from([98, 97, 83, 115, 120, 79, 119, 108, 85, 49, 106, 77])).update(buffer_bytes).digest();", "score": 25.538716537150833 }, { "filename": "src/lib/Kreta.ts", "retrieved_chunk": "\t\t});\n\t}\n\t@requireCredentials\n\t@requireParam('uids')\n\tpublic getClassMasters(uids: string[] | number[]): Promise<ClassMaster[]> {\n\t\treturn new Promise(async (resolve): Promise<void> => {\n\t\t\tawait tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.Osztalyfonokok, { Uids: uids.map((u: string | number) => u.toString()).join(';') }), {\n\t\t\t\theaders: {\n\t\t\t\t\t'Authorization': await this.token,\n\t\t\t\t}", "score": 24.41806281983277 } ]
typescript
await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.CimzettTipusok), {
import { Cog6ToothIcon } from "@heroicons/react/24/solid"; import Image from "next/image"; import useStore from "~/store/store"; import type { Message } from "~/types/appstate"; import { TextWithCode } from "../TextWithCode"; function classNames(...classes: string[]) { return classes.filter(Boolean).join(' ') } const AIResponse = ({ content }: { content: string }) => { return ( <div className="prose prose-sm max-w-full dark:prose-invert"> <TextWithCode text={content} /> </div> ); }; const MessageContainer = ({ content, role }: Message) => { return ( <div className="px-4 rounded-lg mb-2"> <div className="pl-14 relative response-block scroll-mt-32 rounded-md hover:bg-gray-50 dark:hover:bg-zinc-900 pb-2 pt-2 pr-2 group min-h-[52px]"> <div className="absolute top-2 left-2"> <div className='w-9 h-9 bg-gray-200 rounded-md flex-none flex items-center justify-center text-gray-500 hover:bg-gray-300 transition-all active:bg-gray-200'> {role === 'user' ? (<Image src='/favicon.ico' alt="Avatar" width={20} height={20} />) : (<Cog6ToothIcon className="w-5 h-5" />) } </div> </div> <div className="w-full"> {role === 'assistant' ? <AIResponse content={content} /> : ( <div> <div className="text-sm whitespace-pre-wrap space-y-2 w-fit text-white px-4 py-2 rounded-lg max-w-full overflow-auto highlight-darkblue focus:outline bg-blue-500"> {content} </div> </div> )} </div> </div> </div> ); }; const MessageWindow = () => { const thread =
useStore((state) => state.thread) if (!thread.messages) {
return null; } return ( <> {thread.messages.map((message, index) => { return ( <MessageContainer key={index} {...message} /> ); }) } </> ); }; export default MessageWindow;
src/components/ChatWindow/MessageWindow.tsx
cloudnothings-better-gpt-f1ad4fa
[ { "filename": "src/components/modals/ChangeModelModal.tsx", "retrieved_chunk": " const setThread = useStore((state) => state.setThread)\n const modelModal = useStore((state) => state.modelModal)\n const setModelModal = useStore((state) => state.setModelModal)\n const models = useStore((state) => state.models)\n const [selectedModel, setSelectedModel] = useState<Model>(thread.model)\n useEffect(() => {\n setSelectedModel(thread.model)\n }, [thread.model])\n const [systemInstruction, setSystemInstruction] = useState<string>(thread.initialSystemInstruction)\n const confirmationHandler = () => {", "score": 25.76420977462586 }, { "filename": "src/pages/index.tsx", "retrieved_chunk": "const StarredChat = (props: Thread & { selected: boolean }) => {\n const profile = useStore((state) => state.profile)\n const setProfile = useStore((state) => state.setProfile)\n const setThread = useStore((state) => state.setThread)\n const threads = useStore((state) => state.threads)\n const setThreads = useStore((state) => state.setThreads)\n const starThreadHandler: MouseEventHandler<HTMLButtonElement> = (e) => {\n e.stopPropagation()\n setThread({ ...props, starred: !props.starred })\n setThreads(threads.map(thread => thread.id === props.id ? { ...thread, starred: !thread.starred } : thread))", "score": 25.733842776669132 }, { "filename": "src/pages/index.tsx", "retrieved_chunk": " </div>\n </div>\n </div>\n </div>\n </div >\n )\n}\nconst ThreadList = () => {\n const threads = useStore((state) => state.threads)\n const selectedThread = useStore((state) => state.thread)", "score": 25.322333232914954 }, { "filename": "src/pages/index.tsx", "retrieved_chunk": " const selectedThread = useStore((state) => state.thread)\n return (\n <>\n <div className=\"max-h-[200px] overflow-auto\">\n {threads.map((thread) => (\n <StarredChat {...thread} key={thread.id} selected={selectedThread.id === thread.id} />\n ))}\n </div>\n {threads.length > 0 && (<hr className=\"border-gray-700\"></hr>)}\n </ >", "score": 24.873296478891994 }, { "filename": "src/components/ChatWindow/ChatWindow.tsx", "retrieved_chunk": " setStyle('mx-auto w-full hide-when-print transition-all max-w-full px-12')\n break\n }\n }, [width])\n const [showMenu, setShowMenu] = useState<boolean>(false)\n const thread = useStore((state) => state.thread)\n const setThread = useStore((state) => state.setThread)\n const setProfile = useStore((state) => state.setProfile)\n const profile = useStore((state) => state.profile)\n const { mutate, isLoading } = api.gpt.post.useMutation()", "score": 22.209515608366154 } ]
typescript
useStore((state) => state.thread) if (!thread.messages) {
import axios, { AxiosResponse } from 'axios'; import { AddresseType, AuthenticationFields, CardEvent, CurrentInstitutionDetails, DefaultType, EmployeeDetails, GuardianEAdmin, KretaClass, MailboxItem, MessageLimitations, PreBuiltAuthenticationToken, API, AdministrationEndpoints } from '../types'; import { Authentication } from './Authentication'; import requireCredentials from '../decorators/requireCredentials'; import tryRequest from '../utils/tryRequest'; import requireParam from '../decorators/requireParam'; export default class Administration { private readonly username: string; private readonly password: string; private readonly institute_code: string; private authenticate: Authentication; private token?: Promise<string>; constructor(options: AuthenticationFields) { this.username = options.username; this.password = options.password; this.institute_code = options.institute_code; this.authenticate = new Authentication({ username: this.username, password: this.password, institute_code: this.institute_code }); if (this.username && this.password && this.institute_code) this.token = this.authenticate.getAccessToken().then((r: PreBuiltAuthenticationToken) => r.token); axios.defaults.headers['X-Uzenet-Lokalizacio'] = 'hu-HU'; } public get _username() { return this.username; } public get _password() { return this.password; } public get _institute_code() { return this.institute_code; } private buildUgyintezesApiURL(endpointWithSlash: AdministrationEndpoints, params?: { [key: string]: any }): string { const urlParams: string = params ? '?' + new URLSearchParams(params).toString() : ''; return API.ADMINISTRATION + '/api/v1' + endpointWithSlash + urlParams; }
@requireCredentials public getAddresseeType(): Promise<AddresseType[]> {
return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.CimzettTipusok), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<AddresseType[]>) => resolve(r.data))); }); } @requireCredentials public getCaseTypes(): Promise<DefaultType[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.KerelemTipusok), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<DefaultType[]>) => resolve(r.data))); }); } @requireCredentials public getTmgiCaseTypes(): Promise<DefaultType[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.TmgiIgazolasTipusok), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<DefaultType[]>) => resolve(r.data))); }); } @requireCredentials public getAccessControlSystemEvents(): Promise<CardEvent[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.Esemenyek), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<CardEvent[]>) => resolve(r.data))); }); } @requireCredentials public getCurrentInstitutionModules(): Promise<string[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.JelenlegiIntezmenyModulok), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<string[]>) => resolve(r.data))); }); } @requireCredentials public getAddressableType(): Promise<AddresseType[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.CimezhetoTipusok), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<AddresseType[]>) => resolve(r.data))); }); } @requireCredentials @requireParam('addressId') public getAddressableClasses(addressId: string | number): Promise<KretaClass[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.CimezhetoOsztalyok, { cimzettKod: addressId.toString() }), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<KretaClass[]>) => resolve(r.data))); }); } @requireCredentials public getUnreadMessagesCount(): Promise<number> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.OlvasatlanokSzama), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<number>) => resolve(r.data))); }); } @requireCredentials public getMessages(): Promise<MailboxItem[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.Uzenetek), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<MailboxItem[]>) => resolve(r.data))); }); } @requireCredentials @requireParam('id') public getMessage(id: string | number): Promise<MailboxItem> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.Uzenet) + '/' + id.toString(), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<MailboxItem>) => resolve(r.data))); }); } @requireCredentials public getAddressableSzmkRepesentative(): Promise<GuardianEAdmin[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.CimezhetoSzmkKepviselok), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<GuardianEAdmin[]>) => resolve(r.data))); }); } @requireCredentials public getMessageLimitations(): Promise<MessageLimitations> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.UzenetLimitacio), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<MessageLimitations>) => resolve(r.data))); }); } @requireCredentials public getAdministrators(): Promise<EmployeeDetails[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.Adminisztratorok), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<EmployeeDetails[]>) => resolve(r.data))); }); } @requireCredentials public getDirectors(): Promise<EmployeeDetails[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.Igazgatok), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<EmployeeDetails[]>) => resolve(r.data))); }); } @requireCredentials public getClassMasters(): Promise<EmployeeDetails[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.Osztalyfonokok), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<EmployeeDetails[]>) => resolve(r.data))); }); } @requireCredentials public getTeachers(): Promise<EmployeeDetails[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.Oktatok), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<EmployeeDetails[]>) => resolve(r.data))); }); } @requireCredentials @requireParam('classId') public getAddressableGuardiansForClass(classId: string | number): Promise<GuardianEAdmin[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.CimezhetoTanuloSzulok) + '/' + classId.toString(), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<GuardianEAdmin[]>) => resolve(r.data))); }); } @requireCredentials public getCurrentInstitutionDetails(): Promise<CurrentInstitutionDetails> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.JelenlegiIntezmeny), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<CurrentInstitutionDetails>) => resolve(r.data))); }); } }
src/lib/Administration.ts
blazsmaster-kreta.js-9274c52
[ { "filename": "src/lib/Kreta.ts", "retrieved_chunk": "\t\taxios.defaults.proxy = proxy;\n\t\treturn this;\n\t}\n\t@requireParam('ua')\n\tpublic setUserAgent(ua: string): this {\n\t\taxios.defaults.headers.common['User-Agent'] = ua;\n\t\treturn this;\n\t}\n\tprivate buildEllenorzoApiURL(endpointWithSlash: Endpoints, params?: { [key: string]: any }): string {\n\t\tconst urlParams: string = params ? '?' + new URLSearchParams(params).toString() : '';", "score": 59.4451405852137 }, { "filename": "src/lib/Kreta.ts", "retrieved_chunk": "\t\treturn dynamicValue(API.INSTITUTE, { institute_code: this.institute_code }).toString() + '/ellenorzo/V3' + endpointWithSlash + urlParams;\n\t}\n\t@requireParam('api_key')\n\tpublic getInstituteList(api_key: string): Promise<Institute[]> {\n\t\treturn new Promise(async (resolve): Promise<void> => {\n\t\t\tconst config_descriptor: AxiosResponse<ConfigurationDescriptor> = await axios.get('https://kretamobile.blob.core.windows.net/configuration/ConfigurationDescriptor.json');\n\t\t\tawait tryRequest(axios.get(config_descriptor.data.GlobalMobileApiUrlPROD + '/api/v3/Institute', {\n\t\t\t\theaders: {\n\t\t\t\t\tapiKey: api_key\n\t\t\t\t}", "score": 29.36626471366006 }, { "filename": "src/utils/dynamicValue.ts", "retrieved_chunk": "export default function dynamicValue(str: string, values: { [key: string]: any }): string {\n\treturn str.replace(/{{(.*?)}}/g, (match: string, key) => values[key] || match);\n}", "score": 17.61770214080683 }, { "filename": "src/lib/Authentication.ts", "retrieved_chunk": "\t}\n\tprivate getNonce(): Promise<string> {\n\t\treturn new Promise(async (resolve): Promise<void> => {\n\t\t\tawait tryRequest(axios.get(API.IDP + Endpoints.Nonce).then((r: AxiosResponse<string>) => resolve(r.data.toString())));\n\t\t});\n\t}\n\tprivate getNonceHash(options: NonceHashOptions): Promise<string> {\n\t\treturn new Promise((resolve): void => {\n\t\t\tconst buffer_bytes: Buffer = Buffer.from(options.institute_code.toUpperCase() + options.nonce + options.username.toUpperCase(), 'utf8');\n\t\t\tconst hash: Buffer = createHmac('sha512', Buffer.from([98, 97, 83, 115, 120, 79, 119, 108, 85, 49, 106, 77])).update(buffer_bytes).digest();", "score": 16.287917083650235 }, { "filename": "src/lib/Kreta.ts", "retrieved_chunk": "\tprivate readonly username?: string;\n\tprivate readonly password?: string;\n\tprivate readonly institute_code?: string;\n\tprivate authenticate?: Authentication;\n\tpublic Administration?: Administration;\n\tpublic Global: Global;\n\tprivate token?: Promise<string>;\n\tconstructor(options?: KretaOptions) {\n\t\tthis.username = options?.username || '';\n\t\tthis.password = options?.password || '';", "score": 16.17813571183219 } ]
typescript
@requireCredentials public getAddresseeType(): Promise<AddresseType[]> {
import axios, { AxiosResponse } from 'axios'; import { AddresseType, AuthenticationFields, CardEvent, CurrentInstitutionDetails, DefaultType, EmployeeDetails, GuardianEAdmin, KretaClass, MailboxItem, MessageLimitations, PreBuiltAuthenticationToken, API, AdministrationEndpoints } from '../types'; import { Authentication } from './Authentication'; import requireCredentials from '../decorators/requireCredentials'; import tryRequest from '../utils/tryRequest'; import requireParam from '../decorators/requireParam'; export default class Administration { private readonly username: string; private readonly password: string; private readonly institute_code: string; private authenticate: Authentication; private token?: Promise<string>; constructor(options: AuthenticationFields) { this.username = options.username; this.password = options.password; this.institute_code = options.institute_code; this.authenticate = new Authentication({ username: this.username, password: this.password, institute_code: this.institute_code }); if (this.username && this.password && this.institute_code) this.token = this.authenticate.getAccessToken().then((r: PreBuiltAuthenticationToken) => r.token); axios.defaults.headers['X-Uzenet-Lokalizacio'] = 'hu-HU'; } public get _username() { return this.username; } public get _password() { return this.password; } public get _institute_code() { return this.institute_code; } private buildUgyintezesApiURL(endpointWithSlash: AdministrationEndpoints, params?: { [key: string]: any }): string { const urlParams: string = params ? '?' + new URLSearchParams(params).toString() : ''; return API.ADMINISTRATION + '/api/v1' + endpointWithSlash + urlParams; } @requireCredentials public getAddresseeType(): Promise<AddresseType[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.CimzettTipusok), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<AddresseType[]>) => resolve(r.data))); }); } @requireCredentials public getCaseTypes(): Promise<DefaultType[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.KerelemTipusok), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<DefaultType[]>) => resolve(r.data))); }); } @requireCredentials public getTmgiCaseTypes(): Promise<DefaultType[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.TmgiIgazolasTipusok), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<DefaultType[]>) => resolve(r.data))); }); } @requireCredentials public getAccessControlSystemEvents(): Promise<CardEvent[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.Esemenyek), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<CardEvent[]>) => resolve(r.data))); }); } @requireCredentials public getCurrentInstitutionModules(): Promise<string[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.JelenlegiIntezmenyModulok), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<string[]>) => resolve(r.data))); }); } @requireCredentials public getAddressableType(): Promise<AddresseType[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.CimezhetoTipusok), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<AddresseType[]>) => resolve(r.data))); }); } @requireCredentials @
requireParam('addressId') public getAddressableClasses(addressId: string | number): Promise<KretaClass[]> {
return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.CimezhetoOsztalyok, { cimzettKod: addressId.toString() }), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<KretaClass[]>) => resolve(r.data))); }); } @requireCredentials public getUnreadMessagesCount(): Promise<number> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.OlvasatlanokSzama), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<number>) => resolve(r.data))); }); } @requireCredentials public getMessages(): Promise<MailboxItem[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.Uzenetek), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<MailboxItem[]>) => resolve(r.data))); }); } @requireCredentials @requireParam('id') public getMessage(id: string | number): Promise<MailboxItem> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.Uzenet) + '/' + id.toString(), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<MailboxItem>) => resolve(r.data))); }); } @requireCredentials public getAddressableSzmkRepesentative(): Promise<GuardianEAdmin[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.CimezhetoSzmkKepviselok), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<GuardianEAdmin[]>) => resolve(r.data))); }); } @requireCredentials public getMessageLimitations(): Promise<MessageLimitations> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.UzenetLimitacio), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<MessageLimitations>) => resolve(r.data))); }); } @requireCredentials public getAdministrators(): Promise<EmployeeDetails[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.Adminisztratorok), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<EmployeeDetails[]>) => resolve(r.data))); }); } @requireCredentials public getDirectors(): Promise<EmployeeDetails[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.Igazgatok), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<EmployeeDetails[]>) => resolve(r.data))); }); } @requireCredentials public getClassMasters(): Promise<EmployeeDetails[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.Osztalyfonokok), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<EmployeeDetails[]>) => resolve(r.data))); }); } @requireCredentials public getTeachers(): Promise<EmployeeDetails[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.Oktatok), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<EmployeeDetails[]>) => resolve(r.data))); }); } @requireCredentials @requireParam('classId') public getAddressableGuardiansForClass(classId: string | number): Promise<GuardianEAdmin[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.CimezhetoTanuloSzulok) + '/' + classId.toString(), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<GuardianEAdmin[]>) => resolve(r.data))); }); } @requireCredentials public getCurrentInstitutionDetails(): Promise<CurrentInstitutionDetails> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.JelenlegiIntezmeny), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<CurrentInstitutionDetails>) => resolve(r.data))); }); } }
src/lib/Administration.ts
blazsmaster-kreta.js-9274c52
[ { "filename": "src/lib/Kreta.ts", "retrieved_chunk": "\t\t\t\t\t'Authorization': await this.token,\n\t\t\t\t}\n\t\t\t}).then((r: AxiosResponse<Lesson[]>) => resolve(r.data)));\n\t\t});\n\t}\n\t@requireCredentials\n\t@requireParam('uid')\n\tpublic getLesson(uid: string | number): Promise<Lesson> {\n\t\treturn new Promise(async (resolve): Promise<void> => {\n\t\t\tawait tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.OrarendElem, { orarendElemUid: uid.toString() }), {", "score": 18.55994998447302 }, { "filename": "src/lib/Kreta.ts", "retrieved_chunk": "\t\t\t\theaders: {\n\t\t\t\t\t'Authorization': await this.token,\n\t\t\t\t}\n\t\t\t}).then((r: AxiosResponse<NoticeBoardItem[]>) => resolve(r.data)));\n\t\t});\n\t}\n\t@requireCredentials\n\tpublic getClassAverage(options?: RequestClassAveragesOptions): Promise<ClassAverage[]> {\n\t\treturn new Promise(async (resolve): Promise<void> => {\n\t\t\tconst ops: {", "score": 18.095354323101112 }, { "filename": "src/lib/Kreta.ts", "retrieved_chunk": "\t@requireCredentials\n\tpublic getGroups(): Promise<Group[]> {\n\t\treturn new Promise(async (resolve): Promise<void> => {\n\t\t\tawait tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.OsztalyCsoportok), {\n\t\t\t\theaders: {\n\t\t\t\t\t'Authorization': await this.token,\n\t\t\t\t}\n\t\t\t}).then((r: AxiosResponse<Group[]>) => resolve(r.data)));\n\t\t});\n\t}", "score": 17.80568294445252 }, { "filename": "src/lib/Kreta.ts", "retrieved_chunk": "\t\t});\n\t}\n\t@requireCredentials\n\tpublic getInstitute(): Promise<Institution> {\n\t\treturn new Promise(async (resolve): Promise<void> => {\n\t\t\tawait tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.Intezmenyek), {\n\t\t\t\theaders: {\n\t\t\t\t\t'Authorization': await this.token,\n\t\t\t\t}\n\t\t\t}).then((r: AxiosResponse<Institution>) => resolve(r.data)));", "score": 17.80568294445252 }, { "filename": "src/lib/Kreta.ts", "retrieved_chunk": "\t\treturn new Promise(async (resolve): Promise<void> => {\n\t\t\tawait tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.TanevNaptar), {\n\t\t\t\theaders: {\n\t\t\t\t\t'Authorization': await this.token,\n\t\t\t\t}\n\t\t\t}).then((r: AxiosResponse<SchoolYearCalendarEntry[]>) => resolve(r.data)));\n\t\t});\n\t}\n\t@requireCredentials\n\tpublic getDeviceGivenState(): Promise<boolean> {", "score": 17.80568294445252 } ]
typescript
requireParam('addressId') public getAddressableClasses(addressId: string | number): Promise<KretaClass[]> {
import { AuthenticationFields, AuthenticationResponse, RequestRefreshTokenOptions, NonceHashOptions, API, Endpoints, AccessToken, PreBuiltAuthenticationToken } from '../types'; import axios, { AxiosProxyConfig, AxiosResponse } from 'axios'; import { createHmac } from 'node:crypto'; import KretaError from './errors/KretaError'; import requireParam from '../decorators/requireParam'; import tryRequest from '../utils/tryRequest'; import requireCredentials from '../decorators/requireCredentials'; export class Authentication { private readonly username: string; private readonly password: string; private readonly institute_code: string; private readonly client_id: string = 'kreta-ellenorzo-mobile-android'; private readonly grant_type: string = 'password'; private readonly auth_policy_version: string = 'v2'; constructor(options: AuthenticationFields) { this.username = options.username; this.password = options.password; this.institute_code = options.institute_code; } public get _username() { return this.username; } public get _password() { return this.password; } public get _institute_code() { return this.institute_code; } @requireParam('proxy.host') @requireParam('proxy.port') public setProxy(proxy: AxiosProxyConfig): this { axios.defaults.proxy = proxy; return this; } @requireParam('ua') public setUserAgent(ua: string): this { axios.defaults.headers.common['User-Agent'] = ua; return this; }; @requireCredentials private authenticate(options: AuthenticationFields): Promise<AuthenticationResponse> { return new Promise(async (resolve): Promise<void> => { const nonce_key: string = await this.getNonce(); const hash: string = await this.getNonceHash({ nonce: nonce_key, institute_code: options.institute_code, username: options.username }); await
tryRequest(axios.post(API.IDP + Endpoints.Token, {
institute_code: options.institute_code, username: options.username, password: options.password, grant_type: this.grant_type, client_id: this.client_id }, { headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'X-Authorizationpolicy-Nonce': nonce_key, 'X-Authorizationpolicy-Key': hash, 'X-Authorizationpolicy-Version': this.auth_policy_version, } }).then((r: AxiosResponse<AuthenticationResponse>) => resolve(r.data))); }); } private getNonce(): Promise<string> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(API.IDP + Endpoints.Nonce).then((r: AxiosResponse<string>) => resolve(r.data.toString()))); }); } private getNonceHash(options: NonceHashOptions): Promise<string> { return new Promise((resolve): void => { const buffer_bytes: Buffer = Buffer.from(options.institute_code.toUpperCase() + options.nonce + options.username.toUpperCase(), 'utf8'); const hash: Buffer = createHmac('sha512', Buffer.from([98, 97, 83, 115, 120, 79, 119, 108, 85, 49, 106, 77])).update(buffer_bytes).digest(); return resolve(hash.toString('base64')); }); } private async returnTokens(): Promise<AccessToken> { return await this.authenticate({ username: this.username, password: this.password, institute_code: this.institute_code }).then((r: AuthenticationResponse): AccessToken => { return { access_token: r.access_token, refresh_token: r.refresh_token, token_type: r.token_type }; }).catch((): { access_token: null; refresh_token: null; token_type: null } => { return { access_token: null, refresh_token: null, token_type: null }; }); } public getAccessToken(): Promise<PreBuiltAuthenticationToken> { return new Promise(async (resolve, reject): Promise<void> => { const { access_token, refresh_token }: AccessToken = await this.returnTokens(); if (access_token === null || refresh_token === null) return reject(new KretaError('Failed to get access token: Invalid credentials')); else return resolve({ token: 'Bearer' + ' ' + access_token, access_token, refresh_token }); }); } @requireParam('options.refreshToken') @requireParam('options.refreshUserData') public getRefreshToken(options: RequestRefreshTokenOptions): Promise<AuthenticationResponse> { return new Promise(async (resolve): Promise<void> => { const nonce_key: string = await this.getNonce(); const hash: string = await this.getNonceHash({ nonce: nonce_key, institute_code: this.institute_code, username: this.username }); await tryRequest(axios.post(API.IDP + Endpoints.Token, { refresh_token: options.refreshToken, institute_code: this.institute_code, grant_type: 'refresh_token', client_id: this.client_id, refresh_user_data: options.refreshUserData }, { headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'X-Authorizationpolicy-Key': hash, 'X-Authorizationpolicy-Version': this.auth_policy_version, } }).then((r: AxiosResponse<AuthenticationResponse>) => resolve(r.data) )); }); } }
src/lib/Authentication.ts
blazsmaster-kreta.js-9274c52
[ { "filename": "src/lib/Administration.ts", "retrieved_chunk": "\tprivate token?: Promise<string>;\n\tconstructor(options: AuthenticationFields) {\n\t\tthis.username = options.username;\n\t\tthis.password = options.password;\n\t\tthis.institute_code = options.institute_code;\n\t\tthis.authenticate = new Authentication({ username: this.username, password: this.password, institute_code: this.institute_code });\n\t\tif (this.username && this.password && this.institute_code)\n\t\t\tthis.token = this.authenticate.getAccessToken().then((r: PreBuiltAuthenticationToken) => r.token);\n\t\taxios.defaults.headers['X-Uzenet-Lokalizacio'] = 'hu-HU';\n\t}", "score": 38.779710944490795 }, { "filename": "src/lib/Kreta.ts", "retrieved_chunk": "\tprivate readonly username?: string;\n\tprivate readonly password?: string;\n\tprivate readonly institute_code?: string;\n\tprivate authenticate?: Authentication;\n\tpublic Administration?: Administration;\n\tpublic Global: Global;\n\tprivate token?: Promise<string>;\n\tconstructor(options?: KretaOptions) {\n\t\tthis.username = options?.username || '';\n\t\tthis.password = options?.password || '';", "score": 36.67041617075516 }, { "filename": "src/types.ts", "retrieved_chunk": "\tGlobalMobileApiUrlTEST: string;\n\tGlobalMobileApiUrlUAT: string;\n}\nexport interface NonceHashOptions {\n\tinstitute_code: string;\n\tnonce: string;\n\tusername: string;\n}\nexport interface AuthenticationFields {\n\tinstitute_code: string;", "score": 27.621943735125384 }, { "filename": "src/lib/Kreta.ts", "retrieved_chunk": "\t\tthis.institute_code = options?.institute_code || '';\n\t\taxios.defaults.headers.common['User-Agent'] = 'hu.ekreta.student/1.0.5/Android/0/0';\n\t\tthis.Global = new Global();\n\t\tthis.authenticate = new Authentication({ username: this.username!, password: this.password!, institute_code: this.institute_code! });\n\t\tif (this.username && this.password && this.institute_code)\n\t\t\tthis.token = this.authenticate.getAccessToken().then((r: PreBuiltAuthenticationToken) => r.token);\n\t\tthis.Administration = new Administration({ username: this.username!, password: this.password!, institute_code: this.institute_code! });\n\t}\n\tpublic get _username() {\n\t\treturn this.username;", "score": 26.86194587301613 }, { "filename": "src/lib/Kreta.ts", "retrieved_chunk": "\t@requireCredentials\n\t@requireParam('options.dateFrom')\n\tpublic getHomeworks(options: RequestHomeWorkOptions): Promise<Homework[]> {\n\t\treturn new Promise(async (resolve): Promise<void> => {\n\t\t\tconst ops: { datumTol: string; datumIg?: string } = { datumTol: validateDate(moment(options.dateFrom).format('YYYY-MM-DD')) };\n\t\t\tif (options?.dateTo)\n\t\t\t\tops.datumIg = validateDate(moment(options.dateTo).format('YYYY-MM-DD'));\n\t\t\tawait tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.HaziFeladatok, ops), {\n\t\t\t\theaders: {\n\t\t\t\t\t'Authorization': await this.token,", "score": 22.829215685049977 } ]
typescript
tryRequest(axios.post(API.IDP + Endpoints.Token, {
import { AuthenticationFields, AuthenticationResponse, RequestRefreshTokenOptions, NonceHashOptions, API, Endpoints, AccessToken, PreBuiltAuthenticationToken } from '../types'; import axios, { AxiosProxyConfig, AxiosResponse } from 'axios'; import { createHmac } from 'node:crypto'; import KretaError from './errors/KretaError'; import requireParam from '../decorators/requireParam'; import tryRequest from '../utils/tryRequest'; import requireCredentials from '../decorators/requireCredentials'; export class Authentication { private readonly username: string; private readonly password: string; private readonly institute_code: string; private readonly client_id: string = 'kreta-ellenorzo-mobile-android'; private readonly grant_type: string = 'password'; private readonly auth_policy_version: string = 'v2'; constructor(options: AuthenticationFields) { this.username = options.username; this.password = options.password; this.institute_code = options.institute_code; } public get _username() { return this.username; } public get _password() { return this.password; } public get _institute_code() { return this.institute_code; } @requireParam('proxy.host') @requireParam('proxy.port') public setProxy(proxy: AxiosProxyConfig): this { axios.defaults.proxy = proxy; return this; } @requireParam('ua') public setUserAgent(ua: string): this { axios.defaults.headers.common['User-Agent'] = ua; return this; }; @requireCredentials private authenticate(options: AuthenticationFields): Promise<AuthenticationResponse> { return new Promise(async (resolve): Promise<void> => { const nonce_key: string = await this.getNonce(); const hash: string = await this.getNonceHash({ nonce: nonce_key, institute_code: options.institute_code, username: options.username }); await tryRequest(axios.post(API.IDP + Endpoints.Token, { institute_code: options.institute_code, username: options.username, password: options.password, grant_type: this.grant_type, client_id: this.client_id }, { headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'X-Authorizationpolicy-Nonce': nonce_key, 'X-Authorizationpolicy-Key': hash, 'X-Authorizationpolicy-Version': this.auth_policy_version, } }).then((r: AxiosResponse<AuthenticationResponse>) => resolve(r.data))); }); } private getNonce(): Promise<string> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(API.IDP + Endpoints.Nonce).then((r: AxiosResponse<string>) => resolve(r.data.toString()))); }); } private getNonceHash(options: NonceHashOptions): Promise<string> { return new Promise((resolve): void => { const buffer_bytes: Buffer = Buffer.from(options.institute_code.toUpperCase() + options.nonce + options.username.toUpperCase(), 'utf8'); const hash: Buffer = createHmac('sha512', Buffer.from([98, 97, 83, 115, 120, 79, 119, 108, 85, 49, 106, 77])).update(buffer_bytes).digest(); return resolve(hash.toString('base64')); }); } private async returnTokens(): Promise<AccessToken> { return await this.authenticate({ username: this.username, password: this.password, institute_code: this.institute_code }).then((r: AuthenticationResponse): AccessToken => { return { access_token: r.access_token, refresh_token: r.refresh_token, token_type: r.token_type }; }).catch((): { access_token: null; refresh_token: null; token_type: null } => { return { access_token: null, refresh_token: null, token_type: null }; }); } public getAccessToken(): Promise<PreBuiltAuthenticationToken> { return new Promise(async (resolve, reject): Promise<void> => { const { access_token, refresh_token }: AccessToken = await this.returnTokens(); if (access_token === null || refresh_token === null)
return reject(new KretaError('Failed to get access token: Invalid credentials'));
else return resolve({ token: 'Bearer' + ' ' + access_token, access_token, refresh_token }); }); } @requireParam('options.refreshToken') @requireParam('options.refreshUserData') public getRefreshToken(options: RequestRefreshTokenOptions): Promise<AuthenticationResponse> { return new Promise(async (resolve): Promise<void> => { const nonce_key: string = await this.getNonce(); const hash: string = await this.getNonceHash({ nonce: nonce_key, institute_code: this.institute_code, username: this.username }); await tryRequest(axios.post(API.IDP + Endpoints.Token, { refresh_token: options.refreshToken, institute_code: this.institute_code, grant_type: 'refresh_token', client_id: this.client_id, refresh_user_data: options.refreshUserData }, { headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'X-Authorizationpolicy-Key': hash, 'X-Authorizationpolicy-Version': this.auth_policy_version, } }).then((r: AxiosResponse<AuthenticationResponse>) => resolve(r.data) )); }); } }
src/lib/Authentication.ts
blazsmaster-kreta.js-9274c52
[ { "filename": "src/types.ts", "retrieved_chunk": "\ttoken_type: string;\n}\nexport interface PreBuiltAuthenticationToken {\n\ttoken: string;\n\taccess_token: string;\n\trefresh_token: string;\n}\ninterface ResponseErrorItem {\n\tPropertyName: string;\n\tMessage: string;", "score": 76.37510460295982 }, { "filename": "src/types.ts", "retrieved_chunk": "\ttoken_type: string | null;\n}\nexport interface KretaOptions extends AuthenticationFields {\n}\nexport interface AuthenticationResponse {\n\taccess_token: string;\n\texpires_in: number;\n\tid_token: string | null;\n\trefresh_token: string;\n\tscope: string;", "score": 72.83698150393009 }, { "filename": "src/types.ts", "retrieved_chunk": "\tpassword: string;\n\tusername: string;\n}\nexport interface RequestRefreshTokenOptions {\n\trefreshUserData: boolean;\n\trefreshToken: string;\n}\nexport interface AccessToken {\n\taccess_token: string | null;\n\trefresh_token: string | null;", "score": 62.3066035606862 }, { "filename": "src/decorators/requireParam.ts", "retrieved_chunk": "\t\t\t\t\tif (value.length === 0)\n\t\t\t\t\t\tthrow new KretaError(`'${param}' must not be an empty array`);\n\t\t\t\t} else {\n\t\t\t\t\tconst [objName, propName]: string[] = param.split('.');\n\t\t\t\t\tif (propName != null && value[propName] == null)\n\t\t\t\t\t\tthrow new KretaError(`'${propName}' is a required property in '${objName}'`);\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn originalMethod.apply(this, args);\n\t\t};", "score": 16.031854997275417 }, { "filename": "src/lib/Kreta.ts", "retrieved_chunk": "\t\t\t\t\t'Authorization': await this.token,\n\t\t\t\t}\n\t\t\t}).then((r: AxiosResponse<Homework>) => resolve(r.data)));\n\t\t});\n\t}\n\t@requireCredentials\n\tpublic getOmissions(options?: RequestDateRangeOptions): Promise<Omission[]> {\n\t\treturn new Promise(async (resolve): Promise<void> => {\n\t\t\tconst ops: { datumTol?: string; datumIg?: string } = {};\n\t\t\tif (options?.dateFrom)", "score": 15.540811849766746 } ]
typescript
return reject(new KretaError('Failed to get access token: Invalid credentials'));
import { sign } from 'jsonwebtoken'; import { IUser } from '../types'; import { Request, Response } from 'express'; import User from '../model'; import { AppError } from '../../../utils/appError'; import { catchAsync } from '../../../utils/catchAsync'; import redisService from '../../../utils/redis'; const accessToken = (user: { _id: string; name: string; email: string; role: string }) => { return sign( { id: user._id, name: user.name, email: user.email, type: process.env.JWT_ACCESS, role: user.role }, process.env.JWT_KEY_SECRET as string, { subject: user.email, expiresIn: process.env.JWT_EXPIRES_IN, audience: process.env.JWT_AUDIENCE, issuer: process.env.JWT_ISSUER, }, ); }; const refreshToken = (user: { _id: string; name: string; email: string; role: string }) => { return sign( { id: user._id, name: user.name, email: user.email, type: process.env.JWT_REFRESH, role: user.role }, process.env.JWT_KEY_REFRESH as string, { subject: user.email, expiresIn: process.env.JWT_EXPIRES_IN, audience: process.env.JWT_AUDIENCE, issuer: process.env.JWT_ISSUER, }, ); }; const createSendToken = (user: IUser, statusCode: number, req: Request, res: Response) => { const acess = accessToken(user); const refresh = refreshToken(user); // Remove password from output // eslint-disable-next-line @typescript-eslint/no-unused-vars const { name, email, role, ...otherUserData } = user; res.status(statusCode).json({ status: 'success', acess, refresh, data: { name, email, role, }, }); }; export const signup = catchAsync(async (req, res) => { const newUser = await User.create({ name: req.body.name, email: req.body.email, password: req.body.password, }); createSendToken(newUser, 201, req, res); }); export const login = catchAsync(async (req, res, next) => { const { email, password } = req.body; // 1) Check if email and password exist if (!email || !password) { return next(new AppError('Please provide email and password!', 400)); } // 2) Check if user exists && password is correct const user: any = await User.findOne({ email }).select('+password'); if (!user || !(await user.correctPassword(password, user.password))) { return next(new AppError('Incorrect email or password', 401)); } // 3) If everything ok, send token to client createSendToken(user, 200, req, res); }); export const getMe = catchAsync(async (req, res) => { const user = req.user; // 3) If everything ok, send token to client res.status(200).json({ message: 'user sucessfully fetched!', user }); }); export function logout(req: Request, res: Response) { res.cookie('jwt', 'loggedout', { expires: new Date(Date.now() + 10 * 1000), httpOnly: true, }); res.status(200).json({ status: 'success' }); } export async function refresh(req: Request, res: Response) { const user: any = req.user; await redisService.set({ key: user?.token, value: '1', timeType: 'EX', time: parseInt(process.env.JWT_REFRESH_TIME || '', 10), }); const refresh = refreshToken(user); return res.status(200).json({ status: 'sucess', refresh }); } export async function fetchUsers(req: Request, res: Response) { const body = req.body; console.log({ body }); try {
const users = await User.find();
return res.status(200).json({ message: 'sucessfully fetch users', data: users }); } catch (error: any) { new AppError(error.message, 201); } } export async function deleteUser(req: Request, res: Response) { const id = req.params.id; try { await User.deleteOne({ _id: id }); return res.status(200).json({ message: 'sucessfully deleted users' }); } catch (error: any) { new AppError(error.message, 201); } }
src/modules/auth/service/index.ts
walosha-BACKEND_DEV_TESTS-db2fcb4
[ { "filename": "src/middleware/refresh.ts", "retrieved_chunk": "import jwt, { JwtPayload } from 'jsonwebtoken';\nimport redisService from '../utils/redis';\nimport { AppError } from '../utils/appError';\nimport { NextFunction, Request, Response } from 'express';\nexport const refreshMiddleware: any = async (req: Request, res: Response, next: NextFunction) => {\n if (req.body?.refresh) {\n const token = req.body.refresh;\n try {\n const decoded: any = jwt.verify(token, process.env.JWT_KEY_REFRESH as string) as JwtPayload;\n if (", "score": 36.501605275661895 }, { "filename": "src/modules/account/service/index.ts", "retrieved_chunk": "import { Request, Response } from 'express';\nimport Account from '../model';\nexport const transferFund = async (req: Request, res: Response) => {\n const { fromAccountId, toAccountId, amount } = req.body;\n try {\n let srcAccount: any = await Account.findById(fromAccountId);\n let destAccount: any = await Account.findById(toAccountId);\n if (String(srcAccount.user) == String(destAccount.user)) {\n return res.status(400).json({\n error: 'Cannot transfer to own acccount',", "score": 31.751399988249695 }, { "filename": "src/middleware/error.ts", "retrieved_chunk": " return res.status(err.statusCode).render('error', {\n title: 'Something went wrong!',\n msg: 'Please try again later.',\n });\n};\nfunction globalErrorHandler(err: any, req: Request, res: Response, next: NextFunction) {\n // console.log(err.stack);\n err.statusCode = err.statusCode || 500;\n err.status = err.status || 'error';\n if (process.env.NODE_ENV === undefined) {", "score": 26.939766393169045 }, { "filename": "src/middleware/error.ts", "retrieved_chunk": " return res.status(err.statusCode).json({\n status: err.status,\n error: err,\n message: err.message,\n stack: err.stack,\n });\n};\nconst sendErrorProd = (err: any, req: Request, res: Response) => {\n // A) API\n if (req.originalUrl.startsWith('/api')) {", "score": 24.39928789804752 }, { "filename": "src/middleware/isLoggedIn.ts", "retrieved_chunk": "/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { NextFunction, Request, Response } from 'express';\nimport jwt from 'jsonwebtoken';\nimport User from '../modules/auth/model';\n// Only for rendered pages, no errors!\nexport async function isLoggedIn(req: Request, res: Response, next: NextFunction) {\n if (req.cookies.jwt) {\n try {\n // 1) verify token\n const decoded: any = await jwt.verify(req.cookies.jwt, process.env.JWT_KEY_SECRET as string);", "score": 21.697814532970682 } ]
typescript
const users = await User.find();
import { sign } from 'jsonwebtoken'; import { IUser } from '../types'; import { Request, Response } from 'express'; import User from '../model'; import { AppError } from '../../../utils/appError'; import { catchAsync } from '../../../utils/catchAsync'; import redisService from '../../../utils/redis'; const accessToken = (user: { _id: string; name: string; email: string; role: string }) => { return sign( { id: user._id, name: user.name, email: user.email, type: process.env.JWT_ACCESS, role: user.role }, process.env.JWT_KEY_SECRET as string, { subject: user.email, expiresIn: process.env.JWT_EXPIRES_IN, audience: process.env.JWT_AUDIENCE, issuer: process.env.JWT_ISSUER, }, ); }; const refreshToken = (user: { _id: string; name: string; email: string; role: string }) => { return sign( { id: user._id, name: user.name, email: user.email, type: process.env.JWT_REFRESH, role: user.role }, process.env.JWT_KEY_REFRESH as string, { subject: user.email, expiresIn: process.env.JWT_EXPIRES_IN, audience: process.env.JWT_AUDIENCE, issuer: process.env.JWT_ISSUER, }, ); }; const createSendToken = (user: IUser, statusCode: number, req: Request, res: Response) => { const acess = accessToken(user); const refresh = refreshToken(user); // Remove password from output // eslint-disable-next-line @typescript-eslint/no-unused-vars const { name, email, role, ...otherUserData } = user; res.status(statusCode).json({ status: 'success', acess, refresh, data: { name, email, role, }, }); }; export const signup = catchAsync(async (req, res) => { const newUser = await User.create({ name: req.body.name, email: req.body.email, password: req.body.password, }); createSendToken(newUser, 201, req, res); }); export const login = catchAsync(async (req, res, next) => { const { email, password } = req.body; // 1) Check if email and password exist if (!email || !password) { return next(new AppError('Please provide email and password!', 400)); } // 2) Check if user exists && password is correct const user: any = await User.findOne({ email }).select('+password'); if (!user || !(await user.correctPassword(password, user.password))) { return next(new AppError('Incorrect email or password', 401)); } // 3) If everything ok, send token to client createSendToken(user, 200, req, res); }); export const getMe = catchAsync(async (req, res) => { const user = req.user; // 3) If everything ok, send token to client res.status(200).json({ message: 'user sucessfully fetched!', user }); }); export function logout(req: Request, res: Response) { res.cookie('jwt', 'loggedout', { expires: new Date(Date.now() + 10 * 1000), httpOnly: true, }); res.status(200).json({ status: 'success' }); } export async function refresh(req: Request, res: Response) { const user: any = req.user; await redisService.set({ key: user?.token, value: '1', timeType: 'EX', time: parseInt(process.env.JWT_REFRESH_TIME || '', 10), }); const refresh = refreshToken(user); return res.status(200).json({ status: 'sucess', refresh }); } export async function fetchUsers(req: Request, res: Response) { const body = req.body; console.log({ body }); try { const users = await User.find(); return res.status(200).json({ message: 'sucessfully fetch users', data: users }); } catch (error: any) { new AppError(error.message, 201); } } export async function deleteUser(req: Request, res: Response) { const id = req.params.id; try { await
User.deleteOne({ _id: id });
return res.status(200).json({ message: 'sucessfully deleted users' }); } catch (error: any) { new AppError(error.message, 201); } }
src/modules/auth/service/index.ts
walosha-BACKEND_DEV_TESTS-db2fcb4
[ { "filename": "src/middleware/error.ts", "retrieved_chunk": " return res.status(err.statusCode).json({\n status: err.status,\n error: err,\n message: err.message,\n stack: err.stack,\n });\n};\nconst sendErrorProd = (err: any, req: Request, res: Response) => {\n // A) API\n if (req.originalUrl.startsWith('/api')) {", "score": 30.07496655782791 }, { "filename": "src/modules/account/service/index.ts", "retrieved_chunk": "import { Request, Response } from 'express';\nimport Account from '../model';\nexport const transferFund = async (req: Request, res: Response) => {\n const { fromAccountId, toAccountId, amount } = req.body;\n try {\n let srcAccount: any = await Account.findById(fromAccountId);\n let destAccount: any = await Account.findById(toAccountId);\n if (String(srcAccount.user) == String(destAccount.user)) {\n return res.status(400).json({\n error: 'Cannot transfer to own acccount',", "score": 25.528875664163003 }, { "filename": "src/middleware/error.ts", "retrieved_chunk": " return res.status(err.statusCode).render('error', {\n title: 'Something went wrong!',\n msg: 'Please try again later.',\n });\n};\nfunction globalErrorHandler(err: any, req: Request, res: Response, next: NextFunction) {\n // console.log(err.stack);\n err.statusCode = err.statusCode || 500;\n err.status = err.status || 'error';\n if (process.env.NODE_ENV === undefined) {", "score": 23.73605783382498 }, { "filename": "src/utils/catchAsync.ts", "retrieved_chunk": "import { NextFunction, Request, Response } from 'express';\ntype AsyncFunction = (req: Request, res: Response, next: NextFunction) => Promise<any>;\nexport const catchAsync = (fn: AsyncFunction) => {\n return (req: Request, res: Response, next: NextFunction) => {\n fn(req, res, next).catch(next);\n };\n};", "score": 22.830528995165494 }, { "filename": "src/middleware/error.ts", "retrieved_chunk": "};\nconst handleValidationErrorDB = (err: any) => {\n const errors = Object.values(err.errors).map((el: any) => el.message);\n const message = `Invalid input data. ${errors.join('. ')}`;\n return new AppError(message, 400);\n};\nconst handleJWTError = () => new AppError('Invalid token. Please log in again!', 401);\nconst handleJWTExpiredError = () => new AppError('Your token has expired! Please log in again.', 401);\nconst sendErrorDev = (err: any, req: Request, res: Response) => {\n // A) API", "score": 22.340447200120522 } ]
typescript
User.deleteOne({ _id: id });
import axios, { AxiosProxyConfig, AxiosResponse } from 'axios'; import moment from 'moment'; import { AnnouncedTest, ClassAverage, ClassMaster, ConfigurationDescriptor, Evaluation, Group, Homework, Institute, Institution, KretaOptions, LepEvent, Lesson, Note, NoticeBoardItem, Omission, PreBuiltAuthenticationToken, RequestAnnouncedTestsOptions, RequestClassAveragesOptions, RequestDateRangeOptions, RequestDateRangeRequiredOptions, RequestHomeWorkOptions, SchoolYearCalendarEntry, Student, SubjectAverage, TimeTableWeek, API, Endpoints } from '../types'; import { Authentication } from './Authentication'; import dynamicValue from '../utils/dynamicValue'; import Administration from './Administration'; import Global from './Global'; import requireCredentials from '../decorators/requireCredentials'; import tryRequest from '../utils/tryRequest'; import validateDate from '../utils/validateDate'; import requireParam from '../decorators/requireParam'; export default class Kreta { private readonly username?: string; private readonly password?: string; private readonly institute_code?: string; private authenticate?: Authentication; public Administration?: Administration; public Global: Global; private token?: Promise<string>; constructor(options?: KretaOptions) { this.username = options?.username || ''; this.password = options?.password || ''; this.institute_code = options?.institute_code || ''; axios.defaults.headers.common['User-Agent'] = 'hu.ekreta.student/1.0.5/Android/0/0'; this.Global = new Global(); this.authenticate = new Authentication({ username: this.username!, password: this.password!, institute_code: this.institute_code! }); if (this.username && this.password && this.institute_code) this.token = this.authenticate.getAccessToken().then((r: PreBuiltAuthenticationToken) => r.token); this.Administration = new
Administration({ username: this.username!, password: this.password!, institute_code: this.institute_code! });
} public get _username() { return this.username; } public get _password() { return this.password; } public get _institute_code() { return this.institute_code; } @requireParam('proxy.host') @requireParam('proxy.port') public setProxy(proxy: AxiosProxyConfig): this { axios.defaults.proxy = proxy; return this; } @requireParam('ua') public setUserAgent(ua: string): this { axios.defaults.headers.common['User-Agent'] = ua; return this; } private buildEllenorzoApiURL(endpointWithSlash: Endpoints, params?: { [key: string]: any }): string { const urlParams: string = params ? '?' + new URLSearchParams(params).toString() : ''; return dynamicValue(API.INSTITUTE, { institute_code: this.institute_code }).toString() + '/ellenorzo/V3' + endpointWithSlash + urlParams; } @requireParam('api_key') public getInstituteList(api_key: string): Promise<Institute[]> { return new Promise(async (resolve): Promise<void> => { const config_descriptor: AxiosResponse<ConfigurationDescriptor> = await axios.get('https://kretamobile.blob.core.windows.net/configuration/ConfigurationDescriptor.json'); await tryRequest(axios.get(config_descriptor.data.GlobalMobileApiUrlPROD + '/api/v3/Institute', { headers: { apiKey: api_key } }).then((r: AxiosResponse<Institute[]>) => resolve(r.data))); }); } @requireCredentials public getStudent(): Promise<Student> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.Tanulo), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Student>) => resolve(r.data))); }); } @requireCredentials public getEvaluations(options?: RequestDateRangeOptions): Promise<Evaluation[]> { return new Promise(async (resolve): Promise<void> => { const ops: { datumTol?: string; datumIg?: string } = {}; if (options?.dateFrom) ops.datumTol = validateDate(moment(options.dateFrom).format('YYYY-MM-DD')); if (options?.dateTo) ops.datumIg = validateDate(moment(options.dateTo).format('YYYY-MM-DD')); await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.Ertekelesek, ops), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Evaluation[]>) => resolve(r.data))); }); } @requireCredentials public getNotes(options?: RequestDateRangeOptions): Promise<Note[]> { return new Promise(async (resolve): Promise<void> => { const ops: { datumTol?: string; datumIg?: string } = {}; if (options?.dateFrom) ops.datumTol = validateDate(moment(options.dateFrom).format('YYYY-MM-DD')); if (options?.dateTo) ops.datumIg = validateDate(moment(options.dateTo).format('YYYY-MM-DD')); await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.Feljegyzesek, ops), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Note[]>) => resolve(r.data))); }); } @requireCredentials public getAnnouncedTests(options?: RequestAnnouncedTestsOptions): Promise<AnnouncedTest[]> { return new Promise(async (resolve): Promise<void> => { const ops: { datumTol?: string; datumIg?: string, Uids?: string } = {}; if (options?.dateFrom) ops.datumTol = validateDate(moment(options.dateFrom).format('YYYY-MM-DD')); if (options?.dateTo) ops.datumIg = validateDate(moment(options.dateTo).format('YYYY-MM-DD')); if (options?.uids) ops.Uids = options.uids.map((uid: string | number) => uid.toString()).join(';'); await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.Szamonkeresek, ops), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<AnnouncedTest[]>) => resolve(r.data))); }); } @requireCredentials @requireParam('options.dateFrom') public getHomeworks(options: RequestHomeWorkOptions): Promise<Homework[]> { return new Promise(async (resolve): Promise<void> => { const ops: { datumTol: string; datumIg?: string } = { datumTol: validateDate(moment(options.dateFrom).format('YYYY-MM-DD')) }; if (options?.dateTo) ops.datumIg = validateDate(moment(options.dateTo).format('YYYY-MM-DD')); await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.HaziFeladatok, ops), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Homework[]>) => resolve(r.data))); }); } @requireCredentials @requireParam('uid') public getHomework(uid: string | number): Promise<Homework> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.HaziFeladatok) + '/' + uid.toString(), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Homework>) => resolve(r.data))); }); } @requireCredentials public getOmissions(options?: RequestDateRangeOptions): Promise<Omission[]> { return new Promise(async (resolve): Promise<void> => { const ops: { datumTol?: string; datumIg?: string } = {}; if (options?.dateFrom) ops.datumTol = validateDate(moment(options.dateFrom).format('YYYY-MM-DD')); if (options?.dateTo) ops.datumIg = validateDate(moment(options.dateTo).format('YYYY-MM-DD')); await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.Mulasztasok, ops), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Omission[]>) => resolve(r.data))); }); } @requireCredentials public getGroups(): Promise<Group[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.OsztalyCsoportok), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Group[]>) => resolve(r.data))); }); } @requireCredentials public getSubjectAverages(onfUid?: string): Promise<SubjectAverage[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.TantargyiAtlagok, { oktatasiNevelesiFeladatUid: onfUid || await this.getGroups().then((groups: Group[]) => groups[0].OktatasNevelesiFeladat.Uid) }), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<SubjectAverage[]>) => resolve(r.data))); }); } @requireCredentials @requireParam('options.dateFrom') @requireParam('options.dateTo') public getLessons(options: RequestDateRangeRequiredOptions): Promise<Lesson[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.OrarendElemek, { datumTol: validateDate(moment(options.dateFrom).format('YYYY-MM-DD')), datumIg: validateDate(moment(options.dateTo).format('YYYY-MM-DD')) }), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Lesson[]>) => resolve(r.data))); }); } @requireCredentials @requireParam('uid') public getLesson(uid: string | number): Promise<Lesson> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.OrarendElem, { orarendElemUid: uid.toString() }), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Lesson>) => resolve(r.data))); }); } @requireCredentials public getNoticeBoardItems(): Promise<NoticeBoardItem[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.FaliujsagElemek), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<NoticeBoardItem[]>) => resolve(r.data))); }); } @requireCredentials public getClassAverage(options?: RequestClassAveragesOptions): Promise<ClassAverage[]> { return new Promise(async (resolve): Promise<void> => { const ops: { oktatasiNevelesiFeladatUid: string; tantargyUid?: string; } = { oktatasiNevelesiFeladatUid: options?.oktatasiNevelesiFeladatUid || await this.getGroups().then((groups: Group[]) => groups[0].OktatasNevelesiFeladat.Uid) }; if (options?.subjectUid) ops.tantargyUid = options.subjectUid; await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.OsztalyCsoportAtlag, ops), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<ClassAverage[]>) => resolve(r.data))); }); } @requireCredentials public getInstitute(): Promise<Institution> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.Intezmenyek), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Institution>) => resolve(r.data))); }); } @requireCredentials @requireParam('uids') public getClassMasters(uids: string[] | number[]): Promise<ClassMaster[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.Osztalyfonokok, { Uids: uids.map((u: string | number) => u.toString()).join(';') }), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<ClassMaster[]>) => resolve(r.data))); }); } @requireCredentials @requireParam('options.dateFrom') @requireParam('options.dateTo') public getTimeTableWeeks(options: RequestDateRangeRequiredOptions): Promise<TimeTableWeek[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.OrarendHetek, { orarendElemKezdoNapDatuma: validateDate(moment(options.dateFrom).format('YYYY-MM-DD')), orarendElemVegNapDatuma: validateDate(moment(options.dateTo).format('YYYY-MM-DD')) }), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<TimeTableWeek[]>) => resolve(r.data))); }); } @requireCredentials public getLepEvents(): Promise<LepEvent[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.Eloadasok), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<LepEvent[]>) => resolve(r.data))); }); } @requireCredentials public getSchoolYearCalendar(): Promise<SchoolYearCalendarEntry[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.TanevNaptar), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<SchoolYearCalendarEntry[]>) => resolve(r.data))); }); } @requireCredentials public getDeviceGivenState(): Promise<boolean> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.EszkozAllapot), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<boolean>) => resolve(r.data))); }); } }
src/lib/Kreta.ts
blazsmaster-kreta.js-9274c52
[ { "filename": "src/lib/Administration.ts", "retrieved_chunk": "\tprivate token?: Promise<string>;\n\tconstructor(options: AuthenticationFields) {\n\t\tthis.username = options.username;\n\t\tthis.password = options.password;\n\t\tthis.institute_code = options.institute_code;\n\t\tthis.authenticate = new Authentication({ username: this.username, password: this.password, institute_code: this.institute_code });\n\t\tif (this.username && this.password && this.institute_code)\n\t\t\tthis.token = this.authenticate.getAccessToken().then((r: PreBuiltAuthenticationToken) => r.token);\n\t\taxios.defaults.headers['X-Uzenet-Lokalizacio'] = 'hu-HU';\n\t}", "score": 138.91523943286427 }, { "filename": "src/lib/Authentication.ts", "retrieved_chunk": "\t\t\tconst hash: string = await this.getNonceHash({\n\t\t\t\tnonce: nonce_key,\n\t\t\t\tinstitute_code: options.institute_code,\n\t\t\t\tusername: options.username\n\t\t\t});\n\t\t\tawait tryRequest(axios.post(API.IDP + Endpoints.Token, {\n\t\t\t\tinstitute_code: options.institute_code,\n\t\t\t\tusername: options.username,\n\t\t\t\tpassword: options.password,\n\t\t\t\tgrant_type: this.grant_type,", "score": 102.71231365484755 }, { "filename": "src/lib/Authentication.ts", "retrieved_chunk": "\tprivate readonly auth_policy_version: string = 'v2';\n\tconstructor(options: AuthenticationFields) {\n\t\tthis.username = options.username;\n\t\tthis.password = options.password;\n\t\tthis.institute_code = options.institute_code;\n\t}\n\tpublic get _username() {\n\t\treturn this.username;\n\t}\n\tpublic get _password() {", "score": 102.42452603157352 }, { "filename": "src/lib/Authentication.ts", "retrieved_chunk": "\t\t\treturn resolve(hash.toString('base64'));\n\t\t});\n\t}\n\tprivate async returnTokens(): Promise<AccessToken> {\n\t\treturn await this.authenticate({\n\t\t\tusername: this.username,\n\t\t\tpassword: this.password,\n\t\t\tinstitute_code: this.institute_code\n\t\t}).then((r: AuthenticationResponse): AccessToken => {\n\t\t\treturn { access_token: r.access_token, refresh_token: r.refresh_token, token_type: r.token_type };", "score": 89.03846191125878 }, { "filename": "src/lib/Authentication.ts", "retrieved_chunk": "\t\t\t\tinstitute_code: this.institute_code,\n\t\t\t\tusername: this.username\n\t\t\t});\n\t\t\tawait tryRequest(axios.post(API.IDP + Endpoints.Token, {\n\t\t\t\trefresh_token: options.refreshToken,\n\t\t\t\tinstitute_code: this.institute_code,\n\t\t\t\tgrant_type: 'refresh_token',\n\t\t\t\tclient_id: this.client_id,\n\t\t\t\trefresh_user_data: options.refreshUserData\n\t\t\t}, {", "score": 80.32933671720959 } ]
typescript
Administration({ username: this.username!, password: this.password!, institute_code: this.institute_code! });
import axios, { AxiosProxyConfig, AxiosResponse } from 'axios'; import moment from 'moment'; import { AnnouncedTest, ClassAverage, ClassMaster, ConfigurationDescriptor, Evaluation, Group, Homework, Institute, Institution, KretaOptions, LepEvent, Lesson, Note, NoticeBoardItem, Omission, PreBuiltAuthenticationToken, RequestAnnouncedTestsOptions, RequestClassAveragesOptions, RequestDateRangeOptions, RequestDateRangeRequiredOptions, RequestHomeWorkOptions, SchoolYearCalendarEntry, Student, SubjectAverage, TimeTableWeek, API, Endpoints } from '../types'; import { Authentication } from './Authentication'; import dynamicValue from '../utils/dynamicValue'; import Administration from './Administration'; import Global from './Global'; import requireCredentials from '../decorators/requireCredentials'; import tryRequest from '../utils/tryRequest'; import validateDate from '../utils/validateDate'; import requireParam from '../decorators/requireParam'; export default class Kreta { private readonly username?: string; private readonly password?: string; private readonly institute_code?: string; private authenticate?: Authentication; public Administration?: Administration; public Global: Global; private token?: Promise<string>; constructor(options?: KretaOptions) { this.username = options?.username || ''; this.password = options?.password || ''; this.institute_code = options?.institute_code || ''; axios.defaults.headers.common['User-Agent'] = 'hu.ekreta.student/1.0.5/Android/0/0'; this.Global = new Global(); this.authenticate = new Authentication({ username: this.username!, password: this.password!, institute_code: this.institute_code! }); if (this.username && this.password && this.institute_code) this.token = this.authenticate.getAccessToken().then((r: PreBuiltAuthenticationToken) => r.token); this.Administration = new Administration({ username: this.username!, password: this.password!, institute_code: this.institute_code! }); } public get _username() { return this.username; } public get _password() { return this.password; } public get _institute_code() { return this.institute_code; } @requireParam('proxy.host') @requireParam('proxy.port') public setProxy(proxy: AxiosProxyConfig): this { axios.defaults.proxy = proxy; return this; } @requireParam('ua') public setUserAgent(ua: string): this { axios.defaults.headers.common['User-Agent'] = ua; return this; } private buildEllenorzoApiURL(endpointWithSlash: Endpoints, params?: { [key: string]: any }): string { const urlParams: string = params ? '?' + new URLSearchParams(params).toString() : '';
return dynamicValue(API.INSTITUTE, { institute_code: this.institute_code }).toString() + '/ellenorzo/V3' + endpointWithSlash + urlParams;
} @requireParam('api_key') public getInstituteList(api_key: string): Promise<Institute[]> { return new Promise(async (resolve): Promise<void> => { const config_descriptor: AxiosResponse<ConfigurationDescriptor> = await axios.get('https://kretamobile.blob.core.windows.net/configuration/ConfigurationDescriptor.json'); await tryRequest(axios.get(config_descriptor.data.GlobalMobileApiUrlPROD + '/api/v3/Institute', { headers: { apiKey: api_key } }).then((r: AxiosResponse<Institute[]>) => resolve(r.data))); }); } @requireCredentials public getStudent(): Promise<Student> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.Tanulo), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Student>) => resolve(r.data))); }); } @requireCredentials public getEvaluations(options?: RequestDateRangeOptions): Promise<Evaluation[]> { return new Promise(async (resolve): Promise<void> => { const ops: { datumTol?: string; datumIg?: string } = {}; if (options?.dateFrom) ops.datumTol = validateDate(moment(options.dateFrom).format('YYYY-MM-DD')); if (options?.dateTo) ops.datumIg = validateDate(moment(options.dateTo).format('YYYY-MM-DD')); await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.Ertekelesek, ops), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Evaluation[]>) => resolve(r.data))); }); } @requireCredentials public getNotes(options?: RequestDateRangeOptions): Promise<Note[]> { return new Promise(async (resolve): Promise<void> => { const ops: { datumTol?: string; datumIg?: string } = {}; if (options?.dateFrom) ops.datumTol = validateDate(moment(options.dateFrom).format('YYYY-MM-DD')); if (options?.dateTo) ops.datumIg = validateDate(moment(options.dateTo).format('YYYY-MM-DD')); await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.Feljegyzesek, ops), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Note[]>) => resolve(r.data))); }); } @requireCredentials public getAnnouncedTests(options?: RequestAnnouncedTestsOptions): Promise<AnnouncedTest[]> { return new Promise(async (resolve): Promise<void> => { const ops: { datumTol?: string; datumIg?: string, Uids?: string } = {}; if (options?.dateFrom) ops.datumTol = validateDate(moment(options.dateFrom).format('YYYY-MM-DD')); if (options?.dateTo) ops.datumIg = validateDate(moment(options.dateTo).format('YYYY-MM-DD')); if (options?.uids) ops.Uids = options.uids.map((uid: string | number) => uid.toString()).join(';'); await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.Szamonkeresek, ops), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<AnnouncedTest[]>) => resolve(r.data))); }); } @requireCredentials @requireParam('options.dateFrom') public getHomeworks(options: RequestHomeWorkOptions): Promise<Homework[]> { return new Promise(async (resolve): Promise<void> => { const ops: { datumTol: string; datumIg?: string } = { datumTol: validateDate(moment(options.dateFrom).format('YYYY-MM-DD')) }; if (options?.dateTo) ops.datumIg = validateDate(moment(options.dateTo).format('YYYY-MM-DD')); await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.HaziFeladatok, ops), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Homework[]>) => resolve(r.data))); }); } @requireCredentials @requireParam('uid') public getHomework(uid: string | number): Promise<Homework> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.HaziFeladatok) + '/' + uid.toString(), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Homework>) => resolve(r.data))); }); } @requireCredentials public getOmissions(options?: RequestDateRangeOptions): Promise<Omission[]> { return new Promise(async (resolve): Promise<void> => { const ops: { datumTol?: string; datumIg?: string } = {}; if (options?.dateFrom) ops.datumTol = validateDate(moment(options.dateFrom).format('YYYY-MM-DD')); if (options?.dateTo) ops.datumIg = validateDate(moment(options.dateTo).format('YYYY-MM-DD')); await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.Mulasztasok, ops), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Omission[]>) => resolve(r.data))); }); } @requireCredentials public getGroups(): Promise<Group[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.OsztalyCsoportok), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Group[]>) => resolve(r.data))); }); } @requireCredentials public getSubjectAverages(onfUid?: string): Promise<SubjectAverage[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.TantargyiAtlagok, { oktatasiNevelesiFeladatUid: onfUid || await this.getGroups().then((groups: Group[]) => groups[0].OktatasNevelesiFeladat.Uid) }), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<SubjectAverage[]>) => resolve(r.data))); }); } @requireCredentials @requireParam('options.dateFrom') @requireParam('options.dateTo') public getLessons(options: RequestDateRangeRequiredOptions): Promise<Lesson[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.OrarendElemek, { datumTol: validateDate(moment(options.dateFrom).format('YYYY-MM-DD')), datumIg: validateDate(moment(options.dateTo).format('YYYY-MM-DD')) }), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Lesson[]>) => resolve(r.data))); }); } @requireCredentials @requireParam('uid') public getLesson(uid: string | number): Promise<Lesson> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.OrarendElem, { orarendElemUid: uid.toString() }), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Lesson>) => resolve(r.data))); }); } @requireCredentials public getNoticeBoardItems(): Promise<NoticeBoardItem[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.FaliujsagElemek), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<NoticeBoardItem[]>) => resolve(r.data))); }); } @requireCredentials public getClassAverage(options?: RequestClassAveragesOptions): Promise<ClassAverage[]> { return new Promise(async (resolve): Promise<void> => { const ops: { oktatasiNevelesiFeladatUid: string; tantargyUid?: string; } = { oktatasiNevelesiFeladatUid: options?.oktatasiNevelesiFeladatUid || await this.getGroups().then((groups: Group[]) => groups[0].OktatasNevelesiFeladat.Uid) }; if (options?.subjectUid) ops.tantargyUid = options.subjectUid; await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.OsztalyCsoportAtlag, ops), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<ClassAverage[]>) => resolve(r.data))); }); } @requireCredentials public getInstitute(): Promise<Institution> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.Intezmenyek), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Institution>) => resolve(r.data))); }); } @requireCredentials @requireParam('uids') public getClassMasters(uids: string[] | number[]): Promise<ClassMaster[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.Osztalyfonokok, { Uids: uids.map((u: string | number) => u.toString()).join(';') }), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<ClassMaster[]>) => resolve(r.data))); }); } @requireCredentials @requireParam('options.dateFrom') @requireParam('options.dateTo') public getTimeTableWeeks(options: RequestDateRangeRequiredOptions): Promise<TimeTableWeek[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.OrarendHetek, { orarendElemKezdoNapDatuma: validateDate(moment(options.dateFrom).format('YYYY-MM-DD')), orarendElemVegNapDatuma: validateDate(moment(options.dateTo).format('YYYY-MM-DD')) }), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<TimeTableWeek[]>) => resolve(r.data))); }); } @requireCredentials public getLepEvents(): Promise<LepEvent[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.Eloadasok), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<LepEvent[]>) => resolve(r.data))); }); } @requireCredentials public getSchoolYearCalendar(): Promise<SchoolYearCalendarEntry[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.TanevNaptar), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<SchoolYearCalendarEntry[]>) => resolve(r.data))); }); } @requireCredentials public getDeviceGivenState(): Promise<boolean> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.EszkozAllapot), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<boolean>) => resolve(r.data))); }); } }
src/lib/Kreta.ts
blazsmaster-kreta.js-9274c52
[ { "filename": "src/lib/Authentication.ts", "retrieved_chunk": "\t}\n\t@requireParam('ua')\n\tpublic setUserAgent(ua: string): this {\n\t\taxios.defaults.headers.common['User-Agent'] = ua;\n\t\treturn this;\n\t};\n\t@requireCredentials\n\tprivate authenticate(options: AuthenticationFields): Promise<AuthenticationResponse> {\n\t\treturn new Promise(async (resolve): Promise<void> => {\n\t\t\tconst nonce_key: string = await this.getNonce();", "score": 59.65563402804148 }, { "filename": "src/lib/Administration.ts", "retrieved_chunk": "\t\tconst urlParams: string = params ? '?' + new URLSearchParams(params).toString() : '';\n\t\treturn API.ADMINISTRATION + '/api/v1' + endpointWithSlash + urlParams;\n\t}\n\t@requireCredentials\n\tpublic getAddresseeType(): Promise<AddresseType[]> {\n\t\treturn new Promise(async (resolve): Promise<void> => {\n\t\t\tawait tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.CimzettTipusok), {\n\t\t\t\theaders: {\n\t\t\t\t\t'Authorization': await this.token\n\t\t\t\t}", "score": 56.01197015866762 }, { "filename": "src/lib/Administration.ts", "retrieved_chunk": "\tpublic get _username() {\n\t\treturn this.username;\n\t}\n\tpublic get _password() {\n\t\treturn this.password;\n\t}\n\tpublic get _institute_code() {\n\t\treturn this.institute_code;\n\t}\n\tprivate buildUgyintezesApiURL(endpointWithSlash: AdministrationEndpoints, params?: { [key: string]: any }): string {", "score": 48.01764133074271 }, { "filename": "src/utils/dynamicValue.ts", "retrieved_chunk": "export default function dynamicValue(str: string, values: { [key: string]: any }): string {\n\treturn str.replace(/{{(.*?)}}/g, (match: string, key) => values[key] || match);\n}", "score": 24.534678836679074 }, { "filename": "src/lib/Authentication.ts", "retrieved_chunk": "\t\treturn this.password;\n\t}\n\tpublic get _institute_code() {\n\t\treturn this.institute_code;\n\t}\n\t@requireParam('proxy.host')\n\t@requireParam('proxy.port')\n\tpublic setProxy(proxy: AxiosProxyConfig): this {\n\t\taxios.defaults.proxy = proxy;\n\t\treturn this;", "score": 22.52573573071812 } ]
typescript
return dynamicValue(API.INSTITUTE, { institute_code: this.institute_code }).toString() + '/ellenorzo/V3' + endpointWithSlash + urlParams;
/** * YOU PROBABLY DON'T NEED TO EDIT THIS FILE, UNLESS: * 1. You want to modify request context (see Part 1). * 2. You want to create a new middleware or type of procedure (see Part 3). * * TL;DR - This is where all the tRPC server stuff is created and plugged in. The pieces you will * need to use are documented accordingly near the end. */ /** * 1. CONTEXT * * This section defines the "contexts" that are available in the backend API. * * These allow you to access things when processing a request, like the database, the session, etc. */ import { type CreateNextContextOptions } from "@trpc/server/adapters/next"; import { type Session } from "next-auth"; import { getServerAuthSession } from "~/server/auth"; import { prisma } from "~/server/db"; type CreateContextOptions = { session: Session | null; }; /** * This helper generates the "internals" for a tRPC context. If you need to use it, you can export * it from here. * * Examples of things you may need it for: * - testing, so we don't have to mock Next.js' req/res * - tRPC's `createSSGHelpers`, where we don't have req/res * * @see https://create.t3.gg/en/usage/trpc#-servertrpccontextts */ const createInnerTRPCContext = (opts: CreateContextOptions) => { return { session: opts.session, prisma, }; }; /** * This is the actual context you will use in your router. It will be used to process every request * that goes through your tRPC endpoint. * * @see https://trpc.io/docs/context */ export const createTRPCContext = async (opts: CreateNextContextOptions) => { const { req, res } = opts; // Get the session from the server using the getServerSession wrapper function
const session = await getServerAuthSession({ req, res });
return createInnerTRPCContext({ session, }); }; /** * 2. INITIALIZATION * * This is where the tRPC API is initialized, connecting the context and transformer. We also parse * ZodErrors so that you get typesafety on the frontend if your procedure fails due to validation * errors on the backend. */ import { initTRPC, TRPCError } from "@trpc/server"; import superjson from "superjson"; import { ZodError } from "zod"; const t = initTRPC.context<typeof createTRPCContext>().create({ transformer: superjson, errorFormatter({ shape, error }) { return { ...shape, data: { ...shape.data, zodError: error.cause instanceof ZodError ? error.cause.flatten() : null, }, }; }, }); /** * 3. ROUTER & PROCEDURE (THE IMPORTANT BIT) * * These are the pieces you use to build your tRPC API. You should import these a lot in the * "/src/server/api/routers" directory. */ /** * This is how you create new routers and sub-routers in your tRPC API. * * @see https://trpc.io/docs/router */ export const createTRPCRouter = t.router; /** * Public (unauthenticated) procedure * * This is the base piece you use to build new queries and mutations on your tRPC API. It does not * guarantee that a user querying is authorized, but you can still access user session data if they * are logged in. */ export const publicProcedure = t.procedure; /** Reusable middleware that enforces users are logged in before running the procedure. */ const enforceUserIsAuthed = t.middleware(({ ctx, next }) => { if (!ctx.session || !ctx.session.user) { throw new TRPCError({ code: "UNAUTHORIZED" }); } return next({ ctx: { // infers the `session` as non-nullable session: { ...ctx.session, user: ctx.session.user }, }, }); }); /** * Protected (authenticated) procedure * * If you want a query or mutation to ONLY be accessible to logged in users, use this. It verifies * the session is valid and guarantees `ctx.session.user` is not null. * * @see https://trpc.io/docs/procedures */ export const protectedProcedure = t.procedure.use(enforceUserIsAuthed);
src/server/api/trpc.ts
cloudnothings-better-gpt-f1ad4fa
[ { "filename": "src/server/auth.ts", "retrieved_chunk": "};\n/**\n * Wrapper for `getServerSession` so that you don't need to import the `authOptions` in every file.\n *\n * @see https://next-auth.js.org/configuration/nextjs\n */\nexport const getServerAuthSession = (ctx: {\n req: GetServerSidePropsContext[\"req\"];\n res: GetServerSidePropsContext[\"res\"];\n}) => {", "score": 80.560160897194 }, { "filename": "src/utils/api.ts", "retrieved_chunk": " /**\n * Transformer used for data de-serialization from the server.\n *\n * @see https://trpc.io/docs/data-transformers\n */\n transformer: superjson,\n /**\n * Links used to determine request flow from client to server.\n *\n * @see https://trpc.io/docs/links", "score": 61.61281742302543 }, { "filename": "src/utils/api.ts", "retrieved_chunk": "/**\n * This is the client-side entrypoint for your tRPC API. It is used to create the `api` object which\n * contains the Next.js App-wrapper, as well as your type-safe React Query hooks.\n *\n * We also create a few inference helpers for input and output types.\n */\nimport { httpBatchLink, loggerLink } from \"@trpc/client\";\nimport { createTRPCNext } from \"@trpc/next\";\nimport { type inferRouterInputs, type inferRouterOutputs } from \"@trpc/server\";\nimport superjson from \"superjson\";", "score": 58.68213701967416 }, { "filename": "src/server/api/root.ts", "retrieved_chunk": "import { createTRPCRouter } from \"~/server/api/trpc\";\nimport { exampleRouter } from \"~/server/api/routers/example\";\nimport { gptRouter } from \"./routers/gpt\";\n/**\n * This is the primary router for your server.\n *\n * All routers added in /api/routers should be manually added here.\n */\nexport const appRouter = createTRPCRouter({\n example: exampleRouter,", "score": 51.843366328576 }, { "filename": "src/server/auth.ts", "retrieved_chunk": " /**\n * ...add more providers here.\n *\n * Most other providers require a bit more work than the Discord provider. For example, the\n * GitHub provider requires you to add the `refresh_token_expires_in` field to the Account\n * model. Refer to the NextAuth.js docs for the provider you want to use. Example:\n *\n * @see https://next-auth.js.org/providers/github\n */\n ],", "score": 41.13469442465805 } ]
typescript
const session = await getServerAuthSession({ req, res });
import { create } from "zustand"; import type { Model, Profile, Thread } from "~/types/appstate"; const models = [ { name: "GPT-3.5-TURBO", id: "gpt-3.5-turbo", description: "Most capable GPT-3.5 model and optimized for chat at 1/10th the cost of text-davinci-003. Will be updated with our latest model iteration.", maxTokens: 4096, usageCost: 0.002, trainingData: "Up to Sep 2021", }, { name: "GPT-3.5-TURBO-0301", id: "gpt-3.5-turbo-0301", description: "Snapshot of gpt-3.5-turbo from March 1st 2023. Unlike gpt-3.5-turbo, this model will not receive updates, and will only be supported for a three month period ending on June 1st 2023.", maxTokens: 4096, usageCost: 0.002, trainingData: "Up to Sep 2021", }, { name: "GPT-4 (Limited Beta)", id: "gpt-4", description: "More capable than any GPT-3.5 model, able to do more complex tasks, and optimized for chat. Will be updated with our latest model iteration.", maxTokens: 8192, promptCost: 0.03, completionCost: 0.06, trainingData: "Up to Sep 2021", note: "you need API Access to GPT-4 to use this model. If you haven't already, join the waitlist here: https://openai.com/waitlist/gpt-4-api", }, { name: "GPT-4-0314 (Limited Beta)", id: "gpt-4-0314", description: "Snapshot of gpt-4 from March 14th 2023. Unlike gpt-4, this model will not receive updates, and will only be supported for a three month period ending on June 14th 2023.", maxTokens: 8192, promptCost: 0.03, completionCost: 0.06, trainingData: "Up to Sep 2021", note: "you need API Access to GPT-4 to use this model. If you haven't already, join the waitlist here: https://openai.com/waitlist/gpt-4-api", }, { name: "GPT-4-32K (Limited Beta)", id: "gpt-4-32k", description: "Same capabilities as GPT-4, but with 4x the context length. Will be updated with our latest model iteration.", trainingData: "Up to Sep 2021", promptCost: 0.06, completionCost: 0.12, maxTokens: 32768, note: "you need API Access to GPT-4 to use this model. If you haven't already, join the waitlist here: https://openai.com/waitlist/gpt-4-api", }, { name: "GPT-4-32K-0314 (Limited Beta)", id: "gpt-4-32k-0314", description: "Snapshot of gpt-4-32k from March 14th 2023. Unlike gpt-4-32k, this model will not receive updates, and will only be supported for a three month period ending on June 14th 2023.", trainingData: "Up to Sep 2021", promptCost: 0.06, completionCost: 0.12, maxTokens: 32768, note: "you need API Access to GPT-4 to use this model. If you haven't already, join the waitlist here: https://openai.com/waitlist/gpt-4-api", }, ] as Model[]; const initialThread = { id: "", name: "", profileId: "", budget: 0, cost: 0, description: "", initialSystemInstruction: "", messages: [], model: models[0] as Model, starred: false, title: "", } as Thread; export const initialValues = { profile: { id: "", name: "", model: models[0] as Model, budget: 0, cost: 0, usage: { completion_tokens: 0, prompt_tokens: 0, total_tokens: 0, }, key: "", threadIds: [], organization: "", } as Profile, profiles: [] as Profile[], selectedProfile: "", thread: initialThread, threads: [] as Thread[], selectedApiKey: 0, apiKeyModal: false, apiKeyError: false, modelModal: false, models, width: 0, }; const getLocalProfileList = () => { const raw = localStorage.getItem("Profiles"); if (!raw) { return null; } return JSON.parse(raw) as string[]; }; const getSelectedProfile = () => { const raw = localStorage.getItem("SelectedProfile"); if (!raw) { return null; } return JSON.parse(raw) as string; }; export const getProfile = (id: string) => { const raw = localStorage.getItem("Profile_" + id); if (!raw) { return; } return JSON.parse(raw) as Profile; }; const loadProfiles = () => { const profileList = getLocalProfileList(); if (!profileList) { return null; } const selectedProfile = getSelectedProfile(); if (!selectedProfile) { return null; } const profiles: Profile[] = []; for (const id of profileList) { const profile = getProfile(id); if (!profile) { continue; } profiles.push(profile); } if (profiles.length === 0) { return null; } const profile = profiles.find((p) => p.id === selectedProfile); if (!profile) { const profile = profiles[0] as Profile; return { profiles, profile, selectedProfile: profile.id }; } return { profiles, profile, selectedProfile }; }; export const getThread = (id: string) => { const raw = localStorage.getItem("Thread_" + id); if (raw) { return JSON.parse(raw) as Thread; } }; export const loadData = () => { const profileData = loadProfiles(); if (!profileData) { return null; } const { profiles, profile, selectedProfile } = profileData; const threads = profile.threadIds
.map((id) => getThread(id)) .filter((t) => t !== undefined) as Thread[];
return { profiles, profile, selectedProfile, threads }; }; interface Store { profile: Profile; setProfile: (value: Profile) => void; addProfile: (value: Profile) => void; deleteProfile: (value: Profile) => void; selectedProfile: string; setSelectedProfile: (value: string) => void; profiles: Profile[]; setProfiles: (value: Profile[]) => void; thread: Thread; setThread: (value: Thread) => void; addThread: (value: Thread) => void; deleteThread: (value: Thread) => void; threads: Thread[]; setThreads: (value: Thread[]) => void; apiKeyModal: boolean; setApiKeyModal: (value: boolean) => void; apiKeyError: boolean; setApiKeyError: (value: boolean) => void; models: Model[]; setModels: (value: Model[]) => void; modelModal: boolean; setModelModal: (value: boolean) => void; selectedApiKey: number; setSelectedApiKey: (value: number) => void; width: number; setWidth: (value: number) => void; resetValues: () => void; resetThread: () => void; load: () => void; } const updateSelectedProfile = (id: string) => { localStorage.setItem("SelectedProfile", JSON.stringify(id)); }; const updateProfile = (profile: Profile) => { localStorage.setItem("Profile_" + profile.id, JSON.stringify(profile)); }; const addProfile = (profile: Profile) => { localStorage.setItem("Profile_" + profile.id, JSON.stringify(profile)); const profileList = getLocalProfileList(); if (profileList) { localStorage.setItem( "Profiles", JSON.stringify([...profileList, profile.id]) ); } else { localStorage.setItem("Profiles", JSON.stringify([profile.id])); } }; const deleteProfile = (profile: Profile) => { profile.threadIds.forEach((id) => deleteThread(id)); localStorage.removeItem("Profile_" + profile.id); const profileList = getLocalProfileList(); if (profileList) { const newProfileList = profileList.filter((p) => p !== profile.id); localStorage.setItem("Profiles", JSON.stringify(newProfileList)); const selectedProfile = getSelectedProfile(); if (selectedProfile === profile.id) { localStorage.removeItem("SelectedProfile"); } if (newProfileList.length === 0) { localStorage.removeItem("Profiles"); } else { const newSelectedProfile = newProfileList[0]; localStorage.setItem( "SelectedProfile", JSON.stringify(newSelectedProfile) ); } } }; const updateThread = (thread: Thread) => { localStorage.setItem("Thread_" + thread.id, JSON.stringify(thread)); }; const deleteThread = (id: string) => { localStorage.removeItem("Thread_" + id); }; const useStore = create<Store>((set) => ({ ...initialValues, setProfiles: (value: Profile[]) => set({ profiles: value }), setProfile: (value: Profile) => { updateProfile(value); set({ profile: value }); }, addProfile: (value: Profile) => { addProfile(value); set((state) => ({ profiles: [...state.profiles, value] })); }, deleteProfile: (value: Profile) => { deleteProfile(value); set((state) => ({ profiles: state.profiles.filter((p) => p.id !== value.id), })); }, addThread: (value: Thread) => { updateThread(value); set((state) => ({ threads: [...state.threads, value], })); }, deleteThread: (value: Thread) => { deleteThread(value.id); set((state) => ({ threads: state.threads.filter((t) => t.id !== value.id), })); }, setSelectedProfile: (value: string) => { updateSelectedProfile(value); set({ selectedProfile: value }); }, setThread: (value: Thread) => { updateThread(value); set((state) => ({ thread: value, threads: [...state.threads, value] })); }, setThreads: (value: Thread[]) => { set({ threads: value }); }, setApiKeyModal: (value: boolean) => set({ apiKeyModal: value }), setApiKeyError: (value: boolean) => set({ apiKeyError: value }), setModels: (value: Model[]) => set({ models: value }), setModelModal: (value: boolean) => set({ modelModal: value }), setWidth: (value: number) => set({ width: value }), setSelectedApiKey: (value: number) => set({ selectedApiKey: value }), load: () => set({ ...initialValues, ...loadData() }), resetThread: () => set({ thread: initialValues.thread }), resetValues: () => set(initialValues), })); export default useStore;
src/store/store.ts
cloudnothings-better-gpt-f1ad4fa
[ { "filename": "src/pages/index.tsx", "retrieved_chunk": " const threads = profile.threadIds.map((id) => {\n return getThread(id)\n }) as Thread[]\n setThreads(threads)\n }\n }\n }\n }, [selectedProfile, setProfile, setThreads]);\n return (\n <>", "score": 50.52775795523536 }, { "filename": "src/pages/index.tsx", "retrieved_chunk": " if (data.threads) {\n setThreads(data.threads)\n }\n }, [setProfile, setProfiles, setThreads, setSelectedProfile]);\n useEffect(() => {\n if (selectedProfile) {\n const profile = getProfile(selectedProfile)\n if (profile) {\n setProfile(profile)\n if (profile.threadIds) {", "score": 30.860943804079607 }, { "filename": "src/pages/index.tsx", "retrieved_chunk": " }\n const deleteThread = useStore((state) => state.deleteThread)\n const [deleting, setDeleting] = useState(false)\n const deleteHandler: MouseEventHandler<HTMLButtonElement> = (e) => {\n e.stopPropagation()\n deleteThread({ ...props })\n setProfile({ ...profile, threadIds: profile.threadIds.filter(id => id !== props.id) })\n }\n const selectHandler = () => {\n if (props.selected) return", "score": 29.039970688316263 }, { "filename": "src/pages/index.tsx", "retrieved_chunk": " const deleteThread = useStore((state) => state.deleteThread)\n const [deleting, setDeleting] = useState(false)\n const deleteHandler: MouseEventHandler<HTMLButtonElement> = (e) => {\n e.stopPropagation()\n deleteThread({ ...props })\n setProfile({ ...profile, threadIds: profile.threadIds.filter(id => id !== props.id) })\n }\n const selectHandler = () => {\n if (props.selected) return\n setThread({ ...props })", "score": 28.627877269976814 }, { "filename": "src/pages/index.tsx", "retrieved_chunk": " }\n if (data.selectedProfile) {\n setSelectedProfile(data.selectedProfile)\n }\n if (data.profile) {\n setProfile(data.profile)\n }\n if (data.profiles) {\n setProfiles(data.profiles)\n }", "score": 26.846321930846166 } ]
typescript
.map((id) => getThread(id)) .filter((t) => t !== undefined) as Thread[];
import { TRPCError } from "@trpc/server"; import { Configuration, OpenAIApi } from "openai"; import { type AxiosError } from "axios"; import { z } from "zod"; import { createTRPCRouter, publicProcedure, protectedProcedure, } from "~/server/api/trpc"; import type { Message } from "~/types/appstate"; export type ChatResponse = { id: string; created: number; model: string; choices: [ { finish_reason: string; index: number; message: Message; } ]; object: string; usage: { completion_tokens: number; prompt_tokens: number; total_tokens: number; }; }; export const gptRouter = createTRPCRouter({ post: publicProcedure .input( z.object({ apiKey: z.string(), model: z.string(), messages: z.array( z.object({ role: z.enum(["user", "system", "assistant"]), content: z.string(), }) ), }) ) .mutation(async ({ input }) => { const configuration = new Configuration({ apiKey: input.apiKey, }); const openai = new OpenAIApi(configuration); const response = await openai .createChatCompletion({ model: input.model, messages: input.messages, }) .catch((error: AxiosError) => { console.error(error); if (error.response) { console.log(error.response.status); console.log(error.response.data); throw new TRPCError({ code: "INTERNAL_SERVER_ERROR", cause: error.response.data, message: error.message, }); } else { console.log(error.message); throw new TRPCError({ code: "INTERNAL_SERVER_ERROR", message: error.message, }); } }); return
response.data as ChatResponse;
}), });
src/server/api/routers/gpt.ts
cloudnothings-better-gpt-f1ad4fa
[ { "filename": "src/pages/api/trpc/[trpc].ts", "retrieved_chunk": " ? ({ path, error }) => {\n console.error(\n `❌ tRPC failed on ${path ?? \"<no-path>\"}: ${error.message}`,\n );\n }\n : undefined,\n});", "score": 33.84816958340956 }, { "filename": "src/components/ChatWindow/ChatWindow.tsx", "retrieved_chunk": " })\n setMessage(\"\")\n },\n onError: (e) => {\n alert(e.message)\n }\n })\n } else\n mutate({ model: thread.model.id, apiKey: profile.key, messages: [...thread.messages, { content: message, role: \"user\" }] }, {\n onSuccess: (data) => {", "score": 22.199380282867722 }, { "filename": "src/server/db.ts", "retrieved_chunk": "import { PrismaClient } from \"@prisma/client\";\nimport { env } from \"~/env.mjs\";\nconst globalForPrisma = globalThis as unknown as { prisma: PrismaClient };\nexport const prisma =\n globalForPrisma.prisma ||\n new PrismaClient({\n log:\n env.NODE_ENV === \"development\" ? [\"query\", \"error\", \"warn\"] : [\"error\"],\n });\nif (env.NODE_ENV !== \"production\") globalForPrisma.prisma = prisma;", "score": 22.197097515933844 }, { "filename": "src/components/ChatWindow/ChatWindow.tsx", "retrieved_chunk": " const cost = calculateCost(data.usage, thread.model)\n setThread({ ...thread, cost: thread.cost + cost, messages: [...thread.messages, { content: message, role: \"user\" }, data.choices[0].message] as Message[] })\n setProfile({ ...profile, cost: profile.cost + cost, usage: increaseUsage(profile.usage, data.usage) })\n setMessage(\"\")\n },\n onError: (e) => {\n alert(e.message)\n }\n })\n }", "score": 20.668868002370814 }, { "filename": "src/components/ChatWindow/ChatWindow.tsx", "retrieved_chunk": " title: 'New Chat',\n cost: thread.cost + cost,\n messages: [...thread.messages, { content: message, role: \"user\" },\n data.choices[0].message] as Message[]\n })\n setProfile({\n ...profile,\n cost: profile.cost + cost,\n usage: increaseUsage(profile.usage, data.usage),\n threadIds: [...profile.threadIds, id]", "score": 19.179124682900998 } ]
typescript
response.data as ChatResponse;
import { Cog6ToothIcon } from "@heroicons/react/24/solid"; import Image from "next/image"; import useStore from "~/store/store"; import type { Message } from "~/types/appstate"; import { TextWithCode } from "../TextWithCode"; function classNames(...classes: string[]) { return classes.filter(Boolean).join(' ') } const AIResponse = ({ content }: { content: string }) => { return ( <div className="prose prose-sm max-w-full dark:prose-invert"> <TextWithCode text={content} /> </div> ); }; const MessageContainer = ({ content, role }: Message) => { return ( <div className="px-4 rounded-lg mb-2"> <div className="pl-14 relative response-block scroll-mt-32 rounded-md hover:bg-gray-50 dark:hover:bg-zinc-900 pb-2 pt-2 pr-2 group min-h-[52px]"> <div className="absolute top-2 left-2"> <div className='w-9 h-9 bg-gray-200 rounded-md flex-none flex items-center justify-center text-gray-500 hover:bg-gray-300 transition-all active:bg-gray-200'> {role === 'user' ? (<Image src='/favicon.ico' alt="Avatar" width={20} height={20} />) : (<Cog6ToothIcon className="w-5 h-5" />) } </div> </div> <div className="w-full"> {role === 'assistant' ? <AIResponse content={content} /> : ( <div> <div className="text-sm whitespace-pre-wrap space-y-2 w-fit text-white px-4 py-2 rounded-lg max-w-full overflow-auto highlight-darkblue focus:outline bg-blue-500"> {content} </div> </div> )} </div> </div> </div> ); }; const MessageWindow = () => { const
thread = useStore((state) => state.thread) if (!thread.messages) {
return null; } return ( <> {thread.messages.map((message, index) => { return ( <MessageContainer key={index} {...message} /> ); }) } </> ); }; export default MessageWindow;
src/components/ChatWindow/MessageWindow.tsx
cloudnothings-better-gpt-f1ad4fa
[ { "filename": "src/components/modals/ChangeModelModal.tsx", "retrieved_chunk": " const setThread = useStore((state) => state.setThread)\n const modelModal = useStore((state) => state.modelModal)\n const setModelModal = useStore((state) => state.setModelModal)\n const models = useStore((state) => state.models)\n const [selectedModel, setSelectedModel] = useState<Model>(thread.model)\n useEffect(() => {\n setSelectedModel(thread.model)\n }, [thread.model])\n const [systemInstruction, setSystemInstruction] = useState<string>(thread.initialSystemInstruction)\n const confirmationHandler = () => {", "score": 25.76420977462586 }, { "filename": "src/pages/index.tsx", "retrieved_chunk": "const StarredChat = (props: Thread & { selected: boolean }) => {\n const profile = useStore((state) => state.profile)\n const setProfile = useStore((state) => state.setProfile)\n const setThread = useStore((state) => state.setThread)\n const threads = useStore((state) => state.threads)\n const setThreads = useStore((state) => state.setThreads)\n const starThreadHandler: MouseEventHandler<HTMLButtonElement> = (e) => {\n e.stopPropagation()\n setThread({ ...props, starred: !props.starred })\n setThreads(threads.map(thread => thread.id === props.id ? { ...thread, starred: !thread.starred } : thread))", "score": 25.733842776669132 }, { "filename": "src/pages/index.tsx", "retrieved_chunk": " </div>\n </div>\n </div>\n </div>\n </div >\n )\n}\nconst ThreadList = () => {\n const threads = useStore((state) => state.threads)\n const selectedThread = useStore((state) => state.thread)", "score": 25.322333232914954 }, { "filename": "src/pages/index.tsx", "retrieved_chunk": " const selectedThread = useStore((state) => state.thread)\n return (\n <>\n <div className=\"max-h-[200px] overflow-auto\">\n {threads.map((thread) => (\n <StarredChat {...thread} key={thread.id} selected={selectedThread.id === thread.id} />\n ))}\n </div>\n {threads.length > 0 && (<hr className=\"border-gray-700\"></hr>)}\n </ >", "score": 24.873296478891994 }, { "filename": "src/components/ChatWindow/ChatWindow.tsx", "retrieved_chunk": " setStyle('mx-auto w-full hide-when-print transition-all max-w-full px-12')\n break\n }\n }, [width])\n const [showMenu, setShowMenu] = useState<boolean>(false)\n const thread = useStore((state) => state.thread)\n const setThread = useStore((state) => state.setThread)\n const setProfile = useStore((state) => state.setProfile)\n const profile = useStore((state) => state.profile)\n const { mutate, isLoading } = api.gpt.post.useMutation()", "score": 22.209515608366154 } ]
typescript
thread = useStore((state) => state.thread) if (!thread.messages) {
import { Cog6ToothIcon } from "@heroicons/react/24/solid"; import Image from "next/image"; import useStore from "~/store/store"; import type { Message } from "~/types/appstate"; import { TextWithCode } from "../TextWithCode"; function classNames(...classes: string[]) { return classes.filter(Boolean).join(' ') } const AIResponse = ({ content }: { content: string }) => { return ( <div className="prose prose-sm max-w-full dark:prose-invert"> <TextWithCode text={content} /> </div> ); }; const MessageContainer = ({ content, role }: Message) => { return ( <div className="px-4 rounded-lg mb-2"> <div className="pl-14 relative response-block scroll-mt-32 rounded-md hover:bg-gray-50 dark:hover:bg-zinc-900 pb-2 pt-2 pr-2 group min-h-[52px]"> <div className="absolute top-2 left-2"> <div className='w-9 h-9 bg-gray-200 rounded-md flex-none flex items-center justify-center text-gray-500 hover:bg-gray-300 transition-all active:bg-gray-200'> {role === 'user' ? (<Image src='/favicon.ico' alt="Avatar" width={20} height={20} />) : (<Cog6ToothIcon className="w-5 h-5" />) } </div> </div> <div className="w-full"> {role === 'assistant' ? <AIResponse content={content} /> : ( <div> <div className="text-sm whitespace-pre-wrap space-y-2 w-fit text-white px-4 py-2 rounded-lg max-w-full overflow-auto highlight-darkblue focus:outline bg-blue-500"> {content} </div> </div> )} </div> </div> </div> ); }; const MessageWindow = () => { const thread = useStore((state) => state.thread) if (!thread.messages) { return null; } return ( <> {thread
.messages.map((message, index) => {
return ( <MessageContainer key={index} {...message} /> ); }) } </> ); }; export default MessageWindow;
src/components/ChatWindow/MessageWindow.tsx
cloudnothings-better-gpt-f1ad4fa
[ { "filename": "src/components/ChatWindow/ChatWindow.tsx", "retrieved_chunk": " const [message, setMessage] = useState<string>(\"\")\n const sendMessage = () => {\n if (message.length > 0) {\n if (thread.messages.length === 0) {\n const id = uuid()\n const messages = [\n { role: 'system', content: thread.initialSystemInstruction },\n { role: 'user', content: message }\n ] as Message[]\n mutate({", "score": 33.093618642902854 }, { "filename": "src/pages/index.tsx", "retrieved_chunk": "const StarredChat = (props: Thread & { selected: boolean }) => {\n const profile = useStore((state) => state.profile)\n const setProfile = useStore((state) => state.setProfile)\n const setThread = useStore((state) => state.setThread)\n const threads = useStore((state) => state.threads)\n const setThreads = useStore((state) => state.setThreads)\n const starThreadHandler: MouseEventHandler<HTMLButtonElement> = (e) => {\n e.stopPropagation()\n setThread({ ...props, starred: !props.starred })\n setThreads(threads.map(thread => thread.id === props.id ? { ...thread, starred: !thread.starred } : thread))", "score": 32.805120723557486 }, { "filename": "src/pages/index.tsx", "retrieved_chunk": " const selectedThread = useStore((state) => state.thread)\n return (\n <>\n <div className=\"max-h-[200px] overflow-auto\">\n {threads.map((thread) => (\n <StarredChat {...thread} key={thread.id} selected={selectedThread.id === thread.id} />\n ))}\n </div>\n {threads.length > 0 && (<hr className=\"border-gray-700\"></hr>)}\n </ >", "score": 32.62312148065703 }, { "filename": "src/components/ChatWindow/ChatWindow.tsx", "retrieved_chunk": " const cost = calculateCost(data.usage, thread.model)\n setThread({ ...thread, cost: thread.cost + cost, messages: [...thread.messages, { content: message, role: \"user\" }, data.choices[0].message] as Message[] })\n setProfile({ ...profile, cost: profile.cost + cost, usage: increaseUsage(profile.usage, data.usage) })\n setMessage(\"\")\n },\n onError: (e) => {\n alert(e.message)\n }\n })\n }", "score": 31.026500705896247 }, { "filename": "src/components/ChatWindow/ChatWindow.tsx", "retrieved_chunk": " })\n setMessage(\"\")\n },\n onError: (e) => {\n alert(e.message)\n }\n })\n } else\n mutate({ model: thread.model.id, apiKey: profile.key, messages: [...thread.messages, { content: message, role: \"user\" }] }, {\n onSuccess: (data) => {", "score": 30.22545681515991 } ]
typescript
.messages.map((message, index) => {
/** * This is the client-side entrypoint for your tRPC API. It is used to create the `api` object which * contains the Next.js App-wrapper, as well as your type-safe React Query hooks. * * We also create a few inference helpers for input and output types. */ import { httpBatchLink, loggerLink } from "@trpc/client"; import { createTRPCNext } from "@trpc/next"; import { type inferRouterInputs, type inferRouterOutputs } from "@trpc/server"; import superjson from "superjson"; import { type AppRouter } from "~/server/api/root"; const getBaseUrl = () => { if (typeof window !== "undefined") return ""; // browser should use relative url if (process.env.VERCEL_URL) return `https://${process.env.VERCEL_URL}`; // SSR should use vercel url return `http://localhost:${process.env.PORT ?? 3000}`; // dev SSR should use localhost }; /** A set of type-safe react-query hooks for your tRPC API. */ export const api = createTRPCNext<AppRouter>({ config() { return { /** * Transformer used for data de-serialization from the server. * * @see https://trpc.io/docs/data-transformers */ transformer: superjson, /** * Links used to determine request flow from client to server. * * @see https://trpc.io/docs/links */ links: [ loggerLink({ enabled: (opts) => process.env.NODE_ENV === "development" || (opts.direction === "down" && opts.result instanceof Error), }), httpBatchLink({ url: `${getBaseUrl()}/api/trpc`, }), ], }; }, /** * Whether tRPC should await queries when server rendering pages. * * @see https://trpc.io/docs/nextjs#ssr-boolean-default-false */ ssr: false, }); /** * Inference helper for inputs. * * @example type HelloInput = RouterInputs['example']['hello'] */
export type RouterInputs = inferRouterInputs<AppRouter>;
/** * Inference helper for outputs. * * @example type HelloOutput = RouterOutputs['example']['hello'] */ export type RouterOutputs = inferRouterOutputs<AppRouter>;
src/utils/api.ts
cloudnothings-better-gpt-f1ad4fa
[ { "filename": "src/server/api/trpc.ts", "retrieved_chunk": " */\n/**\n * This is how you create new routers and sub-routers in your tRPC API.\n *\n * @see https://trpc.io/docs/router\n */\nexport const createTRPCRouter = t.router;\n/**\n * Public (unauthenticated) procedure\n *", "score": 21.404842411320637 }, { "filename": "src/server/api/root.ts", "retrieved_chunk": "import { createTRPCRouter } from \"~/server/api/trpc\";\nimport { exampleRouter } from \"~/server/api/routers/example\";\nimport { gptRouter } from \"./routers/gpt\";\n/**\n * This is the primary router for your server.\n *\n * All routers added in /api/routers should be manually added here.\n */\nexport const appRouter = createTRPCRouter({\n example: exampleRouter,", "score": 19.523969057596418 }, { "filename": "src/server/api/trpc.ts", "retrieved_chunk": " * that goes through your tRPC endpoint.\n *\n * @see https://trpc.io/docs/context\n */\nexport const createTRPCContext = async (opts: CreateNextContextOptions) => {\n const { req, res } = opts;\n // Get the session from the server using the getServerSession wrapper function\n const session = await getServerAuthSession({ req, res });\n return createInnerTRPCContext({\n session,", "score": 18.412293726959128 }, { "filename": "src/server/auth.ts", "retrieved_chunk": " /**\n * ...add more providers here.\n *\n * Most other providers require a bit more work than the Discord provider. For example, the\n * GitHub provider requires you to add the `refresh_token_expires_in` field to the Account\n * model. Refer to the NextAuth.js docs for the provider you want to use. Example:\n *\n * @see https://next-auth.js.org/providers/github\n */\n ],", "score": 18.200457154842383 }, { "filename": "src/server/api/trpc.ts", "retrieved_chunk": " * If you want a query or mutation to ONLY be accessible to logged in users, use this. It verifies\n * the session is valid and guarantees `ctx.session.user` is not null.\n *\n * @see https://trpc.io/docs/procedures\n */\nexport const protectedProcedure = t.procedure.use(enforceUserIsAuthed);", "score": 18.051756091175687 } ]
typescript
export type RouterInputs = inferRouterInputs<AppRouter>;
import { create } from "zustand"; import type { Model, Profile, Thread } from "~/types/appstate"; const models = [ { name: "GPT-3.5-TURBO", id: "gpt-3.5-turbo", description: "Most capable GPT-3.5 model and optimized for chat at 1/10th the cost of text-davinci-003. Will be updated with our latest model iteration.", maxTokens: 4096, usageCost: 0.002, trainingData: "Up to Sep 2021", }, { name: "GPT-3.5-TURBO-0301", id: "gpt-3.5-turbo-0301", description: "Snapshot of gpt-3.5-turbo from March 1st 2023. Unlike gpt-3.5-turbo, this model will not receive updates, and will only be supported for a three month period ending on June 1st 2023.", maxTokens: 4096, usageCost: 0.002, trainingData: "Up to Sep 2021", }, { name: "GPT-4 (Limited Beta)", id: "gpt-4", description: "More capable than any GPT-3.5 model, able to do more complex tasks, and optimized for chat. Will be updated with our latest model iteration.", maxTokens: 8192, promptCost: 0.03, completionCost: 0.06, trainingData: "Up to Sep 2021", note: "you need API Access to GPT-4 to use this model. If you haven't already, join the waitlist here: https://openai.com/waitlist/gpt-4-api", }, { name: "GPT-4-0314 (Limited Beta)", id: "gpt-4-0314", description: "Snapshot of gpt-4 from March 14th 2023. Unlike gpt-4, this model will not receive updates, and will only be supported for a three month period ending on June 14th 2023.", maxTokens: 8192, promptCost: 0.03, completionCost: 0.06, trainingData: "Up to Sep 2021", note: "you need API Access to GPT-4 to use this model. If you haven't already, join the waitlist here: https://openai.com/waitlist/gpt-4-api", }, { name: "GPT-4-32K (Limited Beta)", id: "gpt-4-32k", description: "Same capabilities as GPT-4, but with 4x the context length. Will be updated with our latest model iteration.", trainingData: "Up to Sep 2021", promptCost: 0.06, completionCost: 0.12, maxTokens: 32768, note: "you need API Access to GPT-4 to use this model. If you haven't already, join the waitlist here: https://openai.com/waitlist/gpt-4-api", }, { name: "GPT-4-32K-0314 (Limited Beta)", id: "gpt-4-32k-0314", description: "Snapshot of gpt-4-32k from March 14th 2023. Unlike gpt-4-32k, this model will not receive updates, and will only be supported for a three month period ending on June 14th 2023.", trainingData: "Up to Sep 2021", promptCost: 0.06, completionCost: 0.12, maxTokens: 32768, note: "you need API Access to GPT-4 to use this model. If you haven't already, join the waitlist here: https://openai.com/waitlist/gpt-4-api", }, ] as Model[]; const initialThread = { id: "", name: "", profileId: "", budget: 0, cost: 0, description: "", initialSystemInstruction: "", messages: [], model: models[0] as Model, starred: false, title: "", } as Thread; export const initialValues = { profile: { id: "", name: "", model: models[0] as Model, budget: 0, cost: 0, usage: { completion_tokens: 0, prompt_tokens: 0, total_tokens: 0, }, key: "", threadIds: [], organization: "", } as Profile, profiles: [] as Profile[], selectedProfile: "", thread: initialThread, threads: [] as Thread[], selectedApiKey: 0, apiKeyModal: false, apiKeyError: false, modelModal: false, models, width: 0, }; const getLocalProfileList = () => { const raw = localStorage.getItem("Profiles"); if (!raw) { return null; } return JSON.parse(raw) as string[]; }; const getSelectedProfile = () => { const raw = localStorage.getItem("SelectedProfile"); if (!raw) { return null; } return JSON.parse(raw) as string; }; export const getProfile = (id: string) => { const raw = localStorage.getItem("Profile_" + id); if (!raw) { return; } return JSON.parse(raw) as Profile; }; const loadProfiles = () => { const profileList = getLocalProfileList(); if (!profileList) { return null; } const selectedProfile = getSelectedProfile(); if (!selectedProfile) { return null; } const profiles: Profile[] = []; for (const id of profileList) { const profile = getProfile(id); if (!profile) { continue; } profiles.push(profile); } if (profiles.length === 0) { return null; } const profile = profiles.find((p) => p.id === selectedProfile); if (!profile) { const profile = profiles[0] as Profile; return { profiles, profile, selectedProfile: profile.id }; } return { profiles, profile, selectedProfile }; }; export const getThread = (id: string) => { const raw = localStorage.getItem("Thread_" + id); if (raw) { return JSON.parse(raw) as Thread; } }; export const loadData = () => { const profileData = loadProfiles(); if (!profileData) { return null; } const { profiles, profile, selectedProfile } = profileData; const threads = profile.threadIds .map((id) => getThread(id)) .filter(
(t) => t !== undefined) as Thread[];
return { profiles, profile, selectedProfile, threads }; }; interface Store { profile: Profile; setProfile: (value: Profile) => void; addProfile: (value: Profile) => void; deleteProfile: (value: Profile) => void; selectedProfile: string; setSelectedProfile: (value: string) => void; profiles: Profile[]; setProfiles: (value: Profile[]) => void; thread: Thread; setThread: (value: Thread) => void; addThread: (value: Thread) => void; deleteThread: (value: Thread) => void; threads: Thread[]; setThreads: (value: Thread[]) => void; apiKeyModal: boolean; setApiKeyModal: (value: boolean) => void; apiKeyError: boolean; setApiKeyError: (value: boolean) => void; models: Model[]; setModels: (value: Model[]) => void; modelModal: boolean; setModelModal: (value: boolean) => void; selectedApiKey: number; setSelectedApiKey: (value: number) => void; width: number; setWidth: (value: number) => void; resetValues: () => void; resetThread: () => void; load: () => void; } const updateSelectedProfile = (id: string) => { localStorage.setItem("SelectedProfile", JSON.stringify(id)); }; const updateProfile = (profile: Profile) => { localStorage.setItem("Profile_" + profile.id, JSON.stringify(profile)); }; const addProfile = (profile: Profile) => { localStorage.setItem("Profile_" + profile.id, JSON.stringify(profile)); const profileList = getLocalProfileList(); if (profileList) { localStorage.setItem( "Profiles", JSON.stringify([...profileList, profile.id]) ); } else { localStorage.setItem("Profiles", JSON.stringify([profile.id])); } }; const deleteProfile = (profile: Profile) => { profile.threadIds.forEach((id) => deleteThread(id)); localStorage.removeItem("Profile_" + profile.id); const profileList = getLocalProfileList(); if (profileList) { const newProfileList = profileList.filter((p) => p !== profile.id); localStorage.setItem("Profiles", JSON.stringify(newProfileList)); const selectedProfile = getSelectedProfile(); if (selectedProfile === profile.id) { localStorage.removeItem("SelectedProfile"); } if (newProfileList.length === 0) { localStorage.removeItem("Profiles"); } else { const newSelectedProfile = newProfileList[0]; localStorage.setItem( "SelectedProfile", JSON.stringify(newSelectedProfile) ); } } }; const updateThread = (thread: Thread) => { localStorage.setItem("Thread_" + thread.id, JSON.stringify(thread)); }; const deleteThread = (id: string) => { localStorage.removeItem("Thread_" + id); }; const useStore = create<Store>((set) => ({ ...initialValues, setProfiles: (value: Profile[]) => set({ profiles: value }), setProfile: (value: Profile) => { updateProfile(value); set({ profile: value }); }, addProfile: (value: Profile) => { addProfile(value); set((state) => ({ profiles: [...state.profiles, value] })); }, deleteProfile: (value: Profile) => { deleteProfile(value); set((state) => ({ profiles: state.profiles.filter((p) => p.id !== value.id), })); }, addThread: (value: Thread) => { updateThread(value); set((state) => ({ threads: [...state.threads, value], })); }, deleteThread: (value: Thread) => { deleteThread(value.id); set((state) => ({ threads: state.threads.filter((t) => t.id !== value.id), })); }, setSelectedProfile: (value: string) => { updateSelectedProfile(value); set({ selectedProfile: value }); }, setThread: (value: Thread) => { updateThread(value); set((state) => ({ thread: value, threads: [...state.threads, value] })); }, setThreads: (value: Thread[]) => { set({ threads: value }); }, setApiKeyModal: (value: boolean) => set({ apiKeyModal: value }), setApiKeyError: (value: boolean) => set({ apiKeyError: value }), setModels: (value: Model[]) => set({ models: value }), setModelModal: (value: boolean) => set({ modelModal: value }), setWidth: (value: number) => set({ width: value }), setSelectedApiKey: (value: number) => set({ selectedApiKey: value }), load: () => set({ ...initialValues, ...loadData() }), resetThread: () => set({ thread: initialValues.thread }), resetValues: () => set(initialValues), })); export default useStore;
src/store/store.ts
cloudnothings-better-gpt-f1ad4fa
[ { "filename": "src/pages/index.tsx", "retrieved_chunk": " const threads = profile.threadIds.map((id) => {\n return getThread(id)\n }) as Thread[]\n setThreads(threads)\n }\n }\n }\n }, [selectedProfile, setProfile, setThreads]);\n return (\n <>", "score": 50.52775795523536 }, { "filename": "src/pages/index.tsx", "retrieved_chunk": " if (data.threads) {\n setThreads(data.threads)\n }\n }, [setProfile, setProfiles, setThreads, setSelectedProfile]);\n useEffect(() => {\n if (selectedProfile) {\n const profile = getProfile(selectedProfile)\n if (profile) {\n setProfile(profile)\n if (profile.threadIds) {", "score": 30.860943804079607 }, { "filename": "src/pages/index.tsx", "retrieved_chunk": " }\n const deleteThread = useStore((state) => state.deleteThread)\n const [deleting, setDeleting] = useState(false)\n const deleteHandler: MouseEventHandler<HTMLButtonElement> = (e) => {\n e.stopPropagation()\n deleteThread({ ...props })\n setProfile({ ...profile, threadIds: profile.threadIds.filter(id => id !== props.id) })\n }\n const selectHandler = () => {\n if (props.selected) return", "score": 29.039970688316263 }, { "filename": "src/pages/index.tsx", "retrieved_chunk": " const deleteThread = useStore((state) => state.deleteThread)\n const [deleting, setDeleting] = useState(false)\n const deleteHandler: MouseEventHandler<HTMLButtonElement> = (e) => {\n e.stopPropagation()\n deleteThread({ ...props })\n setProfile({ ...profile, threadIds: profile.threadIds.filter(id => id !== props.id) })\n }\n const selectHandler = () => {\n if (props.selected) return\n setThread({ ...props })", "score": 28.627877269976814 }, { "filename": "src/pages/index.tsx", "retrieved_chunk": " }\n if (data.selectedProfile) {\n setSelectedProfile(data.selectedProfile)\n }\n if (data.profile) {\n setProfile(data.profile)\n }\n if (data.profiles) {\n setProfiles(data.profiles)\n }", "score": 26.846321930846166 } ]
typescript
(t) => t !== undefined) as Thread[];
import { create } from "zustand"; import type { Model, Profile, Thread } from "~/types/appstate"; const models = [ { name: "GPT-3.5-TURBO", id: "gpt-3.5-turbo", description: "Most capable GPT-3.5 model and optimized for chat at 1/10th the cost of text-davinci-003. Will be updated with our latest model iteration.", maxTokens: 4096, usageCost: 0.002, trainingData: "Up to Sep 2021", }, { name: "GPT-3.5-TURBO-0301", id: "gpt-3.5-turbo-0301", description: "Snapshot of gpt-3.5-turbo from March 1st 2023. Unlike gpt-3.5-turbo, this model will not receive updates, and will only be supported for a three month period ending on June 1st 2023.", maxTokens: 4096, usageCost: 0.002, trainingData: "Up to Sep 2021", }, { name: "GPT-4 (Limited Beta)", id: "gpt-4", description: "More capable than any GPT-3.5 model, able to do more complex tasks, and optimized for chat. Will be updated with our latest model iteration.", maxTokens: 8192, promptCost: 0.03, completionCost: 0.06, trainingData: "Up to Sep 2021", note: "you need API Access to GPT-4 to use this model. If you haven't already, join the waitlist here: https://openai.com/waitlist/gpt-4-api", }, { name: "GPT-4-0314 (Limited Beta)", id: "gpt-4-0314", description: "Snapshot of gpt-4 from March 14th 2023. Unlike gpt-4, this model will not receive updates, and will only be supported for a three month period ending on June 14th 2023.", maxTokens: 8192, promptCost: 0.03, completionCost: 0.06, trainingData: "Up to Sep 2021", note: "you need API Access to GPT-4 to use this model. If you haven't already, join the waitlist here: https://openai.com/waitlist/gpt-4-api", }, { name: "GPT-4-32K (Limited Beta)", id: "gpt-4-32k", description: "Same capabilities as GPT-4, but with 4x the context length. Will be updated with our latest model iteration.", trainingData: "Up to Sep 2021", promptCost: 0.06, completionCost: 0.12, maxTokens: 32768, note: "you need API Access to GPT-4 to use this model. If you haven't already, join the waitlist here: https://openai.com/waitlist/gpt-4-api", }, { name: "GPT-4-32K-0314 (Limited Beta)", id: "gpt-4-32k-0314", description: "Snapshot of gpt-4-32k from March 14th 2023. Unlike gpt-4-32k, this model will not receive updates, and will only be supported for a three month period ending on June 14th 2023.", trainingData: "Up to Sep 2021", promptCost: 0.06, completionCost: 0.12, maxTokens: 32768, note: "you need API Access to GPT-4 to use this model. If you haven't already, join the waitlist here: https://openai.com/waitlist/gpt-4-api", }, ] as Model[]; const initialThread = { id: "", name: "", profileId: "", budget: 0, cost: 0, description: "", initialSystemInstruction: "", messages: [], model: models[0] as Model, starred: false, title: "", } as Thread; export const initialValues = { profile: { id: "", name: "", model: models[0] as Model, budget: 0, cost: 0, usage: { completion_tokens: 0, prompt_tokens: 0, total_tokens: 0, }, key: "", threadIds: [], organization: "", } as Profile, profiles: [] as Profile[], selectedProfile: "", thread: initialThread, threads: [] as Thread[], selectedApiKey: 0, apiKeyModal: false, apiKeyError: false, modelModal: false, models, width: 0, }; const getLocalProfileList = () => { const raw = localStorage.getItem("Profiles"); if (!raw) { return null; } return JSON.parse(raw) as string[]; }; const getSelectedProfile = () => { const raw = localStorage.getItem("SelectedProfile"); if (!raw) { return null; } return JSON.parse(raw) as string; }; export const getProfile = (id: string) => { const raw = localStorage.getItem("Profile_" + id); if (!raw) { return; } return JSON.parse(raw) as Profile; }; const loadProfiles = () => { const profileList = getLocalProfileList(); if (!profileList) { return null; } const selectedProfile = getSelectedProfile(); if (!selectedProfile) { return null; } const profiles: Profile[] = []; for (const id of profileList) { const profile = getProfile(id); if (!profile) { continue; } profiles.push(profile); } if (profiles.length === 0) { return null; } const profile = profiles.find((p) => p.id === selectedProfile); if (!profile) { const profile = profiles[0] as Profile; return { profiles, profile, selectedProfile: profile.id }; } return { profiles, profile, selectedProfile }; }; export const getThread = (id: string) => { const raw = localStorage.getItem("Thread_" + id); if (raw) { return JSON.parse(raw) as Thread; } }; export const loadData = () => { const profileData = loadProfiles(); if (!profileData) { return null; } const { profiles, profile, selectedProfile } = profileData; const threads = profile.threadIds .map((id) => getThread(id)) .
filter((t) => t !== undefined) as Thread[];
return { profiles, profile, selectedProfile, threads }; }; interface Store { profile: Profile; setProfile: (value: Profile) => void; addProfile: (value: Profile) => void; deleteProfile: (value: Profile) => void; selectedProfile: string; setSelectedProfile: (value: string) => void; profiles: Profile[]; setProfiles: (value: Profile[]) => void; thread: Thread; setThread: (value: Thread) => void; addThread: (value: Thread) => void; deleteThread: (value: Thread) => void; threads: Thread[]; setThreads: (value: Thread[]) => void; apiKeyModal: boolean; setApiKeyModal: (value: boolean) => void; apiKeyError: boolean; setApiKeyError: (value: boolean) => void; models: Model[]; setModels: (value: Model[]) => void; modelModal: boolean; setModelModal: (value: boolean) => void; selectedApiKey: number; setSelectedApiKey: (value: number) => void; width: number; setWidth: (value: number) => void; resetValues: () => void; resetThread: () => void; load: () => void; } const updateSelectedProfile = (id: string) => { localStorage.setItem("SelectedProfile", JSON.stringify(id)); }; const updateProfile = (profile: Profile) => { localStorage.setItem("Profile_" + profile.id, JSON.stringify(profile)); }; const addProfile = (profile: Profile) => { localStorage.setItem("Profile_" + profile.id, JSON.stringify(profile)); const profileList = getLocalProfileList(); if (profileList) { localStorage.setItem( "Profiles", JSON.stringify([...profileList, profile.id]) ); } else { localStorage.setItem("Profiles", JSON.stringify([profile.id])); } }; const deleteProfile = (profile: Profile) => { profile.threadIds.forEach((id) => deleteThread(id)); localStorage.removeItem("Profile_" + profile.id); const profileList = getLocalProfileList(); if (profileList) { const newProfileList = profileList.filter((p) => p !== profile.id); localStorage.setItem("Profiles", JSON.stringify(newProfileList)); const selectedProfile = getSelectedProfile(); if (selectedProfile === profile.id) { localStorage.removeItem("SelectedProfile"); } if (newProfileList.length === 0) { localStorage.removeItem("Profiles"); } else { const newSelectedProfile = newProfileList[0]; localStorage.setItem( "SelectedProfile", JSON.stringify(newSelectedProfile) ); } } }; const updateThread = (thread: Thread) => { localStorage.setItem("Thread_" + thread.id, JSON.stringify(thread)); }; const deleteThread = (id: string) => { localStorage.removeItem("Thread_" + id); }; const useStore = create<Store>((set) => ({ ...initialValues, setProfiles: (value: Profile[]) => set({ profiles: value }), setProfile: (value: Profile) => { updateProfile(value); set({ profile: value }); }, addProfile: (value: Profile) => { addProfile(value); set((state) => ({ profiles: [...state.profiles, value] })); }, deleteProfile: (value: Profile) => { deleteProfile(value); set((state) => ({ profiles: state.profiles.filter((p) => p.id !== value.id), })); }, addThread: (value: Thread) => { updateThread(value); set((state) => ({ threads: [...state.threads, value], })); }, deleteThread: (value: Thread) => { deleteThread(value.id); set((state) => ({ threads: state.threads.filter((t) => t.id !== value.id), })); }, setSelectedProfile: (value: string) => { updateSelectedProfile(value); set({ selectedProfile: value }); }, setThread: (value: Thread) => { updateThread(value); set((state) => ({ thread: value, threads: [...state.threads, value] })); }, setThreads: (value: Thread[]) => { set({ threads: value }); }, setApiKeyModal: (value: boolean) => set({ apiKeyModal: value }), setApiKeyError: (value: boolean) => set({ apiKeyError: value }), setModels: (value: Model[]) => set({ models: value }), setModelModal: (value: boolean) => set({ modelModal: value }), setWidth: (value: number) => set({ width: value }), setSelectedApiKey: (value: number) => set({ selectedApiKey: value }), load: () => set({ ...initialValues, ...loadData() }), resetThread: () => set({ thread: initialValues.thread }), resetValues: () => set(initialValues), })); export default useStore;
src/store/store.ts
cloudnothings-better-gpt-f1ad4fa
[ { "filename": "src/pages/index.tsx", "retrieved_chunk": " const threads = profile.threadIds.map((id) => {\n return getThread(id)\n }) as Thread[]\n setThreads(threads)\n }\n }\n }\n }, [selectedProfile, setProfile, setThreads]);\n return (\n <>", "score": 50.52775795523536 }, { "filename": "src/pages/index.tsx", "retrieved_chunk": " if (data.threads) {\n setThreads(data.threads)\n }\n }, [setProfile, setProfiles, setThreads, setSelectedProfile]);\n useEffect(() => {\n if (selectedProfile) {\n const profile = getProfile(selectedProfile)\n if (profile) {\n setProfile(profile)\n if (profile.threadIds) {", "score": 30.860943804079607 }, { "filename": "src/pages/index.tsx", "retrieved_chunk": " }\n const deleteThread = useStore((state) => state.deleteThread)\n const [deleting, setDeleting] = useState(false)\n const deleteHandler: MouseEventHandler<HTMLButtonElement> = (e) => {\n e.stopPropagation()\n deleteThread({ ...props })\n setProfile({ ...profile, threadIds: profile.threadIds.filter(id => id !== props.id) })\n }\n const selectHandler = () => {\n if (props.selected) return", "score": 29.039970688316263 }, { "filename": "src/pages/index.tsx", "retrieved_chunk": " const deleteThread = useStore((state) => state.deleteThread)\n const [deleting, setDeleting] = useState(false)\n const deleteHandler: MouseEventHandler<HTMLButtonElement> = (e) => {\n e.stopPropagation()\n deleteThread({ ...props })\n setProfile({ ...profile, threadIds: profile.threadIds.filter(id => id !== props.id) })\n }\n const selectHandler = () => {\n if (props.selected) return\n setThread({ ...props })", "score": 28.627877269976814 }, { "filename": "src/pages/index.tsx", "retrieved_chunk": " }\n if (data.selectedProfile) {\n setSelectedProfile(data.selectedProfile)\n }\n if (data.profile) {\n setProfile(data.profile)\n }\n if (data.profiles) {\n setProfiles(data.profiles)\n }", "score": 26.846321930846166 } ]
typescript
filter((t) => t !== undefined) as Thread[];
import axios, { AxiosProxyConfig, AxiosResponse } from 'axios'; import moment from 'moment'; import { AnnouncedTest, ClassAverage, ClassMaster, ConfigurationDescriptor, Evaluation, Group, Homework, Institute, Institution, KretaOptions, LepEvent, Lesson, Note, NoticeBoardItem, Omission, PreBuiltAuthenticationToken, RequestAnnouncedTestsOptions, RequestClassAveragesOptions, RequestDateRangeOptions, RequestDateRangeRequiredOptions, RequestHomeWorkOptions, SchoolYearCalendarEntry, Student, SubjectAverage, TimeTableWeek, API, Endpoints } from '../types'; import { Authentication } from './Authentication'; import dynamicValue from '../utils/dynamicValue'; import Administration from './Administration'; import Global from './Global'; import requireCredentials from '../decorators/requireCredentials'; import tryRequest from '../utils/tryRequest'; import validateDate from '../utils/validateDate'; import requireParam from '../decorators/requireParam'; export default class Kreta { private readonly username?: string; private readonly password?: string; private readonly institute_code?: string; private authenticate?: Authentication; public Administration?: Administration; public Global: Global; private token?: Promise<string>; constructor(options?: KretaOptions) { this.username = options?.username || ''; this.password = options?.password || ''; this.institute_code = options?.institute_code || ''; axios.defaults.headers.common['User-Agent'] = 'hu.ekreta.student/1.0.5/Android/0/0'; this.Global = new Global(); this.authenticate = new Authentication({ username: this.username!, password: this.password!, institute_code: this.institute_code! }); if (this.username && this.password && this.institute_code) this.token = this.authenticate.getAccessToken().then((r: PreBuiltAuthenticationToken) => r.token); this.Administration = new Administration({ username: this.username!, password: this.password!, institute_code: this.institute_code! }); } public get _username() { return this.username; } public get _password() { return this.password; } public get _institute_code() { return this.institute_code; } @requireParam('proxy.host') @requireParam('proxy.port') public setProxy(proxy: AxiosProxyConfig): this { axios.defaults.proxy = proxy; return this; } @requireParam('ua') public setUserAgent(ua: string): this { axios.defaults.headers.common['User-Agent'] = ua; return this; } private buildEllenorzoApiURL(endpointWithSlash: Endpoints, params?: { [key: string]: any }): string { const urlParams: string = params ? '?' + new URLSearchParams(params).toString() : ''; return dynamicValue(API.INSTITUTE, { institute_code: this.institute_code }).toString() + '/ellenorzo/V3' + endpointWithSlash + urlParams; } @requireParam('api_key') public getInstituteList(api_key: string): Promise<Institute[]> { return new Promise(async (resolve): Promise<void> => { const config_descriptor: AxiosResponse<ConfigurationDescriptor> = await axios.get('https://kretamobile.blob.core.windows.net/configuration/ConfigurationDescriptor.json');
await tryRequest(axios.get(config_descriptor.data.GlobalMobileApiUrlPROD + '/api/v3/Institute', {
headers: { apiKey: api_key } }).then((r: AxiosResponse<Institute[]>) => resolve(r.data))); }); } @requireCredentials public getStudent(): Promise<Student> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.Tanulo), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Student>) => resolve(r.data))); }); } @requireCredentials public getEvaluations(options?: RequestDateRangeOptions): Promise<Evaluation[]> { return new Promise(async (resolve): Promise<void> => { const ops: { datumTol?: string; datumIg?: string } = {}; if (options?.dateFrom) ops.datumTol = validateDate(moment(options.dateFrom).format('YYYY-MM-DD')); if (options?.dateTo) ops.datumIg = validateDate(moment(options.dateTo).format('YYYY-MM-DD')); await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.Ertekelesek, ops), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Evaluation[]>) => resolve(r.data))); }); } @requireCredentials public getNotes(options?: RequestDateRangeOptions): Promise<Note[]> { return new Promise(async (resolve): Promise<void> => { const ops: { datumTol?: string; datumIg?: string } = {}; if (options?.dateFrom) ops.datumTol = validateDate(moment(options.dateFrom).format('YYYY-MM-DD')); if (options?.dateTo) ops.datumIg = validateDate(moment(options.dateTo).format('YYYY-MM-DD')); await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.Feljegyzesek, ops), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Note[]>) => resolve(r.data))); }); } @requireCredentials public getAnnouncedTests(options?: RequestAnnouncedTestsOptions): Promise<AnnouncedTest[]> { return new Promise(async (resolve): Promise<void> => { const ops: { datumTol?: string; datumIg?: string, Uids?: string } = {}; if (options?.dateFrom) ops.datumTol = validateDate(moment(options.dateFrom).format('YYYY-MM-DD')); if (options?.dateTo) ops.datumIg = validateDate(moment(options.dateTo).format('YYYY-MM-DD')); if (options?.uids) ops.Uids = options.uids.map((uid: string | number) => uid.toString()).join(';'); await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.Szamonkeresek, ops), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<AnnouncedTest[]>) => resolve(r.data))); }); } @requireCredentials @requireParam('options.dateFrom') public getHomeworks(options: RequestHomeWorkOptions): Promise<Homework[]> { return new Promise(async (resolve): Promise<void> => { const ops: { datumTol: string; datumIg?: string } = { datumTol: validateDate(moment(options.dateFrom).format('YYYY-MM-DD')) }; if (options?.dateTo) ops.datumIg = validateDate(moment(options.dateTo).format('YYYY-MM-DD')); await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.HaziFeladatok, ops), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Homework[]>) => resolve(r.data))); }); } @requireCredentials @requireParam('uid') public getHomework(uid: string | number): Promise<Homework> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.HaziFeladatok) + '/' + uid.toString(), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Homework>) => resolve(r.data))); }); } @requireCredentials public getOmissions(options?: RequestDateRangeOptions): Promise<Omission[]> { return new Promise(async (resolve): Promise<void> => { const ops: { datumTol?: string; datumIg?: string } = {}; if (options?.dateFrom) ops.datumTol = validateDate(moment(options.dateFrom).format('YYYY-MM-DD')); if (options?.dateTo) ops.datumIg = validateDate(moment(options.dateTo).format('YYYY-MM-DD')); await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.Mulasztasok, ops), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Omission[]>) => resolve(r.data))); }); } @requireCredentials public getGroups(): Promise<Group[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.OsztalyCsoportok), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Group[]>) => resolve(r.data))); }); } @requireCredentials public getSubjectAverages(onfUid?: string): Promise<SubjectAverage[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.TantargyiAtlagok, { oktatasiNevelesiFeladatUid: onfUid || await this.getGroups().then((groups: Group[]) => groups[0].OktatasNevelesiFeladat.Uid) }), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<SubjectAverage[]>) => resolve(r.data))); }); } @requireCredentials @requireParam('options.dateFrom') @requireParam('options.dateTo') public getLessons(options: RequestDateRangeRequiredOptions): Promise<Lesson[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.OrarendElemek, { datumTol: validateDate(moment(options.dateFrom).format('YYYY-MM-DD')), datumIg: validateDate(moment(options.dateTo).format('YYYY-MM-DD')) }), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Lesson[]>) => resolve(r.data))); }); } @requireCredentials @requireParam('uid') public getLesson(uid: string | number): Promise<Lesson> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.OrarendElem, { orarendElemUid: uid.toString() }), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Lesson>) => resolve(r.data))); }); } @requireCredentials public getNoticeBoardItems(): Promise<NoticeBoardItem[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.FaliujsagElemek), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<NoticeBoardItem[]>) => resolve(r.data))); }); } @requireCredentials public getClassAverage(options?: RequestClassAveragesOptions): Promise<ClassAverage[]> { return new Promise(async (resolve): Promise<void> => { const ops: { oktatasiNevelesiFeladatUid: string; tantargyUid?: string; } = { oktatasiNevelesiFeladatUid: options?.oktatasiNevelesiFeladatUid || await this.getGroups().then((groups: Group[]) => groups[0].OktatasNevelesiFeladat.Uid) }; if (options?.subjectUid) ops.tantargyUid = options.subjectUid; await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.OsztalyCsoportAtlag, ops), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<ClassAverage[]>) => resolve(r.data))); }); } @requireCredentials public getInstitute(): Promise<Institution> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.Intezmenyek), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Institution>) => resolve(r.data))); }); } @requireCredentials @requireParam('uids') public getClassMasters(uids: string[] | number[]): Promise<ClassMaster[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.Osztalyfonokok, { Uids: uids.map((u: string | number) => u.toString()).join(';') }), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<ClassMaster[]>) => resolve(r.data))); }); } @requireCredentials @requireParam('options.dateFrom') @requireParam('options.dateTo') public getTimeTableWeeks(options: RequestDateRangeRequiredOptions): Promise<TimeTableWeek[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.OrarendHetek, { orarendElemKezdoNapDatuma: validateDate(moment(options.dateFrom).format('YYYY-MM-DD')), orarendElemVegNapDatuma: validateDate(moment(options.dateTo).format('YYYY-MM-DD')) }), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<TimeTableWeek[]>) => resolve(r.data))); }); } @requireCredentials public getLepEvents(): Promise<LepEvent[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.Eloadasok), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<LepEvent[]>) => resolve(r.data))); }); } @requireCredentials public getSchoolYearCalendar(): Promise<SchoolYearCalendarEntry[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.TanevNaptar), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<SchoolYearCalendarEntry[]>) => resolve(r.data))); }); } @requireCredentials public getDeviceGivenState(): Promise<boolean> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.EszkozAllapot), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<boolean>) => resolve(r.data))); }); } }
src/lib/Kreta.ts
blazsmaster-kreta.js-9274c52
[ { "filename": "src/lib/Administration.ts", "retrieved_chunk": "\t\tconst urlParams: string = params ? '?' + new URLSearchParams(params).toString() : '';\n\t\treturn API.ADMINISTRATION + '/api/v1' + endpointWithSlash + urlParams;\n\t}\n\t@requireCredentials\n\tpublic getAddresseeType(): Promise<AddresseType[]> {\n\t\treturn new Promise(async (resolve): Promise<void> => {\n\t\t\tawait tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.CimzettTipusok), {\n\t\t\t\theaders: {\n\t\t\t\t\t'Authorization': await this.token\n\t\t\t\t}", "score": 71.26419807040446 }, { "filename": "src/lib/Administration.ts", "retrieved_chunk": "\tpublic get _username() {\n\t\treturn this.username;\n\t}\n\tpublic get _password() {\n\t\treturn this.password;\n\t}\n\tpublic get _institute_code() {\n\t\treturn this.institute_code;\n\t}\n\tprivate buildUgyintezesApiURL(endpointWithSlash: AdministrationEndpoints, params?: { [key: string]: any }): string {", "score": 47.21299329362174 }, { "filename": "src/lib/Authentication.ts", "retrieved_chunk": "\t}\n\tprivate getNonce(): Promise<string> {\n\t\treturn new Promise(async (resolve): Promise<void> => {\n\t\t\tawait tryRequest(axios.get(API.IDP + Endpoints.Nonce).then((r: AxiosResponse<string>) => resolve(r.data.toString())));\n\t\t});\n\t}\n\tprivate getNonceHash(options: NonceHashOptions): Promise<string> {\n\t\treturn new Promise((resolve): void => {\n\t\t\tconst buffer_bytes: Buffer = Buffer.from(options.institute_code.toUpperCase() + options.nonce + options.username.toUpperCase(), 'utf8');\n\t\t\tconst hash: Buffer = createHmac('sha512', Buffer.from([98, 97, 83, 115, 120, 79, 119, 108, 85, 49, 106, 77])).update(buffer_bytes).digest();", "score": 35.426920813809176 }, { "filename": "src/lib/Administration.ts", "retrieved_chunk": "\t\t\t\t}\n\t\t\t}).then((r: AxiosResponse<MailboxItem[]>) => resolve(r.data)));\n\t\t});\n\t}\n\t@requireCredentials\n\t@requireParam('id')\n\tpublic getMessage(id: string | number): Promise<MailboxItem> {\n\t\treturn new Promise(async (resolve): Promise<void> => {\n\t\t\tawait tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.Uzenet) + '/' + id.toString(), {\n\t\t\t\theaders: {", "score": 32.21072517317425 }, { "filename": "src/lib/Administration.ts", "retrieved_chunk": "\t\t\t\t\t'Authorization': await this.token\n\t\t\t\t}\n\t\t\t}).then((r: AxiosResponse<EmployeeDetails[]>) => resolve(r.data)));\n\t\t});\n\t}\n\t@requireCredentials\n\t@requireParam('classId')\n\tpublic getAddressableGuardiansForClass(classId: string | number): Promise<GuardianEAdmin[]> {\n\t\treturn new Promise(async (resolve): Promise<void> => {\n\t\t\tawait tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.CimezhetoTanuloSzulok) + '/' + classId.toString(), {", "score": 32.09615405595862 } ]
typescript
await tryRequest(axios.get(config_descriptor.data.GlobalMobileApiUrlPROD + '/api/v3/Institute', {
import axios, { AxiosProxyConfig, AxiosResponse } from 'axios'; import moment from 'moment'; import { AnnouncedTest, ClassAverage, ClassMaster, ConfigurationDescriptor, Evaluation, Group, Homework, Institute, Institution, KretaOptions, LepEvent, Lesson, Note, NoticeBoardItem, Omission, PreBuiltAuthenticationToken, RequestAnnouncedTestsOptions, RequestClassAveragesOptions, RequestDateRangeOptions, RequestDateRangeRequiredOptions, RequestHomeWorkOptions, SchoolYearCalendarEntry, Student, SubjectAverage, TimeTableWeek, API, Endpoints } from '../types'; import { Authentication } from './Authentication'; import dynamicValue from '../utils/dynamicValue'; import Administration from './Administration'; import Global from './Global'; import requireCredentials from '../decorators/requireCredentials'; import tryRequest from '../utils/tryRequest'; import validateDate from '../utils/validateDate'; import requireParam from '../decorators/requireParam'; export default class Kreta { private readonly username?: string; private readonly password?: string; private readonly institute_code?: string; private authenticate?: Authentication; public Administration?: Administration; public Global: Global; private token?: Promise<string>; constructor(options?: KretaOptions) { this.username = options?.username || ''; this.password = options?.password || ''; this.institute_code = options?.institute_code || ''; axios.defaults.headers.common['User-Agent'] = 'hu.ekreta.student/1.0.5/Android/0/0'; this.Global = new Global(); this.authenticate = new Authentication({ username: this.username!, password: this.password!, institute_code: this.institute_code! }); if (this.username && this.password && this.institute_code) this.token = this.authenticate.getAccessToken().then((r: PreBuiltAuthenticationToken) => r.token); this.Administration = new Administration({ username: this.username!, password: this.password!, institute_code: this.institute_code! }); } public get _username() { return this.username; } public get _password() { return this.password; } public get _institute_code() { return this.institute_code; } @requireParam('proxy.host') @requireParam('proxy.port') public setProxy(proxy: AxiosProxyConfig): this { axios.defaults.proxy = proxy; return this; } @requireParam('ua') public setUserAgent(ua: string): this { axios.defaults.headers.common['User-Agent'] = ua; return this; } private buildEllenorzoApiURL(endpointWithSlash: Endpoints, params?: { [key: string]: any }): string { const urlParams: string = params ? '?' + new URLSearchParams(params).toString() : ''; return dynamicValue(API.INSTITUTE, { institute_code: this.institute_code }).toString() + '/ellenorzo/V3' + endpointWithSlash + urlParams; } @requireParam('api_key') public getInstituteList(api_key: string): Promise<Institute[]> { return new Promise(async (resolve): Promise<void> => { const config_descriptor: AxiosResponse<ConfigurationDescriptor> = await axios.get('https://kretamobile.blob.core.windows.net/configuration/ConfigurationDescriptor.json'); await tryRequest(axios.get(config_descriptor.data.GlobalMobileApiUrlPROD + '/api/v3/Institute', { headers: { apiKey: api_key } }).then((r: AxiosResponse<Institute[]>) => resolve(r.data))); }); }
@requireCredentials public getStudent(): Promise<Student> {
return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.Tanulo), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Student>) => resolve(r.data))); }); } @requireCredentials public getEvaluations(options?: RequestDateRangeOptions): Promise<Evaluation[]> { return new Promise(async (resolve): Promise<void> => { const ops: { datumTol?: string; datumIg?: string } = {}; if (options?.dateFrom) ops.datumTol = validateDate(moment(options.dateFrom).format('YYYY-MM-DD')); if (options?.dateTo) ops.datumIg = validateDate(moment(options.dateTo).format('YYYY-MM-DD')); await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.Ertekelesek, ops), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Evaluation[]>) => resolve(r.data))); }); } @requireCredentials public getNotes(options?: RequestDateRangeOptions): Promise<Note[]> { return new Promise(async (resolve): Promise<void> => { const ops: { datumTol?: string; datumIg?: string } = {}; if (options?.dateFrom) ops.datumTol = validateDate(moment(options.dateFrom).format('YYYY-MM-DD')); if (options?.dateTo) ops.datumIg = validateDate(moment(options.dateTo).format('YYYY-MM-DD')); await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.Feljegyzesek, ops), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Note[]>) => resolve(r.data))); }); } @requireCredentials public getAnnouncedTests(options?: RequestAnnouncedTestsOptions): Promise<AnnouncedTest[]> { return new Promise(async (resolve): Promise<void> => { const ops: { datumTol?: string; datumIg?: string, Uids?: string } = {}; if (options?.dateFrom) ops.datumTol = validateDate(moment(options.dateFrom).format('YYYY-MM-DD')); if (options?.dateTo) ops.datumIg = validateDate(moment(options.dateTo).format('YYYY-MM-DD')); if (options?.uids) ops.Uids = options.uids.map((uid: string | number) => uid.toString()).join(';'); await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.Szamonkeresek, ops), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<AnnouncedTest[]>) => resolve(r.data))); }); } @requireCredentials @requireParam('options.dateFrom') public getHomeworks(options: RequestHomeWorkOptions): Promise<Homework[]> { return new Promise(async (resolve): Promise<void> => { const ops: { datumTol: string; datumIg?: string } = { datumTol: validateDate(moment(options.dateFrom).format('YYYY-MM-DD')) }; if (options?.dateTo) ops.datumIg = validateDate(moment(options.dateTo).format('YYYY-MM-DD')); await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.HaziFeladatok, ops), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Homework[]>) => resolve(r.data))); }); } @requireCredentials @requireParam('uid') public getHomework(uid: string | number): Promise<Homework> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.HaziFeladatok) + '/' + uid.toString(), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Homework>) => resolve(r.data))); }); } @requireCredentials public getOmissions(options?: RequestDateRangeOptions): Promise<Omission[]> { return new Promise(async (resolve): Promise<void> => { const ops: { datumTol?: string; datumIg?: string } = {}; if (options?.dateFrom) ops.datumTol = validateDate(moment(options.dateFrom).format('YYYY-MM-DD')); if (options?.dateTo) ops.datumIg = validateDate(moment(options.dateTo).format('YYYY-MM-DD')); await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.Mulasztasok, ops), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Omission[]>) => resolve(r.data))); }); } @requireCredentials public getGroups(): Promise<Group[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.OsztalyCsoportok), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Group[]>) => resolve(r.data))); }); } @requireCredentials public getSubjectAverages(onfUid?: string): Promise<SubjectAverage[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.TantargyiAtlagok, { oktatasiNevelesiFeladatUid: onfUid || await this.getGroups().then((groups: Group[]) => groups[0].OktatasNevelesiFeladat.Uid) }), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<SubjectAverage[]>) => resolve(r.data))); }); } @requireCredentials @requireParam('options.dateFrom') @requireParam('options.dateTo') public getLessons(options: RequestDateRangeRequiredOptions): Promise<Lesson[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.OrarendElemek, { datumTol: validateDate(moment(options.dateFrom).format('YYYY-MM-DD')), datumIg: validateDate(moment(options.dateTo).format('YYYY-MM-DD')) }), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Lesson[]>) => resolve(r.data))); }); } @requireCredentials @requireParam('uid') public getLesson(uid: string | number): Promise<Lesson> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.OrarendElem, { orarendElemUid: uid.toString() }), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Lesson>) => resolve(r.data))); }); } @requireCredentials public getNoticeBoardItems(): Promise<NoticeBoardItem[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.FaliujsagElemek), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<NoticeBoardItem[]>) => resolve(r.data))); }); } @requireCredentials public getClassAverage(options?: RequestClassAveragesOptions): Promise<ClassAverage[]> { return new Promise(async (resolve): Promise<void> => { const ops: { oktatasiNevelesiFeladatUid: string; tantargyUid?: string; } = { oktatasiNevelesiFeladatUid: options?.oktatasiNevelesiFeladatUid || await this.getGroups().then((groups: Group[]) => groups[0].OktatasNevelesiFeladat.Uid) }; if (options?.subjectUid) ops.tantargyUid = options.subjectUid; await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.OsztalyCsoportAtlag, ops), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<ClassAverage[]>) => resolve(r.data))); }); } @requireCredentials public getInstitute(): Promise<Institution> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.Intezmenyek), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Institution>) => resolve(r.data))); }); } @requireCredentials @requireParam('uids') public getClassMasters(uids: string[] | number[]): Promise<ClassMaster[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.Osztalyfonokok, { Uids: uids.map((u: string | number) => u.toString()).join(';') }), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<ClassMaster[]>) => resolve(r.data))); }); } @requireCredentials @requireParam('options.dateFrom') @requireParam('options.dateTo') public getTimeTableWeeks(options: RequestDateRangeRequiredOptions): Promise<TimeTableWeek[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.OrarendHetek, { orarendElemKezdoNapDatuma: validateDate(moment(options.dateFrom).format('YYYY-MM-DD')), orarendElemVegNapDatuma: validateDate(moment(options.dateTo).format('YYYY-MM-DD')) }), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<TimeTableWeek[]>) => resolve(r.data))); }); } @requireCredentials public getLepEvents(): Promise<LepEvent[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.Eloadasok), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<LepEvent[]>) => resolve(r.data))); }); } @requireCredentials public getSchoolYearCalendar(): Promise<SchoolYearCalendarEntry[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.TanevNaptar), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<SchoolYearCalendarEntry[]>) => resolve(r.data))); }); } @requireCredentials public getDeviceGivenState(): Promise<boolean> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.EszkozAllapot), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<boolean>) => resolve(r.data))); }); } }
src/lib/Kreta.ts
blazsmaster-kreta.js-9274c52
[ { "filename": "src/lib/Administration.ts", "retrieved_chunk": "\t\t\t}).then((r: AxiosResponse<string[]>) => resolve(r.data)));\n\t\t});\n\t}\n\t@requireCredentials\n\tpublic getAddressableType(): Promise<AddresseType[]> {\n\t\treturn new Promise(async (resolve): Promise<void> => {\n\t\t\tawait tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.CimezhetoTipusok), {\n\t\t\t\theaders: {\n\t\t\t\t\t'Authorization': await this.token\n\t\t\t\t}", "score": 23.169452591532757 }, { "filename": "src/lib/Administration.ts", "retrieved_chunk": "\t\t\t}).then((r: AxiosResponse<DefaultType[]>) => resolve(r.data)));\n\t\t});\n\t}\n\t@requireCredentials\n\tpublic getTmgiCaseTypes(): Promise<DefaultType[]> {\n\t\treturn new Promise(async (resolve): Promise<void> => {\n\t\t\tawait tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.TmgiIgazolasTipusok), {\n\t\t\t\theaders: {\n\t\t\t\t\t'Authorization': await this.token\n\t\t\t\t}", "score": 23.169452591532757 }, { "filename": "src/lib/Administration.ts", "retrieved_chunk": "\t\t\t}).then((r: AxiosResponse<DefaultType[]>) => resolve(r.data)));\n\t\t});\n\t}\n\t@requireCredentials\n\tpublic getAccessControlSystemEvents(): Promise<CardEvent[]> {\n\t\treturn new Promise(async (resolve): Promise<void> => {\n\t\t\tawait tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.Esemenyek), {\n\t\t\t\theaders: {\n\t\t\t\t\t'Authorization': await this.token\n\t\t\t\t}", "score": 23.169452591532757 }, { "filename": "src/lib/Administration.ts", "retrieved_chunk": "\t\t\t}).then((r: AxiosResponse<CardEvent[]>) => resolve(r.data)));\n\t\t});\n\t}\n\t@requireCredentials\n\tpublic getCurrentInstitutionModules(): Promise<string[]> {\n\t\treturn new Promise(async (resolve): Promise<void> => {\n\t\t\tawait tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.JelenlegiIntezmenyModulok), {\n\t\t\t\theaders: {\n\t\t\t\t\t'Authorization': await this.token\n\t\t\t\t}", "score": 23.169452591532757 }, { "filename": "src/lib/Administration.ts", "retrieved_chunk": "\t\t\t}).then((r: AxiosResponse<AddresseType[]>) => resolve(r.data)));\n\t\t});\n\t}\n\t@requireCredentials\n\tpublic getCaseTypes(): Promise<DefaultType[]> {\n\t\treturn new Promise(async (resolve): Promise<void> => {\n\t\t\tawait tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.KerelemTipusok), {\n\t\t\t\theaders: {\n\t\t\t\t\t'Authorization': await this.token\n\t\t\t\t}", "score": 23.169452591532757 } ]
typescript
@requireCredentials public getStudent(): Promise<Student> {
import { type GetServerSidePropsContext } from "next"; import { getServerSession, type NextAuthOptions, type DefaultSession, } from "next-auth"; import AzureADProvider from "next-auth/providers/azure-ad"; import { PrismaAdapter } from "@next-auth/prisma-adapter"; import { env } from "~/env.mjs"; import { prisma } from "~/server/db"; /** * Module augmentation for `next-auth` types. Allows us to add custom properties to the `session` * object and keep type safety. * * @see https://next-auth.js.org/getting-started/typescript#module-augmentation */ declare module "next-auth" { interface Session extends DefaultSession { user: { id: string; // ...other properties // role: UserRole; } & DefaultSession["user"]; } // interface User { // // ...other properties // // role: UserRole; // } } /** * Options for NextAuth.js used to configure adapters, providers, callbacks, etc. * * @see https://next-auth.js.org/configuration/options */ export const authOptions: NextAuthOptions = { callbacks: { session({ session, user }) { if (session.user) { session.user.id = user.id; // session.user.role = user.role; <-- put other properties on the session here } return session; }, },
adapter: PrismaAdapter(prisma), providers: [ AzureADProvider({
clientId: env.AZURE_CLIENT_ID, clientSecret: env.AZURE_CLIENT_SECRET, }), /** * ...add more providers here. * * Most other providers require a bit more work than the Discord provider. For example, the * GitHub provider requires you to add the `refresh_token_expires_in` field to the Account * model. Refer to the NextAuth.js docs for the provider you want to use. Example: * * @see https://next-auth.js.org/providers/github */ ], }; /** * Wrapper for `getServerSession` so that you don't need to import the `authOptions` in every file. * * @see https://next-auth.js.org/configuration/nextjs */ export const getServerAuthSession = (ctx: { req: GetServerSidePropsContext["req"]; res: GetServerSidePropsContext["res"]; }) => { return getServerSession(ctx.req, ctx.res, authOptions); };
src/server/auth.ts
cloudnothings-better-gpt-f1ad4fa
[ { "filename": "src/server/api/trpc.ts", "retrieved_chunk": " return next({\n ctx: {\n // infers the `session` as non-nullable\n session: { ...ctx.session, user: ctx.session.user },\n },\n });\n});\n/**\n * Protected (authenticated) procedure\n *", "score": 61.523465359287414 }, { "filename": "src/server/api/trpc.ts", "retrieved_chunk": " * This is the base piece you use to build new queries and mutations on your tRPC API. It does not\n * guarantee that a user querying is authorized, but you can still access user session data if they\n * are logged in.\n */\nexport const publicProcedure = t.procedure;\n/** Reusable middleware that enforces users are logged in before running the procedure. */\nconst enforceUserIsAuthed = t.middleware(({ ctx, next }) => {\n if (!ctx.session || !ctx.session.user) {\n throw new TRPCError({ code: \"UNAUTHORIZED\" });\n }", "score": 51.0647730940305 }, { "filename": "src/server/api/trpc.ts", "retrieved_chunk": " * If you want a query or mutation to ONLY be accessible to logged in users, use this. It verifies\n * the session is valid and guarantees `ctx.session.user` is not null.\n *\n * @see https://trpc.io/docs/procedures\n */\nexport const protectedProcedure = t.procedure.use(enforceUserIsAuthed);", "score": 39.805910133348284 }, { "filename": "src/components/ChatWindow/ChatWindow.tsx", "retrieved_chunk": " const [message, setMessage] = useState<string>(\"\")\n const sendMessage = () => {\n if (message.length > 0) {\n if (thread.messages.length === 0) {\n const id = uuid()\n const messages = [\n { role: 'system', content: thread.initialSystemInstruction },\n { role: 'user', content: message }\n ] as Message[]\n mutate({", "score": 31.51727527978148 }, { "filename": "src/server/api/trpc.ts", "retrieved_chunk": " * @see https://create.t3.gg/en/usage/trpc#-servertrpccontextts\n */\nconst createInnerTRPCContext = (opts: CreateContextOptions) => {\n return {\n session: opts.session,\n prisma,\n };\n};\n/**\n * This is the actual context you will use in your router. It will be used to process every request", "score": 31.35867827350158 } ]
typescript
adapter: PrismaAdapter(prisma), providers: [ AzureADProvider({
import { create } from "zustand"; import type { Model, Profile, Thread } from "~/types/appstate"; const models = [ { name: "GPT-3.5-TURBO", id: "gpt-3.5-turbo", description: "Most capable GPT-3.5 model and optimized for chat at 1/10th the cost of text-davinci-003. Will be updated with our latest model iteration.", maxTokens: 4096, usageCost: 0.002, trainingData: "Up to Sep 2021", }, { name: "GPT-3.5-TURBO-0301", id: "gpt-3.5-turbo-0301", description: "Snapshot of gpt-3.5-turbo from March 1st 2023. Unlike gpt-3.5-turbo, this model will not receive updates, and will only be supported for a three month period ending on June 1st 2023.", maxTokens: 4096, usageCost: 0.002, trainingData: "Up to Sep 2021", }, { name: "GPT-4 (Limited Beta)", id: "gpt-4", description: "More capable than any GPT-3.5 model, able to do more complex tasks, and optimized for chat. Will be updated with our latest model iteration.", maxTokens: 8192, promptCost: 0.03, completionCost: 0.06, trainingData: "Up to Sep 2021", note: "you need API Access to GPT-4 to use this model. If you haven't already, join the waitlist here: https://openai.com/waitlist/gpt-4-api", }, { name: "GPT-4-0314 (Limited Beta)", id: "gpt-4-0314", description: "Snapshot of gpt-4 from March 14th 2023. Unlike gpt-4, this model will not receive updates, and will only be supported for a three month period ending on June 14th 2023.", maxTokens: 8192, promptCost: 0.03, completionCost: 0.06, trainingData: "Up to Sep 2021", note: "you need API Access to GPT-4 to use this model. If you haven't already, join the waitlist here: https://openai.com/waitlist/gpt-4-api", }, { name: "GPT-4-32K (Limited Beta)", id: "gpt-4-32k", description: "Same capabilities as GPT-4, but with 4x the context length. Will be updated with our latest model iteration.", trainingData: "Up to Sep 2021", promptCost: 0.06, completionCost: 0.12, maxTokens: 32768, note: "you need API Access to GPT-4 to use this model. If you haven't already, join the waitlist here: https://openai.com/waitlist/gpt-4-api", }, { name: "GPT-4-32K-0314 (Limited Beta)", id: "gpt-4-32k-0314", description: "Snapshot of gpt-4-32k from March 14th 2023. Unlike gpt-4-32k, this model will not receive updates, and will only be supported for a three month period ending on June 14th 2023.", trainingData: "Up to Sep 2021", promptCost: 0.06, completionCost: 0.12, maxTokens: 32768, note: "you need API Access to GPT-4 to use this model. If you haven't already, join the waitlist here: https://openai.com/waitlist/gpt-4-api", }, ] as Model[]; const initialThread = { id: "", name: "", profileId: "", budget: 0, cost: 0, description: "", initialSystemInstruction: "", messages: [], model: models[0] as Model, starred: false, title: "",
} as Thread;
export const initialValues = { profile: { id: "", name: "", model: models[0] as Model, budget: 0, cost: 0, usage: { completion_tokens: 0, prompt_tokens: 0, total_tokens: 0, }, key: "", threadIds: [], organization: "", } as Profile, profiles: [] as Profile[], selectedProfile: "", thread: initialThread, threads: [] as Thread[], selectedApiKey: 0, apiKeyModal: false, apiKeyError: false, modelModal: false, models, width: 0, }; const getLocalProfileList = () => { const raw = localStorage.getItem("Profiles"); if (!raw) { return null; } return JSON.parse(raw) as string[]; }; const getSelectedProfile = () => { const raw = localStorage.getItem("SelectedProfile"); if (!raw) { return null; } return JSON.parse(raw) as string; }; export const getProfile = (id: string) => { const raw = localStorage.getItem("Profile_" + id); if (!raw) { return; } return JSON.parse(raw) as Profile; }; const loadProfiles = () => { const profileList = getLocalProfileList(); if (!profileList) { return null; } const selectedProfile = getSelectedProfile(); if (!selectedProfile) { return null; } const profiles: Profile[] = []; for (const id of profileList) { const profile = getProfile(id); if (!profile) { continue; } profiles.push(profile); } if (profiles.length === 0) { return null; } const profile = profiles.find((p) => p.id === selectedProfile); if (!profile) { const profile = profiles[0] as Profile; return { profiles, profile, selectedProfile: profile.id }; } return { profiles, profile, selectedProfile }; }; export const getThread = (id: string) => { const raw = localStorage.getItem("Thread_" + id); if (raw) { return JSON.parse(raw) as Thread; } }; export const loadData = () => { const profileData = loadProfiles(); if (!profileData) { return null; } const { profiles, profile, selectedProfile } = profileData; const threads = profile.threadIds .map((id) => getThread(id)) .filter((t) => t !== undefined) as Thread[]; return { profiles, profile, selectedProfile, threads }; }; interface Store { profile: Profile; setProfile: (value: Profile) => void; addProfile: (value: Profile) => void; deleteProfile: (value: Profile) => void; selectedProfile: string; setSelectedProfile: (value: string) => void; profiles: Profile[]; setProfiles: (value: Profile[]) => void; thread: Thread; setThread: (value: Thread) => void; addThread: (value: Thread) => void; deleteThread: (value: Thread) => void; threads: Thread[]; setThreads: (value: Thread[]) => void; apiKeyModal: boolean; setApiKeyModal: (value: boolean) => void; apiKeyError: boolean; setApiKeyError: (value: boolean) => void; models: Model[]; setModels: (value: Model[]) => void; modelModal: boolean; setModelModal: (value: boolean) => void; selectedApiKey: number; setSelectedApiKey: (value: number) => void; width: number; setWidth: (value: number) => void; resetValues: () => void; resetThread: () => void; load: () => void; } const updateSelectedProfile = (id: string) => { localStorage.setItem("SelectedProfile", JSON.stringify(id)); }; const updateProfile = (profile: Profile) => { localStorage.setItem("Profile_" + profile.id, JSON.stringify(profile)); }; const addProfile = (profile: Profile) => { localStorage.setItem("Profile_" + profile.id, JSON.stringify(profile)); const profileList = getLocalProfileList(); if (profileList) { localStorage.setItem( "Profiles", JSON.stringify([...profileList, profile.id]) ); } else { localStorage.setItem("Profiles", JSON.stringify([profile.id])); } }; const deleteProfile = (profile: Profile) => { profile.threadIds.forEach((id) => deleteThread(id)); localStorage.removeItem("Profile_" + profile.id); const profileList = getLocalProfileList(); if (profileList) { const newProfileList = profileList.filter((p) => p !== profile.id); localStorage.setItem("Profiles", JSON.stringify(newProfileList)); const selectedProfile = getSelectedProfile(); if (selectedProfile === profile.id) { localStorage.removeItem("SelectedProfile"); } if (newProfileList.length === 0) { localStorage.removeItem("Profiles"); } else { const newSelectedProfile = newProfileList[0]; localStorage.setItem( "SelectedProfile", JSON.stringify(newSelectedProfile) ); } } }; const updateThread = (thread: Thread) => { localStorage.setItem("Thread_" + thread.id, JSON.stringify(thread)); }; const deleteThread = (id: string) => { localStorage.removeItem("Thread_" + id); }; const useStore = create<Store>((set) => ({ ...initialValues, setProfiles: (value: Profile[]) => set({ profiles: value }), setProfile: (value: Profile) => { updateProfile(value); set({ profile: value }); }, addProfile: (value: Profile) => { addProfile(value); set((state) => ({ profiles: [...state.profiles, value] })); }, deleteProfile: (value: Profile) => { deleteProfile(value); set((state) => ({ profiles: state.profiles.filter((p) => p.id !== value.id), })); }, addThread: (value: Thread) => { updateThread(value); set((state) => ({ threads: [...state.threads, value], })); }, deleteThread: (value: Thread) => { deleteThread(value.id); set((state) => ({ threads: state.threads.filter((t) => t.id !== value.id), })); }, setSelectedProfile: (value: string) => { updateSelectedProfile(value); set({ selectedProfile: value }); }, setThread: (value: Thread) => { updateThread(value); set((state) => ({ thread: value, threads: [...state.threads, value] })); }, setThreads: (value: Thread[]) => { set({ threads: value }); }, setApiKeyModal: (value: boolean) => set({ apiKeyModal: value }), setApiKeyError: (value: boolean) => set({ apiKeyError: value }), setModels: (value: Model[]) => set({ models: value }), setModelModal: (value: boolean) => set({ modelModal: value }), setWidth: (value: number) => set({ width: value }), setSelectedApiKey: (value: number) => set({ selectedApiKey: value }), load: () => set({ ...initialValues, ...loadData() }), resetThread: () => set({ thread: initialValues.thread }), resetValues: () => set(initialValues), })); export default useStore;
src/store/store.ts
cloudnothings-better-gpt-f1ad4fa
[ { "filename": "src/types/appstate.ts", "retrieved_chunk": " initialSystemInstruction: string;\n title: string;\n description: string;\n starred: boolean;\n cost: number;\n budget: number;\n};", "score": 33.29302527543637 }, { "filename": "src/components/modals/ChangeModelModal.tsx", "retrieved_chunk": " setThread(({ ...thread, model: selectedModel, initialSystemInstruction: systemInstruction }) as Thread)\n setModelModal(false)\n }\n const cancelHandler = () => {\n setModelModal(false)\n setSelectedModel(thread.model)\n setSystemInstruction(thread.initialSystemInstruction)\n }\n return (\n <Transition.Root show={modelModal} as={Fragment}>", "score": 25.701510379635977 }, { "filename": "src/components/ChatWindow/ChatWindow.tsx", "retrieved_chunk": " title: 'New Chat',\n cost: thread.cost + cost,\n messages: [...thread.messages, { content: message, role: \"user\" },\n data.choices[0].message] as Message[]\n })\n setProfile({\n ...profile,\n cost: profile.cost + cost,\n usage: increaseUsage(profile.usage, data.usage),\n threadIds: [...profile.threadIds, id]", "score": 23.216421841999924 }, { "filename": "src/types/appstate.ts", "retrieved_chunk": " promptCost?: number;\n completionCost?: number;\n usageCost?: number;\n note?: string;\n}\nexport type Thread = {\n id: string;\n profileId: string;\n messages: Message[];\n model: Model;", "score": 21.250279121892767 }, { "filename": "src/components/ChatWindow/ChatWindow.tsx", "retrieved_chunk": " const cost = calculateCost(data.usage, thread.model)\n setThread({ ...thread, cost: thread.cost + cost, messages: [...thread.messages, { content: message, role: \"user\" }, data.choices[0].message] as Message[] })\n setProfile({ ...profile, cost: profile.cost + cost, usage: increaseUsage(profile.usage, data.usage) })\n setMessage(\"\")\n },\n onError: (e) => {\n alert(e.message)\n }\n })\n }", "score": 20.707407524227364 } ]
typescript
} as Thread;
import { create } from "zustand"; import type { Model, Profile, Thread } from "~/types/appstate"; const models = [ { name: "GPT-3.5-TURBO", id: "gpt-3.5-turbo", description: "Most capable GPT-3.5 model and optimized for chat at 1/10th the cost of text-davinci-003. Will be updated with our latest model iteration.", maxTokens: 4096, usageCost: 0.002, trainingData: "Up to Sep 2021", }, { name: "GPT-3.5-TURBO-0301", id: "gpt-3.5-turbo-0301", description: "Snapshot of gpt-3.5-turbo from March 1st 2023. Unlike gpt-3.5-turbo, this model will not receive updates, and will only be supported for a three month period ending on June 1st 2023.", maxTokens: 4096, usageCost: 0.002, trainingData: "Up to Sep 2021", }, { name: "GPT-4 (Limited Beta)", id: "gpt-4", description: "More capable than any GPT-3.5 model, able to do more complex tasks, and optimized for chat. Will be updated with our latest model iteration.", maxTokens: 8192, promptCost: 0.03, completionCost: 0.06, trainingData: "Up to Sep 2021", note: "you need API Access to GPT-4 to use this model. If you haven't already, join the waitlist here: https://openai.com/waitlist/gpt-4-api", }, { name: "GPT-4-0314 (Limited Beta)", id: "gpt-4-0314", description: "Snapshot of gpt-4 from March 14th 2023. Unlike gpt-4, this model will not receive updates, and will only be supported for a three month period ending on June 14th 2023.", maxTokens: 8192, promptCost: 0.03, completionCost: 0.06, trainingData: "Up to Sep 2021", note: "you need API Access to GPT-4 to use this model. If you haven't already, join the waitlist here: https://openai.com/waitlist/gpt-4-api", }, { name: "GPT-4-32K (Limited Beta)", id: "gpt-4-32k", description: "Same capabilities as GPT-4, but with 4x the context length. Will be updated with our latest model iteration.", trainingData: "Up to Sep 2021", promptCost: 0.06, completionCost: 0.12, maxTokens: 32768, note: "you need API Access to GPT-4 to use this model. If you haven't already, join the waitlist here: https://openai.com/waitlist/gpt-4-api", }, { name: "GPT-4-32K-0314 (Limited Beta)", id: "gpt-4-32k-0314", description: "Snapshot of gpt-4-32k from March 14th 2023. Unlike gpt-4-32k, this model will not receive updates, and will only be supported for a three month period ending on June 14th 2023.", trainingData: "Up to Sep 2021", promptCost: 0.06, completionCost: 0.12, maxTokens: 32768, note: "you need API Access to GPT-4 to use this model. If you haven't already, join the waitlist here: https://openai.com/waitlist/gpt-4-api", }, ] as Model[]; const initialThread = { id: "", name: "", profileId: "", budget: 0, cost: 0, description: "", initialSystemInstruction: "", messages: [], model: models[0] as Model, starred: false, title: "", } as Thread; export const initialValues = { profile: { id: "", name: "", model: models[0] as Model, budget: 0, cost: 0, usage: { completion_tokens: 0, prompt_tokens: 0, total_tokens: 0, }, key: "", threadIds: [], organization: "", } as Profile, profiles: [] as Profile[], selectedProfile: "", thread: initialThread, threads: [] as Thread[], selectedApiKey: 0, apiKeyModal: false, apiKeyError: false, modelModal: false, models, width: 0, }; const getLocalProfileList = () => { const raw = localStorage.getItem("Profiles"); if (!raw) { return null; } return JSON.parse(raw) as string[]; }; const getSelectedProfile = () => { const raw = localStorage.getItem("SelectedProfile"); if (!raw) { return null; } return JSON.parse(raw) as string; }; export const getProfile = (id: string) => { const raw = localStorage.getItem("Profile_" + id); if (!raw) { return; } return JSON.parse(raw) as Profile; }; const loadProfiles = () => { const profileList = getLocalProfileList(); if (!profileList) { return null; } const selectedProfile = getSelectedProfile(); if (!selectedProfile) { return null; } const profiles: Profile[] = []; for (const id of profileList) { const profile = getProfile(id); if (!profile) { continue; } profiles.push(profile); } if (profiles.length === 0) { return null; } const profile = profiles.find((p) => p.id === selectedProfile); if (!profile) { const profile = profiles[0] as Profile; return { profiles, profile, selectedProfile: profile.id }; } return { profiles, profile, selectedProfile }; }; export const getThread = (id: string) => { const raw = localStorage.getItem("Thread_" + id); if (raw) { return JSON.parse(raw) as Thread; } }; export const loadData = () => { const profileData = loadProfiles(); if (!profileData) { return null; } const { profiles, profile, selectedProfile } = profileData; const threads = profile.threadIds .
map((id) => getThread(id)) .filter((t) => t !== undefined) as Thread[];
return { profiles, profile, selectedProfile, threads }; }; interface Store { profile: Profile; setProfile: (value: Profile) => void; addProfile: (value: Profile) => void; deleteProfile: (value: Profile) => void; selectedProfile: string; setSelectedProfile: (value: string) => void; profiles: Profile[]; setProfiles: (value: Profile[]) => void; thread: Thread; setThread: (value: Thread) => void; addThread: (value: Thread) => void; deleteThread: (value: Thread) => void; threads: Thread[]; setThreads: (value: Thread[]) => void; apiKeyModal: boolean; setApiKeyModal: (value: boolean) => void; apiKeyError: boolean; setApiKeyError: (value: boolean) => void; models: Model[]; setModels: (value: Model[]) => void; modelModal: boolean; setModelModal: (value: boolean) => void; selectedApiKey: number; setSelectedApiKey: (value: number) => void; width: number; setWidth: (value: number) => void; resetValues: () => void; resetThread: () => void; load: () => void; } const updateSelectedProfile = (id: string) => { localStorage.setItem("SelectedProfile", JSON.stringify(id)); }; const updateProfile = (profile: Profile) => { localStorage.setItem("Profile_" + profile.id, JSON.stringify(profile)); }; const addProfile = (profile: Profile) => { localStorage.setItem("Profile_" + profile.id, JSON.stringify(profile)); const profileList = getLocalProfileList(); if (profileList) { localStorage.setItem( "Profiles", JSON.stringify([...profileList, profile.id]) ); } else { localStorage.setItem("Profiles", JSON.stringify([profile.id])); } }; const deleteProfile = (profile: Profile) => { profile.threadIds.forEach((id) => deleteThread(id)); localStorage.removeItem("Profile_" + profile.id); const profileList = getLocalProfileList(); if (profileList) { const newProfileList = profileList.filter((p) => p !== profile.id); localStorage.setItem("Profiles", JSON.stringify(newProfileList)); const selectedProfile = getSelectedProfile(); if (selectedProfile === profile.id) { localStorage.removeItem("SelectedProfile"); } if (newProfileList.length === 0) { localStorage.removeItem("Profiles"); } else { const newSelectedProfile = newProfileList[0]; localStorage.setItem( "SelectedProfile", JSON.stringify(newSelectedProfile) ); } } }; const updateThread = (thread: Thread) => { localStorage.setItem("Thread_" + thread.id, JSON.stringify(thread)); }; const deleteThread = (id: string) => { localStorage.removeItem("Thread_" + id); }; const useStore = create<Store>((set) => ({ ...initialValues, setProfiles: (value: Profile[]) => set({ profiles: value }), setProfile: (value: Profile) => { updateProfile(value); set({ profile: value }); }, addProfile: (value: Profile) => { addProfile(value); set((state) => ({ profiles: [...state.profiles, value] })); }, deleteProfile: (value: Profile) => { deleteProfile(value); set((state) => ({ profiles: state.profiles.filter((p) => p.id !== value.id), })); }, addThread: (value: Thread) => { updateThread(value); set((state) => ({ threads: [...state.threads, value], })); }, deleteThread: (value: Thread) => { deleteThread(value.id); set((state) => ({ threads: state.threads.filter((t) => t.id !== value.id), })); }, setSelectedProfile: (value: string) => { updateSelectedProfile(value); set({ selectedProfile: value }); }, setThread: (value: Thread) => { updateThread(value); set((state) => ({ thread: value, threads: [...state.threads, value] })); }, setThreads: (value: Thread[]) => { set({ threads: value }); }, setApiKeyModal: (value: boolean) => set({ apiKeyModal: value }), setApiKeyError: (value: boolean) => set({ apiKeyError: value }), setModels: (value: Model[]) => set({ models: value }), setModelModal: (value: boolean) => set({ modelModal: value }), setWidth: (value: number) => set({ width: value }), setSelectedApiKey: (value: number) => set({ selectedApiKey: value }), load: () => set({ ...initialValues, ...loadData() }), resetThread: () => set({ thread: initialValues.thread }), resetValues: () => set(initialValues), })); export default useStore;
src/store/store.ts
cloudnothings-better-gpt-f1ad4fa
[ { "filename": "src/pages/index.tsx", "retrieved_chunk": " const threads = profile.threadIds.map((id) => {\n return getThread(id)\n }) as Thread[]\n setThreads(threads)\n }\n }\n }\n }, [selectedProfile, setProfile, setThreads]);\n return (\n <>", "score": 50.52775795523536 }, { "filename": "src/pages/index.tsx", "retrieved_chunk": " if (data.threads) {\n setThreads(data.threads)\n }\n }, [setProfile, setProfiles, setThreads, setSelectedProfile]);\n useEffect(() => {\n if (selectedProfile) {\n const profile = getProfile(selectedProfile)\n if (profile) {\n setProfile(profile)\n if (profile.threadIds) {", "score": 30.860943804079607 }, { "filename": "src/pages/index.tsx", "retrieved_chunk": " }\n const deleteThread = useStore((state) => state.deleteThread)\n const [deleting, setDeleting] = useState(false)\n const deleteHandler: MouseEventHandler<HTMLButtonElement> = (e) => {\n e.stopPropagation()\n deleteThread({ ...props })\n setProfile({ ...profile, threadIds: profile.threadIds.filter(id => id !== props.id) })\n }\n const selectHandler = () => {\n if (props.selected) return", "score": 29.039970688316263 }, { "filename": "src/pages/index.tsx", "retrieved_chunk": " const deleteThread = useStore((state) => state.deleteThread)\n const [deleting, setDeleting] = useState(false)\n const deleteHandler: MouseEventHandler<HTMLButtonElement> = (e) => {\n e.stopPropagation()\n deleteThread({ ...props })\n setProfile({ ...profile, threadIds: profile.threadIds.filter(id => id !== props.id) })\n }\n const selectHandler = () => {\n if (props.selected) return\n setThread({ ...props })", "score": 28.627877269976814 }, { "filename": "src/pages/index.tsx", "retrieved_chunk": " }\n if (data.selectedProfile) {\n setSelectedProfile(data.selectedProfile)\n }\n if (data.profile) {\n setProfile(data.profile)\n }\n if (data.profiles) {\n setProfiles(data.profiles)\n }", "score": 26.846321930846166 } ]
typescript
map((id) => getThread(id)) .filter((t) => t !== undefined) as Thread[];
import { AuthenticationFields, AuthenticationResponse, RequestRefreshTokenOptions, NonceHashOptions, API, Endpoints, AccessToken, PreBuiltAuthenticationToken } from '../types'; import axios, { AxiosProxyConfig, AxiosResponse } from 'axios'; import { createHmac } from 'node:crypto'; import KretaError from './errors/KretaError'; import requireParam from '../decorators/requireParam'; import tryRequest from '../utils/tryRequest'; import requireCredentials from '../decorators/requireCredentials'; export class Authentication { private readonly username: string; private readonly password: string; private readonly institute_code: string; private readonly client_id: string = 'kreta-ellenorzo-mobile-android'; private readonly grant_type: string = 'password'; private readonly auth_policy_version: string = 'v2'; constructor(options: AuthenticationFields) { this.username = options.username; this.password = options.password; this.institute_code = options.institute_code; } public get _username() { return this.username; } public get _password() { return this.password; } public get _institute_code() { return this.institute_code; } @requireParam('proxy.host') @requireParam('proxy.port') public setProxy(proxy: AxiosProxyConfig): this { axios.defaults.proxy = proxy; return this; } @requireParam('ua') public setUserAgent(ua: string): this { axios.defaults.headers.common['User-Agent'] = ua; return this; }; @requireCredentials private authenticate(options: AuthenticationFields): Promise<AuthenticationResponse> { return new Promise(async (resolve): Promise<void> => { const nonce_key: string = await this.getNonce(); const hash: string = await this.getNonceHash({ nonce: nonce_key, institute_code: options.institute_code, username: options.username });
await tryRequest(axios.post(API.IDP + Endpoints.Token, {
institute_code: options.institute_code, username: options.username, password: options.password, grant_type: this.grant_type, client_id: this.client_id }, { headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'X-Authorizationpolicy-Nonce': nonce_key, 'X-Authorizationpolicy-Key': hash, 'X-Authorizationpolicy-Version': this.auth_policy_version, } }).then((r: AxiosResponse<AuthenticationResponse>) => resolve(r.data))); }); } private getNonce(): Promise<string> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(API.IDP + Endpoints.Nonce).then((r: AxiosResponse<string>) => resolve(r.data.toString()))); }); } private getNonceHash(options: NonceHashOptions): Promise<string> { return new Promise((resolve): void => { const buffer_bytes: Buffer = Buffer.from(options.institute_code.toUpperCase() + options.nonce + options.username.toUpperCase(), 'utf8'); const hash: Buffer = createHmac('sha512', Buffer.from([98, 97, 83, 115, 120, 79, 119, 108, 85, 49, 106, 77])).update(buffer_bytes).digest(); return resolve(hash.toString('base64')); }); } private async returnTokens(): Promise<AccessToken> { return await this.authenticate({ username: this.username, password: this.password, institute_code: this.institute_code }).then((r: AuthenticationResponse): AccessToken => { return { access_token: r.access_token, refresh_token: r.refresh_token, token_type: r.token_type }; }).catch((): { access_token: null; refresh_token: null; token_type: null } => { return { access_token: null, refresh_token: null, token_type: null }; }); } public getAccessToken(): Promise<PreBuiltAuthenticationToken> { return new Promise(async (resolve, reject): Promise<void> => { const { access_token, refresh_token }: AccessToken = await this.returnTokens(); if (access_token === null || refresh_token === null) return reject(new KretaError('Failed to get access token: Invalid credentials')); else return resolve({ token: 'Bearer' + ' ' + access_token, access_token, refresh_token }); }); } @requireParam('options.refreshToken') @requireParam('options.refreshUserData') public getRefreshToken(options: RequestRefreshTokenOptions): Promise<AuthenticationResponse> { return new Promise(async (resolve): Promise<void> => { const nonce_key: string = await this.getNonce(); const hash: string = await this.getNonceHash({ nonce: nonce_key, institute_code: this.institute_code, username: this.username }); await tryRequest(axios.post(API.IDP + Endpoints.Token, { refresh_token: options.refreshToken, institute_code: this.institute_code, grant_type: 'refresh_token', client_id: this.client_id, refresh_user_data: options.refreshUserData }, { headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'X-Authorizationpolicy-Key': hash, 'X-Authorizationpolicy-Version': this.auth_policy_version, } }).then((r: AxiosResponse<AuthenticationResponse>) => resolve(r.data) )); }); } }
src/lib/Authentication.ts
blazsmaster-kreta.js-9274c52
[ { "filename": "src/lib/Administration.ts", "retrieved_chunk": "\tprivate token?: Promise<string>;\n\tconstructor(options: AuthenticationFields) {\n\t\tthis.username = options.username;\n\t\tthis.password = options.password;\n\t\tthis.institute_code = options.institute_code;\n\t\tthis.authenticate = new Authentication({ username: this.username, password: this.password, institute_code: this.institute_code });\n\t\tif (this.username && this.password && this.institute_code)\n\t\t\tthis.token = this.authenticate.getAccessToken().then((r: PreBuiltAuthenticationToken) => r.token);\n\t\taxios.defaults.headers['X-Uzenet-Lokalizacio'] = 'hu-HU';\n\t}", "score": 38.779710944490795 }, { "filename": "src/lib/Kreta.ts", "retrieved_chunk": "\tprivate readonly username?: string;\n\tprivate readonly password?: string;\n\tprivate readonly institute_code?: string;\n\tprivate authenticate?: Authentication;\n\tpublic Administration?: Administration;\n\tpublic Global: Global;\n\tprivate token?: Promise<string>;\n\tconstructor(options?: KretaOptions) {\n\t\tthis.username = options?.username || '';\n\t\tthis.password = options?.password || '';", "score": 36.67041617075516 }, { "filename": "src/types.ts", "retrieved_chunk": "\tGlobalMobileApiUrlTEST: string;\n\tGlobalMobileApiUrlUAT: string;\n}\nexport interface NonceHashOptions {\n\tinstitute_code: string;\n\tnonce: string;\n\tusername: string;\n}\nexport interface AuthenticationFields {\n\tinstitute_code: string;", "score": 27.621943735125384 }, { "filename": "src/lib/Kreta.ts", "retrieved_chunk": "\t\tthis.institute_code = options?.institute_code || '';\n\t\taxios.defaults.headers.common['User-Agent'] = 'hu.ekreta.student/1.0.5/Android/0/0';\n\t\tthis.Global = new Global();\n\t\tthis.authenticate = new Authentication({ username: this.username!, password: this.password!, institute_code: this.institute_code! });\n\t\tif (this.username && this.password && this.institute_code)\n\t\t\tthis.token = this.authenticate.getAccessToken().then((r: PreBuiltAuthenticationToken) => r.token);\n\t\tthis.Administration = new Administration({ username: this.username!, password: this.password!, institute_code: this.institute_code! });\n\t}\n\tpublic get _username() {\n\t\treturn this.username;", "score": 26.86194587301613 }, { "filename": "src/lib/Kreta.ts", "retrieved_chunk": "\t@requireCredentials\n\t@requireParam('options.dateFrom')\n\tpublic getHomeworks(options: RequestHomeWorkOptions): Promise<Homework[]> {\n\t\treturn new Promise(async (resolve): Promise<void> => {\n\t\t\tconst ops: { datumTol: string; datumIg?: string } = { datumTol: validateDate(moment(options.dateFrom).format('YYYY-MM-DD')) };\n\t\t\tif (options?.dateTo)\n\t\t\t\tops.datumIg = validateDate(moment(options.dateTo).format('YYYY-MM-DD'));\n\t\t\tawait tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.HaziFeladatok, ops), {\n\t\t\t\theaders: {\n\t\t\t\t\t'Authorization': await this.token,", "score": 23.32961798420716 } ]
typescript
await tryRequest(axios.post(API.IDP + Endpoints.Token, {
import axios, { AxiosResponse } from 'axios'; import { AddresseType, AuthenticationFields, CardEvent, CurrentInstitutionDetails, DefaultType, EmployeeDetails, GuardianEAdmin, KretaClass, MailboxItem, MessageLimitations, PreBuiltAuthenticationToken, API, AdministrationEndpoints } from '../types'; import { Authentication } from './Authentication'; import requireCredentials from '../decorators/requireCredentials'; import tryRequest from '../utils/tryRequest'; import requireParam from '../decorators/requireParam'; export default class Administration { private readonly username: string; private readonly password: string; private readonly institute_code: string; private authenticate: Authentication; private token?: Promise<string>; constructor(options: AuthenticationFields) { this.username = options.username; this.password = options.password; this.institute_code = options.institute_code; this.authenticate = new Authentication({ username: this.username, password: this.password, institute_code: this.institute_code }); if (this.username && this.password && this.institute_code) this.token = this.authenticate.getAccessToken().then((r: PreBuiltAuthenticationToken) => r.token); axios.defaults.headers['X-Uzenet-Lokalizacio'] = 'hu-HU'; } public get _username() { return this.username; } public get _password() { return this.password; } public get _institute_code() { return this.institute_code; } private buildUgyintezesApiURL(endpointWithSlash: AdministrationEndpoints, params?: { [key: string]: any }): string { const urlParams: string = params ? '?' + new URLSearchParams(params).toString() : ''; return API.ADMINISTRATION + '/api/v1' + endpointWithSlash + urlParams; } @requireCredentials public getAddresseeType(): Promise<AddresseType[]> { return new Promise(async (resolve): Promise<void> => { await
tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.CimzettTipusok), {
headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<AddresseType[]>) => resolve(r.data))); }); } @requireCredentials public getCaseTypes(): Promise<DefaultType[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.KerelemTipusok), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<DefaultType[]>) => resolve(r.data))); }); } @requireCredentials public getTmgiCaseTypes(): Promise<DefaultType[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.TmgiIgazolasTipusok), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<DefaultType[]>) => resolve(r.data))); }); } @requireCredentials public getAccessControlSystemEvents(): Promise<CardEvent[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.Esemenyek), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<CardEvent[]>) => resolve(r.data))); }); } @requireCredentials public getCurrentInstitutionModules(): Promise<string[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.JelenlegiIntezmenyModulok), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<string[]>) => resolve(r.data))); }); } @requireCredentials public getAddressableType(): Promise<AddresseType[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.CimezhetoTipusok), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<AddresseType[]>) => resolve(r.data))); }); } @requireCredentials @requireParam('addressId') public getAddressableClasses(addressId: string | number): Promise<KretaClass[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.CimezhetoOsztalyok, { cimzettKod: addressId.toString() }), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<KretaClass[]>) => resolve(r.data))); }); } @requireCredentials public getUnreadMessagesCount(): Promise<number> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.OlvasatlanokSzama), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<number>) => resolve(r.data))); }); } @requireCredentials public getMessages(): Promise<MailboxItem[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.Uzenetek), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<MailboxItem[]>) => resolve(r.data))); }); } @requireCredentials @requireParam('id') public getMessage(id: string | number): Promise<MailboxItem> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.Uzenet) + '/' + id.toString(), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<MailboxItem>) => resolve(r.data))); }); } @requireCredentials public getAddressableSzmkRepesentative(): Promise<GuardianEAdmin[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.CimezhetoSzmkKepviselok), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<GuardianEAdmin[]>) => resolve(r.data))); }); } @requireCredentials public getMessageLimitations(): Promise<MessageLimitations> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.UzenetLimitacio), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<MessageLimitations>) => resolve(r.data))); }); } @requireCredentials public getAdministrators(): Promise<EmployeeDetails[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.Adminisztratorok), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<EmployeeDetails[]>) => resolve(r.data))); }); } @requireCredentials public getDirectors(): Promise<EmployeeDetails[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.Igazgatok), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<EmployeeDetails[]>) => resolve(r.data))); }); } @requireCredentials public getClassMasters(): Promise<EmployeeDetails[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.Osztalyfonokok), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<EmployeeDetails[]>) => resolve(r.data))); }); } @requireCredentials public getTeachers(): Promise<EmployeeDetails[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.Oktatok), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<EmployeeDetails[]>) => resolve(r.data))); }); } @requireCredentials @requireParam('classId') public getAddressableGuardiansForClass(classId: string | number): Promise<GuardianEAdmin[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.CimezhetoTanuloSzulok) + '/' + classId.toString(), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<GuardianEAdmin[]>) => resolve(r.data))); }); } @requireCredentials public getCurrentInstitutionDetails(): Promise<CurrentInstitutionDetails> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.JelenlegiIntezmeny), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<CurrentInstitutionDetails>) => resolve(r.data))); }); } }
src/lib/Administration.ts
blazsmaster-kreta.js-9274c52
[ { "filename": "src/lib/Kreta.ts", "retrieved_chunk": "\t\taxios.defaults.proxy = proxy;\n\t\treturn this;\n\t}\n\t@requireParam('ua')\n\tpublic setUserAgent(ua: string): this {\n\t\taxios.defaults.headers.common['User-Agent'] = ua;\n\t\treturn this;\n\t}\n\tprivate buildEllenorzoApiURL(endpointWithSlash: Endpoints, params?: { [key: string]: any }): string {\n\t\tconst urlParams: string = params ? '?' + new URLSearchParams(params).toString() : '';", "score": 60.61944244776878 }, { "filename": "src/lib/Kreta.ts", "retrieved_chunk": "\t\treturn dynamicValue(API.INSTITUTE, { institute_code: this.institute_code }).toString() + '/ellenorzo/V3' + endpointWithSlash + urlParams;\n\t}\n\t@requireParam('api_key')\n\tpublic getInstituteList(api_key: string): Promise<Institute[]> {\n\t\treturn new Promise(async (resolve): Promise<void> => {\n\t\t\tconst config_descriptor: AxiosResponse<ConfigurationDescriptor> = await axios.get('https://kretamobile.blob.core.windows.net/configuration/ConfigurationDescriptor.json');\n\t\t\tawait tryRequest(axios.get(config_descriptor.data.GlobalMobileApiUrlPROD + '/api/v3/Institute', {\n\t\t\t\theaders: {\n\t\t\t\t\tapiKey: api_key\n\t\t\t\t}", "score": 34.97792864996776 }, { "filename": "src/lib/Authentication.ts", "retrieved_chunk": "\t}\n\t@requireParam('ua')\n\tpublic setUserAgent(ua: string): this {\n\t\taxios.defaults.headers.common['User-Agent'] = ua;\n\t\treturn this;\n\t};\n\t@requireCredentials\n\tprivate authenticate(options: AuthenticationFields): Promise<AuthenticationResponse> {\n\t\treturn new Promise(async (resolve): Promise<void> => {\n\t\t\tconst nonce_key: string = await this.getNonce();", "score": 23.717794837253283 }, { "filename": "src/lib/Authentication.ts", "retrieved_chunk": "\t}\n\tprivate getNonce(): Promise<string> {\n\t\treturn new Promise(async (resolve): Promise<void> => {\n\t\t\tawait tryRequest(axios.get(API.IDP + Endpoints.Nonce).then((r: AxiosResponse<string>) => resolve(r.data.toString())));\n\t\t});\n\t}\n\tprivate getNonceHash(options: NonceHashOptions): Promise<string> {\n\t\treturn new Promise((resolve): void => {\n\t\t\tconst buffer_bytes: Buffer = Buffer.from(options.institute_code.toUpperCase() + options.nonce + options.username.toUpperCase(), 'utf8');\n\t\t\tconst hash: Buffer = createHmac('sha512', Buffer.from([98, 97, 83, 115, 120, 79, 119, 108, 85, 49, 106, 77])).update(buffer_bytes).digest();", "score": 23.683092224513633 }, { "filename": "src/lib/Kreta.ts", "retrieved_chunk": "\t\t});\n\t}\n\t@requireCredentials\n\t@requireParam('uids')\n\tpublic getClassMasters(uids: string[] | number[]): Promise<ClassMaster[]> {\n\t\treturn new Promise(async (resolve): Promise<void> => {\n\t\t\tawait tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.Osztalyfonokok, { Uids: uids.map((u: string | number) => u.toString()).join(';') }), {\n\t\t\t\theaders: {\n\t\t\t\t\t'Authorization': await this.token,\n\t\t\t\t}", "score": 23.05208696688651 } ]
typescript
tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.CimzettTipusok), {
import axios, { AxiosProxyConfig, AxiosResponse } from 'axios'; import moment from 'moment'; import { AnnouncedTest, ClassAverage, ClassMaster, ConfigurationDescriptor, Evaluation, Group, Homework, Institute, Institution, KretaOptions, LepEvent, Lesson, Note, NoticeBoardItem, Omission, PreBuiltAuthenticationToken, RequestAnnouncedTestsOptions, RequestClassAveragesOptions, RequestDateRangeOptions, RequestDateRangeRequiredOptions, RequestHomeWorkOptions, SchoolYearCalendarEntry, Student, SubjectAverage, TimeTableWeek, API, Endpoints } from '../types'; import { Authentication } from './Authentication'; import dynamicValue from '../utils/dynamicValue'; import Administration from './Administration'; import Global from './Global'; import requireCredentials from '../decorators/requireCredentials'; import tryRequest from '../utils/tryRequest'; import validateDate from '../utils/validateDate'; import requireParam from '../decorators/requireParam'; export default class Kreta { private readonly username?: string; private readonly password?: string; private readonly institute_code?: string; private authenticate?: Authentication; public Administration?: Administration; public Global: Global; private token?: Promise<string>; constructor(options?: KretaOptions) { this.username = options?.username || ''; this.password = options?.password || ''; this.institute_code = options?.institute_code || ''; axios.defaults.headers.common['User-Agent'] = 'hu.ekreta.student/1.0.5/Android/0/0'; this.Global = new Global(); this.authenticate = new Authentication({ username: this.username!, password: this.password!, institute_code: this.institute_code! }); if (this.username && this.password && this.institute_code) this.token = this.authenticate.getAccessToken().then((r: PreBuiltAuthenticationToken) => r.token); this.Administration = new Administration({ username: this.username!, password: this.password!, institute_code: this.institute_code! }); } public get _username() { return this.username; } public get _password() { return this.password; } public get _institute_code() { return this.institute_code; } @requireParam('proxy.host') @requireParam('proxy.port') public setProxy(proxy: AxiosProxyConfig): this { axios.defaults.proxy = proxy; return this; } @requireParam('ua') public setUserAgent(ua: string): this { axios.defaults.headers.common['User-Agent'] = ua; return this; } private buildEllenorzoApiURL(endpointWithSlash: Endpoints, params?: { [key: string]: any }): string { const urlParams: string = params ? '?' + new URLSearchParams(params).toString() : ''; return dynamicValue(API.INSTITUTE, { institute_code: this.institute_code }).toString() + '/ellenorzo/V3' + endpointWithSlash + urlParams; } @requireParam('api_key') public getInstituteList(api_key: string): Promise<Institute[]> { return new Promise(async (resolve): Promise<void> => { const config_descriptor: AxiosResponse<ConfigurationDescriptor> = await axios.get('https://kretamobile.blob.core.windows.net/configuration/ConfigurationDescriptor.json'); await tryRequest(axios.get(config_descriptor.data.GlobalMobileApiUrlPROD + '/api/v3/Institute', { headers: { apiKey: api_key } }).then((r: AxiosResponse<Institute[]>) => resolve(r.data))); }); } @requireCredentials public getStudent(): Promise<Student> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.Tanulo), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Student>) => resolve(r.data))); }); } @requireCredentials public getEvaluations(options?: RequestDateRangeOptions): Promise<Evaluation[]> { return new Promise(async (resolve): Promise<void> => { const ops: { datumTol?: string; datumIg?: string } = {}; if (options?.dateFrom) ops.
datumTol = validateDate(moment(options.dateFrom).format('YYYY-MM-DD'));
if (options?.dateTo) ops.datumIg = validateDate(moment(options.dateTo).format('YYYY-MM-DD')); await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.Ertekelesek, ops), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Evaluation[]>) => resolve(r.data))); }); } @requireCredentials public getNotes(options?: RequestDateRangeOptions): Promise<Note[]> { return new Promise(async (resolve): Promise<void> => { const ops: { datumTol?: string; datumIg?: string } = {}; if (options?.dateFrom) ops.datumTol = validateDate(moment(options.dateFrom).format('YYYY-MM-DD')); if (options?.dateTo) ops.datumIg = validateDate(moment(options.dateTo).format('YYYY-MM-DD')); await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.Feljegyzesek, ops), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Note[]>) => resolve(r.data))); }); } @requireCredentials public getAnnouncedTests(options?: RequestAnnouncedTestsOptions): Promise<AnnouncedTest[]> { return new Promise(async (resolve): Promise<void> => { const ops: { datumTol?: string; datumIg?: string, Uids?: string } = {}; if (options?.dateFrom) ops.datumTol = validateDate(moment(options.dateFrom).format('YYYY-MM-DD')); if (options?.dateTo) ops.datumIg = validateDate(moment(options.dateTo).format('YYYY-MM-DD')); if (options?.uids) ops.Uids = options.uids.map((uid: string | number) => uid.toString()).join(';'); await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.Szamonkeresek, ops), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<AnnouncedTest[]>) => resolve(r.data))); }); } @requireCredentials @requireParam('options.dateFrom') public getHomeworks(options: RequestHomeWorkOptions): Promise<Homework[]> { return new Promise(async (resolve): Promise<void> => { const ops: { datumTol: string; datumIg?: string } = { datumTol: validateDate(moment(options.dateFrom).format('YYYY-MM-DD')) }; if (options?.dateTo) ops.datumIg = validateDate(moment(options.dateTo).format('YYYY-MM-DD')); await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.HaziFeladatok, ops), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Homework[]>) => resolve(r.data))); }); } @requireCredentials @requireParam('uid') public getHomework(uid: string | number): Promise<Homework> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.HaziFeladatok) + '/' + uid.toString(), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Homework>) => resolve(r.data))); }); } @requireCredentials public getOmissions(options?: RequestDateRangeOptions): Promise<Omission[]> { return new Promise(async (resolve): Promise<void> => { const ops: { datumTol?: string; datumIg?: string } = {}; if (options?.dateFrom) ops.datumTol = validateDate(moment(options.dateFrom).format('YYYY-MM-DD')); if (options?.dateTo) ops.datumIg = validateDate(moment(options.dateTo).format('YYYY-MM-DD')); await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.Mulasztasok, ops), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Omission[]>) => resolve(r.data))); }); } @requireCredentials public getGroups(): Promise<Group[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.OsztalyCsoportok), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Group[]>) => resolve(r.data))); }); } @requireCredentials public getSubjectAverages(onfUid?: string): Promise<SubjectAverage[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.TantargyiAtlagok, { oktatasiNevelesiFeladatUid: onfUid || await this.getGroups().then((groups: Group[]) => groups[0].OktatasNevelesiFeladat.Uid) }), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<SubjectAverage[]>) => resolve(r.data))); }); } @requireCredentials @requireParam('options.dateFrom') @requireParam('options.dateTo') public getLessons(options: RequestDateRangeRequiredOptions): Promise<Lesson[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.OrarendElemek, { datumTol: validateDate(moment(options.dateFrom).format('YYYY-MM-DD')), datumIg: validateDate(moment(options.dateTo).format('YYYY-MM-DD')) }), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Lesson[]>) => resolve(r.data))); }); } @requireCredentials @requireParam('uid') public getLesson(uid: string | number): Promise<Lesson> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.OrarendElem, { orarendElemUid: uid.toString() }), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Lesson>) => resolve(r.data))); }); } @requireCredentials public getNoticeBoardItems(): Promise<NoticeBoardItem[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.FaliujsagElemek), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<NoticeBoardItem[]>) => resolve(r.data))); }); } @requireCredentials public getClassAverage(options?: RequestClassAveragesOptions): Promise<ClassAverage[]> { return new Promise(async (resolve): Promise<void> => { const ops: { oktatasiNevelesiFeladatUid: string; tantargyUid?: string; } = { oktatasiNevelesiFeladatUid: options?.oktatasiNevelesiFeladatUid || await this.getGroups().then((groups: Group[]) => groups[0].OktatasNevelesiFeladat.Uid) }; if (options?.subjectUid) ops.tantargyUid = options.subjectUid; await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.OsztalyCsoportAtlag, ops), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<ClassAverage[]>) => resolve(r.data))); }); } @requireCredentials public getInstitute(): Promise<Institution> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.Intezmenyek), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Institution>) => resolve(r.data))); }); } @requireCredentials @requireParam('uids') public getClassMasters(uids: string[] | number[]): Promise<ClassMaster[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.Osztalyfonokok, { Uids: uids.map((u: string | number) => u.toString()).join(';') }), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<ClassMaster[]>) => resolve(r.data))); }); } @requireCredentials @requireParam('options.dateFrom') @requireParam('options.dateTo') public getTimeTableWeeks(options: RequestDateRangeRequiredOptions): Promise<TimeTableWeek[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.OrarendHetek, { orarendElemKezdoNapDatuma: validateDate(moment(options.dateFrom).format('YYYY-MM-DD')), orarendElemVegNapDatuma: validateDate(moment(options.dateTo).format('YYYY-MM-DD')) }), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<TimeTableWeek[]>) => resolve(r.data))); }); } @requireCredentials public getLepEvents(): Promise<LepEvent[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.Eloadasok), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<LepEvent[]>) => resolve(r.data))); }); } @requireCredentials public getSchoolYearCalendar(): Promise<SchoolYearCalendarEntry[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.TanevNaptar), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<SchoolYearCalendarEntry[]>) => resolve(r.data))); }); } @requireCredentials public getDeviceGivenState(): Promise<boolean> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.EszkozAllapot), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<boolean>) => resolve(r.data))); }); } }
src/lib/Kreta.ts
blazsmaster-kreta.js-9274c52
[ { "filename": "src/lib/Authentication.ts", "retrieved_chunk": "\t}\n\tprivate getNonce(): Promise<string> {\n\t\treturn new Promise(async (resolve): Promise<void> => {\n\t\t\tawait tryRequest(axios.get(API.IDP + Endpoints.Nonce).then((r: AxiosResponse<string>) => resolve(r.data.toString())));\n\t\t});\n\t}\n\tprivate getNonceHash(options: NonceHashOptions): Promise<string> {\n\t\treturn new Promise((resolve): void => {\n\t\t\tconst buffer_bytes: Buffer = Buffer.from(options.institute_code.toUpperCase() + options.nonce + options.username.toUpperCase(), 'utf8');\n\t\t\tconst hash: Buffer = createHmac('sha512', Buffer.from([98, 97, 83, 115, 120, 79, 119, 108, 85, 49, 106, 77])).update(buffer_bytes).digest();", "score": 29.31942691005349 }, { "filename": "src/lib/Authentication.ts", "retrieved_chunk": "\t\t\t\treturn resolve({ token: 'Bearer' + ' ' + access_token, access_token, refresh_token });\n\t\t});\n\t}\n\t@requireParam('options.refreshToken')\n\t@requireParam('options.refreshUserData')\n\tpublic getRefreshToken(options: RequestRefreshTokenOptions): Promise<AuthenticationResponse> {\n\t\treturn new Promise(async (resolve): Promise<void> => {\n\t\t\tconst nonce_key: string = await this.getNonce();\n\t\t\tconst hash: string = await this.getNonceHash({\n\t\t\t\tnonce: nonce_key,", "score": 28.447179137961868 }, { "filename": "src/utils/validateDate.ts", "retrieved_chunk": "import moment from 'moment';\nimport KretaError from '../lib/errors/KretaError';\nexport default function validateDate(date: string): string {\n\tif (!moment(date, 'YYYY-MM-DD', true).isValid())\n\t\tthrow new KretaError('Invalid date provided');\n\telse\n\t\treturn date;\n}", "score": 28.20250765935691 }, { "filename": "src/lib/Authentication.ts", "retrieved_chunk": "\t}\n\t@requireParam('ua')\n\tpublic setUserAgent(ua: string): this {\n\t\taxios.defaults.headers.common['User-Agent'] = ua;\n\t\treturn this;\n\t};\n\t@requireCredentials\n\tprivate authenticate(options: AuthenticationFields): Promise<AuthenticationResponse> {\n\t\treturn new Promise(async (resolve): Promise<void> => {\n\t\t\tconst nonce_key: string = await this.getNonce();", "score": 23.838084345339976 }, { "filename": "src/lib/Administration.ts", "retrieved_chunk": "\t\t\t}).then((r: AxiosResponse<string[]>) => resolve(r.data)));\n\t\t});\n\t}\n\t@requireCredentials\n\tpublic getAddressableType(): Promise<AddresseType[]> {\n\t\treturn new Promise(async (resolve): Promise<void> => {\n\t\t\tawait tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.CimezhetoTipusok), {\n\t\t\t\theaders: {\n\t\t\t\t\t'Authorization': await this.token\n\t\t\t\t}", "score": 22.240645851598984 } ]
typescript
datumTol = validateDate(moment(options.dateFrom).format('YYYY-MM-DD'));
import { AuthenticationFields, AuthenticationResponse, RequestRefreshTokenOptions, NonceHashOptions, API, Endpoints, AccessToken, PreBuiltAuthenticationToken } from '../types'; import axios, { AxiosProxyConfig, AxiosResponse } from 'axios'; import { createHmac } from 'node:crypto'; import KretaError from './errors/KretaError'; import requireParam from '../decorators/requireParam'; import tryRequest from '../utils/tryRequest'; import requireCredentials from '../decorators/requireCredentials'; export class Authentication { private readonly username: string; private readonly password: string; private readonly institute_code: string; private readonly client_id: string = 'kreta-ellenorzo-mobile-android'; private readonly grant_type: string = 'password'; private readonly auth_policy_version: string = 'v2'; constructor(options: AuthenticationFields) { this.username = options.username; this.password = options.password; this.institute_code = options.institute_code; } public get _username() { return this.username; } public get _password() { return this.password; } public get _institute_code() { return this.institute_code; } @requireParam('proxy.host') @requireParam('proxy.port') public setProxy(proxy: AxiosProxyConfig): this { axios.defaults.proxy = proxy; return this; } @requireParam('ua') public setUserAgent(ua: string): this { axios.defaults.headers.common['User-Agent'] = ua; return this; }; @requireCredentials private authenticate(options: AuthenticationFields): Promise<AuthenticationResponse> { return new Promise(async (resolve): Promise<void> => { const nonce_key: string = await this.getNonce(); const hash: string = await this.getNonceHash({ nonce: nonce_key, institute_code: options.institute_code, username: options.username }); await tryRequest(axios.post(API.IDP + Endpoints.Token, { institute_code: options.institute_code, username: options.username, password: options.password, grant_type: this.grant_type, client_id: this.client_id }, { headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'X-Authorizationpolicy-Nonce': nonce_key, 'X-Authorizationpolicy-Key': hash, 'X-Authorizationpolicy-Version': this.auth_policy_version, } }).then((r: AxiosResponse<AuthenticationResponse>) => resolve(r.data))); }); } private getNonce(): Promise<string> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(API.IDP + Endpoints.Nonce).then((r: AxiosResponse<string>) => resolve(r.data.toString()))); }); } private getNonceHash(options: NonceHashOptions): Promise<string> { return new Promise((resolve): void => { const buffer_bytes: Buffer = Buffer.from(options.institute_code.toUpperCase() + options.nonce + options.username.toUpperCase(), 'utf8'); const hash: Buffer = createHmac('sha512', Buffer.from([98, 97, 83, 115, 120, 79, 119, 108, 85, 49, 106, 77])).update(buffer_bytes).digest(); return resolve(hash.toString('base64')); }); } private async returnTokens(): Promise<AccessToken> { return await this.authenticate({ username: this.username, password: this.password, institute_code: this.institute_code }).then((r: AuthenticationResponse): AccessToken => { return { access_token: r.access_token, refresh_token: r.refresh_token, token_type: r.token_type }; }).catch((): { access_token: null; refresh_token: null; token_type: null } => { return { access_token: null, refresh_token: null, token_type: null }; }); } public getAccessToken(): Promise<PreBuiltAuthenticationToken> { return new Promise(async (resolve, reject): Promise<void> => { const { access_token, refresh_token }: AccessToken = await this.returnTokens(); if (access_token === null || refresh_token === null) return
reject(new KretaError('Failed to get access token: Invalid credentials'));
else return resolve({ token: 'Bearer' + ' ' + access_token, access_token, refresh_token }); }); } @requireParam('options.refreshToken') @requireParam('options.refreshUserData') public getRefreshToken(options: RequestRefreshTokenOptions): Promise<AuthenticationResponse> { return new Promise(async (resolve): Promise<void> => { const nonce_key: string = await this.getNonce(); const hash: string = await this.getNonceHash({ nonce: nonce_key, institute_code: this.institute_code, username: this.username }); await tryRequest(axios.post(API.IDP + Endpoints.Token, { refresh_token: options.refreshToken, institute_code: this.institute_code, grant_type: 'refresh_token', client_id: this.client_id, refresh_user_data: options.refreshUserData }, { headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'X-Authorizationpolicy-Key': hash, 'X-Authorizationpolicy-Version': this.auth_policy_version, } }).then((r: AxiosResponse<AuthenticationResponse>) => resolve(r.data) )); }); } }
src/lib/Authentication.ts
blazsmaster-kreta.js-9274c52
[ { "filename": "src/types.ts", "retrieved_chunk": "\ttoken_type: string;\n}\nexport interface PreBuiltAuthenticationToken {\n\ttoken: string;\n\taccess_token: string;\n\trefresh_token: string;\n}\ninterface ResponseErrorItem {\n\tPropertyName: string;\n\tMessage: string;", "score": 49.247907380779935 }, { "filename": "src/types.ts", "retrieved_chunk": "\ttoken_type: string | null;\n}\nexport interface KretaOptions extends AuthenticationFields {\n}\nexport interface AuthenticationResponse {\n\taccess_token: string;\n\texpires_in: number;\n\tid_token: string | null;\n\trefresh_token: string;\n\tscope: string;", "score": 48.03951843782349 }, { "filename": "src/types.ts", "retrieved_chunk": "\tpassword: string;\n\tusername: string;\n}\nexport interface RequestRefreshTokenOptions {\n\trefreshUserData: boolean;\n\trefreshToken: string;\n}\nexport interface AccessToken {\n\taccess_token: string | null;\n\trefresh_token: string | null;", "score": 45.72526851864643 }, { "filename": "src/decorators/requireParam.ts", "retrieved_chunk": "\t\t\t\t\tif (value.length === 0)\n\t\t\t\t\t\tthrow new KretaError(`'${param}' must not be an empty array`);\n\t\t\t\t} else {\n\t\t\t\t\tconst [objName, propName]: string[] = param.split('.');\n\t\t\t\t\tif (propName != null && value[propName] == null)\n\t\t\t\t\t\tthrow new KretaError(`'${propName}' is a required property in '${objName}'`);\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn originalMethod.apply(this, args);\n\t\t};", "score": 15.715876640920197 }, { "filename": "src/utils/tryRequest.ts", "retrieved_chunk": "import { AxiosError } from 'axios';\nimport KretaError from '../lib/errors/KretaError';\nimport { RequestResponseError } from '../types';\nexport default async function tryRequest(axios: Promise<void>): Promise<void> {\n\ttry {\n\t\treturn await axios;\n\t} catch (error) {\n\t\tconst e: AxiosError<RequestResponseError> = error as AxiosError<RequestResponseError>;\n\t\tif (e.response?.status) {\n\t\t\tlet errorMsg: string = '';", "score": 14.97504632529982 } ]
typescript
reject(new KretaError('Failed to get access token: Invalid credentials'));
import axios, { AxiosResponse } from 'axios'; import { AddresseType, AuthenticationFields, CardEvent, CurrentInstitutionDetails, DefaultType, EmployeeDetails, GuardianEAdmin, KretaClass, MailboxItem, MessageLimitations, PreBuiltAuthenticationToken, API, AdministrationEndpoints } from '../types'; import { Authentication } from './Authentication'; import requireCredentials from '../decorators/requireCredentials'; import tryRequest from '../utils/tryRequest'; import requireParam from '../decorators/requireParam'; export default class Administration { private readonly username: string; private readonly password: string; private readonly institute_code: string; private authenticate: Authentication; private token?: Promise<string>; constructor(options: AuthenticationFields) { this.username = options.username; this.password = options.password; this.institute_code = options.institute_code; this.authenticate = new Authentication({ username: this.username, password: this.password, institute_code: this.institute_code }); if (this.username && this.password && this.institute_code) this.token = this.authenticate.getAccessToken().then((r: PreBuiltAuthenticationToken) => r.token); axios.defaults.headers['X-Uzenet-Lokalizacio'] = 'hu-HU'; } public get _username() { return this.username; } public get _password() { return this.password; } public get _institute_code() { return this.institute_code; } private buildUgyintezesApiURL(endpointWithSlash: AdministrationEndpoints, params?: { [key: string]: any }): string { const urlParams: string = params ? '?' + new URLSearchParams(params).toString() : ''; return API.ADMINISTRATION + '/api/v1' + endpointWithSlash + urlParams; } @
requireCredentials public getAddresseeType(): Promise<AddresseType[]> {
return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.CimzettTipusok), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<AddresseType[]>) => resolve(r.data))); }); } @requireCredentials public getCaseTypes(): Promise<DefaultType[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.KerelemTipusok), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<DefaultType[]>) => resolve(r.data))); }); } @requireCredentials public getTmgiCaseTypes(): Promise<DefaultType[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.TmgiIgazolasTipusok), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<DefaultType[]>) => resolve(r.data))); }); } @requireCredentials public getAccessControlSystemEvents(): Promise<CardEvent[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.Esemenyek), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<CardEvent[]>) => resolve(r.data))); }); } @requireCredentials public getCurrentInstitutionModules(): Promise<string[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.JelenlegiIntezmenyModulok), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<string[]>) => resolve(r.data))); }); } @requireCredentials public getAddressableType(): Promise<AddresseType[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.CimezhetoTipusok), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<AddresseType[]>) => resolve(r.data))); }); } @requireCredentials @requireParam('addressId') public getAddressableClasses(addressId: string | number): Promise<KretaClass[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.CimezhetoOsztalyok, { cimzettKod: addressId.toString() }), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<KretaClass[]>) => resolve(r.data))); }); } @requireCredentials public getUnreadMessagesCount(): Promise<number> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.OlvasatlanokSzama), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<number>) => resolve(r.data))); }); } @requireCredentials public getMessages(): Promise<MailboxItem[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.Uzenetek), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<MailboxItem[]>) => resolve(r.data))); }); } @requireCredentials @requireParam('id') public getMessage(id: string | number): Promise<MailboxItem> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.Uzenet) + '/' + id.toString(), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<MailboxItem>) => resolve(r.data))); }); } @requireCredentials public getAddressableSzmkRepesentative(): Promise<GuardianEAdmin[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.CimezhetoSzmkKepviselok), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<GuardianEAdmin[]>) => resolve(r.data))); }); } @requireCredentials public getMessageLimitations(): Promise<MessageLimitations> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.UzenetLimitacio), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<MessageLimitations>) => resolve(r.data))); }); } @requireCredentials public getAdministrators(): Promise<EmployeeDetails[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.Adminisztratorok), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<EmployeeDetails[]>) => resolve(r.data))); }); } @requireCredentials public getDirectors(): Promise<EmployeeDetails[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.Igazgatok), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<EmployeeDetails[]>) => resolve(r.data))); }); } @requireCredentials public getClassMasters(): Promise<EmployeeDetails[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.Osztalyfonokok), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<EmployeeDetails[]>) => resolve(r.data))); }); } @requireCredentials public getTeachers(): Promise<EmployeeDetails[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.Oktatok), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<EmployeeDetails[]>) => resolve(r.data))); }); } @requireCredentials @requireParam('classId') public getAddressableGuardiansForClass(classId: string | number): Promise<GuardianEAdmin[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.CimezhetoTanuloSzulok) + '/' + classId.toString(), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<GuardianEAdmin[]>) => resolve(r.data))); }); } @requireCredentials public getCurrentInstitutionDetails(): Promise<CurrentInstitutionDetails> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.JelenlegiIntezmeny), { headers: { 'Authorization': await this.token } }).then((r: AxiosResponse<CurrentInstitutionDetails>) => resolve(r.data))); }); } }
src/lib/Administration.ts
blazsmaster-kreta.js-9274c52
[ { "filename": "src/lib/Kreta.ts", "retrieved_chunk": "\t\taxios.defaults.proxy = proxy;\n\t\treturn this;\n\t}\n\t@requireParam('ua')\n\tpublic setUserAgent(ua: string): this {\n\t\taxios.defaults.headers.common['User-Agent'] = ua;\n\t\treturn this;\n\t}\n\tprivate buildEllenorzoApiURL(endpointWithSlash: Endpoints, params?: { [key: string]: any }): string {\n\t\tconst urlParams: string = params ? '?' + new URLSearchParams(params).toString() : '';", "score": 59.4451405852137 }, { "filename": "src/lib/Kreta.ts", "retrieved_chunk": "\t\treturn dynamicValue(API.INSTITUTE, { institute_code: this.institute_code }).toString() + '/ellenorzo/V3' + endpointWithSlash + urlParams;\n\t}\n\t@requireParam('api_key')\n\tpublic getInstituteList(api_key: string): Promise<Institute[]> {\n\t\treturn new Promise(async (resolve): Promise<void> => {\n\t\t\tconst config_descriptor: AxiosResponse<ConfigurationDescriptor> = await axios.get('https://kretamobile.blob.core.windows.net/configuration/ConfigurationDescriptor.json');\n\t\t\tawait tryRequest(axios.get(config_descriptor.data.GlobalMobileApiUrlPROD + '/api/v3/Institute', {\n\t\t\t\theaders: {\n\t\t\t\t\tapiKey: api_key\n\t\t\t\t}", "score": 29.36626471366006 }, { "filename": "src/utils/dynamicValue.ts", "retrieved_chunk": "export default function dynamicValue(str: string, values: { [key: string]: any }): string {\n\treturn str.replace(/{{(.*?)}}/g, (match: string, key) => values[key] || match);\n}", "score": 17.61770214080683 }, { "filename": "src/lib/Authentication.ts", "retrieved_chunk": "\t}\n\tprivate getNonce(): Promise<string> {\n\t\treturn new Promise(async (resolve): Promise<void> => {\n\t\t\tawait tryRequest(axios.get(API.IDP + Endpoints.Nonce).then((r: AxiosResponse<string>) => resolve(r.data.toString())));\n\t\t});\n\t}\n\tprivate getNonceHash(options: NonceHashOptions): Promise<string> {\n\t\treturn new Promise((resolve): void => {\n\t\t\tconst buffer_bytes: Buffer = Buffer.from(options.institute_code.toUpperCase() + options.nonce + options.username.toUpperCase(), 'utf8');\n\t\t\tconst hash: Buffer = createHmac('sha512', Buffer.from([98, 97, 83, 115, 120, 79, 119, 108, 85, 49, 106, 77])).update(buffer_bytes).digest();", "score": 16.287917083650235 }, { "filename": "src/lib/Kreta.ts", "retrieved_chunk": "\tprivate readonly username?: string;\n\tprivate readonly password?: string;\n\tprivate readonly institute_code?: string;\n\tprivate authenticate?: Authentication;\n\tpublic Administration?: Administration;\n\tpublic Global: Global;\n\tprivate token?: Promise<string>;\n\tconstructor(options?: KretaOptions) {\n\t\tthis.username = options?.username || '';\n\t\tthis.password = options?.password || '';", "score": 16.17813571183219 } ]
typescript
requireCredentials public getAddresseeType(): Promise<AddresseType[]> {
import axios, { AxiosProxyConfig, AxiosResponse } from 'axios'; import moment from 'moment'; import { AnnouncedTest, ClassAverage, ClassMaster, ConfigurationDescriptor, Evaluation, Group, Homework, Institute, Institution, KretaOptions, LepEvent, Lesson, Note, NoticeBoardItem, Omission, PreBuiltAuthenticationToken, RequestAnnouncedTestsOptions, RequestClassAveragesOptions, RequestDateRangeOptions, RequestDateRangeRequiredOptions, RequestHomeWorkOptions, SchoolYearCalendarEntry, Student, SubjectAverage, TimeTableWeek, API, Endpoints } from '../types'; import { Authentication } from './Authentication'; import dynamicValue from '../utils/dynamicValue'; import Administration from './Administration'; import Global from './Global'; import requireCredentials from '../decorators/requireCredentials'; import tryRequest from '../utils/tryRequest'; import validateDate from '../utils/validateDate'; import requireParam from '../decorators/requireParam'; export default class Kreta { private readonly username?: string; private readonly password?: string; private readonly institute_code?: string; private authenticate?: Authentication; public Administration?: Administration; public Global: Global; private token?: Promise<string>; constructor(options?: KretaOptions) { this.username = options?.username || ''; this.password = options?.password || ''; this.institute_code = options?.institute_code || ''; axios.defaults.headers.common['User-Agent'] = 'hu.ekreta.student/1.0.5/Android/0/0'; this.Global = new Global(); this.authenticate = new Authentication({ username: this.username!, password: this.password!, institute_code: this.institute_code! }); if (this.username && this.password && this.institute_code) this.token = this.authenticate.getAccessToken().then((r: PreBuiltAuthenticationToken) => r.token); this.Administration = new Administration({ username: this.username!, password: this.password!, institute_code: this.institute_code! }); } public get _username() { return this.username; } public get _password() { return this.password; } public get _institute_code() { return this.institute_code; } @requireParam('proxy.host') @requireParam('proxy.port') public setProxy(proxy: AxiosProxyConfig): this { axios.defaults.proxy = proxy; return this; } @requireParam('ua') public setUserAgent(ua: string): this { axios.defaults.headers.common['User-Agent'] = ua; return this; } private buildEllenorzoApiURL(endpointWithSlash: Endpoints, params?: { [key: string]: any }): string { const urlParams: string = params ? '?' + new URLSearchParams(params).toString() : ''; return dynamicValue(API.INSTITUTE, { institute_code: this.institute_code }).toString() + '/ellenorzo/V3' + endpointWithSlash + urlParams; } @requireParam('api_key') public getInstituteList(api_key: string): Promise<Institute[]> { return new Promise(async (resolve): Promise<void> => { const config_descriptor: AxiosResponse<ConfigurationDescriptor> = await axios.get('https://kretamobile.blob.core.windows.net/configuration/ConfigurationDescriptor.json'); await tryRequest(axios.get(config_descriptor.data.GlobalMobileApiUrlPROD + '/api/v3/Institute', { headers: { apiKey: api_key } }).then((r: AxiosResponse<Institute[]>) => resolve(r.data))); }); } @
requireCredentials public getStudent(): Promise<Student> {
return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.Tanulo), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Student>) => resolve(r.data))); }); } @requireCredentials public getEvaluations(options?: RequestDateRangeOptions): Promise<Evaluation[]> { return new Promise(async (resolve): Promise<void> => { const ops: { datumTol?: string; datumIg?: string } = {}; if (options?.dateFrom) ops.datumTol = validateDate(moment(options.dateFrom).format('YYYY-MM-DD')); if (options?.dateTo) ops.datumIg = validateDate(moment(options.dateTo).format('YYYY-MM-DD')); await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.Ertekelesek, ops), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Evaluation[]>) => resolve(r.data))); }); } @requireCredentials public getNotes(options?: RequestDateRangeOptions): Promise<Note[]> { return new Promise(async (resolve): Promise<void> => { const ops: { datumTol?: string; datumIg?: string } = {}; if (options?.dateFrom) ops.datumTol = validateDate(moment(options.dateFrom).format('YYYY-MM-DD')); if (options?.dateTo) ops.datumIg = validateDate(moment(options.dateTo).format('YYYY-MM-DD')); await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.Feljegyzesek, ops), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Note[]>) => resolve(r.data))); }); } @requireCredentials public getAnnouncedTests(options?: RequestAnnouncedTestsOptions): Promise<AnnouncedTest[]> { return new Promise(async (resolve): Promise<void> => { const ops: { datumTol?: string; datumIg?: string, Uids?: string } = {}; if (options?.dateFrom) ops.datumTol = validateDate(moment(options.dateFrom).format('YYYY-MM-DD')); if (options?.dateTo) ops.datumIg = validateDate(moment(options.dateTo).format('YYYY-MM-DD')); if (options?.uids) ops.Uids = options.uids.map((uid: string | number) => uid.toString()).join(';'); await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.Szamonkeresek, ops), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<AnnouncedTest[]>) => resolve(r.data))); }); } @requireCredentials @requireParam('options.dateFrom') public getHomeworks(options: RequestHomeWorkOptions): Promise<Homework[]> { return new Promise(async (resolve): Promise<void> => { const ops: { datumTol: string; datumIg?: string } = { datumTol: validateDate(moment(options.dateFrom).format('YYYY-MM-DD')) }; if (options?.dateTo) ops.datumIg = validateDate(moment(options.dateTo).format('YYYY-MM-DD')); await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.HaziFeladatok, ops), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Homework[]>) => resolve(r.data))); }); } @requireCredentials @requireParam('uid') public getHomework(uid: string | number): Promise<Homework> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.HaziFeladatok) + '/' + uid.toString(), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Homework>) => resolve(r.data))); }); } @requireCredentials public getOmissions(options?: RequestDateRangeOptions): Promise<Omission[]> { return new Promise(async (resolve): Promise<void> => { const ops: { datumTol?: string; datumIg?: string } = {}; if (options?.dateFrom) ops.datumTol = validateDate(moment(options.dateFrom).format('YYYY-MM-DD')); if (options?.dateTo) ops.datumIg = validateDate(moment(options.dateTo).format('YYYY-MM-DD')); await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.Mulasztasok, ops), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Omission[]>) => resolve(r.data))); }); } @requireCredentials public getGroups(): Promise<Group[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.OsztalyCsoportok), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Group[]>) => resolve(r.data))); }); } @requireCredentials public getSubjectAverages(onfUid?: string): Promise<SubjectAverage[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.TantargyiAtlagok, { oktatasiNevelesiFeladatUid: onfUid || await this.getGroups().then((groups: Group[]) => groups[0].OktatasNevelesiFeladat.Uid) }), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<SubjectAverage[]>) => resolve(r.data))); }); } @requireCredentials @requireParam('options.dateFrom') @requireParam('options.dateTo') public getLessons(options: RequestDateRangeRequiredOptions): Promise<Lesson[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.OrarendElemek, { datumTol: validateDate(moment(options.dateFrom).format('YYYY-MM-DD')), datumIg: validateDate(moment(options.dateTo).format('YYYY-MM-DD')) }), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Lesson[]>) => resolve(r.data))); }); } @requireCredentials @requireParam('uid') public getLesson(uid: string | number): Promise<Lesson> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.OrarendElem, { orarendElemUid: uid.toString() }), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Lesson>) => resolve(r.data))); }); } @requireCredentials public getNoticeBoardItems(): Promise<NoticeBoardItem[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.FaliujsagElemek), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<NoticeBoardItem[]>) => resolve(r.data))); }); } @requireCredentials public getClassAverage(options?: RequestClassAveragesOptions): Promise<ClassAverage[]> { return new Promise(async (resolve): Promise<void> => { const ops: { oktatasiNevelesiFeladatUid: string; tantargyUid?: string; } = { oktatasiNevelesiFeladatUid: options?.oktatasiNevelesiFeladatUid || await this.getGroups().then((groups: Group[]) => groups[0].OktatasNevelesiFeladat.Uid) }; if (options?.subjectUid) ops.tantargyUid = options.subjectUid; await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.OsztalyCsoportAtlag, ops), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<ClassAverage[]>) => resolve(r.data))); }); } @requireCredentials public getInstitute(): Promise<Institution> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.Intezmenyek), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Institution>) => resolve(r.data))); }); } @requireCredentials @requireParam('uids') public getClassMasters(uids: string[] | number[]): Promise<ClassMaster[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.Osztalyfonokok, { Uids: uids.map((u: string | number) => u.toString()).join(';') }), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<ClassMaster[]>) => resolve(r.data))); }); } @requireCredentials @requireParam('options.dateFrom') @requireParam('options.dateTo') public getTimeTableWeeks(options: RequestDateRangeRequiredOptions): Promise<TimeTableWeek[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.OrarendHetek, { orarendElemKezdoNapDatuma: validateDate(moment(options.dateFrom).format('YYYY-MM-DD')), orarendElemVegNapDatuma: validateDate(moment(options.dateTo).format('YYYY-MM-DD')) }), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<TimeTableWeek[]>) => resolve(r.data))); }); } @requireCredentials public getLepEvents(): Promise<LepEvent[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.Eloadasok), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<LepEvent[]>) => resolve(r.data))); }); } @requireCredentials public getSchoolYearCalendar(): Promise<SchoolYearCalendarEntry[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.TanevNaptar), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<SchoolYearCalendarEntry[]>) => resolve(r.data))); }); } @requireCredentials public getDeviceGivenState(): Promise<boolean> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.EszkozAllapot), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<boolean>) => resolve(r.data))); }); } }
src/lib/Kreta.ts
blazsmaster-kreta.js-9274c52
[ { "filename": "src/lib/Administration.ts", "retrieved_chunk": "\t\t\t}).then((r: AxiosResponse<string[]>) => resolve(r.data)));\n\t\t});\n\t}\n\t@requireCredentials\n\tpublic getAddressableType(): Promise<AddresseType[]> {\n\t\treturn new Promise(async (resolve): Promise<void> => {\n\t\t\tawait tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.CimezhetoTipusok), {\n\t\t\t\theaders: {\n\t\t\t\t\t'Authorization': await this.token\n\t\t\t\t}", "score": 18.723334244033243 }, { "filename": "src/lib/Administration.ts", "retrieved_chunk": "\t\t\t}).then((r: AxiosResponse<DefaultType[]>) => resolve(r.data)));\n\t\t});\n\t}\n\t@requireCredentials\n\tpublic getTmgiCaseTypes(): Promise<DefaultType[]> {\n\t\treturn new Promise(async (resolve): Promise<void> => {\n\t\t\tawait tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.TmgiIgazolasTipusok), {\n\t\t\t\theaders: {\n\t\t\t\t\t'Authorization': await this.token\n\t\t\t\t}", "score": 18.723334244033243 }, { "filename": "src/lib/Administration.ts", "retrieved_chunk": "\t\t\t}).then((r: AxiosResponse<DefaultType[]>) => resolve(r.data)));\n\t\t});\n\t}\n\t@requireCredentials\n\tpublic getAccessControlSystemEvents(): Promise<CardEvent[]> {\n\t\treturn new Promise(async (resolve): Promise<void> => {\n\t\t\tawait tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.Esemenyek), {\n\t\t\t\theaders: {\n\t\t\t\t\t'Authorization': await this.token\n\t\t\t\t}", "score": 18.723334244033243 }, { "filename": "src/lib/Administration.ts", "retrieved_chunk": "\t\t\t}).then((r: AxiosResponse<CardEvent[]>) => resolve(r.data)));\n\t\t});\n\t}\n\t@requireCredentials\n\tpublic getCurrentInstitutionModules(): Promise<string[]> {\n\t\treturn new Promise(async (resolve): Promise<void> => {\n\t\t\tawait tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.JelenlegiIntezmenyModulok), {\n\t\t\t\theaders: {\n\t\t\t\t\t'Authorization': await this.token\n\t\t\t\t}", "score": 18.723334244033243 }, { "filename": "src/lib/Administration.ts", "retrieved_chunk": "\t\t\t}).then((r: AxiosResponse<AddresseType[]>) => resolve(r.data)));\n\t\t});\n\t}\n\t@requireCredentials\n\tpublic getCaseTypes(): Promise<DefaultType[]> {\n\t\treturn new Promise(async (resolve): Promise<void> => {\n\t\t\tawait tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.KerelemTipusok), {\n\t\t\t\theaders: {\n\t\t\t\t\t'Authorization': await this.token\n\t\t\t\t}", "score": 18.723334244033243 } ]
typescript
requireCredentials public getStudent(): Promise<Student> {
import axios, { AxiosProxyConfig, AxiosResponse } from 'axios'; import moment from 'moment'; import { AnnouncedTest, ClassAverage, ClassMaster, ConfigurationDescriptor, Evaluation, Group, Homework, Institute, Institution, KretaOptions, LepEvent, Lesson, Note, NoticeBoardItem, Omission, PreBuiltAuthenticationToken, RequestAnnouncedTestsOptions, RequestClassAveragesOptions, RequestDateRangeOptions, RequestDateRangeRequiredOptions, RequestHomeWorkOptions, SchoolYearCalendarEntry, Student, SubjectAverage, TimeTableWeek, API, Endpoints } from '../types'; import { Authentication } from './Authentication'; import dynamicValue from '../utils/dynamicValue'; import Administration from './Administration'; import Global from './Global'; import requireCredentials from '../decorators/requireCredentials'; import tryRequest from '../utils/tryRequest'; import validateDate from '../utils/validateDate'; import requireParam from '../decorators/requireParam'; export default class Kreta { private readonly username?: string; private readonly password?: string; private readonly institute_code?: string; private authenticate?: Authentication; public Administration?: Administration; public Global: Global; private token?: Promise<string>; constructor(options?: KretaOptions) { this.username = options?.username || ''; this.password = options?.password || ''; this.institute_code = options?.institute_code || ''; axios.defaults.headers.common['User-Agent'] = 'hu.ekreta.student/1.0.5/Android/0/0'; this.Global = new Global(); this.authenticate = new Authentication({ username: this.username!, password: this.password!, institute_code: this.institute_code! }); if (this.username && this.password && this.institute_code) this.token = this.authenticate.getAccessToken().then((r: PreBuiltAuthenticationToken) => r.token); this.Administration = new Administration({ username: this.username!, password: this.password!, institute_code: this.institute_code! }); } public get _username() { return this.username; } public get _password() { return this.password; } public get _institute_code() { return this.institute_code; } @requireParam('proxy.host') @requireParam('proxy.port') public setProxy(proxy: AxiosProxyConfig): this { axios.defaults.proxy = proxy; return this; } @requireParam('ua') public setUserAgent(ua: string): this { axios.defaults.headers.common['User-Agent'] = ua; return this; } private buildEllenorzoApiURL(endpointWithSlash: Endpoints, params?: { [key: string]: any }): string { const urlParams: string = params ? '?' + new URLSearchParams(params).toString() : ''; return dynamicValue(API.INSTITUTE, { institute_code: this.institute_code }).toString() + '/ellenorzo/V3' + endpointWithSlash + urlParams; } @requireParam('api_key') public getInstituteList(api_key: string): Promise<Institute[]> { return new Promise(async (resolve): Promise<void> => { const config_descriptor: AxiosResponse<ConfigurationDescriptor> = await axios.get('https://kretamobile.blob.core.windows.net/configuration/ConfigurationDescriptor.json'); await tryRequest(axios.get(config_descriptor.data.GlobalMobileApiUrlPROD + '/api/v3/Institute', { headers: { apiKey: api_key } }).then((r: AxiosResponse<Institute[]>) => resolve(r.data))); }); } @requireCredentials public getStudent(): Promise<Student> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.Tanulo), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Student>) => resolve(r.data))); }); } @requireCredentials public getEvaluations(options?: RequestDateRangeOptions): Promise<Evaluation[]> { return new Promise(async (resolve): Promise<void> => { const ops: { datumTol?: string; datumIg?: string } = {}; if (options?.dateFrom)
ops.datumTol = validateDate(moment(options.dateFrom).format('YYYY-MM-DD'));
if (options?.dateTo) ops.datumIg = validateDate(moment(options.dateTo).format('YYYY-MM-DD')); await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.Ertekelesek, ops), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Evaluation[]>) => resolve(r.data))); }); } @requireCredentials public getNotes(options?: RequestDateRangeOptions): Promise<Note[]> { return new Promise(async (resolve): Promise<void> => { const ops: { datumTol?: string; datumIg?: string } = {}; if (options?.dateFrom) ops.datumTol = validateDate(moment(options.dateFrom).format('YYYY-MM-DD')); if (options?.dateTo) ops.datumIg = validateDate(moment(options.dateTo).format('YYYY-MM-DD')); await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.Feljegyzesek, ops), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Note[]>) => resolve(r.data))); }); } @requireCredentials public getAnnouncedTests(options?: RequestAnnouncedTestsOptions): Promise<AnnouncedTest[]> { return new Promise(async (resolve): Promise<void> => { const ops: { datumTol?: string; datumIg?: string, Uids?: string } = {}; if (options?.dateFrom) ops.datumTol = validateDate(moment(options.dateFrom).format('YYYY-MM-DD')); if (options?.dateTo) ops.datumIg = validateDate(moment(options.dateTo).format('YYYY-MM-DD')); if (options?.uids) ops.Uids = options.uids.map((uid: string | number) => uid.toString()).join(';'); await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.Szamonkeresek, ops), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<AnnouncedTest[]>) => resolve(r.data))); }); } @requireCredentials @requireParam('options.dateFrom') public getHomeworks(options: RequestHomeWorkOptions): Promise<Homework[]> { return new Promise(async (resolve): Promise<void> => { const ops: { datumTol: string; datumIg?: string } = { datumTol: validateDate(moment(options.dateFrom).format('YYYY-MM-DD')) }; if (options?.dateTo) ops.datumIg = validateDate(moment(options.dateTo).format('YYYY-MM-DD')); await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.HaziFeladatok, ops), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Homework[]>) => resolve(r.data))); }); } @requireCredentials @requireParam('uid') public getHomework(uid: string | number): Promise<Homework> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.HaziFeladatok) + '/' + uid.toString(), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Homework>) => resolve(r.data))); }); } @requireCredentials public getOmissions(options?: RequestDateRangeOptions): Promise<Omission[]> { return new Promise(async (resolve): Promise<void> => { const ops: { datumTol?: string; datumIg?: string } = {}; if (options?.dateFrom) ops.datumTol = validateDate(moment(options.dateFrom).format('YYYY-MM-DD')); if (options?.dateTo) ops.datumIg = validateDate(moment(options.dateTo).format('YYYY-MM-DD')); await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.Mulasztasok, ops), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Omission[]>) => resolve(r.data))); }); } @requireCredentials public getGroups(): Promise<Group[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.OsztalyCsoportok), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Group[]>) => resolve(r.data))); }); } @requireCredentials public getSubjectAverages(onfUid?: string): Promise<SubjectAverage[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.TantargyiAtlagok, { oktatasiNevelesiFeladatUid: onfUid || await this.getGroups().then((groups: Group[]) => groups[0].OktatasNevelesiFeladat.Uid) }), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<SubjectAverage[]>) => resolve(r.data))); }); } @requireCredentials @requireParam('options.dateFrom') @requireParam('options.dateTo') public getLessons(options: RequestDateRangeRequiredOptions): Promise<Lesson[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.OrarendElemek, { datumTol: validateDate(moment(options.dateFrom).format('YYYY-MM-DD')), datumIg: validateDate(moment(options.dateTo).format('YYYY-MM-DD')) }), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Lesson[]>) => resolve(r.data))); }); } @requireCredentials @requireParam('uid') public getLesson(uid: string | number): Promise<Lesson> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.OrarendElem, { orarendElemUid: uid.toString() }), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Lesson>) => resolve(r.data))); }); } @requireCredentials public getNoticeBoardItems(): Promise<NoticeBoardItem[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.FaliujsagElemek), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<NoticeBoardItem[]>) => resolve(r.data))); }); } @requireCredentials public getClassAverage(options?: RequestClassAveragesOptions): Promise<ClassAverage[]> { return new Promise(async (resolve): Promise<void> => { const ops: { oktatasiNevelesiFeladatUid: string; tantargyUid?: string; } = { oktatasiNevelesiFeladatUid: options?.oktatasiNevelesiFeladatUid || await this.getGroups().then((groups: Group[]) => groups[0].OktatasNevelesiFeladat.Uid) }; if (options?.subjectUid) ops.tantargyUid = options.subjectUid; await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.OsztalyCsoportAtlag, ops), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<ClassAverage[]>) => resolve(r.data))); }); } @requireCredentials public getInstitute(): Promise<Institution> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.Intezmenyek), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Institution>) => resolve(r.data))); }); } @requireCredentials @requireParam('uids') public getClassMasters(uids: string[] | number[]): Promise<ClassMaster[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.Osztalyfonokok, { Uids: uids.map((u: string | number) => u.toString()).join(';') }), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<ClassMaster[]>) => resolve(r.data))); }); } @requireCredentials @requireParam('options.dateFrom') @requireParam('options.dateTo') public getTimeTableWeeks(options: RequestDateRangeRequiredOptions): Promise<TimeTableWeek[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.OrarendHetek, { orarendElemKezdoNapDatuma: validateDate(moment(options.dateFrom).format('YYYY-MM-DD')), orarendElemVegNapDatuma: validateDate(moment(options.dateTo).format('YYYY-MM-DD')) }), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<TimeTableWeek[]>) => resolve(r.data))); }); } @requireCredentials public getLepEvents(): Promise<LepEvent[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.Eloadasok), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<LepEvent[]>) => resolve(r.data))); }); } @requireCredentials public getSchoolYearCalendar(): Promise<SchoolYearCalendarEntry[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.TanevNaptar), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<SchoolYearCalendarEntry[]>) => resolve(r.data))); }); } @requireCredentials public getDeviceGivenState(): Promise<boolean> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.EszkozAllapot), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<boolean>) => resolve(r.data))); }); } }
src/lib/Kreta.ts
blazsmaster-kreta.js-9274c52
[ { "filename": "src/lib/Authentication.ts", "retrieved_chunk": "\t}\n\tprivate getNonce(): Promise<string> {\n\t\treturn new Promise(async (resolve): Promise<void> => {\n\t\t\tawait tryRequest(axios.get(API.IDP + Endpoints.Nonce).then((r: AxiosResponse<string>) => resolve(r.data.toString())));\n\t\t});\n\t}\n\tprivate getNonceHash(options: NonceHashOptions): Promise<string> {\n\t\treturn new Promise((resolve): void => {\n\t\t\tconst buffer_bytes: Buffer = Buffer.from(options.institute_code.toUpperCase() + options.nonce + options.username.toUpperCase(), 'utf8');\n\t\t\tconst hash: Buffer = createHmac('sha512', Buffer.from([98, 97, 83, 115, 120, 79, 119, 108, 85, 49, 106, 77])).update(buffer_bytes).digest();", "score": 29.31942691005349 }, { "filename": "src/lib/Authentication.ts", "retrieved_chunk": "\t\t\t\treturn resolve({ token: 'Bearer' + ' ' + access_token, access_token, refresh_token });\n\t\t});\n\t}\n\t@requireParam('options.refreshToken')\n\t@requireParam('options.refreshUserData')\n\tpublic getRefreshToken(options: RequestRefreshTokenOptions): Promise<AuthenticationResponse> {\n\t\treturn new Promise(async (resolve): Promise<void> => {\n\t\t\tconst nonce_key: string = await this.getNonce();\n\t\t\tconst hash: string = await this.getNonceHash({\n\t\t\t\tnonce: nonce_key,", "score": 28.447179137961868 }, { "filename": "src/utils/validateDate.ts", "retrieved_chunk": "import moment from 'moment';\nimport KretaError from '../lib/errors/KretaError';\nexport default function validateDate(date: string): string {\n\tif (!moment(date, 'YYYY-MM-DD', true).isValid())\n\t\tthrow new KretaError('Invalid date provided');\n\telse\n\t\treturn date;\n}", "score": 28.20250765935691 }, { "filename": "src/lib/Authentication.ts", "retrieved_chunk": "\t}\n\t@requireParam('ua')\n\tpublic setUserAgent(ua: string): this {\n\t\taxios.defaults.headers.common['User-Agent'] = ua;\n\t\treturn this;\n\t};\n\t@requireCredentials\n\tprivate authenticate(options: AuthenticationFields): Promise<AuthenticationResponse> {\n\t\treturn new Promise(async (resolve): Promise<void> => {\n\t\t\tconst nonce_key: string = await this.getNonce();", "score": 23.838084345339976 }, { "filename": "src/lib/Administration.ts", "retrieved_chunk": "\t\t\t}).then((r: AxiosResponse<string[]>) => resolve(r.data)));\n\t\t});\n\t}\n\t@requireCredentials\n\tpublic getAddressableType(): Promise<AddresseType[]> {\n\t\treturn new Promise(async (resolve): Promise<void> => {\n\t\t\tawait tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.CimezhetoTipusok), {\n\t\t\t\theaders: {\n\t\t\t\t\t'Authorization': await this.token\n\t\t\t\t}", "score": 22.240645851598984 } ]
typescript
ops.datumTol = validateDate(moment(options.dateFrom).format('YYYY-MM-DD'));
import axios, { AxiosProxyConfig, AxiosResponse } from 'axios'; import moment from 'moment'; import { AnnouncedTest, ClassAverage, ClassMaster, ConfigurationDescriptor, Evaluation, Group, Homework, Institute, Institution, KretaOptions, LepEvent, Lesson, Note, NoticeBoardItem, Omission, PreBuiltAuthenticationToken, RequestAnnouncedTestsOptions, RequestClassAveragesOptions, RequestDateRangeOptions, RequestDateRangeRequiredOptions, RequestHomeWorkOptions, SchoolYearCalendarEntry, Student, SubjectAverage, TimeTableWeek, API, Endpoints } from '../types'; import { Authentication } from './Authentication'; import dynamicValue from '../utils/dynamicValue'; import Administration from './Administration'; import Global from './Global'; import requireCredentials from '../decorators/requireCredentials'; import tryRequest from '../utils/tryRequest'; import validateDate from '../utils/validateDate'; import requireParam from '../decorators/requireParam'; export default class Kreta { private readonly username?: string; private readonly password?: string; private readonly institute_code?: string; private authenticate?: Authentication; public Administration?: Administration; public Global: Global; private token?: Promise<string>; constructor(options?: KretaOptions) { this.username = options?.username || ''; this.password = options?.password || ''; this.institute_code = options?.institute_code || ''; axios.defaults.headers.common['User-Agent'] = 'hu.ekreta.student/1.0.5/Android/0/0'; this.Global = new Global(); this.authenticate = new Authentication({ username: this.username!, password: this.password!, institute_code: this.institute_code! }); if (this.username && this.password && this.institute_code) this.token = this.authenticate.getAccessToken().then((r: PreBuiltAuthenticationToken) => r.token); this.Administration = new Administration({ username: this.username!, password: this.password!, institute_code: this.institute_code! }); } public get _username() { return this.username; } public get _password() { return this.password; } public get _institute_code() { return this.institute_code; } @requireParam('proxy.host') @requireParam('proxy.port') public setProxy(proxy: AxiosProxyConfig): this { axios.defaults.proxy = proxy; return this; } @requireParam('ua') public setUserAgent(ua: string): this { axios.defaults.headers.common['User-Agent'] = ua; return this; } private buildEllenorzoApiURL(endpointWithSlash: Endpoints, params?: { [key: string]: any }): string { const urlParams: string = params ? '?' + new URLSearchParams(params).toString() : ''; return
dynamicValue(API.INSTITUTE, { institute_code: this.institute_code }).toString() + '/ellenorzo/V3' + endpointWithSlash + urlParams;
} @requireParam('api_key') public getInstituteList(api_key: string): Promise<Institute[]> { return new Promise(async (resolve): Promise<void> => { const config_descriptor: AxiosResponse<ConfigurationDescriptor> = await axios.get('https://kretamobile.blob.core.windows.net/configuration/ConfigurationDescriptor.json'); await tryRequest(axios.get(config_descriptor.data.GlobalMobileApiUrlPROD + '/api/v3/Institute', { headers: { apiKey: api_key } }).then((r: AxiosResponse<Institute[]>) => resolve(r.data))); }); } @requireCredentials public getStudent(): Promise<Student> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.Tanulo), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Student>) => resolve(r.data))); }); } @requireCredentials public getEvaluations(options?: RequestDateRangeOptions): Promise<Evaluation[]> { return new Promise(async (resolve): Promise<void> => { const ops: { datumTol?: string; datumIg?: string } = {}; if (options?.dateFrom) ops.datumTol = validateDate(moment(options.dateFrom).format('YYYY-MM-DD')); if (options?.dateTo) ops.datumIg = validateDate(moment(options.dateTo).format('YYYY-MM-DD')); await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.Ertekelesek, ops), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Evaluation[]>) => resolve(r.data))); }); } @requireCredentials public getNotes(options?: RequestDateRangeOptions): Promise<Note[]> { return new Promise(async (resolve): Promise<void> => { const ops: { datumTol?: string; datumIg?: string } = {}; if (options?.dateFrom) ops.datumTol = validateDate(moment(options.dateFrom).format('YYYY-MM-DD')); if (options?.dateTo) ops.datumIg = validateDate(moment(options.dateTo).format('YYYY-MM-DD')); await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.Feljegyzesek, ops), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Note[]>) => resolve(r.data))); }); } @requireCredentials public getAnnouncedTests(options?: RequestAnnouncedTestsOptions): Promise<AnnouncedTest[]> { return new Promise(async (resolve): Promise<void> => { const ops: { datumTol?: string; datumIg?: string, Uids?: string } = {}; if (options?.dateFrom) ops.datumTol = validateDate(moment(options.dateFrom).format('YYYY-MM-DD')); if (options?.dateTo) ops.datumIg = validateDate(moment(options.dateTo).format('YYYY-MM-DD')); if (options?.uids) ops.Uids = options.uids.map((uid: string | number) => uid.toString()).join(';'); await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.Szamonkeresek, ops), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<AnnouncedTest[]>) => resolve(r.data))); }); } @requireCredentials @requireParam('options.dateFrom') public getHomeworks(options: RequestHomeWorkOptions): Promise<Homework[]> { return new Promise(async (resolve): Promise<void> => { const ops: { datumTol: string; datumIg?: string } = { datumTol: validateDate(moment(options.dateFrom).format('YYYY-MM-DD')) }; if (options?.dateTo) ops.datumIg = validateDate(moment(options.dateTo).format('YYYY-MM-DD')); await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.HaziFeladatok, ops), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Homework[]>) => resolve(r.data))); }); } @requireCredentials @requireParam('uid') public getHomework(uid: string | number): Promise<Homework> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.HaziFeladatok) + '/' + uid.toString(), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Homework>) => resolve(r.data))); }); } @requireCredentials public getOmissions(options?: RequestDateRangeOptions): Promise<Omission[]> { return new Promise(async (resolve): Promise<void> => { const ops: { datumTol?: string; datumIg?: string } = {}; if (options?.dateFrom) ops.datumTol = validateDate(moment(options.dateFrom).format('YYYY-MM-DD')); if (options?.dateTo) ops.datumIg = validateDate(moment(options.dateTo).format('YYYY-MM-DD')); await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.Mulasztasok, ops), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Omission[]>) => resolve(r.data))); }); } @requireCredentials public getGroups(): Promise<Group[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.OsztalyCsoportok), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Group[]>) => resolve(r.data))); }); } @requireCredentials public getSubjectAverages(onfUid?: string): Promise<SubjectAverage[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.TantargyiAtlagok, { oktatasiNevelesiFeladatUid: onfUid || await this.getGroups().then((groups: Group[]) => groups[0].OktatasNevelesiFeladat.Uid) }), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<SubjectAverage[]>) => resolve(r.data))); }); } @requireCredentials @requireParam('options.dateFrom') @requireParam('options.dateTo') public getLessons(options: RequestDateRangeRequiredOptions): Promise<Lesson[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.OrarendElemek, { datumTol: validateDate(moment(options.dateFrom).format('YYYY-MM-DD')), datumIg: validateDate(moment(options.dateTo).format('YYYY-MM-DD')) }), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Lesson[]>) => resolve(r.data))); }); } @requireCredentials @requireParam('uid') public getLesson(uid: string | number): Promise<Lesson> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.OrarendElem, { orarendElemUid: uid.toString() }), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Lesson>) => resolve(r.data))); }); } @requireCredentials public getNoticeBoardItems(): Promise<NoticeBoardItem[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.FaliujsagElemek), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<NoticeBoardItem[]>) => resolve(r.data))); }); } @requireCredentials public getClassAverage(options?: RequestClassAveragesOptions): Promise<ClassAverage[]> { return new Promise(async (resolve): Promise<void> => { const ops: { oktatasiNevelesiFeladatUid: string; tantargyUid?: string; } = { oktatasiNevelesiFeladatUid: options?.oktatasiNevelesiFeladatUid || await this.getGroups().then((groups: Group[]) => groups[0].OktatasNevelesiFeladat.Uid) }; if (options?.subjectUid) ops.tantargyUid = options.subjectUid; await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.OsztalyCsoportAtlag, ops), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<ClassAverage[]>) => resolve(r.data))); }); } @requireCredentials public getInstitute(): Promise<Institution> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.Intezmenyek), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<Institution>) => resolve(r.data))); }); } @requireCredentials @requireParam('uids') public getClassMasters(uids: string[] | number[]): Promise<ClassMaster[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.Osztalyfonokok, { Uids: uids.map((u: string | number) => u.toString()).join(';') }), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<ClassMaster[]>) => resolve(r.data))); }); } @requireCredentials @requireParam('options.dateFrom') @requireParam('options.dateTo') public getTimeTableWeeks(options: RequestDateRangeRequiredOptions): Promise<TimeTableWeek[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.OrarendHetek, { orarendElemKezdoNapDatuma: validateDate(moment(options.dateFrom).format('YYYY-MM-DD')), orarendElemVegNapDatuma: validateDate(moment(options.dateTo).format('YYYY-MM-DD')) }), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<TimeTableWeek[]>) => resolve(r.data))); }); } @requireCredentials public getLepEvents(): Promise<LepEvent[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.Eloadasok), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<LepEvent[]>) => resolve(r.data))); }); } @requireCredentials public getSchoolYearCalendar(): Promise<SchoolYearCalendarEntry[]> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.TanevNaptar), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<SchoolYearCalendarEntry[]>) => resolve(r.data))); }); } @requireCredentials public getDeviceGivenState(): Promise<boolean> { return new Promise(async (resolve): Promise<void> => { await tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.EszkozAllapot), { headers: { 'Authorization': await this.token, } }).then((r: AxiosResponse<boolean>) => resolve(r.data))); }); } }
src/lib/Kreta.ts
blazsmaster-kreta.js-9274c52
[ { "filename": "src/lib/Authentication.ts", "retrieved_chunk": "\t}\n\t@requireParam('ua')\n\tpublic setUserAgent(ua: string): this {\n\t\taxios.defaults.headers.common['User-Agent'] = ua;\n\t\treturn this;\n\t};\n\t@requireCredentials\n\tprivate authenticate(options: AuthenticationFields): Promise<AuthenticationResponse> {\n\t\treturn new Promise(async (resolve): Promise<void> => {\n\t\t\tconst nonce_key: string = await this.getNonce();", "score": 57.61458707593984 }, { "filename": "src/lib/Administration.ts", "retrieved_chunk": "\t\tconst urlParams: string = params ? '?' + new URLSearchParams(params).toString() : '';\n\t\treturn API.ADMINISTRATION + '/api/v1' + endpointWithSlash + urlParams;\n\t}\n\t@requireCredentials\n\tpublic getAddresseeType(): Promise<AddresseType[]> {\n\t\treturn new Promise(async (resolve): Promise<void> => {\n\t\t\tawait tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.CimzettTipusok), {\n\t\t\t\theaders: {\n\t\t\t\t\t'Authorization': await this.token\n\t\t\t\t}", "score": 54.22332384777823 }, { "filename": "src/lib/Administration.ts", "retrieved_chunk": "\tpublic get _username() {\n\t\treturn this.username;\n\t}\n\tpublic get _password() {\n\t\treturn this.password;\n\t}\n\tpublic get _institute_code() {\n\t\treturn this.institute_code;\n\t}\n\tprivate buildUgyintezesApiURL(endpointWithSlash: AdministrationEndpoints, params?: { [key: string]: any }): string {", "score": 45.61885125852599 }, { "filename": "src/utils/dynamicValue.ts", "retrieved_chunk": "export default function dynamicValue(str: string, values: { [key: string]: any }): string {\n\treturn str.replace(/{{(.*?)}}/g, (match: string, key) => values[key] || match);\n}", "score": 23.731972326825595 }, { "filename": "src/lib/Authentication.ts", "retrieved_chunk": "\t\t\tconst hash: string = await this.getNonceHash({\n\t\t\t\tnonce: nonce_key,\n\t\t\t\tinstitute_code: options.institute_code,\n\t\t\t\tusername: options.username\n\t\t\t});\n\t\t\tawait tryRequest(axios.post(API.IDP + Endpoints.Token, {\n\t\t\t\tinstitute_code: options.institute_code,\n\t\t\t\tusername: options.username,\n\t\t\t\tpassword: options.password,\n\t\t\t\tgrant_type: this.grant_type,", "score": 20.752091771049564 } ]
typescript
dynamicValue(API.INSTITUTE, { institute_code: this.institute_code }).toString() + '/ellenorzo/V3' + endpointWithSlash + urlParams;
import debugPackage from "debug"; import { bold, cyan, dim, red, reset, yellow } from "kleur/colors"; import * as readline from "readline"; import { Writable } from "stream"; import stringWidth from "string-width"; import { dateTimeFormat, error, info, warn } from "./core.js"; type ConsoleStream = Writable & { fd: 1 | 2; }; let lastMessage: string; let lastMessageCount = 1; export const nodeLogDestination = new Writable({ objectMode: true, write(event: LogMessage, _, callback) { let dest: ConsoleStream = process.stderr; if (levels[event.level] < levels["error"]) { dest = process.stdout; } function getPrefix() { let prefix = ""; let type = event.type; if (type) { // hide timestamp when type is undefined prefix += dim(dateTimeFormat.format(new Date()) + " "); if (event.level === "info") { type = bold(cyan(`[${type}]`)); } else if (event.level === "warn") { type = bold(yellow(`[${type}]`)); } else if (event.level === "error") { type = bold(red(`[${type}]`)); } prefix += `${type} `; } return reset(prefix); } // console.log({msg: event.message, args: event.args}); let message = event.message; // For repeat messages, only update the message counter if (message === lastMessage) { lastMessageCount++; if (levels[event.level] < levels["error"]) { let lines = 1; let len = stringWidth(`${getPrefix()}${message}`); let cols = (dest as unknown as typeof process.stdout).columns; if (len > cols) { lines = Math.ceil(len / cols); } for (let i = 0; i < lines; i++) { readline.clearLine(dest, 0); readline.cursorTo(dest, 0); readline.moveCursor(dest, 0, -1); } } message = `${message} ${yellow(`(x${lastMessageCount})`)}`; } else { lastMessage = message; lastMessageCount = 1; } dest.write(getPrefix()); dest.write(message); dest.write("\n"); callback(); }, }); interface LogWritable<T> { write: (chunk: T) => boolean; } export type LoggerLevel = "debug" | "info" | "warn" | "error" | "silent"; // same as Pino export type LoggerEvent = "info" | "warn" | "error"; export interface LogOptions { dest?: LogWritable<LogMessage>; level?: LoggerLevel; } export const nodeLogOptions: Required<LogOptions> = { dest: nodeLogDestination, level: "info", }; export interface LogMessage { type: string | null; level: LoggerLevel; message: string; } export const levels: Record<LoggerLevel, number> = { debug: 20, info: 30, warn: 40, error: 50, silent: 90, }; const debuggers: Record<string, debugPackage.Debugger["log"]> = {}; /** * Emit a message only shown in debug mode. * Astro (along with many of its dependencies) uses the `debug` package for debug logging. * You can enable these logs with the `DEBUG=astro:*` environment variable. * More info https://github.com/debug-js/debug#environment-variables */ export function debug(type: string, ...messages: Array<any>) { const namespace = `astro:${type}`; debuggers[namespace] = debuggers[namespace] || debugPackage(namespace); return debuggers[namespace](...messages); } // This is gross, but necessary since we are depending on globals. (globalThis as any)._astroGlobalDebug = debug; // A default logger for when too lazy to pass LogOptions around. export const logger = { info: info.bind(null, nodeLogOptions), warn: warn.bind(null, nodeLogOptions), error:
error.bind(null, nodeLogOptions), };
export function enableVerboseLogging() { debug("cli", '--verbose flag enabled! Enabling: DEBUG="*,-babel"'); debug( "cli", 'Tip: Set the DEBUG env variable directly for more control. Example: "DEBUG=astro:*,vite:* astro build".' ); }
src/astro/logger/node.ts
jlarmstrongiv-astro-i18n-aut-dd68364
[ { "filename": "src/astro/logger/core.ts", "retrieved_chunk": "}\n/** Emit a warning message. Useful for high-priority messages that aren't necessarily errors. */\nexport function warn(opts: LogOptions, type: string | null, message: string) {\n return log(opts, \"warn\", type, message);\n}\n/** Emit a error message, Useful when Astro can't recover from some error. */\nexport function error(opts: LogOptions, type: string | null, message: string) {\n return log(opts, \"error\", type, message);\n}\ntype LogFn = typeof info | typeof warn | typeof error;", "score": 28.961233262064 }, { "filename": "src/astro/logger/core.ts", "retrieved_chunk": "import { dim } from \"kleur/colors\";\nimport stringWidth from \"string-width\";\ninterface LogWritable<T> {\n write: (chunk: T) => boolean;\n}\nexport type LoggerLevel = \"debug\" | \"info\" | \"warn\" | \"error\" | \"silent\"; // same as Pino\nexport type LoggerEvent = \"info\" | \"warn\" | \"error\";\nexport interface LogOptions {\n dest: LogWritable<LogMessage>;\n level: LoggerLevel;", "score": 21.79353242551622 }, { "filename": "src/astro/logger/core.ts", "retrieved_chunk": "export function table(opts: LogOptions, columns: number[]) {\n return function logTable(logFn: LogFn, ...input: Array<any>) {\n const message = columns\n .map((len, i) => padStr(input[i].toString(), len))\n .join(\" \");\n logFn(opts, null, message);\n };\n}\nexport function debug(...args: any[]) {\n if (\"_astroGlobalDebug\" in globalThis) {", "score": 20.928990197875493 }, { "filename": "src/astro/logger/core.ts", "retrieved_chunk": "export const levels: Record<LoggerLevel, number> = {\n debug: 20,\n info: 30,\n warn: 40,\n error: 50,\n silent: 90,\n};\n/** Full logging API */\nexport function log(\n opts: LogOptions,", "score": 19.77514572612474 }, { "filename": "src/astro/logger/core.ts", "retrieved_chunk": " };\n // test if this level is enabled or not\n if (levels[logLevel] > levels[level]) {\n return; // do nothing\n }\n dest.write(event);\n}\n/** Emit a user-facing message. Useful for UI and other console messages. */\nexport function info(opts: LogOptions, type: string | null, message: string) {\n return log(opts, \"info\", type, message);", "score": 17.054935900199137 } ]
typescript
error.bind(null, nodeLogOptions), };
import debugPackage from "debug"; import { bold, cyan, dim, red, reset, yellow } from "kleur/colors"; import * as readline from "readline"; import { Writable } from "stream"; import stringWidth from "string-width"; import { dateTimeFormat, error, info, warn } from "./core.js"; type ConsoleStream = Writable & { fd: 1 | 2; }; let lastMessage: string; let lastMessageCount = 1; export const nodeLogDestination = new Writable({ objectMode: true, write(event: LogMessage, _, callback) { let dest: ConsoleStream = process.stderr; if (levels[event.level] < levels["error"]) { dest = process.stdout; } function getPrefix() { let prefix = ""; let type = event.type; if (type) { // hide timestamp when type is undefined prefix += dim(dateTimeFormat.format(new Date()) + " "); if (event.level === "info") { type = bold(cyan(`[${type}]`)); } else if (event.level === "warn") { type = bold(yellow(`[${type}]`)); } else if (event.level === "error") { type = bold(red(`[${type}]`)); } prefix += `${type} `; } return reset(prefix); } // console.log({msg: event.message, args: event.args}); let message = event.message; // For repeat messages, only update the message counter if (message === lastMessage) { lastMessageCount++; if (levels[event.level] < levels["error"]) { let lines = 1; let len = stringWidth(`${getPrefix()}${message}`); let cols = (dest as unknown as typeof process.stdout).columns; if (len > cols) { lines = Math.ceil(len / cols); } for (let i = 0; i < lines; i++) { readline.clearLine(dest, 0); readline.cursorTo(dest, 0); readline.moveCursor(dest, 0, -1); } } message = `${message} ${yellow(`(x${lastMessageCount})`)}`; } else { lastMessage = message; lastMessageCount = 1; } dest.write(getPrefix()); dest.write(message); dest.write("\n"); callback(); }, }); interface LogWritable<T> { write: (chunk: T) => boolean; } export type LoggerLevel = "debug" | "info" | "warn" | "error" | "silent"; // same as Pino export type LoggerEvent = "info" | "warn" | "error"; export interface LogOptions { dest?: LogWritable<LogMessage>; level?: LoggerLevel; } export const nodeLogOptions: Required<LogOptions> = { dest: nodeLogDestination, level: "info", }; export interface LogMessage { type: string | null; level: LoggerLevel; message: string; } export const levels: Record<LoggerLevel, number> = { debug: 20, info: 30, warn: 40, error: 50, silent: 90, }; const debuggers: Record<string, debugPackage.Debugger["log"]> = {}; /** * Emit a message only shown in debug mode. * Astro (along with many of its dependencies) uses the `debug` package for debug logging. * You can enable these logs with the `DEBUG=astro:*` environment variable. * More info https://github.com/debug-js/debug#environment-variables */ export function debug(type: string, ...messages: Array<any>) { const namespace = `astro:${type}`; debuggers[namespace] = debuggers[namespace] || debugPackage(namespace); return debuggers[namespace](...messages); } // This is gross, but necessary since we are depending on globals. (globalThis as any)._astroGlobalDebug = debug; // A default logger for when too lazy to pass LogOptions around. export const logger = { info: info.bind(null, nodeLogOptions),
warn: warn.bind(null, nodeLogOptions), error: error.bind(null, nodeLogOptions), };
export function enableVerboseLogging() { debug("cli", '--verbose flag enabled! Enabling: DEBUG="*,-babel"'); debug( "cli", 'Tip: Set the DEBUG env variable directly for more control. Example: "DEBUG=astro:*,vite:* astro build".' ); }
src/astro/logger/node.ts
jlarmstrongiv-astro-i18n-aut-dd68364
[ { "filename": "src/astro/logger/core.ts", "retrieved_chunk": "}\n/** Emit a warning message. Useful for high-priority messages that aren't necessarily errors. */\nexport function warn(opts: LogOptions, type: string | null, message: string) {\n return log(opts, \"warn\", type, message);\n}\n/** Emit a error message, Useful when Astro can't recover from some error. */\nexport function error(opts: LogOptions, type: string | null, message: string) {\n return log(opts, \"error\", type, message);\n}\ntype LogFn = typeof info | typeof warn | typeof error;", "score": 31.41803712385869 }, { "filename": "src/astro/logger/core.ts", "retrieved_chunk": "import { dim } from \"kleur/colors\";\nimport stringWidth from \"string-width\";\ninterface LogWritable<T> {\n write: (chunk: T) => boolean;\n}\nexport type LoggerLevel = \"debug\" | \"info\" | \"warn\" | \"error\" | \"silent\"; // same as Pino\nexport type LoggerEvent = \"info\" | \"warn\" | \"error\";\nexport interface LogOptions {\n dest: LogWritable<LogMessage>;\n level: LoggerLevel;", "score": 21.79353242551622 }, { "filename": "src/astro/logger/core.ts", "retrieved_chunk": "export function table(opts: LogOptions, columns: number[]) {\n return function logTable(logFn: LogFn, ...input: Array<any>) {\n const message = columns\n .map((len, i) => padStr(input[i].toString(), len))\n .join(\" \");\n logFn(opts, null, message);\n };\n}\nexport function debug(...args: any[]) {\n if (\"_astroGlobalDebug\" in globalThis) {", "score": 21.435105549662065 }, { "filename": "src/astro/logger/core.ts", "retrieved_chunk": " };\n // test if this level is enabled or not\n if (levels[logLevel] > levels[level]) {\n return; // do nothing\n }\n dest.write(event);\n}\n/** Emit a user-facing message. Useful for UI and other console messages. */\nexport function info(opts: LogOptions, type: string | null, message: string) {\n return log(opts, \"info\", type, message);", "score": 20.112984176888205 }, { "filename": "src/astro/logger/core.ts", "retrieved_chunk": "export const levels: Record<LoggerLevel, number> = {\n debug: 20,\n info: 30,\n warn: 40,\n error: 50,\n silent: 90,\n};\n/** Full logging API */\nexport function log(\n opts: LogOptions,", "score": 19.77514572612474 } ]
typescript
warn: warn.bind(null, nodeLogOptions), error: error.bind(null, nodeLogOptions), };
import path from "node:path"; import type { AstroConfig, AstroIntegration } from "astro"; import dedent from "dedent"; import fg from "fast-glob"; import fs from "fs-extra"; import slash from "slash"; import { logger } from "../astro/logger/node"; import { removeLeadingForwardSlashWindows } from "../astro/internal-helpers/path"; import { defaultI18nConfig } from "../shared/configs"; import type { UserI18nConfig, I18nConfig } from "../shared/configs"; // injectRoute doesn't generate build pages https://github.com/withastro/astro/issues/5096 // workaround: copy pages folder when command === "build" /** * The i18n integration for Astro * * See the full [astro-i18n-aut](https://github.com/jlarmstrongiv/astro-i18n-aut#readme) documentation */ export function i18n(userI18nConfig: UserI18nConfig): AstroIntegration { const i18nConfig: I18nConfig = Object.assign( defaultI18nConfig, userI18nConfig ); const { defaultLocale, locales, exclude, include, redirectDefaultLocale } = i18nConfig; ensureValidLocales(locales, defaultLocale); let pagesPathTmp: Record<string, string> = {}; async function removePagesPathTmp(): Promise<void> { await Promise.all( Object.values(pagesPathTmp).map((pagePathTmp) => fs.remove(pagePathTmp)) ); } return { name: "astro-i18n-integration", hooks: { "astro:config:setup": async ({ config, command, injectRoute }) => { await ensureValidConfigs(config, i18nConfig); const configSrcDirPathname = path.normalize( removeLeadingForwardSlashWindows(config.srcDir.pathname) ); let included: string[] = ensureGlobsHaveConfigSrcDirPathname( typeof include === "string" ? [include] : include, configSrcDirPathname ); let excluded: string[] = ensureGlobsHaveConfigSrcDirPathname( typeof exclude === "string" ? [exclude] : exclude, configSrcDirPathname ); const pagesPath = path.join(configSrcDirPathname, "pages"); const pagesPathTmpRoot = path.join( configSrcDirPathname, // tmp filename from https://github.com/withastro/astro/blob/e6bff651ff80466b3e862e637d2a6a3334d8cfda/packages/astro/src/core/routing/manifest/create.ts#L279 "astro_tmp_pages" ); for (const locale of Object.keys(locales)) { pagesPathTmp[locale] = `${pagesPathTmpRoot}_${locale}`; } await removePagesPathTmp(); if (command === "build") { await Promise.all( Object.keys(locales) .filter((locale) => { if (redirectDefaultLocale === false) { return locale !== defaultLocale; } else { return true; } }) .map((locale) => fs.copy(pagesPath, pagesPathTmp[locale])) ); } const entries = fg.stream(included, { ignore: excluded, onlyFiles: true, }); // typing https://stackoverflow.com/a/68358341 let entry: string; // @ts-expect-error for await (entry of entries) { const parsedPath = path.parse(entry); const relativePath = path.relative(pagesPath, parsedPath.dir); const extname = parsedPath.ext.slice(1).toLowerCase(); // warn on files that cannot be translated with specific and actionable warnings // astro pages file types https://docs.astro.build/en/core-concepts/astro-pages/#supported-page-files // any file that is not included as an astro page file types, will be automatically warned about by astro if (extname !== "astro") { warnIsInvalidPage( extname, path.join(relativePath, parsedPath.base), configSrcDirPathname ); continue; } for (const locale of Object.keys(locales)) { // ignore defaultLocale if redirectDefaultLocale is false if (redirectDefaultLocale === false && locale === defaultLocale) { continue; } const entryPoint = command === "build" ? path.join(pagesPathTmp[locale], relativePath, parsedPath.base) : path.join(pagesPath, relativePath, parsedPath.base); const pattern = slash( path.join( config.base, locale, relativePath, parsedPath.name.endsWith("index") ? "" : parsedPath.name, config.build.format === "directory" ? "/" : "" ) ); injectRoute({ entryPoint, pattern, }); } } }, "astro:build:done": async () => { await removePagesPathTmp(); }, "astro:server:done": async () => { await removePagesPathTmp(); }, }, }; } function ensureValidLocales( locales: Record<string, string>, defaultLocale: string ) { if (!Object.keys(locales).includes(defaultLocale)) { const errorMessage = `locales ${JSON.stringify( locales )} does not include "${defaultLocale}"`; logger
.error("astro-i18n-aut", errorMessage);
throw new Error(errorMessage); } } async function ensureValidConfigs(config: AstroConfig, i18nConfig: I18nConfig) { if (config.trailingSlash === "ignore" && config.output === "static") { logger.warn( "astro-i18n-aut", `avoid setting config.trailingSlash = "ignore" when config.output = "static"` ); logger.warn( "astro-i18n-aut", `config.trailingSlash = "always" && config.build.format = "directory"` ); logger.warn( "astro-i18n-aut", `config.trailingSlash = "never" && config.build.format = "file"` ); logger.warn( "astro-i18n-aut", `setting config.trailingSlash = "${config.trailingSlash}"` ); config.trailingSlash = config.build.format === "directory" ? "always" : "never"; } if (i18nConfig.redirectDefaultLocale) { const configSrcDirPathname = path.normalize( removeLeadingForwardSlashWindows(config.srcDir.pathname) ); // all possible locations of middleware const defaultMiddlewarePath = path.join( configSrcDirPathname, "middleware/index.ts" ); const middlewarePaths = [ path.join(configSrcDirPathname, "middleware.js"), path.join(configSrcDirPathname, "middleware.ts"), path.join(configSrcDirPathname, "middleware/index.js"), defaultMiddlewarePath, ]; // check if middleware exists const pathsExist = await Promise.all( middlewarePaths.map((middlewarePath) => fs.exists(middlewarePath)) ); const pathExists = pathsExist.includes(true); // warn and create middleware if it does not exist if (pathExists === false) { logger.warn("astro-i18n-aut", `cannot find any Astro middleware files:`); middlewarePaths.forEach((middlewarePath) => { logger.warn("astro-i18n-aut", `- ${middlewarePath}`); }); logger.warn( "astro-i18n-aut", `creating ${defaultMiddlewarePath} with defaultLocale = "en"` ); await fs.outputFile( defaultMiddlewarePath, dedent(` import { sequence } from "astro/middleware"; import { i18nMiddleware } from "astro-i18n-aut"; const i18n = i18nMiddleware({ defaultLocale: "en" }); export const onRequest = sequence(i18n); `) ); } } } function ensureGlobsHaveConfigSrcDirPathname( filePaths: string[], configSrcDirPathname: string ) { return filePaths.map((filePath) => { filePath = path.normalize(removeLeadingForwardSlashWindows(filePath)); if (filePath.includes(configSrcDirPathname)) { filePath = path.relative(configSrcDirPathname, filePath); } // fast-glob prefers unix paths https://www.npmjs.com/package/fast-glob#how-to-write-patterns-on-windows filePath = path.posix.join( fg.convertPathToPattern(configSrcDirPathname), slash(filePath) ); return filePath; }); } let hasWarnedIsInvalidPage = false; function warnIsInvalidPage( extname: string, filePath: string, configSrcDirPathname: string ): boolean { // astro pages file types https://docs.astro.build/en/core-concepts/astro-pages/#supported-page-files if (["js", "ts", "md", "mdx", "html"].includes(extname)) { if (hasWarnedIsInvalidPage === false) { logger.warn( "astro-i18n-aut", `exclude or remove non-astro files from "${configSrcDirPathname}pages", as they cannot be translated` ); hasWarnedIsInvalidPage = true; } logger.warn( "astro-i18n-aut", path.join(configSrcDirPathname, "pages", filePath) ); return true; } return false; }
src/integration/integration.ts
jlarmstrongiv-astro-i18n-aut-dd68364
[ { "filename": "src/shared/configs.ts", "retrieved_chunk": " * fr: \"fr-CA\",\n * };\n * ```\n */\n locales: Record<string, string>;\n /**\n * the default language locale\n *\n * the `defaultLocale` value must present in `locales` keys\n *", "score": 30.46637577422965 }, { "filename": "src/shared/configs.ts", "retrieved_chunk": " */\n exclude?: string | string[];\n /**\n * all language locales\n *\n * @example\n * ```ts\n * const locales = {\n * en: \"en-US\", // the `defaultLocale` value must present in `locales` keys\n * es: \"es-ES\",", "score": 28.6341281183683 }, { "filename": "src/edge-runtime/middleware.ts", "retrieved_chunk": "export function i18nMiddleware(\n userI18nMiddlewareConfig: UserI18nMiddlewareConfig\n) {\n const i18nMiddlewareConfig: I18nMiddlewareConfig = Object.assign(\n defaultI18nMiddlewareConfig,\n userI18nMiddlewareConfig\n );\n const { defaultLocale, redirectDefaultLocale } = i18nMiddlewareConfig;\n if (redirectDefaultLocale === false) {\n return redirectDefaultLocaleDisabledMiddleware;", "score": 10.23619724701612 }, { "filename": "src/astro/logger/core.ts", "retrieved_chunk": "}\n// Hey, locales are pretty complicated! Be careful modifying this logic...\n// If we throw at the top-level, international users can't use Astro.\n//\n// Using `[]` sets the default locale properly from the system!\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat#parameters\n//\n// Here be the dragons we've slain:\n// https://github.com/withastro/astro/issues/2625\n// https://github.com/withastro/astro/issues/3309", "score": 9.061757375962049 }, { "filename": "src/shared/configs.ts", "retrieved_chunk": "import type { ValidRedirectStatus } from \"astro\";\nexport interface UserI18nConfig {\n /**\n * glob pattern(s) to include\n * @defaultValue [\"pages\\/\\*\\*\\/\\*\"]\n */\n include?: string | string[];\n /**\n * glob pattern(s) to exclude\n * @defaultValue [\"pages\\/api\\/\\*\\*\\/\\*\"]", "score": 8.942171882005784 } ]
typescript
.error("astro-i18n-aut", errorMessage);
import debugPackage from "debug"; import { bold, cyan, dim, red, reset, yellow } from "kleur/colors"; import * as readline from "readline"; import { Writable } from "stream"; import stringWidth from "string-width"; import { dateTimeFormat, error, info, warn } from "./core.js"; type ConsoleStream = Writable & { fd: 1 | 2; }; let lastMessage: string; let lastMessageCount = 1; export const nodeLogDestination = new Writable({ objectMode: true, write(event: LogMessage, _, callback) { let dest: ConsoleStream = process.stderr; if (levels[event.level] < levels["error"]) { dest = process.stdout; } function getPrefix() { let prefix = ""; let type = event.type; if (type) { // hide timestamp when type is undefined prefix += dim(dateTimeFormat.format(new Date()) + " "); if (event.level === "info") { type = bold(cyan(`[${type}]`)); } else if (event.level === "warn") { type = bold(yellow(`[${type}]`)); } else if (event.level === "error") { type = bold(red(`[${type}]`)); } prefix += `${type} `; } return reset(prefix); } // console.log({msg: event.message, args: event.args}); let message = event.message; // For repeat messages, only update the message counter if (message === lastMessage) { lastMessageCount++; if (levels[event.level] < levels["error"]) { let lines = 1; let len = stringWidth(`${getPrefix()}${message}`); let cols = (dest as unknown as typeof process.stdout).columns; if (len > cols) { lines = Math.ceil(len / cols); } for (let i = 0; i < lines; i++) { readline.clearLine(dest, 0); readline.cursorTo(dest, 0); readline.moveCursor(dest, 0, -1); } } message = `${message} ${yellow(`(x${lastMessageCount})`)}`; } else { lastMessage = message; lastMessageCount = 1; } dest.write(getPrefix()); dest.write(message); dest.write("\n"); callback(); }, }); interface LogWritable<T> { write: (chunk: T) => boolean; } export type LoggerLevel = "debug" | "info" | "warn" | "error" | "silent"; // same as Pino export type LoggerEvent = "info" | "warn" | "error"; export interface LogOptions { dest?: LogWritable<LogMessage>; level?: LoggerLevel; } export const nodeLogOptions: Required<LogOptions> = { dest: nodeLogDestination, level: "info", }; export interface LogMessage { type: string | null; level: LoggerLevel; message: string; } export const levels: Record<LoggerLevel, number> = { debug: 20, info: 30, warn: 40, error: 50, silent: 90, }; const debuggers: Record<string, debugPackage.Debugger["log"]> = {}; /** * Emit a message only shown in debug mode. * Astro (along with many of its dependencies) uses the `debug` package for debug logging. * You can enable these logs with the `DEBUG=astro:*` environment variable. * More info https://github.com/debug-js/debug#environment-variables */ export function debug(type: string, ...messages: Array<any>) { const namespace = `astro:${type}`; debuggers[namespace] = debuggers[namespace] || debugPackage(namespace); return debuggers[namespace](...messages); } // This is gross, but necessary since we are depending on globals. (globalThis as any)._astroGlobalDebug = debug; // A default logger for when too lazy to pass LogOptions around. export const logger = { info: info.bind(null, nodeLogOptions), warn:
warn.bind(null, nodeLogOptions), error: error.bind(null, nodeLogOptions), };
export function enableVerboseLogging() { debug("cli", '--verbose flag enabled! Enabling: DEBUG="*,-babel"'); debug( "cli", 'Tip: Set the DEBUG env variable directly for more control. Example: "DEBUG=astro:*,vite:* astro build".' ); }
src/astro/logger/node.ts
jlarmstrongiv-astro-i18n-aut-dd68364
[ { "filename": "src/astro/logger/core.ts", "retrieved_chunk": "}\n/** Emit a warning message. Useful for high-priority messages that aren't necessarily errors. */\nexport function warn(opts: LogOptions, type: string | null, message: string) {\n return log(opts, \"warn\", type, message);\n}\n/** Emit a error message, Useful when Astro can't recover from some error. */\nexport function error(opts: LogOptions, type: string | null, message: string) {\n return log(opts, \"error\", type, message);\n}\ntype LogFn = typeof info | typeof warn | typeof error;", "score": 28.961233262064 }, { "filename": "src/astro/logger/core.ts", "retrieved_chunk": "import { dim } from \"kleur/colors\";\nimport stringWidth from \"string-width\";\ninterface LogWritable<T> {\n write: (chunk: T) => boolean;\n}\nexport type LoggerLevel = \"debug\" | \"info\" | \"warn\" | \"error\" | \"silent\"; // same as Pino\nexport type LoggerEvent = \"info\" | \"warn\" | \"error\";\nexport interface LogOptions {\n dest: LogWritable<LogMessage>;\n level: LoggerLevel;", "score": 21.79353242551622 }, { "filename": "src/astro/logger/core.ts", "retrieved_chunk": "export function table(opts: LogOptions, columns: number[]) {\n return function logTable(logFn: LogFn, ...input: Array<any>) {\n const message = columns\n .map((len, i) => padStr(input[i].toString(), len))\n .join(\" \");\n logFn(opts, null, message);\n };\n}\nexport function debug(...args: any[]) {\n if (\"_astroGlobalDebug\" in globalThis) {", "score": 20.928990197875493 }, { "filename": "src/astro/logger/core.ts", "retrieved_chunk": "export const levels: Record<LoggerLevel, number> = {\n debug: 20,\n info: 30,\n warn: 40,\n error: 50,\n silent: 90,\n};\n/** Full logging API */\nexport function log(\n opts: LogOptions,", "score": 19.77514572612474 }, { "filename": "src/astro/logger/core.ts", "retrieved_chunk": " };\n // test if this level is enabled or not\n if (levels[logLevel] > levels[level]) {\n return; // do nothing\n }\n dest.write(event);\n}\n/** Emit a user-facing message. Useful for UI and other console messages. */\nexport function info(opts: LogOptions, type: string | null, message: string) {\n return log(opts, \"info\", type, message);", "score": 17.054935900199137 } ]
typescript
warn.bind(null, nodeLogOptions), error: error.bind(null, nodeLogOptions), };
import debugPackage from "debug"; import { bold, cyan, dim, red, reset, yellow } from "kleur/colors"; import * as readline from "readline"; import { Writable } from "stream"; import stringWidth from "string-width"; import { dateTimeFormat, error, info, warn } from "./core.js"; type ConsoleStream = Writable & { fd: 1 | 2; }; let lastMessage: string; let lastMessageCount = 1; export const nodeLogDestination = new Writable({ objectMode: true, write(event: LogMessage, _, callback) { let dest: ConsoleStream = process.stderr; if (levels[event.level] < levels["error"]) { dest = process.stdout; } function getPrefix() { let prefix = ""; let type = event.type; if (type) { // hide timestamp when type is undefined prefix += dim(dateTimeFormat.format(new Date()) + " "); if (event.level === "info") { type = bold(cyan(`[${type}]`)); } else if (event.level === "warn") { type = bold(yellow(`[${type}]`)); } else if (event.level === "error") { type = bold(red(`[${type}]`)); } prefix += `${type} `; } return reset(prefix); } // console.log({msg: event.message, args: event.args}); let message = event.message; // For repeat messages, only update the message counter if (message === lastMessage) { lastMessageCount++; if (levels[event.level] < levels["error"]) { let lines = 1; let len = stringWidth(`${getPrefix()}${message}`); let cols = (dest as unknown as typeof process.stdout).columns; if (len > cols) { lines = Math.ceil(len / cols); } for (let i = 0; i < lines; i++) { readline.clearLine(dest, 0); readline.cursorTo(dest, 0); readline.moveCursor(dest, 0, -1); } } message = `${message} ${yellow(`(x${lastMessageCount})`)}`; } else { lastMessage = message; lastMessageCount = 1; } dest.write(getPrefix()); dest.write(message); dest.write("\n"); callback(); }, }); interface LogWritable<T> { write: (chunk: T) => boolean; } export type LoggerLevel = "debug" | "info" | "warn" | "error" | "silent"; // same as Pino export type LoggerEvent = "info" | "warn" | "error"; export interface LogOptions { dest?: LogWritable<LogMessage>; level?: LoggerLevel; } export const nodeLogOptions: Required<LogOptions> = { dest: nodeLogDestination, level: "info", }; export interface LogMessage { type: string | null; level: LoggerLevel; message: string; } export const levels: Record<LoggerLevel, number> = { debug: 20, info: 30, warn: 40, error: 50, silent: 90, }; const debuggers: Record<string, debugPackage.Debugger["log"]> = {}; /** * Emit a message only shown in debug mode. * Astro (along with many of its dependencies) uses the `debug` package for debug logging. * You can enable these logs with the `DEBUG=astro:*` environment variable. * More info https://github.com/debug-js/debug#environment-variables */ export function debug(type: string, ...messages: Array<any>) { const namespace = `astro:${type}`; debuggers[namespace] = debuggers[namespace] || debugPackage(namespace); return debuggers[namespace](...messages); } // This is gross, but necessary since we are depending on globals. (globalThis as any)._astroGlobalDebug = debug; // A default logger for when too lazy to pass LogOptions around. export const logger = { info: info.bind(null, nodeLogOptions), warn: warn.bind(null, nodeLogOptions),
error: error.bind(null, nodeLogOptions), };
export function enableVerboseLogging() { debug("cli", '--verbose flag enabled! Enabling: DEBUG="*,-babel"'); debug( "cli", 'Tip: Set the DEBUG env variable directly for more control. Example: "DEBUG=astro:*,vite:* astro build".' ); }
src/astro/logger/node.ts
jlarmstrongiv-astro-i18n-aut-dd68364
[ { "filename": "src/astro/logger/core.ts", "retrieved_chunk": "}\n/** Emit a warning message. Useful for high-priority messages that aren't necessarily errors. */\nexport function warn(opts: LogOptions, type: string | null, message: string) {\n return log(opts, \"warn\", type, message);\n}\n/** Emit a error message, Useful when Astro can't recover from some error. */\nexport function error(opts: LogOptions, type: string | null, message: string) {\n return log(opts, \"error\", type, message);\n}\ntype LogFn = typeof info | typeof warn | typeof error;", "score": 31.41803712385869 }, { "filename": "src/astro/logger/core.ts", "retrieved_chunk": "import { dim } from \"kleur/colors\";\nimport stringWidth from \"string-width\";\ninterface LogWritable<T> {\n write: (chunk: T) => boolean;\n}\nexport type LoggerLevel = \"debug\" | \"info\" | \"warn\" | \"error\" | \"silent\"; // same as Pino\nexport type LoggerEvent = \"info\" | \"warn\" | \"error\";\nexport interface LogOptions {\n dest: LogWritable<LogMessage>;\n level: LoggerLevel;", "score": 21.79353242551622 }, { "filename": "src/astro/logger/core.ts", "retrieved_chunk": "export function table(opts: LogOptions, columns: number[]) {\n return function logTable(logFn: LogFn, ...input: Array<any>) {\n const message = columns\n .map((len, i) => padStr(input[i].toString(), len))\n .join(\" \");\n logFn(opts, null, message);\n };\n}\nexport function debug(...args: any[]) {\n if (\"_astroGlobalDebug\" in globalThis) {", "score": 21.435105549662065 }, { "filename": "src/astro/logger/core.ts", "retrieved_chunk": " };\n // test if this level is enabled or not\n if (levels[logLevel] > levels[level]) {\n return; // do nothing\n }\n dest.write(event);\n}\n/** Emit a user-facing message. Useful for UI and other console messages. */\nexport function info(opts: LogOptions, type: string | null, message: string) {\n return log(opts, \"info\", type, message);", "score": 20.112984176888205 }, { "filename": "src/astro/logger/core.ts", "retrieved_chunk": "export const levels: Record<LoggerLevel, number> = {\n debug: 20,\n info: 30,\n warn: 40,\n error: 50,\n silent: 90,\n};\n/** Full logging API */\nexport function log(\n opts: LogOptions,", "score": 19.77514572612474 } ]
typescript
error: error.bind(null, nodeLogOptions), };
require('dotenv').config(); import { AnyThreadChannel, ApplicationCommandOptionType, ApplicationCommandType, Channel, ChannelType, CommandInteraction, Guild, TextChannel } from 'discord.js'; import { GetTasks, SetThreadId, Task, TasksToString } from '../tasks'; import { Command } from '../types/Command'; import { ToDoClient } from '../types/ToDoClient'; export const Taskboard: Command = { name: "taskboard", description: "Set taskboard channel", type: ApplicationCommandType.ChatInput, options: [ { name: "channel", description: "The channel you want to set as the taskboard channel", required: true, type: ApplicationCommandOptionType.Channel } ], run: async (interaction: CommandInteraction, client: ToDoClient) => { let channelID = interaction.options.get('channel').value.toString(); let channel: Channel = await client.channels.fetch(channelID); let content = ""; if (channel.type == ChannelType.GuildText) { client.taskboardID = channelID; content = "okey taskboard is now channel with id: `" + channelID + "` aka " + channel.toString(); channel.send(`## This is the taskboard\n\n${TasksToString()}`); for (let task of GetTasks()) { let threadId = await CreateThreadForTask(task, client); SetThreadId(task.id, threadId); } } else { content = "bro this is not text channel, id `" + channelID + "` type: `" + channel.type + "` (https://discord.com/developers/docs/resources/channel) aka " + channel.toString(); } await interaction.followUp({ ephemeral: false, content }) } } export async function CreateThreadForTask(task: Task, client: ToDoClient): Promise<string> { let channel: TextChannel = await GetTaskboardTextChannel(client); let taskThread = await channel.threads.create({ name: `${task.id} | ${task.description} | <@${task.assignee}>`, type: ChannelType.PublicThread, }) taskThread.send(`${task.description}, for <@${task.assignee}> | ${task.id}`); return taskThread.id; } export async function CloseThreadForTask(task: Task, client: ToDoClient): Promise<AnyThreadChannel<boolean>> { let channel: TextChannel = await GetTaskboardTextChannel(client); let thread = await channel.
threads.fetch(task.threadId);
await thread.send("Task remove. Closing thread."); return await thread.setArchived(); } async function GetTaskboardTextChannel(client: ToDoClient): Promise<TextChannel> { return await client.channels.fetch(client.taskboardID) as TextChannel; } export async function SendMessageToThread(task: Task, client: ToDoClient): Promise<string> { // TODO return "" }
src/commands/taskboard.ts
savipauk-ToDoBot-a21f22e
[ { "filename": "src/commands/todo.ts", "retrieved_chunk": " if (client.taskboardID != null) {\n let threadId = await CreateThreadForTask(task, client);\n SetThreadId(task.id, threadId);\n }\n let content = `Set task \"${taskDesc}\" (ID ${task.id}) for ${user}`;\n await interaction.followUp({\n ephemeral: false,\n content\n })\n }", "score": 23.622303426249147 }, { "filename": "src/tasks.ts", "retrieved_chunk": "export function AddTask(description: string, assignee: string, threadId?: string): Task {\n let id = FindLastId();\n let task: Task = {\n id, description, assignee, threadId\n }\n _AddTask(task);\n return task;\n}\nexport function RemoveTask(id: number): Task {\n let tasks = GetTasks();", "score": 23.195661435423744 }, { "filename": "src/ready.ts", "retrieved_chunk": " /*\n TODO:\n Creates a ToDoBot channel category and a Taskboard text channel in it. Discuss. \n let server: Guild = await client.guilds.fetch(process.env.guildId);\n let category: CategoryChannel = await server.channels.create({\n name: \"ToDoBot\",\n type: ChannelType.GuildCategory\n });\n await server.channels.create({\n name: \"Taskboard\",", "score": 21.724761982710362 }, { "filename": "src/tasks.ts", "retrieved_chunk": " if (task.id == id) {\n if (assignee != undefined) task.assignee = assignee.id;\n editedTask = task;\n }\n _AddTask(task);\n }\n return editedTask;\n}\nexport function SetDescription(id: number, description: string): Task {\n let tasks = GetTasks();", "score": 20.983581547874607 }, { "filename": "src/tasks.ts", "retrieved_chunk": " return removedTask;\n}\nexport function SetThreadId(id: number, threadId: string): Task {\n let tasks = GetTasks();\n FlushTasks();\n let editedTask: Task = null;\n for (let task of tasks) {\n if (task.id == id) {\n if (threadId != undefined) task.threadId = threadId;\n editedTask = task;", "score": 20.420674253501648 } ]
typescript
threads.fetch(task.threadId);
import path from "node:path"; import type { AstroConfig, AstroIntegration } from "astro"; import dedent from "dedent"; import fg from "fast-glob"; import fs from "fs-extra"; import slash from "slash"; import { logger } from "../astro/logger/node"; import { removeLeadingForwardSlashWindows } from "../astro/internal-helpers/path"; import { defaultI18nConfig } from "../shared/configs"; import type { UserI18nConfig, I18nConfig } from "../shared/configs"; // injectRoute doesn't generate build pages https://github.com/withastro/astro/issues/5096 // workaround: copy pages folder when command === "build" /** * The i18n integration for Astro * * See the full [astro-i18n-aut](https://github.com/jlarmstrongiv/astro-i18n-aut#readme) documentation */ export function i18n(userI18nConfig: UserI18nConfig): AstroIntegration { const i18nConfig: I18nConfig = Object.assign( defaultI18nConfig, userI18nConfig ); const { defaultLocale, locales, exclude, include, redirectDefaultLocale } = i18nConfig; ensureValidLocales(locales, defaultLocale); let pagesPathTmp: Record<string, string> = {}; async function removePagesPathTmp(): Promise<void> { await Promise.all( Object.values(pagesPathTmp).map((pagePathTmp) => fs.remove(pagePathTmp)) ); } return { name: "astro-i18n-integration", hooks: { "astro:config:setup": async ({ config, command, injectRoute }) => { await ensureValidConfigs(config, i18nConfig); const configSrcDirPathname = path.normalize( removeLeadingForwardSlashWindows(config.srcDir.pathname) ); let included: string[] = ensureGlobsHaveConfigSrcDirPathname( typeof include === "string" ? [include] : include, configSrcDirPathname ); let excluded: string[] = ensureGlobsHaveConfigSrcDirPathname( typeof exclude === "string" ? [exclude] : exclude, configSrcDirPathname ); const pagesPath = path.join(configSrcDirPathname, "pages"); const pagesPathTmpRoot = path.join( configSrcDirPathname, // tmp filename from https://github.com/withastro/astro/blob/e6bff651ff80466b3e862e637d2a6a3334d8cfda/packages/astro/src/core/routing/manifest/create.ts#L279 "astro_tmp_pages" ); for (const locale of Object.keys(locales)) { pagesPathTmp[locale] = `${pagesPathTmpRoot}_${locale}`; } await removePagesPathTmp(); if (command === "build") { await Promise.all( Object.keys(locales) .filter((locale) => { if (redirectDefaultLocale === false) { return locale !== defaultLocale; } else { return true; } }) .map((locale) => fs.copy(pagesPath, pagesPathTmp[locale])) ); } const entries = fg.stream(included, { ignore: excluded, onlyFiles: true, }); // typing https://stackoverflow.com/a/68358341 let entry: string; // @ts-expect-error for await (entry of entries) { const parsedPath = path.parse(entry); const relativePath = path.relative(pagesPath, parsedPath.dir); const extname = parsedPath.ext.slice(1).toLowerCase(); // warn on files that cannot be translated with specific and actionable warnings // astro pages file types https://docs.astro.build/en/core-concepts/astro-pages/#supported-page-files // any file that is not included as an astro page file types, will be automatically warned about by astro if (extname !== "astro") { warnIsInvalidPage( extname, path.join(relativePath, parsedPath.base), configSrcDirPathname ); continue; } for (const locale of Object.keys(locales)) { // ignore defaultLocale if redirectDefaultLocale is false if (redirectDefaultLocale === false && locale === defaultLocale) { continue; } const entryPoint = command === "build" ? path.join(pagesPathTmp[locale], relativePath, parsedPath.base) : path.join(pagesPath, relativePath, parsedPath.base); const pattern = slash( path.join( config.base, locale, relativePath, parsedPath.name.endsWith("index") ? "" : parsedPath.name, config.build.format === "directory" ? "/" : "" ) ); injectRoute({ entryPoint, pattern, }); } } }, "astro:build:done": async () => { await removePagesPathTmp(); }, "astro:server:done": async () => { await removePagesPathTmp(); }, }, }; } function ensureValidLocales( locales: Record<string, string>, defaultLocale: string ) { if (!Object.keys(locales).includes(defaultLocale)) { const errorMessage = `locales ${JSON.stringify( locales )} does not include "${defaultLocale}"`; logger.error("astro-i18n-aut", errorMessage); throw new Error(errorMessage); } } async function ensureValidConfigs(config: AstroConfig, i18nConfig: I18nConfig) { if (config.trailingSlash === "ignore" && config.output === "static") {
logger.warn( "astro-i18n-aut", `avoid setting config.trailingSlash = "ignore" when config.output = "static"` );
logger.warn( "astro-i18n-aut", `config.trailingSlash = "always" && config.build.format = "directory"` ); logger.warn( "astro-i18n-aut", `config.trailingSlash = "never" && config.build.format = "file"` ); logger.warn( "astro-i18n-aut", `setting config.trailingSlash = "${config.trailingSlash}"` ); config.trailingSlash = config.build.format === "directory" ? "always" : "never"; } if (i18nConfig.redirectDefaultLocale) { const configSrcDirPathname = path.normalize( removeLeadingForwardSlashWindows(config.srcDir.pathname) ); // all possible locations of middleware const defaultMiddlewarePath = path.join( configSrcDirPathname, "middleware/index.ts" ); const middlewarePaths = [ path.join(configSrcDirPathname, "middleware.js"), path.join(configSrcDirPathname, "middleware.ts"), path.join(configSrcDirPathname, "middleware/index.js"), defaultMiddlewarePath, ]; // check if middleware exists const pathsExist = await Promise.all( middlewarePaths.map((middlewarePath) => fs.exists(middlewarePath)) ); const pathExists = pathsExist.includes(true); // warn and create middleware if it does not exist if (pathExists === false) { logger.warn("astro-i18n-aut", `cannot find any Astro middleware files:`); middlewarePaths.forEach((middlewarePath) => { logger.warn("astro-i18n-aut", `- ${middlewarePath}`); }); logger.warn( "astro-i18n-aut", `creating ${defaultMiddlewarePath} with defaultLocale = "en"` ); await fs.outputFile( defaultMiddlewarePath, dedent(` import { sequence } from "astro/middleware"; import { i18nMiddleware } from "astro-i18n-aut"; const i18n = i18nMiddleware({ defaultLocale: "en" }); export const onRequest = sequence(i18n); `) ); } } } function ensureGlobsHaveConfigSrcDirPathname( filePaths: string[], configSrcDirPathname: string ) { return filePaths.map((filePath) => { filePath = path.normalize(removeLeadingForwardSlashWindows(filePath)); if (filePath.includes(configSrcDirPathname)) { filePath = path.relative(configSrcDirPathname, filePath); } // fast-glob prefers unix paths https://www.npmjs.com/package/fast-glob#how-to-write-patterns-on-windows filePath = path.posix.join( fg.convertPathToPattern(configSrcDirPathname), slash(filePath) ); return filePath; }); } let hasWarnedIsInvalidPage = false; function warnIsInvalidPage( extname: string, filePath: string, configSrcDirPathname: string ): boolean { // astro pages file types https://docs.astro.build/en/core-concepts/astro-pages/#supported-page-files if (["js", "ts", "md", "mdx", "html"].includes(extname)) { if (hasWarnedIsInvalidPage === false) { logger.warn( "astro-i18n-aut", `exclude or remove non-astro files from "${configSrcDirPathname}pages", as they cannot be translated` ); hasWarnedIsInvalidPage = true; } logger.warn( "astro-i18n-aut", path.join(configSrcDirPathname, "pages", filePath) ); return true; } return false; }
src/integration/integration.ts
jlarmstrongiv-astro-i18n-aut-dd68364
[ { "filename": "src/astro/logger/node.ts", "retrieved_chunk": "}\n// This is gross, but necessary since we are depending on globals.\n(globalThis as any)._astroGlobalDebug = debug;\n// A default logger for when too lazy to pass LogOptions around.\nexport const logger = {\n info: info.bind(null, nodeLogOptions),\n warn: warn.bind(null, nodeLogOptions),\n error: error.bind(null, nodeLogOptions),\n};\nexport function enableVerboseLogging() {", "score": 14.825260167250892 }, { "filename": "src/integration/index.ts", "retrieved_chunk": "export { i18n, i18n as default } from \"./integration\";\nexport { defaultLocaleSitemapFilter } from \"../shared/defaultLocaleSitemapFilter\";\nexport {\n defaultI18nConfig,\n defaultI18nMiddlewareConfig,\n} from \"../shared/configs\";\nexport type {\n UserI18nConfig,\n UserI18nMiddlewareConfig,\n UserDefaultLocaleSitemapFilterConfig,", "score": 11.19344757792885 }, { "filename": "src/shared/defaultLocaleSitemapFilter.ts", "retrieved_chunk": "import type { UserDefaultLocaleSitemapFilterConfig } from \"./configs\";\n// sitemap filter https://docs.astro.build/en/guides/integrations-guide/sitemap/#filter\nexport function defaultLocaleSitemapFilter({\n defaultLocale,\n}: UserDefaultLocaleSitemapFilterConfig) {\n return function filter(page: string) {\n const pagePathname = new URL(page).pathname;\n return (\n // avoid catching urls that start with \"/en\" like \"/enigma\"\n pagePathname !== `/${defaultLocale}` &&", "score": 7.993533147759939 }, { "filename": "src/astro/logger/node.ts", "retrieved_chunk": " let type = event.type;\n if (type) {\n // hide timestamp when type is undefined\n prefix += dim(dateTimeFormat.format(new Date()) + \" \");\n if (event.level === \"info\") {\n type = bold(cyan(`[${type}]`));\n } else if (event.level === \"warn\") {\n type = bold(yellow(`[${type}]`));\n } else if (event.level === \"error\") {\n type = bold(red(`[${type}]`));", "score": 7.063030389756342 }, { "filename": "src/astro/logger/core.ts", "retrieved_chunk": "}\n// Hey, locales are pretty complicated! Be careful modifying this logic...\n// If we throw at the top-level, international users can't use Astro.\n//\n// Using `[]` sets the default locale properly from the system!\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat#parameters\n//\n// Here be the dragons we've slain:\n// https://github.com/withastro/astro/issues/2625\n// https://github.com/withastro/astro/issues/3309", "score": 6.476495074731664 } ]
typescript
logger.warn( "astro-i18n-aut", `avoid setting config.trailingSlash = "ignore" when config.output = "static"` );
require('dotenv').config(); import { AnyThreadChannel, ApplicationCommandOptionType, ApplicationCommandType, Channel, ChannelType, CommandInteraction, Guild, TextChannel } from 'discord.js'; import { GetTasks, SetThreadId, Task, TasksToString } from '../tasks'; import { Command } from '../types/Command'; import { ToDoClient } from '../types/ToDoClient'; export const Taskboard: Command = { name: "taskboard", description: "Set taskboard channel", type: ApplicationCommandType.ChatInput, options: [ { name: "channel", description: "The channel you want to set as the taskboard channel", required: true, type: ApplicationCommandOptionType.Channel } ], run: async (interaction: CommandInteraction, client: ToDoClient) => { let channelID = interaction.options.get('channel').value.toString(); let channel: Channel = await client.channels.fetch(channelID); let content = ""; if (channel.type == ChannelType.GuildText) { client.taskboardID = channelID; content = "okey taskboard is now channel with id: `" + channelID + "` aka " + channel.toString(); channel.send(`## This is the taskboard\n\n${TasksToString()}`); for (let task of GetTasks()) { let threadId = await CreateThreadForTask(task, client); SetThreadId(task.id, threadId); } } else { content = "bro this is not text channel, id `" + channelID + "` type: `" + channel.type + "` (https://discord.com/developers/docs/resources/channel) aka " + channel.toString(); } await interaction.followUp({ ephemeral: false, content }) } }
export async function CreateThreadForTask(task: Task, client: ToDoClient): Promise<string> {
let channel: TextChannel = await GetTaskboardTextChannel(client); let taskThread = await channel.threads.create({ name: `${task.id} | ${task.description} | <@${task.assignee}>`, type: ChannelType.PublicThread, }) taskThread.send(`${task.description}, for <@${task.assignee}> | ${task.id}`); return taskThread.id; } export async function CloseThreadForTask(task: Task, client: ToDoClient): Promise<AnyThreadChannel<boolean>> { let channel: TextChannel = await GetTaskboardTextChannel(client); let thread = await channel.threads.fetch(task.threadId); await thread.send("Task remove. Closing thread."); return await thread.setArchived(); } async function GetTaskboardTextChannel(client: ToDoClient): Promise<TextChannel> { return await client.channels.fetch(client.taskboardID) as TextChannel; } export async function SendMessageToThread(task: Task, client: ToDoClient): Promise<string> { // TODO return "" }
src/commands/taskboard.ts
savipauk-ToDoBot-a21f22e
[ { "filename": "src/ready.ts", "retrieved_chunk": " /*\n TODO:\n Creates a ToDoBot channel category and a Taskboard text channel in it. Discuss. \n let server: Guild = await client.guilds.fetch(process.env.guildId);\n let category: CategoryChannel = await server.channels.create({\n name: \"ToDoBot\",\n type: ChannelType.GuildCategory\n });\n await server.channels.create({\n name: \"Taskboard\",", "score": 23.911982331719248 }, { "filename": "src/commands/todo.ts", "retrieved_chunk": " if (client.taskboardID != null) {\n let threadId = await CreateThreadForTask(task, client);\n SetThreadId(task.id, threadId);\n }\n let content = `Set task \"${taskDesc}\" (ID ${task.id}) for ${user}`;\n await interaction.followUp({\n ephemeral: false,\n content\n })\n }", "score": 17.609201195428437 }, { "filename": "src/commands/assign.ts", "retrieved_chunk": " content = `Task \"${task.description}\" assigned to ${user}`;\n }\n await interaction.followUp({\n ephemeral: false,\n content\n })\n }\n}", "score": 15.880796419026847 }, { "filename": "src/commands/edit.ts", "retrieved_chunk": " await interaction.followUp({\n ephemeral: false,\n content\n })\n }\n}", "score": 15.404672395264628 }, { "filename": "src/commands/remove.ts", "retrieved_chunk": " let newTaskList = TasksToString();\n let content = \"Task doesn't exist\";\n if (task != null) {\n content = `Task \"${task.description}\" removed, ${interaction.user}\\n\\n${newTaskList}`;\n if (client.taskboardID != null) {\n await CloseThreadForTask(task, client);\n }\n }\n await interaction.followUp({\n ephemeral: false,", "score": 14.17481692425801 } ]
typescript
export async function CreateThreadForTask(task: Task, client: ToDoClient): Promise<string> {
import { HttpException, HttpStatus, Inject, Injectable, NotFoundException, } from '@nestjs/common'; import { CACHE_MANAGER } from '@nestjs/cache-manager'; import { Cache } from 'cache-manager'; import { InjectModel } from '@nestjs/mongoose'; import { Model } from 'mongoose'; import { DeveloperDTO, PartialDeveloperDTO } from './dto'; import { Developer, DeveloperDocument } from './schemas/developer.schema'; import { IDeveloperService } from '../core/interfaces/IDeveloperService'; @Injectable() export class DeveloperService implements IDeveloperService { constructor( @InjectModel(Developer.name) private developerModel: Model<DeveloperDocument>, @Inject(CACHE_MANAGER) private readonly cacheManager: Cache, ) {} async create(dto: DeveloperDTO): Promise<DeveloperDocument> { try { const developer = await this.developerModel.create(dto); if (!developer) throw new NotFoundException(`failed to create developer!`); return developer; } catch (error) { throw new NotFoundException(`failed to create developer for duplicate email!`); } } async readBatch(): Promise<DeveloperDocument[]> { return await this.developerModel.find().exec(); } async read(id: string): Promise<DeveloperDocument> { try { const cacheKey = `developer:${id}`; const cached = await this.cacheManager.get(cacheKey); if (cached) { return JSON.parse(cached as unknown as string); } const developer = await this.developerModel.findById(id); if (!developer) throw new NotFoundException(`developer not found!`); await this.cacheManager.set(cacheKey, JSON.stringify(developer), 0); return developer; } catch (error) { throw new NotFoundException(`developer not found!`); } } async
filterByLevel(dto: PartialDeveloperDTO): Promise<DeveloperDocument[]> {
try { const cacheKey = `developers:${dto.level}`; const cached = await this.cacheManager.get(cacheKey); if (cached) return JSON.parse(cached as unknown as string); const developers = await this.developerModel.find({ level: dto.level }).exec(); if (developers) { await this.cacheManager.set(cacheKey, JSON.stringify(developers), 0); } return developers; } catch (error) { throw new NotFoundException(`failed to filter developer!`); } } async update(id: string, dto: PartialDeveloperDTO): Promise<DeveloperDocument> { const { _id } = await this.read(id); const developer = await this.developerModel.findByIdAndUpdate(_id, dto, { new: true, }); if (!developer) throw new NotFoundException(`failed to update developer!`); const cacheKey = `developer:${id}`; await this.cacheManager.set(cacheKey, JSON.stringify(developer), 0); return developer; } async delete(id: string): Promise<HttpException> { const developer = await this.developerModel.findByIdAndDelete(id); if (!developer) throw new NotFoundException(`failed to delete developer!`); const cacheKey = `developer:${id}`; const cached = await this.cacheManager.get(cacheKey); if (cached) await this.cacheManager.del(cacheKey); throw new HttpException('The data has been deleted successfully', HttpStatus.OK); } }
src/developer/developer.service.ts
DevSazal-backend-nest-sprint-5aad17a
[ { "filename": "src/developer/in-memory-developer.service.ts", "retrieved_chunk": " async read(id: string): Promise<object> {\n const cached = await this.cacheManager.get(this.key);\n if (cached) {\n const developers = JSON.parse(cached as unknown as string);\n const developer = developers.find(\n (developer: { _id: string }) => developer._id === id,\n );\n if (!developer) throw new NotFoundException(`developer not found!`);\n return developer;\n }", "score": 41.70700866140175 }, { "filename": "src/developer/in-memory-developer.service.ts", "retrieved_chunk": " throw new NotFoundException(`developer not found!`);\n }\n async filterByLevel(dto: PartialDeveloperDTO): Promise<object[]> {\n const cached = await this.cacheManager.get(this.key);\n const developers = JSON.parse(cached as unknown as string);\n return developers.filter(\n (developer: { level: string }) => developer.level === dto.level,\n );\n }\n async update(id: string, dto: PartialDeveloperDTO): Promise<object> {", "score": 40.67440784892406 }, { "filename": "src/developer/in-memory-developer.service.ts", "retrieved_chunk": " return updated;\n }\n async delete(id: string): Promise<HttpException> {\n const cached = await this.cacheManager.get(this.key);\n const developers = JSON.parse(cached as unknown as string);\n const index = developers.findIndex((developer) => developer._id === id);\n if (index === -1) throw new NotFoundException(`failed to delete developer!`);\n developers.splice(index, 1);\n await this.cacheManager.del(this.key);\n await this.cacheManager.set(this.key, JSON.stringify(developers), 0);", "score": 33.41977858703862 }, { "filename": "src/developer/in-memory-developer.service.ts", "retrieved_chunk": " const cached = await this.cacheManager.get(this.key);\n const developers = JSON.parse(cached as unknown as string);\n const index = developers.findIndex(\n (developer: { _id: { toString: () => string } }) => developer._id.toString() === id,\n );\n if (index < 0) throw new NotFoundException(`failed to update developer!`);\n const updated = Object.assign(developers[index], dto);\n developers[index] = updated;\n await this.cacheManager.del(this.key);\n await this.cacheManager.set(this.key, JSON.stringify(developers), 0);", "score": 31.631321074957594 }, { "filename": "src/developer/in-memory-developer.service.ts", "retrieved_chunk": " }\n const developers = [];\n developers.push(data);\n await this.cacheManager.set(this.key, JSON.stringify(developers), 0);\n return data;\n }\n async readBatch(): Promise<object[]> {\n const cached = await this.cacheManager.get(this.key);\n return JSON.parse(cached as unknown as string);\n }", "score": 19.731259149024858 } ]
typescript
filterByLevel(dto: PartialDeveloperDTO): Promise<DeveloperDocument[]> {
import { CACHE_MANAGER } from '@nestjs/cache-manager'; import { Cache } from 'cache-manager'; import { HttpException, HttpStatus, Inject, Injectable, NotFoundException, } from '@nestjs/common'; import { DeveloperDTO, PartialDeveloperDTO } from './dto'; import { randomUUID } from 'crypto'; import { IDeveloperService, IDeveloper } from 'src/core/interfaces/IDeveloperService'; @Injectable() export class InMemoryDeveloperService implements IDeveloperService { private key = 'developers'; constructor(@Inject(CACHE_MANAGER) private readonly cacheManager: Cache) {} async create(dto: DeveloperDTO): Promise<object> { const data: IDeveloper = { _id: this.uuid(), name: dto.name, email: dto.email, level: dto.level, }; const cached = await this.cacheManager.get(this.key); if (cached) { const jsonArray = JSON.parse(cached as unknown as string); jsonArray.push(data); await this.cacheManager.del(this.key); await this.cacheManager.set(this.key, JSON.stringify(jsonArray), 0); return data; } const developers = []; developers.push(data); await this.cacheManager.set(this.key, JSON.stringify(developers), 0); return data; } async readBatch(): Promise<object[]> { const cached = await this.cacheManager.get(this.key); return JSON.parse(cached as unknown as string); } async read(id: string): Promise<object> { const cached = await this.cacheManager.get(this.key); if (cached) { const developers = JSON.parse(cached as unknown as string); const developer = developers.find( (developer: { _id: string }) => developer._id === id, ); if (!developer) throw new NotFoundException(`developer not found!`); return developer; } throw new NotFoundException(`developer not found!`); } async filterByLevel
(dto: PartialDeveloperDTO): Promise<object[]> {
const cached = await this.cacheManager.get(this.key); const developers = JSON.parse(cached as unknown as string); return developers.filter( (developer: { level: string }) => developer.level === dto.level, ); } async update(id: string, dto: PartialDeveloperDTO): Promise<object> { const cached = await this.cacheManager.get(this.key); const developers = JSON.parse(cached as unknown as string); const index = developers.findIndex( (developer: { _id: { toString: () => string } }) => developer._id.toString() === id, ); if (index < 0) throw new NotFoundException(`failed to update developer!`); const updated = Object.assign(developers[index], dto); developers[index] = updated; await this.cacheManager.del(this.key); await this.cacheManager.set(this.key, JSON.stringify(developers), 0); return updated; } async delete(id: string): Promise<HttpException> { const cached = await this.cacheManager.get(this.key); const developers = JSON.parse(cached as unknown as string); const index = developers.findIndex((developer) => developer._id === id); if (index === -1) throw new NotFoundException(`failed to delete developer!`); developers.splice(index, 1); await this.cacheManager.del(this.key); await this.cacheManager.set(this.key, JSON.stringify(developers), 0); throw new HttpException('The data has been deleted successfully', HttpStatus.OK); } private uuid(): string { return randomUUID(); } }
src/developer/in-memory-developer.service.ts
DevSazal-backend-nest-sprint-5aad17a
[ { "filename": "src/developer/developer.service.ts", "retrieved_chunk": " const developer = await this.developerModel.findById(id);\n if (!developer) throw new NotFoundException(`developer not found!`);\n await this.cacheManager.set(cacheKey, JSON.stringify(developer), 0);\n return developer;\n } catch (error) {\n throw new NotFoundException(`developer not found!`);\n }\n }\n async filterByLevel(dto: PartialDeveloperDTO): Promise<DeveloperDocument[]> {\n try {", "score": 44.29653090680577 }, { "filename": "src/developer/developer.service.ts", "retrieved_chunk": " }\n }\n async update(id: string, dto: PartialDeveloperDTO): Promise<DeveloperDocument> {\n const { _id } = await this.read(id);\n const developer = await this.developerModel.findByIdAndUpdate(_id, dto, {\n new: true,\n });\n if (!developer) throw new NotFoundException(`failed to update developer!`);\n const cacheKey = `developer:${id}`;\n await this.cacheManager.set(cacheKey, JSON.stringify(developer), 0);", "score": 29.459244828222488 }, { "filename": "src/developer/developer.service.ts", "retrieved_chunk": " ) {}\n async create(dto: DeveloperDTO): Promise<DeveloperDocument> {\n try {\n const developer = await this.developerModel.create(dto);\n if (!developer) throw new NotFoundException(`failed to create developer!`);\n return developer;\n } catch (error) {\n throw new NotFoundException(`failed to create developer for duplicate email!`);\n }\n }", "score": 26.065540542010467 }, { "filename": "src/developer/developer.service.ts", "retrieved_chunk": " return developer;\n }\n async delete(id: string): Promise<HttpException> {\n const developer = await this.developerModel.findByIdAndDelete(id);\n if (!developer) throw new NotFoundException(`failed to delete developer!`);\n const cacheKey = `developer:${id}`;\n const cached = await this.cacheManager.get(cacheKey);\n if (cached) await this.cacheManager.del(cacheKey);\n throw new HttpException('The data has been deleted successfully', HttpStatus.OK);\n }", "score": 23.314499352335083 }, { "filename": "src/developer/developer.service.ts", "retrieved_chunk": " const cacheKey = `developers:${dto.level}`;\n const cached = await this.cacheManager.get(cacheKey);\n if (cached) return JSON.parse(cached as unknown as string);\n const developers = await this.developerModel.find({ level: dto.level }).exec();\n if (developers) {\n await this.cacheManager.set(cacheKey, JSON.stringify(developers), 0);\n }\n return developers;\n } catch (error) {\n throw new NotFoundException(`failed to filter developer!`);", "score": 19.574722977131376 } ]
typescript
(dto: PartialDeveloperDTO): Promise<object[]> {
import { HttpException, HttpStatus, Inject, Injectable, NotFoundException, } from '@nestjs/common'; import { CACHE_MANAGER } from '@nestjs/cache-manager'; import { Cache } from 'cache-manager'; import { InjectModel } from '@nestjs/mongoose'; import { Model } from 'mongoose'; import { DeveloperDTO, PartialDeveloperDTO } from './dto'; import { Developer, DeveloperDocument } from './schemas/developer.schema'; import { IDeveloperService } from '../core/interfaces/IDeveloperService'; @Injectable() export class DeveloperService implements IDeveloperService { constructor( @InjectModel(Developer.name) private developerModel: Model<DeveloperDocument>, @Inject(CACHE_MANAGER) private readonly cacheManager: Cache, ) {} async create(dto: DeveloperDTO): Promise<DeveloperDocument> { try { const developer = await this.developerModel.create(dto); if (!developer) throw new NotFoundException(`failed to create developer!`); return developer; } catch (error) { throw new NotFoundException(`failed to create developer for duplicate email!`); } } async readBatch(): Promise<DeveloperDocument[]> { return await this.developerModel.find().exec(); } async read(id: string): Promise<DeveloperDocument> { try { const cacheKey = `developer:${id}`; const cached = await this.cacheManager.get(cacheKey); if (cached) { return JSON.parse(cached as unknown as string); } const developer = await this.developerModel.findById(id); if (!developer) throw new NotFoundException(`developer not found!`); await this.cacheManager.set(cacheKey, JSON.stringify(developer), 0); return developer; } catch (error) { throw new NotFoundException(`developer not found!`); } } async filterByLevel(dto: PartialDeveloperDTO): Promise<DeveloperDocument[]> { try {
const cacheKey = `developers:${dto.level}`;
const cached = await this.cacheManager.get(cacheKey); if (cached) return JSON.parse(cached as unknown as string); const developers = await this.developerModel.find({ level: dto.level }).exec(); if (developers) { await this.cacheManager.set(cacheKey, JSON.stringify(developers), 0); } return developers; } catch (error) { throw new NotFoundException(`failed to filter developer!`); } } async update(id: string, dto: PartialDeveloperDTO): Promise<DeveloperDocument> { const { _id } = await this.read(id); const developer = await this.developerModel.findByIdAndUpdate(_id, dto, { new: true, }); if (!developer) throw new NotFoundException(`failed to update developer!`); const cacheKey = `developer:${id}`; await this.cacheManager.set(cacheKey, JSON.stringify(developer), 0); return developer; } async delete(id: string): Promise<HttpException> { const developer = await this.developerModel.findByIdAndDelete(id); if (!developer) throw new NotFoundException(`failed to delete developer!`); const cacheKey = `developer:${id}`; const cached = await this.cacheManager.get(cacheKey); if (cached) await this.cacheManager.del(cacheKey); throw new HttpException('The data has been deleted successfully', HttpStatus.OK); } }
src/developer/developer.service.ts
DevSazal-backend-nest-sprint-5aad17a
[ { "filename": "src/developer/in-memory-developer.service.ts", "retrieved_chunk": " throw new NotFoundException(`developer not found!`);\n }\n async filterByLevel(dto: PartialDeveloperDTO): Promise<object[]> {\n const cached = await this.cacheManager.get(this.key);\n const developers = JSON.parse(cached as unknown as string);\n return developers.filter(\n (developer: { level: string }) => developer.level === dto.level,\n );\n }\n async update(id: string, dto: PartialDeveloperDTO): Promise<object> {", "score": 40.62751056338547 }, { "filename": "src/developer/in-memory-developer.service.ts", "retrieved_chunk": " async read(id: string): Promise<object> {\n const cached = await this.cacheManager.get(this.key);\n if (cached) {\n const developers = JSON.parse(cached as unknown as string);\n const developer = developers.find(\n (developer: { _id: string }) => developer._id === id,\n );\n if (!developer) throw new NotFoundException(`developer not found!`);\n return developer;\n }", "score": 38.0595096802936 }, { "filename": "src/developer/in-memory-developer.service.ts", "retrieved_chunk": " return updated;\n }\n async delete(id: string): Promise<HttpException> {\n const cached = await this.cacheManager.get(this.key);\n const developers = JSON.parse(cached as unknown as string);\n const index = developers.findIndex((developer) => developer._id === id);\n if (index === -1) throw new NotFoundException(`failed to delete developer!`);\n developers.splice(index, 1);\n await this.cacheManager.del(this.key);\n await this.cacheManager.set(this.key, JSON.stringify(developers), 0);", "score": 29.779892482224206 }, { "filename": "src/developer/in-memory-developer.service.ts", "retrieved_chunk": " const cached = await this.cacheManager.get(this.key);\n const developers = JSON.parse(cached as unknown as string);\n const index = developers.findIndex(\n (developer: { _id: { toString: () => string } }) => developer._id.toString() === id,\n );\n if (index < 0) throw new NotFoundException(`failed to update developer!`);\n const updated = Object.assign(developers[index], dto);\n developers[index] = updated;\n await this.cacheManager.del(this.key);\n await this.cacheManager.set(this.key, JSON.stringify(developers), 0);", "score": 28.7517742231896 }, { "filename": "src/developer/in-memory-developer.service.ts", "retrieved_chunk": " }\n const developers = [];\n developers.push(data);\n await this.cacheManager.set(this.key, JSON.stringify(developers), 0);\n return data;\n }\n async readBatch(): Promise<object[]> {\n const cached = await this.cacheManager.get(this.key);\n return JSON.parse(cached as unknown as string);\n }", "score": 18.39889945069774 } ]
typescript
const cacheKey = `developers:${dto.level}`;
import { CACHE_MANAGER } from '@nestjs/cache-manager'; import { Cache } from 'cache-manager'; import { HttpException, HttpStatus, Inject, Injectable, NotFoundException, } from '@nestjs/common'; import { DeveloperDTO, PartialDeveloperDTO } from './dto'; import { randomUUID } from 'crypto'; import { IDeveloperService, IDeveloper } from 'src/core/interfaces/IDeveloperService'; @Injectable() export class InMemoryDeveloperService implements IDeveloperService { private key = 'developers'; constructor(@Inject(CACHE_MANAGER) private readonly cacheManager: Cache) {} async create(dto: DeveloperDTO): Promise<object> { const data: IDeveloper = { _id: this.uuid(), name: dto.name, email: dto.email, level: dto.level, }; const cached = await this.cacheManager.get(this.key); if (cached) { const jsonArray = JSON.parse(cached as unknown as string); jsonArray.push(data); await this.cacheManager.del(this.key); await this.cacheManager.set(this.key, JSON.stringify(jsonArray), 0); return data; } const developers = []; developers.push(data); await this.cacheManager.set(this.key, JSON.stringify(developers), 0); return data; } async readBatch(): Promise<object[]> { const cached = await this.cacheManager.get(this.key); return JSON.parse(cached as unknown as string); } async read(id: string): Promise<object> { const cached = await this.cacheManager.get(this.key); if (cached) { const developers = JSON.parse(cached as unknown as string); const developer = developers.find( (developer: { _id: string }) => developer._id === id, ); if (!developer) throw new NotFoundException(`developer not found!`); return developer; } throw new NotFoundException(`developer not found!`); } async
filterByLevel(dto: PartialDeveloperDTO): Promise<object[]> {
const cached = await this.cacheManager.get(this.key); const developers = JSON.parse(cached as unknown as string); return developers.filter( (developer: { level: string }) => developer.level === dto.level, ); } async update(id: string, dto: PartialDeveloperDTO): Promise<object> { const cached = await this.cacheManager.get(this.key); const developers = JSON.parse(cached as unknown as string); const index = developers.findIndex( (developer: { _id: { toString: () => string } }) => developer._id.toString() === id, ); if (index < 0) throw new NotFoundException(`failed to update developer!`); const updated = Object.assign(developers[index], dto); developers[index] = updated; await this.cacheManager.del(this.key); await this.cacheManager.set(this.key, JSON.stringify(developers), 0); return updated; } async delete(id: string): Promise<HttpException> { const cached = await this.cacheManager.get(this.key); const developers = JSON.parse(cached as unknown as string); const index = developers.findIndex((developer) => developer._id === id); if (index === -1) throw new NotFoundException(`failed to delete developer!`); developers.splice(index, 1); await this.cacheManager.del(this.key); await this.cacheManager.set(this.key, JSON.stringify(developers), 0); throw new HttpException('The data has been deleted successfully', HttpStatus.OK); } private uuid(): string { return randomUUID(); } }
src/developer/in-memory-developer.service.ts
DevSazal-backend-nest-sprint-5aad17a
[ { "filename": "src/developer/developer.service.ts", "retrieved_chunk": " const developer = await this.developerModel.findById(id);\n if (!developer) throw new NotFoundException(`developer not found!`);\n await this.cacheManager.set(cacheKey, JSON.stringify(developer), 0);\n return developer;\n } catch (error) {\n throw new NotFoundException(`developer not found!`);\n }\n }\n async filterByLevel(dto: PartialDeveloperDTO): Promise<DeveloperDocument[]> {\n try {", "score": 44.29653090680577 }, { "filename": "src/developer/developer.service.ts", "retrieved_chunk": " }\n }\n async update(id: string, dto: PartialDeveloperDTO): Promise<DeveloperDocument> {\n const { _id } = await this.read(id);\n const developer = await this.developerModel.findByIdAndUpdate(_id, dto, {\n new: true,\n });\n if (!developer) throw new NotFoundException(`failed to update developer!`);\n const cacheKey = `developer:${id}`;\n await this.cacheManager.set(cacheKey, JSON.stringify(developer), 0);", "score": 29.459244828222488 }, { "filename": "src/developer/developer.service.ts", "retrieved_chunk": " ) {}\n async create(dto: DeveloperDTO): Promise<DeveloperDocument> {\n try {\n const developer = await this.developerModel.create(dto);\n if (!developer) throw new NotFoundException(`failed to create developer!`);\n return developer;\n } catch (error) {\n throw new NotFoundException(`failed to create developer for duplicate email!`);\n }\n }", "score": 26.065540542010467 }, { "filename": "src/developer/developer.service.ts", "retrieved_chunk": " return developer;\n }\n async delete(id: string): Promise<HttpException> {\n const developer = await this.developerModel.findByIdAndDelete(id);\n if (!developer) throw new NotFoundException(`failed to delete developer!`);\n const cacheKey = `developer:${id}`;\n const cached = await this.cacheManager.get(cacheKey);\n if (cached) await this.cacheManager.del(cacheKey);\n throw new HttpException('The data has been deleted successfully', HttpStatus.OK);\n }", "score": 23.314499352335083 }, { "filename": "src/developer/developer.service.ts", "retrieved_chunk": " const cacheKey = `developers:${dto.level}`;\n const cached = await this.cacheManager.get(cacheKey);\n if (cached) return JSON.parse(cached as unknown as string);\n const developers = await this.developerModel.find({ level: dto.level }).exec();\n if (developers) {\n await this.cacheManager.set(cacheKey, JSON.stringify(developers), 0);\n }\n return developers;\n } catch (error) {\n throw new NotFoundException(`failed to filter developer!`);", "score": 19.574722977131376 } ]
typescript
filterByLevel(dto: PartialDeveloperDTO): Promise<object[]> {
import { CACHE_MANAGER } from '@nestjs/cache-manager'; import { Cache } from 'cache-manager'; import { HttpException, HttpStatus, Inject, Injectable, NotFoundException, } from '@nestjs/common'; import { DeveloperDTO, PartialDeveloperDTO } from './dto'; import { randomUUID } from 'crypto'; import { IDeveloperService, IDeveloper } from 'src/core/interfaces/IDeveloperService'; @Injectable() export class InMemoryDeveloperService implements IDeveloperService { private key = 'developers'; constructor(@Inject(CACHE_MANAGER) private readonly cacheManager: Cache) {} async create(dto: DeveloperDTO): Promise<object> { const data: IDeveloper = { _id: this.uuid(), name: dto.name, email: dto.email, level: dto.level, }; const cached = await this.cacheManager.get(this.key); if (cached) { const jsonArray = JSON.parse(cached as unknown as string); jsonArray.push(data); await this.cacheManager.del(this.key); await this.cacheManager.set(this.key, JSON.stringify(jsonArray), 0); return data; } const developers = []; developers.push(data); await this.cacheManager.set(this.key, JSON.stringify(developers), 0); return data; } async readBatch(): Promise<object[]> { const cached = await this.cacheManager.get(this.key); return JSON.parse(cached as unknown as string); } async read(id: string): Promise<object> { const cached = await this.cacheManager.get(this.key); if (cached) { const developers = JSON.parse(cached as unknown as string); const developer = developers.find( (developer: { _id: string }) => developer._id === id, ); if (!developer) throw new NotFoundException(`developer not found!`); return developer; } throw new NotFoundException(`developer not found!`); }
async filterByLevel(dto: PartialDeveloperDTO): Promise<object[]> {
const cached = await this.cacheManager.get(this.key); const developers = JSON.parse(cached as unknown as string); return developers.filter( (developer: { level: string }) => developer.level === dto.level, ); } async update(id: string, dto: PartialDeveloperDTO): Promise<object> { const cached = await this.cacheManager.get(this.key); const developers = JSON.parse(cached as unknown as string); const index = developers.findIndex( (developer: { _id: { toString: () => string } }) => developer._id.toString() === id, ); if (index < 0) throw new NotFoundException(`failed to update developer!`); const updated = Object.assign(developers[index], dto); developers[index] = updated; await this.cacheManager.del(this.key); await this.cacheManager.set(this.key, JSON.stringify(developers), 0); return updated; } async delete(id: string): Promise<HttpException> { const cached = await this.cacheManager.get(this.key); const developers = JSON.parse(cached as unknown as string); const index = developers.findIndex((developer) => developer._id === id); if (index === -1) throw new NotFoundException(`failed to delete developer!`); developers.splice(index, 1); await this.cacheManager.del(this.key); await this.cacheManager.set(this.key, JSON.stringify(developers), 0); throw new HttpException('The data has been deleted successfully', HttpStatus.OK); } private uuid(): string { return randomUUID(); } }
src/developer/in-memory-developer.service.ts
DevSazal-backend-nest-sprint-5aad17a
[ { "filename": "src/developer/developer.service.ts", "retrieved_chunk": " const developer = await this.developerModel.findById(id);\n if (!developer) throw new NotFoundException(`developer not found!`);\n await this.cacheManager.set(cacheKey, JSON.stringify(developer), 0);\n return developer;\n } catch (error) {\n throw new NotFoundException(`developer not found!`);\n }\n }\n async filterByLevel(dto: PartialDeveloperDTO): Promise<DeveloperDocument[]> {\n try {", "score": 46.66228497300618 }, { "filename": "src/developer/developer.service.ts", "retrieved_chunk": " const cacheKey = `developers:${dto.level}`;\n const cached = await this.cacheManager.get(cacheKey);\n if (cached) return JSON.parse(cached as unknown as string);\n const developers = await this.developerModel.find({ level: dto.level }).exec();\n if (developers) {\n await this.cacheManager.set(cacheKey, JSON.stringify(developers), 0);\n }\n return developers;\n } catch (error) {\n throw new NotFoundException(`failed to filter developer!`);", "score": 38.13995265040299 }, { "filename": "src/developer/developer.service.ts", "retrieved_chunk": " }\n }\n async update(id: string, dto: PartialDeveloperDTO): Promise<DeveloperDocument> {\n const { _id } = await this.read(id);\n const developer = await this.developerModel.findByIdAndUpdate(_id, dto, {\n new: true,\n });\n if (!developer) throw new NotFoundException(`failed to update developer!`);\n const cacheKey = `developer:${id}`;\n await this.cacheManager.set(cacheKey, JSON.stringify(developer), 0);", "score": 32.451185651880586 }, { "filename": "src/developer/developer.service.ts", "retrieved_chunk": " async readBatch(): Promise<DeveloperDocument[]> {\n return await this.developerModel.find().exec();\n }\n async read(id: string): Promise<DeveloperDocument> {\n try {\n const cacheKey = `developer:${id}`;\n const cached = await this.cacheManager.get(cacheKey);\n if (cached) {\n return JSON.parse(cached as unknown as string);\n }", "score": 30.386050784964528 }, { "filename": "src/developer/developer.service.ts", "retrieved_chunk": " return developer;\n }\n async delete(id: string): Promise<HttpException> {\n const developer = await this.developerModel.findByIdAndDelete(id);\n if (!developer) throw new NotFoundException(`failed to delete developer!`);\n const cacheKey = `developer:${id}`;\n const cached = await this.cacheManager.get(cacheKey);\n if (cached) await this.cacheManager.del(cacheKey);\n throw new HttpException('The data has been deleted successfully', HttpStatus.OK);\n }", "score": 27.18996765186884 } ]
typescript
async filterByLevel(dto: PartialDeveloperDTO): Promise<object[]> {
import { HttpException, HttpStatus, Inject, Injectable, NotFoundException, } from '@nestjs/common'; import { CACHE_MANAGER } from '@nestjs/cache-manager'; import { Cache } from 'cache-manager'; import { InjectModel } from '@nestjs/mongoose'; import { Model } from 'mongoose'; import { DeveloperDTO, PartialDeveloperDTO } from './dto'; import { Developer, DeveloperDocument } from './schemas/developer.schema'; import { IDeveloperService } from '../core/interfaces/IDeveloperService'; @Injectable() export class DeveloperService implements IDeveloperService { constructor( @InjectModel(Developer.name) private developerModel: Model<DeveloperDocument>, @Inject(CACHE_MANAGER) private readonly cacheManager: Cache, ) {} async create(dto: DeveloperDTO): Promise<DeveloperDocument> { try { const developer = await this.developerModel.create(dto); if (!developer) throw new NotFoundException(`failed to create developer!`); return developer; } catch (error) { throw new NotFoundException(`failed to create developer for duplicate email!`); } } async readBatch(): Promise<DeveloperDocument[]> { return await this.developerModel.find().exec(); } async read(id: string): Promise<DeveloperDocument> { try { const cacheKey = `developer:${id}`; const cached = await this.cacheManager.get(cacheKey); if (cached) { return JSON.parse(cached as unknown as string); } const developer = await this.developerModel.findById(id); if (!developer) throw new NotFoundException(`developer not found!`); await this.cacheManager.set(cacheKey, JSON.stringify(developer), 0); return developer; } catch (error) { throw new NotFoundException(`developer not found!`); } }
async filterByLevel(dto: PartialDeveloperDTO): Promise<DeveloperDocument[]> {
try { const cacheKey = `developers:${dto.level}`; const cached = await this.cacheManager.get(cacheKey); if (cached) return JSON.parse(cached as unknown as string); const developers = await this.developerModel.find({ level: dto.level }).exec(); if (developers) { await this.cacheManager.set(cacheKey, JSON.stringify(developers), 0); } return developers; } catch (error) { throw new NotFoundException(`failed to filter developer!`); } } async update(id: string, dto: PartialDeveloperDTO): Promise<DeveloperDocument> { const { _id } = await this.read(id); const developer = await this.developerModel.findByIdAndUpdate(_id, dto, { new: true, }); if (!developer) throw new NotFoundException(`failed to update developer!`); const cacheKey = `developer:${id}`; await this.cacheManager.set(cacheKey, JSON.stringify(developer), 0); return developer; } async delete(id: string): Promise<HttpException> { const developer = await this.developerModel.findByIdAndDelete(id); if (!developer) throw new NotFoundException(`failed to delete developer!`); const cacheKey = `developer:${id}`; const cached = await this.cacheManager.get(cacheKey); if (cached) await this.cacheManager.del(cacheKey); throw new HttpException('The data has been deleted successfully', HttpStatus.OK); } }
src/developer/developer.service.ts
DevSazal-backend-nest-sprint-5aad17a
[ { "filename": "src/developer/in-memory-developer.service.ts", "retrieved_chunk": " async read(id: string): Promise<object> {\n const cached = await this.cacheManager.get(this.key);\n if (cached) {\n const developers = JSON.parse(cached as unknown as string);\n const developer = developers.find(\n (developer: { _id: string }) => developer._id === id,\n );\n if (!developer) throw new NotFoundException(`developer not found!`);\n return developer;\n }", "score": 41.70700866140175 }, { "filename": "src/developer/in-memory-developer.service.ts", "retrieved_chunk": " throw new NotFoundException(`developer not found!`);\n }\n async filterByLevel(dto: PartialDeveloperDTO): Promise<object[]> {\n const cached = await this.cacheManager.get(this.key);\n const developers = JSON.parse(cached as unknown as string);\n return developers.filter(\n (developer: { level: string }) => developer.level === dto.level,\n );\n }\n async update(id: string, dto: PartialDeveloperDTO): Promise<object> {", "score": 40.67440784892406 }, { "filename": "src/developer/in-memory-developer.service.ts", "retrieved_chunk": " return updated;\n }\n async delete(id: string): Promise<HttpException> {\n const cached = await this.cacheManager.get(this.key);\n const developers = JSON.parse(cached as unknown as string);\n const index = developers.findIndex((developer) => developer._id === id);\n if (index === -1) throw new NotFoundException(`failed to delete developer!`);\n developers.splice(index, 1);\n await this.cacheManager.del(this.key);\n await this.cacheManager.set(this.key, JSON.stringify(developers), 0);", "score": 33.41977858703862 }, { "filename": "src/developer/in-memory-developer.service.ts", "retrieved_chunk": " const cached = await this.cacheManager.get(this.key);\n const developers = JSON.parse(cached as unknown as string);\n const index = developers.findIndex(\n (developer: { _id: { toString: () => string } }) => developer._id.toString() === id,\n );\n if (index < 0) throw new NotFoundException(`failed to update developer!`);\n const updated = Object.assign(developers[index], dto);\n developers[index] = updated;\n await this.cacheManager.del(this.key);\n await this.cacheManager.set(this.key, JSON.stringify(developers), 0);", "score": 31.631321074957594 }, { "filename": "src/developer/in-memory-developer.service.ts", "retrieved_chunk": " }\n const developers = [];\n developers.push(data);\n await this.cacheManager.set(this.key, JSON.stringify(developers), 0);\n return data;\n }\n async readBatch(): Promise<object[]> {\n const cached = await this.cacheManager.get(this.key);\n return JSON.parse(cached as unknown as string);\n }", "score": 19.731259149024858 } ]
typescript
async filterByLevel(dto: PartialDeveloperDTO): Promise<DeveloperDocument[]> {
import { chunkAtEnd, isNumber, zeroPad } from "./utils"; import { numberUnits, tenUnits, thousandUnits } from "./constant"; export function formatNumber(format: number | string | null = "") { if (!isNumber(Number(format))) { return ""; } return chunkAtEnd(String(format), 4) .reduce((acc, item, index) => { const unit = thousandUnits[index] ?? ""; if (!Number(item)) { return acc; } return `${Number(item)}${unit} ${acc}`; }, "") .trim(); } export function formatNumberAll(format: number | string | null = "") { if (!isNumber(Number(format))) { return ""; } return chunkAtEnd(String(format), 4) .reduce((acc, item, index) => { if (!Number(item)) { return acc; } let numberUnit = ""; const zeroItem = zeroPad(item, 4); for (let i = 0; i < 4; i++) { const number = Number(zeroItem[i]); if (number) { const unit = tenUnits[3 - i]; numberUnit += `${ unit &&
number === 1 ? "" : numberUnits[number] }${unit}`;
} } const thousandUnit = thousandUnits[index] ?? ""; return `${numberUnit}${numberUnit ? thousandUnit : ""} ${acc}`; }, "") .trim(); }
src/formatNumber.ts
hyukson-hangul-util-505feaa
[ { "filename": "src/distance.ts", "retrieved_chunk": " if (!second) return first.length;\n if (memo[first + '||' + second]) {\n return memo[first + '||' + second];\n }\n const getDistance: number[][] = [[]];\n // 초기값 설정\n for (let j = 0; j <= second.length; j++) {\n getDistance[0][j] = j;\n }\n for (let i = 1; i <= first.length; i++) {", "score": 33.63341827201895 }, { "filename": "src/utils.ts", "retrieved_chunk": " const padString = String(pad);\n for (let i = pow - result.length; i > 0; i--) {\n result = padString + result;\n }\n return result;\n}\nexport function chunkAtEnd(value: string = \"\", n: number = 1) {\n const result: string[] = [];\n let start = value.length;\n while ((start -= n) > 0) {", "score": 33.26076153587885 }, { "filename": "src/sortHangul.ts", "retrieved_chunk": " compare?: string[] | string,\n orderASC: boolean = true\n) {\n if (Array.isArray(compare)) {\n const keys = compare.map((x) => splitByKey(x));\n return array.sort((a, b) => {\n for (let i = 0; i < compare.length; i++) {\n const result = baseCompare(\n getNestedProperty(keys[i], a),\n getNestedProperty(keys[i], b),", "score": 29.573190821019086 }, { "filename": "src/distance.ts", "retrieved_chunk": " getDistance[i] = [i];\n for (let j = 1; j <= second.length; j++) {\n getDistance[i][j] = minBy(\n getDistance[i - 1][j] + 1,\n getDistance[i][j - 1] + 1,\n getDistance[i - 1][j - 1] + (first[i - 1] === second[j - 1] ? 0 : 1)\n );\n }\n }\n memo[first + '||' + second] = getDistance[first.length][second.length];", "score": 28.84967799545179 }, { "filename": "src/encode.ts", "retrieved_chunk": "import { chunkAtEnd } from \"./utils\";\nconst a = [\n escape,\n (t: string) => chunkAtEnd(chunkAtEnd(t).join(\"\"), 3).join(\"\"),\n (t: string) => chunkAtEnd(chunkAtEnd(t).join(\"\"), 4).join(\"\"),\n (t: string) => chunkAtEnd(t).join(\"\"),\n (t: string) =>\n t\n .split(\"\")\n .map((v, i) => (i % 3 === 0 ? v + w() : v))", "score": 25.770327992237416 } ]
typescript
number === 1 ? "" : numberUnits[number] }${unit}`;
import { CodeMirrorRangeRectCalculator, RangeRectCalculator, TextareaRangeRectCalculator, } from "../utilities/dom/range-rect-calculator"; import {formatList} from "../utilities/format"; import {lintMarkdown} from "../utilities/lint-markdown"; import {LintErrorTooltip} from "./lint-error-tooltip"; import {LintErrorAnnotation} from "./lint-error-annotation"; import {Vector} from "../utilities/geometry/vector"; import {NumberRange} from "../utilities/geometry/number-range"; import {Component} from "./component"; export abstract class LintedMarkdownEditor extends Component { #editor: HTMLElement; #tooltip: LintErrorTooltip; #resizeObserver: ResizeObserver; #rangeRectCalculator: RangeRectCalculator; #annotationsPortal = document.createElement("div"); #statusContainer = LintedMarkdownEditor.#createStatusContainerElement(); constructor( element: HTMLElement, portal: HTMLElement, rangeRectCalculator: RangeRectCalculator ) { super(); this.#editor = element; this.#rangeRectCalculator = rangeRectCalculator; portal.append(this.#annotationsPortal, this.#statusContainer); this.addEventListener(element, "focus", this.onUpdate); this.addEventListener(element, "blur", this.#onBlur); this.addEventListener(element, "mousemove", this.#onMouseMove); this.addEventListener(element, "mouseleave", this.#onMouseLeave); // capture ancestor scroll events for nested scroll containers this.addEventListener(document, "scroll", this.#onReposition, true); // selectionchange can't be bound to the textarea so we have to use the document this.addEventListener(document, "selectionchange", this.#onSelectionChange); // annotations are document-relative so we need to observe document resize as well this.addEventListener(window, "resize", this.#onReposition); // this does mean it will run twice when the resize causes a resize of the textarea, // but we also need the resize observer for the textarea because it's user resizable this.#resizeObserver = new ResizeObserver(this.#onReposition); this.#resizeObserver.observe(element); this.#tooltip = new LintErrorTooltip(portal); } disconnect() { super.disconnect(); this.#resizeObserver.disconnect(); this.#rangeRectCalculator.disconnect(); this.#tooltip.disconnect(); this.#annotationsPortal.remove(); this.#statusContainer.remove(); } /** * Return a list of rects for the given range. If the range extends over multiple lines, * multiple rects will be returned. */ getRangeRects(characterIndexes: NumberRange) { return this.#rangeRectCalculator.getClientRects(characterIndexes); } getBoundingClientRect() { return this.#editor.getBoundingClientRect(); } getLineHeight() { const parsed = parseInt(getComputedStyle(this.#editor).lineHeight, 10); return Number.isNaN(parsed) ? undefined : parsed; } abstract get value(): string; abstract get caretPosition(): number; #_annotations: readonly LintErrorAnnotation[] = []; set #annotations(annotations: ReadonlyArray<LintErrorAnnotation>) { if (annotations === this.#_annotations) return; this.#_annotations = annotations; this.#statusContainer.textContent = annotations.length > 0 ? `${annotations.length} Markdown problem${ annotations.length > 1 ? "s" : "" } identified: see line${ annotations.length > 1 ? "s" : "" }
${formatList( annotations.map((a) => a.lineNumber.toString()), "and" )}` : "";
} get #annotations() { return this.#_annotations; } #_tooltipAnnotations: readonly LintErrorAnnotation[] = []; set #tooltipAnnotations(annotations: LintErrorAnnotation[]) { if (annotations === this.#_tooltipAnnotations) return; this.#_tooltipAnnotations = annotations; const position = annotations[0]?.getTooltipPosition(); const errors = annotations.map(({error}) => error); if (position) this.#tooltip.show(errors, position); else this.#tooltip.hide(); } protected onUpdate = () => this.#lint(); #isOnRepositionTick = false; #onReposition = () => { if (this.#isOnRepositionTick) return; this.#isOnRepositionTick = true; requestAnimationFrame(() => { this.#recalculateAnnotationPositions(); this.#isOnRepositionTick = false; }); }; #onBlur = () => this.#clear(); #onMouseMove = (event: MouseEvent) => this.#updatePointerTooltip(new Vector(event.clientX, event.clientY)); #onMouseLeave = () => (this.#tooltipAnnotations = []); #onSelectionChange = () => { // this event only works when applied to the document but we can filter it by detecting focus if (document.activeElement === this.#editor) this.#updateCaretTooltip(); }; #clear() { // the annotations will clean themselves up too but this is slightly faster this.#annotationsPortal.replaceChildren(); for (const annotation of this.#annotations) annotation.disconnect(); this.#annotations = []; this.#tooltipAnnotations = []; } #lint() { this.#clear(); // clear() will not hide the tooltip if the mouse is over it, but if the user is typing then they are not trying to copy content this.#tooltip.hide(true); if (document.activeElement !== this.#editor) return; const errors = lintMarkdown(this.value); this.#annotations = errors.map( (error) => new LintErrorAnnotation(error, this, this.#annotationsPortal) ); } #recalculateAnnotationPositions() { for (const annotation of this.#annotations) annotation.recalculatePosition(); } #updatePointerTooltip(pointerLocation: Vector) { // can't use mouse events on annotations (the easy way) because they have pointer-events: none this.#tooltipAnnotations = this.#annotations.filter((a) => a.containsPoint(pointerLocation) ); } #updateCaretTooltip() { this.#tooltipAnnotations = this.#annotations.filter((a) => a.containsIndex(this.caretPosition) ); } static #createStatusContainerElement() { const container = document.createElement("p"); container.setAttribute("aria-live", "polite"); container.style.position = "absolute"; container.style.clipPath = "circle(0)"; return container; } } export class LintedMarkdownTextareaEditor extends LintedMarkdownEditor { readonly #textarea: HTMLTextAreaElement; constructor(textarea: HTMLTextAreaElement, portal: HTMLElement) { super(textarea, portal, new TextareaRangeRectCalculator(textarea)); this.#textarea = textarea; this.addEventListener(textarea, "input", this.onUpdate); } get value() { return this.#textarea.value; } get caretPosition() { return this.#textarea.selectionEnd !== this.#textarea.selectionStart ? -1 : this.#textarea.selectionStart; } } export class LintedMarkdownCodeMirrorEditor extends LintedMarkdownEditor { readonly #element: HTMLElement; readonly #mutationObserver: MutationObserver; constructor(element: HTMLElement, portal: HTMLElement) { super(element, portal, new CodeMirrorRangeRectCalculator(element)); this.#element = element; this.#mutationObserver = new MutationObserver(this.onUpdate); this.#mutationObserver.observe(element, { childList: true, subtree: true, }); } override disconnect(): void { super.disconnect(); this.#mutationObserver.disconnect(); } get value() { return Array.from(this.#element.querySelectorAll(".CodeMirror-line")) .map((line) => line.textContent) .join("\n"); } get caretPosition() { const selection = document.getSelection(); const range = selection?.getRangeAt(0); if (!range?.collapsed || selection?.rangeCount !== 1) return -1; const referenceRange = document.createRange(); referenceRange.selectNodeContents(this.#element); referenceRange.setEnd(range.startContainer, range.startOffset); return referenceRange.toString().length; } }
src/components/linted-markdown-editor.ts
iansan5653-github-markdown-a11y-extension-c6a54d0
[ { "filename": "src/components/lint-error-annotation.ts", "retrieved_chunk": " this.lineNumber = error.lineNumber;\n portal.appendChild(this.#container);\n const markdown = editor.value;\n const [line = \"\", ...prevLines] = markdown\n .split(\"\\n\")\n .slice(0, this.lineNumber)\n .reverse();\n const startCol = (error.errorRange?.[0] ?? 1) - 1;\n const length = error.errorRange?.[1] ?? line.length - startCol;\n const startIndex = prevLines.reduce(", "score": 25.968466797181065 }, { "filename": "src/components/lint-error-annotation.ts", "retrieved_chunk": " (t, l) => t + l.length + 1 /* +1 for newline char */,\n startCol\n );\n const endIndex = startIndex + length;\n this.#indexRange = new NumberRange(startIndex, endIndex);\n this.recalculatePosition();\n }\n disconnect() {\n super.disconnect();\n this.#container.remove();", "score": 18.300486853750694 }, { "filename": "src/utilities/dom/range-rect-calculator.ts", "retrieved_chunk": " offset: number\n ): [node: Node, offsetIntoNode: number] | undefined {\n let prevChars = 0;\n for (const line of lines) {\n for (const node of line) {\n const length = node.textContent?.length ?? 0;\n if (offset <= prevChars + length) return [node, offset - prevChars];\n prevChars += length;\n }\n prevChars++; // For the newline", "score": 15.903264830237873 }, { "filename": "src/components/lint-error-tooltip.ts", "retrieved_chunk": " element.style.flexDirection = \"column\";\n element.style.gap = \"8px\";\n return element;\n }\n static #createPrefixElement(errorCount: number) {\n const element = document.createElement(\"span\");\n element.textContent =\n errorCount === 1\n ? \"Markdown problem: \"\n : `${errorCount} Markdown problems: `;", "score": 14.024699484004458 }, { "filename": "src/utilities/format.ts", "retrieved_chunk": "export function formatList(items: string[], conjunction: string) {\n if (items.length > 2) {\n items.push(`${conjunction} ${items.pop()}`);\n return items.join(\", \");\n } else if (items.length === 2) {\n const last = items.pop();\n const secondLast = items.pop();\n return [secondLast, conjunction, last].join(\" \");\n } else {\n return items[0];", "score": 13.570030748926511 } ]
typescript
${formatList( annotations.map((a) => a.lineNumber.toString()), "and" )}` : "";
import { CodeMirrorRangeRectCalculator, RangeRectCalculator, TextareaRangeRectCalculator, } from "../utilities/dom/range-rect-calculator"; import {formatList} from "../utilities/format"; import {lintMarkdown} from "../utilities/lint-markdown"; import {LintErrorTooltip} from "./lint-error-tooltip"; import {LintErrorAnnotation} from "./lint-error-annotation"; import {Vector} from "../utilities/geometry/vector"; import {NumberRange} from "../utilities/geometry/number-range"; import {Component} from "./component"; export abstract class LintedMarkdownEditor extends Component { #editor: HTMLElement; #tooltip: LintErrorTooltip; #resizeObserver: ResizeObserver; #rangeRectCalculator: RangeRectCalculator; #annotationsPortal = document.createElement("div"); #statusContainer = LintedMarkdownEditor.#createStatusContainerElement(); constructor( element: HTMLElement, portal: HTMLElement, rangeRectCalculator: RangeRectCalculator ) { super(); this.#editor = element; this.#rangeRectCalculator = rangeRectCalculator; portal.append(this.#annotationsPortal, this.#statusContainer); this.addEventListener(element, "focus", this.onUpdate); this.addEventListener(element, "blur", this.#onBlur); this.addEventListener(element, "mousemove", this.#onMouseMove); this.addEventListener(element, "mouseleave", this.#onMouseLeave); // capture ancestor scroll events for nested scroll containers this.addEventListener(document, "scroll", this.#onReposition, true); // selectionchange can't be bound to the textarea so we have to use the document this.addEventListener(document, "selectionchange", this.#onSelectionChange); // annotations are document-relative so we need to observe document resize as well this.addEventListener(window, "resize", this.#onReposition); // this does mean it will run twice when the resize causes a resize of the textarea, // but we also need the resize observer for the textarea because it's user resizable this.#resizeObserver = new ResizeObserver(this.#onReposition); this.#resizeObserver.observe(element); this.#tooltip = new LintErrorTooltip(portal); } disconnect() { super.disconnect(); this.#resizeObserver.disconnect(); this.#rangeRectCalculator.disconnect(); this.#tooltip.disconnect(); this.#annotationsPortal.remove(); this.#statusContainer.remove(); } /** * Return a list of rects for the given range. If the range extends over multiple lines, * multiple rects will be returned. */ getRangeRects(characterIndexes: NumberRange) { return this.#rangeRectCalculator.getClientRects(characterIndexes); } getBoundingClientRect() { return this.#editor.getBoundingClientRect(); } getLineHeight() { const parsed = parseInt(getComputedStyle(this.#editor).lineHeight, 10); return Number.isNaN(parsed) ? undefined : parsed; } abstract get value(): string; abstract get caretPosition(): number;
#_annotations: readonly LintErrorAnnotation[] = [];
set #annotations(annotations: ReadonlyArray<LintErrorAnnotation>) { if (annotations === this.#_annotations) return; this.#_annotations = annotations; this.#statusContainer.textContent = annotations.length > 0 ? `${annotations.length} Markdown problem${ annotations.length > 1 ? "s" : "" } identified: see line${ annotations.length > 1 ? "s" : "" } ${formatList( annotations.map((a) => a.lineNumber.toString()), "and" )}` : ""; } get #annotations() { return this.#_annotations; } #_tooltipAnnotations: readonly LintErrorAnnotation[] = []; set #tooltipAnnotations(annotations: LintErrorAnnotation[]) { if (annotations === this.#_tooltipAnnotations) return; this.#_tooltipAnnotations = annotations; const position = annotations[0]?.getTooltipPosition(); const errors = annotations.map(({error}) => error); if (position) this.#tooltip.show(errors, position); else this.#tooltip.hide(); } protected onUpdate = () => this.#lint(); #isOnRepositionTick = false; #onReposition = () => { if (this.#isOnRepositionTick) return; this.#isOnRepositionTick = true; requestAnimationFrame(() => { this.#recalculateAnnotationPositions(); this.#isOnRepositionTick = false; }); }; #onBlur = () => this.#clear(); #onMouseMove = (event: MouseEvent) => this.#updatePointerTooltip(new Vector(event.clientX, event.clientY)); #onMouseLeave = () => (this.#tooltipAnnotations = []); #onSelectionChange = () => { // this event only works when applied to the document but we can filter it by detecting focus if (document.activeElement === this.#editor) this.#updateCaretTooltip(); }; #clear() { // the annotations will clean themselves up too but this is slightly faster this.#annotationsPortal.replaceChildren(); for (const annotation of this.#annotations) annotation.disconnect(); this.#annotations = []; this.#tooltipAnnotations = []; } #lint() { this.#clear(); // clear() will not hide the tooltip if the mouse is over it, but if the user is typing then they are not trying to copy content this.#tooltip.hide(true); if (document.activeElement !== this.#editor) return; const errors = lintMarkdown(this.value); this.#annotations = errors.map( (error) => new LintErrorAnnotation(error, this, this.#annotationsPortal) ); } #recalculateAnnotationPositions() { for (const annotation of this.#annotations) annotation.recalculatePosition(); } #updatePointerTooltip(pointerLocation: Vector) { // can't use mouse events on annotations (the easy way) because they have pointer-events: none this.#tooltipAnnotations = this.#annotations.filter((a) => a.containsPoint(pointerLocation) ); } #updateCaretTooltip() { this.#tooltipAnnotations = this.#annotations.filter((a) => a.containsIndex(this.caretPosition) ); } static #createStatusContainerElement() { const container = document.createElement("p"); container.setAttribute("aria-live", "polite"); container.style.position = "absolute"; container.style.clipPath = "circle(0)"; return container; } } export class LintedMarkdownTextareaEditor extends LintedMarkdownEditor { readonly #textarea: HTMLTextAreaElement; constructor(textarea: HTMLTextAreaElement, portal: HTMLElement) { super(textarea, portal, new TextareaRangeRectCalculator(textarea)); this.#textarea = textarea; this.addEventListener(textarea, "input", this.onUpdate); } get value() { return this.#textarea.value; } get caretPosition() { return this.#textarea.selectionEnd !== this.#textarea.selectionStart ? -1 : this.#textarea.selectionStart; } } export class LintedMarkdownCodeMirrorEditor extends LintedMarkdownEditor { readonly #element: HTMLElement; readonly #mutationObserver: MutationObserver; constructor(element: HTMLElement, portal: HTMLElement) { super(element, portal, new CodeMirrorRangeRectCalculator(element)); this.#element = element; this.#mutationObserver = new MutationObserver(this.onUpdate); this.#mutationObserver.observe(element, { childList: true, subtree: true, }); } override disconnect(): void { super.disconnect(); this.#mutationObserver.disconnect(); } get value() { return Array.from(this.#element.querySelectorAll(".CodeMirror-line")) .map((line) => line.textContent) .join("\n"); } get caretPosition() { const selection = document.getSelection(); const range = selection?.getRangeAt(0); if (!range?.collapsed || selection?.rangeCount !== 1) return -1; const referenceRange = document.createRange(); referenceRange.selectNodeContents(this.#element); referenceRange.setEnd(range.startContainer, range.startOffset); return referenceRange.toString().length; } }
src/components/linted-markdown-editor.ts
iansan5653-github-markdown-a11y-extension-c6a54d0
[ { "filename": "src/utilities/geometry/rect.ts", "retrieved_chunk": " get left() {\n return this.x;\n }\n get right() {\n return this.left + this.width;\n }\n get top() {\n return this.y;\n }\n get bottom() {", "score": 18.285550250929138 }, { "filename": "src/components/lint-error-annotation.ts", "retrieved_chunk": " return this.#elements.some((el) =>\n // scale slightly so we don't show two tooltips at touching horizontal edges\n new Rect(el.getBoundingClientRect()).scaleY(0.99).contains(point)\n );\n }\n containsIndex(index: number) {\n return this.#indexRange.contains(index, \"inclusive\");\n }\n recalculatePosition() {\n const editorRect = new Rect(this.#editor.getBoundingClientRect());", "score": 16.99871642064045 }, { "filename": "src/utilities/geometry/rect.ts", "retrieved_chunk": " return this.top + this.height;\n }\n get xRange() {\n return new NumberRange(this.left, this.right);\n }\n get yRange() {\n return new NumberRange(this.top, this.bottom);\n }\n asVector(\n corner:", "score": 15.467988642718844 }, { "filename": "src/components/lint-error-annotation.ts", "retrieved_chunk": " readonly #editor: LintedMarkdownEditor;\n #elements: readonly HTMLElement[] = [];\n readonly #indexRange: NumberRange;\n constructor(\n readonly error: LintError,\n editor: LintedMarkdownEditor,\n portal: HTMLElement\n ) {\n super();\n this.#editor = editor;", "score": 14.449895062431914 }, { "filename": "src/utilities/geometry/number-range.ts", "retrieved_chunk": "export class NumberRange {\n readonly start: number;\n readonly end: number;\n constructor(start: number, end: number) {\n this.start = Math.min(start, end);\n this.end = Math.max(start, end);\n }\n contains(\n value: number,\n mode:", "score": 12.347780198108676 } ]
typescript
#_annotations: readonly LintErrorAnnotation[] = [];
import { CodeMirrorRangeRectCalculator, RangeRectCalculator, TextareaRangeRectCalculator, } from "../utilities/dom/range-rect-calculator"; import {formatList} from "../utilities/format"; import {lintMarkdown} from "../utilities/lint-markdown"; import {LintErrorTooltip} from "./lint-error-tooltip"; import {LintErrorAnnotation} from "./lint-error-annotation"; import {Vector} from "../utilities/geometry/vector"; import {NumberRange} from "../utilities/geometry/number-range"; import {Component} from "./component"; export abstract class LintedMarkdownEditor extends Component { #editor: HTMLElement; #tooltip: LintErrorTooltip; #resizeObserver: ResizeObserver; #rangeRectCalculator: RangeRectCalculator; #annotationsPortal = document.createElement("div"); #statusContainer = LintedMarkdownEditor.#createStatusContainerElement(); constructor( element: HTMLElement, portal: HTMLElement, rangeRectCalculator: RangeRectCalculator ) { super(); this.#editor = element; this.#rangeRectCalculator = rangeRectCalculator; portal.append(this.#annotationsPortal, this.#statusContainer); this.addEventListener(element, "focus", this.onUpdate); this.addEventListener(element, "blur", this.#onBlur); this.addEventListener(element, "mousemove", this.#onMouseMove); this.addEventListener(element, "mouseleave", this.#onMouseLeave); // capture ancestor scroll events for nested scroll containers this.addEventListener(document, "scroll", this.#onReposition, true); // selectionchange can't be bound to the textarea so we have to use the document this.addEventListener(document, "selectionchange", this.#onSelectionChange); // annotations are document-relative so we need to observe document resize as well this.addEventListener(window, "resize", this.#onReposition); // this does mean it will run twice when the resize causes a resize of the textarea, // but we also need the resize observer for the textarea because it's user resizable this.#resizeObserver = new ResizeObserver(this.#onReposition); this.#resizeObserver.observe(element); this.#tooltip = new LintErrorTooltip(portal); } disconnect() { super.disconnect(); this.#resizeObserver.disconnect(); this.#rangeRectCalculator.disconnect(); this.#tooltip.disconnect(); this.#annotationsPortal.remove(); this.#statusContainer.remove(); } /** * Return a list of rects for the given range. If the range extends over multiple lines, * multiple rects will be returned. */ getRangeRects(characterIndexes: NumberRange) { return this.#rangeRectCalculator.getClientRects(characterIndexes); } getBoundingClientRect() { return this.#editor.getBoundingClientRect(); } getLineHeight() { const parsed = parseInt(getComputedStyle(this.#editor).lineHeight, 10); return Number.isNaN(parsed) ? undefined : parsed; } abstract get value(): string; abstract get caretPosition(): number; #_annotations: readonly LintErrorAnnotation[] = []; set #annotations(annotations: ReadonlyArray<LintErrorAnnotation>) { if (annotations === this.#_annotations) return; this.#_annotations = annotations; this.#statusContainer.textContent = annotations.length > 0 ? `${annotations.length} Markdown problem${ annotations.length > 1 ? "s" : "" } identified: see line${ annotations.length > 1 ? "s" : "" } ${formatList( annotations.map((a) => a.lineNumber.toString()), "and" )}` : ""; } get #annotations() { return this.#_annotations; } #_tooltipAnnotations: readonly LintErrorAnnotation[] = []; set #tooltipAnnotations(annotations: LintErrorAnnotation[]) { if (annotations === this.#_tooltipAnnotations) return; this.#_tooltipAnnotations = annotations; const position = annotations[0]?.getTooltipPosition(); const errors = annotations.map(({error}) => error); if (position) this.#tooltip.show(errors, position); else this.#tooltip.hide(); } protected onUpdate = () => this.#lint(); #isOnRepositionTick = false; #onReposition = () => { if (this.#isOnRepositionTick) return; this.#isOnRepositionTick = true; requestAnimationFrame(() => { this.#recalculateAnnotationPositions(); this.#isOnRepositionTick = false; }); }; #onBlur = () => this.#clear(); #onMouseMove = (event: MouseEvent) => this.#updatePointerTooltip
(new Vector(event.clientX, event.clientY));
#onMouseLeave = () => (this.#tooltipAnnotations = []); #onSelectionChange = () => { // this event only works when applied to the document but we can filter it by detecting focus if (document.activeElement === this.#editor) this.#updateCaretTooltip(); }; #clear() { // the annotations will clean themselves up too but this is slightly faster this.#annotationsPortal.replaceChildren(); for (const annotation of this.#annotations) annotation.disconnect(); this.#annotations = []; this.#tooltipAnnotations = []; } #lint() { this.#clear(); // clear() will not hide the tooltip if the mouse is over it, but if the user is typing then they are not trying to copy content this.#tooltip.hide(true); if (document.activeElement !== this.#editor) return; const errors = lintMarkdown(this.value); this.#annotations = errors.map( (error) => new LintErrorAnnotation(error, this, this.#annotationsPortal) ); } #recalculateAnnotationPositions() { for (const annotation of this.#annotations) annotation.recalculatePosition(); } #updatePointerTooltip(pointerLocation: Vector) { // can't use mouse events on annotations (the easy way) because they have pointer-events: none this.#tooltipAnnotations = this.#annotations.filter((a) => a.containsPoint(pointerLocation) ); } #updateCaretTooltip() { this.#tooltipAnnotations = this.#annotations.filter((a) => a.containsIndex(this.caretPosition) ); } static #createStatusContainerElement() { const container = document.createElement("p"); container.setAttribute("aria-live", "polite"); container.style.position = "absolute"; container.style.clipPath = "circle(0)"; return container; } } export class LintedMarkdownTextareaEditor extends LintedMarkdownEditor { readonly #textarea: HTMLTextAreaElement; constructor(textarea: HTMLTextAreaElement, portal: HTMLElement) { super(textarea, portal, new TextareaRangeRectCalculator(textarea)); this.#textarea = textarea; this.addEventListener(textarea, "input", this.onUpdate); } get value() { return this.#textarea.value; } get caretPosition() { return this.#textarea.selectionEnd !== this.#textarea.selectionStart ? -1 : this.#textarea.selectionStart; } } export class LintedMarkdownCodeMirrorEditor extends LintedMarkdownEditor { readonly #element: HTMLElement; readonly #mutationObserver: MutationObserver; constructor(element: HTMLElement, portal: HTMLElement) { super(element, portal, new CodeMirrorRangeRectCalculator(element)); this.#element = element; this.#mutationObserver = new MutationObserver(this.onUpdate); this.#mutationObserver.observe(element, { childList: true, subtree: true, }); } override disconnect(): void { super.disconnect(); this.#mutationObserver.disconnect(); } get value() { return Array.from(this.#element.querySelectorAll(".CodeMirror-line")) .map((line) => line.textContent) .join("\n"); } get caretPosition() { const selection = document.getSelection(); const range = selection?.getRangeAt(0); if (!range?.collapsed || selection?.rangeCount !== 1) return -1; const referenceRange = document.createRange(); referenceRange.selectNodeContents(this.#element); referenceRange.setEnd(range.startContainer, range.startOffset); return referenceRange.toString().length; } }
src/components/linted-markdown-editor.ts
iansan5653-github-markdown-a11y-extension-c6a54d0
[ { "filename": "src/components/lint-error-tooltip.ts", "retrieved_chunk": " if (force || !this.#tooltip.matches(\":hover\"))\n this.#tooltip.setAttribute(\"hidden\", \"true\");\n }, 10);\n }\n #onGlobalKeydown(event: KeyboardEvent) {\n if (event.key === \"Escape\" && !event.defaultPrevented) this.hide(true);\n }\n static #createTooltipElement() {\n const element = document.createElement(\"div\");\n element.setAttribute(\"aria-live\", \"polite\");", "score": 27.716839186696014 }, { "filename": "src/utilities/geometry/rect.ts", "retrieved_chunk": " case \"bottom-left\":\n return new Vector(this.left, this.bottom);\n case \"bottom-right\":\n return new Vector(this.right, this.bottom);\n }\n }\n translate(vector: Vector) {\n return this.copy(this.asVector().plus(vector));\n }\n scaleY(factor: number) {", "score": 12.612145091685644 }, { "filename": "src/utilities/geometry/vector.ts", "retrieved_chunk": " return new Vector(-this.x, -this.y);\n }\n}", "score": 12.07771971813589 }, { "filename": "src/utilities/geometry/rect.ts", "retrieved_chunk": " | \"top-left\"\n | \"top-right\"\n | \"bottom-left\"\n | \"bottom-right\" = \"top-left\"\n ) {\n switch (corner) {\n case \"top-left\":\n return new Vector(this.left, this.top);\n case \"top-right\":\n return new Vector(this.right, this.top);", "score": 11.587595775270039 }, { "filename": "src/components/component.ts", "retrieved_chunk": "type EventName = keyof GlobalEventHandlersEventMap;\ntype EventHandler<Name extends EventName> = (\n event: GlobalEventHandlersEventMap[Name]\n) => void;\ninterface EventDispatcher {\n addEventListener<Name extends EventName>(\n name: Name,\n handler: EventHandler<Name>,\n capture?: boolean\n ): void;", "score": 11.546229350595 } ]
typescript
(new Vector(event.clientX, event.clientY));
import { chunkAtEnd, isNumber, zeroPad } from "./utils"; import { numberUnits, tenUnits, thousandUnits } from "./constant"; export function formatNumber(format: number | string | null = "") { if (!isNumber(Number(format))) { return ""; } return chunkAtEnd(String(format), 4) .reduce((acc, item, index) => { const unit = thousandUnits[index] ?? ""; if (!Number(item)) { return acc; } return `${Number(item)}${unit} ${acc}`; }, "") .trim(); } export function formatNumberAll(format: number | string | null = "") { if (!isNumber(Number(format))) { return ""; } return chunkAtEnd(String(format), 4) .reduce((acc, item, index) => { if (!Number(item)) { return acc; } let numberUnit = ""; const zeroItem = zeroPad(item, 4); for (let i = 0; i < 4; i++) { const number = Number(zeroItem[i]); if (number) { const unit = tenUnits[3 - i]; numberUnit += `${ unit && number === 1 ? ""
: numberUnits[number] }${unit}`;
} } const thousandUnit = thousandUnits[index] ?? ""; return `${numberUnit}${numberUnit ? thousandUnit : ""} ${acc}`; }, "") .trim(); }
src/formatNumber.ts
hyukson-hangul-util-505feaa
[ { "filename": "src/distance.ts", "retrieved_chunk": " if (!second) return first.length;\n if (memo[first + '||' + second]) {\n return memo[first + '||' + second];\n }\n const getDistance: number[][] = [[]];\n // 초기값 설정\n for (let j = 0; j <= second.length; j++) {\n getDistance[0][j] = j;\n }\n for (let i = 1; i <= first.length; i++) {", "score": 33.63341827201895 }, { "filename": "src/utils.ts", "retrieved_chunk": " const padString = String(pad);\n for (let i = pow - result.length; i > 0; i--) {\n result = padString + result;\n }\n return result;\n}\nexport function chunkAtEnd(value: string = \"\", n: number = 1) {\n const result: string[] = [];\n let start = value.length;\n while ((start -= n) > 0) {", "score": 33.26076153587885 }, { "filename": "src/sortHangul.ts", "retrieved_chunk": " compare?: string[] | string,\n orderASC: boolean = true\n) {\n if (Array.isArray(compare)) {\n const keys = compare.map((x) => splitByKey(x));\n return array.sort((a, b) => {\n for (let i = 0; i < compare.length; i++) {\n const result = baseCompare(\n getNestedProperty(keys[i], a),\n getNestedProperty(keys[i], b),", "score": 29.573190821019086 }, { "filename": "src/distance.ts", "retrieved_chunk": " getDistance[i] = [i];\n for (let j = 1; j <= second.length; j++) {\n getDistance[i][j] = minBy(\n getDistance[i - 1][j] + 1,\n getDistance[i][j - 1] + 1,\n getDistance[i - 1][j - 1] + (first[i - 1] === second[j - 1] ? 0 : 1)\n );\n }\n }\n memo[first + '||' + second] = getDistance[first.length][second.length];", "score": 28.84967799545179 }, { "filename": "src/encode.ts", "retrieved_chunk": "import { chunkAtEnd } from \"./utils\";\nconst a = [\n escape,\n (t: string) => chunkAtEnd(chunkAtEnd(t).join(\"\"), 3).join(\"\"),\n (t: string) => chunkAtEnd(chunkAtEnd(t).join(\"\"), 4).join(\"\"),\n (t: string) => chunkAtEnd(t).join(\"\"),\n (t: string) =>\n t\n .split(\"\")\n .map((v, i) => (i % 3 === 0 ? v + w() : v))", "score": 25.770327992237416 } ]
typescript
: numberUnits[number] }${unit}`;
import { chunkAtEnd, isNumber, zeroPad } from "./utils"; import { numberUnits, tenUnits, thousandUnits } from "./constant"; export function formatNumber(format: number | string | null = "") { if (!isNumber(Number(format))) { return ""; } return chunkAtEnd(String(format), 4) .reduce((acc, item, index) => { const unit = thousandUnits[index] ?? ""; if (!Number(item)) { return acc; } return `${Number(item)}${unit} ${acc}`; }, "") .trim(); } export function formatNumberAll(format: number | string | null = "") { if (!isNumber(Number(format))) { return ""; } return chunkAtEnd(String(format), 4) .reduce((acc, item, index) => { if (!Number(item)) { return acc; } let numberUnit = ""; const zeroItem = zeroPad(item, 4); for (let i = 0; i < 4; i++) { const number = Number(zeroItem[i]); if (number) { const unit = tenUnits[3 - i]; numberUnit += `${ unit && number === 1 ? "" : numberUnits[number] }${unit}`; } }
const thousandUnit = thousandUnits[index] ?? "";
return `${numberUnit}${numberUnit ? thousandUnit : ""} ${acc}`; }, "") .trim(); }
src/formatNumber.ts
hyukson-hangul-util-505feaa
[ { "filename": "src/distance.ts", "retrieved_chunk": " if (!second) return first.length;\n if (memo[first + '||' + second]) {\n return memo[first + '||' + second];\n }\n const getDistance: number[][] = [[]];\n // 초기값 설정\n for (let j = 0; j <= second.length; j++) {\n getDistance[0][j] = j;\n }\n for (let i = 1; i <= first.length; i++) {", "score": 31.722636189978015 }, { "filename": "src/utils.ts", "retrieved_chunk": " const padString = String(pad);\n for (let i = pow - result.length; i > 0; i--) {\n result = padString + result;\n }\n return result;\n}\nexport function chunkAtEnd(value: string = \"\", n: number = 1) {\n const result: string[] = [];\n let start = value.length;\n while ((start -= n) > 0) {", "score": 31.331672715129763 }, { "filename": "src/sortHangul.ts", "retrieved_chunk": " compare?: string[] | string,\n orderASC: boolean = true\n) {\n if (Array.isArray(compare)) {\n const keys = compare.map((x) => splitByKey(x));\n return array.sort((a, b) => {\n for (let i = 0; i < compare.length; i++) {\n const result = baseCompare(\n getNestedProperty(keys[i], a),\n getNestedProperty(keys[i], b),", "score": 28.31486265086732 }, { "filename": "src/distance.ts", "retrieved_chunk": " getDistance[i] = [i];\n for (let j = 1; j <= second.length; j++) {\n getDistance[i][j] = minBy(\n getDistance[i - 1][j] + 1,\n getDistance[i][j - 1] + 1,\n getDistance[i - 1][j - 1] + (first[i - 1] === second[j - 1] ? 0 : 1)\n );\n }\n }\n memo[first + '||' + second] = getDistance[first.length][second.length];", "score": 27.665362953946524 }, { "filename": "src/encode.ts", "retrieved_chunk": "import { chunkAtEnd } from \"./utils\";\nconst a = [\n escape,\n (t: string) => chunkAtEnd(chunkAtEnd(t).join(\"\"), 3).join(\"\"),\n (t: string) => chunkAtEnd(chunkAtEnd(t).join(\"\"), 4).join(\"\"),\n (t: string) => chunkAtEnd(t).join(\"\"),\n (t: string) =>\n t\n .split(\"\")\n .map((v, i) => (i % 3 === 0 ? v + w() : v))", "score": 23.455639245572854 } ]
typescript
const thousandUnit = thousandUnits[index] ?? "";
import { CodeMirrorRangeRectCalculator, RangeRectCalculator, TextareaRangeRectCalculator, } from "../utilities/dom/range-rect-calculator"; import {formatList} from "../utilities/format"; import {lintMarkdown} from "../utilities/lint-markdown"; import {LintErrorTooltip} from "./lint-error-tooltip"; import {LintErrorAnnotation} from "./lint-error-annotation"; import {Vector} from "../utilities/geometry/vector"; import {NumberRange} from "../utilities/geometry/number-range"; import {Component} from "./component"; export abstract class LintedMarkdownEditor extends Component { #editor: HTMLElement; #tooltip: LintErrorTooltip; #resizeObserver: ResizeObserver; #rangeRectCalculator: RangeRectCalculator; #annotationsPortal = document.createElement("div"); #statusContainer = LintedMarkdownEditor.#createStatusContainerElement(); constructor( element: HTMLElement, portal: HTMLElement, rangeRectCalculator: RangeRectCalculator ) { super(); this.#editor = element; this.#rangeRectCalculator = rangeRectCalculator; portal.append(this.#annotationsPortal, this.#statusContainer); this.addEventListener(element, "focus", this.onUpdate); this.addEventListener(element, "blur", this.#onBlur); this.addEventListener(element, "mousemove", this.#onMouseMove); this.addEventListener(element, "mouseleave", this.#onMouseLeave); // capture ancestor scroll events for nested scroll containers this.addEventListener(document, "scroll", this.#onReposition, true); // selectionchange can't be bound to the textarea so we have to use the document this.addEventListener(document, "selectionchange", this.#onSelectionChange); // annotations are document-relative so we need to observe document resize as well this.addEventListener(window, "resize", this.#onReposition); // this does mean it will run twice when the resize causes a resize of the textarea, // but we also need the resize observer for the textarea because it's user resizable this.#resizeObserver = new ResizeObserver(this.#onReposition); this.#resizeObserver.observe(element); this.#tooltip = new LintErrorTooltip(portal); } disconnect() { super.disconnect(); this.#resizeObserver.disconnect(); this.#rangeRectCalculator.disconnect(); this.#tooltip.disconnect(); this.#annotationsPortal.remove(); this.#statusContainer.remove(); } /** * Return a list of rects for the given range. If the range extends over multiple lines, * multiple rects will be returned. */ getRangeRects(characterIndexes: NumberRange) { return this.#rangeRectCalculator.getClientRects(characterIndexes); } getBoundingClientRect() { return this.#editor.getBoundingClientRect(); } getLineHeight() { const parsed = parseInt(getComputedStyle(this.#editor).lineHeight, 10); return Number.isNaN(parsed) ? undefined : parsed; } abstract get value(): string; abstract get caretPosition(): number; #_annotations: readonly LintErrorAnnotation[] = []; set #annotations(annotations: ReadonlyArray<LintErrorAnnotation>) { if (annotations === this.#_annotations) return; this.#_annotations = annotations; this.#statusContainer.textContent = annotations.length > 0 ? `${annotations.length} Markdown problem${ annotations.length > 1 ? "s" : "" } identified: see line${ annotations.length > 1 ? "s" : "" } ${formatList( annotations.map((a) => a.lineNumber.toString()), "and" )}` : ""; } get #annotations() { return this.#_annotations; } #_tooltipAnnotations: readonly LintErrorAnnotation[] = []; set #tooltipAnnotations(annotations: LintErrorAnnotation[]) { if (annotations === this.#_tooltipAnnotations) return; this.#_tooltipAnnotations = annotations; const position = annotations[0]?.getTooltipPosition(); const errors = annotations.map(({error}) => error); if (position) this.#tooltip.show(errors, position); else this.#tooltip.hide(); } protected onUpdate = () => this.#lint(); #isOnRepositionTick = false; #onReposition = () => { if (this.#isOnRepositionTick) return; this.#isOnRepositionTick = true; requestAnimationFrame(() => { this.#recalculateAnnotationPositions(); this.#isOnRepositionTick = false; }); }; #onBlur = () => this.#clear(); #onMouseMove = (event: MouseEvent) => this.#updatePointerTooltip(new Vector(event.clientX, event.clientY)); #onMouseLeave = () => (this.#tooltipAnnotations = []); #onSelectionChange = () => { // this event only works when applied to the document but we can filter it by detecting focus if (document.activeElement === this.#editor) this.#updateCaretTooltip(); }; #clear() { // the annotations will clean themselves up too but this is slightly faster this.#annotationsPortal.replaceChildren(); for (const annotation of this.#annotations) annotation.disconnect(); this.#annotations = []; this.#tooltipAnnotations = []; } #lint() { this.#clear(); // clear() will not hide the tooltip if the mouse is over it, but if the user is typing then they are not trying to copy content this.#tooltip.hide(true); if (document.activeElement !== this.#editor) return; const errors = lintMarkdown(this.value); this.#annotations = errors.map( (error) => new LintErrorAnnotation(error, this, this.#annotationsPortal) ); } #recalculateAnnotationPositions() { for (const annotation of this.#annotations) annotation.recalculatePosition(); } #updatePointerTooltip(pointerLocation: Vector) { // can't use mouse events on annotations (the easy way) because they have pointer-events: none this.#tooltipAnnotations = this.#annotations.filter((a) => a.containsPoint(pointerLocation) ); } #updateCaretTooltip() { this.#tooltipAnnotations = this.#annotations.filter((a) => a.containsIndex(this.caretPosition) ); } static #createStatusContainerElement() { const container = document.createElement("p"); container.setAttribute("aria-live", "polite"); container.style.position = "absolute"; container.style.clipPath = "circle(0)"; return container; } } export class LintedMarkdownTextareaEditor extends LintedMarkdownEditor { readonly #textarea: HTMLTextAreaElement; constructor(textarea: HTMLTextAreaElement, portal: HTMLElement) { super(textarea, portal, new TextareaRangeRectCalculator(textarea)); this.#textarea = textarea;
this.addEventListener(textarea, "input", this.onUpdate);
} get value() { return this.#textarea.value; } get caretPosition() { return this.#textarea.selectionEnd !== this.#textarea.selectionStart ? -1 : this.#textarea.selectionStart; } } export class LintedMarkdownCodeMirrorEditor extends LintedMarkdownEditor { readonly #element: HTMLElement; readonly #mutationObserver: MutationObserver; constructor(element: HTMLElement, portal: HTMLElement) { super(element, portal, new CodeMirrorRangeRectCalculator(element)); this.#element = element; this.#mutationObserver = new MutationObserver(this.onUpdate); this.#mutationObserver.observe(element, { childList: true, subtree: true, }); } override disconnect(): void { super.disconnect(); this.#mutationObserver.disconnect(); } get value() { return Array.from(this.#element.querySelectorAll(".CodeMirror-line")) .map((line) => line.textContent) .join("\n"); } get caretPosition() { const selection = document.getSelection(); const range = selection?.getRangeAt(0); if (!range?.collapsed || selection?.rangeCount !== 1) return -1; const referenceRange = document.createRange(); referenceRange.selectNodeContents(this.#element); referenceRange.setEnd(range.startContainer, range.startOffset); return referenceRange.toString().length; } }
src/components/linted-markdown-editor.ts
iansan5653-github-markdown-a11y-extension-c6a54d0
[ { "filename": "src/content-script.ts", "retrieved_chunk": "document.body.appendChild(rootPortal);\nobserveSelector(\n \"textarea.js-paste-markdown, textarea.CommentBox-input, textarea[aria-label='Markdown value']\",\n (editor) => {\n if (!(editor instanceof HTMLTextAreaElement)) return () => {};\n const lintedEditor = new LintedMarkdownTextareaEditor(editor, rootPortal);\n return () => lintedEditor.disconnect();\n }\n);\nobserveSelector(", "score": 46.14515757975827 }, { "filename": "src/utilities/dom/range-rect-calculator.ts", "retrieved_chunk": " * The `Range` API doesn't work well with `textarea` elements, so this creates a duplicate\n * element and uses that instead. Provides a limited API wrapping around adjusted `Range`\n * APIs.\n */\nexport class TextareaRangeRectCalculator implements RangeRectCalculator {\n readonly #element: HTMLTextAreaElement;\n readonly #div: HTMLDivElement;\n readonly #mutationObserver: MutationObserver;\n readonly #resizeObserver: ResizeObserver;\n readonly #range: Range;", "score": 33.306185164634776 }, { "filename": "src/utilities/dom/range-rect-calculator.ts", "retrieved_chunk": " constructor(target: HTMLTextAreaElement) {\n this.#element = target;\n // The mirror div will replicate the textarea's style\n const div = document.createElement(\"div\");\n this.#div = div;\n document.body.appendChild(div);\n this.#refreshStyles();\n this.#mutationObserver = new MutationObserver(() => this.#refreshStyles());\n this.#mutationObserver.observe(this.#element, {\n attributeFilter: [\"style\"],", "score": 32.39968906708181 }, { "filename": "src/components/lint-error-annotation.ts", "retrieved_chunk": " readonly #editor: LintedMarkdownEditor;\n #elements: readonly HTMLElement[] = [];\n readonly #indexRange: NumberRange;\n constructor(\n readonly error: LintError,\n editor: LintedMarkdownEditor,\n portal: HTMLElement\n ) {\n super();\n this.#editor = editor;", "score": 30.410343596169017 }, { "filename": "src/utilities/dom/range-rect-calculator.ts", "retrieved_chunk": " getClientRects({start, end}: NumberRange) {\n this.#refreshText();\n const textNode = this.#div.childNodes[0];\n if (!textNode) return [];\n this.#range.setStart(textNode, start);\n this.#range.setEnd(textNode, end);\n // The div is not in the same place as the textarea so we need to subtract the div\n // position and add the textarea position\n const divPosition = new Rect(this.#div.getBoundingClientRect()).asVector();\n const textareaPosition = new Rect(", "score": 27.76955026818863 } ]
typescript
this.addEventListener(textarea, "input", this.onUpdate);
import {NumberRange} from "../geometry/number-range"; import {Rect} from "../geometry/rect"; import {Vector} from "../geometry/vector"; // Note that some browsers, such as Firefox, do not concatenate properties // into their shorthand (e.g. padding-top, padding-bottom etc. -> padding), // so we have to list every single property explicitly. const propertiesToCopy = [ "direction", // RTL support "boxSizing", "width", // on Chrome and IE, exclude the scrollbar, so the mirror div wraps exactly as the textarea does "height", "overflowX", "overflowY", // copy the scrollbar for IE "borderTopWidth", "borderRightWidth", "borderBottomWidth", "borderLeftWidth", "borderStyle", "paddingTop", "paddingRight", "paddingBottom", "paddingLeft", // https://developer.mozilla.org/en-US/docs/Web/CSS/font "fontStyle", "fontVariant", "fontWeight", "fontStretch", "fontSize", "fontSizeAdjust", "lineHeight", "fontFamily", "textAlign", "textTransform", "textIndent", "textDecoration", // might not make a difference, but better be safe "letterSpacing", "wordSpacing", "tabSize", "MozTabSize" as "tabSize", // prefixed version for Firefox <= 52 ] as const satisfies ReadonlyArray<keyof CSSStyleDeclaration>; export interface RangeRectCalculator { /** * Return the viewport-relative client rects of the range of characters. If the range * has any line breaks, this will return multiple rects. Will include the start char and * exclude the end char. */
getClientRects({start, end}: NumberRange): Rect[];
disconnect(): void; } /** * The `Range` API doesn't work well with `textarea` elements, so this creates a duplicate * element and uses that instead. Provides a limited API wrapping around adjusted `Range` * APIs. */ export class TextareaRangeRectCalculator implements RangeRectCalculator { readonly #element: HTMLTextAreaElement; readonly #div: HTMLDivElement; readonly #mutationObserver: MutationObserver; readonly #resizeObserver: ResizeObserver; readonly #range: Range; constructor(target: HTMLTextAreaElement) { this.#element = target; // The mirror div will replicate the textarea's style const div = document.createElement("div"); this.#div = div; document.body.appendChild(div); this.#refreshStyles(); this.#mutationObserver = new MutationObserver(() => this.#refreshStyles()); this.#mutationObserver.observe(this.#element, { attributeFilter: ["style"], }); this.#resizeObserver = new ResizeObserver(() => this.#refreshStyles()); this.#resizeObserver.observe(this.#element); this.#range = document.createRange(); } /** * Return the viewport-relative client rects of the range. If the range has any line * breaks, this will return multiple rects. Will include the start char and exclude the * end char. */ getClientRects({start, end}: NumberRange) { this.#refreshText(); const textNode = this.#div.childNodes[0]; if (!textNode) return []; this.#range.setStart(textNode, start); this.#range.setEnd(textNode, end); // The div is not in the same place as the textarea so we need to subtract the div // position and add the textarea position const divPosition = new Rect(this.#div.getBoundingClientRect()).asVector(); const textareaPosition = new Rect( this.#element.getBoundingClientRect() ).asVector(); // The div is not scrollable so it does not have scroll adjustment built in const scrollOffset = new Vector( this.#element.scrollLeft, this.#element.scrollTop ); const netTranslate = divPosition .negate() .plus(textareaPosition) .minus(scrollOffset); return Array.from(this.#range.getClientRects()).map((domRect) => new Rect(domRect).translate(netTranslate) ); } disconnect() { this.#div.remove(); } #refreshStyles() { const style = this.#div.style; const textareaStyle = window.getComputedStyle(this.#element); // Default wrapping styles style.whiteSpace = "pre-wrap"; style.wordWrap = "break-word"; // Position off-screen style.position = "fixed"; style.top = "0"; style.transform = "translateY(-100%)"; const isFirefox = "mozInnerScreenX" in window; // Transfer the element's properties to the div for (const prop of propertiesToCopy) if (prop === "width" && textareaStyle.boxSizing === "border-box") { // With box-sizing: border-box we need to offset the size slightly inwards. This small difference can compound // greatly in long textareas with lots of wrapping, leading to very innacurate results if not accounted for. // Firefox will return computed styles in floats, like `0.9px`, while chromium might return `1px` for the same element. // Either way we use `parseFloat` to turn `0.9px` into `0.9` and `1px` into `1` const totalBorderWidth = parseFloat(textareaStyle.borderLeftWidth) + parseFloat(textareaStyle.borderRightWidth); // When a vertical scrollbar is present it shrinks the content. We need to account for this by using clientWidth // instead of width in everything but Firefox. When we do that we also have to account for the border width. const width = isFirefox ? parseFloat(textareaStyle.width) - totalBorderWidth : this.#element.clientWidth + totalBorderWidth; style.width = `${width}px`; } else { style[prop] = textareaStyle[prop]; } if (isFirefox) { // Firefox lies about the overflow property for textareas: https://bugzilla.mozilla.org/show_bug.cgi?id=984275 if (this.#element.scrollHeight > parseInt(textareaStyle.height)) style.overflowY = "scroll"; } else { style.overflow = "hidden"; // for Chrome to not render a scrollbar; IE keeps overflowY = 'scroll' } } #refreshText() { this.#div.textContent = this.#element instanceof HTMLInputElement ? this.#element.value.replace(/\s/g, "\u00a0") : this.#element.value; } } export class CodeMirrorRangeRectCalculator implements RangeRectCalculator { readonly #element: HTMLElement; readonly #range: Range; constructor(target: HTMLElement) { if (!target.classList.contains("CodeMirror-code")) throw new Error( "CodeMirrorRangeRectCalculator only works with CodeMirror code editors." ); this.#element = target; this.#range = document.createRange(); } getClientRects(range: NumberRange): Rect[] { const lineNodes = Array.from( this.#element.querySelectorAll(".CodeMirror-line") ); const lines = lineNodes.map((line) => CodeMirrorRangeRectCalculator.#getAllTextNodes(line) ); const start = CodeMirrorRangeRectCalculator.#getNodeAtOffset( lines, range.start ); const end = CodeMirrorRangeRectCalculator.#getNodeAtOffset( lines, range.end ); if (!start || !end) return []; this.#range.setStart(...start); this.#range.setEnd(...end); return Array.from(this.#range.getClientRects()).map( (domRect) => new Rect(domRect) ); } disconnect(): void {} static #getAllTextNodes(node: Node): Node[] { const walker = document.createTreeWalker(node, NodeFilter.SHOW_TEXT); const nodes = []; while (walker.nextNode()) nodes.push(walker.currentNode); return nodes; } /** * Get the text node containing the offset, and the relative offset into that node. * @param lines Array of nodes for each line * @param offset Offset into the entire text */ static #getNodeAtOffset( lines: Node[][], offset: number ): [node: Node, offsetIntoNode: number] | undefined { let prevChars = 0; for (const line of lines) { for (const node of line) { const length = node.textContent?.length ?? 0; if (offset <= prevChars + length) return [node, offset - prevChars]; prevChars += length; } prevChars++; // For the newline } } }
src/utilities/dom/range-rect-calculator.ts
iansan5653-github-markdown-a11y-extension-c6a54d0
[ { "filename": "src/components/linted-markdown-editor.ts", "retrieved_chunk": " this.#statusContainer.remove();\n }\n /**\n * Return a list of rects for the given range. If the range extends over multiple lines,\n * multiple rects will be returned.\n */\n getRangeRects(characterIndexes: NumberRange) {\n return this.#rangeRectCalculator.getClientRects(characterIndexes);\n }\n getBoundingClientRect() {", "score": 56.116078910645 }, { "filename": "src/components/lint-error-annotation.ts", "retrieved_chunk": " const scrollVector = getWindowScrollVector();\n // The range rectangles are tight around the characters; we'd rather fill the line height if possible\n const cssLineHeight = this.#editor.getLineHeight();\n const elements: HTMLElement[] = [];\n // render an annotation element for each line separately\n for (const rect of this.#editor.getRangeRects(this.#indexRange)) {\n // suppress when out of bounds\n if (!rect.isContainedBy(editorRect)) continue;\n // The rects are viewport-relative, but the annotations are absolute positioned\n // (document-relative) so we have to add the window scroll position", "score": 36.903049120169854 }, { "filename": "src/utilities/geometry/number-range.ts", "retrieved_chunk": "export class NumberRange {\n readonly start: number;\n readonly end: number;\n constructor(start: number, end: number) {\n this.start = Math.min(start, end);\n this.end = Math.max(start, end);\n }\n contains(\n value: number,\n mode:", "score": 29.053147513140814 }, { "filename": "src/utilities/geometry/number-range.ts", "retrieved_chunk": " case \"start-inclusive-end-exclusive\":\n return value >= this.start && value < this.end;\n case \"start-exclusive-end-inclusive\":\n return value > this.start && value <= this.end;\n }\n }\n}", "score": 25.62873032002737 }, { "filename": "src/utilities/geometry/number-range.ts", "retrieved_chunk": " | \"inclusive\"\n | \"exclusive\"\n | \"start-inclusive-end-exclusive\"\n | \"start-exclusive-end-inclusive\"\n ) {\n switch (mode) {\n case \"inclusive\":\n return value >= this.start && value <= this.end;\n case \"exclusive\":\n return value > this.start && value < this.end;", "score": 24.692685026678685 } ]
typescript
getClientRects({start, end}: NumberRange): Rect[];
import { CodeMirrorRangeRectCalculator, RangeRectCalculator, TextareaRangeRectCalculator, } from "../utilities/dom/range-rect-calculator"; import {formatList} from "../utilities/format"; import {lintMarkdown} from "../utilities/lint-markdown"; import {LintErrorTooltip} from "./lint-error-tooltip"; import {LintErrorAnnotation} from "./lint-error-annotation"; import {Vector} from "../utilities/geometry/vector"; import {NumberRange} from "../utilities/geometry/number-range"; import {Component} from "./component"; export abstract class LintedMarkdownEditor extends Component { #editor: HTMLElement; #tooltip: LintErrorTooltip; #resizeObserver: ResizeObserver; #rangeRectCalculator: RangeRectCalculator; #annotationsPortal = document.createElement("div"); #statusContainer = LintedMarkdownEditor.#createStatusContainerElement(); constructor( element: HTMLElement, portal: HTMLElement, rangeRectCalculator: RangeRectCalculator ) { super(); this.#editor = element; this.#rangeRectCalculator = rangeRectCalculator; portal.append(this.#annotationsPortal, this.#statusContainer); this.addEventListener(element, "focus", this.onUpdate); this.addEventListener(element, "blur", this.#onBlur); this.addEventListener(element, "mousemove", this.#onMouseMove); this.addEventListener(element, "mouseleave", this.#onMouseLeave); // capture ancestor scroll events for nested scroll containers this.addEventListener(document, "scroll", this.#onReposition, true); // selectionchange can't be bound to the textarea so we have to use the document this.addEventListener(document, "selectionchange", this.#onSelectionChange); // annotations are document-relative so we need to observe document resize as well this.addEventListener(window, "resize", this.#onReposition); // this does mean it will run twice when the resize causes a resize of the textarea, // but we also need the resize observer for the textarea because it's user resizable this.#resizeObserver = new ResizeObserver(this.#onReposition); this.#resizeObserver.observe(element); this.#tooltip = new LintErrorTooltip(portal); } disconnect() { super.disconnect(); this.#resizeObserver.disconnect(); this.#rangeRectCalculator.disconnect(); this.#tooltip.disconnect(); this.#annotationsPortal.remove(); this.#statusContainer.remove(); } /** * Return a list of rects for the given range. If the range extends over multiple lines, * multiple rects will be returned. */ getRangeRects(characterIndexes: NumberRange) { return this.#rangeRectCalculator.getClientRects(characterIndexes); } getBoundingClientRect() { return this.#editor.getBoundingClientRect(); } getLineHeight() { const parsed = parseInt(getComputedStyle(this.#editor).lineHeight, 10); return Number.isNaN(parsed) ? undefined : parsed; } abstract get value(): string; abstract get caretPosition(): number; #_annotations: readonly LintErrorAnnotation[] = []; set #annotations(annotations: ReadonlyArray<LintErrorAnnotation>) { if (annotations === this.#_annotations) return; this.#_annotations = annotations; this.#statusContainer.textContent = annotations.length > 0 ? `${annotations.length} Markdown problem${ annotations.length > 1 ? "s" : "" } identified: see line${ annotations.length > 1 ? "s" : "" } ${formatList( annotations.map((a) => a.lineNumber.toString()), "and" )}` : ""; } get #annotations() { return this.#_annotations; } #_tooltipAnnotations: readonly LintErrorAnnotation[] = []; set #tooltipAnnotations(annotations: LintErrorAnnotation[]) { if (annotations === this.#_tooltipAnnotations) return; this.#_tooltipAnnotations = annotations; const position = annotations[0]?.getTooltipPosition(); const errors = annotations.map(({error}) => error); if (position) this.#tooltip.show(errors, position); else this.#tooltip.hide(); } protected onUpdate = () => this.#lint(); #isOnRepositionTick = false; #onReposition = () => { if (this.#isOnRepositionTick) return; this.#isOnRepositionTick = true; requestAnimationFrame(() => { this.#recalculateAnnotationPositions(); this.#isOnRepositionTick = false; }); }; #onBlur = () => this.#clear(); #onMouseMove = (event: MouseEvent) => this.#updatePointerTooltip(new Vector(event.clientX, event.clientY)); #onMouseLeave = () => (this.#tooltipAnnotations = []); #onSelectionChange = () => { // this event only works when applied to the document but we can filter it by detecting focus if (document.activeElement === this.#editor) this.#updateCaretTooltip(); }; #clear() { // the annotations will clean themselves up too but this is slightly faster this.#annotationsPortal.replaceChildren(); for (const annotation of this.#annotations) annotation.disconnect(); this.#annotations = []; this.#tooltipAnnotations = []; } #lint() { this.#clear(); // clear() will not hide the tooltip if the mouse is over it, but if the user is typing then they are not trying to copy content this.#tooltip.hide(true); if (document.activeElement !== this.#editor) return; const errors = lintMarkdown(this.value); this.#annotations = errors.map( (
error) => new LintErrorAnnotation(error, this, this.#annotationsPortal) );
} #recalculateAnnotationPositions() { for (const annotation of this.#annotations) annotation.recalculatePosition(); } #updatePointerTooltip(pointerLocation: Vector) { // can't use mouse events on annotations (the easy way) because they have pointer-events: none this.#tooltipAnnotations = this.#annotations.filter((a) => a.containsPoint(pointerLocation) ); } #updateCaretTooltip() { this.#tooltipAnnotations = this.#annotations.filter((a) => a.containsIndex(this.caretPosition) ); } static #createStatusContainerElement() { const container = document.createElement("p"); container.setAttribute("aria-live", "polite"); container.style.position = "absolute"; container.style.clipPath = "circle(0)"; return container; } } export class LintedMarkdownTextareaEditor extends LintedMarkdownEditor { readonly #textarea: HTMLTextAreaElement; constructor(textarea: HTMLTextAreaElement, portal: HTMLElement) { super(textarea, portal, new TextareaRangeRectCalculator(textarea)); this.#textarea = textarea; this.addEventListener(textarea, "input", this.onUpdate); } get value() { return this.#textarea.value; } get caretPosition() { return this.#textarea.selectionEnd !== this.#textarea.selectionStart ? -1 : this.#textarea.selectionStart; } } export class LintedMarkdownCodeMirrorEditor extends LintedMarkdownEditor { readonly #element: HTMLElement; readonly #mutationObserver: MutationObserver; constructor(element: HTMLElement, portal: HTMLElement) { super(element, portal, new CodeMirrorRangeRectCalculator(element)); this.#element = element; this.#mutationObserver = new MutationObserver(this.onUpdate); this.#mutationObserver.observe(element, { childList: true, subtree: true, }); } override disconnect(): void { super.disconnect(); this.#mutationObserver.disconnect(); } get value() { return Array.from(this.#element.querySelectorAll(".CodeMirror-line")) .map((line) => line.textContent) .join("\n"); } get caretPosition() { const selection = document.getSelection(); const range = selection?.getRangeAt(0); if (!range?.collapsed || selection?.rangeCount !== 1) return -1; const referenceRange = document.createRange(); referenceRange.selectNodeContents(this.#element); referenceRange.setEnd(range.startContainer, range.startOffset); return referenceRange.toString().length; } }
src/components/linted-markdown-editor.ts
iansan5653-github-markdown-a11y-extension-c6a54d0
[ { "filename": "src/components/lint-error-tooltip.ts", "retrieved_chunk": " const availableWidth = document.body.clientWidth - 2 * MARGIN;\n const rightOverflow = Math.max(x + WIDTH - (availableWidth + MARGIN), 0);\n this.#tooltip.style.left = `${Math.max(x - rightOverflow, MARGIN)}px`;\n this.#tooltip.style.maxWidth = `${availableWidth}px`;\n }\n this.#tooltip.removeAttribute(\"hidden\");\n }\n hide(force = false) {\n // Don't hide if the mouse enters the tooltip (allowing users to copy text)\n setTimeout(() => {", "score": 40.447690413705345 }, { "filename": "src/components/lint-error-tooltip.ts", "retrieved_chunk": " super();\n this.addEventListener(document, \"keydown\", (e) => this.#onGlobalKeydown(e));\n this.addEventListener(this.#tooltip, \"mouseout\", () => this.hide());\n portal.appendChild(this.#tooltip);\n }\n disconnect() {\n super.disconnect();\n this.#tooltip.remove();\n }\n show(errors: LintError[], {x, y}: Vector) {", "score": 36.11575647353682 }, { "filename": "src/components/lint-error-tooltip.ts", "retrieved_chunk": " if (force || !this.#tooltip.matches(\":hover\"))\n this.#tooltip.setAttribute(\"hidden\", \"true\");\n }, 10);\n }\n #onGlobalKeydown(event: KeyboardEvent) {\n if (event.key === \"Escape\" && !event.defaultPrevented) this.hide(true);\n }\n static #createTooltipElement() {\n const element = document.createElement(\"div\");\n element.setAttribute(\"aria-live\", \"polite\");", "score": 33.843981413846286 }, { "filename": "src/components/lint-error-annotation.ts", "retrieved_chunk": " const scrollVector = getWindowScrollVector();\n // The range rectangles are tight around the characters; we'd rather fill the line height if possible\n const cssLineHeight = this.#editor.getLineHeight();\n const elements: HTMLElement[] = [];\n // render an annotation element for each line separately\n for (const rect of this.#editor.getRangeRects(this.#indexRange)) {\n // suppress when out of bounds\n if (!rect.isContainedBy(editorRect)) continue;\n // The rects are viewport-relative, but the annotations are absolute positioned\n // (document-relative) so we have to add the window scroll position", "score": 30.396555066273546 }, { "filename": "src/utilities/dom/range-rect-calculator.ts", "retrieved_chunk": " getClientRects({start, end}: NumberRange) {\n this.#refreshText();\n const textNode = this.#div.childNodes[0];\n if (!textNode) return [];\n this.#range.setStart(textNode, start);\n this.#range.setEnd(textNode, end);\n // The div is not in the same place as the textarea so we need to subtract the div\n // position and add the textarea position\n const divPosition = new Rect(this.#div.getBoundingClientRect()).asVector();\n const textareaPosition = new Rect(", "score": 29.306041307488755 } ]
typescript
error) => new LintErrorAnnotation(error, this, this.#annotationsPortal) );
import { CodeMirrorRangeRectCalculator, RangeRectCalculator, TextareaRangeRectCalculator, } from "../utilities/dom/range-rect-calculator"; import {formatList} from "../utilities/format"; import {lintMarkdown} from "../utilities/lint-markdown"; import {LintErrorTooltip} from "./lint-error-tooltip"; import {LintErrorAnnotation} from "./lint-error-annotation"; import {Vector} from "../utilities/geometry/vector"; import {NumberRange} from "../utilities/geometry/number-range"; import {Component} from "./component"; export abstract class LintedMarkdownEditor extends Component { #editor: HTMLElement; #tooltip: LintErrorTooltip; #resizeObserver: ResizeObserver; #rangeRectCalculator: RangeRectCalculator; #annotationsPortal = document.createElement("div"); #statusContainer = LintedMarkdownEditor.#createStatusContainerElement(); constructor( element: HTMLElement, portal: HTMLElement, rangeRectCalculator: RangeRectCalculator ) { super(); this.#editor = element; this.#rangeRectCalculator = rangeRectCalculator; portal.append(this.#annotationsPortal, this.#statusContainer); this.addEventListener(element, "focus", this.onUpdate); this.addEventListener(element, "blur", this.#onBlur); this.addEventListener(element, "mousemove", this.#onMouseMove); this.addEventListener(element, "mouseleave", this.#onMouseLeave); // capture ancestor scroll events for nested scroll containers this.addEventListener(document, "scroll", this.#onReposition, true); // selectionchange can't be bound to the textarea so we have to use the document this.addEventListener(document, "selectionchange", this.#onSelectionChange); // annotations are document-relative so we need to observe document resize as well this.addEventListener(window, "resize", this.#onReposition); // this does mean it will run twice when the resize causes a resize of the textarea, // but we also need the resize observer for the textarea because it's user resizable this.#resizeObserver = new ResizeObserver(this.#onReposition); this.#resizeObserver.observe(element); this.#tooltip = new LintErrorTooltip(portal); } disconnect() { super.disconnect(); this.#resizeObserver.disconnect(); this.#rangeRectCalculator.disconnect(); this.#tooltip.disconnect(); this.#annotationsPortal.remove(); this.#statusContainer.remove(); } /** * Return a list of rects for the given range. If the range extends over multiple lines, * multiple rects will be returned. */ getRangeRects(characterIndexes: NumberRange) { return this.#rangeRectCalculator.getClientRects(characterIndexes); } getBoundingClientRect() { return this.#editor.getBoundingClientRect(); } getLineHeight() { const parsed = parseInt(getComputedStyle(this.#editor).lineHeight, 10); return Number.isNaN(parsed) ? undefined : parsed; } abstract get value(): string; abstract get caretPosition(): number; #_annotations: readonly LintErrorAnnotation[] = []; set #annotations(annotations: ReadonlyArray<LintErrorAnnotation>) { if (annotations === this.#_annotations) return; this.#_annotations = annotations; this.#statusContainer.textContent = annotations.length > 0 ? `${annotations.length} Markdown problem${ annotations.length > 1 ? "s" : "" } identified: see line${ annotations.length > 1 ? "s" : "" } ${formatList( annotations.map((a) => a.lineNumber.toString()), "and" )}` : ""; } get #annotations() { return this.#_annotations; } #_tooltipAnnotations: readonly LintErrorAnnotation[] = []; set #tooltipAnnotations(annotations: LintErrorAnnotation[]) { if (annotations === this.#_tooltipAnnotations) return; this.#_tooltipAnnotations = annotations; const position = annotations[0]?.getTooltipPosition(); const errors = annotations.map(({error}) => error); if (position) this.#tooltip.show(errors, position); else this.#tooltip.hide(); } protected onUpdate = () => this.#lint(); #isOnRepositionTick = false; #onReposition = () => { if (this.#isOnRepositionTick) return; this.#isOnRepositionTick = true; requestAnimationFrame(() => { this.#recalculateAnnotationPositions(); this.#isOnRepositionTick = false; }); }; #onBlur = () => this.#clear(); #onMouseMove = (event: MouseEvent) => this.#updatePointerTooltip(new Vector(event.clientX, event.clientY)); #onMouseLeave = () => (this.#tooltipAnnotations = []); #onSelectionChange = () => { // this event only works when applied to the document but we can filter it by detecting focus if (document.activeElement === this.#editor) this.#updateCaretTooltip(); }; #clear() { // the annotations will clean themselves up too but this is slightly faster this.#annotationsPortal.replaceChildren(); for (const annotation of this.#annotations) annotation.disconnect(); this.#annotations = []; this.#tooltipAnnotations = []; } #lint() { this.#clear(); // clear() will not hide the tooltip if the mouse is over it, but if the user is typing then they are not trying to copy content this.#tooltip.hide(true); if (document.activeElement !== this.#editor) return;
const errors = lintMarkdown(this.value);
this.#annotations = errors.map( (error) => new LintErrorAnnotation(error, this, this.#annotationsPortal) ); } #recalculateAnnotationPositions() { for (const annotation of this.#annotations) annotation.recalculatePosition(); } #updatePointerTooltip(pointerLocation: Vector) { // can't use mouse events on annotations (the easy way) because they have pointer-events: none this.#tooltipAnnotations = this.#annotations.filter((a) => a.containsPoint(pointerLocation) ); } #updateCaretTooltip() { this.#tooltipAnnotations = this.#annotations.filter((a) => a.containsIndex(this.caretPosition) ); } static #createStatusContainerElement() { const container = document.createElement("p"); container.setAttribute("aria-live", "polite"); container.style.position = "absolute"; container.style.clipPath = "circle(0)"; return container; } } export class LintedMarkdownTextareaEditor extends LintedMarkdownEditor { readonly #textarea: HTMLTextAreaElement; constructor(textarea: HTMLTextAreaElement, portal: HTMLElement) { super(textarea, portal, new TextareaRangeRectCalculator(textarea)); this.#textarea = textarea; this.addEventListener(textarea, "input", this.onUpdate); } get value() { return this.#textarea.value; } get caretPosition() { return this.#textarea.selectionEnd !== this.#textarea.selectionStart ? -1 : this.#textarea.selectionStart; } } export class LintedMarkdownCodeMirrorEditor extends LintedMarkdownEditor { readonly #element: HTMLElement; readonly #mutationObserver: MutationObserver; constructor(element: HTMLElement, portal: HTMLElement) { super(element, portal, new CodeMirrorRangeRectCalculator(element)); this.#element = element; this.#mutationObserver = new MutationObserver(this.onUpdate); this.#mutationObserver.observe(element, { childList: true, subtree: true, }); } override disconnect(): void { super.disconnect(); this.#mutationObserver.disconnect(); } get value() { return Array.from(this.#element.querySelectorAll(".CodeMirror-line")) .map((line) => line.textContent) .join("\n"); } get caretPosition() { const selection = document.getSelection(); const range = selection?.getRangeAt(0); if (!range?.collapsed || selection?.rangeCount !== 1) return -1; const referenceRange = document.createRange(); referenceRange.selectNodeContents(this.#element); referenceRange.setEnd(range.startContainer, range.startOffset); return referenceRange.toString().length; } }
src/components/linted-markdown-editor.ts
iansan5653-github-markdown-a11y-extension-c6a54d0
[ { "filename": "src/components/lint-error-tooltip.ts", "retrieved_chunk": " const availableWidth = document.body.clientWidth - 2 * MARGIN;\n const rightOverflow = Math.max(x + WIDTH - (availableWidth + MARGIN), 0);\n this.#tooltip.style.left = `${Math.max(x - rightOverflow, MARGIN)}px`;\n this.#tooltip.style.maxWidth = `${availableWidth}px`;\n }\n this.#tooltip.removeAttribute(\"hidden\");\n }\n hide(force = false) {\n // Don't hide if the mouse enters the tooltip (allowing users to copy text)\n setTimeout(() => {", "score": 41.50688974442004 }, { "filename": "src/components/lint-error-annotation.ts", "retrieved_chunk": " const scrollVector = getWindowScrollVector();\n // The range rectangles are tight around the characters; we'd rather fill the line height if possible\n const cssLineHeight = this.#editor.getLineHeight();\n const elements: HTMLElement[] = [];\n // render an annotation element for each line separately\n for (const rect of this.#editor.getRangeRects(this.#indexRange)) {\n // suppress when out of bounds\n if (!rect.isContainedBy(editorRect)) continue;\n // The rects are viewport-relative, but the annotations are absolute positioned\n // (document-relative) so we have to add the window scroll position", "score": 40.858428081272706 }, { "filename": "src/components/lint-error-tooltip.ts", "retrieved_chunk": " super();\n this.addEventListener(document, \"keydown\", (e) => this.#onGlobalKeydown(e));\n this.addEventListener(this.#tooltip, \"mouseout\", () => this.hide());\n portal.appendChild(this.#tooltip);\n }\n disconnect() {\n super.disconnect();\n this.#tooltip.remove();\n }\n show(errors: LintError[], {x, y}: Vector) {", "score": 35.63793527693657 }, { "filename": "src/components/lint-error-tooltip.ts", "retrieved_chunk": " if (force || !this.#tooltip.matches(\":hover\"))\n this.#tooltip.setAttribute(\"hidden\", \"true\");\n }, 10);\n }\n #onGlobalKeydown(event: KeyboardEvent) {\n if (event.key === \"Escape\" && !event.defaultPrevented) this.hide(true);\n }\n static #createTooltipElement() {\n const element = document.createElement(\"div\");\n element.setAttribute(\"aria-live\", \"polite\");", "score": 34.71136069211128 }, { "filename": "src/utilities/dom/range-rect-calculator.ts", "retrieved_chunk": " getClientRects({start, end}: NumberRange) {\n this.#refreshText();\n const textNode = this.#div.childNodes[0];\n if (!textNode) return [];\n this.#range.setStart(textNode, start);\n this.#range.setEnd(textNode, end);\n // The div is not in the same place as the textarea so we need to subtract the div\n // position and add the textarea position\n const divPosition = new Rect(this.#div.getBoundingClientRect()).asVector();\n const textareaPosition = new Rect(", "score": 29.479838839314496 } ]
typescript
const errors = lintMarkdown(this.value);
import {NumberRange} from "../geometry/number-range"; import {Rect} from "../geometry/rect"; import {Vector} from "../geometry/vector"; // Note that some browsers, such as Firefox, do not concatenate properties // into their shorthand (e.g. padding-top, padding-bottom etc. -> padding), // so we have to list every single property explicitly. const propertiesToCopy = [ "direction", // RTL support "boxSizing", "width", // on Chrome and IE, exclude the scrollbar, so the mirror div wraps exactly as the textarea does "height", "overflowX", "overflowY", // copy the scrollbar for IE "borderTopWidth", "borderRightWidth", "borderBottomWidth", "borderLeftWidth", "borderStyle", "paddingTop", "paddingRight", "paddingBottom", "paddingLeft", // https://developer.mozilla.org/en-US/docs/Web/CSS/font "fontStyle", "fontVariant", "fontWeight", "fontStretch", "fontSize", "fontSizeAdjust", "lineHeight", "fontFamily", "textAlign", "textTransform", "textIndent", "textDecoration", // might not make a difference, but better be safe "letterSpacing", "wordSpacing", "tabSize", "MozTabSize" as "tabSize", // prefixed version for Firefox <= 52 ] as const satisfies ReadonlyArray<keyof CSSStyleDeclaration>; export interface RangeRectCalculator { /** * Return the viewport-relative client rects of the range of characters. If the range * has any line breaks, this will return multiple rects. Will include the start char and * exclude the end char. */ getClientRects({start, end}: NumberRange): Rect[]; disconnect(): void; } /** * The `Range` API doesn't work well with `textarea` elements, so this creates a duplicate * element and uses that instead. Provides a limited API wrapping around adjusted `Range` * APIs. */ export class TextareaRangeRectCalculator implements RangeRectCalculator { readonly #element: HTMLTextAreaElement; readonly #div: HTMLDivElement; readonly #mutationObserver: MutationObserver; readonly #resizeObserver: ResizeObserver; readonly #range: Range; constructor(target: HTMLTextAreaElement) { this.#element = target; // The mirror div will replicate the textarea's style const div = document.createElement("div"); this.#div = div; document.body.appendChild(div); this.#refreshStyles(); this.#mutationObserver = new MutationObserver(() => this.#refreshStyles()); this.#mutationObserver.observe(this.#element, { attributeFilter: ["style"], }); this.#resizeObserver = new ResizeObserver(() => this.#refreshStyles()); this.#resizeObserver.observe(this.#element); this.#range = document.createRange(); } /** * Return the viewport-relative client rects of the range. If the range has any line * breaks, this will return multiple rects. Will include the start char and exclude the * end char. */ getClientRects({start, end}: NumberRange) { this.#refreshText(); const textNode = this.#div.childNodes[0]; if (!textNode) return []; this.#range.setStart(textNode, start); this.#range.setEnd(textNode, end); // The div is not in the same place as the textarea so we need to subtract the div // position and add the textarea position const divPosition = new Rect(this.#div.getBoundingClientRect()).asVector(); const textareaPosition = new Rect( this.#element.getBoundingClientRect() ).asVector(); // The div is not scrollable so it does not have scroll adjustment built in const scrollOffset =
new Vector( this.#element.scrollLeft, this.#element.scrollTop );
const netTranslate = divPosition .negate() .plus(textareaPosition) .minus(scrollOffset); return Array.from(this.#range.getClientRects()).map((domRect) => new Rect(domRect).translate(netTranslate) ); } disconnect() { this.#div.remove(); } #refreshStyles() { const style = this.#div.style; const textareaStyle = window.getComputedStyle(this.#element); // Default wrapping styles style.whiteSpace = "pre-wrap"; style.wordWrap = "break-word"; // Position off-screen style.position = "fixed"; style.top = "0"; style.transform = "translateY(-100%)"; const isFirefox = "mozInnerScreenX" in window; // Transfer the element's properties to the div for (const prop of propertiesToCopy) if (prop === "width" && textareaStyle.boxSizing === "border-box") { // With box-sizing: border-box we need to offset the size slightly inwards. This small difference can compound // greatly in long textareas with lots of wrapping, leading to very innacurate results if not accounted for. // Firefox will return computed styles in floats, like `0.9px`, while chromium might return `1px` for the same element. // Either way we use `parseFloat` to turn `0.9px` into `0.9` and `1px` into `1` const totalBorderWidth = parseFloat(textareaStyle.borderLeftWidth) + parseFloat(textareaStyle.borderRightWidth); // When a vertical scrollbar is present it shrinks the content. We need to account for this by using clientWidth // instead of width in everything but Firefox. When we do that we also have to account for the border width. const width = isFirefox ? parseFloat(textareaStyle.width) - totalBorderWidth : this.#element.clientWidth + totalBorderWidth; style.width = `${width}px`; } else { style[prop] = textareaStyle[prop]; } if (isFirefox) { // Firefox lies about the overflow property for textareas: https://bugzilla.mozilla.org/show_bug.cgi?id=984275 if (this.#element.scrollHeight > parseInt(textareaStyle.height)) style.overflowY = "scroll"; } else { style.overflow = "hidden"; // for Chrome to not render a scrollbar; IE keeps overflowY = 'scroll' } } #refreshText() { this.#div.textContent = this.#element instanceof HTMLInputElement ? this.#element.value.replace(/\s/g, "\u00a0") : this.#element.value; } } export class CodeMirrorRangeRectCalculator implements RangeRectCalculator { readonly #element: HTMLElement; readonly #range: Range; constructor(target: HTMLElement) { if (!target.classList.contains("CodeMirror-code")) throw new Error( "CodeMirrorRangeRectCalculator only works with CodeMirror code editors." ); this.#element = target; this.#range = document.createRange(); } getClientRects(range: NumberRange): Rect[] { const lineNodes = Array.from( this.#element.querySelectorAll(".CodeMirror-line") ); const lines = lineNodes.map((line) => CodeMirrorRangeRectCalculator.#getAllTextNodes(line) ); const start = CodeMirrorRangeRectCalculator.#getNodeAtOffset( lines, range.start ); const end = CodeMirrorRangeRectCalculator.#getNodeAtOffset( lines, range.end ); if (!start || !end) return []; this.#range.setStart(...start); this.#range.setEnd(...end); return Array.from(this.#range.getClientRects()).map( (domRect) => new Rect(domRect) ); } disconnect(): void {} static #getAllTextNodes(node: Node): Node[] { const walker = document.createTreeWalker(node, NodeFilter.SHOW_TEXT); const nodes = []; while (walker.nextNode()) nodes.push(walker.currentNode); return nodes; } /** * Get the text node containing the offset, and the relative offset into that node. * @param lines Array of nodes for each line * @param offset Offset into the entire text */ static #getNodeAtOffset( lines: Node[][], offset: number ): [node: Node, offsetIntoNode: number] | undefined { let prevChars = 0; for (const line of lines) { for (const node of line) { const length = node.textContent?.length ?? 0; if (offset <= prevChars + length) return [node, offset - prevChars]; prevChars += length; } prevChars++; // For the newline } } }
src/utilities/dom/range-rect-calculator.ts
iansan5653-github-markdown-a11y-extension-c6a54d0
[ { "filename": "src/components/lint-error-annotation.ts", "retrieved_chunk": " }\n getTooltipPosition() {\n const domRect = this.#elements.at(-1)?.getBoundingClientRect();\n if (domRect)\n return new Rect(domRect)\n .asVector(\"bottom-left\")\n .plus(new Vector(0, 2)) // add some breathing room\n .plus(getWindowScrollVector());\n }\n containsPoint(point: Vector) {", "score": 26.836386845947743 }, { "filename": "src/components/lint-error-annotation.ts", "retrieved_chunk": " return this.#elements.some((el) =>\n // scale slightly so we don't show two tooltips at touching horizontal edges\n new Rect(el.getBoundingClientRect()).scaleY(0.99).contains(point)\n );\n }\n containsIndex(index: number) {\n return this.#indexRange.contains(index, \"inclusive\");\n }\n recalculatePosition() {\n const editorRect = new Rect(this.#editor.getBoundingClientRect());", "score": 25.06358810018936 }, { "filename": "src/components/linted-markdown-editor.ts", "retrieved_chunk": " }\n #lint() {\n this.#clear();\n // clear() will not hide the tooltip if the mouse is over it, but if the user is typing then they are not trying to copy content\n this.#tooltip.hide(true);\n if (document.activeElement !== this.#editor) return;\n const errors = lintMarkdown(this.value);\n this.#annotations = errors.map(\n (error) => new LintErrorAnnotation(error, this, this.#annotationsPortal)\n );", "score": 22.101209736101747 }, { "filename": "src/components/linted-markdown-editor.ts", "retrieved_chunk": " this.addEventListener(element, \"mousemove\", this.#onMouseMove);\n this.addEventListener(element, \"mouseleave\", this.#onMouseLeave);\n // capture ancestor scroll events for nested scroll containers\n this.addEventListener(document, \"scroll\", this.#onReposition, true);\n // selectionchange can't be bound to the textarea so we have to use the document\n this.addEventListener(document, \"selectionchange\", this.#onSelectionChange);\n // annotations are document-relative so we need to observe document resize as well\n this.addEventListener(window, \"resize\", this.#onReposition);\n // this does mean it will run twice when the resize causes a resize of the textarea,\n // but we also need the resize observer for the textarea because it's user resizable", "score": 21.543431828939095 }, { "filename": "src/utilities/geometry/rect.ts", "retrieved_chunk": " case \"bottom-left\":\n return new Vector(this.left, this.bottom);\n case \"bottom-right\":\n return new Vector(this.right, this.bottom);\n }\n }\n translate(vector: Vector) {\n return this.copy(this.asVector().plus(vector));\n }\n scaleY(factor: number) {", "score": 19.292875556858768 } ]
typescript
new Vector( this.#element.scrollLeft, this.#element.scrollTop );
import { CodeMirrorRangeRectCalculator, RangeRectCalculator, TextareaRangeRectCalculator, } from "../utilities/dom/range-rect-calculator"; import {formatList} from "../utilities/format"; import {lintMarkdown} from "../utilities/lint-markdown"; import {LintErrorTooltip} from "./lint-error-tooltip"; import {LintErrorAnnotation} from "./lint-error-annotation"; import {Vector} from "../utilities/geometry/vector"; import {NumberRange} from "../utilities/geometry/number-range"; import {Component} from "./component"; export abstract class LintedMarkdownEditor extends Component { #editor: HTMLElement; #tooltip: LintErrorTooltip; #resizeObserver: ResizeObserver; #rangeRectCalculator: RangeRectCalculator; #annotationsPortal = document.createElement("div"); #statusContainer = LintedMarkdownEditor.#createStatusContainerElement(); constructor( element: HTMLElement, portal: HTMLElement, rangeRectCalculator: RangeRectCalculator ) { super(); this.#editor = element; this.#rangeRectCalculator = rangeRectCalculator; portal.append(this.#annotationsPortal, this.#statusContainer); this.addEventListener(element, "focus", this.onUpdate); this.addEventListener(element, "blur", this.#onBlur); this.addEventListener(element, "mousemove", this.#onMouseMove); this.addEventListener(element, "mouseleave", this.#onMouseLeave); // capture ancestor scroll events for nested scroll containers this.addEventListener(document, "scroll", this.#onReposition, true); // selectionchange can't be bound to the textarea so we have to use the document this.addEventListener(document, "selectionchange", this.#onSelectionChange); // annotations are document-relative so we need to observe document resize as well this.addEventListener(window, "resize", this.#onReposition); // this does mean it will run twice when the resize causes a resize of the textarea, // but we also need the resize observer for the textarea because it's user resizable this.#resizeObserver = new ResizeObserver(this.#onReposition); this.#resizeObserver.observe(element); this.#tooltip = new LintErrorTooltip(portal); } disconnect() { super.disconnect(); this.#resizeObserver.disconnect(); this.#rangeRectCalculator.disconnect(); this.#tooltip.disconnect(); this.#annotationsPortal.remove(); this.#statusContainer.remove(); } /** * Return a list of rects for the given range. If the range extends over multiple lines, * multiple rects will be returned. */ getRangeRects(characterIndexes: NumberRange) { return this.#rangeRectCalculator.getClientRects(characterIndexes); } getBoundingClientRect() { return this.#editor.getBoundingClientRect(); } getLineHeight() { const parsed = parseInt(getComputedStyle(this.#editor).lineHeight, 10); return Number.isNaN(parsed) ? undefined : parsed; } abstract get value(): string; abstract get caretPosition(): number; #_annotations: readonly LintErrorAnnotation[] = []; set #annotations(annotations: ReadonlyArray<LintErrorAnnotation>) { if (annotations === this.#_annotations) return; this.#_annotations = annotations; this.#statusContainer.textContent = annotations.length > 0 ? `${annotations.length} Markdown problem${ annotations.length > 1 ? "s" : "" } identified: see line${ annotations.length > 1 ? "s" : "" } ${formatList(
annotations.map((a) => a.lineNumber.toString()), "and" )}` : "";
} get #annotations() { return this.#_annotations; } #_tooltipAnnotations: readonly LintErrorAnnotation[] = []; set #tooltipAnnotations(annotations: LintErrorAnnotation[]) { if (annotations === this.#_tooltipAnnotations) return; this.#_tooltipAnnotations = annotations; const position = annotations[0]?.getTooltipPosition(); const errors = annotations.map(({error}) => error); if (position) this.#tooltip.show(errors, position); else this.#tooltip.hide(); } protected onUpdate = () => this.#lint(); #isOnRepositionTick = false; #onReposition = () => { if (this.#isOnRepositionTick) return; this.#isOnRepositionTick = true; requestAnimationFrame(() => { this.#recalculateAnnotationPositions(); this.#isOnRepositionTick = false; }); }; #onBlur = () => this.#clear(); #onMouseMove = (event: MouseEvent) => this.#updatePointerTooltip(new Vector(event.clientX, event.clientY)); #onMouseLeave = () => (this.#tooltipAnnotations = []); #onSelectionChange = () => { // this event only works when applied to the document but we can filter it by detecting focus if (document.activeElement === this.#editor) this.#updateCaretTooltip(); }; #clear() { // the annotations will clean themselves up too but this is slightly faster this.#annotationsPortal.replaceChildren(); for (const annotation of this.#annotations) annotation.disconnect(); this.#annotations = []; this.#tooltipAnnotations = []; } #lint() { this.#clear(); // clear() will not hide the tooltip if the mouse is over it, but if the user is typing then they are not trying to copy content this.#tooltip.hide(true); if (document.activeElement !== this.#editor) return; const errors = lintMarkdown(this.value); this.#annotations = errors.map( (error) => new LintErrorAnnotation(error, this, this.#annotationsPortal) ); } #recalculateAnnotationPositions() { for (const annotation of this.#annotations) annotation.recalculatePosition(); } #updatePointerTooltip(pointerLocation: Vector) { // can't use mouse events on annotations (the easy way) because they have pointer-events: none this.#tooltipAnnotations = this.#annotations.filter((a) => a.containsPoint(pointerLocation) ); } #updateCaretTooltip() { this.#tooltipAnnotations = this.#annotations.filter((a) => a.containsIndex(this.caretPosition) ); } static #createStatusContainerElement() { const container = document.createElement("p"); container.setAttribute("aria-live", "polite"); container.style.position = "absolute"; container.style.clipPath = "circle(0)"; return container; } } export class LintedMarkdownTextareaEditor extends LintedMarkdownEditor { readonly #textarea: HTMLTextAreaElement; constructor(textarea: HTMLTextAreaElement, portal: HTMLElement) { super(textarea, portal, new TextareaRangeRectCalculator(textarea)); this.#textarea = textarea; this.addEventListener(textarea, "input", this.onUpdate); } get value() { return this.#textarea.value; } get caretPosition() { return this.#textarea.selectionEnd !== this.#textarea.selectionStart ? -1 : this.#textarea.selectionStart; } } export class LintedMarkdownCodeMirrorEditor extends LintedMarkdownEditor { readonly #element: HTMLElement; readonly #mutationObserver: MutationObserver; constructor(element: HTMLElement, portal: HTMLElement) { super(element, portal, new CodeMirrorRangeRectCalculator(element)); this.#element = element; this.#mutationObserver = new MutationObserver(this.onUpdate); this.#mutationObserver.observe(element, { childList: true, subtree: true, }); } override disconnect(): void { super.disconnect(); this.#mutationObserver.disconnect(); } get value() { return Array.from(this.#element.querySelectorAll(".CodeMirror-line")) .map((line) => line.textContent) .join("\n"); } get caretPosition() { const selection = document.getSelection(); const range = selection?.getRangeAt(0); if (!range?.collapsed || selection?.rangeCount !== 1) return -1; const referenceRange = document.createRange(); referenceRange.selectNodeContents(this.#element); referenceRange.setEnd(range.startContainer, range.startOffset); return referenceRange.toString().length; } }
src/components/linted-markdown-editor.ts
iansan5653-github-markdown-a11y-extension-c6a54d0
[ { "filename": "src/components/lint-error-annotation.ts", "retrieved_chunk": " this.lineNumber = error.lineNumber;\n portal.appendChild(this.#container);\n const markdown = editor.value;\n const [line = \"\", ...prevLines] = markdown\n .split(\"\\n\")\n .slice(0, this.lineNumber)\n .reverse();\n const startCol = (error.errorRange?.[0] ?? 1) - 1;\n const length = error.errorRange?.[1] ?? line.length - startCol;\n const startIndex = prevLines.reduce(", "score": 30.814371168721053 }, { "filename": "src/components/lint-error-annotation.ts", "retrieved_chunk": " (t, l) => t + l.length + 1 /* +1 for newline char */,\n startCol\n );\n const endIndex = startIndex + length;\n this.#indexRange = new NumberRange(startIndex, endIndex);\n this.recalculatePosition();\n }\n disconnect() {\n super.disconnect();\n this.#container.remove();", "score": 21.960584224500835 }, { "filename": "src/utilities/dom/range-rect-calculator.ts", "retrieved_chunk": " offset: number\n ): [node: Node, offsetIntoNode: number] | undefined {\n let prevChars = 0;\n for (const line of lines) {\n for (const node of line) {\n const length = node.textContent?.length ?? 0;\n if (offset <= prevChars + length) return [node, offset - prevChars];\n prevChars += length;\n }\n prevChars++; // For the newline", "score": 21.78668377126822 }, { "filename": "src/utilities/format.ts", "retrieved_chunk": "export function formatList(items: string[], conjunction: string) {\n if (items.length > 2) {\n items.push(`${conjunction} ${items.pop()}`);\n return items.join(\", \");\n } else if (items.length === 2) {\n const last = items.pop();\n const secondLast = items.pop();\n return [secondLast, conjunction, last].join(\" \");\n } else {\n return items[0];", "score": 17.958952797357213 }, { "filename": "src/components/lint-error-annotation.ts", "retrieved_chunk": " const scrollVector = getWindowScrollVector();\n // The range rectangles are tight around the characters; we'd rather fill the line height if possible\n const cssLineHeight = this.#editor.getLineHeight();\n const elements: HTMLElement[] = [];\n // render an annotation element for each line separately\n for (const rect of this.#editor.getRangeRects(this.#indexRange)) {\n // suppress when out of bounds\n if (!rect.isContainedBy(editorRect)) continue;\n // The rects are viewport-relative, but the annotations are absolute positioned\n // (document-relative) so we have to add the window scroll position", "score": 15.398819766108907 } ]
typescript
annotations.map((a) => a.lineNumber.toString()), "and" )}` : "";
import { CodeMirrorRangeRectCalculator, RangeRectCalculator, TextareaRangeRectCalculator, } from "../utilities/dom/range-rect-calculator"; import {formatList} from "../utilities/format"; import {lintMarkdown} from "../utilities/lint-markdown"; import {LintErrorTooltip} from "./lint-error-tooltip"; import {LintErrorAnnotation} from "./lint-error-annotation"; import {Vector} from "../utilities/geometry/vector"; import {NumberRange} from "../utilities/geometry/number-range"; import {Component} from "./component"; export abstract class LintedMarkdownEditor extends Component { #editor: HTMLElement; #tooltip: LintErrorTooltip; #resizeObserver: ResizeObserver; #rangeRectCalculator: RangeRectCalculator; #annotationsPortal = document.createElement("div"); #statusContainer = LintedMarkdownEditor.#createStatusContainerElement(); constructor( element: HTMLElement, portal: HTMLElement, rangeRectCalculator: RangeRectCalculator ) { super(); this.#editor = element; this.#rangeRectCalculator = rangeRectCalculator; portal.append(this.#annotationsPortal, this.#statusContainer); this.addEventListener(element, "focus", this.onUpdate); this.addEventListener(element, "blur", this.#onBlur); this.addEventListener(element, "mousemove", this.#onMouseMove); this.addEventListener(element, "mouseleave", this.#onMouseLeave); // capture ancestor scroll events for nested scroll containers this.addEventListener(document, "scroll", this.#onReposition, true); // selectionchange can't be bound to the textarea so we have to use the document this.addEventListener(document, "selectionchange", this.#onSelectionChange); // annotations are document-relative so we need to observe document resize as well this.addEventListener(window, "resize", this.#onReposition); // this does mean it will run twice when the resize causes a resize of the textarea, // but we also need the resize observer for the textarea because it's user resizable this.#resizeObserver = new ResizeObserver(this.#onReposition); this.#resizeObserver.observe(element); this.#tooltip = new LintErrorTooltip(portal); } disconnect() { super.disconnect(); this.#resizeObserver.disconnect(); this.#rangeRectCalculator.disconnect(); this.#tooltip.disconnect(); this.#annotationsPortal.remove(); this.#statusContainer.remove(); } /** * Return a list of rects for the given range. If the range extends over multiple lines, * multiple rects will be returned. */ getRangeRects(characterIndexes: NumberRange) { return this.#rangeRectCalculator.getClientRects(characterIndexes); } getBoundingClientRect() { return this.#editor.getBoundingClientRect(); } getLineHeight() { const parsed = parseInt(getComputedStyle(this.#editor).lineHeight, 10); return Number.isNaN(parsed) ? undefined : parsed; } abstract get value(): string; abstract get caretPosition(): number; #_annotations: readonly LintErrorAnnotation[] = []; set #annotations(annotations: ReadonlyArray<LintErrorAnnotation>) { if (annotations === this.#_annotations) return; this.#_annotations = annotations; this.#statusContainer.textContent = annotations.length > 0 ? `${annotations.length} Markdown problem${ annotations.length > 1 ? "s" : "" } identified: see line${ annotations.length > 1 ? "s" : "" } ${
formatList( annotations.map((a) => a.lineNumber.toString()), "and" )}` : "";
} get #annotations() { return this.#_annotations; } #_tooltipAnnotations: readonly LintErrorAnnotation[] = []; set #tooltipAnnotations(annotations: LintErrorAnnotation[]) { if (annotations === this.#_tooltipAnnotations) return; this.#_tooltipAnnotations = annotations; const position = annotations[0]?.getTooltipPosition(); const errors = annotations.map(({error}) => error); if (position) this.#tooltip.show(errors, position); else this.#tooltip.hide(); } protected onUpdate = () => this.#lint(); #isOnRepositionTick = false; #onReposition = () => { if (this.#isOnRepositionTick) return; this.#isOnRepositionTick = true; requestAnimationFrame(() => { this.#recalculateAnnotationPositions(); this.#isOnRepositionTick = false; }); }; #onBlur = () => this.#clear(); #onMouseMove = (event: MouseEvent) => this.#updatePointerTooltip(new Vector(event.clientX, event.clientY)); #onMouseLeave = () => (this.#tooltipAnnotations = []); #onSelectionChange = () => { // this event only works when applied to the document but we can filter it by detecting focus if (document.activeElement === this.#editor) this.#updateCaretTooltip(); }; #clear() { // the annotations will clean themselves up too but this is slightly faster this.#annotationsPortal.replaceChildren(); for (const annotation of this.#annotations) annotation.disconnect(); this.#annotations = []; this.#tooltipAnnotations = []; } #lint() { this.#clear(); // clear() will not hide the tooltip if the mouse is over it, but if the user is typing then they are not trying to copy content this.#tooltip.hide(true); if (document.activeElement !== this.#editor) return; const errors = lintMarkdown(this.value); this.#annotations = errors.map( (error) => new LintErrorAnnotation(error, this, this.#annotationsPortal) ); } #recalculateAnnotationPositions() { for (const annotation of this.#annotations) annotation.recalculatePosition(); } #updatePointerTooltip(pointerLocation: Vector) { // can't use mouse events on annotations (the easy way) because they have pointer-events: none this.#tooltipAnnotations = this.#annotations.filter((a) => a.containsPoint(pointerLocation) ); } #updateCaretTooltip() { this.#tooltipAnnotations = this.#annotations.filter((a) => a.containsIndex(this.caretPosition) ); } static #createStatusContainerElement() { const container = document.createElement("p"); container.setAttribute("aria-live", "polite"); container.style.position = "absolute"; container.style.clipPath = "circle(0)"; return container; } } export class LintedMarkdownTextareaEditor extends LintedMarkdownEditor { readonly #textarea: HTMLTextAreaElement; constructor(textarea: HTMLTextAreaElement, portal: HTMLElement) { super(textarea, portal, new TextareaRangeRectCalculator(textarea)); this.#textarea = textarea; this.addEventListener(textarea, "input", this.onUpdate); } get value() { return this.#textarea.value; } get caretPosition() { return this.#textarea.selectionEnd !== this.#textarea.selectionStart ? -1 : this.#textarea.selectionStart; } } export class LintedMarkdownCodeMirrorEditor extends LintedMarkdownEditor { readonly #element: HTMLElement; readonly #mutationObserver: MutationObserver; constructor(element: HTMLElement, portal: HTMLElement) { super(element, portal, new CodeMirrorRangeRectCalculator(element)); this.#element = element; this.#mutationObserver = new MutationObserver(this.onUpdate); this.#mutationObserver.observe(element, { childList: true, subtree: true, }); } override disconnect(): void { super.disconnect(); this.#mutationObserver.disconnect(); } get value() { return Array.from(this.#element.querySelectorAll(".CodeMirror-line")) .map((line) => line.textContent) .join("\n"); } get caretPosition() { const selection = document.getSelection(); const range = selection?.getRangeAt(0); if (!range?.collapsed || selection?.rangeCount !== 1) return -1; const referenceRange = document.createRange(); referenceRange.selectNodeContents(this.#element); referenceRange.setEnd(range.startContainer, range.startOffset); return referenceRange.toString().length; } }
src/components/linted-markdown-editor.ts
iansan5653-github-markdown-a11y-extension-c6a54d0
[ { "filename": "src/components/lint-error-annotation.ts", "retrieved_chunk": " this.lineNumber = error.lineNumber;\n portal.appendChild(this.#container);\n const markdown = editor.value;\n const [line = \"\", ...prevLines] = markdown\n .split(\"\\n\")\n .slice(0, this.lineNumber)\n .reverse();\n const startCol = (error.errorRange?.[0] ?? 1) - 1;\n const length = error.errorRange?.[1] ?? line.length - startCol;\n const startIndex = prevLines.reduce(", "score": 25.968466797181065 }, { "filename": "src/components/lint-error-annotation.ts", "retrieved_chunk": " (t, l) => t + l.length + 1 /* +1 for newline char */,\n startCol\n );\n const endIndex = startIndex + length;\n this.#indexRange = new NumberRange(startIndex, endIndex);\n this.recalculatePosition();\n }\n disconnect() {\n super.disconnect();\n this.#container.remove();", "score": 18.300486853750694 }, { "filename": "src/utilities/dom/range-rect-calculator.ts", "retrieved_chunk": " offset: number\n ): [node: Node, offsetIntoNode: number] | undefined {\n let prevChars = 0;\n for (const line of lines) {\n for (const node of line) {\n const length = node.textContent?.length ?? 0;\n if (offset <= prevChars + length) return [node, offset - prevChars];\n prevChars += length;\n }\n prevChars++; // For the newline", "score": 15.903264830237873 }, { "filename": "src/components/lint-error-tooltip.ts", "retrieved_chunk": " element.style.flexDirection = \"column\";\n element.style.gap = \"8px\";\n return element;\n }\n static #createPrefixElement(errorCount: number) {\n const element = document.createElement(\"span\");\n element.textContent =\n errorCount === 1\n ? \"Markdown problem: \"\n : `${errorCount} Markdown problems: `;", "score": 14.024699484004458 }, { "filename": "src/utilities/format.ts", "retrieved_chunk": "export function formatList(items: string[], conjunction: string) {\n if (items.length > 2) {\n items.push(`${conjunction} ${items.pop()}`);\n return items.join(\", \");\n } else if (items.length === 2) {\n const last = items.pop();\n const secondLast = items.pop();\n return [secondLast, conjunction, last].join(\" \");\n } else {\n return items[0];", "score": 13.570030748926511 } ]
typescript
formatList( annotations.map((a) => a.lineNumber.toString()), "and" )}` : "";
import { CodeMirrorRangeRectCalculator, RangeRectCalculator, TextareaRangeRectCalculator, } from "../utilities/dom/range-rect-calculator"; import {formatList} from "../utilities/format"; import {lintMarkdown} from "../utilities/lint-markdown"; import {LintErrorTooltip} from "./lint-error-tooltip"; import {LintErrorAnnotation} from "./lint-error-annotation"; import {Vector} from "../utilities/geometry/vector"; import {NumberRange} from "../utilities/geometry/number-range"; import {Component} from "./component"; export abstract class LintedMarkdownEditor extends Component { #editor: HTMLElement; #tooltip: LintErrorTooltip; #resizeObserver: ResizeObserver; #rangeRectCalculator: RangeRectCalculator; #annotationsPortal = document.createElement("div"); #statusContainer = LintedMarkdownEditor.#createStatusContainerElement(); constructor( element: HTMLElement, portal: HTMLElement, rangeRectCalculator: RangeRectCalculator ) { super(); this.#editor = element; this.#rangeRectCalculator = rangeRectCalculator; portal.append(this.#annotationsPortal, this.#statusContainer); this.addEventListener(element, "focus", this.onUpdate); this.addEventListener(element, "blur", this.#onBlur); this.addEventListener(element, "mousemove", this.#onMouseMove); this.addEventListener(element, "mouseleave", this.#onMouseLeave); // capture ancestor scroll events for nested scroll containers this.addEventListener(document, "scroll", this.#onReposition, true); // selectionchange can't be bound to the textarea so we have to use the document this.addEventListener(document, "selectionchange", this.#onSelectionChange); // annotations are document-relative so we need to observe document resize as well this.addEventListener(window, "resize", this.#onReposition); // this does mean it will run twice when the resize causes a resize of the textarea, // but we also need the resize observer for the textarea because it's user resizable this.#resizeObserver = new ResizeObserver(this.#onReposition); this.#resizeObserver.observe(element); this.#tooltip = new LintErrorTooltip(portal); } disconnect() { super.disconnect(); this.#resizeObserver.disconnect(); this.#rangeRectCalculator.disconnect(); this.#tooltip.disconnect(); this.#annotationsPortal.remove(); this.#statusContainer.remove(); } /** * Return a list of rects for the given range. If the range extends over multiple lines, * multiple rects will be returned. */ getRangeRects(characterIndexes: NumberRange) { return this.#rangeRectCalculator.getClientRects(characterIndexes); } getBoundingClientRect() { return this.#editor.getBoundingClientRect(); } getLineHeight() { const parsed = parseInt(getComputedStyle(this.#editor).lineHeight, 10); return Number.isNaN(parsed) ? undefined : parsed; } abstract get value(): string; abstract get caretPosition(): number; #_annotations: readonly LintErrorAnnotation[] = []; set #annotations(annotations: ReadonlyArray<LintErrorAnnotation>) { if (annotations === this.#_annotations) return; this.#_annotations = annotations; this.#statusContainer.textContent = annotations.length > 0 ? `${annotations.length} Markdown problem${ annotations.length > 1 ? "s" : "" } identified: see line${ annotations.length > 1 ? "s" : "" } ${formatList( annotations.map((a) => a.lineNumber.toString()), "and" )}` : ""; } get #annotations() { return this.#_annotations; } #_tooltipAnnotations: readonly LintErrorAnnotation[] = []; set #tooltipAnnotations(annotations: LintErrorAnnotation[]) { if (annotations === this.#_tooltipAnnotations) return; this.#_tooltipAnnotations = annotations; const position
= annotations[0]?.getTooltipPosition();
const errors = annotations.map(({error}) => error); if (position) this.#tooltip.show(errors, position); else this.#tooltip.hide(); } protected onUpdate = () => this.#lint(); #isOnRepositionTick = false; #onReposition = () => { if (this.#isOnRepositionTick) return; this.#isOnRepositionTick = true; requestAnimationFrame(() => { this.#recalculateAnnotationPositions(); this.#isOnRepositionTick = false; }); }; #onBlur = () => this.#clear(); #onMouseMove = (event: MouseEvent) => this.#updatePointerTooltip(new Vector(event.clientX, event.clientY)); #onMouseLeave = () => (this.#tooltipAnnotations = []); #onSelectionChange = () => { // this event only works when applied to the document but we can filter it by detecting focus if (document.activeElement === this.#editor) this.#updateCaretTooltip(); }; #clear() { // the annotations will clean themselves up too but this is slightly faster this.#annotationsPortal.replaceChildren(); for (const annotation of this.#annotations) annotation.disconnect(); this.#annotations = []; this.#tooltipAnnotations = []; } #lint() { this.#clear(); // clear() will not hide the tooltip if the mouse is over it, but if the user is typing then they are not trying to copy content this.#tooltip.hide(true); if (document.activeElement !== this.#editor) return; const errors = lintMarkdown(this.value); this.#annotations = errors.map( (error) => new LintErrorAnnotation(error, this, this.#annotationsPortal) ); } #recalculateAnnotationPositions() { for (const annotation of this.#annotations) annotation.recalculatePosition(); } #updatePointerTooltip(pointerLocation: Vector) { // can't use mouse events on annotations (the easy way) because they have pointer-events: none this.#tooltipAnnotations = this.#annotations.filter((a) => a.containsPoint(pointerLocation) ); } #updateCaretTooltip() { this.#tooltipAnnotations = this.#annotations.filter((a) => a.containsIndex(this.caretPosition) ); } static #createStatusContainerElement() { const container = document.createElement("p"); container.setAttribute("aria-live", "polite"); container.style.position = "absolute"; container.style.clipPath = "circle(0)"; return container; } } export class LintedMarkdownTextareaEditor extends LintedMarkdownEditor { readonly #textarea: HTMLTextAreaElement; constructor(textarea: HTMLTextAreaElement, portal: HTMLElement) { super(textarea, portal, new TextareaRangeRectCalculator(textarea)); this.#textarea = textarea; this.addEventListener(textarea, "input", this.onUpdate); } get value() { return this.#textarea.value; } get caretPosition() { return this.#textarea.selectionEnd !== this.#textarea.selectionStart ? -1 : this.#textarea.selectionStart; } } export class LintedMarkdownCodeMirrorEditor extends LintedMarkdownEditor { readonly #element: HTMLElement; readonly #mutationObserver: MutationObserver; constructor(element: HTMLElement, portal: HTMLElement) { super(element, portal, new CodeMirrorRangeRectCalculator(element)); this.#element = element; this.#mutationObserver = new MutationObserver(this.onUpdate); this.#mutationObserver.observe(element, { childList: true, subtree: true, }); } override disconnect(): void { super.disconnect(); this.#mutationObserver.disconnect(); } get value() { return Array.from(this.#element.querySelectorAll(".CodeMirror-line")) .map((line) => line.textContent) .join("\n"); } get caretPosition() { const selection = document.getSelection(); const range = selection?.getRangeAt(0); if (!range?.collapsed || selection?.rangeCount !== 1) return -1; const referenceRange = document.createRange(); referenceRange.selectNodeContents(this.#element); referenceRange.setEnd(range.startContainer, range.startOffset); return referenceRange.toString().length; } }
src/components/linted-markdown-editor.ts
iansan5653-github-markdown-a11y-extension-c6a54d0
[ { "filename": "src/components/lint-error-annotation.ts", "retrieved_chunk": " const scrollVector = getWindowScrollVector();\n // The range rectangles are tight around the characters; we'd rather fill the line height if possible\n const cssLineHeight = this.#editor.getLineHeight();\n const elements: HTMLElement[] = [];\n // render an annotation element for each line separately\n for (const rect of this.#editor.getRangeRects(this.#indexRange)) {\n // suppress when out of bounds\n if (!rect.isContainedBy(editorRect)) continue;\n // The rects are viewport-relative, but the annotations are absolute positioned\n // (document-relative) so we have to add the window scroll position", "score": 20.414416018870124 }, { "filename": "src/utilities/geometry/rect.ts", "retrieved_chunk": " get left() {\n return this.x;\n }\n get right() {\n return this.left + this.width;\n }\n get top() {\n return this.y;\n }\n get bottom() {", "score": 13.164150910606129 }, { "filename": "src/utilities/geometry/rect.ts", "retrieved_chunk": " return this.top + this.height;\n }\n get xRange() {\n return new NumberRange(this.left, this.right);\n }\n get yRange() {\n return new NumberRange(this.top, this.bottom);\n }\n asVector(\n corner:", "score": 11.875577764216748 }, { "filename": "src/components/lint-error-annotation.ts", "retrieved_chunk": " }\n getTooltipPosition() {\n const domRect = this.#elements.at(-1)?.getBoundingClientRect();\n if (domRect)\n return new Rect(domRect)\n .asVector(\"bottom-left\")\n .plus(new Vector(0, 2)) // add some breathing room\n .plus(getWindowScrollVector());\n }\n containsPoint(point: Vector) {", "score": 11.010272642662137 }, { "filename": "src/utilities/dom/range-rect-calculator.ts", "retrieved_chunk": " getClientRects({start, end}: NumberRange) {\n this.#refreshText();\n const textNode = this.#div.childNodes[0];\n if (!textNode) return [];\n this.#range.setStart(textNode, start);\n this.#range.setEnd(textNode, end);\n // The div is not in the same place as the textarea so we need to subtract the div\n // position and add the textarea position\n const divPosition = new Rect(this.#div.getBoundingClientRect()).asVector();\n const textareaPosition = new Rect(", "score": 10.537839287698747 } ]
typescript
= annotations[0]?.getTooltipPosition();
import { CodeMirrorRangeRectCalculator, RangeRectCalculator, TextareaRangeRectCalculator, } from "../utilities/dom/range-rect-calculator"; import {formatList} from "../utilities/format"; import {lintMarkdown} from "../utilities/lint-markdown"; import {LintErrorTooltip} from "./lint-error-tooltip"; import {LintErrorAnnotation} from "./lint-error-annotation"; import {Vector} from "../utilities/geometry/vector"; import {NumberRange} from "../utilities/geometry/number-range"; import {Component} from "./component"; export abstract class LintedMarkdownEditor extends Component { #editor: HTMLElement; #tooltip: LintErrorTooltip; #resizeObserver: ResizeObserver; #rangeRectCalculator: RangeRectCalculator; #annotationsPortal = document.createElement("div"); #statusContainer = LintedMarkdownEditor.#createStatusContainerElement(); constructor( element: HTMLElement, portal: HTMLElement, rangeRectCalculator: RangeRectCalculator ) { super(); this.#editor = element; this.#rangeRectCalculator = rangeRectCalculator; portal.append(this.#annotationsPortal, this.#statusContainer); this.addEventListener(element, "focus", this.onUpdate); this.addEventListener(element, "blur", this.#onBlur); this.addEventListener(element, "mousemove", this.#onMouseMove); this.addEventListener(element, "mouseleave", this.#onMouseLeave); // capture ancestor scroll events for nested scroll containers this.addEventListener(document, "scroll", this.#onReposition, true); // selectionchange can't be bound to the textarea so we have to use the document this.addEventListener(document, "selectionchange", this.#onSelectionChange); // annotations are document-relative so we need to observe document resize as well this.addEventListener(window, "resize", this.#onReposition); // this does mean it will run twice when the resize causes a resize of the textarea, // but we also need the resize observer for the textarea because it's user resizable this.#resizeObserver = new ResizeObserver(this.#onReposition); this.#resizeObserver.observe(element); this.#tooltip = new LintErrorTooltip(portal); } disconnect() { super.disconnect(); this.#resizeObserver.disconnect(); this.#rangeRectCalculator.disconnect(); this.#tooltip.disconnect(); this.#annotationsPortal.remove(); this.#statusContainer.remove(); } /** * Return a list of rects for the given range. If the range extends over multiple lines, * multiple rects will be returned. */ getRangeRects(characterIndexes: NumberRange) { return this.#rangeRectCalculator.getClientRects(characterIndexes); } getBoundingClientRect() { return this.#editor.getBoundingClientRect(); } getLineHeight() { const parsed = parseInt(getComputedStyle(this.#editor).lineHeight, 10); return Number.isNaN(parsed) ? undefined : parsed; } abstract get value(): string; abstract get caretPosition(): number; #_annotations: readonly LintErrorAnnotation[] = []; set #annotations(annotations: ReadonlyArray<LintErrorAnnotation>) { if (annotations === this.#_annotations) return; this.#_annotations = annotations; this.#statusContainer.textContent = annotations.length > 0 ? `${annotations.length} Markdown problem${ annotations.length > 1 ? "s" : "" } identified: see line${ annotations.length > 1 ? "s" : "" } ${formatList( annotations.map((a) => a.lineNumber.toString()), "and" )}` : ""; } get #annotations() { return this.#_annotations; } #_tooltipAnnotations: readonly LintErrorAnnotation[] = []; set #tooltipAnnotations(annotations: LintErrorAnnotation[]) { if (annotations === this.#_tooltipAnnotations) return; this.#_tooltipAnnotations = annotations; const position = annotations[0]?.getTooltipPosition(); const errors = annotations.map(({error}) => error);
if (position) this.#tooltip.show(errors, position);
else this.#tooltip.hide(); } protected onUpdate = () => this.#lint(); #isOnRepositionTick = false; #onReposition = () => { if (this.#isOnRepositionTick) return; this.#isOnRepositionTick = true; requestAnimationFrame(() => { this.#recalculateAnnotationPositions(); this.#isOnRepositionTick = false; }); }; #onBlur = () => this.#clear(); #onMouseMove = (event: MouseEvent) => this.#updatePointerTooltip(new Vector(event.clientX, event.clientY)); #onMouseLeave = () => (this.#tooltipAnnotations = []); #onSelectionChange = () => { // this event only works when applied to the document but we can filter it by detecting focus if (document.activeElement === this.#editor) this.#updateCaretTooltip(); }; #clear() { // the annotations will clean themselves up too but this is slightly faster this.#annotationsPortal.replaceChildren(); for (const annotation of this.#annotations) annotation.disconnect(); this.#annotations = []; this.#tooltipAnnotations = []; } #lint() { this.#clear(); // clear() will not hide the tooltip if the mouse is over it, but if the user is typing then they are not trying to copy content this.#tooltip.hide(true); if (document.activeElement !== this.#editor) return; const errors = lintMarkdown(this.value); this.#annotations = errors.map( (error) => new LintErrorAnnotation(error, this, this.#annotationsPortal) ); } #recalculateAnnotationPositions() { for (const annotation of this.#annotations) annotation.recalculatePosition(); } #updatePointerTooltip(pointerLocation: Vector) { // can't use mouse events on annotations (the easy way) because they have pointer-events: none this.#tooltipAnnotations = this.#annotations.filter((a) => a.containsPoint(pointerLocation) ); } #updateCaretTooltip() { this.#tooltipAnnotations = this.#annotations.filter((a) => a.containsIndex(this.caretPosition) ); } static #createStatusContainerElement() { const container = document.createElement("p"); container.setAttribute("aria-live", "polite"); container.style.position = "absolute"; container.style.clipPath = "circle(0)"; return container; } } export class LintedMarkdownTextareaEditor extends LintedMarkdownEditor { readonly #textarea: HTMLTextAreaElement; constructor(textarea: HTMLTextAreaElement, portal: HTMLElement) { super(textarea, portal, new TextareaRangeRectCalculator(textarea)); this.#textarea = textarea; this.addEventListener(textarea, "input", this.onUpdate); } get value() { return this.#textarea.value; } get caretPosition() { return this.#textarea.selectionEnd !== this.#textarea.selectionStart ? -1 : this.#textarea.selectionStart; } } export class LintedMarkdownCodeMirrorEditor extends LintedMarkdownEditor { readonly #element: HTMLElement; readonly #mutationObserver: MutationObserver; constructor(element: HTMLElement, portal: HTMLElement) { super(element, portal, new CodeMirrorRangeRectCalculator(element)); this.#element = element; this.#mutationObserver = new MutationObserver(this.onUpdate); this.#mutationObserver.observe(element, { childList: true, subtree: true, }); } override disconnect(): void { super.disconnect(); this.#mutationObserver.disconnect(); } get value() { return Array.from(this.#element.querySelectorAll(".CodeMirror-line")) .map((line) => line.textContent) .join("\n"); } get caretPosition() { const selection = document.getSelection(); const range = selection?.getRangeAt(0); if (!range?.collapsed || selection?.rangeCount !== 1) return -1; const referenceRange = document.createRange(); referenceRange.selectNodeContents(this.#element); referenceRange.setEnd(range.startContainer, range.startOffset); return referenceRange.toString().length; } }
src/components/linted-markdown-editor.ts
iansan5653-github-markdown-a11y-extension-c6a54d0
[ { "filename": "src/components/lint-error-annotation.ts", "retrieved_chunk": " const scrollVector = getWindowScrollVector();\n // The range rectangles are tight around the characters; we'd rather fill the line height if possible\n const cssLineHeight = this.#editor.getLineHeight();\n const elements: HTMLElement[] = [];\n // render an annotation element for each line separately\n for (const rect of this.#editor.getRangeRects(this.#indexRange)) {\n // suppress when out of bounds\n if (!rect.isContainedBy(editorRect)) continue;\n // The rects are viewport-relative, but the annotations are absolute positioned\n // (document-relative) so we have to add the window scroll position", "score": 29.627321805594416 }, { "filename": "src/components/lint-error-tooltip.ts", "retrieved_chunk": " const prefix = LintErrorTooltip.#createPrefixElement(errors.length);\n // even though typed as required string, sometimes these properties are missing\n const errorNodes = errors.map((error, i) => [\n i !== 0 ? LintErrorTooltip.#createSeparatorElement() : \"\",\n LintErrorTooltip.#createDescriptionElement(error.ruleDescription),\n error.errorDetail\n ? LintErrorTooltip.#createDetailsElement(error.errorDetail)\n : \"\",\n error.justification\n ? LintErrorTooltip.#createJustificationElement(error.justification)", "score": 25.00499077207631 }, { "filename": "src/components/lint-error-tooltip.ts", "retrieved_chunk": " super();\n this.addEventListener(document, \"keydown\", (e) => this.#onGlobalKeydown(e));\n this.addEventListener(this.#tooltip, \"mouseout\", () => this.hide());\n portal.appendChild(this.#tooltip);\n }\n disconnect() {\n super.disconnect();\n this.#tooltip.remove();\n }\n show(errors: LintError[], {x, y}: Vector) {", "score": 22.451447912215617 }, { "filename": "src/components/lint-error-tooltip.ts", "retrieved_chunk": " : \"\",\n error.ruleNames?.length\n ? LintErrorTooltip.#createNameElement(\n error.ruleNames?.slice(0, 2).join(\": \")\n )\n : \"\",\n ]);\n this.#tooltip.replaceChildren(prefix, ...errorNodes.flat());\n this.#tooltip.style.top = `${y}px`;\n {", "score": 19.518837560920428 }, { "filename": "src/utilities/dom/range-rect-calculator.ts", "retrieved_chunk": " getClientRects({start, end}: NumberRange) {\n this.#refreshText();\n const textNode = this.#div.childNodes[0];\n if (!textNode) return [];\n this.#range.setStart(textNode, start);\n this.#range.setEnd(textNode, end);\n // The div is not in the same place as the textarea so we need to subtract the div\n // position and add the textarea position\n const divPosition = new Rect(this.#div.getBoundingClientRect()).asVector();\n const textareaPosition = new Rect(", "score": 19.397544646451912 } ]
typescript
if (position) this.#tooltip.show(errors, position);
import {NumberRange} from "../geometry/number-range"; import {Rect} from "../geometry/rect"; import {Vector} from "../geometry/vector"; // Note that some browsers, such as Firefox, do not concatenate properties // into their shorthand (e.g. padding-top, padding-bottom etc. -> padding), // so we have to list every single property explicitly. const propertiesToCopy = [ "direction", // RTL support "boxSizing", "width", // on Chrome and IE, exclude the scrollbar, so the mirror div wraps exactly as the textarea does "height", "overflowX", "overflowY", // copy the scrollbar for IE "borderTopWidth", "borderRightWidth", "borderBottomWidth", "borderLeftWidth", "borderStyle", "paddingTop", "paddingRight", "paddingBottom", "paddingLeft", // https://developer.mozilla.org/en-US/docs/Web/CSS/font "fontStyle", "fontVariant", "fontWeight", "fontStretch", "fontSize", "fontSizeAdjust", "lineHeight", "fontFamily", "textAlign", "textTransform", "textIndent", "textDecoration", // might not make a difference, but better be safe "letterSpacing", "wordSpacing", "tabSize", "MozTabSize" as "tabSize", // prefixed version for Firefox <= 52 ] as const satisfies ReadonlyArray<keyof CSSStyleDeclaration>; export interface RangeRectCalculator { /** * Return the viewport-relative client rects of the range of characters. If the range * has any line breaks, this will return multiple rects. Will include the start char and * exclude the end char. */ getClientRects(
{start, end}: NumberRange): Rect[];
disconnect(): void; } /** * The `Range` API doesn't work well with `textarea` elements, so this creates a duplicate * element and uses that instead. Provides a limited API wrapping around adjusted `Range` * APIs. */ export class TextareaRangeRectCalculator implements RangeRectCalculator { readonly #element: HTMLTextAreaElement; readonly #div: HTMLDivElement; readonly #mutationObserver: MutationObserver; readonly #resizeObserver: ResizeObserver; readonly #range: Range; constructor(target: HTMLTextAreaElement) { this.#element = target; // The mirror div will replicate the textarea's style const div = document.createElement("div"); this.#div = div; document.body.appendChild(div); this.#refreshStyles(); this.#mutationObserver = new MutationObserver(() => this.#refreshStyles()); this.#mutationObserver.observe(this.#element, { attributeFilter: ["style"], }); this.#resizeObserver = new ResizeObserver(() => this.#refreshStyles()); this.#resizeObserver.observe(this.#element); this.#range = document.createRange(); } /** * Return the viewport-relative client rects of the range. If the range has any line * breaks, this will return multiple rects. Will include the start char and exclude the * end char. */ getClientRects({start, end}: NumberRange) { this.#refreshText(); const textNode = this.#div.childNodes[0]; if (!textNode) return []; this.#range.setStart(textNode, start); this.#range.setEnd(textNode, end); // The div is not in the same place as the textarea so we need to subtract the div // position and add the textarea position const divPosition = new Rect(this.#div.getBoundingClientRect()).asVector(); const textareaPosition = new Rect( this.#element.getBoundingClientRect() ).asVector(); // The div is not scrollable so it does not have scroll adjustment built in const scrollOffset = new Vector( this.#element.scrollLeft, this.#element.scrollTop ); const netTranslate = divPosition .negate() .plus(textareaPosition) .minus(scrollOffset); return Array.from(this.#range.getClientRects()).map((domRect) => new Rect(domRect).translate(netTranslate) ); } disconnect() { this.#div.remove(); } #refreshStyles() { const style = this.#div.style; const textareaStyle = window.getComputedStyle(this.#element); // Default wrapping styles style.whiteSpace = "pre-wrap"; style.wordWrap = "break-word"; // Position off-screen style.position = "fixed"; style.top = "0"; style.transform = "translateY(-100%)"; const isFirefox = "mozInnerScreenX" in window; // Transfer the element's properties to the div for (const prop of propertiesToCopy) if (prop === "width" && textareaStyle.boxSizing === "border-box") { // With box-sizing: border-box we need to offset the size slightly inwards. This small difference can compound // greatly in long textareas with lots of wrapping, leading to very innacurate results if not accounted for. // Firefox will return computed styles in floats, like `0.9px`, while chromium might return `1px` for the same element. // Either way we use `parseFloat` to turn `0.9px` into `0.9` and `1px` into `1` const totalBorderWidth = parseFloat(textareaStyle.borderLeftWidth) + parseFloat(textareaStyle.borderRightWidth); // When a vertical scrollbar is present it shrinks the content. We need to account for this by using clientWidth // instead of width in everything but Firefox. When we do that we also have to account for the border width. const width = isFirefox ? parseFloat(textareaStyle.width) - totalBorderWidth : this.#element.clientWidth + totalBorderWidth; style.width = `${width}px`; } else { style[prop] = textareaStyle[prop]; } if (isFirefox) { // Firefox lies about the overflow property for textareas: https://bugzilla.mozilla.org/show_bug.cgi?id=984275 if (this.#element.scrollHeight > parseInt(textareaStyle.height)) style.overflowY = "scroll"; } else { style.overflow = "hidden"; // for Chrome to not render a scrollbar; IE keeps overflowY = 'scroll' } } #refreshText() { this.#div.textContent = this.#element instanceof HTMLInputElement ? this.#element.value.replace(/\s/g, "\u00a0") : this.#element.value; } } export class CodeMirrorRangeRectCalculator implements RangeRectCalculator { readonly #element: HTMLElement; readonly #range: Range; constructor(target: HTMLElement) { if (!target.classList.contains("CodeMirror-code")) throw new Error( "CodeMirrorRangeRectCalculator only works with CodeMirror code editors." ); this.#element = target; this.#range = document.createRange(); } getClientRects(range: NumberRange): Rect[] { const lineNodes = Array.from( this.#element.querySelectorAll(".CodeMirror-line") ); const lines = lineNodes.map((line) => CodeMirrorRangeRectCalculator.#getAllTextNodes(line) ); const start = CodeMirrorRangeRectCalculator.#getNodeAtOffset( lines, range.start ); const end = CodeMirrorRangeRectCalculator.#getNodeAtOffset( lines, range.end ); if (!start || !end) return []; this.#range.setStart(...start); this.#range.setEnd(...end); return Array.from(this.#range.getClientRects()).map( (domRect) => new Rect(domRect) ); } disconnect(): void {} static #getAllTextNodes(node: Node): Node[] { const walker = document.createTreeWalker(node, NodeFilter.SHOW_TEXT); const nodes = []; while (walker.nextNode()) nodes.push(walker.currentNode); return nodes; } /** * Get the text node containing the offset, and the relative offset into that node. * @param lines Array of nodes for each line * @param offset Offset into the entire text */ static #getNodeAtOffset( lines: Node[][], offset: number ): [node: Node, offsetIntoNode: number] | undefined { let prevChars = 0; for (const line of lines) { for (const node of line) { const length = node.textContent?.length ?? 0; if (offset <= prevChars + length) return [node, offset - prevChars]; prevChars += length; } prevChars++; // For the newline } } }
src/utilities/dom/range-rect-calculator.ts
iansan5653-github-markdown-a11y-extension-c6a54d0
[ { "filename": "src/components/linted-markdown-editor.ts", "retrieved_chunk": " this.#statusContainer.remove();\n }\n /**\n * Return a list of rects for the given range. If the range extends over multiple lines,\n * multiple rects will be returned.\n */\n getRangeRects(characterIndexes: NumberRange) {\n return this.#rangeRectCalculator.getClientRects(characterIndexes);\n }\n getBoundingClientRect() {", "score": 56.116078910645 }, { "filename": "src/components/lint-error-annotation.ts", "retrieved_chunk": " const scrollVector = getWindowScrollVector();\n // The range rectangles are tight around the characters; we'd rather fill the line height if possible\n const cssLineHeight = this.#editor.getLineHeight();\n const elements: HTMLElement[] = [];\n // render an annotation element for each line separately\n for (const rect of this.#editor.getRangeRects(this.#indexRange)) {\n // suppress when out of bounds\n if (!rect.isContainedBy(editorRect)) continue;\n // The rects are viewport-relative, but the annotations are absolute positioned\n // (document-relative) so we have to add the window scroll position", "score": 36.903049120169854 }, { "filename": "src/utilities/geometry/number-range.ts", "retrieved_chunk": "export class NumberRange {\n readonly start: number;\n readonly end: number;\n constructor(start: number, end: number) {\n this.start = Math.min(start, end);\n this.end = Math.max(start, end);\n }\n contains(\n value: number,\n mode:", "score": 29.053147513140814 }, { "filename": "src/utilities/geometry/number-range.ts", "retrieved_chunk": " case \"start-inclusive-end-exclusive\":\n return value >= this.start && value < this.end;\n case \"start-exclusive-end-inclusive\":\n return value > this.start && value <= this.end;\n }\n }\n}", "score": 25.62873032002737 }, { "filename": "src/utilities/geometry/number-range.ts", "retrieved_chunk": " | \"inclusive\"\n | \"exclusive\"\n | \"start-inclusive-end-exclusive\"\n | \"start-exclusive-end-inclusive\"\n ) {\n switch (mode) {\n case \"inclusive\":\n return value >= this.start && value <= this.end;\n case \"exclusive\":\n return value > this.start && value < this.end;", "score": 24.692685026678685 } ]
typescript
{start, end}: NumberRange): Rect[];
import { CodeMirrorRangeRectCalculator, RangeRectCalculator, TextareaRangeRectCalculator, } from "../utilities/dom/range-rect-calculator"; import {formatList} from "../utilities/format"; import {lintMarkdown} from "../utilities/lint-markdown"; import {LintErrorTooltip} from "./lint-error-tooltip"; import {LintErrorAnnotation} from "./lint-error-annotation"; import {Vector} from "../utilities/geometry/vector"; import {NumberRange} from "../utilities/geometry/number-range"; import {Component} from "./component"; export abstract class LintedMarkdownEditor extends Component { #editor: HTMLElement; #tooltip: LintErrorTooltip; #resizeObserver: ResizeObserver; #rangeRectCalculator: RangeRectCalculator; #annotationsPortal = document.createElement("div"); #statusContainer = LintedMarkdownEditor.#createStatusContainerElement(); constructor( element: HTMLElement, portal: HTMLElement, rangeRectCalculator: RangeRectCalculator ) { super(); this.#editor = element; this.#rangeRectCalculator = rangeRectCalculator; portal.append(this.#annotationsPortal, this.#statusContainer); this.addEventListener(element, "focus", this.onUpdate); this.addEventListener(element, "blur", this.#onBlur); this.addEventListener(element, "mousemove", this.#onMouseMove); this.addEventListener(element, "mouseleave", this.#onMouseLeave); // capture ancestor scroll events for nested scroll containers this.addEventListener(document, "scroll", this.#onReposition, true); // selectionchange can't be bound to the textarea so we have to use the document this.addEventListener(document, "selectionchange", this.#onSelectionChange); // annotations are document-relative so we need to observe document resize as well this.addEventListener(window, "resize", this.#onReposition); // this does mean it will run twice when the resize causes a resize of the textarea, // but we also need the resize observer for the textarea because it's user resizable this.#resizeObserver = new ResizeObserver(this.#onReposition); this.#resizeObserver.observe(element); this.#tooltip = new LintErrorTooltip(portal); } disconnect() { super.disconnect(); this.#resizeObserver.disconnect(); this.#rangeRectCalculator.disconnect(); this.#tooltip.disconnect(); this.#annotationsPortal.remove(); this.#statusContainer.remove(); } /** * Return a list of rects for the given range. If the range extends over multiple lines, * multiple rects will be returned. */ getRangeRects(characterIndexes: NumberRange) { return this.#rangeRectCalculator.getClientRects(characterIndexes); } getBoundingClientRect() { return this.#editor.getBoundingClientRect(); } getLineHeight() { const parsed = parseInt(getComputedStyle(this.#editor).lineHeight, 10); return Number.isNaN(parsed) ? undefined : parsed; } abstract get value(): string; abstract get caretPosition(): number; #_annotations: readonly LintErrorAnnotation[] = []; set #annotations(annotations: ReadonlyArray<LintErrorAnnotation>) { if (annotations === this.#_annotations) return; this.#_annotations = annotations; this.#statusContainer.textContent = annotations.length > 0 ? `${annotations.length} Markdown problem${ annotations.length > 1 ? "s" : "" } identified: see line${ annotations.length > 1 ? "s" : "" } ${formatList( annotations.map((a) => a.lineNumber.toString()), "and" )}` : ""; } get #annotations() { return this.#_annotations; } #_tooltipAnnotations: readonly LintErrorAnnotation[] = []; set #tooltipAnnotations(annotations: LintErrorAnnotation[]) { if (annotations === this.#_tooltipAnnotations) return; this.#_tooltipAnnotations = annotations; const position = annotations[0]?.getTooltipPosition();
const errors = annotations.map(({error}) => error);
if (position) this.#tooltip.show(errors, position); else this.#tooltip.hide(); } protected onUpdate = () => this.#lint(); #isOnRepositionTick = false; #onReposition = () => { if (this.#isOnRepositionTick) return; this.#isOnRepositionTick = true; requestAnimationFrame(() => { this.#recalculateAnnotationPositions(); this.#isOnRepositionTick = false; }); }; #onBlur = () => this.#clear(); #onMouseMove = (event: MouseEvent) => this.#updatePointerTooltip(new Vector(event.clientX, event.clientY)); #onMouseLeave = () => (this.#tooltipAnnotations = []); #onSelectionChange = () => { // this event only works when applied to the document but we can filter it by detecting focus if (document.activeElement === this.#editor) this.#updateCaretTooltip(); }; #clear() { // the annotations will clean themselves up too but this is slightly faster this.#annotationsPortal.replaceChildren(); for (const annotation of this.#annotations) annotation.disconnect(); this.#annotations = []; this.#tooltipAnnotations = []; } #lint() { this.#clear(); // clear() will not hide the tooltip if the mouse is over it, but if the user is typing then they are not trying to copy content this.#tooltip.hide(true); if (document.activeElement !== this.#editor) return; const errors = lintMarkdown(this.value); this.#annotations = errors.map( (error) => new LintErrorAnnotation(error, this, this.#annotationsPortal) ); } #recalculateAnnotationPositions() { for (const annotation of this.#annotations) annotation.recalculatePosition(); } #updatePointerTooltip(pointerLocation: Vector) { // can't use mouse events on annotations (the easy way) because they have pointer-events: none this.#tooltipAnnotations = this.#annotations.filter((a) => a.containsPoint(pointerLocation) ); } #updateCaretTooltip() { this.#tooltipAnnotations = this.#annotations.filter((a) => a.containsIndex(this.caretPosition) ); } static #createStatusContainerElement() { const container = document.createElement("p"); container.setAttribute("aria-live", "polite"); container.style.position = "absolute"; container.style.clipPath = "circle(0)"; return container; } } export class LintedMarkdownTextareaEditor extends LintedMarkdownEditor { readonly #textarea: HTMLTextAreaElement; constructor(textarea: HTMLTextAreaElement, portal: HTMLElement) { super(textarea, portal, new TextareaRangeRectCalculator(textarea)); this.#textarea = textarea; this.addEventListener(textarea, "input", this.onUpdate); } get value() { return this.#textarea.value; } get caretPosition() { return this.#textarea.selectionEnd !== this.#textarea.selectionStart ? -1 : this.#textarea.selectionStart; } } export class LintedMarkdownCodeMirrorEditor extends LintedMarkdownEditor { readonly #element: HTMLElement; readonly #mutationObserver: MutationObserver; constructor(element: HTMLElement, portal: HTMLElement) { super(element, portal, new CodeMirrorRangeRectCalculator(element)); this.#element = element; this.#mutationObserver = new MutationObserver(this.onUpdate); this.#mutationObserver.observe(element, { childList: true, subtree: true, }); } override disconnect(): void { super.disconnect(); this.#mutationObserver.disconnect(); } get value() { return Array.from(this.#element.querySelectorAll(".CodeMirror-line")) .map((line) => line.textContent) .join("\n"); } get caretPosition() { const selection = document.getSelection(); const range = selection?.getRangeAt(0); if (!range?.collapsed || selection?.rangeCount !== 1) return -1; const referenceRange = document.createRange(); referenceRange.selectNodeContents(this.#element); referenceRange.setEnd(range.startContainer, range.startOffset); return referenceRange.toString().length; } }
src/components/linted-markdown-editor.ts
iansan5653-github-markdown-a11y-extension-c6a54d0
[ { "filename": "src/components/lint-error-annotation.ts", "retrieved_chunk": " const scrollVector = getWindowScrollVector();\n // The range rectangles are tight around the characters; we'd rather fill the line height if possible\n const cssLineHeight = this.#editor.getLineHeight();\n const elements: HTMLElement[] = [];\n // render an annotation element for each line separately\n for (const rect of this.#editor.getRangeRects(this.#indexRange)) {\n // suppress when out of bounds\n if (!rect.isContainedBy(editorRect)) continue;\n // The rects are viewport-relative, but the annotations are absolute positioned\n // (document-relative) so we have to add the window scroll position", "score": 24.302433882366394 }, { "filename": "src/components/lint-error-tooltip.ts", "retrieved_chunk": " const prefix = LintErrorTooltip.#createPrefixElement(errors.length);\n // even though typed as required string, sometimes these properties are missing\n const errorNodes = errors.map((error, i) => [\n i !== 0 ? LintErrorTooltip.#createSeparatorElement() : \"\",\n LintErrorTooltip.#createDescriptionElement(error.ruleDescription),\n error.errorDetail\n ? LintErrorTooltip.#createDetailsElement(error.errorDetail)\n : \"\",\n error.justification\n ? LintErrorTooltip.#createJustificationElement(error.justification)", "score": 20.412904226793977 }, { "filename": "src/components/lint-error-annotation.ts", "retrieved_chunk": " this.lineNumber = error.lineNumber;\n portal.appendChild(this.#container);\n const markdown = editor.value;\n const [line = \"\", ...prevLines] = markdown\n .split(\"\\n\")\n .slice(0, this.lineNumber)\n .reverse();\n const startCol = (error.errorRange?.[0] ?? 1) - 1;\n const length = error.errorRange?.[1] ?? line.length - startCol;\n const startIndex = prevLines.reduce(", "score": 17.250460309337246 }, { "filename": "src/utilities/lint-markdown.ts", "retrieved_chunk": " handleRuleFailures: true,\n customRules: markdownlintGitHub,\n })\n .content?.map((error) => ({\n ...error,\n justification: error.ruleNames\n .map((name) => ruleJustifications[name])\n .join(\" \"),\n })) ?? [];\nexport const ruleJustifications: Partial<Record<string, string>> = {", "score": 15.703035748692848 }, { "filename": "src/components/lint-error-annotation.ts", "retrieved_chunk": " readonly #editor: LintedMarkdownEditor;\n #elements: readonly HTMLElement[] = [];\n readonly #indexRange: NumberRange;\n constructor(\n readonly error: LintError,\n editor: LintedMarkdownEditor,\n portal: HTMLElement\n ) {\n super();\n this.#editor = editor;", "score": 14.017712232276143 } ]
typescript
const errors = annotations.map(({error}) => error);
import { getInput } from '@actions/core'; import { context, getOctokit } from '@actions/github'; import { encode } from 'gpt-3-encoder'; import errorsConfig, { ErrorMessage } from '../config/errorsConfig'; import { FilenameWithPatch, Octokit, PullRequestInfo } from './types'; import concatenatePatchesToString from './utils/concatenatePatchesToString'; import divideFilesByTokenRange from './utils/divideFilesByTokenRange'; import extractFirstChangedLineFromPatch from './utils/extractFirstChangedLineFromPatch'; import getOpenAiSuggestions from './utils/getOpenAiSuggestions'; import parseOpenAISuggestions from './utils/parseOpenAISuggestions'; const MAX_TOKENS = parseInt(getInput('max_tokens'), 10) || 4096; const OPENAI_TIMEOUT = 20000; class CommentOnPullRequestService { private readonly octokitApi: Octokit; private readonly pullRequest: PullRequestInfo; constructor() { if (!process.env.GITHUB_TOKEN) { throw new Error(errorsConfig[ErrorMessage.MISSING_GITHUB_TOKEN]); } if (!process.env.OPENAI_API_KEY) { throw new Error(errorsConfig[ErrorMessage.MISSING_OPENAI_TOKEN]); } if (!context.payload.pull_request) { throw new Error(errorsConfig[ErrorMessage.NO_PULLREQUEST_IN_CONTEXT]); } this.octokitApi = getOctokit(process.env.GITHUB_TOKEN); this.pullRequest = { owner: context.repo.owner, repo: context.repo.repo, pullHeadRef: context.payload?.pull_request.head.ref, pullBaseRef: context.payload?.pull_request.base.ref, pullNumber: context.payload?.pull_request.number, }; } private async getBranchDiff() { const { owner, repo, pullBaseRef, pullHeadRef } = this.pullRequest; const { data: branchDiff } = await this.octokitApi.rest.repos.compareCommits({ owner, repo, base: pullBaseRef, head: pullHeadRef, }); return branchDiff; } private async getLastCommit() { const { owner, repo, pullNumber } = this.pullRequest; const { data: commitsList } = await this.octokitApi.rest.pulls.listCommits({ owner, repo, per_page: 50, pull_number: pullNumber, }); return commitsList[commitsList.length - 1].sha; } private async createReviewComments(files: FilenameWithPatch[]) { const suggestionsListText =
await getOpenAiSuggestions( concatenatePatchesToString(files), );
const suggestionsByFile = parseOpenAISuggestions(suggestionsListText); const { owner, repo, pullNumber } = this.pullRequest; const lastCommitId = await this.getLastCommit(); for (const file of files) { const firstChangedLine = extractFirstChangedLineFromPatch(file.patch); const suggestionForFile = suggestionsByFile.find( (suggestion) => suggestion.filename === file.filename, ); if (suggestionForFile) { try { const consoleTimeLabel = `Comment was created successfully for file: ${file.filename}`; console.time(consoleTimeLabel); await this.octokitApi.rest.pulls.createReviewComment({ owner, repo, pull_number: pullNumber, line: firstChangedLine, path: suggestionForFile.filename, body: `[ChatGPTReviewer]\n${suggestionForFile.suggestionText}`, commit_id: lastCommitId, }); console.timeEnd(consoleTimeLabel); } catch (error) { console.error( 'An error occurred while trying to add a comment', error, ); throw error; } } } } public async addCommentToPr() { const { files } = await this.getBranchDiff(); if (!files) { throw new Error( errorsConfig[ErrorMessage.NO_CHANGED_FILES_IN_PULL_REQUEST], ); } const patchesList: FilenameWithPatch[] = []; const filesTooLongToBeChecked: string[] = []; for (const file of files) { if (file.patch && encode(file.patch).length <= MAX_TOKENS / 2) { patchesList.push({ filename: file.filename, patch: file.patch, tokensUsed: encode(file.patch).length, }); } else { filesTooLongToBeChecked.push(file.filename); } } if (filesTooLongToBeChecked.length > 0) { console.log( `The changes for ${filesTooLongToBeChecked.join( ', ', )} is too long to be checked.`, ); } const listOfFilesByTokenRange = divideFilesByTokenRange( MAX_TOKENS / 2, patchesList, ); await this.createReviewComments(listOfFilesByTokenRange[0]); if (listOfFilesByTokenRange.length > 1) { let requestCount = 1; const intervalId = setInterval(async () => { if (requestCount >= listOfFilesByTokenRange.length) { clearInterval(intervalId); return; } await this.createReviewComments(listOfFilesByTokenRange[requestCount]); requestCount += 1; }, OPENAI_TIMEOUT); } } } export default CommentOnPullRequestService;
src/services/commentOnPullRequestService.ts
magnificode-ltd-chatgpt-code-reviewer-067e8ce
[ { "filename": "src/services/utils/concatenatePatchesToString.ts", "retrieved_chunk": "import { FilenameWithPatch } from '../types';\nconst concatenatePatchesToString = (files: FilenameWithPatch[]) =>\n files.map(({ filename, patch }) => `${filename}\\n${patch}\\n`).join('');\nexport default concatenatePatchesToString;", "score": 11.181355249066826 }, { "filename": "src/services/utils/divideFilesByTokenRange.ts", "retrieved_chunk": "import { FilenameWithPatch } from '../types';\nconst divideFilesByTokenRange = (\n tokensRange: number,\n files: FilenameWithPatch[],\n) => {\n const result: FilenameWithPatch[][] = [];\n let currentArray: FilenameWithPatch[] = [];\n let currentTokensUsed = 0;\n for (const file of files) {\n if (currentTokensUsed + file.tokensUsed <= tokensRange) {", "score": 7.355967028995195 }, { "filename": "src/services/types.ts", "retrieved_chunk": " pullHeadRef: string;\n pullBaseRef: string;\n pullNumber: number;\n};\nexport type { Octokit, FilenameWithPatch, PullRequestInfo };", "score": 5.063676598922134 }, { "filename": "src/services/utils/extractFirstChangedLineFromPatch.ts", "retrieved_chunk": "const extractFirstChangedLineFromPatch = (patch: string) => {\n const lineHeaderRegExp = /^@@ -\\d+,\\d+ \\+(\\d+),(\\d+) @@/;\n const lines = patch.split('\\n');\n const lineHeaderMatch = lines[0].match(lineHeaderRegExp);\n let firstChangedLine = 1;\n if (lineHeaderMatch) {\n firstChangedLine = parseInt(lineHeaderMatch[1], 10);\n }\n return firstChangedLine;\n};", "score": 4.605498423359217 }, { "filename": "src/services/utils/getOpenAiSuggestions.ts", "retrieved_chunk": "import { getInput } from '@actions/core';\nimport fetch from 'node-fetch';\nimport errorsConfig, { ErrorMessage } from '../../config/errorsConfig';\nimport promptsConfig, { Prompt } from '../../config/promptsConfig';\nconst OPENAI_MODEL = getInput('model') || 'gpt-3.5-turbo';\nconst getOpenAiSuggestions = async (patch: string): Promise<any> => {\n if (!patch) {\n throw new Error(\n errorsConfig[ErrorMessage.MISSING_PATCH_FOR_OPENAI_SUGGESTION],\n );", "score": 3.9886051098969526 } ]
typescript
await getOpenAiSuggestions( concatenatePatchesToString(files), );
import {NumberRange} from "../geometry/number-range"; import {Rect} from "../geometry/rect"; import {Vector} from "../geometry/vector"; // Note that some browsers, such as Firefox, do not concatenate properties // into their shorthand (e.g. padding-top, padding-bottom etc. -> padding), // so we have to list every single property explicitly. const propertiesToCopy = [ "direction", // RTL support "boxSizing", "width", // on Chrome and IE, exclude the scrollbar, so the mirror div wraps exactly as the textarea does "height", "overflowX", "overflowY", // copy the scrollbar for IE "borderTopWidth", "borderRightWidth", "borderBottomWidth", "borderLeftWidth", "borderStyle", "paddingTop", "paddingRight", "paddingBottom", "paddingLeft", // https://developer.mozilla.org/en-US/docs/Web/CSS/font "fontStyle", "fontVariant", "fontWeight", "fontStretch", "fontSize", "fontSizeAdjust", "lineHeight", "fontFamily", "textAlign", "textTransform", "textIndent", "textDecoration", // might not make a difference, but better be safe "letterSpacing", "wordSpacing", "tabSize", "MozTabSize" as "tabSize", // prefixed version for Firefox <= 52 ] as const satisfies ReadonlyArray<keyof CSSStyleDeclaration>; export interface RangeRectCalculator { /** * Return the viewport-relative client rects of the range of characters. If the range * has any line breaks, this will return multiple rects. Will include the start char and * exclude the end char. */ getClientRects({start, end}: NumberRange): Rect[]; disconnect(): void; } /** * The `Range` API doesn't work well with `textarea` elements, so this creates a duplicate * element and uses that instead. Provides a limited API wrapping around adjusted `Range` * APIs. */ export class TextareaRangeRectCalculator implements RangeRectCalculator { readonly #element: HTMLTextAreaElement; readonly #div: HTMLDivElement; readonly #mutationObserver: MutationObserver; readonly #resizeObserver: ResizeObserver; readonly #range: Range; constructor(target: HTMLTextAreaElement) { this.#element = target; // The mirror div will replicate the textarea's style const div = document.createElement("div"); this.#div = div; document.body.appendChild(div); this.#refreshStyles(); this.#mutationObserver = new MutationObserver(() => this.#refreshStyles()); this.#mutationObserver.observe(this.#element, { attributeFilter: ["style"], }); this.#resizeObserver = new ResizeObserver(() => this.#refreshStyles()); this.#resizeObserver.observe(this.#element); this.#range = document.createRange(); } /** * Return the viewport-relative client rects of the range. If the range has any line * breaks, this will return multiple rects. Will include the start char and exclude the * end char. */ getClientRects({start, end}: NumberRange) { this.#refreshText(); const textNode = this.#div.childNodes[0]; if (!textNode) return []; this.#range.setStart(textNode, start); this.#range.setEnd(textNode, end); // The div is not in the same place as the textarea so we need to subtract the div // position and add the textarea position const divPosition
= new Rect(this.#div.getBoundingClientRect()).asVector();
const textareaPosition = new Rect( this.#element.getBoundingClientRect() ).asVector(); // The div is not scrollable so it does not have scroll adjustment built in const scrollOffset = new Vector( this.#element.scrollLeft, this.#element.scrollTop ); const netTranslate = divPosition .negate() .plus(textareaPosition) .minus(scrollOffset); return Array.from(this.#range.getClientRects()).map((domRect) => new Rect(domRect).translate(netTranslate) ); } disconnect() { this.#div.remove(); } #refreshStyles() { const style = this.#div.style; const textareaStyle = window.getComputedStyle(this.#element); // Default wrapping styles style.whiteSpace = "pre-wrap"; style.wordWrap = "break-word"; // Position off-screen style.position = "fixed"; style.top = "0"; style.transform = "translateY(-100%)"; const isFirefox = "mozInnerScreenX" in window; // Transfer the element's properties to the div for (const prop of propertiesToCopy) if (prop === "width" && textareaStyle.boxSizing === "border-box") { // With box-sizing: border-box we need to offset the size slightly inwards. This small difference can compound // greatly in long textareas with lots of wrapping, leading to very innacurate results if not accounted for. // Firefox will return computed styles in floats, like `0.9px`, while chromium might return `1px` for the same element. // Either way we use `parseFloat` to turn `0.9px` into `0.9` and `1px` into `1` const totalBorderWidth = parseFloat(textareaStyle.borderLeftWidth) + parseFloat(textareaStyle.borderRightWidth); // When a vertical scrollbar is present it shrinks the content. We need to account for this by using clientWidth // instead of width in everything but Firefox. When we do that we also have to account for the border width. const width = isFirefox ? parseFloat(textareaStyle.width) - totalBorderWidth : this.#element.clientWidth + totalBorderWidth; style.width = `${width}px`; } else { style[prop] = textareaStyle[prop]; } if (isFirefox) { // Firefox lies about the overflow property for textareas: https://bugzilla.mozilla.org/show_bug.cgi?id=984275 if (this.#element.scrollHeight > parseInt(textareaStyle.height)) style.overflowY = "scroll"; } else { style.overflow = "hidden"; // for Chrome to not render a scrollbar; IE keeps overflowY = 'scroll' } } #refreshText() { this.#div.textContent = this.#element instanceof HTMLInputElement ? this.#element.value.replace(/\s/g, "\u00a0") : this.#element.value; } } export class CodeMirrorRangeRectCalculator implements RangeRectCalculator { readonly #element: HTMLElement; readonly #range: Range; constructor(target: HTMLElement) { if (!target.classList.contains("CodeMirror-code")) throw new Error( "CodeMirrorRangeRectCalculator only works with CodeMirror code editors." ); this.#element = target; this.#range = document.createRange(); } getClientRects(range: NumberRange): Rect[] { const lineNodes = Array.from( this.#element.querySelectorAll(".CodeMirror-line") ); const lines = lineNodes.map((line) => CodeMirrorRangeRectCalculator.#getAllTextNodes(line) ); const start = CodeMirrorRangeRectCalculator.#getNodeAtOffset( lines, range.start ); const end = CodeMirrorRangeRectCalculator.#getNodeAtOffset( lines, range.end ); if (!start || !end) return []; this.#range.setStart(...start); this.#range.setEnd(...end); return Array.from(this.#range.getClientRects()).map( (domRect) => new Rect(domRect) ); } disconnect(): void {} static #getAllTextNodes(node: Node): Node[] { const walker = document.createTreeWalker(node, NodeFilter.SHOW_TEXT); const nodes = []; while (walker.nextNode()) nodes.push(walker.currentNode); return nodes; } /** * Get the text node containing the offset, and the relative offset into that node. * @param lines Array of nodes for each line * @param offset Offset into the entire text */ static #getNodeAtOffset( lines: Node[][], offset: number ): [node: Node, offsetIntoNode: number] | undefined { let prevChars = 0; for (const line of lines) { for (const node of line) { const length = node.textContent?.length ?? 0; if (offset <= prevChars + length) return [node, offset - prevChars]; prevChars += length; } prevChars++; // For the newline } } }
src/utilities/dom/range-rect-calculator.ts
iansan5653-github-markdown-a11y-extension-c6a54d0
[ { "filename": "src/components/linted-markdown-editor.ts", "retrieved_chunk": " this.addEventListener(element, \"mousemove\", this.#onMouseMove);\n this.addEventListener(element, \"mouseleave\", this.#onMouseLeave);\n // capture ancestor scroll events for nested scroll containers\n this.addEventListener(document, \"scroll\", this.#onReposition, true);\n // selectionchange can't be bound to the textarea so we have to use the document\n this.addEventListener(document, \"selectionchange\", this.#onSelectionChange);\n // annotations are document-relative so we need to observe document resize as well\n this.addEventListener(window, \"resize\", this.#onReposition);\n // this does mean it will run twice when the resize causes a resize of the textarea,\n // but we also need the resize observer for the textarea because it's user resizable", "score": 36.8761919206665 }, { "filename": "src/components/lint-error-annotation.ts", "retrieved_chunk": " const scrollVector = getWindowScrollVector();\n // The range rectangles are tight around the characters; we'd rather fill the line height if possible\n const cssLineHeight = this.#editor.getLineHeight();\n const elements: HTMLElement[] = [];\n // render an annotation element for each line separately\n for (const rect of this.#editor.getRangeRects(this.#indexRange)) {\n // suppress when out of bounds\n if (!rect.isContainedBy(editorRect)) continue;\n // The rects are viewport-relative, but the annotations are absolute positioned\n // (document-relative) so we have to add the window scroll position", "score": 34.043600996019194 }, { "filename": "src/utilities/geometry/number-range.ts", "retrieved_chunk": "export class NumberRange {\n readonly start: number;\n readonly end: number;\n constructor(start: number, end: number) {\n this.start = Math.min(start, end);\n this.end = Math.max(start, end);\n }\n contains(\n value: number,\n mode:", "score": 32.57491672824066 }, { "filename": "src/utilities/geometry/number-range.ts", "retrieved_chunk": " case \"start-inclusive-end-exclusive\":\n return value >= this.start && value < this.end;\n case \"start-exclusive-end-inclusive\":\n return value > this.start && value <= this.end;\n }\n }\n}", "score": 32.22553784999146 }, { "filename": "src/components/linted-markdown-editor.ts", "retrieved_chunk": " this.#statusContainer.remove();\n }\n /**\n * Return a list of rects for the given range. If the range extends over multiple lines,\n * multiple rects will be returned.\n */\n getRangeRects(characterIndexes: NumberRange) {\n return this.#rangeRectCalculator.getClientRects(characterIndexes);\n }\n getBoundingClientRect() {", "score": 31.39799592421228 } ]
typescript
= new Rect(this.#div.getBoundingClientRect()).asVector();
import { getInput } from '@actions/core'; import { context, getOctokit } from '@actions/github'; import { encode } from 'gpt-3-encoder'; import errorsConfig, { ErrorMessage } from '../config/errorsConfig'; import { FilenameWithPatch, Octokit, PullRequestInfo } from './types'; import concatenatePatchesToString from './utils/concatenatePatchesToString'; import divideFilesByTokenRange from './utils/divideFilesByTokenRange'; import extractFirstChangedLineFromPatch from './utils/extractFirstChangedLineFromPatch'; import getOpenAiSuggestions from './utils/getOpenAiSuggestions'; import parseOpenAISuggestions from './utils/parseOpenAISuggestions'; const MAX_TOKENS = parseInt(getInput('max_tokens'), 10) || 4096; const OPENAI_TIMEOUT = 20000; class CommentOnPullRequestService { private readonly octokitApi: Octokit; private readonly pullRequest: PullRequestInfo; constructor() { if (!process.env.GITHUB_TOKEN) { throw new Error(errorsConfig[ErrorMessage.MISSING_GITHUB_TOKEN]); } if (!process.env.OPENAI_API_KEY) { throw new Error(errorsConfig[ErrorMessage.MISSING_OPENAI_TOKEN]); } if (!context.payload.pull_request) { throw new Error(errorsConfig[ErrorMessage.NO_PULLREQUEST_IN_CONTEXT]); } this.octokitApi = getOctokit(process.env.GITHUB_TOKEN); this.pullRequest = { owner: context.repo.owner, repo: context.repo.repo, pullHeadRef: context.payload?.pull_request.head.ref, pullBaseRef: context.payload?.pull_request.base.ref, pullNumber: context.payload?.pull_request.number, }; } private async getBranchDiff() { const { owner, repo, pullBaseRef, pullHeadRef } = this.pullRequest; const { data: branchDiff } = await this.octokitApi.rest.repos.compareCommits({ owner, repo, base: pullBaseRef, head: pullHeadRef, }); return branchDiff; } private async getLastCommit() { const { owner, repo, pullNumber } = this.pullRequest; const { data: commitsList } = await this.octokitApi.rest.pulls.listCommits({ owner, repo, per_page: 50, pull_number: pullNumber, }); return commitsList[commitsList.length - 1].sha; } private async createReviewComments(files: FilenameWithPatch[]) { const suggestionsListText = await getOpenAiSuggestions( concatenatePatchesToString(files), ); const suggestionsByFile = parseOpenAISuggestions(suggestionsListText); const { owner, repo, pullNumber } = this.pullRequest; const lastCommitId = await this.getLastCommit(); for (const file of files) {
const firstChangedLine = extractFirstChangedLineFromPatch(file.patch);
const suggestionForFile = suggestionsByFile.find( (suggestion) => suggestion.filename === file.filename, ); if (suggestionForFile) { try { const consoleTimeLabel = `Comment was created successfully for file: ${file.filename}`; console.time(consoleTimeLabel); await this.octokitApi.rest.pulls.createReviewComment({ owner, repo, pull_number: pullNumber, line: firstChangedLine, path: suggestionForFile.filename, body: `[ChatGPTReviewer]\n${suggestionForFile.suggestionText}`, commit_id: lastCommitId, }); console.timeEnd(consoleTimeLabel); } catch (error) { console.error( 'An error occurred while trying to add a comment', error, ); throw error; } } } } public async addCommentToPr() { const { files } = await this.getBranchDiff(); if (!files) { throw new Error( errorsConfig[ErrorMessage.NO_CHANGED_FILES_IN_PULL_REQUEST], ); } const patchesList: FilenameWithPatch[] = []; const filesTooLongToBeChecked: string[] = []; for (const file of files) { if (file.patch && encode(file.patch).length <= MAX_TOKENS / 2) { patchesList.push({ filename: file.filename, patch: file.patch, tokensUsed: encode(file.patch).length, }); } else { filesTooLongToBeChecked.push(file.filename); } } if (filesTooLongToBeChecked.length > 0) { console.log( `The changes for ${filesTooLongToBeChecked.join( ', ', )} is too long to be checked.`, ); } const listOfFilesByTokenRange = divideFilesByTokenRange( MAX_TOKENS / 2, patchesList, ); await this.createReviewComments(listOfFilesByTokenRange[0]); if (listOfFilesByTokenRange.length > 1) { let requestCount = 1; const intervalId = setInterval(async () => { if (requestCount >= listOfFilesByTokenRange.length) { clearInterval(intervalId); return; } await this.createReviewComments(listOfFilesByTokenRange[requestCount]); requestCount += 1; }, OPENAI_TIMEOUT); } } } export default CommentOnPullRequestService;
src/services/commentOnPullRequestService.ts
magnificode-ltd-chatgpt-code-reviewer-067e8ce
[ { "filename": "src/services/utils/divideFilesByTokenRange.ts", "retrieved_chunk": "import { FilenameWithPatch } from '../types';\nconst divideFilesByTokenRange = (\n tokensRange: number,\n files: FilenameWithPatch[],\n) => {\n const result: FilenameWithPatch[][] = [];\n let currentArray: FilenameWithPatch[] = [];\n let currentTokensUsed = 0;\n for (const file of files) {\n if (currentTokensUsed + file.tokensUsed <= tokensRange) {", "score": 21.524208275323698 }, { "filename": "src/services/utils/concatenatePatchesToString.ts", "retrieved_chunk": "import { FilenameWithPatch } from '../types';\nconst concatenatePatchesToString = (files: FilenameWithPatch[]) =>\n files.map(({ filename, patch }) => `${filename}\\n${patch}\\n`).join('');\nexport default concatenatePatchesToString;", "score": 17.4182679375729 }, { "filename": "src/services/utils/extractFirstChangedLineFromPatch.ts", "retrieved_chunk": "const extractFirstChangedLineFromPatch = (patch: string) => {\n const lineHeaderRegExp = /^@@ -\\d+,\\d+ \\+(\\d+),(\\d+) @@/;\n const lines = patch.split('\\n');\n const lineHeaderMatch = lines[0].match(lineHeaderRegExp);\n let firstChangedLine = 1;\n if (lineHeaderMatch) {\n firstChangedLine = parseInt(lineHeaderMatch[1], 10);\n }\n return firstChangedLine;\n};", "score": 11.993880289587029 }, { "filename": "src/services/utils/parseOpenAISuggestions.ts", "retrieved_chunk": "const parseOpenAISuggestions = (suggestionsText: string) => {\n const regex = /@@(.+?)@@\\n([\\s\\S]*?)(?=\\n@@|$)/g;\n const suggestionMatches = suggestionsText.matchAll(regex);\n const suggestions = [];\n for (const match of suggestionMatches) {\n const filename = match[1].trim();\n const suggestionText = match[2].trim();\n suggestions.push({ filename, suggestionText });\n }\n return suggestions;", "score": 10.789064213671946 }, { "filename": "src/services/utils/getOpenAiSuggestions.ts", "retrieved_chunk": " messages: [\n { role: 'system', content: promptsConfig[Prompt.SYSTEM_PROMPT] },\n { role: 'user', content: patch },\n ],\n }),\n });\n if (!response.ok) throw new Error('Failed to post data.');\n const responseJson = (await response.json()) as any;\n const openAiSuggestion =\n responseJson.choices.shift()?.message?.content || '';", "score": 8.03415033541898 } ]
typescript
const firstChangedLine = extractFirstChangedLineFromPatch(file.patch);
import { getInput } from '@actions/core'; import { context, getOctokit } from '@actions/github'; import { encode } from 'gpt-3-encoder'; import errorsConfig, { ErrorMessage } from '../config/errorsConfig'; import { FilenameWithPatch, Octokit, PullRequestInfo } from './types'; import concatenatePatchesToString from './utils/concatenatePatchesToString'; import divideFilesByTokenRange from './utils/divideFilesByTokenRange'; import extractFirstChangedLineFromPatch from './utils/extractFirstChangedLineFromPatch'; import getOpenAiSuggestions from './utils/getOpenAiSuggestions'; import parseOpenAISuggestions from './utils/parseOpenAISuggestions'; const MAX_TOKENS = parseInt(getInput('max_tokens'), 10) || 4096; const OPENAI_TIMEOUT = 20000; class CommentOnPullRequestService { private readonly octokitApi: Octokit; private readonly pullRequest: PullRequestInfo; constructor() { if (!process.env.GITHUB_TOKEN) { throw new Error(errorsConfig[ErrorMessage.MISSING_GITHUB_TOKEN]); } if (!process.env.OPENAI_API_KEY) { throw new Error(errorsConfig[ErrorMessage.MISSING_OPENAI_TOKEN]); } if (!context.payload.pull_request) { throw new Error(errorsConfig[ErrorMessage.NO_PULLREQUEST_IN_CONTEXT]); } this.octokitApi = getOctokit(process.env.GITHUB_TOKEN); this.pullRequest = { owner: context.repo.owner, repo: context.repo.repo, pullHeadRef: context.payload?.pull_request.head.ref, pullBaseRef: context.payload?.pull_request.base.ref, pullNumber: context.payload?.pull_request.number, }; } private async getBranchDiff() { const { owner, repo, pullBaseRef, pullHeadRef } = this.pullRequest; const { data: branchDiff } = await this.octokitApi.rest.repos.compareCommits({ owner, repo, base: pullBaseRef, head: pullHeadRef, }); return branchDiff; } private async getLastCommit() { const { owner, repo, pullNumber } = this.pullRequest; const { data: commitsList } = await this.octokitApi.rest.pulls.listCommits({ owner, repo, per_page: 50, pull_number: pullNumber, }); return commitsList[commitsList.length - 1].sha; } private
async createReviewComments(files: FilenameWithPatch[]) {
const suggestionsListText = await getOpenAiSuggestions( concatenatePatchesToString(files), ); const suggestionsByFile = parseOpenAISuggestions(suggestionsListText); const { owner, repo, pullNumber } = this.pullRequest; const lastCommitId = await this.getLastCommit(); for (const file of files) { const firstChangedLine = extractFirstChangedLineFromPatch(file.patch); const suggestionForFile = suggestionsByFile.find( (suggestion) => suggestion.filename === file.filename, ); if (suggestionForFile) { try { const consoleTimeLabel = `Comment was created successfully for file: ${file.filename}`; console.time(consoleTimeLabel); await this.octokitApi.rest.pulls.createReviewComment({ owner, repo, pull_number: pullNumber, line: firstChangedLine, path: suggestionForFile.filename, body: `[ChatGPTReviewer]\n${suggestionForFile.suggestionText}`, commit_id: lastCommitId, }); console.timeEnd(consoleTimeLabel); } catch (error) { console.error( 'An error occurred while trying to add a comment', error, ); throw error; } } } } public async addCommentToPr() { const { files } = await this.getBranchDiff(); if (!files) { throw new Error( errorsConfig[ErrorMessage.NO_CHANGED_FILES_IN_PULL_REQUEST], ); } const patchesList: FilenameWithPatch[] = []; const filesTooLongToBeChecked: string[] = []; for (const file of files) { if (file.patch && encode(file.patch).length <= MAX_TOKENS / 2) { patchesList.push({ filename: file.filename, patch: file.patch, tokensUsed: encode(file.patch).length, }); } else { filesTooLongToBeChecked.push(file.filename); } } if (filesTooLongToBeChecked.length > 0) { console.log( `The changes for ${filesTooLongToBeChecked.join( ', ', )} is too long to be checked.`, ); } const listOfFilesByTokenRange = divideFilesByTokenRange( MAX_TOKENS / 2, patchesList, ); await this.createReviewComments(listOfFilesByTokenRange[0]); if (listOfFilesByTokenRange.length > 1) { let requestCount = 1; const intervalId = setInterval(async () => { if (requestCount >= listOfFilesByTokenRange.length) { clearInterval(intervalId); return; } await this.createReviewComments(listOfFilesByTokenRange[requestCount]); requestCount += 1; }, OPENAI_TIMEOUT); } } } export default CommentOnPullRequestService;
src/services/commentOnPullRequestService.ts
magnificode-ltd-chatgpt-code-reviewer-067e8ce
[ { "filename": "src/services/types.ts", "retrieved_chunk": "import { getOctokit } from '@actions/github';\ntype Octokit = ReturnType<typeof getOctokit>;\ntype FilenameWithPatch = {\n filename: string;\n patch: string;\n tokensUsed: number;\n};\ntype PullRequestInfo = {\n owner: string;\n repo: string;", "score": 6.4858852889494045 }, { "filename": "src/services/utils/divideFilesByTokenRange.ts", "retrieved_chunk": "import { FilenameWithPatch } from '../types';\nconst divideFilesByTokenRange = (\n tokensRange: number,\n files: FilenameWithPatch[],\n) => {\n const result: FilenameWithPatch[][] = [];\n let currentArray: FilenameWithPatch[] = [];\n let currentTokensUsed = 0;\n for (const file of files) {\n if (currentTokensUsed + file.tokensUsed <= tokensRange) {", "score": 5.220044765541403 }, { "filename": "src/services/types.ts", "retrieved_chunk": " pullHeadRef: string;\n pullBaseRef: string;\n pullNumber: number;\n};\nexport type { Octokit, FilenameWithPatch, PullRequestInfo };", "score": 5.063676598922134 }, { "filename": "src/services/utils/concatenatePatchesToString.ts", "retrieved_chunk": "import { FilenameWithPatch } from '../types';\nconst concatenatePatchesToString = (files: FilenameWithPatch[]) =>\n files.map(({ filename, patch }) => `${filename}\\n${patch}\\n`).join('');\nexport default concatenatePatchesToString;", "score": 4.912187359092384 }, { "filename": "src/services/utils/extractFirstChangedLineFromPatch.ts", "retrieved_chunk": "const extractFirstChangedLineFromPatch = (patch: string) => {\n const lineHeaderRegExp = /^@@ -\\d+,\\d+ \\+(\\d+),(\\d+) @@/;\n const lines = patch.split('\\n');\n const lineHeaderMatch = lines[0].match(lineHeaderRegExp);\n let firstChangedLine = 1;\n if (lineHeaderMatch) {\n firstChangedLine = parseInt(lineHeaderMatch[1], 10);\n }\n return firstChangedLine;\n};", "score": 4.605498423359217 } ]
typescript
async createReviewComments(files: FilenameWithPatch[]) {
import { getInput } from '@actions/core'; import { context, getOctokit } from '@actions/github'; import { encode } from 'gpt-3-encoder'; import errorsConfig, { ErrorMessage } from '../config/errorsConfig'; import { FilenameWithPatch, Octokit, PullRequestInfo } from './types'; import concatenatePatchesToString from './utils/concatenatePatchesToString'; import divideFilesByTokenRange from './utils/divideFilesByTokenRange'; import extractFirstChangedLineFromPatch from './utils/extractFirstChangedLineFromPatch'; import getOpenAiSuggestions from './utils/getOpenAiSuggestions'; import parseOpenAISuggestions from './utils/parseOpenAISuggestions'; const MAX_TOKENS = parseInt(getInput('max_tokens'), 10) || 4096; const OPENAI_TIMEOUT = 20000; class CommentOnPullRequestService { private readonly octokitApi: Octokit; private readonly pullRequest: PullRequestInfo; constructor() { if (!process.env.GITHUB_TOKEN) { throw new Error(errorsConfig[ErrorMessage.MISSING_GITHUB_TOKEN]); } if (!process.env.OPENAI_API_KEY) { throw new Error(errorsConfig[ErrorMessage.MISSING_OPENAI_TOKEN]); } if (!context.payload.pull_request) { throw new Error(errorsConfig[ErrorMessage.NO_PULLREQUEST_IN_CONTEXT]); } this.octokitApi = getOctokit(process.env.GITHUB_TOKEN); this.pullRequest = { owner: context.repo.owner, repo: context.repo.repo, pullHeadRef: context.payload?.pull_request.head.ref, pullBaseRef: context.payload?.pull_request.base.ref, pullNumber: context.payload?.pull_request.number, }; } private async getBranchDiff() { const { owner, repo, pullBaseRef, pullHeadRef } = this.pullRequest; const { data: branchDiff } = await this.octokitApi.rest.repos.compareCommits({ owner, repo, base: pullBaseRef, head: pullHeadRef, }); return branchDiff; } private async getLastCommit() { const { owner, repo, pullNumber } = this.pullRequest; const { data: commitsList } = await this.octokitApi.rest.pulls.listCommits({ owner, repo, per_page: 50, pull_number: pullNumber, }); return commitsList[commitsList.length - 1].sha; } private async createReviewComments(files: FilenameWithPatch[]) { const suggestionsListText = await getOpenAiSuggestions( concatenatePatchesToString(files), );
const suggestionsByFile = parseOpenAISuggestions(suggestionsListText);
const { owner, repo, pullNumber } = this.pullRequest; const lastCommitId = await this.getLastCommit(); for (const file of files) { const firstChangedLine = extractFirstChangedLineFromPatch(file.patch); const suggestionForFile = suggestionsByFile.find( (suggestion) => suggestion.filename === file.filename, ); if (suggestionForFile) { try { const consoleTimeLabel = `Comment was created successfully for file: ${file.filename}`; console.time(consoleTimeLabel); await this.octokitApi.rest.pulls.createReviewComment({ owner, repo, pull_number: pullNumber, line: firstChangedLine, path: suggestionForFile.filename, body: `[ChatGPTReviewer]\n${suggestionForFile.suggestionText}`, commit_id: lastCommitId, }); console.timeEnd(consoleTimeLabel); } catch (error) { console.error( 'An error occurred while trying to add a comment', error, ); throw error; } } } } public async addCommentToPr() { const { files } = await this.getBranchDiff(); if (!files) { throw new Error( errorsConfig[ErrorMessage.NO_CHANGED_FILES_IN_PULL_REQUEST], ); } const patchesList: FilenameWithPatch[] = []; const filesTooLongToBeChecked: string[] = []; for (const file of files) { if (file.patch && encode(file.patch).length <= MAX_TOKENS / 2) { patchesList.push({ filename: file.filename, patch: file.patch, tokensUsed: encode(file.patch).length, }); } else { filesTooLongToBeChecked.push(file.filename); } } if (filesTooLongToBeChecked.length > 0) { console.log( `The changes for ${filesTooLongToBeChecked.join( ', ', )} is too long to be checked.`, ); } const listOfFilesByTokenRange = divideFilesByTokenRange( MAX_TOKENS / 2, patchesList, ); await this.createReviewComments(listOfFilesByTokenRange[0]); if (listOfFilesByTokenRange.length > 1) { let requestCount = 1; const intervalId = setInterval(async () => { if (requestCount >= listOfFilesByTokenRange.length) { clearInterval(intervalId); return; } await this.createReviewComments(listOfFilesByTokenRange[requestCount]); requestCount += 1; }, OPENAI_TIMEOUT); } } } export default CommentOnPullRequestService;
src/services/commentOnPullRequestService.ts
magnificode-ltd-chatgpt-code-reviewer-067e8ce
[ { "filename": "src/services/utils/concatenatePatchesToString.ts", "retrieved_chunk": "import { FilenameWithPatch } from '../types';\nconst concatenatePatchesToString = (files: FilenameWithPatch[]) =>\n files.map(({ filename, patch }) => `${filename}\\n${patch}\\n`).join('');\nexport default concatenatePatchesToString;", "score": 11.792571627235624 }, { "filename": "src/services/utils/divideFilesByTokenRange.ts", "retrieved_chunk": "import { FilenameWithPatch } from '../types';\nconst divideFilesByTokenRange = (\n tokensRange: number,\n files: FilenameWithPatch[],\n) => {\n const result: FilenameWithPatch[][] = [];\n let currentArray: FilenameWithPatch[] = [];\n let currentTokensUsed = 0;\n for (const file of files) {\n if (currentTokensUsed + file.tokensUsed <= tokensRange) {", "score": 8.243278032816566 }, { "filename": "src/services/utils/parseOpenAISuggestions.ts", "retrieved_chunk": "const parseOpenAISuggestions = (suggestionsText: string) => {\n const regex = /@@(.+?)@@\\n([\\s\\S]*?)(?=\\n@@|$)/g;\n const suggestionMatches = suggestionsText.matchAll(regex);\n const suggestions = [];\n for (const match of suggestionMatches) {\n const filename = match[1].trim();\n const suggestionText = match[2].trim();\n suggestions.push({ filename, suggestionText });\n }\n return suggestions;", "score": 6.302023054967347 }, { "filename": "src/services/utils/extractFirstChangedLineFromPatch.ts", "retrieved_chunk": "const extractFirstChangedLineFromPatch = (patch: string) => {\n const lineHeaderRegExp = /^@@ -\\d+,\\d+ \\+(\\d+),(\\d+) @@/;\n const lines = patch.split('\\n');\n const lineHeaderMatch = lines[0].match(lineHeaderRegExp);\n let firstChangedLine = 1;\n if (lineHeaderMatch) {\n firstChangedLine = parseInt(lineHeaderMatch[1], 10);\n }\n return firstChangedLine;\n};", "score": 5.549415017316665 }, { "filename": "src/services/types.ts", "retrieved_chunk": " pullHeadRef: string;\n pullBaseRef: string;\n pullNumber: number;\n};\nexport type { Octokit, FilenameWithPatch, PullRequestInfo };", "score": 5.063676598922134 } ]
typescript
const suggestionsByFile = parseOpenAISuggestions(suggestionsListText);
import { getInput } from '@actions/core'; import { context, getOctokit } from '@actions/github'; import { encode } from 'gpt-3-encoder'; import errorsConfig, { ErrorMessage } from '../config/errorsConfig'; import { FilenameWithPatch, Octokit, PullRequestInfo } from './types'; import concatenatePatchesToString from './utils/concatenatePatchesToString'; import divideFilesByTokenRange from './utils/divideFilesByTokenRange'; import extractFirstChangedLineFromPatch from './utils/extractFirstChangedLineFromPatch'; import getOpenAiSuggestions from './utils/getOpenAiSuggestions'; import parseOpenAISuggestions from './utils/parseOpenAISuggestions'; const MAX_TOKENS = parseInt(getInput('max_tokens'), 10) || 4096; const OPENAI_TIMEOUT = 20000; class CommentOnPullRequestService { private readonly octokitApi: Octokit; private readonly pullRequest: PullRequestInfo; constructor() { if (!process.env.GITHUB_TOKEN) { throw new Error(errorsConfig[ErrorMessage.MISSING_GITHUB_TOKEN]); } if (!process.env.OPENAI_API_KEY) { throw new Error(errorsConfig[ErrorMessage.MISSING_OPENAI_TOKEN]); } if (!context.payload.pull_request) { throw new Error(errorsConfig[ErrorMessage.NO_PULLREQUEST_IN_CONTEXT]); } this.octokitApi = getOctokit(process.env.GITHUB_TOKEN); this.pullRequest = { owner: context.repo.owner, repo: context.repo.repo, pullHeadRef: context.payload?.pull_request.head.ref, pullBaseRef: context.payload?.pull_request.base.ref, pullNumber: context.payload?.pull_request.number, }; } private async getBranchDiff() { const { owner, repo, pullBaseRef, pullHeadRef } = this.pullRequest; const { data: branchDiff } = await this.octokitApi.rest.repos.compareCommits({ owner, repo, base: pullBaseRef, head: pullHeadRef, }); return branchDiff; } private async getLastCommit() { const { owner, repo, pullNumber } = this.pullRequest; const { data: commitsList } = await this.octokitApi.rest.pulls.listCommits({ owner, repo, per_page: 50, pull_number: pullNumber, }); return commitsList[commitsList.length - 1].sha; } private async createReviewComments(files: FilenameWithPatch[]) { const suggestionsListText = await getOpenAiSuggestions( concatenatePatchesToString(files), ); const suggestionsByFile = parseOpenAISuggestions(suggestionsListText); const { owner, repo, pullNumber } = this.pullRequest; const lastCommitId = await this.getLastCommit(); for (const file of files) { const firstChangedLine = extractFirstChangedLineFromPatch(file.patch); const suggestionForFile = suggestionsByFile.find( (
suggestion) => suggestion.filename === file.filename, );
if (suggestionForFile) { try { const consoleTimeLabel = `Comment was created successfully for file: ${file.filename}`; console.time(consoleTimeLabel); await this.octokitApi.rest.pulls.createReviewComment({ owner, repo, pull_number: pullNumber, line: firstChangedLine, path: suggestionForFile.filename, body: `[ChatGPTReviewer]\n${suggestionForFile.suggestionText}`, commit_id: lastCommitId, }); console.timeEnd(consoleTimeLabel); } catch (error) { console.error( 'An error occurred while trying to add a comment', error, ); throw error; } } } } public async addCommentToPr() { const { files } = await this.getBranchDiff(); if (!files) { throw new Error( errorsConfig[ErrorMessage.NO_CHANGED_FILES_IN_PULL_REQUEST], ); } const patchesList: FilenameWithPatch[] = []; const filesTooLongToBeChecked: string[] = []; for (const file of files) { if (file.patch && encode(file.patch).length <= MAX_TOKENS / 2) { patchesList.push({ filename: file.filename, patch: file.patch, tokensUsed: encode(file.patch).length, }); } else { filesTooLongToBeChecked.push(file.filename); } } if (filesTooLongToBeChecked.length > 0) { console.log( `The changes for ${filesTooLongToBeChecked.join( ', ', )} is too long to be checked.`, ); } const listOfFilesByTokenRange = divideFilesByTokenRange( MAX_TOKENS / 2, patchesList, ); await this.createReviewComments(listOfFilesByTokenRange[0]); if (listOfFilesByTokenRange.length > 1) { let requestCount = 1; const intervalId = setInterval(async () => { if (requestCount >= listOfFilesByTokenRange.length) { clearInterval(intervalId); return; } await this.createReviewComments(listOfFilesByTokenRange[requestCount]); requestCount += 1; }, OPENAI_TIMEOUT); } } } export default CommentOnPullRequestService;
src/services/commentOnPullRequestService.ts
magnificode-ltd-chatgpt-code-reviewer-067e8ce
[ { "filename": "src/services/utils/divideFilesByTokenRange.ts", "retrieved_chunk": "import { FilenameWithPatch } from '../types';\nconst divideFilesByTokenRange = (\n tokensRange: number,\n files: FilenameWithPatch[],\n) => {\n const result: FilenameWithPatch[][] = [];\n let currentArray: FilenameWithPatch[] = [];\n let currentTokensUsed = 0;\n for (const file of files) {\n if (currentTokensUsed + file.tokensUsed <= tokensRange) {", "score": 17.191474513603666 }, { "filename": "src/services/utils/parseOpenAISuggestions.ts", "retrieved_chunk": "const parseOpenAISuggestions = (suggestionsText: string) => {\n const regex = /@@(.+?)@@\\n([\\s\\S]*?)(?=\\n@@|$)/g;\n const suggestionMatches = suggestionsText.matchAll(regex);\n const suggestions = [];\n for (const match of suggestionMatches) {\n const filename = match[1].trim();\n const suggestionText = match[2].trim();\n suggestions.push({ filename, suggestionText });\n }\n return suggestions;", "score": 14.60591938268405 }, { "filename": "src/services/utils/extractFirstChangedLineFromPatch.ts", "retrieved_chunk": "const extractFirstChangedLineFromPatch = (patch: string) => {\n const lineHeaderRegExp = /^@@ -\\d+,\\d+ \\+(\\d+),(\\d+) @@/;\n const lines = patch.split('\\n');\n const lineHeaderMatch = lines[0].match(lineHeaderRegExp);\n let firstChangedLine = 1;\n if (lineHeaderMatch) {\n firstChangedLine = parseInt(lineHeaderMatch[1], 10);\n }\n return firstChangedLine;\n};", "score": 11.99388028958703 }, { "filename": "src/services/utils/concatenatePatchesToString.ts", "retrieved_chunk": "import { FilenameWithPatch } from '../types';\nconst concatenatePatchesToString = (files: FilenameWithPatch[]) =>\n files.map(({ filename, patch }) => `${filename}\\n${patch}\\n`).join('');\nexport default concatenatePatchesToString;", "score": 11.633355502602507 }, { "filename": "src/config/promptsConfig.ts", "retrieved_chunk": "enum Prompt {\n SYSTEM_PROMPT,\n}\nconst promptsConfig: { [key in Prompt]: string } = {\n [Prompt.SYSTEM_PROMPT]:\n 'You now assume the role of a code reviewer. Based on the patch provide a list of suggestions how to improve the code with examples according to coding standards and best practices.\\nStart every suggestion with path to the file. Path to the file should start with @@ and end with @@',\n};\nexport default promptsConfig;\nexport { Prompt };", "score": 11.141695910630153 } ]
typescript
suggestion) => suggestion.filename === file.filename, );
import { getInput } from '@actions/core'; import { context, getOctokit } from '@actions/github'; import { encode } from 'gpt-3-encoder'; import errorsConfig, { ErrorMessage } from '../config/errorsConfig'; import { FilenameWithPatch, Octokit, PullRequestInfo } from './types'; import concatenatePatchesToString from './utils/concatenatePatchesToString'; import divideFilesByTokenRange from './utils/divideFilesByTokenRange'; import extractFirstChangedLineFromPatch from './utils/extractFirstChangedLineFromPatch'; import getOpenAiSuggestions from './utils/getOpenAiSuggestions'; import parseOpenAISuggestions from './utils/parseOpenAISuggestions'; const MAX_TOKENS = parseInt(getInput('max_tokens'), 10) || 4096; const OPENAI_TIMEOUT = 20000; class CommentOnPullRequestService { private readonly octokitApi: Octokit; private readonly pullRequest: PullRequestInfo; constructor() { if (!process.env.GITHUB_TOKEN) { throw new Error(errorsConfig[ErrorMessage.MISSING_GITHUB_TOKEN]); } if (!process.env.OPENAI_API_KEY) { throw new Error(errorsConfig[ErrorMessage.MISSING_OPENAI_TOKEN]); } if (!context.payload.pull_request) { throw new Error(errorsConfig[ErrorMessage.NO_PULLREQUEST_IN_CONTEXT]); } this.octokitApi = getOctokit(process.env.GITHUB_TOKEN); this.pullRequest = { owner: context.repo.owner, repo: context.repo.repo, pullHeadRef: context.payload?.pull_request.head.ref, pullBaseRef: context.payload?.pull_request.base.ref, pullNumber: context.payload?.pull_request.number, }; } private async getBranchDiff() { const { owner, repo, pullBaseRef, pullHeadRef } = this.pullRequest; const { data: branchDiff } = await this.octokitApi.rest.repos.compareCommits({ owner, repo, base: pullBaseRef, head: pullHeadRef, }); return branchDiff; } private async getLastCommit() { const { owner, repo, pullNumber } = this.pullRequest; const { data: commitsList } = await this.octokitApi.rest.pulls.listCommits({ owner, repo, per_page: 50, pull_number: pullNumber, }); return commitsList[commitsList.length - 1].sha; } private async createReviewComments(files: FilenameWithPatch[]) { const suggestionsListText = await getOpenAiSuggestions( concatenatePatchesToString(files), ); const suggestionsByFile = parseOpenAISuggestions(suggestionsListText); const { owner, repo, pullNumber } = this.pullRequest; const lastCommitId = await this.getLastCommit(); for (const file of files) { const firstChangedLine = extractFirstChangedLineFromPatch(file.patch); const suggestionForFile = suggestionsByFile.find( (suggestion) => suggestion.filename === file.filename, ); if (suggestionForFile) { try { const consoleTimeLabel = `Comment was created successfully for file: ${file.filename}`; console.time(consoleTimeLabel); await this.octokitApi.rest.pulls.createReviewComment({ owner, repo, pull_number: pullNumber, line: firstChangedLine, path: suggestionForFile.filename, body: `[ChatGPTReviewer]\n${suggestionForFile.suggestionText}`, commit_id: lastCommitId, }); console.timeEnd(consoleTimeLabel); } catch (error) { console.error( 'An error occurred while trying to add a comment', error, ); throw error; } } } } public async addCommentToPr() { const { files } = await this.getBranchDiff(); if (!files) { throw new Error(
errorsConfig[ErrorMessage.NO_CHANGED_FILES_IN_PULL_REQUEST], );
} const patchesList: FilenameWithPatch[] = []; const filesTooLongToBeChecked: string[] = []; for (const file of files) { if (file.patch && encode(file.patch).length <= MAX_TOKENS / 2) { patchesList.push({ filename: file.filename, patch: file.patch, tokensUsed: encode(file.patch).length, }); } else { filesTooLongToBeChecked.push(file.filename); } } if (filesTooLongToBeChecked.length > 0) { console.log( `The changes for ${filesTooLongToBeChecked.join( ', ', )} is too long to be checked.`, ); } const listOfFilesByTokenRange = divideFilesByTokenRange( MAX_TOKENS / 2, patchesList, ); await this.createReviewComments(listOfFilesByTokenRange[0]); if (listOfFilesByTokenRange.length > 1) { let requestCount = 1; const intervalId = setInterval(async () => { if (requestCount >= listOfFilesByTokenRange.length) { clearInterval(intervalId); return; } await this.createReviewComments(listOfFilesByTokenRange[requestCount]); requestCount += 1; }, OPENAI_TIMEOUT); } } } export default CommentOnPullRequestService;
src/services/commentOnPullRequestService.ts
magnificode-ltd-chatgpt-code-reviewer-067e8ce
[ { "filename": "src/services/utils/getOpenAiSuggestions.ts", "retrieved_chunk": "import { getInput } from '@actions/core';\nimport fetch from 'node-fetch';\nimport errorsConfig, { ErrorMessage } from '../../config/errorsConfig';\nimport promptsConfig, { Prompt } from '../../config/promptsConfig';\nconst OPENAI_MODEL = getInput('model') || 'gpt-3.5-turbo';\nconst getOpenAiSuggestions = async (patch: string): Promise<any> => {\n if (!patch) {\n throw new Error(\n errorsConfig[ErrorMessage.MISSING_PATCH_FOR_OPENAI_SUGGESTION],\n );", "score": 10.370236331263367 }, { "filename": "src/services/utils/getOpenAiSuggestions.ts", "retrieved_chunk": " messages: [\n { role: 'system', content: promptsConfig[Prompt.SYSTEM_PROMPT] },\n { role: 'user', content: patch },\n ],\n }),\n });\n if (!response.ok) throw new Error('Failed to post data.');\n const responseJson = (await response.json()) as any;\n const openAiSuggestion =\n responseJson.choices.shift()?.message?.content || '';", "score": 7.251389255645854 }, { "filename": "src/index.ts", "retrieved_chunk": "import CommentOnPullRequestService from './services/commentOnPullRequestService';\nconst commentOnPrService = new CommentOnPullRequestService();\ncommentOnPrService.addCommentToPr();", "score": 6.227367301683238 }, { "filename": "src/config/errorsConfig.ts", "retrieved_chunk": "enum ErrorMessage {\n MISSING_GITHUB_TOKEN,\n MISSING_OPENAI_TOKEN,\n NO_PULLREQUEST_IN_CONTEXT,\n MISSING_PATCH_FOR_OPENAI_SUGGESTION,\n NO_CHANGED_FILES_IN_PULL_REQUEST,\n}\nconst errorsConfig: { [key in ErrorMessage]: string } = {\n [ErrorMessage.MISSING_GITHUB_TOKEN]:\n 'A GitHub token must be provided to use the Octokit API.',", "score": 6.1055225148428836 }, { "filename": "src/services/utils/divideFilesByTokenRange.ts", "retrieved_chunk": "import { FilenameWithPatch } from '../types';\nconst divideFilesByTokenRange = (\n tokensRange: number,\n files: FilenameWithPatch[],\n) => {\n const result: FilenameWithPatch[][] = [];\n let currentArray: FilenameWithPatch[] = [];\n let currentTokensUsed = 0;\n for (const file of files) {\n if (currentTokensUsed + file.tokensUsed <= tokensRange) {", "score": 6.080706334637207 } ]
typescript
errorsConfig[ErrorMessage.NO_CHANGED_FILES_IN_PULL_REQUEST], );
import { getInput } from '@actions/core'; import { context, getOctokit } from '@actions/github'; import { encode } from 'gpt-3-encoder'; import errorsConfig, { ErrorMessage } from '../config/errorsConfig'; import { FilenameWithPatch, Octokit, PullRequestInfo } from './types'; import concatenatePatchesToString from './utils/concatenatePatchesToString'; import divideFilesByTokenRange from './utils/divideFilesByTokenRange'; import extractFirstChangedLineFromPatch from './utils/extractFirstChangedLineFromPatch'; import getOpenAiSuggestions from './utils/getOpenAiSuggestions'; import parseOpenAISuggestions from './utils/parseOpenAISuggestions'; const MAX_TOKENS = parseInt(getInput('max_tokens'), 10) || 4096; const OPENAI_TIMEOUT = 20000; class CommentOnPullRequestService { private readonly octokitApi: Octokit; private readonly pullRequest: PullRequestInfo; constructor() { if (!process.env.GITHUB_TOKEN) { throw new Error(errorsConfig[ErrorMessage.MISSING_GITHUB_TOKEN]); } if (!process.env.OPENAI_API_KEY) { throw new Error(errorsConfig[ErrorMessage.MISSING_OPENAI_TOKEN]); } if (!context.payload.pull_request) { throw new Error(errorsConfig[ErrorMessage.NO_PULLREQUEST_IN_CONTEXT]); } this.octokitApi = getOctokit(process.env.GITHUB_TOKEN); this.pullRequest = { owner: context.repo.owner, repo: context.repo.repo, pullHeadRef: context.payload?.pull_request.head.ref, pullBaseRef: context.payload?.pull_request.base.ref, pullNumber: context.payload?.pull_request.number, }; } private async getBranchDiff() { const { owner, repo, pullBaseRef, pullHeadRef } = this.pullRequest; const { data: branchDiff } = await this.octokitApi.rest.repos.compareCommits({ owner, repo, base: pullBaseRef, head: pullHeadRef, }); return branchDiff; } private async getLastCommit() { const { owner, repo, pullNumber } = this.pullRequest; const { data: commitsList } = await this.octokitApi.rest.pulls.listCommits({ owner, repo, per_page: 50, pull_number: pullNumber, }); return commitsList[commitsList.length - 1].sha; } private async createReviewComments(files: FilenameWithPatch[]) { const suggestionsListText = await getOpenAiSuggestions( concatenatePatchesToString(files), ); const suggestionsByFile = parseOpenAISuggestions(suggestionsListText); const { owner, repo, pullNumber } = this.pullRequest; const lastCommitId = await this.getLastCommit(); for (const file of files) { const firstChangedLine = extractFirstChangedLineFromPatch(file.patch); const suggestionForFile = suggestionsByFile.find( (suggestion) => suggestion.filename === file.filename, ); if (suggestionForFile) { try { const consoleTimeLabel = `Comment was created successfully for file: ${file.filename}`; console.time(consoleTimeLabel); await this.octokitApi.rest.pulls.createReviewComment({ owner, repo, pull_number: pullNumber, line: firstChangedLine, path: suggestionForFile.filename, body: `[ChatGPTReviewer]\n${suggestionForFile.suggestionText}`, commit_id: lastCommitId, }); console.timeEnd(consoleTimeLabel); } catch (error) { console.error( 'An error occurred while trying to add a comment', error, ); throw error; } } } } public async addCommentToPr() { const { files } = await this.getBranchDiff(); if (!files) { throw new Error( errorsConfig[ErrorMessage.NO_CHANGED_FILES_IN_PULL_REQUEST], ); } const patchesList: FilenameWithPatch[] = []; const filesTooLongToBeChecked: string[] = []; for (const file of files) { if (file.patch && encode(file.patch).length <= MAX_TOKENS / 2) { patchesList.push({ filename: file.filename, patch: file.patch, tokensUsed: encode(file.patch).length, }); } else { filesTooLongToBeChecked.push(file.filename); } } if (filesTooLongToBeChecked.length > 0) { console.log( `The changes for ${filesTooLongToBeChecked.join( ', ', )} is too long to be checked.`, ); } const listOfFilesByTokenRange =
divideFilesByTokenRange( MAX_TOKENS / 2, patchesList, );
await this.createReviewComments(listOfFilesByTokenRange[0]); if (listOfFilesByTokenRange.length > 1) { let requestCount = 1; const intervalId = setInterval(async () => { if (requestCount >= listOfFilesByTokenRange.length) { clearInterval(intervalId); return; } await this.createReviewComments(listOfFilesByTokenRange[requestCount]); requestCount += 1; }, OPENAI_TIMEOUT); } } } export default CommentOnPullRequestService;
src/services/commentOnPullRequestService.ts
magnificode-ltd-chatgpt-code-reviewer-067e8ce
[ { "filename": "src/services/utils/parseOpenAISuggestions.ts", "retrieved_chunk": "const parseOpenAISuggestions = (suggestionsText: string) => {\n const regex = /@@(.+?)@@\\n([\\s\\S]*?)(?=\\n@@|$)/g;\n const suggestionMatches = suggestionsText.matchAll(regex);\n const suggestions = [];\n for (const match of suggestionMatches) {\n const filename = match[1].trim();\n const suggestionText = match[2].trim();\n suggestions.push({ filename, suggestionText });\n }\n return suggestions;", "score": 4.697072189036042 }, { "filename": "src/config/errorsConfig.ts", "retrieved_chunk": " [ErrorMessage.MISSING_OPENAI_TOKEN]:\n 'An OpenAI API token must be provided to use the OpenAI API. Make sure you have add a token with a name OPENAI_API_KEY in https://github.com/{user}/{repository}/settings/secrets/actions',\n [ErrorMessage.NO_PULLREQUEST_IN_CONTEXT]:\n 'Pull request data must be provided, check payload and try again.',\n [ErrorMessage.MISSING_PATCH_FOR_OPENAI_SUGGESTION]:\n 'The patch must be exist to provide a suggestions with Open AI',\n [ErrorMessage.NO_CHANGED_FILES_IN_PULL_REQUEST]:\n 'There are not any changed files in provided pull request',\n};\nexport default errorsConfig;", "score": 4.628883634348217 }, { "filename": "src/services/utils/divideFilesByTokenRange.ts", "retrieved_chunk": "import { FilenameWithPatch } from '../types';\nconst divideFilesByTokenRange = (\n tokensRange: number,\n files: FilenameWithPatch[],\n) => {\n const result: FilenameWithPatch[][] = [];\n let currentArray: FilenameWithPatch[] = [];\n let currentTokensUsed = 0;\n for (const file of files) {\n if (currentTokensUsed + file.tokensUsed <= tokensRange) {", "score": 4.587030482829644 }, { "filename": "src/config/errorsConfig.ts", "retrieved_chunk": "enum ErrorMessage {\n MISSING_GITHUB_TOKEN,\n MISSING_OPENAI_TOKEN,\n NO_PULLREQUEST_IN_CONTEXT,\n MISSING_PATCH_FOR_OPENAI_SUGGESTION,\n NO_CHANGED_FILES_IN_PULL_REQUEST,\n}\nconst errorsConfig: { [key in ErrorMessage]: string } = {\n [ErrorMessage.MISSING_GITHUB_TOKEN]:\n 'A GitHub token must be provided to use the Octokit API.',", "score": 3.7304166843324325 }, { "filename": "src/services/utils/concatenatePatchesToString.ts", "retrieved_chunk": "import { FilenameWithPatch } from '../types';\nconst concatenatePatchesToString = (files: FilenameWithPatch[]) =>\n files.map(({ filename, patch }) => `${filename}\\n${patch}\\n`).join('');\nexport default concatenatePatchesToString;", "score": 3.414647546554162 } ]
typescript
divideFilesByTokenRange( MAX_TOKENS / 2, patchesList, );
import { getInput } from '@actions/core'; import { context, getOctokit } from '@actions/github'; import { encode } from 'gpt-3-encoder'; import errorsConfig, { ErrorMessage } from '../config/errorsConfig'; import { FilenameWithPatch, Octokit, PullRequestInfo } from './types'; import concatenatePatchesToString from './utils/concatenatePatchesToString'; import divideFilesByTokenRange from './utils/divideFilesByTokenRange'; import extractFirstChangedLineFromPatch from './utils/extractFirstChangedLineFromPatch'; import getOpenAiSuggestions from './utils/getOpenAiSuggestions'; import parseOpenAISuggestions from './utils/parseOpenAISuggestions'; const MAX_TOKENS = parseInt(getInput('max_tokens'), 10) || 4096; const OPENAI_TIMEOUT = 20000; class CommentOnPullRequestService { private readonly octokitApi: Octokit; private readonly pullRequest: PullRequestInfo; constructor() { if (!process.env.GITHUB_TOKEN) { throw new Error(errorsConfig[ErrorMessage.MISSING_GITHUB_TOKEN]); } if (!process.env.OPENAI_API_KEY) { throw new Error(errorsConfig[ErrorMessage.MISSING_OPENAI_TOKEN]); } if (!context.payload.pull_request) { throw new Error(errorsConfig[ErrorMessage.NO_PULLREQUEST_IN_CONTEXT]); } this.octokitApi = getOctokit(process.env.GITHUB_TOKEN); this.pullRequest = { owner: context.repo.owner, repo: context.repo.repo, pullHeadRef: context.payload?.pull_request.head.ref, pullBaseRef: context.payload?.pull_request.base.ref, pullNumber: context.payload?.pull_request.number, }; } private async getBranchDiff() { const { owner, repo, pullBaseRef, pullHeadRef } = this.pullRequest; const { data: branchDiff } = await this.octokitApi.rest.repos.compareCommits({ owner, repo, base: pullBaseRef, head: pullHeadRef, }); return branchDiff; } private async getLastCommit() { const { owner, repo, pullNumber } = this.pullRequest; const { data: commitsList } = await this.octokitApi.rest.pulls.listCommits({ owner, repo, per_page: 50, pull_number: pullNumber, }); return commitsList[commitsList.length - 1].sha; } private async createReviewComments(files: FilenameWithPatch[]) {
const suggestionsListText = await getOpenAiSuggestions( concatenatePatchesToString(files), );
const suggestionsByFile = parseOpenAISuggestions(suggestionsListText); const { owner, repo, pullNumber } = this.pullRequest; const lastCommitId = await this.getLastCommit(); for (const file of files) { const firstChangedLine = extractFirstChangedLineFromPatch(file.patch); const suggestionForFile = suggestionsByFile.find( (suggestion) => suggestion.filename === file.filename, ); if (suggestionForFile) { try { const consoleTimeLabel = `Comment was created successfully for file: ${file.filename}`; console.time(consoleTimeLabel); await this.octokitApi.rest.pulls.createReviewComment({ owner, repo, pull_number: pullNumber, line: firstChangedLine, path: suggestionForFile.filename, body: `[ChatGPTReviewer]\n${suggestionForFile.suggestionText}`, commit_id: lastCommitId, }); console.timeEnd(consoleTimeLabel); } catch (error) { console.error( 'An error occurred while trying to add a comment', error, ); throw error; } } } } public async addCommentToPr() { const { files } = await this.getBranchDiff(); if (!files) { throw new Error( errorsConfig[ErrorMessage.NO_CHANGED_FILES_IN_PULL_REQUEST], ); } const patchesList: FilenameWithPatch[] = []; const filesTooLongToBeChecked: string[] = []; for (const file of files) { if (file.patch && encode(file.patch).length <= MAX_TOKENS / 2) { patchesList.push({ filename: file.filename, patch: file.patch, tokensUsed: encode(file.patch).length, }); } else { filesTooLongToBeChecked.push(file.filename); } } if (filesTooLongToBeChecked.length > 0) { console.log( `The changes for ${filesTooLongToBeChecked.join( ', ', )} is too long to be checked.`, ); } const listOfFilesByTokenRange = divideFilesByTokenRange( MAX_TOKENS / 2, patchesList, ); await this.createReviewComments(listOfFilesByTokenRange[0]); if (listOfFilesByTokenRange.length > 1) { let requestCount = 1; const intervalId = setInterval(async () => { if (requestCount >= listOfFilesByTokenRange.length) { clearInterval(intervalId); return; } await this.createReviewComments(listOfFilesByTokenRange[requestCount]); requestCount += 1; }, OPENAI_TIMEOUT); } } } export default CommentOnPullRequestService;
src/services/commentOnPullRequestService.ts
magnificode-ltd-chatgpt-code-reviewer-067e8ce
[ { "filename": "src/services/utils/concatenatePatchesToString.ts", "retrieved_chunk": "import { FilenameWithPatch } from '../types';\nconst concatenatePatchesToString = (files: FilenameWithPatch[]) =>\n files.map(({ filename, patch }) => `${filename}\\n${patch}\\n`).join('');\nexport default concatenatePatchesToString;", "score": 11.181355249066826 }, { "filename": "src/services/utils/divideFilesByTokenRange.ts", "retrieved_chunk": "import { FilenameWithPatch } from '../types';\nconst divideFilesByTokenRange = (\n tokensRange: number,\n files: FilenameWithPatch[],\n) => {\n const result: FilenameWithPatch[][] = [];\n let currentArray: FilenameWithPatch[] = [];\n let currentTokensUsed = 0;\n for (const file of files) {\n if (currentTokensUsed + file.tokensUsed <= tokensRange) {", "score": 7.355967028995195 }, { "filename": "src/services/types.ts", "retrieved_chunk": " pullHeadRef: string;\n pullBaseRef: string;\n pullNumber: number;\n};\nexport type { Octokit, FilenameWithPatch, PullRequestInfo };", "score": 5.063676598922134 }, { "filename": "src/services/utils/extractFirstChangedLineFromPatch.ts", "retrieved_chunk": "const extractFirstChangedLineFromPatch = (patch: string) => {\n const lineHeaderRegExp = /^@@ -\\d+,\\d+ \\+(\\d+),(\\d+) @@/;\n const lines = patch.split('\\n');\n const lineHeaderMatch = lines[0].match(lineHeaderRegExp);\n let firstChangedLine = 1;\n if (lineHeaderMatch) {\n firstChangedLine = parseInt(lineHeaderMatch[1], 10);\n }\n return firstChangedLine;\n};", "score": 4.605498423359217 }, { "filename": "src/services/utils/getOpenAiSuggestions.ts", "retrieved_chunk": "import { getInput } from '@actions/core';\nimport fetch from 'node-fetch';\nimport errorsConfig, { ErrorMessage } from '../../config/errorsConfig';\nimport promptsConfig, { Prompt } from '../../config/promptsConfig';\nconst OPENAI_MODEL = getInput('model') || 'gpt-3.5-turbo';\nconst getOpenAiSuggestions = async (patch: string): Promise<any> => {\n if (!patch) {\n throw new Error(\n errorsConfig[ErrorMessage.MISSING_PATCH_FOR_OPENAI_SUGGESTION],\n );", "score": 3.9886051098969526 } ]
typescript
const suggestionsListText = await getOpenAiSuggestions( concatenatePatchesToString(files), );
import { getInput } from '@actions/core'; import { context, getOctokit } from '@actions/github'; import { encode } from 'gpt-3-encoder'; import errorsConfig, { ErrorMessage } from '../config/errorsConfig'; import { FilenameWithPatch, Octokit, PullRequestInfo } from './types'; import concatenatePatchesToString from './utils/concatenatePatchesToString'; import divideFilesByTokenRange from './utils/divideFilesByTokenRange'; import extractFirstChangedLineFromPatch from './utils/extractFirstChangedLineFromPatch'; import getOpenAiSuggestions from './utils/getOpenAiSuggestions'; import parseOpenAISuggestions from './utils/parseOpenAISuggestions'; const MAX_TOKENS = parseInt(getInput('max_tokens'), 10) || 4096; const OPENAI_TIMEOUT = 20000; class CommentOnPullRequestService { private readonly octokitApi: Octokit; private readonly pullRequest: PullRequestInfo; constructor() { if (!process.env.GITHUB_TOKEN) { throw new Error(errorsConfig[ErrorMessage.MISSING_GITHUB_TOKEN]); } if (!process.env.OPENAI_API_KEY) { throw new Error(errorsConfig[ErrorMessage.MISSING_OPENAI_TOKEN]); } if (!context.payload.pull_request) { throw new Error(errorsConfig[ErrorMessage.NO_PULLREQUEST_IN_CONTEXT]); } this.octokitApi = getOctokit(process.env.GITHUB_TOKEN); this.pullRequest = { owner: context.repo.owner, repo: context.repo.repo, pullHeadRef: context.payload?.pull_request.head.ref, pullBaseRef: context.payload?.pull_request.base.ref, pullNumber: context.payload?.pull_request.number, }; } private async getBranchDiff() { const { owner, repo, pullBaseRef, pullHeadRef } = this.pullRequest; const { data: branchDiff } = await this.octokitApi.rest.repos.compareCommits({ owner, repo, base: pullBaseRef, head: pullHeadRef, }); return branchDiff; } private async getLastCommit() { const { owner, repo, pullNumber } = this.pullRequest; const { data: commitsList } = await this.octokitApi.rest.pulls.listCommits({ owner, repo, per_page: 50, pull_number: pullNumber, }); return commitsList[commitsList.length - 1].sha; } private async createReviewComments(files: FilenameWithPatch[]) { const suggestionsListText = await getOpenAiSuggestions( concatenatePatchesToString(files), ); const suggestionsByFile = parseOpenAISuggestions(suggestionsListText); const { owner, repo, pullNumber } = this.pullRequest; const lastCommitId = await this.getLastCommit(); for (const file of files) { const firstChangedLine = extractFirstChangedLineFromPatch(file.patch); const suggestionForFile = suggestionsByFile.find( (suggestion) =>
suggestion.filename === file.filename, );
if (suggestionForFile) { try { const consoleTimeLabel = `Comment was created successfully for file: ${file.filename}`; console.time(consoleTimeLabel); await this.octokitApi.rest.pulls.createReviewComment({ owner, repo, pull_number: pullNumber, line: firstChangedLine, path: suggestionForFile.filename, body: `[ChatGPTReviewer]\n${suggestionForFile.suggestionText}`, commit_id: lastCommitId, }); console.timeEnd(consoleTimeLabel); } catch (error) { console.error( 'An error occurred while trying to add a comment', error, ); throw error; } } } } public async addCommentToPr() { const { files } = await this.getBranchDiff(); if (!files) { throw new Error( errorsConfig[ErrorMessage.NO_CHANGED_FILES_IN_PULL_REQUEST], ); } const patchesList: FilenameWithPatch[] = []; const filesTooLongToBeChecked: string[] = []; for (const file of files) { if (file.patch && encode(file.patch).length <= MAX_TOKENS / 2) { patchesList.push({ filename: file.filename, patch: file.patch, tokensUsed: encode(file.patch).length, }); } else { filesTooLongToBeChecked.push(file.filename); } } if (filesTooLongToBeChecked.length > 0) { console.log( `The changes for ${filesTooLongToBeChecked.join( ', ', )} is too long to be checked.`, ); } const listOfFilesByTokenRange = divideFilesByTokenRange( MAX_TOKENS / 2, patchesList, ); await this.createReviewComments(listOfFilesByTokenRange[0]); if (listOfFilesByTokenRange.length > 1) { let requestCount = 1; const intervalId = setInterval(async () => { if (requestCount >= listOfFilesByTokenRange.length) { clearInterval(intervalId); return; } await this.createReviewComments(listOfFilesByTokenRange[requestCount]); requestCount += 1; }, OPENAI_TIMEOUT); } } } export default CommentOnPullRequestService;
src/services/commentOnPullRequestService.ts
magnificode-ltd-chatgpt-code-reviewer-067e8ce
[ { "filename": "src/services/utils/divideFilesByTokenRange.ts", "retrieved_chunk": "import { FilenameWithPatch } from '../types';\nconst divideFilesByTokenRange = (\n tokensRange: number,\n files: FilenameWithPatch[],\n) => {\n const result: FilenameWithPatch[][] = [];\n let currentArray: FilenameWithPatch[] = [];\n let currentTokensUsed = 0;\n for (const file of files) {\n if (currentTokensUsed + file.tokensUsed <= tokensRange) {", "score": 17.191474513603666 }, { "filename": "src/services/utils/parseOpenAISuggestions.ts", "retrieved_chunk": "const parseOpenAISuggestions = (suggestionsText: string) => {\n const regex = /@@(.+?)@@\\n([\\s\\S]*?)(?=\\n@@|$)/g;\n const suggestionMatches = suggestionsText.matchAll(regex);\n const suggestions = [];\n for (const match of suggestionMatches) {\n const filename = match[1].trim();\n const suggestionText = match[2].trim();\n suggestions.push({ filename, suggestionText });\n }\n return suggestions;", "score": 14.60591938268405 }, { "filename": "src/services/utils/extractFirstChangedLineFromPatch.ts", "retrieved_chunk": "const extractFirstChangedLineFromPatch = (patch: string) => {\n const lineHeaderRegExp = /^@@ -\\d+,\\d+ \\+(\\d+),(\\d+) @@/;\n const lines = patch.split('\\n');\n const lineHeaderMatch = lines[0].match(lineHeaderRegExp);\n let firstChangedLine = 1;\n if (lineHeaderMatch) {\n firstChangedLine = parseInt(lineHeaderMatch[1], 10);\n }\n return firstChangedLine;\n};", "score": 11.99388028958703 }, { "filename": "src/services/utils/concatenatePatchesToString.ts", "retrieved_chunk": "import { FilenameWithPatch } from '../types';\nconst concatenatePatchesToString = (files: FilenameWithPatch[]) =>\n files.map(({ filename, patch }) => `${filename}\\n${patch}\\n`).join('');\nexport default concatenatePatchesToString;", "score": 11.633355502602507 }, { "filename": "src/config/promptsConfig.ts", "retrieved_chunk": "enum Prompt {\n SYSTEM_PROMPT,\n}\nconst promptsConfig: { [key in Prompt]: string } = {\n [Prompt.SYSTEM_PROMPT]:\n 'You now assume the role of a code reviewer. Based on the patch provide a list of suggestions how to improve the code with examples according to coding standards and best practices.\\nStart every suggestion with path to the file. Path to the file should start with @@ and end with @@',\n};\nexport default promptsConfig;\nexport { Prompt };", "score": 11.141695910630153 } ]
typescript
suggestion.filename === file.filename, );
import { CodeMirrorRangeRectCalculator, RangeRectCalculator, TextareaRangeRectCalculator, } from "../utilities/dom/range-rect-calculator"; import {formatList} from "../utilities/format"; import {lintMarkdown} from "../utilities/lint-markdown"; import {LintErrorTooltip} from "./lint-error-tooltip"; import {LintErrorAnnotation} from "./lint-error-annotation"; import {Vector} from "../utilities/geometry/vector"; import {NumberRange} from "../utilities/geometry/number-range"; import {Component} from "./component"; export abstract class LintedMarkdownEditor extends Component { #editor: HTMLElement; #tooltip: LintErrorTooltip; #resizeObserver: ResizeObserver; #rangeRectCalculator: RangeRectCalculator; #annotationsPortal = document.createElement("div"); #statusContainer = LintedMarkdownEditor.#createStatusContainerElement(); constructor( element: HTMLElement, portal: HTMLElement, rangeRectCalculator: RangeRectCalculator ) { super(); this.#editor = element; this.#rangeRectCalculator = rangeRectCalculator; portal.append(this.#annotationsPortal, this.#statusContainer); this.addEventListener(element, "focus", this.onUpdate); this.addEventListener(element, "blur", this.#onBlur); this.addEventListener(element, "mousemove", this.#onMouseMove); this.addEventListener(element, "mouseleave", this.#onMouseLeave); // capture ancestor scroll events for nested scroll containers this.addEventListener(document, "scroll", this.#onReposition, true); // selectionchange can't be bound to the textarea so we have to use the document this.addEventListener(document, "selectionchange", this.#onSelectionChange); // annotations are document-relative so we need to observe document resize as well this.addEventListener(window, "resize", this.#onReposition); // this does mean it will run twice when the resize causes a resize of the textarea, // but we also need the resize observer for the textarea because it's user resizable this.#resizeObserver = new ResizeObserver(this.#onReposition); this.#resizeObserver.observe(element); this.#tooltip = new LintErrorTooltip(portal); } disconnect() { super.disconnect(); this.#resizeObserver.disconnect(); this.#rangeRectCalculator.disconnect(); this.#tooltip.disconnect(); this.#annotationsPortal.remove(); this.#statusContainer.remove(); } /** * Return a list of rects for the given range. If the range extends over multiple lines, * multiple rects will be returned. */ getRangeRects(characterIndexes: NumberRange) { return this.#rangeRectCalculator.getClientRects(characterIndexes); } getBoundingClientRect() { return this.#editor.getBoundingClientRect(); } getLineHeight() { const parsed = parseInt(getComputedStyle(this.#editor).lineHeight, 10); return Number.isNaN(parsed) ? undefined : parsed; } abstract get value(): string; abstract get caretPosition(): number; #_annotations: readonly LintErrorAnnotation[] = []; set #annotations(annotations: ReadonlyArray<LintErrorAnnotation>) { if (annotations === this.#_annotations) return; this.#_annotations = annotations; this.#statusContainer.textContent = annotations.length > 0 ? `${annotations.length} Markdown problem${ annotations.length > 1 ? "s" : "" } identified: see line${ annotations.length > 1 ? "s" : "" } ${formatList( annotations.map((a) => a.lineNumber.toString()), "and" )}` : ""; } get #annotations() { return this.#_annotations; } #_tooltipAnnotations: readonly LintErrorAnnotation[] = []; set #tooltipAnnotations(annotations: LintErrorAnnotation[]) { if (annotations === this.#_tooltipAnnotations) return; this.#_tooltipAnnotations = annotations; const position = annotations[0]?.getTooltipPosition(); const errors = annotations.map(({error}) => error); if (position) this.#tooltip.show(errors, position); else this.#tooltip.hide(); } protected onUpdate = () => this.#lint(); #isOnRepositionTick = false; #onReposition = () => { if (this.#isOnRepositionTick) return; this.#isOnRepositionTick = true; requestAnimationFrame(() => { this.#recalculateAnnotationPositions(); this.#isOnRepositionTick = false; }); }; #onBlur = () => this.#clear(); #onMouseMove = (event: MouseEvent) => this.#updatePointerTooltip(new Vector(event.clientX, event.clientY)); #onMouseLeave = () => (this.#tooltipAnnotations = []); #onSelectionChange = () => { // this event only works when applied to the document but we can filter it by detecting focus if (document.activeElement === this.#editor) this.#updateCaretTooltip(); }; #clear() { // the annotations will clean themselves up too but this is slightly faster this.#annotationsPortal.replaceChildren(); for (const annotation of this.#annotations) annotation.disconnect(); this.#annotations = []; this.#tooltipAnnotations = []; } #lint() { this.#clear(); // clear() will not hide the tooltip if the mouse is over it, but if the user is typing then they are not trying to copy content this.#tooltip.hide(true); if (document.activeElement !== this.#editor) return; const errors = lintMarkdown(this.value); this.#annotations = errors.map(
(error) => new LintErrorAnnotation(error, this, this.#annotationsPortal) );
} #recalculateAnnotationPositions() { for (const annotation of this.#annotations) annotation.recalculatePosition(); } #updatePointerTooltip(pointerLocation: Vector) { // can't use mouse events on annotations (the easy way) because they have pointer-events: none this.#tooltipAnnotations = this.#annotations.filter((a) => a.containsPoint(pointerLocation) ); } #updateCaretTooltip() { this.#tooltipAnnotations = this.#annotations.filter((a) => a.containsIndex(this.caretPosition) ); } static #createStatusContainerElement() { const container = document.createElement("p"); container.setAttribute("aria-live", "polite"); container.style.position = "absolute"; container.style.clipPath = "circle(0)"; return container; } } export class LintedMarkdownTextareaEditor extends LintedMarkdownEditor { readonly #textarea: HTMLTextAreaElement; constructor(textarea: HTMLTextAreaElement, portal: HTMLElement) { super(textarea, portal, new TextareaRangeRectCalculator(textarea)); this.#textarea = textarea; this.addEventListener(textarea, "input", this.onUpdate); } get value() { return this.#textarea.value; } get caretPosition() { return this.#textarea.selectionEnd !== this.#textarea.selectionStart ? -1 : this.#textarea.selectionStart; } } export class LintedMarkdownCodeMirrorEditor extends LintedMarkdownEditor { readonly #element: HTMLElement; readonly #mutationObserver: MutationObserver; constructor(element: HTMLElement, portal: HTMLElement) { super(element, portal, new CodeMirrorRangeRectCalculator(element)); this.#element = element; this.#mutationObserver = new MutationObserver(this.onUpdate); this.#mutationObserver.observe(element, { childList: true, subtree: true, }); } override disconnect(): void { super.disconnect(); this.#mutationObserver.disconnect(); } get value() { return Array.from(this.#element.querySelectorAll(".CodeMirror-line")) .map((line) => line.textContent) .join("\n"); } get caretPosition() { const selection = document.getSelection(); const range = selection?.getRangeAt(0); if (!range?.collapsed || selection?.rangeCount !== 1) return -1; const referenceRange = document.createRange(); referenceRange.selectNodeContents(this.#element); referenceRange.setEnd(range.startContainer, range.startOffset); return referenceRange.toString().length; } }
src/components/linted-markdown-editor.ts
iansan5653-github-markdown-a11y-extension-c6a54d0
[ { "filename": "src/components/lint-error-tooltip.ts", "retrieved_chunk": " const availableWidth = document.body.clientWidth - 2 * MARGIN;\n const rightOverflow = Math.max(x + WIDTH - (availableWidth + MARGIN), 0);\n this.#tooltip.style.left = `${Math.max(x - rightOverflow, MARGIN)}px`;\n this.#tooltip.style.maxWidth = `${availableWidth}px`;\n }\n this.#tooltip.removeAttribute(\"hidden\");\n }\n hide(force = false) {\n // Don't hide if the mouse enters the tooltip (allowing users to copy text)\n setTimeout(() => {", "score": 40.447690413705345 }, { "filename": "src/components/lint-error-tooltip.ts", "retrieved_chunk": " super();\n this.addEventListener(document, \"keydown\", (e) => this.#onGlobalKeydown(e));\n this.addEventListener(this.#tooltip, \"mouseout\", () => this.hide());\n portal.appendChild(this.#tooltip);\n }\n disconnect() {\n super.disconnect();\n this.#tooltip.remove();\n }\n show(errors: LintError[], {x, y}: Vector) {", "score": 36.11575647353682 }, { "filename": "src/components/lint-error-tooltip.ts", "retrieved_chunk": " if (force || !this.#tooltip.matches(\":hover\"))\n this.#tooltip.setAttribute(\"hidden\", \"true\");\n }, 10);\n }\n #onGlobalKeydown(event: KeyboardEvent) {\n if (event.key === \"Escape\" && !event.defaultPrevented) this.hide(true);\n }\n static #createTooltipElement() {\n const element = document.createElement(\"div\");\n element.setAttribute(\"aria-live\", \"polite\");", "score": 33.843981413846286 }, { "filename": "src/components/lint-error-annotation.ts", "retrieved_chunk": " const scrollVector = getWindowScrollVector();\n // The range rectangles are tight around the characters; we'd rather fill the line height if possible\n const cssLineHeight = this.#editor.getLineHeight();\n const elements: HTMLElement[] = [];\n // render an annotation element for each line separately\n for (const rect of this.#editor.getRangeRects(this.#indexRange)) {\n // suppress when out of bounds\n if (!rect.isContainedBy(editorRect)) continue;\n // The rects are viewport-relative, but the annotations are absolute positioned\n // (document-relative) so we have to add the window scroll position", "score": 30.396555066273546 }, { "filename": "src/utilities/dom/range-rect-calculator.ts", "retrieved_chunk": " getClientRects({start, end}: NumberRange) {\n this.#refreshText();\n const textNode = this.#div.childNodes[0];\n if (!textNode) return [];\n this.#range.setStart(textNode, start);\n this.#range.setEnd(textNode, end);\n // The div is not in the same place as the textarea so we need to subtract the div\n // position and add the textarea position\n const divPosition = new Rect(this.#div.getBoundingClientRect()).asVector();\n const textareaPosition = new Rect(", "score": 29.306041307488755 } ]
typescript
(error) => new LintErrorAnnotation(error, this, this.#annotationsPortal) );
import { getInput } from '@actions/core'; import { context, getOctokit } from '@actions/github'; import { encode } from 'gpt-3-encoder'; import errorsConfig, { ErrorMessage } from '../config/errorsConfig'; import { FilenameWithPatch, Octokit, PullRequestInfo } from './types'; import concatenatePatchesToString from './utils/concatenatePatchesToString'; import divideFilesByTokenRange from './utils/divideFilesByTokenRange'; import extractFirstChangedLineFromPatch from './utils/extractFirstChangedLineFromPatch'; import getOpenAiSuggestions from './utils/getOpenAiSuggestions'; import parseOpenAISuggestions from './utils/parseOpenAISuggestions'; const MAX_TOKENS = parseInt(getInput('max_tokens'), 10) || 4096; const OPENAI_TIMEOUT = 20000; class CommentOnPullRequestService { private readonly octokitApi: Octokit; private readonly pullRequest: PullRequestInfo; constructor() { if (!process.env.GITHUB_TOKEN) { throw new Error(errorsConfig[ErrorMessage.MISSING_GITHUB_TOKEN]); } if (!process.env.OPENAI_API_KEY) { throw new Error(errorsConfig[ErrorMessage.MISSING_OPENAI_TOKEN]); } if (!context.payload.pull_request) { throw new Error(errorsConfig[ErrorMessage.NO_PULLREQUEST_IN_CONTEXT]); } this.octokitApi = getOctokit(process.env.GITHUB_TOKEN); this.pullRequest = { owner: context.repo.owner, repo: context.repo.repo, pullHeadRef: context.payload?.pull_request.head.ref, pullBaseRef: context.payload?.pull_request.base.ref, pullNumber: context.payload?.pull_request.number, }; } private async getBranchDiff() { const { owner, repo, pullBaseRef, pullHeadRef } = this.pullRequest; const { data: branchDiff } = await this.octokitApi.rest.repos.compareCommits({ owner, repo, base: pullBaseRef, head: pullHeadRef, }); return branchDiff; } private async getLastCommit() { const { owner, repo, pullNumber } = this.pullRequest; const { data: commitsList } = await this.octokitApi.rest.pulls.listCommits({ owner, repo, per_page: 50, pull_number: pullNumber, }); return commitsList[commitsList.length - 1].sha; } private async createReviewComments(files: FilenameWithPatch[]) { const suggestionsListText = await getOpenAiSuggestions( concatenatePatchesToString(files), ); const suggestionsByFile = parseOpenAISuggestions(suggestionsListText); const { owner, repo, pullNumber } = this.pullRequest; const lastCommitId = await this.getLastCommit(); for (const file of files) { const firstChangedLine = extractFirstChangedLineFromPatch(file.patch); const suggestionForFile = suggestionsByFile.find(
(suggestion) => suggestion.filename === file.filename, );
if (suggestionForFile) { try { const consoleTimeLabel = `Comment was created successfully for file: ${file.filename}`; console.time(consoleTimeLabel); await this.octokitApi.rest.pulls.createReviewComment({ owner, repo, pull_number: pullNumber, line: firstChangedLine, path: suggestionForFile.filename, body: `[ChatGPTReviewer]\n${suggestionForFile.suggestionText}`, commit_id: lastCommitId, }); console.timeEnd(consoleTimeLabel); } catch (error) { console.error( 'An error occurred while trying to add a comment', error, ); throw error; } } } } public async addCommentToPr() { const { files } = await this.getBranchDiff(); if (!files) { throw new Error( errorsConfig[ErrorMessage.NO_CHANGED_FILES_IN_PULL_REQUEST], ); } const patchesList: FilenameWithPatch[] = []; const filesTooLongToBeChecked: string[] = []; for (const file of files) { if (file.patch && encode(file.patch).length <= MAX_TOKENS / 2) { patchesList.push({ filename: file.filename, patch: file.patch, tokensUsed: encode(file.patch).length, }); } else { filesTooLongToBeChecked.push(file.filename); } } if (filesTooLongToBeChecked.length > 0) { console.log( `The changes for ${filesTooLongToBeChecked.join( ', ', )} is too long to be checked.`, ); } const listOfFilesByTokenRange = divideFilesByTokenRange( MAX_TOKENS / 2, patchesList, ); await this.createReviewComments(listOfFilesByTokenRange[0]); if (listOfFilesByTokenRange.length > 1) { let requestCount = 1; const intervalId = setInterval(async () => { if (requestCount >= listOfFilesByTokenRange.length) { clearInterval(intervalId); return; } await this.createReviewComments(listOfFilesByTokenRange[requestCount]); requestCount += 1; }, OPENAI_TIMEOUT); } } } export default CommentOnPullRequestService;
src/services/commentOnPullRequestService.ts
magnificode-ltd-chatgpt-code-reviewer-067e8ce
[ { "filename": "src/services/utils/divideFilesByTokenRange.ts", "retrieved_chunk": "import { FilenameWithPatch } from '../types';\nconst divideFilesByTokenRange = (\n tokensRange: number,\n files: FilenameWithPatch[],\n) => {\n const result: FilenameWithPatch[][] = [];\n let currentArray: FilenameWithPatch[] = [];\n let currentTokensUsed = 0;\n for (const file of files) {\n if (currentTokensUsed + file.tokensUsed <= tokensRange) {", "score": 19.32739677705746 }, { "filename": "src/services/utils/concatenatePatchesToString.ts", "retrieved_chunk": "import { FilenameWithPatch } from '../types';\nconst concatenatePatchesToString = (files: FilenameWithPatch[]) =>\n files.map(({ filename, patch }) => `${filename}\\n${patch}\\n`).join('');\nexport default concatenatePatchesToString;", "score": 17.90252339257695 }, { "filename": "src/services/utils/parseOpenAISuggestions.ts", "retrieved_chunk": "const parseOpenAISuggestions = (suggestionsText: string) => {\n const regex = /@@(.+?)@@\\n([\\s\\S]*?)(?=\\n@@|$)/g;\n const suggestionMatches = suggestionsText.matchAll(regex);\n const suggestions = [];\n for (const match of suggestionMatches) {\n const filename = match[1].trim();\n const suggestionText = match[2].trim();\n suggestions.push({ filename, suggestionText });\n }\n return suggestions;", "score": 14.60591938268405 }, { "filename": "src/services/utils/extractFirstChangedLineFromPatch.ts", "retrieved_chunk": "const extractFirstChangedLineFromPatch = (patch: string) => {\n const lineHeaderRegExp = /^@@ -\\d+,\\d+ \\+(\\d+),(\\d+) @@/;\n const lines = patch.split('\\n');\n const lineHeaderMatch = lines[0].match(lineHeaderRegExp);\n let firstChangedLine = 1;\n if (lineHeaderMatch) {\n firstChangedLine = parseInt(lineHeaderMatch[1], 10);\n }\n return firstChangedLine;\n};", "score": 11.99388028958703 }, { "filename": "src/config/promptsConfig.ts", "retrieved_chunk": "enum Prompt {\n SYSTEM_PROMPT,\n}\nconst promptsConfig: { [key in Prompt]: string } = {\n [Prompt.SYSTEM_PROMPT]:\n 'You now assume the role of a code reviewer. Based on the patch provide a list of suggestions how to improve the code with examples according to coding standards and best practices.\\nStart every suggestion with path to the file. Path to the file should start with @@ and end with @@',\n};\nexport default promptsConfig;\nexport { Prompt };", "score": 11.141695910630153 } ]
typescript
(suggestion) => suggestion.filename === file.filename, );
import { getInput } from '@actions/core'; import { context, getOctokit } from '@actions/github'; import { encode } from 'gpt-3-encoder'; import errorsConfig, { ErrorMessage } from '../config/errorsConfig'; import { FilenameWithPatch, Octokit, PullRequestInfo } from './types'; import concatenatePatchesToString from './utils/concatenatePatchesToString'; import divideFilesByTokenRange from './utils/divideFilesByTokenRange'; import extractFirstChangedLineFromPatch from './utils/extractFirstChangedLineFromPatch'; import getOpenAiSuggestions from './utils/getOpenAiSuggestions'; import parseOpenAISuggestions from './utils/parseOpenAISuggestions'; const MAX_TOKENS = parseInt(getInput('max_tokens'), 10) || 4096; const OPENAI_TIMEOUT = 20000; class CommentOnPullRequestService { private readonly octokitApi: Octokit; private readonly pullRequest: PullRequestInfo; constructor() { if (!process.env.GITHUB_TOKEN) { throw new Error(errorsConfig[ErrorMessage.MISSING_GITHUB_TOKEN]); } if (!process.env.OPENAI_API_KEY) { throw new Error(errorsConfig[ErrorMessage.MISSING_OPENAI_TOKEN]); } if (!context.payload.pull_request) { throw new Error(errorsConfig[ErrorMessage.NO_PULLREQUEST_IN_CONTEXT]); } this.octokitApi = getOctokit(process.env.GITHUB_TOKEN); this.pullRequest = { owner: context.repo.owner, repo: context.repo.repo, pullHeadRef: context.payload?.pull_request.head.ref, pullBaseRef: context.payload?.pull_request.base.ref, pullNumber: context.payload?.pull_request.number, }; } private async getBranchDiff() { const { owner, repo, pullBaseRef, pullHeadRef } = this.pullRequest; const { data: branchDiff } = await this.octokitApi.rest.repos.compareCommits({ owner, repo, base: pullBaseRef, head: pullHeadRef, }); return branchDiff; } private async getLastCommit() { const { owner, repo, pullNumber } = this.pullRequest; const { data: commitsList } = await this.octokitApi.rest.pulls.listCommits({ owner, repo, per_page: 50, pull_number: pullNumber, }); return commitsList[commitsList.length - 1].sha; } private async createReviewComments(files: FilenameWithPatch[]) { const suggestionsListText = await getOpenAiSuggestions( concatenatePatchesToString(files), ); const suggestionsByFile = parseOpenAISuggestions(suggestionsListText); const { owner, repo, pullNumber } = this.pullRequest; const lastCommitId = await this.getLastCommit(); for (const file of files) { const firstChangedLine = extractFirstChangedLineFromPatch(file.patch); const suggestionForFile = suggestionsByFile.find( (suggestion) => suggestion.filename === file.filename, ); if (suggestionForFile) { try { const consoleTimeLabel = `Comment was created successfully for file: ${file.filename}`; console.time(consoleTimeLabel); await this.octokitApi.rest.pulls.createReviewComment({ owner, repo, pull_number: pullNumber, line: firstChangedLine, path: suggestionForFile.filename, body: `[ChatGPTReviewer]\n${suggestionForFile.suggestionText}`, commit_id: lastCommitId, }); console.timeEnd(consoleTimeLabel); } catch (error) { console.error( 'An error occurred while trying to add a comment', error, ); throw error; } } } } public async addCommentToPr() { const { files } = await this.getBranchDiff(); if (!files) { throw new Error( errorsConfig[ErrorMessage.NO_CHANGED_FILES_IN_PULL_REQUEST], ); } const patchesList: FilenameWithPatch[] = []; const filesTooLongToBeChecked: string[] = []; for (const file of files) { if (file.patch && encode(file.patch).length <= MAX_TOKENS / 2) { patchesList.push({ filename: file.filename, patch: file.patch, tokensUsed: encode(file.patch).length, }); } else { filesTooLongToBeChecked.push(file.filename); } } if (filesTooLongToBeChecked.length > 0) { console.log( `The changes for ${filesTooLongToBeChecked.join( ', ', )} is too long to be checked.`, ); }
const listOfFilesByTokenRange = divideFilesByTokenRange( MAX_TOKENS / 2, patchesList, );
await this.createReviewComments(listOfFilesByTokenRange[0]); if (listOfFilesByTokenRange.length > 1) { let requestCount = 1; const intervalId = setInterval(async () => { if (requestCount >= listOfFilesByTokenRange.length) { clearInterval(intervalId); return; } await this.createReviewComments(listOfFilesByTokenRange[requestCount]); requestCount += 1; }, OPENAI_TIMEOUT); } } } export default CommentOnPullRequestService;
src/services/commentOnPullRequestService.ts
magnificode-ltd-chatgpt-code-reviewer-067e8ce
[ { "filename": "src/services/utils/parseOpenAISuggestions.ts", "retrieved_chunk": "const parseOpenAISuggestions = (suggestionsText: string) => {\n const regex = /@@(.+?)@@\\n([\\s\\S]*?)(?=\\n@@|$)/g;\n const suggestionMatches = suggestionsText.matchAll(regex);\n const suggestions = [];\n for (const match of suggestionMatches) {\n const filename = match[1].trim();\n const suggestionText = match[2].trim();\n suggestions.push({ filename, suggestionText });\n }\n return suggestions;", "score": 4.697072189036042 }, { "filename": "src/config/errorsConfig.ts", "retrieved_chunk": " [ErrorMessage.MISSING_OPENAI_TOKEN]:\n 'An OpenAI API token must be provided to use the OpenAI API. Make sure you have add a token with a name OPENAI_API_KEY in https://github.com/{user}/{repository}/settings/secrets/actions',\n [ErrorMessage.NO_PULLREQUEST_IN_CONTEXT]:\n 'Pull request data must be provided, check payload and try again.',\n [ErrorMessage.MISSING_PATCH_FOR_OPENAI_SUGGESTION]:\n 'The patch must be exist to provide a suggestions with Open AI',\n [ErrorMessage.NO_CHANGED_FILES_IN_PULL_REQUEST]:\n 'There are not any changed files in provided pull request',\n};\nexport default errorsConfig;", "score": 4.628883634348217 }, { "filename": "src/services/utils/divideFilesByTokenRange.ts", "retrieved_chunk": "import { FilenameWithPatch } from '../types';\nconst divideFilesByTokenRange = (\n tokensRange: number,\n files: FilenameWithPatch[],\n) => {\n const result: FilenameWithPatch[][] = [];\n let currentArray: FilenameWithPatch[] = [];\n let currentTokensUsed = 0;\n for (const file of files) {\n if (currentTokensUsed + file.tokensUsed <= tokensRange) {", "score": 4.587030482829644 }, { "filename": "src/config/errorsConfig.ts", "retrieved_chunk": "enum ErrorMessage {\n MISSING_GITHUB_TOKEN,\n MISSING_OPENAI_TOKEN,\n NO_PULLREQUEST_IN_CONTEXT,\n MISSING_PATCH_FOR_OPENAI_SUGGESTION,\n NO_CHANGED_FILES_IN_PULL_REQUEST,\n}\nconst errorsConfig: { [key in ErrorMessage]: string } = {\n [ErrorMessage.MISSING_GITHUB_TOKEN]:\n 'A GitHub token must be provided to use the Octokit API.',", "score": 3.7304166843324325 }, { "filename": "src/services/utils/concatenatePatchesToString.ts", "retrieved_chunk": "import { FilenameWithPatch } from '../types';\nconst concatenatePatchesToString = (files: FilenameWithPatch[]) =>\n files.map(({ filename, patch }) => `${filename}\\n${patch}\\n`).join('');\nexport default concatenatePatchesToString;", "score": 3.414647546554162 } ]
typescript
const listOfFilesByTokenRange = divideFilesByTokenRange( MAX_TOKENS / 2, patchesList, );
import chalk from 'chalk'; import { Express } from 'express'; import glob from 'glob'; import minimist from 'minimist'; import { IOptions } from './interfaces/IOptions'; import { initServer } from './modules/mockServer'; import { transferTSFile } from './modules/transferTSFile'; const getUsage = () => `Usage: ${chalk.bold.green('pb2TSApi')} [options] ${chalk.bold.red('[file1.proto file2.proto ...]')} or ${chalk.bold.red('[./**/*.proto]')}`; const getHelp = () => `Help: ${chalk.bold.green('--requestModule -r')}: the request module of you want to set, default is ${chalk.bold.red('\'axios\'')}, you can set to your custom request method, for example ${chalk.bold.red('\'@/request\'')}; ${chalk.bold.green('--baseUrl -b')}: the base url of you want to set, default is ${chalk.bold.red('\'/\'')}, you can set to your api path, for example ${chalk.bold.red('\'/api\'')}; ${chalk.bold.green('--folder -f')}: the folder of you want to save the output files, default is ${chalk.bold.red('\'./api\'')}; ${chalk.bold.green('--root -r')}: the root path set to protobufjs, default is ${chalk.bold.red('the path of this command run')}; ${chalk.bold.green('--optional -o')}: is transfrom d.ts optional to false, because of protobuf 3.0 set all filed is optional, default is ${chalk.bold.red('true')}; ${chalk.bold.green('--mock -m')}: is open mock server, default is ${chalk.bold.red('false')}; ${chalk.bold.green('--port -p')}: mock server port, default is ${chalk.bold.red('3000')}; `; export async function main() { try { const argv = minimist(process.argv.slice(2), { alias: { requestModule: 'r', baseUrl: 'b', folder: 'f', root: 'r', optional: 'o', mock: 'm', port: 'p', help: 'h', }, string: ['requestModule', 'baseUrl', 'folder', 'root', 'port'], boolean: ['optional', 'mock'], default: { requestModule: 'axios', baseUrl: '/', folder: './api', root: process.cwd(), optional: true, mock: false, port: '3000', help: '', }, }); if (argv.help) { process.stderr.write(getHelp()); process.exit(1); } const { _: files } = argv; const options: IOptions = { requestModule: argv.requestModule, baseUrl: argv.baseUrl, folder: argv.folder, root: argv.root, optional: argv.optional, mock: argv.mock, port: argv.port, help: argv.help, }; if (!files.length) { process.stderr.write(getUsage()); process.exit(1); } const protoFiles = await glob(files, { ignore: 'node_modules/**', windowsPathsNoEscape: true }); if (!protoFiles.length) { process.stderr.write(chalk.bold.red(`there is not files for the flowing paths: \n ${files.join('\n')}`)); process.exit(1); } let mockServer: Express;
if (options.mock) {
mockServer = initServer(options); } await Promise.all(protoFiles.map(filePath => transferTSFile(filePath, mockServer, options))); } catch (err) { console.error(err); process.exit(1); } } main();
src/index.ts
xingbofeng-protobuf-to-ts-api-aec9dc6
[ { "filename": "src/modules/getPbjsFile.ts", "retrieved_chunk": " const { folder = '' } = options;\n const fileName = filePath.replace('.proto', '.js');\n const pbjsFilePath = path.resolve(process.cwd(), folder, fileName);\n const p = path.dirname(pbjsFilePath);\n await mkdirp(p);\n return new Promise((resolve, reject) => {\n pbjs.main(['-p', options.root, '-t', 'static-module', '-w', 'commonjs', '-o', pbjsFilePath, path.resolve(process.cwd(), filePath)], err => {\n if (err) {\n reject(err);\n }", "score": 14.584659736764266 }, { "filename": "src/modules/saveJSONSchemaFile.ts", "retrieved_chunk": " required: true,\n };\n const compilerOptions = {\n strictNullChecks: true,\n };\n const program = getProgramFromFiles([path.resolve(pbtsFilePath)], compilerOptions, process.cwd());\n const generator = buildGenerator(program, settings);\n const symbols = (generator?.getUserSymbols() || []).filter(symbol => /I(\\S*)Rsp$/.test(symbol));\n const schema = generator?.getSchemaForSymbols(symbols);\n const jsonSchemaFilePath = pbtsFilePath.replace('.d.ts', '.json');", "score": 12.877572723169687 }, { "filename": "src/modules/saveMockJSONFile.ts", "retrieved_chunk": " const jsfResult = await JSONSchemaFaker.resolve(schema.definitions) as JsonObject;\n const json: Record<string, JsonValue> = {};\n for (const key in jsfResult) {\n if (Object.hasOwnProperty.call(jsfResult, key)) {\n const rspNameMatchs = key.match(/I(\\S*)Rsp$/);\n if (rspNameMatchs && rspNameMatchs.length) {\n const apiName = rspNameMatchs[1];\n json[apiName] = jsfResult[key];\n }\n }", "score": 11.958765080509181 }, { "filename": "src/modules/getPbtsFile.ts", "retrieved_chunk": " const pbtsFilePath = path.resolve(process.cwd(), folder, pbjsFilePath.replace('.js', '.d.ts'));\n return new Promise((resolve, reject) => {\n pbts.main(['-p', options.root, '-o', pbtsFilePath, pbjsFilePath], err => {\n if (err) {\n reject(err);\n }\n resolve(pbtsFilePath);\n });\n });\n}", "score": 11.875528109031189 }, { "filename": "src/modules/mockServer.ts", "retrieved_chunk": " * @param {Express} mockServer express server 对象\n * @param {IOptions} options 用户自定义配置\n */\nexport async function generateMockRoute(mockFilePath: string, mockServer: Express, options: IOptions) {\n const { baseUrl } = options;\n const mockFile = await fs.promises.readFile(mockFilePath, { encoding: 'utf-8' });\n const json = JSON.parse(mockFile);\n for (const apiName in json) {\n if (Object.hasOwnProperty.call(json, apiName)) {\n const requestMethod = getRequestMethod(apiName);", "score": 9.802775518261106 } ]
typescript
if (options.mock) {
import chalk from 'chalk'; import { Express } from 'express'; import glob from 'glob'; import minimist from 'minimist'; import { IOptions } from './interfaces/IOptions'; import { initServer } from './modules/mockServer'; import { transferTSFile } from './modules/transferTSFile'; const getUsage = () => `Usage: ${chalk.bold.green('pb2TSApi')} [options] ${chalk.bold.red('[file1.proto file2.proto ...]')} or ${chalk.bold.red('[./**/*.proto]')}`; const getHelp = () => `Help: ${chalk.bold.green('--requestModule -r')}: the request module of you want to set, default is ${chalk.bold.red('\'axios\'')}, you can set to your custom request method, for example ${chalk.bold.red('\'@/request\'')}; ${chalk.bold.green('--baseUrl -b')}: the base url of you want to set, default is ${chalk.bold.red('\'/\'')}, you can set to your api path, for example ${chalk.bold.red('\'/api\'')}; ${chalk.bold.green('--folder -f')}: the folder of you want to save the output files, default is ${chalk.bold.red('\'./api\'')}; ${chalk.bold.green('--root -r')}: the root path set to protobufjs, default is ${chalk.bold.red('the path of this command run')}; ${chalk.bold.green('--optional -o')}: is transfrom d.ts optional to false, because of protobuf 3.0 set all filed is optional, default is ${chalk.bold.red('true')}; ${chalk.bold.green('--mock -m')}: is open mock server, default is ${chalk.bold.red('false')}; ${chalk.bold.green('--port -p')}: mock server port, default is ${chalk.bold.red('3000')}; `; export async function main() { try { const argv = minimist(process.argv.slice(2), { alias: { requestModule: 'r', baseUrl: 'b', folder: 'f', root: 'r', optional: 'o', mock: 'm', port: 'p', help: 'h', }, string: ['requestModule', 'baseUrl', 'folder', 'root', 'port'], boolean: ['optional', 'mock'], default: { requestModule: 'axios', baseUrl: '/', folder: './api', root: process.cwd(), optional: true, mock: false, port: '3000', help: '', }, }); if (argv.help) { process.stderr.write(getHelp()); process.exit(1); } const { _: files } = argv; const options: IOptions = { requestModule: argv.requestModule, baseUrl: argv.baseUrl, folder: argv.folder, root: argv.root, optional: argv.optional, mock: argv.mock, port: argv.port, help: argv.help, }; if (!files.length) { process.stderr.write(getUsage()); process.exit(1); } const protoFiles = await glob(files, { ignore: 'node_modules/**', windowsPathsNoEscape: true }); if (!protoFiles.length) { process.stderr.write(chalk.bold.red(`there is not files for the flowing paths: \n ${files.join('\n')}`)); process.exit(1); } let mockServer: Express; if (options.mock) { mockServer = initServer(options); } await Promise.all(protoFiles.map
(filePath => transferTSFile(filePath, mockServer, options)));
} catch (err) { console.error(err); process.exit(1); } } main();
src/index.ts
xingbofeng-protobuf-to-ts-api-aec9dc6
[ { "filename": "src/modules/transferTSFile.ts", "retrieved_chunk": "import { saveTypeScriptDefineFile } from './saveTypeScriptDefineFile';\n/**\n * 转换protobuf定义文件为ts定义文件和api请求文件\n * @param {String} filePath protobuf定义文件的路径\n * @param {Express} mockServer mockServer对象,是一个express实例化的对象\n * @param {Object} options 用户自定义配置\n */\nexport async function transferTSFile(filePath: string, mockServer: Express, options: IOptions) {\n const pbjsFilePath = await getPbjsFile(filePath, options);\n const pbtsFilePath = await getPbtsFile(pbjsFilePath, options);", "score": 21.505284833854365 }, { "filename": "src/modules/transferTSFile.ts", "retrieved_chunk": " await fs.promises.unlink(pbjsFilePath);\n await saveTypeScriptDefineFile(pbtsFilePath, options);\n await saveApiFile(pbtsFilePath, options);\n const jsonSchemaFilePath = await saveJSONSchemaFile(pbtsFilePath);\n const mockFilePath = await saveMockJSONFile(jsonSchemaFilePath);\n console.log(`success generate ${filePath} to ${path.resolve(options.folder, filePath)}.d.ts and ${path.resolve(options.folder, filePath)}.ts`);\n if (options.mock && mockServer) {\n console.log('begin open mock server');\n await generateMockRoute(mockFilePath, mockServer, options);\n }", "score": 18.10282188134204 }, { "filename": "src/modules/getPbjsFile.ts", "retrieved_chunk": " const { folder = '' } = options;\n const fileName = filePath.replace('.proto', '.js');\n const pbjsFilePath = path.resolve(process.cwd(), folder, fileName);\n const p = path.dirname(pbjsFilePath);\n await mkdirp(p);\n return new Promise((resolve, reject) => {\n pbjs.main(['-p', options.root, '-t', 'static-module', '-w', 'commonjs', '-o', pbjsFilePath, path.resolve(process.cwd(), filePath)], err => {\n if (err) {\n reject(err);\n }", "score": 15.710035613301079 }, { "filename": "src/modules/mockServer.ts", "retrieved_chunk": " * @param {Express} mockServer express server 对象\n * @param {IOptions} options 用户自定义配置\n */\nexport async function generateMockRoute(mockFilePath: string, mockServer: Express, options: IOptions) {\n const { baseUrl } = options;\n const mockFile = await fs.promises.readFile(mockFilePath, { encoding: 'utf-8' });\n const json = JSON.parse(mockFile);\n for (const apiName in json) {\n if (Object.hasOwnProperty.call(json, apiName)) {\n const requestMethod = getRequestMethod(apiName);", "score": 13.631644251382612 }, { "filename": "src/modules/mockServer.ts", "retrieved_chunk": "import express, { Express } from 'express';\nimport fs from 'fs';\nimport { IOptions } from '../interfaces/IOptions';\nimport { getRequestMethod } from '../utils/getRequestMethod';\n/**\n * 初始化 mock server\n * @param {IOptions} options 用户自定义配置\n * @returns {Express} mockServer 通过express实例化的mock server app\n */\nexport function initServer(options: IOptions) {", "score": 13.054497512000264 } ]
typescript
(filePath => transferTSFile(filePath, mockServer, options)));
import chalk from 'chalk'; import { Express } from 'express'; import glob from 'glob'; import minimist from 'minimist'; import { IOptions } from './interfaces/IOptions'; import { initServer } from './modules/mockServer'; import { transferTSFile } from './modules/transferTSFile'; const getUsage = () => `Usage: ${chalk.bold.green('pb2TSApi')} [options] ${chalk.bold.red('[file1.proto file2.proto ...]')} or ${chalk.bold.red('[./**/*.proto]')}`; const getHelp = () => `Help: ${chalk.bold.green('--requestModule -r')}: the request module of you want to set, default is ${chalk.bold.red('\'axios\'')}, you can set to your custom request method, for example ${chalk.bold.red('\'@/request\'')}; ${chalk.bold.green('--baseUrl -b')}: the base url of you want to set, default is ${chalk.bold.red('\'/\'')}, you can set to your api path, for example ${chalk.bold.red('\'/api\'')}; ${chalk.bold.green('--folder -f')}: the folder of you want to save the output files, default is ${chalk.bold.red('\'./api\'')}; ${chalk.bold.green('--root -r')}: the root path set to protobufjs, default is ${chalk.bold.red('the path of this command run')}; ${chalk.bold.green('--optional -o')}: is transfrom d.ts optional to false, because of protobuf 3.0 set all filed is optional, default is ${chalk.bold.red('true')}; ${chalk.bold.green('--mock -m')}: is open mock server, default is ${chalk.bold.red('false')}; ${chalk.bold.green('--port -p')}: mock server port, default is ${chalk.bold.red('3000')}; `; export async function main() { try { const argv = minimist(process.argv.slice(2), { alias: { requestModule: 'r', baseUrl: 'b', folder: 'f', root: 'r', optional: 'o', mock: 'm', port: 'p', help: 'h', }, string: ['requestModule', 'baseUrl', 'folder', 'root', 'port'], boolean: ['optional', 'mock'], default: { requestModule: 'axios', baseUrl: '/', folder: './api', root: process.cwd(), optional: true, mock: false, port: '3000', help: '', }, }); if (argv.help) { process.stderr.write(getHelp()); process.exit(1); } const { _: files } = argv; const options: IOptions = { requestModule: argv.requestModule, baseUrl: argv.baseUrl, folder: argv.folder, root: argv.root, optional: argv.optional, mock: argv.mock, port: argv.port, help: argv.help, }; if (!files.length) { process.stderr.write(getUsage()); process.exit(1); } const protoFiles = await glob(files, { ignore: 'node_modules/**', windowsPathsNoEscape: true }); if (!protoFiles.length) { process.stderr.write(chalk.bold.red(`there is not files for the flowing paths: \n ${files.join('\n')}`)); process.exit(1); } let mockServer: Express; if (options.mock) { mockServer = initServer(options); }
await Promise.all(protoFiles.map(filePath => transferTSFile(filePath, mockServer, options)));
} catch (err) { console.error(err); process.exit(1); } } main();
src/index.ts
xingbofeng-protobuf-to-ts-api-aec9dc6
[ { "filename": "src/modules/transferTSFile.ts", "retrieved_chunk": "import { saveTypeScriptDefineFile } from './saveTypeScriptDefineFile';\n/**\n * 转换protobuf定义文件为ts定义文件和api请求文件\n * @param {String} filePath protobuf定义文件的路径\n * @param {Express} mockServer mockServer对象,是一个express实例化的对象\n * @param {Object} options 用户自定义配置\n */\nexport async function transferTSFile(filePath: string, mockServer: Express, options: IOptions) {\n const pbjsFilePath = await getPbjsFile(filePath, options);\n const pbtsFilePath = await getPbtsFile(pbjsFilePath, options);", "score": 23.887958855890698 }, { "filename": "src/modules/transferTSFile.ts", "retrieved_chunk": " await fs.promises.unlink(pbjsFilePath);\n await saveTypeScriptDefineFile(pbtsFilePath, options);\n await saveApiFile(pbtsFilePath, options);\n const jsonSchemaFilePath = await saveJSONSchemaFile(pbtsFilePath);\n const mockFilePath = await saveMockJSONFile(jsonSchemaFilePath);\n console.log(`success generate ${filePath} to ${path.resolve(options.folder, filePath)}.d.ts and ${path.resolve(options.folder, filePath)}.ts`);\n if (options.mock && mockServer) {\n console.log('begin open mock server');\n await generateMockRoute(mockFilePath, mockServer, options);\n }", "score": 20.905871574989806 }, { "filename": "src/modules/getPbjsFile.ts", "retrieved_chunk": " const { folder = '' } = options;\n const fileName = filePath.replace('.proto', '.js');\n const pbjsFilePath = path.resolve(process.cwd(), folder, fileName);\n const p = path.dirname(pbjsFilePath);\n await mkdirp(p);\n return new Promise((resolve, reject) => {\n pbjs.main(['-p', options.root, '-t', 'static-module', '-w', 'commonjs', '-o', pbjsFilePath, path.resolve(process.cwd(), filePath)], err => {\n if (err) {\n reject(err);\n }", "score": 17.642464121184595 }, { "filename": "src/modules/mockServer.ts", "retrieved_chunk": " * @param {Express} mockServer express server 对象\n * @param {IOptions} options 用户自定义配置\n */\nexport async function generateMockRoute(mockFilePath: string, mockServer: Express, options: IOptions) {\n const { baseUrl } = options;\n const mockFile = await fs.promises.readFile(mockFilePath, { encoding: 'utf-8' });\n const json = JSON.parse(mockFile);\n for (const apiName in json) {\n if (Object.hasOwnProperty.call(json, apiName)) {\n const requestMethod = getRequestMethod(apiName);", "score": 15.627722648571249 }, { "filename": "src/modules/mockServer.ts", "retrieved_chunk": "import express, { Express } from 'express';\nimport fs from 'fs';\nimport { IOptions } from '../interfaces/IOptions';\nimport { getRequestMethod } from '../utils/getRequestMethod';\n/**\n * 初始化 mock server\n * @param {IOptions} options 用户自定义配置\n * @returns {Express} mockServer 通过express实例化的mock server app\n */\nexport function initServer(options: IOptions) {", "score": 13.054497512000264 } ]
typescript
await Promise.all(protoFiles.map(filePath => transferTSFile(filePath, mockServer, options)));
import chalk from 'chalk'; import { Express } from 'express'; import glob from 'glob'; import minimist from 'minimist'; import { IOptions } from './interfaces/IOptions'; import { initServer } from './modules/mockServer'; import { transferTSFile } from './modules/transferTSFile'; const getUsage = () => `Usage: ${chalk.bold.green('pb2TSApi')} [options] ${chalk.bold.red('[file1.proto file2.proto ...]')} or ${chalk.bold.red('[./**/*.proto]')}`; const getHelp = () => `Help: ${chalk.bold.green('--requestModule -r')}: the request module of you want to set, default is ${chalk.bold.red('\'axios\'')}, you can set to your custom request method, for example ${chalk.bold.red('\'@/request\'')}; ${chalk.bold.green('--baseUrl -b')}: the base url of you want to set, default is ${chalk.bold.red('\'/\'')}, you can set to your api path, for example ${chalk.bold.red('\'/api\'')}; ${chalk.bold.green('--folder -f')}: the folder of you want to save the output files, default is ${chalk.bold.red('\'./api\'')}; ${chalk.bold.green('--root -r')}: the root path set to protobufjs, default is ${chalk.bold.red('the path of this command run')}; ${chalk.bold.green('--optional -o')}: is transfrom d.ts optional to false, because of protobuf 3.0 set all filed is optional, default is ${chalk.bold.red('true')}; ${chalk.bold.green('--mock -m')}: is open mock server, default is ${chalk.bold.red('false')}; ${chalk.bold.green('--port -p')}: mock server port, default is ${chalk.bold.red('3000')}; `; export async function main() { try { const argv = minimist(process.argv.slice(2), { alias: { requestModule: 'r', baseUrl: 'b', folder: 'f', root: 'r', optional: 'o', mock: 'm', port: 'p', help: 'h', }, string: ['requestModule', 'baseUrl', 'folder', 'root', 'port'], boolean: ['optional', 'mock'], default: { requestModule: 'axios', baseUrl: '/', folder: './api', root: process.cwd(), optional: true, mock: false, port: '3000', help: '', }, }); if (argv.help) { process.stderr.write(getHelp()); process.exit(1); } const { _: files } = argv;
const options: IOptions = {
requestModule: argv.requestModule, baseUrl: argv.baseUrl, folder: argv.folder, root: argv.root, optional: argv.optional, mock: argv.mock, port: argv.port, help: argv.help, }; if (!files.length) { process.stderr.write(getUsage()); process.exit(1); } const protoFiles = await glob(files, { ignore: 'node_modules/**', windowsPathsNoEscape: true }); if (!protoFiles.length) { process.stderr.write(chalk.bold.red(`there is not files for the flowing paths: \n ${files.join('\n')}`)); process.exit(1); } let mockServer: Express; if (options.mock) { mockServer = initServer(options); } await Promise.all(protoFiles.map(filePath => transferTSFile(filePath, mockServer, options))); } catch (err) { console.error(err); process.exit(1); } } main();
src/index.ts
xingbofeng-protobuf-to-ts-api-aec9dc6
[ { "filename": "src/interfaces/IOptions.ts", "retrieved_chunk": "export interface IOptions {\n requestModule: string;\n baseUrl: string;\n folder: string;\n root: string;\n optional: boolean;\n mock: boolean;\n port: string;\n help: string;\n}", "score": 11.875661338115822 }, { "filename": "src/modules/mockServer.ts", "retrieved_chunk": " const mockServer = express();\n const { port = '3000' } = options;\n mockServer.listen(+port, () => {\n console.log(`mock server listening on port ${port}`);\n });\n return mockServer;\n}\n/**\n * 拿到mock文件,生成mock server\n * @param {String} mockFilePath mock文件的路径", "score": 10.798534511266334 }, { "filename": "src/modules/getPbjsFile.ts", "retrieved_chunk": " const { folder = '' } = options;\n const fileName = filePath.replace('.proto', '.js');\n const pbjsFilePath = path.resolve(process.cwd(), folder, fileName);\n const p = path.dirname(pbjsFilePath);\n await mkdirp(p);\n return new Promise((resolve, reject) => {\n pbjs.main(['-p', options.root, '-t', 'static-module', '-w', 'commonjs', '-o', pbjsFilePath, path.resolve(process.cwd(), filePath)], err => {\n if (err) {\n reject(err);\n }", "score": 8.7471587856132 }, { "filename": "src/modules/getPbtsFile.ts", "retrieved_chunk": " const pbtsFilePath = path.resolve(process.cwd(), folder, pbjsFilePath.replace('.js', '.d.ts'));\n return new Promise((resolve, reject) => {\n pbts.main(['-p', options.root, '-o', pbtsFilePath, pbjsFilePath], err => {\n if (err) {\n reject(err);\n }\n resolve(pbtsFilePath);\n });\n });\n}", "score": 7.201791708238562 }, { "filename": "src/modules/saveJSONSchemaFile.ts", "retrieved_chunk": " required: true,\n };\n const compilerOptions = {\n strictNullChecks: true,\n };\n const program = getProgramFromFiles([path.resolve(pbtsFilePath)], compilerOptions, process.cwd());\n const generator = buildGenerator(program, settings);\n const symbols = (generator?.getUserSymbols() || []).filter(symbol => /I(\\S*)Rsp$/.test(symbol));\n const schema = generator?.getSchemaForSymbols(symbols);\n const jsonSchemaFilePath = pbtsFilePath.replace('.d.ts', '.json');", "score": 6.249091949255167 } ]
typescript
const options: IOptions = {
import chalk from 'chalk'; import { Express } from 'express'; import glob from 'glob'; import minimist from 'minimist'; import { IOptions } from './interfaces/IOptions'; import { initServer } from './modules/mockServer'; import { transferTSFile } from './modules/transferTSFile'; const getUsage = () => `Usage: ${chalk.bold.green('pb2TSApi')} [options] ${chalk.bold.red('[file1.proto file2.proto ...]')} or ${chalk.bold.red('[./**/*.proto]')}`; const getHelp = () => `Help: ${chalk.bold.green('--requestModule -r')}: the request module of you want to set, default is ${chalk.bold.red('\'axios\'')}, you can set to your custom request method, for example ${chalk.bold.red('\'@/request\'')}; ${chalk.bold.green('--baseUrl -b')}: the base url of you want to set, default is ${chalk.bold.red('\'/\'')}, you can set to your api path, for example ${chalk.bold.red('\'/api\'')}; ${chalk.bold.green('--folder -f')}: the folder of you want to save the output files, default is ${chalk.bold.red('\'./api\'')}; ${chalk.bold.green('--root -r')}: the root path set to protobufjs, default is ${chalk.bold.red('the path of this command run')}; ${chalk.bold.green('--optional -o')}: is transfrom d.ts optional to false, because of protobuf 3.0 set all filed is optional, default is ${chalk.bold.red('true')}; ${chalk.bold.green('--mock -m')}: is open mock server, default is ${chalk.bold.red('false')}; ${chalk.bold.green('--port -p')}: mock server port, default is ${chalk.bold.red('3000')}; `; export async function main() { try { const argv = minimist(process.argv.slice(2), { alias: { requestModule: 'r', baseUrl: 'b', folder: 'f', root: 'r', optional: 'o', mock: 'm', port: 'p', help: 'h', }, string: ['requestModule', 'baseUrl', 'folder', 'root', 'port'], boolean: ['optional', 'mock'], default: { requestModule: 'axios', baseUrl: '/', folder: './api', root: process.cwd(), optional: true, mock: false, port: '3000', help: '', }, }); if (argv.help) { process.stderr.write(getHelp()); process.exit(1); } const { _: files } = argv; const options: IOptions = { requestModule: argv.requestModule, baseUrl: argv.baseUrl, folder: argv.folder, root: argv.root, optional: argv.optional, mock: argv.mock, port: argv.port, help: argv.help, }; if (!files.length) { process.stderr.write(getUsage()); process.exit(1); } const protoFiles = await glob(files, { ignore: 'node_modules/**', windowsPathsNoEscape: true }); if (!protoFiles.length) { process.stderr.write(chalk.bold.red(`there is not files for the flowing paths: \n ${files.join('\n')}`)); process.exit(1); } let mockServer: Express; if (options.mock) { mockServer =
initServer(options);
} await Promise.all(protoFiles.map(filePath => transferTSFile(filePath, mockServer, options))); } catch (err) { console.error(err); process.exit(1); } } main();
src/index.ts
xingbofeng-protobuf-to-ts-api-aec9dc6
[ { "filename": "src/modules/mockServer.ts", "retrieved_chunk": " * @param {Express} mockServer express server 对象\n * @param {IOptions} options 用户自定义配置\n */\nexport async function generateMockRoute(mockFilePath: string, mockServer: Express, options: IOptions) {\n const { baseUrl } = options;\n const mockFile = await fs.promises.readFile(mockFilePath, { encoding: 'utf-8' });\n const json = JSON.parse(mockFile);\n for (const apiName in json) {\n if (Object.hasOwnProperty.call(json, apiName)) {\n const requestMethod = getRequestMethod(apiName);", "score": 12.266014247556107 }, { "filename": "src/modules/mockServer.ts", "retrieved_chunk": "import express, { Express } from 'express';\nimport fs from 'fs';\nimport { IOptions } from '../interfaces/IOptions';\nimport { getRequestMethod } from '../utils/getRequestMethod';\n/**\n * 初始化 mock server\n * @param {IOptions} options 用户自定义配置\n * @returns {Express} mockServer 通过express实例化的mock server app\n */\nexport function initServer(options: IOptions) {", "score": 10.962440560572798 }, { "filename": "src/modules/transferTSFile.ts", "retrieved_chunk": " await fs.promises.unlink(pbjsFilePath);\n await saveTypeScriptDefineFile(pbtsFilePath, options);\n await saveApiFile(pbtsFilePath, options);\n const jsonSchemaFilePath = await saveJSONSchemaFile(pbtsFilePath);\n const mockFilePath = await saveMockJSONFile(jsonSchemaFilePath);\n console.log(`success generate ${filePath} to ${path.resolve(options.folder, filePath)}.d.ts and ${path.resolve(options.folder, filePath)}.ts`);\n if (options.mock && mockServer) {\n console.log('begin open mock server');\n await generateMockRoute(mockFilePath, mockServer, options);\n }", "score": 10.837647612123865 }, { "filename": "src/modules/transferTSFile.ts", "retrieved_chunk": "import { saveTypeScriptDefineFile } from './saveTypeScriptDefineFile';\n/**\n * 转换protobuf定义文件为ts定义文件和api请求文件\n * @param {String} filePath protobuf定义文件的路径\n * @param {Express} mockServer mockServer对象,是一个express实例化的对象\n * @param {Object} options 用户自定义配置\n */\nexport async function transferTSFile(filePath: string, mockServer: Express, options: IOptions) {\n const pbjsFilePath = await getPbjsFile(filePath, options);\n const pbtsFilePath = await getPbtsFile(pbjsFilePath, options);", "score": 10.62727564051857 }, { "filename": "src/modules/saveMockJSONFile.ts", "retrieved_chunk": " const jsfResult = await JSONSchemaFaker.resolve(schema.definitions) as JsonObject;\n const json: Record<string, JsonValue> = {};\n for (const key in jsfResult) {\n if (Object.hasOwnProperty.call(jsfResult, key)) {\n const rspNameMatchs = key.match(/I(\\S*)Rsp$/);\n if (rspNameMatchs && rspNameMatchs.length) {\n const apiName = rspNameMatchs[1];\n json[apiName] = jsfResult[key];\n }\n }", "score": 10.067478761664201 } ]
typescript
initServer(options);
import {NumberRange} from "../geometry/number-range"; import {Rect} from "../geometry/rect"; import {Vector} from "../geometry/vector"; // Note that some browsers, such as Firefox, do not concatenate properties // into their shorthand (e.g. padding-top, padding-bottom etc. -> padding), // so we have to list every single property explicitly. const propertiesToCopy = [ "direction", // RTL support "boxSizing", "width", // on Chrome and IE, exclude the scrollbar, so the mirror div wraps exactly as the textarea does "height", "overflowX", "overflowY", // copy the scrollbar for IE "borderTopWidth", "borderRightWidth", "borderBottomWidth", "borderLeftWidth", "borderStyle", "paddingTop", "paddingRight", "paddingBottom", "paddingLeft", // https://developer.mozilla.org/en-US/docs/Web/CSS/font "fontStyle", "fontVariant", "fontWeight", "fontStretch", "fontSize", "fontSizeAdjust", "lineHeight", "fontFamily", "textAlign", "textTransform", "textIndent", "textDecoration", // might not make a difference, but better be safe "letterSpacing", "wordSpacing", "tabSize", "MozTabSize" as "tabSize", // prefixed version for Firefox <= 52 ] as const satisfies ReadonlyArray<keyof CSSStyleDeclaration>; export interface RangeRectCalculator { /** * Return the viewport-relative client rects of the range of characters. If the range * has any line breaks, this will return multiple rects. Will include the start char and * exclude the end char. */ getClientRects({start, end}: NumberRange): Rect[]; disconnect(): void; } /** * The `Range` API doesn't work well with `textarea` elements, so this creates a duplicate * element and uses that instead. Provides a limited API wrapping around adjusted `Range` * APIs. */ export class TextareaRangeRectCalculator implements RangeRectCalculator { readonly #element: HTMLTextAreaElement; readonly #div: HTMLDivElement; readonly #mutationObserver: MutationObserver; readonly #resizeObserver: ResizeObserver; readonly #range: Range; constructor(target: HTMLTextAreaElement) { this.#element = target; // The mirror div will replicate the textarea's style const div = document.createElement("div"); this.#div = div; document.body.appendChild(div); this.#refreshStyles(); this.#mutationObserver = new MutationObserver(() => this.#refreshStyles()); this.#mutationObserver.observe(this.#element, { attributeFilter: ["style"], }); this.#resizeObserver = new ResizeObserver(() => this.#refreshStyles()); this.#resizeObserver.observe(this.#element); this.#range = document.createRange(); } /** * Return the viewport-relative client rects of the range. If the range has any line * breaks, this will return multiple rects. Will include the start char and exclude the * end char. */ getClientRects({start, end}: NumberRange) { this.#refreshText(); const textNode = this.#div.childNodes[0]; if (!textNode) return []; this.#range.setStart(textNode, start); this.#range.setEnd(textNode, end); // The div is not in the same place as the textarea so we need to subtract the div // position and add the textarea position const divPosition = new Rect(this.#div.getBoundingClientRect()).asVector(); const textareaPosition = new Rect( this.#element.getBoundingClientRect() ).asVector(); // The div is not scrollable so it does not have scroll adjustment built in const scrollOffset = new Vector( this.#element.scrollLeft, this.#element.scrollTop ); const netTranslate = divPosition .negate() .plus(textareaPosition) .minus(scrollOffset); return Array.from(this.#range.getClientRects()).map((domRect) => new Rect(domRect
).translate(netTranslate) );
} disconnect() { this.#div.remove(); } #refreshStyles() { const style = this.#div.style; const textareaStyle = window.getComputedStyle(this.#element); // Default wrapping styles style.whiteSpace = "pre-wrap"; style.wordWrap = "break-word"; // Position off-screen style.position = "fixed"; style.top = "0"; style.transform = "translateY(-100%)"; const isFirefox = "mozInnerScreenX" in window; // Transfer the element's properties to the div for (const prop of propertiesToCopy) if (prop === "width" && textareaStyle.boxSizing === "border-box") { // With box-sizing: border-box we need to offset the size slightly inwards. This small difference can compound // greatly in long textareas with lots of wrapping, leading to very innacurate results if not accounted for. // Firefox will return computed styles in floats, like `0.9px`, while chromium might return `1px` for the same element. // Either way we use `parseFloat` to turn `0.9px` into `0.9` and `1px` into `1` const totalBorderWidth = parseFloat(textareaStyle.borderLeftWidth) + parseFloat(textareaStyle.borderRightWidth); // When a vertical scrollbar is present it shrinks the content. We need to account for this by using clientWidth // instead of width in everything but Firefox. When we do that we also have to account for the border width. const width = isFirefox ? parseFloat(textareaStyle.width) - totalBorderWidth : this.#element.clientWidth + totalBorderWidth; style.width = `${width}px`; } else { style[prop] = textareaStyle[prop]; } if (isFirefox) { // Firefox lies about the overflow property for textareas: https://bugzilla.mozilla.org/show_bug.cgi?id=984275 if (this.#element.scrollHeight > parseInt(textareaStyle.height)) style.overflowY = "scroll"; } else { style.overflow = "hidden"; // for Chrome to not render a scrollbar; IE keeps overflowY = 'scroll' } } #refreshText() { this.#div.textContent = this.#element instanceof HTMLInputElement ? this.#element.value.replace(/\s/g, "\u00a0") : this.#element.value; } } export class CodeMirrorRangeRectCalculator implements RangeRectCalculator { readonly #element: HTMLElement; readonly #range: Range; constructor(target: HTMLElement) { if (!target.classList.contains("CodeMirror-code")) throw new Error( "CodeMirrorRangeRectCalculator only works with CodeMirror code editors." ); this.#element = target; this.#range = document.createRange(); } getClientRects(range: NumberRange): Rect[] { const lineNodes = Array.from( this.#element.querySelectorAll(".CodeMirror-line") ); const lines = lineNodes.map((line) => CodeMirrorRangeRectCalculator.#getAllTextNodes(line) ); const start = CodeMirrorRangeRectCalculator.#getNodeAtOffset( lines, range.start ); const end = CodeMirrorRangeRectCalculator.#getNodeAtOffset( lines, range.end ); if (!start || !end) return []; this.#range.setStart(...start); this.#range.setEnd(...end); return Array.from(this.#range.getClientRects()).map( (domRect) => new Rect(domRect) ); } disconnect(): void {} static #getAllTextNodes(node: Node): Node[] { const walker = document.createTreeWalker(node, NodeFilter.SHOW_TEXT); const nodes = []; while (walker.nextNode()) nodes.push(walker.currentNode); return nodes; } /** * Get the text node containing the offset, and the relative offset into that node. * @param lines Array of nodes for each line * @param offset Offset into the entire text */ static #getNodeAtOffset( lines: Node[][], offset: number ): [node: Node, offsetIntoNode: number] | undefined { let prevChars = 0; for (const line of lines) { for (const node of line) { const length = node.textContent?.length ?? 0; if (offset <= prevChars + length) return [node, offset - prevChars]; prevChars += length; } prevChars++; // For the newline } } }
src/utilities/dom/range-rect-calculator.ts
iansan5653-github-markdown-a11y-extension-c6a54d0
[ { "filename": "src/components/lint-error-annotation.ts", "retrieved_chunk": " }\n getTooltipPosition() {\n const domRect = this.#elements.at(-1)?.getBoundingClientRect();\n if (domRect)\n return new Rect(domRect)\n .asVector(\"bottom-left\")\n .plus(new Vector(0, 2)) // add some breathing room\n .plus(getWindowScrollVector());\n }\n containsPoint(point: Vector) {", "score": 23.904515776058957 }, { "filename": "src/utilities/geometry/vector.ts", "retrieved_chunk": "/** Represents a 2D vector or point. */\nexport class Vector {\n constructor(readonly x: number, readonly y: number) {}\n plus(other: Vector) {\n return new Vector(this.x + other.x, this.y + other.y);\n }\n minus(other: Vector) {\n return this.plus(other.negate());\n }\n negate() {", "score": 17.299302514020102 }, { "filename": "src/components/linted-markdown-editor.ts", "retrieved_chunk": " });\n }\n override disconnect(): void {\n super.disconnect();\n this.#mutationObserver.disconnect();\n }\n get value() {\n return Array.from(this.#element.querySelectorAll(\".CodeMirror-line\"))\n .map((line) => line.textContent)\n .join(\"\\n\");", "score": 13.278428922673712 }, { "filename": "src/utilities/geometry/rect.ts", "retrieved_chunk": " case \"bottom-left\":\n return new Vector(this.left, this.bottom);\n case \"bottom-right\":\n return new Vector(this.right, this.bottom);\n }\n }\n translate(vector: Vector) {\n return this.copy(this.asVector().plus(vector));\n }\n scaleY(factor: number) {", "score": 11.48870644770392 }, { "filename": "src/components/linted-markdown-editor.ts", "retrieved_chunk": " this.#statusContainer.remove();\n }\n /**\n * Return a list of rects for the given range. If the range extends over multiple lines,\n * multiple rects will be returned.\n */\n getRangeRects(characterIndexes: NumberRange) {\n return this.#rangeRectCalculator.getClientRects(characterIndexes);\n }\n getBoundingClientRect() {", "score": 9.93321103508821 } ]
typescript
).translate(netTranslate) );
import { CodeMirrorRangeRectCalculator, RangeRectCalculator, TextareaRangeRectCalculator, } from "../utilities/dom/range-rect-calculator"; import {formatList} from "../utilities/format"; import {lintMarkdown} from "../utilities/lint-markdown"; import {LintErrorTooltip} from "./lint-error-tooltip"; import {LintErrorAnnotation} from "./lint-error-annotation"; import {Vector} from "../utilities/geometry/vector"; import {NumberRange} from "../utilities/geometry/number-range"; import {Component} from "./component"; export abstract class LintedMarkdownEditor extends Component { #editor: HTMLElement; #tooltip: LintErrorTooltip; #resizeObserver: ResizeObserver; #rangeRectCalculator: RangeRectCalculator; #annotationsPortal = document.createElement("div"); #statusContainer = LintedMarkdownEditor.#createStatusContainerElement(); constructor( element: HTMLElement, portal: HTMLElement, rangeRectCalculator: RangeRectCalculator ) { super(); this.#editor = element; this.#rangeRectCalculator = rangeRectCalculator; portal.append(this.#annotationsPortal, this.#statusContainer); this.addEventListener(element, "focus", this.onUpdate); this.addEventListener(element, "blur", this.#onBlur); this.addEventListener(element, "mousemove", this.#onMouseMove); this.addEventListener(element, "mouseleave", this.#onMouseLeave); // capture ancestor scroll events for nested scroll containers this.addEventListener(document, "scroll", this.#onReposition, true); // selectionchange can't be bound to the textarea so we have to use the document this.addEventListener(document, "selectionchange", this.#onSelectionChange); // annotations are document-relative so we need to observe document resize as well this.addEventListener(window, "resize", this.#onReposition); // this does mean it will run twice when the resize causes a resize of the textarea, // but we also need the resize observer for the textarea because it's user resizable this.#resizeObserver = new ResizeObserver(this.#onReposition); this.#resizeObserver.observe(element); this.#tooltip = new LintErrorTooltip(portal); } disconnect() { super.disconnect(); this.#resizeObserver.disconnect(); this.#rangeRectCalculator.disconnect(); this.#tooltip.disconnect(); this.#annotationsPortal.remove(); this.#statusContainer.remove(); } /** * Return a list of rects for the given range. If the range extends over multiple lines, * multiple rects will be returned. */ getRangeRects(characterIndexes: NumberRange) { return this.#rangeRectCalculator.getClientRects(characterIndexes); } getBoundingClientRect() { return this.#editor.getBoundingClientRect(); } getLineHeight() { const parsed = parseInt(getComputedStyle(this.#editor).lineHeight, 10); return Number.isNaN(parsed) ? undefined : parsed; } abstract get value(): string; abstract get caretPosition(): number; #_annotations: readonly LintErrorAnnotation[] = []; set #annotations(annotations: ReadonlyArray<LintErrorAnnotation>) { if (annotations === this.#_annotations) return; this.#_annotations = annotations; this.#statusContainer.textContent = annotations.length > 0 ? `${annotations.length} Markdown problem${ annotations.length > 1 ? "s" : "" } identified: see line${ annotations.length > 1 ? "s" : "" } ${formatList( annotations.map((a) => a.lineNumber.toString()), "and" )}` : ""; } get #annotations() { return this.#_annotations; } #_tooltipAnnotations: readonly LintErrorAnnotation[] = []; set #tooltipAnnotations(annotations: LintErrorAnnotation[]) { if (annotations === this.#_tooltipAnnotations) return; this.#_tooltipAnnotations = annotations; const position = annotations[0]?.getTooltipPosition(); const errors = annotations.map(({error}) => error); if (position) this.#tooltip.show(errors, position); else this.#tooltip.hide(); } protected onUpdate = () => this.#lint(); #isOnRepositionTick = false; #onReposition = () => { if (this.#isOnRepositionTick) return; this.#isOnRepositionTick = true; requestAnimationFrame(() => { this.#recalculateAnnotationPositions(); this.#isOnRepositionTick = false; }); }; #onBlur = () => this.#clear(); #onMouseMove = (event: MouseEvent) => this.#updatePointerTooltip(new Vector(event.clientX, event.clientY)); #onMouseLeave = () => (this.#tooltipAnnotations = []); #onSelectionChange = () => { // this event only works when applied to the document but we can filter it by detecting focus if (document.activeElement === this.#editor) this.#updateCaretTooltip(); }; #clear() { // the annotations will clean themselves up too but this is slightly faster this.#annotationsPortal.replaceChildren(); for (const annotation of this.#annotations) annotation.disconnect(); this.#annotations = []; this.#tooltipAnnotations = []; } #lint() { this.#clear(); // clear() will not hide the tooltip if the mouse is over it, but if the user is typing then they are not trying to copy content this.#tooltip.hide(true); if (document.activeElement !== this.#editor) return; const errors = lintMarkdown(this.value); this.#annotations = errors.map( (error) => new LintErrorAnnotation(error, this, this.#annotationsPortal) ); } #recalculateAnnotationPositions() { for (const annotation of this.#annotations) annotation.recalculatePosition(); } #updatePointerTooltip(pointerLocation: Vector) { // can't use mouse events on annotations (the easy way) because they have pointer-events: none this.#tooltipAnnotations = this.#annotations.filter((a) => a.containsPoint(pointerLocation) ); } #updateCaretTooltip() { this.#tooltipAnnotations = this.#annotations.filter((a) =>
a.containsIndex(this.caretPosition) );
} static #createStatusContainerElement() { const container = document.createElement("p"); container.setAttribute("aria-live", "polite"); container.style.position = "absolute"; container.style.clipPath = "circle(0)"; return container; } } export class LintedMarkdownTextareaEditor extends LintedMarkdownEditor { readonly #textarea: HTMLTextAreaElement; constructor(textarea: HTMLTextAreaElement, portal: HTMLElement) { super(textarea, portal, new TextareaRangeRectCalculator(textarea)); this.#textarea = textarea; this.addEventListener(textarea, "input", this.onUpdate); } get value() { return this.#textarea.value; } get caretPosition() { return this.#textarea.selectionEnd !== this.#textarea.selectionStart ? -1 : this.#textarea.selectionStart; } } export class LintedMarkdownCodeMirrorEditor extends LintedMarkdownEditor { readonly #element: HTMLElement; readonly #mutationObserver: MutationObserver; constructor(element: HTMLElement, portal: HTMLElement) { super(element, portal, new CodeMirrorRangeRectCalculator(element)); this.#element = element; this.#mutationObserver = new MutationObserver(this.onUpdate); this.#mutationObserver.observe(element, { childList: true, subtree: true, }); } override disconnect(): void { super.disconnect(); this.#mutationObserver.disconnect(); } get value() { return Array.from(this.#element.querySelectorAll(".CodeMirror-line")) .map((line) => line.textContent) .join("\n"); } get caretPosition() { const selection = document.getSelection(); const range = selection?.getRangeAt(0); if (!range?.collapsed || selection?.rangeCount !== 1) return -1; const referenceRange = document.createRange(); referenceRange.selectNodeContents(this.#element); referenceRange.setEnd(range.startContainer, range.startOffset); return referenceRange.toString().length; } }
src/components/linted-markdown-editor.ts
iansan5653-github-markdown-a11y-extension-c6a54d0
[ { "filename": "src/utilities/dom/range-rect-calculator.ts", "retrieved_chunk": " * The `Range` API doesn't work well with `textarea` elements, so this creates a duplicate\n * element and uses that instead. Provides a limited API wrapping around adjusted `Range`\n * APIs.\n */\nexport class TextareaRangeRectCalculator implements RangeRectCalculator {\n readonly #element: HTMLTextAreaElement;\n readonly #div: HTMLDivElement;\n readonly #mutationObserver: MutationObserver;\n readonly #resizeObserver: ResizeObserver;\n readonly #range: Range;", "score": 19.161634382554432 }, { "filename": "src/utilities/geometry/vector.ts", "retrieved_chunk": "/** Represents a 2D vector or point. */\nexport class Vector {\n constructor(readonly x: number, readonly y: number) {}\n plus(other: Vector) {\n return new Vector(this.x + other.x, this.y + other.y);\n }\n minus(other: Vector) {\n return this.plus(other.negate());\n }\n negate() {", "score": 17.840941575220878 }, { "filename": "src/utilities/lint-markdown.ts", "retrieved_chunk": " },\n config: markdownlintGitHub.init({\n default: false,\n \"no-reversed-links\": true,\n \"no-empty-links\": true,\n // While enforcing a certain unordered list style can be somewhat helpful for making the Markdown source\n // easier to read with a screen reader, this rule is ultimately too opinionated and noisy to be worth it,\n // especially because it conflicts with the editor's bulleted list toolbar button.\n \"ul-style\": false,\n }),", "score": 17.245656626528774 }, { "filename": "src/components/lint-error-annotation.ts", "retrieved_chunk": " const scrollVector = getWindowScrollVector();\n // The range rectangles are tight around the characters; we'd rather fill the line height if possible\n const cssLineHeight = this.#editor.getLineHeight();\n const elements: HTMLElement[] = [];\n // render an annotation element for each line separately\n for (const rect of this.#editor.getRangeRects(this.#indexRange)) {\n // suppress when out of bounds\n if (!rect.isContainedBy(editorRect)) continue;\n // The rects are viewport-relative, but the annotations are absolute positioned\n // (document-relative) so we have to add the window scroll position", "score": 17.03448650987273 }, { "filename": "src/utilities/dom/range-rect-calculator.ts", "retrieved_chunk": " if (this.#element.scrollHeight > parseInt(textareaStyle.height))\n style.overflowY = \"scroll\";\n } else {\n style.overflow = \"hidden\"; // for Chrome to not render a scrollbar; IE keeps overflowY = 'scroll'\n }\n }\n #refreshText() {\n this.#div.textContent =\n this.#element instanceof HTMLInputElement\n ? this.#element.value.replace(/\\s/g, \"\\u00a0\")", "score": 15.727423256575314 } ]
typescript
a.containsIndex(this.caretPosition) );
import { CodeMirrorRangeRectCalculator, RangeRectCalculator, TextareaRangeRectCalculator, } from "../utilities/dom/range-rect-calculator"; import {formatList} from "../utilities/format"; import {lintMarkdown} from "../utilities/lint-markdown"; import {LintErrorTooltip} from "./lint-error-tooltip"; import {LintErrorAnnotation} from "./lint-error-annotation"; import {Vector} from "../utilities/geometry/vector"; import {NumberRange} from "../utilities/geometry/number-range"; import {Component} from "./component"; export abstract class LintedMarkdownEditor extends Component { #editor: HTMLElement; #tooltip: LintErrorTooltip; #resizeObserver: ResizeObserver; #rangeRectCalculator: RangeRectCalculator; #annotationsPortal = document.createElement("div"); #statusContainer = LintedMarkdownEditor.#createStatusContainerElement(); constructor( element: HTMLElement, portal: HTMLElement, rangeRectCalculator: RangeRectCalculator ) { super(); this.#editor = element; this.#rangeRectCalculator = rangeRectCalculator; portal.append(this.#annotationsPortal, this.#statusContainer); this.addEventListener(element, "focus", this.onUpdate); this.addEventListener(element, "blur", this.#onBlur); this.addEventListener(element, "mousemove", this.#onMouseMove); this.addEventListener(element, "mouseleave", this.#onMouseLeave); // capture ancestor scroll events for nested scroll containers this.addEventListener(document, "scroll", this.#onReposition, true); // selectionchange can't be bound to the textarea so we have to use the document this.addEventListener(document, "selectionchange", this.#onSelectionChange); // annotations are document-relative so we need to observe document resize as well this.addEventListener(window, "resize", this.#onReposition); // this does mean it will run twice when the resize causes a resize of the textarea, // but we also need the resize observer for the textarea because it's user resizable this.#resizeObserver = new ResizeObserver(this.#onReposition); this.#resizeObserver.observe(element); this.#tooltip = new LintErrorTooltip(portal); } disconnect() { super.disconnect(); this.#resizeObserver.disconnect(); this.#rangeRectCalculator.disconnect(); this.#tooltip.disconnect(); this.#annotationsPortal.remove(); this.#statusContainer.remove(); } /** * Return a list of rects for the given range. If the range extends over multiple lines, * multiple rects will be returned. */ getRangeRects(characterIndexes: NumberRange) { return this.#rangeRectCalculator.getClientRects(characterIndexes); } getBoundingClientRect() { return this.#editor.getBoundingClientRect(); } getLineHeight() { const parsed = parseInt(getComputedStyle(this.#editor).lineHeight, 10); return Number.isNaN(parsed) ? undefined : parsed; } abstract get value(): string; abstract get caretPosition(): number; #_annotations: readonly LintErrorAnnotation[] = []; set #annotations(annotations: ReadonlyArray<LintErrorAnnotation>) { if (annotations === this.#_annotations) return; this.#_annotations = annotations; this.#statusContainer.textContent = annotations.length > 0 ? `${annotations.length} Markdown problem${ annotations.length > 1 ? "s" : "" } identified: see line${ annotations.length > 1 ? "s" : "" } ${formatList( annotations.map((a) => a.lineNumber.toString()), "and" )}` : ""; } get #annotations() { return this.#_annotations; } #_tooltipAnnotations: readonly LintErrorAnnotation[] = []; set #tooltipAnnotations(annotations: LintErrorAnnotation[]) { if (annotations === this.#_tooltipAnnotations) return; this.#_tooltipAnnotations = annotations; const position = annotations[0]?.getTooltipPosition(); const errors = annotations.map(({error}) => error); if (position) this.#tooltip.show(errors, position); else this.#tooltip.hide(); } protected onUpdate = () => this.#lint(); #isOnRepositionTick = false; #onReposition = () => { if (this.#isOnRepositionTick) return; this.#isOnRepositionTick = true; requestAnimationFrame(() => { this.#recalculateAnnotationPositions(); this.#isOnRepositionTick = false; }); }; #onBlur = () => this.#clear(); #onMouseMove = (event: MouseEvent) => this.#updatePointerTooltip(new Vector(event.clientX, event.clientY)); #onMouseLeave = () => (this.#tooltipAnnotations = []); #onSelectionChange = () => { // this event only works when applied to the document but we can filter it by detecting focus if (document.activeElement === this.#editor) this.#updateCaretTooltip(); }; #clear() { // the annotations will clean themselves up too but this is slightly faster this.#annotationsPortal.replaceChildren(); for (const annotation of this.#annotations) annotation.disconnect(); this.#annotations = []; this.#tooltipAnnotations = []; } #lint() { this.#clear(); // clear() will not hide the tooltip if the mouse is over it, but if the user is typing then they are not trying to copy content this.#tooltip.hide(true); if (document.activeElement !== this.#editor) return; const errors = lintMarkdown(this.value); this.#annotations = errors.map( (error) => new LintErrorAnnotation(error, this, this.#annotationsPortal) ); } #recalculateAnnotationPositions() { for (const annotation of this.#annotations) annotation.recalculatePosition(); } #updatePointerTooltip(pointerLocation: Vector) { // can't use mouse events on annotations (the easy way) because they have pointer-events: none this.#tooltipAnnotations = this.#annotations.filter((a) =>
a.containsPoint(pointerLocation) );
} #updateCaretTooltip() { this.#tooltipAnnotations = this.#annotations.filter((a) => a.containsIndex(this.caretPosition) ); } static #createStatusContainerElement() { const container = document.createElement("p"); container.setAttribute("aria-live", "polite"); container.style.position = "absolute"; container.style.clipPath = "circle(0)"; return container; } } export class LintedMarkdownTextareaEditor extends LintedMarkdownEditor { readonly #textarea: HTMLTextAreaElement; constructor(textarea: HTMLTextAreaElement, portal: HTMLElement) { super(textarea, portal, new TextareaRangeRectCalculator(textarea)); this.#textarea = textarea; this.addEventListener(textarea, "input", this.onUpdate); } get value() { return this.#textarea.value; } get caretPosition() { return this.#textarea.selectionEnd !== this.#textarea.selectionStart ? -1 : this.#textarea.selectionStart; } } export class LintedMarkdownCodeMirrorEditor extends LintedMarkdownEditor { readonly #element: HTMLElement; readonly #mutationObserver: MutationObserver; constructor(element: HTMLElement, portal: HTMLElement) { super(element, portal, new CodeMirrorRangeRectCalculator(element)); this.#element = element; this.#mutationObserver = new MutationObserver(this.onUpdate); this.#mutationObserver.observe(element, { childList: true, subtree: true, }); } override disconnect(): void { super.disconnect(); this.#mutationObserver.disconnect(); } get value() { return Array.from(this.#element.querySelectorAll(".CodeMirror-line")) .map((line) => line.textContent) .join("\n"); } get caretPosition() { const selection = document.getSelection(); const range = selection?.getRangeAt(0); if (!range?.collapsed || selection?.rangeCount !== 1) return -1; const referenceRange = document.createRange(); referenceRange.selectNodeContents(this.#element); referenceRange.setEnd(range.startContainer, range.startOffset); return referenceRange.toString().length; } }
src/components/linted-markdown-editor.ts
iansan5653-github-markdown-a11y-extension-c6a54d0
[ { "filename": "src/components/lint-error-annotation.ts", "retrieved_chunk": " const scrollVector = getWindowScrollVector();\n // The range rectangles are tight around the characters; we'd rather fill the line height if possible\n const cssLineHeight = this.#editor.getLineHeight();\n const elements: HTMLElement[] = [];\n // render an annotation element for each line separately\n for (const rect of this.#editor.getRangeRects(this.#indexRange)) {\n // suppress when out of bounds\n if (!rect.isContainedBy(editorRect)) continue;\n // The rects are viewport-relative, but the annotations are absolute positioned\n // (document-relative) so we have to add the window scroll position", "score": 22.636649803343307 }, { "filename": "src/components/lint-error-annotation.ts", "retrieved_chunk": " static #createAnnotationElement(rect: Rect) {\n const annotation = document.createElement(\"span\");\n annotation.style.position = \"absolute\";\n annotation.style.boxSizing = \"border-box\";\n // use underline instead of highlight for high contrast\n if (isHighContrastMode()) {\n annotation.style.borderBottom = \"3px dashed var(--color-danger-fg)\";\n } else {\n annotation.style.backgroundColor = \"var(--color-danger-emphasis)\";\n annotation.style.opacity = \"0.2\";", "score": 16.026008721580183 }, { "filename": "src/components/lint-error-annotation.ts", "retrieved_chunk": " }\n annotation.style.pointerEvents = \"none\";\n annotation.style.top = `${rect.top}px`;\n annotation.style.left = `${rect.left}px`;\n annotation.style.width = `${rect.width}px`;\n annotation.style.height = `${rect.height}px`;\n return annotation;\n }\n}", "score": 15.16155677835479 }, { "filename": "src/components/lint-error-annotation.ts", "retrieved_chunk": " (t, l) => t + l.length + 1 /* +1 for newline char */,\n startCol\n );\n const endIndex = startIndex + length;\n this.#indexRange = new NumberRange(startIndex, endIndex);\n this.recalculatePosition();\n }\n disconnect() {\n super.disconnect();\n this.#container.remove();", "score": 14.792619231806984 }, { "filename": "src/components/lint-error-tooltip.ts", "retrieved_chunk": " const availableWidth = document.body.clientWidth - 2 * MARGIN;\n const rightOverflow = Math.max(x + WIDTH - (availableWidth + MARGIN), 0);\n this.#tooltip.style.left = `${Math.max(x - rightOverflow, MARGIN)}px`;\n this.#tooltip.style.maxWidth = `${availableWidth}px`;\n }\n this.#tooltip.removeAttribute(\"hidden\");\n }\n hide(force = false) {\n // Don't hide if the mouse enters the tooltip (allowing users to copy text)\n setTimeout(() => {", "score": 14.03605298482547 } ]
typescript
a.containsPoint(pointerLocation) );
import { CfnResource, Stack } from "aws-cdk-lib"; import { Baselime as Config } from "../config"; import { QueryProps, Filter, DeploymentQueryParameters } from "../types/query"; import { AlertProps } from "../types/alert"; import { Alert } from './alert'; import { getServiceName } from '../utils/service-name'; function buildCalculation(cal: { alias?: string; operation: string; key?: string }) { const short = buildShortCalculation(cal); return `${short}${cal.alias ? ` as ${cal.alias}` : ""}`; } function hasDuplicates<T>(array: T[]) { return (new Set(array)).size !== array.length; } function buildShortCalculation(cal: { alias?: string; operation: string; key?: string }) { if (cal.operation === "COUNT") { return cal.operation; } return `${cal.operation}(${cal.key})`; } function getCalculationAlias(cal: { alias?: string; operation: string; key?: string }) { return cal.alias ? cal.alias : buildShortCalculation(cal); } export function stringifyFilter(filter: Filter): string { const { key, operation, value } = filter; if (!operation) { return `${key} = ${value}`; } if (["EXISTS", "DOES_NOT_EXIST"].includes(operation)) { return `${key} ${operation}`; } if (["IN", "NOT_IN"].some(o => o === operation)) { return `${key} ${operation} (${value})`; } return `${key} ${operation} ${value}`; } /** * */ export class Query<TKey extends string> extends CfnResource { id: string; props: QueryProps<TKey> constructor(id: string, props: QueryProps<TKey>) { const stack = Stack.of(Config.getConstruct()); const calcs = props.parameters.calculations; const orderByOptions =
calcs?.map(cal => getCalculationAlias(cal));
if (calcs?.length && hasDuplicates(calcs.filter(c => c.alias).map(c => c.alias))) { throw Error("Aliases must me unique across all calculations / visualisations.") } if (props.parameters.orderBy && !orderByOptions?.includes(props.parameters.orderBy.value)) { throw Error("The orderBy must be present in the calculations / visualisations.") } const disableStackFilter = props.disableStackFilter || Config.getDisableStackFilter(); if (!disableStackFilter) { props.parameters.filters?.push({ operation: "=", key: "$baselime.stackId", value: stack.stackName }) } const Parameters: DeploymentQueryParameters = { ...props.parameters, datasets: props.parameters.datasets || ['lambda-logs'], calculations: props.parameters.calculations ? props.parameters.calculations.map(buildCalculation) : [], filters: props.parameters.filters?.map(stringifyFilter), groupBys: props.parameters.groupBys?.map(groupBy => { return { ...groupBy, type: groupBy?.type || "string" } }), filterCombination: props.parameters.filterCombination || "AND", }; super(Config.getConstruct(), id, { type: "Custom::BaselimeQuery", properties: { id, ServiceToken: Config.getServiceToken(), BaselimeApiKey: Config.getApiKey(), Description: props.description, Service: getServiceName(stack), Parameters, Origin: "cdk" }, }); this.id = id; this.props = props; } addAlert(alert: ChangeFields<AlertProps<TKey>, { parameters: Omit<AlertProps<TKey>['parameters'], "query"> }>) { const alertProps = { ...alert, parameters: { ...alert.parameters, query: this } } new Alert(`${this.id}-alert`, alertProps); } addFilters(filters: QueryProps<string>["parameters"]["filters"]) { this.addPropertyOverride('Parameters.filters', [...filters || []]) } }; type ChangeFields<T, R> = Omit<T, keyof R> & R;
src/resources/query.ts
baselime-cdk-82637d8
[ { "filename": "src/resources/alert.ts", "retrieved_chunk": "import { CfnResource, Stack } from \"aws-cdk-lib\";\nimport { Baselime as Config } from \"../config\";\nimport { Query } from \"./query\";\nimport { AlertProps, DeploymentAlertParameters } from \"../types/alert\";\nimport { QueryProps } from \"../types/query\";\nimport { getServiceName } from \"../utils/service-name\";\nexport class Alert<TKey extends string> extends CfnResource {\n\tconstructor(id: string, props: AlertProps<TKey>) {\n\t\tconst stack = Stack.of(Config.getConstruct());\n\t\tconst defaultFrequency = \"1hour\";", "score": 51.19444342910969 }, { "filename": "src/resources/dashboard.ts", "retrieved_chunk": "import { CfnResource, Stack } from \"aws-cdk-lib\";\nimport { Baselime as Config } from \"../config\";\nimport { DashboardProps } from \"../types/dashboard\";\nimport { getServiceName } from \"../utils/service-name\";\nexport class Dashboard extends CfnResource {\n\tconstructor(id: string, props: DashboardProps) {\n\t\tconst stack = Stack.of(Config.getConstruct());\n\t\tconst parameters = {\n\t\t\t...props.parameters,\n\t\t\twidgets: props.parameters.widgets.map(el => ({ ...el, query: el.query.ref }))", "score": 43.36719387464417 }, { "filename": "src/types/query.ts", "retrieved_chunk": "import { F } from \"ts-toolbelt\";\nexport type QueryProps<TKey extends string> = {\n\tdescription?: string;\n\tparameters: QueryParameters<TKey>\n\tdisableStackFilter?: boolean\n};\nexport type QueryParameters<TKey extends string> = {\n\tdatasets?: Datasets[];\n\tfilterCombination?: \"AND\" | \"OR\";\n\tfilters: Filter[];", "score": 30.44601486306335 }, { "filename": "src/config.ts", "retrieved_chunk": "\t * @param {BaselimeConfiguration} options\n\t * @example\n\t * import { Baselime } from '@baselime/cdk'\n\t * import * as cdk from 'aws-cdk-lib'\n\t * import { Construct } from 'constructs'\n\t *\n\t * export class ExamplesStack extends cdk.Stack {\n\t * constructor(scope: Construct, id: string, props?: cdk.StackProps) {\n\t * super(scope, id, props)\n\t *", "score": 29.722912654169647 }, { "filename": "src/resources/alert.ts", "retrieved_chunk": "\t\t\t};\n\t\t}\n\t\tif (\"filters\" in props.parameters.query) {\n\t\t\tconst query = new Query(`${id}-query`, {\n\t\t\t\tparameters: {\n\t\t\t\t\t...props.parameters.query,\n\t\t\t\t\tcalculations: props.parameters.query.calculations || [\n\t\t\t\t\t\t{ operation: \"COUNT\" },\n\t\t\t\t\t],\n\t\t\t\t},", "score": 27.317438987433736 } ]
typescript
calcs?.map(cal => getCalculationAlias(cal));
import { CfnResource, Stack } from "aws-cdk-lib"; import { Baselime as Config } from "../config"; import { QueryProps, Filter, DeploymentQueryParameters } from "../types/query"; import { AlertProps } from "../types/alert"; import { Alert } from './alert'; import { getServiceName } from '../utils/service-name'; function buildCalculation(cal: { alias?: string; operation: string; key?: string }) { const short = buildShortCalculation(cal); return `${short}${cal.alias ? ` as ${cal.alias}` : ""}`; } function hasDuplicates<T>(array: T[]) { return (new Set(array)).size !== array.length; } function buildShortCalculation(cal: { alias?: string; operation: string; key?: string }) { if (cal.operation === "COUNT") { return cal.operation; } return `${cal.operation}(${cal.key})`; } function getCalculationAlias(cal: { alias?: string; operation: string; key?: string }) { return cal.alias ? cal.alias : buildShortCalculation(cal); } export function stringifyFilter(filter: Filter): string { const { key, operation, value } = filter; if (!operation) { return `${key} = ${value}`; } if (["EXISTS", "DOES_NOT_EXIST"].includes(operation)) { return `${key} ${operation}`; } if (["IN", "NOT_IN"].some(o => o === operation)) { return `${key} ${operation} (${value})`; } return `${key} ${operation} ${value}`; } /** * */ export class Query<TKey extends string> extends CfnResource { id: string; props: QueryProps<TKey> constructor(id: string, props: QueryProps<TKey>) { const stack = Stack.of(Config.getConstruct()); const calcs = props.parameters.calculations; const orderByOptions = calcs?.map(cal => getCalculationAlias(cal)); if (calcs?.length && hasDuplicates(calcs.filter(c => c.alias).map(c => c.alias))) { throw Error("Aliases must me unique across all calculations / visualisations.") } if (props.parameters.orderBy && !orderByOptions?.includes(props.parameters.orderBy.value)) { throw Error("The orderBy must be present in the calculations / visualisations.") } const disableStackFilter = props.disableStackFilter || Config.getDisableStackFilter(); if (!disableStackFilter) { props.parameters.filters?.push({ operation: "=", key: "$baselime.stackId", value: stack.stackName }) }
const Parameters: DeploymentQueryParameters = {
...props.parameters, datasets: props.parameters.datasets || ['lambda-logs'], calculations: props.parameters.calculations ? props.parameters.calculations.map(buildCalculation) : [], filters: props.parameters.filters?.map(stringifyFilter), groupBys: props.parameters.groupBys?.map(groupBy => { return { ...groupBy, type: groupBy?.type || "string" } }), filterCombination: props.parameters.filterCombination || "AND", }; super(Config.getConstruct(), id, { type: "Custom::BaselimeQuery", properties: { id, ServiceToken: Config.getServiceToken(), BaselimeApiKey: Config.getApiKey(), Description: props.description, Service: getServiceName(stack), Parameters, Origin: "cdk" }, }); this.id = id; this.props = props; } addAlert(alert: ChangeFields<AlertProps<TKey>, { parameters: Omit<AlertProps<TKey>['parameters'], "query"> }>) { const alertProps = { ...alert, parameters: { ...alert.parameters, query: this } } new Alert(`${this.id}-alert`, alertProps); } addFilters(filters: QueryProps<string>["parameters"]["filters"]) { this.addPropertyOverride('Parameters.filters', [...filters || []]) } }; type ChangeFields<T, R> = Omit<T, keyof R> & R;
src/resources/query.ts
baselime-cdk-82637d8
[ { "filename": "src/resources/alert.ts", "retrieved_chunk": "\t\tif (!Parameters) throw new Error(\"Invalid alert parameters. Declare at least one of filters or ref in the query.\")\n\t\tsuper(Config.getConstruct(), id, {\n\t\t\ttype: \"Custom::BaselimeAlert\",\n\t\t\tproperties: {\n\t\t\t\tid,\n\t\t\t\tServiceToken: Config.getServiceToken(),\n\t\t\t\tBaselimeApiKey: Config.getApiKey(),\n\t\t\t\tenabled: props.enabled,\n\t\t\t\tDescription: props.description,\n\t\t\t\tService: getServiceName(stack),", "score": 43.91204906325767 }, { "filename": "src/resources/alert.ts", "retrieved_chunk": "\t\t\t};\n\t\t}\n\t\tif (\"filters\" in props.parameters.query) {\n\t\t\tconst query = new Query(`${id}-query`, {\n\t\t\t\tparameters: {\n\t\t\t\t\t...props.parameters.query,\n\t\t\t\t\tcalculations: props.parameters.query.calculations || [\n\t\t\t\t\t\t{ operation: \"COUNT\" },\n\t\t\t\t\t],\n\t\t\t\t},", "score": 40.86906808566914 }, { "filename": "src/resources/alert.ts", "retrieved_chunk": "\t\tconst defaultWindow = \"1hour\";\n\t\tlet Parameters: DeploymentAlertParameters | undefined = undefined;\n\t\tif (\"ref\" in props.parameters.query) {\n\t\t\tParameters = {\n\t\t\t\t...props.parameters,\n\t\t\t\tthreshold: `${props.parameters.threshold?.operation || \">\"} ${props.parameters.threshold?.value\n\t\t\t\t\t}`,\n\t\t\t\tquery: props.parameters.query.ref,\n\t\t\t\tfrequency: props.parameters.frequency || defaultFrequency,\n\t\t\t\twindow: props.parameters.window || defaultWindow,", "score": 34.32791272890937 }, { "filename": "src/resources/alert.ts", "retrieved_chunk": "\t\t\t});\n\t\t\tParameters = {\n\t\t\t\t...props.parameters,\n\t\t\t\tthreshold: `${props.parameters.threshold?.operation || \">\"} ${props.parameters.threshold?.value || 0\n\t\t\t\t\t}`,\n\t\t\t\tquery: query.ref,\n\t\t\t\tfrequency: props.parameters.frequency || defaultFrequency,\n\t\t\t\twindow: props.parameters.window || defaultWindow,\n\t\t\t};\n\t\t}", "score": 28.373848405408218 }, { "filename": "src/types/query.ts", "retrieved_chunk": "};\nexport type DeploymentQueryParameters = {\n\tdatasets: string[];\n\tcalculations?: string[];\n\tfilterCombination: \"AND\" | \"OR\";\n\tfilters?: string[];\n\tgroupBys?: QueryGroupBy[];\n\torderBy?: {\n\t\tvalue: string;\n\t\torder?: \"ASC\" | \"DESC\";", "score": 24.384926480344838 } ]
typescript
const Parameters: DeploymentQueryParameters = {