@wcstack/state 1.27.0 → 1.28.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.
@@ -0,0 +1,1452 @@
1
+ const DELIMITER = '.';
2
+ const WILDCARD = '*';
3
+ const MAX_WILDCARD_DEPTH = 128;
4
+ // data-wcs バインディング構文 `[prop][#mod]: [path][@state][|filter...]` の区切り文字(単一正本)。
5
+ // これらは「死守の壁(構文契約)」であり値は不変。manifest.syntax.delimiters で公開される。
6
+ const BINDING_SEPARATOR = ';'; // 複数バインディングの区切り
7
+ const PROP_VALUE_SEPARATOR = ':'; // 左辺(prop)と右辺(path)の区切り
8
+ const MODIFIER_SEPARATOR = '#'; // prop と修飾子の区切り
9
+ const STATE_NAME_SEPARATOR = '@'; // path と @stateName の区切り
10
+ const FILTER_SEPARATOR = '|'; // フィルタパイプの区切り
11
+ // bindingType 判別と左辺 namespace の語彙(単一正本)。manifest.syntax.bindingTypes で
12
+ // 公開される。パーサ(parseBindTextsForElement)とイベント層はこの定数に分岐する。
13
+ // apply 層のディスパッチマップ(apply/applyChange.ts の applyChangeByFirstSegment)の
14
+ // キー集合との一致は __tests__/manifest.test.ts の drift テストが強制する —
15
+ // manifest エントリ(DOM 非依存)から apply 層を import しないための分離。
16
+ const ELSE_KEYWORD = 'else';
17
+ const SPREAD_PROP = '...';
18
+ const EVENT_PROP_PREFIX = 'on';
19
+ const EVENT_TOKEN_NAMESPACE = 'eventToken';
20
+ // リストインデックス参照名(`$1`..`$N`)の接頭辞(単一正本)。
21
+ // manifest.syntax.indexParam で公開される。
22
+ const INDEX_PARAM_PREFIX = '$';
23
+ /**
24
+ * stackIndexByIndexName
25
+ * インデックス名からスタックインデックスへのマッピング
26
+ * $1 => 0
27
+ * $2 => 1
28
+ * :
29
+ * ${i + 1} => i
30
+ * i < MAX_WILDCARD_DEPTH
31
+ */
32
+ const tmpIndexByIndexName = {};
33
+ for (let i = 0; i < MAX_WILDCARD_DEPTH; i++) {
34
+ tmpIndexByIndexName[`${INDEX_PARAM_PREFIX}${i + 1}`] = i;
35
+ }
36
+ Object.freeze(tmpIndexByIndexName);
37
+
38
+ const _cache = new Map();
39
+ let id = 0;
40
+ function getPathInfo(path) {
41
+ let pathInfo = _cache.get(path);
42
+ if (typeof pathInfo !== "undefined") {
43
+ return pathInfo;
44
+ }
45
+ pathInfo = Object.freeze(new PathInfo(path));
46
+ _cache.set(path, pathInfo);
47
+ return pathInfo;
48
+ }
49
+ class PathInfo {
50
+ id = ++id;
51
+ path;
52
+ segments;
53
+ lastSegment;
54
+ cumulativePaths;
55
+ cumulativePathSet;
56
+ cumulativePathInfos;
57
+ cumulativePathInfoSet;
58
+ parentPath;
59
+ wildcardPaths;
60
+ wildcardPathSet;
61
+ indexByWildcardPath;
62
+ wildcardPathInfos;
63
+ wildcardPathInfoSet;
64
+ wildcardParentPaths;
65
+ wildcardParentPathSet;
66
+ wildcardParentPathInfos;
67
+ wildcardParentPathInfoSet;
68
+ wildcardPositions;
69
+ lastWildcardPath;
70
+ lastWildcardInfo;
71
+ wildcardCount;
72
+ parentPathInfo;
73
+ constructor(path) {
74
+ // Helper to get or create StructuredPathInfo instances, avoiding redundant creation for self-reference
75
+ const getPattern = (_path) => {
76
+ return (path === _path) ? this : getPathInfo(_path);
77
+ };
78
+ // Split the pattern into individual path segments (e.g., "items.*.name" → ["items", "*", "name"])
79
+ const segments = path.split(".");
80
+ // Arrays to track all cumulative paths from root to each segment
81
+ const cumulativePaths = [];
82
+ const cumulativePathInfos = [];
83
+ // Arrays to track wildcard-specific information
84
+ const wildcardPaths = [];
85
+ const indexByWildcardPath = {}; // Maps wildcard path to its index position
86
+ const wildcardPathInfos = [];
87
+ const wildcardParentPaths = []; // Paths of parent segments for each wildcard
88
+ const wildcardParentPathInfos = [];
89
+ const wildcardPositions = [];
90
+ let currentPatternPath = "", prevPatternPath = "";
91
+ let wildcardCount = 0;
92
+ // Iterate through each segment to build cumulative paths and identify wildcards
93
+ for (let i = 0; i < segments.length; i++) {
94
+ currentPatternPath += segments[i];
95
+ // If this segment is a wildcard, track it with all wildcard-specific metadata
96
+ if (segments[i] === WILDCARD) {
97
+ wildcardPaths.push(currentPatternPath);
98
+ indexByWildcardPath[currentPatternPath] = wildcardCount; // Store wildcard's ordinal position
99
+ wildcardPathInfos.push(getPattern(currentPatternPath));
100
+ wildcardParentPaths.push(prevPatternPath); // Parent path is the previous cumulative path
101
+ wildcardParentPathInfos.push(getPattern(prevPatternPath));
102
+ wildcardPositions.push(i);
103
+ wildcardCount++;
104
+ }
105
+ // Track all cumulative paths for hierarchical navigation (e.g., "items", "items.*", "items.*.name")
106
+ cumulativePaths.push(currentPatternPath);
107
+ cumulativePathInfos.push(getPattern(currentPatternPath));
108
+ // Save current path as previous for next iteration, then add separator
109
+ prevPatternPath = currentPatternPath;
110
+ currentPatternPath += ".";
111
+ }
112
+ // Determine the deepest (last) wildcard path and the parent path of the entire pattern
113
+ const lastWildcardPath = wildcardPaths.length > 0 ? wildcardPaths[wildcardPaths.length - 1] : null;
114
+ const parentPath = cumulativePaths.length > 1 ? cumulativePaths[cumulativePaths.length - 2] : null;
115
+ // Assign all analyzed data to readonly properties
116
+ this.path = path;
117
+ this.segments = segments;
118
+ this.lastSegment = segments[segments.length - 1];
119
+ this.cumulativePaths = cumulativePaths;
120
+ this.cumulativePathSet = new Set(cumulativePaths); // Set for fast lookup
121
+ this.cumulativePathInfos = cumulativePathInfos;
122
+ this.cumulativePathInfoSet = new Set(cumulativePathInfos);
123
+ this.wildcardPaths = wildcardPaths;
124
+ this.wildcardPathSet = new Set(wildcardPaths);
125
+ this.indexByWildcardPath = indexByWildcardPath;
126
+ this.wildcardPathInfos = wildcardPathInfos;
127
+ this.wildcardPathInfoSet = new Set(wildcardPathInfos);
128
+ this.wildcardParentPaths = wildcardParentPaths;
129
+ this.wildcardParentPathSet = new Set(wildcardParentPaths);
130
+ this.wildcardParentPathInfos = wildcardParentPathInfos;
131
+ this.wildcardParentPathInfoSet = new Set(wildcardParentPathInfos);
132
+ this.wildcardPositions = wildcardPositions;
133
+ this.lastWildcardPath = lastWildcardPath;
134
+ this.lastWildcardInfo = lastWildcardPath ? getPattern(lastWildcardPath) : null;
135
+ this.parentPath = parentPath;
136
+ this.parentPathInfo = parentPath ? getPattern(parentPath) : null;
137
+ this.wildcardCount = wildcardCount;
138
+ }
139
+ }
140
+
141
+ function raiseError(message) {
142
+ throw new Error(`[@wcstack/state] ${message}`);
143
+ }
144
+
145
+ const STRUCTURAL_BINDING_TYPE_SET = new Set([
146
+ "if",
147
+ "elseif",
148
+ "else",
149
+ "for",
150
+ ]);
151
+
152
+ const _config = {
153
+ locale: 'en'};
154
+ // backward compatible export (read-only usage)
155
+ const config = _config;
156
+
157
+ /**
158
+ * errorGuidance.ts — エラーメッセージへの self-fix 誘導(GTM 2-5 /
159
+ * docs/static-wiring-dx-design.md §3)。
160
+ *
161
+ * コンソールは「書き手(人間・AI とも)が誤った瞬間に必ず読む面」なので、
162
+ * (a) did-you-mean 候補 (b) lint への誘導 をエラーメッセージ自体に埋め込む。
163
+ * ここの関数は全て**エラーパスでのみ**呼ばれる — 正常系のコストはゼロ。
164
+ * auto.min.js に同梱されるため文字列は最小限に保つ(エラーパス専用モジュールの
165
+ * 遅延 import は `src/auto.ts` の SRI 自己完結制約で不可)。
166
+ *
167
+ * 診断 code の語彙はコンソール → lint → IDE の三面で共有する:
168
+ * メッセージ先頭の `[wcs/...]` は wcstack-intellisense / @wcstack/lint の
169
+ * 安定診断 code(packages/vscode-wcs/src/core/diagnostics.ts)と同一。
170
+ */
171
+ /** 挿入・削除・置換の編集距離。長さ差が max を超えたら早期に max+1 を返す。 */
172
+ function editDistance(a, b, max) {
173
+ if (Math.abs(a.length - b.length) > max) {
174
+ return max + 1;
175
+ }
176
+ const prev = new Array(b.length + 1);
177
+ const curr = new Array(b.length + 1);
178
+ for (let j = 0; j <= b.length; j++) {
179
+ prev[j] = j;
180
+ }
181
+ for (let i = 1; i <= a.length; i++) {
182
+ curr[0] = i;
183
+ for (let j = 1; j <= b.length; j++) {
184
+ const cost = a[i - 1] === b[j - 1] ? 0 : 1;
185
+ curr[j] = Math.min(prev[j] + 1, curr[j - 1] + 1, prev[j - 1] + cost);
186
+ }
187
+ for (let j = 0; j <= b.length; j++) {
188
+ prev[j] = curr[j];
189
+ }
190
+ }
191
+ return prev[b.length];
192
+ }
193
+ /**
194
+ * 候補集合から編集距離 2 以内の最近傍を探し、` Did you mean "<best>"?` を返す。
195
+ * 該当なしは空文字。規準(距離 2・同距離は先勝ち・大小文字は畳んで比較)は
196
+ * lint の did-you-mean(ioNodeValidator の suggestion)と同じ — 三面で提案が
197
+ * 割れないように揃えている。動的キー等で候補が列挙できないサイトでは呼ばない
198
+ * = 誘導文のみに縮退(設計 §3 の縮退)。
199
+ */
200
+ function didYouMean(input, candidates) {
201
+ // 空入力(`a|` の末尾パイプ等)に短い候補を提案しても無意味なので出さない。
202
+ if (input.length === 0) {
203
+ return "";
204
+ }
205
+ const folded = input.toLowerCase();
206
+ let best = null;
207
+ let bestDistance = 3;
208
+ for (const candidate of candidates) {
209
+ const distance = editDistance(folded, candidate.toLowerCase(), 2);
210
+ if (distance < bestDistance) {
211
+ best = candidate;
212
+ bestDistance = distance;
213
+ }
214
+ }
215
+ return best !== null ? ` Did you mean "${best}"?` : "";
216
+ }
217
+ /**
218
+ * lint への誘導(誘導付きメッセージ共通の一文)。
219
+ * **lint が実際にそのケースを検出するサイトにだけ付ける** — 検出しないケースに
220
+ * 付けると「エラー → lint 実行 → clean」の空振りで検証ループの信頼を毀損する
221
+ * (DCC 宣言・watch の一部 shape・構造型単独バインディング違反は lint 未検出のため
222
+ * 付けない。lint 側への検査追加は follow-up)。
223
+ */
224
+ const LINT_HINT = " Validate statically: npx @wcstack/lint <file>.";
225
+
226
+ /**
227
+ * errorMessages.ts
228
+ *
229
+ * Error message generation utilities used by filter functions.
230
+ *
231
+ * Main responsibilities:
232
+ * - Throws clear error messages when filter options or value type checks fail
233
+ * - Takes function name as argument to specify which filter caused the error
234
+ *
235
+ * Design points:
236
+ * - optionsRequired: Error when required option is not specified
237
+ * - optionMustBeNumber: Error when option value is not a number
238
+ * - valueMustBeNumber: Error when value is not a number
239
+ * - valueMustBeBoolean: Error when value is not boolean
240
+ * - valueMustBeDate: Error when value is not a Date
241
+ */
242
+ /**
243
+ * Throws error when filter requires at least one option but none provided.
244
+ *
245
+ * @param fnName - Name of the filter function
246
+ * @returns Never returns (always throws)
247
+ */
248
+ function optionsRequired(fnName) {
249
+ raiseError(`filter ${fnName} requires at least one option`);
250
+ }
251
+ /**
252
+ * Throws error when filter option must be a number but invalid value provided.
253
+ *
254
+ * @param fnName - Name of the filter function
255
+ * @returns Never returns (always throws)
256
+ */
257
+ function optionMustBeNumber(fnName) {
258
+ raiseError(`filter ${fnName} requires a number as option`);
259
+ }
260
+ /**
261
+ * Throws error when filter requires numeric value but non-number provided.
262
+ *
263
+ * @param fnName - Name of the filter function
264
+ * @returns Never returns (always throws)
265
+ */
266
+ function valueMustBeNumber(fnName) {
267
+ raiseError(`filter ${fnName} requires a number value`);
268
+ }
269
+ /**
270
+ * Throws error when filter requires boolean value but non-boolean provided.
271
+ *
272
+ * @param fnName - Name of the filter function
273
+ * @returns Never returns (always throws)
274
+ */
275
+ function valueMustBeBoolean(fnName) {
276
+ raiseError(`filter ${fnName} requires a boolean value`);
277
+ }
278
+ /**
279
+ * Throws error when filter requires Date value but non-Date provided.
280
+ *
281
+ * @param fnName - Name of the filter function
282
+ * @returns Never returns (always throws)
283
+ */
284
+ function valueMustBeDate(fnName) {
285
+ raiseError(`filter ${fnName} requires a date value`);
286
+ }
287
+ /**
288
+ * Throws error when filter requires array value but non-array provided.
289
+ *
290
+ * @param fnName - Name of the filter function
291
+ * @returns Never returns (always throws)
292
+ */
293
+ function valueMustBeArray(fnName) {
294
+ raiseError(`filter ${fnName} requires an array value`);
295
+ }
296
+
297
+ /**
298
+ * builtinFilters.ts
299
+ *
300
+ * Implementation file for built-in filter functions available in Structive.
301
+ *
302
+ * Main responsibilities:
303
+ * - Provides filters for conversion, comparison, formatting, and validation of numbers, strings, dates, booleans, etc.
304
+ * - Defines functions with options for each filter name, enabling flexible use during binding
305
+ * - Designed for common use as both input and output filters
306
+ *
307
+ * Design points:
308
+ * - Comprehensive coverage of diverse filters: eq, ne, lt, gt, inc, abs, clamp, fix, locale, uc, lc, cap, trim, slice, pad, truncate, join, int, float, round, percent, unit, date, time, ymd, hms, falsy, truthy, defaults, boolean, number, string, null, etc.
309
+ * - Rich type checking and error handling for option values
310
+ * - Centralized management of filter functions with FilterWithOptions type, easy to extend
311
+ * - Dynamic retrieval of filter functions from filter names and options via builtinFilterFn
312
+ */
313
+ function validateNumberString(value) {
314
+ if (!value || isNaN(Number(value))) {
315
+ return false;
316
+ }
317
+ return true;
318
+ }
319
+ /**
320
+ * Equality filter - compares value with option.
321
+ *
322
+ * @param options - Array with comparison value as first element
323
+ * @returns Filter function that returns boolean
324
+ */
325
+ const eq = (options) => {
326
+ const opt = options?.[0] ?? optionsRequired('eq');
327
+ return (value) => {
328
+ // Align types for comparison
329
+ if (typeof value === 'number') {
330
+ if (!validateNumberString(opt)) {
331
+ optionMustBeNumber('eq');
332
+ }
333
+ return value === Number(opt);
334
+ }
335
+ if (typeof value === 'string') {
336
+ return value === opt;
337
+ }
338
+ // Strict equality for others
339
+ return value === opt;
340
+ };
341
+ };
342
+ /**
343
+ * Inequality filter - compares value with option.
344
+ *
345
+ * @param options - Array with comparison value as first element
346
+ * @returns Filter function that returns boolean
347
+ */
348
+ const ne = (options) => {
349
+ const opt = options?.[0] ?? optionsRequired('ne');
350
+ return (value) => {
351
+ // Align types for comparison
352
+ if (typeof value === 'number') {
353
+ if (!validateNumberString(opt)) {
354
+ optionMustBeNumber('ne');
355
+ }
356
+ return value !== Number(opt);
357
+ }
358
+ if (typeof value === 'string') {
359
+ return value !== opt;
360
+ }
361
+ // Strict equality for others
362
+ return value !== opt;
363
+ };
364
+ };
365
+ /**
366
+ * Boolean NOT filter - inverts boolean value.
367
+ *
368
+ * @param options - Unused
369
+ * @returns Filter function that returns inverted boolean
370
+ */
371
+ const not = (_options) => {
372
+ return (value) => {
373
+ if (typeof value !== 'boolean') {
374
+ valueMustBeBoolean('not');
375
+ }
376
+ return !value;
377
+ };
378
+ };
379
+ /**
380
+ * Less than filter - checks if value is less than option.
381
+ *
382
+ * @param options - Array with comparison number as first element
383
+ * @returns Filter function that returns boolean
384
+ */
385
+ const lt = (options) => {
386
+ const opt = options?.[0] ?? optionsRequired('lt');
387
+ if (!validateNumberString(opt)) {
388
+ optionMustBeNumber('lt');
389
+ }
390
+ return (value) => {
391
+ if (typeof value !== 'number') {
392
+ valueMustBeNumber('lt');
393
+ }
394
+ return value < Number(opt);
395
+ };
396
+ };
397
+ /**
398
+ * Less than or equal filter - checks if value is less than or equal to option.
399
+ *
400
+ * @param options - Array with comparison number as first element
401
+ * @returns Filter function that returns boolean
402
+ */
403
+ const le = (options) => {
404
+ const opt = options?.[0] ?? optionsRequired('le');
405
+ if (!validateNumberString(opt)) {
406
+ optionMustBeNumber('le');
407
+ }
408
+ return (value) => {
409
+ if (typeof value !== 'number') {
410
+ valueMustBeNumber('le');
411
+ }
412
+ return value <= Number(opt);
413
+ };
414
+ };
415
+ /**
416
+ * Greater than filter - checks if value is greater than option.
417
+ *
418
+ * @param options - Array with comparison number as first element
419
+ * @returns Filter function that returns boolean
420
+ */
421
+ const gt = (options) => {
422
+ const opt = options?.[0] ?? optionsRequired('gt');
423
+ if (!validateNumberString(opt)) {
424
+ optionMustBeNumber('gt');
425
+ }
426
+ return (value) => {
427
+ if (typeof value !== 'number') {
428
+ valueMustBeNumber('gt');
429
+ }
430
+ return value > Number(opt);
431
+ };
432
+ };
433
+ /**
434
+ * Greater than or equal filter - checks if value is greater than or equal to option.
435
+ *
436
+ * @param options - Array with comparison number as first element
437
+ * @returns Filter function that returns boolean
438
+ */
439
+ const ge = (options) => {
440
+ const opt = options?.[0] ?? optionsRequired('ge');
441
+ if (!validateNumberString(opt)) {
442
+ optionMustBeNumber('ge');
443
+ }
444
+ return (value) => {
445
+ if (typeof value !== 'number') {
446
+ valueMustBeNumber('ge');
447
+ }
448
+ return value >= Number(opt);
449
+ };
450
+ };
451
+ /**
452
+ * Increment filter - adds option value to input value.
453
+ *
454
+ * @param options - Array with increment number as first element
455
+ * @returns Filter function that returns incremented number
456
+ */
457
+ const inc = (options) => {
458
+ const opt = options?.[0] ?? optionsRequired('inc');
459
+ if (!validateNumberString(opt)) {
460
+ optionMustBeNumber('inc');
461
+ }
462
+ return (value) => {
463
+ if (typeof value !== 'number') {
464
+ valueMustBeNumber('inc');
465
+ }
466
+ return value + Number(opt);
467
+ };
468
+ };
469
+ /**
470
+ * Decrement filter - subtracts option value from input value.
471
+ *
472
+ * @param options - Array with decrement number as first element
473
+ * @returns Filter function that returns decremented number
474
+ */
475
+ const dec = (options) => {
476
+ const opt = options?.[0] ?? optionsRequired('dec');
477
+ if (!validateNumberString(opt)) {
478
+ optionMustBeNumber('dec');
479
+ }
480
+ return (value) => {
481
+ if (typeof value !== 'number') {
482
+ valueMustBeNumber('dec');
483
+ }
484
+ return value - Number(opt);
485
+ };
486
+ };
487
+ /**
488
+ * Multiply filter - multiplies value by option.
489
+ *
490
+ * @param options - Array with multiplier number as first element
491
+ * @returns Filter function that returns multiplied number
492
+ */
493
+ const mul = (options) => {
494
+ const opt = options?.[0] ?? optionsRequired('mul');
495
+ if (!validateNumberString(opt)) {
496
+ optionMustBeNumber('mul');
497
+ }
498
+ return (value) => {
499
+ if (typeof value !== 'number') {
500
+ valueMustBeNumber('mul');
501
+ }
502
+ return value * Number(opt);
503
+ };
504
+ };
505
+ /**
506
+ * Divide filter - divides value by option.
507
+ *
508
+ * @param options - Array with divisor number as first element
509
+ * @returns Filter function that returns divided number
510
+ */
511
+ const div = (options) => {
512
+ const opt = options?.[0] ?? optionsRequired('div');
513
+ if (!validateNumberString(opt)) {
514
+ optionMustBeNumber('div');
515
+ }
516
+ return (value) => {
517
+ if (typeof value !== 'number') {
518
+ valueMustBeNumber('div');
519
+ }
520
+ return value / Number(opt);
521
+ };
522
+ };
523
+ /**
524
+ * Modulo filter - returns remainder of division.
525
+ *
526
+ * @param options - Array with divisor number as first element
527
+ * @returns Filter function that returns remainder
528
+ */
529
+ const mod = (options) => {
530
+ const opt = options?.[0] ?? optionsRequired('mod');
531
+ if (!validateNumberString(opt)) {
532
+ optionMustBeNumber('mod');
533
+ }
534
+ return (value) => {
535
+ if (typeof value !== 'number') {
536
+ valueMustBeNumber('mod');
537
+ }
538
+ return value % Number(opt);
539
+ };
540
+ };
541
+ /**
542
+ * Absolute value filter - returns the magnitude of a number.
543
+ *
544
+ * @param options - Unused
545
+ * @returns Filter function that returns the absolute value
546
+ */
547
+ const abs = (_options) => {
548
+ return (value) => {
549
+ if (typeof value !== 'number') {
550
+ valueMustBeNumber('abs');
551
+ }
552
+ return Math.abs(value);
553
+ };
554
+ };
555
+ /**
556
+ * Clamp filter - constrains a number to the inclusive range [min, max].
557
+ *
558
+ * Saturating conversion in the same family as round/floor/ceil, so it stays on
559
+ * the wire rather than in state. Pairs with `unit` for style bindings:
560
+ * `style.width: ratio|clamp(0,1)|percent(0)`.
561
+ *
562
+ * @param options - Array with minimum as first element and maximum as second (both required)
563
+ * @returns Filter function that returns the clamped number
564
+ */
565
+ const clamp = (options) => {
566
+ const opt1 = options?.[0] ?? optionsRequired('clamp');
567
+ if (!validateNumberString(opt1)) {
568
+ optionMustBeNumber('clamp');
569
+ }
570
+ const opt2 = options?.[1] ?? optionsRequired('clamp');
571
+ if (!validateNumberString(opt2)) {
572
+ optionMustBeNumber('clamp');
573
+ }
574
+ const min = Number(opt1);
575
+ const max = Number(opt2);
576
+ return (value) => {
577
+ if (typeof value !== 'number') {
578
+ valueMustBeNumber('clamp');
579
+ }
580
+ return Math.min(Math.max(value, min), max);
581
+ };
582
+ };
583
+ /**
584
+ * Fixed decimal filter - formats number to fixed decimal places.
585
+ *
586
+ * @param options - Array with decimal places as first element (default: 0)
587
+ * @returns Filter function that returns formatted string
588
+ */
589
+ const fix = (options) => {
590
+ const opt = options?.[0] ?? "0";
591
+ if (!validateNumberString(opt)) {
592
+ optionMustBeNumber('fix');
593
+ }
594
+ return (value) => {
595
+ if (typeof value !== 'number') {
596
+ valueMustBeNumber('fix');
597
+ }
598
+ return value.toFixed(Number(opt));
599
+ };
600
+ };
601
+ /**
602
+ * Locale number filter - formats number according to locale.
603
+ *
604
+ * @param options - Array with locale string as first element (default: config.locale)
605
+ * @returns Filter function that returns localized number string
606
+ */
607
+ const locale = (options) => {
608
+ const opt = options?.[0] ?? config.locale;
609
+ return (value) => {
610
+ if (typeof value !== 'number') {
611
+ valueMustBeNumber('locale');
612
+ }
613
+ return value.toLocaleString(opt);
614
+ };
615
+ };
616
+ /**
617
+ * Uppercase filter - converts string to uppercase.
618
+ *
619
+ * @param options - Unused
620
+ * @returns Filter function that returns uppercase string
621
+ */
622
+ const uc = (_options) => {
623
+ return (value) => {
624
+ return String(value).toUpperCase();
625
+ };
626
+ };
627
+ /**
628
+ * Lowercase filter - converts string to lowercase.
629
+ *
630
+ * @param options - Unused
631
+ * @returns Filter function that returns lowercase string
632
+ */
633
+ const lc = (_options) => {
634
+ return (value) => {
635
+ return String(value).toLowerCase();
636
+ };
637
+ };
638
+ /**
639
+ * Capitalize filter - capitalizes first character of string.
640
+ *
641
+ * @param options - Unused
642
+ * @returns Filter function that returns capitalized string
643
+ */
644
+ const cap = (_options) => {
645
+ return (value) => {
646
+ const v = String(value);
647
+ if (v.length === 0) {
648
+ return v;
649
+ }
650
+ if (v.length === 1) {
651
+ return v.toUpperCase();
652
+ }
653
+ return v.charAt(0).toUpperCase() + v.slice(1);
654
+ };
655
+ };
656
+ /**
657
+ * Trim filter - removes whitespace from both ends of string.
658
+ *
659
+ * @param options - Unused
660
+ * @returns Filter function that returns trimmed string
661
+ */
662
+ const trim = (_options) => {
663
+ return (value) => {
664
+ return String(value).trim();
665
+ };
666
+ };
667
+ /**
668
+ * Slice filter - extracts portion of string from specified index.
669
+ *
670
+ * @param options - Array with start index and optional end index
671
+ * @returns Filter function that returns sliced string
672
+ */
673
+ const slice = (options) => {
674
+ const numberedOpts = [];
675
+ const opt1 = options?.[0] ?? optionsRequired('slice');
676
+ if (!validateNumberString(opt1)) {
677
+ optionMustBeNumber('slice');
678
+ }
679
+ numberedOpts.push(Number(opt1));
680
+ const opt2 = options?.[1];
681
+ if (typeof opt2 !== 'undefined') {
682
+ if (!validateNumberString(opt2)) {
683
+ optionMustBeNumber('slice');
684
+ }
685
+ numberedOpts.push(Number(opt2));
686
+ }
687
+ return (value) => {
688
+ return String(value).slice(...numberedOpts);
689
+ };
690
+ };
691
+ /**
692
+ * Substring filter - extracts substring from specified position and length.
693
+ *
694
+ * @param options - Array with start index and length
695
+ * @returns Filter function that returns substring
696
+ */
697
+ const substr = (options) => {
698
+ const opt1 = options?.[0] ?? optionsRequired('substr');
699
+ if (!validateNumberString(opt1)) {
700
+ optionMustBeNumber('substr');
701
+ }
702
+ const opt2 = options?.[1] ?? optionsRequired('substr');
703
+ if (!validateNumberString(opt2)) {
704
+ optionMustBeNumber('substr');
705
+ }
706
+ return (value) => {
707
+ return String(value).substr(Number(opt1), Number(opt2));
708
+ };
709
+ };
710
+ /**
711
+ * Pad filter - pads string to specified length from start.
712
+ *
713
+ * @param options - Array with target length and pad string (default: '0')
714
+ * @returns Filter function that returns padded string
715
+ */
716
+ const pad = (options) => {
717
+ const opt1 = options?.[0] ?? optionsRequired('pad');
718
+ if (!validateNumberString(opt1)) {
719
+ optionMustBeNumber('pad');
720
+ }
721
+ const opt2 = options?.[1] ?? '0';
722
+ return (value) => {
723
+ return String(value).padStart(Number(opt1), opt2);
724
+ };
725
+ };
726
+ /**
727
+ * Repeat filter - repeats string specified number of times.
728
+ *
729
+ * @param options - Array with repeat count as first element
730
+ * @returns Filter function that returns repeated string
731
+ */
732
+ const rep = (options) => {
733
+ const opt = options?.[0] ?? optionsRequired('rep');
734
+ if (!validateNumberString(opt)) {
735
+ optionMustBeNumber('rep');
736
+ }
737
+ return (value) => {
738
+ return String(value).repeat(Number(opt));
739
+ };
740
+ };
741
+ /**
742
+ * Reverse filter - reverses character order in string.
743
+ *
744
+ * @param options - Unused
745
+ * @returns Filter function that returns reversed string
746
+ */
747
+ const rev = (_options) => {
748
+ return (value) => {
749
+ return String(value).split('').reverse().join('');
750
+ };
751
+ };
752
+ /**
753
+ * Integer filter - parses value to integer.
754
+ *
755
+ * @param options - Unused
756
+ * @returns Filter function that returns integer
757
+ */
758
+ const int = (_options) => {
759
+ return (value) => {
760
+ return parseInt(String(value), 10);
761
+ };
762
+ };
763
+ /**
764
+ * Float filter - parses value to floating point number.
765
+ *
766
+ * @param options - Unused
767
+ * @returns Filter function that returns float
768
+ */
769
+ const float = (_options) => {
770
+ return (value) => {
771
+ return parseFloat(String(value));
772
+ };
773
+ };
774
+ /**
775
+ * Round filter - rounds number to specified decimal places.
776
+ *
777
+ * @param options - Array with decimal places as first element (default: 0)
778
+ * @returns Filter function that returns rounded number
779
+ */
780
+ const round = (options) => {
781
+ const opt = options?.[0] ?? '0';
782
+ if (!validateNumberString(opt)) {
783
+ optionMustBeNumber('round');
784
+ }
785
+ return (value) => {
786
+ if (typeof value !== 'number') {
787
+ valueMustBeNumber('round');
788
+ }
789
+ const optValue = Math.pow(10, Number(opt));
790
+ return Math.round(value * optValue) / optValue;
791
+ };
792
+ };
793
+ /**
794
+ * Floor filter - rounds number down to specified decimal places.
795
+ *
796
+ * @param options - Array with decimal places as first element (default: 0)
797
+ * @returns Filter function that returns floored number
798
+ */
799
+ const floor = (options) => {
800
+ const opt = options?.[0] ?? '0';
801
+ if (!validateNumberString(opt)) {
802
+ optionMustBeNumber('floor');
803
+ }
804
+ return (value) => {
805
+ if (typeof value !== 'number') {
806
+ valueMustBeNumber('floor');
807
+ }
808
+ const optValue = Math.pow(10, Number(opt));
809
+ return Math.floor(value * optValue) / optValue;
810
+ };
811
+ };
812
+ /**
813
+ * Ceiling filter - rounds number up to specified decimal places.
814
+ *
815
+ * @param options - Array with decimal places as first element (default: 0)
816
+ * @returns Filter function that returns ceiled number
817
+ */
818
+ const ceil = (options) => {
819
+ const opt = options?.[0] ?? '0';
820
+ if (!validateNumberString(opt)) {
821
+ optionMustBeNumber('ceil');
822
+ }
823
+ return (value) => {
824
+ if (typeof value !== 'number') {
825
+ valueMustBeNumber('ceil');
826
+ }
827
+ const optValue = Math.pow(10, Number(opt));
828
+ return Math.ceil(value * optValue) / optValue;
829
+ };
830
+ };
831
+ /**
832
+ * Percent filter - formats number as percentage string.
833
+ *
834
+ * @param options - Array with decimal places as first element (default: 0)
835
+ * @returns Filter function that returns percentage string with '%'
836
+ */
837
+ const percent = (options) => {
838
+ const opt = options?.[0] ?? '0';
839
+ if (!validateNumberString(opt)) {
840
+ optionMustBeNumber('percent');
841
+ }
842
+ return (value) => {
843
+ if (typeof value !== 'number') {
844
+ valueMustBeNumber('percent');
845
+ }
846
+ return `${(value * 100).toFixed(Number(opt))}%`;
847
+ };
848
+ };
849
+ /**
850
+ * Unit filter - appends a CSS unit (or any suffix) to the value.
851
+ *
852
+ * A number alone does nothing in CSS, so without this the unit has to be built in
853
+ * state — which drags presentation into the source of truth, and in the worst case
854
+ * forces a whole derived array just to carry `"42%"` strings.
855
+ * `style.height: samples.*.cpu|clamp(0,100)|fix(0)|unit(%)` keeps it on the wire.
856
+ *
857
+ * Accepts strings as well as numbers **on purpose**: the useful chains run through
858
+ * `fix` / `percent`, which already return strings. Rejecting non-numbers here would
859
+ * break exactly the combination this filter exists for.
860
+ *
861
+ * `null` / `undefined` pass through untouched rather than becoming `"undefinedpx"`,
862
+ * so the binding layer's "undefined skips the write, null clears" semantics survive.
863
+ *
864
+ * @param options - Array with the unit/suffix as first element (required)
865
+ * @returns Filter function that returns the value with the unit appended
866
+ */
867
+ const unit = (options) => {
868
+ const opt = options?.[0] ?? optionsRequired('unit');
869
+ return (value) => {
870
+ if (value === null || typeof value === 'undefined') {
871
+ return value;
872
+ }
873
+ return String(value) + opt;
874
+ };
875
+ };
876
+ /**
877
+ * Join filter - joins array elements into a string.
878
+ *
879
+ * The default separator is `", "` rather than `","`: a bare comma is what `String()`
880
+ * already produces without any filter, so defaulting to it would make `|join` a no-op.
881
+ *
882
+ * @param options - Array with separator as first element (default: ', ')
883
+ * @returns Filter function that returns the joined string
884
+ */
885
+ const join = (options) => {
886
+ const opt = options?.[0] ?? ', ';
887
+ return (value) => {
888
+ if (!Array.isArray(value)) {
889
+ valueMustBeArray('join');
890
+ }
891
+ return value.join(opt);
892
+ };
893
+ };
894
+ /**
895
+ * Truncate filter - shortens a string and appends an ellipsis.
896
+ *
897
+ * The length option counts **kept characters**, not the total including the suffix,
898
+ * matching the existing `slice(0, n)` reading. A string at or below the limit is
899
+ * returned untouched (no suffix).
900
+ *
901
+ * @param options - Array with max kept length as first element and suffix as second (default: '…')
902
+ * @returns Filter function that returns the truncated string
903
+ */
904
+ const truncate = (options) => {
905
+ const opt1 = options?.[0] ?? optionsRequired('truncate');
906
+ if (!validateNumberString(opt1)) {
907
+ optionMustBeNumber('truncate');
908
+ }
909
+ const maxLength = Number(opt1);
910
+ const suffix = options?.[1] ?? '…';
911
+ return (value) => {
912
+ const v = String(value);
913
+ if (v.length <= maxLength) {
914
+ return v;
915
+ }
916
+ return v.slice(0, maxLength) + suffix;
917
+ };
918
+ };
919
+ /**
920
+ * Date filter - formats Date object as localized date string.
921
+ *
922
+ * @param options - Array with locale string as first element (default: config.locale)
923
+ * @returns Filter function that returns date string
924
+ */
925
+ const date = (options) => {
926
+ const opt = options?.[0] ?? config.locale;
927
+ return (value) => {
928
+ if (!(value instanceof Date)) {
929
+ valueMustBeDate('date');
930
+ }
931
+ return value.toLocaleDateString(opt);
932
+ };
933
+ };
934
+ /**
935
+ * Time filter - formats Date object as localized time string.
936
+ *
937
+ * @param options - Array with locale string as first element (default: config.locale)
938
+ * @returns Filter function that returns time string
939
+ */
940
+ const time = (options) => {
941
+ const opt = options?.[0] ?? config.locale;
942
+ return (value) => {
943
+ if (!(value instanceof Date)) {
944
+ valueMustBeDate('time');
945
+ }
946
+ return value.toLocaleTimeString(opt);
947
+ };
948
+ };
949
+ /**
950
+ * DateTime filter - formats Date object as localized date and time string.
951
+ *
952
+ * @param options - Array with locale string as first element (default: config.locale)
953
+ * @returns Filter function that returns datetime string
954
+ */
955
+ const datetime = (options) => {
956
+ const opt = options?.[0] ?? config.locale;
957
+ return (value) => {
958
+ if (!(value instanceof Date)) {
959
+ valueMustBeDate('datetime');
960
+ }
961
+ return value.toLocaleString(opt);
962
+ };
963
+ };
964
+ /**
965
+ * Year-Month-Day filter - formats Date object as YYYY-MM-DD string.
966
+ *
967
+ * @param options - Array with separator string as first element (default: '-')
968
+ * @returns Filter function that returns formatted date string
969
+ */
970
+ const ymd = (options) => {
971
+ const opt = options?.[0] ?? '-';
972
+ return (value) => {
973
+ if (!(value instanceof Date)) {
974
+ valueMustBeDate('ymd');
975
+ }
976
+ const year = value.getFullYear().toString();
977
+ const month = (value.getMonth() + 1).toString().padStart(2, '0');
978
+ const day = value.getDate().toString().padStart(2, '0');
979
+ return `${year}${opt}${month}${opt}${day}`;
980
+ };
981
+ };
982
+ /**
983
+ * Hour-Minute-Second filter - formats Date object as HH:MM:SS string.
984
+ *
985
+ * The counterpart of `ymd`: a fixed, zero-padded, locale-independent rendering with a
986
+ * configurable separator, for when `time` (locale-formatted) is not stable enough.
987
+ *
988
+ * @param options - Array with separator string as first element (default: ':')
989
+ * @returns Filter function that returns formatted time string
990
+ */
991
+ const hms = (options) => {
992
+ const opt = options?.[0] ?? ':';
993
+ return (value) => {
994
+ if (!(value instanceof Date)) {
995
+ valueMustBeDate('hms');
996
+ }
997
+ const hours = value.getHours().toString().padStart(2, '0');
998
+ const minutes = value.getMinutes().toString().padStart(2, '0');
999
+ const seconds = value.getSeconds().toString().padStart(2, '0');
1000
+ return `${hours}${opt}${minutes}${opt}${seconds}`;
1001
+ };
1002
+ };
1003
+ /**
1004
+ * Falsy filter - checks if value is falsy.
1005
+ *
1006
+ * @param options - Unused
1007
+ * @returns Filter function that returns true for false/null/undefined/0/''/NaN
1008
+ */
1009
+ const falsy = (_options) => {
1010
+ return (value) => value === false || value === null || value === undefined || value === 0 || value === '' || Number.isNaN(value);
1011
+ };
1012
+ /**
1013
+ * Truthy filter - checks if value is truthy.
1014
+ *
1015
+ * @param options - Unused
1016
+ * @returns Filter function that returns true for non-falsy values
1017
+ */
1018
+ const truthy = (_options) => {
1019
+ return (value) => value !== false && value !== null && value !== undefined && value !== 0 && value !== '' && !Number.isNaN(value);
1020
+ };
1021
+ /**
1022
+ * Default filter - returns default value if input is falsy.
1023
+ *
1024
+ * @param options - Array with default value as first element
1025
+ * @returns Filter function that returns value or default
1026
+ */
1027
+ const defaults = (options) => {
1028
+ const opt = options?.[0] ?? optionsRequired('defaults');
1029
+ return (value) => {
1030
+ if (value === false || value === null || value === undefined || value === 0 || value === '' || Number.isNaN(value)) {
1031
+ return opt;
1032
+ }
1033
+ return value;
1034
+ };
1035
+ };
1036
+ /**
1037
+ * Boolean filter - converts value to boolean.
1038
+ *
1039
+ * @param options - Unused
1040
+ * @returns Filter function that returns boolean
1041
+ */
1042
+ const boolean = (_options) => {
1043
+ return (value) => {
1044
+ return Boolean(value);
1045
+ };
1046
+ };
1047
+ /**
1048
+ * Number filter - converts value to number.
1049
+ *
1050
+ * @param options - Unused
1051
+ * @returns Filter function that returns number
1052
+ */
1053
+ const number = (_options) => {
1054
+ return (value) => {
1055
+ return Number(value);
1056
+ };
1057
+ };
1058
+ /**
1059
+ * String filter - converts value to string.
1060
+ *
1061
+ * @param options - Unused
1062
+ * @returns Filter function that returns string
1063
+ */
1064
+ const string = (_options) => {
1065
+ return (value) => {
1066
+ return String(value);
1067
+ };
1068
+ };
1069
+ /**
1070
+ * Null filter - converts empty string to null.
1071
+ *
1072
+ * @param options - Unused
1073
+ * @returns Filter function that returns null for empty string, otherwise original value
1074
+ */
1075
+ const _null = (_options) => {
1076
+ return (value) => {
1077
+ return (value === "") ? null : value;
1078
+ };
1079
+ };
1080
+ const builtinFilters = {
1081
+ "eq": eq,
1082
+ "ne": ne,
1083
+ "not": not,
1084
+ "lt": lt,
1085
+ "le": le,
1086
+ "gt": gt,
1087
+ "ge": ge,
1088
+ "inc": inc,
1089
+ "dec": dec,
1090
+ "mul": mul,
1091
+ "div": div,
1092
+ "mod": mod,
1093
+ "abs": abs,
1094
+ "clamp": clamp,
1095
+ "fix": fix,
1096
+ "locale": locale,
1097
+ "uc": uc,
1098
+ "lc": lc,
1099
+ "cap": cap,
1100
+ "trim": trim,
1101
+ "slice": slice,
1102
+ "substr": substr,
1103
+ "pad": pad,
1104
+ "rep": rep,
1105
+ "rev": rev,
1106
+ "truncate": truncate,
1107
+ "join": join,
1108
+ "int": int,
1109
+ "float": float,
1110
+ "round": round,
1111
+ "floor": floor,
1112
+ "ceil": ceil,
1113
+ "percent": percent,
1114
+ "unit": unit,
1115
+ "date": date,
1116
+ "time": time,
1117
+ "datetime": datetime,
1118
+ "ymd": ymd,
1119
+ "hms": hms,
1120
+ "falsy": falsy,
1121
+ "truthy": truthy,
1122
+ "defaults": defaults,
1123
+ "boolean": boolean,
1124
+ "number": number,
1125
+ "string": string,
1126
+ "null": _null,
1127
+ };
1128
+ const outputBuiltinFilters = builtinFilters;
1129
+ const inputBuiltinFilters = builtinFilters;
1130
+ const builtinFiltersByFilterIOType = {
1131
+ "input": inputBuiltinFilters,
1132
+ "output": outputBuiltinFilters,
1133
+ };
1134
+ /**
1135
+ * Retrieves built-in filter function by name and options.
1136
+ *
1137
+ * @param name - Filter name
1138
+ * @param options - Array of option strings
1139
+ * @returns Function that takes FilterWithOptions and returns filter function
1140
+ */
1141
+ const builtinFilterFn = (name, options) => (filters) => {
1142
+ const filter = filters[name];
1143
+ if (!filter) {
1144
+ // lint の wcs/filter-unknown と同じ語彙・同じ did-you-mean 規準(三面同語彙)。
1145
+ raiseError(`[wcs/filter-unknown] filter not found: ${name}.${didYouMean(name, Object.keys(filters))}${LINT_HINT}`);
1146
+ }
1147
+ return filter(options);
1148
+ };
1149
+
1150
+ /**
1151
+ * フィルタ引数リストのパース。`filter(a, b)` の `a, b` 部分を受け取る。
1152
+ *
1153
+ * トリムの規則は「**クォートの外側だけ**」。`fix( 2 )` のような書き癖を吸収するために
1154
+ * 素の引数は前後をトリムするが、クォートは「ここは literal」という宣言なので中身の
1155
+ * 空白は残す。両方まとめてトリムしていたため `pad(5, ' ')` が空文字パディング
1156
+ * (=無変化)に化けており、空白区切りの `join(' / ')` も指定できなかった。
1157
+ */
1158
+ /** 引数 1 つを確定する。クォート由来の文字が入った範囲より外側だけをトリムする。 */
1159
+ function finalizeArg(text, firstQuoteStart, lastQuoteEnd) {
1160
+ // 先頭側: 最初のクォート文字より前だけが削れる(クォートが無ければ全体が対象)
1161
+ const startLimit = firstQuoteStart === -1 ? text.length : firstQuoteStart;
1162
+ let start = 0;
1163
+ while (start < startLimit && /\s/.test(text[start])) {
1164
+ start++;
1165
+ }
1166
+ // 末尾側: 最後のクォート文字より後ろだけが削れる(クォートが無ければ全体が対象)
1167
+ const endLimit = lastQuoteEnd === -1 ? 0 : lastQuoteEnd;
1168
+ let end = text.length;
1169
+ while (end > endLimit && /\s/.test(text[end - 1])) {
1170
+ end--;
1171
+ }
1172
+ return text.slice(start, end);
1173
+ }
1174
+ function parseFilterArgs(argsText) {
1175
+ const args = [];
1176
+ let current = '';
1177
+ let inQuote = null;
1178
+ let hasQuote = false;
1179
+ let firstQuoteStart = -1;
1180
+ let lastQuoteEnd = -1;
1181
+ const flush = () => {
1182
+ args.push(finalizeArg(current, firstQuoteStart, lastQuoteEnd));
1183
+ current = '';
1184
+ hasQuote = false;
1185
+ firstQuoteStart = -1;
1186
+ lastQuoteEnd = -1;
1187
+ };
1188
+ for (let i = 0; i < argsText.length; i++) {
1189
+ const char = argsText[i];
1190
+ if (inQuote) {
1191
+ if (char === inQuote) {
1192
+ inQuote = null;
1193
+ }
1194
+ else {
1195
+ if (firstQuoteStart === -1) {
1196
+ firstQuoteStart = current.length;
1197
+ }
1198
+ current += char;
1199
+ lastQuoteEnd = current.length;
1200
+ }
1201
+ }
1202
+ else if (char === '"' || char === "'") {
1203
+ inQuote = char;
1204
+ hasQuote = true;
1205
+ }
1206
+ else if (char === ',') {
1207
+ flush();
1208
+ }
1209
+ else {
1210
+ current += char;
1211
+ }
1212
+ }
1213
+ const last = finalizeArg(current, firstQuoteStart, lastQuoteEnd);
1214
+ if (last || hasQuote) {
1215
+ args.push(last);
1216
+ }
1217
+ return args;
1218
+ }
1219
+
1220
+ const filterFnByKey = new Map();
1221
+ // format: filterName(arg1,arg2) or filterName
1222
+ function parseFilters(filterTextList, filterIOType) {
1223
+ const builtinFilters = builtinFiltersByFilterIOType[filterIOType];
1224
+ const filters = filterTextList.map((filterText) => {
1225
+ const openParenIndex = filterText.indexOf('(');
1226
+ const closeParenIndex = filterText.lastIndexOf(')');
1227
+ // check parentheses
1228
+ if (openParenIndex !== -1 && closeParenIndex === -1) {
1229
+ raiseError(`Invalid filter format: missing closing parenthesis in "${filterText}"`);
1230
+ }
1231
+ if (closeParenIndex !== -1 && openParenIndex === -1) {
1232
+ raiseError(`Invalid filter format: missing opening parenthesis in "${filterText}"`);
1233
+ }
1234
+ if (openParenIndex === -1) {
1235
+ // no arguments
1236
+ const filterName = filterText.trim();
1237
+ const filterKey = `${filterName}():${filterIOType}`;
1238
+ let filterFn = filterFnByKey.get(filterKey);
1239
+ if (typeof filterFn === 'undefined') {
1240
+ filterFn = builtinFilterFn(filterName, [])(builtinFilters);
1241
+ filterFnByKey.set(filterKey, filterFn);
1242
+ }
1243
+ return {
1244
+ filterName: filterName,
1245
+ args: [],
1246
+ filterFn: filterFn,
1247
+ };
1248
+ }
1249
+ else {
1250
+ const argsText = filterText.substring(openParenIndex + 1, closeParenIndex);
1251
+ const filterName = filterText.substring(0, openParenIndex).trim();
1252
+ const args = parseFilterArgs(argsText);
1253
+ const filterKey = `${filterName}(${args.join(',')}):${filterIOType}`;
1254
+ let filterFn = filterFnByKey.get(filterKey);
1255
+ if (typeof filterFn === 'undefined') {
1256
+ filterFn = builtinFilterFn(filterName, args)(builtinFilters);
1257
+ filterFnByKey.set(filterKey, filterFn);
1258
+ }
1259
+ return {
1260
+ filterName,
1261
+ args,
1262
+ filterFn,
1263
+ };
1264
+ }
1265
+ });
1266
+ return filters;
1267
+ }
1268
+
1269
+ const trimFn = (s) => s.trim();
1270
+
1271
+ const cacheFilterInfos$1 = new Map();
1272
+ // format: propName#moodifier1,modifier2
1273
+ // propName-format: path.to.property (e.g., textContent, style.color, not include :)
1274
+ // special path:
1275
+ // 'attr.attributeName' for attributes (e.g., attr.href, attr.data-id)
1276
+ // 'style.propertyName' for style properties (e.g., style.backgroundColor, style.fontSize)
1277
+ // 'class.className' for class names (e.g., class.active, class.hidden)
1278
+ // 'onclick', 'onchange' etc. for event listeners
1279
+ function parsePropPart(propPart) {
1280
+ const pos = propPart.indexOf(FILTER_SEPARATOR);
1281
+ let propText = '';
1282
+ let filterTexts = [];
1283
+ let filtersText = '';
1284
+ let filters = [];
1285
+ if (pos !== -1) {
1286
+ propText = propPart.slice(0, pos).trim();
1287
+ filtersText = propPart.slice(pos + 1).trim();
1288
+ if (cacheFilterInfos$1.has(filtersText)) {
1289
+ filters = cacheFilterInfos$1.get(filtersText);
1290
+ }
1291
+ else {
1292
+ filterTexts = filtersText.split(FILTER_SEPARATOR).map(trimFn);
1293
+ filters = parseFilters(filterTexts, "input");
1294
+ cacheFilterInfos$1.set(filtersText, filters);
1295
+ }
1296
+ }
1297
+ else {
1298
+ propText = propPart.trim();
1299
+ }
1300
+ const [propName, propModifiersText] = propText.split(MODIFIER_SEPARATOR).map(trimFn);
1301
+ const propSegments = propName.split(DELIMITER).map(trimFn);
1302
+ const propModifiers = propModifiersText
1303
+ ? propModifiersText.split(',').map(trimFn)
1304
+ : [];
1305
+ return {
1306
+ propName,
1307
+ propSegments,
1308
+ propModifiers,
1309
+ inFilters: filters,
1310
+ };
1311
+ }
1312
+
1313
+ const cacheFilterInfos = new Map();
1314
+ // format: statePath@stateName|filter|filter
1315
+ // statePath-format: path.to.property (e.g., user.name.first, users.*.name, users.0.name, not include @)
1316
+ // stateName: optional, default is 'default'
1317
+ // filters-format: filterName or filterName(arg1,arg2)
1318
+ function parseStatePart(statePart) {
1319
+ const pos = statePart.indexOf(FILTER_SEPARATOR);
1320
+ let stateAndPath = '';
1321
+ let filterTexts = [];
1322
+ let filtersText = '';
1323
+ let filters = [];
1324
+ if (pos !== -1) {
1325
+ stateAndPath = statePart.slice(0, pos).trim();
1326
+ filtersText = statePart.slice(pos + 1).trim();
1327
+ if (cacheFilterInfos.has(filtersText)) {
1328
+ filters = cacheFilterInfos.get(filtersText);
1329
+ }
1330
+ else {
1331
+ filterTexts = filtersText.split(FILTER_SEPARATOR).map(trimFn);
1332
+ filters = parseFilters(filterTexts, "output");
1333
+ cacheFilterInfos.set(filtersText, filters);
1334
+ }
1335
+ }
1336
+ else {
1337
+ stateAndPath = statePart.trim();
1338
+ }
1339
+ const [statePathName, stateName = 'default'] = stateAndPath.split(STATE_NAME_SEPARATOR).map(trimFn);
1340
+ const pathInfo = getPathInfo(statePathName);
1341
+ return {
1342
+ stateName,
1343
+ statePathName,
1344
+ statePathInfo: pathInfo,
1345
+ outFilters: filters,
1346
+ };
1347
+ }
1348
+
1349
+ // format: propPart:statePart; propPart:statePart; ...
1350
+ // special-propPart:
1351
+ // if: statePart (single binding for conditional rendering)
1352
+ // else: (single binding for conditional rendering, and statePart is ignored)
1353
+ // elseif: statePart only (single binding for conditional rendering)
1354
+ // for: statePart only (single binding for loop rendering)
1355
+ // onclick: statePart, onchange: statePart etc. (event listeners)
1356
+ // ...: statePart (spread — expand wcBindable properties+inputs of target object)
1357
+ function parseBindTextsForElement(bindText) {
1358
+ const [...bindTexts] = bindText.split(BINDING_SEPARATOR).map(trimFn).filter(s => s.length > 0);
1359
+ const results = bindTexts.map((bindText) => {
1360
+ const separatorIndex = bindText.indexOf(PROP_VALUE_SEPARATOR);
1361
+ if (separatorIndex === -1) {
1362
+ raiseError(`Invalid bindText: "${bindText}". Missing ':' separator between propPart and statePart.`);
1363
+ }
1364
+ const propPart = bindText.slice(0, separatorIndex).trim();
1365
+ const statePart = bindText.slice(separatorIndex + 1).trim();
1366
+ if (propPart === ELSE_KEYWORD) {
1367
+ const pathInfo = getPathInfo('#else');
1368
+ return {
1369
+ propName: ELSE_KEYWORD,
1370
+ propSegments: [ELSE_KEYWORD],
1371
+ propModifiers: [],
1372
+ statePathName: '#else',
1373
+ statePathInfo: pathInfo,
1374
+ stateName: '',
1375
+ inFilters: [],
1376
+ outFilters: [],
1377
+ bindingType: 'else',
1378
+ };
1379
+ }
1380
+ else if (propPart === SPREAD_PROP) {
1381
+ const stateResult = parseStatePart(statePart);
1382
+ if (stateResult.outFilters.length > 0) {
1383
+ raiseError(`Invalid spread binding "${bindText}": filters are not allowed on spread targets.`);
1384
+ }
1385
+ if (stateResult.statePathName.length === 0) {
1386
+ raiseError(`Invalid spread binding "${bindText}": spread target path is required.`);
1387
+ }
1388
+ return {
1389
+ propName: SPREAD_PROP,
1390
+ propSegments: [SPREAD_PROP],
1391
+ propModifiers: [],
1392
+ inFilters: [],
1393
+ ...stateResult,
1394
+ bindingType: 'spread',
1395
+ };
1396
+ }
1397
+ else if (propPart === 'if'
1398
+ || propPart === 'elseif'
1399
+ || propPart === 'for'
1400
+ || propPart === 'radio'
1401
+ || propPart === 'checkbox') {
1402
+ const stateResult = parseStatePart(statePart);
1403
+ return {
1404
+ propName: propPart,
1405
+ propSegments: [propPart],
1406
+ propModifiers: [],
1407
+ inFilters: [],
1408
+ ...stateResult,
1409
+ bindingType: propPart,
1410
+ };
1411
+ }
1412
+ else {
1413
+ const stateResult = parseStatePart(statePart);
1414
+ const propResult = parsePropPart(propPart);
1415
+ // eventToken.<prop>: <name> は要素 dispatch を state へ流す pub/sub 配線。
1416
+ // 値適用ではないため bindingType 'event' として listener attach 経路に乗せる。
1417
+ if (propResult.propSegments[0] === EVENT_TOKEN_NAMESPACE) {
1418
+ return {
1419
+ ...propResult,
1420
+ ...stateResult,
1421
+ bindingType: 'event',
1422
+ };
1423
+ }
1424
+ if (propResult.propSegments[0].startsWith(EVENT_PROP_PREFIX)) {
1425
+ return {
1426
+ ...propResult,
1427
+ ...stateResult,
1428
+ bindingType: 'event',
1429
+ };
1430
+ }
1431
+ else {
1432
+ return {
1433
+ ...propResult,
1434
+ ...stateResult,
1435
+ bindingType: 'prop',
1436
+ };
1437
+ }
1438
+ }
1439
+ });
1440
+ // check for sigle binding for 'if', 'elseif', 'else', 'for'
1441
+ if (results.length > 1) {
1442
+ const isIncludeSingleBinding = results.some(r => STRUCTURAL_BINDING_TYPE_SET.has(r.bindingType));
1443
+ if (isIncludeSingleBinding) {
1444
+ // LINT_HINT は付けない: 単独バインディング検査は lint 側に未実装で、誘導が
1445
+ // 空振りする(lint への検査追加は follow-up)。
1446
+ raiseError(`[wcs/template-syntax] Invalid bindText: "${bindText}". 'if', 'elseif', 'else', and 'for' bindings must be single binding. Put the structural binding alone in its own data-wcs (e.g. <template data-wcs="for: items">).`);
1447
+ }
1448
+ }
1449
+ return results;
1450
+ }
1451
+
1452
+ export { getPathInfo, parseBindTextsForElement };