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/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": 0.8626762628555298 }, { "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": 0.8247320652008057 }, { "filename": "src/modules/account/service/index.ts", "retrieved_chunk": " },\n { returnOriginal: false },\n );\n destAccount = await Account.findByIdAndUpdate(destAccount, {\n $inc: {\n balance: amount,\n },\n });\n console.log('srcAcc', srcAccount);\n const destUserId = destAccount.user;", "score": 0.8139983415603638 }, { "filename": "src/modules/account/model/index.ts", "retrieved_chunk": "import mongoose, { Document, Model, Schema, model } from 'mongoose';\ninterface AccountAttrs {\n id: string;\n user: string;\n accountType: any;\n balance: number;\n}\ninterface IAccount extends Document {\n id: string;\n user: string;", "score": 0.8138062953948975 }, { "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": 0.809367835521698 } ]
typescript
const newUser = await User.create({
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": " 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": 0.8549710512161255 }, { "filename": "src/constant/swaggerOptions.ts", "retrieved_chunk": " },\n },\n },\n security: [{ bearerAuth: [] }],\n servers: [\n {\n url: 'http://localhost:3000',\n description: 'Development server',\n },\n ],", "score": 0.8177624344825745 }, { "filename": "src/modules/account/model/index.ts", "retrieved_chunk": "import mongoose, { Document, Model, Schema, model } from 'mongoose';\ninterface AccountAttrs {\n id: string;\n user: string;\n accountType: any;\n balance: number;\n}\ninterface IAccount extends Document {\n id: string;\n user: string;", "score": 0.7963523864746094 }, { "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": 0.7901844382286072 }, { "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": 0.7878838181495667 } ]
typescript
export const signup = catchAsync(async (req, res) => {
/** * @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": 0.9000084400177002 }, { "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": 0.8888334035873413 }, { "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": 0.8866318464279175 }, { "filename": "src/modules/auth/controller/index.ts", "retrieved_chunk": " * \"401\":\n * description: Invalid or expired token or refresh token was already used\n */\nrouter.post('/refresh', refreshMiddleware, refresh);\n/**\n * @swagger\n * /api/v1/auth/me:\n * post:\n * summary: Get user profile\n * tags: [Auth]", "score": 0.879890501499176 }, { "filename": "src/modules/auth/controller/index.ts", "retrieved_chunk": " * security:\n * - bearerAuth: []\n * responses:\n * \"200\":\n * description: The user profile\n * \"401\":\n * description: Unauthorized\n */\nrouter.post('/me', protect, getMe);\nexport default router;", "score": 0.8770184516906738 } ]
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": 0.915802001953125 }, { "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": 0.9100673198699951 }, { "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": 0.8724126815795898 }, { "filename": "src/modules/auth/controller/users.ts", "retrieved_chunk": " * summary: Delete a user by ID\n * tags: [User]\n * security:\n * - bearerAuth: []\n * parameters:\n * - in: path\n * name: id\n * schema:\n * type: string\n * required: true", "score": 0.8512394428253174 }, { "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": 0.8490641117095947 } ]
typescript
'/me', protect, getMe);
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": " } else if (req.cookies.jwt) {\n token = req.cookies.jwt;\n }\n console.log({ token });\n if (!token) {\n return next(new AppError('You are not logged in! Please log in to get access.', 401));\n }\n // 2) Verification token\n const decoded = (await verify(token, process.env.JWT_KEY_SECRET as string)) as JwtPayload;\n console.log({ decoded });", "score": 0.8631474375724792 }, { "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": 0.8473331928253174 }, { "filename": "src/modules/auth/model/index.ts", "retrieved_chunk": " },\n});\nuserSchema.pre('save', async function (next) {\n // Only run this function if password was actually modified\n if (!this.isModified('password')) return next();\n // Hash the password with cost of 12\n this.password = await hash(this.password, 12);\n // Delete passwordConfirm field\n next();\n});", "score": 0.8471087217330933 }, { "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": 0.8469362258911133 }, { "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": 0.8440902233123779 } ]
typescript
return next(new AppError('Please provide email and password!', 400));
/** * @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": " * 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": 0.9204448461532593 }, { "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": 0.9127182960510254 }, { "filename": "src/modules/auth/controller/index.ts", "retrieved_chunk": " * security:\n * - bearerAuth: []\n * responses:\n * \"200\":\n * description: The user profile\n * \"401\":\n * description: Unauthorized\n */\nrouter.post('/me', protect, getMe);\nexport default router;", "score": 0.9061654806137085 }, { "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": 0.8821520805358887 }, { "filename": "src/modules/auth/controller/index.ts", "retrieved_chunk": " * \"401\":\n * description: Invalid or expired token or refresh token was already used\n */\nrouter.post('/refresh', refreshMiddleware, refresh);\n/**\n * @swagger\n * /api/v1/auth/me:\n * post:\n * summary: Get user profile\n * tags: [Auth]", "score": 0.8714908361434937 } ]
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": 0.8648285865783691 }, { "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": 0.8266907930374146 }, { "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": 0.82637619972229 }, { "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": 0.8233258724212646 }, { "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": 0.7979257702827454 } ]
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/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": 0.8653203248977661 }, { "filename": "src/constant/swaggerOptions.ts", "retrieved_chunk": " },\n },\n },\n security: [{ bearerAuth: [] }],\n servers: [\n {\n url: 'http://localhost:3000',\n description: 'Development server',\n },\n ],", "score": 0.815880537033081 }, { "filename": "src/modules/account/model/index.ts", "retrieved_chunk": "import mongoose, { Document, Model, Schema, model } from 'mongoose';\ninterface AccountAttrs {\n id: string;\n user: string;\n accountType: any;\n balance: number;\n}\ninterface IAccount extends Document {\n id: string;\n user: string;", "score": 0.8029049038887024 }, { "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": 0.7955483198165894 }, { "filename": "src/modules/account/model/index.ts", "retrieved_chunk": " },\n user: {\n type: mongoose.Types.ObjectId,\n ref: 'User',\n },\n balance: {\n type: Number,\n default: 0,\n },\n});", "score": 0.7920310497283936 } ]
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": 0.8632878661155701 }, { "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": 0.8253593444824219 }, { "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": 0.8248541355133057 }, { "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": 0.8223466277122498 }, { "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": 0.798911988735199 } ]
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": 0.8109390139579773 }, { "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": 0.7971003651618958 }, { "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": 0.7954885959625244 }, { "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": 0.7951069474220276 }, { "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": 0.7915548086166382 } ]
typescript
, next) => {
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/store/store.ts", "retrieved_chunk": "export const loadData = () => {\n const profileData = loadProfiles();\n if (!profileData) {\n return null;\n }\n const { profiles, profile, selectedProfile } = profileData;\n const threads = profile.threadIds\n .map((id) => getThread(id))\n .filter((t) => t !== undefined) as Thread[];\n return { profiles, profile, selectedProfile, threads };", "score": 0.8508017063140869 }, { "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": 0.8487931489944458 }, { "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": 0.843796968460083 }, { "filename": "src/store/store.ts", "retrieved_chunk": " },\n deleteThread: (value: Thread) => {\n deleteThread(value.id);\n set((state) => ({\n threads: state.threads.filter((t) => t.id !== value.id),\n }));\n },\n setSelectedProfile: (value: string) => {\n updateSelectedProfile(value);\n set({ selectedProfile: value });", "score": 0.8286716938018799 }, { "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": 0.8261810541152954 } ]
typescript
{thread.messages.map((message, index) => {
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": 0.8721414804458618 }, { "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": 0.8715741634368896 }, { "filename": "src/modules/auth/model/index.ts", "retrieved_chunk": " },\n});\nuserSchema.pre('save', async function (next) {\n // Only run this function if password was actually modified\n if (!this.isModified('password')) return next();\n // Hash the password with cost of 12\n this.password = await hash(this.password, 12);\n // Delete passwordConfirm field\n next();\n});", "score": 0.8640854358673096 }, { "filename": "src/middleware/protect.ts", "retrieved_chunk": " } else if (req.cookies.jwt) {\n token = req.cookies.jwt;\n }\n console.log({ token });\n if (!token) {\n return next(new AppError('You are not logged in! Please log in to get access.', 401));\n }\n // 2) Verification token\n const decoded = (await verify(token, process.env.JWT_KEY_SECRET as string)) as JwtPayload;\n console.log({ decoded });", "score": 0.8571628332138062 }, { "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": 0.85451740026474 } ]
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": 0.8360746502876282 }, { "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": 0.8028523921966553 }, { "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": 0.7988437414169312 }, { "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": 0.7928603291511536 }, { "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": 0.7896557450294495 } ]
typescript
@requireCredentials private authenticate(options: AuthenticationFields): Promise<AuthenticationResponse> {
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": 0.9380767941474915 }, { "filename": "src/pages/index.tsx", "retrieved_chunk": " </div>\n </div>\n </div>\n )\n}\nconst LicenseCluster = () => {\n const setApiKeyModal = useStore((state) => state.setApiKeyModal)\n const profile = useStore((state) => state.profile)\n return (\n <div className=\"flex items-center justify-center\">", "score": 0.8421325087547302 }, { "filename": "src/pages/index.tsx", "retrieved_chunk": " }\n </div>\n </div>\n </div>\n )\n}\nfunction classNames(...classes: string[]) {\n return classes.filter(Boolean).join(' ')\n}\nconst TopBar = () => {", "score": 0.8413629531860352 }, { "filename": "src/components/ChatWindow/ChatWindow.tsx", "retrieved_chunk": " return (\n <Feature featureName={feature} key={index} />\n )\n })}\n </div>\n </div>\n )\n}\nconst Feature = (props: { featureName: string }) => {\n return (", "score": 0.8410086035728455 }, { "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": 0.8319525122642517 } ]
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/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": 0.9338220953941345 }, { "filename": "src/pages/index.tsx", "retrieved_chunk": " </div>\n </div>\n </div>\n )\n}\nconst LicenseCluster = () => {\n const setApiKeyModal = useStore((state) => state.setApiKeyModal)\n const profile = useStore((state) => state.profile)\n return (\n <div className=\"flex items-center justify-center\">", "score": 0.8496676683425903 }, { "filename": "src/components/ChatWindow/ChatWindow.tsx", "retrieved_chunk": " </div>\n </div>\n </div >\n )\n}\nconst ResizeColumn = () => {\n const width = useStore((state) => state.width)\n const setWidth = useStore((state) => state.setWidth)\n const changeWidthHandler = () => {\n switch (width) {", "score": 0.8315149545669556 }, { "filename": "src/pages/index.tsx", "retrieved_chunk": " }\n </div>\n </div>\n </div>\n )\n}\nfunction classNames(...classes: string[]) {\n return classes.filter(Boolean).join(' ')\n}\nconst TopBar = () => {", "score": 0.8293147683143616 }, { "filename": "src/store/store.ts", "retrieved_chunk": " return { profiles, profile, selectedProfile: profile.id };\n }\n return { profiles, profile, selectedProfile };\n};\nexport const getThread = (id: string) => {\n const raw = localStorage.getItem(\"Thread_\" + id);\n if (raw) {\n return JSON.parse(raw) as Thread;\n }\n};", "score": 0.8228663206100464 } ]
typescript
useStore((state) => state.thread) if (!thread.messages) {
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": 0.8756392002105713 }, { "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": 0.8210270404815674 }, { "filename": "src/decorators/requireCredentials.ts", "retrieved_chunk": "import Kreta from '../lib/Kreta';\nimport Administration from '../lib/Administration';\nimport KretaError from '../lib/errors/KretaError';\nexport default function requireCredentials(target: any, propertyName: string, descriptor: PropertyDescriptor): PropertyDescriptor {\n\tconst originalMethod = descriptor.value;\n\tdescriptor.value = function (...args: any[]) {\n\t\tconst instance: Kreta | Administration = this as Kreta || Administration;\n\t\tif (!instance._username || !instance._password || !instance._institute_code)\n\t\t\tthrow new KretaError('Missing required credentials');\n\t\treturn originalMethod.call(this, ...args);", "score": 0.7618520259857178 }, { "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": 0.7506759166717529 }, { "filename": "src/lib/Authentication.ts", "retrieved_chunk": "import KretaError from './errors/KretaError';\nimport requireParam from '../decorators/requireParam';\nimport tryRequest from '../utils/tryRequest';\nimport requireCredentials from '../decorators/requireCredentials';\nexport class Authentication {\n\tprivate readonly username: string;\n\tprivate readonly password: string;\n\tprivate readonly institute_code: string;\n\tprivate readonly client_id: string = 'kreta-ellenorzo-mobile-android';\n\tprivate readonly grant_type: string = 'password';", "score": 0.736220121383667 } ]
typescript
this.Global = new Global();
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": 0.8801479339599609 }, { "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": 0.8472682237625122 }, { "filename": "src/lib/Kreta.ts", "retrieved_chunk": "\t\t\t\t}\n\t\t\t}).then((r: AxiosResponse<Homework[]>) => resolve(r.data)));\n\t\t});\n\t}\n\t@requireCredentials\n\t@requireParam('uid')\n\tpublic getHomework(uid: string | number): Promise<Homework> {\n\t\treturn new Promise(async (resolve): Promise<void> => {\n\t\t\tawait tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.HaziFeladatok) + '/' + uid.toString(), {\n\t\t\t\theaders: {", "score": 0.8352378010749817 }, { "filename": "src/lib/Kreta.ts", "retrieved_chunk": "\t\t\t}).then((r: AxiosResponse<Institute[]>) => resolve(r.data)));\n\t\t});\n\t}\n\t@requireCredentials\n\tpublic getStudent(): Promise<Student> {\n\t\treturn new Promise(async (resolve): Promise<void> => {\n\t\t\tawait tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.Tanulo), {\n\t\t\t\theaders: {\n\t\t\t\t\t'Authorization': await this.token,\n\t\t\t\t}", "score": 0.834272027015686 }, { "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": 0.8337181806564331 } ]
typescript
await tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.CimzettTipusok), {
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": 0.8716312646865845 }, { "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": 0.7763448357582092 }, { "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": 0.7399575710296631 }, { "filename": "src/lib/Global.ts", "retrieved_chunk": "import axios, { AxiosResponse } from 'axios';\nimport { API, Endpoints, InstituteGlobal } from '../types';\nimport tryRequest from '../utils/tryRequest';\nexport default class Global {\n\tconstructor() {\n\t}\n\tpublic getInstituteList(): Promise<InstituteGlobal[]> {\n\t\treturn new Promise(async (resolve): Promise<void> => {\n\t\t\tawait tryRequest(axios.get(API.GLOBAL + Endpoints.PublikusIntezmenyek, {\n\t\t\t\theaders: {", "score": 0.737820029258728 }, { "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": 0.7355947494506836 } ]
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\theaders: {\n\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\tpublic getNoticeBoardItems(): Promise<NoticeBoardItem[]> {\n\t\treturn new Promise(async (resolve): Promise<void> => {\n\t\t\tawait tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.FaliujsagElemek), {", "score": 0.8638172149658203 }, { "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": 0.8587646484375 }, { "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": 0.8451936841011047 }, { "filename": "src/lib/Kreta.ts", "retrieved_chunk": "\t\t\t\torarendElemVegNapDatuma: validateDate(moment(options.dateTo).format('YYYY-MM-DD'))\n\t\t\t}), {\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<TimeTableWeek[]>) => resolve(r.data)));\n\t\t});\n\t}\n\t@requireCredentials\n\tpublic getLepEvents(): Promise<LepEvent[]> {", "score": 0.8347604870796204 }, { "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": 0.8326256275177002 } ]
typescript
requireParam('addressId') public getAddressableClasses(addressId: string | number): Promise<KretaClass[]> {
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": 0.870269775390625 }, { "filename": "src/middleware/protect.ts", "retrieved_chunk": " } else if (req.cookies.jwt) {\n token = req.cookies.jwt;\n }\n console.log({ token });\n if (!token) {\n return next(new AppError('You are not logged in! Please log in to get access.', 401));\n }\n // 2) Verification token\n const decoded = (await verify(token, process.env.JWT_KEY_SECRET as string)) as JwtPayload;\n console.log({ decoded });", "score": 0.8648214936256409 }, { "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": 0.8576058149337769 }, { "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": 0.841513991355896 }, { "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": 0.8321233987808228 } ]
typescript
const users = await User.find();
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 | 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": 0.7919475436210632 }, { "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": 0.7643077969551086 }, { "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": 0.7592978477478027 }, { "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": 0.7243713140487671 }, { "filename": "src/decorators/requireCredentials.ts", "retrieved_chunk": "import Kreta from '../lib/Kreta';\nimport Administration from '../lib/Administration';\nimport KretaError from '../lib/errors/KretaError';\nexport default function requireCredentials(target: any, propertyName: string, descriptor: PropertyDescriptor): PropertyDescriptor {\n\tconst originalMethod = descriptor.value;\n\tdescriptor.value = function (...args: any[]) {\n\t\tconst instance: Kreta | Administration = this as Kreta || Administration;\n\t\tif (!instance._username || !instance._password || !instance._institute_code)\n\t\t\tthrow new KretaError('Missing required credentials');\n\t\treturn originalMethod.call(this, ...args);", "score": 0.7135665416717529 } ]
typescript
return reject(new KretaError('Failed to get access token: Invalid credentials'));
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": 0.9300267696380615 }, { "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": 0.8226920366287231 }, { "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": 0.7859198451042175 }, { "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": 0.7796189785003662 }, { "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": 0.7507902383804321 } ]
typescript
Administration({ username: this.username!, password: this.password!, institute_code: this.institute_code! });
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\t\t}).then((r: AxiosResponse<Institute[]>) => resolve(r.data)));\n\t\t});\n\t}\n\t@requireCredentials\n\tpublic getStudent(): Promise<Student> {\n\t\treturn new Promise(async (resolve): Promise<void> => {\n\t\t\tawait tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.Tanulo), {\n\t\t\t\theaders: {\n\t\t\t\t\t'Authorization': await this.token,\n\t\t\t\t}", "score": 0.7754889130592346 }, { "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": 0.7713781595230103 }, { "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": 0.7701512575149536 }, { "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": 0.7677990198135376 }, { "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": 0.7616324424743652 } ]
typescript
tryRequest(axios.post(API.IDP + Endpoints.Token, {
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/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": 0.8530048727989197 }, { "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": 0.8420774340629578 }, { "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": 0.8249284029006958 }, { "filename": "src/modules/account/service/index.ts", "retrieved_chunk": " });\n } else {\n return res.status(400).json({\n error: 'Not enough balance',\n errorCode: 400,\n });\n }\n } catch (err) {\n console.log(err);\n return res.status(400).json({", "score": 0.8212436437606812 }, { "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": 0.817674458026886 } ]
typescript
User.deleteOne({ _id: id });
/** * 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/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": 0.853754997253418 }, { "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": 0.8322606086730957 }, { "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": 0.8258317708969116 }, { "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": 0.8197879791259766 }, { "filename": "src/server/auth.ts", "retrieved_chunk": " * Options for NextAuth.js used to configure adapters, providers, callbacks, etc.\n *\n * @see https://next-auth.js.org/configuration/options\n */\nexport const authOptions: NextAuthOptions = {\n callbacks: {\n session({ session, user }) {\n if (session.user) {\n session.user.id = user.id;\n // session.user.role = user.role; <-- put other properties on the session here", "score": 0.7784111499786377 } ]
typescript
const session = await getServerAuthSession({ req, res });
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": 0.8352340459823608 }, { "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": 0.7886449098587036 }, { "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": 0.7776532173156738 }, { "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\t@requireParam('addressId')\n\tpublic getAddressableClasses(addressId: string | number): Promise<KretaClass[]> {\n\t\treturn new Promise(async (resolve): Promise<void> => {\n\t\t\tawait tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.CimezhetoOsztalyok, { cimzettKod: addressId.toString() }), {\n\t\t\t\theaders: {\n\t\t\t\t\t'Authorization': await this.token", "score": 0.767132580280304 }, { "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": 0.7547670006752014 } ]
typescript
return dynamicValue(API.INSTITUTE, { institute_code: this.institute_code }).toString() + '/ellenorzo/V3' + endpointWithSlash + urlParams;
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": " 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": 0.8745287656784058 }, { "filename": "src/components/ChatWindow/MessageWindow.tsx", "retrieved_chunk": " );\n};\nconst MessageWindow = () => {\n const thread = useStore((state) => state.thread)\n if (!thread.messages) {\n return null;\n }\n return (\n <>\n {thread.messages.map((message, index) => {", "score": 0.8647012710571289 }, { "filename": "src/pages/index.tsx", "retrieved_chunk": "const Home: NextPage = () => {\n const setProfile = useStore((state) => state.setProfile);\n const setProfiles = useStore((state) => state.setProfiles);\n const setThreads = useStore((state) => state.setThreads);\n const selectedProfile = useStore((state) => state.selectedProfile);\n const setSelectedProfile = useStore((state) => state.setSelectedProfile);\n useEffect(() => {\n const data = loadData();\n if (!data) {\n return", "score": 0.8610533475875854 }, { "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": 0.8522873520851135 }, { "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": 0.8370941877365112 } ]
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": 0.7848830223083496 }, { "filename": "src/components/modals/ApiKeyModal.tsx", "retrieved_chunk": " mutate({\n apiKey: value, messages: [\n {\n role: 'user',\n content: 'Hello',\n }],\n model: 'gpt-3.5-turbo',\n }, {\n onSuccess: () => {\n if (editMode) {", "score": 0.7323156595230103 }, { "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": 0.7218705415725708 }, { "filename": "src/server/api/trpc.ts", "retrieved_chunk": " error.cause instanceof ZodError ? error.cause.flatten() : null,\n },\n };\n },\n});\n/**\n * 3. ROUTER & PROCEDURE (THE IMPORTANT BIT)\n *\n * These are the pieces you use to build your tRPC API. You should import these a lot in the\n * \"/src/server/api/routers\" directory.", "score": 0.7215216159820557 }, { "filename": "src/components/modals/ApiKeyModal.tsx", "retrieved_chunk": " cost: 0,\n threadIds: [],\n usage: {} as Usage\n })\n setSelectedProfile(id)\n }\n closeModalHandler()\n },\n onError: (e) => {\n alert(e.message)", "score": 0.7137672305107117 } ]
typescript
response.data as ChatResponse;
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": " 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": 0.8798873424530029 }, { "filename": "src/components/ChatWindow/MessageWindow.tsx", "retrieved_chunk": " );\n};\nconst MessageWindow = () => {\n const thread = useStore((state) => state.thread)\n if (!thread.messages) {\n return null;\n }\n return (\n <>\n {thread.messages.map((message, index) => {", "score": 0.8667473196983337 }, { "filename": "src/pages/index.tsx", "retrieved_chunk": "const Home: NextPage = () => {\n const setProfile = useStore((state) => state.setProfile);\n const setProfiles = useStore((state) => state.setProfiles);\n const setThreads = useStore((state) => state.setThreads);\n const selectedProfile = useStore((state) => state.selectedProfile);\n const setSelectedProfile = useStore((state) => state.setSelectedProfile);\n useEffect(() => {\n const data = loadData();\n if (!data) {\n return", "score": 0.8627210855484009 }, { "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": 0.8496056795120239 }, { "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": 0.8369954824447632 } ]
typescript
filter((t) => t !== undefined) as Thread[];
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": 0.9346203207969666 }, { "filename": "src/pages/index.tsx", "retrieved_chunk": " </div>\n </div>\n </div>\n )\n}\nconst LicenseCluster = () => {\n const setApiKeyModal = useStore((state) => state.setApiKeyModal)\n const profile = useStore((state) => state.profile)\n return (\n <div className=\"flex items-center justify-center\">", "score": 0.8464488983154297 }, { "filename": "src/components/ChatWindow/ChatWindow.tsx", "retrieved_chunk": " </div>\n </div>\n </div >\n )\n}\nconst ResizeColumn = () => {\n const width = useStore((state) => state.width)\n const setWidth = useStore((state) => state.setWidth)\n const changeWidthHandler = () => {\n switch (width) {", "score": 0.8330385684967041 }, { "filename": "src/store/store.ts", "retrieved_chunk": " return { profiles, profile, selectedProfile: profile.id };\n }\n return { profiles, profile, selectedProfile };\n};\nexport const getThread = (id: string) => {\n const raw = localStorage.getItem(\"Thread_\" + id);\n if (raw) {\n return JSON.parse(raw) as Thread;\n }\n};", "score": 0.8279204964637756 }, { "filename": "src/pages/index.tsx", "retrieved_chunk": " }\n </div>\n </div>\n </div>\n )\n}\nfunction classNames(...classes: string[]) {\n return classes.filter(Boolean).join(' ')\n}\nconst TopBar = () => {", "score": 0.8264706134796143 } ]
typescript
thread = useStore((state) => state.thread) if (!thread.messages) {
/** * 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/auth.ts", "retrieved_chunk": "/**\n * Module augmentation for `next-auth` types. Allows us to add custom properties to the `session`\n * object and keep type safety.\n *\n * @see https://next-auth.js.org/getting-started/typescript#module-augmentation\n */\ndeclare module \"next-auth\" {\n interface Session extends DefaultSession {\n user: {\n id: string;", "score": 0.7525506019592285 }, { "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": 0.7499970197677612 }, { "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": 0.7445261478424072 }, { "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": 0.74296635389328 }, { "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": 0.7218069434165955 } ]
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": " 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": 0.8786917328834534 }, { "filename": "src/components/ChatWindow/MessageWindow.tsx", "retrieved_chunk": " );\n};\nconst MessageWindow = () => {\n const thread = useStore((state) => state.thread)\n if (!thread.messages) {\n return null;\n }\n return (\n <>\n {thread.messages.map((message, index) => {", "score": 0.8685270547866821 }, { "filename": "src/pages/index.tsx", "retrieved_chunk": "const Home: NextPage = () => {\n const setProfile = useStore((state) => state.setProfile);\n const setProfiles = useStore((state) => state.setProfiles);\n const setThreads = useStore((state) => state.setThreads);\n const selectedProfile = useStore((state) => state.selectedProfile);\n const setSelectedProfile = useStore((state) => state.setSelectedProfile);\n useEffect(() => {\n const data = loadData();\n if (!data) {\n return", "score": 0.8614532351493835 }, { "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": 0.8516809940338135 }, { "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": 0.8381351232528687 } ]
typescript
(t) => t !== undefined) as Thread[];
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/store/store.ts", "retrieved_chunk": "export const loadData = () => {\n const profileData = loadProfiles();\n if (!profileData) {\n return null;\n }\n const { profiles, profile, selectedProfile } = profileData;\n const threads = profile.threadIds\n .map((id) => getThread(id))\n .filter((t) => t !== undefined) as Thread[];\n return { profiles, profile, selectedProfile, threads };", "score": 0.856232225894928 }, { "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": 0.8545960187911987 }, { "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": 0.8479107618331909 }, { "filename": "src/store/store.ts", "retrieved_chunk": " },\n deleteThread: (value: Thread) => {\n deleteThread(value.id);\n set((state) => ({\n threads: state.threads.filter((t) => t.id !== value.id),\n }));\n },\n setSelectedProfile: (value: string) => {\n updateSelectedProfile(value);\n set({ selectedProfile: value });", "score": 0.8333394527435303 }, { "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": 0.8263883590698242 } ]
typescript
.messages.map((message, index) => {
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": 0.8665446043014526 }, { "filename": "src/components/modals/ApiKeyModal.tsx", "retrieved_chunk": " mutate({\n apiKey: value, messages: [\n {\n role: 'user',\n content: 'Hello',\n }],\n model: 'gpt-3.5-turbo',\n }, {\n onSuccess: () => {\n if (editMode) {", "score": 0.7979055643081665 }, { "filename": "src/server/api/routers/example.ts", "retrieved_chunk": " return {\n greeting: `Hello ${input.text}`,\n };\n }),\n getAll: publicProcedure.query(({ ctx }) => {\n return ctx.prisma.example.findMany();\n }),\n getSecretMessage: protectedProcedure.query(() => {\n return \"you can now see this secret message!\";\n }),", "score": 0.7874888181686401 }, { "filename": "src/components/modals/ApiKeyModal.tsx", "retrieved_chunk": " setProfile({ ...profile, key: value })\n setSelectedProfile(profile.id)\n }\n else {\n const id = uuid()\n addProfile({\n key: value,\n id,\n name: 'New Profile',\n budget: 0,", "score": 0.7799543142318726 }, { "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": 0.773139476776123 } ]
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": 0.8413217067718506 }, { "filename": "src/types/appstate.ts", "retrieved_chunk": " cost: number;\n budget: number;\n threadIds: string[];\n};\nexport interface Model {\n id: string;\n maxTokens: number;\n name: string;\n description: string;\n trainingData: string;", "score": 0.8396421074867249 }, { "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": 0.8363280296325684 }, { "filename": "src/server/api/routers/gpt.ts", "retrieved_chunk": "export type ChatResponse = {\n id: string;\n created: number;\n model: string;\n choices: [\n {\n finish_reason: string;\n index: number;\n message: Message;\n }", "score": 0.8236557245254517 }, { "filename": "src/types/appstate.ts", "retrieved_chunk": "export type Profile = {\n id: string;\n key: string;\n name: string;\n organization?: string;\n usage: {\n total_tokens: number;\n completion_tokens: number;\n prompt_tokens: number;\n };", "score": 0.796043872833252 } ]
typescript
} 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": 0.8580865859985352 }, { "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\t@requireParam('addressId')\n\tpublic getAddressableClasses(addressId: string | number): Promise<KretaClass[]> {\n\t\treturn new Promise(async (resolve): Promise<void> => {\n\t\t\tawait tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.CimezhetoOsztalyok, { cimzettKod: addressId.toString() }), {\n\t\t\t\theaders: {\n\t\t\t\t\t'Authorization': await this.token", "score": 0.8314530849456787 }, { "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": 0.8308761119842529 }, { "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": 0.81812983751297 }, { "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": 0.804714024066925 } ]
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<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": 0.8400150537490845 }, { "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": 0.8306026458740234 }, { "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\tpublic getClassMasters(): Promise<EmployeeDetails[]> {\n\t\treturn new Promise(async (resolve): Promise<void> => {\n\t\t\tawait tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.Osztalyfonokok), {\n\t\t\t\theaders: {", "score": 0.8270068764686584 }, { "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<MessageLimitations>) => resolve(r.data)));\n\t\t});\n\t}\n\t@requireCredentials\n\tpublic getAdministrators(): Promise<EmployeeDetails[]> {\n\t\treturn new Promise(async (resolve): Promise<void> => {\n\t\t\tawait tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.Adminisztratorok), {\n\t\t\t\theaders: {", "score": 0.824711799621582 }, { "filename": "src/lib/Administration.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<GuardianEAdmin[]>) => resolve(r.data)));\n\t\t});\n\t}\n\t@requireCredentials\n\tpublic getCurrentInstitutionDetails(): Promise<CurrentInstitutionDetails> {\n\t\treturn new Promise(async (resolve): Promise<void> => {\n\t\t\tawait tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.JelenlegiIntezmeny), {", "score": 0.823775589466095 } ]
typescript
@requireCredentials public getStudent(): Promise<Student> {
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\t\t}).then((r: AxiosResponse<Institute[]>) => resolve(r.data)));\n\t\t});\n\t}\n\t@requireCredentials\n\tpublic getStudent(): Promise<Student> {\n\t\treturn new Promise(async (resolve): Promise<void> => {\n\t\t\tawait tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.Tanulo), {\n\t\t\t\theaders: {\n\t\t\t\t\t'Authorization': await this.token,\n\t\t\t\t}", "score": 0.7863485813140869 }, { "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": 0.7773555517196655 }, { "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": 0.7762179374694824 }, { "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": 0.7741736173629761 }, { "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": 0.772413969039917 } ]
typescript
await tryRequest(axios.post(API.IDP + Endpoints.Token, {
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": " 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": 0.8794670104980469 }, { "filename": "src/components/ChatWindow/MessageWindow.tsx", "retrieved_chunk": " );\n};\nconst MessageWindow = () => {\n const thread = useStore((state) => state.thread)\n if (!thread.messages) {\n return null;\n }\n return (\n <>\n {thread.messages.map((message, index) => {", "score": 0.8669478297233582 }, { "filename": "src/pages/index.tsx", "retrieved_chunk": "const Home: NextPage = () => {\n const setProfile = useStore((state) => state.setProfile);\n const setProfiles = useStore((state) => state.setProfiles);\n const setThreads = useStore((state) => state.setThreads);\n const selectedProfile = useStore((state) => state.selectedProfile);\n const setSelectedProfile = useStore((state) => state.setSelectedProfile);\n useEffect(() => {\n const data = loadData();\n if (!data) {\n return", "score": 0.8629659414291382 }, { "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": 0.8494753837585449 }, { "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": 0.837821364402771 } ]
typescript
map((id) => getThread(id)) .filter((t) => t !== undefined) as Thread[];
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": 0.8858815431594849 }, { "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": 0.8305591344833374 }, { "filename": "src/lib/Kreta.ts", "retrieved_chunk": "\t\t\t\t}\n\t\t\t}).then((r: AxiosResponse<Homework[]>) => resolve(r.data)));\n\t\t});\n\t}\n\t@requireCredentials\n\t@requireParam('uid')\n\tpublic getHomework(uid: string | number): Promise<Homework> {\n\t\treturn new Promise(async (resolve): Promise<void> => {\n\t\t\tawait tryRequest(axios.get(this.buildEllenorzoApiURL(Endpoints.HaziFeladatok) + '/' + uid.toString(), {\n\t\t\t\theaders: {", "score": 0.8188542127609253 }, { "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": 0.8134902715682983 }, { "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": 0.812126874923706 } ]
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/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": 0.8038660287857056 }, { "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": 0.8002852201461792 }, { "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": 0.799172580242157 }, { "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<MessageLimitations>) => resolve(r.data)));\n\t\t});\n\t}\n\t@requireCredentials\n\tpublic getAdministrators(): Promise<EmployeeDetails[]> {\n\t\treturn new Promise(async (resolve): Promise<void> => {\n\t\t\tawait tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.Adminisztratorok), {\n\t\t\t\theaders: {", "score": 0.7991558313369751 }, { "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\tpublic getTeachers(): Promise<EmployeeDetails[]> {\n\t\treturn new Promise(async (resolve): Promise<void> => {\n\t\t\tawait tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.Oktatok), {\n\t\t\t\theaders: {", "score": 0.7989389300346375 } ]
typescript
datumTol = validateDate(moment(options.dateFrom).format('YYYY-MM-DD'));
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": 0.8784744739532471 }, { "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": 0.7755002975463867 }, { "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": 0.7321872115135193 }, { "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": 0.7321155071258545 }, { "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": 0.7317904233932495 } ]
typescript
requireCredentials public getAddresseeType(): Promise<AddresseType[]> {
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 | 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": 0.7967157363891602 }, { "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": 0.7806369066238403 }, { "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": 0.7701988220214844 }, { "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": 0.7358658313751221 }, { "filename": "src/decorators/requireCredentials.ts", "retrieved_chunk": "import Kreta from '../lib/Kreta';\nimport Administration from '../lib/Administration';\nimport KretaError from '../lib/errors/KretaError';\nexport default function requireCredentials(target: any, propertyName: string, descriptor: PropertyDescriptor): PropertyDescriptor {\n\tconst originalMethod = descriptor.value;\n\tdescriptor.value = function (...args: any[]) {\n\t\tconst instance: Kreta | Administration = this as Kreta || Administration;\n\t\tif (!instance._username || !instance._password || !instance._institute_code)\n\t\t\tthrow new KretaError('Missing required credentials');\n\t\treturn originalMethod.call(this, ...args);", "score": 0.7303807139396667 } ]
typescript
reject(new KretaError('Failed to get access token: Invalid credentials'));
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<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": 0.8342735767364502 }, { "filename": "src/lib/Administration.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<GuardianEAdmin[]>) => resolve(r.data)));\n\t\t});\n\t}\n\t@requireCredentials\n\tpublic getCurrentInstitutionDetails(): Promise<CurrentInstitutionDetails> {\n\t\treturn new Promise(async (resolve): Promise<void> => {\n\t\t\tawait tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.JelenlegiIntezmeny), {", "score": 0.8333484530448914 }, { "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\tpublic getClassMasters(): Promise<EmployeeDetails[]> {\n\t\treturn new Promise(async (resolve): Promise<void> => {\n\t\t\tawait tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.Osztalyfonokok), {\n\t\t\t\theaders: {", "score": 0.8253470659255981 }, { "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<MessageLimitations>) => resolve(r.data)));\n\t\t});\n\t}\n\t@requireCredentials\n\tpublic getAdministrators(): Promise<EmployeeDetails[]> {\n\t\treturn new Promise(async (resolve): Promise<void> => {\n\t\t\tawait tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.Adminisztratorok), {\n\t\t\t\theaders: {", "score": 0.8249375820159912 }, { "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\tpublic getTeachers(): Promise<EmployeeDetails[]> {\n\t\treturn new Promise(async (resolve): Promise<void> => {\n\t\t\tawait tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.Oktatok), {\n\t\t\t\theaders: {", "score": 0.8242502212524414 } ]
typescript
requireCredentials public getStudent(): Promise<Student> {
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/edge-runtime/middleware.ts", "retrieved_chunk": " }\n let status: ValidRedirectStatus | undefined;\n if (typeof redirectDefaultLocale === \"number\") {\n status = redirectDefaultLocale;\n }\n return defineMiddleware((context, next) => {\n const requestUrlPathname = new URL(context.request.url).pathname;\n // avoid catching urls that start with \"/en\" like \"/enigma\"\n if (requestUrlPathname === `/${defaultLocale}`) {\n return context.redirect(", "score": 0.7664744853973389 }, { "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": 0.7594667673110962 }, { "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": 0.7554947137832642 }, { "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": 0.7405006885528564 }, { "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": 0.735202431678772 } ]
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": 0.8203425407409668 }, { "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": 0.8079569339752197 }, { "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": 0.802291750907898 }, { "filename": "src/astro/logger/console.ts", "retrieved_chunk": "import { bold, cyan, dim, red, reset, yellow } from \"kleur/colors\";\nimport type { LogMessage } from \"./core.js\";\nimport { dateTimeFormat, levels } from \"./core.js\";\nlet lastMessage: string;\nlet lastMessageCount = 1;\nexport const consoleLogDestination = {\n write(event: LogMessage) {\n // eslint-disable-next-line no-console\n let dest = console.error;\n if (levels[event.level] < levels[\"error\"]) {", "score": 0.8003178834915161 }, { "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": 0.7865266799926758 } ]
typescript
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": 0.8389203548431396 }, { "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": 0.8273488283157349 }, { "filename": "src/astro/logger/core.ts", "retrieved_chunk": "}\nexport let defaultLogLevel: LoggerLevel;\nif (typeof process !== \"undefined\") {\n // This could be a shimmed environment so we don't know that `process` is the full\n // NodeJS.process. This code treats it as a plain object so TS doesn't let us\n // get away with incorrect assumptions.\n let proc: object = process;\n if (\"argv\" in proc && Array.isArray(proc.argv)) {\n if (proc.argv.includes(\"--verbose\")) {\n defaultLogLevel = \"debug\";", "score": 0.8082424402236938 }, { "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": 0.806964635848999 }, { "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": 0.7906535863876343 } ]
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": 0.8203425407409668 }, { "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": 0.8079569339752197 }, { "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": 0.802291750907898 }, { "filename": "src/astro/logger/console.ts", "retrieved_chunk": "import { bold, cyan, dim, red, reset, yellow } from \"kleur/colors\";\nimport type { LogMessage } from \"./core.js\";\nimport { dateTimeFormat, levels } from \"./core.js\";\nlet lastMessage: string;\nlet lastMessageCount = 1;\nexport const consoleLogDestination = {\n write(event: LogMessage) {\n // eslint-disable-next-line no-console\n let dest = console.error;\n if (levels[event.level] < levels[\"error\"]) {", "score": 0.8003178834915161 }, { "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": 0.7865266799926758 } ]
typescript
warn: warn.bind(null, nodeLogOptions), error: error.bind(null, nodeLogOptions), };
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": 0.8321523666381836 }, { "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": 0.7948814630508423 }, { "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": 0.7659249305725098 }, { "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\t@requireParam('addressId')\n\tpublic getAddressableClasses(addressId: string | number): Promise<KretaClass[]> {\n\t\treturn new Promise(async (resolve): Promise<void> => {\n\t\t\tawait tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.CimezhetoOsztalyok, { cimzettKod: addressId.toString() }), {\n\t\t\t\theaders: {\n\t\t\t\t\t'Authorization': await this.token", "score": 0.7589370012283325 }, { "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": 0.7582294940948486 } ]
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": 0.8388093709945679 }, { "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": 0.8262419700622559 }, { "filename": "src/astro/logger/core.ts", "retrieved_chunk": "}\nexport let defaultLogLevel: LoggerLevel;\nif (typeof process !== \"undefined\") {\n // This could be a shimmed environment so we don't know that `process` is the full\n // NodeJS.process. This code treats it as a plain object so TS doesn't let us\n // get away with incorrect assumptions.\n let proc: object = process;\n if (\"argv\" in proc && Array.isArray(proc.argv)) {\n if (proc.argv.includes(\"--verbose\")) {\n defaultLogLevel = \"debug\";", "score": 0.8093773722648621 }, { "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": 0.8061891794204712 }, { "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": 0.7910507321357727 } ]
typescript
warn.bind(null, nodeLogOptions), error: error.bind(null, nodeLogOptions), };
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\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\tpublic getTeachers(): Promise<EmployeeDetails[]> {\n\t\treturn new Promise(async (resolve): Promise<void> => {\n\t\t\tawait tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.Oktatok), {\n\t\t\t\theaders: {", "score": 0.8150492310523987 }, { "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": 0.8147833347320557 }, { "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<MessageLimitations>) => resolve(r.data)));\n\t\t});\n\t}\n\t@requireCredentials\n\tpublic getAdministrators(): Promise<EmployeeDetails[]> {\n\t\treturn new Promise(async (resolve): Promise<void> => {\n\t\t\tawait tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.Adminisztratorok), {\n\t\t\t\theaders: {", "score": 0.813461184501648 }, { "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\tpublic getDirectors(): Promise<EmployeeDetails[]> {\n\t\treturn new Promise(async (resolve): Promise<void> => {\n\t\t\tawait tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.Igazgatok), {\n\t\t\t\theaders: {", "score": 0.812650740146637 }, { "filename": "src/lib/Administration.ts", "retrieved_chunk": "\t\t\t\t}\n\t\t\t}).then((r: AxiosResponse<number>) => resolve(r.data)));\n\t\t});\n\t}\n\t@requireCredentials\n\tpublic getMessages(): Promise<MailboxItem[]> {\n\t\treturn new Promise(async (resolve): Promise<void> => {\n\t\t\tawait tryRequest(axios.get(this.buildUgyintezesApiURL(AdministrationEndpoints.Uzenetek), {\n\t\t\t\theaders: {\n\t\t\t\t\t'Authorization': await this.token", "score": 0.8084070086479187 } ]
typescript
ops.datumTol = validateDate(moment(options.dateFrom).format('YYYY-MM-DD'));
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": 0.8340733051300049 }, { "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": 0.7757847905158997 }, { "filename": "src/commands/edit.ts", "retrieved_chunk": " ],\n run: async (interaction: CommandInteraction) => {\n let taskId = interaction.options.get('task').value.toString();\n let taskDescription = interaction.options.get('description').value.toString();\n let content = \"Task doesn't exist\";\n let oldTaskDescription = GetTaskById(parseInt(taskId))?.description;\n if (oldTaskDescription != null) {\n let task = SetDescription(parseInt(taskId), taskDescription);\n content = `Updated task \"${oldTaskDescription}\" (ID ${taskId})\\n\\n\"${task.description}\" for <@${task.assignee}>`;\n }", "score": 0.7678501605987549 }, { "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": 0.7645245790481567 }, { "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": 0.7589638829231262 } ]
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/edge-runtime/middleware.ts", "retrieved_chunk": "import type { ValidRedirectStatus } from \"astro\";\nimport { defineMiddleware } from \"astro/middleware\";\nimport { defaultI18nMiddlewareConfig } from \"../shared/configs\";\nimport type {\n UserI18nMiddlewareConfig,\n I18nMiddlewareConfig,\n} from \"../shared/configs\";\nconst redirectDefaultLocaleDisabledMiddleware = defineMiddleware((_, next) =>\n next()\n);", "score": 0.7379167079925537 }, { "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": 0.726486325263977 }, { "filename": "src/astro/logger/console.ts", "retrieved_chunk": "import { bold, cyan, dim, red, reset, yellow } from \"kleur/colors\";\nimport type { LogMessage } from \"./core.js\";\nimport { dateTimeFormat, levels } from \"./core.js\";\nlet lastMessage: string;\nlet lastMessageCount = 1;\nexport const consoleLogDestination = {\n write(event: LogMessage) {\n // eslint-disable-next-line no-console\n let dest = console.error;\n if (levels[event.level] < levels[\"error\"]) {", "score": 0.7202253937721252 }, { "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": 0.7137894630432129 }, { "filename": "src/shared/configs.ts", "retrieved_chunk": " [K in keyof T as T[K] extends Required<T>[K] ? never : K]: T[K];\n};\n/**\n * The default values for I18nConfig\n */\nexport const defaultI18nConfig: Required<PartialFieldsOnly<UserI18nConfig>> = {\n include: [\"pages/**/*\"],\n exclude: [\"pages/api/**/*\"],\n redirectDefaultLocale: true,\n};", "score": 0.697746992111206 } ]
typescript
logger.warn( "astro-i18n-aut", `avoid setting config.trailingSlash = "ignore" when config.output = "static"` );
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": 0.9119923114776611 }, { "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": 0.8730205297470093 }, { "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": 0.8626627922058105 }, { "filename": "src/core/interfaces/IDeveloperService.ts", "retrieved_chunk": " * get all the developers by level\n */\n filterByLevel(dto: PartialDeveloperDTO): Promise<DeveloperDocument[] | object[]>;\n /**\n * update a single record\n */\n update(id: string, dto: PartialDeveloperDTO): Promise<DeveloperDocument | object>;\n /**\n * delete a single record\n */", "score": 0.8212317824363708 }, { "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": 0.8104628324508667 } ]
typescript
(dto: PartialDeveloperDTO): Promise<object[]> {
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": 0.8033888339996338 }, { "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": 0.7947403192520142 }, { "filename": "src/tasks.ts", "retrieved_chunk": "import { User } from 'discord.js';\nimport fs from 'fs';\nconst tasksFile = \"tasks.json\";\nexport type Task = {\n id: number;\n description: string;\n assignee: string;\n threadId?: string;\n}\n// TODO: throw this shit into a database", "score": 0.7745097279548645 }, { "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": 0.7661213874816895 }, { "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": 0.7502649426460266 } ]
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": " 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": 0.8847931027412415 }, { "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": 0.8821263313293457 }, { "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": 0.8581129312515259 }, { "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": 0.8544462323188782 }, { "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": 0.8223053216934204 } ]
typescript
filterByLevel(dto: PartialDeveloperDTO): Promise<DeveloperDocument[]> {
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": 0.9213232398033142 }, { "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": 0.8997536301612854 }, { "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": 0.8621851205825806 }, { "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": 0.8545673489570618 }, { "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": 0.844007670879364 } ]
typescript
const cacheKey = `developers:${dto.level}`;
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": 0.9002568125724792 }, { "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": 0.8985349535942078 }, { "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": 0.8669116497039795 }, { "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": 0.8594762086868286 }, { "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": 0.823078453540802 } ]
typescript
async 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": 0.9102035164833069 }, { "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": 0.8687143325805664 }, { "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": 0.8616460561752319 }, { "filename": "src/core/interfaces/IDeveloperService.ts", "retrieved_chunk": " * get all the developers by level\n */\n filterByLevel(dto: PartialDeveloperDTO): Promise<DeveloperDocument[] | object[]>;\n /**\n * update a single record\n */\n update(id: string, dto: PartialDeveloperDTO): Promise<DeveloperDocument | object>;\n /**\n * delete a single record\n */", "score": 0.8187768459320068 }, { "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": 0.8083604574203491 } ]
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": 0.928687572479248 }, { "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": 0.8953959941864014 }, { "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": 0.8822941780090332 }, { "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": 0.8667277097702026 }, { "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": 0.8440440893173218 } ]
typescript
async filterByLevel(dto: PartialDeveloperDTO): Promise<object[]> {
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/getLocal.ts", "retrieved_chunk": " en: 0,\n number: 0,\n special: 0,\n etc: 0,\n };\n const result: string[] = [];\n for (let index = 0; index < word.length; index++) {\n const language = getLocal(word[index]);\n if (isPercent) {\n countObject[language]++;", "score": 0.8233377933502197 }, { "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": 0.8158692121505737 }, { "filename": "src/combine.ts", "retrieved_chunk": " // Group 형식일 때, [ ['ㄱㅏ'], 'ㄴㅏ', ['ㄷ', 'ㅏ'] ]\n const result: string[] = [];\n const _temp: string[] = [];\n for (let index = 0; index < word.length; index++) {\n const item = word[index];\n if (typeof item === \"string\") {\n _temp.push(...item.toString().split(\"\"));\n } else {\n result.push(\n combineLoop(_temp.splice(0)).concat(", "score": 0.7927260398864746 }, { "filename": "src/distance.ts", "retrieved_chunk": " const minDist = [];\n const dividedWord = divideHangul(word, true).join(\"\");\n for (let index = 0; index < list.length; index++) {\n const dist = isSplit\n ? getDistance(dividedWord, divideHangul(list[index], true).join(\"\"))\n : getDistance(word, list[index]);\n if (dist <= distance) {\n minDist.push({ dist, word: list[index] });\n }\n }", "score": 0.7922173738479614 }, { "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": 0.785486102104187 } ]
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-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": 0.7871877551078796 }, { "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": 0.7361325025558472 }, { "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": 0.7045961022377014 }, { "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": 0.7042955160140991 }, { "filename": "src/utilities/dom/range-rect-calculator.ts", "retrieved_chunk": " while (walker.nextNode()) nodes.push(walker.currentNode);\n return nodes;\n }\n /**\n * Get the text node containing the offset, and the relative offset into that node.\n * @param lines Array of nodes for each line\n * @param offset Offset into the entire text\n */\n static #getNodeAtOffset(\n lines: Node[][],", "score": 0.6991270184516907 } ]
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": " 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": 0.8106852769851685 }, { "filename": "src/components/lint-error-annotation.ts", "retrieved_chunk": " const absoluteRect = rect.translate(scrollVector);\n // We want ranges spanning multiple lines to look like one annotation, so we need to\n // expand them to fill the gap around the lines\n const lineHeight = cssLineHeight ?? rect.height * 1.2;\n const scaledRect = absoluteRect.scaleY(lineHeight / absoluteRect.height);\n elements.push(LintErrorAnnotation.#createAnnotationElement(scaledRect));\n }\n this.#container.replaceChildren(...elements);\n this.#elements = elements;\n }", "score": 0.7978033423423767 }, { "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": 0.7837846875190735 }, { "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": 0.7804888486862183 }, { "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": 0.7793018221855164 } ]
typescript
#_annotations: readonly LintErrorAnnotation[] = [];
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/getLocal.ts", "retrieved_chunk": " en: 0,\n number: 0,\n special: 0,\n etc: 0,\n };\n const result: string[] = [];\n for (let index = 0; index < word.length; index++) {\n const language = getLocal(word[index]);\n if (isPercent) {\n countObject[language]++;", "score": 0.7919415235519409 }, { "filename": "src/distance.ts", "retrieved_chunk": " const minDist = [];\n const dividedWord = divideHangul(word, true).join(\"\");\n for (let index = 0; index < list.length; index++) {\n const dist = isSplit\n ? getDistance(dividedWord, divideHangul(list[index], true).join(\"\"))\n : getDistance(word, list[index]);\n if (dist <= distance) {\n minDist.push({ dist, word: list[index] });\n }\n }", "score": 0.7674050331115723 }, { "filename": "src/combine.ts", "retrieved_chunk": " // Group 형식일 때, [ ['ㄱㅏ'], 'ㄴㅏ', ['ㄷ', 'ㅏ'] ]\n const result: string[] = [];\n const _temp: string[] = [];\n for (let index = 0; index < word.length; index++) {\n const item = word[index];\n if (typeof item === \"string\") {\n _temp.push(...item.toString().split(\"\"));\n } else {\n result.push(\n combineLoop(_temp.splice(0)).concat(", "score": 0.7519688606262207 }, { "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": 0.749361515045166 }, { "filename": "src/formatDate.ts", "retrieved_chunk": " const day = date.getDate();\n const hour = date.getHours();\n const minute = date.getMinutes();\n const second = date.getSeconds();\n const week = date.getDay();\n function matcher(match: string): any {\n return (\n {\n YY: year.slice(-2),\n YYYY: year,", "score": 0.7478528022766113 } ]
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/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": 0.7790369987487793 }, { "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": 0.7469833493232727 }, { "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": 0.741650402545929 }, { "filename": "src/utilities/dom/range-rect-calculator.ts", "retrieved_chunk": " .minus(scrollOffset);\n return Array.from(this.#range.getClientRects()).map((domRect) =>\n new Rect(domRect).translate(netTranslate)\n );\n }\n disconnect() {\n this.#div.remove();\n }\n #refreshStyles() {\n const style = this.#div.style;", "score": 0.7315304279327393 }, { "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": 0.7119247913360596 } ]
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/getLocal.ts", "retrieved_chunk": " en: 0,\n number: 0,\n special: 0,\n etc: 0,\n };\n const result: string[] = [];\n for (let index = 0; index < word.length; index++) {\n const language = getLocal(word[index]);\n if (isPercent) {\n countObject[language]++;", "score": 0.8229249715805054 }, { "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": 0.817088782787323 }, { "filename": "src/combine.ts", "retrieved_chunk": " // Group 형식일 때, [ ['ㄱㅏ'], 'ㄴㅏ', ['ㄷ', 'ㅏ'] ]\n const result: string[] = [];\n const _temp: string[] = [];\n for (let index = 0; index < word.length; index++) {\n const item = word[index];\n if (typeof item === \"string\") {\n _temp.push(...item.toString().split(\"\"));\n } else {\n result.push(\n combineLoop(_temp.splice(0)).concat(", "score": 0.793677806854248 }, { "filename": "src/distance.ts", "retrieved_chunk": " const minDist = [];\n const dividedWord = divideHangul(word, true).join(\"\");\n for (let index = 0; index < list.length; index++) {\n const dist = isSplit\n ? getDistance(dividedWord, divideHangul(list[index], true).join(\"\"))\n : getDistance(word, list[index]);\n if (dist <= distance) {\n minDist.push({ dist, word: list[index] });\n }\n }", "score": 0.7922077178955078 }, { "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": 0.7865400314331055 } ]
typescript
: 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/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": 0.8449342250823975 }, { "filename": "src/utilities/dom/range-rect-calculator.ts", "retrieved_chunk": " : this.#element.value;\n }\n}\nexport class CodeMirrorRangeRectCalculator implements RangeRectCalculator {\n readonly #element: HTMLElement;\n readonly #range: Range;\n constructor(target: HTMLElement) {\n if (!target.classList.contains(\"CodeMirror-code\"))\n throw new Error(\n \"CodeMirrorRangeRectCalculator only works with CodeMirror code editors.\"", "score": 0.8096676468849182 }, { "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": 0.8056020736694336 }, { "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": 0.7656018733978271 }, { "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": 0.7603145837783813 } ]
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": 0.9199070930480957 }, { "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": 0.8788310289382935 }, { "filename": "src/utilities/geometry/rect.ts", "retrieved_chunk": " y: this.y,\n height: this.height,\n width: this.width,\n });\n }\n /**\n * Return `true` if `rect` is entirely contained by `otherRect`.\n */\n isContainedBy(other: Rect) {\n return (", "score": 0.807193398475647 }, { "filename": "src/utilities/geometry/rect.ts", "retrieved_chunk": "import {NumberRange} from \"./number-range\";\nimport {Vector} from \"./vector\";\ntype RectParams = Pick<DOMRect, \"x\" | \"y\" | \"height\" | \"width\">;\n/** Represents a rectangle, typically the bounding box for an HTML element. */\nexport class Rect implements DOMRect {\n readonly height: number;\n readonly width: number;\n readonly x: number;\n readonly y: number;\n constructor({x, y, height, width}: RectParams) {", "score": 0.8033982515335083 }, { "filename": "src/components/lint-error-annotation.ts", "retrieved_chunk": " const absoluteRect = rect.translate(scrollVector);\n // We want ranges spanning multiple lines to look like one annotation, so we need to\n // expand them to fill the gap around the lines\n const lineHeight = cssLineHeight ?? rect.height * 1.2;\n const scaledRect = absoluteRect.scaleY(lineHeight / absoluteRect.height);\n elements.push(LintErrorAnnotation.#createAnnotationElement(scaledRect));\n }\n this.#container.replaceChildren(...elements);\n this.#elements = elements;\n }", "score": 0.78000408411026 } ]
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-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": 0.7982094883918762 }, { "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": 0.7744818925857544 }, { "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": 0.7667728662490845 }, { "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": 0.7666324377059937 }, { "filename": "src/utilities/dom/range-rect-calculator.ts", "retrieved_chunk": " });\n this.#resizeObserver = new ResizeObserver(() => this.#refreshStyles());\n this.#resizeObserver.observe(this.#element);\n this.#range = document.createRange();\n }\n /**\n * Return the viewport-relative client rects of the range. If the range has any line\n * breaks, this will return multiple rects. Will include the start char and exclude the\n * end char.\n */", "score": 0.7647051811218262 } ]
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": 0.8398491740226746 }, { "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": 0.8189032077789307 }, { "filename": "src/components/lint-error-annotation.ts", "retrieved_chunk": " const absoluteRect = rect.translate(scrollVector);\n // We want ranges spanning multiple lines to look like one annotation, so we need to\n // expand them to fill the gap around the lines\n const lineHeight = cssLineHeight ?? rect.height * 1.2;\n const scaledRect = absoluteRect.scaleY(lineHeight / absoluteRect.height);\n elements.push(LintErrorAnnotation.#createAnnotationElement(scaledRect));\n }\n this.#container.replaceChildren(...elements);\n this.#elements = elements;\n }", "score": 0.8091140389442444 }, { "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": 0.8084208965301514 }, { "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": 0.7953552603721619 } ]
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": " 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": 0.8157579898834229 }, { "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": 0.7891266345977783 }, { "filename": "src/components/lint-error-annotation.ts", "retrieved_chunk": " const absoluteRect = rect.translate(scrollVector);\n // We want ranges spanning multiple lines to look like one annotation, so we need to\n // expand them to fill the gap around the lines\n const lineHeight = cssLineHeight ?? rect.height * 1.2;\n const scaledRect = absoluteRect.scaleY(lineHeight / absoluteRect.height);\n elements.push(LintErrorAnnotation.#createAnnotationElement(scaledRect));\n }\n this.#container.replaceChildren(...elements);\n this.#elements = elements;\n }", "score": 0.7847815752029419 }, { "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": 0.7775161266326904 }, { "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": 0.7748628854751587 } ]
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": " 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": 0.7926422357559204 }, { "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": 0.7350989580154419 }, { "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": 0.7178146839141846 }, { "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": 0.7048481106758118 }, { "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": 0.6898600459098816 } ]
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-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": 0.790805995464325 }, { "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": 0.7378139495849609 }, { "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": 0.7097488045692444 }, { "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": 0.7039234638214111 }, { "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": 0.7035044431686401 } ]
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": " 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": 0.7456822991371155 }, { "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": 0.7192181348800659 }, { "filename": "src/components/lint-error-annotation.ts", "retrieved_chunk": " const absoluteRect = rect.translate(scrollVector);\n // We want ranges spanning multiple lines to look like one annotation, so we need to\n // expand them to fill the gap around the lines\n const lineHeight = cssLineHeight ?? rect.height * 1.2;\n const scaledRect = absoluteRect.scaleY(lineHeight / absoluteRect.height);\n elements.push(LintErrorAnnotation.#createAnnotationElement(scaledRect));\n }\n this.#container.replaceChildren(...elements);\n this.#elements = elements;\n }", "score": 0.7123508453369141 }, { "filename": "src/utilities/dom/range-rect-calculator.ts", "retrieved_chunk": " );\n this.#element = target;\n this.#range = document.createRange();\n }\n getClientRects(range: NumberRange): Rect[] {\n const lineNodes = Array.from(\n this.#element.querySelectorAll(\".CodeMirror-line\")\n );\n const lines = lineNodes.map((line) =>\n CodeMirrorRangeRectCalculator.#getAllTextNodes(line)", "score": 0.7115186452865601 }, { "filename": "src/utilities/dom/range-rect-calculator.ts", "retrieved_chunk": " this.#range.setStart(...start);\n this.#range.setEnd(...end);\n return Array.from(this.#range.getClientRects()).map(\n (domRect) => new Rect(domRect)\n );\n }\n disconnect(): void {}\n static #getAllTextNodes(node: Node): Node[] {\n const walker = document.createTreeWalker(node, NodeFilter.SHOW_TEXT);\n const nodes = [];", "score": 0.7075214385986328 } ]
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": " 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": 0.7698302268981934 }, { "filename": "src/components/lint-error-annotation.ts", "retrieved_chunk": " const absoluteRect = rect.translate(scrollVector);\n // We want ranges spanning multiple lines to look like one annotation, so we need to\n // expand them to fill the gap around the lines\n const lineHeight = cssLineHeight ?? rect.height * 1.2;\n const scaledRect = absoluteRect.scaleY(lineHeight / absoluteRect.height);\n elements.push(LintErrorAnnotation.#createAnnotationElement(scaledRect));\n }\n this.#container.replaceChildren(...elements);\n this.#elements = elements;\n }", "score": 0.7492154836654663 }, { "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": 0.7394028902053833 }, { "filename": "src/utilities/dom/range-rect-calculator.ts", "retrieved_chunk": " this.#range.setStart(...start);\n this.#range.setEnd(...end);\n return Array.from(this.#range.getClientRects()).map(\n (domRect) => new Rect(domRect)\n );\n }\n disconnect(): void {}\n static #getAllTextNodes(node: Node): Node[] {\n const walker = document.createTreeWalker(node, NodeFilter.SHOW_TEXT);\n const nodes = [];", "score": 0.7298064827919006 }, { "filename": "src/utilities/dom/range-rect-calculator.ts", "retrieved_chunk": " );\n this.#element = target;\n this.#range = document.createRange();\n }\n getClientRects(range: NumberRange): Rect[] {\n const lineNodes = Array.from(\n this.#element.querySelectorAll(\".CodeMirror-line\")\n );\n const lines = lineNodes.map((line) =>\n CodeMirrorRangeRectCalculator.#getAllTextNodes(line)", "score": 0.7283346652984619 } ]
typescript
if (position) this.#tooltip.show(errors, position);
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": 0.8029159903526306 }, { "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": 0.7738971710205078 }, { "filename": "src/services/types.ts", "retrieved_chunk": " pullHeadRef: string;\n pullBaseRef: string;\n pullNumber: number;\n};\nexport type { Octokit, FilenameWithPatch, PullRequestInfo };", "score": 0.7679247260093689 }, { "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": 0.7340510487556458 }, { "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": 0.7263373732566833 } ]
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.#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": 0.9240579605102539 }, { "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": 0.8808567523956299 }, { "filename": "src/utilities/geometry/rect.ts", "retrieved_chunk": " y: this.y,\n height: this.height,\n width: this.width,\n });\n }\n /**\n * Return `true` if `rect` is entirely contained by `otherRect`.\n */\n isContainedBy(other: Rect) {\n return (", "score": 0.8140463829040527 }, { "filename": "src/utilities/geometry/rect.ts", "retrieved_chunk": "import {NumberRange} from \"./number-range\";\nimport {Vector} from \"./vector\";\ntype RectParams = Pick<DOMRect, \"x\" | \"y\" | \"height\" | \"width\">;\n/** Represents a rectangle, typically the bounding box for an HTML element. */\nexport class Rect implements DOMRect {\n readonly height: number;\n readonly width: number;\n readonly x: number;\n readonly y: number;\n constructor({x, y, height, width}: RectParams) {", "score": 0.8036434650421143 }, { "filename": "src/components/lint-error-annotation.ts", "retrieved_chunk": " const absoluteRect = rect.translate(scrollVector);\n // We want ranges spanning multiple lines to look like one annotation, so we need to\n // expand them to fill the gap around the lines\n const lineHeight = cssLineHeight ?? rect.height * 1.2;\n const scaledRect = absoluteRect.scaleY(lineHeight / absoluteRect.height);\n elements.push(LintErrorAnnotation.#createAnnotationElement(scaledRect));\n }\n this.#container.replaceChildren(...elements);\n this.#elements = elements;\n }", "score": 0.7814404368400574 } ]
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": " 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": 0.7545368671417236 }, { "filename": "src/components/lint-error-annotation.ts", "retrieved_chunk": " const absoluteRect = rect.translate(scrollVector);\n // We want ranges spanning multiple lines to look like one annotation, so we need to\n // expand them to fill the gap around the lines\n const lineHeight = cssLineHeight ?? rect.height * 1.2;\n const scaledRect = absoluteRect.scaleY(lineHeight / absoluteRect.height);\n elements.push(LintErrorAnnotation.#createAnnotationElement(scaledRect));\n }\n this.#container.replaceChildren(...elements);\n this.#elements = elements;\n }", "score": 0.7338669300079346 }, { "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": 0.7258942127227783 }, { "filename": "src/utilities/dom/range-rect-calculator.ts", "retrieved_chunk": " this.#range.setStart(...start);\n this.#range.setEnd(...end);\n return Array.from(this.#range.getClientRects()).map(\n (domRect) => new Rect(domRect)\n );\n }\n disconnect(): void {}\n static #getAllTextNodes(node: Node): Node[] {\n const walker = document.createTreeWalker(node, NodeFilter.SHOW_TEXT);\n const nodes = [];", "score": 0.7208813428878784 }, { "filename": "src/utilities/dom/range-rect-calculator.ts", "retrieved_chunk": " );\n this.#element = target;\n this.#range = document.createRange();\n }\n getClientRects(range: NumberRange): Rect[] {\n const lineNodes = Array.from(\n this.#element.querySelectorAll(\".CodeMirror-line\")\n );\n const lines = lineNodes.map((line) =>\n CodeMirrorRangeRectCalculator.#getAllTextNodes(line)", "score": 0.7205177545547485 } ]
typescript
const errors = annotations.map(({error}) => error);
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": " 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": 0.8475338220596313 }, { "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": 0.8341162204742432 }, { "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": 0.8240045309066772 }, { "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": 0.8213365077972412 }, { "filename": "src/components/lint-error-annotation.ts", "retrieved_chunk": " const absoluteRect = rect.translate(scrollVector);\n // We want ranges spanning multiple lines to look like one annotation, so we need to\n // expand them to fill the gap around the lines\n const lineHeight = cssLineHeight ?? rect.height * 1.2;\n const scaledRect = absoluteRect.scaleY(lineHeight / absoluteRect.height);\n elements.push(LintErrorAnnotation.#createAnnotationElement(scaledRect));\n }\n this.#container.replaceChildren(...elements);\n this.#elements = elements;\n }", "score": 0.8175686001777649 } ]
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": 0.783161461353302 }, { "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": 0.7710111141204834 }, { "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": 0.7185889482498169 }, { "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": 0.6885316967964172 }, { "filename": "src/services/types.ts", "retrieved_chunk": " pullHeadRef: string;\n pullBaseRef: string;\n pullNumber: number;\n};\nexport type { Octokit, FilenameWithPatch, PullRequestInfo };", "score": 0.688478946685791 } ]
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": " pullHeadRef: string;\n pullBaseRef: string;\n pullNumber: number;\n};\nexport type { Octokit, FilenameWithPatch, PullRequestInfo };", "score": 0.7553034424781799 }, { "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": 0.7503028512001038 }, { "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": 0.6563286781311035 }, { "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": 0.6561138033866882 }, { "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": 0.6455000638961792 } ]
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/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": 0.7597618103027344 }, { "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": 0.7563264966011047 }, { "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": 0.7330371141433716 }, { "filename": "src/services/types.ts", "retrieved_chunk": " pullHeadRef: string;\n pullBaseRef: string;\n pullNumber: number;\n};\nexport type { Octokit, FilenameWithPatch, PullRequestInfo };", "score": 0.7069061994552612 }, { "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": 0.701676607131958 } ]
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/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": 0.7884865999221802 }, { "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": 0.7625547647476196 }, { "filename": "src/services/types.ts", "retrieved_chunk": " pullHeadRef: string;\n pullBaseRef: string;\n pullNumber: number;\n};\nexport type { Octokit, FilenameWithPatch, PullRequestInfo };", "score": 0.7580355405807495 }, { "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": 0.7222966551780701 }, { "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": 0.719448447227478 } ]
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/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": 0.7815436124801636 }, { "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": 0.7788513898849487 }, { "filename": "src/services/types.ts", "retrieved_chunk": " pullHeadRef: string;\n pullBaseRef: string;\n pullNumber: number;\n};\nexport type { Octokit, FilenameWithPatch, PullRequestInfo };", "score": 0.7149426937103271 }, { "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": 0.7131856679916382 }, { "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": 0.7119470834732056 } ]
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": 0.8393142223358154 }, { "filename": "src/services/utils/divideFilesByTokenRange.ts", "retrieved_chunk": " currentArray.push(file);\n currentTokensUsed += file.tokensUsed;\n } else {\n result.push(currentArray);\n currentArray = [file];\n currentTokensUsed = file.tokensUsed;\n }\n }\n if (currentArray.length > 0) {\n result.push(currentArray);", "score": 0.712037205696106 }, { "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": 0.7069690227508545 }, { "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": 0.6936347484588623 }, { "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": 0.6934627294540405 } ]
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/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": 0.7652850151062012 }, { "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": 0.753515362739563 }, { "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": 0.7319937944412231 }, { "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": 0.6849982738494873 }, { "filename": "src/services/types.ts", "retrieved_chunk": " pullHeadRef: string;\n pullBaseRef: string;\n pullNumber: number;\n};\nexport type { Octokit, FilenameWithPatch, PullRequestInfo };", "score": 0.6791877150535583 } ]
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": 0.7676889300346375 }, { "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": 0.7581756114959717 }, { "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": 0.734055757522583 }, { "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": 0.6877155303955078 }, { "filename": "src/services/types.ts", "retrieved_chunk": " pullHeadRef: string;\n pullBaseRef: string;\n pullNumber: number;\n};\nexport type { Octokit, FilenameWithPatch, PullRequestInfo };", "score": 0.6859478950500488 } ]
typescript
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": 0.7752059698104858 }, { "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": 0.7627862691879272 }, { "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": 0.7379002571105957 }, { "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": 0.7007440328598022 }, { "filename": "src/services/types.ts", "retrieved_chunk": " pullHeadRef: string;\n pullBaseRef: string;\n pullNumber: number;\n};\nexport type { Octokit, FilenameWithPatch, PullRequestInfo };", "score": 0.6919172406196594 } ]
typescript
(suggestion) => 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-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": 0.811642587184906 }, { "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": 0.7959346771240234 }, { "filename": "src/components/lint-error-annotation.ts", "retrieved_chunk": " const absoluteRect = rect.translate(scrollVector);\n // We want ranges spanning multiple lines to look like one annotation, so we need to\n // expand them to fill the gap around the lines\n const lineHeight = cssLineHeight ?? rect.height * 1.2;\n const scaledRect = absoluteRect.scaleY(lineHeight / absoluteRect.height);\n elements.push(LintErrorAnnotation.#createAnnotationElement(scaledRect));\n }\n this.#container.replaceChildren(...elements);\n this.#elements = elements;\n }", "score": 0.787267804145813 }, { "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": 0.7780811786651611 }, { "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": 0.7743200063705444 } ]
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": 0.8248355388641357 }, { "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": 0.7116116285324097 }, { "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": 0.7047911882400513 }, { "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": 0.7025633454322815 }, { "filename": "src/services/utils/divideFilesByTokenRange.ts", "retrieved_chunk": " currentArray.push(file);\n currentTokensUsed += file.tokensUsed;\n } else {\n result.push(currentArray);\n currentArray = [file];\n currentTokensUsed = file.tokensUsed;\n }\n }\n if (currentArray.length > 0) {\n result.push(currentArray);", "score": 0.7024252414703369 } ]
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": 0.7726460695266724 }, { "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": 0.7555226683616638 }, { "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": 0.7415643930435181 }, { "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": 0.7403607964515686 }, { "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": 0.739902675151825 } ]
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/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": 0.7861262559890747 }, { "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": 0.7846541404724121 }, { "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": 0.7624102830886841 }, { "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": 0.7593109607696533 }, { "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": 0.7591222524642944 } ]
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/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": 0.754325807094574 }, { "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": 0.7325900197029114 }, { "filename": "src/modules/saveApiFile.ts", "retrieved_chunk": " * @param {Object} options 用户传入的自定义配置选项\n */\nexport async function saveApiFile(pbtsFilePath: string, options: IOptions) {\n const {\n requestModule,\n baseUrl,\n } = options;\n // 获取当前d.ts文件的目录名称和文件名称\n const tsDefineDirname = path.dirname(pbtsFilePath);\n const tsDefineFilename = path.basename(pbtsFilePath);", "score": 0.7191663980484009 }, { "filename": "src/modules/travelAllModule.ts", "retrieved_chunk": " const hasModule = children.length > 0;\n const fullName = `${parentName ? `${parentName}.` : ''}${module.getName()}`;\n callback(module, fullName);\n if (hasModule) {\n travelAllModule(children, callback, fullName);\n }\n }\n}", "score": 0.717566728591919 }, { "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": 0.7022875547409058 } ]
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": 0.8015433549880981 }, { "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": 0.7999531030654907 }, { "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": 0.7959960699081421 }, { "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": 0.7795333862304688 }, { "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": 0.769261360168457 } ]
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/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": 0.7915422916412354 }, { "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": 0.7802917957305908 }, { "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": 0.7574494481086731 }, { "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": 0.7572226524353027 }, { "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": 0.7542070150375366 } ]
typescript
initServer(options);
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": " 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": 0.8461204767227173 }, { "filename": "src/utilities/dom/range-rect-calculator.ts", "retrieved_chunk": " this.#range.setStart(...start);\n this.#range.setEnd(...end);\n return Array.from(this.#range.getClientRects()).map(\n (domRect) => new Rect(domRect)\n );\n }\n disconnect(): void {}\n static #getAllTextNodes(node: Node): Node[] {\n const walker = document.createTreeWalker(node, NodeFilter.SHOW_TEXT);\n const nodes = [];", "score": 0.7523829340934753 }, { "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": 0.7499904632568359 }, { "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": 0.7408946752548218 }, { "filename": "src/utilities/dom/range-rect-calculator.ts", "retrieved_chunk": " );\n this.#element = target;\n this.#range = document.createRange();\n }\n getClientRects(range: NumberRange): Rect[] {\n const lineNodes = Array.from(\n this.#element.querySelectorAll(\".CodeMirror-line\")\n );\n const lines = lineNodes.map((line) =>\n CodeMirrorRangeRectCalculator.#getAllTextNodes(line)", "score": 0.7310812473297119 } ]
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": " 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": 0.8404337167739868 }, { "filename": "src/components/lint-error-annotation.ts", "retrieved_chunk": " const absoluteRect = rect.translate(scrollVector);\n // We want ranges spanning multiple lines to look like one annotation, so we need to\n // expand them to fill the gap around the lines\n const lineHeight = cssLineHeight ?? rect.height * 1.2;\n const scaledRect = absoluteRect.scaleY(lineHeight / absoluteRect.height);\n elements.push(LintErrorAnnotation.#createAnnotationElement(scaledRect));\n }\n this.#container.replaceChildren(...elements);\n this.#elements = elements;\n }", "score": 0.7695305347442627 }, { "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": 0.765360951423645 }, { "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": 0.7586686611175537 }, { "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": 0.7558308243751526 } ]
typescript
a.containsPoint(pointerLocation) );
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": 0.8634171485900879 }, { "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": 0.809224009513855 }, { "filename": "src/components/lint-error-annotation.ts", "retrieved_chunk": " const absoluteRect = rect.translate(scrollVector);\n // We want ranges spanning multiple lines to look like one annotation, so we need to\n // expand them to fill the gap around the lines\n const lineHeight = cssLineHeight ?? rect.height * 1.2;\n const scaledRect = absoluteRect.scaleY(lineHeight / absoluteRect.height);\n elements.push(LintErrorAnnotation.#createAnnotationElement(scaledRect));\n }\n this.#container.replaceChildren(...elements);\n this.#elements = elements;\n }", "score": 0.7752767205238342 }, { "filename": "src/components/linted-markdown-editor.ts", "retrieved_chunk": " }\n get caretPosition() {\n const selection = document.getSelection();\n const range = selection?.getRangeAt(0);\n if (!range?.collapsed || selection?.rangeCount !== 1) return -1;\n const referenceRange = document.createRange();\n referenceRange.selectNodeContents(this.#element);\n referenceRange.setEnd(range.startContainer, range.startOffset);\n return referenceRange.toString().length;\n }", "score": 0.7467300891876221 }, { "filename": "src/utilities/geometry/rect.ts", "retrieved_chunk": " const scaledHeight = this.height * factor;\n const deltaY = (this.height - scaledHeight) / 2;\n return this.translate(new Vector(0, deltaY)).copy({height: scaledHeight});\n }\n}", "score": 0.7452440857887268 } ]
typescript
).translate(netTranslate) );
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/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": 0.7693004012107849 }, { "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": 0.7647542953491211 }, { "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": 0.7492647171020508 }, { "filename": "src/types/alert.ts", "retrieved_chunk": "import { CfnResource } from \"aws-cdk-lib\";\nimport { QueryOperationString, QueryParameters } from \"./query\";\nexport type AlertProps<TKey extends string> = {\n\tdescription?: string;\n\tenabled?: boolean;\n\tparameters: {\n\t\tquery: CfnResource | QueryParameters<TKey>,\n\t\tthreshold?: {\n\t\t\toperation?: QueryOperationString,\n\t\t\tvalue: string | number", "score": 0.7375560998916626 }, { "filename": "src/types/dashboard.ts", "retrieved_chunk": "import { CfnResource } from \"aws-cdk-lib\";\nexport type DashboardProps = {\n\tdescription?: string;\n\tparameters: DeploymentDashboardParameters;\n};\ninterface DeploymentDashboardParameters {\n\twidgets: Array<{\n\t\tname?: string;\n\t\tdescription?: string;\n\t\tquery: CfnResource;", "score": 0.7174244523048401 } ]
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\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": 0.7506853342056274 }, { "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": 0.7501338124275208 }, { "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": 0.7182499170303345 }, { "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": 0.6837076544761658 }, { "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": 0.682066798210144 } ]
typescript
const Parameters: DeploymentQueryParameters = {