Documentation
¶
Overview ¶
Package piko provides the public API for the Piko web framework.
This is the primary entry point for applications built with Piko. It exposes a unified facade over the framework's internal subsystems, including server lifecycle management, server actions, component rendering, collections, search, health monitoring, internationalisation, linguistics, and testing.
Getting started ¶
Create a server with functional options and call Run. Every configuration knob is a With* option; piko reads no configuration files and no environment variables (apart from PIKO_LOG_LEVEL, which seeds the bootstrap logger before options are applied).
server := piko.New(
piko.WithPort(8080),
piko.WithLogLevel("info"),
)
if err := server.Run(piko.RunModeDev); err != nil {
log.Fatal(err)
}
Server actions ¶
Actions handle client-initiated mutations. Actions embed ActionMetadata and define a Call method with any signature:
type DeleteAction struct {
piko.ActionMetadata
}
func (a DeleteAction) Call(id int64) (Response, error) {
return Response{Success: true}, nil
}
Structured error types (ValidationError, NotFoundError, ForbiddenError, etc.) are automatically mapped to HTTP status codes by the action handler.
Collections and search ¶
Use GetData, GetSections, and GetSectionsTree to extract typed data and table-of-contents headings from collection content. SearchCollection provides fuzzy full-text search with field weighting, and QuickSearch offers a convenience wrapper with sensible defaults.
Lifecycle and health ¶
Register external components for managed startup/shutdown with SSRServer.RegisterLifecycle. Components that also implement LifecycleHealthProbe are automatically added to the health monitoring system. Custom health probes can also be registered via WithCustomHealthProbe.
Testing ¶
The package provides a testing framework for components and actions. Use NewComponentTester to render and assert against a component's AST, and NewActionTester to invoke and verify server actions. NewTestRequest builds RequestData with a fluent API for injecting context, query parameters, and form data.
Thread safety ¶
SSRServer methods must be called from a single goroutine during setup. Once SSRServer.Run is called, the underlying HTTP server and all registered services are safe for concurrent use. Collection query functions (GetData, SearchCollection, GetAllCollectionItems) are safe to call concurrently.
Index ¶
- Constants
- Variables
- func AddAnalyticsProperty(ctx context.Context, key, value string)
- func GenerateLocaleHead(r *RequestData, i18nConfig I18nConfig, pagePath string, ...) (locale string, canonicalURL string, alternateLinks []map[string]string)
- func GetAllCollectionItems(collectionName string) ([]map[string]any, error)
- func GetData[T any](r *RequestData) T
- func GetDataLink(tType reflect.Type, r *RequestData) reflect.Value
- func InitialiseForTesting() *bootstrap.Container
- func IsAuthenticated(r *RequestData) bool
- func IsDevelopmentMode(r *RequestData) bool
- func QuickSearch[T any](r *RequestData, collectionName string, query string) ([]T, error)
- func QuickSearchLink(tType reflect.Type, r *RequestData, collectionName string, query string) (reflect.Value, error)
- func RegisterActions(entries map[string]ActionHandlerEntry)
- func RunHeadless(opts ...Option) (*bootstrap.Container, error)
- func SearchCollectionLink(tType reflect.Type, r *RequestData, collectionName string, query string, ...) (reflect.Value, error)
- func SetAnalyticsEventName(ctx context.Context, name string)
- func SetAnalyticsRevenue(ctx context.Context, revenue maths.Money)
- func TrackAnalyticsEvent(ctx context.Context, event *AnalyticsEvent)
- type ASTQueryResult
- type AWSKMSConfig
- type ActionError
- type ActionHandlerEntry
- type ActionMetadata
- type ActionResult
- type ActionResultView
- type ActionTester
- type AnalyticsCollector
- type AnalyticsConfig
- type AnalyticsEvent
- type AnalyticsEventType
- type AssetTransformationStep
- type AssetsConfig
- type AuthContext
- type AuthGuardConfig
- type AuthPolicy
- type AuthProvider
- type BadRequestError
- type BuildASTFunc
- type CSPBuilder
- type CSSResetOption
- type CacheConfig
- type CachePolicy
- type Cacheable
- type CaptchaConfig
- type CaptchaOptions
- type CaptchaProtected
- type ComponentDefinition
- type ComponentOption
- type ComponentTester
- type ConfigResolver
- type ConflictError
- type Container
- type CookieOption
- type CookieSecurityConfig
- type Error
- type ErrorPageContext
- type FaviconDefinition
- type FileUpload
- type Filter
- type FilterGroup
- type FilterOperator
- type FontDefinition
- type ForbiddenError
- type FrontendModule
- type GCPKMSConfig
- type GeneratorProfilingOption
- func WithGeneratorProfilingBlockRate(rate int) GeneratorProfilingOption
- func WithGeneratorProfilingMemProfileRate(rate int) GeneratorProfilingOption
- func WithGeneratorProfilingMutexFraction(fraction int) GeneratorProfilingOption
- func WithGeneratorProfilingOutputDir(directory string) GeneratorProfilingOption
- type GenericPageError
- type HTTPMethod
- type HealthCheckType
- type HealthProbe
- type HealthState
- type HealthStatus
- type HealthTLSOption
- type HelperCall
- type I18nConfig
- type ImageAssetsConfig
- type LifecycleComponent
- type LifecycleHealthProbe
- type LifecycleStartTimeout
- type LifecycleWithHealth
- type LoggerConfig
- type MetaTag
- type Metadata
- type MetricsExporter
- type ModalsConfig
- type MonitoringOption
- func WithMonitoringAddress(addr string) MonitoringOption
- func WithMonitoringAutoNextPort(enabled bool) MonitoringOption
- func WithMonitoringBindAddress(addr string) MonitoringOption
- func WithMonitoringOtelFactories(factories monitoring_domain.ServiceFactories) MonitoringOption
- func WithMonitoringProfiling() MonitoringOption
- func WithMonitoringTLS(opts ...MonitoringTLSOption) MonitoringOption
- func WithMonitoringTransport(factory monitoring_domain.TransportFactory) MonitoringOption
- func WithMonitoringWatchdog(opts ...WatchdogOption) MonitoringOption
- func WithWatchdogNotifier(notifier WatchdogNotifier) MonitoringOption
- func WithWatchdogProfileUploader(uploader WatchdogProfileUploader) MonitoringOption
- type MonitoringTLSOption
- func WithMonitoringTLSCertFile(path string) MonitoringTLSOption
- func WithMonitoringTLSClientAuth(authType string) MonitoringTLSOption
- func WithMonitoringTLSClientCA(path string) MonitoringTLSOption
- func WithMonitoringTLSHotReload(enabled bool) MonitoringTLSOption
- func WithMonitoringTLSKeyFile(path string) MonitoringTLSOption
- func WithMonitoringTLSMinVersion(version string) MonitoringTLSOption
- type NavigationConfig
- type NavigationGroups
- type NavigationNode
- type NavigationTree
- type NoProps
- type NoResponse
- type NotFoundError
- type OGTag
- type Option
- func WithAPICSP() Option
- func WithAWSKMS(k AWSKMSConfig) Option
- func WithActionMaxBodyBytes(n int64) Option
- func WithActionResponseCacheMaxBytes(maxBytes uint64) Option
- func WithActionServePath(path string) Option
- func WithArtefactServePath(path string) Option
- func WithAssetsSourceDir(dir string) Option
- func WithAuthGuard(authGuardConfig AuthGuardConfig) Option
- func WithAuthProvider(provider AuthProvider) Option
- func WithAutoMemoryLimit(provider func() (int64, error)) Option
- func WithAutoNextPort(enabled bool) Option
- func WithBackendAnalytics(collectors ...AnalyticsCollector) Option
- func WithBaseDir(dir string) Option
- func WithBaseServePath(path string) Option
- func WithCSP(configure func(*CSPBuilder)) Option
- func WithCSPString(policy string) Option
- func WithCSRFSecFetchSiteEnforcement(enabled bool) Option
- func WithCSRFSecret(key []byte) Option
- func WithCSRFTokenMaxAge(d time.Duration) Option
- func WithCSSReset(opts ...CSSResetOption) Option
- func WithCSSTreeShaking() Option
- func WithCSSTreeShakingSafelist(classes ...string) Option
- func WithCacheProvider(name string, provider cache_domain.Provider) Option
- func WithCacheService(service cache_domain.Service) Option
- func WithCapabilityService(service capabilities.Service) Option
- func WithCaptcha(opts CaptchaOptions) Option
- func WithCaptchaProvider(name string, provider captcha_domain.CaptchaProvider) Option
- func WithCloudflareEnabled(enabled bool) Option
- func WithComponentsSourceDir(dir string) Option
- func WithConfigResolvers(resolvers ...ConfigResolver) Option
- func WithCookieSecurity(cookies CookieSecurityConfig) Option
- func WithCrashOutput(path string) Option
- func WithCrashTraceback(level string) Option
- func WithCrossOriginResourcePolicy(policy string) Option
- func WithCryptoProvider(name string, provider crypto_domain.EncryptionProvider) Option
- func WithCryptoService(service crypto_domain.CryptoServicePort) Option
- func WithCustomFrontendModule(name string, content []byte, moduleConfig ...map[string]any) Option
- func WithCustomHealthProbe(probe HealthProbe) Option
- func WithD1APIToken(token string) Option
- func WithD1AccountID(id string) Option
- func WithD1DatabaseID(id string) Option
- func WithDataKeyCacheMaxSize(n int) Option
- func WithDataKeyCacheTTL(d time.Duration) Option
- func WithDatabase(name string, registration *bootstrap.DatabaseRegistration) Option
- func WithDatabaseDriver(driver string) Option
- func WithDefaultCacheProvider(name string) Option
- func WithDefaultCaptchaProvider(name string) Option
- func WithDefaultCryptoProvider(name string) Option
- func WithDefaultEmailProvider(name string) Option
- func WithDefaultEmbeddingProvider(name string) Option
- func WithDefaultImageProvider(name string) Option
- func WithDefaultLLMProvider(name string) Option
- func WithDefaultMaxSSEDuration(d time.Duration) Option
- func WithDefaultNotificationProvider(name string) Option
- func WithDefaultServeMode(mode string) Option
- func WithDefaultStorageProvider(name string) Option
- func WithDefaultVideoProvider(name string) Option
- func WithDeprecatedKeyIDs(ids ...string) Option
- func WithDevHotreload() Option
- func WithDevWidget() Option
- func WithDiagnosticDirectory(directory string) Option
- func WithDistServePath(path string) Option
- func WithE2EMode(enabled bool) Option
- func WithE2ESourceDir(dir string) Option
- func WithEmailDeadLetterQueue(dlq email_domain.DeadLetterPort) Option
- func WithEmailDispatcher(dispatcherConfig email_dto.DispatcherConfig) Option
- func WithEmailProvider(name string, provider email_domain.EmailProviderPort) Option
- func WithEmailService(service email_domain.Service) Option
- func WithEmailsSourceDir(dir string) Option
- func WithEmbeddingProvider(name string, provider llm_domain.EmbeddingProviderPort) Option
- func WithEncryptionKey(key string) Option
- func WithEventBus(bus orchestrator_domain.EventBus) Option
- func WithEventsProvider(provider events_domain.Provider) Option
- func WithExperimentalCommentStripping(enabled bool) Option
- func WithExperimentalDwarfLineDirectives(enabled bool) Option
- func WithExperimentalPrerendering(enabled bool) Option
- func WithForceHTTPS(enabled bool) Option
- func WithFrontendModule(module FrontendModule, moduleConfig ...any) Option
- func WithGCPKMS(k GCPKMSConfig) Option
- func WithGeneratorProfiling(opts ...GeneratorProfilingOption) Option
- func WithHealthAutoNextPort(enabled bool) Option
- func WithHealthBindAddress(addr string) Option
- func WithHealthCheckTimeout(d time.Duration) Option
- func WithHealthEnabled(enabled bool) Option
- func WithHealthLivePath(path string) Option
- func WithHealthMetricsEnabled(enabled bool) Option
- func WithHealthMetricsPath(path string) Option
- func WithHealthProbePort(port int) Option
- func WithHealthReadyPath(path string) Option
- func WithHealthTLS(opts ...HealthTLSOption) Option
- func WithHighlighter(h highlight_domain.Highlighter) Option
- func WithHybridCacheMaxBytes(maxBytes uint64) Option
- func WithHybridCacheWriteExpiration(expiration time.Duration) Option
- func WithI18nDefaultLocale(locale string) Option
- func WithI18nService(service i18n_domain.Service) Option
- func WithI18nSourceDir(dir string) Option
- func WithIAmACatPerson() Option
- func WithImage(imageConfig *image_domain.ImageConfig) Option
- func WithImageProvider(name string, provider image_domain.TransformerPort) Option
- func WithImageService(service image_domain.Service) Option
- func WithJSONProvider(provider json.Provider) Option
- func WithJSONTypeInspectorCache() Option
- func WithLLMProvider(name string, provider llm_domain.LLMProviderPort) Option
- func WithLLMService(service llm_domain.Service) Option
- func WithLibServePath(path string) Option
- func WithLogLevel(level string) Option
- func WithLogger(cfg logger_dto.Config) Option
- func WithMarkdownParser(parser markdown_domain.MarkdownParserPort) Option
- func WithMaxConcurrentRequests(n int) Option
- func WithMaxMultipartFormBytes(n int64) Option
- func WithMemoryRegistryCache() Option
- func WithMetricsExporter(exporter MetricsExporter) Option
- func WithMonitoring(opts ...MonitoringOption) Option
- func WithNotificationProvider(name string, provider notification_domain.NotificationProviderPort) Option
- func WithOTLP(o OtlpConfig) Option
- func WithOTLPEnabled(enabled bool) Option
- func WithOTLPEndpoint(endpoint string) Option
- func WithOTLPHeaders(headers map[string]string) Option
- func WithOTLPInsecureTLS(insecure bool) Option
- func WithOTLPProtocol(protocol string) Option
- func WithOTLPTraceSampleRate(rate float64) Option
- func WithOrchestratorService(service orchestrator_domain.OrchestratorService) Option
- func WithPMLTransformer(transformer pml_domain.Transformer) Option
- func WithPagesSourceDir(dir string) Option
- func WithPartialServePath(path string) Option
- func WithPartialsSourceDir(dir string) Option
- func WithPdfsSourceDir(dir string) Option
- func WithPikoDefaultCSP() Option
- func WithPort(port int) Option
- func WithPostgresMaxConns(n int32) Option
- func WithPostgresMinConns(n int32) Option
- func WithPostgresURL(url string) Option
- func WithProfiling(opts ...ProfilingOption) Option
- func WithPublicDomain(domain string) Option
- func WithRateLimit(rl RateLimitConfig) Option
- func WithRateLimitEnabled(enabled bool) Option
- func WithRegistryMetadataCacheConfig(registryCacheConfig RegistryMetadataCacheConfig) Option
- func WithRegistryService(service registry_domain.RegistryService) Option
- func WithRelaxedCSP() Option
- func WithReporting(r ReportingConfig) Option
- func WithReportingEndpoints(endpoints ...ReportingEndpoint) Option
- func WithRequestTimeout(d time.Duration) Option
- func WithSRI(enabled bool) Option
- func WithSandbox(s SandboxConfig) Option
- func WithSecurityHeaders(headers SecurityHeadersConfig) Option
- func WithShutdownDrainDelay(delay time.Duration) Option
- func WithSpamDetector(name string, detector spamdetect_domain.Detector) Option
- func WithSpamFeedbackStore(store spamdetect_domain.FeedbackStore) Option
- func WithStartupBanner(enabled bool) Option
- func WithStorageDispatcher(storageDispatcherConfig storage_domain.DispatcherConfig) Option
- func WithStoragePresign(p StoragePresignConfig) Option
- func WithStoragePresignBaseURL(baseURL string) Option
- func WithStoragePresignDefaultExpiry(d time.Duration) Option
- func WithStoragePresignDefaultMaxSize(size int64) Option
- func WithStoragePresignMaxExpiry(d time.Duration) Option
- func WithStoragePresignMaxMaxSize(size int64) Option
- func WithStoragePresignRateLimit(rpm int) Option
- func WithStoragePresignSecret(secret string) Option
- func WithStorageProvider(name string, provider storage_domain.StorageProviderPort) Option
- func WithStoragePublicBaseURL(baseURL string) Option
- func WithStorageService(service storage_domain.Service) Option
- func WithStrictCSP() Option
- func WithSystemStorageProvider(provider storage_domain.StorageProviderPort) Option
- func WithTLS(opts ...TLSOption) Option
- func WithTrustedProxies(cidrs ...string) Option
- func WithValidator(v bootstrap.StructValidator) Option
- func WithVideoProvider(name string, provider video_domain.TranscoderPort) Option
- func WithVideoService(service video_domain.Service) Option
- func WithWatchMode(enabled bool) Option
- type OtlpConfig
- type OtlpTLSConfig
- type PaginationOptions
- type PreviewScenario
- type ProfilingOption
- func WithProfilingBindAddress(addr string) ProfilingOption
- func WithProfilingBlockRate(rate int) ProfilingOption
- func WithProfilingMemProfileRate(rate int) ProfilingOption
- func WithProfilingMutexFraction(fraction int) ProfilingOption
- func WithProfilingPort(port int) ProfilingOption
- func WithProfilingRollingTrace() ProfilingOption
- func WithProfilingRollingTraceMaxBytes(maxBytes uint64) ProfilingOption
- func WithProfilingRollingTraceMinAge(minAge time.Duration) ProfilingOption
- type PublicConfig
- type RateLimit
- type RateLimitConfig
- type RateLimitKeyFunc
- type RateLimitTierConfig
- type RateLimitable
- type RawBody
- type RegistryMetadataCacheConfig
- type ReportingConfig
- type ReportingEndpoint
- type RequestBuilder
- type RequestData
- type RequestMetadata
- type ResourceLimitable
- type ResourceLimits
- type ResponseWriter
- type RobotsConfig
- type RobotsRuleGroup
- type SEOConfig
- type SSECapable
- type SSEStream
- type SSRServer
- func (*SSRServer) Close()
- func (s *SSRServer) Configure(publicConfig PublicConfig)
- func (s *SSRServer) Generate(ctx context.Context, runMode string) error
- func (s *SSRServer) GetHandler() http.Handler
- func (s *SSRServer) RegisterLifecycle(component LifecycleComponent)
- func (s *SSRServer) Run(runMode string) error
- func (s *SSRServer) Setup() error
- func (s *SSRServer) Stop() error
- func (s *SSRServer) WithInterpreterProvider(provider templater_domain.InterpreterProviderPort)
- func (s *SSRServer) WithSymbols(symbols templater_domain.SymbolExports)
- type SandboxConfig
- type SearchField
- type SearchOption
- func WithCaseSensitive(sensitive bool) SearchOption
- func WithFuzzyThreshold(threshold float64) SearchOption
- func WithMinScore(score float64) SearchOption
- func WithSearchFields(fields ...SearchField) SearchOption
- func WithSearchLimit(limit int) SearchOption
- func WithSearchMode(mode string) SearchOption
- func WithSearchOffset(offset int) SearchOption
- type SearchResult
- type Secret
- type SecretHandle
- type SecretManager
- type SecretStats
- type Section
- type SectionNode
- type SectionTreeOption
- type SecurityHeadersConfig
- type Session
- type SitemapChunkConfig
- type SitemapConfig
- type SitemapEntryDefaults
- type SortOption
- type SortOrder
- type SpamConfig
- type SpamConfigurable
- type SpamProtected
- type SpamSchema
- type SpamSignal
- type StoragePresignConfig
- type SymbolExports
- type TLSOption
- func WithTLSCertFile(path string) TLSOption
- func WithTLSClientAuth(authType string) TLSOption
- func WithTLSClientCA(path string) TLSOption
- func WithTLSHotReload(enabled bool) TLSOption
- func WithTLSKeyFile(path string) TLSOption
- func WithTLSMinVersion(version string) TLSOption
- func WithTLSRedirectHTTP(port int) TLSOption
- type TeapotError
- type TestView
- type ToastsConfig
- type Translation
- type Transport
- type UnauthorisedError
- type ValidationError
- type VideoAssetsConfig
- type WatchdogEvent
- type WatchdogEventPriority
- type WatchdogEventType
- type WatchdogNotifier
- type WatchdogOption
- func WithWatchdogCheckInterval(interval time.Duration) WatchdogOption
- func WithWatchdogContentionDiagnosticAutoFire() WatchdogOption
- func WithWatchdogContentionDiagnosticBlockProfileRate(rate int) WatchdogOption
- func WithWatchdogContentionDiagnosticMutexProfileFraction(fraction int) WatchdogOption
- func WithWatchdogContentionDiagnosticWindow(window time.Duration) WatchdogOption
- func WithWatchdogContinuousProfiling() WatchdogOption
- func WithWatchdogContinuousProfilingInterval(interval time.Duration) WatchdogOption
- func WithWatchdogContinuousProfilingNotify() WatchdogOption
- func WithWatchdogContinuousProfilingRetention(count int) WatchdogOption
- func WithWatchdogContinuousProfilingTypes(types ...string) WatchdogOption
- func WithWatchdogCooldown(duration time.Duration) WatchdogOption
- func WithWatchdogDeltaProfiling() WatchdogOption
- func WithWatchdogFDPressureThresholdPercent(percent float64) WatchdogOption
- func WithWatchdogGoroutineThreshold(threshold int) WatchdogOption
- func WithWatchdogHeapThresholdBytes(thresholdBytes uint64) WatchdogOption
- func WithWatchdogHeapThresholdPercent(percent float64) WatchdogOption
- func WithWatchdogIncludeGoroutineStacks(enabled bool) WatchdogOption
- func WithWatchdogMaxProfilesPerType(count int) WatchdogOption
- func WithWatchdogMaxWarningsPerWindow(count int) WatchdogOption
- func WithWatchdogProfileDirectory(directory string) WatchdogOption
- func WithWatchdogRSSThresholdPercent(percent float64) WatchdogOption
- func WithWatchdogSchedulerLatencyP99Threshold(threshold time.Duration) WatchdogOption
- type WatchdogProfileUploader
- type WebsiteConfig
Constants ¶
const ( // TransportHTTP is the HTTP transport protocol identifier. TransportHTTP = daemon_domain.TransportHTTP // TransportSSE is the Server-Sent Events transport type. TransportSSE = daemon_domain.TransportSSE // MethodGet is the HTTP GET method identifier. MethodGet = daemon_domain.MethodGet // MethodPost is the HTTP POST method constant. MethodPost = daemon_domain.MethodPost // MethodPut is the HTTP PUT method for updating resources. MethodPut = daemon_domain.MethodPut // MethodDelete is the HTTP DELETE method identifier. MethodDelete = daemon_domain.MethodDelete // MethodPatch is the HTTP PATCH method for partial resource updates. MethodPatch = daemon_domain.MethodPatch // MethodHead is the HTTP HEAD method identifier. MethodHead = daemon_domain.MethodHead // MethodOptions is an alias for daemon_domain.MethodOptions. MethodOptions = daemon_domain.MethodOptions )
const ( // EventPageView is fired automatically for each page request. EventPageView = analytics_dto.EventPageView // EventAction is fired when a server action executes. EventAction = analytics_dto.EventAction // EventCustom is a user-defined event fired manually from action // handlers. EventCustom = analytics_dto.EventCustom )
const ( // FilterOpEquals is the equality comparison operator for filters. FilterOpEquals = runtime.FilterOpEquals // FilterOpNotEquals is the filter operation for inequality comparisons. FilterOpNotEquals = runtime.FilterOpNotEquals // FilterOpGreaterThan is the greater than comparison operator for filters. FilterOpGreaterThan = runtime.FilterOpGreaterThan // FilterOpGreaterEqual is the greater-than-or-equal filter operation. FilterOpGreaterEqual = runtime.FilterOpGreaterEqual // FilterOpLessThan is the filter operation for less than comparisons. FilterOpLessThan = runtime.FilterOpLessThan // FilterOpLessEqual is the filter operator for less than or equal comparison. FilterOpLessEqual = runtime.FilterOpLessEqual // FilterOpContains is the filter operation for substring matching. FilterOpContains = runtime.FilterOpContains // FilterOpStartsWith is the filter operation for prefix matching. FilterOpStartsWith = runtime.FilterOpStartsWith // FilterOpEndsWith is the filter operation for suffix matching. FilterOpEndsWith = runtime.FilterOpEndsWith // FilterOpIn is the filter operator for membership testing. FilterOpIn = runtime.FilterOpIn // FilterOpNotIn is the filter operation for excluding matching values. FilterOpNotIn = runtime.FilterOpNotIn // FilterOpExists is the filter operation that checks for field existence. FilterOpExists = runtime.FilterOpExists // FilterOpFuzzyMatch is a filter operation for approximate string matching. FilterOpFuzzyMatch = runtime.FilterOpFuzzyMatch // SortAsc is the ascending sort order. SortAsc = runtime.SortAsc // SortDesc indicates descending sort order. SortDesc = runtime.SortDesc )
const ( // HealthStateHealthy indicates the component is working normally. HealthStateHealthy HealthState = healthprobe_dto.StateHealthy // HealthStateDegraded indicates the component is working but with reduced // performance or limited features. HealthStateDegraded HealthState = healthprobe_dto.StateDegraded // HealthStateUnhealthy indicates the component is not working. HealthStateUnhealthy HealthState = healthprobe_dto.StateUnhealthy // HealthCheckLiveness checks if the application is running and not stuck. // If this check fails, the application is usually restarted. HealthCheckLiveness HealthCheckType = healthprobe_dto.CheckTypeLiveness // HealthCheckReadiness determines if the application is ready to serve // traffic. Failing this check typically results in traffic being withheld from // the application. HealthCheckReadiness HealthCheckType = healthprobe_dto.CheckTypeReadiness )
const ( // WatchdogPriorityNormal is informational; safe to ignore in alerting. WatchdogPriorityNormal = monitoring_domain.WatchdogPriorityNormal // WatchdogPriorityHigh warrants prompt investigation. WatchdogPriorityHigh = monitoring_domain.WatchdogPriorityHigh // WatchdogPriorityCritical indicates imminent system instability. WatchdogPriorityCritical = monitoring_domain.WatchdogPriorityCritical // ModuleAnalytics provides Google Analytics (GA4) support through hooks. // It tracks page views, navigation, server actions, modal opens, and errors. ModuleAnalytics = daemon_frontend.ModuleAnalytics // ModuleModals provides helper functions for modal dialogues. It exports // showModal, closeModal, updateModal, and reloadPartial. ModuleModals = daemon_frontend.ModuleModals // ModuleToasts provides toast notification helpers. It exports showToast which // takes a message, variant, and duration. ModuleToasts = daemon_frontend.ModuleToasts // CORPSameOrigin restricts resources to same-origin requests only. // This is the default and most secure option. CORPSameOrigin = "same-origin" // CORPSameSite allows resources to be loaded by same-site requests. CORPSameSite = "same-site" // CORPCrossOrigin allows resources to be loaded by any origin. // Use this for headless CMS scenarios where resources are served to // frontends on different origins. CORPCrossOrigin = "cross-origin" )
const ( // SpamSignalGibberish tags a field for gibberish detection. SpamSignalGibberish = spamdetect_dto.SignalGibberish // SpamSignalLinkDensity tags a field for link density analysis. SpamSignalLinkDensity = spamdetect_dto.SignalLinkDensity // SpamSignalBlocklist tags a field for blocklist matching. SpamSignalBlocklist = spamdetect_dto.SignalBlocklist )
const ( // RunModeDev is the development mode with hot reloading. RunModeDev = "dev" // RunModeDevInterpreted is the run mode for development with interpreted code. RunModeDevInterpreted = "dev-i" // RunModeProd is the production run mode for the SSR server. RunModeProd = "prod" // GenerateModeManifest is the generation mode for manifest output. GenerateModeManifest = bootstrap.GenerateModeManifest // GenerateModeAll generates all build outputs including SQL, manifest, and assets. GenerateModeAll = bootstrap.GenerateModeAll // GenerateModeSQL runs the querier code generator against registered databases. GenerateModeSQL = bootstrap.GenerateModeSQL // GenerateModeAssets runs annotation to discover template-derived asset // requirements, then builds static assets. Code emission is skipped. GenerateModeAssets = bootstrap.GenerateModeAssets // LevelDebug is the debug log level for detailed diagnostic information. LevelDebug = slog.LevelDebug // LevelInfo is the info logging level from the standard slog package. LevelInfo = slog.LevelInfo // LevelWarn is the warning log level for conditions that may need attention. LevelWarn = slog.LevelWarn // LevelError is the error severity level for log messages. LevelError = slog.LevelError )
Variables ¶
var ( // RateLimitByIP is a rate limiting strategy that limits requests by IP // address. RateLimitByIP = daemon_domain.RateLimitByIP // RateLimitByUser is a rate limiting strategy that tracks limits per user. RateLimitByUser = daemon_domain.RateLimitByUser // RateLimitBySession is the rate limiting strategy that tracks requests per // session. RateLimitBySession = daemon_domain.RateLimitBySession // NewFileUpload creates a FileUpload from a multipart.FileHeader. // This is called by generated wrapper code; users typically don't need this. NewFileUpload = daemon_dto.NewFileUpload // NewRawBody creates a RawBody from raw data. // This is called by the action handler; users typically don't need this. NewRawBody = daemon_dto.NewRawBody // NewValidationError creates a validation error with // field-specific messages. // // Example: // return nil, piko.NewValidationError(map[string]string{ // "email": "invalid email format", // "age": "must be at least 18", // }) NewValidationError = daemon_dto.NewValidationError // ValidationField creates a single-field validation error. This is a helper // for the common case of one field failing validation. // // Example: // return nil, piko.ValidationField("email", "invalid email format") ValidationField = daemon_dto.ValidationField // NotFound creates a not found error for a resource. // // Example: // return nil, piko.NotFound("user", userID) NotFound = daemon_dto.NotFound // NotFoundResource creates a not found error without a specific ID. // Use this when the resource type is known but there's no specific identifier. // // Example: // return nil, piko.NotFoundResource("configuration") NotFoundResource = daemon_dto.NotFoundResource // Conflict creates a conflict error with the default CONFLICT code. // // Example: // return nil, piko.Conflict("email already registered") Conflict = daemon_dto.Conflict // ConflictWithCode creates a conflict error with a custom error code. Use this // when the client needs to discriminate between different conflict types. // // Example: // return nil, piko.ConflictWithCode("email already registered", "EMAIL_EXISTS") ConflictWithCode = daemon_dto.ConflictWithCode // Forbidden creates a forbidden error. // // Example: // return nil, piko.Forbidden("you do not have permission to delete this resource") Forbidden = daemon_dto.Forbidden // // Example: // return nil, piko.Unauthorised("session expired") Unauthorised = daemon_dto.Unauthorised // BadRequest creates a bad request error. // // Example: // return nil, piko.BadRequest("missing required header: X-Request-ID") BadRequest = daemon_dto.BadRequest // PageError creates a generic page error with an arbitrary HTTP status // code. Use this when none of the specific error helpers match. // // Example: // return Response{}, piko.Metadata{}, piko.PageError(429, "too many requests") PageError = daemon_dto.PageError // Teapot creates an HTTP 418 I'm a Teapot error. Short and stout. // // Example: // return Response{}, piko.Metadata{}, // piko.Teapot("this server is a teapot, not a coffee machine") Teapot = daemon_dto.Teapot // SessionCookie creates a secure session cookie with sensible defaults. // // The cookie is set up with: // - HttpOnly: true (stops JavaScript access, protects against XSS) // - Secure: true (HTTPS only - use SessionCookieInsecure for local work) // - SameSite: Lax (protects against CSRF while allowing normal browsing) // - Path: "/" (works for the whole site) // // Example usage in a login action: // return piko.ActionResponse{ // Status: 200, // Message: "Login successful", // Cookies: []*http.Cookie{ // piko.SessionCookie("pp_session", session.ID.String(), session.ExpiresAt), // }, // } SessionCookie = daemon_dto.SessionCookie // SessionCookieInsecure is a session cookie option that allows HTTP // connections. Use this only for local development where HTTPS is not // available. // // Warning: Do not use in production. Cookies will be sent as plain text. SessionCookieInsecure = daemon_dto.SessionCookieInsecure // ClearCookie creates a cookie that instructs the browser to delete an // existing cookie. // // Example usage in a logout action: // return piko.ActionResponse{ // Status: 200, // Message: "Logged out", // Cookies: []*http.Cookie{ // piko.ClearCookie("pp_session"), // }, // } ClearCookie = daemon_dto.ClearCookie // ClearCookieInsecure creates a cookie deletion instruction that works over // HTTP. Use this only for local development where HTTPS is not available. ClearCookieInsecure = daemon_dto.ClearCookieInsecure // SmartSessionCookie creates a session cookie that automatically sets // the Secure flag based on the runtime environment. In production // Secure is true; in development Secure is false. SmartSessionCookie = daemon_dto.SmartSessionCookie // SmartClearCookie creates a clear-cookie that automatically adapts // the Secure flag to match the runtime environment. SmartClearCookie = daemon_dto.SmartClearCookie // Cookie is a helper that creates a cookie with custom settings. // Use this when you need more control than SessionCookie gives. // // Example: // return piko.ActionResponse{ // Status: 200, // Cookies: []*http.Cookie{ // piko.Cookie("preferences", prefs, time.Hour*24*365, // piko.WithPath("/settings"), // piko.WithSameSiteStrict(), // ), // }, // } Cookie = daemon_dto.Cookie // WithPath sets the path attribute for a cookie. WithPath = daemon_dto.WithPath // WithDomain sets the cookie domain. WithDomain = daemon_dto.WithDomain // WithInsecure allows the cookie to be sent over HTTP. // WARNING: Only use for local development. WithInsecure = daemon_dto.WithInsecure // WithJavaScriptAccess allows JavaScript to access the cookie (removes // HttpOnly). WARNING: Only use if the cookie does not contain sensitive data. WithJavaScriptAccess = daemon_dto.WithJavaScriptAccess // WithSameSiteStrict sets the cookie to SameSite=Strict mode. This gives the // strongest CSRF protection but may stop some normal website features from // working correctly. WithSameSiteStrict = daemon_dto.WithSameSiteStrict // WithSameSiteNone sets the cookie to SameSite=None mode, permitting // cross-site requests but requiring Secure to be true. WithSameSiteNone = daemon_dto.WithSameSiteNone )
var ( // NewError wraps a cause error with a user-safe message. The cause's // Error() string is used for internal logging, while safeMessage is // the string shown to users in production. // // The returned error implements Unwrap(), so errors.Is and errors.As // continue to work through the chain. // // Example: // // return piko.NewError("something went wrong", err) NewError = safeerror.NewError // Errorf creates an error with a user-safe message and a formatted // internal cause (using fmt.Errorf semantics for the internal part). // // Example: // // return piko.Errorf("could not process order", // "loading order %s from database: %w", orderID, err) Errorf = safeerror.Errorf )
var ( // CSPSelf allows resources from the same origin (scheme, host, and port). CSPSelf = security_domain.Self // CSPNone disallows all resources for the directive. CSPNone = security_domain.None // CSPUnsafeInline allows inline scripts and styles. // Warning: This significantly reduces CSP protection against XSS. CSPUnsafeInline = security_domain.UnsafeInline // CSPUnsafeEval allows use of eval() and similar dynamic code execution. // Warning: This significantly reduces CSP protection against XSS. CSPUnsafeEval = security_domain.UnsafeEval // CSPUnsafeHashes allows specific inline event handlers based on their hash. CSPUnsafeHashes = security_domain.UnsafeHashes // CSPStrictDynamic allows scripts loaded by trusted scripts to execute. // When present, 'self' and URL-based allowlists are ignored for script-src. CSPStrictDynamic = security_domain.StrictDynamic // CSPReportSample tells the browser to include a sample of the code that // broke the rules in violation reports. CSPReportSample = security_domain.ReportSample // CSPWasmUnsafeEval permits WebAssembly code to run. CSPWasmUnsafeEval = security_domain.WasmUnsafeEval // CSPData allows data: URIs (e.g., inline images, fonts). CSPData = security_domain.Data // CSPBlob allows blob: URIs such as URL.createObjectURL results. CSPBlob = security_domain.Blob // CSPHTTPS allows any resource loaded over HTTPS. CSPHTTPS = security_domain.HTTPS // CSPHTTP allows any resource loaded over HTTP. // Warning: Using HTTP reduces security; prefer HTTPS. CSPHTTP = security_domain.HTTP // CSPRequestToken is a placeholder for dynamic per-request tokens. // // When used, the security middleware generates a unique cryptographic token // for each request and replaces this placeholder in the CSP header. Use // CSPTokenAttr in templates to add the token attribute to inline scripts // and styles. CSPRequestToken = security_domain.RequestTokenPlaceholder // CSPHost creates a source from a host specification such as // "cdn.example.com", "*.example.com", or "https://cdn.example.com". CSPHost = security_domain.Host // CSPScheme creates a source from a URL scheme. // The scheme should include the trailing colon (e.g., "wss:"). CSPScheme = security_domain.Scheme // CSPSHA256 creates a source from a base64-encoded SHA-256 hash. Use this for // allowing specific inline scripts or styles by their content hash. CSPSHA256 = security_domain.SHA256 // CSPSHA384 creates a source from a base64-encoded SHA-384 hash. CSPSHA384 = security_domain.SHA384 // CSPSHA512 creates a source from a base64-encoded SHA-512 hash. CSPSHA512 = security_domain.SHA512 // CSPStaticToken creates a source from a specific token value. // For dynamic per-request tokens, use CSPRequestToken instead. CSPStaticToken = security_domain.RequestToken // CSPPolicyName creates a Trusted Types policy name source. // Policy names are unquoted in the CSP header output. // // Example: // builder.TrustedTypes( // piko.CSPPolicyName("default"), // piko.CSPPolicyName("dompurify"), // ) // // outputs: trusted-types default dompurify CSPPolicyName = security_domain.PolicyName // CSPScript is the 'script' keyword for require-trusted-types-for directive. // This is used internally; prefer using RequireTrustedTypesFor() method. CSPScript = security_domain.Script // CSPAllowDuplicates is the 'allow-duplicates' keyword for the trusted-types // directive. This enables creating multiple policies with the same name. CSPAllowDuplicates = security_domain.AllowDuplicates // CSPWildcard is the wildcard (*) for trusted-types directive. // Allows creating policies with any unique names. CSPWildcard = security_domain.Wildcard // CSPSandboxAllowDownloads enables file downloads. CSPSandboxAllowDownloads = security_domain.SandboxAllowDownloads // CSPSandboxAllowForms allows form submission in sandboxed content. CSPSandboxAllowForms = security_domain.SandboxAllowForms // CSPSandboxAllowModals enables opening modal windows. CSPSandboxAllowModals = security_domain.SandboxAllowModals // CSPSandboxAllowOrientationLock allows the page to lock the screen direction. CSPSandboxAllowOrientationLock = security_domain.SandboxAllowOrientationLock // CSPSandboxAllowPointerLock enables the Pointer Lock API in sandboxed // content. CSPSandboxAllowPointerLock = security_domain.SandboxAllowPointerLock // CSPSandboxAllowPopups enables window.open() and similar. CSPSandboxAllowPopups = security_domain.SandboxAllowPopups // CSPSandboxAllowPopupsToEscapeSandbox enables popups to open unsandboxed // windows. CSPSandboxAllowPopupsToEscapeSandbox = security_domain.SandboxAllowPopupsToEscapeSandbox // CSPSandboxAllowPresentation enables the Presentation API in sandboxed // content. CSPSandboxAllowPresentation = security_domain.SandboxAllowPresentation // CSPSandboxAllowSameOrigin allows sandboxed content to be treated as being // from the same origin. CSPSandboxAllowSameOrigin = security_domain.SandboxAllowSameOrigin // CSPSandboxAllowScripts allows JavaScript to run in a sandboxed iframe. CSPSandboxAllowScripts = security_domain.SandboxAllowScripts // CSPSandboxAllowStorageAccessByUserActivation enables the Storage Access API // with user gesture. CSPSandboxAllowStorageAccessByUserActivation = security_domain.SandboxAllowStorageAccessByUserActivation // to a new address. CSPSandboxAllowTopNavigation = security_domain.SandboxAllowTopNavigation // user gesture. CSPSandboxAllowTopNavigationByUserActivation = security_domain.SandboxAllowTopNavigationByUserActivation // custom protocols. CSPSandboxAllowTopNavigationToCustomProtocols = security_domain.SandboxAllowTopNavigationToCustomProtocols )
var ( // NewSpamSchema creates a spam detection schema from entries. NewSpamSchema = spamdetect_dto.NewSchema // SpamTextField creates a schema entry for a text form field. SpamTextField = spamdetect_dto.TextField // SpamHoneypot declares the honeypot field key in a schema. SpamHoneypot = spamdetect_dto.Honeypot // SpamTiming declares the timing timestamp field key in a schema. SpamTiming = spamdetect_dto.Timing // SpamThreshold sets the score threshold for a schema. SpamThreshold = spamdetect_dto.Threshold // SpamFieldGroup composes multiple field entries for reuse. SpamFieldGroup = spamdetect_dto.FieldGroup // SpamEmailField creates a schema entry for an email field. SpamEmailField = spamdetect_dto.EmailField // SpamPhoneField creates a schema entry for a phone field. SpamPhoneField = spamdetect_dto.PhoneField // SpamNameField creates a schema entry for a name field. SpamNameField = spamdetect_dto.NameField // SpamURLField creates a schema entry for a URL field. SpamURLField = spamdetect_dto.URLField // SpamTypedField creates a schema entry with a custom field type. SpamTypedField = spamdetect_dto.TypedField // SpamDetectorWeight sets the scoring weight for a detector. SpamDetectorWeight = spamdetect_dto.DetectorWeight // SpamDetectorConfig sets per-schema config for a detector. SpamDetectorConfig = spamdetect_dto.DetectorConfig // SpamLanguage sets the expected content language. SpamLanguage = spamdetect_dto.Language // SpamMeta declares a static metadata key-value pair. SpamMeta = spamdetect_dto.Meta // SpamCaptureHeader declares an HTTP header to capture. SpamCaptureHeader = spamdetect_dto.CaptureHeader )
var ( // Version holds the current version of Piko. This can be overridden at build // time using: go build -ldflags "-X piko.sh/piko.Version=1.0.0". Version = "0.1.0-alpha" // WithComponents registers external PKC components with the Piko framework, // letting third-party component libraries provide components that can be used // in templates. // // Components registered via WithComponents are validated at startup: // - Tag names must contain a hyphen (e.g., "my-button", not "button") // - Tag names must not shadow HTML elements (e.g., "div", "span") // - Tag names must not use reserved prefixes (piko:, pml-) // - Duplicate tag names result in a startup error // // Takes components (...ComponentDefinition) which specifies the external // components to register. // // Returns Option which configures the container with the external components. // // Example: // server := piko.New( // piko.WithComponents( // piko.ComponentDefinition{ // TagName: "my-button", // ModulePath: "github.com/myorg/piko-components", // }, // piko.ComponentDefinition{ // TagName: "my-card", // ModulePath: "github.com/myorg/piko-components", // }, // ), // ) WithComponents = bootstrap.WithComponents // WithSEO provides the SEO configuration for sitemap and robots.txt // generation. SEO is only active when this option is provided with an // enabled configuration and a non-empty sitemap hostname. WithSEO = bootstrap.WithSEO // WithAssets provides the asset configuration including image/video profiles, // screen breakpoints, and default densities for responsive images. These // settings are used at compile time for static asset analysis. WithAssets = bootstrap.WithAssets // WithWebsiteConfig provides the website configuration programmatically, // replacing the file-based config.json loading entirely. When set, the // config.json file is not read. // // Use it for programmatic server setup where the website settings are // defined in Go code rather than a JSON file. WithWebsiteConfig = bootstrap.WithWebsiteConfig // WithStandardLoader causes the type inspector to use the // standard golang.org/x/tools/go/packages.Load instead of the // faster quickpackages loader. // // This is slower but always stable, since it is maintained by // the Go team. Useful as a fallback when quickpackages // encounters issues with specific dependency configurations // (e.g. complex CGo setups). WithStandardLoader = bootstrap.WithStandardLoader )
var ( // ErrSecretNotSet is returned when trying to acquire a secret that was never // populated. ErrSecretNotSet = config_domain.ErrSecretNotSet // ErrSecretClosed is returned when trying to acquire a secret that has been // closed. ErrSecretClosed = config_domain.ErrSecretClosed // ErrSecretResolutionFailed is returned when the resolver fails to resolve the // secret. ErrSecretResolutionFailed = config_domain.ErrSecretResolutionFailed // ErrSecretHandleClosed is returned when trying to use a handle that has // already been released. ErrSecretHandleClosed = config_domain.ErrSecretHandleClosed // ErrNoResolver is returned when no resolver is available for the secret's // prefix. ErrNoResolver = config_domain.ErrNoResolver )
Functions ¶
func AddAnalyticsProperty ¶
AddAnalyticsProperty attaches a key-value property to the automatic analytics event for the current request.
The middleware merges all properties into the event after the handler returns. No-op when called outside a request context.
Takes key (string) which is the property name. Takes value (string) which is the property value.
func GenerateLocaleHead ¶
func GenerateLocaleHead( r *RequestData, i18nConfig I18nConfig, pagePath string, supportedLocalesOverride []string, ) (locale string, canonicalURL string, alternateLinks []map[string]string)
GenerateLocaleHead generates internationalisation SEO metadata for a page.
Designed to be called from within a component's Render function to populate the Metadata.Language, Metadata.CanonicalUrl, and Metadata.AlternateLinks fields.
Takes r (*RequestData) which provides the current request data. Takes i18nConfig (I18nConfig) which defines locales and URL strategy. Takes pagePath (string) which is the page's URL path (e.g. "/about"). Takes supportedLocalesOverride ([]string) which optionally specifies locales to use instead of the full config. Pass nil or empty slice to use all locales from the config.
Returns locale (string) which is the current request's locale from r.Locale. Returns canonicalURL (string) which is the canonical URL for this page. Returns alternateLinks ([]map[string]string) which contains hreflang alternate links for SEO.
func GetAllCollectionItems ¶
GetAllCollectionItems retrieves all items from a static collection.
Retrieves all items in a collection without their content ASTs, suitable for building navigation, sitemaps, or indexes.
Takes collectionName (string) which specifies the collection to retrieve.
Returns []map[string]any which contains metadata maps for all items. Returns error when the collection is not found.
func GetData ¶
func GetData[T any](r *RequestData) T
GetData retrieves the page data from CollectionData and converts it to type T. This provides type-safe access to collection data in Render functions.
The function extracts page data from the collection root map and performs automatic type conversion using JSON marshalling/unmarshalling, which handles:
- Field name matching (case-sensitive)
- Type coercion (int to float, etc.)
- Nested structure conversion
- Missing fields (set to zero values)
Takes r (*RequestData) which contains the CollectionData to extract from.
Returns T which is the page data converted to the requested type, or the zero value if conversion fails.
func GetDataLink ¶
func GetDataLink(tType reflect.Type, r *RequestData) reflect.Value
GetDataLink is the //piko:link sibling for GetData.
The interpreter dispatches to GetDataLink when compiling piko.GetData[T](r) in a .pk file whose T is a user-defined struct. The first argument is the instantiated T supplied by the interpreter; the remaining signature mirrors GetData's non-generic parameters.
Takes tType (reflect.Type) which is the instantiated type the user wrote inside the brackets (e.g. Post from piko.GetData[Post](r)). Takes r (*RequestData) which contains the CollectionData to extract from.
Returns a reflect.Value of concrete type tType carrying the page data, or a zero value of tType if conversion fails.
func InitialiseForTesting ¶
InitialiseForTesting initialises Piko's global services with minimal dependencies suitable for unit and integration tests.
Creates a fully mocked Piko environment with:
- In-memory cache provider (no Redis/external cache required)
- In-memory storage provider (no S3/disk writes)
- In-memory registry (no metadata.db SQLite file created)
- Mock email provider (no actual emails sent)
- Mock email template service
- Mock image transformer (no actual image processing)
- In-memory event bus
This keeps tests:
- Fast (no I/O operations)
- Isolated (no shared state between tests)
- Portable (no external dependencies)
- Clean (no persistent state or files created)
Returns *bootstrap.Container which can be used to access services or for cleanup.
Example usage:
func TestMain(m *testing.M) {
piko.InitialiseForTesting()
os.Exit(m.Run())
}
This initialisation is lightweight and does not start the full daemon. It provides a complete mocked Piko environment suitable for testing. Tests should defer cleanup of any resources if needed.
func IsAuthenticated ¶
func IsAuthenticated(r *RequestData) bool
IsAuthenticated reports whether the request has a valid auth session. Returns false when r is nil, the context is missing, or no auth provider is configured.
Takes r (*RequestData) which is the current request to check.
Returns bool which is true if the request is authenticated.
func IsDevelopmentMode ¶
func IsDevelopmentMode(r *RequestData) bool
IsDevelopmentMode reports whether the current request is being served in development mode (dev or dev-i).
Use this in error page Render functions to decide whether to show internal error details. Returns false when r is nil or the request context does not carry development mode information.
Takes r (*RequestData) which provides the request context to check.
Returns bool which is true when the request is being served in development mode.
Example:
func Render(r *piko.RequestData, props piko.NoProps) (Response, piko.Metadata, error) {
errCtx := piko.GetErrorContext(r)
if errCtx == nil {
return Response{Message: "Unknown error"}, piko.Metadata{}, nil
}
message := errCtx.Message
if piko.IsDevelopmentMode(r) && errCtx.InternalMessage != "" {
message = errCtx.InternalMessage
}
return Response{Code: errCtx.StatusCode, Message: message}, piko.Metadata{}, nil
}
func QuickSearch ¶
func QuickSearch[T any](r *RequestData, collectionName string, query string) ([]T, error)
QuickSearch performs a simple fuzzy search and returns just the matched items without scores.
This is a convenience wrapper around SearchCollection for simple use cases. It uses default search settings:
- Fuzzy threshold: 0.3
- Searches all string fields
- Returns top 10 results
Example usage:
func Render(r *piko.RequestData, props piko.NoProps) (Response, piko.Metadata, error) {
query := r.QueryParams.Get("q")
results := piko.QuickSearch[Post](r, "blog", query)
return Response{Results: results}, piko.Metadata{}, nil
}
Takes r (*RequestData) which provides the request context. Takes collectionName (string) which specifies the collection to search. Takes query (string) which is the search term to match.
Returns []T which contains the matched items. Returns error when the search fails.
func QuickSearchLink ¶
func QuickSearchLink( tType reflect.Type, r *RequestData, collectionName string, query string, ) (reflect.Value, error)
QuickSearchLink is the //piko:link sibling for QuickSearch.
Takes tType (reflect.Type) which is the instantiated T. Remaining parameters mirror QuickSearch's non-type-parameter signature.
Returns a reflect.Value wrapping []T plus any search error.
func RegisterActions ¶
func RegisterActions(entries map[string]ActionHandlerEntry)
RegisterActions registers multiple actions with the global action registry. This is called by generated code in init() functions to auto-register actions.
Takes entries (map[string]ActionHandlerEntry) which maps action names (e.g., "email.contact") to their handler entries.
func RunHeadless ¶
RunHeadless bootstraps Piko's global services for headless use cases such as CLI tools, import scripts, background workers, and microservices.
This initialises the framework's service container (image processing, storage, cache, persistence) without starting an HTTP server, loading configuration files, or setting up frontend assets. Call this before any code that uses framework services via global access functions (e.g., media.GetImageDimensions, storage.GetDefaultService).
Takes opts (...Option) which configure providers, identical to New.
Returns *bootstrap.Container which provides direct service access if needed. Returns error when provider configuration is invalid.
Example:
container, err := piko.RunHeadless(
persistence.WithDriver(sqlite.New(sqlite.Config{})),
piko.WithImageProvider("imaging", imagingProvider),
piko.WithStorageProvider("media", diskProvider),
)
if err != nil {
log.Fatal(err)
}
// Framework services are now available globally
width, height, err := media.GetImageDimensions(ctx, reader)
func SearchCollectionLink ¶
func SearchCollectionLink( tType reflect.Type, r *RequestData, collectionName string, query string, opts ...SearchOption, ) (reflect.Value, error)
SearchCollectionLink is the //piko:link sibling for SearchCollection. The interpreter dispatches here when a .pk file calls piko.SearchCollection[T](r, ...) with a user-defined T.
Takes tType (reflect.Type) which is the instantiated T. Remaining parameters mirror SearchCollection's non-type-parameter signature.
Returns a reflect.Value wrapping []SearchResult[T] plus any search error.
func SetAnalyticsEventName ¶
SetAnalyticsEventName changes the automatic analytics event from a page view to a named custom event.
When set, the middleware promotes the event type from pageview to custom. No-op when called outside a request context.
Takes name (string) which is the event name.
func SetAnalyticsRevenue ¶
SetAnalyticsRevenue attaches revenue data to the automatic analytics event for the current request.
The middleware copies the value into the pageview event after the handler returns. No-op when called outside a request context.
Takes revenue (maths.Money) which is the monetary value to record.
func TrackAnalyticsEvent ¶
func TrackAnalyticsEvent(ctx context.Context, event *AnalyticsEvent)
TrackAnalyticsEvent sends a custom analytics event to all registered collectors. The event is enriched with request context (ClientIP, Locale, UserID, etc.) from the PikoRequestCtx if available.
When no collectors are registered, this is a no-op.
Takes event (*AnalyticsEvent) which is the event to send.
Types ¶
type ASTQueryResult ¶
type ASTQueryResult = pikotest_domain.ASTQueryResult
ASTQueryResult wraps a set of AST nodes from a CSS selector query and provides fluent assertion methods.
type AWSKMSConfig ¶
type AWSKMSConfig = config.AWSKMSConfig
AWSKMSConfig holds settings for AWS Key Management Service.
type ActionError ¶
type ActionError = daemon_dto.ActionError
ActionError is the base interface for action errors with HTTP semantics. Errors implementing ActionError are automatically discriminated by the action handler to return appropriate HTTP status codes and structured responses.
type ActionHandlerEntry ¶
type ActionHandlerEntry = daemon_adapters.ActionHandlerEntry
ActionHandlerEntry describes a registered action for the runtime. Generated code creates entries for each action and registers them at startup.
type ActionMetadata ¶
type ActionMetadata = daemon_dto.ActionMetadata
ActionMetadata is embedded in action structs to provide access to request context, metadata, and response building capabilities.
Example:
type DeleteAction struct {
piko.ActionMetadata
}
func (a DeleteAction) Call(id int64) (DeleteResponse, error) {
ctx := a.Ctx()
userID := a.Request().Session.UserID
a.Response().AddHelper("showToast", "Deleted", "success")
return DeleteResponse{Success: true}, nil
}
type ActionResult ¶
type ActionResult = pikotest_dto.ActionResult
ActionResult holds the raw result of a server action invocation.
type ActionResultView ¶
type ActionResultView = pikotest_domain.ActionResultView
ActionResultView wraps the result of an action invocation for assertions.
type ActionTester ¶
type ActionTester = pikotest_domain.ActionTester
ActionTester provides a test harness for server actions. Create one using NewActionTester with an ActionHandlerEntry.
func NewActionTester ¶
func NewActionTester(tb testing.TB, entry ActionHandlerEntry) *ActionTester
NewActionTester creates a new ActionTester for the given action handler entry.
Takes tb (testing.TB) which is the test instance for error reporting. Takes entry (ActionHandlerEntry) which describes the action to test.
Returns *ActionTester ready for invoking and asserting.
Example: tester := piko.NewActionTester(t, CustomerCreate) result := tester.Invoke(ctx, map[string]any{"name": "Acme Corp"}) result.AssertSuccess()
type AnalyticsCollector ¶
type AnalyticsCollector = analytics_domain.Collector
AnalyticsCollector is the interface that backend analytics adapters implement.
type AnalyticsConfig ¶
type AnalyticsConfig = daemon_frontend.AnalyticsConfig
AnalyticsConfig is an alias for the frontend analytics settings. It configures Google Analytics (GA4) integration.
type AnalyticsEvent ¶
type AnalyticsEvent = analytics_dto.Event
AnalyticsEvent carries the data for a single backend analytics event.
type AnalyticsEventType ¶
type AnalyticsEventType = analytics_dto.EventType
AnalyticsEventType classifies a backend analytics event.
type AssetTransformationStep ¶
type AssetTransformationStep = config.AssetTransformationStep
AssetTransformationStep represents a single transformation to apply to an asset.
type AssetsConfig ¶
type AssetsConfig = config.AssetsConfig
AssetsConfig holds settings for image and video asset processing including transformation profiles, screen breakpoints, and default densities.
type AuthContext ¶
type AuthContext = daemon_dto.AuthContext
AuthContext represents the resolved authentication state for a request. Users implement AuthContext to expose their auth system's data to Piko pages and actions.
type AuthGuardConfig ¶
type AuthGuardConfig = daemon_dto.AuthGuardConfig
AuthGuardConfig controls prefix-level and page-level authentication enforcement.
type AuthPolicy ¶
type AuthPolicy = daemon_dto.AuthPolicy
AuthPolicy declares authentication requirements for a page. Returned by the optional AuthPolicy() function in PK files.
type AuthProvider ¶
type AuthProvider = daemon_dto.AuthProvider
AuthProvider resolves authentication state from an HTTP request. Piko calls Authenticate on every request when a provider is registered.
type BadRequestError ¶
type BadRequestError = daemon_dto.BadRequestError
BadRequestError represents a malformed request (HTTP 400). Use this when the request itself is invalid, not just the data within it.
type BuildASTFunc ¶
type BuildASTFunc = pikotest_dto.BuildASTFunc
BuildASTFunc is the signature of the generated BuildAST function in compiled components.
type CSPBuilder ¶
type CSPBuilder = security_domain.CSPBuilder
CSPBuilder is a helper for creating Content-Security-Policy headers. See WithCSP for usage examples.
func NewCSPBuilder ¶
func NewCSPBuilder() *CSPBuilder
NewCSPBuilder creates a new CSP builder with no directives configured. This is the starting point for building a Content-Security-Policy.
Returns *CSPBuilder which is ready for chaining directive methods.
Example: builder := piko.NewCSPBuilder().
DefaultSrc(piko.CSPSelf).
ScriptSrc(piko.CSPSelf, piko.CSPHost("cdn.example.com")).
Build()
type CSSResetOption ¶
type CSSResetOption = bootstrap.CSSResetOption
CSSResetOption is a functional option for configuring the CSS reset feature. It is used as a sub-option of WithCSSReset.
func WithCSSResetComplete ¶
func WithCSSResetComplete() CSSResetOption
WithCSSResetComplete selects the comprehensive legacy CSS reset instead of the simple default. The comprehensive reset includes element-level resets, typography defaults, heading sizes via theme variables, and focus-ring styles.
Returns CSSResetOption which switches to the complete reset preset.
func WithCSSResetPKOverride ¶
func WithCSSResetPKOverride(css string) CSSResetOption
WithCSSResetPKOverride replaces the default CSS reset with custom CSS content for PK files (pages, partials, emails).
Takes css (string) which is the custom CSS reset content.
Returns CSSResetOption which sets the custom CSS override.
type CacheConfig ¶
type CacheConfig = daemon_domain.CacheConfig
CacheConfig defines caching behaviour for action responses.
type CachePolicy ¶
type CachePolicy = templater_dto.CachePolicy
CachePolicy defines the caching behaviour for a component's output.
type Cacheable ¶
type Cacheable = daemon_domain.Cacheable
Cacheable is an interface for configuring response caching.
type CaptchaConfig ¶
type CaptchaConfig = daemon_domain.CaptchaConfig
CaptchaConfig defines captcha verification configuration.
type CaptchaOptions ¶
type CaptchaOptions = bootstrap.CaptchaOptions
CaptchaOptions groups the captcha provider's per-deployment settings. The provider implementation itself is selected via WithDefaultCaptchaProvider and registered via WithCaptchaProvider.
type CaptchaProtected ¶
type CaptchaProtected = daemon_domain.CaptchaProtected
CaptchaProtected is an interface for requiring captcha verification.
type ComponentDefinition ¶
type ComponentDefinition = component_dto.ComponentDefinition
ComponentDefinition describes a PKC component that can be used in templates.
Tag names must contain a hyphen (per Web Components specification) and must not shadow HTML element names or use reserved prefixes (piko:, pml-).
type ComponentOption ¶
type ComponentOption = pikotest_dto.ComponentOption
ComponentOption sets optional behaviour for the ComponentTester.
func WithPageID ¶
func WithPageID(pageID string) ComponentOption
WithPageID sets the page identifier for this component test.
Takes pageID (string) which specifies the unique page identifier.
Returns ComponentOption which configures the test with the given page ID.
func WithRenderer
deprecated
func WithRenderer(_ any) ComponentOption
WithRenderer attaches a RenderService to enable full HTML rendering in tests. Most tests should use AST queries instead, which do not require a renderer.
Returns ComponentOption which logs an error at apply-time without configuring the renderer. The piko package cannot reference the internal RenderService type without inducing an import cycle, so this stub exists for surface compatibility only.
Deprecated: Use pikotest_domain.WithRenderer directly. Calling this function emits an error via slog and does not attach a renderer; HTML() assertions on the resulting TestView will fail with a missing-renderer diagnostic.
type ComponentTester ¶
type ComponentTester = pikotest_domain.ComponentTester
ComponentTester manages the testing of a compiled Piko component. Create one using NewComponentTester with your component's BuildAST function.
func NewComponentTester ¶
func NewComponentTester(tb testing.TB, buildAST BuildASTFunc, opts ...ComponentOption) *ComponentTester
NewComponentTester creates a new ComponentTester for the given component's BuildAST function.
Example: import "myapp/dist/pages/customers"
func TestCustomersPage(t *testing.T) {
tester := piko.NewComponentTester(t, customers.BuildAST)
// ...
}
Takes tb (testing.TB) which provides the test context. Takes buildAST (BuildASTFunc) which builds the component's AST. Takes opts (...ComponentOption) which configures the tester behaviour.
Returns *ComponentTester which is ready to test the component.
type ConfigResolver ¶
type ConfigResolver = config_domain.Resolver
ConfigResolver enables integration with secret managers such as AWS Secrets Manager or HashiCorp Vault for custom configuration value resolution.
type ConflictError ¶
type ConflictError = daemon_dto.ConflictError
ConflictError represents a conflict (HTTP 409). Use this when an operation cannot complete due to a conflict with current state.
type Container ¶
Container is the Dependency Injection container that holds all application services. It is exposed for advanced use cases where direct access to a service is needed.
type CookieOption ¶
type CookieOption = daemon_dto.CookieOption
CookieOption is a functional option for configuring cookies created with Cookie().
type CookieSecurityConfig ¶
type CookieSecurityConfig = config.CookieSecurityConfig
CookieSecurityConfig holds secure defaults for HTTP cookies.
type Error ¶
Error is an error that carries a user-safe message separate from its internal cause.
In production, only SafeMessage() reaches the user; the full error detail is logged server-side. In development mode (dev or dev-i), the full error string is shown for easier debugging.
Any error in the chain can implement Error; the error boundary will discover it via errors.As. Existing sentinels and errors.Is chains are preserved through Unwrap().
Example:
func Render(r *piko.RequestData, props piko.NoProps) (Response, piko.Metadata, error) {
user, err := loadUser(r.Context(), id)
if err != nil {
return Response{}, piko.Metadata{},
piko.NewError("could not load user profile", err)
}
return Response{User: user}, piko.Metadata{}, nil
}
type ErrorPageContext ¶
type ErrorPageContext = daemon_dto.ErrorPageContext
ErrorPageContext carries error details into a custom error page's Render function. When a page returns an error (or a route is not found), the runtime injects this context before rendering the matching error page.
Access it via GetErrorContext in your error page's Render function:
func Render(r *piko.RequestData, props piko.NoProps) (Response, piko.Metadata, error) {
if errCtx := piko.GetErrorContext(r); errCtx != nil {
// errCtx.StatusCode, errCtx.Message, errCtx.OriginalPath
}
}
func GetErrorContext ¶
func GetErrorContext(r *RequestData) *ErrorPageContext
GetErrorContext returns the error page context from the request, if present, providing the status code, message, and original request path for use inside error page Render functions.
Takes r (*RequestData) which is the current request to check for error context.
Returns nil when the request is not being rendered as an error page.
Example:
func Render(r *piko.RequestData, props piko.NoProps) (Response, piko.Metadata, error) {
errCtx := piko.GetErrorContext(r)
if errCtx != nil {
return Response{Code: errCtx.StatusCode, Message: errCtx.Message}, piko.Metadata{}, nil
}
return Response{Code: 500, Message: "Unknown error"}, piko.Metadata{}, nil
}
type FaviconDefinition ¶
type FaviconDefinition = config.FaviconDefinition
FaviconDefinition describes a single favicon link element for a website.
type FileUpload ¶
type FileUpload = daemon_dto.FileUpload
FileUpload represents an uploaded file from a multipart form request. Use FileUpload in action Call parameters to receive file uploads.
Example:
func (a *UploadAction) Call(document piko.FileUpload) (Response, error) {
content, err := document.ReadAll()
if err != nil {
return Response{}, err
}
return Response{Size: document.Size}, nil
}
For multiple files, use []piko.FileUpload:
func (a *UploadAction) Call(documents []piko.FileUpload) (Response, error) {
for _, doc := range documents {
// Process each file...
}
return Response{Count: len(documents)}, nil
}
type Filter ¶
Filter represents a single filtering condition for collection queries.
func NewFilter ¶
func NewFilter(field string, operator FilterOperator, value any) Filter
NewFilter creates a single filter condition.
Takes field (string) which specifies the field name to filter on. Takes operator (FilterOperator) which defines the comparison operation. Takes value (interface{}) which provides the value to compare against.
Returns Filter which is the constructed filter condition.
Example: filter := piko.NewFilter("status", piko.FilterOpEquals, "published")
type FilterGroup ¶
type FilterGroup = runtime.FilterGroup
FilterGroup represents multiple filters combined with AND/OR logic.
func And ¶
func And(filters ...Filter) FilterGroup
And combines multiple filters with AND logic (all must match).
Takes filters (...Filter) which specifies the filters to combine.
Returns FilterGroup which contains the combined filters.
Example: filters := piko.And(
piko.NewFilter("status", piko.FilterOpEquals, "published"),
piko.NewFilter("featured", piko.FilterOpEquals, true),
)
func Or ¶
func Or(filters ...Filter) FilterGroup
Or combines multiple filters with OR logic where at least one must match.
Takes filters (...Filter) which are the conditions to combine.
Returns FilterGroup which contains the combined filters.
Example: filters := piko.Or(
piko.NewFilter("category", piko.FilterOpEquals, "tech"),
piko.NewFilter("category", piko.FilterOpEquals, "science"),
)
type FilterOperator ¶
type FilterOperator = runtime.FilterOperator
FilterOperator defines comparison operations (eq, contains, gt, etc).
type FontDefinition ¶
type FontDefinition = config.FontDefinition
FontDefinition defines a font to be loaded by the website.
type ForbiddenError ¶
type ForbiddenError = daemon_dto.ForbiddenError
ForbiddenError represents authorisation failure (HTTP 403). Use this when the user is authenticated but lacks permission.
type FrontendModule ¶
type FrontendModule = daemon_frontend.FrontendModule
FrontendModule represents a built-in Piko frontend module. These are optional JavaScript bundles that add features like analytics, modals, or toasts to the core framework.
type GCPKMSConfig ¶
type GCPKMSConfig = config.GCPKMSConfig
GCPKMSConfig holds settings for Google Cloud Key Management Service.
type GeneratorProfilingOption ¶
type GeneratorProfilingOption = bootstrap.GeneratorProfilingOption
GeneratorProfilingOption configures profiling for short-lived generator builds that capture profiles to disk.
func WithGeneratorProfilingBlockRate ¶
func WithGeneratorProfilingBlockRate(rate int) GeneratorProfilingOption
WithGeneratorProfilingBlockRate sets the block profiling rate for generator profiling.
Takes rate (int) which specifies the sampling rate in nanoseconds.
Returns GeneratorProfilingOption which configures the block profile rate.
func WithGeneratorProfilingMemProfileRate ¶
func WithGeneratorProfilingMemProfileRate(rate int) GeneratorProfilingOption
WithGeneratorProfilingMemProfileRate sets the memory profiling sample rate for generator profiling. 0 uses the Go runtime default.
Takes rate (int) which specifies the sampling rate in bytes.
Returns GeneratorProfilingOption which configures the memory profile rate.
func WithGeneratorProfilingMutexFraction ¶
func WithGeneratorProfilingMutexFraction(fraction int) GeneratorProfilingOption
WithGeneratorProfilingMutexFraction sets the mutex profiling fraction for generator profiling.
Takes fraction (int) which specifies the sampling fraction.
Returns GeneratorProfilingOption which configures the mutex profile fraction.
func WithGeneratorProfilingOutputDir ¶
func WithGeneratorProfilingOutputDir(directory string) GeneratorProfilingOption
WithGeneratorProfilingOutputDir sets the directory for captured profile files.
Takes directory (string) which specifies the output directory path.
Returns GeneratorProfilingOption which configures the output directory.
type GenericPageError ¶
type GenericPageError = daemon_dto.GenericPageError
GenericPageError represents an error with an arbitrary HTTP status code. Use this when none of the specific error types match the status code you need.
type HTTPMethod ¶
type HTTPMethod = daemon_domain.HTTPMethod
HTTPMethod defines the valid HTTP methods for an action.
type HealthCheckType ¶
type HealthCheckType = healthprobe_dto.CheckType
HealthCheckType indicates whether this is a liveness or readiness check.
type HealthProbe ¶
type HealthProbe = healthprobe_domain.Probe
HealthProbe is the interface that custom application health checks must implement. Implementing HealthProbe allows your application to take part in Piko's health check system, which is exposed via the /live and /ready endpoints.
Interface definition:
type HealthProbe interface {
Name() string
Check(ctx context.Context, checkType HealthCheckType) HealthStatus
}
The Check method receives the checkType parameter, which allows your probe to return different results for liveness vs readiness checks:
- Liveness: Quick check - is the service initialised and not deadlocked?
- Readiness: Thorough check - is the service ready to handle requests?
type HealthState ¶
type HealthState = healthprobe_dto.State
HealthState represents the health status of a component.
type HealthStatus ¶
type HealthStatus = healthprobe_dto.Status
HealthStatus represents the result of a health check operation. It includes the component name, state, optional message, timestamp, and duration.
type HealthTLSOption ¶
type HealthTLSOption = bootstrap.HealthTLSOption
HealthTLSOption configures TLS settings for the health probe server. Use with WithHealthTLS.
func WithHealthTLSCertFile ¶
func WithHealthTLSCertFile(path string) HealthTLSOption
WithHealthTLSCertFile sets the certificate file for the health probe server.
Takes path (string) which specifies the certificate file path.
Returns HealthTLSOption which sets the certificate path.
func WithHealthTLSKeyFile ¶
func WithHealthTLSKeyFile(path string) HealthTLSOption
WithHealthTLSKeyFile sets the key file for the health probe server.
Takes path (string) which specifies the key file path.
Returns HealthTLSOption which sets the key path.
func WithHealthTLSMinVersion ¶
func WithHealthTLSMinVersion(version string) HealthTLSOption
WithHealthTLSMinVersion sets the minimum TLS version for the health probe server.
Takes version (string) which specifies the minimum version ("1.2" or "1.3").
Returns HealthTLSOption which sets the minimum TLS version.
type HelperCall ¶
type HelperCall = daemon_dto.HelperCall
HelperCall represents a client-side helper function call.
type I18nConfig ¶
type I18nConfig = config.I18nConfig
I18nConfig contains the internationalisation configuration for a website. It defines the supported locales, default locale, and URL strategy for i18n routing.
Use I18nConfig when calling GenerateLocaleHead to generate SEO metadata for your pages, or when populating WebsiteConfig.I18n via WithWebsiteConfig.
Strategy values:
- "query-only": Single bare path; locale is read from a query parameter or detection (e.g., /about?lang=fr).
- "prefix": All routes are prefixed with the locale (e.g., /en/about, /fr/about).
- "prefix_except_default": Only non-default locales get a prefix (e.g., /about, /fr/about).
type ImageAssetsConfig ¶
type ImageAssetsConfig = config.ImageAssetsConfig
ImageAssetsConfig holds image-specific asset configuration.
type LifecycleComponent ¶
type LifecycleComponent interface {
// OnStart runs when the server starts up.
// Use this to set up resources, open connections, run migrations, and so on.
//
// Returns error to stop the server from starting.
//
// The context has a timeout. If OnStart does not finish in time, the server
// will fail to start.
OnStart(ctx context.Context) error
// OnStop is called when the server is shutting down gracefully.
// Use this to close connections, flush caches, save state, etc.
//
// The context will have a timeout applied. If OnStop does not complete
// within the timeout, the server will forcefully terminate.
//
// Return an error to log the issue, but shutdown will continue.
OnStop(ctx context.Context) error
// Name returns a readable name for this component, used for logging and
// identification.
//
// Returns string which is the component name.
Name() string
}
LifecycleComponent defines the contract for components that require lifecycle management.
Components implementing LifecycleComponent have their OnStart method called during server startup (before accepting HTTP traffic) and their OnStop method called during graceful shutdown.
Lifecycle components are executed in the order they are registered. During shutdown, they are stopped in reverse order (last registered, first stopped).
Example implementation:
type MyComponent struct {
db *sql.DB
}
func (c *MyComponent) OnStart(ctx context.Context) error {
var err error
c.db, err = sql.Open("postgres", connString)
if err != nil {
return fmt.Errorf("failed to connect to database: %w", err)
}
return nil
}
func (c *MyComponent) OnStop(ctx context.Context) error {
if c.db != nil {
return c.db.Close()
}
return nil
}
func (c *MyComponent) Name() string {
return "MyDatabaseComponent"
}
type LifecycleHealthProbe ¶
type LifecycleHealthProbe interface {
healthprobe_domain.Probe
}
LifecycleHealthProbe provides health monitoring for components. It is an alias to the internal healthprobe_domain.Probe interface, allowing external packages to implement health probes without importing internal packages.
Probes are called periodically by the health monitoring system and exposed via HTTP endpoints. Components can implement both LifecycleComponent and LifecycleHealthProbe to get both lifecycle management and health monitoring.
Example implementation:
func (c *MyComponent) Check(ctx context.Context, checkType piko.HealthCheckType) piko.HealthStatus {
// For liveness: check if component is alive (not deadlocked)
if checkType == piko.HealthCheckLiveness {
return piko.HealthStatus{
Name: c.Name(),
State: piko.HealthStateHealthy,
Timestamp: time.Now(),
}
}
// For readiness: check if component is ready to serve traffic
if err := c.db.PingContext(ctx); err != nil {
return piko.HealthStatus{
Name: c.Name(),
State: piko.HealthStateUnhealthy,
Message: fmt.Sprintf("database unreachable: %v", err),
Timestamp: time.Now(),
}
}
return piko.HealthStatus{
Name: c.Name(),
State: piko.HealthStateHealthy,
Timestamp: time.Now(),
}
}
type LifecycleStartTimeout ¶
type LifecycleStartTimeout interface {
// StartTimeout returns the timeout duration for starting the server.
//
// Returns time.Duration which is the maximum time allowed for startup.
StartTimeout() time.Duration
}
LifecycleStartTimeout is an optional interface that lifecycle components can implement to override the default 30-second startup timeout. Components performing long-running initialisation (such as document ingestion or database migrations) should implement this to request more time.
Example:
func (c *MyComponent) StartTimeout() time.Duration {
return 5 * time.Minute
}
type LifecycleWithHealth ¶
type LifecycleWithHealth interface {
LifecycleComponent
LifecycleHealthProbe
}
LifecycleWithHealth combines lifecycle management and health probing for components that need both managed startup/shutdown and runtime health checks.
When you register a component that implements LifecycleWithHealth:
- OnStart is called during server startup.
- The component is automatically registered as a health probe.
- Check is called periodically for /health, /live, and /ready endpoints.
- OnStop is called during server shutdown.
type LoggerConfig ¶
type LoggerConfig = logger_dto.Config
LoggerConfig holds settings for the application logger. Pass to WithLogger.
type MetaTag ¶
type MetaTag = templater_dto.MetaTag
MetaTag represents an HTML <meta> tag used for page metadata (e.g., <meta name="author" content="...">).
type Metadata ¶
type Metadata = templater_dto.Metadata
Metadata allows a component's Render function to return SEO information, caching policies, and other page-level metadata that influences the final HTTP response.
type MetricsExporter ¶
type MetricsExporter = monitoring_domain.MetricsExporter
MetricsExporter is the interface for metrics exporters. Implementations provide OTEL metric reader integration and HTTP handlers.
type ModalsConfig ¶
type ModalsConfig = daemon_frontend.ModalsConfig
ModalsConfig provides settings for the Modals module.
type MonitoringOption ¶
type MonitoringOption = bootstrap.MonitoringOption
MonitoringOption sets up the gRPC monitoring service.
func WithMonitoringAddress ¶
func WithMonitoringAddress(addr string) MonitoringOption
WithMonitoringAddress sets the gRPC server listen address for monitoring. Default: ":9091".
Takes addr (string) which specifies the address and port to listen on.
Returns MonitoringOption which configures the monitoring server address.
func WithMonitoringAutoNextPort ¶
func WithMonitoringAutoNextPort(enabled bool) MonitoringOption
WithMonitoringAutoNextPort enables automatic port selection for the monitoring server. When the configured port is already in use, the server tries consecutive ports up to 100 attempts.
Takes enabled (bool) which controls whether auto-port selection is active.
Returns MonitoringOption which configures auto-port selection.
func WithMonitoringBindAddress ¶
func WithMonitoringBindAddress(addr string) MonitoringOption
WithMonitoringBindAddress sets the network address for the monitoring server to bind to. Default is "127.0.0.1" (localhost only for security).
Takes addr (string) which specifies the network address to bind to.
Returns MonitoringOption which configures the monitoring bind address.
func WithMonitoringOtelFactories ¶
func WithMonitoringOtelFactories(factories monitoring_domain.ServiceFactories) MonitoringOption
WithMonitoringOtelFactories overrides the default noop monitoring service factories with real OTEL SDK implementations. Use this with the factories from logger_otel_sdk.OtelServiceFactories() to enable SDK-backed span processing and metrics collection.
Example:
piko.WithMonitoring(
piko.WithMonitoringOtelFactories(logger_otel_sdk.OtelServiceFactories()),
)
Takes factories (monitoring_domain.ServiceFactories) which provides the span processor and metrics collector factories.
Returns MonitoringOption which configures the factories on the service.
func WithMonitoringProfiling ¶
func WithMonitoringProfiling() MonitoringOption
WithMonitoringProfiling enables the remote profiling gRPC service, allowing operators to toggle pprof on and off at runtime via the monitoring endpoint. Without this option, the ProfilingService is not registered and profiling cannot be controlled remotely.
Usage:
piko.WithMonitoring(
piko.WithMonitoringTransport(monitoring_transport_grpc.Transport()),
piko.WithMonitoringProfiling(),
)
Once enabled, operators can use the CLI to control profiling:
piko profiling enable 30m # Start profiling for 30 minutes piko profiling capture heap # Capture a heap profile piko profiling disable # Stop profiling early
Returns MonitoringOption which enables the profiling service.
func WithMonitoringTLS ¶
func WithMonitoringTLS(opts ...MonitoringTLSOption) MonitoringOption
WithMonitoringTLS enables TLS for the monitoring gRPC server. Sub-options configure certificate paths, mTLS, and hot-reload settings.
Takes opts (...MonitoringTLSOption) which provides optional TLS settings:
- WithMonitoringTLSCertFile("/path/to/cert.pem"): sets the certificate.
- WithMonitoringTLSKeyFile("/path/to/key.pem"): sets the private key.
- WithMonitoringTLSClientCA("/path/to/ca.pem"): enables mTLS.
- WithMonitoringTLSClientAuth("require_and_verify"): sets client auth mode.
- WithMonitoringTLSMinVersion("1.3"): sets minimum TLS version.
- WithMonitoringTLSHotReload(true): enables certificate hot-reload.
Returns MonitoringOption which configures TLS on the monitoring service.
func WithMonitoringTransport ¶
func WithMonitoringTransport(factory monitoring_domain.TransportFactory) MonitoringOption
WithMonitoringTransport sets the transport factory for the monitoring service.
Example:
piko.WithMonitoring(
piko.WithMonitoringTransport(monitoring_transport_grpc.Transport()),
)
Takes factory (monitoring_domain.TransportFactory) which creates the transport server.
Returns MonitoringOption which configures the transport on the service.
func WithMonitoringWatchdog ¶
func WithMonitoringWatchdog(opts ...WatchdogOption) MonitoringOption
WithMonitoringWatchdog enables the runtime watchdog that monitors heap memory, goroutine counts, and GC pressure, automatically capturing diagnostic profiles when anomalies are detected.
Takes opts (...WatchdogOption) which configure thresholds and behaviour.
Returns MonitoringOption which enables the watchdog on the service.
func WithWatchdogNotifier ¶
func WithWatchdogNotifier(notifier WatchdogNotifier) MonitoringOption
WithWatchdogNotifier sets the notification delivery mechanism for watchdog events. When set, the watchdog sends notifications to external systems when thresholds are breached or errors occur.
Takes notifier (WatchdogNotifier) which delivers event notifications.
Returns MonitoringOption which configures the notifier on the service.
func WithWatchdogProfileUploader ¶
func WithWatchdogProfileUploader(uploader WatchdogProfileUploader) MonitoringOption
WithWatchdogProfileUploader sets the remote storage backend for watchdog profile uploads. When set, captured profiles are uploaded after being written to local disk.
Takes uploader (WatchdogProfileUploader) which handles remote storage.
Returns MonitoringOption which configures the uploader on the service.
type MonitoringTLSOption ¶
type MonitoringTLSOption = bootstrap.MonitoringTLSOption
MonitoringTLSOption configures TLS settings for the monitoring gRPC server.
func WithMonitoringTLSCertFile ¶
func WithMonitoringTLSCertFile(path string) MonitoringTLSOption
WithMonitoringTLSCertFile sets the certificate file for the monitoring server.
Takes path (string) which specifies the certificate file path.
Returns MonitoringTLSOption which sets the certificate path.
func WithMonitoringTLSClientAuth ¶
func WithMonitoringTLSClientAuth(authType string) MonitoringTLSOption
WithMonitoringTLSClientAuth sets the client certificate verification mode for the monitoring server.
Takes authType (string) which specifies the auth mode.
Returns MonitoringTLSOption which sets the client auth type.
func WithMonitoringTLSClientCA ¶
func WithMonitoringTLSClientCA(path string) MonitoringTLSOption
WithMonitoringTLSClientCA sets the client CA file for mTLS on the monitoring server.
Takes path (string) which specifies the client CA file path.
Returns MonitoringTLSOption which sets the client CA path.
func WithMonitoringTLSHotReload ¶
func WithMonitoringTLSHotReload(enabled bool) MonitoringTLSOption
WithMonitoringTLSHotReload enables or disables automatic certificate reload for the monitoring server.
Takes enabled (bool) which controls hot-reload behaviour.
Returns MonitoringTLSOption which sets the hot-reload flag.
func WithMonitoringTLSKeyFile ¶
func WithMonitoringTLSKeyFile(path string) MonitoringTLSOption
WithMonitoringTLSKeyFile sets the key file for the monitoring server.
Takes path (string) which specifies the key file path.
Returns MonitoringTLSOption which sets the key path.
func WithMonitoringTLSMinVersion ¶
func WithMonitoringTLSMinVersion(version string) MonitoringTLSOption
WithMonitoringTLSMinVersion sets the minimum TLS version for the monitoring server.
Takes version (string) which specifies the minimum version ("1.2" or "1.3").
Returns MonitoringTLSOption which sets the minimum TLS version.
type NavigationConfig ¶
type NavigationConfig = runtime.NavigationConfig
NavigationConfig controls how navigation trees are built.
func DefaultNavigationConfig ¶
func DefaultNavigationConfig() NavigationConfig
DefaultNavigationConfig returns a NavigationConfig with sensible defaults. Use this when you do not need custom configuration.
Returns NavigationConfig which provides ready-to-use navigation settings.
type NavigationGroups ¶
type NavigationGroups = runtime.NavigationGroups
NavigationGroups contains multiple named navigation structures. Each group represents a distinct navigation UI such as sidebar, footer, or breadcrumb.
func BuildNavigationFromMetadata ¶
func BuildNavigationFromMetadata(ctx context.Context, items []map[string]any, config NavigationConfig) *NavigationGroups
BuildNavigationFromMetadata constructs hierarchical navigation from collection metadata.
Takes metadata maps (from GetAllCollectionItems) and builds navigation trees based on the "Navigation" field in each item's metadata.
The navigation metadata should follow the layout below: metadata["Navigation"] = NavigationMetadata with Groups["sidebar"], etc.
Takes items ([]map[string]interface{}) which is a slice of metadata maps from a collection. Takes config (NavigationConfig) which specifies navigation building options.
Returns *NavigationGroups which contains all named navigation trees.
Example usage in a template:
func Render(r *piko.RequestData) (Response, piko.Metadata, error) {
// Get all docs metadata (lightweight - no ASTs)
allDocuments, err := piko.GetAllCollectionItems("docs")
if err != nil {
return Response{}, piko.Metadata{}, err
}
// Build navigation
navGroups := piko.BuildNavigationFromMetadata(allDocuments, piko.DefaultNavigationConfig())
// Access navigation for different contexts
sidebar := navGroups.Groups["sidebar"]
footer := navGroups.Groups["footer"]
return Response{
Sidebar: sidebar,
Footer: footer,
}, piko.Metadata{}, nil
}
type NavigationNode ¶
type NavigationNode = runtime.NavigationNode
NavigationNode represents a single node in the navigation hierarchy. Nodes can be categories (grouping) or content pages (with URLs).
type NavigationTree ¶
type NavigationTree = runtime.NavigationTree
NavigationTree represents a hierarchical navigation structure for a specific locale.
type NoProps ¶
type NoProps = templater_dto.NoProps
NoProps is a placeholder type for components that do not accept any properties. It is used in the Render function signature when a component is self-contained.
type NoResponse ¶
type NoResponse = templater_dto.NoResponse
NoResponse is a placeholder type for Render functions that do not return any data for the template. The template can still access global state such as the request object.
type NotFoundError ¶
type NotFoundError = daemon_dto.NotFoundError
NotFoundError represents resource not found (HTTP 404). Use this when a requested resource does not exist.
type OGTag ¶
type OGTag = templater_dto.OGTag
OGTag represents an Open Graph protocol <meta> tag for social media sharing (e.g., <meta property="og:title" content="...">).
type Option ¶
Option is a functional option used to customise the Piko server during initialisation.
func WithAPICSP ¶
func WithAPICSP() Option
WithAPICSP configures a minimal CSP policy for JSON API servers. This policy blocks all resource types, which protects against cases where the API accidentally serves HTML content (e.g., error pages with user input).
The policy includes:
- default-src 'none' (blocks everything by default)
- frame-ancestors 'none' (cannot be embedded in frames)
- base-uri 'none' (no base element allowed)
- form-action 'none' (no form submissions)
This is ideal for API endpoints that should only return JSON data.
Returns Option which applies the API CSP configuration to the server.
Example: server := piko.New(
piko.WithAPICSP(),
)
func WithAWSKMS ¶
func WithAWSKMS(k AWSKMSConfig) Option
WithAWSKMS configures AWS Key Management Service settings.
Takes k (AWSKMSConfig) which is the value to apply.
Returns Option which the bootstrap consumes when applied.
func WithActionMaxBodyBytes ¶
WithActionMaxBodyBytes sets the maximum size in bytes for action request bodies.
Takes n (int64) which is the value to apply.
Returns Option which the bootstrap consumes when applied.
func WithActionResponseCacheMaxBytes ¶
WithActionResponseCacheMaxBytes overrides the framework default weight cap on the action-response cache.
Takes maxBytes (uint64) which is the cap in bytes; zero leaves the framework default in place.
Returns Option which configures the cap on the container.
func WithActionServePath ¶
WithActionServePath sets the URL path prefix for server actions.
Takes path (string) which is the value to apply.
Returns Option which the bootstrap consumes when applied.
func WithArtefactServePath ¶
WithArtefactServePath sets the URL path prefix for serving compiled assets.
Takes path (string) which is the value to apply.
Returns Option which the bootstrap consumes when applied.
func WithAssetsSourceDir ¶
WithAssetsSourceDir sets the directory for asset files.
Takes dir (string) which is the value to apply.
Returns Option which the bootstrap consumes when applied.
func WithAuthGuard ¶
func WithAuthGuard(authGuardConfig AuthGuardConfig) Option
WithAuthGuard enables route-level authentication enforcement.
Requires WithAuthProvider to be set; ignored without it.
Takes authGuardConfig (AuthGuardConfig) which specifies public paths, login redirect, and optional custom handler.
Returns Option which configures the auth guard.
func WithAuthProvider ¶
func WithAuthProvider(provider AuthProvider) Option
WithAuthProvider registers an authentication provider that Piko calls on every request to resolve the auth state. The resolved AuthContext is available via RequestData.Auth() in pages and ActionMetadata.Auth() in actions.
Takes provider (AuthProvider) which resolves auth state from HTTP requests.
Returns Option which configures the auth provider.
func WithAutoMemoryLimit ¶
WithAutoMemoryLimit configures the Go runtime to set GOMEMLIMIT based on the container's cgroup memory limit. This prevents OOM kills in containerised deployments by making the garbage collector aware of the memory ceiling.
Takes provider (func() (int64, error)) which detects and applies the memory limit. Use the automemlimit WDK module for a ready-made provider.
Returns Option which configures automatic memory limit detection.
func WithAutoNextPort ¶
WithAutoNextPort enables automatic port selection for the main HTTP server when the configured port is already in use.
Takes enabled (bool) which is the value to apply.
Returns Option which the bootstrap consumes when applied.
func WithBackendAnalytics ¶
func WithBackendAnalytics(collectors ...AnalyticsCollector) Option
WithBackendAnalytics registers one or more backend analytics collectors. When at least one collector is registered, the analytics middleware is automatically installed in the HTTP request chain (after auth, before rate limiting) and fires page view events for every request.
Takes collectors (...AnalyticsCollector) which handle event delivery to external analytics backends.
Returns Option which registers the collectors.
func WithBaseDir ¶
WithBaseDir sets the root directory of the website project.
Takes dir (string) which is the value to apply.
Returns Option which the bootstrap consumes when applied.
func WithBaseServePath ¶
WithBaseServePath sets the URL path prefix for serving pages.
Takes path (string) which is the value to apply.
Returns Option which the bootstrap consumes when applied.
func WithCSP ¶
func WithCSP(configure func(*CSPBuilder)) Option
WithCSP configures the Content-Security-Policy header using a builder function.
Takes configure (func(*CSPBuilder)) which is a callback that receives a CSPBuilder for configuring CSP directives.
Returns Option which applies the CSP configuration to the server.
The builder function receives a CSPBuilder that you configure with your desired directives. The resulting policy is applied to all HTTP responses.
Example - Simple custom policy: server := piko.New(
piko.WithCSP(func(b *piko.CSPBuilder) {
b.DefaultSrc(piko.CSPSelf).
ScriptSrc(piko.CSPSelf, piko.CSPHost("cdn.example.com")).
StyleSrc(piko.CSPSelf, piko.CSPUnsafeInline)
}),
) Example - Extend Piko defaults: server := piko.New(
piko.WithCSP(func(b *piko.CSPBuilder) {
b.WithPikoDefaults().
ScriptSrc(piko.CSPSelf, piko.CSPHost("analytics.example.com"))
}),
) Example - Report-only mode for testing: server := piko.New(
piko.WithCSP(func(b *piko.CSPBuilder) {
b.WithPikoDefaults().
ReportOnly().
ReportToDirective("csp-violations")
}),
) Example - Dynamic per-request tokens for strict CSP: server := piko.New(
piko.WithCSP(func(b *piko.CSPBuilder) {
b.DefaultSrc(piko.CSPSelf).
ScriptSrc(piko.CSPSelf, piko.CSPStrictDynamic, piko.CSPRequestToken).
StyleSrc(piko.CSPSelf, piko.CSPRequestToken)
}),
) When using CSPRequestToken, add the token attribute to inline elements in templates: <script {{ .CSPTokenAttr }}>...</script> <style {{ .CSPTokenAttr }}>...</style>
func WithCSPString ¶
WithCSPString sets the Content-Security-Policy header directly from a string. This is an escape hatch for complex cases that don't fit the builder pattern, or for migrating existing CSP configurations.
Pass an empty string to disable the CSP header entirely.
Takes policy (string) which specifies the raw CSP policy value.
Returns Option which configures the CSP header on the container.
Example: // Use a pre-existing policy string server := piko.New(
piko.WithCSPString("default-src 'self'; script-src 'self' cdn.example.com"),
) // Disable CSP entirely server := piko.New(
piko.WithCSPString(""),
)
func WithCSRFSecFetchSiteEnforcement ¶
WithCSRFSecFetchSiteEnforcement controls whether browser requests must include CSRF tokens when the Sec-Fetch-Site header is present.
Takes enabled (bool) which controls whether enforcement is active.
Returns Option which configures the CSRF enforcement on the server.
func WithCSRFSecret ¶
WithCSRFSecret configures the CSRF service with a specific secret key.
Takes key ([]byte) which is the secret key for CSRF token generation.
Returns Option which applies the CSRF secret configuration.
func WithCSRFTokenMaxAge ¶
WithCSRFTokenMaxAge sets the fallback maximum age for CSRF tokens.
The primary expiry mechanism is cookie rotation; this setting acts as a safety net for tokens backed by cookies that persist beyond their expected lifetime. When d is 0 or negative, the default of 30 days is used.
Takes d (time.Duration) which specifies the maximum token age.
Returns Option which configures the CSRF token max age on the server.
func WithCSSReset ¶
func WithCSSReset(opts ...CSSResetOption) Option
WithCSSReset enables the CSS reset for PK files (pages, partials, emails). Without sub-options, the simple default reset is used which zeroes margins and padding and sets border-box sizing on all elements.
Use WithCSSResetComplete to switch to the comprehensive legacy reset that includes element-level resets, typography defaults, heading sizes via theme variables, and focus-ring styles.
Use WithCSSResetPKOverride to provide entirely custom CSS reset content.
When WithCSSReset is not called, no CSS reset is included in the generated theme CSS.
Takes opts (...CSSResetOption) which provides optional settings:
- WithCSSResetComplete(): selects the comprehensive legacy reset.
- WithCSSResetPKOverride(css): overrides with custom CSS content.
Returns Option which configures the server's CSS reset behaviour.
Example:
server := piko.New(
piko.WithCSSReset(),
)
server := piko.New(
piko.WithCSSReset(piko.WithCSSResetComplete()),
)
server := piko.New(
piko.WithCSSReset(piko.WithCSSResetPKOverride(myCustomCSS)),
)
func WithCSSTreeShaking ¶
func WithCSSTreeShaking() Option
WithCSSTreeShaking enables CSS tree-shaking during scaffold generation.
When enabled, unused CSS rules (based on static HTML analysis) are removed from the final output, reducing CSS bundle size.
Returns Option which configures the server to enable CSS tree-shaking.
WARNING: Tree-shaking removes CSS for classes that are not present in static HTML. Classes added dynamically via JavaScript (e.g., via classList.add()) will be removed unless added to the safelist using WithCSSTreeShakingSafelist.
By default, CSS tree-shaking is DISABLED to prevent accidentally removing styles needed for dynamic functionality.
Example: server := piko.New(
piko.WithCSSTreeShaking(),
piko.WithCSSTreeShakingSafelist("open", "active", "hidden", "visible"),
)
func WithCSSTreeShakingSafelist ¶
WithCSSTreeShakingSafelist specifies CSS class names that should never be removed by tree-shaking, even when CSSTreeShaking is enabled.
Use this for classes that are added dynamically via JavaScript, such as modal open states, visibility toggles, or animation classes.
Class names should be specified without the leading dot.
Example: server := piko.New(
piko.WithCSSTreeShaking(),
piko.WithCSSTreeShakingSafelist("open", "active", "hidden", "visible"),
) This preserves CSS rules for .open, .active, .hidden, and .visible even if those classes don't appear in the static HTML.
Takes classes (...string) which lists the CSS class names to preserve.
Returns Option which configures the safelist on the server.
func WithCacheProvider ¶
func WithCacheProvider(name string, provider cache_domain.Provider) Option
WithCacheProvider registers a named cache provider instance with the default cache service. If multiple providers are registered, use WithDefaultCacheProvider to specify which one is the default.
Cache providers implement the Provider interface, which creates namespaced Cache[K, V] instances on demand, so a single provider (e.g., a Redis connection pool) can serve multiple typed caches.
Takes name (string) which identifies this provider for later reference. Takes provider (cache_domain.Provider) which creates cache instances.
Returns Option which configures the container with the cache provider.
Example: import (
"piko.sh/piko" cache_provider_otter "piko.sh/piko/internal/cache/cache_adapters/provider_otter"
) otterProvider := cache_provider_otter.NewOtterProvider() app := piko.New(
piko.WithCacheProvider("otter", otterProvider),
piko.WithDefaultCacheProvider("otter"),
)
func WithCacheService ¶
func WithCacheService(service cache_domain.Service) Option
WithCacheService sets a fully configured cache service instance. This overrides the default cache service creation and provider registration.
Takes service (cache_domain.Service) which is the configured cache service.
Returns Option which applies the cache service to the container.
Example: import (
"piko.sh/piko/wdk/cache" "piko.sh/piko/wdk/cache/cache_provider_otter"
) // Create a custom cache service cacheService := cache.NewService("otter") otterFactory := cache_provider_otter.NewOtterProviderFactory[string, []byte]() cacheService.RegisterProvider("otter", otterFactory) // Use it when initialising Piko server, err := piko.New(
piko.WithCacheService(cacheService),
)
func WithCapabilityService ¶
func WithCapabilityService(service capabilities.Service) Option
WithCapabilityService provides a custom CapabilityService implementation.
Takes service (capabilities.Service) which is the custom capability service to use.
Returns Option which configures the bootstrap with the given service.
func WithCaptcha ¶
func WithCaptcha(opts CaptchaOptions) Option
WithCaptcha sets the per-deployment captcha settings (site key, secret, score threshold).
Takes opts (CaptchaOptions) which is the value to apply.
Returns Option which the bootstrap consumes when applied.
func WithCaptchaProvider ¶
func WithCaptchaProvider(name string, provider captcha_domain.CaptchaProvider) Option
WithCaptchaProvider registers a named captcha provider instance with the default captcha service.
Multiple providers can be registered. Use WithDefaultCaptchaProvider to specify which provider is active.
Takes name (string) which identifies the provider for later reference. Takes provider (captcha_domain.CaptchaProvider) which handles captcha verification.
Returns Option which configures the container with the captcha provider.
Example:
import "piko.sh/piko/wdk/captcha/captcha_provider_turnstile"
provider, _ := captcha_provider_turnstile.NewProvider(config)
server := piko.New(
piko.WithCaptchaProvider("turnstile", provider),
piko.WithDefaultCaptchaProvider("turnstile"),
)
func WithCloudflareEnabled ¶
WithCloudflareEnabled enables trust of the CF-Connecting-IP header from trusted proxies.
When false (the default), the header is ignored even from trusted proxies. Enable this only when Cloudflare is your edge proxy and its IP ranges are listed in WithTrustedProxies.
Takes enabled (bool) which controls whether CF-Connecting-IP is trusted.
Returns Option which configures the Cloudflare setting on the server.
func WithComponentsSourceDir ¶
WithComponentsSourceDir sets the directory for .pkc/.sfc component files.
Takes dir (string) which is the value to apply.
Returns Option which the bootstrap consumes when applied.
func WithConfigResolvers ¶
func WithConfigResolvers(resolvers ...ConfigResolver) Option
WithConfigResolvers allows for injecting custom configuration resolvers. This is the primary mechanism for integrating with secret managers like AWS Secrets Manager, GCP Secret Manager, or HashiCorp Vault.
Takes resolvers (...ConfigResolver) which provide custom resolution logic.
Returns Option which configures the application with the given resolvers.
func WithCookieSecurity ¶
func WithCookieSecurity(cookies CookieSecurityConfig) Option
WithCookieSecurity sets the secure cookie defaults applied to all cookies the framework writes.
Takes cookies (CookieSecurityConfig) which is the value to apply.
Returns Option which the bootstrap consumes when applied.
func WithCrashOutput ¶
WithCrashOutput configures runtime/debug.SetCrashOutput so the Go runtime mirrors fatal-error output (panics, stack overflows, concurrent map writes, OOM aborts) to the given file path. The file is opened in append mode so captures from earlier crashes are preserved, and the runtime retains ownership of the file descriptor for the process lifetime.
When the file cannot be opened the feature is disabled silently and a warning is logged. Crash output must never block startup.
Pass an empty path to leave the feature disabled (default).
Takes path (string) which is the absolute file path for crash output.
Returns Option which sets the crash-output path.
func WithCrashTraceback ¶
WithCrashTraceback sets the GOTRACEBACK level via runtime/debug.SetTraceback. Valid levels are "none", "single" (Go default), "all", "system", "crash" (raises SIGABRT after the traceback so the kernel or systemd-coredump can capture a coredump), and "wer" (Windows error reporting).
Takes level (string) which is the traceback level.
Returns Option which sets the crash-traceback level.
func WithCrossOriginResourcePolicy ¶
WithCrossOriginResourcePolicy sets the Cross-Origin-Resource-Policy header value. This header controls which origins can load resources from this server.
Takes policy (string) which specifies the CORP policy. Use one of:
- CORPSameOrigin (default): Only same-origin requests can load resources
- CORPSameSite: Same-site requests can load resources
- CORPCrossOrigin: Any origin can load resources (required for headless CMS)
Returns Option which configures the CORP header on the container.
Example - Enable cross-origin resource sharing for headless CMS: server := piko.New(
piko.WithCrossOriginResourcePolicy(piko.CORPCrossOrigin),
)
func WithCryptoProvider ¶
func WithCryptoProvider(name string, provider crypto_domain.EncryptionProvider) Option
WithCryptoProvider registers a named encryption provider instance with the default crypto service.
Multiple providers can be registered (e.g., one for development, one for production). Use WithDefaultCryptoProvider to specify which provider is active.
Takes name (string) which identifies the provider for later reference. Takes provider (crypto_domain.EncryptionProvider) which handles encryption operations.
Returns Option which configures the container with the named provider.
Example: import (
"piko.sh/piko" "piko.sh/piko/wdk/crypto/crypto_provider_aws_kms" "piko.sh/piko/wdk/crypto/crypto_provider_local_aes_gcm"
) // Register multiple providers localProvider, _ := crypto_provider_local_aes_gcm.NewProvider(ctx, localConfig) awsProvider, _ := crypto_provider_aws_kms.NewAWSKMSProvider(ctx, awsConfig) server := piko.New(
piko.WithCryptoProvider("local", localProvider),
piko.WithCryptoProvider("aws_kms", awsProvider),
piko.WithDefaultCryptoProvider("aws_kms"), // Use AWS KMS as default
)
func WithCryptoService ¶
func WithCryptoService(service crypto_domain.CryptoServicePort) Option
WithCryptoService provides a fully configured crypto service instance.
Use it in advanced scenarios where you need complete control over service construction.
For most use cases, prefer using WithCryptoProvider and WithDefaultCryptoProvider instead.
Takes service (crypto_domain.CryptoServicePort) which is the custom crypto service to use.
Returns Option which configures the server to use the provided service.
Example: customService := crypto.NewService(myProvider, myConfig) server := piko.New(
piko.WithCryptoService(customService),
)
func WithCustomFrontendModule ¶
WithCustomFrontendModule registers a custom frontend JavaScript module. The module will be served at /_piko/dist/ppframework.{name}.min.js and automatically included in all pages.
The content should be provided via go:embed at compile time to ensure the module is bundled into the binary: //go:embed static/js/tracking.js var trackingJS []byte server := piko.New(
piko.WithCustomFrontendModule("tracking", trackingJS),
) The optional config parameter allows passing configuration to the module: server := piko.New(
piko.WithCustomFrontendModule("tracking", trackingJS, map[string]any{
"endpoint": "https://analytics.example.com",
"debug": true,
}),
) The module can access its config via PPFramework.getModuleConfig("tracking").
Takes name (string) which identifies the module in the URL and config lookup. Takes content ([]byte) which contains the JavaScript module source code. Takes moduleConfig (...map[string]any) which provides optional key-value settings accessible to the module at runtime.
Returns Option which configures the server to serve this custom module.
func WithCustomHealthProbe ¶
func WithCustomHealthProbe(probe HealthProbe) Option
WithCustomHealthProbe registers a custom health probe with the Piko framework. The probe will be included in the /live and /ready health check endpoints.
Use it to extend Piko's built-in health monitoring with application-specific checks (e.g., database connectivity, external API availability).
Takes probe (HealthProbe) which is the health probe to register.
Returns Option which configures the container with the custom probe.
Example:
type RedisProbe struct {
client *redis.Client
}
func (p *RedisProbe) Name() string { return "ApplicationRedisCache" }
func (p *RedisProbe) Check(ctx context.Context, checkType piko.HealthCheckType) piko.HealthStatus {
startTime := time.Now()
err := p.client.Ping(ctx).Err()
state := piko.HealthStateHealthy
message := "Redis connection OK"
if err != nil {
state = piko.HealthStateUnhealthy
message = fmt.Sprintf("Redis connection failed: %v", err)
}
return piko.HealthStatus{
Name: p.Name(),
State: state,
Message: message,
Timestamp: time.Now(),
Duration: time.Since(startTime).String(),
}
}
// Register the probe server := piko.New(
piko.WithCustomHealthProbe(&RedisProbe{client: redisClient}),
)
func WithD1APIToken ¶
WithD1APIToken sets the Cloudflare API token used for D1 access.
Takes token (string) which is the value to apply.
Returns Option which the bootstrap consumes when applied.
func WithD1AccountID ¶
WithD1AccountID sets the Cloudflare account ID for D1 access.
Takes id (string) which is the value to apply.
Returns Option which the bootstrap consumes when applied.
func WithD1DatabaseID ¶
WithD1DatabaseID sets the D1 database UUID.
Takes id (string) which is the value to apply.
Returns Option which the bootstrap consumes when applied.
func WithDataKeyCacheMaxSize ¶
WithDataKeyCacheMaxSize sets the maximum number of cached data keys.
Takes n (int) which is the value to apply.
Returns Option which the bootstrap consumes when applied.
func WithDataKeyCacheTTL ¶
WithDataKeyCacheTTL configures how long decrypted data keys are cached for KMS providers. Zero disables caching.
Takes d (time.Duration) which is the value to apply.
Returns Option which the bootstrap consumes when applied.
func WithDatabase ¶
func WithDatabase(name string, registration *bootstrap.DatabaseRegistration) Option
WithDatabase registers a named SQL database connection for the registry or orchestrator subsystem. When a database named "registry" or "orchestrator" is registered, piko uses a SQL-backed DAL instead of the default otter in-memory backend for that subsystem.
Available driver packages:
- db_driver_sqlite_cgo: CGO SQLite (maximum performance)
- db_driver_sqlite_nocgo: Pure-Go SQLite (no CGO required)
- db_driver_d1: Cloudflare D1
Example:
import (
"piko.sh/piko"
"piko.sh/piko/wdk/db"
"piko.sh/piko/wdk/db/db_driver_sqlite_cgo"
"piko.sh/piko/wdk/db/db_engine_sqlite"
"piko.sh/piko/wdk/db/db_schema_registry_sqlite"
"piko.sh/piko/wdk/db/db_schema_orchestrator_sqlite"
)
app := piko.New(
piko.WithDatabase(db.DatabaseNameRegistry, &db.DatabaseRegistration{
DB: db_driver_sqlite_cgo.Open("data/registry.db", db_driver_sqlite_cgo.Config{}),
EngineConfig: db_engine_sqlite.SQLite(),
MigrationFS: db_schema_registry_sqlite.Migrations,
}),
piko.WithDatabase(db.DatabaseNameOrchestrator, &db.DatabaseRegistration{
DB: db_driver_sqlite_cgo.Open("data/orchestrator.db", db_driver_sqlite_cgo.Config{}),
EngineConfig: db_engine_sqlite.SQLite(),
MigrationFS: db_schema_orchestrator_sqlite.Migrations,
}),
)
Takes name (string) which identifies the database (db.DatabaseNameRegistry or db.DatabaseNameOrchestrator for framework subsystems, or any custom name for application databases). Takes registration (*bootstrap.DatabaseRegistration) which provides the connection and migration configuration.
Returns Option which registers the database with the application.
func WithDatabaseDriver ¶
WithDatabaseDriver selects the database backend. Valid values: "sqlite" (default), "postgres", "d1".
Takes driver (string) which is the value to apply.
Returns Option which the bootstrap consumes when applied.
func WithDefaultCacheProvider ¶
WithDefaultCacheProvider sets the name of the provider to use for default cache creation. A provider with this name must be registered via WithCacheProvider.
Takes name (string) which specifies the provider name to use as default.
Returns Option which configures the container with the default cache provider.
Example: app := piko.New(
piko.WithCacheProvider("redis", redisProvider),
piko.WithCacheProvider("otter", otterProvider),
piko.WithDefaultCacheProvider("redis"),
)
func WithDefaultCaptchaProvider ¶
WithDefaultCaptchaProvider sets the name of the provider to use for captcha verification. A provider with this name must be registered via WithCaptchaProvider.
Takes name (string) which specifies the provider name to use as default.
Returns Option which configures the container with the default captcha provider.
func WithDefaultCryptoProvider ¶
WithDefaultCryptoProvider sets the name of the provider to use for encryption operations. A provider with this name must be registered via WithCryptoProvider.
Use it to switch between providers (e.g., local for dev, KMS for production) without changing application code.
Takes name (string) which specifies the registered provider to use.
Returns Option which configures the default crypto provider.
Example: server := piko.New(
piko.WithCryptoProvider("local", localProvider),
piko.WithCryptoProvider("aws_kms", awsProvider),
piko.WithDefaultCryptoProvider("aws_kms"), // Active provider
)
func WithDefaultEmailProvider ¶
WithDefaultEmailProvider sets the name of the provider to use for default email sending. A provider with this name must be registered via WithEmailProvider.
Takes name (string) which specifies the provider name to use as default.
Returns Option which configures the container with the default email provider.
func WithDefaultEmbeddingProvider ¶
WithDefaultEmbeddingProvider sets the name of the default embedding provider. When set, this takes precedence over any auto-detected embedding support from the default LLM provider.
A provider with this name must be registered via WithEmbeddingProvider or be an LLM provider that implements EmbeddingProviderPort.
Takes name (string) which specifies the provider name to use as default.
Returns Option which configures the container with the default embedding provider.
func WithDefaultImageProvider ¶
WithDefaultImageProvider sets which registered provider should be used as the default. A provider with this name must be registered via WithImageProvider.
Takes name (string) which specifies the registered provider name.
Returns Option which configures the default image provider.
func WithDefaultLLMProvider ¶
WithDefaultLLMProvider sets the name of the provider to use for default LLM operations. A provider with this name must be registered via WithLLMProvider.
Takes name (string) which specifies the provider name to use as default.
Returns Option which configures the container with the default LLM provider.
Example: app := piko.New(
piko.WithLLMProvider("anthropic", anthropicProvider),
piko.WithLLMProvider("openai", openaiProvider),
piko.WithDefaultLLMProvider("anthropic"),
) // Default provider is used when no provider is specified llmService, _ := llm.GetDefaultService() response, err := llmService.Complete(ctx, request) // Uses "anthropic"
func WithDefaultMaxSSEDuration ¶
WithDefaultMaxSSEDuration sets the maximum lifetime for SSE connections that do not specify their own limit. Zero means unlimited.
Takes d (time.Duration) which is the value to apply.
Returns Option which the bootstrap consumes when applied.
func WithDefaultNotificationProvider ¶
WithDefaultNotificationProvider sets the name of the provider to use for default notification sending. A provider with this name must be registered via WithNotificationProvider.
Takes name (string) which specifies the provider name to use as default.
Returns Option which configures the container with the default notification provider.
Example: app := piko.New(
piko.WithNotificationProvider("webhook", webhookProvider),
piko.WithNotificationProvider("email", emailNotifier),
piko.WithDefaultNotificationProvider("webhook"),
)
func WithDefaultServeMode ¶
WithDefaultServeMode selects the default page serving mode. Valid values: "preview" (dynamic) or "render" (static).
Takes mode (string) which is the value to apply.
Returns Option which the bootstrap consumes when applied.
func WithDefaultStorageProvider ¶
WithDefaultStorageProvider sets the name of the provider to use for default storage operations. A provider with this name must be registered via WithStorageProvider.
Takes name (string) which specifies the registered provider name.
Returns Option which configures the container's default storage provider.
func WithDefaultVideoProvider ¶
WithDefaultVideoProvider sets which registered provider should be used as the default. A provider with this name must be registered via WithVideoProvider.
Takes name (string) which is the identifier of the provider to use.
Returns Option which configures the container's default video provider.
func WithDeprecatedKeyIDs ¶
WithDeprecatedKeyIDs lists key IDs that remain valid for decryption but are not used for new encryption.
Takes ids (...string) which is the value to apply.
Returns Option which the bootstrap consumes when applied.
func WithDevHotreload ¶
func WithDevHotreload() Option
WithDevHotreload enables automatic page refresh in dev mode.
Returns Option which enables dev hot-reload.
func WithDevWidget ¶
func WithDevWidget() Option
WithDevWidget enables the dev tools overlay widget in dev mode.
Returns Option which enables the dev widget.
func WithDiagnosticDirectory ¶
WithDiagnosticDirectory sets a single root directory for all runtime diagnostic artefacts: the crash mirror file (dir/crash.log) and the watchdog's profile / sidecar / startup-history files (dir/profiles).
Takes directory (string) which is the root directory for diagnostic artefacts.
Returns Option which sets the diagnostic directory on the container.
func WithDistServePath ¶
WithDistServePath sets the URL path prefix for serving frontend distribution files.
Takes path (string) which is the value to apply.
Returns Option which the bootstrap consumes when applied.
func WithE2EMode ¶
WithE2EMode controls whether E2E test pages and partials are included in the build. WARNING: Never enable in production.
Takes enabled (bool) which controls whether E2E mode is active.
Returns Option which configures the E2E mode setting.
func WithE2ESourceDir ¶
WithE2ESourceDir sets the directory for E2E test pages and partials.
Takes dir (string) which is the value to apply.
Returns Option which the bootstrap consumes when applied.
func WithEmailDeadLetterQueue ¶
func WithEmailDeadLetterQueue(dlq email_domain.DeadLetterPort) Option
WithEmailDeadLetterQueue provides a custom dead letter queue implementation used by the dispatcher. If omitted, an in-memory DLQ will be used by default when a dispatcher is enabled.
Takes dlq (email_domain.DeadLetterPort) which handles failed email delivery attempts.
Returns Option which configures the container with the provided DLQ.
func WithEmailDispatcher ¶
func WithEmailDispatcher(dispatcherConfig email_dto.DispatcherConfig) Option
WithEmailDispatcher enables and configures the background dispatcher for the default email service.
Takes dispatcherConfig (email_dto.DispatcherConfig) which controls batching, retries, and queue sizes.
Returns Option which applies the dispatcher configuration to the container.
func WithEmailProvider ¶
func WithEmailProvider(name string, provider email_domain.EmailProviderPort) Option
WithEmailProvider registers a named email provider instance with the default email service. If multiple providers are registered, use WithDefaultEmailProvider to specify which one is the default.
Takes name (string) which identifies this provider for later reference. Takes provider (email_domain.EmailProviderPort) which handles email sending.
Returns Option which configures the container with the email provider.
func WithEmailService ¶
func WithEmailService(service email_domain.Service) Option
WithEmailService returns an option that configures the email service.
Takes service (email_domain.Service) which provides email functionality.
Returns Option which applies the email service configuration.
func WithEmailsSourceDir ¶
WithEmailsSourceDir sets the directory for email template source files.
Takes dir (string) which is the value to apply.
Returns Option which the bootstrap consumes when applied.
func WithEmbeddingProvider ¶
func WithEmbeddingProvider(name string, provider llm_domain.EmbeddingProviderPort) Option
WithEmbeddingProvider registers a standalone embedding provider for embedding-only services such as Voyage AI.
Unlike WithLLMProvider, this does not register a completion provider. When using an LLM provider that also supports embeddings (e.g. OpenAI, Ollama), embedding support is auto-detected and this option is not needed.
Takes name (string) which identifies this provider. Takes provider (llm_domain.EmbeddingProviderPort) which handles embedding requests.
Returns Option which configures the container with the embedding provider.
Example: app := piko.New(
piko.WithLLMProvider("anthropic", anthropicProvider),
piko.WithDefaultLLMProvider("anthropic"),
piko.WithEmbeddingProvider("voyage", voyageProvider),
piko.WithDefaultEmbeddingProvider("voyage"),
)
func WithEncryptionKey ¶
WithEncryptionKey sets the base64-encoded 32-byte encryption key for the default local AES-GCM crypto provider.
Takes key (string) which is the value to apply.
Returns Option which the bootstrap consumes when applied.
func WithEventBus ¶
func WithEventBus(bus orchestrator_domain.EventBus) Option
WithEventBus provides a custom EventBus implementation.
Takes bus (orchestrator_domain.EventBus) which specifies the event bus to use.
Returns Option which configures the application to use the provided event bus.
func WithEventsProvider ¶
func WithEventsProvider(provider events_domain.Provider) Option
WithEventsProvider sets a custom events provider, overriding the default GoChannel provider.
Use this to configure NATS JetStream, PostgreSQL, SQLite, or a custom provider.
Example with NATS JetStream: import "piko.sh/piko/wdk/events/events_provider_nats" provider, _ := events_provider_nats.NewNATSProvider(ctx,
events_provider_nats.Config{URL: "nats://localhost:4222"},
) provider.Start(ctx) app := piko.New(
piko.WithEventsProvider(provider),
) Example with custom GoChannel configuration: import "piko.sh/piko/wdk/events/events_provider_gochannel" channelConfig := events_provider_gochannel.DefaultConfig() channelConfig.OutputChannelBuffer = 2048 provider, _ := events_provider_gochannel.NewGoChannelProvider(channelConfig) provider.Start(ctx) app := piko.New(
piko.WithEventsProvider(provider),
) The provider must be started (via Start()) before passing it to WithEventsProvider. If you pass an unstarted provider, the container will not start it automatically.
Takes provider (events_domain.Provider) which is the events provider to use.
Returns Option which configures the container's events provider.
func WithExperimentalCommentStripping ¶
WithExperimentalCommentStripping toggles stripping of HTML comments from generated output.
When enabled, <!-- ... --> comments are omitted from rendered HTML.
Takes enabled (bool) which specifies whether comment stripping is active.
Returns Option which the bootstrap consumes when applied.
func WithExperimentalDwarfLineDirectives ¶
WithExperimentalDwarfLineDirectives toggles DWARF-compatible line directives in generated Go code.
When enabled, the generator emits "//line file:line" (no space) which the Go compiler embeds in DWARF debug info, allowing debuggers like Delve to map breakpoints back to .pk source files. Disabled by default; the generator emits a plain "// line file:line" comment.
Takes enabled (bool) which specifies whether DWARF line directives are active.
Returns Option which the bootstrap consumes when applied.
func WithExperimentalPrerendering ¶
WithExperimentalPrerendering toggles prerendering of pages during build.
When enabled, eligible pages are rendered to HTML at build time rather than per request. Email templates are never prerendered regardless of this setting.
Takes enabled (bool) which specifies whether prerendering is active.
Returns Option which the bootstrap consumes when applied.
func WithForceHTTPS ¶
WithForceHTTPS enables redirection from HTTP to HTTPS.
Takes enabled (bool) which is the value to apply.
Returns Option which the bootstrap consumes when applied.
func WithFrontendModule ¶
func WithFrontendModule(module FrontendModule, moduleConfig ...any) Option
WithFrontendModule enables a built-in frontend module to be loaded site-wide. The module's JavaScript will be automatically preloaded and executed on every page.
The optional config parameter allows passing configuration to the module. Use the appropriate config type for each module:
- AnalyticsConfig for ModuleAnalytics
- ModalsConfig for ModuleModals
- ToastsConfig for ModuleToasts
Example without config: server := piko.New(
piko.WithFrontendModule(piko.ModuleModals),
) Example with config: server := piko.New(
piko.WithFrontendModule(piko.ModuleAnalytics, piko.AnalyticsConfig{
TrackingIDs: []string{"G-XXXXXXXXXX", "G-YYYYYYYYYY"},
DebugMode: true,
}),
)
Takes module (FrontendModule) which specifies the frontend module to enable. Takes moduleConfig (...any) which provides optional configuration for the module.
Returns Option which configures the server to load the specified module.
func WithGCPKMS ¶
func WithGCPKMS(k GCPKMSConfig) Option
WithGCPKMS configures Google Cloud KMS settings.
Takes k (GCPKMSConfig) which is the value to apply.
Returns Option which the bootstrap consumes when applied.
func WithGeneratorProfiling ¶
func WithGeneratorProfiling(opts ...GeneratorProfilingOption) Option
WithGeneratorProfiling enables profiling for short-lived generator builds. CPU, trace, heap, block, mutex, goroutine, and allocs profiles are captured to disk in the specified output directory (default "./profiles").
Unlike WithProfiling, this does not start an HTTP server. Instead, it wraps the build execution: profiling starts before the build and profiles are written when the build completes.
Takes opts (...GeneratorProfilingOption) which provides optional settings:
- WithGeneratorProfilingOutputDir("./profiles"): sets the output directory.
- WithGeneratorProfilingBlockRate(1): sets the block profile rate.
- WithGeneratorProfilingMutexFraction(1): sets the mutex profile fraction.
Returns Option which configures the container with generator profiling settings.
Example:
server := piko.New(
piko.WithGeneratorProfiling(),
)
With custom output directory:
server := piko.New(
piko.WithGeneratorProfiling(
piko.WithGeneratorProfilingOutputDir("/tmp/profiles"),
),
)
func WithHealthAutoNextPort ¶
WithHealthAutoNextPort enables automatic port selection for the health probe server.
Takes enabled (bool) which is the value to apply.
Returns Option which the bootstrap consumes when applied.
func WithHealthBindAddress ¶
WithHealthBindAddress sets the network address to bind the health probe server to.
Takes addr (string) which is the value to apply.
Returns Option which the bootstrap consumes when applied.
func WithHealthCheckTimeout ¶
WithHealthCheckTimeout sets the maximum time for each individual health check.
Takes d (time.Duration) which is the value to apply.
Returns Option which the bootstrap consumes when applied.
func WithHealthEnabled ¶
WithHealthEnabled controls whether the health probe server starts.
Takes enabled (bool) which is the value to apply.
Returns Option which the bootstrap consumes when applied.
func WithHealthLivePath ¶
WithHealthLivePath sets the URL path for the liveness probe endpoint.
Takes path (string) which is the value to apply.
Returns Option which the bootstrap consumes when applied.
func WithHealthMetricsEnabled ¶
WithHealthMetricsEnabled controls whether the Prometheus metrics endpoint is exposed on the health probe server.
Takes enabled (bool) which is the value to apply.
Returns Option which the bootstrap consumes when applied.
func WithHealthMetricsPath ¶
WithHealthMetricsPath sets the URL path for the Prometheus metrics endpoint.
Takes path (string) which is the value to apply.
Returns Option which the bootstrap consumes when applied.
func WithHealthProbePort ¶
WithHealthProbePort sets the port for the health probe server.
Takes port (int) which is the value to apply.
Returns Option which the bootstrap consumes when applied.
func WithHealthReadyPath ¶
WithHealthReadyPath sets the URL path for the readiness probe endpoint.
Takes path (string) which is the value to apply.
Returns Option which the bootstrap consumes when applied.
func WithHealthTLS ¶
func WithHealthTLS(opts ...HealthTLSOption) Option
WithHealthTLS enables TLS for the health probe server.
Takes opts (...HealthTLSOption) which provides optional health TLS settings.
Returns Option which configures the container with health server TLS.
func WithHighlighter ¶
func WithHighlighter(h highlight_domain.Highlighter) Option
WithHighlighter configures syntax highlighting for markdown code blocks.
When a highlighter is configured, code blocks in markdown content will be syntax-highlighted using the provided implementation. If no highlighter is configured, code blocks render as plain <pre><code> elements.
Example with Chroma (recommended): import (
"piko.sh/piko" "piko.sh/piko/wdk/highlight/highlight_chroma"
)
highlighter := highlight_chroma.NewChromaHighlighter(highlight_chroma.Config{
Style: "dracula",
WithClasses: true,
})
server := piko.New(
piko.WithHighlighter(highlighter),
) When using WithClasses: true, you must include the appropriate CSS styles in your page for the highlighting to be visible.
Takes h (highlight_domain.Highlighter) which provides the syntax highlighting implementation.
Returns Option which configures the server to use the given highlighter.
func WithHybridCacheMaxBytes ¶
WithHybridCacheMaxBytes overrides the framework default weight cap on the hybrid-collections cache.
Takes maxBytes (uint64) which is the cap in bytes; zero leaves the framework default in place.
Returns Option which configures the cap on the container.
func WithHybridCacheWriteExpiration ¶
WithHybridCacheWriteExpiration overrides the framework default write-expiration on the hybrid-collections cache.
Takes expiration (time.Duration) which is the write-expiration; zero or negative leaves the framework default in place.
Returns Option which configures the expiration on the container.
func WithI18nDefaultLocale ¶
WithI18nDefaultLocale sets the default locale used for internationalisation.
Takes locale (string) which is the value to apply.
Returns Option which the bootstrap consumes when applied.
func WithI18nService ¶
func WithI18nService(service i18n_domain.Service) Option
WithI18nService provides a custom I18nService implementation.
Takes service (i18n_domain.Service) which is the internationalisation service to use.
Returns Option which configures the application to use the provided service.
func WithI18nSourceDir ¶
WithI18nSourceDir sets the directory containing locale and translation JSON files.
Takes dir (string) which is the value to apply.
Returns Option which the bootstrap consumes when applied.
func WithIAmACatPerson ¶
func WithIAmACatPerson() Option
WithIAmACatPerson swaps the large pixel-art mascot in the startup banner for the small ASCII art version. Defaults to false.
Returns Option which configures the mascot preference.
func WithImage ¶
func WithImage(imageConfig *image_domain.ImageConfig) Option
WithImage configures the image service using an ImageConfig from the builder. This is the recommended way to configure image processing with full control.
Takes imageConfig (*image_domain.ImageConfig) which specifies the image processing settings including provider, file size limits, and variants.
Returns Option which applies the image configuration to the container.
Example: import (
"piko.sh/piko/wdk/media" "piko.sh/piko/wdk/media/image_provider_vips"
) vipsProvider, _ := image_provider_vips.NewProvider(image_provider_vips.Config{}) app := piko.New(
piko.WithImage(
media.Image().
Provider("vips", vipsProvider).
MaxFileSizeMB(50).
WithVariant("thumb", media.Variant().Size(200, 200).Cover().Build()).
Build(),
),
)
func WithImageProvider ¶
func WithImageProvider(name string, provider image_domain.TransformerPort) Option
WithImageProvider registers a named image provider with the image service. The first provider registered becomes the default unless WithDefaultImageProvider is called.
If no providers are registered, the image service will be nil and components like piko:img will gracefully degrade to basic HTML output without responsive image features.
Takes name (string) which identifies this provider. Takes provider (image_domain.TransformerPort) which provides image transformation capabilities.
Returns Option which configures the container with the provider.
Example usage: import imaging "piko.sh/piko/wdk/media/image_provider_imaging" imgProvider, _ := imaging.NewProvider(imaging.Config{}) app := piko.New(
piko.WithImageProvider("imaging", imgProvider),
)
func WithImageService ¶
func WithImageService(service image_domain.Service) Option
WithImageService sets a custom image service for the application.
This gives you full control over image transformation, including:
- Using different transformer adapters (e.g., vips for high performance)
- Configuring custom storage backends for image caching
- Setting custom security limits and allowed formats
Most users should use WithImageTransformer instead to register individual transformers.
Takes service (image_domain.Service) which provides the image transformation implementation.
Returns Option which configures the application to use the given service.
Example with vips transformer: import "piko.sh/piko/wdk/media/image_provider_vips" vipsTransformer, _ := image_provider_vips.NewProvider(config)
transformers := map[string]image_domain.TransformerPort{
"vips": vipsTransformer,
}
imageService, _ := image_domain.NewService(transformers, "vips", config) app := piko.New(piko.WithImageService(imageService))
func WithJSONProvider ¶
WithJSONProvider activates a JSON encoding provider, replacing the default standard-library implementation for the entire application.
Takes provider (json.Provider) which supplies the JSON implementation.
Returns Option which activates the provider during bootstrap.
Example:
import sonicjson "piko.sh/piko/wdk/json/json_provider_sonic"
ssr := piko.New(
piko.WithJSONProvider(sonicjson.New()),
)
func WithJSONTypeInspectorCache ¶
func WithJSONTypeInspectorCache() Option
WithJSONTypeInspectorCache configures the TypeInspectorManager to use a JSON file-based cache.
Returns Option which applies the JSON cache configuration.
func WithLLMProvider ¶
func WithLLMProvider(name string, provider llm_domain.LLMProviderPort) Option
WithLLMProvider registers a named LLM provider instance with the default LLM service. If multiple providers are registered, use WithDefaultLLMProvider to specify which one is the default.
LLM providers handle completion and streaming requests to language models. Multiple providers enable fallback scenarios and cost optimisation strategies.
Takes name (string) which identifies this provider for later reference. Takes provider (llm_domain.LLMProviderPort) which handles LLM requests.
Returns Option which configures the container with the LLM provider.
Example: import (
"piko.sh/piko" "piko.sh/piko/wdk/llm/llm_provider_anthropic" "piko.sh/piko/wdk/llm/llm_provider_openai"
) // Create providers anthropicProvider := llm_provider_anthropic.NewProvider(anthropicConfig) openaiProvider := llm_provider_openai.NewProvider(openaiConfig) // Register multiple providers with fallback capability app := piko.New(
piko.WithLLMProvider("anthropic", anthropicProvider),
piko.WithLLMProvider("openai", openaiProvider),
piko.WithDefaultLLMProvider("anthropic"),
) // Later, use specific provider or fallback llmService, _ := llm.GetDefaultService() response, err := llmService.CompleteWithProvider(ctx, "openai", request)
func WithLLMService ¶
func WithLLMService(service llm_domain.Service) Option
WithLLMService sets a fully configured LLM service instance. This overrides the default LLM service creation and provider registration.
Takes service (llm_domain.Service) which is the configured LLM service.
Returns Option which applies the LLM service to the container.
Example: import (
"piko.sh/piko" "piko.sh/piko/wdk/llm" "piko.sh/piko/wdk/llm/llm_provider_anthropic"
) // Create and configure a custom LLM service llmService := llm.NewService("anthropic") anthropicProvider := llm_provider_anthropic.NewProvider(config) llmService.RegisterProvider("anthropic", anthropicProvider) llmService.SetDefaultProvider("anthropic") // Configure budgets and rate limits
llmService.SetBudget("user:123", &llm.BudgetConfig{
MaxDailyCost: 10.0,
})
llmService.SetRateLimits("global", 100, 100000) // Use the custom service app := piko.New(
piko.WithLLMService(llmService),
)
func WithLibServePath ¶
WithLibServePath sets the URL path prefix for serving internal library files.
Takes path (string) which is the value to apply.
Returns Option which the bootstrap consumes when applied.
func WithLogLevel ¶
WithLogLevel sets the application log level. Accepts standard slog level strings: "debug", "info", "warn", "error".
PIKO_LOG_LEVEL environment variable, when set, overrides this option for the bootstrap logger before any options apply.
Takes level (string) which is the value to apply.
Returns Option which the bootstrap consumes when applied.
func WithLogger ¶
func WithLogger(cfg logger_dto.Config) Option
WithLogger replaces the entire logger configuration.
Takes cfg (logger_dto.Config) which is the value to apply.
Returns Option which the bootstrap consumes when applied.
func WithMarkdownParser ¶
func WithMarkdownParser(parser markdown_domain.MarkdownParserPort) Option
WithMarkdownParser sets the markdown parser implementation used by the collection service for processing markdown content.
When a parser is configured, the collection service will register a markdown content provider that uses it to parse .md files. If no parser is set, the markdown collection provider is not registered.
Takes parser (markdown_domain.MarkdownParserPort) which provides the markdown parsing implementation.
Returns Option which configures the server to use the given parser.
Example usage with the goldmark provider:
import "piko.sh/piko/wdk/markdown/markdown_provider_goldmark"
server := piko.New(
piko.WithMarkdownParser(markdown_provider_goldmark.NewParser()),
)
func WithMaxConcurrentRequests ¶
WithMaxConcurrentRequests sets the maximum number of in-flight requests the server will process simultaneously. Zero disables the limit.
Takes n (int) which is the value to apply.
Returns Option which the bootstrap consumes when applied.
func WithMaxMultipartFormBytes ¶
WithMaxMultipartFormBytes sets the maximum in-memory size for multipart form data.
Takes n (int64) which is the value to apply.
Returns Option which the bootstrap consumes when applied.
func WithMemoryRegistryCache ¶
func WithMemoryRegistryCache() Option
WithMemoryRegistryCache configures the default RegistryService to be built with an in-memory cache.
Returns Option which applies the memory cache configuration.
func WithMetricsExporter ¶
func WithMetricsExporter(exporter MetricsExporter) Option
WithMetricsExporter configures a metrics exporter for the health probe server. When enabled, OTEL metrics are exposed at /metrics on port 9090 by default.
The exporter integrates with the OTEL MeterProvider, so all metrics recorded through OTEL instrumentation will be available for scraping.
Example with Prometheus: import prometheus "piko.sh/piko/wdk/metrics/metrics_exporter_prometheus" server := piko.New(
piko.WithMetricsExporter(prometheus.New()),
) The metrics endpoint path can be configured via the healthProbe.metricsPath config option.
Takes exporter (MetricsExporter) which provides the metrics export backend.
Returns Option which configures the metrics exporter on the server.
func WithMonitoring ¶
func WithMonitoring(opts ...MonitoringOption) Option
WithMonitoring enables the gRPC monitoring server for TUI integration. The monitoring server exposes telemetry data (metrics, traces, system stats) via gRPC on port 9091 by default.
When enabled, the following gRPC services are available:
- HealthService - Basic health checks
- MetricsService - OTEL metrics, traces, system stats, file descriptors
- OrchestratorInspectorService - Task and workflow status (if orchestrator enabled)
- RegistryInspectorService - Artefact status (if registry enabled)
The monitoring service also provides span processors and metric readers for integration with the OTEL SDK, allowing traces and metrics to be captured for the TUI without requiring external backends like Jaeger or Prometheus.
Takes opts (...MonitoringOption) which configures the monitoring server.
Returns Option which enables monitoring when passed to New.
Example: server := piko.New(
piko.WithMonitoring(),
) With custom configuration: server := piko.New(
piko.WithMonitoring(
piko.WithMonitoringAddress(":9092"),
piko.WithMonitoringBindAddress("0.0.0.0"),
),
)
func WithNotificationProvider ¶
func WithNotificationProvider(name string, provider notification_domain.NotificationProviderPort) Option
WithNotificationProvider registers a named notification provider instance with the default notification service. If multiple providers are registered, use WithDefaultNotificationProvider to specify which one is the default.
Takes name (string) which identifies this provider for later reference. Takes provider (notification_domain.NotificationProviderPort) which handles notification delivery.
Returns Option which configures the container with the notification provider.
Example: import (
"piko.sh/piko" "piko.sh/piko/wdk/notification/notification_provider_webhook"
) webhookProvider := notification_provider_webhook.NewProvider(config) app := piko.New(
piko.WithNotificationProvider("webhook", webhookProvider),
piko.WithDefaultNotificationProvider("webhook"),
)
func WithOTLP ¶
func WithOTLP(o OtlpConfig) Option
WithOTLP replaces the entire OpenTelemetry Protocol exporter configuration.
Takes o (OtlpConfig) which is the value to apply.
Returns Option which the bootstrap consumes when applied.
func WithOTLPEnabled ¶
WithOTLPEnabled controls whether OTLP exporting is active.
Takes enabled (bool) which is the value to apply.
Returns Option which the bootstrap consumes when applied.
func WithOTLPEndpoint ¶
WithOTLPEndpoint sets the OTLP collector endpoint.
Takes endpoint (string) which is the value to apply.
Returns Option which the bootstrap consumes when applied.
func WithOTLPHeaders ¶
WithOTLPHeaders sets the HTTP headers sent with OTLP requests.
Takes headers (map[string]string) which is the value to apply.
Returns Option which the bootstrap consumes when applied.
func WithOTLPInsecureTLS ¶
WithOTLPInsecureTLS controls whether TLS certificate verification is disabled for the OTLP connection.
Takes insecure (bool) which is the value to apply.
Returns Option which the bootstrap consumes when applied.
func WithOTLPProtocol ¶
WithOTLPProtocol sets the OTLP transport protocol. Valid values: "grpc", "http", "https".
Takes protocol (string) which is the value to apply.
Returns Option which the bootstrap consumes when applied.
func WithOTLPTraceSampleRate ¶
WithOTLPTraceSampleRate sets the fraction of traces to sample (0.0 to 1.0).
Takes rate (float64) which is the value to apply.
Returns Option which the bootstrap consumes when applied.
func WithOrchestratorService ¶
func WithOrchestratorService(service orchestrator_domain.OrchestratorService) Option
WithOrchestratorService provides a custom OrchestratorService implementation.
Takes service (OrchestratorService) which is the service to use for orchestration.
Returns Option which configures the application with the given service.
func WithPMLTransformer ¶
func WithPMLTransformer(transformer pml_domain.Transformer) Option
WithPMLTransformer sets a custom PML transformation engine.
Use it to customise the PikoML to HTML transformation process. If not provided, a default transformer with all built-in components will be used.
Takes transformer (pml_domain.Transformer) which handles the PikoML to HTML conversion.
Returns Option which configures the container with the custom transformer.
func WithPagesSourceDir ¶
WithPagesSourceDir sets the directory for page definition files.
Takes dir (string) which is the value to apply.
Returns Option which the bootstrap consumes when applied.
func WithPartialServePath ¶
WithPartialServePath sets the URL path prefix for serving partials.
Takes path (string) which is the value to apply.
Returns Option which the bootstrap consumes when applied.
func WithPartialsSourceDir ¶
WithPartialsSourceDir sets the directory for partial definition files.
Takes dir (string) which is the value to apply.
Returns Option which the bootstrap consumes when applied.
func WithPdfsSourceDir ¶
WithPdfsSourceDir sets the directory for PDF template source files.
Takes dir (string) which is the value to apply.
Returns Option which the bootstrap consumes when applied.
func WithPikoDefaultCSP ¶
func WithPikoDefaultCSP() Option
WithPikoDefaultCSP configures the Content-Security-Policy with Piko's recommended default settings. This provides a secure baseline that works with Piko's built-in features including font loading, inline styles, and the async font loader script.
The default policy includes:
- default-src 'self'
- style-src 'self' 'unsafe-inline' https://fonts.googleapis.com
- script-src-attr 'unsafe-hashes' 'sha256-...' (for font loader)
- font-src 'self' https://fonts.gstatic.com data:
- img-src 'self' data: blob: https:
- connect-src 'self'
Returns Option which applies the default CSP configuration to the server.
Example: server := piko.New(
piko.WithPikoDefaultCSP(),
)
func WithPort ¶
WithPort sets the TCP port for the main HTTP server.
Takes port (int) which specifies the port number (e.g. 8080, 443).
Returns Option which sets the server port.
func WithPostgresMaxConns ¶
WithPostgresMaxConns sets the maximum number of connections in the PostgreSQL pool.
Takes n (int32) which is the value to apply.
Returns Option which the bootstrap consumes when applied.
func WithPostgresMinConns ¶
WithPostgresMinConns sets the minimum number of connections kept in the PostgreSQL pool.
Takes n (int32) which is the value to apply.
Returns Option which the bootstrap consumes when applied.
func WithPostgresURL ¶
WithPostgresURL sets the PostgreSQL connection URL.
Takes url (string) which is the value to apply.
Returns Option which the bootstrap consumes when applied.
func WithProfiling ¶
func WithProfiling(opts ...ProfilingOption) Option
WithProfiling enables the pprof HTTP debug server. The server exposes profiling endpoints at /_piko/debug/pprof/ on a dedicated port (default 6060).
When enabled, block and mutex profiling rates are configured so that /_piko/debug/pprof/block and /_piko/debug/pprof/mutex return meaningful data.
The server starts during application bootstrap and stops during graceful shutdown.
Takes opts (...ProfilingOption) which provides optional settings:
- WithProfilingPort(6060): sets the HTTP listen port.
- WithProfilingBindAddress("localhost"): sets the bind address.
- WithProfilingBlockRate(1000): sets the block profile rate.
- WithProfilingMutexFraction(10): sets the mutex profile fraction.
- WithProfilingMemProfileRate(0): sets the memory profile sample rate.
- WithProfilingRollingTrace(): enables bounded rolling trace capture.
- WithProfilingRollingTraceMinAge(15 * time.Second): adjusts retained trace age.
- WithProfilingRollingTraceMaxBytes(16 * 1024 * 1024): adjusts trace buffer size.
Returns Option which configures the container with profiling settings.
Example:
server := piko.New(
piko.WithProfiling(),
)
With custom port:
server := piko.New(
piko.WithProfiling(
piko.WithProfilingPort(7070),
),
)
func WithPublicDomain ¶
WithPublicDomain sets the public domain used for CORS allowed origins and absolute URLs. Empty string allows all origins.
Takes domain (string) which is the value to apply.
Returns Option which the bootstrap consumes when applied.
func WithRateLimit ¶
func WithRateLimit(rl RateLimitConfig) Option
WithRateLimit sets the request rate limiting configuration. Disabled by default; pass Enabled=true to activate.
Takes rl (RateLimitConfig) which is the value to apply.
Returns Option which the bootstrap consumes when applied.
func WithRateLimitEnabled ¶
WithRateLimitEnabled enables or disables HTTP request rate limiting. Rate limiting is disabled by default to prevent accidental self-limiting when deployed behind a reverse proxy without WithTrustedProxies configured.
Takes enabled (bool) which controls whether rate limiting is active.
Returns Option which configures rate limiting on the server.
Example: server := piko.New(
piko.WithTrustedProxies("10.0.0.0/8"),
piko.WithRateLimitEnabled(true),
)
func WithRegistryMetadataCacheConfig ¶
func WithRegistryMetadataCacheConfig(registryCacheConfig RegistryMetadataCacheConfig) Option
WithRegistryMetadataCacheConfig configures the Registry service's metadata cache. The metadata cache stores artefact metadata to reduce database queries and improve Registry performance, especially for frequently accessed artefacts.
The cache uses weight-based eviction (calculated by the approximate memory size of artefact metadata) and access-based expiration (TTL resets on every read).
Takes registryCacheConfig (RegistryMetadataCacheConfig) which specifies the cache settings including maximum weight, TTL, and whether stats are enabled.
Returns Option which configures the metadata cache when applied.
Example: import "piko.sh/piko" import "time" server, err := piko.New(
piko.WithRegistryMetadataCacheConfig(piko.RegistryMetadataCacheConfig{
MaxWeight: 512 * 1024 * 1024, // 512 MB
TTL: time.Hour, // 1 hour sliding window
StatsEnabled: true, // Enable observability
}),
)
func WithRegistryService ¶
func WithRegistryService(service registry_domain.RegistryService) Option
WithRegistryService provides a custom RegistryService implementation.
Takes service (RegistryService) which provides the registry service to use.
Returns Option which configures the application with the given registry.
func WithRelaxedCSP ¶
func WithRelaxedCSP() Option
WithRelaxedCSP configures a permissive CSP policy for legacy applications.
Returns Option which applies a relaxed CSP policy to the server.
WARNING: This policy allows 'unsafe-inline' and 'unsafe-eval', which significantly reduces XSS protection. Use only when migrating legacy code that cannot be updated to use token-based CSP or content hashes.
The policy includes:
- default-src 'self'
- script-src 'self' 'unsafe-inline' 'unsafe-eval'
- style-src 'self' 'unsafe-inline'
- img-src 'self' data: https:
- font-src 'self' data:
- connect-src 'self'
- frame-ancestors 'self' (clickjacking protection)
Example: server := piko.New(
piko.WithRelaxedCSP(),
)
func WithReporting ¶
func WithReporting(r ReportingConfig) Option
WithReporting configures the Reporting-Endpoints HTTP header.
Takes r (ReportingConfig) which is the value to apply.
Returns Option which the bootstrap consumes when applied.
func WithReportingEndpoints ¶
func WithReportingEndpoints(endpoints ...ReportingEndpoint) Option
WithReportingEndpoints enables the Reporting-Endpoints HTTP header and configures the specified reporting endpoints. These endpoints can be referenced by CSP report-to directives and other web platform reporting APIs (Network Error Logging, Deprecation Reports, Crash Reports).
Takes endpoints (...ReportingEndpoint) which specifies the reporting endpoints to configure.
Returns Option which configures the server with the reporting endpoints.
Example: server := piko.New(
piko.WithReportingEndpoints(
piko.ReportingEndpoint{
Name: "csp-violations",
URL: "https://monitoring.example.com/reports/csp",
},
piko.ReportingEndpoint{
Name: "deprecations",
URL: "https://monitoring.example.com/reports/deprecations",
},
),
piko.WithCSP(func(b *piko.CSPBuilder) {
b.WithStrictPolicy().
ReportToDirective("csp-violations")
}),
) The resulting headers will be: Reporting-Endpoints: csp-violations="...", deprecations="..." Content-Security-Policy: ...; report-to csp-violations
func WithRequestTimeout ¶
WithRequestTimeout sets the maximum duration for dynamic HTTP requests. Zero disables the timeout middleware.
Takes d (time.Duration) which is the value to apply.
Returns Option which the bootstrap consumes when applied.
func WithSRI ¶
WithSRI controls whether Subresource Integrity (SRI) hashes are added to script and link tags in rendered HTML. Enabled by default; disable for development environments where assets change frequently.
Takes enabled (bool) which controls whether integrity attributes are emitted.
Returns Option which configures the SRI setting.
func WithSandbox ¶
func WithSandbox(s SandboxConfig) Option
WithSandbox configures filesystem sandboxing for Piko internals.
Takes s (SandboxConfig) which is the value to apply.
Returns Option which the bootstrap consumes when applied.
func WithSecurityHeaders ¶
func WithSecurityHeaders(headers SecurityHeadersConfig) Option
WithSecurityHeaders sets the HTTP security header policy. Pass a fully populated SecurityHeadersConfig.
Takes headers (SecurityHeadersConfig) which is the value to apply.
Returns Option which the bootstrap consumes when applied.
func WithShutdownDrainDelay ¶
WithShutdownDrainDelay sets the duration to wait after marking the instance as not ready (readiness returns 503) before shutting down the HTTP server. This gives load balancers time to deregister the instance during rolling deploys.
Default: 0s in dev mode, 3s in production.
Takes delay (time.Duration) which specifies how long to wait.
Returns Option which configures the shutdown drain delay.
func WithSpamDetector ¶
func WithSpamDetector(name string, detector spamdetect_domain.Detector) Option
WithSpamDetector registers a named spam detection detector with the service.
Takes name (string) which identifies the detector. Takes detector (spamdetect_domain.Detector) which handles spam analysis.
Returns Option which registers the detector.
func WithSpamFeedbackStore ¶
func WithSpamFeedbackStore(store spamdetect_domain.FeedbackStore) Option
WithSpamFeedbackStore configures the feedback persistence backend for spam detection.
Takes store (spamdetect_domain.FeedbackStore) which persists spam/ham feedback.
Returns Option which configures the feedback store.
func WithStartupBanner ¶
WithStartupBanner controls whether the startup information banner is displayed when the server starts. Defaults to true.
Takes enabled (bool) which specifies whether the banner is shown.
Returns Option which configures the startup banner setting.
func WithStorageDispatcher ¶
func WithStorageDispatcher(storageDispatcherConfig storage_domain.DispatcherConfig) Option
WithStorageDispatcher enables and configures the background dispatcher for the default storage service.
Takes storageDispatcherConfig (storage_domain.DispatcherConfig) which controls batching, retries, and queue sizes.
Returns Option which configures the dispatcher on the container.
func WithStoragePresign ¶
func WithStoragePresign(p StoragePresignConfig) Option
WithStoragePresign replaces the entire presigned URL configuration.
Takes p (StoragePresignConfig) which is the value to apply.
Returns Option which the bootstrap consumes when applied.
func WithStoragePresignBaseURL ¶
WithStoragePresignBaseURL sets the base URL prefix for presigned storage URLs. This is essential when Piko is used as a headless CMS where content is consumed by a frontend on a different host or port.
Without this option, presigned URLs will be relative paths that do not work cross-origin.
Takes baseURL (string) which is the full base URL including scheme and host, e.g., "http://localhost:8080" or "https://cms.example.com".
Returns Option which configures the presign base URL on the storage service.
func WithStoragePresignDefaultExpiry ¶
WithStoragePresignDefaultExpiry sets the default validity duration for presigned URLs.
Takes d (time.Duration) which is the value to apply.
Returns Option which the bootstrap consumes when applied.
func WithStoragePresignDefaultMaxSize ¶
WithStoragePresignDefaultMaxSize sets the default maximum upload size in bytes.
Takes size (int64) which is the value to apply.
Returns Option which the bootstrap consumes when applied.
func WithStoragePresignMaxExpiry ¶
WithStoragePresignMaxExpiry sets the maximum validity duration for presigned URLs.
Takes d (time.Duration) which is the value to apply.
Returns Option which the bootstrap consumes when applied.
func WithStoragePresignMaxMaxSize ¶
WithStoragePresignMaxMaxSize sets the absolute maximum upload size in bytes.
Takes size (int64) which is the value to apply.
Returns Option which the bootstrap consumes when applied.
func WithStoragePresignRateLimit ¶
WithStoragePresignRateLimit sets the per-IP rate limit for presigned upload requests.
Takes rpm (int) which is the value to apply.
Returns Option which the bootstrap consumes when applied.
func WithStoragePresignSecret ¶
WithStoragePresignSecret sets the HMAC secret for signing presign tokens.
Takes secret (string) which is the value to apply.
Returns Option which the bootstrap consumes when applied.
func WithStorageProvider ¶
func WithStorageProvider(name string, provider storage_domain.StorageProviderPort) Option
WithStorageProvider registers a named storage provider instance with the default storage service. If multiple providers are registered, use WithDefaultStorageProvider to specify which one is the default.
Takes name (string) which identifies the storage provider. Takes provider (StorageProviderPort) which is the storage provider instance.
Returns Option which configures the container with the storage provider.
func WithStoragePublicBaseURL ¶
WithStoragePublicBaseURL sets the base URL for public storage URLs.
When set, public URLs are generated as absolute URLs (e.g., "http://localhost:8080/_piko/storage/public/..."). When empty, URLs are generated as relative paths (e.g., "/_piko/storage/public/..."). This is required when the website and CMS/API run on different ports or hosts.
Takes baseURL (string) which is the full base URL including scheme and host, e.g., "http://localhost:8080" or "https://cms.example.com".
Returns Option which configures the public base URL on the storage service.
func WithStorageService ¶
func WithStorageService(service storage_domain.Service) Option
WithStorageService overrides the default storage service with a custom implementation. Use it for testing or providing a fully configured service with custom behaviour.
Takes service (storage_domain.Service) which is the custom storage service.
Returns Option which configures the container to use the provided service.
func WithStrictCSP ¶
func WithStrictCSP() Option
WithStrictCSP configures a strict Content Security Policy following Google's recommendations, using per-request tokens and 'strict-dynamic' for script execution to provide strong XSS protection while allowing dynamically loaded scripts.
The policy includes:
- default-src 'self'
- script-src 'strict-dynamic' {{REQUEST_TOKEN}} (token-based)
- style-src 'self' {{REQUEST_TOKEN}} (token-based)
- object-src 'none' (blocks plugins like Flash)
- base-uri 'self' (prevents base tag hijacking)
- frame-ancestors 'self' (clickjacking protection)
- upgrade-insecure-requests
Returns Option which applies the strict CSP configuration to the server.
IMPORTANT: This policy uses request tokens. Templates must use {{ .CSPTokenAttr }} on inline script and style elements: <script {{ .CSPTokenAttr }}>console.log("safe");</script> <style {{ .CSPTokenAttr }}>.my-class { color: red; }</style> Example: server := piko.New(
piko.WithStrictCSP(),
)
func WithSystemStorageProvider ¶
func WithSystemStorageProvider(provider storage_domain.StorageProviderPort) Option
WithSystemStorageProvider registers a storage provider for Piko internal operations such as registry blob storage.
If not set, Piko internals will use the "default" provider. Set it to separate application storage from Piko's internal storage needs.
Example: Use GCS for app storage but keep Piko internals on local disk: piko.New(
piko.WithStorageProvider("default", gcsProvider), // App uses GCS
piko.WithSystemStorageProvider(diskProvider), // Piko uses disk
)
Takes provider (StorageProviderPort) which provides the storage backend for Piko internal operations.
Returns Option which configures the container with the system storage provider.
func WithTLS ¶
WithTLS enables TLS/HTTPS for the main server. Sub-options configure certificate paths, mTLS, and hot-reload settings.
Takes opts (...TLSOption) which provides optional TLS configuration:
- WithTLSCertFile("/path/to/cert.pem"): sets the certificate path.
- WithTLSKeyFile("/path/to/key.pem"): sets the private key path.
- WithTLSClientCA("/path/to/ca.pem"): enables mTLS with client CA.
- WithTLSClientAuth("require_and_verify"): sets client auth mode.
- WithTLSMinVersion("1.3"): sets minimum TLS version.
- WithTLSHotReload(true): enables certificate hot-reload.
- WithTLSRedirectHTTP("80"): starts an HTTP-to-HTTPS redirect listener.
Returns Option which configures the container with TLS settings.
func WithTrustedProxies ¶
WithTrustedProxies configures the CIDR ranges of reverse proxies trusted to set X-Forwarded-For headers. When a request arrives from one of these ranges, the real client IP is extracted from forwarding headers rather than using the connection IP directly.
Common values include RFC 1918 private ranges: "10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16". For Cloudflare deployments, add their published IP ranges from https://www.cloudflare.com/ips/.
Takes cidrs (...string) which are the CIDR ranges to trust.
Returns Option which configures the trusted proxy list on the server.
Example: server := piko.New(
piko.WithTrustedProxies("10.0.0.0/8", "172.16.0.0/12"),
)
func WithValidator ¶
func WithValidator(v bootstrap.StructValidator) Option
WithValidator provides a struct validator implementation. Any type that implements the bootstrap.StructValidator interface (a single Struct(any) error method) can be used.
The recommended implementation is the validation_provider_playground WDK module, which provides a go-playground/validator backed validator with Piko's built-in Money and Decimal validation rules pre-registered.
When no validator is configured, struct validation is skipped entirely.
Takes v (bootstrap.StructValidator) which is the validator to use.
Returns Option which configures Piko to use the provided validator.
Example:
import (
"piko.sh/piko"
playground "piko.sh/piko/wdk/validation/validation_provider_playground"
)
validator := playground.NewValidator()
server, err := piko.New(
piko.WithValidator(validator),
)
func WithVideoProvider ¶
func WithVideoProvider(name string, provider video_domain.TranscoderPort) Option
WithVideoProvider registers a named video provider with the video service. The first provider registered becomes the default unless WithDefaultVideoProvider is called.
If no providers are registered, the video service will be nil and components like piko:video will gracefully degrade to basic HTML output without transcoding features.
Takes name (string) which identifies the provider for later reference. Takes provider (video_domain.TranscoderPort) which provides the video transcoding implementation.
Returns Option which configures the container with the video provider.
Example usage: import astiav "piko.sh/piko/wdk/media/video_provider_astiav" vidProvider, _ := astiav.NewProvider(astiav.Config{}) app := piko.New(
piko.WithVideoProvider("astiav", vidProvider),
)
func WithVideoService ¶
func WithVideoService(service video_domain.Service) Option
WithVideoService sets a custom video service implementation.
This gives full control over video transcoding, including the ability to:
- Use different transcoder adapters (e.g., astiav for FFmpeg-based transcoding)
- Configure custom encoding profiles and quality settings
- Set custom security limits and allowed codecs
Most users should use WithVideoTranscoder instead to register individual transcoders.
Example with astiav transcoder: import "piko.sh/piko/wdk/media/video_provider_astiav" astiavTranscoder, _ := video_provider_astiav.NewProvider(config)
transcoders := map[string]video_domain.TranscoderPort{
"astiav": astiavTranscoder,
}
videoService, _ := video_domain.NewService(transcoders, "astiav", config) app := piko.New(piko.WithVideoService(videoService))
Takes service (video_domain.Service) which provides the video transcoding implementation.
Returns Option which configures the container with the video service.
func WithWatchMode ¶
WithWatchMode controls whether file system watching for hot-reloading is enabled. This is typically derived from the run mode (dev -> true, prod -> false) and does not need to be set manually.
Takes enabled (bool) which controls whether watch mode is active.
Returns Option which configures the watch mode setting.
type OtlpConfig ¶
type OtlpConfig = config.OtlpConfig
OtlpConfig holds configuration for OpenTelemetry Protocol exporting. Pass to WithOTLP.
type OtlpTLSConfig ¶
type OtlpTLSConfig = config.OtlpTLSConfig
OtlpTLSConfig holds TLS settings for the OTLP exporter connection.
type PaginationOptions ¶
type PaginationOptions = runtime.PaginationOptions
PaginationOptions specifies offset and limit for pagination.
func NewPaginationOptions ¶
func NewPaginationOptions(limit, offset int) PaginationOptions
NewPaginationOptions creates pagination parameters.
Takes limit (int) which specifies the maximum number of items to return. Takes offset (int) which specifies the number of items to skip.
Returns PaginationOptions which contains the configured pagination settings.
Example: pagination := piko.NewPaginationOptions(10, 20) // Limit 10, Offset 20
type PreviewScenario ¶
type PreviewScenario = templater_dto.PreviewScenario
PreviewScenario describes a single named preview scenario for a component. The Preview() convention function returns a slice of these, providing sample data for rendering the component in the dev tools preview panel.
type ProfilingOption ¶
type ProfilingOption = bootstrap.ProfilingOption
ProfilingOption configures the pprof HTTP debug server.
func WithProfilingBindAddress ¶
func WithProfilingBindAddress(addr string) ProfilingOption
WithProfilingBindAddress sets the network address for the pprof server to bind to.
Takes addr (string) which specifies the bind address.
Returns ProfilingOption which configures the pprof server bind address.
func WithProfilingBlockRate ¶
func WithProfilingBlockRate(rate int) ProfilingOption
WithProfilingBlockRate sets the block profiling rate. After calling runtime.SetBlockProfileRate, the profiler samples one blocking event per this many nanoseconds of blocking.
Takes rate (int) which specifies the sampling rate in nanoseconds.
Returns ProfilingOption which configures the block profile rate.
func WithProfilingMemProfileRate ¶
func WithProfilingMemProfileRate(rate int) ProfilingOption
WithProfilingMemProfileRate sets the memory profiling sample rate; 0 uses the Go runtime default of 512KB and lower values capture smaller allocations at higher cost.
Takes rate (int) which specifies the sampling rate in bytes.
Returns ProfilingOption which configures the memory profile rate.
func WithProfilingMutexFraction ¶
func WithProfilingMutexFraction(fraction int) ProfilingOption
WithProfilingMutexFraction sets the mutex profiling fraction. On average 1/n mutex contention events are reported.
Takes fraction (int) which specifies the sampling fraction.
Returns ProfilingOption which configures the mutex profile fraction.
func WithProfilingPort ¶
func WithProfilingPort(port int) ProfilingOption
WithProfilingPort sets the port for the pprof HTTP server.
Takes port (int) which specifies the port number to listen on.
Returns ProfilingOption which configures the pprof server port.
func WithProfilingRollingTrace ¶
func WithProfilingRollingTrace() ProfilingOption
WithProfilingRollingTrace enables an in-memory rolling execution trace buffer for the profiling server. The trace window can later be downloaded from `/_piko/profiler/trace/recent`.
Returns ProfilingOption which enables rolling trace capture with safe defaults.
func WithProfilingRollingTraceMaxBytes ¶
func WithProfilingRollingTraceMaxBytes(maxBytes uint64) ProfilingOption
WithProfilingRollingTraceMaxBytes sets the in-memory budget hint for the rolling trace recorder. Implicitly enables rolling trace capture if not already enabled.
Takes maxBytes (uint64) which specifies the approximate buffer size.
Returns ProfilingOption which configures the rolling trace memory budget.
func WithProfilingRollingTraceMinAge ¶
func WithProfilingRollingTraceMinAge(minAge time.Duration) ProfilingOption
WithProfilingRollingTraceMinAge sets how much recent trace history the rolling trace recorder should try to retain. Implicitly enables rolling trace capture if not already enabled.
Takes minAge (time.Duration) which specifies the retention target.
Returns ProfilingOption which configures the rolling trace minimum age.
type PublicConfig ¶
type PublicConfig struct {
// BaseDir is the base directory path for server files; empty uses the default.
BaseDir string
// AssetsSourceDir is the path to the folder that holds static assets.
AssetsSourceDir string
// PagesSourceDir is the path to the folder containing page templates.
PagesSourceDir string
// Port specifies the TCP port number; 0 uses the default from the config.
Port int
// WatchMode enables automatic rebuilding when source files change.
WatchMode bool
}
PublicConfig defines the set of configurable options that can be set programmatically when embedding the Piko server.
type RateLimit ¶
type RateLimit = daemon_domain.RateLimit
RateLimit defines rate limiting configuration.
type RateLimitConfig ¶
type RateLimitConfig = config.RateLimitConfig
RateLimitConfig configures request rate limiting with trusted proxy support.
type RateLimitKeyFunc ¶
type RateLimitKeyFunc = daemon_domain.RateLimitKeyFunc
RateLimitKeyFunc extracts a rate limit key from a request.
type RateLimitTierConfig ¶
type RateLimitTierConfig = config.RateLimitTierConfig
RateLimitTierConfig configures rate limits for a tier (global or actions).
type RateLimitable ¶
type RateLimitable = daemon_domain.RateLimitable
RateLimitable is an interface for configuring rate limiting.
type RawBody ¶
type RawBody = daemon_dto.RawBody
RawBody provides access to the unparsed request body. Use this when you need to verify signatures or parse custom formats.
Example:
func (a *WebhookAction) Call(body piko.RawBody) (Response, error) {
signature := a.Request().RawRequest.Header.Get("X-Signature")
if !verifySignature(body.Bytes(), signature) {
return Response{}, piko.Unauthorised("invalid signature")
}
return Response{OK: true}, nil
}
type RegistryMetadataCacheConfig ¶
type RegistryMetadataCacheConfig struct {
// MaxWeight is the maximum total weight (in bytes) the cache may hold,
// calculated by a custom weigher that estimates the memory footprint of
// each artefact metadata entry and evicting the least recently used
// entries when the limit is reached.
// Default: 256 MB (256 * 1024 * 1024).
MaxWeight uint64
// TTL is the time-to-live for cached entries, using access-based
// expiration that resets on every read to implement a sliding window
// policy ideal for keeping frequently accessed artefacts in cache.
// Default: 30 minutes.
TTL time.Duration
// StatsEnabled enables collection of cache performance statistics,
// reserved for future functionality and currently having no effect
// since statistics are always available via the cache's Stats() method.
// Default: false.
StatsEnabled bool
}
RegistryMetadataCacheConfig configures the metadata cache for the Registry service. This cache stores artefact metadata to reduce database queries and improve performance.
func DefaultRegistryMetadataCacheConfig ¶
func DefaultRegistryMetadataCacheConfig() RegistryMetadataCacheConfig
DefaultRegistryMetadataCacheConfig returns the default configuration for the Registry metadata cache.
Returns RegistryMetadataCacheConfig which provides sensible defaults with 256 MB max weight, 30 minute TTL, and stats disabled.
type ReportingConfig ¶
type ReportingConfig = config.ReportingConfig
ReportingConfig configures the Reporting-Endpoints HTTP header.
type ReportingEndpoint ¶
type ReportingEndpoint = config.ReportingEndpoint
ReportingEndpoint defines a single reporting endpoint for the Reporting-Endpoints header. These endpoints can be referenced by CSP report-to directives and other reporting APIs.
type RequestBuilder ¶
type RequestBuilder = pikotest_domain.RequestBuilder
RequestBuilder builds RequestData for tests. Use NewTestRequest to create a builder.
func NewTestRequest ¶
func NewTestRequest(method, path string) *RequestBuilder
NewTestRequest creates a new RequestBuilder for the specified HTTP method and path. This is the primary entry point for building test requests with proper context injection.
Takes method (string) which specifies the HTTP method (GET, POST, etc.). Takes path (string) which specifies the request path.
Returns *RequestBuilder which provides a fluent interface for building test requests.
Example: request := piko.NewTestRequest("GET", "/customers").
WithQueryParam("sort", "desc").
Build(ctx)
type RequestData ¶
type RequestData = templater_dto.RequestData
RequestData encapsulates all information about an incoming HTTP request. It is made available within a component's Render function and includes the request context, URL, headers, and parsed form/query data.
type RequestMetadata ¶
type RequestMetadata = daemon_dto.RequestMetadata
RequestMetadata contains HTTP request information available to actions.
type ResourceLimitable ¶
type ResourceLimitable = daemon_domain.ResourceLimitable
ResourceLimitable is an interface that actions can implement to configure resource limits for protection against resource exhaustion.
type ResourceLimits ¶
type ResourceLimits = daemon_domain.ResourceLimits
ResourceLimits defines resource constraints for an action.
type ResponseWriter ¶
type ResponseWriter = daemon_dto.ResponseWriter
ResponseWriter allows actions to set response metadata.
type RobotsConfig ¶
type RobotsConfig = config.RobotsConfig
RobotsConfig holds settings for robots.txt generation.
type RobotsRuleGroup ¶
type RobotsRuleGroup = config.RobotsRuleGroup
RobotsRuleGroup holds a set of rules for one or more user agents.
type SEOConfig ¶
SEOConfig holds settings for SEO artefact generation including sitemap.xml and robots.txt. Use WithSEO to provide this configuration.
type SSECapable ¶
type SSECapable = daemon_domain.SSECapable
SSECapable is an interface that actions can implement to support Server-Sent Events (SSE) streaming for progressive updates.
Example:
func (a UploadAction) StreamProgress(stream *piko.SSEStream) error {
for progress := range uploadWithProgress(a.File) {
stream.Send("progress", progress)
}
return stream.SendComplete(UploadResponse{URL: finalURL})
}
type SSEStream ¶
type SSEStream = daemon_domain.SSEStream
SSEStream provides methods for sending Server-Sent Events.
type SSRServer ¶
type SSRServer struct {
// AppRouter is the HTTP router for web requests.
AppRouter *chi.Mux
// Container holds the dependency injection container for the server.
Container *bootstrap.Container
// PreBuildHook is called after the previous daemon is stopped and caches
// are invalidated, but before the new daemon starts building. This allows
// tests to reset spy statistics in a race-free window.
PreBuildHook func()
// contains filtered or unexported fields
}
SSRServer is the main struct for working with the Piko framework.
func New ¶
New creates and sets up a new SSRServer instance.
Configure the server through the supplied With* options. piko reads no configuration files and no environment variables by default. The single exception is the PIKO_LOG_LEVEL environment variable, which is consulted here to seed the bootstrap logger level before options are applied. Any explicit WithLogLevel option in opts overrides it.
Takes opts (...bootstrap.Option) which configures the server behaviour.
Returns *SSRServer which is ready for use with default router and config.
func (*SSRServer) Close ¶
func (*SSRServer) Close()
Close performs graceful cleanup of all services created during Generate(). Call this after Generate() when you do not intend to call Run(), to ensure background goroutines (orchestrator, coordinator, event bus, cache, etc.) are properly terminated.
Safe to call multiple times.
func (*SSRServer) Configure ¶
func (s *SSRServer) Configure(publicConfig PublicConfig)
Configure appends additional bootstrap options to the server based on the supplied PublicConfig. Equivalent to calling the corresponding With* options at piko.New time.
Takes publicConfig (PublicConfig) which specifies the configuration values to apply.
func (*SSRServer) Generate ¶
Generate produces a Piko build using the two-phase bootstrap process.
For dev-i mode, this also builds the daemon infrastructure to set up routes on the AppRouter, allowing the server to serve requests immediately after generation completes. The daemon is not started; use Run to actually start serving HTTP requests.
Takes runMode (string) which specifies the execution mode for the build.
Returns error when configuration bootstrap fails, interpreter provider is missing for dev-i mode, or the build process fails.
func (*SSRServer) GetHandler ¶
GetHandler returns the HTTP handler for serving requests, or nil if the daemon has not been built yet.
Use it to test without starting the full server. The daemon must be built first via Generate or Run.
Returns http.Handler which processes incoming HTTP requests.
func (*SSRServer) RegisterLifecycle ¶
func (s *SSRServer) RegisterLifecycle(component LifecycleComponent)
RegisterLifecycle adds a component to be managed during server startup and shutdown.
Components are started in the order they are added. OnStart is called before the HTTP server starts. During shutdown, components are stopped in reverse order (last added, first stopped).
If the component also implements HealthProbe, it will be added to the health monitoring system and shown via the /health, /live, and /ready endpoints.
May be called many times, but must be called before Run.
Takes component (LifecycleComponent) which is the component to add.
Example: ssr := piko.New() ssr.RegisterLifecycle(myDatabaseComponent) ssr.RegisterLifecycle(myCacheComponent) ssr.Run(actions, piko.RunModeDev)
func (*SSRServer) Run ¶
Run is the high-level API for starting the Piko server.
Takes runMode (string) which specifies the execution mode (prod, dev, or dev-interpreted).
Returns error when configuration bootstrap fails, global setup fails, lifecycle components fail to start, daemon bootstrap fails, or the daemon exits with an unexpected error.
Spawns a goroutine to listen for shutdown signals. The goroutine runs until a shutdown signal is received.
func (*SSRServer) Setup ¶
Setup bootstraps the configuration and creates the DI container without starting the server. Use it when you need access to services without running the daemon, such as in tests.
Returns error when the container fails to initialise.
func (*SSRServer) Stop ¶
Stop initiates a graceful shutdown of the running daemon service.
Returns error when the shutdown fails or times out.
func (*SSRServer) WithInterpreterProvider ¶
func (s *SSRServer) WithInterpreterProvider(provider templater_domain.InterpreterProviderPort)
WithInterpreterProvider sets the interpreter provider for dev-i mode.
This is required when running in RunModeDevInterpreted. The provider creates pooled interpreters with pre-loaded symbols for efficient JIT compilation.
Takes provider (templater_domain.InterpreterProviderPort) which provides the interpreter pool and symbol management.
Example: import pikointerp "piko.sh/piko/wdk/interp/interp_provider_piko" server := piko.New() server.WithInterpreterProvider(pikointerp.NewProvider()) server.Run(actions, piko.RunModeDevInterpreted)
func (*SSRServer) WithSymbols ¶
func (s *SSRServer) WithSymbols(symbols templater_domain.SymbolExports)
WithSymbols sets additional exported symbols for the interpreter.
These symbols will be registered with the interpreter provider when running in dev-i mode, making custom types and functions available to interpreted template code.
Takes symbols (templater_domain.SymbolExports) which provides the symbols to expose.
type SandboxConfig ¶
type SandboxConfig = config.SandboxConfig
SandboxConfig configures filesystem sandboxing for Piko internals.
type SearchField ¶
type SearchField = runtime.SearchField
SearchField specifies a field to search with optional weighting.
type SearchOption ¶
type SearchOption = runtime.SearchOption
SearchOption is a functional option for configuring search.
func WithCaseSensitive ¶
func WithCaseSensitive(sensitive bool) SearchOption
WithCaseSensitive enables case-sensitive search.
Takes sensitive (bool) which controls whether matching is case-sensitive.
Returns SearchOption which configures the search behaviour.
Example: results := piko.SearchCollection[Post](r, "blog", "GoLang",
piko.WithCaseSensitive(true))
func WithFuzzyThreshold ¶
func WithFuzzyThreshold(threshold float64) SearchOption
WithFuzzyThreshold sets the fuzzy matching threshold for search operations. Values range from 0.0 to 1.0, with 0.3 as the default.
Takes threshold (float64) which specifies the matching tolerance level.
Returns SearchOption which configures the search with the given threshold.
Example: results := piko.SearchCollection[Post](r, "blog", "golang",
piko.WithFuzzyThreshold(0.5)) // More lenient matching
func WithMinScore ¶
func WithMinScore(score float64) SearchOption
WithMinScore filters out results below the specified score.
Takes score (float64) which specifies the minimum relevance threshold.
Returns SearchOption which configures the search to exclude low-scoring results.
Example: results := piko.SearchCollection[Post](r, "blog", "golang",
piko.WithMinScore(0.5)) // Only highly relevant results
func WithSearchFields ¶
func WithSearchFields(fields ...SearchField) SearchOption
WithSearchFields specifies which fields to search with their weights.
Takes fields (...SearchField) which defines the searchable fields and their relative weights.
Returns SearchOption which configures field-specific search behaviour.
Example: results := piko.SearchCollection[Post](r, "blog", "golang",
piko.WithSearchFields(
piko.SearchField{Name: "Title", Weight: 2.0},
piko.SearchField{Name: "Body", Weight: 1.0},
))
func WithSearchLimit ¶
func WithSearchLimit(limit int) SearchOption
WithSearchLimit limits the number of search results.
Takes limit (int) which specifies the maximum number of results to return.
Returns SearchOption which configures the search limit.
Example: results := piko.SearchCollection[Post](r, "blog", "golang",
piko.WithSearchLimit(20))
func WithSearchMode ¶
func WithSearchMode(mode string) SearchOption
WithSearchMode sets the search mode to use.
Valid values: "fast" (default) or "smart" (with stemming and phonetic matching).
Fast mode uses basic tokenisation and exact matching, optimised for speed. Smart mode uses stemming, phonetic encoding, and fuzzy matching for better recall.
Takes mode (string) which specifies the search mode ("fast" or "smart").
Returns SearchOption which configures the search behaviour.
Example: results := piko.SearchCollection[Post](r, "blog", "running",
piko.WithSearchMode("smart")) // Matches "run", "runs", "running"
func WithSearchOffset ¶
func WithSearchOffset(offset int) SearchOption
WithSearchOffset skips the first N results for pagination.
Takes offset (int) which specifies the number of results to skip.
Returns SearchOption which configures the search to skip the specified number of results.
type SearchResult ¶
type SearchResult[T any] = runtime.SearchResult[T]
SearchResult represents a search result with relevance scoring.
func SearchCollection ¶
func SearchCollection[T any](r *RequestData, collectionName string, query string, opts ...SearchOption) ([]SearchResult[T], error)
SearchCollection performs fuzzy text search on collection data. Results are ranked by relevance score (0.0 - 1.0).
Searches both static (markdown) and dynamic (CMS) collections with configurable fuzzy matching.
Takes r (*RequestData) which provides the request context. Takes collectionName (string) which identifies the collection to search. Takes query (string) which is the search term to match against collection items. Takes opts (...SearchOption) which provides optional search configuration such as fields, threshold, and limit.
Returns []SearchResult[T] which contains matched items with relevance scores. Returns error when the search fails.
Example usage:
func Render(r *piko.RequestData, props piko.NoProps) (Response, piko.Metadata, error) {
query := r.QueryParams.Get("q")
results := piko.SearchCollection[Post](r, "blog", query,
piko.WithSearchFields(
piko.SearchField{Name: "Title", Weight: 2.0}, // Title weighted 2x
piko.SearchField{Name: "Body", Weight: 1.0},
),
piko.WithFuzzyThreshold(0.3),
piko.WithSearchLimit(20),
)
return Response{Results: results, Query: query}, piko.Metadata{}, nil
}
type Secret ¶
type Secret[T any] = config_domain.Secret[T]
Secret provides lazy-loaded, secure secret handling for configuration values. Unlike regular config fields, Secret[T] stores the resolver reference and resolves on-demand when Acquire() is called rather than at startup.
Type parameter T should be:
- string: For text secrets (memory zeroing is best-effort)
- []byte: For binary secrets (stored in SecureBytes with mmap+mlock)
Security characteristics:
- Lazy loading: Secrets don't enter memory until needed
- Explicit lifecycle: Acquire() + Release() for scoped access
- Reference counting: Multiple concurrent Acquire() calls are safe
- Automatic registration: Secrets register with SecretManager for shutdown
- Finaliser safety net: Unreleased handles are cleaned up by GC
type SecretHandle ¶
type SecretHandle[T any] = config_domain.SecretHandle[T]
SecretHandle provides scoped access to a secret value. It must be released when no longer needed to allow the secret to be refreshed or cleaned up during shutdown.
SecretHandle implements io.Closer for use with defer.
type SecretManager ¶
type SecretManager = config_domain.SecretManager
SecretManager coordinates the lifecycle of all Secret[T] instances, handling registration, stats tracking, and graceful shutdown. SecretManager is a singleton; use GetSecretManager to access it.
func GetSecretManager ¶
func GetSecretManager() *SecretManager
GetSecretManager returns the singleton secret manager. Use this to access secret statistics or manually trigger shutdown.
Returns *SecretManager which provides access to secret management operations.
Example: stats := piko.GetSecretManager().Stats() log.Info("Active secrets", "count", stats.TotalSecrets)
type SecretStats ¶
type SecretStats = config_domain.SecretStats
SecretStats provides statistics about secret usage.
type Section ¶
Section represents a heading in markdown content (h2-h6). Used for building Table of Contents (flat list).
func GetSections ¶
func GetSections(r *RequestData) []Section
GetSections extracts the table of contents sections from collection data. Returns a list of headings found in markdown content, useful for building a ToC sidebar.
Takes r (*RequestData) which provides the collection data to extract from.
Returns []Section which contains the headings found in the content.
Example usage:
func Render(r *piko.RequestData, props piko.NoProps) (Response, piko.Metadata, error) {
doc := piko.GetData[Doc](r)
sections := piko.GetSections(r)
return Response{
Title: doc.Title,
Sections: sections, // Pass to template for ToC rendering
}, piko.Metadata{}, nil
}
type SectionNode ¶
type SectionNode = runtime.SectionNode
SectionNode represents a hierarchical section entry for table of contents. Unlike Section (which is flat), SectionNode contains nested children for building tree-structured navigation.
func GetSectionsTree ¶
func GetSectionsTree(r *RequestData, opts ...SectionTreeOption) []SectionNode
GetSectionsTree extracts sections from collection data and builds a hierarchical tree. Unlike GetSections which returns a flat list, this returns nested SectionNode structures suitable for rendering a table of contents with proper nesting.
Takes r (*RequestData) which contains the collection data to extract from. Takes opts (...SectionTreeOption) which configures level filtering.
Returns []SectionNode which contains top-level sections with nested children.
Example usage:
func Render(r *piko.RequestData, props piko.NoProps) (Response, piko.Metadata, error) {
// Get hierarchical sections (defaults: h2-h4)
sections := piko.GetSectionsTree(r)
// Or with custom level filtering:
sections := piko.GetSectionsTree(r,
piko.WithMinLevel(2),
piko.WithMaxLevel(3),
)
return Response{Sections: sections}, piko.Metadata{}, nil
}
type SectionTreeOption ¶
type SectionTreeOption = runtime.SectionTreeOption
SectionTreeOption is a functional option for configuring GetSectionsTree.
func WithMaxLevel ¶
func WithMaxLevel(level int) SectionTreeOption
WithMaxLevel sets the maximum heading level to include (default: 4). Headings above this level are filtered out.
Takes level (int) which specifies the maximum heading level to include.
Returns SectionTreeOption which configures the section tree builder.
Example: tree := piko.GetSectionsTree(r, piko.WithMaxLevel(3)) // Only h2 and h3
func WithMinLevel ¶
func WithMinLevel(level int) SectionTreeOption
WithMinLevel sets the minimum heading level to include (default: 2). Headings below this level are filtered out.
Takes level (int) which specifies the minimum heading level.
Returns SectionTreeOption which configures the section tree filtering.
Example: tree := piko.GetSectionsTree(r, piko.WithMinLevel(2)) // Start from h2
type SecurityHeadersConfig ¶
type SecurityHeadersConfig = config.SecurityHeadersConfig
SecurityHeadersConfig configures HTTP security headers following OWASP best practices. Pass to WithSecurityHeaders.
type Session ¶
type Session = daemon_dto.Session
Session contains session data for the current request.
type SitemapChunkConfig ¶
type SitemapChunkConfig = config.SitemapChunkConfig
SitemapChunkConfig defines a named sitemap chunk with its own sources.
type SitemapConfig ¶
type SitemapConfig = config.SitemapConfig
SitemapConfig holds settings for sitemap.xml generation.
type SitemapEntryDefaults ¶
type SitemapEntryDefaults = config.SitemapEntryDefaults
SitemapEntryDefaults provides default values for sitemap entries.
type SortOption ¶
type SortOption = runtime.SortOption
SortOption specifies a field and direction for sorting.
func NewSortOption ¶
func NewSortOption(field string, order SortOrder) SortOption
NewSortOption creates a sorting option.
Takes field (string) which specifies the field name to sort by. Takes order (SortOrder) which sets the sort direction.
Returns SortOption which is the configured sorting option.
Example: sort := piko.NewSortOption("publishedAt", piko.SortDesc)
type SpamConfig ¶
type SpamConfig = daemon_domain.SpamConfig
SpamConfig defines per-action spam detection behaviour.
type SpamConfigurable ¶
type SpamConfigurable = daemon_domain.SpamConfigurable
SpamConfigurable is optionally implemented alongside SpamProtected to override per-action spam detection settings.
type SpamProtected ¶
type SpamProtected = daemon_domain.SpamProtected
SpamProtected is an interface for requiring spam detection before action execution. Actions implement SpamSchema() to declare which fields should be checked and with which signals.
type SpamSchema ¶
type SpamSchema = spamdetect_dto.Schema
SpamSchema describes the spam-checkable fields of a form.
type SpamSignal ¶
type SpamSignal = spamdetect_dto.Signal
SpamSignal identifies a category of spam detection.
type StoragePresignConfig ¶
type StoragePresignConfig = config.StoragePresignConfig
StoragePresignConfig configures presigned URL support for storage operations. Pass to WithStoragePresign.
type SymbolExports ¶
type SymbolExports = templater_domain.SymbolExports
SymbolExports is a type alias for registering exported symbols with the template interpreter. It maps package names to symbol names to their values, and is compatible with SymbolExports from the interpreter provider.
type TLSOption ¶
TLSOption configures TLS settings for the main server. Use with WithTLS.
func WithTLSCertFile ¶
WithTLSCertFile sets the path to the PEM-encoded TLS certificate file.
Takes path (string) which specifies the certificate file path.
Returns TLSOption which sets the certificate path.
func WithTLSClientAuth ¶
WithTLSClientAuth sets the client certificate verification mode. Valid values are "none", "request", "require", "verify", and "require_and_verify".
Takes authType (string) which specifies the auth mode.
Returns TLSOption which sets the client auth type.
func WithTLSClientCA ¶
WithTLSClientCA sets the path to a PEM-encoded CA bundle for mTLS client certificate verification.
Takes path (string) which specifies the client CA file path.
Returns TLSOption which sets the client CA path.
func WithTLSHotReload ¶
WithTLSHotReload enables or disables automatic certificate reload when certificate files change on disk.
Takes enabled (bool) which controls hot-reload behaviour.
Returns TLSOption which sets the hot-reload flag.
func WithTLSKeyFile ¶
WithTLSKeyFile sets the path to the PEM-encoded TLS private key file.
Takes path (string) which specifies the key file path.
Returns TLSOption which sets the key path.
func WithTLSMinVersion ¶
WithTLSMinVersion sets the minimum TLS version. Valid values are "1.2" and "1.3".
Takes version (string) which specifies the minimum version.
Returns TLSOption which sets the minimum TLS version.
func WithTLSRedirectHTTP ¶
WithTLSRedirectHTTP starts a plain HTTP listener on the given port that 301-redirects all requests to the HTTPS server. Use this to redirect http://example.com to https://example.com.
Takes port (int) which specifies the HTTP port to listen on (e.g. 80 or 8080).
Returns TLSOption which configures the redirect listener.
type TeapotError ¶
type TeapotError = daemon_dto.TeapotError
TeapotError represents HTTP 418 I'm a Teapot (RFC 2324).
type TestView ¶
type TestView = pikotest_domain.TestView
TestView wraps the result of a component render and provides methods to check state, metadata, and DOM structure.
type ToastsConfig ¶
type ToastsConfig = daemon_frontend.ToastsConfig
ToastsConfig provides settings for the Toasts module.
type Translation ¶
type Translation = i18n_domain.Translation
Translation represents a translatable string returned by r.T() and r.LT(). It supports variables and pluralisation, and implements fmt.Stringer.
type Transport ¶
type Transport = daemon_domain.Transport
Transport represents a supported transport mechanism for actions.
type UnauthorisedError ¶
type UnauthorisedError = daemon_dto.UnauthorisedError
UnauthorisedError represents authentication failure (HTTP 401). Use this when the user needs to authenticate.
type ValidationError ¶
type ValidationError = daemon_dto.ValidationError
ValidationError represents validation failures (HTTP 422). Use this when user input fails validation rules.
type VideoAssetsConfig ¶
type VideoAssetsConfig = config.VideoAssetsConfig
VideoAssetsConfig holds video-specific asset configuration.
type WatchdogEvent ¶
type WatchdogEvent = monitoring_domain.WatchdogEvent
WatchdogEvent describes a notable runtime event detected by the watchdog.
type WatchdogEventPriority ¶
type WatchdogEventPriority = monitoring_domain.WatchdogEventPriority
WatchdogEventPriority indicates the urgency of a watchdog event.
type WatchdogEventType ¶
type WatchdogEventType = monitoring_domain.WatchdogEventType
WatchdogEventType identifies the category of a watchdog event.
type WatchdogNotifier ¶
type WatchdogNotifier = monitoring_domain.WatchdogNotifier
WatchdogNotifier delivers watchdog event notifications to external systems.
type WatchdogOption ¶
type WatchdogOption = bootstrap.WatchdogOption
WatchdogOption configures the runtime watchdog.
func WithWatchdogCheckInterval ¶
func WithWatchdogCheckInterval(interval time.Duration) WatchdogOption
WithWatchdogCheckInterval sets how often the watchdog evaluates runtime metrics.
Shorter intervals detect anomalies faster at negligible CPU cost. Default: 500ms.
Takes interval (time.Duration) which is the check period.
Returns WatchdogOption which configures the check interval.
func WithWatchdogContentionDiagnosticAutoFire ¶
func WithWatchdogContentionDiagnosticAutoFire() WatchdogOption
WithWatchdogContentionDiagnosticAutoFire enables automatic contention-diagnostic firing when scheduler-latency events repeat. Default behaviour is manual (operator must call RunContentionDiagnostic).
Returns WatchdogOption which enables automatic contention diagnostic firing.
func WithWatchdogContentionDiagnosticBlockProfileRate ¶
func WithWatchdogContentionDiagnosticBlockProfileRate(rate int) WatchdogOption
WithWatchdogContentionDiagnosticBlockProfileRate sets the runtime block profile rate during a contention diagnostic. Default: 1e6 (one sample per 1ms of blocking).
Takes rate (int) which is the runtime block profile rate.
Returns WatchdogOption which configures the block profile rate.
func WithWatchdogContentionDiagnosticMutexProfileFraction ¶
func WithWatchdogContentionDiagnosticMutexProfileFraction(fraction int) WatchdogOption
WithWatchdogContentionDiagnosticMutexProfileFraction sets the runtime mutex profile fraction during a contention diagnostic. Default: 100.
Takes fraction (int) which is the runtime mutex profile fraction.
Returns WatchdogOption which configures the mutex profile fraction.
func WithWatchdogContentionDiagnosticWindow ¶
func WithWatchdogContentionDiagnosticWindow(window time.Duration) WatchdogOption
WithWatchdogContentionDiagnosticWindow sets the duration during which block + mutex profiling are active during a contention diagnostic.
Default is 60s; allowed range is 1s to 5m.
Takes window (time.Duration) which is the diagnostic window duration.
Returns WatchdogOption which configures the diagnostic window.
func WithWatchdogContinuousProfiling ¶
func WithWatchdogContinuousProfiling() WatchdogOption
WithWatchdogContinuousProfiling enables the continuous-profiling loop which captures routine profile snapshots so post-mortem operators have recent profiles even when no threshold breach occurred. Default behaviour is disabled (opt-in).
Returns WatchdogOption which enables continuous profiling.
func WithWatchdogContinuousProfilingInterval ¶
func WithWatchdogContinuousProfilingInterval(interval time.Duration) WatchdogOption
WithWatchdogContinuousProfilingInterval sets the interval between routine profile captures.
Default is 10 minutes; validation enforces a minimum of 1 minute.
Takes interval (time.Duration) which is the period between captures.
Returns WatchdogOption which configures the routine capture interval.
func WithWatchdogContinuousProfilingNotify ¶
func WithWatchdogContinuousProfilingNotify() WatchdogOption
WithWatchdogContinuousProfilingNotify enables informational notifications for each routine capture. Default behaviour is suppression to avoid flooding notifiers.
Returns WatchdogOption which enables routine-capture notifications.
func WithWatchdogContinuousProfilingRetention ¶
func WithWatchdogContinuousProfilingRetention(count int) WatchdogOption
WithWatchdogContinuousProfilingRetention sets the maximum number of routine profile files retained per type. Default: 6.
Takes count (int) which is the retention cap.
Returns WatchdogOption which configures routine profile retention.
func WithWatchdogContinuousProfilingTypes ¶
func WithWatchdogContinuousProfilingTypes(types ...string) WatchdogOption
WithWatchdogContinuousProfilingTypes sets the profile types captured each routine interval.
Default is ["heap"]. Allowed values are heap, goroutine, and allocs.
Takes types (...string) which is the list of profile types to capture.
Returns WatchdogOption which configures the routine capture set.
func WithWatchdogCooldown ¶
func WithWatchdogCooldown(duration time.Duration) WatchdogOption
WithWatchdogCooldown sets the minimum duration between consecutive profile captures for the same metric type. Default: 2 minutes.
Takes duration (time.Duration) which is the cooldown period.
Returns WatchdogOption which configures the cooldown.
func WithWatchdogDeltaProfiling ¶
func WithWatchdogDeltaProfiling() WatchdogOption
WithWatchdogDeltaProfiling enables storing a baseline heap profile alongside each capture so the user can compute a diff between consecutive captures using `go tool pprof -diff_base`.
Returns WatchdogOption which enables delta profiling.
func WithWatchdogFDPressureThresholdPercent ¶
func WithWatchdogFDPressureThresholdPercent(percent float64) WatchdogOption
WithWatchdogFDPressureThresholdPercent sets the fraction of the soft RLIMIT_NOFILE above which the watchdog emits an FD pressure warning.
Default is 0.80; pass 0 to disable the rule.
Takes percent (float64) which is the threshold fraction (0.0-1.0).
Returns WatchdogOption which configures the FD pressure threshold.
func WithWatchdogGoroutineThreshold ¶
func WithWatchdogGoroutineThreshold(threshold int) WatchdogOption
WithWatchdogGoroutineThreshold sets the goroutine count that triggers a goroutine profile capture. Default: 10,000.
Takes threshold (int) which is the goroutine count threshold.
Returns WatchdogOption which configures the goroutine threshold.
func WithWatchdogHeapThresholdBytes ¶
func WithWatchdogHeapThresholdBytes(thresholdBytes uint64) WatchdogOption
WithWatchdogHeapThresholdBytes sets the absolute heap threshold in bytes, used when GOMEMLIMIT is not configured. Default: 512 MiB.
Takes thresholdBytes (uint64) which is the threshold in bytes.
Returns WatchdogOption which configures the heap threshold.
func WithWatchdogHeapThresholdPercent ¶
func WithWatchdogHeapThresholdPercent(percent float64) WatchdogOption
WithWatchdogHeapThresholdPercent sets the heap threshold as a fraction of GOMEMLIMIT (0.0-1.0). Default: 0.85.
Takes percent (float64) which is the threshold fraction.
Returns WatchdogOption which configures the heap threshold.
func WithWatchdogIncludeGoroutineStacks ¶
func WithWatchdogIncludeGoroutineStacks(enabled bool) WatchdogOption
WithWatchdogIncludeGoroutineStacks toggles per-goroutine stack capture. When enabled, each goroutine profile firing also writes a human-readable .stacks.txt sidecar containing the full stack of every goroutine (pprof debug=2 output), alongside the existing aggregated .pb.gz binary profile.
Useful when investigating goroutine leaks where you need to know the exact call site or closure-captured arguments (e.g. which channel a publisher is blocked on). Disabled by default because the sidecar can be tens of megabytes per dump for processes with many thousand goroutines.
Takes enabled (bool) which toggles the feature.
Returns WatchdogOption which configures the stacks sidecar capture.
func WithWatchdogMaxProfilesPerType ¶
func WithWatchdogMaxProfilesPerType(count int) WatchdogOption
WithWatchdogMaxProfilesPerType sets the maximum number of stored profiles per type (heap, goroutine).
Oldest profiles are rotated out. Default: 5.
Takes count (int) which is the maximum profile count per type.
Returns WatchdogOption which configures profile rotation.
func WithWatchdogMaxWarningsPerWindow ¶
func WithWatchdogMaxWarningsPerWindow(count int) WatchdogOption
WithWatchdogMaxWarningsPerWindow sets the maximum number of warning-only events permitted within a single CaptureWindow.
Default is 10. Warnings have their own budget separate from profile captures so flapping warnings cannot crowd out real captures.
Takes count (int) which is the maximum warnings per window.
Returns WatchdogOption which configures the warning budget.
func WithWatchdogProfileDirectory ¶
func WithWatchdogProfileDirectory(directory string) WatchdogOption
WithWatchdogProfileDirectory sets the local directory for profile storage. Default: os.TempDir()/piko-watchdog.
Takes directory (string) which is the directory path.
Returns WatchdogOption which configures the profile directory.
func WithWatchdogRSSThresholdPercent ¶
func WithWatchdogRSSThresholdPercent(percent float64) WatchdogOption
WithWatchdogRSSThresholdPercent sets the fraction of the cgroup memory limit above which RSS triggers a profile capture. Default: 0.85.
Takes percent (float64) which is the threshold fraction (0.0-1.0).
Returns WatchdogOption which configures the RSS threshold.
func WithWatchdogSchedulerLatencyP99Threshold ¶
func WithWatchdogSchedulerLatencyP99Threshold(threshold time.Duration) WatchdogOption
WithWatchdogSchedulerLatencyP99Threshold sets the p99 scheduler latency above which the watchdog emits a scheduler-latency warning.
Default is 10ms; pass zero to disable the rule.
Takes threshold (time.Duration) which is the p99 latency threshold.
Returns WatchdogOption which configures the scheduler-latency threshold.
type WatchdogProfileUploader ¶
type WatchdogProfileUploader = monitoring_domain.WatchdogProfileUploader
WatchdogProfileUploader uploads captured diagnostic profiles to remote storage.
type WebsiteConfig ¶
type WebsiteConfig = config.WebsiteConfig
WebsiteConfig defines the user-facing properties of the website being served, including theme, favicons, fonts, and i18n settings.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
cmd
|
|
|
piko
module
|
|
|
Package components provides Piko's built-in PKC component library.
|
Package components provides Piko's built-in PKC component library. |
|
internal
|
|
|
analytics/analytics_adapters
Package analytics_adapters implements driven adapters for the backend analytics subsystem.
|
Package analytics_adapters implements driven adapters for the backend analytics subsystem. |
|
analytics/analytics_domain
Package analytics_domain coordinates the distribution of backend analytics events to pluggable collector backends.
|
Package analytics_domain coordinates the distribution of backend analytics events to pluggable collector backends. |
|
analytics/analytics_dto
Package analytics_dto defines data transfer objects for the backend analytics subsystem.
|
Package analytics_dto defines data transfer objects for the backend analytics subsystem. |
|
annotator/annotator_adapters
Package annotator_adapters implements driven adapters for the annotator domain.
|
Package annotator_adapters implements driven adapters for the annotator domain. |
|
annotator/annotator_domain
Package annotator_domain provides the core compilation pipeline for Piko templates.
|
Package annotator_domain provides the core compilation pipeline for Piko templates. |
|
annotator/annotator_dto
Package annotator_dto defines data transfer objects for the annotator module.
|
Package annotator_dto defines data transfer objects for the annotator module. |
|
apitest
Package apitest guards against unintentional API breakage using YAML golden files.
|
Package apitest guards against unintentional API breakage using YAML golden files. |
|
assetpath
Package assetpath handles predicates and transformations for asset source paths used throughout the Piko asset pipeline.
|
Package assetpath handles predicates and transformations for asset source paths used throughout the Piko asset pipeline. |
|
ast/ast_adapters
Package ast_adapters implements FlatBuffers serialisation and multi-level caching for template ASTs.
|
Package ast_adapters implements FlatBuffers serialisation and multi-level caching for template ASTs. |
|
ast/ast_domain
Package ast_domain defines the core Abstract Syntax Tree types and operations for Piko templates.
|
Package ast_domain defines the core Abstract Syntax Tree types and operations for Piko templates. |
|
ast/ast_schema
Package ast_schema manages versioned serialisation for the template AST FlatBuffer representation.
|
Package ast_schema manages versioned serialisation for the template AST FlatBuffer representation. |
|
ast/ast_schema/ast_schema_gen
Package ast_schema_gen contains generated FlatBuffer types for the template AST serialisation format.
|
Package ast_schema_gen contains generated FlatBuffer types for the template AST serialisation format. |
|
binder
Package binder bridges HTTP form data with Go struct population, using the Piko Expression Language for field mapping.
|
Package binder bridges HTTP form data with Go struct population, using the Piko Expression Language for field mapping. |
|
bootstrap
Package bootstrap assembles the Piko application and acts as its composition root.
|
Package bootstrap assembles the Piko application and acts as its composition root. |
|
cache/cache_adapters/cache_transformer_crypto
Package cache_transformer_crypto implements the cache transformer port using the centralised crypto service for encryption and decryption.
|
Package cache_transformer_crypto implements the cache transformer port using the centralised crypto service for encryption and decryption. |
|
cache/cache_adapters/cache_transformer_mock
Package cache_transformer_mock implements a test double for the cache transformer port.
|
Package cache_transformer_mock implements a test double for the cache transformer port. |
|
cache/cache_adapters/cache_transformer_zstd
Package cache_transformer_zstd implements the cache transformer port using Zstandard compression.
|
Package cache_transformer_zstd implements the cache transformer port using Zstandard compression. |
|
cache/cache_adapters/encoder_gob
Package encoder_gob implements the cache encoder port using Go's native Gob binary encoding format.
|
Package encoder_gob implements the cache encoder port using Go's native Gob binary encoding format. |
|
cache/cache_adapters/encoder_json
Package encoder_json implements the cache encoder port using JSON serialisation.
|
Package encoder_json implements the cache encoder port using JSON serialisation. |
|
cache/cache_adapters/encoder_mock
Package encoder_mock implements the cache encoder port for testing.
|
Package encoder_mock implements the cache encoder port for testing. |
|
cache/cache_adapters/provider_mock
Package provider_mock supplies in-memory mock cache adapters for testing.
|
Package provider_mock supplies in-memory mock cache adapters for testing. |
|
cache/cache_adapters/provider_multilevel
Package provider_multilevel implements a two-tier cache provider that orchestrates an L1 (fast, local) and L2 (slower, distributed) cache.
|
Package provider_multilevel implements a two-tier cache provider that orchestrates an L1 (fast, local) and L2 (slower, distributed) cache. |
|
cache/cache_adapters/provider_otter
Package provider_otter implements the cache provider port using the Otter in-memory cache library.
|
Package provider_otter implements the cache provider port using the Otter in-memory cache library. |
|
cache/cache_domain
Package cache_domain defines the core caching abstractions and business logic for the cache hexagon.
|
Package cache_domain defines the core caching abstractions and business logic for the cache hexagon. |
|
cache/cache_dto
Package cache_dto defines data transfer objects for the cache hexagon.
|
Package cache_dto defines data transfer objects for the cache hexagon. |
|
cache/cache_test/conformance
Package conformance provides a reusable conformance test suite for validating cache provider implementations against the cache interface contract.
|
Package conformance provides a reusable conformance test suite for validating cache provider implementations against the cache interface contract. |
|
caller
Package caller captures stack frames with zero allocations on the hot path.
|
Package caller captures stack frames with zero allocations on the hot path. |
|
capabilities
Package capabilities provides a registry for named capabilities that can be invoked to transform content.
|
Package capabilities provides a registry for named capabilities that can be invoked to transform content. |
|
capabilities/capabilities_domain
Package capabilities_domain defines the port interface and service for pluggable content transformation capabilities.
|
Package capabilities_domain defines the port interface and service for pluggable content transformation capabilities. |
|
capabilities/capabilities_dto
Package capabilities_dto defines data transfer objects for the capabilities module.
|
Package capabilities_dto defines data transfer objects for the capabilities module. |
|
capabilities/capabilities_functions
Package capabilities_functions supplies built-in capability implementations for content transformation and processing.
|
Package capabilities_functions supplies built-in capability implementations for content transformation and processing. |
|
captcha/captcha_adapters/hmac_challenge
Package hmac_challenge provides a built-in captcha provider using HMAC-SHA256 signed challenge tokens.
|
Package hmac_challenge provides a built-in captcha provider using HMAC-SHA256 signed challenge tokens. |
|
captcha/captcha_domain
Package captcha_domain defines the captcha verification port interfaces and service logic for the Piko framework.
|
Package captcha_domain defines the captcha verification port interfaces and service logic for the Piko framework. |
|
captcha/captcha_dto
Package captcha_dto defines data transfer objects for the captcha module.
|
Package captcha_dto defines data transfer objects for the captcha module. |
|
collection/collection_adapters
Package collection_adapters implements the driven ports for the collection hexagon, covering encoding, persistence, and provider interfaces defined in collection_domain.
|
Package collection_adapters implements the driven ports for the collection hexagon, covering encoding, persistence, and provider interfaces defined in collection_domain. |
|
collection/collection_adapters/cache_factory
Package cache_factory registers a ProviderFactoryBlueprint for hybrid collection caches so they can be created through the cache service.
|
Package cache_factory registers a ProviderFactoryBlueprint for hybrid collection caches so they can be created through the cache service. |
|
collection/collection_adapters/driver_asset_registrar
Package driver_asset_registrar implements the collection_domain.AssetRegistrar port backed by the artefact registry.
|
Package driver_asset_registrar implements the collection_domain.AssetRegistrar port backed by the artefact registry. |
|
collection/collection_adapters/driver_markdown
Package driver_markdown implements a static collection provider for markdown files.
|
Package driver_markdown implements a static collection provider for markdown files. |
|
collection/collection_adapters/driver_mock_cms
Package driver_mock_cms simulates a headless CMS collection provider for testing and demonstration.
|
Package driver_mock_cms simulates a headless CMS collection provider for testing and demonstration. |
|
collection/collection_adapters/driver_registry
Package driver_registry implements the provider registry port for collections.
|
Package driver_registry implements the provider registry port for collections. |
|
collection/collection_domain
Package collection_domain defines the core domain logic for the collection hexagon.
|
Package collection_domain defines the core domain logic for the collection hexagon. |
|
collection/collection_dto
Package collection_dto defines data transfer objects for the collection module.
|
Package collection_dto defines data transfer objects for the collection module. |
|
collection/collection_schema
Package collection_schema provides versioned serialisation for the collection hexagon's FlatBuffer representation.
|
Package collection_schema provides versioned serialisation for the collection hexagon's FlatBuffer representation. |
|
colour
Package colour handles zero-allocation ANSI colour output for terminal text.
|
Package colour handles zero-allocation ANSI colour output for terminal text. |
|
compiler/compiler_adapters
Package compiler_adapters implements compiler_domain.InputReaderPort for reading SFC (Single File Component) sources.
|
Package compiler_adapters implements compiler_domain.InputReaderPort for reading SFC (Single File Component) sources. |
|
compiler/compiler_domain
Package compiler_domain provides the core business logic for compiling Single File Components (.pkc) into JavaScript and HTML artefacts.
|
Package compiler_domain provides the core business logic for compiling Single File Components (.pkc) into JavaScript and HTML artefacts. |
|
compiler/compiler_dto
Package compiler_dto defines data transfer objects for the compiler module.
|
Package compiler_dto defines data transfer objects for the compiler module. |
|
component/component_adapters
Package component_adapters implements component_domain.ComponentRegistry with an in-memory, thread-safe store.
|
Package component_adapters implements component_domain.ComponentRegistry with an in-memory, thread-safe store. |
|
component/component_domain
Package component_domain defines the ComponentRegistry port interface and validation logic for the PKC component registry system.
|
Package component_domain defines the ComponentRegistry port interface and validation logic for the PKC component registry system. |
|
component/component_dto
Package component_dto defines data transfer objects for the PKC component registry system.
|
Package component_dto defines data transfer objects for the PKC component registry system. |
|
config
Package config holds piko's internal value-type definitions for the configuration domains the framework cares about (network, security, paths, storage, database, OTLP, build, and so on).
|
Package config holds piko's internal value-type definitions for the configuration domains the framework cares about (network, security, paths, storage, database, OTLP, build, and so on). |
|
config/config_domain
Package config_domain orchestrates reflection-based configuration loading from multiple sources.
|
Package config_domain orchestrates reflection-based configuration loading from multiple sources. |
|
contextaware
Package contextaware wraps standard library types to respect context cancellation.
|
Package contextaware wraps standard library types to respect context cancellation. |
|
coordinator/coordinator_adapters
Package coordinator_adapters implements the coordinator domain ports for caching and diagnostic output.
|
Package coordinator_adapters implements the coordinator domain ports for caching and diagnostic output. |
|
coordinator/coordinator_domain
Package coordinator_domain orchestrates the build lifecycle for Piko projects.
|
Package coordinator_domain orchestrates the build lifecycle for Piko projects. |
|
coordinator/coordinator_dto
Package coordinator_dto defines data transfer objects for the coordinator module.
|
Package coordinator_dto defines data transfer objects for the coordinator module. |
|
crypto/crypto_adapters
Package crypto_adapters implements encryption providers for the crypto domain.
|
Package crypto_adapters implements encryption providers for the crypto domain. |
|
crypto/crypto_adapters/local_aes_gcm
Package local_aes_gcm implements AES-256-GCM encryption without external dependencies.
|
Package local_aes_gcm implements AES-256-GCM encryption without external dependencies. |
|
crypto/crypto_domain
Package crypto_domain defines the encryption port interfaces and service logic for the Piko framework.
|
Package crypto_domain defines the encryption port interfaces and service logic for the Piko framework. |
|
crypto/crypto_dto
Package crypto_dto defines data transfer objects for the crypto module.
|
Package crypto_dto defines data transfer objects for the crypto module. |
|
crypto/crypto_test
Package crypto_test provides test doubles for the crypto module.
|
Package crypto_test provides test doubles for the crypto module. |
|
cssinliner
Package cssinliner provides CSS @import resolution and processing.
|
Package cssinliner provides CSS @import resolution and processing. |
|
daemon/daemon_adapters
Package daemon_adapters implements the daemon domain ports for HTTP routing, request handling, action dispatch, response caching, middleware, and server lifecycle management.
|
Package daemon_adapters implements the daemon domain ports for HTTP routing, request handling, action dispatch, response caching, middleware, and server lifecycle management. |
|
daemon/daemon_domain
Package daemon_domain orchestrates HTTP server lifecycle, graceful shutdown, build notification processing, and on-demand image variant generation.
|
Package daemon_domain orchestrates HTTP server lifecycle, graceful shutdown, build notification processing, and on-demand image variant generation. |
|
daemon/daemon_dto
Package daemon_dto contains request/response types, typed action errors, and shared dependencies used by HTTP handlers in the daemon module.
|
Package daemon_dto contains request/response types, typed action errors, and shared dependencies used by HTTP handlers in the daemon module. |
|
daemon/daemon_frontend
Package daemon_frontend manages embedded frontend assets and module registration for the Piko development daemon.
|
Package daemon_frontend manages embedded frontend assets and module registration for the Piko development daemon. |
|
deadletter/deadletter_adapters
Package deadletter_adapters implements deadletter_domain.DeadLetterPort with in-memory and disk-based (JSON lines) storage backends.
|
Package deadletter_adapters implements deadletter_domain.DeadLetterPort with in-memory and disk-based (JSON lines) storage backends. |
|
deadletter/deadletter_domain
Package deadletter_domain defines the port interfaces and entry constraints for a generic dead letter queue.
|
Package deadletter_domain defines the port interfaces and entry constraints for a generic dead letter queue. |
|
dispatcher/dispatcher_adapters
Package dispatcher_adapters provides the driven adapter implementations for the dispatcher hexagon.
|
Package dispatcher_adapters provides the driven adapter implementations for the dispatcher hexagon. |
|
dispatcher/dispatcher_domain
Package dispatcher_domain defines the core port interfaces and domain types for the dispatcher hexagon.
|
Package dispatcher_domain defines the core port interfaces and domain types for the dispatcher hexagon. |
|
email/email_adapters/asset_resolver
Package asset_resolver implements the email asset resolver port using the registry service.
|
Package asset_resolver implements the email asset resolver port using the registry service. |
|
email/email_adapters/provider_disk
Package provider_disk implements the email provider port by writing emails to disk as RFC 5322 compliant .eml files suitable for development, testing, and auditing.
|
Package provider_disk implements the email provider port by writing emails to disk as RFC 5322 compliant .eml files suitable for development, testing, and auditing. |
|
email/email_adapters/provider_mock
Package provider_mock implements a mock email provider for testing.
|
Package provider_mock implements a mock email provider for testing. |
|
email/email_adapters/provider_stdout
Package provider_stdout implements an email provider that writes emails to stdout as human-readable blocks for development use.
|
Package provider_stdout implements an email provider that writes emails to stdout as human-readable blocks for development use. |
|
email/email_adapters/templater_adapter
Package templater_adapter implements the email domain's template rendering port by delegating to the templater domain.
|
Package templater_adapter implements the email domain's template rendering port by delegating to the templater domain. |
|
email/email_domain
Package email_domain defines the core business logic and ports for the email subsystem.
|
Package email_domain defines the core business logic and ports for the email subsystem. |
|
email/email_dto
Package email_dto defines data transfer objects for the email module.
|
Package email_dto defines data transfer objects for the email module. |
|
esbuild/js_ast
This file was automatically generated by gen-unicode-table.js.
|
This file was automatically generated by gen-unicode-table.js. |
|
events/events_domain
Package events_domain defines the Provider port interface and configuration types for the Watermill-based message bus infrastructure.
|
Package events_domain defines the Provider port interface and configuration types for the Watermill-based message bus infrastructure. |
|
fbs
Package fbs handles versioned FlatBuffer serialisation with automatic cache invalidation via schema-hash prefixes.
|
Package fbs handles versioned FlatBuffer serialisation with automatic cache invalidation via schema-hash prefixes. |
|
fonts
Package fonts provides embedded NotoSans TrueType font data shared across the layouter, PDF writer, and test packages.
|
Package fonts provides embedded NotoSans TrueType font data shared across the layouter, PDF writer, and test packages. |
|
formatter/formatter_domain
Package formatter_domain handles formatting of Piko template files (.pk), covering all Single File Component (SFC) blocks (template, script, style, and i18n) with consistent, opinionated rules that preserve semantic meaning while improving readability.
|
Package formatter_domain handles formatting of Piko template files (.pk), covering all Single File Component (SFC) blocks (template, script, style, and i18n) with consistent, opinionated rules that preserve semantic meaning while improving readability. |
|
generator/generator_adapters
Package generator_adapters implements driven adapters for the generator domain.
|
Package generator_adapters implements driven adapters for the generator domain. |
|
generator/generator_adapters/driven_code_emitter_go_literal
Package driven_code_emitter_go_literal implements the code emitter that translates Piko's annotated AST into executable Go source code.
|
Package driven_code_emitter_go_literal implements the code emitter that translates Piko's annotated AST into executable Go source code. |
|
generator/generator_domain
Package generator_domain defines the core code generation business logic for Piko.
|
Package generator_domain defines the core code generation business logic for Piko. |
|
generator/generator_dto
Package generator_dto defines data transfer objects for the generator module.
|
Package generator_dto defines data transfer objects for the generator module. |
|
generator/generator_helpers
Package generator_helpers provides runtime utility functions called by generated Go code from Piko templates.
|
Package generator_helpers provides runtime utility functions called by generated Go code from Piko templates. |
|
generator/generator_schema
Package generator_schema provides versioned serialisation for the generator hexagon's project manifest FlatBuffer representation.
|
Package generator_schema provides versioned serialisation for the generator hexagon's project manifest FlatBuffer representation. |
|
goastutil
Package goastutil provides Go AST construction, type-string parsing, and type classification utilities.
|
Package goastutil provides Go AST construction, type-string parsing, and type classification utilities. |
|
goroutine
Package goroutine provides panic recovery and safe-call utilities for goroutine lifecycle management.
|
Package goroutine provides panic recovery and safe-call utilities for goroutine lifecycle management. |
|
healthprobe/healthprobe_adapters
Package healthprobe_adapters implements the healthprobe_domain ports for probe registration (InMemoryRegistry) and HTTP endpoint serving (HTTPHandlerAdapter).
|
Package healthprobe_adapters implements the healthprobe_domain ports for probe registration (InMemoryRegistry) and HTTP endpoint serving (HTTPHandlerAdapter). |
|
healthprobe/healthprobe_domain
Package healthprobe_domain defines port interfaces (Probe, Registry, Service) and the service that runs all registered probes concurrently, aggregating their results into a unified health status.
|
Package healthprobe_domain defines port interfaces (Probe, Registry, Service) and the service that runs all registered probes concurrently, aggregating their results into a unified health status. |
|
healthprobe/healthprobe_dto
Package healthprobe_dto defines the types used to represent health check requests and responses, including the hierarchical status structure that supports nested dependency reporting.
|
Package healthprobe_dto defines the types used to represent health check requests and responses, including the hierarchical status structure that supports nested dependency reporting. |
|
highlight/highlight_domain
Package highlight_domain defines the Highlighter port interface that syntax highlighting backends must implement.
|
Package highlight_domain defines the Highlighter port interface that syntax highlighting backends must implement. |
|
hnsw
Package hnsw implements a Hierarchical Navigable Small World (HNSW) graph for approximate nearest neighbour search over float32 vectors.
|
Package hnsw implements a Hierarchical Navigable Small World (HNSW) graph for approximate nearest neighbour search over float32 vectors. |
|
htmllexer
Package htmllexer provides a streaming, zero-allocation HTML tokeniser with built-in source position tracking.
|
Package htmllexer provides a streaming, zero-allocation HTML tokeniser with built-in source position tracking. |
|
i18n/i18n_adapters
Package i18n_adapters implements i18n_domain.Service via filesystem-backed loaders and emitters for internationalisation data.
|
Package i18n_adapters implements i18n_domain.Service via filesystem-backed loaders and emitters for internationalisation data. |
|
i18n/i18n_domain
Package i18n_domain defines the Service port interface and implements translation storage, template parsing, pluralisation rules, and zero-allocation rendering for localised strings.
|
Package i18n_domain defines the Service port interface and implements translation storage, template parsing, pluralisation rules, and zero-allocation rendering for localised strings. |
|
i18n/i18n_schema
Package i18n_schema provides versioned serialisation for the internationalisation (i18n) hexagon's FlatBuffer representation.
|
Package i18n_schema provides versioned serialisation for the internationalisation (i18n) hexagon's FlatBuffer representation. |
|
image/image_adapters/transformer_mock
Package transformer_mock is a thread-safe, in-memory test double for image_domain.TransformerPort.
|
Package transformer_mock is a thread-safe, in-memory test double for image_domain.TransformerPort. |
|
image/image_domain
Package image_domain coordinates image transformations, responsive variant generation, and placeholder creation through the TransformerPort interface.
|
Package image_domain coordinates image transformations, responsive variant generation, and placeholder creation through the TransformerPort interface. |
|
image/image_dto
Package image_dto contains configuration and result types for image transformations, covering resizing, format conversion, responsive variant generation, and placeholder (LQIP) creation.
|
Package image_dto contains configuration and result types for image transformations, covering resizing, format conversion, responsive variant generation, and placeholder (LQIP) creation. |
|
inspector/inspector_adapters
Package inspector_adapters implements type data caching and serialisation for the inspector subsystem, with FlatBuffers binary, JSON (debugging), and in-memory (testing) backends.
|
Package inspector_adapters implements type data caching and serialisation for the inspector subsystem, with FlatBuffers binary, JSON (debugging), and in-memory (testing) backends. |
|
inspector/inspector_domain
Package inspector_domain provides the core business logic for analysing Go source code and extracting type information.
|
Package inspector_domain provides the core business logic for analysing Go source code and extracting type information. |
|
inspector/inspector_dto
Package inspector_dto defines the types used to represent Go type information extracted during static analysis.
|
Package inspector_dto defines the types used to represent Go type information extracted during static analysis. |
|
inspector/inspector_schema
Package inspector_schema manages versioned serialisation for the inspector's type data cache using FlatBuffers.
|
Package inspector_schema manages versioned serialisation for the inspector's type data cache using FlatBuffers. |
|
inspector/inspector_test/builder_lite
Package builder_lite provides integration tests for the LiteBuilder, the lightweight AST-only code inspection path that extracts type information without invoking go/packages.
|
Package builder_lite provides integration tests for the LiteBuilder, the lightweight AST-only code inspection path that extracts type information without invoking go/packages. |
|
interp/interp_adapters
Package interp_adapters provides adapter implementations for the bytecode interpreter's driven ports.
|
Package interp_adapters provides adapter implementations for the bytecode interpreter's driven ports. |
|
interp/interp_adapters/driven_piko_symbols
Package driven_piko_symbols provides vendored piko runtime symbol tables for the bytecode interpreter.
|
Package driven_piko_symbols provides vendored piko runtime symbol tables for the bytecode interpreter. |
|
interp/interp_adapters/driven_system_symbols
Package driven_system_symbols provides vendored Go standard library symbol tables for the bytecode interpreter.
|
Package driven_system_symbols provides vendored Go standard library symbol tables for the bytecode interpreter. |
|
interp/interp_adapters/driver_symbols_extract
Package driver_symbols_extract provides the code generation tooling that produces vendored symbol tables for the bytecode interpreter.
|
Package driver_symbols_extract provides the code generation tooling that produces vendored symbol tables for the bytecode interpreter. |
|
interp/interp_domain
Package interp_domain implements a bytecode-compiling Go interpreter.
|
Package interp_domain implements a bytecode-compiling Go interpreter. |
|
interp/interp_domain/asm
Package asm defines the architecture-neutral handler descriptions for the interp_domain bytecode dispatch loop.
|
Package asm defines the architecture-neutral handler descriptions for the interp_domain bytecode dispatch loop. |
|
interp/interp_domain/asm/asmgen_arch_amd64
Package asmgen_arch_amd64 provides the AMD64 assembly code generation backend for the piko bytecode interpreter.
|
Package asmgen_arch_amd64 provides the AMD64 assembly code generation backend for the piko bytecode interpreter. |
|
interp/interp_domain/asm/asmgen_arch_arm64
Package asmgen_arch_arm64 provides the ARM64 assembly code generation backend for the piko bytecode interpreter.
|
Package asmgen_arch_arm64 provides the ARM64 assembly code generation backend for the piko bytecode interpreter. |
|
interp/interp_schema
Package interp_schema provides versioned serialisation for the interpreter hexagon's compiled bytecode FlatBuffer representation.
|
Package interp_schema provides versioned serialisation for the interpreter hexagon's compiled bytecode FlatBuffer representation. |
|
jsimport
Package jsimport provides shared JavaScript and TypeScript import path transformation utilities.
|
Package jsimport provides shared JavaScript and TypeScript import path transformation utilities. |
|
json
Package json wraps JSON encoding and decoding behind a pluggable Provider interface.
|
Package json wraps JSON encoding and decoding behind a pluggable Provider interface. |
|
layouter/layouter_adapters
Package layouter_adapters provides adapter implementations for the layout engine's driven ports.
|
Package layouter_adapters provides adapter implementations for the layout engine's driven ports. |
|
layouter/layouter_domain
Package layouter_domain contains the core domain types, port interfaces, and algorithms for the Piko layout engine.
|
Package layouter_domain contains the core domain types, port interfaces, and algorithms for the Piko layout engine. |
|
layouter/layouter_dto
Package layouter_dto defines data transfer objects for the layouter module.
|
Package layouter_dto defines data transfer objects for the layouter module. |
|
lifecycle/lifecycle_adapters
Package lifecycle_adapters implements the lifecycle_domain ports for file watching (fsNotifyWatcher), production builds (buildService), and interpreted code execution (InterpretedBuildOrchestrator).
|
Package lifecycle_adapters implements the lifecycle_domain ports for file watching (fsNotifyWatcher), production builds (buildService), and interpreted code execution (InterpretedBuildOrchestrator). |
|
lifecycle/lifecycle_domain
Package lifecycle_domain orchestrates the bridge between build-time operations and runtime execution, defining port interfaces (FileSystemWatcher, RouterReloadNotifier, InterpretedBuildOrchestrator) and coordinating file watching, build notifications, asset pipeline processing, and router hot-reload.
|
Package lifecycle_domain orchestrates the bridge between build-time operations and runtime execution, defining port interfaces (FileSystemWatcher, RouterReloadNotifier, InterpretedBuildOrchestrator) and coordinating file watching, build notifications, asset pipeline processing, and router hot-reload. |
|
lifecycle/lifecycle_dto
Package lifecycle_dto contains event types and enumerations for communicating lifecycle events, particularly file system change notifications for hot-reload functionality.
|
Package lifecycle_dto contains event types and enumerations for communicating lifecycle events, particularly file system change notifications for hot-reload functionality. |
|
linguistics/linguistics_domain
Package linguistics_domain defines the text analysis pipeline for Piko's search system, covering tokenisation, normalisation, stemming, phonetic encoding, stop words, and fuzzy matching with multi-language support and typo tolerance.
|
Package linguistics_domain defines the text analysis pipeline for Piko's search system, covering tokenisation, normalisation, stemming, phonetic encoding, stop words, and fuzzy matching with multi-language support and typo tolerance. |
|
llm/llm_adapters/budget_store/cache
Package cache implements llm_domain.BudgetStorePort using the internal/cache system.
|
Package cache implements llm_domain.BudgetStorePort using the internal/cache system. |
|
llm/llm_adapters/budget_store/memory
Package memory implements llm_domain.BudgetStorePort using in-memory storage.
|
Package memory implements llm_domain.BudgetStorePort using in-memory storage. |
|
llm/llm_adapters/cache
Package cache implements llm_domain.CacheStorePort by bridging the LLM domain to the internal/cache hexagon.
|
Package cache implements llm_domain.CacheStorePort by bridging the LLM domain to the internal/cache hexagon. |
|
llm/llm_adapters/memory_memory
Package memory_memory implements llm_domain.MemoryStorePort using in-memory storage suited for development, testing, and single-instance deployments.
|
Package memory_memory implements llm_domain.MemoryStorePort using in-memory storage suited for development, testing, and single-instance deployments. |
|
llm/llm_adapters/provider_mock
Package provider_mock is a test double for llm_domain.LLMProviderPort that supports canned responses, error simulation, and call recording for both synchronous completions and streaming responses.
|
Package provider_mock is a test double for llm_domain.LLMProviderPort that supports canned responses, error simulation, and call recording for both synchronous completions and streaming responses. |
|
llm/llm_adapters/vector_cache
Package vector_cache implements llm_domain.VectorStorePort by delegating to the cache system.
|
Package vector_cache implements llm_domain.VectorStorePort by delegating to the cache system. |
|
llm/llm_domain
Package llm_domain orchestrates provider-agnostic interaction with large language models.
|
Package llm_domain orchestrates provider-agnostic interaction with large language models. |
|
llm/llm_dto
Package llm_dto contains provider-agnostic request/response types, configuration structs, and parameter objects for the LLM subsystem, covering completions, embeddings, vector search, batch processing, conversation memory, budget management, response caching, retry policies, provider fallback, and pricing.
|
Package llm_dto contains provider-agnostic request/response types, configuration structs, and parameter objects for the LLM subsystem, covering completions, embeddings, vector search, batch processing, conversation memory, budget management, response caching, retry policies, provider fallback, and pricing. |
|
logger/logger_adapters/driver_handlers
Package driver_handlers implements log/slog.Handler for the Piko logging system, including pretty-printed console output with colours and OpenTelemetry integration for distributed tracing.
|
Package driver_handlers implements log/slog.Handler for the Piko logging system, including pretty-printed console output with colours and OpenTelemetry integration for distributed tracing. |
|
logger/logger_adapters/integrations
Package integrations bridges the logging subsystem to external services by implementing the driven port interfaces defined in logger_domain.
|
Package integrations bridges the logging subsystem to external services by implementing the driven port interfaces defined in logger_domain. |
|
logger/logger_adapters/integrations/watermill
Package watermill bridges Piko's structured logging with Watermill's LoggerAdapter interface so that Watermill components (publishers, subscribers, routers) log through Piko's unified infrastructure.
|
Package watermill bridges Piko's structured logging with Watermill's LoggerAdapter interface so that Watermill components (publishers, subscribers, routers) log through Piko's unified infrastructure. |
|
logger/logger_domain
Package logger_domain defines the Logger interface and implements structured logging with OpenTelemetry integration.
|
Package logger_domain defines the Logger interface and implements structured logging with OpenTelemetry integration. |
|
logger/logger_dto
Package logger_dto defines configuration structs for logging outputs and third-party integrations.
|
Package logger_dto defines configuration structs for logging outputs and third-party integrations. |
|
logger/logger_test
Package logger_test verifies the full logger initialisation pipeline end-to-end, including configuration parsing, handler composition, output formatting (pretty, JSON, text), notification debouncing, and OpenTelemetry trace context injection.
|
Package logger_test verifies the full logger initialisation pipeline end-to-end, including configuration parsing, handler composition, output formatting (pretty, JSON, text), notification debouncing, and OpenTelemetry trace context injection. |
|
logrotate
Package logrotate manages size-based log file rotation, implementing io.WriteCloser.
|
Package logrotate manages size-based log file rotation, implementing io.WriteCloser. |
|
markdown/markdown_ast
Package markdown_ast defines the piko-native markdown AST used by parser adapters and the markdown domain.
|
Package markdown_ast defines the piko-native markdown AST used by parser adapters and the markdown domain. |
|
markdown/markdown_domain
Package markdown_domain orchestrates the transformation of Markdown content into structured build artefacts.
|
Package markdown_domain orchestrates the transformation of Markdown content into structured build artefacts. |
|
markdown/markdown_dto
Package markdown_dto contains the types used to represent processed Markdown content and its associated metadata, including page information, navigation data, and extracted elements such as headings, images, and links.
|
Package markdown_dto contains the types used to represent processed Markdown content and its associated metadata, including page information, navigation data, and extracted elements such as headings, images, and links. |
|
markdown/markdown_testparser
Package markdown_testparser provides a lightweight, zero-dependency markdown parser that produces piko-native AST.
|
Package markdown_testparser provides a lightweight, zero-dependency markdown parser that produces piko-native AST. |
|
mem
Package mem wraps unsafe operations to provide zero-allocation memory utilities.
|
Package mem wraps unsafe operations to provide zero-allocation memory utilities. |
|
monitoring/monitoring_adapters
Package monitoring_adapters implements gRPC services and noop factories for the monitoring hexagon.
|
Package monitoring_adapters implements gRPC services and noop factories for the monitoring hexagon. |
|
monitoring/monitoring_domain
Package monitoring_domain defines the core abstractions and business logic for the monitoring subsystem.
|
Package monitoring_domain defines the core abstractions and business logic for the monitoring subsystem. |
|
netutil
Package netutil provides network utility helpers.
|
Package netutil provides network utility helpers. |
|
notification/notification_adapters/driver_providers
Package driver_providers implements notification delivery adapters for third-party messaging services and generic endpoints.
|
Package driver_providers implements notification delivery adapters for third-party messaging services and generic endpoints. |
|
notification/notification_domain
Package notification_domain coordinates the sending of notifications through a pluggable provider registry.
|
Package notification_domain coordinates the sending of notifications through a pluggable provider registry. |
|
notification/notification_dto
Package notification_dto defines data transfer objects for the notification subsystem.
|
Package notification_dto defines data transfer objects for the notification subsystem. |
|
orchestrator
Package orchestrator provides task orchestration and workflow management as the facade for the orchestrator hexagon.
|
Package orchestrator provides task orchestration and workflow management as the facade for the orchestrator hexagon. |
|
orchestrator/orchestrator_adapters
Package orchestrator_adapters implements the orchestrator domain ports using Watermill for distributed event-driven task processing.
|
Package orchestrator_adapters implements the orchestrator domain ports using Watermill for distributed event-driven task processing. |
|
orchestrator/orchestrator_dal
Package orchestrator_dal defines data access layer abstractions for the orchestrator hexagon.
|
Package orchestrator_dal defines data access layer abstractions for the orchestrator hexagon. |
|
orchestrator/orchestrator_dal/mock
Package mock implements the orchestrator DAL interfaces for testing.
|
Package mock implements the orchestrator DAL interfaces for testing. |
|
orchestrator/orchestrator_dal/otter
Package otter implements the orchestrator DAL using in-memory otter cache for development, testing, and embedded deployments.
|
Package otter implements the orchestrator DAL using in-memory otter cache for development, testing, and embedded deployments. |
|
orchestrator/orchestrator_dal/querier_adapter
Package querier_adapter wraps the code-generated SQLite queries to satisfy the orchestrator DAL and task store interfaces.
|
Package querier_adapter wraps the code-generated SQLite queries to satisfy the orchestrator DAL and task store interfaces. |
|
orchestrator/orchestrator_dal/querier_sqlite/db
Package db contains code-generated SQLite query functions and model types for the orchestrator's data access layer.
|
Package db contains code-generated SQLite query functions and model types for the orchestrator's data access layer. |
|
orchestrator/orchestrator_domain
Package orchestrator_domain defines the core task orchestration abstractions and business logic.
|
Package orchestrator_domain defines the core task orchestration abstractions and business logic. |
|
pdfwriter/pdfwriter_adapters
Package pdfwriter_adapters implements the driven port interfaces defined in pdfwriter_domain, connecting the PDF writer to the layouter and template runner.
|
Package pdfwriter_adapters implements the driven port interfaces defined in pdfwriter_domain, connecting the PDF writer to the layouter and template runner. |
|
pdfwriter/pdfwriter_adapters/driven_svgwriter
Package driven_svgwriter parses SVG markup and emits native PDF vector drawing commands into a content stream.
|
Package driven_svgwriter parses SVG markup and emits native PDF vector drawing commands into a content stream. |
|
pdfwriter/pdfwriter_adapters/driven_transform_compress
Package driven_transform_compress implements byte-level compression as a PDF post-processing transformer.
|
Package driven_transform_compress implements byte-level compression as a PDF post-processing transformer. |
|
pdfwriter/pdfwriter_adapters/driven_transform_encrypt
Package driven_transform_encrypt implements PDF encryption as a post-processing transformer.
|
Package driven_transform_encrypt implements PDF encryption as a post-processing transformer. |
|
pdfwriter/pdfwriter_adapters/driven_transform_flatten
Package driven_transform_flatten converts interactive PDF elements into static page content as a post-processing transformer.
|
Package driven_transform_flatten converts interactive PDF elements into static page content as a post-processing transformer. |
|
pdfwriter/pdfwriter_adapters/driven_transform_linearise
Package driven_transform_linearise reorganises PDF object order as a post-processing transformer so viewers can render pages progressively.
|
Package driven_transform_linearise reorganises PDF object order as a post-processing transformer so viewers can render pages progressively. |
|
pdfwriter/pdfwriter_adapters/driven_transform_objstm
Package driven_transform_objstm re-encodes PDF stream objects with FlateDecode as a post-processing transformer.
|
Package driven_transform_objstm re-encodes PDF stream objects with FlateDecode as a post-processing transformer. |
|
pdfwriter/pdfwriter_adapters/driven_transform_pades
Package driven_transform_pades adds PAdES (PDF Advanced Electronic Signatures) digital signatures as a post-processing transformer.
|
Package driven_transform_pades adds PAdES (PDF Advanced Electronic Signatures) digital signatures as a post-processing transformer. |
|
pdfwriter/pdfwriter_adapters/driven_transform_pdfa
Package driven_transform_pdfa applies PDF/A archival conformance as a post-processing transformer.
|
Package driven_transform_pdfa applies PDF/A archival conformance as a post-processing transformer. |
|
pdfwriter/pdfwriter_adapters/driven_transform_pdfua
Package driven_transform_pdfua adds PDF/UA (Universal Accessibility) structural metadata as a post-processing transformer.
|
Package driven_transform_pdfua adds PDF/UA (Universal Accessibility) structural metadata as a post-processing transformer. |
|
pdfwriter/pdfwriter_adapters/driven_transform_redaction
Package driven_transform_redaction removes sensitive content from PDFs as a post-processing transformer.
|
Package driven_transform_redaction removes sensitive content from PDFs as a post-processing transformer. |
|
pdfwriter/pdfwriter_adapters/driven_transform_watermark
Package driven_transform_watermark overlays text watermarks on PDF pages as a post-processing transformer.
|
Package driven_transform_watermark overlays text watermarks on PDF pages as a post-processing transformer. |
|
pdfwriter/pdfwriter_adapters/pdfparse
Package pdfparse provides a minimal PDF parser and writer for post-processing transformations.
|
Package pdfparse provides a minimal PDF parser and writer for post-processing transformations. |
|
pdfwriter/pdfwriter_domain
Package pdfwriter_domain contains the core domain types, port interfaces, and service implementation for the PDF writer.
|
Package pdfwriter_domain contains the core domain types, port interfaces, and service implementation for the PDF writer. |
|
pdfwriter/pdfwriter_dto
Package pdfwriter_dto defines the data transfer objects for the PDF writer module, including configuration and result types.
|
Package pdfwriter_dto defines the data transfer objects for the PDF writer module, including configuration and result types. |
|
persistence
Package persistence defines the port interfaces and types for the persistence hexagon, allowing the application to switch between database backends (SQLite, PostgreSQL, D1) without coupling to driver-specific types.
|
Package persistence defines the port interfaces and types for the persistence hexagon, allowing the application to switch between database backends (SQLite, PostgreSQL, D1) without coupling to driver-specific types. |
|
pikotest/pikotest_domain
Package pikotest_domain supplies testing utilities for validating Piko components and server actions without requiring a running server.
|
Package pikotest_domain supplies testing utilities for validating Piko components and server actions without requiring a running server. |
|
pikotest/pikotest_dto
Package pikotest_dto defines pure data structures used by the pikotest testing framework.
|
Package pikotest_dto defines pure data structures used by the pikotest testing framework. |
|
pml/pml_adapters
Package pml_adapters implements the collector interfaces defined in pml_domain, handling responsive CSS media query generation and Microsoft Outlook conditional comment blocks for email compatibility.
|
Package pml_adapters implements the collector interfaces defined in pml_domain, handling responsive CSS media query generation and Microsoft Outlook conditional comment blocks for email compatibility. |
|
pml/pml_components
Package pml_components implements all built-in PikoML components.
|
Package pml_components implements all built-in PikoML components. |
|
pml/pml_domain
Package pml_domain defines the core interfaces and domain models for the PikoML transformation engine.
|
Package pml_domain defines the core interfaces and domain models for the PikoML transformation engine. |
|
pml/pml_dto
Package pml_dto holds configuration structs for the PikoML templating engine.
|
Package pml_dto holds configuration structs for the PikoML templating engine. |
|
premailer
Package premailer handles CSS inlining and email compatibility transformations.
|
Package premailer handles CSS inlining and email compatibility transformations. |
|
profiler
Package profiler provides runtime profiling for Piko.
|
Package profiler provides runtime profiling for Piko. |
|
provider/provider_domain
Package provider_domain manages named provider instances (e.g.
|
Package provider_domain manages named provider instances (e.g. |
|
querier/querier_adapters
Package querier_adapters provides infrastructure implementations for the querier domain's port interfaces.
|
Package querier_adapters provides infrastructure implementations for the querier domain's port interfaces. |
|
querier/querier_adapters/emitter_go
Package emitter_go provides backwards-compatible access to the database/sql code emitter via GoEmitter.
|
Package emitter_go provides backwards-compatible access to the database/sql code emitter via GoEmitter. |
|
querier/querier_adapters/emitter_go_sql
Package emitter_go_sql implements CodeEmitterPort for the database/sql runtime target.
|
Package emitter_go_sql implements CodeEmitterPort for the database/sql runtime target. |
|
querier/querier_adapters/emitter_shared
Package emitter_shared provides shared utilities for Go code emitter adapters.
|
Package emitter_shared provides shared utilities for Go code emitter adapters. |
|
querier/querier_adapters/migration_sql
Package migration_sql implements MigrationExecutorPort using database/sql.
|
Package migration_sql implements MigrationExecutorPort using database/sql. |
|
querier/querier_domain
Package querier_domain provides the core SQL analysis and code generation pipeline for Piko's database integration.
|
Package querier_domain provides the core SQL analysis and code generation pipeline for Piko's database integration. |
|
querier/querier_dto
Package querier_dto provides data transfer objects for the querier hexagon.
|
Package querier_dto provides data transfer objects for the querier hexagon. |
|
quickpackages
Package quickpackages provides a performance-optimised replacement for golang.org/x/tools/go/packages.
|
Package quickpackages provides a performance-optimised replacement for golang.org/x/tools/go/packages. |
|
ratelimiter/ratelimiter_adapters
Package ratelimiter_adapters bridges the rate limiter domain with the cache infrastructure.
|
Package ratelimiter_adapters bridges the rate limiter domain with the cache infrastructure. |
|
ratelimiter/ratelimiter_domain
Package ratelimiter_domain handles centralised rate limiting with pluggable algorithms and cache-backed storage.
|
Package ratelimiter_domain handles centralised rate limiting with pluggable algorithms and cache-backed storage. |
|
ratelimiter/ratelimiter_dto
Package ratelimiter_dto contains configuration and result types for the centralised rate limiter, shared across the domain, adapters, and consumer packages (email, storage, LLM, security).
|
Package ratelimiter_dto contains configuration and result types for the centralised rate limiter, shared across the domain, adapters, and consumer packages (email, storage, LLM, security). |
|
registry/registry_adapters
Package registry_adapters implements the storage and caching ports defined by registry_domain.
|
Package registry_adapters implements the storage and caching ports defined by registry_domain. |
|
registry/registry_dal
Package registry_dal defines data access layer abstractions for the registry hexagon.
|
Package registry_dal defines data access layer abstractions for the registry hexagon. |
|
registry/registry_dal/mock
Package mock implements the registry DAL interface for testing purposes.
|
Package mock implements the registry DAL interface for testing purposes. |
|
registry/registry_dal/otter
Package otter implements the registry DAL using in-memory otter cache for development, testing, and embedded deployments.
|
Package otter implements the registry DAL using in-memory otter cache for development, testing, and embedded deployments. |
|
registry/registry_dal/querier_adapter
Package querier_adapter wraps the querier-generated Queries struct to satisfy the RegistryDALWithTx interface.
|
Package querier_adapter wraps the querier-generated Queries struct to satisfy the RegistryDALWithTx interface. |
|
registry/registry_dal/querier_sqlite/db
Package db contains code-generated SQLite query functions and model types for the registry's data access layer.
|
Package db contains code-generated SQLite query functions and model types for the registry's data access layer. |
|
registry/registry_domain
Package registry_domain defines the core business logic for the artefact registry.
|
Package registry_domain defines the core business logic for the artefact registry. |
|
registry/registry_dto
Package registry_dto defines data transfer objects for the artefact registry.
|
Package registry_dto defines data transfer objects for the artefact registry. |
|
registry/registry_schema
Package registry_schema provides FlatBuffer serialisation and schema versioning for registry artefacts.
|
Package registry_schema provides FlatBuffer serialisation and schema versioning for registry artefacts. |
|
render/render_adapters
Package render_adapters implements the render domain ports for registry access with caching and headless rendering.
|
Package render_adapters implements the render domain ports for registry access with caching and headless rendering. |
|
render/render_domain
Package render_domain provides the core rendering engine for transforming Piko AST into HTML output.
|
Package render_domain provides the core rendering engine for transforming Piko AST into HTML output. |
|
render/render_dto
Package render_dto defines data transfer objects for the render module, including page definitions, component trees, and the artefacts produced by the rendering process.
|
Package render_dto defines data transfer objects for the render module, including page definitions, component trees, and the artefacts produced by the rendering process. |
|
render/render_templates
Package render_templates provides quicktemplate-based HTML page wrappers for different output contexts: full web pages, partial fragments, and email messages.
|
Package render_templates provides quicktemplate-based HTML page wrappers for different output contexts: full web pages, partial fragments, and email messages. |
|
render/render_test/pages/fixtures
Package fixtures provides pre-built template AST structures for render integration tests.
|
Package fixtures provides pre-built template AST structures for render integration tests. |
|
render/render_test/pages/mocks
Package mocks provides test doubles for render page integration tests.
|
Package mocks provides test doubles for render page integration tests. |
|
resolver/resolver_adapters
Package resolver_adapters implements the ResolverPort interface for resolving Piko component, CSS, and asset paths from different sources.
|
Package resolver_adapters implements the ResolverPort interface for resolving Piko component, CSS, and asset paths from different sources. |
|
resolver/resolver_domain
Package resolver_domain defines the port interfaces for import path resolution.
|
Package resolver_domain defines the port interfaces for import path resolution. |
|
resolver/resolver_dto
Package resolver_dto defines data transfer objects for the resolver module.
|
Package resolver_dto defines data transfer objects for the resolver module. |
|
retry
Package retry provides shared retry configuration and error classification for operations that may fail with transient errors.
|
Package retry provides shared retry configuration and error classification for operations that may fail with transient errors. |
|
route_pattern
Package route_pattern parses the trailing `{name[:regex]}` segment of a piko route pattern.
|
Package route_pattern parses the trailing `{name[:regex]}` segment of a piko route pattern. |
|
safeerror
Package safeerror separates user-safe messages from internal error details for secure error handling in HTTP responses.
|
Package safeerror separates user-safe messages from internal error details for secure error handling in HTTP responses. |
|
search/search_adapters
Package search_adapters provides adapters for registering and querying full-text search indexes.
|
Package search_adapters provides adapters for registering and querying full-text search indexes. |
|
search/search_domain
Package search_domain defines the core search abstractions and business logic.
|
Package search_domain defines the core search abstractions and business logic. |
|
search/search_dto
Package search_dto defines data transfer objects for the search module.
|
Package search_dto defines data transfer objects for the search module. |
|
search/search_schema
Package search_schema provides schema versioning for Search FlatBuffers.
|
Package search_schema provides schema versioning for Search FlatBuffers. |
|
security/security_adapters
Package security_adapters implements the security domain port interfaces.
|
Package security_adapters implements the security domain port interfaces. |
|
security/security_domain
Package security_domain defines the core security abstractions, services, and policies for the Piko framework.
|
Package security_domain defines the core security abstractions, services, and policies for the Piko framework. |
|
security/security_dto
Package security_dto defines data transfer objects for the security module.
|
Package security_dto defines data transfer objects for the security module. |
|
seo/seo_adapters
Package seo_adapters implements the driven ports for the SEO hexagon.
|
Package seo_adapters implements the driven ports for the SEO hexagon. |
|
seo/seo_domain
Package seo_domain defines the core SEO business logic and port interfaces.
|
Package seo_domain defines the core SEO business logic and port interfaces. |
|
seo/seo_dto
Package seo_dto defines data transfer objects for the SEO module.
|
Package seo_dto defines data transfer objects for the SEO module. |
|
sfcparser
Package sfcparser provides parsing for Piko Single File Components (SFC).
|
Package sfcparser provides parsing for Piko Single File Components (SFC). |
|
shutdown
Package shutdown provides graceful shutdown coordination for applications.
|
Package shutdown provides graceful shutdown coordination for applications. |
|
spamdetect/spamdetect_adapters
Package spamdetect_adapters groups concrete implementations of the Detector port defined in spamdetect_domain.
|
Package spamdetect_adapters groups concrete implementations of the Detector port defined in spamdetect_domain. |
|
spamdetect/spamdetect_adapters/builtin_detectors
Package builtin_detectors provides zero-dependency spam detection detectors that operate on schema-annotated form fields.
|
Package builtin_detectors provides zero-dependency spam detection detectors that operate on schema-annotated form fields. |
|
spamdetect/spamdetect_domain
Package spamdetect_domain defines the spam detection port interfaces and composite service logic for the Piko framework.
|
Package spamdetect_domain defines the spam detection port interfaces and composite service logic for the Piko framework. |
|
spamdetect/spamdetect_dto
Package spamdetect_dto defines data transfer objects for the spam detection module.
|
Package spamdetect_dto defines data transfer objects for the spam detection module. |
|
storage/storage_adapters/presign_http
Package presign_http implements HTTP handlers for presigned storage operations and public file serving.
|
Package presign_http implements HTTP handlers for presigned storage operations and public file serving. |
|
storage/storage_adapters/provider_disk
Package provider_disk implements the storage provider port using the local filesystem with atomic writes and safedisk sandboxing.
|
Package provider_disk implements the storage provider port using the local filesystem with atomic writes and safedisk sandboxing. |
|
storage/storage_adapters/provider_mock
Package provider_mock implements a mock storage provider for testing.
|
Package provider_mock implements a mock storage provider for testing. |
|
storage/storage_adapters/registry_blob_adapter
Package registry_blob_adapter implements the registry hexagon's BlobStore interface using the storage hexagon's providers.
|
Package registry_blob_adapter implements the registry hexagon's BlobStore interface using the storage hexagon's providers. |
|
storage/storage_adapters/transformer_crypto
Package transformer_crypto implements storage stream encryption using the centralised crypto service.
|
Package transformer_crypto implements storage stream encryption using the centralised crypto service. |
|
storage/storage_adapters/transformer_mock
Package transformer_mock provides mock implementations of StreamTransformerPort for testing storage transformations.
|
Package transformer_mock provides mock implementations of StreamTransformerPort for testing storage transformations. |
|
storage/storage_domain
Package storage_domain defines the core storage abstractions and business logic for Piko's object storage hexagon.
|
Package storage_domain defines the core storage abstractions and business logic for Piko's object storage hexagon. |
|
storage/storage_dto
Package storage_dto defines data transfer objects for the storage module.
|
Package storage_dto defines data transfer objects for the storage module. |
|
templater/templater_adapters
Package templater_adapters implements the templater port interfaces for manifest loading, template execution, and rendering.
|
Package templater_adapters implements the templater port interfaces for manifest loading, template execution, and rendering. |
|
templater/templater_domain
Package templater_domain provides domain types and services for the template compilation and rendering pipeline.
|
Package templater_domain provides domain types and services for the template compilation and rendering pipeline. |
|
templater/templater_dto
Package templater_dto defines data transfer objects for the templater system.
|
Package templater_dto defines data transfer objects for the templater system. |
|
testutil/leakcheck
Package leakcheck provides goroutine leak detection for Piko tests.
|
Package leakcheck provides goroutine leak detection for Piko tests. |
|
tlscert
Package tlscert provides TLS certificate management shared by the daemon HTTP server and the monitoring gRPC server.
|
Package tlscert provides TLS certificate management shared by the daemon HTTP server and the monitoring gRPC server. |
|
typegen/typegen_adapters
Package typegen_adapters implements TypeScript code emission, action manifest serialisation, and embedded type definition management for the typegen module.
|
Package typegen_adapters implements TypeScript code emission, action manifest serialisation, and embedded type definition management for the typegen module. |
|
typegen/typegen_domain
Package typegen_domain handles TypeScript type definition management and LSP intellisense for the Piko frontend framework.
|
Package typegen_domain handles TypeScript type definition management and LSP intellisense for the Piko frontend framework. |
|
typegen/typegen_dto
Package typegen_dto defines data transfer objects for the type generation module.
|
Package typegen_dto defines data transfer objects for the type generation module. |
|
typegen/typegen_frontend
Package typegen_frontend bundles embedded TypeScript type definitions for the Piko frontend framework.
|
Package typegen_frontend bundles embedded TypeScript type definitions for the Piko frontend framework. |
|
typegen/typegen_schema
Package typegen_schema provides schema versioning for the LSP Action Manifest FlatBuffers.
|
Package typegen_schema provides schema versioning for the LSP Action Manifest FlatBuffers. |
|
typegen/typegen_schema/typegen_schema
Package typegen_schema contains the FlatBuffers-generated Go types for the LSP Action Manifest schema.
|
Package typegen_schema contains the FlatBuffers-generated Go types for the LSP Action Manifest schema. |
|
vectormaths
Package vectormaths provides float32 vector similarity and normalisation functions with SIMD acceleration.
|
Package vectormaths provides float32 vector similarity and normalisation functions with SIMD acceleration. |
|
vectormaths/asm
Package asm defines the architecture-neutral handler descriptions for the vectormaths SIMD functions.
|
Package asm defines the architecture-neutral handler descriptions for the vectormaths SIMD functions. |
|
vectormaths/asm/asmgen_arch_amd64
Package asmgen_arch_amd64 provides the AMD64 assembly code generation backend for SIMD vector mathematics operations.
|
Package asmgen_arch_amd64 provides the AMD64 assembly code generation backend for SIMD vector mathematics operations. |
|
vectormaths/asm/asmgen_arch_arm64
Package asmgen_arch_arm64 provides the ARM64 assembly code generation backend for SIMD vector mathematics operations.
|
Package asmgen_arch_arm64 provides the ARM64 assembly code generation backend for SIMD vector mathematics operations. |
|
video/video_adapters/transcoder_mock
Package transcoder_mock is an in-memory test double for video_domain.TranscoderPort and video_domain.StreamingTranscoderPort.
|
Package transcoder_mock is an in-memory test double for video_domain.TranscoderPort and video_domain.StreamingTranscoderPort. |
|
video/video_domain
Package video_domain owns the core video processing abstractions and business logic.
|
Package video_domain owns the core video processing abstractions and business logic. |
|
video/video_dto
Package video_dto defines data transfer objects for the video module.
|
Package video_dto defines data transfer objects for the video module. |
|
wal/wal_adapters/driven_disk
Package driven_disk implements disk-based write-ahead log and snapshot storage.
|
Package driven_disk implements disk-based write-ahead log and snapshot storage. |
|
wal/wal_domain
Package wal_domain defines the core abstractions and business types for write-ahead logging.
|
Package wal_domain defines the core abstractions and business types for write-ahead logging. |
|
wasm/wasm_adapters
Package wasm_adapters implements the driven port interfaces defined in wasm_domain for running the Piko compiler pipeline inside a WASM environment.
|
Package wasm_adapters implements the driven port interfaces defined in wasm_domain for running the Piko compiler pipeline inside a WASM environment. |
|
wasm/wasm_data
Package wasm_data holds embedded standard library type data for the WASM runtime.
|
Package wasm_data holds embedded standard library type data for the WASM runtime. |
|
wasm/wasm_domain
Package wasm_domain orchestrates the WASM runtime for Piko.
|
Package wasm_domain orchestrates the WASM runtime for Piko. |
|
wasm/wasm_dto
Package wasm_dto defines data transfer objects for the WASM hexagon.
|
Package wasm_dto defines data transfer objects for the WASM hexagon. |
|
plugins
|
|
|
agents
Package agents embeds the AI agent integration files for use by the scaffold wizard and the "piko agents update" command.
|
Package agents embeds the AI agent integration files for use by the scaffold wizard and the "piko agents update" command. |
|
wdk
|
|
|
analytics
Package analytics provides a provider-agnostic framework for backend analytics event collection, with support for batching, retry, and circuit breaking.
|
Package analytics provides a provider-agnostic framework for backend analytics event collection, with support for batching, retry, and circuit breaking. |
|
analytics/analytics_collector_stdout
Package analytics_collector_stdout provides an analytics collector that prints events to the structured logger.
|
Package analytics_collector_stdout provides an analytics collector that prints events to the structured logger. |
|
analytics/analytics_collector_webhook
Package analytics_collector_webhook provides an analytics collector that batches events and POSTs them as JSON to a configurable webhook endpoint.
|
Package analytics_collector_webhook provides an analytics collector that batches events and POSTs them as JSON to a configurable webhook endpoint. |
|
asmgen
Package asmgen implements a text-based Plan 9 assembly code generator.
|
Package asmgen implements a text-based Plan 9 assembly code generator. |
|
asmgen/asmgen_arch_amd64
Package asmgen_arch_amd64 implements ArchitecturePort for x86-64 Plan 9 assembly generation.
|
Package asmgen_arch_amd64 implements ArchitecturePort for x86-64 Plan 9 assembly generation. |
|
asmgen/asmgen_arch_arm64
Package asmgen_arch_arm64 implements ArchitecturePort for ARM 64-bit Plan 9 assembly generation.
|
Package asmgen_arch_arm64 implements ArchitecturePort for ARM 64-bit Plan 9 assembly generation. |
|
binder
Package binder provides form-data binding for populating Go structs from key-value form submissions.
|
Package binder provides form-data binding for populating Go structs from key-value form submissions. |
|
cache
Package cache provides a provider-agnostic caching framework for Piko applications.
|
Package cache provides a provider-agnostic caching framework for Piko applications. |
|
cache/cache_encoder_gob
Package cache_encoder_gob provides Gob-based encoding for cache values.
|
Package cache_encoder_gob provides Gob-based encoding for cache values. |
|
cache/cache_encoder_json
Package cache_encoder_json provides JSON-based encoding for cache values.
|
Package cache_encoder_json provides JSON-based encoding for cache values. |
|
cache/cache_provider_mock
Package cache_provider_mock provides an in-memory mock cache provider for testing.
|
Package cache_provider_mock provides an in-memory mock cache provider for testing. |
|
cache/cache_provider_multilevel
Package cache_provider_multilevel provides a multi-level cache adapter with L1/L2 coordination and circuit breaker resilience.
|
Package cache_provider_multilevel provides a multi-level cache adapter with L1/L2 coordination and circuit breaker resilience. |
|
cache/cache_provider_otter
Package cache_provider_otter provides a high-performance in-memory cache provider backed by the Otter library.
|
Package cache_provider_otter provides a high-performance in-memory cache provider backed by the Otter library. |
|
cache/cache_transformer_crypto
Package cache_transformer_crypto provides encryption transformation for cache values using the centralised crypto service.
|
Package cache_transformer_crypto provides encryption transformation for cache values using the centralised crypto service. |
|
cache/cache_transformer_zstd
Package cache_transformer_zstd provides Zstandard compression transformation for cache values.
|
Package cache_transformer_zstd provides Zstandard compression transformation for cache values. |
|
captcha
Package captcha provides the public API for captcha verification in Piko.
|
Package captcha provides the public API for captcha verification in Piko. |
|
captcha/captcha_provider_hmac_challenge
Package captcha_provider_hmac_challenge provides a built-in HMAC-based captcha provider.
|
Package captcha_provider_hmac_challenge provides a built-in HMAC-based captcha provider. |
|
clock
Package clock provides a time abstraction for testability.
|
Package clock provides a time abstraction for testability. |
|
collection
Package collection provides the public API for integrating external data sources with the Piko collection system.
|
Package collection provides the public API for integrating external data sources with the Piko collection system. |
|
config
Package config provides a reflection-based configuration loading framework that populates structs from multiple sources with a clear precedence order.
|
Package config provides a reflection-based configuration loading framework that populates structs from multiple sources with a clear precedence order. |
|
crypto
Package crypto provides the public API for encryption and key management in Piko.
|
Package crypto provides the public API for encryption and key management in Piko. |
|
crypto/crypto_provider_local_aes_gcm
Package crypto_provider_local_aes_gcm provides a local AES-256-GCM encryption provider.
|
Package crypto_provider_local_aes_gcm provides a local AES-256-GCM encryption provider. |
|
crypto/crypto_streaming
Package crypto_streaming provides streaming encryption primitives for envelope encryption with constant memory usage.
|
Package crypto_streaming provides streaming encryption primitives for envelope encryption with constant memory usage. |
|
db
Package db handles database migration management and SQL code generation for Piko applications, with pluggable engine backends for different SQL dialects.
|
Package db handles database migration management and SQL code generation for Piko applications, with pluggable engine backends for different SQL dialects. |
|
db/db_schema_orchestrator_sqlite
Package db_schema_orchestrator_sqlite provides embedded SQLite migration files for the piko orchestrator database.
|
Package db_schema_orchestrator_sqlite provides embedded SQLite migration files for the piko orchestrator database. |
|
db/db_schema_registry_sqlite
Package db_schema_registry_sqlite provides embedded SQLite migration files for the piko registry database.
|
Package db_schema_registry_sqlite provides embedded SQLite migration files for the piko registry database. |
|
email
Package email provides a provider-agnostic framework for sending emails, with support for templating, attachments, and background dispatch.
|
Package email provides a provider-agnostic framework for sending emails, with support for templating, attachments, and background dispatch. |
|
email/email_provider_disk
Package email_provider_disk provides a disk-based email provider that writes emails as standard .eml files to the local filesystem.
|
Package email_provider_disk provides a disk-based email provider that writes emails as standard .eml files to the local filesystem. |
|
email/email_provider_mock
Package email_provider_mock provides a mock email provider for testing purposes.
|
Package email_provider_mock provides a mock email provider for testing purposes. |
|
email/email_provider_stdout
Package email_provider_stdout provides an email provider that writes messages to standard output.
|
Package email_provider_stdout provides an email provider that writes messages to standard output. |
|
encoding
Package encoding provides base-X encoding utilities and UUID generation.
|
Package encoding provides base-X encoding utilities and UUID generation. |
|
events
Package events provides access to Piko's message bus infrastructure powered by Watermill.
|
Package events provides access to Piko's message bus infrastructure powered by Watermill. |
|
events/events_provider_gochannel
Package events_provider_gochannel provides an in-memory Watermill pub/sub provider using Go channels.
|
Package events_provider_gochannel provides an in-memory Watermill pub/sub provider using Go channels. |
|
fbs
Package fbs provides public access to the FlatBuffer versioning utilities used across Piko.
|
Package fbs provides public access to the FlatBuffer versioning utilities used across Piko. |
|
fbs/collection
Package collection provides public access to the collection FlatBuffer schema for inspecting compiled data.bin files.
|
Package collection provides public access to the collection FlatBuffer schema for inspecting compiled data.bin files. |
|
fbs/i18n
Package i18n provides public access to the i18n FlatBuffer schema for inspecting compiled i18n.bin files.
|
Package i18n provides public access to the i18n FlatBuffer schema for inspecting compiled i18n.bin files. |
|
fbs/manifest
Package manifest provides public access to the manifest FlatBuffer schema for inspecting compiled manifest.bin files.
|
Package manifest provides public access to the manifest FlatBuffer schema for inspecting compiled manifest.bin files. |
|
fbs/search
Package search provides public access to the search FlatBuffer schema for inspecting compiled search index .bin files.
|
Package search provides public access to the search FlatBuffer schema for inspecting compiled search index .bin files. |
|
formatter
Package formatter exposes the Piko template formatter for .pk files.
|
Package formatter exposes the Piko template formatter for .pk files. |
|
highlight
Package highlight provides syntax highlighting for code blocks in Piko applications.
|
Package highlight provides syntax highlighting for code blocks in Piko applications. |
|
interp/interp_link
Package interp_link exposes the sentinel type used to bridge Go generic functions into Piko's interpreter.
|
Package interp_link exposes the sentinel type used to bridge Go generic functions into Piko's interpreter. |
|
json
Package json provides a pluggable JSON encoding and decoding abstraction.
|
Package json provides a pluggable JSON encoding and decoding abstraction. |
|
lifecycle
Package lifecycle provides utilities for managing application lifecycle events, including graceful shutdown.
|
Package lifecycle provides utilities for managing application lifecycle events, including graceful shutdown. |
|
linguistics
Package linguistics provides text processing utilities for search and natural language processing.
|
Package linguistics provides text processing utilities for search and natural language processing. |
|
llm
Package llm provides a unified, provider-agnostic interface for interacting with large language models.
|
Package llm provides a unified, provider-agnostic interface for interacting with large language models. |
|
llm/llm_provider_voyage
Package llm_provider_voyage provides an embedding provider backed by the Voyage AI API.
|
Package llm_provider_voyage provides an embedding provider backed by the Voyage AI API. |
|
logger
Package logger provides the public API for Piko's structured, context-aware logging system.
|
Package logger provides the public API for Piko's structured, context-aware logging system. |
|
logger/logger_output_file
Package logger_output_file provides file-based log output with automatic rotation for Piko's logging system.
|
Package logger_output_file provides file-based log output with automatic rotation for Piko's logging system. |
|
logger/logger_state
Package logger_state provides shared state management for the logger facade.
|
Package logger_state provides shared state management for the logger facade. |
|
maths
Package maths provides arbitrary-precision numeric types with fluent APIs.
|
Package maths provides arbitrary-precision numeric types with fluent APIs. |
|
media
Package media provides a provider-agnostic framework for image and video processing.
|
Package media provides a provider-agnostic framework for image and video processing. |
|
media/image_provider_mock
Package image_provider_mock provides a mock implementation of the image transformer interface for testing.
|
Package image_provider_mock provides a mock implementation of the image transformer interface for testing. |
|
media/video_provider_mock
Package video_provider_mock provides a mock video transcoder for testing applications that use piko's video service.
|
Package video_provider_mock provides a mock video transcoder for testing applications that use piko's video service. |
|
metrics
Package metrics provides a provider-agnostic facade for exposing application metrics from a Piko server.
|
Package metrics provides a provider-agnostic facade for exposing application metrics from a Piko server. |
|
notification
Package notification provides a provider-agnostic framework for sending notifications from a Piko application.
|
Package notification provides a provider-agnostic framework for sending notifications from a Piko application. |
|
pdf
Package pdf provides a builder-based interface for rendering PDF documents from Piko templates, with support for metadata, watermarks, PDF/A conformance, accessibility tagging, page labels, SVG vector rendering, custom fonts, and post-processing transformations.
|
Package pdf provides a builder-based interface for rendering PDF documents from Piko templates, with support for metadata, watermarks, PDF/A conformance, accessibility tagging, page labels, SVG vector rendering, custom fonts, and post-processing transformations. |
|
runtime
Package runtime provides the stable public API consumed by Piko's generated Go code.
|
Package runtime provides the stable public API consumed by Piko's generated Go code. |
|
safeconv
Package safeconv provides safe integer type conversions with bounds checking.
|
Package safeconv provides safe integer type conversions with bounds checking. |
|
safedisk
Package safedisk provides sandboxed filesystem operations using Go 1.24's os.Root.
|
Package safedisk provides sandboxed filesystem operations using Go 1.24's os.Root. |
|
spamdetect
Package spamdetect provides the public API for spam detection in Piko.
|
Package spamdetect provides the public API for spam detection in Piko. |
|
spamdetect/spamdetect_provider_builtin_detectors
Package spamdetect_provider_builtin_detectors provides the built-in spam detection detectors: honeypot, gibberish, link density, blocklist, timing, and repetition.
|
Package spamdetect_provider_builtin_detectors provides the built-in spam detection detectors: honeypot, gibberish, link density, blocklist, timing, and repetition. |
|
storage
Package storage provides a provider-agnostic framework for object storage operations.
|
Package storage provides a provider-agnostic framework for object storage operations. |
|
storage/storage_provider_disk
Package storage_provider_disk provides a filesystem-based storage provider for the Piko storage system.
|
Package storage_provider_disk provides a filesystem-based storage provider for the Piko storage system. |
|
storage/storage_provider_mock
Package storage_provider_mock provides an in-memory mock implementation of the storage provider interface for testing and development.
|
Package storage_provider_mock provides an in-memory mock implementation of the storage provider interface for testing and development. |
|
storage/storage_transformer_crypto
Package storage_transformer_crypto provides a storage stream transformer that encrypts and decrypts data using the centralised crypto service.
|
Package storage_transformer_crypto provides a storage stream transformer that encrypts and decrypts data using the centralised crypto service. |
|
browser
module
|
|
|
cache/cache_linguistics
module
|
|
|
db/db_driver_sqlite_nocgo
module
|
|
|
db/db_engine_sqlite
module
|
|
|
highlight/highlight_chroma
module
|
|
|
interp/interp_provider_piko
module
|
|
|
json/json_provider_sonic
module
|
|
|
llm/llm_provider_ollama
module
|
|
|
llm/llm_provider_zoltai
module
|
|
|
logger/logger_otel_sdk
module
|
|
|
media/image_provider_imaging
module
|
|
|
media/image_provider_vips
module
|
|
|
monitoring/monitoring_api
module
|
|
|
storage/storage_provider_gcs
module
|
|