argot-css 0.0.0-stage → 0.0.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.
Files changed (96) hide show
  1. package/LICENSE.md +20 -0
  2. package/README.md +259 -2
  3. package/bin/argot.js +4 -0
  4. package/dist/cli/ansiColors.d.ts +7 -0
  5. package/dist/cli/ansiColors.js +8 -0
  6. package/dist/cli/ansiColors.js.map +1 -0
  7. package/dist/cli/print.d.ts +2 -0
  8. package/dist/cli/print.js +13 -0
  9. package/dist/cli/print.js.map +1 -0
  10. package/dist/cli/run.d.ts +2 -0
  11. package/dist/cli/run.js +34 -0
  12. package/dist/cli/run.js.map +1 -0
  13. package/dist/cli/usage.d.ts +2 -0
  14. package/dist/cli/usage.js +17 -0
  15. package/dist/cli/usage.js.map +1 -0
  16. package/dist/palette/cli.d.ts +2 -0
  17. package/dist/palette/cli.js +33 -0
  18. package/dist/palette/cli.js.map +1 -0
  19. package/dist/palette/generateName.d.ts +3 -0
  20. package/dist/palette/generateName.js +65 -0
  21. package/dist/palette/generateName.js.map +1 -0
  22. package/dist/palette/generatePalette.d.ts +7 -0
  23. package/dist/palette/generatePalette.js +97 -0
  24. package/dist/palette/generatePalette.js.map +1 -0
  25. package/dist/palette/index.d.ts +5 -0
  26. package/dist/palette/index.js +6 -0
  27. package/dist/palette/index.js.map +1 -0
  28. package/dist/palette/node.d.ts +19 -0
  29. package/dist/palette/node.js +70 -0
  30. package/dist/palette/node.js.map +1 -0
  31. package/dist/palette/parseCssColor.d.ts +7 -0
  32. package/dist/palette/parseCssColor.js +41 -0
  33. package/dist/palette/parseCssColor.js.map +1 -0
  34. package/dist/palette/render.d.ts +8 -0
  35. package/dist/palette/render.js +49 -0
  36. package/dist/palette/render.js.map +1 -0
  37. package/dist/palette/types.d.ts +50 -0
  38. package/dist/palette/types.js +2 -0
  39. package/dist/palette/types.js.map +1 -0
  40. package/dist/palette/validation.d.ts +13 -0
  41. package/dist/palette/validation.js +110 -0
  42. package/dist/palette/validation.js.map +1 -0
  43. package/dist/processor/atImport.d.ts +4 -0
  44. package/dist/processor/atImport.js +149 -0
  45. package/dist/processor/atImport.js.map +1 -0
  46. package/dist/processor/cli.d.ts +1 -0
  47. package/dist/processor/cli.js +32 -0
  48. package/dist/processor/cli.js.map +1 -0
  49. package/dist/processor/index.d.ts +7 -0
  50. package/dist/processor/index.js +47 -0
  51. package/dist/processor/index.js.map +1 -0
  52. package/dist/processor/parseImportParams.d.ts +19 -0
  53. package/dist/processor/parseImportParams.js +139 -0
  54. package/dist/processor/parseImportParams.js.map +1 -0
  55. package/dist/processor/stylelintDefault.d.ts +4 -0
  56. package/dist/processor/stylelintDefault.js +19 -0
  57. package/dist/processor/stylelintDefault.js.map +1 -0
  58. package/dist/semantics/cli.d.ts +2 -0
  59. package/dist/semantics/cli.js +34 -0
  60. package/dist/semantics/cli.js.map +1 -0
  61. package/dist/semantics/generate.d.ts +16 -0
  62. package/dist/semantics/generate.js +53 -0
  63. package/dist/semantics/generate.js.map +1 -0
  64. package/dist/semantics/load-tokens.d.ts +29 -0
  65. package/dist/semantics/load-tokens.js +74 -0
  66. package/dist/semantics/load-tokens.js.map +1 -0
  67. package/dist/semantics/token-index.d.ts +14 -0
  68. package/dist/semantics/token-index.js +30 -0
  69. package/dist/semantics/token-index.js.map +1 -0
  70. package/dist/stylelint/config.d.ts +16 -0
  71. package/dist/stylelint/config.js +19 -0
  72. package/dist/stylelint/config.js.map +1 -0
  73. package/dist/stylelint/index.d.ts +3 -0
  74. package/dist/stylelint/index.js +4 -0
  75. package/dist/stylelint/index.js.map +1 -0
  76. package/dist/stylelint/rules/valid-token.d.ts +3 -0
  77. package/dist/stylelint/rules/valid-token.js +32 -0
  78. package/dist/stylelint/rules/valid-token.js.map +1 -0
  79. package/docs/api.md +514 -0
  80. package/package.json +115 -4
  81. package/templates/base.css +53 -0
  82. package/templates/modules/index.css +0 -0
  83. package/templates/semantics-extended.css +115 -0
  84. package/templates/semantics.css +94 -0
  85. package/templates/styles.css +7 -0
  86. package/tokens/borders.json +37 -0
  87. package/tokens/color-bg.json +104 -0
  88. package/tokens/color-border.json +59 -0
  89. package/tokens/color-chart.json +40 -0
  90. package/tokens/color-icon.json +53 -0
  91. package/tokens/color-text.json +107 -0
  92. package/tokens/layout.json +66 -0
  93. package/tokens/misc.json +16 -0
  94. package/tokens/motion.json +40 -0
  95. package/tokens/spacing.json +41 -0
  96. package/tokens/typography.json +107 -0
@@ -0,0 +1 @@
1
+ {"version":3,"file":"generatePalette.js","sourceRoot":"","sources":["../../src/palette/generatePalette.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,0BAA0B,EAAE,MAAM,iBAAiB,CAAC;AAQ7D,MAAM,SAAS,GAAG,MAAM,CAAC,MAAM,CAAC;IAC9B,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,GAAG,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI;IAC3E,GAAG,EAAE,IAAI,EAAE,GAAG;CACf,CAAC,CAAC;AACH,MAAM,MAAM,GAAG,MAAM,CAAC,MAAM,CAAC;IAC3B,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,GAAG,EAAE,IAAI,EAAE,CAAC,EAAE,IAAI,EAAE,GAAG,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI;IAC7E,IAAI,EAAE,IAAI;CACX,CAAC,CAAC;AAEH;;;GAGG;AACH,SAAS,eAAe,CAAC,UAA6B;IACpD,MAAM,UAAU,GAAG,0BAA0B,CAAC,UAAU,CAAC,CAAC;IAE1D,MAAM,MAAM,GAAG,UAAU,CAAC,UAAU,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAChD,aAAa,CAAC,IAAI,EAAE,UAAU,CAAC,OAAO,IAAI,EAAE,CAAC,CAC9C,CAAC;IACF,OAAO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AI,CAAC,SAAS,GAAG,CAAC,GAAG,SAAS,CAAC,CAAC;IACjD,CAAC;IACD,OAAO,cAAc,CAAC;AACxB,CAAC;AAED,OAAO,EAAE,eAAe,EAAE,CAAC","sourcesContent":["import { normalizePaletteDefinition } from './validation.ts';\nimport type {\n Palette,\n PaletteDefinition,\n PaletteOptions,\n NormalizedSeedColor,\n} from './types.ts';\n\nconst LIGHTNESS = Object.freeze([\n 0.98, 0.97, 0.93, 0.84, 0.8, 0.71, 0.66, 0.58, 0.53, 0.49, 0.42, 0.35, 0.27,\n 0.2, 0.16, 0.1,\n]);\nconst CHROMA = Object.freeze([\n 0.14, 0.29, 0.48, 0.57, 0.76, 0.9, 0.95, 1, 0.95, 0.9, 0.81, 0.71, 0.57, 0.43,\n 0.33, 0.24,\n]);\n\n/**\n * Generate serializable raw OKLCH scales, before gamut mapping or rounding.\n * Steps and baseStep are one-based; input order is preserved without mutation.\n */\nfunction generatePalette(definition: PaletteDefinition): Palette {\n const normalized = normalizePaletteDefinition(definition);\n\n const colors = normalized.seedColors.map((seed) =>\n generateScale(seed, definition.options || {}),\n );\n return { version: 1, options: normalized.options, colors };\n}\n\n// TODO skip normalizing, just fill in defaults here\nfunction generateScale(seed: NormalizedSeedColor, options: PaletteOptions) {\n const { lightnessCurve = 'uniform', chromaCurve = 'centered' } = options;\n const index = findTargetIndex(seed.l);\n const chromaScale =\n chromaCurve === 'weighted' ? buildChromaCurve(index, seed.c) : CHROMA;\n const anchor = lightnessCurve === 'centered' ? 8 : index;\n // Centered lightness rescales the original chroma curve at step 9; it does\n // not rebuild the weighted curve around that step.\n let chromaMultiplier = 1;\n if (lightnessCurve === 'centered') {\n chromaMultiplier = seed.c / chromaScale[8];\n } else if (chromaCurve === 'centered') {\n chromaMultiplier = seed.c / chromaScale[index];\n }\n if (!Number.isFinite(chromaMultiplier)) {\n // handle divide by zero for 0-chroma values\n chromaMultiplier = 0;\n }\n const lightness =\n lightnessCurve === 'uniform'\n ? LIGHTNESS\n : buildInclusiveLightnessCurve(seed.l, anchor);\n return {\n name: seed.name,\n baseStep: anchor + 1,\n steps: lightness.map((l, index) => ({\n step: index + 1,\n l,\n c: chromaScale[index] * chromaMultiplier,\n h: seed.h,\n })),\n };\n}\n\nfunction findTargetIndex(lightness: number): number {\n const after = LIGHTNESS.findIndex((value) => value < lightness);\n const before = after !== -1 ? after - 1 : 15;\n if (after === -1) return before;\n if (before === -1) return after;\n const beforeDiff = LIGHTNESS[before] - lightness;\n const afterDiff = lightness - LIGHTNESS[after];\n return beforeDiff < afterDiff ? before : after;\n}\n\nfunction buildChromaCurve(index: number, peakValue: number): number[] {\n const endValue = peakValue < 0.04 ? 0 : 0.01;\n const beforeSteps = index;\n const afterSteps = 15 - index;\n const beforeInterval = (peakValue - endValue) / beforeSteps;\n const afterInterval = (peakValue - endValue) / afterSteps;\n const scale = [];\n for (let i = beforeSteps; i > 0; i--) {\n scale.push(peakValue - i * beforeInterval);\n }\n scale.push(peakValue);\n for (let i = 1; i <= afterSteps; i++) {\n scale.push(peakValue - i * afterInterval);\n }\n return scale;\n}\n\nfunction buildInclusiveLightnessCurve(\n lightness: number,\n index: number,\n): number[] {\n const maxLightness = LIGHTNESS[0];\n const minLightness = LIGHTNESS[15];\n\n const lSteps = index;\n const dSteps = 15 - index;\n const lInterval = (maxLightness - lightness) / lSteps;\n const dInterval = (lightness - minLightness) / dSteps;\n\n const lightnessScale = [];\n for (let i = 0; i < lSteps; i++) {\n lightnessScale.push(maxLightness - i * lInterval);\n }\n lightnessScale.push(lightness);\n for (let i = 1; i <= dSteps; i++) {\n lightnessScale.push(lightness - i * dInterval);\n }\n return lightnessScale;\n}\n\nexport { generatePalette };\n"]}
@@ -0,0 +1,5 @@
1
+ export { normalizePaletteDefinition, serializePaletteDefinition, } from './validation.ts';
2
+ export { generatePalette } from './generatePalette.ts';
3
+ export { renderPaletteCss, generatePaletteCss } from './render.ts';
4
+ export { parseCssColor } from './parseCssColor.ts';
5
+ export type { ChromaCurve, ColorFormat, ColorGamut, LightnessCurve, NormalizedPaletteDefinition, NormalizedPaletteOptions, OklchColor, Palette, PaletteScale, SeedColor, PaletteDefinition, PaletteOptions, PaletteStep, } from './types.ts';
@@ -0,0 +1,6 @@
1
+ // Browser-safe public entrypoint. Keep Node file adapters in ./node.ts.
2
+ export { normalizePaletteDefinition, serializePaletteDefinition, } from "./validation.js";
3
+ export { generatePalette } from "./generatePalette.js";
4
+ export { renderPaletteCss, generatePaletteCss } from "./render.js";
5
+ export { parseCssColor } from "./parseCssColor.js";
6
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/palette/index.ts"],"names":[],"mappings":"AAAA,wEAAwE;AACxE,OAAO,EACL,0BAA0B,EAC1B,0BAA0B,GAC3B,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAAE,eAAe,EAAE,MAAM,sBAAsB,CAAC;AACvD,OAAO,EAAE,gBAAgB,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAC;AACnE,OAAO,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC","sourcesContent":["// Browser-safe public entrypoint. Keep Node file adapters in ./node.ts.\nexport {\n normalizePaletteDefinition,\n serializePaletteDefinition,\n} from './validation.ts';\nexport { generatePalette } from './generatePalette.ts';\nexport { renderPaletteCss, generatePaletteCss } from './render.ts';\nexport { parseCssColor } from './parseCssColor.ts';\nexport type {\n ChromaCurve,\n ColorFormat,\n ColorGamut,\n LightnessCurve,\n NormalizedPaletteDefinition,\n NormalizedPaletteOptions,\n OklchColor,\n Palette,\n PaletteScale,\n SeedColor,\n PaletteDefinition,\n PaletteOptions,\n PaletteStep,\n} from './types.ts';\n"]}
@@ -0,0 +1,19 @@
1
+ import type { NormalizedPaletteDefinition, PaletteDefinition } from './types.ts';
2
+ export interface WritePaletteOptions {
3
+ force?: boolean;
4
+ dryRun?: boolean;
5
+ }
6
+ export interface WritePaletteResult {
7
+ path: string;
8
+ css: string;
9
+ written: boolean;
10
+ }
11
+ /** Load and validate a portable JSON definition, resolving paths only in Node. */
12
+ declare function loadPaletteDefinition(filename: string): NormalizedPaletteDefinition;
13
+ /**
14
+ * Write only explicitly designated output. Dry runs validate without writing.
15
+ * Exclusive creation protects existing files; forced writes reject symlinks
16
+ * and non-regular files rather than following them.
17
+ */
18
+ declare function writePalette(outPath: string, definition: PaletteDefinition, { force, dryRun }?: WritePaletteOptions): WritePaletteResult;
19
+ export { loadPaletteDefinition, writePalette };
@@ -0,0 +1,70 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { normalizePaletteDefinition } from "./validation.js";
4
+ import { generatePaletteCss } from "./render.js";
5
+ /** Load and validate a portable JSON definition, resolving paths only in Node. */
6
+ function loadPaletteDefinition(filename) {
7
+ const resolved = path.resolve(filename);
8
+ let source;
9
+ try {
10
+ source = fs.readFileSync(resolved, 'utf8');
11
+ }
12
+ catch (error) {
13
+ throw new Error(`Cannot read palette definition "${resolved}": ${error.code}`, { cause: error });
14
+ }
15
+ let definition;
16
+ try {
17
+ definition = JSON.parse(source);
18
+ }
19
+ catch {
20
+ throw new Error(`Invalid JSON in palette definition "${resolved}"`);
21
+ }
22
+ try {
23
+ return normalizePaletteDefinition(definition);
24
+ }
25
+ catch (error) {
26
+ throw new Error(`Invalid palette definition "${resolved}": ${error instanceof Error ? error.message : String(error)}`, { cause: error });
27
+ }
28
+ }
29
+ /**
30
+ * Write only explicitly designated output. Dry runs validate without writing.
31
+ * Exclusive creation protects existing files; forced writes reject symlinks
32
+ * and non-regular files rather than following them.
33
+ */
34
+ function writePalette(outPath, definition, { force = false, dryRun = false } = {}) {
35
+ const resolved = path.resolve(outPath);
36
+ const css = generatePaletteCss(definition);
37
+ let stat;
38
+ try {
39
+ stat = fs.lstatSync(resolved);
40
+ }
41
+ catch (error) {
42
+ if (error.code !== 'ENOENT')
43
+ throw error;
44
+ }
45
+ if (stat && (!stat.isFile() || stat.isSymbolicLink())) {
46
+ throw new Error(`Refusing to overwrite non-regular file: ${resolved}`);
47
+ }
48
+ if (stat && !force) {
49
+ throw new Error(`Output already exists: ${resolved}. Use --force to replace it.`);
50
+ }
51
+ if (!dryRun) {
52
+ fs.mkdirSync(path.dirname(resolved), { recursive: true });
53
+ const flags = force
54
+ ? fs.constants.O_WRONLY |
55
+ fs.constants.O_CREAT |
56
+ fs.constants.O_TRUNC |
57
+ fs.constants.O_NOFOLLOW
58
+ : 'wx';
59
+ const descriptor = fs.openSync(resolved, flags);
60
+ try {
61
+ fs.writeFileSync(descriptor, css, 'utf8');
62
+ }
63
+ finally {
64
+ fs.closeSync(descriptor);
65
+ }
66
+ }
67
+ return { path: resolved, css, written: !dryRun };
68
+ }
69
+ export { loadPaletteDefinition, writePalette };
70
+ //# sourceMappingURL=node.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"node.js","sourceRoot":"","sources":["../../src/palette/node.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,SAAS,CAAC;AACzB,OAAO,IAAI,MAAM,WAAW,CAAC;AAC7B,OAAO,EAAE,0BAA0B,EAAE,MAAM,iBAAiB,CAAC;AAC7D,OAAO,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAC;AAiBjD,kFAAkF;AAClF,SAAS,qBAAqB,CAAC,QAAgB;IAC7C,MAAM,QAAQ,GAAG,IAAI,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC;IACxC,IAAI,MAAM,CAAC;IACX,IAAI,CAAC;QACH,MAAM,GAAG,EAAE,CAAC,YAAY,CAAC,QAAQ,EAAE,MAAM,CAAC,CAAC;IAC7C,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,MAAM,IAAI,KAAK,CACb,mCAAmC,QAAQ,MAAO,KAA+B,CAAC,IAAI,EAAE,EACxF,EAAE,KAAK,EAAE,KAAK,EAAE,CACjB,CAAC;IACJ,CAAC;IACD,IAAI,UAAmB,CAAC;IACxB,IAAI,CAAC;QACH,UAAU,GAAG,IAAI,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;IACJ,CAAC;IACD,IAAI,CAAC,MAAM,EAAE,CAAC;QACZ,EAAE,CAAC,SAAS,CAAC,IAAI,CAAC,OAAO,CAAC,QAAQ,CAAC,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,CAAC;QAC1D,MAAM,KAAK,GAAG,KAAK;YACjB,CAAC,CAAC,EAAE,CAAC,SAAS,CAAC,QAAQ;gBACrB,EAAE,CAAC,SAAS,CAAC,OAAO;gBACpB,EAAE,CAAC,SAAS,CAAC,OAAO;gBACpB,EAAE,CAAC,SAAS,CAAC,UAAU;YACzB,CAAC,CAAC,IAAI,CAAC;QACT,MAAM,UAAU,GAAG,EAAE,CAAC,QAAQ,CAAC,QAAQ,EAAE,KAAK,CAAC,CAAC;QAChD,IAAI,CAAC;YACH,EAAE,CAAC,aAAa,CAAC,UAAU,EAAE,GAAG,EAAE,MAAM,CAAC,CAAC;QAC5C,CAAC;gBAAS,CAAC;YACT,EAAE,CAAC,SAAS,CAAC,UAAU,CAAC,CAAC;QAC3B,CAAC;IACH,CAAC;IACD,OAAO,EAAE,IAAI,EAAE,QAAQ,EAAE,GAAG,EAAE,OAAO,EAAE,CAAC,MAAM,EAAE,CAAC;AACnD,CAAC;AAED,OAAO,EAAE,qBAAqB,EAAE,YAAY,EAAE,CAAC","sourcesContent":["import fs from 'node:fs';\nimport path from 'node:path';\nimport { normalizePaletteDefinition } from './validation.ts';\nimport { generatePaletteCss } from './render.ts';\nimport type {\n NormalizedPaletteDefinition,\n PaletteDefinition,\n} from './types.ts';\n\nexport interface WritePaletteOptions {\n force?: boolean;\n dryRun?: boolean;\n}\n\nexport interface WritePaletteResult {\n path: string;\n css: string;\n written: boolean;\n}\n\n/** Load and validate a portable JSON definition, resolving paths only in Node. */\nfunction loadPaletteDefinition(filename: string): NormalizedPaletteDefinition {\n const resolved = path.resolve(filename);\n let source;\n try {\n source = fs.readFileSync(resolved, 'utf8');\n } catch (error) {\n throw new Error(\n `Cannot read palette definition \"${resolved}\": ${(error as NodeJS.ErrnoException).code}`,\n { cause: error },\n );\n }\n let definition: unknown;\n try {\n definition = JSON.parse(source);\n } catch {\n throw new Error(`Invalid JSON in palette definition \"${resolved}\"`);\n }\n try {\n return normalizePaletteDefinition(definition);\n } catch (error) {\n throw new Error(\n `Invalid palette definition \"${resolved}\": ${error instanceof Error ? error.message : String(error)}`,\n { cause: error },\n );\n }\n}\n\n/**\n * Write only explicitly designated output. Dry runs validate without writing.\n * Exclusive creation protects existing files; forced writes reject symlinks\n * and non-regular files rather than following them.\n */\nfunction writePalette(\n outPath: string,\n definition: PaletteDefinition,\n { force = false, dryRun = false }: WritePaletteOptions = {},\n): WritePaletteResult {\n const resolved = path.resolve(outPath);\n const css = generatePaletteCss(definition);\n let stat;\n try {\n stat = fs.lstatSync(resolved);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;\n }\n if (stat && (!stat.isFile() || stat.isSymbolicLink())) {\n throw new Error(`Refusing to overwrite non-regular file: ${resolved}`);\n }\n if (stat && !force) {\n throw new Error(\n `Output already exists: ${resolved}. Use --force to replace it.`,\n );\n }\n if (!dryRun) {\n fs.mkdirSync(path.dirname(resolved), { recursive: true });\n const flags = force\n ? fs.constants.O_WRONLY |\n fs.constants.O_CREAT |\n fs.constants.O_TRUNC |\n fs.constants.O_NOFOLLOW\n : 'wx';\n const descriptor = fs.openSync(resolved, flags);\n try {\n fs.writeFileSync(descriptor, css, 'utf8');\n } finally {\n fs.closeSync(descriptor);\n }\n }\n return { path: resolved, css, written: !dryRun };\n}\n\nexport { loadPaletteDefinition, writePalette };\n"]}
@@ -0,0 +1,7 @@
1
+ import type { OklchColor } from './types.ts';
2
+ /**
3
+ * Optional input adapter for standalone opaque CSS colors. Palette definitions
4
+ * store the returned numeric coordinates, never the CSS string.
5
+ */
6
+ declare function parseCssColor(value: string): OklchColor;
7
+ export { parseCssColor };
@@ -0,0 +1,41 @@
1
+ import Color from 'colorjs.io';
2
+ import { checkCoordinates } from "./validation.js";
3
+ /**
4
+ * Optional input adapter for standalone opaque CSS colors. Palette definitions
5
+ * store the returned numeric coordinates, never the CSS string.
6
+ */
7
+ function parseCssColor(value) {
8
+ if (typeof value !== 'string' || value.trim() === '') {
9
+ throw new Error('color: expected an opaque CSS color string');
10
+ }
11
+ let color;
12
+ try {
13
+ color = new Color(value.trim()).to('oklch');
14
+ }
15
+ catch {
16
+ throw new Error('color: invalid or context-dependent CSS color');
17
+ }
18
+ if (color.alpha !== 1) {
19
+ throw new Error('color: expected an opaque color (alpha must be 1)');
20
+ }
21
+ const [l, c, h] = color.coords;
22
+ // Conversions of white can be a fraction above 1 due to floating-point error.
23
+ // This tolerance belongs to CSS conversion, not numeric definition validation.
24
+ if (typeof l !== 'number' ||
25
+ !Number.isFinite(l) ||
26
+ l < -1e-12 ||
27
+ l > 1 + 1e-12) {
28
+ throw new Error('color.l: expected finite lightness between 0 and 1');
29
+ }
30
+ const newL = Math.min(1, Math.max(0, l));
31
+ let newH = h;
32
+ // Achromatic CSS colors may have no hue; supply a numeric angle for handoff.
33
+ if (c === 0 && (h === null || Number.isNaN(h))) {
34
+ newH = 0;
35
+ }
36
+ const coordinates = { l: newL, c, h: newH };
37
+ checkCoordinates(coordinates, 'color');
38
+ return coordinates;
39
+ }
40
+ export { parseCssColor };
41
+ //# sourceMappingURL=parseCssColor.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"parseCssColor.js","sourceRoot":"","sources":["../../src/palette/parseCssColor.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,MAAM,YAAY,CAAC;AAC/B,OAAO,EAAE,gBAAgB,EAAE,MAAM,iBAAiB,CAAC;AAGnD;;;GAGG;AACH,SAAS,aAAa,CAAC,KAAa;IAClC,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,CAAC,IAAI,EAAE,KAAK,EAAE,EAAE,CAAC;QACrD,MAAM,IAAI,KAAK,CAAC,4CAA4C,CAAC,CAAC;IAChE,CAAC;IACD,IAAI,K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ent":["import Color from 'colorjs.io';\nimport { checkCoordinates } from './validation.ts';\nimport type { OklchColor } from './types.ts';\n\n/**\n * Optional input adapter for standalone opaque CSS colors. Palette definitions\n * store the returned numeric coordinates, never the CSS string.\n */\nfunction parseCssColor(value: string): OklchColor {\n if (typeof value !== 'string' || value.trim() === '') {\n throw new Error('color: expected an opaque CSS color string');\n }\n let color;\n try {\n color = new Color(value.trim()).to('oklch');\n } catch {\n throw new Error('color: invalid or context-dependent CSS color');\n }\n if (color.alpha !== 1) {\n throw new Error('color: expected an opaque color (alpha must be 1)');\n }\n const [l, c, h] = color.coords;\n\n // Conversions of white can be a fraction above 1 due to floating-point error.\n // This tolerance belongs to CSS conversion, not numeric definition validation.\n if (\n typeof l !== 'number' ||\n !Number.isFinite(l) ||\n l < -1e-12 ||\n l > 1 + 1e-12\n ) {\n throw new Error('color.l: expected finite lightness between 0 and 1');\n }\n const newL = Math.min(1, Math.max(0, l));\n\n let newH = h;\n // Achromatic CSS colors may have no hue; supply a numeric angle for handoff.\n if (c === 0 && (h === null || Number.isNaN(h))) {\n newH = 0;\n }\n const coordinates = { l: newL, c, h: newH };\n checkCoordinates(coordinates, 'color');\n return coordinates;\n}\n\nexport { parseCssColor };\n"]}
@@ -0,0 +1,8 @@
1
+ import type { Palette, PaletteDefinition } from './types.ts';
2
+ /**
3
+ * Render a model returned by generatePalette without mutating its raw steps.
4
+ * Gamut mapping happens here, independently of CSS output format.
5
+ */
6
+ declare function renderPaletteCss(palette: Palette): string;
7
+ declare function generatePaletteCss(definition: PaletteDefinition): string;
8
+ export { renderPaletteCss, generatePaletteCss };
@@ -0,0 +1,49 @@
1
+ import Color from 'colorjs.io';
2
+ import { checkName, normalizeOptions } from "./validation.js";
3
+ import { generatePalette } from "./generatePalette.js";
4
+ /**
5
+ * Render a model returned by generatePalette without mutating its raw steps.
6
+ * Gamut mapping happens here, independently of CSS output format.
7
+ */
8
+ function renderPaletteCss(palette) {
9
+ const options = normalizeOptions(palette.options);
10
+ const blocks = palette.colors.map(({ name, baseStep, steps }) => {
11
+ checkName(name, 'palette color name');
12
+ const lines = steps.map(({ step, l, c, h }) => {
13
+ if (!Number.isInteger(step) || step < 1 || step > 16) {
14
+ throw new Error('palette step: expected an integer from 1 to 16');
15
+ }
16
+ return ` --${name}-${step}: ${formatColor({ l, c, h }, options)};`;
17
+ });
18
+ if (!Number.isInteger(baseStep) || baseStep < 1 || baseStep > 16) {
19
+ throw new Error('palette baseStep: expected an integer from 1 to 16');
20
+ }
21
+ lines.push(` --${name}: var(--${name}-${baseStep});`);
22
+ return lines.join('\n');
23
+ });
24
+ return [
25
+ '/* Generated by Argot. */',
26
+ ':root {',
27
+ blocks.join('\n\n'),
28
+ '}',
29
+ '',
30
+ ].join('\n');
31
+ }
32
+ function formatColor({ l, c, h }, { format, gamut }) {
33
+ if (![l, c, h].every(Number.isFinite)) {
34
+ throw new Error('palette coordinates: expected finite OKLCH values');
35
+ }
36
+ const color = new Color('oklch', [l, c, h]).toGamut({
37
+ space: gamut,
38
+ method: 'css',
39
+ });
40
+ if (format === 'hex') {
41
+ return color.to('srgb').toString({ format: 'hex', collapse: false });
42
+ }
43
+ return color.to('oklch').toString({ precision: 6 });
44
+ }
45
+ function generatePaletteCss(definition) {
46
+ return renderPaletteCss(generatePalette(definition));
47
+ }
48
+ export { renderPaletteCss, generatePaletteCss };
49
+ //# sourceMappingURL=render.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"render.js","sourceRoot":"","sources":["../../src/palette/render.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,MAAM,YAAY,CAAC;AAC/B,OAAO,EAAE,SAAS,EAAE,gBAAgB,EAAE,MAAM,iBAAiB,CAAC;AAC9D,OAAO,EAAE,eAAe,EAAE,MAAM,sBAAsB,CAAC;AAQvD;;;GAGG;AACH,SAAS,gBAAgB,CAAC,OAAgB;IACxC,MAAM,OAAO,GAAG,gBAAgB,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC;IAClD,MAAM,MAA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AC,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC,KAAK,CAAC,MAAM,CAAC,QAAQ,CAAC,EAAE,CAAC;QACtC,MAAM,IAAI,KAAK,CAAC,mDAAmD,CAAC,CAAC;IACvE,CAAC;IACD,MAAM,KAAK,GAAG,IAAI,KAAK,CAAC,OAAO,EAAE,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC;QAClD,KAAK,EAAE,KAAK;QACZ,MAAM,EAAE,KAAK;KACd,CAAC,CAAC;IACH,IAAI,MAAM,KAAK,KAAK,EAAE,CAAC;QACrB,OAAO,KAAK,CAAC,EAAE,CAAC,MAAM,CAAC,CAAC,QAAQ,CAAC,EAAE,MAAM,EAAE,KAAK,EAAE,QAAQ,EAAE,KAAK,EAAE,CAAC,CAAC;IACvE,CAAC;IACD,OAAO,KAAK,CAAC,EAAE,CAAC,OAAO,CAAC,CAAC,QAAQ,CAAC,EAAE,SAAS,EAAE,CAAC,EAAE,CAAC,CAAC;AACtD,CAAC;AAED,SAAS,kBAAkB,CAAC,UAA6B;IACvD,OAAO,gBAAgB,CAAC,eAAe,CAAC,UAAU,CAAC,CAAC,CAAC;AACvD,CAAC;AAED,OAAO,EAAE,gBAAgB,EAAE,kBAAkB,EAAE,CAAC","sourcesContent":["import Color from 'colorjs.io';\nimport { checkName, normalizeOptions } from './validation.ts';\nimport { generatePalette } from './generatePalette.ts';\nimport type {\n NormalizedPaletteOptions,\n OklchColor,\n Palette,\n PaletteDefinition,\n} from './types.ts';\n\n/**\n * Render a model returned by generatePalette without mutating its raw steps.\n * Gamut mapping happens here, independently of CSS output format.\n */\nfunction renderPaletteCss(palette: Palette): string {\n const options = normalizeOptions(palette.options);\n const blocks = palette.colors.map(({ name, baseStep, steps }) => {\n checkName(name, 'palette color name');\n const lines = steps.map(({ step, l, c, h }) => {\n if (!Number.isInteger(step) || step < 1 || step > 16) {\n throw new Error('palette step: expected an integer from 1 to 16');\n }\n return ` --${name}-${step}: ${formatColor({ l, c, h }, options)};`;\n });\n if (!Number.isInteger(baseStep) || baseStep < 1 || baseStep > 16) {\n throw new Error('palette baseStep: expected an integer from 1 to 16');\n }\n lines.push(` --${name}: var(--${name}-${baseStep});`);\n return lines.join('\\n');\n });\n return [\n '/* Generated by Argot. */',\n ':root {',\n blocks.join('\\n\\n'),\n '}',\n '',\n ].join('\\n');\n}\n\nfunction formatColor(\n { l, c, h }: OklchColor,\n { format, gamut }: NormalizedPaletteOptions,\n): string {\n if (![l, c, h].every(Number.isFinite)) {\n throw new Error('palette coordinates: expected finite OKLCH values');\n }\n const color = new Color('oklch', [l, c, h]).toGamut({\n space: gamut,\n method: 'css',\n });\n if (format === 'hex') {\n return color.to('srgb').toString({ format: 'hex', collapse: false });\n }\n return color.to('oklch').toString({ precision: 6 });\n}\n\nfunction generatePaletteCss(definition: PaletteDefinition): string {\n return renderPaletteCss(generatePalette(definition));\n}\n\nexport { renderPaletteCss, generatePaletteCss };\n"]}
@@ -0,0 +1,50 @@
1
+ export type LightnessCurve = 'uniform' | 'inclusive' | 'centered';
2
+ export type ChromaCurve = 'centered' | 'weighted';
3
+ export type ColorFormat = 'oklch' | 'hex';
4
+ export type ColorGamut = 'p3' | 'srgb';
5
+ export interface PaletteOptions {
6
+ lightnessCurve?: LightnessCurve;
7
+ chromaCurve?: ChromaCurve;
8
+ format?: ColorFormat;
9
+ gamut?: ColorGamut;
10
+ }
11
+ export type NormalizedPaletteOptions = Required<PaletteOptions>;
12
+ export interface OklchColor {
13
+ /** Lightness from 0 to 1 */
14
+ l: number;
15
+ /** Chroma */
16
+ c: number;
17
+ /** Hue angle in degrees; stored without wrapping or rounding. */
18
+ h: number;
19
+ }
20
+ /** Numeric OKLCH seed coordinates, matching Theme Machine's data model. */
21
+ export interface SeedColor extends OklchColor {
22
+ name?: string;
23
+ }
24
+ export type NormalizedSeedColor = Required<SeedColor>;
25
+ export interface PaletteStep extends OklchColor {
26
+ /** One-based index, from 1 through 16. */
27
+ step: number;
28
+ }
29
+ export interface PaletteDefinition {
30
+ version: 1;
31
+ seedColors: readonly SeedColor[];
32
+ options?: PaletteOptions;
33
+ }
34
+ export interface NormalizedPaletteDefinition {
35
+ version: 1;
36
+ seedColors: NormalizedSeedColor[];
37
+ options: NormalizedPaletteOptions;
38
+ }
39
+ export interface PaletteScale {
40
+ name: string;
41
+ /** One-based step used for the unnumbered custom-property alias. */
42
+ baseStep: number;
43
+ steps: PaletteStep[];
44
+ }
45
+ /** Raw OKLCH coordinates, before output gamut mapping or rounding. */
46
+ export interface Palette {
47
+ version: 1;
48
+ colors: PaletteScale[];
49
+ options: NormalizedPaletteOptions;
50
+ }
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/palette/types.ts"],"names":[],"mappings":"","sourcesContent":["export type LightnessCurve = 'uniform' | 'inclusive' | 'centered';\nexport type ChromaCurve = 'centered' | 'weighted';\nexport type ColorFormat = 'oklch' | 'hex';\nexport type ColorGamut = 'p3' | 'srgb';\n\n// TODO convert to enums?\n// export const LightnessCurveEnum = {\n// UNIFORM: 'uniform',\n// INCLUSIVE: 'inclusive',\n// CENTERED: 'centered',\n// } as const;\n\n// Seed - input l,c,h (and optional name) to generate steps\n// Step - tint/shade of a certain hue\n// Scale - set of 16 steps\n// Palette - full set of colors\n\nexport interface PaletteOptions {\n lightnessCurve?: LightnessCurve;\n chromaCurve?: ChromaCurve;\n format?: ColorFormat;\n gamut?: ColorGamut;\n}\n\nexport type NormalizedPaletteOptions = Required<PaletteOptions>;\n\nexport interface OklchColor {\n /** Lightness from 0 to 1 */\n l: number;\n /** Chroma */\n c: number;\n /** Hue angle in degrees; stored without wrapping or rounding. */\n h: number;\n}\n\n/** Numeric OKLCH seed coordinates, matching Theme Machine's data model. */\nexport interface SeedColor extends OklchColor {\n name?: string;\n}\nexport type NormalizedSeedColor = Required<SeedColor>;\n\nexport interface PaletteStep extends OklchColor {\n /** One-based index, from 1 through 16. */\n step: number;\n}\n\nexport interface PaletteDefinition {\n version: 1;\n seedColors: readonly SeedColor[];\n options?: PaletteOptions;\n}\n\n// PaletteDefinition with all options filled in\nexport interface NormalizedPaletteDefinition {\n version: 1;\n seedColors: NormalizedSeedColor[];\n options: NormalizedPaletteOptions;\n}\n\n// TODO: can baseStep be removed?\n// don't need to output it to CSS any longer, but might need to\n// indicate to user where seedColor landed in the set\nexport interface PaletteScale {\n name: string;\n /** One-based step used for the unnumbered custom-property alias. */\n baseStep: number;\n steps: PaletteStep[];\n}\n\n/** Raw OKLCH coordinates, before output gamut mapping or rounding. */\nexport interface Palette {\n version: 1;\n colors: PaletteScale[];\n options: NormalizedPaletteOptions;\n}\n"]}
@@ -0,0 +1,13 @@
1
+ import type { NormalizedPaletteDefinition, NormalizedPaletteOptions, OklchColor, PaletteDefinition } from './types.ts';
2
+ /**
3
+ * Validate a version-1 definition and return a fresh copy with explicit defaults.
4
+ * Color names must also be unique across all emitted step names and aliases.
5
+ */
6
+ declare function normalizePaletteDefinition(definition: unknown): NormalizedPaletteDefinition;
7
+ declare function normalizeOptions(options?: unknown): NormalizedPaletteOptions;
8
+ declare function checkName(name: unknown, field: string): asserts name is string;
9
+ /** Validate numeric seeds without conversion, wrapping, clamping, or rounding. */
10
+ declare function checkCoordinates(value: Record<string, unknown>, field: string): asserts value is Record<string, unknown> & OklchColor;
11
+ /** Serialize generation inputs, not generated CSS or browser application state. */
12
+ declare function serializePaletteDefinition(definition: PaletteDefinition): string;
13
+ export { normalizePaletteDefinition, serializePaletteDefinition, normalizeOptions, checkName, checkCoordinates, };
@@ -0,0 +1,110 @@
1
+ import { generateName, dedupeNames } from "./generateName.js";
2
+ const OPTION_VALUES = {
3
+ lightnessCurve: ['uniform', 'inclusive', 'centered'],
4
+ chromaCurve: ['centered', 'weighted'],
5
+ format: ['oklch', 'hex'],
6
+ gamut: ['p3', 'srgb'],
7
+ };
8
+ /**
9
+ * Validate a version-1 definition and return a fresh copy with explicit defaults.
10
+ * Color names must also be unique across all emitted step names and aliases.
11
+ */
12
+ function normalizePaletteDefinition(definition) {
13
+ checkObject(definition, 'definition', ['version', 'seedColors', 'options']);
14
+ if (definition.version !== 1) {
15
+ throw new Error('definition.version: expected supported version 1');
16
+ }
17
+ if (!Array.isArray(definition.seedColors) ||
18
+ definition.seedColors.length === 0) {
19
+ throw new Error('definition.seedColors: expected a nonempty array');
20
+ }
21
+ // const names = new Set<string>();
22
+ const entries = definition.seedColors;
23
+ const colors = Array.from(entries, (entry, index) => {
24
+ const field = `definition.seedColors[${index}]`;
25
+ checkObject(entry, field, ['name', 'l', 'c', 'h']);
26
+ checkCoordinates(entry, field);
27
+ if (!entry.name) {
28
+ entry.name = generateName(entry);
29
+ // throw new Error('name ' + entry.name);
30
+ }
31
+ checkName(entry.name, `${field}.name`);
32
+ // for (const name of [
33
+ // entry.name,
34
+ // ...Array.from({ length: 16 }, (_, i) => `${entry.name}-${i + 1}`),
35
+ // ]) {
36
+ // if (names.has(name)) {
37
+ // throw new Error(`${field}.name: duplicate custom property "--${name}"`);
38
+ // }
39
+ // names.add(name);
40
+ // }
41
+ return { name: entry.name, l: entry.l, c: entry.c, h: entry.h };
42
+ });
43
+ return {
44
+ version: 1,
45
+ seedColors: dedupeNames(colors),
46
+ options: normalizeOptions(definition.options),
47
+ };
48
+ }
49
+ function normalizeOptions(options = {}) {
50
+ checkObject(options, 'definition.options', Object.keys(OPTION_VALUES));
51
+ const supplied = options;
52
+ function option(key, fallback) {
53
+ const value = Object.hasOwn(supplied, key) ? supplied[key] : fallback;
54
+ const values = OPTION_VALUES[key];
55
+ if (!values.some((candidate) => candidate === value)) {
56
+ throw new Error(`definition.options.${key}: expected one of ${values.join(', ')}`);
57
+ }
58
+ // Runtime membership validation above establishes the public option union.
59
+ return value;
60
+ }
61
+ const result = {
62
+ lightnessCurve: option('lightnessCurve', 'uniform'),
63
+ chromaCurve: option('chromaCurve', 'centered'),
64
+ format: option('format', 'oklch'),
65
+ gamut: 'p3',
66
+ };
67
+ result.gamut = option('gamut', result.format === 'hex' ? 'srgb' : 'p3');
68
+ if (result.format === 'hex' && result.gamut !== 'srgb') {
69
+ throw new Error('definition.options.gamut: hex output requires srgb');
70
+ }
71
+ return result;
72
+ }
73
+ function checkObject(value, field, keys) {
74
+ if (value === null ||
75
+ typeof value !== 'object' ||
76
+ Array.isArray(value) ||
77
+ ![Object.prototype, null].includes(Object.getPrototypeOf(value))) {
78
+ throw new Error(`${field}: expected a plain object`);
79
+ }
80
+ for (const key of Object.keys(value)) {
81
+ if (!keys.includes(key)) {
82
+ throw new Error(`${field}.${key}: unknown field`);
83
+ }
84
+ }
85
+ }
86
+ function checkName(name, field) {
87
+ if (typeof name !== 'string' ||
88
+ !/^[a-zA-Z][a-zA-Z0-9]*(?:-[a-zA-Z0-9]+)*$/.test(name)) {
89
+ throw new Error(`${field}: expected an alphanumeric name such as "blue" or "BrandPrimary"`);
90
+ }
91
+ }
92
+ /** Validate numeric seeds without conversion, wrapping, clamping, or rounding. */
93
+ function checkCoordinates(value, field) {
94
+ const { l, c, h } = value;
95
+ if (typeof l !== 'number' || !Number.isFinite(l) || l < 0 || l > 1) {
96
+ throw new Error(`${field}.l: expected finite lightness between 0 and 1`);
97
+ }
98
+ if (typeof c !== 'number' || !Number.isFinite(c) || c < 0) {
99
+ throw new Error(`${field}.c: expected finite, nonnegative chroma`);
100
+ }
101
+ if (typeof h !== 'number' || !Number.isFinite(h)) {
102
+ throw new Error(`${field}.h: expected a finite hue angle in degrees`);
103
+ }
104
+ }
105
+ /** Serialize generation inputs, not generated CSS or browser application state. */
106
+ function serializePaletteDefinition(definition) {
107
+ return `${JSON.stringify(normalizePaletteDefinition(definition), null, 2)}\n`;
108
+ }
109
+ export { normalizePaletteDefinition, serializePaletteDefinition, normalizeOptions, checkName, checkCoordinates, };
110
+ //# sourceMappingURL=validation.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"validation.js","s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","sourcesContent":["import { generateName, dedupeNames } from './generateName.ts';\nimport type {\n NormalizedPaletteDefinition,\n NormalizedPaletteOptions,\n OklchColor,\n PaletteDefinition,\n} from './types.ts';\n\nconst OPTION_VALUES = {\n lightnessCurve: ['uniform', 'inclusive', 'centered'],\n chromaCurve: ['centered', 'weighted'],\n format: ['oklch', 'hex'],\n gamut: ['p3', 'srgb'],\n} as const;\n\n/**\n * Validate a version-1 definition and return a fresh copy with explicit defaults.\n * Color names must also be unique across all emitted step names and aliases.\n */\nfunction normalizePaletteDefinition(\n definition: unknown,\n): NormalizedPaletteDefinition {\n checkObject(definition, 'definition', ['version', 'seedColors', 'options']);\n if (definition.version !== 1) {\n throw new Error('definition.version: expected supported version 1');\n }\n if (\n !Array.isArray(definition.seedColors) ||\n definition.seedColors.length === 0\n ) {\n throw new Error('definition.seedColors: expected a nonempty array');\n }\n\n // const names = new Set<string>();\n const entries: unknown[] = definition.seedColors;\n const colors = Array.from(entries, (entry, index) => {\n const field = `definition.seedColors[${index}]`;\n checkObject(entry, field, ['name', 'l', 'c', 'h']);\n checkCoordinates(entry, field);\n if (!entry.name) {\n entry.name = generateName(entry);\n // throw new Error('name ' + entry.name);\n }\n checkName(entry.name, `${field}.name`);\n // for (const name of [\n // entry.name,\n // ...Array.from({ length: 16 }, (_, i) => `${entry.name}-${i + 1}`),\n // ]) {\n // if (names.has(name)) {\n // throw new Error(`${field}.name: duplicate custom property \"--${name}\"`);\n // }\n // names.add(name);\n // }\n return { name: entry.name, l: entry.l, c: entry.c, h: entry.h };\n });\n\n return {\n version: 1,\n seedColors: dedupeNames(colors),\n options: normalizeOptions(definition.options),\n };\n}\n\nfunction normalizeOptions(options: unknown = {}): NormalizedPaletteOptions {\n checkObject(options, 'definition.options', Object.keys(OPTION_VALUES));\n const supplied = options;\n function option<K extends keyof NormalizedPaletteOptions>(\n key: K,\n fallback: NormalizedPaletteOptions[K],\n ): NormalizedPaletteOptions[K] {\n const value = Object.hasOwn(supplied, key) ? supplied[key] : fallback;\n const values = OPTION_VALUES[key];\n if (!values.some((candidate) => candidate === value)) {\n throw new Error(\n `definition.options.${key}: expected one of ${values.join(', ')}`,\n );\n }\n // Runtime membership validation above establishes the public option union.\n return value as NormalizedPaletteOptions[K];\n }\n const result: NormalizedPaletteOptions = {\n lightnessCurve: option('lightnessCurve', 'uniform'),\n chromaCurve: option('chromaCurve', 'centered'),\n format: option('format', 'oklch'),\n gamut: 'p3',\n };\n result.gamut = option('gamut', result.format === 'hex' ? 'srgb' : 'p3');\n if (result.format === 'hex' && result.gamut !== 'srgb') {\n throw new Error('definition.options.gamut: hex output requires srgb');\n }\n return result;\n}\n\nfunction checkObject(\n value: unknown,\n field: string,\n keys: readonly string[],\n): asserts value is Record<string, unknown> {\n if (\n value === null ||\n typeof value !== 'object' ||\n Array.isArray(value) ||\n ![Object.prototype, null].includes(Object.getPrototypeOf(value))\n ) {\n throw new Error(`${field}: expected a plain object`);\n }\n for (const key of Object.keys(value)) {\n if (!keys.includes(key)) {\n throw new Error(`${field}.${key}: unknown field`);\n }\n }\n}\n\nfunction checkName(name: unknown, field: string): asserts name is string {\n if (\n typeof name !== 'string' ||\n !/^[a-zA-Z][a-zA-Z0-9]*(?:-[a-zA-Z0-9]+)*$/.test(name)\n ) {\n throw new Error(\n `${field}: expected an alphanumeric name such as \"blue\" or \"BrandPrimary\"`,\n );\n }\n}\n\n/** Validate numeric seeds without conversion, wrapping, clamping, or rounding. */\nfunction checkCoordinates(\n value: Record<string, unknown>,\n field: string,\n): asserts value is Record<string, unknown> & OklchColor {\n const { l, c, h } = value;\n if (typeof l !== 'number' || !Number.isFinite(l) || l < 0 || l > 1) {\n throw new Error(`${field}.l: expected finite lightness between 0 and 1`);\n }\n if (typeof c !== 'number' || !Number.isFinite(c) || c < 0) {\n throw new Error(`${field}.c: expected finite, nonnegative chroma`);\n }\n if (typeof h !== 'number' || !Number.isFinite(h)) {\n throw new Error(`${field}.h: expected a finite hue angle in degrees`);\n }\n}\n\n/** Serialize generation inputs, not generated CSS or browser application state. */\nfunction serializePaletteDefinition(definition: PaletteDefinition): string {\n return `${JSON.stringify(normalizePaletteDefinition(definition), null, 2)}\\n`;\n}\n\nexport {\n normalizePaletteDefinition,\n serializePaletteDefinition,\n normalizeOptions,\n checkName,\n checkCoordinates,\n};\n"]}
@@ -0,0 +1,4 @@
1
+ import { type PluginCreator } from 'postcss';
2
+ export type ImportOptions = Record<string, never>;
3
+ declare const atImport: PluginCreator<ImportOptions | void>;
4
+ export default atImport;
@@ -0,0 +1,149 @@
1
+ import fs from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ import postcss, {} from 'postcss';
4
+ import { parseImportParams } from "./parseImportParams.js";
5
+ const REMOTE_URI = /^(?:[a-z]+:)?\/\//i;
6
+ const DATA_URI = /^data:/i;
7
+ const atImport = () => ({
8
+ postcssPlugin: 'argot-import',
9
+ async Once(root, { result }) {
10
+ const fromFile = root.source?.input.file ?? result.opts.from;
11
+ if (!fromFile) {
12
+ throw root.error('argot-import requires the PostCSS `from` option (or a file input) so relative @import paths can be resolved');
13
+ }
14
+ const resolvedFrom = path.resolve(fromFile);
15
+ const importedFiles = new Set([resolvedFrom]);
16
+ await processRoot(root, resolvedFrom, [resolvedFrom], importedFiles);
17
+ },
18
+ });
19
+ atImport.postcss = true;
20
+ async function processRoot(root, fromFile, stack, importedFiles) {
21
+ const imports = [];
22
+ root.walkAtRules('import', (atRule) => {
23
+ imports.push(atRule);
24
+ });
25
+ for (const atRule of imports) {
26
+ if (!atRule.parent) {
27
+ // Skip if already detached from the tree
28
+ continue;
29
+ }
30
+ await processImport(atRule, fromFile, stack, importedFiles);
31
+ }
32
+ }
33
+ async function processImport(atRule, fromFile, stack, importedFiles) {
34
+ const importParams = parseImportParams(atRule.params);
35
+ if (!importParams) {
36
+ throw atRule.error(`Invalid @import parameters '${atRule.params}'. ` +
37
+ `Expected a local path or url(), optionally followed by layer, scope, supports, and media conditions.`);
38
+ }
39
+ if (isRemote(importParams.uri)) {
40
+ return;
41
+ }
42
+ const importFile = path.resolve(path.dirname(fromFile), importParams.uri);
43
+ if (stack.includes(importFile)) {
44
+ const chain = [...stack, importFile]
45
+ .map((file) => path.relative(process.cwd(), file) || file)
46
+ .join(' -> ');
47
+ throw atRule.error(`Circular @import: ${chain}`);
48
+ }
49
+ if (importedFiles.has(importFile)) {
50
+ atRule.remove();
51
+ return;
52
+ }
53
+ let css;
54
+ try {
55
+ css = await fs.readFile(importFile, 'utf8');
56
+ }
57
+ catch {
58
+ throw atRule.error(`Failed to find CSS file to import: ${importParams.uri}`, {
59
+ word: importParams.uri,
60
+ });
61
+ }
62
+ importedFiles.add(importFile);
63
+ stack.push(importFile);
64
+ let childRoot;
65
+ try {
66
+ childRoot = postcss.parse(css, { from: importFile });
67
+ await processRoot(childRoot, importFile, stack, importedFiles);
68
+ }
69
+ finally {
70
+ stack.pop();
71
+ }
72
+ replaceImportWithContents(atRule, childRoot.nodes, importParams);
73
+ }
74
+ function replaceImportWithContents(atRule, nodes, importParams) {
75
+ const { layer, scope, supports, media } = importParams;
76
+ let contents = nodes;
77
+ // Nest outside-in as layer → scope → supports → media → content.
78
+ if (media !== undefined) {
79
+ const mediaRule = postcss.atRule({
80
+ name: 'media',
81
+ params: media,
82
+ source: atRule.source,
83
+ });
84
+ prependNewline(contents);
85
+ mediaRule.append(contents);
86
+ contents = [mediaRule];
87
+ }
88
+ if (supports !== undefined) {
89
+ const supportsRule = postcss.atRule({
90
+ name: 'supports',
91
+ params: `(${supports})`,
92
+ source: atRule.source,
93
+ });
94
+ prependNewline(contents);
95
+ supportsRule.append(contents);
96
+ contents = [supportsRule];
97
+ }
98
+ if (scope !== undefined) {
99
+ const scopeRule = postcss.atRule({
100
+ name: 'scope',
101
+ params: scope,
102
+ source: atRule.source,
103
+ });
104
+ prependNewline(contents);
105
+ scopeRule.append(contents);
106
+ contents = [scopeRule];
107
+ }
108
+ if (layer !== undefined) {
109
+ const layerRule = postcss.atRule({
110
+ name: 'layer',
111
+ params: layer,
112
+ source: atRule.source,
113
+ });
114
+ prependNewline(contents);
115
+ layerRule.append(contents);
116
+ contents = [layerRule];
117
+ }
118
+ if (contents.length === 0) {
119
+ atRule.remove();
120
+ return;
121
+ }
122
+ // keep pretty formatting to lint rule isn't triggered by output
123
+ appendNewline(atRule);
124
+ atRule.replaceWith(contents);
125
+ }
126
+ function isRemote(uri) {
127
+ return REMOTE_URI.test(uri) || DATA_URI.test(uri);
128
+ }
129
+ function prependNewline(nodes) {
130
+ if (nodes.length === 0) {
131
+ return;
132
+ }
133
+ nodes[0].raws.before = '\n';
134
+ }
135
+ function appendNewline(atRule) {
136
+ // Space after a node lives on the next sibling's `before`, or the parent's
137
+ // `after` when this is the last child (Root trailing newline / before `}`).
138
+ const next = atRule.next();
139
+ if (next) {
140
+ next.raws.before = `\n${next.raws.before ?? ''}`;
141
+ return;
142
+ }
143
+ const parent = atRule.parent;
144
+ if (parent) {
145
+ parent.raws.after = `\n${parent.raws.after ?? ''}`;
146
+ }
147
+ }
148
+ export default atImport;
149
+ //# sourceMappingURL=atImport.js.map