Skip to content

Integration API reference

Source information
  • Package: @pikacss/integration
  • Generated from the exported surface and JSDoc in packages/integration/src/index.ts.
  • Source files: packages/integration/src/compiler/analyze.ts, packages/integration/src/compiler/errors.ts, packages/integration/src/compiler/evaluate.ts, packages/integration/src/compiler/parse.ts, packages/integration/src/ctx.ts, packages/integration/src/fnConfig.ts, packages/integration/src/index.ts, packages/integration/src/log.ts, packages/integration/src/moduleId.ts, packages/integration/src/processors/js.ts, packages/integration/src/processors/registry.ts, packages/integration/src/processors/types.ts, packages/integration/src/types.ts

Package summary

Build-tool integration context Re-exports the public surface of @pikacss/core.

Use Unplugin integration when you need conceptual usage guidance instead of exact symbol lookup.

Functions

analyzeJs(code, id, dialect, fnConfig, options?)

Analyzes a JavaScript/TypeScript source chunk: parse, collect macro calls, and statically evaluate each call's arguments.

ParameterTypeDescription
codestringThe source chunk.
idstringNormalized absolute path of the module (for diagnostics).
dialectJsDialectThe JsDialect deciding the parser plugin set.
fnConfigFnConfigThe variant config derived from the base function name.
options?AnalyzeJsOptionsOptional AnalyzeJsOptions.

Returns: MacroCall[] - Macro calls sorted by start offset. Offsets are absolute into the surrounding file when options.offsets is set.



createCtx(options)

Creates an IntegrationContext that wires together config loading, engine initialization, source file transformation, and codegen output.

ParameterTypeDescription
optionsIntegrationContextOptionsThe integration configuration including paths, function name, scan globs, and codegen settings.

Returns: IntegrationContext - A fully constructed IntegrationContext. Call setup() on the returned context before using transforms.

The context uses reactive signals internally so that computed paths (CSS and TS codegen file paths) automatically update when cwd changes. The setup() method must be called before any transform or codegen operations - transform calls automatically await the pending setup promise.



createDefaultProcessorRegistry()

Creates the default processor registry: the JS/TS processor (static import — it is the hot path) and the Vue SFC processor (lazy — @vue/compiler-sfc never loads in non-Vue projects).

Returns: ProcessorRegistry - The default ProcessorRegistry.



createFnConfig(fnName)

Builds the structured variant config for all pika() call forms derived from the given base name.

ParameterTypeDescription
fnNamestringThe base function name (e.g. 'pika'). The preview name (p suffix) and .str/.arr members are derived from it.

Returns: FnConfig - An immutable FnConfig describing all six variants.

Remarks:

Keep variant derivation in sync with buildFnNamePatterns in @pikacss/eslint-config (packages/eslint-config/src/utils/fn-names.ts), which re-derives the same dot-form variants without a runtime dependency on this package. The consistency test in its fn-names.test.ts guards the agreement.

ts
const config = createFnConfig('pika')
config.roots.has('pikap') // true
config.variants.get('pika.str')?.kind // 'forceString'


createProcessorRegistry()

Creates an empty processor registry.

Returns: ProcessorRegistry - A ProcessorRegistry with case-insensitive extension keys and memoized lazy loading.



dialectForExtension(ext)

Maps a file extension to the JsDialect it is parsed as.

ParameterTypeDescription
extstringLowercase extension without the leading dot.

Returns: JsDialect - The dialect; unknown extensions fall back to 'js'.



evaluateStatic(node, ctx)

Statically evaluates a macro-call argument AST node to a plain value.

ParameterTypeDescription
nodet.NodeThe argument expression node.
ctxEvaluateContextThe EvaluateContext carrying the module id and scope lookup.

Returns: unknown - The evaluated plain value (JSON-serializable by construction, plus undefined).

Remarks:

Replaces the legacy new Function() evaluation of argument source text. Supported: literals, undefined/NaN/Infinity (when unshadowed), unary - + ! void, static template literals, object/array expressions (including static computed keys, spreads, and holes), conditional and logical short-circuits, and binary + - * / === !== on static operands.



nodeLoc(node)

Extracts a TransformErrorLoc from an AST node's source location.

