nextcore

package
v0.8.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 1, 2026 License: MIT Imports: 15 Imported by: 0

Documentation

Index

Constants

View Source
const (
	BuildLockFileName = ".nextdeploy/build.lock"
	MetadataFileName  = ".nextdeploy/metadata.json"
	AssetsOutputDir   = ".nextdeploy/assets"
	PublicDir         = "public"
)

Variables

View Source
var (
	NextCoreLogger = shared.PackageLogger("nextcore", "📦 NEXTCORE")
)

Functions

func BuildCSP

func BuildCSP(f *DetectedFeatures) string

BuildCSP generates a Content-Security-Policy header value based on what the app actually uses

func GetNextJsVersion

func GetNextJsVersion(packageJsonPath string) (string, error)

func IsNextJSProject

func IsNextJSProject(dir string) (bool, string, error)

func MajorVersion

func MajorVersion(v string) int

MajorVersion parses a semver-ish string like "16.1.6", "^16.0.0", "~15.2" and returns the major component. Returns 0 if it cannot be parsed (which the callers treat as "don't apply Next 16-specific behaviour").

func MaybeInjectWebpackFlag

func MaybeInjectWebpackFlag(
	buildCmd, projectDir string,
	cfg *NextConfig,
	nextVersion string,
	log buildFlagLogger,
) string

MaybeInjectWebpackFlag conditionally appends `-- --webpack` to buildCmd so the underlying `next build` runs under the webpack builder. Returns the (possibly unchanged) command.

Decision table (only modifies when all four are true):

  • next.config has a `webpack:` key
  • next.config has no `turbopack:` key
  • Next.js major version >= 16
  • package.json scripts.build ends with a `next build` invocation and does not already pin --webpack / --turbopack

If the first three are true but the script is too exotic to patch (e.g. `next build && post-step`), we log a clear warning and leave the command untouched so the user sees the real Turbopack error.

func ValidateBuildState

func ValidateBuildState() error

ValidateBuildState checks if the current git state matches the build lock

func ValidateNextJSProject

func ValidateNextJSProject(cmd *cobra.Command, args []string) error

Types

type BuildLock

type BuildLock struct {
	GitCommit   string `json:"git_commit"`
	GitDirty    bool   `json:"git_dirty"`
	GeneratedAt string `json:"generated_at"`
	Metadata    string `json:"metadata_file"`
}

type CompilerConfig

type CompilerConfig struct {
	Emotion               interface{} `json:"emotion,omitempty"`
	ReactRemoveProperties interface{} `json:"reactRemoveProperties,omitempty"`
	RemoveConsole         interface{} `json:"removeConsole,omitempty"`
	StyledComponents      interface{} `json:"styledComponents,omitempty"`
	Relay                 interface{} `json:"relay,omitempty"`
}

type DetectedFeatures

type DetectedFeatures struct {
	HasYouTube         bool
	HasGoogleFonts     bool
	HasGoogleAnalytics bool
	HasStripe          bool
	HasCloudinary      bool
	HasExternalImages  []string
	HasServerActions   bool
	HasI18n            bool
	UserDefinedCSP     bool
	AllowedOrigins     []string
	DistDir            string
	ExportDir          string
}

func DetectFeatures

func DetectFeatures(config *NextConfig) *DetectedFeatures

DetectFeatures inspects a NextConfig and returns what external services the app uses — this drives the dynamic CSP generation in Caddy

type Domain

type Domain struct {
	Domain        string   `json:"domain"`
	Locales       []string `json:"locales,omitempty"`
	DefaultLocale string   `json:"defaultLocale,omitempty"`
}

type ExperimentalConfig

