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
/* * Copyright (c) AXA Group Operations Spain S.A. * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import { NlpManager } from '../nlp'; import MemoryConversationContext from './memory-conversation-context'; /** * Microsoft Bot Framework compatible recognizer for nlp.js. */ class Recognizer { private readonly nlpManager: NlpManager; private readonly threshold: number; private readonly conversationContext: MemoryConversationContext; /** * Constructor of the class. * @param {Object} settings Settings for the instance. */ constructor(private readonly settings: { nlpManager?: NlpManager; container?: any; nerThreshold?: number; threshold?: number; conversationContext?: MemoryConversationContext; }) { this.nlpManager = this.settings.nlpManager || new NlpManager({ container: this.settings.container, ner: { threshold: this.settings.nerThreshold || 1 }, }); this.threshold = this.settings.threshold || 0.7; this.conversationContext = this.settings.conversationContext || new MemoryConversationContext({}); } /** * Train the NLP manager. */ public async train(): Promise<void> { await this.nlpManager.train(); } /** * Loads the model from a file. * @param {String} filename Name of the file. */ public load(filename: string): void {
this.nlpManager.load(filename);
} /** * Saves the model into a file. * @param {String} filename Name of the file. */ public save(filename: string): void { this.nlpManager.save(filename); } /** * Loads the NLP manager from an excel. * @param {String} filename Name of the file. */ public async loadExcel(filename: string): Promise<void> { this.nlpManager.loadExcel(filename); await this.train(); this.save(filename); } /** * Process an utterance using the NLP manager. This is done using a given context * as the context object. * @param {Object} srcContext Source context * @param {String} locale Locale of the utterance. * @param {String} utterance Locale of the utterance. */ public async process( srcContext: Record<string, unknown>, locale?: string, utterance?: string ): Promise<string> { const context = srcContext || {}; const response = await (locale ? this.nlpManager.process(locale, utterance, context) : this.nlpManager.process(utterance, undefined, context)); if (response.score < this.threshold || response.intent === 'None') { response.answer = undefined; return response; } for (let i = 0; i < response.entities.length; i += 1) { const entity = response.entities[i]; context[entity.entity] = entity.option; } if (response.slotFill) { context.slotFill = response.slotFill; } else { delete context.slotFill; } return response; } /** * Given an utterance and the locale, returns the recognition of the utterance. * @param {String} utterance Utterance to be recognized. * @param {String} model Model of the utterance. * @param {Function} cb Callback Function. */ public async recognizeUtterance(utterance: string, model: {locale: string}, cb: Function): Promise<any> { const response = await this.process( model, model ? model.locale : undefined, utterance ); return cb(null, response); } } export default Recognizer;
src/recognizer/recognizer.ts
Leoglme-node-nlp-typescript-fbee5fd
[ { "filename": "src/nlp/nlp-manager.ts", "retrieved_chunk": " * @param srcFileName\n */\n load(srcFileName?: string): void {\n const fileName = srcFileName || 'model.nlp';\n const data = fs.readFileSync(fileName, 'utf8');\n this.import(data);\n }\n /**\n * Load the NLP manager information from an Excel file.\n * @param fileName", "score": 33.67901891658537 }, { "filename": "src/nlp/nlp-manager.ts", "retrieved_chunk": " * Save the NLP manager information into a file.\n * @param {String} srcFileName Filename for saving the NLP manager.\n * @param minified\n */\n save(srcFileName?: string, minified = false): void {\n const fileName = srcFileName || 'model.nlp';\n fs.writeFileSync(fileName, this.export(minified), 'utf8');\n }\n /**\n * Load the NLP manager information from a file.", "score": 33.08632554463863 }, { "filename": "src/nlp/nlp-excel-reader.ts", "retrieved_chunk": "import { XDoc } from '@nlpjs/xtables';\nimport NlpManager from './nlp-manager';\nclass NlpExcelReader {\n private manager: NlpManager;\n private xdoc: XDoc;\n constructor(manager: NlpManager) {\n this.manager = manager;\n this.xdoc = new XDoc();\n }\n load(filename: string): void {", "score": 28.327953541597086 }, { "filename": "src/sentiment/sentiment-manager.ts", "retrieved_chunk": " }\n /**\n * Process a phrase of a given locale, calculating the sentiment analysis.\n * @param {String} locale Locale of the phrase.\n * @param {String} phrase Phrase to calculate the sentiment.\n * @returns {Promise Object} Promise sentiment analysis of the phrase.\n */\n async process(locale: string, phrase: string) {\n const sentiment = await this.analyzer.getSentiment(\n phrase,", "score": 24.927925687707756 }, { "filename": "src/nlp/nlp-excel-reader.ts", "retrieved_chunk": " this.xdoc.read(filename);\n this.loadSettings();\n this.loadLanguages();\n this.loadNamedEntities();\n this.loadRegexEntities();\n this.loadIntents();\n this.loadResponses();\n }\n loadSettings(): void {}\n loadLanguages(): void {", "score": 21.942980161651505 } ]
typescript
this.nlpManager.load(filename);
import { Context, MiddlewareHandler } from 'hono' import { Instructions, ExporioMiddlewareOptions, RequestJson } from './types' import { After, Append, AppendGlobalCode, Before, Prepend, Remove, RemoveAndKeepContent, RemoveAttribute, Replace, SetAttribute, SetInnerContent, SetStyleProperty, } from './htmlRewriterClasses' export const exporioMiddleware = (options: ExporioMiddlewareOptions): MiddlewareHandler => { if (!options.url) { options.url = 'https://edge-api.exporio.cloud' } if (!options.apiKey) { throw new Error('Exporio middleware requires options for "apiKey"') } return async (c, next) => { const exporioInstructions = await fetchExporioInstructions(c, options) if (!exporioInstructions) { c.set('contentUrl', c.req.url) await next() } else { c.set('contentUrl', getContentUrl(exporioInstructions, c.req.url)) await next() applyRewriterInstruction(c, exporioInstructions) applyCookieInstruction(c.res.headers, exporioInstructions) } } } const buildRequestJson = (c: Context
, apiKey: string): RequestJson => {
const headersInit: HeadersInit = [] c.req.headers.forEach((value: string, key: string) => headersInit.push([key, value])) return { originalRequest: { url: c.req.url, method: c.req.method, headersInit: headersInit, }, params: { API_KEY: apiKey, }, } } const fetchExporioInstructions = async ( c: Context, options: ExporioMiddlewareOptions ): Promise<Instructions | null> => { try { const requestJson = buildRequestJson(c, options.apiKey) const exporioRequest = new Request(options.url, { method: 'POST', body: JSON.stringify(requestJson), headers: { 'Content-Type': 'application/json' }, }) const exporioResponse = await fetch(exporioRequest) return await exporioResponse.json() } catch (err) { console.error('Failed to fetch exporio instructions', err) return null } } const getContentUrl = (instructions: Instructions, defaultUrl: string): string => { const customUrlInstruction = instructions?.customUrlInstruction return customUrlInstruction?.loadCustomUrl && customUrlInstruction?.customUrl ? customUrlInstruction.customUrl : defaultUrl } const applyRewriterInstruction = (c: Context, instructions: Instructions) => { let response = new Response(c.res.body, c.res) instructions?.rewriterInstruction?.transformations?.forEach(({ selector, argument1, argument2, method }) => { switch (method) { // Default Methods case 'After': { const rewriter = new HTMLRewriter().on(selector, new After(argument1, argument2)) response = rewriter.transform(response) break } case 'Append': { const rewriter = new HTMLRewriter().on(selector, new Append(argument1, argument2)) response = rewriter.transform(response) break } case 'Before': { const rewriter = new HTMLRewriter().on(selector, new Before(argument1, argument2)) response = rewriter.transform(response) break } case 'Prepend': { const rewriter = new HTMLRewriter().on(selector, new Prepend(argument1, argument2)) response = rewriter.transform(response) break } case 'Remove': { const rewriter = new HTMLRewriter().on(selector, new Remove()) response = rewriter.transform(response) break } case 'RemoveAndKeepContent': { const rewriter = new HTMLRewriter().on(selector, new RemoveAndKeepContent()) response = rewriter.transform(response) break } case 'RemoveAttribute': { const rewriter = new HTMLRewriter().on(selector, new RemoveAttribute(argument1)) response = rewriter.transform(response) break } case 'Replace': { const rewriter = new HTMLRewriter().on(selector, new Replace(argument1, argument2)) response = rewriter.transform(response) break } case 'SetAttribute': { const rewriter = new HTMLRewriter().on(selector, new SetAttribute(argument1, argument2)) response = rewriter.transform(response) break } case 'SetInnerContent': { const rewriter = new HTMLRewriter().on(selector, new SetInnerContent(argument1, argument2)) response = rewriter.transform(response) break } // Custom Methods case 'AppendGlobalCode': { const rewriter = new HTMLRewriter().on(selector, new AppendGlobalCode(argument1, argument2)) response = rewriter.transform(response) break } case 'SetStyleProperty': { const rewriter = new HTMLRewriter().on(selector, new SetStyleProperty(argument1, argument2)) response = rewriter.transform(response) break } } }) c.res = new Response(response.body, response) } const applyCookieInstruction = (headers: Headers, instructions: Instructions) => { instructions?.cookieInstruction?.cookies.forEach((cookie) => { let cookieAttributes = [`${cookie.name}=${cookie.value}`] if (cookie.domain) { cookieAttributes.push(`Domain=${cookie.domain}`) } if (cookie.path) { cookieAttributes.push(`Path=${cookie.path}`) } if (cookie.expires) { cookieAttributes.push(`Expires=${cookie.expires}`) } if (cookie.maxAge) { cookieAttributes.push(`Max-Age=${cookie.maxAge}`) } if (cookie.httpOnly) { cookieAttributes.push('HttpOnly') } if (cookie.secure) { cookieAttributes.push('Secure') } if (cookie.sameSite) { cookieAttributes.push(`SameSite=${cookie.sameSite}`) } if (cookie.partitioned) { cookieAttributes.push('Partitioned') } headers.append('Set-Cookie', cookieAttributes.join('; ')) }) }
src/index.ts
exporio-edge-sdk-hono-23bcafc
[ { "filename": "src/types/general.ts", "retrieved_chunk": "type ExporioMiddlewareOptions = {\n url: string\n apiKey: string\n}\ntype RequestJson = {\n originalRequest: {\n url: string\n method: string\n headersInit: HeadersInit\n }", "score": 9.658877754809476 }, { "filename": "src/htmlRewriterClasses/SetStyleProperty.ts", "retrieved_chunk": " const styleProperties = currentStyleAttribute.split(';')\n styleProperties.forEach((property) => {\n if (property.includes(`${this.propertyName}:`)) {\n currentStyleAttribute = currentStyleAttribute.replace(\n property,\n `${this.propertyName}:${this.propertyValue}`\n )\n }\n })\n } else {", "score": 4.733507846183725 }, { "filename": "src/types/general.ts", "retrieved_chunk": " params: {\n API_KEY: string\n [key: string]: any\n }\n}\nexport { ExporioMiddlewareOptions, RequestJson }", "score": 2.690837462715257 }, { "filename": "src/types/index.ts", "retrieved_chunk": "export { ExporioMiddlewareOptions, RequestJson } from './general'\nexport {\n Instructions,\n CustomUrlInstruction,\n RewriterInstruction,\n Transformation,\n CookieInstruction,\n Cookie,\n} from './instructions'", "score": 2.195530015750635 }, { "filename": "src/htmlRewriterClasses/AppendGlobalCode.ts", "retrieved_chunk": "class AppendGlobalCode {\n htmlTag?: string\n content: string\n constructor(htmlTag: string, content: string) {\n this.htmlTag = htmlTag\n this.content = content\n }\n element(element: Element) {\n const contentWithTags = `<${this.htmlTag}>${this.content}</${this.htmlTag}>`\n element.append(contentWithTags, { html: true })", "score": 1.7322915288081508 } ]
typescript
, apiKey: string): RequestJson => {
/* * Copyright (c) AXA Group Operations Spain S.A. * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import { NlpManager } from '../nlp'; import MemoryConversationContext from './memory-conversation-context'; /** * Microsoft Bot Framework compatible recognizer for nlp.js. */ class Recognizer { private readonly nlpManager: NlpManager; private readonly threshold: number; private readonly conversationContext: MemoryConversationContext; /** * Constructor of the class. * @param {Object} settings Settings for the instance. */ constructor(private readonly settings: { nlpManager?: NlpManager; container?: any; nerThreshold?: number; threshold?: number; conversationContext?: MemoryConversationContext; }) { this.nlpManager = this.settings.nlpManager || new NlpManager({ container: this.settings.container, ner: { threshold: this.settings.nerThreshold || 1 }, }); this.threshold = this.settings.threshold || 0.7; this.conversationContext = this.settings.conversationContext || new MemoryConversationContext({}); } /** * Train the NLP manager. */ public async train(): Promise<void> { await this.nlpManager.train(); } /** * Loads the model from a file. * @param {String} filename Name of the file. */ public load(filename: string): void { this.nlpManager.load(filename); } /** * Saves the model into a file. * @param {String} filename Name of the file. */ public save(filename: string): void { this.nlpManager.save(filename); } /** * Loads the NLP manager from an excel. * @param {String} filename Name of the file. */ public async loadExcel(filename: string): Promise<void> { this.nlpManager.loadExcel(filename); await this.train(); this.save(filename); } /** * Process an utterance using the NLP manager. This is done using a given context * as the context object. * @param {Object} srcContext Source context * @param {String} locale Locale of the utterance. * @param {String} utterance Locale of the utterance. */ public async process( srcContext: Record<string, unknown>, locale?: string, utterance?: string ): Promise<string> { const context = srcContext || {}; const response = await (locale
? this.nlpManager.process(locale, utterance, context) : this.nlpManager.process(utterance, undefined, context));
if (response.score < this.threshold || response.intent === 'None') { response.answer = undefined; return response; } for (let i = 0; i < response.entities.length; i += 1) { const entity = response.entities[i]; context[entity.entity] = entity.option; } if (response.slotFill) { context.slotFill = response.slotFill; } else { delete context.slotFill; } return response; } /** * Given an utterance and the locale, returns the recognition of the utterance. * @param {String} utterance Utterance to be recognized. * @param {String} model Model of the utterance. * @param {Function} cb Callback Function. */ public async recognizeUtterance(utterance: string, model: {locale: string}, cb: Function): Promise<any> { const response = await this.process( model, model ? model.locale : undefined, utterance ); return cb(null, response); } } export default Recognizer;
src/recognizer/recognizer.ts
Leoglme-node-nlp-typescript-fbee5fd
[ { "filename": "src/nlp/nlp-manager.ts", "retrieved_chunk": " async train(): Promise<void> {\n return this.nlp.train();\n }\n classify(locale: string, utterance: string, settings?: Record<string, unknown>): Promise<any> {\n return this.nlp.classify(locale, utterance, settings);\n }\n async process(locale?: string, utterance?: string, context?: Record<string, unknown>, settings?: Record<string, unknown>): Promise<any> {\n const result = await this.nlp.process(locale, utterance, context, settings);\n if (this.settings.processTransformer) {\n return this.settings.processTransformer(result);", "score": 65.00401448240218 }, { "filename": "src/sentiment/sentiment-analyzer.ts", "retrieved_chunk": " this.container.use(Nlu);\n }\n async getSentiment(utterance: string, locale = 'en', settings: [key: string]) {\n const input = {\n utterance,\n locale,\n ...settings,\n };\n const result = await this.process(input);\n return result.sentiment;", "score": 46.63835539075688 }, { "filename": "src/nlp/nlp-manager.ts", "retrieved_chunk": " }\n return result;\n }\n extractEntities(locale: string, utterance: string, context?: Record<string, unknown>, settings?: Record<string, unknown>): Promise<any> {\n return this.nlp.extractEntities(locale, utterance, context, settings);\n }\n toObj(): any {\n return this.nlp.toJSON();\n }\n fromObj(obj: any): any {", "score": 43.309650703159924 }, { "filename": "src/nlu/brain-nlu.ts", "retrieved_chunk": " async getClassifications(utterance: string) {\n const result = await this.nlu?.process(utterance);\n return result?.classifications.sort((a, b) => b.score - a.score);\n }\n async getBestClassification(utterance: string) {\n const result = await this.getClassifications(utterance);\n return result?.[0];\n }\n}\nexport default BrainNLU;", "score": 41.53289972721397 }, { "filename": "src/nlg/nlg-manager.ts", "retrieved_chunk": " return this.add(locale, intent, answer, opts);\n }\n async findAnswer(locale: string, intent: string, context: any, settings?: any): Promise<{ response: any } | undefined> {\n const answer = await this.find(locale, intent, context, settings);\n if (!answer.answer) {\n return undefined;\n }\n return {\n response: answer.answer,\n };", "score": 40.49489090152133 } ]
typescript
? this.nlpManager.process(locale, utterance, context) : this.nlpManager.process(utterance, undefined, context));
import { Context, MiddlewareHandler } from 'hono' import { Instructions, ExporioMiddlewareOptions, RequestJson } from './types' import { After, Append, AppendGlobalCode, Before, Prepend, Remove, RemoveAndKeepContent, RemoveAttribute, Replace, SetAttribute, SetInnerContent, SetStyleProperty, } from './htmlRewriterClasses' export const exporioMiddleware = (options: ExporioMiddlewareOptions): MiddlewareHandler => { if (!options.url) { options.url = 'https://edge-api.exporio.cloud' } if (!options.apiKey) { throw new Error('Exporio middleware requires options for "apiKey"') } return async (c, next) => { const exporioInstructions = await fetchExporioInstructions(c, options) if (!exporioInstructions) { c.set('contentUrl', c.req.url) await next() } else { c.set('contentUrl', getContentUrl(exporioInstructions, c.req.url)) await next() applyRewriterInstruction(c, exporioInstructions) applyCookieInstruction(c.res.headers, exporioInstructions) } } } const buildRequestJson = (c: Context, apiKey: string): RequestJson => { const headersInit: HeadersInit = [] c.req.headers.forEach((value: string, key: string) => headersInit.push([key, value])) return { originalRequest: { url: c.req.url, method: c.req.method, headersInit: headersInit, }, params: { API_KEY: apiKey, }, } } const fetchExporioInstructions = async ( c: Context, options: ExporioMiddlewareOptions ): Promise<Instructions | null> => { try { const requestJson = buildRequestJson(c, options.apiKey) const exporioRequest = new Request(options.url, { method: 'POST', body: JSON.stringify(requestJson), headers: { 'Content-Type': 'application/json' }, }) const exporioResponse = await fetch(exporioRequest) return await exporioResponse.json() } catch (err) { console.error('Failed to fetch exporio instructions', err) return null } } const getContentUrl = (instructions: Instructions, defaultUrl: string): string => { const customUrlInstruction = instructions?.customUrlInstruction return customUrlInstruction?.loadCustomUrl && customUrlInstruction?.customUrl ? customUrlInstruction.customUrl : defaultUrl } const applyRewriterInstruction = (c: Context, instructions: Instructions) => { let response = new Response(c.res.body, c.res) instructions?.rewriterInstruction?.transformations?.forEach(({ selector, argument1, argument2, method }) => { switch (method) { // Default Methods case 'After': { const rewriter = new HTMLRewriter().on(selector, new After(argument1, argument2)) response = rewriter.transform(response) break } case 'Append': { const rewriter = new HTMLRewriter().on(selector, new Append(argument1, argument2)) response = rewriter.transform(response) break } case 'Before': { const rewriter = new HTMLRewriter().on(selector, new Before(argument1, argument2)) response = rewriter.transform(response) break } case 'Prepend': { const rewriter = new HTMLRewriter().on(selector, new Prepend(argument1, argument2)) response = rewriter.transform(response) break } case 'Remove': { const rewriter = new HTMLRewriter().on(selector, new Remove()) response = rewriter.transform(response) break } case 'RemoveAndKeepContent': { const rewriter = new HTMLRewriter().on(selector, new RemoveAndKeepContent()) response = rewriter.transform(response) break } case 'RemoveAttribute': { const rewriter = new HTMLRewriter().on(selector, new RemoveAttribute(argument1)) response = rewriter.transform(response) break } case 'Replace': { const rewriter = new HTMLRewriter().on(selector, new Replace(argument1, argument2)) response = rewriter.transform(response) break } case 'SetAttribute': { const rewriter = new HTMLRewriter().on(selector, new SetAttribute(argument1, argument2)) response = rewriter.transform(response) break } case 'SetInnerContent': { const rewriter = new HTMLRewriter().on(selector, new SetInnerContent(argument1, argument2)) response = rewriter.transform(response) break } // Custom Methods case 'AppendGlobalCode': { const rewriter = new HTMLRewriter().on(selector, new AppendGlobalCode(argument1, argument2)) response = rewriter.transform(response) break } case 'SetStyleProperty': { const rewriter = new HTMLRewriter().on(selector, new SetStyleProperty(argument1, argument2)) response = rewriter.transform(response) break } } }) c.res = new Response(response.body, response) } const applyCookieInstruction = (headers: Headers, instructions: Instructions) => { instructions
?.cookieInstruction?.cookies.forEach((cookie) => {
let cookieAttributes = [`${cookie.name}=${cookie.value}`] if (cookie.domain) { cookieAttributes.push(`Domain=${cookie.domain}`) } if (cookie.path) { cookieAttributes.push(`Path=${cookie.path}`) } if (cookie.expires) { cookieAttributes.push(`Expires=${cookie.expires}`) } if (cookie.maxAge) { cookieAttributes.push(`Max-Age=${cookie.maxAge}`) } if (cookie.httpOnly) { cookieAttributes.push('HttpOnly') } if (cookie.secure) { cookieAttributes.push('Secure') } if (cookie.sameSite) { cookieAttributes.push(`SameSite=${cookie.sameSite}`) } if (cookie.partitioned) { cookieAttributes.push('Partitioned') } headers.append('Set-Cookie', cookieAttributes.join('; ')) }) }
src/index.ts
exporio-edge-sdk-hono-23bcafc
[ { "filename": "src/types/index.ts", "retrieved_chunk": "export { ExporioMiddlewareOptions, RequestJson } from './general'\nexport {\n Instructions,\n CustomUrlInstruction,\n RewriterInstruction,\n Transformation,\n CookieInstruction,\n Cookie,\n} from './instructions'", "score": 8.891060236655811 }, { "filename": "src/types/instructions.ts", "retrieved_chunk": "type Instructions = {\n customUrlInstruction: CustomUrlInstruction\n rewriterInstruction: RewriterInstruction\n cookieInstruction: CookieInstruction\n}\nexport { Instructions, CustomUrlInstruction, RewriterInstruction, Transformation, CookieInstruction, Cookie }", "score": 6.62712768331548 }, { "filename": "src/htmlRewriterClasses/SetStyleProperty.ts", "retrieved_chunk": " const styleProperties = currentStyleAttribute.split(';')\n styleProperties.forEach((property) => {\n if (property.includes(`${this.propertyName}:`)) {\n currentStyleAttribute = currentStyleAttribute.replace(\n property,\n `${this.propertyName}:${this.propertyValue}`\n )\n }\n })\n } else {", "score": 4.733507846183725 }, { "filename": "src/types/instructions.ts", "retrieved_chunk": " partitioned?: boolean\n}\ntype CookieInstruction = {\n setCookie: boolean\n cookies: Cookie[]\n}\ntype Transformation = {\n method: string\n selector: string\n argument1: any", "score": 2.9733976641276003 }, { "filename": "src/htmlRewriterClasses/AppendGlobalCode.ts", "retrieved_chunk": "class AppendGlobalCode {\n htmlTag?: string\n content: string\n constructor(htmlTag: string, content: string) {\n this.htmlTag = htmlTag\n this.content = content\n }\n element(element: Element) {\n const contentWithTags = `<${this.htmlTag}>${this.content}</${this.htmlTag}>`\n element.append(contentWithTags, { html: true })", "score": 1.6398428205518238 } ]
typescript
?.cookieInstruction?.cookies.forEach((cookie) => {
import { Context, MiddlewareHandler } from 'hono' import { Instructions, ExporioMiddlewareOptions, RequestJson } from './types' import { After, Append, AppendGlobalCode, Before, Prepend, Remove, RemoveAndKeepContent, RemoveAttribute, Replace, SetAttribute, SetInnerContent, SetStyleProperty, } from './htmlRewriterClasses' export const exporioMiddleware = (options: ExporioMiddlewareOptions): MiddlewareHandler => { if (!options.url) { options.url = 'https://edge-api.exporio.cloud' } if (!options.apiKey) { throw new Error('Exporio middleware requires options for "apiKey"') } return async (c, next) => { const exporioInstructions = await fetchExporioInstructions(c, options) if (!exporioInstructions) { c.set('contentUrl', c.req.url) await next() } else { c.set('contentUrl', getContentUrl(exporioInstructions, c.req.url)) await next() applyRewriterInstruction(c, exporioInstructions) applyCookieInstruction(c.res.headers, exporioInstructions) } } } const buildRequestJson = (c: Context, apiKey: string): RequestJson => { const headersInit: HeadersInit = [] c.req.headers.forEach((value: string, key: string) => headersInit.push([key, value])) return { originalRequest: { url: c.req.url, method: c.req.method, headersInit: headersInit, }, params: { API_KEY: apiKey, }, } } const fetchExporioInstructions = async ( c: Context, options: ExporioMiddlewareOptions )
: Promise<Instructions | null> => {
try { const requestJson = buildRequestJson(c, options.apiKey) const exporioRequest = new Request(options.url, { method: 'POST', body: JSON.stringify(requestJson), headers: { 'Content-Type': 'application/json' }, }) const exporioResponse = await fetch(exporioRequest) return await exporioResponse.json() } catch (err) { console.error('Failed to fetch exporio instructions', err) return null } } const getContentUrl = (instructions: Instructions, defaultUrl: string): string => { const customUrlInstruction = instructions?.customUrlInstruction return customUrlInstruction?.loadCustomUrl && customUrlInstruction?.customUrl ? customUrlInstruction.customUrl : defaultUrl } const applyRewriterInstruction = (c: Context, instructions: Instructions) => { let response = new Response(c.res.body, c.res) instructions?.rewriterInstruction?.transformations?.forEach(({ selector, argument1, argument2, method }) => { switch (method) { // Default Methods case 'After': { const rewriter = new HTMLRewriter().on(selector, new After(argument1, argument2)) response = rewriter.transform(response) break } case 'Append': { const rewriter = new HTMLRewriter().on(selector, new Append(argument1, argument2)) response = rewriter.transform(response) break } case 'Before': { const rewriter = new HTMLRewriter().on(selector, new Before(argument1, argument2)) response = rewriter.transform(response) break } case 'Prepend': { const rewriter = new HTMLRewriter().on(selector, new Prepend(argument1, argument2)) response = rewriter.transform(response) break } case 'Remove': { const rewriter = new HTMLRewriter().on(selector, new Remove()) response = rewriter.transform(response) break } case 'RemoveAndKeepContent': { const rewriter = new HTMLRewriter().on(selector, new RemoveAndKeepContent()) response = rewriter.transform(response) break } case 'RemoveAttribute': { const rewriter = new HTMLRewriter().on(selector, new RemoveAttribute(argument1)) response = rewriter.transform(response) break } case 'Replace': { const rewriter = new HTMLRewriter().on(selector, new Replace(argument1, argument2)) response = rewriter.transform(response) break } case 'SetAttribute': { const rewriter = new HTMLRewriter().on(selector, new SetAttribute(argument1, argument2)) response = rewriter.transform(response) break } case 'SetInnerContent': { const rewriter = new HTMLRewriter().on(selector, new SetInnerContent(argument1, argument2)) response = rewriter.transform(response) break } // Custom Methods case 'AppendGlobalCode': { const rewriter = new HTMLRewriter().on(selector, new AppendGlobalCode(argument1, argument2)) response = rewriter.transform(response) break } case 'SetStyleProperty': { const rewriter = new HTMLRewriter().on(selector, new SetStyleProperty(argument1, argument2)) response = rewriter.transform(response) break } } }) c.res = new Response(response.body, response) } const applyCookieInstruction = (headers: Headers, instructions: Instructions) => { instructions?.cookieInstruction?.cookies.forEach((cookie) => { let cookieAttributes = [`${cookie.name}=${cookie.value}`] if (cookie.domain) { cookieAttributes.push(`Domain=${cookie.domain}`) } if (cookie.path) { cookieAttributes.push(`Path=${cookie.path}`) } if (cookie.expires) { cookieAttributes.push(`Expires=${cookie.expires}`) } if (cookie.maxAge) { cookieAttributes.push(`Max-Age=${cookie.maxAge}`) } if (cookie.httpOnly) { cookieAttributes.push('HttpOnly') } if (cookie.secure) { cookieAttributes.push('Secure') } if (cookie.sameSite) { cookieAttributes.push(`SameSite=${cookie.sameSite}`) } if (cookie.partitioned) { cookieAttributes.push('Partitioned') } headers.append('Set-Cookie', cookieAttributes.join('; ')) }) }
src/index.ts
exporio-edge-sdk-hono-23bcafc
[ { "filename": "src/types/general.ts", "retrieved_chunk": " params: {\n API_KEY: string\n [key: string]: any\n }\n}\nexport { ExporioMiddlewareOptions, RequestJson }", "score": 10.020842641849754 }, { "filename": "src/types/general.ts", "retrieved_chunk": "type ExporioMiddlewareOptions = {\n url: string\n apiKey: string\n}\ntype RequestJson = {\n originalRequest: {\n url: string\n method: string\n headersInit: HeadersInit\n }", "score": 5.191803728565614 }, { "filename": "src/types/index.ts", "retrieved_chunk": "export { ExporioMiddlewareOptions, RequestJson } from './general'\nexport {\n Instructions,\n CustomUrlInstruction,\n RewriterInstruction,\n Transformation,\n CookieInstruction,\n Cookie,\n} from './instructions'", "score": 4.779422227239168 }, { "filename": "src/types/instructions.ts", "retrieved_chunk": "type Instructions = {\n customUrlInstruction: CustomUrlInstruction\n rewriterInstruction: RewriterInstruction\n cookieInstruction: CookieInstruction\n}\nexport { Instructions, CustomUrlInstruction, RewriterInstruction, Transformation, CookieInstruction, Cookie }", "score": 3.566286364893414 }, { "filename": "src/types/instructions.ts", "retrieved_chunk": " argument2: any\n}\ntype RewriterInstruction = {\n useRewriter: boolean\n transformations: Transformation[]\n}\ntype CustomUrlInstruction = {\n loadCustomUrl: boolean\n customUrl: string | null\n}", "score": 3.060841318422066 } ]
typescript
: Promise<Instructions | null> => {
/* * Copyright (c) AXA Group Operations Spain S.A. * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import SentimentAnalyzer from './sentiment-analyzer'; /** * Class for the sentiment analysis manager, able to manage * several languages at the same time. */ class SentimentManager { private readonly settings: any private languages: {} private analyzer: SentimentAnalyzer /** * Constructor of the class. */ constructor(settings?: any) { this.settings = settings || {}; this.languages = {}; this.analyzer = new SentimentAnalyzer(); } addLanguage() { // do nothing } translate(sentiment: {score: number, average: number, type: string, numHits: number, numWords: number, locale: string}) { let vote; if (sentiment.score > 0) { vote = 'positive'; } else if (sentiment.score < 0) { vote = 'negative'; } else { vote = 'neutral'; } return { score: sentiment.score, comparative: sentiment.average, vote, numWords: sentiment.numWords, numHits: sentiment.numHits, type: sentiment.type, language: sentiment.locale, }; } /** * Process a phrase of a given locale, calculating the sentiment analysis. * @param {String} locale Locale of the phrase. * @param {String} phrase Phrase to calculate the sentiment. * @returns {Promise Object} Promise sentiment analysis of the phrase. */ async process(locale: string, phrase: string) {
const sentiment = await this.analyzer.getSentiment( phrase, locale, this.settings );
return this.translate(sentiment); } } export default SentimentManager
src/sentiment/sentiment-manager.ts
Leoglme-node-nlp-typescript-fbee5fd
[ { "filename": "src/recognizer/recognizer.ts", "retrieved_chunk": " return response;\n }\n /**\n * Given an utterance and the locale, returns the recognition of the utterance.\n * @param {String} utterance Utterance to be recognized.\n * @param {String} model Model of the utterance.\n * @param {Function} cb Callback Function.\n */\n public async recognizeUtterance(utterance: string, model: {locale: string}, cb: Function): Promise<any> {\n const response = await this.process(", "score": 48.471665280158795 }, { "filename": "src/recognizer/recognizer.ts", "retrieved_chunk": " }\n /**\n * Process an utterance using the NLP manager. This is done using a given context\n * as the context object.\n * @param {Object} srcContext Source context\n * @param {String} locale Locale of the utterance.\n * @param {String} utterance Locale of the utterance.\n */\n public async process(\n srcContext: Record<string, unknown>,", "score": 44.91561526285787 }, { "filename": "src/nlp/nlp-util.ts", "retrieved_chunk": " zh: false,\n };\n /**\n * Given a locale, get the 2 character one.\n * @param {String} locale Locale of the language.\n * @returns {String} Locale in 2 character length.\n */\n static getTruncatedLocale(locale: string): string | undefined {\n return locale ? locale.substring(0, 2).toLowerCase() : undefined;\n }", "score": 40.35450052068314 }, { "filename": "src/sentiment/sentiment-analyzer.ts", "retrieved_chunk": " this.container.use(Nlu);\n }\n async getSentiment(utterance: string, locale = 'en', settings: [key: string]) {\n const input = {\n utterance,\n locale,\n ...settings,\n };\n const result = await this.process(input);\n return result.sentiment;", "score": 40.19834855830167 }, { "filename": "src/nlp/nlp-manager.ts", "retrieved_chunk": " return this.nlp.addAnswer(locale, intent, answer, opts);\n }\n removeAnswer(locale: string, intent: string, answer: string, opts?: any): boolean {\n return this.nlp.removeAnswer(locale, intent, answer, opts);\n }\n findAllAnswers(locale: string, intent: string): string[] {\n return this.nlp.findAllAnswers(locale, intent);\n }\n async getSentiment(locale: string, utterance: string): Promise<{ numHits: number; score: number; comparative: number; language: string; numWords: number; type: string; vote: any }> {\n const sentiment = await this.nlp.getSentiment(locale, utterance);", "score": 31.028094179312326 } ]
typescript
const sentiment = await this.analyzer.getSentiment( phrase, locale, this.settings );
/* * Copyright (c) AXA Group Operations Spain S.A. * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import { NlpManager } from '../nlp'; import MemoryConversationContext from './memory-conversation-context'; /** * Microsoft Bot Framework compatible recognizer for nlp.js. */ class Recognizer { private readonly nlpManager: NlpManager; private readonly threshold: number; private readonly conversationContext: MemoryConversationContext; /** * Constructor of the class. * @param {Object} settings Settings for the instance. */ constructor(private readonly settings: { nlpManager?: NlpManager; container?: any; nerThreshold?: number; threshold?: number; conversationContext?: MemoryConversationContext; }) { this.nlpManager = this.settings.nlpManager || new NlpManager({ container: this.settings.container, ner: { threshold: this.settings.nerThreshold || 1 }, }); this.threshold = this.settings.threshold || 0.7; this.conversationContext = this.settings.conversationContext || new MemoryConversationContext({}); } /** * Train the NLP manager. */ public async train(): Promise<void> { await this.nlpManager.train(); } /** * Loads the model from a file. * @param {String} filename Name of the file. */ public load(filename: string): void { this.nlpManager.load(filename); } /** * Saves the model into a file. * @param {String} filename Name of the file. */ public save(filename: string): void {
this.nlpManager.save(filename);
} /** * Loads the NLP manager from an excel. * @param {String} filename Name of the file. */ public async loadExcel(filename: string): Promise<void> { this.nlpManager.loadExcel(filename); await this.train(); this.save(filename); } /** * Process an utterance using the NLP manager. This is done using a given context * as the context object. * @param {Object} srcContext Source context * @param {String} locale Locale of the utterance. * @param {String} utterance Locale of the utterance. */ public async process( srcContext: Record<string, unknown>, locale?: string, utterance?: string ): Promise<string> { const context = srcContext || {}; const response = await (locale ? this.nlpManager.process(locale, utterance, context) : this.nlpManager.process(utterance, undefined, context)); if (response.score < this.threshold || response.intent === 'None') { response.answer = undefined; return response; } for (let i = 0; i < response.entities.length; i += 1) { const entity = response.entities[i]; context[entity.entity] = entity.option; } if (response.slotFill) { context.slotFill = response.slotFill; } else { delete context.slotFill; } return response; } /** * Given an utterance and the locale, returns the recognition of the utterance. * @param {String} utterance Utterance to be recognized. * @param {String} model Model of the utterance. * @param {Function} cb Callback Function. */ public async recognizeUtterance(utterance: string, model: {locale: string}, cb: Function): Promise<any> { const response = await this.process( model, model ? model.locale : undefined, utterance ); return cb(null, response); } } export default Recognizer;
src/recognizer/recognizer.ts
Leoglme-node-nlp-typescript-fbee5fd
[ { "filename": "src/nlp/nlp-manager.ts", "retrieved_chunk": " * Save the NLP manager information into a file.\n * @param {String} srcFileName Filename for saving the NLP manager.\n * @param minified\n */\n save(srcFileName?: string, minified = false): void {\n const fileName = srcFileName || 'model.nlp';\n fs.writeFileSync(fileName, this.export(minified), 'utf8');\n }\n /**\n * Load the NLP manager information from a file.", "score": 44.22454854800639 }, { "filename": "src/nlp/nlp-excel-reader.ts", "retrieved_chunk": "import { XDoc } from '@nlpjs/xtables';\nimport NlpManager from './nlp-manager';\nclass NlpExcelReader {\n private manager: NlpManager;\n private xdoc: XDoc;\n constructor(manager: NlpManager) {\n this.manager = manager;\n this.xdoc = new XDoc();\n }\n load(filename: string): void {", "score": 35.78350877379495 }, { "filename": "src/nlp/nlp-excel-reader.ts", "retrieved_chunk": " this.xdoc.read(filename);\n this.loadSettings();\n this.loadLanguages();\n this.loadNamedEntities();\n this.loadRegexEntities();\n this.loadIntents();\n this.loadResponses();\n }\n loadSettings(): void {}\n loadLanguages(): void {", "score": 33.38238271134372 }, { "filename": "src/nlp/nlp-manager.ts", "retrieved_chunk": " * @param srcFileName\n */\n load(srcFileName?: string): void {\n const fileName = srcFileName || 'model.nlp';\n const data = fs.readFileSync(fileName, 'utf8');\n this.import(data);\n }\n /**\n * Load the NLP manager information from an Excel file.\n * @param fileName", "score": 32.050710293296184 }, { "filename": "src/types/@nlpjs/xtables.d.ts", "retrieved_chunk": " export class XTable {\n static CSV: string;\n static TSV: string;\n constructor();\n load(data: string, type?: string): void;\n save(type?: string): string;\n getTable(name: string): XTable;\n getRows(): Record<string, string>[];\n addRow(row: Record<string, string>): void;\n addRows(rows: Record<string, string>[]): void;", "score": 20.074672309661963 } ]
typescript
this.nlpManager.save(filename);
import { Context, MiddlewareHandler } from 'hono' import { Instructions, ExporioMiddlewareOptions, RequestJson } from './types' import { After, Append, AppendGlobalCode, Before, Prepend, Remove, RemoveAndKeepContent, RemoveAttribute, Replace, SetAttribute, SetInnerContent, SetStyleProperty, } from './htmlRewriterClasses' export const exporioMiddleware = (options: ExporioMiddlewareOptions): MiddlewareHandler => { if (!options.url) { options.url = 'https://edge-api.exporio.cloud' } if (!options.apiKey) { throw new Error('Exporio middleware requires options for "apiKey"') } return async (c, next) => { const exporioInstructions = await fetchExporioInstructions(c, options) if (!exporioInstructions) { c.set('contentUrl', c.req.url) await next() } else { c.set('contentUrl', getContentUrl(exporioInstructions, c.req.url)) await next() applyRewriterInstruction(c, exporioInstructions) applyCookieInstruction(c.res.headers, exporioInstructions) } } } const buildRequestJson = (c: Context, apiKey: string): RequestJson => { const headersInit: HeadersInit = [] c.req.headers.forEach((value: string, key: string) => headersInit.push([key, value])) return { originalRequest: { url: c.req.url, method: c.req.method, headersInit: headersInit, }, params: { API_KEY: apiKey, }, } } const fetchExporioInstructions = async ( c: Context, options: ExporioMiddlewareOptions ): Promise<Instructions | null> => { try { const requestJson = buildRequestJson(c, options.apiKey) const exporioRequest = new Request(options.url, { method: 'POST', body: JSON.stringify(requestJson), headers: { 'Content-Type': 'application/json' }, }) const exporioResponse = await fetch(exporioRequest) return await exporioResponse.json() } catch (err) { console.error('Failed to fetch exporio instructions', err) return null } } const getContentUrl = (instructions: Instructions, defaultUrl: string): string => { const customUrlInstruction = instructions?.customUrlInstruction return customUrlInstruction?.loadCustomUrl && customUrlInstruction?.customUrl ? customUrlInstruction.customUrl : defaultUrl } const applyRewriterInstruction = (c: Context, instructions: Instructions) => { let response = new Response(c.res.body, c.res) instructions?.rewriterInstruction?.transformations?.forEach(({ selector, argument1, argument2, method }) => { switch (method) { // Default Methods case 'After': { const rewriter = new HTMLRewriter().on(selector, new After(argument1, argument2)) response = rewriter.transform(response) break } case 'Append': { const rewriter = new HTMLRewriter().on(selector, new Append(argument1, argument2)) response = rewriter.transform(response) break } case 'Before': { const rewriter = new HTMLRewriter().on(selector, new Before(argument1, argument2)) response = rewriter.transform(response) break } case 'Prepend': { const rewriter = new HTMLRewriter().on(selector, new Prepend(argument1, argument2)) response = rewriter.transform(response) break } case 'Remove': { const rewriter = new HTMLRewriter().on(selector, new Remove()) response = rewriter.transform(response) break } case 'RemoveAndKeepContent': { const rewriter = new HTMLRewriter().on(selector, new RemoveAndKeepContent()) response = rewriter.transform(response) break } case 'RemoveAttribute': { const rewriter = new HTMLRewriter().on(selector, new RemoveAttribute(argument1)) response = rewriter.transform(response) break } case 'Replace': { const rewriter = new HTMLRewriter().on(selector, new Replace(argument1, argument2)) response = rewriter.transform(response) break } case 'SetAttribute': { const rewriter = new HTMLRewriter().on(selector, new SetAttribute(argument1, argument2)) response = rewriter.transform(response) break } case 'SetInnerContent': { const rewriter = new HTMLRewriter().on(selector, new SetInnerContent(argument1, argument2)) response = rewriter.transform(response) break } // Custom Methods case 'AppendGlobalCode': { const rewriter = new HTMLRewriter().on(selector, new AppendGlobalCode(argument1, argument2)) response = rewriter.transform(response) break } case 'SetStyleProperty': { const rewriter = new HTMLRewriter().on(selector, new SetStyleProperty(argument1, argument2)) response = rewriter.transform(response) break } } }) c.res = new Response(response.body, response) } const applyCookieInstruction = (headers: Headers, instructions: Instructions) => {
instructions?.cookieInstruction?.cookies.forEach((cookie) => {
let cookieAttributes = [`${cookie.name}=${cookie.value}`] if (cookie.domain) { cookieAttributes.push(`Domain=${cookie.domain}`) } if (cookie.path) { cookieAttributes.push(`Path=${cookie.path}`) } if (cookie.expires) { cookieAttributes.push(`Expires=${cookie.expires}`) } if (cookie.maxAge) { cookieAttributes.push(`Max-Age=${cookie.maxAge}`) } if (cookie.httpOnly) { cookieAttributes.push('HttpOnly') } if (cookie.secure) { cookieAttributes.push('Secure') } if (cookie.sameSite) { cookieAttributes.push(`SameSite=${cookie.sameSite}`) } if (cookie.partitioned) { cookieAttributes.push('Partitioned') } headers.append('Set-Cookie', cookieAttributes.join('; ')) }) }
src/index.ts
exporio-edge-sdk-hono-23bcafc
[ { "filename": "src/types/instructions.ts", "retrieved_chunk": " partitioned?: boolean\n}\ntype CookieInstruction = {\n setCookie: boolean\n cookies: Cookie[]\n}\ntype Transformation = {\n method: string\n selector: string\n argument1: any", "score": 8.920192992382802 }, { "filename": "src/types/index.ts", "retrieved_chunk": "export { ExporioMiddlewareOptions, RequestJson } from './general'\nexport {\n Instructions,\n CustomUrlInstruction,\n RewriterInstruction,\n Transformation,\n CookieInstruction,\n Cookie,\n} from './instructions'", "score": 8.891060236655811 }, { "filename": "src/htmlRewriterClasses/SetStyleProperty.ts", "retrieved_chunk": " const styleProperties = currentStyleAttribute.split(';')\n styleProperties.forEach((property) => {\n if (property.includes(`${this.propertyName}:`)) {\n currentStyleAttribute = currentStyleAttribute.replace(\n property,\n `${this.propertyName}:${this.propertyValue}`\n )\n }\n })\n } else {", "score": 6.8652594350544724 }, { "filename": "src/types/instructions.ts", "retrieved_chunk": "type Instructions = {\n customUrlInstruction: CustomUrlInstruction\n rewriterInstruction: RewriterInstruction\n cookieInstruction: CookieInstruction\n}\nexport { Instructions, CustomUrlInstruction, RewriterInstruction, Transformation, CookieInstruction, Cookie }", "score": 6.62712768331548 }, { "filename": "src/htmlRewriterClasses/index.ts", "retrieved_chunk": "export { SetInnerContent } from './SetInnerContent'\nexport { SetStyleProperty } from './SetStyleProperty'", "score": 3.5498578375824135 } ]
typescript
instructions?.cookieInstruction?.cookies.forEach((cookie) => {
import { RiTranslate } from "react-icons/ri"; import { MdHighQuality } from "react-icons/md"; import { BsGlobe2 } from "react-icons/bs"; import { HiOutlineDocumentText, HiUserGroup } from "react-icons/hi"; import { BsFillBookmarkHeartFill } from "react-icons/bs"; import TextAnimation from "../animation/text"; import PopAnimation from "../animation/pop"; const Features = () => { const perks = [ { icon: ( <BsGlobe2 className="h-10 w-10" style={{ fill: "url(#gradient)" }} /> ), title: "Multilingual Meeting Support", desc: "Our app allows users who speak different languages to communicate with each other. The app translates the text and speaks it out to other participants in the language they have selected.", }, { icon: ( <RiTranslate className="h-10 w-10" style={{ fill: "url(#gradient)" }} /> ), title: "Real-time Translation", desc: "Our app provides real-time translation, so you can focus on the conversation without worrying about the language barrier. The translation is done quickly and accurately, ensuring smooth communication.", }, { icon: ( <HiOutlineDocumentText className="h-10 w-10" style={{ stroke: "url(#gradient)" }} /> ), title: "Meeting Minutes", desc: "Our app automatically generates a summary of the entire meeting or conference. This feature saves time and helps ensure that all participants are on the same page.", }, { icon: ( <HiUserGroup className="h-10 w-10" style={{ fill: "url(#gradient)" }} /> ), title: "Large Capacity", desc: "Our app can support up to 100 concurrent users. This means that even large meetings and conferences can be easily accommodated, making it ideal for businesses, schools, and other organizations.", }, { icon: ( <MdHighQuality className="h-10 w-10" style={{ fill: "url(#gradient)" }} /> ), title: "HQ video and Screen Sharing", desc: "Our app provides high-quality video and screen sharing, ensuring that everyone can see and hear each other clearly. This feature helps to ensure that the meeting is productive and engaging.", }, { icon: ( <BsFillBookmarkHeartFill className="h-10 w-10" style={{ fill: "url(#gradient)" }} /> ), title: "User friendly Interface", desc: "Our app has a user-friendly interface that is easy to navigate. This ensures that everyone can participate in the meeting or conference without any technical difficulties, making it ideal for users of all skill levels.", }, ]; return ( <section id="about" className="bg-gray-900/10 text-white transition-colors duration-500" > <svg width="0" height="0"> <linearGradient id="gradient" x1="100%" y1="100%" x2="0%" y2="0%"> <stop stopColor="#6366f1" offset="0%" /> <stop stopColor="#a855f7" offset="50%" /> <stop stopColor="#ec4899" offset="100%" /> </linearGradient> </svg> <div className="mx-auto max-w-screen-xl px-4 py-16 sm:px-6 lg:px-28"> <div> <div className="mx-auto max-w-lg text-center"> <TextAnimation text="What makes us special!" textStyle="heading text-2xl font-bold lg:text-4xl" className="flex justify-center" /> </div> </div> <div> <div className="mt-8 grid grid-cols-1 gap-8 md:grid-cols-2 lg:grid-cols-3"> {perks.map((perk, index) => ( <a key={index} className="block rounded-xl border border-primary p-8 shadow-xl transition-all duration-300 hover:scale-[1.05] hover:border-secondary hover:shadow-primary/25" >
<PopAnimation>{perk.icon}</PopAnimation> <TextAnimation textStyle="text-xl font-bold text-white" text={perk.title}
className="mt-4" /> <p className="mt-1 text-sm text-gray-200">{perk.desc}</p> </a> ))} </div> </div> </div> </section> ); }; export default Features;
src/components/features/index.tsx
swasthikshetty10-hackoverflow-0b245c9
[ { "filename": "src/components/navbar/index.tsx", "retrieved_chunk": " <CharacterAnimation\n text=\"Jab We Meet\"\n textStyle=\"text-xl font-bold text-white\"\n />\n </Link>\n <div className=\"hidden space-x-6 text-white lg:flex lg:items-center\">\n {links.map((link) => (\n <Link\n className=\"transition-colors duration-300 hover:text-gray-400\"\n key={link.path}", "score": 50.94833336314895 }, { "filename": "src/components/footer/index.tsx", "retrieved_chunk": " <ul className=\"flex flex-wrap justify-center gap-6 md:gap-8 lg:gap-12\">\n {links.map((link) => (\n <li key={link.path}>\n <Link\n className=\"text-white transition hover:text-gray-400\"\n href={link.path}\n >\n <TextAnimation text={link.label} />\n </Link>\n </li>", "score": 48.359592150139406 }, { "filename": "src/components/card/index.tsx", "retrieved_chunk": " slug: string | null;\n createdAt: Date;\n };\n}) {\n let [isOpen, setIsOpen] = useState(false)\n return (\n <div className=\"m-4 flex flex-col items-center justify-center rounded-2xl bg-white bg-opacity-5 p-4 shadow-lg backdrop-blur-lg backdrop-filter hover:bg-opacity-10\">\n <div key={room.name}>\n <TextAnimation textStyle=\"text-xl font-bold text-white\" text=\"Room\" />\n <div className=\"gradient-text\">{room.slug || room.name}</div>", "score": 43.06238846444712 }, { "filename": "src/components/tabs/index.tsx", "retrieved_chunk": " classNames(\n \"w-full rounded-lg py-2.5 text-sm font-medium leading-5 \",\n \"ring-white ring-opacity-60 ring-offset-2 ring-offset-blue-400 focus:outline-none focus:ring-2\",\n selected\n ? \"bg-secondary-300/10 shadow\"\n : \"text-blue-100 hover:bg-white/[0.12] hover:text-white\"\n )\n }\n >\n Transcription", "score": 38.93073392872695 }, { "filename": "src/components/tabs/index.tsx", "retrieved_chunk": " selected\n ? \"bg-secondary/10 shadow\"\n : \"text-blue-100 hover:bg-white/[0.12] hover:text-white\"\n )\n }\n >\n Summary\n </Tab>\n <Tab\n className={({ selected }) =>", "score": 38.47385796380913 } ]
typescript
<PopAnimation>{perk.icon}</PopAnimation> <TextAnimation textStyle="text-xl font-bold text-white" text={perk.title}
import React, { useState } from "react"; import Modal from "../modal"; import { IoDocumentTextOutline } from "react-icons/io5"; import PopAnimation from "../animation/pop"; import TextAnimation from "../animation/text"; function Card({ room, }: { room: { name: string; slug: string | null; createdAt: Date; }; }) { let [isOpen, setIsOpen] = useState(false) return ( <div className="m-4 flex flex-col items-center justify-center rounded-2xl bg-white bg-opacity-5 p-4 shadow-lg backdrop-blur-lg backdrop-filter hover:bg-opacity-10"> <div key={room.name}> <TextAnimation textStyle="text-xl font-bold text-white" text="Room" /> <div className="gradient-text">{room.slug || room.name}</div> <div className="text-sm font-bold text-gray-100 text-opacity-50"> {room.createdAt.toLocaleDateString("en-US", { year: "numeric", month: "long", day: "numeric", })}{" "} at{" "} {room.createdAt.toLocaleTimeString("en-US", { hour: "numeric", minute: "numeric", hour12: true, })} </div> <PopAnimation className="flex flex-row items-center justify-center"> <button onClick={() => setIsOpen(true)} className="mt-5 flex flex-row items-center justify-center space-x-2 rounded-lg bg-gray-100 bg-opacity-5 p-2 backdrop-blur-lg backdrop-filter hover:bg-gray-100 hover:bg-opacity-10" > <IoDocumentTextOutline className="text-2xl text-gray-100" size={15} /> <div>Details</div> </button> </PopAnimation> {isOpen && ( <
Modal roomName={room.name} setIsOpen={setIsOpen} visible={isOpen} /> )}
</div> </div> ); } export default Card;
src/components/card/index.tsx
swasthikshetty10-hackoverflow-0b245c9
[ { "filename": "src/components/modal/index.tsx", "retrieved_chunk": "};\nconst Modal: FunctionComponent<ModalProps> = ({\n setIsOpen,\n roomName,\n visible,\n}) => {\n const { data, error, isLoading } = api.rooms.getRoomSummary.useQuery({\n roomName,\n });\n console.log(data);", "score": 21.570958734913805 }, { "filename": "src/pages/profile.tsx", "retrieved_chunk": " <div className=\"mt-10 flex flex-col bg-black p-10 text-gray-100 lg:p-20\">\n <div className=\"my-5 flex items-center justify-center\">\n <h2 className=\"text-center text-2xl font-bold text-white\">\n Hello {session?.user.name}!👋🏻\n </h2>\n </div>\n <div className=\"flex flex-col items-center justify-center\">\n <TextAnimation\n textStyle=\"text-lg font-bold text-secondary\"\n text=\"Your Rooms\"", "score": 15.953285812638306 }, { "filename": "src/components/modal/index.tsx", "retrieved_chunk": " // input array\n // output array-> contents [0].utterance\n return (\n <Transition appear show={visible} as={Fragment}>\n <Dialog\n as=\"div\"\n className=\"relative z-10\"\n onClose={() => setIsOpen(false)}\n >\n <Transition.Child", "score": 15.004884766306862 }, { "filename": "src/components/modal/index.tsx", "retrieved_chunk": " ) : (\n <div className=\"text-sm text-gray-100 text-opacity-50\">\n No summary available\n </div>\n )}\n </div>\n </Dialog.Panel>\n </Transition.Child>\n </div>\n </div>", "score": 15.004300893230019 }, { "filename": "src/components/tabs/index.tsx", "retrieved_chunk": " <h2 className=\"gradient-text\">{transcription?.speaker}</h2>\n <p className=\"font-lg text-white\">\n {transcription.utterance}\n </p>\n <div className=\"text-sm font-bold text-gray-100 text-opacity-50\">\n {transcription.timestamp}\n </div>\n </div>\n );\n })}", "score": 13.932289714304034 } ]
typescript
Modal roomName={room.name} setIsOpen={setIsOpen} visible={isOpen} /> )}
import { type GetServerSidePropsContext } from "next"; import { getServerSession, type NextAuthOptions, type DefaultSession, } from "next-auth"; import GoogleProvider from "next-auth/providers/google"; 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: [ GoogleProvider({
clientId: env.GOOGLE_CLIENT_ID, clientSecret: env.GOOGLE_CLIENT_SECRET, }), ], };
/** * 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
swasthikshetty10-hackoverflow-0b245c9
[ { "filename": "src/server/db.ts", "retrieved_chunk": "import { PrismaClient } from \"@prisma/client\";\nimport { env } from \"~/env.mjs\";\nconst globalForPrisma = globalThis as unknown as { prisma: PrismaClient };\nexport const prisma =\n globalForPrisma.prisma ||\n new PrismaClient({\n log:\n env.NODE_ENV === \"development\" ? [\"query\", \"error\", \"warn\"] : [\"error\"],\n });\nif (env.NODE_ENV !== \"production\") globalForPrisma.prisma = prisma;", "score": 15.065588776912378 }, { "filename": "src/utils/pusher.ts", "retrieved_chunk": "import Pusher from \"pusher\";\nexport const pusher = new Pusher({\n appId: process.env.PUSHER_APP_ID as string,\n key: process.env.PUSHER_KEY as string,\n secret: process.env.PUSHER_SECRET as string,\n cluster: process.env.PUSHER_CLUSTER as string,\n useTLS: true,\n});", "score": 9.613925500746863 }, { "filename": "src/server/api/routers/rooms.ts", "retrieved_chunk": " at.ttl = \"5m\";\n at.addGrant(grant);\n return at.toJwt();\n};\nimport axios from \"axios\";\nconst apiKey = process.env.LIVEKIT_API_KEY;\nconst apiSecret = process.env.LIVEKIT_API_SECRET;\nconst apiHost = process.env.NEXT_PUBLIC_LIVEKIT_API_HOST as string;\nimport {\n createTRPCRouter,", "score": 8.961306020773232 }, { "filename": "src/pages/api/trpc/[trpc].ts", "retrieved_chunk": "import { createNextApiHandler } from \"@trpc/server/adapters/next\";\nimport { env } from \"~/env.mjs\";\nimport { createTRPCContext } from \"~/server/api/trpc\";\nimport { appRouter } from \"~/server/api/root\";\n// export API handler\nexport default createNextApiHandler({\n router: appRouter,\n createContext: createTRPCContext,\n onError:\n env.NODE_ENV === \"development\"", "score": 8.538635324954877 }, { "filename": "src/pages/rooms/[name].tsx", "retrieved_chunk": " >([]);\n useTranscribe({\n roomName,\n audioEnabled: userChoices.audioEnabled,\n languageCode: selectedLanguage,\n });\n useEffect(() => {\n const pusher = new Pusher(process.env.NEXT_PUBLIC_PUSHER_KEY as string, {\n cluster: process.env.NEXT_PUBLIC_PUSHER_CLUSTER as string,\n });", "score": 8.442004511749978 } ]
typescript
clientId: env.GOOGLE_CLIENT_ID, clientSecret: env.GOOGLE_CLIENT_SECRET, }), ], };
import { nullable, string, z } from "zod"; import { AccessToken, RoomServiceClient } from "livekit-server-sdk"; import type { AccessTokenOptions, VideoGrant, CreateOptions, } from "livekit-server-sdk"; import { translate } from "@vitalets/google-translate-api"; const createToken = (userInfo: AccessTokenOptions, grant: VideoGrant) => { const at = new AccessToken(apiKey, apiSecret, userInfo); at.ttl = "5m"; at.addGrant(grant); return at.toJwt(); }; import axios from "axios"; const apiKey = process.env.LIVEKIT_API_KEY; const apiSecret = process.env.LIVEKIT_API_SECRET; const apiHost = process.env.NEXT_PUBLIC_LIVEKIT_API_HOST as string; import { createTRPCRouter, publicProcedure, protectedProcedure, } from "~/server/api/trpc"; import { TokenResult } from "~/lib/type"; import { CreateRoomRequest } from "livekit-server-sdk/dist/proto/livekit_room"; const roomClient = new RoomServiceClient(apiHost, apiKey, apiSecret); const configuration = new Configuration({ apiKey: process.env.OPEN_API_SECRET, }); import { Configuration, OpenAIApi } from "openai"; const openai = new OpenAIApi(configuration); export const roomsRouter = createTRPCRouter({ joinRoom: protectedProcedure .input( z.object({ roomName: z.string(), }) ) .query(async ({ input, ctx }) => { const identity = ctx.session.user.id; const name = ctx.session.user.name; const grant: VideoGrant = { room: input.roomName, roomJoin: true, canPublish: true, canPublishData: true, canSubscribe: true, }; const { roomName } = input; const token = createToken({ identity, name: name as string }, grant); const result: TokenResult = { identity, accessToken: token, }; try { // check if user is already in room console.log("here"); const participant = await ctx.prisma.participant.findUnique({ where: { UserId_RoomName: { UserId: ctx.session.user.id, RoomName: roomName, }, }, }); if (participant === null) await ctx.prisma.participant.create({ data: { User: { connect: { id: ctx.session.user.id, }, }, Room: { connect: { name: roomName, }, }, }, }); } catch (error) { console.log(error); } return result; }), createRoom: protectedProcedure.mutation(async ({ ctx }) => { const identity = ctx.session.user.id; const name = ctx.session.user.name; const room = await ctx.prisma.room.create({ data: { Owner: { connect: { id: ctx.session.user.id, }, }, }, }); await roomClient.createRoom({ name: room.name, }); const grant: VideoGrant = { room: room.name, roomJoin: true, canPublish: true, canPublishData: true, canSubscribe: true, }; const token = createToken({ identity, name: name as string }, grant); const result = { roomName: room.name, }; return result; }), getRoomsByUser: protectedProcedure.query(async ({ ctx }) => { const rooms = await ctx.prisma.room.findMany({ where: { OR: [ { Owner: { id: ctx.session.user.id, }, }, { Participant: { some: { UserId: ctx.session.user.id, }, }, }, ], }, }); return rooms; }), getRoomSummary: protectedProcedure .input( z.object({ roomName: z.string(), }) ) .query(async ({ input, ctx }) => { // order all transcripts by createdAt in ascending order const transcripts = await ctx.prisma.transcript.findMany({ where: { Room: { name: input.roomName, }, }, include: { User: true, }, orderBy: { createdAt: "asc", }, });
const chatLog = transcripts.map((transcript) => ({
speaker: transcript.User.name, utterance: transcript.text, timestamp: transcript.createdAt.toISOString(), })); if (chatLog.length === 0) { return null; } const apiKey = process.env.ONEAI_API_KEY; console.log(chatLog); try { const config = { method: "POST", url: "https://api.oneai.com/api/v0/pipeline", headers: { "api-key": apiKey, "Content-Type": "application/json", }, data: { input: chatLog, input_type: "conversation", content_type: "application/json", output_type: "json", multilingual: { enabled: true, }, steps: [ { skill: "article-topics", }, { skill: "numbers", }, { skill: "names", }, { skill: "emotions", }, { skill: "summarize", }, ], }, }; const res = await axios.request(config); console.log(res.status); return res.data; } catch (error) { console.log(error); } }), });
src/server/api/routers/rooms.ts
swasthikshetty10-hackoverflow-0b245c9
[ { "filename": "src/hooks/useTranscribe.ts", "retrieved_chunk": " } = useSpeechRecognition();\n const pusherMutation = api.pusher.send.useMutation();\n useEffect(() => {\n if (finalTranscript !== \"\") {\n pusherMutation.mutate({\n message: transcript,\n roomName: roomName,\n isFinal: true,\n });\n resetTranscript();", "score": 8.842289671252715 }, { "filename": "src/hooks/useTranscribe.ts", "retrieved_chunk": "const useTranscribe = ({\n roomName,\n audioEnabled,\n languageCode,\n}: UseTranscribeProps) => {\n const {\n transcript,\n resetTranscript,\n finalTranscript,\n browserSupportsSpeechRecognition,", "score": 7.125082930306826 }, { "filename": "src/server/api/routers/pusher.ts", "retrieved_chunk": " },\n User: {\n connect: {\n id: user.id,\n },\n },\n },\n });\n return response;\n }),", "score": 6.102457441786328 }, { "filename": "src/components/card/index.tsx", "retrieved_chunk": " <div className=\"text-sm font-bold text-gray-100 text-opacity-50\">\n {room.createdAt.toLocaleDateString(\"en-US\", {\n year: \"numeric\",\n month: \"long\",\n day: \"numeric\",\n })}{\" \"}\n at{\" \"}\n {room.createdAt.toLocaleTimeString(\"en-US\", {\n hour: \"numeric\",\n minute: \"numeric\",", "score": 6.025154061484767 }, { "filename": "src/server/api/routers/pusher.ts", "retrieved_chunk": " const { text } = await translate(message, {\n to: \"en\",\n });\n await ctx.prisma.transcript.create({\n data: {\n text: text,\n Room: {\n connect: {\n name: input.roomName,\n },", "score": 5.723514353011765 } ]
typescript
const chatLog = transcripts.map((transcript) => ({
import React, { useState } from "react"; import Modal from "../modal"; import { IoDocumentTextOutline } from "react-icons/io5"; import PopAnimation from "../animation/pop"; import TextAnimation from "../animation/text"; function Card({ room, }: { room: { name: string; slug: string | null; createdAt: Date; }; }) { let [isOpen, setIsOpen] = useState(false) return ( <div className="m-4 flex flex-col items-center justify-center rounded-2xl bg-white bg-opacity-5 p-4 shadow-lg backdrop-blur-lg backdrop-filter hover:bg-opacity-10"> <div key={room.name}> <TextAnimation textStyle="text-xl font-bold text-white" text="Room" /> <div className="gradient-text">{room.slug || room.name}</div> <div className="text-sm font-bold text-gray-100 text-opacity-50"> {room.createdAt.toLocaleDateString("en-US", { year: "numeric", month: "long", day: "numeric", })}{" "} at{" "} {room.createdAt.toLocaleTimeString("en-US", { hour: "numeric", minute: "numeric", hour12: true, })} </div> <PopAnimation className="flex flex-row items-center justify-center"> <button onClick={() => setIsOpen(true)} className="mt-5 flex flex-row items-center justify-center space-x-2 rounded-lg bg-gray-100 bg-opacity-5 p-2 backdrop-blur-lg backdrop-filter hover:bg-gray-100 hover:bg-opacity-10" > <IoDocumentTextOutline className="text-2xl text-gray-100" size={15} /> <div>Details</div> </button> </PopAnimation> {isOpen && (
<Modal roomName={room.name} setIsOpen={setIsOpen} visible={isOpen} /> )}
</div> </div> ); } export default Card;
src/components/card/index.tsx
swasthikshetty10-hackoverflow-0b245c9
[ { "filename": "src/components/modal/index.tsx", "retrieved_chunk": "};\nconst Modal: FunctionComponent<ModalProps> = ({\n setIsOpen,\n roomName,\n visible,\n}) => {\n const { data, error, isLoading } = api.rooms.getRoomSummary.useQuery({\n roomName,\n });\n console.log(data);", "score": 21.570958734913805 }, { "filename": "src/pages/profile.tsx", "retrieved_chunk": " <div className=\"mt-10 flex flex-col bg-black p-10 text-gray-100 lg:p-20\">\n <div className=\"my-5 flex items-center justify-center\">\n <h2 className=\"text-center text-2xl font-bold text-white\">\n Hello {session?.user.name}!👋🏻\n </h2>\n </div>\n <div className=\"flex flex-col items-center justify-center\">\n <TextAnimation\n textStyle=\"text-lg font-bold text-secondary\"\n text=\"Your Rooms\"", "score": 15.953285812638306 }, { "filename": "src/components/modal/index.tsx", "retrieved_chunk": " // input array\n // output array-> contents [0].utterance\n return (\n <Transition appear show={visible} as={Fragment}>\n <Dialog\n as=\"div\"\n className=\"relative z-10\"\n onClose={() => setIsOpen(false)}\n >\n <Transition.Child", "score": 15.004884766306862 }, { "filename": "src/components/modal/index.tsx", "retrieved_chunk": " ) : (\n <div className=\"text-sm text-gray-100 text-opacity-50\">\n No summary available\n </div>\n )}\n </div>\n </Dialog.Panel>\n </Transition.Child>\n </div>\n </div>", "score": 15.004300893230019 }, { "filename": "src/components/tabs/index.tsx", "retrieved_chunk": " <h2 className=\"gradient-text\">{transcription?.speaker}</h2>\n <p className=\"font-lg text-white\">\n {transcription.utterance}\n </p>\n <div className=\"text-sm font-bold text-gray-100 text-opacity-50\">\n {transcription.timestamp}\n </div>\n </div>\n );\n })}", "score": 13.932289714304034 } ]
typescript
<Modal roomName={room.name} setIsOpen={setIsOpen} visible={isOpen} /> )}
import { RiTranslate } from "react-icons/ri"; import { MdHighQuality } from "react-icons/md"; import { BsGlobe2 } from "react-icons/bs"; import { HiOutlineDocumentText, HiUserGroup } from "react-icons/hi"; import { BsFillBookmarkHeartFill } from "react-icons/bs"; import TextAnimation from "../animation/text"; import PopAnimation from "../animation/pop"; const Features = () => { const perks = [ { icon: ( <BsGlobe2 className="h-10 w-10" style={{ fill: "url(#gradient)" }} /> ), title: "Multilingual Meeting Support", desc: "Our app allows users who speak different languages to communicate with each other. The app translates the text and speaks it out to other participants in the language they have selected.", }, { icon: ( <RiTranslate className="h-10 w-10" style={{ fill: "url(#gradient)" }} /> ), title: "Real-time Translation", desc: "Our app provides real-time translation, so you can focus on the conversation without worrying about the language barrier. The translation is done quickly and accurately, ensuring smooth communication.", }, { icon: ( <HiOutlineDocumentText className="h-10 w-10" style={{ stroke: "url(#gradient)" }} /> ), title: "Meeting Minutes", desc: "Our app automatically generates a summary of the entire meeting or conference. This feature saves time and helps ensure that all participants are on the same page.", }, { icon: ( <HiUserGroup className="h-10 w-10" style={{ fill: "url(#gradient)" }} /> ), title: "Large Capacity", desc: "Our app can support up to 100 concurrent users. This means that even large meetings and conferences can be easily accommodated, making it ideal for businesses, schools, and other organizations.", }, { icon: ( <MdHighQuality className="h-10 w-10" style={{ fill: "url(#gradient)" }} /> ), title: "HQ video and Screen Sharing", desc: "Our app provides high-quality video and screen sharing, ensuring that everyone can see and hear each other clearly. This feature helps to ensure that the meeting is productive and engaging.", }, { icon: ( <BsFillBookmarkHeartFill className="h-10 w-10" style={{ fill: "url(#gradient)" }} /> ), title: "User friendly Interface", desc: "Our app has a user-friendly interface that is easy to navigate. This ensures that everyone can participate in the meeting or conference without any technical difficulties, making it ideal for users of all skill levels.", }, ]; return ( <section id="about" className="bg-gray-900/10 text-white transition-colors duration-500" > <svg width="0" height="0"> <linearGradient id="gradient" x1="100%" y1="100%" x2="0%" y2="0%"> <stop stopColor="#6366f1" offset="0%" /> <stop stopColor="#a855f7" offset="50%" /> <stop stopColor="#ec4899" offset="100%" /> </linearGradient> </svg> <div className="mx-auto max-w-screen-xl px-4 py-16 sm:px-6 lg:px-28"> <div> <div className="mx-auto max-w-lg text-center"> <TextAnimation text="What makes us special!" textStyle="heading text-2xl font-bold lg:text-4xl" className="flex justify-center" /> </div> </div> <div> <div className="mt-8 grid grid-cols-1 gap-8 md:grid-cols-2 lg:grid-cols-3"> {perks.map((perk, index) => ( <a key={index} className="block rounded-xl border border-primary p-8 shadow-xl transition-all duration-300 hover:scale-[1.05] hover:border-secondary hover:shadow-primary/25" > <
PopAnimation>{perk.icon}</PopAnimation> <TextAnimation textStyle="text-xl font-bold text-white" text={perk.title}
className="mt-4" /> <p className="mt-1 text-sm text-gray-200">{perk.desc}</p> </a> ))} </div> </div> </div> </section> ); }; export default Features;
src/components/features/index.tsx
swasthikshetty10-hackoverflow-0b245c9
[ { "filename": "src/components/navbar/index.tsx", "retrieved_chunk": " <CharacterAnimation\n text=\"Jab We Meet\"\n textStyle=\"text-xl font-bold text-white\"\n />\n </Link>\n <div className=\"hidden space-x-6 text-white lg:flex lg:items-center\">\n {links.map((link) => (\n <Link\n className=\"transition-colors duration-300 hover:text-gray-400\"\n key={link.path}", "score": 46.10162262632238 }, { "filename": "src/components/card/index.tsx", "retrieved_chunk": " slug: string | null;\n createdAt: Date;\n };\n}) {\n let [isOpen, setIsOpen] = useState(false)\n return (\n <div className=\"m-4 flex flex-col items-center justify-center rounded-2xl bg-white bg-opacity-5 p-4 shadow-lg backdrop-blur-lg backdrop-filter hover:bg-opacity-10\">\n <div key={room.name}>\n <TextAnimation textStyle=\"text-xl font-bold text-white\" text=\"Room\" />\n <div className=\"gradient-text\">{room.slug || room.name}</div>", "score": 38.31781867849544 }, { "filename": "src/components/tabs/index.tsx", "retrieved_chunk": " selected\n ? \"bg-secondary/10 shadow\"\n : \"text-blue-100 hover:bg-white/[0.12] hover:text-white\"\n )\n }\n >\n Summary\n </Tab>\n <Tab\n className={({ selected }) =>", "score": 37.42520156505175 }, { "filename": "src/components/tabs/index.tsx", "retrieved_chunk": " classNames(\n \"w-full rounded-lg py-2.5 text-sm font-medium leading-5 \",\n \"ring-white ring-opacity-60 ring-offset-2 ring-offset-blue-400 focus:outline-none focus:ring-2\",\n selected\n ? \"bg-secondary-300/10 shadow\"\n : \"text-blue-100 hover:bg-white/[0.12] hover:text-white\"\n )\n }\n >\n Transcription", "score": 33.89577923004439 }, { "filename": "src/components/modal/index.tsx", "retrieved_chunk": " >\n <Dialog.Panel className=\"w-full max-w-md transform overflow-hidden rounded-2xl bg-white bg-opacity-10 p-6 text-left align-middle shadow-xl backdrop-blur-2xl backdrop-filter transition-all\">\n <Dialog.Title\n as=\"h3\"\n className=\"gradient-text text-lg font-medium leading-6\"\n >\n Meeting Details\n </Dialog.Title>\n <div className=\"\">\n {isLoading ? (", "score": 31.877388615098234 } ]
typescript
PopAnimation>{perk.icon}</PopAnimation> <TextAnimation textStyle="text-xl font-bold text-white" text={perk.title}
import { LiveKitRoom, PreJoin, LocalUserChoices, VideoConference, formatChatMessageLinks, } from "@livekit/components-react"; import { LogLevel, RoomOptions, VideoPresets } from "livekit-client"; import type { NextPage } from "next"; import { useRouter } from "next/router"; import { useEffect, useMemo, useState } from "react"; import { DebugMode } from "../../lib/Debug"; import { api } from "~/utils/api"; import { signIn, useSession } from "next-auth/react"; import Pusher from "pusher-js"; import useTranscribe from "~/hooks/useTranscribe"; import Captions from "~/components/captions"; import SplashScreen from "~/components/splashScreen"; import { AiFillSetting } from "react-icons/ai"; const Home: NextPage = () => { const router = useRouter(); const { name: roomName } = router.query; const { data: session, status } = useSession(); const [preJoinChoices, setPreJoinChoices] = useState< LocalUserChoices | undefined >(undefined); const [selectedCode, setSelectedCode] = useState("en"); if (status === "loading") return <SplashScreen />; if (!session) signIn("google"); const languageCodes = [ { language: "English", code: "en-US", }, { language: "Hindi", code: "hi-IN", }, { language: "Japanese", code: "ja-JP", }, { language: "French", code: "fr-FR", }, { language: "Deutsch", code: "de-DE", }, ]; return ( <main data-lk-theme="default"> {roomName && !Array.isArray(roomName) && preJoinChoices ? ( <> <ActiveRoom roomName={roomName} userChoices={preJoinChoices} onLeave={() => setPreJoinChoices(undefined)} userId={session?.user.id as string} selectedLanguage={selectedCode} ></ActiveRoom> <div className="lk-prejoin" style={{ width: "100%", }} > <label className="flex items-center justify-center gap-2"> <span className="flex items-center space-x-2 text-center text-xs lg:text-sm"> <AiFillSetting /> <a>Switch Language</a> </span> <select className="lk-button" onChange={(e) => setSelectedCode(e.target.value)} defaultValue={selectedCode} > {languageCodes.map((language) => ( <option value={language.code}>{language.language}</option> ))} </select> </label> </div> </> ) : ( <div className="flex h-screen flex-col items-center justify-center"> <div className="lk-prejoin flex flex-col gap-3"> <div className="text-2xl font-bold">Hey, {session?.user.name}!</div> <div className="text-sm font-normal"> You are joining{" "} <span className="gradient-text font-semibold">{roomName}</span> </div> <label> <span>Choose your Language</span> </label> <select className="lk-button" onChange={(e) => setSelectedCode(e.target.value)} > {languageCodes.map((language) => ( <option value={language.code}>{language.language}</option> ))} </select> </div> <PreJoin onError={(err) => console.log("Error while setting up prejoin", err) } defaults={{ username: session?.user.name as string, videoEnabled: true, audioEnabled: true, }} onSubmit={(values) => { console.log("Joining with: ", values); setPreJoinChoices(values); }} ></PreJoin> </div> )} </main> ); }; export default Home; type ActiveRoomProps = { userChoices: LocalUserChoices; roomName: string; region?: string; onLeave?: () => void; userId: string; selectedLanguage: string; }; const ActiveRoom = ({ roomName, userChoices, onLeave, userId, selectedLanguage, }: ActiveRoomProps) => { const { data, error, isLoading } = api.rooms.joinRoom.useQuery({ roomName }); const router = useRouter(); const { region, hq } = router.query; // const liveKitUrl = useServerUrl(region as string | undefined); const roomOptions = useMemo((): RoomOptions => { return { videoCaptureDefaults: { deviceId: userChoices.videoDeviceId ?? undefined, resolution: hq === "true" ? VideoPresets.h2160 : VideoPresets.h720, }, publishDefaults: { videoSimulcastLayers: hq === "true" ? [VideoPresets.h1080, VideoPresets.h720] : [VideoPresets.h540, VideoPresets.h216], }, audioCaptureDefaults: { deviceId: userChoices.audioDeviceId ?? undefined, }, adaptiveStream: { pixelDensity: "screen" }, dynacast: true, }; }, [userChoices, hq]); const [transcriptionQueue, setTranscriptionQueue] = useState< { sender: string; message: string; senderId: string; isFinal: boolean; }[] >([]); useTranscribe({ roomName, audioEnabled: userChoices.audioEnabled, languageCode: selectedLanguage, }); useEffect(() => { const pusher = new Pusher(process.env.NEXT_PUBLIC_PUSHER_KEY as string, { cluster: process.env.NEXT_PUBLIC_PUSHER_CLUSTER as string, }); const channel = pusher.subscribe(roomName); channel.bind( "transcribe-event", function (data: { sender: string; message: string; senderId: string; isFinal: boolean; }) { if (data.isFinal && userId !== data.senderId) { setTranscriptionQueue((prev) => { return [...prev, data]; }); } } ); return () => { pusher.unsubscribe(roomName); }; }, []); return ( <> {data && ( <LiveKitRoom token={data.accessToken} serverUrl={process.env.NEXT_PUBLIC_LIVEKIT_API_HOST} options={roomOptions} video={userChoices.videoEnabled} audio={userChoices.audioEnabled} onDisconnected={onLeave} >
<Captions transcriptionQueue={transcriptionQueue}
setTranscriptionQueue={setTranscriptionQueue} languageCode={selectedLanguage} /> <VideoConference chatMessageFormatter={formatChatMessageLinks} /> <DebugMode logLevel={LogLevel.info} /> </LiveKitRoom> )} </> ); };
src/pages/rooms/[name].tsx
swasthikshetty10-hackoverflow-0b245c9
[ { "filename": "src/components/captions/index.tsx", "retrieved_chunk": "};\ninterface Props {\n transcriptionQueue: Transcription[];\n setTranscriptionQueue: Dispatch<SetStateAction<Transcription[]>>;\n languageCode: string;\n}\nconst Captions: React.FC<Props> = ({\n transcriptionQueue,\n setTranscriptionQueue,\n languageCode,", "score": 17.524467584242746 }, { "filename": "src/server/api/routers/rooms.ts", "retrieved_chunk": " at.ttl = \"5m\";\n at.addGrant(grant);\n return at.toJwt();\n};\nimport axios from \"axios\";\nconst apiKey = process.env.LIVEKIT_API_KEY;\nconst apiSecret = process.env.LIVEKIT_API_SECRET;\nconst apiHost = process.env.NEXT_PUBLIC_LIVEKIT_API_HOST as string;\nimport {\n createTRPCRouter,", "score": 13.936103927491246 }, { "filename": "src/components/captions/index.tsx", "retrieved_chunk": "}) => {\n const [caption, setCaption] = useState<{ sender: string; message: string }>();\n useEffect(() => {\n async function translateText() {\n console.info(\"transcriptionQueue\", transcriptionQueue);\n if (transcriptionQueue.length > 0) {\n const res = await translate(transcriptionQueue[0]?.message as string, {\n // @ts-ignore\n to: languageCode.split(\"-\")[0],\n });", "score": 13.125054055206192 }, { "filename": "src/components/captions/index.tsx", "retrieved_chunk": " setCaption({\n message: res.text,\n sender: transcriptionQueue[0]?.sender as string,\n });\n const isEmpty = transcriptionQueue.length === 0;\n speakOut(res.text as string, isEmpty);\n setTranscriptionQueue((prev) => prev.slice(1));\n }\n }\n translateText();", "score": 11.02532901612281 }, { "filename": "src/utils/pusher.ts", "retrieved_chunk": "import Pusher from \"pusher\";\nexport const pusher = new Pusher({\n appId: process.env.PUSHER_APP_ID as string,\n key: process.env.PUSHER_KEY as string,\n secret: process.env.PUSHER_SECRET as string,\n cluster: process.env.PUSHER_CLUSTER as string,\n useTLS: true,\n});", "score": 9.883072183219925 } ]
typescript
<Captions transcriptionQueue={transcriptionQueue}
import { LiveKitRoom, PreJoin, LocalUserChoices, VideoConference, formatChatMessageLinks, } from "@livekit/components-react"; import { LogLevel, RoomOptions, VideoPresets } from "livekit-client"; import type { NextPage } from "next"; import { useRouter } from "next/router"; import { useEffect, useMemo, useState } from "react"; import { DebugMode } from "../../lib/Debug"; import { api } from "~/utils/api"; import { signIn, useSession } from "next-auth/react"; import Pusher from "pusher-js"; import useTranscribe from "~/hooks/useTranscribe"; import Captions from "~/components/captions"; import SplashScreen from "~/components/splashScreen"; import { AiFillSetting } from "react-icons/ai"; const Home: NextPage = () => { const router = useRouter(); const { name: roomName } = router.query; const { data: session, status } = useSession(); const [preJoinChoices, setPreJoinChoices] = useState< LocalUserChoices | undefined >(undefined); const [selectedCode, setSelectedCode] = useState("en"); if (status === "loading") return <SplashScreen />; if (!session) signIn("google"); const languageCodes = [ { language: "English", code: "en-US", }, { language: "Hindi", code: "hi-IN", }, { language: "Japanese", code: "ja-JP", }, { language: "French", code: "fr-FR", }, { language: "Deutsch", code: "de-DE", }, ]; return ( <main data-lk-theme="default"> {roomName && !Array.isArray(roomName) && preJoinChoices ? ( <> <ActiveRoom roomName={roomName} userChoices={preJoinChoices} onLeave={() => setPreJoinChoices(undefined)} userId={session?.user.id as string} selectedLanguage={selectedCode} ></ActiveRoom> <div className="lk-prejoin" style={{ width: "100%", }} > <label className="flex items-center justify-center gap-2"> <span className="flex items-center space-x-2 text-center text-xs lg:text-sm"> <AiFillSetting /> <a>Switch Language</a> </span> <select className="lk-button" onChange={(e) => setSelectedCode(e.target.value)} defaultValue={selectedCode} > {languageCodes.map((language) => ( <option value={language.code}>{language.language}</option> ))} </select> </label> </div> </> ) : ( <div className="flex h-screen flex-col items-center justify-center"> <div className="lk-prejoin flex flex-col gap-3"> <div className="text-2xl font-bold">Hey, {session?.user.name}!</div> <div className="text-sm font-normal"> You are joining{" "} <span className="gradient-text font-semibold">{roomName}</span> </div> <label> <span>Choose your Language</span> </label> <select className="lk-button" onChange={(e) => setSelectedCode(e.target.value)} > {languageCodes.map((language) => ( <option value={language.code}>{language.language}</option> ))} </select> </div> <PreJoin onError={(err) => console.log("Error while setting up prejoin", err) } defaults={{ username: session?.user.name as string, videoEnabled: true, audioEnabled: true, }} onSubmit={(values) => { console.log("Joining with: ", values); setPreJoinChoices(values); }} ></PreJoin> </div> )} </main> ); }; export default Home; type ActiveRoomProps = { userChoices: LocalUserChoices; roomName: string; region?: string; onLeave?: () => void; userId: string; selectedLanguage: string; }; const ActiveRoom = ({ roomName, userChoices, onLeave, userId, selectedLanguage, }: ActiveRoomProps) => { const { data, error, isLoading } =
api.rooms.joinRoom.useQuery({ roomName });
const router = useRouter(); const { region, hq } = router.query; // const liveKitUrl = useServerUrl(region as string | undefined); const roomOptions = useMemo((): RoomOptions => { return { videoCaptureDefaults: { deviceId: userChoices.videoDeviceId ?? undefined, resolution: hq === "true" ? VideoPresets.h2160 : VideoPresets.h720, }, publishDefaults: { videoSimulcastLayers: hq === "true" ? [VideoPresets.h1080, VideoPresets.h720] : [VideoPresets.h540, VideoPresets.h216], }, audioCaptureDefaults: { deviceId: userChoices.audioDeviceId ?? undefined, }, adaptiveStream: { pixelDensity: "screen" }, dynacast: true, }; }, [userChoices, hq]); const [transcriptionQueue, setTranscriptionQueue] = useState< { sender: string; message: string; senderId: string; isFinal: boolean; }[] >([]); useTranscribe({ roomName, audioEnabled: userChoices.audioEnabled, languageCode: selectedLanguage, }); useEffect(() => { const pusher = new Pusher(process.env.NEXT_PUBLIC_PUSHER_KEY as string, { cluster: process.env.NEXT_PUBLIC_PUSHER_CLUSTER as string, }); const channel = pusher.subscribe(roomName); channel.bind( "transcribe-event", function (data: { sender: string; message: string; senderId: string; isFinal: boolean; }) { if (data.isFinal && userId !== data.senderId) { setTranscriptionQueue((prev) => { return [...prev, data]; }); } } ); return () => { pusher.unsubscribe(roomName); }; }, []); return ( <> {data && ( <LiveKitRoom token={data.accessToken} serverUrl={process.env.NEXT_PUBLIC_LIVEKIT_API_HOST} options={roomOptions} video={userChoices.videoEnabled} audio={userChoices.audioEnabled} onDisconnected={onLeave} > <Captions transcriptionQueue={transcriptionQueue} setTranscriptionQueue={setTranscriptionQueue} languageCode={selectedLanguage} /> <VideoConference chatMessageFormatter={formatChatMessageLinks} /> <DebugMode logLevel={LogLevel.info} /> </LiveKitRoom> )} </> ); };
src/pages/rooms/[name].tsx
swasthikshetty10-hackoverflow-0b245c9
[ { "filename": "src/components/modal/index.tsx", "retrieved_chunk": "};\nconst Modal: FunctionComponent<ModalProps> = ({\n setIsOpen,\n roomName,\n visible,\n}) => {\n const { data, error, isLoading } = api.rooms.getRoomSummary.useQuery({\n roomName,\n });\n console.log(data);", "score": 32.27743365539583 }, { "filename": "src/pages/profile.tsx", "retrieved_chunk": " const { data: rooms, isLoading, error } = api.rooms.getRoomsByUser.useQuery();\n if (status === \"loading\") return <SplashScreen />;\n if (!session && status === \"unauthenticated\") return signIn(\"google\");\n const ownedRooms =\n rooms?.filter((room) => room.OwnerId === session?.user.id) || [];\n const joinedRooms =\n rooms?.filter((room) => room.OwnerId !== session?.user.id) || [];\n return (\n <>\n <Navbar status={status} session={session} />", "score": 19.339014627890208 }, { "filename": "src/pages/index.tsx", "retrieved_chunk": " });\n const [roomLoading, setRoomLoading] = React.useState(false);\n const createRoomHandler = async () => {\n if (status === \"unauthenticated\") signIn(\"google\");\n else {\n setRoomLoading(true);\n const data = await createRoom.mutateAsync();\n setRoomLoading(false);\n router.push(`/rooms/${data.roomName}`);\n }", "score": 13.1853539872138 }, { "filename": "src/server/api/routers/rooms.ts", "retrieved_chunk": "const openai = new OpenAIApi(configuration);\nexport const roomsRouter = createTRPCRouter({\n joinRoom: protectedProcedure\n .input(\n z.object({\n roomName: z.string(),\n })\n )\n .query(async ({ input, ctx }) => {\n const identity = ctx.session.user.id;", "score": 11.816989728863891 }, { "filename": "src/hooks/useTranscribe.ts", "retrieved_chunk": " } = useSpeechRecognition();\n const pusherMutation = api.pusher.send.useMutation();\n useEffect(() => {\n if (finalTranscript !== \"\") {\n pusherMutation.mutate({\n message: transcript,\n roomName: roomName,\n isFinal: true,\n });\n resetTranscript();", "score": 10.73676951573374 } ]
typescript
api.rooms.joinRoom.useQuery({ roomName });
import Image from "next/image"; import Link from "next/link"; import CharacterAnimation from "../animation/character"; import { BiMenuAltRight as MenuIcon } from "react-icons/bi"; import { AiOutlineClose as XIcon } from "react-icons/ai"; import { useState } from "react"; import { signIn, signOut } from "next-auth/react"; import { Session } from "next-auth"; import { FcGoogle } from "react-icons/fc"; import PopAnimation from "../animation/pop"; import Loader from "../loader"; const Navbar = ({ status, session, }: { status: "loading" | "authenticated" | "unauthenticated"; session: Session | null; }) => { const links = [ { label: "Home", path: "#", }, { label: "About", path: "#about", }, { label: "Contact", path: "#contact", }, ]; const [isMenuOpen, setIsMenuOpen] = useState(false); const toggleMenu = () => { setIsMenuOpen(!isMenuOpen); }; return ( <nav className="fixed top-0 z-10 w-full border-b border-gray-400/20 bg-white bg-opacity-5 backdrop-blur-lg backdrop-filter"> <div className="mx-auto max-w-5xl px-4"> <div className="flex h-16 items-center justify-between"> <Link href="/" className="flex items-center space-x-2"> <
PopAnimation> <Image src="/logo.png" alt="Logo" width={40}
height={40} priority /> </PopAnimation> <CharacterAnimation text="Jab We Meet" textStyle="text-xl font-bold text-white" /> </Link> <div className="hidden space-x-6 text-white lg:flex lg:items-center"> {links.map((link) => ( <Link className="transition-colors duration-300 hover:text-gray-400" key={link.path} href={link.path} > <CharacterAnimation text={link.label} textStyle="text-lg font-medium" /> </Link> ))} <PopAnimation> <button className="lk-button" onClick={() => { if (status === "authenticated") { signOut(); } else { signIn("google"); } }} > {status === "authenticated" ? ( "Sign Out" ) : ( <div className="flex items-center space-x-2"> <FcGoogle /> <div>Sign In</div> </div> )} </button> </PopAnimation> <PopAnimation> <select className="lk-button"> <option value="en">English</option> </select> </PopAnimation> <PopAnimation> <Link href="/profile"> {status === "loading" ? ( <Loader /> ) : status === "authenticated" ? ( <Image src={session?.user.image as string} width={40} height={40} className="cursor-pointer rounded-full transition duration-300 hover:grayscale" alt="profile picture" /> ) : null} </Link> </PopAnimation> </div> <div className="flex items-center space-x-4 lg:hidden"> {isMenuOpen ? ( <XIcon className="h-6 w-6 text-white" onClick={toggleMenu} /> ) : ( <MenuIcon className="h-6 w-6 text-white" onClick={toggleMenu} /> )} </div> </div> {isMenuOpen && ( <div className="flex flex-col space-y-2 p-5 text-white lg:hidden"> {links.map((link) => ( <Link key={link.path} href={link.path} className="block py-2 px-4 text-sm hover:bg-white" > {link.label} </Link> ))} <div className="flex items-center space-x-4"> <button className="lk-button" onClick={() => { if (status === "authenticated") { signIn("google"); } else { signOut(); } }} > {status === "authenticated" ? "Sign Out" : "Sign In"} </button> <select className="lk-button"> <option value="en">English</option> </select> </div> <PopAnimation> <Link href="/profile"> {status === "loading" ? ( <Loader /> ) : status === "authenticated" ? ( <Image src={session?.user.image as string} width={40} height={40} className="cursor-pointer rounded-full transition duration-300 hover:grayscale" alt="profile picture" /> ) : null} </Link> </PopAnimation> </div> )} </div> </nav> ); }; export default Navbar;
src/components/navbar/index.tsx
swasthikshetty10-hackoverflow-0b245c9
[ { "filename": "src/components/footer/index.tsx", "retrieved_chunk": " <footer id=\"contact\" className=\"bg-gray-900\">\n <div className=\"mx-auto max-w-5xl px-4 py-16 sm:px-6 lg:px-8\">\n <PopAnimation className=\"flex justify-center text-primary\">\n <Image\n src=\"/logo.png\"\n alt=\"Logo\"\n width={100}\n height={100}\n className=\"h-12 w-auto\"\n />", "score": 81.82292184634977 }, { "filename": "src/components/card/index.tsx", "retrieved_chunk": " hour12: true,\n })}\n </div>\n <PopAnimation className=\"flex flex-row items-center justify-center\">\n <button\n onClick={() => setIsOpen(true)}\n className=\"mt-5 flex flex-row items-center justify-center space-x-2 rounded-lg bg-gray-100 bg-opacity-5 p-2 backdrop-blur-lg backdrop-filter hover:bg-gray-100 hover:bg-opacity-10\"\n >\n <IoDocumentTextOutline\n className=\"text-2xl text-gray-100\"", "score": 70.51731645627657 }, { "filename": "src/components/splashScreen/index.tsx", "retrieved_chunk": "import Image from \"next/image\";\nimport Loader from \"../loader\";\nconst SplashScreen = () => {\n return (\n <div className=\"flex h-screen w-screen flex-col items-center justify-center space-y-5\">\n <Image\n src=\"/logo.png\"\n alt=\"Logo\"\n width={100}\n height={100}", "score": 60.81726891163345 }, { "filename": "src/components/card/index.tsx", "retrieved_chunk": " slug: string | null;\n createdAt: Date;\n };\n}) {\n let [isOpen, setIsOpen] = useState(false)\n return (\n <div className=\"m-4 flex flex-col items-center justify-center rounded-2xl bg-white bg-opacity-5 p-4 shadow-lg backdrop-blur-lg backdrop-filter hover:bg-opacity-10\">\n <div key={room.name}>\n <TextAnimation textStyle=\"text-xl font-bold text-white\" text=\"Room\" />\n <div className=\"gradient-text\">{room.slug || room.name}</div>", "score": 53.71842516551209 }, { "filename": "src/pages/index.tsx", "retrieved_chunk": " };\n if (status === \"loading\") return <SplashScreen />;\n return (\n <>\n <Navbar status={status} session={session} />\n <div className=\"isolate overflow-x-hidden\">\n <div className=\"flex h-screen w-screen flex-col items-center justify-center space-y-4 p-5 text-center md:flex-row\">\n <div className=\"absolute inset-x-0 top-[-10rem] -z-10 transform-gpu overflow-hidden opacity-80 blur-3xl sm:top-[-20rem]\">\n <svg\n className=\"relative left-[calc(50%-11rem)] -z-10 h-[21.1875rem] max-w-none -translate-x-1/2 rotate-[30deg] sm:left-[calc(50%-30rem)] sm:h-[42.375rem]\"", "score": 49.49758107814586 } ]
typescript
PopAnimation> <Image src="/logo.png" alt="Logo" width={40}
// @refresh reset import type { NextPage } from "next"; import { signIn, useSession } from "next-auth/react"; import { useRouter } from "next/router"; import React from "react"; import Typing from "~/components/animation/typing"; import Navbar from "~/components/navbar"; import { api } from "~/utils/api"; import { AiOutlineVideoCameraAdd } from "react-icons/ai"; import JoinRoom from "~/components/join"; import Image from "next/image"; import Features from "~/components/features"; import CharacterAnimation from "~/components/animation/character"; import { useRive, Layout, Fit, Alignment } from "@rive-app/react-canvas"; import TextAnimation from "~/components/animation/text"; import Loader from "~/components/loader"; import Footer from "~/components/footer"; import SplashScreen from "~/components/splashScreen"; function ConnectionTab() { const { data: session, status } = useSession(); const createRoom = api.rooms.createRoom.useMutation(); const router = useRouter(); const { RiveComponent: Hero } = useRive({ src: `hero.riv`, stateMachines: ["State Machine 1"], autoplay: true, layout: new Layout({ fit: Fit.FitWidth, alignment: Alignment.Center, }), }); const [roomLoading, setRoomLoading] = React.useState(false); const createRoomHandler = async () => { if (status === "unauthenticated") signIn("google"); else { setRoomLoading(true); const data = await createRoom.mutateAsync(); setRoomLoading(false); router.push(`/rooms/${data.roomName}`); } }; if (status === "loading") return <SplashScreen />; return ( <> <Navbar status={status} session={session} /> <div className="isolate overflow-x-hidden"> <div className="flex h-screen w-screen flex-col items-center justify-center space-y-4 p-5 text-center md:flex-row"> <div className="absolute inset-x-0 top-[-10rem] -z-10 transform-gpu overflow-hidden opacity-80 blur-3xl sm:top-[-20rem]"> <svg className="relative left-[calc(50%-11rem)] -z-10 h-[21.1875rem] max-w-none -translate-x-1/2 rotate-[30deg] sm:left-[calc(50%-30rem)] sm:h-[42.375rem]" viewBox="0 0 1155 678" fill="none" xmlns="http://www.w3.org/2000/svg" > <path fill="url(#45de2b6b-92d5-4d68-a6a0-9b9b2abad533)" fillOpacity=".3" d="M317.219 518.975L203.852 678 0 438.341l317.219 80.634 204.172-286.402c1.307 132.337 45.083 346.658 209.733 145.248C936.936 126.058 882.053-94.234 1031.02 41.331c119.18 108.451 130.68 295.337 121.53 375.223L855 299l21.173 362.054-558.954-142.079z" /> <defs> <linearGradient id="45de2b6b-92d5-4d68-a6a0-9b9b2abad533" x1="1155.49" x2="-78.208" y1=".177" y2="474.645" gradientUnits="userSpaceOnUse" > <stop stopColor="#9089FC" /> <stop offset={1} stopColor="#FF80B5" /> </linearGradient> </defs> </svg> </div> <div className="w-full max-w-md space-y-4"> <Typing /> <TextAnimation className="flex justify-center" textStyle="text-sm text-gray-400" text="Multilingual Video Conferencing App" /> <div className="flex flex-col items-center justify-center space-y-4 lg:flex-row lg:space-y-0 lg:space-x-4"> <button onClick={createRoomHandler} className="lk-button h-fit"> {roomLoading ? ( <Loader /> ) : ( <> <AiOutlineVideoCameraAdd /> <CharacterAnimation text="Create Room" textStyle="text-sm" /> </> )} </button> {!
roomLoading && <JoinRoom />}
</div> </div> <div className="flex w-full max-w-md items-center justify-center"> <Hero className="h-[40vh] w-full md:h-screen" /> </div> </div> <Features /> <Footer /> <div className="absolute inset-x-0 top-[calc(100%-13rem)] -z-10 transform-gpu overflow-hidden opacity-80 blur-3xl sm:top-[calc(100%-30rem)]"> <svg className="relative left-[calc(50%+3rem)] h-[21.1875rem] max-w-none -translate-x-1/2 sm:left-[calc(50%+36rem)] sm:h-[42.375rem]" viewBox="0 0 1155 678" fill="none" xmlns="http://www.w3.org/2000/svg" > <path fill="url(#ecb5b0c9-546c-4772-8c71-4d3f06d544bc)" fillOpacity=".3" d="M317.219 518.975L203.852 678 0 438.341l317.219 80.634 204.172-286.402c1.307 132.337 45.083 346.658 209.733 145.248C936.936 126.058 882.053-94.234 1031.02 41.331c119.18 108.451 130.68 295.337 121.53 375.223L855 299l21.173 362.054-558.954-142.079z" /> <defs> <linearGradient id="ecb5b0c9-546c-4772-8c71-4d3f06d544bc" x1="1155.49" x2="-78.208" y1=".177" y2="474.645" gradientUnits="userSpaceOnUse" > <stop stopColor="#9089FC" /> <stop offset={1} stopColor="#FF80B5" /> </linearGradient> </defs> </svg> </div> </div> </> ); } const Home: NextPage = () => { return ( <> <main data-lk-theme="default"> <ConnectionTab /> </main> </> ); }; export default Home;
src/pages/index.tsx
swasthikshetty10-hackoverflow-0b245c9
[ { "filename": "src/components/join/index.tsx", "retrieved_chunk": " />\n </label>\n <button\n disabled={!roomName}\n className={`lk-button ${\n !roomName && \"pointer-events-none cursor-not-allowed\"\n }`}\n onClick={() => router.push(`/rooms/${roomName}`)}\n >\n <CharacterAnimation text=\"Join\" textStyle=\"text-sm\"/>", "score": 16.43130775617538 }, { "filename": "src/components/navbar/index.tsx", "retrieved_chunk": " href={link.path}\n >\n <CharacterAnimation\n text={link.label}\n textStyle=\"text-lg font-medium\"\n />\n </Link>\n ))}\n <PopAnimation>\n <button", "score": 14.862329474180921 }, { "filename": "src/components/join/index.tsx", "retrieved_chunk": " </button>\n </div>\n );\n};\nexport default JoinRoom;", "score": 11.22631208441641 }, { "filename": "src/components/animation/character.tsx", "retrieved_chunk": "import React, { FC, useRef } from 'react';\nimport { motion, useInView } from 'framer-motion';\nconst CharacterAnimation: FC<{\n text: string;\n className?: string;\n textStyle?: string;\n}> = ({ text, className, textStyle }) => {\n const ref = useRef<HTMLDivElement>(null);\n const isInView = useInView(ref, { once: true });\n const letters = Array.from(text);", "score": 9.639230236059115 }, { "filename": "src/components/features/index.tsx", "retrieved_chunk": " <PopAnimation>{perk.icon}</PopAnimation>\n <TextAnimation\n textStyle=\"text-xl font-bold text-white\"\n text={perk.title}\n className=\"mt-4\"\n />\n <p className=\"mt-1 text-sm text-gray-200\">{perk.desc}</p>\n </a>\n ))}\n </div>", "score": 9.346427144407443 } ]
typescript
roomLoading && <JoinRoom />}
import { nullable, string, z } from "zod"; import { AccessToken, RoomServiceClient } from "livekit-server-sdk"; import type { AccessTokenOptions, VideoGrant, CreateOptions, } from "livekit-server-sdk"; import { translate } from "@vitalets/google-translate-api"; const createToken = (userInfo: AccessTokenOptions, grant: VideoGrant) => { const at = new AccessToken(apiKey, apiSecret, userInfo); at.ttl = "5m"; at.addGrant(grant); return at.toJwt(); }; import axios from "axios"; const apiKey = process.env.LIVEKIT_API_KEY; const apiSecret = process.env.LIVEKIT_API_SECRET; const apiHost = process.env.NEXT_PUBLIC_LIVEKIT_API_HOST as string; import { createTRPCRouter, publicProcedure, protectedProcedure, } from "~/server/api/trpc"; import { TokenResult } from "~/lib/type"; import { CreateRoomRequest } from "livekit-server-sdk/dist/proto/livekit_room"; const roomClient = new RoomServiceClient(apiHost, apiKey, apiSecret); const configuration = new Configuration({ apiKey: process.env.OPEN_API_SECRET, }); import { Configuration, OpenAIApi } from "openai"; const openai = new OpenAIApi(configuration); export const roomsRouter = createTRPCRouter({ joinRoom: protectedProcedure .input( z.object({ roomName: z.string(), }) ) .query(async ({ input, ctx }) => { const identity = ctx.session.user.id; const name = ctx.session.user.name; const grant: VideoGrant = { room: input.roomName, roomJoin: true, canPublish: true, canPublishData: true, canSubscribe: true, }; const { roomName } = input; const token = createToken({ identity, name: name as string }, grant);
const result: TokenResult = {
identity, accessToken: token, }; try { // check if user is already in room console.log("here"); const participant = await ctx.prisma.participant.findUnique({ where: { UserId_RoomName: { UserId: ctx.session.user.id, RoomName: roomName, }, }, }); if (participant === null) await ctx.prisma.participant.create({ data: { User: { connect: { id: ctx.session.user.id, }, }, Room: { connect: { name: roomName, }, }, }, }); } catch (error) { console.log(error); } return result; }), createRoom: protectedProcedure.mutation(async ({ ctx }) => { const identity = ctx.session.user.id; const name = ctx.session.user.name; const room = await ctx.prisma.room.create({ data: { Owner: { connect: { id: ctx.session.user.id, }, }, }, }); await roomClient.createRoom({ name: room.name, }); const grant: VideoGrant = { room: room.name, roomJoin: true, canPublish: true, canPublishData: true, canSubscribe: true, }; const token = createToken({ identity, name: name as string }, grant); const result = { roomName: room.name, }; return result; }), getRoomsByUser: protectedProcedure.query(async ({ ctx }) => { const rooms = await ctx.prisma.room.findMany({ where: { OR: [ { Owner: { id: ctx.session.user.id, }, }, { Participant: { some: { UserId: ctx.session.user.id, }, }, }, ], }, }); return rooms; }), getRoomSummary: protectedProcedure .input( z.object({ roomName: z.string(), }) ) .query(async ({ input, ctx }) => { // order all transcripts by createdAt in ascending order const transcripts = await ctx.prisma.transcript.findMany({ where: { Room: { name: input.roomName, }, }, include: { User: true, }, orderBy: { createdAt: "asc", }, }); const chatLog = transcripts.map((transcript) => ({ speaker: transcript.User.name, utterance: transcript.text, timestamp: transcript.createdAt.toISOString(), })); if (chatLog.length === 0) { return null; } const apiKey = process.env.ONEAI_API_KEY; console.log(chatLog); try { const config = { method: "POST", url: "https://api.oneai.com/api/v0/pipeline", headers: { "api-key": apiKey, "Content-Type": "application/json", }, data: { input: chatLog, input_type: "conversation", content_type: "application/json", output_type: "json", multilingual: { enabled: true, }, steps: [ { skill: "article-topics", }, { skill: "numbers", }, { skill: "names", }, { skill: "emotions", }, { skill: "summarize", }, ], }, }; const res = await axios.request(config); console.log(res.status); return res.data; } catch (error) { console.log(error); } }), });
src/server/api/routers/rooms.ts
swasthikshetty10-hackoverflow-0b245c9
[ { "filename": "src/pages/rooms/[name].tsx", "retrieved_chunk": " username: session?.user.name as string,\n videoEnabled: true,\n audioEnabled: true,\n }}\n onSubmit={(values) => {\n console.log(\"Joining with: \", values);\n setPreJoinChoices(values);\n }}\n ></PreJoin>\n </div>", "score": 26.724349387831328 }, { "filename": "src/server/api/routers/pusher.ts", "retrieved_chunk": " const response = await pusher.trigger(\n input.roomName,\n \"transcribe-event\",\n {\n message,\n sender: user.name,\n isFinal: input.isFinal,\n senderId: user.id,\n }\n );", "score": 25.886620792758265 }, { "filename": "src/server/api/routers/pusher.ts", "retrieved_chunk": " .input(\n z.object({\n message: string(),\n roomName: string(),\n isFinal: z.boolean(),\n })\n )\n .mutation(async ({ input, ctx }) => {\n const { message } = input;\n const { user } = ctx.session;", "score": 24.025364401674494 }, { "filename": "src/server/api/routers/pusher.ts", "retrieved_chunk": " const { text } = await translate(message, {\n to: \"en\",\n });\n await ctx.prisma.transcript.create({\n data: {\n text: text,\n Room: {\n connect: {\n name: input.roomName,\n },", "score": 22.783744930524648 }, { "filename": "src/hooks/useTranscribe.ts", "retrieved_chunk": " } = useSpeechRecognition();\n const pusherMutation = api.pusher.send.useMutation();\n useEffect(() => {\n if (finalTranscript !== \"\") {\n pusherMutation.mutate({\n message: transcript,\n roomName: roomName,\n isFinal: true,\n });\n resetTranscript();", "score": 22.567922420812653 } ]
typescript
const result: TokenResult = {
import Image from "next/image"; import Link from "next/link"; import CharacterAnimation from "../animation/character"; import { BiMenuAltRight as MenuIcon } from "react-icons/bi"; import { AiOutlineClose as XIcon } from "react-icons/ai"; import { useState } from "react"; import { signIn, signOut } from "next-auth/react"; import { Session } from "next-auth"; import { FcGoogle } from "react-icons/fc"; import PopAnimation from "../animation/pop"; import Loader from "../loader"; const Navbar = ({ status, session, }: { status: "loading" | "authenticated" | "unauthenticated"; session: Session | null; }) => { const links = [ { label: "Home", path: "#", }, { label: "About", path: "#about", }, { label: "Contact", path: "#contact", }, ]; const [isMenuOpen, setIsMenuOpen] = useState(false); const toggleMenu = () => { setIsMenuOpen(!isMenuOpen); }; return ( <nav className="fixed top-0 z-10 w-full border-b border-gray-400/20 bg-white bg-opacity-5 backdrop-blur-lg backdrop-filter"> <div className="mx-auto max-w-5xl px-4"> <div className="flex h-16 items-center justify-between"> <Link href="/" className="flex items-center space-x-2"> <PopAnimation> <Image src="/logo.png" alt="Logo" width={40} height={40} priority /> </PopAnimation> <CharacterAnimation text="Jab We Meet" textStyle="text-xl font-bold text-white" /> </Link> <div className="hidden space-x-6 text-white lg:flex lg:items-center"> {links.map((link) => ( <Link className="transition-colors duration-300 hover:text-gray-400" key={link.path} href={link.path} > <CharacterAnimation text={link.label} textStyle="text-lg font-medium" /> </Link> ))} <PopAnimation> <button className="lk-button" onClick={() => { if (status === "authenticated") { signOut(); } else { signIn("google"); } }} > {status === "authenticated" ? ( "Sign Out" ) : ( <div className="flex items-center space-x-2"> <FcGoogle /> <div>Sign In</div> </div> )} </button> </PopAnimation> <PopAnimation> <select className="lk-button"> <option value="en">English</option> </select> </PopAnimation> <PopAnimation> <Link href="/profile"> {status === "loading" ? (
<Loader /> ) : status === "authenticated" ? ( <Image src={session?.user.image as string}
width={40} height={40} className="cursor-pointer rounded-full transition duration-300 hover:grayscale" alt="profile picture" /> ) : null} </Link> </PopAnimation> </div> <div className="flex items-center space-x-4 lg:hidden"> {isMenuOpen ? ( <XIcon className="h-6 w-6 text-white" onClick={toggleMenu} /> ) : ( <MenuIcon className="h-6 w-6 text-white" onClick={toggleMenu} /> )} </div> </div> {isMenuOpen && ( <div className="flex flex-col space-y-2 p-5 text-white lg:hidden"> {links.map((link) => ( <Link key={link.path} href={link.path} className="block py-2 px-4 text-sm hover:bg-white" > {link.label} </Link> ))} <div className="flex items-center space-x-4"> <button className="lk-button" onClick={() => { if (status === "authenticated") { signIn("google"); } else { signOut(); } }} > {status === "authenticated" ? "Sign Out" : "Sign In"} </button> <select className="lk-button"> <option value="en">English</option> </select> </div> <PopAnimation> <Link href="/profile"> {status === "loading" ? ( <Loader /> ) : status === "authenticated" ? ( <Image src={session?.user.image as string} width={40} height={40} className="cursor-pointer rounded-full transition duration-300 hover:grayscale" alt="profile picture" /> ) : null} </Link> </PopAnimation> </div> )} </div> </nav> ); }; export default Navbar;
src/components/navbar/index.tsx
swasthikshetty10-hackoverflow-0b245c9
[ { "filename": "src/pages/rooms/[name].tsx", "retrieved_chunk": " <AiFillSetting />\n <a>Switch Language</a>\n </span>\n <select\n className=\"lk-button\"\n onChange={(e) => setSelectedCode(e.target.value)}\n defaultValue={selectedCode}\n >\n {languageCodes.map((language) => (\n <option value={language.code}>{language.language}</option>", "score": 22.027822225531146 }, { "filename": "src/pages/rooms/[name].tsx", "retrieved_chunk": " {languageCodes.map((language) => (\n <option value={language.code}>{language.language}</option>\n ))}\n </select>\n </div>\n <PreJoin\n onError={(err) =>\n console.log(\"Error while setting up prejoin\", err)\n }\n defaults={{", "score": 21.511062042668943 }, { "filename": "src/pages/profile.tsx", "retrieved_chunk": " const { data: rooms, isLoading, error } = api.rooms.getRoomsByUser.useQuery();\n if (status === \"loading\") return <SplashScreen />;\n if (!session && status === \"unauthenticated\") return signIn(\"google\");\n const ownedRooms =\n rooms?.filter((room) => room.OwnerId === session?.user.id) || [];\n const joinedRooms =\n rooms?.filter((room) => room.OwnerId !== session?.user.id) || [];\n return (\n <>\n <Navbar status={status} session={session} />", "score": 19.001890038955082 }, { "filename": "src/components/footer/index.tsx", "retrieved_chunk": "import Image from \"next/image\";\nimport Link from \"next/link\";\nimport PopAnimation from \"../animation/pop\";\nimport TextAnimation from \"../animation/text\";\nconst Footer = () => {\n const links = [\n {\n label: \"Home\",\n path: \"#\",\n },", "score": 18.678048721030795 }, { "filename": "src/pages/rooms/[name].tsx", "retrieved_chunk": " const router = useRouter();\n const { name: roomName } = router.query;\n const { data: session, status } = useSession();\n const [preJoinChoices, setPreJoinChoices] = useState<\n LocalUserChoices | undefined\n >(undefined);\n const [selectedCode, setSelectedCode] = useState(\"en\");\n if (status === \"loading\") return <SplashScreen />;\n if (!session) signIn(\"google\");\n const languageCodes = [", "score": 17.683738030677134 } ]
typescript
<Loader /> ) : status === "authenticated" ? ( <Image src={session?.user.image as string}
import { LiveKitRoom, PreJoin, LocalUserChoices, VideoConference, formatChatMessageLinks, } from "@livekit/components-react"; import { LogLevel, RoomOptions, VideoPresets } from "livekit-client"; import type { NextPage } from "next"; import { useRouter } from "next/router"; import { useEffect, useMemo, useState } from "react"; import { DebugMode } from "../../lib/Debug"; import { api } from "~/utils/api"; import { signIn, useSession } from "next-auth/react"; import Pusher from "pusher-js"; import useTranscribe from "~/hooks/useTranscribe"; import Captions from "~/components/captions"; import SplashScreen from "~/components/splashScreen"; import { AiFillSetting } from "react-icons/ai"; const Home: NextPage = () => { const router = useRouter(); const { name: roomName } = router.query; const { data: session, status } = useSession(); const [preJoinChoices, setPreJoinChoices] = useState< LocalUserChoices | undefined >(undefined); const [selectedCode, setSelectedCode] = useState("en"); if (status === "loading") return <SplashScreen />; if (!session) signIn("google"); const languageCodes = [ { language: "English", code: "en-US", }, { language: "Hindi", code: "hi-IN", }, { language: "Japanese", code: "ja-JP", }, { language: "French", code: "fr-FR", }, { language: "Deutsch", code: "de-DE", }, ]; return ( <main data-lk-theme="default"> {roomName && !Array.isArray(roomName) && preJoinChoices ? ( <> <ActiveRoom roomName={roomName} userChoices={preJoinChoices} onLeave={() => setPreJoinChoices(undefined)} userId={session?.user.id as string} selectedLanguage={selectedCode} ></ActiveRoom> <div className="lk-prejoin" style={{ width: "100%", }} > <label className="flex items-center justify-center gap-2"> <span className="flex items-center space-x-2 text-center text-xs lg:text-sm"> <AiFillSetting /> <a>Switch Language</a> </span> <select className="lk-button" onChange={(e) => setSelectedCode(e.target.value)} defaultValue={selectedCode} > {languageCodes.map((language) => ( <option value={language.code}>{language.language}</option> ))} </select> </label> </div> </> ) : ( <div className="flex h-screen flex-col items-center justify-center"> <div className="lk-prejoin flex flex-col gap-3"> <div className="text-2xl font-bold">Hey, {session?.user.name}!</div> <div className="text-sm font-normal"> You are joining{" "} <span className="gradient-text font-semibold">{roomName}</span> </div> <label> <span>Choose your Language</span> </label> <select className="lk-button" onChange={(e) => setSelectedCode(e.target.value)} > {languageCodes.map((language) => ( <option value={language.code}>{language.language}</option> ))} </select> </div> <PreJoin onError={(err) => console.log("Error while setting up prejoin", err) } defaults={{ username: session?.user.name as string, videoEnabled: true, audioEnabled: true, }} onSubmit={(values) => { console.log("Joining with: ", values); setPreJoinChoices(values); }} ></PreJoin> </div> )} </main> ); }; export default Home; type ActiveRoomProps = { userChoices: LocalUserChoices; roomName: string; region?: string; onLeave?: () => void; userId: string; selectedLanguage: string; }; const ActiveRoom = ({ roomName, userChoices, onLeave, userId, selectedLanguage, }: ActiveRoomProps) => { const { data, error, isLoading } = api.rooms.joinRoom.useQuery({ roomName }); const router = useRouter(); const { region, hq } = router.query; // const liveKitUrl = useServerUrl(region as string | undefined); const roomOptions = useMemo((): RoomOptions => { return { videoCaptureDefaults: { deviceId: userChoices.videoDeviceId ?? undefined, resolution: hq === "true" ? VideoPresets.h2160 : VideoPresets.h720, }, publishDefaults: { videoSimulcastLayers: hq === "true" ? [VideoPresets.h1080, VideoPresets.h720] : [VideoPresets.h540, VideoPresets.h216], }, audioCaptureDefaults: { deviceId: userChoices.audioDeviceId ?? undefined, }, adaptiveStream: { pixelDensity: "screen" }, dynacast: true, }; }, [userChoices, hq]); const [transcriptionQueue, setTranscriptionQueue] = useState< { sender: string; message: string; senderId: string; isFinal: boolean; }[] >([]); useTranscribe({ roomName, audioEnabled: userChoices.audioEnabled, languageCode: selectedLanguage, }); useEffect(() => { const pusher = new Pusher(process.env.NEXT_PUBLIC_PUSHER_KEY as string, { cluster: process.env.NEXT_PUBLIC_PUSHER_CLUSTER as string, }); const channel = pusher.subscribe(roomName); channel.bind( "transcribe-event", function (data: { sender: string; message: string; senderId: string; isFinal: boolean; }) { if (data.isFinal && userId !== data.senderId) { setTranscriptionQueue((prev) => { return [...prev, data]; }); } } ); return () => { pusher.unsubscribe(roomName); }; }, []); return ( <> {data && ( <LiveKitRoom token={data.accessToken} serverUrl={process.env.NEXT_PUBLIC_LIVEKIT_API_HOST} options={roomOptions} video={userChoices.videoEnabled} audio={userChoices.audioEnabled} onDisconnected={onLeave} > <Captions transcriptionQueue={transcriptionQueue} setTranscriptionQueue={setTranscriptionQueue} languageCode={selectedLanguage} /> <VideoConference chatMessageFormatter={formatChatMessageLinks} />
<DebugMode logLevel={LogLevel.info} /> </LiveKitRoom> )}
</> ); };
src/pages/rooms/[name].tsx
swasthikshetty10-hackoverflow-0b245c9
[ { "filename": "src/components/captions/index.tsx", "retrieved_chunk": "};\ninterface Props {\n transcriptionQueue: Transcription[];\n setTranscriptionQueue: Dispatch<SetStateAction<Transcription[]>>;\n languageCode: string;\n}\nconst Captions: React.FC<Props> = ({\n transcriptionQueue,\n setTranscriptionQueue,\n languageCode,", "score": 37.50682476792408 }, { "filename": "src/components/captions/index.tsx", "retrieved_chunk": "}) => {\n const [caption, setCaption] = useState<{ sender: string; message: string }>();\n useEffect(() => {\n async function translateText() {\n console.info(\"transcriptionQueue\", transcriptionQueue);\n if (transcriptionQueue.length > 0) {\n const res = await translate(transcriptionQueue[0]?.message as string, {\n // @ts-ignore\n to: languageCode.split(\"-\")[0],\n });", "score": 20.93501726634264 }, { "filename": "src/components/captions/index.tsx", "retrieved_chunk": " setCaption({\n message: res.text,\n sender: transcriptionQueue[0]?.sender as string,\n });\n const isEmpty = transcriptionQueue.length === 0;\n speakOut(res.text as string, isEmpty);\n setTranscriptionQueue((prev) => prev.slice(1));\n }\n }\n translateText();", "score": 20.114502830501984 }, { "filename": "src/lib/Debug.tsx", "retrieved_chunk": " // @ts-expect-error\n window.__lk_room = undefined;\n };\n });\n};\nexport const DebugMode = ({ logLevel }: { logLevel?: LogLevel }) => {\n useDebugMode({ logLevel });\n return <></>;\n};", "score": 20.0988583851734 }, { "filename": "src/lib/Debug.tsx", "retrieved_chunk": "import * as React from 'react';\nimport { useRoomContext } from '@livekit/components-react';\nimport { setLogLevel, LogLevel } from 'livekit-client';\nexport const useDebugMode = ({ logLevel }: { logLevel?: LogLevel }) => {\n setLogLevel(logLevel ?? 'debug');\n const room = useRoomContext();\n React.useEffect(() => {\n // @ts-expect-error\n window.__lk_room = room;\n return () => {", "score": 12.481249770686077 } ]
typescript
<DebugMode logLevel={LogLevel.info} /> </LiveKitRoom> )}
import { Dispatch, SetStateAction, type FunctionComponent } from "react"; import { api } from "~/utils/api"; import { Dialog, Transition } from "@headlessui/react"; import { Fragment, useState } from "react"; import Loader from "../loader"; import Tabs from "../tabs"; type ModalProps = { setIsOpen: Dispatch<SetStateAction<boolean>>; roomName: string; visible: boolean; }; const Modal: FunctionComponent<ModalProps> = ({ setIsOpen, roomName, visible, }) => { const { data, error, isLoading } = api.rooms.getRoomSummary.useQuery({ roomName, }); console.log(data); // input array // output array-> contents [0].utterance return ( <Transition appear show={visible} as={Fragment}> <Dialog as="div" className="relative z-10" onClose={() => setIsOpen(false)} > <Transition.Child as={Fragment} enter="ease-out duration-300" enterFrom="opacity-0" enterTo="opacity-100" leave="ease-in duration-200" leaveFrom="opacity-100" leaveTo="opacity-0" > <div className="fixed inset-0 bg-black bg-opacity-25" /> </Transition.Child> <div className="fixed inset-0 overflow-y-auto"> <div className="flex min-h-full items-center justify-center p-4 text-center"> <Transition.Child as={Fragment} enter="ease-out duration-300" enterFrom="opacity-0 scale-95" enterTo="opacity-100 scale-100" leave="ease-in duration-200" leaveFrom="opacity-100 scale-100" leaveTo="opacity-0 scale-95" > <Dialog.Panel className="w-full max-w-md transform overflow-hidden rounded-2xl bg-white bg-opacity-10 p-6 text-left align-middle shadow-xl backdrop-blur-2xl backdrop-filter transition-all"> <Dialog.Title as="h3" className="gradient-text text-lg font-medium leading-6" > Meeting Details </Dialog.Title> <div className=""> {isLoading ? ( <Loader /> ) : data ? ( <div className="text-sm text-gray-100 text-opacity-50"> {data.output[0].contents.length > 1 && (
<Tabs summary={data.output[0].contents[1]?.utterance}
transcriptions={data.input} /> )} </div> ) : ( <div className="text-sm text-gray-100 text-opacity-50"> No summary available </div> )} </div> </Dialog.Panel> </Transition.Child> </div> </div> </Dialog> </Transition> ); }; export default Modal;
src/components/modal/index.tsx
swasthikshetty10-hackoverflow-0b245c9
[ { "filename": "src/components/tabs/index.tsx", "retrieved_chunk": " <h2 className=\"gradient-text\">{transcription?.speaker}</h2>\n <p className=\"font-lg text-white\">\n {transcription.utterance}\n </p>\n <div className=\"text-sm font-bold text-gray-100 text-opacity-50\">\n {transcription.timestamp}\n </div>\n </div>\n );\n })}", "score": 29.94606883489448 }, { "filename": "src/pages/index.tsx", "retrieved_chunk": " </div>\n </div>\n <Features />\n <Footer />\n <div className=\"absolute inset-x-0 top-[calc(100%-13rem)] -z-10 transform-gpu overflow-hidden opacity-80 blur-3xl sm:top-[calc(100%-30rem)]\">\n <svg\n className=\"relative left-[calc(50%+3rem)] h-[21.1875rem] max-w-none -translate-x-1/2 sm:left-[calc(50%+36rem)] sm:h-[42.375rem]\"\n viewBox=\"0 0 1155 678\"\n fill=\"none\"\n xmlns=\"http://www.w3.org/2000/svg\"", "score": 23.311703693342682 }, { "filename": "src/components/card/index.tsx", "retrieved_chunk": " <div className=\"text-sm font-bold text-gray-100 text-opacity-50\">\n {room.createdAt.toLocaleDateString(\"en-US\", {\n year: \"numeric\",\n month: \"long\",\n day: \"numeric\",\n })}{\" \"}\n at{\" \"}\n {room.createdAt.toLocaleTimeString(\"en-US\", {\n hour: \"numeric\",\n minute: \"numeric\",", "score": 21.88097172407791 }, { "filename": "src/components/features/index.tsx", "retrieved_chunk": " <PopAnimation>{perk.icon}</PopAnimation>\n <TextAnimation\n textStyle=\"text-xl font-bold text-white\"\n text={perk.title}\n className=\"mt-4\"\n />\n <p className=\"mt-1 text-sm text-gray-200\">{perk.desc}</p>\n </a>\n ))}\n </div>", "score": 21.06012697579942 }, { "filename": "src/components/animation/text.tsx", "retrieved_chunk": " const container = {\n hidden: { opacity: 0 },\n visible: (i = 1) => ({\n opacity: 1,\n transition: { staggerChildren: 0.12, delayChildren: 0.04 * i },\n }),\n };\n const child = {\n visible: {\n opacity: 1,", "score": 20.982865890082643 } ]
typescript
<Tabs summary={data.output[0].contents[1]?.utterance}
import Image from "next/image"; import Link from "next/link"; import CharacterAnimation from "../animation/character"; import { BiMenuAltRight as MenuIcon } from "react-icons/bi"; import { AiOutlineClose as XIcon } from "react-icons/ai"; import { useState } from "react"; import { signIn, signOut } from "next-auth/react"; import { Session } from "next-auth"; import { FcGoogle } from "react-icons/fc"; import PopAnimation from "../animation/pop"; import Loader from "../loader"; const Navbar = ({ status, session, }: { status: "loading" | "authenticated" | "unauthenticated"; session: Session | null; }) => { const links = [ { label: "Home", path: "#", }, { label: "About", path: "#about", }, { label: "Contact", path: "#contact", }, ]; const [isMenuOpen, setIsMenuOpen] = useState(false); const toggleMenu = () => { setIsMenuOpen(!isMenuOpen); }; return ( <nav className="fixed top-0 z-10 w-full border-b border-gray-400/20 bg-white bg-opacity-5 backdrop-blur-lg backdrop-filter"> <div className="mx-auto max-w-5xl px-4"> <div className="flex h-16 items-center justify-between"> <Link href="/" className="flex items-center space-x-2"> <PopAnimation> <Image src="/logo.png" alt="Logo" width={40} height={40} priority /> </PopAnimation> <CharacterAnimation text="Jab We Meet" textStyle="text-xl font-bold text-white" /> </Link> <div className="hidden space-x-6 text-white lg:flex lg:items-center"> {links.map((link) => ( <Link className="transition-colors duration-300 hover:text-gray-400" key={link.path} href={link.path} > <CharacterAnimation text={link.label} textStyle="text-lg font-medium" /> </Link> ))} <PopAnimation> <button className="lk-button" onClick={() => { if (status === "authenticated") { signOut(); } else { signIn("google"); } }} > {status === "authenticated" ? ( "Sign Out" ) : ( <div className="flex items-center space-x-2"> <FcGoogle /> <div>Sign In</div> </div> )} </button> </PopAnimation> <PopAnimation> <select className="lk-button"> <option value="en">English</option> </select> </PopAnimation> <PopAnimation> <Link href="/profile"> {status === "loading" ? ( <
Loader /> ) : status === "authenticated" ? ( <Image src={session?.user.image as string}
width={40} height={40} className="cursor-pointer rounded-full transition duration-300 hover:grayscale" alt="profile picture" /> ) : null} </Link> </PopAnimation> </div> <div className="flex items-center space-x-4 lg:hidden"> {isMenuOpen ? ( <XIcon className="h-6 w-6 text-white" onClick={toggleMenu} /> ) : ( <MenuIcon className="h-6 w-6 text-white" onClick={toggleMenu} /> )} </div> </div> {isMenuOpen && ( <div className="flex flex-col space-y-2 p-5 text-white lg:hidden"> {links.map((link) => ( <Link key={link.path} href={link.path} className="block py-2 px-4 text-sm hover:bg-white" > {link.label} </Link> ))} <div className="flex items-center space-x-4"> <button className="lk-button" onClick={() => { if (status === "authenticated") { signIn("google"); } else { signOut(); } }} > {status === "authenticated" ? "Sign Out" : "Sign In"} </button> <select className="lk-button"> <option value="en">English</option> </select> </div> <PopAnimation> <Link href="/profile"> {status === "loading" ? ( <Loader /> ) : status === "authenticated" ? ( <Image src={session?.user.image as string} width={40} height={40} className="cursor-pointer rounded-full transition duration-300 hover:grayscale" alt="profile picture" /> ) : null} </Link> </PopAnimation> </div> )} </div> </nav> ); }; export default Navbar;
src/components/navbar/index.tsx
swasthikshetty10-hackoverflow-0b245c9
[ { "filename": "src/pages/profile.tsx", "retrieved_chunk": " const { data: rooms, isLoading, error } = api.rooms.getRoomsByUser.useQuery();\n if (status === \"loading\") return <SplashScreen />;\n if (!session && status === \"unauthenticated\") return signIn(\"google\");\n const ownedRooms =\n rooms?.filter((room) => room.OwnerId === session?.user.id) || [];\n const joinedRooms =\n rooms?.filter((room) => room.OwnerId !== session?.user.id) || [];\n return (\n <>\n <Navbar status={status} session={session} />", "score": 19.001890038955082 }, { "filename": "src/components/footer/index.tsx", "retrieved_chunk": "import Image from \"next/image\";\nimport Link from \"next/link\";\nimport PopAnimation from \"../animation/pop\";\nimport TextAnimation from \"../animation/text\";\nconst Footer = () => {\n const links = [\n {\n label: \"Home\",\n path: \"#\",\n },", "score": 18.678048721030795 }, { "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": 15.002889976150797 }, { "filename": "src/pages/rooms/[name].tsx", "retrieved_chunk": " const router = useRouter();\n const { name: roomName } = router.query;\n const { data: session, status } = useSession();\n const [preJoinChoices, setPreJoinChoices] = useState<\n LocalUserChoices | undefined\n >(undefined);\n const [selectedCode, setSelectedCode] = useState(\"en\");\n if (status === \"loading\") return <SplashScreen />;\n if (!session) signIn(\"google\");\n const languageCodes = [", "score": 14.59224420080647 }, { "filename": "src/components/splashScreen/index.tsx", "retrieved_chunk": "import Image from \"next/image\";\nimport Loader from \"../loader\";\nconst SplashScreen = () => {\n return (\n <div className=\"flex h-screen w-screen flex-col items-center justify-center space-y-5\">\n <Image\n src=\"/logo.png\"\n alt=\"Logo\"\n width={100}\n height={100}", "score": 14.414759742119202 } ]
typescript
Loader /> ) : status === "authenticated" ? ( <Image src={session?.user.image as string}
// @refresh reset import type { NextPage } from "next"; import { signIn, useSession } from "next-auth/react"; import { useRouter } from "next/router"; import React from "react"; import Typing from "~/components/animation/typing"; import Navbar from "~/components/navbar"; import { api } from "~/utils/api"; import { AiOutlineVideoCameraAdd } from "react-icons/ai"; import JoinRoom from "~/components/join"; import Image from "next/image"; import Features from "~/components/features"; import CharacterAnimation from "~/components/animation/character"; import { useRive, Layout, Fit, Alignment } from "@rive-app/react-canvas"; import TextAnimation from "~/components/animation/text"; import Loader from "~/components/loader"; import Footer from "~/components/footer"; import SplashScreen from "~/components/splashScreen"; function ConnectionTab() { const { data: session, status } = useSession(); const createRoom = api.rooms.createRoom.useMutation(); const router = useRouter(); const { RiveComponent: Hero } = useRive({ src: `hero.riv`, stateMachines: ["State Machine 1"], autoplay: true, layout: new Layout({ fit: Fit.FitWidth, alignment: Alignment.Center, }), }); const [roomLoading, setRoomLoading] = React.useState(false); const createRoomHandler = async () => { if (status === "unauthenticated") signIn("google"); else { setRoomLoading(true); const data = await createRoom.mutateAsync(); setRoomLoading(false); router.push(`/rooms/${data.roomName}`); } }; if (status === "loading") return <SplashScreen />; return ( <> <Navbar status={status} session={session} /> <div className="isolate overflow-x-hidden"> <div className="flex h-screen w-screen flex-col items-center justify-center space-y-4 p-5 text-center md:flex-row"> <div className="absolute inset-x-0 top-[-10rem] -z-10 transform-gpu overflow-hidden opacity-80 blur-3xl sm:top-[-20rem]"> <svg className="relative left-[calc(50%-11rem)] -z-10 h-[21.1875rem] max-w-none -translate-x-1/2 rotate-[30deg] sm:left-[calc(50%-30rem)] sm:h-[42.375rem]" viewBox="0 0 1155 678" fill="none" xmlns="http://www.w3.org/2000/svg" > <path fill="url(#45de2b6b-92d5-4d68-a6a0-9b9b2abad533)" fillOpacity=".3" d="M317.219 518.975L203.852 678 0 438.341l317.219 80.634 204.172-286.402c1.307 132.337 45.083 346.658 209.733 145.248C936.936 126.058 882.053-94.234 1031.02 41.331c119.18 108.451 130.68 295.337 121.53 375.223L855 299l21.173 362.054-558.954-142.079z" /> <defs> <linearGradient id="45de2b6b-92d5-4d68-a6a0-9b9b2abad533" x1="1155.49" x2="-78.208" y1=".177" y2="474.645" gradientUnits="userSpaceOnUse" > <stop stopColor="#9089FC" /> <stop offset={1} stopColor="#FF80B5" /> </linearGradient> </defs> </svg> </div> <div className="w-full max-w-md space-y-4"> <Typing /> <TextAnimation className="flex justify-center" textStyle="text-sm text-gray-400" text="Multilingual Video Conferencing App" /> <div className="flex flex-col items-center justify-center space-y-4 lg:flex-row lg:space-y-0 lg:space-x-4"> <button onClick={createRoomHandler} className="lk-button h-fit"> {roomLoading ? ( <Loader /> ) : ( <> <AiOutlineVideoCameraAdd /> <CharacterAnimation text="Create Room" textStyle="text-sm" /> </> )} </button>
{!roomLoading && <JoinRoom />}
</div> </div> <div className="flex w-full max-w-md items-center justify-center"> <Hero className="h-[40vh] w-full md:h-screen" /> </div> </div> <Features /> <Footer /> <div className="absolute inset-x-0 top-[calc(100%-13rem)] -z-10 transform-gpu overflow-hidden opacity-80 blur-3xl sm:top-[calc(100%-30rem)]"> <svg className="relative left-[calc(50%+3rem)] h-[21.1875rem] max-w-none -translate-x-1/2 sm:left-[calc(50%+36rem)] sm:h-[42.375rem]" viewBox="0 0 1155 678" fill="none" xmlns="http://www.w3.org/2000/svg" > <path fill="url(#ecb5b0c9-546c-4772-8c71-4d3f06d544bc)" fillOpacity=".3" d="M317.219 518.975L203.852 678 0 438.341l317.219 80.634 204.172-286.402c1.307 132.337 45.083 346.658 209.733 145.248C936.936 126.058 882.053-94.234 1031.02 41.331c119.18 108.451 130.68 295.337 121.53 375.223L855 299l21.173 362.054-558.954-142.079z" /> <defs> <linearGradient id="ecb5b0c9-546c-4772-8c71-4d3f06d544bc" x1="1155.49" x2="-78.208" y1=".177" y2="474.645" gradientUnits="userSpaceOnUse" > <stop stopColor="#9089FC" /> <stop offset={1} stopColor="#FF80B5" /> </linearGradient> </defs> </svg> </div> </div> </> ); } const Home: NextPage = () => { return ( <> <main data-lk-theme="default"> <ConnectionTab /> </main> </> ); }; export default Home;
src/pages/index.tsx
swasthikshetty10-hackoverflow-0b245c9
[ { "filename": "src/components/join/index.tsx", "retrieved_chunk": " />\n </label>\n <button\n disabled={!roomName}\n className={`lk-button ${\n !roomName && \"pointer-events-none cursor-not-allowed\"\n }`}\n onClick={() => router.push(`/rooms/${roomName}`)}\n >\n <CharacterAnimation text=\"Join\" textStyle=\"text-sm\"/>", "score": 16.43130775617538 }, { "filename": "src/components/navbar/index.tsx", "retrieved_chunk": " href={link.path}\n >\n <CharacterAnimation\n text={link.label}\n textStyle=\"text-lg font-medium\"\n />\n </Link>\n ))}\n <PopAnimation>\n <button", "score": 14.862329474180921 }, { "filename": "src/components/join/index.tsx", "retrieved_chunk": " </button>\n </div>\n );\n};\nexport default JoinRoom;", "score": 11.22631208441641 }, { "filename": "src/components/animation/character.tsx", "retrieved_chunk": "import React, { FC, useRef } from 'react';\nimport { motion, useInView } from 'framer-motion';\nconst CharacterAnimation: FC<{\n text: string;\n className?: string;\n textStyle?: string;\n}> = ({ text, className, textStyle }) => {\n const ref = useRef<HTMLDivElement>(null);\n const isInView = useInView(ref, { once: true });\n const letters = Array.from(text);", "score": 9.639230236059115 }, { "filename": "src/components/features/index.tsx", "retrieved_chunk": " <PopAnimation>{perk.icon}</PopAnimation>\n <TextAnimation\n textStyle=\"text-xl font-bold text-white\"\n text={perk.title}\n className=\"mt-4\"\n />\n <p className=\"mt-1 text-sm text-gray-200\">{perk.desc}</p>\n </a>\n ))}\n </div>", "score": 9.346427144407443 } ]
typescript
{!roomLoading && <JoinRoom />}
import { Dispatch, SetStateAction, type FunctionComponent } from "react"; import { api } from "~/utils/api"; import { Dialog, Transition } from "@headlessui/react"; import { Fragment, useState } from "react"; import Loader from "../loader"; import Tabs from "../tabs"; type ModalProps = { setIsOpen: Dispatch<SetStateAction<boolean>>; roomName: string; visible: boolean; }; const Modal: FunctionComponent<ModalProps> = ({ setIsOpen, roomName, visible, }) => { const { data, error, isLoading } = api.rooms.getRoomSummary.useQuery({ roomName, }); console.log(data); // input array // output array-> contents [0].utterance return ( <Transition appear show={visible} as={Fragment}> <Dialog as="div" className="relative z-10" onClose={() => setIsOpen(false)} > <Transition.Child as={Fragment} enter="ease-out duration-300" enterFrom="opacity-0" enterTo="opacity-100" leave="ease-in duration-200" leaveFrom="opacity-100" leaveTo="opacity-0" > <div className="fixed inset-0 bg-black bg-opacity-25" /> </Transition.Child> <div className="fixed inset-0 overflow-y-auto"> <div className="flex min-h-full items-center justify-center p-4 text-center"> <Transition.Child as={Fragment} enter="ease-out duration-300" enterFrom="opacity-0 scale-95" enterTo="opacity-100 scale-100" leave="ease-in duration-200" leaveFrom="opacity-100 scale-100" leaveTo="opacity-0 scale-95" > <Dialog.Panel className="w-full max-w-md transform overflow-hidden rounded-2xl bg-white bg-opacity-10 p-6 text-left align-middle shadow-xl backdrop-blur-2xl backdrop-filter transition-all"> <Dialog.Title as="h3" className="gradient-text text-lg font-medium leading-6" > Meeting Details </Dialog.Title> <div className=""> {isLoading ? ( <Loader /> ) : data ? ( <div className="text-sm text-gray-100 text-opacity-50"> {data.output[0].contents.length > 1 && ( <
Tabs summary={data.output[0].contents[1]?.utterance}
transcriptions={data.input} /> )} </div> ) : ( <div className="text-sm text-gray-100 text-opacity-50"> No summary available </div> )} </div> </Dialog.Panel> </Transition.Child> </div> </div> </Dialog> </Transition> ); }; export default Modal;
src/components/modal/index.tsx
swasthikshetty10-hackoverflow-0b245c9
[ { "filename": "src/components/tabs/index.tsx", "retrieved_chunk": " <h2 className=\"gradient-text\">{transcription?.speaker}</h2>\n <p className=\"font-lg text-white\">\n {transcription.utterance}\n </p>\n <div className=\"text-sm font-bold text-gray-100 text-opacity-50\">\n {transcription.timestamp}\n </div>\n </div>\n );\n })}", "score": 29.94606883489448 }, { "filename": "src/pages/index.tsx", "retrieved_chunk": " </div>\n </div>\n <Features />\n <Footer />\n <div className=\"absolute inset-x-0 top-[calc(100%-13rem)] -z-10 transform-gpu overflow-hidden opacity-80 blur-3xl sm:top-[calc(100%-30rem)]\">\n <svg\n className=\"relative left-[calc(50%+3rem)] h-[21.1875rem] max-w-none -translate-x-1/2 sm:left-[calc(50%+36rem)] sm:h-[42.375rem]\"\n viewBox=\"0 0 1155 678\"\n fill=\"none\"\n xmlns=\"http://www.w3.org/2000/svg\"", "score": 23.311703693342682 }, { "filename": "src/components/card/index.tsx", "retrieved_chunk": " <div className=\"text-sm font-bold text-gray-100 text-opacity-50\">\n {room.createdAt.toLocaleDateString(\"en-US\", {\n year: \"numeric\",\n month: \"long\",\n day: \"numeric\",\n })}{\" \"}\n at{\" \"}\n {room.createdAt.toLocaleTimeString(\"en-US\", {\n hour: \"numeric\",\n minute: \"numeric\",", "score": 21.88097172407791 }, { "filename": "src/components/features/index.tsx", "retrieved_chunk": " <PopAnimation>{perk.icon}</PopAnimation>\n <TextAnimation\n textStyle=\"text-xl font-bold text-white\"\n text={perk.title}\n className=\"mt-4\"\n />\n <p className=\"mt-1 text-sm text-gray-200\">{perk.desc}</p>\n </a>\n ))}\n </div>", "score": 21.06012697579942 }, { "filename": "src/components/animation/text.tsx", "retrieved_chunk": " const container = {\n hidden: { opacity: 0 },\n visible: (i = 1) => ({\n opacity: 1,\n transition: { staggerChildren: 0.12, delayChildren: 0.04 * i },\n }),\n };\n const child = {\n visible: {\n opacity: 1,", "score": 20.982865890082643 } ]
typescript
Tabs summary={data.output[0].contents[1]?.utterance}
import Image from "next/image"; import Link from "next/link"; import CharacterAnimation from "../animation/character"; import { BiMenuAltRight as MenuIcon } from "react-icons/bi"; import { AiOutlineClose as XIcon } from "react-icons/ai"; import { useState } from "react"; import { signIn, signOut } from "next-auth/react"; import { Session } from "next-auth"; import { FcGoogle } from "react-icons/fc"; import PopAnimation from "../animation/pop"; import Loader from "../loader"; const Navbar = ({ status, session, }: { status: "loading" | "authenticated" | "unauthenticated"; session: Session | null; }) => { const links = [ { label: "Home", path: "#", }, { label: "About", path: "#about", }, { label: "Contact", path: "#contact", }, ]; const [isMenuOpen, setIsMenuOpen] = useState(false); const toggleMenu = () => { setIsMenuOpen(!isMenuOpen); }; return ( <nav className="fixed top-0 z-10 w-full border-b border-gray-400/20 bg-white bg-opacity-5 backdrop-blur-lg backdrop-filter"> <div className="mx-auto max-w-5xl px-4"> <div className="flex h-16 items-center justify-between"> <Link href="/" className="flex items-center space-x-2">
<PopAnimation> <Image src="/logo.png" alt="Logo" width={40}
height={40} priority /> </PopAnimation> <CharacterAnimation text="Jab We Meet" textStyle="text-xl font-bold text-white" /> </Link> <div className="hidden space-x-6 text-white lg:flex lg:items-center"> {links.map((link) => ( <Link className="transition-colors duration-300 hover:text-gray-400" key={link.path} href={link.path} > <CharacterAnimation text={link.label} textStyle="text-lg font-medium" /> </Link> ))} <PopAnimation> <button className="lk-button" onClick={() => { if (status === "authenticated") { signOut(); } else { signIn("google"); } }} > {status === "authenticated" ? ( "Sign Out" ) : ( <div className="flex items-center space-x-2"> <FcGoogle /> <div>Sign In</div> </div> )} </button> </PopAnimation> <PopAnimation> <select className="lk-button"> <option value="en">English</option> </select> </PopAnimation> <PopAnimation> <Link href="/profile"> {status === "loading" ? ( <Loader /> ) : status === "authenticated" ? ( <Image src={session?.user.image as string} width={40} height={40} className="cursor-pointer rounded-full transition duration-300 hover:grayscale" alt="profile picture" /> ) : null} </Link> </PopAnimation> </div> <div className="flex items-center space-x-4 lg:hidden"> {isMenuOpen ? ( <XIcon className="h-6 w-6 text-white" onClick={toggleMenu} /> ) : ( <MenuIcon className="h-6 w-6 text-white" onClick={toggleMenu} /> )} </div> </div> {isMenuOpen && ( <div className="flex flex-col space-y-2 p-5 text-white lg:hidden"> {links.map((link) => ( <Link key={link.path} href={link.path} className="block py-2 px-4 text-sm hover:bg-white" > {link.label} </Link> ))} <div className="flex items-center space-x-4"> <button className="lk-button" onClick={() => { if (status === "authenticated") { signIn("google"); } else { signOut(); } }} > {status === "authenticated" ? "Sign Out" : "Sign In"} </button> <select className="lk-button"> <option value="en">English</option> </select> </div> <PopAnimation> <Link href="/profile"> {status === "loading" ? ( <Loader /> ) : status === "authenticated" ? ( <Image src={session?.user.image as string} width={40} height={40} className="cursor-pointer rounded-full transition duration-300 hover:grayscale" alt="profile picture" /> ) : null} </Link> </PopAnimation> </div> )} </div> </nav> ); }; export default Navbar;
src/components/navbar/index.tsx
swasthikshetty10-hackoverflow-0b245c9
[ { "filename": "src/components/footer/index.tsx", "retrieved_chunk": " <footer id=\"contact\" className=\"bg-gray-900\">\n <div className=\"mx-auto max-w-5xl px-4 py-16 sm:px-6 lg:px-8\">\n <PopAnimation className=\"flex justify-center text-primary\">\n <Image\n src=\"/logo.png\"\n alt=\"Logo\"\n width={100}\n height={100}\n className=\"h-12 w-auto\"\n />", "score": 81.82292184634977 }, { "filename": "src/components/card/index.tsx", "retrieved_chunk": " hour12: true,\n })}\n </div>\n <PopAnimation className=\"flex flex-row items-center justify-center\">\n <button\n onClick={() => setIsOpen(true)}\n className=\"mt-5 flex flex-row items-center justify-center space-x-2 rounded-lg bg-gray-100 bg-opacity-5 p-2 backdrop-blur-lg backdrop-filter hover:bg-gray-100 hover:bg-opacity-10\"\n >\n <IoDocumentTextOutline\n className=\"text-2xl text-gray-100\"", "score": 70.51731645627657 }, { "filename": "src/components/splashScreen/index.tsx", "retrieved_chunk": "import Image from \"next/image\";\nimport Loader from \"../loader\";\nconst SplashScreen = () => {\n return (\n <div className=\"flex h-screen w-screen flex-col items-center justify-center space-y-5\">\n <Image\n src=\"/logo.png\"\n alt=\"Logo\"\n width={100}\n height={100}", "score": 61.809497425582094 }, { "filename": "src/components/card/index.tsx", "retrieved_chunk": " slug: string | null;\n createdAt: Date;\n };\n}) {\n let [isOpen, setIsOpen] = useState(false)\n return (\n <div className=\"m-4 flex flex-col items-center justify-center rounded-2xl bg-white bg-opacity-5 p-4 shadow-lg backdrop-blur-lg backdrop-filter hover:bg-opacity-10\">\n <div key={room.name}>\n <TextAnimation textStyle=\"text-xl font-bold text-white\" text=\"Room\" />\n <div className=\"gradient-text\">{room.slug || room.name}</div>", "score": 54.44698125631374 }, { "filename": "src/pages/index.tsx", "retrieved_chunk": " };\n if (status === \"loading\") return <SplashScreen />;\n return (\n <>\n <Navbar status={status} session={session} />\n <div className=\"isolate overflow-x-hidden\">\n <div className=\"flex h-screen w-screen flex-col items-center justify-center space-y-4 p-5 text-center md:flex-row\">\n <div className=\"absolute inset-x-0 top-[-10rem] -z-10 transform-gpu overflow-hidden opacity-80 blur-3xl sm:top-[-20rem]\">\n <svg\n className=\"relative left-[calc(50%-11rem)] -z-10 h-[21.1875rem] max-w-none -translate-x-1/2 rotate-[30deg] sm:left-[calc(50%-30rem)] sm:h-[42.375rem]\"", "score": 50.45753141772649 } ]
typescript
<PopAnimation> <Image src="/logo.png" alt="Logo" width={40}
import { LiveKitRoom, PreJoin, LocalUserChoices, VideoConference, formatChatMessageLinks, } from "@livekit/components-react"; import { LogLevel, RoomOptions, VideoPresets } from "livekit-client"; import type { NextPage } from "next"; import { useRouter } from "next/router"; import { useEffect, useMemo, useState } from "react"; import { DebugMode } from "../../lib/Debug"; import { api } from "~/utils/api"; import { signIn, useSession } from "next-auth/react"; import Pusher from "pusher-js"; import useTranscribe from "~/hooks/useTranscribe"; import Captions from "~/components/captions"; import SplashScreen from "~/components/splashScreen"; import { AiFillSetting } from "react-icons/ai"; const Home: NextPage = () => { const router = useRouter(); const { name: roomName } = router.query; const { data: session, status } = useSession(); const [preJoinChoices, setPreJoinChoices] = useState< LocalUserChoices | undefined >(undefined); const [selectedCode, setSelectedCode] = useState("en"); if (status === "loading") return <SplashScreen />; if (!session) signIn("google"); const languageCodes = [ { language: "English", code: "en-US", }, { language: "Hindi", code: "hi-IN", }, { language: "Japanese", code: "ja-JP", }, { language: "French", code: "fr-FR", }, { language: "Deutsch", code: "de-DE", }, ]; return ( <main data-lk-theme="default"> {roomName && !Array.isArray(roomName) && preJoinChoices ? ( <> <ActiveRoom roomName={roomName} userChoices={preJoinChoices} onLeave={() => setPreJoinChoices(undefined)} userId={session?.user.id as string} selectedLanguage={selectedCode} ></ActiveRoom> <div className="lk-prejoin" style={{ width: "100%", }} > <label className="flex items-center justify-center gap-2"> <span className="flex items-center space-x-2 text-center text-xs lg:text-sm"> <AiFillSetting /> <a>Switch Language</a> </span> <select className="lk-button" onChange={(e) => setSelectedCode(e.target.value)} defaultValue={selectedCode} > {languageCodes.map((language) => ( <option value={language.code}>{language.language}</option> ))} </select> </label> </div> </> ) : ( <div className="flex h-screen flex-col items-center justify-center"> <div className="lk-prejoin flex flex-col gap-3"> <div className="text-2xl font-bold">Hey, {session?.user.name}!</div> <div className="text-sm font-normal"> You are joining{" "} <span className="gradient-text font-semibold">{roomName}</span> </div> <label> <span>Choose your Language</span> </label> <select className="lk-button" onChange={(e) => setSelectedCode(e.target.value)} > {languageCodes.map((language) => ( <option value={language.code}>{language.language}</option> ))} </select> </div> <PreJoin onError={(err) => console.log("Error while setting up prejoin", err) } defaults={{ username: session?.user.name as string, videoEnabled: true, audioEnabled: true, }} onSubmit={(values) => { console.log("Joining with: ", values); setPreJoinChoices(values); }} ></PreJoin> </div> )} </main> ); }; export default Home; type ActiveRoomProps = { userChoices: LocalUserChoices; roomName: string; region?: string; onLeave?: () => void; userId: string; selectedLanguage: string; }; const ActiveRoom = ({ roomName, userChoices, onLeave, userId, selectedLanguage, }: ActiveRoomProps) => {
const { data, error, isLoading } = api.rooms.joinRoom.useQuery({ roomName });
const router = useRouter(); const { region, hq } = router.query; // const liveKitUrl = useServerUrl(region as string | undefined); const roomOptions = useMemo((): RoomOptions => { return { videoCaptureDefaults: { deviceId: userChoices.videoDeviceId ?? undefined, resolution: hq === "true" ? VideoPresets.h2160 : VideoPresets.h720, }, publishDefaults: { videoSimulcastLayers: hq === "true" ? [VideoPresets.h1080, VideoPresets.h720] : [VideoPresets.h540, VideoPresets.h216], }, audioCaptureDefaults: { deviceId: userChoices.audioDeviceId ?? undefined, }, adaptiveStream: { pixelDensity: "screen" }, dynacast: true, }; }, [userChoices, hq]); const [transcriptionQueue, setTranscriptionQueue] = useState< { sender: string; message: string; senderId: string; isFinal: boolean; }[] >([]); useTranscribe({ roomName, audioEnabled: userChoices.audioEnabled, languageCode: selectedLanguage, }); useEffect(() => { const pusher = new Pusher(process.env.NEXT_PUBLIC_PUSHER_KEY as string, { cluster: process.env.NEXT_PUBLIC_PUSHER_CLUSTER as string, }); const channel = pusher.subscribe(roomName); channel.bind( "transcribe-event", function (data: { sender: string; message: string; senderId: string; isFinal: boolean; }) { if (data.isFinal && userId !== data.senderId) { setTranscriptionQueue((prev) => { return [...prev, data]; }); } } ); return () => { pusher.unsubscribe(roomName); }; }, []); return ( <> {data && ( <LiveKitRoom token={data.accessToken} serverUrl={process.env.NEXT_PUBLIC_LIVEKIT_API_HOST} options={roomOptions} video={userChoices.videoEnabled} audio={userChoices.audioEnabled} onDisconnected={onLeave} > <Captions transcriptionQueue={transcriptionQueue} setTranscriptionQueue={setTranscriptionQueue} languageCode={selectedLanguage} /> <VideoConference chatMessageFormatter={formatChatMessageLinks} /> <DebugMode logLevel={LogLevel.info} /> </LiveKitRoom> )} </> ); };
src/pages/rooms/[name].tsx
swasthikshetty10-hackoverflow-0b245c9
[ { "filename": "src/components/modal/index.tsx", "retrieved_chunk": "};\nconst Modal: FunctionComponent<ModalProps> = ({\n setIsOpen,\n roomName,\n visible,\n}) => {\n const { data, error, isLoading } = api.rooms.getRoomSummary.useQuery({\n roomName,\n });\n console.log(data);", "score": 32.27743365539583 }, { "filename": "src/pages/profile.tsx", "retrieved_chunk": " const { data: rooms, isLoading, error } = api.rooms.getRoomsByUser.useQuery();\n if (status === \"loading\") return <SplashScreen />;\n if (!session && status === \"unauthenticated\") return signIn(\"google\");\n const ownedRooms =\n rooms?.filter((room) => room.OwnerId === session?.user.id) || [];\n const joinedRooms =\n rooms?.filter((room) => room.OwnerId !== session?.user.id) || [];\n return (\n <>\n <Navbar status={status} session={session} />", "score": 19.339014627890208 }, { "filename": "src/server/api/routers/rooms.ts", "retrieved_chunk": "const openai = new OpenAIApi(configuration);\nexport const roomsRouter = createTRPCRouter({\n joinRoom: protectedProcedure\n .input(\n z.object({\n roomName: z.string(),\n })\n )\n .query(async ({ input, ctx }) => {\n const identity = ctx.session.user.id;", "score": 13.522264959034015 }, { "filename": "src/pages/index.tsx", "retrieved_chunk": " });\n const [roomLoading, setRoomLoading] = React.useState(false);\n const createRoomHandler = async () => {\n if (status === \"unauthenticated\") signIn(\"google\");\n else {\n setRoomLoading(true);\n const data = await createRoom.mutateAsync();\n setRoomLoading(false);\n router.push(`/rooms/${data.roomName}`);\n }", "score": 13.1853539872138 }, { "filename": "src/server/api/routers/rooms.ts", "retrieved_chunk": " },\n });\n return rooms;\n }),\n getRoomSummary: protectedProcedure\n .input(\n z.object({\n roomName: z.string(),\n })\n )", "score": 12.455935198232723 } ]
typescript
const { data, error, isLoading } = api.rooms.joinRoom.useQuery({ roomName });
import { nullable, string, z } from "zod"; import { AccessToken, RoomServiceClient } from "livekit-server-sdk"; import type { AccessTokenOptions, VideoGrant, CreateOptions, } from "livekit-server-sdk"; import { translate } from "@vitalets/google-translate-api"; const createToken = (userInfo: AccessTokenOptions, grant: VideoGrant) => { const at = new AccessToken(apiKey, apiSecret, userInfo); at.ttl = "5m"; at.addGrant(grant); return at.toJwt(); }; import axios from "axios"; const apiKey = process.env.LIVEKIT_API_KEY; const apiSecret = process.env.LIVEKIT_API_SECRET; const apiHost = process.env.NEXT_PUBLIC_LIVEKIT_API_HOST as string; import { createTRPCRouter, publicProcedure, protectedProcedure, } from "~/server/api/trpc"; import { TokenResult } from "~/lib/type"; import { CreateRoomRequest } from "livekit-server-sdk/dist/proto/livekit_room"; const roomClient = new RoomServiceClient(apiHost, apiKey, apiSecret); const configuration = new Configuration({ apiKey: process.env.OPEN_API_SECRET, }); import { Configuration, OpenAIApi } from "openai"; const openai = new OpenAIApi(configuration); export const roomsRouter = createTRPCRouter({ joinRoom: protectedProcedure .input( z.object({ roomName: z.string(), }) ) .query(async ({ input, ctx }) => { const identity = ctx.session.user.id; const name = ctx.session.user.name; const grant: VideoGrant = { room: input.roomName, roomJoin: true, canPublish: true, canPublishData: true, canSubscribe: true, }; const { roomName } = input; const token = createToken({ identity, name: name as string }, grant); const result: TokenResult = { identity, accessToken: token, }; try { // check if user is already in room console.log("here");
const participant = await ctx.prisma.participant.findUnique({
where: { UserId_RoomName: { UserId: ctx.session.user.id, RoomName: roomName, }, }, }); if (participant === null) await ctx.prisma.participant.create({ data: { User: { connect: { id: ctx.session.user.id, }, }, Room: { connect: { name: roomName, }, }, }, }); } catch (error) { console.log(error); } return result; }), createRoom: protectedProcedure.mutation(async ({ ctx }) => { const identity = ctx.session.user.id; const name = ctx.session.user.name; const room = await ctx.prisma.room.create({ data: { Owner: { connect: { id: ctx.session.user.id, }, }, }, }); await roomClient.createRoom({ name: room.name, }); const grant: VideoGrant = { room: room.name, roomJoin: true, canPublish: true, canPublishData: true, canSubscribe: true, }; const token = createToken({ identity, name: name as string }, grant); const result = { roomName: room.name, }; return result; }), getRoomsByUser: protectedProcedure.query(async ({ ctx }) => { const rooms = await ctx.prisma.room.findMany({ where: { OR: [ { Owner: { id: ctx.session.user.id, }, }, { Participant: { some: { UserId: ctx.session.user.id, }, }, }, ], }, }); return rooms; }), getRoomSummary: protectedProcedure .input( z.object({ roomName: z.string(), }) ) .query(async ({ input, ctx }) => { // order all transcripts by createdAt in ascending order const transcripts = await ctx.prisma.transcript.findMany({ where: { Room: { name: input.roomName, }, }, include: { User: true, }, orderBy: { createdAt: "asc", }, }); const chatLog = transcripts.map((transcript) => ({ speaker: transcript.User.name, utterance: transcript.text, timestamp: transcript.createdAt.toISOString(), })); if (chatLog.length === 0) { return null; } const apiKey = process.env.ONEAI_API_KEY; console.log(chatLog); try { const config = { method: "POST", url: "https://api.oneai.com/api/v0/pipeline", headers: { "api-key": apiKey, "Content-Type": "application/json", }, data: { input: chatLog, input_type: "conversation", content_type: "application/json", output_type: "json", multilingual: { enabled: true, }, steps: [ { skill: "article-topics", }, { skill: "numbers", }, { skill: "names", }, { skill: "emotions", }, { skill: "summarize", }, ], }, }; const res = await axios.request(config); console.log(res.status); return res.data; } catch (error) { console.log(error); } }), });
src/server/api/routers/rooms.ts
swasthikshetty10-hackoverflow-0b245c9
[ { "filename": "src/lib/type.ts", "retrieved_chunk": "export interface TokenResult {\n identity: string;\n accessToken: string;\n}", "score": 30.24393356133244 }, { "filename": "src/server/api/routers/pusher.ts", "retrieved_chunk": " const { text } = await translate(message, {\n to: \"en\",\n });\n await ctx.prisma.transcript.create({\n data: {\n text: text,\n Room: {\n connect: {\n name: input.roomName,\n },", "score": 29.353881528568337 }, { "filename": "src/server/api/routers/pusher.ts", "retrieved_chunk": " const response = await pusher.trigger(\n input.roomName,\n \"transcribe-event\",\n {\n message,\n sender: user.name,\n isFinal: input.isFinal,\n senderId: user.id,\n }\n );", "score": 25.74617477912603 }, { "filename": "src/server/api/routers/pusher.ts", "retrieved_chunk": " .input(\n z.object({\n message: string(),\n roomName: string(),\n isFinal: z.boolean(),\n })\n )\n .mutation(async ({ input, ctx }) => {\n const { message } = input;\n const { user } = ctx.session;", "score": 23.704763115087363 }, { "filename": "src/pages/rooms/[name].tsx", "retrieved_chunk": " username: session?.user.name as string,\n videoEnabled: true,\n audioEnabled: true,\n }}\n onSubmit={(values) => {\n console.log(\"Joining with: \", values);\n setPreJoinChoices(values);\n }}\n ></PreJoin>\n </div>", "score": 20.503256384100606 } ]
typescript
const participant = await ctx.prisma.participant.findUnique({
import { type GetServerSidePropsContext } from "next"; import { getServerSession, type NextAuthOptions, type DefaultSession, } from "next-auth"; import GoogleProvider from "next-auth/providers/google"; 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: [ GoogleProvider({ clientId: env.
GOOGLE_CLIENT_ID, clientSecret: env.GOOGLE_CLIENT_SECRET, }), ], };
/** * 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
swasthikshetty10-hackoverflow-0b245c9
[ { "filename": "src/server/db.ts", "retrieved_chunk": "import { PrismaClient } from \"@prisma/client\";\nimport { env } from \"~/env.mjs\";\nconst globalForPrisma = globalThis as unknown as { prisma: PrismaClient };\nexport const prisma =\n globalForPrisma.prisma ||\n new PrismaClient({\n log:\n env.NODE_ENV === \"development\" ? [\"query\", \"error\", \"warn\"] : [\"error\"],\n });\nif (env.NODE_ENV !== \"production\") globalForPrisma.prisma = prisma;", "score": 15.065588776912378 }, { "filename": "src/utils/pusher.ts", "retrieved_chunk": "import Pusher from \"pusher\";\nexport const pusher = new Pusher({\n appId: process.env.PUSHER_APP_ID as string,\n key: process.env.PUSHER_KEY as string,\n secret: process.env.PUSHER_SECRET as string,\n cluster: process.env.PUSHER_CLUSTER as string,\n useTLS: true,\n});", "score": 9.613925500746863 }, { "filename": "src/server/api/routers/rooms.ts", "retrieved_chunk": " at.ttl = \"5m\";\n at.addGrant(grant);\n return at.toJwt();\n};\nimport axios from \"axios\";\nconst apiKey = process.env.LIVEKIT_API_KEY;\nconst apiSecret = process.env.LIVEKIT_API_SECRET;\nconst apiHost = process.env.NEXT_PUBLIC_LIVEKIT_API_HOST as string;\nimport {\n createTRPCRouter,", "score": 8.961306020773232 }, { "filename": "src/pages/api/trpc/[trpc].ts", "retrieved_chunk": "import { createNextApiHandler } from \"@trpc/server/adapters/next\";\nimport { env } from \"~/env.mjs\";\nimport { createTRPCContext } from \"~/server/api/trpc\";\nimport { appRouter } from \"~/server/api/root\";\n// export API handler\nexport default createNextApiHandler({\n router: appRouter,\n createContext: createTRPCContext,\n onError:\n env.NODE_ENV === \"development\"", "score": 8.538635324954877 }, { "filename": "src/pages/rooms/[name].tsx", "retrieved_chunk": " >([]);\n useTranscribe({\n roomName,\n audioEnabled: userChoices.audioEnabled,\n languageCode: selectedLanguage,\n });\n useEffect(() => {\n const pusher = new Pusher(process.env.NEXT_PUBLIC_PUSHER_KEY as string, {\n cluster: process.env.NEXT_PUBLIC_PUSHER_CLUSTER as string,\n });", "score": 8.442004511749978 } ]
typescript
GOOGLE_CLIENT_ID, clientSecret: env.GOOGLE_CLIENT_SECRET, }), ], };
import { nullable, string, z } from "zod"; import { AccessToken, RoomServiceClient } from "livekit-server-sdk"; import type { AccessTokenOptions, VideoGrant, CreateOptions, } from "livekit-server-sdk"; import { translate } from "@vitalets/google-translate-api"; const createToken = (userInfo: AccessTokenOptions, grant: VideoGrant) => { const at = new AccessToken(apiKey, apiSecret, userInfo); at.ttl = "5m"; at.addGrant(grant); return at.toJwt(); }; import axios from "axios"; const apiKey = process.env.LIVEKIT_API_KEY; const apiSecret = process.env.LIVEKIT_API_SECRET; const apiHost = process.env.NEXT_PUBLIC_LIVEKIT_API_HOST as string; import { createTRPCRouter, publicProcedure, protectedProcedure, } from "~/server/api/trpc"; import { TokenResult } from "~/lib/type"; import { CreateRoomRequest } from "livekit-server-sdk/dist/proto/livekit_room"; const roomClient = new RoomServiceClient(apiHost, apiKey, apiSecret); const configuration = new Configuration({ apiKey: process.env.OPEN_API_SECRET, }); import { Configuration, OpenAIApi } from "openai"; const openai = new OpenAIApi(configuration); export const roomsRouter = createTRPCRouter({ joinRoom: protectedProcedure .input( z.object({ roomName: z.string(), }) ) .query(async ({ input, ctx }) => { const identity = ctx.session.user.id; const name = ctx.session.user.name; const grant: VideoGrant = { room: input.roomName, roomJoin: true, canPublish: true, canPublishData: true, canSubscribe: true, }; const { roomName } = input; const token = createToken({ identity, name: name as string }, grant); const result: TokenResult = { identity, accessToken: token, }; try { // check if user is already in room console.log("here"); const participant = await ctx.prisma.participant.findUnique({ where: { UserId_RoomName: { UserId: ctx.session.user.id, RoomName: roomName, }, }, }); if (participant === null) await ctx.prisma.participant.create({ data: { User: { connect: { id: ctx.session.user.id, }, }, Room: { connect: { name: roomName, }, }, }, }); } catch (error) { console.log(error); } return result; }), createRoom: protectedProcedure.mutation(async ({ ctx }) => { const identity = ctx.session.user.id; const name = ctx.session.user.name; const room = await ctx.prisma.room.create({ data: { Owner: { connect: { id: ctx.session.user.id, }, }, }, }); await roomClient.createRoom({ name: room.name, }); const grant: VideoGrant = { room: room.name, roomJoin: true, canPublish: true, canPublishData: true, canSubscribe: true, }; const token = createToken({ identity, name: name as string }, grant); const result = { roomName: room.name, }; return result; }), getRoomsByUser: protectedProcedure.query(async ({ ctx }) => { const rooms = await ctx.prisma.room.findMany({ where: { OR: [ { Owner: { id: ctx.session.user.id, }, }, { Participant: { some: { UserId: ctx.session.user.id, }, }, }, ], }, }); return rooms; }), getRoomSummary: protectedProcedure .input( z.object({ roomName: z.string(), }) ) .query(async ({ input, ctx }) => { // order all transcripts by createdAt in ascending order const transcripts = await ctx.prisma.transcript.findMany({ where: { Room: { name: input.roomName, }, }, include: { User: true, }, orderBy: { createdAt: "asc", }, }); const chatLog
= transcripts.map((transcript) => ({
speaker: transcript.User.name, utterance: transcript.text, timestamp: transcript.createdAt.toISOString(), })); if (chatLog.length === 0) { return null; } const apiKey = process.env.ONEAI_API_KEY; console.log(chatLog); try { const config = { method: "POST", url: "https://api.oneai.com/api/v0/pipeline", headers: { "api-key": apiKey, "Content-Type": "application/json", }, data: { input: chatLog, input_type: "conversation", content_type: "application/json", output_type: "json", multilingual: { enabled: true, }, steps: [ { skill: "article-topics", }, { skill: "numbers", }, { skill: "names", }, { skill: "emotions", }, { skill: "summarize", }, ], }, }; const res = await axios.request(config); console.log(res.status); return res.data; } catch (error) { console.log(error); } }), });
src/server/api/routers/rooms.ts
swasthikshetty10-hackoverflow-0b245c9
[ { "filename": "src/hooks/useTranscribe.ts", "retrieved_chunk": " } = useSpeechRecognition();\n const pusherMutation = api.pusher.send.useMutation();\n useEffect(() => {\n if (finalTranscript !== \"\") {\n pusherMutation.mutate({\n message: transcript,\n roomName: roomName,\n isFinal: true,\n });\n resetTranscript();", "score": 8.842289671252715 }, { "filename": "src/hooks/useTranscribe.ts", "retrieved_chunk": "const useTranscribe = ({\n roomName,\n audioEnabled,\n languageCode,\n}: UseTranscribeProps) => {\n const {\n transcript,\n resetTranscript,\n finalTranscript,\n browserSupportsSpeechRecognition,", "score": 7.125082930306826 }, { "filename": "src/server/api/routers/pusher.ts", "retrieved_chunk": " },\n User: {\n connect: {\n id: user.id,\n },\n },\n },\n });\n return response;\n }),", "score": 6.102457441786328 }, { "filename": "src/components/card/index.tsx", "retrieved_chunk": " <div className=\"text-sm font-bold text-gray-100 text-opacity-50\">\n {room.createdAt.toLocaleDateString(\"en-US\", {\n year: \"numeric\",\n month: \"long\",\n day: \"numeric\",\n })}{\" \"}\n at{\" \"}\n {room.createdAt.toLocaleTimeString(\"en-US\", {\n hour: \"numeric\",\n minute: \"numeric\",", "score": 6.025154061484767 }, { "filename": "src/server/api/routers/pusher.ts", "retrieved_chunk": " const { text } = await translate(message, {\n to: \"en\",\n });\n await ctx.prisma.transcript.create({\n data: {\n text: text,\n Room: {\n connect: {\n name: input.roomName,\n },", "score": 5.723514353011765 } ]
typescript
= transcripts.map((transcript) => ({
import { Body, Controller, Get, HttpCode, HttpStatus, Inject, NotFoundException, Param, Post, Req, Res, UnauthorizedException, } from '@nestjs/common'; import { ConfigType } from '@nestjs/config'; import { EventBus } from '@nestjs/cqrs'; import { JwtService } from '@nestjs/jwt'; import { ApiNoContentResponse, ApiOkResponse, ApiOperation, ApiTags, } from '@nestjs/swagger'; import { Request, Response } from 'express'; import iamConfig from '../configs/iam.config'; import { ActiveUser } from '../decorators/active-user.decorator'; import { Auth } from '../decorators/auth.decorator'; import { LoginRequestDto } from '../dtos/login-request.dto'; import { LoginResponseDto } from '../dtos/login-response.dto'; import { PasswordlessLoginRequestRequestDto } from '../dtos/passwordless-login-request-request.dto'; import { AuthType } from '../enums/auth-type.enum'; import { TokenType } from '../enums/token-type.enum'; import { LoggedInEvent } from '../events/logged-in.event'; import { LoggedOutEvent } from '../events/logged-out.event'; import { BcryptHasher } from '../hashers/bcrypt.hasher'; import { MODULE_OPTIONS_TOKEN } from '../iam.module-definition'; import { IActiveUser } from '../interfaces/active-user.interface'; import { IModuleOptions } from '../interfaces/module-options.interface'; import { IRefreshTokenJwtPayload } from '../interfaces/refresh-token-jwt-payload.interface'; import { LoginProcessor } from '../processors/login.processor'; import { LogoutProcessor } from '../processors/logout.processor'; import { PasswordlessLoginRequestProcessor } from '../processors/passwordless-login-request.processor'; @Controller() @ApiTags('Auth') export class AuthController { constructor( private readonly eventBus: EventBus, private readonly hasher: BcryptHasher, private readonly loginProcessor: LoginProcessor, private readonly logoutProcessor: LogoutProcessor, private readonly passwordlessLoginRequestProcessor: PasswordlessLoginRequestProcessor, private readonly jwtService: JwtService, @Inject(MODULE_OPTIONS_TOKEN) private readonly moduleOptions: IModuleOptions, @Inject(iamConfig.KEY) private readonly config: ConfigType<typeof iamConfig>, ) {} @HttpCode(HttpStatus.OK) @ApiOperation({ operationId: 'authLogin' }) @ApiOkResponse({ type: LoginResponseDto }) @Auth(AuthType.None) @Post('/auth/login') async login( @Body() request
: LoginRequestDto, @Res({ passthrough: true }) response: Response, ): Promise<LoginResponseDto> {
if (!this.config.auth.methods.includes('basic')) { throw new NotFoundException(); } try { const user = await this.moduleOptions.authService.checkUser( request.username, ); if (!(await this.hasher.compare(request.password, user.getPassword()))) { throw new UnauthorizedException(); } const login = await this.loginProcessor.process(user, response); this.eventBus.publish(new LoggedInEvent(user.getId())); return { accessToken: login.accessToken, refreshToken: login.refreshToken, }; } catch { throw new UnauthorizedException(); } } @HttpCode(HttpStatus.OK) @ApiOperation({ operationId: 'authPasswordlessLogin' }) @ApiOkResponse({ type: LoginResponseDto }) @Auth(AuthType.None) @Get('/auth/passwordless_login/:id') async passwordlessLogin( @Param('id') tokenId: string, @Req() request: Request, @Res({ passthrough: true }) response: Response, ): Promise<LoginResponseDto> { if (!this.config.auth.methods.includes('passwordless')) { throw new NotFoundException(); } const requestId = request.cookies[TokenType.PasswordlessLoginToken]; if (!requestId) { throw new UnauthorizedException(); } try { const token = await this.moduleOptions.authService.checkToken( tokenId, TokenType.PasswordlessLoginToken, requestId, ); const user = await this.moduleOptions.authService.getUser( token.getUserId(), ); await this.moduleOptions.authService.checkUser(user.getUsername()); await this.moduleOptions.authService.removeToken(tokenId); const login = await this.loginProcessor.process(user, response); return { accessToken: login.accessToken, refreshToken: login.refreshToken, }; } catch { throw new UnauthorizedException(); } } @HttpCode(HttpStatus.NO_CONTENT) @ApiOperation({ operationId: 'authPasswordlessLoginRequest' }) @ApiNoContentResponse() @Auth(AuthType.None) @Post('/auth/passwordless_login') async passwordlessLoginRequest( @Body() request: PasswordlessLoginRequestRequestDto, @Res({ passthrough: true }) response: Response, ): Promise<void> { if (!this.config.auth.methods.includes('passwordless')) { throw new NotFoundException(); } try { const user = await this.moduleOptions.authService.checkUser( request.username, ); await this.passwordlessLoginRequestProcessor.process(user, response); } catch {} } @HttpCode(HttpStatus.OK) @ApiOperation({ operationId: 'authRefreshTokens' }) @ApiOkResponse({ type: LoginResponseDto }) @Auth(AuthType.None) @Get('/auth/refresh_tokens') async refreshTokens( @Req() request: Request, @Res({ passthrough: true }) response: Response, ): Promise<LoginResponseDto> { try { const refreshTokenJwtPayload: IRefreshTokenJwtPayload = await this.jwtService.verifyAsync( request.cookies[TokenType.RefreshToken], ); await this.moduleOptions.authService.checkToken( refreshTokenJwtPayload.id, TokenType.RefreshToken, ); const user = await this.moduleOptions.authService.getUser( refreshTokenJwtPayload.sub, ); await this.moduleOptions.authService.checkUser(user.getUsername()); await this.moduleOptions.authService.removeToken( refreshTokenJwtPayload.id, ); const login = await this.loginProcessor.process(user, response); return { accessToken: login.accessToken, refreshToken: login.refreshToken, }; } catch { throw new UnauthorizedException(); } } @HttpCode(HttpStatus.NO_CONTENT) @ApiOperation({ operationId: 'authLogout' }) @ApiNoContentResponse() @Auth(AuthType.None) @Get('/auth/logout') async logout( @Req() request: Request, @Res({ passthrough: true }) response: Response, @ActiveUser() activeUser: IActiveUser, ) { await this.logoutProcessor.process(request, response); if (!activeUser) { return; } this.eventBus.publish(new LoggedOutEvent(activeUser.userId)); } }
src/controllers/auth.controller.ts
fastnloud-nest-iam-463230d
[ { "filename": "src/decorators/auth.decorator.ts", "retrieved_chunk": "import { SetMetadata } from '@nestjs/common';\nimport { IAM_AUTH_TYPE_KEY } from '../constants/iam.constants';\nimport { AuthType } from '../enums/auth-type.enum';\nexport const Auth = (...authTypes: AuthType[]) =>\n SetMetadata(IAM_AUTH_TYPE_KEY, authTypes);", "score": 11.153951066401191 }, { "filename": "src/processors/login.processor.ts", "retrieved_chunk": " private readonly config: ConfigType<typeof iamConfig>,\n ) {}\n public async process(user: IUser, response: Response): Promise<ILogin> {\n const accessToken = await this.accessTokenGenerator.generate(user);\n const refreshToken = await this.refreshTokenGenerator.generate(user);\n const login = {\n accessToken: accessToken.jwt,\n refreshToken: refreshToken.jwt,\n };\n await this.moduleOptions.authService.saveToken(", "score": 10.274993769594374 }, { "filename": "src/enums/auth-type.enum.ts", "retrieved_chunk": "export enum AuthType {\n AccessToken,\n None,\n}", "score": 9.780300348009533 }, { "filename": "src/dtos/login-response.dto.ts", "retrieved_chunk": "import { ApiProperty } from '@nestjs/swagger';\nexport class LoginResponseDto {\n @ApiProperty()\n public readonly accessToken: string;\n @ApiProperty()\n public readonly refreshToken: string;\n}", "score": 9.494117414408711 }, { "filename": "src/processors/logout.processor.ts", "retrieved_chunk": "export class LogoutProcessor {\n public constructor(\n private readonly jwtService: JwtService,\n @Inject(MODULE_OPTIONS_TOKEN)\n private readonly moduleOptions: IModuleOptions,\n @Inject(iamConfig.KEY)\n private readonly config: ConfigType<typeof iamConfig>,\n ) {}\n public async process(request: Request, response: Response): Promise<void> {\n try {", "score": 9.270901570343838 } ]
typescript
: LoginRequestDto, @Res({ passthrough: true }) response: Response, ): Promise<LoginResponseDto> {
import { nullable, string, z } from "zod"; import { AccessToken, RoomServiceClient } from "livekit-server-sdk"; import type { AccessTokenOptions, VideoGrant, CreateOptions, } from "livekit-server-sdk"; import { translate } from "@vitalets/google-translate-api"; const createToken = (userInfo: AccessTokenOptions, grant: VideoGrant) => { const at = new AccessToken(apiKey, apiSecret, userInfo); at.ttl = "5m"; at.addGrant(grant); return at.toJwt(); }; import axios from "axios"; const apiKey = process.env.LIVEKIT_API_KEY; const apiSecret = process.env.LIVEKIT_API_SECRET; const apiHost = process.env.NEXT_PUBLIC_LIVEKIT_API_HOST as string; import { createTRPCRouter, publicProcedure, protectedProcedure, } from "~/server/api/trpc"; import { TokenResult } from "~/lib/type"; import { CreateRoomRequest } from "livekit-server-sdk/dist/proto/livekit_room"; const roomClient = new RoomServiceClient(apiHost, apiKey, apiSecret); const configuration = new Configuration({ apiKey: process.env.OPEN_API_SECRET, }); import { Configuration, OpenAIApi } from "openai"; const openai = new OpenAIApi(configuration); export const roomsRouter = createTRPCRouter({ joinRoom: protectedProcedure .input( z.object({ roomName: z.string(), }) ) .query(async ({ input, ctx }) => { const identity = ctx.session.user.id; const name = ctx.session.user.name; const grant: VideoGrant = { room: input.roomName, roomJoin: true, canPublish: true, canPublishData: true, canSubscribe: true, }; const { roomName } = input; const token = createToken({ identity, name: name as string }, grant); const result: TokenResult = { identity, accessToken: token, }; try { // check if user is already in room console.log("here"); const participant = await ctx.prisma.participant.findUnique({ where: { UserId_RoomName: { UserId: ctx.session.user.id, RoomName: roomName, }, }, }); if (participant === null) await ctx.prisma.participant.create({ data: { User: { connect: { id: ctx.session.user.id, }, }, Room: { connect: { name: roomName, }, }, }, }); } catch (error) { console.log(error); } return result; }), createRoom: protectedProcedure.mutation(async ({ ctx }) => { const identity = ctx.session.user.id; const name = ctx.session.user.name; const room = await ctx.prisma.room.create({ data: { Owner: { connect: { id: ctx.session.user.id, }, }, }, }); await roomClient.createRoom({ name: room.name, }); const grant: VideoGrant = { room: room.name, roomJoin: true, canPublish: true, canPublishData: true, canSubscribe: true, }; const token = createToken({ identity, name: name as string }, grant); const result = { roomName: room.name, }; return result; }), getRoomsByUser: protectedProcedure.query(async ({ ctx }) => { const rooms = await ctx.prisma.room.findMany({ where: { OR: [ { Owner: { id: ctx.session.user.id, }, }, { Participant: { some: { UserId: ctx.session.user.id, }, }, }, ], }, }); return rooms; }), getRoomSummary: protectedProcedure .input( z.object({ roomName: z.string(), }) ) .query(async ({ input, ctx }) => { // order all transcripts by createdAt in ascending order
const transcripts = await ctx.prisma.transcript.findMany({
where: { Room: { name: input.roomName, }, }, include: { User: true, }, orderBy: { createdAt: "asc", }, }); const chatLog = transcripts.map((transcript) => ({ speaker: transcript.User.name, utterance: transcript.text, timestamp: transcript.createdAt.toISOString(), })); if (chatLog.length === 0) { return null; } const apiKey = process.env.ONEAI_API_KEY; console.log(chatLog); try { const config = { method: "POST", url: "https://api.oneai.com/api/v0/pipeline", headers: { "api-key": apiKey, "Content-Type": "application/json", }, data: { input: chatLog, input_type: "conversation", content_type: "application/json", output_type: "json", multilingual: { enabled: true, }, steps: [ { skill: "article-topics", }, { skill: "numbers", }, { skill: "names", }, { skill: "emotions", }, { skill: "summarize", }, ], }, }; const res = await axios.request(config); console.log(res.status); return res.data; } catch (error) { console.log(error); } }), });
src/server/api/routers/rooms.ts
swasthikshetty10-hackoverflow-0b245c9
[ { "filename": "src/server/api/routers/pusher.ts", "retrieved_chunk": " .input(\n z.object({\n message: string(),\n roomName: string(),\n isFinal: z.boolean(),\n })\n )\n .mutation(async ({ input, ctx }) => {\n const { message } = input;\n const { user } = ctx.session;", "score": 46.388402908162575 }, { "filename": "src/server/api/routers/pusher.ts", "retrieved_chunk": " const { text } = await translate(message, {\n to: \"en\",\n });\n await ctx.prisma.transcript.create({\n data: {\n text: text,\n Room: {\n connect: {\n name: input.roomName,\n },", "score": 32.11819633088503 }, { "filename": "src/server/api/routers/pusher.ts", "retrieved_chunk": " const response = await pusher.trigger(\n input.roomName,\n \"transcribe-event\",\n {\n message,\n sender: user.name,\n isFinal: input.isFinal,\n senderId: user.id,\n }\n );", "score": 17.510532800914113 }, { "filename": "src/server/api/routers/pusher.ts", "retrieved_chunk": "import { string, z } from \"zod\";\nimport { pusher } from \"~/utils/pusher\";\nimport {\n createTRPCRouter,\n publicProcedure,\n protectedProcedure,\n} from \"~/server/api/trpc\";\nimport { translate } from \"@vitalets/google-translate-api\";\nexport const pusherRouter = createTRPCRouter({\n send: protectedProcedure", "score": 14.898118430191326 }, { "filename": "src/server/api/trpc.ts", "retrieved_chunk": " * If you want a query or mutation to ONLY be accessible to logged in users, use this. It verifies\n * the session is valid and guarantees `ctx.session.user` is not null.\n *\n * @see https://trpc.io/docs/procedures\n */\nexport const protectedProcedure = t.procedure.use(enforceUserIsAuthed);", "score": 14.754295730137354 } ]
typescript
const transcripts = await ctx.prisma.transcript.findMany({
/** * 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
swasthikshetty10-hackoverflow-0b245c9
[ { "filename": "src/server/api/root.ts", "retrieved_chunk": " pusher: pusherRouter,\n});\n// export type definition of API\nexport type AppRouter = typeof appRouter;", "score": 16.494634489987877 }, { "filename": "src/server/api/trpc.ts", "retrieved_chunk": " session: Session | null;\n};\n/**\n * This helper generates the \"internals\" for a tRPC context. If you need to use it, you can export\n * it from here.\n *\n * Examples of things you may need it for:\n * - testing, so we don't have to mock Next.js' req/res\n * - tRPC's `createSSGHelpers`, where we don't have req/res\n *", "score": 8.094275607944185 }, { "filename": "src/pages/rooms/[name].tsx", "retrieved_chunk": " )}\n </main>\n );\n};\nexport default Home;\ntype ActiveRoomProps = {\n userChoices: LocalUserChoices;\n roomName: string;\n region?: string;\n onLeave?: () => void;", "score": 7.263169754477904 }, { "filename": "src/server/auth.ts", "retrieved_chunk": "import { type GetServerSidePropsContext } from \"next\";\nimport {\n getServerSession,\n type NextAuthOptions,\n type DefaultSession,\n} from \"next-auth\";\nimport GoogleProvider from \"next-auth/providers/google\";\nimport { PrismaAdapter } from \"@next-auth/prisma-adapter\";\nimport { env } from \"~/env.mjs\";\nimport { prisma } from \"~/server/db\";", "score": 6.5270580006353125 }, { "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": 6.279007592053544 } ]
typescript
= inferRouterInputs<AppRouter>;
import { Body, Controller, Get, HttpCode, HttpStatus, Inject, NotFoundException, Param, Post, Req, Res, UnauthorizedException, } from '@nestjs/common'; import { ConfigType } from '@nestjs/config'; import { EventBus } from '@nestjs/cqrs'; import { JwtService } from '@nestjs/jwt'; import { ApiNoContentResponse, ApiOkResponse, ApiOperation, ApiTags, } from '@nestjs/swagger'; import { Request, Response } from 'express'; import iamConfig from '../configs/iam.config'; import { ActiveUser } from '../decorators/active-user.decorator'; import { Auth } from '../decorators/auth.decorator'; import { LoginRequestDto } from '../dtos/login-request.dto'; import { LoginResponseDto } from '../dtos/login-response.dto'; import { PasswordlessLoginRequestRequestDto } from '../dtos/passwordless-login-request-request.dto'; import { AuthType } from '../enums/auth-type.enum'; import { TokenType } from '../enums/token-type.enum'; import { LoggedInEvent } from '../events/logged-in.event'; import { LoggedOutEvent } from '../events/logged-out.event'; import { BcryptHasher } from '../hashers/bcrypt.hasher'; import { MODULE_OPTIONS_TOKEN } from '../iam.module-definition'; import { IActiveUser } from '../interfaces/active-user.interface'; import { IModuleOptions } from '../interfaces/module-options.interface'; import { IRefreshTokenJwtPayload } from '../interfaces/refresh-token-jwt-payload.interface'; import { LoginProcessor } from '../processors/login.processor'; import { LogoutProcessor } from '../processors/logout.processor'; import { PasswordlessLoginRequestProcessor } from '../processors/passwordless-login-request.processor'; @Controller() @ApiTags('Auth') export class AuthController { constructor( private readonly eventBus: EventBus, private readonly hasher: BcryptHasher, private readonly loginProcessor: LoginProcessor, private readonly logoutProcessor: LogoutProcessor, private readonly passwordlessLoginRequestProcessor: PasswordlessLoginRequestProcessor, private readonly jwtService: JwtService, @Inject(MODULE_OPTIONS_TOKEN) private readonly moduleOptions: IModuleOptions, @Inject(iamConfig.KEY) private readonly config: ConfigType<typeof iamConfig>, ) {} @HttpCode(HttpStatus.OK) @ApiOperation({ operationId: 'authLogin' }) @ApiOkResponse({ type: LoginResponseDto }) @Auth(AuthType.None) @Post('/auth/login') async login(
@Body() request: LoginRequestDto, @Res({ passthrough: true }) response: Response, ): Promise<LoginResponseDto> {
if (!this.config.auth.methods.includes('basic')) { throw new NotFoundException(); } try { const user = await this.moduleOptions.authService.checkUser( request.username, ); if (!(await this.hasher.compare(request.password, user.getPassword()))) { throw new UnauthorizedException(); } const login = await this.loginProcessor.process(user, response); this.eventBus.publish(new LoggedInEvent(user.getId())); return { accessToken: login.accessToken, refreshToken: login.refreshToken, }; } catch { throw new UnauthorizedException(); } } @HttpCode(HttpStatus.OK) @ApiOperation({ operationId: 'authPasswordlessLogin' }) @ApiOkResponse({ type: LoginResponseDto }) @Auth(AuthType.None) @Get('/auth/passwordless_login/:id') async passwordlessLogin( @Param('id') tokenId: string, @Req() request: Request, @Res({ passthrough: true }) response: Response, ): Promise<LoginResponseDto> { if (!this.config.auth.methods.includes('passwordless')) { throw new NotFoundException(); } const requestId = request.cookies[TokenType.PasswordlessLoginToken]; if (!requestId) { throw new UnauthorizedException(); } try { const token = await this.moduleOptions.authService.checkToken( tokenId, TokenType.PasswordlessLoginToken, requestId, ); const user = await this.moduleOptions.authService.getUser( token.getUserId(), ); await this.moduleOptions.authService.checkUser(user.getUsername()); await this.moduleOptions.authService.removeToken(tokenId); const login = await this.loginProcessor.process(user, response); return { accessToken: login.accessToken, refreshToken: login.refreshToken, }; } catch { throw new UnauthorizedException(); } } @HttpCode(HttpStatus.NO_CONTENT) @ApiOperation({ operationId: 'authPasswordlessLoginRequest' }) @ApiNoContentResponse() @Auth(AuthType.None) @Post('/auth/passwordless_login') async passwordlessLoginRequest( @Body() request: PasswordlessLoginRequestRequestDto, @Res({ passthrough: true }) response: Response, ): Promise<void> { if (!this.config.auth.methods.includes('passwordless')) { throw new NotFoundException(); } try { const user = await this.moduleOptions.authService.checkUser( request.username, ); await this.passwordlessLoginRequestProcessor.process(user, response); } catch {} } @HttpCode(HttpStatus.OK) @ApiOperation({ operationId: 'authRefreshTokens' }) @ApiOkResponse({ type: LoginResponseDto }) @Auth(AuthType.None) @Get('/auth/refresh_tokens') async refreshTokens( @Req() request: Request, @Res({ passthrough: true }) response: Response, ): Promise<LoginResponseDto> { try { const refreshTokenJwtPayload: IRefreshTokenJwtPayload = await this.jwtService.verifyAsync( request.cookies[TokenType.RefreshToken], ); await this.moduleOptions.authService.checkToken( refreshTokenJwtPayload.id, TokenType.RefreshToken, ); const user = await this.moduleOptions.authService.getUser( refreshTokenJwtPayload.sub, ); await this.moduleOptions.authService.checkUser(user.getUsername()); await this.moduleOptions.authService.removeToken( refreshTokenJwtPayload.id, ); const login = await this.loginProcessor.process(user, response); return { accessToken: login.accessToken, refreshToken: login.refreshToken, }; } catch { throw new UnauthorizedException(); } } @HttpCode(HttpStatus.NO_CONTENT) @ApiOperation({ operationId: 'authLogout' }) @ApiNoContentResponse() @Auth(AuthType.None) @Get('/auth/logout') async logout( @Req() request: Request, @Res({ passthrough: true }) response: Response, @ActiveUser() activeUser: IActiveUser, ) { await this.logoutProcessor.process(request, response); if (!activeUser) { return; } this.eventBus.publish(new LoggedOutEvent(activeUser.userId)); } }
src/controllers/auth.controller.ts
fastnloud-nest-iam-463230d
[ { "filename": "src/decorators/auth.decorator.ts", "retrieved_chunk": "import { SetMetadata } from '@nestjs/common';\nimport { IAM_AUTH_TYPE_KEY } from '../constants/iam.constants';\nimport { AuthType } from '../enums/auth-type.enum';\nexport const Auth = (...authTypes: AuthType[]) =>\n SetMetadata(IAM_AUTH_TYPE_KEY, authTypes);", "score": 11.153951066401191 }, { "filename": "src/processors/login.processor.ts", "retrieved_chunk": " private readonly config: ConfigType<typeof iamConfig>,\n ) {}\n public async process(user: IUser, response: Response): Promise<ILogin> {\n const accessToken = await this.accessTokenGenerator.generate(user);\n const refreshToken = await this.refreshTokenGenerator.generate(user);\n const login = {\n accessToken: accessToken.jwt,\n refreshToken: refreshToken.jwt,\n };\n await this.moduleOptions.authService.saveToken(", "score": 10.274993769594374 }, { "filename": "src/enums/auth-type.enum.ts", "retrieved_chunk": "export enum AuthType {\n AccessToken,\n None,\n}", "score": 9.780300348009533 }, { "filename": "src/dtos/login-response.dto.ts", "retrieved_chunk": "import { ApiProperty } from '@nestjs/swagger';\nexport class LoginResponseDto {\n @ApiProperty()\n public readonly accessToken: string;\n @ApiProperty()\n public readonly refreshToken: string;\n}", "score": 9.494117414408711 }, { "filename": "src/processors/logout.processor.ts", "retrieved_chunk": "export class LogoutProcessor {\n public constructor(\n private readonly jwtService: JwtService,\n @Inject(MODULE_OPTIONS_TOKEN)\n private readonly moduleOptions: IModuleOptions,\n @Inject(iamConfig.KEY)\n private readonly config: ConfigType<typeof iamConfig>,\n ) {}\n public async process(request: Request, response: Response): Promise<void> {\n try {", "score": 9.270901570343838 } ]
typescript
@Body() request: LoginRequestDto, @Res({ passthrough: true }) response: Response, ): Promise<LoginResponseDto> {
import { Body, Controller, Get, HttpCode, HttpStatus, Inject, NotFoundException, Param, Post, Req, Res, UnauthorizedException, } from '@nestjs/common'; import { ConfigType } from '@nestjs/config'; import { EventBus } from '@nestjs/cqrs'; import { JwtService } from '@nestjs/jwt'; import { ApiNoContentResponse, ApiOkResponse, ApiOperation, ApiTags, } from '@nestjs/swagger'; import { Request, Response } from 'express'; import iamConfig from '../configs/iam.config'; import { ActiveUser } from '../decorators/active-user.decorator'; import { Auth } from '../decorators/auth.decorator'; import { LoginRequestDto } from '../dtos/login-request.dto'; import { LoginResponseDto } from '../dtos/login-response.dto'; import { PasswordlessLoginRequestRequestDto } from '../dtos/passwordless-login-request-request.dto'; import { AuthType } from '../enums/auth-type.enum'; import { TokenType } from '../enums/token-type.enum'; import { LoggedInEvent } from '../events/logged-in.event'; import { LoggedOutEvent } from '../events/logged-out.event'; import { BcryptHasher } from '../hashers/bcrypt.hasher'; import { MODULE_OPTIONS_TOKEN } from '../iam.module-definition'; import { IActiveUser } from '../interfaces/active-user.interface'; import { IModuleOptions } from '../interfaces/module-options.interface'; import { IRefreshTokenJwtPayload } from '../interfaces/refresh-token-jwt-payload.interface'; import { LoginProcessor } from '../processors/login.processor'; import { LogoutProcessor } from '../processors/logout.processor'; import { PasswordlessLoginRequestProcessor } from '../processors/passwordless-login-request.processor'; @Controller() @ApiTags('Auth') export class AuthController { constructor( private readonly eventBus: EventBus, private readonly hasher: BcryptHasher, private readonly loginProcessor: LoginProcessor, private readonly logoutProcessor: LogoutProcessor, private readonly passwordlessLoginRequestProcessor: PasswordlessLoginRequestProcessor, private readonly jwtService: JwtService, @Inject(MODULE_OPTIONS_TOKEN) private readonly moduleOptions: IModuleOptions, @Inject(iamConfig.KEY) private readonly config: ConfigType<typeof iamConfig>, ) {} @HttpCode(HttpStatus.OK) @ApiOperation({ operationId: 'authLogin' }) @ApiOkResponse({ type: LoginResponseDto }) @Auth(AuthType.None) @Post('/auth/login') async login( @Body() request: LoginRequestDto, @Res({ passthrough: true }) response: Response, ): Promise<LoginResponseDto> { if (!this.config.auth.methods.includes('basic')) { throw new NotFoundException(); } try { const user = await this.moduleOptions.authService.checkUser( request.username, ); if (!(await this.hasher.compare(request.password, user.getPassword()))) { throw new UnauthorizedException(); } const login = await this.loginProcessor.process(user, response); this.eventBus.publish(new LoggedInEvent(user.getId())); return { accessToken: login.accessToken, refreshToken: login.refreshToken, }; } catch { throw new UnauthorizedException(); } } @HttpCode(HttpStatus.OK) @ApiOperation({ operationId: 'authPasswordlessLogin' }) @ApiOkResponse({ type: LoginResponseDto }) @Auth(AuthType.None) @Get('/auth/passwordless_login/:id') async passwordlessLogin( @Param('id') tokenId: string, @Req() request: Request, @Res({ passthrough: true }) response: Response, ): Promise<LoginResponseDto> { if (!this.config.auth.methods.includes('passwordless')) { throw new NotFoundException(); } const requestId = request.cookies[
TokenType.PasswordlessLoginToken];
if (!requestId) { throw new UnauthorizedException(); } try { const token = await this.moduleOptions.authService.checkToken( tokenId, TokenType.PasswordlessLoginToken, requestId, ); const user = await this.moduleOptions.authService.getUser( token.getUserId(), ); await this.moduleOptions.authService.checkUser(user.getUsername()); await this.moduleOptions.authService.removeToken(tokenId); const login = await this.loginProcessor.process(user, response); return { accessToken: login.accessToken, refreshToken: login.refreshToken, }; } catch { throw new UnauthorizedException(); } } @HttpCode(HttpStatus.NO_CONTENT) @ApiOperation({ operationId: 'authPasswordlessLoginRequest' }) @ApiNoContentResponse() @Auth(AuthType.None) @Post('/auth/passwordless_login') async passwordlessLoginRequest( @Body() request: PasswordlessLoginRequestRequestDto, @Res({ passthrough: true }) response: Response, ): Promise<void> { if (!this.config.auth.methods.includes('passwordless')) { throw new NotFoundException(); } try { const user = await this.moduleOptions.authService.checkUser( request.username, ); await this.passwordlessLoginRequestProcessor.process(user, response); } catch {} } @HttpCode(HttpStatus.OK) @ApiOperation({ operationId: 'authRefreshTokens' }) @ApiOkResponse({ type: LoginResponseDto }) @Auth(AuthType.None) @Get('/auth/refresh_tokens') async refreshTokens( @Req() request: Request, @Res({ passthrough: true }) response: Response, ): Promise<LoginResponseDto> { try { const refreshTokenJwtPayload: IRefreshTokenJwtPayload = await this.jwtService.verifyAsync( request.cookies[TokenType.RefreshToken], ); await this.moduleOptions.authService.checkToken( refreshTokenJwtPayload.id, TokenType.RefreshToken, ); const user = await this.moduleOptions.authService.getUser( refreshTokenJwtPayload.sub, ); await this.moduleOptions.authService.checkUser(user.getUsername()); await this.moduleOptions.authService.removeToken( refreshTokenJwtPayload.id, ); const login = await this.loginProcessor.process(user, response); return { accessToken: login.accessToken, refreshToken: login.refreshToken, }; } catch { throw new UnauthorizedException(); } } @HttpCode(HttpStatus.NO_CONTENT) @ApiOperation({ operationId: 'authLogout' }) @ApiNoContentResponse() @Auth(AuthType.None) @Get('/auth/logout') async logout( @Req() request: Request, @Res({ passthrough: true }) response: Response, @ActiveUser() activeUser: IActiveUser, ) { await this.logoutProcessor.process(request, response); if (!activeUser) { return; } this.eventBus.publish(new LoggedOutEvent(activeUser.userId)); } }
src/controllers/auth.controller.ts
fastnloud-nest-iam-463230d
[ { "filename": "src/processors/logout.processor.ts", "retrieved_chunk": " const refreshTokenJwtPayload: IRefreshTokenJwtPayload =\n await this.jwtService.verifyAsync(\n request.cookies[TokenType.RefreshToken],\n );\n await this.moduleOptions.authService.removeToken(\n refreshTokenJwtPayload.id,\n );\n } catch {}\n response.clearCookie(TokenType.AccessToken);\n response.clearCookie(TokenType.RefreshToken, {", "score": 18.17797330587699 }, { "filename": "src/generators/passwordless-login-token.generator.ts", "retrieved_chunk": " constructor(\n @Inject(iamConfig.KEY)\n private readonly config: ConfigType<typeof iamConfig>,\n ) {}\n async generate(user: IUser, requestId: string): Promise<IToken> {\n const id = randomUUID();\n const ttl = this.config.auth.passwordless.tokenTtl;\n const expiresAt = new Date();\n expiresAt.setSeconds(expiresAt.getSeconds() + ttl);\n return new TokenModel(", "score": 16.317378553928677 }, { "filename": "src/guards/access-token.guard.ts", "retrieved_chunk": " );\n const activeUser: IActiveUser = {\n userId: accessTokenJwtPayload.sub,\n roles: accessTokenJwtPayload.roles,\n };\n request[IAM_REQUEST_USER_KEY] = activeUser;\n } catch {\n throw new UnauthorizedException();\n }\n return true;", "score": 16.161604210295486 }, { "filename": "src/guards/auth.guard.ts", "retrieved_chunk": " const guards = authTypes.map((type) => this.authTypeGuardMap[type]).flat();\n for (const guard of guards) {\n if (await Promise.resolve(guard.canActivate(context))) {\n return true;\n }\n }\n throw new UnauthorizedException();\n }\n}", "score": 15.94224447344438 }, { "filename": "src/processors/logout.processor.ts", "retrieved_chunk": "export class LogoutProcessor {\n public constructor(\n private readonly jwtService: JwtService,\n @Inject(MODULE_OPTIONS_TOKEN)\n private readonly moduleOptions: IModuleOptions,\n @Inject(iamConfig.KEY)\n private readonly config: ConfigType<typeof iamConfig>,\n ) {}\n public async process(request: Request, response: Response): Promise<void> {\n try {", "score": 15.224270409991274 } ]
typescript
TokenType.PasswordlessLoginToken];
import { Body, Controller, Get, HttpCode, HttpStatus, Inject, NotFoundException, Param, Post, Req, Res, UnauthorizedException, } from '@nestjs/common'; import { ConfigType } from '@nestjs/config'; import { EventBus } from '@nestjs/cqrs'; import { JwtService } from '@nestjs/jwt'; import { ApiNoContentResponse, ApiOkResponse, ApiOperation, ApiTags, } from '@nestjs/swagger'; import { Request, Response } from 'express'; import iamConfig from '../configs/iam.config'; import { ActiveUser } from '../decorators/active-user.decorator'; import { Auth } from '../decorators/auth.decorator'; import { LoginRequestDto } from '../dtos/login-request.dto'; import { LoginResponseDto } from '../dtos/login-response.dto'; import { PasswordlessLoginRequestRequestDto } from '../dtos/passwordless-login-request-request.dto'; import { AuthType } from '../enums/auth-type.enum'; import { TokenType } from '../enums/token-type.enum'; import { LoggedInEvent } from '../events/logged-in.event'; import { LoggedOutEvent } from '../events/logged-out.event'; import { BcryptHasher } from '../hashers/bcrypt.hasher'; import { MODULE_OPTIONS_TOKEN } from '../iam.module-definition'; import { IActiveUser } from '../interfaces/active-user.interface'; import { IModuleOptions } from '../interfaces/module-options.interface'; import { IRefreshTokenJwtPayload } from '../interfaces/refresh-token-jwt-payload.interface'; import { LoginProcessor } from '../processors/login.processor'; import { LogoutProcessor } from '../processors/logout.processor'; import { PasswordlessLoginRequestProcessor } from '../processors/passwordless-login-request.processor'; @Controller() @ApiTags('Auth') export class AuthController { constructor( private readonly eventBus: EventBus, private readonly hasher: BcryptHasher, private readonly loginProcessor: LoginProcessor, private readonly logoutProcessor: LogoutProcessor, private readonly passwordlessLoginRequestProcessor: PasswordlessLoginRequestProcessor, private readonly jwtService: JwtService, @Inject(MODULE_OPTIONS_TOKEN) private readonly moduleOptions: IModuleOptions, @Inject(iamConfig.KEY) private readonly config: ConfigType<typeof iamConfig>, ) {} @HttpCode(HttpStatus.OK) @ApiOperation({ operationId: 'authLogin' }) @ApiOkResponse({ type: LoginResponseDto }) @Auth(AuthType.None) @Post('/auth/login') async login( @Body() request: LoginRequestDto, @Res({ passthrough: true }) response: Response, ): Promise<LoginResponseDto> { if (!this.config.auth.methods.includes('basic')) { throw new NotFoundException(); } try { const user = await this.moduleOptions.authService.checkUser( request.username, ); if (!(await this.hasher.compare(request.password, user.getPassword()))) { throw new UnauthorizedException(); } const login = await this.loginProcessor.process(user, response);
this.eventBus.publish(new LoggedInEvent(user.getId()));
return { accessToken: login.accessToken, refreshToken: login.refreshToken, }; } catch { throw new UnauthorizedException(); } } @HttpCode(HttpStatus.OK) @ApiOperation({ operationId: 'authPasswordlessLogin' }) @ApiOkResponse({ type: LoginResponseDto }) @Auth(AuthType.None) @Get('/auth/passwordless_login/:id') async passwordlessLogin( @Param('id') tokenId: string, @Req() request: Request, @Res({ passthrough: true }) response: Response, ): Promise<LoginResponseDto> { if (!this.config.auth.methods.includes('passwordless')) { throw new NotFoundException(); } const requestId = request.cookies[TokenType.PasswordlessLoginToken]; if (!requestId) { throw new UnauthorizedException(); } try { const token = await this.moduleOptions.authService.checkToken( tokenId, TokenType.PasswordlessLoginToken, requestId, ); const user = await this.moduleOptions.authService.getUser( token.getUserId(), ); await this.moduleOptions.authService.checkUser(user.getUsername()); await this.moduleOptions.authService.removeToken(tokenId); const login = await this.loginProcessor.process(user, response); return { accessToken: login.accessToken, refreshToken: login.refreshToken, }; } catch { throw new UnauthorizedException(); } } @HttpCode(HttpStatus.NO_CONTENT) @ApiOperation({ operationId: 'authPasswordlessLoginRequest' }) @ApiNoContentResponse() @Auth(AuthType.None) @Post('/auth/passwordless_login') async passwordlessLoginRequest( @Body() request: PasswordlessLoginRequestRequestDto, @Res({ passthrough: true }) response: Response, ): Promise<void> { if (!this.config.auth.methods.includes('passwordless')) { throw new NotFoundException(); } try { const user = await this.moduleOptions.authService.checkUser( request.username, ); await this.passwordlessLoginRequestProcessor.process(user, response); } catch {} } @HttpCode(HttpStatus.OK) @ApiOperation({ operationId: 'authRefreshTokens' }) @ApiOkResponse({ type: LoginResponseDto }) @Auth(AuthType.None) @Get('/auth/refresh_tokens') async refreshTokens( @Req() request: Request, @Res({ passthrough: true }) response: Response, ): Promise<LoginResponseDto> { try { const refreshTokenJwtPayload: IRefreshTokenJwtPayload = await this.jwtService.verifyAsync( request.cookies[TokenType.RefreshToken], ); await this.moduleOptions.authService.checkToken( refreshTokenJwtPayload.id, TokenType.RefreshToken, ); const user = await this.moduleOptions.authService.getUser( refreshTokenJwtPayload.sub, ); await this.moduleOptions.authService.checkUser(user.getUsername()); await this.moduleOptions.authService.removeToken( refreshTokenJwtPayload.id, ); const login = await this.loginProcessor.process(user, response); return { accessToken: login.accessToken, refreshToken: login.refreshToken, }; } catch { throw new UnauthorizedException(); } } @HttpCode(HttpStatus.NO_CONTENT) @ApiOperation({ operationId: 'authLogout' }) @ApiNoContentResponse() @Auth(AuthType.None) @Get('/auth/logout') async logout( @Req() request: Request, @Res({ passthrough: true }) response: Response, @ActiveUser() activeUser: IActiveUser, ) { await this.logoutProcessor.process(request, response); if (!activeUser) { return; } this.eventBus.publish(new LoggedOutEvent(activeUser.userId)); } }
src/controllers/auth.controller.ts
fastnloud-nest-iam-463230d
[ { "filename": "src/processors/login.processor.ts", "retrieved_chunk": " private readonly config: ConfigType<typeof iamConfig>,\n ) {}\n public async process(user: IUser, response: Response): Promise<ILogin> {\n const accessToken = await this.accessTokenGenerator.generate(user);\n const refreshToken = await this.refreshTokenGenerator.generate(user);\n const login = {\n accessToken: accessToken.jwt,\n refreshToken: refreshToken.jwt,\n };\n await this.moduleOptions.authService.saveToken(", "score": 34.34014172220062 }, { "filename": "src/processors/logout.processor.ts", "retrieved_chunk": " const refreshTokenJwtPayload: IRefreshTokenJwtPayload =\n await this.jwtService.verifyAsync(\n request.cookies[TokenType.RefreshToken],\n );\n await this.moduleOptions.authService.removeToken(\n refreshTokenJwtPayload.id,\n );\n } catch {}\n response.clearCookie(TokenType.AccessToken);\n response.clearCookie(TokenType.RefreshToken, {", "score": 30.37250098763788 }, { "filename": "src/guards/auth.guard.ts", "retrieved_chunk": " const guards = authTypes.map((type) => this.authTypeGuardMap[type]).flat();\n for (const guard of guards) {\n if (await Promise.resolve(guard.canActivate(context))) {\n return true;\n }\n }\n throw new UnauthorizedException();\n }\n}", "score": 27.64283064416322 }, { "filename": "src/processors/passwordless-login-request.processor.ts", "retrieved_chunk": " const requestId = randomUUID();\n const passwordlessLoginToken =\n await this.passwordlessLoginTokenGenerator.generate(user, requestId);\n await this.moduleOptions.authService.saveToken(passwordlessLoginToken);\n response.cookie(TokenType.PasswordlessLoginToken, requestId, {\n secure: this.config.cookie.secure,\n httpOnly: this.config.cookie.httpOnly,\n sameSite: this.config.cookie.sameSite,\n expires: passwordlessLoginToken.getExpiresAt(),\n path: `${this.config.routePathPrefix}/auth`,", "score": 26.85170833586864 }, { "filename": "src/generators/refresh-token.generator.ts", "retrieved_chunk": " return {\n id,\n jwt: await this.jwtService.signAsync(\n {\n id,\n sub: user.getId(),\n username: user.getUsername(),\n roles: user.getRoles(),\n } as IRefreshTokenJwtPayload,\n {", "score": 24.51275233763202 } ]
typescript
this.eventBus.publish(new LoggedInEvent(user.getId()));
import { type GetServerSidePropsContext } from "next"; import { getServerSession, type NextAuthOptions, type DefaultSession, } from "next-auth"; import GoogleProvider from "next-auth/providers/google"; 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: [ GoogleProvider({ clientId: env.GOOGLE_CLIENT_ID,
clientSecret: env.GOOGLE_CLIENT_SECRET, }), ], };
/** * 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
swasthikshetty10-hackoverflow-0b245c9
[ { "filename": "src/server/db.ts", "retrieved_chunk": "import { PrismaClient } from \"@prisma/client\";\nimport { env } from \"~/env.mjs\";\nconst globalForPrisma = globalThis as unknown as { prisma: PrismaClient };\nexport const prisma =\n globalForPrisma.prisma ||\n new PrismaClient({\n log:\n env.NODE_ENV === \"development\" ? [\"query\", \"error\", \"warn\"] : [\"error\"],\n });\nif (env.NODE_ENV !== \"production\") globalForPrisma.prisma = prisma;", "score": 15.065588776912378 }, { "filename": "src/utils/pusher.ts", "retrieved_chunk": "import Pusher from \"pusher\";\nexport const pusher = new Pusher({\n appId: process.env.PUSHER_APP_ID as string,\n key: process.env.PUSHER_KEY as string,\n secret: process.env.PUSHER_SECRET as string,\n cluster: process.env.PUSHER_CLUSTER as string,\n useTLS: true,\n});", "score": 9.613925500746863 }, { "filename": "src/server/api/routers/rooms.ts", "retrieved_chunk": " at.ttl = \"5m\";\n at.addGrant(grant);\n return at.toJwt();\n};\nimport axios from \"axios\";\nconst apiKey = process.env.LIVEKIT_API_KEY;\nconst apiSecret = process.env.LIVEKIT_API_SECRET;\nconst apiHost = process.env.NEXT_PUBLIC_LIVEKIT_API_HOST as string;\nimport {\n createTRPCRouter,", "score": 8.961306020773232 }, { "filename": "src/pages/api/trpc/[trpc].ts", "retrieved_chunk": "import { createNextApiHandler } from \"@trpc/server/adapters/next\";\nimport { env } from \"~/env.mjs\";\nimport { createTRPCContext } from \"~/server/api/trpc\";\nimport { appRouter } from \"~/server/api/root\";\n// export API handler\nexport default createNextApiHandler({\n router: appRouter,\n createContext: createTRPCContext,\n onError:\n env.NODE_ENV === \"development\"", "score": 8.538635324954877 }, { "filename": "src/pages/rooms/[name].tsx", "retrieved_chunk": " >([]);\n useTranscribe({\n roomName,\n audioEnabled: userChoices.audioEnabled,\n languageCode: selectedLanguage,\n });\n useEffect(() => {\n const pusher = new Pusher(process.env.NEXT_PUBLIC_PUSHER_KEY as string, {\n cluster: process.env.NEXT_PUBLIC_PUSHER_CLUSTER as string,\n });", "score": 8.442004511749978 } ]
typescript
clientSecret: env.GOOGLE_CLIENT_SECRET, }), ], };
import { Body, Controller, Get, HttpCode, HttpStatus, Inject, NotFoundException, Param, Post, Req, Res, UnauthorizedException, } from '@nestjs/common'; import { ConfigType } from '@nestjs/config'; import { EventBus } from '@nestjs/cqrs'; import { JwtService } from '@nestjs/jwt'; import { ApiNoContentResponse, ApiOkResponse, ApiOperation, ApiTags, } from '@nestjs/swagger'; import { Request, Response } from 'express'; import iamConfig from '../configs/iam.config'; import { ActiveUser } from '../decorators/active-user.decorator'; import { Auth } from '../decorators/auth.decorator'; import { LoginRequestDto } from '../dtos/login-request.dto'; import { LoginResponseDto } from '../dtos/login-response.dto'; import { PasswordlessLoginRequestRequestDto } from '../dtos/passwordless-login-request-request.dto'; import { AuthType } from '../enums/auth-type.enum'; import { TokenType } from '../enums/token-type.enum'; import { LoggedInEvent } from '../events/logged-in.event'; import { LoggedOutEvent } from '../events/logged-out.event'; import { BcryptHasher } from '../hashers/bcrypt.hasher'; import { MODULE_OPTIONS_TOKEN } from '../iam.module-definition'; import { IActiveUser } from '../interfaces/active-user.interface'; import { IModuleOptions } from '../interfaces/module-options.interface'; import { IRefreshTokenJwtPayload } from '../interfaces/refresh-token-jwt-payload.interface'; import { LoginProcessor } from '../processors/login.processor'; import { LogoutProcessor } from '../processors/logout.processor'; import { PasswordlessLoginRequestProcessor } from '../processors/passwordless-login-request.processor'; @Controller() @ApiTags('Auth') export class AuthController { constructor( private readonly eventBus: EventBus, private readonly hasher: BcryptHasher, private readonly loginProcessor: LoginProcessor, private readonly logoutProcessor: LogoutProcessor, private readonly passwordlessLoginRequestProcessor: PasswordlessLoginRequestProcessor, private readonly jwtService: JwtService, @Inject(MODULE_OPTIONS_TOKEN) private readonly moduleOptions: IModuleOptions, @Inject(iamConfig.KEY) private readonly config: ConfigType<typeof iamConfig>, ) {} @HttpCode(HttpStatus.OK) @ApiOperation({ operationId: 'authLogin' }) @ApiOkResponse({ type: LoginResponseDto }) @Auth(AuthType.None) @Post('/auth/login') async login( @Body() request: LoginRequestDto, @Res({ passthrough: true }) response: Response, ): Promise<LoginResponseDto> { if (!this.config.auth.methods.includes('basic')) { throw new NotFoundException(); } try { const user = await this.moduleOptions.authService.checkUser( request.username, ); if (!(await this.hasher.compare(request.password, user.getPassword()))) { throw new UnauthorizedException(); } const login = await this.loginProcessor.process(user, response); this.eventBus.publish(new LoggedInEvent(user.getId())); return { accessToken: login.accessToken, refreshToken: login.refreshToken, }; } catch { throw new UnauthorizedException(); } } @HttpCode(HttpStatus.OK) @ApiOperation({ operationId: 'authPasswordlessLogin' }) @ApiOkResponse({ type: LoginResponseDto }) @Auth(AuthType.None) @Get('/auth/passwordless_login/:id') async passwordlessLogin( @Param('id') tokenId: string, @Req() request: Request, @Res({ passthrough: true }) response: Response, ): Promise<LoginResponseDto> { if (!this.config.auth.methods.includes('passwordless')) { throw new NotFoundException(); } const requestId = request.cookies[TokenType.PasswordlessLoginToken]; if (!requestId) { throw new UnauthorizedException(); } try { const token = await this.moduleOptions.authService.checkToken( tokenId, TokenType.PasswordlessLoginToken, requestId, ); const user = await this.moduleOptions.authService.getUser( token.getUserId(), ); await this.moduleOptions.authService.checkUser(user.getUsername()); await this.moduleOptions.authService.removeToken(tokenId); const login = await this.loginProcessor.process(user, response); return { accessToken: login.accessToken, refreshToken: login.refreshToken, }; } catch { throw new UnauthorizedException(); } } @HttpCode(HttpStatus.NO_CONTENT) @ApiOperation({ operationId: 'authPasswordlessLoginRequest' }) @ApiNoContentResponse() @Auth(AuthType.None) @Post('/auth/passwordless_login') async passwordlessLoginRequest( @Body() request: PasswordlessLoginRequestRequestDto, @Res({ passthrough: true }) response: Response, ): Promise<void> { if (!this.config.auth.methods.includes('passwordless')) { throw new NotFoundException(); } try { const user = await this.moduleOptions.authService.checkUser( request.username, ); await this.passwordlessLoginRequestProcessor.process(user, response); } catch {} } @HttpCode(HttpStatus.OK) @ApiOperation({ operationId: 'authRefreshTokens' }) @ApiOkResponse({ type: LoginResponseDto }) @Auth(AuthType.None) @Get('/auth/refresh_tokens') async refreshTokens( @Req() request: Request, @Res({ passthrough: true }) response: Response, ): Promise<LoginResponseDto> { try { const refreshTokenJwtPayload: IRefreshTokenJwtPayload = await this.jwtService.verifyAsync( request.cookies[TokenType.RefreshToken], ); await this.moduleOptions.authService.checkToken( refreshTokenJwtPayload.id, TokenType.RefreshToken, ); const user = await this.moduleOptions.authService.getUser( refreshTokenJwtPayload.sub, ); await this.moduleOptions.authService.checkUser(user.getUsername()); await this.moduleOptions.authService.removeToken( refreshTokenJwtPayload.id, ); const login = await this.loginProcessor.process(user, response); return { accessToken: login.accessToken, refreshToken: login.refreshToken, }; } catch { throw new UnauthorizedException(); } } @HttpCode(HttpStatus.NO_CONTENT) @ApiOperation({ operationId: 'authLogout' }) @ApiNoContentResponse() @Auth(AuthType.None) @Get('/auth/logout') async logout( @Req() request: Request, @Res({ passthrough: true }) response: Response, @ActiveUser() activeUser: IActiveUser, ) { await this.logoutProcessor.process(request, response); if (!activeUser) { return; } this.eventBus.
publish(new LoggedOutEvent(activeUser.userId));
} }
src/controllers/auth.controller.ts
fastnloud-nest-iam-463230d
[ { "filename": "src/guards/access-token.guard.ts", "retrieved_chunk": " );\n const activeUser: IActiveUser = {\n userId: accessTokenJwtPayload.sub,\n roles: accessTokenJwtPayload.roles,\n };\n request[IAM_REQUEST_USER_KEY] = activeUser;\n } catch {\n throw new UnauthorizedException();\n }\n return true;", "score": 33.547916761787114 }, { "filename": "src/guards/none.guard.ts", "retrieved_chunk": " request[IAM_REQUEST_USER_KEY] = activeUser;\n } catch {\n return true;\n }\n return true;\n }\n}", "score": 28.49914338904795 }, { "filename": "src/guards/none.guard.ts", "retrieved_chunk": " const request = context.switchToHttp().getRequest();\n const accessToken: string | undefined =\n request.cookies[TokenType.AccessToken];\n try {\n const accessTokenJwtPayload: IAccessTokenJwtPayload =\n await this.jwtService.verifyAsync(accessToken);\n const activeUser: IActiveUser = {\n userId: accessTokenJwtPayload.sub,\n roles: accessTokenJwtPayload.roles,\n };", "score": 23.243743409485774 }, { "filename": "src/processors/logout.processor.ts", "retrieved_chunk": " const refreshTokenJwtPayload: IRefreshTokenJwtPayload =\n await this.jwtService.verifyAsync(\n request.cookies[TokenType.RefreshToken],\n );\n await this.moduleOptions.authService.removeToken(\n refreshTokenJwtPayload.id,\n );\n } catch {}\n response.clearCookie(TokenType.AccessToken);\n response.clearCookie(TokenType.RefreshToken, {", "score": 17.282677114674286 }, { "filename": "src/processors/logout.processor.ts", "retrieved_chunk": "export class LogoutProcessor {\n public constructor(\n private readonly jwtService: JwtService,\n @Inject(MODULE_OPTIONS_TOKEN)\n private readonly moduleOptions: IModuleOptions,\n @Inject(iamConfig.KEY)\n private readonly config: ConfigType<typeof iamConfig>,\n ) {}\n public async process(request: Request, response: Response): Promise<void> {\n try {", "score": 15.811920294185931 } ]
typescript
publish(new LoggedOutEvent(activeUser.userId));
import { Module } from '@nestjs/common'; import { ConfigModule, ConfigService } from '@nestjs/config'; import { APP_GUARD } from '@nestjs/core'; import { CqrsModule } from '@nestjs/cqrs'; import { JwtModule } from '@nestjs/jwt'; import iamConfig from './configs/iam.config'; import { AuthController } from './controllers/auth.controller'; import { AccessTokenGenerator } from './generators/access-token.generator'; import { PasswordlessLoginTokenGenerator } from './generators/passwordless-login-token.generator'; import { RefreshTokenGenerator } from './generators/refresh-token.generator'; import { AccessTokenGuard } from './guards/access-token.guard'; import { AuthGuard } from './guards/auth.guard'; import { NoneGuard } from './guards/none.guard'; import { RolesGuard } from './guards/roles.guard'; import { BcryptHasher } from './hashers/bcrypt.hasher'; import { ConfigurableModuleClass } from './iam.module-definition'; import { LoginProcessor } from './processors/login.processor'; import { LogoutProcessor } from './processors/logout.processor'; import { PasswordlessLoginRequestProcessor } from './processors/passwordless-login-request.processor'; @Module({ imports: [ ConfigModule.forFeature(iamConfig), CqrsModule, JwtModule.registerAsync({ imports: [ConfigModule], useFactory: async (config: ConfigService) => ({ secret: config.get('iam.jwt.secret'), signOptions: { audience: config.get('iam.jwt.audience'), issuer: config.get('iam.jwt.issuer'), }, }), inject: [ConfigService], }), ], providers: [ AccessTokenGenerator, AccessTokenGuard, AuthGuard, BcryptHasher, LoginProcessor, LogoutProcessor, NoneGuard, PasswordlessLoginRequestProcessor, PasswordlessLoginTokenGenerator, RefreshTokenGenerator, RolesGuard, { provide: APP_GUARD, useClass: AuthGuard, }, { provide: APP_GUARD, useClass: RolesGuard, }, ], exports: [BcryptHasher, LoginProcessor], controllers
: [AuthController], }) export class IamModule extends ConfigurableModuleClass {}
src/iam.module.ts
fastnloud-nest-iam-463230d
[ { "filename": "src/controllers/auth.controller.ts", "retrieved_chunk": "import { LogoutProcessor } from '../processors/logout.processor';\nimport { PasswordlessLoginRequestProcessor } from '../processors/passwordless-login-request.processor';\n@Controller()\n@ApiTags('Auth')\nexport class AuthController {\n constructor(\n private readonly eventBus: EventBus,\n private readonly hasher: BcryptHasher,\n private readonly loginProcessor: LoginProcessor,\n private readonly logoutProcessor: LogoutProcessor,", "score": 10.542104056448201 }, { "filename": "src/guards/roles.guard.ts", "retrieved_chunk": "import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';\nimport { Reflector } from '@nestjs/core';\nimport { Observable } from 'rxjs';\nimport {\n IAM_REQUEST_USER_KEY,\n IAM_ROLES_KEY,\n} from '../constants/iam.constants';\nimport { IActiveUser } from '../interfaces/active-user.interface';\n@Injectable()\nexport class RolesGuard implements CanActivate {", "score": 5.2994371434709056 }, { "filename": "src/iam.module-definition.ts", "retrieved_chunk": "import { ConfigurableModuleBuilder } from '@nestjs/common';\nimport { IModuleOptions } from './interfaces/module-options.interface';\nexport const { ConfigurableModuleClass, MODULE_OPTIONS_TOKEN } =\n new ConfigurableModuleBuilder<IModuleOptions>()\n .setClassMethodName('register')\n .build();", "score": 5.011291671820732 }, { "filename": "src/processors/login.processor.ts", "retrieved_chunk": "import { IUser } from '../interfaces/user.interface';\nimport { TokenModel } from '../models/token.model';\n@Injectable()\nexport class LoginProcessor {\n public constructor(\n private readonly accessTokenGenerator: AccessTokenGenerator,\n private readonly refreshTokenGenerator: RefreshTokenGenerator,\n @Inject(MODULE_OPTIONS_TOKEN)\n private readonly moduleOptions: IModuleOptions,\n @Inject(iamConfig.KEY)", "score": 4.605874517714911 }, { "filename": "src/controllers/auth.controller.ts", "retrieved_chunk": "import { AuthType } from '../enums/auth-type.enum';\nimport { TokenType } from '../enums/token-type.enum';\nimport { LoggedInEvent } from '../events/logged-in.event';\nimport { LoggedOutEvent } from '../events/logged-out.event';\nimport { BcryptHasher } from '../hashers/bcrypt.hasher';\nimport { MODULE_OPTIONS_TOKEN } from '../iam.module-definition';\nimport { IActiveUser } from '../interfaces/active-user.interface';\nimport { IModuleOptions } from '../interfaces/module-options.interface';\nimport { IRefreshTokenJwtPayload } from '../interfaces/refresh-token-jwt-payload.interface';\nimport { LoginProcessor } from '../processors/login.processor';", "score": 3.6567741400421303 } ]
typescript
: [AuthController], }) export class IamModule extends ConfigurableModuleClass {}
import { Body, Controller, Get, HttpCode, HttpStatus, Inject, NotFoundException, Param, Post, Req, Res, UnauthorizedException, } from '@nestjs/common'; import { ConfigType } from '@nestjs/config'; import { EventBus } from '@nestjs/cqrs'; import { JwtService } from '@nestjs/jwt'; import { ApiNoContentResponse, ApiOkResponse, ApiOperation, ApiTags, } from '@nestjs/swagger'; import { Request, Response } from 'express'; import iamConfig from '../configs/iam.config'; import { ActiveUser } from '../decorators/active-user.decorator'; import { Auth } from '../decorators/auth.decorator'; import { LoginRequestDto } from '../dtos/login-request.dto'; import { LoginResponseDto } from '../dtos/login-response.dto'; import { PasswordlessLoginRequestRequestDto } from '../dtos/passwordless-login-request-request.dto'; import { AuthType } from '../enums/auth-type.enum'; import { TokenType } from '../enums/token-type.enum'; import { LoggedInEvent } from '../events/logged-in.event'; import { LoggedOutEvent } from '../events/logged-out.event'; import { BcryptHasher } from '../hashers/bcrypt.hasher'; import { MODULE_OPTIONS_TOKEN } from '../iam.module-definition'; import { IActiveUser } from '../interfaces/active-user.interface'; import { IModuleOptions } from '../interfaces/module-options.interface'; import { IRefreshTokenJwtPayload } from '../interfaces/refresh-token-jwt-payload.interface'; import { LoginProcessor } from '../processors/login.processor'; import { LogoutProcessor } from '../processors/logout.processor'; import { PasswordlessLoginRequestProcessor } from '../processors/passwordless-login-request.processor'; @Controller() @ApiTags('Auth') export class AuthController { constructor( private readonly eventBus: EventBus, private readonly hasher: BcryptHasher, private readonly loginProcessor: LoginProcessor, private readonly logoutProcessor: LogoutProcessor, private readonly passwordlessLoginRequestProcessor: PasswordlessLoginRequestProcessor, private readonly jwtService: JwtService, @Inject(MODULE_OPTIONS_TOKEN) private readonly moduleOptions: IModuleOptions, @Inject(iamConfig.KEY) private readonly config: ConfigType<typeof iamConfig>, ) {} @HttpCode(HttpStatus.OK) @ApiOperation({ operationId: 'authLogin' }) @ApiOkResponse({ type: LoginResponseDto }) @Auth(AuthType.None) @Post('/auth/login') async login( @Body() request: LoginRequestDto, @Res({ passthrough: true }) response: Response, ): Promise<LoginResponseDto> { if (!this.config.auth.methods.includes('basic')) { throw new NotFoundException(); } try { const user = await this.moduleOptions.authService.checkUser( request.username, ); if (!(await this.hasher.compare(request.password, user.getPassword()))) { throw new UnauthorizedException(); } const login = await this.loginProcessor.process(user, response); this.eventBus.publish(new LoggedInEvent(user.getId())); return { accessToken: login.accessToken, refreshToken: login.refreshToken, }; } catch { throw new UnauthorizedException(); } } @HttpCode(HttpStatus.OK) @ApiOperation({ operationId: 'authPasswordlessLogin' }) @ApiOkResponse({ type: LoginResponseDto }) @Auth(AuthType.None) @Get('/auth/passwordless_login/:id') async passwordlessLogin( @Param('id') tokenId: string, @Req() request: Request, @Res({ passthrough: true }) response: Response, ): Promise<LoginResponseDto> { if (!this.config.auth.methods.includes('passwordless')) { throw new NotFoundException(); } const requestId = request.cookies[TokenType.PasswordlessLoginToken]; if (!requestId) { throw new UnauthorizedException(); } try { const token = await this.moduleOptions.authService.checkToken( tokenId, TokenType.PasswordlessLoginToken, requestId, ); const user = await this.moduleOptions.authService.getUser( token.getUserId(), ); await this.moduleOptions.authService.checkUser(user.getUsername()); await this.moduleOptions.authService.removeToken(tokenId); const login = await this.loginProcessor.process(user, response); return { accessToken: login.accessToken, refreshToken: login.refreshToken, }; } catch { throw new UnauthorizedException(); } } @HttpCode(HttpStatus.NO_CONTENT) @ApiOperation({ operationId: 'authPasswordlessLoginRequest' }) @ApiNoContentResponse() @Auth(AuthType.None) @Post('/auth/passwordless_login') async passwordlessLoginRequest(
@Body() request: PasswordlessLoginRequestRequestDto, @Res({ passthrough: true }) response: Response, ): Promise<void> {
if (!this.config.auth.methods.includes('passwordless')) { throw new NotFoundException(); } try { const user = await this.moduleOptions.authService.checkUser( request.username, ); await this.passwordlessLoginRequestProcessor.process(user, response); } catch {} } @HttpCode(HttpStatus.OK) @ApiOperation({ operationId: 'authRefreshTokens' }) @ApiOkResponse({ type: LoginResponseDto }) @Auth(AuthType.None) @Get('/auth/refresh_tokens') async refreshTokens( @Req() request: Request, @Res({ passthrough: true }) response: Response, ): Promise<LoginResponseDto> { try { const refreshTokenJwtPayload: IRefreshTokenJwtPayload = await this.jwtService.verifyAsync( request.cookies[TokenType.RefreshToken], ); await this.moduleOptions.authService.checkToken( refreshTokenJwtPayload.id, TokenType.RefreshToken, ); const user = await this.moduleOptions.authService.getUser( refreshTokenJwtPayload.sub, ); await this.moduleOptions.authService.checkUser(user.getUsername()); await this.moduleOptions.authService.removeToken( refreshTokenJwtPayload.id, ); const login = await this.loginProcessor.process(user, response); return { accessToken: login.accessToken, refreshToken: login.refreshToken, }; } catch { throw new UnauthorizedException(); } } @HttpCode(HttpStatus.NO_CONTENT) @ApiOperation({ operationId: 'authLogout' }) @ApiNoContentResponse() @Auth(AuthType.None) @Get('/auth/logout') async logout( @Req() request: Request, @Res({ passthrough: true }) response: Response, @ActiveUser() activeUser: IActiveUser, ) { await this.logoutProcessor.process(request, response); if (!activeUser) { return; } this.eventBus.publish(new LoggedOutEvent(activeUser.userId)); } }
src/controllers/auth.controller.ts
fastnloud-nest-iam-463230d
[ { "filename": "src/processors/logout.processor.ts", "retrieved_chunk": "export class LogoutProcessor {\n public constructor(\n private readonly jwtService: JwtService,\n @Inject(MODULE_OPTIONS_TOKEN)\n private readonly moduleOptions: IModuleOptions,\n @Inject(iamConfig.KEY)\n private readonly config: ConfigType<typeof iamConfig>,\n ) {}\n public async process(request: Request, response: Response): Promise<void> {\n try {", "score": 12.104533527035624 }, { "filename": "src/processors/passwordless-login-request.processor.ts", "retrieved_chunk": "@Injectable()\nexport class PasswordlessLoginRequestProcessor {\n public constructor(\n private readonly passwordlessLoginTokenGenerator: PasswordlessLoginTokenGenerator,\n @Inject(MODULE_OPTIONS_TOKEN)\n private readonly moduleOptions: IModuleOptions,\n @Inject(iamConfig.KEY)\n private readonly config: ConfigType<typeof iamConfig>,\n ) {}\n public async process(user: IUser, response: Response): Promise<void> {", "score": 10.122616849902354 }, { "filename": "src/enums/auth-type.enum.ts", "retrieved_chunk": "export enum AuthType {\n AccessToken,\n None,\n}", "score": 9.780300348009533 }, { "filename": "src/decorators/auth.decorator.ts", "retrieved_chunk": "import { SetMetadata } from '@nestjs/common';\nimport { IAM_AUTH_TYPE_KEY } from '../constants/iam.constants';\nimport { AuthType } from '../enums/auth-type.enum';\nexport const Auth = (...authTypes: AuthType[]) =>\n SetMetadata(IAM_AUTH_TYPE_KEY, authTypes);", "score": 9.529492408659475 }, { "filename": "src/guards/none.guard.ts", "retrieved_chunk": " request[IAM_REQUEST_USER_KEY] = activeUser;\n } catch {\n return true;\n }\n return true;\n }\n}", "score": 8.585251384275729 } ]
typescript
@Body() request: PasswordlessLoginRequestRequestDto, @Res({ passthrough: true }) response: Response, ): Promise<void> {
import { Body, Controller, Get, HttpCode, HttpStatus, Inject, NotFoundException, Param, Post, Req, Res, UnauthorizedException, } from '@nestjs/common'; import { ConfigType } from '@nestjs/config'; import { EventBus } from '@nestjs/cqrs'; import { JwtService } from '@nestjs/jwt'; import { ApiNoContentResponse, ApiOkResponse, ApiOperation, ApiTags, } from '@nestjs/swagger'; import { Request, Response } from 'express'; import iamConfig from '../configs/iam.config'; import { ActiveUser } from '../decorators/active-user.decorator'; import { Auth } from '../decorators/auth.decorator'; import { LoginRequestDto } from '../dtos/login-request.dto'; import { LoginResponseDto } from '../dtos/login-response.dto'; import { PasswordlessLoginRequestRequestDto } from '../dtos/passwordless-login-request-request.dto'; import { AuthType } from '../enums/auth-type.enum'; import { TokenType } from '../enums/token-type.enum'; import { LoggedInEvent } from '../events/logged-in.event'; import { LoggedOutEvent } from '../events/logged-out.event'; import { BcryptHasher } from '../hashers/bcrypt.hasher'; import { MODULE_OPTIONS_TOKEN } from '../iam.module-definition'; import { IActiveUser } from '../interfaces/active-user.interface'; import { IModuleOptions } from '../interfaces/module-options.interface'; import { IRefreshTokenJwtPayload } from '../interfaces/refresh-token-jwt-payload.interface'; import { LoginProcessor } from '../processors/login.processor'; import { LogoutProcessor } from '../processors/logout.processor'; import { PasswordlessLoginRequestProcessor } from '../processors/passwordless-login-request.processor'; @Controller() @ApiTags('Auth') export class AuthController { constructor( private readonly eventBus: EventBus, private readonly hasher: BcryptHasher, private readonly loginProcessor: LoginProcessor, private readonly logoutProcessor: LogoutProcessor, private readonly passwordlessLoginRequestProcessor: PasswordlessLoginRequestProcessor, private readonly jwtService: JwtService, @Inject(MODULE_OPTIONS_TOKEN) private readonly moduleOptions: IModuleOptions, @Inject(iamConfig.KEY) private readonly config: ConfigType<typeof iamConfig>, ) {} @HttpCode(HttpStatus.OK) @ApiOperation({ operationId: 'authLogin' }) @ApiOkResponse({ type: LoginResponseDto }) @Auth(AuthType.None) @Post('/auth/login') async login( @Body() request: LoginRequestDto, @Res({ passthrough: true }) response: Response, ): Promise<LoginResponseDto> { if (!this.config.auth.methods.includes('basic')) { throw new NotFoundException(); } try { const user = await this.moduleOptions.authService.checkUser( request.username, ); if (!(await this.hasher.compare(request.password, user.getPassword()))) { throw new UnauthorizedException(); } const login = await this.loginProcessor.process(user, response); this.eventBus.publish(new LoggedInEvent(user.getId())); return { accessToken: login.accessToken, refreshToken: login.refreshToken, }; } catch { throw new UnauthorizedException(); } } @HttpCode(HttpStatus.OK) @ApiOperation({ operationId: 'authPasswordlessLogin' }) @ApiOkResponse({ type: LoginResponseDto }) @Auth(AuthType.None) @Get('/auth/passwordless_login/:id') async passwordlessLogin( @Param('id') tokenId: string, @Req() request: Request, @Res({ passthrough: true }) response: Response, ): Promise<LoginResponseDto> { if (!this.config.auth.methods.includes('passwordless')) { throw new NotFoundException(); } const requestId = request.cookies[TokenType.PasswordlessLoginToken]; if (!requestId) { throw new UnauthorizedException(); } try { const token = await this.moduleOptions.authService.checkToken( tokenId, TokenType.PasswordlessLoginToken, requestId, ); const user = await this.moduleOptions.authService.getUser( token.getUserId(), ); await this.moduleOptions.authService.checkUser(user.getUsername()); await this.moduleOptions.authService.removeToken(tokenId); const login = await this.loginProcessor.process(user, response); return { accessToken: login.accessToken, refreshToken: login.refreshToken, }; } catch { throw new UnauthorizedException(); } } @HttpCode(HttpStatus.NO_CONTENT) @ApiOperation({ operationId: 'authPasswordlessLoginRequest' }) @ApiNoContentResponse() @Auth(AuthType.None) @Post('/auth/passwordless_login') async passwordlessLoginRequest( @Body() request: PasswordlessLoginRequestRequestDto, @Res({ passthrough: true }) response: Response, ): Promise<void> { if (!this.config.auth.methods.includes('passwordless')) { throw new NotFoundException(); } try { const user = await this.moduleOptions.authService.checkUser( request.username, ); await this.passwordlessLoginRequestProcessor.process(user, response); } catch {} } @HttpCode(HttpStatus.OK) @ApiOperation({ operationId: 'authRefreshTokens' }) @ApiOkResponse({ type: LoginResponseDto }) @Auth(AuthType.None) @Get('/auth/refresh_tokens') async refreshTokens( @Req() request: Request, @Res({ passthrough: true }) response: Response, ): Promise<LoginResponseDto> { try { const refreshTokenJwtPayload: IRefreshTokenJwtPayload = await this.jwtService.verifyAsync( request.cookies[TokenType.RefreshToken], ); await this.moduleOptions.authService.checkToken( refreshTokenJwtPayload.id, TokenType.RefreshToken, ); const user = await this.moduleOptions.authService.getUser( refreshTokenJwtPayload.sub, ); await this.moduleOptions.authService.checkUser(user.getUsername()); await this.moduleOptions.authService.removeToken( refreshTokenJwtPayload.id, ); const login = await this.loginProcessor.process(user, response); return { accessToken: login.accessToken, refreshToken: login.refreshToken, }; } catch { throw new UnauthorizedException(); } } @HttpCode(HttpStatus.NO_CONTENT) @ApiOperation({ operationId: 'authLogout' }) @ApiNoContentResponse() @Auth(AuthType.None) @Get('/auth/logout') async logout( @Req() request: Request, @Res({ passthrough: true }) response: Response, @ActiveUser() activeUser:
IActiveUser, ) {
await this.logoutProcessor.process(request, response); if (!activeUser) { return; } this.eventBus.publish(new LoggedOutEvent(activeUser.userId)); } }
src/controllers/auth.controller.ts
fastnloud-nest-iam-463230d
[ { "filename": "src/guards/access-token.guard.ts", "retrieved_chunk": " );\n const activeUser: IActiveUser = {\n userId: accessTokenJwtPayload.sub,\n roles: accessTokenJwtPayload.roles,\n };\n request[IAM_REQUEST_USER_KEY] = activeUser;\n } catch {\n throw new UnauthorizedException();\n }\n return true;", "score": 13.675327688763867 }, { "filename": "src/guards/none.guard.ts", "retrieved_chunk": " request[IAM_REQUEST_USER_KEY] = activeUser;\n } catch {\n return true;\n }\n return true;\n }\n}", "score": 13.212047402518202 }, { "filename": "src/processors/logout.processor.ts", "retrieved_chunk": "export class LogoutProcessor {\n public constructor(\n private readonly jwtService: JwtService,\n @Inject(MODULE_OPTIONS_TOKEN)\n private readonly moduleOptions: IModuleOptions,\n @Inject(iamConfig.KEY)\n private readonly config: ConfigType<typeof iamConfig>,\n ) {}\n public async process(request: Request, response: Response): Promise<void> {\n try {", "score": 10.986312157211172 }, { "filename": "src/enums/auth-type.enum.ts", "retrieved_chunk": "export enum AuthType {\n AccessToken,\n None,\n}", "score": 9.780300348009533 }, { "filename": "src/decorators/auth.decorator.ts", "retrieved_chunk": "import { SetMetadata } from '@nestjs/common';\nimport { IAM_AUTH_TYPE_KEY } from '../constants/iam.constants';\nimport { AuthType } from '../enums/auth-type.enum';\nexport const Auth = (...authTypes: AuthType[]) =>\n SetMetadata(IAM_AUTH_TYPE_KEY, authTypes);", "score": 9.529492408659475 } ]
typescript
IActiveUser, ) {
import { Body, Controller, Get, HttpCode, HttpStatus, Inject, NotFoundException, Param, Post, Req, Res, UnauthorizedException, } from '@nestjs/common'; import { ConfigType } from '@nestjs/config'; import { EventBus } from '@nestjs/cqrs'; import { JwtService } from '@nestjs/jwt'; import { ApiNoContentResponse, ApiOkResponse, ApiOperation, ApiTags, } from '@nestjs/swagger'; import { Request, Response } from 'express'; import iamConfig from '../configs/iam.config'; import { ActiveUser } from '../decorators/active-user.decorator'; import { Auth } from '../decorators/auth.decorator'; import { LoginRequestDto } from '../dtos/login-request.dto'; import { LoginResponseDto } from '../dtos/login-response.dto'; import { PasswordlessLoginRequestRequestDto } from '../dtos/passwordless-login-request-request.dto'; import { AuthType } from '../enums/auth-type.enum'; import { TokenType } from '../enums/token-type.enum'; import { LoggedInEvent } from '../events/logged-in.event'; import { LoggedOutEvent } from '../events/logged-out.event'; import { BcryptHasher } from '../hashers/bcrypt.hasher'; import { MODULE_OPTIONS_TOKEN } from '../iam.module-definition'; import { IActiveUser } from '../interfaces/active-user.interface'; import { IModuleOptions } from '../interfaces/module-options.interface'; import { IRefreshTokenJwtPayload } from '../interfaces/refresh-token-jwt-payload.interface'; import { LoginProcessor } from '../processors/login.processor'; import { LogoutProcessor } from '../processors/logout.processor'; import { PasswordlessLoginRequestProcessor } from '../processors/passwordless-login-request.processor'; @Controller() @ApiTags('Auth') export class AuthController { constructor( private readonly eventBus: EventBus, private readonly hasher: BcryptHasher, private readonly loginProcessor: LoginProcessor, private readonly logoutProcessor: LogoutProcessor, private readonly passwordlessLoginRequestProcessor: PasswordlessLoginRequestProcessor, private readonly jwtService: JwtService, @Inject(MODULE_OPTIONS_TOKEN) private readonly moduleOptions: IModuleOptions, @Inject(iamConfig.KEY) private readonly config: ConfigType<typeof iamConfig>, ) {} @HttpCode(HttpStatus.OK) @ApiOperation({ operationId: 'authLogin' }) @ApiOkResponse({ type: LoginResponseDto }) @Auth(AuthType.None) @Post('/auth/login') async login( @Body() request: LoginRequestDto, @Res({ passthrough: true }) response: Response, ): Promise<LoginResponseDto> { if (!this.config.auth.methods.includes('basic')) { throw new NotFoundException(); } try { const user = await this.moduleOptions.authService.checkUser( request.username, ); if (!(await this.hasher.compare(request.password, user.getPassword()))) { throw new UnauthorizedException(); } const login = await this.loginProcessor.process(user, response); this.eventBus.publish(new LoggedInEvent(user.getId())); return { accessToken: login.accessToken, refreshToken: login.refreshToken, }; } catch { throw new UnauthorizedException(); } } @HttpCode(HttpStatus.OK) @ApiOperation({ operationId: 'authPasswordlessLogin' }) @ApiOkResponse({ type: LoginResponseDto }) @Auth(AuthType.None) @Get('/auth/passwordless_login/:id') async passwordlessLogin( @Param('id') tokenId: string, @Req() request: Request, @Res({ passthrough: true }) response: Response, ): Promise<LoginResponseDto> { if (!this.config.auth.methods.includes('passwordless')) { throw new NotFoundException(); } const requestId = request.cookies[TokenType.PasswordlessLoginToken]; if (!requestId) { throw new UnauthorizedException(); } try { const token = await this.moduleOptions.authService.checkToken( tokenId, TokenType.PasswordlessLoginToken, requestId, ); const user = await this.moduleOptions.authService.getUser( token.getUserId(), ); await this.moduleOptions.authService.checkUser(user.getUsername()); await this.moduleOptions.authService.removeToken(tokenId); const login = await this.loginProcessor.process(user, response); return { accessToken: login.accessToken, refreshToken: login.refreshToken, }; } catch { throw new UnauthorizedException(); } } @HttpCode(HttpStatus.NO_CONTENT) @ApiOperation({ operationId: 'authPasswordlessLoginRequest' }) @ApiNoContentResponse() @Auth(AuthType.None) @Post('/auth/passwordless_login') async passwordlessLoginRequest( @Body()
request: PasswordlessLoginRequestRequestDto, @Res({ passthrough: true }) response: Response, ): Promise<void> {
if (!this.config.auth.methods.includes('passwordless')) { throw new NotFoundException(); } try { const user = await this.moduleOptions.authService.checkUser( request.username, ); await this.passwordlessLoginRequestProcessor.process(user, response); } catch {} } @HttpCode(HttpStatus.OK) @ApiOperation({ operationId: 'authRefreshTokens' }) @ApiOkResponse({ type: LoginResponseDto }) @Auth(AuthType.None) @Get('/auth/refresh_tokens') async refreshTokens( @Req() request: Request, @Res({ passthrough: true }) response: Response, ): Promise<LoginResponseDto> { try { const refreshTokenJwtPayload: IRefreshTokenJwtPayload = await this.jwtService.verifyAsync( request.cookies[TokenType.RefreshToken], ); await this.moduleOptions.authService.checkToken( refreshTokenJwtPayload.id, TokenType.RefreshToken, ); const user = await this.moduleOptions.authService.getUser( refreshTokenJwtPayload.sub, ); await this.moduleOptions.authService.checkUser(user.getUsername()); await this.moduleOptions.authService.removeToken( refreshTokenJwtPayload.id, ); const login = await this.loginProcessor.process(user, response); return { accessToken: login.accessToken, refreshToken: login.refreshToken, }; } catch { throw new UnauthorizedException(); } } @HttpCode(HttpStatus.NO_CONTENT) @ApiOperation({ operationId: 'authLogout' }) @ApiNoContentResponse() @Auth(AuthType.None) @Get('/auth/logout') async logout( @Req() request: Request, @Res({ passthrough: true }) response: Response, @ActiveUser() activeUser: IActiveUser, ) { await this.logoutProcessor.process(request, response); if (!activeUser) { return; } this.eventBus.publish(new LoggedOutEvent(activeUser.userId)); } }
src/controllers/auth.controller.ts
fastnloud-nest-iam-463230d
[ { "filename": "src/processors/logout.processor.ts", "retrieved_chunk": "export class LogoutProcessor {\n public constructor(\n private readonly jwtService: JwtService,\n @Inject(MODULE_OPTIONS_TOKEN)\n private readonly moduleOptions: IModuleOptions,\n @Inject(iamConfig.KEY)\n private readonly config: ConfigType<typeof iamConfig>,\n ) {}\n public async process(request: Request, response: Response): Promise<void> {\n try {", "score": 12.104533527035624 }, { "filename": "src/processors/passwordless-login-request.processor.ts", "retrieved_chunk": "@Injectable()\nexport class PasswordlessLoginRequestProcessor {\n public constructor(\n private readonly passwordlessLoginTokenGenerator: PasswordlessLoginTokenGenerator,\n @Inject(MODULE_OPTIONS_TOKEN)\n private readonly moduleOptions: IModuleOptions,\n @Inject(iamConfig.KEY)\n private readonly config: ConfigType<typeof iamConfig>,\n ) {}\n public async process(user: IUser, response: Response): Promise<void> {", "score": 10.122616849902354 }, { "filename": "src/enums/auth-type.enum.ts", "retrieved_chunk": "export enum AuthType {\n AccessToken,\n None,\n}", "score": 9.780300348009533 }, { "filename": "src/decorators/auth.decorator.ts", "retrieved_chunk": "import { SetMetadata } from '@nestjs/common';\nimport { IAM_AUTH_TYPE_KEY } from '../constants/iam.constants';\nimport { AuthType } from '../enums/auth-type.enum';\nexport const Auth = (...authTypes: AuthType[]) =>\n SetMetadata(IAM_AUTH_TYPE_KEY, authTypes);", "score": 9.529492408659475 }, { "filename": "src/guards/none.guard.ts", "retrieved_chunk": " request[IAM_REQUEST_USER_KEY] = activeUser;\n } catch {\n return true;\n }\n return true;\n }\n}", "score": 8.585251384275729 } ]
typescript
request: PasswordlessLoginRequestRequestDto, @Res({ passthrough: true }) response: Response, ): Promise<void> {
import { Body, Controller, Get, HttpCode, HttpStatus, Inject, NotFoundException, Param, Post, Req, Res, UnauthorizedException, } from '@nestjs/common'; import { ConfigType } from '@nestjs/config'; import { EventBus } from '@nestjs/cqrs'; import { JwtService } from '@nestjs/jwt'; import { ApiNoContentResponse, ApiOkResponse, ApiOperation, ApiTags, } from '@nestjs/swagger'; import { Request, Response } from 'express'; import iamConfig from '../configs/iam.config'; import { ActiveUser } from '../decorators/active-user.decorator'; import { Auth } from '../decorators/auth.decorator'; import { LoginRequestDto } from '../dtos/login-request.dto'; import { LoginResponseDto } from '../dtos/login-response.dto'; import { PasswordlessLoginRequestRequestDto } from '../dtos/passwordless-login-request-request.dto'; import { AuthType } from '../enums/auth-type.enum'; import { TokenType } from '../enums/token-type.enum'; import { LoggedInEvent } from '../events/logged-in.event'; import { LoggedOutEvent } from '../events/logged-out.event'; import { BcryptHasher } from '../hashers/bcrypt.hasher'; import { MODULE_OPTIONS_TOKEN } from '../iam.module-definition'; import { IActiveUser } from '../interfaces/active-user.interface'; import { IModuleOptions } from '../interfaces/module-options.interface'; import { IRefreshTokenJwtPayload } from '../interfaces/refresh-token-jwt-payload.interface'; import { LoginProcessor } from '../processors/login.processor'; import { LogoutProcessor } from '../processors/logout.processor'; import { PasswordlessLoginRequestProcessor } from '../processors/passwordless-login-request.processor'; @Controller() @ApiTags('Auth') export class AuthController { constructor( private readonly eventBus: EventBus, private readonly hasher: BcryptHasher, private readonly loginProcessor: LoginProcessor, private readonly logoutProcessor: LogoutProcessor, private readonly passwordlessLoginRequestProcessor: PasswordlessLoginRequestProcessor, private readonly jwtService: JwtService, @Inject(MODULE_OPTIONS_TOKEN) private readonly moduleOptions: IModuleOptions, @Inject(iamConfig.KEY) private readonly config: ConfigType<typeof iamConfig>, ) {} @HttpCode(HttpStatus.OK) @ApiOperation({ operationId: 'authLogin' }) @ApiOkResponse({ type: LoginResponseDto }) @Auth(AuthType.None) @Post('/auth/login') async login( @Body() request: LoginRequestDto, @Res({ passthrough: true }) response: Response, ): Promise<LoginResponseDto> { if (!this.config.auth.methods.includes('basic')) { throw new NotFoundException(); } try { const user = await this.moduleOptions.authService.checkUser( request.username, ); if (!(await this.hasher.compare(request.password, user.getPassword()))) { throw new UnauthorizedException(); } const login = await this.loginProcessor.process(user, response); this.eventBus.publish(new LoggedInEvent(user.getId())); return { accessToken: login.accessToken, refreshToken: login.refreshToken, }; } catch { throw new UnauthorizedException(); } } @HttpCode(HttpStatus.OK) @ApiOperation({ operationId: 'authPasswordlessLogin' }) @ApiOkResponse({ type: LoginResponseDto }) @Auth(AuthType.None) @Get('/auth/passwordless_login/:id') async passwordlessLogin( @Param('id') tokenId: string, @Req() request: Request, @Res({ passthrough: true }) response: Response, ): Promise<LoginResponseDto> { if (!this.config.auth.methods.includes('passwordless')) { throw new NotFoundException(); } const requestId = request.cookies[TokenType.PasswordlessLoginToken]; if (!requestId) { throw new UnauthorizedException(); } try { const token = await this.moduleOptions.authService.checkToken( tokenId, TokenType.PasswordlessLoginToken, requestId, ); const user = await this.moduleOptions.authService.getUser( token.getUserId(), ); await this.moduleOptions.authService.checkUser(user.getUsername()); await this.moduleOptions.authService.removeToken(tokenId); const login = await this.loginProcessor.process(user, response); return { accessToken: login.accessToken, refreshToken: login.refreshToken, }; } catch { throw new UnauthorizedException(); } } @HttpCode(HttpStatus.NO_CONTENT) @ApiOperation({ operationId: 'authPasswordlessLoginRequest' }) @ApiNoContentResponse() @Auth(AuthType.None) @Post('/auth/passwordless_login') async passwordlessLoginRequest( @Body() request: PasswordlessLoginRequestRequestDto, @Res({ passthrough: true }) response: Response, ): Promise<void> { if (!this.config.auth.methods.includes('passwordless')) { throw new NotFoundException(); } try { const user = await this.moduleOptions.authService.checkUser( request.username, ); await this.passwordlessLoginRequestProcessor.process(user, response); } catch {} } @HttpCode(HttpStatus.OK) @ApiOperation({ operationId: 'authRefreshTokens' }) @ApiOkResponse({ type: LoginResponseDto }) @Auth(AuthType.None) @Get('/auth/refresh_tokens') async refreshTokens( @Req() request: Request, @Res({ passthrough: true }) response: Response, ): Promise<LoginResponseDto> { try { const refreshTokenJwtPayload: IRefreshTokenJwtPayload = await this.jwtService.verifyAsync( request.cookies[TokenType.RefreshToken], ); await this.moduleOptions.authService.checkToken( refreshTokenJwtPayload.id, TokenType.RefreshToken, ); const user = await this.moduleOptions.authService.getUser( refreshTokenJwtPayload.sub, ); await this.moduleOptions.authService.checkUser(user.getUsername()); await this.moduleOptions.authService.removeToken( refreshTokenJwtPayload.id, ); const login = await this.loginProcessor.process(user, response); return { accessToken: login.accessToken, refreshToken: login.refreshToken, }; } catch { throw new UnauthorizedException(); } } @HttpCode(HttpStatus.NO_CONTENT) @ApiOperation({ operationId: 'authLogout' }) @ApiNoContentResponse() @Auth(AuthType.None) @Get('/auth/logout') async logout( @Req() request: Request, @Res({ passthrough: true }) response: Response, @
ActiveUser() activeUser: IActiveUser, ) {
await this.logoutProcessor.process(request, response); if (!activeUser) { return; } this.eventBus.publish(new LoggedOutEvent(activeUser.userId)); } }
src/controllers/auth.controller.ts
fastnloud-nest-iam-463230d
[ { "filename": "src/guards/access-token.guard.ts", "retrieved_chunk": " );\n const activeUser: IActiveUser = {\n userId: accessTokenJwtPayload.sub,\n roles: accessTokenJwtPayload.roles,\n };\n request[IAM_REQUEST_USER_KEY] = activeUser;\n } catch {\n throw new UnauthorizedException();\n }\n return true;", "score": 13.675327688763867 }, { "filename": "src/guards/none.guard.ts", "retrieved_chunk": " request[IAM_REQUEST_USER_KEY] = activeUser;\n } catch {\n return true;\n }\n return true;\n }\n}", "score": 13.212047402518202 }, { "filename": "src/processors/logout.processor.ts", "retrieved_chunk": "export class LogoutProcessor {\n public constructor(\n private readonly jwtService: JwtService,\n @Inject(MODULE_OPTIONS_TOKEN)\n private readonly moduleOptions: IModuleOptions,\n @Inject(iamConfig.KEY)\n private readonly config: ConfigType<typeof iamConfig>,\n ) {}\n public async process(request: Request, response: Response): Promise<void> {\n try {", "score": 10.986312157211172 }, { "filename": "src/enums/auth-type.enum.ts", "retrieved_chunk": "export enum AuthType {\n AccessToken,\n None,\n}", "score": 9.780300348009533 }, { "filename": "src/decorators/auth.decorator.ts", "retrieved_chunk": "import { SetMetadata } from '@nestjs/common';\nimport { IAM_AUTH_TYPE_KEY } from '../constants/iam.constants';\nimport { AuthType } from '../enums/auth-type.enum';\nexport const Auth = (...authTypes: AuthType[]) =>\n SetMetadata(IAM_AUTH_TYPE_KEY, authTypes);", "score": 9.529492408659475 } ]
typescript
ActiveUser() activeUser: IActiveUser, ) {
import { Body, Controller, Get, HttpCode, HttpStatus, Inject, NotFoundException, Param, Post, Req, Res, UnauthorizedException, } from '@nestjs/common'; import { ConfigType } from '@nestjs/config'; import { EventBus } from '@nestjs/cqrs'; import { JwtService } from '@nestjs/jwt'; import { ApiNoContentResponse, ApiOkResponse, ApiOperation, ApiTags, } from '@nestjs/swagger'; import { Request, Response } from 'express'; import iamConfig from '../configs/iam.config'; import { ActiveUser } from '../decorators/active-user.decorator'; import { Auth } from '../decorators/auth.decorator'; import { LoginRequestDto } from '../dtos/login-request.dto'; import { LoginResponseDto } from '../dtos/login-response.dto'; import { PasswordlessLoginRequestRequestDto } from '../dtos/passwordless-login-request-request.dto'; import { AuthType } from '../enums/auth-type.enum'; import { TokenType } from '../enums/token-type.enum'; import { LoggedInEvent } from '../events/logged-in.event'; import { LoggedOutEvent } from '../events/logged-out.event'; import { BcryptHasher } from '../hashers/bcrypt.hasher'; import { MODULE_OPTIONS_TOKEN } from '../iam.module-definition'; import { IActiveUser } from '../interfaces/active-user.interface'; import { IModuleOptions } from '../interfaces/module-options.interface'; import { IRefreshTokenJwtPayload } from '../interfaces/refresh-token-jwt-payload.interface'; import { LoginProcessor } from '../processors/login.processor'; import { LogoutProcessor } from '../processors/logout.processor'; import { PasswordlessLoginRequestProcessor } from '../processors/passwordless-login-request.processor'; @Controller() @ApiTags('Auth') export class AuthController { constructor( private readonly eventBus: EventBus, private readonly hasher: BcryptHasher, private readonly loginProcessor: LoginProcessor, private readonly logoutProcessor: LogoutProcessor, private readonly passwordlessLoginRequestProcessor: PasswordlessLoginRequestProcessor, private readonly jwtService: JwtService, @Inject(MODULE_OPTIONS_TOKEN) private readonly moduleOptions: IModuleOptions, @Inject(iamConfig.KEY) private readonly config: ConfigType<typeof iamConfig>, ) {} @HttpCode(HttpStatus.OK) @ApiOperation({ operationId: 'authLogin' }) @ApiOkResponse({ type: LoginResponseDto }) @Auth(AuthType.None) @Post('/auth/login') async login( @Body() request: LoginRequestDto, @Res({ passthrough: true }) response: Response, ): Promise<LoginResponseDto> { if (!this.config.auth.methods.includes('basic')) { throw new NotFoundException(); } try { const user = await this.moduleOptions.authService.checkUser( request.username, ); if (!(await this.hasher.compare(request.password, user.getPassword()))) { throw new UnauthorizedException(); } const login = await this.loginProcessor.process(user, response); this.eventBus.publish(new LoggedInEvent(user.getId())); return { accessToken: login.accessToken, refreshToken: login.refreshToken, }; } catch { throw new UnauthorizedException(); } } @HttpCode(HttpStatus.OK) @ApiOperation({ operationId: 'authPasswordlessLogin' }) @ApiOkResponse({ type: LoginResponseDto }) @Auth(AuthType.None) @Get('/auth/passwordless_login/:id') async passwordlessLogin( @Param('id') tokenId: string, @Req() request: Request, @Res({ passthrough: true }) response: Response, ): Promise<LoginResponseDto> { if (!this.config.auth.methods.includes('passwordless')) { throw new NotFoundException(); } const requestId = request.cookies[TokenType.PasswordlessLoginToken]; if (!requestId) { throw new UnauthorizedException(); } try { const token = await this.moduleOptions.authService.checkToken( tokenId, TokenType.PasswordlessLoginToken, requestId, ); const user = await this.moduleOptions.authService.getUser( token.getUserId(), ); await this.moduleOptions.authService.checkUser(user.getUsername()); await this.moduleOptions.authService.removeToken(tokenId); const login = await this.loginProcessor.process(user, response); return { accessToken: login.accessToken, refreshToken: login.refreshToken, }; } catch { throw new UnauthorizedException(); } } @HttpCode(HttpStatus.NO_CONTENT) @ApiOperation({ operationId: 'authPasswordlessLoginRequest' }) @ApiNoContentResponse() @Auth(AuthType.None) @Post('/auth/passwordless_login') async passwordlessLoginRequest( @Body() request: PasswordlessLoginRequestRequestDto, @Res({ passthrough: true }) response: Response, ): Promise<void> { if (!this.config.auth.methods.includes('passwordless')) { throw new NotFoundException(); } try { const user = await this.moduleOptions.authService.checkUser( request.username, ); await this.passwordlessLoginRequestProcessor.process(user, response); } catch {} } @HttpCode(HttpStatus.OK) @ApiOperation({ operationId: 'authRefreshTokens' }) @ApiOkResponse({ type: LoginResponseDto }) @Auth(AuthType.None) @Get('/auth/refresh_tokens') async refreshTokens( @Req() request: Request, @Res({ passthrough: true }) response: Response, ): Promise<LoginResponseDto> { try { const refreshTokenJwtPayload: IRefreshTokenJwtPayload = await this.jwtService.verifyAsync( request.cookies[TokenType.RefreshToken], ); await this.moduleOptions.authService.checkToken( refreshTokenJwtPayload.id, TokenType.RefreshToken, ); const user = await this.moduleOptions.authService.getUser( refreshTokenJwtPayload.sub, ); await this.moduleOptions.authService.checkUser(user.getUsername()); await this.moduleOptions.authService.removeToken( refreshTokenJwtPayload.id, ); const login = await this.loginProcessor.process(user, response); return { accessToken: login.accessToken, refreshToken: login.refreshToken, }; } catch { throw new UnauthorizedException(); } } @HttpCode(HttpStatus.NO_CONTENT) @ApiOperation({ operationId: 'authLogout' }) @ApiNoContentResponse() @Auth(AuthType.None) @Get('/auth/logout') async logout( @Req() request: Request, @Res({ passthrough: true }) response: Response,
@ActiveUser() activeUser: IActiveUser, ) {
await this.logoutProcessor.process(request, response); if (!activeUser) { return; } this.eventBus.publish(new LoggedOutEvent(activeUser.userId)); } }
src/controllers/auth.controller.ts
fastnloud-nest-iam-463230d
[ { "filename": "src/guards/access-token.guard.ts", "retrieved_chunk": " );\n const activeUser: IActiveUser = {\n userId: accessTokenJwtPayload.sub,\n roles: accessTokenJwtPayload.roles,\n };\n request[IAM_REQUEST_USER_KEY] = activeUser;\n } catch {\n throw new UnauthorizedException();\n }\n return true;", "score": 13.675327688763867 }, { "filename": "src/guards/none.guard.ts", "retrieved_chunk": " request[IAM_REQUEST_USER_KEY] = activeUser;\n } catch {\n return true;\n }\n return true;\n }\n}", "score": 13.212047402518202 }, { "filename": "src/processors/logout.processor.ts", "retrieved_chunk": "export class LogoutProcessor {\n public constructor(\n private readonly jwtService: JwtService,\n @Inject(MODULE_OPTIONS_TOKEN)\n private readonly moduleOptions: IModuleOptions,\n @Inject(iamConfig.KEY)\n private readonly config: ConfigType<typeof iamConfig>,\n ) {}\n public async process(request: Request, response: Response): Promise<void> {\n try {", "score": 10.986312157211172 }, { "filename": "src/enums/auth-type.enum.ts", "retrieved_chunk": "export enum AuthType {\n AccessToken,\n None,\n}", "score": 9.780300348009533 }, { "filename": "src/decorators/auth.decorator.ts", "retrieved_chunk": "import { SetMetadata } from '@nestjs/common';\nimport { IAM_AUTH_TYPE_KEY } from '../constants/iam.constants';\nimport { AuthType } from '../enums/auth-type.enum';\nexport const Auth = (...authTypes: AuthType[]) =>\n SetMetadata(IAM_AUTH_TYPE_KEY, authTypes);", "score": 9.529492408659475 } ]
typescript
@ActiveUser() activeUser: IActiveUser, ) {
import { toError } from '../core/helper.js'; import { CacheStrategy } from './strategy.js'; import { CacheStrategyOptions, FetchListenerEnv } from './types.js'; export interface NetworkOnlyOptions extends Omit<CacheStrategyOptions, 'cacheName' | 'matchOptions'> { networkTimeoutSeconds?: number; } export class NetworkOnly extends CacheStrategy { private fetchListenerEnv: FetchListenerEnv; private readonly _networkTimeoutSeconds: number; constructor(options: NetworkOnlyOptions = {}, env?: FetchListenerEnv) { // this is gonna come back and bite me. // I need to sort this out quick though //@ts-ignore super(options); this.fetchListenerEnv = env || {}; this._networkTimeoutSeconds = options.networkTimeoutSeconds || 10; } override async _handle(request: Request) { if (request.method !== 'GET') { return fetch(request); } // `fetcher` is a custom fetch function that can de defined and passed to the constructor or just regular fetch const fetcher = this.fetchListenerEnv.state!.fetcher || fetch; const timeoutPromise = new Promise((_, reject) => { setTimeout(() => { reject( new Error( `Network request timed out after ${ this._networkTimeoutSeconds * 1000 } seconds` ) ); }, this._networkTimeoutSeconds * 1000); }); try { for (let plugin of this.plugins) { if (plugin.requestWillFetch) { plugin.requestWillFetch({ request }); } } const fetchPromise: Response = await fetcher(request); const response = (await Promise.race([ fetchPromise, timeoutPromise ])) as Response; if (response) { for (const plugin of this.plugins) { if (plugin.fetchDidSucceed) { await plugin.fetchDidSucceed({ request, response }); } } return response; } // Re-thrown error to be caught by `catch` block throw new Error('Network request failed'); } catch (error) { for (const plugin of this.plugins) { if (plugin.fetchDidFail) { await plugin.fetchDidFail({ request, error:
toError(error) });
} } const headers = { 'X-Remix-Catch': 'yes', 'X-Remix-Worker': 'yes' }; return new Response(JSON.stringify({ message: 'Network Error' }), { status: 500, ...(this.isLoader ? { headers } : {}) }); } } }
src/strategy/networkOnly.ts
remix-pwa-sw-eb66466
[ { "filename": "src/strategy/networkFirst.ts", "retrieved_chunk": " request: updatedRequest\n });\n }\n }\n const fetchPromise = fetcher(updatedRequest).catch((err) => {\n for (const plugin of this.plugins) {\n if (plugin.fetchDidFail)\n plugin.fetchDidFail({\n request: updatedRequest,\n error: err as unknown as Error", "score": 45.12219010470833 }, { "filename": "src/strategy/cacheFirst.ts", "retrieved_chunk": " let response = await fetch(req).catch((err) => {\n for (const plugin of this.plugins) {\n if (plugin.fetchDidFail) {\n plugin.fetchDidFail({\n request: req.clone(),\n error: err\n });\n }\n }\n });", "score": 45.081418775340495 }, { "filename": "src/react/loader.ts", "retrieved_chunk": " }\n });\n } catch (error) {\n // console.error('Service worker registration failed', error);\n }\n }\n if (\n document.readyState === 'complete' ||\n document.readyState === 'interactive'\n ) {", "score": 23.67643602664403 }, { "filename": "src/strategy/networkFirst.ts", "retrieved_chunk": " // a new variable that can be checked for if null.\n let aboutToBeCachedResponse: Response | null = updatedResponse;\n for (const plugin of this.plugins) {\n if (plugin.cacheWillUpdate) {\n aboutToBeCachedResponse = await plugin.cacheWillUpdate({\n request: updatedRequest,\n response: aboutToBeCachedResponse!\n });\n if (!aboutToBeCachedResponse) {\n break;", "score": 23.115184772008035 }, { "filename": "src/strategy/networkFirst.ts", "retrieved_chunk": " let updatedResponse: Response = response.clone();\n for (const plugin of this.plugins) {\n if (plugin.fetchDidSucceed) {\n updatedResponse = await plugin.fetchDidSucceed({\n request: updatedRequest,\n response: updatedResponse\n });\n }\n }\n // `null` can be returned here to avoid caching resources. Hence store in", "score": 22.38392667887776 } ]
typescript
toError(error) });
import { toError } from '../core/helper.js'; import { CacheStrategy } from './strategy.js'; import { CacheStrategyOptions, FetchListenerEnv } from './types.js'; export interface NetworkOnlyOptions extends Omit<CacheStrategyOptions, 'cacheName' | 'matchOptions'> { networkTimeoutSeconds?: number; } export class NetworkOnly extends CacheStrategy { private fetchListenerEnv: FetchListenerEnv; private readonly _networkTimeoutSeconds: number; constructor(options: NetworkOnlyOptions = {}, env?: FetchListenerEnv) { // this is gonna come back and bite me. // I need to sort this out quick though //@ts-ignore super(options); this.fetchListenerEnv = env || {}; this._networkTimeoutSeconds = options.networkTimeoutSeconds || 10; } override async _handle(request: Request) { if (request.method !== 'GET') { return fetch(request); } // `fetcher` is a custom fetch function that can de defined and passed to the constructor or just regular fetch const fetcher = this.fetchListenerEnv.state!.fetcher || fetch; const timeoutPromise = new Promise((_, reject) => { setTimeout(() => { reject( new Error( `Network request timed out after ${ this._networkTimeoutSeconds * 1000 } seconds` ) ); }, this._networkTimeoutSeconds * 1000); }); try {
for (let plugin of this.plugins) {
if (plugin.requestWillFetch) { plugin.requestWillFetch({ request }); } } const fetchPromise: Response = await fetcher(request); const response = (await Promise.race([ fetchPromise, timeoutPromise ])) as Response; if (response) { for (const plugin of this.plugins) { if (plugin.fetchDidSucceed) { await plugin.fetchDidSucceed({ request, response }); } } return response; } // Re-thrown error to be caught by `catch` block throw new Error('Network request failed'); } catch (error) { for (const plugin of this.plugins) { if (plugin.fetchDidFail) { await plugin.fetchDidFail({ request, error: toError(error) }); } } const headers = { 'X-Remix-Catch': 'yes', 'X-Remix-Worker': 'yes' }; return new Response(JSON.stringify({ message: 'Network Error' }), { status: 500, ...(this.isLoader ? { headers } : {}) }); } } }
src/strategy/networkOnly.ts
remix-pwa-sw-eb66466
[ { "filename": "src/strategy/networkFirst.ts", "retrieved_chunk": " }\n private async fetchAndCache(request: Request): Promise<Response> {\n const cache = await caches.open(this.cacheName);\n const timeoutPromise =\n this._networkTimeoutSeconds !== Infinity\n ? new Promise<Response>((_, reject) => {\n setTimeout(() => {\n reject(\n new Error(\n `Network timed out after ${this._networkTimeoutSeconds} seconds`", "score": 37.66890257016848 }, { "filename": "src/strategy/networkFirst.ts", "retrieved_chunk": " )\n );\n }, this._networkTimeoutSeconds * 1000);\n })\n : null;\n const fetcher = this.fetchListenerEnv.state?.fetcher || fetch;\n let updatedRequest = request.clone();\n for (const plugin of this.plugins) {\n if (plugin.requestWillFetch) {\n updatedRequest = await plugin.requestWillFetch({", "score": 30.846426685671858 }, { "filename": "src/strategy/networkFirst.ts", "retrieved_chunk": " super(options);\n this.fetchListenerEnv = env;\n // Default timeout of `Infinity`\n this._networkTimeoutSeconds = options.networkTimeoutSeconds || Infinity;\n }\n override async _handle(request: Request) {\n const cache = await caches.open(this.cacheName);\n try {\n const response = await this.fetchAndCache(request);\n return response;", "score": 16.239458292398908 }, { "filename": "src/strategy/networkFirst.ts", "retrieved_chunk": " request: updatedRequest\n });\n }\n }\n const fetchPromise = fetcher(updatedRequest).catch((err) => {\n for (const plugin of this.plugins) {\n if (plugin.fetchDidFail)\n plugin.fetchDidFail({\n request: updatedRequest,\n error: err as unknown as Error", "score": 14.406729562345276 }, { "filename": "src/strategy/cacheFirst.ts", "retrieved_chunk": " for (const plugin of this.plugins) {\n if (plugin.cacheDidUpdate) {\n plugin.cacheDidUpdate({\n cacheName: this.cacheName,\n request,\n oldResponse,\n newResponse\n });\n }\n }", "score": 14.116734153323959 } ]
typescript
for (let plugin of this.plugins) {
import { toError } from '../core/helper.js'; import { CacheStrategy } from './strategy.js'; import { CacheStrategyOptions, FetchListenerEnv } from './types.js'; export interface NetworkFirstOptions extends CacheStrategyOptions { networkTimeoutSeconds?: number; } export class NetworkFirst extends CacheStrategy { private fetchListenerEnv: FetchListenerEnv; private readonly _networkTimeoutSeconds: number; constructor(options: NetworkFirstOptions, env: FetchListenerEnv = {}) { super(options); this.fetchListenerEnv = env; // Default timeout of `Infinity` this._networkTimeoutSeconds = options.networkTimeoutSeconds || Infinity; } override async _handle(request: Request) { const cache = await caches.open(this.cacheName); try { const response = await this.fetchAndCache(request); return response; } catch (error) { let err = toError(error); const cachedResponse = await cache.match(request, this.matchOptions); if (cachedResponse) { const body = cachedResponse.clone().body; const headers = new Headers(cachedResponse.clone().headers); // Safari throws an error if we try to mutate the headers directly const newResponse = new Response(body, { headers: { ...headers, 'X-Remix-Worker': 'yes' }, status: cachedResponse.status, statusText: cachedResponse.statusText }); return newResponse; } // throw error; return new Response(JSON.stringify({ message: 'Network Error' }), { status: 500, headers: { 'X-Remix-Catch': 'yes', 'X-Remix-Worker': 'yes' } }); } } private async fetchAndCache(request: Request): Promise<Response> { const cache = await caches.open(this.cacheName); const timeoutPromise = this._networkTimeoutSeconds !== Infinity ? new Promise<Response>((_, reject) => { setTimeout(() => { reject( new Error( `Network timed out after ${this._networkTimeoutSeconds} seconds` ) ); }, this._networkTimeoutSeconds * 1000); }) : null; const fetcher = this.fetchListenerEnv.state?.fetcher || fetch; let updatedRequest = request.clone(); for (const plugin of this.plugins) { if (plugin.requestWillFetch) { updatedRequest = await plugin.requestWillFetch({ request: updatedRequest }); } }
const fetchPromise = fetcher(updatedRequest).catch((err) => {
for (const plugin of this.plugins) { if (plugin.fetchDidFail) plugin.fetchDidFail({ request: updatedRequest, error: err as unknown as Error }); } }); let response = timeoutPromise ? await Promise.race([fetchPromise, timeoutPromise]) : await fetchPromise; // If the fetch was successful, then proceed along else throw an error if (response) { // `fetchDidSucceed` performs some changes to response so store it elsewhere // to avoid overtyping original variable let updatedResponse: Response = response.clone(); for (const plugin of this.plugins) { if (plugin.fetchDidSucceed) { updatedResponse = await plugin.fetchDidSucceed({ request: updatedRequest, response: updatedResponse }); } } // `null` can be returned here to avoid caching resources. Hence store in // a new variable that can be checked for if null. let aboutToBeCachedResponse: Response | null = updatedResponse; for (const plugin of this.plugins) { if (plugin.cacheWillUpdate) { aboutToBeCachedResponse = await plugin.cacheWillUpdate({ request: updatedRequest, response: aboutToBeCachedResponse! }); if (!aboutToBeCachedResponse) { break; } } } // If response wasn't null, update cache and return the response if (aboutToBeCachedResponse) { await cache.put(request, response.clone()); for (const plugin of this.plugins) { if (plugin.cacheDidUpdate) { await plugin.cacheDidUpdate({ request: updatedRequest, cacheName: this.cacheName, newResponse: updatedResponse }); } } return aboutToBeCachedResponse; } return updatedResponse; } throw new Error('No response received from fetch: Timeout'); } }
src/strategy/networkFirst.ts
remix-pwa-sw-eb66466
[ { "filename": "src/strategy/cacheFirst.ts", "retrieved_chunk": " let response = await fetch(req).catch((err) => {\n for (const plugin of this.plugins) {\n if (plugin.fetchDidFail) {\n plugin.fetchDidFail({\n request: req.clone(),\n error: err\n });\n }\n }\n });", "score": 41.98756329709793 }, { "filename": "src/strategy/networkOnly.ts", "retrieved_chunk": " });\n }\n }\n const fetchPromise: Response = await fetcher(request);\n const response = (await Promise.race([\n fetchPromise,\n timeoutPromise\n ])) as Response;\n if (response) {\n for (const plugin of this.plugins) {", "score": 41.84009442491669 }, { "filename": "src/strategy/cacheFirst.ts", "retrieved_chunk": " }\n return null;\n }\n private async getFromNetwork(request: Request): Promise<Response | null> {\n let req: Request = request.clone();\n for (const plugin of this.plugins) {\n if (plugin.requestWillFetch) {\n req = await plugin.requestWillFetch({ request: req });\n }\n }", "score": 38.389597037990086 }, { "filename": "src/strategy/networkOnly.ts", "retrieved_chunk": " } seconds`\n )\n );\n }, this._networkTimeoutSeconds * 1000);\n });\n try {\n for (let plugin of this.plugins) {\n if (plugin.requestWillFetch) {\n plugin.requestWillFetch({\n request", "score": 37.03784185705745 }, { "filename": "src/strategy/networkOnly.ts", "retrieved_chunk": " return fetch(request);\n }\n // `fetcher` is a custom fetch function that can de defined and passed to the constructor or just regular fetch\n const fetcher = this.fetchListenerEnv.state!.fetcher || fetch;\n const timeoutPromise = new Promise((_, reject) => {\n setTimeout(() => {\n reject(\n new Error(\n `Network request timed out after ${\n this._networkTimeoutSeconds * 1000", "score": 31.80297748257453 } ]
typescript
const fetchPromise = fetcher(updatedRequest).catch((err) => {
import { logger } from '../core/logger.js'; import { MessageHandler } from './message.js'; import type { MessageHandlerParams } from './message.js'; export interface RemixNavigationHandlerOptions extends MessageHandlerParams { dataCacheName: string; documentCacheName: string; } export class RemixNavigationHandler extends MessageHandler { dataCacheName: string; documentCacheName: string; constructor({ plugins, dataCacheName, documentCacheName, state }: RemixNavigationHandlerOptions) { super({ plugins, state }); this.dataCacheName = dataCacheName; this.documentCacheName = documentCacheName; this._handleMessage = this._handleMessage.bind(this); } override async _handleMessage( event: ExtendableMessageEvent ): Promise<void> { const { data } = event; let DATA, PAGES; DATA = this.dataCacheName; PAGES = this.documentCacheName; this.runPlugins("messageDidReceive", { event, }) let cachePromises: Map<string, Promise<void>> = new Map(); if (data.type === 'REMIX_NAVIGATION') { let { isMount, location, matches, manifest } = data; let documentUrl = location.pathname + location.search + location.hash; let [dataCache, documentCache, existingDocument] = await Promise.all([ caches.open(DATA), caches.open(PAGES), caches.match(documentUrl) ]); if (!existingDocument || !isMount) { cachePromises.set( documentUrl, documentCache.add(documentUrl).catch((error) => {
logger.error(`Failed to cache document for ${documentUrl}:`, error);
}) ); } if (isMount) { for (let match of matches) { if (manifest.routes[match.id].hasLoader) { let params = new URLSearchParams(location.search); params.set('_data', match.id); let search = params.toString(); search = search ? `?${search}` : ''; let url = location.pathname + search + location.hash; if (!cachePromises.has(url)) { logger.debug('Caching data for:', url); cachePromises.set( url, dataCache.add(url).catch((error) => { logger.error(`Failed to cache data for ${url}:`, error); }) ); } } } } } await Promise.all(cachePromises.values()); } }
src/message/remixNavigationHandler.ts
remix-pwa-sw-eb66466
[ { "filename": "src/message/precacheHandler.ts", "retrieved_chunk": " ASSET_CACHE = this.assetCacheName;\n this.runPlugins(\"messageDidReceive\", {\n event,\n });\n const cachePromises: Map<string, Promise<void>> = new Map();\n const [dataCache, documentCache, assetCache] = await Promise.all([\n caches.open(DATA_CACHE),\n caches.open(DOCUMENT_CACHE),\n caches.open(ASSET_CACHE),\n ]);", "score": 43.600498204045266 }, { "filename": "src/message/precacheHandler.ts", "retrieved_chunk": " if (cachePromises.has(assetUrl)) {\n continue;\n }\n cachePromises.set(assetUrl, cacheAsset(assetUrl));\n }\n }\n logger.info(\"Caching document:\", pathname);\n cachePromises.set(\n pathname,\n documentCache.add(pathname).catch((error) => {", "score": 36.669495083881564 }, { "filename": "src/message/precacheHandler.ts", "retrieved_chunk": " if (error instanceof TypeError) {\n logger.error(`TypeError when caching document ${pathname}:`, error.message);\n } else if (error instanceof DOMException) {\n logger.error(`DOMException when caching document ${pathname}:`, error.message);\n } else {\n logger.error(`Failed to cache document ${pathname}:`, error);\n }\n })\n );\n }", "score": 23.45635477893891 }, { "filename": "src/strategy/cacheFirst.ts", "retrieved_chunk": " private async updateCache(\n request: Request,\n response: Response\n ): Promise<void> {\n const cache = await caches.open(this.cacheName);\n const oldResponse = await cache.match(request);\n let newResponse: Response | null = response.clone();\n for (const plugin of this.plugins) {\n if (plugin.cacheWillUpdate) {\n newResponse = await plugin.cacheWillUpdate({", "score": 21.987398830309036 }, { "filename": "src/plugins/cache/expirationPlugin.ts", "retrieved_chunk": " async cacheDidUpdate(options: {\n cacheName: string;\n request: Request;\n oldResponse?: Response | undefined;\n newResponse: Response;\n event?: ExtendableEvent | undefined;\n }) {\n const cache = await caches.open(options.cacheName);\n const keys = await cache.keys();\n console.error(keys.length, this.maxEntries);", "score": 20.873777866735978 } ]
typescript
logger.error(`Failed to cache document for ${documentUrl}:`, error);
import type { MessagePlugin } from '../plugins/interfaces/messagePlugin.js'; import type { MessageEnv } from './types.js'; export interface MessageHandlerParams { plugins?: MessagePlugin[]; state?: MessageEnv; } export abstract class MessageHandler { /** * The plugins array is used to run plugins before and after the message handler. * They are passed in when the handler is initialised. */ protected plugins: MessagePlugin[]; /** * The state object is used to pass data between plugins. */ protected state: MessageEnv; constructor({ plugins, state }: MessageHandlerParams = {}) { this.plugins = plugins || []; this.state = state || {}; } /** * The method that handles the message event. * * Takes in the MessageEvent as a mandatory argument as well as an optional * object that can be used to pass further information/data. */ async handle(event: ExtendableMessageEvent, state: Record<string, any> = {}) { await this._handleMessage(event, state); } protected abstract _handleMessage( event: ExtendableMessageEvent, state: Record<string, any> ): Promise<void> | void; /** * Runs the plugins that are passed in when the handler is initialised. */ protected
async runPlugins(hook: keyof MessagePlugin, env: MessageEnv) {
for (const plugin of this.plugins) { if (plugin[hook]) { plugin[hook]!(env); } } } }
src/message/message.ts
remix-pwa-sw-eb66466
[ { "filename": "src/plugins/interfaces/messagePlugin.ts", "retrieved_chunk": "import { MessageEnv } from '../../message/types.js';\n/**\n * A plugin that can be used to modify the message environment\n */\nexport interface MessagePlugin {\n /**\n * A function that is called when a message is received\n */\n messageDidReceive?: (env: MessageEnv) => void;\n /**", "score": 28.322782574799316 }, { "filename": "src/message/remixNavigationHandler.ts", "retrieved_chunk": " }\n override async _handleMessage(\n event: ExtendableMessageEvent\n ): Promise<void> {\n const { data } = event;\n let DATA, PAGES;\n DATA = this.dataCacheName;\n PAGES = this.documentCacheName;\n this.runPlugins(\"messageDidReceive\", {\n event,", "score": 26.18445973003917 }, { "filename": "src/message/types.ts", "retrieved_chunk": "/**\n * @fileoverview Global typings for `message` sub-module\n */\nexport interface MessageEnv {\n event?: ExtendableMessageEvent;\n state?: Record<string, any>;\n}", "score": 26.01527074124108 }, { "filename": "src/plugins/interfaces/messagePlugin.ts", "retrieved_chunk": " * A function that is called before a message is sent\n * or broadcasted back to the client\n */\n messageWillSend?: (env: MessageEnv) => void;\n}", "score": 24.077428674330605 }, { "filename": "src/message/precacheHandler.ts", "retrieved_chunk": " this.dataCacheName = dataCacheName;\n this.documentCacheName = documentCacheName;\n this.assetCacheName = assetCacheName;\n this._handleMessage = this._handleMessage.bind(this);\n this._ignoredFiles = state?.ignoredRoutes || null;\n }\n override async _handleMessage(event: ExtendableMessageEvent): Promise<void> {\n let DATA_CACHE, DOCUMENT_CACHE, ASSET_CACHE;\n DATA_CACHE = this.dataCacheName;\n DOCUMENT_CACHE = this.documentCacheName;", "score": 21.39156397539036 } ]
typescript
async runPlugins(hook: keyof MessagePlugin, env: MessageEnv) {
import type { MessagePlugin } from '../plugins/interfaces/messagePlugin.js'; import type { MessageEnv } from './types.js'; export interface MessageHandlerParams { plugins?: MessagePlugin[]; state?: MessageEnv; } export abstract class MessageHandler { /** * The plugins array is used to run plugins before and after the message handler. * They are passed in when the handler is initialised. */ protected plugins: MessagePlugin[]; /** * The state object is used to pass data between plugins. */ protected state: MessageEnv; constructor({ plugins, state }: MessageHandlerParams = {}) { this.plugins = plugins || []; this.state = state || {}; } /** * The method that handles the message event. * * Takes in the MessageEvent as a mandatory argument as well as an optional * object that can be used to pass further information/data. */ async handle(event: ExtendableMessageEvent, state: Record<string, any> = {}) { await this._handleMessage(event, state); } protected abstract _handleMessage( event: ExtendableMessageEvent, state: Record<string, any> ): Promise<void> | void; /** * Runs the plugins that are passed in when the handler is initialised. */ protected async runPlugins(
hook: keyof MessagePlugin, env: MessageEnv) {
for (const plugin of this.plugins) { if (plugin[hook]) { plugin[hook]!(env); } } } }
src/message/message.ts
remix-pwa-sw-eb66466
[ { "filename": "src/plugins/interfaces/messagePlugin.ts", "retrieved_chunk": "import { MessageEnv } from '../../message/types.js';\n/**\n * A plugin that can be used to modify the message environment\n */\nexport interface MessagePlugin {\n /**\n * A function that is called when a message is received\n */\n messageDidReceive?: (env: MessageEnv) => void;\n /**", "score": 28.322782574799316 }, { "filename": "src/message/remixNavigationHandler.ts", "retrieved_chunk": " }\n override async _handleMessage(\n event: ExtendableMessageEvent\n ): Promise<void> {\n const { data } = event;\n let DATA, PAGES;\n DATA = this.dataCacheName;\n PAGES = this.documentCacheName;\n this.runPlugins(\"messageDidReceive\", {\n event,", "score": 26.18445973003917 }, { "filename": "src/message/types.ts", "retrieved_chunk": "/**\n * @fileoverview Global typings for `message` sub-module\n */\nexport interface MessageEnv {\n event?: ExtendableMessageEvent;\n state?: Record<string, any>;\n}", "score": 26.01527074124108 }, { "filename": "src/plugins/interfaces/messagePlugin.ts", "retrieved_chunk": " * A function that is called before a message is sent\n * or broadcasted back to the client\n */\n messageWillSend?: (env: MessageEnv) => void;\n}", "score": 24.077428674330605 }, { "filename": "src/message/precacheHandler.ts", "retrieved_chunk": " this.dataCacheName = dataCacheName;\n this.documentCacheName = documentCacheName;\n this.assetCacheName = assetCacheName;\n this._handleMessage = this._handleMessage.bind(this);\n this._ignoredFiles = state?.ignoredRoutes || null;\n }\n override async _handleMessage(event: ExtendableMessageEvent): Promise<void> {\n let DATA_CACHE, DOCUMENT_CACHE, ASSET_CACHE;\n DATA_CACHE = this.dataCacheName;\n DOCUMENT_CACHE = this.documentCacheName;", "score": 21.39156397539036 } ]
typescript
hook: keyof MessagePlugin, env: MessageEnv) {
import { logger } from '../core/logger.js'; import { MessageHandler } from './message.js'; import type { MessageHandlerParams } from './message.js'; export interface RemixNavigationHandlerOptions extends MessageHandlerParams { dataCacheName: string; documentCacheName: string; } export class RemixNavigationHandler extends MessageHandler { dataCacheName: string; documentCacheName: string; constructor({ plugins, dataCacheName, documentCacheName, state }: RemixNavigationHandlerOptions) { super({ plugins, state }); this.dataCacheName = dataCacheName; this.documentCacheName = documentCacheName; this._handleMessage = this._handleMessage.bind(this); } override async _handleMessage( event: ExtendableMessageEvent ): Promise<void> { const { data } = event; let DATA, PAGES; DATA = this.dataCacheName; PAGES = this.documentCacheName; this.runPlugins("messageDidReceive", { event, }) let cachePromises: Map<string, Promise<void>> = new Map(); if (data.type === 'REMIX_NAVIGATION') { let { isMount, location, matches, manifest } = data; let documentUrl = location.pathname + location.search + location.hash; let [dataCache, documentCache, existingDocument] = await Promise.all([ caches.open(DATA), caches.open(PAGES), caches.match(documentUrl) ]); if (!existingDocument || !isMount) { cachePromises.set( documentUrl, documentCache.add(documentUrl).catch((error) => { logger.error(`Failed to cache document for ${documentUrl}:`, error); }) ); } if (isMount) { for (let match of matches) { if (manifest.routes[match.id].hasLoader) { let params = new URLSearchParams(location.search); params.set('_data', match.id); let search = params.toString(); search = search ? `?${search}` : ''; let url = location.pathname + search + location.hash; if (!cachePromises.has(url)) { logger.
debug('Caching data for:', url);
cachePromises.set( url, dataCache.add(url).catch((error) => { logger.error(`Failed to cache data for ${url}:`, error); }) ); } } } } } await Promise.all(cachePromises.values()); } }
src/message/remixNavigationHandler.ts
remix-pwa-sw-eb66466
[ { "filename": "src/message/precacheHandler.ts", "retrieved_chunk": " function cacheLoaderData(route: EntryRoute) {\n const pathname = getPathname(route);\n const params = new URLSearchParams({ _data: route.id });\n const search = `?${params.toString()}`;\n const url = pathname + search;\n if (!cachePromises.has(url)) {\n logger.debug(\"caching loader data\", url);\n cachePromises.set(\n url,\n dataCache.add(url).catch((error) => {", "score": 105.1221056326125 }, { "filename": "src/react/useSWEffect.ts", "retrieved_chunk": " isMount: mounted,\n location,\n matches: matches.filter(filteredMatches).map(sanitizeHandleObject),\n manifest: window.__remixManifest,\n });\n } else {\n let listener = async () => {\n await navigator.serviceWorker.ready;\n navigator.serviceWorker.controller?.postMessage({\n type: \"REMIX_NAVIGATION\",", "score": 26.09492528278032 }, { "filename": "src/message/precacheHandler.ts", "retrieved_chunk": " if (cachePromises.has(assetUrl)) {\n continue;\n }\n cachePromises.set(assetUrl, cacheAsset(assetUrl));\n }\n }\n logger.info(\"Caching document:\", pathname);\n cachePromises.set(\n pathname,\n documentCache.add(pathname).catch((error) => {", "score": 25.912532045566472 }, { "filename": "src/message/precacheHandler.ts", "retrieved_chunk": " const manifest: AssetsManifest = event.data.manifest;\n const routes = Object.values(manifest?.routes || {});\n for (const route of routes) {\n if (route.id.includes(\"$\")) {\n logger.info(\"Skipping parametrized route:\", route.id);\n continue;\n }\n // Handle ignored routes \n if (Array.isArray(this._ignoredFiles)) {\n // E.g '/dashboard' or 'dashboard'", "score": 24.731826953526735 }, { "filename": "src/react/useSWEffect.ts", "retrieved_chunk": " isMount: mounted,\n location,\n matches: matches.filter(filteredMatches).map(sanitizeHandleObject),\n manifest: window.__remixManifest,\n });\n };\n navigator.serviceWorker.addEventListener(\"controllerchange\", listener);\n return () => {\n navigator.serviceWorker.removeEventListener(\n \"controllerchange\",", "score": 20.513344307218155 } ]
typescript
debug('Caching data for:', url);
import { Module } from '@nestjs/common'; import { ConfigModule, ConfigService } from '@nestjs/config'; import { APP_GUARD } from '@nestjs/core'; import { CqrsModule } from '@nestjs/cqrs'; import { JwtModule } from '@nestjs/jwt'; import iamConfig from './configs/iam.config'; import { AuthController } from './controllers/auth.controller'; import { AccessTokenGenerator } from './generators/access-token.generator'; import { PasswordlessLoginTokenGenerator } from './generators/passwordless-login-token.generator'; import { RefreshTokenGenerator } from './generators/refresh-token.generator'; import { AccessTokenGuard } from './guards/access-token.guard'; import { AuthGuard } from './guards/auth.guard'; import { NoneGuard } from './guards/none.guard'; import { RolesGuard } from './guards/roles.guard'; import { BcryptHasher } from './hashers/bcrypt.hasher'; import { ConfigurableModuleClass } from './iam.module-definition'; import { LoginProcessor } from './processors/login.processor'; import { LogoutProcessor } from './processors/logout.processor'; import { PasswordlessLoginRequestProcessor } from './processors/passwordless-login-request.processor'; @Module({ imports: [ ConfigModule.forFeature(iamConfig), CqrsModule, JwtModule.registerAsync({ imports: [ConfigModule], useFactory: async (config: ConfigService) => ({ secret: config.get('iam.jwt.secret'), signOptions: { audience: config.get('iam.jwt.audience'), issuer: config.get('iam.jwt.issuer'), }, }), inject: [ConfigService], }), ], providers: [ AccessTokenGenerator, AccessTokenGuard, AuthGuard, BcryptHasher, LoginProcessor, LogoutProcessor, NoneGuard, PasswordlessLoginRequestProcessor, PasswordlessLoginTokenGenerator, RefreshTokenGenerator, RolesGuard, { provide: APP_GUARD, useClass: AuthGuard, }, { provide: APP_GUARD, useClass: RolesGuard, }, ], exports: [BcryptHasher, LoginProcessor], controllers: [AuthController], })
export class IamModule extends ConfigurableModuleClass {}
src/iam.module.ts
fastnloud-nest-iam-463230d
[ { "filename": "src/controllers/auth.controller.ts", "retrieved_chunk": "import { LogoutProcessor } from '../processors/logout.processor';\nimport { PasswordlessLoginRequestProcessor } from '../processors/passwordless-login-request.processor';\n@Controller()\n@ApiTags('Auth')\nexport class AuthController {\n constructor(\n private readonly eventBus: EventBus,\n private readonly hasher: BcryptHasher,\n private readonly loginProcessor: LoginProcessor,\n private readonly logoutProcessor: LogoutProcessor,", "score": 10.542104056448201 }, { "filename": "src/guards/roles.guard.ts", "retrieved_chunk": "import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';\nimport { Reflector } from '@nestjs/core';\nimport { Observable } from 'rxjs';\nimport {\n IAM_REQUEST_USER_KEY,\n IAM_ROLES_KEY,\n} from '../constants/iam.constants';\nimport { IActiveUser } from '../interfaces/active-user.interface';\n@Injectable()\nexport class RolesGuard implements CanActivate {", "score": 5.2994371434709056 }, { "filename": "src/iam.module-definition.ts", "retrieved_chunk": "import { ConfigurableModuleBuilder } from '@nestjs/common';\nimport { IModuleOptions } from './interfaces/module-options.interface';\nexport const { ConfigurableModuleClass, MODULE_OPTIONS_TOKEN } =\n new ConfigurableModuleBuilder<IModuleOptions>()\n .setClassMethodName('register')\n .build();", "score": 5.011291671820732 }, { "filename": "src/processors/login.processor.ts", "retrieved_chunk": "import { IUser } from '../interfaces/user.interface';\nimport { TokenModel } from '../models/token.model';\n@Injectable()\nexport class LoginProcessor {\n public constructor(\n private readonly accessTokenGenerator: AccessTokenGenerator,\n private readonly refreshTokenGenerator: RefreshTokenGenerator,\n @Inject(MODULE_OPTIONS_TOKEN)\n private readonly moduleOptions: IModuleOptions,\n @Inject(iamConfig.KEY)", "score": 4.605874517714911 }, { "filename": "src/controllers/auth.controller.ts", "retrieved_chunk": "import { AuthType } from '../enums/auth-type.enum';\nimport { TokenType } from '../enums/token-type.enum';\nimport { LoggedInEvent } from '../events/logged-in.event';\nimport { LoggedOutEvent } from '../events/logged-out.event';\nimport { BcryptHasher } from '../hashers/bcrypt.hasher';\nimport { MODULE_OPTIONS_TOKEN } from '../iam.module-definition';\nimport { IActiveUser } from '../interfaces/active-user.interface';\nimport { IModuleOptions } from '../interfaces/module-options.interface';\nimport { IRefreshTokenJwtPayload } from '../interfaces/refresh-token-jwt-payload.interface';\nimport { LoginProcessor } from '../processors/login.processor';", "score": 3.6567741400421303 } ]
typescript
export class IamModule extends ConfigurableModuleClass {}
import { logger } from "../../core/logger"; import { CacheQueryMatchOptions } from "../../strategy/types"; import { StrategyPlugin } from "../interfaces/strategyPlugin"; export class ExpirationPlugin implements StrategyPlugin { private readonly maxEntries: number; private readonly maxAgeSeconds: number; constructor({ maxEntries, maxAgeSeconds, }: { maxEntries?: number; maxAgeSeconds?: number } = {}) { this.maxAgeSeconds = maxAgeSeconds || 30 * 24 * 3_600; this.maxEntries = maxEntries || Infinity; } async cachedResponseWillBeUsed(options: { cacheName: string; request: Request; matchOptions: CacheQueryMatchOptions; cachedResponse: Response; event?: ExtendableEvent | undefined; }): Promise<Response | null> { const now = Date.now(); const expirationDate = options.cachedResponse.headers.get("X-Expires"); const newResponse = options.cachedResponse.clone() const headers = new Headers(newResponse.headers) const modifedResponse = new Response(newResponse.body, { status: newResponse.status, statusText: newResponse.statusText, headers }) if (expirationDate) { const elapsedTime = new Date(expirationDate).getTime() - now; if (elapsedTime < 0) { const cache = await caches.open(options.cacheName); await cache.delete(options.request, options.matchOptions); console.log("cacheResponseWillBeUsed", options.request.url); return options.cachedResponse; } modifedResponse.headers.set( "X-Access-Time", new Date(now).toUTCString() ); return modifedResponse } else { modifedResponse.headers.set( "X-Access-Time", new Date(now).toUTCString() ); return modifedResponse; } } async cacheWillUpdate(options: { response: Response; request: Request; event?: ExtendableEvent | undefined; }): Promise<Response | null> { const now = Date.now(); console.log("cacheWillUpdate", options.request.url); let newResponse = options.response.clone(); const headers = new Headers(newResponse.headers) const modifedResponse = new Response(newResponse.body, { status: newResponse.status, statusText: newResponse.statusText, headers }) modifedResponse.headers.set( "X-Expires", new Date(now + this.maxAgeSeconds * 1_000).toUTCString() ); return modifedResponse; } async cacheDidUpdate(options: { cacheName: string; request: Request; oldResponse?: Response | undefined; newResponse: Response; event?: ExtendableEvent | undefined; }) { const cache = await caches.open(options.cacheName); const keys = await cache.keys(); console.error(keys.length, this.maxEntries); if (keys.length > this.maxEntries) {
logger.debug("Cache is full, removing oldest entry");
this.removeLRUEntry(options.cacheName); } } async removeLRUEntry(cacheName: string) { const cache = await caches.open(cacheName); const keys = await cache.keys(); let oldestEntry: Response | null = null; for (const key of keys) { const entry = await cache.match(key); if (!entry) { continue; } if (!oldestEntry) { oldestEntry = entry; continue; } const oldestEntryDate = oldestEntry.headers.get("X-Access-Time"); const entryDate = entry.headers.get("X-Access-Time"); if (!oldestEntryDate || !entryDate) { continue; } if (new Date(oldestEntryDate).getTime() > new Date(entryDate).getTime()) { oldestEntry = entry; } } if (oldestEntry) { await cache.delete(oldestEntry.url); } } }
src/plugins/cache/expirationPlugin.ts
remix-pwa-sw-eb66466
[ { "filename": "src/strategy/cacheFirst.ts", "retrieved_chunk": " private async updateCache(\n request: Request,\n response: Response\n ): Promise<void> {\n const cache = await caches.open(this.cacheName);\n const oldResponse = await cache.match(request);\n let newResponse: Response | null = response.clone();\n for (const plugin of this.plugins) {\n if (plugin.cacheWillUpdate) {\n newResponse = await plugin.cacheWillUpdate({", "score": 32.35532123355476 }, { "filename": "src/plugins/interfaces/strategyPlugin.ts", "retrieved_chunk": " cacheDidUpdate?: (options: {\n cacheName: string;\n request: Request;\n oldResponse?: Response;\n newResponse: Response;\n event?: ExtendableEvent;\n }) => Promise<void>;\n // Called before a cached response is used to respond to a fetch event.\n /**\n * This is called just before a response from a cache is used, which allows you to examine that ", "score": 25.954397513472614 }, { "filename": "src/strategy/networkFirst.ts", "retrieved_chunk": " super(options);\n this.fetchListenerEnv = env;\n // Default timeout of `Infinity`\n this._networkTimeoutSeconds = options.networkTimeoutSeconds || Infinity;\n }\n override async _handle(request: Request) {\n const cache = await caches.open(this.cacheName);\n try {\n const response = await this.fetchAndCache(request);\n return response;", "score": 23.589801906736234 }, { "filename": "src/strategy/networkFirst.ts", "retrieved_chunk": " }\n private async fetchAndCache(request: Request): Promise<Response> {\n const cache = await caches.open(this.cacheName);\n const timeoutPromise =\n this._networkTimeoutSeconds !== Infinity\n ? new Promise<Response>((_, reject) => {\n setTimeout(() => {\n reject(\n new Error(\n `Network timed out after ${this._networkTimeoutSeconds} seconds`", "score": 23.477207873059875 }, { "filename": "src/plugins/interfaces/strategyPlugin.ts", "retrieved_chunk": " cacheWillUpdate?: (options: {\n response: Response;\n request: Request;\n event?: ExtendableEvent;\n }) => Promise<Response | null>;\n // Called after a response is stored in the cache.\n /**\n * Called when a new entry is added to a cache or if an existing entry is updated. \n * Plugins that use this method may be useful when you want to perform an action after a cache update.\n */", "score": 23.14763232715327 } ]
typescript
logger.debug("Cache is full, removing oldest entry");
import { Module } from '@nestjs/common'; import { ConfigModule, ConfigService } from '@nestjs/config'; import { APP_GUARD } from '@nestjs/core'; import { CqrsModule } from '@nestjs/cqrs'; import { JwtModule } from '@nestjs/jwt'; import iamConfig from './configs/iam.config'; import { AuthController } from './controllers/auth.controller'; import { AccessTokenGenerator } from './generators/access-token.generator'; import { PasswordlessLoginTokenGenerator } from './generators/passwordless-login-token.generator'; import { RefreshTokenGenerator } from './generators/refresh-token.generator'; import { AccessTokenGuard } from './guards/access-token.guard'; import { AuthGuard } from './guards/auth.guard'; import { NoneGuard } from './guards/none.guard'; import { RolesGuard } from './guards/roles.guard'; import { BcryptHasher } from './hashers/bcrypt.hasher'; import { ConfigurableModuleClass } from './iam.module-definition'; import { LoginProcessor } from './processors/login.processor'; import { LogoutProcessor } from './processors/logout.processor'; import { PasswordlessLoginRequestProcessor } from './processors/passwordless-login-request.processor'; @Module({ imports: [ ConfigModule.forFeature(iamConfig), CqrsModule, JwtModule.registerAsync({ imports: [ConfigModule], useFactory: async (config: ConfigService) => ({ secret: config.get('iam.jwt.secret'), signOptions: { audience: config.get('iam.jwt.audience'), issuer: config.get('iam.jwt.issuer'), }, }), inject: [ConfigService], }), ], providers: [ AccessTokenGenerator, AccessTokenGuard, AuthGuard, BcryptHasher, LoginProcessor, LogoutProcessor, NoneGuard, PasswordlessLoginRequestProcessor, PasswordlessLoginTokenGenerator, RefreshTokenGenerator, RolesGuard, { provide: APP_GUARD, useClass: AuthGuard, }, { provide: APP_GUARD, useClass: RolesGuard, }, ], exports: [BcryptHasher, LoginProcessor], controllers: [AuthController], }) export class IamModule extends
ConfigurableModuleClass {}
src/iam.module.ts
fastnloud-nest-iam-463230d
[ { "filename": "src/controllers/auth.controller.ts", "retrieved_chunk": "import { LogoutProcessor } from '../processors/logout.processor';\nimport { PasswordlessLoginRequestProcessor } from '../processors/passwordless-login-request.processor';\n@Controller()\n@ApiTags('Auth')\nexport class AuthController {\n constructor(\n private readonly eventBus: EventBus,\n private readonly hasher: BcryptHasher,\n private readonly loginProcessor: LoginProcessor,\n private readonly logoutProcessor: LogoutProcessor,", "score": 10.542104056448201 }, { "filename": "src/guards/roles.guard.ts", "retrieved_chunk": "import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';\nimport { Reflector } from '@nestjs/core';\nimport { Observable } from 'rxjs';\nimport {\n IAM_REQUEST_USER_KEY,\n IAM_ROLES_KEY,\n} from '../constants/iam.constants';\nimport { IActiveUser } from '../interfaces/active-user.interface';\n@Injectable()\nexport class RolesGuard implements CanActivate {", "score": 5.2994371434709056 }, { "filename": "src/iam.module-definition.ts", "retrieved_chunk": "import { ConfigurableModuleBuilder } from '@nestjs/common';\nimport { IModuleOptions } from './interfaces/module-options.interface';\nexport const { ConfigurableModuleClass, MODULE_OPTIONS_TOKEN } =\n new ConfigurableModuleBuilder<IModuleOptions>()\n .setClassMethodName('register')\n .build();", "score": 5.011291671820732 }, { "filename": "src/processors/login.processor.ts", "retrieved_chunk": "import { IUser } from '../interfaces/user.interface';\nimport { TokenModel } from '../models/token.model';\n@Injectable()\nexport class LoginProcessor {\n public constructor(\n private readonly accessTokenGenerator: AccessTokenGenerator,\n private readonly refreshTokenGenerator: RefreshTokenGenerator,\n @Inject(MODULE_OPTIONS_TOKEN)\n private readonly moduleOptions: IModuleOptions,\n @Inject(iamConfig.KEY)", "score": 4.605874517714911 }, { "filename": "src/controllers/auth.controller.ts", "retrieved_chunk": "import { AuthType } from '../enums/auth-type.enum';\nimport { TokenType } from '../enums/token-type.enum';\nimport { LoggedInEvent } from '../events/logged-in.event';\nimport { LoggedOutEvent } from '../events/logged-out.event';\nimport { BcryptHasher } from '../hashers/bcrypt.hasher';\nimport { MODULE_OPTIONS_TOKEN } from '../iam.module-definition';\nimport { IActiveUser } from '../interfaces/active-user.interface';\nimport { IModuleOptions } from '../interfaces/module-options.interface';\nimport { IRefreshTokenJwtPayload } from '../interfaces/refresh-token-jwt-payload.interface';\nimport { LoginProcessor } from '../processors/login.processor';", "score": 3.6567741400421303 } ]
typescript
ConfigurableModuleClass {}
import { Body, Controller, Get, HttpCode, HttpStatus, Inject, NotFoundException, Param, Post, Req, Res, UnauthorizedException, } from '@nestjs/common'; import { ConfigType } from '@nestjs/config'; import { EventBus } from '@nestjs/cqrs'; import { JwtService } from '@nestjs/jwt'; import { ApiNoContentResponse, ApiOkResponse, ApiOperation, ApiTags, } from '@nestjs/swagger'; import { Request, Response } from 'express'; import iamConfig from '../configs/iam.config'; import { ActiveUser } from '../decorators/active-user.decorator'; import { Auth } from '../decorators/auth.decorator'; import { LoginRequestDto } from '../dtos/login-request.dto'; import { LoginResponseDto } from '../dtos/login-response.dto'; import { PasswordlessLoginRequestRequestDto } from '../dtos/passwordless-login-request-request.dto'; import { AuthType } from '../enums/auth-type.enum'; import { TokenType } from '../enums/token-type.enum'; import { LoggedInEvent } from '../events/logged-in.event'; import { LoggedOutEvent } from '../events/logged-out.event'; import { BcryptHasher } from '../hashers/bcrypt.hasher'; import { MODULE_OPTIONS_TOKEN } from '../iam.module-definition'; import { IActiveUser } from '../interfaces/active-user.interface'; import { IModuleOptions } from '../interfaces/module-options.interface'; import { IRefreshTokenJwtPayload } from '../interfaces/refresh-token-jwt-payload.interface'; import { LoginProcessor } from '../processors/login.processor'; import { LogoutProcessor } from '../processors/logout.processor'; import { PasswordlessLoginRequestProcessor } from '../processors/passwordless-login-request.processor'; @Controller() @ApiTags('Auth') export class AuthController { constructor( private readonly eventBus: EventBus, private readonly hasher: BcryptHasher, private readonly loginProcessor: LoginProcessor, private readonly logoutProcessor: LogoutProcessor, private readonly passwordlessLoginRequestProcessor: PasswordlessLoginRequestProcessor, private readonly jwtService: JwtService, @Inject(MODULE_OPTIONS_TOKEN) private readonly moduleOptions: IModuleOptions, @Inject(iamConfig.KEY) private readonly config: ConfigType<typeof iamConfig>, ) {} @HttpCode(HttpStatus.OK) @ApiOperation({ operationId: 'authLogin' }) @ApiOkResponse({ type: LoginResponseDto }) @Auth(AuthType.None) @Post('/auth/login') async login( @Body() request: LoginRequestDto, @Res({ passthrough: true }) response: Response, ): Promise<LoginResponseDto> { if (!this.config.auth.methods.includes('basic')) { throw new NotFoundException(); } try { const user = await this.moduleOptions.authService.checkUser( request.username, );
if (!(await this.hasher.compare(request.password, user.getPassword()))) {
throw new UnauthorizedException(); } const login = await this.loginProcessor.process(user, response); this.eventBus.publish(new LoggedInEvent(user.getId())); return { accessToken: login.accessToken, refreshToken: login.refreshToken, }; } catch { throw new UnauthorizedException(); } } @HttpCode(HttpStatus.OK) @ApiOperation({ operationId: 'authPasswordlessLogin' }) @ApiOkResponse({ type: LoginResponseDto }) @Auth(AuthType.None) @Get('/auth/passwordless_login/:id') async passwordlessLogin( @Param('id') tokenId: string, @Req() request: Request, @Res({ passthrough: true }) response: Response, ): Promise<LoginResponseDto> { if (!this.config.auth.methods.includes('passwordless')) { throw new NotFoundException(); } const requestId = request.cookies[TokenType.PasswordlessLoginToken]; if (!requestId) { throw new UnauthorizedException(); } try { const token = await this.moduleOptions.authService.checkToken( tokenId, TokenType.PasswordlessLoginToken, requestId, ); const user = await this.moduleOptions.authService.getUser( token.getUserId(), ); await this.moduleOptions.authService.checkUser(user.getUsername()); await this.moduleOptions.authService.removeToken(tokenId); const login = await this.loginProcessor.process(user, response); return { accessToken: login.accessToken, refreshToken: login.refreshToken, }; } catch { throw new UnauthorizedException(); } } @HttpCode(HttpStatus.NO_CONTENT) @ApiOperation({ operationId: 'authPasswordlessLoginRequest' }) @ApiNoContentResponse() @Auth(AuthType.None) @Post('/auth/passwordless_login') async passwordlessLoginRequest( @Body() request: PasswordlessLoginRequestRequestDto, @Res({ passthrough: true }) response: Response, ): Promise<void> { if (!this.config.auth.methods.includes('passwordless')) { throw new NotFoundException(); } try { const user = await this.moduleOptions.authService.checkUser( request.username, ); await this.passwordlessLoginRequestProcessor.process(user, response); } catch {} } @HttpCode(HttpStatus.OK) @ApiOperation({ operationId: 'authRefreshTokens' }) @ApiOkResponse({ type: LoginResponseDto }) @Auth(AuthType.None) @Get('/auth/refresh_tokens') async refreshTokens( @Req() request: Request, @Res({ passthrough: true }) response: Response, ): Promise<LoginResponseDto> { try { const refreshTokenJwtPayload: IRefreshTokenJwtPayload = await this.jwtService.verifyAsync( request.cookies[TokenType.RefreshToken], ); await this.moduleOptions.authService.checkToken( refreshTokenJwtPayload.id, TokenType.RefreshToken, ); const user = await this.moduleOptions.authService.getUser( refreshTokenJwtPayload.sub, ); await this.moduleOptions.authService.checkUser(user.getUsername()); await this.moduleOptions.authService.removeToken( refreshTokenJwtPayload.id, ); const login = await this.loginProcessor.process(user, response); return { accessToken: login.accessToken, refreshToken: login.refreshToken, }; } catch { throw new UnauthorizedException(); } } @HttpCode(HttpStatus.NO_CONTENT) @ApiOperation({ operationId: 'authLogout' }) @ApiNoContentResponse() @Auth(AuthType.None) @Get('/auth/logout') async logout( @Req() request: Request, @Res({ passthrough: true }) response: Response, @ActiveUser() activeUser: IActiveUser, ) { await this.logoutProcessor.process(request, response); if (!activeUser) { return; } this.eventBus.publish(new LoggedOutEvent(activeUser.userId)); } }
src/controllers/auth.controller.ts
fastnloud-nest-iam-463230d
[ { "filename": "src/guards/auth.guard.ts", "retrieved_chunk": " const guards = authTypes.map((type) => this.authTypeGuardMap[type]).flat();\n for (const guard of guards) {\n if (await Promise.resolve(guard.canActivate(context))) {\n return true;\n }\n }\n throw new UnauthorizedException();\n }\n}", "score": 25.541886190878294 }, { "filename": "src/processors/login.processor.ts", "retrieved_chunk": " private readonly config: ConfigType<typeof iamConfig>,\n ) {}\n public async process(user: IUser, response: Response): Promise<ILogin> {\n const accessToken = await this.accessTokenGenerator.generate(user);\n const refreshToken = await this.refreshTokenGenerator.generate(user);\n const login = {\n accessToken: accessToken.jwt,\n refreshToken: refreshToken.jwt,\n };\n await this.moduleOptions.authService.saveToken(", "score": 25.49836409122332 }, { "filename": "src/processors/logout.processor.ts", "retrieved_chunk": " const refreshTokenJwtPayload: IRefreshTokenJwtPayload =\n await this.jwtService.verifyAsync(\n request.cookies[TokenType.RefreshToken],\n );\n await this.moduleOptions.authService.removeToken(\n refreshTokenJwtPayload.id,\n );\n } catch {}\n response.clearCookie(TokenType.AccessToken);\n response.clearCookie(TokenType.RefreshToken, {", "score": 24.852311917601124 }, { "filename": "src/processors/passwordless-login-request.processor.ts", "retrieved_chunk": " const requestId = randomUUID();\n const passwordlessLoginToken =\n await this.passwordlessLoginTokenGenerator.generate(user, requestId);\n await this.moduleOptions.authService.saveToken(passwordlessLoginToken);\n response.cookie(TokenType.PasswordlessLoginToken, requestId, {\n secure: this.config.cookie.secure,\n httpOnly: this.config.cookie.httpOnly,\n sameSite: this.config.cookie.sameSite,\n expires: passwordlessLoginToken.getExpiresAt(),\n path: `${this.config.routePathPrefix}/auth`,", "score": 22.326385345498526 }, { "filename": "src/guards/access-token.guard.ts", "retrieved_chunk": "import { IActiveUser } from '../interfaces/active-user.interface';\n@Injectable()\nexport class AccessTokenGuard implements CanActivate {\n constructor(private readonly jwtService: JwtService) {}\n async canActivate(context: ExecutionContext): Promise<boolean> {\n const request = context.switchToHttp().getRequest();\n try {\n const accessTokenJwtPayload: IAccessTokenJwtPayload =\n await this.jwtService.verifyAsync(\n request.cookies[TokenType.AccessToken] ?? '',", "score": 18.17382628397842 } ]
typescript
if (!(await this.hasher.compare(request.password, user.getPassword()))) {
import { toError } from '../core/helper.js'; import { CacheStrategy } from './strategy.js'; import { CacheStrategyOptions, FetchListenerEnv } from './types.js'; export interface NetworkOnlyOptions extends Omit<CacheStrategyOptions, 'cacheName' | 'matchOptions'> { networkTimeoutSeconds?: number; } export class NetworkOnly extends CacheStrategy { private fetchListenerEnv: FetchListenerEnv; private readonly _networkTimeoutSeconds: number; constructor(options: NetworkOnlyOptions = {}, env?: FetchListenerEnv) { // this is gonna come back and bite me. // I need to sort this out quick though //@ts-ignore super(options); this.fetchListenerEnv = env || {}; this._networkTimeoutSeconds = options.networkTimeoutSeconds || 10; } override async _handle(request: Request) { if (request.method !== 'GET') { return fetch(request); } // `fetcher` is a custom fetch function that can de defined and passed to the constructor or just regular fetch const fetcher = this.fetchListenerEnv.state!.fetcher || fetch; const timeoutPromise = new Promise((_, reject) => { setTimeout(() => { reject( new Error( `Network request timed out after ${ this._networkTimeoutSeconds * 1000 } seconds` ) ); }, this._networkTimeoutSeconds * 1000); }); try { for (let plugin of this.plugins) { if (plugin.requestWillFetch) { plugin.requestWillFetch({ request }); } } const fetchPromise: Response = await fetcher(request); const response = (await Promise.race([ fetchPromise, timeoutPromise ])) as Response; if (response) { for (const plugin of this.plugins) { if (plugin.fetchDidSucceed) { await plugin.fetchDidSucceed({ request, response }); } } return response; } // Re-thrown error to be caught by `catch` block throw new Error('Network request failed'); } catch (error) { for (const plugin of this.plugins) { if (plugin.fetchDidFail) { await plugin.fetchDidFail({ request,
error: toError(error) });
} } const headers = { 'X-Remix-Catch': 'yes', 'X-Remix-Worker': 'yes' }; return new Response(JSON.stringify({ message: 'Network Error' }), { status: 500, ...(this.isLoader ? { headers } : {}) }); } } }
src/strategy/networkOnly.ts
remix-pwa-sw-eb66466
[ { "filename": "src/strategy/networkFirst.ts", "retrieved_chunk": " request: updatedRequest\n });\n }\n }\n const fetchPromise = fetcher(updatedRequest).catch((err) => {\n for (const plugin of this.plugins) {\n if (plugin.fetchDidFail)\n plugin.fetchDidFail({\n request: updatedRequest,\n error: err as unknown as Error", "score": 45.12219010470833 }, { "filename": "src/strategy/cacheFirst.ts", "retrieved_chunk": " let response = await fetch(req).catch((err) => {\n for (const plugin of this.plugins) {\n if (plugin.fetchDidFail) {\n plugin.fetchDidFail({\n request: req.clone(),\n error: err\n });\n }\n }\n });", "score": 45.081418775340495 }, { "filename": "src/react/loader.ts", "retrieved_chunk": " }\n });\n } catch (error) {\n // console.error('Service worker registration failed', error);\n }\n }\n if (\n document.readyState === 'complete' ||\n document.readyState === 'interactive'\n ) {", "score": 23.67643602664403 }, { "filename": "src/strategy/networkFirst.ts", "retrieved_chunk": " // a new variable that can be checked for if null.\n let aboutToBeCachedResponse: Response | null = updatedResponse;\n for (const plugin of this.plugins) {\n if (plugin.cacheWillUpdate) {\n aboutToBeCachedResponse = await plugin.cacheWillUpdate({\n request: updatedRequest,\n response: aboutToBeCachedResponse!\n });\n if (!aboutToBeCachedResponse) {\n break;", "score": 23.115184772008035 }, { "filename": "src/strategy/networkFirst.ts", "retrieved_chunk": " let updatedResponse: Response = response.clone();\n for (const plugin of this.plugins) {\n if (plugin.fetchDidSucceed) {\n updatedResponse = await plugin.fetchDidSucceed({\n request: updatedRequest,\n response: updatedResponse\n });\n }\n }\n // `null` can be returned here to avoid caching resources. Hence store in", "score": 22.38392667887776 } ]
typescript
error: toError(error) });
import { Body, Controller, Get, HttpCode, HttpStatus, Inject, NotFoundException, Param, Post, Req, Res, UnauthorizedException, } from '@nestjs/common'; import { ConfigType } from '@nestjs/config'; import { EventBus } from '@nestjs/cqrs'; import { JwtService } from '@nestjs/jwt'; import { ApiNoContentResponse, ApiOkResponse, ApiOperation, ApiTags, } from '@nestjs/swagger'; import { Request, Response } from 'express'; import iamConfig from '../configs/iam.config'; import { ActiveUser } from '../decorators/active-user.decorator'; import { Auth } from '../decorators/auth.decorator'; import { LoginRequestDto } from '../dtos/login-request.dto'; import { LoginResponseDto } from '../dtos/login-response.dto'; import { PasswordlessLoginRequestRequestDto } from '../dtos/passwordless-login-request-request.dto'; import { AuthType } from '../enums/auth-type.enum'; import { TokenType } from '../enums/token-type.enum'; import { LoggedInEvent } from '../events/logged-in.event'; import { LoggedOutEvent } from '../events/logged-out.event'; import { BcryptHasher } from '../hashers/bcrypt.hasher'; import { MODULE_OPTIONS_TOKEN } from '../iam.module-definition'; import { IActiveUser } from '../interfaces/active-user.interface'; import { IModuleOptions } from '../interfaces/module-options.interface'; import { IRefreshTokenJwtPayload } from '../interfaces/refresh-token-jwt-payload.interface'; import { LoginProcessor } from '../processors/login.processor'; import { LogoutProcessor } from '../processors/logout.processor'; import { PasswordlessLoginRequestProcessor } from '../processors/passwordless-login-request.processor'; @Controller() @ApiTags('Auth') export class AuthController { constructor( private readonly eventBus: EventBus, private readonly hasher: BcryptHasher, private readonly loginProcessor: LoginProcessor, private readonly logoutProcessor: LogoutProcessor, private readonly passwordlessLoginRequestProcessor: PasswordlessLoginRequestProcessor, private readonly jwtService: JwtService, @Inject(MODULE_OPTIONS_TOKEN) private readonly moduleOptions: IModuleOptions, @Inject(iamConfig.KEY) private readonly config: ConfigType<typeof iamConfig>, ) {} @HttpCode(HttpStatus.OK) @ApiOperation({ operationId: 'authLogin' }) @ApiOkResponse({ type: LoginResponseDto }) @Auth(AuthType.None) @Post('/auth/login') async login( @Body() request: LoginRequestDto, @Res({ passthrough: true }) response: Response, ): Promise<LoginResponseDto> { if (!this.config.auth.methods.includes('basic')) { throw new NotFoundException(); } try { const user = await this.moduleOptions.authService.checkUser( request.username, ); if (!(await this.hasher.compare(request.password, user.getPassword()))) { throw new UnauthorizedException(); } const login = await this.loginProcessor.process(user, response); this.eventBus.publish(new LoggedInEvent(user.getId())); return { accessToken: login.accessToken, refreshToken: login.refreshToken, }; } catch { throw new UnauthorizedException(); } } @HttpCode(HttpStatus.OK) @ApiOperation({ operationId: 'authPasswordlessLogin' }) @ApiOkResponse({ type: LoginResponseDto }) @Auth(AuthType.None) @Get('/auth/passwordless_login/:id') async passwordlessLogin( @Param('id') tokenId: string, @Req() request: Request, @Res({ passthrough: true }) response: Response, ): Promise<LoginResponseDto> { if (!this.config.auth.methods.includes('passwordless')) { throw new NotFoundException(); } const requestId = request.cookies[TokenType.PasswordlessLoginToken]; if (!requestId) { throw new UnauthorizedException(); } try { const token = await this.moduleOptions.authService.checkToken( tokenId, TokenType.PasswordlessLoginToken, requestId, ); const user = await this.moduleOptions.authService.getUser( token.getUserId(), ); await this.moduleOptions.authService.checkUser(user.getUsername()); await this.moduleOptions.authService.removeToken(tokenId); const login = await this.loginProcessor.process(user, response); return { accessToken: login.accessToken, refreshToken: login.refreshToken, }; } catch { throw new UnauthorizedException(); } } @HttpCode(HttpStatus.NO_CONTENT) @ApiOperation({ operationId: 'authPasswordlessLoginRequest' }) @ApiNoContentResponse() @Auth(AuthType.None) @Post('/auth/passwordless_login') async passwordlessLoginRequest( @Body() request: PasswordlessLoginRequestRequestDto, @Res({ passthrough: true }) response: Response, ): Promise<void> { if (!this.config.auth.methods.includes('passwordless')) { throw new NotFoundException(); } try { const user = await this.moduleOptions.authService.checkUser( request.username, ); await this.passwordlessLoginRequestProcessor.process(user, response); } catch {} } @HttpCode(HttpStatus.OK) @ApiOperation({ operationId: 'authRefreshTokens' }) @ApiOkResponse({ type: LoginResponseDto }) @Auth(AuthType.None) @Get('/auth/refresh_tokens') async refreshTokens( @Req() request: Request, @Res({ passthrough: true }) response: Response, ): Promise<LoginResponseDto> { try { const refreshTokenJwtPayload: IRefreshTokenJwtPayload = await this.jwtService.verifyAsync( request.cookies[TokenType.RefreshToken], ); await this.moduleOptions.authService.checkToken( refreshTokenJwtPayload.id, TokenType.RefreshToken, ); const user = await this.moduleOptions.authService.getUser( refreshTokenJwtPayload.sub, ); await this.moduleOptions.authService.checkUser(user.getUsername()); await this.moduleOptions.authService.removeToken( refreshTokenJwtPayload.id, ); const login = await this.loginProcessor.process(user, response); return { accessToken: login.accessToken, refreshToken: login.refreshToken, }; } catch { throw new UnauthorizedException(); } } @HttpCode(HttpStatus.NO_CONTENT) @ApiOperation({ operationId: 'authLogout' }) @ApiNoContentResponse() @Auth(AuthType.None) @Get('/auth/logout') async logout( @Req() request: Request, @Res({ passthrough: true }) response: Response, @ActiveUser() activeUser: IActiveUser, ) {
await this.logoutProcessor.process(request, response);
if (!activeUser) { return; } this.eventBus.publish(new LoggedOutEvent(activeUser.userId)); } }
src/controllers/auth.controller.ts
fastnloud-nest-iam-463230d
[ { "filename": "src/processors/logout.processor.ts", "retrieved_chunk": "export class LogoutProcessor {\n public constructor(\n private readonly jwtService: JwtService,\n @Inject(MODULE_OPTIONS_TOKEN)\n private readonly moduleOptions: IModuleOptions,\n @Inject(iamConfig.KEY)\n private readonly config: ConfigType<typeof iamConfig>,\n ) {}\n public async process(request: Request, response: Response): Promise<void> {\n try {", "score": 17.319195566543748 }, { "filename": "src/guards/none.guard.ts", "retrieved_chunk": " request[IAM_REQUEST_USER_KEY] = activeUser;\n } catch {\n return true;\n }\n return true;\n }\n}", "score": 16.448150160532794 }, { "filename": "src/guards/access-token.guard.ts", "retrieved_chunk": " );\n const activeUser: IActiveUser = {\n userId: accessTokenJwtPayload.sub,\n roles: accessTokenJwtPayload.roles,\n };\n request[IAM_REQUEST_USER_KEY] = activeUser;\n } catch {\n throw new UnauthorizedException();\n }\n return true;", "score": 16.27797208852735 }, { "filename": "src/processors/logout.processor.ts", "retrieved_chunk": " const refreshTokenJwtPayload: IRefreshTokenJwtPayload =\n await this.jwtService.verifyAsync(\n request.cookies[TokenType.RefreshToken],\n );\n await this.moduleOptions.authService.removeToken(\n refreshTokenJwtPayload.id,\n );\n } catch {}\n response.clearCookie(TokenType.AccessToken);\n response.clearCookie(TokenType.RefreshToken, {", "score": 15.621820423961118 }, { "filename": "src/guards/none.guard.ts", "retrieved_chunk": " const request = context.switchToHttp().getRequest();\n const accessToken: string | undefined =\n request.cookies[TokenType.AccessToken];\n try {\n const accessTokenJwtPayload: IAccessTokenJwtPayload =\n await this.jwtService.verifyAsync(accessToken);\n const activeUser: IActiveUser = {\n userId: accessTokenJwtPayload.sub,\n roles: accessTokenJwtPayload.roles,\n };", "score": 14.01656584431324 } ]
typescript
await this.logoutProcessor.process(request, response);
import { Body, Controller, Get, HttpCode, HttpStatus, Inject, NotFoundException, Param, Post, Req, Res, UnauthorizedException, } from '@nestjs/common'; import { ConfigType } from '@nestjs/config'; import { EventBus } from '@nestjs/cqrs'; import { JwtService } from '@nestjs/jwt'; import { ApiNoContentResponse, ApiOkResponse, ApiOperation, ApiTags, } from '@nestjs/swagger'; import { Request, Response } from 'express'; import iamConfig from '../configs/iam.config'; import { ActiveUser } from '../decorators/active-user.decorator'; import { Auth } from '../decorators/auth.decorator'; import { LoginRequestDto } from '../dtos/login-request.dto'; import { LoginResponseDto } from '../dtos/login-response.dto'; import { PasswordlessLoginRequestRequestDto } from '../dtos/passwordless-login-request-request.dto'; import { AuthType } from '../enums/auth-type.enum'; import { TokenType } from '../enums/token-type.enum'; import { LoggedInEvent } from '../events/logged-in.event'; import { LoggedOutEvent } from '../events/logged-out.event'; import { BcryptHasher } from '../hashers/bcrypt.hasher'; import { MODULE_OPTIONS_TOKEN } from '../iam.module-definition'; import { IActiveUser } from '../interfaces/active-user.interface'; import { IModuleOptions } from '../interfaces/module-options.interface'; import { IRefreshTokenJwtPayload } from '../interfaces/refresh-token-jwt-payload.interface'; import { LoginProcessor } from '../processors/login.processor'; import { LogoutProcessor } from '../processors/logout.processor'; import { PasswordlessLoginRequestProcessor } from '../processors/passwordless-login-request.processor'; @Controller() @ApiTags('Auth') export class AuthController { constructor( private readonly eventBus: EventBus, private readonly hasher: BcryptHasher, private readonly loginProcessor: LoginProcessor, private readonly logoutProcessor: LogoutProcessor, private readonly passwordlessLoginRequestProcessor: PasswordlessLoginRequestProcessor, private readonly jwtService: JwtService, @Inject(MODULE_OPTIONS_TOKEN) private readonly moduleOptions: IModuleOptions, @Inject(iamConfig.KEY) private readonly config: ConfigType<typeof iamConfig>, ) {} @HttpCode(HttpStatus.OK) @ApiOperation({ operationId: 'authLogin' }) @ApiOkResponse({ type: LoginResponseDto }) @Auth(AuthType.None) @Post('/auth/login') async login( @Body() request: LoginRequestDto, @Res({ passthrough: true }) response: Response, ): Promise<LoginResponseDto> { if (!this.config.auth.methods.includes('basic')) { throw new NotFoundException(); } try {
const user = await this.moduleOptions.authService.checkUser( request.username, );
if (!(await this.hasher.compare(request.password, user.getPassword()))) { throw new UnauthorizedException(); } const login = await this.loginProcessor.process(user, response); this.eventBus.publish(new LoggedInEvent(user.getId())); return { accessToken: login.accessToken, refreshToken: login.refreshToken, }; } catch { throw new UnauthorizedException(); } } @HttpCode(HttpStatus.OK) @ApiOperation({ operationId: 'authPasswordlessLogin' }) @ApiOkResponse({ type: LoginResponseDto }) @Auth(AuthType.None) @Get('/auth/passwordless_login/:id') async passwordlessLogin( @Param('id') tokenId: string, @Req() request: Request, @Res({ passthrough: true }) response: Response, ): Promise<LoginResponseDto> { if (!this.config.auth.methods.includes('passwordless')) { throw new NotFoundException(); } const requestId = request.cookies[TokenType.PasswordlessLoginToken]; if (!requestId) { throw new UnauthorizedException(); } try { const token = await this.moduleOptions.authService.checkToken( tokenId, TokenType.PasswordlessLoginToken, requestId, ); const user = await this.moduleOptions.authService.getUser( token.getUserId(), ); await this.moduleOptions.authService.checkUser(user.getUsername()); await this.moduleOptions.authService.removeToken(tokenId); const login = await this.loginProcessor.process(user, response); return { accessToken: login.accessToken, refreshToken: login.refreshToken, }; } catch { throw new UnauthorizedException(); } } @HttpCode(HttpStatus.NO_CONTENT) @ApiOperation({ operationId: 'authPasswordlessLoginRequest' }) @ApiNoContentResponse() @Auth(AuthType.None) @Post('/auth/passwordless_login') async passwordlessLoginRequest( @Body() request: PasswordlessLoginRequestRequestDto, @Res({ passthrough: true }) response: Response, ): Promise<void> { if (!this.config.auth.methods.includes('passwordless')) { throw new NotFoundException(); } try { const user = await this.moduleOptions.authService.checkUser( request.username, ); await this.passwordlessLoginRequestProcessor.process(user, response); } catch {} } @HttpCode(HttpStatus.OK) @ApiOperation({ operationId: 'authRefreshTokens' }) @ApiOkResponse({ type: LoginResponseDto }) @Auth(AuthType.None) @Get('/auth/refresh_tokens') async refreshTokens( @Req() request: Request, @Res({ passthrough: true }) response: Response, ): Promise<LoginResponseDto> { try { const refreshTokenJwtPayload: IRefreshTokenJwtPayload = await this.jwtService.verifyAsync( request.cookies[TokenType.RefreshToken], ); await this.moduleOptions.authService.checkToken( refreshTokenJwtPayload.id, TokenType.RefreshToken, ); const user = await this.moduleOptions.authService.getUser( refreshTokenJwtPayload.sub, ); await this.moduleOptions.authService.checkUser(user.getUsername()); await this.moduleOptions.authService.removeToken( refreshTokenJwtPayload.id, ); const login = await this.loginProcessor.process(user, response); return { accessToken: login.accessToken, refreshToken: login.refreshToken, }; } catch { throw new UnauthorizedException(); } } @HttpCode(HttpStatus.NO_CONTENT) @ApiOperation({ operationId: 'authLogout' }) @ApiNoContentResponse() @Auth(AuthType.None) @Get('/auth/logout') async logout( @Req() request: Request, @Res({ passthrough: true }) response: Response, @ActiveUser() activeUser: IActiveUser, ) { await this.logoutProcessor.process(request, response); if (!activeUser) { return; } this.eventBus.publish(new LoggedOutEvent(activeUser.userId)); } }
src/controllers/auth.controller.ts
fastnloud-nest-iam-463230d
[ { "filename": "src/processors/logout.processor.ts", "retrieved_chunk": " const refreshTokenJwtPayload: IRefreshTokenJwtPayload =\n await this.jwtService.verifyAsync(\n request.cookies[TokenType.RefreshToken],\n );\n await this.moduleOptions.authService.removeToken(\n refreshTokenJwtPayload.id,\n );\n } catch {}\n response.clearCookie(TokenType.AccessToken);\n response.clearCookie(TokenType.RefreshToken, {", "score": 20.370866308809514 }, { "filename": "src/processors/login.processor.ts", "retrieved_chunk": " private readonly config: ConfigType<typeof iamConfig>,\n ) {}\n public async process(user: IUser, response: Response): Promise<ILogin> {\n const accessToken = await this.accessTokenGenerator.generate(user);\n const refreshToken = await this.refreshTokenGenerator.generate(user);\n const login = {\n accessToken: accessToken.jwt,\n refreshToken: refreshToken.jwt,\n };\n await this.moduleOptions.authService.saveToken(", "score": 19.47463655787946 }, { "filename": "src/guards/auth.guard.ts", "retrieved_chunk": " const guards = authTypes.map((type) => this.authTypeGuardMap[type]).flat();\n for (const guard of guards) {\n if (await Promise.resolve(guard.canActivate(context))) {\n return true;\n }\n }\n throw new UnauthorizedException();\n }\n}", "score": 19.133419222015775 }, { "filename": "src/processors/passwordless-login-request.processor.ts", "retrieved_chunk": " const requestId = randomUUID();\n const passwordlessLoginToken =\n await this.passwordlessLoginTokenGenerator.generate(user, requestId);\n await this.moduleOptions.authService.saveToken(passwordlessLoginToken);\n response.cookie(TokenType.PasswordlessLoginToken, requestId, {\n secure: this.config.cookie.secure,\n httpOnly: this.config.cookie.httpOnly,\n sameSite: this.config.cookie.sameSite,\n expires: passwordlessLoginToken.getExpiresAt(),\n path: `${this.config.routePathPrefix}/auth`,", "score": 17.135953821100873 }, { "filename": "src/guards/access-token.guard.ts", "retrieved_chunk": " );\n const activeUser: IActiveUser = {\n userId: accessTokenJwtPayload.sub,\n roles: accessTokenJwtPayload.roles,\n };\n request[IAM_REQUEST_USER_KEY] = activeUser;\n } catch {\n throw new UnauthorizedException();\n }\n return true;", "score": 16.161604210295486 } ]
typescript
const user = await this.moduleOptions.authService.checkUser( request.username, );
import { Body, Controller, Get, HttpCode, HttpStatus, Inject, NotFoundException, Param, Post, Req, Res, UnauthorizedException, } from '@nestjs/common'; import { ConfigType } from '@nestjs/config'; import { EventBus } from '@nestjs/cqrs'; import { JwtService } from '@nestjs/jwt'; import { ApiNoContentResponse, ApiOkResponse, ApiOperation, ApiTags, } from '@nestjs/swagger'; import { Request, Response } from 'express'; import iamConfig from '../configs/iam.config'; import { ActiveUser } from '../decorators/active-user.decorator'; import { Auth } from '../decorators/auth.decorator'; import { LoginRequestDto } from '../dtos/login-request.dto'; import { LoginResponseDto } from '../dtos/login-response.dto'; import { PasswordlessLoginRequestRequestDto } from '../dtos/passwordless-login-request-request.dto'; import { AuthType } from '../enums/auth-type.enum'; import { TokenType } from '../enums/token-type.enum'; import { LoggedInEvent } from '../events/logged-in.event'; import { LoggedOutEvent } from '../events/logged-out.event'; import { BcryptHasher } from '../hashers/bcrypt.hasher'; import { MODULE_OPTIONS_TOKEN } from '../iam.module-definition'; import { IActiveUser } from '../interfaces/active-user.interface'; import { IModuleOptions } from '../interfaces/module-options.interface'; import { IRefreshTokenJwtPayload } from '../interfaces/refresh-token-jwt-payload.interface'; import { LoginProcessor } from '../processors/login.processor'; import { LogoutProcessor } from '../processors/logout.processor'; import { PasswordlessLoginRequestProcessor } from '../processors/passwordless-login-request.processor'; @Controller() @ApiTags('Auth') export class AuthController { constructor( private readonly eventBus: EventBus, private readonly hasher: BcryptHasher, private readonly loginProcessor: LoginProcessor, private readonly logoutProcessor: LogoutProcessor, private readonly passwordlessLoginRequestProcessor: PasswordlessLoginRequestProcessor, private readonly jwtService: JwtService, @Inject(MODULE_OPTIONS_TOKEN) private readonly moduleOptions: IModuleOptions, @Inject(iamConfig.KEY) private readonly config: ConfigType<typeof iamConfig>, ) {} @HttpCode(HttpStatus.OK) @ApiOperation({ operationId: 'authLogin' }) @ApiOkResponse({ type: LoginResponseDto }) @Auth(AuthType.None) @Post('/auth/login') async login( @Body() request: LoginRequestDto, @Res({ passthrough: true }) response: Response, ): Promise<LoginResponseDto> { if (!this.config.auth.methods.includes('basic')) { throw new NotFoundException(); } try { const user = await this.moduleOptions.authService.checkUser( request.username, ); if (!(await this.hasher.compare(request.password, user.getPassword()))) { throw new UnauthorizedException(); }
const login = await this.loginProcessor.process(user, response);
this.eventBus.publish(new LoggedInEvent(user.getId())); return { accessToken: login.accessToken, refreshToken: login.refreshToken, }; } catch { throw new UnauthorizedException(); } } @HttpCode(HttpStatus.OK) @ApiOperation({ operationId: 'authPasswordlessLogin' }) @ApiOkResponse({ type: LoginResponseDto }) @Auth(AuthType.None) @Get('/auth/passwordless_login/:id') async passwordlessLogin( @Param('id') tokenId: string, @Req() request: Request, @Res({ passthrough: true }) response: Response, ): Promise<LoginResponseDto> { if (!this.config.auth.methods.includes('passwordless')) { throw new NotFoundException(); } const requestId = request.cookies[TokenType.PasswordlessLoginToken]; if (!requestId) { throw new UnauthorizedException(); } try { const token = await this.moduleOptions.authService.checkToken( tokenId, TokenType.PasswordlessLoginToken, requestId, ); const user = await this.moduleOptions.authService.getUser( token.getUserId(), ); await this.moduleOptions.authService.checkUser(user.getUsername()); await this.moduleOptions.authService.removeToken(tokenId); const login = await this.loginProcessor.process(user, response); return { accessToken: login.accessToken, refreshToken: login.refreshToken, }; } catch { throw new UnauthorizedException(); } } @HttpCode(HttpStatus.NO_CONTENT) @ApiOperation({ operationId: 'authPasswordlessLoginRequest' }) @ApiNoContentResponse() @Auth(AuthType.None) @Post('/auth/passwordless_login') async passwordlessLoginRequest( @Body() request: PasswordlessLoginRequestRequestDto, @Res({ passthrough: true }) response: Response, ): Promise<void> { if (!this.config.auth.methods.includes('passwordless')) { throw new NotFoundException(); } try { const user = await this.moduleOptions.authService.checkUser( request.username, ); await this.passwordlessLoginRequestProcessor.process(user, response); } catch {} } @HttpCode(HttpStatus.OK) @ApiOperation({ operationId: 'authRefreshTokens' }) @ApiOkResponse({ type: LoginResponseDto }) @Auth(AuthType.None) @Get('/auth/refresh_tokens') async refreshTokens( @Req() request: Request, @Res({ passthrough: true }) response: Response, ): Promise<LoginResponseDto> { try { const refreshTokenJwtPayload: IRefreshTokenJwtPayload = await this.jwtService.verifyAsync( request.cookies[TokenType.RefreshToken], ); await this.moduleOptions.authService.checkToken( refreshTokenJwtPayload.id, TokenType.RefreshToken, ); const user = await this.moduleOptions.authService.getUser( refreshTokenJwtPayload.sub, ); await this.moduleOptions.authService.checkUser(user.getUsername()); await this.moduleOptions.authService.removeToken( refreshTokenJwtPayload.id, ); const login = await this.loginProcessor.process(user, response); return { accessToken: login.accessToken, refreshToken: login.refreshToken, }; } catch { throw new UnauthorizedException(); } } @HttpCode(HttpStatus.NO_CONTENT) @ApiOperation({ operationId: 'authLogout' }) @ApiNoContentResponse() @Auth(AuthType.None) @Get('/auth/logout') async logout( @Req() request: Request, @Res({ passthrough: true }) response: Response, @ActiveUser() activeUser: IActiveUser, ) { await this.logoutProcessor.process(request, response); if (!activeUser) { return; } this.eventBus.publish(new LoggedOutEvent(activeUser.userId)); } }
src/controllers/auth.controller.ts
fastnloud-nest-iam-463230d
[ { "filename": "src/processors/login.processor.ts", "retrieved_chunk": " private readonly config: ConfigType<typeof iamConfig>,\n ) {}\n public async process(user: IUser, response: Response): Promise<ILogin> {\n const accessToken = await this.accessTokenGenerator.generate(user);\n const refreshToken = await this.refreshTokenGenerator.generate(user);\n const login = {\n accessToken: accessToken.jwt,\n refreshToken: refreshToken.jwt,\n };\n await this.moduleOptions.authService.saveToken(", "score": 31.205949040576765 }, { "filename": "src/guards/auth.guard.ts", "retrieved_chunk": " const guards = authTypes.map((type) => this.authTypeGuardMap[type]).flat();\n for (const guard of guards) {\n if (await Promise.resolve(guard.canActivate(context))) {\n return true;\n }\n }\n throw new UnauthorizedException();\n }\n}", "score": 29.67745004075609 }, { "filename": "src/processors/logout.processor.ts", "retrieved_chunk": " const refreshTokenJwtPayload: IRefreshTokenJwtPayload =\n await this.jwtService.verifyAsync(\n request.cookies[TokenType.RefreshToken],\n );\n await this.moduleOptions.authService.removeToken(\n refreshTokenJwtPayload.id,\n );\n } catch {}\n response.clearCookie(TokenType.AccessToken);\n response.clearCookie(TokenType.RefreshToken, {", "score": 28.711644296924714 }, { "filename": "src/processors/passwordless-login-request.processor.ts", "retrieved_chunk": " const requestId = randomUUID();\n const passwordlessLoginToken =\n await this.passwordlessLoginTokenGenerator.generate(user, requestId);\n await this.moduleOptions.authService.saveToken(passwordlessLoginToken);\n response.cookie(TokenType.PasswordlessLoginToken, requestId, {\n secure: this.config.cookie.secure,\n httpOnly: this.config.cookie.httpOnly,\n sameSite: this.config.cookie.sameSite,\n expires: passwordlessLoginToken.getExpiresAt(),\n path: `${this.config.routePathPrefix}/auth`,", "score": 23.984840885646634 }, { "filename": "src/guards/access-token.guard.ts", "retrieved_chunk": " );\n const activeUser: IActiveUser = {\n userId: accessTokenJwtPayload.sub,\n roles: accessTokenJwtPayload.roles,\n };\n request[IAM_REQUEST_USER_KEY] = activeUser;\n } catch {\n throw new UnauthorizedException();\n }\n return true;", "score": 23.70710338831371 } ]
typescript
const login = await this.loginProcessor.process(user, response);
import { Body, Controller, Get, HttpCode, HttpStatus, Inject, NotFoundException, Param, Post, Req, Res, UnauthorizedException, } from '@nestjs/common'; import { ConfigType } from '@nestjs/config'; import { EventBus } from '@nestjs/cqrs'; import { JwtService } from '@nestjs/jwt'; import { ApiNoContentResponse, ApiOkResponse, ApiOperation, ApiTags, } from '@nestjs/swagger'; import { Request, Response } from 'express'; import iamConfig from '../configs/iam.config'; import { ActiveUser } from '../decorators/active-user.decorator'; import { Auth } from '../decorators/auth.decorator'; import { LoginRequestDto } from '../dtos/login-request.dto'; import { LoginResponseDto } from '../dtos/login-response.dto'; import { PasswordlessLoginRequestRequestDto } from '../dtos/passwordless-login-request-request.dto'; import { AuthType } from '../enums/auth-type.enum'; import { TokenType } from '../enums/token-type.enum'; import { LoggedInEvent } from '../events/logged-in.event'; import { LoggedOutEvent } from '../events/logged-out.event'; import { BcryptHasher } from '../hashers/bcrypt.hasher'; import { MODULE_OPTIONS_TOKEN } from '../iam.module-definition'; import { IActiveUser } from '../interfaces/active-user.interface'; import { IModuleOptions } from '../interfaces/module-options.interface'; import { IRefreshTokenJwtPayload } from '../interfaces/refresh-token-jwt-payload.interface'; import { LoginProcessor } from '../processors/login.processor'; import { LogoutProcessor } from '../processors/logout.processor'; import { PasswordlessLoginRequestProcessor } from '../processors/passwordless-login-request.processor'; @Controller() @ApiTags('Auth') export class AuthController { constructor( private readonly eventBus: EventBus, private readonly hasher: BcryptHasher, private readonly loginProcessor: LoginProcessor, private readonly logoutProcessor: LogoutProcessor, private readonly passwordlessLoginRequestProcessor: PasswordlessLoginRequestProcessor, private readonly jwtService: JwtService, @Inject(MODULE_OPTIONS_TOKEN) private readonly moduleOptions: IModuleOptions, @Inject(iamConfig.KEY) private readonly config: ConfigType<typeof iamConfig>, ) {} @HttpCode(HttpStatus.OK) @ApiOperation({ operationId: 'authLogin' }) @ApiOkResponse({ type: LoginResponseDto }) @Auth(AuthType.None) @Post('/auth/login') async login( @Body() request: LoginRequestDto, @Res({ passthrough: true }) response: Response, ): Promise<LoginResponseDto> { if (!this.config.auth.methods.includes('basic')) { throw new NotFoundException(); } try { const user = await this.moduleOptions.authService.checkUser( request.username, ); if (!(await this.hasher.compare(request.password, user.getPassword()))) { throw new UnauthorizedException(); } const login = await this.loginProcessor.process(user, response); this.eventBus.publish(new LoggedInEvent(user.getId())); return { accessToken: login.accessToken, refreshToken: login.refreshToken, }; } catch { throw new UnauthorizedException(); } } @HttpCode(HttpStatus.OK) @ApiOperation({ operationId: 'authPasswordlessLogin' }) @ApiOkResponse({ type: LoginResponseDto }) @Auth(AuthType.None) @Get('/auth/passwordless_login/:id') async passwordlessLogin( @Param('id') tokenId: string, @Req() request: Request, @Res({ passthrough: true }) response: Response, ): Promise<LoginResponseDto> { if (!this.config.auth.methods.includes('passwordless')) { throw new NotFoundException(); } const requestId = request.cookies[TokenType.PasswordlessLoginToken]; if (!requestId) { throw new UnauthorizedException(); } try { const token = await this.moduleOptions.authService.checkToken( tokenId, TokenType.PasswordlessLoginToken, requestId, ); const user = await this.moduleOptions.authService.getUser( token.getUserId(), ); await this.moduleOptions.authService.checkUser(user.getUsername()); await this.moduleOptions.authService.removeToken(tokenId); const login = await this.loginProcessor.process(user, response); return { accessToken: login.accessToken, refreshToken: login.refreshToken, }; } catch { throw new UnauthorizedException(); } } @HttpCode(HttpStatus.NO_CONTENT) @ApiOperation({ operationId: 'authPasswordlessLoginRequest' }) @ApiNoContentResponse() @Auth(AuthType.None) @Post('/auth/passwordless_login') async passwordlessLoginRequest( @Body() request: PasswordlessLoginRequestRequestDto, @Res({ passthrough: true }) response: Response, ): Promise<void> { if (!this.config.auth.methods.includes('passwordless')) { throw new NotFoundException(); } try { const user = await this.moduleOptions.authService.checkUser( request.username, ); await this.passwordlessLoginRequestProcessor.process(user, response); } catch {} } @HttpCode(HttpStatus.OK) @ApiOperation({ operationId: 'authRefreshTokens' }) @ApiOkResponse({ type: LoginResponseDto }) @Auth(AuthType.None) @Get('/auth/refresh_tokens') async refreshTokens( @Req() request: Request, @Res({ passthrough: true }) response: Response, ): Promise<LoginResponseDto> { try { const refreshTokenJwtPayload: IRefreshTokenJwtPayload = await this.jwtService.verifyAsync( request.cookies[TokenType.RefreshToken], ); await this.moduleOptions.authService.checkToken( refreshTokenJwtPayload.
id, TokenType.RefreshToken, );
const user = await this.moduleOptions.authService.getUser( refreshTokenJwtPayload.sub, ); await this.moduleOptions.authService.checkUser(user.getUsername()); await this.moduleOptions.authService.removeToken( refreshTokenJwtPayload.id, ); const login = await this.loginProcessor.process(user, response); return { accessToken: login.accessToken, refreshToken: login.refreshToken, }; } catch { throw new UnauthorizedException(); } } @HttpCode(HttpStatus.NO_CONTENT) @ApiOperation({ operationId: 'authLogout' }) @ApiNoContentResponse() @Auth(AuthType.None) @Get('/auth/logout') async logout( @Req() request: Request, @Res({ passthrough: true }) response: Response, @ActiveUser() activeUser: IActiveUser, ) { await this.logoutProcessor.process(request, response); if (!activeUser) { return; } this.eventBus.publish(new LoggedOutEvent(activeUser.userId)); } }
src/controllers/auth.controller.ts
fastnloud-nest-iam-463230d
[ { "filename": "src/processors/logout.processor.ts", "retrieved_chunk": " const refreshTokenJwtPayload: IRefreshTokenJwtPayload =\n await this.jwtService.verifyAsync(\n request.cookies[TokenType.RefreshToken],\n );\n await this.moduleOptions.authService.removeToken(\n refreshTokenJwtPayload.id,\n );\n } catch {}\n response.clearCookie(TokenType.AccessToken);\n response.clearCookie(TokenType.RefreshToken, {", "score": 55.851198199126735 }, { "filename": "src/guards/none.guard.ts", "retrieved_chunk": " const request = context.switchToHttp().getRequest();\n const accessToken: string | undefined =\n request.cookies[TokenType.AccessToken];\n try {\n const accessTokenJwtPayload: IAccessTokenJwtPayload =\n await this.jwtService.verifyAsync(accessToken);\n const activeUser: IActiveUser = {\n userId: accessTokenJwtPayload.sub,\n roles: accessTokenJwtPayload.roles,\n };", "score": 24.70208077989648 }, { "filename": "src/guards/access-token.guard.ts", "retrieved_chunk": "import { IActiveUser } from '../interfaces/active-user.interface';\n@Injectable()\nexport class AccessTokenGuard implements CanActivate {\n constructor(private readonly jwtService: JwtService) {}\n async canActivate(context: ExecutionContext): Promise<boolean> {\n const request = context.switchToHttp().getRequest();\n try {\n const accessTokenJwtPayload: IAccessTokenJwtPayload =\n await this.jwtService.verifyAsync(\n request.cookies[TokenType.AccessToken] ?? '',", "score": 22.069450563452044 }, { "filename": "src/processors/passwordless-login-request.processor.ts", "retrieved_chunk": " const requestId = randomUUID();\n const passwordlessLoginToken =\n await this.passwordlessLoginTokenGenerator.generate(user, requestId);\n await this.moduleOptions.authService.saveToken(passwordlessLoginToken);\n response.cookie(TokenType.PasswordlessLoginToken, requestId, {\n secure: this.config.cookie.secure,\n httpOnly: this.config.cookie.httpOnly,\n sameSite: this.config.cookie.sameSite,\n expires: passwordlessLoginToken.getExpiresAt(),\n path: `${this.config.routePathPrefix}/auth`,", "score": 16.71461114772853 }, { "filename": "src/generators/refresh-token.generator.ts", "retrieved_chunk": " return {\n id,\n jwt: await this.jwtService.signAsync(\n {\n id,\n sub: user.getId(),\n username: user.getUsername(),\n roles: user.getRoles(),\n } as IRefreshTokenJwtPayload,\n {", "score": 15.844186798102688 } ]
typescript
id, TokenType.RefreshToken, );
import { Body, Controller, Get, HttpCode, HttpStatus, Inject, NotFoundException, Param, Post, Req, Res, UnauthorizedException, } from '@nestjs/common'; import { ConfigType } from '@nestjs/config'; import { EventBus } from '@nestjs/cqrs'; import { JwtService } from '@nestjs/jwt'; import { ApiNoContentResponse, ApiOkResponse, ApiOperation, ApiTags, } from '@nestjs/swagger'; import { Request, Response } from 'express'; import iamConfig from '../configs/iam.config'; import { ActiveUser } from '../decorators/active-user.decorator'; import { Auth } from '../decorators/auth.decorator'; import { LoginRequestDto } from '../dtos/login-request.dto'; import { LoginResponseDto } from '../dtos/login-response.dto'; import { PasswordlessLoginRequestRequestDto } from '../dtos/passwordless-login-request-request.dto'; import { AuthType } from '../enums/auth-type.enum'; import { TokenType } from '../enums/token-type.enum'; import { LoggedInEvent } from '../events/logged-in.event'; import { LoggedOutEvent } from '../events/logged-out.event'; import { BcryptHasher } from '../hashers/bcrypt.hasher'; import { MODULE_OPTIONS_TOKEN } from '../iam.module-definition'; import { IActiveUser } from '../interfaces/active-user.interface'; import { IModuleOptions } from '../interfaces/module-options.interface'; import { IRefreshTokenJwtPayload } from '../interfaces/refresh-token-jwt-payload.interface'; import { LoginProcessor } from '../processors/login.processor'; import { LogoutProcessor } from '../processors/logout.processor'; import { PasswordlessLoginRequestProcessor } from '../processors/passwordless-login-request.processor'; @Controller() @ApiTags('Auth') export class AuthController { constructor( private readonly eventBus: EventBus, private readonly hasher: BcryptHasher, private readonly loginProcessor: LoginProcessor, private readonly logoutProcessor: LogoutProcessor, private readonly passwordlessLoginRequestProcessor: PasswordlessLoginRequestProcessor, private readonly jwtService: JwtService, @Inject(MODULE_OPTIONS_TOKEN) private readonly moduleOptions: IModuleOptions, @Inject(iamConfig.KEY) private readonly config: ConfigType<typeof iamConfig>, ) {} @HttpCode(HttpStatus.OK) @ApiOperation({ operationId: 'authLogin' }) @ApiOkResponse({ type: LoginResponseDto }) @Auth(AuthType.None) @Post('/auth/login') async login( @Body() request: LoginRequestDto, @Res({ passthrough: true }) response: Response, ): Promise<LoginResponseDto> { if (!this.config.auth.methods.includes('basic')) { throw new NotFoundException(); } try { const user = await this.moduleOptions.authService.checkUser( request.username, ); if (!(await this.hasher.compare(request.password, user.getPassword()))) { throw new UnauthorizedException(); } const login = await this.loginProcessor.process(user, response); this.eventBus.publish(new LoggedInEvent(user.getId())); return { accessToken: login.accessToken, refreshToken: login.refreshToken, }; } catch { throw new UnauthorizedException(); } } @HttpCode(HttpStatus.OK) @ApiOperation({ operationId: 'authPasswordlessLogin' }) @ApiOkResponse({ type: LoginResponseDto }) @Auth(AuthType.None) @Get('/auth/passwordless_login/:id') async passwordlessLogin( @Param('id') tokenId: string, @Req() request: Request, @Res({ passthrough: true }) response: Response, ): Promise<LoginResponseDto> { if (!this.config.auth.methods.includes('passwordless')) { throw new NotFoundException(); } const requestId = request.cookies[TokenType.PasswordlessLoginToken]; if (!requestId) { throw new UnauthorizedException(); } try { const token = await this.moduleOptions.authService.checkToken( tokenId, TokenType.PasswordlessLoginToken, requestId, ); const user = await this.moduleOptions.authService.getUser( token.getUserId(), ); await this.moduleOptions.authService.checkUser(user.getUsername()); await this.moduleOptions.authService.removeToken(tokenId); const login = await this.loginProcessor.process(user, response); return { accessToken: login.accessToken, refreshToken: login.refreshToken, }; } catch { throw new UnauthorizedException(); } } @HttpCode(HttpStatus.NO_CONTENT) @ApiOperation({ operationId: 'authPasswordlessLoginRequest' }) @ApiNoContentResponse() @Auth(AuthType.None) @Post('/auth/passwordless_login') async passwordlessLoginRequest( @Body() request: PasswordlessLoginRequestRequestDto, @Res({ passthrough: true }) response: Response, ): Promise<void> { if (!this.config.auth.methods.includes('passwordless')) { throw new NotFoundException(); } try { const user = await this.moduleOptions.authService.checkUser( request.username, ); await this.passwordlessLoginRequestProcessor.process(user, response); } catch {} } @HttpCode(HttpStatus.OK) @ApiOperation({ operationId: 'authRefreshTokens' }) @ApiOkResponse({ type: LoginResponseDto }) @Auth(AuthType.None) @Get('/auth/refresh_tokens') async refreshTokens( @Req() request: Request, @Res({ passthrough: true }) response: Response, ): Promise<LoginResponseDto> { try { const refreshTokenJwtPayload: IRefreshTokenJwtPayload = await this.jwtService.verifyAsync( request.cookies[TokenType.RefreshToken], ); await this.moduleOptions.authService.checkToken( refreshTokenJwtPayload.id, TokenType.RefreshToken, ); const user = await this.moduleOptions.authService.getUser( refreshTokenJwtPayload.sub, ); await this.moduleOptions.authService.checkUser(user.getUsername()); await this.moduleOptions.authService.removeToken( refreshTokenJwtPayload.id, ); const login = await this.loginProcessor.process(user, response); return { accessToken: login.accessToken, refreshToken: login.refreshToken, }; } catch { throw new UnauthorizedException(); } } @HttpCode(HttpStatus.NO_CONTENT) @ApiOperation({ operationId: 'authLogout' }) @ApiNoContentResponse() @Auth(AuthType.None) @Get('/auth/logout') async logout( @Req() request: Request, @Res({ passthrough: true }) response: Response, @ActiveUser() activeUser: IActiveUser, ) { await this.logoutProcessor.process(request, response); if (!activeUser) { return; }
this.eventBus.publish(new LoggedOutEvent(activeUser.userId));
} }
src/controllers/auth.controller.ts
fastnloud-nest-iam-463230d
[ { "filename": "src/guards/access-token.guard.ts", "retrieved_chunk": " );\n const activeUser: IActiveUser = {\n userId: accessTokenJwtPayload.sub,\n roles: accessTokenJwtPayload.roles,\n };\n request[IAM_REQUEST_USER_KEY] = activeUser;\n } catch {\n throw new UnauthorizedException();\n }\n return true;", "score": 33.547916761787114 }, { "filename": "src/guards/none.guard.ts", "retrieved_chunk": " request[IAM_REQUEST_USER_KEY] = activeUser;\n } catch {\n return true;\n }\n return true;\n }\n}", "score": 28.49914338904795 }, { "filename": "src/guards/none.guard.ts", "retrieved_chunk": " const request = context.switchToHttp().getRequest();\n const accessToken: string | undefined =\n request.cookies[TokenType.AccessToken];\n try {\n const accessTokenJwtPayload: IAccessTokenJwtPayload =\n await this.jwtService.verifyAsync(accessToken);\n const activeUser: IActiveUser = {\n userId: accessTokenJwtPayload.sub,\n roles: accessTokenJwtPayload.roles,\n };", "score": 23.243743409485774 }, { "filename": "src/processors/logout.processor.ts", "retrieved_chunk": "export class LogoutProcessor {\n public constructor(\n private readonly jwtService: JwtService,\n @Inject(MODULE_OPTIONS_TOKEN)\n private readonly moduleOptions: IModuleOptions,\n @Inject(iamConfig.KEY)\n private readonly config: ConfigType<typeof iamConfig>,\n ) {}\n public async process(request: Request, response: Response): Promise<void> {\n try {", "score": 17.319195566543748 }, { "filename": "src/processors/logout.processor.ts", "retrieved_chunk": " const refreshTokenJwtPayload: IRefreshTokenJwtPayload =\n await this.jwtService.verifyAsync(\n request.cookies[TokenType.RefreshToken],\n );\n await this.moduleOptions.authService.removeToken(\n refreshTokenJwtPayload.id,\n );\n } catch {}\n response.clearCookie(TokenType.AccessToken);\n response.clearCookie(TokenType.RefreshToken, {", "score": 17.282677114674286 } ]
typescript
this.eventBus.publish(new LoggedOutEvent(activeUser.userId));
import { LiteralTypeNode, Project, SourceFile, ts } from 'ts-morph'; import { toCamelCase } from './toCamelCase'; import chalk from 'chalk'; export function getEnumsProperties( project: Project, sourceFile: SourceFile, schema: string ) { const databaseInterface = sourceFile.getInterfaceOrThrow('Database'); const publicProperty = databaseInterface.getPropertyOrThrow(schema); const publicType = publicProperty.getType(); const enumsProperty = publicType .getApparentProperties() .find((property) => property.getName() === 'Enums'); if (!enumsProperty) { console.log( `${chalk.yellow.bold( 'warn' )} No Enums property found within the Database interface for schema ${schema}.` ); return []; } const enumsType = project .getProgram() .getTypeChecker() .getTypeAtLocation(enumsProperty.getValueDeclarationOrThrow()); const enumsProperties = enumsType.getProperties(); if (enumsProperties.length < 1) { console.log( `${chalk.yellow.bold( 'warn' )} No enums found within the Enums property for schema ${schema}.` ); return []; } return enumsProperties; } function getEnumValueLabel(value: LiteralTypeNode) { let enumValue = value.getText().replace(/"/g, ''); if (enumValue.includes(' ')) { enumValue.replace(/ /g, '_'); } if (enumValue.includes('-')) { enumValue.replace(/-/g, '_'); } if (enumValue.includes('.')) { enumValue =
toCamelCase(enumValue, '.');
} return enumValue; } function getEnumValueText(value: LiteralTypeNode) { return value.getText(); } export function getEnumValuesText( enumProperty: ReturnType<typeof getEnumsProperties>[number] ) { const enumValues = enumProperty .getValueDeclarationOrThrow() .getChildrenOfKind(ts.SyntaxKind.UnionType) .flatMap((enumValue) => enumValue.getChildrenOfKind(ts.SyntaxKind.LiteralType) ); return enumValues.map( (value) => ` ${getEnumValueLabel(value)} = ${getEnumValueText(value)},` ); }
src/utils/getEnumsProperties.ts
FroggyPanda-better-supabase-types-4e1b1eb
[ { "filename": "src/utils/toCamelCase.ts", "retrieved_chunk": "export function toCamelCase(str: string, delimiter: string = '-') {\n const pattern = new RegExp(('\\\\' + delimiter + '([a-z])'), 'g')\n return str.replace(pattern, (match, capture) => capture.toUpperCase())\n}", "score": 24.217117285997553 }, { "filename": "src/utils/toPascalCase.ts", "retrieved_chunk": "import { singular } from 'pluralize';\nconst wordToPascalCase = (makeSingular: boolean) => (word: string) => {\n const singularWord = makeSingular ? singular(word) : word;\n return singularWord.charAt(0).toUpperCase() + singularWord.substring(1);\n}\nexport function toPascalCase(str: string, makeSingular: boolean = false) {\n return str\n .split('_')\n .map(wordToPascalCase(makeSingular))\n .join('');", "score": 5.344479093161584 }, { "filename": "src/generate.ts", "retrieved_chunk": " const functionNameType = toPascalCase(functionName, makeSingular);\n types.push(\n `export type Args${functionNameType} = Database['${schemaName}']['Functions']['${functionName}']['Args'];`,\n `export type ReturnType${functionNameType} = Database['${schemaName}']['Functions']['${functionName}']['Returns'];`,\n '\\n'\n );\n }\n }\n const fileContent = fs.readFileSync(input, 'utf-8');\n let updatedFileContent = fileContent + '\\n' + types.join('\\n') + '\\n';", "score": 2.636938004825423 }, { "filename": "src/generate.ts", "retrieved_chunk": " if (prettierConfigPath) {\n updatedFileContent = await prettierFormat(\n updatedFileContent,\n prettierConfigPath\n );\n }\n fs.writeFileSync(output, updatedFileContent);\n}", "score": 1.3551732888896444 }, { "filename": "src/index.ts", "retrieved_chunk": " // Load config from 'package.json' file\n // Check if config is correct\n const result = schema.safeParse(packageJsonFile['betterConfig']);\n if (!result.success) {\n console.log('Invalid config in package.json');\n } else {\n if (!result.data.output && !result.data.force) {\n console.log(\n 'It looks like you want to overwrite your input file. Add the force property to do that in your config file.'\n );", "score": 1.2976779016492093 } ]
typescript
toCamelCase(enumValue, '.');
import { Body, Controller, Get, HttpCode, HttpStatus, Inject, NotFoundException, Param, Post, Req, Res, UnauthorizedException, } from '@nestjs/common'; import { ConfigType } from '@nestjs/config'; import { EventBus } from '@nestjs/cqrs'; import { JwtService } from '@nestjs/jwt'; import { ApiNoContentResponse, ApiOkResponse, ApiOperation, ApiTags, } from '@nestjs/swagger'; import { Request, Response } from 'express'; import iamConfig from '../configs/iam.config'; import { ActiveUser } from '../decorators/active-user.decorator'; import { Auth } from '../decorators/auth.decorator'; import { LoginRequestDto } from '../dtos/login-request.dto'; import { LoginResponseDto } from '../dtos/login-response.dto'; import { PasswordlessLoginRequestRequestDto } from '../dtos/passwordless-login-request-request.dto'; import { AuthType } from '../enums/auth-type.enum'; import { TokenType } from '../enums/token-type.enum'; import { LoggedInEvent } from '../events/logged-in.event'; import { LoggedOutEvent } from '../events/logged-out.event'; import { BcryptHasher } from '../hashers/bcrypt.hasher'; import { MODULE_OPTIONS_TOKEN } from '../iam.module-definition'; import { IActiveUser } from '../interfaces/active-user.interface'; import { IModuleOptions } from '../interfaces/module-options.interface'; import { IRefreshTokenJwtPayload } from '../interfaces/refresh-token-jwt-payload.interface'; import { LoginProcessor } from '../processors/login.processor'; import { LogoutProcessor } from '../processors/logout.processor'; import { PasswordlessLoginRequestProcessor } from '../processors/passwordless-login-request.processor'; @Controller() @ApiTags('Auth') export class AuthController { constructor( private readonly eventBus: EventBus, private readonly hasher: BcryptHasher, private readonly loginProcessor: LoginProcessor, private readonly logoutProcessor: LogoutProcessor, private readonly passwordlessLoginRequestProcessor: PasswordlessLoginRequestProcessor, private readonly jwtService: JwtService, @Inject(MODULE_OPTIONS_TOKEN) private readonly moduleOptions: IModuleOptions, @Inject(iamConfig.KEY) private readonly config: ConfigType<typeof iamConfig>, ) {} @HttpCode(HttpStatus.OK) @ApiOperation({ operationId: 'authLogin' }) @ApiOkResponse({ type: LoginResponseDto }) @Auth(AuthType.None) @Post('/auth/login') async login( @Body() request: LoginRequestDto, @Res({ passthrough: true }) response: Response, ): Promise<LoginResponseDto> { if (!this.config.auth.methods.includes('basic')) { throw new NotFoundException(); } try { const user = await this.moduleOptions.authService.checkUser( request.username, ); if (!(await this.hasher.compare(request.password, user.getPassword()))) { throw new UnauthorizedException(); } const login = await this.loginProcessor.process(user, response); this.eventBus.publish(new LoggedInEvent(user.getId())); return { accessToken: login.accessToken, refreshToken: login.refreshToken, }; } catch { throw new UnauthorizedException(); } } @HttpCode(HttpStatus.OK) @ApiOperation({ operationId: 'authPasswordlessLogin' }) @ApiOkResponse({ type: LoginResponseDto }) @Auth(AuthType.None) @Get('/auth/passwordless_login/:id') async passwordlessLogin( @Param('id') tokenId: string, @Req() request: Request, @Res({ passthrough: true }) response: Response, ): Promise<LoginResponseDto> { if (!this.config.auth.methods.includes('passwordless')) { throw new NotFoundException(); }
const requestId = request.cookies[TokenType.PasswordlessLoginToken];
if (!requestId) { throw new UnauthorizedException(); } try { const token = await this.moduleOptions.authService.checkToken( tokenId, TokenType.PasswordlessLoginToken, requestId, ); const user = await this.moduleOptions.authService.getUser( token.getUserId(), ); await this.moduleOptions.authService.checkUser(user.getUsername()); await this.moduleOptions.authService.removeToken(tokenId); const login = await this.loginProcessor.process(user, response); return { accessToken: login.accessToken, refreshToken: login.refreshToken, }; } catch { throw new UnauthorizedException(); } } @HttpCode(HttpStatus.NO_CONTENT) @ApiOperation({ operationId: 'authPasswordlessLoginRequest' }) @ApiNoContentResponse() @Auth(AuthType.None) @Post('/auth/passwordless_login') async passwordlessLoginRequest( @Body() request: PasswordlessLoginRequestRequestDto, @Res({ passthrough: true }) response: Response, ): Promise<void> { if (!this.config.auth.methods.includes('passwordless')) { throw new NotFoundException(); } try { const user = await this.moduleOptions.authService.checkUser( request.username, ); await this.passwordlessLoginRequestProcessor.process(user, response); } catch {} } @HttpCode(HttpStatus.OK) @ApiOperation({ operationId: 'authRefreshTokens' }) @ApiOkResponse({ type: LoginResponseDto }) @Auth(AuthType.None) @Get('/auth/refresh_tokens') async refreshTokens( @Req() request: Request, @Res({ passthrough: true }) response: Response, ): Promise<LoginResponseDto> { try { const refreshTokenJwtPayload: IRefreshTokenJwtPayload = await this.jwtService.verifyAsync( request.cookies[TokenType.RefreshToken], ); await this.moduleOptions.authService.checkToken( refreshTokenJwtPayload.id, TokenType.RefreshToken, ); const user = await this.moduleOptions.authService.getUser( refreshTokenJwtPayload.sub, ); await this.moduleOptions.authService.checkUser(user.getUsername()); await this.moduleOptions.authService.removeToken( refreshTokenJwtPayload.id, ); const login = await this.loginProcessor.process(user, response); return { accessToken: login.accessToken, refreshToken: login.refreshToken, }; } catch { throw new UnauthorizedException(); } } @HttpCode(HttpStatus.NO_CONTENT) @ApiOperation({ operationId: 'authLogout' }) @ApiNoContentResponse() @Auth(AuthType.None) @Get('/auth/logout') async logout( @Req() request: Request, @Res({ passthrough: true }) response: Response, @ActiveUser() activeUser: IActiveUser, ) { await this.logoutProcessor.process(request, response); if (!activeUser) { return; } this.eventBus.publish(new LoggedOutEvent(activeUser.userId)); } }
src/controllers/auth.controller.ts
fastnloud-nest-iam-463230d
[ { "filename": "src/processors/logout.processor.ts", "retrieved_chunk": " const refreshTokenJwtPayload: IRefreshTokenJwtPayload =\n await this.jwtService.verifyAsync(\n request.cookies[TokenType.RefreshToken],\n );\n await this.moduleOptions.authService.removeToken(\n refreshTokenJwtPayload.id,\n );\n } catch {}\n response.clearCookie(TokenType.AccessToken);\n response.clearCookie(TokenType.RefreshToken, {", "score": 20.048620418580956 }, { "filename": "src/generators/passwordless-login-token.generator.ts", "retrieved_chunk": " constructor(\n @Inject(iamConfig.KEY)\n private readonly config: ConfigType<typeof iamConfig>,\n ) {}\n async generate(user: IUser, requestId: string): Promise<IToken> {\n const id = randomUUID();\n const ttl = this.config.auth.passwordless.tokenTtl;\n const expiresAt = new Date();\n expiresAt.setSeconds(expiresAt.getSeconds() + ttl);\n return new TokenModel(", "score": 19.102090045179903 }, { "filename": "src/generators/passwordless-login-token.generator.ts", "retrieved_chunk": " id,\n TokenType.PasswordlessLoginToken,\n user.getId(),\n expiresAt,\n requestId,\n );\n }\n}", "score": 16.502195061594563 }, { "filename": "src/processors/passwordless-login-request.processor.ts", "retrieved_chunk": " const requestId = randomUUID();\n const passwordlessLoginToken =\n await this.passwordlessLoginTokenGenerator.generate(user, requestId);\n await this.moduleOptions.authService.saveToken(passwordlessLoginToken);\n response.cookie(TokenType.PasswordlessLoginToken, requestId, {\n secure: this.config.cookie.secure,\n httpOnly: this.config.cookie.httpOnly,\n sameSite: this.config.cookie.sameSite,\n expires: passwordlessLoginToken.getExpiresAt(),\n path: `${this.config.routePathPrefix}/auth`,", "score": 16.1960787724444 }, { "filename": "src/guards/access-token.guard.ts", "retrieved_chunk": " );\n const activeUser: IActiveUser = {\n userId: accessTokenJwtPayload.sub,\n roles: accessTokenJwtPayload.roles,\n };\n request[IAM_REQUEST_USER_KEY] = activeUser;\n } catch {\n throw new UnauthorizedException();\n }\n return true;", "score": 16.161604210295486 } ]
typescript
const requestId = request.cookies[TokenType.PasswordlessLoginToken];
import { LiteralTypeNode, Project, SourceFile, ts } from 'ts-morph'; import { toCamelCase } from './toCamelCase'; import chalk from 'chalk'; export function getEnumsProperties( project: Project, sourceFile: SourceFile, schema: string ) { const databaseInterface = sourceFile.getInterfaceOrThrow('Database'); const publicProperty = databaseInterface.getPropertyOrThrow(schema); const publicType = publicProperty.getType(); const enumsProperty = publicType .getApparentProperties() .find((property) => property.getName() === 'Enums'); if (!enumsProperty) { console.log( `${chalk.yellow.bold( 'warn' )} No Enums property found within the Database interface for schema ${schema}.` ); return []; } const enumsType = project .getProgram() .getTypeChecker() .getTypeAtLocation(enumsProperty.getValueDeclarationOrThrow()); const enumsProperties = enumsType.getProperties(); if (enumsProperties.length < 1) { console.log( `${chalk.yellow.bold( 'warn' )} No enums found within the Enums property for schema ${schema}.` ); return []; } return enumsProperties; } function getEnumValueLabel(value: LiteralTypeNode) { let enumValue = value.getText().replace(/"/g, ''); if (enumValue.includes(' ')) { enumValue.replace(/ /g, '_'); } if (enumValue.includes('-')) { enumValue.replace(/-/g, '_'); } if (enumValue.includes('.')) { enumValue
= toCamelCase(enumValue, '.');
} return enumValue; } function getEnumValueText(value: LiteralTypeNode) { return value.getText(); } export function getEnumValuesText( enumProperty: ReturnType<typeof getEnumsProperties>[number] ) { const enumValues = enumProperty .getValueDeclarationOrThrow() .getChildrenOfKind(ts.SyntaxKind.UnionType) .flatMap((enumValue) => enumValue.getChildrenOfKind(ts.SyntaxKind.LiteralType) ); return enumValues.map( (value) => ` ${getEnumValueLabel(value)} = ${getEnumValueText(value)},` ); }
src/utils/getEnumsProperties.ts
FroggyPanda-better-supabase-types-4e1b1eb
[ { "filename": "src/utils/toCamelCase.ts", "retrieved_chunk": "export function toCamelCase(str: string, delimiter: string = '-') {\n const pattern = new RegExp(('\\\\' + delimiter + '([a-z])'), 'g')\n return str.replace(pattern, (match, capture) => capture.toUpperCase())\n}", "score": 24.217117285997553 }, { "filename": "src/utils/toPascalCase.ts", "retrieved_chunk": "import { singular } from 'pluralize';\nconst wordToPascalCase = (makeSingular: boolean) => (word: string) => {\n const singularWord = makeSingular ? singular(word) : word;\n return singularWord.charAt(0).toUpperCase() + singularWord.substring(1);\n}\nexport function toPascalCase(str: string, makeSingular: boolean = false) {\n return str\n .split('_')\n .map(wordToPascalCase(makeSingular))\n .join('');", "score": 5.344479093161584 }, { "filename": "src/generate.ts", "retrieved_chunk": " const functionNameType = toPascalCase(functionName, makeSingular);\n types.push(\n `export type Args${functionNameType} = Database['${schemaName}']['Functions']['${functionName}']['Args'];`,\n `export type ReturnType${functionNameType} = Database['${schemaName}']['Functions']['${functionName}']['Returns'];`,\n '\\n'\n );\n }\n }\n const fileContent = fs.readFileSync(input, 'utf-8');\n let updatedFileContent = fileContent + '\\n' + types.join('\\n') + '\\n';", "score": 2.636938004825423 }, { "filename": "src/generate.ts", "retrieved_chunk": " if (prettierConfigPath) {\n updatedFileContent = await prettierFormat(\n updatedFileContent,\n prettierConfigPath\n );\n }\n fs.writeFileSync(output, updatedFileContent);\n}", "score": 1.3551732888896444 }, { "filename": "src/index.ts", "retrieved_chunk": " // Load config from 'package.json' file\n // Check if config is correct\n const result = schema.safeParse(packageJsonFile['betterConfig']);\n if (!result.success) {\n console.log('Invalid config in package.json');\n } else {\n if (!result.data.output && !result.data.force) {\n console.log(\n 'It looks like you want to overwrite your input file. Add the force property to do that in your config file.'\n );", "score": 1.2976779016492093 } ]
typescript
= toCamelCase(enumValue, '.');
import defaultStore from './Store'; import produce from 'immer'; import merge from '../utils/merge'; import { logByFunc } from '../log'; import { IStore } from './types'; // TODO add enhancer export function createDefineStore( _store: IStore = defaultStore, enhancer?: (createDefineStore: any) => <S>( name: any, initState: S ) => { getState: () => S; setState: (state: Partial<S> | ((pre: S) => void), currName?: any) => void; regist: (funcs?: {}) => void; store: IStore; setAsyncState: (state: (pre: S) => void) => Promise<S>; name: any; subscribe: any; } ) { console.log('test enhancer.............'); console.log(enhancer); if (typeof enhancer !== 'undefined') { if (typeof enhancer !== 'function') { throw new Error(`Expected the enhancer to be a function`); } return enhancer(createDefineStore); } const store: IStore = _store || defaultStore; return function defineStore<S>(name, initState: S) { function getState(): S { const state = store.getState(); if (typeof state === 'object' && state) { return state[name] as S; } return void 0 as unknown as S; } function setState(state: Partial<S> | ((pre: S) => void)) { const lastState = getState(); //TODO let nextState; if (typeof state === 'function') { nextState = produce(lastState, state as (pre: S) => void); } else { nextState = merge(lastState, state); } if (process.env.NODE_ENV === 'development') { logByFunc(setState, name, lastState, nextState); }
store.setState({
[name]: nextState, }); //TODO } async function setAsyncState(state: (pre: S) => void) { const startStack = new Error().stack; const lastState = getState(); let nextState; nextState = await produce(lastState, state as (pre: S) => void); if (process.env.NODE_ENV === 'development') { logByFunc(startStack, name, lastState, nextState, true); } store.setState({ [name]: nextState, }); } function regist(funcs = {}) { store[name] = merge(store[name], funcs); } function init() { const currentState = getState(); if (!currentState) { setState(initState); } } init(); return { getState, setState, regist, store, setAsyncState, subscribe: store.subscribe, }; }; } export default createDefineStore();
src/store/defineStore.ts
hongyin163-silver-store-8ffcb94
[ { "filename": "src/store/StoreBase.ts", "retrieved_chunk": " const lastState = this.getState();\n let nextState;\n if (typeof state === \"function\") {\n nextState = produce(lastState, state as (pre: S) => void);\n } else {\n nextState = merge(lastState, state);\n }\n if (process.env.NODE_ENV === \"development\") {\n logByFunc(this.setState, this.name, lastState, nextState);\n }", "score": 45.84430825226323 }, { "filename": "src/store/StoreBase.ts", "retrieved_chunk": " setState = (state: S | ((pre: S) => void)) => {\n const lastState = this.getState();\n let nextState;\n if (typeof state === \"function\") {\n nextState = produce(lastState, state as (pre: S) => void);\n } else {\n nextState = merge(lastState, state);\n }\n if (process.env.NODE_ENV === \"development\") {\n logByFunc(this.setState, this.name, lastState, nextState);", "score": 45.84210197946679 }, { "filename": "src/store/StoreBase.ts", "retrieved_chunk": " const currentState = this.getState();\n if (!currentState) {\n if (typeof initState === \"function\") {\n this.setState(initState());\n } else {\n this.setState(initState);\n }\n }\n };\n setState = (state: S | ((pre: S) => void)) => {", "score": 16.416683455487885 }, { "filename": "src/log/index.ts", "retrieved_chunk": "export function logByFunc(stack, name, lastState, nextState, isAsync = false) {\n let obj: any = {};\n // console.trace()\n if (!isAsync) {\n Error.captureStackTrace(obj, stack);\n } else {\n obj.stack = stack;\n }\n const action = extract(obj.stack, isAsync);\n console.group(`%c @${name}/${action}`, 'color:#03A9F4');", "score": 14.408924681701626 }, { "filename": "src/store/StoreBase.ts", "retrieved_chunk": " this.store.setState({\n [this.name]: nextState,\n } as any);\n };\n}", "score": 12.344777091192418 } ]
typescript
store.setState({
import type {OperatorKey} from '../core/operators'; import type {Signal, SignalSet} from '../signals'; import type Rule from './rule'; import {assertArray, assertString} from '../core/assert'; import {operator} from '../core/operators'; import GroupRule from './group'; import InverseRule from './inverse'; import SignalRule from './signal'; function assertObjectWithSingleKey( data: unknown, ): asserts data is {[key: string]: unknown} { if (data == null || typeof data !== 'object') { throw new Error('Expected an object, got: ' + data); } if (Object.keys(data).length !== 1) { throw new Error('Expected an object with a single key, got: ' + data); } } function assertOperatorKey(data: unknown): asserts data is OperatorKey { if (!Object.keys(operator).includes(assertString(data))) { throw new Error('Expected an operator key, got: ' + data); } } export default async function parse<TContext>( data: unknown, signals: SignalSet<TContext>, ): Promise<Rule<TContext>> { assertObjectWithSingleKey(data); const key = Object.keys(data)[0]; const value = data[key]; switch (key) { case '$and': case '$or': return new GroupRule<TContext>( operator[key], await Promise.all( assertArray(value).map(element => parse(element, signals)), ), ); case '$not': return new InverseRule(await parse(value, signals)); } const signal = signals[key]; assertObjectWithSingleKey(value); const operatorKey = Object.keys(value)[0]; assertOperatorKey(operatorKey); const operatorValue = value[operatorKey];
const arraySignal = signal as Signal<TContext, Array<unknown>>;
const numberSignal = signal as Signal<TContext, number>; const stringSignal = signal as Signal<TContext, string>; switch (operatorKey) { case '$and': case '$or': return new SignalRule<TContext, Array<TContext>, Array<Rule<TContext>>>( operator[operatorKey], signal as Signal<TContext, Array<TContext>>, [await parse(operatorValue, signals)], ); case '$not': throw new Error('Invalid operator key: ' + operatorKey); case '$all': case '$any': return new SignalRule( operator[operatorKey], arraySignal, await arraySignal.__assert(operatorValue), ); case '$inc': case '$pfx': case '$sfx': return new SignalRule( operator[operatorKey], stringSignal, await stringSignal.__assert(operatorValue), ); case '$rx': const match = (await stringSignal.__assert(operatorValue)).match( new RegExp('^/(.*?)/([dgimsuy]*)$'), ); if (match == null) { throw new Error('Expected a regular expression, got: ' + operatorValue); } return new SignalRule( operator[operatorKey], signal, new RegExp(match[1], match[2]), ); case '$gt': case '$gte': case '$lt': case '$lte': return new SignalRule( operator[operatorKey], numberSignal, await numberSignal.__assert(operatorValue), ); case '$eq': return new SignalRule(operator[operatorKey], signal, operatorValue); case '$in': return new SignalRule( operator[operatorKey], signal, assertArray(operatorValue), ); } }
src/rules/parse.ts
decs-ruls-c037c91
[ { "filename": "src/core/operators.ts", "retrieved_chunk": " fn: (first: TFirst, second: TSecond) => boolean | Promise<boolean>,\n): OperatorKey {\n const operatorKey = (Object.keys(operator) as Array<OperatorKey>).find(\n key => operator[key] === fn,\n );\n if (operatorKey == null) {\n throw new Error('Invalid operator: ' + fn);\n }\n return operatorKey;\n}", "score": 35.927487841535076 }, { "filename": "src/signals/factory.ts", "retrieved_chunk": " in: values => new SignalRule(operator.$in, signal, values),\n };\n}\nfunction addArrayOperators<TContext, TValue>(\n signal: Signal<TContext, TValue>,\n): Signal<TContext, TValue> {\n const arraySignal = signal as unknown as Signal<TContext, Array<unknown>>;\n return {\n ...signal,\n contains: value => new SignalRule(operator.$all, arraySignal, [value]),", "score": 22.236738441927848 }, { "filename": "src/signals/factory.ts", "retrieved_chunk": "function addStringOperators<TContext, TValue>(\n signal: Signal<TContext, TValue>,\n): Signal<TContext, TValue> {\n const stringSignal = signal as unknown as Signal<TContext, string>;\n return {\n ...signal,\n endsWith: value => new SignalRule(operator.$sfx, stringSignal, value),\n includes: value => new SignalRule(operator.$inc, stringSignal, value),\n matches: value => new SignalRule(operator.$rx, stringSignal, value),\n startsWith: value => new SignalRule(operator.$pfx, stringSignal, value),", "score": 16.62516056516239 }, { "filename": "src/signals/factory.ts", "retrieved_chunk": " containsEvery: values => new SignalRule(operator.$all, arraySignal, values),\n containsSome: values => new SignalRule(operator.$any, arraySignal, values),\n every: rule => new SignalRule(operator.$and, arraySignal, [rule]),\n some: rule => new SignalRule(operator.$or, arraySignal, [rule]),\n };\n}\nfunction addBooleanOperators<TContext, TValue>(\n signal: Signal<TContext, TValue>,\n): Signal<TContext, TValue> {\n const booleanSignal = signal as unknown as Signal<TContext, boolean>;", "score": 16.32950329659075 }, { "filename": "src/signals/set.ts", "retrieved_chunk": "import type {Signal} from './factory';\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type SignalSet<TContext> = Record<string, Signal<TContext, any>>;\nexport function getSignalKey<TContext, TValue>(\n signal: Signal<TContext, TValue>,\n signals: SignalSet<TContext>,\n): string {\n const signalKey = Object.keys(signals).find(\n key => signals[key].equals === signal.equals,\n );", "score": 16.152936803742048 } ]
typescript
const arraySignal = signal as Signal<TContext, Array<unknown>>;
import {describe, expect, test} from '@jest/globals'; import {z} from 'zod'; import {rule} from '../rules'; import {signal} from '../signals'; describe('json-rules-engine', () => { test('basic example', async () => { type Context = { gameDuration: number; personalFouls: number; }; const signals = { gameDuration: signal .type(z.number()) .value<Context>(({gameDuration}) => gameDuration), personalFouls: signal .type(z.number()) .value<Context>(({personalFouls}) => personalFouls), }; const fouledOut = rule.some([ rule.every([ signals.gameDuration.equals(40), signals.personalFouls.greaterThanOrEquals(5), ]), rule.every([ signals.gameDuration.equals(48), signals.personalFouls.greaterThanOrEquals(6), ]), ]); expect( await fouledOut.evaluate({gameDuration: 40, personalFouls: 6}), ).toBeTruthy(); expect( await fouledOut.evaluate({gameDuration: 48, personalFouls: 5}), ).toBeFalsy(); }); test('advanced example', async () => { type Context = { company: string; status: string; ptoDaysTaken: Array<string>; }; const signals = { company: signal.type(z.string()).value<Context>(({company}) => company), ptoDaysTaken: signal .type(z.array(z.string())) .value<Context>(({ptoDaysTaken}) => ptoDaysTaken),
status: signal.type(z.string()).value<Context>(({status}) => status), };
const microsoftEmployeeOutOnChristmas = rule.every([ signals.company.equals('microsoft'), signals.status.in(['active', 'paid-leave']), signals.ptoDaysTaken.contains('2016-12-25'), ]); const accountInformation = { company: 'microsoft', ptoDaysTaken: ['2016-12-24', '2016-12-25'], status: 'active', }; expect( await microsoftEmployeeOutOnChristmas.evaluate(accountInformation), ).toBeTruthy(); accountInformation.company = 'apple'; expect( await microsoftEmployeeOutOnChristmas.evaluate(accountInformation), ).toBeFalsy(); }); });
src/__tests__/comparison.test.ts
decs-ruls-c037c91
[ { "filename": "src/__tests__/main.test.ts", "retrieved_chunk": " sampleArray: signal\n .type(z.array(z.number()))\n .value<Context>(({id}) => [id]),\n sampleBoolean: signal.type(z.boolean()).value<Context>(({id}) => id > 0),\n sampleNumber: signal.type(z.number()).value<Context>(({id}) => 2 * id),\n sampleString: signal.type(z.string()).value<Context>(({id}) => `id=${id}`),\n };\n test('evaluate', async () => {\n expect(await signals.sampleArray.evaluate({id: 123})).toEqual([123]);\n expect(await signals.sampleBoolean.evaluate({id: 123})).toEqual(true);", "score": 45.24562253152101 }, { "filename": "src/__tests__/async.test.ts", "retrieved_chunk": " return {name: `record_${id}`};\n}\ndescribe('ruls', () => {\n const signals = {\n name: signal\n .type(z.string())\n .value<Context>(async ({id}) => (await fetchRecord(id)).name),\n };\n test('evaluate', async () => {\n expect(await signals.name.evaluate({id: 123})).toEqual('record_123');", "score": 31.102744754467988 }, { "filename": "src/__tests__/async.test.ts", "retrieved_chunk": "import {describe, expect, test} from '@jest/globals';\nimport {z} from 'zod';\nimport {signal} from '../signals';\ntype Record = {\n name: string;\n};\ntype Context = {\n id: number;\n};\nasync function fetchRecord(id: number): Promise<Record> {", "score": 30.516422853707866 }, { "filename": "src/__tests__/main.test.ts", "retrieved_chunk": "import {describe, expect, test} from '@jest/globals';\nimport {z} from 'zod';\nimport {rule} from '../rules';\nimport Rule from '../rules/rule';\nimport {signal} from '../signals';\ntype Context = {\n id: number;\n};\ndescribe('ruls', () => {\n const signals = {", "score": 23.825125844762635 }, { "filename": "src/rules/signal.ts", "retrieved_chunk": "import type {Signal, SignalSet} from '../signals';\nimport {getOperatorKey} from '../core/operators';\nimport {getSignalKey} from '../signals/set';\nimport Rule from './rule';\nexport type EncodedSignalRule = {\n [signal: string]: {[operator: string]: unknown};\n};\nexport default class SignalRule<\n TContext,\n TFirst,", "score": 14.0175691087872 } ]
typescript
status: signal.type(z.string()).value<Context>(({status}) => status), };
import type Rule from '../rules/rule'; import type {Infer, Schema} from '@decs/typeschema'; import {createAssert} from '@decs/typeschema'; import {operator} from '../core/operators'; import InverseRule from '../rules/inverse'; import SignalRule from '../rules/signal'; export type Signal<TContext, TValue> = { __assert: (data: unknown) => Promise<TValue>; evaluate: (context: TContext) => Promise<TValue>; not: Omit<Signal<TContext, TValue>, 'evaluate' | 'not'>; equals(value: TValue): Rule<TContext>; in(values: Array<TValue>): Rule<TContext>; } & (TValue extends Array<infer TElement> ? { every(rule: Rule<TElement>): Rule<TContext>; some(rule: Rule<TElement>): Rule<TContext>; contains(value: TElement): Rule<TContext>; containsEvery(values: Array<TElement>): Rule<TContext>; containsSome(values: Array<TElement>): Rule<TContext>; } : TValue extends boolean ? { isTrue(): Rule<TContext>; isFalse(): Rule<TContext>; } : TValue extends number ? { lessThan(value: TValue): Rule<TContext>; lessThanOrEquals(value: TValue): Rule<TContext>; greaterThan(value: TValue): Rule<TContext>; greaterThanOrEquals(value: TValue): Rule<TContext>; } : TValue extends string ? { includes(value: TValue): Rule<TContext>; endsWith(value: TValue): Rule<TContext>; startsWith(value: TValue): Rule<TContext>; matches(value: RegExp): Rule<TContext>; } : Record<string, never>); export type SignalFactory<TValue> = { value: <TContext>( fn: (context: TContext) => TValue | Promise<TValue>, ) => Signal<TContext, TValue>; }; function createSignal<TContext, TValue>( assert: (data: unknown) => Promise<TValue>, fn: (context: TContext) => TValue | Promise<TValue>, ): Signal<TContext, TValue> { return { __assert: assert, evaluate: async (context: TContext) => assert(await fn(context)), } as Signal<TContext, TValue>; } function addOperators<TContext, TValue>( signal: Signal<TContext, TValue>, ): Signal<TContext, TValue> { return { ...signal, equals: value => new SignalRule(operator.$eq, signal, value), in: values => new SignalRule(operator.$in, signal, values), }; } function addArrayOperators<TContext, TValue>( signal: Signal<TContext, TValue>, ): Signal<TContext, TValue> { const arraySignal = signal as unknown as Signal<TContext, Array<unknown>>; return { ...signal, contains: value => new SignalRule(operator.$all, arraySignal, [value]), containsEvery: values => new SignalRule(operator.$all, arraySignal, values), containsSome: values => new SignalRule(operator.$any, arraySignal, values), every: rule => new SignalRule(operator.$and, arraySignal, [rule]), some: rule => new SignalRule(operator.$or, arraySignal, [rule]), }; } function addBooleanOperators<TContext, TValue>( signal: Signal<TContext, TValue>, ): Signal<TContext, TValue> { const booleanSignal = signal as unknown as Signal<TContext, boolean>; return { ...signal, isFalse: () => new SignalRule(operator.$eq, booleanSignal, false), isTrue: () => new SignalRule(operator.$eq, booleanSignal, true), }; } function addNumberOperators<TContext, TValue>( signal: Signal<TContext, TValue>, ): Signal<TContext, TValue> { const numberSignal = signal as unknown as Signal<TContext, number>; return { ...signal, greaterThan: value => new SignalRule(operator.$gt, numberSignal, value), greaterThanOrEquals: value => new SignalRule(operator.$gte, numberSignal, value), lessThan: value => new SignalRule(operator.$lt, numberSignal, value), lessThanOrEquals: value => new SignalRule(operator.$lte, numberSignal, value), }; } function addStringOperators<TContext, TValue>( signal: Signal<TContext, TValue>, ): Signal<TContext, TValue> { const stringSignal = signal as unknown as Signal<TContext, string>; return { ...signal, endsWith: value => new SignalRule(operator.$sfx, stringSignal, value), includes: value => new SignalRule(operator.$inc, stringSignal, value), matches: value => new SignalRule(operator.$rx, stringSignal, value), startsWith: value => new SignalRule(operator.$pfx, stringSignal, value), }; } function addModifiers<TContext, TValue>( signal: Signal<TContext, TValue>, ): Signal<TContext, TValue> { return { ...signal, not: new Proxy(signal, { get: (target, property, receiver) => { const value = Reflect.get(target, property, receiver); return typeof value === 'function' ? (...args: Array<unknown>) => new
InverseRule(value.bind(target)(...args)) : value;
}, }), }; } export function type<TSchema extends Schema>( schema: TSchema, ): SignalFactory<Infer<TSchema>> { return { value<TContext>( fn: (context: TContext) => Infer<TSchema> | Promise<Infer<TSchema>>, ) { return [ addOperators, addArrayOperators, addBooleanOperators, addNumberOperators, addStringOperators, addModifiers, ].reduce( (value, operation) => operation(value), createSignal(createAssert(schema), fn), ); }, }; }
src/signals/factory.ts
decs-ruls-c037c91
[ { "filename": "src/core/assert.ts", "retrieved_chunk": " return value;\n}\nexport function assertNumber(value: unknown): number {\n if (typeof value !== 'number') {\n throw new Error('Expected a number, got: ' + value);\n }\n return value;\n}\nexport function assertString(value: unknown): string {\n if (typeof value !== 'string') {", "score": 21.70683932662313 }, { "filename": "src/core/assert.ts", "retrieved_chunk": "export function assertArray<T>(value: unknown): Array<T> {\n if (!Array.isArray(value)) {\n throw new Error('Expected an array, got: ' + value);\n }\n return value;\n}\nexport function assertBoolean(value: unknown): boolean {\n if (typeof value !== 'boolean') {\n throw new Error('Expected a boolean, got: ' + value);\n }", "score": 21.510609920549392 }, { "filename": "src/rules/parse.ts", "retrieved_chunk": " return new InverseRule(await parse(value, signals));\n }\n const signal = signals[key];\n assertObjectWithSingleKey(value);\n const operatorKey = Object.keys(value)[0];\n assertOperatorKey(operatorKey);\n const operatorValue = value[operatorKey];\n const arraySignal = signal as Signal<TContext, Array<unknown>>;\n const numberSignal = signal as Signal<TContext, number>;\n const stringSignal = signal as Signal<TContext, string>;", "score": 18.364053370004896 }, { "filename": "src/core/assert.ts", "retrieved_chunk": " throw new Error('Expected a string, got: ' + value);\n }\n return value;\n}", "score": 12.86107168784861 }, { "filename": "src/__tests__/comparison.test.ts", "retrieved_chunk": " };\n const signals = {\n company: signal.type(z.string()).value<Context>(({company}) => company),\n ptoDaysTaken: signal\n .type(z.array(z.string()))\n .value<Context>(({ptoDaysTaken}) => ptoDaysTaken),\n status: signal.type(z.string()).value<Context>(({status}) => status),\n };\n const microsoftEmployeeOutOnChristmas = rule.every([\n signals.company.equals('microsoft'),", "score": 11.498578363050731 } ]
typescript
InverseRule(value.bind(target)(...args)) : value;
import type {OperatorKey} from '../core/operators'; import type {Signal, SignalSet} from '../signals'; import type Rule from './rule'; import {assertArray, assertString} from '../core/assert'; import {operator} from '../core/operators'; import GroupRule from './group'; import InverseRule from './inverse'; import SignalRule from './signal'; function assertObjectWithSingleKey( data: unknown, ): asserts data is {[key: string]: unknown} { if (data == null || typeof data !== 'object') { throw new Error('Expected an object, got: ' + data); } if (Object.keys(data).length !== 1) { throw new Error('Expected an object with a single key, got: ' + data); } } function assertOperatorKey(data: unknown): asserts data is OperatorKey { if (!Object.keys(operator).includes(assertString(data))) { throw new Error('Expected an operator key, got: ' + data); } } export default async function parse<TContext>( data: unknown, signals: SignalSet<TContext>, ): Promise<Rule<TContext>> { assertObjectWithSingleKey(data); const key = Object.keys(data)[0]; const value = data[key]; switch (key) { case '$and': case '$or': return new GroupRule<TContext>( operator[key], await Promise.all( assertArray(value).map(element => parse(element, signals)), ), ); case '$not':
return new InverseRule(await parse(value, signals));
} const signal = signals[key]; assertObjectWithSingleKey(value); const operatorKey = Object.keys(value)[0]; assertOperatorKey(operatorKey); const operatorValue = value[operatorKey]; const arraySignal = signal as Signal<TContext, Array<unknown>>; const numberSignal = signal as Signal<TContext, number>; const stringSignal = signal as Signal<TContext, string>; switch (operatorKey) { case '$and': case '$or': return new SignalRule<TContext, Array<TContext>, Array<Rule<TContext>>>( operator[operatorKey], signal as Signal<TContext, Array<TContext>>, [await parse(operatorValue, signals)], ); case '$not': throw new Error('Invalid operator key: ' + operatorKey); case '$all': case '$any': return new SignalRule( operator[operatorKey], arraySignal, await arraySignal.__assert(operatorValue), ); case '$inc': case '$pfx': case '$sfx': return new SignalRule( operator[operatorKey], stringSignal, await stringSignal.__assert(operatorValue), ); case '$rx': const match = (await stringSignal.__assert(operatorValue)).match( new RegExp('^/(.*?)/([dgimsuy]*)$'), ); if (match == null) { throw new Error('Expected a regular expression, got: ' + operatorValue); } return new SignalRule( operator[operatorKey], signal, new RegExp(match[1], match[2]), ); case '$gt': case '$gte': case '$lt': case '$lte': return new SignalRule( operator[operatorKey], numberSignal, await numberSignal.__assert(operatorValue), ); case '$eq': return new SignalRule(operator[operatorKey], signal, operatorValue); case '$in': return new SignalRule( operator[operatorKey], signal, assertArray(operatorValue), ); } }
src/rules/parse.ts
decs-ruls-c037c91
[ { "filename": "src/rules/index.ts", "retrieved_chunk": " none<TContext>(rules: Array<Rule<TContext>>): Rule<TContext> {\n return new InverseRule(new GroupRule(operator.$or, rules));\n },\n parse,\n some<TContext>(rules: Array<Rule<TContext>>): Rule<TContext> {\n return new GroupRule(operator.$or, rules);\n },\n};", "score": 21.20103048046437 }, { "filename": "src/core/operators.ts", "retrieved_chunk": "import type Rule from '../rules/rule';\nexport type OperatorKey = keyof typeof operator;\nexport const operator = {\n $all<T>(first: Array<T>, second: Array<T>): boolean {\n return second.every(element => first.includes(element));\n },\n async $and<T>(first: Array<T>, second: Array<Rule<T>>): Promise<boolean> {\n const values = await Promise.all(\n first.flatMap(firstElement =>\n second.map(secondElement => secondElement.evaluate(firstElement)),", "score": 18.032107012796878 }, { "filename": "src/rules/index.ts", "retrieved_chunk": "import type Rule from './rule';\nimport {operator} from '../core/operators';\nimport GroupRule from './group';\nimport InverseRule from './inverse';\nimport parse from './parse';\nexport type {default as Rule} from './rule';\nexport const rule = {\n every<TContext>(rules: Array<Rule<TContext>>): Rule<TContext> {\n return new GroupRule(operator.$and, rules);\n },", "score": 17.591448518219092 }, { "filename": "src/__tests__/main.test.ts", "retrieved_chunk": " expect(encodedCheck).toEqual({\n $and: [\n {sampleString: {$rx: '/3$/g'}},\n {$not: {sampleArray: {$all: [246]}}},\n ],\n });\n expect(JSON.stringify(encodedCheck)).toEqual(\n '{\"$and\":[{\"sampleString\":{\"$rx\":\"/3$/g\"}},{\"$not\":{\"sampleArray\":{\"$all\":[246]}}}]}',\n );\n const parsedCheck = await rule.parse(encodedCheck, signals);", "score": 17.40786828613402 }, { "filename": "src/core/operators.ts", "retrieved_chunk": " },\n async $or<T>(first: Array<T>, second: Array<Rule<T>>): Promise<boolean> {\n const values = await Promise.all(\n first.flatMap(firstElement =>\n second.map(secondElement => secondElement.evaluate(firstElement)),\n ),\n );\n return values.some(Boolean);\n },\n $pfx<T extends string>(first: T, second: T): boolean {", "score": 11.230051276214802 } ]
typescript
return new InverseRule(await parse(value, signals));
import type {OperatorKey} from '../core/operators'; import type {Signal, SignalSet} from '../signals'; import type Rule from './rule'; import {assertArray, assertString} from '../core/assert'; import {operator} from '../core/operators'; import GroupRule from './group'; import InverseRule from './inverse'; import SignalRule from './signal'; function assertObjectWithSingleKey( data: unknown, ): asserts data is {[key: string]: unknown} { if (data == null || typeof data !== 'object') { throw new Error('Expected an object, got: ' + data); } if (Object.keys(data).length !== 1) { throw new Error('Expected an object with a single key, got: ' + data); } } function assertOperatorKey(data: unknown): asserts data is OperatorKey { if (!Object.keys(operator).includes(assertString(data))) { throw new Error('Expected an operator key, got: ' + data); } } export default async function parse<TContext>( data: unknown, signals: SignalSet<TContext>, ): Promise<Rule<TContext>> { assertObjectWithSingleKey(data); const key = Object.keys(data)[0]; const value = data[key]; switch (key) { case '$and': case '$or': return new GroupRule<TContext>( operator[key], await Promise.all( assertArray(value).map(element => parse(element, signals)), ), ); case '$not': return new InverseRule(await parse(value, signals)); } const signal = signals[key]; assertObjectWithSingleKey(value); const operatorKey = Object.keys(value)[0]; assertOperatorKey(operatorKey); const operatorValue = value[operatorKey]; const arraySignal = signal as Signal<TContext, Array<unknown>>; const numberSignal = signal as Signal<TContext, number>; const stringSignal = signal as Signal<TContext, string>; switch (operatorKey) { case '$and': case '$or': return new SignalRule<TContext, Array<TContext>, Array<Rule<TContext>>>( operator[operatorKey], signal as Signal<TContext, Array<TContext>>, [await parse(operatorValue, signals)], ); case '$not': throw new Error('Invalid operator key: ' + operatorKey); case '$all': case '$any': return new SignalRule( operator[operatorKey], arraySignal, await arraySignal.__assert(operatorValue), ); case '$inc': case '$pfx': case '$sfx': return new SignalRule( operator[operatorKey], stringSignal, await stringSignal.__assert(operatorValue), ); case '$rx': const match = (await stringSignal.__assert(operatorValue)).match( new RegExp('^/(.*?)/([dgimsuy]*)$'), ); if (match == null) { throw new Error('Expected a regular expression, got: ' + operatorValue); } return new SignalRule( operator[operatorKey], signal, new RegExp(match[1], match[2]), ); case '$gt': case '$gte': case '$lt': case '$lte': return new SignalRule( operator[operatorKey], numberSignal, await numberSignal.__assert(operatorValue), ); case '$eq':
return new SignalRule(operator[operatorKey], signal, operatorValue);
case '$in': return new SignalRule( operator[operatorKey], signal, assertArray(operatorValue), ); } }
src/rules/parse.ts
decs-ruls-c037c91
[ { "filename": "src/signals/factory.ts", "retrieved_chunk": " return {\n ...signal,\n greaterThan: value => new SignalRule(operator.$gt, numberSignal, value),\n greaterThanOrEquals: value =>\n new SignalRule(operator.$gte, numberSignal, value),\n lessThan: value => new SignalRule(operator.$lt, numberSignal, value),\n lessThanOrEquals: value =>\n new SignalRule(operator.$lte, numberSignal, value),\n };\n}", "score": 34.49253610009954 }, { "filename": "src/signals/factory.ts", "retrieved_chunk": " return {\n ...signal,\n isFalse: () => new SignalRule(operator.$eq, booleanSignal, false),\n isTrue: () => new SignalRule(operator.$eq, booleanSignal, true),\n };\n}\nfunction addNumberOperators<TContext, TValue>(\n signal: Signal<TContext, TValue>,\n): Signal<TContext, TValue> {\n const numberSignal = signal as unknown as Signal<TContext, number>;", "score": 21.09576237916552 }, { "filename": "src/core/operators.ts", "retrieved_chunk": " fn: (first: TFirst, second: TSecond) => boolean | Promise<boolean>,\n): OperatorKey {\n const operatorKey = (Object.keys(operator) as Array<OperatorKey>).find(\n key => operator[key] === fn,\n );\n if (operatorKey == null) {\n throw new Error('Invalid operator: ' + fn);\n }\n return operatorKey;\n}", "score": 17.338705557806442 }, { "filename": "src/signals/factory.ts", "retrieved_chunk": " __assert: assert,\n evaluate: async (context: TContext) => assert(await fn(context)),\n } as Signal<TContext, TValue>;\n}\nfunction addOperators<TContext, TValue>(\n signal: Signal<TContext, TValue>,\n): Signal<TContext, TValue> {\n return {\n ...signal,\n equals: value => new SignalRule(operator.$eq, signal, value),", "score": 15.055218133174158 }, { "filename": "src/signals/factory.ts", "retrieved_chunk": "function addStringOperators<TContext, TValue>(\n signal: Signal<TContext, TValue>,\n): Signal<TContext, TValue> {\n const stringSignal = signal as unknown as Signal<TContext, string>;\n return {\n ...signal,\n endsWith: value => new SignalRule(operator.$sfx, stringSignal, value),\n includes: value => new SignalRule(operator.$inc, stringSignal, value),\n matches: value => new SignalRule(operator.$rx, stringSignal, value),\n startsWith: value => new SignalRule(operator.$pfx, stringSignal, value),", "score": 12.917565131721256 } ]
typescript
return new SignalRule(operator[operatorKey], signal, operatorValue);
import type Rule from '../rules/rule'; import type {Infer, Schema} from '@decs/typeschema'; import {createAssert} from '@decs/typeschema'; import {operator} from '../core/operators'; import InverseRule from '../rules/inverse'; import SignalRule from '../rules/signal'; export type Signal<TContext, TValue> = { __assert: (data: unknown) => Promise<TValue>; evaluate: (context: TContext) => Promise<TValue>; not: Omit<Signal<TContext, TValue>, 'evaluate' | 'not'>; equals(value: TValue): Rule<TContext>; in(values: Array<TValue>): Rule<TContext>; } & (TValue extends Array<infer TElement> ? { every(rule: Rule<TElement>): Rule<TContext>; some(rule: Rule<TElement>): Rule<TContext>; contains(value: TElement): Rule<TContext>; containsEvery(values: Array<TElement>): Rule<TContext>; containsSome(values: Array<TElement>): Rule<TContext>; } : TValue extends boolean ? { isTrue(): Rule<TContext>; isFalse(): Rule<TContext>; } : TValue extends number ? { lessThan(value: TValue): Rule<TContext>; lessThanOrEquals(value: TValue): Rule<TContext>; greaterThan(value: TValue): Rule<TContext>; greaterThanOrEquals(value: TValue): Rule<TContext>; } : TValue extends string ? { includes(value: TValue): Rule<TContext>; endsWith(value: TValue): Rule<TContext>; startsWith(value: TValue): Rule<TContext>; matches(value: RegExp): Rule<TContext>; } : Record<string, never>); export type SignalFactory<TValue> = { value: <TContext>( fn: (context: TContext) => TValue | Promise<TValue>, ) => Signal<TContext, TValue>; }; function createSignal<TContext, TValue>( assert: (data: unknown) => Promise<TValue>, fn: (context: TContext) => TValue | Promise<TValue>, ): Signal<TContext, TValue> { return { __assert: assert, evaluate: async (context: TContext) => assert(await fn(context)), } as Signal<TContext, TValue>; } function addOperators<TContext, TValue>( signal: Signal<TContext, TValue>, ): Signal<TContext, TValue> { return { ...signal, equals: value => new
SignalRule(operator.$eq, signal, value), in: values => new SignalRule(operator.$in, signal, values), };
} function addArrayOperators<TContext, TValue>( signal: Signal<TContext, TValue>, ): Signal<TContext, TValue> { const arraySignal = signal as unknown as Signal<TContext, Array<unknown>>; return { ...signal, contains: value => new SignalRule(operator.$all, arraySignal, [value]), containsEvery: values => new SignalRule(operator.$all, arraySignal, values), containsSome: values => new SignalRule(operator.$any, arraySignal, values), every: rule => new SignalRule(operator.$and, arraySignal, [rule]), some: rule => new SignalRule(operator.$or, arraySignal, [rule]), }; } function addBooleanOperators<TContext, TValue>( signal: Signal<TContext, TValue>, ): Signal<TContext, TValue> { const booleanSignal = signal as unknown as Signal<TContext, boolean>; return { ...signal, isFalse: () => new SignalRule(operator.$eq, booleanSignal, false), isTrue: () => new SignalRule(operator.$eq, booleanSignal, true), }; } function addNumberOperators<TContext, TValue>( signal: Signal<TContext, TValue>, ): Signal<TContext, TValue> { const numberSignal = signal as unknown as Signal<TContext, number>; return { ...signal, greaterThan: value => new SignalRule(operator.$gt, numberSignal, value), greaterThanOrEquals: value => new SignalRule(operator.$gte, numberSignal, value), lessThan: value => new SignalRule(operator.$lt, numberSignal, value), lessThanOrEquals: value => new SignalRule(operator.$lte, numberSignal, value), }; } function addStringOperators<TContext, TValue>( signal: Signal<TContext, TValue>, ): Signal<TContext, TValue> { const stringSignal = signal as unknown as Signal<TContext, string>; return { ...signal, endsWith: value => new SignalRule(operator.$sfx, stringSignal, value), includes: value => new SignalRule(operator.$inc, stringSignal, value), matches: value => new SignalRule(operator.$rx, stringSignal, value), startsWith: value => new SignalRule(operator.$pfx, stringSignal, value), }; } function addModifiers<TContext, TValue>( signal: Signal<TContext, TValue>, ): Signal<TContext, TValue> { return { ...signal, not: new Proxy(signal, { get: (target, property, receiver) => { const value = Reflect.get(target, property, receiver); return typeof value === 'function' ? (...args: Array<unknown>) => new InverseRule(value.bind(target)(...args)) : value; }, }), }; } export function type<TSchema extends Schema>( schema: TSchema, ): SignalFactory<Infer<TSchema>> { return { value<TContext>( fn: (context: TContext) => Infer<TSchema> | Promise<Infer<TSchema>>, ) { return [ addOperators, addArrayOperators, addBooleanOperators, addNumberOperators, addStringOperators, addModifiers, ].reduce( (value, operation) => operation(value), createSignal(createAssert(schema), fn), ); }, }; }
src/signals/factory.ts
decs-ruls-c037c91
[ { "filename": "src/signals/set.ts", "retrieved_chunk": "import type {Signal} from './factory';\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type SignalSet<TContext> = Record<string, Signal<TContext, any>>;\nexport function getSignalKey<TContext, TValue>(\n signal: Signal<TContext, TValue>,\n signals: SignalSet<TContext>,\n): string {\n const signalKey = Object.keys(signals).find(\n key => signals[key].equals === signal.equals,\n );", "score": 27.790577037224956 }, { "filename": "src/rules/parse.ts", "retrieved_chunk": " case '$lte':\n return new SignalRule(\n operator[operatorKey],\n numberSignal,\n await numberSignal.__assert(operatorValue),\n );\n case '$eq':\n return new SignalRule(operator[operatorKey], signal, operatorValue);\n case '$in':\n return new SignalRule(", "score": 23.137501754889616 }, { "filename": "src/core/evaluator.ts", "retrieved_chunk": "export default abstract class Evaluator<TContext, TValue> {\n constructor(protected fn: (context: TContext) => TValue | Promise<TValue>) {}\n async evaluate(context: TContext): Promise<TValue> {\n return this.fn(context);\n }\n}", "score": 21.207601197409513 }, { "filename": "src/rules/parse.ts", "retrieved_chunk": " return new InverseRule(await parse(value, signals));\n }\n const signal = signals[key];\n assertObjectWithSingleKey(value);\n const operatorKey = Object.keys(value)[0];\n assertOperatorKey(operatorKey);\n const operatorValue = value[operatorKey];\n const arraySignal = signal as Signal<TContext, Array<unknown>>;\n const numberSignal = signal as Signal<TContext, number>;\n const stringSignal = signal as Signal<TContext, string>;", "score": 18.6186076420113 }, { "filename": "src/rules/parse.ts", "retrieved_chunk": " switch (operatorKey) {\n case '$and':\n case '$or':\n return new SignalRule<TContext, Array<TContext>, Array<Rule<TContext>>>(\n operator[operatorKey],\n signal as Signal<TContext, Array<TContext>>,\n [await parse(operatorValue, signals)],\n );\n case '$not':\n throw new Error('Invalid operator key: ' + operatorKey);", "score": 17.12167315343835 } ]
typescript
SignalRule(operator.$eq, signal, value), in: values => new SignalRule(operator.$in, signal, values), };
import type Rule from '../rules/rule'; import type {Infer, Schema} from '@decs/typeschema'; import {createAssert} from '@decs/typeschema'; import {operator} from '../core/operators'; import InverseRule from '../rules/inverse'; import SignalRule from '../rules/signal'; export type Signal<TContext, TValue> = { __assert: (data: unknown) => Promise<TValue>; evaluate: (context: TContext) => Promise<TValue>; not: Omit<Signal<TContext, TValue>, 'evaluate' | 'not'>; equals(value: TValue): Rule<TContext>; in(values: Array<TValue>): Rule<TContext>; } & (TValue extends Array<infer TElement> ? { every(rule: Rule<TElement>): Rule<TContext>; some(rule: Rule<TElement>): Rule<TContext>; contains(value: TElement): Rule<TContext>; containsEvery(values: Array<TElement>): Rule<TContext>; containsSome(values: Array<TElement>): Rule<TContext>; } : TValue extends boolean ? { isTrue(): Rule<TContext>; isFalse(): Rule<TContext>; } : TValue extends number ? { lessThan(value: TValue): Rule<TContext>; lessThanOrEquals(value: TValue): Rule<TContext>; greaterThan(value: TValue): Rule<TContext>; greaterThanOrEquals(value: TValue): Rule<TContext>; } : TValue extends string ? { includes(value: TValue): Rule<TContext>; endsWith(value: TValue): Rule<TContext>; startsWith(value: TValue): Rule<TContext>; matches(value: RegExp): Rule<TContext>; } : Record<string, never>); export type SignalFactory<TValue> = { value: <TContext>( fn: (context: TContext) => TValue | Promise<TValue>, ) => Signal<TContext, TValue>; }; function createSignal<TContext, TValue>( assert: (data: unknown) => Promise<TValue>, fn: (context: TContext) => TValue | Promise<TValue>, ): Signal<TContext, TValue> { return { __assert: assert, evaluate: async (context: TContext) => assert(await fn(context)), } as Signal<TContext, TValue>; } function addOperators<TContext, TValue>( signal: Signal<TContext, TValue>, ): Signal<TContext, TValue> { return { ...signal, equals: value => new SignalRule
(operator.$eq, signal, value), in: values => new SignalRule(operator.$in, signal, values), };
} function addArrayOperators<TContext, TValue>( signal: Signal<TContext, TValue>, ): Signal<TContext, TValue> { const arraySignal = signal as unknown as Signal<TContext, Array<unknown>>; return { ...signal, contains: value => new SignalRule(operator.$all, arraySignal, [value]), containsEvery: values => new SignalRule(operator.$all, arraySignal, values), containsSome: values => new SignalRule(operator.$any, arraySignal, values), every: rule => new SignalRule(operator.$and, arraySignal, [rule]), some: rule => new SignalRule(operator.$or, arraySignal, [rule]), }; } function addBooleanOperators<TContext, TValue>( signal: Signal<TContext, TValue>, ): Signal<TContext, TValue> { const booleanSignal = signal as unknown as Signal<TContext, boolean>; return { ...signal, isFalse: () => new SignalRule(operator.$eq, booleanSignal, false), isTrue: () => new SignalRule(operator.$eq, booleanSignal, true), }; } function addNumberOperators<TContext, TValue>( signal: Signal<TContext, TValue>, ): Signal<TContext, TValue> { const numberSignal = signal as unknown as Signal<TContext, number>; return { ...signal, greaterThan: value => new SignalRule(operator.$gt, numberSignal, value), greaterThanOrEquals: value => new SignalRule(operator.$gte, numberSignal, value), lessThan: value => new SignalRule(operator.$lt, numberSignal, value), lessThanOrEquals: value => new SignalRule(operator.$lte, numberSignal, value), }; } function addStringOperators<TContext, TValue>( signal: Signal<TContext, TValue>, ): Signal<TContext, TValue> { const stringSignal = signal as unknown as Signal<TContext, string>; return { ...signal, endsWith: value => new SignalRule(operator.$sfx, stringSignal, value), includes: value => new SignalRule(operator.$inc, stringSignal, value), matches: value => new SignalRule(operator.$rx, stringSignal, value), startsWith: value => new SignalRule(operator.$pfx, stringSignal, value), }; } function addModifiers<TContext, TValue>( signal: Signal<TContext, TValue>, ): Signal<TContext, TValue> { return { ...signal, not: new Proxy(signal, { get: (target, property, receiver) => { const value = Reflect.get(target, property, receiver); return typeof value === 'function' ? (...args: Array<unknown>) => new InverseRule(value.bind(target)(...args)) : value; }, }), }; } export function type<TSchema extends Schema>( schema: TSchema, ): SignalFactory<Infer<TSchema>> { return { value<TContext>( fn: (context: TContext) => Infer<TSchema> | Promise<Infer<TSchema>>, ) { return [ addOperators, addArrayOperators, addBooleanOperators, addNumberOperators, addStringOperators, addModifiers, ].reduce( (value, operation) => operation(value), createSignal(createAssert(schema), fn), ); }, }; }
src/signals/factory.ts
decs-ruls-c037c91
[ { "filename": "src/signals/set.ts", "retrieved_chunk": "import type {Signal} from './factory';\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type SignalSet<TContext> = Record<string, Signal<TContext, any>>;\nexport function getSignalKey<TContext, TValue>(\n signal: Signal<TContext, TValue>,\n signals: SignalSet<TContext>,\n): string {\n const signalKey = Object.keys(signals).find(\n key => signals[key].equals === signal.equals,\n );", "score": 27.790577037224956 }, { "filename": "src/rules/parse.ts", "retrieved_chunk": " case '$lte':\n return new SignalRule(\n operator[operatorKey],\n numberSignal,\n await numberSignal.__assert(operatorValue),\n );\n case '$eq':\n return new SignalRule(operator[operatorKey], signal, operatorValue);\n case '$in':\n return new SignalRule(", "score": 23.137501754889616 }, { "filename": "src/core/evaluator.ts", "retrieved_chunk": "export default abstract class Evaluator<TContext, TValue> {\n constructor(protected fn: (context: TContext) => TValue | Promise<TValue>) {}\n async evaluate(context: TContext): Promise<TValue> {\n return this.fn(context);\n }\n}", "score": 21.207601197409513 }, { "filename": "src/rules/parse.ts", "retrieved_chunk": " return new InverseRule(await parse(value, signals));\n }\n const signal = signals[key];\n assertObjectWithSingleKey(value);\n const operatorKey = Object.keys(value)[0];\n assertOperatorKey(operatorKey);\n const operatorValue = value[operatorKey];\n const arraySignal = signal as Signal<TContext, Array<unknown>>;\n const numberSignal = signal as Signal<TContext, number>;\n const stringSignal = signal as Signal<TContext, string>;", "score": 18.6186076420113 }, { "filename": "src/rules/parse.ts", "retrieved_chunk": " switch (operatorKey) {\n case '$and':\n case '$or':\n return new SignalRule<TContext, Array<TContext>, Array<Rule<TContext>>>(\n operator[operatorKey],\n signal as Signal<TContext, Array<TContext>>,\n [await parse(operatorValue, signals)],\n );\n case '$not':\n throw new Error('Invalid operator key: ' + operatorKey);", "score": 17.12167315343835 } ]
typescript
(operator.$eq, signal, value), in: values => new SignalRule(operator.$in, signal, values), };
import type Rule from '../rules/rule'; import type {Infer, Schema} from '@decs/typeschema'; import {createAssert} from '@decs/typeschema'; import {operator} from '../core/operators'; import InverseRule from '../rules/inverse'; import SignalRule from '../rules/signal'; export type Signal<TContext, TValue> = { __assert: (data: unknown) => Promise<TValue>; evaluate: (context: TContext) => Promise<TValue>; not: Omit<Signal<TContext, TValue>, 'evaluate' | 'not'>; equals(value: TValue): Rule<TContext>; in(values: Array<TValue>): Rule<TContext>; } & (TValue extends Array<infer TElement> ? { every(rule: Rule<TElement>): Rule<TContext>; some(rule: Rule<TElement>): Rule<TContext>; contains(value: TElement): Rule<TContext>; containsEvery(values: Array<TElement>): Rule<TContext>; containsSome(values: Array<TElement>): Rule<TContext>; } : TValue extends boolean ? { isTrue(): Rule<TContext>; isFalse(): Rule<TContext>; } : TValue extends number ? { lessThan(value: TValue): Rule<TContext>; lessThanOrEquals(value: TValue): Rule<TContext>; greaterThan(value: TValue): Rule<TContext>; greaterThanOrEquals(value: TValue): Rule<TContext>; } : TValue extends string ? { includes(value: TValue): Rule<TContext>; endsWith(value: TValue): Rule<TContext>; startsWith(value: TValue): Rule<TContext>; matches(value: RegExp): Rule<TContext>; } : Record<string, never>); export type SignalFactory<TValue> = { value: <TContext>( fn: (context: TContext) => TValue | Promise<TValue>, ) => Signal<TContext, TValue>; }; function createSignal<TContext, TValue>( assert: (data: unknown) => Promise<TValue>, fn: (context: TContext) => TValue | Promise<TValue>, ): Signal<TContext, TValue> { return { __assert: assert, evaluate: async (context: TContext) => assert(await fn(context)), } as Signal<TContext, TValue>; } function addOperators<TContext, TValue>( signal: Signal<TContext, TValue>, ): Signal<TContext, TValue> { return { ...signal, equals: value => new SignalRule(operator.$eq, signal, value), in: values => new SignalRule(operator.$in, signal, values), }; } function addArrayOperators<TContext, TValue>( signal: Signal<TContext, TValue>, ): Signal<TContext, TValue> { const arraySignal = signal as unknown as Signal<TContext, Array<unknown>>; return { ...signal, contains: value => new SignalRule(operator.$all, arraySignal, [value]), containsEvery: values => new SignalRule(operator.$all, arraySignal, values), containsSome: values => new SignalRule(operator.$any, arraySignal, values), every: rule => new SignalRule(operator.$and, arraySignal, [rule]),
some: rule => new SignalRule(operator.$or, arraySignal, [rule]), };
} function addBooleanOperators<TContext, TValue>( signal: Signal<TContext, TValue>, ): Signal<TContext, TValue> { const booleanSignal = signal as unknown as Signal<TContext, boolean>; return { ...signal, isFalse: () => new SignalRule(operator.$eq, booleanSignal, false), isTrue: () => new SignalRule(operator.$eq, booleanSignal, true), }; } function addNumberOperators<TContext, TValue>( signal: Signal<TContext, TValue>, ): Signal<TContext, TValue> { const numberSignal = signal as unknown as Signal<TContext, number>; return { ...signal, greaterThan: value => new SignalRule(operator.$gt, numberSignal, value), greaterThanOrEquals: value => new SignalRule(operator.$gte, numberSignal, value), lessThan: value => new SignalRule(operator.$lt, numberSignal, value), lessThanOrEquals: value => new SignalRule(operator.$lte, numberSignal, value), }; } function addStringOperators<TContext, TValue>( signal: Signal<TContext, TValue>, ): Signal<TContext, TValue> { const stringSignal = signal as unknown as Signal<TContext, string>; return { ...signal, endsWith: value => new SignalRule(operator.$sfx, stringSignal, value), includes: value => new SignalRule(operator.$inc, stringSignal, value), matches: value => new SignalRule(operator.$rx, stringSignal, value), startsWith: value => new SignalRule(operator.$pfx, stringSignal, value), }; } function addModifiers<TContext, TValue>( signal: Signal<TContext, TValue>, ): Signal<TContext, TValue> { return { ...signal, not: new Proxy(signal, { get: (target, property, receiver) => { const value = Reflect.get(target, property, receiver); return typeof value === 'function' ? (...args: Array<unknown>) => new InverseRule(value.bind(target)(...args)) : value; }, }), }; } export function type<TSchema extends Schema>( schema: TSchema, ): SignalFactory<Infer<TSchema>> { return { value<TContext>( fn: (context: TContext) => Infer<TSchema> | Promise<Infer<TSchema>>, ) { return [ addOperators, addArrayOperators, addBooleanOperators, addNumberOperators, addStringOperators, addModifiers, ].reduce( (value, operation) => operation(value), createSignal(createAssert(schema), fn), ); }, }; }
src/signals/factory.ts
decs-ruls-c037c91
[ { "filename": "src/rules/parse.ts", "retrieved_chunk": " case '$all':\n case '$any':\n return new SignalRule(\n operator[operatorKey],\n arraySignal,\n await arraySignal.__assert(operatorValue),\n );\n case '$inc':\n case '$pfx':\n case '$sfx':", "score": 57.4899653964959 }, { "filename": "src/rules/parse.ts", "retrieved_chunk": " return new InverseRule(await parse(value, signals));\n }\n const signal = signals[key];\n assertObjectWithSingleKey(value);\n const operatorKey = Object.keys(value)[0];\n assertOperatorKey(operatorKey);\n const operatorValue = value[operatorKey];\n const arraySignal = signal as Signal<TContext, Array<unknown>>;\n const numberSignal = signal as Signal<TContext, number>;\n const stringSignal = signal as Signal<TContext, string>;", "score": 44.988505330592716 }, { "filename": "src/rules/parse.ts", "retrieved_chunk": " switch (operatorKey) {\n case '$and':\n case '$or':\n return new SignalRule<TContext, Array<TContext>, Array<Rule<TContext>>>(\n operator[operatorKey],\n signal as Signal<TContext, Array<TContext>>,\n [await parse(operatorValue, signals)],\n );\n case '$not':\n throw new Error('Invalid operator key: ' + operatorKey);", "score": 35.772797952319046 }, { "filename": "src/rules/parse.ts", "retrieved_chunk": " case '$lte':\n return new SignalRule(\n operator[operatorKey],\n numberSignal,\n await numberSignal.__assert(operatorValue),\n );\n case '$eq':\n return new SignalRule(operator[operatorKey], signal, operatorValue);\n case '$in':\n return new SignalRule(", "score": 29.40901869043796 }, { "filename": "src/core/operators.ts", "retrieved_chunk": " },\n async $or<T>(first: Array<T>, second: Array<Rule<T>>): Promise<boolean> {\n const values = await Promise.all(\n first.flatMap(firstElement =>\n second.map(secondElement => secondElement.evaluate(firstElement)),\n ),\n );\n return values.some(Boolean);\n },\n $pfx<T extends string>(first: T, second: T): boolean {", "score": 24.619229034934442 } ]
typescript
some: rule => new SignalRule(operator.$or, arraySignal, [rule]), };
import type Rule from '../rules/rule'; import type {Infer, Schema} from '@decs/typeschema'; import {createAssert} from '@decs/typeschema'; import {operator} from '../core/operators'; import InverseRule from '../rules/inverse'; import SignalRule from '../rules/signal'; export type Signal<TContext, TValue> = { __assert: (data: unknown) => Promise<TValue>; evaluate: (context: TContext) => Promise<TValue>; not: Omit<Signal<TContext, TValue>, 'evaluate' | 'not'>; equals(value: TValue): Rule<TContext>; in(values: Array<TValue>): Rule<TContext>; } & (TValue extends Array<infer TElement> ? { every(rule: Rule<TElement>): Rule<TContext>; some(rule: Rule<TElement>): Rule<TContext>; contains(value: TElement): Rule<TContext>; containsEvery(values: Array<TElement>): Rule<TContext>; containsSome(values: Array<TElement>): Rule<TContext>; } : TValue extends boolean ? { isTrue(): Rule<TContext>; isFalse(): Rule<TContext>; } : TValue extends number ? { lessThan(value: TValue): Rule<TContext>; lessThanOrEquals(value: TValue): Rule<TContext>; greaterThan(value: TValue): Rule<TContext>; greaterThanOrEquals(value: TValue): Rule<TContext>; } : TValue extends string ? { includes(value: TValue): Rule<TContext>; endsWith(value: TValue): Rule<TContext>; startsWith(value: TValue): Rule<TContext>; matches(value: RegExp): Rule<TContext>; } : Record<string, never>); export type SignalFactory<TValue> = { value: <TContext>( fn: (context: TContext) => TValue | Promise<TValue>, ) => Signal<TContext, TValue>; }; function createSignal<TContext, TValue>( assert: (data: unknown) => Promise<TValue>, fn: (context: TContext) => TValue | Promise<TValue>, ): Signal<TContext, TValue> { return { __assert: assert, evaluate: async (context: TContext) => assert(await fn(context)), } as Signal<TContext, TValue>; } function addOperators<TContext, TValue>( signal: Signal<TContext, TValue>, ): Signal<TContext, TValue> { return { ...signal, equals: value => new SignalRule(operator.$eq, signal, value), in: values => new SignalRule(operator.$in, signal, values), }; } function addArrayOperators<TContext, TValue>( signal: Signal<TContext, TValue>, ): Signal<TContext, TValue> { const arraySignal = signal as unknown as Signal<TContext, Array<unknown>>; return { ...signal, contains: value => new SignalRule(operator.$all, arraySignal, [value]), containsEvery: values => new SignalRule(operator.$all, arraySignal, values), containsSome: values => new SignalRule(operator.$any, arraySignal, values), every: rule => new SignalRule(operator.$and, arraySignal, [rule]), some: rule => new SignalRule(operator.$or, arraySignal, [rule]), }; } function addBooleanOperators<TContext, TValue>( signal: Signal<TContext, TValue>, ): Signal<TContext, TValue> { const booleanSignal = signal as unknown as Signal<TContext, boolean>; return { ...signal, isFalse: () => new SignalRule(operator.$eq, booleanSignal, false), isTrue: () => new SignalRule(operator.$eq, booleanSignal, true), }; } function addNumberOperators<TContext, TValue>( signal: Signal<TContext, TValue>, ): Signal<TContext, TValue> { const numberSignal = signal as unknown as Signal<TContext, number>; return { ...signal, greaterThan: value => new SignalRule(operator.$gt, numberSignal, value), greaterThanOrEquals: value => new SignalRule(operator.$gte, numberSignal, value), lessThan: value => new SignalRule(operator.$lt, numberSignal, value), lessThanOrEquals: value => new SignalRule(operator.$lte, numberSignal, value), }; } function addStringOperators<TContext, TValue>( signal: Signal<TContext, TValue>, ): Signal<TContext, TValue> { const stringSignal = signal as unknown as Signal<TContext, string>; return { ...signal, endsWith: value => new SignalRule(operator.$sfx, stringSignal, value), includes: value => new SignalRule(operator.$inc, stringSignal, value), matches: value => new SignalRule(operator.$rx, stringSignal, value), startsWith: value => new SignalRule
(operator.$pfx, stringSignal, value), };
} function addModifiers<TContext, TValue>( signal: Signal<TContext, TValue>, ): Signal<TContext, TValue> { return { ...signal, not: new Proxy(signal, { get: (target, property, receiver) => { const value = Reflect.get(target, property, receiver); return typeof value === 'function' ? (...args: Array<unknown>) => new InverseRule(value.bind(target)(...args)) : value; }, }), }; } export function type<TSchema extends Schema>( schema: TSchema, ): SignalFactory<Infer<TSchema>> { return { value<TContext>( fn: (context: TContext) => Infer<TSchema> | Promise<Infer<TSchema>>, ) { return [ addOperators, addArrayOperators, addBooleanOperators, addNumberOperators, addStringOperators, addModifiers, ].reduce( (value, operation) => operation(value), createSignal(createAssert(schema), fn), ); }, }; }
src/signals/factory.ts
decs-ruls-c037c91
[ { "filename": "src/rules/parse.ts", "retrieved_chunk": " return new InverseRule(await parse(value, signals));\n }\n const signal = signals[key];\n assertObjectWithSingleKey(value);\n const operatorKey = Object.keys(value)[0];\n assertOperatorKey(operatorKey);\n const operatorValue = value[operatorKey];\n const arraySignal = signal as Signal<TContext, Array<unknown>>;\n const numberSignal = signal as Signal<TContext, number>;\n const stringSignal = signal as Signal<TContext, string>;", "score": 53.452442197691255 }, { "filename": "src/rules/parse.ts", "retrieved_chunk": " return new SignalRule(\n operator[operatorKey],\n stringSignal,\n await stringSignal.__assert(operatorValue),\n );\n case '$rx':\n const match = (await stringSignal.__assert(operatorValue)).match(\n new RegExp('^/(.*?)/([dgimsuy]*)$'),\n );\n if (match == null) {", "score": 46.51550947803749 }, { "filename": "src/core/assert.ts", "retrieved_chunk": " return value;\n}\nexport function assertNumber(value: unknown): number {\n if (typeof value !== 'number') {\n throw new Error('Expected a number, got: ' + value);\n }\n return value;\n}\nexport function assertString(value: unknown): string {\n if (typeof value !== 'string') {", "score": 29.730615490159533 }, { "filename": "src/core/assert.ts", "retrieved_chunk": "export function assertArray<T>(value: unknown): Array<T> {\n if (!Array.isArray(value)) {\n throw new Error('Expected an array, got: ' + value);\n }\n return value;\n}\nexport function assertBoolean(value: unknown): boolean {\n if (typeof value !== 'boolean') {\n throw new Error('Expected a boolean, got: ' + value);\n }", "score": 28.461175139531 }, { "filename": "src/rules/parse.ts", "retrieved_chunk": " case '$all':\n case '$any':\n return new SignalRule(\n operator[operatorKey],\n arraySignal,\n await arraySignal.__assert(operatorValue),\n );\n case '$inc':\n case '$pfx':\n case '$sfx':", "score": 26.566589967890057 } ]
typescript
(operator.$pfx, stringSignal, value), };
import* as fs from 'fs'; import error from '../modules/log.js'; import { Runner, Test, Out } from '../modules/types.js'; function parseOut(test: any): Out { let expected: Out = { stdout: undefined, stderr: undefined, exitCode: undefined } if (test.stdout) expected.stdout = test.stdout; if (test.stderr) expected.stderr = test.stderr; if (test.exitCode !== undefined) expected.exitCode = test.exitCode; return expected; } export default async function parse(runner: Runner, doc: any): Promise<Runner> { const tests: Test[] = []; try { let testId = 0; for (const test of doc.Tests) { testId++; const testObj: Test = { id: testId, name: test.name, description: test.description, command: test.command, testType: test.testType, referCommand: undefined, expected: undefined, result: undefined }; if (test.testType === 'refer') testObj.referCommand = test.referCommand; else if (test.testType === "expect") testObj.expected = parseOut(test.expected); else throw new Error(`Invalid testType or comparsionType in test ${testObj.id}`); tests.push(testObj); } } catch(e) { error(`Error parsing: ${e}`); }
runner.tests = tests;
return runner; }
src/fileParsing/parse.ts
Epitests-unofficial-BinaryTester-4b511ec
[ { "filename": "src/fileParsing/yaml.ts", "retrieved_chunk": " } catch(e) {\n error(`Error parsing YAML: ${e}`);\n }\n}", "score": 28.044059488745397 }, { "filename": "src/fileParsing/json.ts", "retrieved_chunk": " error(`Error parsing JSON: ${e}`);\n }\n}", "score": 22.83217572302634 }, { "filename": "src/runTests.ts", "retrieved_chunk": " if (runner.settings.verbose) {\n print_test_description(test);\n } else if (runner.settings.outputFormat == 'text') \n process.stdout.write(`Test ${test.id}: ${test.name}... \\t`);\n if (test.testType === 'refer')\n await runRefer(runner, test);\n else if (test.testType === 'expect')\n await runExpect(runner, test);\n if (runner.settings.verbose)\n console.log('\\n');", "score": 19.185903651237737 }, { "filename": "src/runTests.ts", "retrieved_chunk": " console.log(`Test ${test.id}: ${test.name}`);\n console.log(`Test Command: $${test.command}`);\n console.log(`Test type: [${test.testType}]`);\n if (test.testType === 'refer')\n console.log(`Refer Command: $${test.referCommand}`);\n else {\n print_expected(test.expected);\n }\n}\nasync function runTest(runner: Runner, test: Test): Promise<void> {", "score": 17.840832652404906 }, { "filename": "src/modules/types.ts", "retrieved_chunk": " id: number;\n name: string;\n description: string;\n command: string;\n testType: 'refer' | 'expect';\n referCommand: string;\n expected: Out;\n result: Result;\n}\nexport type Settings = {", "score": 17.002532994356304 } ]
typescript
runner.tests = tests;
import type Rule from '../rules/rule'; import type {Infer, Schema} from '@decs/typeschema'; import {createAssert} from '@decs/typeschema'; import {operator} from '../core/operators'; import InverseRule from '../rules/inverse'; import SignalRule from '../rules/signal'; export type Signal<TContext, TValue> = { __assert: (data: unknown) => Promise<TValue>; evaluate: (context: TContext) => Promise<TValue>; not: Omit<Signal<TContext, TValue>, 'evaluate' | 'not'>; equals(value: TValue): Rule<TContext>; in(values: Array<TValue>): Rule<TContext>; } & (TValue extends Array<infer TElement> ? { every(rule: Rule<TElement>): Rule<TContext>; some(rule: Rule<TElement>): Rule<TContext>; contains(value: TElement): Rule<TContext>; containsEvery(values: Array<TElement>): Rule<TContext>; containsSome(values: Array<TElement>): Rule<TContext>; } : TValue extends boolean ? { isTrue(): Rule<TContext>; isFalse(): Rule<TContext>; } : TValue extends number ? { lessThan(value: TValue): Rule<TContext>; lessThanOrEquals(value: TValue): Rule<TContext>; greaterThan(value: TValue): Rule<TContext>; greaterThanOrEquals(value: TValue): Rule<TContext>; } : TValue extends string ? { includes(value: TValue): Rule<TContext>; endsWith(value: TValue): Rule<TContext>; startsWith(value: TValue): Rule<TContext>; matches(value: RegExp): Rule<TContext>; } : Record<string, never>); export type SignalFactory<TValue> = { value: <TContext>( fn: (context: TContext) => TValue | Promise<TValue>, ) => Signal<TContext, TValue>; }; function createSignal<TContext, TValue>( assert: (data: unknown) => Promise<TValue>, fn: (context: TContext) => TValue | Promise<TValue>, ): Signal<TContext, TValue> { return { __assert: assert, evaluate: async (context: TContext) => assert(await fn(context)), } as Signal<TContext, TValue>; } function addOperators<TContext, TValue>( signal: Signal<TContext, TValue>, ): Signal<TContext, TValue> { return { ...signal, equals: value => new SignalRule(operator.$eq, signal, value), in: values => new SignalRule(operator.$in, signal, values), }; } function addArrayOperators<TContext, TValue>( signal: Signal<TContext, TValue>, ): Signal<TContext, TValue> { const arraySignal = signal as unknown as Signal<TContext, Array<unknown>>; return { ...signal, contains: value => new SignalRule(operator.$all, arraySignal, [value]), containsEvery: values => new SignalRule(operator.$all, arraySignal, values), containsSome: values => new SignalRule(operator.$any, arraySignal, values), every: rule => new SignalRule(operator.$and, arraySignal, [rule]), some: rule => new SignalRule(operator.$or, arraySignal, [rule]), }; } function addBooleanOperators<TContext, TValue>( signal: Signal<TContext, TValue>, ): Signal<TContext, TValue> { const booleanSignal = signal as unknown as Signal<TContext, boolean>; return { ...signal, isFalse: () => new SignalRule(operator.$eq, booleanSignal, false), isTrue: () => new SignalRule(operator.$eq, booleanSignal, true), }; } function addNumberOperators<TContext, TValue>( signal: Signal<TContext, TValue>, ): Signal<TContext, TValue> { const numberSignal = signal as unknown as Signal<TContext, number>; return { ...signal, greaterThan: value => new SignalRule(operator.$gt, numberSignal, value), greaterThanOrEquals: value => new SignalRule(operator.$gte, numberSignal, value), lessThan: value => new SignalRule(operator.$lt, numberSignal, value), lessThanOrEquals: value => new SignalRule(operator
.$lte, numberSignal, value), };
} function addStringOperators<TContext, TValue>( signal: Signal<TContext, TValue>, ): Signal<TContext, TValue> { const stringSignal = signal as unknown as Signal<TContext, string>; return { ...signal, endsWith: value => new SignalRule(operator.$sfx, stringSignal, value), includes: value => new SignalRule(operator.$inc, stringSignal, value), matches: value => new SignalRule(operator.$rx, stringSignal, value), startsWith: value => new SignalRule(operator.$pfx, stringSignal, value), }; } function addModifiers<TContext, TValue>( signal: Signal<TContext, TValue>, ): Signal<TContext, TValue> { return { ...signal, not: new Proxy(signal, { get: (target, property, receiver) => { const value = Reflect.get(target, property, receiver); return typeof value === 'function' ? (...args: Array<unknown>) => new InverseRule(value.bind(target)(...args)) : value; }, }), }; } export function type<TSchema extends Schema>( schema: TSchema, ): SignalFactory<Infer<TSchema>> { return { value<TContext>( fn: (context: TContext) => Infer<TSchema> | Promise<Infer<TSchema>>, ) { return [ addOperators, addArrayOperators, addBooleanOperators, addNumberOperators, addStringOperators, addModifiers, ].reduce( (value, operation) => operation(value), createSignal(createAssert(schema), fn), ); }, }; }
src/signals/factory.ts
decs-ruls-c037c91
[ { "filename": "src/rules/parse.ts", "retrieved_chunk": " case '$lte':\n return new SignalRule(\n operator[operatorKey],\n numberSignal,\n await numberSignal.__assert(operatorValue),\n );\n case '$eq':\n return new SignalRule(operator[operatorKey], signal, operatorValue);\n case '$in':\n return new SignalRule(", "score": 44.78383870760377 }, { "filename": "src/rules/parse.ts", "retrieved_chunk": " return new InverseRule(await parse(value, signals));\n }\n const signal = signals[key];\n assertObjectWithSingleKey(value);\n const operatorKey = Object.keys(value)[0];\n assertOperatorKey(operatorKey);\n const operatorValue = value[operatorKey];\n const arraySignal = signal as Signal<TContext, Array<unknown>>;\n const numberSignal = signal as Signal<TContext, number>;\n const stringSignal = signal as Signal<TContext, string>;", "score": 31.438307184024502 }, { "filename": "src/rules/parse.ts", "retrieved_chunk": " throw new Error('Expected a regular expression, got: ' + operatorValue);\n }\n return new SignalRule(\n operator[operatorKey],\n signal,\n new RegExp(match[1], match[2]),\n );\n case '$gt':\n case '$gte':\n case '$lt':", "score": 26.62755298251256 }, { "filename": "src/core/assert.ts", "retrieved_chunk": "export function assertArray<T>(value: unknown): Array<T> {\n if (!Array.isArray(value)) {\n throw new Error('Expected an array, got: ' + value);\n }\n return value;\n}\nexport function assertBoolean(value: unknown): boolean {\n if (typeof value !== 'boolean') {\n throw new Error('Expected a boolean, got: ' + value);\n }", "score": 26.045829885110237 }, { "filename": "src/core/assert.ts", "retrieved_chunk": " return value;\n}\nexport function assertNumber(value: unknown): number {\n if (typeof value !== 'number') {\n throw new Error('Expected a number, got: ' + value);\n }\n return value;\n}\nexport function assertString(value: unknown): string {\n if (typeof value !== 'string') {", "score": 25.766991572447246 } ]
typescript
.$lte, numberSignal, value), };
import type Rule from '../rules/rule'; import type {Infer, Schema} from '@decs/typeschema'; import {createAssert} from '@decs/typeschema'; import {operator} from '../core/operators'; import InverseRule from '../rules/inverse'; import SignalRule from '../rules/signal'; export type Signal<TContext, TValue> = { __assert: (data: unknown) => Promise<TValue>; evaluate: (context: TContext) => Promise<TValue>; not: Omit<Signal<TContext, TValue>, 'evaluate' | 'not'>; equals(value: TValue): Rule<TContext>; in(values: Array<TValue>): Rule<TContext>; } & (TValue extends Array<infer TElement> ? { every(rule: Rule<TElement>): Rule<TContext>; some(rule: Rule<TElement>): Rule<TContext>; contains(value: TElement): Rule<TContext>; containsEvery(values: Array<TElement>): Rule<TContext>; containsSome(values: Array<TElement>): Rule<TContext>; } : TValue extends boolean ? { isTrue(): Rule<TContext>; isFalse(): Rule<TContext>; } : TValue extends number ? { lessThan(value: TValue): Rule<TContext>; lessThanOrEquals(value: TValue): Rule<TContext>; greaterThan(value: TValue): Rule<TContext>; greaterThanOrEquals(value: TValue): Rule<TContext>; } : TValue extends string ? { includes(value: TValue): Rule<TContext>; endsWith(value: TValue): Rule<TContext>; startsWith(value: TValue): Rule<TContext>; matches(value: RegExp): Rule<TContext>; } : Record<string, never>); export type SignalFactory<TValue> = { value: <TContext>( fn: (context: TContext) => TValue | Promise<TValue>, ) => Signal<TContext, TValue>; }; function createSignal<TContext, TValue>( assert: (data: unknown) => Promise<TValue>, fn: (context: TContext) => TValue | Promise<TValue>, ): Signal<TContext, TValue> { return { __assert: assert, evaluate: async (context: TContext) => assert(await fn(context)), } as Signal<TContext, TValue>; } function addOperators<TContext, TValue>( signal: Signal<TContext, TValue>, ): Signal<TContext, TValue> { return { ...signal, equals: value => new SignalRule(operator.$eq, signal, value), in: values => new SignalRule(operator.$in, signal, values), }; } function addArrayOperators<TContext, TValue>( signal: Signal<TContext, TValue>, ): Signal<TContext, TValue> { const arraySignal = signal as unknown as Signal<TContext, Array<unknown>>; return { ...signal, contains: value => new SignalRule(operator.$all, arraySignal, [value]), containsEvery: values => new SignalRule(operator.$all, arraySignal, values), containsSome: values => new SignalRule(operator.$any, arraySignal, values), every: rule => new SignalRule(operator.$and, arraySignal, [rule]), some: rule => new SignalRule(operator.$or, arraySignal, [rule]), }; } function addBooleanOperators<TContext, TValue>( signal: Signal<TContext, TValue>, ): Signal<TContext, TValue> { const booleanSignal = signal as unknown as Signal<TContext, boolean>; return { ...signal, isFalse: () => new SignalRule(operator.$eq, booleanSignal, false), isTrue: () => new SignalRule(operator.$eq, booleanSignal, true), }; } function addNumberOperators<TContext, TValue>( signal: Signal<TContext, TValue>, ): Signal<TContext, TValue> { const numberSignal = signal as unknown as Signal<TContext, number>; return { ...signal, greaterThan: value => new SignalRule(operator.$gt, numberSignal, value), greaterThanOrEquals: value => new SignalRule(operator.$gte, numberSignal, value), lessThan: value => new SignalRule(operator.$lt, numberSignal, value), lessThanOrEquals: value => new SignalRule(operator.$lte, numberSignal, value), }; } function addStringOperators<TContext, TValue>( signal: Signal<TContext, TValue>, ): Signal<TContext, TValue> { const stringSignal = signal as unknown as Signal<TContext, string>; return { ...signal, endsWith: value => new SignalRule(operator.$sfx, stringSignal, value), includes: value => new SignalRule(operator.$inc, stringSignal, value), matches: value => new SignalRule(operator.$rx, stringSignal, value), startsWith: value => new SignalRule(operator.$pfx, stringSignal, value), }; } function addModifiers<TContext, TValue>( signal: Signal<TContext, TValue>, ): Signal<TContext, TValue> { return { ...signal, not: new Proxy(signal, { get: (target, property, receiver) => { const value = Reflect.get(target, property, receiver); return typeof value === 'function' ? (...args: Array<unknown>) => new InverseRule
(value.bind(target)(...args)) : value;
}, }), }; } export function type<TSchema extends Schema>( schema: TSchema, ): SignalFactory<Infer<TSchema>> { return { value<TContext>( fn: (context: TContext) => Infer<TSchema> | Promise<Infer<TSchema>>, ) { return [ addOperators, addArrayOperators, addBooleanOperators, addNumberOperators, addStringOperators, addModifiers, ].reduce( (value, operation) => operation(value), createSignal(createAssert(schema), fn), ); }, }; }
src/signals/factory.ts
decs-ruls-c037c91
[ { "filename": "src/core/assert.ts", "retrieved_chunk": " return value;\n}\nexport function assertNumber(value: unknown): number {\n if (typeof value !== 'number') {\n throw new Error('Expected a number, got: ' + value);\n }\n return value;\n}\nexport function assertString(value: unknown): string {\n if (typeof value !== 'string') {", "score": 21.70683932662313 }, { "filename": "src/core/assert.ts", "retrieved_chunk": "export function assertArray<T>(value: unknown): Array<T> {\n if (!Array.isArray(value)) {\n throw new Error('Expected an array, got: ' + value);\n }\n return value;\n}\nexport function assertBoolean(value: unknown): boolean {\n if (typeof value !== 'boolean') {\n throw new Error('Expected a boolean, got: ' + value);\n }", "score": 21.510609920549392 }, { "filename": "src/rules/parse.ts", "retrieved_chunk": " return new InverseRule(await parse(value, signals));\n }\n const signal = signals[key];\n assertObjectWithSingleKey(value);\n const operatorKey = Object.keys(value)[0];\n assertOperatorKey(operatorKey);\n const operatorValue = value[operatorKey];\n const arraySignal = signal as Signal<TContext, Array<unknown>>;\n const numberSignal = signal as Signal<TContext, number>;\n const stringSignal = signal as Signal<TContext, string>;", "score": 18.364053370004896 }, { "filename": "src/core/assert.ts", "retrieved_chunk": " throw new Error('Expected a string, got: ' + value);\n }\n return value;\n}", "score": 12.86107168784861 }, { "filename": "src/__tests__/comparison.test.ts", "retrieved_chunk": " };\n const signals = {\n company: signal.type(z.string()).value<Context>(({company}) => company),\n ptoDaysTaken: signal\n .type(z.array(z.string()))\n .value<Context>(({ptoDaysTaken}) => ptoDaysTaken),\n status: signal.type(z.string()).value<Context>(({status}) => status),\n };\n const microsoftEmployeeOutOnChristmas = rule.every([\n signals.company.equals('microsoft'),", "score": 11.498578363050731 } ]
typescript
(value.bind(target)(...args)) : value;
import type Rule from '../rules/rule'; import type {Infer, Schema} from '@decs/typeschema'; import {createAssert} from '@decs/typeschema'; import {operator} from '../core/operators'; import InverseRule from '../rules/inverse'; import SignalRule from '../rules/signal'; export type Signal<TContext, TValue> = { __assert: (data: unknown) => Promise<TValue>; evaluate: (context: TContext) => Promise<TValue>; not: Omit<Signal<TContext, TValue>, 'evaluate' | 'not'>; equals(value: TValue): Rule<TContext>; in(values: Array<TValue>): Rule<TContext>; } & (TValue extends Array<infer TElement> ? { every(rule: Rule<TElement>): Rule<TContext>; some(rule: Rule<TElement>): Rule<TContext>; contains(value: TElement): Rule<TContext>; containsEvery(values: Array<TElement>): Rule<TContext>; containsSome(values: Array<TElement>): Rule<TContext>; } : TValue extends boolean ? { isTrue(): Rule<TContext>; isFalse(): Rule<TContext>; } : TValue extends number ? { lessThan(value: TValue): Rule<TContext>; lessThanOrEquals(value: TValue): Rule<TContext>; greaterThan(value: TValue): Rule<TContext>; greaterThanOrEquals(value: TValue): Rule<TContext>; } : TValue extends string ? { includes(value: TValue): Rule<TContext>; endsWith(value: TValue): Rule<TContext>; startsWith(value: TValue): Rule<TContext>; matches(value: RegExp): Rule<TContext>; } : Record<string, never>); export type SignalFactory<TValue> = { value: <TContext>( fn: (context: TContext) => TValue | Promise<TValue>, ) => Signal<TContext, TValue>; }; function createSignal<TContext, TValue>( assert: (data: unknown) => Promise<TValue>, fn: (context: TContext) => TValue | Promise<TValue>, ): Signal<TContext, TValue> { return { __assert: assert, evaluate: async (context: TContext) => assert(await fn(context)), } as Signal<TContext, TValue>; } function addOperators<TContext, TValue>( signal: Signal<TContext, TValue>, ): Signal<TContext, TValue> { return { ...signal, equals: value => new SignalRule(operator.$eq, signal, value), in: values => new
SignalRule(operator.$in, signal, values), };
} function addArrayOperators<TContext, TValue>( signal: Signal<TContext, TValue>, ): Signal<TContext, TValue> { const arraySignal = signal as unknown as Signal<TContext, Array<unknown>>; return { ...signal, contains: value => new SignalRule(operator.$all, arraySignal, [value]), containsEvery: values => new SignalRule(operator.$all, arraySignal, values), containsSome: values => new SignalRule(operator.$any, arraySignal, values), every: rule => new SignalRule(operator.$and, arraySignal, [rule]), some: rule => new SignalRule(operator.$or, arraySignal, [rule]), }; } function addBooleanOperators<TContext, TValue>( signal: Signal<TContext, TValue>, ): Signal<TContext, TValue> { const booleanSignal = signal as unknown as Signal<TContext, boolean>; return { ...signal, isFalse: () => new SignalRule(operator.$eq, booleanSignal, false), isTrue: () => new SignalRule(operator.$eq, booleanSignal, true), }; } function addNumberOperators<TContext, TValue>( signal: Signal<TContext, TValue>, ): Signal<TContext, TValue> { const numberSignal = signal as unknown as Signal<TContext, number>; return { ...signal, greaterThan: value => new SignalRule(operator.$gt, numberSignal, value), greaterThanOrEquals: value => new SignalRule(operator.$gte, numberSignal, value), lessThan: value => new SignalRule(operator.$lt, numberSignal, value), lessThanOrEquals: value => new SignalRule(operator.$lte, numberSignal, value), }; } function addStringOperators<TContext, TValue>( signal: Signal<TContext, TValue>, ): Signal<TContext, TValue> { const stringSignal = signal as unknown as Signal<TContext, string>; return { ...signal, endsWith: value => new SignalRule(operator.$sfx, stringSignal, value), includes: value => new SignalRule(operator.$inc, stringSignal, value), matches: value => new SignalRule(operator.$rx, stringSignal, value), startsWith: value => new SignalRule(operator.$pfx, stringSignal, value), }; } function addModifiers<TContext, TValue>( signal: Signal<TContext, TValue>, ): Signal<TContext, TValue> { return { ...signal, not: new Proxy(signal, { get: (target, property, receiver) => { const value = Reflect.get(target, property, receiver); return typeof value === 'function' ? (...args: Array<unknown>) => new InverseRule(value.bind(target)(...args)) : value; }, }), }; } export function type<TSchema extends Schema>( schema: TSchema, ): SignalFactory<Infer<TSchema>> { return { value<TContext>( fn: (context: TContext) => Infer<TSchema> | Promise<Infer<TSchema>>, ) { return [ addOperators, addArrayOperators, addBooleanOperators, addNumberOperators, addStringOperators, addModifiers, ].reduce( (value, operation) => operation(value), createSignal(createAssert(schema), fn), ); }, }; }
src/signals/factory.ts
decs-ruls-c037c91
[ { "filename": "src/signals/set.ts", "retrieved_chunk": "import type {Signal} from './factory';\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type SignalSet<TContext> = Record<string, Signal<TContext, any>>;\nexport function getSignalKey<TContext, TValue>(\n signal: Signal<TContext, TValue>,\n signals: SignalSet<TContext>,\n): string {\n const signalKey = Object.keys(signals).find(\n key => signals[key].equals === signal.equals,\n );", "score": 27.790577037224956 }, { "filename": "src/rules/parse.ts", "retrieved_chunk": " case '$lte':\n return new SignalRule(\n operator[operatorKey],\n numberSignal,\n await numberSignal.__assert(operatorValue),\n );\n case '$eq':\n return new SignalRule(operator[operatorKey], signal, operatorValue);\n case '$in':\n return new SignalRule(", "score": 23.137501754889616 }, { "filename": "src/core/evaluator.ts", "retrieved_chunk": "export default abstract class Evaluator<TContext, TValue> {\n constructor(protected fn: (context: TContext) => TValue | Promise<TValue>) {}\n async evaluate(context: TContext): Promise<TValue> {\n return this.fn(context);\n }\n}", "score": 21.207601197409513 }, { "filename": "src/rules/parse.ts", "retrieved_chunk": " return new InverseRule(await parse(value, signals));\n }\n const signal = signals[key];\n assertObjectWithSingleKey(value);\n const operatorKey = Object.keys(value)[0];\n assertOperatorKey(operatorKey);\n const operatorValue = value[operatorKey];\n const arraySignal = signal as Signal<TContext, Array<unknown>>;\n const numberSignal = signal as Signal<TContext, number>;\n const stringSignal = signal as Signal<TContext, string>;", "score": 18.6186076420113 }, { "filename": "src/rules/parse.ts", "retrieved_chunk": " switch (operatorKey) {\n case '$and':\n case '$or':\n return new SignalRule<TContext, Array<TContext>, Array<Rule<TContext>>>(\n operator[operatorKey],\n signal as Signal<TContext, Array<TContext>>,\n [await parse(operatorValue, signals)],\n );\n case '$not':\n throw new Error('Invalid operator key: ' + operatorKey);", "score": 17.12167315343835 } ]
typescript
SignalRule(operator.$in, signal, values), };
import { Runner, Test, Out } from './modules/types.js'; import runRefer from './runner/refer.js'; import runExpect from './runner/expect.js'; import yaml from 'js-yaml'; import createOutput from './output.js'; function print_expected(out: Out): void { if (out.stdout !== undefined) if (out.stdout.string !== undefined) console.log(`Expected stdout: "${out.stdout.string}"`); else if (out.stdout.regex !== undefined) console.log(`stdout must match: /${out.stdout.regex}/`); if (out.stderr !== undefined) if (out.stderr.string !== undefined) console.log(`Expected stderr: "${out.stderr.string}"`); else if (out.stderr.regex !== undefined) console.log(`stderr must match: /${out.stderr.regex}/`); if (out.exitCode !== undefined) console.log(`Expected exit code: ${out.exitCode}`); } function print_test_description(test: Test): void { console.log(`Test ${test.id}: ${test.name}`); console.log(`Test Command: $${test.command}`); console.log(`Test type: [${test.testType}]`); if (test.testType === 'refer') console.log(`Refer Command: $${test.referCommand}`); else { print_expected(test.expected); } } async function runTest(runner: Runner, test: Test): Promise<void> { if (runner.settings.verbose) { print_test_description(test); } else if (runner.settings.outputFormat == 'text') process.stdout.write(`Test ${test.id}: ${test.name}... \t`); if (test.testType === 'refer') await runRefer(runner, test); else if (test.testType === 'expect') await runExpect(runner, test); if (runner.settings.verbose) console.log('\n'); } export default async function runTests(runner: Runner): Promise<void> { if (runner.settings.verbose) {
console.log(`Starting Tests for ${runner.testFilePath}...`);
console.log(`Settings: \n${yaml.dump(runner.settings)}`); console.log("Test Queue:"); for (const test of runner.tests) { if (runner.settings.runList.includes(test.id) || runner.settings.runList.length === 0) console.log(`Test ${test.id}: ${test.name}`); } } if (runner.settings.outputFormat == 'text') console.log("Starting Tests...\n"); for (const test of runner.tests) { if (runner.settings.runList.includes(test.id) || runner.settings.runList.length === 0) { test.result = { status: 'pending', msg: 'In the queue', result: { stdout: undefined, stderr: undefined, exitCode: undefined }, timeTaken: undefined }; } else { test.result = { status: 'skipped', msg: 'Skipped by user', result: { stdout: undefined, stderr: undefined, exitCode: undefined }, timeTaken: undefined }; } } for (const test of runner.tests) { if (runner.settings.runList.includes(test.id) || runner.settings.runList.length === 0) { test.result = { status: 'pending', msg: 'In the queue', result: { stdout: undefined, stderr: undefined, exitCode: undefined }, timeTaken: undefined }; await runTest(runner, test); } } createOutput(runner); }
src/runTests.ts
Epitests-unofficial-BinaryTester-4b511ec
[ { "filename": "src/runner/expect.ts", "retrieved_chunk": "}\nasync function runExpect(runner: Runner, test: Test): Promise<void> {\n let startTime = Date.now();\n let run: SpawnSyncReturns<Buffer> = spawnSync(test.command, {\n timeout: runner.settings.timeout,\n shell: true\n });\n let endTime = Date.now();\n if (runner.settings.verbose) {\n console.log(`Run stdout: \"${run.stdout}\"`);", "score": 25.73948393949878 }, { "filename": "src/output.ts", "retrieved_chunk": "export function returnYaml(runner: Runner): string {\n return yaml.dump(constructReturn(runner));\n}\nfunction print_end(runner: Runner): void {\n if (runner.settings.verbose)\n console.log(\"Finished Tests!\");\n if (runner.settings.outputFormat == 'text')\n console.log(`\\nTests Results\n->\\tSuccess: ${runner.numberSuccess}\\tFail: ${runner.numberFail} \\tSkipped: ${runner.tests.length - runner.numberFail - runner.numberSuccess}\\t<-`);\n}", "score": 23.98031685105549 }, { "filename": "src/fileParsing/parse.ts", "retrieved_chunk": " expected: undefined,\n result: undefined\n };\n if (test.testType === 'refer')\n testObj.referCommand = test.referCommand;\n else if (test.testType === \"expect\")\n testObj.expected = parseOut(test.expected);\n else\n throw new Error(`Invalid testType or comparsionType in test ${testObj.id}`);\n tests.push(testObj);", "score": 20.65324986282937 }, { "filename": "src/argsHandler.ts", "retrieved_chunk": " break;\n }\n }\n if (runner.testFilePath === '') {\n help();\n process.exit(1);\n }\n if (runner.testFilePath.endsWith('.yaml') || runner.testFilePath.endsWith('.yml'))\n runner = await parseYaml(runner);\n else if (runner.testFilePath.endsWith('.json'))", "score": 19.186654687553467 }, { "filename": "src/runner/jobError.ts", "retrieved_chunk": " if (runner.settings.outputFormat === 'text') {\n console.log(\"You have chosen to stop when a test fails.\");\n console.log(\"Stopping Tests...\");\n }\n for (const test of runner.tests) {\n if (test.result.status === 'pending') {\n test.result.status = 'skipped';\n test.result.msg = 'Skipped: Test stopped due to previous failure';\n }\n }", "score": 18.887346962002347 } ]
typescript
console.log(`Starting Tests for ${runner.testFilePath}...`);
import help from './modules/help.js'; import error from './modules/log.js'; import { Runner } from './modules/types.js'; import parseYaml from './fileParsing/yaml.js'; import parseJson from './fileParsing/json.js'; async function parseArguments(args: string[]): Promise<Runner> { let runner: Runner = { testFilePath: '', tests: [], settings: { output: 'stdout', outputFormat: 'text', timeout: 0, verbose: false, status: false, runList: [], stopWhenFail: false, }, numberSuccess: 0, numberFail: 0, }; for (let i = 0; i < args.length; i++) { switch (args[i]) { case '-o': case '--output': if (args[i + 1] === undefined) error("Invalid output (must be 'file [json or yaml]')"); runner.settings.output = args[i + 1]; runner.settings.outputFormat = 'yaml'; if (args[i + 1].endsWith('.json')) runner.settings.outputFormat = 'json'; i++; break; case '-t': case '--timeout': if (args[i + 1] === undefined || isNaN(parseInt(args[i + 1])) || parseInt(args[i + 1]) < 0) error('Invalid timeout'); runner.settings.timeout = parseInt(args[i + 1]); i++; break; case '-v': case '--verbose': runner.settings.verbose = true; break; case '-s': case '--status': runner.settings.status = true; break; case '-swf': case '--stop-when-fail': runner.settings.stopWhenFail = true; break; case '-r': case '--runList': if (args[i + 1] === undefined || args[i + 1].split(',').some((x) => isNaN(parseInt(x)))) error('Invalid run list'); runner.settings.runList = args[i + 1].split(',').map((x) => parseInt(x)); i++; break; case '-h': case '--help': help(); process.exit(0); default: if (args[i].startsWith('-') || args[i].startsWith('--')) error(`Invalid argument: ${args[i]}`); runner.testFilePath = args[i]; break; } } if (runner.testFilePath === '') { help(); process.exit(1); } if (runner.testFilePath.endsWith('.yaml') || runner.testFilePath.endsWith('.yml')) runner = await parseYaml(runner); else if (runner.testFilePath.endsWith('.json'))
runner = await parseJson(runner);
return runner; } export default parseArguments; export { parseArguments };
src/argsHandler.ts
Epitests-unofficial-BinaryTester-4b511ec
[ { "filename": "src/fileParsing/yaml.ts", "retrieved_chunk": "import* as fs from 'fs';\nimport* as yaml from 'js-yaml';\nimport error from '../modules/log.js';\nimport { Runner, Test, Out } from '../modules/types.js';\nimport parse from './parse.js';\nexport default async function parseYaml(runner: Runner): Promise<Runner> {\n let data = fs.readFileSync(runner.testFilePath, 'utf8');\n if (!data) error(`Error reading file from disk: ${runner.testFilePath}`);\n try {\n return await parse(runner, yaml.load(data));", "score": 27.432088941113534 }, { "filename": "src/fileParsing/json.ts", "retrieved_chunk": "import* as fs from 'fs';\nimport error from '../modules/log.js';\nimport { Runner, Test, Out } from '../modules/types.js';\nimport parse from './parse.js';\nexport default async function parseYaml(runner: Runner): Promise<Runner> {\n let data = fs.readFileSync(runner.testFilePath, 'utf8');\n if (!data) error(`Error reading file from disk: ${runner.testFilePath}`);\n try {\n return await parse(runner, JSON.parse(data));\n } catch(e) {", "score": 25.731006404096764 }, { "filename": "src/runner/jobError.ts", "retrieved_chunk": " createOutput(runner);\n if (runner.settings.status)\n process.exit(1);\n else\n process.exit(0);\n }\n}", "score": 23.318425196025817 }, { "filename": "src/runTests.ts", "retrieved_chunk": " if (runner.settings.verbose) {\n print_test_description(test);\n } else if (runner.settings.outputFormat == 'text') \n process.stdout.write(`Test ${test.id}: ${test.name}... \\t`);\n if (test.testType === 'refer')\n await runRefer(runner, test);\n else if (test.testType === 'expect')\n await runExpect(runner, test);\n if (runner.settings.verbose)\n console.log('\\n');", "score": 22.178120187420227 }, { "filename": "src/runTests.ts", "retrieved_chunk": "}\nexport default async function runTests(runner: Runner): Promise<void> {\n if (runner.settings.verbose) {\n console.log(`Starting Tests for ${runner.testFilePath}...`);\n console.log(`Settings: \\n${yaml.dump(runner.settings)}`);\n console.log(\"Test Queue:\");\n for (const test of runner.tests) {\n if (runner.settings.runList.includes(test.id) || runner.settings.runList.length === 0)\n console.log(`Test ${test.id}: ${test.name}`);\n }", "score": 20.51350725256373 } ]
typescript
runner = await parseJson(runner);
import help from './modules/help.js'; import error from './modules/log.js'; import { Runner } from './modules/types.js'; import parseYaml from './fileParsing/yaml.js'; import parseJson from './fileParsing/json.js'; async function parseArguments(args: string[]): Promise<Runner> { let runner: Runner = { testFilePath: '', tests: [], settings: { output: 'stdout', outputFormat: 'text', timeout: 0, verbose: false, status: false, runList: [], stopWhenFail: false, }, numberSuccess: 0, numberFail: 0, }; for (let i = 0; i < args.length; i++) { switch (args[i]) { case '-o': case '--output': if (args[i + 1] === undefined) error("Invalid output (must be 'file [json or yaml]')"); runner.settings.output = args[i + 1]; runner.settings.outputFormat = 'yaml'; if (args[i + 1].endsWith('.json')) runner.settings.outputFormat = 'json'; i++; break; case '-t': case '--timeout': if (args[i + 1] === undefined || isNaN(parseInt(args[i + 1])) || parseInt(args[i + 1]) < 0) error('Invalid timeout'); runner.settings.timeout = parseInt(args[i + 1]); i++; break; case '-v': case '--verbose': runner.settings.verbose = true; break; case '-s': case '--status': runner.settings.status = true; break; case '-swf': case '--stop-when-fail': runner.settings.stopWhenFail = true; break; case '-r': case '--runList': if (args[i + 1] === undefined || args[i + 1].split(',').some((x) => isNaN(parseInt(x)))) error('Invalid run list'); runner.settings.runList = args[i + 1].split(',').map((x) => parseInt(x)); i++; break; case '-h': case '--help': help(); process.exit(0); default: if (args[i].startsWith('-') || args[i].startsWith('--')) error(`Invalid argument: ${args[i]}`); runner.testFilePath = args[i]; break; } } if (runner.testFilePath === '') { help(); process.exit(1); } if (runner.testFilePath.endsWith('.yaml') || runner.testFilePath.endsWith('.yml')) runner
= await parseYaml(runner);
else if (runner.testFilePath.endsWith('.json')) runner = await parseJson(runner); return runner; } export default parseArguments; export { parseArguments };
src/argsHandler.ts
Epitests-unofficial-BinaryTester-4b511ec
[ { "filename": "src/fileParsing/yaml.ts", "retrieved_chunk": "import* as fs from 'fs';\nimport* as yaml from 'js-yaml';\nimport error from '../modules/log.js';\nimport { Runner, Test, Out } from '../modules/types.js';\nimport parse from './parse.js';\nexport default async function parseYaml(runner: Runner): Promise<Runner> {\n let data = fs.readFileSync(runner.testFilePath, 'utf8');\n if (!data) error(`Error reading file from disk: ${runner.testFilePath}`);\n try {\n return await parse(runner, yaml.load(data));", "score": 19.856753420813085 }, { "filename": "src/fileParsing/json.ts", "retrieved_chunk": "import* as fs from 'fs';\nimport error from '../modules/log.js';\nimport { Runner, Test, Out } from '../modules/types.js';\nimport parse from './parse.js';\nexport default async function parseYaml(runner: Runner): Promise<Runner> {\n let data = fs.readFileSync(runner.testFilePath, 'utf8');\n if (!data) error(`Error reading file from disk: ${runner.testFilePath}`);\n try {\n return await parse(runner, JSON.parse(data));\n } catch(e) {", "score": 17.936977310399563 }, { "filename": "src/runner/jobError.ts", "retrieved_chunk": " createOutput(runner);\n if (runner.settings.status)\n process.exit(1);\n else\n process.exit(0);\n }\n}", "score": 16.561100441466344 }, { "filename": "src/runTests.ts", "retrieved_chunk": "}\nexport default async function runTests(runner: Runner): Promise<void> {\n if (runner.settings.verbose) {\n console.log(`Starting Tests for ${runner.testFilePath}...`);\n console.log(`Settings: \\n${yaml.dump(runner.settings)}`);\n console.log(\"Test Queue:\");\n for (const test of runner.tests) {\n if (runner.settings.runList.includes(test.id) || runner.settings.runList.length === 0)\n console.log(`Test ${test.id}: ${test.name}`);\n }", "score": 14.337786179772115 }, { "filename": "src/output.ts", "retrieved_chunk": "export default function createOutput(runner: Runner): void {\n let output: string;\n switch (runner.settings.outputFormat) {\n case 'json':\n output = returnJson(runner);\n break;\n case 'yaml':\n output = returnYaml(runner);\n break;\n default:", "score": 12.59105951623149 } ]
typescript
= await parseYaml(runner);
import help from './modules/help.js'; import error from './modules/log.js'; import { Runner } from './modules/types.js'; import parseYaml from './fileParsing/yaml.js'; import parseJson from './fileParsing/json.js'; async function parseArguments(args: string[]): Promise<Runner> { let runner: Runner = { testFilePath: '', tests: [], settings: { output: 'stdout', outputFormat: 'text', timeout: 0, verbose: false, status: false, runList: [], stopWhenFail: false, }, numberSuccess: 0, numberFail: 0, }; for (let i = 0; i < args.length; i++) { switch (args[i]) { case '-o': case '--output': if (args[i + 1] === undefined) error("Invalid output (must be 'file [json or yaml]')"); runner.settings.output = args[i + 1]; runner.settings.outputFormat = 'yaml'; if (args[i + 1].endsWith('.json')) runner.settings.outputFormat = 'json'; i++; break; case '-t': case '--timeout': if (args[i + 1] === undefined || isNaN(parseInt(args[i + 1])) || parseInt(args[i + 1]) < 0) error('Invalid timeout'); runner.settings.timeout = parseInt(args[i + 1]); i++; break; case '-v': case '--verbose': runner.settings.verbose = true; break; case '-s': case '--status': runner.settings.status = true; break; case '-swf': case '--stop-when-fail': runner.settings.stopWhenFail = true; break; case '-r': case '--runList': if (args[i + 1] === undefined || args[i + 1].split(',').some((x) => isNaN(parseInt(x)))) error('Invalid run list'); runner.settings.runList = args[i + 1].split(',').map((x) => parseInt(x)); i++; break; case '-h': case '--help': help(); process.exit(0); default: if (args[i].startsWith('-') || args[i].startsWith('--')) error(`Invalid argument: ${args[i]}`);
runner.testFilePath = args[i];
break; } } if (runner.testFilePath === '') { help(); process.exit(1); } if (runner.testFilePath.endsWith('.yaml') || runner.testFilePath.endsWith('.yml')) runner = await parseYaml(runner); else if (runner.testFilePath.endsWith('.json')) runner = await parseJson(runner); return runner; } export default parseArguments; export { parseArguments };
src/argsHandler.ts
Epitests-unofficial-BinaryTester-4b511ec
[ { "filename": "src/output.ts", "retrieved_chunk": "export default function createOutput(runner: Runner): void {\n let output: string;\n switch (runner.settings.outputFormat) {\n case 'json':\n output = returnJson(runner);\n break;\n case 'yaml':\n output = returnYaml(runner);\n break;\n default:", "score": 20.20581050911982 }, { "filename": "src/runner/jobError.ts", "retrieved_chunk": " createOutput(runner);\n if (runner.settings.status)\n process.exit(1);\n else\n process.exit(0);\n }\n}", "score": 15.366130564904568 }, { "filename": "src/modules/help.ts", "retrieved_chunk": " process.stdout.write(`\\t-v, --verbose\\t`);\n process.stdout.write(`Verbose output (default: false)\\n`);\n process.stdout.write(`\\t-s, --status\\t`);\n process.stdout.write(`Show status (default: false)\\n`);\n process.stdout.write(`\\t-r, --runList [number,number,...]\\t`);\n process.stdout.write(`Run only specified tests (default: [])\\n`);\n process.stdout.write(`\\t-h, --help\\t`);\n process.stdout.write(`Show this help message\\n`);\n process.stdout.write(`\\n`);\n}", "score": 14.72051021614259 }, { "filename": "src/modules/help.ts", "retrieved_chunk": "function help(): void {\n process.stdout.write(`Usage ${process.argv[1].split(\"/\").slice(-1)} [options] [file]`);\n process.stdout.write(`\\n\\n`);\n process.stdout.write(`Options:\\n`);\n process.stdout.write(`\\t-o, --output [file (json or yaml)]\\t`);\n process.stdout.write(`Output format (default: text)\\n`);\n process.stdout.write(`\\t-swf, --stop-when-fail\\t`);\n process.stdout.write(`Stop when a test fails (default: false)\\n`);\n process.stdout.write(`\\t-t, --timeout [number]\\t`);\n process.stdout.write(`Timeout in milliseconds (default: -1)\\n`);", "score": 13.223577619684605 }, { "filename": "src/modules/log.ts", "retrieved_chunk": "function error(message: string): void {\n process.stderr.write(message);\n process.stderr.write('\\n');\n process.exit(1);\n}\nexport default error;", "score": 12.104066685258458 } ]
typescript
runner.testFilePath = args[i];
import chalk from "chalk" import fs from "fs" import path from "path" import { Ora } from "ora" import promiseExec from "./promise-exec.js" import { EOL } from "os" import runProcess from "./run-process.js" import getFact from "./get-fact.js" import onProcessTerminated from "./on-process-terminated.js" import boxen from "boxen" type PrepareOptions = { directory: string dbConnectionString: string admin?: { email: string } seed?: boolean spinner?: Ora abortController?: AbortController } const showFact = (lastFact: string, spinner: Ora): string => { const fact = getFact(lastFact) spinner.text = `${boxen(fact, { title: chalk.cyan("Installing Dependencies..."), titleAlignment: "center", textAlignment: "center", padding: 1, margin: 1, float: "center", })}` return fact } export default async ({ directory, dbConnectionString, admin, seed, spinner, abortController, }: PrepareOptions) => { // initialize execution options const execOptions = { cwd: directory, signal: abortController?.signal, } // initialize the invite token to return let inviteToken: string | undefined = undefined // add connection string to project fs.appendFileSync( path.join(directory, `.env`), `DATABASE_TYPE=postgres${EOL}DATABASE_URL=${dbConnectionString}` ) let interval: NodeJS.Timer | undefined = undefined let fact = "" if (spinner) { spinner.spinner = { frames: [""], } fact = showFact(fact, spinner) interval = setInterval(() => { fact = showFact(fact, spinner) }, 6000) onProcessTerminated(() => clearInterval(interval)) } await runProcess({ process: async () => { try { await
promiseExec(`yarn`, execOptions) } catch (e) {
// yarn isn't available // use npm await promiseExec(`npm install`, execOptions) } }, ignoreERESOLVE: true, }) if (interval) { clearInterval(interval) } if (spinner) { spinner.spinner = "dots" spinner.succeed(chalk.green("Installed Dependencies")) spinner.start(chalk.white("Running Migrations...")) } // run migrations await runProcess({ process: async () => { await promiseExec( "npx -y @medusajs/medusa-cli@latest migrations run", execOptions ) }, }) spinner?.succeed(chalk.green("Ran Migrations")).start() if (admin) { // create admin user if (spinner) { spinner.text = chalk.white("Creating an admin user...") } await runProcess({ process: async () => { const proc = await promiseExec( `npx -y @medusajs/[email protected] user -e ${admin.email} --invite`, execOptions ) // get invite token from stdout const match = proc.stdout.match(/Invite token: (?<token>.+)/) inviteToken = match?.groups?.token }, }) spinner?.succeed(chalk.green("Created admin user")).start() } if (seed) { if (spinner) { spinner.text = chalk.white("Seeding database...") } // check if a seed file exists in the project if (!fs.existsSync(path.join(directory, "data", "seed.jsons"))) { spinner ?.warn( chalk.yellow( "Seed file was not found in the project. Skipping seeding..." ) ) .start() return } if (spinner) { spinner.text = chalk.white("Seeding database with demo data...") } await runProcess({ process: async () => { await promiseExec( `npx -y @medusajs/medusa-cli@latest seed --seed-file=${path.join( "data", "seed.json" )}`, execOptions ) }, }) spinner?.succeed(chalk.green("Seeded database with demo data")).start() } return inviteToken }
src/utils/prepare-project.ts
shahednasser-create-medusa-app-demo-e3950ff
[ { "filename": "src/utils/get-fact.ts", "retrieved_chunk": " let index = 0\n if (lastFact.length) {\n const lastFactIndex = facts.findIndex((fact) => fact === lastFact)\n if (lastFactIndex !== facts.length - 1) {\n index = lastFactIndex + 1\n }\n }\n return facts[index]\n}", "score": 10.181293241788905 }, { "filename": "src/commands/create.ts", "retrieved_chunk": " ? true\n : \"Please enter a valid email\"\n },\n },\n ])\n const spinner = ora(chalk.white(\"Setting up project\")).start()\n onProcessTerminated(() => spinner.stop())\n // clone repository\n try {\n await cloneRepo({", "score": 9.109817707548991 }, { "filename": "src/utils/create-abort-controller.ts", "retrieved_chunk": "import onProcessTerminated from \"./on-process-terminated.js\"\nexport default () => {\n const abortController = new AbortController()\n onProcessTerminated(() => abortController.abort())\n return abortController\n}\nexport const isAbortError = (e: any) =>\n e !== null && \"code\" in e && e.code === \"ABORT_ERR\"", "score": 7.452732584062165 }, { "filename": "src/utils/run-process.ts", "retrieved_chunk": " do {\n try {\n await process()\n } catch (error) {\n if (\n typeof error === \"object\" &&\n error !== null &&\n \"code\" in error &&\n error?.code === \"EAGAIN\"\n ) {", "score": 7.143419798296814 }, { "filename": "src/commands/create.ts", "retrieved_chunk": " let postgresUsername = \"postgres\"\n let postgresPassword = \"\"\n // try to log in with default db username and password\n try {\n client = await postgresClient({\n user: postgresUsername,\n password: postgresPassword,\n })\n } catch (e) {\n // ask for the user's credentials", "score": 6.754548920088266 } ]
typescript
promiseExec(`yarn`, execOptions) } catch (e) {
import axios from "axios"; import { getOptions, Options } from "../../types/Bing"; import * as cheerio from 'cheerio'; import HttpsProxyAgent from 'https-proxy-agent'; import _url from "../../utils/handleUrl"; import useProxies from "../../utils/useProxies"; import https from 'https'; export class Bing { private options: Options = getOptions(); private updateQueries: (name: string, value: any) => void; constructor(options: Options = getOptions()) { let _options = { ...getOptions(), ...options }; function updateQueries(name: string, value: any) { _options.queries = { ..._options.queries, [name]: value } } if (_options?.mkt) { if (!_options?.queries?.mkt) updateQueries('mkt', _options?.mkt); if (!_options?.queries?.setlang) updateQueries('setlang', _options?.mkt); } if (_options?.safe) { if (!_options?.queries?.safe) updateQueries('safeSearch', _options?.safe); } if (_options?.perPage) { if (!_options?.queries?.count) updateQueries('count', _options?.perPage); if (!_options?.queries?.offset) updateQueries('offset', (_options?.perPage * (_options?.page - 1))); } if (!_options?.queries?.pt) updateQueries('pt', 'page.serp'); if (!_options?.queries?.mkt) updateQueries('mkt', 'en-us'); if (!_options?.queries?.cp) updateQueries('cp', 6); if (!_options?.queries?.msbqf) updateQueries('msbqf', false); if (!_options?.queries?.cvid) updateQueries('cvid', 'void_development'); this.updateQueries = updateQueries; this.options = _options; } useProxies = useProxies; public async search(query: string): Promise<{}> {
if (!this.options?.queries?.bq) this.updateQueries('bq', query);
if (!this.options?.queries?.q) this.updateQueries('q', query); if (!this.options?.queries?.qry) this.updateQueries('qry', query); const __proxy = this.options.proxy; if (__proxy) { this.options.proxies.push(__proxy); this.options.proxy = undefined; } return await this.useProxies(() => this._search(query)); } private async _search(query: string): Promise<{}> { return new Promise(async (resolve, reject) => { const agent = this.options.proxy ? HttpsProxyAgent({ host: this.options.proxy?.host, port: this.options.proxy?.port, auth: this.options.proxy?.auth?.username + ':' + this.options.proxy?.auth?.password }) : new https.Agent({ rejectUnauthorized: false }); return await axios(Object.assign({ url: _url(`https://www.bing.com/search`, this.options.queries), method: 'GET', headers: this.options.headers }, (agent ? { proxy: this.options.proxy ? { host: this.options.proxy?.host, port: this.options.proxy?.port, auth: { username: this.options.proxy?.auth?.username, password: this.options.proxy?.auth?.password } } : undefined, httpsAgent: agent } : {}))).then(response => { const html = response.data; const $ = cheerio.load(html); const results: any[] = []; $('#b_results .b_algo').each((i, el) => { const title = $(el).find('h2 a').first().text(); const description = $(el).find('.b_algoSlug').each((i, el) => { $(el).find('span').remove(); }).text(); const link = $(el).find('a').first().attr('href'); const deepLinks: any[] = []; $(el).find('.b_deep li').each((i, el) => { deepLinks.push({ title: $(el).find('a').text(), link: $(el).find('a').attr('href'), description: $(el).find('p').text() }); }); results.push({ title, description, link, deepLinks }); }); const data = { results, proxy: this.options.proxy, queries: this.options.queries }; return resolve(data); }).catch(error => { return reject(error); }); }); } public async suggestions(query: string): Promise<{}> { if (!this.options?.queries?.bq) this.updateQueries('bq', query); if (!this.options?.queries?.q) this.updateQueries('q', query); if (!this.options?.queries?.qry) this.updateQueries('qry', query); const __proxy = this.options.proxy; if (__proxy) { this.options.proxies.push(__proxy); this.options.proxy = undefined; } return await this.useProxies(() => this._suggestions(query)); } private async _suggestions(query: string): Promise<{}> { return new Promise(async (resolve, reject) => { const agent = this.options.proxy ? HttpsProxyAgent({ host: this.options.proxy?.host, port: this.options.proxy?.port, auth: this.options.proxy?.auth?.username + ':' + this.options.proxy?.auth?.password }) : new https.Agent({ rejectUnauthorized: false }); return await axios(Object.assign({ url: _url(`https://www.bing.com/AS/Suggestions`, this.options.queries), method: 'GET', headers: this.options.headers }, (agent ? { proxy: this.options.proxy ? { host: this.options.proxy?.host, port: this.options.proxy?.port, auth: { username: this.options.proxy?.auth?.username, password: this.options.proxy?.auth?.password } } : undefined, httpsAgent: agent } : {}))).then(response => { const html = response.data; const $ = cheerio.load(html); const suggestions: any[] = []; $('#sa_ul li').each((i, el) => { suggestions.push({ text: $(el).find('.pp_title').text() || $(el).find('.sa_tm_text').text() || null, image: $(el).find('img').attr('src') ? 'https://th.bing.com' + $(el).find('img').attr('src') : null }); }); const data = { suggestions: suggestions.filter(s => s.text), proxy: this.options.proxy, queries: this.options.queries }; return resolve(data); }).catch(error => { return reject(error); }); }); } public async images(query: string): Promise<{}> { return new Error('Not implemented yet'); } }
src/engines/lib/Bing.ts
VoidDevsorg-node-scrapper-470e34a
[ { "filename": "src/engines/lib/Google.ts", "retrieved_chunk": " if (!_options?.queries?.num) updateQueries('num', _options?.perPage);\n if (!_options?.queries?.start) updateQueries('start', (_options?.page - 1) * _options?.perPage);\n }\n this.updateQueries = updateQueries;\n this.options = _options;\n }\n useProxies = useProxies;\n public async search(query: string): Promise<{}> {\n if (!this.options?.queries?.q) this.updateQueries('q', query);\n const __proxy = this.options.proxy;", "score": 88.70583220516166 }, { "filename": "src/engines/lib/Google.ts", "retrieved_chunk": " }\n if (_options?.mkt) {\n if (!_options?.queries?.lr) updateQueries('lr', 'lang_' + (_options?.mkt?.split('-')?.[0] || 'en'));\n if (!_options?.queries?.hl) updateQueries('hl', _options?.mkt?.split('-')?.[0] || 'en');\n if (!_options?.queries?.gl) updateQueries('gl', _options?.mkt?.split('-')?.[1] || 'US');\n }\n if (_options?.safe) {\n if (!_options?.queries?.safe) updateQueries('safe', _options?.safe);\n }\n if (_options?.perPage) {", "score": 77.71973845317876 }, { "filename": "src/engines/lib/YouTube.ts", "retrieved_chunk": " }\n this.updateQueries = updateQueries;\n this.options = _options;\n }\n useProxies = useProxies;\n public async search(query: string): Promise<{}> {\n this.updateQueries('search_query', encodeURIComponent(query));\n const __proxy = this.options.proxy;\n if (__proxy) {\n this.options.proxies.push(__proxy);", "score": 69.31720213372843 }, { "filename": "src/engines/lib/Google.ts", "retrieved_chunk": " }).catch(error => {\n return reject(error);\n });\n });\n }\n public async suggestions(query: string): Promise<{}> {\n if (!this.options?.queries?.q) this.updateQueries('q', query);\n this.updateQueries('cp', 6);\n this.updateQueries('xssi', 't');\n this.updateQueries('authuser', 0);", "score": 68.82205296522795 }, { "filename": "src/engines/lib/Wikipedia.ts", "retrieved_chunk": " }\n this.updateQueries = updateQueries;\n this.options = _options;\n }\n useProxies = useProxies;\n public async get(query: string): Promise<{}> {\n const __proxy = this.options.proxy;\n if (__proxy) {\n this.options.proxies.push(__proxy);\n this.options.proxy = undefined;", "score": 63.64586753573265 } ]
typescript
if (!this.options?.queries?.bq) this.updateQueries('bq', query);
import inquirer from "inquirer" import slugifyType from "slugify" import chalk from "chalk" import pg from "pg" import createDb from "../utils/create-db.js" import postgresClient from "../utils/postgres-client.js" import cloneRepo from "../utils/clone-repo.js" import prepareProject from "../utils/prepare-project.js" import startMedusa from "../utils/start-medusa.js" import open from "open" import waitOn from "wait-on" import formatConnectionString from "../utils/format-connection-string.js" import ora from "ora" import fs from "fs" import { nanoid } from "nanoid" import isEmailImported from "validator/lib/isEmail.js" import logMessage from "../utils/log-message.js" import onProcessTerminated from "../utils/on-process-terminated.js" import createAbortController, { isAbortError, } from "../utils/create-abort-controller.js" const slugify = slugifyType.default const isEmail = isEmailImported.default type CreateOptions = { repoUrl?: string seed?: boolean } export default async ({ repoUrl = "", seed }: CreateOptions) => { const abortController = createAbortController() const { projectName } = await inquirer.prompt([ { type: "input", name: "projectName", message: "What's the name of your project?", default: "my-medusa-store", filter: (input) => { return slugify(input) }, validate: (input) => { if (!input.length) { return "Please enter a project name" } return fs.existsSync(input) && fs.lstatSync(input).isDirectory() ? "A directory already exists with the same name. Please enter a different project name." : true }, }, ]) let client: pg.Client | undefined let dbConnectionString = "" let postgresUsername = "postgres" let postgresPassword = "" // try to log in with default db username and password try {
client = await postgresClient({
user: postgresUsername, password: postgresPassword, }) } catch (e) { // ask for the user's credentials const answers = await inquirer.prompt([ { type: "input", name: "postgresUsername", message: "Enter your Postgres username", default: "postgres", validate: (input) => { return typeof input === "string" && input.length > 0 }, }, { type: "password", name: "postgresPassword", message: "Enter your Postgres password", }, ]) postgresUsername = answers.postgresUsername postgresPassword = answers.postgresPassword try { client = await postgresClient({ user: postgresUsername, password: postgresPassword, }) } catch (e) { logMessage({ message: "Couldn't connect to PostgreSQL. Make sure you have PostgreSQL installed and the credentials you provided are correct.\n\n" + "You can learn how to install PostgreSQL here: https://docs.medusajs.com/development/backend/prepare-environment#postgresql", type: "error", }) } } const { adminEmail } = await inquirer.prompt([ { type: "input", name: "adminEmail", message: "Enter an email for your admin dashboard user", default: !seed ? "[email protected]" : undefined, validate: (input) => { return typeof input === "string" && input.length > 0 && isEmail(input) ? true : "Please enter a valid email" }, }, ]) const spinner = ora(chalk.white("Setting up project")).start() onProcessTerminated(() => spinner.stop()) // clone repository try { await cloneRepo({ directoryName: projectName, repoUrl, abortController, }) } catch (e) { if (isAbortError(e)) { process.exit() } logMessage({ message: `An error occurred while setting up your project: ${e}`, type: "error", }) } spinner.succeed(chalk.green("Created project directory")).start() if (client) { spinner.text = chalk.white("Creating database...") const dbName = `medusa-${nanoid(4)}` // create postgres database try { await createDb({ client, db: dbName, }) } catch (e) { logMessage({ message: `An error occurred while trying to create your database: ${e}`, type: "error", }) } // format connection string dbConnectionString = formatConnectionString({ user: postgresUsername, password: postgresPassword, host: client.host, db: dbName, }) spinner.succeed(chalk.green(`Database ${dbName} created`)).start() } spinner.text = chalk.white("Preparing project...") // prepare project let inviteToken: string | undefined = undefined try { inviteToken = await prepareProject({ directory: projectName, dbConnectionString, admin: { email: adminEmail, }, seed, spinner, abortController, }) } catch (e: any) { if (isAbortError(e)) { process.exit() } logMessage({ message: `An error occurred while preparing project: ${e}`, type: "error", }) } spinner.succeed(chalk.green("Project Prepared")) // close db connection await client?.end() // start backend logMessage({ message: "Starting Medusa...", }) try { startMedusa({ directory: projectName, abortController, }) } catch (e) { if (isAbortError(e)) { process.exit() } logMessage({ message: `An error occurred while starting Medusa`, type: "error", }) } waitOn({ resources: ["http://localhost:9000/health"], }).then(() => open( inviteToken ? `http://localhost:9000/app/invite?token=${inviteToken}` : "http://localhost:9000/app" ) ) }
src/commands/create.ts
shahednasser-create-medusa-app-demo-e3950ff
[ { "filename": "src/utils/create-db.ts", "retrieved_chunk": "import pg from \"pg\"\ntype CreateDbOptions = {\n client: pg.Client\n db: string\n}\nexport default async ({ client, db }: CreateDbOptions) => {\n await client.query(`CREATE DATABASE \"${db}\"`)\n}", "score": 21.434122729700352 }, { "filename": "src/utils/prepare-project.ts", "retrieved_chunk": " `DATABASE_TYPE=postgres${EOL}DATABASE_URL=${dbConnectionString}`\n )\n let interval: NodeJS.Timer | undefined = undefined\n let fact = \"\"\n if (spinner) {\n spinner.spinner = {\n frames: [\"\"],\n }\n fact = showFact(fact, spinner)\n interval = setInterval(() => {", "score": 20.121751232352715 }, { "filename": "src/utils/postgres-client.ts", "retrieved_chunk": "import pg from \"pg\"\nconst { Client } = pg\ntype PostgresConnection = {\n user?: string\n password?: string\n}\nexport default async (connect: PostgresConnection) => {\n const client = new Client(connect)\n await client.connect()\n return client", "score": 19.998516620647425 }, { "filename": "src/utils/format-connection-string.ts", "retrieved_chunk": "type ConnectionStringOptions = {\n user?: string\n password?: string\n host?: string\n db: string\n}\nexport default ({ user, password, host, db }: ConnectionStringOptions) => {\n let connection = `postgres://`\n if (user) {\n connection += user", "score": 18.285570751424366 }, { "filename": "src/utils/prepare-project.ts", "retrieved_chunk": " // initialize execution options\n const execOptions = {\n cwd: directory,\n signal: abortController?.signal,\n }\n // initialize the invite token to return\n let inviteToken: string | undefined = undefined\n // add connection string to project\n fs.appendFileSync(\n path.join(directory, `.env`),", "score": 13.291875723513433 } ]
typescript
client = await postgresClient({
import chalk from "chalk" import fs from "fs" import path from "path" import { Ora } from "ora" import promiseExec from "./promise-exec.js" import { EOL } from "os" import runProcess from "./run-process.js" import getFact from "./get-fact.js" import onProcessTerminated from "./on-process-terminated.js" import boxen from "boxen" type PrepareOptions = { directory: string dbConnectionString: string admin?: { email: string } seed?: boolean spinner?: Ora abortController?: AbortController } const showFact = (lastFact: string, spinner: Ora): string => { const fact = getFact(lastFact) spinner.text = `${boxen(fact, { title: chalk.cyan("Installing Dependencies..."), titleAlignment: "center", textAlignment: "center", padding: 1, margin: 1, float: "center", })}` return fact } export default async ({ directory, dbConnectionString, admin, seed, spinner, abortController, }: PrepareOptions) => { // initialize execution options const execOptions = { cwd: directory, signal: abortController?.signal, } // initialize the invite token to return let inviteToken: string | undefined = undefined // add connection string to project fs.appendFileSync( path.join(directory, `.env`), `DATABASE_TYPE=postgres${EOL}DATABASE_URL=${dbConnectionString}` ) let interval: NodeJS.Timer | undefined = undefined let fact = "" if (spinner) { spinner.spinner = { frames: [""], } fact = showFact(fact, spinner) interval = setInterval(() => { fact = showFact(fact, spinner) }, 6000) onProcessTerminated(() => clearInterval(interval)) } await
runProcess({
process: async () => { try { await promiseExec(`yarn`, execOptions) } catch (e) { // yarn isn't available // use npm await promiseExec(`npm install`, execOptions) } }, ignoreERESOLVE: true, }) if (interval) { clearInterval(interval) } if (spinner) { spinner.spinner = "dots" spinner.succeed(chalk.green("Installed Dependencies")) spinner.start(chalk.white("Running Migrations...")) } // run migrations await runProcess({ process: async () => { await promiseExec( "npx -y @medusajs/medusa-cli@latest migrations run", execOptions ) }, }) spinner?.succeed(chalk.green("Ran Migrations")).start() if (admin) { // create admin user if (spinner) { spinner.text = chalk.white("Creating an admin user...") } await runProcess({ process: async () => { const proc = await promiseExec( `npx -y @medusajs/[email protected] user -e ${admin.email} --invite`, execOptions ) // get invite token from stdout const match = proc.stdout.match(/Invite token: (?<token>.+)/) inviteToken = match?.groups?.token }, }) spinner?.succeed(chalk.green("Created admin user")).start() } if (seed) { if (spinner) { spinner.text = chalk.white("Seeding database...") } // check if a seed file exists in the project if (!fs.existsSync(path.join(directory, "data", "seed.jsons"))) { spinner ?.warn( chalk.yellow( "Seed file was not found in the project. Skipping seeding..." ) ) .start() return } if (spinner) { spinner.text = chalk.white("Seeding database with demo data...") } await runProcess({ process: async () => { await promiseExec( `npx -y @medusajs/medusa-cli@latest seed --seed-file=${path.join( "data", "seed.json" )}`, execOptions ) }, }) spinner?.succeed(chalk.green("Seeded database with demo data")).start() } return inviteToken }
src/utils/prepare-project.ts
shahednasser-create-medusa-app-demo-e3950ff
[ { "filename": "src/utils/get-fact.ts", "retrieved_chunk": " let index = 0\n if (lastFact.length) {\n const lastFactIndex = facts.findIndex((fact) => fact === lastFact)\n if (lastFactIndex !== facts.length - 1) {\n index = lastFactIndex + 1\n }\n }\n return facts[index]\n}", "score": 20.36258648357781 }, { "filename": "src/commands/create.ts", "retrieved_chunk": " ? true\n : \"Please enter a valid email\"\n },\n },\n ])\n const spinner = ora(chalk.white(\"Setting up project\")).start()\n onProcessTerminated(() => spinner.stop())\n // clone repository\n try {\n await cloneRepo({", "score": 9.483993476662349 }, { "filename": "src/commands/create.ts", "retrieved_chunk": " type: \"error\",\n })\n }\n spinner.succeed(chalk.green(\"Created project directory\")).start()\n if (client) {\n spinner.text = chalk.white(\"Creating database...\")\n const dbName = `medusa-${nanoid(4)}`\n // create postgres database\n try {\n await createDb({", "score": 6.312003652755634 }, { "filename": "src/commands/create.ts", "retrieved_chunk": " let inviteToken: string | undefined = undefined\n try {\n inviteToken = await prepareProject({\n directory: projectName,\n dbConnectionString,\n admin: {\n email: adminEmail,\n },\n seed,\n spinner,", "score": 5.7062588383319675 }, { "filename": "src/commands/create.ts", "retrieved_chunk": " dbConnectionString = formatConnectionString({\n user: postgresUsername,\n password: postgresPassword,\n host: client.host,\n db: dbName,\n })\n spinner.succeed(chalk.green(`Database ${dbName} created`)).start()\n }\n spinner.text = chalk.white(\"Preparing project...\")\n // prepare project", "score": 5.658028213071223 } ]
typescript
runProcess({
import type { Attributes, ModelStatic, Sequelize, Transaction, } from "sequelize"; import type { IAssociation, JSONAnyObject } from "../types"; import { handleUpdateMany, handleUpdateOne } from "./sequelize.patch"; import { handleBulkCreateHasOne, handleBulkCreateMany, handleCreateHasOne, handleCreateMany, } from "./sequelize.post"; export const getValidAttributesAndAssociations = ( attributes: Attributes<any> | Array<Attributes<any>>, associations: Record<string, IAssociation> | undefined, ) => { const externalAssociations: string[] = []; let currentModelAttributes = attributes; const otherAssociationAttributes: JSONAnyObject = {}; if (associations) { const associationsKeys = Object.keys(associations); const attributeKeys = Array.isArray(currentModelAttributes) ? Object.keys(attributes[0]) : Object.keys(attributes); // GET ALL ASSOCIATION ATTRIBUTES AND SEPARATE THEM FROM DATA LEFT associationsKeys.forEach((association) => { if (attributeKeys.includes(association)) { let data: any; if (Array.isArray(currentModelAttributes)) { data = currentModelAttributes.map((attribute: any) => { const { [association]: _, ...attributesleft } = attribute; const otherAttr = otherAssociationAttributes[association] ?? []; otherAssociationAttributes[association] = [...otherAttr, _]; return attributesleft; }); } else { const { [association]: _, ...attributesLeft } = currentModelAttributes; data = attributesLeft; } currentModelAttributes = data; externalAssociations.push(association); } }); } return { otherAssociationAttributes, externalAssociations, currentModelAttributes, }; }; export const handleCreateAssociations = async ( sequelize: Sequelize, model: ModelStatic<any>, validAssociations: string[], associations: Record<string, IAssociation>, attributes: Attributes<any>, transaction: Transaction, modelId: string, primaryKey = "id", ): Promise<void> => { for (const association of validAssociations) { const associationDetails = associations[association]; const associationAttribute = attributes[association]; switch (associationDetails.type) { case "BelongsTo": case "HasOne": await handleCreateHasOne( sequelize, { details: associationDetails, attributes: associationAttribute, }, { name: model.name, id: modelId }, transaction, primaryKey, ); break; case "BelongsToMany": case "HasMany": await handleCreateMany( sequelize, { details: associationDetails, attributes: associationAttribute, }, { name: model.name, id: modelId }, transaction, primaryKey, ); break; default: break; } } }; export const handleBulkCreateAssociations = async ( sequelize: Sequelize, model: ModelStatic<any>, validAssociations: string[], associations: Record<string, IAssociation>, attributes: JSONAnyObject, transaction: Transaction, modelIds: string[], primaryKey = "id", ): Promise<void> => { for (const association of validAssociations) { const associationDetails = associations[association]; const associationAttribute = attributes[association]; switch (associationDetails.type) { case "BelongsTo": case "HasOne": await handleBulkCreateHasOne( sequelize, { details: associationDetails, attributes: associationAttribute, }, { name: model.name, id: modelIds }, transaction, primaryKey, ); break; case "BelongsToMany": case "HasMany": await handleBulkCreateMany( sequelize, { details: associationDetails, attributes: associationAttribute, }, { name: model.name, id: modelIds }, transaction, primaryKey, ); break; default: break; } } }; export const handleUpdateAssociations = async ( sequelize: Sequelize, model: ModelStatic<any>, validAssociations: string[], associations: Record<string, IAssociation>, attributes: Attributes<any>, transaction: Transaction, modelId: string, primaryKey = "id", ): Promise<void> => { for (const association of validAssociations) { const associationDetails = associations[association]; const associationAttribute = attributes[association]; switch (associationDetails.type) { case "BelongsTo": case "HasOne":
await handleUpdateOne( sequelize, {
details: associationDetails, attributes: associationAttribute, }, { name: model.name, id: modelId, }, transaction, primaryKey, ); break; case "HasMany": case "BelongsToMany": await handleUpdateMany( sequelize, { details: associationDetails, attributes: associationAttribute, }, { name: model.name, id: modelId, }, transaction, primaryKey, ); break; default: break; } } };
src/sequelize/associations/index.ts
bitovi-sequelize-create-with-associations-908ee8a
[ { "filename": "src/sequelize/associations/sequelize.patch.ts", "retrieved_chunk": " primaryKey = \"id\",\n): Promise<void> => {\n const modelName = association.details.model;\n const associatedId = association.attributes?.[primaryKey] || null;\n const [modelInstance, associatedInstance] = await Promise.all([\n sequelize.models[model.name].findByPk(model[primaryKey], {\n transaction,\n }),\n associatedId\n ? sequelize.models[modelName].findByPk(associatedId, {", "score": 9.693838618889531 }, { "filename": "src/sequelize/associations/sequelize.patch.ts", "retrieved_chunk": " sequelize: Sequelize,\n association: IAssociationBody<Array<Record<string, any>>>,\n model: { name: string; id: string },\n transaction: Transaction,\n primaryKey = \"id\",\n): Promise<void> => {\n const modelName = association.details.model;\n const associatedIds = association.attributes.map((data) => data[primaryKey]);\n const [modelInstance, associatedInstances] = await Promise.all([\n sequelize.models[model.name].findByPk(model[primaryKey], {", "score": 9.415610862578959 }, { "filename": "src/sequelize/associations/sequelize.post.ts", "retrieved_chunk": " const modelName = association.details.model;\n const results = await Promise.allSettled(\n association.attributes.map(async (attribute, index) => {\n const isCreate = !attribute[primaryKey];\n if (isCreate) {\n const id = (\n await sequelize.models[association.details.model].create(\n { ...attribute, through: undefined },\n { transaction },\n )", "score": 8.358319075042923 }, { "filename": "src/sequelize/associations/sequelize.post.ts", "retrieved_chunk": "};\nexport const handleBulkCreateMany = async (\n sequelize: Sequelize,\n association: IAssociationBody<JSONAnyObject[][]>,\n model: { name: string; id: string[] },\n transaction: Transaction,\n primaryKey = \"id\",\n): Promise<void> => {\n // Create an instance of the model using the id\n const modelInstances = await sequelize.models[model.name].findAll({", "score": 8.158767300603818 }, { "filename": "src/sequelize/associations/sequelize.patch.ts", "retrieved_chunk": "import { pluralize } from \"inflection\";\nimport { Op } from \"sequelize\";\nimport type { Sequelize, Transaction } from \"sequelize\";\nimport { NotFoundError } from \"../types\";\nimport type { IAssociationBody } from \"../types\";\nexport const handleUpdateOne = async (\n sequelize: Sequelize,\n association: IAssociationBody<Array<Record<string, any>>>,\n model: { name: string; id: string },\n transaction: Transaction,", "score": 7.532113144820411 } ]
typescript
await handleUpdateOne( sequelize, {
import axios from "axios"; import { getOptions, Options } from "../../types/Wikipedia"; import * as cheerio from 'cheerio'; import HttpsProxyAgent from 'https-proxy-agent'; import _url from "../../utils/handleUrl"; import useProxies from "../../utils/useProxies"; import https from 'https'; export class Wikipedia { private options: Options = getOptions(); private updateQueries: (name: string, value: any) => void; constructor(options: Options = getOptions()) { let _options = { ...getOptions(), ...options }; function updateQueries(name: string, value: any) { _options.queries = { ..._options.queries, [name]: value } } this.updateQueries = updateQueries; this.options = _options; } useProxies = useProxies; public async get(query: string): Promise<{}> { const __proxy = this.options.proxy; if (__proxy) { this.options.proxies.push(__proxy); this.options.proxy = undefined; } return await this.useProxies(() => this._get(query)); } private async _get(query: string): Promise<{}> { return new Promise(async (resolve, reject) => { const agent = this.options.proxy ? HttpsProxyAgent({ host: this.options.proxy?.host, port: this.options.proxy?.port, auth: this.options.proxy?.auth ? this.options.proxy?.auth?.username + ':' + this.options.proxy?.auth?.password : undefined }) : new https.Agent({ rejectUnauthorized: false }); return await axios(Object.assign({ url: _url(`https://${this.options.language}.wikipedia.org/wiki/${query.replace(/ /g, '_')}`, this.options.queries), method: 'GET', headers: this.
options.headers, }, (agent ? {
proxy: this.options.proxy ? { host: this.options.proxy?.host, port: this.options.proxy?.port, auth: { username: this.options.proxy?.auth?.username, password: this.options.proxy?.auth?.password } } : undefined, httpsAgent: agent } : {}))).then(response => { const html = response.data; const $ = cheerio.load(html); let result: { title?: string, image?: string, description?: { clean?: string, links?: any[], markdown?: string } infobox?: any[] } = { title: undefined, image: undefined, description: { clean: undefined, links: undefined, markdown: undefined }, infobox: undefined }; const fixText = (text: string) => text.replace(/(\r\n|\n|\r)/gm, '').replace(/\s+/g, ' ').trim(); const formatLink = (text: string) => { let _ = text; const regex = /\(([^)]+)\)/; const match = regex.exec(_); if (match) { const m = match[1]; _ = _.replace(`_(${m})`, ''); } _ = _.replace('/wiki/', '').replace(/_/g, '+').toLowerCase(); if (_.endsWith('.')) _ = _.slice(0, _.length - 1); return `https://nustry.com/search?q=${_}` } $('.mw-parser-output').each((i, element) => { const $element = $(element); const $p = $element.find('p').not('.mw-empty-elt'); $p.find('sup').remove(); $p.first().each((i, element) => { const $element = $(element); const text = $element.text(); const links: any[] = []; $element.find('a').each((i, element) => { const $element = $(element); const href = $element.attr('href'); if (href && href.startsWith('/wiki/')) { links.push({ href: href, text: $element.text() }) } }); result.description.clean = fixText(text); result.description.links = links; result.description.markdown = links.reduce((prev, curr) => { return prev.replace(curr.text, `[${curr.text}](${formatLink(curr.href)})`); }, fixText(text)); }); }); $('.infobox').each((i, element) => { const $element = $(element); result.title = $element.find('caption').first().text(); result.image = $element.find('a.image img').first().attr('src'); const $tr = $element.find('tr'); let values: any[] = []; $tr.each((i, element) => { const $element = $(element); const $th = $element.find('th'); const $td = $element.find('td'); $td.find('sup').remove(); const th = $th.text(); if (!th) return; const isHaveLI = $td.find('li').length > 0; const isHaveTable = $td.find('table').length > 0; const isHaveBR = $td.find('br').length > 0; let res: any = [fixText($td.text())]; if (isHaveLI) { const $li = $td.find('li'); const li: string[] = []; $li.each((i, element) => { const $element = $(element); li.push(fixText($element.text())); }); res = li; } else if (isHaveTable) { const $table = $td.find('table'); const table: { [key: string]: any } = {}; $table.each((i, element) => { const $element = $(element); const $tr = $element.find('tr'); $tr.each((i, element) => { const $element = $(element); const $th = $element.find('th'); const $td = $element.find('td'); const th = fixText($th.text()); if (!th) return; table[th] = fixText($td.text()); }); }); res = table; } else if (isHaveBR) { const removeTags = (text: string) => text.replace(/(<([^>]+)>)/gi, ''); res = $td.html().split('<br>').map((text: string) => { return fixText(removeTags(text)); }) } const response = res; const $a = $td.find('a'); const href = $a.attr('href'); let links: any[] = []; if (href) { $a.map((i, element) => { const $element = $(element); links.push({ href: $element.attr('href'), text: $element.text(), isFound: $element.attr('href').startsWith('/wiki/') }); }); } const _ = { label: th, response: { clean: response, markdown: links.reduce((prev, curr) => { return prev.replace(curr.text, `[${curr.text}](${formatLink(curr.href)})`); }, fixText($td.text())) }, links }; values.push(_); }); result['infobox'] = values }); const data = { result, proxy: this.options.proxy, queries: this.options.queries }; return resolve(data); }).catch(error => { return reject(error); }); }); } }
src/engines/lib/Wikipedia.ts
VoidDevsorg-node-scrapper-470e34a
[ { "filename": "src/engines/lib/Google.ts", "retrieved_chunk": " port: this.options.proxy?.port,\n auth: this.options.proxy?.auth?.username + ':' + this.options.proxy?.auth?.password\n }) : new https.Agent({\n rejectUnauthorized: false\n });\n return await axios(Object.assign({\n url: _url(`https://www.google.com/search`, this.options.queries),\n method: 'GET',\n headers: this.options.headers\n }, (agent ? {", "score": 59.226223689145954 }, { "filename": "src/engines/lib/YouTube.ts", "retrieved_chunk": " }) : new https.Agent({\n rejectUnauthorized: false\n });\n return await axios(Object.assign({\n url: _url(`https://www.youtube.com/results`, this.options.queries),\n method: 'GET',\n headers: this.options.headers\n }, (agent ? {\n proxy: this.options.proxy ? {\n host: this.options.proxy?.host,", "score": 50.180292198013575 }, { "filename": "src/engines/lib/Google.ts", "retrieved_chunk": " return new Promise(async (resolve, reject) => {\n const agent = this.options.proxy ? HttpsProxyAgent({\n host: this.options.proxy?.host,\n port: this.options.proxy?.port,\n auth: this.options.proxy?.auth?.username + ':' + this.options.proxy?.auth?.password\n }) : new https.Agent({\n rejectUnauthorized: false\n });\n return await axios(Object.assign({\n url: _url(`https://www.google.com/complete/search`, this.options.queries),", "score": 47.22026750454672 }, { "filename": "src/engines/lib/Bing.ts", "retrieved_chunk": " });\n return await axios(Object.assign({\n url: _url(`https://www.bing.com/search`, this.options.queries),\n method: 'GET',\n headers: this.options.headers\n }, (agent ? {\n proxy: this.options.proxy ? {\n host: this.options.proxy?.host,\n port: this.options.proxy?.port,\n auth: {", "score": 46.16782366485412 }, { "filename": "src/engines/lib/Bing.ts", "retrieved_chunk": " });\n return await axios(Object.assign({\n url: _url(`https://www.bing.com/AS/Suggestions`, this.options.queries),\n method: 'GET',\n headers: this.options.headers\n }, (agent ? {\n proxy: this.options.proxy ? {\n host: this.options.proxy?.host,\n port: this.options.proxy?.port,\n auth: {", "score": 45.71558338374436 } ]
typescript
options.headers, }, (agent ? {
import inquirer from "inquirer" import slugifyType from "slugify" import chalk from "chalk" import pg from "pg" import createDb from "../utils/create-db.js" import postgresClient from "../utils/postgres-client.js" import cloneRepo from "../utils/clone-repo.js" import prepareProject from "../utils/prepare-project.js" import startMedusa from "../utils/start-medusa.js" import open from "open" import waitOn from "wait-on" import formatConnectionString from "../utils/format-connection-string.js" import ora from "ora" import fs from "fs" import { nanoid } from "nanoid" import isEmailImported from "validator/lib/isEmail.js" import logMessage from "../utils/log-message.js" import onProcessTerminated from "../utils/on-process-terminated.js" import createAbortController, { isAbortError, } from "../utils/create-abort-controller.js" const slugify = slugifyType.default const isEmail = isEmailImported.default type CreateOptions = { repoUrl?: string seed?: boolean } export default async ({ repoUrl = "", seed }: CreateOptions) => { const abortController = createAbortController() const { projectName } = await inquirer.prompt([ { type: "input", name: "projectName", message: "What's the name of your project?", default: "my-medusa-store", filter: (input) => { return slugify(input) }, validate: (input) => { if (!input.length) { return "Please enter a project name" } return fs.existsSync(input) && fs.lstatSync(input).isDirectory() ? "A directory already exists with the same name. Please enter a different project name." : true }, }, ]) let client: pg.Client | undefined let dbConnectionString = "" let postgresUsername = "postgres" let postgresPassword = "" // try to log in with default db username and password try { client
= await postgresClient({
user: postgresUsername, password: postgresPassword, }) } catch (e) { // ask for the user's credentials const answers = await inquirer.prompt([ { type: "input", name: "postgresUsername", message: "Enter your Postgres username", default: "postgres", validate: (input) => { return typeof input === "string" && input.length > 0 }, }, { type: "password", name: "postgresPassword", message: "Enter your Postgres password", }, ]) postgresUsername = answers.postgresUsername postgresPassword = answers.postgresPassword try { client = await postgresClient({ user: postgresUsername, password: postgresPassword, }) } catch (e) { logMessage({ message: "Couldn't connect to PostgreSQL. Make sure you have PostgreSQL installed and the credentials you provided are correct.\n\n" + "You can learn how to install PostgreSQL here: https://docs.medusajs.com/development/backend/prepare-environment#postgresql", type: "error", }) } } const { adminEmail } = await inquirer.prompt([ { type: "input", name: "adminEmail", message: "Enter an email for your admin dashboard user", default: !seed ? "[email protected]" : undefined, validate: (input) => { return typeof input === "string" && input.length > 0 && isEmail(input) ? true : "Please enter a valid email" }, }, ]) const spinner = ora(chalk.white("Setting up project")).start() onProcessTerminated(() => spinner.stop()) // clone repository try { await cloneRepo({ directoryName: projectName, repoUrl, abortController, }) } catch (e) { if (isAbortError(e)) { process.exit() } logMessage({ message: `An error occurred while setting up your project: ${e}`, type: "error", }) } spinner.succeed(chalk.green("Created project directory")).start() if (client) { spinner.text = chalk.white("Creating database...") const dbName = `medusa-${nanoid(4)}` // create postgres database try { await createDb({ client, db: dbName, }) } catch (e) { logMessage({ message: `An error occurred while trying to create your database: ${e}`, type: "error", }) } // format connection string dbConnectionString = formatConnectionString({ user: postgresUsername, password: postgresPassword, host: client.host, db: dbName, }) spinner.succeed(chalk.green(`Database ${dbName} created`)).start() } spinner.text = chalk.white("Preparing project...") // prepare project let inviteToken: string | undefined = undefined try { inviteToken = await prepareProject({ directory: projectName, dbConnectionString, admin: { email: adminEmail, }, seed, spinner, abortController, }) } catch (e: any) { if (isAbortError(e)) { process.exit() } logMessage({ message: `An error occurred while preparing project: ${e}`, type: "error", }) } spinner.succeed(chalk.green("Project Prepared")) // close db connection await client?.end() // start backend logMessage({ message: "Starting Medusa...", }) try { startMedusa({ directory: projectName, abortController, }) } catch (e) { if (isAbortError(e)) { process.exit() } logMessage({ message: `An error occurred while starting Medusa`, type: "error", }) } waitOn({ resources: ["http://localhost:9000/health"], }).then(() => open( inviteToken ? `http://localhost:9000/app/invite?token=${inviteToken}` : "http://localhost:9000/app" ) ) }
src/commands/create.ts
shahednasser-create-medusa-app-demo-e3950ff
[ { "filename": "src/utils/create-db.ts", "retrieved_chunk": "import pg from \"pg\"\ntype CreateDbOptions = {\n client: pg.Client\n db: string\n}\nexport default async ({ client, db }: CreateDbOptions) => {\n await client.query(`CREATE DATABASE \"${db}\"`)\n}", "score": 21.434122729700352 }, { "filename": "src/utils/prepare-project.ts", "retrieved_chunk": " `DATABASE_TYPE=postgres${EOL}DATABASE_URL=${dbConnectionString}`\n )\n let interval: NodeJS.Timer | undefined = undefined\n let fact = \"\"\n if (spinner) {\n spinner.spinner = {\n frames: [\"\"],\n }\n fact = showFact(fact, spinner)\n interval = setInterval(() => {", "score": 20.121751232352715 }, { "filename": "src/utils/postgres-client.ts", "retrieved_chunk": "import pg from \"pg\"\nconst { Client } = pg\ntype PostgresConnection = {\n user?: string\n password?: string\n}\nexport default async (connect: PostgresConnection) => {\n const client = new Client(connect)\n await client.connect()\n return client", "score": 19.998516620647425 }, { "filename": "src/utils/format-connection-string.ts", "retrieved_chunk": "type ConnectionStringOptions = {\n user?: string\n password?: string\n host?: string\n db: string\n}\nexport default ({ user, password, host, db }: ConnectionStringOptions) => {\n let connection = `postgres://`\n if (user) {\n connection += user", "score": 18.285570751424366 }, { "filename": "src/utils/prepare-project.ts", "retrieved_chunk": " // initialize execution options\n const execOptions = {\n cwd: directory,\n signal: abortController?.signal,\n }\n // initialize the invite token to return\n let inviteToken: string | undefined = undefined\n // add connection string to project\n fs.appendFileSync(\n path.join(directory, `.env`),", "score": 13.291875723513433 } ]
typescript
= await postgresClient({
import inquirer from "inquirer" import slugifyType from "slugify" import chalk from "chalk" import pg from "pg" import createDb from "../utils/create-db.js" import postgresClient from "../utils/postgres-client.js" import cloneRepo from "../utils/clone-repo.js" import prepareProject from "../utils/prepare-project.js" import startMedusa from "../utils/start-medusa.js" import open from "open" import waitOn from "wait-on" import formatConnectionString from "../utils/format-connection-string.js" import ora from "ora" import fs from "fs" import { nanoid } from "nanoid" import isEmailImported from "validator/lib/isEmail.js" import logMessage from "../utils/log-message.js" import onProcessTerminated from "../utils/on-process-terminated.js" import createAbortController, { isAbortError, } from "../utils/create-abort-controller.js" const slugify = slugifyType.default const isEmail = isEmailImported.default type CreateOptions = { repoUrl?: string seed?: boolean } export default async ({ repoUrl = "", seed }: CreateOptions) => { const abortController = createAbortController() const { projectName } = await inquirer.prompt([ { type: "input", name: "projectName", message: "What's the name of your project?", default: "my-medusa-store", filter: (input) => { return slugify(input) }, validate: (input) => { if (!input.length) { return "Please enter a project name" } return fs.existsSync(input) && fs.lstatSync(input).isDirectory() ? "A directory already exists with the same name. Please enter a different project name." : true }, }, ]) let client: pg.Client | undefined let dbConnectionString = "" let postgresUsername = "postgres" let postgresPassword = "" // try to log in with default db username and password try { client = await postgresClient({ user: postgresUsername, password: postgresPassword, }) } catch (e) { // ask for the user's credentials const answers = await inquirer.prompt([ { type: "input", name: "postgresUsername", message: "Enter your Postgres username", default: "postgres", validate: (input) => { return typeof input === "string" && input.length > 0 }, }, { type: "password", name: "postgresPassword", message: "Enter your Postgres password", }, ]) postgresUsername = answers.postgresUsername postgresPassword = answers.postgresPassword try { client = await postgresClient({ user: postgresUsername, password: postgresPassword, }) } catch (e) { logMessage({ message: "Couldn't connect to PostgreSQL. Make sure you have PostgreSQL installed and the credentials you provided are correct.\n\n" + "You can learn how to install PostgreSQL here: https://docs.medusajs.com/development/backend/prepare-environment#postgresql", type: "error", }) } } const { adminEmail } = await inquirer.prompt([ { type: "input", name: "adminEmail", message: "Enter an email for your admin dashboard user", default: !seed ? "[email protected]" : undefined, validate: (input) => { return typeof input === "string" && input.length > 0 && isEmail(input) ? true : "Please enter a valid email" }, }, ]) const spinner = ora(chalk.white("Setting up project")).start() onProcessTerminated(() => spinner.stop()) // clone repository try {
await cloneRepo({
directoryName: projectName, repoUrl, abortController, }) } catch (e) { if (isAbortError(e)) { process.exit() } logMessage({ message: `An error occurred while setting up your project: ${e}`, type: "error", }) } spinner.succeed(chalk.green("Created project directory")).start() if (client) { spinner.text = chalk.white("Creating database...") const dbName = `medusa-${nanoid(4)}` // create postgres database try { await createDb({ client, db: dbName, }) } catch (e) { logMessage({ message: `An error occurred while trying to create your database: ${e}`, type: "error", }) } // format connection string dbConnectionString = formatConnectionString({ user: postgresUsername, password: postgresPassword, host: client.host, db: dbName, }) spinner.succeed(chalk.green(`Database ${dbName} created`)).start() } spinner.text = chalk.white("Preparing project...") // prepare project let inviteToken: string | undefined = undefined try { inviteToken = await prepareProject({ directory: projectName, dbConnectionString, admin: { email: adminEmail, }, seed, spinner, abortController, }) } catch (e: any) { if (isAbortError(e)) { process.exit() } logMessage({ message: `An error occurred while preparing project: ${e}`, type: "error", }) } spinner.succeed(chalk.green("Project Prepared")) // close db connection await client?.end() // start backend logMessage({ message: "Starting Medusa...", }) try { startMedusa({ directory: projectName, abortController, }) } catch (e) { if (isAbortError(e)) { process.exit() } logMessage({ message: `An error occurred while starting Medusa`, type: "error", }) } waitOn({ resources: ["http://localhost:9000/health"], }).then(() => open( inviteToken ? `http://localhost:9000/app/invite?token=${inviteToken}` : "http://localhost:9000/app" ) ) }
src/commands/create.ts
shahednasser-create-medusa-app-demo-e3950ff
[ { "filename": "src/utils/prepare-project.ts", "retrieved_chunk": " spinner?.succeed(chalk.green(\"Created admin user\")).start()\n }\n if (seed) {\n if (spinner) {\n spinner.text = chalk.white(\"Seeding database...\")\n }\n // check if a seed file exists in the project\n if (!fs.existsSync(path.join(directory, \"data\", \"seed.jsons\"))) {\n spinner\n ?.warn(", "score": 10.859000364877721 }, { "filename": "src/utils/prepare-project.ts", "retrieved_chunk": " chalk.yellow(\n \"Seed file was not found in the project. Skipping seeding...\"\n )\n )\n .start()\n return\n }\n if (spinner) {\n spinner.text = chalk.white(\"Seeding database with demo data...\")\n }", "score": 9.97117318242925 }, { "filename": "src/utils/prepare-project.ts", "retrieved_chunk": " )\n },\n })\n spinner?.succeed(chalk.green(\"Ran Migrations\")).start()\n if (admin) {\n // create admin user\n if (spinner) {\n spinner.text = chalk.white(\"Creating an admin user...\")\n }\n await runProcess({", "score": 9.313245246867545 }, { "filename": "src/utils/prepare-project.ts", "retrieved_chunk": " spinner.spinner = \"dots\"\n spinner.succeed(chalk.green(\"Installed Dependencies\"))\n spinner.start(chalk.white(\"Running Migrations...\"))\n }\n // run migrations\n await runProcess({\n process: async () => {\n await promiseExec(\n \"npx -y @medusajs/medusa-cli@latest migrations run\",\n execOptions", "score": 9.072870778962963 }, { "filename": "src/utils/prepare-project.ts", "retrieved_chunk": " fact = showFact(fact, spinner)\n }, 6000)\n onProcessTerminated(() => clearInterval(interval))\n }\n await runProcess({\n process: async () => {\n try {\n await promiseExec(`yarn`, execOptions)\n } catch (e) {\n // yarn isn't available", "score": 8.577029191978067 } ]
typescript
await cloneRepo({
import chalk from "chalk" import fs from "fs" import path from "path" import { Ora } from "ora" import promiseExec from "./promise-exec.js" import { EOL } from "os" import runProcess from "./run-process.js" import getFact from "./get-fact.js" import onProcessTerminated from "./on-process-terminated.js" import boxen from "boxen" type PrepareOptions = { directory: string dbConnectionString: string admin?: { email: string } seed?: boolean spinner?: Ora abortController?: AbortController } const showFact = (lastFact: string, spinner: Ora): string => { const fact = getFact(lastFact) spinner.text = `${boxen(fact, { title: chalk.cyan("Installing Dependencies..."), titleAlignment: "center", textAlignment: "center", padding: 1, margin: 1, float: "center", })}` return fact } export default async ({ directory, dbConnectionString, admin, seed, spinner, abortController, }: PrepareOptions) => { // initialize execution options const execOptions = { cwd: directory, signal: abortController?.signal, } // initialize the invite token to return let inviteToken: string | undefined = undefined // add connection string to project fs.appendFileSync( path.join(directory, `.env`), `DATABASE_TYPE=postgres${EOL}DATABASE_URL=${dbConnectionString}` ) let interval: NodeJS.Timer | undefined = undefined let fact = "" if (spinner) { spinner.spinner = { frames: [""], } fact = showFact(fact, spinner) interval = setInterval(() => { fact = showFact(fact, spinner) }, 6000) onProcessTerminated(() => clearInterval(interval)) }
await runProcess({
process: async () => { try { await promiseExec(`yarn`, execOptions) } catch (e) { // yarn isn't available // use npm await promiseExec(`npm install`, execOptions) } }, ignoreERESOLVE: true, }) if (interval) { clearInterval(interval) } if (spinner) { spinner.spinner = "dots" spinner.succeed(chalk.green("Installed Dependencies")) spinner.start(chalk.white("Running Migrations...")) } // run migrations await runProcess({ process: async () => { await promiseExec( "npx -y @medusajs/medusa-cli@latest migrations run", execOptions ) }, }) spinner?.succeed(chalk.green("Ran Migrations")).start() if (admin) { // create admin user if (spinner) { spinner.text = chalk.white("Creating an admin user...") } await runProcess({ process: async () => { const proc = await promiseExec( `npx -y @medusajs/[email protected] user -e ${admin.email} --invite`, execOptions ) // get invite token from stdout const match = proc.stdout.match(/Invite token: (?<token>.+)/) inviteToken = match?.groups?.token }, }) spinner?.succeed(chalk.green("Created admin user")).start() } if (seed) { if (spinner) { spinner.text = chalk.white("Seeding database...") } // check if a seed file exists in the project if (!fs.existsSync(path.join(directory, "data", "seed.jsons"))) { spinner ?.warn( chalk.yellow( "Seed file was not found in the project. Skipping seeding..." ) ) .start() return } if (spinner) { spinner.text = chalk.white("Seeding database with demo data...") } await runProcess({ process: async () => { await promiseExec( `npx -y @medusajs/medusa-cli@latest seed --seed-file=${path.join( "data", "seed.json" )}`, execOptions ) }, }) spinner?.succeed(chalk.green("Seeded database with demo data")).start() } return inviteToken }
src/utils/prepare-project.ts
shahednasser-create-medusa-app-demo-e3950ff
[ { "filename": "src/utils/get-fact.ts", "retrieved_chunk": " let index = 0\n if (lastFact.length) {\n const lastFactIndex = facts.findIndex((fact) => fact === lastFact)\n if (lastFactIndex !== facts.length - 1) {\n index = lastFactIndex + 1\n }\n }\n return facts[index]\n}", "score": 20.36258648357781 }, { "filename": "src/commands/create.ts", "retrieved_chunk": " ? true\n : \"Please enter a valid email\"\n },\n },\n ])\n const spinner = ora(chalk.white(\"Setting up project\")).start()\n onProcessTerminated(() => spinner.stop())\n // clone repository\n try {\n await cloneRepo({", "score": 15.395990294863672 }, { "filename": "src/commands/create.ts", "retrieved_chunk": " type: \"error\",\n })\n }\n spinner.succeed(chalk.green(\"Created project directory\")).start()\n if (client) {\n spinner.text = chalk.white(\"Creating database...\")\n const dbName = `medusa-${nanoid(4)}`\n // create postgres database\n try {\n await createDb({", "score": 11.851058027001699 }, { "filename": "src/commands/create.ts", "retrieved_chunk": " dbConnectionString = formatConnectionString({\n user: postgresUsername,\n password: postgresPassword,\n host: client.host,\n db: dbName,\n })\n spinner.succeed(chalk.green(`Database ${dbName} created`)).start()\n }\n spinner.text = chalk.white(\"Preparing project...\")\n // prepare project", "score": 11.316056426142445 }, { "filename": "src/commands/create.ts", "retrieved_chunk": " let inviteToken: string | undefined = undefined\n try {\n inviteToken = await prepareProject({\n directory: projectName,\n dbConnectionString,\n admin: {\n email: adminEmail,\n },\n seed,\n spinner,", "score": 10.471768260622357 } ]
typescript
await runProcess({
import type { Attributes, ModelStatic, Sequelize, Transaction, } from "sequelize"; import type { IAssociation, JSONAnyObject } from "../types"; import { handleUpdateMany, handleUpdateOne } from "./sequelize.patch"; import { handleBulkCreateHasOne, handleBulkCreateMany, handleCreateHasOne, handleCreateMany, } from "./sequelize.post"; export const getValidAttributesAndAssociations = ( attributes: Attributes<any> | Array<Attributes<any>>, associations: Record<string, IAssociation> | undefined, ) => { const externalAssociations: string[] = []; let currentModelAttributes = attributes; const otherAssociationAttributes: JSONAnyObject = {}; if (associations) { const associationsKeys = Object.keys(associations); const attributeKeys = Array.isArray(currentModelAttributes) ? Object.keys(attributes[0]) : Object.keys(attributes); // GET ALL ASSOCIATION ATTRIBUTES AND SEPARATE THEM FROM DATA LEFT associationsKeys.forEach((association) => { if (attributeKeys.includes(association)) { let data: any; if (Array.isArray(currentModelAttributes)) { data = currentModelAttributes.map((attribute: any) => { const { [association]: _, ...attributesleft } = attribute; const otherAttr = otherAssociationAttributes[association] ?? []; otherAssociationAttributes[association] = [...otherAttr, _]; return attributesleft; }); } else { const { [association]: _, ...attributesLeft } = currentModelAttributes; data = attributesLeft; } currentModelAttributes = data; externalAssociations.push(association); } }); } return { otherAssociationAttributes, externalAssociations, currentModelAttributes, }; }; export const handleCreateAssociations = async ( sequelize: Sequelize, model: ModelStatic<any>, validAssociations: string[], associations: Record<string, IAssociation>, attributes: Attributes<any>, transaction: Transaction, modelId: string, primaryKey = "id", ): Promise<void> => { for (const association of validAssociations) { const associationDetails = associations[association]; const associationAttribute = attributes[association];
switch (associationDetails.type) {
case "BelongsTo": case "HasOne": await handleCreateHasOne( sequelize, { details: associationDetails, attributes: associationAttribute, }, { name: model.name, id: modelId }, transaction, primaryKey, ); break; case "BelongsToMany": case "HasMany": await handleCreateMany( sequelize, { details: associationDetails, attributes: associationAttribute, }, { name: model.name, id: modelId }, transaction, primaryKey, ); break; default: break; } } }; export const handleBulkCreateAssociations = async ( sequelize: Sequelize, model: ModelStatic<any>, validAssociations: string[], associations: Record<string, IAssociation>, attributes: JSONAnyObject, transaction: Transaction, modelIds: string[], primaryKey = "id", ): Promise<void> => { for (const association of validAssociations) { const associationDetails = associations[association]; const associationAttribute = attributes[association]; switch (associationDetails.type) { case "BelongsTo": case "HasOne": await handleBulkCreateHasOne( sequelize, { details: associationDetails, attributes: associationAttribute, }, { name: model.name, id: modelIds }, transaction, primaryKey, ); break; case "BelongsToMany": case "HasMany": await handleBulkCreateMany( sequelize, { details: associationDetails, attributes: associationAttribute, }, { name: model.name, id: modelIds }, transaction, primaryKey, ); break; default: break; } } }; export const handleUpdateAssociations = async ( sequelize: Sequelize, model: ModelStatic<any>, validAssociations: string[], associations: Record<string, IAssociation>, attributes: Attributes<any>, transaction: Transaction, modelId: string, primaryKey = "id", ): Promise<void> => { for (const association of validAssociations) { const associationDetails = associations[association]; const associationAttribute = attributes[association]; switch (associationDetails.type) { case "BelongsTo": case "HasOne": await handleUpdateOne( sequelize, { details: associationDetails, attributes: associationAttribute, }, { name: model.name, id: modelId, }, transaction, primaryKey, ); break; case "HasMany": case "BelongsToMany": await handleUpdateMany( sequelize, { details: associationDetails, attributes: associationAttribute, }, { name: model.name, id: modelId, }, transaction, primaryKey, ); break; default: break; } } };
src/sequelize/associations/index.ts
bitovi-sequelize-create-with-associations-908ee8a
[ { "filename": "src/sequelize/associations/sequelize.patch.ts", "retrieved_chunk": " sequelize: Sequelize,\n association: IAssociationBody<Array<Record<string, any>>>,\n model: { name: string; id: string },\n transaction: Transaction,\n primaryKey = \"id\",\n): Promise<void> => {\n const modelName = association.details.model;\n const associatedIds = association.attributes.map((data) => data[primaryKey]);\n const [modelInstance, associatedInstances] = await Promise.all([\n sequelize.models[model.name].findByPk(model[primaryKey], {", "score": 19.596267238120774 }, { "filename": "src/sequelize/extended.ts", "retrieved_chunk": "type AssociationLookup = Record<string, Record<string, IAssociation>>;\nlet associationsLookup: AssociationLookup;\nfunction calculateAssociationProp(associations) {\n const result = {};\n Object.keys(associations).forEach((key) => {\n const association = {};\n let propertyName;\n if (associations[key].hasOwnProperty(\"options\")) {\n const { associationType, target, foreignKey, throughModel } =\n associations[key];", "score": 16.36944525085931 }, { "filename": "src/sequelize/associations/sequelize.patch.ts", "retrieved_chunk": "import { pluralize } from \"inflection\";\nimport { Op } from \"sequelize\";\nimport type { Sequelize, Transaction } from \"sequelize\";\nimport { NotFoundError } from \"../types\";\nimport type { IAssociationBody } from \"../types\";\nexport const handleUpdateOne = async (\n sequelize: Sequelize,\n association: IAssociationBody<Array<Record<string, any>>>,\n model: { name: string; id: string },\n transaction: Transaction,", "score": 14.348464844160421 }, { "filename": "src/sequelize/associations/sequelize.post.ts", "retrieved_chunk": "};\nexport const handleBulkCreateMany = async (\n sequelize: Sequelize,\n association: IAssociationBody<JSONAnyObject[][]>,\n model: { name: string; id: string[] },\n transaction: Transaction,\n primaryKey = \"id\",\n): Promise<void> => {\n // Create an instance of the model using the id\n const modelInstances = await sequelize.models[model.name].findAll({", "score": 14.064384009768059 }, { "filename": "src/sequelize/extended.ts", "retrieved_chunk": " await handleCreateAssociations(\n this.sequelize,\n this,\n externalAssociations,\n associations as Record<string, IAssociation>,\n attributes,\n transaction,\n modelData?.[modelPrimaryKey],\n modelPrimaryKey,\n );", "score": 13.465853423403384 } ]
typescript
switch (associationDetails.type) {
import type { Model, CreateOptions, Attributes, UpdateOptions, } from "sequelize"; import type { Col, Fn, Literal, MakeNullishOptional, } from "sequelize/types/utils"; import { getValidAttributesAndAssociations, handleBulkCreateAssociations, handleCreateAssociations, handleUpdateAssociations, } from "./associations"; import { UnexpectedValueError } from "./types"; import type { IAssociation } from "./types"; type AssociationLookup = Record<string, Record<string, IAssociation>>; let associationsLookup: AssociationLookup; function calculateAssociationProp(associations) { const result = {}; Object.keys(associations).forEach((key) => { const association = {}; let propertyName; if (associations[key].hasOwnProperty("options")) { const { associationType, target, foreignKey, throughModel } = associations[key]; propertyName = key.toLocaleLowerCase(); association[propertyName] = { type: associationType, key: foreignKey, model: target.name, joinTable: throughModel, }; } result[propertyName] = association[propertyName]; }); return result; } export function getLookup(sequelize): AssociationLookup { //TODO: Fix associations lookup being static /* if (!associationsLookup) { */ const lookup: any = {}; const models = sequelize.models; const modelKeys = Object.keys(models); modelKeys.forEach((key) => { const associations = calculateAssociationProp(models[key].associations); lookup[key] = associations; }); associationsLookup = lookup; return associationsLookup; } export const extendSequelize = (SequelizeClass: any) => { const origCreate = SequelizeClass.Model.create; const origUpdate = SequelizeClass.Model.update; const origBulkCreate = SequelizeClass.Model.bulkCreate; SequelizeClass.Model.create = async function < M extends Model, O extends CreateOptions<Attributes<M>> = CreateOptions<Attributes<M>>, >( attributes: MakeNullishOptional<M["_creationAttributes"]> | undefined, options?: O, ) { const { sequelize } = this.options; const associations = getLookup(sequelize)[this.name]; const modelPrimaryKey = this.primaryKeyAttribute; let modelData: | undefined | (O extends { returning: false } | { ignoreDuplicates: true } ? void : M); const { externalAssociations, currentModelAttributes } = getValidAttributesAndAssociations(attributes, associations); // If there are no associations, create the model with all attributes. if (!externalAssociations.length) { return origCreate.apply(this, [attributes, options]); } const transaction = options?.transaction ?? (await this.sequelize.transaction()); try { // create the model first if it does not exist if (!modelData) { modelData = await origCreate.apply(this, [ currentModelAttributes, { transaction }, ]); } await handleCreateAssociations( this.sequelize, this, externalAssociations, associations as Record<string, IAssociation>, attributes, transaction, modelData?.[modelPrimaryKey], modelPrimaryKey, ); !options?.transaction && (await transaction.commit()); } catch (error) { !options?.transaction && (await transaction.rollback()); throw error; } return modelData; }; SequelizeClass.Model.bulkCreate = async function < M extends Model, O extends CreateOptions<Attributes<M>> = CreateOptions<Attributes<M>>, >( attributes: Array<MakeNullishOptional<M["_creationAttributes"]>>, options?: O, ) { const { sequelize } = this.options; const associations = getLookup(sequelize)[this.name]; const modelPrimaryKey = this.primaryKeyAttribute; let modelData: | undefined | Array< O extends { returning: false } | { ignoreDuplicates: true } ? void : M >; const { otherAssociationAttributes, externalAssociations, currentModelAttributes, } = getValidAttributesAndAssociations(attributes, associations); // If there are no associations, create the model with all attributes. if (!externalAssociations.length) { return origBulkCreate.apply(this, [attributes, options]); } const transaction = options?.transaction ?? (await this.sequelize.transaction()); try { // create the model first if it does not exist if (!modelData) { modelData = await origBulkCreate.apply(this, [ currentModelAttributes, { transaction }, ]); } const modelIds = modelData?.map((data) => data.getDataValue(modelPrimaryKey), ) as string[]; await handleBulkCreateAssociations( this.sequelize, this, externalAssociations, associations as Record<string, IAssociation>, otherAssociationAttributes, transaction, modelIds, modelPrimaryKey, ); !options?.transaction && (await transaction.commit()); } catch (error) { !options?.transaction && (await transaction.rollback()); throw error; } return modelData; }; SequelizeClass.Model.update = async function <M extends Model<any, any>>( attributes: { [key in keyof Attributes<M>]?: | Fn | Col | Literal | Attributes<M>[key] | undefined; }, ops: Omit<UpdateOptions<Attributes<M>>, "returning"> & { returning: Exclude< UpdateOptions<Attributes<M>>["returning"], undefined | false >; }, ) { const { sequelize } = this.options; const associations = getLookup(sequelize)[this.name]; const modelPrimaryKey = this.primaryKeyAttribute; const modelId = ops.where?.[modelPrimaryKey]; let modelUpdateData: [affectedCount: number, affectedRows: M[]] | undefined; const { externalAssociations, currentModelAttributes } = getValidAttributesAndAssociations(attributes, associations); // If there are no associations, create the model with all attributes. if (!externalAssociations.length) { return origUpdate.apply(this, [attributes, ops]); } else if (!modelId) { throw [ new
UnexpectedValueError({
detail: "Only updating by the primary key is supported", }), ]; } const transaction = await this.sequelize.transaction(); try { if (!modelUpdateData) { modelUpdateData = await origUpdate.apply(this, [ currentModelAttributes, { ...ops, transaction, }, ]); } await handleUpdateAssociations( this.sequelize, this, externalAssociations, associations as Record<string, IAssociation>, attributes, transaction, modelId, modelPrimaryKey, ); !ops?.transaction && (await transaction.commit()); } catch (error) { !ops?.transaction && (await transaction.rollback()); throw error; } return modelUpdateData; }; };
src/sequelize/extended.ts
bitovi-sequelize-create-with-associations-908ee8a
[ { "filename": "src/sequelize/associations/index.ts", "retrieved_chunk": " handleBulkCreateMany,\n handleCreateHasOne,\n handleCreateMany,\n} from \"./sequelize.post\";\nexport const getValidAttributesAndAssociations = (\n attributes: Attributes<any> | Array<Attributes<any>>,\n associations: Record<string, IAssociation> | undefined,\n) => {\n const externalAssociations: string[] = [];\n let currentModelAttributes = attributes;", "score": 23.411226140965688 }, { "filename": "src/sequelize/associations/index.ts", "retrieved_chunk": " data = attributesLeft;\n }\n currentModelAttributes = data;\n externalAssociations.push(association);\n }\n });\n }\n return {\n otherAssociationAttributes,\n externalAssociations,", "score": 16.51216547825665 }, { "filename": "src/sequelize/associations/sequelize.post.ts", "retrieved_chunk": " }\n let joinId: string | undefined;\n const isCreate = !association.attributes[primaryKey];\n if (isCreate) {\n const model = await sequelize.models[modelName].create(\n association.attributes,\n {\n transaction,\n },\n );", "score": 13.290160607652785 }, { "filename": "src/sequelize/associations/index.ts", "retrieved_chunk": " const otherAssociationAttributes: JSONAnyObject = {};\n if (associations) {\n const associationsKeys = Object.keys(associations);\n const attributeKeys = Array.isArray(currentModelAttributes)\n ? Object.keys(attributes[0])\n : Object.keys(attributes);\n // GET ALL ASSOCIATION ATTRIBUTES AND SEPARATE THEM FROM DATA LEFT\n associationsKeys.forEach((association) => {\n if (attributeKeys.includes(association)) {\n let data: any;", "score": 12.427197518310736 }, { "filename": "src/sequelize/associations/sequelize.post.ts", "retrieved_chunk": " association.attributes.map(async (attributes, index) => {\n return Promise.allSettled(\n attributes.map(async (attribute, index2) => {\n const isCreate = !attribute[primaryKey];\n if (isCreate) {\n // Create the models first and add their ids to the joinIds.\n const id = (\n await sequelize.models[modelName].create(\n { ...attribute, through: undefined },\n { transaction },", "score": 12.42139774336102 } ]
typescript
UnexpectedValueError({
import chalk from "chalk" import fs from "fs" import path from "path" import { Ora } from "ora" import promiseExec from "./promise-exec.js" import { EOL } from "os" import runProcess from "./run-process.js" import getFact from "./get-fact.js" import onProcessTerminated from "./on-process-terminated.js" import boxen from "boxen" type PrepareOptions = { directory: string dbConnectionString: string admin?: { email: string } seed?: boolean spinner?: Ora abortController?: AbortController } const showFact = (lastFact: string, spinner: Ora): string => { const fact = getFact(lastFact) spinner.text = `${boxen(fact, { title: chalk.cyan("Installing Dependencies..."), titleAlignment: "center", textAlignment: "center", padding: 1, margin: 1, float: "center", })}` return fact } export default async ({ directory, dbConnectionString, admin, seed, spinner, abortController, }: PrepareOptions) => { // initialize execution options const execOptions = { cwd: directory, signal: abortController?.signal, } // initialize the invite token to return let inviteToken: string | undefined = undefined // add connection string to project fs.appendFileSync( path.join(directory, `.env`), `DATABASE_TYPE=postgres${EOL}DATABASE_URL=${dbConnectionString}` ) let interval: NodeJS.Timer | undefined = undefined let fact = "" if (spinner) { spinner.spinner = { frames: [""], } fact = showFact(fact, spinner) interval = setInterval(() => { fact = showFact(fact, spinner) }, 6000) onProcessTerminated(() => clearInterval(interval)) } await runProcess({ process: async () => { try {
await promiseExec(`yarn`, execOptions) } catch (e) {
// yarn isn't available // use npm await promiseExec(`npm install`, execOptions) } }, ignoreERESOLVE: true, }) if (interval) { clearInterval(interval) } if (spinner) { spinner.spinner = "dots" spinner.succeed(chalk.green("Installed Dependencies")) spinner.start(chalk.white("Running Migrations...")) } // run migrations await runProcess({ process: async () => { await promiseExec( "npx -y @medusajs/medusa-cli@latest migrations run", execOptions ) }, }) spinner?.succeed(chalk.green("Ran Migrations")).start() if (admin) { // create admin user if (spinner) { spinner.text = chalk.white("Creating an admin user...") } await runProcess({ process: async () => { const proc = await promiseExec( `npx -y @medusajs/[email protected] user -e ${admin.email} --invite`, execOptions ) // get invite token from stdout const match = proc.stdout.match(/Invite token: (?<token>.+)/) inviteToken = match?.groups?.token }, }) spinner?.succeed(chalk.green("Created admin user")).start() } if (seed) { if (spinner) { spinner.text = chalk.white("Seeding database...") } // check if a seed file exists in the project if (!fs.existsSync(path.join(directory, "data", "seed.jsons"))) { spinner ?.warn( chalk.yellow( "Seed file was not found in the project. Skipping seeding..." ) ) .start() return } if (spinner) { spinner.text = chalk.white("Seeding database with demo data...") } await runProcess({ process: async () => { await promiseExec( `npx -y @medusajs/medusa-cli@latest seed --seed-file=${path.join( "data", "seed.json" )}`, execOptions ) }, }) spinner?.succeed(chalk.green("Seeded database with demo data")).start() } return inviteToken }
src/utils/prepare-project.ts
shahednasser-create-medusa-app-demo-e3950ff
[ { "filename": "src/utils/get-fact.ts", "retrieved_chunk": " let index = 0\n if (lastFact.length) {\n const lastFactIndex = facts.findIndex((fact) => fact === lastFact)\n if (lastFactIndex !== facts.length - 1) {\n index = lastFactIndex + 1\n }\n }\n return facts[index]\n}", "score": 10.181293241788905 }, { "filename": "src/commands/create.ts", "retrieved_chunk": " ? true\n : \"Please enter a valid email\"\n },\n },\n ])\n const spinner = ora(chalk.white(\"Setting up project\")).start()\n onProcessTerminated(() => spinner.stop())\n // clone repository\n try {\n await cloneRepo({", "score": 9.109817707548991 }, { "filename": "src/utils/create-abort-controller.ts", "retrieved_chunk": "import onProcessTerminated from \"./on-process-terminated.js\"\nexport default () => {\n const abortController = new AbortController()\n onProcessTerminated(() => abortController.abort())\n return abortController\n}\nexport const isAbortError = (e: any) =>\n e !== null && \"code\" in e && e.code === \"ABORT_ERR\"", "score": 7.452732584062165 }, { "filename": "src/utils/run-process.ts", "retrieved_chunk": " do {\n try {\n await process()\n } catch (error) {\n if (\n typeof error === \"object\" &&\n error !== null &&\n \"code\" in error &&\n error?.code === \"EAGAIN\"\n ) {", "score": 7.143419798296814 }, { "filename": "src/commands/create.ts", "retrieved_chunk": " let postgresUsername = \"postgres\"\n let postgresPassword = \"\"\n // try to log in with default db username and password\n try {\n client = await postgresClient({\n user: postgresUsername,\n password: postgresPassword,\n })\n } catch (e) {\n // ask for the user's credentials", "score": 6.754548920088266 } ]
typescript
await promiseExec(`yarn`, execOptions) } catch (e) {
import {By, until} from 'selenium-webdriver'; import {createDriver} from '../driver'; import {elementGetter} from './elements'; import {isExcludedByTitle} from './isExcludedByTitle'; import {TJob} from '../../types'; export async function jobCollector(locations: string[], keyword: string) { const driver = await createDriver(); const jobs: TJob[] = []; try { for (const location of locations) { const keywords = encodeURI(keyword); await driver.get( `https://www.linkedin.com/jobs/search?keywords=${keywords}&location=${location}&f_TPR=r86400&trk=public_jobs_jobs-search-bar_search-submit&position=1&pageNum=0`, ); /* **FOR Getting All Job Element** const jobCount = await driver.findElement(By.className('results-context-header__job-count'))?.getText(); Math.ceil(+jobCount) with Select on Show More Button! */ for (let i = 0; i < 4; i++) { // Scroll to the bottom of the page await driver.executeScript('window.scrollTo(0, document.body.scrollHeight);'); // Wait for new content to load await driver.wait(until.elementLocated(By.css('ul.jobs-search__results-list>li'))); // Wait for some additional time to allow the page to fully render await driver.sleep(3000); } // Get job listings console.log('before listing...'); const jobElements = await driver.findElements(By.css('ul.jobs-search__results-list>li')); console.log(jobElements.length, `count of jobs for ${location}`); for (const el of jobElements) { const title = await elementGetter({el, selector: 'h3.base-search-card__title'}); const company = await elementGetter({ el, selector: '[data-tracking-control-name="public_jobs_jserp-result_job-search-card-subtitle"]', }); const location = await elementGetter({el, selector: 'span.job-search-card__location'}); const time = await elementGetter({el, selector: 'time'}); const link = await elementGetter({el, selector: 'a.base-card__full-link', method: 'attribute', attr: 'href'}); if
(isExcludedByTitle(title.toLocaleLowerCase()) && link.length > 1) {
jobs.push({ title: title.toLocaleLowerCase(), company, location, time, link, visa: false, description: '', source: 'Linkedin', }); } else { console.log('filtered by title:', title); } } } return jobs; } catch (err) { console.log(err); } finally { // Close the browser await driver?.quit(); } }
src/modules/scraper/jobCollector.ts
sharifiniaa-job-scraper-26ab436
[ { "filename": "src/modules/scraper/elements.ts", "retrieved_chunk": "import {By, WebDriver, WebElement} from 'selenium-webdriver';\ntype TElementGetter = {\n el: WebElement;\n selector: string;\n method?: 'text' | 'attribute';\n attr?: string;\n};\nexport async function elementGetter({el, selector, method = 'text', attr = 'href'}: TElementGetter) {\n let name = '';\n try {", "score": 79.56891729334484 }, { "filename": "src/modules/scraper/elements.ts", "retrieved_chunk": " const element = await el.findElement(By.css(selector));\n name = method == 'text' ? await element.getText() : await element.getAttribute(attr);\n } catch {\n name = '';\n } finally {\n return name;\n }\n}\nexport async function jobDescriptionClicker(el: WebDriver) {\n try {", "score": 55.32095786076993 }, { "filename": "src/modules/scraper/saveJobs.ts", "retrieved_chunk": " title: job.title,\n company: job.company,\n location: job.location,\n time: job.time,\n link: job.link,\n description: cleanedText(job.description as string),\n job_name: job_name,\n },\n });\n await sendJobToChannel(response, count, jobs.length);", "score": 48.77130430307359 }, { "filename": "src/modules/companies/relocateMe.ts", "retrieved_chunk": " for (const element of parentElement) {\n const childElement = await element.findElement(By.css('span:first-child'));\n const company = await childElement.getText();\n companies.push(company.toLocaleLowerCase());\n }\n let newCompanies = 0;\n for (const el of companies) {\n const isExist = await prisma.companies.findUnique({\n where: {\n name: el,", "score": 39.69243930335836 }, { "filename": "src/modules/companies/siaExplains.ts", "retrieved_chunk": " for (const element of parentElement) {\n const childElement = await element.findElement(By.css('td:first-child'));\n const company = await childElement.getText();\n companies.push(company.toLocaleLowerCase());\n }\n let newCompanies = 0;\n for (const el of companies) {\n const isExist = await prisma.companies.findUnique({\n where: {\n name: el,", "score": 36.172601935959015 } ]
typescript
(isExcludedByTitle(title.toLocaleLowerCase()) && link.length > 1) {
import {cleanedText} from '../../helper/cleanedText'; import {createDriver} from '../driver'; import {jobDescriptionClicker} from './elements'; import {By} from 'selenium-webdriver'; import prisma from '../db'; export async function getDescription(id: number) { try { const job = await prisma.job.findUnique({ where: { id, }, }); if (!job) { console.log(`Job ${id} is not exist in db`); return null; } if (job.description) { return job.description; } const description = await scrapDescription(job.link); const updatedJob = await prisma.job.update({ where: {id}, data: { description, }, }); return updatedJob?.description; } catch (err) { console.log(err); } } export async function scrapDescription(link: string) { const driver = await createDriver(); try { await driver.get(link); await jobDescriptionClicker(driver); await driver.sleep(5000); const element = await driver.findElement(By.className('core-section-container')); const text = await element.getText(); const editedText
= cleanedText(text).substring(0, 3500);
return editedText; } catch (err) { console.log(err); } finally { driver?.quit(); } }
src/modules/scraper/getDescription.ts
sharifiniaa-job-scraper-26ab436
[ { "filename": "src/modules/scraper/filterKeywords.ts", "retrieved_chunk": " const filteredJobs: TJob[] = [];\n for (const job of jobItems) {\n console.log('finding keywords ...', job.link);\n await driver.get(job.link);\n await jobDescriptionClicker(driver);\n await driver.sleep(3000);\n const element = await driver.findElement(By.className('core-section-container'));\n const text = await element.getText();\n await driver.sleep(3000);\n const companyName = text.toLocaleLowerCase();", "score": 73.96931749820615 }, { "filename": "src/modules/companies/relocateMe.ts", "retrieved_chunk": "import prisma from '../db';\nimport {createDriver} from '../driver';\nimport {By} from 'selenium-webdriver';\nexport const relocateMe = async () => {\n const driver = await createDriver();\n try {\n await driver.get('https://relocate.me/companies');\n await driver.sleep(3000);\n const parentElement = await driver.findElements(By.className('wwbc-companies__link'));\n const companies: string[] = [];", "score": 44.97128505833253 }, { "filename": "src/modules/companies/siaExplains.ts", "retrieved_chunk": "import prisma from '../db';\nimport {createDriver} from '../driver';\nimport {By} from 'selenium-webdriver';\nexport const siaExplains = async () => {\n const driver = await createDriver();\n try {\n await driver.get('https://siaexplains.github.io/visa-sponsorship-companies/');\n await driver.sleep(3000);\n const parentElement = await driver.findElements(By.className('odd:bg-white'));\n const companies: string[] = [];", "score": 43.70774926613267 }, { "filename": "src/modules/scraper/elements.ts", "retrieved_chunk": " const element = await el.findElement(By.css(selector));\n name = method == 'text' ? await element.getText() : await element.getAttribute(attr);\n } catch {\n name = '';\n } finally {\n return name;\n }\n}\nexport async function jobDescriptionClicker(el: WebDriver) {\n try {", "score": 39.66025495800121 }, { "filename": "src/modules/scraper/filterKeywords.ts", "retrieved_chunk": " const haveVisa =\n (await prisma.companies.findUnique({where: {name: companyName}})) ||\n text.toLocaleLowerCase().includes('visa sponsorship');\n job.visa = !!haveVisa;\n job.description = cleanedText(text).substring(0, 300) + '...';\n filteredJobs.push(job);\n const handles = await driver.getAllWindowHandles();\n for (let i = 1; i < handles.length; i++) {\n await driver.switchTo().window(handles[i]);\n await driver.close();", "score": 36.683750597267554 } ]
typescript
= cleanedText(text).substring(0, 3500);
import {cleanedText} from '../../helper/cleanedText'; import {createDriver} from '../driver'; import {jobDescriptionClicker} from './elements'; import {By} from 'selenium-webdriver'; import prisma from '../db'; export async function getDescription(id: number) { try { const job = await prisma.job.findUnique({ where: { id, }, }); if (!job) { console.log(`Job ${id} is not exist in db`); return null; } if (job.description) { return job.description; } const description = await scrapDescription(job.link); const updatedJob = await prisma.job.update({ where: {id}, data: { description, }, }); return updatedJob?.description; } catch (err) { console.log(err); } } export async function scrapDescription(link: string) { const driver = await createDriver(); try { await driver.get(link); await jobDescriptionClicker(driver); await driver.sleep(5000); const element = await driver.findElement(By.className('core-section-container')); const text = await element.getText(); const
editedText = cleanedText(text).substring(0, 3500);
return editedText; } catch (err) { console.log(err); } finally { driver?.quit(); } }
src/modules/scraper/getDescription.ts
sharifiniaa-job-scraper-26ab436
[ { "filename": "src/modules/scraper/filterKeywords.ts", "retrieved_chunk": " const filteredJobs: TJob[] = [];\n for (const job of jobItems) {\n console.log('finding keywords ...', job.link);\n await driver.get(job.link);\n await jobDescriptionClicker(driver);\n await driver.sleep(3000);\n const element = await driver.findElement(By.className('core-section-container'));\n const text = await element.getText();\n await driver.sleep(3000);\n const companyName = text.toLocaleLowerCase();", "score": 73.96931749820615 }, { "filename": "src/modules/companies/relocateMe.ts", "retrieved_chunk": "import prisma from '../db';\nimport {createDriver} from '../driver';\nimport {By} from 'selenium-webdriver';\nexport const relocateMe = async () => {\n const driver = await createDriver();\n try {\n await driver.get('https://relocate.me/companies');\n await driver.sleep(3000);\n const parentElement = await driver.findElements(By.className('wwbc-companies__link'));\n const companies: string[] = [];", "score": 44.97128505833253 }, { "filename": "src/modules/companies/siaExplains.ts", "retrieved_chunk": "import prisma from '../db';\nimport {createDriver} from '../driver';\nimport {By} from 'selenium-webdriver';\nexport const siaExplains = async () => {\n const driver = await createDriver();\n try {\n await driver.get('https://siaexplains.github.io/visa-sponsorship-companies/');\n await driver.sleep(3000);\n const parentElement = await driver.findElements(By.className('odd:bg-white'));\n const companies: string[] = [];", "score": 43.70774926613267 }, { "filename": "src/modules/scraper/elements.ts", "retrieved_chunk": " const element = await el.findElement(By.css(selector));\n name = method == 'text' ? await element.getText() : await element.getAttribute(attr);\n } catch {\n name = '';\n } finally {\n return name;\n }\n}\nexport async function jobDescriptionClicker(el: WebDriver) {\n try {", "score": 39.66025495800121 }, { "filename": "src/modules/scraper/filterKeywords.ts", "retrieved_chunk": " const haveVisa =\n (await prisma.companies.findUnique({where: {name: companyName}})) ||\n text.toLocaleLowerCase().includes('visa sponsorship');\n job.visa = !!haveVisa;\n job.description = cleanedText(text).substring(0, 300) + '...';\n filteredJobs.push(job);\n const handles = await driver.getAllWindowHandles();\n for (let i = 1; i < handles.length; i++) {\n await driver.switchTo().window(handles[i]);\n await driver.close();", "score": 36.683750597267554 } ]
typescript
editedText = cleanedText(text).substring(0, 3500);
import { parser } from "./parser.js"; import { writer } from "./writer.js"; import { objectToDom } from "./objectToDom.js"; import { toObject } from "./toObject.js"; import type { Xmltv, XmltvAudio, XmltvChannel, XmltvCreditImage, XmltvCredits, XmltvDom, XmltvDisplayName, XmltvEpisodeNumber, XmltvIcon, XmltvImage, XmltvLength, XmltvPerson, XmltvPreviouslyShown, XmltvProgramme, XmltvRating, XmltvReview, XmltvStarRating, XmltvSubtitle, XmltvUrl, XmltvVideo, } from "./types"; import { addAttributeTranslation, addTagTranslation, } from "./xmltvTranslations.js"; type ParseXmltvOptions = { asDom: boolean; }; type WriteXmltvOptions = { fromDom: boolean; }; /** * parseXmltv * * Parses an xmltv file and returns an `Xmltv` object or a DOM tree * * @param xmltvString The xmltv file content as a string * @param options Options to parse the xmltv file * @param options.asDom If true, the xmltv file will be returned as a DOM tree */ function parseXmltv( xmltvString: string, options: ParseXmltvOptions & { asDom: true } ): XmltvDom; function parseXmltv( xmltvString: string, options: ParseXmltvOptions & { asDom: false } ): XmltvDom; function parseXmltv(xmltvString: string): Xmltv; function parseXmltv( xmltvString: string, options: ParseXmltvOptions = { asDom: false } ): Xmltv | XmltvDom { const parsed = parser(xmltvString); if (options.asDom) { return parsed; }
return <Xmltv>toObject(parsed);
} /** * writeXmltv * * Writes an `Xmltv` object or a DOM tree to an xmltv string * * @param xmltv The `Xmltv` object or a DOM tree * @param options Options to write the xmltv file * @param options.fromDom If true, the xmltv file will be written from a DOM tree * @returns The xmltv file content as a string * @throws If `options.fromDom` is true and `xmltv` is an `Xmltv` object */ function writeXmltv( xmltv: XmltvDom, options: WriteXmltvOptions & { fromDom: true } ): string; function writeXmltv( xmltv: Xmltv, options: WriteXmltvOptions & { fromDom: false } ): string; function writeXmltv(xmltv: Xmltv): string; function writeXmltv( xmltv: Xmltv | XmltvDom, options: WriteXmltvOptions = { fromDom: false } ): string { if (options.fromDom) { if (typeof xmltv === "object" && !Array.isArray(xmltv)) { throw new Error( "Cannot write XMLTV from a DOM object that has been converted to an object" ); } return writer(xmltv); } const dom = objectToDom(xmltv); return writer(dom); } export { parseXmltv, writeXmltv, writer, parser, objectToDom, addTagTranslation, addAttributeTranslation, }; export type { Xmltv, XmltvChannel, XmltvDisplayName, XmltvProgramme, XmltvAudio, XmltvCreditImage, XmltvCredits, XmltvEpisodeNumber, XmltvIcon, XmltvImage, XmltvLength, XmltvPerson, XmltvPreviouslyShown, XmltvRating, XmltvReview, XmltvStarRating, XmltvSubtitle, XmltvUrl, XmltvVideo, };
src/main.ts
ektotv-xmltv-03be15c
[ { "filename": "src/parser.ts", "retrieved_chunk": " function parseString(): string {\n const startChar = xmltvString[pos];\n const start = pos + 1;\n pos = xmltvString.indexOf(startChar, start);\n return xmltvString.slice(start, pos);\n }\n return parseChildren(\"\");\n}", "score": 29.52036453975866 }, { "filename": "src/parser.ts", "retrieved_chunk": " }\n return xmltvString.slice(start, pos);\n }\n function parseNode() {\n pos++;\n const tagName = parseName();\n const attributes: Record<string, any> = {};\n let children: XmltvDom = [];\n // parsing attributes\n while (xmltvString.charCodeAt(pos) !== closeBracketCC && xmltvString[pos]) {", "score": 29.49425616645059 }, { "filename": "src/toObject.ts", "retrieved_chunk": "export function toObject(\n children: any[],\n parent: XmltvDomNode = { tagName: \"tv\", attributes: {}, children: [] }\n): Out | boolean | string | Xmltv {\n let out: Out = {};\n if (!children.length) {\n return out;\n }\n if (\n children.length === 1 &&", "score": 27.846861312071493 }, { "filename": "src/parser.ts", "retrieved_chunk": " /**\n * parsing a list of entries\n */\n function parseChildren(tagName: string): XmltvDom {\n const children: XmltvDom = [];\n while (xmltvString[pos]) {\n if (xmltvString.charCodeAt(pos) == openBracketCC) {\n if (xmltvString.charCodeAt(pos + 1) === slashCC) {\n const closeStart = pos + 2;\n pos = xmltvString.indexOf(closeBracket, pos);", "score": 27.104475071712884 }, { "filename": "src/parser.ts", "retrieved_chunk": " * Based on the original work of Tobias Nickel (txml)\n * I removed the more generic parts of the parser to focus on working with the XMLTV format\n * Outputs a more fluent object structure matching the Xmltv types\n */\nexport function parser(xmltvString: string): XmltvDom {\n let pos = 0;\n const openBracket = \"<\";\n const closeBracket = \">\";\n const openBracketCC = openBracket.charCodeAt(0);\n const closeBracketCC = closeBracket.charCodeAt(0);", "score": 26.20337430551958 } ]
typescript
return <Xmltv>toObject(parsed);
import type { Xmltv, XmltvDomNode } from "./types"; import { xmltvTimestampToUtcDate } from "./utils.js"; import { xmltvAttributeTranslations, xmltvTagTranslations, } from "./xmltvTranslations.js"; import type { XmltvTags, XmltvAttributes } from "./xmltvTagsAttributes.js"; const questionMarkCC = "?".charCodeAt(0); /** * Elements that can only be used once wherever they appear. * eg <credits> can only be used once in a <programme> element * but <actor> can be used multiple times in a <credits> element */ const singleUseElements: XmltvTags[] = [ "credits", "date", "language", "orig-language", "length", "country", "previously-shown", "premiere", "last-chance", "new", "video", "audio", // Sub-elements of 'video' "present", "colour", "aspect", "quality", // Sub-elements of 'audio' "present", "stereo", //sub-elements of rating and star rating "value", ]; /** * Elements that do not have children or attributes so can be rendered as a scalar * * eg <date>2020-01-01</date> should render as * { date: "2020-01-01" } * instead of * { date: { _value: "2020-01-01" } } */ const elementsAsScalar: XmltvTags[] = [ "date", "value", "aspect", "present", "colour", "quality", "stereo", ]; /** * Convert an XmltvDom tree to a plain object * * @param children The XmltvDom tree to convert */ type Out = Record<string, any>; export function toObject( children: any[],
parent: XmltvDomNode = { tagName: "tv", attributes: {}, children: [] }
): Out | boolean | string | Xmltv { let out: Out = {}; if (!children.length) { return out; } if ( children.length === 1 && typeof children[0] === "string" && (children[0] === "yes" || children[0] === "no") ) { return children[0] === "yes"; } if ( children.length === 1 && typeof children[0] === "string" && typeof parent !== "string" ) { if (Object.keys(parent.attributes).length) { return { _value: children[0], }; } return children[0]; } // map each object for (let i = 0, n = children.length; i < n; i++) { let child = children[i]; if ( typeof parent !== "string" && parent.tagName === "actor" && typeof child === "string" ) { out._value = child; } if (typeof child !== "object") { continue; } if (child.tagName.charCodeAt(0) === questionMarkCC) continue; if (child.tagName === "new") { out[child.tagName] = true; continue; } if (child.tagName === "tv") { out = {}; } const translatedName = xmltvTagTranslations.get(child.tagName) || child.tagName; if ( !out[translatedName] && singleUseElements.indexOf(child.tagName) === -1 ) { out[translatedName] = []; } let kids: any = toObject(child.children || [], child); if (Object.keys(child.attributes).length) { if (!Array.isArray(kids)) { if (child.attributes.size) { child.attributes.size = Number(child.attributes.size); } if (translatedName === "programmes") { if (child.attributes.stop) { child.attributes.stop = xmltvTimestampToUtcDate( child.attributes.stop ); } if (child.attributes["pdc-start"]) { child.attributes["pdc-start"] = xmltvTimestampToUtcDate( child.attributes["pdc-start"] ); } if (child.attributes["vps-start"]) { child.attributes["vps-start"] = xmltvTimestampToUtcDate( child.attributes["vps-start"] ); } } else if (translatedName === "icon") { if (child.attributes.width) { child.attributes.width = Number(child.attributes.width); } if (child.attributes.height) { child.attributes.height = Number(child.attributes.height); } } else if (child.attributes.units) { kids._value = Number(kids._value); } else if (child.attributes.guest) { child.attributes.guest = child.attributes.guest === "yes"; } if (child.attributes.date) { child.attributes.date = xmltvTimestampToUtcDate( child.attributes.date ); } if (child.attributes.start) { child.attributes.start = xmltvTimestampToUtcDate( child.attributes.start ); } const translatedAttributes = Object.keys(child.attributes).reduce( (acc: Record<string, string>, key: string) => { acc[xmltvAttributeTranslations.get(key as XmltvAttributes) || key] = child.attributes[key]; return acc; }, {} ); Object.assign(kids, translatedAttributes); } } if (translatedName === "subtitles") { if (typeof kids.language === "string") { kids.language = { _value: kids.language }; } out[translatedName].push(kids); continue; } if (translatedName === "tv") { out = kids; continue; } if (translatedName === "date") { out[translatedName] = xmltvTimestampToUtcDate(kids); continue; } if ( typeof kids === "string" && elementsAsScalar.indexOf(child.tagName) === -1 ) { kids = { _value: kids, }; } if (Array.isArray(out[translatedName])) { out[translatedName].push(kids); continue; } out[translatedName] = kids; } return out as Xmltv; }
src/toObject.ts
ektotv-xmltv-03be15c
[ { "filename": "src/types.ts", "retrieved_chunk": "export type XmltvDomNode =\n | {\n tagName: string;\n attributes: Record<string, any>;\n children: Array<XmltvDomNode | string>;\n }\n | string;\n/**\n * A collection of XMLTV DOM nodes to form a valid XMLTV document\n *", "score": 36.280853720995886 }, { "filename": "src/objectToDom.ts", "retrieved_chunk": " * @param obj The XMLTV object to convert to a DOM tree\n * @param key The current key to loop over\n * @param isArrayChild Controls if the return is an array or not\n * @returns The DOM tree\n */\nexport function objectToDom(obj: any, key = \"tv\", isArrayChild = false): any {\n if (Array.isArray(obj)) {\n return obj.map((item) => objectToDom(item, key, true));\n }\n if (typeof obj === \"number\") {", "score": 34.133293236681325 }, { "filename": "src/parser.ts", "retrieved_chunk": " }\n return xmltvString.slice(start, pos);\n }\n function parseNode() {\n pos++;\n const tagName = parseName();\n const attributes: Record<string, any> = {};\n let children: XmltvDom = [];\n // parsing attributes\n while (xmltvString.charCodeAt(pos) !== closeBracketCC && xmltvString[pos]) {", "score": 32.37425776190635 }, { "filename": "src/main.ts", "retrieved_chunk": " return parsed;\n }\n return <Xmltv>toObject(parsed);\n}\n/**\n * writeXmltv\n *\n * Writes an `Xmltv` object or a DOM tree to an xmltv string\n *\n * @param xmltv The `Xmltv` object or a DOM tree", "score": 30.407942072235894 }, { "filename": "src/main.ts", "retrieved_chunk": " * @param options Options to write the xmltv file\n * @param options.fromDom If true, the xmltv file will be written from a DOM tree\n * @returns The xmltv file content as a string\n * @throws If `options.fromDom` is true and `xmltv` is an `Xmltv` object\n */\nfunction writeXmltv(\n xmltv: XmltvDom,\n options: WriteXmltvOptions & { fromDom: true }\n): string;\nfunction writeXmltv(", "score": 23.416771176695324 } ]
typescript
parent: XmltvDomNode = { tagName: "tv", attributes: {}, children: [] }
import { XmltvDom } from "./types"; /** * The MIT License (MIT) * * Copyright (c) 2015 Tobias Nickel * * Copyright (c) 2023 Liam Potter * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software * and associated documentation files (the "Software"), to deal in the Software without restriction, * including without limitation the rights to use, copy, modify, merge, publish, distribute, * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or * substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /** * @author: Tobias Nickel * @created: 06.04.2015 * I needed a small xml parser that can be used in a worker. * * @author: Liam Potter * @created: 03.04.2023 * Based on the original work of Tobias Nickel (txml) * I removed the more generic parts of the parser to focus on working with the XMLTV format * Outputs a more fluent object structure matching the Xmltv types */
export function parser(xmltvString: string): XmltvDom {
let pos = 0; const openBracket = "<"; const closeBracket = ">"; const openBracketCC = openBracket.charCodeAt(0); const closeBracketCC = closeBracket.charCodeAt(0); const minusCC = "-".charCodeAt(0); const slashCC = "/".charCodeAt(0); const exclamationCC = "!".charCodeAt(0); const singleQuoteCC = "'".charCodeAt(0); const doubleQuoteCC = '"'.charCodeAt(0); const openCornerBracketCC = "[".charCodeAt(0); const closeCornerBracketCC = "]".charCodeAt(0); const questionMarkCC = "?".charCodeAt(0); const nameSpacer = "\r\n\t>/= "; const noChildNodes = ["new", "icon", "previously-shown"]; /** * parsing a list of entries */ function parseChildren(tagName: string): XmltvDom { const children: XmltvDom = []; while (xmltvString[pos]) { if (xmltvString.charCodeAt(pos) == openBracketCC) { if (xmltvString.charCodeAt(pos + 1) === slashCC) { const closeStart = pos + 2; pos = xmltvString.indexOf(closeBracket, pos); const closeTag = xmltvString.substring(closeStart, pos); if (closeTag.indexOf(tagName) == -1) { const parsedText = xmltvString.substring(0, pos).split("\n"); throw new Error( "Unexpected close tag\nLine: " + (parsedText.length - 1) + "\nColumn: " + (parsedText[parsedText.length - 1].length + 1) + "\nChar: " + xmltvString[pos] ); } if (pos + 1) pos += 1; return children; } else if (xmltvString.charCodeAt(pos + 1) === exclamationCC) { if (xmltvString.charCodeAt(pos + 2) == minusCC) { //comment support while ( pos !== -1 && !( xmltvString.charCodeAt(pos) === closeBracketCC && xmltvString.charCodeAt(pos - 1) == minusCC && xmltvString.charCodeAt(pos - 2) == minusCC && pos != -1 ) ) { pos = xmltvString.indexOf(closeBracket, pos + 1); } if (pos === -1) { pos = xmltvString.length; } } else { // doctype support const startDoctype = pos + 1; pos += 2; let encapsulated = false; while ( (xmltvString.charCodeAt(pos) !== closeBracketCC || encapsulated === true) && xmltvString[pos] ) { if (xmltvString.charCodeAt(pos) === openCornerBracketCC) { encapsulated = true; } else if ( encapsulated === true && xmltvString.charCodeAt(pos) === closeCornerBracketCC ) { encapsulated = false; } pos++; } children.push(xmltvString.substring(startDoctype, pos)); } pos++; continue; } const node = parseNode(); children.push(node); if (node.tagName.charCodeAt(0) === questionMarkCC) { for (let i = 0, x = node.children.length; i < x; i++) { children.push(node.children[i]); } node.children = []; } } else { const text = parseText().trim(); if (text.length > 0) { children.push(text); } pos++; } } return children; } /** * returns the text outside of texts until the first '<' */ function parseText() { const start = pos; pos = xmltvString.indexOf(openBracket, pos) - 1; if (pos === -2) pos = xmltvString.length; return xmltvString.slice(start, pos + 1); } /** * returns text until the first nonAlphabetic letter */ function parseName() { const start = pos; while (nameSpacer.indexOf(xmltvString[pos]) === -1 && xmltvString[pos]) { pos++; } return xmltvString.slice(start, pos); } function parseNode() { pos++; const tagName = parseName(); const attributes: Record<string, any> = {}; let children: XmltvDom = []; // parsing attributes while (xmltvString.charCodeAt(pos) !== closeBracketCC && xmltvString[pos]) { const c = xmltvString.charCodeAt(pos); if ((c > 64 && c < 91) || (c > 96 && c < 123)) { const name = parseName(); // search beginning of the string let code = xmltvString.charCodeAt(pos); let value; while ( code && code !== singleQuoteCC && code !== doubleQuoteCC && !((code > 64 && code < 91) || (code > 96 && code < 123)) && code !== closeBracketCC ) { pos++; code = xmltvString.charCodeAt(pos); } if (code === singleQuoteCC || code === doubleQuoteCC) { value = parseString(); if (pos === -1) { return { tagName, attributes, children, }; } } else { value = null; pos--; } attributes[name] = value; } pos++; } // optional parsing of children if (xmltvString.charCodeAt(pos - 1) !== slashCC) { if (noChildNodes.indexOf(tagName) === -1) { pos++; children = parseChildren(tagName); } else { pos++; } } else { pos++; } return { tagName, attributes, children, }; } function parseString(): string { const startChar = xmltvString[pos]; const start = pos + 1; pos = xmltvString.indexOf(startChar, start); return xmltvString.slice(start, pos); } return parseChildren(""); }
src/parser.ts
ektotv-xmltv-03be15c
[ { "filename": "src/main.ts", "retrieved_chunk": " xmltvString: string,\n options: ParseXmltvOptions & { asDom: false }\n): XmltvDom;\nfunction parseXmltv(xmltvString: string): Xmltv;\nfunction parseXmltv(\n xmltvString: string,\n options: ParseXmltvOptions = { asDom: false }\n): Xmltv | XmltvDom {\n const parsed = parser(xmltvString);\n if (options.asDom) {", "score": 33.08169918523131 }, { "filename": "src/types.ts", "retrieved_chunk": " * a particular actor (for example) does not imply that he _didn't_ star in the film - so normally\n * you'd list only the few most important people.\n *\n * Adapter can be either somebody who adapted a work for television, or somebody who did the translation\n * from another lang. The distinction is not always clear.\n *\n * URL can be, for example, a link to a webpage with more information about the actor, director, etc..\n */\nexport type XmltvCredits = {\n /**", "score": 22.701555497605202 }, { "filename": "src/main.ts", "retrieved_chunk": " parseXmltv,\n writeXmltv,\n writer,\n parser,\n objectToDom,\n addTagTranslation,\n addAttributeTranslation,\n};\nexport type {\n Xmltv,", "score": 22.497040620759563 }, { "filename": "src/main.ts", "retrieved_chunk": "import { parser } from \"./parser.js\";\nimport { writer } from \"./writer.js\";\nimport { objectToDom } from \"./objectToDom.js\";\nimport { toObject } from \"./toObject.js\";\nimport type {\n Xmltv,\n XmltvAudio,\n XmltvChannel,\n XmltvCreditImage,\n XmltvCredits,", "score": 20.06565619678566 }, { "filename": "src/main.ts", "retrieved_chunk": " *\n * @param xmltvString The xmltv file content as a string\n * @param options Options to parse the xmltv file\n * @param options.asDom If true, the xmltv file will be returned as a DOM tree\n */\nfunction parseXmltv(\n xmltvString: string,\n options: ParseXmltvOptions & { asDom: true }\n): XmltvDom;\nfunction parseXmltv(", "score": 19.817855443617947 } ]
typescript
export function parser(xmltvString: string): XmltvDom {