ParameterTypeDescription
node{ loc?: { start: { line: number, column: number } } | null }Any node carrying an optional Babel-style loc.

Returns: TransformErrorLoc \| null - The start position, or null when the node has no location info.



parseJs(code, dialect, offsets?)

Parses a JavaScript/TypeScript source file into a Babel AST.

ParameterTypeDescription
codestringThe source chunk to parse.
dialectJsDialectThe JsDialect deciding the parser plugin set.
offsets?ParseOffsetsOptional ParseOffsets making emitted positions absolute into a surrounding file.

Returns: t.File - The parsed File node.



parseJsExpression(code, dialect, offsets?)

Parses a bare JavaScript/TypeScript expression (e.g. a Vue template expression) into a Babel AST node.

ParameterTypeDescription
codestringThe expression source.
dialectJsDialectThe JsDialect deciding the parser plugin set.
offsets?ParseOffsetsOptional ParseOffsets making emitted positions absolute into a surrounding file.

Returns: t.Expression - The parsed expression node.



parseModuleId(id, cwd)

Parses a bundler module id into its canonical identity.

ParameterTypeDescription
idstringA module id: absolute or cwd-relative file path, optionally carrying ?query and/or #hash suffixes.
cwdstringThe base directory used to resolve relative ids.

Returns: ParsedModuleId - The ParsedModuleId with a normalized absolute file, the raw query (hash excluded), and the lowercase ext.

ts
parseModuleId('src/App.vue?vue&type=script', '/repo')
// { file: '/repo/src/App.vue', query: 'vue&type=script', ext: 'vue' }


resolveOutputFormat(variant, transformedFormat)

Resolves the concrete output format for a call variant under the given default format.

ParameterTypeDescription
variantFnVariantThe matched call variant.
transformedFormat'string' | 'array'The integration's configured default output format for normal calls.

Returns: 'string' \| 'array' - 'string' or 'array' — the format the transformed literal must use.



Constants

consoleDiagnosticHandler

Default diagnostic adapter used by official Node.js integrations.



JS_PROCESSOR_EXTENSIONS

File extensions handled by the built-in JS/TS processor.



jsProcessor

The built-in JavaScript/TypeScript processor.

Remarks:

Emitted literals always use single quotes for JS sources (engine invariant: the transformed output convention predates the AST compiler and is pinned by regression tests).



log

Console-backed logger used by Node.js build-tool integrations.



Classes

PikaTransformError

Error thrown when a module cannot be transformed.

PropertyTypeDescriptionDefault
idstringNormalized absolute path of the failing module.
locTransformErrorLoc | nullOne-based position of the failure inside the module, when known.
stageTransformErrorStagePipeline stage that failed.

Remarks:

Module transforms are atomic: any failure aborts the whole module without committing partial results, and this error propagates to the bundler (dev overlay / failed build). The id and loc fields follow the shape bundlers (Vite/Rollup) read to render code frames for plugin errors.



Types

AnalyzedModule

Result of analyzing one module: every macro call found in it.

PropertyTypeDescriptionDefault
idstringNormalized absolute path of the module.
codestringThe exact source that was analyzed.
callsMacroCall[]Macro calls sorted by start offset (deterministic within-module order).


AnalyzeJsOptions

Options for analyzeJs.

PropertyTypeDescriptionDefault
offsets?ParseOffsetsPosition offsets when the chunk is embedded in a surrounding file (e.g. a Vue SFC script block).
quote?'"' | '\''Quote character for emitted literals at the found call sites.'
parseMode?'program' | 'expression'How to parse the chunk. 'expression' parses a bare expression (e.g. a Vue template interpolation, where { a: 1 } must be an object literal, not a block statement).'program'
excludedRoots?ReadonlySet<string>Root identifiers shadowed by the surrounding non-JS context (e.g. Vue v-for aliases); calls through them are not macros.


EvaluateContext

Context for statically evaluating a macro-call argument.

PropertyTypeDescriptionDefault
idstringNormalized absolute path of the module, used in error messages.
hasLocalBinding(name: string) => booleanReturns whether the given name resolves to a local binding at the call site. Global constants (undefined, NaN, Infinity) are only evaluable when unshadowed.


