pax_global_header00006660000000000000000000000064122737236260014524gustar00rootroot0000000000000052 comment=b90ec3ca1e2d67fcb99fab79696e450a715fc3ba with-3.0.0/000077500000000000000000000000001227372362600124775ustar00rootroot00000000000000with-3.0.0/.gitignore000066400000000000000000000001421227372362600144640ustar00rootroot00000000000000lib-cov *.seed *.log *.csv *.dat *.out *.pid *.gz pids logs results npm-debug.log node_modules with-3.0.0/.npmignore000066400000000000000000000000211227372362600144670ustar00rootroot00000000000000test/ .travis.ymlwith-3.0.0/.travis.yml000066400000000000000000000000601227372362600146040ustar00rootroot00000000000000language: node_js node_js: - "0.8" - "0.10" with-3.0.0/LICENSE000066400000000000000000000020641227372362600135060ustar00rootroot00000000000000Copyright (c) 2013 Forbes Lindesay Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.with-3.0.0/README.md000066400000000000000000000037201227372362600137600ustar00rootroot00000000000000# with Compile time `with` for strict mode JavaScript [![build status](https://secure.travis-ci.org/ForbesLindesay/with.png)](http://travis-ci.org/ForbesLindesay/with) [![Dependency Status](https://gemnasium.com/ForbesLindesay/with.png)](https://gemnasium.com/ForbesLindesay/with) [![NPM version](https://badge.fury.io/js/with.png)](http://badge.fury.io/js/with) ## Installation $ npm install with ## Usage ```js var addWith = require('with') addWith('obj', 'console.log(a)') // => ';(function (console, a) { // console.log(a) // }("console" in obj ? obj.console : // typeof console!=="undefined" ? console : undefined, // "a" in obj ? obj.a : // typeof a !== "undefined" ? a : undefined));' addWith('obj', 'console.log(a)', ['console']) // => ';(function (console, a) { // console.log(a) // }("a" in obj ? obj.a : // typeof a !== "undefined" ? a : undefined));' ``` ## API ### addWith(obj, src[, exclude]) The idea is that this is roughly equivallent to: ```js with (obj) { src } ``` There are a few differences though. For starters, assignments to variables will always remain contained within the with block. e.g. ```js var foo = 'foo' with ({}) { foo = 'bar' } assert(foo === 'bar')// => This fails for compile time with but passes for native with var obj = {foo: 'foo'} with ({}) { foo = 'bar' } assert(obj.foo === 'bar')// => This fails for compile time with but passes for native with ``` It also makes everything be declared, so you can always do: ```js if (foo === undefined) ``` instead of ```js if (typeof foo === 'undefined') ``` This is not the case if foo is in `exclude`. If a variable is excluded, we ignore it entirely. This is useful if you know a variable will be global as it can lead to efficiency improvements. It is also safe to use in strict mode (unlike `with`) and it minifies properly (`with` disables virtually all minification). ## License MITwith-3.0.0/index.js000066400000000000000000000063311227372362600141470ustar00rootroot00000000000000'use strict'; var uglify = require('uglify-js') module.exports = addWith /** * Mimic `with` as far as possible but at compile time * * @param {String} obj The object part of a with expression * @param {String} src The body of the with expression * @param {Array.} exclude A list of variable names to explicitly exclude */ function addWith(obj, src, exclude) { obj = obj + '' src = src + '' exclude = exclude || [] exclude = exclude.concat(detect(obj)) var vars = detect(src) .filter(function (v) { return exclude.indexOf(v) === -1 }) if (vars.length === 0) return src var declareLocal = '' var local = 'locals_for_with' var result = 'result_of_with' if (/^[a-zA-Z0-9$_]+$/.test(obj)) { local = obj } else { while (vars.indexOf(local) != -1 || exclude.indexOf(local) != -1) { local += '_' } declareLocal = 'var ' + local + ' = (' + obj + ')' } while (vars.indexOf(result) != -1 || exclude.indexOf(result) != -1) { result += '_' } var inputVars = vars.map(function (v) { return JSON.stringify(v) + ' in ' + local + '?' + local + '.' + v + ':' + 'typeof ' + v + '!=="undefined"?' + v + ':undefined' }) src = '(function (' + vars.join(', ') + ') {' + src + '}(' + inputVars.join(',') + '))' return ';' + declareLocal + ';' + unwrapReturns(src, result) + ';' } /** * Detect, and return a list of, any global variables in a function * * @param {String} src Some JavaScript code */ function detect(src) { var ast = uglify.parse('(function () {' + src + '}())') // allow return keyword ast.figure_out_scope() var globals = ast.globals .map(function (node, name) { return name }) return globals } /** * Take a self calling function, and unwrap it such that return inside the function * results in return outside the function * * @param {String} src Some JavaScript code representing a self-calling function * @param {String} result A temporary variable to store the result in */ function unwrapReturns(src, result) { var originalSource = src var hasReturn = false var ast = uglify.parse(src) src = src.split('') if (ast.body.length !== 1 || ast.body[0].TYPE !== 'SimpleStatement' || ast.body[0].body.TYPE !== 'Call' || ast.body[0].body.expression.TYPE !== 'Function') throw new Error('AST does not seem to represent a self-calling function') var fn = ast.body[0].body.expression var walker = new uglify.TreeWalker(visitor) function visitor(node, descend) { if (node !== fn && (node.TYPE === 'Defun' || node.TYPE === 'Function')) { return true //don't descend into functions } if (node.TYPE === 'Return') { descend() hasReturn = true replace(node, 'return {value: ' + source(node.value) + '};') return true //don't descend again } } function source(node) { return src.slice(node.start.pos, node.end.endpos).join('') } function replace(node, str) { for (var i = node.start.pos; i < node.end.endpos; i++) { src[i] = '' } src[node.start.pos] = str } ast.walk(walker) if (!hasReturn) return originalSource else return 'var ' + result + '=' + src.join('') + ';if (' + result + ') return ' + result + '.value' } with-3.0.0/package.json000066400000000000000000000006561227372362600147740ustar00rootroot00000000000000{ "name": "with", "version": "3.0.0", "description": "Compile time `with` for strict mode JavaScript", "main": "index.js", "scripts": { "test": "mocha -R spec" }, "repository": { "type": "git", "url": "https://github.com/ForbesLindesay/with.git" }, "author": "ForbesLindesay", "license": "MIT", "dependencies": { "uglify-js": "~2.4.12" }, "devDependencies": { "mocha": "~1.12.0" } }with-3.0.0/test/000077500000000000000000000000001227372362600134565ustar00rootroot00000000000000with-3.0.0/test/index.js000066400000000000000000000066671227372362600151420ustar00rootroot00000000000000var assert = require('assert') var addWith = require('../') var sentinel = {} var sentinel2 = {} describe('addWith("obj", "console.log(a)")', function () { it('adds the necessary variable declarations', function (done) { var src = addWith('obj', 'console.log(a)') // var a = obj.a;console.log(a) Function('console,obj', src)( { log: function (a) { assert(a === sentinel) done() } }, {a: sentinel}) }) }) describe('addWith("obj || {}", "console.log(a)")', function () { it('adds the necessary variable declarations', function (done) { var src = addWith('obj || {}', 'console.log(a)') // var locals = (obj || {}),a = locals.a;console.log(a) var expected = 2 Function('console,obj', src)( { log: function (a) { assert(a === sentinel) if (0 === --expected) done() } }, {a: sentinel}) Function('console,obj', src)( { log: function (a) { assert(a === undefined) if (0 === --expected) done() } }) }) }) describe('addWith("obj", "console.log(helper(a))")', function () { it('adds the necessary variable declarations', function (done) { var src = addWith('obj', 'console.log(helper(a))') // var a = obj.a;console.log(helper(a)) Function('console,obj,helper', src)( { log: function (a) { assert(a === sentinel) done() } }, {a: sentinel2}, function (a) { assert(a === sentinel2) return sentinel }) }) }) describe('addWith("obj || {}", "console.log(locals(a))")', function () { it('adds the necessary variable declarations', function (done) { var src = addWith('obj || {}', 'console.log(locals(a))') // var locals__ = (obj || {}),locals = locals__.locals,a = locals__.a;console.log(locals(a)) Function('console,obj', src)( { log: function (a) { assert(a === sentinel) done() } }, { a: sentinel2, locals: function (a) { assert(a === sentinel2) return sentinel } }) }) }) describe('addWith("obj || {}", "console.log(\'foo\')")', function () { it('passes through', function (done) { var src = addWith('obj || {}', 'console.log("foo")') // console.log(\'foo\') Function('console,obj', src)( { log: function (a) { assert(a === 'foo') done() } }) }) }) describe('addWith("obj || {}", "obj.foo")', function () { it('passes through', function (done) { var src = addWith('obj || {}', 'obj.bar = obj.foo') // obj.bar = obj.foo var obj = { foo: 'ding' } Function('obj', src)(obj) assert(obj.bar === 'ding') done() }) }) describe('addWith("obj || {}", "return foo")', function () { it('supports returning values', function (done) { var src = addWith('obj || {}', 'return foo') // obj.bar = obj.foo var obj = { foo: 'ding' } assert(Function('obj', src)(obj) === 'ding') done() }) it('supports returning undefined', function (done) { var src = addWith('obj || {}', 'return foo') assert(Function('obj', src + ';return "ding"')({}) === undefined) done() }) it('supports not actually returning', function (done) { var src = addWith('obj || {}', 'if (false) return foo') assert(Function('obj', src + ';return "ding"')({}) === 'ding') done() }) })with-3.0.0/vars.js000066400000000000000000000377771227372362600140350ustar00rootroot00000000000000// jshint -W001 "use strict"; // Identifiers provided by the ECMAScript standard. exports.reservedVars = { arguments : false, NaN : false }; exports.ecmaIdentifiers = { Array : false, Boolean : false, Date : false, decodeURI : false, decodeURIComponent : false, encodeURI : false, encodeURIComponent : false, Error : false, "eval" : false, EvalError : false, Function : false, hasOwnProperty : false, isFinite : false, isNaN : false, JSON : false, Math : false, Map : false, Number : false, Object : false, parseInt : false, parseFloat : false, RangeError : false, ReferenceError : false, RegExp : false, Set : false, String : false, SyntaxError : false, TypeError : false, URIError : false, WeakMap : false }; // Global variables commonly provided by a web browser environment. exports.browser = { Audio : false, Blob : false, addEventListener : false, applicationCache : false, atob : false, blur : false, btoa : false, clearInterval : false, clearTimeout : false, close : false, closed : false, CustomEvent : false, DOMParser : false, defaultStatus : false, document : false, Element : false, ElementTimeControl : false, event : false, FileReader : false, FormData : false, focus : false, frames : false, getComputedStyle : false, HTMLElement : false, HTMLAnchorElement : false, HTMLBaseElement : false, HTMLBlockquoteElement: false, HTMLBodyElement : false, HTMLBRElement : false, HTMLButtonElement : false, HTMLCanvasElement : false, HTMLDirectoryElement : false, HTMLDivElement : false, HTMLDListElement : false, HTMLFieldSetElement : false, HTMLFontElement : false, HTMLFormElement : false, HTMLFrameElement : false, HTMLFrameSetElement : false, HTMLHeadElement : false, HTMLHeadingElement : false, HTMLHRElement : false, HTMLHtmlElement : false, HTMLIFrameElement : false, HTMLImageElement : false, HTMLInputElement : false, HTMLIsIndexElement : false, HTMLLabelElement : false, HTMLLayerElement : false, HTMLLegendElement : false, HTMLLIElement : false, HTMLLinkElement : false, HTMLMapElement : false, HTMLMenuElement : false, HTMLMetaElement : false, HTMLModElement : false, HTMLObjectElement : false, HTMLOListElement : false, HTMLOptGroupElement : false, HTMLOptionElement : false, HTMLParagraphElement : false, HTMLParamElement : false, HTMLPreElement : false, HTMLQuoteElement : false, HTMLScriptElement : false, HTMLSelectElement : false, HTMLStyleElement : false, HTMLTableCaptionElement: false, HTMLTableCellElement : false, HTMLTableColElement : false, HTMLTableElement : false, HTMLTableRowElement : false, HTMLTableSectionElement: false, HTMLTextAreaElement : false, HTMLTitleElement : false, HTMLUListElement : false, HTMLVideoElement : false, history : false, Image : false, length : false, localStorage : false, location : false, MessageChannel : false, MessageEvent : false, MessagePort : false, MouseEvent : false, moveBy : false, moveTo : false, MutationObserver : false, name : false, Node : false, NodeFilter : false, navigator : false, onbeforeunload : true, onblur : true, onerror : true, onfocus : true, onload : true, onresize : true, onunload : true, open : false, openDatabase : false, opener : false, Option : false, parent : false, print : false, removeEventListener : false, resizeBy : false, resizeTo : false, screen : false, scroll : false, scrollBy : false, scrollTo : false, sessionStorage : false, setInterval : false, setTimeout : false, SharedWorker : false, status : false, SVGAElement : false, SVGAltGlyphDefElement: false, SVGAltGlyphElement : false, SVGAltGlyphItemElement: false, SVGAngle : false, SVGAnimateColorElement: false, SVGAnimateElement : false, SVGAnimateMotionElement: false, SVGAnimateTransformElement: false, SVGAnimatedAngle : false, SVGAnimatedBoolean : false, SVGAnimatedEnumeration: false, SVGAnimatedInteger : false, SVGAnimatedLength : false, SVGAnimatedLengthList: false, SVGAnimatedNumber : false, SVGAnimatedNumberList: false, SVGAnimatedPathData : false, SVGAnimatedPoints : false, SVGAnimatedPreserveAspectRatio: false, SVGAnimatedRect : false, SVGAnimatedString : false, SVGAnimatedTransformList: false, SVGAnimationElement : false, SVGCSSRule : false, SVGCircleElement : false, SVGClipPathElement : false, SVGColor : false, SVGColorProfileElement: false, SVGColorProfileRule : false, SVGComponentTransferFunctionElement: false, SVGCursorElement : false, SVGDefsElement : false, SVGDescElement : false, SVGDocument : false, SVGElement : false, SVGElementInstance : false, SVGElementInstanceList: false, SVGEllipseElement : false, SVGExternalResourcesRequired: false, SVGFEBlendElement : false, SVGFEColorMatrixElement: false, SVGFEComponentTransferElement: false, SVGFECompositeElement: false, SVGFEConvolveMatrixElement: false, SVGFEDiffuseLightingElement: false, SVGFEDisplacementMapElement: false, SVGFEDistantLightElement: false, SVGFEFloodElement : false, SVGFEFuncAElement : false, SVGFEFuncBElement : false, SVGFEFuncGElement : false, SVGFEFuncRElement : false, SVGFEGaussianBlurElement: false, SVGFEImageElement : false, SVGFEMergeElement : false, SVGFEMergeNodeElement: false, SVGFEMorphologyElement: false, SVGFEOffsetElement : false, SVGFEPointLightElement: false, SVGFESpecularLightingElement: false, SVGFESpotLightElement: false, SVGFETileElement : false, SVGFETurbulenceElement: false, SVGFilterElement : false, SVGFilterPrimitiveStandardAttributes: false, SVGFitToViewBox : false, SVGFontElement : false, SVGFontFaceElement : false, SVGFontFaceFormatElement: false, SVGFontFaceNameElement: false, SVGFontFaceSrcElement: false, SVGFontFaceUriElement: false, SVGForeignObjectElement: false, SVGGElement : false, SVGGlyphElement : false, SVGGlyphRefElement : false, SVGGradientElement : false, SVGHKernElement : false, SVGICCColor : false, SVGImageElement : false, SVGLangSpace : false, SVGLength : false, SVGLengthList : false, SVGLineElement : false, SVGLinearGradientElement: false, SVGLocatable : false, SVGMPathElement : false, SVGMarkerElement : false, SVGMaskElement : false, SVGMatrix : false, SVGMetadataElement : false, SVGMissingGlyphElement: false, SVGNumber : false, SVGNumberList : false, SVGPaint : false, SVGPathElement : false, SVGPathSeg : false, SVGPathSegArcAbs : false, SVGPathSegArcRel : false, SVGPathSegClosePath : false, SVGPathSegCurvetoCubicAbs: false, SVGPathSegCurvetoCubicRel: false, SVGPathSegCurvetoCubicSmoothAbs: false, SVGPathSegCurvetoCubicSmoothRel: false, SVGPathSegCurvetoQuadraticAbs: false, SVGPathSegCurvetoQuadraticRel: false, SVGPathSegCurvetoQuadraticSmoothAbs: false, SVGPathSegCurvetoQuadraticSmoothRel: false, SVGPathSegLinetoAbs : false, SVGPathSegLinetoHorizontalAbs: false, SVGPathSegLinetoHorizontalRel: false, SVGPathSegLinetoRel : false, SVGPathSegLinetoVerticalAbs: false, SVGPathSegLinetoVerticalRel: false, SVGPathSegList : false, SVGPathSegMovetoAbs : false, SVGPathSegMovetoRel : false, SVGPatternElement : false, SVGPoint : false, SVGPointList : false, SVGPolygonElement : false, SVGPolylineElement : false, SVGPreserveAspectRatio: false, SVGRadialGradientElement: false, SVGRect : false, SVGRectElement : false, SVGRenderingIntent : false, SVGSVGElement : false, SVGScriptElement : false, SVGSetElement : false, SVGStopElement : false, SVGStringList : false, SVGStylable : false, SVGStyleElement : false, SVGSwitchElement : false, SVGSymbolElement : false, SVGTRefElement : false, SVGTSpanElement : false, SVGTests : false, SVGTextContentElement: false, SVGTextElement : false, SVGTextPathElement : false, SVGTextPositioningElement: false, SVGTitleElement : false, SVGTransform : false, SVGTransformList : false, SVGTransformable : false, SVGURIReference : false, SVGUnitTypes : false, SVGUseElement : false, SVGVKernElement : false, SVGViewElement : false, SVGViewSpec : false, SVGZoomAndPan : false, TimeEvent : false, top : false, WebSocket : false, window : false, Worker : false, XMLHttpRequest : false, XMLSerializer : false, XPathEvaluator : false, XPathException : false, XPathExpression : false, XPathNamespace : false, XPathNSResolver : false, XPathResult : false }; exports.devel = { alert : false, confirm: false, console: false, Debug : false, opera : false, prompt : false }; exports.worker = { importScripts: true, postMessage : true, self : true }; // Widely adopted global names that are not part of ECMAScript standard exports.nonstandard = { escape : false, unescape: false }; // Globals provided by popular JavaScript environments. exports.couch = { "require" : false, respond : false, getRow : false, emit : false, send : false, start : false, sum : false, log : false, exports : false, module : false, provides : false }; exports.node = { __filename : false, __dirname : false, Buffer : false, console : false, exports : true, // In Node it is ok to exports = module.exports = foo(); GLOBAL : false, global : false, module : false, process : false, require : false, setTimeout : false, clearTimeout : false, setInterval : false, clearInterval : false, setImmediate : false, // v0.9.1+ clearImmediate: false // v0.9.1+ }; exports.phantom = { phantom : true, require : true, WebPage : true, console : true, // in examples, but undocumented exports : true // v1.7+ }; exports.rhino = { defineClass : false, deserialize : false, gc : false, help : false, importPackage: false, "java" : false, load : false, loadClass : false, print : false, quit : false, readFile : false, readUrl : false, runCommand : false, seal : false, serialize : false, spawn : false, sync : false, toint32 : false, version : false }; exports.shelljs = { target : false, echo : false, exit : false, cd : false, pwd : false, ls : false, find : false, cp : false, rm : false, mv : false, mkdir : false, test : false, cat : false, sed : false, grep : false, which : false, dirs : false, pushd : false, popd : false, env : false, exec : false, chmod : false, config : false, error : false, tempdir : false }; exports.typed = { ArrayBuffer : false, ArrayBufferView : false, DataView : false, Float32Array : false, Float64Array : false, Int16Array : false, Int32Array : false, Int8Array : false, Uint16Array : false, Uint32Array : false, Uint8Array : false, Uint8ClampedArray : false }; exports.wsh = { ActiveXObject : true, Enumerator : true, GetObject : true, ScriptEngine : true, ScriptEngineBuildVersion : true, ScriptEngineMajorVersion : true, ScriptEngineMinorVersion : true, VBArray : true, WSH : true, WScript : true, XDomainRequest : true }; // Globals provided by popular JavaScript libraries. exports.dojo = { dojo : false, dijit : false, dojox : false, define : false, "require": false }; exports.jquery = { "$" : false, jQuery : false }; exports.mootools = { "$" : false, "$$" : false, Asset : false, Browser : false, Chain : false, Class : false, Color : false, Cookie : false, Core : false, Document : false, DomReady : false, DOMEvent : false, DOMReady : false, Drag : false, Element : false, Elements : false, Event : false, Events : false, Fx : false, Group : false, Hash : false, HtmlTable : false, Iframe : false, IframeShim : false, InputValidator: false, instanceOf : false, Keyboard : false, Locale : false, Mask : false, MooTools : false, Native : false, Options : false, OverText : false, Request : false, Scroller : false, Slick : false, Slider : false, Sortables : false, Spinner : false, Swiff : false, Tips : false, Type : false, typeOf : false, URI : false, Window : false }; exports.prototypejs = { "$" : false, "$$" : false, "$A" : false, "$F" : false, "$H" : false, "$R" : false, "$break" : false, "$continue" : false, "$w" : false, Abstract : false, Ajax : false, Class : false, Enumerable : false, Element : false, Event : false, Field : false, Form : false, Hash : false, Insertion : false, ObjectRange : false, PeriodicalExecuter: false, Position : false, Prototype : false, Selector : false, Template : false, Toggle : false, Try : false, Autocompleter : false, Builder : false, Control : false, Draggable : false, Draggables : false, Droppables : false, Effect : false, Sortable : false, SortableObserver : false, Sound : false, Scriptaculous : false }; exports.yui = { YUI : false, Y : false, YUI_config: false };