-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathdomado.js
7487 lines (7022 loc) · 288 KB
/
domado.js
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) 2008-2012 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview
* A partially tamed browser object model based on
* <a href="http://www.w3.org/TR/DOM-Level-2-HTML/Overview.html"
* >DOM-Level-2-HTML</a> and specifically, the
* <a href="http://www.w3.org/TR/DOM-Level-2-HTML/ecma-script-binding.html"
* >ECMAScript Language Bindings</a>.
*
* Caveats:<ul>
* <li>Security Review is pending.
* <li><code>===</code> and <code>!==</code> on node lists will not
* behave the same as with untamed node lists. Specifically, it is
* not always true that {@code nodeA.childNodes === nodeA.childNodes}.
* </ul>
*
* <p>
* TODO(ihab.awad): Our implementation of getAttribute (and friends)
* is such that standard DOM attributes which we disallow for security
* reasons (like 'form:enctype') are placed in the "virtual" attributes
* map (the data-caja-* namespace). They appear to be settable and gettable,
* but their values are ignored and do not have the expected semantics
* per the DOM API. This is because we do not have a column in
* html4-defs.js stating that an attribute is valid but explicitly
* blacklisted. Alternatives would be to always throw upon access to
* these attributes; to make them always appear to be null; etc. Revisit
* this decision if needed.
*
* @author mikesamuel@gmail.com (original Domita)
* @author kpreid@switchb.org (port to ES5)
* @requires console, Uint8ClampedArray
* @requires bridalMaker, cajaVM, cssSchema, lexCss, URI, unicode
* @requires parseCssDeclarations, sanitizeCssProperty, sanitizeCssSelectorList
* @requires html, html4, htmlSchema
* @requires WeakMap, Proxy
* @requires HtmlEmitter
* @provides Domado
* @overrides window
*/
// The Turkish i seems to be a non-issue, but abort in case it is.
if ('I'.toLowerCase() !== 'i') { throw 'I/i problem'; }
var Domado = (function() {
'use strict';
var isVirtualizedElementName = htmlSchema.isVirtualizedElementName;
var realToVirtualElementName = htmlSchema.realToVirtualElementName;
var virtualToRealElementName = htmlSchema.virtualToRealElementName;
var cajaPrefix = 'data-caja-';
var cajaPrefRe = new RegExp('^' + cajaPrefix);
// From RFC3986
var URI_SCHEME_RE = new RegExp(
'^' +
'(?:' +
'([^:\/?# ]+)' + // scheme
':)?'
);
var ALLOWED_URI_SCHEMES = /^(?:https?|geo|mailto|sms|tel)$/i;
/**
* Tests if the given uri has an allowed scheme.
* This matches the logic in UriPolicyNanny#apply
*/
function allowedUriScheme(uri) {
return (uri.hasScheme() && ALLOWED_URI_SCHEMES.test(uri.getScheme()));
}
function uriFetch(naiveUriPolicy, uri, mime, callback) {
uri = '' + uri;
var parsed = URI.parse(uri);
try {
if (!naiveUriPolicy || 'function' !== typeof naiveUriPolicy.fetch) {
window.setTimeout(function() { callback({}); }, 0);
} else if (allowedUriScheme(parsed)) {
naiveUriPolicy.fetch(parsed, mime, callback);
} else {
naiveUriPolicy.fetch(undefined, mime, callback);
}
} catch (e) {
console.log('Rejecting url ' + uri + ' because ' + e);
window.setTimeout(function() { callback({}); }, 0);
}
}
function uriRewrite(naiveUriPolicy, uri, effects, ltype, hints) {
if (!naiveUriPolicy || 'function' !== typeof naiveUriPolicy.rewrite) {
return null;
}
uri = '' + uri;
var parsed = URI.parse(uri);
try {
if (allowedUriScheme(parsed)) {
var safeUri = naiveUriPolicy.rewrite(parsed, effects, ltype, hints);
return safeUri ? safeUri.toString() : null;
} else {
return null;
}
} catch (e) {
console.log('Rejecting url ' + uri + ' because ' + e);
return null;
}
}
// test for old-style proxies, not ES6 direct proxies, because that's what we
// used and what ES5/3 provides.
// TODO(kpreid): Need to migrate to ES6-planned proxy API
var proxiesAvailable = typeof Proxy !== 'undefined' && !!Proxy.create;
var proxiesInterceptNumeric = proxiesAvailable && (function() {
var handler = {
toString: function() { return 'proxiesInterceptNumeric test handler'; },
getOwnPropertyDescriptor: function(name) {
return {value: name === '1' ? 'ok' : 'other'};
}
};
handler.getPropertyDescriptor = handler.getOwnPropertyDescriptor;
var proxy = Proxy.create(handler);
return proxy[1] === 'ok';
}());
var canHaveEnumerableAccessors = (function() {
// Firefox bug causes enumerable accessor properties to appear as own
// properties of children. SES patches this by prohibiting enumerable
// accessor properties. We work despite the bug by making all such
// properties non-enumerable using this flag.
try {
Object.defineProperty({}, "foo", {
enumerable: true,
configurable: false,
get: function () {}
});
return true;
} catch (e) {
return false;
}
})();
function getPropertyDescriptor(o, n) {
if (o === null || o === undefined) {
return undefined;
} else {
return Object.getOwnPropertyDescriptor(o, n)
|| getPropertyDescriptor(Object.getPrototypeOf(o), n);
}
}
/**
* This is a simple forwarding proxy handler. Code copied 2011-05-24 from
* <http://wiki.ecmascript.org/doku.php?id=harmony:proxy_defaulthandler>
* with modifications to make it work on ES5-not-Harmony-but-with-proxies as
* provided by Firefox 4.0.1 and to be compatible with SES's WeakMap
* emulation.
*/
function ProxyHandler(target) {
this.target = target;
};
ProxyHandler.prototype = {
constructor: ProxyHandler,
// == fundamental traps ==
// Object.getOwnPropertyDescriptor(proxy, name) -> pd | undefined
getOwnPropertyDescriptor: function(name) {
var desc = Object.getOwnPropertyDescriptor(this.target, name);
if (desc !== undefined) { desc.configurable = true; }
return desc;
},
// Object.getPropertyDescriptor(proxy, name) -> pd | undefined
getPropertyDescriptor: function(name) {
var desc = Object.getPropertyDescriptor(this.target, name);
if (desc !== undefined) { desc.configurable = true; }
return desc;
},
// Object.getOwnPropertyNames(proxy) -> [ string ]
getOwnPropertyNames: function() {
return Object.getOwnPropertyNames(this.target);
},
// Object.getPropertyNames(proxy) -> [ string ]
getPropertyNames: function() {
return Object.getPropertyNames(this.target);
},
// Object.defineProperty(proxy, name, pd) -> undefined
defineProperty: function(name, desc) {
Object.defineProperty(this.target, name, desc);
return true;
},
// delete proxy[name] -> boolean
'delete': function(name) {
return delete this.target[name];
},
// Object.{freeze|seal|preventExtensions}(proxy) -> proxy
fix: function() {
// As long as target is not frozen,
// the proxy won't allow itself to be fixed
if (!Object.isFrozen(this.target)) {
return undefined;
}
var props = {};
for (var name in this.target) {
props[name] = Object.getOwnPropertyDescriptor(this.target, name);
}
return props;
},
// == derived traps ==
// name in proxy -> boolean
has: function(name) { return name in this.target; },
// ({}).hasOwnProperty.call(proxy, name) -> boolean
hasOwn: function(name) {
return ({}).hasOwnProperty.call(this.target, name);
},
// proxy[name] -> any
get: function(proxy, name) {
return this.target[name];
},
// proxy[name] = value
set: function(proxy, name, value) {
this.target[name] = value;
return true;
},
// for (var name in proxy) { ... }
enumerate: function() {
var result = [];
for (var name in this.target) { result.push(name); };
return result;
},
/*
// if iterators would be supported:
// for (var name in proxy) { ... }
iterate: function() {
var props = this.enumerate();
var i = 0;
return {
next: function() {
if (i === props.length) throw StopIteration;
return props[i++];
}
};
},*/
// Object.keys(proxy) -> [ string ]
keys: function() { return Object.keys(this.target); }
};
cajaVM.def(ProxyHandler);
function makeOverrideSetter(object, prop) {
return innocuous(function overrideSetter(newValue) {
if (object === this) {
throw new TypeError('Cannot set virtually frozen property: ' + prop);
}
if (!!Object.getOwnPropertyDescriptor(this, prop)) {
this[prop] = newValue;
}
// TODO(erights): Do all the inherited property checks
Object.defineProperty(this, prop, {
value: newValue,
writable: true,
enumerable: true,
configurable: true
});
});
}
/**
* Takes a property descriptor and, if it is a non-writable data property or
* an accessor with only a getter, returns a replacement descriptor which
* allows the property to be overridden by assignment.
*
* Note that the override behavior is only of value when the object is
* inherited from, so properties defined on "instances" should not use this as
* it is unnecessarily expensive.
*/
function allowNonWritableOverride(object, prop, desc) {
if (!('value' in desc && !desc.writable)) {
return desc;
}
var value = desc.value;
// TODO(kpreid): Duplicate of tamperProof() from repairES5.js.
// We should extract that getter/setter pattern as a separate routine; but
// note that we need to make the same API available from ES5/3 (though not
// the same behavior, since ES5/3 rejects the 'override mistake',
// ASSIGN_CAN_OVERRIDE_FROZEN in repairES5 terms) available from ES5/3.
return {
configurable: desc.configurable,
enumerable: desc.enumerable,
get: innocuous(function overrideGetter() { return value; }),
set: makeOverrideSetter(object, prop)
};
}
/**
* Alias for a common pattern: non-enumerable toString method.
*/
function setToString(obj, fn) {
Object.defineProperty(obj, 'toString',
allowNonWritableOverride(obj, 'toString', {value: fn}));
}
/**
* Shortcut for a single unmodifiable property. No provision for override.
*/
function setFinal(object, prop, value) {
Object.defineProperty(object, prop, {
enumerable: true,
value: value
});
}
/**
* Given that n is a string, is n an "array element" property name?
*/
function isNumericName(n) {
return ('' + (+n)) === n;
}
function inherit(subCtor, superCtor, opt_writableProto) {
var inheritingProto = Object.create(superCtor.prototype);
// TODO(kpreid): The following should work but is a no-op on Chrome
// 24.0.1312.56, which breaks everything. Enable it when possible.
//Object.defineProperty(subCtor, 'prototype', {
// value: inheritingProto,
// writable: Boolean(opt_writableProto),
// enumerable: false,
// configurable: false
//});
// Workaround:
if (opt_writableProto) {
subCtor.prototype = inheritingProto;
} else {
Object.defineProperty(subCtor, 'prototype', {
enumerable: false,
value: inheritingProto
});
}
Object.defineProperty(subCtor.prototype, 'constructor', {
value: subCtor,
writable: true,
enumerable: false,
configurable: true
});
}
/**
* Checks that a user-supplied callback is a function. Return silently if the
* callback is valid; throw an exception if it is not valid.
*
* TODO(kpreid): Is this conversion to ES5-world OK?
*
* @param aCallback some user-supplied "function-like" callback.
*/
function ensureValidCallback(aCallback) {
if ('function' !== typeof aCallback) {
throw new Error('Expected function not ' + typeof aCallback);
}
}
/**
* This combines trademarks with amplification, and is really a thin wrapper
* on WeakMap. It allows objects to have an arbitrary collection of private
* properties, which can only be accessed by those holding the amplifier 'p'
* (which, in most cases, should be only a particular prototype's methods.)
*
* Unlike trademarks, this does not freeze the object. It is assumed that the
* caller makes the object sufficiently frozen for its purposes and/or that
* the private properties are all that needs protection.
*
* This is designed to be more efficient and straightforward than using both
* trademarks and per-private-property sealed boxes or weak maps.
*
* Capability design note: This facility provides sibling amplification (the
* ability for one object to access the private state of other similar
* objects).
*/
var Confidence = (function () {
// superTable, superTypename are undefined if there is no supertype
function _SubConfidence(typename, superTable, superTypename) {
var table = new WeakMap();
/**
* Add an object to the confidence. This permits it to pass the
* guard and provides a private-properties record for it.
*
* @param {Object} object The object to add.
* @param {Object} taming The taming membrane which the object is on the
* tame side of.
* @param {Object} opt_sameAs If provided, an existing object whose
* private state will be reused for {@code object}.
*/
this.confide = cajaVM.constFunc(function(object, taming, opt_sameAs) {
//console.debug("Confiding:", object);
if (table.get(object) !== undefined) {
if (table.get(object)._obj !== object) {
throw new Error("WeakMap broke! " + object + " vs. " +
table.get(object)._obj);
}
throw new Error(typename + " has already confided in " + object);
}
var privates;
if (superTable !== undefined) {
privates = superTable.get(object);
if (!privates) {
throw new Error(typename + ': object must already be a ' +
superTypename);
}
// TODO(kpreid): validate taming, opt_sameAs
} else if (opt_sameAs !== undefined) {
privates = table.get(opt_sameAs);
if (!privates) {
throw new Error(typename + ': opt_sameAs not confided');
}
} else {
privates = {_obj: object, _taming: taming};
}
table.set(object, privates);
});
var guard = this.guard = cajaVM.makeTableGuard(table, typename,
'This operation requires a ' + typename);
/**
* Wrap a method or other function so as to ensure that:
* * 'this' is a confidant,
* * the first parameter of the original function is the private state,
* * the wrapper is frozen,
* * and any exceptions thrown from host-side code are wrapped.
*/
this.amplifying = function(method) {
if (typeof method !== 'function') {
throw new Error(typename + ': amplifying(non-function): ' + method);
}
function amplifierMethod(var_args) {
var privates = table.get(this);
if (privates) {
var ampargs = [privates];
ampargs.push.apply(ampargs, arguments);
try {
return method.apply(this, ampargs);
} catch (e) {
throw privates._taming.tameException(e);
}
} else {
guard.coerce(this); // borrow exception
throw 'can\'t happen';
}
}
amplifierMethod.toString = innocuous(function() {
return '[' + typename + ']' + method.toString();
});
return cajaVM.constFunc(amplifierMethod);
};
/**
* 'amplify(o, f)' is identical to 'amplifying(f).call(o)' but
* significantly more efficient.
*/
this.amplify = function(object, method) {
var privates = table.get(object);
if (privates) {
var ampargs = [privates];
ampargs.push.apply(ampargs, arguments);
try {
return method.apply(object, ampargs);
} catch (e) {
throw privates._taming.tameException(e);
}
} else {
guard.coerce(object); // borrow exception
throw 'can\'t happen';
}
};
this.subtype = function(subtypeName) {
return new _SubConfidence(subtypeName, table, typename);
}.bind(this);
this.typename = typename;
}
function Confidence(typename) {
return new _SubConfidence(typename, undefined, undefined);
}
Confidence.prototype.toString = cajaVM.constFunc(function() {
return this.typename + 'Confidence';
});
_SubConfidence.prototype = Confidence.prototype;
return cajaVM.def(Confidence);
})();
/**
* Explicit marker that this is a function intended to be exported that needs
* no other wrapping. Also, remove the function's .prototype object.
*
* As a matter of style, fn should always be a function literal; think of this
* as a modifier to function literal syntax. This ensures that it is not
* misapplied to functions which have more complex circumstances.
*/
// TODO(kpreid): Verify this in tests, e.g. by adding a property and checking
function innocuous(f) {
return cajaVM.constFunc(f);
}
var PROPERTY_DESCRIPTOR_KEYS = {
configurable: 0,
enumerable: 0,
writable: 0,
value: 0,
get: 0,
set: 0
};
/**
* Utilities for defining properties.
*/
var Props = (function() {
var NO_PROPERTY = null;
/**
* Return a function returning an environment. Environments are context
* implicitly available to our extended property descriptors ('property
* specifiers') such as the name of the property being defined (so that a
* single spec can express "forward this property to the same-named property
* on another object", for example).
*/
function makeEnvOuter(object, opt_confidence) {
// TODO(kpreid): confidence typename is not actually currently specific
// enough for debugging (node subclasses, in particular) but it's the
// only formal name we have right now.
var typename = opt_confidence ? opt_confidence.typename : String(object);
var amplifying = opt_confidence
? opt_confidence.amplifying.bind(opt_confidence)
: function(fn) {
throw new Error('Props.define: no confidence, no amplifying');
};
return function(prop) {
var msgPrefix = 'Props.define: ' + typename + '.' + prop;
return {
object: object,
prop: prop,
msgPrefix: msgPrefix,
amplifying: amplifying
};
};
}
/**
* Convert a property spec (our notion) to a property descriptor (ES5
* notion) and validate/repair/kludge it.
*
* The returned property descriptor is fresh.
*/
function specToDesc(env, propSpec) {
if (propSpec === NO_PROPERTY) { return propSpec; }
switch (typeof propSpec) {
case 'function':
if (!propSpec.isPropMaker) {
// TODO(kpreid): Temporary check for refactoring.
throw new TypeError(env.msgPrefix +
' defined with a function not a prop maker');
}
return specToDesc(env, propSpec(env));
case 'object':
// Make a copy so that we can mutate desc, and validate.
var desc = copyAndValidateDesc(env, propSpec);
if ('get' in desc || 'set' in desc) {
// Firefox bug workaround; see canHaveEnumerableAccessors.
desc.enumerable = desc.enumerable && canHaveEnumerableAccessors;
}
if (desc.get && !Object.isFrozen(desc.get)) {
if (typeof console !== 'undefined') {
console.warn(env.msgPrefix + ' getter is not frozen; fixing.');
}
cajaVM.constFunc(desc.get);
}
if (desc.set && !Object.isFrozen(desc.set)) {
if (typeof console !== 'undefined') {
console.warn(env.msgPrefix + ' setter is not frozen; fixing.');
}
cajaVM.constFunc(desc.set);
}
return desc;
default:
throw new TypeError(env.msgPrefix +
' spec not a function or descriptor (' + propSpec + ')');
}
}
function copyAndValidateDesc(env, inDesc) {
var desc = {};
for (var k in inDesc) {
if (PROPERTY_DESCRIPTOR_KEYS.hasOwnProperty(k)) {
// Could imagine doing a type-check here, but not bothering.
desc[k] = inDesc[k];
} else {
throw new TypeError(env.msgPrefix +
': Unexpected key in property descriptor: ' + k);
}
}
return desc;
}
/**
* For each enumerable p: s in propSpecs, do
*
* Object.defineProperty(object, p, specToDesc(..., s))
*
* where specToDesc() passes plain property descriptors through and can
* also construct property descriptors based on the specified 'p' or
* 'confidence' if s is one of the property-maker functions provided by
* Props.
*
* Additionally, getters and setters are checked for being frozen, and the
* syntax of the descriptor is checked.
*/
function define(object, opt_confidence, propSpecs) {
var makeEnv = makeEnvOuter(object, opt_confidence);
for (var prop in propSpecs) {
var desc = specToDesc(makeEnv(prop), propSpecs[prop]);
if (desc !== NO_PROPERTY) {
Object.defineProperty(object, prop, desc);
}
}
}
/**
* A property which behaves as if as it was named the mapName.
*/
function actAs(mapName, propSpec) {
return markPropMaker(function(env) {
return specToDesc(
Object.create(env, {
prop: {value: mapName}
}),
propSpec);
});
}
/**
* A getter which forwards to the other-named property of this
* object.
*
* (This does not also forward a setter so as to avoid producing a visible
* but useless setter if the other property is read-only. If that is needed,
* we'll define aliasRW. Unfortunately there's no way to 'statically'
* determine which behavior to use.)
*
* Remember that the other property could have been overridden by the caller
* if it is inherited!
*/
function aliasRO(enumerable, otherProp) {
return {
enumerable: enumerable,
get: innocuous(function aliasGetter() { return this[otherProp]; })
};
}
/**
* A non-writable, possibly enumerable, overridable constant-valued
* property.
*/
function overridable(enumerable, value) {
return markPropMaker(function overridablePropMaker(env) {
return allowNonWritableOverride(env.object, env.prop, {
enumerable: enumerable,
value: value
});
});
}
/**
* Add override to an accessor property.
*/
function addOverride(spec) {
return markPropMaker(function overridablePropMaker(env) {
var desc = specToDesc(env, spec);
if ('set' in desc || 'value' in desc) {
throw new Error('bad addOverride');
} else {
desc.set = makeOverrideSetter(env.object, env.prop);
}
return desc;
});
}
/**
* An overridable, enumerable method.
*
* fn will have innocuous() applied to it (thus ending up with its
* .prototype removed).
*
* As a matter of style, fn should always be a function literal; think of
* this as a modifier to function literal syntax. This ensures that it is
* not misapplied to functions which have more complex circumstances.
*/
function plainMethod(fn) {
return overridable(true, innocuous(fn));
}
/**
* An overridable, enumerable, amplifying (as in confidence.amplifying)
* method.
*
* The function should be a function literal.
*/
function ampMethod(fn) {
return markPropMaker(function(env) {
return overridable(true, env.amplifying(fn));
});
}
/**
* A non-overridable, enumerable, amplifying (as in confidence.amplifying)
* getter.
*
* The function should be a function literal.
*/
function ampGetter(fn) {
return markPropMaker(function(env) {
return {
enumerable: true,
get: env.amplifying(fn)
};
});
}
/**
* A non-overridable, enumerable, amplifying (as in confidence.amplifying)
* getter and setter.
*
* The functions should be function literals.
*/
function ampAccessor(getter, setter) {
return markPropMaker(function(env) {
return {
enumerable: true,
get: env.amplifying(getter),
set: env.amplifying(setter)
};
});
}
/**
* Checkable label for all property specs implemented functions.
* TODO(kpreid): Have fewer custom property makers outside of Props itself;
* provide tools to build them instead.
*/
function markPropMaker(fn) {
fn.isPropMaker = true;
// causes a TypeError inside ToPropertyDescriptor
fn.get = '<PropMaker used as propdesc canary>';
return fn;
}
/**
* Only define the property if the condition is true.
*
* For more complex cases use regular conditionals and NO_PROPERTY.
*/
function cond(condition, specThen) {
return condition ? specThen : NO_PROPERTY;
}
return {
define: define,
actAs: actAs,
aliasRO: aliasRO,
overridable: overridable,
addOverride: addOverride,
plainMethod: plainMethod,
ampMethod: ampMethod,
ampGetter: ampGetter,
ampAccessor: ampAccessor,
cond: cond,
NO_PROPERTY: NO_PROPERTY,
markPropMaker: markPropMaker
};
})();
var CollectionProxyHandler = (function() {
/**
* Handler for a proxy which presents value properties derived from an
* external data source.
*
* The subclass should implement .col_lookup(name) -> internalvalue,
* .col_evaluate(internalvalue) -> value, and .col_names() -> array.
*/
function CollectionProxyHandler(target) {
ProxyHandler.call(this, target);
}
inherit(CollectionProxyHandler, ProxyHandler);
CollectionProxyHandler.prototype.toString = function() {
return '[CollectionProxyHandler]';
};
CollectionProxyHandler.prototype.getOwnPropertyDescriptor =
function (name) {
var lookup;
if ((lookup = this.col_lookup(name))) {
return {
configurable: true, // proxy invariant check
enumerable: true, // TODO(kpreid): may vary
writable: false,
value: this.col_evaluate(lookup)
};
} else {
return ProxyHandler.prototype.getOwnPropertyDescriptor.call(this, name);
}
};
CollectionProxyHandler.prototype.get = function(receiver, name) {
var lookup;
if ((lookup = this.col_lookup(name))) {
return this.col_evaluate(lookup);
} else {
return ProxyHandler.prototype.get.call(this, receiver, name);
}
};
CollectionProxyHandler.prototype.getOwnPropertyNames = function() {
var names = ProxyHandler.prototype.getOwnPropertyNames.call(this);
names.push.apply(names, this.col_names());
return names;
};
CollectionProxyHandler.prototype['delete'] = function(name) {
var lookup;
if ((lookup = this.col_lookup(name))) {
return false;
} else {
return ProxyHandler.prototype['delete'].call(this, name);
}
};
return cajaVM.def(CollectionProxyHandler);
}());
/** XMLHttpRequest or an equivalent on IE 6. */
function XMLHttpRequestCtor(XMLHttpRequest, ActiveXObject, XDomainRequest) {
if (XMLHttpRequest &&
new XMLHttpRequest().withCredentials !== undefined) {
return XMLHttpRequest;
} else if (XDomainRequest) {
return function XDomainRequestObjectForIE() {
var xdr = new XDomainRequest();
xdr.onload = function () {
if ('function' === typeof xdr.onreadystatechange) {
xdr.status = 200;
xdr.readyState = 4;
xdr.onreadystatechange.call(xdr, null, false);
}
};
var errorHandler = function () {
if ('function' === typeof xdr.onreadystatechange) {
xdr.status = 500;
xdr.readyState = 4;
xdr.onreadystatechange.call(xdr, null, false);
}
};
xdr.onerror = errorHandler;
xdr.ontimeout = errorHandler;
return xdr;
};
} else if (ActiveXObject) {
// The first time the ctor is called, find an ActiveX class supported by
// this version of IE.
var activeXClassId;
return function ActiveXObjectForIE() {
if (activeXClassId === void 0) {
activeXClassId = null;
/** Candidate Active X types. */
var activeXClassIds = [
'MSXML2.XMLHTTP.5.0', 'MSXML2.XMLHTTP.4.0',
'MSXML2.XMLHTTP.3.0', 'MSXML2.XMLHTTP',
'MICROSOFT.XMLHTTP.1.0', 'MICROSOFT.XMLHTTP.1',
'MICROSOFT.XMLHTTP'];
for (var i = 0, n = activeXClassIds.length; i < n; i++) {
var candidate = activeXClassIds[+i];
try {
void new ActiveXObject(candidate);
activeXClassId = candidate;
break;
} catch (e) {
// do nothing; try next choice
}
}
activeXClassIds = null;
}
return new ActiveXObject(activeXClassId);
};
} else {
throw new Error('ActiveXObject not available');
}
}
function TameXMLHttpRequest(
taming,
xmlHttpRequestMaker,
naiveUriPolicy,
getBaseURL,
onerrorTarget) {
// See http://www.w3.org/TR/XMLHttpRequest/
// TODO(ihab.awad): Improve implementation (interleaving, memory leaks)
// per http://www.ilinsky.com/articles/XMLHttpRequest/
var TameXHRConf = new Confidence('TameXMLHttpRequest');
var amplifying = TameXHRConf.amplifying;
var amplify = TameXHRConf.amplify;
// Note: Since there is exactly one TameXMLHttpRequest per feral XHR, we do
// not use an expando proxy and always let clients set expando properties
// directly on this. This simplifies implementing onreadystatechange.
function TameXMLHttpRequest() {
TameXHRConf.confide(this, taming);
amplify(this, function(privates) {
var xhr = privates.feral = new xmlHttpRequestMaker();
taming.tamesTo(xhr, this);
privates.async = undefined;
privates.handler = undefined;
privates.nativeCompleteEventSeen = false;
Object.preventExtensions(privates);
});
}
Props.define(TameXMLHttpRequest.prototype, TameXHRConf, {
onreadystatechange: {
enumerable: true,
set: amplifying(function(privates, handler) {
// TODO(ihab.awad): Do we need more attributes of the event than
// 'target'? May need to implement full "tame event" wrapper similar
// to DOM events.
var self = this;
privates.feral.onreadystatechange = function(event) {
if (privates.feral.readyState === 4) {
// Detect whether this event was fired. See open() for how this
// is used.
privates.nativeCompleteEventSeen = true;
}
var evt = { target: self };
try {
return handler.call(void 0, evt);
} catch (e) {
Domado_.handleUncaughtException(
onerrorTarget, e, '<XMLHttpRequest callback>');
}
};
// Store for later direct invocation if need be
privates.handler = handler;
})
},
// TODO(kpreid): This are PT.ROView properties but our layering does not
// offer that here.
readyState: Props.ampGetter(function(privates) {
// The ready state should be a number
return Number(privates.feral.readyState);
}),
responseText: Props.ampGetter(function(privates) {
var result = privates.feral.responseText;
return (result === undefined || result === null)
? result : String(result);
}),
responseXML: Props.ampGetter(function(privates) {
var feralXml = privates.feral.responseXML;
if (feralXml === null || feralXml === undefined) {
// null = 'The response did not parse as XML.'
return null;