type ExperimentalConfig struct {
	AppDir                            bool                   `json:"appDir,omitempty"`
	CaseSensitiveRoutes               bool                   `json:"caseSensitiveRoutes,omitempty"`
	UseDeploymentId                   bool                   `json:"useDeploymentId,omitempty"`
	UseDeploymentIdServerActions      bool                   `json:"useDeploymentIdServerActions,omitempty"`
	DeploymentId                      string                 `json:"deploymentId,omitempty"`
	ServerComponents                  bool                   `json:"serverComponents,omitempty"`
	ServerActions                     bool                   `json:"serverActions,omitempty"`
	ServerActionsBodySizeLimit        int                    `json:"serverActionsBodySizeLimit,omitempty"`
	OptimizeCss                       bool                   `json:"optimizeCss,omitempty"`
	OptimisticClientCache             bool                   `json:"optimisticClientCache,omitempty"`
	ClientRouterFilter                bool                   `json:"clientRouterFilter,omitempty"`
	ClientRouterFilterRedirects       bool                   `json:"clientRouterFilterRedirects,omitempty"`
	ClientRouterFilterAllowedRate     float64                `json:"clientRouterFilterAllowedRate,omitempty"`
	ExternalDir                       string                 `json:"externalDir,omitempty"`
	ExternalMiddlewareRewritesResolve bool                   `json:"externalMiddlewareRewritesResolve,omitempty"`
	FallbackNodePolyfills             bool                   `json:"fallbackNodePolyfills,omitempty"`
	ForceSwcTransforms                bool                   `json:"forceSwcTransforms,omitempty"`
	FullySpecified                    bool                   `json:"fullySpecified,omitempty"`
	SwcFileReading                    bool                   `json:"swcFileReading,omitempty"`
	SwcMinify                         bool                   `json:"swcMinify,omitempty"`
	SwcPlugins                        []interface{}          `json:"swcPlugins,omitempty"`
	SwcTraceProfiling                 bool                   `json:"swcTraceProfiling,omitempty"`
	Turbo                             map[string]interface{} `json:"turbo,omitempty"`
	Turbotrace                        map[string]interface{} `json:"turbotrace,omitempty"`
	ScrollRestoration                 bool                   `json:"scrollRestoration,omitempty"`
	NewNextLinkBehavior               bool                   `json:"newNextLinkBehavior,omitempty"`
	ManualClientBasePath              bool                   `json:"manualClientBasePath,omitempty"`
	LegacyBrowsers                    bool                   `json:"legacyBrowsers,omitempty"`
	DisableOptimizedLoading           bool                   `json:"disableOptimizedLoading,omitempty"`
	GzipSize                          bool                   `json:"gzipSize,omitempty"`
	SharedPool                        bool                   `json:"sharedPool,omitempty"`
	WebVitalsAttribution              []string               `json:"webVitalsAttribution,omitempty"`
	InstrumentationHook               string                 `json:"instrumentationHook,omitempty"`
}

type I18nConfig

type I18nConfig struct {
	Locales         []string `json:"locales"`
	DefaultLocale   string   `json:"defaultLocale"`
	Domains         []Domain `json:"domains,omitempty"`
	LocaleDetection bool     `json:"localeDetection,omitempty"`
}

type ISRRoute

type ISRRoute struct {
	Path       string   `json:"path"`
	Tags       []string `json:"tags"`
	Revalidate int      `json:"revalidate"`
}

type ImageAsset

type ImageAsset struct {
	Path           string `json:"path"`
	AbsolutePath   string `json:"absolute_path"`
	PublicPath     string `json:"public_path"`
	Format         string `json:"format"`
	IsOptimized    bool   `json:"is_optimized"`
	IsStaticImport bool   `json:"is_static_import"`
	Width          int    `json:"width,omitempty"`
	Height         int    `json:"height,omitempty"`
}

type ImageAssets

type ImageAssets struct {
	PublicImages    []ImageAsset `json:"public_images"`
	OptimizedImages []ImageAsset `json:"optimized_images"`
	StaticImports   []ImageAsset `json:"static_imports"`
}

type ImageConfig

type ImageConfig struct {
	Domains               []string             `json:"domains,omitempty"`
	Formats               []string             `json:"formats,omitempty"`
	DeviceSizes           []int                `json:"deviceSizes,omitempty"`
	ImageSizes            []int                `json:"imageSizes,omitempty"`
	Path                  string               `json:"path,omitempty"`
	Loader                string               `json:"loader,omitempty"`
	LoaderFile            string               `json:"loaderFile,omitempty"`
	MinimumCacheTTL       int                  `json:"minimumCacheTTL,omitempty"`
	Unoptimized           bool                 `json:"unoptimized,omitempty"`
	ContentSecurityPolicy string               `json:"contentSecurityPolicy,omitempty"`
	RemotePatterns        []ImageRemotePattern `json:"remotePatterns,omitempty"`
}

type ImageRemotePattern

type ImageRemotePattern struct {
	Protocol string `json:"protocol,omitempty"`
	Hostname string `json:"hostname,omitempty"`
	Port     string `json:"port,omitempty"`
	Pathname string `json:"pathname,omitempty"`
}

type MiddlewareCondition

