Browse documentation

Shared Modules Reference

.framework/functions/_shared/ is the library every Netlify function builds on — bundled per function, never deployed as an endpoint itself. .framework/functions/_shared/index.ts re-exports the common surface (createHandler, createPublicHandler, requireUserContext, requireSystemContextWithAudit, json, errorResponse, cors, the Principal/RequestContext/CoreContext/HandlerFunction/HandlerResult types). Import a sibling as from './_shared/<module>'.

Request handling

ModuleExportsImport when
middleware.tscreateHandler, createPublicHandler, json, error, cors, parseBody, requireUserContext, requireSystemContextWithAudit; RequestContext, CoreContext, HandlerFunction, HandlerResultevery function — wraps auth, tracing, envelope, and error mapping around your handler
principal.tsresolvePrincipal, SYSTEM_PRINCIPAL, ANONYMOUS_PRINCIPAL, getPrincipalDb, isSystemAdmin, humanHasRole, machineHasScope, resolveInternalPersonId, formatPrincipalForAuditreading ctx.principal, checking roles/scopes, internal invocations
db.tsadminDb (service-role, bypasses RLS), getUserDb(token) (RLS-scoped), joinsdirect table access — prefer ctx.db (already principal-scoped) inside handlers

Permissions & data shape

ModuleExportsImport when
permissions.tsPermissionEngine, resolveFirstSurfacePermissions, sanitizeRecordData, validateUpdatePermissions, canAccessRecord, isSystemAdmin, PermissionResultevaluating design_schema grants, stripping fields a principal can't read, validating writes
schema-utils.tsgenerateValidationSchema, sanitizeFieldData, formatFieldData, transformRecordData, ValidationSchemafield validation/sanitization against data_type; generating validation_schema
resolve-ids.tsresolveTypeId, resolveTypeIds, resolveTypeRecord, resolveAccountId, resolveLinkTypeId(s), resolveAgentId, resolvePromptConfigIdslug→uuid lookups for types, link types, accounts, agents, prompts

Automation & agents

ModuleExportsImport when
trigger-engine.tsfireCreateTriggers, fireUpdateTriggers, fireDeleteTriggers, checkAndFireTriggers, dispatchTriggerPipeline, EventTypefiring record-change triggers; dispatching a pipeline run (needs INTERNAL_INVOKE_SECRET)
pipeline-runner.tsrunPipeline, sweepStaleExecutions, ExecutionResult, StageResultexecuting a pipeline's stages inside a function/background context
agent-runner.tsrunAgent, runAgentStep, claimAgentEpisode, kickAgentEpisode, acquireEpisodeLease, resolveAgentConfig, executeToolAction, retrieveKnowledge, AgentConfig, ToolCall, ToolResultrunning an AI agent turn against a thread
message-sequence.tsinsertMessageSequencedinserting a message outside runAgent — allocates MAX(sequence)+1 and retries on the (thread_id, sequence) race
notify.tsresolveNotificationRecipientsresolving role:<slug> / self / UUID recipients to people.id

Observability & audit

ModuleExportsImport when
logging.tswithAdminLogging, logAdminDataOperation, resolveLogLevels, resolveAppUuid, LogLevelwrapping handlers with the instance log-level-aware logging pipeline
audit.tsemitAudit, emitLog, emitSpan, emitActivitywriting structured log/audit/span rows into public.logs
tracing.tsnewTrace, startSpan, endSpan, withSpan(Sync), traceDb, formatTraceParent/State, parseTraceParent/State, generateTraceId/SpanId, isSampledW3C trace-context propagation and span wrapping of DB calls
outcomes.tsemitOutcomerecording outcome audit rows

Security

ModuleExportsImport when
hash-api-key.tshashApiKey, verifyApiKey, omitSecretFieldsminting/verifying API keys (pbkdf2$iter$salt$hash, 100k sha256); stripping key material from responses
rate-limit.tscheckRateLimit, resolveRateLimitPolicies, RateLimitError, RateLimitPolicyenforcing config.rate_limits policies via the atomic rate_limit_hit RPC
security.tsisBlockedRequest, isBlockedIp, checkTypeSlugRateLimit, detectInjection, emitSecurityEvent, getAppSecurityConfig, checkRegistrationBlocklist, touchPersonGeo, INJECTION_PATTERNSblocklist checks, per-type-slug rate limits, prompt-injection screening
geo.tsgetClientGeo, ClientGeobest-effort client IP/geo from request headers

Integrations & webhooks

ModuleExportsImport when
resolve-credentials.tsresolveCredential, resolveCredentials, ResolvedCredentialresolving integrations.config.credentials (value literal or env_var lookup) server-side
webhook-registration.tsregisterWebhookHandler, deregisterWebhookHandler, isHandlerRegisteredself-registering a custom function as a webhook handler (webhook_handlers upsert)
webhook-registry.tslookupHandler, resolveHandler, loadHandler, listRegisteredHandlers, clearHandlerCacheresolving which registered handler receives an inbound event
retry-deliveries.tsretryPendingDeliveriessweeping due webhook_deliveries rows for retry

Knowledge & LLM

ModuleExportsImport when
kb.tskbIngest, kbPublish, kbReindex, kbRevoke, kbSearch, resolveKnowledgeScope, knowledgeRowAllowed, resolveSecurityLevel, matchItemType, KnowledgeScope, KnowledgeEnvelopeingesting/searching embeddings with scope + security-level enforcement
llm.tscallOpenAI, callOpenAIChat, callOpenAIEmbeddings, callEmbeddingApi, LlmContextthin wrappers over the openai outbound integration
funnel.tsemitSignal, accountDataFlag, SignalInputemitting typed funnel/signal events that can fire triggers
access.tshasInternalAudience, projectMessageForCustomer, INTERNAL_AUDIENCE_ROLES, CUSTOMER_STEP_TYPESdeciding whether a principal may read visibility: 'internal' rows and projecting customer-safe message shapes

Framework internals

ModulePurpose
app-manifest.tsloadManifest, mergeWithManifest, discoverManifests, clearManifestCache — manifest.json loading for app rows with config_source = 'manifest'
ast.tsextractIdentities — TypeScript compiler API for code-analysis pipelines
cil.tsstable-id generation, content hashing, file-tree helpers for the code-intelligence pipeline — not needed by custom apps
testing.tsmockEvent, mockPrincipal, makeTestContext, expectSuccessResponse, expectErrorResponse, setupTests — function-level test harness

Usage notes

  • ctx.db is already the right client for the request's principal — humans get an RLS-scoped client, machines get adminDb. Reach for adminDb directly only when you must deliberately bypass RLS (system writes, cross-account lookups like types/accounts resolution).
  • Never JSON.stringify(ctx.principal) — authContext.jwt rides on it; use formatPrincipalForAudit.
  • Circular-import hazards are real in this layer (middleware → security → rate-limit → funnel → trigger-engine → pipeline-runner → kb → llm → integration-outbound → admin-data → middleware); some modules import lazily on purpose — copy that pattern rather than adding a static edge.

Framework documentation — Verified November 20, 2026 · source revision a812c8e.

Was this page helpful? Ask a question · Report a documentation problem