prefix
stringlengths 82
32.6k
| middle
stringlengths 5
470
| suffix
stringlengths 0
81.2k
| file_path
stringlengths 6
168
| repo_name
stringlengths 16
77
| context
listlengths 5
5
| lang
stringclasses 4
values | ground_truth
stringlengths 5
470
|
---|---|---|---|---|---|---|---|
import { 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": 0.6685104370117188
},
{
"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": 0.6559475660324097
},
{
"filename": "src/htmlRewriterClasses/After.ts",
"retrieved_chunk": "class After {\n content: string\n contentOptions?: ContentOptions\n constructor(content: string, contentOptions?: ContentOptions) {\n this.content = content\n this.contentOptions = contentOptions\n }\n element(element: Element) {\n element.after(this.content, this.contentOptions)\n }",
"score": 0.6528890132904053
},
{
"filename": "src/htmlRewriterClasses/Replace.ts",
"retrieved_chunk": "class Replace {\n content: string\n contentOptions?: ContentOptions\n constructor(content: string, contentOptions?: ContentOptions) {\n this.content = content\n this.contentOptions = contentOptions\n }\n element(element: Element) {\n element.replace(this.content, this.contentOptions)\n }",
"score": 0.6501103639602661
},
{
"filename": "src/htmlRewriterClasses/Before.ts",
"retrieved_chunk": "class Before {\n content: string\n contentOptions?: ContentOptions\n constructor(content: string, contentOptions?: ContentOptions) {\n this.content = content\n this.contentOptions = contentOptions\n }\n element(element: Element) {\n element.before(this.content, this.contentOptions)\n }",
"score": 0.6466993093490601
}
] | 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": " * @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": 0.8809479475021362
},
{
"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": 0.865967869758606
},
{
"filename": "src/nlp/nlp-manager.ts",
"retrieved_chunk": " }\n /**\n * Load NLP manager information from a string.\n * @param {String|Object} data JSON string or object to load NLP manager information from.\n */\n import(data: string | Record<string, unknown>): void {\n const clone = typeof data === 'string' ? JSON.parse(data) : data;\n this.fromObj(clone);\n }\n /**",
"score": 0.8486395478248596
},
{
"filename": "src/recognizer/conversation-context.ts",
"retrieved_chunk": "class ConversationContext {\n private settings: object;\n /**\n * Constructor of the class.\n * @param {Object} settings Settings for the instance.\n */\n constructor(settings: object) {\n this.settings = settings || {};\n }\n /**",
"score": 0.8386363387107849
},
{
"filename": "src/nlp/nlp-manager.ts",
"retrieved_chunk": " */\n loadExcel(fileName = 'model.xls'): void {\n const reader = new NlpExcelReader(this);\n reader.load(fileName);\n }\n async testCorpus(corpus: any): Promise<any> {\n const { data } = corpus;\n const result = {\n total: 0,\n good: 0,",
"score": 0.8336272835731506
}
] | typescript | this.nlpManager.load(filename); |
/*
* 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": 0.8857698440551758
},
{
"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": 0.8744115233421326
},
{
"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": 0.8728644847869873
},
{
"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": 0.8647269010543823
},
{
"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": 0.8508402109146118
}
] | 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": 0.8827080726623535
},
{
"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": 0.8664249181747437
},
{
"filename": "src/nlp/nlp-manager.ts",
"retrieved_chunk": " }\n /**\n * Load NLP manager information from a string.\n * @param {String|Object} data JSON string or object to load NLP manager information from.\n */\n import(data: string | Record<string, unknown>): void {\n const clone = typeof data === 'string' ? JSON.parse(data) : data;\n this.fromObj(clone);\n }\n /**",
"score": 0.820533037185669
},
{
"filename": "src/nlp/nlp-manager.ts",
"retrieved_chunk": " return this.nlp.fromJSON(obj);\n }\n /**\n * Export NLP manager information as a string.\n * @param {Boolean} minified If true, the returned JSON will have no spacing or indentation.\n * @returns {String} NLP manager information as a JSON string.\n */\n export(minified = false): string {\n const clone = this.toObj();\n return minified ? JSON.stringify(clone) : JSON.stringify(clone, null, 2);",
"score": 0.8139758706092834
},
{
"filename": "src/recognizer/conversation-context.ts",
"retrieved_chunk": "class ConversationContext {\n private settings: object;\n /**\n * Constructor of the class.\n * @param {Object} settings Settings for the instance.\n */\n constructor(settings: object) {\n this.settings = settings || {};\n }\n /**",
"score": 0.8126310110092163
}
] | typescript | this.nlpManager.save(filename); |
/*
* 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": " }\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": 0.9018598794937134
},
{
"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": 0.895380973815918
},
{
"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": 0.8716956377029419
},
{
"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": 0.8685584664344788
},
{
"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": 0.86329185962677
}
] | 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/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": 0.696860671043396
},
{
"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": 0.6914286017417908
},
{
"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": 0.6802710294723511
},
{
"filename": "src/htmlRewriterClasses/After.ts",
"retrieved_chunk": "class After {\n content: string\n contentOptions?: ContentOptions\n constructor(content: string, contentOptions?: ContentOptions) {\n this.content = content\n this.contentOptions = contentOptions\n }\n element(element: Element) {\n element.after(this.content, this.contentOptions)\n }",
"score": 0.6752125024795532
},
{
"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": 0.6733402013778687
}
] | 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": 0.8388288021087646
},
{
"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": 0.7760806083679199
},
{
"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": 0.740973949432373
},
{
"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": 0.7245876789093018
},
{
"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": 0.6995694637298584
}
] | typescript | : Promise<Instructions | null> => { |
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/htmlRewriterClasses/SetStyleProperty.ts",
"retrieved_chunk": " currentStyleAttribute += `${this.propertyName}:${this.propertyValue};`\n }\n element.setAttribute('style', currentStyleAttribute)\n }\n}\nexport { SetStyleProperty }",
"score": 0.7145156860351562
},
{
"filename": "src/htmlRewriterClasses/After.ts",
"retrieved_chunk": "class After {\n content: string\n contentOptions?: ContentOptions\n constructor(content: string, contentOptions?: ContentOptions) {\n this.content = content\n this.contentOptions = contentOptions\n }\n element(element: Element) {\n element.after(this.content, this.contentOptions)\n }",
"score": 0.7044486403465271
},
{
"filename": "src/htmlRewriterClasses/Before.ts",
"retrieved_chunk": "class Before {\n content: string\n contentOptions?: ContentOptions\n constructor(content: string, contentOptions?: ContentOptions) {\n this.content = content\n this.contentOptions = contentOptions\n }\n element(element: Element) {\n element.before(this.content, this.contentOptions)\n }",
"score": 0.7010701894760132
},
{
"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": 0.7009414434432983
},
{
"filename": "src/htmlRewriterClasses/SetStyleProperty.ts",
"retrieved_chunk": "class SetStyleProperty {\n propertyName: string\n propertyValue: string\n constructor(propertyName: string, propertyValue: string) {\n this.propertyName = propertyName\n this.propertyValue = propertyValue\n }\n element(element: Element) {\n let currentStyleAttribute = element.getAttribute('style') || ''\n if (currentStyleAttribute.includes(`${this.propertyName}:`)) {",
"score": 0.6991627216339111
}
] | 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": 0.8975307941436768
},
{
"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": 0.8958179950714111
},
{
"filename": "src/components/tabs/index.tsx",
"retrieved_chunk": "}) {\n return (\n <div className=\"w-full max-w-md px-2 py-16 sm:px-0\">\n <Tab.Group>\n <Tab.List className=\"flex gap-10 rounded-xl bg-gray-900/60 p-1\">\n <Tab\n className={({ selected }) =>\n classNames(\n \"w-full rounded-lg py-2.5 text-sm font-medium leading-5 \",\n \" ring-opacity-60 ring-offset-2 ring-offset-blue-400 focus:outline-none focus:ring-2\",",
"score": 0.8943532705307007
},
{
"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": 0.8848928213119507
},
{
"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": 0.882540225982666
}
] | 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/tabs/index.tsx",
"retrieved_chunk": " </Tab>\n </Tab.List>\n <Tab.Panels className=\"mt-2 space-x-10\">\n <Tab.Panel>\n <p className=\"text-lg text-white\">{summary}</p>\n </Tab.Panel>\n <Tab.Panel>\n {transcriptions.map((transcription: any, index) => {\n return (\n <div className=\"bg-white-opacity-5 w-full p-2\" key={index}>",
"score": 0.8177903890609741
},
{
"filename": "src/pages/profile.tsx",
"retrieved_chunk": " You haven't joined any rooms yet\n </p>\n )}\n <div className=\"flex flex-row flex-wrap items-center justify-center\">\n {joinedRooms.map((room) => {\n return <Card room={room} key={room.name} />;\n })}\n </div>\n </div>\n </div>",
"score": 0.8172807693481445
},
{
"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": 0.8141839504241943
},
{
"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": 0.8137688636779785
},
{
"filename": "src/components/navbar/index.tsx",
"retrieved_chunk": " \"Sign Out\"\n ) : (\n <div className=\"flex items-center space-x-2\">\n <FcGoogle />\n <div>Sign In</div>\n </div>\n )}\n </button>\n </PopAnimation>\n <PopAnimation>",
"score": 0.8125483393669128
}
] | typescript | <Modal roomName={room.name} setIsOpen={setIsOpen} visible={isOpen} />
)} |
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/navbar/index.tsx",
"retrieved_chunk": " \"Sign Out\"\n ) : (\n <div className=\"flex items-center space-x-2\">\n <FcGoogle />\n <div>Sign In</div>\n </div>\n )}\n </button>\n </PopAnimation>\n <PopAnimation>",
"score": 0.8264128565788269
},
{
"filename": "src/pages/profile.tsx",
"retrieved_chunk": " You haven't joined any rooms yet\n </p>\n )}\n <div className=\"flex flex-row flex-wrap items-center justify-center\">\n {joinedRooms.map((room) => {\n return <Card room={room} key={room.name} />;\n })}\n </div>\n </div>\n </div>",
"score": 0.8230510354042053
},
{
"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": 0.8144330978393555
},
{
"filename": "src/components/navbar/index.tsx",
"retrieved_chunk": " ) : status === \"authenticated\" ? (\n <Image\n src={session?.user.image as string}\n width={40}\n height={40}\n className=\"cursor-pointer rounded-full transition duration-300 hover:grayscale\"\n alt=\"profile picture\"\n />\n ) : null}\n </Link>",
"score": 0.8109449148178101
},
{
"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": 0.8064058423042297
}
] | 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/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": 0.8004871606826782
},
{
"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": 0.7629610300064087
},
{
"filename": "src/server/api/trpc.ts",
"retrieved_chunk": " return next({\n ctx: {\n // infers the `session` as non-nullable\n session: { ...ctx.session, user: ctx.session.user },\n },\n });\n});\n/**\n * Protected (authenticated) procedure\n *",
"score": 0.7409753799438477
},
{
"filename": "src/server/api/routers/rooms.ts",
"retrieved_chunk": " },\n },\n {\n Participant: {\n some: {\n UserId: ctx.session.user.id,\n },\n },\n },\n ],",
"score": 0.7308764457702637
},
{
"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": 0.7305876016616821
}
] | 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/server/api/routers/pusher.ts",
"retrieved_chunk": " },\n User: {\n connect: {\n id: user.id,\n },\n },\n },\n });\n return response;\n }),",
"score": 0.8360836505889893
},
{
"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": 0.8342241048812866
},
{
"filename": "src/pages/rooms/[name].tsx",
"retrieved_chunk": " dynacast: true,\n };\n }, [userChoices, hq]);\n const [transcriptionQueue, setTranscriptionQueue] = useState<\n {\n sender: string;\n message: string;\n senderId: string;\n isFinal: boolean;\n }[]",
"score": 0.8316035270690918
},
{
"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": 0.8269600868225098
},
{
"filename": "src/components/footer/index.tsx",
"retrieved_chunk": " {\n label: \"About\",\n path: \"#about\",\n },\n {\n label: \"Contact\",\n path: \"#contact\",\n },\n ];\n return (",
"score": 0.8234211802482605
}
] | typescript | const chatLog = transcripts.map((transcript) => ({ |
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": 0.8982934951782227
},
{
"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": 0.8798788189888
},
{
"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": 0.8717703223228455
},
{
"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": 0.8702419996261597
},
{
"filename": "src/components/tabs/index.tsx",
"retrieved_chunk": "}) {\n return (\n <div className=\"w-full max-w-md px-2 py-16 sm:px-0\">\n <Tab.Group>\n <Tab.List className=\"flex gap-10 rounded-xl bg-gray-900/60 p-1\">\n <Tab\n className={({ selected }) =>\n classNames(\n \"w-full rounded-lg py-2.5 text-sm font-medium leading-5 \",\n \" ring-opacity-60 ring-offset-2 ring-offset-blue-400 focus:outline-none focus:ring-2\",",
"score": 0.8698874711990356
}
] | 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/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": 0.6826187372207642
},
{
"filename": "src/server/api/routers/rooms.ts",
"retrieved_chunk": " publicProcedure,\n protectedProcedure,\n} from \"~/server/api/trpc\";\nimport { TokenResult } from \"~/lib/type\";\nimport { CreateRoomRequest } from \"livekit-server-sdk/dist/proto/livekit_room\";\nconst roomClient = new RoomServiceClient(apiHost, apiKey, apiSecret);\nconst configuration = new Configuration({\n apiKey: process.env.OPEN_API_SECRET,\n});\nimport { Configuration, OpenAIApi } from \"openai\";",
"score": 0.662798285484314
},
{
"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": 0.6586093306541443
},
{
"filename": "src/lib/type.ts",
"retrieved_chunk": "import { LocalAudioTrack, LocalVideoTrack } from \"livekit-client\";\nexport interface SessionProps {\n roomName: string;\n identity: string;\n audioTrack?: LocalAudioTrack;\n videoTrack?: LocalVideoTrack;\n region?: string;\n turnServer?: RTCIceServer;\n forceRelay?: boolean;\n}",
"score": 0.6572233438491821
},
{
"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": 0.6531554460525513
}
] | 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": 0.9106656312942505
},
{
"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": 0.8247697949409485
},
{
"filename": "src/server/api/routers/rooms.ts",
"retrieved_chunk": " const name = ctx.session.user.name;\n const grant: VideoGrant = {\n room: input.roomName,\n roomJoin: true,\n canPublish: true,\n canPublishData: true,\n canSubscribe: true,\n };\n const { roomName } = input;\n const token = createToken({ identity, name: name as string }, grant);",
"score": 0.8188653588294983
},
{
"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": 0.8103673458099365
},
{
"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": 0.8070513010025024
}
] | 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": 0.9356405138969421
},
{
"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": 0.9068378806114197
},
{
"filename": "src/components/features/index.tsx",
"retrieved_chunk": " <stop stopColor=\"#ec4899\" offset=\"100%\" />\n </linearGradient>\n </svg>\n <div className=\"mx-auto max-w-screen-xl px-4 py-16 sm:px-6 lg:px-28\">\n <div>\n <div className=\"mx-auto max-w-lg text-center\">\n <TextAnimation\n text=\"What makes us special!\"\n textStyle=\"heading text-2xl font-bold lg:text-4xl\"\n className=\"flex justify-center\"",
"score": 0.9061727523803711
},
{
"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": 0.8954145312309265
},
{
"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": 0.8783397674560547
}
] | 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/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": 0.87356036901474
},
{
"filename": "src/components/navbar/index.tsx",
"retrieved_chunk": " src={session?.user.image as string}\n width={40}\n height={40}\n className=\"cursor-pointer rounded-full transition duration-300 hover:grayscale\"\n alt=\"profile picture\"\n />\n ) : null}\n </Link>\n </PopAnimation>\n </div>",
"score": 0.8234042525291443
},
{
"filename": "src/components/navbar/index.tsx",
"retrieved_chunk": " \"Sign Out\"\n ) : (\n <div className=\"flex items-center space-x-2\">\n <FcGoogle />\n <div>Sign In</div>\n </div>\n )}\n </button>\n </PopAnimation>\n <PopAnimation>",
"score": 0.822756290435791
},
{
"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": 0.8129988312721252
},
{
"filename": "src/components/card/index.tsx",
"retrieved_chunk": " size={15}\n />\n <div>Details</div>\n </button>\n </PopAnimation>\n {isOpen && (\n <Modal roomName={room.name} setIsOpen={setIsOpen} visible={isOpen} />\n )}\n </div>\n </div>",
"score": 0.8020544648170471
}
] | 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/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": 0.8639860153198242
},
{
"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": 0.826511025428772
},
{
"filename": "src/pages/rooms/[name].tsx",
"retrieved_chunk": " const { data, error, isLoading } = api.rooms.joinRoom.useQuery({ roomName });\n const router = useRouter();\n const { region, hq } = router.query;\n // const liveKitUrl = useServerUrl(region as string | undefined);\n const roomOptions = useMemo((): RoomOptions => {\n return {\n videoCaptureDefaults: {\n deviceId: userChoices.videoDeviceId ?? undefined,\n resolution: hq === \"true\" ? VideoPresets.h2160 : VideoPresets.h720,\n },",
"score": 0.8257323503494263
},
{
"filename": "src/pages/rooms/[name].tsx",
"retrieved_chunk": " dynacast: true,\n };\n }, [userChoices, hq]);\n const [transcriptionQueue, setTranscriptionQueue] = useState<\n {\n sender: string;\n message: string;\n senderId: string;\n isFinal: boolean;\n }[]",
"score": 0.8155527114868164
},
{
"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": 0.8136260509490967
}
] | typescript | const result: TokenResult = { |
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/card/index.tsx",
"retrieved_chunk": " size={15}\n />\n <div>Details</div>\n </button>\n </PopAnimation>\n {isOpen && (\n <Modal roomName={room.name} setIsOpen={setIsOpen} visible={isOpen} />\n )}\n </div>\n </div>",
"score": 0.7777240872383118
},
{
"filename": "src/components/navbar/index.tsx",
"retrieved_chunk": " <select className=\"lk-button\">\n <option value=\"en\">English</option>\n </select>\n </PopAnimation>\n <PopAnimation>\n <Link href=\"/profile\">\n {status === \"loading\" ? (\n <Loader />\n ) : status === \"authenticated\" ? (\n <Image",
"score": 0.7327301502227783
},
{
"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": 0.7326206564903259
},
{
"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": 0.7258074879646301
},
{
"filename": "src/components/navbar/index.tsx",
"retrieved_chunk": " {status === \"authenticated\" ? \"Sign Out\" : \"Sign In\"}\n </button>\n <select className=\"lk-button\">\n <option value=\"en\">English</option>\n </select>\n </div>\n <PopAnimation>\n <Link href=\"/profile\">\n {status === \"loading\" ? (\n <Loader />",
"score": 0.7148745059967041
}
] | typescript | <DebugMode logLevel={LogLevel.info} />
</LiveKitRoom>
)} |
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/_app.tsx",
"retrieved_chunk": " pageProps: { session, ...pageProps },\n}) => {\n return (\n <SessionProvider session={session}>\n <Head>\n <title>Jab We Meet</title>\n <link rel=\"icon\" href=\"/favicon.ico\" />\n </Head>\n <Component {...pageProps} />\n </SessionProvider>",
"score": 0.8363350629806519
},
{
"filename": "src/components/card/index.tsx",
"retrieved_chunk": " size={15}\n />\n <div>Details</div>\n </button>\n </PopAnimation>\n {isOpen && (\n <Modal roomName={room.name} setIsOpen={setIsOpen} visible={isOpen} />\n )}\n </div>\n </div>",
"score": 0.8125196695327759
},
{
"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": 0.7781813144683838
},
{
"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": 0.7662365436553955
},
{
"filename": "src/pages/index.tsx",
"retrieved_chunk": " </div>\n </div>\n </>\n );\n}\nconst Home: NextPage = () => {\n return (\n <>\n <main data-lk-theme=\"default\">\n <ConnectionTab />",
"score": 0.759717583656311
}
] | typescript | <Loader />
) : status === "authenticated" ? (
<Image
src={session?.user.image as string} |
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": " </Tab>\n </Tab.List>\n <Tab.Panels className=\"mt-2 space-x-10\">\n <Tab.Panel>\n <p className=\"text-lg text-white\">{summary}</p>\n </Tab.Panel>\n <Tab.Panel>\n {transcriptions.map((transcription: any, index) => {\n return (\n <div className=\"bg-white-opacity-5 w-full p-2\" key={index}>",
"score": 0.8157496452331543
},
{
"filename": "src/pages/profile.tsx",
"retrieved_chunk": " />\n {isLoading && <Loader className=\"flex items-center justify-center\" />}\n {ownedRooms.length === 0 && (\n <p className=\"mt-2 text-xs font-light text-white\">\n You haven't started a room yet\n </p>\n )}\n <div className=\"flex flex-row flex-wrap items-center justify-center\">\n {ownedRooms.map((room) => {\n return <Card room={room} key={room.name} />;",
"score": 0.7978423237800598
},
{
"filename": "src/components/captions/index.tsx",
"retrieved_chunk": " }, [transcriptionQueue]);\n return (\n <div className=\"closed-captions-wrapper z-50\">\n <div className=\"closed-captions-container\">\n {caption?.message ? (\n <>\n <div className=\"closed-captions-username\">{caption.sender}</div>\n <span>: </span>\n </>\n ) : null}",
"score": 0.7889636754989624
},
{
"filename": "src/components/navbar/index.tsx",
"retrieved_chunk": " <div className=\"flex items-center space-x-4 lg:hidden\">\n {isMenuOpen ? (\n <XIcon className=\"h-6 w-6 text-white\" onClick={toggleMenu} />\n ) : (\n <MenuIcon className=\"h-6 w-6 text-white\" onClick={toggleMenu} />\n )}\n </div>\n </div>\n {isMenuOpen && (\n <div className=\"flex flex-col space-y-2 p-5 text-white lg:hidden\">",
"score": 0.7764852046966553
},
{
"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": 0.7749496698379517
}
] | typescript | <Tabs
summary={data.output[0].contents[1]?.utterance} |
// @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/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": 0.8681964874267578
},
{
"filename": "src/components/navbar/index.tsx",
"retrieved_chunk": " \"Sign Out\"\n ) : (\n <div className=\"flex items-center space-x-2\">\n <FcGoogle />\n <div>Sign In</div>\n </div>\n )}\n </button>\n </PopAnimation>\n <PopAnimation>",
"score": 0.8266513347625732
},
{
"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": 0.8119537234306335
},
{
"filename": "src/components/card/index.tsx",
"retrieved_chunk": " size={15}\n />\n <div>Details</div>\n </button>\n </PopAnimation>\n {isOpen && (\n <Modal roomName={room.name} setIsOpen={setIsOpen} visible={isOpen} />\n )}\n </div>\n </div>",
"score": 0.8029016852378845
},
{
"filename": "src/components/navbar/index.tsx",
"retrieved_chunk": " src={session?.user.image as string}\n width={40}\n height={40}\n className=\"cursor-pointer rounded-full transition duration-300 hover:grayscale\"\n alt=\"profile picture\"\n />\n ) : null}\n </Link>\n </PopAnimation>\n </div>",
"score": 0.7967166304588318
}
] | 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": " </Tab>\n </Tab.List>\n <Tab.Panels className=\"mt-2 space-x-10\">\n <Tab.Panel>\n <p className=\"text-lg text-white\">{summary}</p>\n </Tab.Panel>\n <Tab.Panel>\n {transcriptions.map((transcription: any, index) => {\n return (\n <div className=\"bg-white-opacity-5 w-full p-2\" key={index}>",
"score": 0.8022899031639099
},
{
"filename": "src/pages/profile.tsx",
"retrieved_chunk": " />\n {isLoading && <Loader className=\"flex items-center justify-center\" />}\n {ownedRooms.length === 0 && (\n <p className=\"mt-2 text-xs font-light text-white\">\n You haven't started a room yet\n </p>\n )}\n <div className=\"flex flex-row flex-wrap items-center justify-center\">\n {ownedRooms.map((room) => {\n return <Card room={room} key={room.name} />;",
"score": 0.7906996011734009
},
{
"filename": "src/components/captions/index.tsx",
"retrieved_chunk": " }, [transcriptionQueue]);\n return (\n <div className=\"closed-captions-wrapper z-50\">\n <div className=\"closed-captions-container\">\n {caption?.message ? (\n <>\n <div className=\"closed-captions-username\">{caption.sender}</div>\n <span>: </span>\n </>\n ) : null}",
"score": 0.7873611450195312
},
{
"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": 0.7856723070144653
},
{
"filename": "src/components/navbar/index.tsx",
"retrieved_chunk": " <div className=\"flex items-center space-x-4 lg:hidden\">\n {isMenuOpen ? (\n <XIcon className=\"h-6 w-6 text-white\" onClick={toggleMenu} />\n ) : (\n <MenuIcon className=\"h-6 w-6 text-white\" onClick={toggleMenu} />\n )}\n </div>\n </div>\n {isMenuOpen && (\n <div className=\"flex flex-col space-y-2 p-5 text-white lg:hidden\">",
"score": 0.7678714990615845
}
] | 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/_app.tsx",
"retrieved_chunk": " pageProps: { session, ...pageProps },\n}) => {\n return (\n <SessionProvider session={session}>\n <Head>\n <title>Jab We Meet</title>\n <link rel=\"icon\" href=\"/favicon.ico\" />\n </Head>\n <Component {...pageProps} />\n </SessionProvider>",
"score": 0.829293966293335
},
{
"filename": "src/components/card/index.tsx",
"retrieved_chunk": " size={15}\n />\n <div>Details</div>\n </button>\n </PopAnimation>\n {isOpen && (\n <Modal roomName={room.name} setIsOpen={setIsOpen} visible={isOpen} />\n )}\n </div>\n </div>",
"score": 0.7923495173454285
},
{
"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": 0.7746562957763672
},
{
"filename": "src/pages/index.tsx",
"retrieved_chunk": " </div>\n </div>\n </>\n );\n}\nconst Home: NextPage = () => {\n return (\n <>\n <main data-lk-theme=\"default\">\n <ConnectionTab />",
"score": 0.7458091974258423
},
{
"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": 0.7274566888809204
}
] | typescript | Loader />
) : status === "authenticated" ? (
<Image
src={session?.user.image as string} |
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": 0.9344964027404785
},
{
"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": 0.9173287749290466
},
{
"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": 0.9093278050422668
},
{
"filename": "src/components/features/index.tsx",
"retrieved_chunk": " <stop stopColor=\"#ec4899\" offset=\"100%\" />\n </linearGradient>\n </svg>\n <div className=\"mx-auto max-w-screen-xl px-4 py-16 sm:px-6 lg:px-28\">\n <div>\n <div className=\"mx-auto max-w-lg text-center\">\n <TextAnimation\n text=\"What makes us special!\"\n textStyle=\"heading text-2xl font-bold lg:text-4xl\"\n className=\"flex justify-center\"",
"score": 0.8921617269515991
},
{
"filename": "src/components/tabs/index.tsx",
"retrieved_chunk": "}) {\n return (\n <div className=\"w-full max-w-md px-2 py-16 sm:px-0\">\n <Tab.Group>\n <Tab.List className=\"flex gap-10 rounded-xl bg-gray-900/60 p-1\">\n <Tab\n className={({ selected }) =>\n classNames(\n \"w-full rounded-lg py-2.5 text-sm font-medium leading-5 \",\n \" ring-opacity-60 ring-offset-2 ring-offset-blue-400 focus:outline-none focus:ring-2\",",
"score": 0.8883954882621765
}
] | 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": 0.8984967470169067
},
{
"filename": "src/server/api/routers/rooms.ts",
"retrieved_chunk": " const name = ctx.session.user.name;\n const grant: VideoGrant = {\n room: input.roomName,\n roomJoin: true,\n canPublish: true,\n canPublishData: true,\n canSubscribe: true,\n };\n const { roomName } = input;\n const token = createToken({ identity, name: name as string }, grant);",
"score": 0.8058549165725708
},
{
"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": 0.804958164691925
},
{
"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": 0.8010889887809753
},
{
"filename": "src/server/api/routers/rooms.ts",
"retrieved_chunk": " } catch (error) {\n console.log(error);\n }\n return result;\n }),\n createRoom: protectedProcedure.mutation(async ({ ctx }) => {\n const identity = ctx.session.user.id;\n const name = ctx.session.user.name;\n const room = await ctx.prisma.room.create({\n data: {",
"score": 0.7923250794410706
}
] | typescript | const { data, error, isLoading } = api.rooms.joinRoom.useQuery({ roomName }); |
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/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": 0.733465313911438
},
{
"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": 0.7268019914627075
},
{
"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": 0.7171052694320679
},
{
"filename": "src/dtos/login-request.dto.ts",
"retrieved_chunk": "import { ApiProperty } from '@nestjs/swagger';\nimport { IsString } from 'class-validator';\nexport class LoginRequestDto {\n @IsString()\n @ApiProperty()\n username: string;\n @IsString()\n @ApiProperty()\n password: string;\n}",
"score": 0.7075973153114319
},
{
"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": 0.6831459999084473
}
] | typescript | : 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/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": 0.7248786091804504
},
{
"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": 0.7117269039154053
},
{
"filename": "src/dtos/login-request.dto.ts",
"retrieved_chunk": "import { ApiProperty } from '@nestjs/swagger';\nimport { IsString } from 'class-validator';\nexport class LoginRequestDto {\n @IsString()\n @ApiProperty()\n username: string;\n @IsString()\n @ApiProperty()\n password: string;\n}",
"score": 0.7059271335601807
},
{
"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": 0.704369306564331
},
{
"filename": "src/guards/auth.guard.ts",
"retrieved_chunk": "import { NoneGuard } from './none.guard';\n@Injectable()\nexport class AuthGuard implements CanActivate {\n private readonly authTypeGuardMap: Record<\n AuthType,\n CanActivate | CanActivate[]\n > = {\n [AuthType.AccessToken]: this.accessTokenGuard,\n [AuthType.None]: this.noneGuard,\n };",
"score": 0.6804606914520264
}
] | typescript | @Body() request: 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": " 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": 0.8351097106933594
},
{
"filename": "src/components/footer/index.tsx",
"retrieved_chunk": " {\n label: \"About\",\n path: \"#about\",\n },\n {\n label: \"Contact\",\n path: \"#contact\",\n },\n ];\n return (",
"score": 0.8321553468704224
},
{
"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": 0.8300268650054932
},
{
"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": 0.8257635831832886
},
{
"filename": "src/pages/rooms/[name].tsx",
"retrieved_chunk": " dynacast: true,\n };\n }, [userChoices, hq]);\n const [transcriptionQueue, setTranscriptionQueue] = useState<\n {\n sender: string;\n message: string;\n senderId: string;\n isFinal: boolean;\n }[]",
"score": 0.8236157298088074
}
] | typescript | = transcripts.map((transcript) => ({ |
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": 0.8601194620132446
},
{
"filename": "src/server/api/trpc.ts",
"retrieved_chunk": " * This is the base piece you use to build new queries and mutations on your tRPC API. It does not\n * guarantee that a user querying is authorized, but you can still access user session data if they\n * are logged in.\n */\nexport const publicProcedure = t.procedure;\n/** Reusable middleware that enforces users are logged in before running the procedure. */\nconst enforceUserIsAuthed = t.middleware(({ ctx, next }) => {\n if (!ctx.session || !ctx.session.user) {\n throw new TRPCError({ code: \"UNAUTHORIZED\" });\n }",
"score": 0.8265203237533569
},
{
"filename": "src/server/api/trpc.ts",
"retrieved_chunk": " * that goes through your tRPC endpoint.\n *\n * @see https://trpc.io/docs/context\n */\nexport const createTRPCContext = async (opts: CreateNextContextOptions) => {\n const { req, res } = opts;\n // Get the session from the server using the getServerSession wrapper function\n const session = await getServerAuthSession({ req, res });\n return createInnerTRPCContext({\n session,",
"score": 0.8226531744003296
},
{
"filename": "src/server/api/trpc.ts",
"retrieved_chunk": " return next({\n ctx: {\n // infers the `session` as non-nullable\n session: { ...ctx.session, user: ctx.session.user },\n },\n });\n});\n/**\n * Protected (authenticated) procedure\n *",
"score": 0.8127047419548035
},
{
"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": 0.8111598491668701
}
] | 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/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": 0.8110356330871582
},
{
"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": 0.7690750360488892
},
{
"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": 0.7410470247268677
},
{
"filename": "src/server/api/trpc.ts",
"retrieved_chunk": " return next({\n ctx: {\n // infers the `session` as non-nullable\n session: { ...ctx.session, user: ctx.session.user },\n },\n });\n});\n/**\n * Protected (authenticated) procedure\n *",
"score": 0.7365937829017639
},
{
"filename": "src/utils/api.ts",
"retrieved_chunk": " */\n links: [\n loggerLink({\n enabled: (opts) =>\n process.env.NODE_ENV === \"development\" ||\n (opts.direction === \"down\" && opts.result instanceof Error),\n }),\n httpBatchLink({\n url: `${getBaseUrl()}/api/trpc`,\n }),",
"score": 0.7244663834571838
}
] | 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/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": 0.8699722290039062
},
{
"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": 0.8247286081314087
},
{
"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": 0.7901009321212769
},
{
"filename": "src/pages/rooms/[name].tsx",
"retrieved_chunk": " dynacast: true,\n };\n }, [userChoices, hq]);\n const [transcriptionQueue, setTranscriptionQueue] = useState<\n {\n sender: string;\n message: string;\n senderId: string;\n isFinal: boolean;\n }[]",
"score": 0.7785568237304688
},
{
"filename": "src/server/api/trpc.ts",
"retrieved_chunk": " * that goes through your tRPC endpoint.\n *\n * @see https://trpc.io/docs/context\n */\nexport const createTRPCContext = async (opts: CreateNextContextOptions) => {\n const { req, res } = opts;\n // Get the session from the server using the getServerSession wrapper function\n const session = await getServerAuthSession({ req, res });\n return createInnerTRPCContext({\n session,",
"score": 0.7727531790733337
}
] | 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": 0.7719830274581909
},
{
"filename": "src/server/api/trpc.ts",
"retrieved_chunk": " */\n/**\n * This is how you create new routers and sub-routers in your tRPC API.\n *\n * @see https://trpc.io/docs/router\n */\nexport const createTRPCRouter = t.router;\n/**\n * Public (unauthenticated) procedure\n *",
"score": 0.7698845863342285
},
{
"filename": "src/server/api/root.ts",
"retrieved_chunk": "import { createTRPCRouter } from \"~/server/api/trpc\";\nimport { roomsRouter } from \"./routers/rooms\";\nimport { pusherRouter } from \"./routers/pusher\";\n/**\n * This is the primary router for your server.\n *\n * All routers added in /api/routers should be manually added here.\n */\nexport const appRouter = createTRPCRouter({\n rooms: roomsRouter,",
"score": 0.7546259164810181
},
{
"filename": "src/server/auth.ts",
"retrieved_chunk": " ],\n};\n/**\n * Wrapper for `getServerSession` so that you don't need to import the `authOptions` in every file.\n *\n * @see https://next-auth.js.org/configuration/nextjs\n */\nexport const getServerAuthSession = (ctx: {\n req: GetServerSidePropsContext[\"req\"];\n res: GetServerSidePropsContext[\"res\"];",
"score": 0.7498059272766113
},
{
"filename": "src/server/api/trpc.ts",
"retrieved_chunk": " transformer: superjson,\n errorFormatter({ shape }) {\n return shape;\n },\n});\n/**\n * 3. ROUTER & PROCEDURE (THE IMPORTANT BIT)\n *\n * These are the pieces you use to build your tRPC API. You should import these a lot in the\n * \"/src/server/api/routers\" directory.",
"score": 0.7362639904022217
}
] | typescript | = inferRouterInputs<AppRouter>; |
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/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": 0.8004871606826782
},
{
"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": 0.7629610300064087
},
{
"filename": "src/server/api/trpc.ts",
"retrieved_chunk": " return next({\n ctx: {\n // infers the `session` as non-nullable\n session: { ...ctx.session, user: ctx.session.user },\n },\n });\n});\n/**\n * Protected (authenticated) procedure\n *",
"score": 0.7409753799438477
},
{
"filename": "src/server/api/routers/rooms.ts",
"retrieved_chunk": " },\n },\n {\n Participant: {\n some: {\n UserId: ctx.session.user.id,\n },\n },\n },\n ],",
"score": 0.7308764457702637
},
{
"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": 0.7305876016616821
}
] | 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/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": 0.819415271282196
},
{
"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": 0.8144526481628418
},
{
"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": 0.8081740140914917
},
{
"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": 0.8068077564239502
},
{
"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": 0.8066973686218262
}
] | 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": 0.7940908670425415
},
{
"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": 0.7869376540184021
},
{
"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": 0.7819478511810303
},
{
"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": 0.7682976722717285
},
{
"filename": "src/decorators/active-user.decorator.ts",
"retrieved_chunk": "import { createParamDecorator, ExecutionContext } from '@nestjs/common';\nimport { IAM_REQUEST_USER_KEY } from '../constants/iam.constants';\nimport { IActiveUser } from '../interfaces/active-user.interface';\nexport const ActiveUser = createParamDecorator(\n (field: keyof IActiveUser | undefined, ctx: ExecutionContext) => {\n const request = ctx.switchToHttp().getRequest();\n const user: IActiveUser | undefined = request[IAM_REQUEST_USER_KEY];\n return field ? user?.[field] : user;\n },\n);",
"score": 0.7679582834243774
}
] | typescript | publish(new LoggedOutEvent(activeUser.userId)); |
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": 0.7440282106399536
},
{
"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": 0.7329921722412109
},
{
"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": 0.7015557289123535
},
{
"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": 0.700529158115387
},
{
"filename": "src/guards/auth.guard.ts",
"retrieved_chunk": " constructor(\n private readonly reflector: Reflector,\n private readonly accessTokenGuard: AccessTokenGuard,\n private readonly noneGuard: NoneGuard,\n ) {}\n async canActivate(context: ExecutionContext): Promise<boolean> {\n const authTypes = this.reflector.getAllAndOverride<AuthType[]>(\n IAM_AUTH_TYPE_KEY,\n [context.getHandler(), context.getClass()],\n ) ?? [AuthType.AccessToken];",
"score": 0.6984876990318298
}
] | typescript | IActiveUser,
) { |
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/guards/auth.guard.ts",
"retrieved_chunk": "import { NoneGuard } from './none.guard';\n@Injectable()\nexport class AuthGuard implements CanActivate {\n private readonly authTypeGuardMap: Record<\n AuthType,\n CanActivate | CanActivate[]\n > = {\n [AuthType.AccessToken]: this.accessTokenGuard,\n [AuthType.None]: this.noneGuard,\n };",
"score": 0.8071869611740112
},
{
"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": 0.7998158931732178
},
{
"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": 0.7937905788421631
},
{
"filename": "src/controllers/auth.controller.ts",
"retrieved_chunk": " private readonly passwordlessLoginRequestProcessor: PasswordlessLoginRequestProcessor,\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 @HttpCode(HttpStatus.OK)\n @ApiOperation({ operationId: 'authLogin' })\n @ApiOkResponse({ type: LoginResponseDto })",
"score": 0.7908077836036682
},
{
"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": 0.7889218926429749
}
] | 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/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": 0.7081036567687988
},
{
"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": 0.6973203420639038
},
{
"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": 0.6907708048820496
},
{
"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": 0.6893554925918579
},
{
"filename": "src/dtos/login-request.dto.ts",
"retrieved_chunk": "import { ApiProperty } from '@nestjs/swagger';\nimport { IsString } from 'class-validator';\nexport class LoginRequestDto {\n @IsString()\n @ApiProperty()\n username: string;\n @IsString()\n @ApiProperty()\n password: string;\n}",
"score": 0.6861599087715149
}
] | 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/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": 0.8324941396713257
},
{
"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": 0.8082871437072754
},
{
"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": 0.7959343194961548
},
{
"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": 0.7855637073516846
},
{
"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": 0.7657232284545898
}
] | typescript | this.eventBus.publish(new LoggedInEvent(user.getId())); |
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/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": 0.6981338262557983
},
{
"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": 0.6873278617858887
},
{
"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": 0.6812492609024048
},
{
"filename": "src/dtos/login-request.dto.ts",
"retrieved_chunk": "import { ApiProperty } from '@nestjs/swagger';\nimport { IsString } from 'class-validator';\nexport class LoginRequestDto {\n @IsString()\n @ApiProperty()\n username: string;\n @IsString()\n @ApiProperty()\n password: string;\n}",
"score": 0.6791853308677673
},
{
"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": 0.6762150526046753
}
] | 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/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": 0.7235461473464966
},
{
"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": 0.7185976505279541
},
{
"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": 0.7007269859313965
},
{
"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": 0.6879581212997437
},
{
"filename": "src/guards/auth.guard.ts",
"retrieved_chunk": "import { NoneGuard } from './none.guard';\n@Injectable()\nexport class AuthGuard implements CanActivate {\n private readonly authTypeGuardMap: Record<\n AuthType,\n CanActivate | CanActivate[]\n > = {\n [AuthType.AccessToken]: this.accessTokenGuard,\n [AuthType.None]: this.noneGuard,\n };",
"score": 0.6796934008598328
}
] | 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/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": 0.715325117111206
},
{
"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": 0.7084989547729492
},
{
"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": 0.6895909309387207
},
{
"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": 0.6835485696792603
},
{
"filename": "src/guards/auth.guard.ts",
"retrieved_chunk": " constructor(\n private readonly reflector: Reflector,\n private readonly accessTokenGuard: AccessTokenGuard,\n private readonly noneGuard: NoneGuard,\n ) {}\n async canActivate(context: ExecutionContext): Promise<boolean> {\n const authTypes = this.reflector.getAllAndOverride<AuthType[]>(\n IAM_AUTH_TYPE_KEY,\n [context.getHandler(), context.getClass()],\n ) ?? [AuthType.AccessToken];",
"score": 0.6708585023880005
}
] | 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": 0.9425556063652039
},
{
"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": 0.9372057318687439
},
{
"filename": "src/strategy/cacheFirst.ts",
"retrieved_chunk": " if (response) {\n for (const plugin of this.plugins) {\n if (plugin.fetchDidSucceed) {\n response = await plugin.fetchDidSucceed({ request: req, response });\n }\n }\n return response;\n }\n return null;\n }",
"score": 0.9069377183914185
},
{
"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": 0.9058874845504761
},
{
"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": 0.8848233819007874
}
] | 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/cacheFirst.ts",
"retrieved_chunk": " request,\n cachedResponse,\n matchOptions: this.matchOptions || {}\n });\n if (!res) {\n break;\n }\n }\n }\n return res;",
"score": 0.8385632038116455
},
{
"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": 0.8320189714431763
},
{
"filename": "src/strategy/networkFirst.ts",
"retrieved_chunk": " });\n }\n });\n let response = timeoutPromise\n ? await Promise.race([fetchPromise, timeoutPromise])\n : await fetchPromise;\n // If the fetch was successful, then proceed along else throw an error\n if (response) {\n // `fetchDidSucceed` performs some changes to response so store it elsewhere\n // to avoid overtyping original variable",
"score": 0.8193860054016113
},
{
"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": 0.8186092376708984
},
{
"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": 0.8144680261611938
}
] | 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": " }\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": 0.9316524863243103
},
{
"filename": "src/strategy/cacheFirst.ts",
"retrieved_chunk": " if (response) {\n for (const plugin of this.plugins) {\n if (plugin.fetchDidSucceed) {\n response = await plugin.fetchDidSucceed({ request: req, response });\n }\n }\n return response;\n }\n return null;\n }",
"score": 0.9061439633369446
},
{
"filename": "src/strategy/networkOnly.ts",
"retrieved_chunk": " throw new Error('Network request failed');\n } catch (error) {\n for (const plugin of this.plugins) {\n if (plugin.fetchDidFail) {\n await plugin.fetchDidFail({\n request,\n error: toError(error)\n });\n }\n }",
"score": 0.8967226147651672
},
{
"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": 0.8938808441162109
},
{
"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": 0.8792804479598999
}
] | 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": " 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": 0.8662625551223755
},
{
"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": 0.8429092168807983
},
{
"filename": "src/message/precacheHandler.ts",
"retrieved_chunk": " }\n async function cacheAsset(assetUrl: string) {\n if (await assetCache.match(assetUrl)) {\n return;\n }\n logger.debug(\"Caching asset:\", assetUrl);\n return assetCache.add(assetUrl).catch((error) => {\n if (error instanceof TypeError) {\n logger.error(`TypeError when caching asset ${assetUrl}:`, error.message);\n } else if (error instanceof DOMException) {",
"score": 0.835585355758667
},
{
"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": 0.8180726170539856
},
{
"filename": "src/strategy/cacheOnly.ts",
"retrieved_chunk": " modifiedResponse = await plugin.cachedResponseWillBeUsed({\n cacheName: this.cacheName,\n matchOptions: this.matchOptions || {},\n request,\n cachedResponse: response.clone()\n });\n }\n }\n if (!modifiedResponse) {\n // throw new Error(`Unable to find response in cache.`);",
"score": 0.812935471534729
}
] | 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": 0.9086870551109314
},
{
"filename": "src/strategy/strategy.ts",
"retrieved_chunk": " this.isLoader = isLoader;\n this.plugins = plugins;\n this.matchOptions = matchOptions;\n }\n protected abstract _handle(request: Request): Promise<Response>;\n // Can you return null or a custom, handled error???\n async handle(request: Request): Promise<Response> {\n if (!isHttpRequest(request)) {\n // (ShafSpecs) todo: Handle this better. Can't be throwing errors\n // all over the user app if the SW intercepts an extension request",
"score": 0.8823914527893066
},
{
"filename": "src/plugins/interfaces/strategyPlugin.ts",
"retrieved_chunk": " // Can be used to modify the response, for example.\n /**\n * Called whenever a network request succeeds, regardless of the HTTP response code.\n */\n fetchDidSucceed?: (options: {\n request: Request;\n response: Response;\n event?: ExtendableEvent;\n }) => Promise<Response>;\n // Called when a request fails to be fetched and stored in the cache.",
"score": 0.8729785680770874
},
{
"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": 0.8674122095108032
},
{
"filename": "src/plugins/interfaces/strategyPlugin.ts",
"retrieved_chunk": " * response. At this point in time, you could either return a different response, or return null (fetch from server at all costs?).\n */\n cachedResponseWillBeUsed?: (options: {\n cacheName: string;\n request: Request;\n matchOptions: CacheQueryMatchOptions;\n cachedResponse: Response;\n event?: ExtendableEvent;\n }) => Promise<Response | null>;\n // Called after a fetch request is made and a response is received from the network, but before it's returned to the application.",
"score": 0.8668919205665588
}
] | typescript | async runPlugins(hook: keyof MessagePlugin, env: MessageEnv) { |
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/guards/auth.guard.ts",
"retrieved_chunk": "import { NoneGuard } from './none.guard';\n@Injectable()\nexport class AuthGuard implements CanActivate {\n private readonly authTypeGuardMap: Record<\n AuthType,\n CanActivate | CanActivate[]\n > = {\n [AuthType.AccessToken]: this.accessTokenGuard,\n [AuthType.None]: this.noneGuard,\n };",
"score": 0.8210618495941162
},
{
"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": 0.8171539306640625
},
{
"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": 0.8074569702148438
},
{
"filename": "src/guards/auth.guard.ts",
"retrieved_chunk": " constructor(\n private readonly reflector: Reflector,\n private readonly accessTokenGuard: AccessTokenGuard,\n private readonly noneGuard: NoneGuard,\n ) {}\n async canActivate(context: ExecutionContext): Promise<boolean> {\n const authTypes = this.reflector.getAllAndOverride<AuthType[]>(\n IAM_AUTH_TYPE_KEY,\n [context.getHandler(), context.getClass()],\n ) ?? [AuthType.AccessToken];",
"score": 0.793183445930481
},
{
"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": 0.7924001216888428
}
] | 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/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": 0.8495393395423889
},
{
"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": 0.8370551466941833
},
{
"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": 0.8334521055221558
},
{
"filename": "src/strategy/cacheOnly.ts",
"retrieved_chunk": "import { CacheStrategy } from './strategy.js';\n// todo: Should include a way to cache everything at once when the service worker gets loaded\nexport class CacheOnly extends CacheStrategy {\n override async _handle(request: Request) {\n const cache = await caches.open(this.cacheName);\n let response = await cache.match(request, {\n ignoreSearch: this.matchOptions?.ignoreSearch ?? false,\n ignoreVary: this.matchOptions?.ignoreVary ?? false\n });\n if (!response) {",
"score": 0.8295730352401733
},
{
"filename": "src/strategy/cacheFirst.ts",
"retrieved_chunk": " response: newResponse.clone(),\n request\n });\n if (!newResponse) {\n break;\n }\n }\n }\n if (newResponse) {\n await cache.put(request, newResponse.clone());",
"score": 0.8215054869651794
}
] | typescript | logger.debug("Cache is full, removing oldest entry"); |
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": 0.8833295106887817
},
{
"filename": "src/message/precacheHandler.ts",
"retrieved_chunk": " logger.log(\"Precaching route:\", route.id);\n cacheRoute(route);\n }\n await Promise.all(cachePromises.values());\n function cacheRoute(route: EntryRoute) {\n const pathname = getPathname(route);\n if (route.hasLoader) {\n cacheLoaderData(route);\n }\n if (route.module) {",
"score": 0.7795447111129761
},
{
"filename": "src/message/precacheHandler.ts",
"retrieved_chunk": " logger.error(`DOMException when caching asset ${assetUrl}:`, error.message);\n } else {\n logger.error(`Failed to cache asset ${assetUrl}:`, error);\n }\n });\n }\n function getPathname(route: EntryRoute) {\n if (route.index && route.parentId === \"root\") return \"/\";\n let pathname = \"\";\n if (route.path && route.path.length > 0) {",
"score": 0.7605016231536865
},
{
"filename": "src/message/precacheHandler.ts",
"retrieved_chunk": " pathname = \"/\" + route.path;\n }\n if (route.parentId) {\n const parentPath = getPathname(manifest.routes[route.parentId]);\n if (parentPath) {\n pathname = parentPath + pathname;\n }\n }\n return pathname;\n }",
"score": 0.7513666749000549
},
{
"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": 0.7428330183029175
}
] | typescript | debug('Caching data for:', url); |
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": 0.9003055095672607
},
{
"filename": "src/strategy/strategy.ts",
"retrieved_chunk": " this.isLoader = isLoader;\n this.plugins = plugins;\n this.matchOptions = matchOptions;\n }\n protected abstract _handle(request: Request): Promise<Response>;\n // Can you return null or a custom, handled error???\n async handle(request: Request): Promise<Response> {\n if (!isHttpRequest(request)) {\n // (ShafSpecs) todo: Handle this better. Can't be throwing errors\n // all over the user app if the SW intercepts an extension request",
"score": 0.8801715970039368
},
{
"filename": "src/plugins/interfaces/strategyPlugin.ts",
"retrieved_chunk": " // Can be used to modify the response, for example.\n /**\n * Called whenever a network request succeeds, regardless of the HTTP response code.\n */\n fetchDidSucceed?: (options: {\n request: Request;\n response: Response;\n event?: ExtendableEvent;\n }) => Promise<Response>;\n // Called when a request fails to be fetched and stored in the cache.",
"score": 0.8656269907951355
},
{
"filename": "src/plugins/interfaces/strategyPlugin.ts",
"retrieved_chunk": " * response. At this point in time, you could either return a different response, or return null (fetch from server at all costs?).\n */\n cachedResponseWillBeUsed?: (options: {\n cacheName: string;\n request: Request;\n matchOptions: CacheQueryMatchOptions;\n cachedResponse: Response;\n event?: ExtendableEvent;\n }) => Promise<Response | null>;\n // Called after a fetch request is made and a response is received from the network, but before it's returned to the application.",
"score": 0.8591592311859131
},
{
"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": 0.85890132188797
}
] | typescript | hook: keyof MessagePlugin, env: MessageEnv) { |
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/guards/auth.guard.ts",
"retrieved_chunk": "import { NoneGuard } from './none.guard';\n@Injectable()\nexport class AuthGuard implements CanActivate {\n private readonly authTypeGuardMap: Record<\n AuthType,\n CanActivate | CanActivate[]\n > = {\n [AuthType.AccessToken]: this.accessTokenGuard,\n [AuthType.None]: this.noneGuard,\n };",
"score": 0.8071463108062744
},
{
"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": 0.8013502955436707
},
{
"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": 0.7963464856147766
},
{
"filename": "src/controllers/auth.controller.ts",
"retrieved_chunk": " private readonly passwordlessLoginRequestProcessor: PasswordlessLoginRequestProcessor,\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 @HttpCode(HttpStatus.OK)\n @ApiOperation({ operationId: 'authLogin' })\n @ApiOkResponse({ type: LoginResponseDto })",
"score": 0.7907386422157288
},
{
"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": 0.7877407670021057
}
] | typescript | ConfigurableModuleClass {} |
|
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": 0.9381151795387268
},
{
"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": 0.9315247535705566
},
{
"filename": "src/strategy/cacheFirst.ts",
"retrieved_chunk": " if (response) {\n for (const plugin of this.plugins) {\n if (plugin.fetchDidSucceed) {\n response = await plugin.fetchDidSucceed({ request: req, response });\n }\n }\n return response;\n }\n return null;\n }",
"score": 0.9068349599838257
},
{
"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": 0.9060211777687073
},
{
"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": 0.8902443647384644
}
] | 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/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": 0.8520821928977966
},
{
"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": 0.8224928379058838
},
{
"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": 0.8129382133483887
},
{
"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": 0.8101959228515625
},
{
"filename": "src/generators/access-token.generator.ts",
"retrieved_chunk": " private readonly jwtService: JwtService,\n @Inject(iamConfig.KEY)\n private readonly config: ConfigType<typeof iamConfig>,\n ) {}\n async generate(user: IUser): Promise<IAccessToken> {\n const ttl = this.config.jwt.accessTokenTtl;\n const expiresAt = new Date();\n expiresAt.setSeconds(expiresAt.getSeconds() + ttl);\n return {\n jwt: await this.jwtService.signAsync(",
"score": 0.8031575679779053
}
] | typescript | if (!(await this.hasher.compare(request.password, user.getPassword()))) { |
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": 0.7392996549606323
},
{
"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": 0.7372799515724182
},
{
"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": 0.7230288982391357
},
{
"filename": "src/guards/auth.guard.ts",
"retrieved_chunk": " constructor(\n private readonly reflector: Reflector,\n private readonly accessTokenGuard: AccessTokenGuard,\n private readonly noneGuard: NoneGuard,\n ) {}\n async canActivate(context: ExecutionContext): Promise<boolean> {\n const authTypes = this.reflector.getAllAndOverride<AuthType[]>(\n IAM_AUTH_TYPE_KEY,\n [context.getHandler(), context.getClass()],\n ) ?? [AuthType.AccessToken];",
"score": 0.7021133899688721
},
{
"filename": "src/generators/access-token.generator.ts",
"retrieved_chunk": " private readonly jwtService: JwtService,\n @Inject(iamConfig.KEY)\n private readonly config: ConfigType<typeof iamConfig>,\n ) {}\n async generate(user: IUser): Promise<IAccessToken> {\n const ttl = this.config.jwt.accessTokenTtl;\n const expiresAt = new Date();\n expiresAt.setSeconds(expiresAt.getSeconds() + ttl);\n return {\n jwt: await this.jwtService.signAsync(",
"score": 0.6958401203155518
}
] | 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/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": 0.8561785221099854
},
{
"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": 0.8139716386795044
},
{
"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": 0.8003257513046265
},
{
"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": 0.7926603555679321
},
{
"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": 0.79096919298172
}
] | 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/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": 0.805797278881073
},
{
"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": 0.8054607510566711
},
{
"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": 0.7942965030670166
},
{
"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": 0.7872046232223511
},
{
"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": 0.7865850925445557
}
] | typescript | const requestId = request.cookies[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/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": 0.9410432577133179
},
{
"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": 0.9045430421829224
},
{
"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": 0.8833003640174866
},
{
"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": 0.8528231382369995
},
{
"filename": "src/processors/login.processor.ts",
"retrieved_chunk": " new TokenModel(\n refreshToken.id,\n TokenType.RefreshToken,\n user.getId(),\n refreshToken.expiresAt,\n ),\n );\n response.cookie(TokenType.AccessToken, accessToken.jwt, {\n secure: this.config.cookie.secure,\n httpOnly: this.config.cookie.httpOnly,",
"score": 0.8262035846710205
}
] | 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/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": 0.7822277545928955
},
{
"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": 0.7809123992919922
},
{
"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": 0.7668148875236511
},
{
"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": 0.7665731906890869
},
{
"filename": "src/decorators/active-user.decorator.ts",
"retrieved_chunk": "import { createParamDecorator, ExecutionContext } from '@nestjs/common';\nimport { IAM_REQUEST_USER_KEY } from '../constants/iam.constants';\nimport { IActiveUser } from '../interfaces/active-user.interface';\nexport const ActiveUser = createParamDecorator(\n (field: keyof IActiveUser | undefined, ctx: ExecutionContext) => {\n const request = ctx.switchToHttp().getRequest();\n const user: IActiveUser | undefined = request[IAM_REQUEST_USER_KEY];\n return field ? user?.[field] : user;\n },\n);",
"score": 0.762117862701416
}
] | typescript | this.eventBus.publish(new LoggedOutEvent(activeUser.userId)); |
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": 0.8427639603614807
},
{
"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": 0.8201218843460083
},
{
"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": 0.8183279037475586
},
{
"filename": "src/guards/auth.guard.ts",
"retrieved_chunk": " constructor(\n private readonly reflector: Reflector,\n private readonly accessTokenGuard: AccessTokenGuard,\n private readonly noneGuard: NoneGuard,\n ) {}\n async canActivate(context: ExecutionContext): Promise<boolean> {\n const authTypes = this.reflector.getAllAndOverride<AuthType[]>(\n IAM_AUTH_TYPE_KEY,\n [context.getHandler(), context.getClass()],\n ) ?? [AuthType.AccessToken];",
"score": 0.8154314160346985
},
{
"filename": "src/guards/roles.guard.ts",
"retrieved_chunk": " constructor(private readonly reflector: Reflector) {}\n canActivate(\n context: ExecutionContext,\n ): boolean | Promise<boolean> | Observable<boolean> {\n const roles = this.reflector.getAllAndOverride<string[]>(IAM_ROLES_KEY, [\n context.getHandler(),\n context.getClass(),\n ]);\n if (!roles) {\n return true;",
"score": 0.8114479780197144
}
] | typescript | const user = await this.moduleOptions.authService.checkUser(
request.username,
); |
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/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": 0.7138004899024963
},
{
"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": 0.6747899651527405
},
{
"filename": "src/generate.ts",
"retrieved_chunk": " types.push('// Enums');\n }\n for (const enumProperty of enumsProperties) {\n const enumName = enumProperty.getName();\n const enumNameType = toPascalCase(enumName, makeSingular);\n types.push(\n `export enum ${enumNameType} {`,\n ...(getEnumValuesText(enumProperty) ?? []),\n '}',\n '\\n'",
"score": 0.6739554405212402
},
{
"filename": "src/generate.ts",
"retrieved_chunk": " );\n }\n if (tablesProperties.length > 0) {\n types.push('// Tables');\n }\n for (const table of tablesProperties) {\n const tableName = table.getName();\n const tableNameType = toPascalCase(tableName, makeSingular);\n types.push(\n `export type ${tableNameType} = Database['${schemaName}']['Tables']['${tableName}']['Row'];`,",
"score": 0.589290976524353
},
{
"filename": "src/utils/getFunctionProperties.ts",
"retrieved_chunk": " const functionProperty = publicType\n .getApparentProperties()\n .find((property) => property.getName() === 'Functions');\n if (!functionProperty) {\n console.log(\n `${chalk.yellow.bold(\n 'warn'\n )} No Functions property found within the Database interface for schema ${schema}.`\n );\n return [];",
"score": 0.5797442197799683
}
] | typescript | toCamelCase(enumValue, '.'); |
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/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": 0.7141101360321045
},
{
"filename": "src/generate.ts",
"retrieved_chunk": " types.push('// Enums');\n }\n for (const enumProperty of enumsProperties) {\n const enumName = enumProperty.getName();\n const enumNameType = toPascalCase(enumName, makeSingular);\n types.push(\n `export enum ${enumNameType} {`,\n ...(getEnumValuesText(enumProperty) ?? []),\n '}',\n '\\n'",
"score": 0.6745355129241943
},
{
"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": 0.6697861552238464
},
{
"filename": "src/generate.ts",
"retrieved_chunk": " );\n }\n if (tablesProperties.length > 0) {\n types.push('// Tables');\n }\n for (const table of tablesProperties) {\n const tableName = table.getName();\n const tableNameType = toPascalCase(tableName, makeSingular);\n types.push(\n `export type ${tableNameType} = Database['${schemaName}']['Tables']['${tableName}']['Row'];`,",
"score": 0.5877408981323242
},
{
"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": 0.5801740884780884
}
] | 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": 0.9747441411018372
},
{
"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": 0.9616690874099731
},
{
"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": 0.8953198194503784
},
{
"filename": "src/store/StoreBase.ts",
"retrieved_chunk": " init = (initState) => {\n 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 };",
"score": 0.8789698481559753
},
{
"filename": "src/useSelector.ts",
"retrieved_chunk": " useLayoutEffect(() => {\n const subscribe = store.subscribe(() => {\n const newState = selector(store.getState() as unknown as S);\n if (latestState.current === newState) {\n return;\n }\n latestState.current = newState;\n forceRender();\n });\n return () => {",
"score": 0.864992618560791
}
] | 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/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": 0.8326230645179749
},
{
"filename": "src/rules/signal.ts",
"retrieved_chunk": " super(async context => operator(await first.evaluate(context), second));\n }\n encode(signals: SignalSet<TContext>): EncodedSignalRule {\n return {\n [getSignalKey(this.first, signals)]: {\n [getOperatorKey(this.operator)]:\n this.second instanceof Rule\n ? this.second.encode(signals)\n : this.second instanceof RegExp\n ? this.second.toString()",
"score": 0.825311541557312
},
{
"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": 0.8173902034759521
},
{
"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": 0.8156986236572266
},
{
"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": 0.8030693531036377
}
] | typescript | const arraySignal = signal as Signal<TContext, Array<unknown>>; |
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/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": 0.8014448881149292
},
{
"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": 0.7879987955093384
},
{
"filename": "src/rules/signal.ts",
"retrieved_chunk": " super(async context => operator(await first.evaluate(context), second));\n }\n encode(signals: SignalSet<TContext>): EncodedSignalRule {\n return {\n [getSignalKey(this.first, signals)]: {\n [getOperatorKey(this.operator)]:\n this.second instanceof Rule\n ? this.second.encode(signals)\n : this.second instanceof RegExp\n ? this.second.toString()",
"score": 0.7820905447006226
},
{
"filename": "src/rules/parse.ts",
"retrieved_chunk": " throw new Error('Expected an operator key, got: ' + data);\n }\n}\nexport default async function parse<TContext>(\n data: unknown,\n signals: SignalSet<TContext>,\n): Promise<Rule<TContext>> {\n assertObjectWithSingleKey(data);\n const key = Object.keys(data)[0];\n const value = data[key];",
"score": 0.7743628621101379
},
{
"filename": "src/rules/parse.ts",
"retrieved_chunk": " switch (key) {\n case '$and':\n case '$or':\n return new GroupRule<TContext>(\n operator[key],\n await Promise.all(\n assertArray(value).map(element => parse(element, signals)),\n ),\n );\n case '$not':",
"score": 0.773182213306427
}
] | typescript | InverseRule(value.bind(target)(...args))
: value; |
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__/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": 0.7306333184242249
},
{
"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": 0.7278414368629456
},
{
"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": 0.6924760341644287
},
{
"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": 0.692156195640564
},
{
"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": 0.6907505393028259
}
] | typescript | status: signal.type(z.string()).value<Context>(({status}) => status),
}; |
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": "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": 0.8364992141723633
},
{
"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": 0.8251712322235107
},
{
"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": 0.8188562989234924
},
{
"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": 0.81243497133255
},
{
"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": 0.8114572763442993
}
] | typescript | return new InverseRule(await parse(value, signals)); |
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": " 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": 0.8546586632728577
},
{
"filename": "src/rules/group.ts",
"retrieved_chunk": " context: Array<TContext>,\n rules: Array<Rule<TContext>>,\n ) => Promise<boolean>,\n protected rules: Array<Rule<TContext>>,\n ) {\n super(context => operator([context], rules));\n }\n encode(signals: SignalSet<TContext>): EncodedGroupRule<TContext> {\n return {\n [getOperatorKey(this.operator)]: this.rules.map(rule =>",
"score": 0.8499757051467896
},
{
"filename": "src/rules/parse.ts",
"retrieved_chunk": " switch (key) {\n case '$and':\n case '$or':\n return new GroupRule<TContext>(\n operator[key],\n await Promise.all(\n assertArray(value).map(element => parse(element, signals)),\n ),\n );\n case '$not':",
"score": 0.8409512042999268
},
{
"filename": "src/rules/signal.ts",
"retrieved_chunk": " TSecond,\n> extends Rule<TContext> {\n constructor(\n protected operator: (\n first: TFirst,\n second: TSecond,\n ) => boolean | Promise<boolean>,\n protected first: Signal<TContext, TFirst>,\n protected second: TSecond,\n ) {",
"score": 0.8340094089508057
},
{
"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": 0.8339763879776001
}
] | typescript | SignalRule(operator.$eq, signal, value),
in: values => new SignalRule(operator.$in, signal, values),
}; |
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": 0.8544607758522034
},
{
"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": 0.8073974251747131
},
{
"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": 0.7977123260498047
},
{
"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": 0.778962254524231
},
{
"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": 0.7671422362327576
}
] | 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/rules/group.ts",
"retrieved_chunk": " context: Array<TContext>,\n rules: Array<Rule<TContext>>,\n ) => Promise<boolean>,\n protected rules: Array<Rule<TContext>>,\n ) {\n super(context => operator([context], rules));\n }\n encode(signals: SignalSet<TContext>): EncodedGroupRule<TContext> {\n return {\n [getOperatorKey(this.operator)]: this.rules.map(rule =>",
"score": 0.8549233675003052
},
{
"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": 0.8544107675552368
},
{
"filename": "src/rules/parse.ts",
"retrieved_chunk": " switch (key) {\n case '$and':\n case '$or':\n return new GroupRule<TContext>(\n operator[key],\n await Promise.all(\n assertArray(value).map(element => parse(element, signals)),\n ),\n );\n case '$not':",
"score": 0.8373613357543945
},
{
"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": 0.835657000541687
},
{
"filename": "src/rules/signal.ts",
"retrieved_chunk": " TSecond,\n> extends Rule<TContext> {\n constructor(\n protected operator: (\n first: TFirst,\n second: TSecond,\n ) => boolean | Promise<boolean>,\n protected first: Signal<TContext, TFirst>,\n protected second: TSecond,\n ) {",
"score": 0.828689694404602
}
] | 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": " 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": 0.8391398191452026
},
{
"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": 0.8312380909919739
},
{
"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": 0.8310854434967041
},
{
"filename": "src/rules/parse.ts",
"retrieved_chunk": " switch (key) {\n case '$and':\n case '$or':\n return new GroupRule<TContext>(\n operator[key],\n await Promise.all(\n assertArray(value).map(element => parse(element, signals)),\n ),\n );\n case '$not':",
"score": 0.8275781869888306
},
{
"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": 0.8208372592926025
}
] | typescript | (operator.$pfx, stringSignal, 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/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": 0.8429531455039978
},
{
"filename": "src/rules/parse.ts",
"retrieved_chunk": " switch (key) {\n case '$and':\n case '$or':\n return new GroupRule<TContext>(\n operator[key],\n await Promise.all(\n assertArray(value).map(element => parse(element, signals)),\n ),\n );\n case '$not':",
"score": 0.8399813771247864
},
{
"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": 0.8304656147956848
},
{
"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": 0.8135989904403687
},
{
"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": 0.8022036552429199
}
] | 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": " 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": 0.842086911201477
},
{
"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": 0.818661630153656
},
{
"filename": "src/core/operators.ts",
"retrieved_chunk": " return first.includes(second);\n },\n $lt<T extends number>(first: T, second: T): boolean {\n return first < second;\n },\n $lte<T extends number>(first: T, second: T): boolean {\n return first <= second;\n },\n $not<T extends boolean>(value: T): boolean {\n return !value;",
"score": 0.7913609147071838
},
{
"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": 0.7842206358909607
},
{
"filename": "src/rules/parse.ts",
"retrieved_chunk": " switch (key) {\n case '$and':\n case '$or':\n return new GroupRule<TContext>(\n operator[key],\n await Promise.all(\n assertArray(value).map(element => parse(element, signals)),\n ),\n );\n case '$not':",
"score": 0.7744571566581726
}
] | typescript | .$lte, numberSignal, 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/runner/expect.ts",
"retrieved_chunk": " return jobError(runner, test, `Expected stdout not match with run stdout`);\n }\n if (!compareStderr(run.stderr.toString(), test)) {\n return jobError(runner, test, `Expected stderr not match with run stderr`);\n }\n runner.numberSuccess++;\n if (runner.settings.outputFormat === 'text')\n console.log(`OK`);\n}\nexport default runExpect;",
"score": 0.8351882100105286
},
{
"filename": "src/runTests.ts",
"retrieved_chunk": " stdout: undefined,\n stderr: undefined,\n exitCode: undefined\n },\n timeTaken: undefined\n };\n }\n }\n for (const test of runner.tests) {\n if (runner.settings.runList.includes(test.id) || runner.settings.runList.length === 0) {",
"score": 0.8137537240982056
},
{
"filename": "src/runner/expect.ts",
"retrieved_chunk": " },\n timeTaken: endTime - startTime\n };\n if (test.result.timeTaken > runner.settings.timeout && runner.settings.timeout !== 0) {\n return jobError(runner, test, `Test timed out after ${test.result.timeTaken}ms`);\n }\n if (!compareStatus(run.status, test)) {\n return jobError(runner, test, `Expected exit code ${test.expected.exitCode} but got ${run.status}`);\n }\n if (!compareStdout(run.stdout.toString(), test)) {",
"score": 0.8034107685089111
},
{
"filename": "src/runner/jobError.ts",
"retrieved_chunk": "import {Runner, Test, Out} from '../modules/types.js';\nimport createOutput from '../output.js';\nexport default function jobError(runner: Runner, test: Test, msg: string): void {\n test.result.status = 'fail';\n test.result.msg = msg;\n if (runner.settings.outputFormat === 'text') {\n console.log(`Failed: ${msg}`);\n }\n runner.numberFail++;\n if (runner.settings.stopWhenFail) {",
"score": 0.8010307550430298
},
{
"filename": "src/runner/refer.ts",
"retrieved_chunk": " timeTaken: endTime - startTime\n };\n if (test.result.timeTaken > runner.settings.timeout && runner.settings.timeout !== 0) {\n return jobError(runner, test, `Test timed out after ${test.result.timeTaken}ms`);\n }\n if (run.status !== ref.status) {\n return jobError(runner, test, `Expected exit code ${test.expected.exitCode} but got ${run.status}`);\n }\n if (run.stdout.toString() !== ref.stdout.toString()) {\n return jobError(runner, test, `Expected stdout not match with run stdout`);",
"score": 0.7983290553092957
}
] | typescript | runner.tests = tests; |
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/jobError.ts",
"retrieved_chunk": "import {Runner, Test, Out} from '../modules/types.js';\nimport createOutput from '../output.js';\nexport default function jobError(runner: Runner, test: Test, msg: string): void {\n test.result.status = 'fail';\n test.result.msg = msg;\n if (runner.settings.outputFormat === 'text') {\n console.log(`Failed: ${msg}`);\n }\n runner.numberFail++;\n if (runner.settings.stopWhenFail) {",
"score": 0.8626989722251892
},
{
"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": 0.8312571048736572
},
{
"filename": "src/output.ts",
"retrieved_chunk": " testResults: []\n };\n for (const test of runner.tests) {\n output.testResults.push(test);\n }\n return output;\n}\nexport function returnJson(runner: Runner): string {\n return JSON.stringify(constructReturn(runner));\n}",
"score": 0.8186507821083069
},
{
"filename": "src/runner/refer.ts",
"retrieved_chunk": " }\n if (run.stderr.toString() !== ref.stderr.toString()) {\n return jobError(runner, test, `Expected stderr not match with run stderr`);\n }\n runner.numberSuccess++;\n if (runner.settings.outputFormat === 'text')\n console.log(`OK`);\n}\nexport default runRefer;",
"score": 0.8178015947341919
},
{
"filename": "src/runner/expect.ts",
"retrieved_chunk": " return jobError(runner, test, `Expected stdout not match with run stdout`);\n }\n if (!compareStderr(run.stderr.toString(), test)) {\n return jobError(runner, test, `Expected stderr not match with run stderr`);\n }\n runner.numberSuccess++;\n if (runner.settings.outputFormat === 'text')\n console.log(`OK`);\n}\nexport default runExpect;",
"score": 0.8161242008209229
}
] | typescript | console.log(`Starting Tests for ${runner.testFilePath}...`); |
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/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": 0.7979591488838196
},
{
"filename": "src/rules/signal.ts",
"retrieved_chunk": " super(async context => operator(await first.evaluate(context), second));\n }\n encode(signals: SignalSet<TContext>): EncodedSignalRule {\n return {\n [getSignalKey(this.first, signals)]: {\n [getOperatorKey(this.operator)]:\n this.second instanceof Rule\n ? this.second.encode(signals)\n : this.second instanceof RegExp\n ? this.second.toString()",
"score": 0.7862590551376343
},
{
"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": 0.7826058864593506
},
{
"filename": "src/rules/parse.ts",
"retrieved_chunk": " switch (key) {\n case '$and':\n case '$or':\n return new GroupRule<TContext>(\n operator[key],\n await Promise.all(\n assertArray(value).map(element => parse(element, signals)),\n ),\n );\n case '$not':",
"score": 0.7716614603996277
},
{
"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": 0.7699962854385376
}
] | typescript | (value.bind(target)(...args))
: value; |
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/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": 0.8027957677841187
},
{
"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": 0.7777717113494873
},
{
"filename": "src/runTests.ts",
"retrieved_chunk": " stdout: undefined,\n stderr: undefined,\n exitCode: undefined\n },\n timeTaken: undefined\n };\n }\n }\n for (const test of runner.tests) {\n if (runner.settings.runList.includes(test.id) || runner.settings.runList.length === 0) {",
"score": 0.7611872553825378
},
{
"filename": "src/runner/expect.ts",
"retrieved_chunk": " if (test.expected.stdout === undefined || (test.expected.stdout.string === undefined && test.expected.stdout.regex === undefined)) {\n return true;\n }\n if (test.expected.stdout.string !== undefined && test.expected.stdout.string === run)\n return true;\n if (test.expected.stdout.regex !== undefined) {\n let reg = new RegExp(test.expected.stdout.regex);\n return reg.test(run);\n }\n}",
"score": 0.760805070400238
},
{
"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": 0.7562512159347534
}
] | typescript | runner = await parseJson(runner); |
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": " 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": 0.8560137748718262
},
{
"filename": "src/rules/group.ts",
"retrieved_chunk": " context: Array<TContext>,\n rules: Array<Rule<TContext>>,\n ) => Promise<boolean>,\n protected rules: Array<Rule<TContext>>,\n ) {\n super(context => operator([context], rules));\n }\n encode(signals: SignalSet<TContext>): EncodedGroupRule<TContext> {\n return {\n [getOperatorKey(this.operator)]: this.rules.map(rule =>",
"score": 0.8508849143981934
},
{
"filename": "src/rules/parse.ts",
"retrieved_chunk": " switch (key) {\n case '$and':\n case '$or':\n return new GroupRule<TContext>(\n operator[key],\n await Promise.all(\n assertArray(value).map(element => parse(element, signals)),\n ),\n );\n case '$not':",
"score": 0.839887261390686
},
{
"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": 0.8337363600730896
},
{
"filename": "src/rules/signal.ts",
"retrieved_chunk": " TSecond,\n> extends Rule<TContext> {\n constructor(\n protected operator: (\n first: TFirst,\n second: TSecond,\n ) => boolean | Promise<boolean>,\n protected first: Signal<TContext, TFirst>,\n protected second: TSecond,\n ) {",
"score": 0.8331204652786255
}
] | typescript | SignalRule(operator.$in, signal, values),
}; |
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/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": 0.8062068223953247
},
{
"filename": "src/runTests.ts",
"retrieved_chunk": " stdout: undefined,\n stderr: undefined,\n exitCode: undefined\n },\n timeTaken: undefined\n };\n }\n }\n for (const test of runner.tests) {\n if (runner.settings.runList.includes(test.id) || runner.settings.runList.length === 0) {",
"score": 0.7830567359924316
},
{
"filename": "src/output.ts",
"retrieved_chunk": " print_end(runner);\n break;\n }\n try {\n if (output !== undefined)\n fs.writeFileSync(runner.settings.output, output);\n } catch (err) {\n error(`Error writing to file: ${err}`);\n }\n if (runner.settings.status && runner.numberFail > 0)",
"score": 0.7740445733070374
},
{
"filename": "src/runner/refer.ts",
"retrieved_chunk": " }\n if (run.stderr.toString() !== ref.stderr.toString()) {\n return jobError(runner, test, `Expected stderr not match with run stderr`);\n }\n runner.numberSuccess++;\n if (runner.settings.outputFormat === 'text')\n console.log(`OK`);\n}\nexport default runRefer;",
"score": 0.7714009881019592
},
{
"filename": "src/runner/expect.ts",
"retrieved_chunk": " return jobError(runner, test, `Expected stdout not match with run stdout`);\n }\n if (!compareStderr(run.stderr.toString(), test)) {\n return jobError(runner, test, `Expected stderr not match with run stderr`);\n }\n runner.numberSuccess++;\n if (runner.settings.outputFormat === 'text')\n console.log(`OK`);\n}\nexport default runExpect;",
"score": 0.768561601638794
}
] | 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/runTests.ts",
"retrieved_chunk": " stdout: undefined,\n stderr: undefined,\n exitCode: undefined\n },\n timeTaken: undefined\n };\n }\n }\n for (const test of runner.tests) {\n if (runner.settings.runList.includes(test.id) || runner.settings.runList.length === 0) {",
"score": 0.7555906772613525
},
{
"filename": "src/output.ts",
"retrieved_chunk": " print_end(runner);\n break;\n }\n try {\n if (output !== undefined)\n fs.writeFileSync(runner.settings.output, output);\n } catch (err) {\n error(`Error writing to file: ${err}`);\n }\n if (runner.settings.status && runner.numberFail > 0)",
"score": 0.7416676878929138
},
{
"filename": "src/runTests.ts",
"retrieved_chunk": " }\n if (runner.settings.outputFormat == 'text')\n console.log(\"Starting Tests...\\n\");\n for (const test of runner.tests) {\n if (runner.settings.runList.includes(test.id) || runner.settings.runList.length === 0) {\n test.result = {\n status: 'pending',\n msg: 'In the queue',\n result: {\n stdout: undefined,",
"score": 0.720156192779541
},
{
"filename": "src/fileParsing/parse.ts",
"retrieved_chunk": " }\n } catch(e) {\n error(`Error parsing: ${e}`);\n }\n runner.tests = tests;\n return runner;\n}",
"score": 0.7196078300476074
},
{
"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": 0.7170301675796509
}
] | typescript | runner.testFilePath = args[i]; |
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/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": 0.8877233862876892
},
{
"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": 0.8617924451828003
},
{
"filename": "src/utils/prepare-project.ts",
"retrieved_chunk": "type PrepareOptions = {\n directory: string\n dbConnectionString: string\n admin?: {\n email: string\n }\n seed?: boolean\n spinner?: Ora\n abortController?: AbortController\n}",
"score": 0.813666582107544
},
{
"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": 0.8101248741149902
},
{
"filename": "src/utils/run-process.ts",
"retrieved_chunk": "type ProcessOptions = {\n process: Function\n ignoreERESOLVE?: boolean\n}\n// when running commands with npx or npm sometimes they\n// terminate with EAGAIN error unexpectedly\n// this utility function allows retrying the process if\n// EAGAIN occurs, or otherwise throw the error that occurs\nexport default async ({ process, ignoreERESOLVE }: ProcessOptions) => {\n let processError = false",
"score": 0.7973646521568298
}
] | 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/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": 0.8406596183776855
},
{
"filename": "src/commands/create.ts",
"retrieved_chunk": " directoryName: projectName,\n repoUrl,\n abortController,\n })\n } catch (e) {\n if (isAbortError(e)) {\n process.exit()\n }\n logMessage({\n message: `An error occurred while setting up your project: ${e}`,",
"score": 0.834250271320343
},
{
"filename": "src/utils/run-process.ts",
"retrieved_chunk": "type ProcessOptions = {\n process: Function\n ignoreERESOLVE?: boolean\n}\n// when running commands with npx or npm sometimes they\n// terminate with EAGAIN error unexpectedly\n// this utility function allows retrying the process if\n// EAGAIN occurs, or otherwise throw the error that occurs\nexport default async ({ process, ignoreERESOLVE }: ProcessOptions) => {\n let processError = false",
"score": 0.8245203495025635
},
{
"filename": "src/commands/create.ts",
"retrieved_chunk": " abortController,\n })\n } catch (e: any) {\n if (isAbortError(e)) {\n process.exit()\n }\n logMessage({\n message: `An error occurred while preparing project: ${e}`,\n type: \"error\",\n })",
"score": 0.8207845091819763
},
{
"filename": "src/commands/create.ts",
"retrieved_chunk": " client,\n db: dbName,\n })\n } catch (e) {\n logMessage({\n message: `An error occurred while trying to create your database: ${e}`,\n type: \"error\",\n })\n }\n // format connection string",
"score": 0.8047537803649902
}
] | 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": 0.8615726828575134
},
{
"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": 0.826693594455719
},
{
"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": 0.8056542873382568
},
{
"filename": "src/engines/lib/Google.ts",
"retrieved_chunk": " this.updateQueries('client', 'gws-wiz');\n this.updateQueries('dpr', 1);\n const __proxy = this.options.proxy;\n if (__proxy) {\n this.options.proxies.push(__proxy);\n this.options.proxy = undefined;\n }\n return await this.useProxies(() => this._suggestions(query));\n }\n private async _suggestions(query: string): Promise<{}> {",
"score": 0.794279158115387
},
{
"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": 0.7690331935882568
}
] | 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/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": 0.8907875418663025
},
{
"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": 0.8606184720993042
},
{
"filename": "src/utils/prepare-project.ts",
"retrieved_chunk": "type PrepareOptions = {\n directory: string\n dbConnectionString: string\n admin?: {\n email: string\n }\n seed?: boolean\n spinner?: Ora\n abortController?: AbortController\n}",
"score": 0.8170362114906311
},
{
"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": 0.8132597208023071
},
{
"filename": "src/utils/run-process.ts",
"retrieved_chunk": "type ProcessOptions = {\n process: Function\n ignoreERESOLVE?: boolean\n}\n// when running commands with npx or npm sometimes they\n// terminate with EAGAIN error unexpectedly\n// this utility function allows retrying the process if\n// EAGAIN occurs, or otherwise throw the error that occurs\nexport default async ({ process, ignoreERESOLVE }: ProcessOptions) => {\n let processError = false",
"score": 0.7952439188957214
}
] | typescript | = 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/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": 0.7885892987251282
},
{
"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": 0.7486646771430969
},
{
"filename": "src/commands/create.ts",
"retrieved_chunk": " }\n spinner.succeed(chalk.green(\"Project Prepared\"))\n // close db connection\n await client?.end()\n // start backend\n logMessage({\n message: \"Starting Medusa...\",\n })\n try {\n startMedusa({",
"score": 0.7354463934898376
},
{
"filename": "src/utils/on-process-terminated.ts",
"retrieved_chunk": "export default (fn: Function) => {\n process.on(\"SIGTERM\", () => fn())\n process.on(\"SIGINT\", () => fn())\n}",
"score": 0.7343923449516296
},
{
"filename": "src/commands/create.ts",
"retrieved_chunk": " return \"Please enter a project name\"\n }\n return fs.existsSync(input) && fs.lstatSync(input).isDirectory()\n ? \"A directory already exists with the same name. Please enter a different project name.\"\n : true\n },\n },\n ])\n let client: pg.Client | undefined\n let dbConnectionString = \"\"",
"score": 0.731911301612854
}
] | 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.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": 0.856254518032074
},
{
"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": 0.8558863401412964
},
{
"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": 0.8546010255813599
},
{
"filename": "src/sequelize/associations/sequelize.post.ts",
"retrieved_chunk": " throw [new Error(\"Not all models were successfully created\")];\n }\n const modelName = association.details.model;\n await Promise.all(\n association.attributes.map(async (attribute, index) => {\n const isCreate = !attribute[primaryKey];\n if (isCreate) {\n const id = (\n await sequelize.models[modelName].create(attribute, {\n transaction,",
"score": 0.8494635820388794
},
{
"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": 0.8452648520469666
}
] | 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": 0.9618806838989258
},
{
"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": 0.926886796951294
},
{
"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": 0.9235081672668457
},
{
"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": 0.9113471508026123
},
{
"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": 0.9064448475837708
}
] | 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/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": 0.873280942440033
},
{
"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": 0.846115231513977
},
{
"filename": "src/utils/prepare-project.ts",
"retrieved_chunk": " // use npm\n await promiseExec(`npm install`, execOptions)\n }\n },\n ignoreERESOLVE: true,\n })\n if (interval) {\n clearInterval(interval)\n }\n if (spinner) {",
"score": 0.8382086157798767
},
{
"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": 0.8232431411743164
},
{
"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": 0.81216961145401
}
] | 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/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": 0.7985819578170776
},
{
"filename": "src/utils/run-process.ts",
"retrieved_chunk": "type ProcessOptions = {\n process: Function\n ignoreERESOLVE?: boolean\n}\n// when running commands with npx or npm sometimes they\n// terminate with EAGAIN error unexpectedly\n// this utility function allows retrying the process if\n// EAGAIN occurs, or otherwise throw the error that occurs\nexport default async ({ process, ignoreERESOLVE }: ProcessOptions) => {\n let processError = false",
"score": 0.7523209452629089
},
{
"filename": "src/commands/create.ts",
"retrieved_chunk": " }\n spinner.succeed(chalk.green(\"Project Prepared\"))\n // close db connection\n await client?.end()\n // start backend\n logMessage({\n message: \"Starting Medusa...\",\n })\n try {\n startMedusa({",
"score": 0.7476211190223694
},
{
"filename": "src/utils/on-process-terminated.ts",
"retrieved_chunk": "export default (fn: Function) => {\n process.on(\"SIGTERM\", () => fn())\n process.on(\"SIGINT\", () => fn())\n}",
"score": 0.7443010807037354
},
{
"filename": "src/commands/create.ts",
"retrieved_chunk": " client,\n db: dbName,\n })\n } catch (e) {\n logMessage({\n message: `An error occurred while trying to create your database: ${e}`,\n type: \"error\",\n })\n }\n // format connection string",
"score": 0.7340343594551086
}
] | 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": 0.8748500943183899
},
{
"filename": "src/sequelize/extended.ts",
"retrieved_chunk": " >(\n attributes: Array<MakeNullishOptional<M[\"_creationAttributes\"]>>,\n options?: O,\n ) {\n const { sequelize } = this.options;\n const associations = getLookup(sequelize)[this.name];\n const modelPrimaryKey = this.primaryKeyAttribute;\n let modelData:\n | undefined\n | Array<",
"score": 0.8735699653625488
},
{
"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": 0.8717736005783081
},
{
"filename": "src/sequelize/extended.ts",
"retrieved_chunk": " O extends { returning: false } | { ignoreDuplicates: true } ? void : M\n >;\n const {\n otherAssociationAttributes,\n externalAssociations,\n currentModelAttributes,\n } = getValidAttributesAndAssociations(attributes, associations);\n // If there are no associations, create the model with all attributes.\n if (!externalAssociations.length) {\n return origBulkCreate.apply(this, [attributes, options]);",
"score": 0.8611628413200378
},
{
"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": 0.8610727787017822
}
] | 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": " if (Array.isArray(currentModelAttributes)) {\n data = currentModelAttributes.map((attribute: any) => {\n const { [association]: _, ...attributesleft } = attribute;\n const otherAttr = otherAssociationAttributes[association] ?? [];\n otherAssociationAttributes[association] = [...otherAttr, _];\n return attributesleft;\n });\n } else {\n const { [association]: _, ...attributesLeft } =\n currentModelAttributes;",
"score": 0.8680378198623657
},
{
"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": 0.8664118051528931
},
{
"filename": "src/sequelize/associations/sequelize.post.ts",
"retrieved_chunk": " where: {\n [primaryKey]: model.id,\n },\n transaction,\n });\n if (modelInstances.length !== model.id.length) {\n throw [new Error(\"Not all models were successfully created\")];\n }\n const modelName = association.details.model;\n const results = await Promise.all(",
"score": 0.8642544746398926
},
{
"filename": "src/sequelize/associations/sequelize.patch.ts",
"retrieved_chunk": " transaction,\n })\n : null,\n ]);\n if (!modelInstance) {\n throw [new Error(\"Unable to find created model\")];\n }\n if (associatedId && !associatedInstance) {\n throw [\n new NotFoundError({",
"score": 0.8625198602676392
},
{
"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": 0.8595116138458252
}
] | 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/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": 0.8538306951522827
},
{
"filename": "src/commands/create.ts",
"retrieved_chunk": " directoryName: projectName,\n repoUrl,\n abortController,\n })\n } catch (e) {\n if (isAbortError(e)) {\n process.exit()\n }\n logMessage({\n message: `An error occurred while setting up your project: ${e}`,",
"score": 0.8407129049301147
},
{
"filename": "src/commands/create.ts",
"retrieved_chunk": " abortController,\n })\n } catch (e: any) {\n if (isAbortError(e)) {\n process.exit()\n }\n logMessage({\n message: `An error occurred while preparing project: ${e}`,\n type: \"error\",\n })",
"score": 0.8310645818710327
},
{
"filename": "src/utils/run-process.ts",
"retrieved_chunk": "type ProcessOptions = {\n process: Function\n ignoreERESOLVE?: boolean\n}\n// when running commands with npx or npm sometimes they\n// terminate with EAGAIN error unexpectedly\n// this utility function allows retrying the process if\n// EAGAIN occurs, or otherwise throw the error that occurs\nexport default async ({ process, ignoreERESOLVE }: ProcessOptions) => {\n let processError = false",
"score": 0.8252184987068176
},
{
"filename": "src/commands/create.ts",
"retrieved_chunk": " client,\n db: dbName,\n })\n } catch (e) {\n logMessage({\n message: `An error occurred while trying to create your database: ${e}`,\n type: \"error\",\n })\n }\n // format connection string",
"score": 0.8134161829948425
}
] | typescript | await promiseExec(`yarn`, execOptions)
} catch (e) { |
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": 0.8948376178741455
},
{
"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": 0.8337504267692566
},
{
"filename": "src/modules/scraper/jobCollector.ts",
"retrieved_chunk": " for (let i = 0; i < 4; i++) {\n // Scroll to the bottom of the page\n await driver.executeScript('window.scrollTo(0, document.body.scrollHeight);');\n // Wait for new content to load\n await driver.wait(until.elementLocated(By.css('ul.jobs-search__results-list>li')));\n // Wait for some additional time to allow the page to fully render\n await driver.sleep(3000);\n }\n // Get job listings\n console.log('before listing...');",
"score": 0.8013753294944763
},
{
"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": 0.7794670462608337
},
{
"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": 0.7770357131958008
}
] | typescript | editedText = 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": 0.8905379772186279
},
{
"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": 0.8294751048088074
},
{
"filename": "src/modules/scraper/jobCollector.ts",
"retrieved_chunk": " for (let i = 0; i < 4; i++) {\n // Scroll to the bottom of the page\n await driver.executeScript('window.scrollTo(0, document.body.scrollHeight);');\n // Wait for new content to load\n await driver.wait(until.elementLocated(By.css('ul.jobs-search__results-list>li')));\n // Wait for some additional time to allow the page to fully render\n await driver.sleep(3000);\n }\n // Get job listings\n console.log('before listing...');",
"score": 0.7924255132675171
},
{
"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": 0.7729325890541077
},
{
"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": 0.7704979181289673
}
] | typescript | = cleanedText(text).substring(0, 3500); |
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/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": 0.715927243232727
},
{
"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": 0.6915261745452881
},
{
"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": 0.690638542175293
},
{
"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": 0.6897099018096924
},
{
"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": 0.6872512102127075
}
] | typescript | (isExcludedByTitle(title.toLocaleLowerCase()) && link.length > 1) { |
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/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": 0.8245699405670166
},
{
"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": 0.7819942235946655
},
{
"filename": "src/xmltvTranslations.ts",
"retrieved_chunk": " reverseMap<XmltvTagTranslationsReversed>(xmltvTagTranslations);\nconst xmltvAttributeTranslationsReversed =\n reverseMap<XmltvAttributeTranslationsReversed>(xmltvAttributeTranslations);\n/**\n * Adds or modifies a translation for a XMLTV tag\n *\n * @param key A valid Xmltv tag string\n * @param value Your translation\n */\nfunction addTagTranslation(key: XmltvTags, value: string) {",
"score": 0.775722861289978
},
{
"filename": "src/objectToDom.ts",
"retrieved_chunk": " }\n const translatedTagName = xmltvTagTranslationsReversed.get(key) || key;\n const DomNode: XmltvDomNode = {\n tagName: translatedTagName,\n attributes: {},\n children: [],\n };\n for (let childKey in obj) {\n const translatedAttributeName =\n xmltvAttributeTranslationsReversed.get(childKey) || childKey;",
"score": 0.7670811414718628
},
{
"filename": "src/writer.ts",
"retrieved_chunk": "import type { XmltvDom, XmltvDomNode } from \"./types\";\nexport function writer(xmltvDom: XmltvDom): string {\n let out = \"\";\n function writeChildren(node: XmltvDom) {\n if (node)\n for (var i = 0; i < node.length; i++) {\n if (typeof node[i] === \"string\") {\n if ((node[i] as string).includes(\"!DOCTYPE\")) {\n out += \"<\" + (node[i] as string).trim() + \">\";\n continue;",
"score": 0.7660108804702759
}
] | 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": 0.9044835567474365
},
{
"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": 0.8763801455497742
},
{
"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": 0.8737051486968994
},
{
"filename": "src/main.ts",
"retrieved_chunk": "type ParseXmltvOptions = {\n asDom: boolean;\n};\ntype WriteXmltvOptions = {\n fromDom: boolean;\n};\n/**\n * parseXmltv\n *\n * Parses an xmltv file and returns an `Xmltv` object or a DOM tree",
"score": 0.8704812526702881
},
{
"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": 0.8648957014083862
}
] | 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/xmltvTranslations.ts",
"retrieved_chunk": " * from a map is faster than running a function. It also allows us to\n * translate by any rule we want, pluralisation, internationalisation, etc.\n *\n * Here are the results of running a benchmark comparing picking from a\n * map vs running a transform function:\n * map: 6 470 122 ops/s, ±0.21% | fastest\n * convert: 232 614 ops/s, ±0.27% | slowest, 96.4% slower\n *\n */\ntype XmltvTagTranslations = Map<XmltvTags, string>;",
"score": 0.8743690252304077
},
{
"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": 0.8629024624824524
},
{
"filename": "src/types.ts",
"retrieved_chunk": " /**\n * The URL of the person.\n */\n url?: XmltvUrl[];\n};\n/**\n * A representation of the credits for an XMLTV programme object.\n *\n * People are listed in decreasing order of importance; so for example the starring actors appear\n * first followed by the smaller parts. As with other parts of this file format, not mentioning",
"score": 0.8625044822692871
},
{
"filename": "src/types.ts",
"retrieved_chunk": "/**\n * A representation of a person in an XMLTV programme object.\n */\nexport type XmltvPerson = {\n /**\n * The name of the person.\n */\n _value: string;\n /**\n * The role of the actor in the programme eg Bryan Cranston's role in Breaking Bad is \"Walter White\".",
"score": 0.8581730127334595
},
{
"filename": "src/xmltvTranslations.ts",
"retrieved_chunk": "import { reverseMap } from \"./utils.js\";\nimport { xmltvAttributes, xmltvTags } from \"./xmltvTagsAttributes.js\";\nimport type { XmltvTags, XmltvAttributes } from \"./xmltvTagsAttributes.js\";\n/**\n * The map of XMLTV strings to preferred JS strings\n *\n * Why use a map?\n *\n * Instead of using a function to convert to camelCase, we use a map.\n * This is because performance is important in this library, and picking",
"score": 0.8570375442504883
}
] | typescript | export function parser(xmltvString: string): XmltvDom { |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.