-
Notifications
You must be signed in to change notification settings - Fork 791
/
Copy pathclosure.clj
3424 lines (3131 loc) · 141 KB
/
closure.clj
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
; Copyright (c) Rich Hickey. All rights reserved.
; The use and distribution terms for this software are covered by the
; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php)
; which can be found in the file epl-v10.html at the root of this distribution.
; By using this software in any fashion, you are agreeing to be bound by
; the terms of this license.
; You must not remove this notice, or any other, from this software.
(ns cljs.closure
(:refer-clojure :exclude [compile])
(:require [cljs.externs :as externs]
[cljs.util :as util :refer [distinct-by]]
[cljs.core :as cljsm]
[cljs.compiler :as comp]
[cljs.analyzer :as ana]
[cljs.source-map :as sm]
[cljs.env :as env]
[cljs.foreign.node :refer [package-json-entries node-file-seq->libs-spec*]]
[cljs.js-deps :as deps]
[clojure.java.io :as io]
[clojure.java.shell :as sh]
[clojure.reflect]
[clojure.set :as set]
[clojure.string :as string]
[cljs.vendor.clojure.data.json :as json]
[cljs.module-graph :as module-graph])
(:import [java.lang ProcessBuilder]
[java.io
File BufferedReader BufferedInputStream
Writer InputStreamReader IOException StringWriter ByteArrayInputStream]
[java.net URI URL]
[java.util.logging Level]
[java.util List Random HashMap]
[java.util.concurrent
TimeUnit LinkedBlockingDeque Executors CountDownLatch]
[com.google.javascript.jscomp CompilerOptions CompilationLevel
CompilerInput CompilerInput$ModuleType DependencyOptions
CompilerOptions$LanguageMode SourceMap$Format
SourceMap$DetailLevel ClosureCodingConvention SourceFile
Result JSError CheckLevel DiagnosticGroup DiagnosticGroups
CommandLineRunner
JSChunk SourceMap VariableMap PrintStreamErrorManager DiagnosticType
VariableRenamingPolicy PropertyRenamingPolicy]
[com.google.javascript.jscomp.deps ClosureBundler ModuleLoader$ResolutionMode ModuleNames
SimpleDependencyInfo]
[com.google.javascript.rhino Node]
[java.nio.file Path Paths Files StandardWatchEventKinds WatchKey
WatchEvent FileVisitor FileVisitResult FileSystems]
[java.nio.charset Charset StandardCharsets]
[com.sun.nio.file SensitivityWatchEventModifier]))
;; Copied from clojure.tools.gitlibs
(def ^:private GITLIBS-CACHE-DIR
(delay
(.getCanonicalPath
(let [env (System/getenv "GITLIBS")]
(if (string/blank? env)
(io/file (System/getProperty "user.home") ".gitlibs")
(io/file env))))))
(defn- gitlibs-cache-dir
"Returns the gitlibs cache dir, a string."
[]
@GITLIBS-CACHE-DIR)
(defn- gitlibs-src?
"Returns true if the file comes from the gitlibs cache."
[file]
#_(string/starts-with? (util/path file) (gitlibs-cache-dir))
;; NOTE: does not work on first build see CLJS-2765
false)
(def name-chars (map char (concat (range 48 57) (range 65 90) (range 97 122))))
(defn random-char []
(nth name-chars (.nextInt (Random.) (count name-chars))))
(defn random-string [length]
(apply str (take length (repeatedly random-char))))
(defn- sym->var
"Converts a namespaced symbol to a var, loading the requisite namespace if
needed. For use with a function defined under a keyword in opts. The kw and
ex-data arguments are used to form exceptions."
([sym kw]
(sym->var sym kw nil))
([sym kw ex-data]
(let [ns (namespace sym)
_ (when (nil? ns)
(throw
(ex-info (str kw " symbol " sym " is not fully qualified")
(merge ex-data {kw sym
:clojure.error/phase :compilation}))))
var-ns (symbol ns)]
(when (not (find-ns var-ns))
(try
(locking ana/load-mutex
(require var-ns))
(catch Throwable t
(throw (ex-info (str "Cannot require namespace referred by " kw " value " sym)
(merge ex-data {kw sym
:clojure.error/phase :compilation})
t)))))
(find-var sym))))
(defn- opts-fn
"Extracts a function from opts, by default expecting a function value, but
converting from a namespaced symbol if needed."
[kw opts]
(when-let [fn-or-sym (kw opts)]
(cond-> fn-or-sym (symbol? fn-or-sym) (sym->var kw {}))))
;; Closure API
;; ===========
(defmulti js-source-file (fn [_ source] (class source)))
(defmethod js-source-file String [^String name ^String source]
(-> (SourceFile/builder)
(.withPath name)
(.withContent source)
(.build)))
(defmethod js-source-file File [_ ^File source]
(-> (SourceFile/builder)
(.withPath (.toPath source))
(.withCharset StandardCharsets/UTF_8)
(.build)))
(defmethod js-source-file URL [_ ^URL source]
(js-source-file _ (io/file (.getPath source))))
(defmethod js-source-file BufferedInputStream [^String name ^BufferedInputStream source]
(-> (SourceFile/builder)
(.withPath name)
(.withContent source)
(.build)))
(def check-level
{:error CheckLevel/ERROR
:warning CheckLevel/WARNING
:off CheckLevel/OFF})
(def warning-types
{:access-controls DiagnosticGroups/ACCESS_CONTROLS
:analyzer-checks DiagnosticGroups/ANALYZER_CHECKS
:check-regexp DiagnosticGroups/CHECK_REGEXP
:check-types DiagnosticGroups/CHECK_TYPES
:check-useless-code DiagnosticGroups/CHECK_USELESS_CODE
:check-variables DiagnosticGroups/CHECK_VARIABLES
:closure-dep-method-usage-checks DiagnosticGroups/CLOSURE_DEP_METHOD_USAGE_CHECKS
:conformance-violations DiagnosticGroups/CONFORMANCE_VIOLATIONS
:const DiagnosticGroups/CONST
:constant-property DiagnosticGroups/CONSTANT_PROPERTY
:debugger-statement-present DiagnosticGroups/DEBUGGER_STATEMENT_PRESENT
:deprecated DiagnosticGroups/DEPRECATED
:deprecated-annotations DiagnosticGroups/DEPRECATED_ANNOTATIONS
:duplicate-message DiagnosticGroups/DUPLICATE_MESSAGE
:duplicate-vars DiagnosticGroups/DUPLICATE_VARS
:es5-strict DiagnosticGroups/ES5_STRICT
:externs-validation DiagnosticGroups/EXTERNS_VALIDATION
:extra-require DiagnosticGroups/EXTRA_REQUIRE
:function-params DiagnosticGroups/FUNCTION_PARAMS
:global-this DiagnosticGroups/GLOBAL_THIS
:invalid-casts DiagnosticGroups/INVALID_CASTS
:j2cl-checks DiagnosticGroups/J2CL_CHECKS
:jsdoc-missing-type DiagnosticGroups/JSDOC_MISSING_TYPE
:late-provide DiagnosticGroups/LATE_PROVIDE
:lint-checks DiagnosticGroups/LINT_CHECKS
:message-descriptions DiagnosticGroups/MESSAGE_DESCRIPTIONS
:misplaced-msg-annotation DiagnosticGroups/MISPLACED_MSG_ANNOTATION
:misplaced-type-annotation DiagnosticGroups/MISPLACED_TYPE_ANNOTATION
:missing-override DiagnosticGroups/MISSING_OVERRIDE
:missing-polyfill DiagnosticGroups/MISSING_POLYFILL
:missing-properties DiagnosticGroups/MISSING_PROPERTIES
:missing-provide DiagnosticGroups/MISSING_PROVIDE
:missing-require DiagnosticGroups/MISSING_REQUIRE
:missing-return DiagnosticGroups/MISSING_RETURN
:missing-sources-warnings DiagnosticGroups/MISSING_SOURCES_WARNINGS
:module-load DiagnosticGroups/MODULE_LOAD
:msg-conventions DiagnosticGroups/MSG_CONVENTIONS
:non-standard-jsdoc DiagnosticGroups/NON_STANDARD_JSDOC
:report-unknown-types DiagnosticGroups/REPORT_UNKNOWN_TYPES
:strict-missing-properties DiagnosticGroups/STRICT_MISSING_PROPERTIES
:strict-module-dep-check DiagnosticGroups/STRICT_MODULE_DEP_CHECK
:strict-requires DiagnosticGroups/STRICT_REQUIRES
:suspicious-code DiagnosticGroups/SUSPICIOUS_CODE
:too-many-type-params DiagnosticGroups/TOO_MANY_TYPE_PARAMS
:tweaks DiagnosticGroups/TWEAKS
:type-invalidation DiagnosticGroups/TYPE_INVALIDATION
:undefined-variables DiagnosticGroups/UNDEFINED_VARIABLES
:underscore DiagnosticGroups/UNDERSCORE
:unknown-defines DiagnosticGroups/UNKNOWN_DEFINES
:unused-local-variable DiagnosticGroups/UNUSED_LOCAL_VARIABLE
:unused-private-property DiagnosticGroups/UNUSED_PRIVATE_PROPERTY
:violated-module-dep DiagnosticGroups/VIOLATED_MODULE_DEP
:visibility DiagnosticGroups/VISIBILITY})
(def known-opts
"Set of all known compiler options."
#{:anon-fn-naming-policy :asset-path :cache-analysis :closure-defines :closure-extra-annotations
:closure-warnings :compiler-stats :dump-core :elide-asserts :externs :foreign-libs
:hashbang :language-in :language-out :libs :main :modules :source-map-path :source-map-asset-path
:optimizations :optimize-constants :output-dir :output-to :output-wrapper :parallel-build :preamble
:pretty-print :print-input-delimiter :pseudo-names :recompile-dependents :source-map
:source-map-inline :source-map-timestamp :static-fns :target :verbose :warnings
:emit-constants :ups-externs :ups-foreign-libs :ups-libs :warning-handlers :preloads
:browser-repl :cache-analysis-format :infer-externs :closure-generate-exports :npm-deps
:fn-invoke-direct :checked-arrays :closure-module-roots :rewrite-polyfills :use-only-custom-externs
:watch :watch-error-fn :watch-fn :install-deps :process-shim :rename-prefix :rename-prefix-namespace
:closure-variable-map-in :closure-property-map-in :closure-variable-map-out :closure-property-map-out
:stable-names :ignore-js-module-exts :opts-cache :aot-cache :elide-strict :fingerprint :spec-skip-macros
:nodejs-rt :target-fn :deps-cmd :bundle-cmd :global-goog-object&array :node-modules-dirs})
(def string->charset
{"iso-8859-1" StandardCharsets/ISO_8859_1
"us-ascii" StandardCharsets/US_ASCII
"utf-16" StandardCharsets/UTF_16
"utf-16be" StandardCharsets/UTF_16BE
"utf-16le" StandardCharsets/UTF_16LE
"utf-8" StandardCharsets/UTF_8})
(defn to-charset [charset]
(cond
(instance? Charset charset) charset
(and (string? charset)
(contains? string->charset (string/lower-case charset)))
(get string->charset (string/lower-case charset))
:else
(throw
(ex-info
(str "Invalid :closure-output-charset " charset " given, only "
(string/join ", " (keys string->charset)) " supported ")
{:clojure.error/phase :compilation}))))
(def lang-level
[:ecmascript3 :ecmascript5 :ecmascript5-strict :ecmascript6 :ecmascript6-strict
:ecmascript8
:ecmascript-2015 :ecmascript-2016 :ecmascript-2017 :ecmascript-2018
:ecmascript-2019 :ecmascript-2020 :ecmascript-2021 :ecmascript-next
:no-transpile])
(defn expand-lang-key [key]
(keyword (string/replace (name key) #"^es" "ecmascript")))
(defn ^CompilerOptions$LanguageMode lang-key->lang-mode [key]
(case (expand-lang-key key)
:no-transpile CompilerOptions$LanguageMode/NO_TRANSPILE ;; same mode as input (for language-out only)
:ecmascript3 CompilerOptions$LanguageMode/ECMASCRIPT3
:ecmascript5 CompilerOptions$LanguageMode/ECMASCRIPT5
:ecmascript5-strict CompilerOptions$LanguageMode/ECMASCRIPT5_STRICT
:ecmascript6 CompilerOptions$LanguageMode/ECMASCRIPT_2015 ;; (deprecated and remapped)
:ecmascript6-strict CompilerOptions$LanguageMode/ECMASCRIPT_2015 ;; (deprecated and remapped)
:ecmascript8 CompilerOptions$LanguageMode/ECMASCRIPT_2017
:ecmascript-2015 CompilerOptions$LanguageMode/ECMASCRIPT_2015
:ecmascript-2016 CompilerOptions$LanguageMode/ECMASCRIPT_2016
:ecmascript-2017 CompilerOptions$LanguageMode/ECMASCRIPT_2017
:ecmascript-2018 CompilerOptions$LanguageMode/ECMASCRIPT_2018
:ecmascript-2019 CompilerOptions$LanguageMode/ECMASCRIPT_2019
:ecmascript-2020 CompilerOptions$LanguageMode/ECMASCRIPT_2020
:ecmascript-2021 CompilerOptions$LanguageMode/ECMASCRIPT_2021
:ecmascript-next CompilerOptions$LanguageMode/ECMASCRIPT_NEXT))
(defn set-options
"TODO: Add any other options that we would like to support."
[opts ^CompilerOptions compiler-options]
(.setModuleResolutionMode compiler-options ModuleLoader$ResolutionMode/NODE)
(when (contains? opts :pretty-print)
(.setPrettyPrint compiler-options (:pretty-print opts)))
(when (contains? opts :pseudo-names)
(set! (.generatePseudoNames compiler-options) (:pseudo-names opts)))
(when-let [lang-key (:language-in opts :ecmascript-next)]
(.setLanguageIn compiler-options (lang-key->lang-mode lang-key)))
(when-let [lang-key (:language-out opts)]
(.setLanguageOut compiler-options (lang-key->lang-mode lang-key)))
(when (contains? opts :print-input-delimiter)
(set! (.printInputDelimiter compiler-options)
(:print-input-delimiter opts)))
(when (contains? opts :closure-warnings)
(doseq [[type level] (:closure-warnings opts)]
(. compiler-options
(setWarningLevel (type warning-types) (level check-level)))))
(when (contains? opts :closure-extra-annotations)
(. compiler-options
(setExtraAnnotationNames (map name (:closure-extra-annotations opts)))))
(when (contains? opts :closure-module-roots)
(. compiler-options
(setModuleRoots (:closure-module-roots opts))))
(when (contains? opts :closure-generate-exports)
(. compiler-options
(setGenerateExports (:closure-generate-exports opts))))
(when (contains? opts :rewrite-polyfills)
(. compiler-options
(setRewritePolyfills (:rewrite-polyfills opts))))
(when (contains? opts :rename-prefix)
(. compiler-options
(setRenamePrefix (:rename-prefix opts))))
(when (contains? opts :rename-prefix-namespace)
(. compiler-options
(setRenamePrefixNamespace (:rename-prefix-namespace opts))))
(when (contains? opts :closure-variable-map-in)
(let [var-in (io/file (:closure-variable-map-in opts))]
(when (.exists var-in)
(.setInputVariableMap compiler-options
(VariableMap/load (.getAbsolutePath var-in))))))
(when (contains? opts :closure-property-map-in)
(let [prop-in (io/file (:closure-property-map-in opts))]
(when (.exists prop-in)
(.setInputPropertyMap compiler-options
(VariableMap/load (.getAbsolutePath prop-in))))))
(. compiler-options
(setOutputCharset (to-charset (:closure-output-charset opts "UTF-8"))) ;; only works > 20160125 Closure Compiler
)
compiler-options)
(defn ^CompilerOptions make-options
"Create a CompilerOptions object and set options from opts map."
[opts]
(let [level (case (:optimizations opts)
:advanced CompilationLevel/ADVANCED_OPTIMIZATIONS
:whitespace CompilationLevel/WHITESPACE_ONLY
:simple CompilationLevel/SIMPLE_OPTIMIZATIONS)
compiler-options (doto (CompilerOptions.)
(.setCodingConvention (ClosureCodingConvention.)))]
(doseq [[key val] (:closure-defines opts)]
(let [key (name key)]
(cond
(string? val) (.setDefineToStringLiteral compiler-options key val)
(number? val) (.setDefineToDoubleLiteral compiler-options key val)
(or (true? val)
(false? val)) (.setDefineToBooleanLiteral compiler-options key val)
:else (println "value for" key "must be string, int, float, or bool"))))
(if-let [extra-annotations (:closure-extra-annotations opts)]
(. compiler-options (setExtraAnnotationNames (map name extra-annotations))))
(when (:source-map opts)
(if (:modules opts)
;; name is not actually used by Closure in :modules case,
;; but we need to provide _something_ for Closure to not
;; complain
(.setSourceMapOutputPath compiler-options
(str (io/file (util/output-directory opts)
"cljs_modules.map")))
(.setSourceMapOutputPath compiler-options
(:source-map opts)))
(.setSourceMapDetailLevel compiler-options SourceMap$DetailLevel/ALL)
(.setSourceMapFormat compiler-options SourceMap$Format/V3))
(do
(.setOptionsForCompilationLevel level compiler-options)
(set-options opts compiler-options)
compiler-options)))
(defn load-externs
"Externs are JavaScript files which contain empty definitions of
functions which will be provided by the environment. Any function in
an extern file will not be renamed during optimization.
Options may contain an :externs key with a list of file paths to
load. The :use-only-custom-externs flag may be used to indicate that
the default externs should be excluded."
[{:keys [externs use-only-custom-externs target ups-externs infer-externs] :as opts}]
(let [validate (fn validate [p us]
(if (empty? us)
(throw (util/compilation-error (IllegalArgumentException.
(str "Extern " p " does not exist"))))
us))
filter-cp-js (fn [paths]
(for [p paths
u (deps/find-js-classpath p)]
u))
filter-js (fn [paths]
(for [p paths
u (deps/find-js-resources p)]
u))
add-target (fn [ext]
(cons (io/resource "cljs/externs.js")
(if (= :nodejs target)
(cons (io/resource "cljs/nodejs_externs.js")
(or ext []))
ext)))
load-js (fn [ext]
(map #(js-source-file (.getFile %) (slurp %)) ext))]
(let [js-sources (-> externs filter-js add-target load-js)
ups-sources (-> ups-externs filter-cp-js load-js)
all-sources (vec (concat js-sources ups-sources))]
(cond->
(if use-only-custom-externs
all-sources
(into all-sources (externs/default-externs)))
infer-externs
(conj (js-source-file nil
(io/file (util/output-directory opts) "inferred_externs.js")))))))
(defn ^com.google.javascript.jscomp.Compiler make-closure-compiler []
(let [compiler (com.google.javascript.jscomp.Compiler.)]
(com.google.javascript.jscomp.Compiler/setLoggingLevel Level/WARNING)
compiler))
(defn report-failure [^Result result]
(let [errors (.errors result)
warnings (.warnings result)]
(binding [*out* *err*]
(doseq [next (seq errors)]
(println "ERROR:" (.toString ^JSError next)))
(doseq [next (seq warnings)]
(println "WARNING:" (.toString ^JSError next)))
(when (seq errors)
(throw (util/compilation-error (Exception. "Closure compilation failed")))))))
;; Protocols for IJavaScript and Compilable
;; ========================================
(defprotocol ISourceMap
(-source-url [this] "Return the CLJS source url")
(-source-map [this] "Return the CLJS compiler generated JS source mapping"))
(extend-protocol deps/IJavaScript
String
(-foreign? [this] false)
(-closure-lib? [this] false)
(-url
([this] nil)
([this _] nil))
(-relative-path
([this] nil)
([this _] nil))
(-provides [this]
(let [{:keys [provides]} (deps/parse-js-ns (string/split-lines this))]
(cond-> provides
(empty? provides)
(conj (util/content-sha this 7)))))
(-requires [this] (:requires (deps/parse-js-ns (string/split-lines this))))
(-source
([this] this)
([this _] this))
clojure.lang.IPersistentMap
(-foreign? [this] (:foreign this))
(-closure-lib? [this] (:closure-lib this))
(-url
([this] (deps/-url this nil))
([this opts]
(let [[url file] (if-let [url-min (and (#{:advanced :simple} (:optimizations opts))
(:url-min this))]
[url-min (:file-min this)]
[(:url this) (:file this)])]
(or url (deps/to-url file)))))
(-relative-path
([this] (deps/-relative-path this nil))
([this opts]
(let [file (if-let [file-min (and (#{:advanced :simple} (:optimizations opts))
(:file-min this))]
file-min
(:file this))
as-file (io/as-file file)]
(when (and as-file (not (.isAbsolute as-file)))
file))))
(-provides [this] (map name (:provides this)))
(-requires [this] (map name (:requires this)))
(-source
([this] (deps/-source this nil))
([this opts]
(if-let [s (:source this)]
s
(with-open [reader (io/reader (deps/-url this opts))]
(slurp reader))))))
(defrecord JavaScriptFile [foreign ^URL url ^URL source-url provides requires lines source-map]
deps/IJavaScript
(-foreign? [this] foreign)
(-closure-lib? [this] (:closure-lib this))
(-url [this] url)
(-url [this opts] url)
(-relative-path [this] nil)
(-relative-path [this opts] nil)
(-provides [this] provides)
(-requires [this] requires)
(-source [this] (deps/-source this nil))
(-source [this opts]
(with-open [reader (io/reader url)]
(slurp reader)))
ISourceMap
(-source-url [this] source-url)
(-source-map [this] source-map))
(defn javascript-file
([foreign ^URL url provides requires]
(javascript-file foreign url nil provides requires nil nil))
([foreign ^URL url source-url provides requires lines source-map]
(assert (first provides) (str source-url " does not provide a namespace"))
(JavaScriptFile. foreign url source-url (map name provides) (map name requires) lines source-map)))
(defn map->javascript-file [m]
(merge
(javascript-file
(:foreign m)
(when-let [f (or (:file m) (:url m))]
(deps/to-url f))
(when-let [sf (:source-file m)]
(deps/to-url sf))
(:provides m)
(:requires m)
(:lines m)
(:source-map m))
(when-let [source-file (:source-file m)]
{:source-file source-file})
(when-let [out-file (:out-file m)]
{:out-file out-file})
(when (:closure-lib m)
{:closure-lib true})
(when-let [module (:module m)]
{:module module})
(when-let [lang (:lang m)]
{:lang lang})
(when-let [ns (:ns m)]
{:ns ns})
(when (:macros-ns m)
{:macros-ns true})))
(defn read-js
"Read a JavaScript file returning a map of file information."
[f]
(let [source (slurp f)
m (deps/parse-js-ns (string/split-lines source))]
(map->javascript-file (assoc m :file f))))
;; Compile
;; =======
(defprotocol Inputs
(-paths [this] "Returns the file paths to the source inputs"))
(extend-protocol Inputs
String
(-paths [this] [(io/file this)])
File
(-paths [this] [this]))
(defprotocol Compilable
(-compile [this opts] "Returns one or more IJavaScripts.")
(-find-sources [this opts] "Returns one or more IJavascripts, without compiling them."))
(defn compilable-input-paths
"Takes a coll of inputs as strings or files and returns a
single Inputs and Compilable object."
[paths]
(reify
cljs.closure/Inputs
(-paths [_]
(mapcat cljs.closure/-paths paths))
cljs.closure/Compilable
(-compile [_ opts]
(mapcat #(cljs.closure/-compile % opts)
paths))
(-find-sources [_ opts]
(mapcat #(cljs.closure/-find-sources % opts)
paths))))
(defn compile-form-seq
"Compile a sequence of forms to a JavaScript source string."
([forms]
(compile-form-seq forms
(when env/*compiler*
(:options @env/*compiler*))))
([forms opts]
(comp/with-core-cljs opts
(fn []
(with-out-str
(binding [ana/*cljs-ns* 'cljs.user]
(doseq [form forms]
(comp/emit (ana/analyze (ana/empty-env) form)))))))))
(defn compiled-file
"Given a map with at least a :file key, return a map with
{:file .. :provides .. :requires ..}.
Compiled files are cached so they will only be read once."
[m]
(let [path (.getPath (.toURL ^File (:file m)))
js (if (:provides m)
(map->javascript-file m)
(if-let [js (get-in @env/*compiler* [::compiled-cljs path])]
js
(read-js (:file m))))]
(swap! env/*compiler* update-in [::compiled-cljs] assoc path js)
js))
(defn compile
"Given a Compilable, compile it and return an IJavaScript."
[compilable opts]
(-compile compilable opts))
(def ^:private USER-HOME-WRITABLE
(delay (.canWrite (io/file (System/getProperty "user.home")))))
(defn- aot-cache? [opts]
"Returns true if compilation artifacts shuold be placed in the
shared AOT cache."
(and (:aot-cache opts)
@USER-HOME-WRITABLE))
(defn- copy-from-cache
[cache-path cacheable source-file opts]
(doseq [[k ^File f] cacheable]
(when (.exists f)
(let [target (io/file (util/output-directory opts)
(-> (.getAbsolutePath f)
(string/replace (.getAbsolutePath cache-path) "")
(subs 1)))]
(when (and (or ana/*verbose* (:verbose opts)) (= :output-file k))
(util/debug-prn (str "Copying cached " f " to " target)))
(util/mkdirs target)
(spit target (slurp f))
(.setLastModified target (util/last-modified source-file))))))
(defn find-sources
"Given a Compilable, find sources and return a sequence of IJavaScript."
[compilable opts]
(-find-sources compilable opts))
(defn compile-file
"Compile a single cljs file. If no output-file is specified, returns
a string of compiled JavaScript. With an output-file option, the
compiled JavaScript will written to this location and the function
returns a JavaScriptFile. In either case the return value satisfies
IJavaScript."
[^File file {:keys [output-file] :as opts}]
(if output-file
(let [out-file (io/file (util/output-directory opts) output-file)]
(if (and (aot-cache? opts)
(gitlibs-src? file))
(let [cacheable (ana/cacheable-files file (util/ext file) opts)
cache-path (ana/cache-base-path (util/path file) opts)]
(if (not (.exists (:output-file cacheable)))
(let [ret (compiled-file (comp/compile-file file (:output-file cacheable)
(assoc opts :output-dir (util/path cache-path))))]
(copy-from-cache cache-path cacheable file opts)
ret)
(do
(when-not (.exists out-file)
(copy-from-cache cache-path cacheable file opts))
(compiled-file (comp/compile-file file (.toString out-file) opts)))))
(compiled-file (comp/compile-file file (.toString out-file) opts))))
(let [path (.getPath ^File file)]
(binding [ana/*cljs-file* path]
(with-open [rdr (io/reader file)]
(compile-form-seq (ana/forms-seq* rdr path)))))))
(defn compile-dir
"Recursively compile all cljs files under the given source
directory. Return a list of JavaScriptFiles."
[^File src-dir opts]
(let [out-dir (util/output-directory opts)]
(map compiled-file
(comp/compile-root src-dir out-dir opts))))
(defn ^String path-from-jarfile
"Given the URL of a file within a jar, return the path of the file
from the root of the jar."
[^URL url]
(last (string/split (.getFile url) #"\.jar!/")))
(defn jar-file-to-disk
"Copy a file contained within a jar to disk. Return the created file."
([url out-dir]
(jar-file-to-disk url out-dir
(when env/*compiler*
(:options @env/*compiler*))))
([url out-dir opts]
(let [out-file (io/file out-dir (path-from-jarfile url))
content (with-open [reader (io/reader url)]
(slurp reader))]
(when (and url (or ana/*verbose* (:verbose opts)))
(util/debug-prn "Copying" (str url) "to" (str out-file)))
(util/mkdirs out-file)
(spit out-file content)
(.setLastModified ^File out-file (util/last-modified url))
out-file)))
(defn compile-from-jar
"Compile a file from a jar if necessary. Returns IJavaScript."
[jar-file {:keys [output-file] :as opts}]
(let [out-file (when output-file
(io/file (util/output-directory opts) output-file))
cacheable (ana/cacheable-files jar-file (util/ext jar-file) opts)]
(when (or (nil? out-file)
(comp/requires-compilation? jar-file out-file opts))
;; actually compile from JAR
(if (not (aot-cache? opts))
(-compile (jar-file-to-disk jar-file (util/output-directory opts) opts) opts)
(let [cache-path (ana/cache-base-path (util/path jar-file) opts)]
(when (comp/requires-compilation? jar-file (:output-file cacheable) opts)
(-compile (jar-file-to-disk jar-file cache-path opts)
(assoc opts :output-dir (util/path cache-path))))
(copy-from-cache cache-path cacheable jar-file opts))))
;; Files that don't require compilation (cljs.loader for example)
;; need to be copied from JAR to disk.
(when (or (nil? out-file)
(not (.exists out-file)))
(jar-file-to-disk jar-file (util/output-directory opts) opts))
;; have to call compile-file as it includes more IJavaScript
;; information than ana/parse-ns for now
(compile-file
(io/file (util/output-directory opts)
(last (string/split (.getPath ^URL jar-file) #"\.jar!/")))
opts)))
(defn find-jar-sources [this opts]
[(comp/find-source this)])
(extend-protocol Compilable
File
(-compile [this opts]
(if (.isDirectory this)
(compile-dir this opts)
(compile-file this opts)))
(-find-sources [this _]
(if (.isDirectory this)
(comp/find-root-sources this)
[(comp/find-source this)]))
URL
(-compile [this opts]
(case (.getProtocol this)
"file" (-compile (io/file this) opts)
"jar" (compile-from-jar this opts)))
(-find-sources [this opts]
(case (.getProtocol this)
"file" (-find-sources (io/file this) opts)
"jar" (find-jar-sources this opts)))
clojure.lang.PersistentList
(-compile [this opts]
(compile-form-seq [this]))
(-find-sources [this opts]
[(ana/parse-ns [this] opts)])
String
(-compile [this opts] (-compile (io/file this) opts))
(-find-sources [this opts] (-find-sources (io/file this) opts))
clojure.lang.Symbol
(-compile [this opts]
(-compile (util/ns->source this) opts))
(-find-sources [this opts]
(-find-sources (util/ns->source this) opts))
clojure.lang.PersistentVector
(-compile [this opts] (compile-form-seq this))
(-find-sources [this opts]
[(ana/parse-ns this opts)])
clojure.lang.IPersistentSet
(-compile [this opts]
(doall (map (comp #(-compile % opts) util/ns->source) this)))
(-find-sources [this opts]
(into [] (mapcat #(-find-sources % opts)) this))
)
(comment
;; compile a file in memory
(-compile "samples/hello/src/hello/core.cljs" {})
(-find-sources "samples/hello/src/hello/core.cljs" {})
;; compile a file to disk - see file @ 'out/clojure/set.js'
(-compile (io/resource "clojure/set.cljs") {:output-file "clojure/set.js"})
(-find-sources (io/resource "clojure/set.cljs") {:output-file "clojure/set.js"})
;; compile a project
(-compile (io/file "samples/hello/src") {})
(-find-sources (io/file "samples/hello/src") {})
;; compile a project with a custom output directory
(-compile (io/file "samples/hello/src") {:output-dir "my-output"})
(-find-sources (io/file "samples/hello/src") {:output-dir "my-output"})
;; compile a form
(-compile '(defn plus-one [x] (inc x)) {})
;; compile a vector of forms
(-compile '[(ns test.app (:require [goog.array :as array]))
(defn plus-one [x] (inc x))]
{})
(-find-sources 'cljs.core {})
)
(defn js-dependencies
"Given a sequence of Closure namespace strings, return the list of
all dependencies. The returned list includes all Google and
third-party library dependencies.
Third-party libraries are configured using the :libs option where
the value is a list of directories containing third-party
libraries."
[opts requires]
(loop [requires requires
visited (set requires)
deps #{}]
(if (seq requires)
(let [node (or (get (@env/*compiler* :js-dependency-index) (first requires))
(deps/find-classpath-lib (first requires)))
new-req (remove #(contains? visited %)
(into (:requires node) (:require-types node)))]
(recur (into (rest requires) new-req)
(into visited new-req)
(conj deps node)))
(remove nil? deps))))
(comment
;; find dependencies
(binding [env/*compiler* (env/default-compiler-env)]
(js-dependencies {} ["goog.array"]))
;; find dependencies in an external library
(binding [env/*compiler* (env/default-compiler-env)]
(js-dependencies {:libs ["closure/library/third_party/closure"]} ["goog.dom.query"]))
(binding [env/*compiler* (env/default-compiler-env)]
(js-dependencies {} ["goog.math.Long"]))
(binding [env/*compiler* (env/default-compiler-env)]
(js-dependencies {} ["goog.string.StringBuffer"]))
)
(defn add-core-macros-if-cljs-js
"If a compiled entity is the cljs.js namespace, explicitly
add the cljs.core macros namespace dependency to it."
[compiled]
(cond-> compiled
;; TODO: IJavaScript :provides :requires should really
;; always be Vector<MungedString> - David
(= ["cljs.js"] (into [] (map str) (deps/-provides compiled)))
(update-in [:requires] concat ["cljs.core$macros"])))
(defn get-compiled-cljs
"Return an IJavaScript for this file. Compiled output will be
written to the working directory."
[opts {:keys [relative-path uri]}]
(let [js-file (comp/rename-to-js relative-path)
compiled (-compile uri (merge opts {:output-file js-file}))]
(add-core-macros-if-cljs-js compiled)))
(defn cljs-source-for-namespace
"Given a namespace return the corresponding source with either a .cljs or
.cljc extension."
[ns]
(if (= "cljs.core$macros" (str ns))
(let [relpath "cljs/core.cljc"]
{:relative-path relpath :uri (io/resource relpath) :ext :cljc})
(let [path (-> (munge ns) (string/replace \. \/))
relpath (str path ".cljs")]
(if-let [res (io/resource relpath)]
{:relative-path relpath :uri res :ext :cljs}
(let [relpath (str path ".cljc")]
(if-let [res (io/resource relpath)]
{:relative-path relpath :uri res :ext :cljc}))))))
(defn source-for-namespace
"Given a namespace and compilation environment return the relative path and
uri of the corresponding source regardless of the source language extension:
.cljs, .cljc, .js"
[ns compiler-env]
(let [ns-str (str (comp/munge ns {}))
path (string/replace ns-str \. \/)
relpath (str path ".cljs")]
(if-let [cljs-res (io/resource relpath)]
{:relative-path relpath :uri cljs-res :ext :cljs}
(let [relpath (str path ".cljc")]
(if-let [cljc-res (io/resource relpath)]
{:relative-path relpath :uri cljc-res :ext :cljc}
(let [relpath (str path ".js")]
(if-let [js-res (io/resource relpath)]
{:relative-path relpath :uri js-res :ext :js}
(let [ijs (get-in @compiler-env [:js-dependency-index (str ns)])
relpath (or (:file ijs) (:url ijs))]
(if-let [js-res (and relpath
;; try to parse URL, otherwise just return local
;; resource
(or (and (util/url? relpath) relpath)
(try (URL. relpath) (catch Throwable t))
(io/resource relpath)))]
{:relative-path relpath :uri js-res :ext :js}
(throw
(util/compilation-error
(IllegalArgumentException.
(str "Namespace " ns " does not exist."
(when (string/includes? ns "-")
" Please check that namespaces with dashes use underscores in the ClojureScript file name."))))))))))))))
(defn cljs-dependencies
"Given a list of all required namespaces, return a list of
IJavaScripts which are the cljs dependencies. The returned list will
not only include the explicitly required files but any transitive
dependencies as well. JavaScript files will be compiled to the
working directory if they do not already exist.
Only load dependencies from the classpath."
[opts requires]
(letfn [(cljs-deps [lib-names]
(->> lib-names
(remove #(or ((@env/*compiler* :js-dependency-index) %)
(deps/find-classpath-lib %)))
(map cljs-source-for-namespace)
(remove (comp nil? :uri))))]
(loop [required-files (cljs-deps requires)
visited (set required-files)
js-deps #{}]
(if (seq required-files)
(let [next-file (first required-files)
js (get-compiled-cljs opts next-file)
new-req (remove #(contains? visited %) (cljs-deps (deps/-requires js)))]
(recur (into (rest required-files) new-req)
(into visited new-req)
(conj js-deps js)))
(disj js-deps nil)))))
(comment
;; only get cljs deps
(cljs-dependencies {} ["goog.string" "cljs.core"])
;; get transitive deps
(cljs-dependencies {} ["clojure.string"])
;; don't get cljs.core twice
(cljs-dependencies {} ["cljs.core" "clojure.string"])
)
(defn find-cljs-dependencies
"Given set of cljs namespace symbols, find IJavaScript objects for the namespaces."
[requires]
(letfn [(cljs-deps [namespaces]
(->> namespaces
(remove #(or ((@env/*compiler* :js-dependency-index) %)
(deps/find-classpath-lib %)))
(map cljs-source-for-namespace)
(remove (comp nil? :uri))))]
(loop [required-files (cljs-deps requires)
visited (set required-files)
cljs-namespaces #{}]
(if (seq required-files)
(let [next-file (first required-files)
ns-info (ana/parse-ns (:uri next-file))
new-req (remove #(contains? visited %) (cljs-deps (cond-> (deps/-requires ns-info)
(= 'cljs.js (:ns ns-info)) (conj "cljs.core$macros"))))]
(recur (into (rest required-files) new-req)
(into visited new-req)
(conj cljs-namespaces ns-info)))
(disj cljs-namespaces nil)))))
(defn- constants-filename
"Returns the filename of the constants table."
[opts]
(str (util/output-directory opts) File/separator
(string/replace (str ana/constants-ns-sym) "." File/separator) ".js"))
(defn- constants-javascript-file
"Returns the constants table as a JavaScriptFile."
[opts]
(let [url (deps/to-url (constants-filename opts))]
(javascript-file nil url [(str ana/constants-ns-sym)] ["cljs.core"])))
(defn add-dependencies
"DEPRECATED: Given one or more IJavaScript objects in dependency order, produce
a new sequence of IJavaScript objects which includes the input list
plus all dependencies in dependency order."
[opts & inputs]
(let [inputs (set inputs)
requires (set (mapcat deps/-requires inputs))
required-cljs (clojure.set/difference (cljs-dependencies opts requires) inputs)
required-js (js-dependencies opts
(into (set (mapcat deps/-requires required-cljs)) requires))]
(cons
(javascript-file nil (io/resource "goog/base.js") ["goog"] nil)
(deps/dependency-order
(concat
(map
(fn [{:keys [type foreign url file provides requires] :as js-map}]
;; ignore :seed inputs, only for REPL - David
(if (not= :seed type)
(let [url (or url (io/resource file))]
(merge
(javascript-file foreign url provides requires)
js-map))
js-map))