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/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.8109738826751709
},
{
"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.804944634437561
},
{
"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.8028686046600342
},
{
"filename": "src/app.ts",
"retrieved_chunk": " for (const middlware of this.postAuthorizeMiddleware) {\n const response = await middlware(baseRequest);\n if (response) {\n return toCompleteResponse(response);\n }\n }\n const payload = body as SlackRequestBody;\n if (body.type === PayloadType.EventsAPI) {\n // Events API\n const slackRequest: SlackRequest<E, SlackEvent<string>> = {",
"score": 0.7960391044616699
},
{
"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.7890445590019226
}
] | typescript | const authorizeUrl = generateAuthorizeUrl(stateValue, this.env); |
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.7824206352233887
},
{
"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.7787405252456665
},
{
"filename": "src/app.ts",
"retrieved_chunk": " client: new SlackAPIClient(authorizeResult.botToken, {\n logLevel: this.env.SLACK_LOGGING_LEVEL,\n }),\n botToken: authorizeResult.botToken,\n botId: authorizeResult.botId,\n botUserId: authorizeResult.botUserId,\n userToken: authorizeResult.userToken,\n };\n if (authorizedContext.channelId) {\n const context = authorizedContext as SlackAppContextWithChannelId;",
"score": 0.7756693363189697
},
{
"filename": "src/oauth/installation-store.ts",
"retrieved_chunk": "import { SlackOAuthEnv } from \"../app-env\";\nimport { Authorize } from \"../authorization/authorize\";\nimport { Installation } from \"./installation\";\nexport interface InstallationStoreQuery {\n enterpriseId?: string;\n teamId?: string;\n userId?: string;\n isEnterpriseInstall?: boolean;\n}\nexport interface InstallationStore<E extends SlackOAuthEnv> {",
"score": 0.7521806955337524
},
{
"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.7509079575538635
}
] | 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/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.8143414258956909
},
{
"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.8098912239074707
},
{
"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.8092787265777588
},
{
"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.7884279489517212
},
{
"filename": "src/response/response.ts",
"retrieved_chunk": "import {\n MessageResponse,\n AnyOptionsResponse,\n AnyViewResponse,\n} from \"./response-body\";\nexport interface SlackResponse {\n status?: number;\n contentType?: string;\n // deno-lint-ignore no-explicit-any\n body?: string | MessageResponse | Record<string, any>;",
"score": 0.7869217395782471
}
] | typescript | postAuthorizeMiddleware: Middleware<any>[] = [ignoringSelfEvents]; |
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/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.826880931854248
},
{
"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.8136910200119019
},
{
"filename": "src/context/context.ts",
"retrieved_chunk": "export type SlackAppContextWithChannelId = {\n channelId: string;\n say: (\n params: Omit<ChatPostMessageRequest, \"channel\">\n ) => Promise<ChatPostMessageResponse>;\n} & SlackAppContext;\nexport type SlackAppContextWithRespond = {\n channelId: string;\n respond: (params: WebhookParams) => Promise<Response>;\n} & SlackAppContext;",
"score": 0.8094040155410767
},
{
"filename": "src/response/response.ts",
"retrieved_chunk": "import {\n MessageResponse,\n AnyOptionsResponse,\n AnyViewResponse,\n} from \"./response-body\";\nexport interface SlackResponse {\n status?: number;\n contentType?: string;\n // deno-lint-ignore no-explicit-any\n body?: string | MessageResponse | Record<string, any>;",
"score": 0.7960467338562012
},
{
"filename": "src/context/context.ts",
"retrieved_chunk": "export type SlackAppContextWithOptionalRespond = {\n respond?: (params: WebhookParams) => Promise<Response>;\n} & SlackAppContext;\nexport function builtBaseContext(\n // deno-lint-ignore no-explicit-any\n body: Record<string, any>\n): PreAuthorizeSlackAppContext {\n return {\n isEnterpriseinstall: extractIsEnterpriseInstall(body),\n enterpriseId: extractEnterpriseId(body),",
"score": 0.7860159873962402
}
] | 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/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.8217249512672424
},
{
"filename": "src/response/response.ts",
"retrieved_chunk": " | (SlackResponse & {\n body: AnyOptionsResponse;\n })\n | AnyOptionsResponse;\nexport function toCompleteResponse(\n slackResponse:\n | SlackResponse\n | MessageResponse\n | SlackViewResponse\n | SlackOptionsResponse",
"score": 0.8169777989387512
},
{
"filename": "src/response/response.ts",
"retrieved_chunk": "import {\n MessageResponse,\n AnyOptionsResponse,\n AnyViewResponse,\n} from \"./response-body\";\nexport interface SlackResponse {\n status?: number;\n contentType?: string;\n // deno-lint-ignore no-explicit-any\n body?: string | MessageResponse | Record<string, any>;",
"score": 0.8065224289894104
},
{
"filename": "src/context/context.ts",
"retrieved_chunk": "export type SlackAppContextWithChannelId = {\n channelId: string;\n say: (\n params: Omit<ChatPostMessageRequest, \"channel\">\n ) => Promise<ChatPostMessageResponse>;\n} & SlackAppContext;\nexport type SlackAppContextWithRespond = {\n channelId: string;\n respond: (params: WebhookParams) => Promise<Response>;\n} & SlackAppContext;",
"score": 0.7952051162719727
},
{
"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.7894264459609985
}
] | 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/context/context.ts",
"retrieved_chunk": "export type SlackAppContextWithChannelId = {\n channelId: string;\n say: (\n params: Omit<ChatPostMessageRequest, \"channel\">\n ) => Promise<ChatPostMessageResponse>;\n} & SlackAppContext;\nexport type SlackAppContextWithRespond = {\n channelId: string;\n respond: (params: WebhookParams) => Promise<Response>;\n} & SlackAppContext;",
"score": 0.8268086910247803
},
{
"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.825595498085022
},
{
"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.8181287050247192
},
{
"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.8104641437530518
},
{
"filename": "src/context/context.ts",
"retrieved_chunk": "export type SlackAppContextWithOptionalRespond = {\n respond?: (params: WebhookParams) => Promise<Response>;\n} & SlackAppContext;\nexport function builtBaseContext(\n // deno-lint-ignore no-explicit-any\n body: Record<string, any>\n): PreAuthorizeSlackAppContext {\n return {\n isEnterpriseinstall: extractIsEnterpriseInstall(body),\n enterpriseId: extractEnterpriseId(body),",
"score": 0.8082696199417114
}
] | 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": " const client = new SlackAPIClient(undefined, {\n logLevel: this.env.SLACK_LOGGING_LEVEL,\n });\n let oauthAccess: OAuthV2AccessResponse | undefined;\n try {\n // Execute the installation process\n oauthAccess = await client.oauth.v2.access({\n client_id: this.env.SLACK_CLIENT_ID,\n client_secret: this.env.SLACK_CLIENT_SECRET,\n redirect_uri: this.oauth.redirectUri,",
"score": 0.8730091452598572
},
{
"filename": "src/oidc/authorize-url-generator.ts",
"retrieved_chunk": "import { SlackOAuthEnv } from \"../app-env\";\nimport { ConfigError } from \"../errors\";\nexport function generateOIDCAuthorizeUrl<E extends SlackOAuthEnv>(\n state: string,\n env: E\n): string {\n if (!env.SLACK_OIDC_SCOPES) {\n throw new ConfigError(\n \"env.SLACK_OIDC_SCOPES must be present when enabling Sign in with Slack (OpenID Connect)\"\n );",
"score": 0.828860342502594
},
{
"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.8256814479827881
},
{
"filename": "src/oauth-app.ts",
"retrieved_chunk": " return await this.oidc.onFailure(\n this.routes.oidc.start,\n MissingCode,\n request\n );\n }\n try {\n const client = new SlackAPIClient(undefined, {\n logLevel: this.env.SLACK_LOGGING_LEVEL,\n });",
"score": 0.8202152252197266
},
{
"filename": "src/app-env.ts",
"retrieved_chunk": "export interface SlackLoggingLevel {\n SLACK_LOGGING_LEVEL?: \"DEBUG\" | \"INFO\" | \"WARN\" | \"ERROR\";\n}\nexport type SlackAppEnv = SlackLoggingLevel & {\n SLACK_SIGNING_SECRET?: string;\n SLACK_BOT_TOKEN?: string;\n SLACK_APP_TOKEN?: string;\n};\nexport type SlackEdgeAppEnv = SlackAppEnv & {\n SLACK_SIGNING_SECRET: string;",
"score": 0.8118317127227783
}
] | 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/context/context.ts",
"retrieved_chunk": "export type SlackAppContextWithChannelId = {\n channelId: string;\n say: (\n params: Omit<ChatPostMessageRequest, \"channel\">\n ) => Promise<ChatPostMessageResponse>;\n} & SlackAppContext;\nexport type SlackAppContextWithRespond = {\n channelId: string;\n respond: (params: WebhookParams) => Promise<Response>;\n} & SlackAppContext;",
"score": 0.8345113396644592
},
{
"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.83064866065979
},
{
"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.8212666511535645
},
{
"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.8109422922134399
},
{
"filename": "src/request/request.ts",
"retrieved_chunk": " E extends SlackAppEnv,\n Payload\n> = SlackMiddlwareRequest<E> & {\n context: SlackAppContextWithRespond;\n payload: Payload;\n};\nexport type SlackRequestWithOptionalRespond<\n E extends SlackAppEnv,\n Payload\n> = SlackMiddlwareRequest<E> & {",
"score": 0.8097211122512817
}
] | 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/response/response.ts",
"retrieved_chunk": " | (SlackResponse & {\n body: AnyOptionsResponse;\n })\n | AnyOptionsResponse;\nexport function toCompleteResponse(\n slackResponse:\n | SlackResponse\n | MessageResponse\n | SlackViewResponse\n | SlackOptionsResponse",
"score": 0.8250275254249573
},
{
"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.8199408650398254
},
{
"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.8186323046684265
},
{
"filename": "src/context/context.ts",
"retrieved_chunk": "export type SlackAppContextWithChannelId = {\n channelId: string;\n say: (\n params: Omit<ChatPostMessageRequest, \"channel\">\n ) => Promise<ChatPostMessageResponse>;\n} & SlackAppContext;\nexport type SlackAppContextWithRespond = {\n channelId: string;\n respond: (params: WebhookParams) => Promise<Response>;\n} & SlackAppContext;",
"score": 0.8146867752075195
},
{
"filename": "src/context/context.ts",
"retrieved_chunk": "export type SlackAppContextWithOptionalRespond = {\n respond?: (params: WebhookParams) => Promise<Response>;\n} & SlackAppContext;\nexport function builtBaseContext(\n // deno-lint-ignore no-explicit-any\n body: Record<string, any>\n): PreAuthorizeSlackAppContext {\n return {\n isEnterpriseinstall: extractIsEnterpriseInstall(body),\n enterpriseId: extractEnterpriseId(body),",
"score": 0.8145577907562256
}
] | typescript | if (body.type !== PayloadType.ViewSubmission || !body.view) { |
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.is_ext_shared_channel) {\n if (body.type === \"event_callback\") {\n if (body.event) {\n if (extractActorEnterpriseId(body) && extractActorTeamId(body)) {\n // When both enterprise_id and team_id are not identified, we skip returning user_id too for safety\n return undefined;\n }\n return body.event.user || body.event.user_id;\n } else {\n return undefined;",
"score": 0.8104101419448853
},
{
"filename": "src/context/context.ts",
"retrieved_chunk": "): string | undefined {\n if (body.is_ext_shared_channel) {\n if (body.type === \"event_callback\") {\n const eventType = body.event.type;\n if (eventType === \"app_mention\") {\n // The $.event.user_team can be an enterprise_id in app_mention events.\n // In the scenario, there is no way to retrieve actor_team_id as of March 2023\n const userTeam = body.event.user_team;\n if (!userTeam) {\n // working with an app installed in this user's org/workspace side",
"score": 0.8057354688644409
},
{
"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.7889865636825562
},
{
"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.7879828214645386
},
{
"filename": "src/context/context.ts",
"retrieved_chunk": " return body.enterprise_id;\n } else if (\n body.team &&\n typeof body.team === \"object\" &&\n body.team.enterprise_id\n ) {\n return body.team.enterprise_id;\n } else if (body.event) {\n return extractEnterpriseId(body.event);\n }",
"score": 0.7861396074295044
}
] | 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/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.8802701234817505
},
{
"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.8784807324409485
},
{
"filename": "src/request/payload/event.ts",
"retrieved_chunk": " date_expire: number;\n request_reason: string;\n team: {\n id: string;\n name: string;\n domain: string;\n };\n };\n}\nexport interface LinkSharedEvent extends SlackEvent<\"link_shared\"> {",
"score": 0.8523373603820801
},
{
"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.8423817157745361
},
{
"filename": "src/request/payload/event.ts",
"retrieved_chunk": " name: string;\n email: string;\n };\n team: {\n id: string;\n name: string;\n domain: string;\n };\n scopes: {\n name: string;",
"score": 0.8408148288726807
}
] | 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/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.8119566440582275
},
{
"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.8072431087493896
},
{
"filename": "src/app.ts",
"retrieved_chunk": " for (const middlware of this.postAuthorizeMiddleware) {\n const response = await middlware(baseRequest);\n if (response) {\n return toCompleteResponse(response);\n }\n }\n const payload = body as SlackRequestBody;\n if (body.type === PayloadType.EventsAPI) {\n // Events API\n const slackRequest: SlackRequest<E, SlackEvent<string>> = {",
"score": 0.7870619893074036
},
{
"filename": "src/oauth/callback.ts",
"retrieved_chunk": "// deno-lint-ignore require-await\nexport const defaultOnFailure = async (\n startPath: string,\n reason: OAuthErrorCode,\n // deno-lint-ignore no-unused-vars\n req: Request\n) => {\n return new Response(renderErrorPage(startPath, reason), {\n status: 400,\n headers: { \"Content-Type\": \"text/html; charset=utf-8\" },",
"score": 0.7847669124603271
},
{
"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.77994704246521
}
] | typescript | const stateValue = await this.stateStore.issueNewState(); |
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": " 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.7631669044494629
},
{
"filename": "src/app.ts",
"retrieved_chunk": " for (const middlware of this.postAuthorizeMiddleware) {\n const response = await middlware(baseRequest);\n if (response) {\n return toCompleteResponse(response);\n }\n }\n const payload = body as SlackRequestBody;\n if (body.type === PayloadType.EventsAPI) {\n // Events API\n const slackRequest: SlackRequest<E, SlackEvent<string>> = {",
"score": 0.7562764286994934
},
{
"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.7556779980659485
},
{
"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.7550245523452759
},
{
"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.7496211528778076
}
] | 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/context/context.ts",
"retrieved_chunk": "export type SlackAppContextWithChannelId = {\n channelId: string;\n say: (\n params: Omit<ChatPostMessageRequest, \"channel\">\n ) => Promise<ChatPostMessageResponse>;\n} & SlackAppContext;\nexport type SlackAppContextWithRespond = {\n channelId: string;\n respond: (params: WebhookParams) => Promise<Response>;\n} & SlackAppContext;",
"score": 0.8030914068222046
},
{
"filename": "src/context/context.ts",
"retrieved_chunk": "export type SlackAppContextWithOptionalRespond = {\n respond?: (params: WebhookParams) => Promise<Response>;\n} & SlackAppContext;\nexport function builtBaseContext(\n // deno-lint-ignore no-explicit-any\n body: Record<string, any>\n): PreAuthorizeSlackAppContext {\n return {\n isEnterpriseinstall: extractIsEnterpriseInstall(body),\n enterpriseId: extractEnterpriseId(body),",
"score": 0.7887600660324097
},
{
"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.7867929339408875
},
{
"filename": "src/oauth-app.ts",
"retrieved_chunk": " return await this.handleEventRequest(request, ctx);\n }\n }\n return new Response(\"Not found\", { status: 404 });\n }\n async handleEventRequest(\n request: Request,\n ctx: ExecutionContext\n ): Promise<Response> {\n return await super.handleEventRequest(request, ctx);",
"score": 0.7828832268714905
},
{
"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.769662082195282
}
] | 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.8130871057510376
},
{
"filename": "src/context/context.ts",
"retrieved_chunk": " } else if (body.team) {\n // With org-wide installations, payload.team in interactivity payloads can be None\n // You need to extract either payload.user.team_id or payload.view.team_id as below\n if (typeof body.team === \"string\") {\n return body.team;\n } else if (body.team.id) {\n return body.team.id;\n }\n } else if (body.authorizations && body.authorizations.length > 0) {\n // To make Events API handling functioning also for shared channels,",
"score": 0.8047877550125122
},
{
"filename": "src/context/context.ts",
"retrieved_chunk": "): string | undefined {\n if (body.enterprise) {\n if (typeof body.enterprise === \"string\") {\n return body.enterprise;\n } else if (typeof body.enterprise === \"object\" && body.enterprise.id) {\n return body.enterprise.id;\n }\n } else if (body.authorizations && body.authorizations.length > 0) {\n return extractEnterpriseId(body.authorizations[0]);\n } else if (body.enterprise_id) {",
"score": 0.7956883311271667
},
{
"filename": "src/context/context.ts",
"retrieved_chunk": " if (body.is_ext_shared_channel) {\n if (body.type === \"event_callback\") {\n if (body.event) {\n if (extractActorEnterpriseId(body) && extractActorTeamId(body)) {\n // When both enterprise_id and team_id are not identified, we skip returning user_id too for safety\n return undefined;\n }\n return body.event.user || body.event.user_id;\n } else {\n return undefined;",
"score": 0.7776476144790649
},
{
"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.7754275798797607
}
] | typescript | if (body.block_id && body.block_id !== constraints.block_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/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.8338286280632019
},
{
"filename": "src/context/context.ts",
"retrieved_chunk": "export type SlackAppContextWithChannelId = {\n channelId: string;\n say: (\n params: Omit<ChatPostMessageRequest, \"channel\">\n ) => Promise<ChatPostMessageResponse>;\n} & SlackAppContext;\nexport type SlackAppContextWithRespond = {\n channelId: string;\n respond: (params: WebhookParams) => Promise<Response>;\n} & SlackAppContext;",
"score": 0.8312143087387085
},
{
"filename": "src/context/context.ts",
"retrieved_chunk": "export type SlackAppContextWithOptionalRespond = {\n respond?: (params: WebhookParams) => Promise<Response>;\n} & SlackAppContext;\nexport function builtBaseContext(\n // deno-lint-ignore no-explicit-any\n body: Record<string, any>\n): PreAuthorizeSlackAppContext {\n return {\n isEnterpriseinstall: extractIsEnterpriseInstall(body),\n enterpriseId: extractEnterpriseId(body),",
"score": 0.8104354739189148
},
{
"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.8052957653999329
},
{
"filename": "src/response/response.ts",
"retrieved_chunk": " | (SlackResponse & {\n body: AnyOptionsResponse;\n })\n | AnyOptionsResponse;\nexport function toCompleteResponse(\n slackResponse:\n | SlackResponse\n | MessageResponse\n | SlackViewResponse\n | SlackOptionsResponse",
"score": 0.8034871220588684
}
] | typescript | if (body.type !== PayloadType.GlobalShortcut || !body.callback_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/socket-mode/socket-mode-client.ts",
"retrieved_chunk": " `An error was thrown by the Socket Mode connection: ${e}`\n );\n };\n const app = this.app;\n ws.onmessage = async (ev) => {\n try {\n if (\n ev.data &&\n typeof ev.data === \"string\" &&\n ev.data.startsWith(\"{\")",
"score": 0.7696318626403809
},
{
"filename": "src/socket-mode/socket-mode-client.ts",
"retrieved_chunk": " );\n }\n if (this.ws) {\n const ws = this.ws;\n // deno-lint-ignore require-await\n ws.onopen = async (ev) => {\n // TODO: make this customizable\n if (isDebugLogEnabled(app.env.SLACK_LOGGING_LEVEL)) {\n console.log(\n `Now the Socket Mode client is connected to Slack: ${JSON.stringify(",
"score": 0.7676198482513428
},
{
"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.7638852596282959
},
{
"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.7600516080856323
},
{
"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.7574205994606018
}
] | typescript | body.actions ||
!body.actions[0]
) { |
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/components/shell/_main-links.tsx",
"retrieved_chunk": " },\n {\n icon: <IconPencil size=\"1rem\" />,\n color: \"blue\",\n label: \"Manage Course\",\n href: \"/dashboard/courses\",\n },\n];\nexport function MainLinks() {\n return (",
"score": 0.810752272605896
},
{
"filename": "src/pages/dashboard/courses/[courseId].tsx",
"retrieved_chunk": " setNewSection(null);\n await courseQuery.refetch();\n newSectionForm.reset();\n })}\n >\n <Stack spacing=\"xl\">\n <Title order={3}>Create New Section</Title>\n <TextInput\n withAsterisk\n required",
"score": 0.7881389260292053
},
{
"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.7855279445648193
},
{
"filename": "src/pages/_app.tsx",
"retrieved_chunk": " colorScheme,\n }}\n >\n <SessionProvider session={session}>\n <Component {...pageProps} />\n </SessionProvider>\n </MantineProvider>\n </ColorSchemeProvider>\n );\n};",
"score": 0.7842603921890259
},
{
"filename": "src/components/shell/_user.tsx",
"retrieved_chunk": " </Menu>\n </UnstyledButton>\n ) : (\n <Button onClick={() => signIn()}>Login</Button>\n )}\n </Box>\n );\n}",
"score": 0.7777484655380249
}
] | typescript | const courses = api.course.getCourses.useQuery(); |
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": "export type SlackAppContextWithChannelId = {\n channelId: string;\n say: (\n params: Omit<ChatPostMessageRequest, \"channel\">\n ) => Promise<ChatPostMessageResponse>;\n} & SlackAppContext;\nexport type SlackAppContextWithRespond = {\n channelId: string;\n respond: (params: WebhookParams) => Promise<Response>;\n} & SlackAppContext;",
"score": 0.7984786033630371
},
{
"filename": "src/context/context.ts",
"retrieved_chunk": "export type SlackAppContextWithOptionalRespond = {\n respond?: (params: WebhookParams) => Promise<Response>;\n} & SlackAppContext;\nexport function builtBaseContext(\n // deno-lint-ignore no-explicit-any\n body: Record<string, any>\n): PreAuthorizeSlackAppContext {\n return {\n isEnterpriseinstall: extractIsEnterpriseInstall(body),\n enterpriseId: extractEnterpriseId(body),",
"score": 0.7910082340240479
},
{
"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.7846300005912781
},
{
"filename": "src/oauth-app.ts",
"retrieved_chunk": " return await this.handleEventRequest(request, ctx);\n }\n }\n return new Response(\"Not found\", { status: 404 });\n }\n async handleEventRequest(\n request: Request,\n ctx: ExecutionContext\n ): Promise<Response> {\n return await super.handleEventRequest(request, ctx);",
"score": 0.777665376663208
},
{
"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.7694149613380432
}
] | 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": "}\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.8207205533981323
},
{
"filename": "src/server/api/routers/course.ts",
"retrieved_chunk": " data: {\n videoId,\n title: input.title,\n courseId: input.courseId,\n },\n });\n }),\n deleteSection: protectedProcedure\n .input(z.object({ sectionId: z.string() }))\n .mutation(async ({ ctx, input }) => {",
"score": 0.7804670929908752
},
{
"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.7794547080993652
},
{
"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.7745786905288696
},
{
"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.7711912393569946
}
] | 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/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.8314637541770935
},
{
"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.8254573345184326
},
{
"filename": "src/components/layouts/admin-dashboard-layout.tsx",
"retrieved_chunk": " {colorScheme === \"dark\" ? (\n <IconSun size=\"1rem\" />\n ) : (\n <IconMoonStars size=\"1rem\" />\n )}\n </ActionIcon>\n </Group>\n </Header>\n }\n styles={(theme) => ({",
"score": 0.803595781326294
},
{
"filename": "src/pages/_app.tsx",
"retrieved_chunk": " colorScheme,\n }}\n >\n <SessionProvider session={session}>\n <Component {...pageProps} />\n </SessionProvider>\n </MantineProvider>\n </ColorSchemeProvider>\n );\n};",
"score": 0.7799671292304993
},
{
"filename": "src/components/shell/_user.tsx",
"retrieved_chunk": " </Menu>\n </UnstyledButton>\n ) : (\n <Button onClick={() => signIn()}>Login</Button>\n )}\n </Box>\n );\n}",
"score": 0.7778756022453308
}
] | typescript | {sortedSections.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": " <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.8280621767044067
},
{
"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.8164190053939819
},
{
"filename": "src/components/layouts/admin-dashboard-layout.tsx",
"retrieved_chunk": " {colorScheme === \"dark\" ? (\n <IconSun size=\"1rem\" />\n ) : (\n <IconMoonStars size=\"1rem\" />\n )}\n </ActionIcon>\n </Group>\n </Header>\n }\n styles={(theme) => ({",
"score": 0.7861895561218262
},
{
"filename": "src/components/layouts/admin-dashboard-layout.tsx",
"retrieved_chunk": " padding=\"xl\"\n navbar={\n <Navbar p=\"xs\" width={{ base: 300 }}>\n <Navbar.Section grow mt=\"md\">\n <MainLinks />\n </Navbar.Section>\n <Navbar.Section>\n <User />\n </Navbar.Section>\n </Navbar>",
"score": 0.7826257348060608
},
{
"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.7720741629600525
}
] | typescript | .map((section, idx) => (
<Stack
key={section.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": " 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.7793921828269958
},
{
"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.7533944845199585
},
{
"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.7507256269454956
},
{
"filename": "src/server/auth.ts",
"retrieved_chunk": " id: user.id,\n },\n }),\n },\n adapter: PrismaAdapter(prisma),\n providers: [\n GoogleProvider({\n clientId: env.GOOGLE_CLIENT_ID,\n clientSecret: env.GOOGLE_CLIENT_SECRET,\n }),",
"score": 0.7482038140296936
},
{
"filename": "src/server/api/trpc.ts",
"retrieved_chunk": " * that goes through your tRPC endpoint.\n *\n * @see https://trpc.io/docs/context\n */\nexport const createTRPCContext = async (opts: CreateNextContextOptions) => {\n const { req, res } = opts;\n // Get the session from the server using the getServerSession wrapper function\n const session = await getServerAuthSession({ req, res });\n return createInnerTRPCContext({\n session,",
"score": 0.70824134349823
}
] | 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": "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.8035804033279419
},
{
"filename": "src/components/shell/_user.tsx",
"retrieved_chunk": " <Menu.Target>\n <Group>\n <Avatar\n imageProps={{ referrerPolicy: \"no-referrer\" }}\n src={user.data.user.image}\n radius=\"xl\"\n />\n <Box sx={{ flex: 1 }}>\n <Text size=\"sm\" weight={500}>\n {user.data.user.name}",
"score": 0.8020201325416565
},
{
"filename": "src/pages/dashboard/courses/index.tsx",
"retrieved_chunk": " title: \"\",\n description: \"\",\n },\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\" />",
"score": 0.7985028028488159
},
{
"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.7973119020462036
},
{
"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.7965008020401001
}
] | 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.8335639834403992
},
{
"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.8165743350982666
},
{
"filename": "src/server/api/routers/course.ts",
"retrieved_chunk": " }),\n createCourse: protectedProcedure\n .input(z.object({ title: z.string(), description: z.string() }))\n .mutation(async ({ ctx, input }) => {\n const userId = ctx.session.user.id;\n const newCourse = await ctx.prisma.course.create({\n data: {\n title: input.title,\n description: input.description,\n userId: userId,",
"score": 0.800918698310852
},
{
"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.7992311716079712
},
{
"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.7923098206520081
}
] | typescript | = api.course.updateCourse.useMutation(); |
/* 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.8382221460342407
},
{
"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.8198882341384888
},
{
"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.8058461546897888
},
{
"filename": "src/server/api/routers/course.ts",
"retrieved_chunk": " }),\n createCourse: protectedProcedure\n .input(z.object({ title: z.string(), description: z.string() }))\n .mutation(async ({ ctx, input }) => {\n const userId = ctx.session.user.id;\n const newCourse = await ctx.prisma.course.create({\n data: {\n title: input.title,\n description: input.description,\n userId: userId,",
"score": 0.8045102953910828
},
{
"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.7968385219573975
}
] | 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/dashboard/index.tsx",
"retrieved_chunk": " </Head>\n <main>\n <AdminDashboardLayout>Dashboard</AdminDashboardLayout>\n </main>\n </>\n );\n};\nexport default Dashboard;",
"score": 0.7998183369636536
},
{
"filename": "src/components/shell/_user.tsx",
"retrieved_chunk": " </Menu>\n </UnstyledButton>\n ) : (\n <Button onClick={() => signIn()}>Login</Button>\n )}\n </Box>\n );\n}",
"score": 0.7994661331176758
},
{
"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.7735703587532043
},
{
"filename": "src/components/layouts/admin-dashboard-layout.tsx",
"retrieved_chunk": " {colorScheme === \"dark\" ? (\n <IconSun size=\"1rem\" />\n ) : (\n <IconMoonStars size=\"1rem\" />\n )}\n </ActionIcon>\n </Group>\n </Header>\n }\n styles={(theme) => ({",
"score": 0.7628182172775269
},
{
"filename": "src/pages/index.tsx",
"retrieved_chunk": "import { type NextPage } from \"next\";\nimport Head from \"next/head\";\nconst Home: 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\" />\n </Head>",
"score": 0.7570241689682007
}
] | typescript | export default api.withTRPC(MyApp); |
|
/* 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": " 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.8014963269233704
},
{
"filename": "src/pages/dashboard/courses/index.tsx",
"retrieved_chunk": " title: \"\",\n description: \"\",\n },\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\" />",
"score": 0.8013414144515991
},
{
"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.8008159399032593
},
{
"filename": "src/components/shell/_user.tsx",
"retrieved_chunk": " <Menu.Target>\n <Group>\n <Avatar\n imageProps={{ referrerPolicy: \"no-referrer\" }}\n src={user.data.user.image}\n radius=\"xl\"\n />\n <Box sx={{ flex: 1 }}>\n <Text size=\"sm\" weight={500}>\n {user.data.user.name}",
"score": 0.7971209287643433
},
{
"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.7919743061065674
}
] | typescript | getImageUrl(courseQuery.data.imageId)} |
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/trpc.ts",
"retrieved_chunk": " return next({\n ctx: {\n // infers the `session` as non-nullable\n session: { ...ctx.session, user: ctx.session.user },\n },\n });\n});\n/**\n * Protected (authenticated) procedure\n *",
"score": 0.873558521270752
},
{
"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.8287100791931152
},
{
"filename": "src/server/api/routers/example.ts",
"retrieved_chunk": " return {\n greeting: `Hello ${input.text}`,\n };\n }),\n getAll: publicProcedure.query(({ ctx }) => {\n return ctx.prisma.example.findMany();\n }),\n getSecretMessage: protectedProcedure.query(() => {\n return \"you can now see this secret message!\";\n }),",
"score": 0.8186729550361633
},
{
"filename": "src/server/api/routers/course.ts",
"retrieved_chunk": " id: input.courseId,\n userId,\n },\n data: {\n title: input.title,\n },\n });\n return { status: \"updated\" };\n }),\n createPresignedUrl: protectedProcedure",
"score": 0.8008583188056946
},
{
"filename": "src/server/api/routers/course.ts",
"retrieved_chunk": " },\n data: {\n order: sectionTarget.order,\n },\n });\n await ctx.prisma.section.update({\n where: {\n id: input.sectionIdTarget,\n },\n data: {",
"score": 0.7986340522766113
}
] | 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.781749963760376
},
{
"filename": "src/server/auth.ts",
"retrieved_chunk": " id: user.id,\n },\n }),\n },\n adapter: PrismaAdapter(prisma),\n providers: [\n GoogleProvider({\n clientId: env.GOOGLE_CLIENT_ID,\n clientSecret: env.GOOGLE_CLIENT_SECRET,\n }),",
"score": 0.7659011483192444
},
{
"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.7576136589050293
},
{
"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.7556897401809692
},
{
"filename": "src/server/api/trpc.ts",
"retrieved_chunk": " * that goes through your tRPC endpoint.\n *\n * @see https://trpc.io/docs/context\n */\nexport const createTRPCContext = async (opts: CreateNextContextOptions) => {\n const { req, res } = opts;\n // Get the session from the server using the getServerSession wrapper function\n const session = await getServerAuthSession({ req, res });\n return createInnerTRPCContext({\n session,",
"score": 0.7060554027557373
}
] | typescript | Bucket: env.NEXT_PUBLIC_S3_BUCKET_NAME,
Key: imageId,
Fields: { |
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": " </form>\n </Stack>\n </Stack>\n </Stack>\n </AdminDashboardLayout>\n </main>\n </>\n );\n};\nexport default Courses;",
"score": 0.7933382987976074
},
{
"filename": "src/pages/_app.tsx",
"retrieved_chunk": " colorScheme,\n }}\n >\n <SessionProvider session={session}>\n <Component {...pageProps} />\n </SessionProvider>\n </MantineProvider>\n </ColorSchemeProvider>\n );\n};",
"score": 0.7860873937606812
},
{
"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.7846490144729614
},
{
"filename": "src/pages/dashboard/courses/[courseId].tsx",
"retrieved_chunk": " )\n return;\n await deleteSection.mutateAsync({\n sectionId: section.id,\n });\n await courseQuery.refetch();\n }}\n >\n Delete\n </Button>",
"score": 0.7840227484703064
},
{
"filename": "src/components/shell/_main-links.tsx",
"retrieved_chunk": " },\n {\n icon: <IconPencil size=\"1rem\" />,\n color: \"blue\",\n label: \"Manage Course\",\n href: \"/dashboard/courses\",\n },\n];\nexport function MainLinks() {\n return (",
"score": 0.7816774845123291
}
] | typescript | courses = api.course.getCourses.useQuery(); |
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/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.8061161637306213
},
{
"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.7908931374549866
},
{
"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.7615146040916443
},
{
"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.7386829853057861
},
{
"filename": "src/app.ts",
"retrieved_chunk": " for (const middlware of this.postAuthorizeMiddleware) {\n const response = await middlware(baseRequest);\n if (response) {\n return toCompleteResponse(response);\n }\n }\n const payload = body as SlackRequestBody;\n if (body.type === PayloadType.EventsAPI) {\n // Events API\n const slackRequest: SlackRequest<E, SlackEvent<string>> = {",
"score": 0.7362700700759888
}
] | 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/response/response.ts",
"retrieved_chunk": " bodyString = JSON.stringify(completeResponse.body);\n } else {\n bodyString = completeResponse.body || \"\";\n }\n return new Response(bodyString, {\n status,\n headers: { \"Content-Type\": contentType },\n });\n}",
"score": 0.808661699295044
},
{
"filename": "src/oauth/callback.ts",
"retrieved_chunk": "// deno-lint-ignore require-await\nexport const defaultOnFailure = async (\n startPath: string,\n reason: OAuthErrorCode,\n // deno-lint-ignore no-unused-vars\n req: Request\n) => {\n return new Response(renderErrorPage(startPath, reason), {\n status: 400,\n headers: { \"Content-Type\": \"text/html; charset=utf-8\" },",
"score": 0.8010830283164978
},
{
"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.7894115447998047
},
{
"filename": "src/response/response.ts",
"retrieved_chunk": " | string\n | void\n): Response {\n if (!slackResponse) {\n return new Response(\"\", {\n status: 200,\n headers: { \"Content-Type\": \"text/plain\" },\n });\n }\n if (typeof slackResponse === \"string\") {",
"score": 0.7812563180923462
},
{
"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.769511878490448
}
] | typescript | waitUntil: async (promise) => { |
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/cookie.ts",
"retrieved_chunk": " * The object has the various cookies as keys(names) => values\n */\nexport function parse(\n str: string,\n // deno-lint-ignore no-explicit-any\n options: any | undefined = undefined\n): Record<string, string> {\n if (typeof str !== \"string\") {\n throw new TypeError(\"argument str must be a string\");\n }",
"score": 0.7968559861183167
},
{
"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.7905464768409729
},
{
"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.7800626158714294
},
{
"filename": "src/oauth/callback.ts",
"retrieved_chunk": "// deno-lint-ignore require-await\nexport const defaultOnFailure = async (\n startPath: string,\n reason: OAuthErrorCode,\n // deno-lint-ignore no-unused-vars\n req: Request\n) => {\n return new Response(renderErrorPage(startPath, reason), {\n status: 400,\n headers: { \"Content-Type\": \"text/html; charset=utf-8\" },",
"score": 0.7779237031936646
},
{
"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.775656521320343
}
] | typescript | cookie = parseCookie(request.headers.get("Cookie") || ""); |
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/oauth/callback.ts",
"retrieved_chunk": "// deno-lint-ignore require-await\nexport const defaultOnFailure = async (\n startPath: string,\n reason: OAuthErrorCode,\n // deno-lint-ignore no-unused-vars\n req: Request\n) => {\n return new Response(renderErrorPage(startPath, reason), {\n status: 400,\n headers: { \"Content-Type\": \"text/html; charset=utf-8\" },",
"score": 0.8379754424095154
},
{
"filename": "src/response/response.ts",
"retrieved_chunk": " bodyString = JSON.stringify(completeResponse.body);\n } else {\n bodyString = completeResponse.body || \"\";\n }\n return new Response(bodyString, {\n status,\n headers: { \"Content-Type\": contentType },\n });\n}",
"score": 0.8110147714614868
},
{
"filename": "src/response/response.ts",
"retrieved_chunk": " | string\n | void\n): Response {\n if (!slackResponse) {\n return new Response(\"\", {\n status: 200,\n headers: { \"Content-Type\": \"text/plain\" },\n });\n }\n if (typeof slackResponse === \"string\") {",
"score": 0.8105357885360718
},
{
"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.8064903020858765
},
{
"filename": "src/execution-context.ts",
"retrieved_chunk": "export class NoopExecutionContext implements ExecutionContext {\n // deno-lint-ignore no-explicit-any\n waitUntil(promise: Promise<any>): void {\n promise.catch((reason) => {\n console.error(`Failed to run a lazy listener: ${reason}`);\n });\n }\n}",
"score": 0.8063309192657471
}
] | typescript | ((res) => { |
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/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.8100033402442932
},
{
"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.8077268600463867
},
{
"filename": "src/prompts/explain-this.ts",
"retrieved_chunk": "import { IPrompt, PromptOutputType } from \"./type\";\nexport const ExplainThis: IPrompt = {\n name: 'Explain This',\n prompt: `\n Please provide a clear explanation for the following text or code snippet:\n \"\"\"\n {content}\n \"\"\"\n `,\n output: PromptOutputType.insert,",
"score": 0.8051513433456421
},
{
"filename": "src/prompts/make-longer.ts",
"retrieved_chunk": "import { IPrompt, PromptOutputType } from \"./type\";\nexport const makeLonger: IPrompt = {\n name: 'Make Longer',\n prompt: `\n Please expand the following text, providing more details and depth:\n \"\"\"\n {content}\n \"\"\"\n `,\n output: PromptOutputType.replace,",
"score": 0.7970527410507202
},
{
"filename": "src/prompts/ask-ai.ts",
"retrieved_chunk": "import { IPrompt, PromptOutputType } from './type';\nexport const AskAI: IPrompt = {\n name: 'Ask AI',\n prompt: `\n I have a question:\n \"\"\"\n {content}\n \"\"\"\n Please provide a helpful answer.\n `,",
"score": 0.7953126430511475
}
] | typescript | case PromptOutputType.property: { |
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": "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.5994648337364197
},
{
"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.5865823030471802
},
{
"filename": "src/prompts/ask-ai.ts",
"retrieved_chunk": " output: PromptOutputType.insert,\n};",
"score": 0.5650616884231567
},
{
"filename": "src/prompts/change-tone-to-casual.ts",
"retrieved_chunk": "import { IPrompt, PromptOutputType } from \"./type\";\nexport const ChangeToneToCasual: IPrompt = {\n name: 'Change Tone to Casual',\n prompt: `\n Please rewrite the following text with a casual tone:\n \"\"\"\n {content}\n \"\"\"\n `,\n output: PromptOutputType.replace,",
"score": 0.5462404489517212
},
{
"filename": "src/utils.ts",
"retrieved_chunk": " level += 1;\n }\n return content;\n}",
"score": 0.5394691228866577
}
] | typescript | logseq.useSettingsSchema(settings).ready(main).catch(console.error); |
|
// 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/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.8121801614761353
},
{
"filename": "src/providers/navigation/NavigationSupportProvider.ts",
"retrieved_chunk": " if (fileStats.isDirectory()) {\n return null\n }\n if (!FileInfoIndex.codeDataCache.has(resolvedUri)) {\n // Index target file, if necessary\n await Indexer.indexFile(resolvedUri)\n }\n const codeData = FileInfoIndex.codeDataCache.get(resolvedUri)\n // Find definition location within determined file\n if (codeData != null) {",
"score": 0.8051224946975708
},
{
"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.7988530397415161
},
{
"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.7930359244346619
},
{
"filename": "src/indexing/DocumentIndexer.ts",
"retrieved_chunk": " * stale info could be confusing.\n *\n * @param textDocument The document to index\n */\n async ensureDocumentIndexIsUpdated (textDocument: TextDocument): Promise<void> {\n const uri = textDocument.uri\n if (this.pendingFilesToIndex.has(uri)) {\n this.clearTimerForDocumentUri(uri)\n await Indexer.indexDocument(textDocument)\n }",
"score": 0.7915120124816895
}
] | typescript | Indexer.indexFolders(folders.map(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/providers/formatting/FormatSupportProvider.ts",
"retrieved_chunk": " return null\n }\n return await this.formatDocument(docToFormat, params.options)\n }\n /**\n * Determines the edits required to format the given document.\n *\n * @param doc The document being formatted\n * @param options The formatting options\n * @returns An array of text edits required to format the document",
"score": 0.9037184119224548
},
{
"filename": "src/providers/navigation/NavigationSupportProvider.ts",
"retrieved_chunk": " }\n }\n this._documentSymbolCache.set(uri, result)\n return result\n }\n /**\n * Gets the definition/references request target expression.\n *\n * @param textDocument The text document\n * @param position The position in the document",
"score": 0.8927434086799622
},
{
"filename": "src/providers/linting/LintingSupportProvider.ts",
"retrieved_chunk": " *\n * @param uri The document URI\n */\n private clearCodeActionsForDocumentUri (uri: string): void {\n this._availableCodeActions.set(uri, [])\n }\n /**\n * Gets raw linting data from MATLAB.\n *\n * @param code The code to be linted",
"score": 0.8909264206886292
},
{
"filename": "src/providers/linting/LintingSupportProvider.ts",
"retrieved_chunk": " diagnostics: []\n })\n }\n /**\n * Handles a request for code actions.\n *\n * @param params Parameters from the onCodeAction request\n */\n handleCodeActionRequest (params: CodeActionParams): CodeAction[] {\n const uri = params.textDocument.uri",
"score": 0.888092041015625
},
{
"filename": "src/providers/navigation/NavigationSupportProvider.ts",
"retrieved_chunk": " *\n * @param params Parameters for the document symbol request\n * @param documentManager The text document manager\n * @param requestType The type of request\n * @returns Array of symbols found in the document\n */\n async handleDocumentSymbol (params: DocumentSymbolParams, documentManager: TextDocuments<TextDocument>, requestType: RequestType): Promise<SymbolInformation[]> {\n // Get or wait for MATLAB connection to handle files opened before MATLAB is ready.\n // Calling getOrCreateMatlabConnection would effectively make the onDemand launch\n // setting act as onStart.",
"score": 0.883421778678894
}
] | 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/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.8919781446456909
},
{
"filename": "src/indexing/DocumentIndexer.ts",
"retrieved_chunk": " * @param textDocument The document being indexed\n */\n indexDocument (textDocument: TextDocument): void {\n void Indexer.indexDocument(textDocument)\n }\n /**\n * Clears any active indexing timers for the provided document URI.\n *\n * @param uri The document URI\n */",
"score": 0.877656102180481
},
{
"filename": "src/providers/navigation/NavigationSupportProvider.ts",
"retrieved_chunk": " *\n * @param params Parameters for the document symbol request\n * @param documentManager The text document manager\n * @param requestType The type of request\n * @returns Array of symbols found in the document\n */\n async handleDocumentSymbol (params: DocumentSymbolParams, documentManager: TextDocuments<TextDocument>, requestType: RequestType): Promise<SymbolInformation[]> {\n // Get or wait for MATLAB connection to handle files opened before MATLAB is ready.\n // Calling getOrCreateMatlabConnection would effectively make the onDemand launch\n // setting act as onStart.",
"score": 0.8722127676010132
},
{
"filename": "src/indexing/DocumentIndexer.ts",
"retrieved_chunk": " private readonly pendingFilesToIndex = new Map<string, NodeJS.Timer>()\n /**\n * Queues a document to be indexed. This handles debouncing so that\n * indexing is not performed on every keystroke.\n *\n * @param textDocument The document to be indexed\n */\n queueIndexingForDocument (textDocument: TextDocument): void {\n const uri = textDocument.uri\n this.clearTimerForDocumentUri(uri)",
"score": 0.8702843189239502
},
{
"filename": "src/providers/linting/LintingSupportProvider.ts",
"retrieved_chunk": " })\n }\n /**\n * Attempts to determine the path to the mlint executable.\n *\n * @returns The path to the mlint executable, or null if it cannot be determined\n */\n private async getMlintExecutable (): Promise<string | null> {\n const platformDir = this.getBinDirectoryForPlatform()\n if (platformDir == null) {",
"score": 0.8678310513496399
}
] | typescript | const shouldIndexWorkspace = (await ConfigurationManager.getConfiguration()).indexWorkspace
return this.isWorkspaceIndexingSupported && shouldIndexWorkspace
} |
// 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/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.8904522061347961
},
{
"filename": "src/indexing/DocumentIndexer.ts",
"retrieved_chunk": " * @param textDocument The document being indexed\n */\n indexDocument (textDocument: TextDocument): void {\n void Indexer.indexDocument(textDocument)\n }\n /**\n * Clears any active indexing timers for the provided document URI.\n *\n * @param uri The document URI\n */",
"score": 0.8714644908905029
},
{
"filename": "src/indexing/DocumentIndexer.ts",
"retrieved_chunk": " private readonly pendingFilesToIndex = new Map<string, NodeJS.Timer>()\n /**\n * Queues a document to be indexed. This handles debouncing so that\n * indexing is not performed on every keystroke.\n *\n * @param textDocument The document to be indexed\n */\n queueIndexingForDocument (textDocument: TextDocument): void {\n const uri = textDocument.uri\n this.clearTimerForDocumentUri(uri)",
"score": 0.8709603548049927
},
{
"filename": "src/providers/navigation/NavigationSupportProvider.ts",
"retrieved_chunk": " *\n * @param params Parameters for the document symbol request\n * @param documentManager The text document manager\n * @param requestType The type of request\n * @returns Array of symbols found in the document\n */\n async handleDocumentSymbol (params: DocumentSymbolParams, documentManager: TextDocuments<TextDocument>, requestType: RequestType): Promise<SymbolInformation[]> {\n // Get or wait for MATLAB connection to handle files opened before MATLAB is ready.\n // Calling getOrCreateMatlabConnection would effectively make the onDemand launch\n // setting act as onStart.",
"score": 0.869595468044281
},
{
"filename": "src/providers/linting/LintingSupportProvider.ts",
"retrieved_chunk": " })\n }\n /**\n * Attempts to determine the path to the mlint executable.\n *\n * @returns The path to the mlint executable, or null if it cannot be determined\n */\n private async getMlintExecutable (): Promise<string | null> {\n const platformDir = this.getBinDirectoryForPlatform()\n if (platformDir == null) {",
"score": 0.8669194579124451
}
] | typescript | 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/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.8810307383537292
},
{
"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.8700414896011353
},
{
"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.8652480244636536
},
{
"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.8626842498779297
},
{
"filename": "src/providers/completion/CompletionSupportProvider.ts",
"retrieved_chunk": " * @returns An array of possible completions\n */\n async handleCompletionRequest (params: CompletionParams, documentManager: TextDocuments<TextDocument>): Promise<CompletionList> {\n const doc = documentManager.get(params.textDocument.uri)\n if (doc == null) {\n return CompletionList.create()\n }\n const completionData = await this.retrieveCompletionData(doc, params.position)\n return this.parseCompletionItems(completionData)\n }",
"score": 0.8566634058952332
}
] | typescript | if (!FileInfoIndex.codeDataCache.has(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/providers/formatting/FormatSupportProvider.ts",
"retrieved_chunk": " return null\n }\n return await this.formatDocument(docToFormat, params.options)\n }\n /**\n * Determines the edits required to format the given document.\n *\n * @param doc The document being formatted\n * @param options The formatting options\n * @returns An array of text edits required to format the document",
"score": 0.8970351219177246
},
{
"filename": "src/providers/linting/LintingSupportProvider.ts",
"retrieved_chunk": " *\n * @param uri The document URI\n */\n private clearCodeActionsForDocumentUri (uri: string): void {\n this._availableCodeActions.set(uri, [])\n }\n /**\n * Gets raw linting data from MATLAB.\n *\n * @param code The code to be linted",
"score": 0.8895214796066284
},
{
"filename": "src/providers/navigation/NavigationSupportProvider.ts",
"retrieved_chunk": " *\n * @param params Parameters for the document symbol request\n * @param documentManager The text document manager\n * @param requestType The type of request\n * @returns Array of symbols found in the document\n */\n async handleDocumentSymbol (params: DocumentSymbolParams, documentManager: TextDocuments<TextDocument>, requestType: RequestType): Promise<SymbolInformation[]> {\n // Get or wait for MATLAB connection to handle files opened before MATLAB is ready.\n // Calling getOrCreateMatlabConnection would effectively make the onDemand launch\n // setting act as onStart.",
"score": 0.8886703848838806
},
{
"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.8864725828170776
},
{
"filename": "src/indexing/WorkspaceIndexer.ts",
"retrieved_chunk": " }\n /**\n * Determines whether or not the workspace should be indexed.\n * The workspace should be indexed if the client supports workspaces, and if the\n * workspace indexing setting is true.\n *\n * @returns True if workspace indexing should occurr, false otherwise.\n */\n private async shouldIndexWorkspace (): Promise<boolean> {\n const shouldIndexWorkspace = (await ConfigurationManager.getConfiguration()).indexWorkspace",
"score": 0.8858232498168945
}
] | 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/providers/navigation/NavigationSupportProvider.ts",
"retrieved_chunk": " if (fileStats.isDirectory()) {\n return null\n }\n if (!FileInfoIndex.codeDataCache.has(resolvedUri)) {\n // Index target file, if necessary\n await Indexer.indexFile(resolvedUri)\n }\n const codeData = FileInfoIndex.codeDataCache.get(resolvedUri)\n // Find definition location within determined file\n if (codeData != null) {",
"score": 0.7894477844238281
},
{
"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.778244137763977
},
{
"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.7746951580047607
},
{
"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.7714974880218506
},
{
"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.7693386077880859
}
] | typescript | (folder => folder.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/indexing/WorkspaceIndexer.ts",
"retrieved_chunk": " // Workspace indexing not supported\n return\n }\n connection.workspace.onDidChangeWorkspaceFolders((params: WorkspaceFoldersChangeEvent) => {\n void this.handleWorkspaceFoldersAdded(params.added)\n })\n }\n /**\n * Attempts to index the files in the user's workspace.\n */",
"score": 0.7750946283340454
},
{
"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.7746647596359253
},
{
"filename": "src/server.ts",
"retrieved_chunk": "})\nconnection.onDocumentSymbol(async params => {\n return await NavigationSupportProvider.handleDocumentSymbol(params, documentManager, RequestType.DocumentSymbol)\n})\n// Start listening to open/change/close text document events\ndocumentManager.listen(connection)\n/** -------------------- Helper Functions -------------------- **/\nfunction reportFileOpened (document: TextDocument): void {\n const roughSize = Math.ceil(document.getText().length / 1024) // in KB\n reportTelemetryAction(Actions.OpenFile, roughSize.toString())",
"score": 0.7729568481445312
},
{
"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.7651270627975464
},
{
"filename": "src/lifecycle/MatlabLifecycleManager.ts",
"retrieved_chunk": " * @param status The connected status of MATLAB\n */\n private _handleMatlabLifecycleUpdate (status: 'connected' | 'disconnected'): void {\n this._matlabLifecycleCallbacks.forEach(callback => {\n callback(null, {\n matlabStatus: status\n })\n })\n }\n /**",
"score": 0.7628083229064941
}
] | typescript | onDidChangeConfiguration(params => { void this.handleConfigurationChanged(params) })
} |
// 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/FileInfoIndex.ts",
"retrieved_chunk": " }\n}\n/**\n * Class to contain info about variables\n */\nclass MatlabVariableInfo {\n readonly definitions: Range[] = []\n readonly references: Range[] = []\n constructor (public name: string, public isGlobal: boolean) {}\n /**",
"score": 0.8556399941444397
},
{
"filename": "src/indexing/FileInfoIndex.ts",
"retrieved_chunk": "/**\n * Class to contain info about functions\n */\nexport class MatlabFunctionInfo {\n name: string\n range: Range\n declaration: Range | null\n isPrototype: boolean\n parentClass: string\n isClassMethod: boolean",
"score": 0.8465627431869507
},
{
"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.8457613587379456
},
{
"filename": "src/utils/CliUtils.ts",
"retrieved_chunk": " description: 'Use specified socket for IPC',\n requiresArg: true\n }).help('help').alias('h', 'help')\n return argParser\n}\n/**\n * Parse the command line arguments.\n *\n * @param args If provided, these are the arguments to parse. Otherwise, the true\n * command line arguments will be parsed. This is primarily meant for testing.",
"score": 0.8422160744667053
},
{
"filename": "src/providers/completion/CompletionSupportProvider.ts",
"retrieved_chunk": " * Parses the raw completion data to extract function signature help.\n *\n * @param completionData The raw completion data\n * @returns The signature help, or null if no signature help is available\n */\n private parseSignatureHelp (completionData: MCompletionData): SignatureHelp | null {\n let signatureData = completionData.signatures\n if (signatureData == null) {\n return null\n }",
"score": 0.8386922478675842
}
] | 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.8572142124176025
},
{
"filename": "src/lifecycle/LifecycleNotificationHelper.ts",
"retrieved_chunk": " * Sends notification to the language client of a change in the MATLAB® connection state.\n *\n * @param connectionStatus The connection state\n */\n notifyConnectionStatusChange (connectionStatus: ConnectionState): void {\n NotificationService.sendNotification(Notification.MatlabConnectionServerUpdate, {\n connectionStatus\n })\n }\n /**",
"score": 0.8237302303314209
},
{
"filename": "src/indexing/WorkspaceIndexer.ts",
"retrieved_chunk": " /**\n * Handles when new folders are added to the user's workspace by indexing them.\n *\n * @param folders The list of folders added to the workspace\n */\n private async handleWorkspaceFoldersAdded (folders: WorkspaceFolder[]): Promise<void> {\n if (!(await this.shouldIndexWorkspace())) {\n return\n }\n Indexer.indexFolders(folders.map(folder => folder.uri))",
"score": 0.8022280931472778
},
{
"filename": "src/lifecycle/MatlabCommunicationManager.d.ts",
"retrieved_chunk": " *\n * @param callback The callback function\n */\n setLifecycleListener(callback: LifecycleListenerCallback): void;\n protected onConnectionSuccess(): void;\n protected onConnectionFailure(): void;\n protected setupConnectionCallbacks(): void;\n /**\n * Prepends a channel name with '/matlab' as expected by MATLAB\n *",
"score": 0.7999829649925232
},
{
"filename": "src/lifecycle/MatlabLifecycleManager.ts",
"retrieved_chunk": " */\n addMatlabLifecycleListener (callback: MatlabLifecycleCallback): void {\n this._matlabLifecycleCallbacks.push(callback)\n }\n /**\n * Handles requests from the language client to either connect to or disconnect from MATLAB\n *\n * @param data Data about whether or not MATLAB should be connected or disconnected\n */\n handleConnectionStatusChange (data: MatlabConnectionStatusParam): void {",
"score": 0.7986175417900085
}
] | 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": " description: 'Use specified socket for IPC',\n requiresArg: true\n }).help('help').alias('h', 'help')\n return argParser\n}\n/**\n * Parse the command line arguments.\n *\n * @param args If provided, these are the arguments to parse. Otherwise, the true\n * command line arguments will be parsed. This is primarily meant for testing.",
"score": 0.8619612455368042
},
{
"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.859995424747467
},
{
"filename": "src/indexing/FileInfoIndex.ts",
"retrieved_chunk": " }\n}\n/**\n * Class to contain info about variables\n */\nclass MatlabVariableInfo {\n readonly definitions: Range[] = []\n readonly references: Range[] = []\n constructor (public name: string, public isGlobal: boolean) {}\n /**",
"score": 0.8579919934272766
},
{
"filename": "src/providers/completion/CompletionSupportProvider.ts",
"retrieved_chunk": " * Parses the raw completion data to extract function signature help.\n *\n * @param completionData The raw completion data\n * @returns The signature help, or null if no signature help is available\n */\n private parseSignatureHelp (completionData: MCompletionData): SignatureHelp | null {\n let signatureData = completionData.signatures\n if (signatureData == null) {\n return null\n }",
"score": 0.8552600145339966
},
{
"filename": "src/providers/navigation/NavigationSupportProvider.ts",
"retrieved_chunk": " constructor (public components: string[], public selectedComponent: number) {}\n /**\n * The full, dotted expression\n */\n get fullExpression (): string {\n return this.components.join('.')\n }\n /**\n * The dotted expression up to and including the selected component\n */",
"score": 0.8538417816162109
}
] | 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": " * 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.8540793657302856
},
{
"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.8514035940170288
},
{
"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.8490641713142395
},
{
"filename": "src/lifecycle/MatlabLifecycleManager.ts",
"retrieved_chunk": " *\n * @returns True if the MATLAB connection timing setting is set to never. Returns false otherwise.\n */\n private async _isMatlabConnectionTimingNever (): Promise<boolean> {\n const connectionTiming = (await ConfigurationManager.getConfiguration()).matlabConnectionTiming\n return connectionTiming === ConnectionTiming.Never\n }\n}\n/**\n * Represents a MATLAB process",
"score": 0.8467968702316284
},
{
"filename": "src/lifecycle/MatlabLifecycleManager.ts",
"retrieved_chunk": " }\n /**\n * Gets the command with which MATLAB should be launched.\n *\n * @param outFile The file in which MATLAB should output connection details\n * @returns The matlab launch command\n */\n private async _getMatlabLaunchCommand (outFile: string): Promise<{ command: string, args: string[] }> {\n const matlabInstallPath = (await ConfigurationManager.getConfiguration()).installPath\n let command = 'matlab'",
"score": 0.8449689149856567
}
] | typescript | = await connection.workspace.getConfiguration('MATLAB') as Settings
} |
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 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.8207638263702393
},
{
"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.8173493146896362
},
{
"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.8042972087860107
},
{
"filename": "src/context.ts",
"retrieved_chunk": "\t/** A global set of facts about resolvers focused from the GQL side */\n\tfieldFacts: Map<string, FieldFacts>\n\t/** When we emit .d.ts files, it runs the ts formatter over the file first - you can override the default settings */\n\tformatCodeSettings?: FormatCodeSettings\n\t/** So you can override the formatter */\n\tgql: graphql.GraphQLSchema\n\t/** POSXIY- fn not built into System */\n\tjoin: (...paths: string[]) => string\n\t/** Where to find particular files */\n\tpathSettings: {",
"score": 0.7954028844833374
},
{
"filename": "src/index.ts",
"retrieved_chunk": "\t\tcodeFacts: new Map<string, CodeFacts>(),\n\t\tfieldFacts: new Map<string, FieldFacts>(),\n\t\tpathSettings,\n\t\tsys,\n\t\tjoin,\n\t\tbasename,\n\t}\n\t// TODO: Maybe Redwood has an API for this? Its grabbing all the services\n\tconst serviceFiles = appContext.sys.readDirectory(appContext.pathSettings.apiServicesPath)\n\tconst serviceFilesToLookAt = serviceFiles.filter((file) => {",
"score": 0.7823709845542908
}
] | 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.8191931247711182
},
{
"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.7876367568969727
},
{
"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.7833583354949951
},
{
"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.7803774476051331
},
{
"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.7780872583389282
}
] | typescript | args = 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/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.7779080867767334
},
{
"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.77518230676651
},
{
"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.7556405067443848
},
{
"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.7288118004798889
},
{
"filename": "src/sharedSchema.ts",
"retrieved_chunk": "/// The main schema for objects and inputs\nimport * as graphql from \"graphql\"\nimport * as tsMorph from \"ts-morph\"\nimport { AppContext } from \"./context.js\"\nimport { formatDTS, getPrettierConfig } from \"./formatDTS.js\"\nimport { typeMapper } from \"./typeMap.js\"\nexport const createSharedSchemaFiles = (context: AppContext) => {\n\tcreateSharedExternalSchemaFile(context)\n\tcreateSharedReturnPositionSchemaFile(context)\n\treturn [",
"score": 0.725350558757782
}
] | typescript | function addDefinitionsForTopLevelResolvers(parentName: string, config: ResolverFuncFact) { |
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/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.7670655250549316
},
{
"filename": "src/serviceFile.ts",
"retrieved_chunk": "\t\t\t\t\tdocs,\n\t\t\t\t\ttype: resolver.isFunc || resolver.isUnknown ? `(${innerArgs}) => ${returnType ?? \"any\"}` : returnType,\n\t\t\t\t})\n\t\t\t} else {\n\t\t\t\tresolverInterface.addCallSignature({\n\t\t\t\t\tdocs: [` @deprecated: SDL ${modelName}.${resolver.name} does not exist in your schema`],\n\t\t\t\t})\n\t\t\t}\n\t\t})\n\t\tfunction createParentAdditionallyDefinedFunctions() {",
"score": 0.7651612758636475
},
{
"filename": "src/typeMap.ts",
"retrieved_chunk": "\t\t\t\treturn prefix + type.name\n\t\t\t}\n\t\t\t// eslint-disable-next-line @typescript-eslint/restrict-template-expressions\n\t\t\tthrow new Error(`Unknown type ${type} - ${JSON.stringify(type, null, 2)}`)\n\t\t}\n\t\tconst suffix = mapConfig.parentWasNotNull ? \"\" : mapConfig.preferNullOverUndefined ? \"| null\" : \" | undefined\"\n\t\treturn getInner() + suffix\n\t}\n\treturn { map, clear, getReferencedGraphQLThingsInMapping }\n}",
"score": 0.7536486387252808
},
{
"filename": "src/serviceFile.ts",
"retrieved_chunk": "\t\t\t\t{\n\t\t\t\t\tname: \"obj\",\n\t\t\t\t\ttype: `{ root: ${parentName}, context: RedwoodGraphQLContext, info: GraphQLResolveInfo }`,\n\t\t\t\t\thasQuestionToken: config.funcArgCount < 2,\n\t\t\t\t},\n\t\t\t],\n\t\t\treturnType,\n\t\t})\n\t}\n\t/** Ideally, we want to be able to write the type for just the object */",
"score": 0.7461591958999634
},
{
"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.7449288368225098
}
] | typescript | const getResolverInformationForDeclaration = (initialiser: tsMorph.Expression | undefined): Omit<ResolverFuncFact, "name"> => { |
/// 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.7678403854370117
},
{
"filename": "src/run.ts",
"retrieved_chunk": "\t\t\t}\n\t\t}\n\t}\n\t// empty the types folder\n\tfor (const dirEntry of sys.readDirectory(appContext.pathSettings.typesFolderRoot)) {\n\t\tconst fileToDelete = join(appContext.pathSettings.typesFolderRoot, dirEntry)\n\t\tif (sys.deleteFile && sys.fileExists(fileToDelete)) {\n\t\t\tsys.deleteFile(fileToDelete)\n\t\t}\n\t}",
"score": 0.7436631321907043
},
{
"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.7337350845336914
},
{
"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.7320327758789062
},
{
"filename": "src/serviceFile.ts",
"retrieved_chunk": "\t\t\tnamedImports: validPrismaObjs.map((p) => `${p} as P${p}`),\n\t\t})\n\t}\n\tif (fileDTS.getText().includes(\"GraphQLResolveInfo\")) {\n\t\tfileDTS.addImportDeclaration({\n\t\t\tisTypeOnly: true,\n\t\t\tmoduleSpecifier: \"graphql\",\n\t\t\tnamedImports: [\"GraphQLResolveInfo\"],\n\t\t})\n\t}",
"score": 0.7268875241279602
}
] | typescript | const formatted = formatDTS(fullPath, externalTSFile.getText(), config)
context.sys.writeFile(fullPath, formatted)
} |
// 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/navigation/NavigationSupportProvider.ts",
"retrieved_chunk": " reportTelemetry(requestType, ActionErrorConditions.MatlabUnavailable)\n return []\n }\n const uri = params.textDocument.uri\n const textDocument = documentManager.get(uri)\n if (textDocument == null) {\n reportTelemetry(requestType, 'No document')\n return []\n }\n // Find ID for which to find the definition or references",
"score": 0.8290894031524658
},
{
"filename": "src/providers/linting/LintingSupportProvider.ts",
"retrieved_chunk": " if (!MatlabLifecycleManager.isMatlabReady()) {\n // Cannot suppress warnings without MATLAB\n return codeActions\n }\n // Add suppression commands\n const diagnostics = params.context.diagnostics\n const commands: Command[] = []\n diagnostics.forEach(diagnostic => {\n // Don't allow suppressing errors\n if (diagnostic.severity === DiagnosticSeverity.Error) {",
"score": 0.8194037675857544
},
{
"filename": "src/providers/linting/LintingSupportProvider.ts",
"retrieved_chunk": " // Use MATLAB-based linting for better results and fixes\n const code = textDocument.getText()\n lintData = await this.getLintResultsFromMatlab(code, fileName, matlabConnection)\n } else {\n // Try to use mlint executable for basic linting\n lintData = await this.getLintResultsFromExecutable(fileName)\n }\n const lintResults = this.processLintResults(uri, lintData)\n const diagnostics = lintResults.diagnostics\n // Store code actions",
"score": 0.8144910335540771
},
{
"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.8144316077232361
},
{
"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.8105280995368958
}
] | 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": " // Workspace indexing not supported\n return\n }\n connection.workspace.onDidChangeWorkspaceFolders((params: WorkspaceFoldersChangeEvent) => {\n void this.handleWorkspaceFoldersAdded(params.added)\n })\n }\n /**\n * Attempts to index the files in the user's workspace.\n */",
"score": 0.7770590782165527
},
{
"filename": "src/server.ts",
"retrieved_chunk": "})\nconnection.onDocumentSymbol(async params => {\n return await NavigationSupportProvider.handleDocumentSymbol(params, documentManager, RequestType.DocumentSymbol)\n})\n// Start listening to open/change/close text document events\ndocumentManager.listen(connection)\n/** -------------------- Helper Functions -------------------- **/\nfunction reportFileOpened (document: TextDocument): void {\n const roughSize = Math.ceil(document.getText().length / 1024) // in KB\n reportTelemetryAction(Actions.OpenFile, roughSize.toString())",
"score": 0.7770111560821533
},
{
"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.7749496698379517
},
{
"filename": "src/lifecycle/MatlabLifecycleManager.ts",
"retrieved_chunk": " * @param status The connected status of MATLAB\n */\n private _handleMatlabLifecycleUpdate (status: 'connected' | 'disconnected'): void {\n this._matlabLifecycleCallbacks.forEach(callback => {\n callback(null, {\n matlabStatus: status\n })\n })\n }\n /**",
"score": 0.768373429775238
},
{
"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.7681735754013062
}
] | typescript | .onDidChangeConfiguration(params => { void this.handleConfigurationChanged(params) })
} |
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/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.8479675650596619
},
{
"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.8288439512252808
},
{
"filename": "src/run.ts",
"retrieved_chunk": "import { CodeFacts, FieldFacts } from \"./typeFacts.js\"\nexport function run(\n\tappRoot: string,\n\ttypesRoot: string,\n\tconfig: { deleteOldGraphQLDTS?: boolean; runESLint?: boolean; sys?: typescript.System } = {}\n) {\n\tconst sys = config.sys ?? typescript.sys\n\tconst project = new Project({ useInMemoryFileSystem: true })\n\tlet gqlSchema: graphql.GraphQLSchema | undefined\n\tconst getGraphQLSDLFromFile = (settings: AppContext[\"pathSettings\"]) => {",
"score": 0.8256692290306091
},
{
"filename": "src/tests/testRunner.ts",
"retrieved_chunk": "\tconst project = new Project({ useInMemoryFileSystem: true })\n\tconst vfsMap = new Map<string, string>()\n\tconst vfs = createSystem(vfsMap)\n\tconst appContext: AppContext = {\n\t\tgql: schema,\n\t\tprisma: prismaModeller(prisma),\n\t\ttsProject: project,\n\t\tfieldFacts: new Map<string, FieldFacts>(),\n\t\tcodeFacts: new Map<string, CodeFacts>(),\n\t\tpathSettings: {",
"score": 0.8196088075637817
},
{
"filename": "src/context.ts",
"retrieved_chunk": "\t/** A global set of facts about resolvers focused from the GQL side */\n\tfieldFacts: Map<string, FieldFacts>\n\t/** When we emit .d.ts files, it runs the ts formatter over the file first - you can override the default settings */\n\tformatCodeSettings?: FormatCodeSettings\n\t/** So you can override the formatter */\n\tgql: graphql.GraphQLSchema\n\t/** POSXIY- fn not built into System */\n\tjoin: (...paths: string[]) => string\n\t/** Where to find particular files */\n\tpathSettings: {",
"score": 0.8081652522087097
}
] | 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.8112807273864746
},
{
"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.788868248462677
},
{
"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.7624630928039551
},
{
"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.739774227142334
},
{
"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.736090898513794
}
] | 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/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.7762892246246338
},
{
"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.7520968914031982
},
{
"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.7512273788452148
},
{
"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.7166246175765991
},
{
"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.7153481245040894
}
] | 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/typeMap.ts",
"retrieved_chunk": "\t\ttype: graphql.GraphQLType,\n\t\tmapConfig: {\n\t\t\tparentWasNotNull?: true\n\t\t\tpreferNullOverUndefined?: true\n\t\t\ttypenamePrefix?: string\n\t\t}\n\t): string | undefined => {\n\t\tconst prefix = mapConfig.typenamePrefix ?? \"\"\n\t\t// The AST for GQL uses a parent node to indicate the !, we need the opposite\n\t\t// for TS which uses '| undefined' after.",
"score": 0.8488953113555908
},
{
"filename": "src/context.ts",
"retrieved_chunk": "\t/** A global set of facts about resolvers focused from the GQL side */\n\tfieldFacts: Map<string, FieldFacts>\n\t/** When we emit .d.ts files, it runs the ts formatter over the file first - you can override the default settings */\n\tformatCodeSettings?: FormatCodeSettings\n\t/** So you can override the formatter */\n\tgql: graphql.GraphQLSchema\n\t/** POSXIY- fn not built into System */\n\tjoin: (...paths: string[]) => string\n\t/** Where to find particular files */\n\tpathSettings: {",
"score": 0.837141752243042
},
{
"filename": "src/tests/features/returnTypePositionsWhichPreferPrisma.test.ts",
"retrieved_chunk": "\t\t /** SDL: summary: String! */\n\t\t summary: (\n\t\t args: undefined,\n\t\t obj: {\n\t\t root: GameAsParent;\n\t\t context: RedwoodGraphQLContext;\n\t\t info: GraphQLResolveInfo;\n\t\t }\n\t\t ) => string | Promise<string> | (() => Promise<string>);\n\t\t}",
"score": 0.8141939640045166
},
{
"filename": "src/serviceFile.codefacts.ts",
"retrieved_chunk": "\t\t\t\t\t// @ts-expect-error - lets let this go for now\n\t\t\t\t\tfact.resolvers.set(name, { name, ...getResolverInformationForDeclaration(p) })\n\t\t\t\t}\n\t\t\t})\n\t\t\tfileFact[d.getName()] = fact\n\t\t})\n\t}\n}\nconst getResolverInformationForDeclaration = (initialiser: tsMorph.Expression | undefined): Omit<ResolverFuncFact, \"name\"> => {\n\t// Who knows what folks could do, lets not crash",
"score": 0.8072656393051147
},
{
"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.8059650659561157
}
] | typescript | function addCustomTypeModel(modelFacts: ModelResolverFacts) { |
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\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.8397879600524902
},
{
"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.7927818298339844
},
{
"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.7776645421981812
},
{
"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.7606600522994995
},
{
"filename": "src/index.ts",
"retrieved_chunk": "\tconst pathSettings: AppContext[\"pathSettings\"] = {\n\t\troot: paths.base,\n\t\tapiServicesPath: paths.api.services,\n\t\tprismaDSLPath: paths.api.dbSchema,\n\t\tgraphQLSchemaPath: paths.generated.schema,\n\t\tsharedFilename: \"shared-schema-types.d.ts\",\n\t\tsharedInternalFilename: \"shared-return-types.d.ts\",\n\t\ttypesFolderRoot: paths.api.types,\n\t}\n\tconst project = new Project({ useInMemoryFileSystem: true })",
"score": 0.7579895257949829
}
] | typescript | namedImports: sharedInternalGraphQLObjectsReferenced.types.map((t) => `${t} as RT${t}`),
})
} |
/// 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/typeMap.ts",
"retrieved_chunk": "\t\treferencedPrismaModels.clear()\n\t}\n\tconst getReferencedGraphQLThingsInMapping = () => {\n\t\treturn {\n\t\t\ttypes: [...referencedGraphQLTypes.keys()],\n\t\t\tscalars: [...customScalars.keys()],\n\t\t\tprisma: [...referencedPrismaModels.keys()],\n\t\t}\n\t}\n\tconst map = (",
"score": 0.7675501108169556
},
{
"filename": "src/typeMap.ts",
"retrieved_chunk": "\t\t\t}\n\t\t\tif (graphql.isUnionType(type)) {\n\t\t\t\tconst types = type.getTypes()\n\t\t\t\treturn types.map((t) => map(t, mapConfig)).join(\" | \")\n\t\t\t}\n\t\t\tif (graphql.isEnumType(type)) {\n\t\t\t\treturn prefix + type.name\n\t\t\t}\n\t\t\tif (graphql.isInputObjectType(type)) {\n\t\t\t\treferencedGraphQLTypes.add(type.name)",
"score": 0.7596873044967651
},
{
"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.756758451461792
},
{
"filename": "src/typeMap.ts",
"retrieved_chunk": "\t\t\t\treturn prefix + type.name\n\t\t\t}\n\t\t\t// eslint-disable-next-line @typescript-eslint/restrict-template-expressions\n\t\t\tthrow new Error(`Unknown type ${type} - ${JSON.stringify(type, null, 2)}`)\n\t\t}\n\t\tconst suffix = mapConfig.parentWasNotNull ? \"\" : mapConfig.preferNullOverUndefined ? \"| null\" : \" | undefined\"\n\t\treturn getInner() + suffix\n\t}\n\treturn { map, clear, getReferencedGraphQLThingsInMapping }\n}",
"score": 0.7540423274040222
},
{
"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.7510064840316772
}
] | typescript | scalars.map((s) => ({ |
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.8662840127944946
},
{
"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.8255553245544434
},
{
"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.8124139308929443
},
{
"filename": "src/run.ts",
"retrieved_chunk": "import { CodeFacts, FieldFacts } from \"./typeFacts.js\"\nexport function run(\n\tappRoot: string,\n\ttypesRoot: string,\n\tconfig: { deleteOldGraphQLDTS?: boolean; runESLint?: boolean; sys?: typescript.System } = {}\n) {\n\tconst sys = config.sys ?? typescript.sys\n\tconst project = new Project({ useInMemoryFileSystem: true })\n\tlet gqlSchema: graphql.GraphQLSchema | undefined\n\tconst getGraphQLSDLFromFile = (settings: AppContext[\"pathSettings\"]) => {",
"score": 0.8078880310058594
},
{
"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.7951862812042236
}
] | 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/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.8408527374267578
},
{
"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.782361626625061
},
{
"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.7790961861610413
},
{
"filename": "src/index.ts",
"retrieved_chunk": "\tconst pathSettings: AppContext[\"pathSettings\"] = {\n\t\troot: paths.base,\n\t\tapiServicesPath: paths.api.services,\n\t\tprismaDSLPath: paths.api.dbSchema,\n\t\tgraphQLSchemaPath: paths.generated.schema,\n\t\tsharedFilename: \"shared-schema-types.d.ts\",\n\t\tsharedInternalFilename: \"shared-return-types.d.ts\",\n\t\ttypesFolderRoot: paths.api.types,\n\t}\n\tconst project = new Project({ useInMemoryFileSystem: true })",
"score": 0.7660210132598877
},
{
"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.7570794820785522
}
] | typescript | : sharedInternalGraphQLObjectsReferenced.types.map((t) => `${t} as RT${t}`),
})
} |
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\t\t\t// @ts-expect-error - lets let this go for now\n\t\t\t\t\tfact.resolvers.set(name, { name, ...getResolverInformationForDeclaration(p) })\n\t\t\t\t}\n\t\t\t})\n\t\t\tfileFact[d.getName()] = fact\n\t\t})\n\t}\n}\nconst getResolverInformationForDeclaration = (initialiser: tsMorph.Expression | undefined): Omit<ResolverFuncFact, \"name\"> => {\n\t// Who knows what folks could do, lets not crash",
"score": 0.8047512769699097
},
{
"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.7989711761474609
},
{
"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.7980802655220032
},
{
"filename": "src/typeMap.ts",
"retrieved_chunk": "\t\t\t\treturn prefix + type.name\n\t\t\t}\n\t\t\t// eslint-disable-next-line @typescript-eslint/restrict-template-expressions\n\t\t\tthrow new Error(`Unknown type ${type} - ${JSON.stringify(type, null, 2)}`)\n\t\t}\n\t\tconst suffix = mapConfig.parentWasNotNull ? \"\" : mapConfig.preferNullOverUndefined ? \"| null\" : \" | undefined\"\n\t\treturn getInner() + suffix\n\t}\n\treturn { map, clear, getReferencedGraphQLThingsInMapping }\n}",
"score": 0.7870929837226868
},
{
"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.7707970142364502
}
] | typescript | function returnTypeForResolver(mapper: TypeMapper, field: graphql.GraphQLField<unknown, unknown> | undefined, resolver: ResolverFuncFact) { |
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.8636747598648071
},
{
"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.8275898694992065
},
{
"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.8092430830001831
},
{
"filename": "src/run.ts",
"retrieved_chunk": "import { CodeFacts, FieldFacts } from \"./typeFacts.js\"\nexport function run(\n\tappRoot: string,\n\ttypesRoot: string,\n\tconfig: { deleteOldGraphQLDTS?: boolean; runESLint?: boolean; sys?: typescript.System } = {}\n) {\n\tconst sys = config.sys ?? typescript.sys\n\tconst project = new Project({ useInMemoryFileSystem: true })\n\tlet gqlSchema: graphql.GraphQLSchema | undefined\n\tconst getGraphQLSDLFromFile = (settings: AppContext[\"pathSettings\"]) => {",
"score": 0.8086154460906982
},
{
"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.7933601140975952
}
] | typescript | sys.readDirectory(appContext.pathSettings.apiServicesPath)
const serviceFilesToLookAt = serviceFiles.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/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.7779080867767334
},
{
"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.77518230676651
},
{
"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.7556405067443848
},
{
"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.7288118004798889
},
{
"filename": "src/sharedSchema.ts",
"retrieved_chunk": "/// The main schema for objects and inputs\nimport * as graphql from \"graphql\"\nimport * as tsMorph from \"ts-morph\"\nimport { AppContext } from \"./context.js\"\nimport { formatDTS, getPrettierConfig } from \"./formatDTS.js\"\nimport { typeMapper } from \"./typeMap.js\"\nexport const createSharedSchemaFiles = (context: AppContext) => {\n\tcreateSharedExternalSchemaFile(context)\n\tcreateSharedReturnPositionSchemaFile(context)\n\treturn [",
"score": 0.725350558757782
}
] | typescript | context.sys.writeFile(dtsFilepath, formatted)
return dtsFilepath
function addDefinitionsForTopLevelResolvers(parentName: string, config: ResolverFuncFact) { |
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='[email protected]'
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.9267102479934692
},
{
"filename": "src/components/LoginSms.tsx",
"retrieved_chunk": " )}\n {errors && <span className='mt-2 block text-left text-sm text-red-800'>{errors.root?.message}</span>}\n {/* 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.8745205402374268
},
{
"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.8436876535415649
},
{
"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.8245906233787537
},
{
"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.8058634996414185
}
] | 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 { 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/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.8911607265472412
},
{
"filename": "src/utils/phone-countries.ts",
"retrieved_chunk": "import { Country } from 'react-phone-number-input';\n/**\n * These are the countries that Stytch supports at the time of writing\n * https://stytch.com/docs/passcodes#unsupported-countries.\n *\n * This list is used to populate the country dropdown on the phone number input\n * in the login form. Simply remove any countries that you don't want to support. You may\n * want to limit support due to cost, fraud, or because you do not do business in that country.\n **/\nexport const STYTCH_SUPPORTED_SMS_COUNTRIES: Country[] = [",
"score": 0.8364324569702148
},
{
"filename": "src/components/Profile.tsx",
"retrieved_chunk": " </pre>\n <p>\n You are logged in, and a Session has been created. The backend Node SDK has stored the\n Session as a JWT in the browser cookies as{\" \"}\n <span className=\"code\">session_jwt</span>.\n </p>\n <AccountLogout />\n </div>\n );\n};",
"score": 0.8245463371276855
},
{
"filename": "src/server/trpc.ts",
"retrieved_chunk": " errorFormatter({ shape }) {\n return shape;\n },\n});\n/**\n * Reusable middleware that checks if users are authenticated.\n **/\nconst isAuthed = t.middleware(async ({ next, ctx }) => {\n if (!ctx.req || !ctx.res) {\n throw new Error('You are missing `req` or `res` in your call.');",
"score": 0.8190535306930542
},
{
"filename": "src/server/trpc.ts",
"retrieved_chunk": "import { initTRPC, TRPCError } from '@trpc/server';\nimport superjson from 'superjson';\nimport { Context } from './context';\n/**\n * This is your entry point to setup the root configuration for tRPC on the server.\n * - `initTRPC` should only be used once per app.\n * - We export only the functionality that we use so we can enforce which base procedures should be used\n *\n * Learn how to create protected base procedures and other things below:\n * @see https://trpc.io/docs/v10/router",
"score": 0.8158811926841736
}
] | typescript | logout: protectedProcedure.mutation(async ({ ctx }) => { |
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='[email protected]'
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.9218832850456238
},
{
"filename": "src/components/LoginSms.tsx",
"retrieved_chunk": " )}\n {errors && <span className='mt-2 block text-left text-sm text-red-800'>{errors.root?.message}</span>}\n {/* 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.8796671628952026
},
{
"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.8466196656227112
},
{
"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.8317543268203735
},
{
"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.7951794862747192
}
] | 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 { 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.7924309968948364
},
{
"filename": "src/components/VerifyOtp.tsx",
"retrieved_chunk": "export function VerifyOtp(props: { methodId: string; methodValue: string }) {\n const { methodId, methodValue } = props;\n const router = useRouter();\n const utils = trpc.useContext();\n const { mutateAsync } = trpc.auth.authenticateOtp.useMutation({\n onSuccess: () => {\n utils.user.current.invalidate();\n router.push('/profile');\n },\n });",
"score": 0.7324758768081665
},
{
"filename": "src/components/LoginEmail.tsx",
"retrieved_chunk": "});\ntype FormSchemaType = z.infer<typeof formSchema>;\nexport function LoginEmail(props: { onSwitchMethod: (method: StytchAuthMethods) => void }) {\n const { data, mutateAsync } = trpc.auth.loginEmail.useMutation();\n const {\n handleSubmit,\n register,\n getValues,\n setError,\n formState: { errors, isSubmitting },",
"score": 0.7121289372444153
},
{
"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.7092738747596741
},
{
"filename": "src/server/trpc.ts",
"retrieved_chunk": " errorFormatter({ shape }) {\n return shape;\n },\n});\n/**\n * Reusable middleware that checks if users are authenticated.\n **/\nconst isAuthed = t.middleware(async ({ next, ctx }) => {\n if (!ctx.req || !ctx.res) {\n throw new Error('You are missing `req` or `res` in your call.');",
"score": 0.7089566588401794
}
] | 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 { 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/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.9100581407546997
},
{
"filename": "src/components/LoginEmail.tsx",
"retrieved_chunk": " mutateAsync({ email: values.email }).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 <div>\n <Input\n aria-label='Email'\n placeholder='[email protected]'",
"score": 0.8606996536254883
},
{
"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.8574815988540649
},
{
"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.8476648330688477
},
{
"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.8098323345184326
}
] | 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 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 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.8224813938140869
},
{
"filename": "src/typeMap.ts",
"retrieved_chunk": "import * as graphql from \"graphql\"\nimport { AppContext } from \"./context.js\"\nexport type TypeMapper = ReturnType<typeof typeMapper>\nexport const typeMapper = (context: AppContext, config: { preferPrismaModels?: true }) => {\n\tconst referencedGraphQLTypes = new Set<string>()\n\tconst referencedPrismaModels = new Set<string>()\n\tconst customScalars = new Set<string>()\n\tconst clear = () => {\n\t\treferencedGraphQLTypes.clear()\n\t\tcustomScalars.clear()",
"score": 0.7967957258224487
},
{
"filename": "src/context.ts",
"retrieved_chunk": "\t/** A global set of facts about resolvers focused from the GQL side */\n\tfieldFacts: Map<string, FieldFacts>\n\t/** When we emit .d.ts files, it runs the ts formatter over the file first - you can override the default settings */\n\tformatCodeSettings?: FormatCodeSettings\n\t/** So you can override the formatter */\n\tgql: graphql.GraphQLSchema\n\t/** POSXIY- fn not built into System */\n\tjoin: (...paths: string[]) => string\n\t/** Where to find particular files */\n\tpathSettings: {",
"score": 0.7953356504440308
},
{
"filename": "src/index.ts",
"retrieved_chunk": "\t\tcodeFacts: new Map<string, CodeFacts>(),\n\t\tfieldFacts: new Map<string, FieldFacts>(),\n\t\tpathSettings,\n\t\tsys,\n\t\tjoin,\n\t\tbasename,\n\t}\n\t// TODO: Maybe Redwood has an API for this? Its grabbing all the services\n\tconst serviceFiles = appContext.sys.readDirectory(appContext.pathSettings.apiServicesPath)\n\tconst serviceFilesToLookAt = serviceFiles.filter((file) => {",
"score": 0.7855446338653564
},
{
"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.7827046513557434
}
] | 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>; |
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.8207285404205322
},
{
"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.7892066240310669
},
{
"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.7753466367721558
},
{
"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.7602436542510986
},
{
"filename": "src/prismaModeller.ts",
"retrieved_chunk": "}\nexport type PrismaMap = ReadonlyMap<string, Model>\nexport const prismaModeller = (schema: PrismaSchemaBlocks) => {\n\tconst types = new Map<string, Model>()\n\tlet leadingComments: string[] = []\n\tschema.list.forEach((b) => {\n\t\tif (b.type === \"comment\") {\n\t\t\tleadingComments.push(b.text.replace(\"/// \", \"\").replace(\"// \", \"\"))\n\t\t}\n\t\tif (b.type === \"model\") {",
"score": 0.7576229572296143
}
] | typescript | const fact: ModelResolverFacts = fileFact[name] ?? { |
/// 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.7619138360023499
},
{
"filename": "src/run.ts",
"retrieved_chunk": "\t\t\t}\n\t\t}\n\t}\n\t// empty the types folder\n\tfor (const dirEntry of sys.readDirectory(appContext.pathSettings.typesFolderRoot)) {\n\t\tconst fileToDelete = join(appContext.pathSettings.typesFolderRoot, dirEntry)\n\t\tif (sys.deleteFile && sys.fileExists(fileToDelete)) {\n\t\t\tsys.deleteFile(fileToDelete)\n\t\t}\n\t}",
"score": 0.7453845739364624
},
{
"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.7323477268218994
},
{
"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.7271544933319092
},
{
"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.7258760929107666
}
] | 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\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.788486659526825
},
{
"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.773479163646698
},
{
"filename": "src/index.ts",
"retrieved_chunk": "\t\tcodeFacts: new Map<string, CodeFacts>(),\n\t\tfieldFacts: new Map<string, FieldFacts>(),\n\t\tpathSettings,\n\t\tsys,\n\t\tjoin,\n\t\tbasename,\n\t}\n\t// TODO: Maybe Redwood has an API for this? Its grabbing all the services\n\tconst serviceFiles = appContext.sys.readDirectory(appContext.pathSettings.apiServicesPath)\n\tconst serviceFilesToLookAt = serviceFiles.filter((file) => {",
"score": 0.7663620710372925
},
{
"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.7609888315200806
},
{
"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.7536296844482422
}
] | 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/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.8098803162574768
},
{
"filename": "src/typeMap.ts",
"retrieved_chunk": "\t\t\t\treturn prefix + type.name\n\t\t\t}\n\t\t\t// eslint-disable-next-line @typescript-eslint/restrict-template-expressions\n\t\t\tthrow new Error(`Unknown type ${type} - ${JSON.stringify(type, null, 2)}`)\n\t\t}\n\t\tconst suffix = mapConfig.parentWasNotNull ? \"\" : mapConfig.preferNullOverUndefined ? \"| null\" : \" | undefined\"\n\t\treturn getInner() + suffix\n\t}\n\treturn { map, clear, getReferencedGraphQLThingsInMapping }\n}",
"score": 0.7899916172027588
},
{
"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.7855215668678284
},
{
"filename": "src/index.ts",
"retrieved_chunk": "\t\tcodeFacts: new Map<string, CodeFacts>(),\n\t\tfieldFacts: new Map<string, FieldFacts>(),\n\t\tpathSettings,\n\t\tsys,\n\t\tjoin,\n\t\tbasename,\n\t}\n\t// TODO: Maybe Redwood has an API for this? Its grabbing all the services\n\tconst serviceFiles = appContext.sys.readDirectory(appContext.pathSettings.apiServicesPath)\n\tconst serviceFilesToLookAt = serviceFiles.filter((file) => {",
"score": 0.7767446041107178
},
{
"filename": "src/typeMap.ts",
"retrieved_chunk": "\t\tif (graphql.isNonNullType(type)) {\n\t\t\treturn map(type.ofType, { parentWasNotNull: true, ...mapConfig })\n\t\t}\n\t\t// So we can add the | undefined\n\t\tconst getInner = () => {\n\t\t\tif (graphql.isListType(type)) {\n\t\t\t\tconst typeStr = map(type.ofType, mapConfig)\n\t\t\t\tif (!typeStr) return \"any\"\n\t\t\t\tif (graphql.isNonNullType(type.ofType)) {\n\t\t\t\t\treturn `${typeStr}[]`",
"score": 0.7761976718902588
}
] | typescript | hasGenerics = modelFacts.hasGenericArg
// This is what they would have to write
const resolverInterface = fileDTS.addInterface({ |
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.8180668354034424
},
{
"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.7888417840003967
},
{
"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.7845805883407593
},
{
"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.7787858247756958
},
{
"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.7769471406936646
}
] | typescript | createAndReferOrInlineArgsForField(field, { |
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/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.846787691116333
},
{
"filename": "src/controller/redtube/redtubeGetRelated.ts",
"retrieved_chunk": " * async with session.get(\"https://lust.scathach.id/redtube/get?id=41698751\") as resp:\n * print(await resp.json())\n */\n const id = req.query.id as string;\n if (!id) throw Error(\"Parameter key is required\");\n if (isNaN(Number(id))) throw Error(\"Parameter id must be a number\");\n const url = `${c.REDTUBE}/${id}`;\n const data = await scrapeContent(url);\n logger.info({\n path: req.path,",
"score": 0.8387578725814819
},
{
"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.8385841846466064
},
{
"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.8380423784255981
},
{
"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.8377341032028198
}
] | typescript | `${c.PORNHUB}/video/search?search=${spacer(key)}`; |
/// 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.7678403854370117
},
{
"filename": "src/run.ts",
"retrieved_chunk": "\t\t\t}\n\t\t}\n\t}\n\t// empty the types folder\n\tfor (const dirEntry of sys.readDirectory(appContext.pathSettings.typesFolderRoot)) {\n\t\tconst fileToDelete = join(appContext.pathSettings.typesFolderRoot, dirEntry)\n\t\tif (sys.deleteFile && sys.fileExists(fileToDelete)) {\n\t\t\tsys.deleteFile(fileToDelete)\n\t\t}\n\t}",
"score": 0.7436631321907043
},
{
"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.7337350845336914
},
{
"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.7320327758789062
},
{
"filename": "src/serviceFile.ts",
"retrieved_chunk": "\t\t\tnamedImports: validPrismaObjs.map((p) => `${p} as P${p}`),\n\t\t})\n\t}\n\tif (fileDTS.getText().includes(\"GraphQLResolveInfo\")) {\n\t\tfileDTS.addImportDeclaration({\n\t\t\tisTypeOnly: true,\n\t\t\tmoduleSpecifier: \"graphql\",\n\t\t\tnamedImports: [\"GraphQLResolveInfo\"],\n\t\t})\n\t}",
"score": 0.7268875241279602
}
] | 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\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.7880526781082153
},
{
"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.7805324792861938
},
{
"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.7479164600372314
},
{
"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.7350903749465942
},
{
"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.7336313128471375
}
] | typescript | .preferPrismaModels && context.prisma.has(type.name)) { |
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/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.9428274631500244
},
{
"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.9426398277282715
},
{
"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.9422670602798462
},
{
"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.936397910118103
},
{
"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.936397910118103
}
] | 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/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.8917413949966431
},
{
"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.8872424364089966
},
{
"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.8840656876564026
},
{
"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.8833262324333191
},
{
"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.8827658891677856
}
] | 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/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.9623014330863953
},
{
"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.9422093033790588
},
{
"filename": "src/controller/redtube/redtubeGetRelated.ts",
"retrieved_chunk": " * @apiExample {js} JS/TS\n * import axios from \"axios\"\n * \n * axios.get(\"https://lust.scathach.id/redtube/get?id=41698751\")\n * .then(res => console.log(res.data))\n * .catch(err => console.error(err))\n * \n * @apiExample {python} Python\n * import aiohttp\n * async with aiohttp.ClientSession() as session:",
"score": 0.931219756603241
},
{
"filename": "src/controller/pornhub/pornhubRandom.ts",
"retrieved_chunk": " * @apiExample {js} JS/TS\n * import axios from \"axios\"\n * \n * axios.get(\"https://lust.scathach.id/pornhub/random\")\n * .then(res => console.log(res.data))\n * .catch(err => console.error(err))\n * \n * @apiExample {python} Python\n * import aiohttp\n * async with aiohttp.ClientSession() as session:",
"score": 0.9252716898918152
},
{
"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.917486310005188
}
] | 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/redtube/redtubeRandom.ts",
"retrieved_chunk": " const search = $(\"a.video_link\")\n .map((i, el) => {\n return $(el).attr(\"href\");\n }).get();\n const random = Math.floor(Math.random() * search.length);\n const url = c.REDTUBE + search[random];\n const data = await scrapeContent(url);\n logger.info({\n path: req.path,\n query: req.query,",
"score": 0.8984320163726807
},
{
"filename": "src/controller/xvideos/xvideosRandom.ts",
"retrieved_chunk": " .map((i, el) => $(el).attr(\"href\"))\n .get();\n const filtered = search.filter((el) => el.includes(\"/video\"));\n const filtered_ = filtered.filter((el) => !el.includes(\"THUMBNUM\"));\n const random = Math.floor(Math.random() * filtered_.length);\n const url = c.XVIDEOS + filtered[random];\n const data = await scrapeContent(url);\n logger.info({\n path: req.path,\n query: req.query,",
"score": 0.8632037043571472
},
{
"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.8392001986503601
},
{
"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.8269909620285034
},
{
"filename": "src/scraper/youporn/youpornSearchController.ts",
"retrieved_chunk": " dur: string[];\n search: object[];\n constructor() {\n this.dur = $(\"div.video-duration\").map((i, el) => {\n return $(el).text();\n }).get();\n this.search = $(\"a[href^='/watch/']\")\n .map((i, el) => {\n const link = $(el).attr(\"href\");\n const id = `${link}`.split(\"/\")[2] + \"/\" + `${link}`.split(\"/\")[3];",
"score": 0.8192285895347595
}
] | 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/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.9383116960525513
},
{
"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.9366990327835083
},
{
"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.9342479705810547
},
{
"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.9329033493995667
},
{
"filename": "src/controller/redtube/redtubeGetRelated.ts",
"retrieved_chunk": " * async with session.get(\"https://lust.scathach.id/redtube/get?id=41698751\") as resp:\n * print(await resp.json())\n */\n const id = req.query.id as string;\n if (!id) throw Error(\"Parameter key is required\");\n if (isNaN(Number(id))) throw Error(\"Parameter id must be a number\");\n const url = `${c.REDTUBE}/${id}`;\n const data = await scrapeContent(url);\n logger.info({\n path: req.path,",
"score": 0.9006086587905884
}
] | typescript | 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.9423163533210754
},
{
"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.9421521425247192
},
{
"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.9403018951416016
},
{
"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.938409686088562
},
{
"filename": "src/controller/redtube/redtubeGetRelated.ts",
"retrieved_chunk": " * async with session.get(\"https://lust.scathach.id/redtube/get?id=41698751\") as resp:\n * print(await resp.json())\n */\n const id = req.query.id as string;\n if (!id) throw Error(\"Parameter key is required\");\n if (isNaN(Number(id))) throw Error(\"Parameter id must be a number\");\n const url = `${c.REDTUBE}/${id}`;\n const data = await scrapeContent(url);\n logger.info({\n path: req.path,",
"score": 0.9109747409820557
}
] | typescript | const url = `${c.XNXX}/search/${spacer(key)}/${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/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.9396041631698608
},
{
"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.9380888342857361
},
{
"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.9364198446273804
},
{
"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.9357331991195679
},
{
"filename": "src/controller/redtube/redtubeGetRelated.ts",
"retrieved_chunk": " * async with session.get(\"https://lust.scathach.id/redtube/get?id=41698751\") as resp:\n * print(await resp.json())\n */\n const id = req.query.id as string;\n if (!id) throw Error(\"Parameter key is required\");\n if (isNaN(Number(id))) throw Error(\"Parameter id must be a number\");\n const url = `${c.REDTUBE}/${id}`;\n const data = await scrapeContent(url);\n logger.info({\n path: req.path,",
"score": 0.9072864651679993
}
] | 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/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.9456517696380615
},
{
"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.9453915357589722
},
{
"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.9427535533905029
},
{
"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.9406495094299316
},
{
"filename": "src/controller/redtube/redtubeGetRelated.ts",
"retrieved_chunk": " * async with session.get(\"https://lust.scathach.id/redtube/get?id=41698751\") as resp:\n * print(await resp.json())\n */\n const id = req.query.id as string;\n if (!id) throw Error(\"Parameter key is required\");\n if (isNaN(Number(id))) throw Error(\"Parameter id must be a number\");\n const url = `${c.REDTUBE}/${id}`;\n const data = await scrapeContent(url);\n logger.info({\n path: req.path,",
"score": 0.9036144018173218
}
] | 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.9670763611793518
},
{
"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.9507439136505127
},
{
"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.9500371217727661
},
{
"filename": "src/controller/xnxx/xnxxGet.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/xnxx/get?id=video-17vah71a/makima_y_denji\") as resp:\n * print(await resp.json())\n */\n const url = `${c.XNXX}/${id}`;\n const data = await scrapeContent(url);\n logger.info({",
"score": 0.9229494333267212
},
{
"filename": "src/controller/xnxx/xnxxGetRelated.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/xnxx/related?id=video-17vah71a/makima_y_denji\") as resp:\n * print(await resp.json())\n */\n const url = `${c.XNXX}/${id}`;\n const data = await scrapeContent(url);\n logger.info({",
"score": 0.9226687550544739
}
] | typescript | lust.fetchBody(c.XVIDEOS); |
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/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.930422842502594
},
{
"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.9291926622390747
},
{
"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.9289788007736206
},
{
"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.9258741140365601
},
{
"filename": "src/controller/redtube/redtubeGetRelated.ts",
"retrieved_chunk": " * async with session.get(\"https://lust.scathach.id/redtube/get?id=41698751\") as resp:\n * print(await resp.json())\n */\n const id = req.query.id as string;\n if (!id) throw Error(\"Parameter key is required\");\n if (isNaN(Number(id))) throw Error(\"Parameter id must be a number\");\n const url = `${c.REDTUBE}/${id}`;\n const data = await scrapeContent(url);\n logger.info({\n path: req.path,",
"score": 0.8951578736305237
}
] | typescript | .XVIDEOS}/?k=${spacer(key)}&p=${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/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.9401973485946655
},
{
"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.9380810260772705
},
{
"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.9368668794631958
},
{
"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.9357113838195801
},
{
"filename": "src/controller/redtube/redtubeGetRelated.ts",
"retrieved_chunk": " * async with session.get(\"https://lust.scathach.id/redtube/get?id=41698751\") as resp:\n * print(await resp.json())\n */\n const id = req.query.id as string;\n if (!id) throw Error(\"Parameter key is required\");\n if (isNaN(Number(id))) throw Error(\"Parameter id must be a number\");\n const url = `${c.REDTUBE}/${id}`;\n const data = await scrapeContent(url);\n logger.info({\n path: req.path,",
"score": 0.9278162717819214
}
] | typescript | const url = `${c.REDTUBE}/?search=${spacer(key)}&page=${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/utils/pack.ts",
"retrieved_chunk": " const execOptions = {\n maxBuffer: 10 * 1024 * 1024,\n };\n const log = createLogger(getConfig().logLevel);\n const previousCwd = process.cwd();\n process.chdir(srcDir);\n /**\n * PNPM pack seems to be a lot faster than NPM pack, so when PNPM is detected\n * we use that instead.\n */",
"score": 0.8914139866828918
},
{
"filename": "src/index.ts",
"retrieved_chunk": "#!/usr/bin/env node\n/**\n * For PNPM the hashbang at the top of the script was not required, but Yarn 3\n * did not seem to execute without it.\n */\n/**\n * A word about used terminology:\n *\n * The various package managers, while being very similar, seem to use a\n * different definition for the term \"workspace\". If you want to read the code",
"score": 0.8617124557495117
},
{
"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.8610930442810059
},
{
"filename": "src/helpers/pack-dependencies.ts",
"retrieved_chunk": " /**\n * The directory where the isolated package and all its dependencies will end\n * up. This is also the directory from where the package will be deployed. By\n * default it is a subfolder in targetPackageDir called \"isolate\" but you can\n * configure it.\n */\n packDestinationDir,\n}: {\n packagesRegistry: PackagesRegistry;\n localDependencies: string[];",
"score": 0.8544520735740662
},
{
"filename": "src/index.ts",
"retrieved_chunk": " packageManager.version\n );\n /**\n * Disable lock files for PNPM because they are not yet supported.\n */\n if (packageManager.name === \"pnpm\") {\n config.excludeLockfile = true;\n }\n /**\n * Build a packages registry so we can find the workspace packages by name and",
"score": 0.8496531248092651
}
] | 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.8662611246109009
},
{
"filename": "src/helpers/list-local-dependencies.ts",
"retrieved_chunk": " ]\n : Object.keys(manifest.dependencies ?? {})\n ).filter((name) => allWorkspacePackageNames.includes(name));\n const nestedLocalDependencies = localDependencyPackageNames.flatMap(\n (packageName) =>\n listLocalDependencies(\n packagesRegistry[packageName].manifest,\n packagesRegistry,\n { includeDevDependencies }\n )",
"score": 0.8462165594100952
},
{
"filename": "src/index.ts",
"retrieved_chunk": " * have access to their manifest files and relative paths.\n */\n const packagesRegistry = await createPackagesRegistry(\n workspaceRootDir,\n config.workspacePackages\n );\n const localDependencies = listLocalDependencies(\n targetPackageManifest,\n packagesRegistry,\n {",
"score": 0.8372828960418701
},
{
"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.834723174571991
},
{
"filename": "src/helpers/list-local-dependencies.ts",
"retrieved_chunk": " manifest: PackageManifest,\n packagesRegistry: PackagesRegistry,\n { includeDevDependencies = false } = {}\n): string[] {\n const allWorkspacePackageNames = Object.keys(packagesRegistry);\n const localDependencyPackageNames = (\n includeDevDependencies\n ? [\n ...Object.keys(manifest.dependencies ?? {}),\n ...Object.keys(manifest.devDependencies ?? {}),",
"score": 0.8253035545349121
}
] | typescript | allPackages.map(async (rootRelativeDir) => { |
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/index.ts",
"retrieved_chunk": " includeDevDependencies: config.includeDevDependencies,\n }\n );\n const packedFilesByName = await packDependencies({\n localDependencies,\n packagesRegistry,\n packDestinationDir: tmpDir,\n });\n await unpackDependencies(\n packedFilesByName,",
"score": 0.8521535396575928
},
{
"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.8378651738166809
},
{
"filename": "src/helpers/process-lockfile.ts",
"retrieved_chunk": " const targetPackageRelativeDir =\n packagesRegistry[targetPackageName].rootRelativeDir;\n const { name } = usePackageManager();\n const fileName = getLockfileFileName(name);\n const lockfileSrcPath = path.join(workspaceRootDir, fileName);\n const lockfileDstPath = path.join(isolateDir, fileName);\n switch (name) {\n case \"npm\": {\n /**\n * If there is a shrinkwrap file we copy that instead of the lockfile",
"score": 0.8335806727409363
},
{
"filename": "src/helpers/patch-workspace-entries.ts",
"retrieved_chunk": " *\n * For consistency we also write the other file paths starting with\n * ./, but it doesn't seem to be necessary for any package manager.\n */\n const relativePath = parentRootRelativeDir\n ? path.relative(parentRootRelativeDir, `./${def.rootRelativeDir}`)\n : `./${def.rootRelativeDir}`;\n const linkPath = `file:${relativePath}`;\n log.debug(`Linking dependency ${key} to ${linkPath}`);\n return [key, linkPath];",
"score": 0.8218351006507874
},
{
"filename": "src/index.ts",
"retrieved_chunk": " * have access to their manifest files and relative paths.\n */\n const packagesRegistry = await createPackagesRegistry(\n workspaceRootDir,\n config.workspacePackages\n );\n const localDependencies = listLocalDependencies(\n targetPackageManifest,\n packagesRegistry,\n {",
"score": 0.8212759494781494
}
] | typescript | packedFileByName[name] = await pack(
def.absoluteDir,
packDestinationDir,
usePnpmPack
); |
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/helpers/create-packages-registry.ts",
"retrieved_chunk": "): Promise<PackagesRegistry> {\n const log = createLogger(getConfig().logLevel);\n if (workspacePackagesOverride) {\n log.debug(\n `Override workspace packages via config: ${workspacePackagesOverride}`\n );\n }\n const packagesGlobs =\n workspacePackagesOverride ?? findPackagesGlobs(workspaceRootDir);\n const cwd = process.cwd();",
"score": 0.8147311210632324
},
{
"filename": "src/helpers/create-packages-registry.ts",
"retrieved_chunk": " const manifestPath = path.join(rootRelativeDir, \"package.json\");\n if (!fs.existsSync(manifestPath)) {\n log.warn(\n `Ignoring directory ./${rootRelativeDir} because it does not contain a package.json file`\n );\n return;\n } else {\n log.debug(`Registering package ./${rootRelativeDir}`);\n const manifest = await readTypedJson<PackageManifest>(\n path.join(rootRelativeDir, \"package.json\")",
"score": 0.8110390901565552
},
{
"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.8015691637992859
},
{
"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.7901855111122131
},
{
"filename": "src/helpers/process-build-output-files.ts",
"retrieved_chunk": " targetPackageDir: string;\n tmpDir: string;\n isolateDir: string;\n}) {\n const log = createLogger(getConfig().logLevel);\n const packedFilePath = await pack(targetPackageDir, tmpDir);\n const unpackDir = path.join(tmpDir, \"target\");\n const now = Date.now();\n let isWaitingYet = false;\n while (!fs.existsSync(packedFilePath) && Date.now() - now < TIMEOUT_MS) {",
"score": 0.7856639623641968
}
] | 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/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.8755844831466675
},
{
"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.8602615594863892
},
{
"filename": "src/helpers/patch-workspace-entries.ts",
"retrieved_chunk": " *\n * For consistency we also write the other file paths starting with\n * ./, but it doesn't seem to be necessary for any package manager.\n */\n const relativePath = parentRootRelativeDir\n ? path.relative(parentRootRelativeDir, `./${def.rootRelativeDir}`)\n : `./${def.rootRelativeDir}`;\n const linkPath = `file:${relativePath}`;\n log.debug(`Linking dependency ${key} to ${linkPath}`);\n return [key, linkPath];",
"score": 0.8494799137115479
},
{
"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.8444919586181641
},
{
"filename": "src/helpers/pack-dependencies.ts",
"retrieved_chunk": " if (packedFileByName[name]) {\n log.debug(`Skipping ${name} because it has already been packed`);\n continue;\n }\n packedFileByName[name] = await pack(\n def.absoluteDir,\n packDestinationDir,\n usePnpmPack\n );\n }",
"score": 0.8443050384521484
}
] | typescript | await readTypedJson<PackageManifest>(
path.join(rootRelativeDir, "package.json")
); |
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/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.9064900875091553
},
{
"filename": "src/index.ts",
"retrieved_chunk": " includeDevDependencies: config.includeDevDependencies,\n }\n );\n const packedFilesByName = await packDependencies({\n localDependencies,\n packagesRegistry,\n packDestinationDir: tmpDir,\n });\n await unpackDependencies(\n packedFilesByName,",
"score": 0.8914902210235596
},
{
"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.8742198348045349
},
{
"filename": "src/index.ts",
"retrieved_chunk": " * have access to their manifest files and relative paths.\n */\n const packagesRegistry = await createPackagesRegistry(\n workspaceRootDir,\n config.workspacePackages\n );\n const localDependencies = listLocalDependencies(\n targetPackageManifest,\n packagesRegistry,\n {",
"score": 0.870067834854126
},
{
"filename": "src/helpers/adapt-target-package-manifest.ts",
"retrieved_chunk": " packagesRegistry: PackagesRegistry,\n isolateDir: string\n) {\n const outputManifest = adaptManifestWorkspaceDeps(\n {\n manifest,\n packagesRegistry,\n },\n { includeDevDependencies: getConfig().includeDevDependencies }\n );",
"score": 0.8625943660736084
}
] | typescript | const { name, version } = usePackageManager(); |
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/helpers/create-packages-registry.ts",
"retrieved_chunk": "): Promise<PackagesRegistry> {\n const log = createLogger(getConfig().logLevel);\n if (workspacePackagesOverride) {\n log.debug(\n `Override workspace packages via config: ${workspacePackagesOverride}`\n );\n }\n const packagesGlobs =\n workspacePackagesOverride ?? findPackagesGlobs(workspaceRootDir);\n const cwd = process.cwd();",
"score": 0.8020561933517456
},
{
"filename": "src/helpers/adapt-manifest-workspace-deps.ts",
"retrieved_chunk": " packagesRegistry: PackagesRegistry;\n parentRootRelativeDir?: string;\n },\n opts: { includeDevDependencies?: boolean } = {}\n): PackageManifest {\n return Object.assign(\n omit(manifest, [\"devDependencies\"]),\n filterObjectUndefined({\n dependencies: manifest.dependencies\n ? patchWorkspaceEntries(",
"score": 0.7730919122695923
},
{
"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.77283775806427
},
{
"filename": "src/helpers/list-local-dependencies.ts",
"retrieved_chunk": " manifest: PackageManifest,\n packagesRegistry: PackagesRegistry,\n { includeDevDependencies = false } = {}\n): string[] {\n const allWorkspacePackageNames = Object.keys(packagesRegistry);\n const localDependencyPackageNames = (\n includeDevDependencies\n ? [\n ...Object.keys(manifest.dependencies ?? {}),\n ...Object.keys(manifest.devDependencies ?? {}),",
"score": 0.7725744247436523
},
{
"filename": "src/helpers/adapt-target-package-manifest.ts",
"retrieved_chunk": " packagesRegistry: PackagesRegistry,\n isolateDir: string\n) {\n const outputManifest = adaptManifestWorkspaceDeps(\n {\n manifest,\n packagesRegistry,\n },\n { includeDevDependencies: getConfig().includeDevDependencies }\n );",
"score": 0.7715883255004883
}
] | typescript | log.debug("Using configuration:", inspectValue(config)); |
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/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.8439664840698242
},
{
"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.8397828340530396
},
{
"filename": "src/index.ts",
"retrieved_chunk": " * have access to their manifest files and relative paths.\n */\n const packagesRegistry = await createPackagesRegistry(\n workspaceRootDir,\n config.workspacePackages\n );\n const localDependencies = listLocalDependencies(\n targetPackageManifest,\n packagesRegistry,\n {",
"score": 0.8380481600761414
},
{
"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.8305944204330444
},
{
"filename": "src/helpers/process-lockfile.ts",
"retrieved_chunk": " const targetPackageRelativeDir =\n packagesRegistry[targetPackageName].rootRelativeDir;\n const { name } = usePackageManager();\n const fileName = getLockfileFileName(name);\n const lockfileSrcPath = path.join(workspaceRootDir, fileName);\n const lockfileDstPath = path.join(isolateDir, fileName);\n switch (name) {\n case \"npm\": {\n /**\n * If there is a shrinkwrap file we copy that instead of the lockfile",
"score": 0.822157621383667
}
] | typescript | ((dir) => fs.lstatSync(dir).isDirectory()); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.