The complete public API of @lakeql/api, generated from the package's TypeScript source.
The near plug-and-play entry point is createLakeQLApp. The lower-level server entry points are defineApiConfig, createApiServer, and startApiServer. Compose authentication with createApiResolveAuth and trinoUserImpersonation, and permissions with createPermission. The rest of the surface covers the schema builder, error handling, the Yoga integration, and the supporting types.
@lakeql/api/config, @lakeql/api/resolve-auth). Each export below lives
under the subpath matching its source module.Definition
new SchemaBuilder<{
Context: Context
Scalars: Partial<UserScalars["Scalars"]>
AuthScopes: {
authorized: boolean
readPermission: PermissionFields
writePermission: PermissionFields
}
}>({
plugins: [ScopeAuthPlugin, ValidationPlugin],
scopeAuth: {
authScopes: (context) => ({
authorized: !!context.currentUser,
readPermission: ({ dataSource, tableName, catalog, schema }) =>
(context.hasReadPermission ?? hasReadPermission)({
catalog,
context,
dataSource,
schema,
tableName,
}),
writePermission: ({ dataSource, tableName, catalog, schema }) =>
(context.hasWritePermission ?? hasWritePermission)({
catalog,
context,
dataSource,
schema,
tableName,
}),
}),
defaultStrategy: "any",
treatErrorsAsUnauthorized: true,
unauthorizedError: (_parent, _context, _info, result) => {
// throw an error if it's found
// this handles also 403 errors ( aka Permission denied)
throwFirstError(result.failure)
// throw a fallback error if no error was found
return new Error(`Not authorized`)
},
},
validation: {
validationError: (validationResult) =>
handleErrorResponse(
new Error(
validationResult.issues.map((i) => i.message).join("; ") ||
"Validation failed"
)
),
},
})Builds a ready-to-start LakeQL API server from a loaded project config.
Encapsulates the full wiring the generated src/index.ts would otherwise hand-write: it loads the config (unless project is supplied), derives the per-source sources map and the global impersonation resolver, builds the ResolveAuth via createApiResolveAuth, composes the runtime via createLakeQLRuntime, and defines the server via defineApiConfig. Every remaining option is forwarded to defineApiConfig unchanged.
Permissions default to project.config.auth?.permissions ?? [] and can be overridden via CreateLakeQLAppOptions.permissions. When the effective rule set is empty, EMPTY_PERMISSIONS_WARNING is printed so the default behavior is a deliberate choice, not a silent gap.
Parameters
| Name | Type |
|---|---|
| options? | CreateLakeQLAppOptions |
Project source and server-shaping options. All optional. {} | |
The warning printed on startup when no permission rules are configured.
Exported so tests and the docs can assert the exact wording the wrapper emits. Empty auth.permissions is a valid state, but it applies the defaults, so surface it instead of leaving a silent gap.
Definition
"No LakeQL permission rules configured. Defaults apply: human reads are delegated to each data source's own access control (e.g. Trino rules via impersonation, Fabric OBO), service-principal reads are denied, and all writes are denied until a matching Mutation rule is added. Ensure impersonation is configured — otherwise human queries run with the data source's service credentials."Options accepted by createLakeQLApp.
Every server-shaping option is inherited structurally from ApiRuntimeConfig (minus runtime, which the wrapper builds), so a new defineApiConfig option is forwarded automatically without touching this type. Two wrapper-only options are added: project selects an already-loaded config, and handleSignals controls graceful shutdown.
Properties
| Name | Type |
|---|---|
| project? | LoadedLakeQLProject |
An already-loaded project (from loadConfig()). When omitted, the wrapper calls loadConfig() itself with no arguments, matching the generated entry file’s default. | |
| permissions? | ApiRuntimeConfig["permissions"] |
Permission rules for technical users. project.config.auth?.permissions ?? [] | |
| handleSignals? | boolean |
Register SIGTERM/SIGINT handlers that close the runtime and exit. When true (the default) the wrapper owns graceful shutdown, reproducing the generated entry file. Set to false to own the lifecycle yourself via the returned close()/runtime. true | |
The composed application returned by createLakeQLApp.
Exposes the underlying runtime for advanced control plus start/close lifecycle helpers.
Properties
| Name | Type |
|---|---|
| runtimeRequired | LakeQLRuntime |
The composed runtime that owns data sources and read/write strategies. Advanced callers can drive it directly. | |
| startRequired | () => Promise<void> |
Starts the HTTP server. Reproduces the generated entry file’s startup error handling: configuration-state errors (e.g. no schema files yet) are printed without a stack trace and the process exits non-zero. | |
| closeRequired | () => Promise<void> |
Closes the runtime, releasing all data-source connections. Note this does not stop the HTTP listener — the socket is released on process exit. Call it when handleSignals is false and you own shutdown. | |
Defines the API server configuration with convenience methods for creating a Yoga server or starting the full HTTP server.
Parameters
| Name | Type |
|---|---|
| inputRequired | DefineConfigOptions |
API runtime configuration options. | |
Returns
DefinedApiConfigA resolved configuration with createYogaServer and startServer helpers.
Runtime configuration options for the LakeQL API server.
Properties
| Name | Type |
|---|---|
| tokenResolver? | TokenResolver |
Custom JWT token resolver. built-in mock auth | |
| identityResolver? | IdentityResolver |
Maps a JWT payload to a ResolvedIdentity. entraIdIdentityResolver | |
| hasReadPermission? | ReadPermissionResolver |
Custom read permission resolver. built-in read permission check | |
| hasWritePermission? | WritePermissionResolver |
Custom write permission resolver. built-in write permission check | |
| yogaConfig? | YogaConfigOverrides |
Override GraphQL Yoga options. | |
| cors? | CorsOptions |
CORS options for the GraphQL route, applied by the Hono layer that wraps Yoga. When omitted, CORS is not enabled (same-origin only). Set origin to the front-ends allowed to call the API. A wildcard origin ("*") cannot be combined with credentials: true — the browser rejects that pairing — so there is no permissive default. | |
| permissions? | Permission[] |
Permission rules for technical users. [] | |
| runtime? | LakeQLRuntime |
The LakeQL runtime that owns data sources and read/write strategies. Built by the application (via createLakeQLRuntime) and passed in so resolvers can resolve read strategies through the GraphQL context. The API does not construct or own the runtime lifecycle. | |
| baseDir? | string |
Base directory for resolving relative paths. process.cwd() | |
| schemaPath? | string |
Path to query schema files (relative to baseDir). | |
| graphqlPath? | string |
GraphQL endpoint path. "/graphql" | |
| healthCheckEndpoint? | string |
Health check endpoint path. "/live" | |
| port? | number |
Server port. 4000 | |
| onError? | ApiErrorHook |
Hook invoked for every GraphQL execution error after it is logged. Use it to forward errors to external telemetry (OpenTelemetry, Sentry, metrics) without this package depending on any of them. Thrown errors from the hook are swallowed so telemetry never breaks a response. | |
The resolved API configuration returned by defineApiConfig. Carries every ApiRuntimeConfig field through unchanged and adds the server helpers.
Properties
| Name | Type |
|---|---|
| createYogaServerRequired | ( logger: ReturnType<typeof createLogger> ) => ReturnType<typeof createYogaServer> |
| startServerRequired | () => ReturnType<typeof startApiServer> |
Configuration options for defineApiConfig.
Creates the ResolveAuth function for the API runtime.
The returned function resolves the effective impersonation resolver for a data source (per-source, then global), invokes it with the current user from the request context, and returns neutral { requestAuth, options } for the read strategy. When no resolver applies or there is no authenticated user, it returns an empty result (system user).
Parameters
| Name | Type |
|---|---|
| optionsRequired | CreateApiResolveAuthOptions |
Per-source metadata and the global impersonation resolver. | |
Returns
ResolveAuthA ResolveAuth suitable for createLakeQLRuntime.
Per-request auth context expected in the opaque context passed to the read strategy. The API builds this as the GraphQL context.
Properties
| Name | Type |
|---|---|
| currentUserRequired | JWTPayload | null |
Decoded JWT payload, or null when unauthenticated. | |
| identityRequired | ResolvedIdentity | null |
Resolved identity, or null when unauthenticated. | |
Configuration for createApiResolveAuth.
Properties
| Name | Type |
|---|---|
| sourcesRequired | Readonly<Record<string, ResolveAuthSourceInfo>> |
Per-data-source metadata keyed by configured source name. Typically derived from project.config.dataSources (adapter + optional per-source impersonationResolver). | |
| globalImpersonationResolver? | ImpersonationResolver |
Global fallback impersonation resolver (from auth.impersonationResolver). | |
Per-data-source metadata needed to resolve impersonation: the adapter name and an optional per-source impersonation resolver.
Properties
| Name | Type |
|---|---|
| adapterRequired | string |
Open adapter name owning this data source. | |
| impersonationResolver? | ImpersonationResolver |
Optional per-data-source impersonation resolver. | |
Creates an ImpersonationResolver that impersonates the current user by their JWT nameField via Trino’s impersonateAs option (X-Trino-User).
Returns null when the field is missing or not a non-empty string, so the caller falls back to the system user.
Parameters
| Name | Type |
|---|---|
| options? | TrinoUserImpersonationOptions |
Optional field selection. {} | |
Returns
ImpersonationResolverAn ImpersonationResolver producing { options: { impersonateAs } }.
Options for trinoUserImpersonation.
Properties
| Name | Type |
|---|---|
| nameField? | string |
Name of the JWT payload field to impersonate as. "userName" | |
| transform? | TrinoUsernameTransform |
Maps the claim value to the Trino username before it is sent as X-Trino-User. Use this when the IdP claim does not match the Trino username verbatim: "lower" / "upper" for case normalization, or a function for anything else. Applied only to a present, non-empty string claim. When the result is an empty string, the resolver returns null (no impersonation). the claim value is used unchanged | |
Default token resolver — mock auth for development.
In production, callers should supply their own TokenResolver through ApiRuntimeConfig.tokenResolver.
Parameters
| Name | Type |
|---|---|
| reqRequired | Request |
Returns
Promise<JWTPayload | null | undefined>Checks whether the current user may read from a data source table.
Authorization model:
- Unauthenticated users are denied.
- Service principals without an explicit permission entry are denied.
- Human users without a permission entry are allowed (Trino/adapter enforces).
- If rules exist, at least one Query rule for the data source must match.
Parameters
| Name | Type |
|---|---|
| { context: Context } & PermissionFieldsRequired | { context: Context } & PermissionFields |
Returns
booleantrue if read access is allowed, otherwise false.
Checks whether the current user may perform write operations on a data source table.
Authorization model:
- Unauthenticated users are denied.
- If no user-specific Mutation rules exist, write access is denied.
- If rules exist, at least one rule for the data source must match.
Parameters
| Name | Type |
|---|---|
| { context: Context } & PermissionFieldsRequired | { context: Context } & PermissionFields |
Returns
booleantrue if write access is allowed, otherwise false.
Default identity resolver for Microsoft Entra ID (Azure AD) tokens.
Extracts userName from the token using a fallback chain:
- onpremsamaccountname — synced on-prem AD account
- preferred_username — Entra ID UPN
- azp — authorized party (client ID for app-only tokens)
- "unknown" — fallback when none of the above are present
Determines service principal status when:
- idtyp claim is "app" (explicit app-only token), or
- no idtyp claim is present AND no onpremsamaccountname claim exists (heuristic: app-only tokens typically lack user-linked claims)
Parameters
| Name | Type |
|---|---|
| tokenRequired | JWTPayload |
Decoded JWT payload from the token resolver. | |
Returns
ResolvedIdentityTranslates a DataSourceError into a GraphQLError.
If the error is not a DataSourceError, it is re-thrown as a generic 500 GraphQLError.
Parameters
| Name | Type |
|---|---|
| errorRequired | unknown |
The error to handle. | |
Returns
neverParameters
| Name | Type |
|---|---|
| failureRequired | AuthFailure |
Builds a permission entry for a single data source.
Parameters
| Name | Type |
|---|---|
| dataSourceRequired | string |
Runtime name of the data source. | |
| rulesFnRequired | (rule: (r: PermissionRule) => PermissionRule) => PermissionRule[] |
Builder callback receiving a rule helper that creates PermissionRule entries. | |
Returns
{ dataSource: string; rules: PermissionRule[] }A permission entry with dataSource and rules.
Adapter-agnostic permission target fields.
dataSource and tableName are always required. catalog and schema are optional — some adapters expose flat namespaces without catalogs or schemas.
Properties
| Name | Type |
|---|---|
| dataSourceRequired | string |
| tableNameRequired | string |
| catalog? | string |
| schema? | string |
Parameters
| Name | Type |
|---|---|
| options? | ApiRuntimeConfig |
Default: {} | |
Returns
Promise<ApiServer>Parameters
| Name | Type |
|---|---|
| options? | ApiRuntimeConfig |
Default: {} | |
Parameters
| Name | Type |
|---|---|
| loggerRequired | ReturnType<typeof createLogger> |
| options? | ApiRuntimeConfig |
Default: {} | |
Returns
Promise<ApiYoga>Parameters
| Name | Type | ||||
|---|---|---|---|---|---|
| objectRequired | Object | ||||
| |||||
Returns
MiddlewareHandlerCreate the error-logging plugin.
Parameters
| Name | Type |
|---|---|
| loggerRequired | Logger |
The configured logger. | |
| onError? | ApiErrorHook |
Optional application hook for external telemetry. | |
Returns
PluginA Yoga plugin that logs execution errors.
Context passed to an ApiErrorHook for each logged GraphQL error.
Properties
| Name | Type |
|---|---|
| errorRequired | GraphQLError |
The GraphQL error as surfaced to the client. | |
| dataSourceError? | DataSourceError |
The underlying DataSourceError, when the failure originated from one. | |
| operationName? | string |
The GraphQL operation name, when available. | |
Application hook invoked for every logged GraphQL error. Use it to forward errors to external telemetry (OpenTelemetry, Sentry, metrics). Thrown errors from the hook are swallowed so telemetry never breaks a response.
Parameters
| Name | Type |
|---|---|
| options? | SchemaLoadOptions |
Default: {} | |
Returns
Promise<import("graphql").GraphQLSchema>Thrown by loadSchema when no generated schema files are found under the resolved schema directory.
This is an expected configuration state (for example, a freshly scaffolded project before the first pull), not an internal failure. Consumers can catch it to print a concise message instead of a stack trace.
Constructor
| Name | Type |
|---|---|
| schemaDirRequired | string |
The resolved absolute directory that was searched. | |
Properties
| Name | Type |
|---|---|
| nameRequired | unknown |
| schemaDirRequired | string |
The resolved absolute directory that was searched. | |
Properties
| Name | Type |
|---|---|
| baseDir? | string |
| schemaPath? | string |
The GraphQL context object available in every resolver.
Properties
| Name | Type |
|---|---|
| currentUserRequired | JWTPayload | null |
Decoded JWT payload from token verification, or null for unauthenticated requests. | |
| identityRequired | ResolvedIdentity | null |
Resolved identity information (user name, SP flag), or null when unauthenticated. | |
| permissionsRequired | Permission[] |
Configured permission rules for technical users. | |
| hasReadPermission? | ReadPermissionResolver |
Custom resolver for read permission checks. | |
| hasWritePermission? | WritePermissionResolver |
Custom resolver for write permission checks. | |
| getReadStrategyRequired | (name: string) => DataSourceReadStrategy |
Resolves the read strategy for a configured data-source name. Delegates to the runtime passed to defineApiConfig. Always present; when the API was configured without a runtime, calling it throws. | |
| getWriteStrategy? | (name: string) => DataSourceWriteStrategy |
Resolves the write strategy for a configured data-source name. Delegates to the runtime passed to defineApiConfig. Undefined when the API was configured without a runtime. | |
Definition
(
args: {
context: {
currentUser: JWTPayload | null
identity: ResolvedIdentity | null
permissions: Permission[]
}
} & PermissionFields
) => boolean | Promise<boolean>Definition
(
args: {
context: {
currentUser: JWTPayload | null
identity: ResolvedIdentity | null
permissions: Permission[]
}
} & PermissionFields
) => boolean | Promise<boolean>Subset of GraphQL Yoga’s createYoga options, excluding schema and context which are managed internally.
Definition
Omit<
NonNullable<Parameters<typeof createYoga>[0]>,
"schema" | "context"
>Properties
| Name | Type |
|---|---|
| maxPagesRequired | number |
| hasNextRequired | boolean |
| hasPreviousRequired | boolean |
| currentPageRequired | number |
| nextPageRequired | number | null |
| previousPageRequired | number | null |
Type Parameters
| Parameter | Constraint | Default |
|---|---|---|
T | — | — |
Properties
| Name | Type |
|---|---|
| totalCountRequired | number |
| pageInfoRequired | PageInfoInterface |
| nodesRequired | T[] |
Properties
| Name | Type | ||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|
| ScalarsRequired | Object | ||||||||||
| |||||||||||