@dsai-io/tools 1.0.7 → 1.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli/index.js CHANGED
@@ -1,12 +1,13 @@
1
1
  import * as fs3 from 'fs';
2
- import { existsSync, readFileSync, readdirSync, statSync, writeFileSync, mkdirSync, rmSync, copyFileSync } from 'fs';
2
+ import { existsSync, readFileSync, mkdirSync, writeFileSync, readdirSync, statSync, rmSync, copyFileSync } from 'fs';
3
3
  import * as path4 from 'path';
4
- import path4__default, { relative, basename, extname, join, dirname, parse, resolve } from 'path';
4
+ import path4__default, { resolve, join, basename, dirname, relative, extname, parse } from 'path';
5
5
  import { z } from 'zod';
6
6
  import { createHash } from 'crypto';
7
7
  import fg from 'fast-glob';
8
- import { execSync } from 'child_process';
8
+ import { execFileSync, execSync } from 'child_process';
9
9
  import { readFile, writeFile } from 'fs/promises';
10
+ import { fileURLToPath } from 'url';
10
11
  import { Command } from 'commander';
11
12
  import { cosmiconfig } from 'cosmiconfig';
12
13
  import e from 'picocolors';
@@ -4385,20 +4386,6 @@ var init_line_height = __esm({
4385
4386
  }
4386
4387
  });
4387
4388
 
4388
- // src/tokens/style-dictionary/transforms/name.ts
4389
- var nameKebab;
4390
- var init_name = __esm({
4391
- "src/tokens/style-dictionary/transforms/name.ts"() {
4392
- nameKebab = {
4393
- name: "name/kebab",
4394
- type: "name",
4395
- transform: (token) => {
4396
- return token.path.join("-").replace(/_/g, "-").toLowerCase();
4397
- }
4398
- };
4399
- }
4400
- });
4401
-
4402
4389
  // src/tokens/style-dictionary/transforms/name-js-identifier.ts
4403
4390
  function toPascalCaseSegment3(segment) {
4404
4391
  const needsNumericPrefix = /^\d/.test(segment);
@@ -4418,6 +4405,20 @@ var init_name_js_identifier = __esm({
4418
4405
  }
4419
4406
  });
4420
4407
 
4408
+ // src/tokens/style-dictionary/transforms/name.ts
4409
+ var nameKebab;
4410
+ var init_name = __esm({
4411
+ "src/tokens/style-dictionary/transforms/name.ts"() {
4412
+ nameKebab = {
4413
+ name: "name/kebab",
4414
+ type: "name",
4415
+ transform: (token) => {
4416
+ return token.path.join("-").replace(/_/g, "-").toLowerCase();
4417
+ }
4418
+ };
4419
+ }
4420
+ });
4421
+
4421
4422
  // src/tokens/style-dictionary/transforms/index.ts
4422
4423
  var transforms_exports = {};