type MiddlewareCondition struct {
	Type  string `json:"type"`
	Key   string `json:"key,omitempty"`
	Value string `json:"value,omitempty"`
}

type MiddlewareConfig

type MiddlewareConfig struct {
	Path         string            `json:"path"`
	Matchers     []MiddlewareRoute `json:"matchers"`
	Runtime      string            `json:"runtime,omitempty"`
	Regions      []string          `json:"regions,omitempty"`
	UnstableFlag string            `json:"unstable_flag,omitempty"`
}

func ParseMiddleware

func ParseMiddleware(projectDir string) (*MiddlewareConfig, error)

ParseMiddleware parses Next.js middleware configuration

type MiddlewareRoute

type MiddlewareRoute struct {
	Pathname string                `json:"pathname,omitempty"`
	Pattern  string                `json:"pattern,omitempty"`
	Has      []MiddlewareCondition `json:"has,omitempty"`
	Missing  []MiddlewareCondition `json:"missing,omitempty"`
	Type     string                `json:"type,omitempty"`
	Key      string                `json:"key,omitempty"`
	Value    string                `json:"value,omitempty"`
}

type NextBuildMetadata

type NextBuildMetadata struct {
	BuildID               string      `json:"buildId"`
	BuildManifest         interface{} `json:"buildManifest"`
	AppBuildManifest      interface{} `json:"appBuildManifest"`
	PrerenderManifest     interface{} `json:"prerenderManifest"`
	RoutesManifest        interface{} `json:"routesManifest"`
	ImagesManifest        interface{} `json:"imagesManifest"`
	AppPathRoutesManifest interface{} `json:"appPathRoutesManifest"`
	ReactLoadableManifest interface{} `json:"reactLoadableManifest"`
	Diagnostics           []string    `json:"diagnostics"`
	HasAppRouter          bool        `json:"hasAppRouter"`
}

func CollectBuildMetadata

func CollectBuildMetadata(buildCmd string) (*NextBuildMetadata, error)

CollectBuildMetadata runs the Next.js build and reads the manifests it produces. It intentionally does NOT compute OutputMode — the canonical source is NextConfig.Output, and the caller threads that into the payload.

type NextConfig

type NextConfig struct {
	BasePath                   string                 `json:"basePath,omitempty"`
	Output                     string                 `json:"output,omitempty"`
	Images                     *ImageConfig           `json:"images,omitempty"`
	ReactStrictMode            bool                   `json:"reactStrictMode,omitempty"`
	PoweredByHeader            bool                   `json:"poweredByHeader,omitempty"`
	TrailingSlash              bool                   `json:"trailingSlash,omitempty"`
	PageExtensions             []string               `json:"pageExtensions,omitempty"`
	AssetPrefix                string                 `json:"assetPrefix,omitempty"`
	DistDir                    string                 `json:"distDir,omitempty"`
	CleanDistDir               bool                   `json:"cleanDistDir,omitempty"`
	GenerateBuildId            interface{}            `json:"generateBuildId,omitempty"`
	OnDemandEntries            map[string]interface{} `json:"onDemandEntries,omitempty"`
	CompileOptions             map[string]interface{} `json:"compileOptions,omitempty"`
	Headers                    []interface{}          `json:"headers,omitempty"`
	Redirects                  []interface{}          `json:"redirects,omitempty"`
	Rewrites                   []interface{}          `json:"rewrites,omitempty"`
	SkipMiddlewareUrlNormalize bool                   `json:"skipMiddlewareUrlNormalize,omitempty"`
	SkipTrailingSlashRedirect  bool                   `json:"skipTrailingSlashRedirect,omitempty"`
	Env                        map[string]string      `json:"env,omitempty"`
	PublicRuntimeConfig        map[string]interface{} `json:"publicRuntimeConfig,omitempty"`
	ServerRuntimeConfig        map[string]interface{} `json:"serverRuntimeConfig,omitempty"`
	Compiler                   *CompilerConfig        `json:"compiler,omitempty"`
	Webpack                    interface{}            `json:"webpack,omitempty"`
	Webpack5                   bool                   `json:"webpack5,omitempty"`
	Turbopack                  interface{}            `json:"turbopack,omitempty"`
	Experimental               *ExperimentalConfig    `json:"experimental,omitempty"`
	EdgeRegions                []string               `json:"edgeRegions,omitempty"`
	EdgeRuntime                string                 `json:"edgeRuntime,omitempty"`
	I18n                       *I18nConfig            `json:"i18n,omitempty"`
	AnalyticsId                string                 `json:"analyticsId,omitempty"`
	MdxRs                      bool                   `json:"mdxRs,omitempty"`
}

