@@ -2,7 +2,7 @@ import fs from 'node:fs';
22import path from 'node:path' ;
33import os from 'node:os' ;
44
5- import { pkg , config , configPath } from '../src/static.js' ;
5+ import { pkg , config , configPath , configDownloadPath } from '../src/static.js'
66import { parse } from '../src/parse.js' ;
77import { preview } from '../src/preview/index.js' ;
88import { render } from '../src/render.js' ;
@@ -20,7 +20,6 @@ export async function handleRender(source, options) {
2020 let extname = path . extname ( basename ) ;
2121 title = extname ? basename . split ( extname ) [ 0 ] : basename ;
2222 }
23-
2423 let output = await render ( content , {
2524 title,
2625 output : options . output ,
@@ -84,10 +83,26 @@ export async function handleGenerateShape(source) {
8483}
8584
8685export async function handleSetConfig ( field , value ) {
87- config [ field ] = value ;
86+ if ( field === 'css-doodle' ) {
87+ const { result, error } = await fetchCssDoodleSource ( value ) ;
88+ if ( error ) {
89+ return console . error ( error . message ) ;
90+ }
91+ try {
92+ const libPath = path . join ( configDownloadPath , `css-doodle-${ value } .js` ) ;
93+ fs . writeFileSync ( libPath , result ) ;
94+ config [ field ] = libPath ;
95+ } catch ( e ) {
96+ return console . error ( `error: failed to fetch css-doodle@${ value } ` ) ;
97+ }
98+ } else {
99+ config [ field ] = value ;
100+ }
101+
88102 if ( value === '' ) {
89103 delete config [ field ] ;
90104 }
105+
91106 try {
92107 fs . writeFileSync ( configPath , JSON . stringify ( config , null , 2 ) ) ;
93108 console . log ( 'ok' ) ;
@@ -149,3 +164,35 @@ function readFromStdin() {
149164 } ) ;
150165}
151166
167+ async function fetchCssDoodleSource ( version ) {
168+ let result = '' , res , error ;
169+ const messageInvalid = `error: invalid package version '${ version } '` ;
170+
171+ if ( ! ( version === 'latest' || / ^ \d + \. \d + \. \d + $ / . test ( version ) ) ) {
172+ return {
173+ result, error : new Error ( messageInvalid )
174+ }
175+ }
176+
177+ console . log ( `Fetching css-doodle@${ version } ` ) ;
178+
179+ try {
180+ res = await fetch ( `https://esm.sh/css-doodle@${ version } /css-doodle.min.js?raw` , { redirect :'follow' } ) ;
181+ } catch ( error ) {
182+ return {
183+ result, error : new Error ( `error: failed to fetch css-doodle@${ version } ` )
184+ } ;
185+ }
186+
187+ const source = Buffer . from ( await res . arrayBuffer ( ) ) . toString ( ) ;
188+
189+ if ( / ^ i n v a l i d | E R R _ P N P M _ N O _ M A T C H I N G _ V E R S I O N / i. test ( source ) ) {
190+ return {
191+ result, error : new Error ( messageInvalid )
192+ }
193+ }
194+
195+ return {
196+ result : source , error : null
197+ }
198+ }
0 commit comments