jsminifier.pp 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446
  1. { *********************************************************************
  2. This file is part of the Free Component Library (FCL)
  3. Copyright (c) 2016 Michael Van Canneyt.
  4. Javascript minifier
  5. See the file COPYING.FPC, included in this distribution,
  6. for details about the copyright.
  7. This program is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  10. **********************************************************************}
  11. { ---------------------------------------------------------------------
  12. Javascript minifier, based on an implementation by Douglas Crockford,
  13. see original copyright.
  14. ---------------------------------------------------------------------}
  15. { jsmin.c
  16. 2013-03-29
  17. Copyright (c) 2002 Douglas Crockford (www.crockford.com)
  18. Permission is hereby granted, free of charge, to any person obtaining a copy of
  19. this software and associated documentation files (the "Software"), to deal in
  20. the Software without restriction, including without limitation the rights to
  21. use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
  22. of the Software, and to permit persons to whom the Software is furnished to do
  23. so, subject to the following conditions:
  24. The above copyright notice and this permission notice shall be included in all
  25. copies or substantial portions of the Software.
  26. The Software shall be used for Good, not Evil.
  27. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  28. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  29. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  30. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  31. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  32. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  33. SOFTWARE.
  34. }
  35. {$IFNDEF FPC_DOTTEDUNITS}
  36. unit jsminifier;
  37. {$ENDIF FPC_DOTTEDUNITS}
  38. {$mode objfpc}{$H+}
  39. {$inline on}
  40. interface
  41. {$IFDEF FPC_DOTTEDUNITS}
  42. uses System.SysUtils,System.Classes,Fcl.Streams.Buffer;
  43. {$ELSE FPC_DOTTEDUNITS}
  44. uses sysutils,classes,bufstream;
  45. {$ENDIF FPC_DOTTEDUNITS}
  46. Const
  47. EOS = #0;
  48. Type
  49. { TJSONMinifier }
  50. EJSONMinifier = Class(Exception);
  51. TJSONMinifier = Class(TComponent)
  52. Private
  53. FA : AnsiChar;
  54. FB : AnsiChar;
  55. FFileHeader: TStrings;
  56. FLookahead : AnsiChar;
  57. FX : AnsiChar;
  58. FY : AnsiChar ;
  59. Fin : TStream;
  60. Fout : TStream;
  61. procedure SetFileHeader(AValue: TStrings);
  62. Protected
  63. // Token reading routines
  64. function Peek : AnsiChar;
  65. function Get : AnsiChar;inline;
  66. function Next : AnsiChar;
  67. // Token writing routines
  68. procedure Putc(c: AnsiChar);inline;
  69. Procedure Reset;
  70. procedure DoHeader; virtual;
  71. procedure Error(Const Msg: string);
  72. Class Function isAlphaNum(c: AnsiChar): boolean;
  73. Class Function iif(B : Boolean; Const ifTrue,ifFalse : integer) : integer; inline;
  74. procedure Action(d: Byte);
  75. procedure Minify;
  76. Public
  77. Constructor Create(AOwner : TComponent); override;
  78. Destructor Destroy; override;
  79. Procedure Execute(Const SourceFilename,DestFilename : String);
  80. Procedure Execute(Source,Dest : TStream);
  81. Procedure Execute(SourceFilenames : TStrings; Const DestFilename : String);
  82. Procedure Execute(SourceFileNames : Array of string; Const DestFilename : String);
  83. Published
  84. Property FileHeader : TStrings Read FFileHeader Write SetFileHeader;
  85. end;
  86. Implementation
  87. Resourcestring
  88. SErrUnterminatedComment = 'Unterminated comment.';
  89. SErrUnterminatedStringLiteral = 'Unterminated string literal.';
  90. SErrUnterminatedSetInRegexp = 'Unterminated set in Regular Expression literal.';
  91. SerrUnterminatedRegexp = 'Unterminated Regular Expression literal.';
  92. class function TJSONMinifier.iif(B: Boolean; const ifTrue, ifFalse: integer
  93. ): integer;
  94. begin
  95. if B then
  96. Result:=ifTrue
  97. else
  98. Result:=ifFalse;
  99. end;
  100. procedure TJSONMinifier.Error(const Msg: string);
  101. begin
  102. Raise EJSONMinifier.Create('JSMIN Error: '+Msg);
  103. end;
  104. procedure TJSONMinifier.SetFileHeader(AValue: TStrings);
  105. begin
  106. if FFileHeader=AValue then Exit;
  107. FFileHeader.Assign(AValue);
  108. end;
  109. procedure TJSONMinifier.Reset;
  110. begin
  111. FA:=EOS;
  112. FB:=EOS;
  113. FLookahead:=EOS;
  114. FX:=EOS;
  115. FY:=EOS;
  116. end;
  117. class function TJSONMinifier.isAlphaNum(c: AnsiChar): boolean;
  118. begin
  119. Result:= (C in ['a'..'z']) or (c in ['0'..'9']) or (c in ['A'..'Z']) or (C in ['_','$','\']) or (c > #126);
  120. end;
  121. function TJSONMinifier.Get: AnsiChar;
  122. begin
  123. Result:=FLookahead;
  124. FLookahead:=EOS;
  125. if (Result=EOS) then
  126. if Fin.Read(Result,sizeof(Result))=0 then exit;
  127. if (Result>' ') or (Result in [#10,EOS]) then
  128. Exit;
  129. if (Result=#13) then
  130. Result:=#10
  131. else
  132. Result:=' ';
  133. end;
  134. function TJSONMinifier.Peek: AnsiChar;
  135. begin
  136. FLookahead := get();
  137. result:=FLookahead;
  138. end;
  139. function TJSONMinifier.Next: AnsiChar;
  140. var
  141. c : AnsiChar;
  142. begin
  143. c:= get();
  144. if (c='/') then
  145. case peek of
  146. '/': Repeat
  147. c := get();
  148. until (c <= #10);
  149. '*':
  150. begin
  151. Get();
  152. while (c <> ' ') do
  153. case get of
  154. '*':
  155. begin
  156. if (peek()= '/') then
  157. begin
  158. get();
  159. c:=' ';
  160. end;
  161. end;
  162. EOS:
  163. Error(SErrUnterminatedComment);
  164. end;
  165. end;
  166. end;
  167. FY:=FX;
  168. FX:=c;
  169. Result:=c;
  170. end;
  171. procedure TJSONMinifier.Putc(c: AnsiChar);
  172. begin
  173. Fout.writebuffer(c,sizeof(c));
  174. end;
  175. procedure TJSONMinifier.Action(d : Byte);
  176. Procedure Do1;
  177. begin
  178. putc(FA);
  179. if ((FY in [#10,' '])
  180. and (FA in ['+','-','*','/'])
  181. and (FB in ['+','-','*','/'])) then
  182. putc(FY);
  183. end;
  184. Procedure Do2;
  185. begin
  186. FA:=FB;
  187. if (FA in ['''','"','`']) then
  188. While true do
  189. begin
  190. putc(FA);
  191. FA:= get();
  192. if (FA=FB) then
  193. break;
  194. if (FA='\') then
  195. begin
  196. putc(FA);
  197. FA:=get();
  198. end;
  199. if (FA=EOS) then
  200. Error(SErrUnterminatedStringLiteral);
  201. end;
  202. end;
  203. begin
  204. if (D=1) then
  205. Do1;
  206. if (D in [1,2]) then
  207. Do2;
  208. FB := next();
  209. if (FB='/') and (FA in ['(',',','=',':','[','!','&','|','?','+','-','~','*','/','{',#10]) then
  210. begin
  211. putc(FA);
  212. if (FA in ['/','*']) then
  213. putc(' ');
  214. putc(FB);
  215. While true do
  216. begin
  217. FA := get();
  218. if (FA='[') then
  219. begin
  220. While true do
  221. begin
  222. putc(FA);
  223. FA := get();
  224. if (FA = ']') then
  225. break;
  226. if (FA = '\') then
  227. begin
  228. putc(FA);
  229. FA := get();
  230. end;
  231. if (FA = EOS) then
  232. Error(SErrUnterminatedSetInRegexp);
  233. end
  234. end
  235. else if (FA = '/') then
  236. begin
  237. case (peek()) of
  238. '/', '*':
  239. Error(SErrUnterminatedSetInRegexp);
  240. end;
  241. Break;
  242. end
  243. else if (FA ='\') then
  244. begin
  245. putc(FA);
  246. FA := get();
  247. end;
  248. if (FA = EOS) then
  249. Error(SErrUnterminatedRegexp);
  250. putc(FA);
  251. end;
  252. FB := next();
  253. end;
  254. end;
  255. procedure TJSONMinifier.Minify;
  256. begin
  257. if (peek()= #$EF) then
  258. begin
  259. get();
  260. get();
  261. get();
  262. end;
  263. FA:=#10;
  264. action(3);
  265. while (FA <> EOS) do
  266. begin
  267. case (FA) of
  268. ' ':
  269. action(iif(isAlphanum(FB),1,2));
  270. #10:
  271. case (FB) of
  272. '{', '[', '(', '+', '-', '!', '~':
  273. Action(1);
  274. ' ':
  275. Action(3);
  276. else
  277. Action(iif(isAlphanum(FB), 1 , 2));
  278. end;
  279. else
  280. case (FB) of
  281. ' ':
  282. Action(iif(isAlphanum(FA),1,3));
  283. #10:
  284. case (FA) of
  285. '}',']',')','+','-','"', '''', '`':
  286. Action(1);
  287. else
  288. Action(iif(isAlphanum(FA), 1, 3));
  289. end;
  290. else
  291. Action(1);
  292. end;
  293. end;
  294. end;
  295. end;
  296. constructor TJSONMinifier.Create(AOwner: TComponent);
  297. begin
  298. inherited Create(AOwner);
  299. FFileHeader:=TStringList.Create;
  300. end;
  301. destructor TJSONMinifier.Destroy;
  302. begin
  303. FreeAndNil(FFileHeader);
  304. inherited Destroy;
  305. end;
  306. procedure TJSONMinifier.Execute(const SourceFilename, DestFilename: String);
  307. Var
  308. Src,Dest : TBufStream;
  309. begin
  310. Dest:=Nil;
  311. Src:=TReadBufStream.Create(TFileStream.Create(SourceFileName,fmOpenRead or fmShareDenyWrite),1000);
  312. try
  313. Src.SourceOwner:=True;
  314. Dest:=TWriteBufStream.Create(TFileStream.create(DestFileName,fmCreate),1000);
  315. Dest.SourceOwner:=True;
  316. Execute(Src,Dest);
  317. finally
  318. Src.Free;
  319. Dest.Free;
  320. end;
  321. end;
  322. procedure TJSONMinifier.DoHeader;
  323. Var
  324. S,L : String;
  325. begin
  326. For S in FFileHeader do
  327. begin
  328. L:='// '+S+sLineBreak;
  329. Fout.WriteBuffer(L[1],Length(L));
  330. end;
  331. end;
  332. procedure TJSONMinifier.Execute(Source, Dest: TStream);
  333. begin
  334. Fin:=Source;
  335. Fout:=Dest;
  336. try
  337. Reset;
  338. DoHeader;
  339. Minify;
  340. finally
  341. Fin:=Nil;
  342. Fout:=Nil;
  343. end;
  344. end;
  345. procedure TJSONMinifier.Execute(SourceFilenames: TStrings;const DestFilename: String);
  346. Var
  347. Src,Dest : TBufStream;
  348. I : Integer;
  349. begin
  350. Dest:=Src;
  351. Dest:=TWriteBufStream.Create(TFileStream.create(DestFileName,fmCreate),1000);
  352. try
  353. Dest.SourceOwner:=True;
  354. for I:=0 to SourceFileNames.Count-1 do
  355. begin
  356. Src:=TReadBufStream.Create(TFileStream.Create(SourceFileNames[i],fmOpenRead or fmShareDenyWrite),1000);
  357. Src.SourceOwner:=True;
  358. Execute(Src,Dest);
  359. FreeAndNil(Src);
  360. end;
  361. finally
  362. FreeAndNil(Src);
  363. FreeAndNil(Dest);
  364. end;
  365. end;
  366. procedure TJSONMinifier.Execute(SourceFileNames: array of string;
  367. const DestFilename: String);
  368. Var
  369. S : TStrings;
  370. begin
  371. S:=TStringList.Create;
  372. try
  373. S.AddStrings(SourceFileNames);
  374. Execute(S,DestFileName);
  375. finally
  376. S.Free;
  377. end;
  378. end;
  379. end.