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 { ExecutionContext, NoopExecutionContext } from "./execution-context"; import { SlackApp } from "./app"; import { SlackOAuthEnv } from "./app-env"; import { InstallationStore } from "./oauth/installation-store"; import { NoStorageStateStore, StateStore } from "./oauth/state-store"; import { renderCompletionPage, renderStartPage, } from "./oauth/oauth-page-renderer"; import { generateAuthorizeUrl } from "./oauth/authorize-url-generator"; import { parse as parseCookie } from "./cookie"; import { SlackAPIClient, OAuthV2AccessResponse, OpenIDConnectTokenResponse, } from "slack-web-api-client"; import { toInstallation } from "./oauth/installation"; import { AfterInstallation, BeforeInstallation, OnFailure, OnStateValidationError, defaultOnFailure, defaultOnStateValidationError, } from "./oauth/callback"; import { OpenIDConnectCallback, defaultOpenIDConnectCallback, } from "./oidc/callback"; import { generateOIDCAuthorizeUrl } from "./oidc/authorize-url-generator"; import { InstallationError, MissingCode, CompletionPageError, InstallationStoreError, OpenIDConnectError, } from "./oauth/error-codes"; export interface SlackOAuthAppOptions<E extends SlackOAuthEnv> { env: E; installationStore: InstallationStore<E>; stateStore?: StateStore; oauth?: { stateCookieName?: string; beforeInstallation?: BeforeInstallation; afterInstallation?: AfterInstallation; onFailure?: OnFailure; onStateValidationError?: OnStateValidationError; redirectUri?: string; }; oidc?: { stateCookieName?: string; callback: OpenIDConnectCallback; onFailure?: OnFailure; onStateValidationError?: OnStateValidationError; redirectUri?: string; }; routes?: { events: string; oauth: { start: string; callback: string }; oidc?: { start: string; callback: string }; }; } export class SlackOAuthApp<E extends SlackOAuthEnv> extends SlackApp<E> { public env: E; public installationStore: InstallationStore<E>; public stateStore: StateStore; public oauth: { stateCookieName?: string; beforeInstallation?: BeforeInstallation; afterInstallation?: AfterInstallation; onFailure: OnFailure; onStateValidationError: OnStateValidationError; redirectUri?: string; }; public oidc?: { stateCookieName?: string; callback: OpenIDConnectCallback; onFailure: OnFailure; onStateValidationError: OnStateValidationError; redirectUri?: string; }; public routes: { events: string; oauth: { start: string; callback: string }; oidc?: { start: string; callback: string }; }; constructor(options: SlackOAuthAppOptions<E>) { super({ env: options.env, authorize: options.installationStore.toAuthorize(), routes: { events: options.routes?.events ?? "/slack/events" }, }); this.env = options.env; this.installationStore = options.installationStore; this.stateStore = options.stateStore ?? new NoStorageStateStore(); this.oauth = { stateCookieName: options.oauth?.stateCookieName ?? "slack-app-oauth-state", onFailure: options.oauth?.onFailure ?? defaultOnFailure, onStateValidationError: options.oauth?.onStateValidationError ?? defaultOnStateValidationError, redirectUri: options.oauth?.redirectUri ?? this.env.SLACK_REDIRECT_URI, }; if (options.oidc) { this.oidc = { stateCookieName: options.oidc.stateCookieName ?? "slack-app-oidc-state", onFailure: options.oidc.onFailure ?? defaultOnFailure, onStateValidationError: options.oidc.onStateValidationError ?? defaultOnStateValidationError, callback: defaultOpenIDConnectCallback(this.env), redirectUri: options.oidc.redirectUri ?? this.env.SLACK_OIDC_REDIRECT_URI, }; } else { this.oidc = undefined; } this.routes = options.routes ? options.routes : { events: "/slack/events", oauth: { start: "/slack/install", callback: "/slack/oauth_redirect", }, oidc: { start: "/slack/login", callback: "/slack/login/callback", }, }; } async run( request: Request, ctx: ExecutionContext = new NoopExecutionContext() ): Promise<Response> { const url = new URL(request.url); if (request.method === "GET") { if (url.pathname === this.routes.oauth.start) { return await this.handleOAuthStartRequest(request); } else if (url.pathname === this.routes.oauth.callback) { return await this.handleOAuthCallbackRequest(request); } if (this.routes.oidc) { if (url.pathname === this.routes.oidc.start) { return await this.handleOIDCStartRequest(request); } else if (url.pathname === this.routes.oidc.callback) { return await this.handleOIDCCallbackRequest(request); } } } else if (request.method === "POST") { if (url.pathname === this.routes.events) { return await this.handleEventRequest(request, ctx); } } return new Response("Not found", { status: 404 }); } async handleEventRequest( request: Request, ctx: ExecutionContext ): Promise<Response> { return await super.handleEventRequest(request, ctx); } // deno-lint-ignore no-unused-vars async handleOAuthStartRequest(request: Request): Promise<Response> { const stateValue = await this.stateStore.issueNewState();
const authorizeUrl = generateAuthorizeUrl(stateValue, this.env);
return new Response(renderStartPage(authorizeUrl), { status: 302, headers: { Location: authorizeUrl, "Set-Cookie": `${this.oauth.stateCookieName}=${stateValue}; Secure; HttpOnly; Path=/; Max-Age=300`, "Content-Type": "text/html; charset=utf-8", }, }); } async handleOAuthCallbackRequest(request: Request): Promise<Response> { // State parameter validation await this.#validateStateParameter( request, this.routes.oauth.start, this.oauth.stateCookieName! ); const { searchParams } = new URL(request.url); const code = searchParams.get("code"); if (!code) { return await this.oauth.onFailure( this.routes.oauth.start, MissingCode, request ); } const client = new SlackAPIClient(undefined, { logLevel: this.env.SLACK_LOGGING_LEVEL, }); let oauthAccess: OAuthV2AccessResponse | undefined; try { // Execute the installation process oauthAccess = await client.oauth.v2.access({ client_id: this.env.SLACK_CLIENT_ID, client_secret: this.env.SLACK_CLIENT_SECRET, redirect_uri: this.oauth.redirectUri, code, }); } catch (e) { console.log(e); return await this.oauth.onFailure( this.routes.oauth.start, InstallationError, request ); } try { // Store the installation data on this app side await this.installationStore.save(toInstallation(oauthAccess), request); } catch (e) { console.log(e); return await this.oauth.onFailure( this.routes.oauth.start, InstallationStoreError, request ); } try { // Build the completion page const authTest = await client.auth.test({ token: oauthAccess.access_token, }); const enterpriseUrl = authTest.url; return new Response( renderCompletionPage( oauthAccess.app_id!, oauthAccess.team?.id!, oauthAccess.is_enterprise_install, enterpriseUrl ), { status: 200, headers: { "Set-Cookie": `${this.oauth.stateCookieName}=deleted; Secure; HttpOnly; Path=/; Max-Age=0`, "Content-Type": "text/html; charset=utf-8", }, } ); } catch (e) { console.log(e); return await this.oauth.onFailure( this.routes.oauth.start, CompletionPageError, request ); } } // deno-lint-ignore no-unused-vars async handleOIDCStartRequest(request: Request): Promise<Response> { if (!this.oidc) { return new Response("Not found", { status: 404 }); } const stateValue = await this.stateStore.issueNewState(); const authorizeUrl = generateOIDCAuthorizeUrl(stateValue, this.env); return new Response(renderStartPage(authorizeUrl), { status: 302, headers: { Location: authorizeUrl, "Set-Cookie": `${this.oidc.stateCookieName}=${stateValue}; Secure; HttpOnly; Path=/; Max-Age=300`, "Content-Type": "text/html; charset=utf-8", }, }); } async handleOIDCCallbackRequest(request: Request): Promise<Response> { if (!this.oidc || !this.routes.oidc) { return new Response("Not found", { status: 404 }); } // State parameter validation await this.#validateStateParameter( request, this.routes.oidc.start, this.oidc.stateCookieName! ); const { searchParams } = new URL(request.url); const code = searchParams.get("code"); if (!code) { return await this.oidc.onFailure( this.routes.oidc.start, MissingCode, request ); } try { const client = new SlackAPIClient(undefined, { logLevel: this.env.SLACK_LOGGING_LEVEL, }); const apiResponse: OpenIDConnectTokenResponse = await client.openid.connect.token({ client_id: this.env.SLACK_CLIENT_ID, client_secret: this.env.SLACK_CLIENT_SECRET, redirect_uri: this.oidc.redirectUri, code, }); return await this.oidc.callback(apiResponse, request); } catch (e) { console.log(e); return await this.oidc.onFailure( this.routes.oidc.start, OpenIDConnectError, request ); } } async #validateStateParameter( request: Request, startPath: string, cookieName: string ) { const { searchParams } = new URL(request.url); const queryState = searchParams.get("state"); const cookie = parseCookie(request.headers.get("Cookie") || ""); const cookieState = cookie[cookieName]; if ( queryState !== cookieState || !(await this.stateStore.consume(queryState)) ) { if (startPath === this.routes.oauth.start) { return await this.oauth.onStateValidationError(startPath, request); } else if ( this.oidc && this.routes.oidc && startPath === this.routes.oidc.start ) { return await this.oidc.onStateValidationError(startPath, request); } } } }
src/oauth-app.ts
seratch-slack-edge-c75c224
[ { "filename": "src/app.ts", "retrieved_chunk": " await this.socketModeClient.connect();\n }\n async disconnect(): Promise<void> {\n if (this.socketModeClient) {\n await this.socketModeClient.disconnect();\n }\n }\n async handleEventRequest(\n request: Request,\n ctx: ExecutionContext", "score": 0.8398053646087646 }, { "filename": "src/app.ts", "retrieved_chunk": " ): Promise<Response> {\n return await this.handleEventRequest(request, ctx);\n }\n async connect(): Promise<void> {\n if (!this.socketMode) {\n throw new ConfigError(\n \"Both env.SLACK_APP_TOKEN and socketMode: true are required to start a Socket Mode connection!\"\n );\n }\n this.socketModeClient = new SocketModeClient(this);", "score": 0.831208348274231 }, { "filename": "src/oauth/callback.ts", "retrieved_chunk": "export type OnStateValidationError = (\n startPath: string,\n req: Request\n) => Promise<Response>;\n// deno-lint-ignore require-await\nexport const defaultOnStateValidationError = async (\n startPath: string,\n // deno-lint-ignore no-unused-vars\n req: Request\n) => {", "score": 0.8272790908813477 }, { "filename": "src/app.ts", "retrieved_chunk": " (authorizedContext as SlackAppContextWithRespond).respond = async (\n params\n ) => {\n return new ResponseUrlSender(responseUrl).call(params);\n };\n }\n const baseRequest: SlackMiddlwareRequest<E> = {\n ...preAuthorizeRequest,\n context: authorizedContext,\n };", "score": 0.8257582187652588 }, { "filename": "src/app.ts", "retrieved_chunk": " if (response) {\n return toCompleteResponse(response);\n }\n }\n const authorizeResult: AuthorizeResult = await this.authorize(\n preAuthorizeRequest\n );\n const authorizedContext: SlackAppContext = {\n ...preAuthorizeRequest.context,\n authorizeResult,", "score": 0.8240286111831665 } ]
typescript
const authorizeUrl = generateAuthorizeUrl(stateValue, this.env);
import { SlackAppEnv, SlackEdgeAppEnv, SlackSocketModeAppEnv } from "./app-env"; import { parseRequestBody } from "./request/request-parser"; import { verifySlackRequest } from "./request/request-verification"; import { AckResponse, SlackHandler } from "./handler/handler"; import { SlackRequestBody } from "./request/request-body"; import { PreAuthorizeSlackMiddlwareRequest, SlackRequestWithRespond, SlackMiddlwareRequest, SlackRequestWithOptionalRespond, SlackRequest, SlackRequestWithChannelId, } from "./request/request"; import { SlashCommand } from "./request/payload/slash-command"; import { toCompleteResponse } from "./response/response"; import { SlackEvent, AnySlackEvent, AnySlackEventWithChannelId, } from "./request/payload/event"; import { ResponseUrlSender, SlackAPIClient } from "slack-web-api-client"; import { builtBaseContext, SlackAppContext, SlackAppContextWithChannelId, SlackAppContextWithRespond, } from "./context/context"; import { PreAuthorizeMiddleware, Middleware } from "./middleware/middleware"; import { isDebugLogEnabled, prettyPrint } from "slack-web-api-client"; import { Authorize } from "./authorization/authorize"; import { AuthorizeResult } from "./authorization/authorize-result"; import { ignoringSelfEvents, urlVerification, } from "./middleware/built-in-middleware"; import { ConfigError } from "./errors"; import { GlobalShortcut } from "./request/payload/global-shortcut"; import { MessageShortcut } from "./request/payload/message-shortcut"; import { BlockAction, BlockElementAction, BlockElementTypes, } from "./request/payload/block-action"; import { ViewSubmission } from "./request/payload/view-submission"; import { ViewClosed } from "./request/payload/view-closed"; import { BlockSuggestion } from "./request/payload/block-suggestion"; import { OptionsAckResponse, SlackOptionsHandler, } from "./handler/options-handler"; import { SlackViewHandler, ViewAckResponse } from "./handler/view-handler"; import { MessageAckResponse, SlackMessageHandler, } from "./handler/message-handler"; import { singleTeamAuthorize } from "./authorization/single-team-authorize"; import { ExecutionContext, NoopExecutionContext } from "./execution-context"; import { PayloadType } from "./request/payload-types"; import { isPostedMessageEvent } from "./utility/message-events"; import { SocketModeClient } from "./socket-mode/socket-mode-client"; export interface SlackAppOptions< E extends SlackEdgeAppEnv | SlackSocketModeAppEnv > { env: E; authorize?: Authorize<E>; routes?: { events: string; }; socketMode?: boolean; } export class SlackApp<E extends SlackEdgeAppEnv | SlackSocketModeAppEnv> { public env: E; public client: SlackAPIClient; public authorize: Authorize<E>; public routes: { events: string | undefined }; public signingSecret: string; public appLevelToken: string | undefined; public socketMode: boolean; public socketModeClient: SocketModeClient | undefined; // deno-lint-ignore no-explicit-any public preAuthorizeMiddleware: PreAuthorizeMiddleware<any>[] = [ urlVerification, ]; // deno-lint-ignore no-explicit-any public
postAuthorizeMiddleware: Middleware<any>[] = [ignoringSelfEvents];
#slashCommands: (( body: SlackRequestBody ) => SlackMessageHandler<E, SlashCommand> | null)[] = []; #events: (( body: SlackRequestBody ) => SlackHandler<E, SlackEvent<string>> | null)[] = []; #globalShorcuts: (( body: SlackRequestBody ) => SlackHandler<E, GlobalShortcut> | null)[] = []; #messageShorcuts: (( body: SlackRequestBody ) => SlackHandler<E, MessageShortcut> | null)[] = []; #blockActions: ((body: SlackRequestBody) => SlackHandler< E, // deno-lint-ignore no-explicit-any BlockAction<any> > | null)[] = []; #blockSuggestions: (( body: SlackRequestBody ) => SlackOptionsHandler<E, BlockSuggestion> | null)[] = []; #viewSubmissions: (( body: SlackRequestBody ) => SlackViewHandler<E, ViewSubmission> | null)[] = []; #viewClosed: (( body: SlackRequestBody ) => SlackViewHandler<E, ViewClosed> | null)[] = []; constructor(options: SlackAppOptions<E>) { if ( options.env.SLACK_BOT_TOKEN === undefined && (options.authorize === undefined || options.authorize === singleTeamAuthorize) ) { throw new ConfigError( "When you don't pass env.SLACK_BOT_TOKEN, your own authorize function, which supplies a valid token to use, needs to be passed instead." ); } this.env = options.env; this.client = new SlackAPIClient(options.env.SLACK_BOT_TOKEN, { logLevel: this.env.SLACK_LOGGING_LEVEL, }); this.appLevelToken = options.env.SLACK_APP_TOKEN; this.socketMode = options.socketMode ?? this.appLevelToken !== undefined; if (this.socketMode) { this.signingSecret = ""; } else { if (!this.env.SLACK_SIGNING_SECRET) { throw new ConfigError( "env.SLACK_SIGNING_SECRET is required to run your app on edge functions!" ); } this.signingSecret = this.env.SLACK_SIGNING_SECRET; } this.authorize = options.authorize ?? singleTeamAuthorize; this.routes = { events: options.routes?.events }; } beforeAuthorize(middleware: PreAuthorizeMiddleware<E>): SlackApp<E> { this.preAuthorizeMiddleware.push(middleware); return this; } middleware(middleware: Middleware<E>): SlackApp<E> { return this.afterAuthorize(middleware); } use(middleware: Middleware<E>): SlackApp<E> { return this.afterAuthorize(middleware); } afterAuthorize(middleware: Middleware<E>): SlackApp<E> { this.postAuthorizeMiddleware.push(middleware); return this; } command( pattern: StringOrRegExp, ack: ( req: SlackRequestWithRespond<E, SlashCommand> ) => Promise<MessageAckResponse>, lazy: ( req: SlackRequestWithRespond<E, SlashCommand> ) => Promise<void> = noopLazyListener ): SlackApp<E> { const handler: SlackMessageHandler<E, SlashCommand> = { ack, lazy }; this.#slashCommands.push((body) => { if (body.type || !body.command) { return null; } if (typeof pattern === "string" && body.command === pattern) { return handler; } else if ( typeof pattern === "object" && pattern instanceof RegExp && body.command.match(pattern) ) { return handler; } return null; }); return this; } event<Type extends string>( event: Type, lazy: (req: EventRequest<E, Type>) => Promise<void> ): SlackApp<E> { this.#events.push((body) => { if (body.type !== PayloadType.EventsAPI || !body.event) { return null; } if (body.event.type === event) { // deno-lint-ignore require-await return { ack: async () => "", lazy }; } return null; }); return this; } anyMessage(lazy: MessageEventHandler<E>): SlackApp<E> { return this.message(undefined, lazy); } message( pattern: MessageEventPattern, lazy: MessageEventHandler<E> ): SlackApp<E> { this.#events.push((body) => { if ( body.type !== PayloadType.EventsAPI || !body.event || body.event.type !== "message" ) { return null; } if (isPostedMessageEvent(body.event)) { let matched = true; if (pattern !== undefined) { if (typeof pattern === "string") { matched = body.event.text!.includes(pattern); } if (typeof pattern === "object") { matched = body.event.text!.match(pattern) !== null; } } if (matched) { // deno-lint-ignore require-await return { ack: async (_: EventRequest<E, "message">) => "", lazy }; } } return null; }); return this; } shortcut( callbackId: StringOrRegExp, ack: ( req: | SlackRequest<E, GlobalShortcut> | SlackRequestWithRespond<E, MessageShortcut> ) => Promise<AckResponse>, lazy: ( req: | SlackRequest<E, GlobalShortcut> | SlackRequestWithRespond<E, MessageShortcut> ) => Promise<void> = noopLazyListener ): SlackApp<E> { return this.globalShortcut(callbackId, ack, lazy).messageShortcut( callbackId, ack, lazy ); } globalShortcut( callbackId: StringOrRegExp, ack: (req: SlackRequest<E, GlobalShortcut>) => Promise<AckResponse>, lazy: ( req: SlackRequest<E, GlobalShortcut> ) => Promise<void> = noopLazyListener ): SlackApp<E> { const handler: SlackHandler<E, GlobalShortcut> = { ack, lazy }; this.#globalShorcuts.push((body) => { if (body.type !== PayloadType.GlobalShortcut || !body.callback_id) { return null; } if (typeof callbackId === "string" && body.callback_id === callbackId) { return handler; } else if ( typeof callbackId === "object" && callbackId instanceof RegExp && body.callback_id.match(callbackId) ) { return handler; } return null; }); return this; } messageShortcut( callbackId: StringOrRegExp, ack: ( req: SlackRequestWithRespond<E, MessageShortcut> ) => Promise<AckResponse>, lazy: ( req: SlackRequestWithRespond<E, MessageShortcut> ) => Promise<void> = noopLazyListener ): SlackApp<E> { const handler: SlackHandler<E, MessageShortcut> = { ack, lazy }; this.#messageShorcuts.push((body) => { if (body.type !== PayloadType.MessageShortcut || !body.callback_id) { return null; } if (typeof callbackId === "string" && body.callback_id === callbackId) { return handler; } else if ( typeof callbackId === "object" && callbackId instanceof RegExp && body.callback_id.match(callbackId) ) { return handler; } return null; }); return this; } action< T extends BlockElementTypes, A extends BlockAction<BlockElementAction<T>> = BlockAction< BlockElementAction<T> > >( constraints: | StringOrRegExp | { type: T; block_id?: string; action_id: string }, ack: (req: SlackRequestWithOptionalRespond<E, A>) => Promise<AckResponse>, lazy: ( req: SlackRequestWithOptionalRespond<E, A> ) => Promise<void> = noopLazyListener ): SlackApp<E> { const handler: SlackHandler<E, A> = { ack, lazy }; this.#blockActions.push((body) => { if ( body.type !== PayloadType.BlockAction || !body.actions || !body.actions[0] ) { return null; } const action = body.actions[0]; if (typeof constraints === "string" && action.action_id === constraints) { return handler; } else if (typeof constraints === "object") { if (constraints instanceof RegExp) { if (action.action_id.match(constraints)) { return handler; } } else if (constraints.type) { if (action.type === constraints.type) { if (action.action_id === constraints.action_id) { if ( constraints.block_id && action.block_id !== constraints.block_id ) { return null; } return handler; } } } } return null; }); return this; } options( constraints: StringOrRegExp | { block_id?: string; action_id: string }, ack: (req: SlackRequest<E, BlockSuggestion>) => Promise<OptionsAckResponse> ): SlackApp<E> { // Note that block_suggestion response must be done within 3 seconds. // So, we don't support the lazy handler for it. const handler: SlackOptionsHandler<E, BlockSuggestion> = { ack }; this.#blockSuggestions.push((body) => { if (body.type !== PayloadType.BlockSuggestion || !body.action_id) { return null; } if (typeof constraints === "string" && body.action_id === constraints) { return handler; } else if (typeof constraints === "object") { if (constraints instanceof RegExp) { if (body.action_id.match(constraints)) { return handler; } } else { if (body.action_id === constraints.action_id) { if (body.block_id && body.block_id !== constraints.block_id) { return null; } return handler; } } } return null; }); return this; } view( callbackId: StringOrRegExp, ack: ( req: | SlackRequestWithOptionalRespond<E, ViewSubmission> | SlackRequest<E, ViewClosed> ) => Promise<ViewAckResponse>, lazy: ( req: | SlackRequestWithOptionalRespond<E, ViewSubmission> | SlackRequest<E, ViewClosed> ) => Promise<void> = noopLazyListener ): SlackApp<E> { return this.viewSubmission(callbackId, ack, lazy).viewClosed( callbackId, ack, lazy ); } viewSubmission( callbackId: StringOrRegExp, ack: ( req: SlackRequestWithOptionalRespond<E, ViewSubmission> ) => Promise<ViewAckResponse>, lazy: ( req: SlackRequestWithOptionalRespond<E, ViewSubmission> ) => Promise<void> = noopLazyListener ): SlackApp<E> { const handler: SlackViewHandler<E, ViewSubmission> = { ack, lazy }; this.#viewSubmissions.push((body) => { if (body.type !== PayloadType.ViewSubmission || !body.view) { return null; } if ( typeof callbackId === "string" && body.view.callback_id === callbackId ) { return handler; } else if ( typeof callbackId === "object" && callbackId instanceof RegExp && body.view.callback_id.match(callbackId) ) { return handler; } return null; }); return this; } viewClosed( callbackId: StringOrRegExp, ack: (req: SlackRequest<E, ViewClosed>) => Promise<ViewAckResponse>, lazy: (req: SlackRequest<E, ViewClosed>) => Promise<void> = noopLazyListener ): SlackApp<E> { const handler: SlackViewHandler<E, ViewClosed> = { ack, lazy }; this.#viewClosed.push((body) => { if (body.type !== PayloadType.ViewClosed || !body.view) { return null; } if ( typeof callbackId === "string" && body.view.callback_id === callbackId ) { return handler; } else if ( typeof callbackId === "object" && callbackId instanceof RegExp && body.view.callback_id.match(callbackId) ) { return handler; } return null; }); return this; } async run( request: Request, ctx: ExecutionContext = new NoopExecutionContext() ): Promise<Response> { return await this.handleEventRequest(request, ctx); } async connect(): Promise<void> { if (!this.socketMode) { throw new ConfigError( "Both env.SLACK_APP_TOKEN and socketMode: true are required to start a Socket Mode connection!" ); } this.socketModeClient = new SocketModeClient(this); await this.socketModeClient.connect(); } async disconnect(): Promise<void> { if (this.socketModeClient) { await this.socketModeClient.disconnect(); } } async handleEventRequest( request: Request, ctx: ExecutionContext ): Promise<Response> { // If the routes.events is missing, any URLs can work for handing requests from Slack if (this.routes.events) { const { pathname } = new URL(request.url); if (pathname !== this.routes.events) { return new Response("Not found", { status: 404 }); } } // To avoid the following warning by Cloudflware, parse the body as Blob first // Called .text() on an HTTP body which does not appear to be text .. const blobRequestBody = await request.blob(); // We can safely assume the incoming request body is always text data const rawBody: string = await blobRequestBody.text(); // For Request URL verification if (rawBody.includes("ssl_check=")) { // Slack does not send the x-slack-signature header for this pattern. // Thus, we need to check the pattern before verifying a request. const bodyParams = new URLSearchParams(rawBody); if (bodyParams.get("ssl_check") === "1" && bodyParams.get("token")) { return new Response("", { status: 200 }); } } // Verify the request headers and body const isRequestSignatureVerified = this.socketMode || (await verifySlackRequest(this.signingSecret, request.headers, rawBody)); if (isRequestSignatureVerified) { // deno-lint-ignore no-explicit-any const body: Record<string, any> = await parseRequestBody( request.headers, rawBody ); let retryNum: number | undefined = undefined; try { const retryNumHeader = request.headers.get("x-slack-retry-num"); if (retryNumHeader) { retryNum = Number.parseInt(retryNumHeader); } else if (this.socketMode && body.retry_attempt) { retryNum = Number.parseInt(body.retry_attempt); } // deno-lint-ignore no-unused-vars } catch (e) { // Ignore an exception here } const retryReason = request.headers.get("x-slack-retry-reason") ?? body.retry_reason; const preAuthorizeRequest: PreAuthorizeSlackMiddlwareRequest<E> = { body, rawBody, retryNum, retryReason, context: builtBaseContext(body), env: this.env, headers: request.headers, }; if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log(`*** Received request body ***\n ${prettyPrint(body)}`); } for (const middlware of this.preAuthorizeMiddleware) { const response = await middlware(preAuthorizeRequest); if (response) { return toCompleteResponse(response); } } const authorizeResult: AuthorizeResult = await this.authorize( preAuthorizeRequest ); const authorizedContext: SlackAppContext = { ...preAuthorizeRequest.context, authorizeResult, client: new SlackAPIClient(authorizeResult.botToken, { logLevel: this.env.SLACK_LOGGING_LEVEL, }), botToken: authorizeResult.botToken, botId: authorizeResult.botId, botUserId: authorizeResult.botUserId, userToken: authorizeResult.userToken, }; if (authorizedContext.channelId) { const context = authorizedContext as SlackAppContextWithChannelId; const client = new SlackAPIClient(context.botToken); context.say = async (params) => await client.chat.postMessage({ channel: context.channelId, ...params, }); } if (authorizedContext.responseUrl) { const responseUrl = authorizedContext.responseUrl; // deno-lint-ignore require-await (authorizedContext as SlackAppContextWithRespond).respond = async ( params ) => { return new ResponseUrlSender(responseUrl).call(params); }; } const baseRequest: SlackMiddlwareRequest<E> = { ...preAuthorizeRequest, context: authorizedContext, }; for (const middlware of this.postAuthorizeMiddleware) { const response = await middlware(baseRequest); if (response) { return toCompleteResponse(response); } } const payload = body as SlackRequestBody; if (body.type === PayloadType.EventsAPI) { // Events API const slackRequest: SlackRequest<E, SlackEvent<string>> = { payload: body.event, ...baseRequest, }; for (const matcher of this.#events) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (!body.type && body.command) { // Slash commands const slackRequest: SlackRequest<E, SlashCommand> = { payload: body as SlashCommand, ...baseRequest, }; for (const matcher of this.#slashCommands) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (body.type === PayloadType.GlobalShortcut) { // Global shortcuts const slackRequest: SlackRequest<E, GlobalShortcut> = { payload: body as GlobalShortcut, ...baseRequest, }; for (const matcher of this.#globalShorcuts) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (body.type === PayloadType.MessageShortcut) { // Message shortcuts const slackRequest: SlackRequest<E, MessageShortcut> = { payload: body as MessageShortcut, ...baseRequest, }; for (const matcher of this.#messageShorcuts) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (body.type === PayloadType.BlockAction) { // Block actions // deno-lint-ignore no-explicit-any const slackRequest: SlackRequest<E, BlockAction<any>> = { // deno-lint-ignore no-explicit-any payload: body as BlockAction<any>, ...baseRequest, }; for (const matcher of this.#blockActions) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (body.type === PayloadType.BlockSuggestion) { // Block suggestions const slackRequest: SlackRequest<E, BlockSuggestion> = { payload: body as BlockSuggestion, ...baseRequest, }; for (const matcher of this.#blockSuggestions) { const handler = matcher(payload); if (handler) { // Note that the only way to respond to a block_suggestion request // is to send an HTTP response with options/option_groups. // Thus, we don't support lazy handlers for this pattern. const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (body.type === PayloadType.ViewSubmission) { // View submissions const slackRequest: SlackRequest<E, ViewSubmission> = { payload: body as ViewSubmission, ...baseRequest, }; for (const matcher of this.#viewSubmissions) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (body.type === PayloadType.ViewClosed) { // View closed const slackRequest: SlackRequest<E, ViewClosed> = { payload: body as ViewClosed, ...baseRequest, }; for (const matcher of this.#viewClosed) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } // TODO: Add code suggestion here console.log( `*** No listener found ***\n${JSON.stringify(baseRequest.body)}` ); return new Response("No listener found", { status: 404 }); } return new Response("Invalid signature", { status: 401 }); } } export type StringOrRegExp = string | RegExp; export type EventRequest<E extends SlackAppEnv, T> = Extract< AnySlackEventWithChannelId, { type: T } > extends never ? SlackRequest<E, Extract<AnySlackEvent, { type: T }>> : SlackRequestWithChannelId< E, Extract<AnySlackEventWithChannelId, { type: T }> >; export type MessageEventPattern = string | RegExp | undefined; export type MessageEventRequest< E extends SlackAppEnv, ST extends string | undefined > = SlackRequestWithChannelId< E, Extract<AnySlackEventWithChannelId, { subtype: ST }> >; export type MessageEventSubtypes = | undefined | "bot_message" | "thread_broadcast" | "file_share"; export type MessageEventHandler<E extends SlackAppEnv> = ( req: MessageEventRequest<E, MessageEventSubtypes> ) => Promise<void>; export const noopLazyListener = async () => {};
src/app.ts
seratch-slack-edge-c75c224
[ { "filename": "src/socket-mode/socket-mode-client.ts", "retrieved_chunk": " public appLevelToken: string;\n public ws: WebSocket | undefined;\n constructor(\n // deno-lint-ignore no-explicit-any\n app: SlackApp<any>\n ) {\n if (!app.socketMode) {\n throw new ConfigError(\n \"socketMode: true must be set for running with Socket Mode\"\n );", "score": 0.8627897500991821 }, { "filename": "src/middleware/built-in-middleware.ts", "retrieved_chunk": "import { PreAuthorizeMiddleware, Middleware } from \"./middleware\";\n// deno-lint-ignore require-await\nexport const urlVerification: PreAuthorizeMiddleware = async (req) => {\n if (req.body.type === \"url_verification\") {\n return { status: 200, body: req.body.challenge };\n }\n};\nconst eventTypesToKeep = [\"member_joined_channel\", \"member_left_channel\"];\n// deno-lint-ignore require-await\nexport const ignoringSelfEvents: Middleware = async (req) => {", "score": 0.8618937730789185 }, { "filename": "src/context/context.ts", "retrieved_chunk": " // deno-lint-ignore no-explicit-any\n [key: string]: any; // custom properties\n };\n}\nexport type SlackAppContext = {\n client: SlackAPIClient;\n botToken: string;\n userToken?: string;\n authorizeResult: AuthorizeResult;\n} & PreAuthorizeSlackAppContext;", "score": 0.8472067713737488 }, { "filename": "src/authorization/authorize-result.ts", "retrieved_chunk": " user?: string;\n userToken?: string;\n userScopes?: string[];\n}", "score": 0.832544207572937 }, { "filename": "src/oauth/installation.ts", "retrieved_chunk": " bot_scopes?: string[];\n bot_refresh_token?: string; // token rotation\n bot_token_expires_at?: number; // token rotation (epoch time seconds)\n // user token\n user_token?: string;\n user_scopes?: string[];\n user_refresh_token?: string; // token rotation\n user_token_expires_at?: number; // token rotation (epoch time seconds)\n // Only when having incoming-webhooks\n incoming_webhook_url?: string;", "score": 0.8280595541000366 } ]
typescript
postAuthorizeMiddleware: Middleware<any>[] = [ignoringSelfEvents];
import { ExecutionContext, NoopExecutionContext } from "./execution-context"; import { SlackApp } from "./app"; import { SlackOAuthEnv } from "./app-env"; import { InstallationStore } from "./oauth/installation-store"; import { NoStorageStateStore, StateStore } from "./oauth/state-store"; import { renderCompletionPage, renderStartPage, } from "./oauth/oauth-page-renderer"; import { generateAuthorizeUrl } from "./oauth/authorize-url-generator"; import { parse as parseCookie } from "./cookie"; import { SlackAPIClient, OAuthV2AccessResponse, OpenIDConnectTokenResponse, } from "slack-web-api-client"; import { toInstallation } from "./oauth/installation"; import { AfterInstallation, BeforeInstallation, OnFailure, OnStateValidationError, defaultOnFailure, defaultOnStateValidationError, } from "./oauth/callback"; import { OpenIDConnectCallback, defaultOpenIDConnectCallback, } from "./oidc/callback"; import { generateOIDCAuthorizeUrl } from "./oidc/authorize-url-generator"; import { InstallationError, MissingCode, CompletionPageError, InstallationStoreError, OpenIDConnectError, } from "./oauth/error-codes"; export interface SlackOAuthAppOptions<E extends SlackOAuthEnv> { env: E; installationStore: InstallationStore<E>; stateStore?: StateStore; oauth?: { stateCookieName?: string; beforeInstallation?: BeforeInstallation; afterInstallation?: AfterInstallation; onFailure?: OnFailure; onStateValidationError?: OnStateValidationError; redirectUri?: string; }; oidc?: { stateCookieName?: string; callback: OpenIDConnectCallback; onFailure?: OnFailure; onStateValidationError?: OnStateValidationError; redirectUri?: string; }; routes?: { events: string; oauth: { start: string; callback: string }; oidc?: { start: string; callback: string }; }; } export class SlackOAuthApp<E extends SlackOAuthEnv> extends SlackApp<E> { public env: E; public installationStore: InstallationStore<E>; public stateStore: StateStore; public oauth: { stateCookieName?: string; beforeInstallation?: BeforeInstallation; afterInstallation?: AfterInstallation; onFailure: OnFailure; onStateValidationError: OnStateValidationError; redirectUri?: string; }; public oidc?: { stateCookieName?: string; callback: OpenIDConnectCallback; onFailure: OnFailure; onStateValidationError: OnStateValidationError; redirectUri?: string; }; public routes: { events: string; oauth: { start: string; callback: string }; oidc?: { start: string; callback: string }; }; constructor(options: SlackOAuthAppOptions<E>) { super({ env: options.env, authorize: options.installationStore.toAuthorize(), routes: { events: options.routes?.events ?? "/slack/events" }, }); this.env = options.env; this.installationStore = options.installationStore; this.stateStore =
options.stateStore ?? new NoStorageStateStore();
this.oauth = { stateCookieName: options.oauth?.stateCookieName ?? "slack-app-oauth-state", onFailure: options.oauth?.onFailure ?? defaultOnFailure, onStateValidationError: options.oauth?.onStateValidationError ?? defaultOnStateValidationError, redirectUri: options.oauth?.redirectUri ?? this.env.SLACK_REDIRECT_URI, }; if (options.oidc) { this.oidc = { stateCookieName: options.oidc.stateCookieName ?? "slack-app-oidc-state", onFailure: options.oidc.onFailure ?? defaultOnFailure, onStateValidationError: options.oidc.onStateValidationError ?? defaultOnStateValidationError, callback: defaultOpenIDConnectCallback(this.env), redirectUri: options.oidc.redirectUri ?? this.env.SLACK_OIDC_REDIRECT_URI, }; } else { this.oidc = undefined; } this.routes = options.routes ? options.routes : { events: "/slack/events", oauth: { start: "/slack/install", callback: "/slack/oauth_redirect", }, oidc: { start: "/slack/login", callback: "/slack/login/callback", }, }; } async run( request: Request, ctx: ExecutionContext = new NoopExecutionContext() ): Promise<Response> { const url = new URL(request.url); if (request.method === "GET") { if (url.pathname === this.routes.oauth.start) { return await this.handleOAuthStartRequest(request); } else if (url.pathname === this.routes.oauth.callback) { return await this.handleOAuthCallbackRequest(request); } if (this.routes.oidc) { if (url.pathname === this.routes.oidc.start) { return await this.handleOIDCStartRequest(request); } else if (url.pathname === this.routes.oidc.callback) { return await this.handleOIDCCallbackRequest(request); } } } else if (request.method === "POST") { if (url.pathname === this.routes.events) { return await this.handleEventRequest(request, ctx); } } return new Response("Not found", { status: 404 }); } async handleEventRequest( request: Request, ctx: ExecutionContext ): Promise<Response> { return await super.handleEventRequest(request, ctx); } // deno-lint-ignore no-unused-vars async handleOAuthStartRequest(request: Request): Promise<Response> { const stateValue = await this.stateStore.issueNewState(); const authorizeUrl = generateAuthorizeUrl(stateValue, this.env); return new Response(renderStartPage(authorizeUrl), { status: 302, headers: { Location: authorizeUrl, "Set-Cookie": `${this.oauth.stateCookieName}=${stateValue}; Secure; HttpOnly; Path=/; Max-Age=300`, "Content-Type": "text/html; charset=utf-8", }, }); } async handleOAuthCallbackRequest(request: Request): Promise<Response> { // State parameter validation await this.#validateStateParameter( request, this.routes.oauth.start, this.oauth.stateCookieName! ); const { searchParams } = new URL(request.url); const code = searchParams.get("code"); if (!code) { return await this.oauth.onFailure( this.routes.oauth.start, MissingCode, request ); } const client = new SlackAPIClient(undefined, { logLevel: this.env.SLACK_LOGGING_LEVEL, }); let oauthAccess: OAuthV2AccessResponse | undefined; try { // Execute the installation process oauthAccess = await client.oauth.v2.access({ client_id: this.env.SLACK_CLIENT_ID, client_secret: this.env.SLACK_CLIENT_SECRET, redirect_uri: this.oauth.redirectUri, code, }); } catch (e) { console.log(e); return await this.oauth.onFailure( this.routes.oauth.start, InstallationError, request ); } try { // Store the installation data on this app side await this.installationStore.save(toInstallation(oauthAccess), request); } catch (e) { console.log(e); return await this.oauth.onFailure( this.routes.oauth.start, InstallationStoreError, request ); } try { // Build the completion page const authTest = await client.auth.test({ token: oauthAccess.access_token, }); const enterpriseUrl = authTest.url; return new Response( renderCompletionPage( oauthAccess.app_id!, oauthAccess.team?.id!, oauthAccess.is_enterprise_install, enterpriseUrl ), { status: 200, headers: { "Set-Cookie": `${this.oauth.stateCookieName}=deleted; Secure; HttpOnly; Path=/; Max-Age=0`, "Content-Type": "text/html; charset=utf-8", }, } ); } catch (e) { console.log(e); return await this.oauth.onFailure( this.routes.oauth.start, CompletionPageError, request ); } } // deno-lint-ignore no-unused-vars async handleOIDCStartRequest(request: Request): Promise<Response> { if (!this.oidc) { return new Response("Not found", { status: 404 }); } const stateValue = await this.stateStore.issueNewState(); const authorizeUrl = generateOIDCAuthorizeUrl(stateValue, this.env); return new Response(renderStartPage(authorizeUrl), { status: 302, headers: { Location: authorizeUrl, "Set-Cookie": `${this.oidc.stateCookieName}=${stateValue}; Secure; HttpOnly; Path=/; Max-Age=300`, "Content-Type": "text/html; charset=utf-8", }, }); } async handleOIDCCallbackRequest(request: Request): Promise<Response> { if (!this.oidc || !this.routes.oidc) { return new Response("Not found", { status: 404 }); } // State parameter validation await this.#validateStateParameter( request, this.routes.oidc.start, this.oidc.stateCookieName! ); const { searchParams } = new URL(request.url); const code = searchParams.get("code"); if (!code) { return await this.oidc.onFailure( this.routes.oidc.start, MissingCode, request ); } try { const client = new SlackAPIClient(undefined, { logLevel: this.env.SLACK_LOGGING_LEVEL, }); const apiResponse: OpenIDConnectTokenResponse = await client.openid.connect.token({ client_id: this.env.SLACK_CLIENT_ID, client_secret: this.env.SLACK_CLIENT_SECRET, redirect_uri: this.oidc.redirectUri, code, }); return await this.oidc.callback(apiResponse, request); } catch (e) { console.log(e); return await this.oidc.onFailure( this.routes.oidc.start, OpenIDConnectError, request ); } } async #validateStateParameter( request: Request, startPath: string, cookieName: string ) { const { searchParams } = new URL(request.url); const queryState = searchParams.get("state"); const cookie = parseCookie(request.headers.get("Cookie") || ""); const cookieState = cookie[cookieName]; if ( queryState !== cookieState || !(await this.stateStore.consume(queryState)) ) { if (startPath === this.routes.oauth.start) { return await this.oauth.onStateValidationError(startPath, request); } else if ( this.oidc && this.routes.oidc && startPath === this.routes.oidc.start ) { return await this.oidc.onStateValidationError(startPath, request); } } } }
src/oauth-app.ts
seratch-slack-edge-c75c224
[ { "filename": "src/app.ts", "retrieved_chunk": " }\n this.env = options.env;\n this.client = new SlackAPIClient(options.env.SLACK_BOT_TOKEN, {\n logLevel: this.env.SLACK_LOGGING_LEVEL,\n });\n this.appLevelToken = options.env.SLACK_APP_TOKEN;\n this.socketMode = options.socketMode ?? this.appLevelToken !== undefined;\n if (this.socketMode) {\n this.signingSecret = \"\";\n } else {", "score": 0.8891656398773193 }, { "filename": "src/app.ts", "retrieved_chunk": "export interface SlackAppOptions<\n E extends SlackEdgeAppEnv | SlackSocketModeAppEnv\n> {\n env: E;\n authorize?: Authorize<E>;\n routes?: {\n events: string;\n };\n socketMode?: boolean;\n}", "score": 0.8861120343208313 }, { "filename": "src/app.ts", "retrieved_chunk": "export class SlackApp<E extends SlackEdgeAppEnv | SlackSocketModeAppEnv> {\n public env: E;\n public client: SlackAPIClient;\n public authorize: Authorize<E>;\n public routes: { events: string | undefined };\n public signingSecret: string;\n public appLevelToken: string | undefined;\n public socketMode: boolean;\n public socketModeClient: SocketModeClient | undefined;\n // deno-lint-ignore no-explicit-any", "score": 0.8781325817108154 }, { "filename": "src/app.ts", "retrieved_chunk": " if (!this.env.SLACK_SIGNING_SECRET) {\n throw new ConfigError(\n \"env.SLACK_SIGNING_SECRET is required to run your app on edge functions!\"\n );\n }\n this.signingSecret = this.env.SLACK_SIGNING_SECRET;\n }\n this.authorize = options.authorize ?? singleTeamAuthorize;\n this.routes = { events: options.routes?.events };\n }", "score": 0.8774710893630981 }, { "filename": "src/app.ts", "retrieved_chunk": " ) => SlackViewHandler<E, ViewClosed> | null)[] = [];\n constructor(options: SlackAppOptions<E>) {\n if (\n options.env.SLACK_BOT_TOKEN === undefined &&\n (options.authorize === undefined ||\n options.authorize === singleTeamAuthorize)\n ) {\n throw new ConfigError(\n \"When you don't pass env.SLACK_BOT_TOKEN, your own authorize function, which supplies a valid token to use, needs to be passed instead.\"\n );", "score": 0.8527020215988159 } ]
typescript
options.stateStore ?? new NoStorageStateStore();
import { SlackAppEnv, SlackEdgeAppEnv, SlackSocketModeAppEnv } from "./app-env"; import { parseRequestBody } from "./request/request-parser"; import { verifySlackRequest } from "./request/request-verification"; import { AckResponse, SlackHandler } from "./handler/handler"; import { SlackRequestBody } from "./request/request-body"; import { PreAuthorizeSlackMiddlwareRequest, SlackRequestWithRespond, SlackMiddlwareRequest, SlackRequestWithOptionalRespond, SlackRequest, SlackRequestWithChannelId, } from "./request/request"; import { SlashCommand } from "./request/payload/slash-command"; import { toCompleteResponse } from "./response/response"; import { SlackEvent, AnySlackEvent, AnySlackEventWithChannelId, } from "./request/payload/event"; import { ResponseUrlSender, SlackAPIClient } from "slack-web-api-client"; import { builtBaseContext, SlackAppContext, SlackAppContextWithChannelId, SlackAppContextWithRespond, } from "./context/context"; import { PreAuthorizeMiddleware, Middleware } from "./middleware/middleware"; import { isDebugLogEnabled, prettyPrint } from "slack-web-api-client"; import { Authorize } from "./authorization/authorize"; import { AuthorizeResult } from "./authorization/authorize-result"; import { ignoringSelfEvents, urlVerification, } from "./middleware/built-in-middleware"; import { ConfigError } from "./errors"; import { GlobalShortcut } from "./request/payload/global-shortcut"; import { MessageShortcut } from "./request/payload/message-shortcut"; import { BlockAction, BlockElementAction, BlockElementTypes, } from "./request/payload/block-action"; import { ViewSubmission } from "./request/payload/view-submission"; import { ViewClosed } from "./request/payload/view-closed"; import { BlockSuggestion } from "./request/payload/block-suggestion"; import { OptionsAckResponse, SlackOptionsHandler, } from "./handler/options-handler"; import { SlackViewHandler, ViewAckResponse } from "./handler/view-handler"; import { MessageAckResponse, SlackMessageHandler, } from "./handler/message-handler"; import { singleTeamAuthorize } from "./authorization/single-team-authorize"; import { ExecutionContext, NoopExecutionContext } from "./execution-context"; import { PayloadType } from "./request/payload-types"; import { isPostedMessageEvent } from "./utility/message-events"; import { SocketModeClient } from "./socket-mode/socket-mode-client"; export interface SlackAppOptions< E extends SlackEdgeAppEnv | SlackSocketModeAppEnv > { env: E; authorize?: Authorize<E>; routes?: { events: string; }; socketMode?: boolean; } export class SlackApp<E extends SlackEdgeAppEnv | SlackSocketModeAppEnv> { public env: E; public client: SlackAPIClient; public authorize: Authorize<E>; public routes: { events: string | undefined }; public signingSecret: string; public appLevelToken: string | undefined; public socketMode: boolean; public socketModeClient: SocketModeClient | undefined; // deno-lint-ignore no-explicit-any public preAuthorizeMiddleware: PreAuthorizeMiddleware<any>[] = [ urlVerification, ]; // deno-lint-ignore no-explicit-any public postAuthorizeMiddleware: Middleware<any>[] = [ignoringSelfEvents]; #slashCommands: (( body: SlackRequestBody ) => SlackMessageHandler<E, SlashCommand> | null)[] = []; #events: (( body: SlackRequestBody )
=> SlackHandler<E, SlackEvent<string>> | null)[] = [];
#globalShorcuts: (( body: SlackRequestBody ) => SlackHandler<E, GlobalShortcut> | null)[] = []; #messageShorcuts: (( body: SlackRequestBody ) => SlackHandler<E, MessageShortcut> | null)[] = []; #blockActions: ((body: SlackRequestBody) => SlackHandler< E, // deno-lint-ignore no-explicit-any BlockAction<any> > | null)[] = []; #blockSuggestions: (( body: SlackRequestBody ) => SlackOptionsHandler<E, BlockSuggestion> | null)[] = []; #viewSubmissions: (( body: SlackRequestBody ) => SlackViewHandler<E, ViewSubmission> | null)[] = []; #viewClosed: (( body: SlackRequestBody ) => SlackViewHandler<E, ViewClosed> | null)[] = []; constructor(options: SlackAppOptions<E>) { if ( options.env.SLACK_BOT_TOKEN === undefined && (options.authorize === undefined || options.authorize === singleTeamAuthorize) ) { throw new ConfigError( "When you don't pass env.SLACK_BOT_TOKEN, your own authorize function, which supplies a valid token to use, needs to be passed instead." ); } this.env = options.env; this.client = new SlackAPIClient(options.env.SLACK_BOT_TOKEN, { logLevel: this.env.SLACK_LOGGING_LEVEL, }); this.appLevelToken = options.env.SLACK_APP_TOKEN; this.socketMode = options.socketMode ?? this.appLevelToken !== undefined; if (this.socketMode) { this.signingSecret = ""; } else { if (!this.env.SLACK_SIGNING_SECRET) { throw new ConfigError( "env.SLACK_SIGNING_SECRET is required to run your app on edge functions!" ); } this.signingSecret = this.env.SLACK_SIGNING_SECRET; } this.authorize = options.authorize ?? singleTeamAuthorize; this.routes = { events: options.routes?.events }; } beforeAuthorize(middleware: PreAuthorizeMiddleware<E>): SlackApp<E> { this.preAuthorizeMiddleware.push(middleware); return this; } middleware(middleware: Middleware<E>): SlackApp<E> { return this.afterAuthorize(middleware); } use(middleware: Middleware<E>): SlackApp<E> { return this.afterAuthorize(middleware); } afterAuthorize(middleware: Middleware<E>): SlackApp<E> { this.postAuthorizeMiddleware.push(middleware); return this; } command( pattern: StringOrRegExp, ack: ( req: SlackRequestWithRespond<E, SlashCommand> ) => Promise<MessageAckResponse>, lazy: ( req: SlackRequestWithRespond<E, SlashCommand> ) => Promise<void> = noopLazyListener ): SlackApp<E> { const handler: SlackMessageHandler<E, SlashCommand> = { ack, lazy }; this.#slashCommands.push((body) => { if (body.type || !body.command) { return null; } if (typeof pattern === "string" && body.command === pattern) { return handler; } else if ( typeof pattern === "object" && pattern instanceof RegExp && body.command.match(pattern) ) { return handler; } return null; }); return this; } event<Type extends string>( event: Type, lazy: (req: EventRequest<E, Type>) => Promise<void> ): SlackApp<E> { this.#events.push((body) => { if (body.type !== PayloadType.EventsAPI || !body.event) { return null; } if (body.event.type === event) { // deno-lint-ignore require-await return { ack: async () => "", lazy }; } return null; }); return this; } anyMessage(lazy: MessageEventHandler<E>): SlackApp<E> { return this.message(undefined, lazy); } message( pattern: MessageEventPattern, lazy: MessageEventHandler<E> ): SlackApp<E> { this.#events.push((body) => { if ( body.type !== PayloadType.EventsAPI || !body.event || body.event.type !== "message" ) { return null; } if (isPostedMessageEvent(body.event)) { let matched = true; if (pattern !== undefined) { if (typeof pattern === "string") { matched = body.event.text!.includes(pattern); } if (typeof pattern === "object") { matched = body.event.text!.match(pattern) !== null; } } if (matched) { // deno-lint-ignore require-await return { ack: async (_: EventRequest<E, "message">) => "", lazy }; } } return null; }); return this; } shortcut( callbackId: StringOrRegExp, ack: ( req: | SlackRequest<E, GlobalShortcut> | SlackRequestWithRespond<E, MessageShortcut> ) => Promise<AckResponse>, lazy: ( req: | SlackRequest<E, GlobalShortcut> | SlackRequestWithRespond<E, MessageShortcut> ) => Promise<void> = noopLazyListener ): SlackApp<E> { return this.globalShortcut(callbackId, ack, lazy).messageShortcut( callbackId, ack, lazy ); } globalShortcut( callbackId: StringOrRegExp, ack: (req: SlackRequest<E, GlobalShortcut>) => Promise<AckResponse>, lazy: ( req: SlackRequest<E, GlobalShortcut> ) => Promise<void> = noopLazyListener ): SlackApp<E> { const handler: SlackHandler<E, GlobalShortcut> = { ack, lazy }; this.#globalShorcuts.push((body) => { if (body.type !== PayloadType.GlobalShortcut || !body.callback_id) { return null; } if (typeof callbackId === "string" && body.callback_id === callbackId) { return handler; } else if ( typeof callbackId === "object" && callbackId instanceof RegExp && body.callback_id.match(callbackId) ) { return handler; } return null; }); return this; } messageShortcut( callbackId: StringOrRegExp, ack: ( req: SlackRequestWithRespond<E, MessageShortcut> ) => Promise<AckResponse>, lazy: ( req: SlackRequestWithRespond<E, MessageShortcut> ) => Promise<void> = noopLazyListener ): SlackApp<E> { const handler: SlackHandler<E, MessageShortcut> = { ack, lazy }; this.#messageShorcuts.push((body) => { if (body.type !== PayloadType.MessageShortcut || !body.callback_id) { return null; } if (typeof callbackId === "string" && body.callback_id === callbackId) { return handler; } else if ( typeof callbackId === "object" && callbackId instanceof RegExp && body.callback_id.match(callbackId) ) { return handler; } return null; }); return this; } action< T extends BlockElementTypes, A extends BlockAction<BlockElementAction<T>> = BlockAction< BlockElementAction<T> > >( constraints: | StringOrRegExp | { type: T; block_id?: string; action_id: string }, ack: (req: SlackRequestWithOptionalRespond<E, A>) => Promise<AckResponse>, lazy: ( req: SlackRequestWithOptionalRespond<E, A> ) => Promise<void> = noopLazyListener ): SlackApp<E> { const handler: SlackHandler<E, A> = { ack, lazy }; this.#blockActions.push((body) => { if ( body.type !== PayloadType.BlockAction || !body.actions || !body.actions[0] ) { return null; } const action = body.actions[0]; if (typeof constraints === "string" && action.action_id === constraints) { return handler; } else if (typeof constraints === "object") { if (constraints instanceof RegExp) { if (action.action_id.match(constraints)) { return handler; } } else if (constraints.type) { if (action.type === constraints.type) { if (action.action_id === constraints.action_id) { if ( constraints.block_id && action.block_id !== constraints.block_id ) { return null; } return handler; } } } } return null; }); return this; } options( constraints: StringOrRegExp | { block_id?: string; action_id: string }, ack: (req: SlackRequest<E, BlockSuggestion>) => Promise<OptionsAckResponse> ): SlackApp<E> { // Note that block_suggestion response must be done within 3 seconds. // So, we don't support the lazy handler for it. const handler: SlackOptionsHandler<E, BlockSuggestion> = { ack }; this.#blockSuggestions.push((body) => { if (body.type !== PayloadType.BlockSuggestion || !body.action_id) { return null; } if (typeof constraints === "string" && body.action_id === constraints) { return handler; } else if (typeof constraints === "object") { if (constraints instanceof RegExp) { if (body.action_id.match(constraints)) { return handler; } } else { if (body.action_id === constraints.action_id) { if (body.block_id && body.block_id !== constraints.block_id) { return null; } return handler; } } } return null; }); return this; } view( callbackId: StringOrRegExp, ack: ( req: | SlackRequestWithOptionalRespond<E, ViewSubmission> | SlackRequest<E, ViewClosed> ) => Promise<ViewAckResponse>, lazy: ( req: | SlackRequestWithOptionalRespond<E, ViewSubmission> | SlackRequest<E, ViewClosed> ) => Promise<void> = noopLazyListener ): SlackApp<E> { return this.viewSubmission(callbackId, ack, lazy).viewClosed( callbackId, ack, lazy ); } viewSubmission( callbackId: StringOrRegExp, ack: ( req: SlackRequestWithOptionalRespond<E, ViewSubmission> ) => Promise<ViewAckResponse>, lazy: ( req: SlackRequestWithOptionalRespond<E, ViewSubmission> ) => Promise<void> = noopLazyListener ): SlackApp<E> { const handler: SlackViewHandler<E, ViewSubmission> = { ack, lazy }; this.#viewSubmissions.push((body) => { if (body.type !== PayloadType.ViewSubmission || !body.view) { return null; } if ( typeof callbackId === "string" && body.view.callback_id === callbackId ) { return handler; } else if ( typeof callbackId === "object" && callbackId instanceof RegExp && body.view.callback_id.match(callbackId) ) { return handler; } return null; }); return this; } viewClosed( callbackId: StringOrRegExp, ack: (req: SlackRequest<E, ViewClosed>) => Promise<ViewAckResponse>, lazy: (req: SlackRequest<E, ViewClosed>) => Promise<void> = noopLazyListener ): SlackApp<E> { const handler: SlackViewHandler<E, ViewClosed> = { ack, lazy }; this.#viewClosed.push((body) => { if (body.type !== PayloadType.ViewClosed || !body.view) { return null; } if ( typeof callbackId === "string" && body.view.callback_id === callbackId ) { return handler; } else if ( typeof callbackId === "object" && callbackId instanceof RegExp && body.view.callback_id.match(callbackId) ) { return handler; } return null; }); return this; } async run( request: Request, ctx: ExecutionContext = new NoopExecutionContext() ): Promise<Response> { return await this.handleEventRequest(request, ctx); } async connect(): Promise<void> { if (!this.socketMode) { throw new ConfigError( "Both env.SLACK_APP_TOKEN and socketMode: true are required to start a Socket Mode connection!" ); } this.socketModeClient = new SocketModeClient(this); await this.socketModeClient.connect(); } async disconnect(): Promise<void> { if (this.socketModeClient) { await this.socketModeClient.disconnect(); } } async handleEventRequest( request: Request, ctx: ExecutionContext ): Promise<Response> { // If the routes.events is missing, any URLs can work for handing requests from Slack if (this.routes.events) { const { pathname } = new URL(request.url); if (pathname !== this.routes.events) { return new Response("Not found", { status: 404 }); } } // To avoid the following warning by Cloudflware, parse the body as Blob first // Called .text() on an HTTP body which does not appear to be text .. const blobRequestBody = await request.blob(); // We can safely assume the incoming request body is always text data const rawBody: string = await blobRequestBody.text(); // For Request URL verification if (rawBody.includes("ssl_check=")) { // Slack does not send the x-slack-signature header for this pattern. // Thus, we need to check the pattern before verifying a request. const bodyParams = new URLSearchParams(rawBody); if (bodyParams.get("ssl_check") === "1" && bodyParams.get("token")) { return new Response("", { status: 200 }); } } // Verify the request headers and body const isRequestSignatureVerified = this.socketMode || (await verifySlackRequest(this.signingSecret, request.headers, rawBody)); if (isRequestSignatureVerified) { // deno-lint-ignore no-explicit-any const body: Record<string, any> = await parseRequestBody( request.headers, rawBody ); let retryNum: number | undefined = undefined; try { const retryNumHeader = request.headers.get("x-slack-retry-num"); if (retryNumHeader) { retryNum = Number.parseInt(retryNumHeader); } else if (this.socketMode && body.retry_attempt) { retryNum = Number.parseInt(body.retry_attempt); } // deno-lint-ignore no-unused-vars } catch (e) { // Ignore an exception here } const retryReason = request.headers.get("x-slack-retry-reason") ?? body.retry_reason; const preAuthorizeRequest: PreAuthorizeSlackMiddlwareRequest<E> = { body, rawBody, retryNum, retryReason, context: builtBaseContext(body), env: this.env, headers: request.headers, }; if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log(`*** Received request body ***\n ${prettyPrint(body)}`); } for (const middlware of this.preAuthorizeMiddleware) { const response = await middlware(preAuthorizeRequest); if (response) { return toCompleteResponse(response); } } const authorizeResult: AuthorizeResult = await this.authorize( preAuthorizeRequest ); const authorizedContext: SlackAppContext = { ...preAuthorizeRequest.context, authorizeResult, client: new SlackAPIClient(authorizeResult.botToken, { logLevel: this.env.SLACK_LOGGING_LEVEL, }), botToken: authorizeResult.botToken, botId: authorizeResult.botId, botUserId: authorizeResult.botUserId, userToken: authorizeResult.userToken, }; if (authorizedContext.channelId) { const context = authorizedContext as SlackAppContextWithChannelId; const client = new SlackAPIClient(context.botToken); context.say = async (params) => await client.chat.postMessage({ channel: context.channelId, ...params, }); } if (authorizedContext.responseUrl) { const responseUrl = authorizedContext.responseUrl; // deno-lint-ignore require-await (authorizedContext as SlackAppContextWithRespond).respond = async ( params ) => { return new ResponseUrlSender(responseUrl).call(params); }; } const baseRequest: SlackMiddlwareRequest<E> = { ...preAuthorizeRequest, context: authorizedContext, }; for (const middlware of this.postAuthorizeMiddleware) { const response = await middlware(baseRequest); if (response) { return toCompleteResponse(response); } } const payload = body as SlackRequestBody; if (body.type === PayloadType.EventsAPI) { // Events API const slackRequest: SlackRequest<E, SlackEvent<string>> = { payload: body.event, ...baseRequest, }; for (const matcher of this.#events) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (!body.type && body.command) { // Slash commands const slackRequest: SlackRequest<E, SlashCommand> = { payload: body as SlashCommand, ...baseRequest, }; for (const matcher of this.#slashCommands) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (body.type === PayloadType.GlobalShortcut) { // Global shortcuts const slackRequest: SlackRequest<E, GlobalShortcut> = { payload: body as GlobalShortcut, ...baseRequest, }; for (const matcher of this.#globalShorcuts) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (body.type === PayloadType.MessageShortcut) { // Message shortcuts const slackRequest: SlackRequest<E, MessageShortcut> = { payload: body as MessageShortcut, ...baseRequest, }; for (const matcher of this.#messageShorcuts) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (body.type === PayloadType.BlockAction) { // Block actions // deno-lint-ignore no-explicit-any const slackRequest: SlackRequest<E, BlockAction<any>> = { // deno-lint-ignore no-explicit-any payload: body as BlockAction<any>, ...baseRequest, }; for (const matcher of this.#blockActions) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (body.type === PayloadType.BlockSuggestion) { // Block suggestions const slackRequest: SlackRequest<E, BlockSuggestion> = { payload: body as BlockSuggestion, ...baseRequest, }; for (const matcher of this.#blockSuggestions) { const handler = matcher(payload); if (handler) { // Note that the only way to respond to a block_suggestion request // is to send an HTTP response with options/option_groups. // Thus, we don't support lazy handlers for this pattern. const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (body.type === PayloadType.ViewSubmission) { // View submissions const slackRequest: SlackRequest<E, ViewSubmission> = { payload: body as ViewSubmission, ...baseRequest, }; for (const matcher of this.#viewSubmissions) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (body.type === PayloadType.ViewClosed) { // View closed const slackRequest: SlackRequest<E, ViewClosed> = { payload: body as ViewClosed, ...baseRequest, }; for (const matcher of this.#viewClosed) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } // TODO: Add code suggestion here console.log( `*** No listener found ***\n${JSON.stringify(baseRequest.body)}` ); return new Response("No listener found", { status: 404 }); } return new Response("Invalid signature", { status: 401 }); } } export type StringOrRegExp = string | RegExp; export type EventRequest<E extends SlackAppEnv, T> = Extract< AnySlackEventWithChannelId, { type: T } > extends never ? SlackRequest<E, Extract<AnySlackEvent, { type: T }>> : SlackRequestWithChannelId< E, Extract<AnySlackEventWithChannelId, { type: T }> >; export type MessageEventPattern = string | RegExp | undefined; export type MessageEventRequest< E extends SlackAppEnv, ST extends string | undefined > = SlackRequestWithChannelId< E, Extract<AnySlackEventWithChannelId, { subtype: ST }> >; export type MessageEventSubtypes = | undefined | "bot_message" | "thread_broadcast" | "file_share"; export type MessageEventHandler<E extends SlackAppEnv> = ( req: MessageEventRequest<E, MessageEventSubtypes> ) => Promise<void>; export const noopLazyListener = async () => {};
src/app.ts
seratch-slack-edge-c75c224
[ { "filename": "src/middleware/built-in-middleware.ts", "retrieved_chunk": "import { PreAuthorizeMiddleware, Middleware } from \"./middleware\";\n// deno-lint-ignore require-await\nexport const urlVerification: PreAuthorizeMiddleware = async (req) => {\n if (req.body.type === \"url_verification\") {\n return { status: 200, body: req.body.challenge };\n }\n};\nconst eventTypesToKeep = [\"member_joined_channel\", \"member_left_channel\"];\n// deno-lint-ignore require-await\nexport const ignoringSelfEvents: Middleware = async (req) => {", "score": 0.8549148440361023 }, { "filename": "src/request/request.ts", "retrieved_chunk": " context: PreAuthorizeSlackAppContext;\n // deno-lint-ignore no-explicit-any\n body: Record<string, any>;\n retryNum?: number;\n retryReason?: string;\n rawBody: string;\n headers: Headers;\n}\nexport type PreAuthorizeSlackMiddlwareRequest<E extends SlackAppEnv> =\n SlackMiddlewareRequestBase<E> & {", "score": 0.8425491452217102 }, { "filename": "src/context/context.ts", "retrieved_chunk": " // deno-lint-ignore no-explicit-any\n [key: string]: any; // custom properties\n };\n}\nexport type SlackAppContext = {\n client: SlackAPIClient;\n botToken: string;\n userToken?: string;\n authorizeResult: AuthorizeResult;\n} & PreAuthorizeSlackAppContext;", "score": 0.8376249074935913 }, { "filename": "src/middleware/middleware.ts", "retrieved_chunk": "import { SlackAppEnv } from \"../app-env\";\nimport {\n PreAuthorizeSlackMiddlwareRequest,\n SlackMiddlwareRequest,\n} from \"../request/request\";\nimport { SlackResponse } from \"../response/response\";\nexport type PreAuthorizeMiddleware<E extends SlackAppEnv = SlackAppEnv> = (\n req: PreAuthorizeSlackMiddlwareRequest<E>\n) => Promise<SlackResponse | void>;\nexport type Middleware<E extends SlackAppEnv = SlackAppEnv> = (", "score": 0.8282350301742554 }, { "filename": "src/request/request-body.ts", "retrieved_chunk": "export interface SlackRequestBody {\n type?: string;\n // slash commands\n command?: string;\n // event_callback\n event?: {\n type: string;\n subtype?: string;\n text?: string;\n };", "score": 0.8275654315948486 } ]
typescript
=> SlackHandler<E, SlackEvent<string>> | null)[] = [];
import { SlackAppEnv, SlackEdgeAppEnv, SlackSocketModeAppEnv } from "./app-env"; import { parseRequestBody } from "./request/request-parser"; import { verifySlackRequest } from "./request/request-verification"; import { AckResponse, SlackHandler } from "./handler/handler"; import { SlackRequestBody } from "./request/request-body"; import { PreAuthorizeSlackMiddlwareRequest, SlackRequestWithRespond, SlackMiddlwareRequest, SlackRequestWithOptionalRespond, SlackRequest, SlackRequestWithChannelId, } from "./request/request"; import { SlashCommand } from "./request/payload/slash-command"; import { toCompleteResponse } from "./response/response"; import { SlackEvent, AnySlackEvent, AnySlackEventWithChannelId, } from "./request/payload/event"; import { ResponseUrlSender, SlackAPIClient } from "slack-web-api-client"; import { builtBaseContext, SlackAppContext, SlackAppContextWithChannelId, SlackAppContextWithRespond, } from "./context/context"; import { PreAuthorizeMiddleware, Middleware } from "./middleware/middleware"; import { isDebugLogEnabled, prettyPrint } from "slack-web-api-client"; import { Authorize } from "./authorization/authorize"; import { AuthorizeResult } from "./authorization/authorize-result"; import { ignoringSelfEvents, urlVerification, } from "./middleware/built-in-middleware"; import { ConfigError } from "./errors"; import { GlobalShortcut } from "./request/payload/global-shortcut"; import { MessageShortcut } from "./request/payload/message-shortcut"; import { BlockAction, BlockElementAction, BlockElementTypes, } from "./request/payload/block-action"; import { ViewSubmission } from "./request/payload/view-submission"; import { ViewClosed } from "./request/payload/view-closed"; import { BlockSuggestion } from "./request/payload/block-suggestion"; import { OptionsAckResponse, SlackOptionsHandler, } from "./handler/options-handler"; import { SlackViewHandler, ViewAckResponse } from "./handler/view-handler"; import { MessageAckResponse, SlackMessageHandler, } from "./handler/message-handler"; import { singleTeamAuthorize } from "./authorization/single-team-authorize"; import { ExecutionContext, NoopExecutionContext } from "./execution-context"; import { PayloadType } from "./request/payload-types"; import { isPostedMessageEvent } from "./utility/message-events"; import { SocketModeClient } from "./socket-mode/socket-mode-client"; export interface SlackAppOptions< E extends SlackEdgeAppEnv | SlackSocketModeAppEnv > { env: E; authorize?: Authorize<E>; routes?: { events: string; }; socketMode?: boolean; } export class SlackApp<E extends SlackEdgeAppEnv | SlackSocketModeAppEnv> { public env: E; public client: SlackAPIClient; public authorize: Authorize<E>; public routes: { events: string | undefined }; public signingSecret: string; public appLevelToken: string | undefined; public socketMode: boolean; public socketModeClient: SocketModeClient | undefined; // deno-lint-ignore no-explicit-any public preAuthorizeMiddleware: PreAuthorizeMiddleware<any>[] = [ urlVerification, ]; // deno-lint-ignore no-explicit-any public postAuthorizeMiddleware: Middleware<any>[] = [ignoringSelfEvents]; #slashCommands: (( body: SlackRequestBody ) => SlackMessageHandler<E, SlashCommand> | null)[] = []; #events: (( body: SlackRequestBody ) => SlackHandler<E, SlackEvent<string>> | null)[] = []; #globalShorcuts: (( body: SlackRequestBody ) => SlackHandler<E, GlobalShortcut> | null)[] = []; #messageShorcuts: (( body: SlackRequestBody ) => SlackHandler<E, MessageShortcut> | null)[] = []; #blockActions: ((body: SlackRequestBody) => SlackHandler< E, // deno-lint-ignore no-explicit-any BlockAction<any> > | null)[] = []; #blockSuggestions: (( body: SlackRequestBody ) => SlackOptionsHandler<E, BlockSuggestion> | null)[] = []; #viewSubmissions: (( body: SlackRequestBody
) => SlackViewHandler<E, ViewSubmission> | null)[] = [];
#viewClosed: (( body: SlackRequestBody ) => SlackViewHandler<E, ViewClosed> | null)[] = []; constructor(options: SlackAppOptions<E>) { if ( options.env.SLACK_BOT_TOKEN === undefined && (options.authorize === undefined || options.authorize === singleTeamAuthorize) ) { throw new ConfigError( "When you don't pass env.SLACK_BOT_TOKEN, your own authorize function, which supplies a valid token to use, needs to be passed instead." ); } this.env = options.env; this.client = new SlackAPIClient(options.env.SLACK_BOT_TOKEN, { logLevel: this.env.SLACK_LOGGING_LEVEL, }); this.appLevelToken = options.env.SLACK_APP_TOKEN; this.socketMode = options.socketMode ?? this.appLevelToken !== undefined; if (this.socketMode) { this.signingSecret = ""; } else { if (!this.env.SLACK_SIGNING_SECRET) { throw new ConfigError( "env.SLACK_SIGNING_SECRET is required to run your app on edge functions!" ); } this.signingSecret = this.env.SLACK_SIGNING_SECRET; } this.authorize = options.authorize ?? singleTeamAuthorize; this.routes = { events: options.routes?.events }; } beforeAuthorize(middleware: PreAuthorizeMiddleware<E>): SlackApp<E> { this.preAuthorizeMiddleware.push(middleware); return this; } middleware(middleware: Middleware<E>): SlackApp<E> { return this.afterAuthorize(middleware); } use(middleware: Middleware<E>): SlackApp<E> { return this.afterAuthorize(middleware); } afterAuthorize(middleware: Middleware<E>): SlackApp<E> { this.postAuthorizeMiddleware.push(middleware); return this; } command( pattern: StringOrRegExp, ack: ( req: SlackRequestWithRespond<E, SlashCommand> ) => Promise<MessageAckResponse>, lazy: ( req: SlackRequestWithRespond<E, SlashCommand> ) => Promise<void> = noopLazyListener ): SlackApp<E> { const handler: SlackMessageHandler<E, SlashCommand> = { ack, lazy }; this.#slashCommands.push((body) => { if (body.type || !body.command) { return null; } if (typeof pattern === "string" && body.command === pattern) { return handler; } else if ( typeof pattern === "object" && pattern instanceof RegExp && body.command.match(pattern) ) { return handler; } return null; }); return this; } event<Type extends string>( event: Type, lazy: (req: EventRequest<E, Type>) => Promise<void> ): SlackApp<E> { this.#events.push((body) => { if (body.type !== PayloadType.EventsAPI || !body.event) { return null; } if (body.event.type === event) { // deno-lint-ignore require-await return { ack: async () => "", lazy }; } return null; }); return this; } anyMessage(lazy: MessageEventHandler<E>): SlackApp<E> { return this.message(undefined, lazy); } message( pattern: MessageEventPattern, lazy: MessageEventHandler<E> ): SlackApp<E> { this.#events.push((body) => { if ( body.type !== PayloadType.EventsAPI || !body.event || body.event.type !== "message" ) { return null; } if (isPostedMessageEvent(body.event)) { let matched = true; if (pattern !== undefined) { if (typeof pattern === "string") { matched = body.event.text!.includes(pattern); } if (typeof pattern === "object") { matched = body.event.text!.match(pattern) !== null; } } if (matched) { // deno-lint-ignore require-await return { ack: async (_: EventRequest<E, "message">) => "", lazy }; } } return null; }); return this; } shortcut( callbackId: StringOrRegExp, ack: ( req: | SlackRequest<E, GlobalShortcut> | SlackRequestWithRespond<E, MessageShortcut> ) => Promise<AckResponse>, lazy: ( req: | SlackRequest<E, GlobalShortcut> | SlackRequestWithRespond<E, MessageShortcut> ) => Promise<void> = noopLazyListener ): SlackApp<E> { return this.globalShortcut(callbackId, ack, lazy).messageShortcut( callbackId, ack, lazy ); } globalShortcut( callbackId: StringOrRegExp, ack: (req: SlackRequest<E, GlobalShortcut>) => Promise<AckResponse>, lazy: ( req: SlackRequest<E, GlobalShortcut> ) => Promise<void> = noopLazyListener ): SlackApp<E> { const handler: SlackHandler<E, GlobalShortcut> = { ack, lazy }; this.#globalShorcuts.push((body) => { if (body.type !== PayloadType.GlobalShortcut || !body.callback_id) { return null; } if (typeof callbackId === "string" && body.callback_id === callbackId) { return handler; } else if ( typeof callbackId === "object" && callbackId instanceof RegExp && body.callback_id.match(callbackId) ) { return handler; } return null; }); return this; } messageShortcut( callbackId: StringOrRegExp, ack: ( req: SlackRequestWithRespond<E, MessageShortcut> ) => Promise<AckResponse>, lazy: ( req: SlackRequestWithRespond<E, MessageShortcut> ) => Promise<void> = noopLazyListener ): SlackApp<E> { const handler: SlackHandler<E, MessageShortcut> = { ack, lazy }; this.#messageShorcuts.push((body) => { if (body.type !== PayloadType.MessageShortcut || !body.callback_id) { return null; } if (typeof callbackId === "string" && body.callback_id === callbackId) { return handler; } else if ( typeof callbackId === "object" && callbackId instanceof RegExp && body.callback_id.match(callbackId) ) { return handler; } return null; }); return this; } action< T extends BlockElementTypes, A extends BlockAction<BlockElementAction<T>> = BlockAction< BlockElementAction<T> > >( constraints: | StringOrRegExp | { type: T; block_id?: string; action_id: string }, ack: (req: SlackRequestWithOptionalRespond<E, A>) => Promise<AckResponse>, lazy: ( req: SlackRequestWithOptionalRespond<E, A> ) => Promise<void> = noopLazyListener ): SlackApp<E> { const handler: SlackHandler<E, A> = { ack, lazy }; this.#blockActions.push((body) => { if ( body.type !== PayloadType.BlockAction || !body.actions || !body.actions[0] ) { return null; } const action = body.actions[0]; if (typeof constraints === "string" && action.action_id === constraints) { return handler; } else if (typeof constraints === "object") { if (constraints instanceof RegExp) { if (action.action_id.match(constraints)) { return handler; } } else if (constraints.type) { if (action.type === constraints.type) { if (action.action_id === constraints.action_id) { if ( constraints.block_id && action.block_id !== constraints.block_id ) { return null; } return handler; } } } } return null; }); return this; } options( constraints: StringOrRegExp | { block_id?: string; action_id: string }, ack: (req: SlackRequest<E, BlockSuggestion>) => Promise<OptionsAckResponse> ): SlackApp<E> { // Note that block_suggestion response must be done within 3 seconds. // So, we don't support the lazy handler for it. const handler: SlackOptionsHandler<E, BlockSuggestion> = { ack }; this.#blockSuggestions.push((body) => { if (body.type !== PayloadType.BlockSuggestion || !body.action_id) { return null; } if (typeof constraints === "string" && body.action_id === constraints) { return handler; } else if (typeof constraints === "object") { if (constraints instanceof RegExp) { if (body.action_id.match(constraints)) { return handler; } } else { if (body.action_id === constraints.action_id) { if (body.block_id && body.block_id !== constraints.block_id) { return null; } return handler; } } } return null; }); return this; } view( callbackId: StringOrRegExp, ack: ( req: | SlackRequestWithOptionalRespond<E, ViewSubmission> | SlackRequest<E, ViewClosed> ) => Promise<ViewAckResponse>, lazy: ( req: | SlackRequestWithOptionalRespond<E, ViewSubmission> | SlackRequest<E, ViewClosed> ) => Promise<void> = noopLazyListener ): SlackApp<E> { return this.viewSubmission(callbackId, ack, lazy).viewClosed( callbackId, ack, lazy ); } viewSubmission( callbackId: StringOrRegExp, ack: ( req: SlackRequestWithOptionalRespond<E, ViewSubmission> ) => Promise<ViewAckResponse>, lazy: ( req: SlackRequestWithOptionalRespond<E, ViewSubmission> ) => Promise<void> = noopLazyListener ): SlackApp<E> { const handler: SlackViewHandler<E, ViewSubmission> = { ack, lazy }; this.#viewSubmissions.push((body) => { if (body.type !== PayloadType.ViewSubmission || !body.view) { return null; } if ( typeof callbackId === "string" && body.view.callback_id === callbackId ) { return handler; } else if ( typeof callbackId === "object" && callbackId instanceof RegExp && body.view.callback_id.match(callbackId) ) { return handler; } return null; }); return this; } viewClosed( callbackId: StringOrRegExp, ack: (req: SlackRequest<E, ViewClosed>) => Promise<ViewAckResponse>, lazy: (req: SlackRequest<E, ViewClosed>) => Promise<void> = noopLazyListener ): SlackApp<E> { const handler: SlackViewHandler<E, ViewClosed> = { ack, lazy }; this.#viewClosed.push((body) => { if (body.type !== PayloadType.ViewClosed || !body.view) { return null; } if ( typeof callbackId === "string" && body.view.callback_id === callbackId ) { return handler; } else if ( typeof callbackId === "object" && callbackId instanceof RegExp && body.view.callback_id.match(callbackId) ) { return handler; } return null; }); return this; } async run( request: Request, ctx: ExecutionContext = new NoopExecutionContext() ): Promise<Response> { return await this.handleEventRequest(request, ctx); } async connect(): Promise<void> { if (!this.socketMode) { throw new ConfigError( "Both env.SLACK_APP_TOKEN and socketMode: true are required to start a Socket Mode connection!" ); } this.socketModeClient = new SocketModeClient(this); await this.socketModeClient.connect(); } async disconnect(): Promise<void> { if (this.socketModeClient) { await this.socketModeClient.disconnect(); } } async handleEventRequest( request: Request, ctx: ExecutionContext ): Promise<Response> { // If the routes.events is missing, any URLs can work for handing requests from Slack if (this.routes.events) { const { pathname } = new URL(request.url); if (pathname !== this.routes.events) { return new Response("Not found", { status: 404 }); } } // To avoid the following warning by Cloudflware, parse the body as Blob first // Called .text() on an HTTP body which does not appear to be text .. const blobRequestBody = await request.blob(); // We can safely assume the incoming request body is always text data const rawBody: string = await blobRequestBody.text(); // For Request URL verification if (rawBody.includes("ssl_check=")) { // Slack does not send the x-slack-signature header for this pattern. // Thus, we need to check the pattern before verifying a request. const bodyParams = new URLSearchParams(rawBody); if (bodyParams.get("ssl_check") === "1" && bodyParams.get("token")) { return new Response("", { status: 200 }); } } // Verify the request headers and body const isRequestSignatureVerified = this.socketMode || (await verifySlackRequest(this.signingSecret, request.headers, rawBody)); if (isRequestSignatureVerified) { // deno-lint-ignore no-explicit-any const body: Record<string, any> = await parseRequestBody( request.headers, rawBody ); let retryNum: number | undefined = undefined; try { const retryNumHeader = request.headers.get("x-slack-retry-num"); if (retryNumHeader) { retryNum = Number.parseInt(retryNumHeader); } else if (this.socketMode && body.retry_attempt) { retryNum = Number.parseInt(body.retry_attempt); } // deno-lint-ignore no-unused-vars } catch (e) { // Ignore an exception here } const retryReason = request.headers.get("x-slack-retry-reason") ?? body.retry_reason; const preAuthorizeRequest: PreAuthorizeSlackMiddlwareRequest<E> = { body, rawBody, retryNum, retryReason, context: builtBaseContext(body), env: this.env, headers: request.headers, }; if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log(`*** Received request body ***\n ${prettyPrint(body)}`); } for (const middlware of this.preAuthorizeMiddleware) { const response = await middlware(preAuthorizeRequest); if (response) { return toCompleteResponse(response); } } const authorizeResult: AuthorizeResult = await this.authorize( preAuthorizeRequest ); const authorizedContext: SlackAppContext = { ...preAuthorizeRequest.context, authorizeResult, client: new SlackAPIClient(authorizeResult.botToken, { logLevel: this.env.SLACK_LOGGING_LEVEL, }), botToken: authorizeResult.botToken, botId: authorizeResult.botId, botUserId: authorizeResult.botUserId, userToken: authorizeResult.userToken, }; if (authorizedContext.channelId) { const context = authorizedContext as SlackAppContextWithChannelId; const client = new SlackAPIClient(context.botToken); context.say = async (params) => await client.chat.postMessage({ channel: context.channelId, ...params, }); } if (authorizedContext.responseUrl) { const responseUrl = authorizedContext.responseUrl; // deno-lint-ignore require-await (authorizedContext as SlackAppContextWithRespond).respond = async ( params ) => { return new ResponseUrlSender(responseUrl).call(params); }; } const baseRequest: SlackMiddlwareRequest<E> = { ...preAuthorizeRequest, context: authorizedContext, }; for (const middlware of this.postAuthorizeMiddleware) { const response = await middlware(baseRequest); if (response) { return toCompleteResponse(response); } } const payload = body as SlackRequestBody; if (body.type === PayloadType.EventsAPI) { // Events API const slackRequest: SlackRequest<E, SlackEvent<string>> = { payload: body.event, ...baseRequest, }; for (const matcher of this.#events) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (!body.type && body.command) { // Slash commands const slackRequest: SlackRequest<E, SlashCommand> = { payload: body as SlashCommand, ...baseRequest, }; for (const matcher of this.#slashCommands) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (body.type === PayloadType.GlobalShortcut) { // Global shortcuts const slackRequest: SlackRequest<E, GlobalShortcut> = { payload: body as GlobalShortcut, ...baseRequest, }; for (const matcher of this.#globalShorcuts) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (body.type === PayloadType.MessageShortcut) { // Message shortcuts const slackRequest: SlackRequest<E, MessageShortcut> = { payload: body as MessageShortcut, ...baseRequest, }; for (const matcher of this.#messageShorcuts) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (body.type === PayloadType.BlockAction) { // Block actions // deno-lint-ignore no-explicit-any const slackRequest: SlackRequest<E, BlockAction<any>> = { // deno-lint-ignore no-explicit-any payload: body as BlockAction<any>, ...baseRequest, }; for (const matcher of this.#blockActions) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (body.type === PayloadType.BlockSuggestion) { // Block suggestions const slackRequest: SlackRequest<E, BlockSuggestion> = { payload: body as BlockSuggestion, ...baseRequest, }; for (const matcher of this.#blockSuggestions) { const handler = matcher(payload); if (handler) { // Note that the only way to respond to a block_suggestion request // is to send an HTTP response with options/option_groups. // Thus, we don't support lazy handlers for this pattern. const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (body.type === PayloadType.ViewSubmission) { // View submissions const slackRequest: SlackRequest<E, ViewSubmission> = { payload: body as ViewSubmission, ...baseRequest, }; for (const matcher of this.#viewSubmissions) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (body.type === PayloadType.ViewClosed) { // View closed const slackRequest: SlackRequest<E, ViewClosed> = { payload: body as ViewClosed, ...baseRequest, }; for (const matcher of this.#viewClosed) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } // TODO: Add code suggestion here console.log( `*** No listener found ***\n${JSON.stringify(baseRequest.body)}` ); return new Response("No listener found", { status: 404 }); } return new Response("Invalid signature", { status: 401 }); } } export type StringOrRegExp = string | RegExp; export type EventRequest<E extends SlackAppEnv, T> = Extract< AnySlackEventWithChannelId, { type: T } > extends never ? SlackRequest<E, Extract<AnySlackEvent, { type: T }>> : SlackRequestWithChannelId< E, Extract<AnySlackEventWithChannelId, { type: T }> >; export type MessageEventPattern = string | RegExp | undefined; export type MessageEventRequest< E extends SlackAppEnv, ST extends string | undefined > = SlackRequestWithChannelId< E, Extract<AnySlackEventWithChannelId, { subtype: ST }> >; export type MessageEventSubtypes = | undefined | "bot_message" | "thread_broadcast" | "file_share"; export type MessageEventHandler<E extends SlackAppEnv> = ( req: MessageEventRequest<E, MessageEventSubtypes> ) => Promise<void>; export const noopLazyListener = async () => {};
src/app.ts
seratch-slack-edge-c75c224
[ { "filename": "src/request/payload/block-suggestion.ts", "retrieved_chunk": "import { AnyOption } from \"slack-web-api-client\";\nimport { DataSubmissionView } from \"./view-objects\";\nexport interface BlockSuggestion {\n type: \"block_suggestion\";\n block_id: string;\n action_id: string;\n value: string;\n api_app_id: string;\n team: {\n id: string;", "score": 0.8420158624649048 }, { "filename": "src/request/request-body.ts", "retrieved_chunk": " // shortcut, message_action\n callback_id?: string;\n // block_actions\n actions: {\n type: string;\n block_id: string;\n action_id: string;\n }[];\n // block_suggestion\n block_id?: string;", "score": 0.8404335379600525 }, { "filename": "src/request/payload/view-objects.ts", "retrieved_chunk": " type: AnyActionBlockElementType;\n value?: string | null;\n selected_date?: string | null;\n selected_time?: string | null;\n selected_date_time?: number | null;\n selected_conversation?: string | null;\n selected_channel?: string | null;\n selected_user?: string | null;\n selected_option?: ViewStateSelectedOption | null;\n selected_conversations?: string[];", "score": 0.8279174566268921 }, { "filename": "src/request/payload/block-action.ts", "retrieved_chunk": "import { Confirm, AnyOption, PlainTextField } from \"slack-web-api-client\";\nimport { DataSubmissionView, ViewStateValue } from \"./view-objects\";\nexport interface BlockAction<A extends BlockElementAction> {\n type: \"block_actions\";\n actions: A[];\n team: {\n id: string;\n domain: string;\n enterprise_id?: string;\n enterprise_name?: string;", "score": 0.8254776000976562 }, { "filename": "src/response/response.ts", "retrieved_chunk": "}\nexport type SlackViewResponse =\n | (SlackResponse & {\n body: \"\" | AnyViewResponse;\n })\n | \"\"\n | AnyViewResponse\n | undefined\n | void;\nexport type SlackOptionsResponse =", "score": 0.8202595710754395 } ]
typescript
) => SlackViewHandler<E, ViewSubmission> | null)[] = [];
import { SlackAppEnv, SlackEdgeAppEnv, SlackSocketModeAppEnv } from "./app-env"; import { parseRequestBody } from "./request/request-parser"; import { verifySlackRequest } from "./request/request-verification"; import { AckResponse, SlackHandler } from "./handler/handler"; import { SlackRequestBody } from "./request/request-body"; import { PreAuthorizeSlackMiddlwareRequest, SlackRequestWithRespond, SlackMiddlwareRequest, SlackRequestWithOptionalRespond, SlackRequest, SlackRequestWithChannelId, } from "./request/request"; import { SlashCommand } from "./request/payload/slash-command"; import { toCompleteResponse } from "./response/response"; import { SlackEvent, AnySlackEvent, AnySlackEventWithChannelId, } from "./request/payload/event"; import { ResponseUrlSender, SlackAPIClient } from "slack-web-api-client"; import { builtBaseContext, SlackAppContext, SlackAppContextWithChannelId, SlackAppContextWithRespond, } from "./context/context"; import { PreAuthorizeMiddleware, Middleware } from "./middleware/middleware"; import { isDebugLogEnabled, prettyPrint } from "slack-web-api-client"; import { Authorize } from "./authorization/authorize"; import { AuthorizeResult } from "./authorization/authorize-result"; import { ignoringSelfEvents, urlVerification, } from "./middleware/built-in-middleware"; import { ConfigError } from "./errors"; import { GlobalShortcut } from "./request/payload/global-shortcut"; import { MessageShortcut } from "./request/payload/message-shortcut"; import { BlockAction, BlockElementAction, BlockElementTypes, } from "./request/payload/block-action"; import { ViewSubmission } from "./request/payload/view-submission"; import { ViewClosed } from "./request/payload/view-closed"; import { BlockSuggestion } from "./request/payload/block-suggestion"; import { OptionsAckResponse, SlackOptionsHandler, } from "./handler/options-handler"; import { SlackViewHandler, ViewAckResponse } from "./handler/view-handler"; import { MessageAckResponse, SlackMessageHandler, } from "./handler/message-handler"; import { singleTeamAuthorize } from "./authorization/single-team-authorize"; import { ExecutionContext, NoopExecutionContext } from "./execution-context"; import { PayloadType } from "./request/payload-types"; import { isPostedMessageEvent } from "./utility/message-events"; import { SocketModeClient } from "./socket-mode/socket-mode-client"; export interface SlackAppOptions< E extends SlackEdgeAppEnv | SlackSocketModeAppEnv > { env: E; authorize?: Authorize<E>; routes?: { events: string; }; socketMode?: boolean; } export class SlackApp<E extends SlackEdgeAppEnv | SlackSocketModeAppEnv> { public env: E; public client: SlackAPIClient; public authorize: Authorize<E>; public routes: { events: string | undefined }; public signingSecret: string; public appLevelToken: string | undefined; public socketMode: boolean; public socketModeClient: SocketModeClient | undefined; // deno-lint-ignore no-explicit-any public preAuthorizeMiddleware: PreAuthorizeMiddleware<any>[] = [ urlVerification, ]; // deno-lint-ignore no-explicit-any public postAuthorizeMiddleware: Middleware<any>[] = [ignoringSelfEvents]; #slashCommands: (( body: SlackRequestBody ) => SlackMessageHandler<E, SlashCommand> | null)[] = []; #events: (( body: SlackRequestBody ) => SlackHandler<E, SlackEvent<string>> | null)[] = []; #globalShorcuts: (( body: SlackRequestBody ) => SlackHandler<E, GlobalShortcut> | null)[] = []; #messageShorcuts: (( body: SlackRequestBody ) => SlackHandler<E, MessageShortcut> | null)[] = []; #blockActions: ((body: SlackRequestBody) => SlackHandler< E, // deno-lint-ignore no-explicit-any BlockAction<any> > | null)[] = []; #blockSuggestions: (( body: SlackRequestBody ) => SlackOptionsHandler<E, BlockSuggestion> | null)[] = []; #viewSubmissions: (( body: SlackRequestBody ) => SlackViewHandler<E, ViewSubmission> | null)[] = []; #viewClosed: (( body: SlackRequestBody ) => SlackViewHandler<E, ViewClosed> | null)[] = []; constructor(options: SlackAppOptions<E>) { if ( options.env.SLACK_BOT_TOKEN === undefined && (options.authorize === undefined || options.authorize === singleTeamAuthorize) ) { throw new ConfigError( "When you don't pass env.SLACK_BOT_TOKEN, your own authorize function, which supplies a valid token to use, needs to be passed instead." ); } this.env = options.env; this.client = new SlackAPIClient(options.env.SLACK_BOT_TOKEN, { logLevel: this.env.SLACK_LOGGING_LEVEL, }); this.appLevelToken = options.env.SLACK_APP_TOKEN; this.socketMode = options.socketMode ?? this.appLevelToken !== undefined; if (this.socketMode) { this.signingSecret = ""; } else { if (!this.env.SLACK_SIGNING_SECRET) { throw new ConfigError( "env.SLACK_SIGNING_SECRET is required to run your app on edge functions!" ); } this.signingSecret = this.env.SLACK_SIGNING_SECRET; } this.authorize = options.authorize ?? singleTeamAuthorize; this.routes = { events: options.routes?.events }; } beforeAuthorize(middleware: PreAuthorizeMiddleware<E>): SlackApp<E> { this.preAuthorizeMiddleware.push(middleware); return this; } middleware(middleware: Middleware<E>): SlackApp<E> { return this.afterAuthorize(middleware); } use(middleware: Middleware<E>): SlackApp<E> { return this.afterAuthorize(middleware); } afterAuthorize(middleware: Middleware<E>): SlackApp<E> { this.postAuthorizeMiddleware.push(middleware); return this; } command( pattern: StringOrRegExp, ack: ( req: SlackRequestWithRespond<E, SlashCommand> ) => Promise<MessageAckResponse>, lazy: ( req: SlackRequestWithRespond<E, SlashCommand> ) => Promise<void> = noopLazyListener ): SlackApp<E> { const handler: SlackMessageHandler<E, SlashCommand> = { ack, lazy }; this.#slashCommands.push((body) => { if (
body.type || !body.command) {
return null; } if (typeof pattern === "string" && body.command === pattern) { return handler; } else if ( typeof pattern === "object" && pattern instanceof RegExp && body.command.match(pattern) ) { return handler; } return null; }); return this; } event<Type extends string>( event: Type, lazy: (req: EventRequest<E, Type>) => Promise<void> ): SlackApp<E> { this.#events.push((body) => { if (body.type !== PayloadType.EventsAPI || !body.event) { return null; } if (body.event.type === event) { // deno-lint-ignore require-await return { ack: async () => "", lazy }; } return null; }); return this; } anyMessage(lazy: MessageEventHandler<E>): SlackApp<E> { return this.message(undefined, lazy); } message( pattern: MessageEventPattern, lazy: MessageEventHandler<E> ): SlackApp<E> { this.#events.push((body) => { if ( body.type !== PayloadType.EventsAPI || !body.event || body.event.type !== "message" ) { return null; } if (isPostedMessageEvent(body.event)) { let matched = true; if (pattern !== undefined) { if (typeof pattern === "string") { matched = body.event.text!.includes(pattern); } if (typeof pattern === "object") { matched = body.event.text!.match(pattern) !== null; } } if (matched) { // deno-lint-ignore require-await return { ack: async (_: EventRequest<E, "message">) => "", lazy }; } } return null; }); return this; } shortcut( callbackId: StringOrRegExp, ack: ( req: | SlackRequest<E, GlobalShortcut> | SlackRequestWithRespond<E, MessageShortcut> ) => Promise<AckResponse>, lazy: ( req: | SlackRequest<E, GlobalShortcut> | SlackRequestWithRespond<E, MessageShortcut> ) => Promise<void> = noopLazyListener ): SlackApp<E> { return this.globalShortcut(callbackId, ack, lazy).messageShortcut( callbackId, ack, lazy ); } globalShortcut( callbackId: StringOrRegExp, ack: (req: SlackRequest<E, GlobalShortcut>) => Promise<AckResponse>, lazy: ( req: SlackRequest<E, GlobalShortcut> ) => Promise<void> = noopLazyListener ): SlackApp<E> { const handler: SlackHandler<E, GlobalShortcut> = { ack, lazy }; this.#globalShorcuts.push((body) => { if (body.type !== PayloadType.GlobalShortcut || !body.callback_id) { return null; } if (typeof callbackId === "string" && body.callback_id === callbackId) { return handler; } else if ( typeof callbackId === "object" && callbackId instanceof RegExp && body.callback_id.match(callbackId) ) { return handler; } return null; }); return this; } messageShortcut( callbackId: StringOrRegExp, ack: ( req: SlackRequestWithRespond<E, MessageShortcut> ) => Promise<AckResponse>, lazy: ( req: SlackRequestWithRespond<E, MessageShortcut> ) => Promise<void> = noopLazyListener ): SlackApp<E> { const handler: SlackHandler<E, MessageShortcut> = { ack, lazy }; this.#messageShorcuts.push((body) => { if (body.type !== PayloadType.MessageShortcut || !body.callback_id) { return null; } if (typeof callbackId === "string" && body.callback_id === callbackId) { return handler; } else if ( typeof callbackId === "object" && callbackId instanceof RegExp && body.callback_id.match(callbackId) ) { return handler; } return null; }); return this; } action< T extends BlockElementTypes, A extends BlockAction<BlockElementAction<T>> = BlockAction< BlockElementAction<T> > >( constraints: | StringOrRegExp | { type: T; block_id?: string; action_id: string }, ack: (req: SlackRequestWithOptionalRespond<E, A>) => Promise<AckResponse>, lazy: ( req: SlackRequestWithOptionalRespond<E, A> ) => Promise<void> = noopLazyListener ): SlackApp<E> { const handler: SlackHandler<E, A> = { ack, lazy }; this.#blockActions.push((body) => { if ( body.type !== PayloadType.BlockAction || !body.actions || !body.actions[0] ) { return null; } const action = body.actions[0]; if (typeof constraints === "string" && action.action_id === constraints) { return handler; } else if (typeof constraints === "object") { if (constraints instanceof RegExp) { if (action.action_id.match(constraints)) { return handler; } } else if (constraints.type) { if (action.type === constraints.type) { if (action.action_id === constraints.action_id) { if ( constraints.block_id && action.block_id !== constraints.block_id ) { return null; } return handler; } } } } return null; }); return this; } options( constraints: StringOrRegExp | { block_id?: string; action_id: string }, ack: (req: SlackRequest<E, BlockSuggestion>) => Promise<OptionsAckResponse> ): SlackApp<E> { // Note that block_suggestion response must be done within 3 seconds. // So, we don't support the lazy handler for it. const handler: SlackOptionsHandler<E, BlockSuggestion> = { ack }; this.#blockSuggestions.push((body) => { if (body.type !== PayloadType.BlockSuggestion || !body.action_id) { return null; } if (typeof constraints === "string" && body.action_id === constraints) { return handler; } else if (typeof constraints === "object") { if (constraints instanceof RegExp) { if (body.action_id.match(constraints)) { return handler; } } else { if (body.action_id === constraints.action_id) { if (body.block_id && body.block_id !== constraints.block_id) { return null; } return handler; } } } return null; }); return this; } view( callbackId: StringOrRegExp, ack: ( req: | SlackRequestWithOptionalRespond<E, ViewSubmission> | SlackRequest<E, ViewClosed> ) => Promise<ViewAckResponse>, lazy: ( req: | SlackRequestWithOptionalRespond<E, ViewSubmission> | SlackRequest<E, ViewClosed> ) => Promise<void> = noopLazyListener ): SlackApp<E> { return this.viewSubmission(callbackId, ack, lazy).viewClosed( callbackId, ack, lazy ); } viewSubmission( callbackId: StringOrRegExp, ack: ( req: SlackRequestWithOptionalRespond<E, ViewSubmission> ) => Promise<ViewAckResponse>, lazy: ( req: SlackRequestWithOptionalRespond<E, ViewSubmission> ) => Promise<void> = noopLazyListener ): SlackApp<E> { const handler: SlackViewHandler<E, ViewSubmission> = { ack, lazy }; this.#viewSubmissions.push((body) => { if (body.type !== PayloadType.ViewSubmission || !body.view) { return null; } if ( typeof callbackId === "string" && body.view.callback_id === callbackId ) { return handler; } else if ( typeof callbackId === "object" && callbackId instanceof RegExp && body.view.callback_id.match(callbackId) ) { return handler; } return null; }); return this; } viewClosed( callbackId: StringOrRegExp, ack: (req: SlackRequest<E, ViewClosed>) => Promise<ViewAckResponse>, lazy: (req: SlackRequest<E, ViewClosed>) => Promise<void> = noopLazyListener ): SlackApp<E> { const handler: SlackViewHandler<E, ViewClosed> = { ack, lazy }; this.#viewClosed.push((body) => { if (body.type !== PayloadType.ViewClosed || !body.view) { return null; } if ( typeof callbackId === "string" && body.view.callback_id === callbackId ) { return handler; } else if ( typeof callbackId === "object" && callbackId instanceof RegExp && body.view.callback_id.match(callbackId) ) { return handler; } return null; }); return this; } async run( request: Request, ctx: ExecutionContext = new NoopExecutionContext() ): Promise<Response> { return await this.handleEventRequest(request, ctx); } async connect(): Promise<void> { if (!this.socketMode) { throw new ConfigError( "Both env.SLACK_APP_TOKEN and socketMode: true are required to start a Socket Mode connection!" ); } this.socketModeClient = new SocketModeClient(this); await this.socketModeClient.connect(); } async disconnect(): Promise<void> { if (this.socketModeClient) { await this.socketModeClient.disconnect(); } } async handleEventRequest( request: Request, ctx: ExecutionContext ): Promise<Response> { // If the routes.events is missing, any URLs can work for handing requests from Slack if (this.routes.events) { const { pathname } = new URL(request.url); if (pathname !== this.routes.events) { return new Response("Not found", { status: 404 }); } } // To avoid the following warning by Cloudflware, parse the body as Blob first // Called .text() on an HTTP body which does not appear to be text .. const blobRequestBody = await request.blob(); // We can safely assume the incoming request body is always text data const rawBody: string = await blobRequestBody.text(); // For Request URL verification if (rawBody.includes("ssl_check=")) { // Slack does not send the x-slack-signature header for this pattern. // Thus, we need to check the pattern before verifying a request. const bodyParams = new URLSearchParams(rawBody); if (bodyParams.get("ssl_check") === "1" && bodyParams.get("token")) { return new Response("", { status: 200 }); } } // Verify the request headers and body const isRequestSignatureVerified = this.socketMode || (await verifySlackRequest(this.signingSecret, request.headers, rawBody)); if (isRequestSignatureVerified) { // deno-lint-ignore no-explicit-any const body: Record<string, any> = await parseRequestBody( request.headers, rawBody ); let retryNum: number | undefined = undefined; try { const retryNumHeader = request.headers.get("x-slack-retry-num"); if (retryNumHeader) { retryNum = Number.parseInt(retryNumHeader); } else if (this.socketMode && body.retry_attempt) { retryNum = Number.parseInt(body.retry_attempt); } // deno-lint-ignore no-unused-vars } catch (e) { // Ignore an exception here } const retryReason = request.headers.get("x-slack-retry-reason") ?? body.retry_reason; const preAuthorizeRequest: PreAuthorizeSlackMiddlwareRequest<E> = { body, rawBody, retryNum, retryReason, context: builtBaseContext(body), env: this.env, headers: request.headers, }; if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log(`*** Received request body ***\n ${prettyPrint(body)}`); } for (const middlware of this.preAuthorizeMiddleware) { const response = await middlware(preAuthorizeRequest); if (response) { return toCompleteResponse(response); } } const authorizeResult: AuthorizeResult = await this.authorize( preAuthorizeRequest ); const authorizedContext: SlackAppContext = { ...preAuthorizeRequest.context, authorizeResult, client: new SlackAPIClient(authorizeResult.botToken, { logLevel: this.env.SLACK_LOGGING_LEVEL, }), botToken: authorizeResult.botToken, botId: authorizeResult.botId, botUserId: authorizeResult.botUserId, userToken: authorizeResult.userToken, }; if (authorizedContext.channelId) { const context = authorizedContext as SlackAppContextWithChannelId; const client = new SlackAPIClient(context.botToken); context.say = async (params) => await client.chat.postMessage({ channel: context.channelId, ...params, }); } if (authorizedContext.responseUrl) { const responseUrl = authorizedContext.responseUrl; // deno-lint-ignore require-await (authorizedContext as SlackAppContextWithRespond).respond = async ( params ) => { return new ResponseUrlSender(responseUrl).call(params); }; } const baseRequest: SlackMiddlwareRequest<E> = { ...preAuthorizeRequest, context: authorizedContext, }; for (const middlware of this.postAuthorizeMiddleware) { const response = await middlware(baseRequest); if (response) { return toCompleteResponse(response); } } const payload = body as SlackRequestBody; if (body.type === PayloadType.EventsAPI) { // Events API const slackRequest: SlackRequest<E, SlackEvent<string>> = { payload: body.event, ...baseRequest, }; for (const matcher of this.#events) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (!body.type && body.command) { // Slash commands const slackRequest: SlackRequest<E, SlashCommand> = { payload: body as SlashCommand, ...baseRequest, }; for (const matcher of this.#slashCommands) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (body.type === PayloadType.GlobalShortcut) { // Global shortcuts const slackRequest: SlackRequest<E, GlobalShortcut> = { payload: body as GlobalShortcut, ...baseRequest, }; for (const matcher of this.#globalShorcuts) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (body.type === PayloadType.MessageShortcut) { // Message shortcuts const slackRequest: SlackRequest<E, MessageShortcut> = { payload: body as MessageShortcut, ...baseRequest, }; for (const matcher of this.#messageShorcuts) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (body.type === PayloadType.BlockAction) { // Block actions // deno-lint-ignore no-explicit-any const slackRequest: SlackRequest<E, BlockAction<any>> = { // deno-lint-ignore no-explicit-any payload: body as BlockAction<any>, ...baseRequest, }; for (const matcher of this.#blockActions) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (body.type === PayloadType.BlockSuggestion) { // Block suggestions const slackRequest: SlackRequest<E, BlockSuggestion> = { payload: body as BlockSuggestion, ...baseRequest, }; for (const matcher of this.#blockSuggestions) { const handler = matcher(payload); if (handler) { // Note that the only way to respond to a block_suggestion request // is to send an HTTP response with options/option_groups. // Thus, we don't support lazy handlers for this pattern. const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (body.type === PayloadType.ViewSubmission) { // View submissions const slackRequest: SlackRequest<E, ViewSubmission> = { payload: body as ViewSubmission, ...baseRequest, }; for (const matcher of this.#viewSubmissions) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (body.type === PayloadType.ViewClosed) { // View closed const slackRequest: SlackRequest<E, ViewClosed> = { payload: body as ViewClosed, ...baseRequest, }; for (const matcher of this.#viewClosed) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } // TODO: Add code suggestion here console.log( `*** No listener found ***\n${JSON.stringify(baseRequest.body)}` ); return new Response("No listener found", { status: 404 }); } return new Response("Invalid signature", { status: 401 }); } } export type StringOrRegExp = string | RegExp; export type EventRequest<E extends SlackAppEnv, T> = Extract< AnySlackEventWithChannelId, { type: T } > extends never ? SlackRequest<E, Extract<AnySlackEvent, { type: T }>> : SlackRequestWithChannelId< E, Extract<AnySlackEventWithChannelId, { type: T }> >; export type MessageEventPattern = string | RegExp | undefined; export type MessageEventRequest< E extends SlackAppEnv, ST extends string | undefined > = SlackRequestWithChannelId< E, Extract<AnySlackEventWithChannelId, { subtype: ST }> >; export type MessageEventSubtypes = | undefined | "bot_message" | "thread_broadcast" | "file_share"; export type MessageEventHandler<E extends SlackAppEnv> = ( req: MessageEventRequest<E, MessageEventSubtypes> ) => Promise<void>; export const noopLazyListener = async () => {};
src/app.ts
seratch-slack-edge-c75c224
[ { "filename": "src/handler/message-handler.ts", "retrieved_chunk": "import { SlackAppEnv } from \"../app-env\";\nimport { SlackRequest } from \"../request/request\";\nimport { MessageResponse } from \"../response/response-body\";\nimport { AckResponse } from \"./handler\";\nexport type MessageAckResponse = AckResponse | MessageResponse;\nexport interface SlackMessageHandler<E extends SlackAppEnv, Payload> {\n ack(request: SlackRequest<E, Payload>): Promise<MessageAckResponse>;\n lazy(request: SlackRequest<E, Payload>): Promise<void>;\n}", "score": 0.8793871998786926 }, { "filename": "src/handler/handler.ts", "retrieved_chunk": "import { SlackAppEnv } from \"../app-env\";\nimport { SlackRequest } from \"../request/request\";\nimport { SlackResponse } from \"../response/response\";\nexport type AckResponse = SlackResponse | string | void;\nexport interface SlackHandler<E extends SlackAppEnv, Payload> {\n ack(request: SlackRequest<E, Payload>): Promise<AckResponse>;\n lazy(request: SlackRequest<E, Payload>): Promise<void>;\n}", "score": 0.8669531345367432 }, { "filename": "src/handler/view-handler.ts", "retrieved_chunk": "import { SlackAppEnv } from \"../app-env\";\nimport { SlackRequest } from \"../request/request\";\nimport { SlackViewResponse } from \"../response/response\";\nexport type ViewAckResponse = SlackViewResponse | void;\nexport type SlackViewHandler<E extends SlackAppEnv, Payload> = {\n ack(request: SlackRequest<E, Payload>): Promise<ViewAckResponse>;\n lazy(request: SlackRequest<E, Payload>): Promise<void>;\n};", "score": 0.8448954224586487 }, { "filename": "src/handler/options-handler.ts", "retrieved_chunk": "import { SlackAppEnv } from \"../app-env\";\nimport { SlackRequest } from \"../request/request\";\nimport { SlackOptionsResponse } from \"../response/response\";\nexport type OptionsAckResponse = SlackOptionsResponse;\nexport interface SlackOptionsHandler<E extends SlackAppEnv, Payload> {\n ack(request: SlackRequest<E, Payload>): Promise<OptionsAckResponse>;\n // Note that a block_suggestion response must be done synchronously.\n // That's why we don't support lazy functions for the pattern.\n}", "score": 0.8271384835243225 }, { "filename": "src/middleware/middleware.ts", "retrieved_chunk": " req: SlackMiddlwareRequest<E>\n) => Promise<SlackResponse | void>;", "score": 0.8186142444610596 } ]
typescript
body.type || !body.command) {
import { SlackAppEnv, SlackEdgeAppEnv, SlackSocketModeAppEnv } from "./app-env"; import { parseRequestBody } from "./request/request-parser"; import { verifySlackRequest } from "./request/request-verification"; import { AckResponse, SlackHandler } from "./handler/handler"; import { SlackRequestBody } from "./request/request-body"; import { PreAuthorizeSlackMiddlwareRequest, SlackRequestWithRespond, SlackMiddlwareRequest, SlackRequestWithOptionalRespond, SlackRequest, SlackRequestWithChannelId, } from "./request/request"; import { SlashCommand } from "./request/payload/slash-command"; import { toCompleteResponse } from "./response/response"; import { SlackEvent, AnySlackEvent, AnySlackEventWithChannelId, } from "./request/payload/event"; import { ResponseUrlSender, SlackAPIClient } from "slack-web-api-client"; import { builtBaseContext, SlackAppContext, SlackAppContextWithChannelId, SlackAppContextWithRespond, } from "./context/context"; import { PreAuthorizeMiddleware, Middleware } from "./middleware/middleware"; import { isDebugLogEnabled, prettyPrint } from "slack-web-api-client"; import { Authorize } from "./authorization/authorize"; import { AuthorizeResult } from "./authorization/authorize-result"; import { ignoringSelfEvents, urlVerification, } from "./middleware/built-in-middleware"; import { ConfigError } from "./errors"; import { GlobalShortcut } from "./request/payload/global-shortcut"; import { MessageShortcut } from "./request/payload/message-shortcut"; import { BlockAction, BlockElementAction, BlockElementTypes, } from "./request/payload/block-action"; import { ViewSubmission } from "./request/payload/view-submission"; import { ViewClosed } from "./request/payload/view-closed"; import { BlockSuggestion } from "./request/payload/block-suggestion"; import { OptionsAckResponse, SlackOptionsHandler, } from "./handler/options-handler"; import { SlackViewHandler, ViewAckResponse } from "./handler/view-handler"; import { MessageAckResponse, SlackMessageHandler, } from "./handler/message-handler"; import { singleTeamAuthorize } from "./authorization/single-team-authorize"; import { ExecutionContext, NoopExecutionContext } from "./execution-context"; import { PayloadType } from "./request/payload-types"; import { isPostedMessageEvent } from "./utility/message-events"; import { SocketModeClient } from "./socket-mode/socket-mode-client"; export interface SlackAppOptions< E extends SlackEdgeAppEnv | SlackSocketModeAppEnv > { env: E; authorize?: Authorize<E>; routes?: { events: string; }; socketMode?: boolean; } export class SlackApp<E extends SlackEdgeAppEnv | SlackSocketModeAppEnv> { public env: E; public client: SlackAPIClient; public authorize: Authorize<E>; public routes: { events: string | undefined }; public signingSecret: string; public appLevelToken: string | undefined; public socketMode: boolean; public socketModeClient: SocketModeClient | undefined; // deno-lint-ignore no-explicit-any public preAuthorizeMiddleware: PreAuthorizeMiddleware<any>[] = [ urlVerification, ]; // deno-lint-ignore no-explicit-any public postAuthorizeMiddleware: Middleware<any>[] = [ignoringSelfEvents]; #slashCommands: (( body: SlackRequestBody ) => SlackMessageHandler<E, SlashCommand> | null)[] = []; #events: (( body: SlackRequestBody ) => SlackHandler<E, SlackEvent<string>> | null)[] = []; #globalShorcuts: (( body: SlackRequestBody ) => SlackHandler<E, GlobalShortcut> | null)[] = []; #messageShorcuts: (( body: SlackRequestBody ) => SlackHandler<E, MessageShortcut> | null)[] = []; #blockActions: ((body: SlackRequestBody) => SlackHandler< E, // deno-lint-ignore no-explicit-any BlockAction<any> > | null)[] = []; #blockSuggestions: (( body: SlackRequestBody ) => SlackOptionsHandler<E, BlockSuggestion> | null)[] = []; #viewSubmissions: (( body: SlackRequestBody ) => SlackViewHandler<E, ViewSubmission> | null)[] = []; #viewClosed: (( body: SlackRequestBody ) => SlackViewHandler<E, ViewClosed> | null)[] = []; constructor(options: SlackAppOptions<E>) { if ( options.env.SLACK_BOT_TOKEN === undefined && (options.authorize === undefined || options.authorize === singleTeamAuthorize) ) { throw new ConfigError( "When you don't pass env.SLACK_BOT_TOKEN, your own authorize function, which supplies a valid token to use, needs to be passed instead." ); } this.env = options.env; this.client = new SlackAPIClient(options.env.SLACK_BOT_TOKEN, { logLevel: this.env.SLACK_LOGGING_LEVEL, });
this.appLevelToken = options.env.SLACK_APP_TOKEN;
this.socketMode = options.socketMode ?? this.appLevelToken !== undefined; if (this.socketMode) { this.signingSecret = ""; } else { if (!this.env.SLACK_SIGNING_SECRET) { throw new ConfigError( "env.SLACK_SIGNING_SECRET is required to run your app on edge functions!" ); } this.signingSecret = this.env.SLACK_SIGNING_SECRET; } this.authorize = options.authorize ?? singleTeamAuthorize; this.routes = { events: options.routes?.events }; } beforeAuthorize(middleware: PreAuthorizeMiddleware<E>): SlackApp<E> { this.preAuthorizeMiddleware.push(middleware); return this; } middleware(middleware: Middleware<E>): SlackApp<E> { return this.afterAuthorize(middleware); } use(middleware: Middleware<E>): SlackApp<E> { return this.afterAuthorize(middleware); } afterAuthorize(middleware: Middleware<E>): SlackApp<E> { this.postAuthorizeMiddleware.push(middleware); return this; } command( pattern: StringOrRegExp, ack: ( req: SlackRequestWithRespond<E, SlashCommand> ) => Promise<MessageAckResponse>, lazy: ( req: SlackRequestWithRespond<E, SlashCommand> ) => Promise<void> = noopLazyListener ): SlackApp<E> { const handler: SlackMessageHandler<E, SlashCommand> = { ack, lazy }; this.#slashCommands.push((body) => { if (body.type || !body.command) { return null; } if (typeof pattern === "string" && body.command === pattern) { return handler; } else if ( typeof pattern === "object" && pattern instanceof RegExp && body.command.match(pattern) ) { return handler; } return null; }); return this; } event<Type extends string>( event: Type, lazy: (req: EventRequest<E, Type>) => Promise<void> ): SlackApp<E> { this.#events.push((body) => { if (body.type !== PayloadType.EventsAPI || !body.event) { return null; } if (body.event.type === event) { // deno-lint-ignore require-await return { ack: async () => "", lazy }; } return null; }); return this; } anyMessage(lazy: MessageEventHandler<E>): SlackApp<E> { return this.message(undefined, lazy); } message( pattern: MessageEventPattern, lazy: MessageEventHandler<E> ): SlackApp<E> { this.#events.push((body) => { if ( body.type !== PayloadType.EventsAPI || !body.event || body.event.type !== "message" ) { return null; } if (isPostedMessageEvent(body.event)) { let matched = true; if (pattern !== undefined) { if (typeof pattern === "string") { matched = body.event.text!.includes(pattern); } if (typeof pattern === "object") { matched = body.event.text!.match(pattern) !== null; } } if (matched) { // deno-lint-ignore require-await return { ack: async (_: EventRequest<E, "message">) => "", lazy }; } } return null; }); return this; } shortcut( callbackId: StringOrRegExp, ack: ( req: | SlackRequest<E, GlobalShortcut> | SlackRequestWithRespond<E, MessageShortcut> ) => Promise<AckResponse>, lazy: ( req: | SlackRequest<E, GlobalShortcut> | SlackRequestWithRespond<E, MessageShortcut> ) => Promise<void> = noopLazyListener ): SlackApp<E> { return this.globalShortcut(callbackId, ack, lazy).messageShortcut( callbackId, ack, lazy ); } globalShortcut( callbackId: StringOrRegExp, ack: (req: SlackRequest<E, GlobalShortcut>) => Promise<AckResponse>, lazy: ( req: SlackRequest<E, GlobalShortcut> ) => Promise<void> = noopLazyListener ): SlackApp<E> { const handler: SlackHandler<E, GlobalShortcut> = { ack, lazy }; this.#globalShorcuts.push((body) => { if (body.type !== PayloadType.GlobalShortcut || !body.callback_id) { return null; } if (typeof callbackId === "string" && body.callback_id === callbackId) { return handler; } else if ( typeof callbackId === "object" && callbackId instanceof RegExp && body.callback_id.match(callbackId) ) { return handler; } return null; }); return this; } messageShortcut( callbackId: StringOrRegExp, ack: ( req: SlackRequestWithRespond<E, MessageShortcut> ) => Promise<AckResponse>, lazy: ( req: SlackRequestWithRespond<E, MessageShortcut> ) => Promise<void> = noopLazyListener ): SlackApp<E> { const handler: SlackHandler<E, MessageShortcut> = { ack, lazy }; this.#messageShorcuts.push((body) => { if (body.type !== PayloadType.MessageShortcut || !body.callback_id) { return null; } if (typeof callbackId === "string" && body.callback_id === callbackId) { return handler; } else if ( typeof callbackId === "object" && callbackId instanceof RegExp && body.callback_id.match(callbackId) ) { return handler; } return null; }); return this; } action< T extends BlockElementTypes, A extends BlockAction<BlockElementAction<T>> = BlockAction< BlockElementAction<T> > >( constraints: | StringOrRegExp | { type: T; block_id?: string; action_id: string }, ack: (req: SlackRequestWithOptionalRespond<E, A>) => Promise<AckResponse>, lazy: ( req: SlackRequestWithOptionalRespond<E, A> ) => Promise<void> = noopLazyListener ): SlackApp<E> { const handler: SlackHandler<E, A> = { ack, lazy }; this.#blockActions.push((body) => { if ( body.type !== PayloadType.BlockAction || !body.actions || !body.actions[0] ) { return null; } const action = body.actions[0]; if (typeof constraints === "string" && action.action_id === constraints) { return handler; } else if (typeof constraints === "object") { if (constraints instanceof RegExp) { if (action.action_id.match(constraints)) { return handler; } } else if (constraints.type) { if (action.type === constraints.type) { if (action.action_id === constraints.action_id) { if ( constraints.block_id && action.block_id !== constraints.block_id ) { return null; } return handler; } } } } return null; }); return this; } options( constraints: StringOrRegExp | { block_id?: string; action_id: string }, ack: (req: SlackRequest<E, BlockSuggestion>) => Promise<OptionsAckResponse> ): SlackApp<E> { // Note that block_suggestion response must be done within 3 seconds. // So, we don't support the lazy handler for it. const handler: SlackOptionsHandler<E, BlockSuggestion> = { ack }; this.#blockSuggestions.push((body) => { if (body.type !== PayloadType.BlockSuggestion || !body.action_id) { return null; } if (typeof constraints === "string" && body.action_id === constraints) { return handler; } else if (typeof constraints === "object") { if (constraints instanceof RegExp) { if (body.action_id.match(constraints)) { return handler; } } else { if (body.action_id === constraints.action_id) { if (body.block_id && body.block_id !== constraints.block_id) { return null; } return handler; } } } return null; }); return this; } view( callbackId: StringOrRegExp, ack: ( req: | SlackRequestWithOptionalRespond<E, ViewSubmission> | SlackRequest<E, ViewClosed> ) => Promise<ViewAckResponse>, lazy: ( req: | SlackRequestWithOptionalRespond<E, ViewSubmission> | SlackRequest<E, ViewClosed> ) => Promise<void> = noopLazyListener ): SlackApp<E> { return this.viewSubmission(callbackId, ack, lazy).viewClosed( callbackId, ack, lazy ); } viewSubmission( callbackId: StringOrRegExp, ack: ( req: SlackRequestWithOptionalRespond<E, ViewSubmission> ) => Promise<ViewAckResponse>, lazy: ( req: SlackRequestWithOptionalRespond<E, ViewSubmission> ) => Promise<void> = noopLazyListener ): SlackApp<E> { const handler: SlackViewHandler<E, ViewSubmission> = { ack, lazy }; this.#viewSubmissions.push((body) => { if (body.type !== PayloadType.ViewSubmission || !body.view) { return null; } if ( typeof callbackId === "string" && body.view.callback_id === callbackId ) { return handler; } else if ( typeof callbackId === "object" && callbackId instanceof RegExp && body.view.callback_id.match(callbackId) ) { return handler; } return null; }); return this; } viewClosed( callbackId: StringOrRegExp, ack: (req: SlackRequest<E, ViewClosed>) => Promise<ViewAckResponse>, lazy: (req: SlackRequest<E, ViewClosed>) => Promise<void> = noopLazyListener ): SlackApp<E> { const handler: SlackViewHandler<E, ViewClosed> = { ack, lazy }; this.#viewClosed.push((body) => { if (body.type !== PayloadType.ViewClosed || !body.view) { return null; } if ( typeof callbackId === "string" && body.view.callback_id === callbackId ) { return handler; } else if ( typeof callbackId === "object" && callbackId instanceof RegExp && body.view.callback_id.match(callbackId) ) { return handler; } return null; }); return this; } async run( request: Request, ctx: ExecutionContext = new NoopExecutionContext() ): Promise<Response> { return await this.handleEventRequest(request, ctx); } async connect(): Promise<void> { if (!this.socketMode) { throw new ConfigError( "Both env.SLACK_APP_TOKEN and socketMode: true are required to start a Socket Mode connection!" ); } this.socketModeClient = new SocketModeClient(this); await this.socketModeClient.connect(); } async disconnect(): Promise<void> { if (this.socketModeClient) { await this.socketModeClient.disconnect(); } } async handleEventRequest( request: Request, ctx: ExecutionContext ): Promise<Response> { // If the routes.events is missing, any URLs can work for handing requests from Slack if (this.routes.events) { const { pathname } = new URL(request.url); if (pathname !== this.routes.events) { return new Response("Not found", { status: 404 }); } } // To avoid the following warning by Cloudflware, parse the body as Blob first // Called .text() on an HTTP body which does not appear to be text .. const blobRequestBody = await request.blob(); // We can safely assume the incoming request body is always text data const rawBody: string = await blobRequestBody.text(); // For Request URL verification if (rawBody.includes("ssl_check=")) { // Slack does not send the x-slack-signature header for this pattern. // Thus, we need to check the pattern before verifying a request. const bodyParams = new URLSearchParams(rawBody); if (bodyParams.get("ssl_check") === "1" && bodyParams.get("token")) { return new Response("", { status: 200 }); } } // Verify the request headers and body const isRequestSignatureVerified = this.socketMode || (await verifySlackRequest(this.signingSecret, request.headers, rawBody)); if (isRequestSignatureVerified) { // deno-lint-ignore no-explicit-any const body: Record<string, any> = await parseRequestBody( request.headers, rawBody ); let retryNum: number | undefined = undefined; try { const retryNumHeader = request.headers.get("x-slack-retry-num"); if (retryNumHeader) { retryNum = Number.parseInt(retryNumHeader); } else if (this.socketMode && body.retry_attempt) { retryNum = Number.parseInt(body.retry_attempt); } // deno-lint-ignore no-unused-vars } catch (e) { // Ignore an exception here } const retryReason = request.headers.get("x-slack-retry-reason") ?? body.retry_reason; const preAuthorizeRequest: PreAuthorizeSlackMiddlwareRequest<E> = { body, rawBody, retryNum, retryReason, context: builtBaseContext(body), env: this.env, headers: request.headers, }; if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log(`*** Received request body ***\n ${prettyPrint(body)}`); } for (const middlware of this.preAuthorizeMiddleware) { const response = await middlware(preAuthorizeRequest); if (response) { return toCompleteResponse(response); } } const authorizeResult: AuthorizeResult = await this.authorize( preAuthorizeRequest ); const authorizedContext: SlackAppContext = { ...preAuthorizeRequest.context, authorizeResult, client: new SlackAPIClient(authorizeResult.botToken, { logLevel: this.env.SLACK_LOGGING_LEVEL, }), botToken: authorizeResult.botToken, botId: authorizeResult.botId, botUserId: authorizeResult.botUserId, userToken: authorizeResult.userToken, }; if (authorizedContext.channelId) { const context = authorizedContext as SlackAppContextWithChannelId; const client = new SlackAPIClient(context.botToken); context.say = async (params) => await client.chat.postMessage({ channel: context.channelId, ...params, }); } if (authorizedContext.responseUrl) { const responseUrl = authorizedContext.responseUrl; // deno-lint-ignore require-await (authorizedContext as SlackAppContextWithRespond).respond = async ( params ) => { return new ResponseUrlSender(responseUrl).call(params); }; } const baseRequest: SlackMiddlwareRequest<E> = { ...preAuthorizeRequest, context: authorizedContext, }; for (const middlware of this.postAuthorizeMiddleware) { const response = await middlware(baseRequest); if (response) { return toCompleteResponse(response); } } const payload = body as SlackRequestBody; if (body.type === PayloadType.EventsAPI) { // Events API const slackRequest: SlackRequest<E, SlackEvent<string>> = { payload: body.event, ...baseRequest, }; for (const matcher of this.#events) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (!body.type && body.command) { // Slash commands const slackRequest: SlackRequest<E, SlashCommand> = { payload: body as SlashCommand, ...baseRequest, }; for (const matcher of this.#slashCommands) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (body.type === PayloadType.GlobalShortcut) { // Global shortcuts const slackRequest: SlackRequest<E, GlobalShortcut> = { payload: body as GlobalShortcut, ...baseRequest, }; for (const matcher of this.#globalShorcuts) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (body.type === PayloadType.MessageShortcut) { // Message shortcuts const slackRequest: SlackRequest<E, MessageShortcut> = { payload: body as MessageShortcut, ...baseRequest, }; for (const matcher of this.#messageShorcuts) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (body.type === PayloadType.BlockAction) { // Block actions // deno-lint-ignore no-explicit-any const slackRequest: SlackRequest<E, BlockAction<any>> = { // deno-lint-ignore no-explicit-any payload: body as BlockAction<any>, ...baseRequest, }; for (const matcher of this.#blockActions) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (body.type === PayloadType.BlockSuggestion) { // Block suggestions const slackRequest: SlackRequest<E, BlockSuggestion> = { payload: body as BlockSuggestion, ...baseRequest, }; for (const matcher of this.#blockSuggestions) { const handler = matcher(payload); if (handler) { // Note that the only way to respond to a block_suggestion request // is to send an HTTP response with options/option_groups. // Thus, we don't support lazy handlers for this pattern. const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (body.type === PayloadType.ViewSubmission) { // View submissions const slackRequest: SlackRequest<E, ViewSubmission> = { payload: body as ViewSubmission, ...baseRequest, }; for (const matcher of this.#viewSubmissions) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (body.type === PayloadType.ViewClosed) { // View closed const slackRequest: SlackRequest<E, ViewClosed> = { payload: body as ViewClosed, ...baseRequest, }; for (const matcher of this.#viewClosed) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } // TODO: Add code suggestion here console.log( `*** No listener found ***\n${JSON.stringify(baseRequest.body)}` ); return new Response("No listener found", { status: 404 }); } return new Response("Invalid signature", { status: 401 }); } } export type StringOrRegExp = string | RegExp; export type EventRequest<E extends SlackAppEnv, T> = Extract< AnySlackEventWithChannelId, { type: T } > extends never ? SlackRequest<E, Extract<AnySlackEvent, { type: T }>> : SlackRequestWithChannelId< E, Extract<AnySlackEventWithChannelId, { type: T }> >; export type MessageEventPattern = string | RegExp | undefined; export type MessageEventRequest< E extends SlackAppEnv, ST extends string | undefined > = SlackRequestWithChannelId< E, Extract<AnySlackEventWithChannelId, { subtype: ST }> >; export type MessageEventSubtypes = | undefined | "bot_message" | "thread_broadcast" | "file_share"; export type MessageEventHandler<E extends SlackAppEnv> = ( req: MessageEventRequest<E, MessageEventSubtypes> ) => Promise<void>; export const noopLazyListener = async () => {};
src/app.ts
seratch-slack-edge-c75c224
[ { "filename": "src/oauth-app.ts", "retrieved_chunk": " routes: { events: options.routes?.events ?? \"/slack/events\" },\n });\n this.env = options.env;\n this.installationStore = options.installationStore;\n this.stateStore = options.stateStore ?? new NoStorageStateStore();\n this.oauth = {\n stateCookieName:\n options.oauth?.stateCookieName ?? \"slack-app-oauth-state\",\n onFailure: options.oauth?.onFailure ?? defaultOnFailure,\n onStateValidationError:", "score": 0.8800672292709351 }, { "filename": "src/socket-mode/socket-mode-client.ts", "retrieved_chunk": " }\n if (!app.appLevelToken) {\n throw new ConfigError(\n \"appLevelToken must be set for running with Socket Mode\"\n );\n }\n this.app = app as SlackApp<SlackSocketModeAppEnv>;\n this.appLevelToken = app.appLevelToken;\n console.warn(\n \"WARNING: The Socket Mode support provided by slack-edge is still experimental and is not designed to handle reconnections for production-grade applications. It is recommended to use this mode only for local development and testing purposes.\"", "score": 0.8663058876991272 }, { "filename": "src/oauth-app.ts", "retrieved_chunk": " };\n public routes: {\n events: string;\n oauth: { start: string; callback: string };\n oidc?: { start: string; callback: string };\n };\n constructor(options: SlackOAuthAppOptions<E>) {\n super({\n env: options.env,\n authorize: options.installationStore.toAuthorize(),", "score": 0.8640527129173279 }, { "filename": "src/socket-mode/socket-mode-client.ts", "retrieved_chunk": " public appLevelToken: string;\n public ws: WebSocket | undefined;\n constructor(\n // deno-lint-ignore no-explicit-any\n app: SlackApp<any>\n ) {\n if (!app.socketMode) {\n throw new ConfigError(\n \"socketMode: true must be set for running with Socket Mode\"\n );", "score": 0.8529164791107178 }, { "filename": "src/oauth-app.ts", "retrieved_chunk": " options.oauth?.onStateValidationError ?? defaultOnStateValidationError,\n redirectUri: options.oauth?.redirectUri ?? this.env.SLACK_REDIRECT_URI,\n };\n if (options.oidc) {\n this.oidc = {\n stateCookieName: options.oidc.stateCookieName ?? \"slack-app-oidc-state\",\n onFailure: options.oidc.onFailure ?? defaultOnFailure,\n onStateValidationError:\n options.oidc.onStateValidationError ?? defaultOnStateValidationError,\n callback: defaultOpenIDConnectCallback(this.env),", "score": 0.8491338491439819 } ]
typescript
this.appLevelToken = options.env.SLACK_APP_TOKEN;
import { SlackAppEnv, SlackEdgeAppEnv, SlackSocketModeAppEnv } from "./app-env"; import { parseRequestBody } from "./request/request-parser"; import { verifySlackRequest } from "./request/request-verification"; import { AckResponse, SlackHandler } from "./handler/handler"; import { SlackRequestBody } from "./request/request-body"; import { PreAuthorizeSlackMiddlwareRequest, SlackRequestWithRespond, SlackMiddlwareRequest, SlackRequestWithOptionalRespond, SlackRequest, SlackRequestWithChannelId, } from "./request/request"; import { SlashCommand } from "./request/payload/slash-command"; import { toCompleteResponse } from "./response/response"; import { SlackEvent, AnySlackEvent, AnySlackEventWithChannelId, } from "./request/payload/event"; import { ResponseUrlSender, SlackAPIClient } from "slack-web-api-client"; import { builtBaseContext, SlackAppContext, SlackAppContextWithChannelId, SlackAppContextWithRespond, } from "./context/context"; import { PreAuthorizeMiddleware, Middleware } from "./middleware/middleware"; import { isDebugLogEnabled, prettyPrint } from "slack-web-api-client"; import { Authorize } from "./authorization/authorize"; import { AuthorizeResult } from "./authorization/authorize-result"; import { ignoringSelfEvents, urlVerification, } from "./middleware/built-in-middleware"; import { ConfigError } from "./errors"; import { GlobalShortcut } from "./request/payload/global-shortcut"; import { MessageShortcut } from "./request/payload/message-shortcut"; import { BlockAction, BlockElementAction, BlockElementTypes, } from "./request/payload/block-action"; import { ViewSubmission } from "./request/payload/view-submission"; import { ViewClosed } from "./request/payload/view-closed"; import { BlockSuggestion } from "./request/payload/block-suggestion"; import { OptionsAckResponse, SlackOptionsHandler, } from "./handler/options-handler"; import { SlackViewHandler, ViewAckResponse } from "./handler/view-handler"; import { MessageAckResponse, SlackMessageHandler, } from "./handler/message-handler"; import { singleTeamAuthorize } from "./authorization/single-team-authorize"; import { ExecutionContext, NoopExecutionContext } from "./execution-context"; import { PayloadType } from "./request/payload-types"; import { isPostedMessageEvent } from "./utility/message-events"; import { SocketModeClient } from "./socket-mode/socket-mode-client"; export interface SlackAppOptions< E extends SlackEdgeAppEnv | SlackSocketModeAppEnv > { env: E; authorize?: Authorize<E>; routes?: { events: string; }; socketMode?: boolean; } export class SlackApp<E extends SlackEdgeAppEnv | SlackSocketModeAppEnv> { public env: E; public client: SlackAPIClient; public authorize: Authorize<E>; public routes: { events: string | undefined }; public signingSecret: string; public appLevelToken: string | undefined; public socketMode: boolean; public socketModeClient: SocketModeClient | undefined; // deno-lint-ignore no-explicit-any public preAuthorizeMiddleware: PreAuthorizeMiddleware<any>[] = [ urlVerification, ]; // deno-lint-ignore no-explicit-any public postAuthorizeMiddleware: Middleware<any>[] = [ignoringSelfEvents]; #slashCommands: (( body: SlackRequestBody ) => SlackMessageHandler<E, SlashCommand> | null)[] = []; #events: (( body: SlackRequestBody ) => SlackHandler<E, SlackEvent<string>> | null)[] = []; #globalShorcuts: (( body: SlackRequestBody ) => SlackHandler<E, GlobalShortcut> | null)[] = []; #messageShorcuts: (( body: SlackRequestBody ) => SlackHandler<E, MessageShortcut> | null)[] = []; #blockActions: ((body: SlackRequestBody) => SlackHandler< E, // deno-lint-ignore no-explicit-any BlockAction<any> > | null)[] = []; #blockSuggestions: (( body: SlackRequestBody ) => SlackOptionsHandler<E, BlockSuggestion> | null)[] = []; #viewSubmissions: (( body: SlackRequestBody ) => SlackViewHandler<E, ViewSubmission> | null)[] = []; #viewClosed: (( body: SlackRequestBody ) => SlackViewHandler<E, ViewClosed> | null)[] = []; constructor(options: SlackAppOptions<E>) { if ( options.env.SLACK_BOT_TOKEN === undefined && (options.authorize === undefined || options.authorize === singleTeamAuthorize) ) { throw new ConfigError( "When you don't pass env.SLACK_BOT_TOKEN, your own authorize function, which supplies a valid token to use, needs to be passed instead." ); } this.env = options.env; this.client = new SlackAPIClient(options.env.SLACK_BOT_TOKEN, { logLevel: this.env.SLACK_LOGGING_LEVEL, }); this.appLevelToken = options.env.SLACK_APP_TOKEN; this.socketMode = options.socketMode ?? this.appLevelToken !== undefined; if (this.socketMode) { this.signingSecret = ""; } else { if (!this.env.SLACK_SIGNING_SECRET) { throw new ConfigError( "env.SLACK_SIGNING_SECRET is required to run your app on edge functions!" ); } this.signingSecret = this.env.SLACK_SIGNING_SECRET; } this.authorize = options.authorize ?? singleTeamAuthorize; this.routes = { events: options.routes?.events }; } beforeAuthorize(middleware: PreAuthorizeMiddleware<E>): SlackApp<E> { this.preAuthorizeMiddleware.push(middleware); return this; } middleware(middleware: Middleware<E>): SlackApp<E> { return this.afterAuthorize(middleware); } use(middleware: Middleware<E>): SlackApp<E> { return this.afterAuthorize(middleware); } afterAuthorize(middleware: Middleware<E>): SlackApp<E> { this.postAuthorizeMiddleware.push(middleware); return this; } command( pattern: StringOrRegExp, ack: ( req: SlackRequestWithRespond<E, SlashCommand> ) => Promise<MessageAckResponse>, lazy: ( req: SlackRequestWithRespond<E, SlashCommand> ) => Promise<void> = noopLazyListener ): SlackApp<E> { const handler: SlackMessageHandler<E, SlashCommand> = { ack, lazy }; this.#slashCommands.push((body) => {
if (body.type || !body.command) {
return null; } if (typeof pattern === "string" && body.command === pattern) { return handler; } else if ( typeof pattern === "object" && pattern instanceof RegExp && body.command.match(pattern) ) { return handler; } return null; }); return this; } event<Type extends string>( event: Type, lazy: (req: EventRequest<E, Type>) => Promise<void> ): SlackApp<E> { this.#events.push((body) => { if (body.type !== PayloadType.EventsAPI || !body.event) { return null; } if (body.event.type === event) { // deno-lint-ignore require-await return { ack: async () => "", lazy }; } return null; }); return this; } anyMessage(lazy: MessageEventHandler<E>): SlackApp<E> { return this.message(undefined, lazy); } message( pattern: MessageEventPattern, lazy: MessageEventHandler<E> ): SlackApp<E> { this.#events.push((body) => { if ( body.type !== PayloadType.EventsAPI || !body.event || body.event.type !== "message" ) { return null; } if (isPostedMessageEvent(body.event)) { let matched = true; if (pattern !== undefined) { if (typeof pattern === "string") { matched = body.event.text!.includes(pattern); } if (typeof pattern === "object") { matched = body.event.text!.match(pattern) !== null; } } if (matched) { // deno-lint-ignore require-await return { ack: async (_: EventRequest<E, "message">) => "", lazy }; } } return null; }); return this; } shortcut( callbackId: StringOrRegExp, ack: ( req: | SlackRequest<E, GlobalShortcut> | SlackRequestWithRespond<E, MessageShortcut> ) => Promise<AckResponse>, lazy: ( req: | SlackRequest<E, GlobalShortcut> | SlackRequestWithRespond<E, MessageShortcut> ) => Promise<void> = noopLazyListener ): SlackApp<E> { return this.globalShortcut(callbackId, ack, lazy).messageShortcut( callbackId, ack, lazy ); } globalShortcut( callbackId: StringOrRegExp, ack: (req: SlackRequest<E, GlobalShortcut>) => Promise<AckResponse>, lazy: ( req: SlackRequest<E, GlobalShortcut> ) => Promise<void> = noopLazyListener ): SlackApp<E> { const handler: SlackHandler<E, GlobalShortcut> = { ack, lazy }; this.#globalShorcuts.push((body) => { if (body.type !== PayloadType.GlobalShortcut || !body.callback_id) { return null; } if (typeof callbackId === "string" && body.callback_id === callbackId) { return handler; } else if ( typeof callbackId === "object" && callbackId instanceof RegExp && body.callback_id.match(callbackId) ) { return handler; } return null; }); return this; } messageShortcut( callbackId: StringOrRegExp, ack: ( req: SlackRequestWithRespond<E, MessageShortcut> ) => Promise<AckResponse>, lazy: ( req: SlackRequestWithRespond<E, MessageShortcut> ) => Promise<void> = noopLazyListener ): SlackApp<E> { const handler: SlackHandler<E, MessageShortcut> = { ack, lazy }; this.#messageShorcuts.push((body) => { if (body.type !== PayloadType.MessageShortcut || !body.callback_id) { return null; } if (typeof callbackId === "string" && body.callback_id === callbackId) { return handler; } else if ( typeof callbackId === "object" && callbackId instanceof RegExp && body.callback_id.match(callbackId) ) { return handler; } return null; }); return this; } action< T extends BlockElementTypes, A extends BlockAction<BlockElementAction<T>> = BlockAction< BlockElementAction<T> > >( constraints: | StringOrRegExp | { type: T; block_id?: string; action_id: string }, ack: (req: SlackRequestWithOptionalRespond<E, A>) => Promise<AckResponse>, lazy: ( req: SlackRequestWithOptionalRespond<E, A> ) => Promise<void> = noopLazyListener ): SlackApp<E> { const handler: SlackHandler<E, A> = { ack, lazy }; this.#blockActions.push((body) => { if ( body.type !== PayloadType.BlockAction || !body.actions || !body.actions[0] ) { return null; } const action = body.actions[0]; if (typeof constraints === "string" && action.action_id === constraints) { return handler; } else if (typeof constraints === "object") { if (constraints instanceof RegExp) { if (action.action_id.match(constraints)) { return handler; } } else if (constraints.type) { if (action.type === constraints.type) { if (action.action_id === constraints.action_id) { if ( constraints.block_id && action.block_id !== constraints.block_id ) { return null; } return handler; } } } } return null; }); return this; } options( constraints: StringOrRegExp | { block_id?: string; action_id: string }, ack: (req: SlackRequest<E, BlockSuggestion>) => Promise<OptionsAckResponse> ): SlackApp<E> { // Note that block_suggestion response must be done within 3 seconds. // So, we don't support the lazy handler for it. const handler: SlackOptionsHandler<E, BlockSuggestion> = { ack }; this.#blockSuggestions.push((body) => { if (body.type !== PayloadType.BlockSuggestion || !body.action_id) { return null; } if (typeof constraints === "string" && body.action_id === constraints) { return handler; } else if (typeof constraints === "object") { if (constraints instanceof RegExp) { if (body.action_id.match(constraints)) { return handler; } } else { if (body.action_id === constraints.action_id) { if (body.block_id && body.block_id !== constraints.block_id) { return null; } return handler; } } } return null; }); return this; } view( callbackId: StringOrRegExp, ack: ( req: | SlackRequestWithOptionalRespond<E, ViewSubmission> | SlackRequest<E, ViewClosed> ) => Promise<ViewAckResponse>, lazy: ( req: | SlackRequestWithOptionalRespond<E, ViewSubmission> | SlackRequest<E, ViewClosed> ) => Promise<void> = noopLazyListener ): SlackApp<E> { return this.viewSubmission(callbackId, ack, lazy).viewClosed( callbackId, ack, lazy ); } viewSubmission( callbackId: StringOrRegExp, ack: ( req: SlackRequestWithOptionalRespond<E, ViewSubmission> ) => Promise<ViewAckResponse>, lazy: ( req: SlackRequestWithOptionalRespond<E, ViewSubmission> ) => Promise<void> = noopLazyListener ): SlackApp<E> { const handler: SlackViewHandler<E, ViewSubmission> = { ack, lazy }; this.#viewSubmissions.push((body) => { if (body.type !== PayloadType.ViewSubmission || !body.view) { return null; } if ( typeof callbackId === "string" && body.view.callback_id === callbackId ) { return handler; } else if ( typeof callbackId === "object" && callbackId instanceof RegExp && body.view.callback_id.match(callbackId) ) { return handler; } return null; }); return this; } viewClosed( callbackId: StringOrRegExp, ack: (req: SlackRequest<E, ViewClosed>) => Promise<ViewAckResponse>, lazy: (req: SlackRequest<E, ViewClosed>) => Promise<void> = noopLazyListener ): SlackApp<E> { const handler: SlackViewHandler<E, ViewClosed> = { ack, lazy }; this.#viewClosed.push((body) => { if (body.type !== PayloadType.ViewClosed || !body.view) { return null; } if ( typeof callbackId === "string" && body.view.callback_id === callbackId ) { return handler; } else if ( typeof callbackId === "object" && callbackId instanceof RegExp && body.view.callback_id.match(callbackId) ) { return handler; } return null; }); return this; } async run( request: Request, ctx: ExecutionContext = new NoopExecutionContext() ): Promise<Response> { return await this.handleEventRequest(request, ctx); } async connect(): Promise<void> { if (!this.socketMode) { throw new ConfigError( "Both env.SLACK_APP_TOKEN and socketMode: true are required to start a Socket Mode connection!" ); } this.socketModeClient = new SocketModeClient(this); await this.socketModeClient.connect(); } async disconnect(): Promise<void> { if (this.socketModeClient) { await this.socketModeClient.disconnect(); } } async handleEventRequest( request: Request, ctx: ExecutionContext ): Promise<Response> { // If the routes.events is missing, any URLs can work for handing requests from Slack if (this.routes.events) { const { pathname } = new URL(request.url); if (pathname !== this.routes.events) { return new Response("Not found", { status: 404 }); } } // To avoid the following warning by Cloudflware, parse the body as Blob first // Called .text() on an HTTP body which does not appear to be text .. const blobRequestBody = await request.blob(); // We can safely assume the incoming request body is always text data const rawBody: string = await blobRequestBody.text(); // For Request URL verification if (rawBody.includes("ssl_check=")) { // Slack does not send the x-slack-signature header for this pattern. // Thus, we need to check the pattern before verifying a request. const bodyParams = new URLSearchParams(rawBody); if (bodyParams.get("ssl_check") === "1" && bodyParams.get("token")) { return new Response("", { status: 200 }); } } // Verify the request headers and body const isRequestSignatureVerified = this.socketMode || (await verifySlackRequest(this.signingSecret, request.headers, rawBody)); if (isRequestSignatureVerified) { // deno-lint-ignore no-explicit-any const body: Record<string, any> = await parseRequestBody( request.headers, rawBody ); let retryNum: number | undefined = undefined; try { const retryNumHeader = request.headers.get("x-slack-retry-num"); if (retryNumHeader) { retryNum = Number.parseInt(retryNumHeader); } else if (this.socketMode && body.retry_attempt) { retryNum = Number.parseInt(body.retry_attempt); } // deno-lint-ignore no-unused-vars } catch (e) { // Ignore an exception here } const retryReason = request.headers.get("x-slack-retry-reason") ?? body.retry_reason; const preAuthorizeRequest: PreAuthorizeSlackMiddlwareRequest<E> = { body, rawBody, retryNum, retryReason, context: builtBaseContext(body), env: this.env, headers: request.headers, }; if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log(`*** Received request body ***\n ${prettyPrint(body)}`); } for (const middlware of this.preAuthorizeMiddleware) { const response = await middlware(preAuthorizeRequest); if (response) { return toCompleteResponse(response); } } const authorizeResult: AuthorizeResult = await this.authorize( preAuthorizeRequest ); const authorizedContext: SlackAppContext = { ...preAuthorizeRequest.context, authorizeResult, client: new SlackAPIClient(authorizeResult.botToken, { logLevel: this.env.SLACK_LOGGING_LEVEL, }), botToken: authorizeResult.botToken, botId: authorizeResult.botId, botUserId: authorizeResult.botUserId, userToken: authorizeResult.userToken, }; if (authorizedContext.channelId) { const context = authorizedContext as SlackAppContextWithChannelId; const client = new SlackAPIClient(context.botToken); context.say = async (params) => await client.chat.postMessage({ channel: context.channelId, ...params, }); } if (authorizedContext.responseUrl) { const responseUrl = authorizedContext.responseUrl; // deno-lint-ignore require-await (authorizedContext as SlackAppContextWithRespond).respond = async ( params ) => { return new ResponseUrlSender(responseUrl).call(params); }; } const baseRequest: SlackMiddlwareRequest<E> = { ...preAuthorizeRequest, context: authorizedContext, }; for (const middlware of this.postAuthorizeMiddleware) { const response = await middlware(baseRequest); if (response) { return toCompleteResponse(response); } } const payload = body as SlackRequestBody; if (body.type === PayloadType.EventsAPI) { // Events API const slackRequest: SlackRequest<E, SlackEvent<string>> = { payload: body.event, ...baseRequest, }; for (const matcher of this.#events) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (!body.type && body.command) { // Slash commands const slackRequest: SlackRequest<E, SlashCommand> = { payload: body as SlashCommand, ...baseRequest, }; for (const matcher of this.#slashCommands) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (body.type === PayloadType.GlobalShortcut) { // Global shortcuts const slackRequest: SlackRequest<E, GlobalShortcut> = { payload: body as GlobalShortcut, ...baseRequest, }; for (const matcher of this.#globalShorcuts) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (body.type === PayloadType.MessageShortcut) { // Message shortcuts const slackRequest: SlackRequest<E, MessageShortcut> = { payload: body as MessageShortcut, ...baseRequest, }; for (const matcher of this.#messageShorcuts) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (body.type === PayloadType.BlockAction) { // Block actions // deno-lint-ignore no-explicit-any const slackRequest: SlackRequest<E, BlockAction<any>> = { // deno-lint-ignore no-explicit-any payload: body as BlockAction<any>, ...baseRequest, }; for (const matcher of this.#blockActions) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (body.type === PayloadType.BlockSuggestion) { // Block suggestions const slackRequest: SlackRequest<E, BlockSuggestion> = { payload: body as BlockSuggestion, ...baseRequest, }; for (const matcher of this.#blockSuggestions) { const handler = matcher(payload); if (handler) { // Note that the only way to respond to a block_suggestion request // is to send an HTTP response with options/option_groups. // Thus, we don't support lazy handlers for this pattern. const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (body.type === PayloadType.ViewSubmission) { // View submissions const slackRequest: SlackRequest<E, ViewSubmission> = { payload: body as ViewSubmission, ...baseRequest, }; for (const matcher of this.#viewSubmissions) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (body.type === PayloadType.ViewClosed) { // View closed const slackRequest: SlackRequest<E, ViewClosed> = { payload: body as ViewClosed, ...baseRequest, }; for (const matcher of this.#viewClosed) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } // TODO: Add code suggestion here console.log( `*** No listener found ***\n${JSON.stringify(baseRequest.body)}` ); return new Response("No listener found", { status: 404 }); } return new Response("Invalid signature", { status: 401 }); } } export type StringOrRegExp = string | RegExp; export type EventRequest<E extends SlackAppEnv, T> = Extract< AnySlackEventWithChannelId, { type: T } > extends never ? SlackRequest<E, Extract<AnySlackEvent, { type: T }>> : SlackRequestWithChannelId< E, Extract<AnySlackEventWithChannelId, { type: T }> >; export type MessageEventPattern = string | RegExp | undefined; export type MessageEventRequest< E extends SlackAppEnv, ST extends string | undefined > = SlackRequestWithChannelId< E, Extract<AnySlackEventWithChannelId, { subtype: ST }> >; export type MessageEventSubtypes = | undefined | "bot_message" | "thread_broadcast" | "file_share"; export type MessageEventHandler<E extends SlackAppEnv> = ( req: MessageEventRequest<E, MessageEventSubtypes> ) => Promise<void>; export const noopLazyListener = async () => {};
src/app.ts
seratch-slack-edge-c75c224
[ { "filename": "src/handler/message-handler.ts", "retrieved_chunk": "import { SlackAppEnv } from \"../app-env\";\nimport { SlackRequest } from \"../request/request\";\nimport { MessageResponse } from \"../response/response-body\";\nimport { AckResponse } from \"./handler\";\nexport type MessageAckResponse = AckResponse | MessageResponse;\nexport interface SlackMessageHandler<E extends SlackAppEnv, Payload> {\n ack(request: SlackRequest<E, Payload>): Promise<MessageAckResponse>;\n lazy(request: SlackRequest<E, Payload>): Promise<void>;\n}", "score": 0.8879803419113159 }, { "filename": "src/handler/handler.ts", "retrieved_chunk": "import { SlackAppEnv } from \"../app-env\";\nimport { SlackRequest } from \"../request/request\";\nimport { SlackResponse } from \"../response/response\";\nexport type AckResponse = SlackResponse | string | void;\nexport interface SlackHandler<E extends SlackAppEnv, Payload> {\n ack(request: SlackRequest<E, Payload>): Promise<AckResponse>;\n lazy(request: SlackRequest<E, Payload>): Promise<void>;\n}", "score": 0.8774429559707642 }, { "filename": "src/handler/view-handler.ts", "retrieved_chunk": "import { SlackAppEnv } from \"../app-env\";\nimport { SlackRequest } from \"../request/request\";\nimport { SlackViewResponse } from \"../response/response\";\nexport type ViewAckResponse = SlackViewResponse | void;\nexport type SlackViewHandler<E extends SlackAppEnv, Payload> = {\n ack(request: SlackRequest<E, Payload>): Promise<ViewAckResponse>;\n lazy(request: SlackRequest<E, Payload>): Promise<void>;\n};", "score": 0.8550457954406738 }, { "filename": "src/handler/options-handler.ts", "retrieved_chunk": "import { SlackAppEnv } from \"../app-env\";\nimport { SlackRequest } from \"../request/request\";\nimport { SlackOptionsResponse } from \"../response/response\";\nexport type OptionsAckResponse = SlackOptionsResponse;\nexport interface SlackOptionsHandler<E extends SlackAppEnv, Payload> {\n ack(request: SlackRequest<E, Payload>): Promise<OptionsAckResponse>;\n // Note that a block_suggestion response must be done synchronously.\n // That's why we don't support lazy functions for the pattern.\n}", "score": 0.8364858627319336 }, { "filename": "src/middleware/middleware.ts", "retrieved_chunk": " req: SlackMiddlwareRequest<E>\n) => Promise<SlackResponse | void>;", "score": 0.8123351335525513 } ]
typescript
if (body.type || !body.command) {
import { SlackAppEnv, SlackEdgeAppEnv, SlackSocketModeAppEnv } from "./app-env"; import { parseRequestBody } from "./request/request-parser"; import { verifySlackRequest } from "./request/request-verification"; import { AckResponse, SlackHandler } from "./handler/handler"; import { SlackRequestBody } from "./request/request-body"; import { PreAuthorizeSlackMiddlwareRequest, SlackRequestWithRespond, SlackMiddlwareRequest, SlackRequestWithOptionalRespond, SlackRequest, SlackRequestWithChannelId, } from "./request/request"; import { SlashCommand } from "./request/payload/slash-command"; import { toCompleteResponse } from "./response/response"; import { SlackEvent, AnySlackEvent, AnySlackEventWithChannelId, } from "./request/payload/event"; import { ResponseUrlSender, SlackAPIClient } from "slack-web-api-client"; import { builtBaseContext, SlackAppContext, SlackAppContextWithChannelId, SlackAppContextWithRespond, } from "./context/context"; import { PreAuthorizeMiddleware, Middleware } from "./middleware/middleware"; import { isDebugLogEnabled, prettyPrint } from "slack-web-api-client"; import { Authorize } from "./authorization/authorize"; import { AuthorizeResult } from "./authorization/authorize-result"; import { ignoringSelfEvents, urlVerification, } from "./middleware/built-in-middleware"; import { ConfigError } from "./errors"; import { GlobalShortcut } from "./request/payload/global-shortcut"; import { MessageShortcut } from "./request/payload/message-shortcut"; import { BlockAction, BlockElementAction, BlockElementTypes, } from "./request/payload/block-action"; import { ViewSubmission } from "./request/payload/view-submission"; import { ViewClosed } from "./request/payload/view-closed"; import { BlockSuggestion } from "./request/payload/block-suggestion"; import { OptionsAckResponse, SlackOptionsHandler, } from "./handler/options-handler"; import { SlackViewHandler, ViewAckResponse } from "./handler/view-handler"; import { MessageAckResponse, SlackMessageHandler, } from "./handler/message-handler"; import { singleTeamAuthorize } from "./authorization/single-team-authorize"; import { ExecutionContext, NoopExecutionContext } from "./execution-context"; import { PayloadType } from "./request/payload-types"; import { isPostedMessageEvent } from "./utility/message-events"; import { SocketModeClient } from "./socket-mode/socket-mode-client"; export interface SlackAppOptions< E extends SlackEdgeAppEnv | SlackSocketModeAppEnv > { env: E; authorize?: Authorize<E>; routes?: { events: string; }; socketMode?: boolean; } export class SlackApp<E extends SlackEdgeAppEnv | SlackSocketModeAppEnv> { public env: E; public client: SlackAPIClient; public authorize: Authorize<E>; public routes: { events: string | undefined }; public signingSecret: string; public appLevelToken: string | undefined; public socketMode: boolean; public socketModeClient: SocketModeClient | undefined; // deno-lint-ignore no-explicit-any public preAuthorizeMiddleware: PreAuthorizeMiddleware<any>[] = [ urlVerification, ]; // deno-lint-ignore no-explicit-any public postAuthorizeMiddleware: Middleware<any>[] = [ignoringSelfEvents]; #slashCommands: (( body: SlackRequestBody ) => SlackMessageHandler<E, SlashCommand> | null)[] = []; #events: (( body: SlackRequestBody ) => SlackHandler<E, SlackEvent<string>> | null)[] = []; #globalShorcuts: (( body: SlackRequestBody ) => SlackHandler<E, GlobalShortcut> | null)[] = []; #messageShorcuts: (( body: SlackRequestBody ) => SlackHandler<E, MessageShortcut> | null)[] = []; #blockActions: ((body: SlackRequestBody) => SlackHandler< E, // deno-lint-ignore no-explicit-any BlockAction<any> > | null)[] = []; #blockSuggestions: (( body: SlackRequestBody ) => SlackOptionsHandler<E, BlockSuggestion> | null)[] = []; #viewSubmissions: (( body: SlackRequestBody ) => SlackViewHandler<E, ViewSubmission> | null)[] = []; #viewClosed: (( body: SlackRequestBody ) => SlackViewHandler<E, ViewClosed> | null)[] = []; constructor(options: SlackAppOptions<E>) { if ( options.env.SLACK_BOT_TOKEN === undefined && (options.authorize === undefined || options.authorize === singleTeamAuthorize) ) { throw new ConfigError( "When you don't pass env.SLACK_BOT_TOKEN, your own authorize function, which supplies a valid token to use, needs to be passed instead." ); } this.env = options.env; this.client = new SlackAPIClient(options.env.SLACK_BOT_TOKEN, { logLevel: this.env.SLACK_LOGGING_LEVEL, }); this.appLevelToken = options.env.SLACK_APP_TOKEN; this.socketMode = options.socketMode ?? this.appLevelToken !== undefined; if (this.socketMode) { this.signingSecret = ""; } else { if (!this.env.SLACK_SIGNING_SECRET) { throw new ConfigError( "env.SLACK_SIGNING_SECRET is required to run your app on edge functions!" ); } this.signingSecret = this.env.SLACK_SIGNING_SECRET; } this.authorize = options.authorize ?? singleTeamAuthorize; this.routes = { events: options.routes?.events }; } beforeAuthorize(middleware: PreAuthorizeMiddleware<E>): SlackApp<E> { this.preAuthorizeMiddleware.push(middleware); return this; } middleware(middleware: Middleware<E>): SlackApp<E> { return this.afterAuthorize(middleware); } use(middleware: Middleware<E>): SlackApp<E> { return this.afterAuthorize(middleware); } afterAuthorize(middleware: Middleware<E>): SlackApp<E> { this.postAuthorizeMiddleware.push(middleware); return this; } command( pattern: StringOrRegExp, ack: ( req: SlackRequestWithRespond<E, SlashCommand> ) => Promise<MessageAckResponse>, lazy: ( req: SlackRequestWithRespond<E, SlashCommand> ) => Promise<void> = noopLazyListener ): SlackApp<E> { const handler: SlackMessageHandler<E, SlashCommand> = { ack, lazy }; this.#slashCommands.push((body) => { if (body.type || !body.command) { return null; } if (typeof pattern === "string" && body.command === pattern) { return handler; } else if ( typeof pattern === "object" && pattern instanceof RegExp && body.command.match(pattern) ) { return handler; } return null; }); return this; } event<Type extends string>( event: Type, lazy: (req: EventRequest<E, Type>) => Promise<void> ): SlackApp<E> { this.#events.push((body) => { if (body.type !== PayloadType.EventsAPI || !body.event) { return null; } if (body.event.type === event) { // deno-lint-ignore require-await return { ack: async () => "", lazy }; } return null; }); return this; } anyMessage(lazy: MessageEventHandler<E>): SlackApp<E> { return this.message(undefined, lazy); } message( pattern: MessageEventPattern, lazy: MessageEventHandler<E> ): SlackApp<E> { this.#events.push((body) => { if ( body.type !== PayloadType.EventsAPI || !body.event || body.event.type !== "message" ) { return null; } if (isPostedMessageEvent(body.event)) { let matched = true; if (pattern !== undefined) { if (typeof pattern === "string") { matched = body.event.text!.includes(pattern); } if (typeof pattern === "object") { matched = body.event.text!.match(pattern) !== null; } } if (matched) { // deno-lint-ignore require-await return { ack: async (_: EventRequest<E, "message">) => "", lazy }; } } return null; }); return this; } shortcut( callbackId: StringOrRegExp, ack: ( req: | SlackRequest<E, GlobalShortcut> | SlackRequestWithRespond<E, MessageShortcut> ) => Promise<AckResponse>, lazy: ( req: | SlackRequest<E, GlobalShortcut> | SlackRequestWithRespond<E, MessageShortcut> ) => Promise<void> = noopLazyListener ): SlackApp<E> { return this.globalShortcut(callbackId, ack, lazy).messageShortcut( callbackId, ack, lazy ); } globalShortcut( callbackId: StringOrRegExp, ack: (req: SlackRequest<E, GlobalShortcut>) => Promise<AckResponse>, lazy: ( req: SlackRequest<E, GlobalShortcut> ) => Promise<void> = noopLazyListener ): SlackApp<E> { const handler: SlackHandler<E, GlobalShortcut> = { ack, lazy }; this.#globalShorcuts.push((body) => { if (body.type !== PayloadType.GlobalShortcut || !body.callback_id) { return null; } if (typeof callbackId === "string" && body.callback_id === callbackId) { return handler; } else if ( typeof callbackId === "object" && callbackId instanceof RegExp && body.callback_id.match(callbackId) ) { return handler; } return null; }); return this; } messageShortcut( callbackId: StringOrRegExp, ack: ( req: SlackRequestWithRespond<E, MessageShortcut> ) => Promise<AckResponse>, lazy: ( req: SlackRequestWithRespond<E, MessageShortcut> ) => Promise<void> = noopLazyListener ): SlackApp<E> { const handler: SlackHandler<E, MessageShortcut> = { ack, lazy }; this.#messageShorcuts.push((body) => { if (body.type !== PayloadType.MessageShortcut || !body.callback_id) { return null; } if (typeof callbackId === "string" && body.callback_id === callbackId) { return handler; } else if ( typeof callbackId === "object" && callbackId instanceof RegExp && body.callback_id.match(callbackId) ) { return handler; } return null; }); return this; } action< T extends BlockElementTypes, A extends BlockAction<BlockElementAction<T>> = BlockAction< BlockElementAction<T> > >( constraints: | StringOrRegExp | { type: T; block_id?: string; action_id: string }, ack: (req: SlackRequestWithOptionalRespond<E, A>) => Promise<AckResponse>, lazy: ( req: SlackRequestWithOptionalRespond<E, A> ) => Promise<void> = noopLazyListener ): SlackApp<E> { const handler: SlackHandler<E, A> = { ack, lazy }; this.#blockActions.push((body) => { if ( body.type !== PayloadType.BlockAction || !body.actions || !body.actions[0] ) { return null; } const action = body.actions[0]; if (typeof constraints === "string" && action.action_id === constraints) { return handler; } else if (typeof constraints === "object") { if (constraints instanceof RegExp) { if (action.action_id.match(constraints)) { return handler; } } else if (constraints.type) { if (action.type === constraints.type) { if (action.action_id === constraints.action_id) { if ( constraints.block_id && action.block_id !== constraints.block_id ) { return null; } return handler; } } } } return null; }); return this; } options( constraints: StringOrRegExp | { block_id?: string; action_id: string }, ack: (req: SlackRequest<E, BlockSuggestion>) => Promise<OptionsAckResponse> ): SlackApp<E> { // Note that block_suggestion response must be done within 3 seconds. // So, we don't support the lazy handler for it. const handler: SlackOptionsHandler<E, BlockSuggestion> = { ack }; this.#blockSuggestions.push((body) => { if (body.type !== PayloadType.BlockSuggestion || !body.action_id) { return null; } if (typeof constraints === "string" && body.action_id === constraints) { return handler; } else if (typeof constraints === "object") { if (constraints instanceof RegExp) { if (body.action_id.match(constraints)) { return handler; } } else { if (body.action_id === constraints.action_id) { if (body.block_id && body.block_id !== constraints.block_id) { return null; } return handler; } } } return null; }); return this; } view( callbackId: StringOrRegExp, ack: ( req: | SlackRequestWithOptionalRespond<E, ViewSubmission> | SlackRequest<E, ViewClosed> ) => Promise<ViewAckResponse>, lazy: ( req: | SlackRequestWithOptionalRespond<E, ViewSubmission> | SlackRequest<E, ViewClosed> ) => Promise<void> = noopLazyListener ): SlackApp<E> { return this.viewSubmission(callbackId, ack, lazy).viewClosed( callbackId, ack, lazy ); } viewSubmission( callbackId: StringOrRegExp, ack: ( req: SlackRequestWithOptionalRespond<E, ViewSubmission> ) => Promise<ViewAckResponse>, lazy: ( req: SlackRequestWithOptionalRespond<E, ViewSubmission> ) => Promise<void> = noopLazyListener ): SlackApp<E> { const handler: SlackViewHandler<E, ViewSubmission> = { ack, lazy }; this.#viewSubmissions.push((body) => {
if (body.type !== PayloadType.ViewSubmission || !body.view) {
return null; } if ( typeof callbackId === "string" && body.view.callback_id === callbackId ) { return handler; } else if ( typeof callbackId === "object" && callbackId instanceof RegExp && body.view.callback_id.match(callbackId) ) { return handler; } return null; }); return this; } viewClosed( callbackId: StringOrRegExp, ack: (req: SlackRequest<E, ViewClosed>) => Promise<ViewAckResponse>, lazy: (req: SlackRequest<E, ViewClosed>) => Promise<void> = noopLazyListener ): SlackApp<E> { const handler: SlackViewHandler<E, ViewClosed> = { ack, lazy }; this.#viewClosed.push((body) => { if (body.type !== PayloadType.ViewClosed || !body.view) { return null; } if ( typeof callbackId === "string" && body.view.callback_id === callbackId ) { return handler; } else if ( typeof callbackId === "object" && callbackId instanceof RegExp && body.view.callback_id.match(callbackId) ) { return handler; } return null; }); return this; } async run( request: Request, ctx: ExecutionContext = new NoopExecutionContext() ): Promise<Response> { return await this.handleEventRequest(request, ctx); } async connect(): Promise<void> { if (!this.socketMode) { throw new ConfigError( "Both env.SLACK_APP_TOKEN and socketMode: true are required to start a Socket Mode connection!" ); } this.socketModeClient = new SocketModeClient(this); await this.socketModeClient.connect(); } async disconnect(): Promise<void> { if (this.socketModeClient) { await this.socketModeClient.disconnect(); } } async handleEventRequest( request: Request, ctx: ExecutionContext ): Promise<Response> { // If the routes.events is missing, any URLs can work for handing requests from Slack if (this.routes.events) { const { pathname } = new URL(request.url); if (pathname !== this.routes.events) { return new Response("Not found", { status: 404 }); } } // To avoid the following warning by Cloudflware, parse the body as Blob first // Called .text() on an HTTP body which does not appear to be text .. const blobRequestBody = await request.blob(); // We can safely assume the incoming request body is always text data const rawBody: string = await blobRequestBody.text(); // For Request URL verification if (rawBody.includes("ssl_check=")) { // Slack does not send the x-slack-signature header for this pattern. // Thus, we need to check the pattern before verifying a request. const bodyParams = new URLSearchParams(rawBody); if (bodyParams.get("ssl_check") === "1" && bodyParams.get("token")) { return new Response("", { status: 200 }); } } // Verify the request headers and body const isRequestSignatureVerified = this.socketMode || (await verifySlackRequest(this.signingSecret, request.headers, rawBody)); if (isRequestSignatureVerified) { // deno-lint-ignore no-explicit-any const body: Record<string, any> = await parseRequestBody( request.headers, rawBody ); let retryNum: number | undefined = undefined; try { const retryNumHeader = request.headers.get("x-slack-retry-num"); if (retryNumHeader) { retryNum = Number.parseInt(retryNumHeader); } else if (this.socketMode && body.retry_attempt) { retryNum = Number.parseInt(body.retry_attempt); } // deno-lint-ignore no-unused-vars } catch (e) { // Ignore an exception here } const retryReason = request.headers.get("x-slack-retry-reason") ?? body.retry_reason; const preAuthorizeRequest: PreAuthorizeSlackMiddlwareRequest<E> = { body, rawBody, retryNum, retryReason, context: builtBaseContext(body), env: this.env, headers: request.headers, }; if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log(`*** Received request body ***\n ${prettyPrint(body)}`); } for (const middlware of this.preAuthorizeMiddleware) { const response = await middlware(preAuthorizeRequest); if (response) { return toCompleteResponse(response); } } const authorizeResult: AuthorizeResult = await this.authorize( preAuthorizeRequest ); const authorizedContext: SlackAppContext = { ...preAuthorizeRequest.context, authorizeResult, client: new SlackAPIClient(authorizeResult.botToken, { logLevel: this.env.SLACK_LOGGING_LEVEL, }), botToken: authorizeResult.botToken, botId: authorizeResult.botId, botUserId: authorizeResult.botUserId, userToken: authorizeResult.userToken, }; if (authorizedContext.channelId) { const context = authorizedContext as SlackAppContextWithChannelId; const client = new SlackAPIClient(context.botToken); context.say = async (params) => await client.chat.postMessage({ channel: context.channelId, ...params, }); } if (authorizedContext.responseUrl) { const responseUrl = authorizedContext.responseUrl; // deno-lint-ignore require-await (authorizedContext as SlackAppContextWithRespond).respond = async ( params ) => { return new ResponseUrlSender(responseUrl).call(params); }; } const baseRequest: SlackMiddlwareRequest<E> = { ...preAuthorizeRequest, context: authorizedContext, }; for (const middlware of this.postAuthorizeMiddleware) { const response = await middlware(baseRequest); if (response) { return toCompleteResponse(response); } } const payload = body as SlackRequestBody; if (body.type === PayloadType.EventsAPI) { // Events API const slackRequest: SlackRequest<E, SlackEvent<string>> = { payload: body.event, ...baseRequest, }; for (const matcher of this.#events) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (!body.type && body.command) { // Slash commands const slackRequest: SlackRequest<E, SlashCommand> = { payload: body as SlashCommand, ...baseRequest, }; for (const matcher of this.#slashCommands) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (body.type === PayloadType.GlobalShortcut) { // Global shortcuts const slackRequest: SlackRequest<E, GlobalShortcut> = { payload: body as GlobalShortcut, ...baseRequest, }; for (const matcher of this.#globalShorcuts) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (body.type === PayloadType.MessageShortcut) { // Message shortcuts const slackRequest: SlackRequest<E, MessageShortcut> = { payload: body as MessageShortcut, ...baseRequest, }; for (const matcher of this.#messageShorcuts) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (body.type === PayloadType.BlockAction) { // Block actions // deno-lint-ignore no-explicit-any const slackRequest: SlackRequest<E, BlockAction<any>> = { // deno-lint-ignore no-explicit-any payload: body as BlockAction<any>, ...baseRequest, }; for (const matcher of this.#blockActions) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (body.type === PayloadType.BlockSuggestion) { // Block suggestions const slackRequest: SlackRequest<E, BlockSuggestion> = { payload: body as BlockSuggestion, ...baseRequest, }; for (const matcher of this.#blockSuggestions) { const handler = matcher(payload); if (handler) { // Note that the only way to respond to a block_suggestion request // is to send an HTTP response with options/option_groups. // Thus, we don't support lazy handlers for this pattern. const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (body.type === PayloadType.ViewSubmission) { // View submissions const slackRequest: SlackRequest<E, ViewSubmission> = { payload: body as ViewSubmission, ...baseRequest, }; for (const matcher of this.#viewSubmissions) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (body.type === PayloadType.ViewClosed) { // View closed const slackRequest: SlackRequest<E, ViewClosed> = { payload: body as ViewClosed, ...baseRequest, }; for (const matcher of this.#viewClosed) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } // TODO: Add code suggestion here console.log( `*** No listener found ***\n${JSON.stringify(baseRequest.body)}` ); return new Response("No listener found", { status: 404 }); } return new Response("Invalid signature", { status: 401 }); } } export type StringOrRegExp = string | RegExp; export type EventRequest<E extends SlackAppEnv, T> = Extract< AnySlackEventWithChannelId, { type: T } > extends never ? SlackRequest<E, Extract<AnySlackEvent, { type: T }>> : SlackRequestWithChannelId< E, Extract<AnySlackEventWithChannelId, { type: T }> >; export type MessageEventPattern = string | RegExp | undefined; export type MessageEventRequest< E extends SlackAppEnv, ST extends string | undefined > = SlackRequestWithChannelId< E, Extract<AnySlackEventWithChannelId, { subtype: ST }> >; export type MessageEventSubtypes = | undefined | "bot_message" | "thread_broadcast" | "file_share"; export type MessageEventHandler<E extends SlackAppEnv> = ( req: MessageEventRequest<E, MessageEventSubtypes> ) => Promise<void>; export const noopLazyListener = async () => {};
src/app.ts
seratch-slack-edge-c75c224
[ { "filename": "src/handler/view-handler.ts", "retrieved_chunk": "import { SlackAppEnv } from \"../app-env\";\nimport { SlackRequest } from \"../request/request\";\nimport { SlackViewResponse } from \"../response/response\";\nexport type ViewAckResponse = SlackViewResponse | void;\nexport type SlackViewHandler<E extends SlackAppEnv, Payload> = {\n ack(request: SlackRequest<E, Payload>): Promise<ViewAckResponse>;\n lazy(request: SlackRequest<E, Payload>): Promise<void>;\n};", "score": 0.9133676886558533 }, { "filename": "src/handler/handler.ts", "retrieved_chunk": "import { SlackAppEnv } from \"../app-env\";\nimport { SlackRequest } from \"../request/request\";\nimport { SlackResponse } from \"../response/response\";\nexport type AckResponse = SlackResponse | string | void;\nexport interface SlackHandler<E extends SlackAppEnv, Payload> {\n ack(request: SlackRequest<E, Payload>): Promise<AckResponse>;\n lazy(request: SlackRequest<E, Payload>): Promise<void>;\n}", "score": 0.8685986995697021 }, { "filename": "src/handler/message-handler.ts", "retrieved_chunk": "import { SlackAppEnv } from \"../app-env\";\nimport { SlackRequest } from \"../request/request\";\nimport { MessageResponse } from \"../response/response-body\";\nimport { AckResponse } from \"./handler\";\nexport type MessageAckResponse = AckResponse | MessageResponse;\nexport interface SlackMessageHandler<E extends SlackAppEnv, Payload> {\n ack(request: SlackRequest<E, Payload>): Promise<MessageAckResponse>;\n lazy(request: SlackRequest<E, Payload>): Promise<void>;\n}", "score": 0.8679402470588684 }, { "filename": "src/handler/options-handler.ts", "retrieved_chunk": "import { SlackAppEnv } from \"../app-env\";\nimport { SlackRequest } from \"../request/request\";\nimport { SlackOptionsResponse } from \"../response/response\";\nexport type OptionsAckResponse = SlackOptionsResponse;\nexport interface SlackOptionsHandler<E extends SlackAppEnv, Payload> {\n ack(request: SlackRequest<E, Payload>): Promise<OptionsAckResponse>;\n // Note that a block_suggestion response must be done synchronously.\n // That's why we don't support lazy functions for the pattern.\n}", "score": 0.8285363912582397 }, { "filename": "src/socket-mode/socket-mode-client.ts", "retrieved_chunk": " console.info(`Completed a lazy listener execution: ${res}`);\n })\n .catch((err) => {\n console.error(`Failed to run a lazy listener: ${err}`);\n });\n },\n };\n const response = await app.run(request, context);\n // deno-lint-ignore no-explicit-any\n let ack: any = { envelope_id: data.envelope_id };", "score": 0.8094561696052551 } ]
typescript
if (body.type !== PayloadType.ViewSubmission || !body.view) {
import { ExecutionContext, NoopExecutionContext } from "./execution-context"; import { SlackApp } from "./app"; import { SlackOAuthEnv } from "./app-env"; import { InstallationStore } from "./oauth/installation-store"; import { NoStorageStateStore, StateStore } from "./oauth/state-store"; import { renderCompletionPage, renderStartPage, } from "./oauth/oauth-page-renderer"; import { generateAuthorizeUrl } from "./oauth/authorize-url-generator"; import { parse as parseCookie } from "./cookie"; import { SlackAPIClient, OAuthV2AccessResponse, OpenIDConnectTokenResponse, } from "slack-web-api-client"; import { toInstallation } from "./oauth/installation"; import { AfterInstallation, BeforeInstallation, OnFailure, OnStateValidationError, defaultOnFailure, defaultOnStateValidationError, } from "./oauth/callback"; import { OpenIDConnectCallback, defaultOpenIDConnectCallback, } from "./oidc/callback"; import { generateOIDCAuthorizeUrl } from "./oidc/authorize-url-generator"; import { InstallationError, MissingCode, CompletionPageError, InstallationStoreError, OpenIDConnectError, } from "./oauth/error-codes"; export interface SlackOAuthAppOptions<E extends SlackOAuthEnv> { env: E; installationStore: InstallationStore<E>; stateStore?: StateStore; oauth?: { stateCookieName?: string; beforeInstallation?: BeforeInstallation; afterInstallation?: AfterInstallation; onFailure?: OnFailure; onStateValidationError?: OnStateValidationError; redirectUri?: string; }; oidc?: { stateCookieName?: string; callback: OpenIDConnectCallback; onFailure?: OnFailure; onStateValidationError?: OnStateValidationError; redirectUri?: string; }; routes?: { events: string; oauth: { start: string; callback: string }; oidc?: { start: string; callback: string }; }; } export class
SlackOAuthApp<E extends SlackOAuthEnv> extends SlackApp<E> {
public env: E; public installationStore: InstallationStore<E>; public stateStore: StateStore; public oauth: { stateCookieName?: string; beforeInstallation?: BeforeInstallation; afterInstallation?: AfterInstallation; onFailure: OnFailure; onStateValidationError: OnStateValidationError; redirectUri?: string; }; public oidc?: { stateCookieName?: string; callback: OpenIDConnectCallback; onFailure: OnFailure; onStateValidationError: OnStateValidationError; redirectUri?: string; }; public routes: { events: string; oauth: { start: string; callback: string }; oidc?: { start: string; callback: string }; }; constructor(options: SlackOAuthAppOptions<E>) { super({ env: options.env, authorize: options.installationStore.toAuthorize(), routes: { events: options.routes?.events ?? "/slack/events" }, }); this.env = options.env; this.installationStore = options.installationStore; this.stateStore = options.stateStore ?? new NoStorageStateStore(); this.oauth = { stateCookieName: options.oauth?.stateCookieName ?? "slack-app-oauth-state", onFailure: options.oauth?.onFailure ?? defaultOnFailure, onStateValidationError: options.oauth?.onStateValidationError ?? defaultOnStateValidationError, redirectUri: options.oauth?.redirectUri ?? this.env.SLACK_REDIRECT_URI, }; if (options.oidc) { this.oidc = { stateCookieName: options.oidc.stateCookieName ?? "slack-app-oidc-state", onFailure: options.oidc.onFailure ?? defaultOnFailure, onStateValidationError: options.oidc.onStateValidationError ?? defaultOnStateValidationError, callback: defaultOpenIDConnectCallback(this.env), redirectUri: options.oidc.redirectUri ?? this.env.SLACK_OIDC_REDIRECT_URI, }; } else { this.oidc = undefined; } this.routes = options.routes ? options.routes : { events: "/slack/events", oauth: { start: "/slack/install", callback: "/slack/oauth_redirect", }, oidc: { start: "/slack/login", callback: "/slack/login/callback", }, }; } async run( request: Request, ctx: ExecutionContext = new NoopExecutionContext() ): Promise<Response> { const url = new URL(request.url); if (request.method === "GET") { if (url.pathname === this.routes.oauth.start) { return await this.handleOAuthStartRequest(request); } else if (url.pathname === this.routes.oauth.callback) { return await this.handleOAuthCallbackRequest(request); } if (this.routes.oidc) { if (url.pathname === this.routes.oidc.start) { return await this.handleOIDCStartRequest(request); } else if (url.pathname === this.routes.oidc.callback) { return await this.handleOIDCCallbackRequest(request); } } } else if (request.method === "POST") { if (url.pathname === this.routes.events) { return await this.handleEventRequest(request, ctx); } } return new Response("Not found", { status: 404 }); } async handleEventRequest( request: Request, ctx: ExecutionContext ): Promise<Response> { return await super.handleEventRequest(request, ctx); } // deno-lint-ignore no-unused-vars async handleOAuthStartRequest(request: Request): Promise<Response> { const stateValue = await this.stateStore.issueNewState(); const authorizeUrl = generateAuthorizeUrl(stateValue, this.env); return new Response(renderStartPage(authorizeUrl), { status: 302, headers: { Location: authorizeUrl, "Set-Cookie": `${this.oauth.stateCookieName}=${stateValue}; Secure; HttpOnly; Path=/; Max-Age=300`, "Content-Type": "text/html; charset=utf-8", }, }); } async handleOAuthCallbackRequest(request: Request): Promise<Response> { // State parameter validation await this.#validateStateParameter( request, this.routes.oauth.start, this.oauth.stateCookieName! ); const { searchParams } = new URL(request.url); const code = searchParams.get("code"); if (!code) { return await this.oauth.onFailure( this.routes.oauth.start, MissingCode, request ); } const client = new SlackAPIClient(undefined, { logLevel: this.env.SLACK_LOGGING_LEVEL, }); let oauthAccess: OAuthV2AccessResponse | undefined; try { // Execute the installation process oauthAccess = await client.oauth.v2.access({ client_id: this.env.SLACK_CLIENT_ID, client_secret: this.env.SLACK_CLIENT_SECRET, redirect_uri: this.oauth.redirectUri, code, }); } catch (e) { console.log(e); return await this.oauth.onFailure( this.routes.oauth.start, InstallationError, request ); } try { // Store the installation data on this app side await this.installationStore.save(toInstallation(oauthAccess), request); } catch (e) { console.log(e); return await this.oauth.onFailure( this.routes.oauth.start, InstallationStoreError, request ); } try { // Build the completion page const authTest = await client.auth.test({ token: oauthAccess.access_token, }); const enterpriseUrl = authTest.url; return new Response( renderCompletionPage( oauthAccess.app_id!, oauthAccess.team?.id!, oauthAccess.is_enterprise_install, enterpriseUrl ), { status: 200, headers: { "Set-Cookie": `${this.oauth.stateCookieName}=deleted; Secure; HttpOnly; Path=/; Max-Age=0`, "Content-Type": "text/html; charset=utf-8", }, } ); } catch (e) { console.log(e); return await this.oauth.onFailure( this.routes.oauth.start, CompletionPageError, request ); } } // deno-lint-ignore no-unused-vars async handleOIDCStartRequest(request: Request): Promise<Response> { if (!this.oidc) { return new Response("Not found", { status: 404 }); } const stateValue = await this.stateStore.issueNewState(); const authorizeUrl = generateOIDCAuthorizeUrl(stateValue, this.env); return new Response(renderStartPage(authorizeUrl), { status: 302, headers: { Location: authorizeUrl, "Set-Cookie": `${this.oidc.stateCookieName}=${stateValue}; Secure; HttpOnly; Path=/; Max-Age=300`, "Content-Type": "text/html; charset=utf-8", }, }); } async handleOIDCCallbackRequest(request: Request): Promise<Response> { if (!this.oidc || !this.routes.oidc) { return new Response("Not found", { status: 404 }); } // State parameter validation await this.#validateStateParameter( request, this.routes.oidc.start, this.oidc.stateCookieName! ); const { searchParams } = new URL(request.url); const code = searchParams.get("code"); if (!code) { return await this.oidc.onFailure( this.routes.oidc.start, MissingCode, request ); } try { const client = new SlackAPIClient(undefined, { logLevel: this.env.SLACK_LOGGING_LEVEL, }); const apiResponse: OpenIDConnectTokenResponse = await client.openid.connect.token({ client_id: this.env.SLACK_CLIENT_ID, client_secret: this.env.SLACK_CLIENT_SECRET, redirect_uri: this.oidc.redirectUri, code, }); return await this.oidc.callback(apiResponse, request); } catch (e) { console.log(e); return await this.oidc.onFailure( this.routes.oidc.start, OpenIDConnectError, request ); } } async #validateStateParameter( request: Request, startPath: string, cookieName: string ) { const { searchParams } = new URL(request.url); const queryState = searchParams.get("state"); const cookie = parseCookie(request.headers.get("Cookie") || ""); const cookieState = cookie[cookieName]; if ( queryState !== cookieState || !(await this.stateStore.consume(queryState)) ) { if (startPath === this.routes.oauth.start) { return await this.oauth.onStateValidationError(startPath, request); } else if ( this.oidc && this.routes.oidc && startPath === this.routes.oidc.start ) { return await this.oidc.onStateValidationError(startPath, request); } } } }
src/oauth-app.ts
seratch-slack-edge-c75c224
[ { "filename": "src/app.ts", "retrieved_chunk": "export interface SlackAppOptions<\n E extends SlackEdgeAppEnv | SlackSocketModeAppEnv\n> {\n env: E;\n authorize?: Authorize<E>;\n routes?: {\n events: string;\n };\n socketMode?: boolean;\n}", "score": 0.8955090641975403 }, { "filename": "src/app.ts", "retrieved_chunk": "export class SlackApp<E extends SlackEdgeAppEnv | SlackSocketModeAppEnv> {\n public env: E;\n public client: SlackAPIClient;\n public authorize: Authorize<E>;\n public routes: { events: string | undefined };\n public signingSecret: string;\n public appLevelToken: string | undefined;\n public socketMode: boolean;\n public socketModeClient: SocketModeClient | undefined;\n // deno-lint-ignore no-explicit-any", "score": 0.8938888907432556 }, { "filename": "src/app-env.ts", "retrieved_chunk": " SLACK_BOT_SCOPES: string;\n SLACK_USER_SCOPES?: string;\n SLACK_REDIRECT_URI?: string;\n SLACK_OIDC_SCOPES?: string;\n SLACK_OIDC_REDIRECT_URI?: string;\n SLACK_USER_TOKEN_RESOLUTION?: \"installer\" | \"actor\";\n};\nexport type SlackOIDCEnv = SlackAppEnv & {\n SLACK_CLIENT_ID: string;\n SLACK_CLIENT_SECRET: string;", "score": 0.8827636241912842 }, { "filename": "src/app-env.ts", "retrieved_chunk": " SLACK_OIDC_SCOPES?: string;\n SLACK_OIDC_REDIRECT_URI: string;\n};\nexport type SlackOAuthAndOIDCEnv = SlackOAuthEnv & SlackOIDCEnv;", "score": 0.8825173377990723 }, { "filename": "src/app-env.ts", "retrieved_chunk": " SLACK_BOT_TOKEN?: string;\n};\nexport type SlackSocketModeAppEnv = SlackAppEnv & {\n SLACK_SIGNING_SECRET?: string;\n SLACK_BOT_TOKEN?: string;\n SLACK_APP_TOKEN: string;\n};\nexport type SlackOAuthEnv = (SlackEdgeAppEnv | SlackSocketModeAppEnv) & {\n SLACK_CLIENT_ID: string;\n SLACK_CLIENT_SECRET: string;", "score": 0.8815691471099854 } ]
typescript
SlackOAuthApp<E extends SlackOAuthEnv> extends SlackApp<E> {
import { ExecutionContext, NoopExecutionContext } from "./execution-context"; import { SlackApp } from "./app"; import { SlackOAuthEnv } from "./app-env"; import { InstallationStore } from "./oauth/installation-store"; import { NoStorageStateStore, StateStore } from "./oauth/state-store"; import { renderCompletionPage, renderStartPage, } from "./oauth/oauth-page-renderer"; import { generateAuthorizeUrl } from "./oauth/authorize-url-generator"; import { parse as parseCookie } from "./cookie"; import { SlackAPIClient, OAuthV2AccessResponse, OpenIDConnectTokenResponse, } from "slack-web-api-client"; import { toInstallation } from "./oauth/installation"; import { AfterInstallation, BeforeInstallation, OnFailure, OnStateValidationError, defaultOnFailure, defaultOnStateValidationError, } from "./oauth/callback"; import { OpenIDConnectCallback, defaultOpenIDConnectCallback, } from "./oidc/callback"; import { generateOIDCAuthorizeUrl } from "./oidc/authorize-url-generator"; import { InstallationError, MissingCode, CompletionPageError, InstallationStoreError, OpenIDConnectError, } from "./oauth/error-codes"; export interface SlackOAuthAppOptions<E extends SlackOAuthEnv> { env: E; installationStore: InstallationStore<E>; stateStore?: StateStore; oauth?: { stateCookieName?: string; beforeInstallation?: BeforeInstallation; afterInstallation?: AfterInstallation; onFailure?: OnFailure; onStateValidationError?: OnStateValidationError; redirectUri?: string; }; oidc?: { stateCookieName?: string; callback: OpenIDConnectCallback; onFailure?: OnFailure; onStateValidationError?: OnStateValidationError; redirectUri?: string; }; routes?: { events: string; oauth: { start: string; callback: string }; oidc?: { start: string; callback: string }; }; } export class SlackOAuthApp<E extends SlackOAuthEnv> extends SlackApp<E> { public env: E; public installationStore: InstallationStore<E>; public stateStore: StateStore; public oauth: { stateCookieName?: string; beforeInstallation?: BeforeInstallation; afterInstallation?: AfterInstallation; onFailure: OnFailure; onStateValidationError: OnStateValidationError; redirectUri?: string; }; public oidc?: { stateCookieName?: string; callback: OpenIDConnectCallback; onFailure: OnFailure; onStateValidationError: OnStateValidationError; redirectUri?: string; }; public routes: { events: string; oauth: { start: string; callback: string }; oidc?: { start: string; callback: string }; }; constructor(options: SlackOAuthAppOptions<E>) { super({ env: options.env, authorize: options.installationStore.toAuthorize(), routes: { events: options.routes?.events ?? "/slack/events" }, }); this.env = options.env; this.installationStore = options.installationStore; this.stateStore = options.stateStore ?? new NoStorageStateStore(); this.oauth = { stateCookieName: options.oauth?.stateCookieName ?? "slack-app-oauth-state", onFailure: options.oauth?.onFailure ?? defaultOnFailure, onStateValidationError: options.oauth?.onStateValidationError ?? defaultOnStateValidationError, redirectUri: options.oauth?.redirectUri ?? this.env.SLACK_REDIRECT_URI, }; if (options.oidc) { this.oidc = { stateCookieName: options.oidc.stateCookieName ?? "slack-app-oidc-state", onFailure: options.oidc.onFailure ?? defaultOnFailure, onStateValidationError: options.oidc.onStateValidationError ?? defaultOnStateValidationError, callback: defaultOpenIDConnectCallback(this.env), redirectUri: options.oidc.redirectUri ?? this.env.SLACK_OIDC_REDIRECT_URI, }; } else { this.oidc = undefined; } this.routes = options.routes ? options.routes : { events: "/slack/events", oauth: { start: "/slack/install", callback: "/slack/oauth_redirect", }, oidc: { start: "/slack/login", callback: "/slack/login/callback", }, }; } async run( request: Request, ctx: ExecutionContext = new NoopExecutionContext() ): Promise<Response> { const url = new URL(request.url); if (request.method === "GET") { if (url.pathname === this.routes.oauth.start) { return await this.handleOAuthStartRequest(request); } else if (url.pathname === this.routes.oauth.callback) { return await this.handleOAuthCallbackRequest(request); } if (this.routes.oidc) { if (url.pathname === this.routes.oidc.start) { return await this.handleOIDCStartRequest(request); } else if (url.pathname === this.routes.oidc.callback) { return await this.handleOIDCCallbackRequest(request); } } } else if (request.method === "POST") { if (url.pathname === this.routes.events) { return await this.handleEventRequest(request, ctx); } } return new Response("Not found", { status: 404 }); } async handleEventRequest( request: Request, ctx: ExecutionContext ): Promise<Response> { return await super.handleEventRequest(request, ctx); } // deno-lint-ignore no-unused-vars async handleOAuthStartRequest(request: Request): Promise<Response> {
const stateValue = await this.stateStore.issueNewState();
const authorizeUrl = generateAuthorizeUrl(stateValue, this.env); return new Response(renderStartPage(authorizeUrl), { status: 302, headers: { Location: authorizeUrl, "Set-Cookie": `${this.oauth.stateCookieName}=${stateValue}; Secure; HttpOnly; Path=/; Max-Age=300`, "Content-Type": "text/html; charset=utf-8", }, }); } async handleOAuthCallbackRequest(request: Request): Promise<Response> { // State parameter validation await this.#validateStateParameter( request, this.routes.oauth.start, this.oauth.stateCookieName! ); const { searchParams } = new URL(request.url); const code = searchParams.get("code"); if (!code) { return await this.oauth.onFailure( this.routes.oauth.start, MissingCode, request ); } const client = new SlackAPIClient(undefined, { logLevel: this.env.SLACK_LOGGING_LEVEL, }); let oauthAccess: OAuthV2AccessResponse | undefined; try { // Execute the installation process oauthAccess = await client.oauth.v2.access({ client_id: this.env.SLACK_CLIENT_ID, client_secret: this.env.SLACK_CLIENT_SECRET, redirect_uri: this.oauth.redirectUri, code, }); } catch (e) { console.log(e); return await this.oauth.onFailure( this.routes.oauth.start, InstallationError, request ); } try { // Store the installation data on this app side await this.installationStore.save(toInstallation(oauthAccess), request); } catch (e) { console.log(e); return await this.oauth.onFailure( this.routes.oauth.start, InstallationStoreError, request ); } try { // Build the completion page const authTest = await client.auth.test({ token: oauthAccess.access_token, }); const enterpriseUrl = authTest.url; return new Response( renderCompletionPage( oauthAccess.app_id!, oauthAccess.team?.id!, oauthAccess.is_enterprise_install, enterpriseUrl ), { status: 200, headers: { "Set-Cookie": `${this.oauth.stateCookieName}=deleted; Secure; HttpOnly; Path=/; Max-Age=0`, "Content-Type": "text/html; charset=utf-8", }, } ); } catch (e) { console.log(e); return await this.oauth.onFailure( this.routes.oauth.start, CompletionPageError, request ); } } // deno-lint-ignore no-unused-vars async handleOIDCStartRequest(request: Request): Promise<Response> { if (!this.oidc) { return new Response("Not found", { status: 404 }); } const stateValue = await this.stateStore.issueNewState(); const authorizeUrl = generateOIDCAuthorizeUrl(stateValue, this.env); return new Response(renderStartPage(authorizeUrl), { status: 302, headers: { Location: authorizeUrl, "Set-Cookie": `${this.oidc.stateCookieName}=${stateValue}; Secure; HttpOnly; Path=/; Max-Age=300`, "Content-Type": "text/html; charset=utf-8", }, }); } async handleOIDCCallbackRequest(request: Request): Promise<Response> { if (!this.oidc || !this.routes.oidc) { return new Response("Not found", { status: 404 }); } // State parameter validation await this.#validateStateParameter( request, this.routes.oidc.start, this.oidc.stateCookieName! ); const { searchParams } = new URL(request.url); const code = searchParams.get("code"); if (!code) { return await this.oidc.onFailure( this.routes.oidc.start, MissingCode, request ); } try { const client = new SlackAPIClient(undefined, { logLevel: this.env.SLACK_LOGGING_LEVEL, }); const apiResponse: OpenIDConnectTokenResponse = await client.openid.connect.token({ client_id: this.env.SLACK_CLIENT_ID, client_secret: this.env.SLACK_CLIENT_SECRET, redirect_uri: this.oidc.redirectUri, code, }); return await this.oidc.callback(apiResponse, request); } catch (e) { console.log(e); return await this.oidc.onFailure( this.routes.oidc.start, OpenIDConnectError, request ); } } async #validateStateParameter( request: Request, startPath: string, cookieName: string ) { const { searchParams } = new URL(request.url); const queryState = searchParams.get("state"); const cookie = parseCookie(request.headers.get("Cookie") || ""); const cookieState = cookie[cookieName]; if ( queryState !== cookieState || !(await this.stateStore.consume(queryState)) ) { if (startPath === this.routes.oauth.start) { return await this.oauth.onStateValidationError(startPath, request); } else if ( this.oidc && this.routes.oidc && startPath === this.routes.oidc.start ) { return await this.oidc.onStateValidationError(startPath, request); } } } }
src/oauth-app.ts
seratch-slack-edge-c75c224
[ { "filename": "src/app.ts", "retrieved_chunk": " await this.socketModeClient.connect();\n }\n async disconnect(): Promise<void> {\n if (this.socketModeClient) {\n await this.socketModeClient.disconnect();\n }\n }\n async handleEventRequest(\n request: Request,\n ctx: ExecutionContext", "score": 0.8412043452262878 }, { "filename": "src/oauth/callback.ts", "retrieved_chunk": "export type OnStateValidationError = (\n startPath: string,\n req: Request\n) => Promise<Response>;\n// deno-lint-ignore require-await\nexport const defaultOnStateValidationError = async (\n startPath: string,\n // deno-lint-ignore no-unused-vars\n req: Request\n) => {", "score": 0.8334470987319946 }, { "filename": "src/app.ts", "retrieved_chunk": " ): Promise<Response> {\n return await this.handleEventRequest(request, ctx);\n }\n async connect(): Promise<void> {\n if (!this.socketMode) {\n throw new ConfigError(\n \"Both env.SLACK_APP_TOKEN and socketMode: true are required to start a Socket Mode connection!\"\n );\n }\n this.socketModeClient = new SocketModeClient(this);", "score": 0.8319509625434875 }, { "filename": "src/app.ts", "retrieved_chunk": " ) {\n return handler;\n }\n return null;\n });\n return this;\n }\n async run(\n request: Request,\n ctx: ExecutionContext = new NoopExecutionContext()", "score": 0.8201003670692444 }, { "filename": "src/oauth/state-store.ts", "retrieved_chunk": "export interface StateStore {\n issueNewState(): Promise<string>;\n consume(state: string): Promise<boolean>;\n}\nexport class NoStorageStateStore implements StateStore {\n // deno-lint-ignore require-await\n async issueNewState(): Promise<string> {\n return crypto.randomUUID();\n }\n // deno-lint-ignore require-await no-unused-vars", "score": 0.8198094964027405 } ]
typescript
const stateValue = await this.stateStore.issueNewState();
import { SlackAppEnv, SlackEdgeAppEnv, SlackSocketModeAppEnv } from "./app-env"; import { parseRequestBody } from "./request/request-parser"; import { verifySlackRequest } from "./request/request-verification"; import { AckResponse, SlackHandler } from "./handler/handler"; import { SlackRequestBody } from "./request/request-body"; import { PreAuthorizeSlackMiddlwareRequest, SlackRequestWithRespond, SlackMiddlwareRequest, SlackRequestWithOptionalRespond, SlackRequest, SlackRequestWithChannelId, } from "./request/request"; import { SlashCommand } from "./request/payload/slash-command"; import { toCompleteResponse } from "./response/response"; import { SlackEvent, AnySlackEvent, AnySlackEventWithChannelId, } from "./request/payload/event"; import { ResponseUrlSender, SlackAPIClient } from "slack-web-api-client"; import { builtBaseContext, SlackAppContext, SlackAppContextWithChannelId, SlackAppContextWithRespond, } from "./context/context"; import { PreAuthorizeMiddleware, Middleware } from "./middleware/middleware"; import { isDebugLogEnabled, prettyPrint } from "slack-web-api-client"; import { Authorize } from "./authorization/authorize"; import { AuthorizeResult } from "./authorization/authorize-result"; import { ignoringSelfEvents, urlVerification, } from "./middleware/built-in-middleware"; import { ConfigError } from "./errors"; import { GlobalShortcut } from "./request/payload/global-shortcut"; import { MessageShortcut } from "./request/payload/message-shortcut"; import { BlockAction, BlockElementAction, BlockElementTypes, } from "./request/payload/block-action"; import { ViewSubmission } from "./request/payload/view-submission"; import { ViewClosed } from "./request/payload/view-closed"; import { BlockSuggestion } from "./request/payload/block-suggestion"; import { OptionsAckResponse, SlackOptionsHandler, } from "./handler/options-handler"; import { SlackViewHandler, ViewAckResponse } from "./handler/view-handler"; import { MessageAckResponse, SlackMessageHandler, } from "./handler/message-handler"; import { singleTeamAuthorize } from "./authorization/single-team-authorize"; import { ExecutionContext, NoopExecutionContext } from "./execution-context"; import { PayloadType } from "./request/payload-types"; import { isPostedMessageEvent } from "./utility/message-events"; import { SocketModeClient } from "./socket-mode/socket-mode-client"; export interface SlackAppOptions< E extends SlackEdgeAppEnv | SlackSocketModeAppEnv > { env: E; authorize?: Authorize<E>; routes?: { events: string; }; socketMode?: boolean; } export class SlackApp<E extends SlackEdgeAppEnv | SlackSocketModeAppEnv> { public env: E; public client: SlackAPIClient; public authorize: Authorize<E>; public routes: { events: string | undefined }; public signingSecret: string; public appLevelToken: string | undefined; public socketMode: boolean; public socketModeClient: SocketModeClient | undefined; // deno-lint-ignore no-explicit-any public preAuthorizeMiddleware: PreAuthorizeMiddleware<any>[] = [ urlVerification, ]; // deno-lint-ignore no-explicit-any public postAuthorizeMiddleware: Middleware<any>[] = [ignoringSelfEvents]; #slashCommands: (( body: SlackRequestBody ) => SlackMessageHandler<E, SlashCommand> | null)[] = []; #events: (( body: SlackRequestBody ) => SlackHandler<E, SlackEvent<string>> | null)[] = []; #globalShorcuts: (( body: SlackRequestBody ) => SlackHandler<E, GlobalShortcut> | null)[] = []; #messageShorcuts: (( body: SlackRequestBody ) => SlackHandler<E, MessageShortcut> | null)[] = []; #blockActions: ((body: SlackRequestBody) => SlackHandler< E, // deno-lint-ignore no-explicit-any BlockAction<any> > | null)[] = []; #blockSuggestions: (( body: SlackRequestBody ) => SlackOptionsHandler<E, BlockSuggestion> | null)[] = []; #viewSubmissions: (( body: SlackRequestBody ) => SlackViewHandler<E, ViewSubmission> | null)[] = []; #viewClosed: (( body: SlackRequestBody ) => SlackViewHandler<E, ViewClosed> | null)[] = []; constructor(options: SlackAppOptions<E>) { if ( options.env.SLACK_BOT_TOKEN === undefined && (options.authorize === undefined || options.authorize === singleTeamAuthorize) ) { throw new ConfigError( "When you don't pass env.SLACK_BOT_TOKEN, your own authorize function, which supplies a valid token to use, needs to be passed instead." ); } this.env = options.env; this.client = new SlackAPIClient(options.env.SLACK_BOT_TOKEN, { logLevel: this.env.SLACK_LOGGING_LEVEL, }); this.appLevelToken = options.env.SLACK_APP_TOKEN; this.socketMode = options.socketMode ?? this.appLevelToken !== undefined; if (this.socketMode) { this.signingSecret = ""; } else { if (!this.env.SLACK_SIGNING_SECRET) { throw new ConfigError( "env.SLACK_SIGNING_SECRET is required to run your app on edge functions!" ); } this.signingSecret = this.env.SLACK_SIGNING_SECRET; } this.authorize = options.authorize ?? singleTeamAuthorize; this.routes = { events: options.routes?.events }; } beforeAuthorize(middleware: PreAuthorizeMiddleware<E>): SlackApp<E> { this.preAuthorizeMiddleware.push(middleware); return this; } middleware(middleware: Middleware<E>): SlackApp<E> { return this.afterAuthorize(middleware); } use(middleware: Middleware<E>): SlackApp<E> { return this.afterAuthorize(middleware); } afterAuthorize(middleware: Middleware<E>): SlackApp<E> { this.postAuthorizeMiddleware.push(middleware); return this; } command( pattern: StringOrRegExp, ack: ( req: SlackRequestWithRespond<E, SlashCommand> ) => Promise<MessageAckResponse>, lazy: ( req: SlackRequestWithRespond<E, SlashCommand> ) => Promise<void> = noopLazyListener ): SlackApp<E> { const handler: SlackMessageHandler<E, SlashCommand> = { ack, lazy }; this.#slashCommands.push((body) => { if (body.type || !body.command) { return null; } if (typeof pattern === "string" && body.command === pattern) { return handler; } else if ( typeof pattern === "object" && pattern instanceof RegExp && body.command.match(pattern) ) { return handler; } return null; }); return this; } event<Type extends string>( event: Type, lazy: (req: EventRequest<E, Type>) => Promise<void> ): SlackApp<E> { this.#events.push((body) => { if (body.type !== PayloadType.EventsAPI || !body.event) { return null; } if (body.event.type === event) { // deno-lint-ignore require-await return { ack: async () => "", lazy }; } return null; }); return this; } anyMessage(lazy: MessageEventHandler<E>): SlackApp<E> { return this.message(undefined, lazy); } message( pattern: MessageEventPattern, lazy: MessageEventHandler<E> ): SlackApp<E> { this.#events.push((body) => { if ( body.type !== PayloadType.EventsAPI || !body.event || body.event.type !== "message" ) { return null; }
if (isPostedMessageEvent(body.event)) {
let matched = true; if (pattern !== undefined) { if (typeof pattern === "string") { matched = body.event.text!.includes(pattern); } if (typeof pattern === "object") { matched = body.event.text!.match(pattern) !== null; } } if (matched) { // deno-lint-ignore require-await return { ack: async (_: EventRequest<E, "message">) => "", lazy }; } } return null; }); return this; } shortcut( callbackId: StringOrRegExp, ack: ( req: | SlackRequest<E, GlobalShortcut> | SlackRequestWithRespond<E, MessageShortcut> ) => Promise<AckResponse>, lazy: ( req: | SlackRequest<E, GlobalShortcut> | SlackRequestWithRespond<E, MessageShortcut> ) => Promise<void> = noopLazyListener ): SlackApp<E> { return this.globalShortcut(callbackId, ack, lazy).messageShortcut( callbackId, ack, lazy ); } globalShortcut( callbackId: StringOrRegExp, ack: (req: SlackRequest<E, GlobalShortcut>) => Promise<AckResponse>, lazy: ( req: SlackRequest<E, GlobalShortcut> ) => Promise<void> = noopLazyListener ): SlackApp<E> { const handler: SlackHandler<E, GlobalShortcut> = { ack, lazy }; this.#globalShorcuts.push((body) => { if (body.type !== PayloadType.GlobalShortcut || !body.callback_id) { return null; } if (typeof callbackId === "string" && body.callback_id === callbackId) { return handler; } else if ( typeof callbackId === "object" && callbackId instanceof RegExp && body.callback_id.match(callbackId) ) { return handler; } return null; }); return this; } messageShortcut( callbackId: StringOrRegExp, ack: ( req: SlackRequestWithRespond<E, MessageShortcut> ) => Promise<AckResponse>, lazy: ( req: SlackRequestWithRespond<E, MessageShortcut> ) => Promise<void> = noopLazyListener ): SlackApp<E> { const handler: SlackHandler<E, MessageShortcut> = { ack, lazy }; this.#messageShorcuts.push((body) => { if (body.type !== PayloadType.MessageShortcut || !body.callback_id) { return null; } if (typeof callbackId === "string" && body.callback_id === callbackId) { return handler; } else if ( typeof callbackId === "object" && callbackId instanceof RegExp && body.callback_id.match(callbackId) ) { return handler; } return null; }); return this; } action< T extends BlockElementTypes, A extends BlockAction<BlockElementAction<T>> = BlockAction< BlockElementAction<T> > >( constraints: | StringOrRegExp | { type: T; block_id?: string; action_id: string }, ack: (req: SlackRequestWithOptionalRespond<E, A>) => Promise<AckResponse>, lazy: ( req: SlackRequestWithOptionalRespond<E, A> ) => Promise<void> = noopLazyListener ): SlackApp<E> { const handler: SlackHandler<E, A> = { ack, lazy }; this.#blockActions.push((body) => { if ( body.type !== PayloadType.BlockAction || !body.actions || !body.actions[0] ) { return null; } const action = body.actions[0]; if (typeof constraints === "string" && action.action_id === constraints) { return handler; } else if (typeof constraints === "object") { if (constraints instanceof RegExp) { if (action.action_id.match(constraints)) { return handler; } } else if (constraints.type) { if (action.type === constraints.type) { if (action.action_id === constraints.action_id) { if ( constraints.block_id && action.block_id !== constraints.block_id ) { return null; } return handler; } } } } return null; }); return this; } options( constraints: StringOrRegExp | { block_id?: string; action_id: string }, ack: (req: SlackRequest<E, BlockSuggestion>) => Promise<OptionsAckResponse> ): SlackApp<E> { // Note that block_suggestion response must be done within 3 seconds. // So, we don't support the lazy handler for it. const handler: SlackOptionsHandler<E, BlockSuggestion> = { ack }; this.#blockSuggestions.push((body) => { if (body.type !== PayloadType.BlockSuggestion || !body.action_id) { return null; } if (typeof constraints === "string" && body.action_id === constraints) { return handler; } else if (typeof constraints === "object") { if (constraints instanceof RegExp) { if (body.action_id.match(constraints)) { return handler; } } else { if (body.action_id === constraints.action_id) { if (body.block_id && body.block_id !== constraints.block_id) { return null; } return handler; } } } return null; }); return this; } view( callbackId: StringOrRegExp, ack: ( req: | SlackRequestWithOptionalRespond<E, ViewSubmission> | SlackRequest<E, ViewClosed> ) => Promise<ViewAckResponse>, lazy: ( req: | SlackRequestWithOptionalRespond<E, ViewSubmission> | SlackRequest<E, ViewClosed> ) => Promise<void> = noopLazyListener ): SlackApp<E> { return this.viewSubmission(callbackId, ack, lazy).viewClosed( callbackId, ack, lazy ); } viewSubmission( callbackId: StringOrRegExp, ack: ( req: SlackRequestWithOptionalRespond<E, ViewSubmission> ) => Promise<ViewAckResponse>, lazy: ( req: SlackRequestWithOptionalRespond<E, ViewSubmission> ) => Promise<void> = noopLazyListener ): SlackApp<E> { const handler: SlackViewHandler<E, ViewSubmission> = { ack, lazy }; this.#viewSubmissions.push((body) => { if (body.type !== PayloadType.ViewSubmission || !body.view) { return null; } if ( typeof callbackId === "string" && body.view.callback_id === callbackId ) { return handler; } else if ( typeof callbackId === "object" && callbackId instanceof RegExp && body.view.callback_id.match(callbackId) ) { return handler; } return null; }); return this; } viewClosed( callbackId: StringOrRegExp, ack: (req: SlackRequest<E, ViewClosed>) => Promise<ViewAckResponse>, lazy: (req: SlackRequest<E, ViewClosed>) => Promise<void> = noopLazyListener ): SlackApp<E> { const handler: SlackViewHandler<E, ViewClosed> = { ack, lazy }; this.#viewClosed.push((body) => { if (body.type !== PayloadType.ViewClosed || !body.view) { return null; } if ( typeof callbackId === "string" && body.view.callback_id === callbackId ) { return handler; } else if ( typeof callbackId === "object" && callbackId instanceof RegExp && body.view.callback_id.match(callbackId) ) { return handler; } return null; }); return this; } async run( request: Request, ctx: ExecutionContext = new NoopExecutionContext() ): Promise<Response> { return await this.handleEventRequest(request, ctx); } async connect(): Promise<void> { if (!this.socketMode) { throw new ConfigError( "Both env.SLACK_APP_TOKEN and socketMode: true are required to start a Socket Mode connection!" ); } this.socketModeClient = new SocketModeClient(this); await this.socketModeClient.connect(); } async disconnect(): Promise<void> { if (this.socketModeClient) { await this.socketModeClient.disconnect(); } } async handleEventRequest( request: Request, ctx: ExecutionContext ): Promise<Response> { // If the routes.events is missing, any URLs can work for handing requests from Slack if (this.routes.events) { const { pathname } = new URL(request.url); if (pathname !== this.routes.events) { return new Response("Not found", { status: 404 }); } } // To avoid the following warning by Cloudflware, parse the body as Blob first // Called .text() on an HTTP body which does not appear to be text .. const blobRequestBody = await request.blob(); // We can safely assume the incoming request body is always text data const rawBody: string = await blobRequestBody.text(); // For Request URL verification if (rawBody.includes("ssl_check=")) { // Slack does not send the x-slack-signature header for this pattern. // Thus, we need to check the pattern before verifying a request. const bodyParams = new URLSearchParams(rawBody); if (bodyParams.get("ssl_check") === "1" && bodyParams.get("token")) { return new Response("", { status: 200 }); } } // Verify the request headers and body const isRequestSignatureVerified = this.socketMode || (await verifySlackRequest(this.signingSecret, request.headers, rawBody)); if (isRequestSignatureVerified) { // deno-lint-ignore no-explicit-any const body: Record<string, any> = await parseRequestBody( request.headers, rawBody ); let retryNum: number | undefined = undefined; try { const retryNumHeader = request.headers.get("x-slack-retry-num"); if (retryNumHeader) { retryNum = Number.parseInt(retryNumHeader); } else if (this.socketMode && body.retry_attempt) { retryNum = Number.parseInt(body.retry_attempt); } // deno-lint-ignore no-unused-vars } catch (e) { // Ignore an exception here } const retryReason = request.headers.get("x-slack-retry-reason") ?? body.retry_reason; const preAuthorizeRequest: PreAuthorizeSlackMiddlwareRequest<E> = { body, rawBody, retryNum, retryReason, context: builtBaseContext(body), env: this.env, headers: request.headers, }; if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log(`*** Received request body ***\n ${prettyPrint(body)}`); } for (const middlware of this.preAuthorizeMiddleware) { const response = await middlware(preAuthorizeRequest); if (response) { return toCompleteResponse(response); } } const authorizeResult: AuthorizeResult = await this.authorize( preAuthorizeRequest ); const authorizedContext: SlackAppContext = { ...preAuthorizeRequest.context, authorizeResult, client: new SlackAPIClient(authorizeResult.botToken, { logLevel: this.env.SLACK_LOGGING_LEVEL, }), botToken: authorizeResult.botToken, botId: authorizeResult.botId, botUserId: authorizeResult.botUserId, userToken: authorizeResult.userToken, }; if (authorizedContext.channelId) { const context = authorizedContext as SlackAppContextWithChannelId; const client = new SlackAPIClient(context.botToken); context.say = async (params) => await client.chat.postMessage({ channel: context.channelId, ...params, }); } if (authorizedContext.responseUrl) { const responseUrl = authorizedContext.responseUrl; // deno-lint-ignore require-await (authorizedContext as SlackAppContextWithRespond).respond = async ( params ) => { return new ResponseUrlSender(responseUrl).call(params); }; } const baseRequest: SlackMiddlwareRequest<E> = { ...preAuthorizeRequest, context: authorizedContext, }; for (const middlware of this.postAuthorizeMiddleware) { const response = await middlware(baseRequest); if (response) { return toCompleteResponse(response); } } const payload = body as SlackRequestBody; if (body.type === PayloadType.EventsAPI) { // Events API const slackRequest: SlackRequest<E, SlackEvent<string>> = { payload: body.event, ...baseRequest, }; for (const matcher of this.#events) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (!body.type && body.command) { // Slash commands const slackRequest: SlackRequest<E, SlashCommand> = { payload: body as SlashCommand, ...baseRequest, }; for (const matcher of this.#slashCommands) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (body.type === PayloadType.GlobalShortcut) { // Global shortcuts const slackRequest: SlackRequest<E, GlobalShortcut> = { payload: body as GlobalShortcut, ...baseRequest, }; for (const matcher of this.#globalShorcuts) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (body.type === PayloadType.MessageShortcut) { // Message shortcuts const slackRequest: SlackRequest<E, MessageShortcut> = { payload: body as MessageShortcut, ...baseRequest, }; for (const matcher of this.#messageShorcuts) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (body.type === PayloadType.BlockAction) { // Block actions // deno-lint-ignore no-explicit-any const slackRequest: SlackRequest<E, BlockAction<any>> = { // deno-lint-ignore no-explicit-any payload: body as BlockAction<any>, ...baseRequest, }; for (const matcher of this.#blockActions) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (body.type === PayloadType.BlockSuggestion) { // Block suggestions const slackRequest: SlackRequest<E, BlockSuggestion> = { payload: body as BlockSuggestion, ...baseRequest, }; for (const matcher of this.#blockSuggestions) { const handler = matcher(payload); if (handler) { // Note that the only way to respond to a block_suggestion request // is to send an HTTP response with options/option_groups. // Thus, we don't support lazy handlers for this pattern. const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (body.type === PayloadType.ViewSubmission) { // View submissions const slackRequest: SlackRequest<E, ViewSubmission> = { payload: body as ViewSubmission, ...baseRequest, }; for (const matcher of this.#viewSubmissions) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (body.type === PayloadType.ViewClosed) { // View closed const slackRequest: SlackRequest<E, ViewClosed> = { payload: body as ViewClosed, ...baseRequest, }; for (const matcher of this.#viewClosed) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } // TODO: Add code suggestion here console.log( `*** No listener found ***\n${JSON.stringify(baseRequest.body)}` ); return new Response("No listener found", { status: 404 }); } return new Response("Invalid signature", { status: 401 }); } } export type StringOrRegExp = string | RegExp; export type EventRequest<E extends SlackAppEnv, T> = Extract< AnySlackEventWithChannelId, { type: T } > extends never ? SlackRequest<E, Extract<AnySlackEvent, { type: T }>> : SlackRequestWithChannelId< E, Extract<AnySlackEventWithChannelId, { type: T }> >; export type MessageEventPattern = string | RegExp | undefined; export type MessageEventRequest< E extends SlackAppEnv, ST extends string | undefined > = SlackRequestWithChannelId< E, Extract<AnySlackEventWithChannelId, { subtype: ST }> >; export type MessageEventSubtypes = | undefined | "bot_message" | "thread_broadcast" | "file_share"; export type MessageEventHandler<E extends SlackAppEnv> = ( req: MessageEventRequest<E, MessageEventSubtypes> ) => Promise<void>; export const noopLazyListener = async () => {};
src/app.ts
seratch-slack-edge-c75c224
[ { "filename": "src/socket-mode/socket-mode-client.ts", "retrieved_chunk": " ) {\n const data = JSON.parse(ev.data);\n if (data.type === \"hello\") {\n if (isDebugLogEnabled(app.env.SLACK_LOGGING_LEVEL)) {\n console.log(`*** Received hello data ***\\n ${ev.data}`);\n }\n return;\n }\n const payload = JSON.stringify(data.payload);\n console.log(payload);", "score": 0.8138364553451538 }, { "filename": "src/request/payload/event.ts", "retrieved_chunk": " api_app_id: string;\n}\nexport interface AppUninstalledEvent extends SlackEvent<\"app_uninstalled\"> {\n type: \"app_uninstalled\";\n}\nexport interface ChannelArchiveEvent extends SlackEvent<\"channel_archive\"> {\n type: \"channel_archive\";\n channel: string;\n user: string;\n is_moved?: number;", "score": 0.8114609122276306 }, { "filename": "src/request/payload/event.ts", "retrieved_chunk": " | SharedChannelInviteApprovedEvent\n | SharedChannelInviteDeclinedEvent\n | StarAddedEvent\n | StarRemovedEvent;\nexport interface SlackEvent<Type extends string> {\n type: Type;\n subtype?: string;\n}\nexport interface AppRequestedEvent extends SlackEvent<\"app_requested\"> {\n type: \"app_requested\";", "score": 0.81087327003479 }, { "filename": "src/request/payload/event.ts", "retrieved_chunk": " channel: string;\n tab: \"home\" | \"messages\";\n view?: HomeTabView;\n event_ts: string;\n}\nexport interface AppMentionEvent extends SlackEvent<\"app_mention\"> {\n type: \"app_mention\";\n subtype?: string;\n bot_id?: string;\n bot_profile?: BotProfile;", "score": 0.8096605539321899 }, { "filename": "src/request/payload/event.ts", "retrieved_chunk": " | ChannelJoinMessageEvent\n | ChannelLeaveMessageEvent\n | ChannelNameMessageEvent\n | ChannelPostingPermissionsMessageEvent\n | ChannelPurposeMessageEvent\n | ChannelTopicMessageEvent\n | ChannelUnarchiveMessageEvent\n | EKMAccessDeniedMessageEvent\n | FileShareMessageEvent\n | MeMessageEvent", "score": 0.8073296546936035 } ]
typescript
if (isPostedMessageEvent(body.event)) {
import { ExecutionContext, NoopExecutionContext } from "./execution-context"; import { SlackApp } from "./app"; import { SlackOAuthEnv } from "./app-env"; import { InstallationStore } from "./oauth/installation-store"; import { NoStorageStateStore, StateStore } from "./oauth/state-store"; import { renderCompletionPage, renderStartPage, } from "./oauth/oauth-page-renderer"; import { generateAuthorizeUrl } from "./oauth/authorize-url-generator"; import { parse as parseCookie } from "./cookie"; import { SlackAPIClient, OAuthV2AccessResponse, OpenIDConnectTokenResponse, } from "slack-web-api-client"; import { toInstallation } from "./oauth/installation"; import { AfterInstallation, BeforeInstallation, OnFailure, OnStateValidationError, defaultOnFailure, defaultOnStateValidationError, } from "./oauth/callback"; import { OpenIDConnectCallback, defaultOpenIDConnectCallback, } from "./oidc/callback"; import { generateOIDCAuthorizeUrl } from "./oidc/authorize-url-generator"; import { InstallationError, MissingCode, CompletionPageError, InstallationStoreError, OpenIDConnectError, } from "./oauth/error-codes"; export interface SlackOAuthAppOptions<E extends SlackOAuthEnv> { env: E; installationStore: InstallationStore<E>; stateStore?: StateStore; oauth?: { stateCookieName?: string; beforeInstallation?: BeforeInstallation; afterInstallation?: AfterInstallation; onFailure?: OnFailure; onStateValidationError?: OnStateValidationError; redirectUri?: string; }; oidc?: { stateCookieName?: string; callback: OpenIDConnectCallback; onFailure?: OnFailure; onStateValidationError?: OnStateValidationError; redirectUri?: string; }; routes?: { events: string; oauth: { start: string; callback: string }; oidc?: { start: string; callback: string }; }; } export class SlackOAuthApp<E extends SlackOAuthEnv> extends SlackApp<E> { public env: E; public installationStore: InstallationStore<E>; public stateStore: StateStore; public oauth: { stateCookieName?: string; beforeInstallation?: BeforeInstallation; afterInstallation?: AfterInstallation; onFailure: OnFailure; onStateValidationError: OnStateValidationError; redirectUri?: string; }; public oidc?: { stateCookieName?: string; callback: OpenIDConnectCallback; onFailure: OnFailure; onStateValidationError: OnStateValidationError; redirectUri?: string; }; public routes: { events: string; oauth: { start: string; callback: string }; oidc?: { start: string; callback: string }; }; constructor(options: SlackOAuthAppOptions<E>) { super({ env: options.env, authorize: options.installationStore.toAuthorize(), routes: { events: options.routes?.events ?? "/slack/events" }, }); this.env = options.env; this.installationStore = options.installationStore; this.stateStore = options.stateStore ?? new NoStorageStateStore(); this.oauth = { stateCookieName: options.oauth?.stateCookieName ?? "slack-app-oauth-state", onFailure: options.oauth?.onFailure ?? defaultOnFailure, onStateValidationError: options.oauth?.onStateValidationError ?? defaultOnStateValidationError, redirectUri: options.oauth?.redirectUri ?? this.env.SLACK_REDIRECT_URI, }; if (options.oidc) { this.oidc = { stateCookieName: options.oidc.stateCookieName ?? "slack-app-oidc-state", onFailure: options.oidc.onFailure ?? defaultOnFailure, onStateValidationError: options.oidc.onStateValidationError ?? defaultOnStateValidationError, callback: defaultOpenIDConnectCallback(this.env), redirectUri: options.oidc.redirectUri ?? this.env.SLACK_OIDC_REDIRECT_URI, }; } else { this.oidc = undefined; } this.routes = options.routes ? options.routes : { events: "/slack/events", oauth: { start: "/slack/install", callback: "/slack/oauth_redirect", }, oidc: { start: "/slack/login", callback: "/slack/login/callback", }, }; } async run( request: Request, ctx: ExecutionContext = new NoopExecutionContext() ): Promise<Response> { const url = new URL(request.url); if (request.method === "GET") { if (url.pathname === this.routes.oauth.start) { return await this.handleOAuthStartRequest(request); } else if (url.pathname === this.routes.oauth.callback) { return await this.handleOAuthCallbackRequest(request); } if (this.routes.oidc) { if (url.pathname === this.routes.oidc.start) { return await this.handleOIDCStartRequest(request); } else if (url.pathname === this.routes.oidc.callback) { return await this.handleOIDCCallbackRequest(request); } } } else if (request.method === "POST") { if (url.pathname === this.routes.events) { return await this.handleEventRequest(request, ctx); } } return new Response("Not found", { status: 404 }); } async handleEventRequest( request: Request, ctx: ExecutionContext ): Promise<Response> { return await super.handleEventRequest(request, ctx); } // deno-lint-ignore no-unused-vars async handleOAuthStartRequest(request: Request): Promise<Response> { const stateValue = await this.stateStore.issueNewState(); const authorizeUrl = generateAuthorizeUrl(stateValue, this.env); return new Response(renderStartPage(authorizeUrl), { status: 302, headers: { Location: authorizeUrl, "Set-Cookie": `${this.oauth.stateCookieName}=${stateValue}; Secure; HttpOnly; Path=/; Max-Age=300`, "Content-Type": "text/html; charset=utf-8", }, }); } async handleOAuthCallbackRequest(request: Request): Promise<Response> { // State parameter validation await this.#validateStateParameter( request, this.routes.oauth.start, this.oauth.stateCookieName! ); const { searchParams } = new URL(request.url); const code = searchParams.get("code"); if (!code) { return await this.oauth.onFailure( this.routes.oauth.start, MissingCode, request ); } const client = new SlackAPIClient(undefined, { logLevel: this.env.SLACK_LOGGING_LEVEL, }); let oauthAccess: OAuthV2AccessResponse | undefined; try { // Execute the installation process oauthAccess = await client.oauth.v2.access({ client_id: this.env.SLACK_CLIENT_ID, client_secret: this.env.SLACK_CLIENT_SECRET, redirect_uri: this.oauth.redirectUri, code, }); } catch (e) { console.log(e); return await this.oauth.onFailure( this.routes.oauth.start, InstallationError, request ); } try { // Store the installation data on this app side await this.installationStore.
save(toInstallation(oauthAccess), request);
} catch (e) { console.log(e); return await this.oauth.onFailure( this.routes.oauth.start, InstallationStoreError, request ); } try { // Build the completion page const authTest = await client.auth.test({ token: oauthAccess.access_token, }); const enterpriseUrl = authTest.url; return new Response( renderCompletionPage( oauthAccess.app_id!, oauthAccess.team?.id!, oauthAccess.is_enterprise_install, enterpriseUrl ), { status: 200, headers: { "Set-Cookie": `${this.oauth.stateCookieName}=deleted; Secure; HttpOnly; Path=/; Max-Age=0`, "Content-Type": "text/html; charset=utf-8", }, } ); } catch (e) { console.log(e); return await this.oauth.onFailure( this.routes.oauth.start, CompletionPageError, request ); } } // deno-lint-ignore no-unused-vars async handleOIDCStartRequest(request: Request): Promise<Response> { if (!this.oidc) { return new Response("Not found", { status: 404 }); } const stateValue = await this.stateStore.issueNewState(); const authorizeUrl = generateOIDCAuthorizeUrl(stateValue, this.env); return new Response(renderStartPage(authorizeUrl), { status: 302, headers: { Location: authorizeUrl, "Set-Cookie": `${this.oidc.stateCookieName}=${stateValue}; Secure; HttpOnly; Path=/; Max-Age=300`, "Content-Type": "text/html; charset=utf-8", }, }); } async handleOIDCCallbackRequest(request: Request): Promise<Response> { if (!this.oidc || !this.routes.oidc) { return new Response("Not found", { status: 404 }); } // State parameter validation await this.#validateStateParameter( request, this.routes.oidc.start, this.oidc.stateCookieName! ); const { searchParams } = new URL(request.url); const code = searchParams.get("code"); if (!code) { return await this.oidc.onFailure( this.routes.oidc.start, MissingCode, request ); } try { const client = new SlackAPIClient(undefined, { logLevel: this.env.SLACK_LOGGING_LEVEL, }); const apiResponse: OpenIDConnectTokenResponse = await client.openid.connect.token({ client_id: this.env.SLACK_CLIENT_ID, client_secret: this.env.SLACK_CLIENT_SECRET, redirect_uri: this.oidc.redirectUri, code, }); return await this.oidc.callback(apiResponse, request); } catch (e) { console.log(e); return await this.oidc.onFailure( this.routes.oidc.start, OpenIDConnectError, request ); } } async #validateStateParameter( request: Request, startPath: string, cookieName: string ) { const { searchParams } = new URL(request.url); const queryState = searchParams.get("state"); const cookie = parseCookie(request.headers.get("Cookie") || ""); const cookieState = cookie[cookieName]; if ( queryState !== cookieState || !(await this.stateStore.consume(queryState)) ) { if (startPath === this.routes.oauth.start) { return await this.oauth.onStateValidationError(startPath, request); } else if ( this.oidc && this.routes.oidc && startPath === this.routes.oidc.start ) { return await this.oidc.onStateValidationError(startPath, request); } } } }
src/oauth-app.ts
seratch-slack-edge-c75c224
[ { "filename": "src/oauth/callback.ts", "retrieved_chunk": "import { InvalidStateParameter, OAuthErrorCode } from \"./error-codes\";\nimport { Installation } from \"./installation\";\nimport { renderErrorPage } from \"./oauth-page-renderer\";\nexport type BeforeInstallation = (\n req: Request\n) => Promise<Response | undefined | void>;\nexport type AfterInstallation = (\n installation: Installation,\n req: Request\n) => Promise<Response | undefined | void>;", "score": 0.8323832154273987 }, { "filename": "src/oauth/installation.ts", "retrieved_chunk": " incoming_webhook_configuration_url: oauthAccess.incoming_webhook?.url,\n };\n return installation;\n}", "score": 0.8172447681427002 }, { "filename": "src/oauth/installation-store.ts", "retrieved_chunk": " save(installation: Installation, request: Request | undefined): Promise<void>;\n findBotInstallation(\n query: InstallationStoreQuery\n ): Promise<Installation | undefined>;\n findUserInstallation(\n query: InstallationStoreQuery\n ): Promise<Installation | undefined>;\n toAuthorize(): Authorize<E>;\n}", "score": 0.8148121237754822 }, { "filename": "src/oauth/installation.ts", "retrieved_chunk": " incoming_webhook_channel_id?: string;\n incoming_webhook_configuration_url?: string;\n}\nexport function toInstallation(\n oauthAccess: OAuthV2AccessResponse\n): Installation {\n const installation: Installation = {\n app_id: oauthAccess.app_id!,\n is_enterprise_install: oauthAccess.is_enterprise_install,\n enterprise_id: oauthAccess.enterprise?.id,", "score": 0.8125710487365723 }, { "filename": "src/oauth/error-codes.ts", "retrieved_chunk": " message: \"The code parameter is missing\",\n};\nexport const InstallationError: OAuthErrorCode = {\n code: \"installation-error\",\n message: \"The installation process failed\",\n};\nexport const InstallationStoreError: OAuthErrorCode = {\n code: \"installation-store-error\",\n message: \"Saving the installation data failed\",\n};", "score": 0.8084349632263184 } ]
typescript
save(toInstallation(oauthAccess), request);
import { SlackAppEnv, SlackEdgeAppEnv, SlackSocketModeAppEnv } from "./app-env"; import { parseRequestBody } from "./request/request-parser"; import { verifySlackRequest } from "./request/request-verification"; import { AckResponse, SlackHandler } from "./handler/handler"; import { SlackRequestBody } from "./request/request-body"; import { PreAuthorizeSlackMiddlwareRequest, SlackRequestWithRespond, SlackMiddlwareRequest, SlackRequestWithOptionalRespond, SlackRequest, SlackRequestWithChannelId, } from "./request/request"; import { SlashCommand } from "./request/payload/slash-command"; import { toCompleteResponse } from "./response/response"; import { SlackEvent, AnySlackEvent, AnySlackEventWithChannelId, } from "./request/payload/event"; import { ResponseUrlSender, SlackAPIClient } from "slack-web-api-client"; import { builtBaseContext, SlackAppContext, SlackAppContextWithChannelId, SlackAppContextWithRespond, } from "./context/context"; import { PreAuthorizeMiddleware, Middleware } from "./middleware/middleware"; import { isDebugLogEnabled, prettyPrint } from "slack-web-api-client"; import { Authorize } from "./authorization/authorize"; import { AuthorizeResult } from "./authorization/authorize-result"; import { ignoringSelfEvents, urlVerification, } from "./middleware/built-in-middleware"; import { ConfigError } from "./errors"; import { GlobalShortcut } from "./request/payload/global-shortcut"; import { MessageShortcut } from "./request/payload/message-shortcut"; import { BlockAction, BlockElementAction, BlockElementTypes, } from "./request/payload/block-action"; import { ViewSubmission } from "./request/payload/view-submission"; import { ViewClosed } from "./request/payload/view-closed"; import { BlockSuggestion } from "./request/payload/block-suggestion"; import { OptionsAckResponse, SlackOptionsHandler, } from "./handler/options-handler"; import { SlackViewHandler, ViewAckResponse } from "./handler/view-handler"; import { MessageAckResponse, SlackMessageHandler, } from "./handler/message-handler"; import { singleTeamAuthorize } from "./authorization/single-team-authorize"; import { ExecutionContext, NoopExecutionContext } from "./execution-context"; import { PayloadType } from "./request/payload-types"; import { isPostedMessageEvent } from "./utility/message-events"; import { SocketModeClient } from "./socket-mode/socket-mode-client"; export interface SlackAppOptions< E extends SlackEdgeAppEnv | SlackSocketModeAppEnv > { env: E; authorize?: Authorize<E>; routes?: { events: string; }; socketMode?: boolean; } export class SlackApp<E extends SlackEdgeAppEnv | SlackSocketModeAppEnv> { public env: E; public client: SlackAPIClient; public authorize: Authorize<E>; public routes: { events: string | undefined }; public signingSecret: string; public appLevelToken: string | undefined; public socketMode: boolean; public socketModeClient: SocketModeClient | undefined; // deno-lint-ignore no-explicit-any public preAuthorizeMiddleware: PreAuthorizeMiddleware<any>[] = [ urlVerification, ]; // deno-lint-ignore no-explicit-any public postAuthorizeMiddleware: Middleware<any>[] = [ignoringSelfEvents]; #slashCommands: (( body: SlackRequestBody ) => SlackMessageHandler<E, SlashCommand> | null)[] = []; #events: (( body: SlackRequestBody ) => SlackHandler<E, SlackEvent<string>> | null)[] = []; #globalShorcuts: (( body: SlackRequestBody ) => SlackHandler<E, GlobalShortcut> | null)[] = []; #messageShorcuts: (( body: SlackRequestBody ) => SlackHandler<E, MessageShortcut> | null)[] = []; #blockActions: ((body: SlackRequestBody) => SlackHandler< E, // deno-lint-ignore no-explicit-any BlockAction<any> > | null)[] = []; #blockSuggestions: (( body: SlackRequestBody ) => SlackOptionsHandler<E, BlockSuggestion> | null)[] = []; #viewSubmissions: (( body: SlackRequestBody ) => SlackViewHandler<E, ViewSubmission> | null)[] = []; #viewClosed: (( body: SlackRequestBody ) => SlackViewHandler<E, ViewClosed> | null)[] = []; constructor(options: SlackAppOptions<E>) { if ( options.env.SLACK_BOT_TOKEN === undefined && (options.authorize === undefined || options.authorize === singleTeamAuthorize) ) { throw new ConfigError( "When you don't pass env.SLACK_BOT_TOKEN, your own authorize function, which supplies a valid token to use, needs to be passed instead." ); } this.env = options.env; this.client = new SlackAPIClient(options.env.SLACK_BOT_TOKEN, { logLevel: this.env.SLACK_LOGGING_LEVEL, }); this.appLevelToken = options.env.SLACK_APP_TOKEN; this.socketMode = options.socketMode ?? this.appLevelToken !== undefined; if (this.socketMode) { this.signingSecret = ""; } else { if (!this.env.SLACK_SIGNING_SECRET) { throw new ConfigError( "env.SLACK_SIGNING_SECRET is required to run your app on edge functions!" ); } this.signingSecret = this.env.SLACK_SIGNING_SECRET; } this.authorize = options.authorize ?? singleTeamAuthorize; this.routes = { events: options.routes?.events }; } beforeAuthorize(middleware: PreAuthorizeMiddleware<E>): SlackApp<E> { this.preAuthorizeMiddleware.push(middleware); return this; } middleware(middleware: Middleware<E>): SlackApp<E> { return this.afterAuthorize(middleware); } use(middleware: Middleware<E>): SlackApp<E> { return this.afterAuthorize(middleware); } afterAuthorize(middleware: Middleware<E>): SlackApp<E> { this.postAuthorizeMiddleware.push(middleware); return this; } command( pattern: StringOrRegExp, ack: ( req: SlackRequestWithRespond<E, SlashCommand> ) => Promise<MessageAckResponse>, lazy: ( req: SlackRequestWithRespond<E, SlashCommand> ) => Promise<void> = noopLazyListener ): SlackApp<E> { const handler: SlackMessageHandler<E, SlashCommand> = { ack, lazy }; this.#slashCommands.push((body) => { if (body.type || !body.command) { return null; } if (typeof pattern === "string" && body.command === pattern) { return handler; } else if ( typeof pattern === "object" && pattern instanceof RegExp && body.command.match(pattern) ) { return handler; } return null; }); return this; } event<Type extends string>( event: Type, lazy: (req: EventRequest<E, Type>) => Promise<void> ): SlackApp<E> { this.#events.push((body) => { if (body.type !==
PayloadType.EventsAPI || !body.event) {
return null; } if (body.event.type === event) { // deno-lint-ignore require-await return { ack: async () => "", lazy }; } return null; }); return this; } anyMessage(lazy: MessageEventHandler<E>): SlackApp<E> { return this.message(undefined, lazy); } message( pattern: MessageEventPattern, lazy: MessageEventHandler<E> ): SlackApp<E> { this.#events.push((body) => { if ( body.type !== PayloadType.EventsAPI || !body.event || body.event.type !== "message" ) { return null; } if (isPostedMessageEvent(body.event)) { let matched = true; if (pattern !== undefined) { if (typeof pattern === "string") { matched = body.event.text!.includes(pattern); } if (typeof pattern === "object") { matched = body.event.text!.match(pattern) !== null; } } if (matched) { // deno-lint-ignore require-await return { ack: async (_: EventRequest<E, "message">) => "", lazy }; } } return null; }); return this; } shortcut( callbackId: StringOrRegExp, ack: ( req: | SlackRequest<E, GlobalShortcut> | SlackRequestWithRespond<E, MessageShortcut> ) => Promise<AckResponse>, lazy: ( req: | SlackRequest<E, GlobalShortcut> | SlackRequestWithRespond<E, MessageShortcut> ) => Promise<void> = noopLazyListener ): SlackApp<E> { return this.globalShortcut(callbackId, ack, lazy).messageShortcut( callbackId, ack, lazy ); } globalShortcut( callbackId: StringOrRegExp, ack: (req: SlackRequest<E, GlobalShortcut>) => Promise<AckResponse>, lazy: ( req: SlackRequest<E, GlobalShortcut> ) => Promise<void> = noopLazyListener ): SlackApp<E> { const handler: SlackHandler<E, GlobalShortcut> = { ack, lazy }; this.#globalShorcuts.push((body) => { if (body.type !== PayloadType.GlobalShortcut || !body.callback_id) { return null; } if (typeof callbackId === "string" && body.callback_id === callbackId) { return handler; } else if ( typeof callbackId === "object" && callbackId instanceof RegExp && body.callback_id.match(callbackId) ) { return handler; } return null; }); return this; } messageShortcut( callbackId: StringOrRegExp, ack: ( req: SlackRequestWithRespond<E, MessageShortcut> ) => Promise<AckResponse>, lazy: ( req: SlackRequestWithRespond<E, MessageShortcut> ) => Promise<void> = noopLazyListener ): SlackApp<E> { const handler: SlackHandler<E, MessageShortcut> = { ack, lazy }; this.#messageShorcuts.push((body) => { if (body.type !== PayloadType.MessageShortcut || !body.callback_id) { return null; } if (typeof callbackId === "string" && body.callback_id === callbackId) { return handler; } else if ( typeof callbackId === "object" && callbackId instanceof RegExp && body.callback_id.match(callbackId) ) { return handler; } return null; }); return this; } action< T extends BlockElementTypes, A extends BlockAction<BlockElementAction<T>> = BlockAction< BlockElementAction<T> > >( constraints: | StringOrRegExp | { type: T; block_id?: string; action_id: string }, ack: (req: SlackRequestWithOptionalRespond<E, A>) => Promise<AckResponse>, lazy: ( req: SlackRequestWithOptionalRespond<E, A> ) => Promise<void> = noopLazyListener ): SlackApp<E> { const handler: SlackHandler<E, A> = { ack, lazy }; this.#blockActions.push((body) => { if ( body.type !== PayloadType.BlockAction || !body.actions || !body.actions[0] ) { return null; } const action = body.actions[0]; if (typeof constraints === "string" && action.action_id === constraints) { return handler; } else if (typeof constraints === "object") { if (constraints instanceof RegExp) { if (action.action_id.match(constraints)) { return handler; } } else if (constraints.type) { if (action.type === constraints.type) { if (action.action_id === constraints.action_id) { if ( constraints.block_id && action.block_id !== constraints.block_id ) { return null; } return handler; } } } } return null; }); return this; } options( constraints: StringOrRegExp | { block_id?: string; action_id: string }, ack: (req: SlackRequest<E, BlockSuggestion>) => Promise<OptionsAckResponse> ): SlackApp<E> { // Note that block_suggestion response must be done within 3 seconds. // So, we don't support the lazy handler for it. const handler: SlackOptionsHandler<E, BlockSuggestion> = { ack }; this.#blockSuggestions.push((body) => { if (body.type !== PayloadType.BlockSuggestion || !body.action_id) { return null; } if (typeof constraints === "string" && body.action_id === constraints) { return handler; } else if (typeof constraints === "object") { if (constraints instanceof RegExp) { if (body.action_id.match(constraints)) { return handler; } } else { if (body.action_id === constraints.action_id) { if (body.block_id && body.block_id !== constraints.block_id) { return null; } return handler; } } } return null; }); return this; } view( callbackId: StringOrRegExp, ack: ( req: | SlackRequestWithOptionalRespond<E, ViewSubmission> | SlackRequest<E, ViewClosed> ) => Promise<ViewAckResponse>, lazy: ( req: | SlackRequestWithOptionalRespond<E, ViewSubmission> | SlackRequest<E, ViewClosed> ) => Promise<void> = noopLazyListener ): SlackApp<E> { return this.viewSubmission(callbackId, ack, lazy).viewClosed( callbackId, ack, lazy ); } viewSubmission( callbackId: StringOrRegExp, ack: ( req: SlackRequestWithOptionalRespond<E, ViewSubmission> ) => Promise<ViewAckResponse>, lazy: ( req: SlackRequestWithOptionalRespond<E, ViewSubmission> ) => Promise<void> = noopLazyListener ): SlackApp<E> { const handler: SlackViewHandler<E, ViewSubmission> = { ack, lazy }; this.#viewSubmissions.push((body) => { if (body.type !== PayloadType.ViewSubmission || !body.view) { return null; } if ( typeof callbackId === "string" && body.view.callback_id === callbackId ) { return handler; } else if ( typeof callbackId === "object" && callbackId instanceof RegExp && body.view.callback_id.match(callbackId) ) { return handler; } return null; }); return this; } viewClosed( callbackId: StringOrRegExp, ack: (req: SlackRequest<E, ViewClosed>) => Promise<ViewAckResponse>, lazy: (req: SlackRequest<E, ViewClosed>) => Promise<void> = noopLazyListener ): SlackApp<E> { const handler: SlackViewHandler<E, ViewClosed> = { ack, lazy }; this.#viewClosed.push((body) => { if (body.type !== PayloadType.ViewClosed || !body.view) { return null; } if ( typeof callbackId === "string" && body.view.callback_id === callbackId ) { return handler; } else if ( typeof callbackId === "object" && callbackId instanceof RegExp && body.view.callback_id.match(callbackId) ) { return handler; } return null; }); return this; } async run( request: Request, ctx: ExecutionContext = new NoopExecutionContext() ): Promise<Response> { return await this.handleEventRequest(request, ctx); } async connect(): Promise<void> { if (!this.socketMode) { throw new ConfigError( "Both env.SLACK_APP_TOKEN and socketMode: true are required to start a Socket Mode connection!" ); } this.socketModeClient = new SocketModeClient(this); await this.socketModeClient.connect(); } async disconnect(): Promise<void> { if (this.socketModeClient) { await this.socketModeClient.disconnect(); } } async handleEventRequest( request: Request, ctx: ExecutionContext ): Promise<Response> { // If the routes.events is missing, any URLs can work for handing requests from Slack if (this.routes.events) { const { pathname } = new URL(request.url); if (pathname !== this.routes.events) { return new Response("Not found", { status: 404 }); } } // To avoid the following warning by Cloudflware, parse the body as Blob first // Called .text() on an HTTP body which does not appear to be text .. const blobRequestBody = await request.blob(); // We can safely assume the incoming request body is always text data const rawBody: string = await blobRequestBody.text(); // For Request URL verification if (rawBody.includes("ssl_check=")) { // Slack does not send the x-slack-signature header for this pattern. // Thus, we need to check the pattern before verifying a request. const bodyParams = new URLSearchParams(rawBody); if (bodyParams.get("ssl_check") === "1" && bodyParams.get("token")) { return new Response("", { status: 200 }); } } // Verify the request headers and body const isRequestSignatureVerified = this.socketMode || (await verifySlackRequest(this.signingSecret, request.headers, rawBody)); if (isRequestSignatureVerified) { // deno-lint-ignore no-explicit-any const body: Record<string, any> = await parseRequestBody( request.headers, rawBody ); let retryNum: number | undefined = undefined; try { const retryNumHeader = request.headers.get("x-slack-retry-num"); if (retryNumHeader) { retryNum = Number.parseInt(retryNumHeader); } else if (this.socketMode && body.retry_attempt) { retryNum = Number.parseInt(body.retry_attempt); } // deno-lint-ignore no-unused-vars } catch (e) { // Ignore an exception here } const retryReason = request.headers.get("x-slack-retry-reason") ?? body.retry_reason; const preAuthorizeRequest: PreAuthorizeSlackMiddlwareRequest<E> = { body, rawBody, retryNum, retryReason, context: builtBaseContext(body), env: this.env, headers: request.headers, }; if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log(`*** Received request body ***\n ${prettyPrint(body)}`); } for (const middlware of this.preAuthorizeMiddleware) { const response = await middlware(preAuthorizeRequest); if (response) { return toCompleteResponse(response); } } const authorizeResult: AuthorizeResult = await this.authorize( preAuthorizeRequest ); const authorizedContext: SlackAppContext = { ...preAuthorizeRequest.context, authorizeResult, client: new SlackAPIClient(authorizeResult.botToken, { logLevel: this.env.SLACK_LOGGING_LEVEL, }), botToken: authorizeResult.botToken, botId: authorizeResult.botId, botUserId: authorizeResult.botUserId, userToken: authorizeResult.userToken, }; if (authorizedContext.channelId) { const context = authorizedContext as SlackAppContextWithChannelId; const client = new SlackAPIClient(context.botToken); context.say = async (params) => await client.chat.postMessage({ channel: context.channelId, ...params, }); } if (authorizedContext.responseUrl) { const responseUrl = authorizedContext.responseUrl; // deno-lint-ignore require-await (authorizedContext as SlackAppContextWithRespond).respond = async ( params ) => { return new ResponseUrlSender(responseUrl).call(params); }; } const baseRequest: SlackMiddlwareRequest<E> = { ...preAuthorizeRequest, context: authorizedContext, }; for (const middlware of this.postAuthorizeMiddleware) { const response = await middlware(baseRequest); if (response) { return toCompleteResponse(response); } } const payload = body as SlackRequestBody; if (body.type === PayloadType.EventsAPI) { // Events API const slackRequest: SlackRequest<E, SlackEvent<string>> = { payload: body.event, ...baseRequest, }; for (const matcher of this.#events) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (!body.type && body.command) { // Slash commands const slackRequest: SlackRequest<E, SlashCommand> = { payload: body as SlashCommand, ...baseRequest, }; for (const matcher of this.#slashCommands) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (body.type === PayloadType.GlobalShortcut) { // Global shortcuts const slackRequest: SlackRequest<E, GlobalShortcut> = { payload: body as GlobalShortcut, ...baseRequest, }; for (const matcher of this.#globalShorcuts) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (body.type === PayloadType.MessageShortcut) { // Message shortcuts const slackRequest: SlackRequest<E, MessageShortcut> = { payload: body as MessageShortcut, ...baseRequest, }; for (const matcher of this.#messageShorcuts) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (body.type === PayloadType.BlockAction) { // Block actions // deno-lint-ignore no-explicit-any const slackRequest: SlackRequest<E, BlockAction<any>> = { // deno-lint-ignore no-explicit-any payload: body as BlockAction<any>, ...baseRequest, }; for (const matcher of this.#blockActions) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (body.type === PayloadType.BlockSuggestion) { // Block suggestions const slackRequest: SlackRequest<E, BlockSuggestion> = { payload: body as BlockSuggestion, ...baseRequest, }; for (const matcher of this.#blockSuggestions) { const handler = matcher(payload); if (handler) { // Note that the only way to respond to a block_suggestion request // is to send an HTTP response with options/option_groups. // Thus, we don't support lazy handlers for this pattern. const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (body.type === PayloadType.ViewSubmission) { // View submissions const slackRequest: SlackRequest<E, ViewSubmission> = { payload: body as ViewSubmission, ...baseRequest, }; for (const matcher of this.#viewSubmissions) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (body.type === PayloadType.ViewClosed) { // View closed const slackRequest: SlackRequest<E, ViewClosed> = { payload: body as ViewClosed, ...baseRequest, }; for (const matcher of this.#viewClosed) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } // TODO: Add code suggestion here console.log( `*** No listener found ***\n${JSON.stringify(baseRequest.body)}` ); return new Response("No listener found", { status: 404 }); } return new Response("Invalid signature", { status: 401 }); } } export type StringOrRegExp = string | RegExp; export type EventRequest<E extends SlackAppEnv, T> = Extract< AnySlackEventWithChannelId, { type: T } > extends never ? SlackRequest<E, Extract<AnySlackEvent, { type: T }>> : SlackRequestWithChannelId< E, Extract<AnySlackEventWithChannelId, { type: T }> >; export type MessageEventPattern = string | RegExp | undefined; export type MessageEventRequest< E extends SlackAppEnv, ST extends string | undefined > = SlackRequestWithChannelId< E, Extract<AnySlackEventWithChannelId, { subtype: ST }> >; export type MessageEventSubtypes = | undefined | "bot_message" | "thread_broadcast" | "file_share"; export type MessageEventHandler<E extends SlackAppEnv> = ( req: MessageEventRequest<E, MessageEventSubtypes> ) => Promise<void>; export const noopLazyListener = async () => {};
src/app.ts
seratch-slack-edge-c75c224
[ { "filename": "src/request/payload/event.ts", "retrieved_chunk": " | SharedChannelInviteApprovedEvent\n | SharedChannelInviteDeclinedEvent\n | StarAddedEvent\n | StarRemovedEvent;\nexport interface SlackEvent<Type extends string> {\n type: Type;\n subtype?: string;\n}\nexport interface AppRequestedEvent extends SlackEvent<\"app_requested\"> {\n type: \"app_requested\";", "score": 0.826723575592041 }, { "filename": "src/request/payload/event.ts", "retrieved_chunk": " api_app_id: string;\n}\nexport interface AppUninstalledEvent extends SlackEvent<\"app_uninstalled\"> {\n type: \"app_uninstalled\";\n}\nexport interface ChannelArchiveEvent extends SlackEvent<\"channel_archive\"> {\n type: \"channel_archive\";\n channel: string;\n user: string;\n is_moved?: number;", "score": 0.8179848790168762 }, { "filename": "src/middleware/built-in-middleware.ts", "retrieved_chunk": " if (req.body.event) {\n if (eventTypesToKeep.includes(req.body.event.type)) {\n return;\n }\n if (\n req.context.authorizeResult.botId === req.body.event.bot_id ||\n req.context.authorizeResult.botUserId === req.context.userId\n ) {\n return { status: 200, body: \"\" };\n }", "score": 0.807086706161499 }, { "filename": "src/request/request-body.ts", "retrieved_chunk": "export interface SlackRequestBody {\n type?: string;\n // slash commands\n command?: string;\n // event_callback\n event?: {\n type: string;\n subtype?: string;\n text?: string;\n };", "score": 0.8020153045654297 }, { "filename": "src/request/payload/event.ts", "retrieved_chunk": " new_channel_id: string;\n event_ts: string;\n}\nexport interface ChannelLeftEvent extends SlackEvent<\"channel_left\"> {\n type: \"channel_left\";\n channel: string;\n actor_id: string;\n event_ts: string;\n}\nexport interface ChannelRenameEvent extends SlackEvent<\"channel_rename\"> {", "score": 0.800107479095459 } ]
typescript
PayloadType.EventsAPI || !body.event) {
import { SlackAppEnv, SlackEdgeAppEnv, SlackSocketModeAppEnv } from "./app-env"; import { parseRequestBody } from "./request/request-parser"; import { verifySlackRequest } from "./request/request-verification"; import { AckResponse, SlackHandler } from "./handler/handler"; import { SlackRequestBody } from "./request/request-body"; import { PreAuthorizeSlackMiddlwareRequest, SlackRequestWithRespond, SlackMiddlwareRequest, SlackRequestWithOptionalRespond, SlackRequest, SlackRequestWithChannelId, } from "./request/request"; import { SlashCommand } from "./request/payload/slash-command"; import { toCompleteResponse } from "./response/response"; import { SlackEvent, AnySlackEvent, AnySlackEventWithChannelId, } from "./request/payload/event"; import { ResponseUrlSender, SlackAPIClient } from "slack-web-api-client"; import { builtBaseContext, SlackAppContext, SlackAppContextWithChannelId, SlackAppContextWithRespond, } from "./context/context"; import { PreAuthorizeMiddleware, Middleware } from "./middleware/middleware"; import { isDebugLogEnabled, prettyPrint } from "slack-web-api-client"; import { Authorize } from "./authorization/authorize"; import { AuthorizeResult } from "./authorization/authorize-result"; import { ignoringSelfEvents, urlVerification, } from "./middleware/built-in-middleware"; import { ConfigError } from "./errors"; import { GlobalShortcut } from "./request/payload/global-shortcut"; import { MessageShortcut } from "./request/payload/message-shortcut"; import { BlockAction, BlockElementAction, BlockElementTypes, } from "./request/payload/block-action"; import { ViewSubmission } from "./request/payload/view-submission"; import { ViewClosed } from "./request/payload/view-closed"; import { BlockSuggestion } from "./request/payload/block-suggestion"; import { OptionsAckResponse, SlackOptionsHandler, } from "./handler/options-handler"; import { SlackViewHandler, ViewAckResponse } from "./handler/view-handler"; import { MessageAckResponse, SlackMessageHandler, } from "./handler/message-handler"; import { singleTeamAuthorize } from "./authorization/single-team-authorize"; import { ExecutionContext, NoopExecutionContext } from "./execution-context"; import { PayloadType } from "./request/payload-types"; import { isPostedMessageEvent } from "./utility/message-events"; import { SocketModeClient } from "./socket-mode/socket-mode-client"; export interface SlackAppOptions< E extends SlackEdgeAppEnv | SlackSocketModeAppEnv > { env: E; authorize?: Authorize<E>; routes?: { events: string; }; socketMode?: boolean; } export class SlackApp<E extends SlackEdgeAppEnv | SlackSocketModeAppEnv> { public env: E; public client: SlackAPIClient; public authorize: Authorize<E>; public routes: { events: string | undefined }; public signingSecret: string; public appLevelToken: string | undefined; public socketMode: boolean; public socketModeClient: SocketModeClient | undefined; // deno-lint-ignore no-explicit-any public preAuthorizeMiddleware: PreAuthorizeMiddleware<any>[] = [ urlVerification, ]; // deno-lint-ignore no-explicit-any public postAuthorizeMiddleware: Middleware<any>[] = [ignoringSelfEvents]; #slashCommands: (( body: SlackRequestBody ) => SlackMessageHandler<E, SlashCommand> | null)[] = []; #events: (( body: SlackRequestBody ) => SlackHandler<E, SlackEvent<string>> | null)[] = []; #globalShorcuts: (( body: SlackRequestBody ) => SlackHandler<E, GlobalShortcut> | null)[] = []; #messageShorcuts: (( body: SlackRequestBody ) => SlackHandler<E, MessageShortcut> | null)[] = []; #blockActions: ((body: SlackRequestBody) => SlackHandler< E, // deno-lint-ignore no-explicit-any BlockAction<any> > | null)[] = []; #blockSuggestions: (( body: SlackRequestBody ) => SlackOptionsHandler<E, BlockSuggestion> | null)[] = []; #viewSubmissions: (( body: SlackRequestBody ) => SlackViewHandler<E, ViewSubmission> | null)[] = []; #viewClosed: (( body: SlackRequestBody ) => SlackViewHandler<E, ViewClosed> | null)[] = []; constructor(options: SlackAppOptions<E>) { if ( options.env.SLACK_BOT_TOKEN === undefined && (options.authorize === undefined || options.authorize === singleTeamAuthorize) ) { throw new ConfigError( "When you don't pass env.SLACK_BOT_TOKEN, your own authorize function, which supplies a valid token to use, needs to be passed instead." ); } this.env = options.env; this.client = new SlackAPIClient(options.env.SLACK_BOT_TOKEN, { logLevel: this.env.SLACK_LOGGING_LEVEL, }); this.appLevelToken = options.env.SLACK_APP_TOKEN; this.socketMode = options.socketMode ?? this.appLevelToken !== undefined; if (this.socketMode) { this.signingSecret = ""; } else { if (!this.env.SLACK_SIGNING_SECRET) { throw new ConfigError( "env.SLACK_SIGNING_SECRET is required to run your app on edge functions!" ); } this.signingSecret = this.env.SLACK_SIGNING_SECRET; } this.authorize = options.authorize ?? singleTeamAuthorize; this.routes = { events: options.routes?.events }; } beforeAuthorize(middleware: PreAuthorizeMiddleware<E>): SlackApp<E> { this.preAuthorizeMiddleware.push(middleware); return this; } middleware(middleware: Middleware<E>): SlackApp<E> { return this.afterAuthorize(middleware); } use(middleware: Middleware<E>): SlackApp<E> { return this.afterAuthorize(middleware); } afterAuthorize(middleware: Middleware<E>): SlackApp<E> { this.postAuthorizeMiddleware.push(middleware); return this; } command( pattern: StringOrRegExp, ack: ( req: SlackRequestWithRespond<E, SlashCommand> ) => Promise<MessageAckResponse>, lazy: ( req: SlackRequestWithRespond<E, SlashCommand> ) => Promise<void> = noopLazyListener ): SlackApp<E> { const handler: SlackMessageHandler<E, SlashCommand> = { ack, lazy }; this.#slashCommands.push((body) => { if (body.type || !body.command) { return null; } if (typeof pattern === "string" && body.command === pattern) { return handler; } else if ( typeof pattern === "object" && pattern instanceof RegExp && body.command.match(pattern) ) { return handler; } return null; }); return this; } event<Type extends string>( event: Type, lazy: (req: EventRequest<E, Type>) => Promise<void> ): SlackApp<E> { this.#events.push((body) => { if (body.type !== PayloadType.EventsAPI || !body.event) { return null; } if (body.event.type === event) { // deno-lint-ignore require-await return { ack: async () => "", lazy }; } return null; }); return this; } anyMessage(lazy: MessageEventHandler<E>): SlackApp<E> { return this.message(undefined, lazy); } message( pattern: MessageEventPattern, lazy: MessageEventHandler<E> ): SlackApp<E> { this.#events.push((body) => { if ( body.type !== PayloadType.EventsAPI || !body.event || body.event.type !== "message" ) { return null; } if (isPostedMessageEvent(body.event)) { let matched = true; if (pattern !== undefined) { if (typeof pattern === "string") { matched = body.event.text!.includes(pattern); } if (typeof pattern === "object") { matched = body.event.text!.match(pattern) !== null; } } if (matched) { // deno-lint-ignore require-await return { ack: async (_: EventRequest<E, "message">) => "", lazy }; } } return null; }); return this; } shortcut( callbackId: StringOrRegExp, ack: ( req: | SlackRequest<E, GlobalShortcut> | SlackRequestWithRespond<E, MessageShortcut> ) => Promise<AckResponse>, lazy: ( req: | SlackRequest<E, GlobalShortcut> | SlackRequestWithRespond<E, MessageShortcut> ) => Promise<void> = noopLazyListener ): SlackApp<E> { return this.globalShortcut(callbackId, ack, lazy).messageShortcut( callbackId, ack, lazy ); } globalShortcut( callbackId: StringOrRegExp, ack: (req: SlackRequest<E, GlobalShortcut>) => Promise<AckResponse>, lazy: ( req: SlackRequest<E, GlobalShortcut> ) => Promise<void> = noopLazyListener ): SlackApp<E> { const handler: SlackHandler<E, GlobalShortcut> = { ack, lazy }; this.#globalShorcuts.push((body) => { if (body.type !== PayloadType.GlobalShortcut || !body.callback_id) { return null; } if (typeof callbackId === "string" && body.callback_id === callbackId) { return handler; } else if ( typeof callbackId === "object" && callbackId instanceof RegExp && body.callback_id.match(callbackId) ) { return handler; } return null; }); return this; } messageShortcut( callbackId: StringOrRegExp, ack: ( req: SlackRequestWithRespond<E, MessageShortcut> ) => Promise<AckResponse>, lazy: ( req: SlackRequestWithRespond<E, MessageShortcut> ) => Promise<void> = noopLazyListener ): SlackApp<E> { const handler: SlackHandler<E, MessageShortcut> = { ack, lazy }; this.#messageShorcuts.push((body) => { if (body.type !== PayloadType.MessageShortcut || !body.callback_id) { return null; } if (typeof callbackId === "string" && body.callback_id === callbackId) { return handler; } else if ( typeof callbackId === "object" && callbackId instanceof RegExp && body.callback_id.match(callbackId) ) { return handler; } return null; }); return this; } action< T extends BlockElementTypes, A extends BlockAction<BlockElementAction<T>> = BlockAction< BlockElementAction<T> > >( constraints: | StringOrRegExp | { type: T; block_id?: string; action_id: string }, ack: (req: SlackRequestWithOptionalRespond<E, A>) => Promise<AckResponse>, lazy: ( req: SlackRequestWithOptionalRespond<E, A> ) => Promise<void> = noopLazyListener ): SlackApp<E> { const handler: SlackHandler<E, A> = { ack, lazy }; this.#blockActions.push((body) => { if ( body.type !== PayloadType.BlockAction || !body.actions || !body.actions[0] ) { return null; } const action = body.actions[0]; if (typeof constraints === "string" && action.action_id === constraints) { return handler; } else if (typeof constraints === "object") { if (constraints instanceof RegExp) { if (action.action_id.match(constraints)) { return handler; } } else if (constraints.type) { if (action.type === constraints.type) { if (action.action_id === constraints.action_id) { if ( constraints.block_id && action.block_id !== constraints.block_id ) { return null; } return handler; } } } } return null; }); return this; } options( constraints: StringOrRegExp | { block_id?: string; action_id: string }, ack: (req: SlackRequest<E, BlockSuggestion>) => Promise<OptionsAckResponse> ): SlackApp<E> { // Note that block_suggestion response must be done within 3 seconds. // So, we don't support the lazy handler for it. const handler: SlackOptionsHandler<E, BlockSuggestion> = { ack }; this.#blockSuggestions.push((body) => { if (body.type !== PayloadType.BlockSuggestion || !body.action_id) { return null; } if (typeof constraints === "string" && body.action_id === constraints) { return handler; } else if (typeof constraints === "object") { if (constraints instanceof RegExp) { if (body.action_id.match(constraints)) { return handler; } } else { if (body.action_id === constraints.action_id) {
if (body.block_id && body.block_id !== constraints.block_id) {
return null; } return handler; } } } return null; }); return this; } view( callbackId: StringOrRegExp, ack: ( req: | SlackRequestWithOptionalRespond<E, ViewSubmission> | SlackRequest<E, ViewClosed> ) => Promise<ViewAckResponse>, lazy: ( req: | SlackRequestWithOptionalRespond<E, ViewSubmission> | SlackRequest<E, ViewClosed> ) => Promise<void> = noopLazyListener ): SlackApp<E> { return this.viewSubmission(callbackId, ack, lazy).viewClosed( callbackId, ack, lazy ); } viewSubmission( callbackId: StringOrRegExp, ack: ( req: SlackRequestWithOptionalRespond<E, ViewSubmission> ) => Promise<ViewAckResponse>, lazy: ( req: SlackRequestWithOptionalRespond<E, ViewSubmission> ) => Promise<void> = noopLazyListener ): SlackApp<E> { const handler: SlackViewHandler<E, ViewSubmission> = { ack, lazy }; this.#viewSubmissions.push((body) => { if (body.type !== PayloadType.ViewSubmission || !body.view) { return null; } if ( typeof callbackId === "string" && body.view.callback_id === callbackId ) { return handler; } else if ( typeof callbackId === "object" && callbackId instanceof RegExp && body.view.callback_id.match(callbackId) ) { return handler; } return null; }); return this; } viewClosed( callbackId: StringOrRegExp, ack: (req: SlackRequest<E, ViewClosed>) => Promise<ViewAckResponse>, lazy: (req: SlackRequest<E, ViewClosed>) => Promise<void> = noopLazyListener ): SlackApp<E> { const handler: SlackViewHandler<E, ViewClosed> = { ack, lazy }; this.#viewClosed.push((body) => { if (body.type !== PayloadType.ViewClosed || !body.view) { return null; } if ( typeof callbackId === "string" && body.view.callback_id === callbackId ) { return handler; } else if ( typeof callbackId === "object" && callbackId instanceof RegExp && body.view.callback_id.match(callbackId) ) { return handler; } return null; }); return this; } async run( request: Request, ctx: ExecutionContext = new NoopExecutionContext() ): Promise<Response> { return await this.handleEventRequest(request, ctx); } async connect(): Promise<void> { if (!this.socketMode) { throw new ConfigError( "Both env.SLACK_APP_TOKEN and socketMode: true are required to start a Socket Mode connection!" ); } this.socketModeClient = new SocketModeClient(this); await this.socketModeClient.connect(); } async disconnect(): Promise<void> { if (this.socketModeClient) { await this.socketModeClient.disconnect(); } } async handleEventRequest( request: Request, ctx: ExecutionContext ): Promise<Response> { // If the routes.events is missing, any URLs can work for handing requests from Slack if (this.routes.events) { const { pathname } = new URL(request.url); if (pathname !== this.routes.events) { return new Response("Not found", { status: 404 }); } } // To avoid the following warning by Cloudflware, parse the body as Blob first // Called .text() on an HTTP body which does not appear to be text .. const blobRequestBody = await request.blob(); // We can safely assume the incoming request body is always text data const rawBody: string = await blobRequestBody.text(); // For Request URL verification if (rawBody.includes("ssl_check=")) { // Slack does not send the x-slack-signature header for this pattern. // Thus, we need to check the pattern before verifying a request. const bodyParams = new URLSearchParams(rawBody); if (bodyParams.get("ssl_check") === "1" && bodyParams.get("token")) { return new Response("", { status: 200 }); } } // Verify the request headers and body const isRequestSignatureVerified = this.socketMode || (await verifySlackRequest(this.signingSecret, request.headers, rawBody)); if (isRequestSignatureVerified) { // deno-lint-ignore no-explicit-any const body: Record<string, any> = await parseRequestBody( request.headers, rawBody ); let retryNum: number | undefined = undefined; try { const retryNumHeader = request.headers.get("x-slack-retry-num"); if (retryNumHeader) { retryNum = Number.parseInt(retryNumHeader); } else if (this.socketMode && body.retry_attempt) { retryNum = Number.parseInt(body.retry_attempt); } // deno-lint-ignore no-unused-vars } catch (e) { // Ignore an exception here } const retryReason = request.headers.get("x-slack-retry-reason") ?? body.retry_reason; const preAuthorizeRequest: PreAuthorizeSlackMiddlwareRequest<E> = { body, rawBody, retryNum, retryReason, context: builtBaseContext(body), env: this.env, headers: request.headers, }; if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log(`*** Received request body ***\n ${prettyPrint(body)}`); } for (const middlware of this.preAuthorizeMiddleware) { const response = await middlware(preAuthorizeRequest); if (response) { return toCompleteResponse(response); } } const authorizeResult: AuthorizeResult = await this.authorize( preAuthorizeRequest ); const authorizedContext: SlackAppContext = { ...preAuthorizeRequest.context, authorizeResult, client: new SlackAPIClient(authorizeResult.botToken, { logLevel: this.env.SLACK_LOGGING_LEVEL, }), botToken: authorizeResult.botToken, botId: authorizeResult.botId, botUserId: authorizeResult.botUserId, userToken: authorizeResult.userToken, }; if (authorizedContext.channelId) { const context = authorizedContext as SlackAppContextWithChannelId; const client = new SlackAPIClient(context.botToken); context.say = async (params) => await client.chat.postMessage({ channel: context.channelId, ...params, }); } if (authorizedContext.responseUrl) { const responseUrl = authorizedContext.responseUrl; // deno-lint-ignore require-await (authorizedContext as SlackAppContextWithRespond).respond = async ( params ) => { return new ResponseUrlSender(responseUrl).call(params); }; } const baseRequest: SlackMiddlwareRequest<E> = { ...preAuthorizeRequest, context: authorizedContext, }; for (const middlware of this.postAuthorizeMiddleware) { const response = await middlware(baseRequest); if (response) { return toCompleteResponse(response); } } const payload = body as SlackRequestBody; if (body.type === PayloadType.EventsAPI) { // Events API const slackRequest: SlackRequest<E, SlackEvent<string>> = { payload: body.event, ...baseRequest, }; for (const matcher of this.#events) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (!body.type && body.command) { // Slash commands const slackRequest: SlackRequest<E, SlashCommand> = { payload: body as SlashCommand, ...baseRequest, }; for (const matcher of this.#slashCommands) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (body.type === PayloadType.GlobalShortcut) { // Global shortcuts const slackRequest: SlackRequest<E, GlobalShortcut> = { payload: body as GlobalShortcut, ...baseRequest, }; for (const matcher of this.#globalShorcuts) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (body.type === PayloadType.MessageShortcut) { // Message shortcuts const slackRequest: SlackRequest<E, MessageShortcut> = { payload: body as MessageShortcut, ...baseRequest, }; for (const matcher of this.#messageShorcuts) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (body.type === PayloadType.BlockAction) { // Block actions // deno-lint-ignore no-explicit-any const slackRequest: SlackRequest<E, BlockAction<any>> = { // deno-lint-ignore no-explicit-any payload: body as BlockAction<any>, ...baseRequest, }; for (const matcher of this.#blockActions) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (body.type === PayloadType.BlockSuggestion) { // Block suggestions const slackRequest: SlackRequest<E, BlockSuggestion> = { payload: body as BlockSuggestion, ...baseRequest, }; for (const matcher of this.#blockSuggestions) { const handler = matcher(payload); if (handler) { // Note that the only way to respond to a block_suggestion request // is to send an HTTP response with options/option_groups. // Thus, we don't support lazy handlers for this pattern. const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (body.type === PayloadType.ViewSubmission) { // View submissions const slackRequest: SlackRequest<E, ViewSubmission> = { payload: body as ViewSubmission, ...baseRequest, }; for (const matcher of this.#viewSubmissions) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (body.type === PayloadType.ViewClosed) { // View closed const slackRequest: SlackRequest<E, ViewClosed> = { payload: body as ViewClosed, ...baseRequest, }; for (const matcher of this.#viewClosed) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } // TODO: Add code suggestion here console.log( `*** No listener found ***\n${JSON.stringify(baseRequest.body)}` ); return new Response("No listener found", { status: 404 }); } return new Response("Invalid signature", { status: 401 }); } } export type StringOrRegExp = string | RegExp; export type EventRequest<E extends SlackAppEnv, T> = Extract< AnySlackEventWithChannelId, { type: T } > extends never ? SlackRequest<E, Extract<AnySlackEvent, { type: T }>> : SlackRequestWithChannelId< E, Extract<AnySlackEventWithChannelId, { type: T }> >; export type MessageEventPattern = string | RegExp | undefined; export type MessageEventRequest< E extends SlackAppEnv, ST extends string | undefined > = SlackRequestWithChannelId< E, Extract<AnySlackEventWithChannelId, { subtype: ST }> >; export type MessageEventSubtypes = | undefined | "bot_message" | "thread_broadcast" | "file_share"; export type MessageEventHandler<E extends SlackAppEnv> = ( req: MessageEventRequest<E, MessageEventSubtypes> ) => Promise<void>; export const noopLazyListener = async () => {};
src/app.ts
seratch-slack-edge-c75c224
[ { "filename": "src/context/context.ts", "retrieved_chunk": " if (body.channel) {\n if (typeof body.channel === \"string\") {\n return body.channel;\n } else if (typeof body.channel === \"object\" && body.channel.id) {\n return body.channel.id;\n }\n } else if (body.channel_id) {\n return body.channel_id;\n } else if (body.event) {\n return extractChannelId(body.event);", "score": 0.8155465126037598 }, { "filename": "src/context/context.ts", "retrieved_chunk": " } else if (body.item) {\n // reaction_added: body[\"event\"][\"item\"]\n return extractChannelId(body.item);\n }\n return undefined;\n}", "score": 0.8087826371192932 }, { "filename": "src/middleware/built-in-middleware.ts", "retrieved_chunk": " if (req.body.event) {\n if (eventTypesToKeep.includes(req.body.event.type)) {\n return;\n }\n if (\n req.context.authorizeResult.botId === req.body.event.bot_id ||\n req.context.authorizeResult.botUserId === req.context.userId\n ) {\n return { status: 200, body: \"\" };\n }", "score": 0.8064082860946655 }, { "filename": "src/context/context.ts", "retrieved_chunk": " } else if (body.user_id) {\n return body.user_id;\n } else if (body.event) {\n return extractUserId(body.event);\n } else if (body.message) {\n return extractUserId(body.message);\n } else if (body.previous_message) {\n return extractUserId(body.previous_message);\n }\n return undefined;", "score": 0.8059951663017273 }, { "filename": "src/context/context.ts", "retrieved_chunk": " const eventTeam = body.event.team;\n if (eventTeam) {\n if (eventTeam.startsWith(\"T\")) {\n return eventTeam;\n } else if (eventTeam.startsWith(\"E\")) {\n if (eventTeam === body.enterprise_id) {\n return body.team_id;\n } else if (eventTeam === body.context_enterprise_id) {\n return body.context_team_id;\n }", "score": 0.7942037582397461 } ]
typescript
if (body.block_id && body.block_id !== constraints.block_id) {
import { type Course } from "@prisma/client"; import { type NextPage } from "next"; import Head from "next/head"; import { useForm } from "@mantine/form"; import AdminDashboardLayout from "~/components/layouts/admin-dashboard-layout"; import { Card as MantineCard, Image, Text, Flex, Grid, Button, Group, Modal, TextInput, Stack, Textarea, } from "@mantine/core"; import { useDisclosure } from "@mantine/hooks"; import { api } from "~/utils/api"; import Link from "next/link"; import { getImageUrl } from "~/utils/getImageUrl"; export function CourseCard({ course }: { course: Course }) { return ( <MantineCard shadow="sm" padding="lg" radius="md" withBorder> <MantineCard.Section> <Image src={getImageUrl(course.imageId)} height={160} alt="Norway" /> </MantineCard.Section> <Group position="apart" mt="md" mb="xs"> <Text weight={500}>{course.title}</Text> {/* <Badge color="pink" variant="light"> On Sale </Badge> */} </Group> <Text size="sm" color="dimmed"> {course.description} </Text> <Button component={Link} href={`/dashboard/courses/${course.id}`} variant="light" color="blue" fullWidth mt="md" radius="md" > Manage </Button> </MantineCard> ); } const Courses: NextPage = () => {
const courses = api.course.getCourses.useQuery();
const createCourseMutation = api.course.createCourse.useMutation(); const [ isCreateCourseModalOpen, { open: openCreateCourseModal, close: closeCreateCourseModal }, ] = useDisclosure(false); const createCourseForm = useForm({ initialValues: { title: "", description: "", }, }); return ( <> <Head> <title>Manage Courses</title> <meta name="description" content="Generated by create-t3-app" /> <link rel="icon" href="/favicon.ico" /> </Head> <Modal opened={isCreateCourseModalOpen} onClose={closeCreateCourseModal} title="Create Course" > <form onSubmit={createCourseForm.onSubmit(async (values) => { await createCourseMutation.mutateAsync(values); closeCreateCourseModal(); createCourseForm.reset(); await courses.refetch(); })} > <Stack> <TextInput withAsterisk label="Title" required placeholder="name your course here" {...createCourseForm.getInputProps("title")} /> <Textarea withAsterisk minRows={6} required label="Description" placeholder="describe your course a bit" {...createCourseForm.getInputProps("description")} /> </Stack> <Group position="right" mt="md"> <Button type="submit">Create Course</Button> </Group> </form> </Modal> <main> <AdminDashboardLayout> <Flex justify="space-between" align="center" direction="row"> <h1>Manage Courses</h1> <Button onClick={openCreateCourseModal}>Create Course</Button> </Flex> <Grid> {courses.data?.map((course) => ( <Grid.Col key={course.id} span={4}> <CourseCard course={course} /> </Grid.Col> ))} </Grid> </AdminDashboardLayout> </main> </> ); }; export default Courses;
src/pages/dashboard/courses/index.tsx
webdevcody-online-course-platform-ee963ca
[ { "filename": "src/pages/dashboard/courses/[courseId].tsx", "retrieved_chunk": " await fetch(url, {\n method: \"POST\",\n body: formData,\n });\n}\nconst Courses: NextPage = () => {\n const router = useRouter();\n const courseId = router.query.courseId as string;\n const updateCourseMutation = api.course.updateCourse.useMutation();\n const createSectionMutation = api.course.createSection.useMutation();", "score": 0.8988136649131775 }, { "filename": "src/pages/dashboard/courses/[courseId].tsx", "retrieved_chunk": " </form>\n </Stack>\n </Stack>\n </Stack>\n </AdminDashboardLayout>\n </main>\n </>\n );\n};\nexport default Courses;", "score": 0.8694794178009033 }, { "filename": "src/pages/dashboard/courses/[courseId].tsx", "retrieved_chunk": " const sortedSections = (courseQuery.data?.sections ?? []).sort(\n (a, b) => a.order - b.order\n );\n return (\n <>\n <Head>\n <title>Manage Courses</title>\n <meta name=\"description\" content=\"Generated by create-t3-app\" />\n <link rel=\"icon\" href=\"/favicon.ico\" />\n </Head>", "score": 0.8623001575469971 }, { "filename": "src/components/shell/_user.tsx", "retrieved_chunk": " Text,\n Box,\n useMantineTheme,\n rem,\n Button,\n Menu,\n} from \"@mantine/core\";\nimport { signIn, signOut, useSession } from \"next-auth/react\";\nexport function User() {\n const theme = useMantineTheme();", "score": 0.8414021730422974 }, { "filename": "src/pages/dashboard/index.tsx", "retrieved_chunk": "import { type NextPage } from \"next\";\nimport Head from \"next/head\";\nimport AdminDashboardLayout from \"~/components/layouts/admin-dashboard-layout\";\nconst Dashboard: NextPage = () => {\n return (\n <>\n <Head>\n <title>Create T3 App</title>\n <meta name=\"description\" content=\"Generated by create-t3-app\" />\n <link rel=\"icon\" href=\"/favicon.ico\" />", "score": 0.8347902297973633 } ]
typescript
const courses = api.course.getCourses.useQuery();
/* eslint-disable @typescript-eslint/no-unsafe-argument */ /* eslint-disable @next/next/no-img-element */ import { Button, Group, FileInput, TextInput, Title, Stack, } from "@mantine/core"; import { useForm } from "@mantine/form"; import { useDisclosure } from "@mantine/hooks"; import { IconCheck, IconEdit, IconLetterX } from "@tabler/icons-react"; import { type NextPage } from "next"; import Head from "next/head"; import { useRouter } from "next/router"; import { useState } from "react"; import AdminDashboardLayout from "~/components/layouts/admin-dashboard-layout"; import { api } from "~/utils/api"; import { getImageUrl } from "~/utils/getImageUrl"; async function uploadFileToS3({ getPresignedUrl, file, }: { getPresignedUrl: () => Promise<{ url: string; fields: Record<string, string>; }>; file: File; }) { const { url, fields } = await getPresignedUrl(); const data: Record<string, any> = { ...fields, "Content-Type": file.type, file, }; const formData = new FormData(); for (const name in data) { formData.append(name, data[name]); } await fetch(url, { method: "POST", body: formData, }); } const Courses: NextPage = () => { const router = useRouter(); const courseId = router.query.courseId as string; const updateCourseMutation = api.course.updateCourse.useMutation(); const createSectionMutation = api.course.createSection.useMutation(); const deleteSection = api.course.deleteSection.useMutation(); const swapSections = api.course.swapSections.useMutation(); const createPresignedUrlMutation = api.course.createPresignedUrl.useMutation(); const createPresignedUrlForVideoMutation = api.course.createPresignedUrlForVideo.useMutation(); const updateTitleForm = useForm({ initialValues: { title: "", }, }); const newSectionForm = useForm({ initialValues: { title: "", }, }); const [file, setFile] = useState<File | null>(null); const [newSection, setNewSection] = useState<File | null>(null); const courseQuery = api.course.getCourseById.useQuery( { courseId, }, { enabled: !!courseId, onSuccess(data) { updateTitleForm.setFieldValue("title", data?.title ?? ""); }, } ); const [isEditingTitle, { open: setEditTitle, close: unsetEditTitle }] = useDisclosure(false); const uploadImage = async (e: React.FormEvent<HTMLFormElement>) => { e.preventDefault(); if (!file) return; await uploadFileToS3({ getPresignedUrl: () => createPresignedUrlMutation.mutateAsync({ courseId, }), file, }); setFile(null); await courseQuery.refetch(); // if (fileRef.current) { // fileRef.current.value = ""; // } }; // const onFileChange = (e: React.FormEvent<HTMLInputElement>) => { // setFile(e.currentTarget.files?.[0]); // }; const sortedSections = (courseQuery.data?.sections ?? []).sort( (a, b) => a.order - b.order ); return ( <> <Head> <title>Manage Courses</title> <meta name="description" content="Generated by create-t3-app" /> <link rel="icon" href="/favicon.ico" /> </Head> <main> <AdminDashboardLayout> <Stack spacing={"xl"}> {isEditingTitle ? ( <form onSubmit={updateTitleForm.onSubmit(async (values) => { await updateCourseMutation.mutateAsync({ ...values, courseId, }); await courseQuery.refetch(); unsetEditTitle(); })} > <Group> <TextInput withAsterisk required placeholder="name your course here" {...updateTitleForm.getInputProps("title")} /> <Button color="green" type="submit"> <IconCheck /> </Button> <Button color="gray" onClick={unsetEditTitle}> <IconLetterX /> </Button> </Group> </form> ) : ( <Group> <Title order={1}>{courseQuery.data?.title}</Title> <Button color="gray" onClick={setEditTitle}> <IconEdit size="1rem" /> </Button> </Group> )} <Group> {courseQuery.data && ( <img width="200" alt="an image of the course" src={getImageUrl(courseQuery.data.imageId)} /> )} <Stack sx={{ flex: 1 }}> <form onSubmit={uploadImage}> <FileInput label="Course Image" onChange={setFile} value={file} /> <Button disabled={!file} type="submit" variant="light" color="blue" mt="md" radius="md" > Upload Image </Button> </form> </Stack> </Group> <Stack> <Title order={2}>Sections </Title>
{sortedSections.map((section, idx) => ( <Stack key={section.id}
p="xl" sx={{ border: "1px solid white", }} > <Group> <Title sx={{ flex: 1 }} order={3}> {section.title} </Title> {idx > 0 && ( <Button type="submit" variant="light" color="white" mt="md" radius="md" onClick={async () => { const targetSection = sortedSections[idx - 1]; if (!targetSection) return; await swapSections.mutateAsync({ sectionIdSource: section.id, sectionIdTarget: targetSection.id, }); await courseQuery.refetch(); }} > Move Up </Button> )} {idx < sortedSections.length - 1 && ( <Button type="submit" variant="light" color="white" mt="md" radius="md" onClick={async () => { const targetSection = sortedSections[idx + 1]; if (!targetSection) return; await swapSections.mutateAsync({ sectionIdSource: section.id, sectionIdTarget: targetSection.id, }); await courseQuery.refetch(); }} > Move Down </Button> )} <Button type="submit" variant="light" color="red" mt="md" radius="md" onClick={async () => { if ( !confirm( "are you sure you want to delete this section?" ) ) return; await deleteSection.mutateAsync({ sectionId: section.id, }); await courseQuery.refetch(); }} > Delete </Button> </Group> <video width="400" controls> <source src={`http://localhost:9000/wdc-online-course-platform/${section.videoId}`} type="video/mp4" /> Your browser does not support HTML video. </video> </Stack> ))} <Stack p="xl" sx={{ border: "1px dashed white", }} > <form onSubmit={newSectionForm.onSubmit(async (values) => { if (!newSection) return; const section = await createSectionMutation.mutateAsync({ courseId: courseId, title: values.title, }); await uploadFileToS3({ getPresignedUrl: () => createPresignedUrlForVideoMutation.mutateAsync({ sectionId: section.id, }), file: newSection, }); setNewSection(null); await courseQuery.refetch(); newSectionForm.reset(); })} > <Stack spacing="xl"> <Title order={3}>Create New Section</Title> <TextInput withAsterisk required label="Section Title" placeholder="name your section" {...newSectionForm.getInputProps("title")} /> <FileInput label="Section Video" onChange={setNewSection} required value={newSection} /> <Button type="submit" variant="light" color="blue" mt="md" radius="md" > Create Section </Button> </Stack> </form> </Stack> </Stack> </Stack> </AdminDashboardLayout> </main> </> ); }; export default Courses;
src/pages/dashboard/courses/[courseId].tsx
webdevcody-online-course-platform-ee963ca
[ { "filename": "src/pages/dashboard/courses/index.tsx", "retrieved_chunk": " </Stack>\n <Group position=\"right\" mt=\"md\">\n <Button type=\"submit\">Create Course</Button>\n </Group>\n </form>\n </Modal>\n <main>\n <AdminDashboardLayout>\n <Flex justify=\"space-between\" align=\"center\" direction=\"row\">\n <h1>Manage Courses</h1>", "score": 0.8324604034423828 }, { "filename": "src/pages/dashboard/courses/index.tsx", "retrieved_chunk": " createCourseForm.reset();\n await courses.refetch();\n })}\n >\n <Stack>\n <TextInput\n withAsterisk\n label=\"Title\"\n required\n placeholder=\"name your course here\"", "score": 0.8100746870040894 }, { "filename": "src/pages/dashboard/courses/index.tsx", "retrieved_chunk": " <Button onClick={openCreateCourseModal}>Create Course</Button>\n </Flex>\n <Grid>\n {courses.data?.map((course) => (\n <Grid.Col key={course.id} span={4}>\n <CourseCard course={course} />\n </Grid.Col>\n ))}\n </Grid>\n </AdminDashboardLayout>", "score": 0.8073400259017944 }, { "filename": "src/pages/dashboard/courses/index.tsx", "retrieved_chunk": " {/* <Badge color=\"pink\" variant=\"light\">\n On Sale\n </Badge> */}\n </Group>\n <Text size=\"sm\" color=\"dimmed\">\n {course.description}\n </Text>\n <Button\n component={Link}\n href={`/dashboard/courses/${course.id}`}", "score": 0.8000372052192688 }, { "filename": "src/components/shell/_user.tsx", "retrieved_chunk": " </Group>\n </Menu.Target>\n <Menu.Dropdown>\n <Menu.Item\n onClick={() => signOut()}\n icon={<IconPower size={14} />}\n >\n Sign Out\n </Menu.Item>\n </Menu.Dropdown>", "score": 0.7996410131454468 } ]
typescript
{sortedSections.map((section, idx) => ( <Stack key={section.id}
import { SlackAppEnv, SlackEdgeAppEnv, SlackSocketModeAppEnv } from "./app-env"; import { parseRequestBody } from "./request/request-parser"; import { verifySlackRequest } from "./request/request-verification"; import { AckResponse, SlackHandler } from "./handler/handler"; import { SlackRequestBody } from "./request/request-body"; import { PreAuthorizeSlackMiddlwareRequest, SlackRequestWithRespond, SlackMiddlwareRequest, SlackRequestWithOptionalRespond, SlackRequest, SlackRequestWithChannelId, } from "./request/request"; import { SlashCommand } from "./request/payload/slash-command"; import { toCompleteResponse } from "./response/response"; import { SlackEvent, AnySlackEvent, AnySlackEventWithChannelId, } from "./request/payload/event"; import { ResponseUrlSender, SlackAPIClient } from "slack-web-api-client"; import { builtBaseContext, SlackAppContext, SlackAppContextWithChannelId, SlackAppContextWithRespond, } from "./context/context"; import { PreAuthorizeMiddleware, Middleware } from "./middleware/middleware"; import { isDebugLogEnabled, prettyPrint } from "slack-web-api-client"; import { Authorize } from "./authorization/authorize"; import { AuthorizeResult } from "./authorization/authorize-result"; import { ignoringSelfEvents, urlVerification, } from "./middleware/built-in-middleware"; import { ConfigError } from "./errors"; import { GlobalShortcut } from "./request/payload/global-shortcut"; import { MessageShortcut } from "./request/payload/message-shortcut"; import { BlockAction, BlockElementAction, BlockElementTypes, } from "./request/payload/block-action"; import { ViewSubmission } from "./request/payload/view-submission"; import { ViewClosed } from "./request/payload/view-closed"; import { BlockSuggestion } from "./request/payload/block-suggestion"; import { OptionsAckResponse, SlackOptionsHandler, } from "./handler/options-handler"; import { SlackViewHandler, ViewAckResponse } from "./handler/view-handler"; import { MessageAckResponse, SlackMessageHandler, } from "./handler/message-handler"; import { singleTeamAuthorize } from "./authorization/single-team-authorize"; import { ExecutionContext, NoopExecutionContext } from "./execution-context"; import { PayloadType } from "./request/payload-types"; import { isPostedMessageEvent } from "./utility/message-events"; import { SocketModeClient } from "./socket-mode/socket-mode-client"; export interface SlackAppOptions< E extends SlackEdgeAppEnv | SlackSocketModeAppEnv > { env: E; authorize?: Authorize<E>; routes?: { events: string; }; socketMode?: boolean; } export class SlackApp<E extends SlackEdgeAppEnv | SlackSocketModeAppEnv> { public env: E; public client: SlackAPIClient; public authorize: Authorize<E>; public routes: { events: string | undefined }; public signingSecret: string; public appLevelToken: string | undefined; public socketMode: boolean; public socketModeClient: SocketModeClient | undefined; // deno-lint-ignore no-explicit-any public preAuthorizeMiddleware: PreAuthorizeMiddleware<any>[] = [ urlVerification, ]; // deno-lint-ignore no-explicit-any public postAuthorizeMiddleware: Middleware<any>[] = [ignoringSelfEvents]; #slashCommands: (( body: SlackRequestBody ) => SlackMessageHandler<E, SlashCommand> | null)[] = []; #events: (( body: SlackRequestBody ) => SlackHandler<E, SlackEvent<string>> | null)[] = []; #globalShorcuts: (( body: SlackRequestBody ) => SlackHandler<E, GlobalShortcut> | null)[] = []; #messageShorcuts: (( body: SlackRequestBody ) => SlackHandler<E, MessageShortcut> | null)[] = []; #blockActions: ((body: SlackRequestBody) => SlackHandler< E, // deno-lint-ignore no-explicit-any BlockAction<any> > | null)[] = []; #blockSuggestions: (( body: SlackRequestBody ) => SlackOptionsHandler<E, BlockSuggestion> | null)[] = []; #viewSubmissions: (( body: SlackRequestBody ) => SlackViewHandler<E, ViewSubmission> | null)[] = []; #viewClosed: (( body: SlackRequestBody ) => SlackViewHandler<E, ViewClosed> | null)[] = []; constructor(options: SlackAppOptions<E>) { if ( options.env.SLACK_BOT_TOKEN === undefined && (options.authorize === undefined || options.authorize === singleTeamAuthorize) ) { throw new ConfigError( "When you don't pass env.SLACK_BOT_TOKEN, your own authorize function, which supplies a valid token to use, needs to be passed instead." ); } this.env = options.env; this.client = new SlackAPIClient(options.env.SLACK_BOT_TOKEN, { logLevel: this.env.SLACK_LOGGING_LEVEL, }); this.appLevelToken = options.env.SLACK_APP_TOKEN; this.socketMode = options.socketMode ?? this.appLevelToken !== undefined; if (this.socketMode) { this.signingSecret = ""; } else { if (!this.env.SLACK_SIGNING_SECRET) { throw new ConfigError( "env.SLACK_SIGNING_SECRET is required to run your app on edge functions!" ); } this.signingSecret = this.env.SLACK_SIGNING_SECRET; } this.authorize = options.authorize ?? singleTeamAuthorize; this.routes = { events: options.routes?.events }; } beforeAuthorize(middleware: PreAuthorizeMiddleware<E>): SlackApp<E> { this.preAuthorizeMiddleware.push(middleware); return this; } middleware(middleware: Middleware<E>): SlackApp<E> { return this.afterAuthorize(middleware); } use(middleware: Middleware<E>): SlackApp<E> { return this.afterAuthorize(middleware); } afterAuthorize(middleware: Middleware<E>): SlackApp<E> { this.postAuthorizeMiddleware.push(middleware); return this; } command( pattern: StringOrRegExp, ack: ( req: SlackRequestWithRespond<E, SlashCommand> ) => Promise<MessageAckResponse>, lazy: ( req: SlackRequestWithRespond<E, SlashCommand> ) => Promise<void> = noopLazyListener ): SlackApp<E> { const handler: SlackMessageHandler<E, SlashCommand> = { ack, lazy }; this.#slashCommands.push((body) => { if (body.type || !body.command) { return null; } if (typeof pattern === "string" && body.command === pattern) { return handler; } else if ( typeof pattern === "object" && pattern instanceof RegExp && body.command.match(pattern) ) { return handler; } return null; }); return this; } event<Type extends string>( event: Type, lazy: (req: EventRequest<E, Type>) => Promise<void> ): SlackApp<E> { this.#events.push((body) => { if (body.type !== PayloadType.EventsAPI || !body.event) { return null; } if (body.event.type === event) { // deno-lint-ignore require-await return { ack: async () => "", lazy }; } return null; }); return this; } anyMessage(lazy: MessageEventHandler<E>): SlackApp<E> { return this.message(undefined, lazy); } message( pattern: MessageEventPattern, lazy: MessageEventHandler<E> ): SlackApp<E> { this.#events.push((body) => { if ( body.type !== PayloadType.EventsAPI || !body.event || body.event.type !== "message" ) { return null; } if (isPostedMessageEvent(body.event)) { let matched = true; if (pattern !== undefined) { if (typeof pattern === "string") { matched = body.event.text!.includes(pattern); } if (typeof pattern === "object") { matched = body.event.text!.match(pattern) !== null; } } if (matched) { // deno-lint-ignore require-await return { ack: async (_: EventRequest<E, "message">) => "", lazy }; } } return null; }); return this; } shortcut( callbackId: StringOrRegExp, ack: ( req: | SlackRequest<E, GlobalShortcut> | SlackRequestWithRespond<E, MessageShortcut> ) => Promise<AckResponse>, lazy: ( req: | SlackRequest<E, GlobalShortcut> | SlackRequestWithRespond<E, MessageShortcut> ) => Promise<void> = noopLazyListener ): SlackApp<E> { return this.globalShortcut(callbackId, ack, lazy).messageShortcut( callbackId, ack, lazy ); } globalShortcut( callbackId: StringOrRegExp, ack: (req: SlackRequest<E, GlobalShortcut>) => Promise<AckResponse>, lazy: ( req: SlackRequest<E, GlobalShortcut> ) => Promise<void> = noopLazyListener ): SlackApp<E> { const handler: SlackHandler<E, GlobalShortcut> = { ack, lazy }; this.#globalShorcuts.push((body) => {
if (body.type !== PayloadType.GlobalShortcut || !body.callback_id) {
return null; } if (typeof callbackId === "string" && body.callback_id === callbackId) { return handler; } else if ( typeof callbackId === "object" && callbackId instanceof RegExp && body.callback_id.match(callbackId) ) { return handler; } return null; }); return this; } messageShortcut( callbackId: StringOrRegExp, ack: ( req: SlackRequestWithRespond<E, MessageShortcut> ) => Promise<AckResponse>, lazy: ( req: SlackRequestWithRespond<E, MessageShortcut> ) => Promise<void> = noopLazyListener ): SlackApp<E> { const handler: SlackHandler<E, MessageShortcut> = { ack, lazy }; this.#messageShorcuts.push((body) => { if (body.type !== PayloadType.MessageShortcut || !body.callback_id) { return null; } if (typeof callbackId === "string" && body.callback_id === callbackId) { return handler; } else if ( typeof callbackId === "object" && callbackId instanceof RegExp && body.callback_id.match(callbackId) ) { return handler; } return null; }); return this; } action< T extends BlockElementTypes, A extends BlockAction<BlockElementAction<T>> = BlockAction< BlockElementAction<T> > >( constraints: | StringOrRegExp | { type: T; block_id?: string; action_id: string }, ack: (req: SlackRequestWithOptionalRespond<E, A>) => Promise<AckResponse>, lazy: ( req: SlackRequestWithOptionalRespond<E, A> ) => Promise<void> = noopLazyListener ): SlackApp<E> { const handler: SlackHandler<E, A> = { ack, lazy }; this.#blockActions.push((body) => { if ( body.type !== PayloadType.BlockAction || !body.actions || !body.actions[0] ) { return null; } const action = body.actions[0]; if (typeof constraints === "string" && action.action_id === constraints) { return handler; } else if (typeof constraints === "object") { if (constraints instanceof RegExp) { if (action.action_id.match(constraints)) { return handler; } } else if (constraints.type) { if (action.type === constraints.type) { if (action.action_id === constraints.action_id) { if ( constraints.block_id && action.block_id !== constraints.block_id ) { return null; } return handler; } } } } return null; }); return this; } options( constraints: StringOrRegExp | { block_id?: string; action_id: string }, ack: (req: SlackRequest<E, BlockSuggestion>) => Promise<OptionsAckResponse> ): SlackApp<E> { // Note that block_suggestion response must be done within 3 seconds. // So, we don't support the lazy handler for it. const handler: SlackOptionsHandler<E, BlockSuggestion> = { ack }; this.#blockSuggestions.push((body) => { if (body.type !== PayloadType.BlockSuggestion || !body.action_id) { return null; } if (typeof constraints === "string" && body.action_id === constraints) { return handler; } else if (typeof constraints === "object") { if (constraints instanceof RegExp) { if (body.action_id.match(constraints)) { return handler; } } else { if (body.action_id === constraints.action_id) { if (body.block_id && body.block_id !== constraints.block_id) { return null; } return handler; } } } return null; }); return this; } view( callbackId: StringOrRegExp, ack: ( req: | SlackRequestWithOptionalRespond<E, ViewSubmission> | SlackRequest<E, ViewClosed> ) => Promise<ViewAckResponse>, lazy: ( req: | SlackRequestWithOptionalRespond<E, ViewSubmission> | SlackRequest<E, ViewClosed> ) => Promise<void> = noopLazyListener ): SlackApp<E> { return this.viewSubmission(callbackId, ack, lazy).viewClosed( callbackId, ack, lazy ); } viewSubmission( callbackId: StringOrRegExp, ack: ( req: SlackRequestWithOptionalRespond<E, ViewSubmission> ) => Promise<ViewAckResponse>, lazy: ( req: SlackRequestWithOptionalRespond<E, ViewSubmission> ) => Promise<void> = noopLazyListener ): SlackApp<E> { const handler: SlackViewHandler<E, ViewSubmission> = { ack, lazy }; this.#viewSubmissions.push((body) => { if (body.type !== PayloadType.ViewSubmission || !body.view) { return null; } if ( typeof callbackId === "string" && body.view.callback_id === callbackId ) { return handler; } else if ( typeof callbackId === "object" && callbackId instanceof RegExp && body.view.callback_id.match(callbackId) ) { return handler; } return null; }); return this; } viewClosed( callbackId: StringOrRegExp, ack: (req: SlackRequest<E, ViewClosed>) => Promise<ViewAckResponse>, lazy: (req: SlackRequest<E, ViewClosed>) => Promise<void> = noopLazyListener ): SlackApp<E> { const handler: SlackViewHandler<E, ViewClosed> = { ack, lazy }; this.#viewClosed.push((body) => { if (body.type !== PayloadType.ViewClosed || !body.view) { return null; } if ( typeof callbackId === "string" && body.view.callback_id === callbackId ) { return handler; } else if ( typeof callbackId === "object" && callbackId instanceof RegExp && body.view.callback_id.match(callbackId) ) { return handler; } return null; }); return this; } async run( request: Request, ctx: ExecutionContext = new NoopExecutionContext() ): Promise<Response> { return await this.handleEventRequest(request, ctx); } async connect(): Promise<void> { if (!this.socketMode) { throw new ConfigError( "Both env.SLACK_APP_TOKEN and socketMode: true are required to start a Socket Mode connection!" ); } this.socketModeClient = new SocketModeClient(this); await this.socketModeClient.connect(); } async disconnect(): Promise<void> { if (this.socketModeClient) { await this.socketModeClient.disconnect(); } } async handleEventRequest( request: Request, ctx: ExecutionContext ): Promise<Response> { // If the routes.events is missing, any URLs can work for handing requests from Slack if (this.routes.events) { const { pathname } = new URL(request.url); if (pathname !== this.routes.events) { return new Response("Not found", { status: 404 }); } } // To avoid the following warning by Cloudflware, parse the body as Blob first // Called .text() on an HTTP body which does not appear to be text .. const blobRequestBody = await request.blob(); // We can safely assume the incoming request body is always text data const rawBody: string = await blobRequestBody.text(); // For Request URL verification if (rawBody.includes("ssl_check=")) { // Slack does not send the x-slack-signature header for this pattern. // Thus, we need to check the pattern before verifying a request. const bodyParams = new URLSearchParams(rawBody); if (bodyParams.get("ssl_check") === "1" && bodyParams.get("token")) { return new Response("", { status: 200 }); } } // Verify the request headers and body const isRequestSignatureVerified = this.socketMode || (await verifySlackRequest(this.signingSecret, request.headers, rawBody)); if (isRequestSignatureVerified) { // deno-lint-ignore no-explicit-any const body: Record<string, any> = await parseRequestBody( request.headers, rawBody ); let retryNum: number | undefined = undefined; try { const retryNumHeader = request.headers.get("x-slack-retry-num"); if (retryNumHeader) { retryNum = Number.parseInt(retryNumHeader); } else if (this.socketMode && body.retry_attempt) { retryNum = Number.parseInt(body.retry_attempt); } // deno-lint-ignore no-unused-vars } catch (e) { // Ignore an exception here } const retryReason = request.headers.get("x-slack-retry-reason") ?? body.retry_reason; const preAuthorizeRequest: PreAuthorizeSlackMiddlwareRequest<E> = { body, rawBody, retryNum, retryReason, context: builtBaseContext(body), env: this.env, headers: request.headers, }; if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log(`*** Received request body ***\n ${prettyPrint(body)}`); } for (const middlware of this.preAuthorizeMiddleware) { const response = await middlware(preAuthorizeRequest); if (response) { return toCompleteResponse(response); } } const authorizeResult: AuthorizeResult = await this.authorize( preAuthorizeRequest ); const authorizedContext: SlackAppContext = { ...preAuthorizeRequest.context, authorizeResult, client: new SlackAPIClient(authorizeResult.botToken, { logLevel: this.env.SLACK_LOGGING_LEVEL, }), botToken: authorizeResult.botToken, botId: authorizeResult.botId, botUserId: authorizeResult.botUserId, userToken: authorizeResult.userToken, }; if (authorizedContext.channelId) { const context = authorizedContext as SlackAppContextWithChannelId; const client = new SlackAPIClient(context.botToken); context.say = async (params) => await client.chat.postMessage({ channel: context.channelId, ...params, }); } if (authorizedContext.responseUrl) { const responseUrl = authorizedContext.responseUrl; // deno-lint-ignore require-await (authorizedContext as SlackAppContextWithRespond).respond = async ( params ) => { return new ResponseUrlSender(responseUrl).call(params); }; } const baseRequest: SlackMiddlwareRequest<E> = { ...preAuthorizeRequest, context: authorizedContext, }; for (const middlware of this.postAuthorizeMiddleware) { const response = await middlware(baseRequest); if (response) { return toCompleteResponse(response); } } const payload = body as SlackRequestBody; if (body.type === PayloadType.EventsAPI) { // Events API const slackRequest: SlackRequest<E, SlackEvent<string>> = { payload: body.event, ...baseRequest, }; for (const matcher of this.#events) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (!body.type && body.command) { // Slash commands const slackRequest: SlackRequest<E, SlashCommand> = { payload: body as SlashCommand, ...baseRequest, }; for (const matcher of this.#slashCommands) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (body.type === PayloadType.GlobalShortcut) { // Global shortcuts const slackRequest: SlackRequest<E, GlobalShortcut> = { payload: body as GlobalShortcut, ...baseRequest, }; for (const matcher of this.#globalShorcuts) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (body.type === PayloadType.MessageShortcut) { // Message shortcuts const slackRequest: SlackRequest<E, MessageShortcut> = { payload: body as MessageShortcut, ...baseRequest, }; for (const matcher of this.#messageShorcuts) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (body.type === PayloadType.BlockAction) { // Block actions // deno-lint-ignore no-explicit-any const slackRequest: SlackRequest<E, BlockAction<any>> = { // deno-lint-ignore no-explicit-any payload: body as BlockAction<any>, ...baseRequest, }; for (const matcher of this.#blockActions) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (body.type === PayloadType.BlockSuggestion) { // Block suggestions const slackRequest: SlackRequest<E, BlockSuggestion> = { payload: body as BlockSuggestion, ...baseRequest, }; for (const matcher of this.#blockSuggestions) { const handler = matcher(payload); if (handler) { // Note that the only way to respond to a block_suggestion request // is to send an HTTP response with options/option_groups. // Thus, we don't support lazy handlers for this pattern. const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (body.type === PayloadType.ViewSubmission) { // View submissions const slackRequest: SlackRequest<E, ViewSubmission> = { payload: body as ViewSubmission, ...baseRequest, }; for (const matcher of this.#viewSubmissions) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (body.type === PayloadType.ViewClosed) { // View closed const slackRequest: SlackRequest<E, ViewClosed> = { payload: body as ViewClosed, ...baseRequest, }; for (const matcher of this.#viewClosed) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } // TODO: Add code suggestion here console.log( `*** No listener found ***\n${JSON.stringify(baseRequest.body)}` ); return new Response("No listener found", { status: 404 }); } return new Response("Invalid signature", { status: 401 }); } } export type StringOrRegExp = string | RegExp; export type EventRequest<E extends SlackAppEnv, T> = Extract< AnySlackEventWithChannelId, { type: T } > extends never ? SlackRequest<E, Extract<AnySlackEvent, { type: T }>> : SlackRequestWithChannelId< E, Extract<AnySlackEventWithChannelId, { type: T }> >; export type MessageEventPattern = string | RegExp | undefined; export type MessageEventRequest< E extends SlackAppEnv, ST extends string | undefined > = SlackRequestWithChannelId< E, Extract<AnySlackEventWithChannelId, { subtype: ST }> >; export type MessageEventSubtypes = | undefined | "bot_message" | "thread_broadcast" | "file_share"; export type MessageEventHandler<E extends SlackAppEnv> = ( req: MessageEventRequest<E, MessageEventSubtypes> ) => Promise<void>; export const noopLazyListener = async () => {};
src/app.ts
seratch-slack-edge-c75c224
[ { "filename": "src/request/payload/global-shortcut.ts", "retrieved_chunk": "export interface GlobalShortcut {\n type: \"shortcut\";\n callback_id: string;\n trigger_id: string;\n user: {\n id: string;\n username: string;\n team_id: string;\n };\n team: {", "score": 0.8433268070220947 }, { "filename": "src/handler/handler.ts", "retrieved_chunk": "import { SlackAppEnv } from \"../app-env\";\nimport { SlackRequest } from \"../request/request\";\nimport { SlackResponse } from \"../response/response\";\nexport type AckResponse = SlackResponse | string | void;\nexport interface SlackHandler<E extends SlackAppEnv, Payload> {\n ack(request: SlackRequest<E, Payload>): Promise<AckResponse>;\n lazy(request: SlackRequest<E, Payload>): Promise<void>;\n}", "score": 0.8215712308883667 }, { "filename": "src/handler/message-handler.ts", "retrieved_chunk": "import { SlackAppEnv } from \"../app-env\";\nimport { SlackRequest } from \"../request/request\";\nimport { MessageResponse } from \"../response/response-body\";\nimport { AckResponse } from \"./handler\";\nexport type MessageAckResponse = AckResponse | MessageResponse;\nexport interface SlackMessageHandler<E extends SlackAppEnv, Payload> {\n ack(request: SlackRequest<E, Payload>): Promise<MessageAckResponse>;\n lazy(request: SlackRequest<E, Payload>): Promise<void>;\n}", "score": 0.8137940168380737 }, { "filename": "src/handler/view-handler.ts", "retrieved_chunk": "import { SlackAppEnv } from \"../app-env\";\nimport { SlackRequest } from \"../request/request\";\nimport { SlackViewResponse } from \"../response/response\";\nexport type ViewAckResponse = SlackViewResponse | void;\nexport type SlackViewHandler<E extends SlackAppEnv, Payload> = {\n ack(request: SlackRequest<E, Payload>): Promise<ViewAckResponse>;\n lazy(request: SlackRequest<E, Payload>): Promise<void>;\n};", "score": 0.8055113554000854 }, { "filename": "src/request/payload/message-shortcut.ts", "retrieved_chunk": "export interface MessageShortcut {\n type: \"message_action\";\n callback_id: string;\n trigger_id: string;\n message_ts: string;\n response_url: string;\n message: {\n type: \"message\";\n user?: string;\n ts: string;", "score": 0.8042998909950256 } ]
typescript
if (body.type !== PayloadType.GlobalShortcut || !body.callback_id) {
import { z } from "zod"; import { createTRPCRouter, protectedProcedure } from "~/server/api/trpc"; import { S3Client } from "@aws-sdk/client-s3"; import { createPresignedPost } from "@aws-sdk/s3-presigned-post"; import { env } from "~/env.mjs"; import { TRPCError } from "@trpc/server"; import { v4 as uuidv4 } from "uuid"; const UPLOAD_MAX_FILE_SIZE = 1000000; const s3Client = new S3Client({ region: "us-east-1", endpoint: "http://localhost:9000", forcePathStyle: true, credentials: { accessKeyId: "S3RVER", secretAccessKey: "S3RVER", }, }); export const courseRouter = createTRPCRouter({ getCourseById: protectedProcedure .input( z.object({ courseId: z.string(), }) ) .query(({ ctx, input }) => { return ctx.prisma.course.findUnique({ where: { id: input.courseId, }, include: { sections: true, }, }); }), getCourses: protectedProcedure.query(({ ctx }) => { return ctx.prisma.course.findMany({ where: { userId: ctx.session.user.id, }, }); }), createCourse: protectedProcedure .input(z.object({ title: z.string(), description: z.string() })) .mutation(async ({ ctx, input }) => { const userId = ctx.session.user.id; const newCourse = await ctx.prisma.course.create({ data: { title: input.title, description: input.description, userId: userId, }, }); return newCourse; }), updateCourse: protectedProcedure .input(z.object({ title: z.string(), courseId: z.string() })) .mutation(async ({ ctx, input }) => { const userId = ctx.session.user.id; await ctx.prisma.course.updateMany({ where: { id: input.courseId, userId, }, data: { title: input.title, }, }); return { status: "updated" }; }), createPresignedUrl: protectedProcedure .input(z.object({ courseId: z.string() })) .mutation(async ({ ctx, input }) => { // const userId = ctx.session.user.id; const course = await ctx.prisma.course.findUnique({ where: { id: input.courseId, }, }); if (!course) { throw new TRPCError({ code: "NOT_FOUND", message: "the course does not exist", }); } const imageId = uuidv4(); await ctx.prisma.course.update({ where: { id: course.id, }, data: { imageId, }, }); return createPresignedPost(s3Client, { Bucket:
env.NEXT_PUBLIC_S3_BUCKET_NAME, Key: imageId, Fields: {
key: imageId, }, Conditions: [ ["starts-with", "$Content-Type", "image/"], ["content-length-range", 0, UPLOAD_MAX_FILE_SIZE], ], }); }), createSection: protectedProcedure .input(z.object({ courseId: z.string(), title: z.string() })) .mutation(async ({ ctx, input }) => { const videoId = uuidv4(); return await ctx.prisma.section.create({ data: { videoId, title: input.title, courseId: input.courseId, }, }); }), deleteSection: protectedProcedure .input(z.object({ sectionId: z.string() })) .mutation(async ({ ctx, input }) => { const section = await ctx.prisma.section.delete({ where: { id: input.sectionId, }, }); if (!section) { throw new TRPCError({ code: "NOT_FOUND", message: "section not found", }); } if (!section.courseId) { throw new TRPCError({ code: "NOT_FOUND", message: "section has no course", }); } const course = await ctx.prisma.course.findUnique({ where: { id: section.courseId, }, }); if (course?.userId !== ctx.session.user.id) { throw new TRPCError({ code: "FORBIDDEN", message: "you do not have access to this course", }); } return section; }), swapSections: protectedProcedure .input( z.object({ sectionIdSource: z.string(), sectionIdTarget: z.string() }) ) .mutation(async ({ ctx, input }) => { const sectionSource = await ctx.prisma.section.findUnique({ where: { id: input.sectionIdSource, }, }); if (!sectionSource) { throw new TRPCError({ code: "NOT_FOUND", message: "the source section does not exist", }); } const sectionTarget = await ctx.prisma.section.findUnique({ where: { id: input.sectionIdTarget, }, }); if (!sectionTarget) { throw new TRPCError({ code: "NOT_FOUND", message: "the target section does not exist", }); } await ctx.prisma.section.update({ where: { id: input.sectionIdSource, }, data: { order: sectionTarget.order, }, }); await ctx.prisma.section.update({ where: { id: input.sectionIdTarget, }, data: { order: sectionSource.order, }, }); }), createPresignedUrlForVideo: protectedProcedure .input(z.object({ sectionId: z.string() })) .mutation(async ({ ctx, input }) => { const section = await ctx.prisma.section.findUnique({ where: { id: input.sectionId, }, }); if (!section) { throw new TRPCError({ code: "NOT_FOUND", message: "the section does not exist", }); } if (!section.courseId) { throw new TRPCError({ code: "NOT_FOUND", message: "the section has no course", }); } const course = await ctx.prisma.course.findUnique({ where: { id: section.courseId, }, }); if (course?.userId !== ctx.session.user.id) { throw new TRPCError({ code: "FORBIDDEN", message: "you do not have access to this course", }); } return createPresignedPost(s3Client, { Bucket: env.NEXT_PUBLIC_S3_BUCKET_NAME, Key: section.videoId, Fields: { key: section.videoId, }, Conditions: [ ["starts-with", "$Content-Type", "image/"], ["content-length-range", 0, UPLOAD_MAX_FILE_SIZE], ], }); }), });
src/server/api/routers/course.ts
webdevcody-online-course-platform-ee963ca
[ { "filename": "src/pages/dashboard/courses/[courseId].tsx", "retrieved_chunk": " const { url, fields } = await getPresignedUrl();\n const data: Record<string, any> = {\n ...fields,\n \"Content-Type\": file.type,\n file,\n };\n const formData = new FormData();\n for (const name in data) {\n formData.append(name, data[name]);\n }", "score": 0.8326336145401001 }, { "filename": "src/pages/dashboard/courses/[courseId].tsx", "retrieved_chunk": " courseId: courseId,\n title: values.title,\n });\n await uploadFileToS3({\n getPresignedUrl: () =>\n createPresignedUrlForVideoMutation.mutateAsync({\n sectionId: section.id,\n }),\n file: newSection,\n });", "score": 0.8298354148864746 }, { "filename": "src/utils/getImageUrl.ts", "retrieved_chunk": "import { env } from \"~/env.mjs\";\nexport function getImageUrl(id: string) {\n return `http://localhost:9000/${env.NEXT_PUBLIC_S3_BUCKET_NAME}/${id}`;\n}", "score": 0.8219946622848511 }, { "filename": "src/pages/dashboard/courses/[courseId].tsx", "retrieved_chunk": " useDisclosure(false);\n const uploadImage = async (e: React.FormEvent<HTMLFormElement>) => {\n e.preventDefault();\n if (!file) return;\n await uploadFileToS3({\n getPresignedUrl: () =>\n createPresignedUrlMutation.mutateAsync({\n courseId,\n }),\n file,", "score": 0.8150529265403748 }, { "filename": "src/pages/dashboard/courses/[courseId].tsx", "retrieved_chunk": "async function uploadFileToS3({\n getPresignedUrl,\n file,\n}: {\n getPresignedUrl: () => Promise<{\n url: string;\n fields: Record<string, string>;\n }>;\n file: File;\n}) {", "score": 0.8059346675872803 } ]
typescript
env.NEXT_PUBLIC_S3_BUCKET_NAME, Key: imageId, Fields: {
/* eslint-disable @typescript-eslint/no-unsafe-argument */ /* eslint-disable @next/next/no-img-element */ import { Button, Group, FileInput, TextInput, Title, Stack, } from "@mantine/core"; import { useForm } from "@mantine/form"; import { useDisclosure } from "@mantine/hooks"; import { IconCheck, IconEdit, IconLetterX } from "@tabler/icons-react"; import { type NextPage } from "next"; import Head from "next/head"; import { useRouter } from "next/router"; import { useState } from "react"; import AdminDashboardLayout from "~/components/layouts/admin-dashboard-layout"; import { api } from "~/utils/api"; import { getImageUrl } from "~/utils/getImageUrl"; async function uploadFileToS3({ getPresignedUrl, file, }: { getPresignedUrl: () => Promise<{ url: string; fields: Record<string, string>; }>; file: File; }) { const { url, fields } = await getPresignedUrl(); const data: Record<string, any> = { ...fields, "Content-Type": file.type, file, }; const formData = new FormData(); for (const name in data) { formData.append(name, data[name]); } await fetch(url, { method: "POST", body: formData, }); } const Courses: NextPage = () => { const router = useRouter(); const courseId = router.query.courseId as string; const updateCourseMutation = api.course.updateCourse.useMutation(); const createSectionMutation = api.course.createSection.useMutation(); const deleteSection = api.course.deleteSection.useMutation(); const swapSections = api.course.swapSections.useMutation(); const createPresignedUrlMutation = api.course.createPresignedUrl.useMutation(); const createPresignedUrlForVideoMutation = api.course.createPresignedUrlForVideo.useMutation(); const updateTitleForm = useForm({ initialValues: { title: "", }, }); const newSectionForm = useForm({ initialValues: { title: "", }, }); const [file, setFile] = useState<File | null>(null); const [newSection, setNewSection] = useState<File | null>(null); const courseQuery = api.course.getCourseById.useQuery( { courseId, }, { enabled: !!courseId, onSuccess(data) { updateTitleForm.setFieldValue("title", data?.title ?? ""); }, } ); const [isEditingTitle, { open: setEditTitle, close: unsetEditTitle }] = useDisclosure(false); const uploadImage = async (e: React.FormEvent<HTMLFormElement>) => { e.preventDefault(); if (!file) return; await uploadFileToS3({ getPresignedUrl: () => createPresignedUrlMutation.mutateAsync({ courseId, }), file, }); setFile(null); await courseQuery.refetch(); // if (fileRef.current) { // fileRef.current.value = ""; // } }; // const onFileChange = (e: React.FormEvent<HTMLInputElement>) => { // setFile(e.currentTarget.files?.[0]); // }; const sortedSections = (courseQuery.data?.sections ?? []).sort( (a, b) => a.order - b.order ); return ( <> <Head> <title>Manage Courses</title> <meta name="description" content="Generated by create-t3-app" /> <link rel="icon" href="/favicon.ico" /> </Head> <main> <AdminDashboardLayout> <Stack spacing={"xl"}> {isEditingTitle ? ( <form onSubmit={updateTitleForm.onSubmit(async (values) => { await updateCourseMutation.mutateAsync({ ...values, courseId, }); await courseQuery.refetch(); unsetEditTitle(); })} > <Group> <TextInput withAsterisk required placeholder="name your course here" {...updateTitleForm.getInputProps("title")} /> <Button color="green" type="submit"> <IconCheck /> </Button> <Button color="gray" onClick={unsetEditTitle}> <IconLetterX /> </Button> </Group> </form> ) : ( <Group> <Title order={1}>{courseQuery.data?.title}</Title> <Button color="gray" onClick={setEditTitle}> <IconEdit size="1rem" /> </Button> </Group> )} <Group> {courseQuery.data && ( <img width="200" alt="an image of the course" src={getImageUrl(courseQuery.data.imageId)} /> )} <Stack sx={{ flex: 1 }}> <form onSubmit={uploadImage}> <FileInput label="Course Image" onChange={setFile} value={file} /> <Button disabled={!file} type="submit" variant="light" color="blue" mt="md" radius="md" > Upload Image </Button> </form> </Stack> </Group> <Stack> <Title order={2}>Sections </Title> {sortedSections
.map((section, idx) => ( <Stack key={section.id}
p="xl" sx={{ border: "1px solid white", }} > <Group> <Title sx={{ flex: 1 }} order={3}> {section.title} </Title> {idx > 0 && ( <Button type="submit" variant="light" color="white" mt="md" radius="md" onClick={async () => { const targetSection = sortedSections[idx - 1]; if (!targetSection) return; await swapSections.mutateAsync({ sectionIdSource: section.id, sectionIdTarget: targetSection.id, }); await courseQuery.refetch(); }} > Move Up </Button> )} {idx < sortedSections.length - 1 && ( <Button type="submit" variant="light" color="white" mt="md" radius="md" onClick={async () => { const targetSection = sortedSections[idx + 1]; if (!targetSection) return; await swapSections.mutateAsync({ sectionIdSource: section.id, sectionIdTarget: targetSection.id, }); await courseQuery.refetch(); }} > Move Down </Button> )} <Button type="submit" variant="light" color="red" mt="md" radius="md" onClick={async () => { if ( !confirm( "are you sure you want to delete this section?" ) ) return; await deleteSection.mutateAsync({ sectionId: section.id, }); await courseQuery.refetch(); }} > Delete </Button> </Group> <video width="400" controls> <source src={`http://localhost:9000/wdc-online-course-platform/${section.videoId}`} type="video/mp4" /> Your browser does not support HTML video. </video> </Stack> ))} <Stack p="xl" sx={{ border: "1px dashed white", }} > <form onSubmit={newSectionForm.onSubmit(async (values) => { if (!newSection) return; const section = await createSectionMutation.mutateAsync({ courseId: courseId, title: values.title, }); await uploadFileToS3({ getPresignedUrl: () => createPresignedUrlForVideoMutation.mutateAsync({ sectionId: section.id, }), file: newSection, }); setNewSection(null); await courseQuery.refetch(); newSectionForm.reset(); })} > <Stack spacing="xl"> <Title order={3}>Create New Section</Title> <TextInput withAsterisk required label="Section Title" placeholder="name your section" {...newSectionForm.getInputProps("title")} /> <FileInput label="Section Video" onChange={setNewSection} required value={newSection} /> <Button type="submit" variant="light" color="blue" mt="md" radius="md" > Create Section </Button> </Stack> </form> </Stack> </Stack> </Stack> </AdminDashboardLayout> </main> </> ); }; export default Courses;
src/pages/dashboard/courses/[courseId].tsx
webdevcody-online-course-platform-ee963ca
[ { "filename": "src/pages/dashboard/courses/index.tsx", "retrieved_chunk": " </Stack>\n <Group position=\"right\" mt=\"md\">\n <Button type=\"submit\">Create Course</Button>\n </Group>\n </form>\n </Modal>\n <main>\n <AdminDashboardLayout>\n <Flex justify=\"space-between\" align=\"center\" direction=\"row\">\n <h1>Manage Courses</h1>", "score": 0.8117416501045227 }, { "filename": "src/components/shell/_main-links.tsx", "retrieved_chunk": " >\n <Group>\n <ThemeIcon color={link.color} variant=\"light\">\n {link.icon}\n </ThemeIcon>\n <Text size=\"sm\">{link.label}</Text>\n </Group>\n </UnstyledButton>\n ))}\n </>", "score": 0.7980859279632568 }, { "filename": "src/pages/dashboard/courses/index.tsx", "retrieved_chunk": " <Button onClick={openCreateCourseModal}>Create Course</Button>\n </Flex>\n <Grid>\n {courses.data?.map((course) => (\n <Grid.Col key={course.id} span={4}>\n <CourseCard course={course} />\n </Grid.Col>\n ))}\n </Grid>\n </AdminDashboardLayout>", "score": 0.794085681438446 }, { "filename": "src/pages/dashboard/courses/index.tsx", "retrieved_chunk": " createCourseForm.reset();\n await courses.refetch();\n })}\n >\n <Stack>\n <TextInput\n withAsterisk\n label=\"Title\"\n required\n placeholder=\"name your course here\"", "score": 0.7926517724990845 }, { "filename": "src/components/shell/_user.tsx", "retrieved_chunk": " </Group>\n </Menu.Target>\n <Menu.Dropdown>\n <Menu.Item\n onClick={() => signOut()}\n icon={<IconPower size={14} />}\n >\n Sign Out\n </Menu.Item>\n </Menu.Dropdown>", "score": 0.7889552116394043 } ]
typescript
.map((section, idx) => ( <Stack key={section.id}
/* eslint-disable @typescript-eslint/no-unsafe-argument */ /* eslint-disable @next/next/no-img-element */ import { Button, Group, FileInput, TextInput, Title, Stack, } from "@mantine/core"; import { useForm } from "@mantine/form"; import { useDisclosure } from "@mantine/hooks"; import { IconCheck, IconEdit, IconLetterX } from "@tabler/icons-react"; import { type NextPage } from "next"; import Head from "next/head"; import { useRouter } from "next/router"; import { useState } from "react"; import AdminDashboardLayout from "~/components/layouts/admin-dashboard-layout"; import { api } from "~/utils/api"; import { getImageUrl } from "~/utils/getImageUrl"; async function uploadFileToS3({ getPresignedUrl, file, }: { getPresignedUrl: () => Promise<{ url: string; fields: Record<string, string>; }>; file: File; }) { const { url, fields } = await getPresignedUrl(); const data: Record<string, any> = { ...fields, "Content-Type": file.type, file, }; const formData = new FormData(); for (const name in data) { formData.append(name, data[name]); } await fetch(url, { method: "POST", body: formData, }); } const Courses: NextPage = () => { const router = useRouter(); const courseId = router.query.courseId as string; const updateCourseMutation = api.course.updateCourse.useMutation(); const createSectionMutation = api.course.createSection.useMutation(); const deleteSection = api.course.deleteSection.useMutation(); const swapSections = api.course.swapSections.useMutation(); const createPresignedUrlMutation = api.course.createPresignedUrl.useMutation(); const createPresignedUrlForVideoMutation = api.course.createPresignedUrlForVideo.useMutation(); const updateTitleForm = useForm({ initialValues: { title: "", }, }); const newSectionForm = useForm({ initialValues: { title: "", }, }); const [file, setFile] = useState<File | null>(null); const [newSection, setNewSection] = useState<File | null>(null); const courseQuery = api.course.getCourseById.useQuery( { courseId, }, { enabled: !!courseId, onSuccess(data) { updateTitleForm.setFieldValue("title", data?.title ?? ""); }, } ); const [isEditingTitle, { open: setEditTitle, close: unsetEditTitle }] = useDisclosure(false); const uploadImage = async (e: React.FormEvent<HTMLFormElement>) => { e.preventDefault(); if (!file) return; await uploadFileToS3({ getPresignedUrl: () => createPresignedUrlMutation.mutateAsync({ courseId, }), file, }); setFile(null); await courseQuery.refetch(); // if (fileRef.current) { // fileRef.current.value = ""; // } }; // const onFileChange = (e: React.FormEvent<HTMLInputElement>) => { // setFile(e.currentTarget.files?.[0]); // }; const sortedSections = (courseQuery.data?.sections ?? []).sort( (a, b) => a.order - b.order ); return ( <> <Head> <title>Manage Courses</title> <meta name="description" content="Generated by create-t3-app" /> <link rel="icon" href="/favicon.ico" /> </Head> <main> <AdminDashboardLayout> <Stack spacing={"xl"}> {isEditingTitle ? ( <form onSubmit={updateTitleForm.onSubmit(async (values) => { await updateCourseMutation.mutateAsync({ ...values, courseId, }); await courseQuery.refetch(); unsetEditTitle(); })} > <Group> <TextInput withAsterisk required placeholder="name your course here" {...updateTitleForm.getInputProps("title")} /> <Button color="green" type="submit"> <IconCheck /> </Button> <Button color="gray" onClick={unsetEditTitle}> <IconLetterX /> </Button> </Group> </form> ) : ( <Group> <Title order={1}>{courseQuery.data?.title}</Title> <Button color="gray" onClick={setEditTitle}> <IconEdit size="1rem" /> </Button> </Group> )} <Group> {courseQuery.data && ( <img width="200" alt="an image of the course" src
={getImageUrl(courseQuery.data.imageId)}
/> )} <Stack sx={{ flex: 1 }}> <form onSubmit={uploadImage}> <FileInput label="Course Image" onChange={setFile} value={file} /> <Button disabled={!file} type="submit" variant="light" color="blue" mt="md" radius="md" > Upload Image </Button> </form> </Stack> </Group> <Stack> <Title order={2}>Sections </Title> {sortedSections.map((section, idx) => ( <Stack key={section.id} p="xl" sx={{ border: "1px solid white", }} > <Group> <Title sx={{ flex: 1 }} order={3}> {section.title} </Title> {idx > 0 && ( <Button type="submit" variant="light" color="white" mt="md" radius="md" onClick={async () => { const targetSection = sortedSections[idx - 1]; if (!targetSection) return; await swapSections.mutateAsync({ sectionIdSource: section.id, sectionIdTarget: targetSection.id, }); await courseQuery.refetch(); }} > Move Up </Button> )} {idx < sortedSections.length - 1 && ( <Button type="submit" variant="light" color="white" mt="md" radius="md" onClick={async () => { const targetSection = sortedSections[idx + 1]; if (!targetSection) return; await swapSections.mutateAsync({ sectionIdSource: section.id, sectionIdTarget: targetSection.id, }); await courseQuery.refetch(); }} > Move Down </Button> )} <Button type="submit" variant="light" color="red" mt="md" radius="md" onClick={async () => { if ( !confirm( "are you sure you want to delete this section?" ) ) return; await deleteSection.mutateAsync({ sectionId: section.id, }); await courseQuery.refetch(); }} > Delete </Button> </Group> <video width="400" controls> <source src={`http://localhost:9000/wdc-online-course-platform/${section.videoId}`} type="video/mp4" /> Your browser does not support HTML video. </video> </Stack> ))} <Stack p="xl" sx={{ border: "1px dashed white", }} > <form onSubmit={newSectionForm.onSubmit(async (values) => { if (!newSection) return; const section = await createSectionMutation.mutateAsync({ courseId: courseId, title: values.title, }); await uploadFileToS3({ getPresignedUrl: () => createPresignedUrlForVideoMutation.mutateAsync({ sectionId: section.id, }), file: newSection, }); setNewSection(null); await courseQuery.refetch(); newSectionForm.reset(); })} > <Stack spacing="xl"> <Title order={3}>Create New Section</Title> <TextInput withAsterisk required label="Section Title" placeholder="name your section" {...newSectionForm.getInputProps("title")} /> <FileInput label="Section Video" onChange={setNewSection} required value={newSection} /> <Button type="submit" variant="light" color="blue" mt="md" radius="md" > Create Section </Button> </Stack> </form> </Stack> </Stack> </Stack> </AdminDashboardLayout> </main> </> ); }; export default Courses;
src/pages/dashboard/courses/[courseId].tsx
webdevcody-online-course-platform-ee963ca
[ { "filename": "src/pages/dashboard/courses/index.tsx", "retrieved_chunk": "import Link from \"next/link\";\nimport { getImageUrl } from \"~/utils/getImageUrl\";\nexport function CourseCard({ course }: { course: Course }) {\n return (\n <MantineCard shadow=\"sm\" padding=\"lg\" radius=\"md\" withBorder>\n <MantineCard.Section>\n <Image src={getImageUrl(course.imageId)} height={160} alt=\"Norway\" />\n </MantineCard.Section>\n <Group position=\"apart\" mt=\"md\" mb=\"xs\">\n <Text weight={500}>{course.title}</Text>", "score": 0.8594756126403809 }, { "filename": "src/pages/dashboard/courses/index.tsx", "retrieved_chunk": " {/* <Badge color=\"pink\" variant=\"light\">\n On Sale\n </Badge> */}\n </Group>\n <Text size=\"sm\" color=\"dimmed\">\n {course.description}\n </Text>\n <Button\n component={Link}\n href={`/dashboard/courses/${course.id}`}", "score": 0.8583327531814575 }, { "filename": "src/pages/dashboard/courses/index.tsx", "retrieved_chunk": " <Button onClick={openCreateCourseModal}>Create Course</Button>\n </Flex>\n <Grid>\n {courses.data?.map((course) => (\n <Grid.Col key={course.id} span={4}>\n <CourseCard course={course} />\n </Grid.Col>\n ))}\n </Grid>\n </AdminDashboardLayout>", "score": 0.8486855030059814 }, { "filename": "src/pages/dashboard/courses/index.tsx", "retrieved_chunk": " </Stack>\n <Group position=\"right\" mt=\"md\">\n <Button type=\"submit\">Create Course</Button>\n </Group>\n </form>\n </Modal>\n <main>\n <AdminDashboardLayout>\n <Flex justify=\"space-between\" align=\"center\" direction=\"row\">\n <h1>Manage Courses</h1>", "score": 0.8337804079055786 }, { "filename": "src/pages/dashboard/courses/index.tsx", "retrieved_chunk": " createCourseForm.reset();\n await courses.refetch();\n })}\n >\n <Stack>\n <TextInput\n withAsterisk\n label=\"Title\"\n required\n placeholder=\"name your course here\"", "score": 0.8302221298217773 } ]
typescript
={getImageUrl(courseQuery.data.imageId)}
/* eslint-disable @typescript-eslint/no-unsafe-argument */ /* eslint-disable @next/next/no-img-element */ import { Button, Group, FileInput, TextInput, Title, Stack, } from "@mantine/core"; import { useForm } from "@mantine/form"; import { useDisclosure } from "@mantine/hooks"; import { IconCheck, IconEdit, IconLetterX } from "@tabler/icons-react"; import { type NextPage } from "next"; import Head from "next/head"; import { useRouter } from "next/router"; import { useState } from "react"; import AdminDashboardLayout from "~/components/layouts/admin-dashboard-layout"; import { api } from "~/utils/api"; import { getImageUrl } from "~/utils/getImageUrl"; async function uploadFileToS3({ getPresignedUrl, file, }: { getPresignedUrl: () => Promise<{ url: string; fields: Record<string, string>; }>; file: File; }) { const { url, fields } = await getPresignedUrl(); const data: Record<string, any> = { ...fields, "Content-Type": file.type, file, }; const formData = new FormData(); for (const name in data) { formData.append(name, data[name]); } await fetch(url, { method: "POST", body: formData, }); } const Courses: NextPage = () => { const router = useRouter(); const courseId = router.query.courseId as string; const updateCourseMutation
= api.course.updateCourse.useMutation();
const createSectionMutation = api.course.createSection.useMutation(); const deleteSection = api.course.deleteSection.useMutation(); const swapSections = api.course.swapSections.useMutation(); const createPresignedUrlMutation = api.course.createPresignedUrl.useMutation(); const createPresignedUrlForVideoMutation = api.course.createPresignedUrlForVideo.useMutation(); const updateTitleForm = useForm({ initialValues: { title: "", }, }); const newSectionForm = useForm({ initialValues: { title: "", }, }); const [file, setFile] = useState<File | null>(null); const [newSection, setNewSection] = useState<File | null>(null); const courseQuery = api.course.getCourseById.useQuery( { courseId, }, { enabled: !!courseId, onSuccess(data) { updateTitleForm.setFieldValue("title", data?.title ?? ""); }, } ); const [isEditingTitle, { open: setEditTitle, close: unsetEditTitle }] = useDisclosure(false); const uploadImage = async (e: React.FormEvent<HTMLFormElement>) => { e.preventDefault(); if (!file) return; await uploadFileToS3({ getPresignedUrl: () => createPresignedUrlMutation.mutateAsync({ courseId, }), file, }); setFile(null); await courseQuery.refetch(); // if (fileRef.current) { // fileRef.current.value = ""; // } }; // const onFileChange = (e: React.FormEvent<HTMLInputElement>) => { // setFile(e.currentTarget.files?.[0]); // }; const sortedSections = (courseQuery.data?.sections ?? []).sort( (a, b) => a.order - b.order ); return ( <> <Head> <title>Manage Courses</title> <meta name="description" content="Generated by create-t3-app" /> <link rel="icon" href="/favicon.ico" /> </Head> <main> <AdminDashboardLayout> <Stack spacing={"xl"}> {isEditingTitle ? ( <form onSubmit={updateTitleForm.onSubmit(async (values) => { await updateCourseMutation.mutateAsync({ ...values, courseId, }); await courseQuery.refetch(); unsetEditTitle(); })} > <Group> <TextInput withAsterisk required placeholder="name your course here" {...updateTitleForm.getInputProps("title")} /> <Button color="green" type="submit"> <IconCheck /> </Button> <Button color="gray" onClick={unsetEditTitle}> <IconLetterX /> </Button> </Group> </form> ) : ( <Group> <Title order={1}>{courseQuery.data?.title}</Title> <Button color="gray" onClick={setEditTitle}> <IconEdit size="1rem" /> </Button> </Group> )} <Group> {courseQuery.data && ( <img width="200" alt="an image of the course" src={getImageUrl(courseQuery.data.imageId)} /> )} <Stack sx={{ flex: 1 }}> <form onSubmit={uploadImage}> <FileInput label="Course Image" onChange={setFile} value={file} /> <Button disabled={!file} type="submit" variant="light" color="blue" mt="md" radius="md" > Upload Image </Button> </form> </Stack> </Group> <Stack> <Title order={2}>Sections </Title> {sortedSections.map((section, idx) => ( <Stack key={section.id} p="xl" sx={{ border: "1px solid white", }} > <Group> <Title sx={{ flex: 1 }} order={3}> {section.title} </Title> {idx > 0 && ( <Button type="submit" variant="light" color="white" mt="md" radius="md" onClick={async () => { const targetSection = sortedSections[idx - 1]; if (!targetSection) return; await swapSections.mutateAsync({ sectionIdSource: section.id, sectionIdTarget: targetSection.id, }); await courseQuery.refetch(); }} > Move Up </Button> )} {idx < sortedSections.length - 1 && ( <Button type="submit" variant="light" color="white" mt="md" radius="md" onClick={async () => { const targetSection = sortedSections[idx + 1]; if (!targetSection) return; await swapSections.mutateAsync({ sectionIdSource: section.id, sectionIdTarget: targetSection.id, }); await courseQuery.refetch(); }} > Move Down </Button> )} <Button type="submit" variant="light" color="red" mt="md" radius="md" onClick={async () => { if ( !confirm( "are you sure you want to delete this section?" ) ) return; await deleteSection.mutateAsync({ sectionId: section.id, }); await courseQuery.refetch(); }} > Delete </Button> </Group> <video width="400" controls> <source src={`http://localhost:9000/wdc-online-course-platform/${section.videoId}`} type="video/mp4" /> Your browser does not support HTML video. </video> </Stack> ))} <Stack p="xl" sx={{ border: "1px dashed white", }} > <form onSubmit={newSectionForm.onSubmit(async (values) => { if (!newSection) return; const section = await createSectionMutation.mutateAsync({ courseId: courseId, title: values.title, }); await uploadFileToS3({ getPresignedUrl: () => createPresignedUrlForVideoMutation.mutateAsync({ sectionId: section.id, }), file: newSection, }); setNewSection(null); await courseQuery.refetch(); newSectionForm.reset(); })} > <Stack spacing="xl"> <Title order={3}>Create New Section</Title> <TextInput withAsterisk required label="Section Title" placeholder="name your section" {...newSectionForm.getInputProps("title")} /> <FileInput label="Section Video" onChange={setNewSection} required value={newSection} /> <Button type="submit" variant="light" color="blue" mt="md" radius="md" > Create Section </Button> </Stack> </form> </Stack> </Stack> </Stack> </AdminDashboardLayout> </main> </> ); }; export default Courses;
src/pages/dashboard/courses/[courseId].tsx
webdevcody-online-course-platform-ee963ca
[ { "filename": "src/pages/dashboard/courses/index.tsx", "retrieved_chunk": "}\nconst Courses: NextPage = () => {\n const courses = api.course.getCourses.useQuery();\n const createCourseMutation = api.course.createCourse.useMutation();\n const [\n isCreateCourseModalOpen,\n { open: openCreateCourseModal, close: closeCreateCourseModal },\n ] = useDisclosure(false);\n const createCourseForm = useForm({\n initialValues: {", "score": 0.9202366471290588 }, { "filename": "src/pages/dashboard/courses/index.tsx", "retrieved_chunk": "import { type Course } from \"@prisma/client\";\nimport { type NextPage } from \"next\";\nimport Head from \"next/head\";\nimport { useForm } from \"@mantine/form\";\nimport AdminDashboardLayout from \"~/components/layouts/admin-dashboard-layout\";\nimport {\n Card as MantineCard,\n Image,\n Text,\n Flex,", "score": 0.8677759170532227 }, { "filename": "src/pages/dashboard/courses/index.tsx", "retrieved_chunk": " </Head>\n <Modal\n opened={isCreateCourseModalOpen}\n onClose={closeCreateCourseModal}\n title=\"Create Course\"\n >\n <form\n onSubmit={createCourseForm.onSubmit(async (values) => {\n await createCourseMutation.mutateAsync(values);\n closeCreateCourseModal();", "score": 0.8650331497192383 }, { "filename": "src/pages/dashboard/courses/index.tsx", "retrieved_chunk": " </main>\n </>\n );\n};\nexport default Courses;", "score": 0.8368046283721924 }, { "filename": "src/pages/dashboard/courses/index.tsx", "retrieved_chunk": " <Button onClick={openCreateCourseModal}>Create Course</Button>\n </Flex>\n <Grid>\n {courses.data?.map((course) => (\n <Grid.Col key={course.id} span={4}>\n <CourseCard course={course} />\n </Grid.Col>\n ))}\n </Grid>\n </AdminDashboardLayout>", "score": 0.8311731219291687 } ]
typescript
= api.course.updateCourse.useMutation();
import { SlackAppEnv, SlackEdgeAppEnv, SlackSocketModeAppEnv } from "./app-env"; import { parseRequestBody } from "./request/request-parser"; import { verifySlackRequest } from "./request/request-verification"; import { AckResponse, SlackHandler } from "./handler/handler"; import { SlackRequestBody } from "./request/request-body"; import { PreAuthorizeSlackMiddlwareRequest, SlackRequestWithRespond, SlackMiddlwareRequest, SlackRequestWithOptionalRespond, SlackRequest, SlackRequestWithChannelId, } from "./request/request"; import { SlashCommand } from "./request/payload/slash-command"; import { toCompleteResponse } from "./response/response"; import { SlackEvent, AnySlackEvent, AnySlackEventWithChannelId, } from "./request/payload/event"; import { ResponseUrlSender, SlackAPIClient } from "slack-web-api-client"; import { builtBaseContext, SlackAppContext, SlackAppContextWithChannelId, SlackAppContextWithRespond, } from "./context/context"; import { PreAuthorizeMiddleware, Middleware } from "./middleware/middleware"; import { isDebugLogEnabled, prettyPrint } from "slack-web-api-client"; import { Authorize } from "./authorization/authorize"; import { AuthorizeResult } from "./authorization/authorize-result"; import { ignoringSelfEvents, urlVerification, } from "./middleware/built-in-middleware"; import { ConfigError } from "./errors"; import { GlobalShortcut } from "./request/payload/global-shortcut"; import { MessageShortcut } from "./request/payload/message-shortcut"; import { BlockAction, BlockElementAction, BlockElementTypes, } from "./request/payload/block-action"; import { ViewSubmission } from "./request/payload/view-submission"; import { ViewClosed } from "./request/payload/view-closed"; import { BlockSuggestion } from "./request/payload/block-suggestion"; import { OptionsAckResponse, SlackOptionsHandler, } from "./handler/options-handler"; import { SlackViewHandler, ViewAckResponse } from "./handler/view-handler"; import { MessageAckResponse, SlackMessageHandler, } from "./handler/message-handler"; import { singleTeamAuthorize } from "./authorization/single-team-authorize"; import { ExecutionContext, NoopExecutionContext } from "./execution-context"; import { PayloadType } from "./request/payload-types"; import { isPostedMessageEvent } from "./utility/message-events"; import { SocketModeClient } from "./socket-mode/socket-mode-client"; export interface SlackAppOptions< E extends SlackEdgeAppEnv | SlackSocketModeAppEnv > { env: E; authorize?: Authorize<E>; routes?: { events: string; }; socketMode?: boolean; } export class SlackApp<E extends SlackEdgeAppEnv | SlackSocketModeAppEnv> { public env: E; public client: SlackAPIClient; public authorize: Authorize<E>; public routes: { events: string | undefined }; public signingSecret: string; public appLevelToken: string | undefined; public socketMode: boolean; public socketModeClient: SocketModeClient | undefined; // deno-lint-ignore no-explicit-any public preAuthorizeMiddleware: PreAuthorizeMiddleware<any>[] = [ urlVerification, ]; // deno-lint-ignore no-explicit-any public postAuthorizeMiddleware: Middleware<any>[] = [ignoringSelfEvents]; #slashCommands: (( body: SlackRequestBody ) => SlackMessageHandler<E, SlashCommand> | null)[] = []; #events: (( body: SlackRequestBody ) => SlackHandler<E, SlackEvent<string>> | null)[] = []; #globalShorcuts: (( body: SlackRequestBody ) => SlackHandler<E, GlobalShortcut> | null)[] = []; #messageShorcuts: (( body: SlackRequestBody ) => SlackHandler<E, MessageShortcut> | null)[] = []; #blockActions: ((body: SlackRequestBody) => SlackHandler< E, // deno-lint-ignore no-explicit-any BlockAction<any> > | null)[] = []; #blockSuggestions: (( body: SlackRequestBody ) => SlackOptionsHandler<E, BlockSuggestion> | null)[] = []; #viewSubmissions: (( body: SlackRequestBody ) => SlackViewHandler<E, ViewSubmission> | null)[] = []; #viewClosed: (( body: SlackRequestBody ) => SlackViewHandler<E, ViewClosed> | null)[] = []; constructor(options: SlackAppOptions<E>) { if ( options.env.SLACK_BOT_TOKEN === undefined && (options.authorize === undefined || options.authorize === singleTeamAuthorize) ) { throw new ConfigError( "When you don't pass env.SLACK_BOT_TOKEN, your own authorize function, which supplies a valid token to use, needs to be passed instead." ); } this.env = options.env; this.client = new SlackAPIClient(options.env.SLACK_BOT_TOKEN, { logLevel: this.env.SLACK_LOGGING_LEVEL, }); this.appLevelToken = options.env.SLACK_APP_TOKEN; this.socketMode = options.socketMode ?? this.appLevelToken !== undefined; if (this.socketMode) { this.signingSecret = ""; } else { if (!this.env.SLACK_SIGNING_SECRET) { throw new ConfigError( "env.SLACK_SIGNING_SECRET is required to run your app on edge functions!" ); } this.signingSecret = this.env.SLACK_SIGNING_SECRET; } this.authorize = options.authorize ?? singleTeamAuthorize; this.routes = { events: options.routes?.events }; } beforeAuthorize(middleware: PreAuthorizeMiddleware<E>): SlackApp<E> { this.preAuthorizeMiddleware.push(middleware); return this; } middleware(middleware: Middleware<E>): SlackApp<E> { return this.afterAuthorize(middleware); } use(middleware: Middleware<E>): SlackApp<E> { return this.afterAuthorize(middleware); } afterAuthorize(middleware: Middleware<E>): SlackApp<E> { this.postAuthorizeMiddleware.push(middleware); return this; } command( pattern: StringOrRegExp, ack: ( req: SlackRequestWithRespond<E, SlashCommand> ) => Promise<MessageAckResponse>, lazy: ( req: SlackRequestWithRespond<E, SlashCommand> ) => Promise<void> = noopLazyListener ): SlackApp<E> { const handler: SlackMessageHandler<E, SlashCommand> = { ack, lazy }; this.#slashCommands.push((body) => { if (body.type || !body.command) { return null; } if (typeof pattern === "string" && body.command === pattern) { return handler; } else if ( typeof pattern === "object" && pattern instanceof RegExp && body.command.match(pattern) ) { return handler; } return null; }); return this; } event<Type extends string>( event: Type, lazy: (req: EventRequest<E, Type>) => Promise<void> ): SlackApp<E> { this.#events.push((body) => { if (body.type !== PayloadType.EventsAPI || !body.event) { return null; } if (body.event.type === event) { // deno-lint-ignore require-await return { ack: async () => "", lazy }; } return null; }); return this; } anyMessage(lazy: MessageEventHandler<E>): SlackApp<E> { return this.message(undefined, lazy); } message( pattern: MessageEventPattern, lazy: MessageEventHandler<E> ): SlackApp<E> { this.#events.push((body) => { if ( body.type !== PayloadType.EventsAPI || !body.event || body.event.type !== "message" ) { return null; } if (isPostedMessageEvent(body.event)) { let matched = true; if (pattern !== undefined) { if (typeof pattern === "string") { matched = body.event.text!.includes(pattern); } if (typeof pattern === "object") { matched = body.event.text!.match(pattern) !== null; } } if (matched) { // deno-lint-ignore require-await return { ack: async (_: EventRequest<E, "message">) => "", lazy }; } } return null; }); return this; } shortcut( callbackId: StringOrRegExp, ack: ( req: | SlackRequest<E, GlobalShortcut> | SlackRequestWithRespond<E, MessageShortcut> ) => Promise<AckResponse>, lazy: ( req: | SlackRequest<E, GlobalShortcut> | SlackRequestWithRespond<E, MessageShortcut> ) => Promise<void> = noopLazyListener ): SlackApp<E> { return this.globalShortcut(callbackId, ack, lazy).messageShortcut( callbackId, ack, lazy ); } globalShortcut( callbackId: StringOrRegExp, ack: (req: SlackRequest<E, GlobalShortcut>) => Promise<AckResponse>, lazy: ( req: SlackRequest<E, GlobalShortcut> ) => Promise<void> = noopLazyListener ): SlackApp<E> { const handler: SlackHandler<E, GlobalShortcut> = { ack, lazy }; this.#globalShorcuts.push((body) => { if (body.type !== PayloadType.GlobalShortcut || !body.callback_id) { return null; } if (typeof callbackId === "string" && body.callback_id === callbackId) { return handler; } else if ( typeof callbackId === "object" && callbackId instanceof RegExp && body.callback_id.match(callbackId) ) { return handler; } return null; }); return this; } messageShortcut( callbackId: StringOrRegExp, ack: ( req: SlackRequestWithRespond<E, MessageShortcut> ) => Promise<AckResponse>, lazy: ( req: SlackRequestWithRespond<E, MessageShortcut> ) => Promise<void> = noopLazyListener ): SlackApp<E> { const handler: SlackHandler<E, MessageShortcut> = { ack, lazy }; this.#messageShorcuts.push((body) => { if (body.type !== PayloadType.MessageShortcut || !body.callback_id) { return null; } if (typeof callbackId === "string" && body.callback_id === callbackId) { return handler; } else if ( typeof callbackId === "object" && callbackId instanceof RegExp && body.callback_id.match(callbackId) ) { return handler; } return null; }); return this; } action< T extends BlockElementTypes, A extends BlockAction<BlockElementAction<T>> = BlockAction< BlockElementAction<T> > >( constraints: | StringOrRegExp | { type: T; block_id?: string; action_id: string }, ack: (req: SlackRequestWithOptionalRespond<E, A>) => Promise<AckResponse>, lazy: ( req: SlackRequestWithOptionalRespond<E, A> ) => Promise<void> = noopLazyListener ): SlackApp<E> { const handler: SlackHandler<E, A> = { ack, lazy }; this.#blockActions.push((body) => { if ( body.type !== PayloadType.BlockAction || !
body.actions || !body.actions[0] ) {
return null; } const action = body.actions[0]; if (typeof constraints === "string" && action.action_id === constraints) { return handler; } else if (typeof constraints === "object") { if (constraints instanceof RegExp) { if (action.action_id.match(constraints)) { return handler; } } else if (constraints.type) { if (action.type === constraints.type) { if (action.action_id === constraints.action_id) { if ( constraints.block_id && action.block_id !== constraints.block_id ) { return null; } return handler; } } } } return null; }); return this; } options( constraints: StringOrRegExp | { block_id?: string; action_id: string }, ack: (req: SlackRequest<E, BlockSuggestion>) => Promise<OptionsAckResponse> ): SlackApp<E> { // Note that block_suggestion response must be done within 3 seconds. // So, we don't support the lazy handler for it. const handler: SlackOptionsHandler<E, BlockSuggestion> = { ack }; this.#blockSuggestions.push((body) => { if (body.type !== PayloadType.BlockSuggestion || !body.action_id) { return null; } if (typeof constraints === "string" && body.action_id === constraints) { return handler; } else if (typeof constraints === "object") { if (constraints instanceof RegExp) { if (body.action_id.match(constraints)) { return handler; } } else { if (body.action_id === constraints.action_id) { if (body.block_id && body.block_id !== constraints.block_id) { return null; } return handler; } } } return null; }); return this; } view( callbackId: StringOrRegExp, ack: ( req: | SlackRequestWithOptionalRespond<E, ViewSubmission> | SlackRequest<E, ViewClosed> ) => Promise<ViewAckResponse>, lazy: ( req: | SlackRequestWithOptionalRespond<E, ViewSubmission> | SlackRequest<E, ViewClosed> ) => Promise<void> = noopLazyListener ): SlackApp<E> { return this.viewSubmission(callbackId, ack, lazy).viewClosed( callbackId, ack, lazy ); } viewSubmission( callbackId: StringOrRegExp, ack: ( req: SlackRequestWithOptionalRespond<E, ViewSubmission> ) => Promise<ViewAckResponse>, lazy: ( req: SlackRequestWithOptionalRespond<E, ViewSubmission> ) => Promise<void> = noopLazyListener ): SlackApp<E> { const handler: SlackViewHandler<E, ViewSubmission> = { ack, lazy }; this.#viewSubmissions.push((body) => { if (body.type !== PayloadType.ViewSubmission || !body.view) { return null; } if ( typeof callbackId === "string" && body.view.callback_id === callbackId ) { return handler; } else if ( typeof callbackId === "object" && callbackId instanceof RegExp && body.view.callback_id.match(callbackId) ) { return handler; } return null; }); return this; } viewClosed( callbackId: StringOrRegExp, ack: (req: SlackRequest<E, ViewClosed>) => Promise<ViewAckResponse>, lazy: (req: SlackRequest<E, ViewClosed>) => Promise<void> = noopLazyListener ): SlackApp<E> { const handler: SlackViewHandler<E, ViewClosed> = { ack, lazy }; this.#viewClosed.push((body) => { if (body.type !== PayloadType.ViewClosed || !body.view) { return null; } if ( typeof callbackId === "string" && body.view.callback_id === callbackId ) { return handler; } else if ( typeof callbackId === "object" && callbackId instanceof RegExp && body.view.callback_id.match(callbackId) ) { return handler; } return null; }); return this; } async run( request: Request, ctx: ExecutionContext = new NoopExecutionContext() ): Promise<Response> { return await this.handleEventRequest(request, ctx); } async connect(): Promise<void> { if (!this.socketMode) { throw new ConfigError( "Both env.SLACK_APP_TOKEN and socketMode: true are required to start a Socket Mode connection!" ); } this.socketModeClient = new SocketModeClient(this); await this.socketModeClient.connect(); } async disconnect(): Promise<void> { if (this.socketModeClient) { await this.socketModeClient.disconnect(); } } async handleEventRequest( request: Request, ctx: ExecutionContext ): Promise<Response> { // If the routes.events is missing, any URLs can work for handing requests from Slack if (this.routes.events) { const { pathname } = new URL(request.url); if (pathname !== this.routes.events) { return new Response("Not found", { status: 404 }); } } // To avoid the following warning by Cloudflware, parse the body as Blob first // Called .text() on an HTTP body which does not appear to be text .. const blobRequestBody = await request.blob(); // We can safely assume the incoming request body is always text data const rawBody: string = await blobRequestBody.text(); // For Request URL verification if (rawBody.includes("ssl_check=")) { // Slack does not send the x-slack-signature header for this pattern. // Thus, we need to check the pattern before verifying a request. const bodyParams = new URLSearchParams(rawBody); if (bodyParams.get("ssl_check") === "1" && bodyParams.get("token")) { return new Response("", { status: 200 }); } } // Verify the request headers and body const isRequestSignatureVerified = this.socketMode || (await verifySlackRequest(this.signingSecret, request.headers, rawBody)); if (isRequestSignatureVerified) { // deno-lint-ignore no-explicit-any const body: Record<string, any> = await parseRequestBody( request.headers, rawBody ); let retryNum: number | undefined = undefined; try { const retryNumHeader = request.headers.get("x-slack-retry-num"); if (retryNumHeader) { retryNum = Number.parseInt(retryNumHeader); } else if (this.socketMode && body.retry_attempt) { retryNum = Number.parseInt(body.retry_attempt); } // deno-lint-ignore no-unused-vars } catch (e) { // Ignore an exception here } const retryReason = request.headers.get("x-slack-retry-reason") ?? body.retry_reason; const preAuthorizeRequest: PreAuthorizeSlackMiddlwareRequest<E> = { body, rawBody, retryNum, retryReason, context: builtBaseContext(body), env: this.env, headers: request.headers, }; if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log(`*** Received request body ***\n ${prettyPrint(body)}`); } for (const middlware of this.preAuthorizeMiddleware) { const response = await middlware(preAuthorizeRequest); if (response) { return toCompleteResponse(response); } } const authorizeResult: AuthorizeResult = await this.authorize( preAuthorizeRequest ); const authorizedContext: SlackAppContext = { ...preAuthorizeRequest.context, authorizeResult, client: new SlackAPIClient(authorizeResult.botToken, { logLevel: this.env.SLACK_LOGGING_LEVEL, }), botToken: authorizeResult.botToken, botId: authorizeResult.botId, botUserId: authorizeResult.botUserId, userToken: authorizeResult.userToken, }; if (authorizedContext.channelId) { const context = authorizedContext as SlackAppContextWithChannelId; const client = new SlackAPIClient(context.botToken); context.say = async (params) => await client.chat.postMessage({ channel: context.channelId, ...params, }); } if (authorizedContext.responseUrl) { const responseUrl = authorizedContext.responseUrl; // deno-lint-ignore require-await (authorizedContext as SlackAppContextWithRespond).respond = async ( params ) => { return new ResponseUrlSender(responseUrl).call(params); }; } const baseRequest: SlackMiddlwareRequest<E> = { ...preAuthorizeRequest, context: authorizedContext, }; for (const middlware of this.postAuthorizeMiddleware) { const response = await middlware(baseRequest); if (response) { return toCompleteResponse(response); } } const payload = body as SlackRequestBody; if (body.type === PayloadType.EventsAPI) { // Events API const slackRequest: SlackRequest<E, SlackEvent<string>> = { payload: body.event, ...baseRequest, }; for (const matcher of this.#events) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (!body.type && body.command) { // Slash commands const slackRequest: SlackRequest<E, SlashCommand> = { payload: body as SlashCommand, ...baseRequest, }; for (const matcher of this.#slashCommands) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (body.type === PayloadType.GlobalShortcut) { // Global shortcuts const slackRequest: SlackRequest<E, GlobalShortcut> = { payload: body as GlobalShortcut, ...baseRequest, }; for (const matcher of this.#globalShorcuts) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (body.type === PayloadType.MessageShortcut) { // Message shortcuts const slackRequest: SlackRequest<E, MessageShortcut> = { payload: body as MessageShortcut, ...baseRequest, }; for (const matcher of this.#messageShorcuts) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (body.type === PayloadType.BlockAction) { // Block actions // deno-lint-ignore no-explicit-any const slackRequest: SlackRequest<E, BlockAction<any>> = { // deno-lint-ignore no-explicit-any payload: body as BlockAction<any>, ...baseRequest, }; for (const matcher of this.#blockActions) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (body.type === PayloadType.BlockSuggestion) { // Block suggestions const slackRequest: SlackRequest<E, BlockSuggestion> = { payload: body as BlockSuggestion, ...baseRequest, }; for (const matcher of this.#blockSuggestions) { const handler = matcher(payload); if (handler) { // Note that the only way to respond to a block_suggestion request // is to send an HTTP response with options/option_groups. // Thus, we don't support lazy handlers for this pattern. const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (body.type === PayloadType.ViewSubmission) { // View submissions const slackRequest: SlackRequest<E, ViewSubmission> = { payload: body as ViewSubmission, ...baseRequest, }; for (const matcher of this.#viewSubmissions) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (body.type === PayloadType.ViewClosed) { // View closed const slackRequest: SlackRequest<E, ViewClosed> = { payload: body as ViewClosed, ...baseRequest, }; for (const matcher of this.#viewClosed) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } // TODO: Add code suggestion here console.log( `*** No listener found ***\n${JSON.stringify(baseRequest.body)}` ); return new Response("No listener found", { status: 404 }); } return new Response("Invalid signature", { status: 401 }); } } export type StringOrRegExp = string | RegExp; export type EventRequest<E extends SlackAppEnv, T> = Extract< AnySlackEventWithChannelId, { type: T } > extends never ? SlackRequest<E, Extract<AnySlackEvent, { type: T }>> : SlackRequestWithChannelId< E, Extract<AnySlackEventWithChannelId, { type: T }> >; export type MessageEventPattern = string | RegExp | undefined; export type MessageEventRequest< E extends SlackAppEnv, ST extends string | undefined > = SlackRequestWithChannelId< E, Extract<AnySlackEventWithChannelId, { subtype: ST }> >; export type MessageEventSubtypes = | undefined | "bot_message" | "thread_broadcast" | "file_share"; export type MessageEventHandler<E extends SlackAppEnv> = ( req: MessageEventRequest<E, MessageEventSubtypes> ) => Promise<void>; export const noopLazyListener = async () => {};
src/app.ts
seratch-slack-edge-c75c224
[ { "filename": "src/handler/handler.ts", "retrieved_chunk": "import { SlackAppEnv } from \"../app-env\";\nimport { SlackRequest } from \"../request/request\";\nimport { SlackResponse } from \"../response/response\";\nexport type AckResponse = SlackResponse | string | void;\nexport interface SlackHandler<E extends SlackAppEnv, Payload> {\n ack(request: SlackRequest<E, Payload>): Promise<AckResponse>;\n lazy(request: SlackRequest<E, Payload>): Promise<void>;\n}", "score": 0.8387879133224487 }, { "filename": "src/handler/message-handler.ts", "retrieved_chunk": "import { SlackAppEnv } from \"../app-env\";\nimport { SlackRequest } from \"../request/request\";\nimport { MessageResponse } from \"../response/response-body\";\nimport { AckResponse } from \"./handler\";\nexport type MessageAckResponse = AckResponse | MessageResponse;\nexport interface SlackMessageHandler<E extends SlackAppEnv, Payload> {\n ack(request: SlackRequest<E, Payload>): Promise<MessageAckResponse>;\n lazy(request: SlackRequest<E, Payload>): Promise<void>;\n}", "score": 0.8334250450134277 }, { "filename": "src/handler/view-handler.ts", "retrieved_chunk": "import { SlackAppEnv } from \"../app-env\";\nimport { SlackRequest } from \"../request/request\";\nimport { SlackViewResponse } from \"../response/response\";\nexport type ViewAckResponse = SlackViewResponse | void;\nexport type SlackViewHandler<E extends SlackAppEnv, Payload> = {\n ack(request: SlackRequest<E, Payload>): Promise<ViewAckResponse>;\n lazy(request: SlackRequest<E, Payload>): Promise<void>;\n};", "score": 0.8278017044067383 }, { "filename": "src/handler/options-handler.ts", "retrieved_chunk": "import { SlackAppEnv } from \"../app-env\";\nimport { SlackRequest } from \"../request/request\";\nimport { SlackOptionsResponse } from \"../response/response\";\nexport type OptionsAckResponse = SlackOptionsResponse;\nexport interface SlackOptionsHandler<E extends SlackAppEnv, Payload> {\n ack(request: SlackRequest<E, Payload>): Promise<OptionsAckResponse>;\n // Note that a block_suggestion response must be done synchronously.\n // That's why we don't support lazy functions for the pattern.\n}", "score": 0.8274625539779663 }, { "filename": "src/socket-mode/socket-mode-client.ts", "retrieved_chunk": " console.info(`Completed a lazy listener execution: ${res}`);\n })\n .catch((err) => {\n console.error(`Failed to run a lazy listener: ${err}`);\n });\n },\n };\n const response = await app.run(request, context);\n // deno-lint-ignore no-explicit-any\n let ack: any = { envelope_id: data.envelope_id };", "score": 0.8175696730613708 } ]
typescript
body.actions || !body.actions[0] ) {
/* eslint-disable @typescript-eslint/no-unsafe-argument */ /* eslint-disable @next/next/no-img-element */ import { Button, Group, FileInput, TextInput, Title, Stack, } from "@mantine/core"; import { useForm } from "@mantine/form"; import { useDisclosure } from "@mantine/hooks"; import { IconCheck, IconEdit, IconLetterX } from "@tabler/icons-react"; import { type NextPage } from "next"; import Head from "next/head"; import { useRouter } from "next/router"; import { useState } from "react"; import AdminDashboardLayout from "~/components/layouts/admin-dashboard-layout"; import { api } from "~/utils/api"; import { getImageUrl } from "~/utils/getImageUrl"; async function uploadFileToS3({ getPresignedUrl, file, }: { getPresignedUrl: () => Promise<{ url: string; fields: Record<string, string>; }>; file: File; }) { const { url, fields } = await getPresignedUrl(); const data: Record<string, any> = { ...fields, "Content-Type": file.type, file, }; const formData = new FormData(); for (const name in data) { formData.append(name, data[name]); } await fetch(url, { method: "POST", body: formData, }); } const Courses: NextPage = () => { const router = useRouter(); const courseId = router.query.courseId as string; const updateCourseMutation = api.course.updateCourse.useMutation(); const createSectionMutation = api.course.createSection.useMutation(); const deleteSection = api.course.deleteSection.useMutation(); const swapSections = api.course.swapSections.useMutation(); const createPresignedUrlMutation = api.course.createPresignedUrl.useMutation(); const createPresignedUrlForVideoMutation = api.course.createPresignedUrlForVideo.useMutation(); const updateTitleForm = useForm({ initialValues: { title: "", }, }); const newSectionForm = useForm({ initialValues: { title: "", }, }); const [file, setFile] = useState<File | null>(null); const [newSection, setNewSection] = useState<File | null>(null); const courseQuery = api.course.getCourseById.useQuery( { courseId, }, { enabled: !!courseId, onSuccess
(data) {
updateTitleForm.setFieldValue("title", data?.title ?? ""); }, } ); const [isEditingTitle, { open: setEditTitle, close: unsetEditTitle }] = useDisclosure(false); const uploadImage = async (e: React.FormEvent<HTMLFormElement>) => { e.preventDefault(); if (!file) return; await uploadFileToS3({ getPresignedUrl: () => createPresignedUrlMutation.mutateAsync({ courseId, }), file, }); setFile(null); await courseQuery.refetch(); // if (fileRef.current) { // fileRef.current.value = ""; // } }; // const onFileChange = (e: React.FormEvent<HTMLInputElement>) => { // setFile(e.currentTarget.files?.[0]); // }; const sortedSections = (courseQuery.data?.sections ?? []).sort( (a, b) => a.order - b.order ); return ( <> <Head> <title>Manage Courses</title> <meta name="description" content="Generated by create-t3-app" /> <link rel="icon" href="/favicon.ico" /> </Head> <main> <AdminDashboardLayout> <Stack spacing={"xl"}> {isEditingTitle ? ( <form onSubmit={updateTitleForm.onSubmit(async (values) => { await updateCourseMutation.mutateAsync({ ...values, courseId, }); await courseQuery.refetch(); unsetEditTitle(); })} > <Group> <TextInput withAsterisk required placeholder="name your course here" {...updateTitleForm.getInputProps("title")} /> <Button color="green" type="submit"> <IconCheck /> </Button> <Button color="gray" onClick={unsetEditTitle}> <IconLetterX /> </Button> </Group> </form> ) : ( <Group> <Title order={1}>{courseQuery.data?.title}</Title> <Button color="gray" onClick={setEditTitle}> <IconEdit size="1rem" /> </Button> </Group> )} <Group> {courseQuery.data && ( <img width="200" alt="an image of the course" src={getImageUrl(courseQuery.data.imageId)} /> )} <Stack sx={{ flex: 1 }}> <form onSubmit={uploadImage}> <FileInput label="Course Image" onChange={setFile} value={file} /> <Button disabled={!file} type="submit" variant="light" color="blue" mt="md" radius="md" > Upload Image </Button> </form> </Stack> </Group> <Stack> <Title order={2}>Sections </Title> {sortedSections.map((section, idx) => ( <Stack key={section.id} p="xl" sx={{ border: "1px solid white", }} > <Group> <Title sx={{ flex: 1 }} order={3}> {section.title} </Title> {idx > 0 && ( <Button type="submit" variant="light" color="white" mt="md" radius="md" onClick={async () => { const targetSection = sortedSections[idx - 1]; if (!targetSection) return; await swapSections.mutateAsync({ sectionIdSource: section.id, sectionIdTarget: targetSection.id, }); await courseQuery.refetch(); }} > Move Up </Button> )} {idx < sortedSections.length - 1 && ( <Button type="submit" variant="light" color="white" mt="md" radius="md" onClick={async () => { const targetSection = sortedSections[idx + 1]; if (!targetSection) return; await swapSections.mutateAsync({ sectionIdSource: section.id, sectionIdTarget: targetSection.id, }); await courseQuery.refetch(); }} > Move Down </Button> )} <Button type="submit" variant="light" color="red" mt="md" radius="md" onClick={async () => { if ( !confirm( "are you sure you want to delete this section?" ) ) return; await deleteSection.mutateAsync({ sectionId: section.id, }); await courseQuery.refetch(); }} > Delete </Button> </Group> <video width="400" controls> <source src={`http://localhost:9000/wdc-online-course-platform/${section.videoId}`} type="video/mp4" /> Your browser does not support HTML video. </video> </Stack> ))} <Stack p="xl" sx={{ border: "1px dashed white", }} > <form onSubmit={newSectionForm.onSubmit(async (values) => { if (!newSection) return; const section = await createSectionMutation.mutateAsync({ courseId: courseId, title: values.title, }); await uploadFileToS3({ getPresignedUrl: () => createPresignedUrlForVideoMutation.mutateAsync({ sectionId: section.id, }), file: newSection, }); setNewSection(null); await courseQuery.refetch(); newSectionForm.reset(); })} > <Stack spacing="xl"> <Title order={3}>Create New Section</Title> <TextInput withAsterisk required label="Section Title" placeholder="name your section" {...newSectionForm.getInputProps("title")} /> <FileInput label="Section Video" onChange={setNewSection} required value={newSection} /> <Button type="submit" variant="light" color="blue" mt="md" radius="md" > Create Section </Button> </Stack> </form> </Stack> </Stack> </Stack> </AdminDashboardLayout> </main> </> ); }; export default Courses;
src/pages/dashboard/courses/[courseId].tsx
webdevcody-online-course-platform-ee963ca
[ { "filename": "src/pages/dashboard/courses/index.tsx", "retrieved_chunk": "}\nconst Courses: NextPage = () => {\n const courses = api.course.getCourses.useQuery();\n const createCourseMutation = api.course.createCourse.useMutation();\n const [\n isCreateCourseModalOpen,\n { open: openCreateCourseModal, close: closeCreateCourseModal },\n ] = useDisclosure(false);\n const createCourseForm = useForm({\n initialValues: {", "score": 0.8426065444946289 }, { "filename": "src/server/api/routers/course.ts", "retrieved_chunk": " code: \"NOT_FOUND\",\n message: \"the section has no course\",\n });\n }\n const course = await ctx.prisma.course.findUnique({\n where: {\n id: section.courseId,\n },\n });\n if (course?.userId !== ctx.session.user.id) {", "score": 0.8212881684303284 }, { "filename": "src/pages/dashboard/courses/index.tsx", "retrieved_chunk": " </Head>\n <Modal\n opened={isCreateCourseModalOpen}\n onClose={closeCreateCourseModal}\n title=\"Create Course\"\n >\n <form\n onSubmit={createCourseForm.onSubmit(async (values) => {\n await createCourseMutation.mutateAsync(values);\n closeCreateCourseModal();", "score": 0.816155195236206 }, { "filename": "src/server/api/routers/course.ts", "retrieved_chunk": " code: \"NOT_FOUND\",\n message: \"the course does not exist\",\n });\n }\n const imageId = uuidv4();\n await ctx.prisma.course.update({\n where: {\n id: course.id,\n },\n data: {", "score": 0.8113540410995483 }, { "filename": "src/server/api/routers/course.ts", "retrieved_chunk": " },\n });\n if (course?.userId !== ctx.session.user.id) {\n throw new TRPCError({\n code: \"FORBIDDEN\",\n message: \"you do not have access to this course\",\n });\n }\n return section;\n }),", "score": 0.811161458492279 } ]
typescript
(data) {
/* eslint-disable @typescript-eslint/no-unsafe-argument */ /* eslint-disable @next/next/no-img-element */ import { Button, Group, FileInput, TextInput, Title, Stack, } from "@mantine/core"; import { useForm } from "@mantine/form"; import { useDisclosure } from "@mantine/hooks"; import { IconCheck, IconEdit, IconLetterX } from "@tabler/icons-react"; import { type NextPage } from "next"; import Head from "next/head"; import { useRouter } from "next/router"; import { useState } from "react"; import AdminDashboardLayout from "~/components/layouts/admin-dashboard-layout"; import { api } from "~/utils/api"; import { getImageUrl } from "~/utils/getImageUrl"; async function uploadFileToS3({ getPresignedUrl, file, }: { getPresignedUrl: () => Promise<{ url: string; fields: Record<string, string>; }>; file: File; }) { const { url, fields } = await getPresignedUrl(); const data: Record<string, any> = { ...fields, "Content-Type": file.type, file, }; const formData = new FormData(); for (const name in data) { formData.append(name, data[name]); } await fetch(url, { method: "POST", body: formData, }); } const Courses: NextPage = () => { const router = useRouter(); const courseId = router.query.courseId as string; const
updateCourseMutation = api.course.updateCourse.useMutation();
const createSectionMutation = api.course.createSection.useMutation(); const deleteSection = api.course.deleteSection.useMutation(); const swapSections = api.course.swapSections.useMutation(); const createPresignedUrlMutation = api.course.createPresignedUrl.useMutation(); const createPresignedUrlForVideoMutation = api.course.createPresignedUrlForVideo.useMutation(); const updateTitleForm = useForm({ initialValues: { title: "", }, }); const newSectionForm = useForm({ initialValues: { title: "", }, }); const [file, setFile] = useState<File | null>(null); const [newSection, setNewSection] = useState<File | null>(null); const courseQuery = api.course.getCourseById.useQuery( { courseId, }, { enabled: !!courseId, onSuccess(data) { updateTitleForm.setFieldValue("title", data?.title ?? ""); }, } ); const [isEditingTitle, { open: setEditTitle, close: unsetEditTitle }] = useDisclosure(false); const uploadImage = async (e: React.FormEvent<HTMLFormElement>) => { e.preventDefault(); if (!file) return; await uploadFileToS3({ getPresignedUrl: () => createPresignedUrlMutation.mutateAsync({ courseId, }), file, }); setFile(null); await courseQuery.refetch(); // if (fileRef.current) { // fileRef.current.value = ""; // } }; // const onFileChange = (e: React.FormEvent<HTMLInputElement>) => { // setFile(e.currentTarget.files?.[0]); // }; const sortedSections = (courseQuery.data?.sections ?? []).sort( (a, b) => a.order - b.order ); return ( <> <Head> <title>Manage Courses</title> <meta name="description" content="Generated by create-t3-app" /> <link rel="icon" href="/favicon.ico" /> </Head> <main> <AdminDashboardLayout> <Stack spacing={"xl"}> {isEditingTitle ? ( <form onSubmit={updateTitleForm.onSubmit(async (values) => { await updateCourseMutation.mutateAsync({ ...values, courseId, }); await courseQuery.refetch(); unsetEditTitle(); })} > <Group> <TextInput withAsterisk required placeholder="name your course here" {...updateTitleForm.getInputProps("title")} /> <Button color="green" type="submit"> <IconCheck /> </Button> <Button color="gray" onClick={unsetEditTitle}> <IconLetterX /> </Button> </Group> </form> ) : ( <Group> <Title order={1}>{courseQuery.data?.title}</Title> <Button color="gray" onClick={setEditTitle}> <IconEdit size="1rem" /> </Button> </Group> )} <Group> {courseQuery.data && ( <img width="200" alt="an image of the course" src={getImageUrl(courseQuery.data.imageId)} /> )} <Stack sx={{ flex: 1 }}> <form onSubmit={uploadImage}> <FileInput label="Course Image" onChange={setFile} value={file} /> <Button disabled={!file} type="submit" variant="light" color="blue" mt="md" radius="md" > Upload Image </Button> </form> </Stack> </Group> <Stack> <Title order={2}>Sections </Title> {sortedSections.map((section, idx) => ( <Stack key={section.id} p="xl" sx={{ border: "1px solid white", }} > <Group> <Title sx={{ flex: 1 }} order={3}> {section.title} </Title> {idx > 0 && ( <Button type="submit" variant="light" color="white" mt="md" radius="md" onClick={async () => { const targetSection = sortedSections[idx - 1]; if (!targetSection) return; await swapSections.mutateAsync({ sectionIdSource: section.id, sectionIdTarget: targetSection.id, }); await courseQuery.refetch(); }} > Move Up </Button> )} {idx < sortedSections.length - 1 && ( <Button type="submit" variant="light" color="white" mt="md" radius="md" onClick={async () => { const targetSection = sortedSections[idx + 1]; if (!targetSection) return; await swapSections.mutateAsync({ sectionIdSource: section.id, sectionIdTarget: targetSection.id, }); await courseQuery.refetch(); }} > Move Down </Button> )} <Button type="submit" variant="light" color="red" mt="md" radius="md" onClick={async () => { if ( !confirm( "are you sure you want to delete this section?" ) ) return; await deleteSection.mutateAsync({ sectionId: section.id, }); await courseQuery.refetch(); }} > Delete </Button> </Group> <video width="400" controls> <source src={`http://localhost:9000/wdc-online-course-platform/${section.videoId}`} type="video/mp4" /> Your browser does not support HTML video. </video> </Stack> ))} <Stack p="xl" sx={{ border: "1px dashed white", }} > <form onSubmit={newSectionForm.onSubmit(async (values) => { if (!newSection) return; const section = await createSectionMutation.mutateAsync({ courseId: courseId, title: values.title, }); await uploadFileToS3({ getPresignedUrl: () => createPresignedUrlForVideoMutation.mutateAsync({ sectionId: section.id, }), file: newSection, }); setNewSection(null); await courseQuery.refetch(); newSectionForm.reset(); })} > <Stack spacing="xl"> <Title order={3}>Create New Section</Title> <TextInput withAsterisk required label="Section Title" placeholder="name your section" {...newSectionForm.getInputProps("title")} /> <FileInput label="Section Video" onChange={setNewSection} required value={newSection} /> <Button type="submit" variant="light" color="blue" mt="md" radius="md" > Create Section </Button> </Stack> </form> </Stack> </Stack> </Stack> </AdminDashboardLayout> </main> </> ); }; export default Courses;
src/pages/dashboard/courses/[courseId].tsx
webdevcody-online-course-platform-ee963ca
[ { "filename": "src/pages/dashboard/courses/index.tsx", "retrieved_chunk": "}\nconst Courses: NextPage = () => {\n const courses = api.course.getCourses.useQuery();\n const createCourseMutation = api.course.createCourse.useMutation();\n const [\n isCreateCourseModalOpen,\n { open: openCreateCourseModal, close: closeCreateCourseModal },\n ] = useDisclosure(false);\n const createCourseForm = useForm({\n initialValues: {", "score": 0.9177059531211853 }, { "filename": "src/pages/dashboard/courses/index.tsx", "retrieved_chunk": "import { type Course } from \"@prisma/client\";\nimport { type NextPage } from \"next\";\nimport Head from \"next/head\";\nimport { useForm } from \"@mantine/form\";\nimport AdminDashboardLayout from \"~/components/layouts/admin-dashboard-layout\";\nimport {\n Card as MantineCard,\n Image,\n Text,\n Flex,", "score": 0.866690456867218 }, { "filename": "src/pages/dashboard/courses/index.tsx", "retrieved_chunk": " </Head>\n <Modal\n opened={isCreateCourseModalOpen}\n onClose={closeCreateCourseModal}\n title=\"Create Course\"\n >\n <form\n onSubmit={createCourseForm.onSubmit(async (values) => {\n await createCourseMutation.mutateAsync(values);\n closeCreateCourseModal();", "score": 0.8624799251556396 }, { "filename": "src/pages/dashboard/courses/index.tsx", "retrieved_chunk": " </main>\n </>\n );\n};\nexport default Courses;", "score": 0.8359054923057556 }, { "filename": "src/pages/dashboard/courses/index.tsx", "retrieved_chunk": " <Button onClick={openCreateCourseModal}>Create Course</Button>\n </Flex>\n <Grid>\n {courses.data?.map((course) => (\n <Grid.Col key={course.id} span={4}>\n <CourseCard course={course} />\n </Grid.Col>\n ))}\n </Grid>\n </AdminDashboardLayout>", "score": 0.8293809294700623 } ]
typescript
updateCourseMutation = api.course.updateCourse.useMutation();
import { type AppType } from "next/app"; import { type Session } from "next-auth"; import { SessionProvider } from "next-auth/react"; import { ColorScheme, ColorSchemeProvider, MantineProvider, } from "@mantine/core"; import { useColorScheme } from "@mantine/hooks"; import { api } from "~/utils/api"; import "~/styles/globals.css"; import { useState } from "react"; const MyApp: AppType<{ session: Session | null }> = ({ Component, pageProps: { session, ...pageProps }, }) => { const preferredColorScheme = "dark"; //useColorScheme(); const [colorScheme, setColorScheme] = useState<ColorScheme>(preferredColorScheme); const toggleColorScheme = (value?: ColorScheme) => setColorScheme(value || (colorScheme === "dark" ? "light" : "dark")); return ( <ColorSchemeProvider colorScheme={colorScheme} toggleColorScheme={toggleColorScheme} > <MantineProvider withGlobalStyles withNormalizeCSS theme={{ colorScheme, }} > <SessionProvider session={session}> <Component {...pageProps} /> </SessionProvider> </MantineProvider> </ColorSchemeProvider> ); };
export default api.withTRPC(MyApp);
src/pages/_app.tsx
webdevcody-online-course-platform-ee963ca
[ { "filename": "src/pages/api/trpc/[trpc].ts", "retrieved_chunk": "import { createNextApiHandler } from \"@trpc/server/adapters/next\";\nimport { env } from \"~/env.mjs\";\nimport { createTRPCContext } from \"~/server/api/trpc\";\nimport { appRouter } from \"~/server/api/root\";\n// export API handler\nexport default createNextApiHandler({\n router: appRouter,\n createContext: createTRPCContext,\n onError:\n env.NODE_ENV === \"development\"", "score": 0.8366091251373291 }, { "filename": "src/utils/api.ts", "retrieved_chunk": " ],\n };\n },\n /**\n * Whether tRPC should await queries when server rendering pages.\n *\n * @see https://trpc.io/docs/nextjs#ssr-boolean-default-false\n */\n ssr: false,\n});", "score": 0.8302678465843201 }, { "filename": "src/utils/api.ts", "retrieved_chunk": "import { type AppRouter } from \"~/server/api/root\";\nconst getBaseUrl = () => {\n if (typeof window !== \"undefined\") return \"\"; // browser should use relative url\n if (process.env.VERCEL_URL) return `https://${process.env.VERCEL_URL}`; // SSR should use vercel url\n return `http://localhost:${process.env.PORT ?? 3000}`; // dev SSR should use localhost\n};\n/** A set of type-safe react-query hooks for your tRPC API. */\nexport const api = createTRPCNext<AppRouter>({\n config() {\n return {", "score": 0.8276064395904541 }, { "filename": "src/components/layouts/admin-dashboard-layout.tsx", "retrieved_chunk": "import {\n ActionIcon,\n AppShell,\n Group,\n Header,\n Navbar,\n useMantineColorScheme,\n} from \"@mantine/core\";\nimport { IconSun, IconMoonStars } from \"@tabler/icons-react\";\nimport { ReactNode } from \"react\";", "score": 0.8262131214141846 }, { "filename": "src/components/shell/_user.tsx", "retrieved_chunk": " Text,\n Box,\n useMantineTheme,\n rem,\n Button,\n Menu,\n} from \"@mantine/core\";\nimport { signIn, signOut, useSession } from \"next-auth/react\";\nexport function User() {\n const theme = useMantineTheme();", "score": 0.8119941353797913 } ]
typescript
export default api.withTRPC(MyApp);
import { SlackAppEnv, SlackEdgeAppEnv, SlackSocketModeAppEnv } from "./app-env"; import { parseRequestBody } from "./request/request-parser"; import { verifySlackRequest } from "./request/request-verification"; import { AckResponse, SlackHandler } from "./handler/handler"; import { SlackRequestBody } from "./request/request-body"; import { PreAuthorizeSlackMiddlwareRequest, SlackRequestWithRespond, SlackMiddlwareRequest, SlackRequestWithOptionalRespond, SlackRequest, SlackRequestWithChannelId, } from "./request/request"; import { SlashCommand } from "./request/payload/slash-command"; import { toCompleteResponse } from "./response/response"; import { SlackEvent, AnySlackEvent, AnySlackEventWithChannelId, } from "./request/payload/event"; import { ResponseUrlSender, SlackAPIClient } from "slack-web-api-client"; import { builtBaseContext, SlackAppContext, SlackAppContextWithChannelId, SlackAppContextWithRespond, } from "./context/context"; import { PreAuthorizeMiddleware, Middleware } from "./middleware/middleware"; import { isDebugLogEnabled, prettyPrint } from "slack-web-api-client"; import { Authorize } from "./authorization/authorize"; import { AuthorizeResult } from "./authorization/authorize-result"; import { ignoringSelfEvents, urlVerification, } from "./middleware/built-in-middleware"; import { ConfigError } from "./errors"; import { GlobalShortcut } from "./request/payload/global-shortcut"; import { MessageShortcut } from "./request/payload/message-shortcut"; import { BlockAction, BlockElementAction, BlockElementTypes, } from "./request/payload/block-action"; import { ViewSubmission } from "./request/payload/view-submission"; import { ViewClosed } from "./request/payload/view-closed"; import { BlockSuggestion } from "./request/payload/block-suggestion"; import { OptionsAckResponse, SlackOptionsHandler, } from "./handler/options-handler"; import { SlackViewHandler, ViewAckResponse } from "./handler/view-handler"; import { MessageAckResponse, SlackMessageHandler, } from "./handler/message-handler"; import { singleTeamAuthorize } from "./authorization/single-team-authorize"; import { ExecutionContext, NoopExecutionContext } from "./execution-context"; import { PayloadType } from "./request/payload-types"; import { isPostedMessageEvent } from "./utility/message-events"; import { SocketModeClient } from "./socket-mode/socket-mode-client"; export interface SlackAppOptions< E extends SlackEdgeAppEnv | SlackSocketModeAppEnv > { env: E; authorize?: Authorize<E>; routes?: { events: string; }; socketMode?: boolean; } export class SlackApp<E extends SlackEdgeAppEnv | SlackSocketModeAppEnv> { public env: E; public client: SlackAPIClient; public authorize: Authorize<E>; public routes: { events: string | undefined }; public signingSecret: string; public appLevelToken: string | undefined; public socketMode: boolean; public socketModeClient: SocketModeClient | undefined; // deno-lint-ignore no-explicit-any public preAuthorizeMiddleware: PreAuthorizeMiddleware<any>[] = [ urlVerification, ]; // deno-lint-ignore no-explicit-any public postAuthorizeMiddleware: Middleware<any>[] = [ignoringSelfEvents]; #slashCommands: (( body: SlackRequestBody ) => SlackMessageHandler<E, SlashCommand> | null)[] = []; #events: (( body: SlackRequestBody ) => SlackHandler<E, SlackEvent<string>> | null)[] = []; #globalShorcuts: (( body: SlackRequestBody ) => SlackHandler<E, GlobalShortcut> | null)[] = []; #messageShorcuts: (( body: SlackRequestBody ) => SlackHandler<E, MessageShortcut> | null)[] = []; #blockActions: ((body: SlackRequestBody) => SlackHandler< E, // deno-lint-ignore no-explicit-any BlockAction<any> > | null)[] = []; #blockSuggestions: (( body: SlackRequestBody ) => SlackOptionsHandler<E, BlockSuggestion> | null)[] = []; #viewSubmissions: (( body: SlackRequestBody ) => SlackViewHandler<E, ViewSubmission> | null)[] = []; #viewClosed: (( body: SlackRequestBody ) => SlackViewHandler<E, ViewClosed> | null)[] = []; constructor(options: SlackAppOptions<E>) { if ( options.env.SLACK_BOT_TOKEN === undefined && (options.authorize === undefined || options.authorize === singleTeamAuthorize) ) { throw new ConfigError( "When you don't pass env.SLACK_BOT_TOKEN, your own authorize function, which supplies a valid token to use, needs to be passed instead." ); } this.env = options.env; this.client = new SlackAPIClient(options.env.SLACK_BOT_TOKEN, { logLevel: this.env.SLACK_LOGGING_LEVEL, }); this.appLevelToken = options.env.SLACK_APP_TOKEN; this.socketMode = options.socketMode ?? this.appLevelToken !== undefined; if (this.socketMode) { this.signingSecret = ""; } else { if (!this.env.SLACK_SIGNING_SECRET) { throw new ConfigError( "env.SLACK_SIGNING_SECRET is required to run your app on edge functions!" ); } this.signingSecret = this.env.SLACK_SIGNING_SECRET; } this.authorize = options.authorize ?? singleTeamAuthorize; this.routes = { events: options.routes?.events }; } beforeAuthorize(middleware: PreAuthorizeMiddleware<E>): SlackApp<E> { this.preAuthorizeMiddleware.push(middleware); return this; } middleware(middleware: Middleware<E>): SlackApp<E> { return this.afterAuthorize(middleware); } use(middleware: Middleware<E>): SlackApp<E> { return this.afterAuthorize(middleware); } afterAuthorize(middleware: Middleware<E>): SlackApp<E> { this.postAuthorizeMiddleware.push(middleware); return this; } command( pattern: StringOrRegExp, ack: ( req: SlackRequestWithRespond<E, SlashCommand> ) => Promise<MessageAckResponse>, lazy: ( req: SlackRequestWithRespond<E, SlashCommand> ) => Promise<void> = noopLazyListener ): SlackApp<E> { const handler: SlackMessageHandler<E, SlashCommand> = { ack, lazy }; this.#slashCommands.push((body) => { if (body.type || !body.command) { return null; } if (typeof pattern === "string" && body.command === pattern) { return handler; } else if ( typeof pattern === "object" && pattern instanceof RegExp && body.command.match(pattern) ) { return handler; } return null; }); return this; } event<Type extends string>( event: Type, lazy: (req: EventRequest<E, Type>) => Promise<void> ): SlackApp<E> { this.#events.push((body) => { if (body.type !== PayloadType.
EventsAPI || !body.event) {
return null; } if (body.event.type === event) { // deno-lint-ignore require-await return { ack: async () => "", lazy }; } return null; }); return this; } anyMessage(lazy: MessageEventHandler<E>): SlackApp<E> { return this.message(undefined, lazy); } message( pattern: MessageEventPattern, lazy: MessageEventHandler<E> ): SlackApp<E> { this.#events.push((body) => { if ( body.type !== PayloadType.EventsAPI || !body.event || body.event.type !== "message" ) { return null; } if (isPostedMessageEvent(body.event)) { let matched = true; if (pattern !== undefined) { if (typeof pattern === "string") { matched = body.event.text!.includes(pattern); } if (typeof pattern === "object") { matched = body.event.text!.match(pattern) !== null; } } if (matched) { // deno-lint-ignore require-await return { ack: async (_: EventRequest<E, "message">) => "", lazy }; } } return null; }); return this; } shortcut( callbackId: StringOrRegExp, ack: ( req: | SlackRequest<E, GlobalShortcut> | SlackRequestWithRespond<E, MessageShortcut> ) => Promise<AckResponse>, lazy: ( req: | SlackRequest<E, GlobalShortcut> | SlackRequestWithRespond<E, MessageShortcut> ) => Promise<void> = noopLazyListener ): SlackApp<E> { return this.globalShortcut(callbackId, ack, lazy).messageShortcut( callbackId, ack, lazy ); } globalShortcut( callbackId: StringOrRegExp, ack: (req: SlackRequest<E, GlobalShortcut>) => Promise<AckResponse>, lazy: ( req: SlackRequest<E, GlobalShortcut> ) => Promise<void> = noopLazyListener ): SlackApp<E> { const handler: SlackHandler<E, GlobalShortcut> = { ack, lazy }; this.#globalShorcuts.push((body) => { if (body.type !== PayloadType.GlobalShortcut || !body.callback_id) { return null; } if (typeof callbackId === "string" && body.callback_id === callbackId) { return handler; } else if ( typeof callbackId === "object" && callbackId instanceof RegExp && body.callback_id.match(callbackId) ) { return handler; } return null; }); return this; } messageShortcut( callbackId: StringOrRegExp, ack: ( req: SlackRequestWithRespond<E, MessageShortcut> ) => Promise<AckResponse>, lazy: ( req: SlackRequestWithRespond<E, MessageShortcut> ) => Promise<void> = noopLazyListener ): SlackApp<E> { const handler: SlackHandler<E, MessageShortcut> = { ack, lazy }; this.#messageShorcuts.push((body) => { if (body.type !== PayloadType.MessageShortcut || !body.callback_id) { return null; } if (typeof callbackId === "string" && body.callback_id === callbackId) { return handler; } else if ( typeof callbackId === "object" && callbackId instanceof RegExp && body.callback_id.match(callbackId) ) { return handler; } return null; }); return this; } action< T extends BlockElementTypes, A extends BlockAction<BlockElementAction<T>> = BlockAction< BlockElementAction<T> > >( constraints: | StringOrRegExp | { type: T; block_id?: string; action_id: string }, ack: (req: SlackRequestWithOptionalRespond<E, A>) => Promise<AckResponse>, lazy: ( req: SlackRequestWithOptionalRespond<E, A> ) => Promise<void> = noopLazyListener ): SlackApp<E> { const handler: SlackHandler<E, A> = { ack, lazy }; this.#blockActions.push((body) => { if ( body.type !== PayloadType.BlockAction || !body.actions || !body.actions[0] ) { return null; } const action = body.actions[0]; if (typeof constraints === "string" && action.action_id === constraints) { return handler; } else if (typeof constraints === "object") { if (constraints instanceof RegExp) { if (action.action_id.match(constraints)) { return handler; } } else if (constraints.type) { if (action.type === constraints.type) { if (action.action_id === constraints.action_id) { if ( constraints.block_id && action.block_id !== constraints.block_id ) { return null; } return handler; } } } } return null; }); return this; } options( constraints: StringOrRegExp | { block_id?: string; action_id: string }, ack: (req: SlackRequest<E, BlockSuggestion>) => Promise<OptionsAckResponse> ): SlackApp<E> { // Note that block_suggestion response must be done within 3 seconds. // So, we don't support the lazy handler for it. const handler: SlackOptionsHandler<E, BlockSuggestion> = { ack }; this.#blockSuggestions.push((body) => { if (body.type !== PayloadType.BlockSuggestion || !body.action_id) { return null; } if (typeof constraints === "string" && body.action_id === constraints) { return handler; } else if (typeof constraints === "object") { if (constraints instanceof RegExp) { if (body.action_id.match(constraints)) { return handler; } } else { if (body.action_id === constraints.action_id) { if (body.block_id && body.block_id !== constraints.block_id) { return null; } return handler; } } } return null; }); return this; } view( callbackId: StringOrRegExp, ack: ( req: | SlackRequestWithOptionalRespond<E, ViewSubmission> | SlackRequest<E, ViewClosed> ) => Promise<ViewAckResponse>, lazy: ( req: | SlackRequestWithOptionalRespond<E, ViewSubmission> | SlackRequest<E, ViewClosed> ) => Promise<void> = noopLazyListener ): SlackApp<E> { return this.viewSubmission(callbackId, ack, lazy).viewClosed( callbackId, ack, lazy ); } viewSubmission( callbackId: StringOrRegExp, ack: ( req: SlackRequestWithOptionalRespond<E, ViewSubmission> ) => Promise<ViewAckResponse>, lazy: ( req: SlackRequestWithOptionalRespond<E, ViewSubmission> ) => Promise<void> = noopLazyListener ): SlackApp<E> { const handler: SlackViewHandler<E, ViewSubmission> = { ack, lazy }; this.#viewSubmissions.push((body) => { if (body.type !== PayloadType.ViewSubmission || !body.view) { return null; } if ( typeof callbackId === "string" && body.view.callback_id === callbackId ) { return handler; } else if ( typeof callbackId === "object" && callbackId instanceof RegExp && body.view.callback_id.match(callbackId) ) { return handler; } return null; }); return this; } viewClosed( callbackId: StringOrRegExp, ack: (req: SlackRequest<E, ViewClosed>) => Promise<ViewAckResponse>, lazy: (req: SlackRequest<E, ViewClosed>) => Promise<void> = noopLazyListener ): SlackApp<E> { const handler: SlackViewHandler<E, ViewClosed> = { ack, lazy }; this.#viewClosed.push((body) => { if (body.type !== PayloadType.ViewClosed || !body.view) { return null; } if ( typeof callbackId === "string" && body.view.callback_id === callbackId ) { return handler; } else if ( typeof callbackId === "object" && callbackId instanceof RegExp && body.view.callback_id.match(callbackId) ) { return handler; } return null; }); return this; } async run( request: Request, ctx: ExecutionContext = new NoopExecutionContext() ): Promise<Response> { return await this.handleEventRequest(request, ctx); } async connect(): Promise<void> { if (!this.socketMode) { throw new ConfigError( "Both env.SLACK_APP_TOKEN and socketMode: true are required to start a Socket Mode connection!" ); } this.socketModeClient = new SocketModeClient(this); await this.socketModeClient.connect(); } async disconnect(): Promise<void> { if (this.socketModeClient) { await this.socketModeClient.disconnect(); } } async handleEventRequest( request: Request, ctx: ExecutionContext ): Promise<Response> { // If the routes.events is missing, any URLs can work for handing requests from Slack if (this.routes.events) { const { pathname } = new URL(request.url); if (pathname !== this.routes.events) { return new Response("Not found", { status: 404 }); } } // To avoid the following warning by Cloudflware, parse the body as Blob first // Called .text() on an HTTP body which does not appear to be text .. const blobRequestBody = await request.blob(); // We can safely assume the incoming request body is always text data const rawBody: string = await blobRequestBody.text(); // For Request URL verification if (rawBody.includes("ssl_check=")) { // Slack does not send the x-slack-signature header for this pattern. // Thus, we need to check the pattern before verifying a request. const bodyParams = new URLSearchParams(rawBody); if (bodyParams.get("ssl_check") === "1" && bodyParams.get("token")) { return new Response("", { status: 200 }); } } // Verify the request headers and body const isRequestSignatureVerified = this.socketMode || (await verifySlackRequest(this.signingSecret, request.headers, rawBody)); if (isRequestSignatureVerified) { // deno-lint-ignore no-explicit-any const body: Record<string, any> = await parseRequestBody( request.headers, rawBody ); let retryNum: number | undefined = undefined; try { const retryNumHeader = request.headers.get("x-slack-retry-num"); if (retryNumHeader) { retryNum = Number.parseInt(retryNumHeader); } else if (this.socketMode && body.retry_attempt) { retryNum = Number.parseInt(body.retry_attempt); } // deno-lint-ignore no-unused-vars } catch (e) { // Ignore an exception here } const retryReason = request.headers.get("x-slack-retry-reason") ?? body.retry_reason; const preAuthorizeRequest: PreAuthorizeSlackMiddlwareRequest<E> = { body, rawBody, retryNum, retryReason, context: builtBaseContext(body), env: this.env, headers: request.headers, }; if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log(`*** Received request body ***\n ${prettyPrint(body)}`); } for (const middlware of this.preAuthorizeMiddleware) { const response = await middlware(preAuthorizeRequest); if (response) { return toCompleteResponse(response); } } const authorizeResult: AuthorizeResult = await this.authorize( preAuthorizeRequest ); const authorizedContext: SlackAppContext = { ...preAuthorizeRequest.context, authorizeResult, client: new SlackAPIClient(authorizeResult.botToken, { logLevel: this.env.SLACK_LOGGING_LEVEL, }), botToken: authorizeResult.botToken, botId: authorizeResult.botId, botUserId: authorizeResult.botUserId, userToken: authorizeResult.userToken, }; if (authorizedContext.channelId) { const context = authorizedContext as SlackAppContextWithChannelId; const client = new SlackAPIClient(context.botToken); context.say = async (params) => await client.chat.postMessage({ channel: context.channelId, ...params, }); } if (authorizedContext.responseUrl) { const responseUrl = authorizedContext.responseUrl; // deno-lint-ignore require-await (authorizedContext as SlackAppContextWithRespond).respond = async ( params ) => { return new ResponseUrlSender(responseUrl).call(params); }; } const baseRequest: SlackMiddlwareRequest<E> = { ...preAuthorizeRequest, context: authorizedContext, }; for (const middlware of this.postAuthorizeMiddleware) { const response = await middlware(baseRequest); if (response) { return toCompleteResponse(response); } } const payload = body as SlackRequestBody; if (body.type === PayloadType.EventsAPI) { // Events API const slackRequest: SlackRequest<E, SlackEvent<string>> = { payload: body.event, ...baseRequest, }; for (const matcher of this.#events) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (!body.type && body.command) { // Slash commands const slackRequest: SlackRequest<E, SlashCommand> = { payload: body as SlashCommand, ...baseRequest, }; for (const matcher of this.#slashCommands) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (body.type === PayloadType.GlobalShortcut) { // Global shortcuts const slackRequest: SlackRequest<E, GlobalShortcut> = { payload: body as GlobalShortcut, ...baseRequest, }; for (const matcher of this.#globalShorcuts) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (body.type === PayloadType.MessageShortcut) { // Message shortcuts const slackRequest: SlackRequest<E, MessageShortcut> = { payload: body as MessageShortcut, ...baseRequest, }; for (const matcher of this.#messageShorcuts) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (body.type === PayloadType.BlockAction) { // Block actions // deno-lint-ignore no-explicit-any const slackRequest: SlackRequest<E, BlockAction<any>> = { // deno-lint-ignore no-explicit-any payload: body as BlockAction<any>, ...baseRequest, }; for (const matcher of this.#blockActions) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (body.type === PayloadType.BlockSuggestion) { // Block suggestions const slackRequest: SlackRequest<E, BlockSuggestion> = { payload: body as BlockSuggestion, ...baseRequest, }; for (const matcher of this.#blockSuggestions) { const handler = matcher(payload); if (handler) { // Note that the only way to respond to a block_suggestion request // is to send an HTTP response with options/option_groups. // Thus, we don't support lazy handlers for this pattern. const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (body.type === PayloadType.ViewSubmission) { // View submissions const slackRequest: SlackRequest<E, ViewSubmission> = { payload: body as ViewSubmission, ...baseRequest, }; for (const matcher of this.#viewSubmissions) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } else if (body.type === PayloadType.ViewClosed) { // View closed const slackRequest: SlackRequest<E, ViewClosed> = { payload: body as ViewClosed, ...baseRequest, }; for (const matcher of this.#viewClosed) { const handler = matcher(payload); if (handler) { ctx.waitUntil(handler.lazy(slackRequest)); const slackResponse = await handler.ack(slackRequest); if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) { console.log( `*** Slack response ***\n${prettyPrint(slackResponse)}` ); } return toCompleteResponse(slackResponse); } } } // TODO: Add code suggestion here console.log( `*** No listener found ***\n${JSON.stringify(baseRequest.body)}` ); return new Response("No listener found", { status: 404 }); } return new Response("Invalid signature", { status: 401 }); } } export type StringOrRegExp = string | RegExp; export type EventRequest<E extends SlackAppEnv, T> = Extract< AnySlackEventWithChannelId, { type: T } > extends never ? SlackRequest<E, Extract<AnySlackEvent, { type: T }>> : SlackRequestWithChannelId< E, Extract<AnySlackEventWithChannelId, { type: T }> >; export type MessageEventPattern = string | RegExp | undefined; export type MessageEventRequest< E extends SlackAppEnv, ST extends string | undefined > = SlackRequestWithChannelId< E, Extract<AnySlackEventWithChannelId, { subtype: ST }> >; export type MessageEventSubtypes = | undefined | "bot_message" | "thread_broadcast" | "file_share"; export type MessageEventHandler<E extends SlackAppEnv> = ( req: MessageEventRequest<E, MessageEventSubtypes> ) => Promise<void>; export const noopLazyListener = async () => {};
src/app.ts
seratch-slack-edge-c75c224
[ { "filename": "src/request/payload/event.ts", "retrieved_chunk": " | SharedChannelInviteApprovedEvent\n | SharedChannelInviteDeclinedEvent\n | StarAddedEvent\n | StarRemovedEvent;\nexport interface SlackEvent<Type extends string> {\n type: Type;\n subtype?: string;\n}\nexport interface AppRequestedEvent extends SlackEvent<\"app_requested\"> {\n type: \"app_requested\";", "score": 0.8259556889533997 }, { "filename": "src/request/payload/event.ts", "retrieved_chunk": " api_app_id: string;\n}\nexport interface AppUninstalledEvent extends SlackEvent<\"app_uninstalled\"> {\n type: \"app_uninstalled\";\n}\nexport interface ChannelArchiveEvent extends SlackEvent<\"channel_archive\"> {\n type: \"channel_archive\";\n channel: string;\n user: string;\n is_moved?: number;", "score": 0.8155679702758789 }, { "filename": "src/middleware/built-in-middleware.ts", "retrieved_chunk": " if (req.body.event) {\n if (eventTypesToKeep.includes(req.body.event.type)) {\n return;\n }\n if (\n req.context.authorizeResult.botId === req.body.event.bot_id ||\n req.context.authorizeResult.botUserId === req.context.userId\n ) {\n return { status: 200, body: \"\" };\n }", "score": 0.8085384368896484 }, { "filename": "src/request/request-body.ts", "retrieved_chunk": "export interface SlackRequestBody {\n type?: string;\n // slash commands\n command?: string;\n // event_callback\n event?: {\n type: string;\n subtype?: string;\n text?: string;\n };", "score": 0.802403450012207 }, { "filename": "src/socket-mode/socket-mode-client.ts", "retrieved_chunk": " console.info(`Completed a lazy listener execution: ${res}`);\n })\n .catch((err) => {\n console.error(`Failed to run a lazy listener: ${err}`);\n });\n },\n };\n const response = await app.run(request, context);\n // deno-lint-ignore no-explicit-any\n let ack: any = { envelope_id: data.envelope_id };", "score": 0.8018581867218018 } ]
typescript
EventsAPI || !body.event) {
/* eslint-disable @typescript-eslint/no-unsafe-argument */ /* eslint-disable @next/next/no-img-element */ import { Button, Group, FileInput, TextInput, Title, Stack, } from "@mantine/core"; import { useForm } from "@mantine/form"; import { useDisclosure } from "@mantine/hooks"; import { IconCheck, IconEdit, IconLetterX } from "@tabler/icons-react"; import { type NextPage } from "next"; import Head from "next/head"; import { useRouter } from "next/router"; import { useState } from "react"; import AdminDashboardLayout from "~/components/layouts/admin-dashboard-layout"; import { api } from "~/utils/api"; import { getImageUrl } from "~/utils/getImageUrl"; async function uploadFileToS3({ getPresignedUrl, file, }: { getPresignedUrl: () => Promise<{ url: string; fields: Record<string, string>; }>; file: File; }) { const { url, fields } = await getPresignedUrl(); const data: Record<string, any> = { ...fields, "Content-Type": file.type, file, }; const formData = new FormData(); for (const name in data) { formData.append(name, data[name]); } await fetch(url, { method: "POST", body: formData, }); } const Courses: NextPage = () => { const router = useRouter(); const courseId = router.query.courseId as string; const updateCourseMutation = api.course.updateCourse.useMutation(); const createSectionMutation = api.course.createSection.useMutation(); const deleteSection = api.course.deleteSection.useMutation(); const swapSections = api.course.swapSections.useMutation(); const createPresignedUrlMutation = api.course.createPresignedUrl.useMutation(); const createPresignedUrlForVideoMutation = api.course.createPresignedUrlForVideo.useMutation(); const updateTitleForm = useForm({ initialValues: { title: "", }, }); const newSectionForm = useForm({ initialValues: { title: "", }, }); const [file, setFile] = useState<File | null>(null); const [newSection, setNewSection] = useState<File | null>(null); const courseQuery = api.course.getCourseById.useQuery( { courseId, }, { enabled: !!courseId, onSuccess(data) { updateTitleForm.setFieldValue("title", data?.title ?? ""); }, } ); const [isEditingTitle, { open: setEditTitle, close: unsetEditTitle }] = useDisclosure(false); const uploadImage = async (e: React.FormEvent<HTMLFormElement>) => { e.preventDefault(); if (!file) return; await uploadFileToS3({ getPresignedUrl: () => createPresignedUrlMutation.mutateAsync({ courseId, }), file, }); setFile(null); await courseQuery.refetch(); // if (fileRef.current) { // fileRef.current.value = ""; // } }; // const onFileChange = (e: React.FormEvent<HTMLInputElement>) => { // setFile(e.currentTarget.files?.[0]); // }; const sortedSections = (courseQuery.data?.sections ?? []).sort( (a, b) => a.order - b.order ); return ( <> <Head> <title>Manage Courses</title> <meta name="description" content="Generated by create-t3-app" /> <link rel="icon" href="/favicon.ico" /> </Head> <main> <AdminDashboardLayout> <Stack spacing={"xl"}> {isEditingTitle ? ( <form onSubmit={updateTitleForm.onSubmit(async (values) => { await updateCourseMutation.mutateAsync({ ...values, courseId, }); await courseQuery.refetch(); unsetEditTitle(); })} > <Group> <TextInput withAsterisk required placeholder="name your course here" {...updateTitleForm.getInputProps("title")} /> <Button color="green" type="submit"> <IconCheck /> </Button> <Button color="gray" onClick={unsetEditTitle}> <IconLetterX /> </Button> </Group> </form> ) : ( <Group> <Title order={1}>{courseQuery.data?.title}</Title> <Button color="gray" onClick={setEditTitle}> <IconEdit size="1rem" /> </Button> </Group> )} <Group> {courseQuery.data && ( <img width="200" alt="an image of the course" src={
getImageUrl(courseQuery.data.imageId)}
/> )} <Stack sx={{ flex: 1 }}> <form onSubmit={uploadImage}> <FileInput label="Course Image" onChange={setFile} value={file} /> <Button disabled={!file} type="submit" variant="light" color="blue" mt="md" radius="md" > Upload Image </Button> </form> </Stack> </Group> <Stack> <Title order={2}>Sections </Title> {sortedSections.map((section, idx) => ( <Stack key={section.id} p="xl" sx={{ border: "1px solid white", }} > <Group> <Title sx={{ flex: 1 }} order={3}> {section.title} </Title> {idx > 0 && ( <Button type="submit" variant="light" color="white" mt="md" radius="md" onClick={async () => { const targetSection = sortedSections[idx - 1]; if (!targetSection) return; await swapSections.mutateAsync({ sectionIdSource: section.id, sectionIdTarget: targetSection.id, }); await courseQuery.refetch(); }} > Move Up </Button> )} {idx < sortedSections.length - 1 && ( <Button type="submit" variant="light" color="white" mt="md" radius="md" onClick={async () => { const targetSection = sortedSections[idx + 1]; if (!targetSection) return; await swapSections.mutateAsync({ sectionIdSource: section.id, sectionIdTarget: targetSection.id, }); await courseQuery.refetch(); }} > Move Down </Button> )} <Button type="submit" variant="light" color="red" mt="md" radius="md" onClick={async () => { if ( !confirm( "are you sure you want to delete this section?" ) ) return; await deleteSection.mutateAsync({ sectionId: section.id, }); await courseQuery.refetch(); }} > Delete </Button> </Group> <video width="400" controls> <source src={`http://localhost:9000/wdc-online-course-platform/${section.videoId}`} type="video/mp4" /> Your browser does not support HTML video. </video> </Stack> ))} <Stack p="xl" sx={{ border: "1px dashed white", }} > <form onSubmit={newSectionForm.onSubmit(async (values) => { if (!newSection) return; const section = await createSectionMutation.mutateAsync({ courseId: courseId, title: values.title, }); await uploadFileToS3({ getPresignedUrl: () => createPresignedUrlForVideoMutation.mutateAsync({ sectionId: section.id, }), file: newSection, }); setNewSection(null); await courseQuery.refetch(); newSectionForm.reset(); })} > <Stack spacing="xl"> <Title order={3}>Create New Section</Title> <TextInput withAsterisk required label="Section Title" placeholder="name your section" {...newSectionForm.getInputProps("title")} /> <FileInput label="Section Video" onChange={setNewSection} required value={newSection} /> <Button type="submit" variant="light" color="blue" mt="md" radius="md" > Create Section </Button> </Stack> </form> </Stack> </Stack> </Stack> </AdminDashboardLayout> </main> </> ); }; export default Courses;
src/pages/dashboard/courses/[courseId].tsx
webdevcody-online-course-platform-ee963ca
[ { "filename": "src/pages/dashboard/courses/index.tsx", "retrieved_chunk": " {/* <Badge color=\"pink\" variant=\"light\">\n On Sale\n </Badge> */}\n </Group>\n <Text size=\"sm\" color=\"dimmed\">\n {course.description}\n </Text>\n <Button\n component={Link}\n href={`/dashboard/courses/${course.id}`}", "score": 0.859919548034668 }, { "filename": "src/pages/dashboard/courses/index.tsx", "retrieved_chunk": "import Link from \"next/link\";\nimport { getImageUrl } from \"~/utils/getImageUrl\";\nexport function CourseCard({ course }: { course: Course }) {\n return (\n <MantineCard shadow=\"sm\" padding=\"lg\" radius=\"md\" withBorder>\n <MantineCard.Section>\n <Image src={getImageUrl(course.imageId)} height={160} alt=\"Norway\" />\n </MantineCard.Section>\n <Group position=\"apart\" mt=\"md\" mb=\"xs\">\n <Text weight={500}>{course.title}</Text>", "score": 0.8551280498504639 }, { "filename": "src/pages/dashboard/courses/index.tsx", "retrieved_chunk": " <Button onClick={openCreateCourseModal}>Create Course</Button>\n </Flex>\n <Grid>\n {courses.data?.map((course) => (\n <Grid.Col key={course.id} span={4}>\n <CourseCard course={course} />\n </Grid.Col>\n ))}\n </Grid>\n </AdminDashboardLayout>", "score": 0.8466578722000122 }, { "filename": "src/pages/dashboard/courses/index.tsx", "retrieved_chunk": " </Stack>\n <Group position=\"right\" mt=\"md\">\n <Button type=\"submit\">Create Course</Button>\n </Group>\n </form>\n </Modal>\n <main>\n <AdminDashboardLayout>\n <Flex justify=\"space-between\" align=\"center\" direction=\"row\">\n <h1>Manage Courses</h1>", "score": 0.8338977694511414 }, { "filename": "src/pages/dashboard/courses/index.tsx", "retrieved_chunk": " createCourseForm.reset();\n await courses.refetch();\n })}\n >\n <Stack>\n <TextInput\n withAsterisk\n label=\"Title\"\n required\n placeholder=\"name your course here\"", "score": 0.8304056525230408 } ]
typescript
getImageUrl(courseQuery.data.imageId)}
import { type Course } from "@prisma/client"; import { type NextPage } from "next"; import Head from "next/head"; import { useForm } from "@mantine/form"; import AdminDashboardLayout from "~/components/layouts/admin-dashboard-layout"; import { Card as MantineCard, Image, Text, Flex, Grid, Button, Group, Modal, TextInput, Stack, Textarea, } from "@mantine/core"; import { useDisclosure } from "@mantine/hooks"; import { api } from "~/utils/api"; import Link from "next/link"; import { getImageUrl } from "~/utils/getImageUrl"; export function CourseCard({ course }: { course: Course }) { return ( <MantineCard shadow="sm" padding="lg" radius="md" withBorder> <MantineCard.Section> <Image src={getImageUrl(course.imageId)} height={160} alt="Norway" /> </MantineCard.Section> <Group position="apart" mt="md" mb="xs"> <Text weight={500}>{course.title}</Text> {/* <Badge color="pink" variant="light"> On Sale </Badge> */} </Group> <Text size="sm" color="dimmed"> {course.description} </Text> <Button component={Link} href={`/dashboard/courses/${course.id}`} variant="light" color="blue" fullWidth mt="md" radius="md" > Manage </Button> </MantineCard> ); } const Courses: NextPage = () => { const
courses = api.course.getCourses.useQuery();
const createCourseMutation = api.course.createCourse.useMutation(); const [ isCreateCourseModalOpen, { open: openCreateCourseModal, close: closeCreateCourseModal }, ] = useDisclosure(false); const createCourseForm = useForm({ initialValues: { title: "", description: "", }, }); return ( <> <Head> <title>Manage Courses</title> <meta name="description" content="Generated by create-t3-app" /> <link rel="icon" href="/favicon.ico" /> </Head> <Modal opened={isCreateCourseModalOpen} onClose={closeCreateCourseModal} title="Create Course" > <form onSubmit={createCourseForm.onSubmit(async (values) => { await createCourseMutation.mutateAsync(values); closeCreateCourseModal(); createCourseForm.reset(); await courses.refetch(); })} > <Stack> <TextInput withAsterisk label="Title" required placeholder="name your course here" {...createCourseForm.getInputProps("title")} /> <Textarea withAsterisk minRows={6} required label="Description" placeholder="describe your course a bit" {...createCourseForm.getInputProps("description")} /> </Stack> <Group position="right" mt="md"> <Button type="submit">Create Course</Button> </Group> </form> </Modal> <main> <AdminDashboardLayout> <Flex justify="space-between" align="center" direction="row"> <h1>Manage Courses</h1> <Button onClick={openCreateCourseModal}>Create Course</Button> </Flex> <Grid> {courses.data?.map((course) => ( <Grid.Col key={course.id} span={4}> <CourseCard course={course} /> </Grid.Col> ))} </Grid> </AdminDashboardLayout> </main> </> ); }; export default Courses;
src/pages/dashboard/courses/index.tsx
webdevcody-online-course-platform-ee963ca
[ { "filename": "src/pages/dashboard/courses/[courseId].tsx", "retrieved_chunk": " await fetch(url, {\n method: \"POST\",\n body: formData,\n });\n}\nconst Courses: NextPage = () => {\n const router = useRouter();\n const courseId = router.query.courseId as string;\n const updateCourseMutation = api.course.updateCourse.useMutation();\n const createSectionMutation = api.course.createSection.useMutation();", "score": 0.895056962966919 }, { "filename": "src/pages/dashboard/courses/[courseId].tsx", "retrieved_chunk": " </form>\n </Stack>\n </Stack>\n </Stack>\n </AdminDashboardLayout>\n </main>\n </>\n );\n};\nexport default Courses;", "score": 0.8640353083610535 }, { "filename": "src/pages/dashboard/courses/[courseId].tsx", "retrieved_chunk": " const sortedSections = (courseQuery.data?.sections ?? []).sort(\n (a, b) => a.order - b.order\n );\n return (\n <>\n <Head>\n <title>Manage Courses</title>\n <meta name=\"description\" content=\"Generated by create-t3-app\" />\n <link rel=\"icon\" href=\"/favicon.ico\" />\n </Head>", "score": 0.859039843082428 }, { "filename": "src/components/shell/_user.tsx", "retrieved_chunk": " Text,\n Box,\n useMantineTheme,\n rem,\n Button,\n Menu,\n} from \"@mantine/core\";\nimport { signIn, signOut, useSession } from \"next-auth/react\";\nexport function User() {\n const theme = useMantineTheme();", "score": 0.8394746780395508 }, { "filename": "src/pages/dashboard/courses/[courseId].tsx", "retrieved_chunk": "import { useForm } from \"@mantine/form\";\nimport { useDisclosure } from \"@mantine/hooks\";\nimport { IconCheck, IconEdit, IconLetterX } from \"@tabler/icons-react\";\nimport { type NextPage } from \"next\";\nimport Head from \"next/head\";\nimport { useRouter } from \"next/router\";\nimport { useState } from \"react\";\nimport AdminDashboardLayout from \"~/components/layouts/admin-dashboard-layout\";\nimport { api } from \"~/utils/api\";\nimport { getImageUrl } from \"~/utils/getImageUrl\";", "score": 0.8331347703933716 } ]
typescript
courses = api.course.getCourses.useQuery();
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 }) => ({ ...session, user: { ...session.user, id: user.id, }, }), },
adapter: PrismaAdapter(prisma), providers: [ GoogleProvider({
clientId: env.GOOGLE_CLIENT_ID, clientSecret: env.GOOGLE_CLIENT_SECRET, }), /** * ...add more providers here. * * Most other providers require a bit more work than the Discord provider. For example, the * GitHub provider requires you to add the `refresh_token_expires_in` field to the Account * model. Refer to the NextAuth.js docs for the provider you want to use. Example: * * @see https://next-auth.js.org/providers/github */ ], }; /** * Wrapper for `getServerSession` so that you don't need to import the `authOptions` in every file. * * @see https://next-auth.js.org/configuration/nextjs */ export const getServerAuthSession = (ctx: { req: GetServerSidePropsContext["req"]; res: GetServerSidePropsContext["res"]; }) => { return getServerSession(ctx.req, ctx.res, authOptions); };
src/server/auth.ts
webdevcody-online-course-platform-ee963ca
[ { "filename": "src/server/api/routers/course.ts", "retrieved_chunk": " sections: true,\n },\n });\n }),\n getCourses: protectedProcedure.query(({ ctx }) => {\n return ctx.prisma.course.findMany({\n where: {\n userId: ctx.session.user.id,\n },\n });", "score": 0.8027287721633911 }, { "filename": "src/components/shell/_user.tsx", "retrieved_chunk": " const user = useSession();\n return (\n <Box\n sx={{\n paddingTop: theme.spacing.sm,\n borderTop: `${rem(1)} solid ${\n theme.colorScheme === \"dark\"\n ? theme.colors.dark[4]\n : theme.colors.gray[2]\n }`,", "score": 0.7950454950332642 }, { "filename": "src/server/api/routers/course.ts", "retrieved_chunk": " },\n });\n return newCourse;\n }),\n updateCourse: protectedProcedure\n .input(z.object({ title: z.string(), courseId: z.string() }))\n .mutation(async ({ ctx, input }) => {\n const userId = ctx.session.user.id;\n await ctx.prisma.course.updateMany({\n where: {", "score": 0.7942917346954346 }, { "filename": "src/server/db.ts", "retrieved_chunk": " });\nif (env.NODE_ENV !== \"production\") globalForPrisma.prisma = prisma;", "score": 0.7939406037330627 }, { "filename": "src/server/api/routers/course.ts", "retrieved_chunk": " .input(z.object({ courseId: z.string() }))\n .mutation(async ({ ctx, input }) => {\n // const userId = ctx.session.user.id;\n const course = await ctx.prisma.course.findUnique({\n where: {\n id: input.courseId,\n },\n });\n if (!course) {\n throw new TRPCError({", "score": 0.7919312119483948 } ]
typescript
adapter: PrismaAdapter(prisma), providers: [ GoogleProvider({
import { z } from "zod"; import { createTRPCRouter, protectedProcedure } from "~/server/api/trpc"; import { S3Client } from "@aws-sdk/client-s3"; import { createPresignedPost } from "@aws-sdk/s3-presigned-post"; import { env } from "~/env.mjs"; import { TRPCError } from "@trpc/server"; import { v4 as uuidv4 } from "uuid"; const UPLOAD_MAX_FILE_SIZE = 1000000; const s3Client = new S3Client({ region: "us-east-1", endpoint: "http://localhost:9000", forcePathStyle: true, credentials: { accessKeyId: "S3RVER", secretAccessKey: "S3RVER", }, }); export const courseRouter = createTRPCRouter({ getCourseById: protectedProcedure .input( z.object({ courseId: z.string(), }) ) .query(({ ctx, input }) => { return ctx.prisma.course.findUnique({ where: { id: input.courseId, }, include: { sections: true, }, }); }), getCourses: protectedProcedure.query(({ ctx }) => { return ctx.prisma.course.findMany({ where: { userId: ctx.session.user.id, }, }); }), createCourse: protectedProcedure .input(z.object({ title: z.string(), description: z.string() })) .mutation(async ({ ctx, input }) => { const userId = ctx.session.user.id; const newCourse = await ctx.prisma.course.create({ data: { title: input.title, description: input.description, userId: userId, }, }); return newCourse; }), updateCourse: protectedProcedure .input(z.object({ title: z.string(), courseId: z.string() })) .mutation(async ({ ctx, input }) => { const userId = ctx.session.user.id; await ctx.prisma.course.updateMany({ where: { id: input.courseId, userId, }, data: { title: input.title, }, }); return { status: "updated" }; }), createPresignedUrl: protectedProcedure .input(z.object({ courseId: z.string() })) .mutation(async ({ ctx, input }) => { // const userId = ctx.session.user.id; const course = await ctx.prisma.course.findUnique({ where: { id: input.courseId, }, }); if (!course) { throw new TRPCError({ code: "NOT_FOUND", message: "the course does not exist", }); } const imageId = uuidv4(); await ctx.prisma.course.update({ where: { id: course.id, }, data: { imageId, }, }); return createPresignedPost(s3Client, {
Bucket: env.NEXT_PUBLIC_S3_BUCKET_NAME, Key: imageId, Fields: {
key: imageId, }, Conditions: [ ["starts-with", "$Content-Type", "image/"], ["content-length-range", 0, UPLOAD_MAX_FILE_SIZE], ], }); }), createSection: protectedProcedure .input(z.object({ courseId: z.string(), title: z.string() })) .mutation(async ({ ctx, input }) => { const videoId = uuidv4(); return await ctx.prisma.section.create({ data: { videoId, title: input.title, courseId: input.courseId, }, }); }), deleteSection: protectedProcedure .input(z.object({ sectionId: z.string() })) .mutation(async ({ ctx, input }) => { const section = await ctx.prisma.section.delete({ where: { id: input.sectionId, }, }); if (!section) { throw new TRPCError({ code: "NOT_FOUND", message: "section not found", }); } if (!section.courseId) { throw new TRPCError({ code: "NOT_FOUND", message: "section has no course", }); } const course = await ctx.prisma.course.findUnique({ where: { id: section.courseId, }, }); if (course?.userId !== ctx.session.user.id) { throw new TRPCError({ code: "FORBIDDEN", message: "you do not have access to this course", }); } return section; }), swapSections: protectedProcedure .input( z.object({ sectionIdSource: z.string(), sectionIdTarget: z.string() }) ) .mutation(async ({ ctx, input }) => { const sectionSource = await ctx.prisma.section.findUnique({ where: { id: input.sectionIdSource, }, }); if (!sectionSource) { throw new TRPCError({ code: "NOT_FOUND", message: "the source section does not exist", }); } const sectionTarget = await ctx.prisma.section.findUnique({ where: { id: input.sectionIdTarget, }, }); if (!sectionTarget) { throw new TRPCError({ code: "NOT_FOUND", message: "the target section does not exist", }); } await ctx.prisma.section.update({ where: { id: input.sectionIdSource, }, data: { order: sectionTarget.order, }, }); await ctx.prisma.section.update({ where: { id: input.sectionIdTarget, }, data: { order: sectionSource.order, }, }); }), createPresignedUrlForVideo: protectedProcedure .input(z.object({ sectionId: z.string() })) .mutation(async ({ ctx, input }) => { const section = await ctx.prisma.section.findUnique({ where: { id: input.sectionId, }, }); if (!section) { throw new TRPCError({ code: "NOT_FOUND", message: "the section does not exist", }); } if (!section.courseId) { throw new TRPCError({ code: "NOT_FOUND", message: "the section has no course", }); } const course = await ctx.prisma.course.findUnique({ where: { id: section.courseId, }, }); if (course?.userId !== ctx.session.user.id) { throw new TRPCError({ code: "FORBIDDEN", message: "you do not have access to this course", }); } return createPresignedPost(s3Client, { Bucket: env.NEXT_PUBLIC_S3_BUCKET_NAME, Key: section.videoId, Fields: { key: section.videoId, }, Conditions: [ ["starts-with", "$Content-Type", "image/"], ["content-length-range", 0, UPLOAD_MAX_FILE_SIZE], ], }); }), });
src/server/api/routers/course.ts
webdevcody-online-course-platform-ee963ca
[ { "filename": "src/pages/dashboard/courses/[courseId].tsx", "retrieved_chunk": " courseId: courseId,\n title: values.title,\n });\n await uploadFileToS3({\n getPresignedUrl: () =>\n createPresignedUrlForVideoMutation.mutateAsync({\n sectionId: section.id,\n }),\n file: newSection,\n });", "score": 0.852674663066864 }, { "filename": "src/pages/dashboard/courses/[courseId].tsx", "retrieved_chunk": " width=\"200\"\n alt=\"an image of the course\"\n src={getImageUrl(courseQuery.data.imageId)}\n />\n )}\n <Stack sx={{ flex: 1 }}>\n <form onSubmit={uploadImage}>\n <FileInput\n label=\"Course Image\"\n onChange={setFile}", "score": 0.8341711759567261 }, { "filename": "src/pages/dashboard/courses/[courseId].tsx", "retrieved_chunk": " useDisclosure(false);\n const uploadImage = async (e: React.FormEvent<HTMLFormElement>) => {\n e.preventDefault();\n if (!file) return;\n await uploadFileToS3({\n getPresignedUrl: () =>\n createPresignedUrlMutation.mutateAsync({\n courseId,\n }),\n file,", "score": 0.8336523175239563 }, { "filename": "src/pages/dashboard/courses/[courseId].tsx", "retrieved_chunk": " const { url, fields } = await getPresignedUrl();\n const data: Record<string, any> = {\n ...fields,\n \"Content-Type\": file.type,\n file,\n };\n const formData = new FormData();\n for (const name in data) {\n formData.append(name, data[name]);\n }", "score": 0.824459433555603 }, { "filename": "src/pages/dashboard/courses/[courseId].tsx", "retrieved_chunk": " });\n const newSectionForm = useForm({\n initialValues: {\n title: \"\",\n },\n });\n const [file, setFile] = useState<File | null>(null);\n const [newSection, setNewSection] = useState<File | null>(null);\n const courseQuery = api.course.getCourseById.useQuery(\n {", "score": 0.8115779161453247 } ]
typescript
Bucket: env.NEXT_PUBLIC_S3_BUCKET_NAME, Key: imageId, Fields: {
import '@logseq/libs'; import { OpenAI } from 'langchain/llms/openai'; import { PromptTemplate } from 'langchain/prompts'; import { CustomListOutputParser, StructuredOutputParser, } from 'langchain/output_parsers'; import * as presetPrompts from './prompts'; import { IPrompt, PromptOutputType } from './prompts/type'; import settings, { ISettings } from './settings'; import { getBlockContent } from './utils'; function getPrompts() { const { customPrompts } = logseq.settings as unknown as ISettings; const prompts = [...Object.values(presetPrompts)]; if (customPrompts.enable) { prompts.push(...customPrompts.prompts); } return prompts; } function main() { const { apiKey, basePath, model: modelName, tag: tagName, } = logseq.settings as unknown as ISettings; const tag = ` #${tagName}`; const prompts = getPrompts(); const model = new OpenAI( { openAIApiKey: apiKey, modelName, }, { basePath }, ); prompts.map(({ name, prompt: t, output, format }: IPrompt) => { logseq.Editor.registerSlashCommand( name, async ({ uuid }: { uuid: string }) => { const block = await logseq.Editor.getBlock(uuid, { includeChildren: true, }); if (!block) { return; } const content = await getBlockContent(block); const listed = Array.isArray(format); const structured = typeof format === 'object' && !listed; let parser; if (structured) { parser = StructuredOutputParser.fromNamesAndDescriptions( format as { [key: string]: string }, ); } else if (listed) { parser = new CustomListOutputParser({ separator: '\n' }); } const template = t.replace('{{text}}', '{content}'); const prompt = parser ? new PromptTemplate({ template: template + '\n{format_instructions}', inputVariables: ['content'], partialVariables: { format_instructions: parser.getFormatInstructions(), }, }) : new PromptTemplate({ template, inputVariables: ['content'], }); const input = await prompt.format({ content }); const response = await model.call(input); switch (output) { case PromptOutputType.property: { let content = `${block?.content}${tag}\n`; if (!parser) { content += `${name.toLowerCase()}:: ${response}`; } else if (structured) { content += `${name.toLowerCase()}:: `; const record = await parser.parse(response); content += Object.entries(record) .map(([key, value]) => `${key}: ${value}`) .join(' '); } else if (listed) { content += `${name.toLowerCase()}:: `; const list = (await parser.parse(response)) as string[]; content += list.join(', '); } await logseq.Editor.updateBlock(uuid, content); break; } case PromptOutputType.insert: { if (!parser) { await logseq.Editor.insertBlock(uuid, `${response}${tag}`); } else if (structured) { const record = await parser.parse(response); await logseq.Editor.updateBlock( uuid, `${block?.content}${tag}\n`, ); for await (const [key, value] of Object.entries(record)) { await logseq.Editor.insertBlock(uuid, `${key}: ${value}`); } } else if (listed) { await logseq.Editor.updateBlock( uuid, `${block?.content}${tag}\n`, ); const record = (await parser.parse(response)) as string[]; for await (const item of record) { await logseq.Editor.insertBlock(uuid, item); } } break; } case PromptOutputType.replace: await logseq.Editor.updateBlock(uuid, `${response}${tag}`); break; } }, ); logseq.onSettingsChanged(() => main()); }); }
logseq.useSettingsSchema(settings).ready(main).catch(console.error);
src/main.tsx
ahonn-logseq-plugin-ai-assistant-b7a08df
[ { "filename": "src/settings.ts", "retrieved_chunk": " },\n];\nexport default settings;", "score": 0.7769268751144409 }, { "filename": "src/settings.ts", "retrieved_chunk": "import { SettingSchemaDesc } from '@logseq/libs/dist/LSPlugin.user';\nimport { IPrompt } from './prompts/type';\nexport interface ISettings {\n apiKey: string;\n basePath: string;\n model: string;\n tag: string;\n customPrompts: {\n enable: boolean;\n prompts: IPrompt[];", "score": 0.7709803581237793 }, { "filename": "src/settings.ts", "retrieved_chunk": " };\n}\nconst settings: SettingSchemaDesc[] = [\n {\n key: 'apiKey',\n type: 'string',\n title: 'API Key',\n description: 'Enter your OpenAI API key.',\n default: '',\n },", "score": 0.7681758999824524 }, { "filename": "src/utils.ts", "retrieved_chunk": "import { BlockEntity } from '@logseq/libs/dist/LSPlugin.user';\nexport async function getBlockContent(block: BlockEntity) {\n let content = block.content ?? '';\n const childrens = [block.children];\n let level = 1;\n while (childrens.length > 0) {\n const children = childrens.shift();\n for (const child of children!) {\n content += '\\n' + '\\t'.repeat(level) + '- ' + (child as BlockEntity).content;\n }", "score": 0.7662215232849121 }, { "filename": "src/prompts/ask-ai.ts", "retrieved_chunk": " output: PromptOutputType.insert,\n};", "score": 0.7555329203605652 } ]
typescript
logseq.useSettingsSchema(settings).ready(main).catch(console.error);
import '@logseq/libs'; import { OpenAI } from 'langchain/llms/openai'; import { PromptTemplate } from 'langchain/prompts'; import { CustomListOutputParser, StructuredOutputParser, } from 'langchain/output_parsers'; import * as presetPrompts from './prompts'; import { IPrompt, PromptOutputType } from './prompts/type'; import settings, { ISettings } from './settings'; import { getBlockContent } from './utils'; function getPrompts() { const { customPrompts } = logseq.settings as unknown as ISettings; const prompts = [...Object.values(presetPrompts)]; if (customPrompts.enable) { prompts.push(...customPrompts.prompts); } return prompts; } function main() { const { apiKey, basePath, model: modelName, tag: tagName, } = logseq.settings as unknown as ISettings; const tag = ` #${tagName}`; const prompts = getPrompts(); const model = new OpenAI( { openAIApiKey: apiKey, modelName, }, { basePath }, ); prompts.map(({ name, prompt: t, output, format }: IPrompt) => { logseq.Editor.registerSlashCommand( name, async ({ uuid }: { uuid: string }) => { const block = await logseq.Editor.getBlock(uuid, { includeChildren: true, }); if (!block) { return; } const content = await getBlockContent(block); const listed = Array.isArray(format); const structured = typeof format === 'object' && !listed; let parser; if (structured) { parser = StructuredOutputParser.fromNamesAndDescriptions( format as { [key: string]: string }, ); } else if (listed) { parser = new CustomListOutputParser({ separator: '\n' }); } const template = t.replace('{{text}}', '{content}'); const prompt = parser ? new PromptTemplate({ template: template + '\n{format_instructions}', inputVariables: ['content'], partialVariables: { format_instructions: parser.getFormatInstructions(), }, }) : new PromptTemplate({ template, inputVariables: ['content'], }); const input = await prompt.format({ content }); const response = await model.call(input); switch (output) {
case PromptOutputType.property: {
let content = `${block?.content}${tag}\n`; if (!parser) { content += `${name.toLowerCase()}:: ${response}`; } else if (structured) { content += `${name.toLowerCase()}:: `; const record = await parser.parse(response); content += Object.entries(record) .map(([key, value]) => `${key}: ${value}`) .join(' '); } else if (listed) { content += `${name.toLowerCase()}:: `; const list = (await parser.parse(response)) as string[]; content += list.join(', '); } await logseq.Editor.updateBlock(uuid, content); break; } case PromptOutputType.insert: { if (!parser) { await logseq.Editor.insertBlock(uuid, `${response}${tag}`); } else if (structured) { const record = await parser.parse(response); await logseq.Editor.updateBlock( uuid, `${block?.content}${tag}\n`, ); for await (const [key, value] of Object.entries(record)) { await logseq.Editor.insertBlock(uuid, `${key}: ${value}`); } } else if (listed) { await logseq.Editor.updateBlock( uuid, `${block?.content}${tag}\n`, ); const record = (await parser.parse(response)) as string[]; for await (const item of record) { await logseq.Editor.insertBlock(uuid, item); } } break; } case PromptOutputType.replace: await logseq.Editor.updateBlock(uuid, `${response}${tag}`); break; } }, ); logseq.onSettingsChanged(() => main()); }); } logseq.useSettingsSchema(settings).ready(main).catch(console.error);
src/main.tsx
ahonn-logseq-plugin-ai-assistant-b7a08df
[ { "filename": "src/prompts/type.ts", "retrieved_chunk": "export interface IPrompt {\n name: string;\n prompt: string;\n output: PromptOutputType;\n format?: string | [] | { [key: string]: string };\n}\nexport enum PromptOutputType {\n property = 'property',\n replace = 'replace',\n insert = 'insert',", "score": 0.8547694683074951 }, { "filename": "src/prompts/summarize.ts", "retrieved_chunk": "import { IPrompt, PromptOutputType } from './type';\nexport const Summarize: IPrompt = {\n name: 'Summarize',\n prompt: `\n Please provide a concise summary of the following text:\n \"\"\"\n {content}\n \"\"\"\n `,\n output: PromptOutputType.property,", "score": 0.8297693729400635 }, { "filename": "src/prompts/generate-ideas.ts", "retrieved_chunk": "import { IPrompt, PromptOutputType } from \"./type\";\nexport const GenerateIdeas: IPrompt = {\n name: 'Generate Ideas',\n prompt: `\n Please creative ideas related to the following topic:\n \"\"\"\n {content}\n \"\"\"\n `,\n output: PromptOutputType.insert,", "score": 0.8249740600585938 }, { "filename": "src/prompts/ask-ai.ts", "retrieved_chunk": " output: PromptOutputType.insert,\n};", "score": 0.8208903670310974 }, { "filename": "src/prompts/make-shorter.ts", "retrieved_chunk": "import { IPrompt, PromptOutputType } from \"./type\";\nexport const makeShorter: IPrompt = {\n name: 'Make Shorter',\n prompt: `\n Please shorten the following text while maintaining its key points:\n \"\"\"\n {content}\n \"\"\"\n `,\n output: PromptOutputType.replace,", "score": 0.8207554221153259 } ]
typescript
case PromptOutputType.property: {
import { ExecutionContext, NoopExecutionContext } from "./execution-context"; import { SlackApp } from "./app"; import { SlackOAuthEnv } from "./app-env"; import { InstallationStore } from "./oauth/installation-store"; import { NoStorageStateStore, StateStore } from "./oauth/state-store"; import { renderCompletionPage, renderStartPage, } from "./oauth/oauth-page-renderer"; import { generateAuthorizeUrl } from "./oauth/authorize-url-generator"; import { parse as parseCookie } from "./cookie"; import { SlackAPIClient, OAuthV2AccessResponse, OpenIDConnectTokenResponse, } from "slack-web-api-client"; import { toInstallation } from "./oauth/installation"; import { AfterInstallation, BeforeInstallation, OnFailure, OnStateValidationError, defaultOnFailure, defaultOnStateValidationError, } from "./oauth/callback"; import { OpenIDConnectCallback, defaultOpenIDConnectCallback, } from "./oidc/callback"; import { generateOIDCAuthorizeUrl } from "./oidc/authorize-url-generator"; import { InstallationError, MissingCode, CompletionPageError, InstallationStoreError, OpenIDConnectError, } from "./oauth/error-codes"; export interface SlackOAuthAppOptions<E extends SlackOAuthEnv> { env: E; installationStore: InstallationStore<E>; stateStore?: StateStore; oauth?: { stateCookieName?: string; beforeInstallation?: BeforeInstallation; afterInstallation?: AfterInstallation; onFailure?: OnFailure; onStateValidationError?: OnStateValidationError; redirectUri?: string; }; oidc?: { stateCookieName?: string; callback: OpenIDConnectCallback; onFailure?: OnFailure; onStateValidationError?: OnStateValidationError; redirectUri?: string; }; routes?: { events: string; oauth: { start: string; callback: string }; oidc?: { start: string; callback: string }; }; } export class SlackOAuthApp<E extends SlackOAuthEnv> extends SlackApp<E> { public env: E; public installationStore: InstallationStore<E>; public stateStore: StateStore; public oauth: { stateCookieName?: string; beforeInstallation?: BeforeInstallation; afterInstallation?: AfterInstallation; onFailure: OnFailure; onStateValidationError: OnStateValidationError; redirectUri?: string; }; public oidc?: { stateCookieName?: string; callback: OpenIDConnectCallback; onFailure: OnFailure; onStateValidationError: OnStateValidationError; redirectUri?: string; }; public routes: { events: string; oauth: { start: string; callback: string }; oidc?: { start: string; callback: string }; }; constructor(options: SlackOAuthAppOptions<E>) { super({ env: options.env, authorize: options.installationStore.toAuthorize(), routes: { events: options.routes?.events ?? "/slack/events" }, }); this.env = options.env; this.installationStore = options.installationStore; this.stateStore = options.stateStore ?? new NoStorageStateStore(); this.oauth = { stateCookieName: options.oauth?.stateCookieName ?? "slack-app-oauth-state", onFailure: options.oauth?.onFailure ?? defaultOnFailure, onStateValidationError: options.oauth?.onStateValidationError ?? defaultOnStateValidationError, redirectUri: options.oauth?.redirectUri ?? this.env.SLACK_REDIRECT_URI, }; if (options.oidc) { this.oidc = { stateCookieName: options.oidc.stateCookieName ?? "slack-app-oidc-state", onFailure: options.oidc.onFailure ?? defaultOnFailure, onStateValidationError: options.oidc.onStateValidationError ?? defaultOnStateValidationError, callback: defaultOpenIDConnectCallback(this.env), redirectUri: options.oidc.redirectUri ?? this.env.SLACK_OIDC_REDIRECT_URI, }; } else { this.oidc = undefined; } this.routes = options.routes ? options.routes : { events: "/slack/events", oauth: { start: "/slack/install", callback: "/slack/oauth_redirect", }, oidc: { start: "/slack/login", callback: "/slack/login/callback", }, }; } async run( request: Request, ctx: ExecutionContext = new NoopExecutionContext() ): Promise<Response> { const url = new URL(request.url); if (request.method === "GET") { if (url.pathname === this.routes.oauth.start) { return await this.handleOAuthStartRequest(request); } else if (url.pathname === this.routes.oauth.callback) { return await this.handleOAuthCallbackRequest(request); } if (this.routes.oidc) { if (url.pathname === this.routes.oidc.start) { return await this.handleOIDCStartRequest(request); } else if (url.pathname === this.routes.oidc.callback) { return await this.handleOIDCCallbackRequest(request); } } } else if (request.method === "POST") { if (url.pathname === this.routes.events) { return await this.handleEventRequest(request, ctx); } } return new Response("Not found", { status: 404 }); } async handleEventRequest( request: Request, ctx: ExecutionContext ): Promise<Response> { return await super.handleEventRequest(request, ctx); } // deno-lint-ignore no-unused-vars async handleOAuthStartRequest(request: Request): Promise<Response> { const stateValue = await this.stateStore.issueNewState(); const authorizeUrl = generateAuthorizeUrl(stateValue, this.env); return new Response(renderStartPage(authorizeUrl), { status: 302, headers: { Location: authorizeUrl, "Set-Cookie": `${this.oauth.stateCookieName}=${stateValue}; Secure; HttpOnly; Path=/; Max-Age=300`, "Content-Type": "text/html; charset=utf-8", }, }); } async handleOAuthCallbackRequest(request: Request): Promise<Response> { // State parameter validation await this.#validateStateParameter( request, this.routes.oauth.start, this.oauth.stateCookieName! ); const { searchParams } = new URL(request.url); const code = searchParams.get("code"); if (!code) { return await this.oauth.onFailure( this.routes.oauth.start, MissingCode, request ); } const client = new SlackAPIClient(undefined, { logLevel: this.env.SLACK_LOGGING_LEVEL, }); let oauthAccess: OAuthV2AccessResponse | undefined; try { // Execute the installation process oauthAccess = await client.oauth.v2.access({ client_id: this.env.SLACK_CLIENT_ID, client_secret: this.env.SLACK_CLIENT_SECRET, redirect_uri: this.oauth.redirectUri, code, }); } catch (e) { console.log(e); return await this.oauth.onFailure( this.routes.oauth.start, InstallationError, request ); } try { // Store the installation data on this app side await this.installationStore.save(toInstallation(oauthAccess), request); } catch (e) { console.log(e); return await this.oauth.onFailure( this.routes.oauth.start, InstallationStoreError, request ); } try { // Build the completion page const authTest = await client.auth.test({ token: oauthAccess.access_token, }); const enterpriseUrl = authTest.url; return new Response( renderCompletionPage( oauthAccess.app_id!, oauthAccess.team?.id!, oauthAccess.is_enterprise_install, enterpriseUrl ), { status: 200, headers: { "Set-Cookie": `${this.oauth.stateCookieName}=deleted; Secure; HttpOnly; Path=/; Max-Age=0`, "Content-Type": "text/html; charset=utf-8", }, } ); } catch (e) { console.log(e); return await this.oauth.onFailure( this.routes.oauth.start, CompletionPageError, request ); } } // deno-lint-ignore no-unused-vars async handleOIDCStartRequest(request: Request): Promise<Response> { if (!this.oidc) { return new Response("Not found", { status: 404 }); } const stateValue = await this.stateStore.issueNewState(); const authorizeUrl = generateOIDCAuthorizeUrl(stateValue, this.env); return new Response(renderStartPage(authorizeUrl), { status: 302, headers: { Location: authorizeUrl, "Set-Cookie": `${this.oidc.stateCookieName}=${stateValue}; Secure; HttpOnly; Path=/; Max-Age=300`, "Content-Type": "text/html; charset=utf-8", }, }); } async handleOIDCCallbackRequest(request: Request): Promise<Response> { if (!this.oidc || !this.routes.oidc) { return new Response("Not found", { status: 404 }); } // State parameter validation await this.#validateStateParameter( request, this.routes.oidc.start, this.oidc.stateCookieName! ); const { searchParams } = new URL(request.url); const code = searchParams.get("code"); if (!code) { return await this.oidc.onFailure( this.routes.oidc.start, MissingCode, request ); } try { const client = new SlackAPIClient(undefined, { logLevel: this.env.SLACK_LOGGING_LEVEL, }); const apiResponse: OpenIDConnectTokenResponse = await client.openid.connect.token({ client_id: this.env.SLACK_CLIENT_ID, client_secret: this.env.SLACK_CLIENT_SECRET, redirect_uri: this.oidc.redirectUri, code, }); return await this.oidc.callback(apiResponse, request); } catch (e) { console.log(e); return await this.oidc.onFailure( this.routes.oidc.start, OpenIDConnectError, request ); } } async #validateStateParameter( request: Request, startPath: string, cookieName: string ) { const { searchParams } = new URL(request.url); const queryState = searchParams.get("state"); const
cookie = parseCookie(request.headers.get("Cookie") || "");
const cookieState = cookie[cookieName]; if ( queryState !== cookieState || !(await this.stateStore.consume(queryState)) ) { if (startPath === this.routes.oauth.start) { return await this.oauth.onStateValidationError(startPath, request); } else if ( this.oidc && this.routes.oidc && startPath === this.routes.oidc.start ) { return await this.oidc.onStateValidationError(startPath, request); } } } }
src/oauth-app.ts
seratch-slack-edge-c75c224
[ { "filename": "src/oauth/callback.ts", "retrieved_chunk": "export type OnStateValidationError = (\n startPath: string,\n req: Request\n) => Promise<Response>;\n// deno-lint-ignore require-await\nexport const defaultOnStateValidationError = async (\n startPath: string,\n // deno-lint-ignore no-unused-vars\n req: Request\n) => {", "score": 0.8204145431518555 }, { "filename": "src/oauth/callback.ts", "retrieved_chunk": " return new Response(renderErrorPage(startPath, InvalidStateParameter), {\n status: 400,\n headers: { \"Content-Type\": \"text/html; charset=utf-8\" },\n });\n};\nexport type OnFailure = (\n startPath: string,\n reason: OAuthErrorCode,\n req: Request\n) => Promise<Response>;", "score": 0.7938126921653748 }, { "filename": "src/app.ts", "retrieved_chunk": " ): Promise<Response> {\n // If the routes.events is missing, any URLs can work for handing requests from Slack\n if (this.routes.events) {\n const { pathname } = new URL(request.url);\n if (pathname !== this.routes.events) {\n return new Response(\"Not found\", { status: 404 });\n }\n }\n // To avoid the following warning by Cloudflware, parse the body as Blob first\n // Called .text() on an HTTP body which does not appear to be text ..", "score": 0.7869435548782349 }, { "filename": "src/request/request-parser.ts", "retrieved_chunk": " ) {\n return JSON.parse(requestBody);\n }\n const params = new URLSearchParams(requestBody);\n if (params.has(\"payload\")) {\n const payload = params.get(\"payload\")!;\n return JSON.parse(payload);\n }\n // deno-lint-ignore no-explicit-any\n const formBody: any = {};", "score": 0.786431074142456 }, { "filename": "src/app.ts", "retrieved_chunk": " const blobRequestBody = await request.blob();\n // We can safely assume the incoming request body is always text data\n const rawBody: string = await blobRequestBody.text();\n // For Request URL verification\n if (rawBody.includes(\"ssl_check=\")) {\n // Slack does not send the x-slack-signature header for this pattern.\n // Thus, we need to check the pattern before verifying a request.\n const bodyParams = new URLSearchParams(rawBody);\n if (bodyParams.get(\"ssl_check\") === \"1\" && bodyParams.get(\"token\")) {\n return new Response(\"\", { status: 200 });", "score": 0.7787325382232666 } ]
typescript
cookie = parseCookie(request.headers.get("Cookie") || "");
import { ExecutionContext, NoopExecutionContext } from "./execution-context"; import { SlackApp } from "./app"; import { SlackOAuthEnv } from "./app-env"; import { InstallationStore } from "./oauth/installation-store"; import { NoStorageStateStore, StateStore } from "./oauth/state-store"; import { renderCompletionPage, renderStartPage, } from "./oauth/oauth-page-renderer"; import { generateAuthorizeUrl } from "./oauth/authorize-url-generator"; import { parse as parseCookie } from "./cookie"; import { SlackAPIClient, OAuthV2AccessResponse, OpenIDConnectTokenResponse, } from "slack-web-api-client"; import { toInstallation } from "./oauth/installation"; import { AfterInstallation, BeforeInstallation, OnFailure, OnStateValidationError, defaultOnFailure, defaultOnStateValidationError, } from "./oauth/callback"; import { OpenIDConnectCallback, defaultOpenIDConnectCallback, } from "./oidc/callback"; import { generateOIDCAuthorizeUrl } from "./oidc/authorize-url-generator"; import { InstallationError, MissingCode, CompletionPageError, InstallationStoreError, OpenIDConnectError, } from "./oauth/error-codes"; export interface SlackOAuthAppOptions<E extends SlackOAuthEnv> { env: E; installationStore: InstallationStore<E>; stateStore?: StateStore; oauth?: { stateCookieName?: string; beforeInstallation?: BeforeInstallation; afterInstallation?: AfterInstallation; onFailure?: OnFailure; onStateValidationError?: OnStateValidationError; redirectUri?: string; }; oidc?: { stateCookieName?: string; callback: OpenIDConnectCallback; onFailure?: OnFailure; onStateValidationError?: OnStateValidationError; redirectUri?: string; }; routes?: { events: string; oauth: { start: string; callback: string }; oidc?: { start: string; callback: string }; }; } export class SlackOAuthApp<E extends SlackOAuthEnv> extends SlackApp<E> { public env: E; public installationStore: InstallationStore<E>; public stateStore: StateStore; public oauth: { stateCookieName?: string; beforeInstallation?: BeforeInstallation; afterInstallation?: AfterInstallation; onFailure: OnFailure; onStateValidationError: OnStateValidationError; redirectUri?: string; }; public oidc?: { stateCookieName?: string; callback: OpenIDConnectCallback; onFailure: OnFailure; onStateValidationError: OnStateValidationError; redirectUri?: string; }; public routes: { events: string; oauth: { start: string; callback: string }; oidc?: { start: string; callback: string }; }; constructor(options: SlackOAuthAppOptions<E>) { super({ env: options.env, authorize: options.installationStore.toAuthorize(), routes: { events: options.routes?.events ?? "/slack/events" }, }); this.env = options.env; this.installationStore = options.installationStore; this.stateStore = options.stateStore ?? new NoStorageStateStore(); this.oauth = { stateCookieName: options.oauth?.stateCookieName ?? "slack-app-oauth-state", onFailure: options.oauth?.onFailure ?? defaultOnFailure, onStateValidationError: options.oauth?.onStateValidationError ?? defaultOnStateValidationError, redirectUri: options.oauth?.redirectUri ?? this.env.SLACK_REDIRECT_URI, }; if (options.oidc) { this.oidc = { stateCookieName: options.oidc.stateCookieName ?? "slack-app-oidc-state", onFailure: options.oidc.onFailure ?? defaultOnFailure, onStateValidationError: options.oidc.onStateValidationError ?? defaultOnStateValidationError, callback: defaultOpenIDConnectCallback(this.env), redirectUri: options.oidc.redirectUri ?? this.env.SLACK_OIDC_REDIRECT_URI, }; } else { this.oidc = undefined; } this.routes = options.routes ? options.routes : { events: "/slack/events", oauth: { start: "/slack/install", callback: "/slack/oauth_redirect", }, oidc: { start: "/slack/login", callback: "/slack/login/callback", }, }; } async run( request: Request, ctx: ExecutionContext = new NoopExecutionContext() ): Promise<Response> { const url = new URL(request.url); if (request.method === "GET") { if (url.pathname === this.routes.oauth.start) { return await this.handleOAuthStartRequest(request); } else if (url.pathname === this.routes.oauth.callback) { return await this.handleOAuthCallbackRequest(request); } if (this.routes.oidc) { if (url.pathname === this.routes.oidc.start) { return await this.handleOIDCStartRequest(request); } else if (url.pathname === this.routes.oidc.callback) { return await this.handleOIDCCallbackRequest(request); } } } else if (request.method === "POST") { if (url.pathname === this.routes.events) { return await this.handleEventRequest(request, ctx); } } return new Response("Not found", { status: 404 }); } async handleEventRequest( request: Request, ctx: ExecutionContext ): Promise<Response> { return await super.handleEventRequest(request, ctx); } // deno-lint-ignore no-unused-vars async handleOAuthStartRequest(request: Request): Promise<Response> { const stateValue = await this.stateStore.issueNewState(); const authorizeUrl = generateAuthorizeUrl(stateValue, this.env); return new Response(renderStartPage(authorizeUrl), { status: 302, headers: { Location: authorizeUrl, "Set-Cookie": `${this.oauth.stateCookieName}=${stateValue}; Secure; HttpOnly; Path=/; Max-Age=300`, "Content-Type": "text/html; charset=utf-8", }, }); } async handleOAuthCallbackRequest(request: Request): Promise<Response> { // State parameter validation await this.#validateStateParameter( request, this.routes.oauth.start, this.oauth.stateCookieName! ); const { searchParams } = new URL(request.url); const code = searchParams.get("code"); if (!code) { return await this.oauth.onFailure( this.routes.oauth.start, MissingCode, request ); } const client = new SlackAPIClient(undefined, { logLevel: this.env.SLACK_LOGGING_LEVEL, }); let oauthAccess: OAuthV2AccessResponse | undefined; try { // Execute the installation process oauthAccess = await client.oauth.v2.access({ client_id: this.env.SLACK_CLIENT_ID, client_secret: this.env.SLACK_CLIENT_SECRET, redirect_uri: this.oauth.redirectUri, code, }); } catch (e) { console.log(e); return await this.oauth.onFailure( this.routes.oauth.start, InstallationError, request ); } try { // Store the installation data on this app side await this.installationStore.save(toInstallation(oauthAccess), request); } catch (e) { console.log(e); return await this.oauth.onFailure( this.routes.oauth.start, InstallationStoreError, request ); } try { // Build the completion page const authTest = await client.auth.test({ token: oauthAccess.access_token, }); const enterpriseUrl = authTest.url; return new Response( renderCompletionPage( oauthAccess.app_id!, oauthAccess.team?.id!, oauthAccess.is_enterprise_install, enterpriseUrl ), { status: 200, headers: { "Set-Cookie": `${this.oauth.stateCookieName}=deleted; Secure; HttpOnly; Path=/; Max-Age=0`, "Content-Type": "text/html; charset=utf-8", }, } ); } catch (e) { console.log(e); return await this.oauth.onFailure( this.routes.oauth.start, CompletionPageError, request ); } } // deno-lint-ignore no-unused-vars async handleOIDCStartRequest(request: Request): Promise<Response> { if (!this.oidc) { return new Response("Not found", { status: 404 }); } const stateValue = await this.stateStore.issueNewState(); const authorizeUrl = generateOIDCAuthorizeUrl(stateValue, this.env); return new Response(renderStartPage(authorizeUrl), { status: 302, headers: { Location: authorizeUrl, "Set-Cookie": `${this.oidc.stateCookieName}=${stateValue}; Secure; HttpOnly; Path=/; Max-Age=300`, "Content-Type": "text/html; charset=utf-8", }, }); } async handleOIDCCallbackRequest(request: Request): Promise<Response> { if (!this.oidc || !this.routes.oidc) { return new Response("Not found", { status: 404 }); } // State parameter validation await this.#validateStateParameter( request, this.routes.oidc.start, this.oidc.stateCookieName! ); const { searchParams } = new URL(request.url); const code = searchParams.get("code"); if (!code) { return await this.oidc.onFailure( this.routes.oidc.start, MissingCode, request ); } try { const client = new SlackAPIClient(undefined, { logLevel: this.env.SLACK_LOGGING_LEVEL, }); const apiResponse: OpenIDConnectTokenResponse = await client.openid.connect.token({ client_id: this.env.SLACK_CLIENT_ID, client_secret: this.env.SLACK_CLIENT_SECRET, redirect_uri: this.oidc.redirectUri, code, }); return await this.oidc.callback(apiResponse, request); } catch (e) { console.log(e); return await this.oidc.onFailure( this.routes.oidc.start, OpenIDConnectError, request ); } } async #validateStateParameter( request: Request, startPath: string, cookieName: string ) { const { searchParams } = new URL(request.url); const queryState = searchParams.get("state"); const cookie = parseCookie(request.headers.get("Cookie") || ""); const cookieState = cookie[cookieName]; if ( queryState !== cookieState ||
!(await this.stateStore.consume(queryState)) ) {
if (startPath === this.routes.oauth.start) { return await this.oauth.onStateValidationError(startPath, request); } else if ( this.oidc && this.routes.oidc && startPath === this.routes.oidc.start ) { return await this.oidc.onStateValidationError(startPath, request); } } } }
src/oauth-app.ts
seratch-slack-edge-c75c224
[ { "filename": "src/oauth/state-store.ts", "retrieved_chunk": " async consume(state: string): Promise<boolean> {\n return true;\n }\n}", "score": 0.8178726434707642 }, { "filename": "src/oauth/state-store.ts", "retrieved_chunk": "export interface StateStore {\n issueNewState(): Promise<string>;\n consume(state: string): Promise<boolean>;\n}\nexport class NoStorageStateStore implements StateStore {\n // deno-lint-ignore require-await\n async issueNewState(): Promise<string> {\n return crypto.randomUUID();\n }\n // deno-lint-ignore require-await no-unused-vars", "score": 0.8087030649185181 }, { "filename": "src/app.ts", "retrieved_chunk": " ): Promise<Response> {\n // If the routes.events is missing, any URLs can work for handing requests from Slack\n if (this.routes.events) {\n const { pathname } = new URL(request.url);\n if (pathname !== this.routes.events) {\n return new Response(\"Not found\", { status: 404 });\n }\n }\n // To avoid the following warning by Cloudflware, parse the body as Blob first\n // Called .text() on an HTTP body which does not appear to be text ..", "score": 0.7863705158233643 }, { "filename": "src/app.ts", "retrieved_chunk": " await this.socketModeClient.connect();\n }\n async disconnect(): Promise<void> {\n if (this.socketModeClient) {\n await this.socketModeClient.disconnect();\n }\n }\n async handleEventRequest(\n request: Request,\n ctx: ExecutionContext", "score": 0.7792969942092896 }, { "filename": "src/cookie.ts", "retrieved_chunk": " // deno-lint-ignore no-explicit-any\n const obj: any = {};\n const opt = options || {};\n const dec = opt.decode || decode;\n let index = 0;\n while (index < str.length) {\n const eqIdx = str.indexOf(\"=\", index);\n // no more cookie pairs\n if (eqIdx === -1) {\n break;", "score": 0.7761183381080627 } ]
typescript
!(await this.stateStore.consume(queryState)) ) {
import { SlackAPIClient, isDebugLogEnabled } from "slack-web-api-client"; import { SlackApp } from "../app"; import { ConfigError, SocketModeError } from "../errors"; import { ExecutionContext } from "../execution-context"; import { SlackSocketModeAppEnv } from "../app-env"; // TODO: Implement proper reconnection logic // TODO: Add connection monitor like 1st party SDKs do // TODO: Add Bun support (the runtime does not work well with Socket Mode) export class SocketModeClient { public app: SlackApp<SlackSocketModeAppEnv>; public appLevelToken: string; public ws: WebSocket | undefined; constructor( // deno-lint-ignore no-explicit-any app: SlackApp<any> ) { if (!app.socketMode) { throw new ConfigError( "socketMode: true must be set for running with Socket Mode" ); } if (!app.appLevelToken) { throw new ConfigError( "appLevelToken must be set for running with Socket Mode" ); } this.app = app as SlackApp<SlackSocketModeAppEnv>; this.appLevelToken = app.appLevelToken; console.warn( "WARNING: The Socket Mode support provided by slack-edge is still experimental and is not designed to handle reconnections for production-grade applications. It is recommended to use this mode only for local development and testing purposes." ); } async connect() { const client = new SlackAPIClient(this.appLevelToken); try { const newConnection = await client.apps.connections.open(); this.ws = new WebSocket(newConnection.url!); } catch (e) { throw new SocketModeError( `Failed to establish a new WSS connection: ${e}` ); } if (this.ws) { const ws = this.ws; // deno-lint-ignore require-await ws.onopen = async (ev) => { // TODO: make this customizable if (isDebugLogEnabled(app.env.SLACK_LOGGING_LEVEL)) { console.log( `Now the Socket Mode client is connected to Slack: ${JSON.stringify( ev )}` ); } }; // deno-lint-ignore require-await ws.onclose = async (ev) => { // TODO: make this customizable if (isDebugLogEnabled(app.env.SLACK_LOGGING_LEVEL)) { console.log( `The Socket Mode client is disconnected from Slack: ${JSON.stringify( ev )}` ); } }; // deno-lint-ignore require-await ws.onerror = async (e) => { // TODO: make this customizable console.error( `An error was thrown by the Socket Mode connection: ${e}` ); }; const app = this.app; ws.onmessage = async (ev) => { try { if ( ev.data && typeof ev.data === "string" && ev.data.startsWith("{") ) { const data = JSON.parse(ev.data); if (data.type === "hello") { if (isDebugLogEnabled(app.env.SLACK_LOGGING_LEVEL)) { console.log(`*** Received hello data ***\n ${ev.data}`); } return; } const payload = JSON.stringify(data.payload); console.log(payload); const request: Request = new Request(ws.url, { method: "POST", headers: new Headers({ "content-type": "application/json" }), body: new Blob([payload]).stream(), }); const context: ExecutionContext = { // deno-lint-ignore require-await
waitUntil: async (promise) => {
promise .then((res) => { console.info(`Completed a lazy listener execution: ${res}`); }) .catch((err) => { console.error(`Failed to run a lazy listener: ${err}`); }); }, }; const response = await app.run(request, context); // deno-lint-ignore no-explicit-any let ack: any = { envelope_id: data.envelope_id }; if (response.body) { const contentType = response.headers.get("Content-Type"); if (contentType && contentType.startsWith("text/plain")) { const text = await response.text(); ack = { envelope_id: data.envelope_id, payload: { text } }; } else { const json = await response.json(); ack = { envelope_id: data.envelope_id, payload: { ...json } }; } } ws.send(JSON.stringify(ack)); } else { if (isDebugLogEnabled(app.env.SLACK_LOGGING_LEVEL)) { console.log(`*** Received non-JSON data ***\n ${ev.data}`); } } } catch (e) { console.error(`Failed to handle a WebSocke message: ${e}`); } }; } } // deno-lint-ignore require-await async disconnect(): Promise<void> { if (this.ws) { this.ws.close(); this.ws = undefined; } } }
src/socket-mode/socket-mode-client.ts
seratch-slack-edge-c75c224
[ { "filename": "src/app.ts", "retrieved_chunk": " const client = new SlackAPIClient(context.botToken);\n context.say = async (params) =>\n await client.chat.postMessage({\n channel: context.channelId,\n ...params,\n });\n }\n if (authorizedContext.responseUrl) {\n const responseUrl = authorizedContext.responseUrl;\n // deno-lint-ignore require-await", "score": 0.8308497667312622 }, { "filename": "src/app.ts", "retrieved_chunk": " payload: body.event,\n ...baseRequest,\n };\n for (const matcher of this.#events) {\n const handler = matcher(payload);\n if (handler) {\n ctx.waitUntil(handler.lazy(slackRequest));\n const slackResponse = await handler.ack(slackRequest);\n if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) {\n console.log(", "score": 0.8243067860603333 }, { "filename": "src/request/request-parser.ts", "retrieved_chunk": " ) {\n return JSON.parse(requestBody);\n }\n const params = new URLSearchParams(requestBody);\n if (params.has(\"payload\")) {\n const payload = params.get(\"payload\")!;\n return JSON.parse(payload);\n }\n // deno-lint-ignore no-explicit-any\n const formBody: any = {};", "score": 0.8229929804801941 }, { "filename": "src/app.ts", "retrieved_chunk": " }\n }\n // Verify the request headers and body\n const isRequestSignatureVerified =\n this.socketMode ||\n (await verifySlackRequest(this.signingSecret, request.headers, rawBody));\n if (isRequestSignatureVerified) {\n // deno-lint-ignore no-explicit-any\n const body: Record<string, any> = await parseRequestBody(\n request.headers,", "score": 0.8124278783798218 }, { "filename": "src/app.ts", "retrieved_chunk": " const blobRequestBody = await request.blob();\n // We can safely assume the incoming request body is always text data\n const rawBody: string = await blobRequestBody.text();\n // For Request URL verification\n if (rawBody.includes(\"ssl_check=\")) {\n // Slack does not send the x-slack-signature header for this pattern.\n // Thus, we need to check the pattern before verifying a request.\n const bodyParams = new URLSearchParams(rawBody);\n if (bodyParams.get(\"ssl_check\") === \"1\" && bodyParams.get(\"token\")) {\n return new Response(\"\", { status: 200 });", "score": 0.8122352361679077 } ]
typescript
waitUntil: async (promise) => {
// Copyright 2022 - 2023 The MathWorks, Inc. import { ClientCapabilities, WorkspaceFolder, WorkspaceFoldersChangeEvent } from 'vscode-languageserver' import ConfigurationManager from '../lifecycle/ConfigurationManager' import { connection } from '../server' import Indexer from './Indexer' /** * Handles indexing files in the user's workspace to gather data about classes, * functions, and variables. */ class WorkspaceIndexer { private isWorkspaceIndexingSupported = false /** * Sets up workspace change listeners, if supported. * * @param capabilities The client capabilities, which contains information about * whether the client supports workspaces. */ setupCallbacks (capabilities: ClientCapabilities): void { this.isWorkspaceIndexingSupported = capabilities.workspace?.workspaceFolders ?? false if (!this.isWorkspaceIndexingSupported) { // Workspace indexing not supported return } connection.workspace.onDidChangeWorkspaceFolders((params: WorkspaceFoldersChangeEvent) => { void this.handleWorkspaceFoldersAdded(params.added) }) } /** * Attempts to index the files in the user's workspace. */ async indexWorkspace (): Promise<void> { if (!(await this.shouldIndexWorkspace())) { return } const folders = await connection.workspace.getWorkspaceFolders() if (folders == null) { return }
Indexer.indexFolders(folders.map(folder => folder.uri)) }
/** * Handles when new folders are added to the user's workspace by indexing them. * * @param folders The list of folders added to the workspace */ private async handleWorkspaceFoldersAdded (folders: WorkspaceFolder[]): Promise<void> { if (!(await this.shouldIndexWorkspace())) { return } Indexer.indexFolders(folders.map(folder => folder.uri)) } /** * Determines whether or not the workspace should be indexed. * The workspace should be indexed if the client supports workspaces, and if the * workspace indexing setting is true. * * @returns True if workspace indexing should occurr, false otherwise. */ private async shouldIndexWorkspace (): Promise<boolean> { const shouldIndexWorkspace = (await ConfigurationManager.getConfiguration()).indexWorkspace return this.isWorkspaceIndexingSupported && shouldIndexWorkspace } } export default new WorkspaceIndexer()
src/indexing/WorkspaceIndexer.ts
mathworks-MATLAB-language-server-94cac1b
[ { "filename": "src/indexing/Indexer.ts", "retrieved_chunk": " if (uri !== '') {\n void this.indexFile(uri)\n }\n })\n }\n}\nexport default new Indexer()", "score": 0.8481776714324951 }, { "filename": "src/indexing/DocumentIndexer.ts", "retrieved_chunk": " if (!FileInfoIndex.codeDataCache.has(uri)) {\n await Indexer.indexDocument(textDocument)\n }\n }\n}\nexport default new DocumentIndexer()", "score": 0.8394818305969238 }, { "filename": "src/server.ts", "retrieved_chunk": " WorkspaceIndexer.setupCallbacks(capabilities)\n void startMatlabIfOnStartLaunch()\n})\nasync function startMatlabIfOnStartLaunch (): Promise<void> {\n // Launch MATLAB if it should be launched early\n const connectionTiming = (await ConfigurationManager.getConfiguration()).matlabConnectionTiming\n if (connectionTiming === ConnectionTiming.OnStart) {\n void MatlabLifecycleManager.connectToMatlab(connection)\n }\n}", "score": 0.8337074518203735 }, { "filename": "src/indexing/Indexer.ts", "retrieved_chunk": " // Queue indexing for other files in @ class directory\n const classDefFolder = parsedCodeData.classInfo.classDefFolder\n if (classDefFolder !== '') {\n this.indexFolders([classDefFolder])\n }\n // Find and queue indexing for parent classes\n const baseClasses = parsedCodeData.classInfo.baseClasses\n const resolvedBaseClasses = await PathResolver.resolvePaths(baseClasses, uri, matlabConnection)\n resolvedBaseClasses.forEach(resolvedBaseClass => {\n const uri = resolvedBaseClass.uri", "score": 0.8133125305175781 }, { "filename": "src/indexing/Indexer.ts", "retrieved_chunk": " if (matlabConnection == null || !MatlabLifecycleManager.isMatlabReady()) {\n return\n }\n const requestId = this.requestCt++\n const responseSub = matlabConnection.subscribe(`${this.INDEX_FOLDERS_RESPONSE_CHANNEL}${requestId}`, message => {\n const fileResults = message as WorkspaceFileIndexedResponse\n if (fileResults.isDone) {\n // No more files being indexed - safe to unsubscribe\n matlabConnection.unsubscribe(responseSub)\n }", "score": 0.8113009333610535 } ]
typescript
Indexer.indexFolders(folders.map(folder => folder.uri)) }
import { SlackAPIClient, isDebugLogEnabled } from "slack-web-api-client"; import { SlackApp } from "../app"; import { ConfigError, SocketModeError } from "../errors"; import { ExecutionContext } from "../execution-context"; import { SlackSocketModeAppEnv } from "../app-env"; // TODO: Implement proper reconnection logic // TODO: Add connection monitor like 1st party SDKs do // TODO: Add Bun support (the runtime does not work well with Socket Mode) export class SocketModeClient { public app: SlackApp<SlackSocketModeAppEnv>; public appLevelToken: string; public ws: WebSocket | undefined; constructor( // deno-lint-ignore no-explicit-any app: SlackApp<any> ) { if (!app.socketMode) { throw new ConfigError( "socketMode: true must be set for running with Socket Mode" ); } if (!app.appLevelToken) { throw new ConfigError( "appLevelToken must be set for running with Socket Mode" ); } this.app = app as SlackApp<SlackSocketModeAppEnv>; this.appLevelToken = app.appLevelToken; console.warn( "WARNING: The Socket Mode support provided by slack-edge is still experimental and is not designed to handle reconnections for production-grade applications. It is recommended to use this mode only for local development and testing purposes." ); } async connect() { const client = new SlackAPIClient(this.appLevelToken); try { const newConnection = await client.apps.connections.open(); this.ws = new WebSocket(newConnection.url!); } catch (e) { throw new SocketModeError( `Failed to establish a new WSS connection: ${e}` ); } if (this.ws) { const ws = this.ws; // deno-lint-ignore require-await ws.onopen = async (ev) => { // TODO: make this customizable if (isDebugLogEnabled(app.env.SLACK_LOGGING_LEVEL)) { console.log( `Now the Socket Mode client is connected to Slack: ${JSON.stringify( ev )}` ); } }; // deno-lint-ignore require-await ws.onclose = async (ev) => { // TODO: make this customizable if (isDebugLogEnabled(app.env.SLACK_LOGGING_LEVEL)) { console.log( `The Socket Mode client is disconnected from Slack: ${JSON.stringify( ev )}` ); } }; // deno-lint-ignore require-await ws.onerror = async (e) => { // TODO: make this customizable console.error( `An error was thrown by the Socket Mode connection: ${e}` ); }; const app = this.app; ws.onmessage = async (ev) => { try { if ( ev.data && typeof ev.data === "string" && ev.data.startsWith("{") ) { const data = JSON.parse(ev.data); if (data.type === "hello") { if (isDebugLogEnabled(app.env.SLACK_LOGGING_LEVEL)) { console.log(`*** Received hello data ***\n ${ev.data}`); } return; } const payload = JSON.stringify(data.payload); console.log(payload); const request: Request = new Request(ws.url, { method: "POST", headers: new Headers({ "content-type": "application/json" }), body: new Blob([payload]).stream(), }); const context: ExecutionContext = { // deno-lint-ignore require-await waitUntil: async (promise) => { promise .then
((res) => {
console.info(`Completed a lazy listener execution: ${res}`); }) .catch((err) => { console.error(`Failed to run a lazy listener: ${err}`); }); }, }; const response = await app.run(request, context); // deno-lint-ignore no-explicit-any let ack: any = { envelope_id: data.envelope_id }; if (response.body) { const contentType = response.headers.get("Content-Type"); if (contentType && contentType.startsWith("text/plain")) { const text = await response.text(); ack = { envelope_id: data.envelope_id, payload: { text } }; } else { const json = await response.json(); ack = { envelope_id: data.envelope_id, payload: { ...json } }; } } ws.send(JSON.stringify(ack)); } else { if (isDebugLogEnabled(app.env.SLACK_LOGGING_LEVEL)) { console.log(`*** Received non-JSON data ***\n ${ev.data}`); } } } catch (e) { console.error(`Failed to handle a WebSocke message: ${e}`); } }; } } // deno-lint-ignore require-await async disconnect(): Promise<void> { if (this.ws) { this.ws.close(); this.ws = undefined; } } }
src/socket-mode/socket-mode-client.ts
seratch-slack-edge-c75c224
[ { "filename": "src/request/request-parser.ts", "retrieved_chunk": " ) {\n return JSON.parse(requestBody);\n }\n const params = new URLSearchParams(requestBody);\n if (params.has(\"payload\")) {\n const payload = params.get(\"payload\")!;\n return JSON.parse(payload);\n }\n // deno-lint-ignore no-explicit-any\n const formBody: any = {};", "score": 0.8220378160476685 }, { "filename": "src/app.ts", "retrieved_chunk": " const client = new SlackAPIClient(context.botToken);\n context.say = async (params) =>\n await client.chat.postMessage({\n channel: context.channelId,\n ...params,\n });\n }\n if (authorizedContext.responseUrl) {\n const responseUrl = authorizedContext.responseUrl;\n // deno-lint-ignore require-await", "score": 0.817524254322052 }, { "filename": "src/app.ts", "retrieved_chunk": " const blobRequestBody = await request.blob();\n // We can safely assume the incoming request body is always text data\n const rawBody: string = await blobRequestBody.text();\n // For Request URL verification\n if (rawBody.includes(\"ssl_check=\")) {\n // Slack does not send the x-slack-signature header for this pattern.\n // Thus, we need to check the pattern before verifying a request.\n const bodyParams = new URLSearchParams(rawBody);\n if (bodyParams.get(\"ssl_check\") === \"1\" && bodyParams.get(\"token\")) {\n return new Response(\"\", { status: 200 });", "score": 0.815457820892334 }, { "filename": "src/execution-context.ts", "retrieved_chunk": "/**\n * An interface representing context parameter in Cloudflare Workers and Vercel Edge Functions.\n * Refer to the following resources:\n * - https://developers.cloudflare.com/workers/runtime-apis/fetch-event/\n * - https://vercel.com/docs/concepts/functions/edge-functions/edge-functions-api#waituntil\n */\nexport interface ExecutionContext {\n // deno-lint-ignore no-explicit-any\n waitUntil(promise: Promise<any>): void;\n}", "score": 0.8136096596717834 }, { "filename": "src/app.ts", "retrieved_chunk": " }\n }\n // Verify the request headers and body\n const isRequestSignatureVerified =\n this.socketMode ||\n (await verifySlackRequest(this.signingSecret, request.headers, rawBody));\n if (isRequestSignatureVerified) {\n // deno-lint-ignore no-explicit-any\n const body: Record<string, any> = await parseRequestBody(\n request.headers,", "score": 0.8113741874694824 } ]
typescript
((res) => {
// Copyright 2022 - 2023 The MathWorks, Inc. import { TextDocument } from 'vscode-languageserver-textdocument' import Indexer from './Indexer' import FileInfoIndex from './FileInfoIndex' const INDEXING_DELAY = 500 // Delay (in ms) after keystroke before attempting to re-index the document /** * Handles indexing a currently open document to gather data about classes, * functions, and variables. */ class DocumentIndexer { private readonly pendingFilesToIndex = new Map<string, NodeJS.Timer>() /** * Queues a document to be indexed. This handles debouncing so that * indexing is not performed on every keystroke. * * @param textDocument The document to be indexed */ queueIndexingForDocument (textDocument: TextDocument): void { const uri = textDocument.uri this.clearTimerForDocumentUri(uri) this.pendingFilesToIndex.set( uri, setTimeout(() => { this.indexDocument(textDocument) }, INDEXING_DELAY) // Specify timeout for debouncing, to avoid re-indexing every keystroke while a user types ) } /** * Indexes the document and caches the data. * * @param textDocument The document being indexed */ indexDocument (textDocument: TextDocument): void {
void Indexer.indexDocument(textDocument) }
/** * Clears any active indexing timers for the provided document URI. * * @param uri The document URI */ private clearTimerForDocumentUri (uri: string): void { const timerId = this.pendingFilesToIndex.get(uri) if (timerId != null) { clearTimeout(timerId) this.pendingFilesToIndex.delete(uri) } } /** * Ensure that @param textDocument is fully indexed and up to date by flushing any pending indexing tasks * and then forcing an index. This is intended to service requests like documentSymbols where returning * stale info could be confusing. * * @param textDocument The document to index */ async ensureDocumentIndexIsUpdated (textDocument: TextDocument): Promise<void> { const uri = textDocument.uri if (this.pendingFilesToIndex.has(uri)) { this.clearTimerForDocumentUri(uri) await Indexer.indexDocument(textDocument) } if (!FileInfoIndex.codeDataCache.has(uri)) { await Indexer.indexDocument(textDocument) } } } export default new DocumentIndexer()
src/indexing/DocumentIndexer.ts
mathworks-MATLAB-language-server-94cac1b
[ { "filename": "src/indexing/Indexer.ts", "retrieved_chunk": " * Indexes the given TextDocument and caches the data.\n *\n * @param textDocument The document being indexed\n */\n async indexDocument (textDocument: TextDocument): Promise<void> {\n const matlabConnection = MatlabLifecycleManager.getMatlabConnection()\n if (matlabConnection == null || !MatlabLifecycleManager.isMatlabReady()) {\n return\n }\n const rawCodeData = await this.getCodeData(textDocument.getText(), textDocument.uri, matlabConnection)", "score": 0.9169237613677979 }, { "filename": "src/indexing/Indexer.ts", "retrieved_chunk": " * Indexes the file for the given URI and caches the data.\n *\n * @param uri The URI for the file being indexed\n */\n async indexFile (uri: string): Promise<void> {\n const matlabConnection = MatlabLifecycleManager.getMatlabConnection()\n if (matlabConnection == null || !MatlabLifecycleManager.isMatlabReady()) {\n return\n }\n const fileContentBuffer = await fs.readFile(URI.parse(uri).fsPath)", "score": 0.802885890007019 }, { "filename": "src/server.ts", "retrieved_chunk": " void LintingSupportProvider.lintDocument(textDocument, connection)\n void DocumentIndexer.indexDocument(textDocument)\n })\n }\n})\nlet capabilities: ClientCapabilities\n// Handles an initialization request\nconnection.onInitialize((params: InitializeParams) => {\n capabilities = params.capabilities\n // Defines the capabilities supported by this language server", "score": 0.7988089323043823 }, { "filename": "src/providers/linting/LintingSupportProvider.ts", "retrieved_chunk": " * that linting is not performed on every keystroke.\n *\n * @param textDocument The document to be linted\n * @param connection The language server connection\n */\n queueLintingForDocument (textDocument: TextDocument, connection: _Connection): void {\n const uri = textDocument.uri\n this.clearTimerForDocumentUri(uri)\n this._pendingFilesToLint.set(\n uri,", "score": 0.7928696870803833 }, { "filename": "src/server.ts", "retrieved_chunk": "documentManager.onDidSave(params => {\n void LintingSupportProvider.lintDocument(params.document, connection)\n})\n// Handles changes to the text document\ndocumentManager.onDidChangeContent(params => {\n if (MatlabLifecycleManager.isMatlabReady()) {\n // Only want to lint on content changes when linting is being backed by MATLAB\n LintingSupportProvider.queueLintingForDocument(params.document, connection)\n DocumentIndexer.queueIndexingForDocument(params.document)\n }", "score": 0.7898039817810059 } ]
typescript
void Indexer.indexDocument(textDocument) }
// Copyright 2022 - 2023 The MathWorks, Inc. import { ClientCapabilities, WorkspaceFolder, WorkspaceFoldersChangeEvent } from 'vscode-languageserver' import ConfigurationManager from '../lifecycle/ConfigurationManager' import { connection } from '../server' import Indexer from './Indexer' /** * Handles indexing files in the user's workspace to gather data about classes, * functions, and variables. */ class WorkspaceIndexer { private isWorkspaceIndexingSupported = false /** * Sets up workspace change listeners, if supported. * * @param capabilities The client capabilities, which contains information about * whether the client supports workspaces. */ setupCallbacks (capabilities: ClientCapabilities): void { this.isWorkspaceIndexingSupported = capabilities.workspace?.workspaceFolders ?? false if (!this.isWorkspaceIndexingSupported) { // Workspace indexing not supported return } connection.workspace.onDidChangeWorkspaceFolders((params: WorkspaceFoldersChangeEvent) => { void this.handleWorkspaceFoldersAdded(params.added) }) } /** * Attempts to index the files in the user's workspace. */ async indexWorkspace (): Promise<void> { if (!(await this.shouldIndexWorkspace())) { return } const folders = await connection.workspace.getWorkspaceFolders() if (folders == null) { return } Indexer.indexFolders(folders.map(folder => folder.uri)) } /** * Handles when new folders are added to the user's workspace by indexing them. * * @param folders The list of folders added to the workspace */ private async handleWorkspaceFoldersAdded (folders: WorkspaceFolder[]): Promise<void> { if (!(await this.shouldIndexWorkspace())) { return } Indexer.indexFolders(folders.map(folder => folder.uri)) } /** * Determines whether or not the workspace should be indexed. * The workspace should be indexed if the client supports workspaces, and if the * workspace indexing setting is true. * * @returns True if workspace indexing should occurr, false otherwise. */ private async shouldIndexWorkspace (): Promise<boolean> {
const shouldIndexWorkspace = (await ConfigurationManager.getConfiguration()).indexWorkspace return this.isWorkspaceIndexingSupported && shouldIndexWorkspace }
} export default new WorkspaceIndexer()
src/indexing/WorkspaceIndexer.ts
mathworks-MATLAB-language-server-94cac1b
[ { "filename": "src/server.ts", "retrieved_chunk": " WorkspaceIndexer.setupCallbacks(capabilities)\n void startMatlabIfOnStartLaunch()\n})\nasync function startMatlabIfOnStartLaunch (): Promise<void> {\n // Launch MATLAB if it should be launched early\n const connectionTiming = (await ConfigurationManager.getConfiguration()).matlabConnectionTiming\n if (connectionTiming === ConnectionTiming.OnStart) {\n void MatlabLifecycleManager.connectToMatlab(connection)\n }\n}", "score": 0.8059004545211792 }, { "filename": "src/lifecycle/ConfigurationManager.ts", "retrieved_chunk": " }\n }\n /**\n * Sets up the configuration manager\n *\n * @param capabilities The client capabilities\n */\n setup (capabilities: ClientCapabilities): void {\n this.hasConfigurationCapability = capabilities.workspace?.configuration != null\n if (this.hasConfigurationCapability) {", "score": 0.7863316535949707 }, { "filename": "src/lifecycle/ConfigurationManager.ts", "retrieved_chunk": " async getConfiguration (): Promise<Settings> {\n if (this.hasConfigurationCapability) {\n if (this.configuration == null) {\n this.configuration = await connection.workspace.getConfiguration('MATLAB') as Settings\n }\n return this.configuration\n }\n return this.globalSettings\n }\n /**", "score": 0.7829191088676453 }, { "filename": "src/utils/CliUtils.ts", "retrieved_chunk": " boolean: true,\n default: false,\n description: 'Whether or not the user\\'s workspace should be indexed.',\n requiresArg: false\n }).option(Argument.MatlabUrl, {\n type: 'string',\n description: 'URL for communicating with an existing MATLAB instance',\n requiresArg: true\n }).usage(\n 'Usage: $0 {--node-ipc | --stdio | --socket=socket} options\\n' +", "score": 0.7694342136383057 }, { "filename": "src/indexing/Indexer.ts", "retrieved_chunk": "// Copyright 2022 - 2023 The MathWorks, Inc.\nimport { TextDocument } from 'vscode-languageserver-textdocument'\nimport { URI } from 'vscode-uri'\nimport { MatlabConnection } from '../lifecycle/MatlabCommunicationManager'\nimport MatlabLifecycleManager from '../lifecycle/MatlabLifecycleManager'\nimport FileInfoIndex, { MatlabCodeData, RawCodeData } from './FileInfoIndex'\nimport * as fs from 'fs/promises'\nimport PathResolver from '../providers/navigation/PathResolver'\ninterface WorkspaceFileIndexedResponse {\n isDone: boolean", "score": 0.766091525554657 } ]
typescript
const shouldIndexWorkspace = (await ConfigurationManager.getConfiguration()).indexWorkspace return this.isWorkspaceIndexingSupported && shouldIndexWorkspace }
// Copyright 2022 - 2023 The MathWorks, Inc. import { TextDocument } from 'vscode-languageserver-textdocument' import Indexer from './Indexer' import FileInfoIndex from './FileInfoIndex' const INDEXING_DELAY = 500 // Delay (in ms) after keystroke before attempting to re-index the document /** * Handles indexing a currently open document to gather data about classes, * functions, and variables. */ class DocumentIndexer { private readonly pendingFilesToIndex = new Map<string, NodeJS.Timer>() /** * Queues a document to be indexed. This handles debouncing so that * indexing is not performed on every keystroke. * * @param textDocument The document to be indexed */ queueIndexingForDocument (textDocument: TextDocument): void { const uri = textDocument.uri this.clearTimerForDocumentUri(uri) this.pendingFilesToIndex.set( uri, setTimeout(() => { this.indexDocument(textDocument) }, INDEXING_DELAY) // Specify timeout for debouncing, to avoid re-indexing every keystroke while a user types ) } /** * Indexes the document and caches the data. * * @param textDocument The document being indexed */ indexDocument (textDocument: TextDocument): void { void
Indexer.indexDocument(textDocument) }
/** * Clears any active indexing timers for the provided document URI. * * @param uri The document URI */ private clearTimerForDocumentUri (uri: string): void { const timerId = this.pendingFilesToIndex.get(uri) if (timerId != null) { clearTimeout(timerId) this.pendingFilesToIndex.delete(uri) } } /** * Ensure that @param textDocument is fully indexed and up to date by flushing any pending indexing tasks * and then forcing an index. This is intended to service requests like documentSymbols where returning * stale info could be confusing. * * @param textDocument The document to index */ async ensureDocumentIndexIsUpdated (textDocument: TextDocument): Promise<void> { const uri = textDocument.uri if (this.pendingFilesToIndex.has(uri)) { this.clearTimerForDocumentUri(uri) await Indexer.indexDocument(textDocument) } if (!FileInfoIndex.codeDataCache.has(uri)) { await Indexer.indexDocument(textDocument) } } } export default new DocumentIndexer()
src/indexing/DocumentIndexer.ts
mathworks-MATLAB-language-server-94cac1b
[ { "filename": "src/indexing/Indexer.ts", "retrieved_chunk": " * Indexes the given TextDocument and caches the data.\n *\n * @param textDocument The document being indexed\n */\n async indexDocument (textDocument: TextDocument): Promise<void> {\n const matlabConnection = MatlabLifecycleManager.getMatlabConnection()\n if (matlabConnection == null || !MatlabLifecycleManager.isMatlabReady()) {\n return\n }\n const rawCodeData = await this.getCodeData(textDocument.getText(), textDocument.uri, matlabConnection)", "score": 0.9217270612716675 }, { "filename": "src/indexing/Indexer.ts", "retrieved_chunk": " * Indexes the file for the given URI and caches the data.\n *\n * @param uri The URI for the file being indexed\n */\n async indexFile (uri: string): Promise<void> {\n const matlabConnection = MatlabLifecycleManager.getMatlabConnection()\n if (matlabConnection == null || !MatlabLifecycleManager.isMatlabReady()) {\n return\n }\n const fileContentBuffer = await fs.readFile(URI.parse(uri).fsPath)", "score": 0.8087530136108398 }, { "filename": "src/server.ts", "retrieved_chunk": " void LintingSupportProvider.lintDocument(textDocument, connection)\n void DocumentIndexer.indexDocument(textDocument)\n })\n }\n})\nlet capabilities: ClientCapabilities\n// Handles an initialization request\nconnection.onInitialize((params: InitializeParams) => {\n capabilities = params.capabilities\n // Defines the capabilities supported by this language server", "score": 0.7977818250656128 }, { "filename": "src/providers/linting/LintingSupportProvider.ts", "retrieved_chunk": " * that linting is not performed on every keystroke.\n *\n * @param textDocument The document to be linted\n * @param connection The language server connection\n */\n queueLintingForDocument (textDocument: TextDocument, connection: _Connection): void {\n const uri = textDocument.uri\n this.clearTimerForDocumentUri(uri)\n this._pendingFilesToLint.set(\n uri,", "score": 0.79261314868927 }, { "filename": "src/server.ts", "retrieved_chunk": "documentManager.onDidSave(params => {\n void LintingSupportProvider.lintDocument(params.document, connection)\n})\n// Handles changes to the text document\ndocumentManager.onDidChangeContent(params => {\n if (MatlabLifecycleManager.isMatlabReady()) {\n // Only want to lint on content changes when linting is being backed by MATLAB\n LintingSupportProvider.queueLintingForDocument(params.document, connection)\n DocumentIndexer.queueIndexingForDocument(params.document)\n }", "score": 0.7914047241210938 } ]
typescript
Indexer.indexDocument(textDocument) }
// Copyright 2022 - 2023 The MathWorks, Inc. import { ClientCapabilities, WorkspaceFolder, WorkspaceFoldersChangeEvent } from 'vscode-languageserver' import ConfigurationManager from '../lifecycle/ConfigurationManager' import { connection } from '../server' import Indexer from './Indexer' /** * Handles indexing files in the user's workspace to gather data about classes, * functions, and variables. */ class WorkspaceIndexer { private isWorkspaceIndexingSupported = false /** * Sets up workspace change listeners, if supported. * * @param capabilities The client capabilities, which contains information about * whether the client supports workspaces. */ setupCallbacks (capabilities: ClientCapabilities): void { this.isWorkspaceIndexingSupported = capabilities.workspace?.workspaceFolders ?? false if (!this.isWorkspaceIndexingSupported) { // Workspace indexing not supported return } connection.workspace.onDidChangeWorkspaceFolders((params: WorkspaceFoldersChangeEvent) => { void this.handleWorkspaceFoldersAdded(params.added) }) } /** * Attempts to index the files in the user's workspace. */ async indexWorkspace (): Promise<void> { if (!(await this.shouldIndexWorkspace())) { return } const folders = await connection.workspace.getWorkspaceFolders() if (folders == null) { return } Indexer.indexFolders(folders.map(folder => folder.uri)) } /** * Handles when new folders are added to the user's workspace by indexing them. * * @param folders The list of folders added to the workspace */ private async handleWorkspaceFoldersAdded (folders: WorkspaceFolder[]): Promise<void> { if (!(await this.shouldIndexWorkspace())) { return } Indexer.indexFolders(folders.map(folder => folder.uri)) } /** * Determines whether or not the workspace should be indexed. * The workspace should be indexed if the client supports workspaces, and if the * workspace indexing setting is true. * * @returns True if workspace indexing should occurr, false otherwise. */ private async shouldIndexWorkspace (): Promise<boolean> { const shouldIndexWorkspace = (
await ConfigurationManager.getConfiguration()).indexWorkspace return this.isWorkspaceIndexingSupported && shouldIndexWorkspace }
} export default new WorkspaceIndexer()
src/indexing/WorkspaceIndexer.ts
mathworks-MATLAB-language-server-94cac1b
[ { "filename": "src/server.ts", "retrieved_chunk": " WorkspaceIndexer.setupCallbacks(capabilities)\n void startMatlabIfOnStartLaunch()\n})\nasync function startMatlabIfOnStartLaunch (): Promise<void> {\n // Launch MATLAB if it should be launched early\n const connectionTiming = (await ConfigurationManager.getConfiguration()).matlabConnectionTiming\n if (connectionTiming === ConnectionTiming.OnStart) {\n void MatlabLifecycleManager.connectToMatlab(connection)\n }\n}", "score": 0.8162276744842529 }, { "filename": "src/lifecycle/ConfigurationManager.ts", "retrieved_chunk": " }\n }\n /**\n * Sets up the configuration manager\n *\n * @param capabilities The client capabilities\n */\n setup (capabilities: ClientCapabilities): void {\n this.hasConfigurationCapability = capabilities.workspace?.configuration != null\n if (this.hasConfigurationCapability) {", "score": 0.796017050743103 }, { "filename": "src/lifecycle/ConfigurationManager.ts", "retrieved_chunk": " async getConfiguration (): Promise<Settings> {\n if (this.hasConfigurationCapability) {\n if (this.configuration == null) {\n this.configuration = await connection.workspace.getConfiguration('MATLAB') as Settings\n }\n return this.configuration\n }\n return this.globalSettings\n }\n /**", "score": 0.7910019159317017 }, { "filename": "src/utils/CliUtils.ts", "retrieved_chunk": " boolean: true,\n default: false,\n description: 'Whether or not the user\\'s workspace should be indexed.',\n requiresArg: false\n }).option(Argument.MatlabUrl, {\n type: 'string',\n description: 'URL for communicating with an existing MATLAB instance',\n requiresArg: true\n }).usage(\n 'Usage: $0 {--node-ipc | --stdio | --socket=socket} options\\n' +", "score": 0.773186445236206 }, { "filename": "src/indexing/Indexer.ts", "retrieved_chunk": "// Copyright 2022 - 2023 The MathWorks, Inc.\nimport { TextDocument } from 'vscode-languageserver-textdocument'\nimport { URI } from 'vscode-uri'\nimport { MatlabConnection } from '../lifecycle/MatlabCommunicationManager'\nimport MatlabLifecycleManager from '../lifecycle/MatlabLifecycleManager'\nimport FileInfoIndex, { MatlabCodeData, RawCodeData } from './FileInfoIndex'\nimport * as fs from 'fs/promises'\nimport PathResolver from '../providers/navigation/PathResolver'\ninterface WorkspaceFileIndexedResponse {\n isDone: boolean", "score": 0.7722271680831909 } ]
typescript
await ConfigurationManager.getConfiguration()).indexWorkspace return this.isWorkspaceIndexingSupported && shouldIndexWorkspace }
// Copyright 2022 - 2023 The MathWorks, Inc. import { ClientCapabilities, DidChangeConfigurationNotification, DidChangeConfigurationParams } from 'vscode-languageserver' import { reportTelemetrySettingsChange } from '../logging/TelemetryUtils' import { connection } from '../server' import { getCliArgs } from '../utils/CliUtils' export enum Argument { // Basic arguments MatlabLaunchCommandArguments = 'matlabLaunchCommandArgs', MatlabInstallationPath = 'matlabInstallPath', MatlabConnectionTiming = 'matlabConnectionTiming', ShouldIndexWorkspace = 'indexWorkspace', // Advanced arguments MatlabUrl = 'matlabUrl' } export enum ConnectionTiming { OnStart = 'onStart', OnDemand = 'onDemand', Never = 'never' } interface CliArguments { [Argument.MatlabLaunchCommandArguments]: string [Argument.MatlabUrl]: string } interface Settings { installPath: string matlabConnectionTiming: ConnectionTiming indexWorkspace: boolean telemetry: boolean } type SettingName = 'installPath' | 'matlabConnectionTiming' | 'indexWorkspace' | 'telemetry' const SETTING_NAMES: SettingName[] = [ 'installPath', 'matlabConnectionTiming', 'indexWorkspace', 'telemetry' ] class ConfigurationManager { private configuration: Settings | null = null private readonly defaultConfiguration: Settings private globalSettings: Settings // Holds additional command line arguments that are not part of the configuration private readonly additionalArguments: CliArguments private hasConfigurationCapability = false constructor () { const cliArgs = getCliArgs() this.defaultConfiguration = { installPath: '', matlabConnectionTiming: ConnectionTiming.OnStart, indexWorkspace: false, telemetry: true } this.globalSettings = { installPath: cliArgs[Argument.MatlabInstallationPath] ?? this.defaultConfiguration.installPath, matlabConnectionTiming: cliArgs[Argument.MatlabConnectionTiming] as ConnectionTiming ?? this.defaultConfiguration.matlabConnectionTiming, indexWorkspace: cliArgs[Argument.ShouldIndexWorkspace] ?? this.defaultConfiguration.indexWorkspace, telemetry: this.defaultConfiguration.telemetry } this.additionalArguments = { [Argument.MatlabLaunchCommandArguments]: cliArgs[Argument.MatlabLaunchCommandArguments] ?? '', [Argument.MatlabUrl]: cliArgs[Argument.MatlabUrl] ?? '' } } /** * Sets up the configuration manager * * @param capabilities The client capabilities */ setup (capabilities: ClientCapabilities): void { this.hasConfigurationCapability = capabilities.workspace?.configuration != null if (this.hasConfigurationCapability) { // Register for configuration changes void connection.client.register(DidChangeConfigurationNotification.type) } connection.
onDidChangeConfiguration(params => { void this.handleConfigurationChanged(params) }) }
/** * Gets the configuration for the langauge server * * @returns The current configuration */ async getConfiguration (): Promise<Settings> { if (this.hasConfigurationCapability) { if (this.configuration == null) { this.configuration = await connection.workspace.getConfiguration('MATLAB') as Settings } return this.configuration } return this.globalSettings } /** * Gets the value of the given argument * * @param argument The argument * @returns The argument's value */ getArgument (argument: Argument.MatlabLaunchCommandArguments | Argument.MatlabUrl): string { return this.additionalArguments[argument] } /** * Handles a change in the configuration * @param params The configuration changed params */ private async handleConfigurationChanged (params: DidChangeConfigurationParams): Promise<void> { let oldConfig: Settings | null let newConfig: Settings if (this.hasConfigurationCapability) { oldConfig = this.configuration // Clear cached configuration this.configuration = null // Force load new configuration newConfig = await this.getConfiguration() } else { oldConfig = this.globalSettings this.globalSettings = params.settings?.matlab ?? this.defaultConfiguration newConfig = this.globalSettings } this.compareSettingChanges(oldConfig, newConfig) } private compareSettingChanges (oldConfiguration: Settings | null, newConfiguration: Settings): void { if (oldConfiguration == null) { // Not yet initialized return } for (let i = 0; i < SETTING_NAMES.length; i++) { const settingName = SETTING_NAMES[i] const oldValue = oldConfiguration[settingName] const newValue = newConfiguration[settingName] if (oldValue !== newValue) { reportTelemetrySettingsChange(settingName, newValue.toString(), oldValue.toString()) } } } } export default new ConfigurationManager()
src/lifecycle/ConfigurationManager.ts
mathworks-MATLAB-language-server-94cac1b
[ { "filename": "src/indexing/WorkspaceIndexer.ts", "retrieved_chunk": " private isWorkspaceIndexingSupported = false\n /**\n * Sets up workspace change listeners, if supported.\n *\n * @param capabilities The client capabilities, which contains information about\n * whether the client supports workspaces.\n */\n setupCallbacks (capabilities: ClientCapabilities): void {\n this.isWorkspaceIndexingSupported = capabilities.workspace?.workspaceFolders ?? false\n if (!this.isWorkspaceIndexingSupported) {", "score": 0.8675468564033508 }, { "filename": "src/server.ts", "retrieved_chunk": " triggerCharacters: ['(', ',']\n },\n documentSymbolProvider: true\n }\n }\n return initResult\n})\n// Handles the initialized notification\nconnection.onInitialized(() => {\n ConfigurationManager.setup(capabilities)", "score": 0.8626165390014648 }, { "filename": "src/server.ts", "retrieved_chunk": " void LintingSupportProvider.lintDocument(textDocument, connection)\n void DocumentIndexer.indexDocument(textDocument)\n })\n }\n})\nlet capabilities: ClientCapabilities\n// Handles an initialization request\nconnection.onInitialize((params: InitializeParams) => {\n capabilities = params.capabilities\n // Defines the capabilities supported by this language server", "score": 0.8319694995880127 }, { "filename": "src/server.ts", "retrieved_chunk": " WorkspaceIndexer.setupCallbacks(capabilities)\n void startMatlabIfOnStartLaunch()\n})\nasync function startMatlabIfOnStartLaunch (): Promise<void> {\n // Launch MATLAB if it should be launched early\n const connectionTiming = (await ConfigurationManager.getConfiguration()).matlabConnectionTiming\n if (connectionTiming === ConnectionTiming.OnStart) {\n void MatlabLifecycleManager.connectToMatlab(connection)\n }\n}", "score": 0.8283275961875916 }, { "filename": "src/notifications/NotificationService.ts", "retrieved_chunk": " registerNotificationListener (name: string, callback: GenericNotificationHandler): void {\n connection.onNotification(name, callback)\n }\n}\nexport default new NotificationService()", "score": 0.8192124962806702 } ]
typescript
onDidChangeConfiguration(params => { void this.handleConfigurationChanged(params) }) }
// Copyright 2022 - 2023 The MathWorks, Inc. import { ClientCapabilities, WorkspaceFolder, WorkspaceFoldersChangeEvent } from 'vscode-languageserver' import ConfigurationManager from '../lifecycle/ConfigurationManager' import { connection } from '../server' import Indexer from './Indexer' /** * Handles indexing files in the user's workspace to gather data about classes, * functions, and variables. */ class WorkspaceIndexer { private isWorkspaceIndexingSupported = false /** * Sets up workspace change listeners, if supported. * * @param capabilities The client capabilities, which contains information about * whether the client supports workspaces. */ setupCallbacks (capabilities: ClientCapabilities): void { this.isWorkspaceIndexingSupported = capabilities.workspace?.workspaceFolders ?? false if (!this.isWorkspaceIndexingSupported) { // Workspace indexing not supported return } connection.workspace.onDidChangeWorkspaceFolders((params: WorkspaceFoldersChangeEvent) => { void this.handleWorkspaceFoldersAdded(params.added) }) } /** * Attempts to index the files in the user's workspace. */ async indexWorkspace (): Promise<void> { if (!(await this.shouldIndexWorkspace())) { return } const folders = await connection.workspace.getWorkspaceFolders() if (folders == null) { return } Indexer.indexFolders(folders.map
(folder => folder.uri)) }
/** * Handles when new folders are added to the user's workspace by indexing them. * * @param folders The list of folders added to the workspace */ private async handleWorkspaceFoldersAdded (folders: WorkspaceFolder[]): Promise<void> { if (!(await this.shouldIndexWorkspace())) { return } Indexer.indexFolders(folders.map(folder => folder.uri)) } /** * Determines whether or not the workspace should be indexed. * The workspace should be indexed if the client supports workspaces, and if the * workspace indexing setting is true. * * @returns True if workspace indexing should occurr, false otherwise. */ private async shouldIndexWorkspace (): Promise<boolean> { const shouldIndexWorkspace = (await ConfigurationManager.getConfiguration()).indexWorkspace return this.isWorkspaceIndexingSupported && shouldIndexWorkspace } } export default new WorkspaceIndexer()
src/indexing/WorkspaceIndexer.ts
mathworks-MATLAB-language-server-94cac1b
[ { "filename": "src/indexing/Indexer.ts", "retrieved_chunk": " if (uri !== '') {\n void this.indexFile(uri)\n }\n })\n }\n}\nexport default new Indexer()", "score": 0.8475215435028076 }, { "filename": "src/indexing/DocumentIndexer.ts", "retrieved_chunk": " if (!FileInfoIndex.codeDataCache.has(uri)) {\n await Indexer.indexDocument(textDocument)\n }\n }\n}\nexport default new DocumentIndexer()", "score": 0.8440804481506348 }, { "filename": "src/indexing/Indexer.ts", "retrieved_chunk": " const parsedCodeData = FileInfoIndex.parseAndStoreCodeData(textDocument.uri, rawCodeData)\n void this.indexAdditionalClassData(parsedCodeData, matlabConnection, textDocument.uri)\n }\n /**\n * Indexes all M files within the given list of folders.\n *\n * @param folders A list of folder URIs to be indexed\n */\n indexFolders (folders: string[]): void {\n const matlabConnection = MatlabLifecycleManager.getMatlabConnection()", "score": 0.827638566493988 }, { "filename": "src/indexing/Indexer.ts", "retrieved_chunk": " // Convert file path to URI, which is used as an index when storing the code data\n const fileUri = URI.file(fileResults.filePath).toString()\n FileInfoIndex.parseAndStoreCodeData(fileUri, fileResults.codeData)\n })\n matlabConnection.publish(this.INDEX_FOLDERS_REQUEST_CHANNEL, {\n folders,\n requestId\n })\n }\n /**", "score": 0.8254604339599609 }, { "filename": "src/indexing/Indexer.ts", "retrieved_chunk": " // Queue indexing for other files in @ class directory\n const classDefFolder = parsedCodeData.classInfo.classDefFolder\n if (classDefFolder !== '') {\n this.indexFolders([classDefFolder])\n }\n // Find and queue indexing for parent classes\n const baseClasses = parsedCodeData.classInfo.baseClasses\n const resolvedBaseClasses = await PathResolver.resolvePaths(baseClasses, uri, matlabConnection)\n resolvedBaseClasses.forEach(resolvedBaseClass => {\n const uri = resolvedBaseClass.uri", "score": 0.8246771693229675 } ]
typescript
(folder => folder.uri)) }
// Copyright 2022 - 2023 The MathWorks, Inc. import { TextDocument } from 'vscode-languageserver-textdocument' import Indexer from './Indexer' import FileInfoIndex from './FileInfoIndex' const INDEXING_DELAY = 500 // Delay (in ms) after keystroke before attempting to re-index the document /** * Handles indexing a currently open document to gather data about classes, * functions, and variables. */ class DocumentIndexer { private readonly pendingFilesToIndex = new Map<string, NodeJS.Timer>() /** * Queues a document to be indexed. This handles debouncing so that * indexing is not performed on every keystroke. * * @param textDocument The document to be indexed */ queueIndexingForDocument (textDocument: TextDocument): void { const uri = textDocument.uri this.clearTimerForDocumentUri(uri) this.pendingFilesToIndex.set( uri, setTimeout(() => { this.indexDocument(textDocument) }, INDEXING_DELAY) // Specify timeout for debouncing, to avoid re-indexing every keystroke while a user types ) } /** * Indexes the document and caches the data. * * @param textDocument The document being indexed */ indexDocument (textDocument: TextDocument): void { void Indexer.indexDocument(textDocument) } /** * Clears any active indexing timers for the provided document URI. * * @param uri The document URI */ private clearTimerForDocumentUri (uri: string): void { const timerId = this.pendingFilesToIndex.get(uri) if (timerId != null) { clearTimeout(timerId) this.pendingFilesToIndex.delete(uri) } } /** * Ensure that @param textDocument is fully indexed and up to date by flushing any pending indexing tasks * and then forcing an index. This is intended to service requests like documentSymbols where returning * stale info could be confusing. * * @param textDocument The document to index */ async ensureDocumentIndexIsUpdated (textDocument: TextDocument): Promise<void> { const uri = textDocument.uri if (this.pendingFilesToIndex.has(uri)) { this.clearTimerForDocumentUri(uri) await Indexer.indexDocument(textDocument) }
if (!FileInfoIndex.codeDataCache.has(uri)) {
await Indexer.indexDocument(textDocument) } } } export default new DocumentIndexer()
src/indexing/DocumentIndexer.ts
mathworks-MATLAB-language-server-94cac1b
[ { "filename": "src/indexing/Indexer.ts", "retrieved_chunk": " * Indexes the given TextDocument and caches the data.\n *\n * @param textDocument The document being indexed\n */\n async indexDocument (textDocument: TextDocument): Promise<void> {\n const matlabConnection = MatlabLifecycleManager.getMatlabConnection()\n if (matlabConnection == null || !MatlabLifecycleManager.isMatlabReady()) {\n return\n }\n const rawCodeData = await this.getCodeData(textDocument.getText(), textDocument.uri, matlabConnection)", "score": 0.8864030838012695 }, { "filename": "src/providers/linting/LintingSupportProvider.ts", "retrieved_chunk": " * that linting is not performed on every keystroke.\n *\n * @param textDocument The document to be linted\n * @param connection The language server connection\n */\n queueLintingForDocument (textDocument: TextDocument, connection: _Connection): void {\n const uri = textDocument.uri\n this.clearTimerForDocumentUri(uri)\n this._pendingFilesToLint.set(\n uri,", "score": 0.8422949314117432 }, { "filename": "src/providers/navigation/NavigationSupportProvider.ts", "retrieved_chunk": " }\n // Ensure document index is up to date\n await DocumentIndexer.ensureDocumentIndexIsUpdated(textDocument)\n const codeData = FileInfoIndex.codeDataCache.get(uri)\n if (codeData == null) {\n reportTelemetry(requestType, 'No code data')\n return []\n }\n // Result symbols in documented\n const result: SymbolInformation[] = []", "score": 0.8357545733451843 }, { "filename": "src/providers/linting/LintingSupportProvider.ts", "retrieved_chunk": " */\n async lintDocument (textDocument: TextDocument, connection: _Connection): Promise<void> {\n const uri = textDocument.uri\n this.clearTimerForDocumentUri(uri)\n this.clearCodeActionsForDocumentUri(uri)\n const matlabConnection = MatlabLifecycleManager.getMatlabConnection()\n const isMatlabAvailable = (matlabConnection != null) && MatlabLifecycleManager.isMatlabReady()\n const fileName = URI.parse(uri).fsPath\n let lintData: string[] = []\n if (isMatlabAvailable) {", "score": 0.8346942067146301 }, { "filename": "src/providers/linting/LintingSupportProvider.ts", "retrieved_chunk": " */\n private clearTimerForDocumentUri (uri: string): void {\n const timerId = this._pendingFilesToLint.get(uri)\n if (timerId != null) {\n clearTimeout(timerId)\n this._pendingFilesToLint.delete(uri)\n }\n }\n /**\n * Clears any cached code actions for the provided document URI.", "score": 0.8228779435157776 } ]
typescript
if (!FileInfoIndex.codeDataCache.has(uri)) {
// Copyright 2022 - 2023 The MathWorks, Inc. import { ClientCapabilities, DidChangeConfigurationNotification, DidChangeConfigurationParams } from 'vscode-languageserver' import { reportTelemetrySettingsChange } from '../logging/TelemetryUtils' import { connection } from '../server' import { getCliArgs } from '../utils/CliUtils' export enum Argument { // Basic arguments MatlabLaunchCommandArguments = 'matlabLaunchCommandArgs', MatlabInstallationPath = 'matlabInstallPath', MatlabConnectionTiming = 'matlabConnectionTiming', ShouldIndexWorkspace = 'indexWorkspace', // Advanced arguments MatlabUrl = 'matlabUrl' } export enum ConnectionTiming { OnStart = 'onStart', OnDemand = 'onDemand', Never = 'never' } interface CliArguments { [Argument.MatlabLaunchCommandArguments]: string [Argument.MatlabUrl]: string } interface Settings { installPath: string matlabConnectionTiming: ConnectionTiming indexWorkspace: boolean telemetry: boolean } type SettingName = 'installPath' | 'matlabConnectionTiming' | 'indexWorkspace' | 'telemetry' const SETTING_NAMES: SettingName[] = [ 'installPath', 'matlabConnectionTiming', 'indexWorkspace', 'telemetry' ] class ConfigurationManager { private configuration: Settings | null = null private readonly defaultConfiguration: Settings private globalSettings: Settings // Holds additional command line arguments that are not part of the configuration private readonly additionalArguments: CliArguments private hasConfigurationCapability = false constructor () {
const cliArgs = getCliArgs() this.defaultConfiguration = {
installPath: '', matlabConnectionTiming: ConnectionTiming.OnStart, indexWorkspace: false, telemetry: true } this.globalSettings = { installPath: cliArgs[Argument.MatlabInstallationPath] ?? this.defaultConfiguration.installPath, matlabConnectionTiming: cliArgs[Argument.MatlabConnectionTiming] as ConnectionTiming ?? this.defaultConfiguration.matlabConnectionTiming, indexWorkspace: cliArgs[Argument.ShouldIndexWorkspace] ?? this.defaultConfiguration.indexWorkspace, telemetry: this.defaultConfiguration.telemetry } this.additionalArguments = { [Argument.MatlabLaunchCommandArguments]: cliArgs[Argument.MatlabLaunchCommandArguments] ?? '', [Argument.MatlabUrl]: cliArgs[Argument.MatlabUrl] ?? '' } } /** * Sets up the configuration manager * * @param capabilities The client capabilities */ setup (capabilities: ClientCapabilities): void { this.hasConfigurationCapability = capabilities.workspace?.configuration != null if (this.hasConfigurationCapability) { // Register for configuration changes void connection.client.register(DidChangeConfigurationNotification.type) } connection.onDidChangeConfiguration(params => { void this.handleConfigurationChanged(params) }) } /** * Gets the configuration for the langauge server * * @returns The current configuration */ async getConfiguration (): Promise<Settings> { if (this.hasConfigurationCapability) { if (this.configuration == null) { this.configuration = await connection.workspace.getConfiguration('MATLAB') as Settings } return this.configuration } return this.globalSettings } /** * Gets the value of the given argument * * @param argument The argument * @returns The argument's value */ getArgument (argument: Argument.MatlabLaunchCommandArguments | Argument.MatlabUrl): string { return this.additionalArguments[argument] } /** * Handles a change in the configuration * @param params The configuration changed params */ private async handleConfigurationChanged (params: DidChangeConfigurationParams): Promise<void> { let oldConfig: Settings | null let newConfig: Settings if (this.hasConfigurationCapability) { oldConfig = this.configuration // Clear cached configuration this.configuration = null // Force load new configuration newConfig = await this.getConfiguration() } else { oldConfig = this.globalSettings this.globalSettings = params.settings?.matlab ?? this.defaultConfiguration newConfig = this.globalSettings } this.compareSettingChanges(oldConfig, newConfig) } private compareSettingChanges (oldConfiguration: Settings | null, newConfiguration: Settings): void { if (oldConfiguration == null) { // Not yet initialized return } for (let i = 0; i < SETTING_NAMES.length; i++) { const settingName = SETTING_NAMES[i] const oldValue = oldConfiguration[settingName] const newValue = newConfiguration[settingName] if (oldValue !== newValue) { reportTelemetrySettingsChange(settingName, newValue.toString(), oldValue.toString()) } } } } export default new ConfigurationManager()
src/lifecycle/ConfigurationManager.ts
mathworks-MATLAB-language-server-94cac1b
[ { "filename": "src/lifecycle/MatlabLifecycleManager.ts", "retrieved_chunk": " }\n const argsFromSettings = ConfigurationManager.getArgument(Argument.MatlabLaunchCommandArguments) ?? null\n if (argsFromSettings != null) {\n args.push(argsFromSettings)\n }\n return {\n command,\n args\n }\n }", "score": 0.8129938244819641 }, { "filename": "src/utils/CliUtils.ts", "retrieved_chunk": "// Copyright 2022 - 2023 The MathWorks, Inc.\nimport * as yargs from 'yargs'\nimport { Argument } from '../lifecycle/ConfigurationManager'\nexport interface CliArgs {\n [Argument.MatlabLaunchCommandArguments]?: string\n [Argument.MatlabInstallationPath]?: string\n [Argument.MatlabConnectionTiming]?: string\n [Argument.ShouldIndexWorkspace]?: boolean\n [Argument.MatlabUrl]?: string\n}", "score": 0.8100069165229797 }, { "filename": "src/utils/CliUtils.ts", "retrieved_chunk": " * @returns The parsed CLI arguments\n */\nexport function getCliArgs (args?: string[]): CliArgs {\n const cliParser = makeParser()\n return (args != null) ? cliParser.parseSync(args) : cliParser.parseSync()\n}", "score": 0.7917985320091248 }, { "filename": "src/utils/CliUtils.ts", "retrieved_chunk": "/**\n * Creates a yargs parser to extract command line arguments.\n *\n * @returns The parsed command line arguments\n */\nfunction makeParser (): yargs.Argv<CliArgs> {\n const argParser = yargs.option(Argument.MatlabLaunchCommandArguments, {\n description: 'Arguments passed to MATLAB when launching',\n type: 'string',\n requiresArg: true", "score": 0.7729403972625732 }, { "filename": "src/server.ts", "retrieved_chunk": " const initResult: InitializeResult = {\n capabilities: {\n codeActionProvider: true,\n completionProvider: {\n triggerCharacters: [\n '.', // Struct/class properties, package names, etc.\n '(', // Function call\n ' ', // Command-style function call\n ',', // Function arguments\n '/', // File path", "score": 0.7722415924072266 } ]
typescript
const cliArgs = getCliArgs() this.defaultConfiguration = {
// Copyright 2022 - 2023 The MathWorks, Inc. import { ClientCapabilities, DidChangeConfigurationNotification, DidChangeConfigurationParams } from 'vscode-languageserver' import { reportTelemetrySettingsChange } from '../logging/TelemetryUtils' import { connection } from '../server' import { getCliArgs } from '../utils/CliUtils' export enum Argument { // Basic arguments MatlabLaunchCommandArguments = 'matlabLaunchCommandArgs', MatlabInstallationPath = 'matlabInstallPath', MatlabConnectionTiming = 'matlabConnectionTiming', ShouldIndexWorkspace = 'indexWorkspace', // Advanced arguments MatlabUrl = 'matlabUrl' } export enum ConnectionTiming { OnStart = 'onStart', OnDemand = 'onDemand', Never = 'never' } interface CliArguments { [Argument.MatlabLaunchCommandArguments]: string [Argument.MatlabUrl]: string } interface Settings { installPath: string matlabConnectionTiming: ConnectionTiming indexWorkspace: boolean telemetry: boolean } type SettingName = 'installPath' | 'matlabConnectionTiming' | 'indexWorkspace' | 'telemetry' const SETTING_NAMES: SettingName[] = [ 'installPath', 'matlabConnectionTiming', 'indexWorkspace', 'telemetry' ] class ConfigurationManager { private configuration: Settings | null = null private readonly defaultConfiguration: Settings private globalSettings: Settings // Holds additional command line arguments that are not part of the configuration private readonly additionalArguments: CliArguments private hasConfigurationCapability = false constructor () { const cliArgs = getCliArgs() this.defaultConfiguration = { installPath: '', matlabConnectionTiming: ConnectionTiming.OnStart, indexWorkspace: false, telemetry: true } this.globalSettings = { installPath: cliArgs[Argument.MatlabInstallationPath] ?? this.defaultConfiguration.installPath, matlabConnectionTiming: cliArgs[Argument.MatlabConnectionTiming] as ConnectionTiming ?? this.defaultConfiguration.matlabConnectionTiming, indexWorkspace: cliArgs[Argument.ShouldIndexWorkspace] ?? this.defaultConfiguration.indexWorkspace, telemetry: this.defaultConfiguration.telemetry } this.additionalArguments = { [Argument.MatlabLaunchCommandArguments]: cliArgs[Argument.MatlabLaunchCommandArguments] ?? '', [Argument.MatlabUrl]: cliArgs[Argument.MatlabUrl] ?? '' } } /** * Sets up the configuration manager * * @param capabilities The client capabilities */ setup (capabilities: ClientCapabilities): void { this.hasConfigurationCapability = capabilities.workspace?.configuration != null if (this.hasConfigurationCapability) { // Register for configuration changes void
connection.client.register(DidChangeConfigurationNotification.type) }
connection.onDidChangeConfiguration(params => { void this.handleConfigurationChanged(params) }) } /** * Gets the configuration for the langauge server * * @returns The current configuration */ async getConfiguration (): Promise<Settings> { if (this.hasConfigurationCapability) { if (this.configuration == null) { this.configuration = await connection.workspace.getConfiguration('MATLAB') as Settings } return this.configuration } return this.globalSettings } /** * Gets the value of the given argument * * @param argument The argument * @returns The argument's value */ getArgument (argument: Argument.MatlabLaunchCommandArguments | Argument.MatlabUrl): string { return this.additionalArguments[argument] } /** * Handles a change in the configuration * @param params The configuration changed params */ private async handleConfigurationChanged (params: DidChangeConfigurationParams): Promise<void> { let oldConfig: Settings | null let newConfig: Settings if (this.hasConfigurationCapability) { oldConfig = this.configuration // Clear cached configuration this.configuration = null // Force load new configuration newConfig = await this.getConfiguration() } else { oldConfig = this.globalSettings this.globalSettings = params.settings?.matlab ?? this.defaultConfiguration newConfig = this.globalSettings } this.compareSettingChanges(oldConfig, newConfig) } private compareSettingChanges (oldConfiguration: Settings | null, newConfiguration: Settings): void { if (oldConfiguration == null) { // Not yet initialized return } for (let i = 0; i < SETTING_NAMES.length; i++) { const settingName = SETTING_NAMES[i] const oldValue = oldConfiguration[settingName] const newValue = newConfiguration[settingName] if (oldValue !== newValue) { reportTelemetrySettingsChange(settingName, newValue.toString(), oldValue.toString()) } } } } export default new ConfigurationManager()
src/lifecycle/ConfigurationManager.ts
mathworks-MATLAB-language-server-94cac1b
[ { "filename": "src/indexing/WorkspaceIndexer.ts", "retrieved_chunk": " private isWorkspaceIndexingSupported = false\n /**\n * Sets up workspace change listeners, if supported.\n *\n * @param capabilities The client capabilities, which contains information about\n * whether the client supports workspaces.\n */\n setupCallbacks (capabilities: ClientCapabilities): void {\n this.isWorkspaceIndexingSupported = capabilities.workspace?.workspaceFolders ?? false\n if (!this.isWorkspaceIndexingSupported) {", "score": 0.8792648315429688 }, { "filename": "src/server.ts", "retrieved_chunk": " triggerCharacters: ['(', ',']\n },\n documentSymbolProvider: true\n }\n }\n return initResult\n})\n// Handles the initialized notification\nconnection.onInitialized(() => {\n ConfigurationManager.setup(capabilities)", "score": 0.8511715531349182 }, { "filename": "src/server.ts", "retrieved_chunk": " WorkspaceIndexer.setupCallbacks(capabilities)\n void startMatlabIfOnStartLaunch()\n})\nasync function startMatlabIfOnStartLaunch (): Promise<void> {\n // Launch MATLAB if it should be launched early\n const connectionTiming = (await ConfigurationManager.getConfiguration()).matlabConnectionTiming\n if (connectionTiming === ConnectionTiming.OnStart) {\n void MatlabLifecycleManager.connectToMatlab(connection)\n }\n}", "score": 0.8197289109230042 }, { "filename": "src/server.ts", "retrieved_chunk": " void LintingSupportProvider.lintDocument(textDocument, connection)\n void DocumentIndexer.indexDocument(textDocument)\n })\n }\n})\nlet capabilities: ClientCapabilities\n// Handles an initialization request\nconnection.onInitialize((params: InitializeParams) => {\n capabilities = params.capabilities\n // Defines the capabilities supported by this language server", "score": 0.8176645636558533 }, { "filename": "src/notifications/NotificationService.ts", "retrieved_chunk": " */\n sendNotification (name: string, params?: unknown): void {\n void connection.sendNotification(name, params)\n }\n /**\n * Sets up a listener for notifications from the language client\n *\n * @param name The name of the notification\n * @param callback The callback\n */", "score": 0.7925733923912048 } ]
typescript
connection.client.register(DidChangeConfigurationNotification.type) }
// Copyright 2022 - 2023 The MathWorks, Inc. import { ClientCapabilities, DidChangeConfigurationNotification, DidChangeConfigurationParams } from 'vscode-languageserver' import { reportTelemetrySettingsChange } from '../logging/TelemetryUtils' import { connection } from '../server' import { getCliArgs } from '../utils/CliUtils' export enum Argument { // Basic arguments MatlabLaunchCommandArguments = 'matlabLaunchCommandArgs', MatlabInstallationPath = 'matlabInstallPath', MatlabConnectionTiming = 'matlabConnectionTiming', ShouldIndexWorkspace = 'indexWorkspace', // Advanced arguments MatlabUrl = 'matlabUrl' } export enum ConnectionTiming { OnStart = 'onStart', OnDemand = 'onDemand', Never = 'never' } interface CliArguments { [Argument.MatlabLaunchCommandArguments]: string [Argument.MatlabUrl]: string } interface Settings { installPath: string matlabConnectionTiming: ConnectionTiming indexWorkspace: boolean telemetry: boolean } type SettingName = 'installPath' | 'matlabConnectionTiming' | 'indexWorkspace' | 'telemetry' const SETTING_NAMES: SettingName[] = [ 'installPath', 'matlabConnectionTiming', 'indexWorkspace', 'telemetry' ] class ConfigurationManager { private configuration: Settings | null = null private readonly defaultConfiguration: Settings private globalSettings: Settings // Holds additional command line arguments that are not part of the configuration private readonly additionalArguments: CliArguments private hasConfigurationCapability = false constructor () { const cliArgs =
getCliArgs() this.defaultConfiguration = {
installPath: '', matlabConnectionTiming: ConnectionTiming.OnStart, indexWorkspace: false, telemetry: true } this.globalSettings = { installPath: cliArgs[Argument.MatlabInstallationPath] ?? this.defaultConfiguration.installPath, matlabConnectionTiming: cliArgs[Argument.MatlabConnectionTiming] as ConnectionTiming ?? this.defaultConfiguration.matlabConnectionTiming, indexWorkspace: cliArgs[Argument.ShouldIndexWorkspace] ?? this.defaultConfiguration.indexWorkspace, telemetry: this.defaultConfiguration.telemetry } this.additionalArguments = { [Argument.MatlabLaunchCommandArguments]: cliArgs[Argument.MatlabLaunchCommandArguments] ?? '', [Argument.MatlabUrl]: cliArgs[Argument.MatlabUrl] ?? '' } } /** * Sets up the configuration manager * * @param capabilities The client capabilities */ setup (capabilities: ClientCapabilities): void { this.hasConfigurationCapability = capabilities.workspace?.configuration != null if (this.hasConfigurationCapability) { // Register for configuration changes void connection.client.register(DidChangeConfigurationNotification.type) } connection.onDidChangeConfiguration(params => { void this.handleConfigurationChanged(params) }) } /** * Gets the configuration for the langauge server * * @returns The current configuration */ async getConfiguration (): Promise<Settings> { if (this.hasConfigurationCapability) { if (this.configuration == null) { this.configuration = await connection.workspace.getConfiguration('MATLAB') as Settings } return this.configuration } return this.globalSettings } /** * Gets the value of the given argument * * @param argument The argument * @returns The argument's value */ getArgument (argument: Argument.MatlabLaunchCommandArguments | Argument.MatlabUrl): string { return this.additionalArguments[argument] } /** * Handles a change in the configuration * @param params The configuration changed params */ private async handleConfigurationChanged (params: DidChangeConfigurationParams): Promise<void> { let oldConfig: Settings | null let newConfig: Settings if (this.hasConfigurationCapability) { oldConfig = this.configuration // Clear cached configuration this.configuration = null // Force load new configuration newConfig = await this.getConfiguration() } else { oldConfig = this.globalSettings this.globalSettings = params.settings?.matlab ?? this.defaultConfiguration newConfig = this.globalSettings } this.compareSettingChanges(oldConfig, newConfig) } private compareSettingChanges (oldConfiguration: Settings | null, newConfiguration: Settings): void { if (oldConfiguration == null) { // Not yet initialized return } for (let i = 0; i < SETTING_NAMES.length; i++) { const settingName = SETTING_NAMES[i] const oldValue = oldConfiguration[settingName] const newValue = newConfiguration[settingName] if (oldValue !== newValue) { reportTelemetrySettingsChange(settingName, newValue.toString(), oldValue.toString()) } } } } export default new ConfigurationManager()
src/lifecycle/ConfigurationManager.ts
mathworks-MATLAB-language-server-94cac1b
[ { "filename": "src/utils/CliUtils.ts", "retrieved_chunk": "// Copyright 2022 - 2023 The MathWorks, Inc.\nimport * as yargs from 'yargs'\nimport { Argument } from '../lifecycle/ConfigurationManager'\nexport interface CliArgs {\n [Argument.MatlabLaunchCommandArguments]?: string\n [Argument.MatlabInstallationPath]?: string\n [Argument.MatlabConnectionTiming]?: string\n [Argument.ShouldIndexWorkspace]?: boolean\n [Argument.MatlabUrl]?: string\n}", "score": 0.8203953504562378 }, { "filename": "src/lifecycle/MatlabLifecycleManager.ts", "retrieved_chunk": " }\n const argsFromSettings = ConfigurationManager.getArgument(Argument.MatlabLaunchCommandArguments) ?? null\n if (argsFromSettings != null) {\n args.push(argsFromSettings)\n }\n return {\n command,\n args\n }\n }", "score": 0.8123488426208496 }, { "filename": "src/utils/CliUtils.ts", "retrieved_chunk": " * @returns The parsed CLI arguments\n */\nexport function getCliArgs (args?: string[]): CliArgs {\n const cliParser = makeParser()\n return (args != null) ? cliParser.parseSync(args) : cliParser.parseSync()\n}", "score": 0.8049278855323792 }, { "filename": "src/server.ts", "retrieved_chunk": " const initResult: InitializeResult = {\n capabilities: {\n codeActionProvider: true,\n completionProvider: {\n triggerCharacters: [\n '.', // Struct/class properties, package names, etc.\n '(', // Function call\n ' ', // Command-style function call\n ',', // Function arguments\n '/', // File path", "score": 0.7876201868057251 }, { "filename": "src/utils/CliUtils.ts", "retrieved_chunk": "/**\n * Creates a yargs parser to extract command line arguments.\n *\n * @returns The parsed command line arguments\n */\nfunction makeParser (): yargs.Argv<CliArgs> {\n const argParser = yargs.option(Argument.MatlabLaunchCommandArguments, {\n description: 'Arguments passed to MATLAB when launching',\n type: 'string',\n requiresArg: true", "score": 0.783331573009491 } ]
typescript
getCliArgs() this.defaultConfiguration = {
// Copyright 2022 - 2023 The MathWorks, Inc. import { ClientCapabilities, DidChangeConfigurationNotification, DidChangeConfigurationParams } from 'vscode-languageserver' import { reportTelemetrySettingsChange } from '../logging/TelemetryUtils' import { connection } from '../server' import { getCliArgs } from '../utils/CliUtils' export enum Argument { // Basic arguments MatlabLaunchCommandArguments = 'matlabLaunchCommandArgs', MatlabInstallationPath = 'matlabInstallPath', MatlabConnectionTiming = 'matlabConnectionTiming', ShouldIndexWorkspace = 'indexWorkspace', // Advanced arguments MatlabUrl = 'matlabUrl' } export enum ConnectionTiming { OnStart = 'onStart', OnDemand = 'onDemand', Never = 'never' } interface CliArguments { [Argument.MatlabLaunchCommandArguments]: string [Argument.MatlabUrl]: string } interface Settings { installPath: string matlabConnectionTiming: ConnectionTiming indexWorkspace: boolean telemetry: boolean } type SettingName = 'installPath' | 'matlabConnectionTiming' | 'indexWorkspace' | 'telemetry' const SETTING_NAMES: SettingName[] = [ 'installPath', 'matlabConnectionTiming', 'indexWorkspace', 'telemetry' ] class ConfigurationManager { private configuration: Settings | null = null private readonly defaultConfiguration: Settings private globalSettings: Settings // Holds additional command line arguments that are not part of the configuration private readonly additionalArguments: CliArguments private hasConfigurationCapability = false constructor () { const cliArgs = getCliArgs() this.defaultConfiguration = { installPath: '', matlabConnectionTiming: ConnectionTiming.OnStart, indexWorkspace: false, telemetry: true } this.globalSettings = { installPath: cliArgs[Argument.MatlabInstallationPath] ?? this.defaultConfiguration.installPath, matlabConnectionTiming: cliArgs[Argument.MatlabConnectionTiming] as ConnectionTiming ?? this.defaultConfiguration.matlabConnectionTiming, indexWorkspace: cliArgs[Argument.ShouldIndexWorkspace] ?? this.defaultConfiguration.indexWorkspace, telemetry: this.defaultConfiguration.telemetry } this.additionalArguments = { [Argument.MatlabLaunchCommandArguments]: cliArgs[Argument.MatlabLaunchCommandArguments] ?? '', [Argument.MatlabUrl]: cliArgs[Argument.MatlabUrl] ?? '' } } /** * Sets up the configuration manager * * @param capabilities The client capabilities */ setup (capabilities: ClientCapabilities): void { this.hasConfigurationCapability = capabilities.workspace?.configuration != null if (this.hasConfigurationCapability) { // Register for configuration changes void connection.client.register(DidChangeConfigurationNotification.type) } connection.onDidChangeConfiguration(params => { void this.handleConfigurationChanged(params) }) } /** * Gets the configuration for the langauge server * * @returns The current configuration */ async getConfiguration (): Promise<Settings> { if (this.hasConfigurationCapability) { if (this.configuration == null) { this.configuration
= await connection.workspace.getConfiguration('MATLAB') as Settings }
return this.configuration } return this.globalSettings } /** * Gets the value of the given argument * * @param argument The argument * @returns The argument's value */ getArgument (argument: Argument.MatlabLaunchCommandArguments | Argument.MatlabUrl): string { return this.additionalArguments[argument] } /** * Handles a change in the configuration * @param params The configuration changed params */ private async handleConfigurationChanged (params: DidChangeConfigurationParams): Promise<void> { let oldConfig: Settings | null let newConfig: Settings if (this.hasConfigurationCapability) { oldConfig = this.configuration // Clear cached configuration this.configuration = null // Force load new configuration newConfig = await this.getConfiguration() } else { oldConfig = this.globalSettings this.globalSettings = params.settings?.matlab ?? this.defaultConfiguration newConfig = this.globalSettings } this.compareSettingChanges(oldConfig, newConfig) } private compareSettingChanges (oldConfiguration: Settings | null, newConfiguration: Settings): void { if (oldConfiguration == null) { // Not yet initialized return } for (let i = 0; i < SETTING_NAMES.length; i++) { const settingName = SETTING_NAMES[i] const oldValue = oldConfiguration[settingName] const newValue = newConfiguration[settingName] if (oldValue !== newValue) { reportTelemetrySettingsChange(settingName, newValue.toString(), oldValue.toString()) } } } } export default new ConfigurationManager()
src/lifecycle/ConfigurationManager.ts
mathworks-MATLAB-language-server-94cac1b
[ { "filename": "src/lifecycle/MatlabLifecycleManager.ts", "retrieved_chunk": " isMatlabReady (): boolean {\n return Boolean(this._matlabProcess?.isMatlabReady())\n }\n /**\n * Gets the active connection to MATLAB. Does not attempt to create a connection if\n * one does not currently exist.\n *\n * @returns The connection to MATLAB, or null if there is no active connection.\n */\n getMatlabConnection (): MatlabConnection | null {", "score": 0.829688310623169 }, { "filename": "src/lifecycle/MatlabLifecycleManager.ts", "retrieved_chunk": " * @param connection The language server connection\n * @returns The connected MATLAB process\n */\n private async _connectToExistingMatlab (connection: _Connection): Promise<MatlabProcess> {\n const url = ConfigurationManager.getArgument(Argument.MatlabUrl)\n if (this._matlabProcess == null || !this._matlabProcess.isValid) {\n this._matlabProcess = new MatlabProcess(connection)\n }\n await this._matlabProcess.connectToMatlab(url)\n return this._matlabProcess", "score": 0.8142876625061035 }, { "filename": "src/lifecycle/MatlabLifecycleManager.ts", "retrieved_chunk": " * never.\n *\n * @returns The connection to MATLAB, or null if connection timing is never\n * and MATLAB has not been manually launched.\n */\n async getMatlabConnectionAsync (): Promise<MatlabConnection | null> {\n // If MATLAB is up and running return the connection\n const isMatlabReady = this._matlabProcess?.isMatlabReady() ?? false\n if (isMatlabReady) {\n const conn = this._matlabProcess?.getConnection()", "score": 0.8101639747619629 }, { "filename": "src/server.ts", "retrieved_chunk": " WorkspaceIndexer.setupCallbacks(capabilities)\n void startMatlabIfOnStartLaunch()\n})\nasync function startMatlabIfOnStartLaunch (): Promise<void> {\n // Launch MATLAB if it should be launched early\n const connectionTiming = (await ConfigurationManager.getConfiguration()).matlabConnectionTiming\n if (connectionTiming === ConnectionTiming.OnStart) {\n void MatlabLifecycleManager.connectToMatlab(connection)\n }\n}", "score": 0.8094066977500916 }, { "filename": "src/lifecycle/MatlabLifecycleManager.ts", "retrieved_chunk": " }\n /**\n * Attempts to launch and then connect to MATLAB.\n *\n * @param connection The language server connection\n * @returns The connected MATLAB process\n */\n private async _launchAndConnectToMatlab (connection: _Connection): Promise<MatlabProcess> {\n if (this._matlabProcess == null || !this._matlabProcess.isValid) {\n this._matlabProcess = new MatlabProcess(connection)", "score": 0.804265022277832 } ]
typescript
= await connection.workspace.getConfiguration('MATLAB') as Settings }
// Copyright 2022 - 2023 The MathWorks, Inc. import { ExecuteCommandParams, Range, TextDocuments, _Connection } from 'vscode-languageserver' import { TextDocument } from 'vscode-languageserver-textdocument' import LintingSupportProvider from '../linting/LintingSupportProvider' interface LintSuppressionArgs { id: string range: Range uri: string } export const MatlabLSCommands = { MLINT_SUPPRESS_ON_LINE: 'matlabls.lint.suppress.line', MLINT_SUPPRESS_IN_FILE: 'matlabls.lint.suppress.file' } /** * Handles requests to execute commands */ class ExecuteCommandProvider { /** * Handles command execution requests. * * @param params Parameters from the onExecuteCommand request * @param documentManager The text document manager * @param connection The language server connection */ async handleExecuteCommand (params: ExecuteCommandParams, documentManager: TextDocuments<TextDocument>, connection: _Connection): Promise<void> { switch (params.command) { case MatlabLSCommands.MLINT_SUPPRESS_ON_LINE: case MatlabLSCommands.MLINT_SUPPRESS_IN_FILE: void this.handleLintingSuppression(params, documentManager, connection) } } /** * Handles command to suppress a linting diagnostic. * * @param params Parameters from the onExecuteCommand request * @param documentManager The text document manager * @param connection The language server connection */ private async handleLintingSuppression (params: ExecuteCommandParams, documentManager: TextDocuments<TextDocument>, connection: _Connection): Promise<void> { const args = params.arguments?.[0] as LintSuppressionArgs const range = args.range const uri = args.uri const doc = documentManager.get(uri) if (doc == null) { return } const shouldSuppressThroughoutFile = params.command === MatlabLSCommands.MLINT_SUPPRESS_IN_FILE LintingSupportProvider
.suppressDiagnostic(doc, range, args.id, shouldSuppressThroughoutFile) }
} export default new ExecuteCommandProvider()
src/providers/lspCommands/ExecuteCommandProvider.ts
mathworks-MATLAB-language-server-94cac1b
[ { "filename": "src/providers/linting/LintingSupportProvider.ts", "retrieved_chunk": " /**\n * Attempt to suppress a diagnostic.\n *\n * @param textDocument The document\n * @param range The range of the diagnostic being suppress\n * @param id The diagnostic's ID\n * @param shouldSuppressThroughoutFile Whether or not to suppress the diagnostic throughout the entire file\n */\n suppressDiagnostic (textDocument: TextDocument, range: Range, id: string, shouldSuppressThroughoutFile: boolean): void {\n const matlabConnection = MatlabLifecycleManager.getMatlabConnection()", "score": 0.8722699880599976 }, { "filename": "src/providers/linting/LintingSupportProvider.ts", "retrieved_chunk": " uri\n }\n ))\n // Add suppress-in-file option\n commands.push(Command.create(\n `Suppress message ${diagnosticCode} in this file`,\n MatlabLSCommands.MLINT_SUPPRESS_IN_FILE,\n {\n id: diagnosticCode,\n range: diagnostic.range,", "score": 0.8720475435256958 }, { "filename": "src/providers/linting/LintingSupportProvider.ts", "retrieved_chunk": " return\n }\n const diagnosticCode = diagnostic.code as string\n // Add suppress-on-line option\n commands.push(Command.create(\n `Suppress message ${diagnosticCode} on this line`,\n MatlabLSCommands.MLINT_SUPPRESS_ON_LINE,\n {\n id: diagnosticCode,\n range: diagnostic.range,", "score": 0.8635920286178589 }, { "filename": "src/server.ts", "retrieved_chunk": "documentManager.onDidSave(params => {\n void LintingSupportProvider.lintDocument(params.document, connection)\n})\n// Handles changes to the text document\ndocumentManager.onDidChangeContent(params => {\n if (MatlabLifecycleManager.isMatlabReady()) {\n // Only want to lint on content changes when linting is being backed by MATLAB\n LintingSupportProvider.queueLintingForDocument(params.document, connection)\n DocumentIndexer.queueIndexingForDocument(params.document)\n }", "score": 0.8483068346977234 }, { "filename": "src/providers/linting/LintingSupportProvider.ts", "retrieved_chunk": "import which = require('which')\nimport { MatlabLSCommands } from '../lspCommands/ExecuteCommandProvider'\nimport { connection } from '../../server'\ntype mlintSeverity = '0' | '1' | '2' | '3' | '4'\ninterface RawLintResults {\n lintData: string[]\n}\ninterface DiagnosticSuppressionResults {\n suppressionEdits: TextEdit[]\n}", "score": 0.839790940284729 } ]
typescript
.suppressDiagnostic(doc, range, args.id, shouldSuppressThroughoutFile) }
// Copyright 2022 - 2023 The MathWorks, Inc. import { ClientCapabilities, DidChangeConfigurationNotification, DidChangeConfigurationParams } from 'vscode-languageserver' import { reportTelemetrySettingsChange } from '../logging/TelemetryUtils' import { connection } from '../server' import { getCliArgs } from '../utils/CliUtils' export enum Argument { // Basic arguments MatlabLaunchCommandArguments = 'matlabLaunchCommandArgs', MatlabInstallationPath = 'matlabInstallPath', MatlabConnectionTiming = 'matlabConnectionTiming', ShouldIndexWorkspace = 'indexWorkspace', // Advanced arguments MatlabUrl = 'matlabUrl' } export enum ConnectionTiming { OnStart = 'onStart', OnDemand = 'onDemand', Never = 'never' } interface CliArguments { [Argument.MatlabLaunchCommandArguments]: string [Argument.MatlabUrl]: string } interface Settings { installPath: string matlabConnectionTiming: ConnectionTiming indexWorkspace: boolean telemetry: boolean } type SettingName = 'installPath' | 'matlabConnectionTiming' | 'indexWorkspace' | 'telemetry' const SETTING_NAMES: SettingName[] = [ 'installPath', 'matlabConnectionTiming', 'indexWorkspace', 'telemetry' ] class ConfigurationManager { private configuration: Settings | null = null private readonly defaultConfiguration: Settings private globalSettings: Settings // Holds additional command line arguments that are not part of the configuration private readonly additionalArguments: CliArguments private hasConfigurationCapability = false constructor () { const cliArgs = getCliArgs() this.defaultConfiguration = { installPath: '', matlabConnectionTiming: ConnectionTiming.OnStart, indexWorkspace: false, telemetry: true } this.globalSettings = { installPath: cliArgs[Argument.MatlabInstallationPath] ?? this.defaultConfiguration.installPath, matlabConnectionTiming: cliArgs[Argument.MatlabConnectionTiming] as ConnectionTiming ?? this.defaultConfiguration.matlabConnectionTiming, indexWorkspace: cliArgs[Argument.ShouldIndexWorkspace] ?? this.defaultConfiguration.indexWorkspace, telemetry: this.defaultConfiguration.telemetry } this.additionalArguments = { [Argument.MatlabLaunchCommandArguments]: cliArgs[Argument.MatlabLaunchCommandArguments] ?? '', [Argument.MatlabUrl]: cliArgs[Argument.MatlabUrl] ?? '' } } /** * Sets up the configuration manager * * @param capabilities The client capabilities */ setup (capabilities: ClientCapabilities): void { this.hasConfigurationCapability = capabilities.workspace?.configuration != null if (this.hasConfigurationCapability) { // Register for configuration changes void connection.client.register(DidChangeConfigurationNotification.type) } connection
.onDidChangeConfiguration(params => { void this.handleConfigurationChanged(params) }) }
/** * Gets the configuration for the langauge server * * @returns The current configuration */ async getConfiguration (): Promise<Settings> { if (this.hasConfigurationCapability) { if (this.configuration == null) { this.configuration = await connection.workspace.getConfiguration('MATLAB') as Settings } return this.configuration } return this.globalSettings } /** * Gets the value of the given argument * * @param argument The argument * @returns The argument's value */ getArgument (argument: Argument.MatlabLaunchCommandArguments | Argument.MatlabUrl): string { return this.additionalArguments[argument] } /** * Handles a change in the configuration * @param params The configuration changed params */ private async handleConfigurationChanged (params: DidChangeConfigurationParams): Promise<void> { let oldConfig: Settings | null let newConfig: Settings if (this.hasConfigurationCapability) { oldConfig = this.configuration // Clear cached configuration this.configuration = null // Force load new configuration newConfig = await this.getConfiguration() } else { oldConfig = this.globalSettings this.globalSettings = params.settings?.matlab ?? this.defaultConfiguration newConfig = this.globalSettings } this.compareSettingChanges(oldConfig, newConfig) } private compareSettingChanges (oldConfiguration: Settings | null, newConfiguration: Settings): void { if (oldConfiguration == null) { // Not yet initialized return } for (let i = 0; i < SETTING_NAMES.length; i++) { const settingName = SETTING_NAMES[i] const oldValue = oldConfiguration[settingName] const newValue = newConfiguration[settingName] if (oldValue !== newValue) { reportTelemetrySettingsChange(settingName, newValue.toString(), oldValue.toString()) } } } } export default new ConfigurationManager()
src/lifecycle/ConfigurationManager.ts
mathworks-MATLAB-language-server-94cac1b
[ { "filename": "src/indexing/WorkspaceIndexer.ts", "retrieved_chunk": " private isWorkspaceIndexingSupported = false\n /**\n * Sets up workspace change listeners, if supported.\n *\n * @param capabilities The client capabilities, which contains information about\n * whether the client supports workspaces.\n */\n setupCallbacks (capabilities: ClientCapabilities): void {\n this.isWorkspaceIndexingSupported = capabilities.workspace?.workspaceFolders ?? false\n if (!this.isWorkspaceIndexingSupported) {", "score": 0.8668787479400635 }, { "filename": "src/server.ts", "retrieved_chunk": " triggerCharacters: ['(', ',']\n },\n documentSymbolProvider: true\n }\n }\n return initResult\n})\n// Handles the initialized notification\nconnection.onInitialized(() => {\n ConfigurationManager.setup(capabilities)", "score": 0.8620933294296265 }, { "filename": "src/server.ts", "retrieved_chunk": " void LintingSupportProvider.lintDocument(textDocument, connection)\n void DocumentIndexer.indexDocument(textDocument)\n })\n }\n})\nlet capabilities: ClientCapabilities\n// Handles an initialization request\nconnection.onInitialize((params: InitializeParams) => {\n capabilities = params.capabilities\n // Defines the capabilities supported by this language server", "score": 0.8310582637786865 }, { "filename": "src/server.ts", "retrieved_chunk": " WorkspaceIndexer.setupCallbacks(capabilities)\n void startMatlabIfOnStartLaunch()\n})\nasync function startMatlabIfOnStartLaunch (): Promise<void> {\n // Launch MATLAB if it should be launched early\n const connectionTiming = (await ConfigurationManager.getConfiguration()).matlabConnectionTiming\n if (connectionTiming === ConnectionTiming.OnStart) {\n void MatlabLifecycleManager.connectToMatlab(connection)\n }\n}", "score": 0.8291072845458984 }, { "filename": "src/notifications/NotificationService.ts", "retrieved_chunk": " registerNotificationListener (name: string, callback: GenericNotificationHandler): void {\n connection.onNotification(name, callback)\n }\n}\nexport default new NotificationService()", "score": 0.8189369440078735 } ]
typescript
.onDidChangeConfiguration(params => { void this.handleConfigurationChanged(params) }) }
/// The main schema for objects and inputs import * as graphql from "graphql" import * as tsMorph from "ts-morph" import { AppContext } from "./context.js" import { formatDTS, getPrettierConfig } from "./formatDTS.js" import { typeMapper } from "./typeMap.js" export const createSharedSchemaFiles = (context: AppContext) => { createSharedExternalSchemaFile(context) createSharedReturnPositionSchemaFile(context) return [ context.join(context.pathSettings.typesFolderRoot, context.pathSettings.sharedFilename), context.join(context.pathSettings.typesFolderRoot, context.pathSettings.sharedInternalFilename), ] } function createSharedExternalSchemaFile(context: AppContext) { const gql = context.gql const types = gql.getTypeMap() const knownPrimitives = ["String", "Boolean", "Int"] const { prisma, fieldFacts } = context const mapper = typeMapper(context, {}) const externalTSFile = context.tsProject.createSourceFile(`/source/${context.pathSettings.sharedFilename}`, "") Object.keys(types).forEach((name) => { if (name.startsWith("__")) { return } if (knownPrimitives.includes(name)) { return } const type = types[name] const pType = prisma.get(name) if (graphql.isObjectType(type) || graphql.isInterfaceType(type) || graphql.isInputObjectType(type)) { // This is slower than it could be, use the add many at once api const docs = [] if (pType?.leadingComments) { docs.push(pType.leadingComments) } if (type.description) { docs.push(type.description) } externalTSFile.addInterface({ name: type.name, isExported: true, docs: [], properties: [ { name: "__typename", type: `"${type.name}"`, hasQuestionToken: true, }, ...Object.entries(type.getFields()).map(([fieldName, obj]: [string, graphql.GraphQLField<object, object>]) => { const docs = [] const prismaField = pType?.properties.get(fieldName) const type = obj.type as graphql.GraphQLType if (prismaField?.leadingComments.length) { docs.push(prismaField.leadingComments.trim()) } // if (obj.description) docs.push(obj.description); const hasResolverImplementation = fieldFacts.get(name)?.[fieldName]?.hasResolverImplementation const isOptionalInSDL = !graphql.isNonNullType(type) const doesNotExistInPrisma = false // !prismaField; const field: tsMorph.OptionalKind<tsMorph.PropertySignatureStructure> = { name: fieldName, type: mapper.map(type, { preferNullOverUndefined: true }), docs, hasQuestionToken: hasResolverImplementation ?? (isOptionalInSDL || doesNotExistInPrisma), } return field }), ], }) } if (graphql.isEnumType(type)) { externalTSFile.addTypeAlias({ name: type.name, type: '"' + type .getValues() .map((m) => (m as { value: string }).value) .join('" | "') + '"', }) } }) const { scalars } = mapper.getReferencedGraphQLThingsInMapping() if (scalars.length) { externalTSFile.addTypeAliases( scalars.map((s) => ({ name: s, type: "any", })) ) } const fullPath = context.join(context.pathSettings.typesFolderRoot, context.pathSettings.sharedFilename) const config = getPrettierConfig(fullPath)
const formatted = formatDTS(fullPath, externalTSFile.getText(), config) context.sys.writeFile(fullPath, formatted) }
function createSharedReturnPositionSchemaFile(context: AppContext) { const { gql, prisma, fieldFacts } = context const types = gql.getTypeMap() const mapper = typeMapper(context, { preferPrismaModels: true }) const typesToImport = [] as string[] const knownPrimitives = ["String", "Boolean", "Int"] const externalTSFile = context.tsProject.createSourceFile( `/source/${context.pathSettings.sharedInternalFilename}`, ` // You may very reasonably ask yourself, 'what is this file?' and why do I need it. // Roughly, this file ensures that when a resolver wants to return a type - that // type will match a prisma model. This is useful because you can trivially extend // the type in the SDL and not have to worry about type mis-matches because the thing // you returned does not include those functions. // This gets particularly valuable when you want to return a union type, an interface, // or a model where the prisma model is nested pretty deeply (GraphQL connections, for example.) ` ) Object.keys(types).forEach((name) => { if (name.startsWith("__")) { return } if (knownPrimitives.includes(name)) { return } const type = types[name] const pType = prisma.get(name) if (graphql.isObjectType(type) || graphql.isInterfaceType(type) || graphql.isInputObjectType(type)) { // Return straight away if we have a matching type in the prisma schema // as we dont need it if (pType) { typesToImport.push(name) return } externalTSFile.addInterface({ name: type.name, isExported: true, docs: [], properties: [ { name: "__typename", type: `"${type.name}"`, hasQuestionToken: true, }, ...Object.entries(type.getFields()).map(([fieldName, obj]: [string, graphql.GraphQLField<object, object>]) => { const hasResolverImplementation = fieldFacts.get(name)?.[fieldName]?.hasResolverImplementation const isOptionalInSDL = !graphql.isNonNullType(obj.type) const doesNotExistInPrisma = false // !prismaField; const field: tsMorph.OptionalKind<tsMorph.PropertySignatureStructure> = { name: fieldName, type: mapper.map(obj.type, { preferNullOverUndefined: true }), hasQuestionToken: hasResolverImplementation || isOptionalInSDL || doesNotExistInPrisma, } return field }), ], }) } if (graphql.isEnumType(type)) { externalTSFile.addTypeAlias({ name: type.name, type: '"' + type .getValues() .map((m) => (m as { value: string }).value) .join('" | "') + '"', }) } }) const { scalars, prisma: prismaModels } = mapper.getReferencedGraphQLThingsInMapping() if (scalars.length) { externalTSFile.addTypeAliases( scalars.map((s) => ({ name: s, type: "any", })) ) } const allPrismaModels = [...new Set([...prismaModels, ...typesToImport])].sort() if (allPrismaModels.length) { externalTSFile.addImportDeclaration({ isTypeOnly: true, moduleSpecifier: `@prisma/client`, namedImports: allPrismaModels.map((p) => `${p} as P${p}`), }) allPrismaModels.forEach((p) => { externalTSFile.addTypeAlias({ isExported: true, name: p, type: `P${p}`, }) }) } const fullPath = context.join(context.pathSettings.typesFolderRoot, context.pathSettings.sharedInternalFilename) const config = getPrettierConfig(fullPath) const formatted = formatDTS(fullPath, externalTSFile.getText(), config) context.sys.writeFile(fullPath, formatted) }
src/sharedSchema.ts
sdl-codegen-sdl-codegen-de2b8aa
[ { "filename": "src/serviceFile.ts", "retrieved_chunk": "\tif (!shouldWriteDTS) return\n\tconst config = getPrettierConfig(dtsFilepath)\n\tconst formatted = formatDTS(dtsFilepath, dts, config)\n\tcontext.sys.writeFile(dtsFilepath, formatted)\n\treturn dtsFilepath\n\tfunction addDefinitionsForTopLevelResolvers(parentName: string, config: ResolverFuncFact) {\n\t\tconst { name } = config\n\t\tlet field = queryType.getFields()[name]\n\t\tif (!field) {\n\t\t\tfield = mutationType.getFields()[name]", "score": 0.8590914607048035 }, { "filename": "src/serviceFile.ts", "retrieved_chunk": "\t}\n\tserviceFacts.set(fileKey, thisFact)\n\tconst dtsFilename = filename.endsWith(\".ts\") ? filename.replace(\".ts\", \".d.ts\") : filename.replace(\".js\", \".d.ts\")\n\tconst dtsFilepath = context.join(context.pathSettings.typesFolderRoot, dtsFilename)\n\t// Some manual formatting tweaks so we align with Redwood's setup more\n\tconst dts = fileDTS\n\t\t.getText()\n\t\t.replace(`from \"graphql\";`, `from \"graphql\";\\n`)\n\t\t.replace(`from \"@redwoodjs/graphql-server/dist/types\";`, `from \"@redwoodjs/graphql-server/dist/types\";\\n`)\n\tconst shouldWriteDTS = !!dts.trim().length", "score": 0.8332408666610718 }, { "filename": "src/run.ts", "retrieved_chunk": "\t\t// \tcmd: [\"yarn\", \"eslint\", \"--fix\", \"--ext\", \".d.ts\", appContext.settings.typesFolderRoot],\n\t\t// \tstdin: \"inherit\",\n\t\t// \tstdout: \"inherit\",\n\t\t// })\n\t\t// await process.status()\n\t}\n\tif (sys.deleteFile && config.deleteOldGraphQLDTS) {\n\t\tconsole.log(\"Deleting old graphql.d.ts\")\n\t\tsys.deleteFile(join(appRoot, \"api\", \"src\", \"graphql.d.ts\"))\n\t}", "score": 0.8262299299240112 }, { "filename": "src/serviceFile.ts", "retrieved_chunk": "\tconst mutationType = gql.getMutationType()!\n\t// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n\tif (!mutationType) throw new Error(\"No mutation type\")\n\tconst externalMapper = typeMapper(context, { preferPrismaModels: true })\n\tconst returnTypeMapper = typeMapper(context, {})\n\t// The description of the source file\n\tconst fileFacts = getCodeFactsForJSTSFileAtPath(file, context)\n\tif (Object.keys(fileFacts).length === 0) return\n\t// Tracks prospective prisma models which are used in the file\n\tconst extraPrismaReferences = new Set<string>()", "score": 0.8257305026054382 }, { "filename": "src/serviceFile.ts", "retrieved_chunk": "\tif (fileDTS.getText().includes(\"RedwoodGraphQLContext\")) {\n\t\tfileDTS.addImportDeclaration({\n\t\t\tisTypeOnly: true,\n\t\t\tmoduleSpecifier: \"@redwoodjs/graphql-server/dist/types\",\n\t\t\tnamedImports: [\"RedwoodGraphQLContext\"],\n\t\t})\n\t}\n\tif (sharedInternalGraphQLObjectsReferenced.types.length) {\n\t\tfileDTS.addImportDeclaration({\n\t\t\tisTypeOnly: true,", "score": 0.8175538182258606 } ]
typescript
const formatted = formatDTS(fullPath, externalTSFile.getText(), config) context.sys.writeFile(fullPath, formatted) }
import * as graphql from "graphql" import { AppContext } from "./context.js" import { formatDTS, getPrettierConfig } from "./formatDTS.js" import { getCodeFactsForJSTSFileAtPath } from "./serviceFile.codefacts.js" import { CodeFacts, ModelResolverFacts, ResolverFuncFact } from "./typeFacts.js" import { TypeMapper, typeMapper } from "./typeMap.js" import { capitalizeFirstLetter, createAndReferOrInlineArgsForField, inlineArgsForField } from "./utils.js" export const lookAtServiceFile = (file: string, context: AppContext) => { const { gql, prisma, pathSettings: settings, codeFacts: serviceFacts, fieldFacts } = context // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition if (!gql) throw new Error(`No schema when wanting to look at service file: ${file}`) if (!prisma) throw new Error(`No prisma schema when wanting to look at service file: ${file}`) // This isn't good enough, needs to be relative to api/src/services const fileKey = file.replace(settings.apiServicesPath, "") const thisFact: CodeFacts = {} const filename = context.basename(file) // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const queryType = gql.getQueryType()! if (!queryType) throw new Error("No query type") // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const mutationType = gql.getMutationType()! // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition if (!mutationType) throw new Error("No mutation type") const externalMapper = typeMapper(context, { preferPrismaModels: true }) const returnTypeMapper = typeMapper(context, {}) // The description of the source file const fileFacts = getCodeFactsForJSTSFileAtPath(file, context) if (Object.keys(fileFacts).length === 0) return // Tracks prospective prisma models which are used in the file const extraPrismaReferences = new Set<string>() // The file we'll be creating in-memory throughout this fn const fileDTS = context.tsProject.createSourceFile(`source/${fileKey}.d.ts`, "", { overwrite: true }) // Basically if a top level resolver reference Query or Mutation const knownSpecialCasesForGraphQL = new Set<string>() // Add the root function declarations const rootResolvers = fileFacts.maybe_query_mutation?.resolvers if (rootResolvers) rootResolvers.forEach((v) => { const isQuery = v.name in queryType.getFields() const isMutation = v.name in mutationType.getFields() const parentName = isQuery ? queryType.name : isMutation ? mutationType.name : undefined if (parentName) { addDefinitionsForTopLevelResolvers(parentName, v) } else { // Add warning about unused resolver fileDTS.addStatements(`\n// ${v.name} does not exist on Query or Mutation`) } }) // Add the root function declarations Object.values(fileFacts).forEach((model) => { if (!model) return const skip = ["maybe_query_mutation", queryType.name, mutationType.name] if (skip.includes(model.typeName)) return addCustomTypeModel(model) }) // Set up the module imports at the top const sharedGraphQLObjectsReferenced = externalMapper.getReferencedGraphQLThingsInMapping() const sharedGraphQLObjectsReferencedTypes = [...sharedGraphQLObjectsReferenced.types, ...knownSpecialCasesForGraphQL] const sharedInternalGraphQLObjectsReferenced = returnTypeMapper.getReferencedGraphQLThingsInMapping() const aliases = [...new Set([...sharedGraphQLObjectsReferenced.scalars, ...sharedInternalGraphQLObjectsReferenced.scalars])] if (aliases.length) { fileDTS.addTypeAliases( aliases.map((s) => ({ name: s, type: "any", })) ) } const prismases = [ ...new Set([ ...sharedGraphQLObjectsReferenced.prisma, ...sharedInternalGraphQLObjectsReferenced.prisma, ...extraPrismaReferences.values(), ]), ] const validPrismaObjs = prismases.filter((p) => prisma.has(p)) if (validPrismaObjs.length) { fileDTS.addImportDeclaration({ isTypeOnly: true, moduleSpecifier: "@prisma/client", namedImports: validPrismaObjs.map((p) => `${p} as P${p}`), }) } if (fileDTS.getText().includes("GraphQLResolveInfo")) { fileDTS.addImportDeclaration({ isTypeOnly: true, moduleSpecifier: "graphql", namedImports: ["GraphQLResolveInfo"], }) } if (fileDTS.getText().includes("RedwoodGraphQLContext")) { fileDTS.addImportDeclaration({ isTypeOnly: true, moduleSpecifier: "@redwoodjs/graphql-server/dist/types", namedImports: ["RedwoodGraphQLContext"], }) } if (sharedInternalGraphQLObjectsReferenced.types.length) { fileDTS.addImportDeclaration({ isTypeOnly: true, moduleSpecifier: `./${settings.sharedInternalFilename.replace(".d.ts", "")}`, namedImports: sharedInternalGraphQLObjectsReferenced.types.map((t) => `${t} as RT${t}`), }) } if (sharedGraphQLObjectsReferencedTypes.length) { fileDTS.addImportDeclaration({ isTypeOnly: true, moduleSpecifier: `./${settings.sharedFilename.replace(".d.ts", "")}`, namedImports: sharedGraphQLObjectsReferencedTypes, }) } serviceFacts.set(fileKey, thisFact) const dtsFilename = filename.endsWith(".ts") ? filename.replace(".ts", ".d.ts") : filename.replace(".js", ".d.ts") const dtsFilepath = context.join(context.pathSettings.typesFolderRoot, dtsFilename) // Some manual formatting tweaks so we align with Redwood's setup more const dts = fileDTS .getText() .replace(`from "graphql";`, `from "graphql";\n`) .replace(`from "@redwoodjs/graphql-server/dist/types";`, `from "@redwoodjs/graphql-server/dist/types";\n`) const shouldWriteDTS = !!dts.trim().length if (!shouldWriteDTS) return const config = getPrettierConfig(dtsFilepath) const formatted = formatDTS(dtsFilepath, dts, config) context.sys.writeFile(dtsFilepath, formatted) return dtsFilepath
function addDefinitionsForTopLevelResolvers(parentName: string, config: ResolverFuncFact) {
const { name } = config let field = queryType.getFields()[name] if (!field) { field = mutationType.getFields()[name] } const interfaceDeclaration = fileDTS.addInterface({ name: `${capitalizeFirstLetter(config.name)}Resolver`, isExported: true, docs: field.astNode ? ["SDL: " + graphql.print(field.astNode)] : ["@deprecated: Could not find this field in the schema for Mutation or Query"], }) const args = createAndReferOrInlineArgsForField(field, { name: interfaceDeclaration.getName(), file: fileDTS, mapper: externalMapper.map, }) if (parentName === queryType.name) knownSpecialCasesForGraphQL.add(queryType.name) if (parentName === mutationType.name) knownSpecialCasesForGraphQL.add(mutationType.name) const argsParam = args ?? "object" const returnType = returnTypeForResolver(returnTypeMapper, field, config) interfaceDeclaration.addCallSignature({ parameters: [ { name: "args", type: argsParam, hasQuestionToken: config.funcArgCount < 1 }, { name: "obj", type: `{ root: ${parentName}, context: RedwoodGraphQLContext, info: GraphQLResolveInfo }`, hasQuestionToken: config.funcArgCount < 2, }, ], returnType, }) } /** Ideally, we want to be able to write the type for just the object */ function addCustomTypeModel(modelFacts: ModelResolverFacts) { const modelName = modelFacts.typeName extraPrismaReferences.add(modelName) // Make an interface, this is the version we are replacing from graphql-codegen: // Account: MergePrismaWithSdlTypes<PrismaAccount, MakeRelationsOptional<Account, AllMappedModels>, AllMappedModels>; const gqlType = gql.getType(modelName) if (!gqlType) { // throw new Error(`Could not find a GraphQL type named ${d.getName()}`); fileDTS.addStatements(`\n// ${modelName} does not exist in the schema`) return } if (!graphql.isObjectType(gqlType)) { throw new Error(`In your schema ${modelName} is not an object, which we can only make resolver types for`) } const fields = gqlType.getFields() // See: https://github.com/redwoodjs/redwood/pull/6228#issue-1342966511 // For more ideas const hasGenerics = modelFacts.hasGenericArg // This is what they would have to write const resolverInterface = fileDTS.addInterface({ name: `${modelName}TypeResolvers`, typeParameters: hasGenerics ? ["Extended"] : [], isExported: true, }) // The parent type for the resolvers fileDTS.addTypeAlias({ name: `${modelName}AsParent`, typeParameters: hasGenerics ? ["Extended"] : [], type: `P${modelName} ${createParentAdditionallyDefinedFunctions()} ${hasGenerics ? " & Extended" : ""}`, // docs: ["The prisma model, mixed with fns already defined inside the resolvers."], }) const modelFieldFacts = fieldFacts.get(modelName) ?? {} // Loop through the resolvers, adding the fields which have resolvers implemented in the source file modelFacts.resolvers.forEach((resolver) => { const field = fields[resolver.name] if (field) { const fieldName = resolver.name if (modelFieldFacts[fieldName]) modelFieldFacts[fieldName].hasResolverImplementation = true else modelFieldFacts[fieldName] = { hasResolverImplementation: true } const argsType = inlineArgsForField(field, { mapper: externalMapper.map }) ?? "undefined" const param = hasGenerics ? "<Extended>" : "" const firstQ = resolver.funcArgCount < 1 ? "?" : "" const secondQ = resolver.funcArgCount < 2 ? "?" : "" const innerArgs = `args${firstQ}: ${argsType}, obj${secondQ}: { root: ${modelName}AsParent${param}, context: RedwoodGraphQLContext, info: GraphQLResolveInfo }` const returnType = returnTypeForResolver(returnTypeMapper, field, resolver) const docs = field.astNode ? [`SDL: ${graphql.print(field.astNode)}`] : [] // For speed we should switch this out to addProperties eventually resolverInterface.addProperty({ name: fieldName, leadingTrivia: "\n", docs, type: resolver.isFunc || resolver.isUnknown ? `(${innerArgs}) => ${returnType ?? "any"}` : returnType, }) } else { resolverInterface.addCallSignature({ docs: [` @deprecated: SDL ${modelName}.${resolver.name} does not exist in your schema`], }) } }) function createParentAdditionallyDefinedFunctions() { const fns: string[] = [] modelFacts.resolvers.forEach((resolver) => { const existsInGraphQLSchema = fields[resolver.name] if (!existsInGraphQLSchema) { console.warn( `The service file ${filename} has a field ${resolver.name} on ${modelName} that does not exist in the generated schema.graphql` ) } const prefix = !existsInGraphQLSchema ? "\n// This field does not exist in the generated schema.graphql\n" : "" const returnType = returnTypeForResolver(externalMapper, existsInGraphQLSchema, resolver) // fns.push(`${prefix}${resolver.name}: () => Promise<${externalMapper.map(type, {})}>`) fns.push(`${prefix}${resolver.name}: () => ${returnType}`) }) if (fns.length < 1) return "" return "& {" + fns.join(", \n") + "}" } fieldFacts.set(modelName, modelFieldFacts) } return dtsFilename } function returnTypeForResolver(mapper: TypeMapper, field: graphql.GraphQLField<unknown, unknown> | undefined, resolver: ResolverFuncFact) { if (!field) return "void" const tType = mapper.map(field.type, { preferNullOverUndefined: true, typenamePrefix: "RT" }) ?? "void" let returnType = tType const all = `${tType} | Promise<${tType}> | (() => Promise<${tType}>)` if (resolver.isFunc && resolver.isAsync) returnType = `Promise<${tType}>` else if (resolver.isFunc) returnType = all else if (resolver.isObjLiteral) returnType = tType else if (resolver.isUnknown) returnType = all return returnType }
src/serviceFile.ts
sdl-codegen-sdl-codegen-de2b8aa
[ { "filename": "src/sharedSchema.ts", "retrieved_chunk": "\t\t\t})\n\t\t})\n\t}\n\tconst fullPath = context.join(context.pathSettings.typesFolderRoot, context.pathSettings.sharedInternalFilename)\n\tconst config = getPrettierConfig(fullPath)\n\tconst formatted = formatDTS(fullPath, externalTSFile.getText(), config)\n\tcontext.sys.writeFile(fullPath, formatted)\n}", "score": 0.8761507272720337 }, { "filename": "src/sharedSchema.ts", "retrieved_chunk": "\t\t\t}))\n\t\t)\n\t}\n\tconst fullPath = context.join(context.pathSettings.typesFolderRoot, context.pathSettings.sharedFilename)\n\tconst config = getPrettierConfig(fullPath)\n\tconst formatted = formatDTS(fullPath, externalTSFile.getText(), config)\n\tcontext.sys.writeFile(fullPath, formatted)\n}\nfunction createSharedReturnPositionSchemaFile(context: AppContext) {\n\tconst { gql, prisma, fieldFacts } = context", "score": 0.854227602481842 }, { "filename": "src/sharedSchema.ts", "retrieved_chunk": "\tconst types = gql.getTypeMap()\n\tconst mapper = typeMapper(context, { preferPrismaModels: true })\n\tconst typesToImport = [] as string[]\n\tconst knownPrimitives = [\"String\", \"Boolean\", \"Int\"]\n\tconst externalTSFile = context.tsProject.createSourceFile(\n\t\t`/source/${context.pathSettings.sharedInternalFilename}`,\n\t\t`\n// You may very reasonably ask yourself, 'what is this file?' and why do I need it.\n// Roughly, this file ensures that when a resolver wants to return a type - that\n// type will match a prisma model. This is useful because you can trivially extend", "score": 0.846400797367096 }, { "filename": "src/serviceFile.codefacts.ts", "retrieved_chunk": "\tconst referenceFileSourceFile = context.tsProject.createSourceFile(`/source/${fileKey}`, fileContents, { overwrite: true })\n\tconst vars = referenceFileSourceFile.getVariableDeclarations().filter((v) => v.isExported())\n\tconst resolverContainers = vars.filter(varStartsWithUppercase)\n\tconst queryOrMutationResolvers = vars.filter((v) => !varStartsWithUppercase(v))\n\tqueryOrMutationResolvers.forEach((v) => {\n\t\tconst parent = \"maybe_query_mutation\"\n\t\tconst facts = getResolverInformationForDeclaration(v.getInitializer())\n\t\t// Start making facts about the services\n\t\tconst fact: ModelResolverFacts = fileFact[parent] ?? {\n\t\t\ttypeName: parent,", "score": 0.846031129360199 }, { "filename": "src/sharedSchema.ts", "retrieved_chunk": "\tconst externalTSFile = context.tsProject.createSourceFile(`/source/${context.pathSettings.sharedFilename}`, \"\")\n\tObject.keys(types).forEach((name) => {\n\t\tif (name.startsWith(\"__\")) {\n\t\t\treturn\n\t\t}\n\t\tif (knownPrimitives.includes(name)) {\n\t\t\treturn\n\t\t}\n\t\tconst type = types[name]\n\t\tconst pType = prisma.get(name)", "score": 0.8350727558135986 } ]
typescript
function addDefinitionsForTopLevelResolvers(parentName: string, config: ResolverFuncFact) {
import * as graphql from "graphql" import { AppContext } from "./context.js" import { formatDTS, getPrettierConfig } from "./formatDTS.js" import { getCodeFactsForJSTSFileAtPath } from "./serviceFile.codefacts.js" import { CodeFacts, ModelResolverFacts, ResolverFuncFact } from "./typeFacts.js" import { TypeMapper, typeMapper } from "./typeMap.js" import { capitalizeFirstLetter, createAndReferOrInlineArgsForField, inlineArgsForField } from "./utils.js" export const lookAtServiceFile = (file: string, context: AppContext) => { const { gql, prisma, pathSettings: settings, codeFacts: serviceFacts, fieldFacts } = context // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition if (!gql) throw new Error(`No schema when wanting to look at service file: ${file}`) if (!prisma) throw new Error(`No prisma schema when wanting to look at service file: ${file}`) // This isn't good enough, needs to be relative to api/src/services const fileKey = file.replace(settings.apiServicesPath, "") const thisFact: CodeFacts = {} const filename = context.basename(file) // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const queryType = gql.getQueryType()! if (!queryType) throw new Error("No query type") // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const mutationType = gql.getMutationType()! // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition if (!mutationType) throw new Error("No mutation type") const externalMapper = typeMapper(context, { preferPrismaModels: true }) const returnTypeMapper = typeMapper(context, {}) // The description of the source file const fileFacts = getCodeFactsForJSTSFileAtPath(file, context) if (Object.keys(fileFacts).length === 0) return // Tracks prospective prisma models which are used in the file const extraPrismaReferences = new Set<string>() // The file we'll be creating in-memory throughout this fn const fileDTS = context.tsProject.createSourceFile(`source/${fileKey}.d.ts`, "", { overwrite: true }) // Basically if a top level resolver reference Query or Mutation const knownSpecialCasesForGraphQL = new Set<string>() // Add the root function declarations const rootResolvers = fileFacts.maybe_query_mutation?.resolvers if (rootResolvers)
rootResolvers.forEach((v) => {
const isQuery = v.name in queryType.getFields() const isMutation = v.name in mutationType.getFields() const parentName = isQuery ? queryType.name : isMutation ? mutationType.name : undefined if (parentName) { addDefinitionsForTopLevelResolvers(parentName, v) } else { // Add warning about unused resolver fileDTS.addStatements(`\n// ${v.name} does not exist on Query or Mutation`) } }) // Add the root function declarations Object.values(fileFacts).forEach((model) => { if (!model) return const skip = ["maybe_query_mutation", queryType.name, mutationType.name] if (skip.includes(model.typeName)) return addCustomTypeModel(model) }) // Set up the module imports at the top const sharedGraphQLObjectsReferenced = externalMapper.getReferencedGraphQLThingsInMapping() const sharedGraphQLObjectsReferencedTypes = [...sharedGraphQLObjectsReferenced.types, ...knownSpecialCasesForGraphQL] const sharedInternalGraphQLObjectsReferenced = returnTypeMapper.getReferencedGraphQLThingsInMapping() const aliases = [...new Set([...sharedGraphQLObjectsReferenced.scalars, ...sharedInternalGraphQLObjectsReferenced.scalars])] if (aliases.length) { fileDTS.addTypeAliases( aliases.map((s) => ({ name: s, type: "any", })) ) } const prismases = [ ...new Set([ ...sharedGraphQLObjectsReferenced.prisma, ...sharedInternalGraphQLObjectsReferenced.prisma, ...extraPrismaReferences.values(), ]), ] const validPrismaObjs = prismases.filter((p) => prisma.has(p)) if (validPrismaObjs.length) { fileDTS.addImportDeclaration({ isTypeOnly: true, moduleSpecifier: "@prisma/client", namedImports: validPrismaObjs.map((p) => `${p} as P${p}`), }) } if (fileDTS.getText().includes("GraphQLResolveInfo")) { fileDTS.addImportDeclaration({ isTypeOnly: true, moduleSpecifier: "graphql", namedImports: ["GraphQLResolveInfo"], }) } if (fileDTS.getText().includes("RedwoodGraphQLContext")) { fileDTS.addImportDeclaration({ isTypeOnly: true, moduleSpecifier: "@redwoodjs/graphql-server/dist/types", namedImports: ["RedwoodGraphQLContext"], }) } if (sharedInternalGraphQLObjectsReferenced.types.length) { fileDTS.addImportDeclaration({ isTypeOnly: true, moduleSpecifier: `./${settings.sharedInternalFilename.replace(".d.ts", "")}`, namedImports: sharedInternalGraphQLObjectsReferenced.types.map((t) => `${t} as RT${t}`), }) } if (sharedGraphQLObjectsReferencedTypes.length) { fileDTS.addImportDeclaration({ isTypeOnly: true, moduleSpecifier: `./${settings.sharedFilename.replace(".d.ts", "")}`, namedImports: sharedGraphQLObjectsReferencedTypes, }) } serviceFacts.set(fileKey, thisFact) const dtsFilename = filename.endsWith(".ts") ? filename.replace(".ts", ".d.ts") : filename.replace(".js", ".d.ts") const dtsFilepath = context.join(context.pathSettings.typesFolderRoot, dtsFilename) // Some manual formatting tweaks so we align with Redwood's setup more const dts = fileDTS .getText() .replace(`from "graphql";`, `from "graphql";\n`) .replace(`from "@redwoodjs/graphql-server/dist/types";`, `from "@redwoodjs/graphql-server/dist/types";\n`) const shouldWriteDTS = !!dts.trim().length if (!shouldWriteDTS) return const config = getPrettierConfig(dtsFilepath) const formatted = formatDTS(dtsFilepath, dts, config) context.sys.writeFile(dtsFilepath, formatted) return dtsFilepath function addDefinitionsForTopLevelResolvers(parentName: string, config: ResolverFuncFact) { const { name } = config let field = queryType.getFields()[name] if (!field) { field = mutationType.getFields()[name] } const interfaceDeclaration = fileDTS.addInterface({ name: `${capitalizeFirstLetter(config.name)}Resolver`, isExported: true, docs: field.astNode ? ["SDL: " + graphql.print(field.astNode)] : ["@deprecated: Could not find this field in the schema for Mutation or Query"], }) const args = createAndReferOrInlineArgsForField(field, { name: interfaceDeclaration.getName(), file: fileDTS, mapper: externalMapper.map, }) if (parentName === queryType.name) knownSpecialCasesForGraphQL.add(queryType.name) if (parentName === mutationType.name) knownSpecialCasesForGraphQL.add(mutationType.name) const argsParam = args ?? "object" const returnType = returnTypeForResolver(returnTypeMapper, field, config) interfaceDeclaration.addCallSignature({ parameters: [ { name: "args", type: argsParam, hasQuestionToken: config.funcArgCount < 1 }, { name: "obj", type: `{ root: ${parentName}, context: RedwoodGraphQLContext, info: GraphQLResolveInfo }`, hasQuestionToken: config.funcArgCount < 2, }, ], returnType, }) } /** Ideally, we want to be able to write the type for just the object */ function addCustomTypeModel(modelFacts: ModelResolverFacts) { const modelName = modelFacts.typeName extraPrismaReferences.add(modelName) // Make an interface, this is the version we are replacing from graphql-codegen: // Account: MergePrismaWithSdlTypes<PrismaAccount, MakeRelationsOptional<Account, AllMappedModels>, AllMappedModels>; const gqlType = gql.getType(modelName) if (!gqlType) { // throw new Error(`Could not find a GraphQL type named ${d.getName()}`); fileDTS.addStatements(`\n// ${modelName} does not exist in the schema`) return } if (!graphql.isObjectType(gqlType)) { throw new Error(`In your schema ${modelName} is not an object, which we can only make resolver types for`) } const fields = gqlType.getFields() // See: https://github.com/redwoodjs/redwood/pull/6228#issue-1342966511 // For more ideas const hasGenerics = modelFacts.hasGenericArg // This is what they would have to write const resolverInterface = fileDTS.addInterface({ name: `${modelName}TypeResolvers`, typeParameters: hasGenerics ? ["Extended"] : [], isExported: true, }) // The parent type for the resolvers fileDTS.addTypeAlias({ name: `${modelName}AsParent`, typeParameters: hasGenerics ? ["Extended"] : [], type: `P${modelName} ${createParentAdditionallyDefinedFunctions()} ${hasGenerics ? " & Extended" : ""}`, // docs: ["The prisma model, mixed with fns already defined inside the resolvers."], }) const modelFieldFacts = fieldFacts.get(modelName) ?? {} // Loop through the resolvers, adding the fields which have resolvers implemented in the source file modelFacts.resolvers.forEach((resolver) => { const field = fields[resolver.name] if (field) { const fieldName = resolver.name if (modelFieldFacts[fieldName]) modelFieldFacts[fieldName].hasResolverImplementation = true else modelFieldFacts[fieldName] = { hasResolverImplementation: true } const argsType = inlineArgsForField(field, { mapper: externalMapper.map }) ?? "undefined" const param = hasGenerics ? "<Extended>" : "" const firstQ = resolver.funcArgCount < 1 ? "?" : "" const secondQ = resolver.funcArgCount < 2 ? "?" : "" const innerArgs = `args${firstQ}: ${argsType}, obj${secondQ}: { root: ${modelName}AsParent${param}, context: RedwoodGraphQLContext, info: GraphQLResolveInfo }` const returnType = returnTypeForResolver(returnTypeMapper, field, resolver) const docs = field.astNode ? [`SDL: ${graphql.print(field.astNode)}`] : [] // For speed we should switch this out to addProperties eventually resolverInterface.addProperty({ name: fieldName, leadingTrivia: "\n", docs, type: resolver.isFunc || resolver.isUnknown ? `(${innerArgs}) => ${returnType ?? "any"}` : returnType, }) } else { resolverInterface.addCallSignature({ docs: [` @deprecated: SDL ${modelName}.${resolver.name} does not exist in your schema`], }) } }) function createParentAdditionallyDefinedFunctions() { const fns: string[] = [] modelFacts.resolvers.forEach((resolver) => { const existsInGraphQLSchema = fields[resolver.name] if (!existsInGraphQLSchema) { console.warn( `The service file ${filename} has a field ${resolver.name} on ${modelName} that does not exist in the generated schema.graphql` ) } const prefix = !existsInGraphQLSchema ? "\n// This field does not exist in the generated schema.graphql\n" : "" const returnType = returnTypeForResolver(externalMapper, existsInGraphQLSchema, resolver) // fns.push(`${prefix}${resolver.name}: () => Promise<${externalMapper.map(type, {})}>`) fns.push(`${prefix}${resolver.name}: () => ${returnType}`) }) if (fns.length < 1) return "" return "& {" + fns.join(", \n") + "}" } fieldFacts.set(modelName, modelFieldFacts) } return dtsFilename } function returnTypeForResolver(mapper: TypeMapper, field: graphql.GraphQLField<unknown, unknown> | undefined, resolver: ResolverFuncFact) { if (!field) return "void" const tType = mapper.map(field.type, { preferNullOverUndefined: true, typenamePrefix: "RT" }) ?? "void" let returnType = tType const all = `${tType} | Promise<${tType}> | (() => Promise<${tType}>)` if (resolver.isFunc && resolver.isAsync) returnType = `Promise<${tType}>` else if (resolver.isFunc) returnType = all else if (resolver.isObjLiteral) returnType = tType else if (resolver.isUnknown) returnType = all return returnType }
src/serviceFile.ts
sdl-codegen-sdl-codegen-de2b8aa
[ { "filename": "src/serviceFile.codefacts.ts", "retrieved_chunk": "\tconst referenceFileSourceFile = context.tsProject.createSourceFile(`/source/${fileKey}`, fileContents, { overwrite: true })\n\tconst vars = referenceFileSourceFile.getVariableDeclarations().filter((v) => v.isExported())\n\tconst resolverContainers = vars.filter(varStartsWithUppercase)\n\tconst queryOrMutationResolvers = vars.filter((v) => !varStartsWithUppercase(v))\n\tqueryOrMutationResolvers.forEach((v) => {\n\t\tconst parent = \"maybe_query_mutation\"\n\t\tconst facts = getResolverInformationForDeclaration(v.getInitializer())\n\t\t// Start making facts about the services\n\t\tconst fact: ModelResolverFacts = fileFact[parent] ?? {\n\t\t\ttypeName: parent,", "score": 0.8800621032714844 }, { "filename": "src/sharedSchema.ts", "retrieved_chunk": "\tconst types = gql.getTypeMap()\n\tconst mapper = typeMapper(context, { preferPrismaModels: true })\n\tconst typesToImport = [] as string[]\n\tconst knownPrimitives = [\"String\", \"Boolean\", \"Int\"]\n\tconst externalTSFile = context.tsProject.createSourceFile(\n\t\t`/source/${context.pathSettings.sharedInternalFilename}`,\n\t\t`\n// You may very reasonably ask yourself, 'what is this file?' and why do I need it.\n// Roughly, this file ensures that when a resolver wants to return a type - that\n// type will match a prisma model. This is useful because you can trivially extend", "score": 0.8745468854904175 }, { "filename": "src/sharedSchema.ts", "retrieved_chunk": "\tconst externalTSFile = context.tsProject.createSourceFile(`/source/${context.pathSettings.sharedFilename}`, \"\")\n\tObject.keys(types).forEach((name) => {\n\t\tif (name.startsWith(\"__\")) {\n\t\t\treturn\n\t\t}\n\t\tif (knownPrimitives.includes(name)) {\n\t\t\treturn\n\t\t}\n\t\tconst type = types[name]\n\t\tconst pType = prisma.get(name)", "score": 0.855938196182251 }, { "filename": "src/index.ts", "retrieved_chunk": "\t\tif (file.endsWith(\".test.ts\")) return false\n\t\tif (file.endsWith(\"scenarios.ts\")) return false\n\t\treturn file.endsWith(\".ts\") || file.endsWith(\".tsx\") || file.endsWith(\".js\")\n\t})\n\tconst filepaths = [] as string[]\n\t// Create the two shared schema files\n\tconst sharedDTSes = createSharedSchemaFiles(appContext)\n\tfilepaths.push(...sharedDTSes)\n\t// This needs to go first, as it sets up fieldFacts\n\tfor (const path of serviceFilesToLookAt) {", "score": 0.8458139300346375 }, { "filename": "src/serviceFile.codefacts.ts", "retrieved_chunk": "import * as tsMorph from \"ts-morph\"\nimport { AppContext } from \"./context.js\"\nimport { CodeFacts, ModelResolverFacts, ResolverFuncFact } from \"./typeFacts.js\"\nimport { varStartsWithUppercase } from \"./utils.js\"\nexport const getCodeFactsForJSTSFileAtPath = (file: string, context: AppContext) => {\n\tconst { pathSettings: settings } = context\n\tconst fileKey = file.replace(settings.apiServicesPath, \"\")\n\t// const priorFacts = serviceInfo.get(fileKey)\n\tconst fileFact: CodeFacts = {}\n\tconst fileContents = context.sys.readFile(file)", "score": 0.8334662318229675 } ]
typescript
rootResolvers.forEach((v) => {
import * as graphql from "graphql" import { AppContext } from "./context.js" import { formatDTS, getPrettierConfig } from "./formatDTS.js" import { getCodeFactsForJSTSFileAtPath } from "./serviceFile.codefacts.js" import { CodeFacts, ModelResolverFacts, ResolverFuncFact } from "./typeFacts.js" import { TypeMapper, typeMapper } from "./typeMap.js" import { capitalizeFirstLetter, createAndReferOrInlineArgsForField, inlineArgsForField } from "./utils.js" export const lookAtServiceFile = (file: string, context: AppContext) => { const { gql, prisma, pathSettings: settings, codeFacts: serviceFacts, fieldFacts } = context // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition if (!gql) throw new Error(`No schema when wanting to look at service file: ${file}`) if (!prisma) throw new Error(`No prisma schema when wanting to look at service file: ${file}`) // This isn't good enough, needs to be relative to api/src/services const fileKey = file.replace(settings.apiServicesPath, "") const thisFact: CodeFacts = {} const filename = context.basename(file) // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const queryType = gql.getQueryType()! if (!queryType) throw new Error("No query type") // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const mutationType = gql.getMutationType()! // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition if (!mutationType) throw new Error("No mutation type") const externalMapper = typeMapper(context, { preferPrismaModels: true }) const returnTypeMapper = typeMapper(context, {}) // The description of the source file const fileFacts = getCodeFactsForJSTSFileAtPath(file, context) if (Object.keys(fileFacts).length === 0) return // Tracks prospective prisma models which are used in the file const extraPrismaReferences = new Set<string>() // The file we'll be creating in-memory throughout this fn const fileDTS = context.tsProject.createSourceFile(`source/${fileKey}.d.ts`, "", { overwrite: true }) // Basically if a top level resolver reference Query or Mutation const knownSpecialCasesForGraphQL = new Set<string>() // Add the root function declarations const rootResolvers = fileFacts.maybe_query_mutation?.resolvers if (rootResolvers) rootResolvers.forEach((v) => { const isQuery = v.name in queryType.getFields() const isMutation = v.name in mutationType.getFields() const parentName = isQuery ? queryType.name : isMutation ? mutationType.name : undefined if (parentName) { addDefinitionsForTopLevelResolvers(parentName, v) } else { // Add warning about unused resolver fileDTS.addStatements(`\n// ${v.name} does not exist on Query or Mutation`) } }) // Add the root function declarations Object.values(fileFacts).forEach((model) => { if (!model) return const skip = ["maybe_query_mutation", queryType.name, mutationType.name] if (skip.includes(model.typeName)) return addCustomTypeModel(model) }) // Set up the module imports at the top const sharedGraphQLObjectsReferenced = externalMapper.getReferencedGraphQLThingsInMapping() const sharedGraphQLObjectsReferencedTypes = [...sharedGraphQLObjectsReferenced.types, ...knownSpecialCasesForGraphQL] const sharedInternalGraphQLObjectsReferenced = returnTypeMapper.getReferencedGraphQLThingsInMapping() const aliases = [...new Set([...sharedGraphQLObjectsReferenced.scalars, ...sharedInternalGraphQLObjectsReferenced.scalars])] if (aliases.length) { fileDTS.addTypeAliases( aliases.map((s) => ({ name: s, type: "any", })) ) } const prismases = [ ...new Set([ ...sharedGraphQLObjectsReferenced.prisma, ...sharedInternalGraphQLObjectsReferenced.prisma, ...extraPrismaReferences.values(), ]), ] const validPrismaObjs = prismases.filter((p) => prisma.has(p)) if (validPrismaObjs.length) { fileDTS.addImportDeclaration({ isTypeOnly: true, moduleSpecifier: "@prisma/client", namedImports: validPrismaObjs.map((p) => `${p} as P${p}`), }) } if (fileDTS.getText().includes("GraphQLResolveInfo")) { fileDTS.addImportDeclaration({ isTypeOnly: true, moduleSpecifier: "graphql", namedImports: ["GraphQLResolveInfo"], }) } if (fileDTS.getText().includes("RedwoodGraphQLContext")) { fileDTS.addImportDeclaration({ isTypeOnly: true, moduleSpecifier: "@redwoodjs/graphql-server/dist/types", namedImports: ["RedwoodGraphQLContext"], }) } if (sharedInternalGraphQLObjectsReferenced.types.length) { fileDTS.addImportDeclaration({ isTypeOnly: true, moduleSpecifier: `./${settings.sharedInternalFilename.replace(".d.ts", "")}`, namedImports: sharedInternalGraphQLObjectsReferenced.types.map((t) => `${t} as RT${t}`), }) } if (sharedGraphQLObjectsReferencedTypes.length) { fileDTS.addImportDeclaration({ isTypeOnly: true, moduleSpecifier: `./${settings.sharedFilename.replace(".d.ts", "")}`, namedImports: sharedGraphQLObjectsReferencedTypes, }) } serviceFacts.set(fileKey, thisFact) const dtsFilename = filename.endsWith(".ts") ? filename.replace(".ts", ".d.ts") : filename.replace(".js", ".d.ts") const dtsFilepath = context.join(context.pathSettings.typesFolderRoot, dtsFilename) // Some manual formatting tweaks so we align with Redwood's setup more const dts = fileDTS .getText() .replace(`from "graphql";`, `from "graphql";\n`) .replace(`from "@redwoodjs/graphql-server/dist/types";`, `from "@redwoodjs/graphql-server/dist/types";\n`) const shouldWriteDTS = !!dts.trim().length if (!shouldWriteDTS) return const config = getPrettierConfig(dtsFilepath) const formatted = formatDTS(dtsFilepath, dts, config) context.sys.writeFile(dtsFilepath, formatted) return dtsFilepath function addDefinitionsForTopLevelResolvers(parentName: string, config: ResolverFuncFact) { const { name } = config let field = queryType.getFields()[name] if (!field) { field = mutationType.getFields()[name] } const interfaceDeclaration = fileDTS.addInterface({ name: `${capitalizeFirstLetter(config.name)}Resolver`, isExported: true, docs: field.astNode ? ["SDL: " + graphql.print(field.astNode)] : ["@deprecated: Could not find this field in the schema for Mutation or Query"], }) const
args = createAndReferOrInlineArgsForField(field, {
name: interfaceDeclaration.getName(), file: fileDTS, mapper: externalMapper.map, }) if (parentName === queryType.name) knownSpecialCasesForGraphQL.add(queryType.name) if (parentName === mutationType.name) knownSpecialCasesForGraphQL.add(mutationType.name) const argsParam = args ?? "object" const returnType = returnTypeForResolver(returnTypeMapper, field, config) interfaceDeclaration.addCallSignature({ parameters: [ { name: "args", type: argsParam, hasQuestionToken: config.funcArgCount < 1 }, { name: "obj", type: `{ root: ${parentName}, context: RedwoodGraphQLContext, info: GraphQLResolveInfo }`, hasQuestionToken: config.funcArgCount < 2, }, ], returnType, }) } /** Ideally, we want to be able to write the type for just the object */ function addCustomTypeModel(modelFacts: ModelResolverFacts) { const modelName = modelFacts.typeName extraPrismaReferences.add(modelName) // Make an interface, this is the version we are replacing from graphql-codegen: // Account: MergePrismaWithSdlTypes<PrismaAccount, MakeRelationsOptional<Account, AllMappedModels>, AllMappedModels>; const gqlType = gql.getType(modelName) if (!gqlType) { // throw new Error(`Could not find a GraphQL type named ${d.getName()}`); fileDTS.addStatements(`\n// ${modelName} does not exist in the schema`) return } if (!graphql.isObjectType(gqlType)) { throw new Error(`In your schema ${modelName} is not an object, which we can only make resolver types for`) } const fields = gqlType.getFields() // See: https://github.com/redwoodjs/redwood/pull/6228#issue-1342966511 // For more ideas const hasGenerics = modelFacts.hasGenericArg // This is what they would have to write const resolverInterface = fileDTS.addInterface({ name: `${modelName}TypeResolvers`, typeParameters: hasGenerics ? ["Extended"] : [], isExported: true, }) // The parent type for the resolvers fileDTS.addTypeAlias({ name: `${modelName}AsParent`, typeParameters: hasGenerics ? ["Extended"] : [], type: `P${modelName} ${createParentAdditionallyDefinedFunctions()} ${hasGenerics ? " & Extended" : ""}`, // docs: ["The prisma model, mixed with fns already defined inside the resolvers."], }) const modelFieldFacts = fieldFacts.get(modelName) ?? {} // Loop through the resolvers, adding the fields which have resolvers implemented in the source file modelFacts.resolvers.forEach((resolver) => { const field = fields[resolver.name] if (field) { const fieldName = resolver.name if (modelFieldFacts[fieldName]) modelFieldFacts[fieldName].hasResolverImplementation = true else modelFieldFacts[fieldName] = { hasResolverImplementation: true } const argsType = inlineArgsForField(field, { mapper: externalMapper.map }) ?? "undefined" const param = hasGenerics ? "<Extended>" : "" const firstQ = resolver.funcArgCount < 1 ? "?" : "" const secondQ = resolver.funcArgCount < 2 ? "?" : "" const innerArgs = `args${firstQ}: ${argsType}, obj${secondQ}: { root: ${modelName}AsParent${param}, context: RedwoodGraphQLContext, info: GraphQLResolveInfo }` const returnType = returnTypeForResolver(returnTypeMapper, field, resolver) const docs = field.astNode ? [`SDL: ${graphql.print(field.astNode)}`] : [] // For speed we should switch this out to addProperties eventually resolverInterface.addProperty({ name: fieldName, leadingTrivia: "\n", docs, type: resolver.isFunc || resolver.isUnknown ? `(${innerArgs}) => ${returnType ?? "any"}` : returnType, }) } else { resolverInterface.addCallSignature({ docs: [` @deprecated: SDL ${modelName}.${resolver.name} does not exist in your schema`], }) } }) function createParentAdditionallyDefinedFunctions() { const fns: string[] = [] modelFacts.resolvers.forEach((resolver) => { const existsInGraphQLSchema = fields[resolver.name] if (!existsInGraphQLSchema) { console.warn( `The service file ${filename} has a field ${resolver.name} on ${modelName} that does not exist in the generated schema.graphql` ) } const prefix = !existsInGraphQLSchema ? "\n// This field does not exist in the generated schema.graphql\n" : "" const returnType = returnTypeForResolver(externalMapper, existsInGraphQLSchema, resolver) // fns.push(`${prefix}${resolver.name}: () => Promise<${externalMapper.map(type, {})}>`) fns.push(`${prefix}${resolver.name}: () => ${returnType}`) }) if (fns.length < 1) return "" return "& {" + fns.join(", \n") + "}" } fieldFacts.set(modelName, modelFieldFacts) } return dtsFilename } function returnTypeForResolver(mapper: TypeMapper, field: graphql.GraphQLField<unknown, unknown> | undefined, resolver: ResolverFuncFact) { if (!field) return "void" const tType = mapper.map(field.type, { preferNullOverUndefined: true, typenamePrefix: "RT" }) ?? "void" let returnType = tType const all = `${tType} | Promise<${tType}> | (() => Promise<${tType}>)` if (resolver.isFunc && resolver.isAsync) returnType = `Promise<${tType}>` else if (resolver.isFunc) returnType = all else if (resolver.isObjLiteral) returnType = tType else if (resolver.isUnknown) returnType = all return returnType }
src/serviceFile.ts
sdl-codegen-sdl-codegen-de2b8aa
[ { "filename": "src/utils.ts", "retrieved_chunk": "\t\tnoSeparateType?: true\n\t}\n) => {\n\tconst inlineArgs = inlineArgsForField(field, config)\n\tif (!inlineArgs) return undefined\n\tif (inlineArgs.length < 120) return inlineArgs\n\tconst argsInterface = config.file.addInterface({\n\t\tname: `${config.name}Args`,\n\t\tisExported: true,\n\t})", "score": 0.8608594536781311 }, { "filename": "src/utils.ts", "retrieved_chunk": "\t\t\t\t})\n\t\t\t\t.join(\", \")}}`\n\t\t: undefined\n}\nexport const createAndReferOrInlineArgsForField = (\n\tfield: graphql.GraphQLField<unknown, unknown>,\n\tconfig: {\n\t\tfile: tsMorph.SourceFile\n\t\tmapper: TypeMapper[\"map\"]\n\t\tname: string", "score": 0.8501524925231934 }, { "filename": "src/utils.ts", "retrieved_chunk": "export const inlineArgsForField = (field: graphql.GraphQLField<unknown, unknown>, config: { mapper: TypeMapper[\"map\"] }) => {\n\treturn field.args.length\n\t\t? // Always use an args obj\n\t\t `{${field.args\n\t\t\t\t.map((f) => {\n\t\t\t\t\tconst type = config.mapper(f.type, {})\n\t\t\t\t\tif (!type) throw new Error(`No type for ${f.name} on ${field.name}!`)\n\t\t\t\t\tconst q = type.includes(\"undefined\") ? \"?\" : \"\"\n\t\t\t\t\tconst displayType = type.replace(\"| undefined\", \"\")\n\t\t\t\t\treturn `${f.name}${q}: ${displayType}`", "score": 0.8376027941703796 }, { "filename": "src/sharedSchema.ts", "retrieved_chunk": "\t\t\t\t\t\t}\n\t\t\t\t\t\treturn field\n\t\t\t\t\t}),\n\t\t\t\t],\n\t\t\t})\n\t\t}\n\t\tif (graphql.isEnumType(type)) {\n\t\t\texternalTSFile.addTypeAlias({\n\t\t\t\tname: type.name,\n\t\t\t\ttype:", "score": 0.8352160453796387 }, { "filename": "src/serviceFile.codefacts.ts", "retrieved_chunk": "\tconst referenceFileSourceFile = context.tsProject.createSourceFile(`/source/${fileKey}`, fileContents, { overwrite: true })\n\tconst vars = referenceFileSourceFile.getVariableDeclarations().filter((v) => v.isExported())\n\tconst resolverContainers = vars.filter(varStartsWithUppercase)\n\tconst queryOrMutationResolvers = vars.filter((v) => !varStartsWithUppercase(v))\n\tqueryOrMutationResolvers.forEach((v) => {\n\t\tconst parent = \"maybe_query_mutation\"\n\t\tconst facts = getResolverInformationForDeclaration(v.getInitializer())\n\t\t// Start making facts about the services\n\t\tconst fact: ModelResolverFacts = fileFact[parent] ?? {\n\t\t\ttypeName: parent,", "score": 0.8350824117660522 } ]
typescript
args = createAndReferOrInlineArgsForField(field, {
import * as tsMorph from "ts-morph" import { AppContext } from "./context.js" import { CodeFacts, ModelResolverFacts, ResolverFuncFact } from "./typeFacts.js" import { varStartsWithUppercase } from "./utils.js" export const getCodeFactsForJSTSFileAtPath = (file: string, context: AppContext) => { const { pathSettings: settings } = context const fileKey = file.replace(settings.apiServicesPath, "") // const priorFacts = serviceInfo.get(fileKey) const fileFact: CodeFacts = {} const fileContents = context.sys.readFile(file) const referenceFileSourceFile = context.tsProject.createSourceFile(`/source/${fileKey}`, fileContents, { overwrite: true }) const vars = referenceFileSourceFile.getVariableDeclarations().filter((v) => v.isExported()) const resolverContainers = vars.filter(varStartsWithUppercase) const queryOrMutationResolvers = vars.filter((v) => !varStartsWithUppercase(v)) queryOrMutationResolvers.forEach((v) => { const parent = "maybe_query_mutation" const facts = getResolverInformationForDeclaration(v.getInitializer()) // Start making facts about the services const fact: ModelResolverFacts = fileFact[parent] ?? { typeName: parent, resolvers: new Map(), hasGenericArg: false, } fact.resolvers.set(v.getName(), { name: v.getName(), ...facts }) fileFact[parent] = fact }) // Next all the capital consts resolverContainers.forEach((c) => { addCustomTypeResolvers(c) }) return fileFact function addCustomTypeResolvers(variableDeclaration: tsMorph.VariableDeclaration) { const declarations = variableDeclaration.getVariableStatementOrThrow().getDeclarations() declarations.forEach((d) => { const name = d.getName() // only do it if the first letter is a capital if (!name.match(/^[A-Z]/)) return const type = d.getType() const hasGenericArg = type.getText().includes("<") // Start making facts about the services const fact: ModelResolverFacts = fileFact[name] ?? { typeName: name, resolvers: new Map(), hasGenericArg, } // Grab the const Thing = { ... } const obj = d.getFirstDescendantByKind(tsMorph.SyntaxKind.ObjectLiteralExpression) if (!obj) { throw new Error(`Could not find an object literal ( e.g. a { } ) in ${d.getName()}`) } obj.getProperties().forEach((p) => { if (p.isKind(tsMorph.SyntaxKind.SpreadAssignment)) { return } if (p.isKind(tsMorph.SyntaxKind.PropertyAssignment) && p.hasInitializer()) { const name = p.getName() fact.resolvers.set(name, { name, ...getResolverInformationForDeclaration(p.getInitializerOrThrow()) }) } if (p.isKind(tsMorph.SyntaxKind.FunctionDeclaration) && p.getName()) { const name = p.getName() // @ts-expect-error - lets let this go for now fact.resolvers.set(name, { name, ...getResolverInformationForDeclaration(p) }) } }) fileFact[d.getName()] = fact }) } }
const getResolverInformationForDeclaration = (initialiser: tsMorph.Expression | undefined): Omit<ResolverFuncFact, "name"> => {
// Who knows what folks could do, lets not crash if (!initialiser) { return { funcArgCount: 0, isFunc: false, isAsync: false, isUnknown: true, isObjLiteral: false, } } // resolver is a fn if (initialiser.isKind(tsMorph.SyntaxKind.ArrowFunction) || initialiser.isKind(tsMorph.SyntaxKind.FunctionExpression)) { return { funcArgCount: initialiser.getParameters().length, isFunc: true, isAsync: initialiser.isAsync(), isUnknown: false, isObjLiteral: false, } } // resolver is a raw obj if ( initialiser.isKind(tsMorph.SyntaxKind.ObjectLiteralExpression) || initialiser.isKind(tsMorph.SyntaxKind.StringLiteral) || initialiser.isKind(tsMorph.SyntaxKind.NumericLiteral) || initialiser.isKind(tsMorph.SyntaxKind.TrueKeyword) || initialiser.isKind(tsMorph.SyntaxKind.FalseKeyword) || initialiser.isKind(tsMorph.SyntaxKind.NullKeyword) || initialiser.isKind(tsMorph.SyntaxKind.UndefinedKeyword) ) { return { funcArgCount: 0, isFunc: false, isAsync: false, isUnknown: false, isObjLiteral: true, } } // who knows return { funcArgCount: 0, isFunc: false, isAsync: false, isUnknown: true, isObjLiteral: false, } }
src/serviceFile.codefacts.ts
sdl-codegen-sdl-codegen-de2b8aa
[ { "filename": "src/serviceFile.ts", "retrieved_chunk": "\t// The file we'll be creating in-memory throughout this fn\n\tconst fileDTS = context.tsProject.createSourceFile(`source/${fileKey}.d.ts`, \"\", { overwrite: true })\n\t// Basically if a top level resolver reference Query or Mutation\n\tconst knownSpecialCasesForGraphQL = new Set<string>()\n\t// Add the root function declarations\n\tconst rootResolvers = fileFacts.maybe_query_mutation?.resolvers\n\tif (rootResolvers)\n\t\trootResolvers.forEach((v) => {\n\t\t\tconst isQuery = v.name in queryType.getFields()\n\t\t\tconst isMutation = v.name in mutationType.getFields()", "score": 0.8264249563217163 }, { "filename": "src/serviceFile.ts", "retrieved_chunk": "\t\t\tconst parentName = isQuery ? queryType.name : isMutation ? mutationType.name : undefined\n\t\t\tif (parentName) {\n\t\t\t\taddDefinitionsForTopLevelResolvers(parentName, v)\n\t\t\t} else {\n\t\t\t\t// Add warning about unused resolver\n\t\t\t\tfileDTS.addStatements(`\\n// ${v.name} does not exist on Query or Mutation`)\n\t\t\t}\n\t\t})\n\t// Add the root function declarations\n\tObject.values(fileFacts).forEach((model) => {", "score": 0.8155667781829834 }, { "filename": "src/typeFacts.ts", "retrieved_chunk": "export type FieldFacts = Record<string, FieldFact>\nexport interface FieldFact {\n\thasResolverImplementation?: true\n\t// isPrismaBacked?: true;\n}\n// The data-model for the service file which contains the SDL matched functions\n/** A representation of the code inside the source file's */\nexport type CodeFacts = Record<string, ModelResolverFacts | undefined>\nexport interface ModelResolverFacts {\n\t/** Should we type the type as a generic with an override */", "score": 0.81171715259552 }, { "filename": "src/serviceFile.ts", "retrieved_chunk": "\t\t\t\t// fns.push(`${prefix}${resolver.name}: () => Promise<${externalMapper.map(type, {})}>`)\n\t\t\t\tfns.push(`${prefix}${resolver.name}: () => ${returnType}`)\n\t\t\t})\n\t\t\tif (fns.length < 1) return \"\"\n\t\t\treturn \"& {\" + fns.join(\", \\n\") + \"}\"\n\t\t}\n\t\tfieldFacts.set(modelName, modelFieldFacts)\n\t}\n\treturn dtsFilename\n}", "score": 0.807349443435669 }, { "filename": "src/serviceFile.ts", "retrieved_chunk": "\tconst mutationType = gql.getMutationType()!\n\t// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n\tif (!mutationType) throw new Error(\"No mutation type\")\n\tconst externalMapper = typeMapper(context, { preferPrismaModels: true })\n\tconst returnTypeMapper = typeMapper(context, {})\n\t// The description of the source file\n\tconst fileFacts = getCodeFactsForJSTSFileAtPath(file, context)\n\tif (Object.keys(fileFacts).length === 0) return\n\t// Tracks prospective prisma models which are used in the file\n\tconst extraPrismaReferences = new Set<string>()", "score": 0.8046783804893494 } ]
typescript
const getResolverInformationForDeclaration = (initialiser: tsMorph.Expression | undefined): Omit<ResolverFuncFact, "name"> => {
import { getSchema as getPrismaSchema } from "@mrleebo/prisma-ast" import * as graphql from "graphql" import { Project } from "ts-morph" import typescript from "typescript" import { AppContext } from "./context.js" import { PrismaMap, prismaModeller } from "./prismaModeller.js" import { lookAtServiceFile } from "./serviceFile.js" import { createSharedSchemaFiles } from "./sharedSchema.js" import { CodeFacts, FieldFacts } from "./typeFacts.js" import { RedwoodPaths } from "./types.js" export * from "./main.js" export * from "./types.js" import { basename, join } from "node:path" /** The API specifically for Redwood */ export function runFullCodegen(preset: "redwood", config: { paths: RedwoodPaths }): { paths: string[] } export function runFullCodegen(preset: string, config: unknown): { paths: string[] } export function runFullCodegen(preset: string, config: unknown): { paths: string[] } { if (preset !== "redwood") throw new Error("Only Redwood codegen is supported at this time") const paths = (config as { paths: RedwoodPaths }).paths const sys = typescript.sys const pathSettings: AppContext["pathSettings"] = { root: paths.base, apiServicesPath: paths.api.services, prismaDSLPath: paths.api.dbSchema, graphQLSchemaPath: paths.generated.schema, sharedFilename: "shared-schema-types.d.ts", sharedInternalFilename: "shared-return-types.d.ts", typesFolderRoot: paths.api.types, } const project = new Project({ useInMemoryFileSystem: true }) let gqlSchema: graphql.GraphQLSchema | undefined const getGraphQLSDLFromFile = (settings: AppContext["pathSettings"]) => { const schema = sys.readFile(settings.graphQLSchemaPath) if (!schema) throw new Error("No schema found at " + settings.graphQLSchemaPath) gqlSchema = graphql.buildSchema(schema) } let prismaSchema: PrismaMap = new Map() const getPrismaSchemaFromFile = (settings: AppContext["pathSettings"]) => { const prismaSchemaText = sys.readFile(settings.prismaDSLPath) if (!prismaSchemaText) throw new Error("No prisma file found at " + settings.prismaDSLPath) const prismaSchemaBlocks = getPrismaSchema(prismaSchemaText) prismaSchema = prismaModeller(prismaSchemaBlocks) } getGraphQLSDLFromFile(pathSettings) getPrismaSchemaFromFile(pathSettings) if (!gqlSchema) throw new Error("No GraphQL Schema was created during setup") const appContext: AppContext = { gql: gqlSchema, prisma: prismaSchema, tsProject: project, codeFacts: new Map<string, CodeFacts>(), fieldFacts: new Map<string, FieldFacts>(), pathSettings, sys, join, basename, } // TODO: Maybe Redwood has an API for this? Its grabbing all the services const serviceFiles = appContext.sys.readDirectory(appContext.pathSettings.apiServicesPath)
const serviceFilesToLookAt = serviceFiles.filter((file) => {
if (file.endsWith(".test.ts")) return false if (file.endsWith("scenarios.ts")) return false return file.endsWith(".ts") || file.endsWith(".tsx") || file.endsWith(".js") }) const filepaths = [] as string[] // Create the two shared schema files const sharedDTSes = createSharedSchemaFiles(appContext) filepaths.push(...sharedDTSes) // This needs to go first, as it sets up fieldFacts for (const path of serviceFilesToLookAt) { const dts = lookAtServiceFile(path, appContext) if (dts) filepaths.push(dts) } return { paths: filepaths, } }
src/index.ts
sdl-codegen-sdl-codegen-de2b8aa
[ { "filename": "src/run.ts", "retrieved_chunk": "\t\tsys,\n\t\tjoin,\n\t\tbasename,\n\t}\n\tconst serviceFilesToLookAt = [] as string[]\n\tfor (const dirEntry of sys.readDirectory(appContext.pathSettings.apiServicesPath)) {\n\t\t// These are generally the folders\n\t\tif (sys.directoryExists(dirEntry)) {\n\t\t\tconst folderPath = join(appContext.pathSettings.apiServicesPath, dirEntry)\n\t\t\t// And these are the files in them", "score": 0.8888975977897644 }, { "filename": "src/tests/testRunner.ts", "retrieved_chunk": "\t\tjoin,\n\t}\n\tif (run.gamesService) {\n\t\tvfsMap.set(\"/api/src/services/games.ts\", run.gamesService)\n\t\tlookAtServiceFile(\"/api/src/services/games.ts\", appContext)\n\t}\n\treturn {\n\t\tvfsMap,\n\t\tappContext,\n\t}", "score": 0.863024115562439 }, { "filename": "src/run.ts", "retrieved_chunk": "\t}\n\tconst settings: AppContext[\"pathSettings\"] = {\n\t\troot: appRoot,\n\t\tgraphQLSchemaPath: join(appRoot, \".redwood\", \"schema.graphql\"),\n\t\tapiServicesPath: join(appRoot, \"api\", \"src\", \"services\"),\n\t\tprismaDSLPath: join(appRoot, \"api\", \"db\", \"schema.prisma\"),\n\t\tsharedFilename: \"shared-schema-types.d.ts\",\n\t\tsharedInternalFilename: \"shared-return-types.d.ts\",\n\t\ttypesFolderRoot: typesRoot,\n\t}", "score": 0.8543350696563721 }, { "filename": "src/run.ts", "retrieved_chunk": "\t// This needs to go first, as it sets up fieldFacts\n\tfor (const path of serviceFilesToLookAt) {\n\t\tlookAtServiceFile(path, appContext)\n\t}\n\tcreateSharedSchemaFiles(appContext)\n\t// console.log(`Updated`, typesRoot)\n\tif (config.runESLint) {\n\t\t// console.log(\"Running ESLint...\")\n\t\t// const process = Deno.run({\n\t\t// \tcwd: appRoot,", "score": 0.8519176840782166 }, { "filename": "src/run.ts", "retrieved_chunk": "\t\t\tfor (const subdirEntry of sys.readDirectory(folderPath)) {\n\t\t\t\tconst folderPath = join(appContext.pathSettings.apiServicesPath, dirEntry)\n\t\t\t\tif (\n\t\t\t\t\tsys.fileExists(folderPath) &&\n\t\t\t\t\tsubdirEntry.endsWith(\".ts\") &&\n\t\t\t\t\t!subdirEntry.includes(\".test.ts\") &&\n\t\t\t\t\t!subdirEntry.includes(\"scenarios.ts\")\n\t\t\t\t) {\n\t\t\t\t\tserviceFilesToLookAt.push(join(folderPath, subdirEntry))\n\t\t\t\t}", "score": 0.8403507471084595 } ]
typescript
const serviceFilesToLookAt = serviceFiles.filter((file) => {
import { getSchema as getPrismaSchema } from "@mrleebo/prisma-ast" import * as graphql from "graphql" import { Project } from "ts-morph" import typescript from "typescript" import { AppContext } from "./context.js" import { PrismaMap, prismaModeller } from "./prismaModeller.js" import { lookAtServiceFile } from "./serviceFile.js" import { createSharedSchemaFiles } from "./sharedSchema.js" import { CodeFacts, FieldFacts } from "./typeFacts.js" import { RedwoodPaths } from "./types.js" export * from "./main.js" export * from "./types.js" import { basename, join } from "node:path" /** The API specifically for Redwood */ export function runFullCodegen(preset: "redwood", config: { paths: RedwoodPaths }): { paths: string[] } export function runFullCodegen(preset: string, config: unknown): { paths: string[] } export function runFullCodegen(preset: string, config: unknown): { paths: string[] } { if (preset !== "redwood") throw new Error("Only Redwood codegen is supported at this time") const paths = (config as { paths: RedwoodPaths }).paths const sys = typescript.sys const pathSettings: AppContext["pathSettings"] = { root: paths.base, apiServicesPath: paths.api.services, prismaDSLPath: paths.api.dbSchema, graphQLSchemaPath: paths.generated.schema, sharedFilename: "shared-schema-types.d.ts", sharedInternalFilename: "shared-return-types.d.ts", typesFolderRoot: paths.api.types, } const project = new Project({ useInMemoryFileSystem: true }) let gqlSchema: graphql.GraphQLSchema | undefined const getGraphQLSDLFromFile = (settings: AppContext["pathSettings"]) => { const schema = sys.readFile(settings.graphQLSchemaPath) if (!schema) throw new Error("No schema found at " + settings.graphQLSchemaPath) gqlSchema = graphql.buildSchema(schema) } let prismaSchema: PrismaMap = new Map() const getPrismaSchemaFromFile = (settings: AppContext["pathSettings"]) => { const prismaSchemaText = sys.readFile(settings.prismaDSLPath) if (!prismaSchemaText) throw new Error("No prisma file found at " + settings.prismaDSLPath) const prismaSchemaBlocks = getPrismaSchema(prismaSchemaText) prismaSchema = prismaModeller(prismaSchemaBlocks) } getGraphQLSDLFromFile(pathSettings) getPrismaSchemaFromFile(pathSettings) if (!gqlSchema) throw new Error("No GraphQL Schema was created during setup") const appContext: AppContext = { gql: gqlSchema, prisma: prismaSchema, tsProject: project, codeFacts: new Map<string, CodeFacts>(), fieldFacts: new Map<string, FieldFacts>(), pathSettings, sys, join, basename, } // TODO: Maybe Redwood has an API for this? Its grabbing all the services const serviceFiles = appContext.sys.readDirectory(appContext.pathSettings.apiServicesPath) const serviceFilesToLookAt = serviceFiles.filter((file) => { if (file.endsWith(".test.ts")) return false if (file.endsWith("scenarios.ts")) return false return file.endsWith(".ts") || file.endsWith(".tsx") || file.endsWith(".js") }) const filepaths = [] as string[] // Create the two shared schema files const sharedDTSes = createSharedSchemaFiles(appContext) filepaths.push(...sharedDTSes) // This needs to go first, as it sets up fieldFacts for (const path of serviceFilesToLookAt) {
const dts = lookAtServiceFile(path, appContext) if (dts) filepaths.push(dts) }
return { paths: filepaths, } }
src/index.ts
sdl-codegen-sdl-codegen-de2b8aa
[ { "filename": "src/run.ts", "retrieved_chunk": "\t// This needs to go first, as it sets up fieldFacts\n\tfor (const path of serviceFilesToLookAt) {\n\t\tlookAtServiceFile(path, appContext)\n\t}\n\tcreateSharedSchemaFiles(appContext)\n\t// console.log(`Updated`, typesRoot)\n\tif (config.runESLint) {\n\t\t// console.log(\"Running ESLint...\")\n\t\t// const process = Deno.run({\n\t\t// \tcwd: appRoot,", "score": 0.9102056622505188 }, { "filename": "src/run.ts", "retrieved_chunk": "\t\tsys,\n\t\tjoin,\n\t\tbasename,\n\t}\n\tconst serviceFilesToLookAt = [] as string[]\n\tfor (const dirEntry of sys.readDirectory(appContext.pathSettings.apiServicesPath)) {\n\t\t// These are generally the folders\n\t\tif (sys.directoryExists(dirEntry)) {\n\t\t\tconst folderPath = join(appContext.pathSettings.apiServicesPath, dirEntry)\n\t\t\t// And these are the files in them", "score": 0.8612841367721558 }, { "filename": "src/run.ts", "retrieved_chunk": "\t\t\tfor (const subdirEntry of sys.readDirectory(folderPath)) {\n\t\t\t\tconst folderPath = join(appContext.pathSettings.apiServicesPath, dirEntry)\n\t\t\t\tif (\n\t\t\t\t\tsys.fileExists(folderPath) &&\n\t\t\t\t\tsubdirEntry.endsWith(\".ts\") &&\n\t\t\t\t\t!subdirEntry.includes(\".test.ts\") &&\n\t\t\t\t\t!subdirEntry.includes(\"scenarios.ts\")\n\t\t\t\t) {\n\t\t\t\t\tserviceFilesToLookAt.push(join(folderPath, subdirEntry))\n\t\t\t\t}", "score": 0.8601928353309631 }, { "filename": "src/serviceFile.ts", "retrieved_chunk": "import * as graphql from \"graphql\"\nimport { AppContext } from \"./context.js\"\nimport { formatDTS, getPrettierConfig } from \"./formatDTS.js\"\nimport { getCodeFactsForJSTSFileAtPath } from \"./serviceFile.codefacts.js\"\nimport { CodeFacts, ModelResolverFacts, ResolverFuncFact } from \"./typeFacts.js\"\nimport { TypeMapper, typeMapper } from \"./typeMap.js\"\nimport { capitalizeFirstLetter, createAndReferOrInlineArgsForField, inlineArgsForField } from \"./utils.js\"\nexport const lookAtServiceFile = (file: string, context: AppContext) => {\n\tconst { gql, prisma, pathSettings: settings, codeFacts: serviceFacts, fieldFacts } = context\n\t// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition", "score": 0.8569678068161011 }, { "filename": "src/tests/serviceFile.test.ts", "retrieved_chunk": "export const game = () => {}\nexport function game2() {}\n `\n\t)\n\texpect(vfsMap.has(\"/types/example.d.ts\")).toBeFalsy()\n\tlookAtServiceFile(\"/api/src/services/example.ts\", appContext)\n\t// this isn't really very useful as a test, but it proves it doesn't crash?\n})\nit(\"generates useful service facts from a (truncated) real file\", () => {\n\tconst { appContext, vfsMap } = getDTSFilesForRun({})", "score": 0.8436259031295776 } ]
typescript
const dts = lookAtServiceFile(path, appContext) if (dts) filepaths.push(dts) }
import { getSchema as getPrismaSchema } from "@mrleebo/prisma-ast" import * as graphql from "graphql" import { Project } from "ts-morph" import typescript from "typescript" import { AppContext } from "./context.js" import { PrismaMap, prismaModeller } from "./prismaModeller.js" import { lookAtServiceFile } from "./serviceFile.js" import { createSharedSchemaFiles } from "./sharedSchema.js" import { CodeFacts, FieldFacts } from "./typeFacts.js" import { RedwoodPaths } from "./types.js" export * from "./main.js" export * from "./types.js" import { basename, join } from "node:path" /** The API specifically for Redwood */ export function runFullCodegen(preset: "redwood", config: { paths: RedwoodPaths }): { paths: string[] } export function runFullCodegen(preset: string, config: unknown): { paths: string[] } export function runFullCodegen(preset: string, config: unknown): { paths: string[] } { if (preset !== "redwood") throw new Error("Only Redwood codegen is supported at this time") const paths = (config as { paths: RedwoodPaths }).paths const sys = typescript.sys const pathSettings: AppContext["pathSettings"] = { root: paths.base, apiServicesPath: paths.api.services, prismaDSLPath: paths.api.dbSchema, graphQLSchemaPath: paths.generated.schema, sharedFilename: "shared-schema-types.d.ts", sharedInternalFilename: "shared-return-types.d.ts", typesFolderRoot: paths.api.types, } const project = new Project({ useInMemoryFileSystem: true }) let gqlSchema: graphql.GraphQLSchema | undefined const getGraphQLSDLFromFile = (settings: AppContext["pathSettings"]) => { const schema = sys.readFile(settings.graphQLSchemaPath) if (!schema) throw new Error("No schema found at " + settings.graphQLSchemaPath) gqlSchema = graphql.buildSchema(schema) } let prismaSchema: PrismaMap = new Map() const getPrismaSchemaFromFile = (settings: AppContext["pathSettings"]) => { const prismaSchemaText = sys.readFile(settings.prismaDSLPath) if (!prismaSchemaText) throw new Error("No prisma file found at " + settings.prismaDSLPath) const prismaSchemaBlocks = getPrismaSchema(prismaSchemaText) prismaSchema = prismaModeller(prismaSchemaBlocks) } getGraphQLSDLFromFile(pathSettings) getPrismaSchemaFromFile(pathSettings) if (!gqlSchema) throw new Error("No GraphQL Schema was created during setup") const appContext: AppContext = { gql: gqlSchema, prisma: prismaSchema, tsProject: project, codeFacts: new Map<string, CodeFacts>(), fieldFacts: new Map<string, FieldFacts>(), pathSettings, sys, join, basename, } // TODO: Maybe Redwood has an API for this? Its grabbing all the services const serviceFiles = appContext.sys.readDirectory(appContext.pathSettings.apiServicesPath) const serviceFilesToLookAt = serviceFiles
.filter((file) => {
if (file.endsWith(".test.ts")) return false if (file.endsWith("scenarios.ts")) return false return file.endsWith(".ts") || file.endsWith(".tsx") || file.endsWith(".js") }) const filepaths = [] as string[] // Create the two shared schema files const sharedDTSes = createSharedSchemaFiles(appContext) filepaths.push(...sharedDTSes) // This needs to go first, as it sets up fieldFacts for (const path of serviceFilesToLookAt) { const dts = lookAtServiceFile(path, appContext) if (dts) filepaths.push(dts) } return { paths: filepaths, } }
src/index.ts
sdl-codegen-sdl-codegen-de2b8aa
[ { "filename": "src/run.ts", "retrieved_chunk": "\t\tsys,\n\t\tjoin,\n\t\tbasename,\n\t}\n\tconst serviceFilesToLookAt = [] as string[]\n\tfor (const dirEntry of sys.readDirectory(appContext.pathSettings.apiServicesPath)) {\n\t\t// These are generally the folders\n\t\tif (sys.directoryExists(dirEntry)) {\n\t\t\tconst folderPath = join(appContext.pathSettings.apiServicesPath, dirEntry)\n\t\t\t// And these are the files in them", "score": 0.8975462913513184 }, { "filename": "src/run.ts", "retrieved_chunk": "\t\t\tfor (const subdirEntry of sys.readDirectory(folderPath)) {\n\t\t\t\tconst folderPath = join(appContext.pathSettings.apiServicesPath, dirEntry)\n\t\t\t\tif (\n\t\t\t\t\tsys.fileExists(folderPath) &&\n\t\t\t\t\tsubdirEntry.endsWith(\".ts\") &&\n\t\t\t\t\t!subdirEntry.includes(\".test.ts\") &&\n\t\t\t\t\t!subdirEntry.includes(\"scenarios.ts\")\n\t\t\t\t) {\n\t\t\t\t\tserviceFilesToLookAt.push(join(folderPath, subdirEntry))\n\t\t\t\t}", "score": 0.8499971032142639 }, { "filename": "src/tests/testRunner.ts", "retrieved_chunk": "\t\tjoin,\n\t}\n\tif (run.gamesService) {\n\t\tvfsMap.set(\"/api/src/services/games.ts\", run.gamesService)\n\t\tlookAtServiceFile(\"/api/src/services/games.ts\", appContext)\n\t}\n\treturn {\n\t\tvfsMap,\n\t\tappContext,\n\t}", "score": 0.8497567176818848 }, { "filename": "src/run.ts", "retrieved_chunk": "\t// This needs to go first, as it sets up fieldFacts\n\tfor (const path of serviceFilesToLookAt) {\n\t\tlookAtServiceFile(path, appContext)\n\t}\n\tcreateSharedSchemaFiles(appContext)\n\t// console.log(`Updated`, typesRoot)\n\tif (config.runESLint) {\n\t\t// console.log(\"Running ESLint...\")\n\t\t// const process = Deno.run({\n\t\t// \tcwd: appRoot,", "score": 0.8490540981292725 }, { "filename": "src/run.ts", "retrieved_chunk": "\t}\n\tconst settings: AppContext[\"pathSettings\"] = {\n\t\troot: appRoot,\n\t\tgraphQLSchemaPath: join(appRoot, \".redwood\", \"schema.graphql\"),\n\t\tapiServicesPath: join(appRoot, \"api\", \"src\", \"services\"),\n\t\tprismaDSLPath: join(appRoot, \"api\", \"db\", \"schema.prisma\"),\n\t\tsharedFilename: \"shared-schema-types.d.ts\",\n\t\tsharedInternalFilename: \"shared-return-types.d.ts\",\n\t\ttypesFolderRoot: typesRoot,\n\t}", "score": 0.8420535922050476 } ]
typescript
.filter((file) => {
import * as graphql from "graphql" import { AppContext } from "./context.js" import { formatDTS, getPrettierConfig } from "./formatDTS.js" import { getCodeFactsForJSTSFileAtPath } from "./serviceFile.codefacts.js" import { CodeFacts, ModelResolverFacts, ResolverFuncFact } from "./typeFacts.js" import { TypeMapper, typeMapper } from "./typeMap.js" import { capitalizeFirstLetter, createAndReferOrInlineArgsForField, inlineArgsForField } from "./utils.js" export const lookAtServiceFile = (file: string, context: AppContext) => { const { gql, prisma, pathSettings: settings, codeFacts: serviceFacts, fieldFacts } = context // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition if (!gql) throw new Error(`No schema when wanting to look at service file: ${file}`) if (!prisma) throw new Error(`No prisma schema when wanting to look at service file: ${file}`) // This isn't good enough, needs to be relative to api/src/services const fileKey = file.replace(settings.apiServicesPath, "") const thisFact: CodeFacts = {} const filename = context.basename(file) // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const queryType = gql.getQueryType()! if (!queryType) throw new Error("No query type") // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const mutationType = gql.getMutationType()! // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition if (!mutationType) throw new Error("No mutation type") const externalMapper = typeMapper(context, { preferPrismaModels: true }) const returnTypeMapper = typeMapper(context, {}) // The description of the source file const fileFacts = getCodeFactsForJSTSFileAtPath(file, context) if (Object.keys(fileFacts).length === 0) return // Tracks prospective prisma models which are used in the file const extraPrismaReferences = new Set<string>() // The file we'll be creating in-memory throughout this fn const fileDTS = context.tsProject.createSourceFile(`source/${fileKey}.d.ts`, "", { overwrite: true }) // Basically if a top level resolver reference Query or Mutation const knownSpecialCasesForGraphQL = new Set<string>() // Add the root function declarations const rootResolvers = fileFacts.maybe_query_mutation?.resolvers if (rootResolvers) rootResolvers.forEach((v) => { const isQuery = v.name in queryType.getFields() const isMutation = v.name in mutationType.getFields() const parentName = isQuery ? queryType.name : isMutation ? mutationType.name : undefined if (parentName) { addDefinitionsForTopLevelResolvers(parentName, v) } else { // Add warning about unused resolver fileDTS.addStatements(`\n// ${v.name} does not exist on Query or Mutation`) } }) // Add the root function declarations Object.values(fileFacts).forEach((model) => { if (!model) return const skip = ["maybe_query_mutation", queryType.name, mutationType.name] if (skip.includes(model.typeName)) return addCustomTypeModel(model) }) // Set up the module imports at the top const sharedGraphQLObjectsReferenced = externalMapper.getReferencedGraphQLThingsInMapping() const sharedGraphQLObjectsReferencedTypes = [...sharedGraphQLObjectsReferenced.types, ...knownSpecialCasesForGraphQL] const sharedInternalGraphQLObjectsReferenced = returnTypeMapper.getReferencedGraphQLThingsInMapping() const aliases = [...new Set([...sharedGraphQLObjectsReferenced.scalars, ...sharedInternalGraphQLObjectsReferenced.scalars])] if (aliases.length) { fileDTS.addTypeAliases( aliases.map((s) => ({ name: s, type: "any", })) ) } const prismases = [ ...new Set([ ...sharedGraphQLObjectsReferenced.prisma, ...sharedInternalGraphQLObjectsReferenced.prisma, ...extraPrismaReferences.values(), ]), ] const validPrismaObjs = prismases.filter((p) => prisma.has(p)) if (validPrismaObjs.length) { fileDTS.addImportDeclaration({ isTypeOnly: true, moduleSpecifier: "@prisma/client", namedImports: validPrismaObjs.map((p) => `${p} as P${p}`), }) } if (fileDTS.getText().includes("GraphQLResolveInfo")) { fileDTS.addImportDeclaration({ isTypeOnly: true, moduleSpecifier: "graphql", namedImports: ["GraphQLResolveInfo"], }) } if (fileDTS.getText().includes("RedwoodGraphQLContext")) { fileDTS.addImportDeclaration({ isTypeOnly: true, moduleSpecifier: "@redwoodjs/graphql-server/dist/types", namedImports: ["RedwoodGraphQLContext"], }) } if (sharedInternalGraphQLObjectsReferenced.types.length) { fileDTS.addImportDeclaration({ isTypeOnly: true, moduleSpecifier: `./${settings.sharedInternalFilename.replace(".d.ts", "")}`, namedImports: sharedInternalGraphQLObjectsReferenced.types.map((t) => `${t} as RT${t}`), }) } if (sharedGraphQLObjectsReferencedTypes.length) { fileDTS.addImportDeclaration({ isTypeOnly: true, moduleSpecifier: `./${settings.sharedFilename.replace(".d.ts", "")}`, namedImports: sharedGraphQLObjectsReferencedTypes, }) } serviceFacts.set(fileKey, thisFact) const dtsFilename = filename.endsWith(".ts") ? filename.replace(".ts", ".d.ts") : filename.replace(".js", ".d.ts") const dtsFilepath = context.join(context.pathSettings.typesFolderRoot, dtsFilename) // Some manual formatting tweaks so we align with Redwood's setup more const dts = fileDTS .getText() .replace(`from "graphql";`, `from "graphql";\n`) .replace(`from "@redwoodjs/graphql-server/dist/types";`, `from "@redwoodjs/graphql-server/dist/types";\n`) const shouldWriteDTS = !!dts.trim().length if (!shouldWriteDTS) return const config = getPrettierConfig(dtsFilepath) const formatted = formatDTS(dtsFilepath, dts, config) context.sys.writeFile(dtsFilepath, formatted) return dtsFilepath function addDefinitionsForTopLevelResolvers(parentName: string, config: ResolverFuncFact) { const { name } = config let field = queryType.getFields()[name] if (!field) { field = mutationType.getFields()[name] } const interfaceDeclaration = fileDTS.addInterface({ name: `${capitalizeFirstLetter(config.name)}Resolver`, isExported: true, docs: field.astNode ? ["SDL: " + graphql.print(field.astNode)] : ["@deprecated: Could not find this field in the schema for Mutation or Query"], }) const args = createAndReferOrInlineArgsForField(field, { name: interfaceDeclaration.getName(), file: fileDTS, mapper: externalMapper.map, }) if (parentName === queryType.name) knownSpecialCasesForGraphQL.add(queryType.name) if (parentName === mutationType.name) knownSpecialCasesForGraphQL.add(mutationType.name) const argsParam = args ?? "object" const returnType = returnTypeForResolver(returnTypeMapper, field, config) interfaceDeclaration.addCallSignature({ parameters: [ { name: "args", type: argsParam, hasQuestionToken: config.funcArgCount < 1 }, { name: "obj", type: `{ root: ${parentName}, context: RedwoodGraphQLContext, info: GraphQLResolveInfo }`, hasQuestionToken: config.funcArgCount < 2, }, ], returnType, }) } /** Ideally, we want to be able to write the type for just the object */
function addCustomTypeModel(modelFacts: ModelResolverFacts) {
const modelName = modelFacts.typeName extraPrismaReferences.add(modelName) // Make an interface, this is the version we are replacing from graphql-codegen: // Account: MergePrismaWithSdlTypes<PrismaAccount, MakeRelationsOptional<Account, AllMappedModels>, AllMappedModels>; const gqlType = gql.getType(modelName) if (!gqlType) { // throw new Error(`Could not find a GraphQL type named ${d.getName()}`); fileDTS.addStatements(`\n// ${modelName} does not exist in the schema`) return } if (!graphql.isObjectType(gqlType)) { throw new Error(`In your schema ${modelName} is not an object, which we can only make resolver types for`) } const fields = gqlType.getFields() // See: https://github.com/redwoodjs/redwood/pull/6228#issue-1342966511 // For more ideas const hasGenerics = modelFacts.hasGenericArg // This is what they would have to write const resolverInterface = fileDTS.addInterface({ name: `${modelName}TypeResolvers`, typeParameters: hasGenerics ? ["Extended"] : [], isExported: true, }) // The parent type for the resolvers fileDTS.addTypeAlias({ name: `${modelName}AsParent`, typeParameters: hasGenerics ? ["Extended"] : [], type: `P${modelName} ${createParentAdditionallyDefinedFunctions()} ${hasGenerics ? " & Extended" : ""}`, // docs: ["The prisma model, mixed with fns already defined inside the resolvers."], }) const modelFieldFacts = fieldFacts.get(modelName) ?? {} // Loop through the resolvers, adding the fields which have resolvers implemented in the source file modelFacts.resolvers.forEach((resolver) => { const field = fields[resolver.name] if (field) { const fieldName = resolver.name if (modelFieldFacts[fieldName]) modelFieldFacts[fieldName].hasResolverImplementation = true else modelFieldFacts[fieldName] = { hasResolverImplementation: true } const argsType = inlineArgsForField(field, { mapper: externalMapper.map }) ?? "undefined" const param = hasGenerics ? "<Extended>" : "" const firstQ = resolver.funcArgCount < 1 ? "?" : "" const secondQ = resolver.funcArgCount < 2 ? "?" : "" const innerArgs = `args${firstQ}: ${argsType}, obj${secondQ}: { root: ${modelName}AsParent${param}, context: RedwoodGraphQLContext, info: GraphQLResolveInfo }` const returnType = returnTypeForResolver(returnTypeMapper, field, resolver) const docs = field.astNode ? [`SDL: ${graphql.print(field.astNode)}`] : [] // For speed we should switch this out to addProperties eventually resolverInterface.addProperty({ name: fieldName, leadingTrivia: "\n", docs, type: resolver.isFunc || resolver.isUnknown ? `(${innerArgs}) => ${returnType ?? "any"}` : returnType, }) } else { resolverInterface.addCallSignature({ docs: [` @deprecated: SDL ${modelName}.${resolver.name} does not exist in your schema`], }) } }) function createParentAdditionallyDefinedFunctions() { const fns: string[] = [] modelFacts.resolvers.forEach((resolver) => { const existsInGraphQLSchema = fields[resolver.name] if (!existsInGraphQLSchema) { console.warn( `The service file ${filename} has a field ${resolver.name} on ${modelName} that does not exist in the generated schema.graphql` ) } const prefix = !existsInGraphQLSchema ? "\n// This field does not exist in the generated schema.graphql\n" : "" const returnType = returnTypeForResolver(externalMapper, existsInGraphQLSchema, resolver) // fns.push(`${prefix}${resolver.name}: () => Promise<${externalMapper.map(type, {})}>`) fns.push(`${prefix}${resolver.name}: () => ${returnType}`) }) if (fns.length < 1) return "" return "& {" + fns.join(", \n") + "}" } fieldFacts.set(modelName, modelFieldFacts) } return dtsFilename } function returnTypeForResolver(mapper: TypeMapper, field: graphql.GraphQLField<unknown, unknown> | undefined, resolver: ResolverFuncFact) { if (!field) return "void" const tType = mapper.map(field.type, { preferNullOverUndefined: true, typenamePrefix: "RT" }) ?? "void" let returnType = tType const all = `${tType} | Promise<${tType}> | (() => Promise<${tType}>)` if (resolver.isFunc && resolver.isAsync) returnType = `Promise<${tType}>` else if (resolver.isFunc) returnType = all else if (resolver.isObjLiteral) returnType = tType else if (resolver.isUnknown) returnType = all return returnType }
src/serviceFile.ts
sdl-codegen-sdl-codegen-de2b8aa
[ { "filename": "src/serviceFile.codefacts.ts", "retrieved_chunk": "\t\t\tresolvers: new Map(),\n\t\t\thasGenericArg: false,\n\t\t}\n\t\tfact.resolvers.set(v.getName(), { name: v.getName(), ...facts })\n\t\tfileFact[parent] = fact\n\t})\n\t// Next all the capital consts\n\tresolverContainers.forEach((c) => {\n\t\taddCustomTypeResolvers(c)\n\t})", "score": 0.8266813158988953 }, { "filename": "src/serviceFile.codefacts.ts", "retrieved_chunk": "\treturn fileFact\n\tfunction addCustomTypeResolvers(variableDeclaration: tsMorph.VariableDeclaration) {\n\t\tconst declarations = variableDeclaration.getVariableStatementOrThrow().getDeclarations()\n\t\tdeclarations.forEach((d) => {\n\t\t\tconst name = d.getName()\n\t\t\t// only do it if the first letter is a capital\n\t\t\tif (!name.match(/^[A-Z]/)) return\n\t\t\tconst type = d.getType()\n\t\t\tconst hasGenericArg = type.getText().includes(\"<\")\n\t\t\t// Start making facts about the services", "score": 0.8149218559265137 }, { "filename": "src/serviceFile.codefacts.ts", "retrieved_chunk": "\t\t\tconst fact: ModelResolverFacts = fileFact[name] ?? {\n\t\t\t\ttypeName: name,\n\t\t\t\tresolvers: new Map(),\n\t\t\t\thasGenericArg,\n\t\t\t}\n\t\t\t// Grab the const Thing = { ... }\n\t\t\tconst obj = d.getFirstDescendantByKind(tsMorph.SyntaxKind.ObjectLiteralExpression)\n\t\t\tif (!obj) {\n\t\t\t\tthrow new Error(`Could not find an object literal ( e.g. a { } ) in ${d.getName()}`)\n\t\t\t}", "score": 0.8045927286148071 }, { "filename": "src/typeFacts.ts", "retrieved_chunk": "\thasGenericArg: boolean\n\t/** Individual resolvers found for this model */\n\tresolvers: Map<string, ResolverFuncFact>\n\t/** The name (or lack of) for the GraphQL type which we are mapping */\n\ttypeName: string | \"maybe_query_mutation\"\n}\nexport interface ResolverFuncFact {\n\t/** How many args are defined? */\n\tfuncArgCount: number\n\t/** Is it declared as an async fn */", "score": 0.8002992868423462 }, { "filename": "src/sharedSchema.ts", "retrieved_chunk": "\t\t\t\t\t\thasQuestionToken: true,\n\t\t\t\t\t},\n\t\t\t\t\t...Object.entries(type.getFields()).map(([fieldName, obj]: [string, graphql.GraphQLField<object, object>]) => {\n\t\t\t\t\t\tconst hasResolverImplementation = fieldFacts.get(name)?.[fieldName]?.hasResolverImplementation\n\t\t\t\t\t\tconst isOptionalInSDL = !graphql.isNonNullType(obj.type)\n\t\t\t\t\t\tconst doesNotExistInPrisma = false // !prismaField;\n\t\t\t\t\t\tconst field: tsMorph.OptionalKind<tsMorph.PropertySignatureStructure> = {\n\t\t\t\t\t\t\tname: fieldName,\n\t\t\t\t\t\t\ttype: mapper.map(obj.type, { preferNullOverUndefined: true }),\n\t\t\t\t\t\t\thasQuestionToken: hasResolverImplementation || isOptionalInSDL || doesNotExistInPrisma,", "score": 0.7990460395812988 } ]
typescript
function addCustomTypeModel(modelFacts: ModelResolverFacts) {
import { getSchema as getPrismaSchema } from "@mrleebo/prisma-ast" import * as graphql from "graphql" import { Project } from "ts-morph" import typescript from "typescript" import { AppContext } from "./context.js" import { PrismaMap, prismaModeller } from "./prismaModeller.js" import { lookAtServiceFile } from "./serviceFile.js" import { createSharedSchemaFiles } from "./sharedSchema.js" import { CodeFacts, FieldFacts } from "./typeFacts.js" import { RedwoodPaths } from "./types.js" export * from "./main.js" export * from "./types.js" import { basename, join } from "node:path" /** The API specifically for Redwood */ export function runFullCodegen(preset: "redwood", config: { paths: RedwoodPaths }): { paths: string[] } export function runFullCodegen(preset: string, config: unknown): { paths: string[] } export function runFullCodegen(preset: string, config: unknown): { paths: string[] } { if (preset !== "redwood") throw new Error("Only Redwood codegen is supported at this time") const paths = (config as { paths: RedwoodPaths }).paths const sys = typescript.sys const pathSettings: AppContext["pathSettings"] = { root: paths.base, apiServicesPath: paths.api.services, prismaDSLPath: paths.api.dbSchema, graphQLSchemaPath: paths.generated.schema, sharedFilename: "shared-schema-types.d.ts", sharedInternalFilename: "shared-return-types.d.ts", typesFolderRoot: paths.api.types, } const project = new Project({ useInMemoryFileSystem: true }) let gqlSchema: graphql.GraphQLSchema | undefined const getGraphQLSDLFromFile = (settings: AppContext["pathSettings"]) => { const schema = sys.readFile(settings.graphQLSchemaPath) if (!schema) throw new Error("No schema found at " + settings.graphQLSchemaPath) gqlSchema = graphql.buildSchema(schema) } let prismaSchema: PrismaMap = new Map() const getPrismaSchemaFromFile = (settings: AppContext["pathSettings"]) => { const prismaSchemaText = sys.readFile(settings.prismaDSLPath) if (!prismaSchemaText) throw new Error("No prisma file found at " + settings.prismaDSLPath) const prismaSchemaBlocks = getPrismaSchema(prismaSchemaText) prismaSchema = prismaModeller(prismaSchemaBlocks) } getGraphQLSDLFromFile(pathSettings) getPrismaSchemaFromFile(pathSettings) if (!gqlSchema) throw new Error("No GraphQL Schema was created during setup") const appContext: AppContext = { gql: gqlSchema, prisma: prismaSchema, tsProject: project, codeFacts: new Map<string, CodeFacts>(), fieldFacts: new Map<string, FieldFacts>(), pathSettings, sys, join, basename, } // TODO: Maybe Redwood has an API for this? Its grabbing all the services const serviceFiles = appContext.sys.readDirectory(appContext.pathSettings.apiServicesPath) const serviceFilesToLookAt = serviceFiles.filter((file) => { if (file.endsWith(".test.ts")) return false if (file.endsWith("scenarios.ts")) return false return file.endsWith(".ts") || file.endsWith(".tsx") || file.endsWith(".js") }) const filepaths = [] as string[] // Create the two shared schema files
const sharedDTSes = createSharedSchemaFiles(appContext) filepaths.push(...sharedDTSes) // This needs to go first, as it sets up fieldFacts for (const path of serviceFilesToLookAt) {
const dts = lookAtServiceFile(path, appContext) if (dts) filepaths.push(dts) } return { paths: filepaths, } }
src/index.ts
sdl-codegen-sdl-codegen-de2b8aa
[ { "filename": "src/run.ts", "retrieved_chunk": "\t// This needs to go first, as it sets up fieldFacts\n\tfor (const path of serviceFilesToLookAt) {\n\t\tlookAtServiceFile(path, appContext)\n\t}\n\tcreateSharedSchemaFiles(appContext)\n\t// console.log(`Updated`, typesRoot)\n\tif (config.runESLint) {\n\t\t// console.log(\"Running ESLint...\")\n\t\t// const process = Deno.run({\n\t\t// \tcwd: appRoot,", "score": 0.8814862370491028 }, { "filename": "src/run.ts", "retrieved_chunk": "\t\t\tfor (const subdirEntry of sys.readDirectory(folderPath)) {\n\t\t\t\tconst folderPath = join(appContext.pathSettings.apiServicesPath, dirEntry)\n\t\t\t\tif (\n\t\t\t\t\tsys.fileExists(folderPath) &&\n\t\t\t\t\tsubdirEntry.endsWith(\".ts\") &&\n\t\t\t\t\t!subdirEntry.includes(\".test.ts\") &&\n\t\t\t\t\t!subdirEntry.includes(\"scenarios.ts\")\n\t\t\t\t) {\n\t\t\t\t\tserviceFilesToLookAt.push(join(folderPath, subdirEntry))\n\t\t\t\t}", "score": 0.8626819849014282 }, { "filename": "src/serviceFile.ts", "retrieved_chunk": "import * as graphql from \"graphql\"\nimport { AppContext } from \"./context.js\"\nimport { formatDTS, getPrettierConfig } from \"./formatDTS.js\"\nimport { getCodeFactsForJSTSFileAtPath } from \"./serviceFile.codefacts.js\"\nimport { CodeFacts, ModelResolverFacts, ResolverFuncFact } from \"./typeFacts.js\"\nimport { TypeMapper, typeMapper } from \"./typeMap.js\"\nimport { capitalizeFirstLetter, createAndReferOrInlineArgsForField, inlineArgsForField } from \"./utils.js\"\nexport const lookAtServiceFile = (file: string, context: AppContext) => {\n\tconst { gql, prisma, pathSettings: settings, codeFacts: serviceFacts, fieldFacts } = context\n\t// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition", "score": 0.8608241081237793 }, { "filename": "src/serviceFile.ts", "retrieved_chunk": "\t// The file we'll be creating in-memory throughout this fn\n\tconst fileDTS = context.tsProject.createSourceFile(`source/${fileKey}.d.ts`, \"\", { overwrite: true })\n\t// Basically if a top level resolver reference Query or Mutation\n\tconst knownSpecialCasesForGraphQL = new Set<string>()\n\t// Add the root function declarations\n\tconst rootResolvers = fileFacts.maybe_query_mutation?.resolvers\n\tif (rootResolvers)\n\t\trootResolvers.forEach((v) => {\n\t\t\tconst isQuery = v.name in queryType.getFields()\n\t\t\tconst isMutation = v.name in mutationType.getFields()", "score": 0.8551311492919922 }, { "filename": "src/run.ts", "retrieved_chunk": "\t\tsys,\n\t\tjoin,\n\t\tbasename,\n\t}\n\tconst serviceFilesToLookAt = [] as string[]\n\tfor (const dirEntry of sys.readDirectory(appContext.pathSettings.apiServicesPath)) {\n\t\t// These are generally the folders\n\t\tif (sys.directoryExists(dirEntry)) {\n\t\t\tconst folderPath = join(appContext.pathSettings.apiServicesPath, dirEntry)\n\t\t\t// And these are the files in them", "score": 0.8534879684448242 } ]
typescript
const sharedDTSes = createSharedSchemaFiles(appContext) filepaths.push(...sharedDTSes) // This needs to go first, as it sets up fieldFacts for (const path of serviceFilesToLookAt) {
import * as graphql from "graphql" import { AppContext } from "./context.js" import { formatDTS, getPrettierConfig } from "./formatDTS.js" import { getCodeFactsForJSTSFileAtPath } from "./serviceFile.codefacts.js" import { CodeFacts, ModelResolverFacts, ResolverFuncFact } from "./typeFacts.js" import { TypeMapper, typeMapper } from "./typeMap.js" import { capitalizeFirstLetter, createAndReferOrInlineArgsForField, inlineArgsForField } from "./utils.js" export const lookAtServiceFile = (file: string, context: AppContext) => { const { gql, prisma, pathSettings: settings, codeFacts: serviceFacts, fieldFacts } = context // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition if (!gql) throw new Error(`No schema when wanting to look at service file: ${file}`) if (!prisma) throw new Error(`No prisma schema when wanting to look at service file: ${file}`) // This isn't good enough, needs to be relative to api/src/services const fileKey = file.replace(settings.apiServicesPath, "") const thisFact: CodeFacts = {} const filename = context.basename(file) // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const queryType = gql.getQueryType()! if (!queryType) throw new Error("No query type") // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const mutationType = gql.getMutationType()! // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition if (!mutationType) throw new Error("No mutation type") const externalMapper = typeMapper(context, { preferPrismaModels: true }) const returnTypeMapper = typeMapper(context, {}) // The description of the source file const fileFacts = getCodeFactsForJSTSFileAtPath(file, context) if (Object.keys(fileFacts).length === 0) return // Tracks prospective prisma models which are used in the file const extraPrismaReferences = new Set<string>() // The file we'll be creating in-memory throughout this fn const fileDTS = context.tsProject.createSourceFile(`source/${fileKey}.d.ts`, "", { overwrite: true }) // Basically if a top level resolver reference Query or Mutation const knownSpecialCasesForGraphQL = new Set<string>() // Add the root function declarations const rootResolvers = fileFacts.maybe_query_mutation?.resolvers if (rootResolvers) rootResolvers.forEach((v) => { const isQuery = v.name in queryType.getFields() const isMutation = v.name in mutationType.getFields() const parentName = isQuery ? queryType.name : isMutation ? mutationType.name : undefined if (parentName) { addDefinitionsForTopLevelResolvers(parentName, v) } else { // Add warning about unused resolver fileDTS.addStatements(`\n// ${v.name} does not exist on Query or Mutation`) } }) // Add the root function declarations Object.values(fileFacts).forEach((model) => { if (!model) return const skip = ["maybe_query_mutation", queryType.name, mutationType.name] if (skip.includes(model.typeName)) return addCustomTypeModel(model) }) // Set up the module imports at the top const sharedGraphQLObjectsReferenced = externalMapper.getReferencedGraphQLThingsInMapping() const sharedGraphQLObjectsReferencedTypes = [...sharedGraphQLObjectsReferenced.types, ...knownSpecialCasesForGraphQL] const sharedInternalGraphQLObjectsReferenced = returnTypeMapper.getReferencedGraphQLThingsInMapping() const aliases = [...new Set([...sharedGraphQLObjectsReferenced.scalars, ...sharedInternalGraphQLObjectsReferenced.scalars])] if (aliases.length) { fileDTS.addTypeAliases( aliases.map((s) => ({ name: s, type: "any", })) ) } const prismases = [ ...new Set([ ...sharedGraphQLObjectsReferenced.prisma, ...sharedInternalGraphQLObjectsReferenced.prisma, ...extraPrismaReferences.values(), ]), ] const validPrismaObjs = prismases.filter((p) => prisma.has(p)) if (validPrismaObjs.length) { fileDTS.addImportDeclaration({ isTypeOnly: true, moduleSpecifier: "@prisma/client", namedImports: validPrismaObjs.map((p) => `${p} as P${p}`), }) } if (fileDTS.getText().includes("GraphQLResolveInfo")) { fileDTS.addImportDeclaration({ isTypeOnly: true, moduleSpecifier: "graphql", namedImports: ["GraphQLResolveInfo"], }) } if (fileDTS.getText().includes("RedwoodGraphQLContext")) { fileDTS.addImportDeclaration({ isTypeOnly: true, moduleSpecifier: "@redwoodjs/graphql-server/dist/types", namedImports: ["RedwoodGraphQLContext"], }) } if (sharedInternalGraphQLObjectsReferenced.types.length) { fileDTS.addImportDeclaration({ isTypeOnly: true, moduleSpecifier: `./${settings.sharedInternalFilename.replace(".d.ts", "")}`, namedImports: sharedInternalGraphQLObjectsReferenced.types.map((t) => `${t} as RT${t}`), }) } if (sharedGraphQLObjectsReferencedTypes.length) { fileDTS.addImportDeclaration({ isTypeOnly: true, moduleSpecifier: `./${settings.sharedFilename.replace(".d.ts", "")}`, namedImports: sharedGraphQLObjectsReferencedTypes, }) } serviceFacts.set(fileKey, thisFact) const dtsFilename = filename.endsWith(".ts") ? filename.replace(".ts", ".d.ts") : filename.replace(".js", ".d.ts") const dtsFilepath = context.join(context.pathSettings.typesFolderRoot, dtsFilename) // Some manual formatting tweaks so we align with Redwood's setup more const dts = fileDTS .getText() .replace(`from "graphql";`, `from "graphql";\n`) .replace(`from "@redwoodjs/graphql-server/dist/types";`, `from "@redwoodjs/graphql-server/dist/types";\n`) const shouldWriteDTS = !!dts.trim().length if (!shouldWriteDTS) return const config = getPrettierConfig(dtsFilepath) const formatted = formatDTS(dtsFilepath, dts, config) context.sys.writeFile(dtsFilepath, formatted) return dtsFilepath function addDefinitionsForTopLevelResolvers(parentName: string, config: ResolverFuncFact) { const { name } = config let field = queryType.getFields()[name] if (!field) { field = mutationType.getFields()[name] } const interfaceDeclaration = fileDTS.addInterface({ name: `${capitalizeFirstLetter(config.name)}Resolver`, isExported: true, docs: field.astNode ? ["SDL: " + graphql.print(field.astNode)] : ["@deprecated: Could not find this field in the schema for Mutation or Query"], }) const args = createAndReferOrInlineArgsForField(field, { name: interfaceDeclaration.getName(), file: fileDTS, mapper: externalMapper.map, }) if (parentName === queryType.name) knownSpecialCasesForGraphQL.add(queryType.name) if (parentName === mutationType.name) knownSpecialCasesForGraphQL.add(mutationType.name) const argsParam = args ?? "object" const returnType = returnTypeForResolver(returnTypeMapper, field, config) interfaceDeclaration.addCallSignature({ parameters: [ { name: "args", type: argsParam, hasQuestionToken: config.funcArgCount < 1 }, { name: "obj", type: `{ root: ${parentName}, context: RedwoodGraphQLContext, info: GraphQLResolveInfo }`, hasQuestionToken: config.funcArgCount < 2, }, ], returnType, }) } /** Ideally, we want to be able to write the type for just the object */ function addCustomTypeModel(modelFacts: ModelResolverFacts) { const modelName = modelFacts.typeName extraPrismaReferences.add(modelName) // Make an interface, this is the version we are replacing from graphql-codegen: // Account: MergePrismaWithSdlTypes<PrismaAccount, MakeRelationsOptional<Account, AllMappedModels>, AllMappedModels>; const gqlType = gql.getType(modelName) if (!gqlType) { // throw new Error(`Could not find a GraphQL type named ${d.getName()}`); fileDTS.addStatements(`\n// ${modelName} does not exist in the schema`) return } if (!graphql.isObjectType(gqlType)) { throw new Error(`In your schema ${modelName} is not an object, which we can only make resolver types for`) } const fields = gqlType.getFields() // See: https://github.com/redwoodjs/redwood/pull/6228#issue-1342966511 // For more ideas const hasGenerics = modelFacts.hasGenericArg // This is what they would have to write const resolverInterface = fileDTS.addInterface({ name: `${modelName}TypeResolvers`, typeParameters: hasGenerics ? ["Extended"] : [], isExported: true, }) // The parent type for the resolvers fileDTS.addTypeAlias({ name: `${modelName}AsParent`, typeParameters: hasGenerics ? ["Extended"] : [], type: `P${modelName} ${createParentAdditionallyDefinedFunctions()} ${hasGenerics ? " & Extended" : ""}`, // docs: ["The prisma model, mixed with fns already defined inside the resolvers."], }) const modelFieldFacts = fieldFacts.get(modelName) ?? {} // Loop through the resolvers, adding the fields which have resolvers implemented in the source file modelFacts.resolvers.forEach((resolver) => { const field = fields[resolver.name] if (field) { const fieldName = resolver.name if (modelFieldFacts[fieldName]) modelFieldFacts[fieldName].hasResolverImplementation = true else modelFieldFacts[fieldName] = { hasResolverImplementation: true } const argsType = inlineArgsForField(field, { mapper: externalMapper.map }) ?? "undefined" const param = hasGenerics ? "<Extended>" : "" const firstQ = resolver.funcArgCount < 1 ? "?" : "" const secondQ = resolver.funcArgCount < 2 ? "?" : "" const innerArgs = `args${firstQ}: ${argsType}, obj${secondQ}: { root: ${modelName}AsParent${param}, context: RedwoodGraphQLContext, info: GraphQLResolveInfo }` const returnType = returnTypeForResolver(returnTypeMapper, field, resolver) const docs = field.astNode ? [`SDL: ${graphql.print(field.astNode)}`] : [] // For speed we should switch this out to addProperties eventually resolverInterface.addProperty({ name: fieldName, leadingTrivia: "\n", docs, type: resolver.isFunc || resolver.isUnknown ? `(${innerArgs}) => ${returnType ?? "any"}` : returnType, }) } else { resolverInterface.addCallSignature({ docs: [` @deprecated: SDL ${modelName}.${resolver.name} does not exist in your schema`], }) } }) function createParentAdditionallyDefinedFunctions() { const fns: string[] = [] modelFacts.resolvers.forEach((resolver) => { const existsInGraphQLSchema = fields[resolver.name] if (!existsInGraphQLSchema) { console.warn( `The service file ${filename} has a field ${resolver.name} on ${modelName} that does not exist in the generated schema.graphql` ) } const prefix = !existsInGraphQLSchema ? "\n// This field does not exist in the generated schema.graphql\n" : "" const returnType = returnTypeForResolver(externalMapper, existsInGraphQLSchema, resolver) // fns.push(`${prefix}${resolver.name}: () => Promise<${externalMapper.map(type, {})}>`) fns.push(`${prefix}${resolver.name}: () => ${returnType}`) }) if (fns.length < 1) return "" return "& {" + fns.join(", \n") + "}" } fieldFacts.set(modelName, modelFieldFacts) } return dtsFilename }
function returnTypeForResolver(mapper: TypeMapper, field: graphql.GraphQLField<unknown, unknown> | undefined, resolver: ResolverFuncFact) {
if (!field) return "void" const tType = mapper.map(field.type, { preferNullOverUndefined: true, typenamePrefix: "RT" }) ?? "void" let returnType = tType const all = `${tType} | Promise<${tType}> | (() => Promise<${tType}>)` if (resolver.isFunc && resolver.isAsync) returnType = `Promise<${tType}>` else if (resolver.isFunc) returnType = all else if (resolver.isObjLiteral) returnType = tType else if (resolver.isUnknown) returnType = all return returnType }
src/serviceFile.ts
sdl-codegen-sdl-codegen-de2b8aa
[ { "filename": "src/serviceFile.codefacts.ts", "retrieved_chunk": "\treturn fileFact\n\tfunction addCustomTypeResolvers(variableDeclaration: tsMorph.VariableDeclaration) {\n\t\tconst declarations = variableDeclaration.getVariableStatementOrThrow().getDeclarations()\n\t\tdeclarations.forEach((d) => {\n\t\t\tconst name = d.getName()\n\t\t\t// only do it if the first letter is a capital\n\t\t\tif (!name.match(/^[A-Z]/)) return\n\t\t\tconst type = d.getType()\n\t\t\tconst hasGenericArg = type.getText().includes(\"<\")\n\t\t\t// Start making facts about the services", "score": 0.8231444358825684 }, { "filename": "src/sharedSchema.ts", "retrieved_chunk": "\t\t\t\t\t\tconst docs = []\n\t\t\t\t\t\tconst prismaField = pType?.properties.get(fieldName)\n\t\t\t\t\t\tconst type = obj.type as graphql.GraphQLType\n\t\t\t\t\t\tif (prismaField?.leadingComments.length) {\n\t\t\t\t\t\t\tdocs.push(prismaField.leadingComments.trim())\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// if (obj.description) docs.push(obj.description);\n\t\t\t\t\t\tconst hasResolverImplementation = fieldFacts.get(name)?.[fieldName]?.hasResolverImplementation\n\t\t\t\t\t\tconst isOptionalInSDL = !graphql.isNonNullType(type)\n\t\t\t\t\t\tconst doesNotExistInPrisma = false // !prismaField;", "score": 0.8179445862770081 }, { "filename": "src/serviceFile.codefacts.ts", "retrieved_chunk": "\t\t\tconst fact: ModelResolverFacts = fileFact[name] ?? {\n\t\t\t\ttypeName: name,\n\t\t\t\tresolvers: new Map(),\n\t\t\t\thasGenericArg,\n\t\t\t}\n\t\t\t// Grab the const Thing = { ... }\n\t\t\tconst obj = d.getFirstDescendantByKind(tsMorph.SyntaxKind.ObjectLiteralExpression)\n\t\t\tif (!obj) {\n\t\t\t\tthrow new Error(`Could not find an object literal ( e.g. a { } ) in ${d.getName()}`)\n\t\t\t}", "score": 0.8173961639404297 }, { "filename": "src/sharedSchema.ts", "retrieved_chunk": "\t\t\t\t\t\tconst field: tsMorph.OptionalKind<tsMorph.PropertySignatureStructure> = {\n\t\t\t\t\t\t\tname: fieldName,\n\t\t\t\t\t\t\ttype: mapper.map(type, { preferNullOverUndefined: true }),\n\t\t\t\t\t\t\tdocs,\n\t\t\t\t\t\t\thasQuestionToken: hasResolverImplementation ?? (isOptionalInSDL || doesNotExistInPrisma),\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn field\n\t\t\t\t\t}),\n\t\t\t\t],\n\t\t\t})", "score": 0.8126880526542664 }, { "filename": "src/typeFacts.ts", "retrieved_chunk": "export type FieldFacts = Record<string, FieldFact>\nexport interface FieldFact {\n\thasResolverImplementation?: true\n\t// isPrismaBacked?: true;\n}\n// The data-model for the service file which contains the SDL matched functions\n/** A representation of the code inside the source file's */\nexport type CodeFacts = Record<string, ModelResolverFacts | undefined>\nexport interface ModelResolverFacts {\n\t/** Should we type the type as a generic with an override */", "score": 0.812562108039856 } ]
typescript
function returnTypeForResolver(mapper: TypeMapper, field: graphql.GraphQLField<unknown, unknown> | undefined, resolver: ResolverFuncFact) {
/// The main schema for objects and inputs import * as graphql from "graphql" import * as tsMorph from "ts-morph" import { AppContext } from "./context.js" import { formatDTS, getPrettierConfig } from "./formatDTS.js" import { typeMapper } from "./typeMap.js" export const createSharedSchemaFiles = (context: AppContext) => { createSharedExternalSchemaFile(context) createSharedReturnPositionSchemaFile(context) return [ context.join(context.pathSettings.typesFolderRoot, context.pathSettings.sharedFilename), context.join(context.pathSettings.typesFolderRoot, context.pathSettings.sharedInternalFilename), ] } function createSharedExternalSchemaFile(context: AppContext) { const gql = context.gql const types = gql.getTypeMap() const knownPrimitives = ["String", "Boolean", "Int"] const { prisma, fieldFacts } = context const mapper = typeMapper(context, {}) const externalTSFile = context.tsProject.createSourceFile(`/source/${context.pathSettings.sharedFilename}`, "") Object.keys(types).forEach((name) => { if (name.startsWith("__")) { return } if (knownPrimitives.includes(name)) { return } const type = types[name] const pType = prisma.get(name) if (graphql.isObjectType(type) || graphql.isInterfaceType(type) || graphql.isInputObjectType(type)) { // This is slower than it could be, use the add many at once api const docs = [] if (pType?.leadingComments) { docs.push(pType.leadingComments) } if (type.description) { docs.push(type.description) } externalTSFile.addInterface({ name: type.name, isExported: true, docs: [], properties: [ { name: "__typename", type: `"${type.name}"`, hasQuestionToken: true, }, ...Object.entries(type.getFields()).map(([fieldName, obj]: [string, graphql.GraphQLField<object, object>]) => { const docs = [] const prismaField = pType?.properties.get(fieldName) const type = obj.type as graphql.GraphQLType if (prismaField?.leadingComments.length) { docs.push(prismaField.leadingComments.trim()) } // if (obj.description) docs.push(obj.description); const hasResolverImplementation = fieldFacts.get(name)?.[fieldName]?.hasResolverImplementation const isOptionalInSDL = !graphql.isNonNullType(type) const doesNotExistInPrisma = false // !prismaField; const field: tsMorph.OptionalKind<tsMorph.PropertySignatureStructure> = { name: fieldName, type: mapper.map(type, { preferNullOverUndefined: true }), docs, hasQuestionToken: hasResolverImplementation ?? (isOptionalInSDL || doesNotExistInPrisma), } return field }), ], }) } if (graphql.isEnumType(type)) { externalTSFile.addTypeAlias({ name: type.name, type: '"' + type .getValues() .map((m) => (m as { value: string }).value) .join('" | "') + '"', }) } }) const { scalars } = mapper.getReferencedGraphQLThingsInMapping() if (scalars.length) { externalTSFile.addTypeAliases(
scalars.map((s) => ({
name: s, type: "any", })) ) } const fullPath = context.join(context.pathSettings.typesFolderRoot, context.pathSettings.sharedFilename) const config = getPrettierConfig(fullPath) const formatted = formatDTS(fullPath, externalTSFile.getText(), config) context.sys.writeFile(fullPath, formatted) } function createSharedReturnPositionSchemaFile(context: AppContext) { const { gql, prisma, fieldFacts } = context const types = gql.getTypeMap() const mapper = typeMapper(context, { preferPrismaModels: true }) const typesToImport = [] as string[] const knownPrimitives = ["String", "Boolean", "Int"] const externalTSFile = context.tsProject.createSourceFile( `/source/${context.pathSettings.sharedInternalFilename}`, ` // You may very reasonably ask yourself, 'what is this file?' and why do I need it. // Roughly, this file ensures that when a resolver wants to return a type - that // type will match a prisma model. This is useful because you can trivially extend // the type in the SDL and not have to worry about type mis-matches because the thing // you returned does not include those functions. // This gets particularly valuable when you want to return a union type, an interface, // or a model where the prisma model is nested pretty deeply (GraphQL connections, for example.) ` ) Object.keys(types).forEach((name) => { if (name.startsWith("__")) { return } if (knownPrimitives.includes(name)) { return } const type = types[name] const pType = prisma.get(name) if (graphql.isObjectType(type) || graphql.isInterfaceType(type) || graphql.isInputObjectType(type)) { // Return straight away if we have a matching type in the prisma schema // as we dont need it if (pType) { typesToImport.push(name) return } externalTSFile.addInterface({ name: type.name, isExported: true, docs: [], properties: [ { name: "__typename", type: `"${type.name}"`, hasQuestionToken: true, }, ...Object.entries(type.getFields()).map(([fieldName, obj]: [string, graphql.GraphQLField<object, object>]) => { const hasResolverImplementation = fieldFacts.get(name)?.[fieldName]?.hasResolverImplementation const isOptionalInSDL = !graphql.isNonNullType(obj.type) const doesNotExistInPrisma = false // !prismaField; const field: tsMorph.OptionalKind<tsMorph.PropertySignatureStructure> = { name: fieldName, type: mapper.map(obj.type, { preferNullOverUndefined: true }), hasQuestionToken: hasResolverImplementation || isOptionalInSDL || doesNotExistInPrisma, } return field }), ], }) } if (graphql.isEnumType(type)) { externalTSFile.addTypeAlias({ name: type.name, type: '"' + type .getValues() .map((m) => (m as { value: string }).value) .join('" | "') + '"', }) } }) const { scalars, prisma: prismaModels } = mapper.getReferencedGraphQLThingsInMapping() if (scalars.length) { externalTSFile.addTypeAliases( scalars.map((s) => ({ name: s, type: "any", })) ) } const allPrismaModels = [...new Set([...prismaModels, ...typesToImport])].sort() if (allPrismaModels.length) { externalTSFile.addImportDeclaration({ isTypeOnly: true, moduleSpecifier: `@prisma/client`, namedImports: allPrismaModels.map((p) => `${p} as P${p}`), }) allPrismaModels.forEach((p) => { externalTSFile.addTypeAlias({ isExported: true, name: p, type: `P${p}`, }) }) } const fullPath = context.join(context.pathSettings.typesFolderRoot, context.pathSettings.sharedInternalFilename) const config = getPrettierConfig(fullPath) const formatted = formatDTS(fullPath, externalTSFile.getText(), config) context.sys.writeFile(fullPath, formatted) }
src/sharedSchema.ts
sdl-codegen-sdl-codegen-de2b8aa
[ { "filename": "src/serviceFile.ts", "retrieved_chunk": "\tif (aliases.length) {\n\t\tfileDTS.addTypeAliases(\n\t\t\taliases.map((s) => ({\n\t\t\t\tname: s,\n\t\t\t\ttype: \"any\",\n\t\t\t}))\n\t\t)\n\t}\n\tconst prismases = [\n\t\t...new Set([", "score": 0.8462779521942139 }, { "filename": "src/serviceFile.ts", "retrieved_chunk": "\t\t\tfile: fileDTS,\n\t\t\tmapper: externalMapper.map,\n\t\t})\n\t\tif (parentName === queryType.name) knownSpecialCasesForGraphQL.add(queryType.name)\n\t\tif (parentName === mutationType.name) knownSpecialCasesForGraphQL.add(mutationType.name)\n\t\tconst argsParam = args ?? \"object\"\n\t\tconst returnType = returnTypeForResolver(returnTypeMapper, field, config)\n\t\tinterfaceDeclaration.addCallSignature({\n\t\t\tparameters: [\n\t\t\t\t{ name: \"args\", type: argsParam, hasQuestionToken: config.funcArgCount < 1 },", "score": 0.8259633183479309 }, { "filename": "src/serviceFile.ts", "retrieved_chunk": "\t\tif (!model) return\n\t\tconst skip = [\"maybe_query_mutation\", queryType.name, mutationType.name]\n\t\tif (skip.includes(model.typeName)) return\n\t\taddCustomTypeModel(model)\n\t})\n\t// Set up the module imports at the top\n\tconst sharedGraphQLObjectsReferenced = externalMapper.getReferencedGraphQLThingsInMapping()\n\tconst sharedGraphQLObjectsReferencedTypes = [...sharedGraphQLObjectsReferenced.types, ...knownSpecialCasesForGraphQL]\n\tconst sharedInternalGraphQLObjectsReferenced = returnTypeMapper.getReferencedGraphQLThingsInMapping()\n\tconst aliases = [...new Set([...sharedGraphQLObjectsReferenced.scalars, ...sharedInternalGraphQLObjectsReferenced.scalars])]", "score": 0.8189529180526733 }, { "filename": "src/serviceFile.ts", "retrieved_chunk": "\t\t\tmoduleSpecifier: `./${settings.sharedInternalFilename.replace(\".d.ts\", \"\")}`,\n\t\t\tnamedImports: sharedInternalGraphQLObjectsReferenced.types.map((t) => `${t} as RT${t}`),\n\t\t})\n\t}\n\tif (sharedGraphQLObjectsReferencedTypes.length) {\n\t\tfileDTS.addImportDeclaration({\n\t\t\tisTypeOnly: true,\n\t\t\tmoduleSpecifier: `./${settings.sharedFilename.replace(\".d.ts\", \"\")}`,\n\t\t\tnamedImports: sharedGraphQLObjectsReferencedTypes,\n\t\t})", "score": 0.8186004161834717 }, { "filename": "src/serviceFile.ts", "retrieved_chunk": "\tconst mutationType = gql.getMutationType()!\n\t// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n\tif (!mutationType) throw new Error(\"No mutation type\")\n\tconst externalMapper = typeMapper(context, { preferPrismaModels: true })\n\tconst returnTypeMapper = typeMapper(context, {})\n\t// The description of the source file\n\tconst fileFacts = getCodeFactsForJSTSFileAtPath(file, context)\n\tif (Object.keys(fileFacts).length === 0) return\n\t// Tracks prospective prisma models which are used in the file\n\tconst extraPrismaReferences = new Set<string>()", "score": 0.8162380456924438 } ]
typescript
scalars.map((s) => ({
import * as graphql from "graphql" import { AppContext } from "./context.js" import { formatDTS, getPrettierConfig } from "./formatDTS.js" import { getCodeFactsForJSTSFileAtPath } from "./serviceFile.codefacts.js" import { CodeFacts, ModelResolverFacts, ResolverFuncFact } from "./typeFacts.js" import { TypeMapper, typeMapper } from "./typeMap.js" import { capitalizeFirstLetter, createAndReferOrInlineArgsForField, inlineArgsForField } from "./utils.js" export const lookAtServiceFile = (file: string, context: AppContext) => { const { gql, prisma, pathSettings: settings, codeFacts: serviceFacts, fieldFacts } = context // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition if (!gql) throw new Error(`No schema when wanting to look at service file: ${file}`) if (!prisma) throw new Error(`No prisma schema when wanting to look at service file: ${file}`) // This isn't good enough, needs to be relative to api/src/services const fileKey = file.replace(settings.apiServicesPath, "") const thisFact: CodeFacts = {} const filename = context.basename(file) // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const queryType = gql.getQueryType()! if (!queryType) throw new Error("No query type") // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const mutationType = gql.getMutationType()! // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition if (!mutationType) throw new Error("No mutation type") const externalMapper = typeMapper(context, { preferPrismaModels: true }) const returnTypeMapper = typeMapper(context, {}) // The description of the source file const fileFacts = getCodeFactsForJSTSFileAtPath(file, context) if (Object.keys(fileFacts).length === 0) return // Tracks prospective prisma models which are used in the file const extraPrismaReferences = new Set<string>() // The file we'll be creating in-memory throughout this fn const fileDTS = context.tsProject.createSourceFile(`source/${fileKey}.d.ts`, "", { overwrite: true }) // Basically if a top level resolver reference Query or Mutation const knownSpecialCasesForGraphQL = new Set<string>() // Add the root function declarations const rootResolvers = fileFacts.maybe_query_mutation?.resolvers if (rootResolvers) rootResolvers.forEach((v) => { const isQuery = v.name in queryType.getFields() const isMutation = v.name in mutationType.getFields() const parentName = isQuery ? queryType.name : isMutation ? mutationType.name : undefined if (parentName) { addDefinitionsForTopLevelResolvers(parentName, v) } else { // Add warning about unused resolver fileDTS.addStatements(`\n// ${v.name} does not exist on Query or Mutation`) } }) // Add the root function declarations Object.values(fileFacts).forEach((model) => { if (!model) return const skip = ["maybe_query_mutation", queryType.name, mutationType.name] if (skip.includes(model.typeName)) return addCustomTypeModel(model) }) // Set up the module imports at the top const sharedGraphQLObjectsReferenced = externalMapper.getReferencedGraphQLThingsInMapping() const sharedGraphQLObjectsReferencedTypes = [...sharedGraphQLObjectsReferenced.types, ...knownSpecialCasesForGraphQL] const sharedInternalGraphQLObjectsReferenced = returnTypeMapper.getReferencedGraphQLThingsInMapping() const aliases = [...new Set([...sharedGraphQLObjectsReferenced.scalars, ...sharedInternalGraphQLObjectsReferenced.scalars])] if (aliases.length) { fileDTS.addTypeAliases( aliases.map((s) => ({ name: s, type: "any", })) ) } const prismases = [ ...new Set([ ...sharedGraphQLObjectsReferenced.prisma, ...sharedInternalGraphQLObjectsReferenced.prisma, ...extraPrismaReferences.values(), ]), ] const validPrismaObjs = prismases.filter((p) => prisma.has(p)) if (validPrismaObjs.length) { fileDTS.addImportDeclaration({ isTypeOnly: true, moduleSpecifier: "@prisma/client", namedImports: validPrismaObjs.map((p) => `${p} as P${p}`), }) } if (fileDTS.getText().includes("GraphQLResolveInfo")) { fileDTS.addImportDeclaration({ isTypeOnly: true, moduleSpecifier: "graphql", namedImports: ["GraphQLResolveInfo"], }) } if (fileDTS.getText().includes("RedwoodGraphQLContext")) { fileDTS.addImportDeclaration({ isTypeOnly: true, moduleSpecifier: "@redwoodjs/graphql-server/dist/types", namedImports: ["RedwoodGraphQLContext"], }) } if (sharedInternalGraphQLObjectsReferenced.types.length) { fileDTS.addImportDeclaration({ isTypeOnly: true, moduleSpecifier: `./${settings.sharedInternalFilename.replace(".d.ts", "")}`,
namedImports: sharedInternalGraphQLObjectsReferenced.types.map((t) => `${t} as RT${t}`), }) }
if (sharedGraphQLObjectsReferencedTypes.length) { fileDTS.addImportDeclaration({ isTypeOnly: true, moduleSpecifier: `./${settings.sharedFilename.replace(".d.ts", "")}`, namedImports: sharedGraphQLObjectsReferencedTypes, }) } serviceFacts.set(fileKey, thisFact) const dtsFilename = filename.endsWith(".ts") ? filename.replace(".ts", ".d.ts") : filename.replace(".js", ".d.ts") const dtsFilepath = context.join(context.pathSettings.typesFolderRoot, dtsFilename) // Some manual formatting tweaks so we align with Redwood's setup more const dts = fileDTS .getText() .replace(`from "graphql";`, `from "graphql";\n`) .replace(`from "@redwoodjs/graphql-server/dist/types";`, `from "@redwoodjs/graphql-server/dist/types";\n`) const shouldWriteDTS = !!dts.trim().length if (!shouldWriteDTS) return const config = getPrettierConfig(dtsFilepath) const formatted = formatDTS(dtsFilepath, dts, config) context.sys.writeFile(dtsFilepath, formatted) return dtsFilepath function addDefinitionsForTopLevelResolvers(parentName: string, config: ResolverFuncFact) { const { name } = config let field = queryType.getFields()[name] if (!field) { field = mutationType.getFields()[name] } const interfaceDeclaration = fileDTS.addInterface({ name: `${capitalizeFirstLetter(config.name)}Resolver`, isExported: true, docs: field.astNode ? ["SDL: " + graphql.print(field.astNode)] : ["@deprecated: Could not find this field in the schema for Mutation or Query"], }) const args = createAndReferOrInlineArgsForField(field, { name: interfaceDeclaration.getName(), file: fileDTS, mapper: externalMapper.map, }) if (parentName === queryType.name) knownSpecialCasesForGraphQL.add(queryType.name) if (parentName === mutationType.name) knownSpecialCasesForGraphQL.add(mutationType.name) const argsParam = args ?? "object" const returnType = returnTypeForResolver(returnTypeMapper, field, config) interfaceDeclaration.addCallSignature({ parameters: [ { name: "args", type: argsParam, hasQuestionToken: config.funcArgCount < 1 }, { name: "obj", type: `{ root: ${parentName}, context: RedwoodGraphQLContext, info: GraphQLResolveInfo }`, hasQuestionToken: config.funcArgCount < 2, }, ], returnType, }) } /** Ideally, we want to be able to write the type for just the object */ function addCustomTypeModel(modelFacts: ModelResolverFacts) { const modelName = modelFacts.typeName extraPrismaReferences.add(modelName) // Make an interface, this is the version we are replacing from graphql-codegen: // Account: MergePrismaWithSdlTypes<PrismaAccount, MakeRelationsOptional<Account, AllMappedModels>, AllMappedModels>; const gqlType = gql.getType(modelName) if (!gqlType) { // throw new Error(`Could not find a GraphQL type named ${d.getName()}`); fileDTS.addStatements(`\n// ${modelName} does not exist in the schema`) return } if (!graphql.isObjectType(gqlType)) { throw new Error(`In your schema ${modelName} is not an object, which we can only make resolver types for`) } const fields = gqlType.getFields() // See: https://github.com/redwoodjs/redwood/pull/6228#issue-1342966511 // For more ideas const hasGenerics = modelFacts.hasGenericArg // This is what they would have to write const resolverInterface = fileDTS.addInterface({ name: `${modelName}TypeResolvers`, typeParameters: hasGenerics ? ["Extended"] : [], isExported: true, }) // The parent type for the resolvers fileDTS.addTypeAlias({ name: `${modelName}AsParent`, typeParameters: hasGenerics ? ["Extended"] : [], type: `P${modelName} ${createParentAdditionallyDefinedFunctions()} ${hasGenerics ? " & Extended" : ""}`, // docs: ["The prisma model, mixed with fns already defined inside the resolvers."], }) const modelFieldFacts = fieldFacts.get(modelName) ?? {} // Loop through the resolvers, adding the fields which have resolvers implemented in the source file modelFacts.resolvers.forEach((resolver) => { const field = fields[resolver.name] if (field) { const fieldName = resolver.name if (modelFieldFacts[fieldName]) modelFieldFacts[fieldName].hasResolverImplementation = true else modelFieldFacts[fieldName] = { hasResolverImplementation: true } const argsType = inlineArgsForField(field, { mapper: externalMapper.map }) ?? "undefined" const param = hasGenerics ? "<Extended>" : "" const firstQ = resolver.funcArgCount < 1 ? "?" : "" const secondQ = resolver.funcArgCount < 2 ? "?" : "" const innerArgs = `args${firstQ}: ${argsType}, obj${secondQ}: { root: ${modelName}AsParent${param}, context: RedwoodGraphQLContext, info: GraphQLResolveInfo }` const returnType = returnTypeForResolver(returnTypeMapper, field, resolver) const docs = field.astNode ? [`SDL: ${graphql.print(field.astNode)}`] : [] // For speed we should switch this out to addProperties eventually resolverInterface.addProperty({ name: fieldName, leadingTrivia: "\n", docs, type: resolver.isFunc || resolver.isUnknown ? `(${innerArgs}) => ${returnType ?? "any"}` : returnType, }) } else { resolverInterface.addCallSignature({ docs: [` @deprecated: SDL ${modelName}.${resolver.name} does not exist in your schema`], }) } }) function createParentAdditionallyDefinedFunctions() { const fns: string[] = [] modelFacts.resolvers.forEach((resolver) => { const existsInGraphQLSchema = fields[resolver.name] if (!existsInGraphQLSchema) { console.warn( `The service file ${filename} has a field ${resolver.name} on ${modelName} that does not exist in the generated schema.graphql` ) } const prefix = !existsInGraphQLSchema ? "\n// This field does not exist in the generated schema.graphql\n" : "" const returnType = returnTypeForResolver(externalMapper, existsInGraphQLSchema, resolver) // fns.push(`${prefix}${resolver.name}: () => Promise<${externalMapper.map(type, {})}>`) fns.push(`${prefix}${resolver.name}: () => ${returnType}`) }) if (fns.length < 1) return "" return "& {" + fns.join(", \n") + "}" } fieldFacts.set(modelName, modelFieldFacts) } return dtsFilename } function returnTypeForResolver(mapper: TypeMapper, field: graphql.GraphQLField<unknown, unknown> | undefined, resolver: ResolverFuncFact) { if (!field) return "void" const tType = mapper.map(field.type, { preferNullOverUndefined: true, typenamePrefix: "RT" }) ?? "void" let returnType = tType const all = `${tType} | Promise<${tType}> | (() => Promise<${tType}>)` if (resolver.isFunc && resolver.isAsync) returnType = `Promise<${tType}>` else if (resolver.isFunc) returnType = all else if (resolver.isObjLiteral) returnType = tType else if (resolver.isUnknown) returnType = all return returnType }
src/serviceFile.ts
sdl-codegen-sdl-codegen-de2b8aa
[ { "filename": "src/sharedSchema.ts", "retrieved_chunk": "\tconst externalTSFile = context.tsProject.createSourceFile(`/source/${context.pathSettings.sharedFilename}`, \"\")\n\tObject.keys(types).forEach((name) => {\n\t\tif (name.startsWith(\"__\")) {\n\t\t\treturn\n\t\t}\n\t\tif (knownPrimitives.includes(name)) {\n\t\t\treturn\n\t\t}\n\t\tconst type = types[name]\n\t\tconst pType = prisma.get(name)", "score": 0.8589558601379395 }, { "filename": "src/sharedSchema.ts", "retrieved_chunk": "\tconst types = gql.getTypeMap()\n\tconst mapper = typeMapper(context, { preferPrismaModels: true })\n\tconst typesToImport = [] as string[]\n\tconst knownPrimitives = [\"String\", \"Boolean\", \"Int\"]\n\tconst externalTSFile = context.tsProject.createSourceFile(\n\t\t`/source/${context.pathSettings.sharedInternalFilename}`,\n\t\t`\n// You may very reasonably ask yourself, 'what is this file?' and why do I need it.\n// Roughly, this file ensures that when a resolver wants to return a type - that\n// type will match a prisma model. This is useful because you can trivially extend", "score": 0.851163387298584 }, { "filename": "src/sharedSchema.ts", "retrieved_chunk": "\t\texternalTSFile.addImportDeclaration({\n\t\t\tisTypeOnly: true,\n\t\t\tmoduleSpecifier: `@prisma/client`,\n\t\t\tnamedImports: allPrismaModels.map((p) => `${p} as P${p}`),\n\t\t})\n\t\tallPrismaModels.forEach((p) => {\n\t\t\texternalTSFile.addTypeAlias({\n\t\t\t\tisExported: true,\n\t\t\t\tname: p,\n\t\t\t\ttype: `P${p}`,", "score": 0.8446411490440369 }, { "filename": "src/sharedSchema.ts", "retrieved_chunk": "\tif (scalars.length) {\n\t\texternalTSFile.addTypeAliases(\n\t\t\tscalars.map((s) => ({\n\t\t\t\tname: s,\n\t\t\t\ttype: \"any\",\n\t\t\t}))\n\t\t)\n\t}\n\tconst allPrismaModels = [...new Set([...prismaModels, ...typesToImport])].sort()\n\tif (allPrismaModels.length) {", "score": 0.8367199897766113 }, { "filename": "src/sharedSchema.ts", "retrieved_chunk": "\t\t\t\treturn\n\t\t\t}\n\t\t\texternalTSFile.addInterface({\n\t\t\t\tname: type.name,\n\t\t\t\tisExported: true,\n\t\t\t\tdocs: [],\n\t\t\t\tproperties: [\n\t\t\t\t\t{\n\t\t\t\t\t\tname: \"__typename\",\n\t\t\t\t\t\ttype: `\"${type.name}\"`,", "score": 0.8347048759460449 } ]
typescript
namedImports: sharedInternalGraphQLObjectsReferenced.types.map((t) => `${t} as RT${t}`), }) }
import { useForm } from 'react-hook-form'; import { z } from 'zod'; import { zodResolver } from '@hookform/resolvers/zod'; import { type StytchAuthMethods } from '~/types/stytch'; import { trpc } from '~/utils/trpc'; import { VerifyOtp } from './VerifyOtp'; import { Button } from './Button'; import { Input } from './Input'; const formSchema = z.object({ email: z.string().email('Invalid email address').min(1, 'Email address is required'), }); type FormSchemaType = z.infer<typeof formSchema>; export function LoginEmail(props: { onSwitchMethod: (method: StytchAuthMethods) => void }) { const { data, mutateAsync } = trpc.auth.loginEmail.useMutation(); const { handleSubmit, register, getValues, setError, formState: { errors, isSubmitting }, } = useForm<FormSchemaType>({ resolver: zodResolver(formSchema), }); if (data?.methodId) { return <VerifyOtp methodValue={getValues('email')} methodId={data.methodId} />; } return ( <form className='flex w-full flex-col gap-y-4 rounded bg-white p-8 text-center shadow-sm border-[#adbcc5] border-[1px]' onSubmit={handleSubmit((values) => mutateAsync({ email: values.email }).catch((err) => { setError('root', { message: err.message }); }), )} > <h1 className='text-3xl font-semibold text-[#19303d]'>Stytch + T3 example</h1> <div> <Input aria-label='Email' placeholder='example@email.com' type='email' autoCapitalize='off' autoCorrect='off' spellCheck='false' inputMode='email' className='rounded' {...register('email')} /> {errors.email && <span className='mt-2 block text-left text-sm text-red-800'>{errors.email?.message}</span>} </div>
<Button isLoading={isSubmitting} type='submit'> Continue </Button> {/* For mobile users, SMS OTP is often preferrable to email OTP. Allowing users to switch between the two is a great way to improve the user experience. */}
{!data?.methodId && ( <button type='button' className='text-[#19303d] underline' onClick={() => props.onSwitchMethod('otp_sms')}> Or use phone number </button> )} {errors && <span className='mt-2 block text-left text-sm text-red-800'>{errors.root?.message}</span>} {/* The ToS and privacy policy links here are not implemented, but serve as a demonstration of how you can easily customize the UI and include anything that you need in your authentication flow with Stytch. */} <div className='text-neutral-4 text-xs text-neutral-600'> By continuing, you agree to the <span className='underline'>Terms of Service</span> and acknowledge our{' '} <span className='underline'>Privacy Policy</span>. </div> </form> ); }
src/components/LoginEmail.tsx
stytchauth-stytch-t3-example-38b726d
[ { "filename": "src/components/LoginSms.tsx", "retrieved_chunk": " {errors.phone && <span className='mt-2 block text-left text-sm text-red-800'>{errors.phone?.message}</span>}\n </div>\n <Button isLoading={isSubmitting} type='submit'>\n Continue\n </Button>\n {/* Allowing users to switch between the two login delivery methods is a great way to improve the user experience. */}\n {!data?.methodId && (\n <button type='button' className='text-[#19303d] underline' onClick={() => props.onSwitchMethod('otp_email')}>\n Or use email address\n </button>", "score": 0.9415395855903625 }, { "filename": "src/components/VerifyOtp.tsx", "retrieved_chunk": " </div>\n <Button isLoading={isSubmitting || isSubmitSuccessful} type='submit'>\n Continue\n </Button>\n {errors && <span className='mt-2 block text-left text-sm text-red-800'>{errors.root?.message}</span>}\n </form>\n );\n}", "score": 0.8752226829528809 }, { "filename": "src/components/VerifyOtp.tsx", "retrieved_chunk": " </p>\n <div>\n <input\n className='w-full border p-3'\n aria-label='6-Digit Code'\n type='text'\n inputMode='numeric'\n {...register('code')}\n />\n {errors && <span className='mt-2 block text-left text-sm text-red-800'>{errors.code?.message}</span>}", "score": 0.8663959503173828 }, { "filename": "src/components/LoginSms.tsx", "retrieved_chunk": " onSubmit={handleSubmit((values) =>\n mutateAsync({ phone: values.phone }).catch((err) => {\n setError('root', { message: err.message });\n }),\n )}\n >\n <h1 className='text-3xl font-semibold text-[#19303d]'>Stytch + T3 example</h1>\n <p className='text-neutral-600'>Sign in to your account to continue.</p>\n <div>\n <PhoneInput control={control} />", "score": 0.8661606311798096 }, { "filename": "src/components/LoginSms.tsx", "retrieved_chunk": " formState: { errors, isSubmitting },\n } = useForm<FormSchemaType>({\n resolver: zodResolver(formSchema),\n });\n if (data?.methodId) {\n return <VerifyOtp methodValue={getValues('phone')} methodId={data.methodId} />;\n }\n return (\n <form\n className='flex w-full flex-col gap-y-4 rounded-lg bg-white p-8 text-center shadow-sm border-[#adbcc5] border-[1px]'", "score": 0.8652884364128113 } ]
typescript
<Button isLoading={isSubmitting} type='submit'> Continue </Button> {/* For mobile users, SMS OTP is often preferrable to email OTP. Allowing users to switch between the two is a great way to improve the user experience. */}
import * as graphql from "graphql" import { AppContext } from "./context.js" import { formatDTS, getPrettierConfig } from "./formatDTS.js" import { getCodeFactsForJSTSFileAtPath } from "./serviceFile.codefacts.js" import { CodeFacts, ModelResolverFacts, ResolverFuncFact } from "./typeFacts.js" import { TypeMapper, typeMapper } from "./typeMap.js" import { capitalizeFirstLetter, createAndReferOrInlineArgsForField, inlineArgsForField } from "./utils.js" export const lookAtServiceFile = (file: string, context: AppContext) => { const { gql, prisma, pathSettings: settings, codeFacts: serviceFacts, fieldFacts } = context // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition if (!gql) throw new Error(`No schema when wanting to look at service file: ${file}`) if (!prisma) throw new Error(`No prisma schema when wanting to look at service file: ${file}`) // This isn't good enough, needs to be relative to api/src/services const fileKey = file.replace(settings.apiServicesPath, "") const thisFact: CodeFacts = {} const filename = context.basename(file) // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const queryType = gql.getQueryType()! if (!queryType) throw new Error("No query type") // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const mutationType = gql.getMutationType()! // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition if (!mutationType) throw new Error("No mutation type") const externalMapper = typeMapper(context, { preferPrismaModels: true }) const returnTypeMapper = typeMapper(context, {}) // The description of the source file const fileFacts = getCodeFactsForJSTSFileAtPath(file, context) if (Object.keys(fileFacts).length === 0) return // Tracks prospective prisma models which are used in the file const extraPrismaReferences = new Set<string>() // The file we'll be creating in-memory throughout this fn const fileDTS = context.tsProject.createSourceFile(`source/${fileKey}.d.ts`, "", { overwrite: true }) // Basically if a top level resolver reference Query or Mutation const knownSpecialCasesForGraphQL = new Set<string>() // Add the root function declarations const rootResolvers = fileFacts.maybe_query_mutation?.resolvers if (rootResolvers) rootResolvers.forEach((v) => { const isQuery = v.name in queryType.getFields() const isMutation = v.name in mutationType.getFields() const parentName = isQuery ? queryType.name : isMutation ? mutationType.name : undefined if (parentName) { addDefinitionsForTopLevelResolvers(parentName, v) } else { // Add warning about unused resolver fileDTS.addStatements(`\n// ${v.name} does not exist on Query or Mutation`) } }) // Add the root function declarations Object.values(fileFacts).forEach((model) => { if (!model) return const skip = ["maybe_query_mutation", queryType.name, mutationType.name] if (skip.includes(model.typeName)) return addCustomTypeModel(model) }) // Set up the module imports at the top const sharedGraphQLObjectsReferenced = externalMapper.getReferencedGraphQLThingsInMapping() const sharedGraphQLObjectsReferencedTypes = [...sharedGraphQLObjectsReferenced.types, ...knownSpecialCasesForGraphQL] const sharedInternalGraphQLObjectsReferenced = returnTypeMapper.getReferencedGraphQLThingsInMapping() const aliases = [...new Set([...sharedGraphQLObjectsReferenced.scalars, ...sharedInternalGraphQLObjectsReferenced.scalars])] if (aliases.length) { fileDTS.addTypeAliases( aliases.map((s) => ({ name: s, type: "any", })) ) } const prismases = [ ...new Set([ ...sharedGraphQLObjectsReferenced.prisma, ...sharedInternalGraphQLObjectsReferenced.prisma, ...extraPrismaReferences.values(), ]), ] const validPrismaObjs = prismases.filter((p) => prisma.has(p)) if (validPrismaObjs.length) { fileDTS.addImportDeclaration({ isTypeOnly: true, moduleSpecifier: "@prisma/client", namedImports: validPrismaObjs.map((p) => `${p} as P${p}`), }) } if (fileDTS.getText().includes("GraphQLResolveInfo")) { fileDTS.addImportDeclaration({ isTypeOnly: true, moduleSpecifier: "graphql", namedImports: ["GraphQLResolveInfo"], }) } if (fileDTS.getText().includes("RedwoodGraphQLContext")) { fileDTS.addImportDeclaration({ isTypeOnly: true, moduleSpecifier: "@redwoodjs/graphql-server/dist/types", namedImports: ["RedwoodGraphQLContext"], }) } if (sharedInternalGraphQLObjectsReferenced.types.length) { fileDTS.addImportDeclaration({ isTypeOnly: true, moduleSpecifier: `./${settings.sharedInternalFilename.replace(".d.ts", "")}`, namedImports
: sharedInternalGraphQLObjectsReferenced.types.map((t) => `${t} as RT${t}`), }) }
if (sharedGraphQLObjectsReferencedTypes.length) { fileDTS.addImportDeclaration({ isTypeOnly: true, moduleSpecifier: `./${settings.sharedFilename.replace(".d.ts", "")}`, namedImports: sharedGraphQLObjectsReferencedTypes, }) } serviceFacts.set(fileKey, thisFact) const dtsFilename = filename.endsWith(".ts") ? filename.replace(".ts", ".d.ts") : filename.replace(".js", ".d.ts") const dtsFilepath = context.join(context.pathSettings.typesFolderRoot, dtsFilename) // Some manual formatting tweaks so we align with Redwood's setup more const dts = fileDTS .getText() .replace(`from "graphql";`, `from "graphql";\n`) .replace(`from "@redwoodjs/graphql-server/dist/types";`, `from "@redwoodjs/graphql-server/dist/types";\n`) const shouldWriteDTS = !!dts.trim().length if (!shouldWriteDTS) return const config = getPrettierConfig(dtsFilepath) const formatted = formatDTS(dtsFilepath, dts, config) context.sys.writeFile(dtsFilepath, formatted) return dtsFilepath function addDefinitionsForTopLevelResolvers(parentName: string, config: ResolverFuncFact) { const { name } = config let field = queryType.getFields()[name] if (!field) { field = mutationType.getFields()[name] } const interfaceDeclaration = fileDTS.addInterface({ name: `${capitalizeFirstLetter(config.name)}Resolver`, isExported: true, docs: field.astNode ? ["SDL: " + graphql.print(field.astNode)] : ["@deprecated: Could not find this field in the schema for Mutation or Query"], }) const args = createAndReferOrInlineArgsForField(field, { name: interfaceDeclaration.getName(), file: fileDTS, mapper: externalMapper.map, }) if (parentName === queryType.name) knownSpecialCasesForGraphQL.add(queryType.name) if (parentName === mutationType.name) knownSpecialCasesForGraphQL.add(mutationType.name) const argsParam = args ?? "object" const returnType = returnTypeForResolver(returnTypeMapper, field, config) interfaceDeclaration.addCallSignature({ parameters: [ { name: "args", type: argsParam, hasQuestionToken: config.funcArgCount < 1 }, { name: "obj", type: `{ root: ${parentName}, context: RedwoodGraphQLContext, info: GraphQLResolveInfo }`, hasQuestionToken: config.funcArgCount < 2, }, ], returnType, }) } /** Ideally, we want to be able to write the type for just the object */ function addCustomTypeModel(modelFacts: ModelResolverFacts) { const modelName = modelFacts.typeName extraPrismaReferences.add(modelName) // Make an interface, this is the version we are replacing from graphql-codegen: // Account: MergePrismaWithSdlTypes<PrismaAccount, MakeRelationsOptional<Account, AllMappedModels>, AllMappedModels>; const gqlType = gql.getType(modelName) if (!gqlType) { // throw new Error(`Could not find a GraphQL type named ${d.getName()}`); fileDTS.addStatements(`\n// ${modelName} does not exist in the schema`) return } if (!graphql.isObjectType(gqlType)) { throw new Error(`In your schema ${modelName} is not an object, which we can only make resolver types for`) } const fields = gqlType.getFields() // See: https://github.com/redwoodjs/redwood/pull/6228#issue-1342966511 // For more ideas const hasGenerics = modelFacts.hasGenericArg // This is what they would have to write const resolverInterface = fileDTS.addInterface({ name: `${modelName}TypeResolvers`, typeParameters: hasGenerics ? ["Extended"] : [], isExported: true, }) // The parent type for the resolvers fileDTS.addTypeAlias({ name: `${modelName}AsParent`, typeParameters: hasGenerics ? ["Extended"] : [], type: `P${modelName} ${createParentAdditionallyDefinedFunctions()} ${hasGenerics ? " & Extended" : ""}`, // docs: ["The prisma model, mixed with fns already defined inside the resolvers."], }) const modelFieldFacts = fieldFacts.get(modelName) ?? {} // Loop through the resolvers, adding the fields which have resolvers implemented in the source file modelFacts.resolvers.forEach((resolver) => { const field = fields[resolver.name] if (field) { const fieldName = resolver.name if (modelFieldFacts[fieldName]) modelFieldFacts[fieldName].hasResolverImplementation = true else modelFieldFacts[fieldName] = { hasResolverImplementation: true } const argsType = inlineArgsForField(field, { mapper: externalMapper.map }) ?? "undefined" const param = hasGenerics ? "<Extended>" : "" const firstQ = resolver.funcArgCount < 1 ? "?" : "" const secondQ = resolver.funcArgCount < 2 ? "?" : "" const innerArgs = `args${firstQ}: ${argsType}, obj${secondQ}: { root: ${modelName}AsParent${param}, context: RedwoodGraphQLContext, info: GraphQLResolveInfo }` const returnType = returnTypeForResolver(returnTypeMapper, field, resolver) const docs = field.astNode ? [`SDL: ${graphql.print(field.astNode)}`] : [] // For speed we should switch this out to addProperties eventually resolverInterface.addProperty({ name: fieldName, leadingTrivia: "\n", docs, type: resolver.isFunc || resolver.isUnknown ? `(${innerArgs}) => ${returnType ?? "any"}` : returnType, }) } else { resolverInterface.addCallSignature({ docs: [` @deprecated: SDL ${modelName}.${resolver.name} does not exist in your schema`], }) } }) function createParentAdditionallyDefinedFunctions() { const fns: string[] = [] modelFacts.resolvers.forEach((resolver) => { const existsInGraphQLSchema = fields[resolver.name] if (!existsInGraphQLSchema) { console.warn( `The service file ${filename} has a field ${resolver.name} on ${modelName} that does not exist in the generated schema.graphql` ) } const prefix = !existsInGraphQLSchema ? "\n// This field does not exist in the generated schema.graphql\n" : "" const returnType = returnTypeForResolver(externalMapper, existsInGraphQLSchema, resolver) // fns.push(`${prefix}${resolver.name}: () => Promise<${externalMapper.map(type, {})}>`) fns.push(`${prefix}${resolver.name}: () => ${returnType}`) }) if (fns.length < 1) return "" return "& {" + fns.join(", \n") + "}" } fieldFacts.set(modelName, modelFieldFacts) } return dtsFilename } function returnTypeForResolver(mapper: TypeMapper, field: graphql.GraphQLField<unknown, unknown> | undefined, resolver: ResolverFuncFact) { if (!field) return "void" const tType = mapper.map(field.type, { preferNullOverUndefined: true, typenamePrefix: "RT" }) ?? "void" let returnType = tType const all = `${tType} | Promise<${tType}> | (() => Promise<${tType}>)` if (resolver.isFunc && resolver.isAsync) returnType = `Promise<${tType}>` else if (resolver.isFunc) returnType = all else if (resolver.isObjLiteral) returnType = tType else if (resolver.isUnknown) returnType = all return returnType }
src/serviceFile.ts
sdl-codegen-sdl-codegen-de2b8aa
[ { "filename": "src/sharedSchema.ts", "retrieved_chunk": "\tconst externalTSFile = context.tsProject.createSourceFile(`/source/${context.pathSettings.sharedFilename}`, \"\")\n\tObject.keys(types).forEach((name) => {\n\t\tif (name.startsWith(\"__\")) {\n\t\t\treturn\n\t\t}\n\t\tif (knownPrimitives.includes(name)) {\n\t\t\treturn\n\t\t}\n\t\tconst type = types[name]\n\t\tconst pType = prisma.get(name)", "score": 0.8602491617202759 }, { "filename": "src/sharedSchema.ts", "retrieved_chunk": "\t\texternalTSFile.addImportDeclaration({\n\t\t\tisTypeOnly: true,\n\t\t\tmoduleSpecifier: `@prisma/client`,\n\t\t\tnamedImports: allPrismaModels.map((p) => `${p} as P${p}`),\n\t\t})\n\t\tallPrismaModels.forEach((p) => {\n\t\t\texternalTSFile.addTypeAlias({\n\t\t\t\tisExported: true,\n\t\t\t\tname: p,\n\t\t\t\ttype: `P${p}`,", "score": 0.8577436208724976 }, { "filename": "src/sharedSchema.ts", "retrieved_chunk": "\tif (scalars.length) {\n\t\texternalTSFile.addTypeAliases(\n\t\t\tscalars.map((s) => ({\n\t\t\t\tname: s,\n\t\t\t\ttype: \"any\",\n\t\t\t}))\n\t\t)\n\t}\n\tconst allPrismaModels = [...new Set([...prismaModels, ...typesToImport])].sort()\n\tif (allPrismaModels.length) {", "score": 0.8520516157150269 }, { "filename": "src/sharedSchema.ts", "retrieved_chunk": "\t\t\t\t\t'\"',\n\t\t\t})\n\t\t}\n\t})\n\tconst { scalars } = mapper.getReferencedGraphQLThingsInMapping()\n\tif (scalars.length) {\n\t\texternalTSFile.addTypeAliases(\n\t\t\tscalars.map((s) => ({\n\t\t\t\tname: s,\n\t\t\t\ttype: \"any\",", "score": 0.8508264422416687 }, { "filename": "src/sharedSchema.ts", "retrieved_chunk": "\tconst types = gql.getTypeMap()\n\tconst mapper = typeMapper(context, { preferPrismaModels: true })\n\tconst typesToImport = [] as string[]\n\tconst knownPrimitives = [\"String\", \"Boolean\", \"Int\"]\n\tconst externalTSFile = context.tsProject.createSourceFile(\n\t\t`/source/${context.pathSettings.sharedInternalFilename}`,\n\t\t`\n// You may very reasonably ask yourself, 'what is this file?' and why do I need it.\n// Roughly, this file ensures that when a resolver wants to return a type - that\n// type will match a prisma model. This is useful because you can trivially extend", "score": 0.8490405082702637 } ]
typescript
: sharedInternalGraphQLObjectsReferenced.types.map((t) => `${t} as RT${t}`), }) }
import { TRPCError } from '@trpc/server'; import { deleteCookie, setCookie } from 'cookies-next'; import { parsePhoneNumber } from 'react-phone-number-input'; import { StytchError } from 'stytch'; import { z } from 'zod'; import { protectedProcedure, publicProcedure, router } from '~/server/trpc'; import { VALID_PHONE_NUMBER } from '~/utils/regex'; import { STYTCH_SUPPORTED_SMS_COUNTRIES } from '~/utils/phone-countries'; // Change these values to adjust the length of a user's session. 30 day sessions, like we use here, is usually a good default, // but you may find a shorter or longer duration to work better for your app. const SESSION_DURATION_MINUTES = 43200; // SESSION_DURATION_SECONDS is used to set the age of the cookie that we set in the user's browser. const SESSION_DURATION_SECONDS = SESSION_DURATION_MINUTES * 60; export const authRouter = router({ // This route is used to send an OTP via email to a user. loginEmail: publicProcedure .input( z.object({ email: z.string().email('Invalid email address').min(1, 'Email address is required'), }), ) .output( z.object({ methodId: z.string(), userCreated: z.boolean(), }), ) .mutation(async ({ input, ctx }) => { try { // 1. Login or create the user in Stytch. If the user has been seen before, a vanilla login will be performed, if they // haven't been seen before, a signup email will be sent and a new Stytch User will be created. const loginOrCreateResponse = await ctx.stytch.otps.email.loginOrCreate({ email: input.email, create_user_as_pending: true, }); // 2. Create the user in your Prisma database. // // Because Stytch auth lives in your backend, you can perform all of your // normal business logic in sync with your authentication, e.g. syncing your user DB, adding the user to a mailing list, // or provisioning them a Stripe customer, etc. // // If you're coming from Auth0, you might have Rules, Hooks, or Actions that perform this logic. With Stytch, there is // no need for this logic to live outside of your codebase separate from your backend. if (loginOrCreateResponse.user_created) { await ctx.prisma.user.create({ data: { stytchUserId: loginOrCreateResponse.user_id } }); } return { // The method_id is used during the OTP Authenticate step to ensure the OTP code belongs to the user who initiated the // the login flow. methodId: loginOrCreateResponse.email_id, // The user_created flag is used to determine if the user was created during this login flow. This is useful for // determining if you should show a welcome message, or take some other action, for new vs. existing users. userCreated: loginOrCreateResponse.user_created, }; } catch (err) { if (err instanceof StytchError) { throw new TRPCError({ code: 'BAD_REQUEST', message: err.error_message, cause: err }); } throw new TRPCError({ code: 'INTERNAL_SERVER_ERROR', cause: err }); } }), // This route is used to send an SMS OTP to a user. loginSms: publicProcedure .input( z.object({ phone: z.string().regex(VALID_PHONE_NUMBER, 'Invalid phone number').min(1, 'Phone number is required'), }), ) .output( z.object({ methodId: z.string(), userCreated: z.boolean(), }), ) .mutation(async ({ input, ctx }) => { const phoneNumber = parsePhoneNumber(input.phone); if (!phoneNumber?.country || !STYTCH_SUPPORTED_SMS_COUNTRIES.includes(phoneNumber.country)) { throw new TRPCError({ code: 'BAD_REQUEST', message: `Sorry, we don't support sms login for your country yet.`, }); } try { // 1. Login or create the user in Stytch. If the user has been seen before, a vanilla login will be performed, if they // haven't been seen before, an SMS will be sent and a new Stytch User will be created. const loginOrCreateResponse = await ctx.stytch.otps.sms.loginOrCreate({ phone_number: input.phone, create_user_as_pending: true, }); // 2. Create the user in your Prisma database. // // Because Stytch auth lives in your backend, you can perform all of your // normal business logic in sync with your authentication, e.g. syncing your user DB, adding the user to a mailing list, // or provisioning them a Stripe customer, etc. // // If you're coming from Auth0, you might have Rules, Hooks, or Actions that perform this logic. With Stytch, there is // no need for this logic to live outside of your codebase separate from your backend. if (loginOrCreateResponse.user_created) { await ctx.prisma.user.create({ data: { stytchUserId: loginOrCreateResponse.user_id } }); } return { // The method_id is used during the OTP Authenticate step to ensure the OTP code belongs to the user who initiated the // the login flow. methodId: loginOrCreateResponse.phone_id, // The user_created flag is used to determine if the user was created during this login flow. This is useful for // determining if you should show a welcome message, or take some other action, for new vs. existing users. userCreated: loginOrCreateResponse.user_created, }; } catch (err) { if (err instanceof StytchError) { throw new TRPCError({ code: 'BAD_REQUEST', message: err.error_message, cause: err }); } throw new TRPCError({ code: 'INTERNAL_SERVER_ERROR', cause: err }); } }), // This route handles authenticating an OTP as input by the user and adding custom claims to their resulting session. authenticateOtp: publicProcedure .input( z.object({ code: z.string().length(6, 'OTP must be 6 digits'), methodId: z.string(), }), ) .output( z.object({ id: z.string(), }), ) .mutation(async ({ input, ctx }) => { try { // 1. OTP Authenticate step; here we'll validate that the OTP + Method (phone_id or email_id) are valid and belong to // the same user who initiated the login flow. const authenticateResponse = await ctx.stytch.otps.authenticate({ code: input.code, method_id: input.methodId, session_duration_minutes: SESSION_DURATION_MINUTES, }); // 2. Get the user from your Prisma database. // // Here you could also include any other business logic, e.g. firing logs in your own stack, on successful completion of the login flow. const dbUser = await ctx.prisma.user.findUniqueOrThrow({ where: { stytchUserId: authenticateResponse.user.user_id }, select: { id: true, }, }); // Examples of business logic you might want to include on successful user creation: // // Create a Stripe customer for the user. // await ctx.stripe.customers.create({ name: authenticateResponse.user.name.first_name }); // // Subscribe the user to a mailing list. // await ctx.mailchimp.lists.addListMember("list_id", { email_address: authenticateResponse.user.emails[0].email, status: "subscribed" }); // 3. Optional: Add custom claims to the session. These claims will be available in the JWT returned by Stytch. // // Alternatively this can also be accomplished via a custom JWT template set in the Stytch Dashboard if there are values you want on // all JWTs issued for your sessions. const sessionResponse = await ctx.stytch.sessions.authenticate({ // Here we add the Prisma user ID to the session as a custom claim. session_custom_claims: { db_user_id: dbUser.id }, session_jwt: authenticateResponse.session_jwt, session_duration_minutes: SESSION_DURATION_MINUTES, }); // 4. Set the session JWT as a cookie in the user's browser. setCookie('session_jwt', sessionResponse.session_jwt, { req: ctx.req, res: ctx.res, httpOnly: true, maxAge: SESSION_DURATION_SECONDS, secure: process.env.NODE_ENV === 'production', sameSite: 'strict', }); return { id: dbUser.id, }; } catch (err) { if (err instanceof StytchError) { throw new TRPCError({ code: 'BAD_REQUEST', message: err.error_message, cause: err }); } throw new TRPCError({ code: 'INTERNAL_SERVER_ERROR', cause: err }); } }), // This route logs a user out of their session by revoking it with Stytch. // // Note, because JWTs are valid for their lifetime (here we've set it to 30 days), the JWT would still // locally parse, i.e. using an open source JWT parsing library, as valid. We always encourage you to // authenticate a session with Stytch's API directly to ensure that it is still valid.
logout: protectedProcedure.mutation(async ({ ctx }) => {
await ctx.stytch.sessions.revoke({ session_id: ctx.session.session_id }); deleteCookie('session_jwt', { req: ctx.req, res: ctx.res }); return { success: true }; }), });
src/server/routers/auth.ts
stytchauth-stytch-t3-example-38b726d
[ { "filename": "src/server/routers/user.ts", "retrieved_chunk": "import { publicProcedure, router } from '~/server/trpc';\nexport const userRouter = router({\n // This route fetches the current, logged-in user.\n current: publicProcedure.query(async ({ ctx }) => {\n const session = ctx.session;\n if (!session) return null;\n const [stytchUser, dbUser] = await Promise.all([\n ctx.stytch.users.get(session.user_id),\n ctx.prisma.user.findUniqueOrThrow({\n where: { id: session.custom_claims.db_user_id },", "score": 0.8535380363464355 }, { "filename": "src/server/trpc.ts", "retrieved_chunk": " }\n if (!ctx.session) {\n throw new TRPCError({ code: 'UNAUTHORIZED' });\n }\n return next({\n ctx: {\n session: ctx.session,\n req: ctx.req,\n res: ctx.res,\n },", "score": 0.8436892628669739 }, { "filename": "src/components/AccountLogout.tsx", "retrieved_chunk": "import { useRouter } from 'next/router';\nimport { trpc } from '~/utils/trpc';\nimport { Button } from './Button';\nexport function AccountLogout() {\n const router = useRouter();\n const utils = trpc.useContext();\n const { mutate } = trpc.auth.logout.useMutation({\n onSuccess: () => {\n utils.user.current.invalidate();\n router.replace('/login');", "score": 0.8243670463562012 }, { "filename": "src/middleware.ts", "retrieved_chunk": " // If there is a JWT, we need to verify it with Stytch to make sure it is valid and take the appropriate action.\n if (jwtToken) {\n // Authenticate the JWT with Stytch; this will tell us if the session is still valid.\n try {\n const stytch = loadStytch();\n await stytch.sessions.authenticateJwt(jwtToken);\n // If the session is valid and they are on the login screen, redirect them to the profile screen.\n if (pathname === '/login') {\n return NextResponse.redirect(new URL('/profile', req.url));\n }", "score": 0.8234283924102783 }, { "filename": "src/server/context.ts", "retrieved_chunk": " deleteCookie('session_jwt', { req, res });\n }\n }\n return { req, res, prisma, stytch, session };\n}\nexport type Context = trpc.inferAsyncReturnType<typeof createContext>;", "score": 0.8232007026672363 } ]
typescript
logout: protectedProcedure.mutation(async ({ ctx }) => {
import { TRPCError } from '@trpc/server'; import { deleteCookie, setCookie } from 'cookies-next'; import { parsePhoneNumber } from 'react-phone-number-input'; import { StytchError } from 'stytch'; import { z } from 'zod'; import { protectedProcedure, publicProcedure, router } from '~/server/trpc'; import { VALID_PHONE_NUMBER } from '~/utils/regex'; import { STYTCH_SUPPORTED_SMS_COUNTRIES } from '~/utils/phone-countries'; // Change these values to adjust the length of a user's session. 30 day sessions, like we use here, is usually a good default, // but you may find a shorter or longer duration to work better for your app. const SESSION_DURATION_MINUTES = 43200; // SESSION_DURATION_SECONDS is used to set the age of the cookie that we set in the user's browser. const SESSION_DURATION_SECONDS = SESSION_DURATION_MINUTES * 60; export const authRouter = router({ // This route is used to send an OTP via email to a user. loginEmail: publicProcedure .input( z.object({ email: z.string().email('Invalid email address').min(1, 'Email address is required'), }), ) .output( z.object({ methodId: z.string(), userCreated: z.boolean(), }), ) .mutation(async ({ input, ctx }) => { try { // 1. Login or create the user in Stytch. If the user has been seen before, a vanilla login will be performed, if they // haven't been seen before, a signup email will be sent and a new Stytch User will be created. const loginOrCreateResponse = await ctx.stytch.otps.email.loginOrCreate({ email: input.email, create_user_as_pending: true, }); // 2. Create the user in your Prisma database. // // Because Stytch auth lives in your backend, you can perform all of your // normal business logic in sync with your authentication, e.g. syncing your user DB, adding the user to a mailing list, // or provisioning them a Stripe customer, etc. // // If you're coming from Auth0, you might have Rules, Hooks, or Actions that perform this logic. With Stytch, there is // no need for this logic to live outside of your codebase separate from your backend. if (loginOrCreateResponse.user_created) { await ctx.prisma.user.create({ data: { stytchUserId: loginOrCreateResponse.user_id } }); } return { // The method_id is used during the OTP Authenticate step to ensure the OTP code belongs to the user who initiated the // the login flow. methodId: loginOrCreateResponse.email_id, // The user_created flag is used to determine if the user was created during this login flow. This is useful for // determining if you should show a welcome message, or take some other action, for new vs. existing users. userCreated: loginOrCreateResponse.user_created, }; } catch (err) { if (err instanceof StytchError) { throw new TRPCError({ code: 'BAD_REQUEST', message: err.error_message, cause: err }); } throw new TRPCError({ code: 'INTERNAL_SERVER_ERROR', cause: err }); } }), // This route is used to send an SMS OTP to a user. loginSms: publicProcedure .input( z.object({ phone: z.string().regex(VALID_PHONE_NUMBER, 'Invalid phone number').min(1, 'Phone number is required'), }), ) .output( z.object({ methodId: z.string(), userCreated: z.boolean(), }), ) .mutation(async ({ input, ctx }) => { const phoneNumber = parsePhoneNumber(input.phone);
if (!phoneNumber?.country || !STYTCH_SUPPORTED_SMS_COUNTRIES.includes(phoneNumber.country)) {
throw new TRPCError({ code: 'BAD_REQUEST', message: `Sorry, we don't support sms login for your country yet.`, }); } try { // 1. Login or create the user in Stytch. If the user has been seen before, a vanilla login will be performed, if they // haven't been seen before, an SMS will be sent and a new Stytch User will be created. const loginOrCreateResponse = await ctx.stytch.otps.sms.loginOrCreate({ phone_number: input.phone, create_user_as_pending: true, }); // 2. Create the user in your Prisma database. // // Because Stytch auth lives in your backend, you can perform all of your // normal business logic in sync with your authentication, e.g. syncing your user DB, adding the user to a mailing list, // or provisioning them a Stripe customer, etc. // // If you're coming from Auth0, you might have Rules, Hooks, or Actions that perform this logic. With Stytch, there is // no need for this logic to live outside of your codebase separate from your backend. if (loginOrCreateResponse.user_created) { await ctx.prisma.user.create({ data: { stytchUserId: loginOrCreateResponse.user_id } }); } return { // The method_id is used during the OTP Authenticate step to ensure the OTP code belongs to the user who initiated the // the login flow. methodId: loginOrCreateResponse.phone_id, // The user_created flag is used to determine if the user was created during this login flow. This is useful for // determining if you should show a welcome message, or take some other action, for new vs. existing users. userCreated: loginOrCreateResponse.user_created, }; } catch (err) { if (err instanceof StytchError) { throw new TRPCError({ code: 'BAD_REQUEST', message: err.error_message, cause: err }); } throw new TRPCError({ code: 'INTERNAL_SERVER_ERROR', cause: err }); } }), // This route handles authenticating an OTP as input by the user and adding custom claims to their resulting session. authenticateOtp: publicProcedure .input( z.object({ code: z.string().length(6, 'OTP must be 6 digits'), methodId: z.string(), }), ) .output( z.object({ id: z.string(), }), ) .mutation(async ({ input, ctx }) => { try { // 1. OTP Authenticate step; here we'll validate that the OTP + Method (phone_id or email_id) are valid and belong to // the same user who initiated the login flow. const authenticateResponse = await ctx.stytch.otps.authenticate({ code: input.code, method_id: input.methodId, session_duration_minutes: SESSION_DURATION_MINUTES, }); // 2. Get the user from your Prisma database. // // Here you could also include any other business logic, e.g. firing logs in your own stack, on successful completion of the login flow. const dbUser = await ctx.prisma.user.findUniqueOrThrow({ where: { stytchUserId: authenticateResponse.user.user_id }, select: { id: true, }, }); // Examples of business logic you might want to include on successful user creation: // // Create a Stripe customer for the user. // await ctx.stripe.customers.create({ name: authenticateResponse.user.name.first_name }); // // Subscribe the user to a mailing list. // await ctx.mailchimp.lists.addListMember("list_id", { email_address: authenticateResponse.user.emails[0].email, status: "subscribed" }); // 3. Optional: Add custom claims to the session. These claims will be available in the JWT returned by Stytch. // // Alternatively this can also be accomplished via a custom JWT template set in the Stytch Dashboard if there are values you want on // all JWTs issued for your sessions. const sessionResponse = await ctx.stytch.sessions.authenticate({ // Here we add the Prisma user ID to the session as a custom claim. session_custom_claims: { db_user_id: dbUser.id }, session_jwt: authenticateResponse.session_jwt, session_duration_minutes: SESSION_DURATION_MINUTES, }); // 4. Set the session JWT as a cookie in the user's browser. setCookie('session_jwt', sessionResponse.session_jwt, { req: ctx.req, res: ctx.res, httpOnly: true, maxAge: SESSION_DURATION_SECONDS, secure: process.env.NODE_ENV === 'production', sameSite: 'strict', }); return { id: dbUser.id, }; } catch (err) { if (err instanceof StytchError) { throw new TRPCError({ code: 'BAD_REQUEST', message: err.error_message, cause: err }); } throw new TRPCError({ code: 'INTERNAL_SERVER_ERROR', cause: err }); } }), // This route logs a user out of their session by revoking it with Stytch. // // Note, because JWTs are valid for their lifetime (here we've set it to 30 days), the JWT would still // locally parse, i.e. using an open source JWT parsing library, as valid. We always encourage you to // authenticate a session with Stytch's API directly to ensure that it is still valid. logout: protectedProcedure.mutation(async ({ ctx }) => { await ctx.stytch.sessions.revoke({ session_id: ctx.session.session_id }); deleteCookie('session_jwt', { req: ctx.req, res: ctx.res }); return { success: true }; }), });
src/server/routers/auth.ts
stytchauth-stytch-t3-example-38b726d
[ { "filename": "src/components/LoginSms.tsx", "retrieved_chunk": " phone: z.string().regex(VALID_PHONE_NUMBER, 'Invalid phone number').min(1, 'Phone number is required'),\n});\ntype FormSchemaType = z.infer<typeof formSchema>;\nexport function LoginSms(props: { onSwitchMethod: (method: StytchAuthMethods) => void }) {\n const { data, mutateAsync } = trpc.auth.loginSms.useMutation();\n const {\n handleSubmit,\n getValues,\n setError,\n control,", "score": 0.8493573665618896 }, { "filename": "src/components/LoginSms.tsx", "retrieved_chunk": "import { useForm } from 'react-hook-form';\nimport { z } from 'zod';\nimport { zodResolver } from '@hookform/resolvers/zod';\nimport { type StytchAuthMethods } from '~/types/stytch';\nimport { trpc } from '~/utils/trpc';\nimport { VALID_PHONE_NUMBER } from '~/utils/regex';\nimport { Button } from './Button';\nimport { PhoneInput } from './PhoneInput';\nimport { VerifyOtp } from './VerifyOtp';\nconst formSchema = z.object({", "score": 0.843879759311676 }, { "filename": "src/components/PhoneInput.tsx", "retrieved_chunk": " '[&_.PhoneInputCountry]:absolute [&_.PhoneInputCountry]:left-6 [&_.PhoneInputCountry]:self-center',\n '[&_input]:pl-14',\n )}\n control={control}\n countries={STYTCH_SUPPORTED_SMS_COUNTRIES}\n countryCallingCodeEditable={false}\n defaultCountry={STYTCH_SUPPORTED_SMS_COUNTRIES[0]}\n flags={flags}\n inputComponent={Input}\n international", "score": 0.8209471106529236 }, { "filename": "src/components/LoginEmail.tsx", "retrieved_chunk": "import { useForm } from 'react-hook-form';\nimport { z } from 'zod';\nimport { zodResolver } from '@hookform/resolvers/zod';\nimport { type StytchAuthMethods } from '~/types/stytch';\nimport { trpc } from '~/utils/trpc';\nimport { VerifyOtp } from './VerifyOtp';\nimport { Button } from './Button';\nimport { Input } from './Input';\nconst formSchema = z.object({\n email: z.string().email('Invalid email address').min(1, 'Email address is required'),", "score": 0.8193293809890747 }, { "filename": "src/components/LoginSms.tsx", "retrieved_chunk": " onSubmit={handleSubmit((values) =>\n mutateAsync({ phone: values.phone }).catch((err) => {\n setError('root', { message: err.message });\n }),\n )}\n >\n <h1 className='text-3xl font-semibold text-[#19303d]'>Stytch + T3 example</h1>\n <p className='text-neutral-600'>Sign in to your account to continue.</p>\n <div>\n <PhoneInput control={control} />", "score": 0.8157880306243896 } ]
typescript
if (!phoneNumber?.country || !STYTCH_SUPPORTED_SMS_COUNTRIES.includes(phoneNumber.country)) {
import { useForm } from 'react-hook-form'; import { z } from 'zod'; import { zodResolver } from '@hookform/resolvers/zod'; import { type StytchAuthMethods } from '~/types/stytch'; import { trpc } from '~/utils/trpc'; import { VerifyOtp } from './VerifyOtp'; import { Button } from './Button'; import { Input } from './Input'; const formSchema = z.object({ email: z.string().email('Invalid email address').min(1, 'Email address is required'), }); type FormSchemaType = z.infer<typeof formSchema>; export function LoginEmail(props: { onSwitchMethod: (method: StytchAuthMethods) => void }) { const { data, mutateAsync } = trpc.auth.loginEmail.useMutation(); const { handleSubmit, register, getValues, setError, formState: { errors, isSubmitting }, } = useForm<FormSchemaType>({ resolver: zodResolver(formSchema), }); if (data?.methodId) { return <VerifyOtp methodValue={getValues('email')} methodId={data.methodId} />; } return ( <form className='flex w-full flex-col gap-y-4 rounded bg-white p-8 text-center shadow-sm border-[#adbcc5] border-[1px]' onSubmit={handleSubmit((values) => mutateAsync({ email: values.email }).catch((err) => { setError('root', { message: err.message }); }), )} > <h1 className='text-3xl font-semibold text-[#19303d]'>Stytch + T3 example</h1> <div> <Input aria-label='Email' placeholder='example@email.com' type='email' autoCapitalize='off' autoCorrect='off' spellCheck='false' inputMode='email' className='rounded' {...register('email')} /> {errors.email && <span className='mt-2 block text-left text-sm text-red-800'>{errors.email?.message}</span>} </div> <
Button isLoading={isSubmitting} type='submit'> Continue </Button> {/* For mobile users, SMS OTP is often preferrable to email OTP. Allowing users to switch between the two is a great way to improve the user experience. */}
{!data?.methodId && ( <button type='button' className='text-[#19303d] underline' onClick={() => props.onSwitchMethod('otp_sms')}> Or use phone number </button> )} {errors && <span className='mt-2 block text-left text-sm text-red-800'>{errors.root?.message}</span>} {/* The ToS and privacy policy links here are not implemented, but serve as a demonstration of how you can easily customize the UI and include anything that you need in your authentication flow with Stytch. */} <div className='text-neutral-4 text-xs text-neutral-600'> By continuing, you agree to the <span className='underline'>Terms of Service</span> and acknowledge our{' '} <span className='underline'>Privacy Policy</span>. </div> </form> ); }
src/components/LoginEmail.tsx
stytchauth-stytch-t3-example-38b726d
[ { "filename": "src/components/LoginSms.tsx", "retrieved_chunk": " {errors.phone && <span className='mt-2 block text-left text-sm text-red-800'>{errors.phone?.message}</span>}\n </div>\n <Button isLoading={isSubmitting} type='submit'>\n Continue\n </Button>\n {/* Allowing users to switch between the two login delivery methods is a great way to improve the user experience. */}\n {!data?.methodId && (\n <button type='button' className='text-[#19303d] underline' onClick={() => props.onSwitchMethod('otp_email')}>\n Or use email address\n </button>", "score": 0.9367316961288452 }, { "filename": "src/components/VerifyOtp.tsx", "retrieved_chunk": " </div>\n <Button isLoading={isSubmitting || isSubmitSuccessful} type='submit'>\n Continue\n </Button>\n {errors && <span className='mt-2 block text-left text-sm text-red-800'>{errors.root?.message}</span>}\n </form>\n );\n}", "score": 0.8767726421356201 }, { "filename": "src/components/LoginSms.tsx", "retrieved_chunk": " onSubmit={handleSubmit((values) =>\n mutateAsync({ phone: values.phone }).catch((err) => {\n setError('root', { message: err.message });\n }),\n )}\n >\n <h1 className='text-3xl font-semibold text-[#19303d]'>Stytch + T3 example</h1>\n <p className='text-neutral-600'>Sign in to your account to continue.</p>\n <div>\n <PhoneInput control={control} />", "score": 0.8660281896591187 }, { "filename": "src/components/VerifyOtp.tsx", "retrieved_chunk": " </p>\n <div>\n <input\n className='w-full border p-3'\n aria-label='6-Digit Code'\n type='text'\n inputMode='numeric'\n {...register('code')}\n />\n {errors && <span className='mt-2 block text-left text-sm text-red-800'>{errors.code?.message}</span>}", "score": 0.864844799041748 }, { "filename": "src/components/LoginSms.tsx", "retrieved_chunk": " formState: { errors, isSubmitting },\n } = useForm<FormSchemaType>({\n resolver: zodResolver(formSchema),\n });\n if (data?.methodId) {\n return <VerifyOtp methodValue={getValues('phone')} methodId={data.methodId} />;\n }\n return (\n <form\n className='flex w-full flex-col gap-y-4 rounded-lg bg-white p-8 text-center shadow-sm border-[#adbcc5] border-[1px]'", "score": 0.8645678758621216 } ]
typescript
Button isLoading={isSubmitting} type='submit'> Continue </Button> {/* For mobile users, SMS OTP is often preferrable to email OTP. Allowing users to switch between the two is a great way to improve the user experience. */}
import { getSchema as getPrismaSchema } from "@mrleebo/prisma-ast" import * as graphql from "graphql" import { Project } from "ts-morph" import typescript from "typescript" import { AppContext } from "./context.js" import { PrismaMap, prismaModeller } from "./prismaModeller.js" import { lookAtServiceFile } from "./serviceFile.js" import { createSharedSchemaFiles } from "./sharedSchema.js" import { CodeFacts, FieldFacts } from "./typeFacts.js" import { RedwoodPaths } from "./types.js" export * from "./main.js" export * from "./types.js" import { basename, join } from "node:path" /** The API specifically for Redwood */ export function runFullCodegen(preset: "redwood", config: { paths: RedwoodPaths }): { paths: string[] } export function runFullCodegen(preset: string, config: unknown): { paths: string[] } export function runFullCodegen(preset: string, config: unknown): { paths: string[] } { if (preset !== "redwood") throw new Error("Only Redwood codegen is supported at this time") const paths = (config as { paths: RedwoodPaths }).paths const sys = typescript.sys const pathSettings: AppContext["pathSettings"] = { root: paths.base, apiServicesPath: paths.api.services, prismaDSLPath: paths.api.dbSchema, graphQLSchemaPath: paths.generated.schema, sharedFilename: "shared-schema-types.d.ts", sharedInternalFilename: "shared-return-types.d.ts", typesFolderRoot: paths.api.types, } const project = new Project({ useInMemoryFileSystem: true }) let gqlSchema: graphql.GraphQLSchema | undefined const getGraphQLSDLFromFile = (settings: AppContext["pathSettings"]) => { const schema = sys.readFile(settings.graphQLSchemaPath) if (!schema) throw new Error("No schema found at " + settings.graphQLSchemaPath) gqlSchema = graphql.buildSchema(schema) } let prismaSchema: PrismaMap = new Map() const getPrismaSchemaFromFile = (settings: AppContext["pathSettings"]) => { const prismaSchemaText = sys.readFile(settings.prismaDSLPath) if (!prismaSchemaText) throw new Error("No prisma file found at " + settings.prismaDSLPath) const prismaSchemaBlocks = getPrismaSchema(prismaSchemaText) prismaSchema = prismaModeller(prismaSchemaBlocks) } getGraphQLSDLFromFile(pathSettings) getPrismaSchemaFromFile(pathSettings) if (!gqlSchema) throw new Error("No GraphQL Schema was created during setup") const appContext: AppContext = { gql: gqlSchema, prisma: prismaSchema, tsProject: project, codeFacts: new Map<string, CodeFacts>(), fieldFacts: new Map<string, FieldFacts>(), pathSettings, sys, join, basename, } // TODO: Maybe Redwood has an API for this? Its grabbing all the services const serviceFiles = appContext.
sys.readDirectory(appContext.pathSettings.apiServicesPath) const serviceFilesToLookAt = serviceFiles.filter((file) => {
if (file.endsWith(".test.ts")) return false if (file.endsWith("scenarios.ts")) return false return file.endsWith(".ts") || file.endsWith(".tsx") || file.endsWith(".js") }) const filepaths = [] as string[] // Create the two shared schema files const sharedDTSes = createSharedSchemaFiles(appContext) filepaths.push(...sharedDTSes) // This needs to go first, as it sets up fieldFacts for (const path of serviceFilesToLookAt) { const dts = lookAtServiceFile(path, appContext) if (dts) filepaths.push(dts) } return { paths: filepaths, } }
src/index.ts
sdl-codegen-sdl-codegen-de2b8aa
[ { "filename": "src/run.ts", "retrieved_chunk": "\t\tsys,\n\t\tjoin,\n\t\tbasename,\n\t}\n\tconst serviceFilesToLookAt = [] as string[]\n\tfor (const dirEntry of sys.readDirectory(appContext.pathSettings.apiServicesPath)) {\n\t\t// These are generally the folders\n\t\tif (sys.directoryExists(dirEntry)) {\n\t\t\tconst folderPath = join(appContext.pathSettings.apiServicesPath, dirEntry)\n\t\t\t// And these are the files in them", "score": 0.899260401725769 }, { "filename": "src/tests/testRunner.ts", "retrieved_chunk": "\t\tjoin,\n\t}\n\tif (run.gamesService) {\n\t\tvfsMap.set(\"/api/src/services/games.ts\", run.gamesService)\n\t\tlookAtServiceFile(\"/api/src/services/games.ts\", appContext)\n\t}\n\treturn {\n\t\tvfsMap,\n\t\tappContext,\n\t}", "score": 0.8490103483200073 }, { "filename": "src/run.ts", "retrieved_chunk": "\t// This needs to go first, as it sets up fieldFacts\n\tfor (const path of serviceFilesToLookAt) {\n\t\tlookAtServiceFile(path, appContext)\n\t}\n\tcreateSharedSchemaFiles(appContext)\n\t// console.log(`Updated`, typesRoot)\n\tif (config.runESLint) {\n\t\t// console.log(\"Running ESLint...\")\n\t\t// const process = Deno.run({\n\t\t// \tcwd: appRoot,", "score": 0.8447283506393433 }, { "filename": "src/run.ts", "retrieved_chunk": "\t\t\tfor (const subdirEntry of sys.readDirectory(folderPath)) {\n\t\t\t\tconst folderPath = join(appContext.pathSettings.apiServicesPath, dirEntry)\n\t\t\t\tif (\n\t\t\t\t\tsys.fileExists(folderPath) &&\n\t\t\t\t\tsubdirEntry.endsWith(\".ts\") &&\n\t\t\t\t\t!subdirEntry.includes(\".test.ts\") &&\n\t\t\t\t\t!subdirEntry.includes(\"scenarios.ts\")\n\t\t\t\t) {\n\t\t\t\t\tserviceFilesToLookAt.push(join(folderPath, subdirEntry))\n\t\t\t\t}", "score": 0.8424098491668701 }, { "filename": "src/run.ts", "retrieved_chunk": "\t}\n\tconst settings: AppContext[\"pathSettings\"] = {\n\t\troot: appRoot,\n\t\tgraphQLSchemaPath: join(appRoot, \".redwood\", \"schema.graphql\"),\n\t\tapiServicesPath: join(appRoot, \"api\", \"src\", \"services\"),\n\t\tprismaDSLPath: join(appRoot, \"api\", \"db\", \"schema.prisma\"),\n\t\tsharedFilename: \"shared-schema-types.d.ts\",\n\t\tsharedInternalFilename: \"shared-return-types.d.ts\",\n\t\ttypesFolderRoot: typesRoot,\n\t}", "score": 0.8311043977737427 } ]
typescript
sys.readDirectory(appContext.pathSettings.apiServicesPath) const serviceFilesToLookAt = serviceFiles.filter((file) => {
import { useForm } from 'react-hook-form'; import { z } from 'zod'; import { zodResolver } from '@hookform/resolvers/zod'; import { type StytchAuthMethods } from '~/types/stytch'; import { trpc } from '~/utils/trpc'; import { VALID_PHONE_NUMBER } from '~/utils/regex'; import { Button } from './Button'; import { PhoneInput } from './PhoneInput'; import { VerifyOtp } from './VerifyOtp'; const formSchema = z.object({ phone: z.string().regex(VALID_PHONE_NUMBER, 'Invalid phone number').min(1, 'Phone number is required'), }); type FormSchemaType = z.infer<typeof formSchema>; export function LoginSms(props: { onSwitchMethod: (method: StytchAuthMethods) => void }) { const { data, mutateAsync } = trpc.auth.loginSms.useMutation(); const { handleSubmit, getValues, setError, control, formState: { errors, isSubmitting }, } = useForm<FormSchemaType>({ resolver: zodResolver(formSchema), }); if (data?.methodId) { return <VerifyOtp methodValue={getValues('phone')} methodId={data.methodId} />; } return ( <form className='flex w-full flex-col gap-y-4 rounded-lg bg-white p-8 text-center shadow-sm border-[#adbcc5] border-[1px]' onSubmit={handleSubmit((values) => mutateAsync({ phone: values.phone }).catch((err) => { setError('root', { message: err.message }); }), )} > <h1 className='text-3xl font-semibold text-[#19303d]'>Stytch + T3 example</h1> <p className='text-neutral-600'>Sign in to your account to continue.</p> <div> <PhoneInput control={control} /> {errors.phone && <span className='mt-2 block text-left text-sm text-red-800'>{errors.phone?.message}</span>} </div>
<Button isLoading={isSubmitting} type='submit'> Continue </Button> {/* Allowing users to switch between the two login delivery methods is a great way to improve the user experience. */}
{!data?.methodId && ( <button type='button' className='text-[#19303d] underline' onClick={() => props.onSwitchMethod('otp_email')}> Or use email address </button> )} {errors && <span className='mt-2 block text-left text-sm text-red-800'>{errors.root?.message}</span>} {/* The ToS and privacy policy links here are not implemented, but serve as a demonstration of how you can easily customize the UI and include anything that you need in your authentication flow with Stytch. */} <div className='text-neutral-4 text-xs text-neutral-600'> By continuing, you agree to the <span className='underline'>Terms of Service</span> and acknowledge our{' '} <span className='underline'>Privacy Policy</span>. </div> </form> ); }
src/components/LoginSms.tsx
stytchauth-stytch-t3-example-38b726d
[ { "filename": "src/components/Welcome.tsx", "retrieved_chunk": " . You can use One-Time Passcodes, sent via email or SMS, to log in to this app and see the profile page.\n </p>\n <LoginButton />\n <Image alt='Powered by Stytch' src='/powered-by-stytch.png' width={150} height={14} className='pt-5' />\n </div>\n );\n};", "score": 0.8776850700378418 }, { "filename": "src/components/LoginEmail.tsx", "retrieved_chunk": " <Button isLoading={isSubmitting} type='submit'>\n Continue\n </Button>\n {/* For mobile users, SMS OTP is often preferrable to email OTP. Allowing users to switch between the two is a great way to improve the user experience. */}\n {!data?.methodId && (\n <button type='button' className='text-[#19303d] underline' onClick={() => props.onSwitchMethod('otp_sms')}>\n Or use phone number\n </button>\n )}\n {errors && <span className='mt-2 block text-left text-sm text-red-800'>{errors.root?.message}</span>}", "score": 0.8765434622764587 }, { "filename": "src/components/LoginEmail.tsx", "retrieved_chunk": " {/* The ToS and privacy policy links here are not implemented, but serve as a demonstration of how you can easily customize the UI and include anything that you need in your authentication flow with Stytch. */}\n <div className='text-neutral-4 text-xs text-neutral-600'>\n By continuing, you agree to the <span className='underline'>Terms of Service</span> and acknowledge our{' '}\n <span className='underline'>Privacy Policy</span>.\n </div>\n </form>\n );\n}", "score": 0.8706597089767456 }, { "filename": "src/components/VerifyOtp.tsx", "retrieved_chunk": " className='flex w-full flex-col gap-y-4 rounded-lg bg-white p-8 text-center shadow-sm border-[#adbcc5] border-[1px]'\n onSubmit={handleSubmit((values) =>\n mutateAsync({ code: values.code, methodId: methodId }).catch((err) => {\n setError('root', { message: err.message });\n }),\n )}\n >\n <h1 className='text-3xl font-semibold'>Enter your verification code</h1>\n <p className='text-neutral-600'>\n A 6-digit verification was sent to <strong className='font-semibold'>{methodValue}</strong>", "score": 0.868239164352417 }, { "filename": "src/pages/_app.tsx", "retrieved_chunk": " <meta\n name=\"description\"\n content=\"An example T3 application using Stytch for authentication\"\n />\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />\n <link rel=\"icon\" href=\"/favicon.svg\" />\n </Head>\n <SiteHeader />\n <main>\n <div className='container'>", "score": 0.8662672638893127 } ]
typescript
<Button isLoading={isSubmitting} type='submit'> Continue </Button> {/* Allowing users to switch between the two login delivery methods is a great way to improve the user experience. */}
import * as tsMorph from "ts-morph" import { AppContext } from "./context.js" import { CodeFacts, ModelResolverFacts, ResolverFuncFact } from "./typeFacts.js" import { varStartsWithUppercase } from "./utils.js" export const getCodeFactsForJSTSFileAtPath = (file: string, context: AppContext) => { const { pathSettings: settings } = context const fileKey = file.replace(settings.apiServicesPath, "") // const priorFacts = serviceInfo.get(fileKey) const fileFact: CodeFacts = {} const fileContents = context.sys.readFile(file) const referenceFileSourceFile = context.tsProject.createSourceFile(`/source/${fileKey}`, fileContents, { overwrite: true }) const vars = referenceFileSourceFile.getVariableDeclarations().filter((v) => v.isExported()) const resolverContainers = vars.filter(varStartsWithUppercase) const queryOrMutationResolvers = vars.filter((v) => !varStartsWithUppercase(v)) queryOrMutationResolvers.forEach((v) => { const parent = "maybe_query_mutation" const facts = getResolverInformationForDeclaration(v.getInitializer()) // Start making facts about the services const fact: ModelResolverFacts = fileFact[parent] ?? { typeName: parent, resolvers: new Map(), hasGenericArg: false, } fact.resolvers.set(v.getName(), { name: v.getName(), ...facts }) fileFact[parent] = fact }) // Next all the capital consts resolverContainers.forEach((c) => { addCustomTypeResolvers(c) }) return fileFact function addCustomTypeResolvers(variableDeclaration: tsMorph.VariableDeclaration) { const declarations = variableDeclaration.getVariableStatementOrThrow().getDeclarations() declarations.forEach((d) => { const name = d.getName() // only do it if the first letter is a capital if (!name.match(/^[A-Z]/)) return const type = d.getType() const hasGenericArg = type.getText().includes("<") // Start making facts about the services
const fact: ModelResolverFacts = fileFact[name] ?? {
typeName: name, resolvers: new Map(), hasGenericArg, } // Grab the const Thing = { ... } const obj = d.getFirstDescendantByKind(tsMorph.SyntaxKind.ObjectLiteralExpression) if (!obj) { throw new Error(`Could not find an object literal ( e.g. a { } ) in ${d.getName()}`) } obj.getProperties().forEach((p) => { if (p.isKind(tsMorph.SyntaxKind.SpreadAssignment)) { return } if (p.isKind(tsMorph.SyntaxKind.PropertyAssignment) && p.hasInitializer()) { const name = p.getName() fact.resolvers.set(name, { name, ...getResolverInformationForDeclaration(p.getInitializerOrThrow()) }) } if (p.isKind(tsMorph.SyntaxKind.FunctionDeclaration) && p.getName()) { const name = p.getName() // @ts-expect-error - lets let this go for now fact.resolvers.set(name, { name, ...getResolverInformationForDeclaration(p) }) } }) fileFact[d.getName()] = fact }) } } const getResolverInformationForDeclaration = (initialiser: tsMorph.Expression | undefined): Omit<ResolverFuncFact, "name"> => { // Who knows what folks could do, lets not crash if (!initialiser) { return { funcArgCount: 0, isFunc: false, isAsync: false, isUnknown: true, isObjLiteral: false, } } // resolver is a fn if (initialiser.isKind(tsMorph.SyntaxKind.ArrowFunction) || initialiser.isKind(tsMorph.SyntaxKind.FunctionExpression)) { return { funcArgCount: initialiser.getParameters().length, isFunc: true, isAsync: initialiser.isAsync(), isUnknown: false, isObjLiteral: false, } } // resolver is a raw obj if ( initialiser.isKind(tsMorph.SyntaxKind.ObjectLiteralExpression) || initialiser.isKind(tsMorph.SyntaxKind.StringLiteral) || initialiser.isKind(tsMorph.SyntaxKind.NumericLiteral) || initialiser.isKind(tsMorph.SyntaxKind.TrueKeyword) || initialiser.isKind(tsMorph.SyntaxKind.FalseKeyword) || initialiser.isKind(tsMorph.SyntaxKind.NullKeyword) || initialiser.isKind(tsMorph.SyntaxKind.UndefinedKeyword) ) { return { funcArgCount: 0, isFunc: false, isAsync: false, isUnknown: false, isObjLiteral: true, } } // who knows return { funcArgCount: 0, isFunc: false, isAsync: false, isUnknown: true, isObjLiteral: false, } }
src/serviceFile.codefacts.ts
sdl-codegen-sdl-codegen-de2b8aa
[ { "filename": "src/serviceFile.ts", "retrieved_chunk": "\tfunction addCustomTypeModel(modelFacts: ModelResolverFacts) {\n\t\tconst modelName = modelFacts.typeName\n\t\textraPrismaReferences.add(modelName)\n\t\t// Make an interface, this is the version we are replacing from graphql-codegen:\n\t\t// Account: MergePrismaWithSdlTypes<PrismaAccount, MakeRelationsOptional<Account, AllMappedModels>, AllMappedModels>;\n\t\tconst gqlType = gql.getType(modelName)\n\t\tif (!gqlType) {\n\t\t\t// throw new Error(`Could not find a GraphQL type named ${d.getName()}`);\n\t\t\tfileDTS.addStatements(`\\n// ${modelName} does not exist in the schema`)\n\t\t\treturn", "score": 0.8843600153923035 }, { "filename": "src/serviceFile.ts", "retrieved_chunk": "\t\t\tconst parentName = isQuery ? queryType.name : isMutation ? mutationType.name : undefined\n\t\t\tif (parentName) {\n\t\t\t\taddDefinitionsForTopLevelResolvers(parentName, v)\n\t\t\t} else {\n\t\t\t\t// Add warning about unused resolver\n\t\t\t\tfileDTS.addStatements(`\\n// ${v.name} does not exist on Query or Mutation`)\n\t\t\t}\n\t\t})\n\t// Add the root function declarations\n\tObject.values(fileFacts).forEach((model) => {", "score": 0.8569580316543579 }, { "filename": "src/serviceFile.ts", "retrieved_chunk": "\t\t\tconst fns: string[] = []\n\t\t\tmodelFacts.resolvers.forEach((resolver) => {\n\t\t\t\tconst existsInGraphQLSchema = fields[resolver.name]\n\t\t\t\tif (!existsInGraphQLSchema) {\n\t\t\t\t\tconsole.warn(\n\t\t\t\t\t\t`The service file ${filename} has a field ${resolver.name} on ${modelName} that does not exist in the generated schema.graphql`\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t\tconst prefix = !existsInGraphQLSchema ? \"\\n// This field does not exist in the generated schema.graphql\\n\" : \"\"\n\t\t\t\tconst returnType = returnTypeForResolver(externalMapper, existsInGraphQLSchema, resolver)", "score": 0.8565772175788879 }, { "filename": "src/serviceFile.ts", "retrieved_chunk": "\t\t}\n\t\tif (!graphql.isObjectType(gqlType)) {\n\t\t\tthrow new Error(`In your schema ${modelName} is not an object, which we can only make resolver types for`)\n\t\t}\n\t\tconst fields = gqlType.getFields()\n\t\t// See: https://github.com/redwoodjs/redwood/pull/6228#issue-1342966511\n\t\t// For more ideas\n\t\tconst hasGenerics = modelFacts.hasGenericArg\n\t\t// This is what they would have to write\n\t\tconst resolverInterface = fileDTS.addInterface({", "score": 0.8510286808013916 }, { "filename": "src/serviceFile.ts", "retrieved_chunk": "\t// The file we'll be creating in-memory throughout this fn\n\tconst fileDTS = context.tsProject.createSourceFile(`source/${fileKey}.d.ts`, \"\", { overwrite: true })\n\t// Basically if a top level resolver reference Query or Mutation\n\tconst knownSpecialCasesForGraphQL = new Set<string>()\n\t// Add the root function declarations\n\tconst rootResolvers = fileFacts.maybe_query_mutation?.resolvers\n\tif (rootResolvers)\n\t\trootResolvers.forEach((v) => {\n\t\t\tconst isQuery = v.name in queryType.getFields()\n\t\t\tconst isMutation = v.name in mutationType.getFields()", "score": 0.8464657068252563 } ]
typescript
const fact: ModelResolverFacts = fileFact[name] ?? {
import * as graphql from "graphql" import { AppContext } from "./context.js" import { formatDTS, getPrettierConfig } from "./formatDTS.js" import { getCodeFactsForJSTSFileAtPath } from "./serviceFile.codefacts.js" import { CodeFacts, ModelResolverFacts, ResolverFuncFact } from "./typeFacts.js" import { TypeMapper, typeMapper } from "./typeMap.js" import { capitalizeFirstLetter, createAndReferOrInlineArgsForField, inlineArgsForField } from "./utils.js" export const lookAtServiceFile = (file: string, context: AppContext) => { const { gql, prisma, pathSettings: settings, codeFacts: serviceFacts, fieldFacts } = context // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition if (!gql) throw new Error(`No schema when wanting to look at service file: ${file}`) if (!prisma) throw new Error(`No prisma schema when wanting to look at service file: ${file}`) // This isn't good enough, needs to be relative to api/src/services const fileKey = file.replace(settings.apiServicesPath, "") const thisFact: CodeFacts = {} const filename = context.basename(file) // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const queryType = gql.getQueryType()! if (!queryType) throw new Error("No query type") // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const mutationType = gql.getMutationType()! // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition if (!mutationType) throw new Error("No mutation type") const externalMapper = typeMapper(context, { preferPrismaModels: true }) const returnTypeMapper = typeMapper(context, {}) // The description of the source file const fileFacts = getCodeFactsForJSTSFileAtPath(file, context) if (Object.keys(fileFacts).length === 0) return // Tracks prospective prisma models which are used in the file const extraPrismaReferences = new Set<string>() // The file we'll be creating in-memory throughout this fn const fileDTS = context.tsProject.createSourceFile(`source/${fileKey}.d.ts`, "", { overwrite: true }) // Basically if a top level resolver reference Query or Mutation const knownSpecialCasesForGraphQL = new Set<string>() // Add the root function declarations const rootResolvers = fileFacts.maybe_query_mutation?.resolvers if (rootResolvers) rootResolvers.forEach((v) => { const isQuery = v.name in queryType.getFields() const isMutation = v.name in mutationType.getFields() const parentName = isQuery ? queryType.name : isMutation ? mutationType.name : undefined if (parentName) { addDefinitionsForTopLevelResolvers(parentName, v) } else { // Add warning about unused resolver fileDTS.addStatements(`\n// ${v.name} does not exist on Query or Mutation`) } }) // Add the root function declarations Object.values(fileFacts).forEach((model) => { if (!model) return const skip = ["maybe_query_mutation", queryType.name, mutationType.name] if (skip.includes(model.typeName)) return addCustomTypeModel(model) }) // Set up the module imports at the top const sharedGraphQLObjectsReferenced = externalMapper.getReferencedGraphQLThingsInMapping() const sharedGraphQLObjectsReferencedTypes = [...sharedGraphQLObjectsReferenced.types, ...knownSpecialCasesForGraphQL] const sharedInternalGraphQLObjectsReferenced = returnTypeMapper.getReferencedGraphQLThingsInMapping() const aliases = [...new Set([...sharedGraphQLObjectsReferenced.scalars, ...sharedInternalGraphQLObjectsReferenced.scalars])] if (aliases.length) { fileDTS.addTypeAliases( aliases.map((s) => ({ name: s, type: "any", })) ) } const prismases = [ ...new Set([ ...sharedGraphQLObjectsReferenced.prisma, ...sharedInternalGraphQLObjectsReferenced.prisma, ...extraPrismaReferences.values(), ]), ] const validPrismaObjs = prismases.filter((p) => prisma.has(p)) if (validPrismaObjs.length) { fileDTS.addImportDeclaration({ isTypeOnly: true, moduleSpecifier: "@prisma/client", namedImports: validPrismaObjs.map((p) => `${p} as P${p}`), }) } if (fileDTS.getText().includes("GraphQLResolveInfo")) { fileDTS.addImportDeclaration({ isTypeOnly: true, moduleSpecifier: "graphql", namedImports: ["GraphQLResolveInfo"], }) } if (fileDTS.getText().includes("RedwoodGraphQLContext")) { fileDTS.addImportDeclaration({ isTypeOnly: true, moduleSpecifier: "@redwoodjs/graphql-server/dist/types", namedImports: ["RedwoodGraphQLContext"], }) } if (sharedInternalGraphQLObjectsReferenced.types.length) { fileDTS.addImportDeclaration({ isTypeOnly: true, moduleSpecifier: `./${settings.sharedInternalFilename.replace(".d.ts", "")}`, namedImports: sharedInternalGraphQLObjectsReferenced.types.map((t) => `${t} as RT${t}`), }) } if (sharedGraphQLObjectsReferencedTypes.length) { fileDTS.addImportDeclaration({ isTypeOnly: true, moduleSpecifier: `./${settings.sharedFilename.replace(".d.ts", "")}`, namedImports: sharedGraphQLObjectsReferencedTypes, }) } serviceFacts.set(fileKey, thisFact) const dtsFilename = filename.endsWith(".ts") ? filename.replace(".ts", ".d.ts") : filename.replace(".js", ".d.ts") const dtsFilepath = context.join(context.pathSettings.typesFolderRoot, dtsFilename) // Some manual formatting tweaks so we align with Redwood's setup more const dts = fileDTS .getText() .replace(`from "graphql";`, `from "graphql";\n`) .replace(`from "@redwoodjs/graphql-server/dist/types";`, `from "@redwoodjs/graphql-server/dist/types";\n`) const shouldWriteDTS = !!dts.trim().length if (!shouldWriteDTS) return const config = getPrettierConfig(dtsFilepath) const formatted = formatDTS(dtsFilepath, dts, config)
context.sys.writeFile(dtsFilepath, formatted) return dtsFilepath function addDefinitionsForTopLevelResolvers(parentName: string, config: ResolverFuncFact) {
const { name } = config let field = queryType.getFields()[name] if (!field) { field = mutationType.getFields()[name] } const interfaceDeclaration = fileDTS.addInterface({ name: `${capitalizeFirstLetter(config.name)}Resolver`, isExported: true, docs: field.astNode ? ["SDL: " + graphql.print(field.astNode)] : ["@deprecated: Could not find this field in the schema for Mutation or Query"], }) const args = createAndReferOrInlineArgsForField(field, { name: interfaceDeclaration.getName(), file: fileDTS, mapper: externalMapper.map, }) if (parentName === queryType.name) knownSpecialCasesForGraphQL.add(queryType.name) if (parentName === mutationType.name) knownSpecialCasesForGraphQL.add(mutationType.name) const argsParam = args ?? "object" const returnType = returnTypeForResolver(returnTypeMapper, field, config) interfaceDeclaration.addCallSignature({ parameters: [ { name: "args", type: argsParam, hasQuestionToken: config.funcArgCount < 1 }, { name: "obj", type: `{ root: ${parentName}, context: RedwoodGraphQLContext, info: GraphQLResolveInfo }`, hasQuestionToken: config.funcArgCount < 2, }, ], returnType, }) } /** Ideally, we want to be able to write the type for just the object */ function addCustomTypeModel(modelFacts: ModelResolverFacts) { const modelName = modelFacts.typeName extraPrismaReferences.add(modelName) // Make an interface, this is the version we are replacing from graphql-codegen: // Account: MergePrismaWithSdlTypes<PrismaAccount, MakeRelationsOptional<Account, AllMappedModels>, AllMappedModels>; const gqlType = gql.getType(modelName) if (!gqlType) { // throw new Error(`Could not find a GraphQL type named ${d.getName()}`); fileDTS.addStatements(`\n// ${modelName} does not exist in the schema`) return } if (!graphql.isObjectType(gqlType)) { throw new Error(`In your schema ${modelName} is not an object, which we can only make resolver types for`) } const fields = gqlType.getFields() // See: https://github.com/redwoodjs/redwood/pull/6228#issue-1342966511 // For more ideas const hasGenerics = modelFacts.hasGenericArg // This is what they would have to write const resolverInterface = fileDTS.addInterface({ name: `${modelName}TypeResolvers`, typeParameters: hasGenerics ? ["Extended"] : [], isExported: true, }) // The parent type for the resolvers fileDTS.addTypeAlias({ name: `${modelName}AsParent`, typeParameters: hasGenerics ? ["Extended"] : [], type: `P${modelName} ${createParentAdditionallyDefinedFunctions()} ${hasGenerics ? " & Extended" : ""}`, // docs: ["The prisma model, mixed with fns already defined inside the resolvers."], }) const modelFieldFacts = fieldFacts.get(modelName) ?? {} // Loop through the resolvers, adding the fields which have resolvers implemented in the source file modelFacts.resolvers.forEach((resolver) => { const field = fields[resolver.name] if (field) { const fieldName = resolver.name if (modelFieldFacts[fieldName]) modelFieldFacts[fieldName].hasResolverImplementation = true else modelFieldFacts[fieldName] = { hasResolverImplementation: true } const argsType = inlineArgsForField(field, { mapper: externalMapper.map }) ?? "undefined" const param = hasGenerics ? "<Extended>" : "" const firstQ = resolver.funcArgCount < 1 ? "?" : "" const secondQ = resolver.funcArgCount < 2 ? "?" : "" const innerArgs = `args${firstQ}: ${argsType}, obj${secondQ}: { root: ${modelName}AsParent${param}, context: RedwoodGraphQLContext, info: GraphQLResolveInfo }` const returnType = returnTypeForResolver(returnTypeMapper, field, resolver) const docs = field.astNode ? [`SDL: ${graphql.print(field.astNode)}`] : [] // For speed we should switch this out to addProperties eventually resolverInterface.addProperty({ name: fieldName, leadingTrivia: "\n", docs, type: resolver.isFunc || resolver.isUnknown ? `(${innerArgs}) => ${returnType ?? "any"}` : returnType, }) } else { resolverInterface.addCallSignature({ docs: [` @deprecated: SDL ${modelName}.${resolver.name} does not exist in your schema`], }) } }) function createParentAdditionallyDefinedFunctions() { const fns: string[] = [] modelFacts.resolvers.forEach((resolver) => { const existsInGraphQLSchema = fields[resolver.name] if (!existsInGraphQLSchema) { console.warn( `The service file ${filename} has a field ${resolver.name} on ${modelName} that does not exist in the generated schema.graphql` ) } const prefix = !existsInGraphQLSchema ? "\n// This field does not exist in the generated schema.graphql\n" : "" const returnType = returnTypeForResolver(externalMapper, existsInGraphQLSchema, resolver) // fns.push(`${prefix}${resolver.name}: () => Promise<${externalMapper.map(type, {})}>`) fns.push(`${prefix}${resolver.name}: () => ${returnType}`) }) if (fns.length < 1) return "" return "& {" + fns.join(", \n") + "}" } fieldFacts.set(modelName, modelFieldFacts) } return dtsFilename } function returnTypeForResolver(mapper: TypeMapper, field: graphql.GraphQLField<unknown, unknown> | undefined, resolver: ResolverFuncFact) { if (!field) return "void" const tType = mapper.map(field.type, { preferNullOverUndefined: true, typenamePrefix: "RT" }) ?? "void" let returnType = tType const all = `${tType} | Promise<${tType}> | (() => Promise<${tType}>)` if (resolver.isFunc && resolver.isAsync) returnType = `Promise<${tType}>` else if (resolver.isFunc) returnType = all else if (resolver.isObjLiteral) returnType = tType else if (resolver.isUnknown) returnType = all return returnType }
src/serviceFile.ts
sdl-codegen-sdl-codegen-de2b8aa
[ { "filename": "src/sharedSchema.ts", "retrieved_chunk": "\t\t\t})\n\t\t})\n\t}\n\tconst fullPath = context.join(context.pathSettings.typesFolderRoot, context.pathSettings.sharedInternalFilename)\n\tconst config = getPrettierConfig(fullPath)\n\tconst formatted = formatDTS(fullPath, externalTSFile.getText(), config)\n\tcontext.sys.writeFile(fullPath, formatted)\n}", "score": 0.8761507272720337 }, { "filename": "src/sharedSchema.ts", "retrieved_chunk": "\t\t\t}))\n\t\t)\n\t}\n\tconst fullPath = context.join(context.pathSettings.typesFolderRoot, context.pathSettings.sharedFilename)\n\tconst config = getPrettierConfig(fullPath)\n\tconst formatted = formatDTS(fullPath, externalTSFile.getText(), config)\n\tcontext.sys.writeFile(fullPath, formatted)\n}\nfunction createSharedReturnPositionSchemaFile(context: AppContext) {\n\tconst { gql, prisma, fieldFacts } = context", "score": 0.854227602481842 }, { "filename": "src/sharedSchema.ts", "retrieved_chunk": "\tconst types = gql.getTypeMap()\n\tconst mapper = typeMapper(context, { preferPrismaModels: true })\n\tconst typesToImport = [] as string[]\n\tconst knownPrimitives = [\"String\", \"Boolean\", \"Int\"]\n\tconst externalTSFile = context.tsProject.createSourceFile(\n\t\t`/source/${context.pathSettings.sharedInternalFilename}`,\n\t\t`\n// You may very reasonably ask yourself, 'what is this file?' and why do I need it.\n// Roughly, this file ensures that when a resolver wants to return a type - that\n// type will match a prisma model. This is useful because you can trivially extend", "score": 0.846400797367096 }, { "filename": "src/serviceFile.codefacts.ts", "retrieved_chunk": "\tconst referenceFileSourceFile = context.tsProject.createSourceFile(`/source/${fileKey}`, fileContents, { overwrite: true })\n\tconst vars = referenceFileSourceFile.getVariableDeclarations().filter((v) => v.isExported())\n\tconst resolverContainers = vars.filter(varStartsWithUppercase)\n\tconst queryOrMutationResolvers = vars.filter((v) => !varStartsWithUppercase(v))\n\tqueryOrMutationResolvers.forEach((v) => {\n\t\tconst parent = \"maybe_query_mutation\"\n\t\tconst facts = getResolverInformationForDeclaration(v.getInitializer())\n\t\t// Start making facts about the services\n\t\tconst fact: ModelResolverFacts = fileFact[parent] ?? {\n\t\t\ttypeName: parent,", "score": 0.846031129360199 }, { "filename": "src/sharedSchema.ts", "retrieved_chunk": "\tconst externalTSFile = context.tsProject.createSourceFile(`/source/${context.pathSettings.sharedFilename}`, \"\")\n\tObject.keys(types).forEach((name) => {\n\t\tif (name.startsWith(\"__\")) {\n\t\t\treturn\n\t\t}\n\t\tif (knownPrimitives.includes(name)) {\n\t\t\treturn\n\t\t}\n\t\tconst type = types[name]\n\t\tconst pType = prisma.get(name)", "score": 0.8350727558135986 } ]
typescript
context.sys.writeFile(dtsFilepath, formatted) return dtsFilepath function addDefinitionsForTopLevelResolvers(parentName: string, config: ResolverFuncFact) {
import * as graphql from "graphql" import { AppContext } from "./context.js" import { formatDTS, getPrettierConfig } from "./formatDTS.js" import { getCodeFactsForJSTSFileAtPath } from "./serviceFile.codefacts.js" import { CodeFacts, ModelResolverFacts, ResolverFuncFact } from "./typeFacts.js" import { TypeMapper, typeMapper } from "./typeMap.js" import { capitalizeFirstLetter, createAndReferOrInlineArgsForField, inlineArgsForField } from "./utils.js" export const lookAtServiceFile = (file: string, context: AppContext) => { const { gql, prisma, pathSettings: settings, codeFacts: serviceFacts, fieldFacts } = context // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition if (!gql) throw new Error(`No schema when wanting to look at service file: ${file}`) if (!prisma) throw new Error(`No prisma schema when wanting to look at service file: ${file}`) // This isn't good enough, needs to be relative to api/src/services const fileKey = file.replace(settings.apiServicesPath, "") const thisFact: CodeFacts = {} const filename = context.basename(file) // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const queryType = gql.getQueryType()! if (!queryType) throw new Error("No query type") // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const mutationType = gql.getMutationType()! // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition if (!mutationType) throw new Error("No mutation type") const externalMapper = typeMapper(context, { preferPrismaModels: true }) const returnTypeMapper = typeMapper(context, {}) // The description of the source file const fileFacts = getCodeFactsForJSTSFileAtPath(file, context) if (Object.keys(fileFacts).length === 0) return // Tracks prospective prisma models which are used in the file const extraPrismaReferences = new Set<string>() // The file we'll be creating in-memory throughout this fn const fileDTS = context.tsProject.createSourceFile(`source/${fileKey}.d.ts`, "", { overwrite: true }) // Basically if a top level resolver reference Query or Mutation const knownSpecialCasesForGraphQL = new Set<string>() // Add the root function declarations const rootResolvers = fileFacts.maybe_query_mutation?.resolvers if (rootResolvers) rootResolvers.forEach((v) => { const isQuery = v.name in queryType.getFields() const isMutation = v.name in mutationType.getFields() const parentName = isQuery ? queryType.name : isMutation ? mutationType.name : undefined if (parentName) { addDefinitionsForTopLevelResolvers(parentName, v) } else { // Add warning about unused resolver fileDTS.addStatements(`\n// ${v.name} does not exist on Query or Mutation`) } }) // Add the root function declarations Object.values(fileFacts).forEach((model) => { if (!model) return const skip = ["maybe_query_mutation", queryType.name, mutationType.name] if (skip.includes(model.typeName)) return addCustomTypeModel(model) }) // Set up the module imports at the top const sharedGraphQLObjectsReferenced = externalMapper.getReferencedGraphQLThingsInMapping() const sharedGraphQLObjectsReferencedTypes = [...sharedGraphQLObjectsReferenced.types, ...knownSpecialCasesForGraphQL] const sharedInternalGraphQLObjectsReferenced = returnTypeMapper.getReferencedGraphQLThingsInMapping() const aliases = [...new Set([...sharedGraphQLObjectsReferenced.scalars, ...sharedInternalGraphQLObjectsReferenced.scalars])] if (aliases.length) { fileDTS.addTypeAliases( aliases.map((s) => ({ name: s, type: "any", })) ) } const prismases = [ ...new Set([ ...sharedGraphQLObjectsReferenced.prisma, ...sharedInternalGraphQLObjectsReferenced.prisma, ...extraPrismaReferences.values(), ]), ] const validPrismaObjs = prismases.filter((p) => prisma.has(p)) if (validPrismaObjs.length) { fileDTS.addImportDeclaration({ isTypeOnly: true, moduleSpecifier: "@prisma/client", namedImports: validPrismaObjs.map((p) => `${p} as P${p}`), }) } if (fileDTS.getText().includes("GraphQLResolveInfo")) { fileDTS.addImportDeclaration({ isTypeOnly: true, moduleSpecifier: "graphql", namedImports: ["GraphQLResolveInfo"], }) } if (fileDTS.getText().includes("RedwoodGraphQLContext")) { fileDTS.addImportDeclaration({ isTypeOnly: true, moduleSpecifier: "@redwoodjs/graphql-server/dist/types", namedImports: ["RedwoodGraphQLContext"], }) } if (sharedInternalGraphQLObjectsReferenced.types.length) { fileDTS.addImportDeclaration({ isTypeOnly: true, moduleSpecifier: `./${settings.sharedInternalFilename.replace(".d.ts", "")}`, namedImports: sharedInternalGraphQLObjectsReferenced.types.map((t) => `${t} as RT${t}`), }) } if (sharedGraphQLObjectsReferencedTypes.length) { fileDTS.addImportDeclaration({ isTypeOnly: true, moduleSpecifier: `./${settings.sharedFilename.replace(".d.ts", "")}`, namedImports: sharedGraphQLObjectsReferencedTypes, }) } serviceFacts.set(fileKey, thisFact) const dtsFilename = filename.endsWith(".ts") ? filename.replace(".ts", ".d.ts") : filename.replace(".js", ".d.ts") const dtsFilepath = context.join(context.pathSettings.typesFolderRoot, dtsFilename) // Some manual formatting tweaks so we align with Redwood's setup more const dts = fileDTS .getText() .replace(`from "graphql";`, `from "graphql";\n`) .replace(`from "@redwoodjs/graphql-server/dist/types";`, `from "@redwoodjs/graphql-server/dist/types";\n`) const shouldWriteDTS = !!dts.trim().length if (!shouldWriteDTS) return const config = getPrettierConfig(dtsFilepath) const formatted = formatDTS(dtsFilepath, dts, config) context.sys.writeFile(dtsFilepath, formatted) return dtsFilepath function addDefinitionsForTopLevelResolvers(parentName: string, config: ResolverFuncFact) { const { name } = config let field = queryType.getFields()[name] if (!field) { field = mutationType.getFields()[name] } const interfaceDeclaration = fileDTS.addInterface({ name: `${capitalizeFirstLetter(config.name)}Resolver`, isExported: true, docs: field.astNode ? ["SDL: " + graphql.print(field.astNode)] : ["@deprecated: Could not find this field in the schema for Mutation or Query"], }) const args = createAndReferOrInlineArgsForField(field, { name: interfaceDeclaration.getName(), file: fileDTS, mapper: externalMapper.map, }) if (parentName === queryType.name) knownSpecialCasesForGraphQL.add(queryType.name) if (parentName === mutationType.name) knownSpecialCasesForGraphQL.add(mutationType.name) const argsParam = args ?? "object" const returnType = returnTypeForResolver(returnTypeMapper, field, config) interfaceDeclaration.addCallSignature({ parameters: [ { name: "args", type: argsParam, hasQuestionToken: config.funcArgCount < 1 }, { name: "obj", type: `{ root: ${parentName}, context: RedwoodGraphQLContext, info: GraphQLResolveInfo }`, hasQuestionToken: config.funcArgCount < 2, }, ], returnType, }) } /** Ideally, we want to be able to write the type for just the object */ function addCustomTypeModel(modelFacts: ModelResolverFacts) {
const modelName = modelFacts.typeName extraPrismaReferences.add(modelName) // Make an interface, this is the version we are replacing from graphql-codegen: // Account: MergePrismaWithSdlTypes<PrismaAccount, MakeRelationsOptional<Account, AllMappedModels>, AllMappedModels>;
const gqlType = gql.getType(modelName) if (!gqlType) { // throw new Error(`Could not find a GraphQL type named ${d.getName()}`); fileDTS.addStatements(`\n// ${modelName} does not exist in the schema`) return } if (!graphql.isObjectType(gqlType)) { throw new Error(`In your schema ${modelName} is not an object, which we can only make resolver types for`) } const fields = gqlType.getFields() // See: https://github.com/redwoodjs/redwood/pull/6228#issue-1342966511 // For more ideas const hasGenerics = modelFacts.hasGenericArg // This is what they would have to write const resolverInterface = fileDTS.addInterface({ name: `${modelName}TypeResolvers`, typeParameters: hasGenerics ? ["Extended"] : [], isExported: true, }) // The parent type for the resolvers fileDTS.addTypeAlias({ name: `${modelName}AsParent`, typeParameters: hasGenerics ? ["Extended"] : [], type: `P${modelName} ${createParentAdditionallyDefinedFunctions()} ${hasGenerics ? " & Extended" : ""}`, // docs: ["The prisma model, mixed with fns already defined inside the resolvers."], }) const modelFieldFacts = fieldFacts.get(modelName) ?? {} // Loop through the resolvers, adding the fields which have resolvers implemented in the source file modelFacts.resolvers.forEach((resolver) => { const field = fields[resolver.name] if (field) { const fieldName = resolver.name if (modelFieldFacts[fieldName]) modelFieldFacts[fieldName].hasResolverImplementation = true else modelFieldFacts[fieldName] = { hasResolverImplementation: true } const argsType = inlineArgsForField(field, { mapper: externalMapper.map }) ?? "undefined" const param = hasGenerics ? "<Extended>" : "" const firstQ = resolver.funcArgCount < 1 ? "?" : "" const secondQ = resolver.funcArgCount < 2 ? "?" : "" const innerArgs = `args${firstQ}: ${argsType}, obj${secondQ}: { root: ${modelName}AsParent${param}, context: RedwoodGraphQLContext, info: GraphQLResolveInfo }` const returnType = returnTypeForResolver(returnTypeMapper, field, resolver) const docs = field.astNode ? [`SDL: ${graphql.print(field.astNode)}`] : [] // For speed we should switch this out to addProperties eventually resolverInterface.addProperty({ name: fieldName, leadingTrivia: "\n", docs, type: resolver.isFunc || resolver.isUnknown ? `(${innerArgs}) => ${returnType ?? "any"}` : returnType, }) } else { resolverInterface.addCallSignature({ docs: [` @deprecated: SDL ${modelName}.${resolver.name} does not exist in your schema`], }) } }) function createParentAdditionallyDefinedFunctions() { const fns: string[] = [] modelFacts.resolvers.forEach((resolver) => { const existsInGraphQLSchema = fields[resolver.name] if (!existsInGraphQLSchema) { console.warn( `The service file ${filename} has a field ${resolver.name} on ${modelName} that does not exist in the generated schema.graphql` ) } const prefix = !existsInGraphQLSchema ? "\n// This field does not exist in the generated schema.graphql\n" : "" const returnType = returnTypeForResolver(externalMapper, existsInGraphQLSchema, resolver) // fns.push(`${prefix}${resolver.name}: () => Promise<${externalMapper.map(type, {})}>`) fns.push(`${prefix}${resolver.name}: () => ${returnType}`) }) if (fns.length < 1) return "" return "& {" + fns.join(", \n") + "}" } fieldFacts.set(modelName, modelFieldFacts) } return dtsFilename } function returnTypeForResolver(mapper: TypeMapper, field: graphql.GraphQLField<unknown, unknown> | undefined, resolver: ResolverFuncFact) { if (!field) return "void" const tType = mapper.map(field.type, { preferNullOverUndefined: true, typenamePrefix: "RT" }) ?? "void" let returnType = tType const all = `${tType} | Promise<${tType}> | (() => Promise<${tType}>)` if (resolver.isFunc && resolver.isAsync) returnType = `Promise<${tType}>` else if (resolver.isFunc) returnType = all else if (resolver.isObjLiteral) returnType = tType else if (resolver.isUnknown) returnType = all return returnType }
src/serviceFile.ts
sdl-codegen-sdl-codegen-de2b8aa
[ { "filename": "src/serviceFile.codefacts.ts", "retrieved_chunk": "\treturn fileFact\n\tfunction addCustomTypeResolvers(variableDeclaration: tsMorph.VariableDeclaration) {\n\t\tconst declarations = variableDeclaration.getVariableStatementOrThrow().getDeclarations()\n\t\tdeclarations.forEach((d) => {\n\t\t\tconst name = d.getName()\n\t\t\t// only do it if the first letter is a capital\n\t\t\tif (!name.match(/^[A-Z]/)) return\n\t\t\tconst type = d.getType()\n\t\t\tconst hasGenericArg = type.getText().includes(\"<\")\n\t\t\t// Start making facts about the services", "score": 0.8182286024093628 }, { "filename": "src/sharedSchema.ts", "retrieved_chunk": "\tconst types = gql.getTypeMap()\n\tconst mapper = typeMapper(context, { preferPrismaModels: true })\n\tconst typesToImport = [] as string[]\n\tconst knownPrimitives = [\"String\", \"Boolean\", \"Int\"]\n\tconst externalTSFile = context.tsProject.createSourceFile(\n\t\t`/source/${context.pathSettings.sharedInternalFilename}`,\n\t\t`\n// You may very reasonably ask yourself, 'what is this file?' and why do I need it.\n// Roughly, this file ensures that when a resolver wants to return a type - that\n// type will match a prisma model. This is useful because you can trivially extend", "score": 0.8181612491607666 }, { "filename": "src/typeFacts.ts", "retrieved_chunk": "export type FieldFacts = Record<string, FieldFact>\nexport interface FieldFact {\n\thasResolverImplementation?: true\n\t// isPrismaBacked?: true;\n}\n// The data-model for the service file which contains the SDL matched functions\n/** A representation of the code inside the source file's */\nexport type CodeFacts = Record<string, ModelResolverFacts | undefined>\nexport interface ModelResolverFacts {\n\t/** Should we type the type as a generic with an override */", "score": 0.8141096830368042 }, { "filename": "src/typeMap.ts", "retrieved_chunk": "\t\t\t\t\tcase \"String\":\n\t\t\t\t\t\treturn \"string\"\n\t\t\t\t\tcase \"Boolean\":\n\t\t\t\t\t\treturn \"boolean\"\n\t\t\t\t}\n\t\t\t\tcustomScalars.add(type.name)\n\t\t\t\treturn type.name\n\t\t\t}\n\t\t\tif (graphql.isObjectType(type)) {\n\t\t\t\tif (config.preferPrismaModels && context.prisma.has(type.name)) {", "score": 0.8114364147186279 }, { "filename": "src/sharedSchema.ts", "retrieved_chunk": "\t\tif (graphql.isObjectType(type) || graphql.isInterfaceType(type) || graphql.isInputObjectType(type)) {\n\t\t\t// This is slower than it could be, use the add many at once api\n\t\t\tconst docs = []\n\t\t\tif (pType?.leadingComments) {\n\t\t\t\tdocs.push(pType.leadingComments)\n\t\t\t}\n\t\t\tif (type.description) {\n\t\t\t\tdocs.push(type.description)\n\t\t\t}\n\t\t\texternalTSFile.addInterface({", "score": 0.8109842538833618 } ]
typescript
const modelName = modelFacts.typeName extraPrismaReferences.add(modelName) // Make an interface, this is the version we are replacing from graphql-codegen: // Account: MergePrismaWithSdlTypes<PrismaAccount, MakeRelationsOptional<Account, AllMappedModels>, AllMappedModels>;
/// The main schema for objects and inputs import * as graphql from "graphql" import * as tsMorph from "ts-morph" import { AppContext } from "./context.js" import { formatDTS, getPrettierConfig } from "./formatDTS.js" import { typeMapper } from "./typeMap.js" export const createSharedSchemaFiles = (context: AppContext) => { createSharedExternalSchemaFile(context) createSharedReturnPositionSchemaFile(context) return [ context.join(context.pathSettings.typesFolderRoot, context.pathSettings.sharedFilename), context.join(context.pathSettings.typesFolderRoot, context.pathSettings.sharedInternalFilename), ] } function createSharedExternalSchemaFile(context: AppContext) { const gql = context.gql const types = gql.getTypeMap() const knownPrimitives = ["String", "Boolean", "Int"] const { prisma, fieldFacts } = context const mapper = typeMapper(context, {}) const externalTSFile = context.tsProject.createSourceFile(`/source/${context.pathSettings.sharedFilename}`, "") Object.keys(types).forEach((name) => { if (name.startsWith("__")) { return } if (knownPrimitives.includes(name)) { return } const type = types[name] const pType = prisma.get(name) if (graphql.isObjectType(type) || graphql.isInterfaceType(type) || graphql.isInputObjectType(type)) { // This is slower than it could be, use the add many at once api const docs = [] if (pType?.leadingComments) { docs.push(pType.leadingComments) } if (type.description) { docs.push(type.description) } externalTSFile.addInterface({ name: type.name, isExported: true, docs: [], properties: [ { name: "__typename", type: `"${type.name}"`, hasQuestionToken: true, }, ...Object.entries(type.getFields()).map(([fieldName, obj]: [string, graphql.GraphQLField<object, object>]) => { const docs = [] const prismaField = pType?.properties.get(fieldName) const type = obj.type as graphql.GraphQLType if (prismaField?.leadingComments.length) { docs.push(prismaField.leadingComments.trim()) } // if (obj.description) docs.push(obj.description); const hasResolverImplementation = fieldFacts.get(name)?.[fieldName]?.hasResolverImplementation const isOptionalInSDL = !graphql.isNonNullType(type) const doesNotExistInPrisma = false // !prismaField; const field: tsMorph.OptionalKind<tsMorph.PropertySignatureStructure> = { name: fieldName, type: mapper.map(type, { preferNullOverUndefined: true }), docs, hasQuestionToken: hasResolverImplementation ?? (isOptionalInSDL || doesNotExistInPrisma), } return field }), ], }) } if (graphql.isEnumType(type)) { externalTSFile.addTypeAlias({ name: type.name, type: '"' + type .getValues() .map((m) => (m as { value: string }).value) .join('" | "') + '"', }) } }) const { scalars } = mapper.getReferencedGraphQLThingsInMapping() if (scalars.length) { externalTSFile.addTypeAliases( scalars.map((s) => ({ name: s, type: "any", })) ) } const fullPath = context.join(context.pathSettings.typesFolderRoot, context.pathSettings.sharedFilename) const config = getPrettierConfig(fullPath) const formatted
= formatDTS(fullPath, externalTSFile.getText(), config) context.sys.writeFile(fullPath, formatted) }
function createSharedReturnPositionSchemaFile(context: AppContext) { const { gql, prisma, fieldFacts } = context const types = gql.getTypeMap() const mapper = typeMapper(context, { preferPrismaModels: true }) const typesToImport = [] as string[] const knownPrimitives = ["String", "Boolean", "Int"] const externalTSFile = context.tsProject.createSourceFile( `/source/${context.pathSettings.sharedInternalFilename}`, ` // You may very reasonably ask yourself, 'what is this file?' and why do I need it. // Roughly, this file ensures that when a resolver wants to return a type - that // type will match a prisma model. This is useful because you can trivially extend // the type in the SDL and not have to worry about type mis-matches because the thing // you returned does not include those functions. // This gets particularly valuable when you want to return a union type, an interface, // or a model where the prisma model is nested pretty deeply (GraphQL connections, for example.) ` ) Object.keys(types).forEach((name) => { if (name.startsWith("__")) { return } if (knownPrimitives.includes(name)) { return } const type = types[name] const pType = prisma.get(name) if (graphql.isObjectType(type) || graphql.isInterfaceType(type) || graphql.isInputObjectType(type)) { // Return straight away if we have a matching type in the prisma schema // as we dont need it if (pType) { typesToImport.push(name) return } externalTSFile.addInterface({ name: type.name, isExported: true, docs: [], properties: [ { name: "__typename", type: `"${type.name}"`, hasQuestionToken: true, }, ...Object.entries(type.getFields()).map(([fieldName, obj]: [string, graphql.GraphQLField<object, object>]) => { const hasResolverImplementation = fieldFacts.get(name)?.[fieldName]?.hasResolverImplementation const isOptionalInSDL = !graphql.isNonNullType(obj.type) const doesNotExistInPrisma = false // !prismaField; const field: tsMorph.OptionalKind<tsMorph.PropertySignatureStructure> = { name: fieldName, type: mapper.map(obj.type, { preferNullOverUndefined: true }), hasQuestionToken: hasResolverImplementation || isOptionalInSDL || doesNotExistInPrisma, } return field }), ], }) } if (graphql.isEnumType(type)) { externalTSFile.addTypeAlias({ name: type.name, type: '"' + type .getValues() .map((m) => (m as { value: string }).value) .join('" | "') + '"', }) } }) const { scalars, prisma: prismaModels } = mapper.getReferencedGraphQLThingsInMapping() if (scalars.length) { externalTSFile.addTypeAliases( scalars.map((s) => ({ name: s, type: "any", })) ) } const allPrismaModels = [...new Set([...prismaModels, ...typesToImport])].sort() if (allPrismaModels.length) { externalTSFile.addImportDeclaration({ isTypeOnly: true, moduleSpecifier: `@prisma/client`, namedImports: allPrismaModels.map((p) => `${p} as P${p}`), }) allPrismaModels.forEach((p) => { externalTSFile.addTypeAlias({ isExported: true, name: p, type: `P${p}`, }) }) } const fullPath = context.join(context.pathSettings.typesFolderRoot, context.pathSettings.sharedInternalFilename) const config = getPrettierConfig(fullPath) const formatted = formatDTS(fullPath, externalTSFile.getText(), config) context.sys.writeFile(fullPath, formatted) }
src/sharedSchema.ts
sdl-codegen-sdl-codegen-de2b8aa
[ { "filename": "src/serviceFile.ts", "retrieved_chunk": "\tif (!shouldWriteDTS) return\n\tconst config = getPrettierConfig(dtsFilepath)\n\tconst formatted = formatDTS(dtsFilepath, dts, config)\n\tcontext.sys.writeFile(dtsFilepath, formatted)\n\treturn dtsFilepath\n\tfunction addDefinitionsForTopLevelResolvers(parentName: string, config: ResolverFuncFact) {\n\t\tconst { name } = config\n\t\tlet field = queryType.getFields()[name]\n\t\tif (!field) {\n\t\t\tfield = mutationType.getFields()[name]", "score": 0.8682551383972168 }, { "filename": "src/serviceFile.ts", "retrieved_chunk": "\t}\n\tserviceFacts.set(fileKey, thisFact)\n\tconst dtsFilename = filename.endsWith(\".ts\") ? filename.replace(\".ts\", \".d.ts\") : filename.replace(\".js\", \".d.ts\")\n\tconst dtsFilepath = context.join(context.pathSettings.typesFolderRoot, dtsFilename)\n\t// Some manual formatting tweaks so we align with Redwood's setup more\n\tconst dts = fileDTS\n\t\t.getText()\n\t\t.replace(`from \"graphql\";`, `from \"graphql\";\\n`)\n\t\t.replace(`from \"@redwoodjs/graphql-server/dist/types\";`, `from \"@redwoodjs/graphql-server/dist/types\";\\n`)\n\tconst shouldWriteDTS = !!dts.trim().length", "score": 0.8393824100494385 }, { "filename": "src/run.ts", "retrieved_chunk": "\t\t// \tcmd: [\"yarn\", \"eslint\", \"--fix\", \"--ext\", \".d.ts\", appContext.settings.typesFolderRoot],\n\t\t// \tstdin: \"inherit\",\n\t\t// \tstdout: \"inherit\",\n\t\t// })\n\t\t// await process.status()\n\t}\n\tif (sys.deleteFile && config.deleteOldGraphQLDTS) {\n\t\tconsole.log(\"Deleting old graphql.d.ts\")\n\t\tsys.deleteFile(join(appRoot, \"api\", \"src\", \"graphql.d.ts\"))\n\t}", "score": 0.8371486663818359 }, { "filename": "src/serviceFile.ts", "retrieved_chunk": "\tconst mutationType = gql.getMutationType()!\n\t// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n\tif (!mutationType) throw new Error(\"No mutation type\")\n\tconst externalMapper = typeMapper(context, { preferPrismaModels: true })\n\tconst returnTypeMapper = typeMapper(context, {})\n\t// The description of the source file\n\tconst fileFacts = getCodeFactsForJSTSFileAtPath(file, context)\n\tif (Object.keys(fileFacts).length === 0) return\n\t// Tracks prospective prisma models which are used in the file\n\tconst extraPrismaReferences = new Set<string>()", "score": 0.8300657272338867 }, { "filename": "src/serviceFile.ts", "retrieved_chunk": "\tif (fileDTS.getText().includes(\"RedwoodGraphQLContext\")) {\n\t\tfileDTS.addImportDeclaration({\n\t\t\tisTypeOnly: true,\n\t\t\tmoduleSpecifier: \"@redwoodjs/graphql-server/dist/types\",\n\t\t\tnamedImports: [\"RedwoodGraphQLContext\"],\n\t\t})\n\t}\n\tif (sharedInternalGraphQLObjectsReferenced.types.length) {\n\t\tfileDTS.addImportDeclaration({\n\t\t\tisTypeOnly: true,", "score": 0.8247482776641846 } ]
typescript
= formatDTS(fullPath, externalTSFile.getText(), config) context.sys.writeFile(fullPath, formatted) }
import * as graphql from "graphql" import { AppContext } from "./context.js" import { formatDTS, getPrettierConfig } from "./formatDTS.js" import { getCodeFactsForJSTSFileAtPath } from "./serviceFile.codefacts.js" import { CodeFacts, ModelResolverFacts, ResolverFuncFact } from "./typeFacts.js" import { TypeMapper, typeMapper } from "./typeMap.js" import { capitalizeFirstLetter, createAndReferOrInlineArgsForField, inlineArgsForField } from "./utils.js" export const lookAtServiceFile = (file: string, context: AppContext) => { const { gql, prisma, pathSettings: settings, codeFacts: serviceFacts, fieldFacts } = context // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition if (!gql) throw new Error(`No schema when wanting to look at service file: ${file}`) if (!prisma) throw new Error(`No prisma schema when wanting to look at service file: ${file}`) // This isn't good enough, needs to be relative to api/src/services const fileKey = file.replace(settings.apiServicesPath, "") const thisFact: CodeFacts = {} const filename = context.basename(file) // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const queryType = gql.getQueryType()! if (!queryType) throw new Error("No query type") // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const mutationType = gql.getMutationType()! // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition if (!mutationType) throw new Error("No mutation type") const externalMapper = typeMapper(context, { preferPrismaModels: true }) const returnTypeMapper = typeMapper(context, {}) // The description of the source file const fileFacts = getCodeFactsForJSTSFileAtPath(file, context) if (Object.keys(fileFacts).length === 0) return // Tracks prospective prisma models which are used in the file const extraPrismaReferences = new Set<string>() // The file we'll be creating in-memory throughout this fn const fileDTS = context.tsProject.createSourceFile(`source/${fileKey}.d.ts`, "", { overwrite: true }) // Basically if a top level resolver reference Query or Mutation const knownSpecialCasesForGraphQL = new Set<string>() // Add the root function declarations const rootResolvers = fileFacts.maybe_query_mutation?.resolvers if (rootResolvers) rootResolvers.forEach((v) => { const isQuery = v.name in queryType.getFields() const isMutation = v.name in mutationType.getFields() const parentName = isQuery ? queryType.name : isMutation ? mutationType.name : undefined if (parentName) { addDefinitionsForTopLevelResolvers(parentName, v) } else { // Add warning about unused resolver fileDTS.addStatements(`\n// ${v.name} does not exist on Query or Mutation`) } }) // Add the root function declarations Object.values(fileFacts).forEach((model) => { if (!model) return const skip = ["maybe_query_mutation", queryType.name, mutationType.name] if (skip.includes(model.typeName)) return addCustomTypeModel(model) }) // Set up the module imports at the top const sharedGraphQLObjectsReferenced = externalMapper.getReferencedGraphQLThingsInMapping() const sharedGraphQLObjectsReferencedTypes = [...sharedGraphQLObjectsReferenced.types, ...knownSpecialCasesForGraphQL] const sharedInternalGraphQLObjectsReferenced = returnTypeMapper.getReferencedGraphQLThingsInMapping() const aliases = [...new Set([...sharedGraphQLObjectsReferenced.scalars, ...sharedInternalGraphQLObjectsReferenced.scalars])] if (aliases.length) { fileDTS.addTypeAliases( aliases.map((s) => ({ name: s, type: "any", })) ) } const prismases = [ ...new Set([ ...sharedGraphQLObjectsReferenced.prisma, ...sharedInternalGraphQLObjectsReferenced.prisma, ...extraPrismaReferences.values(), ]), ] const validPrismaObjs = prismases.filter((p) => prisma.has(p)) if (validPrismaObjs.length) { fileDTS.addImportDeclaration({ isTypeOnly: true, moduleSpecifier: "@prisma/client", namedImports: validPrismaObjs.map((p) => `${p} as P${p}`), }) } if (fileDTS.getText().includes("GraphQLResolveInfo")) { fileDTS.addImportDeclaration({ isTypeOnly: true, moduleSpecifier: "graphql", namedImports: ["GraphQLResolveInfo"], }) } if (fileDTS.getText().includes("RedwoodGraphQLContext")) { fileDTS.addImportDeclaration({ isTypeOnly: true, moduleSpecifier: "@redwoodjs/graphql-server/dist/types", namedImports: ["RedwoodGraphQLContext"], }) } if (sharedInternalGraphQLObjectsReferenced.types.length) { fileDTS.addImportDeclaration({ isTypeOnly: true, moduleSpecifier: `./${settings.sharedInternalFilename.replace(".d.ts", "")}`, namedImports: sharedInternalGraphQLObjectsReferenced.types.map((t) => `${t} as RT${t}`), }) } if (sharedGraphQLObjectsReferencedTypes.length) { fileDTS.addImportDeclaration({ isTypeOnly: true, moduleSpecifier: `./${settings.sharedFilename.replace(".d.ts", "")}`, namedImports: sharedGraphQLObjectsReferencedTypes, }) } serviceFacts.set(fileKey, thisFact) const dtsFilename = filename.endsWith(".ts") ? filename.replace(".ts", ".d.ts") : filename.replace(".js", ".d.ts") const dtsFilepath = context.join(context.pathSettings.typesFolderRoot, dtsFilename) // Some manual formatting tweaks so we align with Redwood's setup more const dts = fileDTS .getText() .replace(`from "graphql";`, `from "graphql";\n`) .replace(`from "@redwoodjs/graphql-server/dist/types";`, `from "@redwoodjs/graphql-server/dist/types";\n`) const shouldWriteDTS = !!dts.trim().length if (!shouldWriteDTS) return const config = getPrettierConfig(dtsFilepath) const formatted = formatDTS(dtsFilepath, dts, config) context.sys.writeFile(dtsFilepath, formatted) return dtsFilepath function addDefinitionsForTopLevelResolvers(parentName: string, config: ResolverFuncFact) { const { name } = config let field = queryType.getFields()[name] if (!field) { field = mutationType.getFields()[name] } const interfaceDeclaration = fileDTS.addInterface({ name: `${capitalizeFirstLetter(config.name)}Resolver`, isExported: true, docs: field.astNode ? ["SDL: " + graphql.print(field.astNode)] : ["@deprecated: Could not find this field in the schema for Mutation or Query"], }) const args = createAndReferOrInlineArgsForField(field, { name: interfaceDeclaration.getName(), file: fileDTS, mapper: externalMapper.map, }) if (parentName === queryType.name) knownSpecialCasesForGraphQL.add(queryType.name) if (parentName === mutationType.name) knownSpecialCasesForGraphQL.add(mutationType.name) const argsParam = args ?? "object" const returnType = returnTypeForResolver(returnTypeMapper, field, config) interfaceDeclaration.addCallSignature({ parameters: [ { name: "args", type: argsParam, hasQuestionToken: config.funcArgCount < 1 }, { name: "obj", type: `{ root: ${parentName}, context: RedwoodGraphQLContext, info: GraphQLResolveInfo }`, hasQuestionToken: config.funcArgCount < 2, }, ], returnType, }) } /** Ideally, we want to be able to write the type for just the object */ function addCustomTypeModel(modelFacts: ModelResolverFacts) { const modelName = modelFacts.typeName extraPrismaReferences.add(modelName) // Make an interface, this is the version we are replacing from graphql-codegen: // Account: MergePrismaWithSdlTypes<PrismaAccount, MakeRelationsOptional<Account, AllMappedModels>, AllMappedModels>; const gqlType = gql.getType(modelName) if (!gqlType) { // throw new Error(`Could not find a GraphQL type named ${d.getName()}`); fileDTS.addStatements(`\n// ${modelName} does not exist in the schema`) return } if (!graphql.isObjectType(gqlType)) { throw new Error(`In your schema ${modelName} is not an object, which we can only make resolver types for`) } const fields = gqlType.getFields() // See: https://github.com/redwoodjs/redwood/pull/6228#issue-1342966511 // For more ideas const hasGenerics = modelFacts.hasGenericArg // This is what they would have to write const resolverInterface = fileDTS.addInterface({ name: `${modelName}TypeResolvers`, typeParameters: hasGenerics ? ["Extended"] : [], isExported: true, }) // The parent type for the resolvers fileDTS.addTypeAlias({ name: `${modelName}AsParent`, typeParameters: hasGenerics ? ["Extended"] : [], type: `P${modelName} ${createParentAdditionallyDefinedFunctions()} ${hasGenerics ? " & Extended" : ""}`, // docs: ["The prisma model, mixed with fns already defined inside the resolvers."], }) const modelFieldFacts = fieldFacts.get(modelName) ?? {} // Loop through the resolvers, adding the fields which have resolvers implemented in the source file
modelFacts.resolvers.forEach((resolver) => {
const field = fields[resolver.name] if (field) { const fieldName = resolver.name if (modelFieldFacts[fieldName]) modelFieldFacts[fieldName].hasResolverImplementation = true else modelFieldFacts[fieldName] = { hasResolverImplementation: true } const argsType = inlineArgsForField(field, { mapper: externalMapper.map }) ?? "undefined" const param = hasGenerics ? "<Extended>" : "" const firstQ = resolver.funcArgCount < 1 ? "?" : "" const secondQ = resolver.funcArgCount < 2 ? "?" : "" const innerArgs = `args${firstQ}: ${argsType}, obj${secondQ}: { root: ${modelName}AsParent${param}, context: RedwoodGraphQLContext, info: GraphQLResolveInfo }` const returnType = returnTypeForResolver(returnTypeMapper, field, resolver) const docs = field.astNode ? [`SDL: ${graphql.print(field.astNode)}`] : [] // For speed we should switch this out to addProperties eventually resolverInterface.addProperty({ name: fieldName, leadingTrivia: "\n", docs, type: resolver.isFunc || resolver.isUnknown ? `(${innerArgs}) => ${returnType ?? "any"}` : returnType, }) } else { resolverInterface.addCallSignature({ docs: [` @deprecated: SDL ${modelName}.${resolver.name} does not exist in your schema`], }) } }) function createParentAdditionallyDefinedFunctions() { const fns: string[] = [] modelFacts.resolvers.forEach((resolver) => { const existsInGraphQLSchema = fields[resolver.name] if (!existsInGraphQLSchema) { console.warn( `The service file ${filename} has a field ${resolver.name} on ${modelName} that does not exist in the generated schema.graphql` ) } const prefix = !existsInGraphQLSchema ? "\n// This field does not exist in the generated schema.graphql\n" : "" const returnType = returnTypeForResolver(externalMapper, existsInGraphQLSchema, resolver) // fns.push(`${prefix}${resolver.name}: () => Promise<${externalMapper.map(type, {})}>`) fns.push(`${prefix}${resolver.name}: () => ${returnType}`) }) if (fns.length < 1) return "" return "& {" + fns.join(", \n") + "}" } fieldFacts.set(modelName, modelFieldFacts) } return dtsFilename } function returnTypeForResolver(mapper: TypeMapper, field: graphql.GraphQLField<unknown, unknown> | undefined, resolver: ResolverFuncFact) { if (!field) return "void" const tType = mapper.map(field.type, { preferNullOverUndefined: true, typenamePrefix: "RT" }) ?? "void" let returnType = tType const all = `${tType} | Promise<${tType}> | (() => Promise<${tType}>)` if (resolver.isFunc && resolver.isAsync) returnType = `Promise<${tType}>` else if (resolver.isFunc) returnType = all else if (resolver.isObjLiteral) returnType = tType else if (resolver.isUnknown) returnType = all return returnType }
src/serviceFile.ts
sdl-codegen-sdl-codegen-de2b8aa
[ { "filename": "src/serviceFile.codefacts.ts", "retrieved_chunk": "\t\t\tresolvers: new Map(),\n\t\t\thasGenericArg: false,\n\t\t}\n\t\tfact.resolvers.set(v.getName(), { name: v.getName(), ...facts })\n\t\tfileFact[parent] = fact\n\t})\n\t// Next all the capital consts\n\tresolverContainers.forEach((c) => {\n\t\taddCustomTypeResolvers(c)\n\t})", "score": 0.872158944606781 }, { "filename": "src/serviceFile.codefacts.ts", "retrieved_chunk": "\tconst referenceFileSourceFile = context.tsProject.createSourceFile(`/source/${fileKey}`, fileContents, { overwrite: true })\n\tconst vars = referenceFileSourceFile.getVariableDeclarations().filter((v) => v.isExported())\n\tconst resolverContainers = vars.filter(varStartsWithUppercase)\n\tconst queryOrMutationResolvers = vars.filter((v) => !varStartsWithUppercase(v))\n\tqueryOrMutationResolvers.forEach((v) => {\n\t\tconst parent = \"maybe_query_mutation\"\n\t\tconst facts = getResolverInformationForDeclaration(v.getInitializer())\n\t\t// Start making facts about the services\n\t\tconst fact: ModelResolverFacts = fileFact[parent] ?? {\n\t\t\ttypeName: parent,", "score": 0.8640913963317871 }, { "filename": "src/serviceFile.codefacts.ts", "retrieved_chunk": "\treturn fileFact\n\tfunction addCustomTypeResolvers(variableDeclaration: tsMorph.VariableDeclaration) {\n\t\tconst declarations = variableDeclaration.getVariableStatementOrThrow().getDeclarations()\n\t\tdeclarations.forEach((d) => {\n\t\t\tconst name = d.getName()\n\t\t\t// only do it if the first letter is a capital\n\t\t\tif (!name.match(/^[A-Z]/)) return\n\t\t\tconst type = d.getType()\n\t\t\tconst hasGenericArg = type.getText().includes(\"<\")\n\t\t\t// Start making facts about the services", "score": 0.8559221029281616 }, { "filename": "src/typeFacts.ts", "retrieved_chunk": "export type FieldFacts = Record<string, FieldFact>\nexport interface FieldFact {\n\thasResolverImplementation?: true\n\t// isPrismaBacked?: true;\n}\n// The data-model for the service file which contains the SDL matched functions\n/** A representation of the code inside the source file's */\nexport type CodeFacts = Record<string, ModelResolverFacts | undefined>\nexport interface ModelResolverFacts {\n\t/** Should we type the type as a generic with an override */", "score": 0.8546456098556519 }, { "filename": "src/serviceFile.codefacts.ts", "retrieved_chunk": "\t\t\tconst fact: ModelResolverFacts = fileFact[name] ?? {\n\t\t\t\ttypeName: name,\n\t\t\t\tresolvers: new Map(),\n\t\t\t\thasGenericArg,\n\t\t\t}\n\t\t\t// Grab the const Thing = { ... }\n\t\t\tconst obj = d.getFirstDescendantByKind(tsMorph.SyntaxKind.ObjectLiteralExpression)\n\t\t\tif (!obj) {\n\t\t\t\tthrow new Error(`Could not find an object literal ( e.g. a { } ) in ${d.getName()}`)\n\t\t\t}", "score": 0.8492965698242188 } ]
typescript
modelFacts.resolvers.forEach((resolver) => {
import * as graphql from "graphql" import { AppContext } from "./context.js" import { formatDTS, getPrettierConfig } from "./formatDTS.js" import { getCodeFactsForJSTSFileAtPath } from "./serviceFile.codefacts.js" import { CodeFacts, ModelResolverFacts, ResolverFuncFact } from "./typeFacts.js" import { TypeMapper, typeMapper } from "./typeMap.js" import { capitalizeFirstLetter, createAndReferOrInlineArgsForField, inlineArgsForField } from "./utils.js" export const lookAtServiceFile = (file: string, context: AppContext) => { const { gql, prisma, pathSettings: settings, codeFacts: serviceFacts, fieldFacts } = context // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition if (!gql) throw new Error(`No schema when wanting to look at service file: ${file}`) if (!prisma) throw new Error(`No prisma schema when wanting to look at service file: ${file}`) // This isn't good enough, needs to be relative to api/src/services const fileKey = file.replace(settings.apiServicesPath, "") const thisFact: CodeFacts = {} const filename = context.basename(file) // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const queryType = gql.getQueryType()! if (!queryType) throw new Error("No query type") // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const mutationType = gql.getMutationType()! // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition if (!mutationType) throw new Error("No mutation type") const externalMapper = typeMapper(context, { preferPrismaModels: true }) const returnTypeMapper = typeMapper(context, {}) // The description of the source file const fileFacts = getCodeFactsForJSTSFileAtPath(file, context) if (Object.keys(fileFacts).length === 0) return // Tracks prospective prisma models which are used in the file const extraPrismaReferences = new Set<string>() // The file we'll be creating in-memory throughout this fn const fileDTS = context.tsProject.createSourceFile(`source/${fileKey}.d.ts`, "", { overwrite: true }) // Basically if a top level resolver reference Query or Mutation const knownSpecialCasesForGraphQL = new Set<string>() // Add the root function declarations const rootResolvers = fileFacts.maybe_query_mutation?.resolvers if (rootResolvers) rootResolvers.forEach((v) => { const isQuery = v.name in queryType.getFields() const isMutation = v.name in mutationType.getFields() const parentName = isQuery ? queryType.name : isMutation ? mutationType.name : undefined if (parentName) { addDefinitionsForTopLevelResolvers(parentName, v) } else { // Add warning about unused resolver fileDTS.addStatements(`\n// ${v.name} does not exist on Query or Mutation`) } }) // Add the root function declarations Object.values(fileFacts).forEach((model) => { if (!model) return const skip = ["maybe_query_mutation", queryType.name, mutationType.name] if (skip.includes(model.typeName)) return addCustomTypeModel(model) }) // Set up the module imports at the top const sharedGraphQLObjectsReferenced = externalMapper.getReferencedGraphQLThingsInMapping() const sharedGraphQLObjectsReferencedTypes = [...sharedGraphQLObjectsReferenced.types, ...knownSpecialCasesForGraphQL] const sharedInternalGraphQLObjectsReferenced = returnTypeMapper.getReferencedGraphQLThingsInMapping() const aliases = [...new Set([...sharedGraphQLObjectsReferenced.scalars, ...sharedInternalGraphQLObjectsReferenced.scalars])] if (aliases.length) { fileDTS.addTypeAliases( aliases.map((s) => ({ name: s, type: "any", })) ) } const prismases = [ ...new Set([ ...sharedGraphQLObjectsReferenced.prisma, ...sharedInternalGraphQLObjectsReferenced.prisma, ...extraPrismaReferences.values(), ]), ] const validPrismaObjs = prismases.filter((p) => prisma.has(p)) if (validPrismaObjs.length) { fileDTS.addImportDeclaration({ isTypeOnly: true, moduleSpecifier: "@prisma/client", namedImports: validPrismaObjs.map((p) => `${p} as P${p}`), }) } if (fileDTS.getText().includes("GraphQLResolveInfo")) { fileDTS.addImportDeclaration({ isTypeOnly: true, moduleSpecifier: "graphql", namedImports: ["GraphQLResolveInfo"], }) } if (fileDTS.getText().includes("RedwoodGraphQLContext")) { fileDTS.addImportDeclaration({ isTypeOnly: true, moduleSpecifier: "@redwoodjs/graphql-server/dist/types", namedImports: ["RedwoodGraphQLContext"], }) } if (sharedInternalGraphQLObjectsReferenced.types.length) { fileDTS.addImportDeclaration({ isTypeOnly: true, moduleSpecifier: `./${settings.sharedInternalFilename.replace(".d.ts", "")}`, namedImports: sharedInternalGraphQLObjectsReferenced.types.map((t) => `${t} as RT${t}`), }) } if (sharedGraphQLObjectsReferencedTypes.length) { fileDTS.addImportDeclaration({ isTypeOnly: true, moduleSpecifier: `./${settings.sharedFilename.replace(".d.ts", "")}`, namedImports: sharedGraphQLObjectsReferencedTypes, }) } serviceFacts.set(fileKey, thisFact) const dtsFilename = filename.endsWith(".ts") ? filename.replace(".ts", ".d.ts") : filename.replace(".js", ".d.ts") const dtsFilepath = context.join(context.pathSettings.typesFolderRoot, dtsFilename) // Some manual formatting tweaks so we align with Redwood's setup more const dts = fileDTS .getText() .replace(`from "graphql";`, `from "graphql";\n`) .replace(`from "@redwoodjs/graphql-server/dist/types";`, `from "@redwoodjs/graphql-server/dist/types";\n`) const shouldWriteDTS = !!dts.trim().length if (!shouldWriteDTS) return const config = getPrettierConfig(dtsFilepath) const formatted = formatDTS(dtsFilepath, dts, config) context.sys.writeFile(dtsFilepath, formatted) return dtsFilepath function addDefinitionsForTopLevelResolvers(parentName: string, config: ResolverFuncFact) { const { name } = config let field = queryType.getFields()[name] if (!field) { field = mutationType.getFields()[name] } const interfaceDeclaration = fileDTS.addInterface({ name: `${capitalizeFirstLetter(config.name)}Resolver`, isExported: true, docs: field.astNode ? ["SDL: " + graphql.print(field.astNode)] : ["@deprecated: Could not find this field in the schema for Mutation or Query"], }) const args =
createAndReferOrInlineArgsForField(field, {
name: interfaceDeclaration.getName(), file: fileDTS, mapper: externalMapper.map, }) if (parentName === queryType.name) knownSpecialCasesForGraphQL.add(queryType.name) if (parentName === mutationType.name) knownSpecialCasesForGraphQL.add(mutationType.name) const argsParam = args ?? "object" const returnType = returnTypeForResolver(returnTypeMapper, field, config) interfaceDeclaration.addCallSignature({ parameters: [ { name: "args", type: argsParam, hasQuestionToken: config.funcArgCount < 1 }, { name: "obj", type: `{ root: ${parentName}, context: RedwoodGraphQLContext, info: GraphQLResolveInfo }`, hasQuestionToken: config.funcArgCount < 2, }, ], returnType, }) } /** Ideally, we want to be able to write the type for just the object */ function addCustomTypeModel(modelFacts: ModelResolverFacts) { const modelName = modelFacts.typeName extraPrismaReferences.add(modelName) // Make an interface, this is the version we are replacing from graphql-codegen: // Account: MergePrismaWithSdlTypes<PrismaAccount, MakeRelationsOptional<Account, AllMappedModels>, AllMappedModels>; const gqlType = gql.getType(modelName) if (!gqlType) { // throw new Error(`Could not find a GraphQL type named ${d.getName()}`); fileDTS.addStatements(`\n// ${modelName} does not exist in the schema`) return } if (!graphql.isObjectType(gqlType)) { throw new Error(`In your schema ${modelName} is not an object, which we can only make resolver types for`) } const fields = gqlType.getFields() // See: https://github.com/redwoodjs/redwood/pull/6228#issue-1342966511 // For more ideas const hasGenerics = modelFacts.hasGenericArg // This is what they would have to write const resolverInterface = fileDTS.addInterface({ name: `${modelName}TypeResolvers`, typeParameters: hasGenerics ? ["Extended"] : [], isExported: true, }) // The parent type for the resolvers fileDTS.addTypeAlias({ name: `${modelName}AsParent`, typeParameters: hasGenerics ? ["Extended"] : [], type: `P${modelName} ${createParentAdditionallyDefinedFunctions()} ${hasGenerics ? " & Extended" : ""}`, // docs: ["The prisma model, mixed with fns already defined inside the resolvers."], }) const modelFieldFacts = fieldFacts.get(modelName) ?? {} // Loop through the resolvers, adding the fields which have resolvers implemented in the source file modelFacts.resolvers.forEach((resolver) => { const field = fields[resolver.name] if (field) { const fieldName = resolver.name if (modelFieldFacts[fieldName]) modelFieldFacts[fieldName].hasResolverImplementation = true else modelFieldFacts[fieldName] = { hasResolverImplementation: true } const argsType = inlineArgsForField(field, { mapper: externalMapper.map }) ?? "undefined" const param = hasGenerics ? "<Extended>" : "" const firstQ = resolver.funcArgCount < 1 ? "?" : "" const secondQ = resolver.funcArgCount < 2 ? "?" : "" const innerArgs = `args${firstQ}: ${argsType}, obj${secondQ}: { root: ${modelName}AsParent${param}, context: RedwoodGraphQLContext, info: GraphQLResolveInfo }` const returnType = returnTypeForResolver(returnTypeMapper, field, resolver) const docs = field.astNode ? [`SDL: ${graphql.print(field.astNode)}`] : [] // For speed we should switch this out to addProperties eventually resolverInterface.addProperty({ name: fieldName, leadingTrivia: "\n", docs, type: resolver.isFunc || resolver.isUnknown ? `(${innerArgs}) => ${returnType ?? "any"}` : returnType, }) } else { resolverInterface.addCallSignature({ docs: [` @deprecated: SDL ${modelName}.${resolver.name} does not exist in your schema`], }) } }) function createParentAdditionallyDefinedFunctions() { const fns: string[] = [] modelFacts.resolvers.forEach((resolver) => { const existsInGraphQLSchema = fields[resolver.name] if (!existsInGraphQLSchema) { console.warn( `The service file ${filename} has a field ${resolver.name} on ${modelName} that does not exist in the generated schema.graphql` ) } const prefix = !existsInGraphQLSchema ? "\n// This field does not exist in the generated schema.graphql\n" : "" const returnType = returnTypeForResolver(externalMapper, existsInGraphQLSchema, resolver) // fns.push(`${prefix}${resolver.name}: () => Promise<${externalMapper.map(type, {})}>`) fns.push(`${prefix}${resolver.name}: () => ${returnType}`) }) if (fns.length < 1) return "" return "& {" + fns.join(", \n") + "}" } fieldFacts.set(modelName, modelFieldFacts) } return dtsFilename } function returnTypeForResolver(mapper: TypeMapper, field: graphql.GraphQLField<unknown, unknown> | undefined, resolver: ResolverFuncFact) { if (!field) return "void" const tType = mapper.map(field.type, { preferNullOverUndefined: true, typenamePrefix: "RT" }) ?? "void" let returnType = tType const all = `${tType} | Promise<${tType}> | (() => Promise<${tType}>)` if (resolver.isFunc && resolver.isAsync) returnType = `Promise<${tType}>` else if (resolver.isFunc) returnType = all else if (resolver.isObjLiteral) returnType = tType else if (resolver.isUnknown) returnType = all return returnType }
src/serviceFile.ts
sdl-codegen-sdl-codegen-de2b8aa
[ { "filename": "src/utils.ts", "retrieved_chunk": "\t\tnoSeparateType?: true\n\t}\n) => {\n\tconst inlineArgs = inlineArgsForField(field, config)\n\tif (!inlineArgs) return undefined\n\tif (inlineArgs.length < 120) return inlineArgs\n\tconst argsInterface = config.file.addInterface({\n\t\tname: `${config.name}Args`,\n\t\tisExported: true,\n\t})", "score": 0.8597058057785034 }, { "filename": "src/utils.ts", "retrieved_chunk": "\t\t\t\t})\n\t\t\t\t.join(\", \")}}`\n\t\t: undefined\n}\nexport const createAndReferOrInlineArgsForField = (\n\tfield: graphql.GraphQLField<unknown, unknown>,\n\tconfig: {\n\t\tfile: tsMorph.SourceFile\n\t\tmapper: TypeMapper[\"map\"]\n\t\tname: string", "score": 0.852363646030426 }, { "filename": "src/utils.ts", "retrieved_chunk": "export const inlineArgsForField = (field: graphql.GraphQLField<unknown, unknown>, config: { mapper: TypeMapper[\"map\"] }) => {\n\treturn field.args.length\n\t\t? // Always use an args obj\n\t\t `{${field.args\n\t\t\t\t.map((f) => {\n\t\t\t\t\tconst type = config.mapper(f.type, {})\n\t\t\t\t\tif (!type) throw new Error(`No type for ${f.name} on ${field.name}!`)\n\t\t\t\t\tconst q = type.includes(\"undefined\") ? \"?\" : \"\"\n\t\t\t\t\tconst displayType = type.replace(\"| undefined\", \"\")\n\t\t\t\t\treturn `${f.name}${q}: ${displayType}`", "score": 0.8386603593826294 }, { "filename": "src/serviceFile.codefacts.ts", "retrieved_chunk": "\tconst referenceFileSourceFile = context.tsProject.createSourceFile(`/source/${fileKey}`, fileContents, { overwrite: true })\n\tconst vars = referenceFileSourceFile.getVariableDeclarations().filter((v) => v.isExported())\n\tconst resolverContainers = vars.filter(varStartsWithUppercase)\n\tconst queryOrMutationResolvers = vars.filter((v) => !varStartsWithUppercase(v))\n\tqueryOrMutationResolvers.forEach((v) => {\n\t\tconst parent = \"maybe_query_mutation\"\n\t\tconst facts = getResolverInformationForDeclaration(v.getInitializer())\n\t\t// Start making facts about the services\n\t\tconst fact: ModelResolverFacts = fileFact[parent] ?? {\n\t\t\ttypeName: parent,", "score": 0.8353123068809509 }, { "filename": "src/sharedSchema.ts", "retrieved_chunk": "\t\t\t\t\t\t}\n\t\t\t\t\t\treturn field\n\t\t\t\t\t}),\n\t\t\t\t],\n\t\t\t})\n\t\t}\n\t\tif (graphql.isEnumType(type)) {\n\t\t\texternalTSFile.addTypeAlias({\n\t\t\t\tname: type.name,\n\t\t\t\ttype:", "score": 0.8350285291671753 } ]
typescript
createAndReferOrInlineArgsForField(field, {
import * as graphql from "graphql" import { AppContext } from "./context.js" import { formatDTS, getPrettierConfig } from "./formatDTS.js" import { getCodeFactsForJSTSFileAtPath } from "./serviceFile.codefacts.js" import { CodeFacts, ModelResolverFacts, ResolverFuncFact } from "./typeFacts.js" import { TypeMapper, typeMapper } from "./typeMap.js" import { capitalizeFirstLetter, createAndReferOrInlineArgsForField, inlineArgsForField } from "./utils.js" export const lookAtServiceFile = (file: string, context: AppContext) => { const { gql, prisma, pathSettings: settings, codeFacts: serviceFacts, fieldFacts } = context // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition if (!gql) throw new Error(`No schema when wanting to look at service file: ${file}`) if (!prisma) throw new Error(`No prisma schema when wanting to look at service file: ${file}`) // This isn't good enough, needs to be relative to api/src/services const fileKey = file.replace(settings.apiServicesPath, "") const thisFact: CodeFacts = {} const filename = context.basename(file) // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const queryType = gql.getQueryType()! if (!queryType) throw new Error("No query type") // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const mutationType = gql.getMutationType()! // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition if (!mutationType) throw new Error("No mutation type") const externalMapper = typeMapper(context, { preferPrismaModels: true }) const returnTypeMapper = typeMapper(context, {}) // The description of the source file const fileFacts = getCodeFactsForJSTSFileAtPath(file, context) if (Object.keys(fileFacts).length === 0) return // Tracks prospective prisma models which are used in the file const extraPrismaReferences = new Set<string>() // The file we'll be creating in-memory throughout this fn const fileDTS = context.tsProject.createSourceFile(`source/${fileKey}.d.ts`, "", { overwrite: true }) // Basically if a top level resolver reference Query or Mutation const knownSpecialCasesForGraphQL = new Set<string>() // Add the root function declarations const rootResolvers = fileFacts.maybe_query_mutation?.resolvers if (rootResolvers) rootResolvers.forEach((v) => { const isQuery = v.name in queryType.getFields() const isMutation = v.name in mutationType.getFields() const parentName = isQuery ? queryType.name : isMutation ? mutationType.name : undefined if (parentName) { addDefinitionsForTopLevelResolvers(parentName, v) } else { // Add warning about unused resolver fileDTS.addStatements(`\n// ${v.name} does not exist on Query or Mutation`) } }) // Add the root function declarations Object.values(fileFacts).forEach((model) => { if (!model) return const skip = ["maybe_query_mutation", queryType.name, mutationType.name] if (skip.includes(model.typeName)) return addCustomTypeModel(model) }) // Set up the module imports at the top const sharedGraphQLObjectsReferenced = externalMapper.getReferencedGraphQLThingsInMapping() const sharedGraphQLObjectsReferencedTypes = [...sharedGraphQLObjectsReferenced.types, ...knownSpecialCasesForGraphQL] const sharedInternalGraphQLObjectsReferenced = returnTypeMapper.getReferencedGraphQLThingsInMapping() const aliases = [...new Set([...sharedGraphQLObjectsReferenced.scalars, ...sharedInternalGraphQLObjectsReferenced.scalars])] if (aliases.length) { fileDTS.addTypeAliases( aliases.map((s) => ({ name: s, type: "any", })) ) } const prismases = [ ...new Set([ ...sharedGraphQLObjectsReferenced.prisma, ...sharedInternalGraphQLObjectsReferenced.prisma, ...extraPrismaReferences.values(), ]), ] const validPrismaObjs = prismases.filter((p) => prisma.has(p)) if (validPrismaObjs.length) { fileDTS.addImportDeclaration({ isTypeOnly: true, moduleSpecifier: "@prisma/client", namedImports: validPrismaObjs.map((p) => `${p} as P${p}`), }) } if (fileDTS.getText().includes("GraphQLResolveInfo")) { fileDTS.addImportDeclaration({ isTypeOnly: true, moduleSpecifier: "graphql", namedImports: ["GraphQLResolveInfo"], }) } if (fileDTS.getText().includes("RedwoodGraphQLContext")) { fileDTS.addImportDeclaration({ isTypeOnly: true, moduleSpecifier: "@redwoodjs/graphql-server/dist/types", namedImports: ["RedwoodGraphQLContext"], }) } if (sharedInternalGraphQLObjectsReferenced.types.length) { fileDTS.addImportDeclaration({ isTypeOnly: true, moduleSpecifier: `./${settings.sharedInternalFilename.replace(".d.ts", "")}`, namedImports: sharedInternalGraphQLObjectsReferenced.types.map((t) => `${t} as RT${t}`), }) } if (sharedGraphQLObjectsReferencedTypes.length) { fileDTS.addImportDeclaration({ isTypeOnly: true, moduleSpecifier: `./${settings.sharedFilename.replace(".d.ts", "")}`, namedImports: sharedGraphQLObjectsReferencedTypes, }) } serviceFacts.set(fileKey, thisFact) const dtsFilename = filename.endsWith(".ts") ? filename.replace(".ts", ".d.ts") : filename.replace(".js", ".d.ts") const dtsFilepath = context.join(context.pathSettings.typesFolderRoot, dtsFilename) // Some manual formatting tweaks so we align with Redwood's setup more const dts = fileDTS .getText() .replace(`from "graphql";`, `from "graphql";\n`) .replace(`from "@redwoodjs/graphql-server/dist/types";`, `from "@redwoodjs/graphql-server/dist/types";\n`) const shouldWriteDTS = !!dts.trim().length if (!shouldWriteDTS) return const config = getPrettierConfig(dtsFilepath) const formatted = formatDTS(dtsFilepath, dts, config) context.sys.writeFile(dtsFilepath, formatted) return dtsFilepath function addDefinitionsForTopLevelResolvers(parentName: string, config: ResolverFuncFact) { const { name } = config let field = queryType.getFields()[name] if (!field) { field = mutationType.getFields()[name] } const interfaceDeclaration = fileDTS.addInterface({ name: `${capitalizeFirstLetter(config.name)}Resolver`, isExported: true, docs: field.astNode ? ["SDL: " + graphql.print(field.astNode)] : ["@deprecated: Could not find this field in the schema for Mutation or Query"], }) const args = createAndReferOrInlineArgsForField(field, { name: interfaceDeclaration.getName(), file: fileDTS, mapper: externalMapper.map, }) if (parentName === queryType.name) knownSpecialCasesForGraphQL.add(queryType.name) if (parentName === mutationType.name) knownSpecialCasesForGraphQL.add(mutationType.name) const argsParam = args ?? "object" const returnType = returnTypeForResolver(returnTypeMapper, field, config) interfaceDeclaration.addCallSignature({ parameters: [ { name: "args", type: argsParam, hasQuestionToken: config.funcArgCount < 1 }, { name: "obj", type: `{ root: ${parentName}, context: RedwoodGraphQLContext, info: GraphQLResolveInfo }`, hasQuestionToken: config.funcArgCount < 2, }, ], returnType, }) } /** Ideally, we want to be able to write the type for just the object */ function addCustomTypeModel(modelFacts: ModelResolverFacts) { const modelName = modelFacts.typeName extraPrismaReferences.add(modelName) // Make an interface, this is the version we are replacing from graphql-codegen: // Account: MergePrismaWithSdlTypes<PrismaAccount, MakeRelationsOptional<Account, AllMappedModels>, AllMappedModels>; const gqlType = gql.getType(modelName) if (!gqlType) { // throw new Error(`Could not find a GraphQL type named ${d.getName()}`); fileDTS.addStatements(`\n// ${modelName} does not exist in the schema`) return } if (!graphql.isObjectType(gqlType)) { throw new Error(`In your schema ${modelName} is not an object, which we can only make resolver types for`) } const fields = gqlType.getFields() // See: https://github.com/redwoodjs/redwood/pull/6228#issue-1342966511 // For more ideas const
hasGenerics = modelFacts.hasGenericArg // This is what they would have to write const resolverInterface = fileDTS.addInterface({
name: `${modelName}TypeResolvers`, typeParameters: hasGenerics ? ["Extended"] : [], isExported: true, }) // The parent type for the resolvers fileDTS.addTypeAlias({ name: `${modelName}AsParent`, typeParameters: hasGenerics ? ["Extended"] : [], type: `P${modelName} ${createParentAdditionallyDefinedFunctions()} ${hasGenerics ? " & Extended" : ""}`, // docs: ["The prisma model, mixed with fns already defined inside the resolvers."], }) const modelFieldFacts = fieldFacts.get(modelName) ?? {} // Loop through the resolvers, adding the fields which have resolvers implemented in the source file modelFacts.resolvers.forEach((resolver) => { const field = fields[resolver.name] if (field) { const fieldName = resolver.name if (modelFieldFacts[fieldName]) modelFieldFacts[fieldName].hasResolverImplementation = true else modelFieldFacts[fieldName] = { hasResolverImplementation: true } const argsType = inlineArgsForField(field, { mapper: externalMapper.map }) ?? "undefined" const param = hasGenerics ? "<Extended>" : "" const firstQ = resolver.funcArgCount < 1 ? "?" : "" const secondQ = resolver.funcArgCount < 2 ? "?" : "" const innerArgs = `args${firstQ}: ${argsType}, obj${secondQ}: { root: ${modelName}AsParent${param}, context: RedwoodGraphQLContext, info: GraphQLResolveInfo }` const returnType = returnTypeForResolver(returnTypeMapper, field, resolver) const docs = field.astNode ? [`SDL: ${graphql.print(field.astNode)}`] : [] // For speed we should switch this out to addProperties eventually resolverInterface.addProperty({ name: fieldName, leadingTrivia: "\n", docs, type: resolver.isFunc || resolver.isUnknown ? `(${innerArgs}) => ${returnType ?? "any"}` : returnType, }) } else { resolverInterface.addCallSignature({ docs: [` @deprecated: SDL ${modelName}.${resolver.name} does not exist in your schema`], }) } }) function createParentAdditionallyDefinedFunctions() { const fns: string[] = [] modelFacts.resolvers.forEach((resolver) => { const existsInGraphQLSchema = fields[resolver.name] if (!existsInGraphQLSchema) { console.warn( `The service file ${filename} has a field ${resolver.name} on ${modelName} that does not exist in the generated schema.graphql` ) } const prefix = !existsInGraphQLSchema ? "\n// This field does not exist in the generated schema.graphql\n" : "" const returnType = returnTypeForResolver(externalMapper, existsInGraphQLSchema, resolver) // fns.push(`${prefix}${resolver.name}: () => Promise<${externalMapper.map(type, {})}>`) fns.push(`${prefix}${resolver.name}: () => ${returnType}`) }) if (fns.length < 1) return "" return "& {" + fns.join(", \n") + "}" } fieldFacts.set(modelName, modelFieldFacts) } return dtsFilename } function returnTypeForResolver(mapper: TypeMapper, field: graphql.GraphQLField<unknown, unknown> | undefined, resolver: ResolverFuncFact) { if (!field) return "void" const tType = mapper.map(field.type, { preferNullOverUndefined: true, typenamePrefix: "RT" }) ?? "void" let returnType = tType const all = `${tType} | Promise<${tType}> | (() => Promise<${tType}>)` if (resolver.isFunc && resolver.isAsync) returnType = `Promise<${tType}>` else if (resolver.isFunc) returnType = all else if (resolver.isObjLiteral) returnType = tType else if (resolver.isUnknown) returnType = all return returnType }
src/serviceFile.ts
sdl-codegen-sdl-codegen-de2b8aa
[ { "filename": "src/serviceFile.codefacts.ts", "retrieved_chunk": "\t\t\tconst fact: ModelResolverFacts = fileFact[name] ?? {\n\t\t\t\ttypeName: name,\n\t\t\t\tresolvers: new Map(),\n\t\t\t\thasGenericArg,\n\t\t\t}\n\t\t\t// Grab the const Thing = { ... }\n\t\t\tconst obj = d.getFirstDescendantByKind(tsMorph.SyntaxKind.ObjectLiteralExpression)\n\t\t\tif (!obj) {\n\t\t\t\tthrow new Error(`Could not find an object literal ( e.g. a { } ) in ${d.getName()}`)\n\t\t\t}", "score": 0.8490111827850342 }, { "filename": "src/sharedSchema.ts", "retrieved_chunk": "\tconst types = gql.getTypeMap()\n\tconst mapper = typeMapper(context, { preferPrismaModels: true })\n\tconst typesToImport = [] as string[]\n\tconst knownPrimitives = [\"String\", \"Boolean\", \"Int\"]\n\tconst externalTSFile = context.tsProject.createSourceFile(\n\t\t`/source/${context.pathSettings.sharedInternalFilename}`,\n\t\t`\n// You may very reasonably ask yourself, 'what is this file?' and why do I need it.\n// Roughly, this file ensures that when a resolver wants to return a type - that\n// type will match a prisma model. This is useful because you can trivially extend", "score": 0.8437739014625549 }, { "filename": "src/serviceFile.codefacts.ts", "retrieved_chunk": "\treturn fileFact\n\tfunction addCustomTypeResolvers(variableDeclaration: tsMorph.VariableDeclaration) {\n\t\tconst declarations = variableDeclaration.getVariableStatementOrThrow().getDeclarations()\n\t\tdeclarations.forEach((d) => {\n\t\t\tconst name = d.getName()\n\t\t\t// only do it if the first letter is a capital\n\t\t\tif (!name.match(/^[A-Z]/)) return\n\t\t\tconst type = d.getType()\n\t\t\tconst hasGenericArg = type.getText().includes(\"<\")\n\t\t\t// Start making facts about the services", "score": 0.8412801027297974 }, { "filename": "src/sharedSchema.ts", "retrieved_chunk": "\t\tif (graphql.isObjectType(type) || graphql.isInterfaceType(type) || graphql.isInputObjectType(type)) {\n\t\t\t// This is slower than it could be, use the add many at once api\n\t\t\tconst docs = []\n\t\t\tif (pType?.leadingComments) {\n\t\t\t\tdocs.push(pType.leadingComments)\n\t\t\t}\n\t\t\tif (type.description) {\n\t\t\t\tdocs.push(type.description)\n\t\t\t}\n\t\t\texternalTSFile.addInterface({", "score": 0.8392968773841858 }, { "filename": "src/sharedSchema.ts", "retrieved_chunk": "\t\t\t\t\t\thasQuestionToken: true,\n\t\t\t\t\t},\n\t\t\t\t\t...Object.entries(type.getFields()).map(([fieldName, obj]: [string, graphql.GraphQLField<object, object>]) => {\n\t\t\t\t\t\tconst hasResolverImplementation = fieldFacts.get(name)?.[fieldName]?.hasResolverImplementation\n\t\t\t\t\t\tconst isOptionalInSDL = !graphql.isNonNullType(obj.type)\n\t\t\t\t\t\tconst doesNotExistInPrisma = false // !prismaField;\n\t\t\t\t\t\tconst field: tsMorph.OptionalKind<tsMorph.PropertySignatureStructure> = {\n\t\t\t\t\t\t\tname: fieldName,\n\t\t\t\t\t\t\ttype: mapper.map(obj.type, { preferNullOverUndefined: true }),\n\t\t\t\t\t\t\thasQuestionToken: hasResolverImplementation || isOptionalInSDL || doesNotExistInPrisma,", "score": 0.8326175808906555 } ]
typescript
hasGenerics = modelFacts.hasGenericArg // This is what they would have to write const resolverInterface = fileDTS.addInterface({
/// The main schema for objects and inputs import * as graphql from "graphql" import * as tsMorph from "ts-morph" import { AppContext } from "./context.js" import { formatDTS, getPrettierConfig } from "./formatDTS.js" import { typeMapper } from "./typeMap.js" export const createSharedSchemaFiles = (context: AppContext) => { createSharedExternalSchemaFile(context) createSharedReturnPositionSchemaFile(context) return [ context.join(context.pathSettings.typesFolderRoot, context.pathSettings.sharedFilename), context.join(context.pathSettings.typesFolderRoot, context.pathSettings.sharedInternalFilename), ] } function createSharedExternalSchemaFile(context: AppContext) { const gql = context.gql const types = gql.getTypeMap() const knownPrimitives = ["String", "Boolean", "Int"] const { prisma, fieldFacts } = context const mapper = typeMapper(context, {}) const externalTSFile = context.tsProject.createSourceFile(`/source/${context.pathSettings.sharedFilename}`, "") Object.keys(types).forEach((name) => { if (name.startsWith("__")) { return } if (knownPrimitives.includes(name)) { return } const type = types[name] const pType = prisma.get(name) if (graphql.isObjectType(type) || graphql.isInterfaceType(type) || graphql.isInputObjectType(type)) { // This is slower than it could be, use the add many at once api const docs = [] if (pType?.leadingComments) { docs.push(pType.leadingComments) } if (type.description) { docs.push(type.description) } externalTSFile.addInterface({ name: type.name, isExported: true, docs: [], properties: [ { name: "__typename", type: `"${type.name}"`, hasQuestionToken: true, }, ...Object.entries(type.getFields()).map(([fieldName, obj]: [string, graphql.GraphQLField<object, object>]) => { const docs = [] const prismaField = pType?.properties.get(fieldName) const type = obj.type as graphql.GraphQLType if (prismaField?.leadingComments.length) { docs.push(prismaField.leadingComments.trim()) } // if (obj.description) docs.push(obj.description); const hasResolverImplementation = fieldFacts.get(name)?.[fieldName]?.hasResolverImplementation const isOptionalInSDL = !graphql.isNonNullType(type) const doesNotExistInPrisma = false // !prismaField; const field: tsMorph.OptionalKind<tsMorph.PropertySignatureStructure> = { name: fieldName, type: mapper.map(type, { preferNullOverUndefined: true }), docs, hasQuestionToken: hasResolverImplementation ?? (isOptionalInSDL || doesNotExistInPrisma), } return field }), ], }) } if (graphql.isEnumType(type)) { externalTSFile.addTypeAlias({ name: type.name, type: '"' + type .getValues() .map((m) => (m as { value: string }).value) .join('" | "') + '"', }) } }) const { scalars } = mapper.getReferencedGraphQLThingsInMapping() if (scalars.length) { externalTSFile.addTypeAliases( scalars.map((s) => ({ name: s, type: "any", })) ) } const fullPath = context.join(context.pathSettings.typesFolderRoot, context.pathSettings.sharedFilename) const config = getPrettierConfig(fullPath) const formatted = formatDTS(fullPath, externalTSFile.getText(), config)
context.sys.writeFile(fullPath, formatted) }
function createSharedReturnPositionSchemaFile(context: AppContext) { const { gql, prisma, fieldFacts } = context const types = gql.getTypeMap() const mapper = typeMapper(context, { preferPrismaModels: true }) const typesToImport = [] as string[] const knownPrimitives = ["String", "Boolean", "Int"] const externalTSFile = context.tsProject.createSourceFile( `/source/${context.pathSettings.sharedInternalFilename}`, ` // You may very reasonably ask yourself, 'what is this file?' and why do I need it. // Roughly, this file ensures that when a resolver wants to return a type - that // type will match a prisma model. This is useful because you can trivially extend // the type in the SDL and not have to worry about type mis-matches because the thing // you returned does not include those functions. // This gets particularly valuable when you want to return a union type, an interface, // or a model where the prisma model is nested pretty deeply (GraphQL connections, for example.) ` ) Object.keys(types).forEach((name) => { if (name.startsWith("__")) { return } if (knownPrimitives.includes(name)) { return } const type = types[name] const pType = prisma.get(name) if (graphql.isObjectType(type) || graphql.isInterfaceType(type) || graphql.isInputObjectType(type)) { // Return straight away if we have a matching type in the prisma schema // as we dont need it if (pType) { typesToImport.push(name) return } externalTSFile.addInterface({ name: type.name, isExported: true, docs: [], properties: [ { name: "__typename", type: `"${type.name}"`, hasQuestionToken: true, }, ...Object.entries(type.getFields()).map(([fieldName, obj]: [string, graphql.GraphQLField<object, object>]) => { const hasResolverImplementation = fieldFacts.get(name)?.[fieldName]?.hasResolverImplementation const isOptionalInSDL = !graphql.isNonNullType(obj.type) const doesNotExistInPrisma = false // !prismaField; const field: tsMorph.OptionalKind<tsMorph.PropertySignatureStructure> = { name: fieldName, type: mapper.map(obj.type, { preferNullOverUndefined: true }), hasQuestionToken: hasResolverImplementation || isOptionalInSDL || doesNotExistInPrisma, } return field }), ], }) } if (graphql.isEnumType(type)) { externalTSFile.addTypeAlias({ name: type.name, type: '"' + type .getValues() .map((m) => (m as { value: string }).value) .join('" | "') + '"', }) } }) const { scalars, prisma: prismaModels } = mapper.getReferencedGraphQLThingsInMapping() if (scalars.length) { externalTSFile.addTypeAliases( scalars.map((s) => ({ name: s, type: "any", })) ) } const allPrismaModels = [...new Set([...prismaModels, ...typesToImport])].sort() if (allPrismaModels.length) { externalTSFile.addImportDeclaration({ isTypeOnly: true, moduleSpecifier: `@prisma/client`, namedImports: allPrismaModels.map((p) => `${p} as P${p}`), }) allPrismaModels.forEach((p) => { externalTSFile.addTypeAlias({ isExported: true, name: p, type: `P${p}`, }) }) } const fullPath = context.join(context.pathSettings.typesFolderRoot, context.pathSettings.sharedInternalFilename) const config = getPrettierConfig(fullPath) const formatted = formatDTS(fullPath, externalTSFile.getText(), config) context.sys.writeFile(fullPath, formatted) }
src/sharedSchema.ts
sdl-codegen-sdl-codegen-de2b8aa
[ { "filename": "src/serviceFile.ts", "retrieved_chunk": "\tif (!shouldWriteDTS) return\n\tconst config = getPrettierConfig(dtsFilepath)\n\tconst formatted = formatDTS(dtsFilepath, dts, config)\n\tcontext.sys.writeFile(dtsFilepath, formatted)\n\treturn dtsFilepath\n\tfunction addDefinitionsForTopLevelResolvers(parentName: string, config: ResolverFuncFact) {\n\t\tconst { name } = config\n\t\tlet field = queryType.getFields()[name]\n\t\tif (!field) {\n\t\t\tfield = mutationType.getFields()[name]", "score": 0.8591039776802063 }, { "filename": "src/serviceFile.ts", "retrieved_chunk": "\t}\n\tserviceFacts.set(fileKey, thisFact)\n\tconst dtsFilename = filename.endsWith(\".ts\") ? filename.replace(\".ts\", \".d.ts\") : filename.replace(\".js\", \".d.ts\")\n\tconst dtsFilepath = context.join(context.pathSettings.typesFolderRoot, dtsFilename)\n\t// Some manual formatting tweaks so we align with Redwood's setup more\n\tconst dts = fileDTS\n\t\t.getText()\n\t\t.replace(`from \"graphql\";`, `from \"graphql\";\\n`)\n\t\t.replace(`from \"@redwoodjs/graphql-server/dist/types\";`, `from \"@redwoodjs/graphql-server/dist/types\";\\n`)\n\tconst shouldWriteDTS = !!dts.trim().length", "score": 0.8333202600479126 }, { "filename": "src/run.ts", "retrieved_chunk": "\t\t// \tcmd: [\"yarn\", \"eslint\", \"--fix\", \"--ext\", \".d.ts\", appContext.settings.typesFolderRoot],\n\t\t// \tstdin: \"inherit\",\n\t\t// \tstdout: \"inherit\",\n\t\t// })\n\t\t// await process.status()\n\t}\n\tif (sys.deleteFile && config.deleteOldGraphQLDTS) {\n\t\tconsole.log(\"Deleting old graphql.d.ts\")\n\t\tsys.deleteFile(join(appRoot, \"api\", \"src\", \"graphql.d.ts\"))\n\t}", "score": 0.8263021111488342 }, { "filename": "src/serviceFile.ts", "retrieved_chunk": "\tconst mutationType = gql.getMutationType()!\n\t// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n\tif (!mutationType) throw new Error(\"No mutation type\")\n\tconst externalMapper = typeMapper(context, { preferPrismaModels: true })\n\tconst returnTypeMapper = typeMapper(context, {})\n\t// The description of the source file\n\tconst fileFacts = getCodeFactsForJSTSFileAtPath(file, context)\n\tif (Object.keys(fileFacts).length === 0) return\n\t// Tracks prospective prisma models which are used in the file\n\tconst extraPrismaReferences = new Set<string>()", "score": 0.8258090615272522 }, { "filename": "src/serviceFile.ts", "retrieved_chunk": "\tif (fileDTS.getText().includes(\"RedwoodGraphQLContext\")) {\n\t\tfileDTS.addImportDeclaration({\n\t\t\tisTypeOnly: true,\n\t\t\tmoduleSpecifier: \"@redwoodjs/graphql-server/dist/types\",\n\t\t\tnamedImports: [\"RedwoodGraphQLContext\"],\n\t\t})\n\t}\n\tif (sharedInternalGraphQLObjectsReferenced.types.length) {\n\t\tfileDTS.addImportDeclaration({\n\t\t\tisTypeOnly: true,", "score": 0.8176667094230652 } ]
typescript
context.sys.writeFile(fullPath, formatted) }
import * as graphql from "graphql" import { AppContext } from "./context.js" export type TypeMapper = ReturnType<typeof typeMapper> export const typeMapper = (context: AppContext, config: { preferPrismaModels?: true }) => { const referencedGraphQLTypes = new Set<string>() const referencedPrismaModels = new Set<string>() const customScalars = new Set<string>() const clear = () => { referencedGraphQLTypes.clear() customScalars.clear() referencedPrismaModels.clear() } const getReferencedGraphQLThingsInMapping = () => { return { types: [...referencedGraphQLTypes.keys()], scalars: [...customScalars.keys()], prisma: [...referencedPrismaModels.keys()], } } const map = ( type: graphql.GraphQLType, mapConfig: { parentWasNotNull?: true preferNullOverUndefined?: true typenamePrefix?: string } ): string | undefined => { const prefix = mapConfig.typenamePrefix ?? "" // The AST for GQL uses a parent node to indicate the !, we need the opposite // for TS which uses '| undefined' after. if (graphql.isNonNullType(type)) { return map(type.ofType, { parentWasNotNull: true, ...mapConfig }) } // So we can add the | undefined const getInner = () => { if (graphql.isListType(type)) { const typeStr = map(type.ofType, mapConfig) if (!typeStr) return "any" if (graphql.isNonNullType(type.ofType)) { return `${typeStr}[]` } else { return `Array<${typeStr}>` } } if (graphql.isScalarType(type)) { switch (type.toString()) { case "Int": return "number" case "Float": return "number" case "String": return "string" case "Boolean": return "boolean" } customScalars.add(type.name) return type.name } if (graphql.isObjectType(type)) { if (config
.preferPrismaModels && context.prisma.has(type.name)) {
referencedPrismaModels.add(type.name) return "P" + type.name } else { // GraphQL only type referencedGraphQLTypes.add(type.name) return prefix + type.name } } if (graphql.isInterfaceType(type)) { return prefix + type.name } if (graphql.isUnionType(type)) { const types = type.getTypes() return types.map((t) => map(t, mapConfig)).join(" | ") } if (graphql.isEnumType(type)) { return prefix + type.name } if (graphql.isInputObjectType(type)) { referencedGraphQLTypes.add(type.name) return prefix + type.name } // eslint-disable-next-line @typescript-eslint/restrict-template-expressions throw new Error(`Unknown type ${type} - ${JSON.stringify(type, null, 2)}`) } const suffix = mapConfig.parentWasNotNull ? "" : mapConfig.preferNullOverUndefined ? "| null" : " | undefined" return getInner() + suffix } return { map, clear, getReferencedGraphQLThingsInMapping } }
src/typeMap.ts
sdl-codegen-sdl-codegen-de2b8aa
[ { "filename": "src/sharedSchema.ts", "retrieved_chunk": "\t\t\t\t\t'\"' +\n\t\t\t\t\ttype\n\t\t\t\t\t\t.getValues()\n\t\t\t\t\t\t.map((m) => (m as { value: string }).value)\n\t\t\t\t\t\t.join('\" | \"') +\n\t\t\t\t\t'\"',\n\t\t\t})\n\t\t}\n\t})\n\tconst { scalars, prisma: prismaModels } = mapper.getReferencedGraphQLThingsInMapping()", "score": 0.8256130218505859 }, { "filename": "src/sharedSchema.ts", "retrieved_chunk": "\t\tif (knownPrimitives.includes(name)) {\n\t\t\treturn\n\t\t}\n\t\tconst type = types[name]\n\t\tconst pType = prisma.get(name)\n\t\tif (graphql.isObjectType(type) || graphql.isInterfaceType(type) || graphql.isInputObjectType(type)) {\n\t\t\t// Return straight away if we have a matching type in the prisma schema\n\t\t\t// as we dont need it\n\t\t\tif (pType) {\n\t\t\t\ttypesToImport.push(name)", "score": 0.8179174661636353 }, { "filename": "src/sharedSchema.ts", "retrieved_chunk": "\t\t\t\tname: type.name,\n\t\t\t\tisExported: true,\n\t\t\t\tdocs: [],\n\t\t\t\tproperties: [\n\t\t\t\t\t{\n\t\t\t\t\t\tname: \"__typename\",\n\t\t\t\t\t\ttype: `\"${type.name}\"`,\n\t\t\t\t\t\thasQuestionToken: true,\n\t\t\t\t\t},\n\t\t\t\t\t...Object.entries(type.getFields()).map(([fieldName, obj]: [string, graphql.GraphQLField<object, object>]) => {", "score": 0.8047968149185181 }, { "filename": "src/sharedSchema.ts", "retrieved_chunk": "\t\t}\n\t\tif (graphql.isEnumType(type)) {\n\t\t\texternalTSFile.addTypeAlias({\n\t\t\t\tname: type.name,\n\t\t\t\ttype:\n\t\t\t\t\t'\"' +\n\t\t\t\t\ttype\n\t\t\t\t\t\t.getValues()\n\t\t\t\t\t\t.map((m) => (m as { value: string }).value)\n\t\t\t\t\t\t.join('\" | \"') +", "score": 0.803097128868103 }, { "filename": "src/sharedSchema.ts", "retrieved_chunk": "\t\t\t\t\t\t}\n\t\t\t\t\t\treturn field\n\t\t\t\t\t}),\n\t\t\t\t],\n\t\t\t})\n\t\t}\n\t\tif (graphql.isEnumType(type)) {\n\t\t\texternalTSFile.addTypeAlias({\n\t\t\t\tname: type.name,\n\t\t\t\ttype:", "score": 0.8022275567054749 } ]
typescript
.preferPrismaModels && context.prisma.has(type.name)) {
import { scrapeContent } from "../../scraper/pornhub/pornhubSearchController"; import c from "../../utils/options"; import { logger } from "../../utils/logger"; import { maybeError, spacer } from "../../utils/modifier"; import { Request, Response } from "express"; const sorting = ["mr", "mv", "tr", "lg"]; export async function searchPornhub(req: Request, res: Response) { try { /** * @api {get} /pornhub/search Search pornhub videos * @apiName Search pornhub * @apiGroup pornhub * @apiDescription Search pornhub videos * @apiParam {String} key Keyword to search * @apiParam {Number} [page=1] Page number * @apiParam {String} [sort=mr] Sort by * * @apiSuccessExample {json} Success-Response: * HTTP/1.1 200 OK * HTTP/1.1 400 Bad Request * * @apiExample {curl} curl * curl -i https://lust.scathach.id/pornhub/search?key=milf * curl -i https://lust.scathach.id/pornhub/search?key=milf&page=2&sort=mr * * @apiExample {js} JS/TS * import axios from "axios" * * axios.get("https://lust.scathach.id/pornhub/search?key=milf") * .then(res => console.log(res.data)) * .catch(err => console.error(err)) * * @apiExample {python} Python * import aiohttp * async with aiohttp.ClientSession() as session: * async with session.get("https://lust.scathach.id/pornhub/search?key=milf") as resp: * print(await resp.json()) */ const key = req.query.key as string; const page = req.query.page || 1; const sort = req.query.sort as string; if (!key) throw Error("Parameter key is required"); if (isNaN(Number(page))) throw Error("Parameter page must be a number"); let url; if (!sort) url =
`${c.PORNHUB}/video/search?search=${spacer(key)}`;
else if (!sorting.includes(sort)) url = `${c.PORNHUB}/video/search?search=${spacer(key)}&page=${page}`; else url = `${c.PORNHUB}/video/search?search=${spacer(key)}&o=${sort}&page=${page}`; console.log(url); const data = await scrapeContent(url); logger.info({ path: req.path, query: req.query, method: req.method, ip: req.ip, useragent: req.get("User-Agent") }); return res.json(data); } catch (err) { const e = err as Error; res.status(400).json(maybeError(false, e.message)); } }
src/controller/pornhub/pornhubSearch.ts
sinkaroid-lustpress-ac1a6d8
[ { "filename": "src/controller/youporn/youpornSearch.ts", "retrieved_chunk": " * @apiExample {python} Python\n * import aiohttp\n * async with aiohttp.ClientSession() as session:\n * async with session.get(\"https://lust.scathach.id/youporn/search?key=milf\") as resp:\n * print(await resp.json())\n */\n const key = req.query.key as string;\n const page = req.query.page || 1;\n if (!key) throw Error(\"Parameter key is required\");\n if (isNaN(Number(page))) throw Error(\"Parameter page must be a number\");", "score": 0.9169423580169678 }, { "filename": "src/controller/xvideos/xvideosSearch.ts", "retrieved_chunk": " * @apiExample {python} Python\n * import aiohttp\n * async with aiohttp.ClientSession() as session:\n * async with session.get(\"https://lust.scathach.id/xvideos/search?key=milf\") as resp:\n * print(await resp.json())\n */\n const key = req.query.key as string;\n const page = req.query.page || 0;\n if (!key) throw Error(\"Parameter key is required\");\n if (isNaN(Number(page))) throw Error(\"Parameter page must be a number\");", "score": 0.9167563915252686 }, { "filename": "src/controller/xhamster/xhamsterSearch.ts", "retrieved_chunk": " * @apiExample {python} Python\n * import aiohttp\n * async with aiohttp.ClientSession() as session:\n * async with session.get(\"https://lust.scathach.id/xhamster/search?key=milf\") as resp:\n * print(await resp.json())\n */\n const key = req.query.key as string;\n const page = req.query.page || 1;\n if (!key) throw Error(\"Parameter key is required\");\n if (isNaN(Number(page))) throw Error(\"Parameter page must be a number\");", "score": 0.9136993885040283 }, { "filename": "src/controller/redtube/redtubeSearch.ts", "retrieved_chunk": " * @apiExample {python} Python\n * import aiohttp\n * async with aiohttp.ClientSession() as session:\n * async with session.get(\"https://lust.scathach.id/redtube/search?key=milf\") as resp:\n * print(await resp.json())\n */\n const key = req.query.key as string;\n const page = req.query.page || 1;\n if (!key) throw Error(\"Parameter key is required\");\n if (isNaN(Number(page))) throw Error(\"Parameter page must be a number\");", "score": 0.9132177829742432 }, { "filename": "src/controller/xnxx/xnxxSearch.ts", "retrieved_chunk": " * @apiExample {python} Python\n * import aiohttp\n * async with aiohttp.ClientSession() as session:\n * async with session.get(\"https://lust.scathach.id/xnxx/search?key=milf\") as resp:\n * print(await resp.json())\n */\n const key = req.query.key as string;\n const page = req.query.page || 0;\n if (!key) throw Error(\"Parameter key is required\");\n if (isNaN(Number(page))) throw Error(\"Parameter page must be a number\");", "score": 0.9120525121688843 } ]
typescript
`${c.PORNHUB}/video/search?search=${spacer(key)}`;
import { Request, Response } from "express"; import { scrapeContent } from "../../scraper/pornhub/pornhubGetController"; import c from "../../utils/options"; import { logger } from "../../utils/logger"; import { maybeError } from "../../utils/modifier"; export async function randomPornhub(req: Request, res: Response) { try { /** * @api {get} /pornhub/random Random pornhub video * @apiName Random pornhub * @apiGroup pornhub * @apiDescription Gets random pornhub video * * @apiSuccessExample {json} Success-Response: * HTTP/1.1 200 OK * HTTP/1.1 400 Bad Request * * @apiExample {curl} curl * curl -i https://lust.scathach.id/pornhub/random * * @apiExample {js} JS/TS * import axios from "axios" * * axios.get("https://lust.scathach.id/pornhub/random") * .then(res => console.log(res.data)) * .catch(err => console.error(err)) * * @apiExample {python} Python * import aiohttp * async with aiohttp.ClientSession() as session: * async with session.get("https://lust.scathach.id/pornhub/random") as resp: * print(await resp.json()) * */ const
url = `${c.PORNHUB}/video/random`;
const data = await scrapeContent(url); logger.info({ path: req.path, query: req.query, method: req.method, ip: req.ip, useragent: req.get("User-Agent") }); return res.json(data); } catch (err) { const e = err as Error; res.status(400).json(maybeError(false, e.message)); } }
src/controller/pornhub/pornhubRandom.ts
sinkaroid-lustpress-ac1a6d8
[ { "filename": "src/controller/xvideos/xvideosRandom.ts", "retrieved_chunk": " * @apiExample {python} Python\n * import aiohttp\n * async with aiohttp.ClientSession() as session:\n * async with session.get(\"https://lust.scathach.id/xvideos/random\") as resp:\n * print(await resp.json())\n */\n const resolve = await lust.fetchBody(c.XVIDEOS);\n const $ = load(resolve);\n const search = $(\"div.thumb-under\")\n .find(\"a\")", "score": 0.8882381319999695 }, { "filename": "src/controller/pornhub/pornhubGetRelated.ts", "retrieved_chunk": " * \n * @apiExample {python} Python\n * import aiohttp\n * async with aiohttp.ClientSession() as session:\n * async with session.get(\"https://lust.scathach.id/pornhub/get?id=ph63c4e1dc48fe7\") as resp:\n * print(await resp.json())\n */\n const url = `${c.PORNHUB}/view_video.php?viewkey=${id}`;\n const data = await scrapeContent(url);\n logger.info({", "score": 0.8863400220870972 }, { "filename": "src/controller/pornhub/pornhubGet.ts", "retrieved_chunk": " * \n * @apiExample {python} Python\n * import aiohttp\n * async with aiohttp.ClientSession() as session:\n * async with session.get(\"https://lust.scathach.id/pornhub/get?id=ph63c4e1dc48fe7\") as resp:\n * print(await resp.json())\n */\n const url = `${c.PORNHUB}/view_video.php?viewkey=${id}`;\n const data = await scrapeContent(url);\n logger.info({", "score": 0.8863400220870972 }, { "filename": "src/controller/redtube/redtubeRandom.ts", "retrieved_chunk": " * .catch(err => console.error(err))\n * \n * @apiExample {python} Python\n * import aiohttp\n * async with aiohttp.ClientSession() as session:\n * async with session.get(\"https://lust.scathach.id/redtube/random\") as resp:\n * print(await resp.json())\n */\n const resolve = await lust.fetchBody(c.REDTUBE);\n const $ = load(resolve);", "score": 0.8811472654342651 }, { "filename": "src/controller/xhamster/xhamsterRandom.ts", "retrieved_chunk": " * @apiExample {python} Python\n * import aiohttp\n * async with aiohttp.ClientSession() as session:\n * async with session.get(\"https://lust.scathach.id/xhamster/random\") as resp:\n * print(await resp.json())\n */\n const resolve = await lust.fetchBody(`${c.XHAMSTER}/newest`);\n const $ = load(resolve);\n const search = $(\"a.root-9d8b4.video-thumb-info__name.role-pop.with-dropdown\")\n .map((i, el) => $(el).attr(\"href\"))", "score": 0.8807252645492554 } ]
typescript
url = `${c.PORNHUB}/video/random`;
import { scrapeContent } from "../../scraper/pornhub/pornhubSearchController"; import c from "../../utils/options"; import { logger } from "../../utils/logger"; import { maybeError, spacer } from "../../utils/modifier"; import { Request, Response } from "express"; const sorting = ["mr", "mv", "tr", "lg"]; export async function searchPornhub(req: Request, res: Response) { try { /** * @api {get} /pornhub/search Search pornhub videos * @apiName Search pornhub * @apiGroup pornhub * @apiDescription Search pornhub videos * @apiParam {String} key Keyword to search * @apiParam {Number} [page=1] Page number * @apiParam {String} [sort=mr] Sort by * * @apiSuccessExample {json} Success-Response: * HTTP/1.1 200 OK * HTTP/1.1 400 Bad Request * * @apiExample {curl} curl * curl -i https://lust.scathach.id/pornhub/search?key=milf * curl -i https://lust.scathach.id/pornhub/search?key=milf&page=2&sort=mr * * @apiExample {js} JS/TS * import axios from "axios" * * axios.get("https://lust.scathach.id/pornhub/search?key=milf") * .then(res => console.log(res.data)) * .catch(err => console.error(err)) * * @apiExample {python} Python * import aiohttp * async with aiohttp.ClientSession() as session: * async with session.get("https://lust.scathach.id/pornhub/search?key=milf") as resp: * print(await resp.json()) */ const key = req.query.key as string; const page = req.query.page || 1; const sort = req.query.sort as string; if (!key) throw Error("Parameter key is required"); if (isNaN(Number(page))) throw Error("Parameter page must be a number"); let url;
if (!sort) url = `${c.PORNHUB}/video/search?search=${spacer(key)}`;
else if (!sorting.includes(sort)) url = `${c.PORNHUB}/video/search?search=${spacer(key)}&page=${page}`; else url = `${c.PORNHUB}/video/search?search=${spacer(key)}&o=${sort}&page=${page}`; console.log(url); const data = await scrapeContent(url); logger.info({ path: req.path, query: req.query, method: req.method, ip: req.ip, useragent: req.get("User-Agent") }); return res.json(data); } catch (err) { const e = err as Error; res.status(400).json(maybeError(false, e.message)); } }
src/controller/pornhub/pornhubSearch.ts
sinkaroid-lustpress-ac1a6d8
[ { "filename": "src/controller/youporn/youpornSearch.ts", "retrieved_chunk": " * @apiExample {python} Python\n * import aiohttp\n * async with aiohttp.ClientSession() as session:\n * async with session.get(\"https://lust.scathach.id/youporn/search?key=milf\") as resp:\n * print(await resp.json())\n */\n const key = req.query.key as string;\n const page = req.query.page || 1;\n if (!key) throw Error(\"Parameter key is required\");\n if (isNaN(Number(page))) throw Error(\"Parameter page must be a number\");", "score": 0.94941246509552 }, { "filename": "src/controller/xvideos/xvideosSearch.ts", "retrieved_chunk": " * @apiExample {python} Python\n * import aiohttp\n * async with aiohttp.ClientSession() as session:\n * async with session.get(\"https://lust.scathach.id/xvideos/search?key=milf\") as resp:\n * print(await resp.json())\n */\n const key = req.query.key as string;\n const page = req.query.page || 0;\n if (!key) throw Error(\"Parameter key is required\");\n if (isNaN(Number(page))) throw Error(\"Parameter page must be a number\");", "score": 0.9471983909606934 }, { "filename": "src/controller/xhamster/xhamsterSearch.ts", "retrieved_chunk": " * @apiExample {python} Python\n * import aiohttp\n * async with aiohttp.ClientSession() as session:\n * async with session.get(\"https://lust.scathach.id/xhamster/search?key=milf\") as resp:\n * print(await resp.json())\n */\n const key = req.query.key as string;\n const page = req.query.page || 1;\n if (!key) throw Error(\"Parameter key is required\");\n if (isNaN(Number(page))) throw Error(\"Parameter page must be a number\");", "score": 0.9460597038269043 }, { "filename": "src/controller/redtube/redtubeSearch.ts", "retrieved_chunk": " * @apiExample {python} Python\n * import aiohttp\n * async with aiohttp.ClientSession() as session:\n * async with session.get(\"https://lust.scathach.id/redtube/search?key=milf\") as resp:\n * print(await resp.json())\n */\n const key = req.query.key as string;\n const page = req.query.page || 1;\n if (!key) throw Error(\"Parameter key is required\");\n if (isNaN(Number(page))) throw Error(\"Parameter page must be a number\");", "score": 0.944640040397644 }, { "filename": "src/controller/xnxx/xnxxSearch.ts", "retrieved_chunk": " * @apiExample {python} Python\n * import aiohttp\n * async with aiohttp.ClientSession() as session:\n * async with session.get(\"https://lust.scathach.id/xnxx/search?key=milf\") as resp:\n * print(await resp.json())\n */\n const key = req.query.key as string;\n const page = req.query.page || 0;\n if (!key) throw Error(\"Parameter key is required\");\n if (isNaN(Number(page))) throw Error(\"Parameter page must be a number\");", "score": 0.9433473348617554 } ]
typescript
if (!sort) url = `${c.PORNHUB}/video/search?search=${spacer(key)}`;
import { scrapeContent } from "../../scraper/redtube/redtubeGetController"; import c from "../../utils/options"; import { logger } from "../../utils/logger"; import { maybeError } from "../../utils/modifier"; import { Request, Response } from "express"; import { load } from "cheerio"; import LustPress from "../../LustPress"; const lust = new LustPress(); export async function randomRedtube(req: Request, res: Response) { try { /** * @api {get} /redtube/random Get random redtube * @apiName Get random redtube * @apiGroup redtube * @apiDescription Get a random redtube video * * @apiParam {String} id Video ID * * @apiSuccessExample {json} Success-Response: * HTTP/1.1 200 OK * HTTP/1.1 400 Bad Request * * @apiExample {curl} curl * curl -i https://lust.scathach.id/redtube/random * * @apiExample {js} JS/TS * import axios from "axios" * * axios.get("https://lust.scathach.id/redtube/random") * .then(res => console.log(res.data)) * .catch(err => console.error(err)) * * @apiExample {python} Python * import aiohttp * async with aiohttp.ClientSession() as session: * async with session.get("https://lust.scathach.id/redtube/random") as resp: * print(await resp.json()) */
const resolve = await lust.fetchBody(c.REDTUBE);
const $ = load(resolve); const search = $("a.video_link") .map((i, el) => { return $(el).attr("href"); }).get(); const random = Math.floor(Math.random() * search.length); const url = c.REDTUBE + search[random]; const data = await scrapeContent(url); logger.info({ path: req.path, query: req.query, method: req.method, ip: req.ip, useragent: req.get("User-Agent") }); return res.json(data); } catch (err) { const e = err as Error; res.status(400).json(maybeError(false, e.message)); } }
src/controller/redtube/redtubeRandom.ts
sinkaroid-lustpress-ac1a6d8
[ { "filename": "src/controller/xvideos/xvideosRandom.ts", "retrieved_chunk": " * @apiExample {python} Python\n * import aiohttp\n * async with aiohttp.ClientSession() as session:\n * async with session.get(\"https://lust.scathach.id/xvideos/random\") as resp:\n * print(await resp.json())\n */\n const resolve = await lust.fetchBody(c.XVIDEOS);\n const $ = load(resolve);\n const search = $(\"div.thumb-under\")\n .find(\"a\")", "score": 0.9099608063697815 }, { "filename": "src/controller/xhamster/xhamsterRandom.ts", "retrieved_chunk": " * @apiExample {python} Python\n * import aiohttp\n * async with aiohttp.ClientSession() as session:\n * async with session.get(\"https://lust.scathach.id/xhamster/random\") as resp:\n * print(await resp.json())\n */\n const resolve = await lust.fetchBody(`${c.XHAMSTER}/newest`);\n const $ = load(resolve);\n const search = $(\"a.root-9d8b4.video-thumb-info__name.role-pop.with-dropdown\")\n .map((i, el) => $(el).attr(\"href\"))", "score": 0.9034408926963806 }, { "filename": "src/controller/redtube/redtubeGet.ts", "retrieved_chunk": " * .catch(err => console.error(err))\n * \n * @apiExample {python} Python\n * import aiohttp\n * async with aiohttp.ClientSession() as session:\n * async with session.get(\"https://lust.scathach.id/redtube/get?id=42763661\") as resp:\n * print(await resp.json())\n */\n const url = `${c.REDTUBE}/${id}`;\n const data = await scrapeContent(url);", "score": 0.9030685424804688 }, { "filename": "src/controller/youporn/youpornRandom.ts", "retrieved_chunk": " * @apiExample {python} Python\n * import aiohttp\n * async with aiohttp.ClientSession() as session:\n * async with session.get(\"https://lust.scathach.id/youporn/random\") as resp:\n * print(await resp.json())\n */\n const resolve = await lust.fetchBody(`${c.YOUPORN}`);\n const $ = load(resolve);\n const search = $(\"a[href^='/watch/']\")\n .map((i, el) => {", "score": 0.899415135383606 }, { "filename": "src/controller/xnxx/xnxxRandom.ts", "retrieved_chunk": " * @apiExample {python} Python\n * import aiohttp\n * async with aiohttp.ClientSession() as session:\n * async with session.get(\"https://lust.scathach.id/xnxx/random\") as resp:\n * print(await resp.json())\n */\n const resolve = await lust.fetchBody(\"https://www.xnxx.com/search/random/random\");\n const $ = load(resolve);\n const search = $(\"div.mozaique > div\")\n .map((i, el) => {", "score": 0.8904538750648499 } ]
typescript
const resolve = await lust.fetchBody(c.REDTUBE);
import { scrapeContent } from "../../scraper/xnxx/xnxxGetController"; import c from "../../utils/options"; import { logger } from "../../utils/logger"; import { maybeError } from "../../utils/modifier"; import { Request, Response } from "express"; import { load } from "cheerio"; import LustPress from "../../LustPress"; const lust = new LustPress(); export async function randomXnxx(req: Request, res: Response) { try { /** * @api {get} /xnxx/random Get random xnxx * @apiName Get random xnxx * @apiGroup xnxx * @apiDescription Get a random xnxx video * * @apiSuccessExample {json} Success-Response: * HTTP/1.1 200 OK * HTTP/1.1 400 Bad Request * * @apiExample {curl} curl * curl -i https://lust.scathach.id/xnxx/random * * @apiExample {js} JS/TS * import axios from "axios" * * axios.get("https://lust.scathach.id/xnxx/random") * .then(res => console.log(res.data)) * .catch(err => console.error(err)) * * @apiExample {python} Python * import aiohttp * async with aiohttp.ClientSession() as session: * async with session.get("https://lust.scathach.id/xnxx/random") as resp: * print(await resp.json()) */ const resolve = await lust.fetchBody("https://www.xnxx.com/search/random/random"); const $ = load(resolve); const search = $("div.mozaique > div") .map((i, el) => { return $(el).find("a").attr("href"); }).get(); const random = Math.floor(Math.random() * search.length); const
url = c.XNXX + search[random];
const data = await scrapeContent(url); logger.info({ path: req.path, query: req.query, method: req.method, ip: req.ip, useragent: req.get("User-Agent") }); return res.json(data); } catch (err) { const e = err as Error; res.status(400).json(maybeError(false, e.message)); } }
src/controller/xnxx/xnxxRandom.ts
sinkaroid-lustpress-ac1a6d8
[ { "filename": "src/controller/xhamster/xhamsterRandom.ts", "retrieved_chunk": " * @apiExample {python} Python\n * import aiohttp\n * async with aiohttp.ClientSession() as session:\n * async with session.get(\"https://lust.scathach.id/xhamster/random\") as resp:\n * print(await resp.json())\n */\n const resolve = await lust.fetchBody(`${c.XHAMSTER}/newest`);\n const $ = load(resolve);\n const search = $(\"a.root-9d8b4.video-thumb-info__name.role-pop.with-dropdown\")\n .map((i, el) => $(el).attr(\"href\"))", "score": 0.9210559725761414 }, { "filename": "src/controller/xvideos/xvideosRandom.ts", "retrieved_chunk": " * @apiExample {python} Python\n * import aiohttp\n * async with aiohttp.ClientSession() as session:\n * async with session.get(\"https://lust.scathach.id/xvideos/random\") as resp:\n * print(await resp.json())\n */\n const resolve = await lust.fetchBody(c.XVIDEOS);\n const $ = load(resolve);\n const search = $(\"div.thumb-under\")\n .find(\"a\")", "score": 0.9194768071174622 }, { "filename": "src/controller/youporn/youpornRandom.ts", "retrieved_chunk": " * @apiExample {python} Python\n * import aiohttp\n * async with aiohttp.ClientSession() as session:\n * async with session.get(\"https://lust.scathach.id/youporn/random\") as resp:\n * print(await resp.json())\n */\n const resolve = await lust.fetchBody(`${c.YOUPORN}`);\n const $ = load(resolve);\n const search = $(\"a[href^='/watch/']\")\n .map((i, el) => {", "score": 0.9149482250213623 }, { "filename": "src/controller/redtube/redtubeRandom.ts", "retrieved_chunk": " * .catch(err => console.error(err))\n * \n * @apiExample {python} Python\n * import aiohttp\n * async with aiohttp.ClientSession() as session:\n * async with session.get(\"https://lust.scathach.id/redtube/random\") as resp:\n * print(await resp.json())\n */\n const resolve = await lust.fetchBody(c.REDTUBE);\n const $ = load(resolve);", "score": 0.8949792385101318 }, { "filename": "src/controller/xhamster/xhamsterRandom.ts", "retrieved_chunk": " .get();\n const search_ = search.map((el) => el.replace(c.XHAMSTER, \"\"));\n const random = Math.floor(Math.random() * search_.length);\n const url = c.XHAMSTER + search_[random];\n const data = await scrapeContent(url);\n logger.info({\n path: req.path,\n query: req.query,\n method: req.method,\n ip: req.ip,", "score": 0.8866922855377197 } ]
typescript
url = c.XNXX + search[random];
import { scrapeContent } from "../../scraper/xhamster/xhamsterSearchController"; import c from "../../utils/options"; import { logger } from "../../utils/logger"; import { maybeError, spacer } from "../../utils/modifier"; import { Request, Response } from "express"; export async function searchXhamster(req: Request, res: Response) { try { /** * @api {get} /xhamster/search Search xhamster videos * @apiName Search xhamster * @apiGroup xhamster * @apiDescription Search xhamster videos * @apiParam {String} key Keyword to search * @apiParam {Number} [page=1] Page number * * @apiSuccessExample {json} Success-Response: * HTTP/1.1 200 OK * HTTP/1.1 400 Bad Request * * @apiExample {curl} curl * curl -i https://lust.scathach.id/xhamster/search?key=milf * curl -i https://lust.scathach.id/xhamster/search?key=milf&page=2 * * @apiExample {js} JS/TS * import axios from "axios" * * axios.get("https://lust.scathach.id/xhamster/search?key=milf") * .then(res => console.log(res.data)) * .catch(err => console.error(err)) * * @apiExample {python} Python * import aiohttp * async with aiohttp.ClientSession() as session: * async with session.get("https://lust.scathach.id/xhamster/search?key=milf") as resp: * print(await resp.json()) */ const key = req.query.key as string; const page = req.query.page || 1; if (!key) throw Error("Parameter key is required"); if (isNaN(Number(page))) throw Error("Parameter page must be a number"); const
url = `${c.XHAMSTER}/search/${spacer(key)}?page=${page}`;
const data = await scrapeContent(url); logger.info({ path: req.path, query: req.query, method: req.method, ip: req.ip, useragent: req.get("User-Agent") }); return res.json(data); } catch (err) { const e = err as Error; res.status(400).json(maybeError(false, e.message)); } }
src/controller/xhamster/xhamsterSearch.ts
sinkaroid-lustpress-ac1a6d8
[ { "filename": "src/controller/xnxx/xnxxSearch.ts", "retrieved_chunk": " * @apiExample {python} Python\n * import aiohttp\n * async with aiohttp.ClientSession() as session:\n * async with session.get(\"https://lust.scathach.id/xnxx/search?key=milf\") as resp:\n * print(await resp.json())\n */\n const key = req.query.key as string;\n const page = req.query.page || 0;\n if (!key) throw Error(\"Parameter key is required\");\n if (isNaN(Number(page))) throw Error(\"Parameter page must be a number\");", "score": 0.9543484449386597 }, { "filename": "src/controller/youporn/youpornSearch.ts", "retrieved_chunk": " * @apiExample {python} Python\n * import aiohttp\n * async with aiohttp.ClientSession() as session:\n * async with session.get(\"https://lust.scathach.id/youporn/search?key=milf\") as resp:\n * print(await resp.json())\n */\n const key = req.query.key as string;\n const page = req.query.page || 1;\n if (!key) throw Error(\"Parameter key is required\");\n if (isNaN(Number(page))) throw Error(\"Parameter page must be a number\");", "score": 0.9530999660491943 }, { "filename": "src/controller/xvideos/xvideosSearch.ts", "retrieved_chunk": " * @apiExample {python} Python\n * import aiohttp\n * async with aiohttp.ClientSession() as session:\n * async with session.get(\"https://lust.scathach.id/xvideos/search?key=milf\") as resp:\n * print(await resp.json())\n */\n const key = req.query.key as string;\n const page = req.query.page || 0;\n if (!key) throw Error(\"Parameter key is required\");\n if (isNaN(Number(page))) throw Error(\"Parameter page must be a number\");", "score": 0.9528363943099976 }, { "filename": "src/controller/redtube/redtubeSearch.ts", "retrieved_chunk": " * @apiExample {python} Python\n * import aiohttp\n * async with aiohttp.ClientSession() as session:\n * async with session.get(\"https://lust.scathach.id/redtube/search?key=milf\") as resp:\n * print(await resp.json())\n */\n const key = req.query.key as string;\n const page = req.query.page || 1;\n if (!key) throw Error(\"Parameter key is required\");\n if (isNaN(Number(page))) throw Error(\"Parameter page must be a number\");", "score": 0.9520182609558105 }, { "filename": "src/controller/pornhub/pornhubSearch.ts", "retrieved_chunk": " * .catch(err => console.error(err))\n * \n * @apiExample {python} Python\n * import aiohttp\n * async with aiohttp.ClientSession() as session:\n * async with session.get(\"https://lust.scathach.id/pornhub/search?key=milf\") as resp:\n * print(await resp.json())\n */\n const key = req.query.key as string;\n const page = req.query.page || 1;", "score": 0.9411944150924683 } ]
typescript
url = `${c.XHAMSTER}/search/${spacer(key)}?page=${page}`;
import { scrapeContent } from "../../scraper/redtube/redtubeSearchController"; import c from "../../utils/options"; import { logger } from "../../utils/logger"; import { maybeError, spacer } from "../../utils/modifier"; import { Request, Response } from "express"; export async function searchRedtube(req: Request, res: Response) { try { /** * @api {get} /redtube/search Search redtube videos * @apiName Search redtube * @apiGroup redtube * @apiDescription Search redtube videos * @apiParam {String} key Keyword to search * @apiParam {Number} [page=1] Page number * * @apiSuccessExample {json} Success-Response: * HTTP/1.1 200 OK * HTTP/1.1 400 Bad Request * * @apiExample {curl} curl * curl -i https://lust.scathach.id/redtube/search?key=milf * curl -i https://lust.scathach.id/redtube/search?key=milf&page=2 * * @apiExample {js} JS/TS * import axios from "axios" * * axios.get("https://lust.scathach.id/redtube/search?key=milf") * .then(res => console.log(res.data)) * .catch(err => console.error(err)) * * @apiExample {python} Python * import aiohttp * async with aiohttp.ClientSession() as session: * async with session.get("https://lust.scathach.id/redtube/search?key=milf") as resp: * print(await resp.json()) */ const key = req.query.key as string; const page = req.query.page || 1; if (!key) throw Error("Parameter key is required"); if (isNaN(Number(page))) throw Error("Parameter page must be a number");
const url = `${c.REDTUBE}/?search=${spacer(key)}&page=${page}`;
const data = await scrapeContent(url); logger.info({ path: req.path, query: req.query, method: req.method, ip: req.ip, useragent: req.get("User-Agent") }); return res.json(data); } catch (err) { const e = err as Error; res.status(400).json(maybeError(false, e.message)); } }
src/controller/redtube/redtubeSearch.ts
sinkaroid-lustpress-ac1a6d8
[ { "filename": "src/controller/xhamster/xhamsterSearch.ts", "retrieved_chunk": " * @apiExample {python} Python\n * import aiohttp\n * async with aiohttp.ClientSession() as session:\n * async with session.get(\"https://lust.scathach.id/xhamster/search?key=milf\") as resp:\n * print(await resp.json())\n */\n const key = req.query.key as string;\n const page = req.query.page || 1;\n if (!key) throw Error(\"Parameter key is required\");\n if (isNaN(Number(page))) throw Error(\"Parameter page must be a number\");", "score": 0.9565335512161255 }, { "filename": "src/controller/youporn/youpornSearch.ts", "retrieved_chunk": " * @apiExample {python} Python\n * import aiohttp\n * async with aiohttp.ClientSession() as session:\n * async with session.get(\"https://lust.scathach.id/youporn/search?key=milf\") as resp:\n * print(await resp.json())\n */\n const key = req.query.key as string;\n const page = req.query.page || 1;\n if (!key) throw Error(\"Parameter key is required\");\n if (isNaN(Number(page))) throw Error(\"Parameter page must be a number\");", "score": 0.9540812969207764 }, { "filename": "src/controller/xvideos/xvideosSearch.ts", "retrieved_chunk": " * @apiExample {python} Python\n * import aiohttp\n * async with aiohttp.ClientSession() as session:\n * async with session.get(\"https://lust.scathach.id/xvideos/search?key=milf\") as resp:\n * print(await resp.json())\n */\n const key = req.query.key as string;\n const page = req.query.page || 0;\n if (!key) throw Error(\"Parameter key is required\");\n if (isNaN(Number(page))) throw Error(\"Parameter page must be a number\");", "score": 0.9531904458999634 }, { "filename": "src/controller/xnxx/xnxxSearch.ts", "retrieved_chunk": " * @apiExample {python} Python\n * import aiohttp\n * async with aiohttp.ClientSession() as session:\n * async with session.get(\"https://lust.scathach.id/xnxx/search?key=milf\") as resp:\n * print(await resp.json())\n */\n const key = req.query.key as string;\n const page = req.query.page || 0;\n if (!key) throw Error(\"Parameter key is required\");\n if (isNaN(Number(page))) throw Error(\"Parameter page must be a number\");", "score": 0.9528545141220093 }, { "filename": "src/controller/pornhub/pornhubSearch.ts", "retrieved_chunk": " * .catch(err => console.error(err))\n * \n * @apiExample {python} Python\n * import aiohttp\n * async with aiohttp.ClientSession() as session:\n * async with session.get(\"https://lust.scathach.id/pornhub/search?key=milf\") as resp:\n * print(await resp.json())\n */\n const key = req.query.key as string;\n const page = req.query.page || 1;", "score": 0.9428956508636475 } ]
typescript
const url = `${c.REDTUBE}/?search=${spacer(key)}&page=${page}`;
import { scrapeContent } from "../../scraper/xhamster/xhamsterSearchController"; import c from "../../utils/options"; import { logger } from "../../utils/logger"; import { maybeError, spacer } from "../../utils/modifier"; import { Request, Response } from "express"; export async function searchXhamster(req: Request, res: Response) { try { /** * @api {get} /xhamster/search Search xhamster videos * @apiName Search xhamster * @apiGroup xhamster * @apiDescription Search xhamster videos * @apiParam {String} key Keyword to search * @apiParam {Number} [page=1] Page number * * @apiSuccessExample {json} Success-Response: * HTTP/1.1 200 OK * HTTP/1.1 400 Bad Request * * @apiExample {curl} curl * curl -i https://lust.scathach.id/xhamster/search?key=milf * curl -i https://lust.scathach.id/xhamster/search?key=milf&page=2 * * @apiExample {js} JS/TS * import axios from "axios" * * axios.get("https://lust.scathach.id/xhamster/search?key=milf") * .then(res => console.log(res.data)) * .catch(err => console.error(err)) * * @apiExample {python} Python * import aiohttp * async with aiohttp.ClientSession() as session: * async with session.get("https://lust.scathach.id/xhamster/search?key=milf") as resp: * print(await resp.json()) */ const key = req.query.key as string; const page = req.query.page || 1; if (!key) throw Error("Parameter key is required"); if (isNaN(Number(page))) throw Error("Parameter page must be a number");
const url = `${c.XHAMSTER}/search/${spacer(key)}?page=${page}`;
const data = await scrapeContent(url); logger.info({ path: req.path, query: req.query, method: req.method, ip: req.ip, useragent: req.get("User-Agent") }); return res.json(data); } catch (err) { const e = err as Error; res.status(400).json(maybeError(false, e.message)); } }
src/controller/xhamster/xhamsterSearch.ts
sinkaroid-lustpress-ac1a6d8
[ { "filename": "src/controller/xnxx/xnxxSearch.ts", "retrieved_chunk": " * @apiExample {python} Python\n * import aiohttp\n * async with aiohttp.ClientSession() as session:\n * async with session.get(\"https://lust.scathach.id/xnxx/search?key=milf\") as resp:\n * print(await resp.json())\n */\n const key = req.query.key as string;\n const page = req.query.page || 0;\n if (!key) throw Error(\"Parameter key is required\");\n if (isNaN(Number(page))) throw Error(\"Parameter page must be a number\");", "score": 0.955148458480835 }, { "filename": "src/controller/xvideos/xvideosSearch.ts", "retrieved_chunk": " * @apiExample {python} Python\n * import aiohttp\n * async with aiohttp.ClientSession() as session:\n * async with session.get(\"https://lust.scathach.id/xvideos/search?key=milf\") as resp:\n * print(await resp.json())\n */\n const key = req.query.key as string;\n const page = req.query.page || 0;\n if (!key) throw Error(\"Parameter key is required\");\n if (isNaN(Number(page))) throw Error(\"Parameter page must be a number\");", "score": 0.9532448053359985 }, { "filename": "src/controller/youporn/youpornSearch.ts", "retrieved_chunk": " * @apiExample {python} Python\n * import aiohttp\n * async with aiohttp.ClientSession() as session:\n * async with session.get(\"https://lust.scathach.id/youporn/search?key=milf\") as resp:\n * print(await resp.json())\n */\n const key = req.query.key as string;\n const page = req.query.page || 1;\n if (!key) throw Error(\"Parameter key is required\");\n if (isNaN(Number(page))) throw Error(\"Parameter page must be a number\");", "score": 0.9530004262924194 }, { "filename": "src/controller/redtube/redtubeSearch.ts", "retrieved_chunk": " * @apiExample {python} Python\n * import aiohttp\n * async with aiohttp.ClientSession() as session:\n * async with session.get(\"https://lust.scathach.id/redtube/search?key=milf\") as resp:\n * print(await resp.json())\n */\n const key = req.query.key as string;\n const page = req.query.page || 1;\n if (!key) throw Error(\"Parameter key is required\");\n if (isNaN(Number(page))) throw Error(\"Parameter page must be a number\");", "score": 0.9523206949234009 }, { "filename": "src/controller/pornhub/pornhubSearch.ts", "retrieved_chunk": " * .catch(err => console.error(err))\n * \n * @apiExample {python} Python\n * import aiohttp\n * async with aiohttp.ClientSession() as session:\n * async with session.get(\"https://lust.scathach.id/pornhub/search?key=milf\") as resp:\n * print(await resp.json())\n */\n const key = req.query.key as string;\n const page = req.query.page || 1;", "score": 0.9411576390266418 } ]
typescript
const url = `${c.XHAMSTER}/search/${spacer(key)}?page=${page}`;
import { scrapeContent } from "../../scraper/xnxx/xnxxSearchController"; import c from "../../utils/options"; import { logger } from "../../utils/logger"; import { maybeError, spacer } from "../../utils/modifier"; import { Request, Response } from "express"; export async function searchXnxx(req: Request, res: Response) { try { /** * @api {get} /xnxx/search Search xnxx videos * @apiName Search xnxx * @apiGroup xnxx * @apiDescription Search xnxx videos * @apiParam {String} key Keyword to search * @apiParam {Number} [page=0] Page number * * @apiSuccessExample {json} Success-Response: * HTTP/1.1 200 OK * HTTP/1.1 400 Bad Request * * @apiExample {curl} curl * curl -i https://lust.scathach.id/xnxx/search?key=milf * curl -i https://lust.scathach.id/xnxx/search?key=milf&page=2 * * @apiExample {js} JS/TS * import axios from "axios" * * axios.get("https://lust.scathach.id/xnxx/search?key=milf") * .then(res => console.log(res.data)) * .catch(err => console.error(err)) * * @apiExample {python} Python * import aiohttp * async with aiohttp.ClientSession() as session: * async with session.get("https://lust.scathach.id/xnxx/search?key=milf") as resp: * print(await resp.json()) */ const key = req.query.key as string; const page = req.query.page || 0; if (!key) throw Error("Parameter key is required"); if (isNaN(Number(page))) throw Error("Parameter page must be a number"); const url =
`${c.XNXX}/search/${spacer(key)}/${page}`;
const data = await scrapeContent(url); logger.info({ path: req.path, query: req.query, method: req.method, ip: req.ip, useragent: req.get("User-Agent") }); return res.json(data); } catch (err) { const e = err as Error; res.status(400).json(maybeError(false, e.message)); } }
src/controller/xnxx/xnxxSearch.ts
sinkaroid-lustpress-ac1a6d8
[ { "filename": "src/controller/xhamster/xhamsterSearch.ts", "retrieved_chunk": " * @apiExample {python} Python\n * import aiohttp\n * async with aiohttp.ClientSession() as session:\n * async with session.get(\"https://lust.scathach.id/xhamster/search?key=milf\") as resp:\n * print(await resp.json())\n */\n const key = req.query.key as string;\n const page = req.query.page || 1;\n if (!key) throw Error(\"Parameter key is required\");\n if (isNaN(Number(page))) throw Error(\"Parameter page must be a number\");", "score": 0.9604892730712891 }, { "filename": "src/controller/xvideos/xvideosSearch.ts", "retrieved_chunk": " * @apiExample {python} Python\n * import aiohttp\n * async with aiohttp.ClientSession() as session:\n * async with session.get(\"https://lust.scathach.id/xvideos/search?key=milf\") as resp:\n * print(await resp.json())\n */\n const key = req.query.key as string;\n const page = req.query.page || 0;\n if (!key) throw Error(\"Parameter key is required\");\n if (isNaN(Number(page))) throw Error(\"Parameter page must be a number\");", "score": 0.9568865299224854 }, { "filename": "src/controller/youporn/youpornSearch.ts", "retrieved_chunk": " * @apiExample {python} Python\n * import aiohttp\n * async with aiohttp.ClientSession() as session:\n * async with session.get(\"https://lust.scathach.id/youporn/search?key=milf\") as resp:\n * print(await resp.json())\n */\n const key = req.query.key as string;\n const page = req.query.page || 1;\n if (!key) throw Error(\"Parameter key is required\");\n if (isNaN(Number(page))) throw Error(\"Parameter page must be a number\");", "score": 0.9559991955757141 }, { "filename": "src/controller/redtube/redtubeSearch.ts", "retrieved_chunk": " * @apiExample {python} Python\n * import aiohttp\n * async with aiohttp.ClientSession() as session:\n * async with session.get(\"https://lust.scathach.id/redtube/search?key=milf\") as resp:\n * print(await resp.json())\n */\n const key = req.query.key as string;\n const page = req.query.page || 1;\n if (!key) throw Error(\"Parameter key is required\");\n if (isNaN(Number(page))) throw Error(\"Parameter page must be a number\");", "score": 0.9540523290634155 }, { "filename": "src/controller/pornhub/pornhubSearch.ts", "retrieved_chunk": " * .catch(err => console.error(err))\n * \n * @apiExample {python} Python\n * import aiohttp\n * async with aiohttp.ClientSession() as session:\n * async with session.get(\"https://lust.scathach.id/pornhub/search?key=milf\") as resp:\n * print(await resp.json())\n */\n const key = req.query.key as string;\n const page = req.query.page || 1;", "score": 0.943311870098114 } ]
typescript
`${c.XNXX}/search/${spacer(key)}/${page}`;
import { scrapeContent } from "../../scraper/xvideos/xvideosGetController"; import c from "../../utils/options"; import { logger } from "../../utils/logger"; import { maybeError } from "../../utils/modifier"; import { Request, Response } from "express"; import { load } from "cheerio"; import LustPress from "../../LustPress"; const lust = new LustPress(); export async function randomXvideos(req: Request, res: Response) { try { /** * @api {get} /xvideos/random Get random xvideos * @apiName Get random xvideos * @apiGroup xvideos * @apiDescription Get a random xvideos video * * @apiSuccessExample {json} Success-Response: * HTTP/1.1 200 OK * HTTP/1.1 400 Bad Request * * @apiExample {curl} curl * curl -i https://lust.scathach.id/xvideos/random * * @apiExample {js} JS/TS * import axios from "axios" * * axios.get("https://lust.scathach.id/xvideos/random") * .then(res => console.log(res.data)) * .catch(err => console.error(err)) * * @apiExample {python} Python * import aiohttp * async with aiohttp.ClientSession() as session: * async with session.get("https://lust.scathach.id/xvideos/random") as resp: * print(await resp.json()) */ const resolve = await
lust.fetchBody(c.XVIDEOS);
const $ = load(resolve); const search = $("div.thumb-under") .find("a") .map((i, el) => $(el).attr("href")) .get(); const filtered = search.filter((el) => el.includes("/video")); const filtered_ = filtered.filter((el) => !el.includes("THUMBNUM")); const random = Math.floor(Math.random() * filtered_.length); const url = c.XVIDEOS + filtered[random]; const data = await scrapeContent(url); logger.info({ path: req.path, query: req.query, method: req.method, ip: req.ip, useragent: req.get("User-Agent") }); return res.json(data); } catch (err) { const e = err as Error; res.status(400).json(maybeError(false, e.message)); } }
src/controller/xvideos/xvideosRandom.ts
sinkaroid-lustpress-ac1a6d8
[ { "filename": "src/controller/redtube/redtubeRandom.ts", "retrieved_chunk": " * .catch(err => console.error(err))\n * \n * @apiExample {python} Python\n * import aiohttp\n * async with aiohttp.ClientSession() as session:\n * async with session.get(\"https://lust.scathach.id/redtube/random\") as resp:\n * print(await resp.json())\n */\n const resolve = await lust.fetchBody(c.REDTUBE);\n const $ = load(resolve);", "score": 0.9523378014564514 }, { "filename": "src/controller/xhamster/xhamsterRandom.ts", "retrieved_chunk": " * @apiExample {python} Python\n * import aiohttp\n * async with aiohttp.ClientSession() as session:\n * async with session.get(\"https://lust.scathach.id/xhamster/random\") as resp:\n * print(await resp.json())\n */\n const resolve = await lust.fetchBody(`${c.XHAMSTER}/newest`);\n const $ = load(resolve);\n const search = $(\"a.root-9d8b4.video-thumb-info__name.role-pop.with-dropdown\")\n .map((i, el) => $(el).attr(\"href\"))", "score": 0.9191579818725586 }, { "filename": "src/controller/youporn/youpornRandom.ts", "retrieved_chunk": " * @apiExample {python} Python\n * import aiohttp\n * async with aiohttp.ClientSession() as session:\n * async with session.get(\"https://lust.scathach.id/youporn/random\") as resp:\n * print(await resp.json())\n */\n const resolve = await lust.fetchBody(`${c.YOUPORN}`);\n const $ = load(resolve);\n const search = $(\"a[href^='/watch/']\")\n .map((i, el) => {", "score": 0.911418080329895 }, { "filename": "src/controller/xnxx/xnxxRandom.ts", "retrieved_chunk": " * @apiExample {python} Python\n * import aiohttp\n * async with aiohttp.ClientSession() as session:\n * async with session.get(\"https://lust.scathach.id/xnxx/random\") as resp:\n * print(await resp.json())\n */\n const resolve = await lust.fetchBody(\"https://www.xnxx.com/search/random/random\");\n const $ = load(resolve);\n const search = $(\"div.mozaique > div\")\n .map((i, el) => {", "score": 0.9042772054672241 }, { "filename": "src/controller/redtube/redtubeGet.ts", "retrieved_chunk": " * .catch(err => console.error(err))\n * \n * @apiExample {python} Python\n * import aiohttp\n * async with aiohttp.ClientSession() as session:\n * async with session.get(\"https://lust.scathach.id/redtube/get?id=42763661\") as resp:\n * print(await resp.json())\n */\n const url = `${c.REDTUBE}/${id}`;\n const data = await scrapeContent(url);", "score": 0.8844881653785706 } ]
typescript
lust.fetchBody(c.XVIDEOS);
import fs from "fs-extra"; import { isEmpty } from "lodash-es"; import path from "node:path"; import { createLogger, inspectValue, readTypedJsonSync } from "~/utils"; export type IsolateConfigResolved = { buildDirName?: string; includeDevDependencies: boolean; isolateDirName: string; logLevel: "info" | "debug" | "warn" | "error"; targetPackagePath?: string; tsconfigPath: string; workspacePackages?: string[]; workspaceRoot: string; excludeLockfile: boolean; avoidPnpmPack: boolean; }; export type IsolateConfig = Partial<IsolateConfigResolved>; const configDefaults: IsolateConfigResolved = { buildDirName: undefined, includeDevDependencies: false, isolateDirName: "isolate", logLevel: "info", targetPackagePath: undefined, tsconfigPath: "./tsconfig.json", workspacePackages: undefined, workspaceRoot: "../..", excludeLockfile: false, avoidPnpmPack: false, }; /** * Only initialize the configuration once, and keeping it here for subsequent * calls to getConfig. */ let __config: IsolateConfigResolved | undefined; const validConfigKeys = Object.keys(configDefaults); const CONFIG_FILE_NAME = "isolate.config.json"; type LogLevel = IsolateConfigResolved["logLevel"]; export function getConfig(): IsolateConfigResolved { if (__config) { return __config; } /** * Since the logLevel is set via config we can't use it to determine if we * should output verbose logging as part of the config loading process. Using * the env var ISOLATE_CONFIG_LOG_LEVEL you have the option to log debug * output. */ const log =
createLogger( (process.env.ISOLATE_CONFIG_LOG_LEVEL as LogLevel) ?? "warn" );
const configFilePath = path.join(process.cwd(), CONFIG_FILE_NAME); log.debug(`Attempting to load config from ${configFilePath}`); const configFromFile = fs.existsSync(configFilePath) ? readTypedJsonSync<IsolateConfig>(configFilePath) : {}; const foreignKeys = Object.keys(configFromFile).filter( (key) => !validConfigKeys.includes(key) ); if (!isEmpty(foreignKeys)) { log.warn(`Found invalid config settings:`, foreignKeys.join(", ")); } const config = Object.assign( {}, configDefaults, configFromFile ) satisfies IsolateConfigResolved; log.debug("Using configuration:", inspectValue(config)); __config = config; return config; }
src/helpers/config.ts
0x80-isolate-package-4fe8eaf
[ { "filename": "src/utils/logger.ts", "retrieved_chunk": "import chalk from \"chalk\";\nimport { IsolateConfigResolved } from \"~/helpers\";\nexport type Logger = {\n debug(...args: any[]): void;\n info(...args: any[]): void;\n warn(...args: any[]): void;\n error(...args: any[]): void;\n};\nexport function createLogger(\n logLevel: IsolateConfigResolved[\"logLevel\"]", "score": 0.8809511661529541 }, { "filename": "src/utils/logger.ts", "retrieved_chunk": "): Logger {\n return {\n debug(...args: any[]) {\n if (logLevel === \"debug\") {\n console.log(chalk.blue(\"debug\"), ...args);\n }\n },\n info(...args: any[]) {\n if (logLevel === \"debug\" || logLevel === \"info\") {\n console.log(chalk.green(\"info\"), ...args);", "score": 0.8373055458068848 }, { "filename": "src/helpers/process-lockfile.ts", "retrieved_chunk": " targetPackageName,\n packagesRegistry,\n isolateDir,\n}: {\n workspaceRootDir: string;\n targetPackageName: string;\n packagesRegistry: PackagesRegistry;\n isolateDir: string;\n}) {\n const log = createLogger(getConfig().logLevel);", "score": 0.8139201402664185 }, { "filename": "src/utils/logger.ts", "retrieved_chunk": " }\n },\n warn(...args: any[]) {\n if (logLevel === \"debug\" || logLevel === \"info\" || logLevel === \"warn\") {\n console.log(chalk.yellow(\"warning\"), ...args);\n }\n },\n error(...args: any[]) {\n console.log(chalk.red(\"error\"), ...args);\n },", "score": 0.8114327788352966 }, { "filename": "src/index.ts", "retrieved_chunk": "} from \"~/helpers\";\nimport {\n createLogger,\n getDirname,\n getRootRelativePath,\n readTypedJson,\n} from \"~/utils\";\nconst config = getConfig();\nconst log = createLogger(config.logLevel);\nsourceMaps.install();", "score": 0.8076139688491821 } ]
typescript
createLogger( (process.env.ISOLATE_CONFIG_LOG_LEVEL as LogLevel) ?? "warn" );
import fs from "fs-extra"; import { globSync } from "glob"; import path from "node:path"; import { createLogger, readTypedJson } from "~/utils"; import { getConfig } from "./config"; import { findPackagesGlobs } from "./find-packages-globs"; export type PackageManifest = { name: string; packageManager?: string; dependencies?: Record<string, string>; devDependencies?: Record<string, string>; main: string; module?: string; exports?: Record<string, { require: string; import: string }>; files: string[]; version?: string; typings?: string; scripts?: Record<string, string>; }; export type WorkspacePackageInfo = { absoluteDir: string; /** * The path of the package relative to the workspace root. This is the path * referenced in the lock file. */ rootRelativeDir: string; /** * The package.json file contents */ manifest: PackageManifest; }; export type PackagesRegistry = Record<string, WorkspacePackageInfo>; /** * Build a list of all packages in the workspace, depending on the package * manager used, with a possible override from the config file. The list contains * the manifest with some directory info mapped by module name. */ export async function createPackagesRegistry( workspaceRootDir: string, workspacePackagesOverride: string[] | undefined ): Promise<PackagesRegistry> { const log = createLogger(getConfig().logLevel); if (workspacePackagesOverride) { log.debug( `Override workspace packages via config: ${workspacePackagesOverride}` ); } const packagesGlobs = workspacePackagesOverride ?? findPackagesGlobs(workspaceRootDir); const cwd = process.cwd(); process.chdir(workspaceRootDir); const allPackages = packagesGlobs .flatMap((glob) => globSync(glob)) /** * Make sure to filter any loose files that might hang around. */ .filter((dir) => fs.lstatSync(dir).isDirectory()); const registry: PackagesRegistry = ( await Promise.all(
allPackages.map(async (rootRelativeDir) => {
const manifestPath = path.join(rootRelativeDir, "package.json"); if (!fs.existsSync(manifestPath)) { log.warn( `Ignoring directory ./${rootRelativeDir} because it does not contain a package.json file` ); return; } else { log.debug(`Registering package ./${rootRelativeDir}`); const manifest = await readTypedJson<PackageManifest>( path.join(rootRelativeDir, "package.json") ); return { manifest, rootRelativeDir, absoluteDir: path.join(workspaceRootDir, rootRelativeDir), }; } }) ) ).reduce<PackagesRegistry>((acc, info) => { if (info) { acc[info.manifest.name] = info; } return acc; }, {}); process.chdir(cwd); return registry; }
src/helpers/create-packages-registry.ts
0x80-isolate-package-4fe8eaf
[ { "filename": "src/helpers/adapt-manifest-files.ts", "retrieved_chunk": " packagesRegistry: PackagesRegistry,\n isolateDir: string\n) {\n await Promise.all(\n localDependencies.map(async (packageName) => {\n const { manifest, rootRelativeDir } = packagesRegistry[packageName];\n const outputManifest = adaptManifestWorkspaceDeps(\n { manifest, packagesRegistry, parentRootRelativeDir: rootRelativeDir },\n { includeDevDependencies: getConfig().includeDevDependencies }\n );", "score": 0.8857954144477844 }, { "filename": "src/helpers/unpack-dependencies.ts", "retrieved_chunk": " isolateDir: string\n) {\n const log = createLogger(getConfig().logLevel);\n await Promise.all(\n Object.entries(packedFilesByName).map(async ([packageName, filePath]) => {\n const dir = packagesRegistry[packageName].rootRelativeDir;\n const unpackDir = join(tmpDir, dir);\n log.debug(\"Unpacking\", `(temp)/${path.basename(filePath)}`);\n await unpack(filePath, unpackDir);\n const destinationDir = join(isolateDir, dir);", "score": 0.8687908053398132 }, { "filename": "src/index.ts", "retrieved_chunk": " await fs.ensureDir(isolateDir);\n const tmpDir = path.join(isolateDir, \"__tmp\");\n await fs.ensureDir(tmpDir);\n const targetPackageManifest = await readTypedJson<PackageManifest>(\n path.join(targetPackageDir, \"package.json\")\n );\n const packageManager = detectPackageManager(workspaceRootDir);\n log.debug(\n \"Detected package manager\",\n packageManager.name,", "score": 0.857326328754425 }, { "filename": "src/helpers/process-lockfile.ts", "retrieved_chunk": " targetPackageName,\n packagesRegistry,\n isolateDir,\n}: {\n workspaceRootDir: string;\n targetPackageName: string;\n packagesRegistry: PackagesRegistry;\n isolateDir: string;\n}) {\n const log = createLogger(getConfig().logLevel);", "score": 0.8527408838272095 }, { "filename": "src/helpers/find-packages-globs.ts", "retrieved_chunk": " const { packages: globs } = readTypedYamlSync<{ packages: string[] }>(\n path.join(workspaceRootDir, \"pnpm-workspace.yaml\")\n );\n log.debug(\"Detected pnpm packages globs:\", inspectValue(globs));\n return globs;\n }\n case \"yarn\":\n case \"npm\": {\n const workspaceRootManifestPath = path.join(\n workspaceRootDir,", "score": 0.8476948142051697 } ]
typescript
allPackages.map(async (rootRelativeDir) => {
import { scrapeContent } from "../../scraper/xvideos/xvideosSearchController"; import c from "../../utils/options"; import { logger } from "../../utils/logger"; import { maybeError, spacer } from "../../utils/modifier"; import { Request, Response } from "express"; export async function searchXvideos(req: Request, res: Response) { try { /** * @api {get} /xvideos/search Search xvideos videos * @apiName Search xvideos * @apiGroup xvideos * @apiDescription Search xvideos videos * @apiParam {String} key Keyword to search * @apiParam {Number} [page=0] Page number * * @apiSuccessExample {json} Success-Response: * HTTP/1.1 200 OK * HTTP/1.1 400 Bad Request * * @apiExample {curl} curl * curl -i https://lust.scathach.id/xvideos/search?key=milf * curl -i https://lust.scathach.id/xvideos/search?key=milf&page=2 * * @apiExample {js} JS/TS * import axios from "axios" * * axios.get("https://lust.scathach.id/xvideos/search?key=milf") * .then(res => console.log(res.data)) * .catch(err => console.error(err)) * * @apiExample {python} Python * import aiohttp * async with aiohttp.ClientSession() as session: * async with session.get("https://lust.scathach.id/xvideos/search?key=milf") as resp: * print(await resp.json()) */ const key = req.query.key as string; const page = req.query.page || 0; if (!key) throw Error("Parameter key is required"); if (isNaN(Number(page))) throw Error("Parameter page must be a number"); const url = `${c
.XVIDEOS}/?k=${spacer(key)}&p=${page}`;
const data = await scrapeContent(url); logger.info({ path: req.path, query: req.query, method: req.method, ip: req.ip, useragent: req.get("User-Agent") }); return res.json(data); } catch (err) { const e = err as Error; res.status(400).json(maybeError(false, e.message)); } }
src/controller/xvideos/xvideosSearch.ts
sinkaroid-lustpress-ac1a6d8
[ { "filename": "src/controller/xhamster/xhamsterSearch.ts", "retrieved_chunk": " * @apiExample {python} Python\n * import aiohttp\n * async with aiohttp.ClientSession() as session:\n * async with session.get(\"https://lust.scathach.id/xhamster/search?key=milf\") as resp:\n * print(await resp.json())\n */\n const key = req.query.key as string;\n const page = req.query.page || 1;\n if (!key) throw Error(\"Parameter key is required\");\n if (isNaN(Number(page))) throw Error(\"Parameter page must be a number\");", "score": 0.9586790204048157 }, { "filename": "src/controller/xnxx/xnxxSearch.ts", "retrieved_chunk": " * @apiExample {python} Python\n * import aiohttp\n * async with aiohttp.ClientSession() as session:\n * async with session.get(\"https://lust.scathach.id/xnxx/search?key=milf\") as resp:\n * print(await resp.json())\n */\n const key = req.query.key as string;\n const page = req.query.page || 0;\n if (!key) throw Error(\"Parameter key is required\");\n if (isNaN(Number(page))) throw Error(\"Parameter page must be a number\");", "score": 0.956850528717041 }, { "filename": "src/controller/youporn/youpornSearch.ts", "retrieved_chunk": " * @apiExample {python} Python\n * import aiohttp\n * async with aiohttp.ClientSession() as session:\n * async with session.get(\"https://lust.scathach.id/youporn/search?key=milf\") as resp:\n * print(await resp.json())\n */\n const key = req.query.key as string;\n const page = req.query.page || 1;\n if (!key) throw Error(\"Parameter key is required\");\n if (isNaN(Number(page))) throw Error(\"Parameter page must be a number\");", "score": 0.9551706314086914 }, { "filename": "src/controller/redtube/redtubeSearch.ts", "retrieved_chunk": " * @apiExample {python} Python\n * import aiohttp\n * async with aiohttp.ClientSession() as session:\n * async with session.get(\"https://lust.scathach.id/redtube/search?key=milf\") as resp:\n * print(await resp.json())\n */\n const key = req.query.key as string;\n const page = req.query.page || 1;\n if (!key) throw Error(\"Parameter key is required\");\n if (isNaN(Number(page))) throw Error(\"Parameter page must be a number\");", "score": 0.9540885090827942 }, { "filename": "src/controller/pornhub/pornhubSearch.ts", "retrieved_chunk": " * .catch(err => console.error(err))\n * \n * @apiExample {python} Python\n * import aiohttp\n * async with aiohttp.ClientSession() as session:\n * async with session.get(\"https://lust.scathach.id/pornhub/search?key=milf\") as resp:\n * print(await resp.json())\n */\n const key = req.query.key as string;\n const page = req.query.page || 1;", "score": 0.940386176109314 } ]
typescript
.XVIDEOS}/?k=${spacer(key)}&p=${page}`;
import assert from "node:assert"; import { createLogger, pack } from "~/utils"; import { getConfig } from "./config"; import { PackagesRegistry } from "./create-packages-registry"; import { usePackageManager } from "./detect-package-manager"; /** * Pack dependencies so that we extract only the files that are supposed to be * published by the packages. * * @returns A map of package names to the path of the packed file */ export async function packDependencies({ /** * All packages found in the monorepo by workspaces declaration */ packagesRegistry, /** * The package names that appear to be local dependencies */ localDependencies, /** * The directory where the isolated package and all its dependencies will end * up. This is also the directory from where the package will be deployed. By * default it is a subfolder in targetPackageDir called "isolate" but you can * configure it. */ packDestinationDir, }: { packagesRegistry: PackagesRegistry; localDependencies: string[]; packDestinationDir: string; }) { const config = getConfig(); const log = createLogger(config.logLevel); const packedFileByName: Record<string, string> = {}; const { name, version } = usePackageManager(); const versionMajor = parseInt(version.split(".")[0], 10); const usePnpmPack = !config.avoidPnpmPack && name === "pnpm" && versionMajor >= 8; if (usePnpmPack) { log.debug("Using PNPM pack instead of NPM pack"); } for (const dependency of localDependencies) { const def = packagesRegistry[dependency]; assert(dependency, `Failed to find package definition for ${dependency}`); const { name } = def.manifest; /** * If this dependency has already been packed, we skip it. It could happen * because we are packing workspace dependencies recursively. */ if (packedFileByName[name]) { log.debug(`Skipping ${name} because it has already been packed`); continue; }
packedFileByName[name] = await pack( def.absoluteDir, packDestinationDir, usePnpmPack );
} return packedFileByName; }
src/helpers/pack-dependencies.ts
0x80-isolate-package-4fe8eaf
[ { "filename": "src/helpers/unpack-dependencies.ts", "retrieved_chunk": " isolateDir: string\n) {\n const log = createLogger(getConfig().logLevel);\n await Promise.all(\n Object.entries(packedFilesByName).map(async ([packageName, filePath]) => {\n const dir = packagesRegistry[packageName].rootRelativeDir;\n const unpackDir = join(tmpDir, dir);\n log.debug(\"Unpacking\", `(temp)/${path.basename(filePath)}`);\n await unpack(filePath, unpackDir);\n const destinationDir = join(isolateDir, dir);", "score": 0.851274847984314 }, { "filename": "src/helpers/process-build-output-files.ts", "retrieved_chunk": " if (!isWaitingYet) {\n log.debug(`Waiting for ${packedFilePath} to become available...`);\n }\n isWaitingYet = true;\n await new Promise((resolve) => setTimeout(resolve, 100));\n }\n await unpack(packedFilePath, unpackDir);\n await fs.copy(path.join(unpackDir, \"package\"), isolateDir);\n}", "score": 0.8434476852416992 }, { "filename": "src/utils/pack.ts", "retrieved_chunk": " `The response from pack could not be resolved to an existing file: ${filePath}`\n );\n } else {\n log.debug(`Packed (temp)/${fileName}`);\n }\n process.chdir(previousCwd);\n /**\n * Return the path anyway even if it doesn't validate. A later stage will wait\n * for the file to occur still. Not sure if this makes sense. Maybe we should\n * stop at the validation error...", "score": 0.8290923237800598 }, { "filename": "src/helpers/unpack-dependencies.ts", "retrieved_chunk": " await fs.ensureDir(destinationDir);\n await fs.move(join(unpackDir, \"package\"), destinationDir, {\n overwrite: true,\n });\n log.debug(\n `Moved package files to ${getIsolateRelativePath(\n destinationDir,\n isolateDir\n )}`\n );", "score": 0.8257913589477539 }, { "filename": "src/utils/pack.ts", "retrieved_chunk": " const stdout = usePnpmPack\n ? await new Promise<string>((resolve, reject) => {\n exec(\n `pnpm pack --pack-destination ${dstDir}`,\n execOptions,\n (err, stdout, stderr) => {\n if (err) {\n log.error(stderr);\n return reject(err);\n }", "score": 0.8252675533294678 } ]
typescript
packedFileByName[name] = await pack( def.absoluteDir, packDestinationDir, usePnpmPack );
import fs from "fs-extra"; import { globSync } from "glob"; import path from "node:path"; import { createLogger, readTypedJson } from "~/utils"; import { getConfig } from "./config"; import { findPackagesGlobs } from "./find-packages-globs"; export type PackageManifest = { name: string; packageManager?: string; dependencies?: Record<string, string>; devDependencies?: Record<string, string>; main: string; module?: string; exports?: Record<string, { require: string; import: string }>; files: string[]; version?: string; typings?: string; scripts?: Record<string, string>; }; export type WorkspacePackageInfo = { absoluteDir: string; /** * The path of the package relative to the workspace root. This is the path * referenced in the lock file. */ rootRelativeDir: string; /** * The package.json file contents */ manifest: PackageManifest; }; export type PackagesRegistry = Record<string, WorkspacePackageInfo>; /** * Build a list of all packages in the workspace, depending on the package * manager used, with a possible override from the config file. The list contains * the manifest with some directory info mapped by module name. */ export async function createPackagesRegistry( workspaceRootDir: string, workspacePackagesOverride: string[] | undefined ): Promise<PackagesRegistry> { const log = createLogger(getConfig().logLevel); if (workspacePackagesOverride) { log.debug( `Override workspace packages via config: ${workspacePackagesOverride}` ); } const packagesGlobs = workspacePackagesOverride ?? findPackagesGlobs(workspaceRootDir); const cwd = process.cwd(); process.chdir(workspaceRootDir); const allPackages = packagesGlobs .flatMap((glob) => globSync(glob)) /** * Make sure to filter any loose files that might hang around. */ .filter((dir) => fs.lstatSync(dir).isDirectory()); const registry: PackagesRegistry = ( await Promise.all( allPackages.map(async (rootRelativeDir) => { const manifestPath = path.join(rootRelativeDir, "package.json"); if (!fs.existsSync(manifestPath)) { log.warn( `Ignoring directory ./${rootRelativeDir} because it does not contain a package.json file` ); return; } else { log.debug(`Registering package ./${rootRelativeDir}`); const manifest =
await readTypedJson<PackageManifest>( path.join(rootRelativeDir, "package.json") );
return { manifest, rootRelativeDir, absoluteDir: path.join(workspaceRootDir, rootRelativeDir), }; } }) ) ).reduce<PackagesRegistry>((acc, info) => { if (info) { acc[info.manifest.name] = info; } return acc; }, {}); process.chdir(cwd); return registry; }
src/helpers/create-packages-registry.ts
0x80-isolate-package-4fe8eaf
[ { "filename": "src/helpers/manifest.ts", "retrieved_chunk": "import path from \"node:path\";\nimport { readTypedJson } from \"~/utils\";\nimport { PackageManifest } from \"./create-packages-registry\";\nexport async function importManifest(packageDir: string) {\n return readTypedJson<PackageManifest>(path.join(packageDir, \"package.json\"));\n}", "score": 0.8599456548690796 }, { "filename": "src/index.ts", "retrieved_chunk": " await fs.ensureDir(isolateDir);\n const tmpDir = path.join(isolateDir, \"__tmp\");\n await fs.ensureDir(tmpDir);\n const targetPackageManifest = await readTypedJson<PackageManifest>(\n path.join(targetPackageDir, \"package.json\")\n );\n const packageManager = detectPackageManager(workspaceRootDir);\n log.debug(\n \"Detected package manager\",\n packageManager.name,", "score": 0.8562734723091125 }, { "filename": "src/helpers/detect-package-manager.ts", "retrieved_chunk": "function inferFromManifest(workspaceRoot: string) {\n const log = createLogger(getConfig().logLevel);\n const rootManifest = readTypedJsonSync<PackageManifest>(\n path.join(workspaceRoot, \"package.json\")\n );\n if (!rootManifest.packageManager) {\n log.debug(\"No packageManager field found in root manifest\");\n return;\n }\n const [name, version = \"*\"] = rootManifest.packageManager.split(\"@\") as [", "score": 0.8383061289787292 }, { "filename": "src/helpers/adapt-manifest-files.ts", "retrieved_chunk": " await fs.writeFile(\n path.join(isolateDir, rootRelativeDir, \"package.json\"),\n JSON.stringify(outputManifest, null, 2)\n );\n })\n );\n}", "score": 0.8344428539276123 }, { "filename": "src/helpers/get-build-output-dir.ts", "retrieved_chunk": " return path.join(targetPackageDir, config.buildDirName);\n }\n const tsconfigPath = path.join(targetPackageDir, config.tsconfigPath);\n if (fs.existsSync(tsconfigPath)) {\n log.debug(\"Found tsconfig at:\", config.tsconfigPath);\n const tsconfig = await readTypedJson<{\n compilerOptions?: { outDir?: string };\n }>(tsconfigPath);\n const outDir = tsconfig.compilerOptions?.outDir;\n if (outDir) {", "score": 0.8268182277679443 } ]
typescript
await readTypedJson<PackageManifest>( path.join(rootRelativeDir, "package.json") );
import { scrapeContent } from "../../scraper/xnxx/xnxxSearchController"; import c from "../../utils/options"; import { logger } from "../../utils/logger"; import { maybeError, spacer } from "../../utils/modifier"; import { Request, Response } from "express"; export async function searchXnxx(req: Request, res: Response) { try { /** * @api {get} /xnxx/search Search xnxx videos * @apiName Search xnxx * @apiGroup xnxx * @apiDescription Search xnxx videos * @apiParam {String} key Keyword to search * @apiParam {Number} [page=0] Page number * * @apiSuccessExample {json} Success-Response: * HTTP/1.1 200 OK * HTTP/1.1 400 Bad Request * * @apiExample {curl} curl * curl -i https://lust.scathach.id/xnxx/search?key=milf * curl -i https://lust.scathach.id/xnxx/search?key=milf&page=2 * * @apiExample {js} JS/TS * import axios from "axios" * * axios.get("https://lust.scathach.id/xnxx/search?key=milf") * .then(res => console.log(res.data)) * .catch(err => console.error(err)) * * @apiExample {python} Python * import aiohttp * async with aiohttp.ClientSession() as session: * async with session.get("https://lust.scathach.id/xnxx/search?key=milf") as resp: * print(await resp.json()) */ const key = req.query.key as string; const page = req.query.page || 0; if (!key) throw Error("Parameter key is required"); if (isNaN(Number(page))) throw Error("Parameter page must be a number");
const url = `${c.XNXX}/search/${spacer(key)}/${page}`;
const data = await scrapeContent(url); logger.info({ path: req.path, query: req.query, method: req.method, ip: req.ip, useragent: req.get("User-Agent") }); return res.json(data); } catch (err) { const e = err as Error; res.status(400).json(maybeError(false, e.message)); } }
src/controller/xnxx/xnxxSearch.ts
sinkaroid-lustpress-ac1a6d8
[ { "filename": "src/controller/xhamster/xhamsterSearch.ts", "retrieved_chunk": " * @apiExample {python} Python\n * import aiohttp\n * async with aiohttp.ClientSession() as session:\n * async with session.get(\"https://lust.scathach.id/xhamster/search?key=milf\") as resp:\n * print(await resp.json())\n */\n const key = req.query.key as string;\n const page = req.query.page || 1;\n if (!key) throw Error(\"Parameter key is required\");\n if (isNaN(Number(page))) throw Error(\"Parameter page must be a number\");", "score": 0.9601067304611206 }, { "filename": "src/controller/xvideos/xvideosSearch.ts", "retrieved_chunk": " * @apiExample {python} Python\n * import aiohttp\n * async with aiohttp.ClientSession() as session:\n * async with session.get(\"https://lust.scathach.id/xvideos/search?key=milf\") as resp:\n * print(await resp.json())\n */\n const key = req.query.key as string;\n const page = req.query.page || 0;\n if (!key) throw Error(\"Parameter key is required\");\n if (isNaN(Number(page))) throw Error(\"Parameter page must be a number\");", "score": 0.9561083316802979 }, { "filename": "src/controller/youporn/youpornSearch.ts", "retrieved_chunk": " * @apiExample {python} Python\n * import aiohttp\n * async with aiohttp.ClientSession() as session:\n * async with session.get(\"https://lust.scathach.id/youporn/search?key=milf\") as resp:\n * print(await resp.json())\n */\n const key = req.query.key as string;\n const page = req.query.page || 1;\n if (!key) throw Error(\"Parameter key is required\");\n if (isNaN(Number(page))) throw Error(\"Parameter page must be a number\");", "score": 0.9551708102226257 }, { "filename": "src/controller/redtube/redtubeSearch.ts", "retrieved_chunk": " * @apiExample {python} Python\n * import aiohttp\n * async with aiohttp.ClientSession() as session:\n * async with session.get(\"https://lust.scathach.id/redtube/search?key=milf\") as resp:\n * print(await resp.json())\n */\n const key = req.query.key as string;\n const page = req.query.page || 1;\n if (!key) throw Error(\"Parameter key is required\");\n if (isNaN(Number(page))) throw Error(\"Parameter page must be a number\");", "score": 0.9534780979156494 }, { "filename": "src/controller/pornhub/pornhubSearch.ts", "retrieved_chunk": " * .catch(err => console.error(err))\n * \n * @apiExample {python} Python\n * import aiohttp\n * async with aiohttp.ClientSession() as session:\n * async with session.get(\"https://lust.scathach.id/pornhub/search?key=milf\") as resp:\n * print(await resp.json())\n */\n const key = req.query.key as string;\n const page = req.query.page || 1;", "score": 0.9421285390853882 } ]
typescript
const url = `${c.XNXX}/search/${spacer(key)}/${page}`;
import fs from "fs-extra"; import { isEmpty } from "lodash-es"; import path from "node:path"; import { createLogger, inspectValue, readTypedJsonSync } from "~/utils"; export type IsolateConfigResolved = { buildDirName?: string; includeDevDependencies: boolean; isolateDirName: string; logLevel: "info" | "debug" | "warn" | "error"; targetPackagePath?: string; tsconfigPath: string; workspacePackages?: string[]; workspaceRoot: string; excludeLockfile: boolean; avoidPnpmPack: boolean; }; export type IsolateConfig = Partial<IsolateConfigResolved>; const configDefaults: IsolateConfigResolved = { buildDirName: undefined, includeDevDependencies: false, isolateDirName: "isolate", logLevel: "info", targetPackagePath: undefined, tsconfigPath: "./tsconfig.json", workspacePackages: undefined, workspaceRoot: "../..", excludeLockfile: false, avoidPnpmPack: false, }; /** * Only initialize the configuration once, and keeping it here for subsequent * calls to getConfig. */ let __config: IsolateConfigResolved | undefined; const validConfigKeys = Object.keys(configDefaults); const CONFIG_FILE_NAME = "isolate.config.json"; type LogLevel = IsolateConfigResolved["logLevel"]; export function getConfig(): IsolateConfigResolved { if (__config) { return __config; } /** * Since the logLevel is set via config we can't use it to determine if we * should output verbose logging as part of the config loading process. Using * the env var ISOLATE_CONFIG_LOG_LEVEL you have the option to log debug * output. */ const log = createLogger( (process.env.ISOLATE_CONFIG_LOG_LEVEL as LogLevel) ?? "warn" ); const configFilePath = path.join(process.cwd(), CONFIG_FILE_NAME); log.debug(`Attempting to load config from ${configFilePath}`); const configFromFile = fs.existsSync(configFilePath)
? readTypedJsonSync<IsolateConfig>(configFilePath) : {};
const foreignKeys = Object.keys(configFromFile).filter( (key) => !validConfigKeys.includes(key) ); if (!isEmpty(foreignKeys)) { log.warn(`Found invalid config settings:`, foreignKeys.join(", ")); } const config = Object.assign( {}, configDefaults, configFromFile ) satisfies IsolateConfigResolved; log.debug("Using configuration:", inspectValue(config)); __config = config; return config; }
src/helpers/config.ts
0x80-isolate-package-4fe8eaf
[ { "filename": "src/index.ts", "retrieved_chunk": "} from \"~/helpers\";\nimport {\n createLogger,\n getDirname,\n getRootRelativePath,\n readTypedJson,\n} from \"~/utils\";\nconst config = getConfig();\nconst log = createLogger(config.logLevel);\nsourceMaps.install();", "score": 0.8404440879821777 }, { "filename": "src/helpers/process-build-output-files.ts", "retrieved_chunk": "import fs from \"fs-extra\";\nimport path from \"node:path\";\nimport { createLogger, pack, unpack } from \"~/utils\";\nimport { getConfig } from \"./config\";\nconst TIMEOUT_MS = 5000;\nexport async function processBuildOutputFiles({\n targetPackageDir,\n tmpDir,\n isolateDir,\n}: {", "score": 0.8403539061546326 }, { "filename": "src/utils/logger.ts", "retrieved_chunk": "import chalk from \"chalk\";\nimport { IsolateConfigResolved } from \"~/helpers\";\nexport type Logger = {\n debug(...args: any[]): void;\n info(...args: any[]): void;\n warn(...args: any[]): void;\n error(...args: any[]): void;\n};\nexport function createLogger(\n logLevel: IsolateConfigResolved[\"logLevel\"]", "score": 0.8397868275642395 }, { "filename": "src/index.ts", "retrieved_chunk": " : path.join(targetPackageDir, config.workspaceRoot);\n const buildOutputDir = await getBuildOutputDir(targetPackageDir);\n assert(\n fs.existsSync(buildOutputDir),\n `Failed to find build output path at ${buildOutputDir}. Please make sure you build the source before isolating it.`\n );\n log.debug(\"Workspace root resolved to\", workspaceRootDir);\n log.debug(\n \"Isolate target package\",\n getRootRelativePath(targetPackageDir, workspaceRootDir)", "score": 0.8395068645477295 }, { "filename": "src/index.ts", "retrieved_chunk": " await fs.ensureDir(isolateDir);\n const tmpDir = path.join(isolateDir, \"__tmp\");\n await fs.ensureDir(tmpDir);\n const targetPackageManifest = await readTypedJson<PackageManifest>(\n path.join(targetPackageDir, \"package.json\")\n );\n const packageManager = detectPackageManager(workspaceRootDir);\n log.debug(\n \"Detected package manager\",\n packageManager.name,", "score": 0.8392049670219421 } ]
typescript
? readTypedJsonSync<IsolateConfig>(configFilePath) : {};
import fs from "fs-extra"; import { globSync } from "glob"; import path from "node:path"; import { createLogger, readTypedJson } from "~/utils"; import { getConfig } from "./config"; import { findPackagesGlobs } from "./find-packages-globs"; export type PackageManifest = { name: string; packageManager?: string; dependencies?: Record<string, string>; devDependencies?: Record<string, string>; main: string; module?: string; exports?: Record<string, { require: string; import: string }>; files: string[]; version?: string; typings?: string; scripts?: Record<string, string>; }; export type WorkspacePackageInfo = { absoluteDir: string; /** * The path of the package relative to the workspace root. This is the path * referenced in the lock file. */ rootRelativeDir: string; /** * The package.json file contents */ manifest: PackageManifest; }; export type PackagesRegistry = Record<string, WorkspacePackageInfo>; /** * Build a list of all packages in the workspace, depending on the package * manager used, with a possible override from the config file. The list contains * the manifest with some directory info mapped by module name. */ export async function createPackagesRegistry( workspaceRootDir: string, workspacePackagesOverride: string[] | undefined ): Promise<PackagesRegistry> { const log = createLogger(getConfig().logLevel); if (workspacePackagesOverride) { log.debug( `Override workspace packages via config: ${workspacePackagesOverride}` ); } const packagesGlobs = workspacePackagesOverride ?? findPackagesGlobs(workspaceRootDir); const cwd = process.cwd(); process.chdir(workspaceRootDir); const allPackages = packagesGlobs .flatMap((glob) => globSync(glob)) /** * Make sure to filter any loose files that might hang around. */ .filter
((dir) => fs.lstatSync(dir).isDirectory());
const registry: PackagesRegistry = ( await Promise.all( allPackages.map(async (rootRelativeDir) => { const manifestPath = path.join(rootRelativeDir, "package.json"); if (!fs.existsSync(manifestPath)) { log.warn( `Ignoring directory ./${rootRelativeDir} because it does not contain a package.json file` ); return; } else { log.debug(`Registering package ./${rootRelativeDir}`); const manifest = await readTypedJson<PackageManifest>( path.join(rootRelativeDir, "package.json") ); return { manifest, rootRelativeDir, absoluteDir: path.join(workspaceRootDir, rootRelativeDir), }; } }) ) ).reduce<PackagesRegistry>((acc, info) => { if (info) { acc[info.manifest.name] = info; } return acc; }, {}); process.chdir(cwd); return registry; }
src/helpers/create-packages-registry.ts
0x80-isolate-package-4fe8eaf
[ { "filename": "src/helpers/find-packages-globs.ts", "retrieved_chunk": " const { packages: globs } = readTypedYamlSync<{ packages: string[] }>(\n path.join(workspaceRootDir, \"pnpm-workspace.yaml\")\n );\n log.debug(\"Detected pnpm packages globs:\", inspectValue(globs));\n return globs;\n }\n case \"yarn\":\n case \"npm\": {\n const workspaceRootManifestPath = path.join(\n workspaceRootDir,", "score": 0.8673906922340393 }, { "filename": "src/helpers/find-packages-globs.ts", "retrieved_chunk": "/**\n * Find the globs that define where the packages are located within the\n * monorepo. This configuration is dependent on the package manager used, and I\n * don't know if we're covering all cases yet...\n */\nexport function findPackagesGlobs(workspaceRootDir: string) {\n const log = createLogger(getConfig().logLevel);\n const packageManager = usePackageManager();\n switch (packageManager.name) {\n case \"pnpm\": {", "score": 0.8670047521591187 }, { "filename": "src/helpers/adapt-manifest-files.ts", "retrieved_chunk": " packagesRegistry: PackagesRegistry,\n isolateDir: string\n) {\n await Promise.all(\n localDependencies.map(async (packageName) => {\n const { manifest, rootRelativeDir } = packagesRegistry[packageName];\n const outputManifest = adaptManifestWorkspaceDeps(\n { manifest, packagesRegistry, parentRootRelativeDir: rootRelativeDir },\n { includeDevDependencies: getConfig().includeDevDependencies }\n );", "score": 0.846515953540802 }, { "filename": "src/index.ts", "retrieved_chunk": " */\n const targetPackageDir = config.targetPackagePath\n ? path.join(process.cwd(), config.targetPackagePath)\n : process.cwd();\n /**\n * We want a trailing slash here. Functionally it doesn't matter, but it makes\n * the relative paths more correct in the debug output.\n */\n const workspaceRootDir = config.targetPackagePath\n ? process.cwd()", "score": 0.8452800512313843 }, { "filename": "src/index.ts", "retrieved_chunk": " await fs.ensureDir(isolateDir);\n const tmpDir = path.join(isolateDir, \"__tmp\");\n await fs.ensureDir(tmpDir);\n const targetPackageManifest = await readTypedJson<PackageManifest>(\n path.join(targetPackageDir, \"package.json\")\n );\n const packageManager = detectPackageManager(workspaceRootDir);\n log.debug(\n \"Detected package manager\",\n packageManager.name,", "score": 0.8415641188621521 } ]
typescript
((dir) => fs.lstatSync(dir).isDirectory());
import fs from "fs-extra"; import { isEmpty } from "lodash-es"; import path from "node:path"; import { createLogger, inspectValue, readTypedJsonSync } from "~/utils"; export type IsolateConfigResolved = { buildDirName?: string; includeDevDependencies: boolean; isolateDirName: string; logLevel: "info" | "debug" | "warn" | "error"; targetPackagePath?: string; tsconfigPath: string; workspacePackages?: string[]; workspaceRoot: string; excludeLockfile: boolean; avoidPnpmPack: boolean; }; export type IsolateConfig = Partial<IsolateConfigResolved>; const configDefaults: IsolateConfigResolved = { buildDirName: undefined, includeDevDependencies: false, isolateDirName: "isolate", logLevel: "info", targetPackagePath: undefined, tsconfigPath: "./tsconfig.json", workspacePackages: undefined, workspaceRoot: "../..", excludeLockfile: false, avoidPnpmPack: false, }; /** * Only initialize the configuration once, and keeping it here for subsequent * calls to getConfig. */ let __config: IsolateConfigResolved | undefined; const validConfigKeys = Object.keys(configDefaults); const CONFIG_FILE_NAME = "isolate.config.json"; type LogLevel = IsolateConfigResolved["logLevel"]; export function getConfig(): IsolateConfigResolved { if (__config) { return __config; } /** * Since the logLevel is set via config we can't use it to determine if we * should output verbose logging as part of the config loading process. Using * the env var ISOLATE_CONFIG_LOG_LEVEL you have the option to log debug * output. */ const log = createLogger( (process.env.ISOLATE_CONFIG_LOG_LEVEL as LogLevel) ?? "warn" ); const configFilePath = path.join(process.cwd(), CONFIG_FILE_NAME); log.debug(`Attempting to load config from ${configFilePath}`); const configFromFile = fs.existsSync(configFilePath) ? readTypedJsonSync<IsolateConfig>(configFilePath) : {}; const foreignKeys = Object.keys(configFromFile).filter( (key) => !validConfigKeys.includes(key) ); if (!isEmpty(foreignKeys)) { log.warn(`Found invalid config settings:`, foreignKeys.join(", ")); } const config = Object.assign( {}, configDefaults, configFromFile ) satisfies IsolateConfigResolved;
log.debug("Using configuration:", inspectValue(config));
__config = config; return config; }
src/helpers/config.ts
0x80-isolate-package-4fe8eaf
[ { "filename": "src/index.ts", "retrieved_chunk": " : path.join(targetPackageDir, config.workspaceRoot);\n const buildOutputDir = await getBuildOutputDir(targetPackageDir);\n assert(\n fs.existsSync(buildOutputDir),\n `Failed to find build output path at ${buildOutputDir}. Please make sure you build the source before isolating it.`\n );\n log.debug(\"Workspace root resolved to\", workspaceRootDir);\n log.debug(\n \"Isolate target package\",\n getRootRelativePath(targetPackageDir, workspaceRootDir)", "score": 0.7985770106315613 }, { "filename": "src/index.ts", "retrieved_chunk": " * isolate because the settings there could affect how the lockfile is\n * resolved. Note that .npmrc is used by both NPM and PNPM for configuration.\n *\n * See also: https://pnpm.io/npmrc\n */\n const npmrcPath = path.join(workspaceRootDir, \".npmrc\");\n if (fs.existsSync(npmrcPath)) {\n fs.copyFileSync(npmrcPath, path.join(isolateDir, \".npmrc\"));\n log.debug(\"Copied .npmrc file to the isolate output\");\n }", "score": 0.7927068471908569 }, { "filename": "src/helpers/patch-workspace-entries.ts", "retrieved_chunk": " const allWorkspacePackageNames = Object.keys(packagesRegistry);\n return Object.fromEntries(\n Object.entries(dependencies).map(([key, value]) => {\n if (allWorkspacePackageNames.includes(key)) {\n const def = packagesRegistry[key];\n /**\n * When nested shared dependencies are used (local deps linking to other\n * local deps), the parentRootRelativeDir will be passed in, and we\n * store the relative path to the isolate/packages directory, as is\n * required by some package managers.", "score": 0.7906752824783325 }, { "filename": "src/helpers/process-lockfile.ts", "retrieved_chunk": " */\n const shrinkwrapSrcPath = path.join(\n workspaceRootDir,\n \"npm-shrinkwrap.json\"\n );\n const shrinkwrapDstPath = path.join(isolateDir, \"npm-shrinkwrap.json\");\n if (fs.existsSync(shrinkwrapSrcPath)) {\n fs.copyFileSync(shrinkwrapSrcPath, shrinkwrapDstPath);\n log.debug(\"Copied shrinkwrap to\", shrinkwrapDstPath);\n } else {", "score": 0.7858123779296875 }, { "filename": "src/index.ts", "retrieved_chunk": " );\n const isolateDir = path.join(targetPackageDir, config.isolateDirName);\n log.debug(\n \"Isolate output directory\",\n getRootRelativePath(isolateDir, workspaceRootDir)\n );\n if (fs.existsSync(isolateDir)) {\n await fs.remove(isolateDir);\n log.debug(\"Cleaned the existing isolate output directory\");\n }", "score": 0.7841241955757141 } ]
typescript
log.debug("Using configuration:", inspectValue(config));
import fs from "fs-extra"; import { isEmpty } from "lodash-es"; import path from "node:path"; import { createLogger, inspectValue, readTypedJsonSync } from "~/utils"; export type IsolateConfigResolved = { buildDirName?: string; includeDevDependencies: boolean; isolateDirName: string; logLevel: "info" | "debug" | "warn" | "error"; targetPackagePath?: string; tsconfigPath: string; workspacePackages?: string[]; workspaceRoot: string; excludeLockfile: boolean; avoidPnpmPack: boolean; }; export type IsolateConfig = Partial<IsolateConfigResolved>; const configDefaults: IsolateConfigResolved = { buildDirName: undefined, includeDevDependencies: false, isolateDirName: "isolate", logLevel: "info", targetPackagePath: undefined, tsconfigPath: "./tsconfig.json", workspacePackages: undefined, workspaceRoot: "../..", excludeLockfile: false, avoidPnpmPack: false, }; /** * Only initialize the configuration once, and keeping it here for subsequent * calls to getConfig. */ let __config: IsolateConfigResolved | undefined; const validConfigKeys = Object.keys(configDefaults); const CONFIG_FILE_NAME = "isolate.config.json"; type LogLevel = IsolateConfigResolved["logLevel"]; export function getConfig(): IsolateConfigResolved { if (__config) { return __config; } /** * Since the logLevel is set via config we can't use it to determine if we * should output verbose logging as part of the config loading process. Using * the env var ISOLATE_CONFIG_LOG_LEVEL you have the option to log debug * output. */ const log = createLogger( (process.env.ISOLATE_CONFIG_LOG_LEVEL as LogLevel) ?? "warn" ); const configFilePath = path.join(process.cwd(), CONFIG_FILE_NAME); log.debug(`Attempting to load config from ${configFilePath}`); const configFromFile = fs.existsSync(configFilePath) ?
readTypedJsonSync<IsolateConfig>(configFilePath) : {};
const foreignKeys = Object.keys(configFromFile).filter( (key) => !validConfigKeys.includes(key) ); if (!isEmpty(foreignKeys)) { log.warn(`Found invalid config settings:`, foreignKeys.join(", ")); } const config = Object.assign( {}, configDefaults, configFromFile ) satisfies IsolateConfigResolved; log.debug("Using configuration:", inspectValue(config)); __config = config; return config; }
src/helpers/config.ts
0x80-isolate-package-4fe8eaf
[ { "filename": "src/index.ts", "retrieved_chunk": "} from \"~/helpers\";\nimport {\n createLogger,\n getDirname,\n getRootRelativePath,\n readTypedJson,\n} from \"~/utils\";\nconst config = getConfig();\nconst log = createLogger(config.logLevel);\nsourceMaps.install();", "score": 0.8531529903411865 }, { "filename": "src/index.ts", "retrieved_chunk": " await fs.ensureDir(isolateDir);\n const tmpDir = path.join(isolateDir, \"__tmp\");\n await fs.ensureDir(tmpDir);\n const targetPackageManifest = await readTypedJson<PackageManifest>(\n path.join(targetPackageDir, \"package.json\")\n );\n const packageManager = detectPackageManager(workspaceRootDir);\n log.debug(\n \"Detected package manager\",\n packageManager.name,", "score": 0.8465235233306885 }, { "filename": "src/index.ts", "retrieved_chunk": "async function start() {\n const __dirname = getDirname(import.meta.url);\n const thisPackageManifest = await readTypedJson<PackageManifest>(\n path.join(path.join(__dirname, \"..\", \"package.json\"))\n );\n log.debug(\"Running isolate-package version\", thisPackageManifest.version);\n /**\n * If a targetPackagePath is set, we assume the configuration lives in the\n * root of the workspace. If targetPackagePath is undefined (the default), we\n * assume that the configuration lives in the target package directory.", "score": 0.846004068851471 }, { "filename": "src/utils/logger.ts", "retrieved_chunk": "import chalk from \"chalk\";\nimport { IsolateConfigResolved } from \"~/helpers\";\nexport type Logger = {\n debug(...args: any[]): void;\n info(...args: any[]): void;\n warn(...args: any[]): void;\n error(...args: any[]): void;\n};\nexport function createLogger(\n logLevel: IsolateConfigResolved[\"logLevel\"]", "score": 0.845513105392456 }, { "filename": "src/helpers/detect-package-manager.ts", "retrieved_chunk": "import fs from \"fs-extra\";\nimport assert from \"node:assert\";\nimport { execSync } from \"node:child_process\";\nimport path from \"node:path\";\nimport { createLogger, readTypedJsonSync } from \"~/utils\";\nimport { getConfig } from \"./config\";\nimport { PackageManifest } from \"./create-packages-registry\";\nimport { getLockfileFileName } from \"./process-lockfile\";\nconst supportedPackageManagerNames = [\"pnpm\", \"yarn\", \"npm\"] as const;\nexport type PackageManagerName = (typeof supportedPackageManagerNames)[number];", "score": 0.8419296741485596 } ]
typescript
readTypedJsonSync<IsolateConfig>(configFilePath) : {};