func ParseNextConfigFile

func ParseNextConfigFile(configPath string) (*NextConfig, error)

ParseNextConfigFile reads next.config.mjs/js and returns a parsed NextConfig It uses a JS runtime (bun/node) to evaluate the config accurately.

type NextCorePayload

type NextCorePayload struct {
	AppName           string            `json:"app_name"`
	NextBuildMetadata NextBuildMetadata `json:"nextbuildmetadata"`
	CDNEnabled        bool              `json:"cdn_enabled"`
	Domain            string            `json:"domain"`
	Middleware        *MiddlewareConfig `json:"middleware"`
	StaticAssets      *StaticAssets     `json:"static_assets"`
	GitCommit         string            `json:"git_commit,omitempty"`
	GitDirty          bool              `json:"git_dirty,omitempty"`
	GeneratedAt       string            `json:"generated_at,omitempty"`
	Config            config.SafeConfig `json:"config,omitempty"`
	ImageAssets       ImageAssets       `json:"image_assets"`
	RouteInfo         RouteInfo         `json:"route_info"`
	DetectedFeatures  *DetectedFeatures `json:"detected_features,omitempty"`
	DistDir           string            `json:"dist_dir"`
	ExportDir         string            `json:"export_dir"`
	OutputMode        OutputMode        `json:"output_mode"`
	PackageManager    string            `json:"package_manager"`
}

func GenerateMetadata

func GenerateMetadata() (metadata NextCorePayload, err error)

func LoadMetadata

func LoadMetadata() (NextCorePayload, error)

type OutputMode

type OutputMode string
const (
	OutputModeDefault    OutputMode = "default"
	OutputModeStandalone OutputMode = "standalone"
	OutputModeExport     OutputMode = "export"
)

type PackageJSON

type PackageJSON struct {
	Name            string            `json:"name"`
	Version         string            `json:"version"`
	Dependencies    map[string]string `json:"dependencies"`
	DevDependencies map[string]string `json:"devDependencies"`
	Scripts         map[string]string `json:"scripts"`
	Private         bool              `json:"private"`
}

type PackageManager

type PackageManager string
const (
	NPM     PackageManager = "npm"
	Yarn    PackageManager = "yarn"
	PNPM    PackageManager = "pnpm"
	BUN     PackageManager = "bun"
	Unknown PackageManager = "unknown"
)

func DetectPackageManager

func DetectPackageManager(projectPath string) (PackageManager, error)

func (PackageManager) String

func (pm PackageManager) String() string

type RouteInfo

type RouteInfo struct {
	StaticRoutes     []string          `json:"static_routes"`
	DynamicRoutes    []string          `json:"dynamic_routes"`
	SSGRoutes        map[string]string `json:"ssg_routes"`
	SSRRoutes        []string          `json:"ssr_routes"`
	ISRRoutes        map[string]string `json:"isr_routes"` // Route -> HTML File Path
	ISRDetail        []ISRRoute        `json:"isr_detail"` // Extended tagging info for ISR
	APIRoutes        []string          `json:"api_routes"`
	FallbackRoutes   map[string]string `json:"fallback_routes"`
	MiddlewareRoutes []string          `json:"middleware_routes"`
}

type StaticAsset

type StaticAsset struct {
	Path         string `json:"path"`
	AbsolutePath string `json:"absolute_path"`
	PublicPath   string `json:"public_path"`
	Type         string `json:"type"`
	Extension    string `json:"extension"`
	Size         int64  `json:"size"`
}

type StaticAssets

type StaticAssets struct {
	PublicDir    []StaticAsset `json:"public_dir"`
	StaticFolder []StaticAsset `json:"static_folder"`
	NextStatic   []StaticAsset `json:"next_static"`
	OtherAssets  []StaticAsset `json:"other_assets"`
}

func ParseStaticAssets

func ParseStaticAssets(projectDir string, distDir string) (*StaticAssets, error)

ParseStaticAssets scans the project for static assets

type TagPathMap

type TagPathMap struct {
	// tag -> list of cloudfront paths to invalidate
	Tags      map[string][]string `json:"tags"`
	Intervals map[string]int      `json:"intervals"`
}

func BuildTagMap

func BuildTagMap(routes []ISRRoute) TagPathMap

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL