@ispriter/core 2.0.0

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2014 iazrael.
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a
6
+ copy of this software and associated documentation files (the "Software"),
7
+ to deal in the Software without restriction, including without limitation
8
+ the rights to use, copy, modify, merge, publish, distribute, sublicense,
9
+ and/or sell copies of the Software, and to permit persons to whom the
10
+ Software is furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20
+ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
21
+ DEALINGS IN THE SOFTWARE.
@@ -0,0 +1,111 @@
1
+ // src/packer.ts
2
+ function pack(blocks, margin = 0) {
3
+ if (blocks.length === 0) return { placed: [], unfit: [] };
4
+ const sorted = [...blocks].sort((a, b) => b.width * b.height - a.width * a.height);
5
+ const packerBlocks = sorted.map((b) => ({
6
+ x: 0,
7
+ y: 0,
8
+ w: b.width + margin,
9
+ h: b.height + margin,
10
+ data: b.data
11
+ }));
12
+ const packer = new GrowingPacker();
13
+ packer.fit(packerBlocks);
14
+ const placed = [];
15
+ const unfit = [];
16
+ for (let i = 0; i < packerBlocks.length; i++) {
17
+ const b = packerBlocks[i];
18
+ if (b.fit) {
19
+ placed.push({
20
+ width: b.w - margin,
21
+ height: b.h - margin,
22
+ x: b.fit.x,
23
+ y: b.fit.y,
24
+ rotated: false,
25
+ data: b.data
26
+ });
27
+ } else {
28
+ unfit.push(sorted[i]);
29
+ console.warn(`[ispriter] Image could not be packed (too large): skipping`);
30
+ }
31
+ }
32
+ return { placed, unfit };
33
+ }
34
+ var GrowingPacker = class {
35
+ root;
36
+ fit(blocks) {
37
+ const first = blocks[0];
38
+ this.root = { x: 0, y: 0, w: first.w, h: first.h };
39
+ for (const block of blocks) {
40
+ const node = this.findNode(this.root, block.w, block.h);
41
+ if (node) {
42
+ block.fit = { x: node.x, y: node.y, w: node.w, h: node.h };
43
+ this.splitNode(node, block.w, block.h);
44
+ } else {
45
+ const result = this.growNode(block.w, block.h);
46
+ if (result) {
47
+ block.fit = { x: result.x, y: result.y, w: result.w, h: result.h };
48
+ this.splitNode(result, block.w, block.h);
49
+ }
50
+ }
51
+ }
52
+ }
53
+ findNode(root, w, h) {
54
+ if (root.used) {
55
+ return this.findNode(root.right, w, h) || this.findNode(root.down, w, h);
56
+ }
57
+ if (w <= root.w && h <= root.h) {
58
+ return root;
59
+ }
60
+ return null;
61
+ }
62
+ splitNode(node, w, h) {
63
+ node.used = true;
64
+ node.down = { x: node.x, y: node.y + h, w: node.w, h: node.h - h };
65
+ node.right = { x: node.x + w, y: node.y, w: node.w - w, h };
66
+ }
67
+ growNode(w, h) {
68
+ const canGrowDown = w <= this.root.w;
69
+ const canGrowRight = h <= this.root.h;
70
+ const shouldGrowDown = canGrowDown && this.root.w >= this.root.h;
71
+ const shouldGrowRight = canGrowRight && this.root.h >= this.root.w;
72
+ if (shouldGrowRight) {
73
+ return this.growRight(w, h);
74
+ } else if (shouldGrowDown) {
75
+ return this.growDown(w, h);
76
+ } else if (canGrowRight) {
77
+ return this.growRight(w, h);
78
+ } else if (canGrowDown) {
79
+ return this.growDown(w, h);
80
+ }
81
+ return null;
82
+ }
83
+ growRight(w, h) {
84
+ this.root = {
85
+ used: true,
86
+ x: 0,
87
+ y: 0,
88
+ w: this.root.w + w,
89
+ h: this.root.h,
90
+ down: this.root,
91
+ right: { x: this.root.w, y: 0, w, h: this.root.h }
92
+ };
93
+ return this.findNode(this.root, w, h);
94
+ }
95
+ growDown(w, h) {
96
+ this.root = {
97
+ used: true,
98
+ x: 0,
99
+ y: 0,
100
+ w: this.root.w,
101
+ h: this.root.h + h,
102
+ down: { x: 0, y: this.root.h, w: this.root.w, h },
103
+ right: this.root
104
+ };
105
+ return this.findNode(this.root, w, h);
106
+ }
107
+ };
108
+
109
+ export {
110
+ pack
111
+ };
@@ -0,0 +1,284 @@
1
+ import { ErrorCode } from '@ispriter/shared';
2
+ import { z } from 'zod';
3
+ import { Rule } from 'postcss';
4
+
5
+ declare class IspriterError extends Error {
6
+ readonly code: ErrorCode;
7
+ readonly context?: Record<string, unknown> | undefined;
8
+ constructor(message: string, code: ErrorCode, context?: Record<string, unknown> | undefined);
9
+ }
10
+
11
+ declare const SpriterConfigSchema: z.ZodObject<{
12
+ workspace: z.ZodDefault<z.ZodString>;
13
+ input: z.ZodObject<{
14
+ cssSource: z.ZodUnion<[z.ZodString, z.ZodArray<z.ZodString, "many">]>;
15
+ ignoreImages: z.ZodOptional<z.ZodUnion<[z.ZodString, z.ZodArray<z.ZodString, "many">]>>;
16
+ }, "strip", z.ZodTypeAny, {
17
+ cssSource: string | string[];
18
+ ignoreImages?: string | string[] | undefined;
19
+ }, {
20
+ cssSource: string | string[];
21
+ ignoreImages?: string | string[] | undefined;
22
+ }>;
23
+ output: z.ZodObject<{
24
+ cssDist: z.ZodString;
25
+ imageDist: z.ZodDefault<z.ZodString>;
26
+ format: z.ZodDefault<z.ZodEnum<["png", "webp"]>>;
27
+ quality: z.ZodDefault<z.ZodNumber>;
28
+ retina: z.ZodOptional<z.ZodUnion<[z.ZodLiteral<2>, z.ZodLiteral<3>]>>;
29
+ maxSingleSize: z.ZodOptional<z.ZodNumber>;
30
+ margin: z.ZodDefault<z.ZodNumber>;
31
+ prefix: z.ZodDefault<z.ZodString>;
32
+ compress: z.ZodDefault<z.ZodUnion<[z.ZodBoolean, z.ZodRecord<z.ZodString, z.ZodUnknown>]>>;
33
+ combine: z.ZodDefault<z.ZodBoolean>;
34
+ combineCSSRule: z.ZodDefault<z.ZodBoolean>;
35
+ unit: z.ZodDefault<z.ZodEnum<["px", "rem"]>>;
36
+ remBase: z.ZodDefault<z.ZodNumber>;
37
+ }, "strip", z.ZodTypeAny, {
38
+ cssDist: string;
39
+ imageDist: string;
40
+ format: "png" | "webp";
41
+ quality: number;
42
+ margin: number;
43
+ prefix: string;
44
+ compress: boolean | Record<string, unknown>;
45
+ combine: boolean;
46
+ combineCSSRule: boolean;
47
+ unit: "px" | "rem";
48
+ remBase: number;
49
+ retina?: 2 | 3 | undefined;
50
+ maxSingleSize?: number | undefined;
51
+ }, {
52
+ cssDist: string;
53
+ imageDist?: string | undefined;
54
+ format?: "png" | "webp" | undefined;
55
+ quality?: number | undefined;
56
+ retina?: 2 | 3 | undefined;
57
+ maxSingleSize?: number | undefined;
58
+ margin?: number | undefined;
59
+ prefix?: string | undefined;
60
+ compress?: boolean | Record<string, unknown> | undefined;
61
+ combine?: boolean | undefined;
62
+ combineCSSRule?: boolean | undefined;
63
+ unit?: "px" | "rem" | undefined;
64
+ remBase?: number | undefined;
65
+ }>;
66
+ groups: z.ZodOptional<z.ZodArray<z.ZodObject<{
67
+ name: z.ZodString;
68
+ images: z.ZodUnion<[z.ZodString, z.ZodArray<z.ZodString, "many">]>;
69
+ }, "strip", z.ZodTypeAny, {
70
+ name: string;
71
+ images: string | string[];
72
+ }, {
73
+ name: string;
74
+ images: string | string[];
75
+ }>, "many">>;
76
+ }, "strip", z.ZodTypeAny, {
77
+ workspace: string;
78
+ input: {
79
+ cssSource: string | string[];
80
+ ignoreImages?: string | string[] | undefined;
81
+ };
82
+ output: {
83
+ cssDist: string;
84
+ imageDist: string;
85
+ format: "png" | "webp";
86
+ quality: number;
87
+ margin: number;
88
+ prefix: string;
89
+ compress: boolean | Record<string, unknown>;
90
+ combine: boolean;
91
+ combineCSSRule: boolean;
92
+ unit: "px" | "rem";
93
+ remBase: number;
94
+ retina?: 2 | 3 | undefined;
95
+ maxSingleSize?: number | undefined;
96
+ };
97
+ groups?: {
98
+ name: string;
99
+ images: string | string[];
100
+ }[] | undefined;
101
+ }, {
102
+ input: {
103
+ cssSource: string | string[];
104
+ ignoreImages?: string | string[] | undefined;
105
+ };
106
+ output: {
107
+ cssDist: string;
108
+ imageDist?: string | undefined;
109
+ format?: "png" | "webp" | undefined;
110
+ quality?: number | undefined;
111
+ retina?: 2 | 3 | undefined;
112
+ maxSingleSize?: number | undefined;
113
+ margin?: number | undefined;
114
+ prefix?: string | undefined;
115
+ compress?: boolean | Record<string, unknown> | undefined;
116
+ combine?: boolean | undefined;
117
+ combineCSSRule?: boolean | undefined;
118
+ unit?: "px" | "rem" | undefined;
119
+ remBase?: number | undefined;
120
+ };
121
+ workspace?: string | undefined;
122
+ groups?: {
123
+ name: string;
124
+ images: string | string[];
125
+ }[] | undefined;
126
+ }>;
127
+ type SpriterConfig = z.input<typeof SpriterConfigSchema>;
128
+ type ResolvedConfig = z.output<typeof SpriterConfigSchema>;
129
+ declare function normalizeConfig(input: string | SpriterConfig): SpriterConfig;
130
+ declare function parseConfig(raw: unknown): ResolvedConfig;
131
+
132
+ /** 待打包的图片块 */
133
+ interface PackInput<T = unknown> {
134
+ width: number;
135
+ height: number;
136
+ data: T;
137
+ }
138
+ /** 打包后的定位结果 */
139
+ interface PackResult<T = unknown> {
140
+ width: number;
141
+ height: number;
142
+ x: number;
143
+ y: number;
144
+ rotated: boolean;
145
+ data: T;
146
+ }
147
+ /** 图片资产信息 */
148
+ interface ImageAsset {
149
+ url: string;
150
+ buffer: Buffer;
151
+ naturalWidth: number;
152
+ naturalHeight: number;
153
+ rules: BackgroundRule[];
154
+ }
155
+
156
+ /** CSS background 规则提取结果 */
157
+ interface BackgroundRule {
158
+ file: string;
159
+ selector: string;
160
+ imageUrl: string;
161
+ position: {
162
+ x: number | string;
163
+ y: number | string;
164
+ };
165
+ size?: {
166
+ w: number;
167
+ h: number;
168
+ };
169
+ repeat: string;
170
+ node: Rule;
171
+ inAnimation: boolean;
172
+ }
173
+ /** Spriter.run() 输入 */
174
+ interface SpriterRunInput {
175
+ css: Map<string, string>;
176
+ images: Map<string, Buffer>;
177
+ cssBaseDir: string;
178
+ }
179
+ /** 打包后的精灵图条目 */
180
+ interface PackedSprite {
181
+ spriteFile: string;
182
+ canvasWidth: number;
183
+ canvasHeight: number;
184
+ items: Array<{
185
+ asset: ImageAsset;
186
+ x: number;
187
+ y: number;
188
+ width: number;
189
+ height: number;
190
+ }>;
191
+ }
192
+ /** Spriter.run() 输出 */
193
+ interface SpriterResult {
194
+ cssFiles: Map<string, string>;
195
+ spriteImages: Map<string, Buffer>;
196
+ manifest: Map<string, {
197
+ spriteFile: string;
198
+ x: number;
199
+ y: number;
200
+ width: number;
201
+ height: number;
202
+ }>;
203
+ skippedImages: string[];
204
+ }
205
+
206
+ interface PackOutput<T> {
207
+ placed: PackResult<T>[];
208
+ unfit: PackInput<T>[];
209
+ }
210
+ declare function pack<T>(blocks: PackInput<T>[], margin?: number): PackOutput<T>;
211
+
212
+ /**
213
+ * 从多个 CSS 文件中提取所有 background 规则
214
+ * Fix #15/#18: 自动展开 @import
215
+ */
216
+ declare function extractBackgrounds(cssContents: Map<string, string>): Promise<BackgroundRule[]>;
217
+
218
+ interface ParsedBackground {
219
+ imageUrl: string | null;
220
+ positionX: string | number;
221
+ positionY: string | number;
222
+ repeat: string;
223
+ size: string;
224
+ }
225
+ /**
226
+ * 分析 background 简写属性
227
+ * 提取 url、position、repeat、size
228
+ */
229
+ declare function analyseBackground(value: string): ParsedBackground;
230
+ /**
231
+ * 检查是否应该跳过该规则(right/center/bottom position 或 repeat)
232
+ */
233
+ declare function shouldSkip(parsed: ParsedBackground): boolean;
234
+ /**
235
+ * 清理 URL 中的 hash 和 query string,统一使用 shared cleanUrl
236
+ */
237
+ declare function cleanImageUrl(url: string): string;
238
+ /**
239
+ * 判断是否为 #unsprite 标记
240
+ */
241
+ declare function isUnsprite(url: string): boolean;
242
+
243
+ interface RetinaInfo {
244
+ width: number;
245
+ height: number;
246
+ scale: number;
247
+ }
248
+ /**
249
+ * 更新 CSS 内容:替换 background-image url 和 background-position
250
+ * Fix #8: 支持传入 retinaInfo,自动添加 background-size
251
+ * Fix #12: 支持 combineCSSRule 合并同一精灵图的选择器
252
+ */
253
+ declare function emitCSS(cssContents: Map<string, string>, packedSprites: PackedSprite[], config: ResolvedConfig, retinaInfo?: Map<string, RetinaInfo>): Promise<Map<string, string>>;
254
+
255
+ /**
256
+ * 根据打包结果生成精灵图 Buffer
257
+ */
258
+ declare function generateSprites(packedSprites: PackedSprite[], config: ResolvedConfig): Promise<Map<string, Buffer>>;
259
+
260
+ declare class Spriter {
261
+ private config;
262
+ constructor(config: SpriterConfig);
263
+ run(input: SpriterRunInput): Promise<SpriterResult>;
264
+ private buildSpriteTasks;
265
+ /** B1: Promise.allSettled with error handling */
266
+ private fillImageSizes;
267
+ /** Fix #14: 按 groups 配置分桶 */
268
+ private groupAssets;
269
+ private packSprites;
270
+ /** Fix #13: 按 maxSingleSize 拆分精灵图 */
271
+ private splitByMaxSize;
272
+ private buildManifest;
273
+ }
274
+
275
+ interface PluginRunOptions {
276
+ config: SpriterConfig;
277
+ outputDir: string;
278
+ }
279
+ /**
280
+ * Common sprite generation flow shared by CLI and build plugins.
281
+ */
282
+ declare function runSpriteGeneration(options: PluginRunOptions): Promise<void>;
283
+
284
+ export { type BackgroundRule, type ImageAsset, IspriterError, type PackInput, type PackOutput, type PackResult, type PackedSprite, type PluginRunOptions, type ResolvedConfig, Spriter, type SpriterConfig, SpriterConfigSchema, type SpriterResult, type SpriterRunInput, analyseBackground, cleanImageUrl, emitCSS, extractBackgrounds, generateSprites, isUnsprite, normalizeConfig, pack, parseConfig, runSpriteGeneration, shouldSkip };
package/dist/index.js ADDED
@@ -0,0 +1,658 @@
1
+ import {
2
+ pack
3
+ } from "./chunk-3JTOVWUA.js";
4
+
5
+ // src/error.ts
6
+ var IspriterError = class extends Error {
7
+ constructor(message, code, context) {
8
+ super(message);
9
+ this.code = code;
10
+ this.context = context;
11
+ this.name = "IspriterError";
12
+ }
13
+ code;
14
+ context;
15
+ };
16
+
17
+ // src/config.ts
18
+ import { z } from "zod";
19
+ var SpriterConfigSchema = z.object({
20
+ workspace: z.string().default("./"),
21
+ input: z.object({
22
+ cssSource: z.union([z.string(), z.array(z.string())]),
23
+ ignoreImages: z.union([z.string(), z.array(z.string())]).optional()
24
+ }),
25
+ output: z.object({
26
+ cssDist: z.string(),
27
+ imageDist: z.string().default("./img/"),
28
+ format: z.enum(["png", "webp"]).default("png"),
29
+ quality: z.number().min(1).max(100).default(80),
30
+ retina: z.union([z.literal(2), z.literal(3)]).optional(),
31
+ maxSingleSize: z.number().positive().optional(),
32
+ margin: z.number().nonnegative().default(2),
33
+ prefix: z.string().default("sprite_"),
34
+ compress: z.union([z.boolean(), z.record(z.unknown())]).default(false),
35
+ combine: z.boolean().default(false),
36
+ combineCSSRule: z.boolean().default(true),
37
+ unit: z.enum(["px", "rem"]).default("px"),
38
+ remBase: z.number().positive().default(16)
39
+ }),
40
+ groups: z.array(z.object({
41
+ name: z.string(),
42
+ images: z.union([z.string(), z.array(z.string())])
43
+ })).optional()
44
+ });
45
+ function normalizeConfig(input) {
46
+ if (typeof input === "string") {
47
+ return { input: { cssSource: input }, output: { cssDist: input } };
48
+ }
49
+ return input;
50
+ }
51
+ function parseConfig(raw) {
52
+ if (raw !== null && raw !== void 0 && typeof raw !== "string" && typeof raw !== "object") {
53
+ throw new IspriterError("Config must be a string or object", "CONFIG_INVALID");
54
+ }
55
+ const config = normalizeConfig(raw);
56
+ const result = SpriterConfigSchema.safeParse(config);
57
+ if (!result.success) {
58
+ throw new IspriterError(
59
+ `Invalid config: ${result.error.issues.map((i) => i.message).join(", ")}`,
60
+ "CONFIG_INVALID",
61
+ { issues: result.error.issues }
62
+ );
63
+ }
64
+ validateNoTraversal(result.data.workspace, "workspace");
65
+ validateNoTraversal(result.data.output.cssDist, "output.cssDist");
66
+ validateNoTraversal(result.data.output.imageDist, "output.imageDist");
67
+ return result.data;
68
+ }
69
+ function validateNoTraversal(pathStr, fieldName) {
70
+ if (pathStr.includes("..")) {
71
+ throw new IspriterError(
72
+ `Path traversal detected in ${fieldName}: "${pathStr}"`,
73
+ "CONFIG_INVALID",
74
+ { field: fieldName }
75
+ );
76
+ }
77
+ }
78
+
79
+ // src/css/parser.ts
80
+ import postcss2 from "postcss";
81
+
82
+ // src/css/background.ts
83
+ import { cleanUrl as sharedCleanUrl } from "@ispriter/shared";
84
+ function analyseBackground(value) {
85
+ const result = {
86
+ imageUrl: null,
87
+ positionX: "0",
88
+ positionY: "0",
89
+ repeat: "no-repeat",
90
+ size: ""
91
+ };
92
+ const urlMatch = value.match(/url\(['"]?([^'")]+)['"]?\)/);
93
+ if (urlMatch) {
94
+ result.imageUrl = urlMatch[1];
95
+ }
96
+ if (/\bno-repeat\b/i.test(value)) result.repeat = "no-repeat";
97
+ else if (/\brepeat-x\b/i.test(value)) result.repeat = "repeat-x";
98
+ else if (/\brepeat-y\b/i.test(value)) result.repeat = "repeat-y";
99
+ else if (/\brepeat\b/i.test(value)) result.repeat = "repeat";
100
+ const sizeMatch = value.match(/\/\s*(.+?)(?:\s|$)/);
101
+ if (sizeMatch) {
102
+ result.size = sizeMatch[1].trim();
103
+ }
104
+ if (result.imageUrl) {
105
+ const afterUrl = value.replace(/url\([^)]*\)/, "").trim();
106
+ const posTokens = afterUrl.split(/\s+/).filter((t) => t && !["no-repeat", "repeat", "repeat-x", "repeat-y", "repeat-space"].includes(t)).filter((t) => !t.startsWith("/") && !t.startsWith("#"));
107
+ if (posTokens.length >= 1) {
108
+ result.positionX = parsePositionValue(posTokens[0]);
109
+ }
110
+ if (posTokens.length >= 2) {
111
+ result.positionY = parsePositionValue(posTokens[1]);
112
+ }
113
+ }
114
+ return result;
115
+ }
116
+ function parsePositionValue(val) {
117
+ if (val === "left" || val === "top") return 0;
118
+ if (val === "center") return "center";
119
+ if (val === "right" || val === "bottom") return "100%";
120
+ const pxMatch = val.match(/^(-?\d+(?:\.\d+)?)px$/i);
121
+ if (pxMatch) return Number(pxMatch[1]);
122
+ if (val.endsWith("%")) return val;
123
+ return val;
124
+ }
125
+ function shouldSkip(parsed) {
126
+ if (parsed.repeat === "repeat" || parsed.repeat === "repeat-x" || parsed.repeat === "repeat-y") {
127
+ return true;
128
+ }
129
+ if (parsed.positionX === "100%" || parsed.positionY === "100%") return true;
130
+ if (parsed.positionX === "center" || parsed.positionY === "center") return true;
131
+ if (typeof parsed.positionX === "string" && parsed.positionX.endsWith("%") && parsed.positionX !== "100%") return true;
132
+ if (typeof parsed.positionY === "string" && parsed.positionY.endsWith("%") && parsed.positionY !== "100%") return true;
133
+ return false;
134
+ }
135
+ function cleanImageUrl(url) {
136
+ if (url.length > 4096) return url;
137
+ if (url.includes("#unsprite")) return url;
138
+ return sharedCleanUrl(url);
139
+ }
140
+ function isUnsprite(url) {
141
+ return url.includes("#unsprite");
142
+ }
143
+
144
+ // src/css/imports.ts
145
+ import postcss from "postcss";
146
+ import postcssImport from "postcss-import";
147
+ async function expandImports(css, fromFile) {
148
+ try {
149
+ const result = await postcss([postcssImport()]).process(css, { from: fromFile });
150
+ return result.css;
151
+ } catch (e) {
152
+ throw new IspriterError(
153
+ `Failed to expand @import in ${fromFile}: ${e.message}`,
154
+ "CSS_PARSE_ERROR",
155
+ { file: fromFile }
156
+ );
157
+ }
158
+ }
159
+
160
+ // src/css/parser.ts
161
+ async function extractBackgrounds(cssContents) {
162
+ const rules = [];
163
+ for (const [filename, css] of cssContents) {
164
+ try {
165
+ let expandedCss = css;
166
+ if (css.includes("@import")) {
167
+ try {
168
+ expandedCss = await expandImports(css, filename);
169
+ } catch {
170
+ }
171
+ }
172
+ const root = postcss2.parse(expandedCss);
173
+ processRules(root, filename, false, rules);
174
+ root.walkAtRules(/keyframes/i, (atRule) => {
175
+ if (atRule.nodes) {
176
+ const kfRoot = postcss2.parse(atRule.toString().replace(/@[^{]+\{/, "").replace(/\}$/, ""));
177
+ processRules(kfRoot, filename, true, rules);
178
+ }
179
+ });
180
+ } catch (e) {
181
+ if (e.message?.includes("At-rule")) continue;
182
+ throw e;
183
+ }
184
+ }
185
+ return rules;
186
+ }
187
+ function processRules(root, file, inAnimation, results) {
188
+ root.walkRules((rule) => {
189
+ const bgDecls = [];
190
+ const sizeDecls = [];
191
+ for (const node of rule.nodes) {
192
+ if (node.type === "decl") {
193
+ const decl = node;
194
+ if (decl.prop === "background" || decl.prop === "background-image") {
195
+ bgDecls.push(decl);
196
+ }
197
+ if (decl.prop === "background-size") {
198
+ sizeDecls.push(decl);
199
+ }
200
+ }
201
+ }
202
+ for (const decl of bgDecls) {
203
+ const parsed = analyseBackground(decl.value);
204
+ if (!parsed.imageUrl) continue;
205
+ if (isUnsprite(parsed.imageUrl)) continue;
206
+ const hasSize = sizeDecls.length > 0;
207
+ if (shouldSkip(parsed)) continue;
208
+ const cleanUrl = cleanImageUrl(parsed.imageUrl);
209
+ results.push({
210
+ file,
211
+ selector: rule.selector,
212
+ imageUrl: cleanUrl,
213
+ position: { x: parsed.positionX, y: parsed.positionY },
214
+ repeat: parsed.repeat,
215
+ node: rule,
216
+ inAnimation,
217
+ ...hasSize ? { size: parseSizeDecl(sizeDecls[0]) } : {}
218
+ });
219
+ }
220
+ });
221
+ }
222
+ function parseSizeDecl(decl) {
223
+ const parts = decl.value.split(/\s+/);
224
+ const first = parts[0];
225
+ if (!/^-?\d+(\.\d+)?(px)?$/.test(first)) return void 0;
226
+ const w = parseFloat(first) || 0;
227
+ const hStr = parts[1];
228
+ if (hStr && !/^-?\d+(\.\d+)?(px)?$/.test(hStr)) return void 0;
229
+ const h = hStr ? parseFloat(hStr) || w : w;
230
+ return { w, h };
231
+ }
232
+
233
+ // src/css/emitter.ts
234
+ import postcss3 from "postcss";
235
+ import CleanCSS from "clean-css";
236
+ async function emitCSS(cssContents, packedSprites, config, retinaInfo) {
237
+ const urlToSprite = /* @__PURE__ */ new Map();
238
+ for (const sprite of packedSprites) {
239
+ for (const item of sprite.items) {
240
+ urlToSprite.set(item.asset.url, {
241
+ spriteFile: sprite.spriteFile,
242
+ x: item.x,
243
+ y: item.y,
244
+ w: item.width,
245
+ h: item.height
246
+ });
247
+ }
248
+ }
249
+ const results = /* @__PURE__ */ new Map();
250
+ for (const [filename, css] of cssContents) {
251
+ try {
252
+ const root = postcss3.parse(css);
253
+ const spriteSelectors = /* @__PURE__ */ new Map();
254
+ root.walkRules((rule) => {
255
+ for (const node of rule.nodes) {
256
+ if (node.type === "decl") {
257
+ const decl = node;
258
+ if (decl.prop === "background" || decl.prop === "background-image") {
259
+ const urlMatch = decl.value.match(/url\(['"]?([^'")]+)['"]?\)/);
260
+ if (!urlMatch) continue;
261
+ const originalUrl = cleanImageUrl(urlMatch[1]);
262
+ const mapping = urlToSprite.get(originalUrl);
263
+ if (!mapping) continue;
264
+ const newUrl = `${config.output.imageDist}${mapping.spriteFile}`;
265
+ decl.value = decl.value.replace(urlMatch[0], `url('${newUrl}')`);
266
+ const posX = convertUnit(-mapping.x, config);
267
+ const posY = convertUnit(-mapping.y, config);
268
+ let posDecl;
269
+ for (const n of rule.nodes) {
270
+ if (n.type === "decl" && n.prop === "background-position") {
271
+ posDecl = n;
272
+ break;
273
+ }
274
+ }
275
+ if (posDecl) {
276
+ posDecl.value = `${posX} ${posY}`;
277
+ } else {
278
+ rule.append({ prop: "background-position", value: `${posX} ${posY}` });
279
+ }
280
+ if (retinaInfo) {
281
+ const info = retinaInfo.get(originalUrl);
282
+ if (info) {
283
+ const bgW = convertUnit(Math.round(info.width / info.scale), config);
284
+ const bgH = convertUnit(Math.round(info.height / info.scale), config);
285
+ let sizeDecl;
286
+ for (const n of rule.nodes) {
287
+ if (n.type === "decl" && n.prop === "background-size") {
288
+ sizeDecl = n;
289
+ break;
290
+ }
291
+ }
292
+ if (sizeDecl) {
293
+ sizeDecl.value = `${bgW} ${bgH}`;
294
+ } else {
295
+ rule.append({ prop: "background-size", value: `${bgW} ${bgH}` });
296
+ }
297
+ }
298
+ }
299
+ if (config.output.combineCSSRule) {
300
+ const key = mapping.spriteFile;
301
+ if (!spriteSelectors.has(key)) {
302
+ spriteSelectors.set(key, []);
303
+ }
304
+ spriteSelectors.get(key).push({ rule, decl });
305
+ }
306
+ }
307
+ }
308
+ }
309
+ });
310
+ if (config.output.combineCSSRule) {
311
+ for (const [, entries] of spriteSelectors) {
312
+ if (entries.length <= 1) continue;
313
+ const selectors = entries.map((e) => e.rule.selector);
314
+ const combinedRule = postcss3.rule({ selector: selectors.join(", ") });
315
+ const firstEntry = entries[0];
316
+ const bgImageDecl = firstEntry.decl.clone();
317
+ combinedRule.append(bgImageDecl);
318
+ for (const entry of entries) {
319
+ entry.decl.remove();
320
+ }
321
+ firstEntry.rule.before(combinedRule);
322
+ }
323
+ }
324
+ let output = root.toString();
325
+ if (config.output.compress) {
326
+ const cleaner = new CleanCSS(
327
+ typeof config.output.compress === "object" ? config.output.compress : {}
328
+ );
329
+ const minified = cleaner.minify(output);
330
+ if (minified.errors.length > 0) {
331
+ throw new IspriterError(`CSS compression failed: ${minified.errors.join(", ")}`, "OUTPUT_ERROR");
332
+ }
333
+ output = minified.styles;
334
+ }
335
+ results.set(filename, output);
336
+ } catch (e) {
337
+ if (e instanceof IspriterError) throw e;
338
+ throw new IspriterError(`Failed to emit CSS for ${filename}`, "OUTPUT_ERROR", { file: filename });
339
+ }
340
+ }
341
+ if (config.output.combine && results.size > 1) {
342
+ const combined = Array.from(results.values()).join("\n");
343
+ const combinedName = Array.from(results.keys())[0];
344
+ results.clear();
345
+ results.set(combinedName, combined);
346
+ }
347
+ return results;
348
+ }
349
+ function convertUnit(px, config) {
350
+ if (config.output.unit === "rem") {
351
+ return `${(px / config.output.remBase).toFixed(6).replace(/\.?0+$/, "")}rem`;
352
+ }
353
+ return `${px}px`;
354
+ }
355
+
356
+ // src/image/sprite.ts
357
+ import sharp from "sharp";
358
+ async function generateSprites(packedSprites, config) {
359
+ const results = /* @__PURE__ */ new Map();
360
+ for (const sprite of packedSprites) {
361
+ try {
362
+ const { canvasWidth, canvasHeight, items } = sprite;
363
+ const canvas = sharp({
364
+ create: {
365
+ width: canvasWidth,
366
+ height: canvasHeight,
367
+ channels: 4,
368
+ background: { r: 0, g: 0, b: 0, alpha: 0 }
369
+ }
370
+ });
371
+ const composites = await Promise.all(items.map(async (item) => {
372
+ let inputBuf = item.asset.buffer;
373
+ if (item.width !== item.asset.naturalWidth || item.height !== item.asset.naturalHeight) {
374
+ inputBuf = await sharp(item.asset.buffer).resize(item.width, item.height, { fit: "fill" }).toBuffer();
375
+ }
376
+ return { input: inputBuf, left: item.x, top: item.y };
377
+ }));
378
+ let output = canvas.composite(composites);
379
+ if (config.output.format === "webp") {
380
+ output = output.webp({ quality: config.output.quality });
381
+ } else {
382
+ output = output.png();
383
+ }
384
+ const buffer = await output.toBuffer();
385
+ results.set(sprite.spriteFile, buffer);
386
+ } catch (e) {
387
+ if (e instanceof IspriterError) throw e;
388
+ throw new IspriterError(`Failed to generate sprite: ${sprite.spriteFile}: ${e.message}`, "OUTPUT_ERROR", {
389
+ spriteFile: sprite.spriteFile,
390
+ cause: e
391
+ });
392
+ }
393
+ }
394
+ return results;
395
+ }
396
+
397
+ // src/spriter.ts
398
+ import { matchesAny } from "@ispriter/shared";
399
+ import sharp2 from "sharp";
400
+ var Spriter = class {
401
+ config;
402
+ constructor(config) {
403
+ this.config = parseConfig(config);
404
+ }
405
+ async run(input) {
406
+ const { css, images } = input;
407
+ const rules = await extractBackgrounds(css);
408
+ const { assets, skipped } = this.buildSpriteTasks(rules, images);
409
+ await this.fillImageSizes(assets);
410
+ const assetGroups = this.groupAssets(assets);
411
+ const allPackedSprites = [];
412
+ for (let gi = 0; gi < assetGroups.length; gi++) {
413
+ const group = assetGroups[gi];
414
+ const packed = this.packSprites(group, gi);
415
+ allPackedSprites.push(...packed);
416
+ }
417
+ const finalSprites = this.splitByMaxSize(allPackedSprites);
418
+ const spriteImages = await generateSprites(finalSprites, this.config);
419
+ let retinaInfo;
420
+ if (this.config.output.retina) {
421
+ const { generateRetinaSprites } = await import("./retina-NHUTNCL6.js");
422
+ const scale = this.config.output.retina;
423
+ const { packedSprites: retinaPacked, scaledAssets } = await generateRetinaSprites(
424
+ assets,
425
+ this.config,
426
+ scale
427
+ );
428
+ const retinaImages = await generateSprites(retinaPacked, this.config);
429
+ for (const [name, buf] of retinaImages) {
430
+ spriteImages.set(name, buf);
431
+ }
432
+ retinaInfo = /* @__PURE__ */ new Map();
433
+ for (const [url, dims] of scaledAssets) {
434
+ retinaInfo.set(url, { width: dims.width, height: dims.height, scale });
435
+ }
436
+ }
437
+ const cssFiles = await emitCSS(css, finalSprites, this.config, retinaInfo);
438
+ const manifest = this.buildManifest(finalSprites);
439
+ return { cssFiles, spriteImages, manifest, skippedImages: skipped };
440
+ }
441
+ buildSpriteTasks(rules, images) {
442
+ const assetMap = /* @__PURE__ */ new Map();
443
+ const skipped = [];
444
+ const ignorePatterns = this.config.input.ignoreImages ? Array.isArray(this.config.input.ignoreImages) ? this.config.input.ignoreImages : [this.config.input.ignoreImages] : [];
445
+ for (const rule of rules) {
446
+ const url = rule.imageUrl;
447
+ if (ignorePatterns.length > 0 && matchesAny(ignorePatterns, url)) {
448
+ continue;
449
+ }
450
+ if (assetMap.has(url)) {
451
+ assetMap.get(url).rules.push(rule);
452
+ continue;
453
+ }
454
+ const buffer = images.get(url);
455
+ if (!buffer) {
456
+ skipped.push(url);
457
+ continue;
458
+ }
459
+ assetMap.set(url, {
460
+ url,
461
+ buffer,
462
+ naturalWidth: 0,
463
+ naturalHeight: 0,
464
+ rules: [rule]
465
+ });
466
+ }
467
+ return { assets: Array.from(assetMap.values()), skipped };
468
+ }
469
+ /** B1: Promise.allSettled with error handling */
470
+ async fillImageSizes(assets) {
471
+ const results = await Promise.allSettled(
472
+ assets.map(async (asset) => {
473
+ const meta = await sharp2(asset.buffer).metadata();
474
+ return { asset, width: meta.width || 0, height: meta.height || 0 };
475
+ })
476
+ );
477
+ for (const result of results) {
478
+ if (result.status === "fulfilled") {
479
+ result.value.asset.naturalWidth = result.value.width;
480
+ result.value.asset.naturalHeight = result.value.height;
481
+ } else {
482
+ console.warn(`Failed to read image metadata: ${result.reason}`);
483
+ }
484
+ }
485
+ }
486
+ /** Fix #14: 按 groups 配置分桶 */
487
+ groupAssets(assets) {
488
+ const groups = this.config.groups;
489
+ if (!groups || groups.length === 0) {
490
+ return [assets];
491
+ }
492
+ const buckets = groups.map(() => []);
493
+ const assigned = /* @__PURE__ */ new Set();
494
+ for (let gi = 0; gi < groups.length; gi++) {
495
+ const group = groups[gi];
496
+ const patterns = Array.isArray(group.images) ? group.images : [group.images];
497
+ for (const asset of assets) {
498
+ if (assigned.has(asset.url)) continue;
499
+ if (matchesAny(patterns, asset.url)) {
500
+ buckets[gi].push(asset);
501
+ assigned.add(asset.url);
502
+ }
503
+ }
504
+ }
505
+ const lastBucket = buckets[buckets.length - 1];
506
+ for (const asset of assets) {
507
+ if (!assigned.has(asset.url)) {
508
+ lastBucket.push(asset);
509
+ }
510
+ }
511
+ return buckets.filter((b) => b.length > 0);
512
+ }
513
+ packSprites(assets, groupIndex = 0) {
514
+ if (assets.length === 0) return [];
515
+ const inputs = assets.map((a) => ({
516
+ width: a.naturalWidth,
517
+ height: a.naturalHeight,
518
+ data: a
519
+ }));
520
+ const { placed: results, unfit } = pack(inputs, this.config.output.margin);
521
+ if (unfit.length > 0) {
522
+ console.warn(`[ispriter] ${unfit.length} image(s) could not be packed and were skipped`);
523
+ }
524
+ if (results.length === 0) return [];
525
+ const spriteFile = `${this.config.output.prefix}${groupIndex}.${this.config.output.format === "webp" ? "webp" : "png"}`;
526
+ return [
527
+ {
528
+ spriteFile,
529
+ canvasWidth: results.reduce((max, r) => Math.max(max, r.x + r.width), 0),
530
+ canvasHeight: results.reduce((max, r) => Math.max(max, r.y + r.height), 0),
531
+ items: results.map((r) => ({
532
+ asset: r.data,
533
+ x: r.x,
534
+ y: r.y,
535
+ width: r.width,
536
+ height: r.height
537
+ }))
538
+ }
539
+ ];
540
+ }
541
+ /** Fix #13: 按 maxSingleSize 拆分精灵图 */
542
+ splitByMaxSize(sprites) {
543
+ const maxSize = this.config.output.maxSingleSize;
544
+ if (!maxSize) return sprites;
545
+ const maxBytes = maxSize * 1024;
546
+ const result = [];
547
+ for (const sprite of sprites) {
548
+ const estimatedSize = sprite.canvasWidth * sprite.canvasHeight * 4;
549
+ if (estimatedSize <= maxBytes) {
550
+ result.push(sprite);
551
+ continue;
552
+ }
553
+ const mid = Math.ceil(sprite.items.length / 2);
554
+ const chunks = [sprite.items.slice(0, mid), sprite.items.slice(mid)];
555
+ for (let ci = 0; ci < chunks.length; ci++) {
556
+ const items = chunks[ci];
557
+ if (items.length === 0) continue;
558
+ const ext = this.config.output.format === "webp" ? "webp" : "png";
559
+ const baseName = sprite.spriteFile.replace(`.${ext}`, "");
560
+ const newFile = `${baseName}_part${ci}.${ext}`;
561
+ result.push({
562
+ spriteFile: newFile,
563
+ canvasWidth: items.reduce((max, it) => Math.max(max, it.x + it.width), 0),
564
+ canvasHeight: items.reduce((max, it) => Math.max(max, it.y + it.height), 0),
565
+ items
566
+ });
567
+ }
568
+ }
569
+ return result;
570
+ }
571
+ buildManifest(packedSprites) {
572
+ const manifest = /* @__PURE__ */ new Map();
573
+ for (const sprite of packedSprites) {
574
+ for (const item of sprite.items) {
575
+ manifest.set(item.asset.url, {
576
+ spriteFile: sprite.spriteFile,
577
+ x: item.x,
578
+ y: item.y,
579
+ width: item.width,
580
+ height: item.height
581
+ });
582
+ }
583
+ }
584
+ return manifest;
585
+ }
586
+ };
587
+
588
+ // src/plugin-helper.ts
589
+ import { readFile, writeFile, mkdir } from "fs/promises";
590
+ import { glob } from "fs/promises";
591
+ import path from "path";
592
+ async function runSpriteGeneration(options) {
593
+ const { config, outputDir } = options;
594
+ const resolved = parseConfig(config);
595
+ const cssSource = Array.isArray(resolved.input.cssSource) ? resolved.input.cssSource : [resolved.input.cssSource];
596
+ const cssFiles = /* @__PURE__ */ new Map();
597
+ for (const pattern of cssSource) {
598
+ const absPattern = path.resolve(outputDir, pattern);
599
+ try {
600
+ const matches = await Array.fromAsync(glob(absPattern));
601
+ for (const file of matches) {
602
+ if (!file.endsWith(".css")) continue;
603
+ const content = await readFile(file, "utf-8");
604
+ cssFiles.set(file, content);
605
+ }
606
+ } catch {
607
+ }
608
+ }
609
+ if (cssFiles.size === 0) return;
610
+ const rules = await extractBackgrounds(cssFiles);
611
+ const imageUrls = /* @__PURE__ */ new Set();
612
+ for (const rule of rules) {
613
+ imageUrls.add(rule.imageUrl);
614
+ }
615
+ const images = /* @__PURE__ */ new Map();
616
+ const allowedDir = path.resolve(outputDir);
617
+ for (const url of imageUrls) {
618
+ if (url.startsWith("data:") || url.startsWith("http")) continue;
619
+ if (url.length > 4096) continue;
620
+ for (const [cssFile] of cssFiles) {
621
+ const absPath = path.resolve(path.dirname(cssFile), url);
622
+ if (!absPath.startsWith(allowedDir)) continue;
623
+ try {
624
+ if (!images.has(url)) {
625
+ images.set(url, await readFile(absPath));
626
+ }
627
+ } catch {
628
+ }
629
+ }
630
+ }
631
+ const spriter = new Spriter(config);
632
+ const result = await spriter.run({ css: cssFiles, images, cssBaseDir: outputDir });
633
+ const cssDist = path.resolve(outputDir, resolved.output.cssDist);
634
+ const imgDist = path.resolve(cssDist, resolved.output.imageDist);
635
+ await mkdir(imgDist, { recursive: true });
636
+ for (const [name, buf] of result.spriteImages) {
637
+ await writeFile(path.join(imgDist, name), buf);
638
+ }
639
+ for (const [name, content] of result.cssFiles) {
640
+ await writeFile(path.join(cssDist, path.basename(name)), content);
641
+ }
642
+ }
643
+ export {
644
+ IspriterError,
645
+ Spriter,
646
+ SpriterConfigSchema,
647
+ analyseBackground,
648
+ cleanImageUrl,
649
+ emitCSS,
650
+ extractBackgrounds,
651
+ generateSprites,
652
+ isUnsprite,
653
+ normalizeConfig,
654
+ pack,
655
+ parseConfig,
656
+ runSpriteGeneration,
657
+ shouldSkip
658
+ };
@@ -0,0 +1,83 @@
1
+ import {
2
+ pack
3
+ } from "./chunk-3JTOVWUA.js";
4
+
5
+ // src/image/retina.ts
6
+ import sharp from "sharp";
7
+ function matchRetinaImages(assets, scale) {
8
+ const retinaMap = /* @__PURE__ */ new Map();
9
+ const standard = [];
10
+ for (const asset of assets) {
11
+ const retinaSuffix = `@${scale}x`;
12
+ const match = asset.url.match(/^(.+?)(@\dx)(\.\w+)$/);
13
+ if (match && match[2] === retinaSuffix) {
14
+ retinaMap.set(match[1] + match[3], asset);
15
+ } else if (!asset.url.includes("@2x") && !asset.url.includes("@3x")) {
16
+ standard.push(asset);
17
+ }
18
+ }
19
+ return { standard, retina: retinaMap };
20
+ }
21
+ async function generateRetinaSprites(assets, config, scale) {
22
+ const scaledAssets = /* @__PURE__ */ new Map();
23
+ const retinaMatch = matchRetinaImages(assets, scale);
24
+ const preparedAssets = [];
25
+ for (const asset of assets) {
26
+ if (asset.url.includes("@2x") || asset.url.includes("@3x")) continue;
27
+ const retinaAsset = retinaMatch.retina.get(asset.url);
28
+ let buffer;
29
+ let width;
30
+ let height;
31
+ if (retinaAsset) {
32
+ buffer = retinaAsset.buffer;
33
+ width = retinaAsset.naturalWidth;
34
+ height = retinaAsset.naturalHeight;
35
+ } else {
36
+ const scaledWidth = asset.naturalWidth * scale;
37
+ const scaledHeight = asset.naturalHeight * scale;
38
+ buffer = await sharp(asset.buffer).resize(scaledWidth, scaledHeight, { fit: "fill" }).toBuffer();
39
+ width = scaledWidth;
40
+ height = scaledHeight;
41
+ }
42
+ preparedAssets.push({
43
+ ...asset,
44
+ buffer,
45
+ naturalWidth: width,
46
+ naturalHeight: height
47
+ });
48
+ scaledAssets.set(asset.url, { width, height });
49
+ }
50
+ const inputs = preparedAssets.map((a) => ({
51
+ width: a.naturalWidth,
52
+ height: a.naturalHeight,
53
+ data: a
54
+ }));
55
+ const { placed: packedResults, unfit } = pack(inputs, config.output.margin * scale);
56
+ if (unfit.length > 0) {
57
+ console.warn(`[ispriter] ${unfit.length} retina image(s) could not be packed`);
58
+ }
59
+ if (packedResults.length === 0) {
60
+ return { packedSprites: [], scaledAssets };
61
+ }
62
+ const ext = config.output.format === "webp" ? "webp" : "png";
63
+ const spriteFile = `${config.output.prefix}retina_${scale}x.${ext}`;
64
+ const canvasWidth = packedResults.reduce((max, r) => Math.max(max, r.x + r.width), 0);
65
+ const canvasHeight = packedResults.reduce((max, r) => Math.max(max, r.y + r.height), 0);
66
+ const packedSprite = {
67
+ spriteFile,
68
+ canvasWidth,
69
+ canvasHeight,
70
+ items: packedResults.map((r) => ({
71
+ asset: r.data,
72
+ x: r.x,
73
+ y: r.y,
74
+ width: r.width,
75
+ height: r.height
76
+ }))
77
+ };
78
+ return { packedSprites: [packedSprite], scaledAssets };
79
+ }
80
+ export {
81
+ generateRetinaSprites,
82
+ matchRetinaImages
83
+ };
package/package.json ADDED
@@ -0,0 +1,40 @@
1
+ {
2
+ "name": "@ispriter/core",
3
+ "version": "2.0.0",
4
+ "type": "module",
5
+ "main": "./dist/index.js",
6
+ "types": "./dist/index.d.ts",
7
+ "exports": {
8
+ ".": {
9
+ "import": "./dist/index.js",
10
+ "types": "./dist/index.d.ts"
11
+ }
12
+ },
13
+ "dependencies": {
14
+ "clean-css": "^5.3.0",
15
+ "postcss": "^8.5.0",
16
+ "postcss-import": "^16.1.1",
17
+ "sharp": "^0.33.0",
18
+ "zod": "^3.24.0",
19
+ "@ispriter/shared": "2.0.0"
20
+ },
21
+ "devDependencies": {
22
+ "@types/clean-css": "^4.2.0",
23
+ "tsup": "^8.4.0",
24
+ "vitest": "^3.1.0"
25
+ },
26
+ "files": [
27
+ "dist"
28
+ ],
29
+ "engines": {
30
+ "node": ">=20.0.0"
31
+ },
32
+ "publishConfig": {
33
+ "access": "public"
34
+ },
35
+ "scripts": {
36
+ "build": "tsup",
37
+ "dev": "tsup --watch",
38
+ "test": "vitest run"
39
+ }
40
+ }