FnConfig

Structured description of all pika() call variants derived from a base function name.

PropertyTypeDescriptionDefault
fnNamestringThe configured base function name (e.g. 'pika').
previewFnNamestringThe preview function name derived from the base name (e.g. 'pikap').
rootsReadonlySet<string>Root identifiers that make a callee a candidate macro call.
variantsReadonlyMap<string, FnVariant>All variants keyed by canonical dot-form name.

Remarks:

Replaces the legacy regex-based FnUtils classification: the AST macro collector matches call sites against roots and looks classification up in variants instead of testing name strings against a compiled regex.



FnOutputKind

Output-format classification of a pika() call variant.

  • 'normal' — output format follows the integration's transformedFormat option.
  • 'forceString' — always emits a space-joined string literal (pika.str).
  • 'forceArray' — always emits an array of string literals (pika.arr).

Type: "normal" | "forceString" | "forceArray"



FnVariant

One recognized pika() call variant, derived from the configured base function name.

PropertyTypeDescriptionDefault
namestringCanonical dot-form name, e.g. 'pika', 'pika.str', 'pikap.arr'.
rootstringRoot identifier of the call site: the base function name or its preview counterpart.
property'str' | 'arr' | nullMember property of the variant, or null for bare calls.
kindFnOutputKindOutput-format classification of this variant.
previewbooleanWhether this is a preview variant (pikap, pikap.str, pikap.arr).

Remarks:

Variants are identified by their canonical dot-form name (e.g. 'pika.str'). Bracket-notation call sites (pika['str'], pika[`str`]) are normalized to the dot form by the macro collector before variant lookup, so bracket forms are never enumerated here.



FrameworkProcessor

A framework-specific source analyzer.

PropertyTypeDescriptionDefault
namestringDiagnostic name of the processor (e.g. 'js', 'vue').
analyze(code: string, id: string, options: ProcessorOptions) => Promise<AnalyzedModule> | AnalyzedModuleAnalyzes a module and returns every macro call in it.

Remarks:

Processors only ANALYZE — they never rewrite. The pipeline applies all replacements itself so module transforms stay atomic. A processor must throw PikaTransformError on any parse/scope/evaluation failure; partial results are never returned. This is the extensibility seam for future framework support (svelte, astro, ...): implement this interface and register the extensions in the processor registry.



IntegrationContext

The main build-tool integration context that bridges the PikaCSS engine with bundler plugins.

