1+ import fs from "node:fs" ;
2+ import path from "node:path" ;
3+ import { fileURLToPath } from "node:url" ;
14import { format } from "prettier" ;
25import plugin from "prettier/plugins/typescript" ;
3- import componentApi from "../docs/src/COMPONENT_API.json" with { type : "json" } ;
6+ import componentApi from "../src/COMPONENT_API.json" with { type : "json" } ;
7+
8+ const __dirname = path . dirname ( fileURLToPath ( import . meta. url ) ) ;
9+ const outFile = path . join ( __dirname , "../src/COMPONENT_API.json" ) ;
410
511const WHITESPACE_REGEX = / \s { 2 , } / ;
612const TRAILING_SEMICOLON_REGEX = / ; \s * $ / ;
713const EVENT_DETAIL_PREFIX_REGEX = / t y p e E v e n t D e t a i l = / ;
814const SLOT_PROPS_PREFIX_REGEX = / t y p e S l o t P r o p s = / ;
915
10- const formatTypeScript = async ( value ) => {
16+ /** Avoid `type EventDetail = type EventDetail = …` when re-running the formatter. */
17+ const stripLeadingTypeAlias = (
18+ source : string ,
19+ name : "EventDetail" | "SlotProps" ,
20+ ) => {
21+ const re = new RegExp ( `^\\s*type\\s+${ name } \\s*=\\s*` , "i" ) ;
22+ let s = source ;
23+ let next = s . replace ( re , "" ) . trimStart ( ) ;
24+ while ( next !== s ) {
25+ s = next ;
26+ next = s . replace ( re , "" ) . trimStart ( ) ;
27+ }
28+ return s ;
29+ } ;
30+
31+ const formatTypeScript = async ( value : string ) => {
1132 return await format ( value , {
1233 parser : "typescript" ,
1334 plugins : [ plugin ] ,
@@ -67,7 +88,16 @@ const modified = {
6788 return event ;
6889 }
6990
70- const normalizedValue = `type EventDetail = ${ event . detail } ` ;
91+ if ( ! ( "detail" in event ) || typeof event . detail !== "string" ) {
92+ return event ;
93+ }
94+
95+ const detailBody = stripLeadingTypeAlias ( event . detail , "EventDetail" ) ;
96+ if ( ! detailBody ) {
97+ return event ;
98+ }
99+
100+ const normalizedValue = `type EventDetail = ${ detailBody } ` ;
71101
72102 const formatted = ( await formatTypeScript ( normalizedValue ) )
73103 // Remove prefix needed for formatting.
@@ -88,7 +118,10 @@ const modified = {
88118 return slot ;
89119 }
90120
91- let normalizedValue = slot . slot_props ;
121+ let normalizedValue = stripLeadingTypeAlias (
122+ slot . slot_props ,
123+ "SlotProps" ,
124+ ) ;
92125
93126 if ( normalizedValue . startsWith ( "{" ) ) {
94127 normalizedValue = `type SlotProps = ${ normalizedValue } ` ;
@@ -118,9 +151,6 @@ const modified = {
118151 ) ,
119152} ;
120153
121- await Bun . write (
122- "./docs/src/COMPONENT_API.json" ,
123- JSON . stringify ( modified , null , 2 ) ,
124- ) ;
154+ fs . writeFileSync ( outFile , JSON . stringify ( modified , null , 2 ) ) ;
125155
126156console . timeEnd ( "formatComponentApi" ) ;
0 commit comments