4423
4424
  __export(transforms_exports, {
@@ -4446,8 +4447,8 @@ var init_transforms = __esm({
4446
4447
  init_dimension();
4447
4448
  init_font_weight();
4448
4449
  init_line_height();
4449
- init_name();
4450
4450
  init_name_js_identifier();
4451
+ init_name();
4451
4452
  init_font_weight();
4452
4453
  init_line_height();
4453
4454
  init_dimension();
@@ -7877,494 +7878,225 @@ var require_src = __commonJS({
7877
7878
  module.exports = { cursor, scroll, erase, beep };
7878
7879
  }
7879
7880
  });
7880
- var logLevelSchema = z.enum(["silent", "error", "warn", "info", "debug", "verbose"]);
7881
- var outputFormatSchema = z.enum(["css", "scss", "less", "json", "js", "ts", "esm", "cjs"]);
7882
- var frameworkSchema = z.enum(["react", "vue", "angular", "svelte", "vanilla"]);
7883
- var hashTypeSchema = z.enum(["content", "timestamp", "version", "none"]);
7884
- z.string().min(1, "Glob pattern cannot be empty");
7885
- z.string().min(1, "File path cannot be empty");
7886
- z.string().refine(
7887
- (val) => {
7888
- const parts = val.split("-");
7889
- const version2 = parts[0] ?? "";
7890
- const preRelease = parts[1];
7891
- const versionParts = version2.split(".");
7892
- if (versionParts.length !== 3) {
7893
- return false;
7881
+
7882
+ // src/config/defaults.ts
7883
+ var DEFAULT_PREFIX = "--dsai-";
7884
+ var DEFAULT_LOG_LEVEL = "info";
7885
+ var DEFAULT_OUTPUT_DIR = "dist";
7886
+ var DEFAULT_SOURCE_DIR = "figma-exports";
7887
+ var DEFAULT_COLLECTIONS_DIR = "collections";
7888
+ var DEFAULT_ICONS_SOURCE_DIR = "icons";
7889
+ var DEFAULT_ICONS_OUTPUT_DIR = "dist/icons";
7890
+ var defaultSourcePatterns = ["theme.json", "tokens.json", "*.tokens.json"];
7891
+ var defaultFormats = ["css", "scss", "js", "ts", "json"];
7892
+ var defaultOutputFileNames = {
7893
+ css: "tokens.css",
7894
+ scss: "_tokens.scss",
7895
+ js: "tokens.js",
7896
+ ts: "tokens.ts",
7897
+ json: "tokens.json",
7898
+ android: "tokens.xml",
7899
+ ios: "tokens.h"
7900
+ };
7901
+ var defaultSelectorPattern = {
7902
+ default: ":root",
7903
+ others: '[data-dsai-theme="{mode}"]'
7904
+ };
7905
+ var defaultThemeDefinitions = {
7906
+ light: {
7907
+ isDefault: true,
7908
+ suffix: null,
7909
+ selector: ":root",
7910
+ outputFiles: {
7911
+ css: "tokens.css",
7912
+ scss: "_tokens.scss",
7913
+ js: "tokens.js",
7914
+ ts: "tokens.ts",
7915
+ json: "tokens.json",
7916
+ android: "tokens.xml",
7917
+ ios: "tokens.h"
7894
7918
  }
7895
- for (const part of versionParts) {
7896
- const num = Number(part);
7897
- if (!Number.isInteger(num) || num < 0) {
7898
- return false;
7919
+ },
7920
+ dark: {
7921
+ isDefault: false,
7922
+ suffix: "-dark",
7923
+ selector: '[data-dsai-theme="dark"]',
7924
+ mediaQuery: "(prefers-color-scheme: dark)",
7925
+ outputFiles: {
7926
+ css: "tokens-dark.css",
7927
+ scss: "_tokens-dark.scss",
7928
+ js: "tokens-dark.js",
7929
+ ts: "tokens-dark.ts",
7930
+ json: "tokens-dark.json",
7931
+ android: "tokens-dark.xml",
7932
+ ios: "tokens-dark.h"
7933
+ }
7934
+ }
7935
+ };
7936
+ var defaultThemesConfig = {
7937
+ enabled: true,
7938
+ autoDetect: true,
7939
+ default: "light",
7940
+ ignoreModes: [],
7941
+ selectorPattern: defaultSelectorPattern};
7942
+ var defaultIconFramework = "react";
7943
+ var defaultIconsConfig = {
7944
+ sourceDir: DEFAULT_ICONS_SOURCE_DIR,
7945
+ outputDir: DEFAULT_ICONS_OUTPUT_DIR,
7946
+ framework: defaultIconFramework,
7947
+ typescript: true,
7948
+ optimize: true,
7949
+ prefix: "Icon"
7950
+ };
7951
+ var defaultAliasesConfig = {
7952
+ importAlias: "@/",
7953
+ ui: "src/components/ui",
7954
+ hooks: "src/hooks",
7955
+ utils: "src/lib/utils",
7956
+ components: "src/components",
7957
+ lib: "src/lib"
7958
+ };
7959
+ var defaultComponentsConfig = {
7960
+ enabled: true,
7961
+ registryUrl: "https://registry.dsai.dev",
7962
+ tsx: true,
7963
+ overwrite: false
7964
+ };
7965
+ var defaultTokensConfig = {
7966
+ source: "theme",
7967
+ sourceDir: DEFAULT_SOURCE_DIR,
7968
+ collectionsDir: DEFAULT_COLLECTIONS_DIR,
7969
+ sourcePatterns: defaultSourcePatterns,
7970
+ outputDir: DEFAULT_OUTPUT_DIR,
7971
+ outputDirs: {},
7972
+ outputFileNames: defaultOutputFileNames,
7973
+ prefix: DEFAULT_PREFIX,
7974
+ formats: defaultFormats,
7975
+ mergeOrder: "after",
7976
+ createBundle: false,
7977
+ outputReferences: true,
7978
+ baseFontSize: 16,
7979
+ separateThemeFiles: false,
7980
+ watch: false};
7981
+ var defaultGlobalConfig = {
7982
+ cwd: process.cwd(),
7983
+ debug: false,
7984
+ logLevel: DEFAULT_LOG_LEVEL
7985
+ };
7986
+ ({
7987
+ configDir: process.cwd()
7988
+ });
7989
+
7990
+ // src/config/resolver.ts
7991
+ function resolveGlobalConfig(config, options) {
7992
+ const base = defaultGlobalConfig;
7993
+ const cwd = options.cwd ?? process.cwd();
7994
+ return {
7995
+ cwd: config?.cwd ? path4__default.resolve(cwd, config.cwd) : cwd,
7996
+ debug: config?.debug ?? base.debug,
7997
+ logLevel: config?.logLevel ?? base.logLevel
7998
+ };
7999
+ }
8000
+ function resolveThemeDefinition(themeName, definition, selectorPattern, _outputFileNames, isDefaultTheme) {
8001
+ const generateOutputFiles = () => {
8002
+ const suffix = isDefaultTheme ? "" : `-${themeName}`;
8003
+ return {
8004
+ css: `tokens${suffix}.css`,
8005
+ scss: `_tokens${suffix}.scss`,
8006
+ js: `tokens${suffix}.js`,
8007
+ ts: `tokens${suffix}.ts`,
8008
+ json: `tokens${suffix}.json`,
8009
+ android: `tokens${suffix}.xml`,
8010
+ ios: `tokens${suffix}.h`
8011
+ };
8012
+ };
8013
+ const generateSelector = () => {
8014
+ if (isDefaultTheme) {
8015
+ return selectorPattern.default;
8016
+ }
8017
+ return selectorPattern.others.replace("{mode}", themeName);
8018
+ };
8019
+ const defaultOutputFiles = generateOutputFiles();
8020
+ return {
8021
+ isDefault: definition?.isDefault ?? isDefaultTheme,
8022
+ suffix: definition?.suffix ?? (isDefaultTheme ? null : `-${themeName}`),
8023
+ selector: definition?.selector ?? generateSelector(),
8024
+ mediaQuery: definition?.mediaQuery,
8025
+ dataAttribute: definition?.dataAttribute,
8026
+ outputFiles: {
8027
+ ...defaultOutputFiles,
8028
+ ...definition?.outputFiles
8029
+ }
8030
+ };
8031
+ }
8032
+ function resolveThemesConfig(config) {
8033
+ const base = defaultThemesConfig;
8034
+ const selectorPattern = {
8035
+ default: config?.selectorPattern?.default ?? base.selectorPattern.default,
8036
+ others: config?.selectorPattern?.others ?? base.selectorPattern.others
8037
+ };
8038
+ const defaultThemeName = config?.default?.toLowerCase() ?? base.default;
8039
+ let definitions;
8040
+ if (config?.definitions && Object.keys(config.definitions).length > 0) {
8041
+ definitions = {};
8042
+ for (const [themeName, definition] of Object.entries(config.definitions)) {
8043
+ const normalizedName = themeName.toLowerCase();
8044
+ const isDefaultTheme = definition.isDefault ?? normalizedName === defaultThemeName;
8045
+ const resolvedDef = resolveThemeDefinition(
8046
+ normalizedName,
8047
+ definition,
8048
+ selectorPattern,
8049
+ defaultOutputFileNames,
8050
+ isDefaultTheme
8051
+ );
8052
+ Object.defineProperty(definitions, normalizedName, {
8053
+ value: resolvedDef,
8054
+ writable: true,
8055
+ enumerable: true,
8056
+ configurable: true
8057
+ });
8058
+ }
8059
+ } else {
8060
+ definitions = { ...defaultThemeDefinitions };
8061
+ }
8062
+ return {
8063
+ enabled: config?.enabled ?? base.enabled,
8064
+ autoDetect: config?.autoDetect ?? base.autoDetect,
8065
+ default: defaultThemeName,
8066
+ ignoreModes: config?.ignoreModes ?? [...base.ignoreModes],
8067
+ selectorPattern,
8068
+ definitions
8069
+ };
8070
+ }
8071
+ function resolveIconsConfig(config, options) {
8072
+ const base = defaultIconsConfig;
8073
+ const configDir = options.configDir ?? options.cwd ?? process.cwd();
8074
+ return {
8075
+ sourceDir: config?.sourceDir ? path4__default.resolve(configDir, config.sourceDir) : base.sourceDir,
8076
+ outputDir: config?.outputDir ? path4__default.resolve(configDir, config.outputDir) : base.outputDir,
8077
+ framework: config?.framework ?? base.framework,
8078
+ typescript: config?.typescript ?? base.typescript,
8079
+ optimize: config?.optimize ?? base.optimize,
8080
+ prefix: config?.prefix ?? base.prefix
8081
+ };
8082
+ }
8083
+ function resolveTokensConfig(config, options) {
8084
+ const base = defaultTokensConfig;
8085
+ const configDir = options.configDir ?? options.cwd ?? process.cwd();
8086
+ const resolveDir = (dir) => path4__default.resolve(configDir, dir);
8087
+ const outputDirsMap = new Map(Object.entries(base.outputDirs));
8088
+ if (config?.outputDirs) {
8089
+ for (const [format, dir] of Object.entries(config.outputDirs)) {
8090
+ if (dir !== void 0) {
8091
+ outputDirsMap.set(format, resolveDir(dir));
7899
8092
  }
7900
8093
  }
7901
- if (preRelease !== void 0 && preRelease.length === 0) {
7902
- return false;
7903
- }
7904
- return true;
7905
- },
7906
- { message: "Invalid semantic version format" }
7907
- );
7908
- var customTransformSchema = z.object({
7909
- name: z.string().min(1, "Transform name is required"),
7910
- description: z.string().optional(),
7911
- type: z.enum(["value", "attribute", "name"]).optional().default("value"),
7912
- transform: z.function().optional(),
7913
- filter: z.function().optional(),
7914
- matcher: z.function().optional()
7915
- });
7916
- var customFormatSchema = z.object({
7917
- name: z.string().min(1, "Format name is required"),
7918
- description: z.string().optional(),
7919
- formatter: z.function().optional(),
7920
- extension: z.string().min(1).optional()
7921
- });
7922
- var outputFormatEnum = z.enum(["css", "scss", "js", "ts", "json", "android", "ios"]);
7923
- var themeDefinitionSchema = z.object({
7924
- isDefault: z.boolean().optional().default(false),
7925
- suffix: z.string().nullable().optional(),
7926
- selector: z.string().min(1, "Theme selector is required"),
7927
- mediaQuery: z.string().optional(),
7928
- dataAttribute: z.string().optional(),
7929
- outputFiles: z.record(outputFormatEnum, z.string()).optional()
7930
- });
7931
- var themeSelectorPatternSchema = z.object({
7932
- default: z.string().optional().default(":root"),
7933
- others: z.string().optional().default('[data-dsai-theme="{mode}"]')
7934
- });
7935
- var themesConfigSchema = z.object({
7936
- enabled: z.boolean().optional().default(true),
7937
- autoDetect: z.boolean().optional().default(true),
7938
- default: z.string().optional().default("light"),
7939
- ignoreModes: z.array(z.string()).optional().default([]),
7940
- selectorPattern: themeSelectorPatternSchema.optional(),
7941
- definitions: z.record(z.string(), themeDefinitionSchema).optional(),
7942
- // Legacy fields (for backward compatibility)
7943
- defaultMode: z.enum(["light", "dark", "system"]).optional(),
7944
- modes: z.record(
7945
- z.string(),
7946
- z.object({
7947
- selector: z.string().min(1),
7948
- mediaQuery: z.string().optional(),
7949
- dataAttribute: z.string().optional(),
7950
- cssVariables: z.boolean().optional(),
7951
- generateSeparateFiles: z.boolean().optional(),
7952
- prefix: z.string().optional()
7953
- })
7954
- ).optional(),
7955
- outputFileName: z.string().optional(),
7956
- colorScheme: z.object({
7957
- light: z.string().optional(),
7958
- dark: z.string().optional()
7959
- }).optional()
7960
- });
7961
- var iconOptimizationSchema = z.object({
7962
- enabled: z.boolean().optional().default(true),
7963
- removeComments: z.boolean().optional().default(true),
7964
- removeDimensions: z.boolean().optional().default(false),
7965
- removeViewBox: z.boolean().optional().default(false),
7966
- removeXMLNS: z.boolean().optional().default(true),
7967
- cleanupIds: z.boolean().optional().default(true),
7968
- minify: z.boolean().optional().default(true)
7969
- });
7970
- var iconSpriteSchema = z.object({
7971
- enabled: z.boolean().optional().default(true),
7972
- fileName: z.string().optional().default("icons"),
7973
- format: z.enum(["symbol", "stack", "css"]).optional().default("symbol"),
7974
- prefix: z.string().optional().default("icon-")
7975
- });
7976
- var iconsConfigSchema = z.object({
7977
- enabled: z.boolean().optional().default(true),
7978
- sourceDir: z.string().optional().default("assets/icons"),
7979
- outputDir: z.string().optional().default("dist/icons"),
7980
- formats: z.array(z.enum(["svg", "react", "vue", "sprite", "font"])).optional().default(["svg"]),
7981
- optimization: iconOptimizationSchema.optional(),
7982
- sprite: iconSpriteSchema.optional(),
7983
- componentPrefix: z.string().optional().default("Icon"),
7984
- componentSuffix: z.string().optional().default(""),
7985
- generateIndex: z.boolean().optional().default(true),
7986
- generateTypes: z.boolean().optional().default(true)
7987
- });
7988
- var tokenBuildConfigSchema = z.object({
7989
- format: outputFormatSchema,
7990
- outputDir: z.string().optional(),
7991
- outputFileName: z.string().optional(),
7992
- fileExtension: z.string().optional(),
7993
- prefix: z.string().optional(),
7994
- useVariables: z.boolean().optional(),
7995
- selector: z.string().optional(),
7996
- transforms: z.array(z.string()).optional(),
7997
- customTransforms: z.array(customTransformSchema).optional(),
7998
- filter: z.function().optional(),
7999
- header: z.string().optional(),
8000
- footer: z.string().optional()
8001
- });
8002
- var postprocessConfigSchema = z.object({
8003
- enabled: z.boolean().optional(),
8004
- cssDir: z.string().optional(),
8005
- files: z.array(z.string()).optional(),
8006
- replacements: z.array(
8007
- z.object({
8008
- description: z.string().optional(),
8009
- from: z.union([z.string(), z.instanceof(RegExp)]),
8010
- to: z.string()
8011
- })
8012
- ).optional()
8013
- });
8014
- var scssConfigSchema = z.object({
8015
- /** Output styles to generate: 'expanded' (readable) or 'compressed' (minified) */
8016
- outputStyles: z.array(z.enum(["expanded", "compressed"])).optional(),
8017
- /** Generate source maps for SCSS compilation */
8018
- generateSourceMaps: z.boolean().optional(),
8019
- /** Suffix for minified files (e.g., '.min') */
8020
- minifiedSuffix: z.string().optional(),
8021
- /** Theme entry point SCSS file */
8022
- themeEntry: z.string().optional(),
8023
- /** Utilities entry point SCSS file */
8024
- utilitiesEntry: z.string().optional(),
8025
- /** Output directory for compiled CSS files */
8026
- cssOutputDir: z.string().optional(),
8027
- /** Additional Sass load paths */
8028
- loadPaths: z.array(z.string()).optional(),
8029
- /** Target CSS framework for variable name mapping */
8030
- framework: z.enum(["bootstrap", "tailwind", "material", "custom"]).optional(),
8031
- /** Custom token to variable name mappings */
8032
- nameMapping: z.record(z.string(), z.string()).optional(),
8033
- /** Output path for Bootstrap-compatible SCSS variables */
8034
- variablesOutput: z.string().optional()
8035
- });
8036
- var tokenCacheConfigSchema = z.object({
8037
- enabled: z.boolean().optional().default(true),
8038
- directory: z.string().optional().default(".cache"),
8039
- hashType: hashTypeSchema.optional().default("content"),
8040
- maxAge: z.number().optional().default(864e5)
8041
- });
8042
- var tokenWatchConfigSchema = z.object({
8043
- enabled: z.boolean().optional().default(false),
8044
- debounce: z.number().optional().default(300),
8045
- clearScreen: z.boolean().optional().default(true),
8046
- ignorePatterns: z.array(z.string()).optional().default([])
8047
- });
8048
- var tokensHooksSchema = z.object({
8049
- onBuildStart: z.function().optional(),
8050
- onFormatComplete: z.function().optional(),
8051
- onAllFormatsComplete: z.function().optional(),
8052
- onBuildComplete: z.function().optional(),
8053
- onError: z.function().optional()
8054
- });
8055
- var buildPipelineStepSchema = z.enum([
8056
- "validate",
8057
- "snapshot",
8058
- "preprocess",
8059
- "transform",
8060
- "style-dictionary",
8061
- "sync",
8062
- "sass-theme",
8063
- "sass-theme-minified",
8064
- "postprocess",
8065
- "sass-utilities",
8066
- "sass-utilities-minified",
8067
- "bundle"
8068
- ]);
8069
- var tokensBuildPipelineSchema = z.object({
8070
- /**
8071
- * Steps to include in the build.
8072
- * Order matters - steps run in sequence.
8073
- * Default includes all steps for full @dsai-io/tokens build.
8074
- * Simpler packages can use subset like ['validate', 'transform', 'style-dictionary']
8075
- */
8076
- steps: z.array(buildPipelineStepSchema).optional(),
8077
- /**
8078
- * Paths configuration for build steps
8079
- */
8080
- paths: z.object({
8081
- /** Source file for sync step (Style Dictionary JS output) */
8082
- syncSource: z.string().optional(),
8083
- /** Target file for sync step */
8084
- syncTarget: z.string().optional(),
8085
- /** SCSS theme input file */
8086
- sassThemeInput: z.string().optional(),
8087
- /** CSS theme output file */
8088
- sassThemeOutput: z.string().optional(),
8089
- /** CSS theme minified output file */
8090
- sassThemeMinifiedOutput: z.string().optional(),
8091
- /** SCSS utilities input file */
8092
- sassUtilitiesInput: z.string().optional(),
8093
- /** CSS utilities output file */
8094
- sassUtilitiesOutput: z.string().optional(),
8095
- /** CSS utilities minified output file */
8096
- sassUtilitiesMinifiedOutput: z.string().optional()
8097
- }).optional(),
8098
- /** Style Dictionary config file name */
8099
- styleDictionaryConfig: z.string().optional()
8100
- });
8101
- var tokensConfigSchema = z.object({
8102
- enabled: z.boolean().optional().default(true),
8103
- sourcePatterns: z.array(z.string()).optional().default(["src/tokens/**/*.json", "src/tokens/**/*.yaml"]),
8104
- outputDirs: z.object({
8105
- css: z.string().optional().default("dist/css"),
8106
- scss: z.string().optional().default("dist/scss"),
8107
- less: z.string().optional().default("dist/less"),
8108
- js: z.string().optional().default("dist/js"),
8109
- ts: z.string().optional().default("dist/ts"),
8110
- json: z.string().optional().default("dist/json")
8111
- }).optional(),
8112
- additionalScssDirectories: z.array(z.string()).optional().default([]),
8113
- outputFileNames: z.object({
8114
- variables: z.string().optional().default("variables"),
8115
- utilities: z.string().optional().default("utilities"),
8116
- mixins: z.string().optional().default("mixins"),
8117
- tokens: z.string().optional().default("tokens")
8118
- }).optional(),
8119
- prefix: z.string().optional().default("dsai"),
8120
- mergeOrder: z.array(z.string()).optional().default(["base", "semantic", "component"]),
8121
- createBundle: z.boolean().optional().default(true),
8122
- bundleFileName: z.string().optional().default("bundle"),
8123
- formats: z.array(outputFormatSchema).optional().default(["css", "scss", "json"]),
8124
- platforms: z.record(z.string(), tokenBuildConfigSchema).optional(),
8125
- transforms: z.array(z.string()).optional().default([]),
8126
- customTransforms: z.array(customTransformSchema).optional().default([]),
8127
- customFormats: z.array(customFormatSchema).optional().default([]),
8128
- hooks: tokensHooksSchema.optional(),
8129
- cache: tokenCacheConfigSchema.optional(),
8130
- watch: tokenWatchConfigSchema.optional(),
8131
- verbose: z.boolean().optional().default(false),
8132
- /** SCSS/CSS output configuration */
8133
- scss: scssConfigSchema.optional(),
8134
- /** Build pipeline configuration */
8135
- pipeline: tokensBuildPipelineSchema.optional(),
8136
- /** Postprocess configuration */
8137
- postprocess: postprocessConfigSchema.optional()
8138
- });
8139
- var buildConfigSchema = z.object({
8140
- outDir: z.string().optional().default("dist"),
8141
- clean: z.boolean().optional().default(true),
8142
- sourcemap: z.boolean().optional().default(false),
8143
- minify: z.boolean().optional().default(true),
8144
- parallel: z.boolean().optional().default(true),
8145
- maxConcurrency: z.number().optional().default(4)
8146
- });
8147
- var globalConfigSchema = z.object({
8148
- logLevel: logLevelSchema.optional().default("info"),
8149
- colors: z.boolean().optional().default(true),
8150
- ci: z.boolean().optional().default(false),
8151
- dryRun: z.boolean().optional().default(false),
8152
- cwd: z.string().optional(),
8153
- configPath: z.string().optional(),
8154
- framework: frameworkSchema.optional(),
8155
- build: buildConfigSchema.optional()
8156
- });
8157
- z.object({
8158
- $schema: z.string().optional(),
8159
- extends: z.union([z.string(), z.array(z.string())]).optional(),
8160
- global: globalConfigSchema.optional(),
8161
- tokens: tokensConfigSchema.optional(),
8162
- themes: themesConfigSchema.optional(),
8163
- icons: iconsConfigSchema.optional()
8164
- });
8165
-
8166
- // src/config/defaults.ts
8167
- var DEFAULT_PREFIX = "--dsai-";
8168
- var DEFAULT_LOG_LEVEL = "info";
8169
- var DEFAULT_OUTPUT_DIR = "dist";
8170
- var DEFAULT_SOURCE_DIR = "figma-exports";
8171
- var DEFAULT_COLLECTIONS_DIR = "collections";
8172
- var DEFAULT_ICONS_SOURCE_DIR = "icons";
8173
- var DEFAULT_ICONS_OUTPUT_DIR = "dist/icons";
8174
- var defaultSourcePatterns = ["theme.json", "tokens.json", "*.tokens.json"];
8175
- var defaultFormats = ["css", "scss", "js", "ts", "json"];
8176
- var defaultOutputFileNames = {
8177
- css: "tokens.css",
8178
- scss: "_tokens.scss",
8179
- js: "tokens.js",
8180
- ts: "tokens.ts",
8181
- json: "tokens.json",
8182
- android: "tokens.xml",
8183
- ios: "tokens.h"
8184
- };
8185
- var defaultSelectorPattern = {
8186
- default: ":root",
8187
- others: '[data-dsai-theme="{mode}"]'
8188
- };
8189
- var defaultThemeDefinitions = {
8190
- light: {
8191
- isDefault: true,
8192
- suffix: null,
8193
- selector: ":root",
8194
- outputFiles: {
8195
- css: "tokens.css",
8196
- scss: "_tokens.scss",
8197
- js: "tokens.js",
8198
- ts: "tokens.ts",
8199
- json: "tokens.json",
8200
- android: "tokens.xml",
8201
- ios: "tokens.h"
8202
- }
8203
- },
8204
- dark: {
8205
- isDefault: false,
8206
- suffix: "-dark",
8207
- selector: '[data-dsai-theme="dark"]',
8208
- mediaQuery: "(prefers-color-scheme: dark)",
8209
- outputFiles: {
8210
- css: "tokens-dark.css",
8211
- scss: "_tokens-dark.scss",
8212
- js: "tokens-dark.js",
8213
- ts: "tokens-dark.ts",
8214
- json: "tokens-dark.json",
8215
- android: "tokens-dark.xml",
8216
- ios: "tokens-dark.h"
8217
- }
8218
- }
8219
- };
8220
- var defaultThemesConfig = {
8221
- enabled: true,
8222
- autoDetect: true,
8223
- default: "light",
8224
- ignoreModes: [],
8225
- selectorPattern: defaultSelectorPattern};
8226
- var defaultIconFramework = "react";
8227
- var defaultIconsConfig = {
8228
- sourceDir: DEFAULT_ICONS_SOURCE_DIR,
8229
- outputDir: DEFAULT_ICONS_OUTPUT_DIR,
8230
- framework: defaultIconFramework,
8231
- typescript: true,
8232
- optimize: true,
8233
- prefix: "Icon"
8234
- };
8235
- var defaultTokensConfig = {
8236
- source: "theme",
8237
- sourceDir: DEFAULT_SOURCE_DIR,
8238
- collectionsDir: DEFAULT_COLLECTIONS_DIR,
8239
- sourcePatterns: defaultSourcePatterns,
8240
- outputDir: DEFAULT_OUTPUT_DIR,
8241
- outputDirs: {},
8242
- outputFileNames: defaultOutputFileNames,
8243
- prefix: DEFAULT_PREFIX,
8244
- formats: defaultFormats,
8245
- mergeOrder: "after",
8246
- createBundle: false,
8247
- outputReferences: true,
8248
- baseFontSize: 16,
8249
- separateThemeFiles: false,
8250
- watch: false};
8251
- var defaultGlobalConfig = {
8252
- cwd: process.cwd(),
8253
- debug: false,
8254
- logLevel: DEFAULT_LOG_LEVEL
8255
- };
8256
- ({
8257
- configDir: process.cwd()
8258
- });
8259
- function resolveGlobalConfig(config, options) {
8260
- const base = defaultGlobalConfig;
8261
- const cwd = options.cwd ?? process.cwd();
8262
- return {
8263
- cwd: config?.cwd ? path4__default.resolve(cwd, config.cwd) : cwd,
8264
- debug: config?.debug ?? base.debug,
8265
- logLevel: config?.logLevel ?? base.logLevel
8266
- };
8267
- }
8268
- function resolveThemeDefinition(themeName, definition, selectorPattern, _outputFileNames, isDefaultTheme) {
8269
- const generateOutputFiles = () => {
8270
- const suffix = isDefaultTheme ? "" : `-${themeName}`;
8271
- return {
8272
- css: `tokens${suffix}.css`,
8273
- scss: `_tokens${suffix}.scss`,
8274
- js: `tokens${suffix}.js`,
8275
- ts: `tokens${suffix}.ts`,
8276
- json: `tokens${suffix}.json`,
8277
- android: `tokens${suffix}.xml`,
8278
- ios: `tokens${suffix}.h`
8279
- };
8280
- };
8281
- const generateSelector = () => {
8282
- if (isDefaultTheme) {
8283
- return selectorPattern.default;
8284
- }
8285
- return selectorPattern.others.replace("{mode}", themeName);
8286
- };
8287
- const defaultOutputFiles = generateOutputFiles();
8288
- return {
8289
- isDefault: definition?.isDefault ?? isDefaultTheme,
8290
- suffix: definition?.suffix ?? (isDefaultTheme ? null : `-${themeName}`),
8291
- selector: definition?.selector ?? generateSelector(),
8292
- mediaQuery: definition?.mediaQuery,
8293
- dataAttribute: definition?.dataAttribute,
8294
- outputFiles: {
8295
- ...defaultOutputFiles,
8296
- ...definition?.outputFiles
8297
- }
8298
- };
8299
- }
8300
- function resolveThemesConfig(config) {
8301
- const base = defaultThemesConfig;
8302
- const selectorPattern = {
8303
- default: config?.selectorPattern?.default ?? base.selectorPattern.default,
8304
- others: config?.selectorPattern?.others ?? base.selectorPattern.others
8305
- };
8306
- const defaultThemeName = config?.default?.toLowerCase() ?? base.default;
8307
- let definitions;
8308
- if (config?.definitions && Object.keys(config.definitions).length > 0) {
8309
- definitions = {};
8310
- for (const [themeName, definition] of Object.entries(config.definitions)) {
8311
- const normalizedName = themeName.toLowerCase();
8312
- const isDefaultTheme = definition.isDefault ?? normalizedName === defaultThemeName;
8313
- const resolvedDef = resolveThemeDefinition(
8314
- normalizedName,
8315
- definition,
8316
- selectorPattern,
8317
- defaultOutputFileNames,
8318
- isDefaultTheme
8319
- );
8320
- Object.defineProperty(definitions, normalizedName, {
8321
- value: resolvedDef,
8322
- writable: true,
8323
- enumerable: true,
8324
- configurable: true
8325
- });
8326
- }
8327
- } else {
8328
- definitions = { ...defaultThemeDefinitions };
8329
- }
8330
- return {
8331
- enabled: config?.enabled ?? base.enabled,
8332
- autoDetect: config?.autoDetect ?? base.autoDetect,
8333
- default: defaultThemeName,
8334
- ignoreModes: config?.ignoreModes ?? [...base.ignoreModes],
8335
- selectorPattern,
8336
- definitions
8337
- };
8338
- }
8339
- function resolveIconsConfig(config, options) {
8340
- const base = defaultIconsConfig;
8341
- const configDir = options.configDir ?? options.cwd ?? process.cwd();
8342
- return {
8343
- sourceDir: config?.sourceDir ? path4__default.resolve(configDir, config.sourceDir) : base.sourceDir,
8344
- outputDir: config?.outputDir ? path4__default.resolve(configDir, config.outputDir) : base.outputDir,
8345
- framework: config?.framework ?? base.framework,
8346
- typescript: config?.typescript ?? base.typescript,
8347
- optimize: config?.optimize ?? base.optimize,
8348
- prefix: config?.prefix ?? base.prefix
8349
- };
8350
- }
8351
- function resolveTokensConfig(config, options) {
8352
- const base = defaultTokensConfig;
8353
- const configDir = options.configDir ?? options.cwd ?? process.cwd();
8354
- const resolveDir = (dir) => path4__default.resolve(configDir, dir);
8355
- const outputDirsMap = new Map(Object.entries(base.outputDirs));
8356
- if (config?.outputDirs) {
8357
- for (const [format, dir] of Object.entries(config.outputDirs)) {
8358
- if (dir !== void 0) {
8359
- outputDirsMap.set(format, resolveDir(dir));
8360
- }
8361
- }
8362
- }
8363
- const outputDirs = Object.fromEntries(outputDirsMap);
8364
- const collectionMappingMap = /* @__PURE__ */ new Map();
8365
- if (config?.collectionMapping) {
8366
- for (const [name, filePath] of Object.entries(config.collectionMapping)) {
8367
- collectionMappingMap.set(name, resolveDir(filePath));
8094
+ }
8095
+ const outputDirs = Object.fromEntries(outputDirsMap);
8096
+ const collectionMappingMap = /* @__PURE__ */ new Map();
8097
+ if (config?.collectionMapping) {
8098
+ for (const [name, filePath] of Object.entries(config.collectionMapping)) {
8099
+ collectionMappingMap.set(name, resolveDir(filePath));
8368
8100
  }
8369
8101
  }
8370
8102
  const collectionMapping = Object.fromEntries(collectionMappingMap);
@@ -8406,10 +8138,32 @@ function resolveTokensConfig(config, options) {
8406
8138
  postprocess: config?.postprocess
8407
8139
  };
8408
8140
  }
8141
+ function resolveAliasesConfig(config) {
8142
+ const base = defaultAliasesConfig;
8143
+ return {
8144
+ importAlias: config?.importAlias ?? base.importAlias,
8145
+ ui: config?.ui ?? base.ui,
8146
+ hooks: config?.hooks ?? base.hooks,
8147
+ utils: config?.utils ?? base.utils,
8148
+ components: config?.components ?? base.components,
8149
+ lib: config?.lib ?? base.lib
8150
+ };
8151
+ }
8152
+ function resolveComponentsConfig(config) {
8153
+ const base = defaultComponentsConfig;
8154
+ return {
8155
+ enabled: config?.enabled ?? base.enabled,
8156
+ registryUrl: config?.registryUrl ?? base.registryUrl,
8157
+ tsx: config?.tsx ?? base.tsx,
8158
+ overwrite: config?.overwrite ?? base.overwrite
8159
+ };
8160
+ }
8409
8161
  function applyOverrides(config, overrides) {
8410
8162
  return {
8411
8163
  tokens: overrides.tokens ? { ...config.tokens, ...overrides.tokens } : config.tokens,
8412
8164
  icons: overrides.icons ? { ...config.icons, ...overrides.icons } : config.icons,
8165
+ aliases: overrides.aliases ? { ...config.aliases, ...overrides.aliases } : config.aliases,
8166
+ components: overrides.components ? { ...config.components, ...overrides.components } : config.components,
8413
8167
  global: overrides.global ? { ...config.global, ...overrides.global } : config.global
8414
8168
  };
8415
8169
  }
@@ -8420,6 +8174,8 @@ function resolveConfig(config = {}, options = {}) {
8420
8174
  global: resolveGlobalConfig(mergedConfig.global, options),
8421
8175
  tokens: resolveTokensConfig(mergedConfig.tokens, options),
8422
8176
  icons: resolveIconsConfig(mergedConfig.icons, options),
8177
+ aliases: resolveAliasesConfig(mergedConfig.aliases),
8178
+ components: resolveComponentsConfig(mergedConfig.components),
8423
8179
  configDir
8424
8180
  };
8425
8181
  }
@@ -8484,10 +8240,215 @@ async function loadConfig(options = {}) {
8484
8240
  warnings
8485
8241
  };
8486
8242
  }
8243
+ function loadItem(name, registryDir) {
8244
+ const subdirs = ["components", "hooks", "utils", "lib", "styles", "types"];
8245
+ for (const sub of subdirs) {
8246
+ const filePath = join(registryDir, sub, `${name}.json`);
8247
+ if (existsSync(filePath)) {
8248
+ return JSON.parse(readFileSync(filePath, "utf-8"));
8249
+ }
8250
+ }
8251
+ return null;
8252
+ }
8253
+ function resolveTree(names, registryDir) {
8254
+ const visited = /* @__PURE__ */ new Map();
8255
+ const queue = [...names];
8256
+ while (queue.length > 0) {
8257
+ const name = queue.shift();
8258
+ if (visited.has(name)) continue;
8259
+ const item = loadItem(name, registryDir);
8260
+ if (!item) {
8261
+ throw new Error(`Registry item "${name}" not found. Run \`dsai registry build\` or check the name.`);
8262
+ }
8263
+ visited.set(name, item);
8264
+ for (const dep of item.registryDependencies) {
8265
+ if (!visited.has(dep)) queue.push(dep);
8266
+ }
8267
+ }
8268
+ const inDeg = /* @__PURE__ */ new Map();
8269
+ for (const [name, item] of visited) {
8270
+ inDeg.set(name, item.registryDependencies.filter((d3) => visited.has(d3)).length);
8271
+ }
8272
+ const sorted = [];
8273
+ const ready = [];
8274
+ for (const [name, deg] of inDeg) {
8275
+ if (deg === 0) ready.push(name);
8276
+ }
8277
+ while (ready.length > 0) {
8278
+ const name = ready.shift();
8279
+ sorted.push(visited.get(name));
8280
+ for (const [otherName, otherItem] of visited) {
8281
+ if (otherItem.registryDependencies.includes(name)) {
8282
+ const newDeg = (inDeg.get(otherName) ?? 1) - 1;
8283
+ inDeg.set(otherName, newDeg);
8284
+ if (newDeg === 0) ready.push(otherName);
8285
+ }
8286
+ }
8287
+ }
8288
+ if (sorted.length !== visited.size) {
8289
+ const missing = [...visited.keys()].filter((n) => !sorted.some((s) => s.name === n));
8290
+ throw new Error(`Circular dependency detected involving: ${missing.join(", ")}`);
8291
+ }
8292
+ const allDeps = /* @__PURE__ */ new Set();
8293
+ const allDevDeps = /* @__PURE__ */ new Set();
8294
+ const lightVars = {};
8295
+ const darkVars = {};
8296
+ for (const item of sorted) {
8297
+ for (const dep of item.dependencies) allDeps.add(dep);
8298
+ for (const dep of item.devDependencies) allDevDeps.add(dep);
8299
+ if (item.cssVars?.light) Object.assign(lightVars, item.cssVars.light);
8300
+ if (item.cssVars?.dark) Object.assign(darkVars, item.cssVars.dark);
8301
+ }
8302
+ return {
8303
+ items: sorted,
8304
+ dependencies: [...allDeps],
8305
+ devDependencies: [...allDevDeps],
8306
+ cssVars: { light: lightVars, dark: darkVars }
8307
+ };
8308
+ }
8487
8309
 
8488
- // src/cli/commands/tokens.ts
8489
- init_tokens();
8490
- init_snapshot();
8310
+ // src/registry/transformer.ts
8311
+ function transformImports(content, options) {
8312
+ const { aliases } = options;
8313
+ let result = content;
8314
+ result = result.replace(
8315
+ /(from\s+['"])(?:\.\.\/)+types(?:\/([^'"]+))?(['"])/g,
8316
+ (_match, prefix, subpath, suffix) => {
8317
+ if (subpath) {
8318
+ return `${prefix}${aliases.importAlias}${aliases.components}/types/${subpath}${suffix}`;
8319
+ }
8320
+ return `${prefix}${aliases.importAlias}${aliases.components}/types${suffix}`;
8321
+ }
8322
+ );
8323
+ result = result.replace(
8324
+ /(from\s+['"])\.\.\/(([A-Z]\w+)(\/[^'"]+)?)(['"])/g,
8325
+ (_match, prefix, _fullPath, dirName, subPath, suffix) => {
8326
+ const kebab = dirName.replace(/([a-z0-9])([A-Z])/g, "$1-$2").toLowerCase();
8327
+ if (subPath) {
8328
+ return `${prefix}${aliases.importAlias}${aliases.ui}/${kebab}${subPath}${suffix}`;
8329
+ }
8330
+ return `${prefix}${aliases.importAlias}${aliases.ui}/${kebab}${suffix}`;
8331
+ }
8332
+ );
8333
+ result = result.replace(
8334
+ /(from\s+['"])(?:\.\.\/)+hooks\/(\w+)(['"])/g,
8335
+ `$1${aliases.importAlias}${aliases.hooks}/$2$3`
8336
+ );
8337
+ result = result.replace(
8338
+ /(from\s+['"])(?:\.\.\/)+utils\/(\w+(?:\/\w+)?)(['"])/g,
8339
+ `$1${aliases.importAlias}${aliases.utils}/$2$3`
8340
+ );
8341
+ result = result.replace(
8342
+ /(from\s+['"])(?:\.\.\/)+utils(['"])/g,
8343
+ `$1${aliases.importAlias}${aliases.utils}$2`
8344
+ );
8345
+ return result;
8346
+ }
8347
+ function normalizeExtensions(content, tsx) {
8348
+ if (!tsx) {
8349
+ return content.replace(/(from\s+['"][^'"]+)\.tsx(['"])/g, "$1.jsx$2").replace(/(from\s+['"][^'"]+)\.ts(['"])/g, "$1.js$2");
8350
+ }
8351
+ return content;
8352
+ }
8353
+
8354
+ // src/registry/writer.ts
8355
+ function getTargetDir(type, aliases) {
8356
+ switch (type) {
8357
+ case "registry:ui":
8358
+ return aliases.ui;
8359
+ case "registry:hook":
8360
+ return aliases.hooks;
8361
+ case "registry:util":
8362
+ return aliases.utils;
8363
+ case "registry:lib":
8364
+ return aliases.lib;
8365
+ case "registry:component":
8366
+ return aliases.components;
8367
+ case "registry:type":
8368
+ return aliases.components;
8369
+ case "registry:style":
8370
+ return aliases.ui;
8371
+ default:
8372
+ return aliases.lib;
8373
+ }
8374
+ }
8375
+ function detectPackageManager(projectDir) {
8376
+ if (existsSync(join(projectDir, "pnpm-lock.yaml"))) return "pnpm";
8377
+ if (existsSync(join(projectDir, "bun.lockb")) || existsSync(join(projectDir, "bun.lock"))) return "bun";
8378
+ if (existsSync(join(projectDir, "yarn.lock"))) return "yarn";
8379
+ return "npm";
8380
+ }
8381
+ function getInstallArgs(pm, packages, dev) {
8382
+ switch (pm) {
8383
+ case "pnpm":
8384
+ return ["pnpm", ["add", ...[], ...packages]];
8385
+ case "yarn":
8386
+ return ["yarn", ["add", ...[], ...packages]];
8387
+ case "bun":
8388
+ return ["bun", ["add", ...[], ...packages]];
8389
+ default:
8390
+ return ["npm", ["install", ...[], ...packages]];
8391
+ }
8392
+ }
8393
+ function writeRegistryItems(tree, options) {
8394
+ const { projectDir, aliases, components, overwrite, dryRun, log } = options;
8395
+ const result = { written: [], skipped: [], installedDeps: [] };
8396
+ const shouldOverwrite = overwrite ?? components.overwrite;
8397
+ for (const item of tree.items) {
8398
+ const targetBaseDir = getTargetDir(item.type, aliases);
8399
+ for (const file of item.files) {
8400
+ const fileName = basename(file.path);
8401
+ let targetPath;
8402
+ if (file.target) {
8403
+ targetPath = join(projectDir, file.target);
8404
+ } else if (item.type === "registry:ui" || item.type === "registry:component") {
8405
+ targetPath = join(projectDir, targetBaseDir, item.name, fileName);
8406
+ } else if (item.type === "registry:type") {
8407
+ targetPath = join(projectDir, targetBaseDir, file.path);
8408
+ } else {
8409
+ targetPath = join(projectDir, targetBaseDir, fileName);
8410
+ }
8411
+ if (existsSync(targetPath) && !shouldOverwrite) {
8412
+ if (log) log(` Skipped (exists): ${targetPath}`);
8413
+ result.skipped.push(targetPath);
8414
+ continue;
8415
+ }
8416
+ let content = file.content;
8417
+ content = transformImports(content, { aliases, tsx: components.tsx });
8418
+ content = normalizeExtensions(content, components.tsx);
8419
+ if (dryRun) {
8420
+ if (log) log(` Would write: ${targetPath}`);
8421
+ result.written.push(targetPath);
8422
+ continue;
8423
+ }
8424
+ const dir = dirname(targetPath);
8425
+ if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
8426
+ writeFileSync(targetPath, content, "utf-8");
8427
+ if (log) log(` Written: ${targetPath}`);
8428
+ result.written.push(targetPath);
8429
+ }
8430
+ }
8431
+ const depsToInstall = tree.dependencies.filter((dep) => {
8432
+ const pkgJsonPath = join(projectDir, "package.json");
8433
+ if (existsSync(pkgJsonPath)) {
8434
+ const pkgJson = JSON.parse(readFileSync(pkgJsonPath, "utf-8"));
8435
+ const allDeps = { ...pkgJson.dependencies, ...pkgJson.devDependencies };
8436
+ return !Reflect.get(allDeps, dep);
8437
+ }
8438
+ return true;
8439
+ });
8440
+ if (depsToInstall.length > 0 && !dryRun) {
8441
+ const pm = detectPackageManager(projectDir);
8442
+ const [cmd, args] = getInstallArgs(pm, depsToInstall);
8443
+ if (log) log(` Installing: ${cmd} ${args.join(" ")}`);
8444
+ execFileSync(cmd, args, { cwd: projectDir, stdio: "inherit" });
8445
+ result.installedDeps = depsToInstall;
8446
+ } else if (depsToInstall.length > 0 && dryRun) {
8447
+ if (log) log(` Would install: ${depsToInstall.join(", ")}`);
8448
+ result.installedDeps = depsToInstall;
8449
+ }
8450
+ return result;
8451
+ }
8491
8452
 
8492
8453
  // src/cli/types.ts
8493
8454
  var ExitCode = {
@@ -8705,48 +8666,531 @@ function createLogger(options = {}) {
8705
8666
  console.log(`${prefixStr}${colors_default.muted("DEBUG")} ${colors_default.dim(message)}`);
8706
8667
  }
8707
8668
  }
8708
- };
8709
- }
8710
- function formatDuration(ms) {
8711
- if (ms < 1e3) {
8712
- return `${ms}ms`;
8713
- }
8714
- if (ms < 6e4) {
8715
- return `${(ms / 1e3).toFixed(2)}s`;
8716
- }
8717
- const minutes = Math.floor(ms / 6e4);
8718
- const seconds = (ms % 6e4 / 1e3).toFixed(0);
8719
- return `${minutes}m ${seconds}s`;
8720
- }
8721
- function formatBytes(bytes) {
8722
- if (bytes === 0) {
8723
- return "0 B";
8724
- }
8725
- const k3 = 1024;
8726
- const i = Math.floor(Math.log(bytes) / Math.log(k3));
8727
- const sizeIndex = Math.min(i, 3);
8728
- let sizeLabel;
8729
- switch (sizeIndex) {
8730
- case 0:
8731
- sizeLabel = "B";
8732
- break;
8733
- case 1:
8734
- sizeLabel = "KB";
8735
- break;
8736
- case 2:
8737
- sizeLabel = "MB";
8738
- break;
8739
- default:
8740
- sizeLabel = "GB";
8741
- }
8742
- return `${Number.parseFloat((bytes / k3 ** sizeIndex).toFixed(2))} ${sizeLabel}`;
8743
- }
8744
- function formatCount(count, singular, plural) {
8745
- const label = count === 1 ? singular : plural ?? `${singular}s`;
8746
- return `${count} ${label}`;
8669
+ };
8670
+ }
8671
+ function formatDuration(ms) {
8672
+ if (ms < 1e3) {
8673
+ return `${ms}ms`;
8674
+ }
8675
+ if (ms < 6e4) {
8676
+ return `${(ms / 1e3).toFixed(2)}s`;
8677
+ }
8678
+ const minutes = Math.floor(ms / 6e4);
8679
+ const seconds = (ms % 6e4 / 1e3).toFixed(0);
8680
+ return `${minutes}m ${seconds}s`;
8681
+ }
8682
+ function formatBytes(bytes) {
8683
+ if (bytes === 0) {
8684
+ return "0 B";
8685
+ }
8686
+ const k3 = 1024;
8687
+ const i = Math.floor(Math.log(bytes) / Math.log(k3));
8688
+ const sizeIndex = Math.min(i, 3);
8689
+ let sizeLabel;
8690
+ switch (sizeIndex) {
8691
+ case 0:
8692
+ sizeLabel = "B";
8693
+ break;
8694
+ case 1:
8695
+ sizeLabel = "KB";
8696
+ break;
8697
+ case 2:
8698
+ sizeLabel = "MB";
8699
+ break;
8700
+ default:
8701
+ sizeLabel = "GB";
8702
+ }
8703
+ return `${Number.parseFloat((bytes / k3 ** sizeIndex).toFixed(2))} ${sizeLabel}`;
8704
+ }
8705
+ function formatCount(count, singular, plural) {
8706
+ const label = count === 1 ? singular : plural ?? `${singular}s`;
8707
+ return `${count} ${label}`;
8708
+ }
8709
+
8710
+ // src/cli/commands/add.ts
8711
+ var VALID_TYPES = ["ui", "hook", "util", "lib", "type", "style"];
8712
+ function createAddCommand() {
8713
+ const cmd = new Command("add").description("Add DSAi items (components, hooks, utils) to your project").argument("[items...]", "Item names to add (e.g., button use-focus-trap cn)").option("--all", "Add all items of the specified type (default: ui)", false).option("--type <type>", "Filter by type: ui, hook, util, lib, type").option("--overwrite", "Overwrite existing files", false).option("--dry-run", "Preview changes without writing files", false).option("--registry <path>", "Path to local registry directory").option("--list", "List all available items", false).action(async (items, opts, cmdObj) => {
8714
+ const parentOpts = cmdObj.parent?.opts() ?? {};
8715
+ const allOpts = {
8716
+ ...parentOpts,
8717
+ ...opts,
8718
+ dryRun: opts.dryRun || parentOpts.dryRun,
8719
+ overwrite: opts.overwrite || parentOpts.overwrite
8720
+ };
8721
+ const logger = createLogger(allOpts);
8722
+ try {
8723
+ const { config } = await loadConfig({
8724
+ cwd: allOpts.cwd ?? process.cwd(),
8725
+ configPath: allOpts.config
8726
+ });
8727
+ const registryDir = allOpts.registry ? resolve(allOpts.registry) : join(config.configDir, "node_modules", "@dsai-io", "tools", "registry");
8728
+ if (!existsSync(registryDir)) {
8729
+ logger.error(
8730
+ `Registry not found at: ${registryDir}
8731
+ Run \`dsai registry build\` or use --registry <path>.`
8732
+ );
8733
+ process.exit(ExitCode.GeneralError);
8734
+ }
8735
+ const typeFilter = allOpts.type;
8736
+ if (typeFilter && !VALID_TYPES.includes(typeFilter)) {
8737
+ logger.error(
8738
+ `Invalid type "${typeFilter}". Valid types: ${VALID_TYPES.join(", ")}`
8739
+ );
8740
+ process.exit(ExitCode.GeneralError);
8741
+ }
8742
+ const filterByType = (entries) => {
8743
+ if (!typeFilter) return entries;
8744
+ return entries.filter((i) => i.type === `registry:${typeFilter}`);
8745
+ };
8746
+ if (allOpts.list) {
8747
+ const indexPath = join(registryDir, "index.json");
8748
+ if (!existsSync(indexPath)) {
8749
+ logger.error("Registry index not found.");
8750
+ process.exit(ExitCode.GeneralError);
8751
+ }
8752
+ const index = JSON.parse(readFileSync(indexPath, "utf-8"));
8753
+ const filtered = filterByType(index.items);
8754
+ console.log(`
8755
+ ${colors.bold("Available items:")}
8756
+ `);
8757
+ const grouped = {};
8758
+ for (const item of filtered) {
8759
+ const type = item.type.replace("registry:", "");
8760
+ if (!grouped[type]) grouped[type] = [];
8761
+ grouped[type].push(item);
8762
+ }
8763
+ const displayOrder = ["ui", "hook", "util", "lib", "type", "style"];
8764
+ for (const type of displayOrder) {
8765
+ const typeItems = grouped[type];
8766
+ if (!typeItems || typeItems.length === 0) continue;
8767
+ console.log(` ${colors.cyan(type)} (${typeItems.length}):`);
8768
+ for (const item of typeItems.sort((a, b3) => a.name.localeCompare(b3.name))) {
8769
+ console.log(
8770
+ ` ${colors.bold(item.name.padEnd(28))} ${colors.muted(item.description)}`
8771
+ );
8772
+ }
8773
+ console.log();
8774
+ }
8775
+ console.log(` ${colors.muted(`${filtered.length} items available`)}
8776
+ `);
8777
+ console.log(`${colors.muted("Usage:")}`);
8778
+ console.log(` ${colors.command("dsai add button modal")} ${colors.muted("Add specific items")}`);
8779
+ console.log(` ${colors.command("dsai add use-focus-trap cn")} ${colors.muted("Add hooks and utils")}`);
8780
+ console.log(` ${colors.command("dsai add --all")} ${colors.muted("Add all UI components")}`);
8781
+ console.log(` ${colors.command("dsai add --all --type hook")} ${colors.muted("Add all hooks")}`);
8782
+ console.log(` ${colors.command("dsai add --list --type util")} ${colors.muted("List only utilities")}
8783
+ `);
8784
+ return;
8785
+ }
8786
+ if (!allOpts.all && items.length === 0) {
8787
+ logger.error(
8788
+ `No items specified.
8789
+ Usage: ${colors.command("dsai add <item...>")}
8790
+ ${colors.command("dsai add --all [--type hook|util]")}
8791
+ ${colors.command("dsai add --list")}`
8792
+ );
8793
+ process.exit(ExitCode.GeneralError);
8794
+ }
8795
+ let itemNames = items;
8796
+ if (allOpts.all) {
8797
+ const indexPath = join(registryDir, "index.json");
8798
+ const index = JSON.parse(readFileSync(indexPath, "utf-8"));
8799
+ const effectiveType = typeFilter ?? "ui";
8800
+ itemNames = index.items.filter((i) => i.type === `registry:${effectiveType}`).map((i) => i.name);
8801
+ if (itemNames.length === 0) {
8802
+ logger.error(`No items found for type "${effectiveType}".`);
8803
+ process.exit(ExitCode.GeneralError);
8804
+ }
8805
+ }
8806
+ const spinner = createSpinner();
8807
+ spinner.start("Resolving dependencies...");
8808
+ let tree;
8809
+ try {
8810
+ tree = resolveTree(itemNames, registryDir);
8811
+ } catch (err) {
8812
+ spinner.fail("Failed to resolve dependencies");
8813
+ logger.error(err.message);
8814
+ process.exit(ExitCode.GeneralError);
8815
+ }
8816
+ spinner.succeed(
8817
+ `Resolved ${tree.items.length} items (${itemNames.length} requested + ${tree.items.length - itemNames.length} dependencies)`
8818
+ );
8819
+ console.log(`
8820
+ ${colors.bold("Items to install:")}`);
8821
+ for (const item of tree.items) {
8822
+ const type = item.type.replace("registry:", "");
8823
+ console.log(` ${colors.cyan(type.padEnd(10))} ${item.name}`);
8824
+ }
8825
+ if (tree.dependencies.length > 0) {
8826
+ console.log(
8827
+ `
8828
+ ${colors.bold("npm dependencies:")} ${tree.dependencies.join(", ")}`
8829
+ );
8830
+ }
8831
+ console.log();
8832
+ const writeLabel = allOpts.dryRun ? "Previewing changes..." : "Installing items...";
8833
+ const writeSpinner = createSpinner();
8834
+ writeSpinner.start(writeLabel);
8835
+ const result = writeRegistryItems(tree, {
8836
+ projectDir: config.global.cwd,
8837
+ aliases: config.aliases,
8838
+ components: config.components,
8839
+ overwrite: allOpts.overwrite,
8840
+ dryRun: allOpts.dryRun,
8841
+ log: (msg) => {
8842
+ writeSpinner.stop();
8843
+ console.log(msg);
8844
+ writeSpinner.start(writeLabel);
8845
+ }
8846
+ });
8847
+ writeSpinner.succeed(
8848
+ allOpts.dryRun ? "Dry run complete" : `Installed ${result.written.length} files`
8849
+ );
8850
+ if (result.skipped.length > 0) {
8851
+ console.log(
8852
+ `
8853
+ ${colors.warning(`${result.skipped.length} files skipped (already exist). Use --overwrite to replace.`)}`
8854
+ );
8855
+ }
8856
+ if (!allOpts.dryRun) {
8857
+ console.log(`
8858
+ ${colors.success("Done!")} Items are ready to use.
8859
+ `);
8860
+ const firstItem = tree.items.find((i) => itemNames.includes(i.name)) ?? tree.items[0];
8861
+ if (firstItem) {
8862
+ const type = firstItem.type.replace("registry:", "");
8863
+ const name = firstItem.name;
8864
+ const titleCase = name.split("-").map((s) => s.charAt(0).toUpperCase() + s.slice(1)).join("");
8865
+ console.log(`${colors.muted("Import example:")}`);
8866
+ if (type === "ui" || type === "component") {
8867
+ console.log(
8868
+ ` ${colors.cyan(`import { ${titleCase} } from '${config.aliases.importAlias}${config.aliases.ui}/${name}';`)}`
8869
+ );
8870
+ } else if (type === "hook") {
8871
+ console.log(
8872
+ ` ${colors.cyan(`import { ${titleCase.replace("Use", "use")} } from '${config.aliases.importAlias}${config.aliases.hooks}/${titleCase.replace("Use", "use")}';`)}`
8873
+ );
8874
+ } else if (type === "util") {
8875
+ console.log(
8876
+ ` ${colors.cyan(`import { ${name} } from '${config.aliases.importAlias}${config.aliases.utils}/${name}';`)}`
8877
+ );
8878
+ }
8879
+ console.log();
8880
+ }
8881
+ }
8882
+ } catch (err) {
8883
+ logger.error(`Unexpected error: ${err.message}`);
8884
+ process.exit(ExitCode.GeneralError);
8885
+ }
8886
+ });
8887
+ return cmd;
8747
8888
  }
8889
+ var logLevelSchema = z.enum(["silent", "error", "warn", "info", "debug", "verbose"]);
8890
+ var outputFormatSchema = z.enum(["css", "scss", "less", "json", "js", "ts", "esm", "cjs"]);
8891
+ var frameworkSchema = z.enum(["react", "vue", "angular", "svelte", "vanilla"]);
8892
+ var hashTypeSchema = z.enum(["content", "timestamp", "version", "none"]);
8893
+ z.string().min(1, "Glob pattern cannot be empty");
8894
+ z.string().min(1, "File path cannot be empty");
8895
+ z.string().refine(
8896
+ (val) => {
8897
+ const parts = val.split("-");
8898
+ const version2 = parts[0] ?? "";
8899
+ const preRelease = parts[1];
8900
+ const versionParts = version2.split(".");
8901
+ if (versionParts.length !== 3) {
8902
+ return false;
8903
+ }
8904
+ for (const part of versionParts) {
8905
+ const num = Number(part);
8906
+ if (!Number.isInteger(num) || num < 0) {
8907
+ return false;
8908
+ }
8909
+ }
8910
+ if (preRelease !== void 0 && preRelease.length === 0) {
8911
+ return false;
8912
+ }
8913
+ return true;
8914
+ },
8915
+ { message: "Invalid semantic version format" }
8916
+ );
8917
+ var customTransformSchema = z.object({
8918
+ name: z.string().min(1, "Transform name is required"),
8919
+ description: z.string().optional(),
8920
+ type: z.enum(["value", "attribute", "name"]).optional().default("value"),
8921
+ transform: z.function().optional(),
8922
+ filter: z.function().optional(),
8923
+ matcher: z.function().optional()
8924
+ });
8925
+ var customFormatSchema = z.object({
8926
+ name: z.string().min(1, "Format name is required"),
8927
+ description: z.string().optional(),
8928
+ formatter: z.function().optional(),
8929
+ extension: z.string().min(1).optional()
8930
+ });
8931
+ var outputFormatEnum = z.enum(["css", "scss", "js", "ts", "json", "android", "ios"]);
8932
+ var themeDefinitionSchema = z.object({
8933
+ isDefault: z.boolean().optional().default(false),
8934
+ suffix: z.string().nullable().optional(),
8935
+ selector: z.string().min(1, "Theme selector is required"),
8936
+ mediaQuery: z.string().optional(),
8937
+ dataAttribute: z.string().optional(),
8938
+ outputFiles: z.record(outputFormatEnum, z.string()).optional()
8939
+ });
8940
+ var themeSelectorPatternSchema = z.object({
8941
+ default: z.string().optional().default(":root"),
8942
+ others: z.string().optional().default('[data-dsai-theme="{mode}"]')
8943
+ });
8944
+ var themesConfigSchema = z.object({
8945
+ enabled: z.boolean().optional().default(true),
8946
+ autoDetect: z.boolean().optional().default(true),
8947
+ default: z.string().optional().default("light"),
8948
+ ignoreModes: z.array(z.string()).optional().default([]),
8949
+ selectorPattern: themeSelectorPatternSchema.optional(),
8950
+ definitions: z.record(z.string(), themeDefinitionSchema).optional(),
8951
+ // Legacy fields (for backward compatibility)
8952
+ defaultMode: z.enum(["light", "dark", "system"]).optional(),
8953
+ modes: z.record(
8954
+ z.string(),
8955
+ z.object({
8956
+ selector: z.string().min(1),
8957
+ mediaQuery: z.string().optional(),
8958
+ dataAttribute: z.string().optional(),
8959
+ cssVariables: z.boolean().optional(),
8960
+ generateSeparateFiles: z.boolean().optional(),
8961
+ prefix: z.string().optional()
8962
+ })
8963
+ ).optional(),
8964
+ outputFileName: z.string().optional(),
8965
+ colorScheme: z.object({
8966
+ light: z.string().optional(),
8967
+ dark: z.string().optional()
8968
+ }).optional()
8969
+ });
8970
+ var iconOptimizationSchema = z.object({
8971
+ enabled: z.boolean().optional().default(true),
8972
+ removeComments: z.boolean().optional().default(true),
8973
+ removeDimensions: z.boolean().optional().default(false),
8974
+ removeViewBox: z.boolean().optional().default(false),
8975
+ removeXMLNS: z.boolean().optional().default(true),
8976
+ cleanupIds: z.boolean().optional().default(true),
8977
+ minify: z.boolean().optional().default(true)
8978
+ });
8979
+ var iconSpriteSchema = z.object({
8980
+ enabled: z.boolean().optional().default(true),
8981
+ fileName: z.string().optional().default("icons"),
8982
+ format: z.enum(["symbol", "stack", "css"]).optional().default("symbol"),
8983
+ prefix: z.string().optional().default("icon-")
8984
+ });
8985
+ var iconsConfigSchema = z.object({
8986
+ enabled: z.boolean().optional().default(true),
8987
+ sourceDir: z.string().optional().default("assets/icons"),
8988
+ outputDir: z.string().optional().default("dist/icons"),
8989
+ formats: z.array(z.enum(["svg", "react", "vue", "sprite", "font"])).optional().default(["svg"]),
8990
+ optimization: iconOptimizationSchema.optional(),
8991
+ sprite: iconSpriteSchema.optional(),
8992
+ componentPrefix: z.string().optional().default("Icon"),
8993
+ componentSuffix: z.string().optional().default(""),
8994
+ generateIndex: z.boolean().optional().default(true),
8995
+ generateTypes: z.boolean().optional().default(true)
8996
+ });
8997
+ var tokenBuildConfigSchema = z.object({
8998
+ format: outputFormatSchema,
8999
+ outputDir: z.string().optional(),
9000
+ outputFileName: z.string().optional(),
9001
+ fileExtension: z.string().optional(),
9002
+ prefix: z.string().optional(),
9003
+ useVariables: z.boolean().optional(),
9004
+ selector: z.string().optional(),
9005
+ transforms: z.array(z.string()).optional(),
9006
+ customTransforms: z.array(customTransformSchema).optional(),
9007
+ filter: z.function().optional(),
9008
+ header: z.string().optional(),
9009
+ footer: z.string().optional()
9010
+ });
9011
+ var postprocessConfigSchema = z.object({
9012
+ enabled: z.boolean().optional(),
9013
+ cssDir: z.string().optional(),
9014
+ files: z.array(z.string()).optional(),
9015
+ replacements: z.array(
9016
+ z.object({
9017
+ description: z.string().optional(),
9018
+ from: z.union([z.string(), z.instanceof(RegExp)]),
9019
+ to: z.string()
9020
+ })
9021
+ ).optional()
9022
+ });
9023
+ var scssConfigSchema = z.object({
9024
+ /** Output styles to generate: 'expanded' (readable) or 'compressed' (minified) */
9025
+ outputStyles: z.array(z.enum(["expanded", "compressed"])).optional(),
9026
+ /** Generate source maps for SCSS compilation */
9027
+ generateSourceMaps: z.boolean().optional(),
9028
+ /** Suffix for minified files (e.g., '.min') */
9029
+ minifiedSuffix: z.string().optional(),
9030
+ /** Theme entry point SCSS file */
9031
+ themeEntry: z.string().optional(),
9032
+ /** Utilities entry point SCSS file */
9033
+ utilitiesEntry: z.string().optional(),
9034
+ /** Output directory for compiled CSS files */
9035
+ cssOutputDir: z.string().optional(),
9036
+ /** Additional Sass load paths */
9037
+ loadPaths: z.array(z.string()).optional(),
9038
+ /** Target CSS framework for variable name mapping */
9039
+ framework: z.enum(["bootstrap", "tailwind", "material", "custom"]).optional(),
9040
+ /** Custom token to variable name mappings */
9041
+ nameMapping: z.record(z.string(), z.string()).optional(),
9042
+ /** Output path for Bootstrap-compatible SCSS variables */
9043
+ variablesOutput: z.string().optional()
9044
+ });
9045
+ var tokenCacheConfigSchema = z.object({
9046
+ enabled: z.boolean().optional().default(true),
9047
+ directory: z.string().optional().default(".cache"),
9048
+ hashType: hashTypeSchema.optional().default("content"),
9049
+ maxAge: z.number().optional().default(864e5)
9050
+ });
9051
+ var tokenWatchConfigSchema = z.object({
9052
+ enabled: z.boolean().optional().default(false),
9053
+ debounce: z.number().optional().default(300),
9054
+ clearScreen: z.boolean().optional().default(true),
9055
+ ignorePatterns: z.array(z.string()).optional().default([])
9056
+ });
9057
+ var tokensHooksSchema = z.object({
9058
+ onBuildStart: z.function().optional(),
9059
+ onFormatComplete: z.function().optional(),
9060
+ onAllFormatsComplete: z.function().optional(),
9061
+ onBuildComplete: z.function().optional(),
9062
+ onError: z.function().optional()
9063
+ });
9064
+ var buildPipelineStepSchema = z.enum([
9065
+ "validate",
9066
+ "snapshot",
9067
+ "preprocess",
9068
+ "transform",
9069
+ "style-dictionary",
9070
+ "sync",
9071
+ "sass-theme",
9072
+ "sass-theme-minified",
9073
+ "postprocess",
9074
+ "sass-utilities",
9075
+ "sass-utilities-minified",
9076
+ "bundle"
9077
+ ]);
9078
+ var tokensBuildPipelineSchema = z.object({
9079
+ /**
9080
+ * Steps to include in the build.
9081
+ * Order matters - steps run in sequence.
9082
+ * Default includes all steps for full @dsai-io/tokens build.
9083
+ * Simpler packages can use subset like ['validate', 'transform', 'style-dictionary']
9084
+ */
9085
+ steps: z.array(buildPipelineStepSchema).optional(),
9086
+ /**
9087
+ * Paths configuration for build steps
9088
+ */
9089
+ paths: z.object({
9090
+ /** Source file for sync step (Style Dictionary JS output) */
9091
+ syncSource: z.string().optional(),
9092
+ /** Target file for sync step */
9093
+ syncTarget: z.string().optional(),
9094
+ /** SCSS theme input file */
9095
+ sassThemeInput: z.string().optional(),
9096
+ /** CSS theme output file */
9097
+ sassThemeOutput: z.string().optional(),
9098
+ /** CSS theme minified output file */
9099
+ sassThemeMinifiedOutput: z.string().optional(),
9100
+ /** SCSS utilities input file */
9101
+ sassUtilitiesInput: z.string().optional(),
9102
+ /** CSS utilities output file */
9103
+ sassUtilitiesOutput: z.string().optional(),
9104
+ /** CSS utilities minified output file */
9105
+ sassUtilitiesMinifiedOutput: z.string().optional()
9106
+ }).optional(),
9107
+ /** Style Dictionary config file name */
9108
+ styleDictionaryConfig: z.string().optional()
9109
+ });
9110
+ var tokensConfigSchema = z.object({
9111
+ enabled: z.boolean().optional().default(true),
9112
+ sourcePatterns: z.array(z.string()).optional().default(["src/tokens/**/*.json", "src/tokens/**/*.yaml"]),
9113
+ outputDirs: z.object({
9114
+ css: z.string().optional().default("dist/css"),
9115
+ scss: z.string().optional().default("dist/scss"),
9116
+ less: z.string().optional().default("dist/less"),
9117
+ js: z.string().optional().default("dist/js"),
9118
+ ts: z.string().optional().default("dist/ts"),
9119
+ json: z.string().optional().default("dist/json")
9120
+ }).optional(),
9121
+ additionalScssDirectories: z.array(z.string()).optional().default([]),
9122
+ outputFileNames: z.object({
9123
+ variables: z.string().optional().default("variables"),
9124
+ utilities: z.string().optional().default("utilities"),
9125
+ mixins: z.string().optional().default("mixins"),
9126
+ tokens: z.string().optional().default("tokens")
9127
+ }).optional(),
9128
+ prefix: z.string().optional().default("dsai"),
9129
+ mergeOrder: z.array(z.string()).optional().default(["base", "semantic", "component"]),
9130
+ createBundle: z.boolean().optional().default(true),
9131
+ bundleFileName: z.string().optional().default("bundle"),
9132
+ formats: z.array(outputFormatSchema).optional().default(["css", "scss", "json"]),
9133
+ platforms: z.record(z.string(), tokenBuildConfigSchema).optional(),
9134
+ transforms: z.array(z.string()).optional().default([]),
9135
+ customTransforms: z.array(customTransformSchema).optional().default([]),
9136
+ customFormats: z.array(customFormatSchema).optional().default([]),
9137
+ hooks: tokensHooksSchema.optional(),
9138
+ cache: tokenCacheConfigSchema.optional(),
9139
+ watch: tokenWatchConfigSchema.optional(),
9140
+ verbose: z.boolean().optional().default(false),
9141
+ /** SCSS/CSS output configuration */
9142
+ scss: scssConfigSchema.optional(),
9143
+ /** Build pipeline configuration */
9144
+ pipeline: tokensBuildPipelineSchema.optional(),
9145
+ /** Postprocess configuration */
9146
+ postprocess: postprocessConfigSchema.optional()
9147
+ });
9148
+ var buildConfigSchema = z.object({
9149
+ outDir: z.string().optional().default("dist"),
9150
+ clean: z.boolean().optional().default(true),
9151
+ sourcemap: z.boolean().optional().default(false),
9152
+ minify: z.boolean().optional().default(true),
9153
+ parallel: z.boolean().optional().default(true),
9154
+ maxConcurrency: z.number().optional().default(4)
9155
+ });
9156
+ var globalConfigSchema = z.object({
9157
+ logLevel: logLevelSchema.optional().default("info"),
9158
+ colors: z.boolean().optional().default(true),
9159
+ ci: z.boolean().optional().default(false),
9160
+ dryRun: z.boolean().optional().default(false),
9161
+ cwd: z.string().optional(),
9162
+ configPath: z.string().optional(),
9163
+ framework: frameworkSchema.optional(),
9164
+ build: buildConfigSchema.optional()
9165
+ });
9166
+ var aliasesConfigSchema = z.object({
9167
+ importAlias: z.string().optional().default("@/"),
9168
+ ui: z.string().optional().default("src/components/ui"),
9169
+ hooks: z.string().optional().default("src/hooks"),
9170
+ utils: z.string().optional().default("src/lib/utils"),
9171
+ components: z.string().optional().default("src/components"),
9172
+ lib: z.string().optional().default("src/lib")
9173
+ });
9174
+ var componentsConfigSchema = z.object({
9175
+ enabled: z.boolean().optional().default(true),
9176
+ registryUrl: z.string().optional().default("https://registry.dsai.dev"),
9177
+ tsx: z.boolean().optional().default(true),
9178
+ overwrite: z.boolean().optional().default(false)
9179
+ });
9180
+ z.object({
9181
+ $schema: z.string().optional(),
9182
+ extends: z.union([z.string(), z.array(z.string())]).optional(),
9183
+ global: globalConfigSchema.optional(),
9184
+ tokens: tokensConfigSchema.optional(),
9185
+ themes: themesConfigSchema.optional(),
9186
+ icons: iconsConfigSchema.optional(),
9187
+ aliases: aliasesConfigSchema.optional(),
9188
+ components: componentsConfigSchema.optional()
9189
+ });
8748
9190
 
8749
9191
  // src/cli/commands/tokens.ts
9192
+ init_tokens();
9193
+ init_snapshot();
8750
9194
  function createTokensCommand() {
8751
9195
  const tokens = new Command("tokens").description("Design token operations").helpCommand("help [command]", "Show help for a command");
8752
9196
  tokens.command("build").description("Build design tokens").option("-p, --platforms <platforms>", "Platforms to build (comma-separated)", "all").option("-w, --watch", "Watch mode", false).option("--clean", "Clean output before build", false).option("--theme <name>", "Build only a specific theme (e.g., dark)").option("--list-themes", "List available themes from config").action(async (options, command) => {
@@ -10430,7 +10874,7 @@ function safeReadFile(basePath, ...relativePath) {
10430
10874
  return void 0;
10431
10875
  }
10432
10876
  }
10433
- function detectPackageManager(cwd) {
10877
+ function detectPackageManager2(cwd) {
10434
10878
  const basePath = resolve(cwd);
10435
10879
  if (safeExists(basePath, "bun.lockb") || safeExists(basePath, "bun.lock")) {
10436
10880
  return "bun";
@@ -10745,7 +11189,7 @@ function detectProject(cwd = process.cwd()) {
10745
11189
  isMonorepo: false,
10746
11190
  framework: "unknown",
10747
11191
  metaFramework: "none",
10748
- packageManager: detectPackageManager(basePath),
11192
+ packageManager: detectPackageManager2(basePath),
10749
11193
  typescript: false,
10750
11194
  esm: false,
10751
11195
  styling: "unknown",
@@ -10760,7 +11204,7 @@ function detectProject(cwd = process.cwd()) {
10760
11204
  monorepoTool: monorepoInfo.tool,
10761
11205
  framework: detectFramework(packageJson),
10762
11206
  metaFramework: detectMetaFramework(packageJson, basePath),
10763
- packageManager: detectPackageManager(basePath),
11207
+ packageManager: detectPackageManager2(basePath),
10764
11208
  typescript: detectTypeScript(packageJson, basePath),
10765
11209
  esm: detectESM(packageJson, basePath),
10766
11210
  styling: detectStyling(packageJson, basePath),
@@ -12984,6 +13428,941 @@ async function runConfig(options) {
12984
13428
  }
12985
13429
  }
12986
13430
 
13431
+ // src/registry/component-map.ts
13432
+ var componentMap = {
13433
+ accordion: {
13434
+ type: "registry:ui",
13435
+ title: "Accordion",
13436
+ description: "Collapsible content panels for presenting information in a limited space.",
13437
+ categories: ["disclosure", "layout"]
13438
+ },
13439
+ alert: {
13440
+ type: "registry:ui",
13441
+ title: "Alert",
13442
+ description: "Contextual feedback messages for user actions.",
13443
+ categories: ["feedback"]
13444
+ },
13445
+ avatar: {
13446
+ type: "registry:ui",
13447
+ title: "Avatar",
13448
+ description: "Graphical representation of a user or entity.",
13449
+ categories: ["data-display"]
13450
+ },
13451
+ badge: {
13452
+ type: "registry:ui",
13453
+ title: "Badge",
13454
+ description: "Small count or status indicator, typically displayed on other elements.",
13455
+ categories: ["data-display"]
13456
+ },
13457
+ breadcrumb: {
13458
+ type: "registry:ui",
13459
+ title: "Breadcrumb",
13460
+ description: "Navigation aid showing the current page location within a hierarchy.",
13461
+ categories: ["navigation"]
13462
+ },
13463
+ button: {
13464
+ type: "registry:ui",
13465
+ title: "Button",
13466
+ description: "Trigger for actions and events.",
13467
+ categories: ["actions"]
13468
+ },
13469
+ card: {
13470
+ type: "registry:ui",
13471
+ title: "Card",
13472
+ description: "Flexible container for grouping related content and actions.",
13473
+ categories: ["layout", "data-display"]
13474
+ },
13475
+ "card-list": {
13476
+ type: "registry:ui",
13477
+ title: "CardList",
13478
+ description: "Responsive list of selectable cards with keyboard navigation.",
13479
+ categories: ["layout", "data-display"]
13480
+ },
13481
+ carousel: {
13482
+ type: "registry:ui",
13483
+ title: "Carousel",
13484
+ description: "Slideshow component for cycling through content.",
13485
+ categories: ["data-display"]
13486
+ },
13487
+ checkbox: {
13488
+ type: "registry:ui",
13489
+ title: "Checkbox",
13490
+ description: "Toggle control for boolean selections.",
13491
+ categories: ["forms"]
13492
+ },
13493
+ "checkbox-group": {
13494
+ type: "registry:ui",
13495
+ title: "CheckboxGroup",
13496
+ description: "Managed group of checkboxes with shared state.",
13497
+ categories: ["forms"]
13498
+ },
13499
+ dropdown: {
13500
+ type: "registry:ui",
13501
+ title: "Dropdown",
13502
+ description: "Toggleable overlay menu for displaying a list of actions.",
13503
+ categories: ["navigation", "actions"],
13504
+ npmDependencies: ["@floating-ui/react"]
13505
+ },
13506
+ icon: {
13507
+ type: "registry:ui",
13508
+ title: "Icon",
13509
+ description: "Scalable vector icon component with accessibility support.",
13510
+ categories: ["data-display"]
13511
+ },
13512
+ input: {
13513
+ type: "registry:ui",
13514
+ title: "Input",
13515
+ description: "Text input field with validation and formatting support.",
13516
+ categories: ["forms"]
13517
+ },
13518
+ "list-group": {
13519
+ type: "registry:ui",
13520
+ title: "ListGroup",
13521
+ description: "Flexible component for displaying a series of items.",
13522
+ categories: ["data-display", "navigation"]
13523
+ },
13524
+ modal: {
13525
+ type: "registry:ui",
13526
+ title: "Modal",
13527
+ description: "Dialog overlay for focused content and user interactions.",
13528
+ categories: ["feedback", "disclosure"]
13529
+ },
13530
+ navbar: {
13531
+ type: "registry:ui",
13532
+ title: "Navbar",
13533
+ description: "Responsive navigation header with branding and links.",
13534
+ categories: ["navigation"]
13535
+ },
13536
+ pagination: {
13537
+ type: "registry:ui",
13538
+ title: "Pagination",
13539
+ description: "Navigation controls for paged content.",
13540
+ categories: ["navigation"]
13541
+ },
13542
+ popover: {
13543
+ type: "registry:ui",
13544
+ title: "Popover",
13545
+ description: "Floating content panel anchored to a trigger element.",
13546
+ categories: ["disclosure"],
13547
+ npmDependencies: ["@floating-ui/react"]
13548
+ },
13549
+ progress: {
13550
+ type: "registry:ui",
13551
+ title: "Progress",
13552
+ description: "Visual indicator of task completion.",
13553
+ categories: ["feedback"]
13554
+ },
13555
+ radio: {
13556
+ type: "registry:ui",
13557
+ title: "Radio",
13558
+ description: "Single-select control within a group of options.",
13559
+ categories: ["forms"]
13560
+ },
13561
+ scrollspy: {
13562
+ type: "registry:ui",
13563
+ title: "Scrollspy",
13564
+ description: "Automatically highlights navigation links based on scroll position.",
13565
+ categories: ["navigation"]
13566
+ },
13567
+ select: {
13568
+ type: "registry:ui",
13569
+ title: "Select",
13570
+ description: "Dropdown selector for choosing from a list of options.",
13571
+ categories: ["forms"],
13572
+ npmDependencies: ["@floating-ui/react"]
13573
+ },
13574
+ "selectable-card": {
13575
+ type: "registry:ui",
13576
+ title: "SelectableCard",
13577
+ description: "Card variant that acts as a selectable option.",
13578
+ categories: ["forms", "data-display"]
13579
+ },
13580
+ sheet: {
13581
+ type: "registry:ui",
13582
+ title: "Sheet",
13583
+ description: "Sliding panel overlay from screen edges.",
13584
+ categories: ["disclosure", "layout"]
13585
+ },
13586
+ spinner: {
13587
+ type: "registry:ui",
13588
+ title: "Spinner",
13589
+ description: "Loading indicator for asynchronous operations.",
13590
+ categories: ["feedback"]
13591
+ },
13592
+ switch: {
13593
+ type: "registry:ui",
13594
+ title: "Switch",
13595
+ description: "Toggle control for binary on/off states.",
13596
+ categories: ["forms"]
13597
+ },
13598
+ table: {
13599
+ type: "registry:ui",
13600
+ title: "Table",
13601
+ description: "Data table with sorting, selection, and responsive layout.",
13602
+ categories: ["data-display"]
13603
+ },
13604
+ tabs: {
13605
+ type: "registry:ui",
13606
+ title: "Tabs",
13607
+ description: "Tabbed interface for switching between content panels.",
13608
+ categories: ["navigation", "layout"]
13609
+ },
13610
+ "tabs-pro": {
13611
+ type: "registry:ui",
13612
+ title: "TabsPro",
13613
+ description: "Advanced tabbed interface with closable, sortable, and overflow support.",
13614
+ categories: ["navigation", "layout"]
13615
+ },
13616
+ toast: {
13617
+ type: "registry:ui",
13618
+ title: "Toast",
13619
+ description: "Brief notification messages that auto-dismiss.",
13620
+ categories: ["feedback"]
13621
+ },
13622
+ tooltip: {
13623
+ type: "registry:ui",
13624
+ title: "Tooltip",
13625
+ description: "Informational popup displayed on hover or focus.",
13626
+ categories: ["data-display"],
13627
+ npmDependencies: ["@floating-ui/react"]
13628
+ },
13629
+ typography: {
13630
+ type: "registry:ui",
13631
+ title: "Typography",
13632
+ description: "Text rendering primitives with semantic variants.",
13633
+ categories: ["data-display"]
13634
+ }
13635
+ };
13636
+ var hookMap = {
13637
+ "use-async": {
13638
+ type: "registry:hook",
13639
+ title: "useAsync",
13640
+ description: "Manages async operation lifecycle (loading, error, data states).",
13641
+ categories: ["state"]
13642
+ },
13643
+ "use-callback-ref": {
13644
+ type: "registry:hook",
13645
+ title: "useCallbackRef",
13646
+ description: "Stable callback reference that always points to the latest function.",
13647
+ categories: ["refs"]
13648
+ },
13649
+ "use-click-outside": {
13650
+ type: "registry:hook",
13651
+ title: "useClickOutside",
13652
+ description: "Detects clicks outside of a target element.",
13653
+ categories: ["dom"]
13654
+ },
13655
+ "use-controllable-state": {
13656
+ type: "registry:hook",
13657
+ title: "useControllableState",
13658
+ description: "Manages state that can be either controlled or uncontrolled.",
13659
+ categories: ["state"]
13660
+ },
13661
+ "use-dark-mode": {
13662
+ type: "registry:hook",
13663
+ title: "useDarkMode",
13664
+ description: "Detects and toggles dark mode preference.",
13665
+ categories: ["theme"]
13666
+ },
13667
+ "use-debounce": {
13668
+ type: "registry:hook",
13669
+ title: "useDebounce",
13670
+ description: "Debounces a value or callback over a specified delay.",
13671
+ categories: ["timing"]
13672
+ },
13673
+ "use-field": {
13674
+ type: "registry:hook",
13675
+ title: "useField",
13676
+ description: "Form field state management with validation.",
13677
+ categories: ["forms"]
13678
+ },
13679
+ "use-focus-trap": {
13680
+ type: "registry:hook",
13681
+ title: "useFocusTrap",
13682
+ description: "Traps keyboard focus within a container for modal-like experiences.",
13683
+ categories: ["a11y"]
13684
+ },
13685
+ "use-form": {
13686
+ type: "registry:hook",
13687
+ title: "useForm",
13688
+ description: "Comprehensive form state management with validation.",
13689
+ categories: ["forms"]
13690
+ },
13691
+ "use-hover": {
13692
+ type: "registry:hook",
13693
+ title: "useHover",
13694
+ description: "Tracks hover state of an element with enter/leave delays.",
13695
+ categories: ["dom"]
13696
+ },
13697
+ "use-id": {
13698
+ type: "registry:hook",
13699
+ title: "useId",
13700
+ description: "Generates stable unique identifiers for accessibility attributes.",
13701
+ categories: ["a11y"]
13702
+ },
13703
+ "use-intersection-observer": {
13704
+ type: "registry:hook",
13705
+ title: "useIntersectionObserver",
13706
+ description: "Observes element visibility within the viewport.",
13707
+ categories: ["dom"]
13708
+ },
13709
+ "use-key-press": {
13710
+ type: "registry:hook",
13711
+ title: "useKeyPress",
13712
+ description: "Listens for specific keyboard key presses.",
13713
+ categories: ["dom"]
13714
+ },
13715
+ "use-local-storage": {
13716
+ type: "registry:hook",
13717
+ title: "useLocalStorage",
13718
+ description: "Persists state to localStorage with serialization.",
13719
+ categories: ["state", "storage"]
13720
+ },
13721
+ "use-media-query": {
13722
+ type: "registry:hook",
13723
+ title: "useMediaQuery",
13724
+ description: "Matches CSS media queries and provides responsive breakpoint helpers.",
13725
+ categories: ["responsive"]
13726
+ },
13727
+ "use-mounted": {
13728
+ type: "registry:hook",
13729
+ title: "useMounted",
13730
+ description: "Tracks whether the component is currently mounted.",
13731
+ categories: ["lifecycle"]
13732
+ },
13733
+ "use-previous": {
13734
+ type: "registry:hook",
13735
+ title: "usePrevious",
13736
+ description: "Returns the previous value of a variable across renders.",
13737
+ categories: ["state"]
13738
+ },
13739
+ "use-reduced-motion": {
13740
+ type: "registry:hook",
13741
+ title: "useReducedMotion",
13742
+ description: "Detects user preference for reduced motion.",
13743
+ categories: ["a11y"]
13744
+ },
13745
+ "use-resize-observer": {
13746
+ type: "registry:hook",
13747
+ title: "useResizeObserver",
13748
+ description: "Observes element size changes via ResizeObserver.",
13749
+ categories: ["dom"]
13750
+ },
13751
+ "use-roving-focus": {
13752
+ type: "registry:hook",
13753
+ title: "useRovingFocus",
13754
+ description: "Implements roving tabindex pattern for composite widgets.",
13755
+ categories: ["a11y"]
13756
+ },
13757
+ "use-scroll-lock": {
13758
+ type: "registry:hook",
13759
+ title: "useScrollLock",
13760
+ description: "Prevents body scrolling while active (for modals/overlays).",
13761
+ categories: ["dom"]
13762
+ },
13763
+ "use-session-storage": {
13764
+ type: "registry:hook",
13765
+ title: "useSessionStorage",
13766
+ description: "Persists state to sessionStorage with serialization.",
13767
+ categories: ["state", "storage"]
13768
+ },
13769
+ "use-throttle": {
13770
+ type: "registry:hook",
13771
+ title: "useThrottle",
13772
+ description: "Throttles a value or callback to fire at most once per interval.",
13773
+ categories: ["timing"]
13774
+ }
13775
+ };
13776
+ var utilMap = {
13777
+ cn: {
13778
+ type: "registry:util",
13779
+ title: "cn",
13780
+ description: "Conditional class name composition utility.",
13781
+ categories: ["styling"]
13782
+ },
13783
+ a11y: {
13784
+ type: "registry:util",
13785
+ title: "a11y",
13786
+ description: "Accessibility utilities including screen reader announcements and ARIA helpers.",
13787
+ categories: ["a11y"]
13788
+ },
13789
+ async: {
13790
+ type: "registry:util",
13791
+ title: "async",
13792
+ description: "Async operation utilities: abortable tasks, queues, exponential backoff.",
13793
+ categories: ["async"]
13794
+ },
13795
+ browser: {
13796
+ type: "registry:util",
13797
+ title: "browser",
13798
+ description: "Browser environment detection and feature checks.",
13799
+ categories: ["platform"]
13800
+ },
13801
+ collections: {
13802
+ type: "registry:util",
13803
+ title: "collections",
13804
+ description: "Collection utilities: chunk, paginate, memoize, selectors.",
13805
+ categories: ["data"]
13806
+ },
13807
+ color: {
13808
+ type: "registry:util",
13809
+ title: "color",
13810
+ description: "Color manipulation utilities: contrast, luminance, hex/rgb conversion.",
13811
+ categories: ["styling"]
13812
+ },
13813
+ date: {
13814
+ type: "registry:util",
13815
+ title: "date",
13816
+ description: "Date formatting and relative time utilities.",
13817
+ categories: ["formatting"]
13818
+ },
13819
+ "merge-refs": {
13820
+ type: "registry:util",
13821
+ title: "mergeRefs",
13822
+ description: "Merges multiple React refs into a single callback ref.",
13823
+ categories: ["refs"]
13824
+ },
13825
+ dx: {
13826
+ type: "registry:util",
13827
+ title: "dx",
13828
+ description: "Developer experience helpers: component creation, context factories, polymorphic patterns.",
13829
+ categories: ["dx"]
13830
+ },
13831
+ forms: {
13832
+ type: "registry:util",
13833
+ title: "forms",
13834
+ description: "Form utilities: validators, field error extraction, dirty checking.",
13835
+ categories: ["forms"]
13836
+ },
13837
+ keyboard: {
13838
+ type: "registry:util",
13839
+ title: "keyboard",
13840
+ description: "Keyboard event helpers for detecting specific keys.",
13841
+ categories: ["dom"]
13842
+ },
13843
+ layout: {
13844
+ type: "registry:util",
13845
+ title: "layout",
13846
+ description: "Layout measurement utilities: element bounds, viewport size, resize observation.",
13847
+ categories: ["dom"]
13848
+ },
13849
+ misc: {
13850
+ type: "registry:util",
13851
+ title: "misc",
13852
+ description: "Miscellaneous utilities: clear icon, safe input props, event helpers.",
13853
+ categories: ["misc"]
13854
+ },
13855
+ motion: {
13856
+ type: "registry:util",
13857
+ title: "motion",
13858
+ description: "Animation utilities: spring physics, easing functions, distance calculations.",
13859
+ categories: ["animation"]
13860
+ },
13861
+ number: {
13862
+ type: "registry:util",
13863
+ title: "number",
13864
+ description: "Number formatting and clamping utilities.",
13865
+ categories: ["formatting"]
13866
+ },
13867
+ object: {
13868
+ type: "registry:util",
13869
+ title: "object",
13870
+ description: "Object manipulation utilities: deep merge, pick, omit.",
13871
+ categories: ["data"]
13872
+ },
13873
+ platform: {
13874
+ type: "registry:util",
13875
+ title: "platform",
13876
+ description: "Platform detection utilities: browser, OS, device pixel ratio, text direction.",
13877
+ categories: ["platform"]
13878
+ },
13879
+ responsive: {
13880
+ type: "registry:util",
13881
+ title: "responsive",
13882
+ description: "Responsive design utilities.",
13883
+ categories: ["responsive"]
13884
+ },
13885
+ safety: {
13886
+ type: "registry:util",
13887
+ title: "safety",
13888
+ description: "Security utilities: clipboard access, crypto ID generation, token generation.",
13889
+ categories: ["security"]
13890
+ },
13891
+ string: {
13892
+ type: "registry:util",
13893
+ title: "string",
13894
+ description: "String manipulation utilities: capitalize, slugify, variant classes.",
13895
+ categories: ["formatting"]
13896
+ },
13897
+ telemetry: {
13898
+ type: "registry:util",
13899
+ title: "telemetry",
13900
+ description: "Telemetry utilities: error catching, performance measurement, timing.",
13901
+ categories: ["observability"]
13902
+ },
13903
+ timing: {
13904
+ type: "registry:util",
13905
+ title: "timing",
13906
+ description: "Timing utilities: debounce and throttle functions.",
13907
+ categories: ["timing"]
13908
+ },
13909
+ types: {
13910
+ type: "registry:util",
13911
+ title: "types",
13912
+ description: "Shared type guards and type utilities.",
13913
+ categories: ["types"]
13914
+ },
13915
+ validation: {
13916
+ type: "registry:util",
13917
+ title: "validation",
13918
+ description: "Input validation utilities: email, URL, href safety checks.",
13919
+ categories: ["validation"]
13920
+ }
13921
+ };
13922
+ var directoryToRegistryName = {
13923
+ Accordion: "accordion",
13924
+ Alert: "alert",
13925
+ Avatar: "avatar",
13926
+ Badge: "badge",
13927
+ Breadcrumb: "breadcrumb",
13928
+ Button: "button",
13929
+ Card: "card",
13930
+ CardList: "card-list",
13931
+ Carousel: "carousel",
13932
+ Checkbox: "checkbox",
13933
+ CheckboxGroup: "checkbox-group",
13934
+ Dropdown: "dropdown",
13935
+ Icon: "icon",
13936
+ Input: "input",
13937
+ ListGroup: "list-group",
13938
+ Modal: "modal",
13939
+ Navbar: "navbar",
13940
+ Pagination: "pagination",
13941
+ Popover: "popover",
13942
+ Progress: "progress",
13943
+ Radio: "radio",
13944
+ Scrollspy: "scrollspy",
13945
+ Select: "select",
13946
+ SelectableCard: "selectable-card",
13947
+ Sheet: "sheet",
13948
+ Spinner: "spinner",
13949
+ Switch: "switch",
13950
+ Table: "table",
13951
+ Tabs: "tabs",
13952
+ TabsPro: "tabs-pro",
13953
+ Toast: "toast",
13954
+ Tooltip: "tooltip",
13955
+ Typography: "typography"
13956
+ };
13957
+ var hookDirectoryToRegistryName = {
13958
+ useAsync: "use-async",
13959
+ useCallbackRef: "use-callback-ref",
13960
+ useClickOutside: "use-click-outside",
13961
+ useControllableState: "use-controllable-state",
13962
+ useDarkMode: "use-dark-mode",
13963
+ useDebounce: "use-debounce",
13964
+ useField: "use-field",
13965
+ useFocusTrap: "use-focus-trap",
13966
+ useForm: "use-form",
13967
+ useHover: "use-hover",
13968
+ useId: "use-id",
13969
+ useIntersectionObserver: "use-intersection-observer",
13970
+ useKeyPress: "use-key-press",
13971
+ useLocalStorage: "use-local-storage",
13972
+ useMediaQuery: "use-media-query",
13973
+ useMounted: "use-mounted",
13974
+ usePrevious: "use-previous",
13975
+ useReducedMotion: "use-reduced-motion",
13976
+ useResizeObserver: "use-resize-observer",
13977
+ useRovingFocus: "use-roving-focus",
13978
+ useScrollLock: "use-scroll-lock",
13979
+ useSessionStorage: "use-session-storage",
13980
+ useThrottle: "use-throttle"
13981
+ };
13982
+
13983
+ // src/registry/builder.ts
13984
+ var EXCLUDE_PATTERNS = [
13985
+ /\.test\.(tsx?|jsx?)$/,
13986
+ /\.spec\.(tsx?|jsx?)$/,
13987
+ /\.stories\.(tsx?|jsx?)$/,
13988
+ /\.figma\.(tsx?|jsx?)$/,
13989
+ /\.a11y\.test\./,
13990
+ /\.security\.test\./,
13991
+ /\.integration\.test\./,
13992
+ /README\.md$/
13993
+ ];
13994
+ var REACT_BUILTINS = /* @__PURE__ */ new Set(["react", "react-dom", "react/jsx-runtime", "react-dom/client"]);
13995
+ var UTIL_SUBPATH_TO_REGISTRY = {
13996
+ index: "cn",
13997
+ keyboard: "keyboard",
13998
+ dom: "merge-refs",
13999
+ "dom/mergeRefs": "merge-refs",
14000
+ browser: "browser",
14001
+ validation: "validation",
14002
+ string: "string",
14003
+ misc: "misc",
14004
+ a11y: "a11y",
14005
+ types: "types",
14006
+ async: "async",
14007
+ collections: "collections",
14008
+ color: "color",
14009
+ date: "date",
14010
+ dx: "dx",
14011
+ forms: "forms",
14012
+ layout: "layout",
14013
+ motion: "motion",
14014
+ number: "number",
14015
+ object: "object",
14016
+ platform: "platform",
14017
+ responsive: "responsive",
14018
+ safety: "safety",
14019
+ telemetry: "telemetry",
14020
+ timing: "timing"
14021
+ };
14022
+ function shouldIncludeFile(filePath) {
14023
+ const ext = extname(filePath);
14024
+ if (![".ts", ".tsx", ".css"].includes(ext)) return false;
14025
+ return !EXCLUDE_PATTERNS.some((pattern) => pattern.test(filePath));
14026
+ }
14027
+ function readSourceFiles(dirPath) {
14028
+ if (!existsSync(dirPath) || !statSync(dirPath).isDirectory()) return [];
14029
+ const results = [];
14030
+ for (const entry of readdirSync(dirPath, { withFileTypes: true })) {
14031
+ const fullPath = join(dirPath, entry.name);
14032
+ if (entry.isDirectory()) {
14033
+ for (const sub of readdirSync(fullPath, { withFileTypes: true })) {
14034
+ if (sub.isFile()) {
14035
+ const subPath = join(fullPath, sub.name);
14036
+ if (shouldIncludeFile(subPath)) {
14037
+ results.push({ path: relative(dirPath, subPath), content: readFileSync(subPath, "utf-8") });
14038
+ }
14039
+ }
14040
+ }
14041
+ } else if (entry.isFile() && shouldIncludeFile(fullPath)) {
14042
+ results.push({ path: entry.name, content: readFileSync(fullPath, "utf-8") });
14043
+ }
14044
+ }
14045
+ return results;
14046
+ }
14047
+ function extractCnSource(utilsIndexPath) {
14048
+ const content = readFileSync(utilsIndexPath, "utf-8");
14049
+ const cnPattern = /(\/\*\*[\s\S]*?\*\/\s*)?export function cn\b[\s\S]*?\n\}/;
14050
+ const match = cnPattern.exec(content);
14051
+ return match ? match[0] : "export function cn(...classes: (string | boolean | undefined | null)[]): string {\n return classes.filter(Boolean).join(' ');\n}";
14052
+ }
14053
+ function analyzeImports(files, knownNpmDeps) {
14054
+ const registryDeps = /* @__PURE__ */ new Set();
14055
+ const npmDeps = new Set(knownNpmDeps);
14056
+ const importPattern = /(?:import|export)\s+(?:[\s\S]*?)\s+from\s+['"]([^'"]+)['"]/g;
14057
+ for (const file of files) {
14058
+ let m2;
14059
+ importPattern.lastIndex = 0;
14060
+ while ((m2 = importPattern.exec(file.content)) !== null) {
14061
+ const specifier = m2[1] ?? "";
14062
+ const typesPattern = /\.\.\/(?:\.\.\/)?types(?:\/.*)?$/;
14063
+ if (typesPattern.test(specifier)) {
14064
+ registryDeps.add("dsai-types");
14065
+ continue;
14066
+ }
14067
+ const hookPattern = /\.\.\/(?:\.\.\/)?hooks\/(\w+)/;
14068
+ const hookMatch = hookPattern.exec(specifier);
14069
+ if (hookMatch && hookMatch[1]) {
14070
+ const regName = hookDirectoryToRegistryName[hookMatch[1]];
14071
+ if (regName) registryDeps.add(regName);
14072
+ continue;
14073
+ }
14074
+ const utilPattern = /\.\.\/(?:\.\.\/)?utils(?:\/(.+))?$/;
14075
+ const utilMatch = utilPattern.exec(specifier);
14076
+ if (utilMatch) {
14077
+ const subpath = utilMatch[1] ?? "index";
14078
+ const regName = UTIL_SUBPATH_TO_REGISTRY[subpath];
14079
+ if (regName) registryDeps.add(regName);
14080
+ continue;
14081
+ }
14082
+ const compPattern = /^\.\.\/(\.\.\/)?(?:components\/)?([A-Z]\w+)(?:\/.*)?$/;
14083
+ const compMatch = compPattern.exec(specifier);
14084
+ if (compMatch && compMatch[2]) {
14085
+ const compDir = compMatch[2];
14086
+ const regName = directoryToRegistryName[compDir];
14087
+ if (regName) registryDeps.add(regName);
14088
+ continue;
14089
+ }
14090
+ if (!specifier.startsWith(".") && !specifier.startsWith("/")) {
14091
+ const parts = specifier.split("/");
14092
+ const pkgName = specifier.startsWith("@") && parts.length >= 2 ? `${parts[0]}/${parts[1]}` : parts[0] ?? specifier;
14093
+ if (pkgName && !REACT_BUILTINS.has(pkgName) && !pkgName.startsWith("@dsai-io/")) {
14094
+ npmDeps.add(pkgName);
14095
+ }
14096
+ }
14097
+ }
14098
+ }
14099
+ return { registryDeps, npmDeps };
14100
+ }
14101
+ function buildComponentItem(name, dirPath, log) {
14102
+ const meta = componentMap[name];
14103
+ if (!meta) {
14104
+ log(` [WARN] No metadata for component "${name}", skipping`);
14105
+ return null;
14106
+ }
14107
+ const sourceFiles = readSourceFiles(dirPath);
14108
+ if (sourceFiles.length === 0) {
14109
+ log(` [WARN] No source files found in ${dirPath}`);
14110
+ return null;
14111
+ }
14112
+ const { registryDeps, npmDeps } = analyzeImports(sourceFiles, meta.npmDependencies ?? []);
14113
+ const files = sourceFiles.map((f) => ({
14114
+ path: f.path,
14115
+ type: extname(f.path) === ".css" ? "registry:style" : meta.type,
14116
+ content: f.content
14117
+ }));
14118
+ return {
14119
+ name,
14120
+ type: meta.type,
14121
+ title: meta.title,
14122
+ description: meta.description,
14123
+ dependencies: [...npmDeps].sort(),
14124
+ devDependencies: [],
14125
+ registryDependencies: [...registryDeps].sort(),
14126
+ files,
14127
+ categories: meta.categories
14128
+ };
14129
+ }
14130
+ function buildHookItem(name, dirPath, log) {
14131
+ const meta = hookMap[name];
14132
+ if (!meta) {
14133
+ log(` [WARN] No metadata for hook "${name}", skipping`);
14134
+ return null;
14135
+ }
14136
+ const sourceFiles = readSourceFiles(dirPath);
14137
+ if (sourceFiles.length === 0) {
14138
+ log(` [WARN] No source files found in ${dirPath}`);
14139
+ return null;
14140
+ }
14141
+ const { registryDeps, npmDeps } = analyzeImports(sourceFiles, meta.npmDependencies ?? []);
14142
+ const files = sourceFiles.map((f) => ({
14143
+ path: f.path,
14144
+ type: extname(f.path) === ".css" ? "registry:style" : meta.type,
14145
+ content: f.content
14146
+ }));
14147
+ return {
14148
+ name,
14149
+ type: meta.type,
14150
+ title: meta.title,
14151
+ description: meta.description,
14152
+ dependencies: [...npmDeps].sort(),
14153
+ devDependencies: [],
14154
+ registryDependencies: [...registryDeps].sort(),
14155
+ files,
14156
+ categories: meta.categories
14157
+ };
14158
+ }
14159
+ function buildUtilItem(name, reactSrcDir, log) {
14160
+ const meta = utilMap[name];
14161
+ if (!meta) {
14162
+ log(` [WARN] No metadata for util "${name}", skipping`);
14163
+ return null;
14164
+ }
14165
+ let files;
14166
+ let registryDeps = /* @__PURE__ */ new Set();
14167
+ let npmDeps = /* @__PURE__ */ new Set();
14168
+ if (name === "cn") {
14169
+ const indexPath = join(reactSrcDir, "utils", "index.ts");
14170
+ const cnSource = extractCnSource(indexPath);
14171
+ files = [{ path: "cn.ts", type: "registry:util", content: cnSource }];
14172
+ } else if (name === "merge-refs") {
14173
+ const dirPath = join(reactSrcDir, "utils", "dom");
14174
+ const sourceFiles = readSourceFiles(dirPath);
14175
+ const analyzed = analyzeImports(sourceFiles, []);
14176
+ registryDeps = analyzed.registryDeps;
14177
+ npmDeps = analyzed.npmDeps;
14178
+ files = sourceFiles.map((f) => ({
14179
+ path: `dom/${f.path}`,
14180
+ type: extname(f.path) === ".css" ? "registry:style" : "registry:util",
14181
+ content: f.content
14182
+ }));
14183
+ } else {
14184
+ const dirPath = join(reactSrcDir, "utils", name);
14185
+ if (!existsSync(dirPath) || !statSync(dirPath).isDirectory()) {
14186
+ log(` [WARN] Util directory not found: ${dirPath}`);
14187
+ return null;
14188
+ }
14189
+ const sourceFiles = readSourceFiles(dirPath);
14190
+ if (sourceFiles.length === 0) {
14191
+ log(` [WARN] No source files found in ${dirPath}`);
14192
+ return null;
14193
+ }
14194
+ const analyzed = analyzeImports(sourceFiles, []);
14195
+ registryDeps = analyzed.registryDeps;
14196
+ npmDeps = analyzed.npmDeps;
14197
+ files = sourceFiles.map((f) => ({
14198
+ path: `${name}/${f.path}`,
14199
+ type: extname(f.path) === ".css" ? "registry:style" : "registry:util",
14200
+ content: f.content
14201
+ }));
14202
+ }
14203
+ return {
14204
+ name,
14205
+ type: meta.type,
14206
+ title: meta.title,
14207
+ description: meta.description,
14208
+ dependencies: [...npmDeps].sort(),
14209
+ devDependencies: [],
14210
+ registryDependencies: [...registryDeps].sort(),
14211
+ files,
14212
+ categories: meta.categories
14213
+ };
14214
+ }
14215
+ function buildTypesItem(reactSrcDir, log) {
14216
+ const typesDir = join(reactSrcDir, "types");
14217
+ const sourceFiles = readSourceFiles(typesDir);
14218
+ if (sourceFiles.length === 0) {
14219
+ log(" [WARN] No type files found");
14220
+ return null;
14221
+ }
14222
+ const files = sourceFiles.map((f) => {
14223
+ let content = f.content;
14224
+ content = content.replace(/export \{[^}]*\} from ['"]\.\.\/utils\/[^'"]+['"];?\n?/g, "");
14225
+ return {
14226
+ path: `types/${f.path}`,
14227
+ type: "registry:type",
14228
+ content
14229
+ };
14230
+ });
14231
+ return {
14232
+ name: "dsai-types",
14233
+ type: "registry:type",
14234
+ title: "Shared Types",
14235
+ description: "Shared type definitions (SafeHTMLAttributes, ComponentSize, PolymorphicComponentProps, etc.)",
14236
+ dependencies: [],
14237
+ devDependencies: [],
14238
+ registryDependencies: [],
14239
+ files,
14240
+ categories: ["types"]
14241
+ };
14242
+ }
14243
+ function buildRegistry(options) {
14244
+ const { reactSrcDir, outputDir, verbose = false } = options;
14245
+ const log = verbose ? (msg) => console.log(msg) : (_msg) => {
14246
+ };
14247
+ const componentsDir = join(reactSrcDir, "components");
14248
+ const hooksDir = join(reactSrcDir, "hooks");
14249
+ const allItems = [];
14250
+ log("[registry] Scanning components...");
14251
+ if (existsSync(componentsDir)) {
14252
+ for (const entry of readdirSync(componentsDir, { withFileTypes: true })) {
14253
+ if (!entry.isDirectory()) continue;
14254
+ const dirName = entry.name;
14255
+ const registryName = directoryToRegistryName[dirName];
14256
+ if (!registryName) {
14257
+ log(` [SKIP] Unknown component directory: ${dirName}`);
14258
+ continue;
14259
+ }
14260
+ log(` Building ${registryName}...`);
14261
+ const item = buildComponentItem(registryName, join(componentsDir, dirName), log);
14262
+ if (item) allItems.push(item);
14263
+ }
14264
+ }
14265
+ log("[registry] Scanning hooks...");
14266
+ if (existsSync(hooksDir)) {
14267
+ for (const entry of readdirSync(hooksDir, { withFileTypes: true })) {
14268
+ if (!entry.isDirectory()) continue;
14269
+ const dirName = entry.name;
14270
+ const registryName = hookDirectoryToRegistryName[dirName];
14271
+ if (!registryName) {
14272
+ log(` [SKIP] Unknown hook directory: ${dirName}`);
14273
+ continue;
14274
+ }
14275
+ log(` Building ${registryName}...`);
14276
+ const item = buildHookItem(registryName, join(hooksDir, dirName), log);
14277
+ if (item) allItems.push(item);
14278
+ }
14279
+ }
14280
+ log("[registry] Scanning utils...");
14281
+ for (const name of Object.keys(utilMap)) {
14282
+ log(` Building ${name}...`);
14283
+ const item = buildUtilItem(name, reactSrcDir, log);
14284
+ if (item) allItems.push(item);
14285
+ }
14286
+ log("[registry] Building shared types...");
14287
+ const typesItem = buildTypesItem(reactSrcDir, log);
14288
+ if (typesItem) {
14289
+ allItems.push(typesItem);
14290
+ log(` Built dsai-types (${typesItem.files.length} files)`);
14291
+ }
14292
+ log(`[registry] Writing ${allItems.length} items to ${outputDir}...`);
14293
+ for (const sub of ["components", "hooks", "utils", "types"]) {
14294
+ const dir = join(outputDir, sub);
14295
+ if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
14296
+ }
14297
+ const typeToSubdir = {
14298
+ "registry:ui": "components",
14299
+ "registry:component": "components",
14300
+ "registry:hook": "hooks",
14301
+ "registry:util": "utils",
14302
+ "registry:lib": "utils",
14303
+ "registry:type": "types"
14304
+ };
14305
+ for (const item of allItems) {
14306
+ const subdir = typeToSubdir[item.type] ?? "utils";
14307
+ const filePath = join(outputDir, subdir, `${item.name}.json`);
14308
+ writeFileSync(filePath, JSON.stringify(item, null, 2) + "\n", "utf-8");
14309
+ log(` Wrote ${relative(outputDir, filePath)}`);
14310
+ }
14311
+ const indexEntries = allItems.map((item) => ({
14312
+ name: item.name,
14313
+ type: item.type,
14314
+ title: item.title,
14315
+ description: item.description,
14316
+ dependencies: item.dependencies,
14317
+ registryDependencies: item.registryDependencies,
14318
+ categories: item.categories
14319
+ }));
14320
+ const registryIndex = {
14321
+ version: "0.1.0",
14322
+ count: indexEntries.length,
14323
+ items: indexEntries
14324
+ };
14325
+ writeFileSync(join(outputDir, "index.json"), JSON.stringify(registryIndex, null, 2) + "\n", "utf-8");
14326
+ log(`[registry] Wrote index.json (${registryIndex.count} items)`);
14327
+ return registryIndex;
14328
+ }
14329
+
14330
+ // src/cli/commands/registry.ts
14331
+ function createRegistryCommand() {
14332
+ const cmd = new Command("registry").description("Manage the component registry");
14333
+ cmd.command("build").description("Build registry JSON from @dsai-io/react source").option("--src <path>", "Path to @dsai-io/react/src directory").option("--out <path>", "Output directory for registry JSON", "registry").option("--verbose", "Show detailed logging", false).action(async (opts) => {
14334
+ const logger = createLogger(opts);
14335
+ const spinner = createSpinner();
14336
+ spinner.start("Building component registry...");
14337
+ try {
14338
+ const reactSrcDir = opts.src ? resolve(opts.src) : resolve(process.cwd(), "packages", "@dsai-io", "react", "src");
14339
+ const outputDir = resolve(
14340
+ process.cwd(),
14341
+ "packages",
14342
+ "@dsai-io",
14343
+ "tools",
14344
+ opts.out
14345
+ );
14346
+ const index = buildRegistry({
14347
+ reactSrcDir,
14348
+ outputDir,
14349
+ verbose: opts.verbose
14350
+ });
14351
+ spinner.succeed(
14352
+ `Registry built: ${colors.bold(String(index.count))} items (${index.items.filter((i) => i.type === "registry:ui").length} components, ${index.items.filter((i) => i.type === "registry:hook").length} hooks, ${index.items.filter((i) => i.type === "registry:util").length} utils)`
14353
+ );
14354
+ console.log(`
14355
+ Output: ${colors.cyan(outputDir)}
14356
+ `);
14357
+ } catch (err) {
14358
+ spinner.fail("Failed to build registry");
14359
+ logger.error(err.message);
14360
+ process.exit(ExitCode.GeneralError);
14361
+ }
14362
+ });
14363
+ return cmd;
14364
+ }
14365
+
12987
14366
  // src/version.ts
12988
14367
  var version = "0.0.1";
12989
14368
 
@@ -13002,6 +14381,15 @@ Build, validate, and manage design tokens and icons.`
13002
14381
  "after",
13003
14382
  `
13004
14383
  ${colors.bold("Examples:")}
14384
+ ${colors.muted("# Add components, hooks, or utils to your project")}
14385
+ $ dsai add button modal use-focus-trap cn
14386
+
14387
+ ${colors.muted("# List everything available")}
14388
+ $ dsai add --list
14389
+
14390
+ ${colors.muted("# Add all hooks")}
14391
+ $ dsai add --all --type hook
14392
+
13005
14393
  ${colors.muted("# Initialize configuration")}
13006
14394
  $ dsai init
13007
14395
 
@@ -13039,16 +14427,24 @@ function setupErrorHandling(program2) {
13039
14427
  var program;
13040
14428
  async function run(args = process.argv) {
13041
14429
  program = createProgram();
14430
+ program.addCommand(createAddCommand());
13042
14431
  program.addCommand(createTokensCommand());
13043
14432
  program.addCommand(createIconsCommand());
13044
14433
  program.addCommand(createInitCommand());
13045
14434
  program.addCommand(createConfigCommand());
14435
+ program.addCommand(createRegistryCommand());
13046
14436
  setupErrorHandling(program);
13047
14437
  await program.parseAsync(args);
13048
14438
  }
13049
14439
  function getProgram() {
13050
14440
  return program;
13051
14441
  }
14442
+ if (process.argv[1] === fileURLToPath(import.meta.url)) {
14443
+ run().catch((error) => {
14444
+ console.error("Fatal error:", error);
14445
+ process.exit(1);
14446
+ });
14447
+ }
13052
14448
 
13053
14449
  export { ExitCode, colors, createLogger, createSpinner, formatBytes, formatCount, formatDuration, getProgram, run };
13054
14450
  //# sourceMappingURL=index.js.map