PropertyTypeDescriptionDefault
cwdstringThe current working directory. Can be updated at runtime (e.g., when the project root changes).
configErrorBehavior'throw' | 'retain-last-good'How the context reacts to a config file that fails to evaluate or an engine that fails to build. Set by the bundler adapter from the build mode.
currentPackageNamestringThe npm package name of the integration consumer, used in generated file headers and module declarations.
fnNamestringThe base function name recognized in source transforms (e.g., 'pika').
transformedFormat'string' | 'array'The default output format for normal pika() calls: 'string' or 'array'.
cssCodegenFilepathstringAbsolute path to the generated CSS output file, computed from cwd and the configured relative path.
tsCodegenFilepathstring | NullishAbsolute path to the generated TypeScript declaration file, or null if TypeScript codegen is disabled.
hasVuebooleanWhether the vue package is installed in the project, used to include Vue-specific type declarations in codegen.
resolvedConfigEngineConfig | NullishThe loaded engine configuration object, or null if loading failed or no config was found.
resolvedConfigPathstring | NullishAbsolute path to the resolved config file on disk, or null for inline configs or when no config was loaded.
resolvedConfigContentstring | NullishRaw string content of the config file, or null for inline configs or when no config was loaded.
loadConfig() => Promise<LoadedConfigResult>Loads (or reloads) the engine configuration from disk or inline source, updating resolvedConfig, resolvedConfigPath, and resolvedConfigContent.
usagesMap<string, UsageRecord[]>Map from source file ID to the list of UsageRecord entries extracted during transforms. Keyed by the normalized absolute file path (parseModuleId(...).file).
previewUsagesMap<string, UsageRecord[]>Map from source file ID to preview-only UsageRecord entries (from pikap() calls). Only these drive TypeScript preview overload generation.
hooks{ styleUpdated: ReturnType<typeof createEventHook<void>> tsCodegenUpdated: ReturnType<typeof createEventHook<void>> }Event hooks for notifying plugins when generated outputs need refreshing. styleUpdated fires on CSS changes; tsCodegenUpdated fires on TypeScript declaration changes.
engineEngineThe initialized PikaCSS engine instance. Throws if accessed before setup() completes.
transformFilter{ include: string[] exclude: string[] }Glob patterns for the bundler's transform pipeline, derived from the scan config with codegen files excluded.
isTransformTarget(id: string) => booleanReturns whether a module id should be transformed, evaluated against the CURRENT cwd.
isIdlebooleanWhether no transform() calls are currently in flight.
waitForIdle() => Promise<void>Resolves once all in-flight transform() calls have settled.
transform(code: string, id: string) => Promise<{ code: string, map: SourceMap } | Nullish>Processes a source file by extracting pika() calls via the AST compiler, resolving them through the engine, and replacing them with computed output.
dropModule(id: string) => voidDrops all state for a module (usages, preview usages, prepared results), e.g. when the bundler reports the file as deleted. Accepts raw bundler ids (relative paths, query/hash suffixes) and normalizes them internally. Queues output regeneration when styles were dropped.
getScannedButNotTransformedFiles() => string[]Returns the physical files whose styles entered the generated CSS during the build-mode full scan but that the bundler's own transform pass never reached — dead files or files missing from the import graph. Sorted; empty in dev mode (no full scan).
getCssCodegenContent() => Promise<string | Nullish>Generates the full CSS output string, including layer declarations, preflights, and all atomic styles collected from transforms.
getTsCodegenContent() => Promise<string | Nullish>Generates the full TypeScript declaration content for pika.gen.ts, or null if TypeScript codegen is disabled.
writeCssCodegenFile() => Promise<void>Generates and writes the CSS codegen file to disk at cssCodegenFilepath.
writeTsCodegenFile() => Promise<void>Generates and writes the TypeScript codegen file to disk at tsCodegenFilepath. No-op if TypeScript codegen is disabled.
fullyCssCodegen() => Promise<void>Scans all matching source files, collects usages via transform, then writes the CSS codegen file. Used for full rebuilds.
setupPromisePromise<void> | nullThe pending setup promise while initialization is in progress, or null when idle. Transform calls await this before proceeding.
setup() => Promise<void>Initializes (or reinitializes) the context by clearing state, loading config, creating the engine, and wiring up dev hooks. Returns a promise that resolves when setup is complete.

Remarks:

Created via createCtx(). The context manages the full build lifecycle: config loading, engine initialization, source file transformation, usage tracking, and output file generation. All transform and codegen calls automatically await setup() completion before proceeding.



IntegrationContextOptions

Configuration options for creating an integration context.

PropertyTypeDescriptionDefault
cwdstringThe working directory used to resolve relative paths for config files, codegen outputs, and source scanning.
currentPackageNamestringThe npm package name of the integration consumer (e.g., '@pikacss/unplugin-pikacss'), embedded in generated file headers and import paths.
scan{ include: string[] exclude: string[] }Glob patterns controlling which source files are scanned for pika() calls. include specifies files to process; exclude specifies files to skip.
configOrPathEngineConfig | string | NullishThe engine configuration object, a path to a config file, or null/undefined to trigger auto-discovery of pika.config.* files.
fnNamestringThe base function name to recognize in source code (e.g., 'pika'). All variants (.str, .arr, preview) are derived from this name.
transformedFormat'string' | 'array'Controls the default output format of normal pika() calls: 'string' produces a space-joined class string, 'array' produces a string array.
tsCodegenfalse | stringPath to the generated TypeScript declaration file (pika.gen.ts), or false to disable TypeScript codegen entirely.
cssCodegenstringPath to the generated CSS output file (e.g., 'pika.gen.css').
autoCreateConfigbooleanWhen true, automatically scaffolds a default pika.config.js file if no config file is found.
onDiagnostic?DiagnosticHandlerReceives engine diagnostics. Defaults to the official console adapter.

Remarks:

These options are set by bundler plugin adapters (Vite, webpack, Nuxt) and are not typically configured by end users directly.



JsDialect

JavaScript dialect a source chunk is parsed as.

Type: "js" | "jsx" | "ts" | "tsx"

Remarks:

.ts sources must NOT enable the jsx plugin: TypeScript angle-bracket casts (<T>expr) are only parseable without it. .tsx enables both.



LoadedConfigResult

Discriminated union representing the outcome of loading an engine configuration file.

Remarks:

Four shapes are possible: an inline config (no file), a successfully loaded file-based config, a file that exists but failed to evaluate (path and content kept so integrations can watch it and reload after a fix), or a missing load (all fields null). The file and content fields are populated whenever the config file was found on disk, enabling hot-reload detection.



MacroCall

A fully analyzed pika() macro call: its variant, source range, and statically evaluated arguments.

PropertyTypeDescriptionDefault
variantFnVariantThe matched call variant.
startnumberZero-based character offset where the call begins in the module source.
endnumberZero-based character offset one past the call's closing parenthesis (exclusive).
loc{ line: number, column: number }One-based position of the call, for diagnostics.
argsParameters<Engine['use']>Statically evaluated engine.use() arguments (plain data by construction).
quote'"' | '\''Quote character for the emitted literal at this site (' for JS sources; AST-derived in Vue templates).


ParsedModuleId

Normalized identity of a bundler module id.

PropertyTypeDescriptionDefault
filestringNormalized absolute file path with query/hash stripped.
querystring | nullRaw query string without the leading ?, or null when the id has none.
extstringLowercase file extension without the leading dot, or '' when the file has none.

Remarks:

Bundler ids come in many shapes for the same physical file: absolute or cwd-relative paths, ids with query strings (App.vue?vue&type=script), and hash suffixes. All per-module state (usages, prepared results) must be keyed by the same canonical form, which is file.



ParseOffsets

Position offsets applied to all emitted node positions, used when parsing an embedded source chunk (e.g. a Vue SFC block) so node offsets/locations are absolute into the surrounding file.

PropertyTypeDescriptionDefault
startIndex?numberZero-based character offset of the chunk inside the surrounding file.
startLine?numberOne-based line of the chunk's first character.
startColumn?numberZero-based column of the chunk's first character.


ProcessorLoader

Lazily loads a FrameworkProcessor; heavyweight parser dependencies are only imported when a matching file is actually analyzed.



ProcessorOptions

Options handed to a processor's analyze.

PropertyTypeDescriptionDefault
fnConfigFnConfigThe variant config derived from the configured base function name.


ProcessorRegistry

Registry mapping file extensions to framework processors.

PropertyTypeDescriptionDefault
register(extensions: string[], loader: ProcessorLoader) => voidRegisters a lazy processor for the given extensions (leading dots optional, case-insensitive).
resolve(ext: string) => Promise<FrameworkProcessor> | nullResolves the processor for an extension, or null when none is registered. Loaded processors are memoized.
has(ext: string) => booleanReturns whether a processor is registered for the extension.


TransformErrorLoc

One-based source position of a transform failure.

PropertyTypeDescriptionDefault
linenumberOne-based line number of the failure.
columnnumberZero-based column of the failure (Babel convention).


TransformErrorStage

Pipeline stage in which a transform failure occurred.

  • 'parse' — source (or an embedded expression) failed to parse.
  • 'collect' — the macro-call collector rejected a call site.
  • 'evaluate' — a call argument is not statically evaluable.
  • 'prepare' — resolving a call through the engine failed.

Type: "parse" | "collect" | "evaluate" | "prepare"



UsageRecord

Records a single pika() call result, pairing the resolved atomic style IDs with the original call arguments.

PropertyTypeDescriptionDefault
atomicStyleIdsstring[]The list of atomic CSS class names generated by the engine for this call.
paramsParameters<Engine['use']>The original arguments passed to engine.use(), preserved for TypeScript codegen overload generation.

Remarks:

Each source file may produce multiple UsageRecord entries — one per pika() call site. These records drive both CSS output (via atomicStyleIds) and IDE preview overloads (via params).



Next